@hawtio/ai-plugin 0.1.0 → 0.1.5

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 (237) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/index.css +85 -0
  3. package/dist/index.css.map +1 -0
  4. package/dist/index.d.ts +19 -0
  5. package/dist/index.js +16505 -0
  6. package/dist/index.js.map +1 -0
  7. package/package.json +18 -11
  8. package/build/remoteEntry.js +0 -1
  9. package/build/static/js/1107.3ddb1c2d.chunk.js +0 -1
  10. package/build/static/js/1118.cc586ed0.chunk.js +0 -2
  11. package/build/static/js/1118.cc586ed0.chunk.js.LICENSE.txt +0 -6
  12. package/build/static/js/1122.22f683c0.chunk.js +0 -2
  13. package/build/static/js/1122.22f683c0.chunk.js.LICENSE.txt +0 -6
  14. package/build/static/js/1196.36b61548.chunk.js +0 -1
  15. package/build/static/js/1282.13293291.chunk.js +0 -2
  16. package/build/static/js/1282.13293291.chunk.js.LICENSE.txt +0 -6
  17. package/build/static/js/1399.62776aed.chunk.js +0 -1
  18. package/build/static/js/1420.cdad4edc.chunk.js +0 -2
  19. package/build/static/js/1420.cdad4edc.chunk.js.LICENSE.txt +0 -6
  20. package/build/static/js/1438.998bfeaa.chunk.js +0 -2
  21. package/build/static/js/1438.998bfeaa.chunk.js.LICENSE.txt +0 -6
  22. package/build/static/js/1446.078792a0.chunk.js +0 -2
  23. package/build/static/js/1446.078792a0.chunk.js.LICENSE.txt +0 -6
  24. package/build/static/js/1474.d2802542.chunk.js +0 -1
  25. package/build/static/js/1560.dd1d891c.chunk.js +0 -2
  26. package/build/static/js/1560.dd1d891c.chunk.js.LICENSE.txt +0 -6
  27. package/build/static/js/1601.8d77a531.chunk.js +0 -1
  28. package/build/static/js/1657.1022ae9a.chunk.js +0 -1
  29. package/build/static/js/1691.e36cd2a4.chunk.js +0 -1
  30. package/build/static/js/1710.7459cdc6.chunk.js +0 -2
  31. package/build/static/js/1710.7459cdc6.chunk.js.LICENSE.txt +0 -6
  32. package/build/static/js/1740.7846bdc0.chunk.js +0 -2
  33. package/build/static/js/1740.7846bdc0.chunk.js.LICENSE.txt +0 -6
  34. package/build/static/js/1764.ed1eb715.chunk.js +0 -1
  35. package/build/static/js/1819.f3578ba7.chunk.js +0 -1
  36. package/build/static/js/1888.1bf114de.chunk.js +0 -2
  37. package/build/static/js/1888.1bf114de.chunk.js.LICENSE.txt +0 -6
  38. package/build/static/js/1914.2fedcabe.chunk.js +0 -2
  39. package/build/static/js/1914.2fedcabe.chunk.js.LICENSE.txt +0 -6
  40. package/build/static/js/198.e412f14d.chunk.js +0 -2
  41. package/build/static/js/198.e412f14d.chunk.js.LICENSE.txt +0 -6
  42. package/build/static/js/2018.11cc71b6.chunk.js +0 -2
  43. package/build/static/js/2018.11cc71b6.chunk.js.LICENSE.txt +0 -8
  44. package/build/static/js/205.c7a39524.chunk.js +0 -2
  45. package/build/static/js/205.c7a39524.chunk.js.LICENSE.txt +0 -6
  46. package/build/static/js/2052.55dab559.chunk.js +0 -1
  47. package/build/static/js/2077.1abeea86.chunk.js +0 -2
  48. package/build/static/js/2077.1abeea86.chunk.js.LICENSE.txt +0 -6
  49. package/build/static/js/2094.1a90435d.chunk.js +0 -2
  50. package/build/static/js/2094.1a90435d.chunk.js.LICENSE.txt +0 -6
  51. package/build/static/js/2126.fa7086de.chunk.js +0 -1
  52. package/build/static/js/2244.907ff9ca.chunk.js +0 -2
  53. package/build/static/js/2244.907ff9ca.chunk.js.LICENSE.txt +0 -6
  54. package/build/static/js/2278.983ac17a.chunk.js +0 -2
  55. package/build/static/js/2278.983ac17a.chunk.js.LICENSE.txt +0 -6
  56. package/build/static/js/2355.1cb3702b.chunk.js +0 -2
  57. package/build/static/js/2355.1cb3702b.chunk.js.LICENSE.txt +0 -11
  58. package/build/static/js/2398.f417f4a2.chunk.js +0 -2
  59. package/build/static/js/2398.f417f4a2.chunk.js.LICENSE.txt +0 -6
  60. package/build/static/js/2586.f6222422.chunk.js +0 -2
  61. package/build/static/js/2586.f6222422.chunk.js.LICENSE.txt +0 -6
  62. package/build/static/js/2648.5843f909.chunk.js +0 -2
  63. package/build/static/js/2648.5843f909.chunk.js.LICENSE.txt +0 -32
  64. package/build/static/js/2658.add23c16.chunk.js +0 -2
  65. package/build/static/js/2658.add23c16.chunk.js.LICENSE.txt +0 -6
  66. package/build/static/js/2686.850a32f4.chunk.js +0 -2
  67. package/build/static/js/2686.850a32f4.chunk.js.LICENSE.txt +0 -6
  68. package/build/static/js/2692.fe14cdb3.chunk.js +0 -2
  69. package/build/static/js/2692.fe14cdb3.chunk.js.LICENSE.txt +0 -6
  70. package/build/static/js/2745.5a754c4c.chunk.js +0 -2
  71. package/build/static/js/2745.5a754c4c.chunk.js.LICENSE.txt +0 -6
  72. package/build/static/js/2815.2f5b8610.chunk.js +0 -2
  73. package/build/static/js/2815.2f5b8610.chunk.js.LICENSE.txt +0 -6
  74. package/build/static/js/2962.63da9472.chunk.js +0 -2
  75. package/build/static/js/2962.63da9472.chunk.js.LICENSE.txt +0 -6
  76. package/build/static/js/3042.27bed794.chunk.js +0 -2
  77. package/build/static/js/3042.27bed794.chunk.js.LICENSE.txt +0 -6
  78. package/build/static/js/3062.9b619c25.chunk.js +0 -2
  79. package/build/static/js/3062.9b619c25.chunk.js.LICENSE.txt +0 -6
  80. package/build/static/js/3096.77d3d184.chunk.js +0 -2
  81. package/build/static/js/3096.77d3d184.chunk.js.LICENSE.txt +0 -6
  82. package/build/static/js/3182.80e1e1c4.chunk.js +0 -2
  83. package/build/static/js/3182.80e1e1c4.chunk.js.LICENSE.txt +0 -6
  84. package/build/static/js/3622.1381979b.chunk.js +0 -2
  85. package/build/static/js/3622.1381979b.chunk.js.LICENSE.txt +0 -6
  86. package/build/static/js/3726.d4f752df.chunk.js +0 -2
  87. package/build/static/js/3726.d4f752df.chunk.js.LICENSE.txt +0 -6
  88. package/build/static/js/3774.ae96f799.chunk.js +0 -1
  89. package/build/static/js/3780.62776aed.chunk.js +0 -1
  90. package/build/static/js/3913.73506d6d.chunk.js +0 -1
  91. package/build/static/js/3938.763f8f34.chunk.js +0 -1
  92. package/build/static/js/398.09ec70bb.chunk.js +0 -2
  93. package/build/static/js/398.09ec70bb.chunk.js.LICENSE.txt +0 -6
  94. package/build/static/js/4027.95c5d665.chunk.js +0 -2
  95. package/build/static/js/4027.95c5d665.chunk.js.LICENSE.txt +0 -20
  96. package/build/static/js/4114.4bdaacc3.chunk.js +0 -2
  97. package/build/static/js/4114.4bdaacc3.chunk.js.LICENSE.txt +0 -6
  98. package/build/static/js/4120.14cddb2c.chunk.js +0 -2
  99. package/build/static/js/4120.14cddb2c.chunk.js.LICENSE.txt +0 -6
  100. package/build/static/js/4334.fd251383.chunk.js +0 -2
  101. package/build/static/js/4334.fd251383.chunk.js.LICENSE.txt +0 -6
  102. package/build/static/js/434.6e69569b.chunk.js +0 -2
  103. package/build/static/js/434.6e69569b.chunk.js.LICENSE.txt +0 -1
  104. package/build/static/js/4630.3f202237.chunk.js +0 -2
  105. package/build/static/js/4630.3f202237.chunk.js.LICENSE.txt +0 -6
  106. package/build/static/js/4680.a4ec5aaa.chunk.js +0 -2
  107. package/build/static/js/4680.a4ec5aaa.chunk.js.LICENSE.txt +0 -6
  108. package/build/static/js/4698.1bb4f8d7.chunk.js +0 -2
  109. package/build/static/js/4698.1bb4f8d7.chunk.js.LICENSE.txt +0 -6
  110. package/build/static/js/4839.30e37894.chunk.js +0 -2
  111. package/build/static/js/4839.30e37894.chunk.js.LICENSE.txt +0 -6
  112. package/build/static/js/494.831600ac.chunk.js +0 -2
  113. package/build/static/js/494.831600ac.chunk.js.LICENSE.txt +0 -6
  114. package/build/static/js/4958.d1f8353d.chunk.js +0 -2
  115. package/build/static/js/4958.d1f8353d.chunk.js.LICENSE.txt +0 -6
  116. package/build/static/js/4962.e43e6f4e.chunk.js +0 -2
  117. package/build/static/js/4962.e43e6f4e.chunk.js.LICENSE.txt +0 -6
  118. package/build/static/js/5130.6b8ee76b.chunk.js +0 -2
  119. package/build/static/js/5130.6b8ee76b.chunk.js.LICENSE.txt +0 -6
  120. package/build/static/js/5364.f3157b50.chunk.js +0 -2
  121. package/build/static/js/5364.f3157b50.chunk.js.LICENSE.txt +0 -6
  122. package/build/static/js/5550.3a32ea3c.chunk.js +0 -2
  123. package/build/static/js/5550.3a32ea3c.chunk.js.LICENSE.txt +0 -6
  124. package/build/static/js/558.448709e5.chunk.js +0 -2
  125. package/build/static/js/558.448709e5.chunk.js.LICENSE.txt +0 -6
  126. package/build/static/js/5618.ea5c3f41.chunk.js +0 -2
  127. package/build/static/js/5618.ea5c3f41.chunk.js.LICENSE.txt +0 -6
  128. package/build/static/js/5628.562b716d.chunk.js +0 -1
  129. package/build/static/js/5786.acee2584.chunk.js +0 -2
  130. package/build/static/js/5786.acee2584.chunk.js.LICENSE.txt +0 -6
  131. package/build/static/js/5966.2cb0d97e.chunk.js +0 -2
  132. package/build/static/js/5966.2cb0d97e.chunk.js.LICENSE.txt +0 -6
  133. package/build/static/js/6018.1034f99f.chunk.js +0 -2
  134. package/build/static/js/6018.1034f99f.chunk.js.LICENSE.txt +0 -6
  135. package/build/static/js/6134.c56a6141.chunk.js +0 -2
  136. package/build/static/js/6134.c56a6141.chunk.js.LICENSE.txt +0 -6
  137. package/build/static/js/6185.01f6e181.chunk.js +0 -2
  138. package/build/static/js/6185.01f6e181.chunk.js.LICENSE.txt +0 -6
  139. package/build/static/js/6264.995bd452.chunk.js +0 -1
  140. package/build/static/js/6302.b7b9cf31.chunk.js +0 -2
  141. package/build/static/js/6302.b7b9cf31.chunk.js.LICENSE.txt +0 -6
  142. package/build/static/js/6343.00b0271d.chunk.js +0 -2
  143. package/build/static/js/6343.00b0271d.chunk.js.LICENSE.txt +0 -5
  144. package/build/static/js/6414.bfe34fac.chunk.js +0 -2
  145. package/build/static/js/6414.bfe34fac.chunk.js.LICENSE.txt +0 -6
  146. package/build/static/js/6446.e6db7785.chunk.js +0 -2
  147. package/build/static/js/6446.e6db7785.chunk.js.LICENSE.txt +0 -6
  148. package/build/static/js/6540.0651c08e.chunk.js +0 -2
  149. package/build/static/js/6540.0651c08e.chunk.js.LICENSE.txt +0 -9
  150. package/build/static/js/6590.7eaaa156.chunk.js +0 -2
  151. package/build/static/js/6590.7eaaa156.chunk.js.LICENSE.txt +0 -6
  152. package/build/static/js/6830.51680ad4.chunk.js +0 -2
  153. package/build/static/js/6830.51680ad4.chunk.js.LICENSE.txt +0 -6
  154. package/build/static/js/6940.3a036032.chunk.js +0 -2
  155. package/build/static/js/6940.3a036032.chunk.js.LICENSE.txt +0 -6
  156. package/build/static/js/6990.a6bd4bf9.chunk.js +0 -2
  157. package/build/static/js/6990.a6bd4bf9.chunk.js.LICENSE.txt +0 -6
  158. package/build/static/js/7048.0e787cc6.chunk.js +0 -2
  159. package/build/static/js/7048.0e787cc6.chunk.js.LICENSE.txt +0 -6
  160. package/build/static/js/7103.8782bdea.chunk.js +0 -1
  161. package/build/static/js/7200.497ad729.chunk.js +0 -2
  162. package/build/static/js/7200.497ad729.chunk.js.LICENSE.txt +0 -6
  163. package/build/static/js/7246.4174a151.chunk.js +0 -2
  164. package/build/static/js/7246.4174a151.chunk.js.LICENSE.txt +0 -6
  165. package/build/static/js/7282.91c7a4e1.chunk.js +0 -1
  166. package/build/static/js/7359.d0f02461.chunk.js +0 -1
  167. package/build/static/js/7466.78789e01.chunk.js +0 -2
  168. package/build/static/js/7466.78789e01.chunk.js.LICENSE.txt +0 -6
  169. package/build/static/js/7502.245ac470.chunk.js +0 -1
  170. package/build/static/js/7614.6a58b86d.chunk.js +0 -1
  171. package/build/static/js/7836.3f36ca48.chunk.js +0 -2
  172. package/build/static/js/7836.3f36ca48.chunk.js.LICENSE.txt +0 -6
  173. package/build/static/js/7886.9a581df6.chunk.js +0 -2
  174. package/build/static/js/7886.9a581df6.chunk.js.LICENSE.txt +0 -6
  175. package/build/static/js/7901.492e04fd.chunk.js +0 -1
  176. package/build/static/js/7955.961129d7.chunk.js +0 -2
  177. package/build/static/js/7955.961129d7.chunk.js.LICENSE.txt +0 -16
  178. package/build/static/js/8001.b8362437.chunk.js +0 -1
  179. package/build/static/js/8230.8412810c.chunk.js +0 -2
  180. package/build/static/js/8230.8412810c.chunk.js.LICENSE.txt +0 -6
  181. package/build/static/js/8332.214ec5a3.chunk.js +0 -2
  182. package/build/static/js/8332.214ec5a3.chunk.js.LICENSE.txt +0 -6
  183. package/build/static/js/8334.1c22f729.chunk.js +0 -2
  184. package/build/static/js/8334.1c22f729.chunk.js.LICENSE.txt +0 -6
  185. package/build/static/js/8390.e38e84bb.chunk.js +0 -2
  186. package/build/static/js/8390.e38e84bb.chunk.js.LICENSE.txt +0 -6
  187. package/build/static/js/8419.d4bedc1d.chunk.js +0 -2
  188. package/build/static/js/8419.d4bedc1d.chunk.js.LICENSE.txt +0 -9
  189. package/build/static/js/8494.f1def255.chunk.js +0 -2
  190. package/build/static/js/8494.f1def255.chunk.js.LICENSE.txt +0 -6
  191. package/build/static/js/8508.94511b9b.chunk.js +0 -1
  192. package/build/static/js/853.25a6ae32.chunk.js +0 -2
  193. package/build/static/js/853.25a6ae32.chunk.js.LICENSE.txt +0 -4
  194. package/build/static/js/8542.ff0a75e0.chunk.js +0 -2
  195. package/build/static/js/8542.ff0a75e0.chunk.js.LICENSE.txt +0 -6
  196. package/build/static/js/8566.0ca46abb.chunk.js +0 -2
  197. package/build/static/js/8566.0ca46abb.chunk.js.LICENSE.txt +0 -6
  198. package/build/static/js/8643.4e287da3.chunk.js +0 -1
  199. package/build/static/js/8807.3e096883.chunk.js +0 -1
  200. package/build/static/js/8826.d1a03e1d.chunk.js +0 -1
  201. package/build/static/js/8902.01d14b56.chunk.js +0 -2
  202. package/build/static/js/8902.01d14b56.chunk.js.LICENSE.txt +0 -6
  203. package/build/static/js/8976.6765092d.chunk.js +0 -1
  204. package/build/static/js/8990.6e5b2faf.chunk.js +0 -2
  205. package/build/static/js/8990.6e5b2faf.chunk.js.LICENSE.txt +0 -6
  206. package/build/static/js/9034.4d9f7a42.chunk.js +0 -2
  207. package/build/static/js/9034.4d9f7a42.chunk.js.LICENSE.txt +0 -6
  208. package/build/static/js/9038.1bd2fbfd.chunk.js +0 -2
  209. package/build/static/js/9038.1bd2fbfd.chunk.js.LICENSE.txt +0 -6
  210. package/build/static/js/910.71f7efbf.chunk.js +0 -2
  211. package/build/static/js/910.71f7efbf.chunk.js.LICENSE.txt +0 -6
  212. package/build/static/js/9150.370d7055.chunk.js +0 -2
  213. package/build/static/js/9150.370d7055.chunk.js.LICENSE.txt +0 -6
  214. package/build/static/js/9355.313cb110.chunk.js +0 -1
  215. package/build/static/js/9390.49904317.chunk.js +0 -2
  216. package/build/static/js/9390.49904317.chunk.js.LICENSE.txt +0 -6
  217. package/build/static/js/946.ef602f12.chunk.js +0 -2
  218. package/build/static/js/946.ef602f12.chunk.js.LICENSE.txt +0 -6
  219. package/build/static/js/9510.be29e01f.chunk.js +0 -2
  220. package/build/static/js/9510.be29e01f.chunk.js.LICENSE.txt +0 -6
  221. package/build/static/js/961.94ad6975.chunk.js +0 -2
  222. package/build/static/js/961.94ad6975.chunk.js.LICENSE.txt +0 -19
  223. package/build/static/js/968.1fce69dd.chunk.js +0 -2
  224. package/build/static/js/968.1fce69dd.chunk.js.LICENSE.txt +0 -6
  225. package/build/static/js/970.097e9bdb.chunk.js +0 -2
  226. package/build/static/js/970.097e9bdb.chunk.js.LICENSE.txt +0 -6
  227. package/build/static/js/9838.f55a5e51.chunk.js +0 -2
  228. package/build/static/js/9838.f55a5e51.chunk.js.LICENSE.txt +0 -6
  229. package/build/static/js/main.beb03f56.js +0 -1
  230. package/build/static/media/RedHatDisplayVF-Italic.813182e673c38ef5ee4b.woff2 +0 -0
  231. package/build/static/media/RedHatDisplayVF.18ca482120faaa701d8b.woff2 +0 -0
  232. package/build/static/media/RedHatMonoVF-Italic.6e3027616d8de472723c.woff2 +0 -0
  233. package/build/static/media/RedHatMonoVF.e4faf134e53e0f37296b.woff2 +0 -0
  234. package/build/static/media/RedHatTextVF-Italic.078865af129336cde269.woff2 +0 -0
  235. package/build/static/media/RedHatTextVF.c33624692c8b41e36780.woff2 +0 -0
  236. package/build/static/media/codicon.f6283f7ccaed1249d9eb.ttf +0 -0
  237. package/build/static/media/pf-v6-pficon.463d4ddeac4dae277fc4.woff2 +0 -0
@@ -1,2 +0,0 @@
1
- /*! For license information please see 2355.1cb3702b.chunk.js.LICENSE.txt */
2
- "use strict";(globalThis.webpackChunk_hawtio_ai_plugin=globalThis.webpackChunk_hawtio_ai_plugin||[]).push([[2355],{49418(e,t,n){e=n.nmd(e);const r=(e=0)=>t=>`[${38+e};5;${t}m`,a=(e=0)=>(t,n,r)=>`[${38+e};2;${t};${n};${r}m`;Object.defineProperty(e,"exports",{enumerable:!0,get:function(){const e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(const[n,r]of Object.entries(t)){for(const[n,a]of Object.entries(r))t[n]={open:`[${a[0]}m`,close:`[${a[1]}m`},r[n]=t[n],e.set(a[0],a[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,"codes",{value:e,enumerable:!1}),t.color.close="",t.bgColor.close="",t.color.ansi256=r(),t.color.ansi16m=a(),t.bgColor.ansi256=r(10),t.bgColor.ansi16m=a(10),Object.defineProperties(t,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{const t=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(e.toString(16));if(!t)return[0,0,0];let{colorString:n}=t.groups;3===n.length&&(n=n.split("").map(e=>e+e).join(""));const r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,255&r]},enumerable:!1},hexToAnsi256:{value:e=>t.rgbToAnsi256(...t.hexToRgb(e)),enumerable:!1}}),t}})},25148(e){const t=/[\p{Lu}]/u,n=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,a=/([\p{Alpha}\p{N}_]|$)/u,i=/[_.\- ]+/,s=new RegExp("^"+i.source),o=new RegExp(i.source+a.source,"gu"),c=new RegExp("\\d+"+a.source,"gu"),d=(e,a)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");if(a={pascalCase:!1,preserveConsecutiveUppercase:!1,...a},0===(e=Array.isArray(e)?e.map(e=>e.trim()).filter(e=>e.length).join("-"):e.trim()).length)return"";const i=!1===a.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(a.locale),d=!1===a.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(a.locale);return 1===e.length?a.pascalCase?d(e):i(e):(e!==i(e)&&(e=((e,r,a)=>{let i=!1,s=!1,o=!1;for(let c=0;c<e.length;c++){const d=e[c];i&&t.test(d)?(e=e.slice(0,c)+"-"+e.slice(c),i=!1,o=s,s=!0,c++):s&&o&&n.test(d)?(e=e.slice(0,c-1)+"-"+e.slice(c-1),o=s,s=!1,i=!0):(i=r(d)===d&&a(d)!==d,o=s,s=a(d)===d&&r(d)!==d)}return e})(e,i,d)),e=e.replace(s,""),e=a.preserveConsecutiveUppercase?((e,t)=>(r.lastIndex=0,e.replace(r,e=>t(e))))(e,i):i(e),a.pascalCase&&(e=d(e.charAt(0))+e.slice(1)),((e,t)=>(o.lastIndex=0,c.lastIndex=0,e.replace(o,(e,n)=>t(n)).replace(c,e=>t(e))))(e,d))};e.exports=d,e.exports.default=d},79478(e){e.exports=function(e,t){if("string"!=typeof e)throw new TypeError("Expected a string");return t=void 0===t?"_":t,e.replace(/([a-z\d])([A-Z])/g,"$1"+t+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+t+"$2").toLowerCase()}},44617(e){e.exports=(e,t)=>(t=t||(()=>{}),e.then(e=>new Promise(e=>{e(t())}).then(()=>e),e=>new Promise(e=>{e(t())}).then(()=>{throw e})))},73290(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});const r=n(26368),a=n(56641),i=n(54774),s=()=>{},o=new a.TimeoutError;t.default=class extends r{constructor(e){var t,n,r,a;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=s,this._resolveIdle=s,!("number"==typeof(e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:i.default},e)).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(n=null===(t=e.intervalCap)||void 0===t?void 0:t.toString())&&void 0!==n?n:""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(a=null===(r=e.interval)||void 0===r?void 0:r.toString())&&void 0!==a?a:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||0===e.interval,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=!0===e.throwOnTimeout,this._isPaused=!1===e.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=s,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=s,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(void 0===this._intervalId){const t=this._intervalEnd-e;if(!(t<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},t)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const t=this._queue.dequeue();return!!t&&(this.emit("active"),t(),e&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,t={}){return new Promise((n,r)=>{this._queue.enqueue(async()=>{this._pendingCount++,this._intervalCount++;try{const i=void 0===this._timeout&&void 0===t.timeout?e():a.default(Promise.resolve(e()),void 0===t.timeout?this._timeout:t.timeout,()=>{(void 0===t.throwOnTimeout?this._throwOnTimeout:t.throwOnTimeout)&&r(o)});n(await i)}catch(e){r(e)}this._next()},t),this._tryToStartAnother(),this.emit("add")})}async addAll(e,t){return Promise.all(e.map(async e=>this.add(e,t)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise(e=>{const t=this._resolveEmpty;this._resolveEmpty=()=>{t(),e()}})}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise(e=>{const t=this._resolveIdle;this._resolveIdle=()=>{t(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}}},79998(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n){let r=0,a=e.length;for(;a>0;){const i=a/2|0;let s=r+i;n(e[s],t)<=0?(r=++s,a-=i+1):a=i}return r}},54774(e,t,n){Object.defineProperty(t,"__esModule",{value:!0});const r=n(79998);t.default=class{constructor(){this._queue=[]}enqueue(e,t){const n={priority:(t=Object.assign({priority:0},t)).priority,run:e};if(this.size&&this._queue[this.size-1].priority>=t.priority)return void this._queue.push(n);const a=r.default(this._queue,n,(e,t)=>t.priority-e.priority);this._queue.splice(a,0,n)}dequeue(){const e=this._queue.shift();return null==e?void 0:e.run}filter(e){return this._queue.filter(t=>t.priority===e.priority).map(e=>e.run)}get size(){return this._queue.length}}},26368(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function i(e,t,r,i,s){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new a(r,i||e,s),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],o]:e._events[c].push(o):(e._events[c]=o,e._eventsCount++),e}function s(e,t){0===--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(n=!1)),o.prototype.eventNames=function(){var e,r,a=[];if(0===this._eventsCount)return a;for(r in e=this._events)t.call(e,r)&&a.push(n?r.slice(1):r);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(e)):a},o.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var a=0,i=r.length,s=new Array(i);a<i;a++)s[a]=r[a].fn;return s},o.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,a,i,s){var o=n?n+e:e;if(!this._events[o])return!1;var c,d,u=this._events[o],l=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),l){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,r),!0;case 4:return u.fn.call(u.context,t,r,a),!0;case 5:return u.fn.call(u.context,t,r,a,i),!0;case 6:return u.fn.call(u.context,t,r,a,i,s),!0}for(d=1,c=new Array(l-1);d<l;d++)c[d-1]=arguments[d];u.fn.apply(u.context,c)}else{var h,p=u.length;for(d=0;d<p;d++)switch(u[d].once&&this.removeListener(e,u[d].fn,void 0,!0),l){case 1:u[d].fn.call(u[d].context);break;case 2:u[d].fn.call(u[d].context,t);break;case 3:u[d].fn.call(u[d].context,t,r);break;case 4:u[d].fn.call(u[d].context,t,r,a);break;default:if(!c)for(h=1,c=new Array(l-1);h<l;h++)c[h-1]=arguments[h];u[d].fn.apply(u[d].context,c)}}return!0},o.prototype.on=function(e,t,n){return i(this,e,t,n,!1)},o.prototype.once=function(e,t,n){return i(this,e,t,n,!0)},o.prototype.removeListener=function(e,t,r,a){var i=n?n+e:e;if(!this._events[i])return this;if(!t)return s(this,i),this;var o=this._events[i];if(o.fn)o.fn!==t||a&&!o.once||r&&o.context!==r||s(this,i);else{for(var c=0,d=[],u=o.length;c<u;c++)(o[c].fn!==t||a&&!o[c].once||r&&o[c].context!==r)&&d.push(o[c]);d.length?this._events[i]=1===d.length?d[0]:d:s(this,i)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&s(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,e.exports=o},56641(e,t,n){const r=n(44617);class a extends Error{constructor(e){super(e),this.name="TimeoutError"}}const i=(e,t,n)=>new Promise((i,s)=>{if("number"!=typeof t||t<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(t===1/0)return void i(e);const o=setTimeout(()=>{if("function"==typeof n){try{i(n())}catch(e){s(e)}return}const r=n instanceof Error?n:new a("string"==typeof n?n:`Promise timed out after ${t} milliseconds`);"function"==typeof e.cancel&&e.cancel(),s(r)},t);r(e.then(i,s),()=>{clearTimeout(o)})});e.exports=i,e.exports.default=i,e.exports.TimeoutError=a},93904(e,t,n){const r=Symbol("SemVer ANY");class a{static get ANY(){return r}constructor(e,t){if(t=i(t),e instanceof a){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),d("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===r?this.value="":this.value=this.operator+this.semver.version,d("comp",this)}parse(e){const t=this.options.loose?s[o.COMPARATORLOOSE]:s[o.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=void 0!==n[1]?n[1]:"","="===this.operator&&(this.operator=""),n[2]?this.semver=new u(n[2],this.options.loose):this.semver=r}toString(){return this.value}test(e){if(d("Comparator.test",e,this.options.loose),this.semver===r||e===r)return!0;if("string"==typeof e)try{e=new u(e,this.options)}catch(e){return!1}return c(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof a))throw new TypeError("a Comparator is required");return""===this.operator?""===this.value||new l(e.value,t).test(this.value):""===e.operator?""===e.value||new l(this.value,t).test(e.semver):!((t=i(t)).includePrerelease&&("<0.0.0-0"===this.value||"<0.0.0-0"===e.value)||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))||(!this.operator.startsWith(">")||!e.operator.startsWith(">"))&&(!this.operator.startsWith("<")||!e.operator.startsWith("<"))&&(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))&&!(c(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))&&!(c(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}}e.exports=a;const i=n(98587),{safeRe:s,t:o}=n(99718),c=n(72111),d=n(57272),u=n(53908),l=n(78311)},78311(e,t,n){const r=/\s+/g;class a{constructor(e,t){if(t=s(t),e instanceof a)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new a(e.raw,t);if(e instanceof o)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(r," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!y(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&_(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&m)|(this.options.loose&&g))+":"+e,n=i.get(t);if(n)return n;const r=this.options.loose,a=r?u[l.HYPHENRANGELOOSE]:u[l.HYPHENRANGE];e=e.replace(a,$(this.options.includePrerelease)),c("hyphen replace",e),e=e.replace(u[l.COMPARATORTRIM],h),c("comparator trim",e),e=e.replace(u[l.TILDETRIM],p),c("tilde trim",e),e=e.replace(u[l.CARETTRIM],f),c("caret trim",e);let s=e.split(" ").map(e=>w(e,this.options)).join(" ").split(/\s+/).map(e=>A(e,this.options));r&&(s=s.filter(e=>(c("loose invalid filter",e,this.options),!!e.match(u[l.COMPARATORLOOSE])))),c("range list",s);const d=new Map,_=s.map(e=>new o(e,this.options));for(const e of _){if(y(e))return[e];d.set(e.value,e)}d.size>1&&d.has("")&&d.delete("");const v=[...d.values()];return i.set(t,v),v}intersects(e,t){if(!(e instanceof a))throw new TypeError("a Range is required");return this.set.some(n=>v(n,t)&&e.set.some(e=>v(e,t)&&n.every(n=>e.every(e=>n.intersects(e,t)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new d(e,this.options)}catch(e){return!1}for(let t=0;t<this.set.length;t++)if(N(this.set[t],e,this.options))return!0;return!1}}e.exports=a;const i=new(n(68794)),s=n(98587),o=n(93904),c=n(57272),d=n(53908),{safeRe:u,t:l,comparatorTrimReplace:h,tildeTrimReplace:p,caretTrimReplace:f}=n(99718),{FLAG_INCLUDE_PRERELEASE:m,FLAG_LOOSE:g}=n(16874),y=e=>"<0.0.0-0"===e.value,_=e=>""===e.value,v=(e,t)=>{let n=!0;const r=e.slice();let a=r.pop();for(;n&&r.length;)n=r.every(e=>a.intersects(e,t)),a=r.pop();return n},w=(e,t)=>(e=e.replace(u[l.BUILD],""),c("comp",e,t),e=I(e,t),c("caret",e),e=E(e,t),c("tildes",e),e=S(e,t),c("xrange",e),e=T(e,t),c("stars",e),e),b=e=>!e||"x"===e.toLowerCase()||"*"===e,E=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(" "),x=(e,t)=>{const n=t.loose?u[l.TILDELOOSE]:u[l.TILDE];return e.replace(n,(t,n,r,a,i)=>{let s;return c("tilde",e,t,n,r,a,i),b(n)?s="":b(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:b(a)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:i?(c("replaceTilde pr",i),s=`>=${n}.${r}.${a}-${i} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${a} <${n}.${+r+1}.0-0`,c("tilde return",s),s})},I=(e,t)=>e.trim().split(/\s+/).map(e=>k(e,t)).join(" "),k=(e,t)=>{c("caret",e,t);const n=t.loose?u[l.CARETLOOSE]:u[l.CARET],r=t.includePrerelease?"-0":"";return e.replace(n,(t,n,a,i,s)=>{let o;return c("caret",e,t,n,a,i,s),b(n)?o="":b(a)?o=`>=${n}.0.0${r} <${+n+1}.0.0-0`:b(i)?o="0"===n?`>=${n}.${a}.0${r} <${n}.${+a+1}.0-0`:`>=${n}.${a}.0${r} <${+n+1}.0.0-0`:s?(c("replaceCaret pr",s),o="0"===n?"0"===a?`>=${n}.${a}.${i}-${s} <${n}.${a}.${+i+1}-0`:`>=${n}.${a}.${i}-${s} <${n}.${+a+1}.0-0`:`>=${n}.${a}.${i}-${s} <${+n+1}.0.0-0`):(c("no pr"),o="0"===n?"0"===a?`>=${n}.${a}.${i}${r} <${n}.${a}.${+i+1}-0`:`>=${n}.${a}.${i}${r} <${n}.${+a+1}.0-0`:`>=${n}.${a}.${i} <${+n+1}.0.0-0`),c("caret return",o),o})},S=(e,t)=>(c("replaceXRanges",e,t),e.split(/\s+/).map(e=>O(e,t)).join(" ")),O=(e,t)=>{e=e.trim();const n=t.loose?u[l.XRANGELOOSE]:u[l.XRANGE];return e.replace(n,(n,r,a,i,s,o)=>{c("xRange",e,n,r,a,i,s,o);const d=b(a),u=d||b(i),l=u||b(s),h=l;return"="===r&&h&&(r=""),o=t.includePrerelease?"-0":"",d?n=">"===r||"<"===r?"<0.0.0-0":"*":r&&h?(u&&(i=0),s=0,">"===r?(r=">=",u?(a=+a+1,i=0,s=0):(i=+i+1,s=0)):"<="===r&&(r="<",u?a=+a+1:i=+i+1),"<"===r&&(o="-0"),n=`${r+a}.${i}.${s}${o}`):u?n=`>=${a}.0.0${o} <${+a+1}.0.0-0`:l&&(n=`>=${a}.${i}.0${o} <${a}.${+i+1}.0-0`),c("xRange return",n),n})},T=(e,t)=>(c("replaceStars",e,t),e.trim().replace(u[l.STAR],"")),A=(e,t)=>(c("replaceGTE0",e,t),e.trim().replace(u[t.includePrerelease?l.GTE0PRE:l.GTE0],"")),$=e=>(t,n,r,a,i,s,o,c,d,u,l,h)=>`${n=b(r)?"":b(a)?`>=${r}.0.0${e?"-0":""}`:b(i)?`>=${r}.${a}.0${e?"-0":""}`:s?`>=${n}`:`>=${n}${e?"-0":""}`} ${c=b(d)?"":b(u)?`<${+d+1}.0.0-0`:b(l)?`<${d}.${+u+1}.0-0`:h?`<=${d}.${u}.${l}-${h}`:e?`<${d}.${u}.${+l+1}-0`:`<=${c}`}`.trim(),N=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(c(e[n].semver),e[n].semver!==o.ANY&&e[n].semver.prerelease.length>0){const r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}},53908(e,t,n){const r=n(57272),{MAX_LENGTH:a,MAX_SAFE_INTEGER:i}=n(16874),{safeRe:s,t:o}=n(99718),c=n(98587),{compareIdentifiers:d}=n(61123);class u{constructor(e,t){if(t=c(t),e instanceof u){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if("string"!=typeof e)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>a)throw new TypeError(`version is longer than ${a} characters`);r("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const n=e.trim().match(t.loose?s[o.LOOSE]:s[o.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>i||this.major<0)throw new TypeError("Invalid major version");if(this.minor>i||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>i||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=n[5]?n[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(r("SemVer.compare",this.version,this.options,e),!(e instanceof u)){if("string"==typeof e&&e===this.version)return 0;e=new u(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof u||(e=new u(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof u||(e=new u(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const n=this.prerelease[t],a=e.prerelease[t];if(r("prerelease compare",t,n,a),void 0===n&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===n)return-1;if(n!==a)return d(n,a)}while(++t)}compareBuild(e){e instanceof u||(e=new u(e,this.options));let t=0;do{const n=this.build[t],a=e.build[t];if(r("build compare",t,n,a),void 0===n&&void 0===a)return 0;if(void 0===a)return 1;if(void 0===n)return-1;if(n!==a)return d(n,a)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&!1===n)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?s[o.PRERELEASELOOSE]:s[o.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(n)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);if(-1===r){if(t===this.prerelease.join(".")&&!1===n)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let r=[t,e];!1===n&&(r=[t]),0===d(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}e.exports=u},57414(e,t,n){const r=n(30144);e.exports=(e,t)=>{const n=r(e.trim().replace(/^[=v]+/,""),t);return n?n.version:null}},72111(e,t,n){const r=n(94641),a=n(13999),i=n(35580),s=n(54089),o=n(7059),c=n(25200);e.exports=(e,t,n,d)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e===n;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof n&&(n=n.version),e!==n;case"":case"=":case"==":return r(e,n,d);case"!=":return a(e,n,d);case">":return i(e,n,d);case">=":return s(e,n,d);case"<":return o(e,n,d);case"<=":return c(e,n,d);default:throw new TypeError(`Invalid operator: ${t}`)}}},46170(e,t,n){const r=n(53908),a=n(30144),{safeRe:i,t:s}=n(99718);e.exports=(e,t)=>{if(e instanceof r)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;let n=null;if((t=t||{}).rtl){const r=t.includePrerelease?i[s.COERCERTLFULL]:i[s.COERCERTL];let a;for(;(a=r.exec(e))&&(!n||n.index+n[0].length!==e.length);)n&&a.index+a[0].length===n.index+n[0].length||(n=a),r.lastIndex=a.index+a[1].length+a[2].length;r.lastIndex=-1}else n=e.match(t.includePrerelease?i[s.COERCEFULL]:i[s.COERCE]);if(null===n)return null;const o=n[2],c=n[3]||"0",d=n[4]||"0",u=t.includePrerelease&&n[5]?`-${n[5]}`:"",l=t.includePrerelease&&n[6]?`+${n[6]}`:"";return a(`${o}.${c}.${d}${u}${l}`,t)}},40909(e,t,n){const r=n(53908);e.exports=(e,t,n)=>{const a=new r(e,n),i=new r(t,n);return a.compare(i)||a.compareBuild(i)}},11763(e,t,n){const r=n(50560);e.exports=(e,t)=>r(e,t,!0)},50560(e,t,n){const r=n(53908);e.exports=(e,t,n)=>new r(e,n).compare(new r(t,n))},51832(e,t,n){const r=n(30144);e.exports=(e,t)=>{const n=r(e,null,!0),a=r(t,null,!0),i=n.compare(a);if(0===i)return null;const s=i>0,o=s?n:a,c=s?a:n,d=!!o.prerelease.length;if(c.prerelease.length&&!d){if(!c.patch&&!c.minor)return"major";if(0===c.compareMain(o))return c.minor&&!c.patch?"minor":"patch"}const u=d?"pre":"";return n.major!==a.major?u+"major":n.minor!==a.minor?u+"minor":n.patch!==a.patch?u+"patch":"prerelease"}},94641(e,t,n){const r=n(50560);e.exports=(e,t,n)=>0===r(e,t,n)},35580(e,t,n){const r=n(50560);e.exports=(e,t,n)=>r(e,t,n)>0},54089(e,t,n){const r=n(50560);e.exports=(e,t,n)=>r(e,t,n)>=0},93007(e,t,n){const r=n(53908);e.exports=(e,t,n,a,i)=>{"string"==typeof n&&(i=a,a=n,n=void 0);try{return new r(e instanceof r?e.version:e,n).inc(t,a,i).version}catch(e){return null}}},7059(e,t,n){const r=n(50560);e.exports=(e,t,n)=>r(e,t,n)<0},25200(e,t,n){const r=n(50560);e.exports=(e,t,n)=>r(e,t,n)<=0},32938(e,t,n){const r=n(53908);e.exports=(e,t)=>new r(e,t).major},46254(e,t,n){const r=n(53908);e.exports=(e,t)=>new r(e,t).minor},13999(e,t,n){const r=n(50560);e.exports=(e,t,n)=>0!==r(e,t,n)},30144(e,t,n){const r=n(53908);e.exports=(e,t,n=!1)=>{if(e instanceof r)return e;try{return new r(e,t)}catch(e){if(!n)return null;throw e}}},24493(e,t,n){const r=n(53908);e.exports=(e,t)=>new r(e,t).patch},31729(e,t,n){const r=n(30144);e.exports=(e,t)=>{const n=r(e,t);return n&&n.prerelease.length?n.prerelease:null}},9970(e,t,n){const r=n(50560);e.exports=(e,t,n)=>r(t,e,n)},74277(e,t,n){const r=n(40909);e.exports=(e,t)=>e.sort((e,n)=>r(n,e,t))},97638(e,t,n){const r=n(78311);e.exports=(e,t,n)=>{try{t=new r(t,n)}catch(e){return!1}return t.test(e)}},43927(e,t,n){const r=n(40909);e.exports=(e,t)=>e.sort((e,n)=>r(e,n,t))},56953(e,t,n){const r=n(30144);e.exports=(e,t)=>{const n=r(e,t);return n?n.version:null}},99589(e,t,n){const r=n(99718),a=n(16874),i=n(53908),s=n(61123),o=n(30144),c=n(56953),d=n(57414),u=n(93007),l=n(51832),h=n(32938),p=n(46254),f=n(24493),m=n(31729),g=n(50560),y=n(9970),_=n(11763),v=n(40909),w=n(43927),b=n(74277),E=n(35580),x=n(7059),I=n(94641),k=n(13999),S=n(54089),O=n(25200),T=n(72111),A=n(46170),$=n(93904),N=n(78311),j=n(97638),C=n(77631),R=n(19628),P=n(270),L=n(41261),M=n(13874),z=n(97075),D=n(75571),U=n(5342),F=n(76780),Z=n(72525),B=n(75032);e.exports={parse:o,valid:c,clean:d,inc:u,diff:l,major:h,minor:p,patch:f,prerelease:m,compare:g,rcompare:y,compareLoose:_,compareBuild:v,sort:w,rsort:b,gt:E,lt:x,eq:I,neq:k,gte:S,lte:O,cmp:T,coerce:A,Comparator:$,Range:N,satisfies:j,toComparators:C,maxSatisfying:R,minSatisfying:P,minVersion:L,validRange:M,outside:z,gtr:D,ltr:U,intersects:F,simplifyRange:Z,subset:B,SemVer:i,re:r.re,src:r.src,tokens:r.t,SEMVER_SPEC_VERSION:a.SEMVER_SPEC_VERSION,RELEASE_TYPES:a.RELEASE_TYPES,compareIdentifiers:s.compareIdentifiers,rcompareIdentifiers:s.rcompareIdentifiers}},16874(e){const t=Number.MAX_SAFE_INTEGER||9007199254740991;e.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},57272(e){const t="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};e.exports=t},61123(e){const t=/^[0-9]+$/,n=(e,n)=>{if("number"==typeof e&&"number"==typeof n)return e===n?0:e<n?-1:1;const r=t.test(e),a=t.test(n);return r&&a&&(e=+e,n=+n),e===n?0:r&&!a?-1:a&&!r?1:e<n?-1:1};e.exports={compareIdentifiers:n,rcompareIdentifiers:(e,t)=>n(t,e)}},68794(e){e.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}},98587(e){const t=Object.freeze({loose:!0}),n=Object.freeze({});e.exports=e=>e?"object"!=typeof e?t:e:n},99718(e,t,n){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:a,MAX_LENGTH:i}=n(16874),s=n(57272),o=(t=e.exports={}).re=[],c=t.safeRe=[],d=t.src=[],u=t.safeSrc=[],l=t.t={};let h=0;const p="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",i],[p,a]],m=(e,t,n)=>{const r=(e=>{for(const[t,n]of f)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e})(t),a=h++;s(e,a,t),l[e]=a,d[a]=t,u[a]=r,o[a]=new RegExp(t,n?"g":void 0),c[a]=new RegExp(r,n?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),m("MAINVERSION",`(${d[l.NUMERICIDENTIFIER]})\\.(${d[l.NUMERICIDENTIFIER]})\\.(${d[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${d[l.NUMERICIDENTIFIERLOOSE]})\\.(${d[l.NUMERICIDENTIFIERLOOSE]})\\.(${d[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${d[l.NONNUMERICIDENTIFIER]}|${d[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${d[l.NONNUMERICIDENTIFIER]}|${d[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${d[l.PRERELEASEIDENTIFIER]}(?:\\.${d[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${d[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${d[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${p}+`),m("BUILD",`(?:\\+(${d[l.BUILDIDENTIFIER]}(?:\\.${d[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${d[l.MAINVERSION]}${d[l.PRERELEASE]}?${d[l.BUILD]}?`),m("FULL",`^${d[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${d[l.MAINVERSIONLOOSE]}${d[l.PRERELEASELOOSE]}?${d[l.BUILD]}?`),m("LOOSE",`^${d[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${d[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${d[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${d[l.XRANGEIDENTIFIER]})(?:\\.(${d[l.XRANGEIDENTIFIER]})(?:\\.(${d[l.XRANGEIDENTIFIER]})(?:${d[l.PRERELEASE]})?${d[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${d[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${d[l.XRANGEIDENTIFIERLOOSE]})(?:${d[l.PRERELEASELOOSE]})?${d[l.BUILD]}?)?)?`),m("XRANGE",`^${d[l.GTLT]}\\s*${d[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${d[l.GTLT]}\\s*${d[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),m("COERCE",`${d[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",d[l.COERCEPLAIN]+`(?:${d[l.PRERELEASE]})?`+`(?:${d[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",d[l.COERCE],!0),m("COERCERTLFULL",d[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${d[l.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",m("TILDE",`^${d[l.LONETILDE]}${d[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${d[l.LONETILDE]}${d[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${d[l.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",m("CARET",`^${d[l.LONECARET]}${d[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${d[l.LONECARET]}${d[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${d[l.GTLT]}\\s*(${d[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${d[l.GTLT]}\\s*(${d[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${d[l.GTLT]}\\s*(${d[l.LOOSEPLAIN]}|${d[l.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${d[l.XRANGEPLAIN]})\\s+-\\s+(${d[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${d[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${d[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},75571(e,t,n){const r=n(97075);e.exports=(e,t,n)=>r(e,t,">",n)},76780(e,t,n){const r=n(78311);e.exports=(e,t,n)=>(e=new r(e,n),t=new r(t,n),e.intersects(t,n))},5342(e,t,n){const r=n(97075);e.exports=(e,t,n)=>r(e,t,"<",n)},19628(e,t,n){const r=n(53908),a=n(78311);e.exports=(e,t,n)=>{let i=null,s=null,o=null;try{o=new a(t,n)}catch(e){return null}return e.forEach(e=>{o.test(e)&&(i&&-1!==s.compare(e)||(i=e,s=new r(i,n)))}),i}},270(e,t,n){const r=n(53908),a=n(78311);e.exports=(e,t,n)=>{let i=null,s=null,o=null;try{o=new a(t,n)}catch(e){return null}return e.forEach(e=>{o.test(e)&&(i&&1!==s.compare(e)||(i=e,s=new r(i,n)))}),i}},41261(e,t,n){const r=n(53908),a=n(78311),i=n(35580);e.exports=(e,t)=>{e=new a(e,t);let n=new r("0.0.0");if(e.test(n))return n;if(n=new r("0.0.0-0"),e.test(n))return n;n=null;for(let t=0;t<e.set.length;++t){const a=e.set[t];let s=null;a.forEach(e=>{const t=new r(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":s&&!i(t,s)||(s=t);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}),!s||n&&!i(n,s)||(n=s)}return n&&e.test(n)?n:null}},97075(e,t,n){const r=n(53908),a=n(93904),{ANY:i}=a,s=n(78311),o=n(97638),c=n(35580),d=n(7059),u=n(25200),l=n(54089);e.exports=(e,t,n,h)=>{let p,f,m,g,y;switch(e=new r(e,h),t=new s(t,h),n){case">":p=c,f=u,m=d,g=">",y=">=";break;case"<":p=d,f=l,m=c,g="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(e,t,h))return!1;for(let n=0;n<t.set.length;++n){const r=t.set[n];let s=null,o=null;if(r.forEach(e=>{e.semver===i&&(e=new a(">=0.0.0")),s=s||e,o=o||e,p(e.semver,s.semver,h)?s=e:m(e.semver,o.semver,h)&&(o=e)}),s.operator===g||s.operator===y)return!1;if((!o.operator||o.operator===g)&&f(e,o.semver))return!1;if(o.operator===y&&m(e,o.semver))return!1}return!0}},72525(e,t,n){const r=n(97638),a=n(50560);e.exports=(e,t,n)=>{const i=[];let s=null,o=null;const c=e.sort((e,t)=>a(e,t,n));for(const e of c)r(e,t,n)?(o=e,s||(s=e)):(o&&i.push([s,o]),o=null,s=null);s&&i.push([s,null]);const d=[];for(const[e,t]of i)e===t?d.push(e):t||e!==c[0]?t?e===c[0]?d.push(`<=${t}`):d.push(`${e} - ${t}`):d.push(`>=${e}`):d.push("*");const u=d.join(" || "),l="string"==typeof t.raw?t.raw:String(t);return u.length<l.length?u:t}},75032(e,t,n){const r=n(78311),a=n(93904),{ANY:i}=a,s=n(97638),o=n(50560),c=[new a(">=0.0.0-0")],d=[new a(">=0.0.0")],u=(e,t,n)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===i){if(1===t.length&&t[0].semver===i)return!0;e=n.includePrerelease?c:d}if(1===t.length&&t[0].semver===i){if(n.includePrerelease)return!0;t=d}const r=new Set;let a,u,p,f,m,g,y;for(const t of e)">"===t.operator||">="===t.operator?a=l(a,t,n):"<"===t.operator||"<="===t.operator?u=h(u,t,n):r.add(t.semver);if(r.size>1)return null;if(a&&u){if(p=o(a.semver,u.semver,n),p>0)return null;if(0===p&&(">="!==a.operator||"<="!==u.operator))return null}for(const e of r){if(a&&!s(e,String(a),n))return null;if(u&&!s(e,String(u),n))return null;for(const r of t)if(!s(e,String(r),n))return!1;return!0}let _=!(!u||n.includePrerelease||!u.semver.prerelease.length)&&u.semver,v=!(!a||n.includePrerelease||!a.semver.prerelease.length)&&a.semver;_&&1===_.prerelease.length&&"<"===u.operator&&0===_.prerelease[0]&&(_=!1);for(const e of t){if(y=y||">"===e.operator||">="===e.operator,g=g||"<"===e.operator||"<="===e.operator,a)if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),">"===e.operator||">="===e.operator){if(f=l(a,e,n),f===e&&f!==a)return!1}else if(">="===a.operator&&!s(a.semver,String(e),n))return!1;if(u)if(_&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===_.major&&e.semver.minor===_.minor&&e.semver.patch===_.patch&&(_=!1),"<"===e.operator||"<="===e.operator){if(m=h(u,e,n),m===e&&m!==u)return!1}else if("<="===u.operator&&!s(u.semver,String(e),n))return!1;if(!e.operator&&(u||a)&&0!==p)return!1}return!(a&&g&&!u&&0!==p||u&&y&&!a&&0!==p||v||_)},l=(e,t,n)=>{if(!e)return t;const r=o(e.semver,t.semver,n);return r>0?e:r<0||">"===t.operator&&">="===e.operator?t:e},h=(e,t,n)=>{if(!e)return t;const r=o(e.semver,t.semver,n);return r<0?e:r>0||"<"===t.operator&&"<="===e.operator?t:e};e.exports=(e,t,n={})=>{if(e===t)return!0;e=new r(e,n),t=new r(t,n);let a=!1;e:for(const r of e.set){for(const e of t.set){const t=u(r,e,n);if(a=a||null!==t,t)continue e}if(a)return!1}return!0}},77631(e,t,n){const r=n(78311);e.exports=(e,t)=>new r(e,t).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" "))},13874(e,t,n){const r=n(78311);e.exports=(e,t)=>{try{return new r(e,t).range||"*"}catch(e){return null}}},43407(e,t,n){var r;n.d(t,{A:()=>i});var a=new Uint8Array(16);function i(){if(!r&&!(r="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return r(a)}},38823(e,t,n){n.d(t,{k:()=>i});for(var r=[],a=0;a<256;++a)r.push((a+256).toString(16).slice(1));function i(e,t=0){return(r[e[t+0]]+r[e[t+1]]+r[e[t+2]]+r[e[t+3]]+"-"+r[e[t+4]]+r[e[t+5]]+"-"+r[e[t+6]]+r[e[t+7]]+"-"+r[e[t+8]]+r[e[t+9]]+"-"+r[e[t+10]]+r[e[t+11]]+r[e[t+12]]+r[e[t+13]]+r[e[t+14]]+r[e[t+15]]).toLowerCase()}},477(e,t,n){n.d(t,{A:()=>s});const r={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var a=n(43407),i=n(38823);const s=function(e,t,n){if(r.randomUUID&&!t&&!e)return r.randomUUID();var s=(e=e||{}).random||(e.rng||a.A)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){n=n||0;for(var o=0;o<16;++o)t[n+o]=s[o];return t}return(0,i.k)(s)}},41167(e,t,n){n.d(t,{A:()=>c});var r=n(43407),a=n(38823),i=null,s=null,o=0;const c=function(e,t,n){e=e||{};var c=t&&n||0,d=t||new Uint8Array(16),u=e.random||(e.rng||r.A)(),l=void 0!==e.msecs?e.msecs:Date.now(),h=void 0!==e.seq?e.seq:null,p=s,f=i;return l>o&&void 0===e.msecs&&(o=l,null!==h&&(p=null,f=null)),null!==h&&(h>2147483647&&(h=2147483647),p=h>>>19&4095,f=524287&h),null!==p&&null!==f||(p=(p=127&u[6])<<8|u[7],f=(f=(f=63&u[8])<<8|u[9])<<5|u[10]>>>3),l+1e4>o&&null===h?++f>524287&&(f=0,++p>4095&&(p=0,o++)):o=l,s=p,i=f,d[c++]=o/1099511627776&255,d[c++]=o/4294967296&255,d[c++]=o/16777216&255,d[c++]=o/65536&255,d[c++]=o/256&255,d[c++]=255&o,d[c++]=p>>>4&15|112,d[c++]=255&p,d[c++]=f>>>13&63|128,d[c++]=f>>>5&255,d[c++]=f<<3&255|7&u[10],d[c++]=u[11],d[c++]=u[12],d[c++]=u[13],d[c++]=u[14],d[c++]=u[15],t||(0,a.k)(d)}},77265(e,t,n){function r(e,t){const n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const n=e.length;if(n!==t.length)return!1;for(let a=0;a<n;a++)if(!r(e[a],t[a]))return!1;return!0}if("object"===n){if(!e||!t)return e===t;const n=Object.keys(e),a=Object.keys(t);if(n.length!==a.length)return!1;for(const a of n)if(!r(e[a],t[a]))return!1;return!0}return e===t}function a(e){return encodeURI(function(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}(e))}n.d(t,{Dr:()=>x,rA:()=>r,DS:()=>d});const i={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},s={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},o={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let c="undefined"!=typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function d(e,t=Object.create(null),n=c,r=""){if(e&&"object"==typeof e&&!Array.isArray(e)){const a=e.$id||e.id;if(a){const i=new URL(a,n.href);i.hash.length>1?t[i.href]=e:(i.hash="",""===r?n=i:d(e,t,n))}}else if(!0!==e&&!1!==e)return t;const u=n.href+(r?"#"+r:"");if(void 0!==t[u])throw new Error(`Duplicate schema URI "${u}".`);if(t[u]=e,!0===e||!1===e)return t;if(void 0===e.__absolute_uri__&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:u}),e.$ref&&void 0===e.__absolute_ref__){const t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&void 0===e.__absolute_recursive_ref__){const t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}e.$anchor&&(t[new URL("#"+e.$anchor,n.href).href]=e);for(let c in e){if(o[c])continue;const u=`${r}/${a(c)}`,l=e[c];if(Array.isArray(l)){if(i[c]){const e=l.length;for(let r=0;r<e;r++)d(l[r],t,n,`${u}/${r}`)}}else if(s[c])for(let e in l)d(l[e],t,n,`${u}/${a(e)}`);else d(l,t,n,u)}return t}const u=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,l=[0,31,28,31,30,31,30,31,31,30,31,30,31],h=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function p(e){return e.test.bind(e)}const f={date:m,time:g.bind(void 0,!1),"date-time":function(e){const t=e.split(y);return 2==t.length&&m(t[0])&&g(!0,t[1])},duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),uri:function(e){return _.test(e)&&v.test(e)},"uri-reference":p(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),"uri-template":p(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),url:p(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),email:e=>{if('"'===e[0])return!1;const[t,n,...r]=e.split("@");return!(!t||!n||0!==r.length||t.length>64||n.length>253)&&"."!==t[0]&&!t.endsWith(".")&&!t.includes("..")&&!(!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))&&n.split(".").every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},hostname:p(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),ipv4:p(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:p(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),regex:function(e){if(w.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(e){return!1}},uuid:p(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":p(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":p(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":p(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function m(e){const t=e.match(u);if(!t)return!1;const n=+t[1],r=+t[2],a=+t[3];return r>=1&&r<=12&&a>=1&&a<=(2==r&&function(e){return e%4==0&&(e%100!=0||e%400==0)}(n)?29:l[r])}function g(e,t){const n=t.match(h);if(!n)return!1;const r=+n[1],a=+n[2],i=+n[3],s=!!n[5];return(r<=23&&a<=59&&i<=59||23==r&&59==a&&60==i)&&(!e||s)}const y=/t|\s/i,_=/\/|:/,v=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,w=/[^\\]\\Z/;var b;function E(e,t,n="2019-09",i=d(t),s=!0,o=null,c="#",u="#",l=Object.create(null)){if(!0===t)return{valid:!0,errors:[]};if(!1===t)return{valid:!1,errors:[{instanceLocation:c,keyword:"false",keywordLocation:c,error:"False boolean schema."}]};const h=typeof e;let p;switch(h){case"boolean":case"number":case"string":p=h;break;case"object":p=null===e?"null":Array.isArray(e)?"array":"object";break;default:throw new Error(`Instances of "${h}" type are not supported.`)}const{$ref:m,$recursiveRef:g,$recursiveAnchor:y,type:_,const:v,enum:w,required:b,not:x,anyOf:I,allOf:k,oneOf:S,if:O,then:T,else:A,format:$,properties:N,patternProperties:j,additionalProperties:C,unevaluatedProperties:R,minProperties:P,maxProperties:L,propertyNames:M,dependentRequired:z,dependentSchemas:D,dependencies:U,prefixItems:F,items:Z,additionalItems:B,unevaluatedItems:J,contains:q,minContains:H,maxContains:G,minItems:Q,maxItems:V,uniqueItems:W,minimum:K,maximum:Y,exclusiveMinimum:X,exclusiveMaximum:ee,multipleOf:te,minLength:ne,maxLength:re,pattern:ae,__absolute_ref__:ie,__absolute_recursive_ref__:se}=t,oe=[];if(!0===y&&null===o&&(o=t),"#"===g){const r=null===o?i[se]:o,a=`${u}/$recursiveRef`,d=E(e,null===o?t:o,n,i,s,r,c,a,l);d.valid||oe.push({instanceLocation:c,keyword:"$recursiveRef",keywordLocation:a,error:"A subschema had errors."},...d.errors)}if(void 0!==m){const t=i[ie||m];if(void 0===t){let e=`Unresolved $ref "${m}".`;throw ie&&ie!==m&&(e+=` Absolute URI "${ie}".`),e+=`\nKnown schemas:\n- ${Object.keys(i).join("\n- ")}`,new Error(e)}const r=`${u}/$ref`,a=E(e,t,n,i,s,o,c,r,l);if(a.valid||oe.push({instanceLocation:c,keyword:"$ref",keywordLocation:r,error:"A subschema had errors."},...a.errors),"4"===n||"7"===n)return{valid:0===oe.length,errors:oe}}if(Array.isArray(_)){let t=_.length,n=!1;for(let r=0;r<t;r++)if(p===_[r]||"integer"===_[r]&&"number"===p&&e%1==0&&e==e){n=!0;break}n||oe.push({instanceLocation:c,keyword:"type",keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${_.join('", "')}".`})}else"integer"===_?("number"!==p||e%1||e!=e)&&oe.push({instanceLocation:c,keyword:"type",keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${_}".`}):void 0!==_&&p!==_&&oe.push({instanceLocation:c,keyword:"type",keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${_}".`});if(void 0!==v&&("object"===p||"array"===p?r(e,v)||oe.push({instanceLocation:c,keyword:"const",keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&oe.push({instanceLocation:c,keyword:"const",keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),void 0!==w&&("object"===p||"array"===p?w.some(t=>r(e,t))||oe.push({instanceLocation:c,keyword:"enum",keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`}):w.some(t=>e===t)||oe.push({instanceLocation:c,keyword:"enum",keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`})),void 0!==x){const t=`${u}/not`;E(e,x,n,i,s,o,c,t).valid&&oe.push({instanceLocation:c,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let ce=[];if(void 0!==I){const t=`${u}/anyOf`,r=oe.length;let a=!1;for(let r=0;r<I.length;r++){const d=I[r],u=Object.create(l),h=E(e,d,n,i,s,!0===y?o:null,c,`${t}/${r}`,u);oe.push(...h.errors),a=a||h.valid,h.valid&&ce.push(u)}a?oe.length=r:oe.splice(r,0,{instanceLocation:c,keyword:"anyOf",keywordLocation:t,error:"Instance does not match any subschemas."})}if(void 0!==k){const t=`${u}/allOf`,r=oe.length;let a=!0;for(let r=0;r<k.length;r++){const d=k[r],u=Object.create(l),h=E(e,d,n,i,s,!0===y?o:null,c,`${t}/${r}`,u);oe.push(...h.errors),a=a&&h.valid,h.valid&&ce.push(u)}a?oe.length=r:oe.splice(r,0,{instanceLocation:c,keyword:"allOf",keywordLocation:t,error:"Instance does not match every subschema."})}if(void 0!==S){const t=`${u}/oneOf`,r=oe.length,a=S.filter((r,a)=>{const d=Object.create(l),u=E(e,r,n,i,s,!0===y?o:null,c,`${t}/${a}`,d);return oe.push(...u.errors),u.valid&&ce.push(d),u.valid}).length;1===a?oe.length=r:oe.splice(r,0,{instanceLocation:c,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${a} matches).`})}if("object"!==p&&"array"!==p||Object.assign(l,...ce),void 0!==O){const t=`${u}/if`;if(E(e,O,n,i,s,o,c,t,l).valid){if(void 0!==T){const r=E(e,T,n,i,s,o,c,`${u}/then`,l);r.valid||oe.push({instanceLocation:c,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...r.errors)}}else if(void 0!==A){const r=E(e,A,n,i,s,o,c,`${u}/else`,l);r.valid||oe.push({instanceLocation:c,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...r.errors)}}if("object"===p){if(void 0!==b)for(const t of b)t in e||oe.push({instanceLocation:c,keyword:"required",keywordLocation:`${u}/required`,error:`Instance does not have required property "${t}".`});const t=Object.keys(e);if(void 0!==P&&t.length<P&&oe.push({instanceLocation:c,keyword:"minProperties",keywordLocation:`${u}/minProperties`,error:`Instance does not have at least ${P} properties.`}),void 0!==L&&t.length>L&&oe.push({instanceLocation:c,keyword:"maxProperties",keywordLocation:`${u}/maxProperties`,error:`Instance does not have at least ${L} properties.`}),void 0!==M){const t=`${u}/propertyNames`;for(const r in e){const e=`${c}/${a(r)}`,d=E(r,M,n,i,s,o,e,t);d.valid||oe.push({instanceLocation:c,keyword:"propertyNames",keywordLocation:t,error:`Property name "${r}" does not match schema.`},...d.errors)}}if(void 0!==z){const t=`${u}/dependantRequired`;for(const n in z)if(n in e){const r=z[n];for(const a of r)a in e||oe.push({instanceLocation:c,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${n}" but does not have "${a}".`})}}if(void 0!==D)for(const t in D){const r=`${u}/dependentSchemas`;if(t in e){const d=E(e,D[t],n,i,s,o,c,`${r}/${a(t)}`,l);d.valid||oe.push({instanceLocation:c,keyword:"dependentSchemas",keywordLocation:r,error:`Instance has "${t}" but does not match dependant schema.`},...d.errors)}}if(void 0!==U){const t=`${u}/dependencies`;for(const r in U)if(r in e){const d=U[r];if(Array.isArray(d))for(const n of d)n in e||oe.push({instanceLocation:c,keyword:"dependencies",keywordLocation:t,error:`Instance has "${r}" but does not have "${n}".`});else{const u=E(e,d,n,i,s,o,c,`${t}/${a(r)}`);u.valid||oe.push({instanceLocation:c,keyword:"dependencies",keywordLocation:t,error:`Instance has "${r}" but does not match dependant schema.`},...u.errors)}}}const r=Object.create(null);let d=!1;if(void 0!==N){const t=`${u}/properties`;for(const u in N){if(!(u in e))continue;const h=`${c}/${a(u)}`,p=E(e[u],N[u],n,i,s,o,h,`${t}/${a(u)}`);if(p.valid)l[u]=r[u]=!0;else if(d=s,oe.push({instanceLocation:c,keyword:"properties",keywordLocation:t,error:`Property "${u}" does not match schema.`},...p.errors),d)break}}if(!d&&void 0!==j){const t=`${u}/patternProperties`;for(const u in j){const h=new RegExp(u,"u"),p=j[u];for(const f in e){if(!h.test(f))continue;const m=`${c}/${a(f)}`,g=E(e[f],p,n,i,s,o,m,`${t}/${a(u)}`);g.valid?l[f]=r[f]=!0:(d=s,oe.push({instanceLocation:c,keyword:"patternProperties",keywordLocation:t,error:`Property "${f}" matches pattern "${u}" but does not match associated schema.`},...g.errors))}}}if(d||void 0===C){if(!d&&void 0!==R){const t=`${u}/unevaluatedProperties`;for(const r in e)if(!l[r]){const d=`${c}/${a(r)}`,u=E(e[r],R,n,i,s,o,d,t);u.valid?l[r]=!0:oe.push({instanceLocation:c,keyword:"unevaluatedProperties",keywordLocation:t,error:`Property "${r}" does not match unevaluated properties schema.`},...u.errors)}}}else{const t=`${u}/additionalProperties`;for(const u in e){if(r[u])continue;const h=`${c}/${a(u)}`,p=E(e[u],C,n,i,s,o,h,t);p.valid?l[u]=!0:(d=s,oe.push({instanceLocation:c,keyword:"additionalProperties",keywordLocation:t,error:`Property "${u}" does not match additional properties schema.`},...p.errors))}}}else if("array"===p){void 0!==V&&e.length>V&&oe.push({instanceLocation:c,keyword:"maxItems",keywordLocation:`${u}/maxItems`,error:`Array has too many items (${e.length} > ${V}).`}),void 0!==Q&&e.length<Q&&oe.push({instanceLocation:c,keyword:"minItems",keywordLocation:`${u}/minItems`,error:`Array has too few items (${e.length} < ${Q}).`});const t=e.length;let a=0,d=!1;if(void 0!==F){const r=`${u}/prefixItems`,h=Math.min(F.length,t);for(;a<h;a++){const t=E(e[a],F[a],n,i,s,o,`${c}/${a}`,`${r}/${a}`);if(l[a]=!0,!t.valid&&(d=s,oe.push({instanceLocation:c,keyword:"prefixItems",keywordLocation:r,error:"Items did not match schema."},...t.errors),d))break}}if(void 0!==Z){const r=`${u}/items`;if(Array.isArray(Z)){const u=Math.min(Z.length,t);for(;a<u;a++){const t=E(e[a],Z[a],n,i,s,o,`${c}/${a}`,`${r}/${a}`);if(l[a]=!0,!t.valid&&(d=s,oe.push({instanceLocation:c,keyword:"items",keywordLocation:r,error:"Items did not match schema."},...t.errors),d))break}}else for(;a<t;a++){const t=E(e[a],Z,n,i,s,o,`${c}/${a}`,r);if(l[a]=!0,!t.valid&&(d=s,oe.push({instanceLocation:c,keyword:"items",keywordLocation:r,error:"Items did not match schema."},...t.errors),d))break}if(!d&&void 0!==B){const r=`${u}/additionalItems`;for(;a<t;a++){const t=E(e[a],B,n,i,s,o,`${c}/${a}`,r);l[a]=!0,t.valid||(d=s,oe.push({instanceLocation:c,keyword:"additionalItems",keywordLocation:r,error:"Items did not match additional items schema."},...t.errors))}}}if(void 0!==q)if(0===t&&void 0===H)oe.push({instanceLocation:c,keyword:"contains",keywordLocation:`${u}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(void 0!==H&&t<H)oe.push({instanceLocation:c,keyword:"minContains",keywordLocation:`${u}/minContains`,error:`Array has less items (${t}) than minContains (${H}).`});else{const r=`${u}/contains`,a=oe.length;let d=0;for(let a=0;a<t;a++){const t=E(e[a],q,n,i,s,o,`${c}/${a}`,r);t.valid?(l[a]=!0,d++):oe.push(...t.errors)}d>=(H||0)&&(oe.length=a),void 0===H&&void 0===G&&0===d?oe.splice(a,0,{instanceLocation:c,keyword:"contains",keywordLocation:r,error:"Array does not contain item matching schema."}):void 0!==H&&d<H?oe.push({instanceLocation:c,keyword:"minContains",keywordLocation:`${u}/minContains`,error:`Array must contain at least ${H} items matching schema. Only ${d} items were found.`}):void 0!==G&&d>G&&oe.push({instanceLocation:c,keyword:"maxContains",keywordLocation:`${u}/maxContains`,error:`Array may contain at most ${G} items matching schema. ${d} items were found.`})}if(!d&&void 0!==J){const r=`${u}/unevaluatedItems`;for(;a<t;a++){if(l[a])continue;const t=E(e[a],J,n,i,s,o,`${c}/${a}`,r);l[a]=!0,t.valid||oe.push({instanceLocation:c,keyword:"unevaluatedItems",keywordLocation:r,error:"Items did not match unevaluated items schema."},...t.errors)}}if(W)for(let n=0;n<t;n++){const a=e[n],i="object"==typeof a&&null!==a;for(let s=0;s<t;s++){if(n===s)continue;const t=e[s];(a===t||i&&"object"==typeof t&&null!==t&&r(a,t))&&(oe.push({instanceLocation:c,keyword:"uniqueItems",keywordLocation:`${u}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${s}.`}),n=Number.MAX_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER)}}}else if("number"===p){if("4"===n?(void 0!==K&&(!0===X&&e<=K||e<K)&&oe.push({instanceLocation:c,keyword:"minimum",keywordLocation:`${u}/minimum`,error:`${e} is less than ${X?"or equal to ":""} ${K}.`}),void 0!==Y&&(!0===ee&&e>=Y||e>Y)&&oe.push({instanceLocation:c,keyword:"maximum",keywordLocation:`${u}/maximum`,error:`${e} is greater than ${ee?"or equal to ":""} ${Y}.`})):(void 0!==K&&e<K&&oe.push({instanceLocation:c,keyword:"minimum",keywordLocation:`${u}/minimum`,error:`${e} is less than ${K}.`}),void 0!==Y&&e>Y&&oe.push({instanceLocation:c,keyword:"maximum",keywordLocation:`${u}/maximum`,error:`${e} is greater than ${Y}.`}),void 0!==X&&e<=X&&oe.push({instanceLocation:c,keyword:"exclusiveMinimum",keywordLocation:`${u}/exclusiveMinimum`,error:`${e} is less than ${X}.`}),void 0!==ee&&e>=ee&&oe.push({instanceLocation:c,keyword:"exclusiveMaximum",keywordLocation:`${u}/exclusiveMaximum`,error:`${e} is greater than or equal to ${ee}.`})),void 0!==te){const t=e%te;Math.abs(0-t)>=1.1920929e-7&&Math.abs(te-t)>=1.1920929e-7&&oe.push({instanceLocation:c,keyword:"multipleOf",keywordLocation:`${u}/multipleOf`,error:`${e} is not a multiple of ${te}.`})}}else if("string"===p){const t=void 0===ne&&void 0===re?0:function(e){let t,n=0,r=e.length,a=0;for(;a<r;)n++,t=e.charCodeAt(a++),t>=55296&&t<=56319&&a<r&&(t=e.charCodeAt(a),56320==(64512&t)&&a++);return n}(e);void 0!==ne&&t<ne&&oe.push({instanceLocation:c,keyword:"minLength",keywordLocation:`${u}/minLength`,error:`String is too short (${t} < ${ne}).`}),void 0!==re&&t>re&&oe.push({instanceLocation:c,keyword:"maxLength",keywordLocation:`${u}/maxLength`,error:`String is too long (${t} > ${re}).`}),void 0===ae||new RegExp(ae,"u").test(e)||oe.push({instanceLocation:c,keyword:"pattern",keywordLocation:`${u}/pattern`,error:"String does not match pattern."}),void 0!==$&&f[$]&&!f[$](e)&&oe.push({instanceLocation:c,keyword:"format",keywordLocation:`${u}/format`,error:`String does not match format "${$}".`})}return{valid:0===oe.length,errors:oe}}!function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"}(b||(b={}));class x{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=d(e)}validate(e){return E(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),d(e,this.lookup)}}},66630(e,t,n){n.d(t,{I:()=>a});var r=Object.defineProperty,a=(e,t)=>{let n={};for(var a in e)r(n,a,{get:e[a],enumerable:!0});return t||r(n,Symbol.toStringTag,{value:"Module"}),n}},15960(e,t,n){n.d(t,{NK:()=>c,xL:()=>o,zr:()=>d}),n(66630);var r=n(98749),a=n(89583),i=n(16675),s=class{};function o(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var c=class extends s{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,(0,r.ZO)(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers="false"===(0,a.Az)("LANGCHAIN_CALLBACKS_BACKGROUND");constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return r.yL.prototype.toJSON.call(this)}toJSONNotImplemented(){return r.yL.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){return new class extends c{name=i.A();constructor(){super(),Object.assign(this,e)}}}};const d=e=>{const t=e;return void 0!==t&&"function"==typeof t.copy&&"string"==typeof t.name&&"boolean"==typeof t.awaitHandlers}},39149(e,t,n){n.d(t,{Td:()=>P,tW:()=>L}),n(66630);var r=n(56362),a=n(89583),i=n(15960),s=n(11590),o=n(49418);function c(e,t){return`${e.open}${t}${e.close}`}function d(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function u(e){return"string"==typeof e?e.trim():null==e?e:d(e,e.toString())}function l(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}const{color:h}=o;var p=class extends s.JS{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){const t=[];let n=e;for(;n.parent_run_id;){const e=this.runMap.get(n.parent_run_id);if(!e)break;t.push(e),n=e}return t}getBreadcrumbs(e){const t=[...this.getParents(e).reverse(),e].map((e,t,n)=>{const r=`${e.execution_order}:${e.run_type}:${e.name}`;return t===n.length-1?c(o.bold,r):r}).join(" > ");return c(h.grey,t)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.green,"[chain/start]")} [${t}] Entering Chain run with input: ${d(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.cyan,"[chain/end]")} [${t}] [${l(e)}] Exiting Chain run with output: ${d(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.red,"[chain/error]")} [${t}] [${l(e)}] Chain run errored with error: ${d(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),n="prompts"in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${c(h.green,"[llm/start]")} [${t}] Entering LLM run with input: ${d(n,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.cyan,"[llm/end]")} [${t}] [${l(e)}] Exiting LLM run with output: ${d(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.red,"[llm/error]")} [${t}] [${l(e)}] LLM run errored with error: ${d(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.green,"[tool/start]")} [${t}] Entering Tool run with input: "${u(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.cyan,"[tool/end]")} [${t}] [${l(e)}] Exiting Tool run with output: "${u(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.red,"[tool/error]")} [${t}] [${l(e)}] Tool run errored with error: ${d(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${d(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.cyan,"[retriever/end]")} [${t}] [${l(e)}] Exiting Retriever run with output: ${d(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${c(h.red,"[retriever/error]")} [${t}] [${l(e)}] Retriever run errored with error: ${d(e.error,"[error]")}`)}onAgentAction(e){const t=e,n=this.getBreadcrumbs(e);console.log(`${c(h.blue,"[agent/action]")} [${n}] Agent selected action: ${d(t.actions[t.actions.length-1],"[action]")}`)}},f=n(24658),m=n(23549),g=n(31259);let y;const _=()=>(void 0===y&&(y=new g.Kj("false"===(0,a.Az)("LANGCHAIN_CALLBACKS_BACKGROUND")?{blockOnRootRunFinalization:!0}:{})),y);var v=n(51688),w=n(63389),b=class e extends s.JS{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:n,projectName:r,client:a,replicas:i}=t;this.projectName=r??(0,g.q7)(),this.replicas=i,this.exampleId=n,this.client=a??_();const s=e.getTraceableRunTree();s&&this.updateFromRunTree(s)}async persistRun(e){}async onRunCreate(e){e.extra?.lc_defers_inputs||await(this.getRunTreeWithTracingConfig(e.id)?.postRun())}async onRunUpdate(e){const t=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await(t?.postRun()):await(t?.patchRun())}onLLMEnd(e){const t=e.outputs;if(t?.generations){const n=function(e){let t;for(const n of e)for(const e of n)m.Od.isInstance(e.message)&&void 0!==e.message.usage_metadata&&(t=(0,f.n)(t,e.message.usage_metadata));return t}(t.generations);if(void 0!==n){e.extra=e.extra??{};const t=e.extra.metadata??{};t.usage_metadata=n,e.extra.metadata=t}}}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e;const n=new Set;for(;t.parent_run&&!n.has(t.id)&&(n.add(t.id),t.parent_run);)t=t.parent_run;n.clear();const r=[t];for(;r.length>0;){const e=r.shift();e&&!n.has(e.id)&&(n.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&r.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const t=this.runTreeMap.get(e);if(t)return new v.gk({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return(0,w.vR)(!0)}catch{return}}},E=n(36968),x=n(73290);let I;async function k(e,t){if(!0===t){const t=(0,E.X0)();void 0!==t?await t.run(void 0,async()=>e()):await e()}else void 0===I&&(I=new(0,x.default)({autoStart:!0,concurrency:1})),I.add(async()=>{const t=(0,E.X0)();void 0!==t?await t.run(void 0,async()=>e()):await e()})}function S(e){const t=(0,E.X0)();if(void 0!==t)return t.getStore()?.[E.hr]?.[e]}const O=Symbol("lc:configure_hooks");var T=n(16675),A=class{setHandler(e){return this.setHandlers([e])}},$=class{constructor(e,t,n,r,a,i,s,o){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=a,this.metadata=i,this.inheritableMetadata=s,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>k(async()=>{try{await(t.handleText?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,r,a){await Promise.all(this.handlers.map(n=>k(async()=>{try{await(n.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleCustomEvent: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}},N=class extends ${getChild(e){const t=new P(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw e}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreRetriever)try{await(t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags))}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},j=class extends ${async handleLLMNewToken(e,t,n,r,a,i){await Promise.all(this.handlers.map(n=>k(async()=>{if(!n.ignoreLLM)try{await(n.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMNewToken: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}async handleLLMError(e,t,n,r,a){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreLLM)try{await(t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,a))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMEnd(e,t,n,r,a){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreLLM)try{await(t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,a))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},C=class extends ${getChild(e){const t=new P(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,r,a){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreChain)try{await(t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,a))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleChainEnd(e,t,n,r,a){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreChain)try{await(t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,a))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChainEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreAgent)try{await(t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreAgent)try{await(t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},R=class extends ${getChild(e){const t=new P(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreAgent)try{await(t.handleToolError?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEvent(e){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreAgent)try{await(t.handleToolEvent?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if(t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>k(async()=>{if(!t.ignoreAgent)try{await(t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags))}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},P=class e extends A{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,t){super(),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,n=void 0,r=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(t.map(async(t,r)=>{const i=0===r&&n?n:(0,T.A)();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return(0,s.j7)(n)&&n._createRunForLLMStart(e,[t],i,this._parentRunId,a,this.tags,this.metadata,c),k(async()=>{try{await(n.handleLLMStart?.(e,[t],i,this._parentRunId,a,this.tags,this.metadata,c))}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new j(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,a=void 0,i=void 0,o=void 0,c=void 0,d=void 0){return Promise.all(t.map(async(t,a)=>{const o=0===a&&n?n:(0,T.A)();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return(0,s.j7)(n)&&n._createRunForChatModelStart(e,[t],o,this._parentRunId,i,this.tags,this.metadata,d),k(async()=>{try{if(n.handleChatModelStart)await(n.handleChatModelStart?.(e,[t],o,this._parentRunId,i,this.tags,this.metadata,d));else if(n.handleLLMStart){const a=(0,r.Sw)(t);await(n.handleLLMStart?.(e,[a],o,this._parentRunId,i,this.tags,this.metadata,d))}}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new j(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=(0,T.A)(),r=void 0,a=void 0,i=void 0,o=void 0,c=void 0,d=void 0){return await Promise.all(this.handlers.map(a=>{if(!a.ignoreChain)return(0,s.j7)(a)&&a._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,d),k(async()=>{try{await(a.handleChainStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,d))}catch(e){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleChainStart: ${e}`),a.raiseError)throw e}},a.awaitHandlers)})),new C(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=(0,T.A)(),r=void 0,a=void 0,i=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreAgent)return(0,s.j7)(r)&&r._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),k(async()=>{try{await(r.handleToolStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o,c))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleToolStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new R(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=(0,T.A)(),r=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreRetriever)return(0,s.j7)(r)&&r._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),k(async()=>{try{await(r.handleRetrieverStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleRetrieverStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new N(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,r,a){await Promise.all(this.handlers.map(r=>k(async()=>{if(!r.ignoreCustomEvent)try{await(r.handleCustomEvent?.(e,t,n,this.tags,this.metadata))}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleCustomEvent: ${e}`),r.raiseError)throw e}},r.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of e)this.addHandler(n,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(t=[],n=!0){const r=new e(this._parentRunId);for(const e of this.handlers){const t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(const e of this.tags){const t=this.inheritableTags.includes(e);r.addTags([e],t)}for(const e of Object.keys(this.metadata)){const t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(const e of t)r.handlers.filter(e=>"console_callback_handler"===e.name).some(t=>t.name===e.name)||r.addHandler(e,n);return r}static fromHandlers(e){class t extends i.NK{name=(0,T.A)();constructor(){super(),Object.assign(this,e)}}const n=new this;return n.addHandler(new t),n}static configure(e,t,n,r,a,i,s){return this._configureSync(e,t,n,r,a,i,s)}static _configureSync(t,n,r,s,o,c,d){let u;(t||n)&&(Array.isArray(t)||!t?(u=new e,u.setHandlers(t?.map(L)??[],!0)):u=t,u=u.copy(Array.isArray(n)?n.map(L):n?.handlers,!1));const l="true"===(0,a.Az)("LANGCHAIN_VERBOSE")||d?.verbose,h=b.getTraceableRunTree(),f=h?.tracingEnabled??!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>"true"===(0,a.Az)(e));if(!1===h?.tracingEnabled&&u){const e=u.handlers.filter(e=>"langchain_tracer"===e.name);for(const t of e)u.removeHandler(t)}const m=f||((0,a.Az)("LANGCHAIN_TRACING")??!1);if(l||m){if(u||(u=new e),l&&!u.handlers.some(e=>e.name===p.prototype.name)){const e=new p;u.addHandler(e,!0)}if(m&&!u.handlers.some(e=>"langchain_tracer"===e.name)&&f){const e=new b;u.addHandler(e,!0)}f&&h&&void 0===u._parentRunId&&(u._parentRunId=h.id,u.handlers.find(e=>"langchain_tracer"===e.name)?.updateFromRunTree(h))}for(const{contextVar:t,inheritable:n=!0,handlerClass:r,envVar:s}of S(O)||[]){const o=s&&"true"===(0,a.Az)(s)&&r;let c;const d=void 0!==t?S(t):void 0;d&&(0,i.zr)(d)?c=d:o&&(c=new r({})),void 0!==c&&(u||(u=new e),u.handlers.some(e=>e.name===c.name)||u.addHandler(c,n))}return(r||s)&&u&&(u.addTags(r??[]),u.addTags(s??[],!1)),(o||c)&&u&&(u.addMetadata(o??{}),u.addMetadata(c??{},!1)),u}};function L(e){return"name"in e?e:i.NK.fromMethods(e)}},64033(e,t,n){n.d(t,{eN:()=>s,Yt:()=>r}),n(66630);function r(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}const a=function e(t){const n=Symbol.for(t);return{brand(e,r){const a=r?Symbol.for(`${t}.${r}`):n;class i extends e{[a]=!0;constructor(...e){super(...e)}static isInstance(e){return"object"==typeof e&&null!==e&&a in e&&!0===e[a]}}return Object.defineProperty(i,"name",{value:e.name}),i},sub:n=>e(`${t}.${n}`),isInstance:e=>"object"==typeof e&&null!==e&&n in e&&!0===e[n]}}("langchain").sub("error");var i=class extends(a.brand(Error)){name="LangChainError";constructor(e){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},s=class extends(a.brand(i,"model-abort")){name="ModelAbortError";partialOutput;constructor(e,t){super(e),this.partialOutput=t}};a.brand(i,"context-overflow")},98749(e,t,n){n.d(t,{yL:()=>d,ZO:()=>c}),n(66630);var r=n(79478);function a(e,t){return t?.[e]||r(e)}n(25148);const i="__lc_escaped__";function s(e,t=new WeakSet){if(null!==e&&"object"==typeof e&&!Array.isArray(e)){if(t.has(e))return function(e){let t;return t=null!==e&&"object"==typeof e?"lc_id"in e&&Array.isArray(e.lc_id)?e.lc_id:[e.constructor?.name??"Object"]:[typeof e],{lc:1,type:"not_implemented",id:t}}(e);if(null!==(n=e)&&"object"==typeof n&&"lc_serializable"in n&&"function"==typeof n.toJSON)return e;t.add(e);const r=e;if(function(e){return"lc"in e||1===Object.keys(e).length&&"__lc_escaped__"in e}(r))return t.delete(e),function(e){return{[i]:e}}(r);const a={};for(const[e,n]of Object.entries(r))a[e]=s(n,t);return t.delete(e),a}var n;return Array.isArray(e)?e.map(e=>s(e,t)):e}function o(e){return Array.isArray(e)?[...e]:{...e}}function c(e){const t=Object.getPrototypeOf(e);return"function"!=typeof e.lc_name||"function"==typeof t.lc_name&&e.lc_name()===t.lc_name()?e.name:e.lc_name()}var d=class e{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,c(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){void 0!==this.lc_serializable_keys?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([e])=>this.lc_serializable_keys?.includes(e))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof e||"object"!=typeof this.lc_kwargs||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},r=Object.keys(this.lc_kwargs).reduce((e,t)=>(e[t]=t in this?this[t]:this.lc_kwargs[t],e),{});for(let e=Object.getPrototypeOf(this);e;e=Object.getPrototypeOf(e))Object.assign(t,Reflect.get(e,"lc_aliases",this)),Object.assign(n,Reflect.get(e,"lc_secrets",this)),Object.assign(r,Reflect.get(e,"lc_attributes",this));Object.keys(n).forEach(e=>{let t=this,n=r;const[a,...i]=e.split(".").reverse();for(const e of i.reverse()){if(!(e in t)||void 0===t[e])return;e in n&&void 0!==n[e]||("object"==typeof t[e]&&null!=t[e]?n[e]={}:Array.isArray(t[e])&&(n[e]=[])),t=t[e],n=n[e]}a in t&&void 0!==t[a]&&(n[a]=n[a]||t[a])});const i={},c=new WeakSet;c.add(this);for(const[e,t]of Object.entries(r))i[e]=s(t,c);const d=function(e,t,n){const r={};for(const a in e)Object.hasOwn(e,a)&&(r[t(a,n)]=e[a]);return r}(Object.keys(n).length?function(e,t){const n=o(e);for(const[e,r]of Object.entries(t)){const[t,...a]=e.split(".").reverse();let i=n;for(const e of a.reverse()){if(void 0===i[e])break;i[e]=o(i[e]),i=i[e]}void 0!==i[t]&&(i[t]={lc:1,type:"secret",id:[r]})}return n}(i,n):i,a,t);return{lc:1,type:"constructor",id:this.lc_id,kwargs:d}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}},23549(e,t,n){n.d(t,{Od:()=>N,H:()=>R,KX:()=>j,jm:()=>C});var r=n(15282),a=n(99221),i=n(33927),s=n(69860);function o(e){switch(e){case"csv":return"text/csv";case"doc":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":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 c(e){if((0,s.nD)(e.document)&&(0,s.nD)(e.document.source)){const t=o((0,s.nD)(e.document)&&(0,s.vQ)(e.document.format)?e.document.format:"");if((0,s.nD)(e.document.source)){if((0,s.nD)(e.document.source.s3Location)&&(0,s.vQ)(e.document.source.s3Location.uri))return{type:"file",mimeType:t,fileId:e.document.source.s3Location.uri};if((0,s.MS)(e.document.source.bytes))return{type:"file",mimeType:t,data:e.document.source.bytes};if((0,s.vQ)(e.document.source.text))return{type:"file",mimeType:t,data:Buffer.from(e.document.source.text).toString("base64")};if((0,s.V3)(e.document.source.content))return{type:"file",mimeType:t,data:e.document.source.content.reduce((e,t)=>(0,s.nD)(t)&&(0,s.vQ)(t.text)?e+t.text:e,"")}}}return{type:"non_standard",value:e}}function d(e){if((0,s.MP)(e,"image")&&(0,s.nD)(e.image)){const t=o((0,s.nD)(e.image)&&(0,s.vQ)(e.image.format)?e.image.format:"");if((0,s.nD)(e.image.source)){if((0,s.nD)(e.image.source.s3Location)&&(0,s.vQ)(e.image.source.s3Location.uri))return{type:"image",mimeType:t,fileId:e.image.source.s3Location.uri};if((0,s.MS)(e.image.source.bytes))return{type:"image",mimeType:t,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function u(e){if((0,s.MP)(e,"video")&&(0,s.nD)(e.video)){const t=o((0,s.nD)(e.video)&&(0,s.vQ)(e.video.format)?e.video.format:"");if((0,s.nD)(e.video.source)){if((0,s.nD)(e.video.source.s3Location)&&(0,s.vQ)(e.video.source.s3Location.uri))return{type:"video",mimeType:t,fileId:e.video.source.s3Location.uri};if((0,s.MS)(e.video.source.bytes))return{type:"video",mimeType:t,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function l(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const e of t)(0,s.MP)(e,"cache_point")?yield{type:"non_standard",value:e}:(0,s.MP)(e,"citations_content")&&(0,s.nD)(e.citationsContent)?yield{type:"text",text:(0,s.V3)(e.citationsContent.content)?e.citationsContent.content.reduce((e,t)=>(0,s.nD)(t)&&(0,s.vQ)(t.text)?e+t.text:e,""):"",annotations:(0,s.V3)(e.citationsContent.citations)?e.citationsContent.citations.reduce((e,t)=>{if((0,s.nD)(t)){const n=(0,s.V3)(t.sourceContent)?t.sourceContent.reduce((e,t)=>(0,s.nD)(t)&&(0,s.vQ)(t.text)?e+t.text:e,""):"",r=(0,s.iD)(()=>{if((0,s.nD)(t.location)){const e=t.location.documentChar||t.location.documentPage||t.location.documentChunk;if((0,s.nD)(e))return{source:(0,s.jM)(e.documentIndex)?e.documentIndex.toString():void 0,startIndex:(0,s.jM)(e.start)?e.start:void 0,endIndex:(0,s.jM)(e.end)?e.end:void 0}}return{}});e.push({type:"citation",citedText:n,...r})}return e},[]):[]}:(0,s.MP)(e,"document")&&(0,s.nD)(e.document)?yield c(e):(0,s.MP)(e,"guard_content")?yield{type:"non_standard",value:e}:(0,s.MP)(e,"image")&&(0,s.nD)(e.image)?yield d(e):(0,s.MP)(e,"reasoning_content")&&(0,s.vQ)(e.reasoningText)?yield{type:"reasoning",reasoning:e.reasoningText}:(0,s.MP)(e,"text")&&(0,s.vQ)(e.text)?yield{type:"text",text:e.text}:(0,s.MP)(e,"tool_result")?yield{type:"non_standard",value:e}:(0,s.MP)(e,"tool_call")||((0,s.MP)(e,"video")&&(0,s.nD)(e.video)?yield u(e):yield{type:"non_standard",value:e})}())}const h={translateContent:l,translateContentChunk:l};function p(e){const t=[],n=e.additional_kwargs?.reasoning_content;if((0,s.vQ)(n)&&n.length>0&&t.push({type:"reasoning",reasoning:n}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(const n of e.content)"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&(0,s.vQ)(n.text)&&t.push({type:"text",text:n.text});for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}const f={translateContent:p,translateContentChunk:p};function m(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const n of t)(0,s.MP)(n,"text")&&(0,s.vQ)(n.text)?yield{type:"text",text:n.text}:(0,s.MP)(n,"thinking")&&(0,s.vQ)(n.thinking)?yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}}:(0,s.MP)(n,"inlineData")&&(0,s.nD)(n.inlineData)&&(0,s.vQ)(n.inlineData.mimeType)&&(0,s.vQ)(n.inlineData.data)?yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:(0,s.MP)(n,"functionCall")&&(0,s.nD)(n.functionCall)&&(0,s.vQ)(n.functionCall.name)&&(0,s.nD)(n.functionCall.args)?yield{type:"tool_call",id:e.id,name:n.functionCall.name,args:n.functionCall.args}:(0,s.MP)(n,"functionResponse")?yield{type:"non_standard",value:n}:(0,s.MP)(n,"fileData")&&(0,s.nD)(n.fileData)&&(0,s.vQ)(n.fileData.mimeType)&&(0,s.vQ)(n.fileData.fileUri)?yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:((0,s.MP)(n,"executableCode")||(0,s.MP)(n,"codeExecutionResult"),yield{type:"non_standard",value:n})}())}const g={translateContent:m,translateContentChunk:m};function y(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const n of t){if((0,s.MP)(n,"reasoning")&&(0,s.vQ)(n.reasoning)){const r=(0,s.iD)(()=>{const r=t.indexOf(n);if((0,s.V3)(e.additional_kwargs?.signatures)&&r>=0)return e.additional_kwargs.signatures.at(r)});(0,s.vQ)(r)?yield{type:"reasoning",reasoning:n.reasoning,signature:r}:yield{type:"reasoning",reasoning:n.reasoning};continue}if((0,s.MP)(n,"thinking")&&(0,s.vQ)(n.thinking))yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};else if((0,s.MP)(n,"text")&&(0,s.vQ)(n.text))yield{type:"text",text:n.text};else if((0,s.MP)(n,"image_url")){if((0,s.vQ)(n.image_url))if(n.image_url.startsWith("data:")){const e=n.image_url.match(/^data:([^;]+);base64,(.+)$/);e?yield{type:"image",data:e[2],mimeType:e[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url}}else(0,s.MP)(n,"media")&&(0,s.vQ)(n.mimeType)&&(0,s.vQ)(n.data)?yield{type:"file",mimeType:n.mimeType,data:n.data}:yield{type:"non_standard",value:n}}}())}const _={translateContent:y,translateContentChunk:y};function v(e){const t=[],n=e.additional_kwargs?.reasoning;if((0,s.vQ)(n)&&n.length>0&&t.push({type:"reasoning",reasoning:n}),"string"==typeof e.content){let n=e.content;const r=n.match(/<think>([\s\S]*?)<\/think>/);if(r){const e=r[1].trim();e.length>0&&t.push({type:"reasoning",reasoning:e}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&t.push({type:"text",text:n})}else for(const n of e.content)if("object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&(0,s.vQ)(n.text)){let e=n.text;const r=e.match(/<think>([\s\S]*?)<\/think>/);if(r){const n=r[1].trim();n.length>0&&t.push({type:"reasoning",reasoning:n}),e=e.replace(/<think>[\s\S]*?<\/think>/,"").trim()}e.length>0&&t.push({type:"text",text:e})}for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}const w={translateContent:v,translateContentChunk:v};function b(e){const t=[],n=e.additional_kwargs?.reasoning_content;if((0,s.vQ)(n)&&n.length>0&&t.push({type:"reasoning",reasoning:n}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(const n of e.content)"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&(0,s.vQ)(n.text)&&t.push({type:"text",text:n.text});for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}const E={translateContent:b,translateContentChunk:b};function x(e){const t=[];if((0,s.nD)(e.additional_kwargs?.reasoning)){const n=e.additional_kwargs.reasoning;if((0,s.V3)(n.summary)){const e=n.summary.reduce((e,t)=>(0,s.nD)(t)&&(0,s.vQ)(t.text)?`${e}${t.text}`:e,"");e.length>0&&t.push({type:"reasoning",reasoning:e})}}const n=e.additional_kwargs?.reasoning_content;if((0,s.vQ)(n)&&n.length>0&&t.push({type:"reasoning",reasoning:n}),"string"==typeof e.content)e.content.length>0&&t.push({type:"text",text:e.content});else for(const n of e.content)"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&(0,s.vQ)(n.text)&&t.push({type:"text",text:n.text});for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}const I={translateContent:x,translateContentChunk:x};function k(e){return Array.from(function*(){const t=(0,s.iD)(()=>{if("string"==typeof e.content)return e.additional_kwargs.originalTextContentBlock?[{...e.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:e.content}];{const t=e.additional_kwargs?.originalTextContentBlock;if(t?.thoughtSignature&&!e.content.some(e=>"thoughtSignature"in e)){const n=[...e.content];for(let e=n.length-1;e>=0;e--){const r=n[e];if("text"===r.type&&!r.thought)return r.thoughtSignature=t.thoughtSignature,n}}return e.content}});for(const n of t){const t=(0,s.iD)(()=>(0,s.MP)(n,"text")&&(0,s.vQ)(n.text)?{type:"text",text:n.text}:(0,s.MP)(n,"inlineData")&&(0,s.nD)(n.inlineData)&&(0,s.vQ)(n.inlineData.mimeType)&&(0,s.vQ)(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:(0,s.MP)(n,"functionCall")&&(0,s.nD)(n.functionCall)&&(0,s.vQ)(n.functionCall.name)&&(0,s.nD)(n.functionCall.args)?{type:"tool_call",id:e.id,name:n.functionCall.name,args:n.functionCall.args}:(0,s.MP)(n,"functionResponse")?{type:"non_standard",value:n}:(0,s.MP)(n,"fileData")&&(0,s.nD)(n.fileData)&&(0,s.vQ)(n.fileData.mimeType)&&(0,s.vQ)(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:((0,s.MP)(n,"executableCode")||(0,s.MP)(n,"codeExecutionResult"),{type:"non_standard",value:n})),r=(0,s.iD)(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:"text"===t.type?t.text:"",reasoningContentBlock:t}:t),a={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...r};for(const e in a)void 0===a[e]&&delete a[e];yield a}}())}const S={translateContent:k,translateContentChunk:k};function O(e){return globalThis.lc_block_translators_registry.get(e)}globalThis.lc_block_translators_registry??=new Map([["anthropic",a.B],["bedrock-converse",h],["deepseek",f],["google",S],["google-genai",g],["google-vertexai",_],["groq",w],["ollama",E],["openai",i.F],["xai",I]]);var T=n(24658),A=n(48009),$=n(56362),N=class extends r.XQ{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(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const n=t.additional_kwargs?.tool_calls,r=t.tool_calls;null!=n&&n.length>0&&(void 0===r||0===r.length)&&console.warn(["New LangChain packages are available that more efficiently handle","tool calling.\n\nPlease 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!=n&&void 0===r){const[e,r]=(0,A.p1)(n);t.tool_calls=e??[],t.invalid_tool_calls=r??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(void 0!==t.response_metadata&&"output_version"in t.response_metadata&&"v1"===t.response_metadata.output_version&&(t.contentBlocks=t.content,t.content=void 0),void 0!==t.contentBlocks){t.tool_calls&&t.contentBlocks.push(...t.tool_calls.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})));const e=t.contentBlocks.filter(e=>"tool_call"===e.type).filter(e=>!t.tool_calls?.some(t=>t.id===e.id&&t.name===e.name));e.length>0&&(t.tool_calls=e.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}}super(t),"string"!=typeof t&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){const e=O(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const t=this.tool_calls.filter(t=>!e.some(e=>e.id===t.id&&e.name===t.name));e.push(...t.map(e=>({type:"tool_call",id:e.id,name:e.name,args:e.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}};function j(e){return"ai"===e._getType()}function C(e){return"ai"===e._getType()}var R=class extends r.gj{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if("string"==typeof e||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(void 0===e.tool_call_chunks||0===e.tool_call_chunks.length)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0};else{const n=(0,$.oK)(e.tool_call_chunks??[]);t={...e,tool_call_chunks:n.tool_call_chunks,tool_calls:n.tool_calls,invalid_tool_calls:n.invalid_tool_calls,usage_metadata:void 0!==e.usage_metadata?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&"v1"===this.response_metadata.output_version)return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&"string"==typeof this.response_metadata.model_provider){const e=O(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&"string"!=typeof this.content){const t=this.content.filter(e=>"tool_call"===e.type).map(e=>e.id);for(const n of this.tool_calls)n.id&&!t.includes(n.id)&&e.push({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:(0,r._I)(this.content,e.content),additional_kwargs:(0,r.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,T.Z)(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(void 0!==this.tool_call_chunks||void 0!==e.tool_call_chunks){const n=(0,r.Vt)(this.tool_call_chunks,e.tool_call_chunks);void 0!==n&&n.length>0&&(t.tool_call_chunks=n)}if(void 0!==this.tool_calls||void 0!==e.tool_calls){const n=(0,r.Vt)(this.tool_calls,e.tool_calls);void 0!==n&&n.length>0&&(t.tool_calls=n)}return void 0===this.usage_metadata&&void 0===e.usage_metadata||(t.usage_metadata=(0,T.n)(this.usage_metadata,e.usage_metadata)),new(0,this.constructor)(t)}static isInstance(e){return super.isInstance(e)&&"ai"===e.type}}},15282(e,t,n){n.d(t,{XQ:()=>p,gj:()=>E,xE:()=>m,dp:()=>x,ns:()=>g,Vt:()=>w,F7:()=>b,Iv:()=>h,ny:()=>I,AJ:()=>k,Ao:()=>f,_I:()=>l});var r=n(98749),a=n(53813),i=n(99221),s=n(37453),o=n(33927),c=n(54400);const d=Symbol.for("langchain.message");function u(e){return Array.isArray(e)?e:"string"==typeof e?""===e?[]:[{type:"text",text:e}]:null==e?[]:[e]}function l(e,t){if("string"==typeof e)return""===e?t:"string"==typeof t?e+t:Array.isArray(t)&&0===t.length?e:Array.isArray(t)&&t.some(e=>(0,a.Fz)(e))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t];if(Array.isArray(t)){const n=u(e);return w(n,t)??[...n,...t]}return""===t?e:Array.isArray(e)&&e.some(e=>(0,a.Fz)(e))?[...e,{type:"file",source_type:"text",text:t}]:[...u(e),{type:"text",text:t}]}function h(e,t){return"error"===e||"error"===t?"error":"success"}var p=class extends r.yL{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[d]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t="string"==typeof e||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,void 0===t.content&&void 0!==t.contentBlocks?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):void 0!==t.content?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return"string"==typeof this.content?this.content:Array.isArray(this.content)?this.content.map(e=>"string"==typeof e?e:"text"===e.type?e.text:"").join(""):""}get contentBlocks(){const e="string"==typeof this.content?[{type:"text",text:this.content}]:this.content;return[s.Tn,o.T,i.a].reduce((e,t)=>t(e),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return"object"==typeof e&&null!==e&&d in e&&!0===e[d]&&(0,c.K)(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(null===e)return this;const t=(n=this._printableFields,r=Math.max(4,e),JSON.stringify(function e(t,n){if("object"!=typeof t||null==t)return t;if(n>=r)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map(t=>e(t,n+1));const a={};for(const r of Object.keys(t))a[r]=e(t[r],n+1);return a}(n,0),null,2));var n,r;return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return function(e,t="pretty"){return"pretty"===t?function(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),a="=".repeat(r),i=n.length%2==0?a:`${a}=`;if(t.push(`${a}${n}${i}`),"ai"===e.type){const n=e;if(n.tool_calls&&n.tool_calls.length>0){t.push("Tool Calls:");for(const e of n.tool_calls){t.push(` ${e.name} (${e.id})`),t.push(` Call ID: ${e.id}`),t.push(" Args:");for(const[n,r]of Object.entries(e.args))t.push(` ${n}: ${"object"==typeof r?JSON.stringify(r):r}`)}}}if("tool"===e.type){const n=e;n.name&&t.push(`Name: ${n.name}`)}return"string"==typeof e.content&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join("\n")}(e):JSON.stringify(e)}(this,e)}};function f(e){return Array.isArray(e)&&e.every(e=>"number"==typeof e.index)}const m=["index","created","timestamp"];function g(e,t,n){const r=n?.ignoreKeys??m;if(null==e&&null==t)return;if(null==e||null==t)return e??t;const a={...e};for(const[e,i]of Object.entries(t))if(null==a[e])a[e]=i;else{if(null==i)continue;if(typeof a[e]!=typeof i||Array.isArray(a[e])!==Array.isArray(i))throw new Error(`field[${e}] already exists in the message chunk, but with a different type.`);if("string"==typeof a[e]){if("type"===e)continue;if(["id","name","output_version","model_provider"].includes(e))i&&(a[e]=i);else{if(r.includes(e))continue;a[e]+=i}}else if("number"==typeof a[e]){if(r.includes(e))continue;a[e]=a[e]+i}else if("object"!=typeof a[e]||Array.isArray(a[e]))if(Array.isArray(a[e]))a[e]=w(a[e],i,n);else{if(a[e]===i)continue;console.warn(`field[${e}] already exists in this message chunk and value has unsupported type.`)}else a[e]=g(a[e],i,n)}return a}function y(e){return"object"==typeof e&&null!==e&&"index"in e&&("number"==typeof(t=e.index)||"string"==typeof t);var t}function _(e){if("object"!=typeof e||null===e)return!1;if(!("id"in e))return!1;const t=e.id;return null!=t&&""!==t}function v(e,t){const n=y(t),r=_(t);return n||r?e.findIndex(e=>{const a=y(e),i=_(e);return n&&a?!(e.index!==t.index||i&&r&&e.id!==t.id):!(n||a||!r||!i)&&e.id===t.id}):-1}function w(e,t,n){if(null!=e||null!=t){if(null==e||null==t)return e||t;{const r=[...e];for(const e of t){const t=v(r,e);if(-1!==t)r[t]=g(r[t],e,n);else{if("object"==typeof e&&null!==e&&"text"in e&&""===e.text)continue;r.push(e)}}return r}}}function b(e,t,n){if(null!=e||null!=t){if(null==e||null==t)return e??t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.\nLeft ${typeof e}\nRight ${typeof t}`);if("string"==typeof e&&"string"==typeof t)return e+t;if(Array.isArray(e)&&Array.isArray(t))return w(e,t,n);if("object"==typeof e&&"object"==typeof t)return g(e,t,n);if(e===t)return e;throw new Error(`Can not merge objects of different types.\nLeft ${e}\nRight ${t}`)}}var E=class e extends p{static isInstance(t){if(!super.isInstance(t))return!1;let n=Object.getPrototypeOf(t);for(;null!==n;){if(n===e.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function x(e){return"string"==typeof e.role}function I(e){return"function"==typeof e?._getType}function k(e){return E.isInstance(e)}},99221(e,t,n){n.d(t,{B:()=>c,a:()=>s});var r=n(69860);function a(e){if("char_location"===e.type&&(0,r.vQ)(e.document_title)&&(0,r.jM)(e.start_char_index)&&(0,r.jM)(e.end_char_index)&&(0,r.vQ)(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:r,cited_text:a,...i}=e;return{...i,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:r,citedText:a}}if("page_location"===e.type&&(0,r.vQ)(e.document_title)&&(0,r.jM)(e.start_page_number)&&(0,r.jM)(e.end_page_number)&&(0,r.vQ)(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:r,cited_text:a,...i}=e;return{...i,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:r,citedText:a}}if("content_block_location"===e.type&&(0,r.vQ)(e.document_title)&&(0,r.jM)(e.start_block_index)&&(0,r.jM)(e.end_block_index)&&(0,r.vQ)(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:r,cited_text:a,...i}=e;return{...i,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:r,citedText:a}}if("web_search_result_location"===e.type&&(0,r.vQ)(e.url)&&(0,r.vQ)(e.title)&&(0,r.vQ)(e.encrypted_index)&&(0,r.vQ)(e.cited_text)){const{url:t,title:n,encrypted_index:r,cited_text:a,...i}=e;return{...i,type:"citation",source:"url",url:t,title:n,startIndex:Number(r),endIndex:Number(r),citedText:a}}if("search_result_location"===e.type&&(0,r.vQ)(e.source)&&(0,r.vQ)(e.title)&&(0,r.jM)(e.start_block_index)&&(0,r.jM)(e.end_block_index)&&(0,r.vQ)(e.cited_text)){const{source:t,title:n,start_block_index:r,end_block_index:a,cited_text:i,...s}=e;return{...s,type:"citation",source:"search",url:t,title:n??void 0,startIndex:r,endIndex:a,citedText:i}}}function i(e){if((0,r.MP)(e,"document")&&(0,r.nD)(e.source)&&"type"in e.source){if("base64"===e.source.type&&(0,r.vQ)(e.source.media_type)&&(0,r.vQ)(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if("url"===e.source.type&&(0,r.vQ)(e.source.url))return{type:"file",url:e.source.url};if("file"===e.source.type&&(0,r.vQ)(e.source.file_id))return{type:"file",fileId:e.source.file_id};if("text"===e.source.type&&(0,r.vQ)(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if((0,r.MP)(e,"image")&&(0,r.nD)(e.source)&&"type"in e.source){if("base64"===e.source.type&&(0,r.vQ)(e.source.media_type)&&(0,r.vQ)(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if("url"===e.source.type&&(0,r.vQ)(e.source.url))return{type:"image",url:e.source.url};if("file"===e.source.type&&(0,r.vQ)(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function s(e){return Array.from(function*(){for(const t of e){const e=i(t);e?yield e:yield t}}())}function o(e){return Array.from(function*(){const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const n of t){if((0,r.MP)(n,"text")&&(0,r.vQ)(n.text)){const{text:e,citations:t,...i}=n;if((0,r.V3)(t)&&t.length){const n=t.reduce((e,t)=>{const n=a(t);return n?[...e,n]:e},[]);yield{...i,type:"text",text:e,annotations:n};continue}yield{...i,type:"text",text:e};continue}if((0,r.MP)(n,"thinking")&&(0,r.vQ)(n.thinking)){const{thinking:e,signature:t,...r}=n;yield{...r,type:"reasoning",reasoning:e,signature:t};continue}if((0,r.MP)(n,"redacted_thinking"))yield{type:"non_standard",value:n};else if((0,r.MP)(n,"tool_use")&&(0,r.vQ)(n.name)&&(0,r.vQ)(n.id))yield{type:"tool_call",id:n.id,name:n.name,args:n.input};else{if((0,r.MP)(n,"input_json_delta")){if(d(e)&&e.tool_call_chunks?.length){const t=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args,index:t.index};continue}}else if((0,r.MP)(n,"server_tool_use")&&(0,r.vQ)(n.name)&&(0,r.vQ)(n.id)){const{name:e,id:t}=n;if("web_search"===e){yield{id:t,type:"server_tool_call",name:"web_search",args:{query:(0,r.iD)(()=>{if("string"==typeof n.input)return n.input;if((0,r.nD)(n.input)&&(0,r.vQ)(n.input.query))return n.input.query;if((0,r.vQ)(n.partial_json)){const e=(0,r.NS)(n.partial_json);if(e?.query)return e.query}return""})}};continue}if("code_execution"===n.name){yield{id:t,type:"server_tool_call",name:"code_execution",args:{code:(0,r.iD)(()=>{if("string"==typeof n.input)return n.input;if((0,r.nD)(n.input)&&(0,r.vQ)(n.input.code))return n.input.code;if((0,r.vQ)(n.partial_json)){const e=(0,r.NS)(n.partial_json);if(e?.code)return e.code}return""})}};continue}}else{if((0,r.MP)(n,"web_search_tool_result")&&(0,r.vQ)(n.tool_use_id)&&(0,r.V3)(n.content)){const{content:e,tool_use_id:t}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:t,status:"success",output:{urls:e.reduce((e,t)=>(0,r.MP)(t,"web_search_result")?[...e,t.url]:e,[])}};continue}if((0,r.MP)(n,"code_execution_tool_result")&&(0,r.vQ)(n.tool_use_id)&&(0,r.nD)(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}if((0,r.MP)(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}if((0,r.MP)(n,"mcp_tool_result")&&(0,r.vQ)(n.tool_use_id)&&(0,r.nD)(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}if((0,r.MP)(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}if((0,r.MP)(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}if((0,r.MP)(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}{const e=i(n);if(e){yield e;continue}}}yield{type:"non_standard",value:n}}}}())}const c={translateContent:o,translateContentChunk:o};function d(e){return"function"==typeof e?._getType&&"function"==typeof e.concat&&"ai"===e._getType()}},37453(e,t,n){n.d(t,{C4:()=>o,Tn:()=>s,jk:()=>c});var r=n(53813),a=n(69860);function i(e){return(0,r.W)(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:(0,r.cJ)(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:(0,r.oe)(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function s(e){return e.map(i)}function o(e){return!(!(0,a.MP)(e,"image_url")||!(0,a.nD)(e.image_url))||!(!(0,a.MP)(e,"input_audio")||!(0,a.nD)(e.input_audio))||!(!(0,a.MP)(e,"file")||!(0,a.nD)(e.file))}function c(e){if((0,a.MP)(e,"image_url")&&(0,a.nD)(e.image_url)&&(0,a.vQ)(e.image_url.url)){const t=(0,r.Q7)({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}if((0,a.MP)(e,"input_audio")&&(0,a.nD)(e.input_audio)&&(0,a.vQ)(e.input_audio.data)&&(0,a.vQ)(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if((0,a.MP)(e,"file")&&(0,a.nD)(e.file)&&(0,a.vQ)(e.file.data)){const t=(0,r.Q7)({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if((0,a.vQ)(e.file.file_id))return{type:"file",fileId:e.file.file_id}}return e}},33927(e,t,n){n.d(t,{F:()=>c,T:()=>i});var r=n(69860),a=n(37453);function i(e){const t=[];for(const n of e)(0,a.C4)(n)?t.push((0,a.jk)(n)):t.push(n);return t}function s(e){if("url_citation"===e.type){const{url:t,title:n,start_index:r,end_index:a}=e;return{type:"citation",url:t,title:n,startIndex:r,endIndex:a}}if("file_citation"===e.type){const{file_id:t,filename:n,index:r}=e;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:t}}return e}function o(e){return Array.from(function*(){(0,r.nD)(e.additional_kwargs?.reasoning)&&(0,r.V3)(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((e,t)=>(0,r.nD)(t)&&(0,r.vQ)(t.text)?`${e}${t.text}`:e,"")});const t="string"==typeof e.content?[{type:"text",text:e.content}]:e.content;for(const e of t)if((0,r.MP)(e,"text")){const{text:t,annotations:n,phase:a,extras:i,...o}=e,c=(0,r.nD)(i)?{...i}:{};(0,r.vQ)(a)&&(c.phase=a);const d=Object.keys(c).length>0?{extras:c}:{};Array.isArray(n)?yield{...o,...d,type:"text",text:String(t),annotations:n.map(s)}:yield{...o,...d,type:"text",text:String(t)}}for(const t of e.tool_calls??[])yield{type:"tool_call",id:t.id,name:t.name,args:t.args};if((0,r.nD)(e.additional_kwargs)&&(0,r.V3)(e.additional_kwargs.tool_outputs))for(const t of e.additional_kwargs.tool_outputs){if((0,r.MP)(t,"web_search_call")){const e={};if((0,r.nD)(t.action)&&(0,r.vQ)(t.action.query)&&(e.query=t.action.query),yield{id:t.id,type:"server_tool_call",name:"web_search",args:e},"completed"===t.status||"failed"===t.status){const e={};(0,r.nD)(t.action)&&(e.action=t.action),yield{type:"server_tool_call_result",toolCallId:(0,r.vQ)(t.id)?t.id:"",status:"completed"===t.status?"success":"error",output:e}}continue}if((0,r.MP)(t,"file_search_call"))yield{id:t.id,type:"server_tool_call",name:"file_search",args:{queries:(0,r.V3)(t.queries)?t.queries:[]}},"completed"!==t.status&&"failed"!==t.status||(yield{type:"server_tool_call_result",toolCallId:(0,r.vQ)(t.id)?t.id:"",status:"completed"===t.status?"success":"error",output:(0,r.V3)(t.results)?{results:t.results}:{}});else if((0,r.MP)(t,"computer_call"))yield{type:"non_standard",value:t};else if((0,r.MP)(t,"code_interpreter_call")){if((0,r.vQ)(t.code)&&(yield{id:t.id,type:"server_tool_call",name:"code_interpreter",args:{code:t.code}}),(0,r.V3)(t.outputs)){const e=(0,r.iD)(()=>{if("in_progress"!==t.status){if("completed"===t.status)return 0;if("incomplete"===t.status)return 127;if("interpreting"!==t.status)return"failed"===t.status?1:void 0}});for(const n of t.outputs)if((0,r.MP)(n,"logs")){yield{type:"server_tool_call_result",toolCallId:t.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:e??0,stderr:[0,void 0].includes(e)?void 0:String(n.logs),stdout:[0,void 0].includes(e)?String(n.logs):void 0}};continue}}}else if((0,r.MP)(t,"mcp_call"))yield{id:t.id,type:"server_tool_call",name:"mcp_call",args:t.input};else if((0,r.MP)(t,"mcp_list_tools"))yield{id:t.id,type:"server_tool_call",name:"mcp_list_tools",args:t.input};else if((0,r.MP)(t,"mcp_approval_request"))yield{type:"non_standard",value:t};else{if((0,r.MP)(t,"tool_search_call")){const e={};(0,r.nD)(t.arguments)&&Object.assign(e,t.arguments);const n={};(0,r.vQ)(t.execution)&&(n.execution=t.execution),(0,r.vQ)(t.status)&&(n.status=t.status),(0,r.vQ)(t.call_id)&&(n.call_id=t.call_id),yield{id:(0,r.vQ)(t.id)?t.id:"",type:"server_tool_call",name:"tool_search",args:e,...Object.keys(n).length>0?{extras:n}:{}};continue}if((0,r.MP)(t,"tool_search_output")){const e={name:"tool_search"};(0,r.vQ)(t.execution)&&(e.execution=t.execution),yield{type:"server_tool_call_result",toolCallId:(0,r.vQ)(t.id)?t.id:"",status:"completed"===t.status?"success":"failed"===t.status?"error":"success",output:{tools:(0,r.V3)(t.tools)?t.tools:[]},extras:e};continue}(0,r.MP)(t,"image_generation_call")?((0,r.vQ)(t.result)&&(yield{type:"image",mimeType:"image/png",data:t.result,id:(0,r.vQ)(t.id)?t.id:void 0,metadata:{status:(0,r.vQ)(t.status)?t.status:void 0}}),yield{type:"non_standard",value:t}):(0,r.nD)(t)&&(yield{type:"non_standard",value:t})}}}())}const c={translateContent:e=>"string"==typeof e.content?function(e){const t=[];"string"==typeof e.content?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...i(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}(e):o(e),translateContentChunk:e=>"string"==typeof e.content?function(e){const t=[];"string"==typeof e.content?e.content.length>0&&t.push({type:"text",text:e.content}):t.push(...i(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}(e):function(e){return Array.from(function*(){yield*o(e);for(const t of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:t.id,name:t.name,args:t.args}}())}(e)}},69860(e,t,n){function r(e,t){return a(e)&&e.type===t}function a(e){return"object"==typeof e&&null!==e}function i(e){return Array.isArray(e)}function s(e){return"string"==typeof e}function o(e){return"number"==typeof e}function c(e){return e instanceof Uint8Array}function d(e){try{return JSON.parse(e)}catch{return}}n.d(t,{MP:()=>r,MS:()=>c,NS:()=>d,V3:()=>i,iD:()=>u,jM:()=>o,nD:()=>a,vQ:()=>s});const u=e=>e()},64301(e,t,n){n.d(t,{XU:()=>i,bU:()=>o,cM:()=>a,kY:()=>s});var r=n(15282),a=class e extends r.XQ{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return e}constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}},i=class extends r.gj{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){("string"==typeof e||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){return new(0,this.constructor)({content:(0,r._I)(this.content,e.content),additional_kwargs:(0,r.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,r.ns)(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"generic"===e.type}get _printableFields(){return{...super._printableFields,role:this.role}}};function s(e){return"generic"===e._getType()}function o(e){return"generic"===e._getType()}},53813(e,t,n){function r(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"source_type"in e&&("url"===e.source_type||"base64"===e.source_type||"text"===e.source_type||"id"===e.source_type)}function a(e){return r(e)&&"url"===e.source_type&&"url"in e&&"string"==typeof e.url}function i(e){return r(e)&&"base64"===e.source_type&&"data"in e&&"string"==typeof e.data}function s(e){return r(e)&&"text"===e.source_type&&"text"in e&&"string"==typeof e.text}function o(e){return r(e)&&"id"===e.source_type&&"id"in e&&"string"==typeof e.id}function c(e){if(r(e)){if("url"===e.source_type)return{type:"image_url",image_url:{url:e.url}};if("base64"===e.source_type){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function d(e){const t=e.split(";")[0].split("/");if(2!==t.length)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),r=t[1].trim();if(""===n||""===r)throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const a={};for(const t of e.split(";").slice(1)){const n=t.split("=");if(2!==n.length)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const r=n[0].trim(),i=n[1].trim();if(""===r)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);a[r]=i}return{type:n,subtype:r,parameters:a}}function u({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n)return r=n[1].toLowerCase(),{mime_type:r,data:t?Uint8Array.from(atob(n[2]),e=>e.charCodeAt(0)):n[2]}}function l(e,t){if("text"===e.type){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if("image"===e.type){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if("audio"===e.type){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if("file"===e.type){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}n.d(t,{Ac:()=>s,Ej:()=>d,Fz:()=>r,Q7:()=>u,Vi:()=>c,W:()=>a,cJ:()=>i,oe:()=>o,up:()=>l})},8675(e,t,n){n.d(t,{AP:()=>s,FK:()=>i,mg:()=>a,vl:()=>o});var r=n(15282),a=class extends r.XQ{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},i=class extends r.gj{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){return new(0,this.constructor)({content:(0,r._I)(this.content,e.content),additional_kwargs:(0,r.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,r.ns)(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function s(e){return"function"===e._getType()}function o(e){return"function"===e._getType()}},85454(e,t,n){n.d(t,{GZ:()=>o,a7:()=>i,di:()=>s,xc:()=>a});var r=n(15282),a=class extends r.XQ{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&"human"===e.type}},i=class extends r.gj{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){return new(0,this.constructor)({content:(0,r._I)(this.content,e.content),additional_kwargs:(0,r.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,r.ns)(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"human"===e.type}};function s(e){return"human"===e.getType()}function o(e){return"human"===e.getType()}},22355(e,t,n){n.d(t,{Od:()=>s.Od,H:()=>s.H,cM:()=>o.cM,xc:()=>d.xc,tn:()=>l.tn,up:()=>r.up,KX:()=>s.KX,ny:()=>a.ny,Fz:()=>r.Fz,wk:()=>i.wk,Q7:()=>r.Q7}),n(66630);var r=n(53813),a=(n(54400),n(15282)),i=(n(24658),n(48009)),s=n(23549),o=n(64301),c=n(8675),d=n(85454),u=n(78446),l=n(27974);n(56362),n(41666),d.xc,d.a7,s.Od,s.H,l.tn,l.uU,l.tn,l.uU,i.uf,i.dr,c.mg,c.FK,o.cM,o.XU,u.k,u.k},54400(e,t,n){function r(e){return"object"==typeof e&&null!==e&&"type"in e&&"content"in e&&("string"==typeof e.content||Array.isArray(e.content))}n.d(t,{K:()=>r})},24658(e,t,n){n.d(t,{Z:()=>a,n:()=>c});var r=n(15282);function a(e,t){return(0,r.ns)(e,t)??{}}function i(e,t){const n={};return void 0===e?.audio&&void 0===t?.audio||(n.audio=(e?.audio??0)+(t?.audio??0)),void 0===e?.image&&void 0===t?.image||(n.image=(e?.image??0)+(t?.image??0)),void 0===e?.video&&void 0===t?.video||(n.video=(e?.video??0)+(t?.video??0)),void 0===e?.document&&void 0===t?.document||(n.document=(e?.document??0)+(t?.document??0)),void 0===e?.text&&void 0===t?.text||(n.text=(e?.text??0)+(t?.text??0)),n}function s(e,t){const n={...i(e,t)};return void 0===e?.cache_read&&void 0===t?.cache_read||(n.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),void 0===e?.cache_creation&&void 0===t?.cache_creation||(n.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),n}function o(e,t){const n={...i(e,t)};return void 0===e?.reasoning&&void 0===t?.reasoning||(n.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),n}function c(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:s(e?.input_token_details,t?.input_token_details),output_token_details:o(e?.output_token_details,t?.output_token_details)}}},78446(e,t,n){n.d(t,{k:()=>a});var r=n(15282),a=class extends r.XQ{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&"remove"===e.type}}},27974(e,t,n){n.d(t,{UF:()=>o,X4:()=>s,tn:()=>a,uU:()=>i});var r=n(15282),a=class e extends r.XQ{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}concat(t){if("string"==typeof t)return new e({content:(0,r._I)(this.content,t),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(e.isInstance(t))return new e({content:(0,r._I)(this.content,t.content),additional_kwargs:{...this.additional_kwargs,...t.additional_kwargs},response_metadata:{...this.response_metadata,...t.response_metadata},id:this.id??t.id,name:this.name??t.name});throw new Error("Unexpected chunk type for system message")}static isInstance(e){return super.isInstance(e)&&"system"===e.type}},i=class extends r.gj{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){return new(0,this.constructor)({content:(0,r._I)(this.content,e.content),additional_kwargs:(0,r.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,r.ns)(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&"system"===e.type}};function s(e){return"system"===e._getType()}function o(e){return"system"===e._getType()}},48009(e,t,n){n.d(t,{P:()=>d,dr:()=>s,fK:()=>a,p1:()=>o,uf:()=>i,wk:()=>c}),n(66630);var r=n(15282);function a(e){return null!=e&&"object"==typeof e&&"lc_direct_tool_output"in e&&!0===e.lc_direct_tool_output}var i=class extends r.XQ{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,n){const r="string"==typeof e||Array.isArray(e)?{content:e,name:n,tool_call_id:t}:e;super(r),this.tool_call_id=r.tool_call_id,this.artifact=r.artifact,this.status=r.status,this.metadata=r.metadata}static isInstance(e){return super.isInstance(e)&&"tool"===e.type}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},s=class extends r.gj{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){return new(0,this.constructor)({content:(0,r._I)(this.content,e.content),additional_kwargs:(0,r.ns)(this.additional_kwargs,e.additional_kwargs),response_metadata:(0,r.ns)(this.response_metadata,e.response_metadata),artifact:(0,r.F7)(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:(0,r.Iv)(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function o(e){const t=[],n=[];for(const r of e)if(r.function){const e=r.function.name;try{const n=JSON.parse(r.function.arguments);t.push({name:e||"",args:n||{},id:r.id})}catch{n.push({name:e,args:r.function.arguments,id:r.id,error:"Malformed args."})}}return[t,n]}function c(e){return"object"==typeof e&&null!==e&&"getType"in e&&"function"==typeof e.getType&&"tool"===e.getType()}function d(e){return"tool"===e._getType()}},56362(e,t,n){n.d(t,{Js:()=>E,K0:()=>y,Pz:()=>w,Sw:()=>v,iD:()=>f,ih:()=>x,oK:()=>I,rf:()=>b});var r=n(64033),a=n(20199),i=n(30780),s=n(15282),o=n(48009),c=n(23549),d=n(64301),u=n(8675),l=n(85454),h=n(78446),p=n(27974);const f=e=>e();function m(e){return(0,a.Ky)(e)?e:"string"==typeof e.id&&"function"===e.type&&"object"==typeof e.function&&null!==e.function&&"arguments"in e.function&&"string"==typeof e.function.arguments&&"name"in e.function&&"string"==typeof e.function.name?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function g(e){let t,n;if("object"==typeof(a=e)&&null!=a&&1===a.lc&&Array.isArray(a.id)&&null!=a.kwargs&&"object"==typeof a.kwargs){const r=e.id.at(-1);t="HumanMessage"===r||"HumanMessageChunk"===r?"user":"AIMessage"===r||"AIMessageChunk"===r?"assistant":"SystemMessage"===r||"SystemMessageChunk"===r?"system":"FunctionMessage"===r||"FunctionMessageChunk"===r?"function":"ToolMessage"===r||"ToolMessageChunk"===r?"tool":"unknown",n=e.kwargs}else{const{type:r,...a}=e;t=r,n=a}var a;if("human"===t||"user"===t)return new l.xc(n);if("ai"===t||"assistant"===t){const{tool_calls:e,...t}=n;if(!Array.isArray(e))return new c.Od(n);const r=e.map(m);return new c.Od({...t,tool_calls:r})}if("system"===t)return new p.tn(n);if("developer"===t)return new p.tn({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if("tool"===t&&"tool_call_id"in n)return new o.uf({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if("remove"===t&&"id"in n&&"string"==typeof n.id)return new h.k({...n,id:n.id});throw(0,r.Yt)(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}function y(e){if("string"==typeof e)return new l.xc(e);if((0,s.ny)(e))return e;if(Array.isArray(e)){const[t,n]=e;return g({type:t,content:n})}if((0,s.dp)(e)){const{role:t,...n}=e;return g({...n,type:t})}return g(e)}function _(e){if("string"==typeof e)return e;switch(e.type){case"text":return e.text??"";case"text-plain":return e.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return e.type?`[${e.type}]`:""}}function v(e,t="Human",n="AI"){const r=[];for(const a of e){let e;if("human"===a.type)e=t;else if("ai"===a.type)e=n;else if("system"===a.type)e="System";else if("tool"===a.type)e="Tool";else{if("generic"!==a.type)throw new Error(`Got unsupported message type: ${a.type}`);e=a.role}let i=`${e}: ${a.name?`${a.name}, `:""}${"string"==typeof a.content?a.content:Array.isArray(a.content)?a.content.map(_).filter(Boolean).join(""):""}`;if("ai"===a.type){const e=a;e.tool_calls&&e.tool_calls.length>0?i+=JSON.stringify(e.tool_calls):e.additional_kwargs&&"function_call"in e.additional_kwargs&&(i+=JSON.stringify(e.additional_kwargs.function_call))}r.push(i)}return r.join("\n")}function w(e){const t=function(e){if(void 0!==e.data)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}(e);switch(t.type){case"human":return new l.xc(t.data);case"ai":return new c.Od(t.data);case"system":return new p.tn(t.data);case"function":if(void 0===t.data.name)throw new Error("Name must be defined for function messages");return new u.mg(t.data);case"tool":if(void 0===t.data.tool_call_id)throw new Error("Tool call ID must be defined for tool messages");return new o.uf(t.data);case"generic":if(void 0===t.data.role)throw new Error("Role must be defined for chat messages");return new d.cM(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function b(e){return e.map(w)}function E(e){return e.map(e=>e.toDict())}function x(e){const t=e._getType();if("human"===t)return new l.a7({...e});if("ai"===t){let t={...e};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(e=>({...e,type:"tool_call_chunk",index:void 0,args:JSON.stringify(e.args)}))}),new c.H({...t})}if("system"===t)return new p.uU({...e});if("function"===t)return new u.FK({...e});if(d.cM.isInstance(e))return new d.XU({...e});throw new Error("Unknown message type.")}function I(e){const t=e.reduce((e,t)=>{const n=e.findIndex(([e])=>"id"in t&&t.id&&"index"in t&&void 0!==t.index?t.id===e.id&&t.index===e.index:"id"in t&&t.id?t.id===e.id:"index"in t&&void 0!==t.index&&t.index===e.index);return-1!==n?e[n].push(t):e.push([t]),e},[]),n=[],r=[];for(const e of t){let t=null;const a=e[0]?.name??"",s=e.map(e=>e.args||"").join("").trim(),o=s.length?s:"{}",c=e[0]?.id;try{if(t=(0,i.d)(o),!c||null===t||"object"!=typeof t||Array.isArray(t))throw new Error("Malformed tool call chunk args.");n.push({name:a,args:t,id:c,type:"tool_call"})}catch{r.push({name:a,args:o,id:c,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:e,tool_calls:n,invalid_tool_calls:r}}},68028(e,t,n){n.d(t,{Cf:()=>i,SP:()=>r,mu:()=>a});const r="__run";var a=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},i=class e extends a{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}}},41666(e,t,n){n.d(t,{YN:()=>V,B2:()=>se,fJ:()=>W,Vi:()=>K,jY:()=>ne,ck:()=>ee,Pq:()=>re,Fm:()=>oe,AO:()=>Y,zZ:()=>X,pG:()=>ce,lH:()=>ae,GH:()=>Q,Bp:()=>ie});var r=n(20199),a=n(98749),i=n(51415),s=(n(98521),n(10765)),o=n(69830),c=n(50058),d=(n(66630),n(23549)),u=n(11590),l=n(52191),h=(n(27787),class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=(0,l.X6)({},t);return new p({ops:t,state:n[n.length-1].newDocument})}}),p=class e extends h{state;constructor(e){super(e),this.state=e.state}concat(t){const n=this.ops.concat(t.ops),r=(0,l.X6)(this.state,t.ops);return new e({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){const n=(0,l.X6)({},t.ops);return new e({ops:t.ops,state:n[n.length-1].newDocument})}};const f=e=>"log_stream_tracer"===e.name;async function m(e,t){if("original"===t)throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=e;return["retriever","llm","prompt"].includes(e.run_type)?n:1!==Object.keys(n).length||""!==n?.input?n.input:void 0}async function g(e,t){const{outputs:n}=e;return"original"===t||["retriever","llm","prompt"].includes(e.run_type)?n:void 0!==n&&1===Object.keys(n).length&&void 0!==n?.output?n.output:n}var y=class extends u.JS{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=c.bO.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let n=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(n=n||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(n=n||this.includeTypes.includes(e.run_type)),void 0!==this.includeTags&&(n=n||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(n=n&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(n=n&&!this.excludeTypes.includes(e.run_type)),void 0!==this.excludeTags&&(n=n&&t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){for await(const n of t){if(e!==this.rootId){const t=this.keyMapByRunId[e];t&&await this.writer.write(new h({ops:[{op:"add",path:`/logs/${t}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(void 0===this.rootId&&(this.rootId=e.id,await this.writer.write(new h({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;void 0===this.counterMapByRunName[e.name]&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=1===t?e.name:`${e.name}:${t}`;const n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};"streaming_events"===this._schemaFormat&&(n.inputs=await m(e,this._schemaFormat)),await this.writer.write(new h({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(void 0===t)return;const n=[];"streaming_events"===this._schemaFormat&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await m(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await g(e,this._schemaFormat)}),void 0!==e.end_time&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const r=new h({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){const t=new h({ops:[{op:"replace",path:"/final_output",value:await g(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){const r=this.keyMapByRunId[e.id];if(void 0===r)return;let a;var i;void 0!==e.inputs.messages?(i=n?.chunk,a=void 0!==i&&void 0!==i.message?n?.chunk:new d.H({id:`run-${e.id}`,content:t})):a=t;const s=new h({ops:[{op:"add",path:`/logs/${r}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(s)}},_=n(68028);function v({name:e,serialized:t}){return void 0!==e?e:void 0!==t?.name?t.name:void 0!==t?.id&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const w=e=>"event_stream_tracer"===e.name;var b=class extends u.JS{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(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=c.bO.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let n=void 0===this.includeNames&&void 0===this.includeTags&&void 0===this.includeTypes;return void 0!==this.includeNames&&(n=n||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(n=n||this.includeTypes.includes(e.runType)),void 0!==this.includeTags&&(n=n||void 0!==t.find(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(n=n&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(n=n&&!this.excludeTypes.includes(e.runType)),void 0!==this.excludeTags&&(n=n&&t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){const n=await t.next();if(n.done)return;const r=this.runInfoMap.get(e);if(void 0===r)return void(yield n.value);function a(e,t){return"llm"===e&&"string"==typeof t?new _.mu({text:t}):t}let i=this.tappedPromises.get(e);if(void 0===i){let s;i=new Promise(e=>{s=e}),this.tappedPromises.set(e,i);try{const i={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...i,data:{chunk:a(r.runType,n.value)}},r),yield n.value;for await(const e of t)"tool"!==r.runType&&"retriever"!==r.runType&&await this.send({...i,data:{chunk:a(r.runType,e)}},r),yield e}finally{s?.()}}else{yield n.value;for await(const e of t)yield e}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const n=this.tappedPromises.get(e.run_id);void 0!==n?n.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=v(e),n=void 0!==e.inputs.messages?"chat_model":"llm",r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);const a=`on_${n}_start`;await this.send({event:a,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){const r=this.runInfoMap.get(e.id);let a,i;if(void 0===r)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(1!==this.runInfoMap.size){if("chat_model"===r.runType)i="on_chat_model_stream",a=void 0===n?.chunk?new d.H({content:t,id:`run-${e.id}`}):n.chunk.message;else{if("llm"!==r.runType)throw new Error(`Unexpected run type ${r.runType}`);i="on_llm_stream",a=void 0===n?.chunk?new _.mu({text:t}):n.chunk}await this.send({event:i,data:{chunk:a},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);let n;if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const r=e.outputs?.generations;let a;if("chat_model"===t.runType){for(const e of r??[]){if(void 0!==a)break;a=e[0]?.message}n="on_chat_model_end"}else{if("llm"!==t.runType)throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);a={generations:r?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n="on_llm_end"}await this.sendEndEvent({event:n,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=v(e),n=e.run_type??"chain",r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let a={};""===e.inputs.input&&1===Object.keys(e.inputs).length?(a={},r.inputs={}):void 0!==e.inputs.input?(a.input=e.inputs.input,r.inputs=e.inputs.input):(a.input=e.inputs,r.inputs=e.inputs),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},a={output:e.outputs?.output??e.outputs,input:r};r.input&&1===Object.keys(r).length&&(a.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:a,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=v(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const n=void 0===e.outputs?.output?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(void 0===t.inputs)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=v(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},n)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),void 0===t)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){const r=this.runInfoMap.get(n);if(void 0===r)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},E=n(75621),x=n(99624),I=class extends u.JS{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function k(e){return!!e&&e.lc_runnable}var S=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=void 0===this.includeNames&&void 0===this.includeTypes&&void 0===this.includeTags;const r=e.tags??[];return void 0!==this.includeNames&&(n=n||this.includeNames.includes(e.name)),void 0!==this.includeTypes&&(n=n||this.includeTypes.includes(t)),void 0!==this.includeTags&&(n=n||r.some(e=>this.includeTags?.includes(e))),void 0!==this.excludeNames&&(n=n&&!this.excludeNames.includes(e.name)),void 0!==this.excludeTypes&&(n=n&&!this.excludeTypes.includes(t)),void 0!==this.excludeTags&&(n=n&&r.every(e=>!this.excludeTags?.includes(e))),n}},O=n(92535);function T(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const A=["*","_","`"];var $=n(38727);const N=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,j=function(e){return"string"==typeof e&&N.test(e)},C={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};var R=n(62187),P=n(71331);function L(e,t){if(void 0!==e&&!j(e))return e;if(!k(t))return t.name??"UnknownSchema";try{let e=t.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch{return t.getName()}}function M(e){return k(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...(0,$.PF)(e.data.schema),title:e.data.name}}}var z=class e{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=j(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...M(t)})),edges:this.edges.map(t=>{const n={source:e[t.source],target:e[t.target]};return void 0!==t.data&&(n.data=t.data),void 0!==t.conditional&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(void 0!==t&&void 0!==this.nodes[t])throw new Error(`Node with id ${t} already exists`);const r=t??function(e,t,n){if(C.randomUUID&&!t&&!e)return C.randomUUID();const r=(e=e||{}).random??e.rng?.()??(0,R.A)();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return(0,P.k)(r)}(),a={id:r,data:e,name:L(t,e),metadata:n};return this.nodes[r]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,r){if(void 0===this.nodes[e.id])throw new Error(`Source node ${e.id} not in graph`);if(void 0===this.nodes[t.id])throw new Error(`Target node ${t.id} not in graph`);const a={source:e.id,target:t.id,data:n,conditional:r};return this.edges.push(a),a}firstNode(){return D(this)}lastNode(){return U(this)}extend(e,t=""){let n=t;Object.values(e.nodes).map(e=>e.id).every(j)&&(n="");const r=e=>n?`${n}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[r(e)]={...t,id:r(e)}});const a=e.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}));this.edges=[...this.edges,...a];const i=e.firstNode(),s=e.lastNode();return[i?{id:r(i.id),data:i.data}:void 0,s?{id:r(s.id),data:s.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&D(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&U(this,[e.id])&&this.removeNode(e)}reid(){const t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),n=new Map;Object.values(t).forEach(e=>{n.set(e,(n.get(e)||0)+1)});const r=e=>{const r=t[e];return j(e)&&1===n.get(r)?r:e};return new e({nodes:Object.fromEntries(Object.entries(this.nodes).map(([e,t])=>[r(e),{...t,id:r(e)}])),edges:this.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:n,nodeColors:r={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=e??{},i=this.reid(),s=i.firstNode(),o=i.lastNode();return function(e,t,n){const{firstNode:r,lastNode:a,nodeColors:i,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{};let d=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%\ngraph TD;\n`:"graph TD;\n";if(s){const t="default",n={[t]:"{0}({1})"};void 0!==r&&(n[r]="{0}([{1}]):::first"),void 0!==a&&(n[a]="{0}([{1}]):::last");for(const[r,a]of Object.entries(e)){const e=a.name.split(":").pop()??"";let i=A.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(a.metadata??{}).length&&(i+=`<hr/><small><em>${Object.entries(a.metadata??{}).map(([e,t])=>`${e} = ${t}`).join("\n")}</em></small>`);const s=(n[r]??n[t]).replace("{0}",T(r)).replace("{1}",i);d+=`\t${s}\n`}}const u={};for(const e of t){const t=e.source.split(":"),n=e.target.split(":"),r=t.filter((e,t)=>e===n[t]).join(":");u[r]||(u[r]=[]),u[r].push(e)}const l=new Set;function h(e,t){const n=1===e.length&&e[0].source===e[0].target;if(t&&!n){const e=t.split(":").pop();if(l.has(t))throw new Error(`Found duplicate subgraph '${e}' at '${t} -- 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.`);l.add(t),d+=`\tsubgraph ${e}\n`}const r=(a=Object.keys(u).filter(e=>e.startsWith(`${t}:`)&&e!==t&&e.split(":").length===t.split(":").length+1),[...a].sort((e,t)=>e.split(":").length-t.split(":").length));var a;for(const e of r)h(u[e],e);for(const t of e){const{source:e,target:n,data:r,conditional:a}=t;let i="";if(void 0!==r){let e=r;const t=e.split(" ");t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},(e,n)=>t.slice(n*c,(n+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),i=a?` -. &nbsp;${e}&nbsp; .-> `:` -- &nbsp;${e}&nbsp; --\x3e `}else i=a?" -.-> ":" --\x3e ";d+=`\t${T(e)}${i}${T(n)};\n`}t&&!n&&(d+="\tend\n")}h(u[""]??[],"");for(const e in u)e.includes(":")||""===e||h(u[e],e);return s&&(d+=function(e){let t="";for(const[n,r]of Object.entries(e))t+=`\tclassDef ${n} ${r};\n`;return t}(i??{})),d}(i.nodes,i.edges,{firstNode:s?.id,lastNode:o?.id,withStyles:t,curveStyle:n,nodeColors:r,wrapLabelNWords:a})}async drawMermaidPng(e){return async function(e,t){let n=t?.backgroundColor??"white";const r=t?.imageType??"png",a=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");void 0!==n&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const i=`https://mermaid.ink/img/${a}?bgColor=${n}&type=${r}`,s=await fetch(i);if(!s.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${s.status}`,`Status text: ${s.statusText}`].join("\n"));return await s.blob()}(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function D(e,t=[]){const n=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),r=[];for(const a of Object.values(e.nodes))t.includes(a.id)||n.has(a.id)||r.push(a);return 1===r.length?r[0]:void 0}function U(e,t=[]){const n=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),r=[];for(const a of Object.values(e.nodes))t.includes(a.id)||n.has(a.id)||r.push(a);return 1===r.length?r[0]:void 0}function F(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.iterator]&&"function"==typeof e.next}function Z(e){return"object"==typeof e&&null!==e&&"function"==typeof e[Symbol.asyncIterator]}function*B(e,t){for(;;){const{value:n,done:r}=i.N.runWithConfig((0,s.DY)(e),t.next.bind(t),!0);if(r)break;yield n}}async function*J(e,t){const n=t[Symbol.asyncIterator]();for(;;){const{value:r,done:a}=await i.N.runWithConfig((0,s.DY)(e),n.next.bind(t),!0);if(a)break;yield r}}var q=n(16675),H=n(63389),G=n(1038);function Q(e,t){return!e||Array.isArray(e)||e instanceof Date||"object"!=typeof e?{[t]:e}:e}var V=class extends a.yL{lc_runnable=!0;name;getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new Y({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new W({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new ae({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(s.ZI);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(e).filter(([e])=>"runId"!==e));return Array.from({length:t},(t,r)=>(0,s.ZI)(0===r?e:n))}return Array.from({length:t},()=>(0,s.ZI)(e))}async batch(e,t,n){const r=this._getOptionsList(t??{},e.length),a=new x.g({maxConcurrency:r[0]?.maxConcurrency??n?.maxConcurrency,onFailedAttempt:e=>{throw e}}),i=e.map((e,t)=>a.call(async()=>{try{return await this.invoke(e,r[t])}catch(e){if(n?.returnExceptions)return e;throw e}}));return Promise.all(i)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=(0,s.ZI)(t),r=new c.Tr({generator:this._streamIterator(e,n),config:n});return await r.setup,c.bO.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=void 0===e?(0,s.ZI)(e):(0,s.ZI)({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){const r=(0,s.ZI)(n),a=await((await(0,s.kJ)(r))?.handleChainStart(this.toJSON(),Q(t,"input"),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName()));let i;delete r.runId;try{i=await(0,o.o)(e.call(this,t,r,a),r.signal)}catch(e){throw await(a?.handleChainError(e)),e}return await(a?.handleChainEnd(Q(i,"output"))),i}async _batchWithConfig(e,t,n,r){const a=this._getOptionsList(n??{},t.length),i=await Promise.all(a.map(s.kJ)),c=await Promise.all(i.map(async(e,n)=>{const r=await(e?.handleChainStart(this.toJSON(),Q(t[n],"input"),a[n].runId,a[n].runType,void 0,void 0,a[n].runName??this.getName()));return delete a[n].runId,r}));let d;try{d=await(0,o.o)(e.call(this,t,a,c,r),a?.[0]?.signal)}catch(e){throw await Promise.all(c.map(t=>t?.handleChainError(e))),e}return await Promise.all(c.map(e=>e?.handleChainEnd(Q(d,"output")))),d}_concatOutputChunks(e,t){return(0,c.xW)(e,t)}async*_transformStreamWithConfig(e,t,n){let r,a,i=!0,o=!0;const d=(0,s.ZI)(n),u=await(0,s.kJ)(d),l=this;let h;try{const n=await(0,c.DS)(t.bind(this),async function*(){for await(const t of e){if(i)if(void 0===r)r=t;else try{r=l._concatOutputChunks(r,t)}catch{r=void 0,i=!1}yield t}}(),async()=>u?.handleChainStart(this.toJSON(),{input:""},d.runId,d.runType,void 0,void 0,d.runName??this.getName(),void 0,{lc_defers_inputs:!0}),d.signal,d);delete d.runId,h=n.setup;const s=h?.handlers.find(w);let p=n.output;void 0!==s&&void 0!==h&&(p=s.tapOutputIterable(h.runId,p));const m=h?.handlers.find(f);void 0!==m&&void 0!==h&&(p=m.tapOutputIterable(h.runId,p));for await(const e of p)if(yield e,o)if(void 0===a)a=e;else try{a=this._concatOutputChunks(a,e)}catch{a=void 0,o=!1}}catch(e){throw await(h?.handleChainError(e,void 0,void 0,void 0,{inputs:Q(r,"input")})),e}await(h?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:Q(r,"input")}))}getGraph(e){const t=new z,n=t.addNode({name:`${this.getName()}Input`,schema:G.z.any()}),r=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:G.z.any()});return t.addEdge(n,r),t.addEdge(r,a),t}pipe(e){return new X({first:this,last:ie(e)})}pick(e){return this.pipe(new oe(e))}assign(e){return this.pipe(new se(new ee({steps:e})))}async*transform(e,t){let n;for await(const t of e)n=void 0===n?t:this._concatOutputChunks(n,t);yield*this._streamIterator(n,(0,s.ZI)(t))}async*streamLog(e,t,n){const r=new y({...n,autoClose:!1,_schemaFormat:"original"}),a=(0,s.ZI)(t);yield*this._streamLog(e,r,a)}async*_streamLog(e,t,n){const{callbacks:r}=n;if(void 0===r)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{const e=r.copy();e.addHandler(t,!0),n.callbacks=e}const a=this.stream(e,n),i=async function(){try{const e=await a;for await(const n of e){const e=new h({ops:[{op:"add",path:"/streamed_output/-",value:n}]});await t.writer.write(e)}}finally{await t.writer.close()}}();try{for await(const e of t)yield e}finally{await i}}streamEvents(e,t,n){let r;if("v1"===t.version)r=this._streamEventsV1(e,t,n);else{if("v2"!==t.version)throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');r=this._streamEventsV2(e,t,n)}return"text/event-stream"===t.encoding?function(e){const t=new TextEncoder,n=new ReadableStream({async start(n){for await(const r of e)n.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(r)}\n\n`));n.enqueue(t.encode("event: end\n\n")),n.close()}});return c.bO.fromReadableStream(n)}(r):c.bO.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){const r=new b({...n,autoClose:!1}),a=(0,s.ZI)(t),i=a.runId??(0,q.A)();a.runId=i;const o=a.callbacks;if(void 0===o)a.callbacks=[r];else if(Array.isArray(o))a.callbacks=o.concat(r);else{const e=o.copy();e.addHandler(r,!0),a.callbacks=e}const c=new AbortController,d=this,u=async function(){let t;try{if(a.signal)if("any"in AbortSignal)t=AbortSignal.any([c.signal,a.signal]);else{const e=new AbortController;a.signal.addEventListener("abort",()=>e.abort(),{once:!0}),c.signal.addEventListener("abort",()=>e.abort(),{once:!0}),t=e.signal}else t=c.signal;const n=await d.stream(e,{...a,signal:t}),s=r.tapOutputIterable(i,n);for await(const e of s)if(c.signal.aborted)break}finally{await r.finish()}}();let l,h=!1;try{for await(const t of r)h?(t.run_id===l&&t.event.endsWith("_end")&&t.data?.input&&delete t.data.input,yield t):(t.data.input=e,h=!0,l=t.run_id,yield t)}finally{c.abort(),await u}}async*_streamEventsV1(e,t,n){let r,a=!1;const i=(0,s.ZI)(t),o=i.tags??[],c=i.metadata??{},d=i.runName??this.getName(),u=new y({...n,autoClose:!1,_schemaFormat:"streaming_events"}),l=new S({...n}),h=this._streamLog(e,u,i);for await(const t of h){if(r=r?r.concat(t):p.fromRunLogPatch(t),void 0===r.state)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const t={...r.state},n={run_id:t.id,event:`on_${t.type}_start`,name:d,tags:o,metadata:c,data:{input:e}};l.includeEvent(n,t.type)&&(yield n)}const n=t.ops.filter(e=>e.path.startsWith("/logs/")).map(e=>e.path.split("/")[2]),i=[...new Set(n)];for(const e of i){let t,n={};const a=r.state.logs[e];if(t=void 0===a.end_time?a.streamed_output.length>0?"stream":"start":"end","start"===t)void 0!==a.inputs&&(n.input=a.inputs);else if("end"===t)void 0!==a.inputs&&(n.input=a.inputs),n.output=a.final_output;else if("stream"===t){const e=a.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${a.name}"`);n={chunk:a.streamed_output[0]},a.streamed_output=[]}yield{event:`on_${a.type}_${t}`,name:a.name,run_id:a.id,tags:a.tags,metadata:a.metadata,data:n}}const{state:s}=r;if(s.streamed_output.length>0){const e=s.streamed_output.length;if(1!==e)throw new Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${s.name}"`);const t={chunk:s.streamed_output[0]};s.streamed_output=[];const n={event:`on_${s.type}_stream`,run_id:s.id,tags:o,metadata:c,name:d,data:t};l.includeEvent(n,s.type)&&(yield n)}}const f=r?.state;if(void 0!==f){const e={event:`on_${f.type}_end`,name:d,run_id:f.id,tags:o,metadata:c,data:{output:f.final_output}};l.includeEvent(e,f.type)&&(yield e)}}static isRunnable(e){return k(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new W({bound:this,config:{},configFactories:[r=>({callbacks:[new I({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return function(e,t){const n=t.name??e.getName(),r=t.description??(0,O.cg)(t.schema);return(0,O.yQ)(t.schema)?new ce({name:n,description:r,schema:G.z.object({input:G.z.string()}).transform(e=>e.input),bound:e}):new ce({name:n,description:r,schema:t.schema,bound:e})}(this,e)}},W=class e extends V{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=(0,s.SV)(this.config,...e);return(0,s.SV)(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new Y({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,n){const r=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig((0,s.ZI)(e),this.kwargs))):await this._mergeConfig((0,s.ZI)(t),this.kwargs);return this.bound.batch(e,r,n)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig((0,s.ZI)(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig((0,s.ZI)(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig((0,s.ZI)(t),this.kwargs))}streamEvents(e,t,n){const r=this;return c.bO.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig((0,s.ZI)(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&V.isRunnable(e.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new I({config:e,onStart:t,onEnd:n,onError:r})]})]})}},K=class e extends V{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,n){return this.bound.batch(e,(0,s.tn)(t,{callbacks:n?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:r})})}},Y=class extends W{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){const r=e>1?`retry:attempt:${e}`:void 0;return(0,s.tn)(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return(0,E.A)(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:({error:t})=>this.onFailedAttempt(t,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,r){const a={};try{await(0,E.A)(async i=>{const s=e.map((e,t)=>t).filter(e=>void 0===a[e.toString()]||a[e.toString()]instanceof Error),o=s.map(t=>e[t]),c=s.map(e=>this._patchConfigForRetry(i,t?.[e],n?.[e])),d=await super.batch(o,c,{...r,returnExceptions:!0});let u;for(let e=0;e<d.length;e+=1){const t=d[e],n=s[e];t instanceof Error&&void 0===u&&(u=t,u.input=o[e]),a[n.toString()]=t}if(u)throw u;return d},{onFailedAttempt:({error:e})=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(!0!==r?.returnExceptions)throw e}return Object.keys(a).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>a[parseInt(e,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},X=class e extends V{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const n=(0,s.ZI)(t),r=await((await(0,s.kJ)(n))?.handleChainStart(this.toJSON(),Q(e,"input"),n.runId,void 0,void 0,void 0,n?.runName));delete n.runId;let a,i=e;try{const e=[this.first,...this.middle];for(let t=0;t<e.length;t+=1)i=await(0,o.o)(e[t].invoke(i,(0,s.tn)(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),n.signal);if(n.signal?.aborted)throw(0,o.F)(n.signal);a=await this.last.invoke(i,(0,s.tn)(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await(r?.handleChainError(e)),e}return await(r?.handleChainEnd(Q(a,"output"))),a}async batch(e,t,n){const r=this._getOptionsList(t??{},e.length),a=await Promise.all(r.map(s.kJ)),i=await Promise.all(a.map(async(t,n)=>{const a=await(t?.handleChainStart(this.toJSON(),Q(e[n],"input"),r[n].runId,void 0,void 0,void 0,r[n].runName));return delete r[n].runId,a}));let c=e;try{for(let e=0;e<this.steps.length;e+=1)c=await(0,o.o)(this.steps[e].batch(c,i.map((t,n)=>{const a=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return(0,s.tn)(r[n],{callbacks:a})}),n),r[0]?.signal)}catch(e){throw await Promise.all(i.map(t=>t?.handleChainError(e))),e}return await Promise.all(i.map(e=>e?.handleChainEnd(Q(c,"output")))),c}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){const n=await(0,s.kJ)(t),{runId:r,...a}=t??{},i=await(n?.handleChainStart(this.toJSON(),Q(e,"input"),r,void 0,void 0,void 0,a?.runName)),o=[this.first,...this.middle,this.last];let c,d=!0;try{let n=o[0].transform(async function*(){yield e}(),(0,s.tn)(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let e=1;e<o.length;e+=1)n=await o[e].transform(n,(0,s.tn)(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`)}));for await(const e of n)if(t?.signal?.throwIfAborted(),yield e,d)if(void 0===c)c=e;else try{c=this._concatOutputChunks(c,e)}catch{c=void 0,d=!1}}catch(e){throw await(i?.handleChainError(e)),e}await(i?.handleChainEnd(Q(c,"output")))}getGraph(e){const t=new z;let n=null;return this.steps.forEach((r,a)=>{const i=r.getGraph(e);0!==a&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),t.extend(i);const s=i.firstNode();if(!s)throw new Error(`Runnable ${r} has no first node`);n&&t.addEdge(n,s),n=i.lastNode()}),t}pipe(t){return e.isRunnableSequence(t)?new e({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new e({first:this.first,middle:[...this.middle,this.last],last:ie(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&V.isRunnable(e)}static from([t,...n],r){let a={};return"string"==typeof r?a.name=r:void 0!==r&&(a=r),new e({...a,first:ie(t),middle:n.slice(0,-1).map(ie),last:ie(n[n.length-1])})}},ee=class e extends V{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(const[t,n]of Object.entries(e.steps))this.steps[t]=ie(n)}static from(t){return new e({steps:t})}async invoke(e,t){const n=(0,s.ZI)(t),r=await((await(0,s.kJ)(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName));delete n.runId;const a={};try{const t=Object.entries(this.steps).map(async([t,i])=>{a[t]=await i.invoke(e,(0,s.tn)(n,{callbacks:r?.getChild(`map:key:${t}`)}))});await(0,o.o)(Promise.all(t),n.signal)}catch(e){throw await(r?.handleChainError(e)),e}return await(r?.handleChainEnd(a)),a}async*_transform(e,t,n){const r={...this.steps},a=(0,c.gI)(e,Object.keys(r).length),i=new Map(Object.entries(r).map(([e,r],i)=>{const o=r.transform(a[i],(0,s.tn)(n,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,o.next().then(t=>({key:e,gen:o,result:t}))]}));for(;i.size;){const{key:e,result:t,gen:r}=await(0,o.o)(Promise.race(i.values()),n?.signal);i.delete(e),t.done||(yield{[e]:t.value},i.set(e,r.next().then(t=>({key:e,gen:r,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const n=(0,s.ZI)(t),r=new c.Tr({generator:this.transform(async function*(){yield e}(),n),config:n});return await r.setup,c.bO.fromAsyncGenerator(r)}},te=class e extends V{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!(0,H.GZ)(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[n]=this._getOptionsList(t??{},1),r=await(0,s.kJ)(n);return(0,o.o)(this.func((0,s.tn)(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){const[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);var a;if(Z(r))for await(const e of r)n?.signal?.throwIfAborted(),yield e;else if(null!=(a=r)&&"object"==typeof a&&"next"in a&&"function"==typeof a.next)for(;;){n?.signal?.throwIfAborted();const e=r.next();if(e.done)break;yield e.value}else yield r}static from(t){return new e({func:t})}},ne=class e extends V{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if((0,H.GZ)(e.func))return te.from(e.func);super(e),function(e){if((0,H.GZ)(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,n){return new Promise((r,a)=>{const o=(0,s.tn)(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});i.N.runWithConfig((0,s.DY)(o),async()=>{try{let n=await this.func(e,{...o});if(n&&V.isRunnable(n)){if(0===t?.recursionLimit)throw new Error("Recursion limit reached.");n=await n.invoke(e,{...o,recursionLimit:(o.recursionLimit??25)-1})}else if(Z(n)){let e;for await(const r of J(o,n))if(t?.signal?.throwIfAborted(),void 0===e)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}else if(F(n)){let e;for(const r of B(o,n))if(t?.signal?.throwIfAborted(),void 0===e)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}r(n)}catch(e){a(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let r;for await(const t of e)if(void 0===r)r=t;else try{r=this._concatOutputChunks(r,t)}catch{r=t}const a=(0,s.tn)(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),o=await new Promise((e,t)=>{i.N.runWithConfig((0,s.DY)(a),async()=>{try{e(await this.func(r,{...a,config:a}))}catch(e){t(e)}})});if(o&&V.isRunnable(o)){if(0===n?.recursionLimit)throw new Error("Recursion limit reached.");const e=await o.stream(r,a);for await(const t of e)yield t}else if(Z(o))for await(const e of J(a,o))n?.signal?.throwIfAborted(),yield e;else if(F(o))for(const e of B(a,o))n?.signal?.throwIfAborted(),yield e;else yield o}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const n=(0,s.ZI)(t),r=new c.Tr({generator:this.transform(async function*(){yield e}(),n),config:n});return await r.setup,c.bO.fromAsyncGenerator(r)}},re=class extends ee{},ae=class extends V{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=(0,s.ZI)(t),r=await(0,s.kJ)(n),{runId:a,...o}=n,c=await(r?.handleChainStart(this.toJSON(),Q(e,"input"),a,void 0,void 0,void 0,o?.runName)),d=(0,s.tn)(o,{callbacks:c?.getChild()});return await i.N.runWithConfig(d,async()=>{let t;for(const r of this.runnables()){n?.signal?.throwIfAborted();try{const t=await r.invoke(e,d);return await(c?.handleChainEnd(Q(t,"output"))),t}catch(e){void 0===t&&(t=e)}}if(void 0===t)throw new Error("No error stored at end of fallback.");throw await(c?.handleChainError(t)),t})}async*_streamIterator(e,t){const n=(0,s.ZI)(t),r=await(0,s.kJ)(n),{runId:a,...i}=n,o=await(r?.handleChainStart(this.toJSON(),Q(e,"input"),a,void 0,void 0,void 0,i?.runName));let c,d,u;for(const t of this.runnables()){n?.signal?.throwIfAborted();const r=(0,s.tn)(i,{callbacks:o?.getChild()});try{d=J(r,await t.stream(e,r));break}catch(e){void 0===c&&(c=e)}}if(void 0===d){const e=c??new Error("No error stored at end of fallback.");throw await(o?.handleChainError(e)),e}try{for await(const e of d){yield e;try{u=void 0===u?u:this._concatOutputChunks(u,e)}catch{u=void 0}}}catch(e){throw await(o?.handleChainError(e)),e}await(o?.handleChainEnd(Q(u,"output")))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");const r=this._getOptionsList(t??{},e.length),a=await Promise.all(r.map(e=>(0,s.kJ)(e))),i=await Promise.all(a.map(async(t,n)=>{const a=await(t?.handleChainStart(this.toJSON(),Q(e[n],"input"),r[n].runId,void 0,void 0,void 0,r[n].runName));return delete r[n].runId,a}));let o;for(const t of this.runnables()){r[0].signal?.throwIfAborted();try{const a=await t.batch(e,i.map((e,t)=>(0,s.tn)(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(i.map((e,t)=>e?.handleChainEnd(Q(a[t],"output")))),a}catch(e){void 0===o&&(o=e)}}if(!o)throw new Error("No error stored at end of fallbacks.");throw await Promise.all(i.map(e=>e?.handleChainError(o))),o}};function ie(e){if("function"==typeof e)return new ne({func:e});if(V.isRunnable(e))return e;if(Array.isArray(e)||"object"!=typeof e)throw new Error("Expected a Runnable, function or object.\nInstead got an unsupported type.");{const t={};for(const[n,r]of Object.entries(e))t[n]=ie(r);return new ee({steps:t})}}var se=class extends V{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof ee&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){const n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){const r=this.mapper.getStepsKeys(),[a,i]=(0,c.gI)(e),o=this.mapper.transform(i,(0,s.tn)(n,{callbacks:t?.getChild()})),d=o.next();for await(const e of a){if("object"!=typeof e||Array.isArray(e))throw new Error("RunnableAssign can only be used with objects as input, got "+typeof e);const t=Object.fromEntries(Object.entries(e).filter(([e])=>!r.includes(e)));Object.keys(t).length>0&&(yield t)}yield(await d).value;for await(const e of o)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const n=(0,s.ZI)(t),r=new c.Tr({generator:this.transform(async function*(){yield e}(),n),config:n});return await r.setup,c.bO.fromAsyncGenerator(r)}},oe=class extends V{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){("string"==typeof e||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if("string"==typeof this.keys)return e[this.keys];{const t=this.keys.map(t=>[t,e[t]]).filter(e=>void 0!==e[1]);return 0===t.length?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const e=await this._pick(t);void 0!==e&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){const n=(0,s.ZI)(t),r=new c.Tr({generator:this.transform(async function*(){yield e}(),n),config:n});return await r.setup,c.bO.fromAsyncGenerator(r)}},ce=class extends W{name;description;schema;constructor(e){super({bound:X.from([ne.from(async e=>{let t;if((0,r.Ky)(e))try{t=await(0,O.hZ)(this.schema,e.args)}catch{throw new r.qe("Received tool input did not match expected schema",JSON.stringify(e.args))}else t=e;return t}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name}),config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}},10765(e,t,n){n.d(t,{DY:()=>u,SV:()=>s,ZI:()=>c,kJ:()=>i,tn:()=>d});var r=n(39149),a=n(51415);async function i(e){return r.Td._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function s(...e){const t={};for(const n of e.filter(e=>!!e))for(const e of Object.keys(n))if("metadata"===e)t[e]={...t[e],...n[e]};else if("tags"===e){const r=t[e]??[];t[e]=[...new Set(r.concat(n[e]??[]))]}else if("configurable"===e)t[e]={...t[e],...n[e]};else if("timeout"===e)void 0===t.timeout?t.timeout=n.timeout:void 0!==n.timeout&&(t.timeout=Math.min(t.timeout,n.timeout));else if("signal"===e)void 0===t.signal?t.signal=n.signal:void 0!==n.signal&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if("callbacks"===e){const e=t.callbacks,a=n.callbacks;if(Array.isArray(a))if(e)if(Array.isArray(e))t.callbacks=e.concat(a);else{const n=e.copy();for(const e of a)n.addHandler((0,r.tW)(e),!0);t.callbacks=n}else t.callbacks=a;else if(a)if(e)if(Array.isArray(e)){const n=a.copy();for(const t of e)n.addHandler((0,r.tW)(t),!0);t.callbacks=n}else t.callbacks=new r.Td(a._parentRunId,{handlers:e.handlers.concat(a.handlers),inheritableHandlers:e.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(a.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(a.inheritableTags))),metadata:{...e.metadata,...a.metadata}});else t.callbacks=a}else{const r=e;t[r]=n[r]??t[r]}return t}n(98521);const o=new Set(["string","number","boolean"]);function c(e){const t=a.N.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:e,runName:r,...a}=t;n=Object.entries(a).reduce((e,[t,n])=>(void 0!==n&&(e[t]=n),e),n)}if(e&&(n=Object.entries(e).reduce((e,[t,n])=>(void 0!==n&&(e[t]=n),e),n)),n?.configurable)for(const e of Object.keys(n.configurable))o.has(typeof n.configurable[e])&&!n.metadata?.[e]&&(n.metadata||(n.metadata={}),n.metadata[e]=n.configurable[e]);if(void 0!==n.timeout){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const e=n.timeout,t=AbortSignal.timeout(e);n.metadata||(n.metadata={}),void 0===n.metadata.timeoutMs&&(n.metadata.timeoutMs=e),void 0!==n.signal?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,t])):n.signal=t,delete n.timeout}return n}function d(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:a,configurable:i,runId:s}={}){const o=c(e);return void 0!==t&&(delete o.runName,o.callbacks=t),void 0!==r&&(o.recursionLimit=r),void 0!==n&&(o.maxConcurrency=n),void 0!==a&&(o.runName=a),void 0!==i&&(o.configurable={...o.configurable,...i}),void 0!==s&&delete o.runId,o}function u(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}},36968(e,t,n){n.d(t,{X0:()=>s,hr:()=>a,pH:()=>i});const r=Symbol.for("ls:tracing_async_local_storage"),a=Symbol.for("lc:context_variables"),i=e=>{globalThis[r]=e},s=()=>globalThis[r]},51415(e,t,n){n.d(t,{N:()=>d,z:()=>s});var r=n(36968),a=n(39149),i=n(31259),s=class{getStore(){}run(e,t){return t()}enterWith(e){}};const o=new s,c=Symbol.for("lc:child_config"),d=new class{getInstance(){return(0,r.X0)()??o}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[c]}runWithConfig(e,t,n){const s=a.Td._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),o=this.getInstance(),d=o.getStore(),u=s?.getParentRunId(),l=s?.handlers?.find(e=>"langchain_tracer"===e?.name);let h;return l&&u?h=l.getRunTreeWithTracingConfig(u):n||(h=new i.gk({name:"<runnable_lambda>",tracingEnabled:!1})),h&&(h.extra={...h.extra,[c]:e}),void 0!==d&&void 0!==d[r.hr]&&(void 0===h&&(h={}),h[r.hr]=d[r.hr]),o.run(h,t)}initializeGlobalInstance(e){void 0===(0,r.X0)()&&(0,r.pH)(e)}}},98521(e,t,n){n(66630),n(36968),n(51415)},20199(e,t,n){function r(e){return!(!e||"object"!=typeof e||!("type"in e)||"tool_call"!==e.type)}n.d(t,{Ky:()=>r,qe:()=>a});var a=class extends Error{output;constructor(e,t){super(e),this.output=t}}},11590(e,t,n){n.d(t,{JS:()=>d,j7:()=>c}),n(66630);var r=n(89583),a=n(15960),i=n(51688);function s(e,t){if(e)return new i.gk({...e,start_time:e._serialized_start_time??e.start_time,parent_run:s(t),child_runs:e.child_runs.map(e=>s(e)).filter(e=>void 0!==e),extra:{...e.extra,runtime:(0,r.Ec)()},tracingEnabled:!1})}function o(e,t){return e&&!Array.isArray(e)&&"object"==typeof e?e:{[t]:e}}function c(e){return"function"==typeof e._addRunToRunMap}var d=class extends a.NK{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(void 0!==e)return this.usesRunTreeMap?(e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e})(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:""):"string"==typeof e?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:n}=(0,i.sh)(new Date(e.start_time).getTime(),e.id,e.execution_order),r={...e},a=this.getRunById(r.parent_run_id);if(void 0!==r.parent_run_id?a?(this._addChildRun(a,r),a.child_execution_order=Math.max(a.child_execution_order,r.child_execution_order),r.trace_id=a.trace_id,void 0!==a.dotted_order&&(r.dotted_order=[a.dotted_order,t].join("."),r._serialized_start_time=n)):r.parent_run_id=void 0:(r.trace_id=r.id,r.dotted_order=t,r._serialized_start_time=n),this.usesRunTreeMap){const e=s(r,a);void 0!==e&&this.runTreeMap.set(r.id,e)}else this.runMap.set(r.id,r);return r}async _endTrace(e){const t=void 0!==e.parent_run_id&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await(this.onRunUpdate?.(e)),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=void 0!==e&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,r,a,i,s,o){const c=this._getExecutionOrder(r),d=Date.now(),u=s?{...a,metadata:s}:a,l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:i||[]};return this._addRunToRunMap(l)}async handleLLMStart(e,t,n,r,a,i,s,o){const c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,r,a,i,s,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}_createRunForChatModelStart(e,t,n,r,a,i,s,o){const c=this._getExecutionOrder(r),d=Date.now(),u=s?{...a,metadata:s}:a,l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:i||[]};return this._addRunToRunMap(l)}async handleChatModelStart(e,t,n,r,a,i,s,o){const c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,r,a,i,s,o);return await(this.onRunCreate?.(c)),await(this.onLLMStart?.(c)),c}async handleLLMEnd(e,t,n,r,a){const i=this.getRunById(t);if(!i||"llm"!==i?.run_type)throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await(this.onLLMEnd?.(i)),await this._endTrace(i),i}async handleLLMError(e,t,n,r,a){const i=this.getRunById(t);if(!i||"llm"!==i?.run_type)throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await(this.onLLMError?.(i)),await this._endTrace(i),i}_createRunForChainStart(e,t,n,r,a,i,s,o,c){const d=this._getExecutionOrder(r),u=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:t,execution_order:d,child_execution_order:d,run_type:s??"chain",child_runs:[],extra:i?{...c,metadata:i}:{...c},tags:a||[]};return this._addRunToRunMap(l)}async handleChainStart(e,t,n,r,a,i,s,o){const c=this.getRunById(n)??this._createRunForChainStart(e,t,n,r,a,i,s,o);return await(this.onRunCreate?.(c)),await(this.onChainStart?.(c)),c}async handleChainEnd(e,t,n,r,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=o(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),void 0!==a?.inputs&&(i.inputs=o(a.inputs,"input")),await(this.onChainEnd?.(i)),await this._endTrace(i),i}async handleChainError(e,t,n,r,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),void 0!==a?.inputs&&(i.inputs=o(a.inputs,"input")),await(this.onChainError?.(i)),await this._endTrace(i),i}_createRunForToolStart(e,t,n,r,a,i,s){const o=this._getExecutionOrder(r),c=Date.now(),d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(d)}async handleToolStart(e,t,n,r,a,i,s){const o=this.getRunById(n)??this._createRunForToolStart(e,t,n,r,a,i,s);return await(this.onRunCreate?.(o)),await(this.onToolStart?.(o)),o}async handleToolEnd(e,t){const n=this.getRunById(t);if(!n||"tool"!==n?.run_type)throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await(this.onToolEnd?.(n)),await this._endTrace(n),n}async handleToolError(e,t){const n=this.getRunById(t);if(!n||"tool"!==n?.run_type)throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await(this.onToolError?.(n)),await this._endTrace(n),n}async handleAgentAction(e,t){const n=this.getRunById(t);if(!n||"chain"!==n?.run_type)return;const r=n;r.actions=r.actions||[],r.actions.push(e),r.events.push({name:"agent_action",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentAction?.(n))}async handleAgentEnd(e,t){const n=this.getRunById(t);n&&"chain"===n?.run_type&&(n.events.push({name:"agent_end",time:(new Date).toISOString(),kwargs:{action:e}}),await(this.onAgentEnd?.(n)))}_createRunForRetrieverStart(e,t,n,r,a,i,s){const o=this._getExecutionOrder(r),c=Date.now(),d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(d)}async handleRetrieverStart(e,t,n,r,a,i,s){const o=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,r,a,i,s);return await(this.onRunCreate?.(o)),await(this.onRetrieverStart?.(o)),o}async handleRetrieverEnd(e,t){const n=this.getRunById(t);if(!n||"retriever"!==n?.run_type)throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await(this.onRetrieverEnd?.(n)),await this._endTrace(n),n}async handleRetrieverError(e,t){const n=this.getRunById(t);if(!n||"retriever"!==n?.run_type)throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await(this.onRetrieverError?.(n)),await this._endTrace(n),n}async handleText(e,t){const n=this.getRunById(t);n&&"chain"===n?.run_type&&(n.events.push({name:"text",time:(new Date).toISOString(),kwargs:{text:e}}),await(this.onText?.(n)))}async handleLLMNewToken(e,t,n,r,a,i){const s=this.getRunById(n);if(!s||"llm"!==s?.run_type)throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:(new Date).toISOString(),kwargs:{token:e,idx:t,chunk:i?.chunk}}),await(this.onLLMNewToken?.(s,e,{chunk:i?.chunk})),s}}},99624(e,t,n){n.d(t,{g:()=>c}),n(66630);var r=n(69830),a=n(75621),i=n(73290);const s=[400,401,402,403,404,405,406,407,409],o=e=>{if("object"!=typeof e||null===e)return;if("message"in e&&"string"==typeof e.message&&(e.message.startsWith("Cancel")||e.message.startsWith("AbortError"))||"name"in e&&"string"==typeof e.name&&"AbortError"===e.name)throw e;if("code"in e&&"string"==typeof e.code&&"ECONNABORTED"===e.code)throw e;const t="response"in e&&"object"==typeof e.response&&null!==e.response&&"status"in e.response&&"number"==typeof e.response.status?e.response.status:void 0,n="status"in e&&"number"==typeof e.status?e.status:void 0,r=t??n;if(r&&s.includes(+r))throw e;if("insufficient_quota"===("error"in e&&"object"==typeof e.error&&null!==e.error&&"code"in e.error&&"string"==typeof e.error.code?e.error.code:void 0)){const t=new Error("message"in e&&"string"==typeof e.message?e.message:"Insufficient quota");throw t.name="InsufficientQuotaError",t}};var c=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??o,this.queue=new(0,i.default)({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>(0,a.A)(()=>e(...t).catch(e=>{throw e instanceof Error?e:new Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){if(e.signal){let a;return Promise.race([this.call(t,...n),new Promise((t,n)=>{a=()=>{n((0,r.F)(e.signal))},e.signal?.addEventListener("abort",a,{once:!0})})]).finally(()=>{e.signal&&a&&e.signal.removeEventListener("abort",a)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}}},89583(e,t,n){n.d(t,{Az:()=>o,Ec:()=>s});const r=()=>"undefined"!=typeof Deno,a=()=>{let e;return e="undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||r()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":r()?"deno":"other":"node",e};let i;function s(){return void 0===i&&(i={library:"langchain-js",runtime:a()}),i}function o(e){try{return"undefined"!=typeof process?process.env?.[e]:r()?Deno?.env.get(e):void 0}catch{return}}},27787(e,t,n){n(13947);var r=n(52191);n(59250),r.E6},52191(e,t,n){n.d(t,{E6:()=>i,X6:()=>h});var r=n(66630),a=n(13947),i=(0,r.I)({JsonPatchError:()=>s,_areEquals:()=>g,applyOperation:()=>l,applyPatch:()=>h,applyReducer:()=>p,deepClone:()=>o,getValueByPointer:()=>u,validate:()=>m,validator:()=>f});const s=a.DF,o=a.LH,c={add:function(e,t,n){if("__proto__"===t||"constructor"===t)throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){if("__proto__"===t||"constructor"===t)throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){if("__proto__"===t||"constructor"===t)throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=u(n,this.path);r&&(r=(0,a.LH)(r));const i=l(n,{op:"remove",path:this.from}).removed;return l(n,{op:"add",path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){const r=u(n,this.from);return l(n,{op:"add",path:this.path,value:(0,a.LH)(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:g(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}};var d={add:function(e,t,n){return(0,a.Fq)(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:c.move,copy:c.copy,test:c.test,_get:c._get};function u(e,t){if(""==t)return e;var n={op:"_get",path:t};return l(e,n),n.value}function l(e,t,n=!1,r=!0,i=!0,o=0){if(n&&("function"==typeof n?n(t,0,e,t.path):f(t,0)),""===t.path){let r={newDocument:e};if("add"===t.op)return r.newDocument=t.value,r;if("replace"===t.op)return r.newDocument=t.value,r.removed=e,r;if("move"===t.op||"copy"===t.op)return r.newDocument=u(e,t.from),"move"===t.op&&(r.removed=e),r;if("test"===t.op){if(r.test=g(e,t.value),!1===r.test)throw new s("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return r.newDocument=e,r}if("remove"===t.op)return r.removed=e,r.newDocument=null,r;if("_get"===t.op)return t.value=e,r;if(n)throw new s("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,t,e);return r}{r||(e=(0,a.LH)(e));const u=(t.path||"").split("/");let l,h,p,m=e,g=1,y=u.length;for(p="function"==typeof n?n:f;;){if(h=u[g],h&&-1!=h.indexOf("~")&&(h=(0,a.nF)(h)),i&&("__proto__"==h||"prototype"==h&&g>0&&"constructor"==u[g-1]))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&void 0===l&&(void 0===m[h]?l=u.slice(0,g).join("/"):g==y-1&&(l=t.path),void 0!==l&&p(t,0,e,l)),g++,Array.isArray(m)){if("-"===h)h=m.length;else{if(n&&!(0,a.Fq)(h))throw new s("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",o,t,e);(0,a.Fq)(h)&&(h=~~h)}if(g>=y){if(n&&"add"===t.op&&h>m.length)throw new s("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,t,e);const r=d[t.op].call(t,m,h,e);if(!1===r.test)throw new s("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return r}}else if(g>=y){const n=c[t.op].call(t,m,h,e);if(!1===n.test)throw new s("Test operation failed","TEST_OPERATION_FAILED",o,t,e);return n}if(m=m[h],n&&g<y&&(!m||"object"!=typeof m))throw new s("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,t,e)}}}function h(e,t,n,r=!0,i=!0){if(n&&!Array.isArray(t))throw new s("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(e=(0,a.LH)(e));const o=new Array(t.length);for(let r=0,a=t.length;r<a;r++)o[r]=l(e,t[r],n,!0,i,r),e=o[r].newDocument;return o.newDocument=e,o}function p(e,t,n){const r=l(e,t);if(!1===r.test)throw new s("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return r.newDocument}function f(e,t,n,r){if("object"!=typeof e||null===e||Array.isArray(e))throw new s("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(!c[e.op])throw new s("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n);if("string"!=typeof e.path)throw new s("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(0!==e.path.indexOf("/")&&e.path.length>0)throw new s('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if(("move"===e.op||"copy"===e.op)&&"string"!=typeof e.from)throw new s("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&void 0===e.value)throw new s("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if(("add"===e.op||"replace"===e.op||"test"===e.op)&&(0,a.Lb)(e.value))throw new s("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n)if("add"==e.op){var i=e.path.split("/").length,o=r.split("/").length;if(i!==o+1&&i!==o)throw new s("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if("replace"===e.op||"remove"===e.op||"_get"===e.op){if(e.path!==r)throw new s("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if("move"===e.op||"copy"===e.op){var d=m([{op:"_get",path:e.from,value:void 0}],n);if(d&&"OPERATION_PATH_UNRESOLVABLE"===d.name)throw new s("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}function m(e,t,n){try{if(!Array.isArray(e))throw new s("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)h((0,a.LH)(t),(0,a.LH)(e),n||!0);else{n=n||f;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof s)return e;throw e}}function g(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){var n,r,a,i=Array.isArray(e),s=Array.isArray(t);if(i&&s){if((r=e.length)!=t.length)return!1;for(n=r;0!==n--;)if(!g(e[n],t[n]))return!1;return!0}if(i!=s)return!1;var o=Object.keys(e);if((r=o.length)!==Object.keys(t).length)return!1;for(n=r;0!==n--;)if(!t.hasOwnProperty(o[n]))return!1;for(n=r;0!==n--;)if(!g(e[a=o[n]],t[a]))return!1;return!0}return e!=e&&t!=t}},59250(e,t,n){n.d(t,{U:()=>i});var r=n(13947);function a(e,t,n,i,s){if(t!==e){"function"==typeof t.toJSON&&(t=t.toJSON());for(var o=(0,r.bT)(t),c=(0,r.bT)(e),d=!1,u=c.length-1;u>=0;u--){var l=e[p=c[u]];if(!(0,r.mQ)(t,p)||void 0===t[p]&&void 0!==l&&!1===Array.isArray(t))Array.isArray(e)===Array.isArray(t)?(s&&n.push({op:"test",path:i+"/"+(0,r.YX)(p),value:(0,r.LH)(l)}),n.push({op:"remove",path:i+"/"+(0,r.YX)(p)}),d=!0):(s&&n.push({op:"test",path:i,value:e}),n.push({op:"replace",path:i,value:t}));else{var h=t[p];"object"==typeof l&&null!=l&&"object"==typeof h&&null!=h&&Array.isArray(l)===Array.isArray(h)?a(l,h,n,i+"/"+(0,r.YX)(p),s):l!==h&&(s&&n.push({op:"test",path:i+"/"+(0,r.YX)(p),value:(0,r.LH)(l)}),n.push({op:"replace",path:i+"/"+(0,r.YX)(p),value:(0,r.LH)(h)}))}}if(d||o.length!=c.length)for(u=0;u<o.length;u++){var p=o[u];(0,r.mQ)(e,p)||void 0===t[p]||n.push({op:"add",path:i+"/"+(0,r.YX)(p),value:(0,r.LH)(t[p])})}}}function i(e,t,n=!1){var r=[];return a(e,t,r,"",n),r}n(52191)},13947(e,t,n){n.d(t,{DF:()=>h,Fq:()=>o,LH:()=>s,Lb:()=>u,YX:()=>c,bT:()=>i,mQ:()=>a,nF:()=>d});const r=Object.prototype.hasOwnProperty;function a(e,t){return r.call(e,t)}function i(e){if(Array.isArray(e)){const t=new Array(e.length);for(let e=0;e<t.length;e++)t[e]=""+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let n in e)a(e,n)&&t.push(n);return t}function s(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function o(e){let t=0;const n=e.length;let r;for(;t<n;){if(r=e.charCodeAt(t),!(r>=48&&r<=57))return!1;t++}return!0}function c(e){return-1===e.indexOf("/")&&-1===e.indexOf("~")?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function d(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function u(e){if(void 0===e)return!0;if(e)if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(u(e[t]))return!0}else if("object"==typeof e){const n=i(e),r=n.length;for(var t=0;t<r;t++)if(u(e[n[t]]))return!0}return!1}function l(e,t){const n=[e];for(const e in t){const r="object"==typeof t[e]?JSON.stringify(t[e],null,2):t[e];void 0!==r&&n.push(`${e}: ${r}`)}return n.join("\n")}var h=class extends Error{constructor(e,t,n,r,a){super(l(e,{name:t,index:n,operation:r,tree:a})),this.name=t,this.index=n,this.operation=r,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=l(e,{name:t,index:n,operation:r,tree:a})}}},30780(e,t,n){function r(e,t=a){const n=(e=e.trim()).indexOf("```");if(-1===n)return t(e);let r=e.substring(n+3);r.startsWith("json\n")?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith("\n")&&(r=r.substring(1));const i=r.indexOf("```");let s=r;return-1!==i&&(s=r.substring(0,i)),t(s.trim())}function a(e){try{return void 0===e?null:function(e){try{return JSON.parse(e)}catch{}const t=e.trim();if(0===t.length)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<t.length&&/\s/.test(t[n]);)n+=1}function a(){if('"'!==t[n])throw new Error(`Expected '"' at position ${n}, got '${t[n]}'`);n+=1;let e="",r=!1;for(;n<t.length;){const a=t[n];if(r){if("n"===a)e+="\n";else if("t"===a)e+="\t";else if("r"===a)e+="\r";else if("\\"===a)e+="\\";else if('"'===a)e+='"';else if("b"===a)e+="\b";else if("f"===a)e+="\f";else if("/"===a)e+="/";else{if("u"!==a)throw new Error(`Invalid escape sequence '\\${a}' at position ${n}`);{const r=t.substring(n+1,n+5);if(!/^[0-9A-Fa-f]{0,4}$/.test(r))throw new Error(`Invalid unicode escape sequence '\\u${r}' at position ${n}`);4===r.length?e+=String.fromCharCode(Number.parseInt(r,16)):e+=`u${r}`,n+=r.length}}r=!1}else if("\\"===a)r=!0;else{if('"'===a)return n+=1,e;e+=a}n+=1}return r&&(e+="\\"),e}const i=function e(){if(r(),n>=t.length)throw new Error(`Unexpected end of input at position ${n}`);const i=t[n];if("{"===i)return function(){if("{"!==t[n])throw new Error(`Expected '{' at position ${n}, got '${t[n]}'`);const i={};if(n+=1,r(),n>=t.length)return i;if("}"===t[n])return n+=1,i;for(;n<t.length;){if(r(),n>=t.length)return i;const s=a();if(r(),n>=t.length)return i;if(":"!==t[n])throw new Error(`Expected ':' at position ${n}, got '${t[n]}'`);if(n+=1,r(),n>=t.length)return i;if(i[s]=e(),r(),n>=t.length)return i;if("}"===t[n])return n+=1,i;if(","!==t[n])throw new Error(`Expected ',' or '}' at position ${n}, got '${t[n]}'`);n+=1}return i}();if("["===i)return function(){if("["!==t[n])throw new Error(`Expected '[' at position ${n}, got '${t[n]}'`);const a=[];if(n+=1,r(),n>=t.length)return a;if("]"===t[n])return n+=1,a;for(;n<t.length;){if(r(),n>=t.length)return a;if(a.push(e()),r(),n>=t.length)return a;if("]"===t[n])return n+=1,a;if(","!==t[n])throw new Error(`Expected ',' or ']' at position ${n}, got '${t[n]}'`);n+=1}return a}();if('"'===i)return a();if("null".startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),null;if("true".startsWith(t.substring(n,n+4)))return n+=Math.min(4,t.length-n),!0;if("false".startsWith(t.substring(n,n+5)))return n+=Math.min(5,t.length-n),!1;if("-"===i||i>="0"&&i<="9")return function(){const e=n;let r="";if("-"===t[n]&&(r+="-",n+=1),n<t.length&&"0"===t[n]&&(r+="0",n+=1,t[n]>="0"&&t[n]<="9"))throw new Error(`Invalid number at position ${e}`);if(n<t.length&&t[n]>="1"&&t[n]<="9")for(;n<t.length&&t[n]>="0"&&t[n]<="9";)r+=t[n],n+=1;if(n<t.length&&"."===t[n])for(r+=".",n+=1;n<t.length&&t[n]>="0"&&t[n]<="9";)r+=t[n],n+=1;if(n<t.length&&("e"===t[n]||"E"===t[n]))for(r+=t[n],n+=1,n<t.length&&("+"===t[n]||"-"===t[n])&&(r+=t[n],n+=1);n<t.length&&t[n]>="0"&&t[n]<="9";)r+=t[n],n+=1;if("-"===r)return-0;const a=Number.parseFloat(r);if(Number.isNaN(a))throw n=e,new Error(`Invalid number '${r}' at position ${e}`);return a}();throw new Error(`Unexpected character '${i}' at position ${n}`)}();if(r(),n<t.length)throw new Error(`Unexpected character '${t[n]}' at position ${n}`);return i}(e)}catch{return null}}n.d(t,{D:()=>r,d:()=>a})},38727(e,t,n){n.d(t,{PF:()=>B}),n(66630);var r=n(92535);const a=Symbol("Let zodToJsonSchema decide on which parser to use"),i={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"},s=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function o(e){if("openAi"!==e.target)return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:"relative"===e.$refStrategy?s(t,e.currentPath):t.join("/")}}function c(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function d(e,t,n,r,a){e[t]=n,c(e,t,r,a)}var u=n(1038);function l(e,t){return M(e.type._def,t)}function h(e,t,n){const r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>h(e,t,n))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return p(e,t)}}const p=(e,t)=>{const n={type:"integer",format:"unix-time"};if("openApi3"===t.target)return n;for(const r of e.checks)switch(r.kind){case"min":d(n,"minimum",r.value,r.message,t);break;case"max":d(n,"maximum",r.value,r.message,t)}return n};let f;const m=/^[cC][^\s-]{8,}$/,g=/^[0-9a-z]+$/,y=/^[0-9A-HJKMNP-TV-Z]{26}$/,_=/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,v=()=>(void 0===f&&(f=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),f),w=/^(?:(?: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])$/,b=/^(([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])$/,E=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,x=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,I=/^[a-zA-Z0-9_-]{21}$/,k=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;function S(e,t){const n={type:"string"};if(e.checks)for(const r of e.checks)switch(r.kind){case"min":d(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t);break;case"max":d(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"email":switch(t.emailStrategy){case"format:email":A(n,"email",r.message,t);break;case"format:idn-email":A(n,"idn-email",r.message,t);break;case"pattern:zod":$(n,_,r.message,t)}break;case"url":A(n,"uri",r.message,t);break;case"uuid":A(n,"uuid",r.message,t);break;case"regex":$(n,r.regex,r.message,t);break;case"cuid":$(n,m,r.message,t);break;case"cuid2":$(n,g,r.message,t);break;case"startsWith":$(n,RegExp(`^${O(r.value,t)}`),r.message,t);break;case"endsWith":$(n,RegExp(`${O(r.value,t)}$`),r.message,t);break;case"datetime":A(n,"date-time",r.message,t);break;case"date":A(n,"date",r.message,t);break;case"time":A(n,"time",r.message,t);break;case"duration":A(n,"duration",r.message,t);break;case"length":d(n,"minLength","number"==typeof n.minLength?Math.max(n.minLength,r.value):r.value,r.message,t),d(n,"maxLength","number"==typeof n.maxLength?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case"includes":$(n,RegExp(O(r.value,t)),r.message,t);break;case"ip":"v6"!==r.version&&A(n,"ipv4",r.message,t),"v4"!==r.version&&A(n,"ipv6",r.message,t);break;case"base64url":$(n,x,r.message,t);break;case"jwt":$(n,k,r.message,t);break;case"cidr":"v6"!==r.version&&$(n,w,r.message,t),"v4"!==r.version&&$(n,b,r.message,t);break;case"emoji":$(n,v(),r.message,t);break;case"ulid":$(n,y,r.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":A(n,"binary",r.message,t);break;case"contentEncoding:base64":d(n,"contentEncoding","base64",r.message,t);break;case"pattern:zod":$(n,E,r.message,t)}break;case"nanoid":$(n,I,r.message,t);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:(()=>{})()}return n}function O(e,t){return"escape"===t.patternStrategy?function(e){let t="";for(let n=0;n<e.length;n++)T.has(e[n])||(t+="\\"),t+=e[n];return t}(e):e}const T=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function A(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):d(e,"format",t,n,r)}function $(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,0===Object.keys(e.errorMessage).length&&delete e.errorMessage)),e.allOf.push({pattern:N(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):d(e,"pattern",N(t,r),n,r)}function N(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n=e.flags.includes("i"),r=e.flags.includes("m"),a=e.flags.includes("s"),i=n?e.source.toLowerCase():e.source;let s="",o=!1,c=!1,d=!1;for(let e=0;e<i.length;e++)if(o)s+=i[e],o=!1;else{if(n)if(c){if(i[e].match(/[a-z]/)){d?(s+=i[e],s+=`${i[e-2]}-${i[e]}`.toUpperCase(),d=!1):"-"===i[e+1]&&i[e+2]?.match(/[a-z]/)?(s+=i[e],d=!0):s+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){s+=`[${i[e]}${i[e].toUpperCase()}]`;continue}if(r){if("^"===i[e]){s+="(^|(?<=[\r\n]))";continue}if("$"===i[e]){s+="($|(?=[\r\n]))";continue}}a&&"."===i[e]?s+=c?`${i[e]}\r\n`:`[${i[e]}\r\n]`:(s+=i[e],"\\"===i[e]?o=!0:c&&"]"===i[e]?c=!1:c||"["!==i[e]||(c=!0))}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return s}function j(e,t){if("openAi"===t.target&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),"openApi3"===t.target&&e.keyType?._def.typeName===u.kY.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:M(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??o(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:M(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if("openApi3"===t.target)return n;if(e.keyType?._def.typeName===u.kY.ZodString&&e.keyType._def.checks?.length){const{type:r,...a}=S(e.keyType._def,t);return{...n,propertyNames:a}}if(e.keyType?._def.typeName===u.kY.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===u.kY.ZodBranded&&e.keyType._def.type._def.typeName===u.kY.ZodString&&e.keyType._def.type._def.checks?.length){const{type:r,...a}=l(e.keyType._def,t);return{...n,propertyNames:a}}return n}const C={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"},R=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>M(e._def,{...t,currentPath:[...t.currentPath,"anyOf",`${n}`]})).filter(e=>!!e&&(!t.strictUnions||"object"==typeof e&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function P(e){try{return e.isOptional()}catch{return!0}}const L=(e,t,n)=>{switch(t){case u.kY.ZodString:return S(e,n);case u.kY.ZodNumber:return function(e,t){const n={type:"number"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"int":n.type="integer",c(n,"type",r.message,t);break;case"min":"jsonSchema7"===t.target?r.inclusive?d(n,"minimum",r.value,r.message,t):d(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),d(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?d(n,"maximum",r.value,r.message,t):d(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),d(n,"maximum",r.value,r.message,t));break;case"multipleOf":d(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case u.kY.ZodObject:return function(e,t){const n="openAi"===t.target,r={type:"object",properties:{}},a=[],i=e.shape();for(const e in i){let s=i[e];if(void 0===s||void 0===s._def)continue;let o=P(s);o&&n&&("ZodOptional"===s._def.typeName&&(s=s._def.innerType),s.isNullable()||(s=s.nullable()),o=!1);const c=M(s._def,{...t,currentPath:[...t.currentPath,"properties",e],propertyPath:[...t.currentPath,"properties",e]});void 0!==c&&(r.properties[e]=c,o||a.push(e))}a.length&&(r.required=a);const s=function(e,t){if("ZodNever"!==e.catchall._def.typeName)return M(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return"strict"===t.removeAdditionalStrategy?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}(e,t);return void 0!==s&&(r.additionalProperties=s),r}(e,n);case u.kY.ZodBigInt:return function(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const r of e.checks)switch(r.kind){case"min":"jsonSchema7"===t.target?r.inclusive?d(n,"minimum",r.value,r.message,t):d(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),d(n,"minimum",r.value,r.message,t));break;case"max":"jsonSchema7"===t.target?r.inclusive?d(n,"maximum",r.value,r.message,t):d(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),d(n,"maximum",r.value,r.message,t));break;case"multipleOf":d(n,"multipleOf",r.value,r.message,t)}return n}(e,n);case u.kY.ZodBoolean:return{type:"boolean"};case u.kY.ZodDate:return h(e,n);case u.kY.ZodUndefined:return function(e){return{not:o(e)}}(n);case u.kY.ZodNull:return function(e){return"openApi3"===e.target?{enum:["null"],nullable:!0}:{type:"null"}}(n);case u.kY.ZodArray:return function(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==u.kY.ZodAny&&(n.items=M(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&d(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&d(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(d(n,"minItems",e.exactLength.value,e.exactLength.message,t),d(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}(e,n);case u.kY.ZodUnion:case u.kY.ZodDiscriminatedUnion:return function(e,t){if("openApi3"===t.target)return R(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in C&&(!e._def.checks||!e._def.checks.length))){const e=n.reduce((e,t)=>{const n=C[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>"ZodLiteral"===e._def.typeName&&!e.description)){const e=n.reduce((e,t)=>{const n=typeof t._def.value;switch(n){case"string":case"number":case"boolean":return[...e,n];case"bigint":return[...e,"integer"];case"object":return null===t._def.value?[...e,"null"]:e;default:return e}},[]);if(e.length===n.length){const t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>"ZodEnum"===e._def.typeName))return{type:"string",enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return R(e,t)}(e,n);case u.kY.ZodIntersection:return function(e,t){const n=[M(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),M(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(e=>!!e);let r="jsonSchema2019-09"===t.target?{unevaluatedProperties:!1}:void 0;const a=[];return n.forEach(e=>{if("type"in(t=e)&&"string"===t.type||!("allOf"in t)){let t=e;if("additionalProperties"in e&&!1===e.additionalProperties){const{additionalProperties:n,...r}=e;t=r}else r=void 0;a.push(t)}else a.push(...e.allOf),void 0===e.unevaluatedProperties&&(r=void 0);var t}),a.length?{allOf:a,...r}:void 0}(e,n);case u.kY.ZodTuple:return function(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((e,n)=>M(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[]),additionalItems:M(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>M(e._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((e,t)=>void 0===t?e:[...e,t],[])}}(e,n);case u.kY.ZodRecord:return j(e,n);case u.kY.ZodLiteral:return function(e,t){const n=typeof e.value;return"bigint"!==n&&"number"!==n&&"boolean"!==n&&"string"!==n?{type:Array.isArray(e.value)?"array":"object"}:"openApi3"===t.target?{type:"bigint"===n?"integer":n,enum:[e.value]}:{type:"bigint"===n?"integer":n,const:e.value}}(e,n);case u.kY.ZodEnum:return function(e){return{type:"string",enum:Array.from(e.values)}}(e);case u.kY.ZodNativeEnum:return function(e){const t=e.values,n=Object.keys(e.values).filter(e=>"number"!=typeof t[t[e]]).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:1===r.length?"string"===r[0]?"string":"number":["string","number"],enum:n}}(e);case u.kY.ZodNullable:return function(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return"openApi3"===t.target?{type:C[e.innerType._def.typeName],nullable:!0}:{type:[C[e.innerType._def.typeName],"null"]};if("openApi3"===t.target){const n=M(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const n=M(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}(e,n);case u.kY.ZodOptional:return((e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return M(e.innerType._def,t);const n=M(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:o(t)},n]}:o(t)})(e,n);case u.kY.ZodMap:return function(e,t){return"record"===t.mapStrategy?j(e,t):{type:"array",maxItems:125,items:{type:"array",items:[M(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||o(t),M(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||o(t)],minItems:2,maxItems:2}}}(e,n);case u.kY.ZodSet:return function(e,t){const n={type:"array",uniqueItems:!0,items:M(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&d(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&d(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}(e,n);case u.kY.ZodLazy:return()=>e.getter()._def;case u.kY.ZodPromise:return function(e,t){return M(e.type._def,t)}(e,n);case u.kY.ZodNaN:case u.kY.ZodNever:return function(e){return"openAi"===e.target?void 0:{not:o({...e,currentPath:[...e.currentPath,"not"]})}}(n);case u.kY.ZodEffects:return function(e,t){return"input"===t.effectStrategy?M(e.schema._def,t):o(t)}(e,n);case u.kY.ZodAny:return o(n);case u.kY.ZodUnknown:return function(e){return o(e)}(n);case u.kY.ZodDefault:return function(e,t){return{...M(e.innerType._def,t),default:e.defaultValue()}}(e,n);case u.kY.ZodBranded:return l(e,n);case u.kY.ZodReadonly:case u.kY.ZodCatch:return((e,t)=>M(e.innerType._def,t))(e,n);case u.kY.ZodPipeline:return((e,t)=>{if("input"===t.pipeStrategy)return M(e.in._def,t);if("output"===t.pipeStrategy)return M(e.out._def,t);const n=M(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]});return{allOf:[n,M(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]})].filter(e=>void 0!==e)}})(e,n);case u.kY.ZodFunction:case u.kY.ZodVoid:case u.kY.ZodSymbol:default:return}};function M(e,t,n=!1){const r=t.seen.get(e);if(t.override){const i=t.override?.(e,t,r,n);if(i!==a)return i}if(r&&!n){const e=z(r,t);if(void 0!==e)return e}const i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);const s=L(e,e.typeName,t),o="function"==typeof s?M(s(),t):s;if(o&&D(e,t,o),t.postProcess){const n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const z=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:s(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),o(t)):"seen"===t.$refStrategy?o(t):void 0}},D=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);var U=n(66421),F=n(75335);n(77265);const Z=new WeakMap;function B(e,t){const n=!t&&null!=e&&"object"==typeof e;if(n){const t=Z.get(e);if(t)return t}let a;if((0,U.X9)(e)&&!(0,r.Pq)(e))a=e["~standard"].jsonSchema.input({target:"draft-07"});else if((0,r.Pq)(e)){const n=(0,r.EN)(e,!0);a=(0,r.gY)(n)?(0,F.blZ)((0,r.pE)(n,!0),t):(0,F.blZ)(e,t)}else a=(0,r.IU)(e)?((e,t)=>{const n=(e=>{const t=(e=>"string"==typeof e?{...i,name:e}:{...i,...e})(e),n=void 0!==t.name?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}})(t);let r;const a=t?.name,s=M(e._def,void 0===a?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1)??o(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:"relative"===n.$refStrategy?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const c=void 0===a?r?{...s,[n.definitionPath]:r}:s:{$ref:[..."relative"===n.$refStrategy?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...r,[a]:s}};return"jsonSchema7"===n.target?c.$schema="http://json-schema.org/draft-07/schema#":"jsonSchema2019-09"!==n.target&&"openAi"!==n.target||(c.$schema="https://json-schema.org/draft/2019-09/schema#"),"openAi"===n.target&&("anyOf"in c||"oneOf"in c||"allOf"in c||"type"in c&&Array.isArray(c.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),c})(e):e;return n&&null!=a&&"object"==typeof a&&Z.set(e,a),a}},75621(e,t,n){n.d(t,{A:()=>d});const r=Object.prototype.toString,a=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 i(e,t,{min:n=0,allowInfinity:r=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be ≥ ${n}.`)}}var s=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function o(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function c({error:e,attemptNumber:t,retriesConsumed:n,startTime:i,options:c}){const d=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(d instanceof s)throw d.originalError;const u=Number.isFinite(c.retries)?Math.max(0,c.retries-n):c.retries,l=c.maxRetryTime??Number.POSITIVE_INFINITY,h=Object.freeze({error:d,attemptNumber:t,retriesLeft:u,retriesConsumed:n});if(await c.onFailedAttempt(h),o(i,l)<=0)throw d;const p=await c.shouldConsumeRetry(h),f=o(i,l);if(f<=0||u<=0)throw d;if(d instanceof TypeError&&!function(e){if(!e||(t=e,"[object Error]"!==r.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)return!1;var t;const{message:n,stack:i}=e;return"Load failed"===n?void 0===i||"__sentry_captured__"in e:!!n.startsWith("error sending request for url")||a.has(n)}(d)){if(p)throw d;return c.signal?.throwIfAborted(),!1}if(!await c.shouldRetry(h))throw d;if(!p)return c.signal?.throwIfAborted(),!1;const m=function(e,t){const n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1;let a=Math.round(r*t.minTimeout*t.factor**(n-1));return a=Math.min(a,t.maxTimeout),a}(n,c),g=Math.min(m,f);return g>0&&await new Promise((e,t)=>{const n=()=>{clearTimeout(r),c.signal?.removeEventListener("abort",n),t(c.signal.reason)},r=setTimeout(()=>{c.signal?.removeEventListener("abort",n),e()},g);c.unref&&r.unref?.(),c.signal?.addEventListener("abort",n,{once:!0})}),c.signal?.throwIfAborted(),!0}async function d(e,t={}){if(function(e){if("number"==typeof e){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==e)throw new TypeError("Expected `retries` to be a number or Infinity.")}((t={...t}).retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,i("factor",t.factor,{min:0,allowInfinity:!1}),i("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),i("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),i("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0;const a=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();const r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await c({error:e,attemptNumber:n,retriesConsumed:r,startTime:a,options:t})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}},69830(e,t,n){async function r(e,t){if(void 0===t)return e;let n;return Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,r)=>{n=()=>{r(a(t))},t.addEventListener("abort",n,{once:!0}),t.aborted&&r(a(t))})]).finally(()=>t.removeEventListener("abort",n))}function a(e){return e?.reason instanceof Error?e.reason:"string"==typeof e?.reason?new Error(e.reason):new Error("Aborted")}n.d(t,{F:()=>a,o:()=>r})},66421(e,t,n){function r(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"~standard"in e&&"object"==typeof e["~standard"]&&null!==e["~standard"]&&"jsonSchema"in e["~standard"]}function a(e){return function(e){return("object"==typeof e||"function"==typeof e)&&null!==e&&"~standard"in e&&"object"==typeof e["~standard"]&&null!==e["~standard"]&&"validate"in e["~standard"]}(e)&&r(e)}n.d(t,{X9:()=>r,hG:()=>a})},50058(e,t,n){n.d(t,{DS:()=>u,Tr:()=>d,bO:()=>s,gI:()=>o,xW:()=>c}),n(66630);var r=n(51415),a=(n(98521),n(10765)),i=n(69830),s=class e extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const n=t.getReader();return new e({start:e=>function t(){return n.read().then(({done:n,value:r})=>{if(!n)return e.enqueue(r),t();e.close()})}(),cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){const{value:n,done:r}=await t.next();r&&e.close(),e.enqueue(n)},async cancel(e){await t.return(e)}})}};function o(e,t=2){const n=Array.from({length:t},()=>[]);return n.map(async function*(t){for(;;)if(0===t.length){const t=await e.next();for(const e of n)e.push(t)}else{if(t[0].done)return;yield t.shift().value}})}function c(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if("string"==typeof e&&"string"==typeof t)return e+t;if("number"==typeof e&&"number"==typeof t)return e+t;if("concat"in e&&"function"==typeof e.concat)return e.concat(t);if("object"==typeof e&&"object"==typeof t){const n={...e};for(const[e,r]of Object.entries(t))e in n&&!Array.isArray(n[e])?n[e]=c(n[e],r):n[e]=r;return n}throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var d=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{r.N.runWithConfig((0,a.DY)(e.config),async()=>{this.firstResult=this.signal?(0,i.o)(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(e=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?r.N.runWithConfig((0,a.DY)(this.config),this.signal?async()=>(0,i.o)(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function u(e,t,n,r,...a){const i=new d({generator:t,startSetup:n,signal:r}),s=await i.setup;return{output:e(i,s,...a),setup:s}}},92535(e,t,n){n.d(t,{BA:()=>S,BZ:()=>C,EN:()=>N,Gd:()=>u,IS:()=>_,IU:()=>i,K3:()=>l,PA:()=>I,Pq:()=>a,QV:()=>x,RA:()=>A,S8:()=>b,W0:()=>k,X2:()=>g,Yi:()=>p,Zu:()=>f,c9:()=>o,cg:()=>m,gY:()=>v,hZ:()=>h,lm:()=>s,pE:()=>O,qT:()=>T,rA:()=>d,vf:()=>E,yQ:()=>y,yx:()=>c,zL:()=>w,zO:()=>j});var r=n(75335);function a(e){if("object"!=typeof e||null===e)return!1;if(!("_zod"in e))return!1;const t=e._zod;return"object"==typeof t&&null!==t&&"def"in t}function i(e){if("object"!=typeof e||null===e)return!1;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return"object"==typeof t&&null!=t&&"typeName"in t}function s(e){return a(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),i(e)}function o(e){return!(!e||"object"!=typeof e||Array.isArray(e)||!a(e)&&!i(e))}function c(e){return"object"==typeof e&&null!==e&&"_def"in e&&"object"==typeof e._def&&null!==e._def&&"typeName"in e._def&&"ZodLiteral"===e._def.typeName}function d(e){return!!a(e)&&"object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"literal"===e._zod.def.type}function u(e){return!!c(e)||!!d(e)}async function l(e,t){if(a(e))try{return{success:!0,data:await(0,r.EJS)(e,t)}}catch(e){return{success:!1,error:e}}if(i(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function h(e,t){if(a(e))return await(0,r.EJS)(e,t);if(i(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function p(e,t){if(a(e))try{return{success:!0,data:(0,r.qgA)(e,t)}}catch(e){return{success:!1,error:e}}if(i(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function f(e,t){if(a(e))return(0,r.qgA)(e,t);if(i(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function m(e){return a(e)?r.fd.get(e)?.description:i(e)||"description"in e&&"string"==typeof e.description?e.description:void 0}function g(e){if(!o(e))return!1;if(i(e)){const t=e._def;if("ZodObject"===t.typeName){const t=e;return!t.shape||0===Object.keys(t.shape).length}if("ZodRecord"===t.typeName)return!0}if(a(e)){const t=e._zod.def;if("object"===t.type){const t=e;return!t.shape||0===Object.keys(t.shape).length}if("record"===t.type)return!0}return"object"==typeof e&&null!==e&&!("shape"in e)}function y(e){return!!o(e)&&(i(e)?"ZodString"===e._def.typeName:!!a(e)&&"string"===e._zod.def.type)}function _(e){return"object"==typeof e&&null!==e&&"_def"in e&&"object"==typeof e._def&&null!==e._def&&"typeName"in e._def&&"ZodObject"===e._def.typeName}function v(e){return!!a(e)&&"object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"object"===e._zod.def.type}function w(e){return!!a(e)&&"object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"array"===e._zod.def.type}function b(e){return!!a(e)&&"object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"optional"===e._zod.def.type}function E(e){return!!a(e)&&"object"==typeof e&&null!==e&&"_zod"in e&&"object"==typeof e._zod&&null!==e._zod&&"def"in e._zod&&"object"==typeof e._zod.def&&null!==e._zod.def&&"type"in e._zod.def&&"nullable"===e._zod.def.type}function x(e){return!!_(e)||!!v(e)}function I(e){if(i(e))return e.shape;if(a(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function k(e,t){if(i(e))return e.extend(t);if(a(e))return r.ZSL.extend(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function S(e){if(i(e))return e.partial();if(a(e))return r.ZSL.partial(r.igI,e,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function O(e,t=!1){if(_(e))return e.strict();if(v(e)){const n=e._zod.def.shape;if(t)for(const[a,i]of Object.entries(e._zod.def.shape)){if(v(i))n[a]=O(i,t);else if(w(i)){let e=i._zod.def.element;v(e)&&(e=O(e,t)),n[a]=(0,r.o8B)(i,{...i._zod.def,element:e})}else n[a]=i;const e=r.fd.get(i);e&&r.fd.add(n[a],e)}const a=(0,r.o8B)(e,{...e._zod.def,shape:n,catchall:(0,r.G8g)(r.Umr)}),i=r.fd.get(e);return i&&r.fd.add(a,i),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function T(e,t=!1){if(_(e))return e.passthrough();if(v(e)){const n=e._zod.def.shape;if(t)for(const[a,i]of Object.entries(e._zod.def.shape)){if(v(i))n[a]=T(i,t);else if(w(i)){let e=i._zod.def.element;v(e)&&(e=T(e,t)),n[a]=(0,r.o8B)(i,{...i._zod.def,element:e})}else n[a]=i;const e=r.fd.get(i);e&&r.fd.add(n[a],e)}const a=(0,r.o8B)(e,{...e._zod.def,shape:n,catchall:(0,r.emL)(r.GPR)}),i=r.fd.get(e);return i&&r.fd.add(a,i),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function A(e){if(i(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(a(e))try{const t=(0,r.qgA)(e,void 0);return()=>t}catch{return}}function $(e,t,n){const s=n.get(e);if(void 0!==s)return s;if(i(e))return function(e){return i(e)&&"typeName"in e._def&&"ZodEffects"===e._def.typeName}(e)?$(e._def.schema,t,n):e;if(a(e)){let i=e;if(function(e){return a(e)&&"pipe"===e._zod.def.type}(e)&&(i=$(e._zod.def.in,t,n)),t)if(v(i)){const e={};for(const[r,a]of Object.entries(i._zod.def.shape))e[r]=$(a,t,n);i=(0,r.o8B)(i,{...i._zod.def,shape:e})}else if(w(i)){const e=$(i._zod.def.element,t,n);i=(0,r.o8B)(i,{...i._zod.def,element:e})}else if(b(i)){const e=$(i._zod.def.innerType,t,n);i=(0,r.o8B)(i,{...i._zod.def,innerType:e})}else if(E(i)){const e=$(i._zod.def.innerType,t,n);i=(0,r.o8B)(i,{...i._zod.def,innerType:e})}const s=r.fd.get(e);return s&&r.fd.add(i,s),n.set(e,i),i}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function N(e,t=!1){return $(e,t,new WeakMap)}function j(e,t){if(i(e)){const n=I(e),r={};for(const[e,a]of Object.entries(n))t(e,a)?r[e]=a.optional():r[e]=a;return e.extend(r)}if(a(e)){const n=I(e),a={...e._zod.def.shape};for(const[e,i]of Object.entries(n))t(e,i)&&(a[e]=new r.igI({type:"optional",innerType:i}));const i=(0,r.o8B)(e,{...e._zod.def,shape:a}),s=r.fd.get(e);return s&&r.fd.add(i,s),i}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function C(e){return e instanceof Error&&("ZodError"===e.constructor.name||"$ZodError"===e.constructor.name)}},62187(e,t,n){let r;n.d(t,{A:()=>i});const a=new Uint8Array(16);function i(){if(!r){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");r=crypto.getRandomValues.bind(crypto)}return r(a)}},71331(e,t,n){n.d(t,{k:()=>a});const r=[];for(let e=0;e<256;++e)r.push((e+256).toString(16).slice(1));function a(e,t=0){return(r[e[t+0]]+r[e[t+1]]+r[e[t+2]]+r[e[t+3]]+"-"+r[e[t+4]]+r[e[t+5]]+"-"+r[e[t+6]]+r[e[t+7]]+"-"+r[e[t+8]]+r[e[t+9]]+"-"+r[e[t+10]]+r[e[t+11]]+r[e[t+12]]+r[e[t+13]]+r[e[t+14]]+r[e[t+15]]).toLowerCase()}},16675(e,t,n){n.d(t,{A:()=>o});var r=n(62187),a=n(71331);const i={};function s(e,t,n,r,a=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(r){if(a<0||a+16>r.length)throw new RangeError(`UUID byte range ${a}:${a+15} is out of buffer bounds`)}else r=new Uint8Array(16),a=0;return t??=Date.now(),n??=127*e[6]<<24|e[7]<<16|e[8]<<8|e[9],r[a++]=t/1099511627776&255,r[a++]=t/4294967296&255,r[a++]=t/16777216&255,r[a++]=t/65536&255,r[a++]=t/256&255,r[a++]=255&t,r[a++]=112|n>>>28&15,r[a++]=n>>>20&255,r[a++]=128|n>>>14&63,r[a++]=n>>>6&255,r[a++]=n<<2&255|3&e[10],r[a++]=e[11],r[a++]=e[12],r[a++]=e[13],r[a++]=e[14],r[a++]=e[15],r}const o=function(e,t,n){let o;if(e)o=s(e.random??e.rng?.()??(0,r.A)(),e.msecs,e.seq,t,n);else{const e=Date.now(),a=(0,r.A)();!function(e,t,n){e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],e.msecs=t):(e.seq=e.seq+1|0,0===e.seq&&e.msecs++)}(i,e,a),o=s(a,i.msecs,i.seq,t,n)}return t??(0,a.k)(o)}},51906(e,t,n){n.d(t,{Kj:()=>ie});var r=n(477),a=n(41167);const i="gen_ai.request.model",s="gen_ai.usage.input_tokens",o="gen_ai.usage.output_tokens",c="gen_ai.usage.total_tokens",d="langsmith.span.tags";var u=n(24785);class l{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){let n;if(!this.hasWarned&&(0,u.QK)()&&(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),1===t.length&&"function"==typeof t[0]?n=t[0]:2===t.length&&"function"==typeof t[1]?n=t[1]:3===t.length&&"function"==typeof t[2]&&(n=t[2]),"function"==typeof n)return n()}}const h=Symbol.for("ls:otel_trace"),p=Symbol.for("ls:otel_context"),f=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),m=new class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new l})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},g=new class{active(){return{}}with(e,t){return t()}},y=new class{getTraceInstance(){return globalThis[h]??m}getContextInstance(){return globalThis[p]??g}initializeGlobalInstances(e){void 0===globalThis[h]&&(globalThis[h]=e.trace),void 0===globalThis[p]&&(globalThis[p]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[f]=e}getDefaultOTLPTracerComponents(){return globalThis[f]??void 0}};function _(){return y.getTraceInstance()}const v={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};class w{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const n of e)try{if(!n.run)continue;if("post"===n.operation){const e=this.createSpanForRun(n,n.run,t.get(n.id));e&&!n.run.end_time&&this.spans.set(n.id,e)}else this.updateSpanForRun(n,n.run)}catch(e){console.error(`Error processing operation ${n.id}:`,e)}}createSpanForRun(e,t,n){const r=n&&_().getSpan(n);if(r)try{return this.finishSpanSetup(r,t,e)}catch(t){return void console.error(`Failed to create span for run ${e.id}:`,t)}}finishSpanSetup(e,t,n){return this.setSpanAttributes(e,t,n),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{const n=this.spans.get(e.id);if(!n)return void console.debug(`No span found for run ${e.id} during update`);this.setSpanAttributes(n,t,e),t.error?(n.setStatus({code:2}),n.recordException(new Error(t.error))):n.setStatus({code:1});const r=t.end_time;r&&(n.end(new Date(r)),this.spans.delete(e.id))}catch(t){console.error(`Failed to update span for run ${e.id}:`,t)}}extractModelName(e){if(e.extra?.metadata){const t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){const e=t.invocation_params;if(e.model)return e.model;if(e.model_name)return e.model_name}}}setSpanAttributes(e,t,n){if("run_type"in t&&t.run_type){e.setAttribute("langsmith.span.kind",t.run_type);const n=(r=t.run_type||"chain",v[r]||r);e.setAttribute("gen_ai.operation.name",n)}var r;"name"in t&&t.name&&e.setAttribute("langsmith.trace.name",t.name),"session_id"in t&&t.session_id&&e.setAttribute("langsmith.trace.session_id",t.session_id),"session_name"in t&&t.session_name&&e.setAttribute("langsmith.trace.session_name",t.session_name),this.setGenAiSystem(e,t);const a=this.extractModelName(t);a&&e.setAttribute(i,a),"prompt_tokens"in t&&"number"==typeof t.prompt_tokens&&e.setAttribute(s,t.prompt_tokens),"completion_tokens"in t&&"number"==typeof t.completion_tokens&&e.setAttribute(o,t.completion_tokens),"total_tokens"in t&&"number"==typeof t.total_tokens&&e.setAttribute(c,t.total_tokens),this.setInvocationParameters(e,t);const u=t.extra?.metadata||{};for(const[t,n]of Object.entries(u))null!=n&&e.setAttribute(`langsmith.metadata.${t}`,String(n));const l=t.tags;if(l&&Array.isArray(l)?e.setAttribute(d,l.join(", ")):l&&e.setAttribute(d,String(l)),"serialized"in t&&"object"==typeof t.serialized){const n=t.serialized;n.name&&e.setAttribute("gen_ai.serialized.name",String(n.name)),n.signature&&e.setAttribute("gen_ai.serialized.signature",String(n.signature)),n.doc&&e.setAttribute("gen_ai.serialized.doc",String(n.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,t){let n="langchain";const r=this.extractModelName(t);if(r){const e=r.toLowerCase();e.includes("anthropic")||e.startsWith("claude")?n="anthropic":e.includes("bedrock")?n="aws.bedrock":e.includes("azure")&&e.includes("openai")?n="az.ai.openai":e.includes("azure")&&e.includes("inference")?n="az.ai.inference":e.includes("cohere")?n="cohere":e.includes("deepseek")?n="deepseek":e.includes("gemini")?n="gemini":e.includes("groq")?n="groq":e.includes("watson")||e.includes("ibm")?n="ibm.watsonx.ai":e.includes("mistral")?n="mistral_ai":e.includes("gpt")||e.includes("openai")?n="openai":e.includes("perplexity")||e.includes("sonar")?n="perplexity":e.includes("vertex")?n="vertex_ai":(e.includes("xai")||e.includes("grok"))&&(n="xai")}e.setAttribute("gen_ai.system",n)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;const n=t.extra.metadata.invocation_params;void 0!==n.max_tokens&&e.setAttribute("gen_ai.request.max_tokens",n.max_tokens),void 0!==n.temperature&&e.setAttribute("gen_ai.request.temperature",n.temperature),void 0!==n.top_p&&e.setAttribute("gen_ai.request.top_p",n.top_p),void 0!==n.frequency_penalty&&e.setAttribute("gen_ai.request.frequency_penalty",n.frequency_penalty),void 0!==n.presence_penalty&&e.setAttribute("gen_ai.request.presence_penalty",n.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const n=t.run.inputs;"object"==typeof n&&null!==n&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(i,n.model),void 0!==n.stream&&e.setAttribute("langsmith.request.streaming",n.stream),n.extra_headers&&e.setAttribute("langsmith.request.headers",JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute("gen_ai.request.extra_query",JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute("gen_ai.request.extra_body",JSON.stringify(n.extra_body))),e.setAttribute("gen_ai.prompt",JSON.stringify(n))}catch(e){console.debug(`Failed to process inputs for run ${t.id}`,e)}if(t.run.outputs)try{const n=t.run.outputs,r=this.getUnifiedRunTokens(n);if(r&&(e.setAttribute(s,r[0]),e.setAttribute(o,r[1]),e.setAttribute(c,r[0]+r[1])),n&&"object"==typeof n){if(n.model&&e.setAttribute("gen_ai.response.model",String(n.model)),n.id&&e.setAttribute("gen_ai.response.id",n.id),n.choices&&Array.isArray(n.choices)){const t=n.choices.map(e=>e.finish_reason).filter(e=>e).map(String);t.length>0&&e.setAttribute("gen_ai.response.finish_reasons",t.join(", "))}if(n.service_tier&&e.setAttribute("gen_ai.response.service_tier",n.service_tier),n.system_fingerprint&&e.setAttribute("gen_ai.response.system_fingerprint",n.system_fingerprint),n.usage_metadata&&"object"==typeof n.usage_metadata){const t=n.usage_metadata;t.input_token_details&&e.setAttribute("gen_ai.usage.input_token_details",JSON.stringify(t.input_token_details)),t.output_token_details&&e.setAttribute("gen_ai.usage.output_token_details",JSON.stringify(t.output_token_details))}}e.setAttribute("gen_ai.completion",JSON.stringify(n))}catch(e){console.debug(`Failed to process outputs for run ${t.id}`,e)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const n=Object.keys(e);for(const r of n){const n=e[r];if(n&&"object"==typeof n){if(t=this.extractUnifiedRunTokens(n.usage_metadata),t)return t;if(1===n.lc&&n.kwargs&&"object"==typeof n.kwargs&&(t=this.extractUnifiedRunTokens(n.kwargs.usage_metadata),t))return t}}const r=e.generations||[];if(!Array.isArray(r))return null;const a=Array.isArray(r[0])?r.flat():r;for(const e of a)if("object"==typeof e&&e.message&&"object"==typeof e.message&&e.message.kwargs&&"object"==typeof e.message.kwargs&&(t=this.extractUnifiedRunTokens(e.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return e&&"object"==typeof e?"number"!=typeof e.input_tokens||"number"!=typeof e.output_tokens?null:[e.input_tokens,e.output_tokens]:null}}const b=Object.prototype.toString,E=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 x(e,t,{min:n=0,allowInfinity:r=!1}={}){if(void 0!==t){if("number"!=typeof t||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be ≥ ${n}.`)}}class I extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}function k(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function S({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:a}){const i=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(i instanceof I)throw i.originalError;const s=Number.isFinite(a.retries)?Math.max(0,a.retries-n):a.retries,o=a.maxRetryTime??Number.POSITIVE_INFINITY,c=Object.freeze({error:i,attemptNumber:t,retriesLeft:s,retriesConsumed:n});if(await a.onFailedAttempt(c),k(r,o)<=0)throw i;const d=await a.shouldConsumeRetry(c),u=k(r,o);if(u<=0||s<=0)throw i;if(i instanceof TypeError&&!function(e){var t;if(!e||(t=e,"[object Error]"!==b.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)return!1;const{message:n,stack:r}=e;return"Load failed"===n?void 0===r||"__sentry_captured__"in e:!!n.startsWith("error sending request for url")||E.has(n)}(i)){if(d)throw i;return a.signal?.throwIfAborted(),!1}if(!await a.shouldRetry(c))throw i;if(!d)return a.signal?.throwIfAborted(),!1;const l=function(e,t){const n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1;let a=Math.round(r*t.minTimeout*t.factor**(n-1));return a=Math.min(a,t.maxTimeout),a}(n,a),h=Math.min(l,u);return h>0&&await new Promise((e,t)=>{const n=()=>{clearTimeout(r),a.signal?.removeEventListener("abort",n),t(a.signal.reason)},r=setTimeout(()=>{a.signal?.removeEventListener("abort",n),e()},h);a.unref&&r.unref?.(),a.signal?.addEventListener("abort",n,{once:!0})}),a.signal?.throwIfAborted(),!0}const O=n(73290).default,T=[408,425,429,500,502,503,504];class A{constructor(e){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=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new O({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){return this.callWithOptions({},e,...t)}callWithOptions(e,t,...n){const r=e.sizeBytes??0;if(void 0!==this.maxQueueSizeBytes&&r>0&&this.queueSizeBytes+r>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${r} bytes.`));r>0&&(this.queueSizeBytes+=r);const a=this.onFailedResponseHook;let i=this.queue.add(()=>async function(e,t={}){if(function(e){if("number"==typeof e){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(void 0!==e)throw new TypeError("Expected `retries` to be a number or Infinity.")}((t={...t}).retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,x("factor",t.factor,{min:0,allowInfinity:!1}),x("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),x("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),x("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0;const a=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();const r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await S({error:e,attemptNumber:n,retriesConsumed:r,startTime:a,options:t})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}(()=>t(...n).catch(e=>{throw e instanceof Error?e:new Error(e)}),{async onFailedAttempt({error:e}){if("object"!=typeof e||null==e)throw e;const t="message"in e&&"string"==typeof e.message?e.message:void 0;if(t?.startsWith("Cancel")||t?.startsWith("TimeoutError")||t?.startsWith("AbortError"))throw e;if("name"in e&&"TimeoutError"===e.name)throw e;if("code"in e&&"ECONNABORTED"===e.code)throw e;const n="response"in e?e.response:void 0;if(a&&await a(n))return;const r=n?.status??("status"in e?e.status:void 0);if(null!=r&&("number"==typeof r||"string"==typeof r)&&!T.includes(+r))throw e},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return r>0&&(i=i.finally(()=>{this.queueSizeBytes-=r})),e.signal?Promise.race([i,new Promise((t,n)=>{e.signal?.addEventListener("abort",()=>{n(new Error("AbortError"))})})]):i}}function $(e){return"function"==typeof e?._getType}function N(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}var j=n(27843),C=n(34421),R=n(96232),P=(n(99589),n(28152));function L(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error((0,P._Q)(e));const[t,n]=e.split(":"),r=n||"latest";if(t.includes("/")){const[n,a]=t.split("/",2);if(!n||!a)throw new Error((0,P._Q)(e));return[n,a,r]}if(!t)throw new Error((0,P._Q)(e));return["-",t,r]}var M=n(3368),z=n(83805),D=n(60747),U="[...]",F={result:"[Circular]"},Z=[],B=[];const J=new TextEncoder;function q(e){return J.encode(e)}function H(e){if(e&&"object"==typeof e&&null!==e){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if("bigint"==typeof e)return e.toString();return e}function G(e,t,n,r,a){try{return q(JSON.stringify(e,(i=n,function(e,t){if(i){const n=i.call(this,e,t);if(void 0!==n)return n}return H(t)}),r))}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn("[WARNING]: LangSmith received unserializable value."+(t?`\nContext: ${t}`:"")),q("[Unserializable]");let s;"true"!==(0,u.Jz)("SUPPRESS_CIRCULAR_JSON_WARNINGS")&&console.warn("[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. "+(t?`\nContext: ${t}`:"")),void 0===a&&(a={depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}),V(e,"",0,[],void 0,0,a);try{s=0===B.length?JSON.stringify(e,n,r):JSON.stringify(e,function(e){return e=void 0!==e?e:function(e,t){return t},function(t,n){if(B.length>0)for(var r=0;r<B.length;r++){var a=B[r];if(a[1]===t&&a[0]===n){n=a[2],B.splice(r,1);break}}return e.call(this,t,n)}}(n),r)}catch(e){return q("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;0!==Z.length;){const e=Z.pop();4===e.length?Object.defineProperty(e[0],e[1],e[3]):e[0][e[1]]=e[2]}}return q(s)}var i}function Q(e,t,n,r){var a=Object.getOwnPropertyDescriptor(r,n);void 0!==a.get?a.configurable?(Object.defineProperty(r,n,{value:e}),Z.push([r,n,t,a])):B.push([t,n,e]):(r[n]=e,Z.push([r,n,t]))}function V(e,t,n,r,a,i,s){var o;if(i+=1,"object"==typeof e&&null!==e){for(o=0;o<r.length;o++)if(r[o]===e)return void Q(F,e,t,a);if(void 0!==s.depthLimit&&i>s.depthLimit)return void Q(U,e,t,a);if(void 0!==s.edgesLimit&&n+1>s.edgesLimit)return void Q(U,e,t,a);if(r.push(e),Array.isArray(e))for(o=0;o<e.length;o++)V(e[o],o,o,r,e,i,s);else{e=H(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var d=c[o];V(e[d],d,o,r,e,i,s)}}r.pop()}}function W(e){return"string"==typeof e&&e.length>0&&!e.includes("Z")&&!e.includes("+")&&!e.includes("-",10)?e+"Z":e}function K(e){return{...e,start_time:W(e.start_time),end_time:W(e.end_time)}}function Y(e,t,n){if(n)return e;const r=(0,u.Ec)(),a=t??(0,u.I6)(),i=e.extra??{},s=i.metadata;return e.extra={...i,runtime:{...r,...i?.runtime},metadata:{...a,...a.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??a.revision_id}:{},...s}},e}function X(e){if(void 0!==e)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const ee=async e=>{if(429===e?.status){const t=1e3*parseInt(e.headers.get("retry-after")??"10",10);if(t>0)return await new Promise(e=>setTimeout(e,t)),!0}return!1};function te(e){return"number"==typeof e?Number(e.toFixed(4)):e}const ne=1073741824,re="https://api.smith.langchain.com";class ae{constructor(e){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=e??ne}peek(){return this.items[0]}push(e){let t;const n=new Promise(e=>{t=e}),r=G(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+r>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${r} bytes.`),t(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:n,size:r}),this.sizeBytes+=r,n)}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const n=[];let r=0;for(;r+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<t;){const e=this.items.shift();e&&(n.push(e),r+=e.size,this.sizeBytes-=e.size)}if(0===n.length&&this.items.length>0){const e=this.items.shift();n.push(e),r+=e.size,this.sizeBytes-=e.size}return[n.map(e=>({action:e.action,item:e.payload,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,size:e.size})),()=>n.forEach(e=>e.itemPromiseResolve())]}}class ie{get _fetch(){return this.fetchImplementation||(0,D.Yx)(this.debug)}constructor(e={}){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:"false"===(0,u.Az)("LANGSMITH_TRACING_BACKGROUND")}),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:"true"===(0,u.Jz)("DISABLE_RUN_COMPRESSION")}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:104857600}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:"true"===(0,u.Az)("LANGSMITH_DEBUG")});const t=ie.getDefaultClientConfig();if(this.tracingSampleRate=(e=>{const t=e?.toString()??(0,u.Jz)("TRACING_SAMPLING_RATE");if(void 0===t)return;const n=parseFloat(t);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n})(e.tracingSamplingRate),this.apiUrl=X(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=X(e.apiKey??t.apiKey),this.webUrl=X(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=X(e.workspaceId??(0,u.Jz)("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new A({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=(0,u.Jz)("FAILED_TRACES_DIR")||void 0;const n=(0,u.Jz)("FAILED_TRACES_MAX_MB");if(n){const e=parseInt(n,10);Number.isFinite(e)&&e>0&&(this.failedTracesMaxBytes=1024*e*1024)}const r=e.maxIngestMemoryBytes??ne;this.batchIngestCaller=new A({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:r,...e.callerOptions??{},onFailedResponseHook:ee,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new ae(r),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,(0,u.QK)()&&(this.langSmithToOTELTranslator=new w),this.cachedLSEnvVarsForMetadata=(0,u.I6)(),void 0!==e.cache&&e.disablePromptCache&&(0,R.m)("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),void 0!==e.cache?((0,R.m)("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."),!1===e.cache?this._promptCache=void 0:!0===e.cache?this._promptCache=M.MP:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=M.MP)}static getDefaultClientConfig(){const e=(0,u.Jz)("API_KEY");return{apiUrl:(0,u.Jz)("ENDPOINT")??re,apiKey:e,webUrl:void 0,hideInputs:"true"===(0,u.Jz)("HIDE_INPUTS"),hideOutputs:"true"===(0,u.Jz)("HIDE_OUTPUTS")}}getHostUrl(){return this.webUrl?this.webUrl:(()=>{const e=this.apiUrl.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return"localhost"===e||"127.0.0.1"===e||"::1"===e})()?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${j.Ls}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return"/v1"!==this.apiUrl.slice(-3)&&"/v1/"!==this.apiUrl.slice(-4)?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return!1===this.hideInputs?e:!0===this.hideInputs?{}:"function"==typeof this.hideInputs?this.hideInputs(e):e}async processOutputs(e){return!1===this.hideOutputs?e:!0===this.hideOutputs?{}:"function"==typeof this.hideOutputs?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return void 0!==t.inputs&&(t.inputs=await this.processInputs(t.inputs)),void 0!==t.outputs&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const n=t?.toString()??"",r=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{const t=await this._fetch(r,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,`fetch ${e}`),t})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,n){let r=Number(t.get("offset"))||0;const a=Number(t.get("limit"))||100;for(;;){t.set("offset",String(r)),t.set("limit",String(a));const i=`${this.apiUrl}${e}?${t}`,s=await this.caller.call(async()=>{const t=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,`fetch ${e}`),t}),o=n?n(await s.json()):await s.json();if(0===o.length)break;if(yield o,o.length<a)break;r+=o.length}}async*_getCursorPaginatedList(e,t=null,n="POST",r="runs"){const a=t?{...t}:{};for(;;){const t=JSON.stringify(a),i=await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await(0,P.gJ)(r,`fetch ${e}`),r}),s=await i.json();if(!s)break;if(!s[r])break;yield s[r];const o=s.cursors;if(!o)break;if(!o.next)break;a.cursor=o.next}}_shouldSample(){return void 0===this.tracingSampleRate||Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(void 0===this.tracingSampleRate)return e;if(t){const t=[];for(const n of e)this.filteredPostUuids.has(n.trace_id)?n.id===n.trace_id&&this.filteredPostUuids.delete(n.trace_id):t.push(n);return t}{const t=[];for(const n of e){const e=n.trace_id??n.id;this.filteredPostUuids.has(e)||(n.id===e?this._shouldSample()?t.push(n):this.filteredPostUuids.add(e):t.push(n))}return t}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??25165824}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??100}async _getDatasetExamplesMultiPartSupport(){const e=await this._ensureServerInfo();return e.instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const n=[];for(;this.autoBatchQueue.items.length>0;){const[r,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!r.length){a();break}const i=r.reduce((e,t)=>{const n=t.apiUrl??this.apiUrl,r=t.apiKey??this.apiKey,a=t.apiKey===this.apiKey&&t.apiUrl===this.apiUrl?"default":`${n}|${r}`;return e[a]||(e[a]=[]),e[a].push(t),e},{}),s=[];for(const[e,t]of Object.entries(i)){const n=this._processBatch(t,{apiUrl:"default"===e?void 0:e.split("|")[0],apiKey:"default"===e?void 0:e.split("|")[1]});s.push(n)}const o=Promise.all(s).finally(a);n.push(o)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,t,n,a,i){try{const s="string"==typeof t?Buffer.from(t,"utf8"):Buffer.from(t),o=JSON.stringify({version:1,endpoint:a,headers:n,body_base64:s.toString("base64")}),c=`trace_${Date.now()}_${r.A().slice(0,8)}.json`,d=z.Ae.join(e,c);if(ie._fallbackDirsCreated.has(e)||(await z.Ck(e),ie._fallbackDirsCreated.add(e)),void 0!==i&&i>0)try{const t=(await z.Cy(e)).filter(e=>e.startsWith("trace_")&&e.endsWith(".json"));let n=0;for(const r of t){const{size:t}=await z.dJ(z.Ae.join(e,r));n+=t}if(n>=i)return void console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${n} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`)}catch{}await z.Zf(d,o),console.warn(`LangSmith trace upload failed; data saved to ${d} for later replay.`)}catch(t){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,t)}}async _processBatch(e,t){if(!e.length)return;const n=e.reduce((e,t)=>e+(t.size??0),0);try{if(void 0!==this.langSmithToOTELTranslator)this._sendBatchToOTELTranslator(e);else{const r={runCreates:e.filter(e=>"create"===e.action).map(e=>e.item),runUpdates:e.filter(e=>"update"===e.action).map(e=>e.item)},a=await this._ensureServerInfo();if(!this._multipartDisabled&&(a?.batch_ingest_config?.use_multipart_endpoint??1)){const e=!this._runCompressionDisabled&&a?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(r,{...t,useGzip:e,sizeBytes:n})}catch(e){if(!(0,P.xJ)(e))throw e;this._multipartDisabled=!0,await this.batchIngestRuns(r,{...t,sizeBytes:n})}}else await this.batchIngestRuns(r,{...t,sizeBytes:n})}}catch(e){console.error("Error exporting batch:",e)}}_sendBatchToOTELTranslator(e){if(void 0!==this.langSmithToOTELTranslator){const t=new Map,n=[];for(const r of e)r.item.id&&r.otelContext&&(t.set(r.item.id,r.otelContext),"create"===r.action?n.push({operation:"post",id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}):n.push({operation:"patch",id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}));this.langSmithToOTELTranslator.exportBatch(n,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Y(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const n=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>r)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:r})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const e=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4),...this.fetchOptions});return await(0,P.gJ)(e,"get server info"),e}),t=await e.json();return this.debug&&console.log("\n=== LangSmith Server Configuration ===\n"+JSON.stringify(t,null,2)+"\n"),t}async _ensureServerInfo(){return void 0===this._getServerInfoPromise&&(this._getServerInfoPromise=(async()=>{if(void 0===this._serverInfo)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(void 0===this._serverInfo&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=_(),t=y.getContextInstance();if(void 0!==this.langSmithToOTELTranslator){const n=e.getActiveSpan();if(n)return e.setSpan(t.active(),n)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const n={...this.headers,"Content-Type":"application/json"},r=e.project_name;delete e.project_name;const a=await this.prepareRunCreateOrUpdateInputs({session_name:r,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&void 0!==a.trace_id&&void 0!==a.dotted_order){const e=this._cloneCurrentOTELContext();return void this.processRunOperation({action:"create",item:a,otelContext:e,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error)}const i=Y(a,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);void 0!==t?.apiKey&&(n["x-api-key"]=t.apiKey),void 0!==t?.workspaceId&&(n["x-tenant-id"]=t.workspaceId);const s=G(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const e=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await(0,P.gJ)(e,"create run",!0),e})}async batchIngestRuns({runCreates:e,runUpdates:t},n){if(void 0===e&&void 0===t)return;let r=await Promise.all(e?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]),a=await Promise.all(t?.map(e=>this.prepareRunCreateOrUpdateInputs(e))??[]);if(r.length>0&&a.length>0){const e=r.reduce((e,t)=>t.id?(e[t.id]=t,e):e,{}),t=[];for(const n of a)void 0!==n.id&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);r=Object.values(e),a=t}const i={post:r,patch:a};if(!i.post.length&&!i.patch.length)return;const s={post:[],patch:[]};for(const e of["post","patch"]){const t=e,n=i[t].reverse();let r=n.pop();for(;void 0!==r;)s[t].push(r),r=n.pop()}if(s.post.length>0||s.patch.length>0){const e=s.post.map(e=>e.id).concat(s.patch.map(e=>e.id)).join(",");await this._postBatchIngestRuns(G(s,`Ingesting runs with ids: ${e}`),n)}}async _postBatchIngestRuns(e,t){const n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};void 0!==t?.apiKey&&(n["x-api-key"]=t.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:t?.sizeBytes},async()=>{const r=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await(0,P.gJ)(r,"batch create run",!0),r})}async multipartIngestRuns({runCreates:e,runUpdates:t},n){if(void 0===e&&void 0===t)return;const r={};let a=[];for(const t of e??[]){const e=await this.prepareRunCreateOrUpdateInputs(t);void 0!==e.id&&void 0!==e.attachments&&(r[e.id]=e.attachments),delete e.attachments,a.push(e)}let i=[];for(const e of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(e));if(void 0!==a.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(void 0!==i.find(e=>void 0===e.trace_id||void 0===e.dotted_order))throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&i.length>0){const e=a.reduce((e,t)=>t.id?(e[t.id]=t,e):e,{}),t=[];for(const n of i)void 0!==n.id&&e[n.id]?e[n.id]={...e[n.id],...n}:t.push(n);a=Object.values(e),i=t}if(0===a.length&&0===i.length)return;const s=[],o=[];for(const[e,t]of[["post",a],["patch",i]])for(const n of t){const{inputs:t,outputs:a,events:i,extra:c,error:d,serialized:u,attachments:l,...h}=n,p={inputs:t,outputs:a,events:i,extra:c,error:d,serialized:u},f=G(h,`Serializing for multipart ingestion of run with id: ${h.id}`);o.push({name:`${e}.${h.id}`,payload:new Blob([f],{type:`application/json; length=${f.length}`})});for(const[t,n]of Object.entries(p)){if(void 0===n)continue;const r=G(n,`Serializing ${t} for multipart ingestion of run with id: ${h.id}`);o.push({name:`${e}.${h.id}.${t}`,payload:new Blob([r],{type:`application/json; length=${r.length}`})})}if(void 0!==h.id){const e=r[h.id];if(e){delete r[h.id];for(const[t,n]of Object.entries(e)){let e,r;Array.isArray(n)?[e,r]=n:(e=n.mimeType,r=n.data),t.includes(".")?console.warn(`Skipping attachment '${t}' for run ${h.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`):o.push({name:`attachment.${h.id}.${t}`,payload:new Blob([r],{type:`${e}; length=${r.byteLength}`})})}}}s.push(`trace=${h.trace_id},id=${h.id}`)}await this._sendMultipartRequest(o,s.join("; "),n)}async _createNodeFetchBody(e,t){const n=[];for(const r of e)n.push(new Blob([`--${t}\r\n`])),n.push(new Blob([`Content-Disposition: form-data; name="${r.name}"\r\n`,`Content-Type: ${r.payload.type}\r\n\r\n`])),n.push(r.payload),n.push(new Blob(["\r\n"]));n.push(new Blob([`--${t}--\r\n`]));const r=new Blob(n);return await r.arrayBuffer()}async _createMultipartStream(e,t){const n=new TextEncoder;return new ReadableStream({async start(r){const a=async e=>{"string"==typeof e?r.enqueue(n.encode(e)):r.enqueue(e)};for(const n of e){await a(`--${t}\r\n`),await a(`Content-Disposition: form-data; name="${n.name}"\r\n`),await a(`Content-Type: ${n.payload.type}\r\n\r\n`);const e=n.payload.stream().getReader();try{let t;for(;!(t=await e.read()).done;)r.enqueue(t.value)}finally{e.releaseLock()}await a("\r\n")}await a(`--${t}--\r\n`),r.close()}})}async _sendMultipartRequest(e,t,n){const r="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=()=>this._createNodeFetchBody(e,r),i=()=>this._createMultipartStream(e,r),s=async e=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{const t=await e(),a={...this.headers,"Content-Type":`multipart/form-data; boundary=${r}`};void 0!==n?.apiKey&&(a["x-api-key"]=n.apiKey);let i=t;n?.useGzip&&"object"==typeof t&&"pipeThrough"in t&&(i=t.pipeThrough(new CompressionStream("gzip")),a["Content-Encoding"]="gzip");const s=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:a,body:i,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(s,"Failed to send multipart request",!0),s});try{let e,r=!1;(0,D.xb)()&&!this.multipartStreamingDisabled&&"bun"!==(0,u._$)()?(r=!0,e=await s(i)):e=await s(a),this.multipartStreamingDisabled&&!r||422!==e.status||(n?.apiUrl??this.apiUrl)===re||(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,e=await s(a))}catch(n){if((0,P.xJ)(n))throw n;if(console.warn(`${n.message.trim()}\n\nContext: ${t}`),this.failedTracesDir){const t=await this._createNodeFetchBody(e,r).catch(()=>null);t&&await ie._writeTraceToFallbackDir(this.failedTracesDir,t,{"Content-Type":`multipart/form-data; boundary=${r}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,t,n){(0,C.AD)(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const r={...t,id:e};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&void 0!==r.trace_id&&void 0!==r.dotted_order){const e=this._cloneCurrentOTELContext();return void 0!==t.end_time&&void 0===r.parent_run_id&&this.blockOnRootRunFinalization&&!this.manualFlushMode?void await this.processRunOperation({action:"update",item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error):void this.processRunOperation({action:"update",item:r,otelContext:e,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error)}const a={...this.headers,"Content-Type":"application/json"};void 0!==n?.apiKey&&(a["x-api-key"]=n.apiKey),void 0!==n?.workspaceId&&(a["x-tenant-id"]=n.workspaceId);const i=G(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const t=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await(0,P.gJ)(t,"update run",!0),t})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){(0,C.AD)(e);let n=K(await this._get(`/runs/${e}`));return t&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:t,projectOpts:n}){if(void 0!==t){let e;e=t.session_id?t.session_id:n?.projectName?(await this.readProject({projectName:n?.projectName})).id:n?.projectId?n?.projectId:(await this.readProject({projectName:(0,u.Jz)("PROJECT")||"default"})).id;const r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${e}/r/${t.id}?poll=true`}if(void 0!==e){const t=await this.readRun(e);if(!t.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${t.app_path}`}throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await async function(e){const t=[];for await(const n of e)t.push(n);return t}(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},r={};t.sort((e,t)=>(e?.dotted_order??"").localeCompare(t?.dotted_order??""));for(const a of t){if(null===a.parent_run_id||void 0===a.parent_run_id)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in n||(n[a.parent_run_id]=[]),n[a.parent_run_id].push(a),r[a.id]=a)}e.child_runs=n[e.id]||[];for(const t in n)t!==e.id&&(r[t].child_runs=n[t]);return e}async*listRuns(e){const{projectId:t,projectName:n,parentRunId:r,traceId:a,referenceExampleId:i,startTime:s,executionOrder:o,isRoot:c,runType:d,error:u,id:l,query:h,filter:p,traceFilter:f,treeFilter:m,limit:g,select:y,order:_}=e;let v=[];if(t&&(v=Array.isArray(t)?t:[t]),n){const e=Array.isArray(n)?n:[n],t=await Promise.all(e.map(e=>this.readProject({projectName:e}).then(e=>e.id)));v.push(...t)}const w={session:v.length?v:null,run_type:d,reference_example:i,query:h,filter:p,trace_filter:f,tree_filter:m,execution_order:o,parent_run:r,start_time:s?s.toISOString():null,error:u,id:l,limit:g,trace:a,select:y||["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"],is_root:c,order:_};w.select.includes("child_run_ids")&&(0,R.m)("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let b=0;for await(const e of this._getCursorPaginatedList("/runs/query",w)){const t=e.map(K);if(g){if(b>=g)break;if(t.length+b>g){const e=t.slice(0,g-b);yield*e;break}b+=t.length,yield*t}else yield*t}}async*listGroupRuns(e){const{projectId:t,projectName:n,groupBy:r,filter:a,startTime:i,endTime:s,limit:o,offset:c}=e,d={session_id:t||(await this.readProject({projectName:n})).id,group_by:r,filter:a,start_time:i?i.toISOString():null,end_time:s?s.toISOString():null,limit:Number(o)||100};let u=Number(c)||0;const l="/runs/group",h=`${this.apiUrl}${l}`;for(;;){const e={...d,offset:u},t=Object.fromEntries(Object.entries(e).filter(([e,t])=>void 0!==t)),n=JSON.stringify(t),r=await this.caller.call(async()=>{const e=await this._fetch(h,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await(0,P.gJ)(e,`Failed to fetch ${l}`),e}),a=await r.json(),{groups:i,total:s}=a;if(0===i.length)break;for(const e of i)yield e;if(u+=i.length,u>=s)break}}async*readThread(e){const{threadId:t,projectId:n,projectName:r,isRoot:a=!0,limit:i,filter:s,order:o="asc"}=e;if(!n&&!r)throw new Error("threadId requires projectId or projectName");const c=`eq(thread_id, ${JSON.stringify(t)})`,d=s?`and(${c}, ${s})`:c;yield*this.listRuns({projectId:n??void 0,projectName:r??void 0,isRoot:a,limit:i,filter:d,order:o})}async listThreads(e){const{projectId:t,projectName:n,limit:r,offset:a=0,filter:i,startTime:s,isRoot:o=!0}=e;if(!t&&!n)throw new Error("Either projectId or projectName must be provided");if(t&&n)throw new Error("Provide exactly one of projectId or projectName");const c={session:[t??(await this.readProject({projectName:n})).id],is_root:o,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:(s??new Date(Date.now()-864e5)).toISOString()};null!=i&&(c.filter=i);const d=new Map;for await(const e of this._getCursorPaginatedList("/runs/query",c))for(const t of e){const e=K(t),n=e.thread_id;if(n){const t=d.get(n)??[];t.push(e),d.set(n,t)}}const u=[];for(const[e,t]of d.entries()){t.sort((e,t)=>{const n=e,r=t,a=n.start_time??"",i=r.start_time??"";if(a!==i)return a.localeCompare(i);const s=n.dotted_order??"",o=r.dotted_order??"";return s.localeCompare(o)});const n=[...t.map(e=>e.start_time).filter(Boolean)].sort(),r=n.length?n[0]:"",a=n.length?n[n.length-1]:"";u.push({thread_id:e,runs:t,count:t.length,filter:"",total_tokens:0,total_cost:null,min_start_time:r,max_start_time:a,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}u.sort((e,t)=>{const n=e.max_start_time??"";return(t.max_start_time??"").localeCompare(n)});const l=a>0?u.slice(a):u;return void 0!==r?l.slice(0,r):l}async getRunStats({id:e,trace:t,parentRun:n,runType:r,projectNames:a,projectIds:i,referenceExampleIds:s,startTime:o,endTime:c,error:d,query:u,filter:l,traceFilter:h,treeFilter:p,isRoot:f,dataSourceType:m}){let g=i||[];a&&(g=[...i||[],...await Promise.all(a.map(e=>this.readProject({projectName:e}).then(e=>e.id)))]);const y={id:e,trace:t,parent_run:n,run_type:r,session:g,reference_example:s,start_time:o,end_time:c,error:d,query:u,filter:l,trace_filter:h,tree_filter:p,is_root:f,data_source_type:m},_=Object.fromEntries(Object.entries(y).filter(([e,t])=>void 0!==t)),v=JSON.stringify(_),w=await this.caller.call(async()=>{const e=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:v});return await(0,P.gJ)(e,"get run stats"),e});return await w.json()}async shareRun(e,{shareId:t}={}){const n={run_id:e,share_token:t||r.A()};(0,C.AD)(e);const a=JSON.stringify(n),i=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await(0,P.gJ)(t,"share run"),t}),s=await i.json();if(null===s||!("share_token"in s))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${s.share_token}/r`}async unshareRun(e){(0,C.AD)(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"unshare run",!0),t})}async readRunSharedLink(e){(0,C.AD)(e);const t=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"read run shared link"),t}),n=await t.json();if(null!==n&&"share_token"in n)return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const n=new URLSearchParams({share_token:e});if(void 0!==t)for(const e of t)n.append("id",e);(0,C.AD)(e);const r=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"list shared runs"),t});return(await r.json()).map(K)}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){const n=await this.readDataset({datasetName:t});e=n.id}(0,C.AD)(e);const n=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"read dataset shared schema"),t}),r=await n.json();return r.url=`${this.getHostUrl()}/public/${r.share_token}/d`,r}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");if(!e){const n=await this.readDataset({datasetName:t});e=n.id}const n={dataset_id:e};(0,C.AD)(e);const r=JSON.stringify(n),a=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await(0,P.gJ)(t,"share dataset"),t}),i=await a.json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){(0,C.AD)(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"unshare dataset",!0),t})}async readSharedDataset(e){(0,C.AD)(e);const t=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"read shared dataset"),t});return await t.json()}async listSharedExamples(e,t){const n={};t?.exampleIds&&(n.id=t.exampleIds);const r=new URLSearchParams;Object.entries(n).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>r.append(e,t)):r.append(e,t)});const a=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/public/${e}/examples?${r.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"list shared examples"),t}),i=await a.json();if(!a.ok){if("detail"in i)throw new Error(`Failed to list shared examples.\nStatus: ${a.status}\nMessage: ${Array.isArray(i.detail)?i.detail.join("\n"):"Unspecified error"}`);throw new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`)}return i.map(e=>({...e,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:n=null,upsert:r=!1,projectExtra:a=null,referenceDatasetId:i=null}){const s=r?"?upsert=true":"",o=`${this.apiUrl}/sessions${s}`,c=a||{};n&&(c.metadata=n);const d={name:e,extra:c,description:t};null!==i&&(d.reference_dataset_id=i);const u=JSON.stringify(d),l=await this.caller.call(async()=>{const e=await this._fetch(o,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await(0,P.gJ)(e,"create project"),e});return await l.json()}async updateProject(e,{name:t=null,description:n=null,metadata:r=null,projectExtra:a=null,endTime:i=null}){const s=`${this.apiUrl}/sessions/${e}`;let o=a;r&&(o={...o||{},metadata:r});const c=JSON.stringify({name:t,extra:o,description:n,end_time:i?new Date(i).toISOString():null}),d=await this.caller.call(async()=>{const e=await this._fetch(s,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await(0,P.gJ)(e,"update project"),e});return await d.json()}async hasProject({projectId:e,projectName:t}){let n="/sessions";const r=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)(0,C.AD)(e),n+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");r.append("name",t)}const a=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}${n}?${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,"has project"),e});try{const e=await a.json();return!!a.ok&&(!Array.isArray(e)||e.length>0)}catch(e){return!1}}async readProject({projectId:e,projectName:t,includeStats:n}){let r="/sessions";const a=new URLSearchParams;if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");if(void 0!==e)(0,C.AD)(e),r+=`/${e}`;else{if(void 0===t)throw new Error("Must provide projectName or projectId");a.append("name",t)}void 0!==n&&a.append("include_stats",n.toString());const i=await this._get(r,a);let s;if(Array.isArray(i)){if(0===i.length)throw new Error(`Project[id=${e}, name=${t}] not found`);s=i[0]}else s=i;return s}async getProjectUrl({projectId:e,projectName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:e,projectName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(void 0===e&&void 0===t)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:e,datasetName:t}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/datasets/${n.id}`}async _getTenantId(){if(null!==this._tenantId)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:n,referenceDatasetId:r,referenceDatasetName:a,includeStats:i,datasetVersion:s,referenceFree:o,metadata:c}={}){const d=new URLSearchParams;if(void 0!==e)for(const t of e)d.append("id",t);if(void 0!==t&&d.append("name",t),void 0!==n&&d.append("name_contains",n),void 0!==r)d.append("reference_dataset",r);else if(void 0!==a){const e=await this.readDataset({datasetName:a});d.append("reference_dataset",e.id)}void 0!==i&&d.append("include_stats",i.toString()),void 0!==s&&d.append("dataset_version",s),void 0!==o&&d.append("reference_free",o.toString()),void 0!==c&&d.append("metadata",JSON.stringify(c));for await(const e of this._getPaginated("/sessions",d))yield*e}async deleteProject({projectId:e,projectName:t}){let n;if(void 0===e&&void 0===t)throw new Error("Must provide projectName or projectId");if(void 0!==e&&void 0!==t)throw new Error("Must provide either projectName or projectId, not both");n=void 0===e?(await this.readProject({projectName:t})).id:e,(0,C.AD)(n),await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,`delete session ${n} (${t})`,!0),e})}async uploadCsv({csvFile:e,fileName:t,inputKeys:n,outputKeys:r,description:a,dataType:i,name:s}){const o=`${this.apiUrl}/datasets/upload`,c=new FormData,d=new Blob([e],{type:"text/csv"});c.append("file",d,t),n.forEach(e=>{c.append("input_keys",e)}),r.forEach(e=>{c.append("output_keys",e)}),a&&c.append("description",a),i&&c.append("data_type",i),s&&c.append("name",s);const u=await this.caller.call(async()=>{const e=await this._fetch(o,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await(0,P.gJ)(e,"upload CSV"),e});return await u.json()}async createDataset(e,{description:t,dataType:n,inputsSchema:r,outputsSchema:a,metadata:i}={}){const s={name:e,description:t,extra:{source:"sdk",...i?{metadata:i}:{}}};n&&(s.data_type=n),r&&(s.inputs_schema_definition=r),a&&(s.outputs_schema_definition=a);const o=JSON.stringify(s),c=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await(0,P.gJ)(e,"create dataset"),e});return await c.json()}async readDataset({datasetId:e,datasetName:t}){let n="/datasets";const r=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)(0,C.AD)(e),n+=`/${e}`;else{if(!t)throw new Error("Must provide datasetName or datasetId");r.append("name",t)}const a=await this._get(n,r);let i;if(Array.isArray(a)){if(0===a.length)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(e){if(e instanceof Error&&e.message.toLocaleLowerCase().includes("not found"))return!1;throw e}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:n,toVersion:r}){let a=e;if(void 0===a&&void 0===t)throw new Error("Must provide either datasetName or datasetId");if(void 0!==a&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");void 0===a&&(a=(await this.readDataset({datasetName:t})).id);const i=new URLSearchParams({from_version:"string"==typeof n?n:n.toISOString(),to_version:"string"==typeof r?r:r.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){if(void 0!==e);else{if(void 0===t)throw new Error("Must provide either datasetName or datasetId");e=(await this.readDataset({datasetName:t})).id}const n=await this._getResponse(`/datasets/${e}/openai_ft`);return(await n.text()).trim().split("\n").map(e=>JSON.parse(e))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:n,datasetName:r,datasetNameContains:a,metadata:i}={}){const s=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(void 0!==n)for(const e of n)s.append("id",e);void 0!==r&&s.append("name",r),void 0!==a&&s.append("name_contains",a),void 0!==i&&s.append("metadata",JSON.stringify(i));for await(const e of this._getPaginated("/datasets",s))yield*e}async updateDataset(e){const{datasetId:t,datasetName:n,...r}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:n})).id;(0,C.AD)(a);const i=JSON.stringify(r),s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await(0,P.gJ)(e,"update dataset"),e});return await s.json()}async updateDatasetTag(e){const{datasetId:t,datasetName:n,asOf:r,tag:a}=e;if(!t&&!n)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:n})).id;(0,C.AD)(i);const s=JSON.stringify({as_of:"string"==typeof r?r:r.toISOString(),tag:a});await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await(0,P.gJ)(e,"update dataset tags",!0),e})}async deleteDataset({datasetId:e,datasetName:t}){let n="/datasets",r=e;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==t&&(r=(await this.readDataset({datasetName:t})).id),void 0===r)throw new Error("Must provide datasetName or datasetId");(0,C.AD)(r),n+=`/${r}`,await this.caller.call(async()=>{const e=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,`delete ${n}`,!0),e})}async indexDataset({datasetId:e,datasetName:t,tag:n}){let r=e;if(!r&&!t)throw new Error("Must provide either datasetName or datasetId");if(r&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(!r){const e=await this.readDataset({datasetName:t});r=e.id}(0,C.AD)(r);const a={tag:n},i=JSON.stringify(a),s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${r}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await(0,P.gJ)(e,"index dataset"),e});await s.json()}async similarExamples(e,t,n,{filter:r}={}){const a={limit:n,inputs:e};void 0!==r&&(a.filter=r),(0,C.AD)(t);const i=JSON.stringify(a),s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await(0,P.gJ)(e,"fetch similar examples"),e});return(await s.json()).examples}async createExample(e,t,n){if(se(e)&&(void 0!==t||void 0!==n))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=t?n?.datasetId:e.dataset_id;const i=t?n?.datasetName:e.dataset_name;if(void 0===a&&void 0===i)throw new Error("Must provide either datasetName or datasetId");if(void 0!==a&&void 0!==i)throw new Error("Must provide either datasetName or datasetId, not both");void 0===a&&(a=(await this.readDataset({datasetName:i})).id);const s=(t?n?.createdAt:e.created_at)||new Date;let o;o=se(e)?e:{inputs:e,outputs:t,created_at:s?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};const c=await this._uploadExamplesMultipart(a,[o]);return await this.readExample(c.example_ids?.[0]??r.A())}async createExamples(e){if(Array.isArray(e)){if(0===e.length)return[];const t=e;let n=t[0].dataset_id;const r=t[0].dataset_name;if(void 0===n&&void 0===r)throw new Error("Must provide either datasetName or datasetId");if(void 0!==n&&void 0!==r)throw new Error("Must provide either datasetName or datasetId, not both");void 0===n&&(n=(await this.readDataset({datasetName:r})).id);const a=await this._uploadExamplesMultipart(n,t);return await Promise.all(a.example_ids.map(e=>this.readExample(e)))}const{inputs:t,outputs:n,metadata:r,splits:a,sourceRunIds:i,useSourceRunIOs:s,useSourceRunAttachments:o,attachments:c,exampleIds:d,datasetId:u,datasetName:l}=e;if(void 0===t)throw new Error("Must provide inputs when using legacy parameters");let h=u;const p=l;if(void 0===h&&void 0===p)throw new Error("Must provide either datasetName or datasetId");if(void 0!==h&&void 0!==p)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===h){const e=await this.readDataset({datasetName:p});h=e.id}const f=t.map((e,t)=>({dataset_id:h,inputs:e,outputs:n?.[t],metadata:r?.[t],split:a?.[t],id:d?.[t],attachments:c?.[t],source_run_id:i?.[t],use_source_run_io:s?.[t],use_source_run_attachments:o?.[t]})),m=await this._uploadExamplesMultipart(h,f);return await Promise.all(m.example_ids.map(e=>this.readExample(e)))}async createLLMExample(e,t,n){return this.createExample({input:e},{output:t},n)}async createChatExample(e,t,n){const r=e.map(e=>$(e)?N(e):e),a=$(t)?N(t):t;return this.createExample({input:r},{output:a},n)}async readExample(e){(0,C.AD)(e);const t=`/examples/${e}`,n=await this._get(t),{attachment_urls:r,...a}=n,i=a;return r&&(i.attachments=Object.entries(r).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type},e),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:n,asOf:r,splits:a,inlineS3Urls:i,metadata:s,limit:o,offset:c,filter:d,includeAttachments:u}={}){let l;if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0!==e)l=e;else{if(void 0===t)throw new Error("Must provide a datasetName or datasetId");l=(await this.readDataset({datasetName:t})).id}const h=new URLSearchParams({dataset:l}),p=r?"string"==typeof r?r:r?.toISOString():void 0;p&&h.append("as_of",p);const f=i??!0;if(h.append("inline_s3_urls",f.toString()),void 0!==n)for(const e of n)h.append("id",e);if(void 0!==a)for(const e of a)h.append("splits",e);if(void 0!==s){const e=JSON.stringify(s);h.append("metadata",e)}void 0!==o&&h.append("limit",o.toString()),void 0!==c&&h.append("offset",c.toString()),void 0!==d&&h.append("filter",d),!0===u&&["attachment_urls","outputs","metadata"].forEach(e=>h.append("select",e));let m=0;for await(const e of this._getPaginated("/examples",h)){for(const t of e){const{attachment_urls:e,...n}=t,r=n;e&&(r.attachments=Object.entries(e).reduce((e,[t,n])=>(e[t.slice(11)]={presigned_url:n.presigned_url,mime_type:n.mime_type||void 0},e),{})),yield r,m++}if(void 0!==o&&m>=o)break}}async deleteExample(e){(0,C.AD)(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const e=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,`delete ${t}`,!0),e})}async deleteExamples(e,t){if(e.forEach(e=>(0,C.AD)(e)),t?.hardDelete){const t=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}${t}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(n,"hard delete examples",!0),n})}else{const t=new URLSearchParams;e.forEach(e=>t.append("example_ids",e)),await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/examples?${t.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,"delete examples",!0),e})}}async updateExample(e,t){let n,r,a;return n=t?e:e.id,(0,C.AD)(n),r=t?{id:n,...t}:e,a=void 0!==r.dataset_id?r.dataset_id:(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(a,[r])}async updateExamples(e){let t;return t=void 0===e[0].dataset_id?(await this.readExample(e[0].id)).dataset_id:e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:n,tag:r}){let a;if(e)a=e;else{const e=await this.readDataset({datasetName:t});a=e.id}if((0,C.AD)(a),n&&r||!n&&!r)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;void 0!==n&&i.append("as_of","string"==typeof n?n:n.toISOString()),void 0!==r&&i.append("tag",r);const s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,"read dataset version"),e});return await s.json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:n}){let r;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");r=void 0===e?(await this.readDataset({datasetName:t})).id:e,(0,C.AD)(r);const a=new URLSearchParams,i=n?"string"==typeof n?n:n?.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${r}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:n,exampleIds:r,remove:a=!1}){let i;if(void 0===e&&void 0===t)throw new Error("Must provide dataset name or ID");if(void 0!==e&&void 0!==t)throw new Error("Must provide either datasetName or datasetId, not both");if(void 0===e){const e=await this.readDataset({datasetName:t});i=e.id}else i=e;(0,C.AD)(i);const s={split_name:n,examples:r.map(e=>((0,C.AD)(e),e)),remove:a},o=JSON.stringify(s);await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await(0,P.gJ)(e,"update dataset splits",!0),e})}async createFeedback(e,t,{score:n,value:r,correction:i,comment:s,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:d,feedbackId:u,feedbackConfig:l,projectId:h,comparativeExperimentId:p,sessionId:f,startTime:m}){if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)throw new Error("Only one of runId or projectId can be provided");const g={type:c??"api",metadata:o??{}};void 0===d||void 0===g?.metadata||g.metadata.__run||(g.metadata.__run={run_id:d}),void 0!==g?.metadata&&void 0!==g.metadata.__run?.run_id&&(0,C.AD)(g.metadata.__run.run_id);const y={id:u??a.A(),run_id:e,key:t,score:te(n),value:r,correction:i,comment:s,feedback_source:g,comparative_experiment_id:p,feedbackConfig:l,session_id:f??h,start_time:m},_=JSON.stringify(y),v=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const e=await this._fetch(v,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await(0,P.gJ)(e,"create feedback",!0),e}),y}async updateFeedback(e,{score:t,value:n,correction:r,comment:a}){const i={};null!=t&&(i.score=te(t)),null!=n&&(i.value=n),null!=r&&(i.correction=r),null!=a&&(i.comment=a),(0,C.AD)(e);const s=JSON.stringify(i);await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await(0,P.gJ)(t,"update feedback",!0),t})}async readFeedback(e){(0,C.AD)(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){(0,C.AD)(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const e=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,`delete ${t}`,!0),e})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:n}={}){const r=new URLSearchParams;if(e)for(const t of e)(0,C.AD)(t),r.append("run",t);if(t)for(const e of t)r.append("key",e);if(n)for(const e of n)r.append("source",e);for await(const e of this._getPaginated("/feedback",r))yield*e}async createPresignedFeedbackToken(e,t,{expiration:n,feedbackConfig:r}={}){const a={run_id:e,feedback_key:t,feedback_config:r};n?"string"==typeof n?a.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(a.expires_in=n):a.expires_in={hours:3};const i=JSON.stringify(a),s=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await(0,P.gJ)(e,"create presigned feedback token"),e});return await s.json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:n,createdAt:r,description:a,metadata:i,id:s}){if(0===t.length)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:t[0]})).reference_dataset_id),null==!n)throw new Error("A reference dataset is required");const o={id:s,name:e,experiment_ids:t,reference_dataset_id:n,description:a,created_at:(r??new Date)?.toISOString(),extra:{}};i&&(o.extra.metadata=i);const c=JSON.stringify(o);return(await this.caller.call(async()=>{const e=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:c});return await(0,P.gJ)(e,"create comparative experiment"),e})).json()}async*listPresignedFeedbackTokens(e){(0,C.AD)(e);const t=new URLSearchParams({run_id:e});for await(const e of this._getPaginated("/feedback/tokens",t))yield*e}_selectEvalResults(e){let t;return t="results"in e?e.results:Array.isArray(e)?e:[e],t}async _logEvaluationFeedback(e,t,n){const r=this._selectEvalResults(e),a=[];for(const e of r){let r=n||{};e.evaluatorInfo&&(r={...e.evaluatorInfo,...r});let i=null;e.targetRunId?i=e.targetRunId:t&&(i=t.id),a.push(await this.createFeedback(i,e.key,{score:e.score,value:e.value,comment:e.comment,correction:e.correction,sourceInfo:r,sourceRunId:e.sourceRunId,feedbackConfig:e.feedbackConfig,feedbackSourceType:"model",sessionId:t?.session_id,startTime:t?.start_time}))}return[r,a]}async logEvaluationFeedback(e,t,n){const[r]=await this._logEvaluationFeedback(e,t,n);return r}async createFeedbackConfig(e){const{feedbackKey:t,feedbackConfig:n,isLowerScoreBetter:r=!1}=e,a={feedback_key:t,feedback_config:n,is_lower_score_better:r};return(await this.caller.call(async()=>{const e=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(a)});return await(0,P.gJ)(e,"create feedback config"),e})).json()}async*listFeedbackConfigs(e={}){const{feedbackKeys:t,nameContains:n,limit:r}=e,a=new URLSearchParams;t&&t.forEach(e=>{a.append("key",e)}),n&&a.append("name_contains",n),a.append("limit",(void 0!==r?Math.min(r,100):100).toString());let i=0;for await(const e of this._getPaginated("/feedback-configs",a))if(yield*e,i+=e.length,void 0!==r&&i>=r)break}async updateFeedbackConfig(e,t={}){const{feedbackConfig:n,isLowerScoreBetter:r}=t,a={feedback_key:e};return void 0!==n&&(a.feedback_config=n),void 0!==r&&(a.is_lower_score_better=r),(await this.caller.call(async()=>{const e=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(a)});return await(0,P.gJ)(e,"update feedback config"),e})).json()}async deleteFeedbackConfig(e){const t=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/feedback-configs?${t}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,"delete feedback config",!0),e})}async*listAnnotationQueues(e={}){const{queueIds:t,name:n,nameContains:r,limit:a}=e,i=new URLSearchParams;t&&t.forEach((e,t)=>{(0,C.AD)(e,`queueIds[${t}]`),i.append("ids",e)}),n&&i.append("name",n),r&&i.append("name_contains",r),i.append("limit",(void 0!==a?Math.min(a,100):100).toString());let s=0;for await(const e of this._getPaginated("/annotation-queues",i))if(yield*e,s++,void 0!==a&&s>=a)break}async createAnnotationQueue(e){const{name:t,description:n,queueId:a,rubricInstructions:i,rubricItems:s}=e,o={name:t,description:n,id:a||r.A(),rubric_instructions:i,rubric_items:s},c=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([e,t])=>void 0!==t)));return(await this.caller.call(async()=>{const e=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:c});return await(0,P.gJ)(e,"create annotation queue"),e})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,C.AD)(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"read annotation queue"),t})).json()}async updateAnnotationQueue(e,t){const{name:n,description:r,rubricInstructions:a,rubricItems:i}=t,s={};void 0!==n&&(s.name=n),void 0!==r&&(s.description=r),void 0!==a&&(s.rubric_instructions=a),void 0!==i&&(s.rubric_items=i);const o=JSON.stringify(s);await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,C.AD)(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await(0,P.gJ)(t,"update annotation queue",!0),t})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,C.AD)(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const n=JSON.stringify(t.map((e,t)=>(0,C.AD)(e,`runIds[${t}]`).toString()));await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,C.AD)(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await(0,P.gJ)(t,"add runs to annotation queue",!0),t})}async getRunFromAnnotationQueue(e,t){const n=`/annotation-queues/${(0,C.AD)(e,"queueId")}/run`,r=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}${n}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,"get run from annotation queue"),e});return K(await r.json())}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,C.AD)(e,"queueId")}/runs/${(0,C.AD)(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${(0,C.AD)(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"get size from annotation queue"),t})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return"-"==e||t.tenant_handle===e}async _ownerConflictError(e,t){const n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.\n\n Current tenant: ${n.tenant_handle}\n\n Requested tenant: ${t}`)}async _getLatestCommitHash(e){const t=await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(t,"get latest commit hash"),t}),n=await t.json();if(0!==n.commits.length)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[n,r,a]=L(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/likes/${n}/${r}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await(0,P.gJ)(e,(t?"like":"unlike")+" prompt"),e})).json()}async _getPromptUrl(e){const[t,n,r]=L(e);if(await this._currentTenantIsOwner(t)){const e=await this._getSettings();return"latest"!==r?`${this.getHostUrl()}/prompts/${n}/${r.substring(0,8)}?organizationId=${e.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${e.id}`}return"latest"!==r?`${this.getHostUrl()}/hub/${t}/${n}/${r.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){const[t,n,r]=L(e);for await(const e of this._getPaginated(`/commits/${t}/${n}/`,new URLSearchParams,e=>e.commits))yield*e}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),void 0!==e?.isPublic&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const e of this._getPaginated("/repos",t,e=>e.repos))yield*e}async getPrompt(e){const[t,n,r]=L(e),a=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return 404===e?.status?null:(await(0,P.gJ)(e,"get prompt"),e)}),i=await(a?.json());return i?.repo?i.repo:null}async createPrompt(e,t){const n=await this._getSettings();if(t?.isPublic&&!n.tenant_handle)throw new Error("Cannot create a public prompt without first\n\n creating a LangChain Hub handle.\n You can add a handle by creating a public prompt at:\n\n https://smith.langchain.com/prompts");const[r,a,i]=L(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("create a prompt",r);const s={repo_handle:a,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},o=JSON.stringify(s),c=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await(0,P.gJ)(e,"create prompt"),e}),{repo:d}=await c.json();return d}async createCommit(e,t,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,a,i]=L(e),s="latest"!==n?.parentCommitHash&&n?.parentCommitHash?n?.parentCommitHash:await this._getLatestCommitHash(`${r}/${a}`),o={manifest:JSON.parse(JSON.stringify(t)),parent_commit:s},c=JSON.stringify(o),d=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/commits/${r}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await(0,P.gJ)(e,"create commit"),e}),u=await d.json();return this._getPromptUrl(`${r}/${a}${u.commit_hash?`:${u.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const e of t){const t=e.id,r=G({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`),a=new Blob([r],{type:"application/json"});if(n.append(t,a),e.inputs){const r=G(e.inputs,`Serializing inputs for example with id: ${t}`),a=new Blob([r],{type:"application/json"});n.append(`${t}.inputs`,a)}if(e.outputs){const r=G(e.outputs,`Serializing outputs whle updating example with id: ${t}`),a=new Blob([r],{type:"application/json"});n.append(`${t}.outputs`,a)}if(e.attachments)for(const[r,a]of Object.entries(e.attachments)){let e,i;Array.isArray(a)?[e,i]=a:(e=a.mimeType,i=a.data);const s=new Blob([i],{type:`${e}; length=${i.byteLength}`});n.append(`${t}.attachment.${r}`,s)}if(e.attachments_operations){const r=G(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`),a=new Blob([r],{type:"application/json"});n.append(`${t}.attachments_operations`,a)}}const r=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${r}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await(0,P.gJ)(e,"update examples"),e})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const e of t){const t=(e.id??r.A()).toString(),a=G({created_at:e.created_at,...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split},...e.source_run_id&&{source_run_id:e.source_run_id},...e.use_source_run_io&&{use_source_run_io:e.use_source_run_io},...e.use_source_run_attachments&&{use_source_run_attachments:e.use_source_run_attachments}},`Serializing body for uploaded example with id: ${t}`),i=new Blob([a],{type:"application/json"});if(n.append(t,i),e.inputs){const r=G(e.inputs,`Serializing inputs for uploaded example with id: ${t}`),a=new Blob([r],{type:"application/json"});n.append(`${t}.inputs`,a)}if(e.outputs){const r=G(e.outputs,`Serializing outputs for uploaded example with id: ${t}`),a=new Blob([r],{type:"application/json"});n.append(`${t}.outputs`,a)}if(e.attachments)for(const[r,a]of Object.entries(e.attachments)){let e,i;Array.isArray(a)?[e,i]=a:(e=a.mimeType,i=a.data);const s=new Blob([i],{type:`${e}; length=${i.byteLength}`});n.append(`${t}.attachment.${r}`,s)}}return(await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await(0,P.gJ)(t,"upload examples"),t})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,r]=L(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const a={};if(void 0!==t?.description&&(a.description=t.description),void 0!==t?.readme&&(a.readme=t.readme),void 0!==t?.tags&&(a.tags=t.tags),void 0!==t?.isPublic&&(a.is_public=t.isPublic),void 0!==t?.isArchived&&(a.is_archived=t.isArchived),0===Object.keys(a).length)throw new Error("No valid update options provided");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await(0,P.gJ)(e,"update prompt"),e})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,n,r]=L(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,"delete prompt"),e})).json()}_getPromptCacheKey(e,t){return`${e}${t?":with_model":""}`}async _fetchPromptFromApi(e,t){const[n,r,a]=L(e),i=await this.caller.call(async()=>{const e=await this._fetch(`${this.apiUrl}/commits/${n}/${r}/${a}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await(0,P.gJ)(e,"pull prompt commit"),e}),s=await i.json();return{owner:n,repo:r,commit_hash:s.commit_hash,manifest:s.manifest,examples:s.examples}}async pullPromptCommit(e,t){const n=this._fetchPromptFromApi.bind(this,e,t);if(!t?.skipCache&&this._promptCache){const r=this._getPromptCacheKey(e,t?.includeModel),a=this._promptCache.get(r,n);if(a)return a;const i=await n();return this._promptCache.set(r,i,n),i}return this._fetchPromptFromApi(e,t)}async _pullPrompt(e,t){const n=await this.pullPromptCommit(e,{includeModel:t?.includeModel,skipCache:t?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(e=>"object"!==e)&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){const{sourceApiUrl:n=this.apiUrl,datasetName:r}=t,[a,i]=this.parseTokenOrUrl(e,n),s=new ie({apiUrl:a,apiKey:"placeholder"}),o=await s.readSharedDataset(i),c=r||o.name;try{if(await this.hasDataset({datasetId:c}))return void console.log(`Dataset ${c} already exists in your tenant. Skipping.`)}catch(e){}const d=await s.listSharedExamples(i),u=await this.createDataset(c,{description:o.description,dataType:o.data_type||"kv",inputsSchema:o.inputs_schema_definition??void 0,outputsSchema:o.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(e=>e.inputs),outputs:d.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:u.id})}catch(e){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,n=2,r="dataset"){try{return(0,C.AD)(e),[t,e]}catch(e){}try{const a=new URL(e).pathname.split("/").filter(e=>""!==e);if(a.length>=n)return[t,a[a.length-n]];throw new Error(`Invalid public ${r} URL: ${e}`)}catch(t){throw new Error(`Invalid public ${r} URL or token: ${e}`)}}cleanup(){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();await new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),void 0!==this.langSmithToOTELTranslator&&await(y.getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush())}}function se(e){return"dataset_id"in e||"dataset_name"in e}Object.defineProperty(ie,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set})},27843(e,t,n){n.d(t,{Kj:()=>r.Kj,gk:()=>a.gk,Ls:()=>s,q7:()=>i.q});var r=n(51906),a=n(84880),i=(n(60747),n(90639));n(34421),n(3368);const s="0.5.16"},84880(e,t,n){n.d(t,{gk:()=>I,sh:()=>w});var r=n(51906),a=n(24785),i=n(28152);const s=Symbol.for("lc:context_variables"),o=(Symbol.for("lc:child_run_end_promises"),Symbol.for("langsmith:replica_trace_roots"));function c(e,t){if(s in e)return e[s][t]}var d=n(90639),u=n(96232),l=n(34421),h=n(38823);const p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i,f=function(e){if(!function(e){return"string"==typeof e&&p.test(e)}(e))throw TypeError("Invalid UUID");var t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=255&t,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=255&t,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=255&t,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=255&t,n};function m(e,t,n,r){switch(e){case 0:return t&n^~t&r;case 1:case 3:return t^n^r;case 2:return t&n^t&r^n&r}}function g(e,t){return e<<t|e>>>32-t}const y=function(){function e(e,t,n,r){var a;if("string"==typeof e&&(e=function(e){e=unescape(encodeURIComponent(e));for(var t=[],n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}(e)),"string"==typeof t&&(t=f(t)),16!==(null===(a=t)||void 0===a?void 0:a.length))throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var i=new Uint8Array(16+e.length);if(i.set(t),i.set(e,t.length),(i=function(e){var t=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof e){var r=unescape(encodeURIComponent(e));e=[];for(var a=0;a<r.length;++a)e.push(r.charCodeAt(a))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var i=e.length/4+2,s=Math.ceil(i/16),o=new Array(s),c=0;c<s;++c){for(var d=new Uint32Array(16),u=0;u<16;++u)d[u]=e[64*c+4*u]<<24|e[64*c+4*u+1]<<16|e[64*c+4*u+2]<<8|e[64*c+4*u+3];o[c]=d}o[s-1][14]=8*(e.length-1)/Math.pow(2,32),o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=8*(e.length-1)&4294967295;for(var l=0;l<s;++l){for(var h=new Uint32Array(80),p=0;p<16;++p)h[p]=o[l][p];for(var f=16;f<80;++f)h[f]=g(h[f-3]^h[f-8]^h[f-14]^h[f-16],1);for(var y=n[0],_=n[1],v=n[2],w=n[3],b=n[4],E=0;E<80;++E){var x=Math.floor(E/20),I=g(y,5)+m(x,_,v,w)+b+t[x]+h[E]>>>0;b=w,w=v,v=g(_,30)>>>0,_=y,y=I}n[0]=n[0]+y>>>0,n[1]=n[1]+_>>>0,n[2]=n[2]+v>>>0,n[3]=n[3]+w>>>0,n[4]=n[4]+b>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]}(i))[6]=15&i[6]|80,i[8]=63&i[8]|128,n){r=r||0;for(var s=0;s<16;++s)n[r+s]=i[s];return n}return(0,h.k)(i)}try{e.name="v5"}catch(e){}return e.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",e.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",e}();function _(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]??""}`).join("|");return y(t,"6ba7b810-9dad-11d1-80b4-00c04fd430c8")}function v(e,t=1){const n=t.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(e).toISOString().slice(0,-1)}${n}Z`}function w(e,t,n=1){const r=v(e,n);return{dottedOrder:(a=r,a.replace(/[-:.]/g,"")+t),microsecondPrecisionDatestring:r};var a}const b=new Set(["projectName","updates","reroot"]);function E(e){const t={};for(const n of Object.keys(e))b.has(n)&&(t[n]=e[n]);return t}class x{constructor(e,t,n,r){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=e,this.tags=t,this.project_name=n,this.replicas=r}static fromHeader(e){const t=e.split(",");let n,r,a={},i=[];for(const e of t){const[t,s]=e.split("="),o=decodeURIComponent(s);"langsmith-metadata"===t?a=JSON.parse(o):"langsmith-tags"===t?i=o.split(","):"langsmith-project"===t?n=o:"langsmith-replicas"===t&&(r=JSON.parse(o).map(e=>Array.isArray(e)?e:E(e)))}return new x(a,i,n,r)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class I{constructor(e){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}),null!=(t=e)&&"function"==typeof t.createChild&&"function"==typeof t.postRun)return void Object.assign(this,{...e});var t;const n=I.getDefaultConfig(),{metadata:r,...s}=e,o=s.client??I.getSharedClient(),c={...r,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:c},"id"in s&&null==s.id&&delete s.id,Object.assign(this,{...n,...s,client:o}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=v(this.start_time,this.execution_order)),this.id||(this.id=(0,l.Y6)(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=(d=this.replicas)?d.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):function(){const e=(0,a.Az)("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{const t=JSON.parse(e);if(Array.isArray(t)){const e=[];for(const n of t)"object"==typeof n&&null!==n?"string"==typeof n.api_url?"string"==typeof n.api_key?e.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key}):console.warn("Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got "+typeof n.api_key):console.warn("Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got "+typeof n.api_url):console.warn("Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got "+typeof n);return e}if("object"==typeof t&&null!==t){!function(e){if(Object.keys(e).length>0&&(0,a.Jz)("ENDPOINT"))throw new i.tE}(t);const e=[];for(const[n,r]of Object.entries(t)){const t=n.replace(/\/$/,"");"string"==typeof r?e.push({apiUrl:t,apiKey:r}):console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got `+typeof r)}return e}return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got "+typeof t),[]}catch(e){if((0,i.J_)(e))throw e;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"),[]}}(),!this.dotted_order){const{dottedOrder:e}=w(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+e:this.dotted_order=e}var d}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){const e=Date.now();return{run_type:"chain",project_name:(0,d.q)(),child_runs:[],api_url:(0,a.Az)("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:(0,a.Az)("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return I.sharedClient||(I.sharedClient=new r.Kj),I.sharedClient}createChild(e){const t=this.child_execution_order+1,n=this.replicas?.map(e=>{const{reroot:t,...n}=e;return n}),r=e.replicas??n,a=new I({...e,parent_run:this,project_name:this.project_name,replicas:r,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t}),i=this.extra?.metadata??{},o=a.extra?.metadata??{};Object.keys(i).length>0&&(a.extra={...a.extra,metadata:{...i,...o}}),s in this&&(a[s]=this[s]);const c=Symbol.for("lc:child_config"),d=e.extra?.[c]??this.extra[c];if(function(e){const t=e?.callbacks;return null!=e&&"object"==typeof t&&(S(t?.handlers)||S(t))}(d)){const e={...d},t="object"==typeof(u=e.callbacks)&&null!=u&&Array.isArray(u.handlers)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:a.id}),t.handlers?.find(k)?.updateFromRunTree?.(a),e.callbacks=t),a.extra[c]=e}var u;const l=new Set;let h=this;for(;null!=h&&!l.has(h.id);)l.add(h.id),h.child_execution_order=Math.max(h.child_execution_order,t),h=h.parent_run;return this.child_runs.push(a),a}async end(e,t,n=Date.now(),r){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,r&&Object.keys(r).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...r}}:{metadata:r})}_convertToCreate(e,t,n=!0){const r=e.extra??{};if(void 0===r?.runtime?.library&&(r.runtime||(r.runtime={}),t))for(const[e,n]of Object.entries(t))r.runtime[e]||(r.runtime[e]=n);const a=e.parent_run?.id??e.parent_run_id;let i;return i=n?[]:e.child_runs.map(e=>this._convertToCreate(e,t,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:r,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:i,parent_run_id:a,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,t){if(t.dotted_order){const n=t.dotted_order.split(".");let r=null;for(let t=0;t<n.length;t++)if(n[t].slice(-36)===e){r=t;break}if(null!==r){const e=n.slice(r+1);t.dotted_order=e.join("."),e.length>0?t.trace_id=e[0].slice(-36):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){const n=c(this,o)??{};n[e]=t,function(e,t,n){const r=s in e?e[s]:{};r[t]=n,e[s]=r}(this,o,n);for(const n of this.child_runs)n._setReplicaTraceRoot(e,t)}_remapForProject(e){const{projectName:t,runtimeEnv:n,excludeChildRuns:r=!0,reroot:a=!1,distributedParentId:i,apiUrl:s,apiKey:d,workspaceId:u}=e,h=this._convertToCreate(this,n,r);if(t===this.project_name)return{...h,session_name:t};if(a){if(i)this._sliceParentId(i,h);else if(h.parent_run_id=void 0,h.dotted_order){const e=h.dotted_order.split(".");e.length>0&&(h.dotted_order=e[e.length-1],h.trace_id=h.id)}const e=_({projectName:t,apiUrl:s,apiKey:d,workspaceId:u});this._setReplicaTraceRoot(e,h.id)}let p;if(!a&&(p=(c(this,o)??{})[_({projectName:t,apiUrl:s,apiKey:d,workspaceId:u})],p&&(h.trace_id=p,h.dotted_order))){const e=h.dotted_order.split(".");let t=null;for(let n=0;n<e.length;n++)if(e[n].slice(-36)===p){t=n;break}if(null!==t){const n=e.slice(t);h.dotted_order=n.join(".")}}const f=h.id,m=(0,l.pe)(f,t);let g,y,v;return g=h.trace_id?(0,l.pe)(h.trace_id,t):m,h.parent_run_id&&(y=(0,l.pe)(h.parent_run_id,t)),h.dotted_order&&(v=h.dotted_order.split(".").map(e=>{const n=e.slice(-36),r=(0,l.pe)(n,t);return e.slice(0,-36)+r}).join(".")),{...h,id:m,trace_id:g,parent_run_id:y,dotted_order:v,session_name:t}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{const t=(0,a.Ec)();if(this.replicas&&this.replicas.length>0)for(const{projectName:e,apiKey:n,apiUrl:r,workspaceId:a,reroot:i}of this.replicas){const s=this._remapForProject({projectName:e??this.project_name,runtimeEnv:t,excludeChildRuns:!0,reroot:i,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:a});await this.client.createRun(s,{apiKey:n,apiUrl:r,workspaceId:a})}else{const n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){(0,u.m)("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const e of this.child_runs)await e.postRun(!1)}this.child_runs=[]}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:t,apiKey:n,apiUrl:r,workspaceId:a,updates:i,reroot:s}of this.replicas){const o=this._remapForProject({projectName:t??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:s,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:a}),c={id:o.id,name:o.name,run_type:o.run_type,start_time:o.start_time,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...i};e?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:n,apiUrl:r,workspaceId:a})}else try{const t={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};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),"string"==typeof e?this.events.push({name:"event",time:(new Date).toISOString(),message:e}):this.events.push({...e,time:e.time??(new Date).toISOString()})}static fromRunnableConfig(e,t){const n=e?.callbacks;let r,i,s,o=!!["TRACING_V2","TRACING"].find(e=>"true"===(0,a.Jz)(e));if(n){const e=n?.getParentRunId?.()??"",t=n?.handlers?.find(e=>"langchain_tracer"==e?.name);r=t?.getRun?.(e),i=t?.projectName,s=t?.client,o=o||!!t}return r?new I({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:s,tracingEnabled:o,project_name:i,tags:[...new Set((r?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...e?.metadata}}}).createChild(t):new I({...t,client:s,tracingEnabled:o,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const n="get"in e&&"function"==typeof e.get?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,r=n["langsmith-trace"];if(!r||"string"!=typeof r)return;const a=r.trim(),i=a.split(".").map(e=>{const[t,n]=e.split("Z");return{strTime:t,time:Date.parse(t+"Z"),uuid:n}}),s=i[0].uuid,o={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:s,dotted_order:a};if(n.baggage&&"string"==typeof n.baggage){const e=x.fromHeader(n.baggage);o.metadata=e.metadata,o.tags=e.tags,o.project_name=e.project_name,o.replicas=e.replicas}const c=new I(o);return c.distributedParentId=c.id,c}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new x(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[n,r]of Object.entries(t))e.set(n,r);return t}}function k(e){return"object"==typeof e&&null!=e&&"string"==typeof e.name&&"langchain_tracer"===e.name}function S(e){return Array.isArray(e)&&e.some(e=>k(e))}Object.defineProperty(I,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null})},60747(e,t,n){n.d(t,{Yx:()=>o,xb:()=>s});var r=n(24785);const a=(...e)=>fetch(...e);const i=Symbol.for("ls:fetch_implementation"),s=()=>void 0===globalThis[i]||!1,o=e=>async(...t)=>{if(e||"true"===(0,r.Jz)("DEBUG")){const[e,n]=t;console.log(`→ ${n?.method||"GET"} ${e}`)}const n=await(globalThis[i]??a)(...t);return(e||"true"===(0,r.Jz)("DEBUG"))&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n}},34421(e,t,n){n.d(t,{AD:()=>F,pe:()=>J,Y6:()=>Z});var r=n(41167);n(96232);const a=e=>BigInt(e),i=a("0x9E3779B1"),s=a("0x85EBCA77"),o=a("0xC2B2AE3D"),c=a("0x9E3779B185EBCA87"),d=a("0xC2B2AE3D27D4EB4F"),u=a("0x165667B19E3779F9"),l=a("0x85EBCA77C2B2AE63"),h=a("0x27D4EB2F165667C5"),p=a("0x165667919E3779F9"),f=a("0x9FB21C651E98DF25"),m=function(e){const t=new Uint8Array(192);for(let n=0;n<384;n+=2)t[n/2]=parseInt(e.substring(n,n+2),16);return t}("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),g=(a(1)<<a(128))-a(1),y=(a(1)<<a(64))-a(1),_=(a(1)<<a(32))-a(1),v=64;function w(e,t=0){return new Uint8Array(e.buffer,e.byteOffset+t,e.length-t)}function b(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getBigUint64(0,!0)}function E(e,t=0){return new DataView(e.buffer,e.byteOffset+t).getUint32(0,!0)}function x(e,t=0){return e[t]}const I=(e,t)=>(e&_)*(t&_)&y,k=e=>{if(!e)throw new Error("Assert failed")};function S(e,t,n){for(let r=0;r<8;r++){const i=b(t,8*r),s=i^b(n,8*r);e[1^r]+=i,e[r]+=I(s,s>>a(32))}return e}function O(e,t,n,r){for(let a=0;a<r;a++)S(e,w(t,a*v),w(n,8*a));return e}function T(e,t){for(let n=0;n<8;n++){const r=b(t,8*n);let s=e[n];s=L(s,a(47)),s^=r,s*=i,e[n]=s&y}return e}function A(e,t){return N(e[0]^b(t,0),e[1]^b(t,8))}function $(e,t,n){let r=n;return r+=A(e.slice(0),w(t,0)),r+=A(e.slice(2),w(t,16)),r+=A(e.slice(4),w(t,32)),r+=A(e.slice(6),w(t,48)),R(r&y)}function N(e,t){const n=e*t&g;return n&y^n>>a(64)}function j(e,t,n){return N((b(e,0)^b(t,0)+n)&y,(b(e,8)^b(t,8)-n)&y)}function C(e,t,n,r,i){let s=e&y,o=e>>a(64)&y;return s+=j(t,r,i),s^=b(n,0)+b(n,8),s&=y,o+=j(n,w(r,16),i),o^=b(t,0)+b(t,8),o&=y,o<<a(64)|s}function R(e){return e^=e>>a(37),e*=p,(e&=y)^e>>a(32)}function P(e){return e^=e>>a(33),e*=d,e&=y,e^=e>>a(29),e*=u,(e&=y)^e>>a(32)}function L(e,t){return e^e>>t}function M(e,t){const n=e.byteLength;return k(n<=16),n>8?function(e,t,n){const r=e.byteLength;k(r>=9&&r<=16);{const o=(b(t,32)^b(t,40))+n&y,u=(b(t,48)^b(t,56))-n&y,l=b(e);let h=b(e,r-8),p=(l^h^o)*c;const f=(p&y)+(a(r-1)<<a(54));p=p&(g^y)|f,h^=u,p+=h+(h&_)*(s-a(1))<<a(64),p&=g,p^=((i=p>>a(64))&a(255))<<a(56)|(i&a(65280))<<a(40)|(i&a(16711680))<<a(24)|(i&a(4278190080))<<a(8)|(i&a(0xff00000000))>>a(8)|(i&a(0xff0000000000))>>a(24)|(i&a(0xff000000000000))>>a(40)|(i&a(0xff00000000000000))>>a(56);let m=(p&y)*d;return m+=(p>>a(64))*d<<a(64),m&=g,R(m&y)|R(m>>a(64))<<a(64)}var i}(e,m,t):n>=4?function(e,t,n){const r=e.byteLength;k(r>=4&&r<=8);{const i=E(e,0),s=E(e,r-4);let o=((a(i)|a(s)<<a(32))^(b(t,16)^b(t,24))+n&y)*(c+(a(r)<<a(2)))&g;return o+=(o&y)<<a(65),o&=g,o^=o>>a(67),L(L(o&y,a(35))*f&y,a(28))|R(o>>a(64))<<a(64)}}(e,m,t):n>0?function(e,t,n){const r=e.byteLength;k(r>0&&r<=3);const i=a(x(e,r-1))|a(r<<8)|a(x(e,0)<<16)|a(x(e,r>>1)<<24),s=(i^(a(E(t,0))^a(E(t,4)))+n)&y,o=(a(E(t,8))^a(E(t,12)))-n;var c;return(P((function(e,t){return(e<<t|e>>a(32)-t)&_}(((c=((c=i)&a(65535))<<a(16)|(c&a(4294901760))>>a(16))&a(16711935))<<a(8)|(c&a(4278255360))>>a(8),a(13))^o)&y)&y)<<a(64)|P(s)}(e,m,t):P(t^b(m,64)^b(m,72))|P(t^b(m,80)^b(m,88))<<a(64)}function z(e){return~e+a(1)&y}function D(e,t=a(0)){const n=e.byteLength;return n<=16?M(e,t):n<=128?function(e,t,n){let r=a(e.byteLength)*c&y,i=a(e.byteLength-1)/a(32);for(;i>=0;){const a=Number(i);r=C(r,w(e,16*a),w(e,e.byteLength-16*(a+1)),w(t,32*a),n),i--}let s=r+(r>>a(64))&y;s=R(s);let o=(r&y)*c+(r>>a(64))*l+(a(e.byteLength)-n&y)*d;return o&=y,o=z(R(o)),s|o<<a(64)}(e,m,t):n<=240?function(e,t,n){let r=a(e.byteLength)*c&y;for(let a=32;a<160;a+=32)r=C(r,w(e,a-32),w(e,a-16),w(t,a-32),n);r=R(r&y)|R(r>>a(64))<<a(64);for(let a=160;a<=e.byteLength;a+=32)r=C(r,w(e,a-32),w(e,a-16),w(t,3+a-160),n);r=C(r,w(e,e.byteLength-16),w(e,e.byteLength-32),w(t,103),z(n));let i=r+(r>>a(64))&y;i=R(i);let s=(r&y)*c+(r>>a(64))*l+(a(e.byteLength)-n&y)*d;return s&=y,s=z(R(s)),i|s<<a(64)}(e,m,t):function(e,t){let n=new BigUint64Array([o,c,d,u,l,s,h,i]);k(e.length>128),n=function(e,t,n,r,a){const i=Math.floor((n.byteLength-v)/8),s=v*i,o=Math.floor((t.byteLength-1)/s);for(let r=0;r<o;r++)e=a(e=O(e,w(t,r*s),n,i),w(n,n.byteLength-v));{const a=Math.floor((t.byteLength-1-s*o)/v);e=r(e=O(e,w(t,o*s),n,a),w(t,t.byteLength-v),w(n,n.byteLength-v-7))}return e}(n,e,t,S,T),k(8*n.length==64);{const r=$(n,w(t,11),a(e.byteLength)*c&y);return $(n,w(t,t.byteLength-v-11),~(a(e.byteLength)*d)&y)<<a(64)|r}}(e,m)}const U=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function F(e,t){if(!U.test(e))throw new Error(void 0!==t?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`);return e}function Z(e){const t="string"==typeof e?Date.parse(e):e;return(0,r.A)({msecs:t,seq:0})}const B=new TextEncoder;function J(e,t){const n=(i=`${e}:${t}`,function(e){const t=new Uint8Array(16),n=new DataView(t.buffer),r=e&y,i=e>>a(64);return n.setBigUint64(0,i,!1),n.setBigUint64(8,r,!1),t}(D(B.encode(i)))),r=new Uint8Array(16);var i;if(7===function(e){if(!U.test(e))return null;const t=e[14];return parseInt(t,16)}(e)){const t=function(e){const t=e.replace(/-/g,""),n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=parseInt(t.slice(2*e,2*e+2),16);return n}(e);r.set(t.slice(0,6),0)}else{const e=Date.now();r[0]=e/1099511627776&255,r[1]=e/4294967296&255,r[2]=e/16777216&255,r[3]=e/65536&255,r[4]=e/256&255,r[5]=255&e}return r[6]=112|15&n[0],r[7]=n[1],r[8]=128|63&n[2],r.set(n.slice(3,10),9),function(e){const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}(r)}},24785(e,t,n){n.d(t,{Az:()=>l,Ec:()=>d,I6:()=>u,Jz:()=>h,QK:()=>p,_$:()=>s});var r=n(27843);let a;const i=()=>"undefined"!=typeof Deno,s=()=>a||(a="undefined"!=typeof Bun?"bun":"undefined"!=typeof window&&void 0!==window.document?"browser":"undefined"==typeof process||void 0===process.versions||void 0===process.versions.node||i()?"object"==typeof globalThis&&globalThis.constructor&&"DedicatedWorkerGlobalScope"===globalThis.constructor.name?"webworker":"undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&navigator.userAgent.includes("jsdom")?"jsdom":i()?"deno":"other":"node",a);let o,c;function d(){if(void 0===o){const e=s(),t=function(){if(void 0!==c)return c;const e=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(const n of e){const e=l(n);void 0!==e&&(t[n]=e)}return c=t,t}();o={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:r.Ls,...t}}return o}function u(){const e=function(){const e={};try{if("undefined"!=typeof process&&process.env)for(const[t,n]of Object.entries(process.env))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&null!=n&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&"string"==typeof n?e[t]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):e[t]=n)}catch(e){}return e}(),t={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,a]of Object.entries(e))"string"!=typeof a||n.includes(r)||r.toLowerCase().includes("key")||r.toLowerCase().includes("secret")||r.toLowerCase().includes("token")||("LANGCHAIN_REVISION_ID"===r?t.revision_id=a:t[r]=a);return t}function l(e){try{return"undefined"!=typeof process?process.env?.[e]:void 0}catch(e){return}}function h(e){return l(`LANGSMITH_${e}`)||l(`LANGCHAIN_${e}`)}function p(){return"true"===l("OTEL_ENABLED")||"true"===h("OTEL_ENABLED")}},28152(e,t,n){function r(e){return`Invalid prompt identifier format: "${e}". Expected one of:\n - "prompt-name" (for private prompts)\n - "owner/prompt-name" (for prompts with explicit owner)\n - "prompt-name:commit-hash" (with commit reference)\n - "owner/prompt-name:commit-hash" (with owner and commit)`}n.d(t,{J_:()=>u,_Q:()=>r,gJ:()=>o,tE:()=>d,xJ:()=>s});class a extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class i extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function s(e){return null!=e&&"object"==typeof e&&"name"in e&&"LangSmithNotFoundError"===e?.name}async function o(e,t,n){let r;if(e.ok)return void(n&&(r=await e.text()));if(403===e.status)try{const t=await e.json(),n=t?.error;"org_scoped_key_requires_workspace"===n&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch(t){const n=new Error(`${e.status} ${e.statusText}`);throw n.status=e?.status,n}if(void 0===r)try{r=await e.text()}catch(e){r=""}const s=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${r}`;if(404===e.status)throw new i(s);if(409===e.status)throw new a(s);const o=new Error(s);throw o.status=e.status,o}const c="ERR_CONFLICTING_ENDPOINTS";class d 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:c}),this.name="ConflictingEndpointsError"}}function u(e){return"object"==typeof e&&null!==e&&e.code===c}},83805(e,t,n){n.d(t,{Ae:()=>r,Ck:()=>a,Cy:()=>s,Hu:()=>d,Un:()=>p,Zf:()=>i,dJ:()=>o,mN:()=>c,qs:()=>l,vP:()=>h,zp:()=>u});const r={join:(...e)=>e.join("/"),dirname:e=>e.split("/").slice(0,-1).join("/")};async function a(e){}async function i(e,t){}async function s(e){return[]}async function o(e){return{size:0}}function c(e){return!1}function d(e){}function u(e,t){}function l(e,t){}function h(e){}function p(e){return""}},90639(e,t,n){n.d(t,{q:()=>a});var r=n(24785);const a=()=>(0,r.Jz)("PROJECT")??(0,r.Az)("LANGCHAIN_SESSION")??"default"},3368(e,t,n){n.d(t,{MP:()=>i});var r=n(83805);function a(e,t){return null!==t&&Date.now()-e.createdAt>1e3*t}const i=new class{constructor(e={}){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(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){const e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,t){if(0===this.maxSize)return;const n=this.cache.get(e);if(n)return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:t}),this._metrics.hits+=1,n.value;this._metrics.misses+=1}set(e,t,n){if(0===this.maxSize)return;if(void 0===this.refreshTimer&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}const r={value:t,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,r)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){const t={};for(const[e,n]of this.cache.entries())t[e]=n.value;const n=r.Ae.dirname(e);(0,r.mN)(n)||(0,r.Hu)(n);const a=`${e}.tmp`;try{(0,r.zp)(a,JSON.stringify({entries:t},null,2)),(0,r.qs)(a,e)}catch(e){throw(0,r.mN)(a)&&(0,r.vP)(a),e}}load(e){if(!(0,r.mN)(e))return 0;let t;try{const n=(0,r.Un)(e);t=JSON.parse(n).entries??null}catch{return 0}if(!t)return 0;let n=0;const a=Date.now();for(const[e,r]of Object.entries(t)){if(this.cache.size>=this.maxSize)break;const t={value:r,createdAt:a};this.cache.set(e,t),n+=1}return n}startRefreshLoop(){this.stop(),null!==this.ttlSeconds&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},1e3*this.refreshIntervalSeconds),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){const e=[];for(const[t,n]of this.cache.entries())a(n,this.ttlSeconds)&&e.push([t,n]);return e}async refreshStaleEntries(){const e=this.getStaleEntries();if(0!==e.length)for(const[t,n]of e)if(void 0!==n.refreshFunc)try{const e=await n.refreshFunc();this.set(t,e,n.refreshFunc),this._metrics.refreshes+=1}catch(e){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${t}:`,e)}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}}},96232(e,t,n){n.d(t,{m:()=>a});const r={};function a(e){r[e]||(console.warn(e),r[e]=!0)}},31259(e,t,n){n.d(t,{Kj:()=>r.Kj,gk:()=>r.gk,q7:()=>r.q7});var r=n(27843)},51688(e,t,n){n.d(t,{gk:()=>r.gk,sh:()=>r.sh});var r=n(84880)},63389(e,t,n){n.d(t,{vR:()=>s,GZ:()=>o});const r=Symbol.for("ls:tracing_async_local_storage"),a=new class{getStore(){}run(e,t){return t()}},i=new class{getInstance(){return globalThis[r]??a}initializeGlobalInstance(e){void 0===globalThis[r]&&(globalThis[r]=e)}};function s(e=!1){const t=i.getInstance().getStore();if(!e&&void 0===t)throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled.");return t}function o(e){return"function"==typeof e&&"langsmith:traceable"in e}Symbol.for("langsmith:traceable:root")},1038(e,t,n){n.d(t,{kY:()=>qe,z:()=>i});var r,a,i={};n.r(i),n.d(i,{BRAND:()=>ze,DIRTY:()=>w,EMPTY_PATH:()=>g,INVALID:()=>v,NEVER:()=>Nt,OK:()=>b,ParseStatus:()=>_,Schema:()=>$,ZodAny:()=>de,ZodArray:()=>pe,ZodBigInt:()=>re,ZodBoolean:()=>ae,ZodBranded:()=>De,ZodCatch:()=>Le,ZodDate:()=>ie,ZodDefault:()=>Pe,ZodDiscriminatedUnion:()=>_e,ZodEffects:()=>je,ZodEnum:()=>Ae,ZodError:()=>u,ZodFirstPartyTypeKind:()=>qe,ZodFunction:()=>ke,ZodIntersection:()=>we,ZodIssueCode:()=>c,ZodLazy:()=>Se,ZodLiteral:()=>Oe,ZodMap:()=>xe,ZodNaN:()=>Me,ZodNativeEnum:()=>$e,ZodNever:()=>le,ZodNull:()=>ce,ZodNullable:()=>Re,ZodNumber:()=>ne,ZodObject:()=>me,ZodOptional:()=>Ce,ZodParsedType:()=>s,ZodPipeline:()=>Ue,ZodPromise:()=>Ne,ZodReadonly:()=>Fe,ZodRecord:()=>Ee,ZodSchema:()=>$,ZodSet:()=>Ie,ZodString:()=>ee,ZodSymbol:()=>se,ZodTransformer:()=>je,ZodTuple:()=>be,ZodType:()=>$,ZodUndefined:()=>oe,ZodUnion:()=>ge,ZodUnknown:()=>ue,ZodVoid:()=>he,addIssueToContext:()=>y,any:()=>nt,array:()=>st,bigint:()=>We,boolean:()=>Ke,coerce:()=>$t,custom:()=>Be,date:()=>Ye,datetimeRegex:()=>W,defaultErrorMap:()=>l,discriminatedUnion:()=>ut,effect:()=>Et,enum:()=>vt,function:()=>gt,getErrorMap:()=>f,getParsedType:()=>o,instanceof:()=>He,intersection:()=>lt,isAborted:()=>E,isAsync:()=>k,isDirty:()=>x,isValid:()=>I,late:()=>Je,lazy:()=>yt,literal:()=>_t,makeIssue:()=>m,map:()=>ft,nan:()=>Ve,nativeEnum:()=>wt,never:()=>at,null:()=>tt,nullable:()=>It,number:()=>Qe,object:()=>ot,objectUtil:()=>a,oboolean:()=>At,onumber:()=>Tt,optional:()=>xt,ostring:()=>Ot,pipeline:()=>St,preprocess:()=>kt,promise:()=>bt,quotelessJson:()=>d,record:()=>pt,set:()=>mt,setErrorMap:()=>p,strictObject:()=>ct,string:()=>Ge,symbol:()=>Xe,transformer:()=>Et,tuple:()=>ht,undefined:()=>et,union:()=>dt,unknown:()=>rt,util:()=>r,void:()=>it}),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const n of e)t[n]=n;return t},e.getValidEnumValues=t=>{const n=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(const n of e)if(t(n))return n},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(r||(r={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(a||(a={}));const s=r.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),o=e=>{switch(typeof e){case"undefined":return s.undefined;case"string":return s.string;case"number":return Number.isNaN(e)?s.nan:s.number;case"boolean":return s.boolean;case"function":return s.function;case"bigint":return s.bigint;case"symbol":return s.symbol;case"object":return Array.isArray(e)?s.array:null===e?s.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?s.promise:"undefined"!=typeof Map&&e instanceof Map?s.map:"undefined"!=typeof Set&&e instanceof Set?s.set:"undefined"!=typeof Date&&e instanceof Date?s.date:s.object;default:return s.unknown}},c=r.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),d=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class u extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(const a of e.issues)if("invalid_union"===a.code)a.unionErrors.map(r);else if("invalid_return_type"===a.code)r(a.returnTypeError);else if("invalid_arguments"===a.code)r(a.argumentsError);else if(0===a.path.length)n._errors.push(t(a));else{let e=n,r=0;for(;r<a.path.length;){const n=a.path[r];r===a.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(a))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(e){if(!(e instanceof u))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,r.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t=Object.create(null),n=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}u.create=e=>new u(e);const l=(e,t)=>{let n;switch(e.code){case c.invalid_type:n=e.received===s.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case c.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,r.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:n=`Unrecognized key(s) in object: ${r.joinValues(e.keys,", ")}`;break;case c.invalid_union:n="Invalid input";break;case c.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${r.joinValues(e.options)}`;break;case c.invalid_enum_value:n=`Invalid enum value. Expected ${r.joinValues(e.options)}, received '${e.received}'`;break;case c.invalid_arguments:n="Invalid function arguments";break;case c.invalid_return_type:n="Invalid function return type";break;case c.invalid_date:n="Invalid date";break;case c.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:r.assertNever(e.validation):n="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case c.too_small:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case c.too_big:n="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case c.custom:n="Invalid input";break;case c.invalid_intersection_types:n="Intersection results could not be merged";break;case c.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case c.not_finite:n="Number must be finite";break;default:n=t.defaultError,r.assertNever(e)}return{message:n}};let h=l;function p(e){h=e}function f(){return h}const m=e=>{const{data:t,path:n,errorMaps:r,issueData:a}=e,i=[...n,...a.path||[]],s={...a,path:i};if(void 0!==a.message)return{...a,path:i,message:a.message};let o="";const c=r.filter(e=>!!e).slice().reverse();for(const e of c)o=e(s,{data:t,defaultError:o}).message;return{...a,path:i,message:o}},g=[];function y(e,t){const n=f(),r=m({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===l?void 0:l].filter(e=>!!e)});e.common.issues.push(r)}class _{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if("aborted"===r.status)return v;"dirty"===r.status&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const e of t){const t=await e.key,r=await e.value;n.push({key:t,value:r})}return _.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:t,value:a}=r;if("aborted"===t.status)return v;if("aborted"===a.status)return v;"dirty"===t.status&&e.dirty(),"dirty"===a.status&&e.dirty(),"__proto__"===t.value||void 0===a.value&&!r.alwaysSet||(n[t.value]=a.value)}return{status:e.value,value:n}}}const v=Object.freeze({status:"aborted"}),w=e=>({status:"dirty",value:e}),b=e=>({status:"valid",value:e}),E=e=>"aborted"===e.status,x=e=>"dirty"===e.status,I=e=>"valid"===e.status,k=e=>"undefined"!=typeof Promise&&e instanceof Promise;var S;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(S||(S={}));class O{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const T=(e,t)=>{if(I(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new u(e.common.issues);return this._error=t,this._error}}};function A(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:a}=e;if(t&&(n||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:a}:{errorMap:(t,a)=>{const{message:i}=e;return"invalid_enum_value"===t.code?{message:i??a.defaultError}:void 0===a.data?{message:i??r??a.defaultError}:"invalid_type"!==t.code?{message:a.defaultError}:{message:i??n??a.defaultError}},description:a}}class ${get description(){return this._def.description}_getType(e){return o(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _,ctx:{common:e.parent.common,data:e.data,parsedType:o(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(k(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},r=this._parseSync({data:e,path:n.path,parent:n});return T(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return I(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>I(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:o(e)},r=this._parse({data:e,path:n.path,parent:n}),a=await(k(r)?r:Promise.resolve(r));return T(n,a)}refine(e,t){const n=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const a=e(t),i=()=>r.addIssue({code:c.custom,...n(t)});return"undefined"!=typeof Promise&&a instanceof Promise?a.then(e=>!!e||(i(),!1)):!!a||(i(),!1)})}refinement(e,t){return this._refinement((n,r)=>!!e(n)||(r.addIssue("function"==typeof t?t(n,r):t),!1))}_refinement(e){return new je({schema:this,typeName:qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Ce.create(this,this._def)}nullable(){return Re.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pe.create(this)}promise(){return Ne.create(this,this._def)}or(e){return ge.create([this,e],this._def)}and(e){return we.create(this,e,this._def)}transform(e){return new je({...A(this._def),schema:this,typeName:qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Pe({...A(this._def),innerType:this,defaultValue:t,typeName:qe.ZodDefault})}brand(){return new De({typeName:qe.ZodBranded,type:this,...A(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Le({...A(this._def),innerType:this,catchValue:t,typeName:qe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ue.create(this,e)}readonly(){return Fe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const N=/^c[^\s-]{8,}$/i,j=/^[0-9a-z]+$/,C=/^[0-9A-HJKMNP-TV-Z]{26}$/i,R=/^[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}$/i,P=/^[a-z0-9_-]{21}$/i,L=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,M=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,z=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let D;const U=/^(?:(?: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])$/,F=/^(?:(?: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])$/,Z=/^(([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]))$/,B=/^(([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])$/,J=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,q=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,H="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",G=new RegExp(`^${H}$`);function Q(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function V(e){return new RegExp(`^${Q(e)}$`)}function W(e){let t=`${H}T${Q(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function K(e,t){return!("v4"!==t&&t||!U.test(e))||!("v6"!==t&&t||!Z.test(e))}function Y(e,t){if(!L.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),a=JSON.parse(atob(r));return!("object"!=typeof a||null===a||"typ"in a&&"JWT"!==a?.typ||!a.alg||t&&a.alg!==t)}catch{return!1}}function X(e,t){return!("v4"!==t&&t||!F.test(e))||!("v6"!==t&&t||!B.test(e))}class ee extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==s.string){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.string,received:t.parsedType}),v}const t=new _;let n;for(const a of this._def.checks)if("min"===a.kind)e.data.length<a.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:c.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("max"===a.kind)e.data.length>a.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if("length"===a.kind){const r=e.data.length>a.value,i=e.data.length<a.value;(r||i)&&(n=this._getOrReturnCtx(e,n),r?y(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):i&&y(n,{code:c.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if("email"===a.kind)z.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"email",code:c.invalid_string,message:a.message}),t.dirty());else if("emoji"===a.kind)D||(D=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),D.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"emoji",code:c.invalid_string,message:a.message}),t.dirty());else if("uuid"===a.kind)R.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"uuid",code:c.invalid_string,message:a.message}),t.dirty());else if("nanoid"===a.kind)P.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"nanoid",code:c.invalid_string,message:a.message}),t.dirty());else if("cuid"===a.kind)N.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cuid",code:c.invalid_string,message:a.message}),t.dirty());else if("cuid2"===a.kind)j.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cuid2",code:c.invalid_string,message:a.message}),t.dirty());else if("ulid"===a.kind)C.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"ulid",code:c.invalid_string,message:a.message}),t.dirty());else if("url"===a.kind)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),y(n,{validation:"url",code:c.invalid_string,message:a.message}),t.dirty()}else"regex"===a.kind?(a.regex.lastIndex=0,a.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"regex",code:c.invalid_string,message:a.message}),t.dirty())):"trim"===a.kind?e.data=e.data.trim():"includes"===a.kind?e.data.includes(a.value,a.position)||(n=this._getOrReturnCtx(e,n),y(n,{code:c.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty()):"toLowerCase"===a.kind?e.data=e.data.toLowerCase():"toUpperCase"===a.kind?e.data=e.data.toUpperCase():"startsWith"===a.kind?e.data.startsWith(a.value)||(n=this._getOrReturnCtx(e,n),y(n,{code:c.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty()):"endsWith"===a.kind?e.data.endsWith(a.value)||(n=this._getOrReturnCtx(e,n),y(n,{code:c.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty()):"datetime"===a.kind?W(a).test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:c.invalid_string,validation:"datetime",message:a.message}),t.dirty()):"date"===a.kind?G.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:c.invalid_string,validation:"date",message:a.message}),t.dirty()):"time"===a.kind?V(a).test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:c.invalid_string,validation:"time",message:a.message}),t.dirty()):"duration"===a.kind?M.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"duration",code:c.invalid_string,message:a.message}),t.dirty()):"ip"===a.kind?K(e.data,a.version)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"ip",code:c.invalid_string,message:a.message}),t.dirty()):"jwt"===a.kind?Y(e.data,a.alg)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"jwt",code:c.invalid_string,message:a.message}),t.dirty()):"cidr"===a.kind?X(e.data,a.version)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cidr",code:c.invalid_string,message:a.message}),t.dirty()):"base64"===a.kind?J.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"base64",code:c.invalid_string,message:a.message}),t.dirty()):"base64url"===a.kind?q.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"base64url",code:c.invalid_string,message:a.message}),t.dirty()):r.assertNever(a);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:c.invalid_string,...S.errToObj(n)})}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...S.errToObj(e)})}url(e){return this._addCheck({kind:"url",...S.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...S.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...S.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...S.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...S.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...S.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...S.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...S.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...S.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...S.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...S.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...S.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...S.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...S.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...S.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...S.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...S.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...S.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...S.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...S.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...S.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...S.errToObj(t)})}nonempty(e){return this.min(1,S.errToObj(e))}trim(){return new ee({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ee({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ee({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function te(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,a=n>r?n:r;return Number.parseInt(e.toFixed(a).replace(".",""))%Number.parseInt(t.toFixed(a).replace(".",""))/10**a}ee.create=e=>new ee({checks:[],typeName:qe.ZodString,coerce:e?.coerce??!1,...A(e)});class ne extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==s.number){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.number,received:t.parsedType}),v}let t;const n=new _;for(const a of this._def.checks)"int"===a.kind?r.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),y(t,{code:c.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),y(t,{code:c.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),y(t,{code:c.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):"multipleOf"===a.kind?0!==te(e.data,a.value)&&(t=this._getOrReturnCtx(e,t),y(t,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):"finite"===a.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),y(t,{code:c.not_finite,message:a.message}),n.dirty()):r.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,n,r){return new ne({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:S.toString(r)}]})}_addCheck(e){return new ne({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:S.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:S.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:S.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:S.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&r.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if("finite"===n.kind||"int"===n.kind||"multipleOf"===n.kind)return!0;"min"===n.kind?(null===t||n.value>t)&&(t=n.value):"max"===n.kind&&(null===e||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ne.create=e=>new ne({checks:[],typeName:qe.ZodNumber,coerce:e?.coerce||!1,...A(e)});class re extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==s.bigint)return this._getInvalidInput(e);let t;const n=new _;for(const a of this._def.checks)"min"===a.kind?(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),y(t,{code:c.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):"max"===a.kind?(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),y(t,{code:c.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):"multipleOf"===a.kind?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),y(t,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):r.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.bigint,received:t.parsedType}),v}gte(e,t){return this.setLimit("min",e,!0,S.toString(t))}gt(e,t){return this.setLimit("min",e,!1,S.toString(t))}lte(e,t){return this.setLimit("max",e,!0,S.toString(t))}lt(e,t){return this.setLimit("max",e,!1,S.toString(t))}setLimit(e,t,n,r){return new re({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:S.toString(r)}]})}_addCheck(e){return new re({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:S.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:S.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:S.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:S.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:S.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}re.create=e=>new re({checks:[],typeName:qe.ZodBigInt,coerce:e?.coerce??!1,...A(e)});class ae extends ${_parse(e){if(this._def.coerce&&(e.data=Boolean(e.data)),this._getType(e)!==s.boolean){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.boolean,received:t.parsedType}),v}return b(e.data)}}ae.create=e=>new ae({typeName:qe.ZodBoolean,coerce:e?.coerce||!1,...A(e)});class ie extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==s.date){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.date,received:t.parsedType}),v}if(Number.isNaN(e.data.getTime()))return y(this._getOrReturnCtx(e),{code:c.invalid_date}),v;const t=new _;let n;for(const a of this._def.checks)"min"===a.kind?e.data.getTime()<a.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:c.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):"max"===a.kind?e.data.getTime()>a.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:c.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):r.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ie({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:S.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:S.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ie.create=e=>new ie({checks:[],coerce:e?.coerce||!1,typeName:qe.ZodDate,...A(e)});class se extends ${_parse(e){if(this._getType(e)!==s.symbol){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.symbol,received:t.parsedType}),v}return b(e.data)}}se.create=e=>new se({typeName:qe.ZodSymbol,...A(e)});class oe extends ${_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.undefined,received:t.parsedType}),v}return b(e.data)}}oe.create=e=>new oe({typeName:qe.ZodUndefined,...A(e)});class ce extends ${_parse(e){if(this._getType(e)!==s.null){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.null,received:t.parsedType}),v}return b(e.data)}}ce.create=e=>new ce({typeName:qe.ZodNull,...A(e)});class de extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return b(e.data)}}de.create=e=>new de({typeName:qe.ZodAny,...A(e)});class ue extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return b(e.data)}}ue.create=e=>new ue({typeName:qe.ZodUnknown,...A(e)});class le extends ${_parse(e){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.never,received:t.parsedType}),v}}le.create=e=>new le({typeName:qe.ZodNever,...A(e)});class he extends ${_parse(e){if(this._getType(e)!==s.undefined){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.void,received:t.parsedType}),v}return b(e.data)}}he.create=e=>new he({typeName:qe.ZodVoid,...A(e)});class pe extends ${_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==s.array)return y(t,{code:c.invalid_type,expected:s.array,received:t.parsedType}),v;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(e||a)&&(y(t,{code:e?c.too_big:c.too_small,minimum:a?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(y(t,{code:c.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(y(t,{code:c.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new O(t,e,t.path,n)))).then(e=>_.mergeArray(n,e));const a=[...t.data].map((e,n)=>r.type._parseSync(new O(t,e,t.path,n)));return _.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new pe({...this._def,minLength:{value:e,message:S.toString(t)}})}max(e,t){return new pe({...this._def,maxLength:{value:e,message:S.toString(t)}})}length(e,t){return new pe({...this._def,exactLength:{value:e,message:S.toString(t)}})}nonempty(e){return this.min(1,e)}}function fe(e){if(e instanceof me){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Ce.create(fe(r))}return new me({...e._def,shape:()=>t})}return e instanceof pe?new pe({...e._def,type:fe(e.element)}):e instanceof Ce?Ce.create(fe(e.unwrap())):e instanceof Re?Re.create(fe(e.unwrap())):e instanceof be?be.create(e.items.map(e=>fe(e))):e}pe.create=(e,t)=>new pe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:qe.ZodArray,...A(t)});class me extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=r.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==s.object){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.object,received:t.parsedType}),v}const{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:a}=this._getCached(),i=[];if(!(this._def.catchall instanceof le&&"strip"===this._def.unknownKeys))for(const e in n.data)a.includes(e)||i.push(e);const o=[];for(const e of a){const t=r[e],a=n.data[e];o.push({key:{status:"valid",value:e},value:t._parse(new O(n,a,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof le){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of i)o.push({key:{status:"valid",value:e},value:{status:"valid",value:n.data[e]}});else if("strict"===e)i.length>0&&(y(n,{code:c.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const r=n.data[t];o.push({key:{status:"valid",value:t},value:e._parse(new O(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of o){const n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>_.mergeObjectSync(t,e)):_.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(e){return S.errToObj,new me({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return"unrecognized_keys"===t.code?{message:S.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new me({...this._def,unknownKeys:"strip"})}passthrough(){return new me({...this._def,unknownKeys:"passthrough"})}extend(e){return new me({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new me({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new me({...this._def,catchall:e})}pick(e){const t={};for(const n of r.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new me({...this._def,shape:()=>t})}omit(e){const t={};for(const n of r.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new me({...this._def,shape:()=>t})}deepPartial(){return fe(this)}partial(e){const t={};for(const n of r.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new me({...this._def,shape:()=>t})}required(e){const t={};for(const n of r.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let e=this.shape[n];for(;e instanceof Ce;)e=e._def.innerType;t[n]=e}return new me({...this._def,shape:()=>t})}keyof(){return Te(r.objectKeys(this.shape))}}me.create=(e,t)=>new me({shape:()=>e,unknownKeys:"strip",catchall:le.create(),typeName:qe.ZodObject,...A(t)}),me.strictCreate=(e,t)=>new me({shape:()=>e,unknownKeys:"strict",catchall:le.create(),typeName:qe.ZodObject,...A(t)}),me.lazycreate=(e,t)=>new me({shape:e,unknownKeys:"strip",catchall:le.create(),typeName:qe.ZodObject,...A(t)});class ge extends ${_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;if(t.common.async)return Promise.all(n.map(async e=>{const n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const n=e.map(e=>new u(e.ctx.common.issues));return y(t,{code:c.invalid_union,unionErrors:n}),v});{let e;const r=[];for(const a of n){const n={...t,common:{...t.common,issues:[]},parent:null},i=a._parseSync({data:t.data,path:t.path,parent:n});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const a=r.map(e=>new u(e));return y(t,{code:c.invalid_union,unionErrors:a}),v}}get options(){return this._def.options}}ge.create=(e,t)=>new ge({options:e,typeName:qe.ZodUnion,...A(t)});const ye=e=>e instanceof Se?ye(e.schema):e instanceof je?ye(e.innerType()):e instanceof Oe?[e.value]:e instanceof Ae?e.options:e instanceof $e?r.objectValues(e.enum):e instanceof Pe?ye(e._def.innerType):e instanceof oe?[void 0]:e instanceof ce?[null]:e instanceof Ce?[void 0,...ye(e.unwrap())]:e instanceof Re?[null,...ye(e.unwrap())]:e instanceof De||e instanceof Fe?ye(e.unwrap()):e instanceof Le?ye(e._def.innerType):[];class _e extends ${_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.object)return y(t,{code:c.invalid_type,expected:s.object,received:t.parsedType}),v;const n=this.discriminator,r=t.data[n],a=this.optionsMap.get(r);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(y(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){const r=new Map;for(const n of t){const t=ye(n.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of t){if(r.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);r.set(a,n)}}return new _e({typeName:qe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...A(n)})}}function ve(e,t){const n=o(e),a=o(t);if(e===t)return{valid:!0,data:e};if(n===s.object&&a===s.object){const n=r.objectKeys(t),a=r.objectKeys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const n of a){const r=ve(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===s.array&&a===s.array){if(e.length!==t.length)return{valid:!1};const n=[];for(let r=0;r<e.length;r++){const a=ve(e[r],t[r]);if(!a.valid)return{valid:!1};n.push(a.data)}return{valid:!0,data:n}}return n===s.date&&a===s.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class we extends ${_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(E(e)||E(r))return v;const a=ve(e.value,r.value);return a.valid?((x(e)||x(r))&&t.dirty(),{status:t.value,value:a.data}):(y(n,{code:c.invalid_intersection_types}),v)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}we.create=(e,t,n)=>new we({left:e,right:t,typeName:qe.ZodIntersection,...A(n)});class be extends ${_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.array)return y(n,{code:c.invalid_type,expected:s.array,received:n.parsedType}),v;if(n.data.length<this._def.items.length)return y(n,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&n.data.length>this._def.items.length&&(y(n,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...n.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new O(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>_.mergeArray(t,e)):_.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new be({...this._def,rest:e})}}be.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new be({items:e,typeName:qe.ZodTuple,rest:null,...A(t)})};class Ee extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.object)return y(n,{code:c.invalid_type,expected:s.object,received:n.parsedType}),v;const r=[],a=this._def.keyType,i=this._def.valueType;for(const e in n.data)r.push({key:a._parse(new O(n,e,n.path,e)),value:i._parse(new O(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?_.mergeObjectAsync(t,r):_.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){return new Ee(t instanceof $?{keyType:e,valueType:t,typeName:qe.ZodRecord,...A(n)}:{keyType:ee.create(),valueType:e,typeName:qe.ZodRecord,...A(t)})}}class xe extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.map)return y(n,{code:c.invalid_type,expected:s.map,received:n.parsedType}),v;const r=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([e,t],i)=>({key:r._parse(new O(n,e,n.path,[i,"key"])),value:a._parse(new O(n,t,n.path,[i,"value"]))}));if(n.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const n of i){const r=await n.key,a=await n.value;if("aborted"===r.status||"aborted"===a.status)return v;"dirty"!==r.status&&"dirty"!==a.status||t.dirty(),e.set(r.value,a.value)}return{status:t.value,value:e}})}{const e=new Map;for(const n of i){const r=n.key,a=n.value;if("aborted"===r.status||"aborted"===a.status)return v;"dirty"!==r.status&&"dirty"!==a.status||t.dirty(),e.set(r.value,a.value)}return{status:t.value,value:e}}}}xe.create=(e,t,n)=>new xe({valueType:t,keyType:e,typeName:qe.ZodMap,...A(n)});class Ie extends ${_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.set)return y(n,{code:c.invalid_type,expected:s.set,received:n.parsedType}),v;const r=this._def;null!==r.minSize&&n.data.size<r.minSize.value&&(y(n,{code:c.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&n.data.size>r.maxSize.value&&(y(n,{code:c.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const a=this._def.valueType;function i(e){const n=new Set;for(const r of e){if("aborted"===r.status)return v;"dirty"===r.status&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}const o=[...n.data.values()].map((e,t)=>a._parse(new O(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>i(e)):i(o)}min(e,t){return new Ie({...this._def,minSize:{value:e,message:S.toString(t)}})}max(e,t){return new Ie({...this._def,maxSize:{value:e,message:S.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ie.create=(e,t)=>new Ie({valueType:e,minSize:null,maxSize:null,typeName:qe.ZodSet,...A(t)});class ke extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.function)return y(t,{code:c.invalid_type,expected:s.function,received:t.parsedType}),v;function n(e,n){return m({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,f(),l].filter(e=>!!e),issueData:{code:c.invalid_arguments,argumentsError:n}})}function r(e,n){return m({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,f(),l].filter(e=>!!e),issueData:{code:c.invalid_return_type,returnTypeError:n}})}const a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof Ne){const e=this;return b(async function(...t){const s=new u([]),o=await e._def.args.parseAsync(t,a).catch(e=>{throw s.addIssue(n(t,e)),s}),c=await Reflect.apply(i,this,o);return await e._def.returns._def.type.parseAsync(c,a).catch(e=>{throw s.addIssue(r(c,e)),s})})}{const e=this;return b(function(...t){const s=e._def.args.safeParse(t,a);if(!s.success)throw new u([n(t,s.error)]);const o=Reflect.apply(i,this,s.data),c=e._def.returns.safeParse(o,a);if(!c.success)throw new u([r(o,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ke({...this._def,args:be.create(e).rest(ue.create())})}returns(e){return new ke({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new ke({args:e||be.create([]).rest(ue.create()),returns:t||ue.create(),typeName:qe.ZodFunction,...A(n)})}}class Se extends ${get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Se.create=(e,t)=>new Se({getter:e,typeName:qe.ZodLazy,...A(t)});class Oe extends ${_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return y(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Te(e,t){return new Ae({values:e,typeName:qe.ZodEnum,...A(t)})}Oe.create=(e,t)=>new Oe({value:e,typeName:qe.ZodLiteral,...A(t)});class Ae extends ${_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{expected:r.joinValues(n),received:t.parsedType,code:c.invalid_type}),v}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return y(t,{received:t.data,code:c.invalid_enum_value,options:n}),v}return b(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ae.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ae.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ae.create=Te;class $e extends ${_parse(e){const t=r.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==s.string&&n.parsedType!==s.number){const e=r.objectValues(t);return y(n,{expected:r.joinValues(e),received:n.parsedType,code:c.invalid_type}),v}if(this._cache||(this._cache=new Set(r.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=r.objectValues(t);return y(n,{received:n.data,code:c.invalid_enum_value,options:e}),v}return b(e.data)}get enum(){return this._def.values}}$e.create=(e,t)=>new $e({values:e,typeName:qe.ZodNativeEnum,...A(t)});class Ne extends ${unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.promise&&!1===t.common.async)return y(t,{code:c.invalid_type,expected:s.promise,received:t.parsedType}),v;const n=t.parsedType===s.promise?t.data:Promise.resolve(t.data);return b(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Ne.create=(e,t)=>new Ne({type:e,typeName:qe.ZodPromise,...A(t)});class je extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),a=this._def.effect||null,i={addIssue:e=>{y(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===a.type){const e=a.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return v;const r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return"aborted"===r.status?v:"dirty"===r.status||"dirty"===t.value?w(r.value):r});{if("aborted"===t.value)return v;const r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return"aborted"===r.status?v:"dirty"===r.status||"dirty"===t.value?w(r.value):r}}if("refinement"===a.type){const e=e=>{const t=a.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===n.common.async){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===r.status?v:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>"aborted"===n.status?v:("dirty"===n.status&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if("transform"===a.type){if(!1===n.common.async){const e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!I(e))return v;const r=a.transform(e.value,i);if(r instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:r}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>I(e)?Promise.resolve(a.transform(e.value,i)).then(e=>({status:t.value,value:e})):v)}r.assertNever(a)}}je.create=(e,t,n)=>new je({schema:e,typeName:qe.ZodEffects,effect:t,...A(n)}),je.createWithPreprocess=(e,t,n)=>new je({schema:t,effect:{type:"preprocess",transform:e},typeName:qe.ZodEffects,...A(n)});class Ce extends ${_parse(e){return this._getType(e)===s.undefined?b(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ce.create=(e,t)=>new Ce({innerType:e,typeName:qe.ZodOptional,...A(t)});class Re extends ${_parse(e){return this._getType(e)===s.null?b(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Re.create=(e,t)=>new Re({innerType:e,typeName:qe.ZodNullable,...A(t)});class Pe extends ${_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===s.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Pe.create=(e,t)=>new Pe({innerType:e,typeName:qe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...A(t)});class Le extends ${_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return k(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new u(n.common.issues)},input:n.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new u(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Le.create=(e,t)=>new Le({innerType:e,typeName:qe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...A(t)});class Me extends ${_parse(e){if(this._getType(e)!==s.nan){const t=this._getOrReturnCtx(e);return y(t,{code:c.invalid_type,expected:s.nan,received:t.parsedType}),v}return{status:"valid",value:e.data}}}Me.create=e=>new Me({typeName:qe.ZodNaN,...A(e)});const ze=Symbol("zod_brand");class De extends ${_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ue extends ${_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?v:"dirty"===e.status?(t.dirty(),w(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{const e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return"aborted"===e.status?v:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(e,t){return new Ue({in:e,out:t,typeName:qe.ZodPipeline})}}class Fe extends ${_parse(e){const t=this._def.innerType._parse(e),n=e=>(I(e)&&(e.value=Object.freeze(e.value)),e);return k(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}}function Ze(e,t){const n="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof n?{message:n}:n}function Be(e,t={},n){return e?de.create().superRefine((r,a)=>{const i=e(r);if(i instanceof Promise)return i.then(e=>{if(!e){const e=Ze(t,r),i=e.fatal??n??!0;a.addIssue({code:"custom",...e,fatal:i})}});if(!i){const e=Ze(t,r),i=e.fatal??n??!0;a.addIssue({code:"custom",...e,fatal:i})}}):de.create()}Fe.create=(e,t)=>new Fe({innerType:e,typeName:qe.ZodReadonly,...A(t)});const Je={object:me.lazycreate};var qe;!function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(qe||(qe={}));const He=(e,t={message:`Input not instance of ${e.name}`})=>Be(t=>t instanceof e,t),Ge=ee.create,Qe=ne.create,Ve=Me.create,We=re.create,Ke=ae.create,Ye=ie.create,Xe=se.create,et=oe.create,tt=ce.create,nt=de.create,rt=ue.create,at=le.create,it=he.create,st=pe.create,ot=me.create,ct=me.strictCreate,dt=ge.create,ut=_e.create,lt=we.create,ht=be.create,pt=Ee.create,ft=xe.create,mt=Ie.create,gt=ke.create,yt=Se.create,_t=Oe.create,vt=Ae.create,wt=$e.create,bt=Ne.create,Et=je.create,xt=Ce.create,It=Re.create,kt=je.createWithPreprocess,St=Ue.create,Ot=()=>Ge().optional(),Tt=()=>Qe().optional(),At=()=>Ke().optional(),$t={string:e=>ee.create({...e,coerce:!0}),number:e=>ne.create({...e,coerce:!0}),boolean:e=>ae.create({...e,coerce:!0}),bigint:e=>re.create({...e,coerce:!0}),date:e=>ie.create({...e,coerce:!0})},Nt=v},75335(e,t,n){n.d(t,{Umr:()=>Oe,igI:()=>Ae,GPR:()=>Se,G8g:()=>Ce,emL:()=>je,o8B:()=>F,fd:()=>Ne,qgA:()=>we,EJS:()=>be,blZ:()=>Ze,ZSL:()=>r});var r={};function a(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:s,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const a=s.prototype,i=Object.keys(a);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=a[t].bind(n))}}const a=n?.Parent??Object;class i extends a{}function s(e){var t;const a=n?.Parent?new i:this;r(a,e),(t=a._zod).deferred??(t.deferred=[]);for(const e of a._zod.deferred)e();return a}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}n.r(r),n.d(r,{BIGINT_FORMAT_RANGES:()=>G,Class:()=>ge,NUMBER_FORMAT_RANGES:()=>H,aborted:()=>te,allowsEval:()=>C,assert:()=>h,assertEqual:()=>c,assertIs:()=>u,assertNever:()=>l,assertNotEqual:()=>d,assignProp:()=>x,base64ToUint8Array:()=>ue,base64urlToUint8Array:()=>he,cached:()=>g,captureStackTrace:()=>N,cleanEnum:()=>de,cleanRegex:()=>_,clone:()=>F,cloneDef:()=>k,createTransparentProxy:()=>B,defineLazy:()=>b,esc:()=>A,escapeRegex:()=>U,extend:()=>W,finalizeIssue:()=>ae,floatSafeRemainder:()=>v,getElementAtPath:()=>S,getEnumValues:()=>p,getLengthableOrigin:()=>se,getParsedType:()=>M,getSizableOrigin:()=>ie,hexToUint8Array:()=>fe,isObject:()=>j,isPlainObject:()=>R,issue:()=>ce,joinValues:()=>f,jsonStringifyReplacer:()=>m,merge:()=>Y,mergeDefs:()=>I,normalizeParams:()=>Z,nullish:()=>y,numKeys:()=>L,objectClone:()=>E,omit:()=>V,optionalKeys:()=>q,parsedType:()=>oe,partial:()=>X,pick:()=>Q,prefixIssues:()=>ne,primitiveTypes:()=>D,promiseAllObject:()=>O,propertyKeyTypes:()=>z,randomString:()=>T,required:()=>ee,safeExtend:()=>K,shallowClone:()=>P,slugify:()=>$,stringifyPrimitive:()=>J,uint8ArrayToBase64:()=>le,uint8ArrayToBase64url:()=>pe,uint8ArrayToHex:()=>me,unwrapMessage:()=>re}),Object.freeze({status:"aborted"}),Symbol("zod_brand");class i extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}Error;const s={};function o(e){return e&&Object.assign(s,e),s}function c(e){return e}function d(e){return e}function u(e){}function l(e){throw new Error("Unexpected value in exhaustive check")}function h(e){}function p(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function f(e,t="|"){return e.map(e=>J(e)).join(t)}function m(e,t){return"bigint"==typeof t?t.toString():t}function g(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function y(e){return null==e}function _(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function v(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let a=(r.split(".")[1]||"").length;if(0===a&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(a=Number.parseInt(e[1]))}const i=n>a?n:a;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}const w=Symbol("evaluating");function b(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==w)return void 0===r&&(r=w,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function E(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function x(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function I(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function k(e){return I(e._zod.def)}function S(e,t){return t?t.reduce((e,t)=>e?.[t],e):e}function O(e){const t=Object.keys(e),n=t.map(t=>e[t]);return Promise.all(n).then(e=>{const n={};for(let r=0;r<t.length;r++)n[t[r]]=e[r];return n})}function T(e=10){let t="";for(let n=0;n<e;n++)t+="abcdefghijklmnopqrstuvwxyz"[Math.floor(26*Math.random())];return t}function A(e){return JSON.stringify(e)}function $(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const N="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function j(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const C=g(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function R(e){if(!1===j(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==j(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function P(e){return R(e)?{...e}:Array.isArray(e)?[...e]:e}function L(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const M=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":null===e?"null":e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?"promise":"undefined"!=typeof Map&&e instanceof Map?"map":"undefined"!=typeof Set&&e instanceof Set?"set":"undefined"!=typeof Date&&e instanceof Date?"date":"undefined"!=typeof File&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},z=new Set(["string","number","symbol"]),D=new Set(["string","number","bigint","boolean","symbol","undefined"]);function U(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function F(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Z(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function B(e){let t;return new Proxy({},{get:(n,r,a)=>(t??(t=e()),Reflect.get(t,r,a)),set:(n,r,a,i)=>(t??(t=e()),Reflect.set(t,r,a,i)),has:(n,r)=>(t??(t=e()),Reflect.has(t,r)),deleteProperty:(n,r)=>(t??(t=e()),Reflect.deleteProperty(t,r)),ownKeys:n=>(t??(t=e()),Reflect.ownKeys(t)),getOwnPropertyDescriptor:(n,r)=>(t??(t=e()),Reflect.getOwnPropertyDescriptor(t,r)),defineProperty:(n,r,a)=>(t??(t=e()),Reflect.defineProperty(t,r,a))})}function J(e){return"bigint"==typeof e?e.toString()+"n":"string"==typeof e?`"${e}"`:`${e}`}function q(e){return Object.keys(e).filter(t=>"optional"===e[t]._zod.optin&&"optional"===e[t]._zod.optout)}const H={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},G={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Q(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return F(e,I(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return x(this,"shape",e),e},checks:[]}))}function V(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const a=I(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return x(this,"shape",r),r},checks:[]});return F(e,a)}function W(e,t){if(!R(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=I(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return x(this,"shape",n),n}});return F(e,r)}function K(e,t){if(!R(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=I(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return x(this,"shape",n),n}});return F(e,n)}function Y(e,t){const n=I(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return x(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return F(e,n)}function X(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const a=I(t._zod.def,{get shape(){const r=t._zod.def.shape,a={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(a[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)a[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return x(this,"shape",a),a},checks:[]});return F(t,a)}function ee(e,t,n){const r=I(t._zod.def,{get shape(){const r=t._zod.def.shape,a={...r};if(n)for(const t in n){if(!(t in a))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(a[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)a[t]=new e({type:"nonoptional",innerType:r[t]});return x(this,"shape",a),a}});return F(t,r)}function te(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function ne(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function re(e){return"string"==typeof e?e:e?.message}function ae(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const a=re(e.inst?._zod.def?.error?.(e))??re(t?.error?.(e))??re(n.customError?.(e))??re(n.localeError?.(e))??"Invalid input";r.message=a}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function ie(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function se(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function oe(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(null===e)return"null";if(Array.isArray(e))return"array";const t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return t}function ce(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}function de(e){return Object.entries(e).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function ue(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function le(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function he(e){const t=e.replace(/-/g,"+").replace(/_/g,"/");return ue(t+"=".repeat((4-t.length%4)%4))}function pe(e){return le(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fe(e){const t=e.replace(/^0x/,"");if(t.length%2!=0)throw new Error("Invalid hex string length");const n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=Number.parseInt(t.slice(e,e+2),16);return n}function me(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}class ge{constructor(...e){}}const ye=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,m,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_e=a("$ZodError",ye),ve=a("$ZodError",ye,{Parent:Error}),we=(e=>(t,n,r,a)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},c=t._zod.run({value:n,issues:[]},s);if(c instanceof Promise)throw new i;if(c.issues.length){const t=new(a?.Err??e)(c.issues.map(e=>ae(e,s,o())));throw N(t,a?.callee),t}return c.value})(ve),be=(e=>async(t,n,r,a)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(a?.Err??e)(s.issues.map(e=>ae(e,i,o())));throw N(t,a?.callee),t}return s.value})(ve),Ee=(e=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new i;return s.issues.length?{success:!1,error:new(e??_e)(s.issues.map(e=>ae(e,a,o())))}:{success:!0,data:s.value}})(ve),xe=(e=>async(t,n,r)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>ae(e,a,o())))}:{success:!0,data:i.value}})(ve),Ie={major:4,minor:3,patch:6},ke=a("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ie;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,a=te(e);for(const s of t){if(s._zod.def.when){if(!s._zod.def.when(e))continue}else if(a)continue;const t=e.issues.length,o=s._zod.check(e);if(o instanceof Promise&&!1===n?.async)throw new i;if(r||o instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(a||(a=te(e,t)))});else{if(e.issues.length===t)continue;a||(a=te(e,t))}}return r?r.then(()=>e):e},n=(n,a,s)=>{if(te(n))return n.aborted=!0,n;const o=t(a,r,s);if(o instanceof Promise){if(!1===s.async)throw new i;return o.then(t=>e._zod.parse(t,s))}return e._zod.parse(o,s)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if("backward"===s.direction){const t=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,a,s)):n(t,a,s)}const o=e._zod.parse(a,s);if(o instanceof Promise){if(!1===s.async)throw new i;return o.then(e=>t(e,r,s))}return t(o,r,s)}}b(e,"~standard",()=>({validate:t=>{try{const n=Ee(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return xe(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Se=a("$ZodUnknown",(e,t)=>{ke.init(e,t),e._zod.parse=e=>e}),Oe=a("$ZodNever",(e,t)=>{ke.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function Te(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const Ae=a("$ZodOptional",(e,t)=>{ke.init(e,t),e._zod.optin="optional",e._zod.optout="optional",b(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),b(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${_(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Te(t,e.value)):Te(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}});var $e;Symbol("ZodOutput"),Symbol("ZodInput");($e=globalThis).__zod_globalRegistry??($e.__zod_globalRegistry=new class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}});const Ne=globalThis.__zod_globalRegistry;function je(e){return new e({type:"unknown"})}function Ce(e,t){return new e({type:"never",...Z(t)})}function Re(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Ne,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Pe(e,t,n={path:[],schemaPath:[]}){var r;const a=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const o=e._zod.toJSONSchema?.();if(o)s.schema=o;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{const n=s.schema,i=t.processors[a.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(s.ref||(s.ref=i),Pe(i,t,r),t.seen.get(i).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(s.schema,c),"input"===t.io&&ze(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Le(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const a=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:a,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,a=e.external.uri??(e=>e);if(n)return{ref:a(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${a("__shared")}#/${r}/${i}`}}if(t[1]===n)return{ref:"#"};const a=`#/${r}/`,i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:a+i}})(t);r.def={...r.schema},i&&(r.defId=i);const s=r.schema;for(const e in s)delete s[e];s.$ref=a};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){a(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}const i=e.metadataRegistry.get(n[0])?.id;(i||r.cycle||r.count>1&&"ref"===e.reused)&&a(n)}}function Me(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const a=n.def??n.schema,i={...a},s=n.ref;if(n.ref=null,s){r(s);const n=e.seen.get(s),o=n.schema;if(!o.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(a,o):(a.allOf=a.allOf??[],a.allOf.push(o)),Object.assign(a,i),t._zod.parent===s)for(const e in a)"$ref"!==e&&"allOf"!==e&&(e in i||delete a[e]);if(o.$ref&&n.def)for(const e in a)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(a[e])===JSON.stringify(n.def[e])&&delete a[e]}const o=t._zod.parent;if(o&&o!==s){r(o);const t=e.seen.get(o);if(t?.schema.$ref&&(a.$ref=t.schema.$ref,t.def))for(const e in a)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(a[e])===JSON.stringify(t.def[e])&&delete a[e]}e.override({zodSchema:t,jsonSchema:a,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())r(t[0]);const a={};if("draft-2020-12"===e.target?a.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?a.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?a.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");a.$id=e.external.uri(n)}Object.assign(a,n.def??n.schema);const i=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(i[e.defId]=e.def)}e.external||Object.keys(i).length>0&&("draft-2020-12"===e.target?a.$defs=i:a.definitions=i);try{const n=JSON.parse(JSON.stringify(a));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:De(t,"input",e.processors),output:De(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function ze(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return ze(r.element,n);if("set"===r.type)return ze(r.valueType,n);if("lazy"===r.type)return ze(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return ze(r.innerType,n);if("intersection"===r.type)return ze(r.left,n)||ze(r.right,n);if("record"===r.type||"map"===r.type)return ze(r.keyType,n)||ze(r.valueType,n);if("pipe"===r.type)return ze(r.in,n)||ze(r.out,n);if("object"===r.type){for(const e in r.shape)if(ze(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(ze(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(ze(e,n))return!0;return!(!r.rest||!ze(r.rest,n))}return!1}const De=(e,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},s=Re({...a??{},target:i,io:t,processors:n});return Pe(e,s),Le(s,e),Me(s,e)},Ue={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Fe={string:(e,t,n,r)=>{const a=n;a.type="string";const{minimum:i,maximum:s,format:o,patterns:c,contentEncoding:d}=e._zod.bag;if("number"==typeof i&&(a.minLength=i),"number"==typeof s&&(a.maxLength=s),o&&(a.format=Ue[o]??o,""===a.format&&delete a.format,"time"===o&&delete a.format),d&&(a.contentEncoding=d),c&&c.size>0){const e=[...c];1===e.length?a.pattern=e[0].source:e.length>1&&(a.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}},number:(e,t,n,r)=>{const a=n,{minimum:i,maximum:s,format:o,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=e._zod.bag;"string"==typeof o&&o.includes("int")?a.type="integer":a.type="number","number"==typeof u&&("draft-04"===t.target||"openapi-3.0"===t.target?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u),"number"==typeof i&&(a.minimum=i,"number"==typeof u&&"draft-04"!==t.target&&(u>=i?delete a.minimum:delete a.exclusiveMinimum)),"number"==typeof d&&("draft-04"===t.target||"openapi-3.0"===t.target?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d),"number"==typeof s&&(a.maximum=s,"number"==typeof d&&"draft-04"!==t.target&&(d<=s?delete a.maximum:delete a.exclusiveMaximum)),"number"==typeof c&&(a.multipleOf=c)},boolean:(e,t,n,r)=>{n.type="boolean"},bigint:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("BigInt cannot be represented in JSON Schema")},symbol:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Symbols cannot be represented in JSON Schema")},null:(e,t,n,r)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},undefined:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Undefined cannot be represented in JSON Schema")},void:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Void cannot be represented in JSON Schema")},never:(e,t,n,r)=>{n.not={}},any:(e,t,n,r)=>{},unknown:(e,t,n,r)=>{},date:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")},enum:(e,t,n,r)=>{const a=p(e._zod.def.entries);a.every(e=>"number"==typeof e)&&(n.type="number"),a.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=a},literal:(e,t,n,r)=>{const a=e._zod.def,i=[];for(const e of a.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(e))}else i.push(e);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i},nan:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("NaN cannot be represented in JSON Schema")},template_literal:(e,t,n,r)=>{const a=n,i=e._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");a.type="string",a.pattern=i.source},file:(e,t,n,r)=>{const a=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:o,mime:c}=e._zod.bag;void 0!==s&&(i.minLength=s),void 0!==o&&(i.maxLength=o),c?1===c.length?(i.contentMediaType=c[0],Object.assign(a,i)):(Object.assign(a,i),a.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(a,i)},success:(e,t,n,r)=>{n.type="boolean"},custom:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")},function:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Function types cannot be represented in JSON Schema")},transform:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")},map:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Map cannot be represented in JSON Schema")},set:(e,t,n,r)=>{if("throw"===t.unrepresentable)throw new Error("Set cannot be represented in JSON Schema")},array:(e,t,n,r)=>{const a=n,i=e._zod.def,{minimum:s,maximum:o}=e._zod.bag;"number"==typeof s&&(a.minItems=s),"number"==typeof o&&(a.maxItems=o),a.type="array",a.items=Pe(i.element,t,{...r,path:[...r.path,"items"]})},object:(e,t,n,r)=>{const a=n,i=e._zod.def;a.type="object",a.properties={};const s=i.shape;for(const e in s)a.properties[e]=Pe(s[e],t,{...r,path:[...r.path,"properties",e]});const o=new Set(Object.keys(s)),c=new Set([...o].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(a.required=Array.from(c)),"never"===i.catchall?._zod.def.type?a.additionalProperties=!1:i.catchall?i.catchall&&(a.additionalProperties=Pe(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(a.additionalProperties=!1)},union:(e,t,n,r)=>{const a=e._zod.def,i=!1===a.inclusive,s=a.options.map((e,n)=>Pe(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=s:n.anyOf=s},intersection:(e,t,n,r)=>{const a=e._zod.def,i=Pe(a.left,t,{...r,path:[...r.path,"allOf",0]}),s=Pe(a.right,t,{...r,path:[...r.path,"allOf",1]}),o=e=>"allOf"in e&&1===Object.keys(e).length,c=[...o(i)?i.allOf:[i],...o(s)?s.allOf:[s]];n.allOf=c},tuple:(e,t,n,r)=>{const a=n,i=e._zod.def;a.type="array";const s="draft-2020-12"===t.target?"prefixItems":"items",o="draft-2020-12"===t.target||"openapi-3.0"===t.target?"items":"additionalItems",c=i.items.map((e,n)=>Pe(e,t,{...r,path:[...r.path,s,n]})),d=i.rest?Pe(i.rest,t,{...r,path:[...r.path,o,..."openapi-3.0"===t.target?[i.items.length]:[]]}):null;"draft-2020-12"===t.target?(a.prefixItems=c,d&&(a.items=d)):"openapi-3.0"===t.target?(a.items={anyOf:c},d&&a.items.anyOf.push(d),a.minItems=c.length,d||(a.maxItems=c.length)):(a.items=c,d&&(a.additionalItems=d));const{minimum:u,maximum:l}=e._zod.bag;"number"==typeof u&&(a.minItems=u),"number"==typeof l&&(a.maxItems=l)},record:(e,t,n,r)=>{const a=n,i=e._zod.def;a.type="object";const s=i.keyType,o=s._zod.bag,c=o?.patterns;if("loose"===i.mode&&c&&c.size>0){const e=Pe(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});a.patternProperties={};for(const t of c)a.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(a.propertyNames=Pe(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),a.additionalProperties=Pe(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=s._zod.values;if(d){const e=[...d].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(a.required=e)}},nullable:(e,t,n,r)=>{const a=e._zod.def,i=Pe(a.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=a.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},nonoptional:(e,t,n,r)=>{const a=e._zod.def;Pe(a.innerType,t,r),t.seen.get(e).ref=a.innerType},default:(e,t,n,r)=>{const a=e._zod.def;Pe(a.innerType,t,r),t.seen.get(e).ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},prefault:(e,t,n,r)=>{const a=e._zod.def;Pe(a.innerType,t,r),t.seen.get(e).ref=a.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},catch:(e,t,n,r)=>{const a=e._zod.def;let i;Pe(a.innerType,t,r),t.seen.get(e).ref=a.innerType;try{i=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},pipe:(e,t,n,r)=>{const a=e._zod.def,i="input"===t.io?"transform"===a.in._zod.def.type?a.out:a.in:a.out;Pe(i,t,r),t.seen.get(e).ref=i},readonly:(e,t,n,r)=>{const a=e._zod.def;Pe(a.innerType,t,r),t.seen.get(e).ref=a.innerType,n.readOnly=!0},promise:(e,t,n,r)=>{const a=e._zod.def;Pe(a.innerType,t,r),t.seen.get(e).ref=a.innerType},optional:(e,t,n,r)=>{const a=e._zod.def;Pe(a.innerType,t,r),t.seen.get(e).ref=a.innerType},lazy:(e,t,n,r)=>{const a=e._zod.innerType;Pe(a,t,r),t.seen.get(e).ref=a}};function Ze(e,t){if("_idmap"in e){const n=e,r=Re({...t,processors:Fe}),a={};for(const e of n._idmap.entries()){const[t,n]=e;Pe(n,r)}const i={},s={registry:n,uri:t?.uri,defs:a};r.external=s;for(const e of n._idmap.entries()){const[t,n]=e;Le(r,n),i[t]=Me(r,n)}if(Object.keys(a).length>0){const e="draft-2020-12"===r.target?"$defs":"definitions";i.__shared={[e]:a}}return{schemas:i}}const n=Re({...t,processors:Fe});return Pe(e,n),Le(n,e),Me(n,e)}}}]);