wrong-notebook 2026.10.25-2 → 2026.10.25

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 (327) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +3 -0
  3. package/.next/build-manifest.json +3 -3
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/routes-manifest.json +18 -0
  6. package/.next/server/app/_global-error/page.js +1 -1
  7. package/.next/server/app/_global-error/page.js.nft.json +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  13. package/.next/server/app/_not-found/page.js.nft.json +1 -1
  14. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  15. package/.next/server/app/admin/page.js.nft.json +1 -1
  16. package/.next/server/app/admin/page_client-reference-manifest.js +1 -1
  17. package/.next/server/app/admin/user/[id]/page.js.nft.json +1 -1
  18. package/.next/server/app/admin/user/[id]/page_client-reference-manifest.js +1 -1
  19. package/.next/server/app/api/admin/dashboard/route.js +12 -11
  20. package/.next/server/app/api/admin/dashboard/route.js.nft.json +1 -1
  21. package/.next/server/app/api/admin/migrate-tags/route.js +1 -1
  22. package/.next/server/app/api/admin/migrate-tags/route.js.nft.json +1 -1
  23. package/.next/server/app/api/admin/system-reset/route.js +1 -1
  24. package/.next/server/app/api/admin/system-reset/route.js.nft.json +1 -1
  25. package/.next/server/app/api/admin/users/[id]/detail/route.js +12 -11
  26. package/.next/server/app/api/admin/users/[id]/detail/route.js.nft.json +1 -1
  27. package/.next/server/app/api/admin/users/[id]/route.js +1 -1
  28. package/.next/server/app/api/admin/users/[id]/route.js.nft.json +1 -1
  29. package/.next/server/app/api/admin/users/route.js +1 -1
  30. package/.next/server/app/api/admin/users/route.js.nft.json +1 -1
  31. package/.next/server/app/api/ai/models/route.js +1 -1
  32. package/.next/server/app/api/ai/models/route.js.nft.json +1 -1
  33. package/.next/server/app/api/ai/test/route.js +9 -8
  34. package/.next/server/app/api/ai/test/route.js.nft.json +1 -1
  35. package/.next/server/app/api/analytics/route.js +1 -1
  36. package/.next/server/app/api/analytics/route.js.nft.json +1 -1
  37. package/.next/server/app/api/analyze/route.js +12 -11
  38. package/.next/server/app/api/analyze/route.js.nft.json +1 -1
  39. package/.next/server/app/api/auth/[...nextauth]/route.js +1 -1
  40. package/.next/server/app/api/auth/[...nextauth]/route.js.nft.json +1 -1
  41. package/.next/server/app/api/error-items/[id]/delete/route.js +1 -1
  42. package/.next/server/app/api/error-items/[id]/delete/route.js.nft.json +1 -1
  43. package/.next/server/app/api/error-items/[id]/figure/route.js +13 -12
  44. package/.next/server/app/api/error-items/[id]/figure/route.js.nft.json +1 -1
  45. package/.next/server/app/api/error-items/[id]/fix-latex/route.js +14 -13
  46. package/.next/server/app/api/error-items/[id]/fix-latex/route.js.nft.json +1 -1
  47. package/.next/server/app/api/error-items/[id]/geogebra/route.js +11 -10
  48. package/.next/server/app/api/error-items/[id]/geogebra/route.js.nft.json +1 -1
  49. package/.next/server/app/api/error-items/[id]/image/route.js +1 -1
  50. package/.next/server/app/api/error-items/[id]/image/route.js.nft.json +1 -1
  51. package/.next/server/app/api/error-items/[id]/notes/route.js +1 -1
  52. package/.next/server/app/api/error-items/[id]/notes/route.js.nft.json +1 -1
  53. package/.next/server/app/api/error-items/[id]/practice-records/route.js +1 -1
  54. package/.next/server/app/api/error-items/[id]/practice-records/route.js.nft.json +1 -1
  55. package/.next/server/app/api/error-items/[id]/reanswer/route.js +13 -12
  56. package/.next/server/app/api/error-items/[id]/reanswer/route.js.nft.json +1 -1
  57. package/.next/server/app/api/error-items/[id]/retag/route.js +12 -11
  58. package/.next/server/app/api/error-items/[id]/retag/route.js.nft.json +1 -1
  59. package/.next/server/app/api/error-items/[id]/route.js +1 -1
  60. package/.next/server/app/api/error-items/[id]/route.js.nft.json +1 -1
  61. package/.next/server/app/api/error-items/[id]/svg-animation/route.js +13 -12
  62. package/.next/server/app/api/error-items/[id]/svg-animation/route.js.nft.json +1 -1
  63. package/.next/server/app/api/error-items/batch-delete/route.js +1 -1
  64. package/.next/server/app/api/error-items/batch-delete/route.js.nft.json +1 -1
  65. package/.next/server/app/api/error-items/clear/route.js +1 -1
  66. package/.next/server/app/api/error-items/clear/route.js.nft.json +1 -1
  67. package/.next/server/app/api/error-items/list/route.js +1 -1
  68. package/.next/server/app/api/error-items/list/route.js.nft.json +1 -1
  69. package/.next/server/app/api/error-items/route.js +13 -12
  70. package/.next/server/app/api/error-items/route.js.nft.json +1 -1
  71. package/.next/server/app/api/error-items/short/[shortId]/route.js +1 -1
  72. package/.next/server/app/api/error-items/short/[shortId]/route.js.nft.json +1 -1
  73. package/.next/server/app/api/error-items/similarity/route.js +1 -1
  74. package/.next/server/app/api/error-items/similarity/route.js.nft.json +1 -1
  75. package/.next/server/app/api/exams/[id]/questions/[questionId]/regenerate/route.js +12 -11
  76. package/.next/server/app/api/exams/[id]/questions/[questionId]/regenerate/route.js.nft.json +1 -1
  77. package/.next/server/app/api/exams/[id]/results/route.js +12 -11
  78. package/.next/server/app/api/exams/[id]/results/route.js.nft.json +1 -1
  79. package/.next/server/app/api/exams/[id]/retry/route.js +11 -10
  80. package/.next/server/app/api/exams/[id]/retry/route.js.nft.json +1 -1
  81. package/.next/server/app/api/exams/[id]/route.js +11 -10
  82. package/.next/server/app/api/exams/[id]/route.js.nft.json +1 -1
  83. package/.next/server/app/api/exams/route.js +11 -10
  84. package/.next/server/app/api/exams/route.js.nft.json +1 -1
  85. package/.next/server/app/api/export/route.js +1 -1
  86. package/.next/server/app/api/export/route.js.nft.json +1 -1
  87. package/.next/server/app/api/geogebra-analyze/route.js +12 -11
  88. package/.next/server/app/api/geogebra-analyze/route.js.nft.json +1 -1
  89. package/.next/server/app/api/health/route.js +1 -1
  90. package/.next/server/app/api/health/route.js.nft.json +1 -1
  91. package/.next/server/app/api/import/route.js +11 -10
  92. package/.next/server/app/api/import/route.js.nft.json +1 -1
  93. package/.next/server/app/api/logs/frontend/route.js +1 -1
  94. package/.next/server/app/api/logs/frontend/route.js.nft.json +1 -1
  95. package/.next/server/app/api/minimax-code/checkin/route/app-paths-manifest.json +3 -0
  96. package/.next/server/app/api/minimax-code/checkin/route/build-manifest.json +12 -0
  97. package/.next/server/app/api/minimax-code/checkin/route/server-reference-manifest.json +4 -0
  98. package/.next/server/app/api/minimax-code/checkin/route.js +14 -0
  99. package/.next/server/app/api/minimax-code/checkin/route.js.map +5 -0
  100. package/.next/server/app/api/minimax-code/checkin/route.js.nft.json +1 -0
  101. package/.next/server/app/api/minimax-code/checkin/route_client-reference-manifest.js +3 -0
  102. package/.next/server/app/api/minimax-code/login/route/app-paths-manifest.json +3 -0
  103. package/.next/server/app/api/minimax-code/login/route/build-manifest.json +12 -0
  104. package/.next/server/app/api/minimax-code/login/route/server-reference-manifest.json +4 -0
  105. package/.next/server/app/api/minimax-code/login/route.js +12 -0
  106. package/.next/server/app/api/minimax-code/login/route.js.map +5 -0
  107. package/.next/server/app/api/minimax-code/login/route.js.nft.json +1 -0
  108. package/.next/server/app/api/minimax-code/login/route_client-reference-manifest.js +3 -0
  109. package/.next/server/app/api/minimax-code/route/app-paths-manifest.json +3 -0
  110. package/.next/server/app/api/minimax-code/route/build-manifest.json +12 -0
  111. package/.next/server/app/api/minimax-code/route/server-reference-manifest.json +4 -0
  112. package/.next/server/app/api/minimax-code/route.js +14 -0
  113. package/.next/server/app/api/minimax-code/route.js.map +5 -0
  114. package/.next/server/app/api/minimax-code/route.js.nft.json +1 -0
  115. package/.next/server/app/api/minimax-code/route_client-reference-manifest.js +3 -0
  116. package/.next/server/app/api/notebooks/[id]/retag/route.js +11 -10
  117. package/.next/server/app/api/notebooks/[id]/retag/route.js.nft.json +1 -1
  118. package/.next/server/app/api/notebooks/[id]/route.js +1 -1
  119. package/.next/server/app/api/notebooks/[id]/route.js.nft.json +1 -1
  120. package/.next/server/app/api/notebooks/route.js +1 -1
  121. package/.next/server/app/api/notebooks/route.js.nft.json +1 -1
  122. package/.next/server/app/api/openclaw/batch-upload/route.js +12 -11
  123. package/.next/server/app/api/openclaw/batch-upload/route.js.nft.json +1 -1
  124. package/.next/server/app/api/practice/generate/route.js +11 -10
  125. package/.next/server/app/api/practice/generate/route.js.nft.json +1 -1
  126. package/.next/server/app/api/practice/grade/route.js +11 -10
  127. package/.next/server/app/api/practice/grade/route.js.nft.json +1 -1
  128. package/.next/server/app/api/practice/record/[id]/route.js +13 -12
  129. package/.next/server/app/api/practice/record/[id]/route.js.nft.json +1 -1
  130. package/.next/server/app/api/practice/record/route.js +10 -9
  131. package/.next/server/app/api/practice/record/route.js.nft.json +1 -1
  132. package/.next/server/app/api/reanswer/route.js +11 -10
  133. package/.next/server/app/api/reanswer/route.js.nft.json +1 -1
  134. package/.next/server/app/api/register/route.js +1 -1
  135. package/.next/server/app/api/register/route.js.nft.json +1 -1
  136. package/.next/server/app/api/register/status/route.js +1 -1
  137. package/.next/server/app/api/register/status/route.js.nft.json +1 -1
  138. package/.next/server/app/api/review/due/route.js +1 -1
  139. package/.next/server/app/api/review/due/route.js.nft.json +1 -1
  140. package/.next/server/app/api/settings/route.js +6 -5
  141. package/.next/server/app/api/settings/route.js.nft.json +1 -1
  142. package/.next/server/app/api/stats/practice/clear/route.js +1 -1
  143. package/.next/server/app/api/stats/practice/clear/route.js.nft.json +1 -1
  144. package/.next/server/app/api/stats/practice/route.js +1 -1
  145. package/.next/server/app/api/stats/practice/route.js.nft.json +1 -1
  146. package/.next/server/app/api/tags/route.js +1 -1
  147. package/.next/server/app/api/tags/route.js.nft.json +1 -1
  148. package/.next/server/app/api/tags/stats/route.js +1 -1
  149. package/.next/server/app/api/tags/stats/route.js.nft.json +1 -1
  150. package/.next/server/app/api/tags/suggestions/route.js +1 -1
  151. package/.next/server/app/api/tags/suggestions/route.js.nft.json +1 -1
  152. package/.next/server/app/api/tasks/route.js +1 -1
  153. package/.next/server/app/api/tasks/route.js.nft.json +1 -1
  154. package/.next/server/app/api/user/route.js +1 -1
  155. package/.next/server/app/api/user/route.js.nft.json +1 -1
  156. package/.next/server/app/api/version/route.js +1 -1
  157. package/.next/server/app/api/version/route.js.nft.json +1 -1
  158. package/.next/server/app/error-items/[id]/page.js.nft.json +1 -1
  159. package/.next/server/app/error-items/[id]/page_client-reference-manifest.js +1 -1
  160. package/.next/server/app/exams/[id]/page.js.nft.json +1 -1
  161. package/.next/server/app/exams/[id]/page_client-reference-manifest.js +1 -1
  162. package/.next/server/app/exams/[id]/print/page.js.nft.json +1 -1
  163. package/.next/server/app/exams/[id]/print/page_client-reference-manifest.js +1 -1
  164. package/.next/server/app/exams/page.js.nft.json +1 -1
  165. package/.next/server/app/exams/page_client-reference-manifest.js +1 -1
  166. package/.next/server/app/favicon.ico/route.js +1 -1
  167. package/.next/server/app/favicon.ico/route.js.nft.json +1 -1
  168. package/.next/server/app/login/page.js.nft.json +1 -1
  169. package/.next/server/app/login/page_client-reference-manifest.js +1 -1
  170. package/.next/server/app/manifest.webmanifest/route.js +1 -1
  171. package/.next/server/app/manifest.webmanifest/route.js.nft.json +1 -1
  172. package/.next/server/app/notebooks/[id]/add/page.js.nft.json +1 -1
  173. package/.next/server/app/notebooks/[id]/add/page_client-reference-manifest.js +1 -1
  174. package/.next/server/app/notebooks/[id]/page.js.nft.json +1 -1
  175. package/.next/server/app/notebooks/[id]/page_client-reference-manifest.js +1 -1
  176. package/.next/server/app/notebooks/page.js.nft.json +1 -1
  177. package/.next/server/app/notebooks/page_client-reference-manifest.js +1 -1
  178. package/.next/server/app/page.js.nft.json +1 -1
  179. package/.next/server/app/page_client-reference-manifest.js +1 -1
  180. package/.next/server/app/practice/page.js.nft.json +1 -1
  181. package/.next/server/app/practice/page_client-reference-manifest.js +1 -1
  182. package/.next/server/app/print-preview/page.js.nft.json +1 -1
  183. package/.next/server/app/print-preview/page_client-reference-manifest.js +1 -1
  184. package/.next/server/app/register/page.js.nft.json +1 -1
  185. package/.next/server/app/register/page_client-reference-manifest.js +1 -1
  186. package/.next/server/app/review/page.js.nft.json +1 -1
  187. package/.next/server/app/review/page_client-reference-manifest.js +1 -1
  188. package/.next/server/app/stats/page.js.nft.json +1 -1
  189. package/.next/server/app/stats/page_client-reference-manifest.js +1 -1
  190. package/.next/server/app/tags/page.js.nft.json +1 -1
  191. package/.next/server/app/tags/page_client-reference-manifest.js +1 -1
  192. package/.next/server/app-paths-manifest.json +3 -0
  193. package/.next/server/chunks/{[externals]__1yyxisf-dquqj._.js → [externals]__1242krpdwt3fy._.js} +1 -1
  194. package/.next/server/chunks/{[externals]__0pot68n2q47fn._.js → [externals]__1pplcusjo3ok7._.js} +1 -1
  195. package/.next/server/chunks/[externals]__1zw_oy_-csyo1._.js +3 -0
  196. package/.next/server/chunks/{[root-of-the-server]__03_k40ubn0a9g._.js → [root-of-the-server]__0-12_rul4y06m._.js} +1 -1
  197. package/.next/server/chunks/{[root-of-the-server]__1dll9dp1pfrtj._.js → [root-of-the-server]__0-jhvuvprdrmu._.js} +2 -2
  198. package/.next/server/chunks/{[root-of-the-server]__00vnodiir_2d4._.js → [root-of-the-server]__0-lanxvfyc5w7._.js} +1 -1
  199. package/.next/server/chunks/{[root-of-the-server]__0rg4hkgdxbjou._.js → [root-of-the-server]__00rgirsp29kma._.js} +1 -1
  200. package/.next/server/chunks/{[root-of-the-server]__15eu8gun_s7xv._.js → [root-of-the-server]__023qntqk9nbma._.js} +2 -2
  201. package/.next/server/chunks/{[root-of-the-server]__18si67df5ho67._.js → [root-of-the-server]__035mztvplnh0_._.js} +2 -2
  202. package/.next/server/chunks/{[root-of-the-server]__0ry-pq8_6mc_0._.js → [root-of-the-server]__03nsgjsm70ted._.js} +2 -2
  203. package/.next/server/chunks/{[root-of-the-server]__1klj9kp10-bta._.js → [root-of-the-server]__03rln5n_21ad0._.js} +2 -2
  204. package/.next/server/chunks/{[root-of-the-server]__0-d9f8_x-uokl._.js → [root-of-the-server]__05-dvjb11wbvo._.js} +1 -1
  205. package/.next/server/chunks/{[root-of-the-server]__061dm-7_xqjef._.js → [root-of-the-server]__0ayraoa4xz-qt._.js} +2 -2
  206. package/.next/server/chunks/{[root-of-the-server]__04894g43fsy-j._.js → [root-of-the-server]__0b3ss-8ztcftu._.js} +1 -1
  207. package/.next/server/chunks/[root-of-the-server]__0dmllzem7rfag._.js +3 -0
  208. package/.next/server/chunks/[root-of-the-server]__0gx76tnihfcyv._.js +3 -0
  209. package/.next/server/chunks/{[root-of-the-server]__0an5a3hedd42o._.js → [root-of-the-server]__0h7igxq4ub38i._.js} +2 -2
  210. package/.next/server/chunks/{[root-of-the-server]__1i75c6j1-yn3y._.js → [root-of-the-server]__0icc6dvauvb15._.js} +2 -2
  211. package/.next/server/chunks/{[root-of-the-server]__1-g3tlhljmfsp._.js → [root-of-the-server]__0jb_3-yu-o6ms._.js} +2 -2
  212. package/.next/server/chunks/{[root-of-the-server]__1-hc0q3ck7id_._.js → [root-of-the-server]__0jjisfje72sqz._.js} +2 -2
  213. package/.next/server/chunks/[root-of-the-server]__0kskkg4ve55lv._.js +3 -0
  214. package/.next/server/chunks/[root-of-the-server]__0mbd9_76yhyaf._.js +3 -0
  215. package/.next/server/chunks/{[root-of-the-server]__1n8ih5ow23_12._.js → [root-of-the-server]__0my6t3vz24mmo._.js} +2 -2
  216. package/.next/server/chunks/{[root-of-the-server]__1k0zrfx1r08xk._.js → [root-of-the-server]__0nj600_104dqn._.js} +2 -2
  217. package/.next/server/chunks/[root-of-the-server]__0q4s9a9wy51vm._.js +3 -0
  218. package/.next/server/chunks/{[root-of-the-server]__18j9-n7s671bt._.js → [root-of-the-server]__0q_db5a74evdw._.js} +1 -1
  219. package/.next/server/chunks/{[root-of-the-server]__0_qgrtzrjahhc._.js → [root-of-the-server]__0qb8n1h-am-es._.js} +2 -2
  220. package/.next/server/chunks/{[root-of-the-server]__0yd-eoiuoru2o._.js → [root-of-the-server]__0rbh_oqaajxmo._.js} +2 -2
  221. package/.next/server/chunks/{[root-of-the-server]__1k_8n_p3i4my_._.js → [root-of-the-server]__0ssa-hz8b3v1i._.js} +1 -1
  222. package/.next/server/chunks/{[root-of-the-server]__123tftn1fdgwu._.js → [root-of-the-server]__0u2_q8y9hl1u-._.js} +2 -2
  223. package/.next/server/chunks/[root-of-the-server]__0uz7-ix0696nv._.js +3 -0
  224. package/.next/server/chunks/[root-of-the-server]__0v3k8_i3f2v13._.js +3 -0
  225. package/.next/server/chunks/[root-of-the-server]__0vu6_38lbzxar._.js +3 -0
  226. package/.next/server/chunks/[root-of-the-server]__0wcet8-wl-oad._.js +3 -0
  227. package/.next/server/chunks/{[root-of-the-server]__0hjv7gm7tjgzr._.js → [root-of-the-server]__0wmczeyrx2y7f._.js} +1 -1
  228. package/.next/server/chunks/{[root-of-the-server]__1q9wd_k6hcd5m._.js → [root-of-the-server]__0zb48en2m8yk0._.js} +3 -3
  229. package/.next/server/chunks/[root-of-the-server]__0zjg773epx4r_._.js +1 -1
  230. package/.next/server/chunks/{[root-of-the-server]__0p4dqz2jo4o3r._.js → [root-of-the-server]__0zr9l7lnr1i0l._.js} +2 -2
  231. package/.next/server/chunks/{[root-of-the-server]__0k0-mj3lzqicn._.js → [root-of-the-server]__1-302_px1h0qz._.js} +2 -2
  232. package/.next/server/chunks/[root-of-the-server]__1-9hu4j35d9ao._.js +3 -0
  233. package/.next/server/chunks/{[root-of-the-server]__00atddp_h2wsm._.js → [root-of-the-server]__12tt2pf5nuueu._.js} +2 -2
  234. package/.next/server/chunks/[root-of-the-server]__13z5coff9j0sa._.js +3 -0
  235. package/.next/server/chunks/[root-of-the-server]__14n5uude1fj4h._.js +3 -0
  236. package/.next/server/chunks/{[root-of-the-server]__1e_3xwt459gzy._.js → [root-of-the-server]__16c0c0-pt6gz4._.js} +1 -1
  237. package/.next/server/chunks/[root-of-the-server]__17pktht8hd051._.js +3 -0
  238. package/.next/server/chunks/[root-of-the-server]__18lmdddgrhac8._.js +3 -0
  239. package/.next/server/chunks/{[root-of-the-server]__1unmu-s-yg7fk._.js → [root-of-the-server]__199tod2f3vhny._.js} +2 -2
  240. package/.next/server/chunks/[root-of-the-server]__1a1fr6o2wf7qx._.js +3 -0
  241. package/.next/server/chunks/{[root-of-the-server]__0l7y2xk1m7h84._.js → [root-of-the-server]__1ar95f9mysi15._.js} +1 -1
  242. package/.next/server/chunks/[root-of-the-server]__1bep0vcwbtlfu._.js +3 -0
  243. package/.next/server/chunks/[root-of-the-server]__1esyxu40fpnyx._.js +3 -0
  244. package/.next/server/chunks/[root-of-the-server]__1fc23i58z_ao2._.js +1 -1
  245. package/.next/server/chunks/{[root-of-the-server]__15vjk2wddz8hx._.js → [root-of-the-server]__1g2qwf_mnzqly._.js} +2 -2
  246. package/.next/server/chunks/{[root-of-the-server]__20khcxfcwy16p._.js → [root-of-the-server]__1gg8lq2q9gzg2._.js} +3 -3
  247. package/.next/server/chunks/{[root-of-the-server]__1wfua4wupbgjj._.js → [root-of-the-server]__1imiyrtb6t6zp._.js} +2 -2
  248. package/.next/server/chunks/[root-of-the-server]__1iux__qytdtm5._.js +3 -0
  249. package/.next/server/chunks/[root-of-the-server]__1jhz19cuxjpmb._.js +3 -0
  250. package/.next/server/chunks/[root-of-the-server]__1jthkkelxfeb0._.js +3 -0
  251. package/.next/server/chunks/[root-of-the-server]__1k7cmt02s_syx._.js +3 -0
  252. package/.next/server/chunks/[root-of-the-server]__1kvcjw9quzr0w._.js +3 -0
  253. package/.next/server/chunks/[root-of-the-server]__1nsrbw9jntgo8._.js +3 -0
  254. package/.next/server/chunks/[root-of-the-server]__1p08ff3pxle05._.js +3 -0
  255. package/.next/server/chunks/{[root-of-the-server]__1vgkjjilvagrv._.js → [root-of-the-server]__1pulvd2ac2agx._.js} +1 -1
  256. package/.next/server/chunks/[root-of-the-server]__1rfqipe89aq-u._.js +3 -0
  257. package/.next/server/chunks/[root-of-the-server]__1uscfmw0q-en5._.js +3 -0
  258. package/.next/server/chunks/{[root-of-the-server]__15g3fbcq719hq._.js → [root-of-the-server]__1ya630gfyks-f._.js} +2 -2
  259. package/.next/server/chunks/[root-of-the-server]__1yslrvk_y61kt._.js +3 -0
  260. package/.next/server/chunks/[root-of-the-server]__1zyka21s1ahtj._.js +1 -1
  261. package/.next/server/chunks/{[root-of-the-server]__1jvkc3eu49g96._.js → [root-of-the-server]__20i0-g_8_okaf._.js} +2 -2
  262. package/.next/server/chunks/[root-of-the-server]__20sulb1y6n1b8._.js +3 -0
  263. package/.next/server/chunks/_076-jjzrfdsdk._.js +3 -0
  264. package/.next/server/chunks/_0geyrqrvyak26._.js +1 -1
  265. package/.next/server/chunks/_0kkvpy2s_y3-n._.js +1 -1
  266. package/.next/server/chunks/_0lob14xk0ko5z._.js +3 -0
  267. package/.next/server/chunks/_0ne4rbj35w-io._.js +1 -1
  268. package/.next/server/chunks/_0qsjdkq-39qbo._.js +1 -1
  269. package/.next/server/chunks/_13ffmxv8qrwi0._.js +1 -1
  270. package/.next/server/chunks/_1hp9mnz19v199._.js +3 -0
  271. package/.next/server/chunks/_1lrt8e26anbnm._.js +1 -1
  272. package/.next/server/chunks/_1pvqo-qnv-nqm._.js +1 -1
  273. package/.next/server/chunks/_next-internal_server_app_api_minimax-code_checkin_route_actions_0wqvstxphnn7t.js +3 -0
  274. package/.next/server/chunks/_next-internal_server_app_api_minimax-code_login_route_actions_0z7k0201hg8nt.js +3 -0
  275. package/.next/server/chunks/_next-internal_server_app_api_minimax-code_route_actions_0isqzusy30klb.js +3 -0
  276. package/.next/server/chunks/src_03_og0nynnyx2._.js +3 -0
  277. package/.next/server/chunks/src_lib_05svhzm9a162-._.js +1 -1
  278. package/.next/server/chunks/src_lib_logger_ts_1a0ve505bb0y2._.js +3 -0
  279. package/.next/server/chunks/src_lib_minimax-code_auth_ts_0-i5sxuori1um._.js +3 -0
  280. package/.next/server/chunks/src_lib_minimax-code_checkin_ts_1j1mpuxc1vgoz._.js +3 -0
  281. package/.next/server/chunks/ssr/{[root-of-the-server]__070lhtl_a6l81._.js → [root-of-the-server]__1vkia8gjeangv._.js} +1 -1
  282. package/.next/server/chunks/ssr/_00np6xqvkg6u-._.js +1 -1
  283. package/.next/server/chunks/ssr/src_1gayunqs8u2e2._.js +1 -1
  284. package/.next/server/chunks/ssr/src_components_providers_tsx_09kw-mv3nb6xs._.js +10 -10
  285. package/.next/server/instrumentation.js +1 -1
  286. package/.next/server/middleware-build-manifest.js +3 -3
  287. package/.next/server/middleware-manifest.json +5 -5
  288. package/.next/server/pages/500.html +1 -1
  289. package/.next/server/preview-props.json +3 -3
  290. package/.next/server/server-reference-manifest.js +1 -1
  291. package/.next/server/server-reference-manifest.json +1 -1
  292. package/.next/static/chunks/1nimjc5xqpgag.js +191 -0
  293. package/.next/static/chunks/1v_ioerabkr4s.js +1 -0
  294. package/.next/static/chunks/43gsd2ww2f2iy.css +3 -0
  295. package/package.json +1 -1
  296. package/prisma/seed.db +0 -0
  297. package/.next/server/chunks/[root-of-the-server]__076sanerpxzzq._.js +0 -3
  298. package/.next/server/chunks/[root-of-the-server]__08ftj1z8v5lqc._.js +0 -3
  299. package/.next/server/chunks/[root-of-the-server]__09-twlny39tdc._.js +0 -3
  300. package/.next/server/chunks/[root-of-the-server]__09mpwfp41rtdc._.js +0 -3
  301. package/.next/server/chunks/[root-of-the-server]__0dql4kl3n1jq6._.js +0 -3
  302. package/.next/server/chunks/[root-of-the-server]__0fyho53bjgbss._.js +0 -3
  303. package/.next/server/chunks/[root-of-the-server]__0hgoyp7m26_hk._.js +0 -3
  304. package/.next/server/chunks/[root-of-the-server]__0j-pkzf61aot8._.js +0 -3
  305. package/.next/server/chunks/[root-of-the-server]__0swyn0_rzg_pb._.js +0 -3
  306. package/.next/server/chunks/[root-of-the-server]__0tua5u4r1xt_r._.js +0 -3
  307. package/.next/server/chunks/[root-of-the-server]__0vtzo5ex73ywq._.js +0 -3
  308. package/.next/server/chunks/[root-of-the-server]__1-2dj_mbdiqvl._.js +0 -3
  309. package/.next/server/chunks/[root-of-the-server]__1-ti76u3720cd._.js +0 -3
  310. package/.next/server/chunks/[root-of-the-server]__10-um36nto0ht._.js +0 -3
  311. package/.next/server/chunks/[root-of-the-server]__10jwy1-wzrjon._.js +0 -3
  312. package/.next/server/chunks/[root-of-the-server]__12czp5_up_ywb._.js +0 -3
  313. package/.next/server/chunks/[root-of-the-server]__1bqziovn_k5u5._.js +0 -3
  314. package/.next/server/chunks/[root-of-the-server]__1cbj5r83fs2up._.js +0 -3
  315. package/.next/server/chunks/[root-of-the-server]__1d25c4t27ht5c._.js +0 -3
  316. package/.next/server/chunks/[root-of-the-server]__1dxa-5wqgxi3y._.js +0 -3
  317. package/.next/server/chunks/[root-of-the-server]__1i0nyuimhqkda._.js +0 -3
  318. package/.next/server/chunks/[root-of-the-server]__1wpzmu_3tg_74._.js +0 -3
  319. package/.next/server/chunks/[root-of-the-server]__1ztojnklvdebx._.js +0 -3
  320. package/.next/server/chunks/[root-of-the-server]__1zzfvs1z1_tig._.js +0 -3
  321. package/.next/server/chunks/src_0tzpy5j8n_1bx._.js +0 -3
  322. package/.next/static/chunks/00kfvk-buhhsb.js +0 -191
  323. package/.next/static/chunks/0_9gv911-tqmk.css +0 -3
  324. package/.next/static/chunks/2wk_a0jmwmybn.js +0 -1
  325. /package/.next/static/{ZH3ew12HOzoE3JRl8c_8L → 5uNP139l0DCSagwPDMOvD}/_buildManifest.js +0 -0
  326. /package/.next/static/{ZH3ew12HOzoE3JRl8c_8L → 5uNP139l0DCSagwPDMOvD}/_clientMiddlewareManifest.js +0 -0
  327. /package/.next/static/{ZH3ew12HOzoE3JRl8c_8L → 5uNP139l0DCSagwPDMOvD}/_ssgManifest.js +0 -0
@@ -30,9 +30,9 @@ Knowledge Points: ${t.join(", ")}
30
30
  `;h.box("🎯 Generate Similar Question Request",{provider:"Azure OpenAI",endpoint:this.endpoint,model:this.model,deployment:this.deployment,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:i,language:n}),h.box("📝 System Prompt",c),h.box("📝 User Prompt",p);try{let e=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:c},{role:"user",content:p}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",t),!t)throw Error("Empty response from AI");let r=this.parseResponse(t);return h.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,d.f)(r)}catch(e){throw h.box("❌ Error during similar question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(e,t="zh",n,i,s,a){let l=(0,r.generateReanswerPrompt)(t,e,n,{candidateTags:a},s);h.box("🔄 Reanswer Question Request",{provider:"Azure OpenAI",endpoint:this.endpoint,model:this.model,deployment:this.deployment,questionLength:e.length,subject:n||"auto",hasImage:!!i}),h.debug({prompt:l},"Full prompt");try{let e="请根据上述题目提供答案和解析。";if(i){let t=i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`;h.debug({imageLength:t.length},"Image added to request"),e=[{type:"text",text:"请结合图片和题目描述提供答案和解析。"},{type:"image_url",image_url:{url:t}}]}else h.debug({imageBase64Type:typeof i,hasValue:!!i},"No image data");let t=await (0,u.V)(t=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:l},{role:"user",content:e}],max_tokens:t}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.debug({response:JSON.stringify(t)},"Full API response"),!t||!t.choices||0===t.choices.length)throw h.error({response:JSON.stringify(t)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let r=t.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"AI raw response"),!r)throw Error("Empty response from AI");let n=this.extractTag(r,"answer_text")||"",s=this.extractTag(r,"analysis")||"",a=(this.extractTag(r,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),d=this.extractTag(r,"wrong_answer_text")||"",p=this.extractTag(r,"mistake_analysis")||"",f=(0,c.f)(this.extractTag(r,"mistake_status"),d);return h.info("Reanswer parsed successfully"),{answerText:n,analysis:s,knowledgePoints:a,wrongAnswerText:d,mistakeAnalysis:p,mistakeStatus:f,subject:(0,o.G)(this.extractTag(r,"subject")),difficultyStars:(0,o.B)(this.extractTag(r,"difficulty_stars"))}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,n,i){let s=(0,r.generateGeogebraPrompt)(e,t,n,i);h.info({provider:"Azure OpenAI",model:this.model,deployment:this.deployment,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:s},{role:"user",content:"请分析上述题目并生成 GeoGebra 演示命令。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error("Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let i=r.indexOf("{"),o=r.lastIndexOf("}");-1!==i&&-1!==o&&(r=r.substring(i,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,r.generateMasteryPrompt)(e);h.info({provider:"Azure OpenAI",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请根据上述练习历史给出掌握概率评估。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),r=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error("Empty response from AI");return(0,o.r)(r)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async gradeAnswer(e){h.info({provider:"Azure OpenAI"},"Answer Grading Request");try{let t=await (0,u.V)(t=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:(0,r.generateGradingPrompt)(e)},{role:"user",content:"请判定学生答案是否正确。"}],max_tokens:t}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=t.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Grading AI raw response"),!n)throw Error("Empty response from AI");return(0,o.o)(n)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during answer grading"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,r.generateTagSuggestPrompt)(e);h.info({provider:"Azure OpenAI",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请为上述题目选择知识点。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error("Empty response from AI");return(0,o.K)(n,e.allowedTags)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,n){let i=(0,r.generateFigurePrompt)(n);h.info({provider:"Azure OpenAI",deployment:this.deployment,imageSize:e.length},"Figure SVG Request");try{let r=await (0,u.V)(r=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:i},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Figure SVG AI raw response"),!n)throw Error("Empty response from AI");return(0,o.t)(this.extractTag(n,"has_figure"),this.extractTag(n,"figure_svg"))}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,r.generateLatexFixPrompt)(e);h.info({provider:"Azure OpenAI",deployment:this.deployment,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请修复上述内容中的 LaTeX 语法。"}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error("Empty response from AI");return(0,i.f)(n,e)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,i,s,o="zh"){let a=(0,r.generateSvgAnimationPrompt)(e,t,i,s,o);h.info({provider:"Azure OpenAI",deployment:this.deployment,questionLength:e.length},"SVG Animation Request");try{let e=await (0,u.V)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:a},{role:"user",content:r.SVG_ANIMATION_REQUEST[o]}],max_tokens:e}),16384,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error("Empty response from AI");return(0,n.f)(this.extractTag(t,"svg_animation")||t)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(h.error({error:e},"Azure OpenAI error"),e instanceof Error){if(e.message===u.z||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}])},893963,e=>{let t,r,n,i;var s,o,a,l,u,c,d,h,p,f,m,g,y,_,E,A,v,b,w,T,I,S,O,C,R,P,k,x,N,D,U,M,L,j,G,F,$,q,B,H,V,K,J,W,z,Y,X,Q,Z,ee,et,er,en,ei,es,eo,ea,el,eu,ec,ed,eh,ep,ef,em,eg,ey,e_,eE,eA,ev,eb,ew,eT,eI,eS,eO,eC,eR,eP,ek,ex,eN,eD,eU,eM,eL,ej,eG,eF,e$,eq,eB,eH,eV,eK,eJ,eW,ez,eY,eX,eQ,eZ,e0,e1,e2,e4,e6,e3,e5,e8,e9,e7,te,tt,tr,tn,ti,ts,to,ta,tl,tu,tc,td,th,tp,tf,tm,tg,ty,t_,tE,tA=e.i(736850),tv=e.i(947334),tb=e.i(522734),tw=e.i(924868),tT=e.i(81111),tI=e.i(188646);e.i(721365),e.i(196903),e.i(580295),e.i(629485),e.i(816735),e.i(942977);var tS=e.i(835065);e.i(217198),tS.default;var tO=e.i(814747);class tC{}function tR(e,t){return e.replace(/\{([^}]+)\}/g,(e,r)=>{if(Object.prototype.hasOwnProperty.call(t,r)){let e=t[r];return null!=e?String(e):""}throw Error(`Key '${r}' not found in valueMap.`)})}function tP(e,t,r){for(let n=0;n<t.length-1;n++){let i=t[n];if(i.endsWith("[]")){let s=i.slice(0,-2);if(!(s in e))if(Array.isArray(r))e[s]=Array.from({length:r.length},()=>({}));else throw Error(`Value must be a list given an array path ${i}`);if(Array.isArray(e[s])){let i=e[s];if(Array.isArray(r))for(let e=0;e<i.length;e++)tP(i[e],t.slice(n+1),r[e]);else for(let e of i)tP(e,t.slice(n+1),r)}return}if(i.endsWith("[0]")){let s=i.slice(0,-3);s in e||(e[s]=[{}]),tP(e[s][0],t.slice(n+1),r);return}e[i]&&"object"==typeof e[i]||(e[i]={}),e=e[i]}let n=t[t.length-1],i=e[n];if(void 0!==i){if(!r||"object"==typeof r&&0===Object.keys(r).length||r===i)return;if("object"==typeof i&&"object"==typeof r&&null!==i&&null!==r)Object.assign(i,r);else throw Error(`Cannot set value for an existing key. Key: ${n}`)}else"_self"!==n||"object"!=typeof r||null===r||Array.isArray(r)?e[n]=r:Object.assign(e,r)}function tk(e,t,r){try{if(1===t.length&&"_self"===t[0])return e;for(let n=0;n<t.length;n++){if("object"!=typeof e||null===e)return r;let i=t[n];if(i.endsWith("[]")){let s=i.slice(0,-2);if(!(s in e))return r;{let i=e[s];if(!Array.isArray(i))return r;return i.map(e=>tk(e,t.slice(n+1),r))}}e=e[i]}return e}catch(e){if(e instanceof TypeError)return r;throw e}}function tx(e){if("string"!=typeof e)throw Error("fromImageBytes must be a string");return e}function tN(e){var t;let r,n,i,s,o={},a=tk(e,["name"]);null!=a&&tP(o,["name"],a);let l=tk(e,["metadata"]);null!=l&&tP(o,["metadata"],l);let u=tk(e,["done"]);null!=u&&tP(o,["done"],u);let c=tk(e,["error"]);null!=c&&tP(o,["error"],c);let d=tk(e,["response"]);return null!=d&&tP(o,["response"],(r={},null!=(n=tk(t=d,["sdkHttpResponse"]))&&tP(r,["sdkHttpResponse"],n),null!=(i=tk(t,["parent"]))&&tP(r,["parent"],i),null!=(s=tk(t,["documentName"]))&&tP(r,["documentName"],s),r)),o}(s=ey||(ey={})).LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",s.PYTHON="PYTHON",(o=e_||(e_={})).OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",o.OUTCOME_OK="OUTCOME_OK",o.OUTCOME_FAILED="OUTCOME_FAILED",o.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED",(a=eE||(eE={})).SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",a.SILENT="SILENT",a.WHEN_IDLE="WHEN_IDLE",a.INTERRUPT="INTERRUPT",(l=eA||(eA={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",l.STRING="STRING",l.NUMBER="NUMBER",l.INTEGER="INTEGER",l.BOOLEAN="BOOLEAN",l.ARRAY="ARRAY",l.OBJECT="OBJECT",l.NULL="NULL",(u=ev||(ev={})).ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",u.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",(c=eb||(eb={})).AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",c.NO_AUTH="NO_AUTH",c.API_KEY_AUTH="API_KEY_AUTH",c.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",c.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",c.OAUTH="OAUTH",c.OIDC_AUTH="OIDC_AUTH",(d=ew||(ew={})).HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",d.HTTP_IN_QUERY="HTTP_IN_QUERY",d.HTTP_IN_HEADER="HTTP_IN_HEADER",d.HTTP_IN_PATH="HTTP_IN_PATH",d.HTTP_IN_BODY="HTTP_IN_BODY",d.HTTP_IN_COOKIE="HTTP_IN_COOKIE",(h=eT||(eT={})).API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",h.SIMPLE_SEARCH="SIMPLE_SEARCH",h.ELASTIC_SEARCH="ELASTIC_SEARCH",(p=eI||(eI={})).PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",p.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",p.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",p.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",p.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",p.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",p.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH",(f=eS||(eS={})).UNSPECIFIED="UNSPECIFIED",f.BLOCKING="BLOCKING",f.NON_BLOCKING="NON_BLOCKING",(m=eO||(eO={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",m.MODE_DYNAMIC="MODE_DYNAMIC",(g=eC||(eC={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",g.AUTO="AUTO",g.ANY="ANY",g.NONE="NONE",g.VALIDATED="VALIDATED",(y=eR||(eR={})).THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",y.MINIMAL="MINIMAL",y.LOW="LOW",y.MEDIUM="MEDIUM",y.HIGH="HIGH",(_=eP||(eP={})).DONT_ALLOW="DONT_ALLOW",_.ALLOW_ADULT="ALLOW_ADULT",_.ALLOW_ALL="ALLOW_ALL",(E=ek||(ek={})).PROMINENT_PEOPLE_UNSPECIFIED="PROMINENT_PEOPLE_UNSPECIFIED",E.ALLOW_PROMINENT_PEOPLE="ALLOW_PROMINENT_PEOPLE",E.BLOCK_PROMINENT_PEOPLE="BLOCK_PROMINENT_PEOPLE",(A=ex||(ex={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",A.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",A.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",A.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",A.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",A.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",A.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",A.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",A.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",A.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",A.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",(v=eN||(eN={})).HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",v.SEVERITY="SEVERITY",v.PROBABILITY="PROBABILITY",(b=eD||(eD={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",b.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",b.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",b.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",b.BLOCK_NONE="BLOCK_NONE",b.OFF="OFF",(w=eU||(eU={})).FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",w.STOP="STOP",w.MAX_TOKENS="MAX_TOKENS",w.SAFETY="SAFETY",w.RECITATION="RECITATION",w.LANGUAGE="LANGUAGE",w.OTHER="OTHER",w.BLOCKLIST="BLOCKLIST",w.PROHIBITED_CONTENT="PROHIBITED_CONTENT",w.SPII="SPII",w.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",w.IMAGE_SAFETY="IMAGE_SAFETY",w.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",w.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",w.NO_IMAGE="NO_IMAGE",w.IMAGE_RECITATION="IMAGE_RECITATION",w.IMAGE_OTHER="IMAGE_OTHER",(T=eM||(eM={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",T.NEGLIGIBLE="NEGLIGIBLE",T.LOW="LOW",T.MEDIUM="MEDIUM",T.HIGH="HIGH",(I=eL||(eL={})).HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",I.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",I.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",I.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",I.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH",(S=ej||(ej={})).URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",S.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",S.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",S.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",S.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE",(O=eG||(eG={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",O.SAFETY="SAFETY",O.OTHER="OTHER",O.BLOCKLIST="BLOCKLIST",O.PROHIBITED_CONTENT="PROHIBITED_CONTENT",O.IMAGE_SAFETY="IMAGE_SAFETY",O.MODEL_ARMOR="MODEL_ARMOR",O.JAILBREAK="JAILBREAK",(C=eF||(eF={})).TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",C.ON_DEMAND="ON_DEMAND",C.ON_DEMAND_PRIORITY="ON_DEMAND_PRIORITY",C.ON_DEMAND_FLEX="ON_DEMAND_FLEX",C.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT",(R=e$||(e$={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",R.TEXT="TEXT",R.IMAGE="IMAGE",R.AUDIO="AUDIO",R.VIDEO="VIDEO",(P=eq||(eq={})).MODEL_STAGE_UNSPECIFIED="MODEL_STAGE_UNSPECIFIED",P.UNSTABLE_EXPERIMENTAL="UNSTABLE_EXPERIMENTAL",P.EXPERIMENTAL="EXPERIMENTAL",P.PREVIEW="PREVIEW",P.STABLE="STABLE",P.LEGACY="LEGACY",P.DEPRECATED="DEPRECATED",P.RETIRED="RETIRED",(k=eB||(eB={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",k.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",k.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",k.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",(x=eH||(eH={})).TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",x.TUNING_MODE_FULL="TUNING_MODE_FULL",x.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER",(N=eV||(eV={})).ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",N.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",N.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",N.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",N.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",N.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",N.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO",(D=eK||(eK={})).JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",D.JOB_STATE_QUEUED="JOB_STATE_QUEUED",D.JOB_STATE_PENDING="JOB_STATE_PENDING",D.JOB_STATE_RUNNING="JOB_STATE_RUNNING",D.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",D.JOB_STATE_FAILED="JOB_STATE_FAILED",D.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",D.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",D.JOB_STATE_PAUSED="JOB_STATE_PAUSED",D.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",D.JOB_STATE_UPDATING="JOB_STATE_UPDATING",D.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED",(U=eJ||(eJ={})).TUNING_JOB_STATE_UNSPECIFIED="TUNING_JOB_STATE_UNSPECIFIED",U.TUNING_JOB_STATE_WAITING_FOR_QUOTA="TUNING_JOB_STATE_WAITING_FOR_QUOTA",U.TUNING_JOB_STATE_PROCESSING_DATASET="TUNING_JOB_STATE_PROCESSING_DATASET",U.TUNING_JOB_STATE_WAITING_FOR_CAPACITY="TUNING_JOB_STATE_WAITING_FOR_CAPACITY",U.TUNING_JOB_STATE_TUNING="TUNING_JOB_STATE_TUNING",U.TUNING_JOB_STATE_POST_PROCESSING="TUNING_JOB_STATE_POST_PROCESSING",(M=eW||(eW={})).AGGREGATION_METRIC_UNSPECIFIED="AGGREGATION_METRIC_UNSPECIFIED",M.AVERAGE="AVERAGE",M.MODE="MODE",M.STANDARD_DEVIATION="STANDARD_DEVIATION",M.VARIANCE="VARIANCE",M.MINIMUM="MINIMUM",M.MAXIMUM="MAXIMUM",M.MEDIAN="MEDIAN",M.PERCENTILE_P90="PERCENTILE_P90",M.PERCENTILE_P95="PERCENTILE_P95",M.PERCENTILE_P99="PERCENTILE_P99",(L=ez||(ez={})).PAIRWISE_CHOICE_UNSPECIFIED="PAIRWISE_CHOICE_UNSPECIFIED",L.BASELINE="BASELINE",L.CANDIDATE="CANDIDATE",L.TIE="TIE",(j=eY||(eY={})).TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",j.TUNING_TASK_I2V="TUNING_TASK_I2V",j.TUNING_TASK_T2V="TUNING_TASK_T2V",j.TUNING_TASK_R2V="TUNING_TASK_R2V",(G=eX||(eX={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",G.STATE_PENDING="STATE_PENDING",G.STATE_ACTIVE="STATE_ACTIVE",G.STATE_FAILED="STATE_FAILED",(F=eQ||(eQ={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",F.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",F.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",F.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",F.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH",($=eZ||(eZ={})).TOOL_TYPE_UNSPECIFIED="TOOL_TYPE_UNSPECIFIED",$.GOOGLE_SEARCH_WEB="GOOGLE_SEARCH_WEB",$.GOOGLE_SEARCH_IMAGE="GOOGLE_SEARCH_IMAGE",$.URL_CONTEXT="URL_CONTEXT",$.GOOGLE_MAPS="GOOGLE_MAPS",$.FILE_SEARCH="FILE_SEARCH",(e0||(e0={})).COLLECTION="COLLECTION",(q=e1||(e1={})).UNSPECIFIED="unspecified",q.FLEX="flex",q.STANDARD="standard",q.PRIORITY="priority",(B=e2||(e2={})).FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",B.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",B.BALANCED="BALANCED",B.PRIORITIZE_COST="PRIORITIZE_COST",(H=e4||(e4={})).PREDICT="PREDICT",H.EMBED_CONTENT="EMBED_CONTENT",(V=e6||(e6={})).BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",V.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",V.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",V.BLOCK_NONE="BLOCK_NONE",(K=e3||(e3={})).auto="auto",K.en="en",K.ja="ja",K.ko="ko",K.hi="hi",K.zh="zh",K.pt="pt",K.es="es",(J=e5||(e5={})).MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",J.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",J.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",J.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",J.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC",(W=e8||(e8={})).CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",W.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",W.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",W.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH",(z=e9||(e9={})).SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",z.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",z.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",z.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT",(Y=e7||(e7={})).EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",Y.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",Y.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",Y.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",Y.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",Y.EDIT_MODE_STYLE="EDIT_MODE_STYLE",Y.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",Y.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE",(X=te||(te={})).FOREGROUND="FOREGROUND",X.BACKGROUND="BACKGROUND",X.PROMPT="PROMPT",X.SEMANTIC="SEMANTIC",X.INTERACTIVE="INTERACTIVE",(Q=tt||(tt={})).ASSET="ASSET",Q.STYLE="STYLE",(Z=tr||(tr={})).INSERT="INSERT",Z.REMOVE="REMOVE",Z.REMOVE_STATIC="REMOVE_STATIC",Z.OUTPAINT="OUTPAINT",(ee=tn||(tn={})).OPTIMIZED="OPTIMIZED",ee.LOSSLESS="LOSSLESS",(et=ti||(ti={})).CROP="CROP",et.PAD="PAD",(er=ts||(ts={})).SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",er.PREFERENCE_TUNING="PREFERENCE_TUNING",er.DISTILLATION="DISTILLATION",(en=to||(to={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",en.PROCESSING="PROCESSING",en.ACTIVE="ACTIVE",en.FAILED="FAILED",(ei=ta||(ta={})).SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",ei.UPLOADED="UPLOADED",ei.GENERATED="GENERATED",ei.REGISTERED="REGISTERED",(es=tl||(tl={})).TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",es.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",es.RESPONSE_REJECTED="RESPONSE_REJECTED",es.NEED_MORE_INPUT="NEED_MORE_INPUT",es.PROHIBITED_INPUT_CONTENT="PROHIBITED_INPUT_CONTENT",es.IMAGE_PROHIBITED_INPUT_CONTENT="IMAGE_PROHIBITED_INPUT_CONTENT",es.INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED="INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED",es.INPUT_IMAGE_CELEBRITY="INPUT_IMAGE_CELEBRITY",es.INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED="INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED",es.INPUT_TEXT_NCII_PROHIBITED="INPUT_TEXT_NCII_PROHIBITED",es.INPUT_OTHER="INPUT_OTHER",es.INPUT_IP_PROHIBITED="INPUT_IP_PROHIBITED",es.BLOCKLIST="BLOCKLIST",es.UNSAFE_PROMPT_FOR_IMAGE_GENERATION="UNSAFE_PROMPT_FOR_IMAGE_GENERATION",es.GENERATED_IMAGE_SAFETY="GENERATED_IMAGE_SAFETY",es.GENERATED_CONTENT_SAFETY="GENERATED_CONTENT_SAFETY",es.GENERATED_AUDIO_SAFETY="GENERATED_AUDIO_SAFETY",es.GENERATED_VIDEO_SAFETY="GENERATED_VIDEO_SAFETY",es.GENERATED_CONTENT_PROHIBITED="GENERATED_CONTENT_PROHIBITED",es.GENERATED_CONTENT_BLOCKLIST="GENERATED_CONTENT_BLOCKLIST",es.GENERATED_IMAGE_PROHIBITED="GENERATED_IMAGE_PROHIBITED",es.GENERATED_IMAGE_CELEBRITY="GENERATED_IMAGE_CELEBRITY",es.GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER="GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER",es.GENERATED_IMAGE_IDENTIFIABLE_PEOPLE="GENERATED_IMAGE_IDENTIFIABLE_PEOPLE",es.GENERATED_IMAGE_MINORS="GENERATED_IMAGE_MINORS",es.OUTPUT_IMAGE_IP_PROHIBITED="OUTPUT_IMAGE_IP_PROHIBITED",es.GENERATED_OTHER="GENERATED_OTHER",es.MAX_REGENERATION_REACHED="MAX_REGENERATION_REACHED",(eo=tu||(tu={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",eo.TEXT="TEXT",eo.IMAGE="IMAGE",eo.VIDEO="VIDEO",eo.AUDIO="AUDIO",eo.DOCUMENT="DOCUMENT",(ea=tc||(tc={})).VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",ea.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",ea.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS",(el=td||(td={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",el.ACTIVITY_START="ACTIVITY_START",el.ACTIVITY_END="ACTIVITY_END",(eu=th||(th={})).START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",eu.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",eu.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW",(ec=tp||(tp={})).END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",ec.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",ec.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW",(ed=tf||(tf={})).ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",ed.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",ed.NO_INTERRUPTION="NO_INTERRUPTION",(eh=tm||(tm={})).TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",eh.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",eh.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",eh.TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO="TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO",(ep=tg||(tg={})).SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",ep.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",ep.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",ep.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",ep.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",ep.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",ep.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",ep.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",ep.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",ep.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",ep.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",ep.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",ep.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR",(ef=ty||(ty={})).MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",ef.QUALITY="QUALITY",ef.DIVERSITY="DIVERSITY",ef.VOCALIZATION="VOCALIZATION",(em=t_||(t_={})).PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",em.PLAY="PLAY",em.PAUSE="PAUSE",em.STOP="STOP",em.RESET_CONTEXT="RESET_CONTEXT";class tD{constructor(e){let t={};for(let r of e.headers.entries())t[r[0]]=r[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}}class tU{get text(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let l="",u=!1,c=[];for(let e of null!=(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?a:[]){for(let[t,r]of Object.entries(e))"text"!==t&&"thought"!==t&&"thoughtSignature"!==t&&(null!==r||void 0!==r)&&c.push(t);if("string"==typeof e.text){if("boolean"==typeof e.thought&&e.thought)continue;u=!0,l+=e.text}}return c.length>0&&console.warn(`there are non-text parts ${c} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),u?l:void 0}get data(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let l="",u=[];for(let e of null!=(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?a:[]){for(let[t,r]of Object.entries(e))"inlineData"!==t&&(null!==r||void 0!==r)&&u.push(t);e.inlineData&&"string"==typeof e.inlineData.data&&(l+=atob(e.inlineData.data))}return u.length>0&&console.warn(`there are non-data parts ${u} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),l.length>0?btoa(l):void 0}get functionCalls(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let l=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.functionCall).map(e=>e.functionCall).filter(e=>void 0!==e);if((null==l?void 0:l.length)!==0)return l}get executableCode(){var e,t,r,n,i,s,o,a,l;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let u=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.executableCode).map(e=>e.executableCode).filter(e=>void 0!==e);if((null==u?void 0:u.length)!==0)return null==(l=null==u?void 0:u[0])?void 0:l.code}get codeExecutionResult(){var e,t,r,n,i,s,o,a,l;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let u=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.codeExecutionResult).map(e=>e.codeExecutionResult).filter(e=>void 0!==e);if((null==u?void 0:u.length)!==0)return null==(l=null==u?void 0:u[0])?void 0:l.output}}class tM{}class tL{}class tj{}class tG{}class tF{}class t${}class tq{}class tB{}class tH{}class tV{}class tK{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let r,n=new tK;if(t){let t,n,i,s,o,a;t={},null!=(n=tk(e,["name"]))&&tP(t,["name"],n),null!=(i=tk(e,["metadata"]))&&tP(t,["metadata"],i),null!=(s=tk(e,["done"]))&&tP(t,["done"],s),null!=(o=tk(e,["error"]))&&tP(t,["error"],o),null!=(a=tk(e,["response"]))&&tP(t,["response"],function(e){let t={},r=tk(e,["videos"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=tk(e,["_self"]))&&tP(r,["video"],(i={},null!=(s=tk(t=n,["gcsUri"]))&&tP(i,["uri"],s),null!=(o=tk(t,["bytesBase64Encoded"]))&&tP(i,["videoBytes"],tx(o)),null!=(a=tk(t,["mimeType"]))&&tP(i,["mimeType"],a),i)),r})),tP(t,["generatedVideos"],e)}let n=tk(e,["raiMediaFilteredCount"]);null!=n&&tP(t,["raiMediaFilteredCount"],n);let i=tk(e,["raiMediaFilteredReasons"]);return null!=i&&tP(t,["raiMediaFilteredReasons"],i),t}(a)),r=t}else{let t,n,i,s,o,a;t={},null!=(n=tk(e,["name"]))&&tP(t,["name"],n),null!=(i=tk(e,["metadata"]))&&tP(t,["metadata"],i),null!=(s=tk(e,["done"]))&&tP(t,["done"],s),null!=(o=tk(e,["error"]))&&tP(t,["error"],o),null!=(a=tk(e,["response","generateVideoResponse"]))&&tP(t,["response"],function(e){let t={},r=tk(e,["generatedSamples"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=tk(e,["video"]))&&tP(r,["video"],(i={},null!=(s=tk(t=n,["uri"]))&&tP(i,["uri"],s),null!=(o=tk(t,["encodedVideo"]))&&tP(i,["videoBytes"],tx(o)),null!=(a=tk(t,["encoding"]))&&tP(i,["mimeType"],a),i)),r})),tP(t,["generatedVideos"],e)}let n=tk(e,["raiMediaFilteredCount"]);null!=n&&tP(t,["raiMediaFilteredCount"],n);let i=tk(e,["raiMediaFilteredReasons"]);return null!=i&&tP(t,["raiMediaFilteredReasons"],i),t}(a)),r=t}return Object.assign(n,r),n}}class tJ{}class tW{}class tz{}class tY{}class tX{}class tQ{}class tZ{}class t0{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){var r;let n,i,s,o,a,l,u,c,d,h,p=new t0;return Object.assign(p,(a={},null!=(l=tk(e,["name"]))&&tP(a,["name"],l),null!=(u=tk(e,["metadata"]))&&tP(a,["metadata"],u),null!=(c=tk(e,["done"]))&&tP(a,["done"],c),null!=(d=tk(e,["error"]))&&tP(a,["error"],d),null!=(h=tk(e,["response"]))&&tP(a,["response"],(n={},null!=(i=tk(r=h,["sdkHttpResponse"]))&&tP(n,["sdkHttpResponse"],i),null!=(s=tk(r,["parent"]))&&tP(n,["parent"],s),null!=(o=tk(r,["documentName"]))&&tP(n,["documentName"],o),n)),a)),p}}class t1{}class t2{}class t4{}class t6{}class t3{}class t5{get text(){var e,t,r;let n="",i=!1,s=[];for(let o of null!=(r=null==(t=null==(e=this.serverContent)?void 0:e.modelTurn)?void 0:t.parts)?r:[]){for(let[e,t]of Object.entries(o))"text"!==e&&"thought"!==e&&null!==t&&s.push(e);if("string"==typeof o.text){if("boolean"==typeof o.thought&&o.thought)continue;i=!0,n+=o.text}}return s.length>0&&console.warn(`there are non-text parts ${s} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),i?n:void 0}get data(){var e,t,r;let n="",i=[];for(let s of null!=(r=null==(t=null==(e=this.serverContent)?void 0:e.modelTurn)?void 0:t.parts)?r:[]){for(let[e,t]of Object.entries(s))"inlineData"!==e&&null!==t&&i.push(e);s.inlineData&&"string"==typeof s.inlineData.data&&(n+=atob(s.inlineData.data))}return i.length>0&&console.warn(`there are non-data parts ${i} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),n.length>0?btoa(n):void 0}}class t8{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class t9{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let r=new t9;return Object.assign(r,tN(e)),r}}function t7(e,t){if(!t||"string"!=typeof t)throw Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw Error("invalid model parameter");if(e.isVertexAI())if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;else{if(!(t.indexOf("/")>=0))return`publishers/google/models/${t}`;let e=t.split("/",2);return`publishers/${e[0]}/models/${e[1]}`}return t.startsWith("models/")||t.startsWith("tunedModels/")?t:`models/${t}`}function re(e,t){let r=t7(e,t);return r?r.startsWith("publishers/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${r}`:r.startsWith("models/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${r}`:r:""}function rt(e){return Array.isArray(e)?e.map(e=>rr(e)):[rr(e)]}function rr(e){if("object"==typeof e&&null!==e)return e;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function rn(e){let t=rr(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function ri(e){let t=rr(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function rs(e){if(null==e)throw Error("PartUnion is required");if("object"==typeof e)return e;if("string"==typeof e)return{text:e};throw Error(`Unsupported part type: ${typeof e}`)}function ro(e){if(null==e||Array.isArray(e)&&0===e.length)throw Error("PartListUnion is required");return Array.isArray(e)?e.map(e=>rs(e)):[rs(e)]}function ra(e){return null!=e&&"object"==typeof e&&"parts"in e&&Array.isArray(e.parts)}function rl(e){return null!=e&&"object"==typeof e&&"functionCall"in e}function ru(e){return null!=e&&"object"==typeof e&&"functionResponse"in e}function rc(e){if(null==e)throw Error("ContentUnion is required");return ra(e)?e:{role:"user",parts:ro(e)}}function rd(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{let t=rc(e);return t.parts&&t.parts.length>0&&void 0!==t.parts[0].text?[t.parts[0].text]:[]});if(e.isVertexAI()){let e=rc(t);return e.parts&&e.parts.length>0&&void 0!==e.parts[0].text?[e.parts[0].text]:[]}return Array.isArray(t)?t.map(e=>rc(e)):[rc(t)]}function rh(e){if(null==e||Array.isArray(e)&&0===e.length)throw Error("contents are required");if(!Array.isArray(e)){if(rl(e)||ru(e))throw Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[rc(e)]}let t=[],r=[],n=ra(e[0]);for(let i of e){let e=ra(i);if(e!=n)throw Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(e)t.push(i);else if(rl(i)||ru(i))throw Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");else r.push(i)}return n||t.push({role:"user",parts:ro(r)}),t}function rp(e){let t={},r=["items"],n=["anyOf"],i=["properties"];if(e.type&&e.anyOf)throw Error("type and anyOf cannot be both populated.");let s=e.anyOf;for(let[o,a]of(null!=s&&2==s.length&&("null"===s[0].type?(t.nullable=!0,e=s[1]):"null"===s[1].type&&(t.nullable=!0,e=s[0])),e.type instanceof Array&&function(e,t){e.includes("null")&&(t.nullable=!0);let r=e.filter(e=>"null"!==e);if(1===r.length)t.type=Object.values(eA).includes(r[0].toUpperCase())?r[0].toUpperCase():eA.TYPE_UNSPECIFIED;else for(let e of(t.anyOf=[],r))t.anyOf.push({type:Object.values(eA).includes(e.toUpperCase())?e.toUpperCase():eA.TYPE_UNSPECIFIED})}(e.type,t),Object.entries(e)))if(null!=a)if("type"==o){if("null"===a)throw Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;t.type=Object.values(eA).includes(a.toUpperCase())?a.toUpperCase():eA.TYPE_UNSPECIFIED}else if(r.includes(o))t[o]=rp(a);else if(n.includes(o)){let e=[];for(let r of a){if("null"==r.type){t.nullable=!0;continue}e.push(rp(r))}t[o]=e}else if(i.includes(o)){let e={};for(let[t,r]of Object.entries(a))e[t]=rp(r);t[o]=e}else{if("additionalProperties"===o)continue;t[o]=a}return t}function rf(e){if("object"==typeof e)return e;if("string"==typeof e)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw Error(`Unsupported speechConfig type: ${typeof e}`)}function rm(e){if("multiSpeakerVoiceConfig"in e)throw Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function rg(e){if(e.functionDeclarations)for(let t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes("$schema")?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=rp(t.parameters)),t.response&&(Object.keys(t.response).includes("$schema")?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=rp(t.response));return e}function ry(e){if(null==e)throw Error("tools is required");if(!Array.isArray(e))throw Error("tools is required and must be an array of Tools");let t=[];for(let r of e)t.push(r);return t}function r_(e,t){if("string"!=typeof t)throw Error("name must be a string");return function(e,t,r,n=1){let i=!t.startsWith(`${r}/`)&&t.split("/").length===n;if(e.isVertexAI())if(t.startsWith("projects/"))return t;else if(t.startsWith("locations/"))return`projects/${e.getProject()}/${t}`;else if(t.startsWith(`${r}/`))return`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`;else if(i)return`projects/${e.getProject()}/locations/${e.getLocation()}/${r}/${t}`;else return t;return i?`${r}/${t}`:t}(e,t,"cachedContents")}function rE(e){switch(e){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return e}}function rA(e){return null!=e&&"object"==typeof e&&"video"in e}function rv(e){return null!=e&&"object"==typeof e&&"uri"in e}function rb(e){var t;let r;if(null!=e&&"object"==typeof e&&"name"in e&&(r=e.name),!rv(e)||void 0!==(r=e.uri)){if(!rA(e)||void 0!==(r=null==(t=e.video)?void 0:t.uri)){if("string"==typeof e&&(r=e),void 0===r)throw Error("Could not extract file name from the provided input.");if(r.startsWith("https://")){let e=r.split("files/")[1].match(/[a-z0-9]+/);if(null===e)throw Error(`Could not extract file name from URI ${r}`);r=e[0]}else r.startsWith("files/")&&(r=r.split("files/")[1]);return r}}}function rw(e,t){return e.isVertexAI()?t?"publishers/google/models":"models":t?"models":"tunedModels"}function rT(e){for(let n of["models","tunedModels","publisherModels"]){var t,r;if(t=e,r=n,null!==t&&"object"==typeof t&&r in t)return e[n]}return[]}function rI(e,t){let r;if("string"==typeof t)if(e.isVertexAI())if(t.startsWith("gs://"))r={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))r={format:"bigquery",bigqueryUri:t};else if(/^projects\/[^/]+\/locations\/[^/]+\/datasets\/[^/]+$/.test(t))r={format:"vertex-dataset",vertexDatasetName:t};else throw Error(`Unsupported string source for Vertex AI: ${t}`);else if(t.startsWith("files/"))r={fileName:t};else throw Error(`Unsupported string source for Gemini API: ${t}`);else if(Array.isArray(t)){if(e.isVertexAI())throw Error("InlinedRequest[] is not supported in Vertex AI.");r={inlinedRequests:t}}else r=t;let n=[r.gcsUri,r.bigqueryUri,r.vertexDatasetName].filter(Boolean).length,i=[r.inlinedRequests,r.fileName].filter(Boolean).length;if(e.isVertexAI()){if(i>0||1!==n)throw Error("Exactly one of `gcsUri`, `bigqueryUri`, or `vertexDatasetName` must be set for Vertex AI.")}else if(n>0||1!==i)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return r}function rS(e){if("object"!=typeof e||null===e)return{};let t=e.inlinedResponses;if("object"!=typeof t||null===t)return e;let r=t.inlinedResponses;if(!Array.isArray(r)||0===r.length)return e;let n=!1;for(let e of r){if("object"!=typeof e||null===e)continue;let t=e.response;if("object"==typeof t&&null!==t&&void 0!==t.embedding){n=!0;break}}return n&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),e}function rO(e,t){if(!e.isVertexAI()){if(/batches\/[^/]+$/.test(t))return t.split("/").pop();throw Error(`Invalid batch job name: ${t}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(t))return t.split("/").pop();if(/^\d+$/.test(t))return t;throw Error(`Invalid batch job name: ${t}.`)}function rC(e){if("BATCH_STATE_UNSPECIFIED"===e)return"JOB_STATE_UNSPECIFIED";if("BATCH_STATE_PENDING"===e)return"JOB_STATE_PENDING";if("BATCH_STATE_RUNNING"===e)return"JOB_STATE_RUNNING";if("BATCH_STATE_SUCCEEDED"===e)return"JOB_STATE_SUCCEEDED";if("BATCH_STATE_FAILED"===e)return"JOB_STATE_FAILED";else if("BATCH_STATE_CANCELLED"===e)return"JOB_STATE_CANCELLED";else if("BATCH_STATE_EXPIRED"===e)return"JOB_STATE_EXPIRED";else return e}function rR(e){let t={},r=tk(e,["name"]);null!=r&&tP(t,["name"],r);let n=tk(e,["metadata","displayName"]);null!=n&&tP(t,["displayName"],n);let i=tk(e,["metadata","state"]);null!=i&&tP(t,["state"],rC(i));let s=tk(e,["metadata","createTime"]);null!=s&&tP(t,["createTime"],s);let o=tk(e,["metadata","endTime"]);null!=o&&tP(t,["endTime"],o);let a=tk(e,["metadata","updateTime"]);null!=a&&tP(t,["updateTime"],a);let l=tk(e,["metadata","model"]);null!=l&&tP(t,["model"],l);let u=tk(e,["metadata","output"]);return null!=u&&tP(t,["dest"],function(e){let t={},r=tk(e,["responsesFile"]);null!=r&&tP(t,["fileName"],r);let n=tk(e,["inlinedResponses","inlinedResponses"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s;return r={},null!=(n=tk(t=e,["response"]))&&tP(r,["response"],function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["candidates"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["content"]);null!=r&&tP(t,["content"],r);let n=tk(e,["citationMetadata"]);null!=n&&tP(t,["citationMetadata"],function(e){let t={},r=tk(e,["citationSources"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["citations"],e)}return t}(n));let i=tk(e,["tokenCount"]);null!=i&&tP(t,["tokenCount"],i);let s=tk(e,["finishReason"]);null!=s&&tP(t,["finishReason"],s);let o=tk(e,["groundingMetadata"]);null!=o&&tP(t,["groundingMetadata"],o);let a=tk(e,["avgLogprobs"]);null!=a&&tP(t,["avgLogprobs"],a);let l=tk(e,["index"]);null!=l&&tP(t,["index"],l);let u=tk(e,["logprobsResult"]);null!=u&&tP(t,["logprobsResult"],u);let c=tk(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["safetyRatings"],e)}let d=tk(e,["urlContextMetadata"]);return null!=d&&tP(t,["urlContextMetadata"],d),t})(e))),tP(t,["candidates"],e)}let i=tk(e,["modelVersion"]);null!=i&&tP(t,["modelVersion"],i);let s=tk(e,["promptFeedback"]);null!=s&&tP(t,["promptFeedback"],s);let o=tk(e,["responseId"]);null!=o&&tP(t,["responseId"],o);let a=tk(e,["usageMetadata"]);null!=a&&tP(t,["usageMetadata"],a);let l=tk(e,["modelStatus"]);return null!=l&&tP(t,["modelStatus"],l),t}(n)),null!=(i=tk(t,["metadata"]))&&tP(r,["metadata"],i),null!=(s=tk(t,["error"]))&&tP(r,["error"],s),r})),tP(t,["inlinedResponses"],e)}let i=tk(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["inlinedEmbedContentResponses"],e)}return t}(rS(u))),t}function rP(e){var t,r,n;let i,s,o,a,l,u,c,d,h,p,f,m,g,y={},_=tk(e,["name"]);null!=_&&tP(y,["name"],_);let E=tk(e,["displayName"]);null!=E&&tP(y,["displayName"],E);let A=tk(e,["state"]);null!=A&&tP(y,["state"],rC(A));let v=tk(e,["error"]);null!=v&&tP(y,["error"],v);let b=tk(e,["createTime"]);null!=b&&tP(y,["createTime"],b);let w=tk(e,["startTime"]);null!=w&&tP(y,["startTime"],w);let T=tk(e,["endTime"]);null!=T&&tP(y,["endTime"],T);let I=tk(e,["updateTime"]);null!=I&&tP(y,["updateTime"],I);let S=tk(e,["model"]);null!=S&&tP(y,["model"],S);let O=tk(e,["inputConfig"]);null!=O&&tP(y,["src"],(i={},null!=(s=tk(r=O,["instancesFormat"]))&&tP(i,["format"],s),null!=(o=tk(r,["gcsSource","uris"]))&&tP(i,["gcsUri"],o),null!=(a=tk(r,["bigquerySource","inputUri"]))&&tP(i,["bigqueryUri"],a),null!=(l=tk(r,["vertexMultimodalDatasetSource","datasetName"]))&&tP(i,["vertexDatasetName"],l),i));let C=tk(e,["outputConfig"]);null!=C&&tP(y,["dest"],(t=rS(C),h={},null!=(p=tk(t,["predictionsFormat"]))&&tP(h,["format"],p),null!=(f=tk(t,["gcsDestination","outputUriPrefix"]))&&tP(h,["gcsUri"],f),null!=(m=tk(t,["bigqueryDestination","outputUri"]))&&tP(h,["bigqueryUri"],m),null!=(g=tk(t,["vertexMultimodalDatasetDestination"]))&&tP(h,["vertexDataset"],(u={},null!=(c=tk(n=g,["bigqueryDestination","outputUri"]))&&tP(u,["bigqueryDestination"],c),null!=(d=tk(n,["displayName"]))&&tP(u,["displayName"],d),u)),h));let R=tk(e,["completionStats"]);null!=R&&tP(y,["completionStats"],R);let P=tk(e,["outputInfo"]);return null!=P&&tP(y,["outputInfo"],P),y}function rk(e){let t={},r=tk(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p,f,m,g;return r={},null!=(n=tk(t=e,["mediaResolution"]))&&tP(r,["mediaResolution"],n),null!=(i=tk(t,["codeExecutionResult"]))&&tP(r,["codeExecutionResult"],i),null!=(s=tk(t,["executableCode"]))&&tP(r,["executableCode"],s),null!=(o=tk(t,["fileData"]))&&tP(r,["fileData"],function(e){let t={};if(void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=tk(e,["fileUri"]);null!=r&&tP(t,["fileUri"],r);let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(o)),null!=(a=tk(t,["functionCall"]))&&tP(r,["functionCall"],function(e){let t={},r=tk(e,["id"]);null!=r&&tP(t,["id"],r);let n=tk(e,["args"]);null!=n&&tP(t,["args"],n);let i=tk(e,["name"]);if(null!=i&&tP(t,["name"],i),void 0!==tk(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==tk(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=tk(t,["functionResponse"]))&&tP(r,["functionResponse"],l),null!=(u=tk(t,["inlineData"]))&&tP(r,["inlineData"],function(e){let t={},r=tk(e,["data"]);if(null!=r&&tP(t,["data"],r),void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(u)),null!=(c=tk(t,["text"]))&&tP(r,["text"],c),null!=(d=tk(t,["thought"]))&&tP(r,["thought"],d),null!=(h=tk(t,["thoughtSignature"]))&&tP(r,["thoughtSignature"],h),null!=(p=tk(t,["videoMetadata"]))&&tP(r,["videoMetadata"],p),null!=(f=tk(t,["toolCall"]))&&tP(r,["toolCall"],f),null!=(m=tk(t,["toolResponse"]))&&tP(r,["toolResponse"],m),null!=(g=tk(t,["partMetadata"]))&&tP(r,["partMetadata"],g),r})),tP(t,["parts"],e)}let n=tk(e,["role"]);return null!=n&&tP(t,["role"],n),t}function rx(e,t){let r={},n=tk(t,["model"]);null!=n&&tP(r,["_url","model"],t7(e,n));let i=tk(t,["src"]);null!=i&&tP(r,["batch","inputConfig"],function(e,t){let r={};if(void 0!==tk(t,["format"]))throw Error("format parameter is not supported in Gemini API.");if(void 0!==tk(t,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==tk(t,["bigqueryUri"]))throw Error("bigqueryUri parameter is not supported in Gemini API.");let n=tk(t,["fileName"]);null!=n&&tP(r,["fileName"],n);let i=tk(t,["inlinedRequests"]);if(null!=i){let t=i;Array.isArray(t)&&(t=t.map(t=>(function(e,t){let r={},n=tk(t,["model"]);null!=n&&tP(r,["request","model"],t7(e,n));let i=tk(t,["contents"]);if(null!=i){let e=rh(i);Array.isArray(e)&&(e=e.map(e=>rk(e))),tP(r,["request","contents"],e)}let s=tk(t,["metadata"]);null!=s&&tP(r,["metadata"],s);let o=tk(t,["config"]);return null!=o&&tP(r,["request","generationConfig"],function(e,t,r){var n;let i,s,o,a,l={},u=tk(t,["systemInstruction"]);void 0!==r&&null!=u&&tP(r,["systemInstruction"],rk(rc(u)));let c=tk(t,["temperature"]);null!=c&&tP(l,["temperature"],c);let d=tk(t,["topP"]);null!=d&&tP(l,["topP"],d);let h=tk(t,["topK"]);null!=h&&tP(l,["topK"],h);let p=tk(t,["candidateCount"]);null!=p&&tP(l,["candidateCount"],p);let f=tk(t,["maxOutputTokens"]);null!=f&&tP(l,["maxOutputTokens"],f);let m=tk(t,["stopSequences"]);null!=m&&tP(l,["stopSequences"],m);let g=tk(t,["responseLogprobs"]);null!=g&&tP(l,["responseLogprobs"],g);let y=tk(t,["logprobs"]);null!=y&&tP(l,["logprobs"],y);let _=tk(t,["presencePenalty"]);null!=_&&tP(l,["presencePenalty"],_);let E=tk(t,["frequencyPenalty"]);null!=E&&tP(l,["frequencyPenalty"],E);let A=tk(t,["seed"]);null!=A&&tP(l,["seed"],A);let v=tk(t,["responseMimeType"]);null!=v&&tP(l,["responseMimeType"],v);let b=tk(t,["responseSchema"]);null!=b&&tP(l,["responseSchema"],rp(b));let w=tk(t,["responseJsonSchema"]);if(null!=w&&tP(l,["responseJsonSchema"],w),void 0!==tk(t,["routingConfig"]))throw Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==tk(t,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=tk(t,["safetySettings"]);if(void 0!==r&&null!=T){let e=T;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["category"]);if(null!=r&&tP(t,["category"],r),void 0!==tk(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=tk(e,["threshold"]);return null!=n&&tP(t,["threshold"],n),t})(e))),tP(r,["safetySettings"],e)}let I=tk(t,["tools"]);if(void 0!==r&&null!=I){let e=ry(I);Array.isArray(e)&&(e=e.map(e=>(function(e){let t,r,n,i={};if(void 0!==tk(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let s=tk(e,["computerUse"]);null!=s&&tP(i,["computerUse"],s);let o=tk(e,["fileSearch"]);null!=o&&tP(i,["fileSearch"],o);let a=tk(e,["googleSearch"]);null!=a&&tP(i,["googleSearch"],function(e){let t={},r=tk(e,["searchTypes"]);if(null!=r&&tP(t,["searchTypes"],r),void 0!==tk(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==tk(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");let n=tk(e,["timeRangeFilter"]);return null!=n&&tP(t,["timeRangeFilter"],n),t}(a));let l=tk(e,["googleMaps"]);null!=l&&tP(i,["googleMaps"],(t={},null!=(r=tk(l,["authConfig"]))&&tP(t,["authConfig"],function(e){let t={},r=tk(e,["apiKey"]);if(null!=r&&tP(t,["apiKey"],r),void 0!==tk(e,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["authType"]))throw Error("authType parameter is not supported in Gemini API.");if(void 0!==tk(e,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oauthConfig"]))throw Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oidcConfig"]))throw Error("oidcConfig parameter is not supported in Gemini API.");return t}(r)),null!=(n=tk(l,["enableWidget"]))&&tP(t,["enableWidget"],n),t));let u=tk(e,["codeExecution"]);if(null!=u&&tP(i,["codeExecution"],u),void 0!==tk(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=tk(e,["functionDeclarations"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["functionDeclarations"],e)}let d=tk(e,["googleSearchRetrieval"]);if(null!=d&&tP(i,["googleSearchRetrieval"],d),void 0!==tk(e,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is not supported in Gemini API.");let h=tk(e,["urlContext"]);null!=h&&tP(i,["urlContext"],h);let p=tk(e,["mcpServers"]);if(null!=p){let e=p;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["mcpServers"],e)}return i})(rg(e)))),tP(r,["tools"],e)}let S=tk(t,["toolConfig"]);if(void 0!==r&&null!=S&&tP(r,["toolConfig"],(i={},null!=(s=tk(n=S,["retrievalConfig"]))&&tP(i,["retrievalConfig"],s),null!=(o=tk(n,["functionCallingConfig"]))&&tP(i,["functionCallingConfig"],function(e){let t={},r=tk(e,["allowedFunctionNames"]);null!=r&&tP(t,["allowedFunctionNames"],r);let n=tk(e,["mode"]);if(null!=n&&tP(t,["mode"],n),void 0!==tk(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(o)),null!=(a=tk(n,["includeServerSideToolInvocations"]))&&tP(i,["includeServerSideToolInvocations"],a),i)),void 0!==tk(t,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let O=tk(t,["cachedContent"]);void 0!==r&&null!=O&&tP(r,["cachedContent"],r_(e,O));let C=tk(t,["responseModalities"]);null!=C&&tP(l,["responseModalities"],C);let R=tk(t,["mediaResolution"]);null!=R&&tP(l,["mediaResolution"],R);let P=tk(t,["speechConfig"]);if(null!=P&&tP(l,["speechConfig"],rf(P)),void 0!==tk(t,["audioTimestamp"]))throw Error("audioTimestamp parameter is not supported in Gemini API.");let k=tk(t,["thinkingConfig"]);null!=k&&tP(l,["thinkingConfig"],k);let x=tk(t,["imageConfig"]);null!=x&&tP(l,["imageConfig"],function(e){let t={},r=tk(e,["aspectRatio"]);null!=r&&tP(t,["aspectRatio"],r);let n=tk(e,["imageSize"]);if(null!=n&&tP(t,["imageSize"],n),void 0!==tk(e,["personGeneration"]))throw Error("personGeneration parameter is not supported in Gemini API.");if(void 0!==tk(e,["prominentPeople"]))throw Error("prominentPeople parameter is not supported in Gemini API.");if(void 0!==tk(e,["outputMimeType"]))throw Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==tk(e,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is not supported in Gemini API.");if(void 0!==tk(e,["imageOutputOptions"]))throw Error("imageOutputOptions parameter is not supported in Gemini API.");return t}(x));let N=tk(t,["enableEnhancedCivicAnswers"]);if(null!=N&&tP(l,["enableEnhancedCivicAnswers"],N),void 0!==tk(t,["modelArmorConfig"]))throw Error("modelArmorConfig parameter is not supported in Gemini API.");let D=tk(t,["serviceTier"]);return void 0!==r&&null!=D&&tP(r,["serviceTier"],D),l}(e,o,tk(r,["request"],{}))),r})(e,t))),tP(r,["requests","requests"],t)}if(void 0!==tk(t,["vertexDatasetName"]))throw Error("vertexDatasetName parameter is not supported in Gemini API.");return r}(e,rI(e,i)));let s=tk(t,["config"]);return null!=s&&function(e,t){let r=tk(e,["displayName"]);if(void 0!==t&&null!=r&&tP(t,["batch","displayName"],r),void 0!==tk(e,["dest"]))throw Error("dest parameter is not supported in Gemini API.");let n=tk(e,["webhookConfig"]);void 0!==t&&null!=n&&tP(t,["batch","webhookConfig"],n)}(s,r),r}(eg=tE||(tE={})).PAGED_ITEM_BATCH_JOBS="batchJobs",eg.PAGED_ITEM_MODELS="models",eg.PAGED_ITEM_TUNING_JOBS="tuningJobs",eg.PAGED_ITEM_FILES="files",eg.PAGED_ITEM_CACHED_CONTENTS="cachedContents",eg.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",eg.PAGED_ITEM_DOCUMENTS="documents";class rN{constructor(e,t,r,n){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,r,n)}init(e,t,r){var n,i;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=null==t?void 0:t.sdkHttpResponse,this.idxInternal=0;let s={config:{}};(s=r&&0!==Object.keys(r).length?"object"==typeof r?Object.assign({},r):r:{config:{}}).config&&(s.config.pageToken=t.nextPageToken),this.paramsInternal=s,this.pageInternalSize=null!=(i=null==(n=s.config)?void 0:n.pageSize)?i:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(!this.hasNextPage())return{value:void 0,done:!0};else await this.nextPage();let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return(null==(e=this.params.config)?void 0:e.pageToken)!==void 0}}class rD extends tC{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rN(tE.PAGED_ITEM_BATCH_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.create=async e=>(this.apiClient.isVertexAI()&&(e.config=this.formatDestination(e.src,e.config)),this.createInternal(e)),this.createEmbeddings=async e=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){let t=rx(this.apiClient,e),r=tR("{model}:batchGenerateContent",t._url),n=t.batch.inputConfig.requests,i=n.requests,s=[];for(let e of i){let t=Object.assign({},e);if(t.systemInstruction){let e=t.systemInstruction;delete t.systemInstruction;let r=t.request;r.systemInstruction=e,t.request=r}s.push(t)}return n.requests=s,delete t.config,delete t._url,delete t._query,{path:r,body:t}}getGcsUri(e){return"string"==typeof e?e.startsWith("gs://")?e:void 0:!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0?e.gcsUri[0]:void 0}getBigqueryUri(e){return"string"==typeof e?e.startsWith("bq://")?e:void 0:Array.isArray(e)?void 0:e.bigqueryUri}formatDestination(e,t){let r=t?Object.assign({},t):{},n=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${n}`),void 0===r.dest){let t=this.getGcsUri(e),i=this.getBigqueryUri(e);if(t)t.endsWith(".jsonl")?r.dest=`${t.slice(0,-6)}/dest`:r.dest=`${t}_dest_${n}`;else if(i)r.dest=`${i}_dest_${n}`;else throw Error("Unsupported source for Gemini Enterprise Agent Platform (previously known as Vertex AI): No GCS or BigQuery URI found.")}return r}async createInternal(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let n,i,l,u,c=(s=this.apiClient,n={},null!=(i=tk(e,["model"]))&&tP(n,["model"],t7(s,i)),null!=(l=tk(e,["src"]))&&tP(n,["inputConfig"],function(e){let t={},r=tk(e,["format"]);null!=r&&tP(t,["instancesFormat"],r);let n=tk(e,["gcsUri"]);null!=n&&tP(t,["gcsSource","uris"],n);let i=tk(e,["bigqueryUri"]);if(null!=i&&tP(t,["bigquerySource","inputUri"],i),void 0!==tk(e,["fileName"]))throw Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["inlinedRequests"]))throw Error("inlinedRequests parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let s=tk(e,["vertexDatasetName"]);return null!=s&&tP(t,["vertexMultimodalDatasetSource","datasetName"],s),t}(rI(s,l))),null!=(u=tk(e,["config"]))&&function(e,t){let r=tk(e,["displayName"]);void 0!==t&&null!=r&&tP(t,["displayName"],r);let n=tk(e,["dest"]);if(void 0!==t&&null!=n&&tP(t,["outputConfig"],function(e){var t;let r,n,i,s={},o=tk(e,["format"]);null!=o&&tP(s,["predictionsFormat"],o);let a=tk(e,["gcsUri"]);null!=a&&tP(s,["gcsDestination","outputUriPrefix"],a);let l=tk(e,["bigqueryUri"]);if(null!=l&&tP(s,["bigqueryDestination","outputUri"],l),void 0!==tk(e,["fileName"]))throw Error("fileName parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["inlinedResponses"]))throw Error("inlinedResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["inlinedEmbedContentResponses"]))throw Error("inlinedEmbedContentResponses parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let u=tk(e,["vertexDataset"]);return null!=u&&tP(s,["vertexMultimodalDatasetDestination"],(r={},null!=(n=tk(t=u,["bigqueryDestination"]))&&tP(r,["bigqueryDestination","outputUri"],n),null!=(i=tk(t,["displayName"]))&&tP(r,["displayName"],i),r)),s}(function(e){if("string"!=typeof e)return e;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw Error(`Unsupported destination: ${e}`)}(n))),void 0!==tk(e,["webhookConfig"]))throw Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}(u,n),n);return o=tR("batchPredictionJobs",c._url),a=c._query,delete c._url,delete c._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rP(e))}{let t=rx(this.apiClient,e);return o=tR("{model}:batchGenerateContent",t._url),a=t._query,delete t._url,delete t._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rR(e))}}async createEmbeddingsInternal(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let l,u,c,d,h,p,f,m,g=(n=this.apiClient,d={},null!=(h=tk(e,["model"]))&&tP(d,["_url","model"],t7(n,h)),null!=(p=tk(e,["src"]))&&tP(d,["batch","inputConfig"],(i=n,l={},null!=(u=tk(s=p,["fileName"]))&&tP(l,["file_name"],u),null!=(c=tk(s,["inlinedRequests"]))&&tP(l,["requests"],function(e,t){let r={},n=tk(t,["contents"]);if(null!=n){let t=rd(e,n);Array.isArray(t)&&(t=t.map(e=>e)),tP(r,["requests[]","request","content"],t)}let i=tk(t,["config"]);return null!=i&&(tP(r,["_self"],function(e,t){let r=tk(e,["taskType"]);void 0!==t&&null!=r&&tP(t,["requests[]","taskType"],r);let n=tk(e,["title"]);void 0!==t&&null!=n&&tP(t,["requests[]","title"],n);let i=tk(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&tP(t,["requests[]","outputDimensionality"],i),void 0!==tk(e,["mimeType"]))throw Error("mimeType parameter is not supported in Gemini API.");if(void 0!==tk(e,["autoTruncate"]))throw Error("autoTruncate parameter is not supported in Gemini API.");if(void 0!==tk(e,["documentOcr"]))throw Error("documentOcr parameter is not supported in Gemini API.");if(void 0!==tk(e,["audioTrackExtraction"]))throw Error("audioTrackExtraction parameter is not supported in Gemini API.");return{}}(i,r)),!function(e,t){for(let[r,n]of Object.entries(t)){let t=r.split("."),i=n.split("."),s=new Set,o=-1;for(let e=0;e<t.length;e++)if("*"===t[e]){o=e;break}if(-1!==o&&i.length>o)for(let e=o;e<i.length;e++){let t=i[e];"*"===t||t.endsWith("[]")||t.endsWith("[0]")||s.add(t)}!function e(t,r,n,i,s){if(i>=r.length||"object"!=typeof t||null===t)return;let o=r[i];if(o.endsWith("[]")){let a=o.slice(0,-2);if(a in t&&Array.isArray(t[a]))for(let o of t[a])e(o,r,n,i+1,s)}else if("*"===o){if("object"==typeof t&&null!==t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith("_")&&!s.has(e)),r={};for(let n of e)r[n]=t[n];for(let[e,s]of Object.entries(r)){let r=[];for(let t of n.slice(i))"*"===t?r.push(e):r.push(t);tP(t,r,s)}for(let r of e)delete t[r]}}else o in t&&e(t[o],r,n,i+1,s)}(e,t,i,0,s)}}(r,{"requests[].*":"requests[].request.*"})),r}(i,c)),l)),null!=(f=tk(e,["config"]))&&(m=tk(f,["displayName"]),void 0!==d&&null!=m&&tP(d,["batch","displayName"],m)),d);return o=tR("{model}:asyncBatchEmbedContent",g._url),a=g._query,delete g._url,delete g._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(g),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rR(e))}}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],rO(s,i)),n);return a=tR("batchPredictionJobs/{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rP(e))}{let t,r,s=(o=this.apiClient,t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],rO(o,r)),t);return a=tR("batches/{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rR(e))}}async cancel(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],rO(s,i)),n);a=tR("batchPredictionJobs/{name}:cancel",o._url),l=o._query,delete o._url,delete o._query,await this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}else{let t,r,s=(o=this.apiClient,t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],rO(o,r)),t);a=tR("batches/{name}:cancel",s._url),l=s._query,delete s._url,delete s._query,await this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal})}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u,c=(n={},null!=(i=tk(e,["config"]))&&(a=tk(i,["pageSize"]),void 0!==n&&null!=a&&tP(n,["_query","pageSize"],a),l=tk(i,["pageToken"]),void 0!==n&&null!=l&&tP(n,["_query","pageToken"],l),u=tk(i,["filter"]),void 0!==n&&null!=u&&tP(n,["_query","filter"],u)),n);return s=tR("batchPredictionJobs",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["batchPredictionJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rP(e))),tP(t,["batchJobs"],e)}return t}(e),r=new t3;return Object.assign(r,t),r})}{let t,r,a=(t={},null!=(r=tk(e,["config"]))&&function(e,t){let r=tk(e,["pageSize"]);void 0!==t&&null!=r&&tP(t,["_query","pageSize"],r);let n=tk(e,["pageToken"]);if(void 0!==t&&null!=n&&tP(t,["_query","pageToken"],n),void 0!==tk(e,["filter"]))throw Error("filter parameter is not supported in Gemini API.")}(r,t),t);return s=tR("batches",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["operations"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rR(e))),tP(t,["batchJobs"],e)}return t}(e),r=new t3;return Object.assign(r,t),r})}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],rO(s,i)),n);return a=tR("batchPredictionJobs/{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s;return t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),null!=(n=tk(e,["name"]))&&tP(t,["name"],n),null!=(i=tk(e,["done"]))&&tP(t,["done"],i),null!=(s=tk(e,["error"]))&&tP(t,["error"],s),t})}{let t,r,s=(o=this.apiClient,t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],rO(o,r)),t);return a=tR("batches/{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s;return t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),null!=(n=tk(e,["name"]))&&tP(t,["name"],n),null!=(i=tk(e,["done"]))&&tP(t,["done"],i),null!=(s=tk(e,["error"]))&&tP(t,["error"],s),t})}}}function rU(e){let t={},r=tk(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p,f,m,g;return r={},null!=(n=tk(t=e,["mediaResolution"]))&&tP(r,["mediaResolution"],n),null!=(i=tk(t,["codeExecutionResult"]))&&tP(r,["codeExecutionResult"],i),null!=(s=tk(t,["executableCode"]))&&tP(r,["executableCode"],s),null!=(o=tk(t,["fileData"]))&&tP(r,["fileData"],function(e){let t={};if(void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=tk(e,["fileUri"]);null!=r&&tP(t,["fileUri"],r);let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(o)),null!=(a=tk(t,["functionCall"]))&&tP(r,["functionCall"],function(e){let t={},r=tk(e,["id"]);null!=r&&tP(t,["id"],r);let n=tk(e,["args"]);null!=n&&tP(t,["args"],n);let i=tk(e,["name"]);if(null!=i&&tP(t,["name"],i),void 0!==tk(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==tk(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=tk(t,["functionResponse"]))&&tP(r,["functionResponse"],l),null!=(u=tk(t,["inlineData"]))&&tP(r,["inlineData"],function(e){let t={},r=tk(e,["data"]);if(null!=r&&tP(t,["data"],r),void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(u)),null!=(c=tk(t,["text"]))&&tP(r,["text"],c),null!=(d=tk(t,["thought"]))&&tP(r,["thought"],d),null!=(h=tk(t,["thoughtSignature"]))&&tP(r,["thoughtSignature"],h),null!=(p=tk(t,["videoMetadata"]))&&tP(r,["videoMetadata"],p),null!=(f=tk(t,["toolCall"]))&&tP(r,["toolCall"],f),null!=(m=tk(t,["toolResponse"]))&&tP(r,["toolResponse"],m),null!=(g=tk(t,["partMetadata"]))&&tP(r,["partMetadata"],g),r})),tP(t,["parts"],e)}let n=tk(e,["role"]);return null!=n&&tP(t,["role"],n),t}function rM(e){let t={},r=tk(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["mediaResolution"]);null!=r&&tP(t,["mediaResolution"],r);let n=tk(e,["codeExecutionResult"]);null!=n&&tP(t,["codeExecutionResult"],n);let i=tk(e,["executableCode"]);null!=i&&tP(t,["executableCode"],i);let s=tk(e,["fileData"]);null!=s&&tP(t,["fileData"],s);let o=tk(e,["functionCall"]);null!=o&&tP(t,["functionCall"],o);let a=tk(e,["functionResponse"]);null!=a&&tP(t,["functionResponse"],a);let l=tk(e,["inlineData"]);null!=l&&tP(t,["inlineData"],l);let u=tk(e,["text"]);null!=u&&tP(t,["text"],u);let c=tk(e,["thought"]);null!=c&&tP(t,["thought"],c);let d=tk(e,["thoughtSignature"]);null!=d&&tP(t,["thoughtSignature"],d);let h=tk(e,["videoMetadata"]);if(null!=h&&tP(t,["videoMetadata"],h),void 0!==tk(e,["toolCall"]))throw Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["toolResponse"]))throw Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["partMetadata"]))throw Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t})(e))),tP(t,["parts"],e)}let n=tk(e,["role"]);return null!=n&&tP(t,["role"],n),t}class rL extends tC{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rN(tE.PAGED_ITEM_CACHED_CONTENTS,e=>this.listInternal(e),await this.listInternal(e),e)}async create(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u=(s=this.apiClient,n={},null!=(i=tk(e,["model"]))&&tP(n,["model"],re(s,i)),null!=(o=tk(e,["config"]))&&function(e,t){let r=tk(e,["ttl"]);void 0!==t&&null!=r&&tP(t,["ttl"],r);let n=tk(e,["expireTime"]);void 0!==t&&null!=n&&tP(t,["expireTime"],n);let i=tk(e,["displayName"]);void 0!==t&&null!=i&&tP(t,["displayName"],i);let s=tk(e,["contents"]);if(void 0!==t&&null!=s){let e=rh(s);Array.isArray(e)&&(e=e.map(e=>rM(e))),tP(t,["contents"],e)}let o=tk(e,["systemInstruction"]);void 0!==t&&null!=o&&tP(t,["systemInstruction"],rM(rc(o)));let a=tk(e,["tools"]);if(void 0!==t&&null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["retrieval"]);null!=r&&tP(t,["retrieval"],r);let n=tk(e,["computerUse"]);if(null!=n&&tP(t,["computerUse"],n),void 0!==tk(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let i=tk(e,["googleSearch"]);null!=i&&tP(t,["googleSearch"],i);let s=tk(e,["googleMaps"]);null!=s&&tP(t,["googleMaps"],s);let o=tk(e,["codeExecution"]);null!=o&&tP(t,["codeExecution"],o);let a=tk(e,["enterpriseWebSearch"]);null!=a&&tP(t,["enterpriseWebSearch"],a);let l=tk(e,["functionDeclarations"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["description"]);null!=r&&tP(t,["description"],r);let n=tk(e,["name"]);null!=n&&tP(t,["name"],n);let i=tk(e,["parameters"]);null!=i&&tP(t,["parameters"],i);let s=tk(e,["parametersJsonSchema"]);null!=s&&tP(t,["parametersJsonSchema"],s);let o=tk(e,["response"]);null!=o&&tP(t,["response"],o);let a=tk(e,["responseJsonSchema"]);if(null!=a&&tP(t,["responseJsonSchema"],a),void 0!==tk(e,["behavior"]))throw Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t})(e))),tP(t,["functionDeclarations"],e)}let u=tk(e,["googleSearchRetrieval"]);null!=u&&tP(t,["googleSearchRetrieval"],u);let c=tk(e,["parallelAiSearch"]);null!=c&&tP(t,["parallelAiSearch"],c);let d=tk(e,["urlContext"]);if(null!=d&&tP(t,["urlContext"],d),void 0!==tk(e,["mcpServers"]))throw Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t})(e))),tP(t,["tools"],e)}let l=tk(e,["toolConfig"]);void 0!==t&&null!=l&&tP(t,["toolConfig"],function(e){let t={},r=tk(e,["retrievalConfig"]);null!=r&&tP(t,["retrievalConfig"],r);let n=tk(e,["functionCallingConfig"]);if(null!=n&&tP(t,["functionCallingConfig"],n),void 0!==tk(e,["includeServerSideToolInvocations"]))throw Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(l));let u=tk(e,["kmsKeyName"]);void 0!==t&&null!=u&&tP(t,["encryption_spec","kmsKeyName"],u)}(o,n),n);return a=tR("cachedContents",u._url),l=u._query,delete u._url,delete u._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s,u=(o=this.apiClient,t={},null!=(r=tk(e,["model"]))&&tP(t,["model"],re(o,r)),null!=(s=tk(e,["config"]))&&function(e,t){var r;let n,i,s,o,a=tk(e,["ttl"]);void 0!==t&&null!=a&&tP(t,["ttl"],a);let l=tk(e,["expireTime"]);void 0!==t&&null!=l&&tP(t,["expireTime"],l);let u=tk(e,["displayName"]);void 0!==t&&null!=u&&tP(t,["displayName"],u);let c=tk(e,["contents"]);if(void 0!==t&&null!=c){let e=rh(c);Array.isArray(e)&&(e=e.map(e=>rU(e))),tP(t,["contents"],e)}let d=tk(e,["systemInstruction"]);void 0!==t&&null!=d&&tP(t,["systemInstruction"],rU(rc(d)));let h=tk(e,["tools"]);if(void 0!==t&&null!=h){let e=h;Array.isArray(e)&&(e=e.map(e=>(function(e){let t,r,n,i={};if(void 0!==tk(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let s=tk(e,["computerUse"]);null!=s&&tP(i,["computerUse"],s);let o=tk(e,["fileSearch"]);null!=o&&tP(i,["fileSearch"],o);let a=tk(e,["googleSearch"]);null!=a&&tP(i,["googleSearch"],function(e){let t={},r=tk(e,["searchTypes"]);if(null!=r&&tP(t,["searchTypes"],r),void 0!==tk(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==tk(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");let n=tk(e,["timeRangeFilter"]);return null!=n&&tP(t,["timeRangeFilter"],n),t}(a));let l=tk(e,["googleMaps"]);null!=l&&tP(i,["googleMaps"],(t={},null!=(r=tk(l,["authConfig"]))&&tP(t,["authConfig"],function(e){let t={},r=tk(e,["apiKey"]);if(null!=r&&tP(t,["apiKey"],r),void 0!==tk(e,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["authType"]))throw Error("authType parameter is not supported in Gemini API.");if(void 0!==tk(e,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oauthConfig"]))throw Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oidcConfig"]))throw Error("oidcConfig parameter is not supported in Gemini API.");return t}(r)),null!=(n=tk(l,["enableWidget"]))&&tP(t,["enableWidget"],n),t));let u=tk(e,["codeExecution"]);if(null!=u&&tP(i,["codeExecution"],u),void 0!==tk(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=tk(e,["functionDeclarations"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["functionDeclarations"],e)}let d=tk(e,["googleSearchRetrieval"]);if(null!=d&&tP(i,["googleSearchRetrieval"],d),void 0!==tk(e,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is not supported in Gemini API.");let h=tk(e,["urlContext"]);null!=h&&tP(i,["urlContext"],h);let p=tk(e,["mcpServers"]);if(null!=p){let e=p;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["mcpServers"],e)}return i})(e))),tP(t,["tools"],e)}let p=tk(e,["toolConfig"]);if(void 0!==t&&null!=p&&tP(t,["toolConfig"],(n={},null!=(i=tk(r=p,["retrievalConfig"]))&&tP(n,["retrievalConfig"],i),null!=(s=tk(r,["functionCallingConfig"]))&&tP(n,["functionCallingConfig"],function(e){let t={},r=tk(e,["allowedFunctionNames"]);null!=r&&tP(t,["allowedFunctionNames"],r);let n=tk(e,["mode"]);if(null!=n&&tP(t,["mode"],n),void 0!==tk(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(s)),null!=(o=tk(r,["includeServerSideToolInvocations"]))&&tP(n,["includeServerSideToolInvocations"],o),n)),void 0!==tk(e,["kmsKeyName"]))throw Error("kmsKeyName parameter is not supported in Gemini API.")}(s,t),t);return a=tR("cachedContents",u._url),l=u._query,delete u._url,delete u._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],r_(s,i)),n);return a=tR("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s=(o=this.apiClient,t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],r_(o,r)),t);return a=tR("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],r_(s,i)),n);return a=tR("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tz;return Object.assign(i,n),i})}{let t,r,s=(o=this.apiClient,t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],r_(o,r)),t);return a=tR("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tz;return Object.assign(i,n),i})}}async update(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d=(s=this.apiClient,n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],r_(s,i)),null!=(o=tk(e,["config"]))&&(u=tk(o,["ttl"]),void 0!==n&&null!=u&&tP(n,["ttl"],u),c=tk(o,["expireTime"]),void 0!==n&&null!=c&&tP(n,["expireTime"],c)),n);return a=tR("{name}",d._url),l=d._query,delete d._url,delete d._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s,u,c,d=(o=this.apiClient,t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],r_(o,r)),null!=(s=tk(e,["config"]))&&(u=tk(s,["ttl"]),void 0!==t&&null!=u&&tP(t,["ttl"],u),c=tk(s,["expireTime"]),void 0!==t&&null!=c&&tP(t,["expireTime"],c)),t);return a=tR("{name}",d._url),l=d._query,delete d._url,delete d._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u=(n={},null!=(i=tk(e,["config"]))&&(a=tk(i,["pageSize"]),void 0!==n&&null!=a&&tP(n,["_query","pageSize"],a),l=tk(i,["pageToken"]),void 0!==n&&null!=l&&tP(n,["_query","pageToken"],l)),n);return s=tR("cachedContents",u._url),o=u._query,delete u._url,delete u._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["cachedContents"],e)}return t}(e),r=new tY;return Object.assign(r,t),r})}{let t,r,a,l,u=(t={},null!=(r=tk(e,["config"]))&&(a=tk(r,["pageSize"]),void 0!==t&&null!=a&&tP(t,["_query","pageSize"],a),l=tk(r,["pageToken"]),void 0!==t&&null!=l&&tP(t,["_query","pageToken"],l)),t);return s=tR("cachedContents",u._url),o=u._query,delete u._url,delete u._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["cachedContents"],e)}return t}(e),r=new tY;return Object.assign(r,t),r})}}}function rj(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)0>t.indexOf(n[i])&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function rG(e){return this instanceof rG?(this.v=e,this):new rG(e)}function rF(e,t,r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),n[Symbol.asyncIterator]=function(){return this},n;function o(e,t){i[e]&&(n[e]=function(t){return new Promise(function(r,n){s.push([e,t,r,n])>1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{var r;(r=i[e](t)).value instanceof rG?Promise.resolve(r.value.v).then(l,u):c(s[0][2],r)}catch(e){c(s[0][3],e)}}function l(e){a("next",e)}function u(e){a("throw",e)}function c(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function r$(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise(function(n,i){var s,o,a;s=n,o=i,a=(t=e[r](t)).done,Promise.resolve(t.value).then(function(e){s({value:e,done:a})},o)})}}}function rq(e){if(void 0===e.parts||0===e.parts.length)return!1;for(let t of e.parts)if(void 0===t||0===Object.keys(t).length)return!1;return!0}function rB(e){if(void 0===e||0===e.length)return[];let t=[],r=e.length,n=0;for(;n<r;)if("user"===e[n].role)t.push(e[n]),n++;else{let i=[],s=!0;for(;n<r&&"model"===e[n].role;)i.push(e[n]),s&&!rq(e[n])&&(s=!1),n++;s?t.push(...i):t.pop()}return t}"function"==typeof SuppressedError&&SuppressedError;class rH{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new rV(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}}class rV{constructor(e,t,r,n={},i=[]){this.apiClient=e,this.modelsModule=t,this.model=r,this.config=n,this.history=i,this.sendPromise=Promise.resolve();if(0!==i.length){for(let e of i)if("user"!==e.role&&"model"!==e.role)throw Error(`Role must be user or model, but got ${e.role}.`)}}async sendMessage(e){var t;await this.sendPromise;let r=rc(e.message),n=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(r),config:null!=(t=e.config)?t:this.config});return this.sendPromise=(async()=>{var e,t,i;let s=await n,o=null==(t=null==(e=s.candidates)?void 0:e[0])?void 0:t.content,a=s.automaticFunctionCallingHistory,l=this.getHistory(!0).length,u=[];null!=a&&(u=null!=(i=a.slice(l))?i:[]),this.recordHistory(r,o?[o]:[],u)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),n}async sendMessageStream(e){var t;await this.sendPromise;let r=rc(e.message),n=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:null!=(t=e.config)?t:this.config});this.sendPromise=n.then(()=>void 0).catch(()=>void 0);let i=await n;return this.processStreamResponse(i,r)}getHistory(e=!1){return structuredClone(e?rB(this.history):this.history)}processStreamResponse(e,t){return rF(this,arguments,function*(){let r=[];try{for(var n,i,s,o,a,l,u,c=!0,d=r$(e);!(n=(u=yield rG(d.next())).done);c=!0){if(o=u.value,c=!1,function(e){var t;if(void 0==e.candidates||0===e.candidates.length)return!1;let r=null==(t=e.candidates[0])?void 0:t.content;return void 0!==r&&rq(r)}(o)){let e=null==(l=null==(a=o.candidates)?void 0:a[0])?void 0:l.content;void 0!==e&&r.push(e)}yield yield rG(o)}}catch(e){i={error:e}}finally{try{!c&&!n&&(s=d.return)&&(yield rG(s.call(d)))}finally{if(i)throw i.error}}this.recordHistory(t,r)})}recordHistory(e,t,r){let n=[];t.length>0&&t.every(e=>void 0!==e.role)?n=t:n.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...rB(r)):this.history.push(e),this.history.push(...n)}}class rK extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,rK.prototype)}}class rJ extends tC{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rN(tE.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}async upload(e){if(this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(e=>e)}async download(e){await this.apiClient.downloadFile(e)}async registerFiles(e){throw Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(e){return this.registerFilesInternal(e)}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=tk(e,["config"]))&&(a=tk(o,["pageSize"]),void 0!==s&&null!=a&&tP(s,["_query","pageSize"],a),l=tk(o,["pageToken"]),void 0!==s&&null!=l&&tP(s,["_query","pageToken"],l)),s);return n=tR("files",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["files"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["files"],e)}return t}(e),r=new t1;return Object.assign(r,t),r})}}async createInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=tk(e,["file"]))&&tP(s,["file"],o),s);return n=tR("upload/v1beta/files",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new t2;return Object.assign(i,n),i})}}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=tk(e,["name"]))&&tP(s,["_url","file"],rb(o)),s);return n=tR("files/{file}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=tk(e,["name"]))&&tP(s,["_url","file"],rb(o)),s);return n=tR("files/{file}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new t4;return Object.assign(i,n),i})}}async registerFilesInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=tk(e,["uris"]))&&tP(s,["uris"],o),s);return n=tR("files:register",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["files"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["files"],e)}return t}(e),r=new t6;return Object.assign(r,t),r})}}}function rW(e){if(void 0!==tk(e,["languageCodes"]))throw Error("languageCodes parameter is not supported in Gemini API.");return{}}function rz(e){let t={},r=tk(e,["data"]);if(null!=r&&tP(t,["data"],r),void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}function rY(e,t){let r={},n=tk(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p,f,m,g;return r={},null!=(n=tk(t=e,["mediaResolution"]))&&tP(r,["mediaResolution"],n),null!=(i=tk(t,["codeExecutionResult"]))&&tP(r,["codeExecutionResult"],i),null!=(s=tk(t,["executableCode"]))&&tP(r,["executableCode"],s),null!=(o=tk(t,["fileData"]))&&tP(r,["fileData"],function(e){let t={};if(void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=tk(e,["fileUri"]);null!=r&&tP(t,["fileUri"],r);let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(o)),null!=(a=tk(t,["functionCall"]))&&tP(r,["functionCall"],function(e){let t={},r=tk(e,["id"]);null!=r&&tP(t,["id"],r);let n=tk(e,["args"]);null!=n&&tP(t,["args"],n);let i=tk(e,["name"]);if(null!=i&&tP(t,["name"],i),void 0!==tk(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==tk(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=tk(t,["functionResponse"]))&&tP(r,["functionResponse"],l),null!=(u=tk(t,["inlineData"]))&&tP(r,["inlineData"],function(e){let t={},r=tk(e,["data"]);if(null!=r&&tP(t,["data"],r),void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(u)),null!=(c=tk(t,["text"]))&&tP(r,["text"],c),null!=(d=tk(t,["thought"]))&&tP(r,["thought"],d),null!=(h=tk(t,["thoughtSignature"]))&&tP(r,["thoughtSignature"],h),null!=(p=tk(t,["videoMetadata"]))&&tP(r,["videoMetadata"],p),null!=(f=tk(t,["toolCall"]))&&tP(r,["toolCall"],f),null!=(m=tk(t,["toolResponse"]))&&tP(r,["toolResponse"],m),null!=(g=tk(t,["partMetadata"]))&&tP(r,["partMetadata"],g),r})),tP(r,["parts"],e)}let i=tk(e,["role"]);return null!=i&&tP(r,["role"],i),r}function rX(e,t){let r={},n=tk(e,["parts"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["mediaResolution"]);null!=r&&tP(t,["mediaResolution"],r);let n=tk(e,["codeExecutionResult"]);null!=n&&tP(t,["codeExecutionResult"],n);let i=tk(e,["executableCode"]);null!=i&&tP(t,["executableCode"],i);let s=tk(e,["fileData"]);null!=s&&tP(t,["fileData"],s);let o=tk(e,["functionCall"]);null!=o&&tP(t,["functionCall"],o);let a=tk(e,["functionResponse"]);null!=a&&tP(t,["functionResponse"],a);let l=tk(e,["inlineData"]);null!=l&&tP(t,["inlineData"],l);let u=tk(e,["text"]);null!=u&&tP(t,["text"],u);let c=tk(e,["thought"]);null!=c&&tP(t,["thought"],c);let d=tk(e,["thoughtSignature"]);null!=d&&tP(t,["thoughtSignature"],d);let h=tk(e,["videoMetadata"]);if(null!=h&&tP(t,["videoMetadata"],h),void 0!==tk(e,["toolCall"]))throw Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["toolResponse"]))throw Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["partMetadata"]))throw Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t})(e))),tP(r,["parts"],e)}let i=tk(e,["role"]);return null!=i&&tP(r,["role"],i),r}function rQ(e,t,r){let n={},i=tk(t,["model"]);null!=i&&tP(n,["_url","model"],t7(e,i));let s=tk(t,["contents"]);if(null!=s){let e=rh(s);Array.isArray(e)&&(e=e.map(e=>rY(e))),tP(n,["contents"],e)}let o=tk(t,["config"]);return null!=o&&tP(n,["generationConfig"],function(e,t,r){var n;let i,s,o,a,l={},u=tk(t,["systemInstruction"]);void 0!==r&&null!=u&&tP(r,["systemInstruction"],rY(rc(u)));let c=tk(t,["temperature"]);null!=c&&tP(l,["temperature"],c);let d=tk(t,["topP"]);null!=d&&tP(l,["topP"],d);let h=tk(t,["topK"]);null!=h&&tP(l,["topK"],h);let p=tk(t,["candidateCount"]);null!=p&&tP(l,["candidateCount"],p);let f=tk(t,["maxOutputTokens"]);null!=f&&tP(l,["maxOutputTokens"],f);let m=tk(t,["stopSequences"]);null!=m&&tP(l,["stopSequences"],m);let g=tk(t,["responseLogprobs"]);null!=g&&tP(l,["responseLogprobs"],g);let y=tk(t,["logprobs"]);null!=y&&tP(l,["logprobs"],y);let _=tk(t,["presencePenalty"]);null!=_&&tP(l,["presencePenalty"],_);let E=tk(t,["frequencyPenalty"]);null!=E&&tP(l,["frequencyPenalty"],E);let A=tk(t,["seed"]);null!=A&&tP(l,["seed"],A);let v=tk(t,["responseMimeType"]);null!=v&&tP(l,["responseMimeType"],v);let b=tk(t,["responseSchema"]);null!=b&&tP(l,["responseSchema"],rp(b));let w=tk(t,["responseJsonSchema"]);if(null!=w&&tP(l,["responseJsonSchema"],w),void 0!==tk(t,["routingConfig"]))throw Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==tk(t,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is not supported in Gemini API.");let T=tk(t,["safetySettings"]);if(void 0!==r&&null!=T){let e=T;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["category"]);if(null!=r&&tP(t,["category"],r),void 0!==tk(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=tk(e,["threshold"]);return null!=n&&tP(t,["threshold"],n),t})(e))),tP(r,["safetySettings"],e)}let I=tk(t,["tools"]);if(void 0!==r&&null!=I){let e=ry(I);Array.isArray(e)&&(e=e.map(e=>(function(e){let t,r,n,i={};if(void 0!==tk(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let s=tk(e,["computerUse"]);null!=s&&tP(i,["computerUse"],s);let o=tk(e,["fileSearch"]);null!=o&&tP(i,["fileSearch"],o);let a=tk(e,["googleSearch"]);null!=a&&tP(i,["googleSearch"],function(e){let t={},r=tk(e,["searchTypes"]);if(null!=r&&tP(t,["searchTypes"],r),void 0!==tk(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==tk(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");let n=tk(e,["timeRangeFilter"]);return null!=n&&tP(t,["timeRangeFilter"],n),t}(a));let l=tk(e,["googleMaps"]);null!=l&&tP(i,["googleMaps"],(t={},null!=(r=tk(l,["authConfig"]))&&tP(t,["authConfig"],function(e){let t={},r=tk(e,["apiKey"]);if(null!=r&&tP(t,["apiKey"],r),void 0!==tk(e,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["authType"]))throw Error("authType parameter is not supported in Gemini API.");if(void 0!==tk(e,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oauthConfig"]))throw Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oidcConfig"]))throw Error("oidcConfig parameter is not supported in Gemini API.");return t}(r)),null!=(n=tk(l,["enableWidget"]))&&tP(t,["enableWidget"],n),t));let u=tk(e,["codeExecution"]);if(null!=u&&tP(i,["codeExecution"],u),void 0!==tk(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=tk(e,["functionDeclarations"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["functionDeclarations"],e)}let d=tk(e,["googleSearchRetrieval"]);if(null!=d&&tP(i,["googleSearchRetrieval"],d),void 0!==tk(e,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is not supported in Gemini API.");let h=tk(e,["urlContext"]);null!=h&&tP(i,["urlContext"],h);let p=tk(e,["mcpServers"]);if(null!=p){let e=p;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["mcpServers"],e)}return i})(rg(e)))),tP(r,["tools"],e)}let S=tk(t,["toolConfig"]);if(void 0!==r&&null!=S&&tP(r,["toolConfig"],(i={},null!=(s=tk(n=S,["retrievalConfig"]))&&tP(i,["retrievalConfig"],s),null!=(o=tk(n,["functionCallingConfig"]))&&tP(i,["functionCallingConfig"],function(e){let t={},r=tk(e,["allowedFunctionNames"]);null!=r&&tP(t,["allowedFunctionNames"],r);let n=tk(e,["mode"]);if(null!=n&&tP(t,["mode"],n),void 0!==tk(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(o)),null!=(a=tk(n,["includeServerSideToolInvocations"]))&&tP(i,["includeServerSideToolInvocations"],a),i)),void 0!==tk(t,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let O=tk(t,["cachedContent"]);void 0!==r&&null!=O&&tP(r,["cachedContent"],r_(e,O));let C=tk(t,["responseModalities"]);null!=C&&tP(l,["responseModalities"],C);let R=tk(t,["mediaResolution"]);null!=R&&tP(l,["mediaResolution"],R);let P=tk(t,["speechConfig"]);if(null!=P&&tP(l,["speechConfig"],rf(P)),void 0!==tk(t,["audioTimestamp"]))throw Error("audioTimestamp parameter is not supported in Gemini API.");let k=tk(t,["thinkingConfig"]);null!=k&&tP(l,["thinkingConfig"],k);let x=tk(t,["imageConfig"]);null!=x&&tP(l,["imageConfig"],function(e){let t={},r=tk(e,["aspectRatio"]);null!=r&&tP(t,["aspectRatio"],r);let n=tk(e,["imageSize"]);if(null!=n&&tP(t,["imageSize"],n),void 0!==tk(e,["personGeneration"]))throw Error("personGeneration parameter is not supported in Gemini API.");if(void 0!==tk(e,["prominentPeople"]))throw Error("prominentPeople parameter is not supported in Gemini API.");if(void 0!==tk(e,["outputMimeType"]))throw Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==tk(e,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is not supported in Gemini API.");if(void 0!==tk(e,["imageOutputOptions"]))throw Error("imageOutputOptions parameter is not supported in Gemini API.");return t}(x));let N=tk(t,["enableEnhancedCivicAnswers"]);if(null!=N&&tP(l,["enableEnhancedCivicAnswers"],N),void 0!==tk(t,["modelArmorConfig"]))throw Error("modelArmorConfig parameter is not supported in Gemini API.");let D=tk(t,["serviceTier"]);return void 0!==r&&null!=D&&tP(r,["serviceTier"],D),l}(e,o,n)),n}function rZ(e,t,r){let n={},i=tk(t,["model"]);null!=i&&tP(n,["_url","model"],t7(e,i));let s=tk(t,["contents"]);if(null!=s){let e=rh(s);Array.isArray(e)&&(e=e.map(e=>rX(e))),tP(n,["contents"],e)}let o=tk(t,["config"]);return null!=o&&tP(n,["generationConfig"],function(e,t,r){var n;let i,s,o,a,l,u,c,d,h={},p=tk(t,["systemInstruction"]);void 0!==r&&null!=p&&tP(r,["systemInstruction"],rX(rc(p)));let f=tk(t,["temperature"]);null!=f&&tP(h,["temperature"],f);let m=tk(t,["topP"]);null!=m&&tP(h,["topP"],m);let g=tk(t,["topK"]);null!=g&&tP(h,["topK"],g);let y=tk(t,["candidateCount"]);null!=y&&tP(h,["candidateCount"],y);let _=tk(t,["maxOutputTokens"]);null!=_&&tP(h,["maxOutputTokens"],_);let E=tk(t,["stopSequences"]);null!=E&&tP(h,["stopSequences"],E);let A=tk(t,["responseLogprobs"]);null!=A&&tP(h,["responseLogprobs"],A);let v=tk(t,["logprobs"]);null!=v&&tP(h,["logprobs"],v);let b=tk(t,["presencePenalty"]);null!=b&&tP(h,["presencePenalty"],b);let w=tk(t,["frequencyPenalty"]);null!=w&&tP(h,["frequencyPenalty"],w);let T=tk(t,["seed"]);null!=T&&tP(h,["seed"],T);let I=tk(t,["responseMimeType"]);null!=I&&tP(h,["responseMimeType"],I);let S=tk(t,["responseSchema"]);null!=S&&tP(h,["responseSchema"],rp(S));let O=tk(t,["responseJsonSchema"]);null!=O&&tP(h,["responseJsonSchema"],O);let C=tk(t,["routingConfig"]);null!=C&&tP(h,["routingConfig"],C);let R=tk(t,["modelSelectionConfig"]);null!=R&&tP(h,["modelConfig"],R);let P=tk(t,["safetySettings"]);if(void 0!==r&&null!=P){let e=P;Array.isArray(e)&&(e=e.map(e=>e)),tP(r,["safetySettings"],e)}let k=tk(t,["tools"]);if(void 0!==r&&null!=k){let e=ry(k);Array.isArray(e)&&(e=e.map(e=>ne(rg(e)))),tP(r,["tools"],e)}let x=tk(t,["toolConfig"]);void 0!==r&&null!=x&&tP(r,["toolConfig"],function(e){let t={},r=tk(e,["retrievalConfig"]);null!=r&&tP(t,["retrievalConfig"],r);let n=tk(e,["functionCallingConfig"]);if(null!=n&&tP(t,["functionCallingConfig"],n),void 0!==tk(e,["includeServerSideToolInvocations"]))throw Error("includeServerSideToolInvocations parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(x));let N=tk(t,["labels"]);void 0!==r&&null!=N&&tP(r,["labels"],N);let D=tk(t,["cachedContent"]);void 0!==r&&null!=D&&tP(r,["cachedContent"],r_(e,D));let U=tk(t,["responseModalities"]);null!=U&&tP(h,["responseModalities"],U);let M=tk(t,["mediaResolution"]);null!=M&&tP(h,["mediaResolution"],M);let L=tk(t,["speechConfig"]);null!=L&&tP(h,["speechConfig"],rf(L));let j=tk(t,["audioTimestamp"]);null!=j&&tP(h,["audioTimestamp"],j);let G=tk(t,["thinkingConfig"]);null!=G&&tP(h,["thinkingConfig"],G);let F=tk(t,["imageConfig"]);if(null!=F&&tP(h,["imageConfig"],(i={},null!=(s=tk(n=F,["aspectRatio"]))&&tP(i,["aspectRatio"],s),null!=(o=tk(n,["imageSize"]))&&tP(i,["imageSize"],o),null!=(a=tk(n,["personGeneration"]))&&tP(i,["personGeneration"],a),null!=(l=tk(n,["prominentPeople"]))&&tP(i,["prominentPeople"],l),null!=(u=tk(n,["outputMimeType"]))&&tP(i,["imageOutputOptions","mimeType"],u),null!=(c=tk(n,["outputCompressionQuality"]))&&tP(i,["imageOutputOptions","compressionQuality"],c),null!=(d=tk(n,["imageOutputOptions"]))&&tP(i,["imageOutputOptions"],d),i)),void 0!==tk(t,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let $=tk(t,["modelArmorConfig"]);void 0!==r&&null!=$&&tP(r,["modelArmorConfig"],$);let q=tk(t,["serviceTier"]);return void 0!==r&&null!=q&&tP(r,["serviceTier"],q),h}(e,o,n)),n}function r0(e,t){let r={},n=tk(e,["sdkHttpResponse"]);null!=n&&tP(r,["sdkHttpResponse"],n);let i=tk(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["content"]);null!=r&&tP(t,["content"],r);let n=tk(e,["citationMetadata"]);null!=n&&tP(t,["citationMetadata"],function(e){let t={},r=tk(e,["citationSources"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["citations"],e)}return t}(n));let i=tk(e,["tokenCount"]);null!=i&&tP(t,["tokenCount"],i);let s=tk(e,["finishReason"]);null!=s&&tP(t,["finishReason"],s);let o=tk(e,["groundingMetadata"]);null!=o&&tP(t,["groundingMetadata"],o);let a=tk(e,["avgLogprobs"]);null!=a&&tP(t,["avgLogprobs"],a);let l=tk(e,["index"]);null!=l&&tP(t,["index"],l);let u=tk(e,["logprobsResult"]);null!=u&&tP(t,["logprobsResult"],u);let c=tk(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["safetyRatings"],e)}let d=tk(e,["urlContextMetadata"]);return null!=d&&tP(t,["urlContextMetadata"],d),t})(e))),tP(r,["candidates"],e)}let s=tk(e,["modelVersion"]);null!=s&&tP(r,["modelVersion"],s);let o=tk(e,["promptFeedback"]);null!=o&&tP(r,["promptFeedback"],o);let a=tk(e,["responseId"]);null!=a&&tP(r,["responseId"],a);let l=tk(e,["usageMetadata"]);null!=l&&tP(r,["usageMetadata"],l);let u=tk(e,["modelStatus"]);return null!=u&&tP(r,["modelStatus"],u),r}function r1(e,t){let r={},n=tk(e,["sdkHttpResponse"]);null!=n&&tP(r,["sdkHttpResponse"],n);let i=tk(e,["candidates"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),tP(r,["candidates"],e)}let s=tk(e,["createTime"]);null!=s&&tP(r,["createTime"],s);let o=tk(e,["modelVersion"]);null!=o&&tP(r,["modelVersion"],o);let a=tk(e,["promptFeedback"]);null!=a&&tP(r,["promptFeedback"],a);let l=tk(e,["responseId"]);null!=l&&tP(r,["responseId"],l);let u=tk(e,["usageMetadata"]);return null!=u&&tP(r,["usageMetadata"],u),r}function r2(e,t){let r={},n=tk(e,["_self"]);null!=n&&tP(r,["image"],r4(n));let i=tk(e,["raiFilteredReason"]);null!=i&&tP(r,["raiFilteredReason"],i);let s=tk(e,["_self"]);null!=s&&tP(r,["safetyAttributes"],r7(s));let o=tk(e,["prompt"]);return null!=o&&tP(r,["enhancedPrompt"],o),r}function r4(e,t){let r={},n=tk(e,["gcsUri"]);null!=n&&tP(r,["gcsUri"],n);let i=tk(e,["bytesBase64Encoded"]);null!=i&&tP(r,["imageBytes"],tx(i));let s=tk(e,["mimeType"]);return null!=s&&tP(r,["mimeType"],s),r}function r6(e,t){let r={};if(void 0!==tk(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");let n=tk(e,["imageBytes"]);null!=n&&tP(r,["bytesBase64Encoded"],tx(n));let i=tk(e,["mimeType"]);return null!=i&&tP(r,["mimeType"],i),r}function r3(e,t){let r={},n=tk(e,["gcsUri"]);null!=n&&tP(r,["gcsUri"],n);let i=tk(e,["imageBytes"]);null!=i&&tP(r,["bytesBase64Encoded"],tx(i));let s=tk(e,["mimeType"]);return null!=s&&tP(r,["mimeType"],s),r}function r5(e,t){var r;let n,i,s,o,a={},l=tk(e,["name"]);null!=l&&tP(a,["name"],l);let u=tk(e,["displayName"]);null!=u&&tP(a,["displayName"],u);let c=tk(e,["description"]);null!=c&&tP(a,["description"],c);let d=tk(e,["version"]);null!=d&&tP(a,["version"],d);let h=tk(e,["_self"]);null!=h&&tP(a,["tunedModelInfo"],(n={},null!=(i=tk(r=h,["baseModel"]))&&tP(n,["baseModel"],i),null!=(s=tk(r,["createTime"]))&&tP(n,["createTime"],s),null!=(o=tk(r,["updateTime"]))&&tP(n,["updateTime"],o),n));let p=tk(e,["inputTokenLimit"]);null!=p&&tP(a,["inputTokenLimit"],p);let f=tk(e,["outputTokenLimit"]);null!=f&&tP(a,["outputTokenLimit"],f);let m=tk(e,["supportedGenerationMethods"]);null!=m&&tP(a,["supportedActions"],m);let g=tk(e,["temperature"]);null!=g&&tP(a,["temperature"],g);let y=tk(e,["maxTemperature"]);null!=y&&tP(a,["maxTemperature"],y);let _=tk(e,["topP"]);null!=_&&tP(a,["topP"],_);let E=tk(e,["topK"]);null!=E&&tP(a,["topK"],E);let A=tk(e,["thinking"]);return null!=A&&tP(a,["thinking"],A),a}function r8(e,t){var r;let n,i,s,o,a={},l=tk(e,["name"]);null!=l&&tP(a,["name"],l);let u=tk(e,["displayName"]);null!=u&&tP(a,["displayName"],u);let c=tk(e,["description"]);null!=c&&tP(a,["description"],c);let d=tk(e,["versionId"]);null!=d&&tP(a,["version"],d);let h=tk(e,["deployedModels"]);if(null!=h){let e=h;Array.isArray(e)&&(e=e.map(e=>{let t,r,n;return t={},null!=(r=tk(e,["endpoint"]))&&tP(t,["name"],r),null!=(n=tk(e,["deployedModelId"]))&&tP(t,["deployedModelId"],n),t})),tP(a,["endpoints"],e)}let p=tk(e,["labels"]);null!=p&&tP(a,["labels"],p);let f=tk(e,["_self"]);null!=f&&tP(a,["tunedModelInfo"],(n={},null!=(i=tk(r=f,["labels","google-vertex-llm-tuning-base-model-id"]))&&tP(n,["baseModel"],i),null!=(s=tk(r,["createTime"]))&&tP(n,["createTime"],s),null!=(o=tk(r,["updateTime"]))&&tP(n,["updateTime"],o),n));let m=tk(e,["defaultCheckpointId"]);null!=m&&tP(a,["defaultCheckpointId"],m);let g=tk(e,["checkpoints"]);if(null!=g){let e=g;Array.isArray(e)&&(e=e.map(e=>e)),tP(a,["checkpoints"],e)}return a}function r9(e,t){let r={},n=tk(e,["safetyAttributes","categories"]);null!=n&&tP(r,["categories"],n);let i=tk(e,["safetyAttributes","scores"]);null!=i&&tP(r,["scores"],i);let s=tk(e,["contentType"]);return null!=s&&tP(r,["contentType"],s),r}function r7(e,t){let r={},n=tk(e,["safetyAttributes","categories"]);null!=n&&tP(r,["categories"],n);let i=tk(e,["safetyAttributes","scores"]);null!=i&&tP(r,["scores"],i);let s=tk(e,["contentType"]);return null!=s&&tP(r,["contentType"],s),r}function ne(e,t){let r={},n=tk(e,["retrieval"]);null!=n&&tP(r,["retrieval"],n);let i=tk(e,["computerUse"]);if(null!=i&&tP(r,["computerUse"],i),void 0!==tk(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let s=tk(e,["googleSearch"]);null!=s&&tP(r,["googleSearch"],s);let o=tk(e,["googleMaps"]);null!=o&&tP(r,["googleMaps"],o);let a=tk(e,["codeExecution"]);null!=a&&tP(r,["codeExecution"],a);let l=tk(e,["enterpriseWebSearch"]);null!=l&&tP(r,["enterpriseWebSearch"],l);let u=tk(e,["functionDeclarations"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["description"]);null!=r&&tP(t,["description"],r);let n=tk(e,["name"]);null!=n&&tP(t,["name"],n);let i=tk(e,["parameters"]);null!=i&&tP(t,["parameters"],i);let s=tk(e,["parametersJsonSchema"]);null!=s&&tP(t,["parametersJsonSchema"],s);let o=tk(e,["response"]);null!=o&&tP(t,["response"],o);let a=tk(e,["responseJsonSchema"]);if(null!=a&&tP(t,["responseJsonSchema"],a),void 0!==tk(e,["behavior"]))throw Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t})(e))),tP(r,["functionDeclarations"],e)}let c=tk(e,["googleSearchRetrieval"]);null!=c&&tP(r,["googleSearchRetrieval"],c);let d=tk(e,["parallelAiSearch"]);null!=d&&tP(r,["parallelAiSearch"],d);let h=tk(e,["urlContext"]);if(null!=h&&tP(r,["urlContext"],h),void 0!==tk(e,["mcpServers"]))throw Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return r}function nt(e,t){let r={},n=tk(e,["uri"]);null!=n&&tP(r,["uri"],n);let i=tk(e,["videoBytes"]);null!=i&&tP(r,["encodedVideo"],tx(i));let s=tk(e,["mimeType"]);return null!=s&&tP(r,["encoding"],s),r}function nr(e,t){let r={},n=tk(e,["uri"]);null!=n&&tP(r,["gcsUri"],n);let i=tk(e,["videoBytes"]);null!=i&&tP(r,["bytesBase64Encoded"],tx(i));let s=tk(e,["mimeType"]);return null!=s&&tP(r,["mimeType"],s),r}function nn(e,t){let r=tk(e,["mimeType"]);void 0!==t&&null!=r&&tP(t,["mimeType"],r);let n=tk(e,["displayName"]);void 0!==t&&null!=n&&tP(t,["displayName"],n);let i=tk(e,["customMetadata"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["customMetadata"],e)}let s=tk(e,["chunkingConfig"]);return void 0!==t&&null!=s&&tP(t,["chunkingConfig"],s),{}}let ni="x-goog-api-client",ns=new Set(["us","eu"]),no=[408,429,500,502,503,504];class na{constructor(e){var t,r,n;this.clientOptions=Object.assign({},e),this.customBaseUrl=null==(t=e.httpOptions)?void 0:t.baseUrl,this.clientOptions.vertexai&&(this.clientOptions.project&&this.clientOptions.location?this.clientOptions.apiKey=void 0:this.clientOptions.apiKey&&(this.clientOptions.project=void 0,this.clientOptions.location=void 0));let i={};if(this.clientOptions.vertexai){if(this.clientOptions.location||this.clientOptions.apiKey||this.customBaseUrl||(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");let t=e.project&&e.location||!!e.apiKey;this.customBaseUrl&&!t?(i.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||"global"===this.clientOptions.location?i.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&ns.has(this.clientOptions.location)?i.baseUrl=`https://aiplatform.${this.clientOptions.location}.rep.googleapis.com/`:this.clientOptions.project&&this.clientOptions.location&&(i.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),i.apiVersion=null!=(r=this.clientOptions.apiVersion)?r:"v1beta1"}else this.clientOptions.apiKey||console.warn("API key should be set when using the Gemini API."),i.apiVersion=null!=(n=this.clientOptions.apiVersion)?n:"v1beta",i.baseUrl="https://generativelanguage.googleapis.com/";i.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=i,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(i,e.httpOptions))}isVertexAI(){var e;return null!=(e=this.clientOptions.vertexai)&&e}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)return this.clientOptions.httpOptions.baseUrl;throw Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||void 0===e.baseUrl||void 0===e.apiVersion)throw Error("HTTP options are not correctly set.");let t=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&""!==e.apiVersion&&t.push(e.apiVersion),t.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=new URL(this.getBaseUrl());return e.protocol="http:"==e.protocol?"ws":"wss",e.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw Error("HTTP options are not correctly set.")}constructUrl(e,t,r){let n=[this.getRequestUrlInternal(t)];return r&&n.push(this.getBaseResourcePath()),""!==e&&n.push(e),new URL(`${n.join("/")}`)}shouldPrependVertexProjectPath(e,t){return!(t.baseUrl&&t.baseUrlResourceScope===e0.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||"GET"===e.httpMethod&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,t),n=this.constructUrl(e.path,t,r);if(e.queryParams)for(let[t,r]of Object.entries(e.queryParams))n.searchParams.append(t,String(r));let i={};if("GET"===e.httpMethod){if(e.body&&"{}"!==e.body)throw Error("Request body should be empty for GET request, but got non empty request body")}else i.body=e.body;return i=await this.includeExtraHttpOptionsToRequestInit(i,t,n.toString(),e.abortSignal),this.unaryApiCall(n,i,e.httpMethod)}patchHttpOptions(e,t){let r=JSON.parse(JSON.stringify(e));for(let[e,n]of Object.entries(t))"object"==typeof n?r[e]=Object.assign(Object.assign({},r[e]),n):void 0!==n&&(r[e]=n);return r}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e,t),n=this.constructUrl(e.path,t,r);n.searchParams.has("alt")&&"sse"===n.searchParams.get("alt")||n.searchParams.set("alt","sse");let i={};return i.body=e.body,i=await this.includeExtraHttpOptionsToRequestInit(i,t,n.toString(),e.abortSignal),this.streamApiCall(n,i,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,r,n){if(t&&t.timeout||n){let r=new AbortController,i=r.signal;if(t.timeout&&(null==t?void 0:t.timeout)>0){let e=setTimeout(()=>r.abort(),t.timeout);e&&"function"==typeof e.unref&&e.unref()}n&&n.addEventListener("abort",()=>{r.abort()}),e.signal=i}return t&&null!==t.extraBody&&function(e,t){if(!t||0===Object.keys(t).length)return;if(e.body instanceof Blob)return console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");let r={};if("string"==typeof e.body&&e.body.length>0)try{let t=JSON.parse(e.body);if("object"!=typeof t||null===t||Array.isArray(t))return void console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");r=t}catch(e){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}e.body=JSON.stringify(function e(t,r){let n=Object.assign({},t);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)){let i=r[t],s=n[t];i&&"object"==typeof i&&!Array.isArray(i)&&s&&"object"==typeof s&&!Array.isArray(s)?n[t]=e(s,i):(s&&i&&typeof s!=typeof i&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${t}". Original type: ${typeof s}, New type: ${typeof i}. Overwriting.`),n[t]=i)}return n}(r,t))}(e,t.extraBody),e.headers=await this.getHeadersInternal(t,r),e}async unaryApiCall(e,t,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r})).then(async e=>(await nl(e),new tD(e))).catch(e=>{if(e instanceof Error)throw e;throw Error(JSON.stringify(e))})}async streamApiCall(e,t,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r})).then(async e=>(await nl(e),this.processStreamResponse(e))).catch(e=>{if(e instanceof Error)throw e;throw Error(JSON.stringify(e))})}processStreamResponse(e){return rF(this,arguments,function*(){var t;let r=null==(t=null==e?void 0:e.body)?void 0:t.getReader(),n=new TextDecoder("utf-8");if(!r)throw Error("Response body is empty");try{let t="",i="data:",s=["\n\n","\r\r","\r\n\r\n"];for(;;){let{done:o,value:a}=yield rG(r.read());if(o){if(t.trim().length>0)throw Error("Incomplete JSON segment at the end");break}let l=n.decode(a,{stream:!0});try{let e=JSON.parse(l);if("error"in e){let t=JSON.parse(JSON.stringify(e.error)),r=t.status,n=t.code,i=`got status: ${r}. ${JSON.stringify(e)}`;if(n>=400&&n<600)throw new rK({message:i,status:n})}}catch(e){if("ApiError"===e.name)throw e}t+=l;let u=-1,c=0;for(;;){for(let e of(u=-1,c=0,s)){let r=t.indexOf(e);-1!==r&&(-1===u||r<u)&&(u=r,c=e.length)}if(-1===u)break;let r=t.substring(0,u);t=t.substring(u+c);let n=r.trim();if(n.startsWith(i)){let t=n.substring(i.length).trim();try{let r=new Response(t,{headers:null==e?void 0:e.headers,status:null==e?void 0:e.status,statusText:null==e?void 0:e.statusText});yield yield rG(new tD(r))}catch(e){throw Error(`exception parsing stream chunk ${t}. ${e}`)}}}}}finally{r.releaseLock()}})}async apiCall(e,t){var r;if(!this.clientOptions.httpOptions||!this.clientOptions.httpOptions.retryOptions)return fetch(e,t);let n=this.clientOptions.httpOptions.retryOptions,i=async()=>{let r=await fetch(e,t);if(r.ok)return r;if(no.includes(r.status))throw Error(`Retryable HTTP Error: ${r.statusText}`);throw new tA.AbortError(`Non-retryable exception ${r.statusText} sending request`)};return(0,tA.default)(i,{retries:(null!=(r=n.attempts)?r:5)-1})}getDefaultHeaders(){let e={},t="google-genai-sdk/1.52.0 "+this.clientOptions.userAgentExtra;return e["User-Agent"]=t,e[ni]=t,e["Content-Type"]="application/json",e}async getHeadersInternal(e,t){let r=new Headers;if(e&&e.headers){for(let[t,n]of Object.entries(e.headers))r.append(t,n);e.timeout&&e.timeout>0&&r.append("X-Server-Timeout",String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(r,t),r}getFileName(e){var t;let r="";return"string"==typeof e&&(r=null!=(t=(r=e.replace(/[/\\]+$/,"")).split(/[/\\]/).pop())?t:""),r}async uploadFile(e,t){var r;let n={};null!=t&&(n.mimeType=t.mimeType,n.name=t.name,n.displayName=t.displayName),n.name&&!n.name.startsWith("files/")&&(n.name=`files/${n.name}`);let i=this.clientOptions.uploader,s=await i.stat(e);n.sizeBytes=String(s.size);let o=null!=(r=null==t?void 0:t.mimeType)?r:s.type;if(void 0===o||""===o)throw Error("Can not determine mimeType. Please provide mimeType in the config.");n.mimeType=o;let a={file:n},l=this.getFileName(e),u=tR("upload/v1beta/files",a._url),c=await this.fetchUploadUrl(u,n.sizeBytes,n.mimeType,l,a,null==t?void 0:t.httpOptions);return i.upload(e,c,this)}async uploadFileToFileSearchStore(e,t,r){var n;let i=this.clientOptions.uploader,s=await i.stat(t),o=String(s.size),a=null!=(n=null==r?void 0:r.mimeType)?n:s.type;if(void 0===a||""===a)throw Error("Can not determine mimeType. Please provide mimeType in the config.");let l=`upload/v1beta/${e}:uploadToFileSearchStore`,u=this.getFileName(t),c={};null!=r&&nn(r,c);let d=await this.fetchUploadUrl(l,o,a,u,c,null==r?void 0:r.httpOptions);return i.uploadToFileSearchStore(t,d,this)}async downloadFile(e){let t=this.clientOptions.downloader;await t.download(e,this)}async fetchUploadUrl(e,t,r,n,i,s){var o;let a={};a=s||{apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${r}`},n?{"X-Goog-Upload-File-Name":n}:{})};let l=await this.request({path:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:a});if(!l||!(null==l?void 0:l.headers))throw Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let u=null==(o=null==l?void 0:l.headers)?void 0:o["x-goog-upload-url"];if(void 0===u)throw Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}}async function nl(e){var t;if(void 0===e)throw Error("response is undefined");if(!e.ok){let r=e.status,n=JSON.stringify((null==(t=e.headers.get("content-type"))?void 0:t.includes("application/json"))?await e.json():{error:{message:await e.text(),code:e.status,status:e.statusText}});if(r>=400&&r<600)throw new rK({message:n,status:r});throw Error(n)}}function nu(e){for(let r of e){var t;if(null!==(t=r)&&"object"==typeof t&&t instanceof nd||"object"==typeof r&&"inputSchema"in r)return!0}return!1}function nc(e){var t;let r=null!=(t=e[ni])?t:"";e[ni]=(r+" mcp_used/unknown").trimStart()}class nd{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(e,t){return new nd(e,t)}async initialize(){var e,t,r,n;if(this.mcpTools.length>0)return;let i={},s=[];for(let u of this.mcpClients)try{for(var o,a=!0,l=(t=void 0,r$(function(e){return rF(this,arguments,function*(e,t=100){let r,n=0;for(;n<t;){let t=yield rG(e.listTools({cursor:r}));for(let e of t.tools)yield yield rG(e),n++;if(!t.nextCursor)break;r=t.nextCursor}})}(u)));!(e=(o=await l.next()).done);a=!0){n=o.value,a=!1,s.push(n);let e=n.name;if(i[e])throw Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);i[e]=u}}catch(e){t={error:e}}finally{try{!a&&!e&&(r=l.return)&&await r.call(l)}finally{if(t)throw t.error}}this.mcpTools=s,this.functionNameToMcpClient=i}async tool(){return await this.initialize(),function(e,t={}){let r=[],n=new Set;for(let i of e){let e=i.name;if(n.has(e))throw Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);n.add(e);let s=function(e,t={}){let r={name:e.name,description:e.description,parametersJsonSchema:e.inputSchema};return e.outputSchema&&(r.responseJsonSchema=e.outputSchema),t.behavior&&(r.behavior=t.behavior),{functionDeclarations:[r]}}(i,t);s.functionDeclarations&&r.push(...s.functionDeclarations)}return{functionDeclarations:r}}(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let r of e)if(r.name in this.functionNameToMcpClient){let e,n=this.functionNameToMcpClient[r.name];this.config.timeout&&(e={timeout:this.config.timeout});let i=await n.callTool({name:r.name,arguments:r.args},void 0,e);t.push({functionResponse:{name:r.name,response:i.isError?{error:i}:i}})}return t}}async function nh(e,t,r){let n=new t8;Object.assign(n,r.data instanceof Blob?JSON.parse(await r.data.text()):JSON.parse(r.data)),t(n)}class np{constructor(e,t,r){this.apiClient=e,this.auth=t,this.webSocketFactory=r}async connect(e){var t,r;let n;if(this.apiClient.isVertexAI())throw Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let i=this.apiClient.getWebsocketBaseUrl(),s=this.apiClient.getApiVersion(),o=function(e){let t=new Headers;for(let[r,n]of Object.entries(e))t.append(r,n);return t}(this.apiClient.getDefaultHeaders()),a=this.apiClient.getApiKey(),l=`${i}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${a}`,u=()=>{},c=new Promise(e=>{u=e}),d=e.callbacks,h=this.apiClient,p={onopen:function(){u({})},onmessage:e=>{nh(h,d.onmessage,e)},onerror:null!=(t=null==d?void 0:d.onerror)?t:function(e){},onclose:null!=(r=null==d?void 0:d.onclose)?r:function(e){}},f=this.webSocketFactory.create(l,(n={},o.forEach((e,t)=>{n[t]=e}),n),p);f.connect(),await c;let m=t7(this.apiClient,e.model);return f.send(JSON.stringify({setup:{model:m}})),new nf(f,this.apiClient)}}class nf{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||0===Object.keys(e.weightedPrompts).length)throw Error("Weighted prompts must be set and contain at least one entry.");let t=function(e){let t={},r=tk(e,["weightedPrompts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["weightedPrompts"],e)}return t}(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){let t,r;e.musicGenerationConfig||(e.musicGenerationConfig={});let n=(t={},null!=(r=tk(e,["musicGenerationConfig"]))&&tP(t,["musicGenerationConfig"],r),t);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){this.conn.send(JSON.stringify({playbackControl:e}))}play(){this.sendPlaybackControl(t_.PLAY)}pause(){this.sendPlaybackControl(t_.PAUSE)}stop(){this.sendPlaybackControl(t_.STOP)}resetContext(){this.sendPlaybackControl(t_.RESET_CONTEXT)}close(){this.conn.close()}}async function nm(e,t,r){let n=new t5,i=JSON.parse(r.data instanceof Blob?await r.data.text():r.data instanceof ArrayBuffer?new TextDecoder().decode(r.data):r.data);if(e.isVertexAI()){let e,t,r,s,o,a,l,u,c,d,h,p;Object.assign(n,(e={},null!=(t=tk(i,["setupComplete"]))&&tP(e,["setupComplete"],t),null!=(r=tk(i,["serverContent"]))&&tP(e,["serverContent"],r),null!=(s=tk(i,["toolCall"]))&&tP(e,["toolCall"],s),null!=(o=tk(i,["toolCallCancellation"]))&&tP(e,["toolCallCancellation"],o),null!=(a=tk(i,["usageMetadata"]))&&tP(e,["usageMetadata"],function(e){let t={},r=tk(e,["promptTokenCount"]);null!=r&&tP(t,["promptTokenCount"],r);let n=tk(e,["cachedContentTokenCount"]);null!=n&&tP(t,["cachedContentTokenCount"],n);let i=tk(e,["candidatesTokenCount"]);null!=i&&tP(t,["responseTokenCount"],i);let s=tk(e,["toolUsePromptTokenCount"]);null!=s&&tP(t,["toolUsePromptTokenCount"],s);let o=tk(e,["thoughtsTokenCount"]);null!=o&&tP(t,["thoughtsTokenCount"],o);let a=tk(e,["totalTokenCount"]);null!=a&&tP(t,["totalTokenCount"],a);let l=tk(e,["promptTokensDetails"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["promptTokensDetails"],e)}let u=tk(e,["cacheTokensDetails"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["cacheTokensDetails"],e)}let c=tk(e,["candidatesTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["responseTokensDetails"],e)}let d=tk(e,["toolUsePromptTokensDetails"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["toolUsePromptTokensDetails"],e)}let h=tk(e,["trafficType"]);return null!=h&&tP(t,["trafficType"],h),t}(a)),null!=(l=tk(i,["goAway"]))&&tP(e,["goAway"],l),null!=(u=tk(i,["sessionResumptionUpdate"]))&&tP(e,["sessionResumptionUpdate"],u),null!=(c=tk(i,["voiceActivityDetectionSignal"]))&&tP(e,["voiceActivityDetectionSignal"],c),null!=(d=tk(i,["voiceActivity"]))&&tP(e,["voiceActivity"],(h={},null!=(p=tk(d,["type"]))&&tP(h,["voiceActivityType"],p),h)),e))}else Object.assign(n,i);t(n)}class ng{constructor(e,t,r){this.apiClient=e,this.auth=t,this.webSocketFactory=r,this.music=new np(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,r,n,i,s,o,a,l;let u,c;if(e.config&&e.config.httpOptions)throw Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let d=this.apiClient.getWebsocketBaseUrl(),h=this.apiClient.getApiVersion(),p=this.apiClient.getHeaders();e.config&&e.config.tools&&nu(e.config.tools)&&nc(p);let f=function(e){let t=new Headers;for(let[r,n]of Object.entries(e))t.append(r,n);return t}(p);if(this.apiClient.isVertexAI()){let e=this.apiClient.getProject(),t=this.apiClient.getLocation(),r=this.apiClient.getApiKey();this.apiClient.getCustomBaseUrl()&&!(e&&t||r)?u=d:(u=`${d}/ws/google.cloud.aiplatform.${h}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(f,u))}else{let e=this.apiClient.getApiKey(),t="BidiGenerateContent",r="key";(null==e?void 0:e.startsWith("auth_tokens/"))&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),"v1alpha"!==h&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),t="BidiGenerateContentConstrained",r="access_token"),u=`${d}/ws/google.ai.generativelanguage.${h}.GenerativeService.${t}?${r}=${e}`}let m=()=>{},g=new Promise(e=>{m=e}),y=e.callbacks,_=this.apiClient,E={onopen:function(){var e;null==(e=null==y?void 0:y.onopen)||e.call(y),m({})},onmessage:e=>{nm(_,y.onmessage,e)},onerror:null!=(t=null==y?void 0:y.onerror)?t:function(e){},onclose:null!=(r=null==y?void 0:y.onclose)?r:function(e){}},A=this.webSocketFactory.create(u,(c={},f.forEach((e,t)=>{c[t]=e}),c),E);A.connect(),await g;let v=t7(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&v.startsWith("publishers/")){let e=this.apiClient.getProject(),t=this.apiClient.getLocation();e&&t&&(v=`projects/${e}/locations/${t}/`+v)}let b={};this.apiClient.isVertexAI()&&(null==(n=e.config)?void 0:n.responseModalities)===void 0&&(void 0===e.config?e.config={responseModalities:[e$.AUDIO]}:e.config.responseModalities=[e$.AUDIO]),(null==(i=e.config)?void 0:i.generationConfig)&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");let w=null!=(o=null==(s=e.config)?void 0:s.tools)?o:[],T=[];for(let e of w)this.isCallableTool(e)?T.push(await e.tool()):T.push(e);T.length>0&&(e.config.tools=T);let I={model:v,config:e.config,callbacks:e.callbacks};if(this.apiClient.isVertexAI()){let e,t,r;a=this.apiClient,e={},null!=(t=tk(I,["model"]))&&tP(e,["setup","model"],t7(a,t)),null!=(r=tk(I,["config"]))&&tP(e,["config"],function(e,t){let r=tk(e,["generationConfig"]);void 0!==t&&null!=r&&tP(t,["setup","generationConfig"],function(e){let t={},r=tk(e,["modelSelectionConfig"]);null!=r&&tP(t,["modelConfig"],r);let n=tk(e,["responseJsonSchema"]);null!=n&&tP(t,["responseJsonSchema"],n);let i=tk(e,["audioTimestamp"]);null!=i&&tP(t,["audioTimestamp"],i);let s=tk(e,["candidateCount"]);null!=s&&tP(t,["candidateCount"],s);let o=tk(e,["enableAffectiveDialog"]);null!=o&&tP(t,["enableAffectiveDialog"],o);let a=tk(e,["frequencyPenalty"]);null!=a&&tP(t,["frequencyPenalty"],a);let l=tk(e,["logprobs"]);null!=l&&tP(t,["logprobs"],l);let u=tk(e,["maxOutputTokens"]);null!=u&&tP(t,["maxOutputTokens"],u);let c=tk(e,["mediaResolution"]);null!=c&&tP(t,["mediaResolution"],c);let d=tk(e,["presencePenalty"]);null!=d&&tP(t,["presencePenalty"],d);let h=tk(e,["responseLogprobs"]);null!=h&&tP(t,["responseLogprobs"],h);let p=tk(e,["responseMimeType"]);null!=p&&tP(t,["responseMimeType"],p);let f=tk(e,["responseModalities"]);null!=f&&tP(t,["responseModalities"],f);let m=tk(e,["responseSchema"]);null!=m&&tP(t,["responseSchema"],m);let g=tk(e,["routingConfig"]);null!=g&&tP(t,["routingConfig"],g);let y=tk(e,["seed"]);null!=y&&tP(t,["seed"],y);let _=tk(e,["speechConfig"]);null!=_&&tP(t,["speechConfig"],_);let E=tk(e,["stopSequences"]);null!=E&&tP(t,["stopSequences"],E);let A=tk(e,["temperature"]);null!=A&&tP(t,["temperature"],A);let v=tk(e,["thinkingConfig"]);null!=v&&tP(t,["thinkingConfig"],v);let b=tk(e,["topK"]);null!=b&&tP(t,["topK"],b);let w=tk(e,["topP"]);if(null!=w&&tP(t,["topP"],w),void 0!==tk(e,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(r));let n=tk(e,["responseModalities"]);void 0!==t&&null!=n&&tP(t,["setup","generationConfig","responseModalities"],n);let i=tk(e,["temperature"]);void 0!==t&&null!=i&&tP(t,["setup","generationConfig","temperature"],i);let s=tk(e,["topP"]);void 0!==t&&null!=s&&tP(t,["setup","generationConfig","topP"],s);let o=tk(e,["topK"]);void 0!==t&&null!=o&&tP(t,["setup","generationConfig","topK"],o);let a=tk(e,["maxOutputTokens"]);void 0!==t&&null!=a&&tP(t,["setup","generationConfig","maxOutputTokens"],a);let l=tk(e,["mediaResolution"]);void 0!==t&&null!=l&&tP(t,["setup","generationConfig","mediaResolution"],l);let u=tk(e,["seed"]);void 0!==t&&null!=u&&tP(t,["setup","generationConfig","seed"],u);let c=tk(e,["speechConfig"]);void 0!==t&&null!=c&&tP(t,["setup","generationConfig","speechConfig"],rm(c));let d=tk(e,["thinkingConfig"]);void 0!==t&&null!=d&&tP(t,["setup","generationConfig","thinkingConfig"],d);let h=tk(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&tP(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=tk(e,["systemInstruction"]);void 0!==t&&null!=p&&tP(t,["setup","systemInstruction"],function(e){let t={},r=tk(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["mediaResolution"]);null!=r&&tP(t,["mediaResolution"],r);let n=tk(e,["codeExecutionResult"]);null!=n&&tP(t,["codeExecutionResult"],n);let i=tk(e,["executableCode"]);null!=i&&tP(t,["executableCode"],i);let s=tk(e,["fileData"]);null!=s&&tP(t,["fileData"],s);let o=tk(e,["functionCall"]);null!=o&&tP(t,["functionCall"],o);let a=tk(e,["functionResponse"]);null!=a&&tP(t,["functionResponse"],a);let l=tk(e,["inlineData"]);null!=l&&tP(t,["inlineData"],l);let u=tk(e,["text"]);null!=u&&tP(t,["text"],u);let c=tk(e,["thought"]);null!=c&&tP(t,["thought"],c);let d=tk(e,["thoughtSignature"]);null!=d&&tP(t,["thoughtSignature"],d);let h=tk(e,["videoMetadata"]);if(null!=h&&tP(t,["videoMetadata"],h),void 0!==tk(e,["toolCall"]))throw Error("toolCall parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["toolResponse"]))throw Error("toolResponse parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");if(void 0!==tk(e,["partMetadata"]))throw Error("partMetadata parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t})(e))),tP(t,["parts"],e)}let n=tk(e,["role"]);return null!=n&&tP(t,["role"],n),t}(rc(p)));let f=tk(e,["tools"]);if(void 0!==t&&null!=f){let e=ry(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["retrieval"]);null!=r&&tP(t,["retrieval"],r);let n=tk(e,["computerUse"]);if(null!=n&&tP(t,["computerUse"],n),void 0!==tk(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let i=tk(e,["googleSearch"]);null!=i&&tP(t,["googleSearch"],i);let s=tk(e,["googleMaps"]);null!=s&&tP(t,["googleMaps"],s);let o=tk(e,["codeExecution"]);null!=o&&tP(t,["codeExecution"],o);let a=tk(e,["enterpriseWebSearch"]);null!=a&&tP(t,["enterpriseWebSearch"],a);let l=tk(e,["functionDeclarations"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["description"]);null!=r&&tP(t,["description"],r);let n=tk(e,["name"]);null!=n&&tP(t,["name"],n);let i=tk(e,["parameters"]);null!=i&&tP(t,["parameters"],i);let s=tk(e,["parametersJsonSchema"]);null!=s&&tP(t,["parametersJsonSchema"],s);let o=tk(e,["response"]);null!=o&&tP(t,["response"],o);let a=tk(e,["responseJsonSchema"]);if(null!=a&&tP(t,["responseJsonSchema"],a),void 0!==tk(e,["behavior"]))throw Error("behavior parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t})(e))),tP(t,["functionDeclarations"],e)}let u=tk(e,["googleSearchRetrieval"]);null!=u&&tP(t,["googleSearchRetrieval"],u);let c=tk(e,["parallelAiSearch"]);null!=c&&tP(t,["parallelAiSearch"],c);let d=tk(e,["urlContext"]);if(null!=d&&tP(t,["urlContext"],d),void 0!==tk(e,["mcpServers"]))throw Error("mcpServers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t})(rg(e)))),tP(t,["setup","tools"],e)}let m=tk(e,["sessionResumption"]);void 0!==t&&null!=m&&tP(t,["setup","sessionResumption"],m);let g=tk(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&tP(t,["setup","inputAudioTranscription"],g);let y=tk(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&tP(t,["setup","outputAudioTranscription"],y);let _=tk(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&tP(t,["setup","realtimeInputConfig"],_);let E=tk(e,["contextWindowCompression"]);void 0!==t&&null!=E&&tP(t,["setup","contextWindowCompression"],E);let A=tk(e,["proactivity"]);void 0!==t&&null!=A&&tP(t,["setup","proactivity"],A);let v=tk(e,["explicitVadSignal"]);void 0!==t&&null!=v&&tP(t,["setup","explicitVadSignal"],v);let b=tk(e,["avatarConfig"]);void 0!==t&&null!=b&&tP(t,["setup","avatarConfig"],b);let w=tk(e,["safetySettings"]);if(void 0!==t&&null!=w){let e=w;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["setup","safetySettings"],e)}return{}}(r,e)),b=e}else{let e,t,r;l=this.apiClient,e={},null!=(t=tk(I,["model"]))&&tP(e,["setup","model"],t7(l,t)),null!=(r=tk(I,["config"]))&&tP(e,["config"],function(e,t){let r=tk(e,["generationConfig"]);void 0!==t&&null!=r&&tP(t,["setup","generationConfig"],r);let n=tk(e,["responseModalities"]);void 0!==t&&null!=n&&tP(t,["setup","generationConfig","responseModalities"],n);let i=tk(e,["temperature"]);void 0!==t&&null!=i&&tP(t,["setup","generationConfig","temperature"],i);let s=tk(e,["topP"]);void 0!==t&&null!=s&&tP(t,["setup","generationConfig","topP"],s);let o=tk(e,["topK"]);void 0!==t&&null!=o&&tP(t,["setup","generationConfig","topK"],o);let a=tk(e,["maxOutputTokens"]);void 0!==t&&null!=a&&tP(t,["setup","generationConfig","maxOutputTokens"],a);let l=tk(e,["mediaResolution"]);void 0!==t&&null!=l&&tP(t,["setup","generationConfig","mediaResolution"],l);let u=tk(e,["seed"]);void 0!==t&&null!=u&&tP(t,["setup","generationConfig","seed"],u);let c=tk(e,["speechConfig"]);void 0!==t&&null!=c&&tP(t,["setup","generationConfig","speechConfig"],rm(c));let d=tk(e,["thinkingConfig"]);void 0!==t&&null!=d&&tP(t,["setup","generationConfig","thinkingConfig"],d);let h=tk(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&tP(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=tk(e,["systemInstruction"]);void 0!==t&&null!=p&&tP(t,["setup","systemInstruction"],function(e){let t={},r=tk(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p,f,m,g;return r={},null!=(n=tk(t=e,["mediaResolution"]))&&tP(r,["mediaResolution"],n),null!=(i=tk(t,["codeExecutionResult"]))&&tP(r,["codeExecutionResult"],i),null!=(s=tk(t,["executableCode"]))&&tP(r,["executableCode"],s),null!=(o=tk(t,["fileData"]))&&tP(r,["fileData"],function(e){let t={};if(void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=tk(e,["fileUri"]);null!=r&&tP(t,["fileUri"],r);let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(o)),null!=(a=tk(t,["functionCall"]))&&tP(r,["functionCall"],function(e){let t={},r=tk(e,["id"]);null!=r&&tP(t,["id"],r);let n=tk(e,["args"]);null!=n&&tP(t,["args"],n);let i=tk(e,["name"]);if(null!=i&&tP(t,["name"],i),void 0!==tk(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==tk(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=tk(t,["functionResponse"]))&&tP(r,["functionResponse"],l),null!=(u=tk(t,["inlineData"]))&&tP(r,["inlineData"],rz(u)),null!=(c=tk(t,["text"]))&&tP(r,["text"],c),null!=(d=tk(t,["thought"]))&&tP(r,["thought"],d),null!=(h=tk(t,["thoughtSignature"]))&&tP(r,["thoughtSignature"],h),null!=(p=tk(t,["videoMetadata"]))&&tP(r,["videoMetadata"],p),null!=(f=tk(t,["toolCall"]))&&tP(r,["toolCall"],f),null!=(m=tk(t,["toolResponse"]))&&tP(r,["toolResponse"],m),null!=(g=tk(t,["partMetadata"]))&&tP(r,["partMetadata"],g),r})),tP(t,["parts"],e)}let n=tk(e,["role"]);return null!=n&&tP(t,["role"],n),t}(rc(p)));let f=tk(e,["tools"]);if(void 0!==t&&null!=f){let e=ry(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t,r,n,i={};if(void 0!==tk(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let s=tk(e,["computerUse"]);null!=s&&tP(i,["computerUse"],s);let o=tk(e,["fileSearch"]);null!=o&&tP(i,["fileSearch"],o);let a=tk(e,["googleSearch"]);null!=a&&tP(i,["googleSearch"],function(e){let t={},r=tk(e,["searchTypes"]);if(null!=r&&tP(t,["searchTypes"],r),void 0!==tk(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==tk(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");let n=tk(e,["timeRangeFilter"]);return null!=n&&tP(t,["timeRangeFilter"],n),t}(a));let l=tk(e,["googleMaps"]);null!=l&&tP(i,["googleMaps"],(t={},null!=(r=tk(l,["authConfig"]))&&tP(t,["authConfig"],function(e){let t={},r=tk(e,["apiKey"]);if(null!=r&&tP(t,["apiKey"],r),void 0!==tk(e,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["authType"]))throw Error("authType parameter is not supported in Gemini API.");if(void 0!==tk(e,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oauthConfig"]))throw Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oidcConfig"]))throw Error("oidcConfig parameter is not supported in Gemini API.");return t}(r)),null!=(n=tk(l,["enableWidget"]))&&tP(t,["enableWidget"],n),t));let u=tk(e,["codeExecution"]);if(null!=u&&tP(i,["codeExecution"],u),void 0!==tk(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=tk(e,["functionDeclarations"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["functionDeclarations"],e)}let d=tk(e,["googleSearchRetrieval"]);if(null!=d&&tP(i,["googleSearchRetrieval"],d),void 0!==tk(e,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is not supported in Gemini API.");let h=tk(e,["urlContext"]);null!=h&&tP(i,["urlContext"],h);let p=tk(e,["mcpServers"]);if(null!=p){let e=p;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["mcpServers"],e)}return i})(rg(e)))),tP(t,["setup","tools"],e)}let m=tk(e,["sessionResumption"]);void 0!==t&&null!=m&&tP(t,["setup","sessionResumption"],function(e){let t={},r=tk(e,["handle"]);if(null!=r&&tP(t,["handle"],r),void 0!==tk(e,["transparent"]))throw Error("transparent parameter is not supported in Gemini API.");return t}(m));let g=tk(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&tP(t,["setup","inputAudioTranscription"],rW(g));let y=tk(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&tP(t,["setup","outputAudioTranscription"],rW(y));let _=tk(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&tP(t,["setup","realtimeInputConfig"],_);let E=tk(e,["contextWindowCompression"]);void 0!==t&&null!=E&&tP(t,["setup","contextWindowCompression"],E);let A=tk(e,["proactivity"]);if(void 0!==t&&null!=A&&tP(t,["setup","proactivity"],A),void 0!==tk(e,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is not supported in Gemini API.");let v=tk(e,["avatarConfig"]);void 0!==t&&null!=v&&tP(t,["setup","avatarConfig"],v);let b=tk(e,["safetySettings"]);if(void 0!==t&&null!=b){let e=b;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["category"]);if(null!=r&&tP(t,["category"],r),void 0!==tk(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=tk(e,["threshold"]);return null!=n&&tP(t,["threshold"],n),t})(e))),tP(t,["setup","safetySettings"],e)}return{}}(r,e)),b=e}return delete b.config,A.send(JSON.stringify(b)),new n_(A,this.apiClient)}isCallableTool(e){return"callTool"in e&&"function"==typeof e.callTool}}let ny={turnComplete:!0};class n_{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(null!==t.turns&&void 0!==t.turns){let r=[];try{r=rh(t.turns),e.isVertexAI()||(r=r.map(e=>rY(e)))}catch(e){throw Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:r,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let r=[];if(null==t.functionResponses||0===(r=Array.isArray(t.functionResponses)?t.functionResponses:[t.functionResponses]).length)throw Error("functionResponses is required.");for(let t of r){if("object"!=typeof t||null===t||!("name"in t)||!("response"in t))throw Error(`Could not parse function response, type '${typeof t}'.`);if(!e.isVertexAI()&&!("id"in t))throw Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},ny),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:function(e){let t={},r=tk(e,["media"]);if(null!=r){let e=rt(r);Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["mediaChunks"],e)}let n=tk(e,["audio"]);null!=n&&tP(t,["audio"],ri(n));let i=tk(e,["audioStreamEnd"]);null!=i&&tP(t,["audioStreamEnd"],i);let s=tk(e,["video"]);null!=s&&tP(t,["video"],rn(s));let o=tk(e,["text"]);null!=o&&tP(t,["text"],o);let a=tk(e,["activityStart"]);null!=a&&tP(t,["activityStart"],a);let l=tk(e,["activityEnd"]);return null!=l&&tP(t,["activityEnd"],l),t}(e)}:{realtimeInput:function(e){let t={},r=tk(e,["media"]);if(null!=r){let e=rt(r);Array.isArray(e)&&(e=e.map(e=>rz(e))),tP(t,["mediaChunks"],e)}let n=tk(e,["audio"]);null!=n&&tP(t,["audio"],rz(ri(n)));let i=tk(e,["audioStreamEnd"]);null!=i&&tP(t,["audioStreamEnd"],i);let s=tk(e,["video"]);null!=s&&tP(t,["video"],rz(rn(s)));let o=tk(e,["text"]);null!=o&&tP(t,["text"],o);let a=tk(e,["activityStart"]);null!=a&&tP(t,["activityStart"],a);let l=tk(e,["activityEnd"]);return null!=l&&tP(t,["activityEnd"],l),t}(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(null==e.functionResponses)throw Error("Tool response parameters are required.");let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}}function nE(e){var t,r,n;if(null==(t=null==e?void 0:e.automaticFunctionCalling)?void 0:t.disable)return!0;let i=!1;for(let t of null!=(r=null==e?void 0:e.tools)?r:[])if(nA(t)){i=!0;break}if(!i)return!0;let s=null==(n=null==e?void 0:e.automaticFunctionCalling)?void 0:n.maximumRemoteCalls;return(!(!s||!(s<0)&&Number.isInteger(s))||0==s)&&(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",s),!0)}function nA(e){return"callTool"in e&&"function"==typeof e.callTool}function nv(e){var t;let r=[];return(null==(t=null==e?void 0:e.config)?void 0:t.tools)&&e.config.tools.forEach((e,t)=>{nA(e)||e.functionDeclarations&&e.functionDeclarations.length>0&&r.push(t)}),r}function nb(e){var t;return!(null==(t=null==e?void 0:e.automaticFunctionCalling)?void 0:t.ignoreCallHistory)}class nw extends tC{constructor(e){super(),this.apiClient=e,this.embedContent=async e=>{if(!this.apiClient.isVertexAI())return e.model.includes("gemini-embedding-2")&&(e.contents=rh(e.contents)),await this.embedContentInternal(e);if(e.model.includes("gemini")&&"gemini-embedding-001"!==e.model||e.model.includes("maas")){let t=rh(e.contents);if(t.length>1)throw Error("The embedContent API for this model only supports one content at a time.");let r=Object.assign(Object.assign({},e),{content:t[0],embeddingApiType:e4.EMBED_CONTENT});return await this.embedContentInternal(r)}{let t=Object.assign(Object.assign({},e),{embeddingApiType:e4.PREDICT});return await this.embedContentInternal(t)}},this.generateContent=async e=>{var t,r,n,i,s,o,a,l;let u,c,d=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchem(e),!(null!=(l=null==(a=null==(o=e.config)?void 0:o.tools)?void 0:a.some(e=>nA(e)))&&l)||nE(e.config))return await this.generateContentInternal(d);let h=nv(e);if(h.length>0){let e=h.map(e=>`tools[${e}]`).join(", ");throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${e}.`)}let p=rh(d.contents),f=null!=(n=null==(r=null==(t=d.config)?void 0:t.automaticFunctionCalling)?void 0:r.maximumRemoteCalls)?n:10,m=0;for(;m<f&&(u=await this.generateContentInternal(d)).functionCalls&&0!==u.functionCalls.length;){let t=u.candidates[0].content,r=[];for(let t of null!=(s=null==(i=e.config)?void 0:i.tools)?s:[])if(nA(t)){let e=await t.callTool(u.functionCalls);r.push(...e)}m++,c={role:"user",parts:r},d.contents=rh(d.contents),d.contents.push(t),d.contents.push(c),nb(d.config)&&(p.push(t),p.push(c))}return nb(d.config)&&(u.automaticFunctionCallingHistory=p),u},this.generateContentStream=async e=>{var t,r,n,i,s;if(this.maybeMoveToResponseJsonSchem(e),nE(e.config)){let t=await this.processParamsMaybeAddMcpUsage(e);return await this.generateContentStreamInternal(t)}let o=nv(e);if(o.length>0){let e=o.map(e=>`tools[${e}]`).join(", ");throw Error(`Incompatible tools found at ${e}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let a=null==(n=null==(r=null==(t=null==e?void 0:e.config)?void 0:t.toolConfig)?void 0:r.functionCallingConfig)?void 0:n.streamFunctionCallArguments,l=null==(s=null==(i=null==e?void 0:e.config)?void 0:i.automaticFunctionCalling)?void 0:s.disable;if(a&&!l)throw Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(e)},this.generateImages=async e=>await this.generateImagesInternal(e).then(e=>{var t;let r,n=[];if(null==e?void 0:e.generatedImages)for(let i of e.generatedImages)i&&(null==i?void 0:i.safetyAttributes)&&(null==(t=null==i?void 0:i.safetyAttributes)?void 0:t.contentType)==="Positive Prompt"?r=null==i?void 0:i.safetyAttributes:n.push(i);return r?{generatedImages:n,positivePromptSafetyAttributes:r,sdkHttpResponse:e.sdkHttpResponse}:{generatedImages:n,sdkHttpResponse:e.sdkHttpResponse}}),this.list=async e=>{var t;let r={config:Object.assign(Object.assign({},{queryBase:!0}),null==e?void 0:e.config)};if(this.apiClient.isVertexAI()&&!r.config.queryBase)if(null==(t=r.config)?void 0:t.filter)throw Error("Filtering tuned models list for Gemini Enterprise Agent Platform (previously known as Vertex AI) is not currently supported");else r.config.filter="labels.tune-type:*";return new rN(tE.PAGED_ITEM_MODELS,e=>this.listInternal(e),await this.listInternal(r),r)},this.editImage=async e=>{let t={model:e.model,prompt:e.prompt,referenceImages:[],config:e.config};return e.referenceImages&&e.referenceImages&&(t.referenceImages=e.referenceImages.map(e=>e.toReferenceImageAPI())),await this.editImageInternal(t)},this.upscaleImage=async e=>{let t={numberOfImages:1,mode:"upscale"};e.config&&(t=Object.assign(Object.assign({},t),e.config));let r={model:e.model,image:e.image,upscaleFactor:e.upscaleFactor,config:t};return await this.upscaleImageInternal(r)},this.generateVideos=async e=>{var t,r,n,i,s,o;if((e.prompt||e.image||e.video)&&e.source)throw Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return!this.apiClient.isVertexAI()&&((null==(t=e.video)?void 0:t.uri)&&(null==(r=e.video)?void 0:r.videoBytes)?e.video={uri:e.video.uri,mimeType:e.video.mimeType}:(null==(i=null==(n=e.source)?void 0:n.video)?void 0:i.uri)&&(null==(o=null==(s=e.source)?void 0:s.video)?void 0:o.videoBytes)&&(e.source.video={uri:e.source.video.uri,mimeType:e.source.video.mimeType})),await this.generateVideosInternal(e)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&!e.config.responseJsonSchema&&Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema)}async processParamsMaybeAddMcpUsage(e){var t,r,n;let i=null==(t=e.config)?void 0:t.tools;if(!i)return e;let s=await Promise.all(i.map(async e=>nA(e)?await e.tool():e)),o={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:s})};if(o.config.tools=s,e.config&&e.config.tools&&nu(e.config.tools)){let t=Object.assign({},null!=(n=null==(r=e.config.httpOptions)?void 0:r.headers)?n:{});0===Object.keys(t).length&&(t=this.apiClient.getDefaultHeaders()),nc(t),o.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:t})}return o}async initAfcToolsMap(e){var t,r,n;let i=new Map;for(let s of null!=(r=null==(t=e.config)?void 0:t.tools)?r:[])if(nA(s))for(let e of null!=(n=(await s.tool()).functionDeclarations)?n:[]){if(!e.name)throw Error("Function declaration name is required.");if(i.has(e.name))throw Error(`Duplicate tool declaration name: ${e.name}`);i.set(e.name,s)}return i}async processAfcStream(e){var t,r,n;let i=null!=(n=null==(r=null==(t=e.config)?void 0:t.automaticFunctionCalling)?void 0:r.maximumRemoteCalls)?n:10,s=!1,o=0;return function(e,t,r){return rF(this,arguments,function*(){for(;o<i;){s&&(o++,s=!1);let m=yield rG(e.processParamsMaybeAddMcpUsage(r)),g=yield rG(e.generateContentStreamInternal(m)),y=[],_=[];try{for(var n,a,l,u,c,d,h,p=!0,f=(a=void 0,r$(g));!(n=(h=yield rG(f.next())).done);p=!0)if(u=h.value,p=!1,yield yield rG(u),u.candidates&&(null==(c=u.candidates[0])?void 0:c.content)){for(let e of(_.push(u.candidates[0].content),null!=(d=u.candidates[0].content.parts)?d:[]))if(o<i&&e.functionCall){if(!e.functionCall.name)throw Error("Function call name was not returned by the model.");if(t.has(e.functionCall.name)){let r=yield rG(t.get(e.functionCall.name).callTool([e.functionCall]));y.push(...r)}else throw Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${t.keys()}, mising tool: ${e.functionCall.name}`)}}}catch(e){a={error:e}}finally{try{!p&&!n&&(l=f.return)&&(yield rG(l.call(f)))}finally{if(a)throw a.error}}if(y.length>0){s=!0;let e=new tU;e.candidates=[{content:{role:"user",parts:y}}],yield yield rG(e);let t=[];t.push(..._),t.push({role:"user",parts:y});let n=rh(r.contents).concat(t);r.contents=n}else break}})}(this,await this.initAfcToolsMap(e),e)}async generateContentInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=rZ(this.apiClient,e);return s=tR("{model}:generateContent",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=r1(e),r=new tU;return Object.assign(r,t),r})}{let t=rQ(this.apiClient,e);return s=tR("{model}:generateContent",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=r0(e),r=new tU;return Object.assign(r,t),r})}}async generateContentStreamInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=rZ(this.apiClient,e);return s=tR("{model}:streamGenerateContent?alt=sse",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.requestStream({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(function(t){return rF(this,arguments,function*(){var r,n,i,s;try{for(var o,a=!0,l=r$(t);!(r=(o=yield rG(l.next())).done);a=!0){s=o.value,a=!1;let t=r1((yield rG(s.json())),e);t.sdkHttpResponse={headers:s.headers};let r=new tU;Object.assign(r,t),yield yield rG(r)}}catch(e){n={error:e}}finally{try{!a&&!r&&(i=l.return)&&(yield rG(i.call(l)))}finally{if(n)throw n.error}}})})}{let t=rQ(this.apiClient,e);return s=tR("{model}:streamGenerateContent?alt=sse",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.requestStream({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(function(t){return rF(this,arguments,function*(){var r,n,i,s;try{for(var o,a=!0,l=r$(t);!(r=(o=yield rG(l.next())).done);a=!0){s=o.value,a=!1;let t=r0((yield rG(s.json())),e);t.sdkHttpResponse={headers:s.headers};let r=new tU;Object.assign(r,t),yield yield rG(r)}}catch(e){n={error:e}}finally{try{!a&&!r&&(i=l.return)&&(yield rG(i.call(l)))}finally{if(n)throw n.error}}})})}}async embedContentInternal(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let n=function(e,t,r){let n={},i=tk(t,["model"]);null!=i&&tP(n,["_url","model"],t7(e,i));let s=tk(r,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"PREDICT"===s){let r=tk(t,["contents"]);if(null!=r){let t=rd(e,r);Array.isArray(t)&&(t=t.map(e=>e)),tP(n,["instances[]","content"],t)}}let o=tk(r,["embeddingApiType"]);if(void 0===o&&(o="PREDICT"),"EMBED_CONTENT"===o){let e=tk(t,["content"]);null!=e&&tP(n,["content"],rX(rc(e)))}let a=tk(t,["config"]);return null!=a&&function(e,t,r){let n=tk(r,["embeddingApiType"]);if(void 0===n&&(n="PREDICT"),"PREDICT"===n){let r=tk(e,["taskType"]);void 0!==t&&null!=r&&tP(t,["instances[]","task_type"],r)}else if("EMBED_CONTENT"===n){let r=tk(e,["taskType"]);void 0!==t&&null!=r&&tP(t,["embedContentConfig","taskType"],r)}let i=tk(r,["embeddingApiType"]);if(void 0===i&&(i="PREDICT"),"PREDICT"===i){let r=tk(e,["title"]);void 0!==t&&null!=r&&tP(t,["instances[]","title"],r)}else if("EMBED_CONTENT"===i){let r=tk(e,["title"]);void 0!==t&&null!=r&&tP(t,["embedContentConfig","title"],r)}let s=tk(r,["embeddingApiType"]);if(void 0===s&&(s="PREDICT"),"PREDICT"===s){let r=tk(e,["outputDimensionality"]);void 0!==t&&null!=r&&tP(t,["parameters","outputDimensionality"],r)}else if("EMBED_CONTENT"===s){let r=tk(e,["outputDimensionality"]);void 0!==t&&null!=r&&tP(t,["embedContentConfig","outputDimensionality"],r)}let o=tk(r,["embeddingApiType"]);if(void 0===o&&(o="PREDICT"),"PREDICT"===o){let r=tk(e,["mimeType"]);void 0!==t&&null!=r&&tP(t,["instances[]","mimeType"],r)}let a=tk(r,["embeddingApiType"]);if(void 0===a&&(a="PREDICT"),"PREDICT"===a){let r=tk(e,["autoTruncate"]);void 0!==t&&null!=r&&tP(t,["parameters","autoTruncate"],r)}else if("EMBED_CONTENT"===a){let r=tk(e,["autoTruncate"]);void 0!==t&&null!=r&&tP(t,["embedContentConfig","autoTruncate"],r)}let l=tk(r,["embeddingApiType"]);if(void 0===l&&(l="PREDICT"),"EMBED_CONTENT"===l){let r=tk(e,["documentOcr"]);void 0!==t&&null!=r&&tP(t,["embedContentConfig","documentOcr"],r)}let u=tk(r,["embeddingApiType"]);if(void 0===u&&(u="PREDICT"),"EMBED_CONTENT"===u){let r=tk(e,["audioTrackExtraction"]);void 0!==t&&null!=r&&tP(t,["embedContentConfig","audioTrackExtraction"],r)}}(a,n,r),n}(this.apiClient,e,e);return o=tR((s=e.model).includes("gemini")&&"gemini-embedding-001"!==s||s.includes("maas")?"{model}:embedContent":"{model}:predict",n._url),a=n._query,delete n._url,delete n._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(t=>{let r=function(e,t){let r={},n=tk(e,["sdkHttpResponse"]);null!=n&&tP(r,["sdkHttpResponse"],n);let i=tk(e,["predictions[]","embeddings"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=tk(e,["values"]))&&tP(r,["values"],n),null!=(i=tk(e,["statistics"]))&&tP(r,["statistics"],(s={},null!=(o=tk(t=i,["truncated"]))&&tP(s,["truncated"],o),null!=(a=tk(t,["token_count"]))&&tP(s,["tokenCount"],a),s)),r})),tP(r,["embeddings"],e)}let s=tk(e,["metadata"]);if(null!=s&&tP(r,["metadata"],s),t&&"EMBED_CONTENT"===tk(t,["embeddingApiType"])){let t=tk(e,["embedding"]),n=tk(e,["usageMetadata"]),i=tk(e,["truncated"]);if(t){let e={};n&&n.promptTokenCount&&(e.tokenCount=n.promptTokenCount),i&&(e.truncated=i),t.statistics=e,tP(r,["embeddings"],[t])}}return r}(t,e),n=new tM;return Object.assign(n,r),n})}{let t=function(e,t){let r={},n=tk(t,["model"]);null!=n&&tP(r,["_url","model"],t7(e,n));let i=tk(t,["contents"]);if(null!=i){let t=rd(e,i);Array.isArray(t)&&(t=t.map(e=>e)),tP(r,["requests[]","content"],t)}let s=tk(t,["content"]);null!=s&&rY(rc(s));let o=tk(t,["config"]);null!=o&&function(e,t){let r=tk(e,["taskType"]);void 0!==t&&null!=r&&tP(t,["requests[]","taskType"],r);let n=tk(e,["title"]);void 0!==t&&null!=n&&tP(t,["requests[]","title"],n);let i=tk(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&tP(t,["requests[]","outputDimensionality"],i),void 0!==tk(e,["mimeType"]))throw Error("mimeType parameter is not supported in Gemini API.");if(void 0!==tk(e,["autoTruncate"]))throw Error("autoTruncate parameter is not supported in Gemini API.");if(void 0!==tk(e,["documentOcr"]))throw Error("documentOcr parameter is not supported in Gemini API.");if(void 0!==tk(e,["audioTrackExtraction"]))throw Error("audioTrackExtraction parameter is not supported in Gemini API.")}(o,r);let a=tk(t,["model"]);return void 0!==a&&tP(r,["requests[]","model"],t7(e,a)),r}(this.apiClient,e);return o=tR("{model}:batchEmbedContents",t._url),a=t._query,delete t._url,delete t._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["embeddings"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["embeddings"],e)}let i=tk(e,["metadata"]);return null!=i&&tP(t,["metadata"],i),t}(e),r=new tM;return Object.assign(r,t),r})}}async generateImagesInternal(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h,p,f,m,g,y,_,E,A,v,b,w,T,I,S,O=(s=this.apiClient,n={},null!=(i=tk(e,["model"]))&&tP(n,["_url","model"],t7(s,i)),null!=(o=tk(e,["prompt"]))&&tP(n,["instances[0]","prompt"],o),null!=(u=tk(e,["config"]))&&(c=tk(u,["outputGcsUri"]),void 0!==n&&null!=c&&tP(n,["parameters","storageUri"],c),d=tk(u,["negativePrompt"]),void 0!==n&&null!=d&&tP(n,["parameters","negativePrompt"],d),h=tk(u,["numberOfImages"]),void 0!==n&&null!=h&&tP(n,["parameters","sampleCount"],h),p=tk(u,["aspectRatio"]),void 0!==n&&null!=p&&tP(n,["parameters","aspectRatio"],p),f=tk(u,["guidanceScale"]),void 0!==n&&null!=f&&tP(n,["parameters","guidanceScale"],f),m=tk(u,["seed"]),void 0!==n&&null!=m&&tP(n,["parameters","seed"],m),g=tk(u,["safetyFilterLevel"]),void 0!==n&&null!=g&&tP(n,["parameters","safetySetting"],g),y=tk(u,["personGeneration"]),void 0!==n&&null!=y&&tP(n,["parameters","personGeneration"],y),_=tk(u,["includeSafetyAttributes"]),void 0!==n&&null!=_&&tP(n,["parameters","includeSafetyAttributes"],_),E=tk(u,["includeRaiReason"]),void 0!==n&&null!=E&&tP(n,["parameters","includeRaiReason"],E),A=tk(u,["language"]),void 0!==n&&null!=A&&tP(n,["parameters","language"],A),v=tk(u,["outputMimeType"]),void 0!==n&&null!=v&&tP(n,["parameters","outputOptions","mimeType"],v),b=tk(u,["outputCompressionQuality"]),void 0!==n&&null!=b&&tP(n,["parameters","outputOptions","compressionQuality"],b),w=tk(u,["addWatermark"]),void 0!==n&&null!=w&&tP(n,["parameters","addWatermark"],w),T=tk(u,["labels"]),void 0!==n&&null!=T&&tP(n,["labels"],T),I=tk(u,["imageSize"]),void 0!==n&&null!=I&&tP(n,["parameters","sampleImageSize"],I),S=tk(u,["enhancePrompt"]),void 0!==n&&null!=S&&tP(n,["parameters","enhancePrompt"],S)),n);return a=tR("{model}:predict",O._url),l=O._query,delete O._url,delete O._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(O),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>r2(e))),tP(t,["generatedImages"],e)}let i=tk(e,["positivePromptSafetyAttributes"]);return null!=i&&tP(t,["positivePromptSafetyAttributes"],r7(i)),t}(e),r=new tL;return Object.assign(r,t),r})}{let t,r,s,u,c=(o=this.apiClient,t={},null!=(r=tk(e,["model"]))&&tP(t,["_url","model"],t7(o,r)),null!=(s=tk(e,["prompt"]))&&tP(t,["instances[0]","prompt"],s),null!=(u=tk(e,["config"]))&&function(e,t){if(void 0!==tk(e,["outputGcsUri"]))throw Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==tk(e,["negativePrompt"]))throw Error("negativePrompt parameter is not supported in Gemini API.");let r=tk(e,["numberOfImages"]);void 0!==t&&null!=r&&tP(t,["parameters","sampleCount"],r);let n=tk(e,["aspectRatio"]);void 0!==t&&null!=n&&tP(t,["parameters","aspectRatio"],n);let i=tk(e,["guidanceScale"]);if(void 0!==t&&null!=i&&tP(t,["parameters","guidanceScale"],i),void 0!==tk(e,["seed"]))throw Error("seed parameter is not supported in Gemini API.");let s=tk(e,["safetyFilterLevel"]);void 0!==t&&null!=s&&tP(t,["parameters","safetySetting"],s);let o=tk(e,["personGeneration"]);void 0!==t&&null!=o&&tP(t,["parameters","personGeneration"],o);let a=tk(e,["includeSafetyAttributes"]);void 0!==t&&null!=a&&tP(t,["parameters","includeSafetyAttributes"],a);let l=tk(e,["includeRaiReason"]);void 0!==t&&null!=l&&tP(t,["parameters","includeRaiReason"],l);let u=tk(e,["language"]);void 0!==t&&null!=u&&tP(t,["parameters","language"],u);let c=tk(e,["outputMimeType"]);void 0!==t&&null!=c&&tP(t,["parameters","outputOptions","mimeType"],c);let d=tk(e,["outputCompressionQuality"]);if(void 0!==t&&null!=d&&tP(t,["parameters","outputOptions","compressionQuality"],d),void 0!==tk(e,["addWatermark"]))throw Error("addWatermark parameter is not supported in Gemini API.");if(void 0!==tk(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let h=tk(e,["imageSize"]);if(void 0!==t&&null!=h&&tP(t,["parameters","sampleImageSize"],h),void 0!==tk(e,["enhancePrompt"]))throw Error("enhancePrompt parameter is not supported in Gemini API.")}(u,t),t);return a=tR("{model}:predict",c._url),l=c._query,delete c._url,delete c._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t,r;let n,i,s,o,a,l,u;return n={},null!=(i=tk(t=e,["_self"]))&&tP(n,["image"],(s={},null!=(o=tk(r=i,["bytesBase64Encoded"]))&&tP(s,["imageBytes"],tx(o)),null!=(a=tk(r,["mimeType"]))&&tP(s,["mimeType"],a),s)),null!=(l=tk(t,["raiFilteredReason"]))&&tP(n,["raiFilteredReason"],l),null!=(u=tk(t,["_self"]))&&tP(n,["safetyAttributes"],r9(u)),n})),tP(t,["generatedImages"],e)}let i=tk(e,["positivePromptSafetyAttributes"]);return null!=i&&tP(t,["positivePromptSafetyAttributes"],r9(i)),t}(e),r=new tL;return Object.assign(r,t),r})}}async editImageInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s=function(e,t){let r,n,i,s,o,a,l,u,c,d,h,p,f,m,g,y,_,E={},A=tk(t,["model"]);null!=A&&tP(E,["_url","model"],t7(e,A));let v=tk(t,["prompt"]);null!=v&&tP(E,["instances[0]","prompt"],v);let b=tk(t,["referenceImages"]);if(null!=b){let e=b;Array.isArray(e)&&(e=e.map(e=>(function(e){let t,r,n,i,s,o,a,l={},u=tk(e,["referenceImage"]);null!=u&&tP(l,["referenceImage"],r3(u));let c=tk(e,["referenceId"]);null!=c&&tP(l,["referenceId"],c);let d=tk(e,["referenceType"]);null!=d&&tP(l,["referenceType"],d);let h=tk(e,["maskImageConfig"]);null!=h&&tP(l,["maskImageConfig"],(t={},null!=(r=tk(h,["maskMode"]))&&tP(t,["maskMode"],r),null!=(n=tk(h,["segmentationClasses"]))&&tP(t,["maskClasses"],n),null!=(i=tk(h,["maskDilation"]))&&tP(t,["dilation"],i),t));let p=tk(e,["controlImageConfig"]);null!=p&&tP(l,["controlImageConfig"],(s={},null!=(o=tk(p,["controlType"]))&&tP(s,["controlType"],o),null!=(a=tk(p,["enableControlImageComputation"]))&&tP(s,["computeControl"],a),s));let f=tk(e,["styleImageConfig"]);null!=f&&tP(l,["styleImageConfig"],f);let m=tk(e,["subjectImageConfig"]);return null!=m&&tP(l,["subjectImageConfig"],m),l})(e))),tP(E,["instances[0]","referenceImages"],e)}let w=tk(t,["config"]);return null!=w&&(r=tk(w,["outputGcsUri"]),void 0!==E&&null!=r&&tP(E,["parameters","storageUri"],r),n=tk(w,["negativePrompt"]),void 0!==E&&null!=n&&tP(E,["parameters","negativePrompt"],n),i=tk(w,["numberOfImages"]),void 0!==E&&null!=i&&tP(E,["parameters","sampleCount"],i),s=tk(w,["aspectRatio"]),void 0!==E&&null!=s&&tP(E,["parameters","aspectRatio"],s),o=tk(w,["guidanceScale"]),void 0!==E&&null!=o&&tP(E,["parameters","guidanceScale"],o),a=tk(w,["seed"]),void 0!==E&&null!=a&&tP(E,["parameters","seed"],a),l=tk(w,["safetyFilterLevel"]),void 0!==E&&null!=l&&tP(E,["parameters","safetySetting"],l),u=tk(w,["personGeneration"]),void 0!==E&&null!=u&&tP(E,["parameters","personGeneration"],u),c=tk(w,["includeSafetyAttributes"]),void 0!==E&&null!=c&&tP(E,["parameters","includeSafetyAttributes"],c),d=tk(w,["includeRaiReason"]),void 0!==E&&null!=d&&tP(E,["parameters","includeRaiReason"],d),h=tk(w,["language"]),void 0!==E&&null!=h&&tP(E,["parameters","language"],h),p=tk(w,["outputMimeType"]),void 0!==E&&null!=p&&tP(E,["parameters","outputOptions","mimeType"],p),f=tk(w,["outputCompressionQuality"]),void 0!==E&&null!=f&&tP(E,["parameters","outputOptions","compressionQuality"],f),m=tk(w,["addWatermark"]),void 0!==E&&null!=m&&tP(E,["parameters","addWatermark"],m),g=tk(w,["labels"]),void 0!==E&&null!=g&&tP(E,["labels"],g),y=tk(w,["editMode"]),void 0!==E&&null!=y&&tP(E,["parameters","editMode"],y),_=tk(w,["baseSteps"]),void 0!==E&&null!=_&&tP(E,["parameters","editConfig","baseSteps"],_)),E}(this.apiClient,e);return n=tR("{model}:predict",s._url),i=s._query,delete s._url,delete s._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>r2(e))),tP(t,["generatedImages"],e)}return t}(e),r=new tj;return Object.assign(r,t),r})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async upscaleImageInternal(e){var t,r,n;let i="",s={};if(this.apiClient.isVertexAI()){let o,a,l,u,c,d,h,p,f,m,g,y,_,E,A,v,b=(n=this.apiClient,o={},null!=(a=tk(e,["model"]))&&tP(o,["_url","model"],t7(n,a)),null!=(l=tk(e,["image"]))&&tP(o,["instances[0]","image"],r3(l)),null!=(u=tk(e,["upscaleFactor"]))&&tP(o,["parameters","upscaleConfig","upscaleFactor"],u),null!=(c=tk(e,["config"]))&&(d=tk(c,["outputGcsUri"]),void 0!==o&&null!=d&&tP(o,["parameters","storageUri"],d),h=tk(c,["safetyFilterLevel"]),void 0!==o&&null!=h&&tP(o,["parameters","safetySetting"],h),p=tk(c,["personGeneration"]),void 0!==o&&null!=p&&tP(o,["parameters","personGeneration"],p),f=tk(c,["includeRaiReason"]),void 0!==o&&null!=f&&tP(o,["parameters","includeRaiReason"],f),m=tk(c,["outputMimeType"]),void 0!==o&&null!=m&&tP(o,["parameters","outputOptions","mimeType"],m),g=tk(c,["outputCompressionQuality"]),void 0!==o&&null!=g&&tP(o,["parameters","outputOptions","compressionQuality"],g),y=tk(c,["enhanceInputImage"]),void 0!==o&&null!=y&&tP(o,["parameters","upscaleConfig","enhanceInputImage"],y),_=tk(c,["imagePreservationFactor"]),void 0!==o&&null!=_&&tP(o,["parameters","upscaleConfig","imagePreservationFactor"],_),E=tk(c,["labels"]),void 0!==o&&null!=E&&tP(o,["labels"],E),A=tk(c,["numberOfImages"]),void 0!==o&&null!=A&&tP(o,["parameters","sampleCount"],A),v=tk(c,["mode"]),void 0!==o&&null!=v&&tP(o,["parameters","mode"],v)),o);return i=tR("{model}:predict",b._url),s=b._query,delete b._url,delete b._query,this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>r2(e))),tP(t,["generatedImages"],e)}return t}(e),r=new tG;return Object.assign(r,t),r})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async recontextImage(e){var t,r,n;let i="",s={};if(this.apiClient.isVertexAI()){let o,a,l,u,c,d,h,p,f,m,g,y,_,E,A,v=(n=this.apiClient,o={},null!=(a=tk(e,["model"]))&&tP(o,["_url","model"],t7(n,a)),null!=(l=tk(e,["source"]))&&function(e,t){let r=tk(e,["prompt"]);void 0!==t&&null!=r&&tP(t,["instances[0]","prompt"],r);let n=tk(e,["personImage"]);void 0!==t&&null!=n&&tP(t,["instances[0]","personImage","image"],r3(n));let i=tk(e,["productImages"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>{let t,r;return t={},null!=(r=tk(e,["productImage"]))&&tP(t,["image"],r3(r)),t})),tP(t,["instances[0]","productImages"],e)}}(l,o),null!=(u=tk(e,["config"]))&&(c=tk(u,["numberOfImages"]),void 0!==o&&null!=c&&tP(o,["parameters","sampleCount"],c),d=tk(u,["baseSteps"]),void 0!==o&&null!=d&&tP(o,["parameters","baseSteps"],d),h=tk(u,["outputGcsUri"]),void 0!==o&&null!=h&&tP(o,["parameters","storageUri"],h),p=tk(u,["seed"]),void 0!==o&&null!=p&&tP(o,["parameters","seed"],p),f=tk(u,["safetyFilterLevel"]),void 0!==o&&null!=f&&tP(o,["parameters","safetySetting"],f),m=tk(u,["personGeneration"]),void 0!==o&&null!=m&&tP(o,["parameters","personGeneration"],m),g=tk(u,["addWatermark"]),void 0!==o&&null!=g&&tP(o,["parameters","addWatermark"],g),y=tk(u,["outputMimeType"]),void 0!==o&&null!=y&&tP(o,["parameters","outputOptions","mimeType"],y),_=tk(u,["outputCompressionQuality"]),void 0!==o&&null!=_&&tP(o,["parameters","outputOptions","compressionQuality"],_),E=tk(u,["enhancePrompt"]),void 0!==o&&null!=E&&tP(o,["parameters","enhancePrompt"],E),A=tk(u,["labels"]),void 0!==o&&null!=A&&tP(o,["labels"],A)),o);return i=tR("{model}:predict",v._url),s=v._query,delete v._url,delete v._query,this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(v),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=tk(e,["predictions"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>r2(e))),tP(t,["generatedImages"],e)}return t}(e),r=new tF;return Object.assign(r,t),r})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async segmentImage(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let l,u,c,d,h,p,f,m,g,y,_,E,A,v,b,w=(n=this.apiClient,p={},null!=(f=tk(e,["model"]))&&tP(p,["_url","model"],t7(n,f)),null!=(m=tk(e,["source"]))&&(i=m,s=p,c=tk(i,["prompt"]),void 0!==s&&null!=c&&tP(s,["instances[0]","prompt"],c),d=tk(i,["image"]),void 0!==s&&null!=d&&tP(s,["instances[0]","image"],r3(d)),h=tk(i,["scribbleImage"]),void 0!==s&&null!=h&&tP(s,["instances[0]","scribble"],(l={},null!=(u=tk(h,["image"]))&&tP(l,["image"],r3(u)),l))),null!=(g=tk(e,["config"]))&&(y=tk(g,["mode"]),void 0!==p&&null!=y&&tP(p,["parameters","mode"],y),_=tk(g,["maxPredictions"]),void 0!==p&&null!=_&&tP(p,["parameters","maxPredictions"],_),E=tk(g,["confidenceThreshold"]),void 0!==p&&null!=E&&tP(p,["parameters","confidenceThreshold"],E),A=tk(g,["maskDilation"]),void 0!==p&&null!=A&&tP(p,["parameters","maskDilation"],A),v=tk(g,["binaryColorThreshold"]),void 0!==p&&null!=v&&tP(p,["parameters","binaryColorThreshold"],v),b=tk(g,["labels"]),void 0!==p&&null!=b&&tP(p,["labels"],b)),p);return o=tR("{model}:predict",w._url),a=w._query,delete w._url,delete w._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(w),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=tk(e,["predictions"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["_self"]);null!=r&&tP(t,["mask"],r4(r));let n=tk(e,["labels"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["labels"],e)}return t})(e))),tP(t,["generatedMasks"],e)}return t}(e),r=new t$;return Object.assign(r,t),r})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=tk(e,["model"]))&&tP(n,["_url","name"],t7(s,i)),n);return a=tR("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>r8(e))}{let t,r,s=(o=this.apiClient,t={},null!=(r=tk(e,["model"]))&&tP(t,["_url","name"],t7(o,r)),t);return a=tR("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>r5(e))}}async listInternal(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h=(s=this.apiClient,n={},null!=(i=tk(e,["config"]))&&(o=tk(i,["pageSize"]),void 0!==n&&null!=o&&tP(n,["_query","pageSize"],o),u=tk(i,["pageToken"]),void 0!==n&&null!=u&&tP(n,["_query","pageToken"],u),c=tk(i,["filter"]),void 0!==n&&null!=c&&tP(n,["_query","filter"],c),d=tk(i,["queryBase"]),void 0!==n&&null!=d&&tP(n,["_url","models_url"],rw(s,d))),n);return a=tR("{models_url}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["_self"]);if(null!=i){let e=rT(i);Array.isArray(e)&&(e=e.map(e=>r8(e))),tP(t,["models"],e)}return t}(e),r=new tq;return Object.assign(r,t),r})}{let t,r,s,u,c,d,h=(o=this.apiClient,t={},null!=(r=tk(e,["config"]))&&(s=tk(r,["pageSize"]),void 0!==t&&null!=s&&tP(t,["_query","pageSize"],s),u=tk(r,["pageToken"]),void 0!==t&&null!=u&&tP(t,["_query","pageToken"],u),c=tk(r,["filter"]),void 0!==t&&null!=c&&tP(t,["_query","filter"],c),d=tk(r,["queryBase"]),void 0!==t&&null!=d&&tP(t,["_url","models_url"],rw(o,d))),t);return a=tR("{models_url}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["_self"]);if(null!=i){let e=rT(i);Array.isArray(e)&&(e=e.map(e=>r5(e))),tP(t,["models"],e)}return t}(e),r=new tq;return Object.assign(r,t),r})}}async update(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h=(s=this.apiClient,n={},null!=(i=tk(e,["model"]))&&tP(n,["_url","model"],t7(s,i)),null!=(o=tk(e,["config"]))&&(u=tk(o,["displayName"]),void 0!==n&&null!=u&&tP(n,["displayName"],u),c=tk(o,["description"]),void 0!==n&&null!=c&&tP(n,["description"],c),d=tk(o,["defaultCheckpointId"]),void 0!==n&&null!=d&&tP(n,["defaultCheckpointId"],d)),n);return a=tR("{model}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"PATCH",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>r8(e))}{let t,r,s,u,c,d,h=(o=this.apiClient,t={},null!=(r=tk(e,["model"]))&&tP(t,["_url","name"],t7(o,r)),null!=(s=tk(e,["config"]))&&(u=tk(s,["displayName"]),void 0!==t&&null!=u&&tP(t,["displayName"],u),c=tk(s,["description"]),void 0!==t&&null!=c&&tP(t,["description"],c),d=tk(s,["defaultCheckpointId"]),void 0!==t&&null!=d&&tP(t,["defaultCheckpointId"],d)),t);return a=tR("{name}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"PATCH",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>r5(e))}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=tk(e,["model"]))&&tP(n,["_url","name"],t7(s,i)),n);return a=tR("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tB;return Object.assign(i,n),i})}{let t,r,s=(o=this.apiClient,t={},null!=(r=tk(e,["model"]))&&tP(t,["_url","name"],t7(o,r)),t);return a=tR("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tB;return Object.assign(i,n),i})}}async countTokens(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=function(e,t){let r={},n=tk(t,["model"]);null!=n&&tP(r,["_url","model"],t7(e,n));let i=tk(t,["contents"]);if(null!=i){let e=rh(i);Array.isArray(e)&&(e=e.map(e=>rX(e))),tP(r,["contents"],e)}let s=tk(t,["config"]);return null!=s&&function(e,t){let r=tk(e,["systemInstruction"]);void 0!==t&&null!=r&&tP(t,["systemInstruction"],rX(rc(r)));let n=tk(e,["tools"]);if(void 0!==t&&null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>ne(e))),tP(t,["tools"],e)}let i=tk(e,["generationConfig"]);void 0!==t&&null!=i&&tP(t,["generationConfig"],function(e){let t={},r=tk(e,["modelSelectionConfig"]);null!=r&&tP(t,["modelConfig"],r);let n=tk(e,["responseJsonSchema"]);null!=n&&tP(t,["responseJsonSchema"],n);let i=tk(e,["audioTimestamp"]);null!=i&&tP(t,["audioTimestamp"],i);let s=tk(e,["candidateCount"]);null!=s&&tP(t,["candidateCount"],s);let o=tk(e,["enableAffectiveDialog"]);null!=o&&tP(t,["enableAffectiveDialog"],o);let a=tk(e,["frequencyPenalty"]);null!=a&&tP(t,["frequencyPenalty"],a);let l=tk(e,["logprobs"]);null!=l&&tP(t,["logprobs"],l);let u=tk(e,["maxOutputTokens"]);null!=u&&tP(t,["maxOutputTokens"],u);let c=tk(e,["mediaResolution"]);null!=c&&tP(t,["mediaResolution"],c);let d=tk(e,["presencePenalty"]);null!=d&&tP(t,["presencePenalty"],d);let h=tk(e,["responseLogprobs"]);null!=h&&tP(t,["responseLogprobs"],h);let p=tk(e,["responseMimeType"]);null!=p&&tP(t,["responseMimeType"],p);let f=tk(e,["responseModalities"]);null!=f&&tP(t,["responseModalities"],f);let m=tk(e,["responseSchema"]);null!=m&&tP(t,["responseSchema"],m);let g=tk(e,["routingConfig"]);null!=g&&tP(t,["routingConfig"],g);let y=tk(e,["seed"]);null!=y&&tP(t,["seed"],y);let _=tk(e,["speechConfig"]);null!=_&&tP(t,["speechConfig"],_);let E=tk(e,["stopSequences"]);null!=E&&tP(t,["stopSequences"],E);let A=tk(e,["temperature"]);null!=A&&tP(t,["temperature"],A);let v=tk(e,["thinkingConfig"]);null!=v&&tP(t,["thinkingConfig"],v);let b=tk(e,["topK"]);null!=b&&tP(t,["topK"],b);let w=tk(e,["topP"]);if(null!=w&&tP(t,["topP"],w),void 0!==tk(e,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");return t}(i))}(s,r),r}(this.apiClient,e);return s=tR("{model}:countTokens",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),null!=(n=tk(e,["totalTokens"]))&&tP(t,["totalTokens"],n),t),s=new tH;return Object.assign(s,i),s})}{let t=function(e,t){let r={},n=tk(t,["model"]);null!=n&&tP(r,["_url","model"],t7(e,n));let i=tk(t,["contents"]);if(null!=i){let e=rh(i);Array.isArray(e)&&(e=e.map(e=>rY(e))),tP(r,["contents"],e)}let s=tk(t,["config"]);return null!=s&&function(e){if(void 0!==tk(e,["systemInstruction"]))throw Error("systemInstruction parameter is not supported in Gemini API.");if(void 0!==tk(e,["tools"]))throw Error("tools parameter is not supported in Gemini API.");if(void 0!==tk(e,["generationConfig"]))throw Error("generationConfig parameter is not supported in Gemini API.")}(s),r}(this.apiClient,e);return s=tR("{model}:countTokens",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),null!=(n=tk(e,["totalTokens"]))&&tP(t,["totalTokens"],n),null!=(i=tk(e,["cachedContentTokenCount"]))&&tP(t,["cachedContentTokenCount"],i),t),o=new tH;return Object.assign(o,s),o})}}async computeTokens(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s=function(e,t){let r={},n=tk(t,["model"]);null!=n&&tP(r,["_url","model"],t7(e,n));let i=tk(t,["contents"]);if(null!=i){let e=rh(i);Array.isArray(e)&&(e=e.map(e=>rX(e))),tP(r,["contents"],e)}return r}(this.apiClient,e);return n=tR("{model}:computeTokens",s._url),i=s._query,delete s._url,delete s._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["tokensInfo"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["tokensInfo"],e)}return t}(e),r=new tV;return Object.assign(r,t),r})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async generateVideosInternal(e){var t,r,n,i,s,o,a,l,u,c;let d="",h={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,p,f,m,g,y,_=(s=this.apiClient,u={},null!=(c=tk(e,["model"]))&&tP(u,["_url","model"],t7(s,c)),null!=(p=tk(e,["prompt"]))&&tP(u,["instances[0]","prompt"],p),null!=(f=tk(e,["image"]))&&tP(u,["instances[0]","image"],r3(f)),null!=(m=tk(e,["video"]))&&tP(u,["instances[0]","video"],nr(m)),null!=(g=tk(e,["source"]))&&(a=g,l=u,n=tk(a,["prompt"]),void 0!==l&&null!=n&&tP(l,["instances[0]","prompt"],n),i=tk(a,["image"]),void 0!==l&&null!=i&&tP(l,["instances[0]","image"],r3(i)),o=tk(a,["video"]),void 0!==l&&null!=o&&tP(l,["instances[0]","video"],nr(o))),null!=(y=tk(e,["config"]))&&function(e,t){var r;let n,i,s,o=tk(e,["numberOfVideos"]);void 0!==t&&null!=o&&tP(t,["parameters","sampleCount"],o);let a=tk(e,["outputGcsUri"]);void 0!==t&&null!=a&&tP(t,["parameters","storageUri"],a);let l=tk(e,["fps"]);void 0!==t&&null!=l&&tP(t,["parameters","fps"],l);let u=tk(e,["durationSeconds"]);void 0!==t&&null!=u&&tP(t,["parameters","durationSeconds"],u);let c=tk(e,["seed"]);void 0!==t&&null!=c&&tP(t,["parameters","seed"],c);let d=tk(e,["aspectRatio"]);void 0!==t&&null!=d&&tP(t,["parameters","aspectRatio"],d);let h=tk(e,["resolution"]);void 0!==t&&null!=h&&tP(t,["parameters","resolution"],h);let p=tk(e,["personGeneration"]);void 0!==t&&null!=p&&tP(t,["parameters","personGeneration"],p);let f=tk(e,["pubsubTopic"]);void 0!==t&&null!=f&&tP(t,["parameters","pubsubTopic"],f);let m=tk(e,["negativePrompt"]);void 0!==t&&null!=m&&tP(t,["parameters","negativePrompt"],m);let g=tk(e,["enhancePrompt"]);void 0!==t&&null!=g&&tP(t,["parameters","enhancePrompt"],g);let y=tk(e,["generateAudio"]);void 0!==t&&null!=y&&tP(t,["parameters","generateAudio"],y);let _=tk(e,["lastFrame"]);void 0!==t&&null!=_&&tP(t,["instances[0]","lastFrame"],r3(_));let E=tk(e,["referenceImages"]);if(void 0!==t&&null!=E){let e=E;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=tk(t=e,["image"]))&&tP(r,["image"],r3(n)),null!=(i=tk(t,["referenceType"]))&&tP(r,["referenceType"],i),r})),tP(t,["instances[0]","referenceImages"],e)}let A=tk(e,["mask"]);void 0!==t&&null!=A&&tP(t,["instances[0]","mask"],(n={},null!=(i=tk(r=A,["image"]))&&tP(n,["_self"],r3(i)),null!=(s=tk(r,["maskMode"]))&&tP(n,["maskMode"],s),n));let v=tk(e,["compressionQuality"]);void 0!==t&&null!=v&&tP(t,["parameters","compressionQuality"],v);let b=tk(e,["labels"]);if(void 0!==t&&null!=b&&tP(t,["labels"],b),void 0!==tk(e,["webhookConfig"]))throw Error("webhookConfig parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).");let w=tk(e,["resizeMode"]);void 0!==t&&null!=w&&tP(t,["parameters","resizeMode"],w)}(y,u),u);return d=tR("{model}:predictLongRunning",_._url),h=_._query,delete _._url,delete _._query,this.apiClient.request({path:d,queryParams:h,body:JSON.stringify(_),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n,i,s,o,a=(t={},null!=(r=tk(e,["name"]))&&tP(t,["name"],r),null!=(n=tk(e,["metadata"]))&&tP(t,["metadata"],n),null!=(i=tk(e,["done"]))&&tP(t,["done"],i),null!=(s=tk(e,["error"]))&&tP(t,["error"],s),null!=(o=tk(e,["response"]))&&tP(t,["response"],function(e){let t={},r=tk(e,["videos"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=tk(e,["_self"]))&&tP(r,["video"],(i={},null!=(s=tk(t=n,["gcsUri"]))&&tP(i,["uri"],s),null!=(o=tk(t,["bytesBase64Encoded"]))&&tP(i,["videoBytes"],tx(o)),null!=(a=tk(t,["mimeType"]))&&tP(i,["mimeType"],a),i)),r})),tP(t,["generatedVideos"],e)}let n=tk(e,["raiMediaFilteredCount"]);null!=n&&tP(t,["raiMediaFilteredCount"],n);let i=tk(e,["raiMediaFilteredReasons"]);return null!=i&&tP(t,["raiMediaFilteredReasons"],i),t}(o)),t),l=new tK;return Object.assign(l,a),l})}{let t,r,s,a,l,p,f,m,g,y,_=(o=this.apiClient,a={},null!=(l=tk(e,["model"]))&&tP(a,["_url","model"],t7(o,l)),null!=(p=tk(e,["prompt"]))&&tP(a,["instances[0]","prompt"],p),null!=(f=tk(e,["image"]))&&tP(a,["instances[0]","image"],r6(f)),null!=(m=tk(e,["video"]))&&tP(a,["instances[0]","video"],nt(m)),null!=(g=tk(e,["source"]))&&(u=g,c=a,t=tk(u,["prompt"]),void 0!==c&&null!=t&&tP(c,["instances[0]","prompt"],t),r=tk(u,["image"]),void 0!==c&&null!=r&&tP(c,["instances[0]","image"],r6(r)),s=tk(u,["video"]),void 0!==c&&null!=s&&tP(c,["instances[0]","video"],nt(s))),null!=(y=tk(e,["config"]))&&function(e,t){let r=tk(e,["numberOfVideos"]);if(void 0!==t&&null!=r&&tP(t,["parameters","sampleCount"],r),void 0!==tk(e,["outputGcsUri"]))throw Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==tk(e,["fps"]))throw Error("fps parameter is not supported in Gemini API.");let n=tk(e,["durationSeconds"]);if(void 0!==t&&null!=n&&tP(t,["parameters","durationSeconds"],n),void 0!==tk(e,["seed"]))throw Error("seed parameter is not supported in Gemini API.");let i=tk(e,["aspectRatio"]);void 0!==t&&null!=i&&tP(t,["parameters","aspectRatio"],i);let s=tk(e,["resolution"]);void 0!==t&&null!=s&&tP(t,["parameters","resolution"],s);let o=tk(e,["personGeneration"]);if(void 0!==t&&null!=o&&tP(t,["parameters","personGeneration"],o),void 0!==tk(e,["pubsubTopic"]))throw Error("pubsubTopic parameter is not supported in Gemini API.");let a=tk(e,["negativePrompt"]);void 0!==t&&null!=a&&tP(t,["parameters","negativePrompt"],a);let l=tk(e,["enhancePrompt"]);if(void 0!==t&&null!=l&&tP(t,["parameters","enhancePrompt"],l),void 0!==tk(e,["generateAudio"]))throw Error("generateAudio parameter is not supported in Gemini API.");let u=tk(e,["lastFrame"]);void 0!==t&&null!=u&&tP(t,["instances[0]","lastFrame"],r6(u));let c=tk(e,["referenceImages"]);if(void 0!==t&&null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=tk(t=e,["image"]))&&tP(r,["image"],r6(n)),null!=(i=tk(t,["referenceType"]))&&tP(r,["referenceType"],i),r})),tP(t,["instances[0]","referenceImages"],e)}if(void 0!==tk(e,["mask"]))throw Error("mask parameter is not supported in Gemini API.");if(void 0!==tk(e,["compressionQuality"]))throw Error("compressionQuality parameter is not supported in Gemini API.");if(void 0!==tk(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let d=tk(e,["webhookConfig"]);if(void 0!==t&&null!=d&&tP(t,["webhookConfig"],d),void 0!==tk(e,["resizeMode"]))throw Error("resizeMode parameter is not supported in Gemini API.")}(y,a),a);return d=tR("{model}:predictLongRunning",_._url),h=_._query,delete _._url,delete _._query,this.apiClient.request({path:d,queryParams:h,body:JSON.stringify(_),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n,i,s,o,a=(t={},null!=(r=tk(e,["name"]))&&tP(t,["name"],r),null!=(n=tk(e,["metadata"]))&&tP(t,["metadata"],n),null!=(i=tk(e,["done"]))&&tP(t,["done"],i),null!=(s=tk(e,["error"]))&&tP(t,["error"],s),null!=(o=tk(e,["response","generateVideoResponse"]))&&tP(t,["response"],function(e){let t={},r=tk(e,["generatedSamples"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=tk(e,["video"]))&&tP(r,["video"],(i={},null!=(s=tk(t=n,["uri"]))&&tP(i,["uri"],s),null!=(o=tk(t,["encodedVideo"]))&&tP(i,["videoBytes"],tx(o)),null!=(a=tk(t,["encoding"]))&&tP(i,["mimeType"],a),i)),r})),tP(t,["generatedVideos"],e)}let n=tk(e,["raiMediaFilteredCount"]);null!=n&&tP(t,["raiMediaFilteredCount"],n);let i=tk(e,["raiMediaFilteredReasons"]);return null!=i&&tP(t,["raiMediaFilteredReasons"],i),t}(o)),t),l=new tK;return Object.assign(l,a),l})}}}class nT extends tC{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,r=e.config;if(void 0===t.name||""===t.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let e,n=t.name.split("/operations/")[0];r&&"httpOptions"in r&&(e=r.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:n,config:{httpOptions:e}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{let e=await this.getVideosOperationInternal({operationName:t.name,config:r});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async get(e){let t=e.operation,r=e.config;if(void 0===t.name||""===t.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let e,n=t.name.split("/operations/")[0];r&&"httpOptions"in r&&(e=r.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:n,config:{httpOptions:e}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{let e=await this.getVideosOperationInternal({operationName:t.name,config:r});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=tk(e,["operationName"]))&&tP(n,["_url","operationName"],i),n);return s=tR("{operationName}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json())}{let t,r,a=(t={},null!=(r=tk(e,["operationName"]))&&tP(t,["_url","operationName"],r),t);return s=tR("{operationName}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json())}}async fetchPredictVideosOperationInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l=(s={},null!=(o=tk(e,["operationName"]))&&tP(s,["operationName"],o),null!=(a=tk(e,["resourceName"]))&&tP(s,["_url","resourceName"],a),s);return n=tR("{resourceName}:fetchPredictOperation",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json())}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}}function nI(e){if(void 0!==tk(e,["languageCodes"]))throw Error("languageCodes parameter is not supported in Gemini API.");return{}}class nS extends tC{constructor(e){super(),this.apiClient=e}async create(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI())throw Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let l,u,c,d,h,p,f,m,g,y,_=(n=this.apiClient,d={},null!=(h=tk(e,["config"]))&&tP(d,["config"],(p=tk(h,["expireTime"]),void 0!==d&&null!=p&&tP(d,["expireTime"],p),f=tk(h,["newSessionExpireTime"]),void 0!==d&&null!=f&&tP(d,["newSessionExpireTime"],f),m=tk(h,["uses"]),void 0!==d&&null!=m&&tP(d,["uses"],m),g=tk(h,["liveConnectConstraints"]),void 0!==d&&null!=g&&tP(d,["bidiGenerateContentSetup"],(i=n,l={},null!=(u=tk(s=g,["model"]))&&tP(l,["setup","model"],t7(i,u)),null!=(c=tk(s,["config"]))&&tP(l,["config"],function(e,t){let r=tk(e,["generationConfig"]);void 0!==t&&null!=r&&tP(t,["setup","generationConfig"],r);let n=tk(e,["responseModalities"]);void 0!==t&&null!=n&&tP(t,["setup","generationConfig","responseModalities"],n);let i=tk(e,["temperature"]);void 0!==t&&null!=i&&tP(t,["setup","generationConfig","temperature"],i);let s=tk(e,["topP"]);void 0!==t&&null!=s&&tP(t,["setup","generationConfig","topP"],s);let o=tk(e,["topK"]);void 0!==t&&null!=o&&tP(t,["setup","generationConfig","topK"],o);let a=tk(e,["maxOutputTokens"]);void 0!==t&&null!=a&&tP(t,["setup","generationConfig","maxOutputTokens"],a);let l=tk(e,["mediaResolution"]);void 0!==t&&null!=l&&tP(t,["setup","generationConfig","mediaResolution"],l);let u=tk(e,["seed"]);void 0!==t&&null!=u&&tP(t,["setup","generationConfig","seed"],u);let c=tk(e,["speechConfig"]);void 0!==t&&null!=c&&tP(t,["setup","generationConfig","speechConfig"],rm(c));let d=tk(e,["thinkingConfig"]);void 0!==t&&null!=d&&tP(t,["setup","generationConfig","thinkingConfig"],d);let h=tk(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&tP(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=tk(e,["systemInstruction"]);void 0!==t&&null!=p&&tP(t,["setup","systemInstruction"],function(e){let t={},r=tk(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p,f,m,g;return r={},null!=(n=tk(t=e,["mediaResolution"]))&&tP(r,["mediaResolution"],n),null!=(i=tk(t,["codeExecutionResult"]))&&tP(r,["codeExecutionResult"],i),null!=(s=tk(t,["executableCode"]))&&tP(r,["executableCode"],s),null!=(o=tk(t,["fileData"]))&&tP(r,["fileData"],function(e){let t={};if(void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=tk(e,["fileUri"]);null!=r&&tP(t,["fileUri"],r);let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(o)),null!=(a=tk(t,["functionCall"]))&&tP(r,["functionCall"],function(e){let t={},r=tk(e,["id"]);null!=r&&tP(t,["id"],r);let n=tk(e,["args"]);null!=n&&tP(t,["args"],n);let i=tk(e,["name"]);if(null!=i&&tP(t,["name"],i),void 0!==tk(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==tk(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=tk(t,["functionResponse"]))&&tP(r,["functionResponse"],l),null!=(u=tk(t,["inlineData"]))&&tP(r,["inlineData"],function(e){let t={},r=tk(e,["data"]);if(null!=r&&tP(t,["data"],r),void 0!==tk(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=tk(e,["mimeType"]);return null!=n&&tP(t,["mimeType"],n),t}(u)),null!=(c=tk(t,["text"]))&&tP(r,["text"],c),null!=(d=tk(t,["thought"]))&&tP(r,["thought"],d),null!=(h=tk(t,["thoughtSignature"]))&&tP(r,["thoughtSignature"],h),null!=(p=tk(t,["videoMetadata"]))&&tP(r,["videoMetadata"],p),null!=(f=tk(t,["toolCall"]))&&tP(r,["toolCall"],f),null!=(m=tk(t,["toolResponse"]))&&tP(r,["toolResponse"],m),null!=(g=tk(t,["partMetadata"]))&&tP(r,["partMetadata"],g),r})),tP(t,["parts"],e)}let n=tk(e,["role"]);return null!=n&&tP(t,["role"],n),t}(rc(p)));let f=tk(e,["tools"]);if(void 0!==t&&null!=f){let e=ry(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t,r,n,i={};if(void 0!==tk(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let s=tk(e,["computerUse"]);null!=s&&tP(i,["computerUse"],s);let o=tk(e,["fileSearch"]);null!=o&&tP(i,["fileSearch"],o);let a=tk(e,["googleSearch"]);null!=a&&tP(i,["googleSearch"],function(e){let t={},r=tk(e,["searchTypes"]);if(null!=r&&tP(t,["searchTypes"],r),void 0!==tk(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");if(void 0!==tk(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");let n=tk(e,["timeRangeFilter"]);return null!=n&&tP(t,["timeRangeFilter"],n),t}(a));let l=tk(e,["googleMaps"]);null!=l&&tP(i,["googleMaps"],(t={},null!=(r=tk(l,["authConfig"]))&&tP(t,["authConfig"],function(e){let t={},r=tk(e,["apiKey"]);if(null!=r&&tP(t,["apiKey"],r),void 0!==tk(e,["apiKeyConfig"]))throw Error("apiKeyConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["authType"]))throw Error("authType parameter is not supported in Gemini API.");if(void 0!==tk(e,["googleServiceAccountConfig"]))throw Error("googleServiceAccountConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["httpBasicAuthConfig"]))throw Error("httpBasicAuthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oauthConfig"]))throw Error("oauthConfig parameter is not supported in Gemini API.");if(void 0!==tk(e,["oidcConfig"]))throw Error("oidcConfig parameter is not supported in Gemini API.");return t}(r)),null!=(n=tk(l,["enableWidget"]))&&tP(t,["enableWidget"],n),t));let u=tk(e,["codeExecution"]);if(null!=u&&tP(i,["codeExecution"],u),void 0!==tk(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let c=tk(e,["functionDeclarations"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["functionDeclarations"],e)}let d=tk(e,["googleSearchRetrieval"]);if(null!=d&&tP(i,["googleSearchRetrieval"],d),void 0!==tk(e,["parallelAiSearch"]))throw Error("parallelAiSearch parameter is not supported in Gemini API.");let h=tk(e,["urlContext"]);null!=h&&tP(i,["urlContext"],h);let p=tk(e,["mcpServers"]);if(null!=p){let e=p;Array.isArray(e)&&(e=e.map(e=>e)),tP(i,["mcpServers"],e)}return i})(rg(e)))),tP(t,["setup","tools"],e)}let m=tk(e,["sessionResumption"]);void 0!==t&&null!=m&&tP(t,["setup","sessionResumption"],function(e){let t={},r=tk(e,["handle"]);if(null!=r&&tP(t,["handle"],r),void 0!==tk(e,["transparent"]))throw Error("transparent parameter is not supported in Gemini API.");return t}(m));let g=tk(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&tP(t,["setup","inputAudioTranscription"],nI(g));let y=tk(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&tP(t,["setup","outputAudioTranscription"],nI(y));let _=tk(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&tP(t,["setup","realtimeInputConfig"],_);let E=tk(e,["contextWindowCompression"]);void 0!==t&&null!=E&&tP(t,["setup","contextWindowCompression"],E);let A=tk(e,["proactivity"]);if(void 0!==t&&null!=A&&tP(t,["setup","proactivity"],A),void 0!==tk(e,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is not supported in Gemini API.");let v=tk(e,["avatarConfig"]);void 0!==t&&null!=v&&tP(t,["setup","avatarConfig"],v);let b=tk(e,["safetySettings"]);if(void 0!==t&&null!=b){let e=b;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=tk(e,["category"]);if(null!=r&&tP(t,["category"],r),void 0!==tk(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=tk(e,["threshold"]);return null!=n&&tP(t,["threshold"],n),t})(e))),tP(t,["setup","safetySettings"],e)}return{}}(c,l)),l)),y=tk(h,["lockAdditionalFields"]),void 0!==d&&null!=y&&tP(d,["fieldMask"],y),{})),d);o=tR("auth_tokens",_._url),a=_._query,delete _.config,delete _._url,delete _._query;let E=function(e,t){let r=null,n=e.bidiGenerateContentSetup;if("object"==typeof n&&null!==n&&"setup"in n){let t=n.setup;"object"==typeof t&&null!==t?(e.bidiGenerateContentSetup=t,r=t):delete e.bidiGenerateContentSetup}else void 0!==n&&delete e.bidiGenerateContentSetup;let i=e.fieldMask;if(r){let n=function(e){let t=[];for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if("object"==typeof n&&null!=n&&Object.keys(n).length>0){let e=Object.keys(n).map(e=>`${r}.${e}`);t.push(...e)}else t.push(r)}return t.join(",")}(r);if(Array.isArray(null==t?void 0:t.lockAdditionalFields)&&(null==t?void 0:t.lockAdditionalFields.length)===0)n?e.fieldMask=n:delete e.fieldMask;else if((null==t?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&null!==i&&Array.isArray(i)&&i.length>0){let t=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],r=[];i.length>0&&(r=i.map(e=>t.includes(e)?`generationConfig.${e}`:e));let s=[];n&&s.push(n),r.length>0&&s.push(...r),s.length>0?e.fieldMask=s.join(","):delete e.fieldMask}else delete e.fieldMask}else null!==i&&Array.isArray(i)&&i.length>0?e.fieldMask=i.join(","):delete e.fieldMask;return e}(_,e.config);return this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(E),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}}class nO extends tC{constructor(e){super(),this.apiClient=e,this.list=async e=>new rN(tE.PAGED_ITEM_DOCUMENTS,t=>this.listInternal({parent:e.parent,config:t.config}),await this.listInternal(e),e)}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=tk(e,["name"]))&&tP(s,["_url","name"],o),s);return n=tR("{name}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=tk(e,["name"]))&&tP(s,["_url","name"],o),null!=(a=tk(e,["config"]))&&(l=tk(a,["force"]),void 0!==s&&null!=l&&tP(s,["_query","force"],l)),s);n=tR("{name}",u._url),i=u._query,delete u._url,delete u._query,await this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u,c=(s={},null!=(o=tk(e,["parent"]))&&tP(s,["_url","parent"],o),null!=(a=tk(e,["config"]))&&(l=tk(a,["pageSize"]),void 0!==s&&null!=l&&tP(s,["_query","pageSize"],l),u=tk(a,["pageToken"]),void 0!==s&&null!=u&&tP(s,["_query","pageToken"],u)),s);return n=tR("{parent}/documents",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["documents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["documents"],e)}return t}(e),r=new tX;return Object.assign(r,t),r})}}}class nC extends tC{constructor(e,t=new nO(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new rN(tE.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw Error("Gemini Enterprise Agent Platform (previously known as Vertex AI) does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async downloadMedia(e,t){if(this.apiClient.isVertexAI())throw Error("This method is only supported in the Gemini Developer client.");let r=new URL(e,"http://dummy.com"),n=r.pathname;if(n.startsWith("/")&&(n=n.slice(1)),!n.includes("/media/"))throw Error(`Invalid uri format: ${e}. Expected to contain /media/`);let i={};r.searchParams.forEach((e,t)=>{i[t]=e}),i.alt="media";let s=Object.assign({},null==t?void 0:t.httpOptions),o=await this.apiClient.request({path:n,httpMethod:"GET",queryParams:i,httpOptions:s});if(o instanceof tD)return new Uint8Array(await o.responseInternal.arrayBuffer());throw Error("Unexpected response type from downloadMedia")}async create(e){var t,r,n;let i="",s={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let o,a,l,u,c=(n=this.apiClient,o={},null!=(a=tk(e,["config"]))&&(l=tk(a,["displayName"]),void 0!==o&&null!=l&&tP(o,["displayName"],l),u=tk(a,["embeddingModel"]),void 0!==o&&null!=u&&tP(o,["embeddingModel"],t7(n,u))),o);return i=tR("fileSearchStores",c._url),s=c._query,delete c._url,delete c._query,this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=tk(e,["name"]))&&tP(s,["_url","name"],o),s);return n=tR("{name}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=tk(e,["name"]))&&tP(s,["_url","name"],o),null!=(a=tk(e,["config"]))&&(l=tk(a,["force"]),void 0!==s&&null!=l&&tP(s,["_query","force"],l)),s);n=tR("{name}",u._url),i=u._query,delete u._url,delete u._query,await this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=tk(e,["config"]))&&(a=tk(o,["pageSize"]),void 0!==s&&null!=a&&tP(s,["_query","pageSize"],a),l=tk(o,["pageToken"]),void 0!==s&&null!=l&&tP(s,["_query","pageToken"],l)),s);return n=tR("fileSearchStores",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["fileSearchStores"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["fileSearchStores"],e)}return t}(e),r=new tQ;return Object.assign(r,t),r})}}async uploadToFileSearchStoreInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l=(s={},null!=(o=tk(e,["fileSearchStoreName"]))&&tP(s,["_url","file_search_store_name"],o),null!=(a=tk(e,["config"]))&&nn(a,s),s);return n=tR("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tZ;return Object.assign(i,n),i})}}async importFile(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=tk(e,["fileSearchStoreName"]))&&tP(s,["_url","file_search_store_name"],o),null!=(a=tk(e,["fileName"]))&&tP(s,["fileName"],a),null!=(l=tk(e,["config"]))&&function(e,t){let r=tk(e,["customMetadata"]);if(void 0!==t&&null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),tP(t,["customMetadata"],e)}let n=tk(e,["chunkingConfig"]);void 0!==t&&null!=n&&tP(t,["chunkingConfig"],n)}(l,s),s);return n=tR("{file_search_store_name}:importFile",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h=(o={},null!=(a=tk(e,["name"]))&&tP(o,["name"],a),null!=(l=tk(e,["metadata"]))&&tP(o,["metadata"],l),null!=(u=tk(e,["done"]))&&tP(o,["done"],u),null!=(c=tk(e,["error"]))&&tP(o,["error"],c),null!=(d=tk(e,["response"]))&&tP(o,["response"],(r={},null!=(n=tk(t=d,["sdkHttpResponse"]))&&tP(r,["sdkHttpResponse"],n),null!=(i=tk(t,["parent"]))&&tP(r,["parent"],i),null!=(s=tk(t,["documentName"]))&&tP(r,["documentName"],s),r)),o),p=new t0;return Object.assign(p,h),p})}}}let nR=function(){let{crypto:e}=globalThis;if(null==e?void 0:e.randomUUID)return nR=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function nP(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}let nk=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch(e){}try{return Error(JSON.stringify(e))}catch(e){}}return Error(e)};class nx extends Error{}class nN extends nx{constructor(e,t,r,n){super(`${nN.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.error=t}static makeMessage(e,t,r){let n=(null==t?void 0:t.message)?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){return e&&n?400===e?new nL(e,t,r,n):401===e?new nj(e,t,r,n):403===e?new nG(e,t,r,n):404===e?new nF(e,t,r,n):409===e?new n$(e,t,r,n):422===e?new nq(e,t,r,n):429===e?new nB(e,t,r,n):e>=500?new nH(e,t,r,n):new nN(e,t,r,n):new nU({message:r,cause:nk(t)})}}class nD extends nN{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class nU extends nN{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class nM extends nU{constructor({message:e}={}){super({message:null!=e?e:"Request timed out."})}}class nL extends nN{}class nj extends nN{}class nG extends nN{}class nF extends nN{}class n$ extends nN{}class nq extends nN{}class nB extends nN{}class nH extends nN{}let nV=/^[a-z][a-z0-9+.-]*:/i,nK=e=>(nK=Array.isArray)(e),nJ=nK;function nW(e){if(!e)return!0;for(let t in e)return!1;return!0}function nz(...e){let t=globalThis.ReadableStream;if(void 0===t)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function nY(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return(null==e?void 0:e.done)&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function nX(e){var t,r;if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await (null==(r=(t=e[Symbol.asyncIterator]()).return)?void 0:r.call(t));let n=e.getReader(),i=n.cancel();n.releaseLock(),await i}let nQ=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),nZ=()=>{var e;if("u"<typeof File){let{process:t}=globalThis;throw Error("`File` is not defined as a global, which is required for file uploads."+("string"==typeof(null==(e=null==t?void 0:t.versions)?void 0:e.node)&&20>parseInt(t.versions.node.split("."))?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function n0(e,t,r){return nZ(),new File(e,null!=t?t:"unknown_file",r)}let n1=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function n2(e,t,r){var n;let i,s;if(nZ(),null!=(i=e=await e)&&"object"==typeof i&&"string"==typeof i.name&&"number"==typeof i.lastModified&&n1(i))return e instanceof File?e:n0([await e.arrayBuffer()],e.name);if(null!=(s=e)&&"object"==typeof s&&"string"==typeof s.url&&"function"==typeof s.blob){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),n0(await n4(n),t,r)}let o=await n4(e);if(t||(t=("object"==typeof(n=e)&&null!==n&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0),!(null==r?void 0:r.type)){let e=o.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r=Object.assign(Object.assign({},r),{type:e}))}return n0(o,t,r)}async function n4(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(n1(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator])try{for(var r,n,i,s,o,a,l=!0,u=r$(e);!(r=(a=await u.next()).done);l=!0)s=a.value,l=!1,t.push(...await n4(s))}catch(e){n={error:e}}finally{try{!l&&!r&&(i=u.return)&&await i.call(u)}finally{if(n)throw n.error}}else{let t=null==(o=null==e?void 0:e.constructor)?void 0:o.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";let t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}return t}class n6{constructor(e){this._client=e}}function n3(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}n6._key=[];let n5=Object.freeze(Object.create(null)),n8=((e=n3)=>function(t,...r){let n;if(1===t.length)return t[0];let i=!1,s=[],o=t.reduce((t,n,o)=>{var a,l,u;/[?#]/.test(n)&&(i=!0);let c=r[o],d=(i?encodeURIComponent:e)(""+c);return o!==r.length&&(null==c||"object"==typeof c&&c.toString===(null==(u=Object.getPrototypeOf(null!=(l=Object.getPrototypeOf(null!=(a=c.hasOwnProperty)?a:n5))?l:n5))?void 0:u.toString))&&(d=c+"",s.push({start:t.length+n.length,length:d.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),t+n+(o===r.length?"":d)},""),a=o.split(/[?#]/,1)[0],l=/(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;for(;null!==(n=l.exec(a));){let e=n[0].startsWith("/"),t=+!!e,r=e?n[0].slice(1):n[0];s.push({start:n.index+t,length:r.length,error:`Value "${r}" can't be safely passed as a path parameter`})}if(s.sort((e,t)=>e.start-t.start),s.length>0){let e=0,t=s.reduce((t,r)=>{let n=" ".repeat(r.start-e),i="^".repeat(r.length);return e=r.start+r.length,t+n+i},"");throw new nx(`Path parameters result in path with invalid segments:
31
31
  ${s.map(e=>e.error).join("\n")}
32
32
  ${o}
33
- ${t}`)}return o})(n3);class n9 extends n6{create(e,t){var r;let{api_version:n=this._client.apiVersion}=e,i=rj(e,["api_version"]);if("model"in i&&"agent_config"in i)throw new nx("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in i&&"generation_config"in i)throw new nx("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(n8`/${n}/interactions`,Object.assign(Object.assign({body:i},t),{stream:null!=(r=e.stream)&&r}))}delete(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(n8`/${n}/interactions/${e}`,r)}cancel(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.post(n8`/${n}/interactions/${e}/cancel`,r)}get(e,t={},r){var n;let i=null!=t?t:{},{api_version:s=this._client.apiVersion}=i,o=rj(i,["api_version"]);return this._client.get(n8`/${s}/interactions/${e}`,Object.assign(Object.assign({query:o},r),{stream:null!=(n=null==t?void 0:t.stream)&&n}))}}n9._key=Object.freeze(["interactions"]);class n7 extends n9{}class ie extends n6{create(e,t){let{api_version:r=this._client.apiVersion}=e,n=rj(e,["api_version"]);return this._client.post(n8`/${r}/webhooks`,Object.assign({body:n},t))}update(e,t={},r){let n=null!=t?t:{},{api_version:i=this._client.apiVersion,update_mask:s}=n,o=rj(n,["api_version","update_mask"]);return this._client.patch(n8`/${i}/webhooks/${e}`,Object.assign({query:{update_mask:s},body:o},r))}list(e={},t){let r=null!=e?e:{},{api_version:n=this._client.apiVersion}=r,i=rj(r,["api_version"]);return this._client.get(n8`/${n}/webhooks`,Object.assign({query:i},t))}delete(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(n8`/${n}/webhooks/${e}`,r)}get(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.get(n8`/${n}/webhooks/${e}`,r)}ping(e,t,r){let{api_version:n=this._client.apiVersion,body:i}=null!=t?t:{};return this._client.post(n8`/${n}/webhooks/${e}:ping`,Object.assign({body:i},r))}rotateSigningSecret(e,t={},r){let n=null!=t?t:{},{api_version:i=this._client.apiVersion}=n,s=rj(n,["api_version"]);return this._client.post(n8`/${i}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:s},r))}}ie._key=Object.freeze(["webhooks"]);class it extends ie{}function ir(e){let r;return(null!=t?t:t=(r=new globalThis.TextEncoder).encode.bind(r))(e)}function ii(e){let t;return(null!=r?r:r=(t=new globalThis.TextDecoder).decode.bind(t))(e)}class is{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var t;let r;if(null==e)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?ir(e):e;this.buffer=function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}([this.buffer,n]);let i=[];for(;null!=(r=function(e,t){let r,n=null!=t?t:0,i=e.indexOf(10,n),s=e.indexOf(13,n);return -1===i&&-1===s?null:10===e[r=-1!==i&&-1!==s?Math.min(i,s):-1!==i?i:s]?{preceding:r,index:r+1,carriage:!1}:{preceding:r,index:r+1,carriage:!0}}(this.buffer,null!=(t=this.carriageReturnIndex)?t:this.searchIndex));){if(r.carriage&&null==this.carriageReturnIndex){this.carriageReturnIndex=r.index;continue}if(null!=this.carriageReturnIndex&&(r.index!==this.carriageReturnIndex+1||r.carriage)){i.push(ii(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}let e=null!==this.carriageReturnIndex?r.preceding-1:r.preceding,t=ii(this.buffer.subarray(0,e));i.push(t),this.buffer=this.buffer.subarray(r.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),i}flush(){return this.buffer.length?this.decode("\n"):[]}}is.NEWLINE_CHARS=new Set(["\n","\r"]),is.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let io={off:0,error:200,warn:300,info:400,debug:500},ia=(e,t,r)=>{if(e){if(Object.prototype.hasOwnProperty.call(io,e))return e;ih(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(io))}`)}};function il(){}function iu(e,t,r){return!t||io[e]>io[r]?il:t[e].bind(t)}let ic={error:il,warn:il,info:il,debug:il},id=new WeakMap;function ih(e){var t;let r=e.logger,n=null!=(t=e.logLevel)?t:"off";if(!r)return ic;let i=id.get(r);if(i&&i[0]===n)return i[1];let s={error:iu("error",r,n),warn:iu("warn",r,n),info:iu("info",r,n),debug:iu("debug",r,n)};return id.set(r,[n,s]),s}let ip=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class im{constructor(e,t,r){this.iterator=e,this.controller=t,this.client=r}static fromSSEResponse(e,t,r){let n=!1,i=r?ih(r):console;return new im(function(){return rF(this,arguments,function*(){var r,s,o,a;if(n)throw new nx("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{try{for(var u,c=!0,d=r$(function(e,t){return rF(this,arguments,function*(){var r,n,i,s;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new nx("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new nx("Attempted to iterate over a response with no body")}let o=new ig,a=new is,l=nY(e.body);try{for(var u,c=!0,d=r$(function(e){return rF(this,arguments,function*(){var t,r,n,i;try{for(var s,o=!0,a=r$(e);!(t=(s=yield rG(a.next())).done);o=!0){if(i=s.value,o=!1,null==i)continue;let e=i instanceof ArrayBuffer?new Uint8Array(i):"string"==typeof i?ir(i):i;yield yield rG(e)}}catch(e){r={error:e}}finally{try{!o&&!t&&(n=a.return)&&(yield rG(n.call(a)))}finally{if(r)throw r.error}}})}(l));!(r=(u=yield rG(d.next())).done);c=!0)for(let e of(s=u.value,c=!1,a.decode(s))){let t=o.decode(e);t&&(yield yield rG(t))}}catch(e){n={error:e}}finally{try{!c&&!r&&(i=d.return)&&(yield rG(i.call(d)))}finally{if(n)throw n.error}}for(let e of a.flush()){let t=o.decode(e);t&&(yield yield rG(t))}})}(e,t));!(r=(u=yield rG(d.next())).done);c=!0)if(a=u.value,c=!1,!l)if(a.data.startsWith("[DONE]")){l=!0;continue}else try{yield yield rG(JSON.parse(a.data))}catch(e){throw i.error("Could not parse message into JSON:",a.data),i.error("From chunk:",a.raw),e}}catch(e){s={error:e}}finally{try{!c&&!r&&(o=d.return)&&(yield rG(o.call(d)))}finally{if(s)throw s.error}}l=!0}catch(e){if(nP(e))return yield rG(void 0);throw e}finally{l||t.abort()}})},t,r)}static fromReadableStream(e,t,r){let n=!1;return new im(function(){return rF(this,arguments,function*(){var r,i,s,o;if(n)throw new nx("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{try{for(var l,u=!0,c=r$(function(){return rF(this,arguments,function*(){var t,r,n,i;let s=new is,o=nY(e);try{for(var a,l=!0,u=r$(o);!(t=(a=yield rG(u.next())).done);l=!0)for(let e of(i=a.value,l=!1,s.decode(i)))yield yield rG(e)}catch(e){r={error:e}}finally{try{!l&&!t&&(n=u.return)&&(yield rG(n.call(u)))}finally{if(r)throw r.error}}for(let e of s.flush())yield yield rG(e)})}());!(r=(l=yield rG(c.next())).done);u=!0)o=l.value,u=!1,!a&&o&&(yield yield rG(JSON.parse(o)))}catch(e){i={error:e}}finally{try{!u&&!r&&(s=c.return)&&(yield rG(s.call(c)))}finally{if(i)throw i.error}}a=!0}catch(e){if(nP(e))return yield rG(void 0);throw e}finally{a||t.abort()}})},t,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new im(()=>n(e),this.controller,this.client),new im(()=>n(t),this.controller,this.client)]}toReadableStream(){let e,t=this;return nz({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:n}=await e.next();if(n)return t.close();let i=ir(JSON.stringify(r)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){var t;await (null==(t=e.return)?void 0:t.call(e))}})}}class ig{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){var t;let r;if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,s]=-1!==(r=(t=e).indexOf(":"))?[t.substring(0,r),":",t.substring(r+1)]:[t,"",""];return s.startsWith(" ")&&(s=s.substring(1)),"event"===n?this.event=s:"data"===n&&this.data.push(s),null}}async function iy(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=t,o=await (async()=>{var n;if(t.options.stream)return(ih(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller,e):im.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let i=r.headers.get("content-type"),s=null==(n=null==i?void 0:i.split(";")[0])?void 0:n.trim();if((null==s?void 0:s.includes("application/json"))||(null==s?void 0:s.endsWith("+json"))){if("0"===r.headers.get("content-length"))return;return await r.json()}return await r.text()})();return ih(e).debug(`[${n}] response parsed`,ip({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}class i_ extends Promise{constructor(e,t,r=iy){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,this.client=e}_thenUnwrap(e){return new i_(this.client,this.responsePromise,async(t,r)=>e(await this.parseResponse(t,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}let iE=Symbol("brand.privateNullableHeaders"),iA=e=>{let t=new Headers,r=new Set;for(let n of e){let e=new Set;for(let[i,s]of function*(e){let t;if(!e)return;if(iE in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let n of(e instanceof Headers?t=e.entries():nJ(e)?t=e:(r=!0,t=Object.entries(null!=e?e:{})),t)){let e=n[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=nJ(n[1])?n[1]:[n[1]],i=!1;for(let n of t)void 0!==n&&(r&&!i&&(i=!0,yield[e,null]),yield[e,n])}}(n)){let n=i.toLowerCase();e.has(n)||(t.delete(i),e.add(n)),null===s?(t.delete(i),r.add(n)):(t.append(i,s),r.delete(n))}}return{[iE]:!0,values:t,nulls:r}},iv=e=>{var t,r,n,i,s;return void 0!==globalThis.process?(null==(r=null==(t=globalThis.process.env)?void 0:t[e])?void 0:r.trim())||void 0:void 0!==globalThis.Deno&&(null==(s=null==(i=null==(n=globalThis.Deno.env)?void 0:n.get)?void 0:i.call(n,e))?void 0:s.trim())||void 0};class ib{constructor(e){var t,r,n,i,s,o,a,{baseURL:l=iv("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=null!=(t=iv("GEMINI_API_KEY"))?t:null,apiVersion:c="v1beta"}=e;let d=Object.assign(Object.assign({apiKey:u,apiVersion:c},rj(e,["baseURL","apiKey","apiVersion"])),{baseURL:l||"https://generativelanguage.googleapis.com"});this.baseURL=d.baseURL,this.timeout=null!=(r=d.timeout)?r:ib.DEFAULT_TIMEOUT,this.logger=null!=(n=d.logger)?n:console;let h="warn";this.logLevel=h,this.logLevel=null!=(s=null!=(i=ia(d.logLevel,"ClientOptions.logLevel",this))?i:ia(iv("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))?s:h,this.fetchOptions=d.fetchOptions,this.maxRetries=null!=(o=d.maxRetries)?o:2,this.fetch=null!=(a=d.fetch)?a:function(){if("u">typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),this.encoder=nQ,this._options=d,this.apiKey=u,this.apiVersion=c,this.clientAdapter=d.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.has("authorization")||e.has("x-goog-api-key")||this.apiKey&&e.get("x-goog-api-key"))&&!t.has("x-goog-api-key"))throw Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let t=iA([e.headers]);if(!(t.values.has("authorization")||t.values.has("x-goog-api-key"))){if(this.apiKey)return iA([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter&&this.clientAdapter.isVertexAI())return iA([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new nx(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS 0.0.1`}defaultIdempotencyKey(){return`stainless-node-retry-${nR()}`}makeStatusError(e,t,r,n){return nN.generate(e,t,r,n)}buildURL(e,t,r){let n=!this.baseURLOverridden()&&r||this.baseURL,i=new URL(nV.test(e)?e:n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return nW(s)&&nW(o)||(t=Object.assign(Object.assign(Object.assign({},o),s),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>Object.assign({method:e,path:t},r)))}request(e,t=null){return new i_(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var n,i,s;let o=await e,a=null!=(n=o.maxRetries)?n:this.maxRetries;null==t&&(t=a),await this.prepareOptions(o);let{req:l,url:u,timeout:c}=await this.buildRequest(o,{retryCount:a-t});await this.prepareRequest(l,{url:u,options:o});let d="log_"+(0x1000000*Math.random()|0).toString(16).padStart(6,"0"),h=void 0===r?"":`, retryOf: ${r}`,p=Date.now();if(ih(this).debug(`[${d}] sending request`,ip({retryOfRequestLogID:r,method:o.method,url:u,options:o,headers:l.headers})),null==(i=o.signal)?void 0:i.aborted)throw new nD;let f=new AbortController,m=await this.fetchWithTimeout(u,l,c,f).catch(nk),g=Date.now();if(m instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(null==(s=o.signal)?void 0:s.aborted)throw new nD;let n=nP(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return ih(this).info(`[${d}] connection ${n?"timed out":"failed"} - ${e}`),ih(this).debug(`[${d}] connection ${n?"timed out":"failed"} (${e})`,ip({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),this.retryRequest(o,t,null!=r?r:d);if(ih(this).info(`[${d}] connection ${n?"timed out":"failed"} - error; no more retries left`),ih(this).debug(`[${d}] connection ${n?"timed out":"failed"} (error; no more retries left)`,ip({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),n)throw new nM;throw new nU({cause:m})}let y=`[${d}${h}] ${l.method} ${u} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${g-p}ms`;if(!m.ok){let e=await this.shouldRetry(m);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await nX(m.body),ih(this).info(`${y} - ${e}`),ih(this).debug(`[${d}] response error (${e})`,ip({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),this.retryRequest(o,t,null!=r?r:d,m.headers)}let n=e?"error; no more retries left":"error; not retryable";ih(this).info(`${y} - ${n}`);let i=await m.text().catch(e=>nk(e).message),s=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),a=s?void 0:i;throw ih(this).debug(`[${d}] response error (${n})`,ip({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:a,durationMs:Date.now()-p})),this.makeStatusError(m.status,s,a,m.headers)}return ih(this).info(y),ih(this).debug(`[${d}] response start`,ip({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),{response:m,options:o,controller:f,requestLogID:d,retryOfRequestLogID:r,startTime:p}}async fetchWithTimeout(e,t,r,n){let i=t||{},{signal:s,method:o}=i,a=rj(i,["signal","method"]),l=this._makeAbort(n);s&&s.addEventListener("abort",l,{once:!0});let u=setTimeout(l,r),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,d=Object.assign(Object.assign(Object.assign({signal:n.signal},c?{duplex:"half"}:{}),{method:"GET"}),a);o&&(d.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r,n){var i;let s,o,a=null==n?void 0:n.get("retry-after-ms");if(a){let e=parseFloat(a);Number.isNaN(e)||(s=e)}let l=null==n?void 0:n.get("retry-after");if(l&&!s){let e=parseFloat(l);s=Number.isNaN(e)?Date.parse(l)-Date.now():1e3*e}if(void 0===s){let r=null!=(i=e.maxRetries)?i:this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,r)}return await (o=s,new Promise(e=>setTimeout(e,o))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var r,n,i;let s=Object.assign({},e),{method:o,path:a,query:l,defaultBaseURL:u}=s,c=this.buildURL(a,l,u);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new nx(`${e} must be an integer`);if(t<0)throw new nx(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=null!=(r=s.timeout)?r:this.timeout;let{bodyHeaders:d,body:h}=this.buildBody({options:s}),p=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:o,headers:p},s.signal&&{signal:s.signal}),globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"}),h&&{body:h}),null!=(n=this.fetchOptions)?n:{}),null!=(i=s.fetchOptions)?i:{}),url:c,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let i={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=await this.authHeaders(e),o=iA([i,{Accept:"application/json","User-Agent":this.getUserAgent()},this._options.defaultHeaders,r,e.headers,s]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=iA([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};if("object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)){let t;return{bodyHeaders:void 0,body:(t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator](),nz({start(){},async pull(e){let{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){var e;await (null==(e=t.return)?void 0:e.call(t))}}))}}return"object"==typeof e&&"application/x-www-form-urlencoded"===r.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:r})}}ib.DEFAULT_TIMEOUT=6e4;class iw extends ib{constructor(){super(...arguments),this.interactions=new n7(this),this.webhooks=new it(this)}}iw.GeminiNextGenAPIClient=iw,iw.GeminiNextGenAPIClientError=nx,iw.APIError=nN,iw.APIConnectionError=nU,iw.APIConnectionTimeoutError=nM,iw.APIUserAbortError=nD,iw.NotFoundError=nF,iw.ConflictError=n$,iw.RateLimitError=nB,iw.BadRequestError=nL,iw.AuthenticationError=nj,iw.InternalServerError=nH,iw.PermissionDeniedError=nG,iw.UnprocessableEntityError=nq,iw.toFile=n2,iw.Interactions=n7,iw.Webhooks=it;let iT="x-goog-api-key",iI="https://www.googleapis.com/auth/cloud-platform";class iS{constructor(e){if(void 0!==e.apiKey){this.apiKey=e.apiKey;return}let t=function(e){let t;if(!e)return{scopes:[iI]};if((t=e).scopes){if("string"==typeof t.scopes&&t.scopes!==iI||Array.isArray(t.scopes)&&0>t.scopes.indexOf(iI))throw Error(`Invalid auth scopes. Scopes must include: ${iI}`)}else t.scopes=[iI];return t}(e.googleAuthOptions);this.googleAuth=new tv.GoogleAuth(t)}async addAuthHeaders(e,t){if(void 0!==this.apiKey){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(null===e.get(iT)){if(void 0===this.apiKey)throw Error("Trying to set API key header but apiKey is not set");e.append(iT,this.apiKey)}}async addGoogleAuthHeaders(e,t){if(void 0===this.googleAuth)throw Error("Trying to set google-auth headers but googleAuth is unset");for(let[r,n]of(await this.googleAuth.getRequestHeaders(t)))null===e.get(r)&&e.append(r,n)}}class iO{async download(e,t){if(e.downloadPath){let r=await iC(e,t);if(r instanceof tD){let t=(0,tb.createWriteStream)(e.downloadPath);tT.Readable.fromWeb(r.responseInternal.body).pipe(t),await (0,tI.finished)(t)}else try{await (0,tw.writeFile)(e.downloadPath,r,{encoding:"base64"})}catch(t){throw Error(`Failed to write file to ${e.downloadPath}: ${t}`)}}}}async function iC(e,t){var r,n,i;let s=rb(e.file);if(void 0!==s)return await t.request({path:`files/${s}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:null==(r=e.config)?void 0:r.httpOptions,abortSignal:null==(n=e.config)?void 0:n.abortSignal});if(rA(e.file)){let t=null==(i=e.file.video)?void 0:i.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download generated video, Uri or videoBytes not found.")}if(rv(e.file)){let t=e.file.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download video, Uri or videoBytes not found.")}throw Error("Unsupported file type")}class iR{create(e,t,r){return new iP(e,t,r)}}class iP{constructor(e,t,r){this.url=e,this.headers=t,this.callbacks=r}connect(){this.ws=new tS.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.close()}}function ik(e,t){let r={},n=tk(e,["sdkHttpResponse"]);null!=n&&tP(r,["sdkHttpResponse"],n);let i=tk(e,["name"]);null!=i&&tP(r,["name"],i);let s=tk(e,["state"]);null!=s&&tP(r,["state"],rE(s));let o=tk(e,["createTime"]);null!=o&&tP(r,["createTime"],o);let a=tk(e,["startTime"]);null!=a&&tP(r,["startTime"],a);let l=tk(e,["endTime"]);null!=l&&tP(r,["endTime"],l);let u=tk(e,["updateTime"]);null!=u&&tP(r,["updateTime"],u);let c=tk(e,["error"]);null!=c&&tP(r,["error"],c);let d=tk(e,["description"]);null!=d&&tP(r,["description"],d);let h=tk(e,["baseModel"]);null!=h&&tP(r,["baseModel"],h);let p=tk(e,["tunedModel"]);null!=p&&tP(r,["tunedModel"],p);let f=tk(e,["preTunedModel"]);null!=f&&tP(r,["preTunedModel"],f);let m=tk(e,["supervisedTuningSpec"]);null!=m&&tP(r,["supervisedTuningSpec"],m);let g=tk(e,["preferenceOptimizationSpec"]);null!=g&&tP(r,["preferenceOptimizationSpec"],g);let y=tk(e,["distillationSpec"]);null!=y&&tP(r,["distillationSpec"],y);let _=tk(e,["tuningDataStats"]);null!=_&&tP(r,["tuningDataStats"],_);let E=tk(e,["encryptionSpec"]);null!=E&&tP(r,["encryptionSpec"],E);let A=tk(e,["partnerModelTuningSpec"]);null!=A&&tP(r,["partnerModelTuningSpec"],A);let v=tk(e,["customBaseModel"]);null!=v&&tP(r,["customBaseModel"],v);let b=tk(e,["evaluateDatasetRuns"]);if(null!=b){let e=b;Array.isArray(e)&&(e=e.map(e=>e)),tP(r,["evaluateDatasetRuns"],e)}let w=tk(e,["experiment"]);null!=w&&tP(r,["experiment"],w);let T=tk(e,["fullFineTuningSpec"]);null!=T&&tP(r,["fullFineTuningSpec"],T);let I=tk(e,["labels"]);null!=I&&tP(r,["labels"],I);let S=tk(e,["outputUri"]);null!=S&&tP(r,["outputUri"],S);let O=tk(e,["pipelineJob"]);null!=O&&tP(r,["pipelineJob"],O);let C=tk(e,["serviceAccount"]);null!=C&&tP(r,["serviceAccount"],C);let R=tk(e,["tunedModelDisplayName"]);null!=R&&tP(r,["tunedModelDisplayName"],R);let P=tk(e,["tuningJobState"]);null!=P&&tP(r,["tuningJobState"],P);let k=tk(e,["veoTuningSpec"]);null!=k&&tP(r,["veoTuningSpec"],k);let x=tk(e,["distillationSamplingSpec"]);null!=x&&tP(r,["distillationSamplingSpec"],x);let N=tk(e,["tuningJobMetadata"]);return null!=N&&tP(r,["tuningJobMetadata"],N),r}function ix(e,t){let r={},n=tk(e,["gcsUri"]);null!=n&&tP(r,["validationDatasetUri"],n);let i=tk(e,["vertexDatasetResource"]);return null!=i&&tP(r,["validationDatasetUri"],i),r}class iN extends tC{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rN(tE.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI())if(e.baseModel.startsWith("projects/")){let r={tunedModelName:e.baseModel};(null==(t=e.config)?void 0:t.preTunedModelCheckpointId)&&(r.checkpointId=e.config.preTunedModelCheckpointId);let n=Object.assign(Object.assign({},e),{preTunedModel:r});return n.baseModel=void 0,await this.tuneInternal(n)}else{let t=Object.assign({},e);return await this.tuneInternal(t)}{let t=Object.assign({},e),r=await this.tuneMldevInternal(t),n="";return void 0!==r.metadata&&void 0!==r.metadata.tunedModel?n=r.metadata.tunedModel:void 0!==r.name&&r.name.includes("/operations/")&&(n=r.name.split("/operations/")[0]),{name:n,state:eK.JOB_STATE_QUEUED}}}}async getInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],i),n);return s=tR("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ik(e))}{let t,r,a=(t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],r),t);return s=tR("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s,o,a,l,u,c,d,h,p,f;return t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),null!=(n=tk(e,["name"]))&&tP(t,["name"],n),null!=(i=tk(e,["state"]))&&tP(t,["state"],rE(i)),null!=(s=tk(e,["createTime"]))&&tP(t,["createTime"],s),null!=(o=tk(e,["tuningTask","startTime"]))&&tP(t,["startTime"],o),null!=(a=tk(e,["tuningTask","completeTime"]))&&tP(t,["endTime"],a),null!=(l=tk(e,["updateTime"]))&&tP(t,["updateTime"],l),null!=(u=tk(e,["description"]))&&tP(t,["description"],u),null!=(c=tk(e,["baseModel"]))&&tP(t,["baseModel"],c),null!=(d=tk(e,["_self"]))&&tP(t,["tunedModel"],(h={},null!=(p=tk(d,["name"]))&&tP(h,["model"],p),null!=(f=tk(d,["name"]))&&tP(h,["endpoint"],f),h)),t})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l,u,c=(s={},null!=(o=tk(e,["config"]))&&(a=tk(o,["pageSize"]),void 0!==s&&null!=a&&tP(s,["_query","pageSize"],a),l=tk(o,["pageToken"]),void 0!==s&&null!=l&&tP(s,["_query","pageToken"],l),u=tk(o,["filter"]),void 0!==s&&null!=u&&tP(s,["_query","filter"],u)),s);return n=tR("tuningJobs",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["tuningJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>ik(e))),tP(t,["tuningJobs"],e)}return t}(e),r=new tJ;return Object.assign(r,t),r})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],i),n);return s=tR("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tW;return Object.assign(i,n),i})}{let t,r,a=(t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],r),t);return s=tR("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tW;return Object.assign(i,n),i})}}async tuneInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l,u,c=(s={},null!=(o=tk(e,["baseModel"]))&&tP(s,["baseModel"],o),null!=(a=tk(e,["preTunedModel"]))&&tP(s,["preTunedModel"],a),null!=(l=tk(e,["trainingDataset"]))&&function(e,t,r){let n=tk(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=tk(e,["gcsUri"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===n){let r=tk(e,["gcsUri"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}else if("DISTILLATION"===n){let r=tk(e,["gcsUri"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","promptDatasetUri"],r)}let i=tk(r,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){let r=tk(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===i){let r=tk(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}else if("DISTILLATION"===i){let r=tk(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","promptDatasetUri"],r)}if(void 0!==tk(e,["examples"]))throw Error("examples parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}(l,s,e),null!=(u=tk(e,["config"]))&&function(e,t,r){let n=tk(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=tk(e,["validationDataset"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec"],ix(r))}else if("PREFERENCE_TUNING"===n){let r=tk(e,["validationDataset"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec"],ix(r))}else if("DISTILLATION"===n){let r=tk(e,["validationDataset"]);void 0!==t&&null!=r&&tP(t,["distillationSpec"],ix(r))}let i=tk(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&tP(t,["tunedModelDisplayName"],i);let s=tk(e,["description"]);void 0!==t&&null!=s&&tP(t,["description"],s);let o=tk(r,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){let r=tk(e,["epochCount"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","epochCount"],r)}else if("PREFERENCE_TUNING"===o){let r=tk(e,["epochCount"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],r)}else if("DISTILLATION"===o){let r=tk(e,["epochCount"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","epochCount"],r)}let a=tk(r,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){let r=tk(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],r)}else if("PREFERENCE_TUNING"===a){let r=tk(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],r)}else if("DISTILLATION"===a){let r=tk(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","learningRateMultiplier"],r)}let l=tk(r,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){let r=tk(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","exportLastCheckpointOnly"],r)}else if("PREFERENCE_TUNING"===l){let r=tk(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],r)}else if("DISTILLATION"===l){let r=tk(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","exportLastCheckpointOnly"],r)}let u=tk(r,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){let r=tk(e,["adapterSize"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","adapterSize"],r)}else if("PREFERENCE_TUNING"===u){let r=tk(e,["adapterSize"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],r)}else if("DISTILLATION"===u){let r=tk(e,["adapterSize"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","adapterSize"],r)}let c=tk(r,["config","method"]);if(void 0===c&&(c="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===c){let r=tk(e,["tuningMode"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","tuningMode"],r)}else if("DISTILLATION"===c){let r=tk(e,["tuningMode"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","tuningMode"],r)}let d=tk(e,["customBaseModel"]);void 0!==t&&null!=d&&tP(t,["customBaseModel"],d);let h=tk(r,["config","method"]);if(void 0===h&&(h="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===h){let r=tk(e,["batchSize"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","batchSize"],r)}else if("DISTILLATION"===h){let r=tk(e,["batchSize"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","batchSize"],r)}let p=tk(r,["config","method"]);if(void 0===p&&(p="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===p){let r=tk(e,["learningRate"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","learningRate"],r)}else if("DISTILLATION"===p){let r=tk(e,["learningRate"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","learningRate"],r)}let f=tk(e,["labels"]);void 0!==t&&null!=f&&tP(t,["labels"],f);let m=tk(e,["beta"]);void 0!==t&&null!=m&&tP(t,["preferenceOptimizationSpec","hyperParameters","beta"],m);let g=tk(e,["baseTeacherModel"]);void 0!==t&&null!=g&&tP(t,["distillationSpec","baseTeacherModel"],g);let y=tk(e,["tunedTeacherModelSource"]);void 0!==t&&null!=y&&tP(t,["distillationSpec","tunedTeacherModelSource"],y);let _=tk(e,["sftLossWeightMultiplier"]);void 0!==t&&null!=_&&tP(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],_);let E=tk(e,["outputUri"]);void 0!==t&&null!=E&&tP(t,["outputUri"],E);let A=tk(e,["encryptionSpec"]);void 0!==t&&null!=A&&tP(t,["encryptionSpec"],A)}(u,s,e),s);return n=tR("tuningJobs",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ik(e))}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u,c=(s={},null!=(o=tk(e,["baseModel"]))&&tP(s,["baseModel"],o),null!=(a=tk(e,["preTunedModel"]))&&tP(s,["preTunedModel"],a),null!=(l=tk(e,["trainingDataset"]))&&function(e){if(void 0!==tk(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==tk(e,["vertexDatasetResource"]))throw Error("vertexDatasetResource parameter is not supported in Gemini API.");let t=tk(e,["examples"]);if(null!=t){let e=t;Array.isArray(e)&&(e=e.map(e=>e)),tP({},["examples","examples"],e)}}(l),null!=(u=tk(e,["config"]))&&function(e,t){if(void 0!==tk(e,["validationDataset"]))throw Error("validationDataset parameter is not supported in Gemini API.");let r=tk(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=r&&tP(t,["displayName"],r),void 0!==tk(e,["description"]))throw Error("description parameter is not supported in Gemini API.");let n=tk(e,["epochCount"]);void 0!==t&&null!=n&&tP(t,["tuningTask","hyperparameters","epochCount"],n);let i=tk(e,["learningRateMultiplier"]);if(null!=i&&tP({},["tuningTask","hyperparameters","learningRateMultiplier"],i),void 0!==tk(e,["exportLastCheckpointOnly"]))throw Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(void 0!==tk(e,["preTunedModelCheckpointId"]))throw Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(void 0!==tk(e,["adapterSize"]))throw Error("adapterSize parameter is not supported in Gemini API.");if(void 0!==tk(e,["tuningMode"]))throw Error("tuningMode parameter is not supported in Gemini API.");if(void 0!==tk(e,["customBaseModel"]))throw Error("customBaseModel parameter is not supported in Gemini API.");let s=tk(e,["batchSize"]);void 0!==t&&null!=s&&tP(t,["tuningTask","hyperparameters","batchSize"],s);let o=tk(e,["learningRate"]);if(void 0!==t&&null!=o&&tP(t,["tuningTask","hyperparameters","learningRate"],o),void 0!==tk(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");if(void 0!==tk(e,["beta"]))throw Error("beta parameter is not supported in Gemini API.");if(void 0!==tk(e,["baseTeacherModel"]))throw Error("baseTeacherModel parameter is not supported in Gemini API.");if(void 0!==tk(e,["tunedTeacherModelSource"]))throw Error("tunedTeacherModelSource parameter is not supported in Gemini API.");if(void 0!==tk(e,["sftLossWeightMultiplier"]))throw Error("sftLossWeightMultiplier parameter is not supported in Gemini API.");if(void 0!==tk(e,["outputUri"]))throw Error("outputUri parameter is not supported in Gemini API.");if(void 0!==tk(e,["encryptionSpec"]))throw Error("encryptionSpec parameter is not supported in Gemini API.")}(u,s),s);return n=tR("tunedModels",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s,o;return t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),null!=(n=tk(e,["name"]))&&tP(t,["name"],n),null!=(i=tk(e,["metadata"]))&&tP(t,["metadata"],i),null!=(s=tk(e,["done"]))&&tP(t,["done"],s),null!=(o=tk(e,["error"]))&&tP(t,["error"],o),t})}}}let iD="x-goog-upload-status";async function iU(e,t,r,n){var i;let s=await iL(e,t,r,n),o=await (null==s?void 0:s.json());if((null==(i=null==s?void 0:s.headers)?void 0:i[iD])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return o.file}async function iM(e,t,r,n){var i;let s=await iL(e,t,r,n),o=await (null==s?void 0:s.json());if((null==(i=null==s?void 0:s.headers)?void 0:i[iD])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let a=tN(o),l=new t9;return Object.assign(l,a),l}async function iL(e,t,r,n){var i,s,o;let a=t,l=(null==n?void 0:n.baseUrl)||(null==(i=r.clientOptions.httpOptions)?void 0:i.baseUrl);if(l){let e=new URL(l),r=new URL(t);r.protocol=e.protocol,r.host=e.host,r.port=e.port,a=r.toString()}let u=0,c=0,d=new tD(new Response),h="upload";for(u=e.size;c<u;){let t=Math.min(8388608,u-c),i=e.slice(c,c+t);c+t>=u&&(h+=", finalize");let l=0,p=1e3;for(;l<3;){let e=Object.assign(Object.assign({},(null==n?void 0:n.headers)||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(c),"Content-Length":String(t)});if(null==(s=null==(d=await r.request({path:"",body:i,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n),{apiVersion:"",baseUrl:a,headers:e})}))?void 0:d.headers)?void 0:s[iD])break;l++,await iG(p),p*=2}if(c+=t,(null==(o=null==d?void 0:d.headers)?void 0:o[iD])!=="active")break;if(u<=c)throw Error("All content has been uploaded, but the upload status is not finalized.")}return d}async function ij(e){return{size:e.size,type:e.type}}function iG(e){return new Promise(t=>setTimeout(t,e))}class iF{async stat(e){let t={size:0,type:void 0};return"string"==typeof e?(t.size=(await tw.stat(e)).size,t.type=this.inferMimeType(e),t):await ij(e)}async upload(e,t,r,n){return"string"==typeof e?await this.uploadFileFromPath(e,t,r,n):iU(e,t,r,n)}async uploadToFileSearchStore(e,t,r,n){return"string"==typeof e?await this.uploadFileToFileSearchStoreFromPath(e,t,r,n):iM(e,t,r,n)}inferMimeType(e){return({aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"})[e.slice(e.lastIndexOf(".")+1).toLowerCase()]}async uploadFileFromPath(e,t,r,n){var i;let s=await this.uploadFileFromPathInternal(e,t,r,n),o=await (null==s?void 0:s.json());if((null==(i=null==s?void 0:s.headers)?void 0:i[iD])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return o.file}async uploadFileToFileSearchStoreFromPath(e,t,r,n){var i;let s=await this.uploadFileFromPathInternal(e,t,r,n),o=await (null==s?void 0:s.json());if((null==(i=null==s?void 0:s.headers)?void 0:i[iD])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let a=tN(o),l=new t9;return Object.assign(l,a),l}async uploadFileFromPathInternal(e,t,r,n){var i,s,o;let a,l=t,u=(null==n?void 0:n.baseUrl)||(null==(i=r.clientOptions.httpOptions)?void 0:i.baseUrl);if(u){let e=new URL(u),r=new URL(t);r.protocol=e.protocol,r.host=e.host,r.port=e.port,l=r.toString()}let c=0,d=0,h=new tD(new Response),p="upload",f=tO.basename(e);try{if(!(a=await tw.open(e,"r")))throw Error("Failed to open file");for(c=(await a.stat()).size;d<c;){let e=Math.min(8388608,c-d);d+e>=c&&(p+=", finalize");let t=new Uint8Array(e),{bytesRead:i}=await a.read(t,0,e,d);if(i!==e)throw Error(`Failed to read ${e} bytes from file at offset ${d}. bytes actually read: ${i}`);let u=new Blob([t]),m=0,g=1e3;for(;m<3;){let e=Object.assign(Object.assign({},(null==n?void 0:n.headers)||{}),{"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":String(d),"Content-Length":String(i),"X-Goog-Upload-File-Name":f});if(null==(s=null==(h=await r.request({path:"",body:u,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n),{apiVersion:"",baseUrl:l,headers:e})}))?void 0:h.headers)?void 0:s[iD])break;m++,await iG(g),g*=2}if(d+=i,(null==(o=null==h?void 0:h.headers)?void 0:o[iD])!=="active")break;if(c<=d)throw Error("All content has been uploaded, but the upload status is not finalized.")}return h}finally{a&&await a.close()}}}class i$ extends rJ{async registerFiles(e){if("u"<typeof process||!process.versions||!process.versions.node)throw Error("registerFiles is only supported in Node.js environments.");let t=e.auth,r=await t.getRequestHeaders(),n=e.config||{},i=n.httpOptions||{},s=Object.assign({},i.headers||{});if(r)if("function"==typeof r[Symbol.iterator])for(let[e,t]of r)s[e]=t;else for(let[e,t]of Object.entries(r))s[e]=t;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},n),{httpOptions:Object.assign(Object.assign({},i),{headers:s})})})}}class iq{getNextGenClient(){var e;let t=this.httpOptions;return void 0===this._nextGenClient&&(this._nextGenClient=new iw({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:null==t?void 0:t.timeout,maxRetries:null==(e=null==t?void 0:t.retryOptions)?void 0:e.attempts})),(null==t?void 0:t.extraBody)&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored."),this._nextGenClient}get interactions(){return void 0!==this._interactions||(console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."),this._interactions=this.getNextGenClient().interactions),this._interactions}get webhooks(){return void 0!==this._webhooks||(this._webhooks=this.getNextGenClient().webhooks),this._webhooks}constructor(e){var t,r,s,o;let a,l;if((e.project||e.location)&&e.apiKey)throw Error("Project/location and API key are mutually exclusive in the client initializer.");this.vertexai=function(e){var t;if(void 0!==e.enterprise||void 0!==e.vertexai){if(void 0!==e.enterprise&&void 0!==e.vertexai&&e.enterprise!==e.vertexai)throw Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return null!=(t=e.enterprise)?t:e.vertexai}let r=iB("GOOGLE_GENAI_USE_ENTERPRISE"),n=iB("GOOGLE_GENAI_USE_VERTEXAI"),i=iH(r),s=iH(n);return(void 0!==r&&void 0!==n&&i!==s&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),void 0!==r)?i:void 0!==n&&s}(e);let u=(a=iB("GOOGLE_API_KEY"),l=iB("GEMINI_API_KEY"),a&&l&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),a||l||void 0),c=iB("GOOGLE_CLOUD_PROJECT"),d=iB("GOOGLE_CLOUD_LOCATION");this.apiKey=null!=(t=e.apiKey)?t:u,this.project=null!=(r=e.project)?r:c,this.location=null!=(s=e.location)?s:d,this.vertexai||this.apiKey||console.warn("API key should be set when using the Gemini API."),this.vertexai&&((null==(o=e.googleAuthOptions)?void 0:o.credentials)&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),(c||d)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&u?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):(c||d)&&u&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),this.location||this.apiKey||(this.location="global"));let h=function(e,t,r,s){return(null==e?void 0:e.baseUrl)?e.baseUrl:t?null!=i?i:r:null!=n?n:s}(e.httpOptions,this.vertexai,iB("GOOGLE_VERTEX_BASE_URL"),iB("GOOGLE_GEMINI_BASE_URL"));h&&(e.httpOptions?e.httpOptions.baseUrl=h:e.httpOptions={baseUrl:h}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let p=new iS({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new na({auth:p,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/"+process.version,uploader:new iF,downloader:new iO}),this.models=new nw(this.apiClient),this.live=new ng(this.apiClient,p,new iR),this.batches=new rD(this.apiClient),this.chats=new rH(this.models,this.apiClient),this.caches=new rL(this.apiClient),this.files=new i$(this.apiClient),this.operations=new nT(this.apiClient),this.authTokens=new nS(this.apiClient),this.tunings=new iN(this.apiClient),this.fileSearchStores=new nC(this.apiClient)}}function iB(e){var t,r,n;return null!=(n=null==(r=null==(t=null==process?void 0:process.env)?void 0:t[e])?void 0:r.trim())?n:void 0}function iH(e){return void 0!==e&&"true"===e.toLowerCase()}var iV=e.i(405898),iK=e.i(261829),iJ=e.i(983598),iW=e.i(999617),iz=e.i(798003),iY=e.i(459398),iX=e.i(50377),iQ=e.i(93716),iZ=e.i(630166),i0=e.i(115851);let i1=(0,iX.f)("ai:gemini");e.s(["f",0,class{ai;modelName;baseUrl;constructor(e){let t=e?.apiKey,r=e?.baseUrl;if(!t)throw Error("AI_AUTH_ERROR: GOOGLE_API_KEY is required for Gemini provider");this.ai=new iq({apiKey:t,httpOptions:r?{baseUrl:r}:void 0}),this.modelName=e?.model||"gemini-2.0-flash",this.baseUrl=r||"https://generativelanguage.googleapis.com",i1.info({provider:"Gemini",model:this.modelName,baseUrl:this.baseUrl,apiKeyPrefix:t.substring(0,8)+"..."},"AI Provider initialized")}async retryOperation(e,t=3){let r;for(let n=1;n<=t;n++)try{return await e()}catch(s){r=s;let e=s instanceof Error?s.message.toLowerCase():String(s);if(!(e.includes("fetch failed")||e.includes("network")||e.includes("connect")||e.includes("503")||e.includes("502")||e.includes("504")||e.includes("overloaded")||e.includes("timeout")||e.includes("etimedout")||e.includes("enotfound")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("unavailable"))||n===t)throw s;let i=1e3*Math.pow(2,n-1);i1.warn({attempt:n,maxRetries:t,error:e,nextRetryDelayMs:i},"Gemini operation failed, retrying..."),await new Promise(e=>setTimeout(e,i))}throw r}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r),s=e.lastIndexOf(n);return -1===i||-1===s||i>=s?null:e.substring(i+r.length,s).trim()}parseResponse(e){i1.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),o=this.extractTag(e,"requires_image"),a=this.extractTag(e,"wrong_answer_text")||"",l=this.extractTag(e,"mistake_analysis")||"",u=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw i1.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let c="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(c=i);let d=[];s&&(d=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let h=o?.toLowerCase().trim()==="true",p=(0,iZ.f)(u,a),f={questionText:t,answerText:r,analysis:n,wrongAnswerText:a,mistakeAnalysis:l,mistakeStatus:p,subject:c,knowledgePoints:d,requiresImage:h,difficultyStars:(0,iW.B)(this.extractTag(e,"difficulty_stars")),...(0,iW.t)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},m=(0,iW.u)(f);return m.success?(i1.debug("Validated successfully via XML tags"),m.data):(i1.warn({validationError:m.error.format()},"Schema validation warning"),f)}async analyzeImage(e,t="image/jpeg",r="zh",n,i,s,o){let a=(0,iz.b)(),l=o?{candidateTags:o}:await (0,iY.i)(i,n),u=(0,iV.generateAnalyzePrompt)(r,n,i,{customTemplate:a.prompts?.analyze,...l},s);i1.box("🔍 AI Image Analysis Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,imageSize:`${e.length} bytes`,mimeType:t,model:this.modelName,language:r,grade:n||"all"}),i1.box("📝 Full Prompt",u);try{let r={model:this.modelName,contents:[{text:u},{inlineData:{data:`[...${e.length} bytes base64 data...]`,mimeType:t}}]};i1.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(r,null,2));let n=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:u},{inlineData:{data:e,mimeType:t}}]}));i1.box("📦 Full API Response Metadata",{usageMetadata:n.usageMetadata});let i=n.text||"";if(i1.box("🤖 AI Raw Response",i),!i)throw Error(n.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");let s=this.parseResponse(i);return i1.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw i1.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,r="zh",n="medium",i,s){let o=(0,iz.b)(),a=(0,iV.generateSimilarQuestionPrompt)(r,e,t,n,{customTemplate:o.prompts?.similar,originalFigureSvg:s},i);i1.box("🎯 Generate Similar Question Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:n,language:r}),i1.box("📝 Full Prompt",a);try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:a})),t=e.text||"";if(i1.box("🤖 AI Raw Response",t),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");let r=this.parseResponse(t);return i1.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,i0.f)(r)}catch(e){throw i1.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,o){let{generateReanswerPrompt:a}=await e.A(730249),l=a(r,t,n,{candidateTags:o},s);i1.info({provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),i1.debug({prompt:l},"Full prompt");try{let e;if(i){let t=i.replace(/^data:image\/\w+;base64,/,"");e=[{text:l},{inlineData:{mimeType:"image/jpeg",data:t}}]}else e=l;let t=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:e})),r=t.text||"";if(i1.debug({rawResponse:r},"AI raw response"),!r)throw Error(t.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");let n=this.extractTag(r,"answer_text")||"",s=this.extractTag(r,"analysis")||"",o=(this.extractTag(r,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),a=this.extractTag(r,"wrong_answer_text")||"",u=this.extractTag(r,"mistake_analysis")||"",c=(0,iZ.f)(this.extractTag(r,"mistake_status"),a);return i1.info("Reanswer parsed successfully"),{answerText:n,analysis:s,knowledgePoints:o,wrongAnswerText:a,mistakeAnalysis:u,mistakeStatus:c,subject:(0,iW.G)(this.extractTag(r,"subject")),difficultyStars:(0,iW.B)(this.extractTag(r,"difficulty_stars"))}}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,r,n){let i=(0,iV.generateGeogebraPrompt)(e,t,r,n);i1.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:i})),t=e.text||"";if(i1.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let s=r.indexOf("{"),o=r.lastIndexOf("}");-1!==s&&-1!==o&&(r=r.substring(s,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,iV.generateMasteryPrompt)(e);i1.info({provider:"Gemini",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),r=e.text||"";if(i1.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iW.r)(r)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async gradeAnswer(e){i1.info({provider:"Gemini"},"Answer Grading Request");try{let t=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:(0,iV.generateGradingPrompt)(e)})),r=t.text||"";if(i1.debug({rawResponse:r},"Grading AI raw response"),!r)throw Error(t.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iW.o)(r)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during answer grading"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,iV.generateTagSuggestPrompt)(e);i1.info({provider:"Gemini",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),n=r.text||"";if(i1.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iW.K)(n,e.allowedTags)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,r){let n=(0,iV.generateFigurePrompt)(r);i1.info({provider:"Gemini",model:this.modelName,imageSize:e.length},"Figure SVG Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:n},{inlineData:{data:e,mimeType:t}}]})),i=r.text||"";if(i1.debug({rawResponse:i},"Figure SVG AI raw response"),!i)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iW.t)(this.extractTag(i,"has_figure"),this.extractTag(i,"figure_svg"))}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,iV.generateLatexFixPrompt)(e);i1.info({provider:"Gemini",model:this.modelName,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:t},{text:"请修复上述内容中的 LaTeX 语法。"}]})),n=r.text||"";if(i1.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iJ.f)(n,e)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,r,n,i="zh"){let s=(0,iV.generateSvgAnimationPrompt)(e,t,r,n,i);i1.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"SVG Animation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:s},{text:iV.SVG_ANIMATION_REQUEST[i]}]})),t=e.text||"";if(i1.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iK.f)(this.extractTag(t,"svg_animation")||t)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(i1.error({error:e},"Gemini error"),e instanceof Error){if(e.message===iQ.z||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],893963)},592938,e=>{e.i(889228);var t=e.i(88045),t=t,r=e.i(405898),n=e.i(261829),i=e.i(983598),s=e.i(798003),o=e.i(999617),a=e.i(459398),l=e.i(50377),u=e.i(93716),c=e.i(630166),d=e.i(115851);let h=(0,l.f)("ai:openai"),p="gpt-6.1-sol";e.s(["a",0,p,"F",0,class{openai;model;baseURL;apiKey;isLongCat;constructor(e){let r=e?.apiKey,n=e?.baseUrl;if(!r)throw Error("AI_AUTH_ERROR: OPENAI_API_KEY is required for OpenAI provider");this.openai=new t.f({apiKey:r,baseURL:n||void 0,defaultHeaders:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}}),this.model=e?.model||p,this.baseURL=n||"https://api.openai.com/v1",this.apiKey=r,this.isLongCat=this.baseURL.includes("longcat.chat"),h.info({provider:"OpenAI",model:this.model,baseURL:this.baseURL,apiKeyPrefix:r.substring(0,8)+"..."},"AI Provider initialized")}adaptMessagesForLongCat(e){return e.map(e=>{if("string"==typeof e.content)return{...e,content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(e=>"image_url"===e.type?{type:"input_image",input_image:{data:[e.image_url.url],type:"url"}}:e);return{...e,content:t}}return e})}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r);if(-1===i)return null;let s=i+r.length,o=e.lastIndexOf(n);return -1===o&&"analysis"===t?(h.warn({tagName:t},"Tag was verified unclosed, treating as truncated and reading to end"),e.substring(s).trim()):-1===o||s>=o?null:e.substring(s,o).trim()}parseResponse(e){h.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),a=this.extractTag(e,"requires_image"),l=this.extractTag(e,"wrong_answer_text")||"",u=this.extractTag(e,"mistake_analysis")||"",d=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw h.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let p="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(p=i);let f=[];s&&(f=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let m=a?.toLowerCase().trim()==="true",g=(0,c.f)(d,l),y={questionText:t,answerText:r,analysis:n,wrongAnswerText:l,mistakeAnalysis:u,mistakeStatus:g,subject:p,knowledgePoints:f,requiresImage:m,difficultyStars:(0,o.B)(this.extractTag(e,"difficulty_stars")),...(0,o.t)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},_=(0,o.u)(y);return _.success?(h.debug("Validated successfully via XML tags"),_.data):(h.warn({validationError:_.error.format()},"Schema validation warning"),y)}async analyzeImage(e,t="image/jpeg",n="zh",i,o,l,c){let d=(0,s.b)(),p=c?{candidateTags:c}:await (0,a.i)(o,i),f=(0,r.generateAnalyzePrompt)(n,i,o,{customTemplate:d.prompts?.analyze,...p},l);h.box("🔍 AI Image Analysis Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,imageSize:`${e.length} bytes`,mimeType:t,model:this.model,language:n,grade:i||"all"}),h.box("📝 Full System Prompt",f);try{let r,n={model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,[...${e.length} bytes base64 data...]`}}]}],max_tokens:8192};if(h.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(n,null,2)),this.isLongCat){let n=this.adaptMessagesForLongCat([{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}]),i=await fetch(`${this.baseURL}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:n,max_tokens:8192})});if(!i.ok){let e=await i.text();throw h.error({status:i.status,body:e},"LongCat API error"),Error(`${i.status} status code (${e})`)}r=await i.json()}else r=await (0,u.V)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.box("📦 Full API Response",JSON.stringify(r,null,2)),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let i=r.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",i),!i)throw Error("Empty response from AI");let s=this.parseResponse(i);return h.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw h.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,n="zh",i="medium",o,a){let l=(0,s.b)(),c=(0,r.generateSimilarQuestionPrompt)(n,e,t,i,{customTemplate:l.prompts?.similar,originalFigureSvg:a},o),p=`
33
+ ${t}`)}return o})(n3);class n9 extends n6{create(e,t){var r;let{api_version:n=this._client.apiVersion}=e,i=rj(e,["api_version"]);if("model"in i&&"agent_config"in i)throw new nx("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in i&&"generation_config"in i)throw new nx("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(n8`/${n}/interactions`,Object.assign(Object.assign({body:i},t),{stream:null!=(r=e.stream)&&r}))}delete(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(n8`/${n}/interactions/${e}`,r)}cancel(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.post(n8`/${n}/interactions/${e}/cancel`,r)}get(e,t={},r){var n;let i=null!=t?t:{},{api_version:s=this._client.apiVersion}=i,o=rj(i,["api_version"]);return this._client.get(n8`/${s}/interactions/${e}`,Object.assign(Object.assign({query:o},r),{stream:null!=(n=null==t?void 0:t.stream)&&n}))}}n9._key=Object.freeze(["interactions"]);class n7 extends n9{}class ie extends n6{create(e,t){let{api_version:r=this._client.apiVersion}=e,n=rj(e,["api_version"]);return this._client.post(n8`/${r}/webhooks`,Object.assign({body:n},t))}update(e,t={},r){let n=null!=t?t:{},{api_version:i=this._client.apiVersion,update_mask:s}=n,o=rj(n,["api_version","update_mask"]);return this._client.patch(n8`/${i}/webhooks/${e}`,Object.assign({query:{update_mask:s},body:o},r))}list(e={},t){let r=null!=e?e:{},{api_version:n=this._client.apiVersion}=r,i=rj(r,["api_version"]);return this._client.get(n8`/${n}/webhooks`,Object.assign({query:i},t))}delete(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(n8`/${n}/webhooks/${e}`,r)}get(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.get(n8`/${n}/webhooks/${e}`,r)}ping(e,t,r){let{api_version:n=this._client.apiVersion,body:i}=null!=t?t:{};return this._client.post(n8`/${n}/webhooks/${e}:ping`,Object.assign({body:i},r))}rotateSigningSecret(e,t={},r){let n=null!=t?t:{},{api_version:i=this._client.apiVersion}=n,s=rj(n,["api_version"]);return this._client.post(n8`/${i}/webhooks/${e}:rotateSigningSecret`,Object.assign({body:s},r))}}ie._key=Object.freeze(["webhooks"]);class it extends ie{}function ir(e){let r;return(null!=t?t:t=(r=new globalThis.TextEncoder).encode.bind(r))(e)}function ii(e){let t;return(null!=r?r:r=(t=new globalThis.TextDecoder).decode.bind(t))(e)}class is{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null,this.searchIndex=0}decode(e){var t;let r;if(null==e)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?ir(e):e;this.buffer=function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}([this.buffer,n]);let i=[];for(;null!=(r=function(e,t){let r,n=null!=t?t:0,i=e.indexOf(10,n),s=e.indexOf(13,n);return -1===i&&-1===s?null:10===e[r=-1!==i&&-1!==s?Math.min(i,s):-1!==i?i:s]?{preceding:r,index:r+1,carriage:!1}:{preceding:r,index:r+1,carriage:!0}}(this.buffer,null!=(t=this.carriageReturnIndex)?t:this.searchIndex));){if(r.carriage&&null==this.carriageReturnIndex){this.carriageReturnIndex=r.index;continue}if(null!=this.carriageReturnIndex&&(r.index!==this.carriageReturnIndex+1||r.carriage)){i.push(ii(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null,this.searchIndex=0;continue}let e=null!==this.carriageReturnIndex?r.preceding-1:r.preceding,t=ii(this.buffer.subarray(0,e));i.push(t),this.buffer=this.buffer.subarray(r.index),this.carriageReturnIndex=null,this.searchIndex=0}return this.searchIndex=Math.max(0,this.buffer.length-1),i}flush(){return this.buffer.length?this.decode("\n"):[]}}is.NEWLINE_CHARS=new Set(["\n","\r"]),is.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let io={off:0,error:200,warn:300,info:400,debug:500},ia=(e,t,r)=>{if(e){if(Object.prototype.hasOwnProperty.call(io,e))return e;ih(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(io))}`)}};function il(){}function iu(e,t,r){return!t||io[e]>io[r]?il:t[e].bind(t)}let ic={error:il,warn:il,info:il,debug:il},id=new WeakMap;function ih(e){var t;let r=e.logger,n=null!=(t=e.logLevel)?t:"off";if(!r)return ic;let i=id.get(r);if(i&&i[0]===n)return i[1];let s={error:iu("error",r,n),warn:iu("warn",r,n),info:iu("info",r,n),debug:iu("debug",r,n)};return id.set(r,[n,s]),s}let ip=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class im{constructor(e,t,r){this.iterator=e,this.controller=t,this.client=r}static fromSSEResponse(e,t,r){let n=!1,i=r?ih(r):console;return new im(function(){return rF(this,arguments,function*(){var r,s,o,a;if(n)throw new nx("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{try{for(var u,c=!0,d=r$(function(e,t){return rF(this,arguments,function*(){var r,n,i,s;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new nx("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new nx("Attempted to iterate over a response with no body")}let o=new ig,a=new is,l=nY(e.body);try{for(var u,c=!0,d=r$(function(e){return rF(this,arguments,function*(){var t,r,n,i;try{for(var s,o=!0,a=r$(e);!(t=(s=yield rG(a.next())).done);o=!0){if(i=s.value,o=!1,null==i)continue;let e=i instanceof ArrayBuffer?new Uint8Array(i):"string"==typeof i?ir(i):i;yield yield rG(e)}}catch(e){r={error:e}}finally{try{!o&&!t&&(n=a.return)&&(yield rG(n.call(a)))}finally{if(r)throw r.error}}})}(l));!(r=(u=yield rG(d.next())).done);c=!0)for(let e of(s=u.value,c=!1,a.decode(s))){let t=o.decode(e);t&&(yield yield rG(t))}}catch(e){n={error:e}}finally{try{!c&&!r&&(i=d.return)&&(yield rG(i.call(d)))}finally{if(n)throw n.error}}for(let e of a.flush()){let t=o.decode(e);t&&(yield yield rG(t))}})}(e,t));!(r=(u=yield rG(d.next())).done);c=!0)if(a=u.value,c=!1,!l)if(a.data.startsWith("[DONE]")){l=!0;continue}else try{yield yield rG(JSON.parse(a.data))}catch(e){throw i.error("Could not parse message into JSON:",a.data),i.error("From chunk:",a.raw),e}}catch(e){s={error:e}}finally{try{!c&&!r&&(o=d.return)&&(yield rG(o.call(d)))}finally{if(s)throw s.error}}l=!0}catch(e){if(nP(e))return yield rG(void 0);throw e}finally{l||t.abort()}})},t,r)}static fromReadableStream(e,t,r){let n=!1;return new im(function(){return rF(this,arguments,function*(){var r,i,s,o;if(n)throw new nx("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{try{for(var l,u=!0,c=r$(function(){return rF(this,arguments,function*(){var t,r,n,i;let s=new is,o=nY(e);try{for(var a,l=!0,u=r$(o);!(t=(a=yield rG(u.next())).done);l=!0)for(let e of(i=a.value,l=!1,s.decode(i)))yield yield rG(e)}catch(e){r={error:e}}finally{try{!l&&!t&&(n=u.return)&&(yield rG(n.call(u)))}finally{if(r)throw r.error}}for(let e of s.flush())yield yield rG(e)})}());!(r=(l=yield rG(c.next())).done);u=!0)o=l.value,u=!1,!a&&o&&(yield yield rG(JSON.parse(o)))}catch(e){i={error:e}}finally{try{!u&&!r&&(s=c.return)&&(yield rG(s.call(c)))}finally{if(i)throw i.error}}a=!0}catch(e){if(nP(e))return yield rG(void 0);throw e}finally{a||t.abort()}})},t,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new im(()=>n(e),this.controller,this.client),new im(()=>n(t),this.controller,this.client)]}toReadableStream(){let e,t=this;return nz({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:n}=await e.next();if(n)return t.close();let i=ir(JSON.stringify(r)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){var t;await (null==(t=e.return)?void 0:t.call(e))}})}}class ig{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){var t;let r;if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,s]=-1!==(r=(t=e).indexOf(":"))?[t.substring(0,r),":",t.substring(r+1)]:[t,"",""];return s.startsWith(" ")&&(s=s.substring(1)),"event"===n?this.event=s:"data"===n&&this.data.push(s),null}}async function iy(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=t,o=await (async()=>{var n;if(t.options.stream)return(ih(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller,e):im.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let i=r.headers.get("content-type"),s=null==(n=null==i?void 0:i.split(";")[0])?void 0:n.trim();if((null==s?void 0:s.includes("application/json"))||(null==s?void 0:s.endsWith("+json"))){if("0"===r.headers.get("content-length"))return;return await r.json()}return await r.text()})();return ih(e).debug(`[${n}] response parsed`,ip({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}class i_ extends Promise{constructor(e,t,r=iy){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,this.client=e}_thenUnwrap(e){return new i_(this.client,this.responsePromise,async(t,r)=>e(await this.parseResponse(t,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}let iE=Symbol("brand.privateNullableHeaders"),iA=e=>{let t=new Headers,r=new Set;for(let n of e){let e=new Set;for(let[i,s]of function*(e){let t;if(!e)return;if(iE in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let n of(e instanceof Headers?t=e.entries():nJ(e)?t=e:(r=!0,t=Object.entries(null!=e?e:{})),t)){let e=n[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=nJ(n[1])?n[1]:[n[1]],i=!1;for(let n of t)void 0!==n&&(r&&!i&&(i=!0,yield[e,null]),yield[e,n])}}(n)){let n=i.toLowerCase();e.has(n)||(t.delete(i),e.add(n)),null===s?(t.delete(i),r.add(n)):(t.append(i,s),r.delete(n))}}return{[iE]:!0,values:t,nulls:r}},iv=e=>{var t,r,n,i,s;return void 0!==globalThis.process?(null==(r=null==(t=globalThis.process.env)?void 0:t[e])?void 0:r.trim())||void 0:void 0!==globalThis.Deno&&(null==(s=null==(i=null==(n=globalThis.Deno.env)?void 0:n.get)?void 0:i.call(n,e))?void 0:s.trim())||void 0};class ib{constructor(e){var t,r,n,i,s,o,a,{baseURL:l=iv("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=null!=(t=iv("GEMINI_API_KEY"))?t:null,apiVersion:c="v1beta"}=e;let d=Object.assign(Object.assign({apiKey:u,apiVersion:c},rj(e,["baseURL","apiKey","apiVersion"])),{baseURL:l||"https://generativelanguage.googleapis.com"});this.baseURL=d.baseURL,this.timeout=null!=(r=d.timeout)?r:ib.DEFAULT_TIMEOUT,this.logger=null!=(n=d.logger)?n:console;let h="warn";this.logLevel=h,this.logLevel=null!=(s=null!=(i=ia(d.logLevel,"ClientOptions.logLevel",this))?i:ia(iv("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))?s:h,this.fetchOptions=d.fetchOptions,this.maxRetries=null!=(o=d.maxRetries)?o:2,this.fetch=null!=(a=d.fetch)?a:function(){if("u">typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),this.encoder=nQ,this._options=d,this.apiKey=u,this.apiVersion=c,this.clientAdapter=d.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.has("authorization")||e.has("x-goog-api-key")||this.apiKey&&e.get("x-goog-api-key"))&&!t.has("x-goog-api-key"))throw Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let t=iA([e.headers]);if(!(t.values.has("authorization")||t.values.has("x-goog-api-key"))){if(this.apiKey)return iA([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter&&this.clientAdapter.isVertexAI())return iA([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new nx(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS 0.0.1`}defaultIdempotencyKey(){return`stainless-node-retry-${nR()}`}makeStatusError(e,t,r,n){return nN.generate(e,t,r,n)}buildURL(e,t,r){let n=!this.baseURLOverridden()&&r||this.baseURL,i=new URL(nV.test(e)?e:n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return nW(s)&&nW(o)||(t=Object.assign(Object.assign(Object.assign({},o),s),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>Object.assign({method:e,path:t},r)))}request(e,t=null){return new i_(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var n,i,s;let o=await e,a=null!=(n=o.maxRetries)?n:this.maxRetries;null==t&&(t=a),await this.prepareOptions(o);let{req:l,url:u,timeout:c}=await this.buildRequest(o,{retryCount:a-t});await this.prepareRequest(l,{url:u,options:o});let d="log_"+(0x1000000*Math.random()|0).toString(16).padStart(6,"0"),h=void 0===r?"":`, retryOf: ${r}`,p=Date.now();if(ih(this).debug(`[${d}] sending request`,ip({retryOfRequestLogID:r,method:o.method,url:u,options:o,headers:l.headers})),null==(i=o.signal)?void 0:i.aborted)throw new nD;let f=new AbortController,m=await this.fetchWithTimeout(u,l,c,f).catch(nk),g=Date.now();if(m instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(null==(s=o.signal)?void 0:s.aborted)throw new nD;let n=nP(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return ih(this).info(`[${d}] connection ${n?"timed out":"failed"} - ${e}`),ih(this).debug(`[${d}] connection ${n?"timed out":"failed"} (${e})`,ip({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),this.retryRequest(o,t,null!=r?r:d);if(ih(this).info(`[${d}] connection ${n?"timed out":"failed"} - error; no more retries left`),ih(this).debug(`[${d}] connection ${n?"timed out":"failed"} (error; no more retries left)`,ip({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),n)throw new nM;throw new nU({cause:m})}let y=`[${d}${h}] ${l.method} ${u} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${g-p}ms`;if(!m.ok){let e=await this.shouldRetry(m);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await nX(m.body),ih(this).info(`${y} - ${e}`),ih(this).debug(`[${d}] response error (${e})`,ip({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),this.retryRequest(o,t,null!=r?r:d,m.headers)}let n=e?"error; no more retries left":"error; not retryable";ih(this).info(`${y} - ${n}`);let i=await m.text().catch(e=>nk(e).message),s=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),a=s?void 0:i;throw ih(this).debug(`[${d}] response error (${n})`,ip({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:a,durationMs:Date.now()-p})),this.makeStatusError(m.status,s,a,m.headers)}return ih(this).info(y),ih(this).debug(`[${d}] response start`,ip({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),{response:m,options:o,controller:f,requestLogID:d,retryOfRequestLogID:r,startTime:p}}async fetchWithTimeout(e,t,r,n){let i=t||{},{signal:s,method:o}=i,a=rj(i,["signal","method"]),l=this._makeAbort(n);s&&s.addEventListener("abort",l,{once:!0});let u=setTimeout(l,r),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,d=Object.assign(Object.assign(Object.assign({signal:n.signal},c?{duplex:"half"}:{}),{method:"GET"}),a);o&&(d.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r,n){var i;let s,o,a=null==n?void 0:n.get("retry-after-ms");if(a){let e=parseFloat(a);Number.isNaN(e)||(s=e)}let l=null==n?void 0:n.get("retry-after");if(l&&!s){let e=parseFloat(l);s=Number.isNaN(e)?Date.parse(l)-Date.now():1e3*e}if(void 0===s){let r=null!=(i=e.maxRetries)?i:this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,r)}return await (o=s,new Promise(e=>setTimeout(e,o))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var r,n,i;let s=Object.assign({},e),{method:o,path:a,query:l,defaultBaseURL:u}=s,c=this.buildURL(a,l,u);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new nx(`${e} must be an integer`);if(t<0)throw new nx(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=null!=(r=s.timeout)?r:this.timeout;let{bodyHeaders:d,body:h}=this.buildBody({options:s}),p=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:o,headers:p},s.signal&&{signal:s.signal}),globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"}),h&&{body:h}),null!=(n=this.fetchOptions)?n:{}),null!=(i=s.fetchOptions)?i:{}),url:c,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let i={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=await this.authHeaders(e),o=iA([i,{Accept:"application/json","User-Agent":this.getUserAgent()},this._options.defaultHeaders,r,e.headers,s]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=iA([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};if("object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)){let t;return{bodyHeaders:void 0,body:(t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator](),nz({start(){},async pull(e){let{done:r,value:n}=await t.next();r?e.close():e.enqueue(n)},async cancel(){var e;await (null==(e=t.return)?void 0:e.call(t))}}))}}return"object"==typeof e&&"application/x-www-form-urlencoded"===r.values.get("content-type")?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:this.encoder({body:e,headers:r})}}ib.DEFAULT_TIMEOUT=6e4;class iw extends ib{constructor(){super(...arguments),this.interactions=new n7(this),this.webhooks=new it(this)}}iw.GeminiNextGenAPIClient=iw,iw.GeminiNextGenAPIClientError=nx,iw.APIError=nN,iw.APIConnectionError=nU,iw.APIConnectionTimeoutError=nM,iw.APIUserAbortError=nD,iw.NotFoundError=nF,iw.ConflictError=n$,iw.RateLimitError=nB,iw.BadRequestError=nL,iw.AuthenticationError=nj,iw.InternalServerError=nH,iw.PermissionDeniedError=nG,iw.UnprocessableEntityError=nq,iw.toFile=n2,iw.Interactions=n7,iw.Webhooks=it;let iT="x-goog-api-key",iI="https://www.googleapis.com/auth/cloud-platform";class iS{constructor(e){if(void 0!==e.apiKey){this.apiKey=e.apiKey;return}let t=function(e){let t;if(!e)return{scopes:[iI]};if((t=e).scopes){if("string"==typeof t.scopes&&t.scopes!==iI||Array.isArray(t.scopes)&&0>t.scopes.indexOf(iI))throw Error(`Invalid auth scopes. Scopes must include: ${iI}`)}else t.scopes=[iI];return t}(e.googleAuthOptions);this.googleAuth=new tv.GoogleAuth(t)}async addAuthHeaders(e,t){if(void 0!==this.apiKey){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(null===e.get(iT)){if(void 0===this.apiKey)throw Error("Trying to set API key header but apiKey is not set");e.append(iT,this.apiKey)}}async addGoogleAuthHeaders(e,t){if(void 0===this.googleAuth)throw Error("Trying to set google-auth headers but googleAuth is unset");for(let[r,n]of(await this.googleAuth.getRequestHeaders(t)))null===e.get(r)&&e.append(r,n)}}class iO{async download(e,t){if(e.downloadPath){let r=await iC(e,t);if(r instanceof tD){let t=(0,tb.createWriteStream)(e.downloadPath);tT.Readable.fromWeb(r.responseInternal.body).pipe(t),await (0,tI.finished)(t)}else try{await (0,tw.writeFile)(e.downloadPath,r,{encoding:"base64"})}catch(t){throw Error(`Failed to write file to ${e.downloadPath}: ${t}`)}}}}async function iC(e,t){var r,n,i;let s=rb(e.file);if(void 0!==s)return await t.request({path:`files/${s}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:null==(r=e.config)?void 0:r.httpOptions,abortSignal:null==(n=e.config)?void 0:n.abortSignal});if(rA(e.file)){let t=null==(i=e.file.video)?void 0:i.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download generated video, Uri or videoBytes not found.")}if(rv(e.file)){let t=e.file.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download video, Uri or videoBytes not found.")}throw Error("Unsupported file type")}class iR{create(e,t,r){return new iP(e,t,r)}}class iP{constructor(e,t,r){this.url=e,this.headers=t,this.callbacks=r}connect(){this.ws=new tS.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.close()}}function ik(e,t){let r={},n=tk(e,["sdkHttpResponse"]);null!=n&&tP(r,["sdkHttpResponse"],n);let i=tk(e,["name"]);null!=i&&tP(r,["name"],i);let s=tk(e,["state"]);null!=s&&tP(r,["state"],rE(s));let o=tk(e,["createTime"]);null!=o&&tP(r,["createTime"],o);let a=tk(e,["startTime"]);null!=a&&tP(r,["startTime"],a);let l=tk(e,["endTime"]);null!=l&&tP(r,["endTime"],l);let u=tk(e,["updateTime"]);null!=u&&tP(r,["updateTime"],u);let c=tk(e,["error"]);null!=c&&tP(r,["error"],c);let d=tk(e,["description"]);null!=d&&tP(r,["description"],d);let h=tk(e,["baseModel"]);null!=h&&tP(r,["baseModel"],h);let p=tk(e,["tunedModel"]);null!=p&&tP(r,["tunedModel"],p);let f=tk(e,["preTunedModel"]);null!=f&&tP(r,["preTunedModel"],f);let m=tk(e,["supervisedTuningSpec"]);null!=m&&tP(r,["supervisedTuningSpec"],m);let g=tk(e,["preferenceOptimizationSpec"]);null!=g&&tP(r,["preferenceOptimizationSpec"],g);let y=tk(e,["distillationSpec"]);null!=y&&tP(r,["distillationSpec"],y);let _=tk(e,["tuningDataStats"]);null!=_&&tP(r,["tuningDataStats"],_);let E=tk(e,["encryptionSpec"]);null!=E&&tP(r,["encryptionSpec"],E);let A=tk(e,["partnerModelTuningSpec"]);null!=A&&tP(r,["partnerModelTuningSpec"],A);let v=tk(e,["customBaseModel"]);null!=v&&tP(r,["customBaseModel"],v);let b=tk(e,["evaluateDatasetRuns"]);if(null!=b){let e=b;Array.isArray(e)&&(e=e.map(e=>e)),tP(r,["evaluateDatasetRuns"],e)}let w=tk(e,["experiment"]);null!=w&&tP(r,["experiment"],w);let T=tk(e,["fullFineTuningSpec"]);null!=T&&tP(r,["fullFineTuningSpec"],T);let I=tk(e,["labels"]);null!=I&&tP(r,["labels"],I);let S=tk(e,["outputUri"]);null!=S&&tP(r,["outputUri"],S);let O=tk(e,["pipelineJob"]);null!=O&&tP(r,["pipelineJob"],O);let C=tk(e,["serviceAccount"]);null!=C&&tP(r,["serviceAccount"],C);let R=tk(e,["tunedModelDisplayName"]);null!=R&&tP(r,["tunedModelDisplayName"],R);let P=tk(e,["tuningJobState"]);null!=P&&tP(r,["tuningJobState"],P);let k=tk(e,["veoTuningSpec"]);null!=k&&tP(r,["veoTuningSpec"],k);let x=tk(e,["distillationSamplingSpec"]);null!=x&&tP(r,["distillationSamplingSpec"],x);let N=tk(e,["tuningJobMetadata"]);return null!=N&&tP(r,["tuningJobMetadata"],N),r}function ix(e,t){let r={},n=tk(e,["gcsUri"]);null!=n&&tP(r,["validationDatasetUri"],n);let i=tk(e,["vertexDatasetResource"]);return null!=i&&tP(r,["validationDatasetUri"],i),r}class iN extends tC{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rN(tE.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI())if(e.baseModel.startsWith("projects/")){let r={tunedModelName:e.baseModel};(null==(t=e.config)?void 0:t.preTunedModelCheckpointId)&&(r.checkpointId=e.config.preTunedModelCheckpointId);let n=Object.assign(Object.assign({},e),{preTunedModel:r});return n.baseModel=void 0,await this.tuneInternal(n)}else{let t=Object.assign({},e);return await this.tuneInternal(t)}{let t=Object.assign({},e),r=await this.tuneMldevInternal(t),n="";return void 0!==r.metadata&&void 0!==r.metadata.tunedModel?n=r.metadata.tunedModel:void 0!==r.name&&r.name.includes("/operations/")&&(n=r.name.split("/operations/")[0]),{name:n,state:eK.JOB_STATE_QUEUED}}}}async getInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],i),n);return s=tR("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ik(e))}{let t,r,a=(t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],r),t);return s=tR("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s,o,a,l,u,c,d,h,p,f;return t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),null!=(n=tk(e,["name"]))&&tP(t,["name"],n),null!=(i=tk(e,["state"]))&&tP(t,["state"],rE(i)),null!=(s=tk(e,["createTime"]))&&tP(t,["createTime"],s),null!=(o=tk(e,["tuningTask","startTime"]))&&tP(t,["startTime"],o),null!=(a=tk(e,["tuningTask","completeTime"]))&&tP(t,["endTime"],a),null!=(l=tk(e,["updateTime"]))&&tP(t,["updateTime"],l),null!=(u=tk(e,["description"]))&&tP(t,["description"],u),null!=(c=tk(e,["baseModel"]))&&tP(t,["baseModel"],c),null!=(d=tk(e,["_self"]))&&tP(t,["tunedModel"],(h={},null!=(p=tk(d,["name"]))&&tP(h,["model"],p),null!=(f=tk(d,["name"]))&&tP(h,["endpoint"],f),h)),t})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l,u,c=(s={},null!=(o=tk(e,["config"]))&&(a=tk(o,["pageSize"]),void 0!==s&&null!=a&&tP(s,["_query","pageSize"],a),l=tk(o,["pageToken"]),void 0!==s&&null!=l&&tP(s,["_query","pageToken"],l),u=tk(o,["filter"]),void 0!==s&&null!=u&&tP(s,["_query","filter"],u)),s);return n=tR("tuningJobs",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=tk(e,["sdkHttpResponse"]);null!=r&&tP(t,["sdkHttpResponse"],r);let n=tk(e,["nextPageToken"]);null!=n&&tP(t,["nextPageToken"],n);let i=tk(e,["tuningJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>ik(e))),tP(t,["tuningJobs"],e)}return t}(e),r=new tJ;return Object.assign(r,t),r})}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async cancel(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=tk(e,["name"]))&&tP(n,["_url","name"],i),n);return s=tR("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tW;return Object.assign(i,n),i})}{let t,r,a=(t={},null!=(r=tk(e,["name"]))&&tP(t,["_url","name"],r),t);return s=tR("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),t),i=new tW;return Object.assign(i,n),i})}}async tuneInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l,u,c=(s={},null!=(o=tk(e,["baseModel"]))&&tP(s,["baseModel"],o),null!=(a=tk(e,["preTunedModel"]))&&tP(s,["preTunedModel"],a),null!=(l=tk(e,["trainingDataset"]))&&function(e,t,r){let n=tk(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=tk(e,["gcsUri"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===n){let r=tk(e,["gcsUri"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}else if("DISTILLATION"===n){let r=tk(e,["gcsUri"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","promptDatasetUri"],r)}let i=tk(r,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){let r=tk(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===i){let r=tk(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}else if("DISTILLATION"===i){let r=tk(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","promptDatasetUri"],r)}if(void 0!==tk(e,["examples"]))throw Error("examples parameter is not supported in Gemini Enterprise Agent Platform (previously known as Vertex AI).")}(l,s,e),null!=(u=tk(e,["config"]))&&function(e,t,r){let n=tk(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=tk(e,["validationDataset"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec"],ix(r))}else if("PREFERENCE_TUNING"===n){let r=tk(e,["validationDataset"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec"],ix(r))}else if("DISTILLATION"===n){let r=tk(e,["validationDataset"]);void 0!==t&&null!=r&&tP(t,["distillationSpec"],ix(r))}let i=tk(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&tP(t,["tunedModelDisplayName"],i);let s=tk(e,["description"]);void 0!==t&&null!=s&&tP(t,["description"],s);let o=tk(r,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){let r=tk(e,["epochCount"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","epochCount"],r)}else if("PREFERENCE_TUNING"===o){let r=tk(e,["epochCount"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],r)}else if("DISTILLATION"===o){let r=tk(e,["epochCount"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","epochCount"],r)}let a=tk(r,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){let r=tk(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],r)}else if("PREFERENCE_TUNING"===a){let r=tk(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],r)}else if("DISTILLATION"===a){let r=tk(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","learningRateMultiplier"],r)}let l=tk(r,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){let r=tk(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","exportLastCheckpointOnly"],r)}else if("PREFERENCE_TUNING"===l){let r=tk(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],r)}else if("DISTILLATION"===l){let r=tk(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","exportLastCheckpointOnly"],r)}let u=tk(r,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){let r=tk(e,["adapterSize"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","adapterSize"],r)}else if("PREFERENCE_TUNING"===u){let r=tk(e,["adapterSize"]);void 0!==t&&null!=r&&tP(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],r)}else if("DISTILLATION"===u){let r=tk(e,["adapterSize"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","adapterSize"],r)}let c=tk(r,["config","method"]);if(void 0===c&&(c="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===c){let r=tk(e,["tuningMode"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","tuningMode"],r)}else if("DISTILLATION"===c){let r=tk(e,["tuningMode"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","tuningMode"],r)}let d=tk(e,["customBaseModel"]);void 0!==t&&null!=d&&tP(t,["customBaseModel"],d);let h=tk(r,["config","method"]);if(void 0===h&&(h="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===h){let r=tk(e,["batchSize"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","batchSize"],r)}else if("DISTILLATION"===h){let r=tk(e,["batchSize"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","batchSize"],r)}let p=tk(r,["config","method"]);if(void 0===p&&(p="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===p){let r=tk(e,["learningRate"]);void 0!==t&&null!=r&&tP(t,["supervisedTuningSpec","hyperParameters","learningRate"],r)}else if("DISTILLATION"===p){let r=tk(e,["learningRate"]);void 0!==t&&null!=r&&tP(t,["distillationSpec","hyperParameters","learningRate"],r)}let f=tk(e,["labels"]);void 0!==t&&null!=f&&tP(t,["labels"],f);let m=tk(e,["beta"]);void 0!==t&&null!=m&&tP(t,["preferenceOptimizationSpec","hyperParameters","beta"],m);let g=tk(e,["baseTeacherModel"]);void 0!==t&&null!=g&&tP(t,["distillationSpec","baseTeacherModel"],g);let y=tk(e,["tunedTeacherModelSource"]);void 0!==t&&null!=y&&tP(t,["distillationSpec","tunedTeacherModelSource"],y);let _=tk(e,["sftLossWeightMultiplier"]);void 0!==t&&null!=_&&tP(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],_);let E=tk(e,["outputUri"]);void 0!==t&&null!=E&&tP(t,["outputUri"],E);let A=tk(e,["encryptionSpec"]);void 0!==t&&null!=A&&tP(t,["encryptionSpec"],A)}(u,s,e),s);return n=tR("tuningJobs",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ik(e))}throw Error("This method is only supported by the Gemini Enterprise Agent Platform (previously known as Vertex AI).")}async tuneMldevInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u,c=(s={},null!=(o=tk(e,["baseModel"]))&&tP(s,["baseModel"],o),null!=(a=tk(e,["preTunedModel"]))&&tP(s,["preTunedModel"],a),null!=(l=tk(e,["trainingDataset"]))&&function(e){if(void 0!==tk(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==tk(e,["vertexDatasetResource"]))throw Error("vertexDatasetResource parameter is not supported in Gemini API.");let t=tk(e,["examples"]);if(null!=t){let e=t;Array.isArray(e)&&(e=e.map(e=>e)),tP({},["examples","examples"],e)}}(l),null!=(u=tk(e,["config"]))&&function(e,t){if(void 0!==tk(e,["validationDataset"]))throw Error("validationDataset parameter is not supported in Gemini API.");let r=tk(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=r&&tP(t,["displayName"],r),void 0!==tk(e,["description"]))throw Error("description parameter is not supported in Gemini API.");let n=tk(e,["epochCount"]);void 0!==t&&null!=n&&tP(t,["tuningTask","hyperparameters","epochCount"],n);let i=tk(e,["learningRateMultiplier"]);if(null!=i&&tP({},["tuningTask","hyperparameters","learningRateMultiplier"],i),void 0!==tk(e,["exportLastCheckpointOnly"]))throw Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(void 0!==tk(e,["preTunedModelCheckpointId"]))throw Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(void 0!==tk(e,["adapterSize"]))throw Error("adapterSize parameter is not supported in Gemini API.");if(void 0!==tk(e,["tuningMode"]))throw Error("tuningMode parameter is not supported in Gemini API.");if(void 0!==tk(e,["customBaseModel"]))throw Error("customBaseModel parameter is not supported in Gemini API.");let s=tk(e,["batchSize"]);void 0!==t&&null!=s&&tP(t,["tuningTask","hyperparameters","batchSize"],s);let o=tk(e,["learningRate"]);if(void 0!==t&&null!=o&&tP(t,["tuningTask","hyperparameters","learningRate"],o),void 0!==tk(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");if(void 0!==tk(e,["beta"]))throw Error("beta parameter is not supported in Gemini API.");if(void 0!==tk(e,["baseTeacherModel"]))throw Error("baseTeacherModel parameter is not supported in Gemini API.");if(void 0!==tk(e,["tunedTeacherModelSource"]))throw Error("tunedTeacherModelSource parameter is not supported in Gemini API.");if(void 0!==tk(e,["sftLossWeightMultiplier"]))throw Error("sftLossWeightMultiplier parameter is not supported in Gemini API.");if(void 0!==tk(e,["outputUri"]))throw Error("outputUri parameter is not supported in Gemini API.");if(void 0!==tk(e,["encryptionSpec"]))throw Error("encryptionSpec parameter is not supported in Gemini API.")}(u,s),s);return n=tR("tunedModels",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s,o;return t={},null!=(r=tk(e,["sdkHttpResponse"]))&&tP(t,["sdkHttpResponse"],r),null!=(n=tk(e,["name"]))&&tP(t,["name"],n),null!=(i=tk(e,["metadata"]))&&tP(t,["metadata"],i),null!=(s=tk(e,["done"]))&&tP(t,["done"],s),null!=(o=tk(e,["error"]))&&tP(t,["error"],o),t})}}}let iD="x-goog-upload-status";async function iU(e,t,r,n){var i;let s=await iL(e,t,r,n),o=await (null==s?void 0:s.json());if((null==(i=null==s?void 0:s.headers)?void 0:i[iD])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return o.file}async function iM(e,t,r,n){var i;let s=await iL(e,t,r,n),o=await (null==s?void 0:s.json());if((null==(i=null==s?void 0:s.headers)?void 0:i[iD])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let a=tN(o),l=new t9;return Object.assign(l,a),l}async function iL(e,t,r,n){var i,s,o;let a=t,l=(null==n?void 0:n.baseUrl)||(null==(i=r.clientOptions.httpOptions)?void 0:i.baseUrl);if(l){let e=new URL(l),r=new URL(t);r.protocol=e.protocol,r.host=e.host,r.port=e.port,a=r.toString()}let u=0,c=0,d=new tD(new Response),h="upload";for(u=e.size;c<u;){let t=Math.min(8388608,u-c),i=e.slice(c,c+t);c+t>=u&&(h+=", finalize");let l=0,p=1e3;for(;l<3;){let e=Object.assign(Object.assign({},(null==n?void 0:n.headers)||{}),{"X-Goog-Upload-Command":h,"X-Goog-Upload-Offset":String(c),"Content-Length":String(t)});if(null==(s=null==(d=await r.request({path:"",body:i,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n),{apiVersion:"",baseUrl:a,headers:e})}))?void 0:d.headers)?void 0:s[iD])break;l++,await iG(p),p*=2}if(c+=t,(null==(o=null==d?void 0:d.headers)?void 0:o[iD])!=="active")break;if(u<=c)throw Error("All content has been uploaded, but the upload status is not finalized.")}return d}async function ij(e){return{size:e.size,type:e.type}}function iG(e){return new Promise(t=>setTimeout(t,e))}class iF{async stat(e){let t={size:0,type:void 0};return"string"==typeof e?(t.size=(await tw.stat(e)).size,t.type=this.inferMimeType(e),t):await ij(e)}async upload(e,t,r,n){return"string"==typeof e?await this.uploadFileFromPath(e,t,r,n):iU(e,t,r,n)}async uploadToFileSearchStore(e,t,r,n){return"string"==typeof e?await this.uploadFileToFileSearchStoreFromPath(e,t,r,n):iM(e,t,r,n)}inferMimeType(e){return({aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"})[e.slice(e.lastIndexOf(".")+1).toLowerCase()]}async uploadFileFromPath(e,t,r,n){var i;let s=await this.uploadFileFromPathInternal(e,t,r,n),o=await (null==s?void 0:s.json());if((null==(i=null==s?void 0:s.headers)?void 0:i[iD])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return o.file}async uploadFileToFileSearchStoreFromPath(e,t,r,n){var i;let s=await this.uploadFileFromPathInternal(e,t,r,n),o=await (null==s?void 0:s.json());if((null==(i=null==s?void 0:s.headers)?void 0:i[iD])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let a=tN(o),l=new t9;return Object.assign(l,a),l}async uploadFileFromPathInternal(e,t,r,n){var i,s,o;let a,l=t,u=(null==n?void 0:n.baseUrl)||(null==(i=r.clientOptions.httpOptions)?void 0:i.baseUrl);if(u){let e=new URL(u),r=new URL(t);r.protocol=e.protocol,r.host=e.host,r.port=e.port,l=r.toString()}let c=0,d=0,h=new tD(new Response),p="upload",f=tO.basename(e);try{if(!(a=await tw.open(e,"r")))throw Error("Failed to open file");for(c=(await a.stat()).size;d<c;){let e=Math.min(8388608,c-d);d+e>=c&&(p+=", finalize");let t=new Uint8Array(e),{bytesRead:i}=await a.read(t,0,e,d);if(i!==e)throw Error(`Failed to read ${e} bytes from file at offset ${d}. bytes actually read: ${i}`);let u=new Blob([t]),m=0,g=1e3;for(;m<3;){let e=Object.assign(Object.assign({},(null==n?void 0:n.headers)||{}),{"X-Goog-Upload-Command":p,"X-Goog-Upload-Offset":String(d),"Content-Length":String(i),"X-Goog-Upload-File-Name":f});if(null==(s=null==(h=await r.request({path:"",body:u,httpMethod:"POST",httpOptions:Object.assign(Object.assign({},n),{apiVersion:"",baseUrl:l,headers:e})}))?void 0:h.headers)?void 0:s[iD])break;m++,await iG(g),g*=2}if(d+=i,(null==(o=null==h?void 0:h.headers)?void 0:o[iD])!=="active")break;if(c<=d)throw Error("All content has been uploaded, but the upload status is not finalized.")}return h}finally{a&&await a.close()}}}class i$ extends rJ{async registerFiles(e){if("u"<typeof process||!process.versions||!process.versions.node)throw Error("registerFiles is only supported in Node.js environments.");let t=e.auth,r=await t.getRequestHeaders(),n=e.config||{},i=n.httpOptions||{},s=Object.assign({},i.headers||{});if(r)if("function"==typeof r[Symbol.iterator])for(let[e,t]of r)s[e]=t;else for(let[e,t]of Object.entries(r))s[e]=t;return this._registerFiles({uris:e.uris,config:Object.assign(Object.assign({},n),{httpOptions:Object.assign(Object.assign({},i),{headers:s})})})}}class iq{getNextGenClient(){var e;let t=this.httpOptions;return void 0===this._nextGenClient&&(this._nextGenClient=new iw({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:null==t?void 0:t.timeout,maxRetries:null==(e=null==t?void 0:t.retryOptions)?void 0:e.attempts})),(null==t?void 0:t.extraBody)&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored."),this._nextGenClient}get interactions(){return void 0!==this._interactions||(console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."),this._interactions=this.getNextGenClient().interactions),this._interactions}get webhooks(){return void 0!==this._webhooks||(this._webhooks=this.getNextGenClient().webhooks),this._webhooks}constructor(e){var t,r,s,o;let a,l;if((e.project||e.location)&&e.apiKey)throw Error("Project/location and API key are mutually exclusive in the client initializer.");this.vertexai=function(e){var t;if(void 0!==e.enterprise||void 0!==e.vertexai){if(void 0!==e.enterprise&&void 0!==e.vertexai&&e.enterprise!==e.vertexai)throw Error("enterprise and vertexAI flags have conflicting values, please set enterprise value only.");return null!=(t=e.enterprise)?t:e.vertexai}let r=iB("GOOGLE_GENAI_USE_ENTERPRISE"),n=iB("GOOGLE_GENAI_USE_VERTEXAI"),i=iH(r),s=iH(n);return(void 0!==r&&void 0!==n&&i!==s&&console.warn("Warning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used."),void 0!==r)?i:void 0!==n&&s}(e);let u=(a=iB("GOOGLE_API_KEY"),l=iB("GEMINI_API_KEY"),a&&l&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),a||l||void 0),c=iB("GOOGLE_CLOUD_PROJECT"),d=iB("GOOGLE_CLOUD_LOCATION");this.apiKey=null!=(t=e.apiKey)?t:u,this.project=null!=(r=e.project)?r:c,this.location=null!=(s=e.location)?s:d,this.vertexai||this.apiKey||console.warn("API key should be set when using the Gemini API."),this.vertexai&&((null==(o=e.googleAuthOptions)?void 0:o.credentials)&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),(c||d)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&u?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):(c||d)&&u&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),this.location||this.apiKey||(this.location="global"));let h=function(e,t,r,s){return(null==e?void 0:e.baseUrl)?e.baseUrl:t?null!=i?i:r:null!=n?n:s}(e.httpOptions,this.vertexai,iB("GOOGLE_VERTEX_BASE_URL"),iB("GOOGLE_GEMINI_BASE_URL"));h&&(e.httpOptions?e.httpOptions.baseUrl=h:e.httpOptions={baseUrl:h}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;let p=new iS({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new na({auth:p,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/"+process.version,uploader:new iF,downloader:new iO}),this.models=new nw(this.apiClient),this.live=new ng(this.apiClient,p,new iR),this.batches=new rD(this.apiClient),this.chats=new rH(this.models,this.apiClient),this.caches=new rL(this.apiClient),this.files=new i$(this.apiClient),this.operations=new nT(this.apiClient),this.authTokens=new nS(this.apiClient),this.tunings=new iN(this.apiClient),this.fileSearchStores=new nC(this.apiClient)}}function iB(e){var t,r,n;return null!=(n=null==(r=null==(t=null==process?void 0:process.env)?void 0:t[e])?void 0:r.trim())?n:void 0}function iH(e){return void 0!==e&&"true"===e.toLowerCase()}var iV=e.i(405898),iK=e.i(261829),iJ=e.i(983598),iW=e.i(999617),iz=e.i(798003),iY=e.i(459398),iX=e.i(50377),iQ=e.i(93716),iZ=e.i(630166),i0=e.i(115851);let i1=(0,iX.f)("ai:gemini");e.s(["f",0,class{ai;modelName;baseUrl;constructor(e){let t=e?.apiKey,r=e?.baseUrl;if(!t)throw Error("AI_AUTH_ERROR: GOOGLE_API_KEY is required for Gemini provider");this.ai=new iq({apiKey:t,httpOptions:r?{baseUrl:r}:void 0}),this.modelName=e?.model||"gemini-2.0-flash",this.baseUrl=r||"https://generativelanguage.googleapis.com",i1.info({provider:"Gemini",model:this.modelName,baseUrl:this.baseUrl,apiKeyPrefix:t.substring(0,8)+"..."},"AI Provider initialized")}async retryOperation(e,t=3){let r;for(let n=1;n<=t;n++)try{return await e()}catch(s){r=s;let e=s instanceof Error?s.message.toLowerCase():String(s);if(!(e.includes("fetch failed")||e.includes("network")||e.includes("connect")||e.includes("503")||e.includes("502")||e.includes("504")||e.includes("overloaded")||e.includes("timeout")||e.includes("etimedout")||e.includes("enotfound")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("unavailable"))||n===t)throw s;let i=1e3*Math.pow(2,n-1);i1.warn({attempt:n,maxRetries:t,error:e,nextRetryDelayMs:i},"Gemini operation failed, retrying..."),await new Promise(e=>setTimeout(e,i))}throw r}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r),s=e.lastIndexOf(n);return -1===i||-1===s||i>=s?null:e.substring(i+r.length,s).trim()}parseResponse(e){i1.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),o=this.extractTag(e,"requires_image"),a=this.extractTag(e,"wrong_answer_text")||"",l=this.extractTag(e,"mistake_analysis")||"",u=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw i1.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let c="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(c=i);let d=[];s&&(d=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let h=o?.toLowerCase().trim()==="true",p=(0,iZ.f)(u,a),f={questionText:t,answerText:r,analysis:n,wrongAnswerText:a,mistakeAnalysis:l,mistakeStatus:p,subject:c,knowledgePoints:d,requiresImage:h,difficultyStars:(0,iW.B)(this.extractTag(e,"difficulty_stars")),...(0,iW.t)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},m=(0,iW.u)(f);return m.success?(i1.debug("Validated successfully via XML tags"),m.data):(i1.warn({validationError:m.error.format()},"Schema validation warning"),f)}async analyzeImage(e,t="image/jpeg",r="zh",n,i,s,o){let a=(0,iz.b)(),l=o?{candidateTags:o}:await (0,iY.i)(i,n),u=(0,iV.generateAnalyzePrompt)(r,n,i,{customTemplate:a.prompts?.analyze,...l},s);i1.box("🔍 AI Image Analysis Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,imageSize:`${e.length} bytes`,mimeType:t,model:this.modelName,language:r,grade:n||"all"}),i1.box("📝 Full Prompt",u);try{let r={model:this.modelName,contents:[{text:u},{inlineData:{data:`[...${e.length} bytes base64 data...]`,mimeType:t}}]};i1.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(r,null,2));let n=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:u},{inlineData:{data:e,mimeType:t}}]}));i1.box("📦 Full API Response Metadata",{usageMetadata:n.usageMetadata});let i=n.text||"";if(i1.box("🤖 AI Raw Response",i),!i)throw Error(n.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");let s=this.parseResponse(i);return i1.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw i1.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,r="zh",n="medium",i,s){let o=(0,iz.b)(),a=(0,iV.generateSimilarQuestionPrompt)(r,e,t,n,{customTemplate:o.prompts?.similar,originalFigureSvg:s},i);i1.box("🎯 Generate Similar Question Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:n,language:r}),i1.box("📝 Full Prompt",a);try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:a})),t=e.text||"";if(i1.box("🤖 AI Raw Response",t),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");let r=this.parseResponse(t);return i1.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,i0.f)(r)}catch(e){throw i1.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,o){let{generateReanswerPrompt:a}=await e.A(730249),l=a(r,t,n,{candidateTags:o},s);i1.info({provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),i1.debug({prompt:l},"Full prompt");try{let e;if(i){let t=i.replace(/^data:image\/\w+;base64,/,"");e=[{text:l},{inlineData:{mimeType:"image/jpeg",data:t}}]}else e=l;let t=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:e})),r=t.text||"";if(i1.debug({rawResponse:r},"AI raw response"),!r)throw Error(t.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");let n=this.extractTag(r,"answer_text")||"",s=this.extractTag(r,"analysis")||"",o=(this.extractTag(r,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),a=this.extractTag(r,"wrong_answer_text")||"",u=this.extractTag(r,"mistake_analysis")||"",c=(0,iZ.f)(this.extractTag(r,"mistake_status"),a);return i1.info("Reanswer parsed successfully"),{answerText:n,analysis:s,knowledgePoints:o,wrongAnswerText:a,mistakeAnalysis:u,mistakeStatus:c,subject:(0,iW.G)(this.extractTag(r,"subject")),difficultyStars:(0,iW.B)(this.extractTag(r,"difficulty_stars"))}}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,r,n){let i=(0,iV.generateGeogebraPrompt)(e,t,r,n);i1.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:i})),t=e.text||"";if(i1.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let s=r.indexOf("{"),o=r.lastIndexOf("}");-1!==s&&-1!==o&&(r=r.substring(s,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,iV.generateMasteryPrompt)(e);i1.info({provider:"Gemini",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),r=e.text||"";if(i1.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iW.r)(r)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async gradeAnswer(e){i1.info({provider:"Gemini"},"Answer Grading Request");try{let t=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:(0,iV.generateGradingPrompt)(e)})),r=t.text||"";if(i1.debug({rawResponse:r},"Grading AI raw response"),!r)throw Error(t.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iW.o)(r)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during answer grading"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,iV.generateTagSuggestPrompt)(e);i1.info({provider:"Gemini",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),n=r.text||"";if(i1.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iW.K)(n,e.allowedTags)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,r){let n=(0,iV.generateFigurePrompt)(r);i1.info({provider:"Gemini",model:this.modelName,imageSize:e.length},"Figure SVG Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:n},{inlineData:{data:e,mimeType:t}}]})),i=r.text||"";if(i1.debug({rawResponse:i},"Figure SVG AI raw response"),!i)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iW.t)(this.extractTag(i,"has_figure"),this.extractTag(i,"figure_svg"))}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,iV.generateLatexFixPrompt)(e);i1.info({provider:"Gemini",model:this.modelName,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:t},{text:"请修复上述内容中的 LaTeX 语法。"}]})),n=r.text||"";if(i1.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iJ.f)(n,e)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,r,n,i="zh"){let s=(0,iV.generateSvgAnimationPrompt)(e,t,r,n,i);i1.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"SVG Animation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:s},{text:iV.SVG_ANIMATION_REQUEST[i]}]})),t=e.text||"";if(i1.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iQ.z:"Empty response from AI");return(0,iK.f)(this.extractTag(t,"svg_animation")||t)}catch(e){throw i1.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(i1.error({error:e},"Gemini error"),e instanceof Error){if(e.message===iQ.z||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],893963)},59116,e=>{var t=e.i(690604),r=e.i(61221),n=e.i(238712),i=e.i(133458);e.s(["f",0,class{model;constructor(e){this.model=e?.model?.trim()||i.f}run(e){return(0,n.r)(n=>e(new t.R({authToken:n,baseUrl:r.j,model:this.model})))}analyzeImage(...e){return this.run(t=>t.analyzeImage(...e))}generateSimilarQuestion(...e){return this.run(t=>t.generateSimilarQuestion(...e))}generateFigureSvg(...e){return this.run(t=>t.generateFigureSvg(...e))}reanswerQuestion(...e){return this.run(t=>t.reanswerQuestion(...e))}analyzeForGeogebra(...e){return this.run(t=>t.analyzeForGeogebra(...e))}fixLatex(...e){return this.run(t=>t.fixLatex(...e))}generateSvgAnimation(...e){return this.run(t=>t.generateSvgAnimation(...e))}evaluateMastery(...e){return this.run(t=>t.evaluateMastery(...e))}gradeAnswer(...e){return this.run(t=>t.gradeAnswer(...e))}suggestKnowledgeTags(...e){return this.run(t=>t.suggestKnowledgeTags(...e))}}])},592938,e=>{e.i(889228);var t=e.i(88045),t=t,r=e.i(405898),n=e.i(261829),i=e.i(983598),s=e.i(798003),o=e.i(999617),a=e.i(459398),l=e.i(50377),u=e.i(93716),c=e.i(630166),d=e.i(115851);let h=(0,l.f)("ai:openai"),p="gpt-6.1-sol";e.s(["a",0,p,"F",0,class{openai;model;baseURL;apiKey;isLongCat;constructor(e){let r=e?.apiKey,n=e?.baseUrl;if(!r)throw Error("AI_AUTH_ERROR: OPENAI_API_KEY is required for OpenAI provider");this.openai=new t.f({apiKey:r,baseURL:n||void 0,defaultHeaders:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}}),this.model=e?.model||p,this.baseURL=n||"https://api.openai.com/v1",this.apiKey=r,this.isLongCat=this.baseURL.includes("longcat.chat"),h.info({provider:"OpenAI",model:this.model,baseURL:this.baseURL,apiKeyPrefix:r.substring(0,8)+"..."},"AI Provider initialized")}adaptMessagesForLongCat(e){return e.map(e=>{if("string"==typeof e.content)return{...e,content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(e=>"image_url"===e.type?{type:"input_image",input_image:{data:[e.image_url.url],type:"url"}}:e);return{...e,content:t}}return e})}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r);if(-1===i)return null;let s=i+r.length,o=e.lastIndexOf(n);return -1===o&&"analysis"===t?(h.warn({tagName:t},"Tag was verified unclosed, treating as truncated and reading to end"),e.substring(s).trim()):-1===o||s>=o?null:e.substring(s,o).trim()}parseResponse(e){h.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),a=this.extractTag(e,"requires_image"),l=this.extractTag(e,"wrong_answer_text")||"",u=this.extractTag(e,"mistake_analysis")||"",d=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw h.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let p="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(p=i);let f=[];s&&(f=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let m=a?.toLowerCase().trim()==="true",g=(0,c.f)(d,l),y={questionText:t,answerText:r,analysis:n,wrongAnswerText:l,mistakeAnalysis:u,mistakeStatus:g,subject:p,knowledgePoints:f,requiresImage:m,difficultyStars:(0,o.B)(this.extractTag(e,"difficulty_stars")),...(0,o.t)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},_=(0,o.u)(y);return _.success?(h.debug("Validated successfully via XML tags"),_.data):(h.warn({validationError:_.error.format()},"Schema validation warning"),y)}async analyzeImage(e,t="image/jpeg",n="zh",i,o,l,c){let d=(0,s.b)(),p=c?{candidateTags:c}:await (0,a.i)(o,i),f=(0,r.generateAnalyzePrompt)(n,i,o,{customTemplate:d.prompts?.analyze,...p},l);h.box("🔍 AI Image Analysis Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,imageSize:`${e.length} bytes`,mimeType:t,model:this.model,language:n,grade:i||"all"}),h.box("📝 Full System Prompt",f);try{let r,n={model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,[...${e.length} bytes base64 data...]`}}]}],max_tokens:8192};if(h.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(n,null,2)),this.isLongCat){let n=this.adaptMessagesForLongCat([{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}]),i=await fetch(`${this.baseURL}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:n,max_tokens:8192})});if(!i.ok){let e=await i.text();throw h.error({status:i.status,body:e},"LongCat API error"),Error(`${i.status} status code (${e})`)}r=await i.json()}else r=await (0,u.V)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.box("📦 Full API Response",JSON.stringify(r,null,2)),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let i=r.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",i),!i)throw Error("Empty response from AI");let s=this.parseResponse(i);return h.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw h.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,n="zh",i="medium",o,a){let l=(0,s.b)(),c=(0,r.generateSimilarQuestionPrompt)(n,e,t,i,{customTemplate:l.prompts?.similar,originalFigureSvg:a},o),p=`
34
34
  Original Question: "${e}"
35
35
  Knowledge Points: ${t.join(", ")}
36
- `;h.box("🎯 Generate Similar Question Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,model:this.model,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:i,language:n}),h.box("📝 System Prompt",c),h.box("📝 User Prompt",p);try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:c},{role:"user",content:p}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",t),!t)throw Error("Empty response from AI");let r=this.parseResponse(t);return h.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,d.f)(r)}catch(e){throw h.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,a){let{generateReanswerPrompt:l}=await e.A(730249),d=l(r,t,n,{candidateTags:a},s);h.info({provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,model:this.model,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),h.debug({prompt:d},"Full prompt");try{let e="请根据上述题目提供答案和解析。";if(i){let t=i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`;h.debug({imageLength:t.length},"Image added to request"),e=[{type:"text",text:"请结合图片和题目描述提供答案和解析。"},{type:"image_url",image_url:{url:t}}]}else h.debug({imageBase64Type:typeof i,hasValue:!!i},"No image data");let t={model:this.model,messages:[{role:"system",content:d.substring(0,200)+"..."},{role:"user",content:"string"==typeof e?e:"[包含图片的多模态消息]"}],max_tokens:8192};h.debug({requestParams:t},"Request parameters");let r=await (0,u.V)(t=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:d},{role:"user",content:e}],max_tokens:t}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.debug({response:JSON.stringify(r)},"Full API response"),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"AI raw response"),!n)throw Error("Empty response from AI");let s=this.extractTag(n,"answer_text")||"",a=this.extractTag(n,"analysis")||"",l=(this.extractTag(n,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),p=this.extractTag(n,"wrong_answer_text")||"",f=this.extractTag(n,"mistake_analysis")||"",m=(0,c.f)(this.extractTag(n,"mistake_status"),p);return h.info("Reanswer parsed successfully"),{answerText:s,analysis:a,knowledgePoints:l,wrongAnswerText:p,mistakeAnalysis:f,mistakeStatus:m,subject:(0,o.G)(this.extractTag(n,"subject")),difficultyStars:(0,o.B)(this.extractTag(n,"difficulty_stars"))}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,n,i){let s=(0,r.generateGeogebraPrompt)(e,t,n,i);h.info({provider:"OpenAI",model:this.model,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:s},{role:"user",content:"请分析上述题目并生成 GeoGebra 演示命令。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error("Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let i=r.indexOf("{"),o=r.lastIndexOf("}");-1!==i&&-1!==o&&(r=r.substring(i,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,r.generateMasteryPrompt)(e);h.info({provider:"OpenAI",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请根据上述练习历史给出掌握概率评估。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),r=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error("Empty response from AI");return(0,o.r)(r)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async gradeAnswer(e){h.info({provider:"OpenAI"},"Answer Grading Request");try{let t=await (0,u.V)(t=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:(0,r.generateGradingPrompt)(e)},{role:"user",content:"请判定学生答案是否正确。"}],max_tokens:t}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=t.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Grading AI raw response"),!n)throw Error("Empty response from AI");return(0,o.o)(n)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during answer grading"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,r.generateTagSuggestPrompt)(e);h.info({provider:"OpenAI",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请为上述题目选择知识点。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error("Empty response from AI");return(0,o.K)(n,e.allowedTags)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,n){let i=(0,r.generateFigurePrompt)(n);h.info({provider:"OpenAI",model:this.model,imageSize:e.length},"Figure SVG Request");try{let r=await (0,u.V)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:i},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Figure SVG AI raw response"),!n)throw Error("Empty response from AI");return(0,o.t)(this.extractTag(n,"has_figure"),this.extractTag(n,"figure_svg"))}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,r.generateLatexFixPrompt)(e);h.info({provider:"OpenAI",model:this.model,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请修复上述内容中的 LaTeX 语法。"}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error("Empty response from AI");return(0,i.f)(n,e)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,i,s,o="zh"){let a=(0,r.generateSvgAnimationPrompt)(e,t,i,s,o);h.info({provider:"OpenAI",model:this.model,questionLength:e.length},"SVG Animation Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:a},{role:"user",content:r.SVG_ANIMATION_REQUEST[o]}],max_tokens:e}),16384,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error("Empty response from AI");return(0,n.f)(this.extractTag(t,"svg_animation")||t)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(h.error({error:e},"OpenAI error"),e instanceof Error){if(e.message===u.z||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],592938)}],233405,(e,t,r)=>{t.exports=e.x("child_process",()=>require("child_process"))},924868,(e,t,r)=>{t.exports=e.x("fs/promises",()=>require("fs/promises"))},188646,(e,t,r)=>{t.exports=e.x("node:stream/promises",()=>require("node:stream/promises"))},605365,(e,t,r)=>{t.exports=e.x("process",()=>require("process"))},688947,(e,t,r)=>{t.exports=e.x("stream",()=>require("stream"))},345905,(e,t,r)=>{!function(r){"use strict";var n,i=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,s=Math.ceil,o=Math.floor,a="[BigNumber Error] ",l=a+"Number primitive has more than 15 significant digits: ",u=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13];function c(e){var t=0|e;return e>0||e===t?t:t-1}function d(e){for(var t,r,n=1,i=e.length,s=e[0]+"";n<i;){for(r=14-(t=e[n++]+"").length;r--;t="0"+t);s+=t}for(i=s.length;48===s.charCodeAt(--i););return s.slice(0,i+1||1)}function h(e,t){var r,n,i=e.c,s=t.c,o=e.s,a=t.s,l=e.e,u=t.e;if(!o||!a)return null;if(r=i&&!i[0],n=s&&!s[0],r||n)return r?n?0:-a:o;if(o!=a)return o;if(r=o<0,n=l==u,!i||!s)return n?0:!i^r?1:-1;if(!n)return l>u^r?1:-1;for(a=(l=i.length)<(u=s.length)?l:u,o=0;o<a;o++)if(i[o]!=s[o])return i[o]>s[o]^r?1:-1;return l==u?0:l>u^r?1:-1}function p(e,t,r,n){if(e<t||e>r||e!==o(e))throw Error(a+(n||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function f(e){var t=e.c.length-1;return c(e.e/14)==t&&e.c[t]%2!=0}function m(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function g(e,t,r){var n,i;if(t<0){for(i=r+".";++t;i+=r);e=i+e}else if(n=e.length,++t>n){for(i=r,t-=n;--t;i+=r);e+=i}else t<n&&(e=e.slice(0,t)+"."+e.slice(t));return e}if((n=function e(t){var r,n,y,_,E,A,v,b,w,T=j.prototype={constructor:j,toString:null,valueOf:null},I=new j(1),S=20,O=4,C=-7,R=21,P=-1e7,k=1e7,x=!1,N=1,D=0,U={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},M="0123456789abcdefghijklmnopqrstuvwxyz",L=!0;function j(e,t){var r,n,s,a,u,c,d,h,f=this;if(!(f instanceof j))return new j(e,t);if(null==t){if(e&&!0===e._isBigNumber){f.s=e.s,!e.c||e.e>k?f.c=f.e=null:e.e<P?f.c=[f.e=0]:(f.e=e.e,f.c=e.c.slice());return}if((c="number"==typeof e)&&0*e==0){if(f.s=1/e<0?(e=-e,-1):1,e===~~e){for(a=0,u=e;u>=10;u/=10,a++);a>k?f.c=f.e=null:(f.e=a,f.c=[e]);return}h=String(e)}else{if(!i.test(h=String(e)))return w(f,h,c);f.s=45==h.charCodeAt(0)?(h=h.slice(1),-1):1}(a=h.indexOf("."))>-1&&(h=h.replace(".","")),(u=h.search(/e/i))>0?(a<0&&(a=u),a+=+h.slice(u+1),h=h.substring(0,u)):a<0&&(a=h.length)}else{if(p(t,2,M.length,"Base"),10==t&&L)return q(f=new j(e),S+f.e+1,O);if(h=String(e),c="number"==typeof e){if(0*e!=0)return w(f,h,c,t);if(f.s=1/e<0?(h=h.slice(1),-1):1,j.DEBUG&&h.replace(/^0\.0*|\./,"").length>15)throw Error(l+e)}else f.s=45===h.charCodeAt(0)?(h=h.slice(1),-1):1;for(r=M.slice(0,t),a=u=0,d=h.length;u<d;u++)if(0>r.indexOf(n=h.charAt(u))){if("."==n){if(u>a){a=d;continue}}else if(!s&&(h==h.toUpperCase()&&(h=h.toLowerCase())||h==h.toLowerCase()&&(h=h.toUpperCase()))){s=!0,u=-1,a=0;continue}return w(f,String(e),c,t)}c=!1,(a=(h=b(h,t,10,f.s)).indexOf("."))>-1?h=h.replace(".",""):a=h.length}for(u=0;48===h.charCodeAt(u);u++);for(d=h.length;48===h.charCodeAt(--d););if(h=h.slice(u,++d)){if(d-=u,c&&j.DEBUG&&d>15&&(e>0x1fffffffffffff||e!==o(e)))throw Error(l+f.s*e);if((a=a-u-1)>k)f.c=f.e=null;else if(a<P)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%14,a<0&&(u+=14),u<d){for(u&&f.c.push(+h.slice(0,u)),d-=14;u<d;)f.c.push(+h.slice(u,u+=14));u=14-(h=h.slice(u)).length}else u-=d;for(;u--;h+="0");f.c.push(+h)}}else f.c=[f.e=0]}function G(e,t,r,n){var i,s,o,a,l;if(null==r?r=O:p(r,0,8),!e.c)return e.toString();if(i=e.c[0],o=e.e,null==t)l=d(e.c),l=1==n||2==n&&(o<=C||o>=R)?m(l,o):g(l,o,"0");else if(s=(e=q(new j(e),t,r)).e,a=(l=d(e.c)).length,1==n||2==n&&(t<=s||s<=C)){for(;a<t;l+="0",a++);l=m(l,s)}else if(t-=o+(2===n&&s>o),l=g(l,s,"0"),s+1>a){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=s-a)>0)for(s+1==a&&(l+=".");t--;l+="0");return e.s<0&&i?"-"+l:l}function F(e,t){for(var r,n,i=1,s=new j(e[0]);i<e.length;i++)(n=new j(e[i])).s&&(r=h(s,n))!==t&&(0!==r||s.s!==t)||(s=n);return s}function $(e,t,r){for(var n=1,i=t.length;!t[--i];t.pop());for(i=t[0];i>=10;i/=10,n++);return(r=n+14*r-1)>k?e.c=e.e=null:r<P?e.c=[e.e=0]:(e.e=r,e.c=t),e}function q(e,t,r,n){var i,a,l,c,d,h,p,f=e.c;if(f){e:{for(i=1,c=f[0];c>=10;c/=10,i++);if((a=t-i)<0)a+=14,l=t,p=o((d=f[h=0])/u[i-l-1]%10);else if((h=s((a+1)/14))>=f.length)if(n){for(;f.length<=h;f.push(0));d=p=0,i=1,a%=14,l=a-14+1}else break e;else{for(d=c=f[h],i=1;c>=10;c/=10,i++);a%=14,p=(l=a-14+i)<0?0:o(d/u[i-l-1]%10)}if(n=n||t<0||null!=f[h+1]||(l<0?d:d%u[i-l-1]),n=r<4?(p||n)&&(0==r||r==(e.s<0?3:2)):p>5||5==p&&(4==r||n||6==r&&(a>0?l>0?d/u[i-l]:0:f[h-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=u[(14-t%14)%14],e.e=-t||0):f[0]=e.e=0,e;if(0==a?(f.length=h,c=1,h--):(f.length=h+1,c=u[14-a],f[h]=l>0?o(d/u[i-l]%u[l])*c:0),n)for(;;)if(0==h){for(a=1,l=f[0];l>=10;l/=10,a++);for(l=f[0]+=c,c=1;l>=10;l/=10,c++);a!=c&&(e.e++,1e14==f[0]&&(f[0]=1));break}else{if(f[h]+=c,1e14!=f[h])break;f[h--]=0,c=1}for(a=f.length;0===f[--a];f.pop());}e.e>k?e.c=e.e=null:e.e<P&&(e.c=[e.e=0])}return e}function B(e){var t,r=e.e;return null===r?e.toString():(t=d(e.c),t=r<=C||r>=R?m(t,r):g(t,r,"0"),e.s<0?"-"+t:t)}return j.clone=e,j.ROUND_UP=0,j.ROUND_DOWN=1,j.ROUND_CEIL=2,j.ROUND_FLOOR=3,j.ROUND_HALF_UP=4,j.ROUND_HALF_DOWN=5,j.ROUND_HALF_EVEN=6,j.ROUND_HALF_CEIL=7,j.ROUND_HALF_FLOOR=8,j.EUCLID=9,j.config=j.set=function(e){var t,r;if(null!=e)if("object"==typeof e){if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(p(r=e[t],0,1e9,t),S=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(p(r=e[t],0,8,t),O=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(p(r[0],-1e9,0,t),p(r[1],0,1e9,t),C=r[0],R=r[1]):(p(r,-1e9,1e9,t),C=-(R=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)p(r[0],-1e9,-1,t),p(r[1],1,1e9,t),P=r[0],k=r[1];else if(p(r,-1e9,1e9,t),r)P=-(k=r<0?-r:r);else throw Error(a+t+" cannot be zero: "+r);if(e.hasOwnProperty(t="CRYPTO"))if(!!(r=e[t])===r)if(r)if("u">typeof crypto&&crypto&&(crypto.getRandomValues||crypto.randomBytes))x=r;else throw x=!r,Error(a+"crypto unavailable");else x=r;else throw Error(a+t+" not true or false: "+r);if(e.hasOwnProperty(t="MODULO_MODE")&&(p(r=e[t],0,9,t),N=r),e.hasOwnProperty(t="POW_PRECISION")&&(p(r=e[t],0,1e9,t),D=r),e.hasOwnProperty(t="FORMAT"))if("object"==typeof(r=e[t]))U=r;else throw Error(a+t+" not an object: "+r);if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(a+t+" invalid: "+r);L="0123456789"==r.slice(0,10),M=r}}else throw Error(a+"Object expected: "+e);return{DECIMAL_PLACES:S,ROUNDING_MODE:O,EXPONENTIAL_AT:[C,R],RANGE:[P,k],CRYPTO:x,MODULO_MODE:N,POW_PRECISION:D,FORMAT:U,ALPHABET:M}},j.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!j.DEBUG)return!0;var t,r,n=e.c,i=e.e,s=e.s;e:if("[object Array]"==({}).toString.call(n)){if((1===s||-1===s)&&i>=-1e9&&i<=1e9&&i===o(i)){if(0===n[0]){if(0===i&&1===n.length)return!0;break e}if((t=(i+1)%14)<1&&(t+=14),String(n[0]).length==t){for(t=0;t<n.length;t++)if((r=n[t])<0||r>=1e14||r!==o(r))break e;if(0!==r)return!0}}}else if(null===n&&null===i&&(null===s||1===s||-1===s))return!0;throw Error(a+"Invalid BigNumber: "+e)},j.maximum=j.max=function(){return F(arguments,-1)},j.minimum=j.min=function(){return F(arguments,1)},r=0x20000000000000*Math.random()&2097151?function(){return o(0x20000000000000*Math.random())}:function(){return(0x40000000*Math.random()|0)*8388608+(8388608*Math.random()|0)},j.random=function(e){var t,n,i,l,c,d=0,h=[],f=new j(I);if(null==e?e=S:p(e,0,1e9),l=s(e/14),x)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(l*=2));d<l;)(c=131072*t[d]+(t[d+1]>>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),t[d]=n[0],t[d+1]=n[1]):(h.push(c%1e14),d+=2);d=l/2}else if(crypto.randomBytes){for(t=crypto.randomBytes(l*=7);d<l;)(c=(31&t[d])*0x1000000000000+0x10000000000*t[d+1]+0x100000000*t[d+2]+0x1000000*t[d+3]+(t[d+4]<<16)+(t[d+5]<<8)+t[d+6])>=9e15?crypto.randomBytes(7).copy(t,d):(h.push(c%1e14),d+=7);d=l/7}else throw x=!1,Error(a+"crypto unavailable");if(!x)for(;d<l;)(c=r())<9e15&&(h[d++]=c%1e14);for(l=h[--d],e%=14,l&&e&&(c=u[14-e],h[d]=o(l/c)*c);0===h[d];h.pop(),d--);if(d<0)h=[i=0];else{for(i=-1;0===h[0];h.splice(0,1),i-=14);for(d=1,c=h[0];c>=10;c/=10,d++);d<14&&(i-=14-d)}return f.e=i,f.c=h,f},j.sum=function(){for(var e=1,t=arguments,r=new j(t[0]);e<t.length;)r=r.plus(t[e++]);return r},b=function(){var e="0123456789";function t(e,t,r,n){for(var i,s,o=[0],a=0,l=e.length;a<l;){for(s=o.length;s--;o[s]*=t);for(o[0]+=n.indexOf(e.charAt(a++)),i=0;i<o.length;i++)o[i]>r-1&&(null==o[i+1]&&(o[i+1]=0),o[i+1]+=o[i]/r|0,o[i]%=r)}return o.reverse()}return function(r,n,i,s,o){var a,l,u,c,h,p,f,m,y=r.indexOf("."),_=S,E=O;for(y>=0&&(c=D,D=0,r=r.replace(".",""),p=(m=new j(n)).pow(r.length-y),D=c,m.c=t(g(d(p.c),p.e,"0"),10,i,e),m.e=m.c.length),u=c=(f=t(r,n,i,o?(a=M,e):(a=e,M))).length;0==f[--c];f.pop());if(!f[0])return a.charAt(0);if(y<0?--u:(p.c=f,p.e=u,p.s=s,f=(p=v(p,m,_,E,i)).c,h=p.r,u=p.e),y=f[l=u+_+1],c=i/2,h=h||l<0||null!=f[l+1],h=E<4?(null!=y||h)&&(0==E||E==(p.s<0?3:2)):y>c||y==c&&(4==E||h||6==E&&1&f[l-1]||E==(p.s<0?8:7)),l<1||!f[0])r=h?g(a.charAt(1),-_,a.charAt(0)):a.charAt(0);else{if(f.length=l,h)for(--i;++f[--l]>i;)f[l]=0,l||(++u,f=[1].concat(f));for(c=f.length;!f[--c];);for(y=0,r="";y<=c;r+=a.charAt(f[y++]));r=g(r,u,a.charAt(0))}return r}}(),v=function(){function e(e,t,r){var n,i,s,o,a=0,l=e.length,u=t%1e7,c=t/1e7|0;for(e=e.slice();l--;)n=c*(s=e[l]%1e7)+(o=e[l]/1e7|0)*u,a=((i=u*s+n%1e7*1e7+a)/r|0)+(n/1e7|0)+c*o,e[l]=i%r;return a&&(e=[a].concat(e)),e}function t(e,t,r,n){var i,s;if(r!=n)s=r>n?1:-1;else for(i=s=0;i<r;i++)if(e[i]!=t[i]){s=e[i]>t[i]?1:-1;break}return s}function r(e,t,r,n){for(var i=0;r--;)e[r]-=i,i=+(e[r]<t[r]),e[r]=i*n+e[r]-t[r];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(n,i,s,a,l){var u,d,h,p,f,m,g,y,_,E,A,v,b,w,T,I,S,O=n.s==i.s?1:-1,C=n.c,R=i.c;if(!C||!C[0]||!R||!R[0])return new j(!n.s||!i.s||(C?R&&C[0]==R[0]:!R)?0/0:C&&0==C[0]||!R?0*O:O/0);for(_=(y=new j(O)).c=[],O=s+(d=n.e-i.e)+1,l||(l=1e14,d=c(n.e/14)-c(i.e/14),O=O/14|0),h=0;R[h]==(C[h]||0);h++);if(R[h]>(C[h]||0)&&d--,O<0)_.push(1),p=!0;else{for(w=C.length,I=R.length,h=0,O+=2,(f=o(l/(R[0]+1)))>1&&(R=e(R,f,l),C=e(C,f,l),I=R.length,w=C.length),b=I,A=(E=C.slice(0,I)).length;A<I;E[A++]=0);S=[0].concat(S=R.slice()),T=R[0],R[1]>=l/2&&T++;do{if(f=0,(u=t(R,E,I,A))<0){if(v=E[0],I!=A&&(v=v*l+(E[1]||0)),(f=o(v/T))>1)for(f>=l&&(f=l-1),g=(m=e(R,f,l)).length,A=E.length;1==t(m,E,g,A);)f--,r(m,I<g?S:R,g,l),g=m.length,u=1;else 0==f&&(u=f=1),g=(m=R.slice()).length;if(g<A&&(m=[0].concat(m)),r(E,m,A,l),A=E.length,-1==u)for(;1>t(R,E,I,A);)f++,r(E,I<A?S:R,A,l),A=E.length}else 0===u&&(f++,E=[0]);_[h++]=f,E[0]?E[A++]=C[b]||0:(E=[C[b]],A=1)}while((b++<w||null!=E[0])&&O--)p=null!=E[0],_[0]||_.splice(0,1)}if(1e14==l){for(h=1,O=_[0];O>=10;O/=10,h++);q(y,s+(y.e=h+14*d-1)+1,a,p)}else y.e=d,y.r=+p;return y}}(),n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,y=/^([^.]+)\.$/,_=/^\.([^.]+)$/,E=/^-?(Infinity|NaN)$/,A=/^\s*\+(?=[\w.])|^\s+|\s+$/g,w=function(e,t,r,i){var s,o=r?t:t.replace(A,"");if(E.test(o))e.s=isNaN(o)?null:o<0?-1:1;else{if(!r&&(o=o.replace(n,function(e,t,r){return s="x"==(r=r.toLowerCase())?16:"b"==r?2:8,i&&i!=s?e:t}),i&&(s=i,o=o.replace(y,"$1").replace(_,"0.$1")),t!=o))return new j(o,s);if(j.DEBUG)throw Error(a+"Not a"+(i?" base "+i:"")+" number: "+t);e.s=null}e.c=e.e=null},T.absoluteValue=T.abs=function(){var e=new j(this);return e.s<0&&(e.s=1),e},T.comparedTo=function(e,t){return h(this,new j(e,t))},T.decimalPlaces=T.dp=function(e,t){var r,n,i;if(null!=e)return p(e,0,1e9),null==t?t=O:p(t,0,8),q(new j(this),e+this.e+1,t);if(!(r=this.c))return null;if(n=((i=r.length-1)-c(this.e/14))*14,i=r[i])for(;i%10==0;i/=10,n--);return n<0&&(n=0),n},T.dividedBy=T.div=function(e,t){return v(this,new j(e,t),S,O)},T.dividedToIntegerBy=T.idiv=function(e,t){return v(this,new j(e,t),0,1)},T.exponentiatedBy=T.pow=function(e,t){var r,n,i,l,u,c,d,h,p,m=this;if((e=new j(e)).c&&!e.isInteger())throw Error(a+"Exponent not an integer: "+B(e));if(null!=t&&(t=new j(t)),c=e.e>14,!m.c||!m.c[0]||1==m.c[0]&&!m.e&&1==m.c.length||!e.c||!e.c[0])return p=new j(Math.pow(+B(m),c?e.s*(2-f(e)):+B(e))),t?p.mod(t):p;if(d=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new j(0/0);(n=!d&&m.isInteger()&&t.isInteger())&&(m=m.mod(t))}else{if(e.e>9&&(m.e>0||m.e<-1||(0==m.e?m.c[0]>1||c&&m.c[1]>=24e7:m.c[0]<8e13||c&&m.c[0]<=9999975e7)))return l=m.s<0&&f(e)?-0:0,m.e>-1&&(l=1/l),new j(d?1/l:l);D&&(l=s(D/14+2))}for(c?(r=new j(.5),d&&(e.s=1),h=f(e)):h=(i=Math.abs(+B(e)))%2,p=new j(I);;){if(h){if(!(p=p.times(m)).c)break;l?p.c.length>l&&(p.c.length=l):n&&(p=p.mod(t))}if(i){if(0===(i=o(i/2)))break;h=i%2}else if(q(e=e.times(r),e.e+1,1),e.e>14)h=f(e);else{if(0==(i=+B(e)))break;h=i%2}m=m.times(m),l?m.c&&m.c.length>l&&(m.c.length=l):n&&(m=m.mod(t))}return n?p:(d&&(p=I.div(p)),t?p.mod(t):l?q(p,D,O,u):p)},T.integerValue=function(e){var t=new j(this);return null==e?e=O:p(e,0,8),q(t,t.e+1,e)},T.isEqualTo=T.eq=function(e,t){return 0===h(this,new j(e,t))},T.isFinite=function(){return!!this.c},T.isGreaterThan=T.gt=function(e,t){return h(this,new j(e,t))>0},T.isGreaterThanOrEqualTo=T.gte=function(e,t){return 1===(t=h(this,new j(e,t)))||0===t},T.isInteger=function(){return!!this.c&&c(this.e/14)>this.c.length-2},T.isLessThan=T.lt=function(e,t){return 0>h(this,new j(e,t))},T.isLessThanOrEqualTo=T.lte=function(e,t){return -1===(t=h(this,new j(e,t)))||0===t},T.isNaN=function(){return!this.s},T.isNegative=function(){return this.s<0},T.isPositive=function(){return this.s>0},T.isZero=function(){return!!this.c&&0==this.c[0]},T.minus=function(e,t){var r,n,i,s,o=this.s;if(t=(e=new j(e,t)).s,!o||!t)return new j(0/0);if(o!=t)return e.s=-t,this.plus(e);var a=this.e/14,l=e.e/14,u=this.c,d=e.c;if(!a||!l){if(!u||!d)return u?(e.s=-t,e):new j(d?this:0/0);if(!u[0]||!d[0])return d[0]?(e.s=-t,e):new j(u[0]?this:3==O?-0:0)}if(a=c(a),l=c(l),u=u.slice(),o=a-l){for((s=o<0)?(o=-o,i=u):(l=a,i=d),i.reverse(),t=o;t--;i.push(0));i.reverse()}else for(n=(s=(o=u.length)<(t=d.length))?o:t,o=t=0;t<n;t++)if(u[t]!=d[t]){s=u[t]<d[t];break}if(s&&(i=u,u=d,d=i,e.s=-e.s),(t=(n=d.length)-(r=u.length))>0)for(;t--;u[r++]=0);for(t=1e14-1;n>o;){if(u[--n]<d[n]){for(r=n;r&&!u[--r];u[r]=t);--u[r],u[n]+=1e14}u[n]-=d[n]}for(;0==u[0];u.splice(0,1),--l);return u[0]?$(e,u,l):(e.s=3==O?-1:1,e.c=[e.e=0],e)},T.modulo=T.mod=function(e,t){var r,n;return(e=new j(e,t),this.c&&e.s&&(!e.c||e.c[0]))?e.c&&(!this.c||this.c[0])?(9==N?(n=e.s,e.s=1,r=v(this,e,0,3),e.s=n,r.s*=n):r=v(this,e,0,N),(e=this.minus(r.times(e))).c[0]||1!=N||(e.s=this.s),e):new j(this):new j(0/0)},T.multipliedBy=T.times=function(e,t){var r,n,i,s,o,a,l,u,d,h,p,f,m,g=this.c,y=(e=new j(e,t)).c;if(!g||!y||!g[0]||!y[0])return this.s&&e.s&&(!g||g[0]||y)&&(!y||y[0]||g)?(e.s*=this.s,g&&y?(e.c=[0],e.e=0):e.c=e.e=null):e.c=e.e=e.s=null,e;for(n=c(this.e/14)+c(e.e/14),e.s*=this.s,(l=g.length)<(h=y.length)&&(m=g,g=y,y=m,i=l,l=h,h=i),i=l+h,m=[];i--;m.push(0));for(i=h;--i>=0;){for(r=0,p=y[i]%1e7,f=y[i]/1e7|0,s=i+(o=l);s>i;)a=f*(u=g[--o]%1e7)+(d=g[o]/1e7|0)*p,r=((u=p*u+a%1e7*1e7+m[s]+r)/1e14|0)+(a/1e7|0)+f*d,m[s--]=u%1e14;m[s]=r}return r?++n:m.splice(0,1),$(e,m,n)},T.negated=function(){var e=new j(this);return e.s=-e.s||null,e},T.plus=function(e,t){var r,n=this.s;if(t=(e=new j(e,t)).s,!n||!t)return new j(0/0);if(n!=t)return e.s=-t,this.minus(e);var i=this.e/14,s=e.e/14,o=this.c,a=e.c;if(!i||!s){if(!o||!a)return new j(n/0);if(!o[0]||!a[0])return a[0]?e:new j(o[0]?this:0*n)}if(i=c(i),s=c(s),o=o.slice(),n=i-s){for(n>0?(s=i,r=a):(n=-n,r=o),r.reverse();n--;r.push(0));r.reverse()}for((n=o.length)-(t=a.length)<0&&(r=a,a=o,o=r,t=n),n=0;t;)n=(o[--t]=o[t]+a[t]+n)/1e14|0,o[t]=1e14===o[t]?0:o[t]%1e14;return n&&(o=[n].concat(o),++s),$(e,o,s)},T.precision=T.sd=function(e,t){var r,n,i;if(null!=e&&!!e!==e)return p(e,1,1e9),null==t?t=O:p(t,0,8),q(new j(this),e,t);if(!(r=this.c))return null;if(n=14*(i=r.length-1)+1,i=r[i]){for(;i%10==0;i/=10,n--);for(i=r[0];i>=10;i/=10,n++);}return e&&this.e+1>n&&(n=this.e+1),n},T.shiftedBy=function(e){return p(e,-0x1fffffffffffff,0x1fffffffffffff),this.times("1e"+e)},T.squareRoot=T.sqrt=function(){var e,t,r,n,i,s=this.c,o=this.s,a=this.e,l=S+4,u=new j("0.5");if(1!==o||!s||!s[0])return new j(!o||o<0&&(!s||s[0])?0/0:s?this:1/0);if(0==(o=Math.sqrt(+B(this)))||1/0==o?(((t=d(s)).length+a)%2==0&&(t+="0"),o=Math.sqrt(+t),a=c((a+1)/2)-(a<0||a%2),r=new j(t=1/0==o?"5e"+a:(t=o.toExponential()).slice(0,t.indexOf("e")+1)+a)):r=new j(o+""),r.c[0]){for((o=(a=r.e)+l)<3&&(o=0);;)if(i=r,r=u.times(i.plus(v(this,i,l,1))),d(i.c).slice(0,o)===(t=d(r.c)).slice(0,o)){if(r.e<a&&--o,"9999"!=(t=t.slice(o-3,o+1))&&(n||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(q(r,r.e+S+2,1),e=!r.times(r).eq(this));break}if(!n&&(q(i,i.e+S+2,0),i.times(i).eq(this))){r=i;break}l+=4,o+=4,n=1}}return q(r,r.e+S+1,O,e)},T.toExponential=function(e,t){return null!=e&&(p(e,0,1e9),e++),G(this,e,t,1)},T.toFixed=function(e,t){return null!=e&&(p(e,0,1e9),e=e+this.e+1),G(this,e,t)},T.toFormat=function(e,t,r){var n;if(null==r)null!=e&&t&&"object"==typeof t?(r=t,t=null):e&&"object"==typeof e?(r=e,e=t=null):r=U;else if("object"!=typeof r)throw Error(a+"Argument not an object: "+r);if(n=this.toFixed(e,t),this.c){var i,s=n.split("."),o=+r.groupSize,l=+r.secondaryGroupSize,u=r.groupSeparator||"",c=s[0],d=s[1],h=this.s<0,p=h?c.slice(1):c,f=p.length;if(l&&(i=o,o=l,l=i,f-=i),o>0&&f>0){for(i=f%o||o,c=p.substr(0,i);i<f;i+=o)c+=u+p.substr(i,o);l>0&&(c+=u+p.slice(i)),h&&(c="-"+c)}n=d?c+(r.decimalSeparator||"")+((l=+r.fractionGroupSize)?d.replace(RegExp("\\d{"+l+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):d):c}return(r.prefix||"")+n+(r.suffix||"")},T.toFraction=function(e){var t,r,n,i,s,o,l,c,h,p,f,m,g=this.c;if(null!=e&&(!(l=new j(e)).isInteger()&&(l.c||1!==l.s)||l.lt(I)))throw Error(a+"Argument "+(l.isInteger()?"out of range: ":"not an integer: ")+B(l));if(!g)return new j(this);for(t=new j(I),h=r=new j(I),n=c=new j(I),m=d(g),s=t.e=m.length-this.e-1,t.c[0]=u[(o=s%14)<0?14+o:o],e=!e||l.comparedTo(t)>0?s>0?t:h:l,o=k,k=1/0,l=new j(m),c.c[0]=0;p=v(l,t,0,1),1!=(i=r.plus(p.times(n))).comparedTo(e);)r=n,n=i,h=c.plus(p.times(i=h)),c=i,t=l.minus(p.times(i=t)),l=i;return i=v(e.minus(r),n,0,1),c=c.plus(i.times(h)),r=r.plus(i.times(n)),c.s=h.s=this.s,s*=2,f=1>v(h,n,s,O).minus(this).abs().comparedTo(v(c,r,s,O).minus(this).abs())?[h,n]:[c,r],k=o,f},T.toNumber=function(){return+B(this)},T.toPrecision=function(e,t){return null!=e&&p(e,1,1e9),G(this,e,t,2)},T.toString=function(e){var t,r=this,n=r.s,i=r.e;return null===i?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=i<=C||i>=R?m(d(r.c),i):g(d(r.c),i,"0"):10===e&&L?t=g(d((r=q(new j(r),S+i+1,O)).c),r.e,"0"):(p(e,2,M.length,"Base"),t=b(g(d(r.c),i,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},T.valueOf=T.toJSON=function(){return B(this)},T._isBigNumber=!0,null!=t&&j.set(t),j}()).default=n.BigNumber=n,"function"==typeof define&&define.amd)e.r,void 0!==n&&e.v(n);else t.exports?t.exports=n:(r||(r="u">typeof self&&self?self:window),r.BigNumber=n)}(e.e)},73827,(e,t,r)=>{t.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}},357660,(e,t,r)=>{t.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}},301158,(e,t,r)=>{var n=e.r(364349).stringify,i=e.r(767104);t.exports=function(e){return{parse:i(e),stringify:n}},t.exports.parse=i(),t.exports.stringify=n},767104,(e,t,r)=>{var n=null;let i=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,s=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;t.exports=function(t){"use strict";var r={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(null!=t){if(!0===t.strict&&(r.strict=!0),!0===t.storeAsString&&(r.storeAsString=!0),r.alwaysParseAsBig=!0===t.alwaysParseAsBig&&t.alwaysParseAsBig,r.useNativeBigInt=!0===t.useNativeBigInt&&t.useNativeBigInt,void 0!==t.constructorAction)if("error"===t.constructorAction||"ignore"===t.constructorAction||"preserve"===t.constructorAction)r.constructorAction=t.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(void 0!==t.protoAction)if("error"===t.protoAction||"ignore"===t.protoAction||"preserve"===t.protoAction)r.protoAction=t.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var o,a,l,u,c={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:" "},d=function(e){throw{name:"SyntaxError",message:e,at:o,text:l}},h=function(e){return e&&e!==a&&d("Expected '"+e+"' instead of '"+a+"'"),a=l.charAt(o),o+=1,a},p=function(){var t,i="";for("-"===a&&(i="-",h("-"));a>="0"&&a<="9";)i+=a,h();if("."===a)for(i+=".";h()&&a>="0"&&a<="9";)i+=a;if("e"===a||"E"===a)for(i+=a,h(),("-"===a||"+"===a)&&(i+=a,h());a>="0"&&a<="9";)i+=a,h();if(isFinite(t=+i))return(null==n&&(n=e.r(345905)),i.length>15)?r.storeAsString?i:r.useNativeBigInt?BigInt(i):new n(i):r.alwaysParseAsBig?r.useNativeBigInt?BigInt(t):new n(t):t;d("Bad number")},f=function(){var e,t,r,n="";if('"'===a)for(var i=o;h();){if('"'===a)return o-1>i&&(n+=l.substring(i,o-1)),h(),n;if("\\"===a){if(o-1>i&&(n+=l.substring(i,o-1)),h(),"u"===a){for(t=0,r=0;t<4&&isFinite(e=parseInt(h(),16));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else if("string"==typeof c[a])n+=c[a];else break;i=o}}d("Bad string")},m=function(){for(;a&&a<=" ";)h()},g=function(){switch(a){case"t":return h("t"),h("r"),h("u"),h("e"),!0;case"f":return h("f"),h("a"),h("l"),h("s"),h("e"),!1;case"n":return h("n"),h("u"),h("l"),h("l"),null}d("Unexpected '"+a+"'")},y=function(){var e=[];if("["===a){if(h("["),m(),"]"===a)return h("]"),e;for(;a;){if(e.push(u()),m(),"]"===a)return h("]"),e;h(","),m()}}d("Bad array")},_=function(){var e,t=Object.create(null);if("{"===a){if(h("{"),m(),"}"===a)return h("}"),t;for(;a;){if(e=f(),m(),h(":"),!0===r.strict&&Object.hasOwnProperty.call(t,e)&&d('Duplicate key "'+e+'"'),!0===i.test(e)?"error"===r.protoAction?d("Object contains forbidden prototype property"):"ignore"===r.protoAction?u():t[e]=u():!0===s.test(e)?"error"===r.constructorAction?d("Object contains forbidden constructor property"):"ignore"===r.constructorAction?u():t[e]=u():t[e]=u(),m(),"}"===a)return h("}"),t;h(","),m()}}d("Bad object")};return u=function(){switch(m(),a){case"{":return _();case"[":return y();case'"':return f();case"-":return p();default:return a>="0"&&a<="9"?p():g()}},function(e,t){var r;return l=e+"",o=0,a=" ",r=u(),m(),a&&d("Syntax error"),"function"==typeof t?function e(r,n){var i,s=r[n];return s&&"object"==typeof s&&Object.keys(s).forEach(function(t){void 0!==(i=e(s,t))?s[t]=i:delete s[t]}),t.call(r,n,s)}({"":r},""):r}}},364349,(e,t,r)=>{var n=e.r(345905),i=t.exports;!function(){"use strict";var e,t,r,s=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(e){return s.lastIndex=0,s.test(e)?'"'+e.replace(s,function(e){var t=o[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}"function"!=typeof i.stringify&&(i.stringify=function(i,s,o){var l;if(e="",t="","number"==typeof o)for(l=0;l<o;l+=1)t+=" ";else"string"==typeof o&&(t=o);if(r=s,s&&"function"!=typeof s&&("object"!=typeof s||"number"!=typeof s.length))throw Error("JSON.stringify");return function i(s,o){var l,u,c,d,h,p=e,f=o[s],m=null!=f&&(f instanceof n||n.isBigNumber(f));switch(f&&"object"==typeof f&&"function"==typeof f.toJSON&&(f=f.toJSON(s)),"function"==typeof r&&(f=r.call(o,s,f)),typeof f){case"string":if(m)return f;return a(f);case"number":return isFinite(f)?String(f):"null";case"boolean":case"null":case"bigint":return String(f);case"object":if(!f)return"null";if(e+=t,h=[],"[object Array]"===Object.prototype.toString.apply(f)){for(d=f.length,l=0;l<d;l+=1)h[l]=i(l,f)||"null";return c=0===h.length?"[]":e?"[\n"+e+h.join(",\n"+e)+"\n"+p+"]":"["+h.join(",")+"]",e=p,c}if(r&&"object"==typeof r)for(d=r.length,l=0;l<d;l+=1)"string"==typeof r[l]&&(c=i(u=r[l],f))&&h.push(a(u)+(e?": ":":")+c);else Object.keys(f).forEach(function(t){var r=i(t,f);r&&h.push(a(t)+(e?": ":":")+r)});return c=0===h.length?"{}":e?"{\n"+e+h.join(",\n"+e)+"\n"+p+"}":"{"+h.join(",")+"}",e=p,c}}("",{"":i})})}()},757067,(e,t,r)=>{var n,i=e.r(223469).Buffer,s=e.r(254799),o=e.r(732955),a=e.r(224361),l="secret must be a string or buffer",u="key must be a string or a buffer",c="function"==typeof s.createPublicKey;function d(e){if(!i.isBuffer(e)&&"string"!=typeof e&&(!c||"object"!=typeof e||"string"!=typeof e.type||"string"!=typeof e.asymmetricKeyType||"function"!=typeof e.export))throw m(u)}function h(e){if(!i.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw m("key must be a string, a buffer or an object")}function p(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function f(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function m(e){var t=[].slice.call(arguments,1);return TypeError(a.format.bind(a,e).apply(null,t))}function g(e){var t;return t=e,i.isBuffer(t)||"string"==typeof t||(e=JSON.stringify(e)),e}function y(e){return function(t,r){!function(e){if(!i.isBuffer(e)){if("string"!=typeof e){if(!c||"object"!=typeof e||"secret"!==e.type||"function"!=typeof e.export)throw m(l)}}}(r),t=g(t);var n=s.createHmac("sha"+e,r);return p((n.update(t),n.digest("base64")))}}c&&(u+=" or a KeyObject",l+="or a KeyObject");var _="timingSafeEqual"in s?function(e,t){return e.byteLength===t.byteLength&&s.timingSafeEqual(e,t)}:function(t,r){return n||(n=e.r(922691)),n(t,r)};function E(e){return function(t,r,n){var s=y(e)(t,n);return _(i.from(r),i.from(s))}}function A(e){return function(t,r){h(r),t=g(t);var n=s.createSign("RSA-SHA"+e);return p((n.update(t),n.sign(r,"base64")))}}function v(e){return function(t,r,n){d(n),t=g(t),r=f(r);var i=s.createVerify("RSA-SHA"+e);return i.update(t),i.verify(n,r,"base64")}}function b(e){return function(t,r){h(r),t=g(t);var n=s.createSign("RSA-SHA"+e);return p((n.update(t),n.sign({key:r,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}function w(e){return function(t,r,n){d(n),t=g(t),r=f(r);var i=s.createVerify("RSA-SHA"+e);return i.update(t),i.verify({key:n,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function T(e){var t=A(e);return function(){var r=t.apply(null,arguments);return o.derToJose(r,"ES"+e)}}function I(e){var t=v(e);return function(r,n,i){return t(r,n=o.joseToDer(n,"ES"+e).toString("base64"),i)}}function S(){return function(){return""}}function O(){return function(e,t){return""===t}}t.exports=function(e){var t=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!t)throw m('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);var r=(t[1]||t[3]).toLowerCase(),n=t[2];return{sign:({hs:y,rs:A,ps:b,es:T,none:S})[r](n),verify:({hs:E,rs:v,ps:w,es:I,none:O})[r](n)}}},258184,(e,t,r)=>{var n=e.r(614743),i=e.r(148233);r.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],r.sign=n.sign,r.verify=i.verify,r.decode=i.decode,r.isValid=i.isValid,r.createSign=function(e){return new n(e)},r.createVerify=function(e){return new i(e)}},41949,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(688947);function s(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick((function(){this.emit("end",e),this.readable=!1,this.emit("close")}).bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}e.r(224361).inherits(s,i),s.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit("data",e)},s.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},t.exports=s},614743,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(41949),s=e.r(757067),o=e.r(688947),a=e.r(576872),l=e.r(224361);function u(e,t){return n.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function c(e){var t,r,n,i=e.header,o=e.payload,c=e.secret||e.privateKey,d=e.encoding,h=s(i.alg),p=(t=(t=d)||"utf8",r=u(a(i),"binary"),n=u(a(o),t),l.format("%s.%s",r,n)),f=h.sign(p,c);return l.format("%s.%s",p,f)}function d(e){var t=e.secret;if(t=null==(t=null==t?e.privateKey:t)?e.key:t,!0===/^hs/i.test(e.header.alg)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new i(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new i(e.payload),this.secret.once("close",(function(){!this.payload.writable&&this.readable&&this.sign()}).bind(this)),this.payload.once("close",(function(){!this.secret.writable&&this.readable&&this.sign()}).bind(this))}l.inherits(d,o),d.prototype.sign=function(){try{var e=c({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},d.sign=c,t.exports=d},576872,(e,t,r)=>{var n=e.r(500874).Buffer;t.exports=function(e){return"string"==typeof e?e:"number"==typeof e||n.isBuffer(e)?e.toString():JSON.stringify(e)}},148233,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(41949),s=e.r(757067),o=e.r(688947),a=e.r(576872),l=e.r(224361),u=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function c(e){var t=e.split(".",1)[0],r=n.from(t,"base64").toString("binary");if("[object Object]"===Object.prototype.toString.call(r))return r;try{return JSON.parse(r)}catch(e){return}}function d(e){return e.split(".")[2]}function h(e){return u.test(e)&&!!c(e)}function p(e,t,r){if(!t){var n=Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}var i=d(e=a(e)),o=e.split(".",2).join(".");return s(t).verify(o,i,r)}function f(e,t){if(t=t||{},!h(e=a(e)))return null;var r,i,s=c(e);if(!s)return null;var o=(r=r||"utf8",i=e.split(".")[1],n.from(i,"base64").toString(r));return("JWT"===s.typ||t.json)&&(o=JSON.parse(o,t.encoding)),{header:s,payload:o,signature:d(e)}}function m(e){var t=(e=e||{}).secret;if(t=null==(t=null==t?e.publicKey:t)?e.key:t,!0===/^hs/i.test(e.algorithm)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new i(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new i(e.signature),this.secret.once("close",(function(){!this.signature.writable&&this.readable&&this.verify()}).bind(this)),this.signature.once("close",(function(){!this.secret.writable&&this.readable&&this.verify()}).bind(this))}l.inherits(m,o),m.prototype.verify=function(){try{var e=p(this.signature.buffer,this.algorithm,this.key.buffer),t=f(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},m.decode=f,m.isValid=h,m.verify=p,t.exports=m},774167,(e,t,r)=>{t.exports=e.r(318263)},318263,(e,t,r)=>{var n=e.r(138047);r.operation=function(e){return new n(r.timeouts(e),{forever:e&&(e.forever||1/0===e.retries),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},r.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<t.retries;i++)n.push(this.createTimeout(i,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(i,t)),n.sort(function(e,t){return e-t}),n},r.createTimeout=function(e,t){var r=Math.round((t.randomize?Math.random()+1:1)*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(r,t.maxTimeout)},r.wrap=function(e,t,n){if(t instanceof Array&&(n=t,t=null),!n)for(var i in n=[],e)"function"==typeof e[i]&&n.push(i);for(var s=0;s<n.length;s++){var o=n[s],a=e[o];e[o]=(function(n){var i=r.operation(t),s=Array.prototype.slice.call(arguments,1),o=s.pop();s.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){n.apply(e,s)})}).bind(e,a),e[o].options=t}}},138047,(e,t,r)=>{function n(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r)if(!this._cachedTimeouts)return!1;else this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,o=(e[s]||0)+1;e[s]=o,o>=r&&(t=i,r=o)}return t}},223469,(e,t,r)=>{var n=e.r(500874),i=n.Buffer;function s(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(s(n,r),r.Buffer=o),o.prototype=Object.create(i.prototype),s(i,o),o.from=function(e,t,r){if("number"==typeof e)throw TypeError("Argument must not be a number");return i(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},o.allocUnsafe=function(e){if("number"!=typeof e)throw TypeError("Argument must be a number");return i(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw TypeError("Argument must be a number");return n.SlowBuffer(e)}}];
36
+ `;h.box("🎯 Generate Similar Question Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,model:this.model,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:i,language:n}),h.box("📝 System Prompt",c),h.box("📝 User Prompt",p);try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:c},{role:"user",content:p}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",t),!t)throw Error("Empty response from AI");let r=this.parseResponse(t);return h.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,d.f)(r)}catch(e){throw h.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,a){let{generateReanswerPrompt:l}=await e.A(730249),d=l(r,t,n,{candidateTags:a},s);h.info({provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,model:this.model,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),h.debug({prompt:d},"Full prompt");try{let e="请根据上述题目提供答案和解析。";if(i){let t=i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`;h.debug({imageLength:t.length},"Image added to request"),e=[{type:"text",text:"请结合图片和题目描述提供答案和解析。"},{type:"image_url",image_url:{url:t}}]}else h.debug({imageBase64Type:typeof i,hasValue:!!i},"No image data");let t={model:this.model,messages:[{role:"system",content:d.substring(0,200)+"..."},{role:"user",content:"string"==typeof e?e:"[包含图片的多模态消息]"}],max_tokens:8192};h.debug({requestParams:t},"Request parameters");let r=await (0,u.V)(t=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:d},{role:"user",content:e}],max_tokens:t}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.debug({response:JSON.stringify(r)},"Full API response"),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"AI raw response"),!n)throw Error("Empty response from AI");let s=this.extractTag(n,"answer_text")||"",a=this.extractTag(n,"analysis")||"",l=(this.extractTag(n,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),p=this.extractTag(n,"wrong_answer_text")||"",f=this.extractTag(n,"mistake_analysis")||"",m=(0,c.f)(this.extractTag(n,"mistake_status"),p);return h.info("Reanswer parsed successfully"),{answerText:s,analysis:a,knowledgePoints:l,wrongAnswerText:p,mistakeAnalysis:f,mistakeStatus:m,subject:(0,o.G)(this.extractTag(n,"subject")),difficultyStars:(0,o.B)(this.extractTag(n,"difficulty_stars"))}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,n,i){let s=(0,r.generateGeogebraPrompt)(e,t,n,i);h.info({provider:"OpenAI",model:this.model,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:s},{role:"user",content:"请分析上述题目并生成 GeoGebra 演示命令。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error("Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let i=r.indexOf("{"),o=r.lastIndexOf("}");-1!==i&&-1!==o&&(r=r.substring(i,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,r.generateMasteryPrompt)(e);h.info({provider:"OpenAI",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请根据上述练习历史给出掌握概率评估。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),r=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error("Empty response from AI");return(0,o.r)(r)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async gradeAnswer(e){h.info({provider:"OpenAI"},"Answer Grading Request");try{let t=await (0,u.V)(t=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:(0,r.generateGradingPrompt)(e)},{role:"user",content:"请判定学生答案是否正确。"}],max_tokens:t}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=t.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Grading AI raw response"),!n)throw Error("Empty response from AI");return(0,o.o)(n)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during answer grading"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,r.generateTagSuggestPrompt)(e);h.info({provider:"OpenAI",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请为上述题目选择知识点。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error("Empty response from AI");return(0,o.K)(n,e.allowedTags)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,n){let i=(0,r.generateFigurePrompt)(n);h.info({provider:"OpenAI",model:this.model,imageSize:e.length},"Figure SVG Request");try{let r=await (0,u.V)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:i},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Figure SVG AI raw response"),!n)throw Error("Empty response from AI");return(0,o.t)(this.extractTag(n,"has_figure"),this.extractTag(n,"figure_svg"))}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,r.generateLatexFixPrompt)(e);h.info({provider:"OpenAI",model:this.model,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请修复上述内容中的 LaTeX 语法。"}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error("Empty response from AI");return(0,i.f)(n,e)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,i,s,o="zh"){let a=(0,r.generateSvgAnimationPrompt)(e,t,i,s,o);h.info({provider:"OpenAI",model:this.model,questionLength:e.length},"SVG Animation Request");try{let e=await (0,u.V)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:a},{role:"user",content:r.SVG_ANIMATION_REQUEST[o]}],max_tokens:e}),16384,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error("Empty response from AI");return(0,n.f)(this.extractTag(t,"svg_animation")||t)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(h.error({error:e},"OpenAI error"),e instanceof Error){if(e.message===u.z||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],592938)},133458,e=>{e.s(["f",0,"MiniMax-M3.1-Flash"])}],233405,(e,t,r)=>{t.exports=e.x("child_process",()=>require("child_process"))},924868,(e,t,r)=>{t.exports=e.x("fs/promises",()=>require("fs/promises"))},188646,(e,t,r)=>{t.exports=e.x("node:stream/promises",()=>require("node:stream/promises"))},605365,(e,t,r)=>{t.exports=e.x("process",()=>require("process"))},688947,(e,t,r)=>{t.exports=e.x("stream",()=>require("stream"))},345905,(e,t,r)=>{!function(r){"use strict";var n,i=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,s=Math.ceil,o=Math.floor,a="[BigNumber Error] ",l=a+"Number primitive has more than 15 significant digits: ",u=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13];function c(e){var t=0|e;return e>0||e===t?t:t-1}function d(e){for(var t,r,n=1,i=e.length,s=e[0]+"";n<i;){for(r=14-(t=e[n++]+"").length;r--;t="0"+t);s+=t}for(i=s.length;48===s.charCodeAt(--i););return s.slice(0,i+1||1)}function h(e,t){var r,n,i=e.c,s=t.c,o=e.s,a=t.s,l=e.e,u=t.e;if(!o||!a)return null;if(r=i&&!i[0],n=s&&!s[0],r||n)return r?n?0:-a:o;if(o!=a)return o;if(r=o<0,n=l==u,!i||!s)return n?0:!i^r?1:-1;if(!n)return l>u^r?1:-1;for(a=(l=i.length)<(u=s.length)?l:u,o=0;o<a;o++)if(i[o]!=s[o])return i[o]>s[o]^r?1:-1;return l==u?0:l>u^r?1:-1}function p(e,t,r,n){if(e<t||e>r||e!==o(e))throw Error(a+(n||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function f(e){var t=e.c.length-1;return c(e.e/14)==t&&e.c[t]%2!=0}function m(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function g(e,t,r){var n,i;if(t<0){for(i=r+".";++t;i+=r);e=i+e}else if(n=e.length,++t>n){for(i=r,t-=n;--t;i+=r);e+=i}else t<n&&(e=e.slice(0,t)+"."+e.slice(t));return e}if((n=function e(t){var r,n,y,_,E,A,v,b,w,T=j.prototype={constructor:j,toString:null,valueOf:null},I=new j(1),S=20,O=4,C=-7,R=21,P=-1e7,k=1e7,x=!1,N=1,D=0,U={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},M="0123456789abcdefghijklmnopqrstuvwxyz",L=!0;function j(e,t){var r,n,s,a,u,c,d,h,f=this;if(!(f instanceof j))return new j(e,t);if(null==t){if(e&&!0===e._isBigNumber){f.s=e.s,!e.c||e.e>k?f.c=f.e=null:e.e<P?f.c=[f.e=0]:(f.e=e.e,f.c=e.c.slice());return}if((c="number"==typeof e)&&0*e==0){if(f.s=1/e<0?(e=-e,-1):1,e===~~e){for(a=0,u=e;u>=10;u/=10,a++);a>k?f.c=f.e=null:(f.e=a,f.c=[e]);return}h=String(e)}else{if(!i.test(h=String(e)))return w(f,h,c);f.s=45==h.charCodeAt(0)?(h=h.slice(1),-1):1}(a=h.indexOf("."))>-1&&(h=h.replace(".","")),(u=h.search(/e/i))>0?(a<0&&(a=u),a+=+h.slice(u+1),h=h.substring(0,u)):a<0&&(a=h.length)}else{if(p(t,2,M.length,"Base"),10==t&&L)return q(f=new j(e),S+f.e+1,O);if(h=String(e),c="number"==typeof e){if(0*e!=0)return w(f,h,c,t);if(f.s=1/e<0?(h=h.slice(1),-1):1,j.DEBUG&&h.replace(/^0\.0*|\./,"").length>15)throw Error(l+e)}else f.s=45===h.charCodeAt(0)?(h=h.slice(1),-1):1;for(r=M.slice(0,t),a=u=0,d=h.length;u<d;u++)if(0>r.indexOf(n=h.charAt(u))){if("."==n){if(u>a){a=d;continue}}else if(!s&&(h==h.toUpperCase()&&(h=h.toLowerCase())||h==h.toLowerCase()&&(h=h.toUpperCase()))){s=!0,u=-1,a=0;continue}return w(f,String(e),c,t)}c=!1,(a=(h=b(h,t,10,f.s)).indexOf("."))>-1?h=h.replace(".",""):a=h.length}for(u=0;48===h.charCodeAt(u);u++);for(d=h.length;48===h.charCodeAt(--d););if(h=h.slice(u,++d)){if(d-=u,c&&j.DEBUG&&d>15&&(e>0x1fffffffffffff||e!==o(e)))throw Error(l+f.s*e);if((a=a-u-1)>k)f.c=f.e=null;else if(a<P)f.c=[f.e=0];else{if(f.e=a,f.c=[],u=(a+1)%14,a<0&&(u+=14),u<d){for(u&&f.c.push(+h.slice(0,u)),d-=14;u<d;)f.c.push(+h.slice(u,u+=14));u=14-(h=h.slice(u)).length}else u-=d;for(;u--;h+="0");f.c.push(+h)}}else f.c=[f.e=0]}function G(e,t,r,n){var i,s,o,a,l;if(null==r?r=O:p(r,0,8),!e.c)return e.toString();if(i=e.c[0],o=e.e,null==t)l=d(e.c),l=1==n||2==n&&(o<=C||o>=R)?m(l,o):g(l,o,"0");else if(s=(e=q(new j(e),t,r)).e,a=(l=d(e.c)).length,1==n||2==n&&(t<=s||s<=C)){for(;a<t;l+="0",a++);l=m(l,s)}else if(t-=o+(2===n&&s>o),l=g(l,s,"0"),s+1>a){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=s-a)>0)for(s+1==a&&(l+=".");t--;l+="0");return e.s<0&&i?"-"+l:l}function F(e,t){for(var r,n,i=1,s=new j(e[0]);i<e.length;i++)(n=new j(e[i])).s&&(r=h(s,n))!==t&&(0!==r||s.s!==t)||(s=n);return s}function $(e,t,r){for(var n=1,i=t.length;!t[--i];t.pop());for(i=t[0];i>=10;i/=10,n++);return(r=n+14*r-1)>k?e.c=e.e=null:r<P?e.c=[e.e=0]:(e.e=r,e.c=t),e}function q(e,t,r,n){var i,a,l,c,d,h,p,f=e.c;if(f){e:{for(i=1,c=f[0];c>=10;c/=10,i++);if((a=t-i)<0)a+=14,l=t,p=o((d=f[h=0])/u[i-l-1]%10);else if((h=s((a+1)/14))>=f.length)if(n){for(;f.length<=h;f.push(0));d=p=0,i=1,a%=14,l=a-14+1}else break e;else{for(d=c=f[h],i=1;c>=10;c/=10,i++);a%=14,p=(l=a-14+i)<0?0:o(d/u[i-l-1]%10)}if(n=n||t<0||null!=f[h+1]||(l<0?d:d%u[i-l-1]),n=r<4?(p||n)&&(0==r||r==(e.s<0?3:2)):p>5||5==p&&(4==r||n||6==r&&(a>0?l>0?d/u[i-l]:0:f[h-1])%10&1||r==(e.s<0?8:7)),t<1||!f[0])return f.length=0,n?(t-=e.e+1,f[0]=u[(14-t%14)%14],e.e=-t||0):f[0]=e.e=0,e;if(0==a?(f.length=h,c=1,h--):(f.length=h+1,c=u[14-a],f[h]=l>0?o(d/u[i-l]%u[l])*c:0),n)for(;;)if(0==h){for(a=1,l=f[0];l>=10;l/=10,a++);for(l=f[0]+=c,c=1;l>=10;l/=10,c++);a!=c&&(e.e++,1e14==f[0]&&(f[0]=1));break}else{if(f[h]+=c,1e14!=f[h])break;f[h--]=0,c=1}for(a=f.length;0===f[--a];f.pop());}e.e>k?e.c=e.e=null:e.e<P&&(e.c=[e.e=0])}return e}function B(e){var t,r=e.e;return null===r?e.toString():(t=d(e.c),t=r<=C||r>=R?m(t,r):g(t,r,"0"),e.s<0?"-"+t:t)}return j.clone=e,j.ROUND_UP=0,j.ROUND_DOWN=1,j.ROUND_CEIL=2,j.ROUND_FLOOR=3,j.ROUND_HALF_UP=4,j.ROUND_HALF_DOWN=5,j.ROUND_HALF_EVEN=6,j.ROUND_HALF_CEIL=7,j.ROUND_HALF_FLOOR=8,j.EUCLID=9,j.config=j.set=function(e){var t,r;if(null!=e)if("object"==typeof e){if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(p(r=e[t],0,1e9,t),S=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(p(r=e[t],0,8,t),O=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(p(r[0],-1e9,0,t),p(r[1],0,1e9,t),C=r[0],R=r[1]):(p(r,-1e9,1e9,t),C=-(R=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)p(r[0],-1e9,-1,t),p(r[1],1,1e9,t),P=r[0],k=r[1];else if(p(r,-1e9,1e9,t),r)P=-(k=r<0?-r:r);else throw Error(a+t+" cannot be zero: "+r);if(e.hasOwnProperty(t="CRYPTO"))if(!!(r=e[t])===r)if(r)if("u">typeof crypto&&crypto&&(crypto.getRandomValues||crypto.randomBytes))x=r;else throw x=!r,Error(a+"crypto unavailable");else x=r;else throw Error(a+t+" not true or false: "+r);if(e.hasOwnProperty(t="MODULO_MODE")&&(p(r=e[t],0,9,t),N=r),e.hasOwnProperty(t="POW_PRECISION")&&(p(r=e[t],0,1e9,t),D=r),e.hasOwnProperty(t="FORMAT"))if("object"==typeof(r=e[t]))U=r;else throw Error(a+t+" not an object: "+r);if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(a+t+" invalid: "+r);L="0123456789"==r.slice(0,10),M=r}}else throw Error(a+"Object expected: "+e);return{DECIMAL_PLACES:S,ROUNDING_MODE:O,EXPONENTIAL_AT:[C,R],RANGE:[P,k],CRYPTO:x,MODULO_MODE:N,POW_PRECISION:D,FORMAT:U,ALPHABET:M}},j.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!j.DEBUG)return!0;var t,r,n=e.c,i=e.e,s=e.s;e:if("[object Array]"==({}).toString.call(n)){if((1===s||-1===s)&&i>=-1e9&&i<=1e9&&i===o(i)){if(0===n[0]){if(0===i&&1===n.length)return!0;break e}if((t=(i+1)%14)<1&&(t+=14),String(n[0]).length==t){for(t=0;t<n.length;t++)if((r=n[t])<0||r>=1e14||r!==o(r))break e;if(0!==r)return!0}}}else if(null===n&&null===i&&(null===s||1===s||-1===s))return!0;throw Error(a+"Invalid BigNumber: "+e)},j.maximum=j.max=function(){return F(arguments,-1)},j.minimum=j.min=function(){return F(arguments,1)},r=0x20000000000000*Math.random()&2097151?function(){return o(0x20000000000000*Math.random())}:function(){return(0x40000000*Math.random()|0)*8388608+(8388608*Math.random()|0)},j.random=function(e){var t,n,i,l,c,d=0,h=[],f=new j(I);if(null==e?e=S:p(e,0,1e9),l=s(e/14),x)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(l*=2));d<l;)(c=131072*t[d]+(t[d+1]>>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),t[d]=n[0],t[d+1]=n[1]):(h.push(c%1e14),d+=2);d=l/2}else if(crypto.randomBytes){for(t=crypto.randomBytes(l*=7);d<l;)(c=(31&t[d])*0x1000000000000+0x10000000000*t[d+1]+0x100000000*t[d+2]+0x1000000*t[d+3]+(t[d+4]<<16)+(t[d+5]<<8)+t[d+6])>=9e15?crypto.randomBytes(7).copy(t,d):(h.push(c%1e14),d+=7);d=l/7}else throw x=!1,Error(a+"crypto unavailable");if(!x)for(;d<l;)(c=r())<9e15&&(h[d++]=c%1e14);for(l=h[--d],e%=14,l&&e&&(c=u[14-e],h[d]=o(l/c)*c);0===h[d];h.pop(),d--);if(d<0)h=[i=0];else{for(i=-1;0===h[0];h.splice(0,1),i-=14);for(d=1,c=h[0];c>=10;c/=10,d++);d<14&&(i-=14-d)}return f.e=i,f.c=h,f},j.sum=function(){for(var e=1,t=arguments,r=new j(t[0]);e<t.length;)r=r.plus(t[e++]);return r},b=function(){var e="0123456789";function t(e,t,r,n){for(var i,s,o=[0],a=0,l=e.length;a<l;){for(s=o.length;s--;o[s]*=t);for(o[0]+=n.indexOf(e.charAt(a++)),i=0;i<o.length;i++)o[i]>r-1&&(null==o[i+1]&&(o[i+1]=0),o[i+1]+=o[i]/r|0,o[i]%=r)}return o.reverse()}return function(r,n,i,s,o){var a,l,u,c,h,p,f,m,y=r.indexOf("."),_=S,E=O;for(y>=0&&(c=D,D=0,r=r.replace(".",""),p=(m=new j(n)).pow(r.length-y),D=c,m.c=t(g(d(p.c),p.e,"0"),10,i,e),m.e=m.c.length),u=c=(f=t(r,n,i,o?(a=M,e):(a=e,M))).length;0==f[--c];f.pop());if(!f[0])return a.charAt(0);if(y<0?--u:(p.c=f,p.e=u,p.s=s,f=(p=v(p,m,_,E,i)).c,h=p.r,u=p.e),y=f[l=u+_+1],c=i/2,h=h||l<0||null!=f[l+1],h=E<4?(null!=y||h)&&(0==E||E==(p.s<0?3:2)):y>c||y==c&&(4==E||h||6==E&&1&f[l-1]||E==(p.s<0?8:7)),l<1||!f[0])r=h?g(a.charAt(1),-_,a.charAt(0)):a.charAt(0);else{if(f.length=l,h)for(--i;++f[--l]>i;)f[l]=0,l||(++u,f=[1].concat(f));for(c=f.length;!f[--c];);for(y=0,r="";y<=c;r+=a.charAt(f[y++]));r=g(r,u,a.charAt(0))}return r}}(),v=function(){function e(e,t,r){var n,i,s,o,a=0,l=e.length,u=t%1e7,c=t/1e7|0;for(e=e.slice();l--;)n=c*(s=e[l]%1e7)+(o=e[l]/1e7|0)*u,a=((i=u*s+n%1e7*1e7+a)/r|0)+(n/1e7|0)+c*o,e[l]=i%r;return a&&(e=[a].concat(e)),e}function t(e,t,r,n){var i,s;if(r!=n)s=r>n?1:-1;else for(i=s=0;i<r;i++)if(e[i]!=t[i]){s=e[i]>t[i]?1:-1;break}return s}function r(e,t,r,n){for(var i=0;r--;)e[r]-=i,i=+(e[r]<t[r]),e[r]=i*n+e[r]-t[r];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(n,i,s,a,l){var u,d,h,p,f,m,g,y,_,E,A,v,b,w,T,I,S,O=n.s==i.s?1:-1,C=n.c,R=i.c;if(!C||!C[0]||!R||!R[0])return new j(!n.s||!i.s||(C?R&&C[0]==R[0]:!R)?0/0:C&&0==C[0]||!R?0*O:O/0);for(_=(y=new j(O)).c=[],O=s+(d=n.e-i.e)+1,l||(l=1e14,d=c(n.e/14)-c(i.e/14),O=O/14|0),h=0;R[h]==(C[h]||0);h++);if(R[h]>(C[h]||0)&&d--,O<0)_.push(1),p=!0;else{for(w=C.length,I=R.length,h=0,O+=2,(f=o(l/(R[0]+1)))>1&&(R=e(R,f,l),C=e(C,f,l),I=R.length,w=C.length),b=I,A=(E=C.slice(0,I)).length;A<I;E[A++]=0);S=[0].concat(S=R.slice()),T=R[0],R[1]>=l/2&&T++;do{if(f=0,(u=t(R,E,I,A))<0){if(v=E[0],I!=A&&(v=v*l+(E[1]||0)),(f=o(v/T))>1)for(f>=l&&(f=l-1),g=(m=e(R,f,l)).length,A=E.length;1==t(m,E,g,A);)f--,r(m,I<g?S:R,g,l),g=m.length,u=1;else 0==f&&(u=f=1),g=(m=R.slice()).length;if(g<A&&(m=[0].concat(m)),r(E,m,A,l),A=E.length,-1==u)for(;1>t(R,E,I,A);)f++,r(E,I<A?S:R,A,l),A=E.length}else 0===u&&(f++,E=[0]);_[h++]=f,E[0]?E[A++]=C[b]||0:(E=[C[b]],A=1)}while((b++<w||null!=E[0])&&O--)p=null!=E[0],_[0]||_.splice(0,1)}if(1e14==l){for(h=1,O=_[0];O>=10;O/=10,h++);q(y,s+(y.e=h+14*d-1)+1,a,p)}else y.e=d,y.r=+p;return y}}(),n=/^(-?)0([xbo])(?=\w[\w.]*$)/i,y=/^([^.]+)\.$/,_=/^\.([^.]+)$/,E=/^-?(Infinity|NaN)$/,A=/^\s*\+(?=[\w.])|^\s+|\s+$/g,w=function(e,t,r,i){var s,o=r?t:t.replace(A,"");if(E.test(o))e.s=isNaN(o)?null:o<0?-1:1;else{if(!r&&(o=o.replace(n,function(e,t,r){return s="x"==(r=r.toLowerCase())?16:"b"==r?2:8,i&&i!=s?e:t}),i&&(s=i,o=o.replace(y,"$1").replace(_,"0.$1")),t!=o))return new j(o,s);if(j.DEBUG)throw Error(a+"Not a"+(i?" base "+i:"")+" number: "+t);e.s=null}e.c=e.e=null},T.absoluteValue=T.abs=function(){var e=new j(this);return e.s<0&&(e.s=1),e},T.comparedTo=function(e,t){return h(this,new j(e,t))},T.decimalPlaces=T.dp=function(e,t){var r,n,i;if(null!=e)return p(e,0,1e9),null==t?t=O:p(t,0,8),q(new j(this),e+this.e+1,t);if(!(r=this.c))return null;if(n=((i=r.length-1)-c(this.e/14))*14,i=r[i])for(;i%10==0;i/=10,n--);return n<0&&(n=0),n},T.dividedBy=T.div=function(e,t){return v(this,new j(e,t),S,O)},T.dividedToIntegerBy=T.idiv=function(e,t){return v(this,new j(e,t),0,1)},T.exponentiatedBy=T.pow=function(e,t){var r,n,i,l,u,c,d,h,p,m=this;if((e=new j(e)).c&&!e.isInteger())throw Error(a+"Exponent not an integer: "+B(e));if(null!=t&&(t=new j(t)),c=e.e>14,!m.c||!m.c[0]||1==m.c[0]&&!m.e&&1==m.c.length||!e.c||!e.c[0])return p=new j(Math.pow(+B(m),c?e.s*(2-f(e)):+B(e))),t?p.mod(t):p;if(d=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new j(0/0);(n=!d&&m.isInteger()&&t.isInteger())&&(m=m.mod(t))}else{if(e.e>9&&(m.e>0||m.e<-1||(0==m.e?m.c[0]>1||c&&m.c[1]>=24e7:m.c[0]<8e13||c&&m.c[0]<=9999975e7)))return l=m.s<0&&f(e)?-0:0,m.e>-1&&(l=1/l),new j(d?1/l:l);D&&(l=s(D/14+2))}for(c?(r=new j(.5),d&&(e.s=1),h=f(e)):h=(i=Math.abs(+B(e)))%2,p=new j(I);;){if(h){if(!(p=p.times(m)).c)break;l?p.c.length>l&&(p.c.length=l):n&&(p=p.mod(t))}if(i){if(0===(i=o(i/2)))break;h=i%2}else if(q(e=e.times(r),e.e+1,1),e.e>14)h=f(e);else{if(0==(i=+B(e)))break;h=i%2}m=m.times(m),l?m.c&&m.c.length>l&&(m.c.length=l):n&&(m=m.mod(t))}return n?p:(d&&(p=I.div(p)),t?p.mod(t):l?q(p,D,O,u):p)},T.integerValue=function(e){var t=new j(this);return null==e?e=O:p(e,0,8),q(t,t.e+1,e)},T.isEqualTo=T.eq=function(e,t){return 0===h(this,new j(e,t))},T.isFinite=function(){return!!this.c},T.isGreaterThan=T.gt=function(e,t){return h(this,new j(e,t))>0},T.isGreaterThanOrEqualTo=T.gte=function(e,t){return 1===(t=h(this,new j(e,t)))||0===t},T.isInteger=function(){return!!this.c&&c(this.e/14)>this.c.length-2},T.isLessThan=T.lt=function(e,t){return 0>h(this,new j(e,t))},T.isLessThanOrEqualTo=T.lte=function(e,t){return -1===(t=h(this,new j(e,t)))||0===t},T.isNaN=function(){return!this.s},T.isNegative=function(){return this.s<0},T.isPositive=function(){return this.s>0},T.isZero=function(){return!!this.c&&0==this.c[0]},T.minus=function(e,t){var r,n,i,s,o=this.s;if(t=(e=new j(e,t)).s,!o||!t)return new j(0/0);if(o!=t)return e.s=-t,this.plus(e);var a=this.e/14,l=e.e/14,u=this.c,d=e.c;if(!a||!l){if(!u||!d)return u?(e.s=-t,e):new j(d?this:0/0);if(!u[0]||!d[0])return d[0]?(e.s=-t,e):new j(u[0]?this:3==O?-0:0)}if(a=c(a),l=c(l),u=u.slice(),o=a-l){for((s=o<0)?(o=-o,i=u):(l=a,i=d),i.reverse(),t=o;t--;i.push(0));i.reverse()}else for(n=(s=(o=u.length)<(t=d.length))?o:t,o=t=0;t<n;t++)if(u[t]!=d[t]){s=u[t]<d[t];break}if(s&&(i=u,u=d,d=i,e.s=-e.s),(t=(n=d.length)-(r=u.length))>0)for(;t--;u[r++]=0);for(t=1e14-1;n>o;){if(u[--n]<d[n]){for(r=n;r&&!u[--r];u[r]=t);--u[r],u[n]+=1e14}u[n]-=d[n]}for(;0==u[0];u.splice(0,1),--l);return u[0]?$(e,u,l):(e.s=3==O?-1:1,e.c=[e.e=0],e)},T.modulo=T.mod=function(e,t){var r,n;return(e=new j(e,t),this.c&&e.s&&(!e.c||e.c[0]))?e.c&&(!this.c||this.c[0])?(9==N?(n=e.s,e.s=1,r=v(this,e,0,3),e.s=n,r.s*=n):r=v(this,e,0,N),(e=this.minus(r.times(e))).c[0]||1!=N||(e.s=this.s),e):new j(this):new j(0/0)},T.multipliedBy=T.times=function(e,t){var r,n,i,s,o,a,l,u,d,h,p,f,m,g=this.c,y=(e=new j(e,t)).c;if(!g||!y||!g[0]||!y[0])return this.s&&e.s&&(!g||g[0]||y)&&(!y||y[0]||g)?(e.s*=this.s,g&&y?(e.c=[0],e.e=0):e.c=e.e=null):e.c=e.e=e.s=null,e;for(n=c(this.e/14)+c(e.e/14),e.s*=this.s,(l=g.length)<(h=y.length)&&(m=g,g=y,y=m,i=l,l=h,h=i),i=l+h,m=[];i--;m.push(0));for(i=h;--i>=0;){for(r=0,p=y[i]%1e7,f=y[i]/1e7|0,s=i+(o=l);s>i;)a=f*(u=g[--o]%1e7)+(d=g[o]/1e7|0)*p,r=((u=p*u+a%1e7*1e7+m[s]+r)/1e14|0)+(a/1e7|0)+f*d,m[s--]=u%1e14;m[s]=r}return r?++n:m.splice(0,1),$(e,m,n)},T.negated=function(){var e=new j(this);return e.s=-e.s||null,e},T.plus=function(e,t){var r,n=this.s;if(t=(e=new j(e,t)).s,!n||!t)return new j(0/0);if(n!=t)return e.s=-t,this.minus(e);var i=this.e/14,s=e.e/14,o=this.c,a=e.c;if(!i||!s){if(!o||!a)return new j(n/0);if(!o[0]||!a[0])return a[0]?e:new j(o[0]?this:0*n)}if(i=c(i),s=c(s),o=o.slice(),n=i-s){for(n>0?(s=i,r=a):(n=-n,r=o),r.reverse();n--;r.push(0));r.reverse()}for((n=o.length)-(t=a.length)<0&&(r=a,a=o,o=r,t=n),n=0;t;)n=(o[--t]=o[t]+a[t]+n)/1e14|0,o[t]=1e14===o[t]?0:o[t]%1e14;return n&&(o=[n].concat(o),++s),$(e,o,s)},T.precision=T.sd=function(e,t){var r,n,i;if(null!=e&&!!e!==e)return p(e,1,1e9),null==t?t=O:p(t,0,8),q(new j(this),e,t);if(!(r=this.c))return null;if(n=14*(i=r.length-1)+1,i=r[i]){for(;i%10==0;i/=10,n--);for(i=r[0];i>=10;i/=10,n++);}return e&&this.e+1>n&&(n=this.e+1),n},T.shiftedBy=function(e){return p(e,-0x1fffffffffffff,0x1fffffffffffff),this.times("1e"+e)},T.squareRoot=T.sqrt=function(){var e,t,r,n,i,s=this.c,o=this.s,a=this.e,l=S+4,u=new j("0.5");if(1!==o||!s||!s[0])return new j(!o||o<0&&(!s||s[0])?0/0:s?this:1/0);if(0==(o=Math.sqrt(+B(this)))||1/0==o?(((t=d(s)).length+a)%2==0&&(t+="0"),o=Math.sqrt(+t),a=c((a+1)/2)-(a<0||a%2),r=new j(t=1/0==o?"5e"+a:(t=o.toExponential()).slice(0,t.indexOf("e")+1)+a)):r=new j(o+""),r.c[0]){for((o=(a=r.e)+l)<3&&(o=0);;)if(i=r,r=u.times(i.plus(v(this,i,l,1))),d(i.c).slice(0,o)===(t=d(r.c)).slice(0,o)){if(r.e<a&&--o,"9999"!=(t=t.slice(o-3,o+1))&&(n||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(q(r,r.e+S+2,1),e=!r.times(r).eq(this));break}if(!n&&(q(i,i.e+S+2,0),i.times(i).eq(this))){r=i;break}l+=4,o+=4,n=1}}return q(r,r.e+S+1,O,e)},T.toExponential=function(e,t){return null!=e&&(p(e,0,1e9),e++),G(this,e,t,1)},T.toFixed=function(e,t){return null!=e&&(p(e,0,1e9),e=e+this.e+1),G(this,e,t)},T.toFormat=function(e,t,r){var n;if(null==r)null!=e&&t&&"object"==typeof t?(r=t,t=null):e&&"object"==typeof e?(r=e,e=t=null):r=U;else if("object"!=typeof r)throw Error(a+"Argument not an object: "+r);if(n=this.toFixed(e,t),this.c){var i,s=n.split("."),o=+r.groupSize,l=+r.secondaryGroupSize,u=r.groupSeparator||"",c=s[0],d=s[1],h=this.s<0,p=h?c.slice(1):c,f=p.length;if(l&&(i=o,o=l,l=i,f-=i),o>0&&f>0){for(i=f%o||o,c=p.substr(0,i);i<f;i+=o)c+=u+p.substr(i,o);l>0&&(c+=u+p.slice(i)),h&&(c="-"+c)}n=d?c+(r.decimalSeparator||"")+((l=+r.fractionGroupSize)?d.replace(RegExp("\\d{"+l+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):d):c}return(r.prefix||"")+n+(r.suffix||"")},T.toFraction=function(e){var t,r,n,i,s,o,l,c,h,p,f,m,g=this.c;if(null!=e&&(!(l=new j(e)).isInteger()&&(l.c||1!==l.s)||l.lt(I)))throw Error(a+"Argument "+(l.isInteger()?"out of range: ":"not an integer: ")+B(l));if(!g)return new j(this);for(t=new j(I),h=r=new j(I),n=c=new j(I),m=d(g),s=t.e=m.length-this.e-1,t.c[0]=u[(o=s%14)<0?14+o:o],e=!e||l.comparedTo(t)>0?s>0?t:h:l,o=k,k=1/0,l=new j(m),c.c[0]=0;p=v(l,t,0,1),1!=(i=r.plus(p.times(n))).comparedTo(e);)r=n,n=i,h=c.plus(p.times(i=h)),c=i,t=l.minus(p.times(i=t)),l=i;return i=v(e.minus(r),n,0,1),c=c.plus(i.times(h)),r=r.plus(i.times(n)),c.s=h.s=this.s,s*=2,f=1>v(h,n,s,O).minus(this).abs().comparedTo(v(c,r,s,O).minus(this).abs())?[h,n]:[c,r],k=o,f},T.toNumber=function(){return+B(this)},T.toPrecision=function(e,t){return null!=e&&p(e,1,1e9),G(this,e,t,2)},T.toString=function(e){var t,r=this,n=r.s,i=r.e;return null===i?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=i<=C||i>=R?m(d(r.c),i):g(d(r.c),i,"0"):10===e&&L?t=g(d((r=q(new j(r),S+i+1,O)).c),r.e,"0"):(p(e,2,M.length,"Base"),t=b(g(d(r.c),i,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},T.valueOf=T.toJSON=function(){return B(this)},T._isBigNumber=!0,null!=t&&j.set(t),j}()).default=n.BigNumber=n,"function"==typeof define&&define.amd)e.r,void 0!==n&&e.v(n);else t.exports?t.exports=n:(r||(r="u">typeof self&&self?self:window),r.BigNumber=n)}(e.e)},73827,(e,t,r)=>{t.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}},357660,(e,t,r)=>{t.exports={name:"google-auth-library",version:"10.9.1",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=18"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"8.1.2","google-logging-utils":"1.1.3",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}},301158,(e,t,r)=>{var n=e.r(364349).stringify,i=e.r(767104);t.exports=function(e){return{parse:i(e),stringify:n}},t.exports.parse=i(),t.exports.stringify=n},767104,(e,t,r)=>{var n=null;let i=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,s=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/;t.exports=function(t){"use strict";var r={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(null!=t){if(!0===t.strict&&(r.strict=!0),!0===t.storeAsString&&(r.storeAsString=!0),r.alwaysParseAsBig=!0===t.alwaysParseAsBig&&t.alwaysParseAsBig,r.useNativeBigInt=!0===t.useNativeBigInt&&t.useNativeBigInt,void 0!==t.constructorAction)if("error"===t.constructorAction||"ignore"===t.constructorAction||"preserve"===t.constructorAction)r.constructorAction=t.constructorAction;else throw Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(void 0!==t.protoAction)if("error"===t.protoAction||"ignore"===t.protoAction||"preserve"===t.protoAction)r.protoAction=t.protoAction;else throw Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var o,a,l,u,c={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:" "},d=function(e){throw{name:"SyntaxError",message:e,at:o,text:l}},h=function(e){return e&&e!==a&&d("Expected '"+e+"' instead of '"+a+"'"),a=l.charAt(o),o+=1,a},p=function(){var t,i="";for("-"===a&&(i="-",h("-"));a>="0"&&a<="9";)i+=a,h();if("."===a)for(i+=".";h()&&a>="0"&&a<="9";)i+=a;if("e"===a||"E"===a)for(i+=a,h(),("-"===a||"+"===a)&&(i+=a,h());a>="0"&&a<="9";)i+=a,h();if(isFinite(t=+i))return(null==n&&(n=e.r(345905)),i.length>15)?r.storeAsString?i:r.useNativeBigInt?BigInt(i):new n(i):r.alwaysParseAsBig?r.useNativeBigInt?BigInt(t):new n(t):t;d("Bad number")},f=function(){var e,t,r,n="";if('"'===a)for(var i=o;h();){if('"'===a)return o-1>i&&(n+=l.substring(i,o-1)),h(),n;if("\\"===a){if(o-1>i&&(n+=l.substring(i,o-1)),h(),"u"===a){for(t=0,r=0;t<4&&isFinite(e=parseInt(h(),16));t+=1)r=16*r+e;n+=String.fromCharCode(r)}else if("string"==typeof c[a])n+=c[a];else break;i=o}}d("Bad string")},m=function(){for(;a&&a<=" ";)h()},g=function(){switch(a){case"t":return h("t"),h("r"),h("u"),h("e"),!0;case"f":return h("f"),h("a"),h("l"),h("s"),h("e"),!1;case"n":return h("n"),h("u"),h("l"),h("l"),null}d("Unexpected '"+a+"'")},y=function(){var e=[];if("["===a){if(h("["),m(),"]"===a)return h("]"),e;for(;a;){if(e.push(u()),m(),"]"===a)return h("]"),e;h(","),m()}}d("Bad array")},_=function(){var e,t=Object.create(null);if("{"===a){if(h("{"),m(),"}"===a)return h("}"),t;for(;a;){if(e=f(),m(),h(":"),!0===r.strict&&Object.hasOwnProperty.call(t,e)&&d('Duplicate key "'+e+'"'),!0===i.test(e)?"error"===r.protoAction?d("Object contains forbidden prototype property"):"ignore"===r.protoAction?u():t[e]=u():!0===s.test(e)?"error"===r.constructorAction?d("Object contains forbidden constructor property"):"ignore"===r.constructorAction?u():t[e]=u():t[e]=u(),m(),"}"===a)return h("}"),t;h(","),m()}}d("Bad object")};return u=function(){switch(m(),a){case"{":return _();case"[":return y();case'"':return f();case"-":return p();default:return a>="0"&&a<="9"?p():g()}},function(e,t){var r;return l=e+"",o=0,a=" ",r=u(),m(),a&&d("Syntax error"),"function"==typeof t?function e(r,n){var i,s=r[n];return s&&"object"==typeof s&&Object.keys(s).forEach(function(t){void 0!==(i=e(s,t))?s[t]=i:delete s[t]}),t.call(r,n,s)}({"":r},""):r}}},364349,(e,t,r)=>{var n=e.r(345905),i=t.exports;!function(){"use strict";var e,t,r,s=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,o={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function a(e){return s.lastIndex=0,s.test(e)?'"'+e.replace(s,function(e){var t=o[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}"function"!=typeof i.stringify&&(i.stringify=function(i,s,o){var l;if(e="",t="","number"==typeof o)for(l=0;l<o;l+=1)t+=" ";else"string"==typeof o&&(t=o);if(r=s,s&&"function"!=typeof s&&("object"!=typeof s||"number"!=typeof s.length))throw Error("JSON.stringify");return function i(s,o){var l,u,c,d,h,p=e,f=o[s],m=null!=f&&(f instanceof n||n.isBigNumber(f));switch(f&&"object"==typeof f&&"function"==typeof f.toJSON&&(f=f.toJSON(s)),"function"==typeof r&&(f=r.call(o,s,f)),typeof f){case"string":if(m)return f;return a(f);case"number":return isFinite(f)?String(f):"null";case"boolean":case"null":case"bigint":return String(f);case"object":if(!f)return"null";if(e+=t,h=[],"[object Array]"===Object.prototype.toString.apply(f)){for(d=f.length,l=0;l<d;l+=1)h[l]=i(l,f)||"null";return c=0===h.length?"[]":e?"[\n"+e+h.join(",\n"+e)+"\n"+p+"]":"["+h.join(",")+"]",e=p,c}if(r&&"object"==typeof r)for(d=r.length,l=0;l<d;l+=1)"string"==typeof r[l]&&(c=i(u=r[l],f))&&h.push(a(u)+(e?": ":":")+c);else Object.keys(f).forEach(function(t){var r=i(t,f);r&&h.push(a(t)+(e?": ":":")+r)});return c=0===h.length?"{}":e?"{\n"+e+h.join(",\n"+e)+"\n"+p+"}":"{"+h.join(",")+"}",e=p,c}}("",{"":i})})}()},757067,(e,t,r)=>{var n,i=e.r(223469).Buffer,s=e.r(254799),o=e.r(732955),a=e.r(224361),l="secret must be a string or buffer",u="key must be a string or a buffer",c="function"==typeof s.createPublicKey;function d(e){if(!i.isBuffer(e)&&"string"!=typeof e&&(!c||"object"!=typeof e||"string"!=typeof e.type||"string"!=typeof e.asymmetricKeyType||"function"!=typeof e.export))throw m(u)}function h(e){if(!i.isBuffer(e)&&"string"!=typeof e&&"object"!=typeof e)throw m("key must be a string, a buffer or an object")}function p(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function f(e){var t=4-(e=e.toString()).length%4;if(4!==t)for(var r=0;r<t;++r)e+="=";return e.replace(/\-/g,"+").replace(/_/g,"/")}function m(e){var t=[].slice.call(arguments,1);return TypeError(a.format.bind(a,e).apply(null,t))}function g(e){var t;return t=e,i.isBuffer(t)||"string"==typeof t||(e=JSON.stringify(e)),e}function y(e){return function(t,r){!function(e){if(!i.isBuffer(e)){if("string"!=typeof e){if(!c||"object"!=typeof e||"secret"!==e.type||"function"!=typeof e.export)throw m(l)}}}(r),t=g(t);var n=s.createHmac("sha"+e,r);return p((n.update(t),n.digest("base64")))}}c&&(u+=" or a KeyObject",l+="or a KeyObject");var _="timingSafeEqual"in s?function(e,t){return e.byteLength===t.byteLength&&s.timingSafeEqual(e,t)}:function(t,r){return n||(n=e.r(922691)),n(t,r)};function E(e){return function(t,r,n){var s=y(e)(t,n);return _(i.from(r),i.from(s))}}function A(e){return function(t,r){h(r),t=g(t);var n=s.createSign("RSA-SHA"+e);return p((n.update(t),n.sign(r,"base64")))}}function v(e){return function(t,r,n){d(n),t=g(t),r=f(r);var i=s.createVerify("RSA-SHA"+e);return i.update(t),i.verify(n,r,"base64")}}function b(e){return function(t,r){h(r),t=g(t);var n=s.createSign("RSA-SHA"+e);return p((n.update(t),n.sign({key:r,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}function w(e){return function(t,r,n){d(n),t=g(t),r=f(r);var i=s.createVerify("RSA-SHA"+e);return i.update(t),i.verify({key:n,padding:s.constants.RSA_PKCS1_PSS_PADDING,saltLength:s.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function T(e){var t=A(e);return function(){var r=t.apply(null,arguments);return o.derToJose(r,"ES"+e)}}function I(e){var t=v(e);return function(r,n,i){return t(r,n=o.joseToDer(n,"ES"+e).toString("base64"),i)}}function S(){return function(){return""}}function O(){return function(e,t){return""===t}}t.exports=function(e){var t=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!t)throw m('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);var r=(t[1]||t[3]).toLowerCase(),n=t[2];return{sign:({hs:y,rs:A,ps:b,es:T,none:S})[r](n),verify:({hs:E,rs:v,ps:w,es:I,none:O})[r](n)}}},258184,(e,t,r)=>{var n=e.r(614743),i=e.r(148233);r.ALGORITHMS=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],r.sign=n.sign,r.verify=i.verify,r.decode=i.decode,r.isValid=i.isValid,r.createSign=function(e){return new n(e)},r.createVerify=function(e){return new i(e)}},41949,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(688947);function s(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)return this.buffer=n.alloc(0),this;if("function"==typeof e.pipe)return this.buffer=n.alloc(0),e.pipe(this),this;if(e.length||"object"==typeof e)return this.buffer=e,this.writable=!1,process.nextTick((function(){this.emit("end",e),this.readable=!1,this.emit("close")}).bind(this)),this;throw TypeError("Unexpected data type ("+typeof e+")")}e.r(224361).inherits(s,i),s.prototype.write=function(e){this.buffer=n.concat([this.buffer,n.from(e)]),this.emit("data",e)},s.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1},t.exports=s},614743,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(41949),s=e.r(757067),o=e.r(688947),a=e.r(576872),l=e.r(224361);function u(e,t){return n.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function c(e){var t,r,n,i=e.header,o=e.payload,c=e.secret||e.privateKey,d=e.encoding,h=s(i.alg),p=(t=(t=d)||"utf8",r=u(a(i),"binary"),n=u(a(o),t),l.format("%s.%s",r,n)),f=h.sign(p,c);return l.format("%s.%s",p,f)}function d(e){var t=e.secret;if(t=null==(t=null==t?e.privateKey:t)?e.key:t,!0===/^hs/i.test(e.header.alg)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new i(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=new i(e.payload),this.secret.once("close",(function(){!this.payload.writable&&this.readable&&this.sign()}).bind(this)),this.payload.once("close",(function(){!this.secret.writable&&this.readable&&this.sign()}).bind(this))}l.inherits(d,o),d.prototype.sign=function(){try{var e=c({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},d.sign=c,t.exports=d},576872,(e,t,r)=>{var n=e.r(500874).Buffer;t.exports=function(e){return"string"==typeof e?e:"number"==typeof e||n.isBuffer(e)?e.toString():JSON.stringify(e)}},148233,(e,t,r)=>{var n=e.r(223469).Buffer,i=e.r(41949),s=e.r(757067),o=e.r(688947),a=e.r(576872),l=e.r(224361),u=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function c(e){var t=e.split(".",1)[0],r=n.from(t,"base64").toString("binary");if("[object Object]"===Object.prototype.toString.call(r))return r;try{return JSON.parse(r)}catch(e){return}}function d(e){return e.split(".")[2]}function h(e){return u.test(e)&&!!c(e)}function p(e,t,r){if(!t){var n=Error("Missing algorithm parameter for jws.verify");throw n.code="MISSING_ALGORITHM",n}var i=d(e=a(e)),o=e.split(".",2).join(".");return s(t).verify(o,i,r)}function f(e,t){if(t=t||{},!h(e=a(e)))return null;var r,i,s=c(e);if(!s)return null;var o=(r=r||"utf8",i=e.split(".")[1],n.from(i,"base64").toString(r));return("JWT"===s.typ||t.json)&&(o=JSON.parse(o,t.encoding)),{header:s,payload:o,signature:d(e)}}function m(e){var t=(e=e||{}).secret;if(t=null==(t=null==t?e.publicKey:t)?e.key:t,!0===/^hs/i.test(e.algorithm)&&null==t)throw TypeError("secret must be a string or buffer or a KeyObject");var r=new i(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=new i(e.signature),this.secret.once("close",(function(){!this.signature.writable&&this.readable&&this.verify()}).bind(this)),this.signature.once("close",(function(){!this.secret.writable&&this.readable&&this.verify()}).bind(this))}l.inherits(m,o),m.prototype.verify=function(){try{var e=p(this.signature.buffer,this.algorithm,this.key.buffer),t=f(this.signature.buffer,this.encoding);return this.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},m.decode=f,m.isValid=h,m.verify=p,t.exports=m},774167,(e,t,r)=>{t.exports=e.r(318263)},318263,(e,t,r)=>{var n=e.r(138047);r.operation=function(e){return new n(r.timeouts(e),{forever:e&&(e.forever||1/0===e.retries),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},r.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<t.retries;i++)n.push(this.createTimeout(i,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(i,t)),n.sort(function(e,t){return e-t}),n},r.createTimeout=function(e,t){var r=Math.round((t.randomize?Math.random()+1:1)*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(r,t.maxTimeout)},r.wrap=function(e,t,n){if(t instanceof Array&&(n=t,t=null),!n)for(var i in n=[],e)"function"==typeof e[i]&&n.push(i);for(var s=0;s<n.length;s++){var o=n[s],a=e[o];e[o]=(function(n){var i=r.operation(t),s=Array.prototype.slice.call(arguments,1),o=s.pop();s.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){n.apply(e,s)})}).bind(e,a),e[o].options=t}}},138047,(e,t,r)=>{function n(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r)if(!this._cachedTimeouts)return!1;else this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var i=this._errors[n],s=i.message,o=(e[s]||0)+1;e[s]=o,o>=r&&(t=i,r=o)}return t}},223469,(e,t,r)=>{var n=e.r(500874),i=n.Buffer;function s(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(s(n,r),r.Buffer=o),o.prototype=Object.create(i.prototype),s(i,o),o.from=function(e,t,r){if("number"==typeof e)throw TypeError("Argument must not be a number");return i(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},o.allocUnsafe=function(e){if("number"!=typeof e)throw TypeError("Argument must be a number");return i(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw TypeError("Argument must be a number");return n.SlowBuffer(e)}}];
37
37
 
38
- //# sourceMappingURL=%5Broot-of-the-server%5D__1q9wd_k6hcd5m._.js.map
38
+ //# sourceMappingURL=%5Broot-of-the-server%5D__0zb48en2m8yk0._.js.map