decocms 4.290.0 → 4.290.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/dist/client/assets/{AlertCircle-zvRWKcqF.js → AlertCircle-D6hOsGaX.js} +1 -1
  2. package/dist/client/assets/{AreaChart-Ck-GfvRW.js → AreaChart-Owl51y6w.js} +1 -1
  3. package/dist/client/assets/{ArrowLeft-_cwbAq56.js → ArrowLeft-CRVrq-zT.js} +1 -1
  4. package/dist/client/assets/{ArrowUp-Cz94C6Pj.js → ArrowUp-DArBeZUU.js} +1 -1
  5. package/dist/client/assets/{Check-Dos-rhow.js → Check-q8CyHNkV.js} +1 -1
  6. package/dist/client/assets/{CheckCircle-r2V5ouch.js → CheckCircle-DDWvpLsz.js} +1 -1
  7. package/dist/client/assets/{ChevronDown-CR3rze4u.js → ChevronDown-D2S5GFJf.js} +1 -1
  8. package/dist/client/assets/{ChevronRight-CyjwUHQU.js → ChevronRight-xBGZA1CC.js} +1 -1
  9. package/dist/client/assets/{ChevronSelectorVertical-DqKnQvmy.js → ChevronSelectorVertical-scetYlWI.js} +1 -1
  10. package/dist/client/assets/{ChevronUp-YAfgm-J4.js → ChevronUp-Du6zL7V6.js} +1 -1
  11. package/dist/client/assets/{Copy01-BRL_qlcK.js → Copy01-BeAp_OhT.js} +1 -1
  12. package/dist/client/assets/{CreditCard01-vmZJItcX.js → CreditCard01-DaFxsa8w.js} +1 -1
  13. package/dist/client/assets/{DotsVertical-DGbK5RhV.js → DotsVertical-Bh_0m6-Z.js} +1 -1
  14. package/dist/client/assets/{Download01-w-BM7pNG.js → Download01-wdKcsQMp.js} +1 -1
  15. package/dist/client/assets/{Eye-csFOtdcR.js → Eye-daFmHPv7.js} +1 -1
  16. package/dist/client/assets/{FilterLines-BVZFr9pz.js → FilterLines-CyzquHVP.js} +1 -1
  17. package/dist/client/assets/{Globe01-CZHqbNr6.js → Globe01-B3xXFvuz.js} +1 -1
  18. package/dist/client/assets/{Globe04-COtuGcOF.js → Globe04-IMWTB-6u.js} +1 -1
  19. package/dist/client/assets/{HardDrive-C-OHXRNJ.js → HardDrive-Cnj66tgx.js} +1 -1
  20. package/dist/client/assets/{Key01-CwoUjZ5V.js → Key01-WN7fiJNh.js} +1 -1
  21. package/dist/client/assets/{LinkExternal01-CIw7nYl8.js → LinkExternal01-NVTrLYzQ.js} +1 -1
  22. package/dist/client/assets/{LockUnlocked01-C0jiIs5o.js → LockUnlocked01-UoYs296Z.js} +1 -1
  23. package/dist/client/assets/{LogOut01-BKxRGHAw.js → LogOut01-D1nkaaHe.js} +1 -1
  24. package/dist/client/assets/{Monitor01-Dqkh5RuB.js → Monitor01-DhR87Mqh.js} +1 -1
  25. package/dist/client/assets/{Palette-CYn01zuF.js → Palette-D0TGc_zV.js} +1 -1
  26. package/dist/client/assets/{Play-D_Yzq5zF.js → Play-BMS2dZrJ.js} +1 -1
  27. package/dist/client/assets/{Plus-D0ASaue8.js → Plus-DSvFjoZt.js} +1 -1
  28. package/dist/client/assets/{SearchLg-DbbbwIQ4.js → SearchLg-BX4VpE4K.js} +1 -1
  29. package/dist/client/assets/{SearchMd-CoMStJvj.js → SearchMd-C1J97ENv.js} +1 -1
  30. package/dist/client/assets/{Settings02-D3KW-Y48.js → Settings02-CSvEY5HU.js} +1 -1
  31. package/dist/client/assets/{Share07-C8BTB743.js → Share07-DI_6507e.js} +1 -1
  32. package/dist/client/assets/{Shield01-D1sUFpWP.js → Shield01-C1uyh9yl.js} +1 -1
  33. package/dist/client/assets/{Stars01-T-xvq3eE.js → Stars01-BIKScFED.js} +1 -1
  34. package/dist/client/assets/{Stars02-ImmvpRwJ.js → Stars02-C_7Lf3Xh.js} +1 -1
  35. package/dist/client/assets/{Sun-fdxKgBuH.js → Sun-DwdMCH_e.js} +1 -1
  36. package/dist/client/assets/{SwitchHorizontal01-BcmgHCZX.js → SwitchHorizontal01-DyycHaZu.js} +1 -1
  37. package/dist/client/assets/{Tool01-Bso4tJnD.js → Tool01-DEJT7lYv.js} +1 -1
  38. package/dist/client/assets/{Tool02-B6gSGQvZ.js → Tool02-jeUyhSCn.js} +1 -1
  39. package/dist/client/assets/{Trash01-BEJv6VxP.js → Trash01-7XsFF_0J.js} +1 -1
  40. package/dist/client/assets/{TrendUp01-9MzyhwM4.js → TrendUp01-CGgw-Re1.js} +1 -1
  41. package/dist/client/assets/{Upload01-DoLy5iSI.js → Upload01-DauIOL6y.js} +1 -1
  42. package/dist/client/assets/{User01-BdXNIYw2.js → User01-DYwUi9ic.js} +1 -1
  43. package/dist/client/assets/{UserSquare-DzKFjifU.js → UserSquare-Dwkndv7k.js} +1 -1
  44. package/dist/client/assets/{Users01-DhPTaJBO.js → Users01-BY3aZPe_.js} +1 -1
  45. package/dist/client/assets/{Users03-Bfaex32i.js → Users03-CGlxAVas.js} +1 -1
  46. package/dist/client/assets/{XCircle-CTCe4RVG.js → XCircle-k_RB6Agi.js} +1 -1
  47. package/dist/client/assets/{XClose-B5dSJ_GG.js → XClose-BmdyUaQT.js} +1 -1
  48. package/dist/client/assets/{YAxis-7MAgtkXn.js → YAxis-BxpaMbT5.js} +1 -1
  49. package/dist/client/assets/{Zap-C4ROg_eo.js → Zap-CSZIYR6r.js} +1 -1
  50. package/dist/client/assets/{ZapSquare-DC_9rhik.js → ZapSquare-CmFyRNKp.js} +1 -1
  51. package/dist/client/assets/{access-gate-zZkfXH0G.js → access-gate-BGEE0a8s.js} +1 -1
  52. package/dist/client/assets/{agent-icon-BW1mP5IA.js → agent-icon-DsxCWWiJ.js} +1 -1
  53. package/dist/client/assets/{agents-list-DsT9q8_s.js → agents-list-BhAPOQe6.js} +1 -1
  54. package/dist/client/assets/{ai-providers-T5BeHknA.js → ai-providers-CCKzWIOe.js} +1 -1
  55. package/dist/client/assets/{alert-CDZLgFr7.js → alert-B6qdtrsd.js} +1 -1
  56. package/dist/client/assets/{alert-dialog-CQH3L_5Z.js → alert-dialog-DK9Vj_7c.js} +1 -1
  57. package/dist/client/assets/{api-keys-CWS4teZD.js → api-keys-BlSA7agq.js} +1 -1
  58. package/dist/client/assets/{app-editor-CieSlOHq.js → app-editor-w6UUhsa0.js} +1 -1
  59. package/dist/client/assets/{auth-1GNLiIJW.js → auth-DmliiXmW.js} +1 -1
  60. package/dist/client/assets/{auth-catchall-UT1g3-Km.js → auth-catchall-BMzTxbgq.js} +1 -1
  61. package/dist/client/assets/{auth-entry-YgbH8cz5.js → auth-entry-DF4NDAbh.js} +1 -1
  62. package/dist/client/assets/{auth-split-layout-BFjTfZVn.js → auth-split-layout-C_Jd8pGv.js} +1 -1
  63. package/dist/client/assets/{authenticate-and-persist-oauth-zPGlCc_b.js → authenticate-and-persist-oauth-CqecjQ7t.js} +1 -1
  64. package/dist/client/assets/{automation-list-row-BIBs6qRz.js → automation-list-row-EpiYBtEw.js} +1 -1
  65. package/dist/client/assets/{automation-runs-Pzlry2jV.js → automation-runs-BwunUz8L.js} +1 -1
  66. package/dist/client/assets/{automations-DkBTzPHI.js → automations-D1dMsyDs.js} +1 -1
  67. package/dist/client/assets/{avatar-D326FubZ.js → avatar-BEcEkB0r.js} +1 -1
  68. package/dist/client/assets/{badge-Cx2ZjW7s.js → badge-CCx4nbXX.js} +1 -1
  69. package/dist/client/assets/{block-document-BWSvFjqD.js → block-document-J82YP8-R.js} +1 -1
  70. package/dist/client/assets/{breadcrumb-B31zIq_0.js → breadcrumb-B9MYacKP.js} +1 -1
  71. package/dist/client/assets/{buckets-COgrqX__.js → buckets-D6UwkE5K.js} +1 -1
  72. package/dist/client/assets/{bulk-category-panel-k_4SNNFi.js → bulk-category-panel-CAJ6KVNe.js} +1 -1
  73. package/dist/client/assets/{capability-load-error-BTMC50He.js → capability-load-error-BG-mWRax.js} +1 -1
  74. package/dist/client/assets/{cards-zv-WD-LY.js → cards-DfeM5jv6.js} +1 -1
  75. package/dist/client/assets/{category-editor-Cz8QZaXA.js → category-editor-Dgy0tafw.js} +1 -1
  76. package/dist/client/assets/{chart-BnraQYTF.js → chart-YXcVUhA9.js} +1 -1
  77. package/dist/client/assets/{chat-context-BMMWA8si.js → chat-context-CjlInIox.js} +1 -1
  78. package/dist/client/assets/{checkbox-BTRdTYWF.js → checkbox-BN58xHHu.js} +1 -1
  79. package/dist/client/assets/{choose-editor-DrpiCf-S.js → choose-editor-D0omK8fY.js} +1 -1
  80. package/dist/client/assets/{cli-auth-success-DF7bjGTT.js → cli-auth-success--osLwuY-.js} +1 -1
  81. package/dist/client/assets/{collection-detail-BZW-3inU.js → collection-detail-CLfwSTzW.js} +1 -1
  82. package/dist/client/assets/{collection-display-button-1x3DnOn7.js → collection-display-button-C852qFJv.js} +1 -1
  83. package/dist/client/assets/{collection-search-oDphJkvA.js → collection-search-BMSRQGim.js} +1 -1
  84. package/dist/client/assets/{collection-table-wrapper-CdUbIDKH.js → collection-table-wrapper-CEDwEv0x.js} +1 -1
  85. package/dist/client/assets/{collection-tabs-D_x_VewO.js → collection-tabs-CSAaMxnX.js} +1 -1
  86. package/dist/client/assets/{command-RwpBMX89.js → command-DkyhyOWV.js} +1 -1
  87. package/dist/client/assets/{commerce-onboarding-CdYMbsTi.js → commerce-onboarding-tALHXH9r.js} +1 -1
  88. package/dist/client/assets/{config-DnyEkXI1.js → config-BrNmcyEv.js} +1 -1
  89. package/dist/client/assets/{connect-DgCCnZVl.js → connect-D3pcg_Wo.js} +1 -1
  90. package/dist/client/assets/{connection-DTFB45r6.js → connection-C3_R-app.js} +1 -1
  91. package/dist/client/assets/{connection-card-ChMf372j.js → connection-card-DZI_V9Jx.js} +1 -1
  92. package/dist/client/assets/{connection-detail-BjWe4h4x.js → connection-detail-ocTvSuTz.js} +1 -1
  93. package/dist/client/assets/{connection-form-helpers-DNE6M9in.js → connection-form-helpers-DJFiiXi4.js} +1 -1
  94. package/dist/client/assets/{connections-C3pmW9UK.js → connections-CY7U_53v.js} +1 -1
  95. package/dist/client/assets/{decopilot-sse-pool-BiZ834nh.js → decopilot-sse-pool-CsiIgBBB.js} +1 -1
  96. package/dist/client/assets/{dialog-BLy0dOe5.js → dialog-B2EfhvuM.js} +1 -1
  97. package/dist/client/assets/{domain-settings-BepwyTQ7.js → domain-settings-DSJUiATx.js} +1 -1
  98. package/dist/client/assets/{drawer-B1X9HvdB.js → drawer-EAMk0KQN.js} +1 -1
  99. package/dist/client/assets/{dropdown-menu-uB_shXH1.js → dropdown-menu-B-n-Cwvn.js} +1 -1
  100. package/dist/client/assets/{empty-state-CaOyPR6S.js → empty-state-DOjJP8gs.js} +1 -1
  101. package/dist/client/assets/{extract-connection-data-Cy4ReNU4.js → extract-connection-data-DyV1rcGj.js} +1 -1
  102. package/dist/client/assets/{file-explorer-Do9GKq3N.js → file-explorer-BIOEezX2.js} +1 -1
  103. package/dist/client/assets/{file-type-icon-CCoyuB0G.js → file-type-icon-BQXB_eKr.js} +1 -1
  104. package/dist/client/assets/{form-DQdObmwx.js → form-s4pkSrU6.js} +1 -1
  105. package/dist/client/assets/{general-8u_SVfRF.js → general-mPHPybAI.js} +1 -1
  106. package/dist/client/assets/{github-repo-picker-Bqk_aPte.js → github-repo-picker-DDmbVAuc.js} +1 -1
  107. package/dist/client/assets/{hooks-By3FagIo.js → hooks-B27brYwt.js} +1 -1
  108. package/dist/client/assets/{index-DGgUoaf0.js → index--vrjZNmU.js} +1 -1
  109. package/dist/client/assets/{index-rwGWb_g-.js → index-5ZYFooZo.js} +1 -1
  110. package/dist/client/assets/{index-CJnvyTfj.js → index-CP75igKL.js} +6 -6
  111. package/dist/client/assets/{index-OnStvvBp.js → index-Cw2YdLqh.js} +1 -1
  112. package/dist/client/assets/{index-B6LMLugW.js → index-D4k8y7nn.js} +1 -1
  113. package/dist/client/assets/{index-CemuMBtE.js → index-DROh0hSo.js} +1 -1
  114. package/dist/client/assets/{index-CZmUeD7C.js → index-DvSo9mQw.js} +3 -3
  115. package/dist/client/assets/{index-CiIHZGJP.js → index-DxYQLXNE.js} +1 -1
  116. package/dist/client/assets/{index-Bm4fCltS.js → index-ScpfvHdz.js} +1 -1
  117. package/dist/client/assets/{index-redirect-CqpBtOnM.js → index-redirect-NKnevhpO.js} +1 -1
  118. package/dist/client/assets/{infra-billing-CEy7pS50.js → infra-billing-BF5TQkre.js} +1 -1
  119. package/dist/client/assets/{input-DhVX4iCG.js → input-CuOPbA1m.js} +1 -1
  120. package/dist/client/assets/{integration-icon-DO6YPHfo.js → integration-icon-B-2TVbwA.js} +1 -1
  121. package/dist/client/assets/{invite-member-dialog-BQ1wPEJ3.js → invite-member-dialog-D5ZnkY4P.js} +1 -1
  122. package/dist/client/assets/{label-B4ntw-dL.js → label-ox3i10_c.js} +1 -1
  123. package/dist/client/assets/{layout-DwbXYN6v.js → layout-C91Z4yiM.js} +1 -1
  124. package/dist/client/assets/{login-DQx4eYA-.js → login-D7dR7ZLM.js} +1 -1
  125. package/dist/client/assets/{mcp-oauth-B8sNkssM.js → mcp-oauth-CxA5ui5Q.js} +1 -1
  126. package/dist/client/assets/{members-DCttPKWe.js → members-dokTe5-2.js} +1 -1
  127. package/dist/client/assets/{monaco-editor-By463NAt.js → monaco-editor-BTpC3Pqb.js} +1 -1
  128. package/dist/client/assets/{monitoring-stats-row-CaxumDAT.js → monitoring-stats-row-BK3_W4Xy.js} +1 -1
  129. package/dist/client/assets/{multi-select-B8lZKKri.js → multi-select-OD-FUuCs.js} +1 -1
  130. package/dist/client/assets/{oauth-callback-ai-provider-B2ckB--r.js → oauth-callback-ai-provider-ds9l07nm.js} +1 -1
  131. package/dist/client/assets/{oauth-callback-BciK2rUe.js → oauth-callback-ejlfAlfF.js} +1 -1
  132. package/dist/client/assets/{onboarding-iuSPwtT8.js → onboarding-Bg3Rphnw.js} +1 -1
  133. package/dist/client/assets/{org-layout-CQ4FgQvW.js → org-layout-OXpYx5eg.js} +1 -1
  134. package/dist/client/assets/{organization-choice-Bo0PLKWt.js → organization-choice-XMI8T7PM.js} +1 -1
  135. package/dist/client/assets/{orgs-B4IMdWUN.js → orgs-BZQ-zeh7.js} +1 -1
  136. package/dist/client/assets/{page-seo-form-DA6zCQDe.js → page-seo-form-CwDzM5k1.js} +1 -1
  137. package/dist/client/assets/{popover-BPk6M3Ab.js → popover-z2sj3hED.js} +1 -1
  138. package/dist/client/assets/{post-calendar-CqaZim4z.js → post-calendar-D3jmdqnB.js} +1 -1
  139. package/dist/client/assets/{post-editor-DQAQ4U2K.js → post-editor-DSfBJLf0.js} +1 -1
  140. package/dist/client/assets/{primitives-T_9HQYSb.js → primitives-CSnNMKbh.js} +1 -1
  141. package/dist/client/assets/{profile-j2blVqFv.js → profile-lFdRjcls.js} +1 -1
  142. package/dist/client/assets/{project-app-view-DlInBE62.js → project-app-view-DPop13ya.js} +1 -1
  143. package/dist/client/assets/{prompts-3PRL4o1C.js → prompts-Coi0QbTP.js} +1 -1
  144. package/dist/client/assets/record-editor-BkwUHmdp.js +1 -0
  145. package/dist/client/assets/{redirect-editor-4OOV0TKG.js → redirect-editor-Bqx-VhUl.js} +1 -1
  146. package/dist/client/assets/registry-CyXWSZna.js +2 -0
  147. package/dist/client/assets/{registry-layout-BInoVof-.js → registry-layout-BpawV4du.js} +1 -1
  148. package/dist/client/assets/{reports--7aMAL4v.js → reports-XFGouxAg.js} +1 -1
  149. package/dist/client/assets/{require-capability-Cf_X_a5q.js → require-capability-B43kv0qY.js} +1 -1
  150. package/dist/client/assets/{required-auth-layout-BKQXb_Td.js → required-auth-layout-CgJ84Ol6.js} +1 -1
  151. package/dist/client/assets/{reset-password-CnvN1UX2.js → reset-password-DN-VSI6p.js} +1 -1
  152. package/dist/client/assets/{review-settings-Bev_Y6AT.js → review-settings-DJAKp2DP.js} +1 -1
  153. package/dist/client/assets/{roles-75F9eoxQ.js → roles-DG5Vde1b.js} +1 -1
  154. package/dist/client/assets/{scroll-area-CNJqFTWE.js → scroll-area-Rn6eYrbW.js} +1 -1
  155. package/dist/client/assets/{search-input-Dq-2HdH2.js → search-input-qdnxSs8z.js} +1 -1
  156. package/dist/client/assets/{secrets-Dmr8-adp.js → secrets-cv8XPQgE.js} +1 -1
  157. package/dist/client/assets/{sections-editor-BY0_U_bq.js → sections-editor-B9R8O-CO.js} +1 -1
  158. package/dist/client/assets/{select-D_gAqeTo.js → select-BKaDAM0o.js} +1 -1
  159. package/dist/client/assets/{select-model-CRnOUepX.js → select-model-DEpvnb2X.js} +1 -1
  160. package/dist/client/assets/{self-tool-result-Ct7Ucpn3.js → self-tool-result-W2plE0y0.js} +1 -1
  161. package/dist/client/assets/{seo-editor-TV1vynDx.js → seo-editor-CY76Hvrc.js} +1 -1
  162. package/dist/client/assets/{settings-layout-CLGB6c68.js → settings-layout-DsaUMBUM.js} +1 -1
  163. package/dist/client/assets/{shell-controls-Ze8-9Sjk.js → shell-controls-I5I6m5pX.js} +1 -1
  164. package/dist/client/assets/{shell-layout-BIkMATYg.js → shell-layout-BpMspOQ-.js} +1 -1
  165. package/dist/client/assets/{spinner-Bknj58PL.js → spinner-DIykB3cL.js} +1 -1
  166. package/dist/client/assets/{sso-mDIE0CBS.js → sso-CkVDfit6.js} +1 -1
  167. package/dist/client/assets/{store-C35heaqa.js → store-oRVfvpU-.js} +1 -1
  168. package/dist/client/assets/store-registry-BWcInYl6.js +2 -0
  169. package/dist/client/assets/{super-agent-icon-SyRgoxaq.js → super-agent-icon-DMslRrrz.js} +1 -1
  170. package/dist/client/assets/{switch-DJ92Sqvc.js → switch-B81SJRHw.js} +1 -1
  171. package/dist/client/assets/{synced-repos-xoN_yR82.js → synced-repos-BvT2O03L.js} +1 -1
  172. package/dist/client/assets/{table-D2Dttbg8.js → table-BW6xeQWU.js} +1 -1
  173. package/dist/client/assets/{tabs-CxYGOHU2.js → tabs-BRej9j8s.js} +1 -1
  174. package/dist/client/assets/{task-board-DYjoMMlk.js → task-board-LUJhmh0o.js} +1 -1
  175. package/dist/client/assets/{tasks-2ZeWP9F2.js → tasks-DB7gDtEc.js} +1 -1
  176. package/dist/client/assets/{textarea-CYB7oeMg.js → textarea-DW6dhtLG.js} +1 -1
  177. package/dist/client/assets/{toggle-group-D4KPvVpH.js → toggle-group-CJjjnHDp.js} +1 -1
  178. package/dist/client/assets/{toolbar-C7lGIfSe.js → toolbar-CfSv3D-2.js} +1 -1
  179. package/dist/client/assets/{track-Cj1mjNAB.js → track-CfH5Jdn5.js} +1 -1
  180. package/dist/client/assets/{types-BQQga0n1.js → types-DqGWFR6Z.js} +1 -1
  181. package/dist/client/assets/{use-ai-providers-BUAaQZDB.js → use-ai-providers-CUA1pk7n.js} +1 -1
  182. package/dist/client/assets/{use-api-keys-O0s_2wuE.js → use-api-keys-ol-y2c4I.js} +1 -1
  183. package/dist/client/assets/{use-automations-DqhxiSOz.js → use-automations-Sif5qEPl.js} +1 -1
  184. package/dist/client/assets/{use-autosave-Cbftkfjm.js → use-autosave-CpsVm021.js} +1 -1
  185. package/dist/client/assets/{use-connection-Cq-TAk2H.js → use-connection-BQq8tTA5.js} +1 -1
  186. package/dist/client/assets/{use-copy-Cg1go2gj.js → use-copy-kFuBHgMx.js} +1 -1
  187. package/dist/client/assets/{use-create-virtual-mcp-BpR9gaAl.js → use-create-virtual-mcp-ipQR-zEz.js} +1 -1
  188. package/dist/client/assets/{use-debounced-autosave-D9bXFiUD.js → use-debounced-autosave-wiTp5Jhs.js} +1 -1
  189. package/dist/client/assets/{use-debounced-value-D1VMF_Gd.js → use-debounced-value-DYXRwmLu.js} +1 -1
  190. package/dist/client/assets/{use-decopilot-events-DcQV0dPs.js → use-decopilot-events-BCo1tZUl.js} +1 -1
  191. package/dist/client/assets/{use-delete-connection-BLcyP8yi.js → use-delete-connection-Cb0PZpx7.js} +1 -1
  192. package/dist/client/assets/{use-deployment-admin-GjRWRRUf.js → use-deployment-admin-BctbDjSX.js} +1 -1
  193. package/dist/client/assets/{use-destination-route-CqNrZyaz.js → use-destination-route-BtGEBss3.js} +1 -1
  194. package/dist/client/assets/{use-file-configs-CjNJ4edN.js → use-file-configs-C2_YPS5o.js} +1 -1
  195. package/dist/client/assets/{use-infinite-scroll-B1LlrgHQ.js → use-infinite-scroll-DX-Mbfy5.js} +1 -1
  196. package/dist/client/assets/{use-join-requests-Ew3DkICN.js → use-join-requests-SmeLvwBQ.js} +1 -1
  197. package/dist/client/assets/{use-mcp-auth-status-Cf4iHced.js → use-mcp-auth-status-ozpfpq4z.js} +1 -1
  198. package/dist/client/assets/{use-mcp-client-CRMxXjDt.js → use-mcp-client-Bu0mjJpz.js} +1 -1
  199. package/dist/client/assets/{use-mcp-tools-Qxsx4T5U.js → use-mcp-tools-C11FcNHe.js} +1 -1
  200. package/dist/client/assets/{use-members-B1_ygYTt.js → use-members-CSm21N5H.js} +1 -1
  201. package/dist/client/assets/{use-navigate-to-agent-C22bT_Eq.js → use-navigate-to-agent-CbERRPZK.js} +1 -1
  202. package/dist/client/assets/{use-org-auth-client-BVpl8XY7.js → use-org-auth-client-Crz_KEUL.js} +1 -1
  203. package/dist/client/assets/{use-org-repo-syncs-Csqn5niY.js → use-org-repo-syncs-hMq9CrpS.js} +1 -1
  204. package/dist/client/assets/{use-org-sso-lF5_jAIv.js → use-org-sso-DIPqEfKG.js} +1 -1
  205. package/dist/client/assets/{use-organization-roles-IAMtEvx4.js → use-organization-roles-Cf7k7q51.js} +1 -1
  206. package/dist/client/assets/{use-organization-settings-4GVbk9uN.js → use-organization-settings-UOsZ5POf.js} +1 -1
  207. package/dist/client/assets/{use-panel-navigate-BWmKwwdU.js → use-panel-navigate-CzprkJRR.js} +1 -1
  208. package/dist/client/assets/{use-registry-connections-LeUXjb90.js → use-registry-connections-BykIrgSf.js} +1 -1
  209. package/dist/client/assets/{use-secrets-CuPEQZnN.js → use-secrets-jq_7gBHT.js} +1 -1
  210. package/dist/client/assets/{use-section-preview-base-C-vCBMfP.js → use-section-preview-base-Cpv5ho58.js} +1 -1
  211. package/dist/client/assets/{use-status-sounds-JmvieN-E.js → use-status-sounds-K_Zv2VU0.js} +1 -1
  212. package/dist/client/assets/{use-tags-BUwi432c.js → use-tags-C4AG-Vwi.js} +1 -1
  213. package/dist/client/assets/{use-view-mode-GJdIZTFO.js → use-view-mode-CR_c9lOY.js} +1 -1
  214. package/dist/client/assets/{use-virtual-mcp-CtKin0-0.js → use-virtual-mcp-ekZODJZf.js} +1 -1
  215. package/dist/client/assets/useInfiniteQuery-CcQjpi1-.js +1 -0
  216. package/dist/client/assets/useSuspenseInfiniteQuery-Z4bYzTKH.js +1 -0
  217. package/dist/client/assets/{users-CwruFp1s.js → users-Ck0BSrD1.js} +1 -1
  218. package/dist/client/assets/{variant-calendar-CwfOIqAx.js → variant-calendar-BBwgSFgK.js} +1 -1
  219. package/dist/client/assets/{view-mode-toggle-BwI6VU0p.js → view-mode-toggle-DB9-eWNP.js} +1 -1
  220. package/dist/client/index.html +1 -1
  221. package/dist/server/cli.js +3 -3
  222. package/dist/server/server.js +3 -3
  223. package/package.json +1 -1
  224. package/dist/client/assets/record-editor-MuKvgZk5.js +0 -1
  225. package/dist/client/assets/registry-IUDmwrgW.js +0 -2
  226. package/dist/client/assets/store-registry-B5pB-dSI.js +0 -2
  227. package/dist/client/assets/useInfiniteQuery-C0Y3iEwS.js +0 -1
  228. package/dist/client/assets/useSuspenseInfiniteQuery-DfmDaTgg.js +0 -1
@@ -1444,7 +1444,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var qp1=L(()=>{cf()});f
1444
1444
  `.execute($);if(Number(W.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${J}/${K}, keeping in old table`);continue}}await By`
1445
1445
  DELETE FROM kysely_migration WHERE name = ${Q}
1446
1446
  `.execute($)}}async function Oa1($){await la8($),await ma8($);let Z=new Ua1({db:$,provider:{getMigrations:()=>Promise.resolve(vp0)}}),{error:Q,results:X}=await Z.migrateToLatest(),Y=0;if(X?.forEach((G)=>{if(G.status==="Success")Y++;else if(G.status==="Error")console.error(`Failed to execute migration "${G.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q;return Y}async function da8($){let{keepOpen:Z=!1,database:Q,skipBetterAuth:X=!1}=$??{},Y="skipped";if(!X&&!Q)Y=await fl0();let G=Q??H8(),J=async()=>{if(!Z&&!Q)await oB(G).catch((K)=>{console.warn("Warning: Error closing database:",K)})};try{let K=await Oa1(G.db);return await J(),{betterAuth:Y,kysely:K}}catch(K){throw await J(),K}}async function ia8(){let $=H8(),Z=new Ua1({db:$.db,provider:{getMigrations:()=>Promise.resolve(vp0)}}),{error:Q,results:X}=await Z.migrateDown();if(X?.forEach((Y)=>{if(Y.status==="Success")console.log(`\u2705 Migration "${Y.migrationName}" rolled back successfully`);else if(Y.status==="Error")console.error(`\u274C Failed to rollback migration "${Y.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}var Da1=L(()=>{Na1();bl0();QQ()});async function U70($){let Z={...process.env},Q=K80($,Z);console.log(Vw1(Q.settings.encryptionKey));let X=Q.settings.betterAuthSecret||(Q.settings.localMode?Xt1(Q.settings.dataDir):""),{ensureServices:Y}=await Promise.resolve().then(() => (jZ0(),EZ0)),{outputs:G,services:J}=await Y({home:Q.settings.dataDir,externalDatabaseUrl:Q.externalDatabaseUrl,externalNatsUrl:Q.externalNatsUrl});if(!Q.skipMigrations){let{migrateBetterAuth:W}=await Promise.resolve().then(() => (bl0(),Gt1));await W(G.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (QQ(),Pn1)),{migrateToLatest:F}=await Promise.resolve().then(() => (Da1(),La1)),N=H(G.databaseUrl);await F({keepOpen:!0,database:N,skipBetterAuth:!0})}let K={...Q.settings,betterAuthSecret:X,databaseUrl:G.databaseUrl,natsUrls:G.natsUrls,...G.s3?{s3Endpoint:G.s3.endpoint,s3Bucket:G.s3.bucket,s3AccessKeyId:G.s3.accessKeyId,s3SecretAccessKey:G.s3.secretAccessKey,s3ForcePathStyle:G.s3.forcePathStyle}:{}};return Mp1(K),{settings:K,services:J.map((W)=>({name:W.name==="PostgreSQL"?"Postgres":W.name,port:W.port})),managedServiceNames:J.filter((W)=>W.owner==="managed").map((W)=>W.name)}}var xp0=L(()=>{cf();Yt1();R$()});var za1={};Q0(za1,{updateService:()=>gE,subscribeCliState:()=>yp0,setTuiConsoleIntercepted:()=>B70,setServerUrl:()=>Lp,setMigrationsDone:()=>Op,setDevMode:()=>na8,resetCliStateForTests:()=>pa8,isTuiConsoleIntercepted:()=>O70,getCliState:()=>bp0,addLogEntry:()=>QO});function wa1(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function Ea1(){return{services:wa1(),migrationsStatus:"pending",serverUrl:null,logs:[]}}function pa8(){lX=Ea1()}function Bp(){for(let $ of fp0)$()}function bp0(){return lX}function yp0($){return fp0.add($),()=>fp0.delete($)}function gE($){lX={...lX,services:lX.services.map((Z)=>Z.name===$.name?$:Z)},Bp()}function Op(){lX={...lX,migrationsStatus:"done"},Bp()}function Lp($){lX={...lX,serverUrl:$},Bp()}function QO($){let Z=[...lX.logs,$];lX={...lX,logs:Z.length>500?Z.slice(-500):Z},Bp()}function na8(){lX={...lX,services:[...wa1(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},Bp()}function B70($){ja1=$}function O70(){return ja1}var lX,fp0,ja1=!1;var hE=L(()=>{lX=Ea1();fp0=new Set});import{createServer as Pa1}from"net";function ta8($){return new Promise((Z)=>{let Q=Pa1();Q.once("error",()=>Z(!1)),Q.listen($,"0.0.0.0",()=>{Q.close(()=>Z(!0))})})}async function Dp($){if(await ta8($))return $;let Z=await new Promise((Q,X)=>{let Y=Pa1();Y.once("error",X),Y.listen(0,"0.0.0.0",()=>{let G=Y.address(),J=typeof G==="object"&&G?G.port:0;Y.close(()=>Q(J))})});return console.warn(`Port ${$} is in use, using port ${Z} instead.`),Z}var gp0=()=>{};var up0={};Q0(up0,{startDevServer:()=>ra8,pipeToLogStore:()=>hp0});import{join as oa8}from"path";function hp0($){let Z=$.getReader(),Q=new TextDecoder,X="";function Y(){let G=X.split(`
1447
- `);X=G.pop()??"";for(let J of G){let K=Bun.stripANSI(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;QO({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{try{for(;;){let{done:G,value:J}=await Z.read();if(G)break;X+=Q.decode(J,{stream:!0}),Y()}}catch{}if(X.trim()){let G=Bun.stripANSI(X).replace(/^\[\d+\]\s*/,"").trim();if(G)QO({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function ra8($){let{baseUrl:Z,noTui:Q}=$,X=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=X?process.env.PORT:$.vitePort,G=Z||`http://localhost:${Y}`,J=X?await Dp(Number(Y)+1):await Dp(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await U70({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let D of W)gE({name:D.name,status:"ready",port:D.port});Op();let F=oa8(import.meta.dir,"..","..","..","..",".."),N=Q===!0,U=Bun.spawn(["bun","run","dev:servers"],{cwd:F,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:G,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}},stdio:["inherit",N?"inherit":"pipe",N?"inherit":"pipe"]});if(!N)hp0(U.stdout),hp0(U.stderr);Lp(G),gE({name:"Vite",status:"ready",port:Number(Y)}),gE({name:"API",status:"ready",port:Number(K.port)});let O=async(D)=>{if(U.kill(D),await U.exited,H.length>0){let{stopServices:w}=await Promise.resolve().then(() => (jZ0(),EZ0));await w(K.dataDir)}};return process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM")),{port:Number(Y),process:U}}var cp0=L(()=>{xp0();hE();gp0()});var L70;var lp0=L(()=>{L70={name:"decocms",version:"4.290.0",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^2.9.1","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^3.0.10","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as sa8,Text as Aa1}from"ink";import{jsx as ea8,jsxs as Ta1}from"react/jsx-runtime";function Ra1({version:$}){return Ta1(sa8,{flexDirection:"column",marginTop:1,children:[lZ0.map((Z,Q)=>ea8(Aa1,{color:mZ0[Q],children:Z},Q)),Ta1(Aa1,{dimColor:!0,children:[" v",$]})]})}var Ia1=L(()=>{Qp()});import{Box as uE,Text as XO}from"ink";import{Spinner as $s8}from"@inkjs/ui";import{jsx as $G,jsxs as Oy}from"react/jsx-runtime";function qa1({status:$}){if($==="pending")return $G($s8,{label:""});return $G(XO,{color:"green",children:"\u2713"})}function Zs8($){return`${$.name}: ${$.port||"...."}`}function Ma1({services:$,migrationsStatus:Z,home:Q,serverUrl:X}){return Oy(uE,{flexDirection:"column",paddingBottom:1,children:[$G(Ra1,{version:L70.version}),$G(uE,{marginBottom:1,children:$G(XO,{dimColor:!0,children:"\u2500".repeat(80)})}),$G(uE,{children:Oy(XO,{dimColor:!0,children:["Home: ",Q]})}),Oy(uE,{gap:2,children:[$.map((Y)=>Oy(uE,{gap:1,children:[$G(XO,{children:Zs8(Y)}),$G(qa1,{status:Y.status})]},Y.name)),Oy(uE,{gap:1,children:[$G(XO,{children:"Migrations"}),$G(qa1,{status:Z})]})]}),$G(uE,{children:X?Oy(XO,{children:["Open in browser: ",$G(XO,{color:"cyan",children:X})]}):$G(XO,{dimColor:!0,children:"Starting..."})})]})}var Va1=L(()=>{lp0();Ia1()});import{Box as Qs8,Text as wp}from"ink";import{jsx as mp0,jsxs as dp0}from"react/jsx-runtime";function Xs8($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function ka1({logs:$}){return mp0(Qs8,{flexDirection:"column",children:$.map((Z,Q)=>{if(Z.rawLine)return mp0(wp,{dimColor:!0,children:Z.rawLine},Q);let X=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return dp0(wp,{children:[dp0(wp,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),mp0(wp,{color:Xs8(Z.status),children:Z.status}),dp0(wp,{dimColor:!0,children:[" ",X.padStart(8)]})]},Q)})})}var Sa1=()=>{};var ip0={};Q0(ip0,{App:()=>Js8});import{Box as Ys8}from"ink";import{useSyncExternalStore as Gs8}from"react";import{jsx as Ca1,jsxs as Ks8}from"react/jsx-runtime";function Js8({home:$}){let Z=Gs8(yp0,bp0);return Ks8(Ys8,{flexDirection:"column",children:[Ca1(Ma1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),Ca1(ka1,{logs:Z.logs})]})}var pp0=L(()=>{Va1();Sa1();hE()});var u3="thread-gate",KN="decopilot-hosted-harness",WN="decopilot-hosted-harness-sandboxed",LJ="automations",YO="background-tools",cE="task-board-github-reads",lE="jira-push";var _a1="9";function va1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:_a1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var xa1=()=>{};import Ws8 from"pg";async function ba1($,Z){let{databaseUrl:Q,lockTimeoutMs:X=Hs8}=$,Y=$.log??((W)=>console.log(W)),G=new Ws8.Client({connectionString:Q});await G.connect();let J=Date.now(),K=!1;try{while(!K){if(K=(await G.query("SELECT pg_try_advisory_lock($1) AS locked",[fa1.toString()])).rows[0]?.locked===!0,K)break;if(Date.now()-J>=X)throw Error(`Timed out after ${X}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await W$(Fs8)}let W=Date.now()-J;if(W>1000)Y(`[dbos] waited ${W}ms for the migration lock; another process migrated first`);return await Z()}finally{if(K)try{await G.query("SELECT pg_advisory_unlock($1)",[fa1.toString()])}catch{}await G.end().catch(()=>{})}}var fa1=8314027461559302n,Hs8=600000,Fs8=500;var ya1=L(()=>{J4()});function Ns8(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function np0($,Z){for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X===void 0)continue;if(X===Z)return $[Q+1];if(X.startsWith(`${Z}=`))return X.slice(Z.length+1)}return}function ga1(){let $=Ns8();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:np0($,"--cpu-prof-dir")??process.cwd(),name:np0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(np0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function ha1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=xE();if(!Q)return;let X={};try{let{heapStats:Y}=await import("bun:jsc"),G=Y(),J=Object.entries(G.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);X={objectCount:G.objectCount,heapSize:G.heapSize,top:Object.fromEntries(J)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:Q.rss,heapUsed:Q.heapUsed,heapTotal:Q.heapTotal,external:Q.external,arrayBuffers:Q.arrayBuffers,...X}))};return Z().catch(()=>{}),D70=setInterval(()=>void Z().catch(()=>{}),$),D70.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),X=typeof Q==="string"?Q:JSON.stringify(Q),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,X),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(D70)clearInterval(D70)}}var D70;var ua1=()=>{};import*as Us8 from"bun:jsc";function ca1(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{Bs8()}catch(G){return console.error("[stall-watchdog] failed to start sampling profiler:",G),()=>{}}let Q,X=performance.now()+Z,Y=()=>{let G=performance.now(),J=G-X;X=G+Z;let K=[];try{K=Os8()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let F of K){let N=F.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??F.frames[0];if(!N)continue;let U=(N.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${N.name??"?"} @ ${U}:${N.line??"?"}`;W.set(B,(W.get(B)??0)+1)}let H=[...W.entries()].sort((F,N)=>N[1]-F[1]).slice(0,8).map(([F,N])=>({frame:F,count:N}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(J),samplesInWindow:K.length,top:H}))}Q=setTimeout(Y,Z),Q.unref?.()};return Q=setTimeout(Y,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}var Bs8,Os8;var la1=L(()=>{({startSamplingProfiler:Bs8,samplingProfilerStackTraces:Os8}=Us8)});function ma1(){ga1();let $=[ha1(),Bn1(),ca1()];return()=>{for(let Z of $)Z()}}var da1=L(()=>{ql0();ua1();la1()});var mE=v((ia1)=>{Object.defineProperty(ia1,"__esModule",{value:!0});ia1.RepublishHeaders=ia1.DirectMsgHeaders=ia1.JsHeaders=ia1.AdvisoryKind=void 0;ia1.isOrderedPushConsumerOptions=Ls8;ia1.isPullConsumer=Ds8;ia1.isPushConsumer=ws8;ia1.isBoundPushConsumerOptions=Es8;function Ls8($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function Ds8($){return $.isPullConsumer()}function ws8($){return $.isPushConsumer()}function Es8($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}ia1.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};ia1.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};ia1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};ia1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var ZG=v((na1)=>{Object.defineProperty(na1,"__esModule",{value:!0});na1.TD=na1.TE=na1.Empty=void 0;na1.encode=Ms8;na1.decode=Vs8;na1.Empty=new Uint8Array(0);na1.TE=new TextEncoder;na1.TD=new TextDecoder;function qs8(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}function Ms8(...$){let Z=[];for(let Q=0;Q<$.length;Q++)Z.push(na1.TE.encode($[Q]));if(Z.length===0)return na1.Empty;if(Z.length===1)return Z[0];return qs8(...Z)}function Vs8($){if(!$||$.length===0)return"";return na1.TD.decode($)}});var QG=v((ra1)=>{Object.defineProperty(ra1,"__esModule",{value:!0});ra1.errors=ra1.PermissionViolationError=ra1.NoRespondersError=ra1.TimeoutError=ra1.RequestError=ra1.ProtocolError=ra1.ConnectionError=ra1.DrainingConnectionError=ra1.ClosedConnectionError=ra1.AuthorizationError=ra1.UserAuthenticationExpiredError=ra1.InvalidOperationError=ra1.InvalidArgumentError=ra1.InvalidSubjectError=void 0;class op0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}ra1.InvalidSubjectError=op0;class w70 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,Q){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((X)=>`'${X}'`),$=$.join(",");else $=`'${$}'`;return new w70(`${$} ${Z}`,Q)}}ra1.InvalidArgumentError=w70;class rp0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}ra1.InvalidOperationError=rp0;class E70 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new E70($);return null}}ra1.UserAuthenticationExpiredError=E70;class j70 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],Q=$.toLowerCase();for(let X=0;X<Z.length;X++)if(Q.indexOf(Z[X])!==-1)return new j70($);return null}}ra1.AuthorizationError=j70;class ap0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}ra1.ClosedConnectionError=ap0;class sp0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}ra1.DrainingConnectionError=sp0;class ep0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}ra1.ConnectionError=ep0;class $n0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}ra1.ProtocolError=$n0;class Zn0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof z70}}ra1.RequestError=Zn0;class Qn0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}ra1.TimeoutError=Qn0;class z70 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}ra1.NoRespondersError=z70;class P70 extends Error{operation;subject;queue;constructor($,Z,Q,X,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=Q,this.queue=X}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let Q="publish",X="",Y=void 0,G=$.match(/(Publish|Subscription) to "(\S+)"/);if(G){if(Q=G[1].toLowerCase(),X=G[2],Q==="subscription"){let J=$.match(/using queue "(\S+)"/);if(J)Y=J[1]}}return new P70($,Q,X,Y)}}ra1.PermissionViolationError=P70;ra1.errors={AuthorizationError:j70,ClosedConnectionError:ap0,ConnectionError:ep0,DrainingConnectionError:sp0,InvalidArgumentError:w70,InvalidOperationError:rp0,InvalidSubjectError:op0,NoRespondersError:z70,PermissionViolationError:P70,ProtocolError:$n0,RequestError:Zn0,TimeoutError:Qn0,UserAuthenticationExpiredError:E70}});var c3=v((Zs1)=>{Object.defineProperty(Zs1,"__esModule",{value:!0});Zs1.SimpleMutex=Zs1.Perf=void 0;Zs1.extend=is8;Zs1.render=ps8;Zs1.timeout=ns8;Zs1.delay=ts8;Zs1.deadline=os8;Zs1.deferred=Yn0;Zs1.debugDeferred=rs8;Zs1.shuffle=as8;Zs1.collect=ss8;Zs1.jitter=$s1;Zs1.backoff=es8;Zs1.nanos=$e8;Zs1.millis=Ze8;Zs1.randomToken=Ye8;var ds8=ZG(),Xn0=QG();function is8($,...Z){for(let Q=0;Q<Z.length;Q++){let X=Z[Q];Object.keys(X).forEach(function(Y){$[Y]=X[Y]})}return $}function ps8($){return ds8.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function ns8($,Z=!0){let Q=Z?new Xn0.TimeoutError:null,X,Y,G=new Promise((J,K)=>{X={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(Q===null)K(new Xn0.TimeoutError);else K(Q)},$)});return Object.assign(G,X)}function ts8($=0){let Z,Q=new Promise((X)=>{let Y=setTimeout(()=>{X()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),X()}}});return Object.assign(Q,Z)}async function os8($,Z=1000){let Q=Yn0(),X=setTimeout(()=>{Q.reject(new Xn0.TimeoutError)},Z);try{return await Promise.race([$,Q])}finally{clearTimeout(X)}}function Yn0(){let $={},Z=new Promise((Q,X)=>{$={resolve:Q,reject:X}});return Object.assign(Z,$)}function rs8(){let $={},Z=new Promise((Q,X)=>{$={resolve:(Y)=>{console.trace("resolve",Y),Q(Y)},reject:(Y)=>{console.trace("reject"),X(Y)}}});return Object.assign(Z,$)}function as8($){for(let Z=$.length-1;Z>0;Z--){let Q=Math.floor(Math.random()*(Z+1));[$[Z],$[Q]]=[$[Q],$[Z]]}return $}async function ss8($){let Z=[];for await(let Q of $)Z.push(Q);return Z}class sa1{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,Q){let X=this.timers.get(Z);if(X===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(Q);if(Y===void 0)throw Error(`${Q} is not defined`);this.measures.set($,Y-X)}getEntries(){let $=[];return this.measures.forEach((Z,Q)=>{$.push({name:Q,duration:Z})}),$}}Zs1.Perf=sa1;class ea1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=Yn0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}Zs1.SimpleMutex=ea1;function $s1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function es8($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(Q){return $s1(Q>Z?$[Z]:$[Q])}}}function $e8($){return $*1e6}function Ze8($){return Math.floor($/1e6)}var Qe8="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",HN=new Uint8Array(62);for(let $=0;$<62;$++)HN[$]=Qe8.charCodeAt($);var Xe8=218340105584896;function Ye8(){let $=Math.floor(Math.random()*Xe8),Z=$%62,Q=HN[Z];$=($-Z)/62,Z=$%62;let X=HN[Z];$=($-Z)/62,Z=$%62;let Y=HN[Z];$=($-Z)/62,Z=$%62;let G=HN[Z];$=($-Z)/62,Z=$%62;let J=HN[Z];$=($-Z)/62,Z=$%62;let K=HN[Z];$=($-Z)/62,Z=$%62;let W=HN[Z];$=($-Z)/62;let H=HN[$];return String.fromCharCode(Q,X,Y,G,J,K,W,H)}});var Hs1=v((Ks1)=>{Object.defineProperty(Ks1,"__esModule",{value:!0});Ks1.nuid=Ks1.NuidImpl=void 0;var ze8="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",GO=62,T70=12,Gs1=10,Xs1=33,Pe8=333,Ys1=T70+Gs1,Jn0=new Uint8Array(GO);for(let $=0;$<GO;$++)Jn0[$]=ze8.charCodeAt($);var A70=4294967296,Js1=BigInt(GO)**BigInt(Gs1),Ep=Number(Js1/(1n<<32n)),Gn0=Number(Js1%(1n<<32n));function Ae8($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function Te8($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else Ae8($)}class Kn0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Ys1),this.cbuf=new Uint8Array(T70),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(Ep+1)),this.seqLo=Math.floor(Math.random()*A70);while($++<8&&this.seqHi===Ep&&this.seqLo>=Gn0);if(this.seqHi===Ep&&this.seqLo>=Gn0)this.seqLo=0;this.inc=Math.random()*(Pe8-Xs1)+Xs1|0}setPre(){Te8(this.cbuf);for(let $=0;$<T70;$++)this.buf[$]=Jn0[this.cbuf[$]%GO]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let Q=Ys1-1;Q>=T70;Q--){let X=Math.floor($/GO),G=($-X*GO)*A70+Z,J=Math.floor(G/GO),K=G-J*GO;this.buf[Q]=Jn0[K],$=X,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=A70)this.seqLo-=A70,this.seqHi+=1;if(this.seqHi>Ep||this.seqHi===Ep&&this.seqLo>=Gn0)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}Ks1.NuidImpl=Kn0;Ks1.nuid=new Kn0});var Bs1=v((Ns1)=>{Object.defineProperty(Ns1,"__esModule",{value:!0});Ns1.nuid=Ns1.Nuid=void 0;var Fs1=Hs1();Ns1.Nuid=Fs1.NuidImpl;Ns1.nuid=Fs1.nuid});var I70=v((R70)=>{Object.defineProperty(R70,"__esModule",{value:!0});R70.nuid=R70.Nuid=void 0;var Os1=Bs1();Object.defineProperty(R70,"Nuid",{enumerable:!0,get:function(){return Os1.Nuid}});Object.defineProperty(R70,"nuid",{enumerable:!0,get:function(){return Os1.nuid}})});var JO=v((Ls1)=>{Object.defineProperty(Ls1,"__esModule",{value:!0});Ls1.DEFAULT_HOST=Ls1.DEFAULT_PORT=Ls1.Match=void 0;Ls1.syncIterator=ke8;Ls1.createInbox=Se8;var Me8=I70(),Ve8=QG();Ls1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function ke8($){let Z=$[Symbol.asyncIterator]();return{async next(){let Q=await Z.next();if(Q.done)return Promise.resolve(null);return Promise.resolve(Q.value)}}}function Se8($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw Ve8.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${Me8.nuid.next()}`}Ls1.DEFAULT_PORT=4222;Ls1.DEFAULT_HOST="127.0.0.1"});var jp=v((js1)=>{Object.defineProperty(js1,"__esModule",{value:!0});js1.DataBuffer=void 0;var ws1=ZG();class Es1{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}static fromAscii($){if(!$)$="";return ws1.TE.encode($)}static toAscii($){return ws1.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let Q=0;Q<this.buffers.length;Q++)$.set(this.buffers[Q],Z),Z+=this.buffers[Q].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let Q=this.byteLength;if($===void 0||$>Q)$=Q;let X=Z.subarray(0,$);if(Q>$)this.buffers.push(Z.subarray($));return this.byteLength=Q-$,X}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let Q=0;Q<Z.length;Q++)if(Z[Q]&&Z[Q].length)this.buffers.push(Z[Q]),this.byteLength+=Z[Q].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}js1.DataBuffer=Es1});var dE=v((As1)=>{Object.defineProperty(As1,"__esModule",{value:!0});As1.LF=As1.CR=As1.CRLF=As1.CR_LF_LEN=As1.CR_LF=void 0;As1.setTransportFactory=ge8;As1.defaultPort=he8;As1.getUrlParseFn=ue8;As1.newTransport=ce8;As1.getResolveFn=le8;As1.protoLen=Ps1;As1.extractProtocolMessage=me8;var fe8=ZG(),be8=JO(),ye8=jp(),XG;function ge8($){XG=$}function he8(){return XG!==void 0&&XG.defaultPort!==void 0?XG.defaultPort:be8.DEFAULT_PORT}function ue8(){return XG!==void 0&&XG.urlParseFn?XG.urlParseFn:void 0}function ce8(){if(!XG||typeof XG.factory!=="function")throw Error("transport fn is not set");return XG.factory()}function le8(){return XG!==void 0&&XG.dnsResolveFn?XG.dnsResolveFn:void 0}As1.CR_LF=`\r
1447
+ `);X=G.pop()??"";for(let J of G){let K=Bun.stripANSI(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;QO({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{try{for(;;){let{done:G,value:J}=await Z.read();if(G)break;X+=Q.decode(J,{stream:!0}),Y()}}catch{}if(X.trim()){let G=Bun.stripANSI(X).replace(/^\[\d+\]\s*/,"").trim();if(G)QO({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function ra8($){let{baseUrl:Z,noTui:Q}=$,X=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=X?process.env.PORT:$.vitePort,G=Z||`http://localhost:${Y}`,J=X?await Dp(Number(Y)+1):await Dp(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await U70({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let D of W)gE({name:D.name,status:"ready",port:D.port});Op();let F=oa8(import.meta.dir,"..","..","..","..",".."),N=Q===!0,U=Bun.spawn(["bun","run","dev:servers"],{cwd:F,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:G,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}},stdio:["inherit",N?"inherit":"pipe",N?"inherit":"pipe"]});if(!N)hp0(U.stdout),hp0(U.stderr);Lp(G),gE({name:"Vite",status:"ready",port:Number(Y)}),gE({name:"API",status:"ready",port:Number(K.port)});let O=async(D)=>{if(U.kill(D),await U.exited,H.length>0){let{stopServices:w}=await Promise.resolve().then(() => (jZ0(),EZ0));await w(K.dataDir)}};return process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM")),{port:Number(Y),process:U}}var cp0=L(()=>{xp0();hE();gp0()});var L70;var lp0=L(()=>{L70={name:"decocms",version:"4.290.1",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^2.9.1","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^3.0.10","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as sa8,Text as Aa1}from"ink";import{jsx as ea8,jsxs as Ta1}from"react/jsx-runtime";function Ra1({version:$}){return Ta1(sa8,{flexDirection:"column",marginTop:1,children:[lZ0.map((Z,Q)=>ea8(Aa1,{color:mZ0[Q],children:Z},Q)),Ta1(Aa1,{dimColor:!0,children:[" v",$]})]})}var Ia1=L(()=>{Qp()});import{Box as uE,Text as XO}from"ink";import{Spinner as $s8}from"@inkjs/ui";import{jsx as $G,jsxs as Oy}from"react/jsx-runtime";function qa1({status:$}){if($==="pending")return $G($s8,{label:""});return $G(XO,{color:"green",children:"\u2713"})}function Zs8($){return`${$.name}: ${$.port||"...."}`}function Ma1({services:$,migrationsStatus:Z,home:Q,serverUrl:X}){return Oy(uE,{flexDirection:"column",paddingBottom:1,children:[$G(Ra1,{version:L70.version}),$G(uE,{marginBottom:1,children:$G(XO,{dimColor:!0,children:"\u2500".repeat(80)})}),$G(uE,{children:Oy(XO,{dimColor:!0,children:["Home: ",Q]})}),Oy(uE,{gap:2,children:[$.map((Y)=>Oy(uE,{gap:1,children:[$G(XO,{children:Zs8(Y)}),$G(qa1,{status:Y.status})]},Y.name)),Oy(uE,{gap:1,children:[$G(XO,{children:"Migrations"}),$G(qa1,{status:Z})]})]}),$G(uE,{children:X?Oy(XO,{children:["Open in browser: ",$G(XO,{color:"cyan",children:X})]}):$G(XO,{dimColor:!0,children:"Starting..."})})]})}var Va1=L(()=>{lp0();Ia1()});import{Box as Qs8,Text as wp}from"ink";import{jsx as mp0,jsxs as dp0}from"react/jsx-runtime";function Xs8($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function ka1({logs:$}){return mp0(Qs8,{flexDirection:"column",children:$.map((Z,Q)=>{if(Z.rawLine)return mp0(wp,{dimColor:!0,children:Z.rawLine},Q);let X=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return dp0(wp,{children:[dp0(wp,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),mp0(wp,{color:Xs8(Z.status),children:Z.status}),dp0(wp,{dimColor:!0,children:[" ",X.padStart(8)]})]},Q)})})}var Sa1=()=>{};var ip0={};Q0(ip0,{App:()=>Js8});import{Box as Ys8}from"ink";import{useSyncExternalStore as Gs8}from"react";import{jsx as Ca1,jsxs as Ks8}from"react/jsx-runtime";function Js8({home:$}){let Z=Gs8(yp0,bp0);return Ks8(Ys8,{flexDirection:"column",children:[Ca1(Ma1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),Ca1(ka1,{logs:Z.logs})]})}var pp0=L(()=>{Va1();Sa1();hE()});var u3="thread-gate",KN="decopilot-hosted-harness",WN="decopilot-hosted-harness-sandboxed",LJ="automations",YO="background-tools",cE="task-board-github-reads",lE="jira-push";var _a1="9";function va1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:_a1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var xa1=()=>{};import Ws8 from"pg";async function ba1($,Z){let{databaseUrl:Q,lockTimeoutMs:X=Hs8}=$,Y=$.log??((W)=>console.log(W)),G=new Ws8.Client({connectionString:Q});await G.connect();let J=Date.now(),K=!1;try{while(!K){if(K=(await G.query("SELECT pg_try_advisory_lock($1) AS locked",[fa1.toString()])).rows[0]?.locked===!0,K)break;if(Date.now()-J>=X)throw Error(`Timed out after ${X}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await W$(Fs8)}let W=Date.now()-J;if(W>1000)Y(`[dbos] waited ${W}ms for the migration lock; another process migrated first`);return await Z()}finally{if(K)try{await G.query("SELECT pg_advisory_unlock($1)",[fa1.toString()])}catch{}await G.end().catch(()=>{})}}var fa1=8314027461559302n,Hs8=600000,Fs8=500;var ya1=L(()=>{J4()});function Ns8(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function np0($,Z){for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X===void 0)continue;if(X===Z)return $[Q+1];if(X.startsWith(`${Z}=`))return X.slice(Z.length+1)}return}function ga1(){let $=Ns8();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:np0($,"--cpu-prof-dir")??process.cwd(),name:np0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(np0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function ha1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=xE();if(!Q)return;let X={};try{let{heapStats:Y}=await import("bun:jsc"),G=Y(),J=Object.entries(G.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);X={objectCount:G.objectCount,heapSize:G.heapSize,top:Object.fromEntries(J)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:Q.rss,heapUsed:Q.heapUsed,heapTotal:Q.heapTotal,external:Q.external,arrayBuffers:Q.arrayBuffers,...X}))};return Z().catch(()=>{}),D70=setInterval(()=>void Z().catch(()=>{}),$),D70.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),X=typeof Q==="string"?Q:JSON.stringify(Q),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,X),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(D70)clearInterval(D70)}}var D70;var ua1=()=>{};import*as Us8 from"bun:jsc";function ca1(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{Bs8()}catch(G){return console.error("[stall-watchdog] failed to start sampling profiler:",G),()=>{}}let Q,X=performance.now()+Z,Y=()=>{let G=performance.now(),J=G-X;X=G+Z;let K=[];try{K=Os8()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let F of K){let N=F.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??F.frames[0];if(!N)continue;let U=(N.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${N.name??"?"} @ ${U}:${N.line??"?"}`;W.set(B,(W.get(B)??0)+1)}let H=[...W.entries()].sort((F,N)=>N[1]-F[1]).slice(0,8).map(([F,N])=>({frame:F,count:N}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(J),samplesInWindow:K.length,top:H}))}Q=setTimeout(Y,Z),Q.unref?.()};return Q=setTimeout(Y,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}var Bs8,Os8;var la1=L(()=>{({startSamplingProfiler:Bs8,samplingProfilerStackTraces:Os8}=Us8)});function ma1(){ga1();let $=[ha1(),Bn1(),ca1()];return()=>{for(let Z of $)Z()}}var da1=L(()=>{ql0();ua1();la1()});var mE=v((ia1)=>{Object.defineProperty(ia1,"__esModule",{value:!0});ia1.RepublishHeaders=ia1.DirectMsgHeaders=ia1.JsHeaders=ia1.AdvisoryKind=void 0;ia1.isOrderedPushConsumerOptions=Ls8;ia1.isPullConsumer=Ds8;ia1.isPushConsumer=ws8;ia1.isBoundPushConsumerOptions=Es8;function Ls8($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function Ds8($){return $.isPullConsumer()}function ws8($){return $.isPushConsumer()}function Es8($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}ia1.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};ia1.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};ia1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};ia1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var ZG=v((na1)=>{Object.defineProperty(na1,"__esModule",{value:!0});na1.TD=na1.TE=na1.Empty=void 0;na1.encode=Ms8;na1.decode=Vs8;na1.Empty=new Uint8Array(0);na1.TE=new TextEncoder;na1.TD=new TextDecoder;function qs8(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}function Ms8(...$){let Z=[];for(let Q=0;Q<$.length;Q++)Z.push(na1.TE.encode($[Q]));if(Z.length===0)return na1.Empty;if(Z.length===1)return Z[0];return qs8(...Z)}function Vs8($){if(!$||$.length===0)return"";return na1.TD.decode($)}});var QG=v((ra1)=>{Object.defineProperty(ra1,"__esModule",{value:!0});ra1.errors=ra1.PermissionViolationError=ra1.NoRespondersError=ra1.TimeoutError=ra1.RequestError=ra1.ProtocolError=ra1.ConnectionError=ra1.DrainingConnectionError=ra1.ClosedConnectionError=ra1.AuthorizationError=ra1.UserAuthenticationExpiredError=ra1.InvalidOperationError=ra1.InvalidArgumentError=ra1.InvalidSubjectError=void 0;class op0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}ra1.InvalidSubjectError=op0;class w70 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,Q){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((X)=>`'${X}'`),$=$.join(",");else $=`'${$}'`;return new w70(`${$} ${Z}`,Q)}}ra1.InvalidArgumentError=w70;class rp0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}ra1.InvalidOperationError=rp0;class E70 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new E70($);return null}}ra1.UserAuthenticationExpiredError=E70;class j70 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],Q=$.toLowerCase();for(let X=0;X<Z.length;X++)if(Q.indexOf(Z[X])!==-1)return new j70($);return null}}ra1.AuthorizationError=j70;class ap0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}ra1.ClosedConnectionError=ap0;class sp0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}ra1.DrainingConnectionError=sp0;class ep0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}ra1.ConnectionError=ep0;class $n0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}ra1.ProtocolError=$n0;class Zn0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof z70}}ra1.RequestError=Zn0;class Qn0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}ra1.TimeoutError=Qn0;class z70 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}ra1.NoRespondersError=z70;class P70 extends Error{operation;subject;queue;constructor($,Z,Q,X,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=Q,this.queue=X}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let Q="publish",X="",Y=void 0,G=$.match(/(Publish|Subscription) to "(\S+)"/);if(G){if(Q=G[1].toLowerCase(),X=G[2],Q==="subscription"){let J=$.match(/using queue "(\S+)"/);if(J)Y=J[1]}}return new P70($,Q,X,Y)}}ra1.PermissionViolationError=P70;ra1.errors={AuthorizationError:j70,ClosedConnectionError:ap0,ConnectionError:ep0,DrainingConnectionError:sp0,InvalidArgumentError:w70,InvalidOperationError:rp0,InvalidSubjectError:op0,NoRespondersError:z70,PermissionViolationError:P70,ProtocolError:$n0,RequestError:Zn0,TimeoutError:Qn0,UserAuthenticationExpiredError:E70}});var c3=v((Zs1)=>{Object.defineProperty(Zs1,"__esModule",{value:!0});Zs1.SimpleMutex=Zs1.Perf=void 0;Zs1.extend=is8;Zs1.render=ps8;Zs1.timeout=ns8;Zs1.delay=ts8;Zs1.deadline=os8;Zs1.deferred=Yn0;Zs1.debugDeferred=rs8;Zs1.shuffle=as8;Zs1.collect=ss8;Zs1.jitter=$s1;Zs1.backoff=es8;Zs1.nanos=$e8;Zs1.millis=Ze8;Zs1.randomToken=Ye8;var ds8=ZG(),Xn0=QG();function is8($,...Z){for(let Q=0;Q<Z.length;Q++){let X=Z[Q];Object.keys(X).forEach(function(Y){$[Y]=X[Y]})}return $}function ps8($){return ds8.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function ns8($,Z=!0){let Q=Z?new Xn0.TimeoutError:null,X,Y,G=new Promise((J,K)=>{X={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(Q===null)K(new Xn0.TimeoutError);else K(Q)},$)});return Object.assign(G,X)}function ts8($=0){let Z,Q=new Promise((X)=>{let Y=setTimeout(()=>{X()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),X()}}});return Object.assign(Q,Z)}async function os8($,Z=1000){let Q=Yn0(),X=setTimeout(()=>{Q.reject(new Xn0.TimeoutError)},Z);try{return await Promise.race([$,Q])}finally{clearTimeout(X)}}function Yn0(){let $={},Z=new Promise((Q,X)=>{$={resolve:Q,reject:X}});return Object.assign(Z,$)}function rs8(){let $={},Z=new Promise((Q,X)=>{$={resolve:(Y)=>{console.trace("resolve",Y),Q(Y)},reject:(Y)=>{console.trace("reject"),X(Y)}}});return Object.assign(Z,$)}function as8($){for(let Z=$.length-1;Z>0;Z--){let Q=Math.floor(Math.random()*(Z+1));[$[Z],$[Q]]=[$[Q],$[Z]]}return $}async function ss8($){let Z=[];for await(let Q of $)Z.push(Q);return Z}class sa1{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,Q){let X=this.timers.get(Z);if(X===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(Q);if(Y===void 0)throw Error(`${Q} is not defined`);this.measures.set($,Y-X)}getEntries(){let $=[];return this.measures.forEach((Z,Q)=>{$.push({name:Q,duration:Z})}),$}}Zs1.Perf=sa1;class ea1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=Yn0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}Zs1.SimpleMutex=ea1;function $s1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function es8($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(Q){return $s1(Q>Z?$[Z]:$[Q])}}}function $e8($){return $*1e6}function Ze8($){return Math.floor($/1e6)}var Qe8="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",HN=new Uint8Array(62);for(let $=0;$<62;$++)HN[$]=Qe8.charCodeAt($);var Xe8=218340105584896;function Ye8(){let $=Math.floor(Math.random()*Xe8),Z=$%62,Q=HN[Z];$=($-Z)/62,Z=$%62;let X=HN[Z];$=($-Z)/62,Z=$%62;let Y=HN[Z];$=($-Z)/62,Z=$%62;let G=HN[Z];$=($-Z)/62,Z=$%62;let J=HN[Z];$=($-Z)/62,Z=$%62;let K=HN[Z];$=($-Z)/62,Z=$%62;let W=HN[Z];$=($-Z)/62;let H=HN[$];return String.fromCharCode(Q,X,Y,G,J,K,W,H)}});var Hs1=v((Ks1)=>{Object.defineProperty(Ks1,"__esModule",{value:!0});Ks1.nuid=Ks1.NuidImpl=void 0;var ze8="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",GO=62,T70=12,Gs1=10,Xs1=33,Pe8=333,Ys1=T70+Gs1,Jn0=new Uint8Array(GO);for(let $=0;$<GO;$++)Jn0[$]=ze8.charCodeAt($);var A70=4294967296,Js1=BigInt(GO)**BigInt(Gs1),Ep=Number(Js1/(1n<<32n)),Gn0=Number(Js1%(1n<<32n));function Ae8($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function Te8($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else Ae8($)}class Kn0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Ys1),this.cbuf=new Uint8Array(T70),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(Ep+1)),this.seqLo=Math.floor(Math.random()*A70);while($++<8&&this.seqHi===Ep&&this.seqLo>=Gn0);if(this.seqHi===Ep&&this.seqLo>=Gn0)this.seqLo=0;this.inc=Math.random()*(Pe8-Xs1)+Xs1|0}setPre(){Te8(this.cbuf);for(let $=0;$<T70;$++)this.buf[$]=Jn0[this.cbuf[$]%GO]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let Q=Ys1-1;Q>=T70;Q--){let X=Math.floor($/GO),G=($-X*GO)*A70+Z,J=Math.floor(G/GO),K=G-J*GO;this.buf[Q]=Jn0[K],$=X,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=A70)this.seqLo-=A70,this.seqHi+=1;if(this.seqHi>Ep||this.seqHi===Ep&&this.seqLo>=Gn0)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}Ks1.NuidImpl=Kn0;Ks1.nuid=new Kn0});var Bs1=v((Ns1)=>{Object.defineProperty(Ns1,"__esModule",{value:!0});Ns1.nuid=Ns1.Nuid=void 0;var Fs1=Hs1();Ns1.Nuid=Fs1.NuidImpl;Ns1.nuid=Fs1.nuid});var I70=v((R70)=>{Object.defineProperty(R70,"__esModule",{value:!0});R70.nuid=R70.Nuid=void 0;var Os1=Bs1();Object.defineProperty(R70,"Nuid",{enumerable:!0,get:function(){return Os1.Nuid}});Object.defineProperty(R70,"nuid",{enumerable:!0,get:function(){return Os1.nuid}})});var JO=v((Ls1)=>{Object.defineProperty(Ls1,"__esModule",{value:!0});Ls1.DEFAULT_HOST=Ls1.DEFAULT_PORT=Ls1.Match=void 0;Ls1.syncIterator=ke8;Ls1.createInbox=Se8;var Me8=I70(),Ve8=QG();Ls1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function ke8($){let Z=$[Symbol.asyncIterator]();return{async next(){let Q=await Z.next();if(Q.done)return Promise.resolve(null);return Promise.resolve(Q.value)}}}function Se8($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw Ve8.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${Me8.nuid.next()}`}Ls1.DEFAULT_PORT=4222;Ls1.DEFAULT_HOST="127.0.0.1"});var jp=v((js1)=>{Object.defineProperty(js1,"__esModule",{value:!0});js1.DataBuffer=void 0;var ws1=ZG();class Es1{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}static fromAscii($){if(!$)$="";return ws1.TE.encode($)}static toAscii($){return ws1.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let Q=0;Q<this.buffers.length;Q++)$.set(this.buffers[Q],Z),Z+=this.buffers[Q].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let Q=this.byteLength;if($===void 0||$>Q)$=Q;let X=Z.subarray(0,$);if(Q>$)this.buffers.push(Z.subarray($));return this.byteLength=Q-$,X}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let Q=0;Q<Z.length;Q++)if(Z[Q]&&Z[Q].length)this.buffers.push(Z[Q]),this.byteLength+=Z[Q].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}js1.DataBuffer=Es1});var dE=v((As1)=>{Object.defineProperty(As1,"__esModule",{value:!0});As1.LF=As1.CR=As1.CRLF=As1.CR_LF_LEN=As1.CR_LF=void 0;As1.setTransportFactory=ge8;As1.defaultPort=he8;As1.getUrlParseFn=ue8;As1.newTransport=ce8;As1.getResolveFn=le8;As1.protoLen=Ps1;As1.extractProtocolMessage=me8;var fe8=ZG(),be8=JO(),ye8=jp(),XG;function ge8($){XG=$}function he8(){return XG!==void 0&&XG.defaultPort!==void 0?XG.defaultPort:be8.DEFAULT_PORT}function ue8(){return XG!==void 0&&XG.urlParseFn?XG.urlParseFn:void 0}function ce8(){if(!XG||typeof XG.factory!=="function")throw Error("transport fn is not set");return XG.factory()}function le8(){return XG!==void 0&&XG.dnsResolveFn?XG.dnsResolveFn:void 0}As1.CR_LF=`\r
1448
1448
  `;As1.CR_LF_LEN=As1.CR_LF.length;As1.CRLF=ye8.DataBuffer.fromAscii(As1.CR_LF);As1.CR=new Uint8Array(As1.CRLF)[0];As1.LF=new Uint8Array(As1.CRLF)[1];function Ps1($){for(let Z=0;Z<$.length;Z++){let Q=Z+1;if($.byteLength>Q&&$[Z]===As1.CR&&$[Q]===As1.LF)return Q+1}return 0}function me8($){let Z=Ps1($);if(Z>0){let X=new Uint8Array($).slice(0,Z);return fe8.TD.decode(X)}return""}});var Un0=v((Ss1)=>{Object.defineProperty(Ss1,"__esModule",{value:!0});Ss1.ipV4=Ms1;Ss1.isIP=$04;Ss1.parseIP=Vs1;var zp=4,iE=16,q70=48,qs1=57,Rs1=65,se8=70,Is1=97,ee8=102,Nn0=16777215;function Ms1($,Z,Q,X){let Y=new Uint8Array(iE);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((J,K)=>{Y[K]=J}),Y[12]=$,Y[13]=Z,Y[14]=Q,Y[15]=X,Y}function $04($){return Vs1($)!==void 0}function Vs1($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return ks1($);case":":return Z04($)}return}function ks1($){let Z=new Uint8Array(zp);for(let Q=0;Q<zp;Q++){if($.length===0)return;if(Q>0){if($[0]!==".")return;$=$.substring(1)}let{n:X,c:Y,ok:G}=Q04($);if(!G||X>255)return;$=$.substring(Y),Z[Q]=X}return Ms1(Z[0],Z[1],Z[2],Z[3])}function Z04($){let Z=new Uint8Array(iE),Q=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(Q=0,$=$.substring(2),$.length===0)return Z}let X=0;while(X<iE){let{n:Y,c:G,ok:J}=X04($);if(!J||Y>65535)return;if(G<$.length&&$[G]==="."){if(Q<0&&X!=iE-zp)return;if(X+zp>iE)return;let K=ks1($);if(K===void 0)return;Z[X]=K[12],Z[X+1]=K[13],Z[X+2]=K[14],Z[X+3]=K[15],$="",X+=zp;break}if(Z[X]=Y>>8,Z[X+1]=Y,X+=2,$=$.substring(G),$.length===0)break;if($[0]!==":"||$.length==1)return;if($=$.substring(1),$[0]===":"){if(Q>=0)return;if(Q=X,$=$.substring(1),$.length===0)break}}if($.length!==0)return;if(X<iE){if(Q<0)return;let Y=iE-X;for(let G=X-1;G>=Q;G--)Z[G+Y]=Z[G];for(let G=Q+Y-1;G>=Q;G--)Z[G]=0}else if(Q>=0)return;return Z}function Q04($){let Z=0,Q=0;for(Z=0;Z<$.length&&q70<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=qs1;Z++)if(Q=Q*10+($.charCodeAt(Z)-q70),Q>=Nn0)return{n:Nn0,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:Q,c:Z,ok:!0}}function X04($){let Z=0,Q=0;for(Q=0;Q<$.length;Q++){if(q70<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=qs1)Z*=16,Z+=$.charCodeAt(Q)-q70;else if(Is1<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=ee8)Z*=16,Z+=$.charCodeAt(Q)-Is1+10;else if(Rs1<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=se8)Z*=16,Z+=$.charCodeAt(Q)-Rs1+10;else break;if(Z>=Nn0)return{n:0,c:Q,ok:!1}}if(Q===0)return{n:0,c:Q,ok:!1};return{n:Z,c:Q,ok:!0}}});var En0=v((_s1)=>{Object.defineProperty(_s1,"__esModule",{value:!0});_s1.Servers=_s1.ServerImpl=void 0;_s1.isIPV4OrHostname=Cs1;_s1.hostPort=wn0;var Bn0=dE(),On0=c3(),Ln0=Un0(),K04=JO(),W04=QG();function Cs1($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function Dn0($){return!Cs1($)}function H04($){let Q=$.toUpperCase().indexOf("::FFFF:");if(Q!==-1&&$.indexOf(".")!==-1){let X=$.substring(Q+7);return X=X.replace("[",""),X.replace("]","")}return $}function wn0($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=H04($),Dn0($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=Dn0($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),Q=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):K04.DEFAULT_PORT,Y=new URL(`${Q===80?"https":"http"}://${$}`);Y.port=`${Q}`;let G=Y.hostname;if(G.charAt(0)==="[")G=G.substring(1,G.length-1);return{listen:Y.host,hostname:G,port:Q}}class Ly{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let Q=wn0($);this.listen=Q.listen,this.hostname=Q.hostname,this.port=Q.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=Z}toString(){return this.listen}async resolve($){if(!$.fn||$.resolve===!1)return[this];let Z=[];if((0,Ln0.isIP)(this.hostname))return[this];else{let Q=await $.fn(this.hostname);if($.debug)console.log(`resolve ${this.hostname} = ${Q.join(",")}`);for(let X of Q){let Y=this.port===80?"https":"http",G=new URL(`${Y}://${Dn0(X)?"["+X+"]":X}`);G.port=`${this.port}`;let J=new Ly(G.host,!1);J.tlsName=this.hostname,Z.push(J)}}if($.randomize)(0,On0.shuffle)(Z);return this.resolves=Z,Z}}_s1.ServerImpl=Ly;class M70{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw W04.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,Bn0.getUrlParseFn)(),Q=new Map;for(let Y of this.servers)Q.set(Y.listen,Y);let X=[];for(let Y of $){Y=Z?Z(Y):Y;let{listen:G}=wn0(Y),J=Q.get(G);if(J)J.gossiped=!1,X.push(J);else X.push(new Ly(Y))}if(this.randomize)(0,On0.shuffle)(X);if(this.servers=X,this.currentServer===void 0||!X.includes(this.currentServer))this.currentServer=X[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let $=this.getCurrentServer();if(!(0,Ln0.isIP)($.hostname))this.tlsName=$.hostname,this.servers.forEach((Z)=>{if(Z.gossiped)Z.tlsName=this.tlsName})}getCurrentServer(){return this.currentServer}addServer($,Z=!1){let Q=(0,Bn0.getUrlParseFn)();$=Q?Q($):$;let X=new Ly($,Z);if((0,Ln0.isIP)(X.hostname))X.tlsName=this.tlsName;this.servers.push(X)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;let $=this.servers.shift();if($)this.servers.push($),this.currentServer=$;return $}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer($){if($){let Z=this.servers.indexOf($);this.servers.splice(Z,1)}}snapshot(){return M70.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return M70.freezeAll([$,...this.servers.slice(0,Z),...this.servers.slice(Z+1)])}static freezeAll($){return $.map((Z)=>Object.freeze({hostname:Z.hostname,port:Z.port,listen:Z.listen,src:Z.src,tlsName:Z.tlsName,reconnects:Z.reconnects,lastConnect:Z.lastConnect,gossiped:Z.gossiped,didConnect:Z.didConnect}))}find($){return this.servers.find((Z)=>Z.listen===$.listen)}setCurrent($){this.currentServer=$}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update($,Z){let Q=[],X=[],Y=(0,Bn0.getUrlParseFn)(),G=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((K)=>{K=Y?Y(K,Z):K;let W=new Ly(K,!0);G.set(K,W)});let J=[];if(this.servers.forEach((K,W)=>{let H=K.listen;if(K.gossiped&&this.currentServer.listen!==H&&G.get(H)===void 0)J.push(W);G.delete(H)}),J.reverse(),J.forEach((K)=>{let W=this.servers.splice(K,1);X=X.concat(W[0].listen)}),G.forEach((K,W)=>{this.servers.push(K),Q.push(W)}),this.randomize&&Q.length>0){let K=this.currentServer,W=this.servers.filter((H)=>H!==K);(0,On0.shuffle)(W),this.servers=K?[K,...W]:W}return{added:Q,deleted:X}}}_s1.Servers=M70});var V70=v((bs1)=>{Object.defineProperty(bs1,"__esModule",{value:!0});bs1.QueuedIteratorImpl=void 0;var jn0=c3(),xs1=QG();class fs1{inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ctx;_data;err;time;profile;yielding;didBreak;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=(0,jn0.deferred)(),this.yields=[],this.iterClosed=(0,jn0.deferred)(),this.time=0,this.yielding=!1,this.didBreak=!1,this.profile=!1}[Symbol.asyncIterator](){return this.iterate()}push($){if(this.done)return;if(this.didBreak){if(typeof $==="function"){let Z=$;try{Z()}catch(Q){}}return}if(typeof $==="function")this.pendingFiltered++;this.yields.push($),this.signal.resolve()}async*iterate(){if(this.noIterator)throw new xs1.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new xs1.InvalidOperationError("iterator is already yielding");this.yielding=!0;try{while(!0){if(this.yields.length===0)await this.signal;if(this.err)throw this.err;let $=this.yields;this.inflight=$.length,this.yields=[];for(let Z=0;Z<$.length;Z++){if(typeof $[Z]==="function"){this.pendingFiltered--;let X=$[Z];try{X()}catch(Y){throw Y}if(this.err)throw this.err;continue}this.processed++,this.inflight--;let Q=this.profile?Date.now():0;yield $[Z],this.time=this.profile?Date.now()-Q:0}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,jn0.deferred)()}}finally{this.didBreak=!0,this.stop()}}stop($){if(this.done)return;this.err=$,this.done=!0,this.signal.resolve(),this.iterClosed.resolve($)}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}bs1.QueuedIteratorImpl=fs1});var zn0=v((us1)=>{Object.defineProperty(us1,"__esModule",{value:!0});us1.MuxSubscription=void 0;var B04=JO(),gs1=QG();class hs1{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,B04.createInbox)($)}.`,this.baseInbox}add($){if(!isNaN($.received))$.received=0;this.reqs.set($.token,$)}get($){return this.reqs.get($)}cancel($){this.reqs.delete($.token)}getToken($){let Z=$.subject||"";if(Z.indexOf(this.baseInbox)===0)return Z.substring(this.baseInbox.length);return null}all(){return Array.from(this.reqs.values())}handleError($,Z){if($)return this.all().forEach((Q)=>{Q.resolver(Z,{})}),!0;if(Z.operation==="publish"){let Q=this.all().find((X)=>{return X.requestSubject===Z.subject});if(Q)return Q.resolver(Z,{}),!0}return!1}dispatcher(){return($,Z)=>{let Q=this.getToken(Z);if(Q){let X=this.get(Q);if(X){if($===null)$=Z?.data?.length===0&&Z.headers?.code===503?new gs1.NoRespondersError(X.requestSubject):null;X.resolver($,Z)}}}}close(){let $=new gs1.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}us1.MuxSubscription=hs1});var Pn0=v((ms1)=>{Object.defineProperty(ms1,"__esModule",{value:!0});ms1.Heartbeat=void 0;var O04=c3();class ls1{ph;interval;maxOut;timer;pendings;constructor($,Z,Q){this.ph=$,this.interval=Z,this.maxOut=Q,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel($){if(this.timer)clearTimeout(this.timer),this.timer=void 0;if(this._reset(),$)this.ph.disconnect()}_schedule(){this.timer=setTimeout(()=>{if(this.ph.dispatchStatus({type:"ping",pendingPings:this.pendings.length+1}),this.pendings.length===this.maxOut){this.cancel(!0);return}let $=(0,O04.deferred)();this.ph.flush($).then(()=>{this._reset()}).catch(()=>{this.cancel()}),this.pendings.push($),this._schedule()},this.interval)}_reset(){this.pendings=this.pendings.filter(($)=>{return $.resolve(),!1})}}ms1.Heartbeat=ls1});var Rn0=v((ts1)=>{Object.defineProperty(ts1,"__esModule",{value:!0});ts1.DenoBuffer=ts1.MAX_SIZE=ts1.AssertionError=void 0;ts1.assert=ps1;ts1.concat=ns1;ts1.append=D04;ts1.readAll=w04;ts1.writeAll=E04;var L04=ZG();class An0 extends Error{constructor($){super($);this.name="AssertionError"}}ts1.AssertionError=An0;function ps1($,Z="Assertion failed."){if(!$)throw new An0(Z)}var is1=32768;ts1.MAX_SIZE=4294967294;function k70($,Z,Q=0){let X=Z.byteLength-Q;if($.byteLength>X)$=$.subarray(0,X);return Z.set($,Q),$.byteLength}function ns1($,Z){if($===void 0&&Z===void 0)return new Uint8Array(0);if($===void 0)return Z;if(Z===void 0)return $;let Q=new Uint8Array($.length+Z.length);return Q.set($,0),Q.set(Z,$.length),Q}function D04($,Z){return ns1($,Uint8Array.of(Z))}class Tn0{_buf;_off;constructor($){if(this._off=0,$==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array($)}bytes($={copy:!0}){if($.copy===!1)return this._buf.subarray(this._off);return this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate($){if($===0){this.reset();return}if($<0||$>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+$)}reset(){this._reslice(0),this._off=0}_tryGrowByReslice($){let Z=this._buf.byteLength;if($<=this.capacity-Z)return this._reslice(Z+$),Z;return-1}_reslice($){ps1($<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,$)}readByte(){let $=new Uint8Array(1);if(this.read($))return $[0];return null}read($){if(this.empty()){if(this.reset(),$.byteLength===0)return 0;return null}let Z=k70(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write(L04.TE.encode($))}write($){let Z=this._grow($.byteLength);return k70($,this._buf,Z)}_grow($){let Z=this.length;if(Z===0&&this._off!==0)this.reset();let Q=this._tryGrowByReslice($);if(Q>=0)return Q;let X=this.capacity;if($<=Math.floor(X/2)-Z)k70(this._buf.subarray(this._off),this._buf);else if(X+$>ts1.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*X+$,ts1.MAX_SIZE));k70(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,ts1.MAX_SIZE)),Z}grow($){if($<0)throw Error("Buffer._grow: negative count");let Z=this._grow($);this._reslice(Z)}readFrom($){let Z=0,Q=new Uint8Array(is1);while(!0){let X=this.capacity-this.length<is1,Y=X?Q:new Uint8Array(this._buf.buffer,this.length),G=$.read(Y);if(G===null)return Z;if(X)this.write(Y.subarray(0,G));else this._reslice(this.length+G);Z+=G}}}ts1.DenoBuffer=Tn0;function w04($){let Z=new Tn0;return Z.readFrom($),Z.bytes()}function E04($,Z){let Q=0;while(Q<Z.length)Q+=$.write(Z.subarray(Q))}});var Mn0=v((es1)=>{Object.defineProperty(es1,"__esModule",{value:!0});es1.cc=es1.State=es1.Parser=es1.Kind=void 0;es1.describe=I04;var In0=Rn0(),qn0=ZG();es1.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function I04($){let Z,Q="";switch($.kind){case es1.Kind.MSG:Z="MSG";break;case es1.Kind.OK:Z="OK";break;case es1.Kind.ERR:Z="ERR",Q=qn0.TD.decode($.data);break;case es1.Kind.PING:Z="PING";break;case es1.Kind.PONG:Z="PONG";break;case es1.Kind.INFO:Z="INFO",Q=qn0.TD.decode($.data)}return`${Z}: ${Q}`}function rs1(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var as1=48,q04=57,Dy=67108864;class ss1{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=es1.State.OP_START,this.as=0,this.drop=0,this.hdr=0}parse($){let Z;for(Z=0;Z<$.length;Z++){let Q=$[Z];switch(this.state){case es1.State.OP_START:switch(Q){case es1.cc.M:case es1.cc.m:this.state=es1.State.OP_M,this.hdr=-1,this.ma=rs1();break;case es1.cc.H:case es1.cc.h:this.state=es1.State.OP_H,this.hdr=0,this.ma=rs1();break;case es1.cc.P:case es1.cc.p:this.state=es1.State.OP_P;break;case es1.cc.PLUS:this.state=es1.State.OP_PLUS;break;case es1.cc.MINUS:this.state=es1.State.OP_MINUS;break;case es1.cc.I:case es1.cc.i:this.state=es1.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_H:switch(Q){case es1.cc.M:case es1.cc.m:this.state=es1.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_M:switch(Q){case es1.cc.S:case es1.cc.s:this.state=es1.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_MS:switch(Q){case es1.cc.G:case es1.cc.g:this.state=es1.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_MSG:switch(Q){case es1.cc.SPACE:case es1.cc.TAB:this.state=es1.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_MSG_SPC:switch(Q){case es1.cc.SPACE:case es1.cc.TAB:continue;default:this.state=es1.State.MSG_ARG,this.as=Z}break;case es1.State.MSG_ARG:switch(Q){case es1.cc.CR:this.drop=1;break;case es1.cc.NL:{let X=this.argBuf?this.argBuf.bytes():$.subarray(this.as,Z-this.drop);this.processMsgArgs(X),this.drop=0,this.as=Z+1,this.state=es1.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(Q)}break;case es1.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let X=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:es1.Kind.MSG,msg:this.ma,data:X}),this.argBuf=void 0,this.msgBuf=void 0,this.state=es1.State.MSG_END}else{let X=this.ma.size-this.msgBuf.length,Y=$.length-Z;if(Y<X)X=Y;if(X>0)this.msgBuf.write($.subarray(Z,Z+X)),Z=Z+X-1;else this.msgBuf.writeByte(Q)}else if(Z-this.as>=this.ma.size)this.dispatcher.push({kind:es1.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=es1.State.MSG_END;break;case es1.State.MSG_END:switch(Q){case es1.cc.NL:this.drop=0,this.as=Z+1,this.state=es1.State.OP_START;break;default:continue}break;case es1.State.OP_PLUS:switch(Q){case es1.cc.O:case es1.cc.o:this.state=es1.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_PLUS_O:switch(Q){case es1.cc.K:case es1.cc.k:this.state=es1.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_PLUS_OK:switch(Q){case es1.cc.NL:this.dispatcher.push({kind:es1.Kind.OK}),this.drop=0,this.state=es1.State.OP_START;break}break;case es1.State.OP_MINUS:switch(Q){case es1.cc.E:case es1.cc.e:this.state=es1.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_MINUS_E:switch(Q){case es1.cc.R:case es1.cc.r:this.state=es1.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_MINUS_ER:switch(Q){case es1.cc.R:case es1.cc.r:this.state=es1.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_MINUS_ERR:switch(Q){case es1.cc.SPACE:case es1.cc.TAB:this.state=es1.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_MINUS_ERR_SPC:switch(Q){case es1.cc.SPACE:case es1.cc.TAB:continue;default:this.state=es1.State.MINUS_ERR_ARG,this.as=Z}break;case es1.State.MINUS_ERR_ARG:switch(Q){case es1.cc.CR:this.drop=1;break;case es1.cc.NL:{let X;if(this.argBuf)X=this.argBuf.bytes(),this.argBuf=void 0;else X=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:es1.Kind.ERR,data:X}),this.drop=0,this.as=Z+1,this.state=es1.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(Q))}break;case es1.State.OP_P:switch(Q){case es1.cc.I:case es1.cc.i:this.state=es1.State.OP_PI;break;case es1.cc.O:case es1.cc.o:this.state=es1.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_PO:switch(Q){case es1.cc.N:case es1.cc.n:this.state=es1.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_PON:switch(Q){case es1.cc.G:case es1.cc.g:this.state=es1.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_PONG:switch(Q){case es1.cc.NL:this.dispatcher.push({kind:es1.Kind.PONG}),this.drop=0,this.state=es1.State.OP_START;break}break;case es1.State.OP_PI:switch(Q){case es1.cc.N:case es1.cc.n:this.state=es1.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_PIN:switch(Q){case es1.cc.G:case es1.cc.g:this.state=es1.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_PING:switch(Q){case es1.cc.NL:this.dispatcher.push({kind:es1.Kind.PING}),this.drop=0,this.state=es1.State.OP_START;break}break;case es1.State.OP_I:switch(Q){case es1.cc.N:case es1.cc.n:this.state=es1.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_IN:switch(Q){case es1.cc.F:case es1.cc.f:this.state=es1.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_INF:switch(Q){case es1.cc.O:case es1.cc.o:this.state=es1.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_INFO:switch(Q){case es1.cc.SPACE:case es1.cc.TAB:this.state=es1.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case es1.State.OP_INFO_SPC:switch(Q){case es1.cc.SPACE:case es1.cc.TAB:continue;default:this.state=es1.State.INFO_ARG,this.as=Z}break;case es1.State.INFO_ARG:switch(Q){case es1.cc.CR:this.drop=1;break;case es1.cc.NL:{let X;if(this.argBuf)X=this.argBuf.bytes(),this.argBuf=void 0;else X=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:es1.Kind.INFO,data:X}),this.drop=0,this.as=Z+1,this.state=es1.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(Q)}break;default:throw this.fail($.subarray(Z))}}if((this.state===es1.State.MSG_ARG||this.state===es1.State.MINUS_ERR_ARG||this.state===es1.State.INFO_ARG)&&!this.argBuf)this.argBuf=new In0.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===es1.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new In0.DenoBuffer($.subarray(this.as))}}cloneMsgArg(){let $=this.ma.subject.length,Z=this.ma.reply?this.ma.reply.length:0,Q=new Uint8Array($+Z);if(Q.set(this.ma.subject),this.ma.reply)Q.set(this.ma.reply,$);if(this.argBuf=new In0.DenoBuffer(Q),this.ma.subject=Q.subarray(0,$),this.ma.reply)this.ma.reply=Q.subarray($)}processMsgArgs($){if(this.hdr>=0)return this.processHeaderMsgArgs($);let Z=[],Q=-1;for(let X=0;X<$.length;X++)switch($[X]){case es1.cc.SPACE:case es1.cc.TAB:case es1.cc.CR:case es1.cc.NL:if(Q>=0)Z.push($.subarray(Q,X)),Q=-1;break;default:if(Q<0)Q=X}if(Q>=0)Z.push($.subarray(Q));switch(Z.length){case 3:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.size=this.protoParseInt(Z[2],Dy);break;case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.size=this.protoParseInt(Z[3],Dy);break;default:throw this.fail($,"processMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processMsgArgs Bad or Missing Sid Error");if(this.ma.size<0)throw this.fail($,"processMsgArgs Bad or Missing Size Error")}fail($,Z=""){if(!Z)Z=`parse error [${this.state}]`;else Z=`${Z} [${this.state}]`;return Error(`${Z}: ${qn0.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],Q=-1;for(let X=0;X<$.length;X++)switch($[X]){case es1.cc.SPACE:case es1.cc.TAB:case es1.cc.CR:case es1.cc.NL:if(Q>=0)Z.push($.subarray(Q,X)),Q=-1;break;default:if(Q<0)Q=X}if(Q>=0)Z.push($.subarray(Q));switch(Z.length){case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.hdr=this.protoParseInt(Z[2],Dy),this.ma.size=this.protoParseInt(Z[3],Dy);break;case 5:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.hdr=this.protoParseInt(Z[3],Dy),this.ma.size=this.protoParseInt(Z[4],Dy);break;default:throw this.fail($,"processHeaderMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Sid Error");if(this.ma.hdr<0||this.ma.hdr>this.ma.size)throw this.fail($,"processHeaderMsgArgs Bad or Missing Header Size Error");if(this.ma.size<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Size Error")}protoParseInt($,Z){if($.length===0||$.length>15)return-1;let Q=0;for(let X=0;X<$.length;X++){if($[X]<as1||$[X]>q04)return-1;Q=Q*10+($[X]-as1)}return Z!==void 0&&Q>Z?-1:Q}}es1.Parser=ss1;es1.State={OP_START:0,OP_PLUS:1,OP_PLUS_O:2,OP_PLUS_OK:3,OP_MINUS:4,OP_MINUS_E:5,OP_MINUS_ER:6,OP_MINUS_ERR:7,OP_MINUS_ERR_SPC:8,MINUS_ERR_ARG:9,OP_M:10,OP_MS:11,OP_MSG:12,OP_MSG_SPC:13,MSG_ARG:14,MSG_PAYLOAD:15,MSG_END:16,OP_H:17,OP_P:18,OP_PI:19,OP_PIN:20,OP_PING:21,OP_PO:22,OP_PON:23,OP_PONG:24,OP_I:25,OP_IN:26,OP_INF:27,OP_INFO:28,OP_INFO_SPC:29,INFO_ARG:30};es1.cc={CR:13,E:69,e:101,F:70,f:102,G:71,g:103,H:72,h:104,I:73,i:105,K:75,k:107,M:77,m:109,MINUS:45,N:78,n:110,NL:10,O:79,o:111,P:80,p:112,PLUS:43,R:82,r:114,S:83,s:115,SPACE:32,TAB:9}});var _70=v((Ze1)=>{Object.defineProperty(Ze1,"__esModule",{value:!0});Ze1.MsgHdrsImpl=void 0;Ze1.canonicalMIMEHeaderKey=kn0;Ze1.headers=k04;var $e1=ZG(),l3=JO(),C70=QG();function kn0($){let F=!0,N=Array($.length);for(let U=0;U<$.length;U++){let B=$.charCodeAt(U);if(B===58||B<33||B>126)throw C70.InvalidArgumentError.format("header",`'${$[U]}' is not a valid character in a header name`);if(F&&97<=B&&B<=122)B-=32;else if(!F&&65<=B&&B<=90)B+=32;N[U]=B,F=B==45}return String.fromCharCode(...N)}function k04($=0,Z=""){if($===0&&Z!=="")throw C70.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw C70.InvalidArgumentError.format("description","is required");return new wy($,Z)}var Vn0="NATS/1.0";class wy{_code;headers;_description;constructor($=0,Z=""){this._code=$,this._description=Z,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals($){if($&&this.headers.size===$.headers.size&&this._code===$._code){for(let[Z,Q]of this.headers){let X=$.values(Z);if(Q.length!==X.length)return!1;let Y=[...Q].sort(),G=[...X].sort();for(let J=0;J<Y.length;J++)if(Y[J]!==G[J])return!1}return!0}return!1}static decode($){let Z=new wy,X=$e1.TD.decode($).split(`\r
1449
1449
  `),Y=X[0];if(Y!==Vn0){let G=Y.replace(Vn0,"").trim();if(G.length>0){if(Z._code=parseInt(G,10),isNaN(Z._code))Z._code=0;let J=Z._code.toString();G=G.replace(J,""),Z._description=G.trim()}}if(X.length>=1)X.slice(1).map((G)=>{if(G){let J=G.indexOf(":");if(J>-1){let K=G.slice(0,J),W=G.slice(J+1).trim();Z.append(K,W)}}});return Z}toString(){if(this.headers.size===0&&this._code===0)return"";let $=Vn0;if(this._code>0&&this._description!=="")$+=` ${this._code} ${this._description}`;for(let[Z,Q]of this.headers)for(let X=0;X<Q.length;X++)$=`${$}\r
1450
1450
  ${Z}: ${Q[X]}`;return`${$}\r
@@ -2368,7 +2368,7 @@ Caused by: ${Z.stack}`}};Qa=class Qa extends zZ{constructor($,Z){super($,Z);this
2368
2368
  `).some((Q)=>Q.indexOf("(https.js:")!==-1||Q.indexOf("node:https:")!==-1)}incrementSockets($){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[$])this.sockets[$]=[];let Z=new Qh4.Socket({writable:!1});return this.sockets[$].push(Z),this.totalSocketCount++,Z}decrementSockets($,Z){if(!this.sockets[$]||Z===null)return;let Q=this.sockets[$],X=Q.indexOf(Z);if(X!==-1){if(Q.splice(X,1),this.totalSocketCount--,Q.length===0)delete this.sockets[$]}}getName($){if(this.isSecureEndpoint($))return Xh4.Agent.prototype.getName.call(this,$);return super.getName($)}createSocket($,Z,Q){let X={...Z,secureEndpoint:this.isSecureEndpoint(Z)},Y=this.getName(X),G=this.incrementSockets(Y);Promise.resolve().then(()=>this.connect($,X)).then((J)=>{if(this.decrementSockets(Y,G),J instanceof II$.Agent)try{return J.addRequest($,X)}catch(K){return Q(K)}this[_H].currentSocket=J,super.createSocket($,Z,Q)},(J)=>{this.decrementSockets(Y,G),Q(J)})}createConnection(){let $=this[_H].currentSocket;if(this[_H].currentSocket=void 0,!$)throw Error("No socket was returned in the `connect()` function");return $}get defaultPort(){return this[_H].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort($){if(this[_H])this[_H].defaultPort=$}get protocol(){return this[_H].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol($){if(this[_H])this[_H].protocol=$}}MG.Agent=VI$});var SI$=v((dJ)=>{var Yh4=dJ&&dJ.__createBinding||(Object.create?function($,Z,Q,X){if(X===void 0)X=Q;var Y=Object.getOwnPropertyDescriptor(Z,Q);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[Q]}};Object.defineProperty($,X,Y)}:function($,Z,Q,X){if(X===void 0)X=Q;$[X]=Z[Q]}),Gh4=dJ&&dJ.__setModuleDefault||(Object.create?function($,Z){Object.defineProperty($,"default",{enumerable:!0,value:Z})}:function($,Z){$.default=Z}),C51=dJ&&dJ.__importStar||function($){if($&&$.__esModule)return $;var Z={};if($!=null){for(var Q in $)if(Q!=="default"&&Object.prototype.hasOwnProperty.call($,Q))Yh4(Z,$,Q)}return Gh4(Z,$),Z},Jh4=dJ&&dJ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(dJ,"__esModule",{value:!0});dJ.SocksProxyAgent=void 0;var Kh4=PI$(),Wh4=kI$(),Hh4=Jh4(K0("debug")),Fh4=C51(K0("dns")),Nh4=C51(K0("net")),Uh4=C51(K0("tls")),Bh4=K0("url"),PP0=(0,Hh4.default)("socks-proxy-agent"),Oh4=($)=>{if($.servername===void 0&&$.host&&!Nh4.isIP($.host))return{...$,servername:$.host};return $};function Lh4($){let Z=!1,Q=5,X=$.hostname,Y=parseInt($.port,10)||1080;switch($.protocol.replace(":","")){case"socks4":Z=!0,Q=4;break;case"socks4a":Q=4;break;case"socks5":Z=!0,Q=5;break;case"socks":Q=5;break;case"socks5h":Q=5;break;default:throw TypeError(`A "socks" protocol must be specified! Got: ${String($.protocol)}`)}let G={host:X,port:Y,type:Q};if($.username)Object.defineProperty(G,"userId",{value:decodeURIComponent($.username),enumerable:!1});if($.password!=null)Object.defineProperty(G,"password",{value:decodeURIComponent($.password),enumerable:!1});return{lookup:Z,proxy:G}}class _51 extends Wh4.Agent{constructor($,Z){super(Z);let Q=typeof $==="string"?new Bh4.URL($):$,{proxy:X,lookup:Y}=Lh4(Q);this.shouldLookup=Y,this.proxy=X,this.timeout=Z?.timeout??null,this.socketOptions=Z?.socketOptions??null}async connect($,Z){let{shouldLookup:Q,proxy:X,timeout:Y}=this;if(!Z.host)throw Error("No `host` defined!");let{host:G}=Z,{port:J,lookup:K=Fh4.lookup}=Z;if(Q)G=await new Promise((N,U)=>{K(G,{},(B,O)=>{if(B)U(B);else N(O)})});let W={proxy:X,destination:{host:G,port:typeof J==="number"?J:parseInt(J,10)},command:"connect",timeout:Y??void 0,socket_options:this.socketOptions??void 0},H=(N)=>{if($.destroy(),F.destroy(),N)N.destroy()};PP0("Creating socks proxy connection: %o",W);let{socket:F}=await Kh4.SocksClient.createConnection(W);if(PP0("Successfully created socks proxy connection"),Y!==null)F.setTimeout(Y),F.on("timeout",()=>H());if(Z.secureEndpoint){PP0("Upgrading socket connection to TLS");let N=Uh4.connect({...Dh4(Oh4(Z),"host","path","port"),socket:F});return N.once("error",(U)=>{PP0("Socket TLS error",U.message),H(N)}),N}return F}}_51.protocols=["socks","socks4","socks4a","socks5","socks5h"];dJ.SocksProxyAgent=_51;function Dh4($,...Z){let Q={},X;for(X in $)if(!Z.includes(X))Q[X]=$[X];return Q}});var fI$=v((u8Z,xI$)=>{var v51=K0("https"),x51=K0("http"),{URL:CI$}=K0("url");class _I$ extends x51.Agent{constructor($){let{proxy:Z,proxyRequestOptions:Q,...X}=$;super(X);this.proxy=typeof Z==="string"?new CI$(Z):Z,this.proxyRequestOptions=Q||{}}createConnection($,Z){let Q={...this.proxyRequestOptions,method:"CONNECT",host:this.proxy.hostname,port:this.proxy.port,path:`${$.host}:${$.port}`,setHost:!1,headers:{...this.proxyRequestOptions.headers,connection:this.keepAlive?"keep-alive":"close",host:`${$.host}:${$.port}`},agent:!1,timeout:$.timeout||0};if(this.proxy.username||this.proxy.password){let Y=Buffer.from(`${decodeURIComponent(this.proxy.username||"")}:${decodeURIComponent(this.proxy.password||"")}`).toString("base64");Q.headers["proxy-authorization"]=`Basic ${Y}`}if(this.proxy.protocol==="https:")Q.servername=this.proxy.hostname;let X=(this.proxy.protocol==="http:"?x51:v51).request(Q);X.once("connect",(Y,G,J)=>{if(X.removeAllListeners(),G.removeAllListeners(),Y.statusCode===200)Z(null,G);else G.destroy(),Z(Error(`Bad response: ${Y.statusCode}`),null)}),X.once("timeout",()=>{X.destroy(Error("Proxy timeout"))}),X.once("error",(Y)=>{X.removeAllListeners(),Z(Y,null)}),X.end()}}class vI$ extends v51.Agent{constructor($){let{proxy:Z,proxyRequestOptions:Q,...X}=$;super(X);this.proxy=typeof Z==="string"?new CI$(Z):Z,this.proxyRequestOptions=Q||{}}createConnection($,Z){let Q={...this.proxyRequestOptions,method:"CONNECT",host:this.proxy.hostname,port:this.proxy.port,path:`${$.host}:${$.port}`,setHost:!1,headers:{...this.proxyRequestOptions.headers,connection:this.keepAlive?"keep-alive":"close",host:`${$.host}:${$.port}`},agent:!1,timeout:$.timeout||0};if(this.proxy.username||this.proxy.password){let Y=Buffer.from(`${decodeURIComponent(this.proxy.username||"")}:${decodeURIComponent(this.proxy.password||"")}`).toString("base64");Q.headers["proxy-authorization"]=`Basic ${Y}`}if(this.proxy.protocol==="https:")Q.servername=this.proxy.hostname;let X=(this.proxy.protocol==="http:"?x51:v51).request(Q);X.once("connect",(Y,G,J)=>{if(X.removeAllListeners(),G.removeAllListeners(),Y.statusCode===200){let K=super.createConnection({...$,socket:G});Z(null,K)}else G.destroy(),Z(Error(`Bad response: ${Y.statusCode}`),null)}),X.once("timeout",()=>{X.destroy(Error("Proxy timeout"))}),X.once("error",(Y)=>{X.removeAllListeners(),Z(Y,null)}),X.end()}}xI$.exports={HttpProxyAgent:_I$,HttpsProxyAgent:vI$}});var f51,bI$,yI$;var gI$=L(()=>{f51=k(fI$(),1),bI$=f51.default.HttpProxyAgent,yI$=f51.default.HttpsProxyAgent});import YU from"fs";import wh4 from"https";import Eh4 from"http";import jh4 from"net";import Wv from"path";import{Headers as zh4}from"node-fetch";import AP0 from"child_process";function b51($){try{return YU.accessSync($),!0}catch{return!1}}class TP0{addAuthenticator($){this.custom_authenticators.push($)}constructor(){this.authenticators=[new b61,new u61,new g61,new h61,new wa],this.custom_authenticators=[],this.contexts=[],this.clusters=[],this.users=[]}getContexts(){return this.contexts}getClusters(){return this.clusters}getUsers(){return this.users}getCurrentContext(){return this.currentContext}setCurrentContext($){this.currentContext=$}getContextObject($){if(!this.contexts)return null;return h51(this.contexts,$,"context")}getCurrentCluster(){let $=this.getCurrentContextObject();if(!$)return null;return this.getCluster($.cluster)}getCluster($){return h51(this.clusters,$,"cluster")}getCurrentUser(){let $=this.getCurrentContextObject();if(!$)return null;return this.getUser($.user)}getUser($){return h51(this.users,$,"user")}loadFromFile($,Z){let Q=Wv.dirname($);this.loadFromString(YU.readFileSync($).toString("utf-8"),Z),this.makePathsAbsolute(Q)}async applyToFetchOptions($){await this.applyToHTTPSOptions($);let Z=new zh4;for(let[Q,X]of Object.entries($.headers||{}))if(Array.isArray(X))X.forEach((Y)=>{Z.append(Q,Y)});else if(typeof X==="number"||typeof X==="string")Z.set(Q,X.toString());if($.auth)Z.set("Authorization","Basic "+Buffer.from($.auth).toString("base64"));return{agent:$.agent,headers:Z,method:$.method,timeout:$.timeout}}async applyToHTTPSOptions($){let Z=this.getCurrentUser(),Q=this.getCurrentCluster();if(await this.applyOptions($),Z&&Z.username)$.auth=`${Z.username}:${Z.password}`;let X={};if(X.ca=$.ca,X.cert=$.cert,X.key=$.key,X.pfx=$.pfx,X.passphrase=$.passphrase,$.rejectUnauthorized!==void 0)X.rejectUnauthorized=$.rejectUnauthorized;X.timeout=$.timeout,X.servername=$.servername,X.ciphers=$.ciphers,X.honorCipherOrder=$.honorCipherOrder,X.ecdhCurve=$.ecdhCurve,X.clientCertEngine=$.clientCertEngine,X.crl=$.crl,X.dhparam=$.dhparam,X.secureOptions=$.secureOptions,X.secureProtocol=$.secureProtocol,X.sessionIdContext=$.sessionIdContext,$.agent=this.createAgent(Q,X)}async applySecurityAuthentication($){let Z=this.getCurrentCluster(),Q=this.getCurrentUser(),X={},Y={};if(await this.applyOptions(Y),Z&&Z.skipTLSVerify)X.rejectUnauthorized=!1;if(Z&&Z.tlsServerName)X.servername=Z.tlsServerName;if(Q&&Q.username){let J=Buffer.from(`${Q.username}:${Q.password}`).toString("base64");$.setHeaderParam("Authorization",`Basic ${J}`)}let G=Y.headers||{};if(Object.entries(G).forEach(([J,K])=>{$.setHeaderParam(J,`${K}`)}),X.ca=Y.ca,X.cert=Y.cert,X.key=Y.key,X.pfx=Y.pfx,X.passphrase=Y.passphrase,Y.rejectUnauthorized!==void 0)X.rejectUnauthorized=Y.rejectUnauthorized;$.setAgent(this.createAgent(Z,X))}getName(){return"kubeconfig authentication"}loadFromString($,Z){let Q=C61.load($);this.clusters=NT$(Q.clusters,Z),this.contexts=LT$(Q.contexts,Z),this.users=BT$(Q.users,Z),this.currentContext=Q["current-context"]}loadFromOptions($){this.clusters=$.clusters,this.contexts=$.contexts,this.users=$.users,this.currentContext=$.currentContext}loadFromClusterAndUser($,Z){this.clusters=[$],this.users=[Z],this.currentContext="loaded-context",this.contexts=[{cluster:$.name,user:Z.name,name:this.currentContext}]}loadFromCluster($=""){let Z=process.env.KUBERNETES_SERVICE_HOST,Q=process.env.KUBERNETES_SERVICE_PORT,X="inCluster",Y="inClusterUser",G="inClusterContext",J="https";if(Q==="80"||Q==="8080"||Q==="8001")J="http";let K=Z;if(Z&&jh4.isIPv6(Z))K=`[${Z}]`;this.clusters=[{name:"inCluster",caFile:`${$}${Ph4}`,server:`${J}://${K}:${Q}`,skipTLSVerify:!1}],this.users=[{name:"inClusterUser",authProvider:{name:"tokenFile",config:{tokenFile:`${$}${hI$}`}}}];let W=`${$}${Ah4}`,H;if(b51(W))H=YU.readFileSync(W).toString("utf-8");this.contexts=[{cluster:"inCluster",name:"inClusterContext",user:"inClusterUser",namespace:H}],this.currentContext="inClusterContext"}mergeConfig($,Z=!1){if(!Z&&$.currentContext)this.currentContext=$.currentContext;$.clusters.forEach((Q)=>{this.addCluster(Q)}),$.users.forEach((Q)=>{this.addUser(Q)}),$.contexts.forEach((Q)=>{this.addContext(Q)})}addCluster($){if(!this.clusters)this.clusters=[];this.clusters.forEach((Z,Q)=>{if(Z.name===$.name)throw Error(`Duplicate cluster: ${Z.name}`)}),this.clusters.push($)}addUser($){if(!this.users)this.users=[];this.users.forEach((Z,Q)=>{if(Z.name===$.name)throw Error(`Duplicate user: ${Z.name}`)}),this.users.push($)}addContext($){if(!this.contexts)this.contexts=[];this.contexts.forEach((Z,Q)=>{if(Z.name===$.name)throw Error(`Duplicate context: ${Z.name}`)}),this.contexts.push($)}loadFromDefault($,Z=!1,Q=process.platform){if(process.env.KUBECONFIG&&process.env.KUBECONFIG.length>0){let Y=process.env.KUBECONFIG.split(Wv.delimiter).filter((G)=>G);this.loadFromFile(Y[0],$);for(let G=1;G<Y.length;G++){let J=new TP0;J.loadFromFile(Y[G],$),this.mergeConfig(J,Z)}return}let X=Th4(Q);if(X){let Y=Wv.join(X,".kube","config");if(b51(Y)){this.loadFromFile(Y,$);return}}if(Q==="win32"){try{let Y=AP0.spawnSync("wsl.exe",["bash","-c","printenv KUBECONFIG"]);if(Y.status===0&&Y.stdout.length>0){let G=AP0.spawnSync("wsl.exe",["cat",Y.stdout.toString("utf8")]);if(G.status===0){this.loadFromString(G.stdout.toString("utf8"),$);return}}}catch{}try{let Y=AP0.spawnSync("wsl.exe",["cat","~/.kube/config"]);if(Y.status===0){this.loadFromString(Y.stdout.toString("utf8"),$);let G=AP0.spawnSync("wsl.exe",["wslpath","-w","~/.kube"]);if(G.status===0)this.makePathsAbsolute(G.stdout.toString("utf8"));return}}catch{}}if(b51(hI$)){this.loadFromCluster();return}this.loadFromClusterAndUser({name:"cluster",server:"http://localhost:8080"},{name:"user"})}makeApiClient($){let Z=this.getCurrentCluster();if(!Z)throw Error("No active cluster!");let Q={default:this},X=new pz0(Z.server,{}),Y=n61({baseServer:X,authMethods:Q});return new $(Y)}makePathsAbsolute($){this.clusters.forEach((Z)=>{if(Z.caFile)Z.caFile=y51($,Z.caFile)}),this.users.forEach((Z)=>{if(Z.certFile)Z.certFile=y51($,Z.certFile);if(Z.keyFile)Z.keyFile=y51($,Z.keyFile)})}exportConfig(){let $={apiVersion:"v1",kind:"Config",clusters:this.clusters.map(UT$),users:this.users.map(OT$),contexts:this.contexts.map(DT$),preferences:{},"current-context":this.getCurrentContext()};return JSON.stringify($)}getCurrentContextObject(){return this.getContextObject(this.currentContext)}createAgent($,Z){var Q,X;let Y;if($&&$.proxyUrl)if($.proxyUrl.startsWith("socks"))Y=new cI$.SocksProxyAgent($.proxyUrl,Z);else if($.server.startsWith("https")){let G=Z;G.proxy=$.proxyUrl,Y=new yI$(G)}else if($.server.startsWith("http")){let G=Z;G.proxy=$.proxyUrl,Y=new bI$(G)}else throw Error("Unsupported proxy type");else if(((Q=$===null||$===void 0?void 0:$.server)===null||Q===void 0?void 0:Q.startsWith("http:"))&&$.skipTLSVerify)Y=new Eh4.Agent(Z);else if(((X=$===null||$===void 0?void 0:$.server)===null||X===void 0?void 0:X.startsWith("http:"))&&!$.skipTLSVerify)throw Error("HTTP protocol is not allowed when skipTLSVerify is not set or false");else Y=new wh4.Agent(Z);return Y}applyHTTPSOptions($){var Z;let Q=this.getCurrentCluster(),X=this.getCurrentUser();if(!X)return;if(Q!=null&&Q.skipTLSVerify)$.rejectUnauthorized=!1;if(Q!=null&&Q.tlsServerName)$.servername=Q.tlsServerName;let Y=Q!=null?g51(Q.caFile,Q.caData):null;if(Y)$.ca=Y;let G=g51(X.certFile,X.certData);if(G)$.cert=G;let J=g51(X.keyFile,X.keyData);if(J)$.key=J;if(X.impersonateUser!=null)(Z=$.headers)!==null&&Z!==void 0||($.headers={}),$.headers["Impersonate-User"]=X.impersonateUser}async applyAuthorizationHeader($){let Z=this.getCurrentUser();if(!Z)return;let Q=this.authenticators.find((X)=>{return X.isAuthProvider(Z)});if(!Q)Q=this.custom_authenticators.find((X)=>{return X.isAuthProvider(Z)});if(!$.headers)$.headers={};if(Q)await Q.applyAuthentication(Z,$);if(Z.token)$.headers.Authorization=`Bearer ${Z.token}`}async applyOptions($){this.applyHTTPSOptions($),await this.applyAuthorizationHeader($)}}function y51($,Z){if(!$||Wv.isAbsolute(Z))return Z;return Wv.join($,Z)}function g51($,Z){if($)return YU.readFileSync($);if(Z)return Buffer.from(Z,"base64");return null}function uI$($){return $.reduce((Z,Q)=>{if(Q&&!Z.includes(Q))return Z.concat(Q);else return Z},[])}function Th4($=process.platform){if($!=="win32"){if(process.env.HOME)try{return YU.accessSync(process.env.HOME),process.env.HOME}catch{}return null}let Z=process.env.HOMEDRIVE&&process.env.HOMEPATH?Wv.join(process.env.HOMEDRIVE,process.env.HOMEPATH):"",Q=process.env.HOME||"",X=process.env.USERPROFILE||"",Y=uI$([Q,Z,X]),G=uI$([Q,X,Z]);for(let J of Y)try{return YU.accessSync(Wv.join(J,".kube","config")),J}catch{}for(let J of G)try{return YU.accessSync(J,YU.constants.W_OK),J}catch{}for(let J of G)try{return YU.accessSync(J),J}catch{}return G[0]||null}function h51($,Z,Q){if(!$)return null;for(let X of $)if(X.name===Z){if(X[Q])return X[Q].name=Z,X[Q];return X}return null}var cI$,u51="/var/run/secrets/kubernetes.io/serviceaccount",Ph4,hI$,Ah4;var lI$=L(()=>{_61();FT$();wT$();ET$();jT$();zT$();sz0();RR$();gI$();cI$=k(SI$(),1),Ph4=u51+"/ca.crt",hI$=u51+"/token",Ah4=u51+"/namespace"});import{STATUS_CODES as Rh4}from"http";import{createInterface as Ih4}from"readline";import qh4 from"node-fetch";class c51{constructor($){this.config=$}async watch($,Z,Q,X){let Y=this.config.getCurrentCluster();if(!Y)throw Error("No currently active cluster");let G=new URL(Y.server+$);G.searchParams.set("watch","true");for(let[N,U]of Object.entries(Z||{}))if(U!==void 0)G.searchParams.set(N,U.toString());let J=await this.config.applyToFetchOptions({}),K=new AbortController,W=AbortSignal.timeout(30000);J.signal=AbortSignal.any([K.signal,W]),J.signal=K.signal,J.method="GET";let H=!1,F=(N)=>{if(!H)H=!0,K.abort(),X(N)};try{let N=await qh4(G,J);if(J.agent&&typeof J.agent==="object")for(let U of Object.values(J.agent.sockets).flat())U===null||U===void 0||U.setKeepAlive(!0,30000);if(N.status===200){let U=N.body;U.on("error",F),U.on("close",()=>F(null)),U.on("finish",()=>F(null));let B=Ih4(U);B.on("error",F),B.on("close",()=>F(null)),B.on("finish",()=>F(null)),B.on("line",(O)=>{try{let D=JSON.parse(O.toString());Q(D.type,D.object,D)}catch{}})}else{let U=N.statusText||Rh4[N.status]||"Internal Server Error",B=Error(U);throw B.statusCode=N.status,B}}catch(N){F(N)}return K}}var l51=L(()=>{c51.SERVER_SIDE_CLOSE={error:"Connection closed on server"}});var m51=L(()=>{d51();l51()});class _K{serialize(){let $={};for(let Z of _K.attributeTypeMap)if(this[Z.baseName]!==void 0)$[Z.name]=R1.serialize(this[Z.baseName],Z.type,Z.format);for(let[Z,Q]of Object.entries(this)){if(_K.attributeTypeMap.find((X)=>X.name===Z))continue;$[Z]=Q}return $}static fromUnknown($){if(!RP0($))throw Error(`Unable to deseriliaze non-Kubernetes object ${$}.`);let Z=new _K;for(let Q of _K.attributeTypeMap)if($[Q.baseName]!==void 0)Z[Q.name]=R1.deserialize($[Q.baseName],Q.type,Q.format);for(let[Q,X]of Object.entries($)){if(_K.attributeTypeMap.find((Y)=>Y.name===Q))continue;Z[Q]=X}return Z}}var RP0=($)=>!!$&&typeof $==="object"&&("apiVersion"in $)&&("kind"in $),mI$=({group:$,version:Z})=>[$,Z].join("/"),Mh4=($)=>{let[Z,Q]=$.apiVersion.split("/");return{kind:$.kind,group:Q?Z:"",version:Q?Q:Z}},UD;var IP0=L(()=>{s1();_K.attributeTypeMap=[{name:"apiVersion",baseName:"apiVersion",type:"string",format:""},{name:"kind",baseName:"kind",type:"string",format:""},{name:"metadata",baseName:"metadata",type:"V1ObjectMeta",format:""}];UD=class UD extends R1{static registerModel($,Z){var Q,X;let Y=mI$($),G=(Q=(X=this.modelRegistry)[Y])!==null&&Q!==void 0?Q:X[Y]={};if(G[$.kind])throw Error(`Kind ${$.kind} of ${Y} is already defined`);G[$.kind]=Z}static clearModelRegistry(){this.modelRegistry={}}static getSerializerForObject($){var Z;if(!RP0($))return;let Q=Mh4($);return(Z=UD.modelRegistry[mI$(Q)])===null||Z===void 0?void 0:Z[Q.kind]}static serialize($,Z,Q=""){let X=UD.getSerializerForObject($);if(X)return X.serialize($,Z,Q);if($ instanceof _K)return $.serialize();let Y=R1.serialize($,Z,Q);if(Y!==$)return Y;if(!RP0($))return Y;let G={};for(let J of _K.attributeTypeMap)if($[J.baseName]!==void 0)G[J.name]=R1.serialize($[J.baseName],J.type,J.format);for(let[J,K]of Object.entries($)){if(_K.attributeTypeMap.find((W)=>W.name===J))continue;G[J]=K}return G}static deserialize($,Z,Q=""){let X=UD.getSerializerForObject($);if(X)return X.deserialize($,Z,Q);let Y=R1.deserialize($,Z,Q);if(Y!==$)return Y;if(!RP0($))return Y;return _K.fromUnknown($)}};UD.modelRegistry={}});var d51=L(()=>{m51();IP0()});var qP0=L(()=>{sz0()});var i51=()=>{};import dI$ from"ws"with{type:"jsx"};class q5{static supportsClose($){return $==="v5.channel.k8s.io"}static closeStream($,Z){switch($){case q5.StdinStream:Z.stdin.pause();break;case q5.StdoutStream:Z.stdout.end();break;case q5.StderrStream:Z.stderr.end();break}}static handleStandardStreams($,Z,Q,X){if(Z.length<1)return null;if(Q&&$===q5.StdoutStream)Q.write(Z);else if(X&&$===q5.StderrStream)X.write(Z);else if($===q5.StatusStream){if(Q&&Q!==process.stdout)Q.end();if(X&&X!==process.stderr)X.end();return JSON.parse(Z.toString("utf8"))}else throw Error("Unknown stream: "+$);return null}static handleStandardInput($,Z,Q=0){return Z.on("data",(X)=>{$.send(pI$(Q,X,Z.readableEncoding))}),Z.on("end",()=>{if(q5.supportsClose($.protocol)){let X=Buffer.alloc(2);X.writeUint8(this.CloseStream,0),X.writeUint8(this.StdinStream,1),$.send(X);return}$.close()}),!0}static async processData($,Z,Q,X=0,Y=3,G){let J=pI$(X,$,G),K=0;for(;K<Y;++K)if(Z!==null&&Z.readyState===dI$.OPEN){Z.send(J);break}else Z=await Q();if(K>=Y)throw Error("can't send data to ws");return Z}static restartableHandleStandardInput($,Z,Q=0,X=3,Y=!1){if(X<0)throw Error("retryCount can't be lower than 0.");let G=Promise.resolve(),J=null;if(Z.on("data",(K)=>{G=G.then(async()=>{J=await q5.processData(K,J,$,Q,X,Z.readableEncoding)})}),Y)Z.on("flush",async()=>{await G});return Z.on("end",()=>{if(J!==null)J.close()}),()=>J}constructor($,Z,Q={stdin:process.stdin,stdout:process.stdout,stderr:process.stderr}){this.config=$,this.socketFactory=Z,this.streams=Q}async connect($,Z,Q){let X=this.config.getCurrentCluster();if(!X)throw Error("No cluster is defined.");let Y=X.server,G=Y.startsWith("https://"),J=G?Y.substr(8):Y.substr(7),W=`${G?"wss":"ws"}://${J}${$}`,H={};return await this.config.applyToHTTPSOptions(H),await new Promise((F,N)=>{let U=this.socketFactory?this.socketFactory(W,iI$,H):new dI$(W,iI$,H),B=!1;U.onopen=()=>{B=!0,F(U)},U.onerror=(O)=>{if(!B)N(O)},U.onmessage=({data:O})=>{if(typeof O==="string"){if(O.charCodeAt(0)===q5.CloseStream)q5.closeStream(O.charCodeAt(1),this.streams);if(Z&&!Z(O))U.close()}else if(O instanceof Buffer){let D=O.readUint8(0);if(D===q5.CloseStream)q5.closeStream(O.readInt8(1),this.streams);if(Q&&!Q(D,O.slice(1)))U.close()}}})}}function pI$($,Z,Q){let X;if(Z instanceof Buffer)X=Buffer.alloc(Z.length+1),Z.copy(X,1);else{Q!==null&&Q!==void 0||(Q="utf-8");let Y=Buffer.byteLength(Z,Q);X=Buffer.alloc(Y+1),X.write(Z,1,Y,Q)}return X.writeInt8($,0),X}var iI$;var MP0=L(()=>{iI$=["v5.channel.k8s.io","v4.channel.k8s.io","v3.channel.k8s.io","v2.channel.k8s.io","channel.k8s.io"];q5.StdinStream=0;q5.StdoutStream=1;q5.StderrStream=2;q5.StatusStream=3;q5.ResizeStream=4;q5.CloseStream=255});var nI$=L(()=>{i51();MP0()});var p51=L(()=>{i51();MP0()});import Sh4 from"querystring";class n51{constructor($,Z,Q){this.handler=Q||new q5($),this.disconnectOnErr=Z===void 0?!0:Z}async portForward($,Z,Q,X,Y,G,J=0){if(Q.length===0)throw Error("You must provide at least one port to forward to.");if(Q.length>1)throw Error("Only one port is currently supported for port-forward");let K={ports:Q[0]},W=Sh4.stringify(K),H=[];Q.forEach((U,B)=>{H[B*2]=!0,H[B*2+1]=!0});let F=`/api/v1/namespaces/${$}/pods/${Z}/portforward?${W}`,N=()=>{return this.handler.connect(F,null,(U,B)=>{if(U>=Q.length*2)return!this.disconnectOnErr;if(H[U])B=B.slice(2),H[U]=!1;if(U%2===1){if(Y)Y.write(B)}else X.write(B);return!0})};if(J<1){let U=await N();return q5.handleStandardInput(U,G,0),U}return q5.restartableHandleStandardInput(N,G,0,J)}}var tI$=L(()=>{MP0()});var oI$=()=>{};var rI$=L(()=>{_61();IP0()});var aI$=L(()=>{qP0()});var sI$=()=>{};var VP0=v((Q6Z,eI$)=>{eI$.exports={DEFAULT_INITIAL_SIZE:8192,DEFAULT_INCREMENT_AMOUNT:8192,DEFAULT_FREQUENCY:1,DEFAULT_CHUNK_SIZE:1024}});var Qq$=v((X6Z,Zq$)=>{var $q$=K0("stream"),kP0=VP0(),vh4=K0("util"),xh4=Zq$.exports=function($){var Z=this;$=$||{},$q$.Readable.call(this,$),this.stopped=!1;var Q=$.hasOwnProperty("frequency")?$.frequency:kP0.DEFAULT_FREQUENCY,X=$.chunkSize||kP0.DEFAULT_CHUNK_SIZE,Y=$.initialSize||kP0.DEFAULT_INITIAL_SIZE,G=$.incrementAmount||kP0.DEFAULT_INCREMENT_AMOUNT,J=0,K=new Buffer(Y),W=!1,H=function(){var U=Math.min(X,J),B=!1;if(U>0){var O=null;O=new Buffer(U),K.copy(O,0,0,U),B=Z.push(O)!==!1,W=B,K.copy(K,0,U,J),J-=U}if(J===0&&Z.stopped)Z.push(null);if(B)H.timeout=setTimeout(H,Q);else H.timeout=null};this.stop=function(){if(this.stopped)throw Error("stop() called on already stopped ReadableStreamBuffer");if(this.stopped=!0,J===0)this.push(null)},this.size=function(){return J},this.maxSize=function(){return K.length};var F=function(U){if(K.length-J<U){var B=Math.ceil((U-(K.length-J))/G),O=new Buffer(K.length+G*B);K.copy(O,0,0,J),K=O}},N=function(){if(!H.timeout&&W)H.timeout=setTimeout(H,Q)};this.put=function(U,B){if(Z.stopped)throw Error("Tried to write data to a stopped ReadableStreamBuffer");if(Buffer.isBuffer(U))F(U.length),U.copy(K,J,0),J+=U.length;else{U=U+"";var O=Buffer.byteLength(U);F(O),K.write(U,J,B||"utf8"),J+=O}N()},this._read=function(){W=!0,N()}};vh4.inherits(xh4,$q$.Readable)});var Jq$=v((Y6Z,Gq$)=>{var fh4=K0("util"),Yq$=K0("stream"),Xq$=VP0(),bh4=Gq$.exports=function($){$=$||{},$.decodeStrings=!0,Yq$.Writable.call(this,$);var Z=$.initialSize||Xq$.DEFAULT_INITIAL_SIZE,Q=$.incrementAmount||Xq$.DEFAULT_INCREMENT_AMOUNT,X=new Buffer(Z),Y=0;this.size=function(){return Y},this.maxSize=function(){return X.length},this.getContents=function(J){if(!Y)return!1;var K=new Buffer(Math.min(J||Y,Y));if(X.copy(K,0,0,K.length),K.length<Y)X.copy(X,0,K.length);return Y-=K.length,K},this.getContentsAsString=function(J,K){if(!Y)return!1;var W=X.toString(J||"utf8",0,Math.min(K||Y,Y)),H=Buffer.byteLength(W);if(H<Y)X.copy(X,0,H);return Y-=H,W};var G=function(J){if(X.length-Y<J){var K=Math.ceil((J-(X.length-Y))/Q),W=new Buffer(X.length+Q*K);X.copy(W,0,0,Y),X=W}};this._write=function(J,K,W){G(J.length),J.copy(X,Y,0),Y+=J.length,W()}};fh4.inherits(bh4,Yq$.Writable)});var Kq$=v((G6Z,SP0)=>{SP0.exports=VP0();SP0.exports.ReadableStreamBuffer=Qq$();SP0.exports.WritableStreamBuffer=Jq$()});var Hq$=v((J6Z,Wq$)=>{Wq$.exports=class{constructor(Z){if(!(Z>0)||(Z-1&Z)!==0)throw Error("Max size for a FixedFIFO should be a power of two");this.buffer=Array(Z),this.mask=Z-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(Z){if(this.buffer[this.top]!==void 0)return!1;return this.buffer[this.top]=Z,this.top=this.top+1&this.mask,!0}shift(){let Z=this.buffer[this.btm];if(Z===void 0)return;return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,Z}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var t51=v((K6Z,Nq$)=>{var Fq$=Hq$();Nq$.exports=class{constructor(Z){this.hwm=Z||16,this.head=new Fq$(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(Z){if(this.length++,!this.head.push(Z)){let Q=this.head;this.head=Q.next=new Fq$(2*this.head.buffer.length),this.head.push(Z)}}shift(){if(this.length!==0)this.length--;let Z=this.tail.shift();if(Z===void 0&&this.tail.next){let Q=this.tail.next;return this.tail.next=null,this.tail=Q,this.tail.shift()}return Z}peek(){let Z=this.tail.peek();if(Z===void 0&&this.tail.next)return this.tail.next.peek();return Z}isEmpty(){return this.length===0}}});var qu=v((W6Z,Uq$)=>{function yh4($){return Buffer.isBuffer($)||$ instanceof Uint8Array}function gh4($){return Buffer.isEncoding($)}function hh4($,Z,Q){return Buffer.alloc($,Z,Q)}function uh4($){return Buffer.allocUnsafe($)}function ch4($){return Buffer.allocUnsafeSlow($)}function lh4($,Z){return Buffer.byteLength($,Z)}function mh4($,Z){return Buffer.compare($,Z)}function dh4($,Z){return Buffer.concat($,Z)}function ih4($,Z,Q,X,Y){return h6($).copy(Z,Q,X,Y)}function ph4($,Z){return h6($).equals(Z)}function nh4($,Z,Q,X,Y){return h6($).fill(Z,Q,X,Y)}function th4($,Z,Q){return Buffer.from($,Z,Q)}function oh4($,Z,Q,X){return h6($).includes(Z,Q,X)}function rh4($,Z,Q,X){return h6($).indexOf(Z,Q,X)}function ah4($,Z,Q,X){return h6($).lastIndexOf(Z,Q,X)}function sh4($){return h6($).swap16()}function eh4($){return h6($).swap32()}function $u4($){return h6($).swap64()}function h6($){if(Buffer.isBuffer($))return $;return Buffer.from($.buffer,$.byteOffset,$.byteLength)}function Zu4($,Z,Q,X){return h6($).toString(Z,Q,X)}function Qu4($,Z,Q,X,Y){return h6($).write(Z,Q,X,Y)}function Xu4($,Z){return h6($).readDoubleBE(Z)}function Yu4($,Z){return h6($).readDoubleLE(Z)}function Gu4($,Z){return h6($).readFloatBE(Z)}function Ju4($,Z){return h6($).readFloatLE(Z)}function Ku4($,Z){return h6($).readInt32BE(Z)}function Wu4($,Z){return h6($).readInt32LE(Z)}function Hu4($,Z){return h6($).readUInt32BE(Z)}function Fu4($,Z){return h6($).readUInt32LE(Z)}function Nu4($,Z,Q){return h6($).writeDoubleBE(Z,Q)}function Uu4($,Z,Q){return h6($).writeDoubleLE(Z,Q)}function Bu4($,Z,Q){return h6($).writeFloatBE(Z,Q)}function Ou4($,Z,Q){return h6($).writeFloatLE(Z,Q)}function Lu4($,Z,Q){return h6($).writeInt32BE(Z,Q)}function Du4($,Z,Q){return h6($).writeInt32LE(Z,Q)}function wu4($,Z,Q){return h6($).writeUInt32BE(Z,Q)}function Eu4($,Z,Q){return h6($).writeUInt32LE(Z,Q)}Uq$.exports={isBuffer:yh4,isEncoding:gh4,alloc:hh4,allocUnsafe:uh4,allocUnsafeSlow:ch4,byteLength:lh4,compare:mh4,concat:dh4,copy:ih4,equals:ph4,fill:nh4,from:th4,includes:oh4,indexOf:rh4,lastIndexOf:ah4,swap16:sh4,swap32:eh4,swap64:$u4,toBuffer:h6,toString:Zu4,write:Qu4,readDoubleBE:Xu4,readDoubleLE:Yu4,readFloatBE:Gu4,readFloatLE:Ju4,readInt32BE:Ku4,readInt32LE:Wu4,readUInt32BE:Hu4,readUInt32LE:Fu4,writeDoubleBE:Nu4,writeDoubleLE:Uu4,writeFloatBE:Bu4,writeFloatLE:Ou4,writeInt32BE:Lu4,writeInt32LE:Du4,writeUInt32BE:wu4,writeUInt32LE:Eu4}});var Oq$=v((H6Z,Bq$)=>{var ju4=qu();Bq$.exports=class{constructor(Z){this.encoding=Z}get remaining(){return 0}decode(Z){return ju4.toString(Z,this.encoding)}flush(){return""}}});var Eq$=v((F6Z,wq$)=>{var Lq$=qu();wq$.exports=class{constructor(){this._reset()}get remaining(){return this.bytesSeen}decode(Z){if(Z.byteLength===0)return"";if(this.bytesNeeded===0&&Dq$(Z,0)===0)return this.bytesSeen=zu4(Z),Lq$.toString(Z,"utf8");let Q="",X=0;if(this.bytesNeeded>0){while(X<Z.byteLength){let J=Z[X];if(J<this.lowerBoundary||J>this.upperBoundary){Q+="\uFFFD",this._reset();break}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|J&63,this.bytesSeen++,X++,this.bytesSeen===this.bytesNeeded){Q+=String.fromCodePoint(this.codePoint),this._reset();break}}if(this.bytesNeeded>0)return Q}let Y=Dq$(Z,X),G=Z.byteLength-Y;if(G>X)Q+=Lq$.toString(Z,"utf8",X,G);for(let J=G;J<Z.byteLength;J++){let K=Z[J];if(this.bytesNeeded===0){if(K<=127)this.bytesSeen=0,Q+=String.fromCharCode(K);else if(K>=194&&K<=223)this.bytesNeeded=2,this.bytesSeen=1,this.codePoint=K&31;else if(K>=224&&K<=239){if(K===224)this.lowerBoundary=160;else if(K===237)this.upperBoundary=159;this.bytesNeeded=3,this.bytesSeen=1,this.codePoint=K&15}else if(K>=240&&K<=244){if(K===240)this.lowerBoundary=144;else if(K===244)this.upperBoundary=143;this.bytesNeeded=4,this.bytesSeen=1,this.codePoint=K&7}else this.bytesSeen=1,Q+="\uFFFD";continue}if(K<this.lowerBoundary||K>this.upperBoundary){Q+="\uFFFD",J--,this._reset();continue}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|K&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded)Q+=String.fromCodePoint(this.codePoint),this._reset()}return Q}flush(){let Z=this.bytesNeeded>0?"\uFFFD":"";return this._reset(),Z}_reset(){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191}};function Dq$($,Z){let Q=$.byteLength;if(Q<=Z)return 0;let X=Math.max(Z,Q-4),Y=Q-1;while(Y>X&&($[Y]&192)===128)Y--;if(Y<Z)return 0;let G=$[Y],J;if(G<=127)return 0;if(G>=194&&G<=223)J=2;else if(G>=224&&G<=239)J=3;else if(G>=240&&G<=244)J=4;else return 0;let K=Q-Y;return K<J?K:0}function zu4($){let Z=$.byteLength;if(Z===0)return 0;let Q=$[Z-1];if(Q<=127)return 0;if((Q&192)!==128)return 1;let X=Math.max(0,Z-4),Y=Z-2;while(Y>=X&&($[Y]&192)===128)Y--;if(Y<0)return 1;let G=$[Y],J;if(G>=194&&G<=223)J=2;else if(G>=224&&G<=239)J=3;else if(G>=240&&G<=244)J=4;else return 1;if(Z-Y!==J)return 1;if(J>=3){let K=$[Y+1];if(G===224&&K<160)return 1;if(G===237&&K>159)return 1;if(G===240&&K<144)return 1;if(G===244&&K>143)return 1}return 0}});var zq$=v((N6Z,jq$)=>{var Pu4=Oq$(),Au4=Eq$();jq$.exports=class{constructor(Z="utf8"){switch(this.encoding=Tu4(Z),this.encoding){case"utf8":this.decoder=new Au4;break;case"utf16le":case"base64":throw Error("Unsupported encoding: "+this.encoding);default:this.decoder=new Pu4(this.encoding)}}get remaining(){return this.decoder.remaining}push(Z){if(typeof Z==="string")return Z;return this.decoder.decode(Z)}write(Z){return this.push(Z)}end(Z){let Q="";if(Z)Q=this.push(Z);return Q+=this.decoder.flush(),Q}};function Tu4($){switch($=$.toLowerCase(),$){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return $;default:throw Error("Unknown encoding: "+$)}}});var $91=v((U6Z,_q$)=>{var{EventEmitter:Ru4}=K0("events"),_P0=Error("Stream was destroyed"),o51=Error("Premature close"),Aq$=t51(),Iu4=zq$(),r51=typeof queueMicrotask>"u"?($)=>global.process.nextTick($):queueMicrotask,CP0=Symbol.asyncIterator||Symbol("asyncIterator");class a51{constructor($,{highWaterMark:Z=16384,map:Q=null,mapWritable:X,byteLength:Y,byteLengthWritable:G}={}){this.stream=$,this.queue=new Aq$,this.highWaterMark=Z,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=G||Y||Cq$,this.map=X||Q,this.afterWrite=Vu4.bind(this),this.afterUpdateNextTick=Cu4.bind(this)}get ending(){return(this.stream._duplexState&134217728)!==0}get ended(){return(this.stream._duplexState&8388608)!==0}push($){if((this.stream._duplexState&142606350)!==0)return!1;if(this.map!==null)$=this.map($);if(this.buffered+=this.byteLength($),this.queue.push($),this.buffered<this.highWaterMark)return this.stream._duplexState|=2097152,!0;return this.stream._duplexState|=6291456,!1}shift(){let $=this.queue.shift();if(this.buffered-=this.byteLength($),this.buffered===0)this.stream._duplexState&=534773759;return $}end($){if(typeof $==="function")this.stream.once("finish",$);else if($!==void 0&&$!==null)this.push($);this.stream._duplexState=(this.stream._duplexState|134217728)&535822335}autoBatch($,Z){let Q=[],X=this.stream;Q.push($);while((X._duplexState&270794767)===2359296)Q.push(X._writableState.shift());if((X._duplexState&15)!==0)return Z(null);X._writev(Q,Z)}update(){let $=this.stream;$._duplexState|=524288;do{while(($._duplexState&270794767)===2097152){let Z=this.shift();$._duplexState|=67371008,$._write(Z,this.afterWrite)}if(($._duplexState&1310720)===0)this.updateNonPrimary()}while(this.continueUpdate()===!0);$._duplexState&=536346623}updateNonPrimary(){let $=this.stream;if(($._duplexState&144965647)===134217728){$._duplexState=$._duplexState|262144,$._final(Mu4.bind(this));return}if(($._duplexState&14)===4){if(($._duplexState&33587200)===0)$._duplexState|=262160,$._destroy(qq$.bind(this));return}if(($._duplexState&33587215)===1)$._duplexState=($._duplexState|262160)&536870910,$._open(Mq$.bind(this))}continueUpdate(){if((this.stream._duplexState&33554432)===0)return!1;return this.stream._duplexState&=503316479,!0}updateCallback(){if((this.stream._duplexState&35127311)===1048576)this.update();else this.updateNextTick()}updateNextTick(){if((this.stream._duplexState&33554432)!==0)return;if(this.stream._duplexState|=33554432,(this.stream._duplexState&524288)===0)r51(this.afterUpdateNextTick)}}class Tq${constructor($,{highWaterMark:Z=16384,map:Q=null,mapReadable:X,byteLength:Y,byteLengthReadable:G}={}){this.stream=$,this.queue=new Aq$,this.highWaterMark=Z===0?1:Z,this.buffered=0,this.readAhead=Z>0,this.error=null,this.pipeline=null,this.byteLength=G||Y||Cq$,this.map=X||Q,this.pipeTo=null,this.afterRead=ku4.bind(this),this.afterUpdateNextTick=Su4.bind(this)}get ending(){return(this.stream._duplexState&1024)!==0}get ended(){return(this.stream._duplexState&16384)!==0}pipe($,Z){if(this.pipeTo!==null)throw Error("Can only pipe to one destination");if(typeof Z!=="function")Z=null;if(this.stream._duplexState|=512,this.pipeTo=$,this.pipeline=new Iq$(this.stream,$,Z),Z)this.stream.on("error",Pq$);if(za($)){if($._writableState.pipeline=this.pipeline,Z)$.on("error",Pq$);$.on("finish",this.pipeline.finished.bind(this.pipeline))}else{let Q=this.pipeline.done.bind(this.pipeline,$),X=this.pipeline.done.bind(this.pipeline,$,null);$.on("error",Q),$.on("close",X),$.on("finish",this.pipeline.finished.bind(this.pipeline))}$.on("drain",qu4.bind(this)),this.stream.emit("piping",$),$.emit("pipe",this.stream)}push($){let Z=this.stream;if($===null)return this.highWaterMark=0,Z._duplexState=(Z._duplexState|1024)&536805311,!1;if(this.map!==null){if($=this.map($),$===null)return Z._duplexState&=536805375,this.buffered<this.highWaterMark}return this.buffered+=this.byteLength($),this.queue.push($),Z._duplexState=(Z._duplexState|128)&536805375,this.buffered<this.highWaterMark}shift(){let $=this.queue.shift();if(this.buffered-=this.byteLength($),this.buffered===0)this.stream._duplexState&=536862591;return $}unshift($){let Z=[this.map!==null?this.map($):$];while(this.buffered>0)Z.push(this.shift());for(let Q=0;Q<Z.length-1;Q++){let X=Z[Q];this.buffered+=this.byteLength(X),this.queue.push(X)}this.push(Z[Z.length-1])}read(){let $=this.stream;if(($._duplexState&16527)===128){let Z=this.shift();if(this.pipeTo!==null&&this.pipeTo.write(Z)===!1)$._duplexState&=536870143;if(($._duplexState&2048)!==0)$.emit("data",Z);return Z}if(this.readAhead===!1)$._duplexState|=131072,this.updateNextTick();return null}drain(){let $=this.stream;while(($._duplexState&16527)===128&&($._duplexState&768)!==0){let Z=this.shift();if(this.pipeTo!==null&&this.pipeTo.write(Z)===!1)$._duplexState&=536870143;if(($._duplexState&2048)!==0)$.emit("data",Z)}}update(){let $=this.stream;$._duplexState|=32;do{this.drain();while(this.buffered<this.highWaterMark&&($._duplexState&214047)===131072)$._duplexState|=65552,$._read(this.afterRead),this.drain();if(($._duplexState&12431)===4224)$._duplexState|=8192,$.emit("readable");if(($._duplexState&80)===0)this.updateNonPrimary()}while(this.continueUpdate()===!0);$._duplexState&=536870879}updateNonPrimary(){let $=this.stream;if(($._duplexState&1167)===1024){if($._duplexState=($._duplexState|16384)&536869887,$.emit("end"),($._duplexState&8405006)===8404992)$._duplexState|=4;if(this.pipeTo!==null)this.pipeTo.end()}if(($._duplexState&14)===4){if(($._duplexState&33587200)===0)$._duplexState|=262160,$._destroy(qq$.bind(this));return}if(($._duplexState&33587215)===1)$._duplexState=($._duplexState|262160)&536870910,$._open(Mq$.bind(this))}continueUpdate(){if((this.stream._duplexState&32768)===0)return!1;return this.stream._duplexState&=536838143,!0}updateCallback(){if((this.stream._duplexState&32879)===64)this.update();else this.updateNextTick()}updateNextTickIfOpen(){if((this.stream._duplexState&32769)!==0)return;if(this.stream._duplexState|=32768,(this.stream._duplexState&32)===0)r51(this.afterUpdateNextTick)}updateNextTick(){if((this.stream._duplexState&32768)!==0)return;if(this.stream._duplexState|=32768,(this.stream._duplexState&32)===0)r51(this.afterUpdateNextTick)}}class Rq${constructor($){this.data=null,this.afterTransform=vu4.bind($),this.afterFinal=null}}class Iq${constructor($,Z,Q){this.from=$,this.to=Z,this.afterPipe=Q,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done($,Z){if(Z)this.error=Z;if($===this.to){if(this.to=null,this.from!==null){if((this.from._duplexState&16384)===0||!this.pipeToFinished)this.from.destroy(this.error||Error("Writable stream closed prematurely"));return}}if($===this.from){if(this.from=null,this.to!==null){if(($._duplexState&16384)===0)this.to.destroy(this.error||Error("Readable stream closed before ending"));return}}if(this.afterPipe!==null)this.afterPipe(this.error);this.to=this.from=this.afterPipe=null}}function qu4(){this.stream._duplexState|=512,this.updateCallback()}function Mu4($){let Z=this.stream;if($)Z.destroy($);if((Z._duplexState&14)===0)Z._duplexState|=8388608,Z.emit("finish");if((Z._duplexState&8405006)===8404992)Z._duplexState|=4;if(Z._duplexState&=402391039,(Z._duplexState&524288)===0)this.update();else this.updateNextTick()}function qq$($){let Z=this.stream;if(!$&&this.error!==_P0)$=this.error;if($)Z.emit("error",$);Z._duplexState|=8,Z.emit("close");let{_readableState:Q,_writableState:X}=Z;if(Q!==null&&Q.pipeline!==null)Q.pipeline.done(Z,$);if(X!==null){while(X.drains!==null&&X.drains.length>0)X.drains.shift().resolve(!1);if(X.pipeline!==null)X.pipeline.done(Z,$)}}function Vu4($){let Z=this.stream;if($)Z.destroy($);if(Z._duplexState&=469499903,this.drains!==null)_u4(this.drains);if((Z._duplexState&6553615)===4194304){if(Z._duplexState&=532676607,(Z._duplexState&16777216)===16777216)Z.emit("drain")}this.updateCallback()}function ku4($){if($)this.stream.destroy($);if(this.stream._duplexState&=536870895,this.readAhead===!1&&(this.stream._duplexState&256)===0)this.stream._duplexState&=536739839;this.updateCallback()}function Su4(){if((this.stream._duplexState&32)===0)this.stream._duplexState&=536838143,this.update()}function Cu4(){if((this.stream._duplexState&524288)===0)this.stream._duplexState&=503316479,this.update()}function _u4($){for(let Z=0;Z<$.length;Z++)if(--$[Z].writes===0)$.shift().resolve(!0),Z--}function Mq$($){let Z=this.stream;if($)Z.destroy($);if((Z._duplexState&4)===0){if((Z._duplexState&17423)===0)Z._duplexState|=64;if((Z._duplexState&142606351)===0)Z._duplexState|=1048576;Z.emit("open")}if(Z._duplexState&=536608751,Z._writableState!==null)Z._writableState.updateCallback();if(Z._readableState!==null)Z._readableState.updateCallback()}function vu4($,Z){if(Z!==void 0&&Z!==null)this.push(Z);this._writableState.afterWrite($)}function xu4($){if(this._readableState!==null){if($==="data")this._duplexState|=133376,this._readableState.updateNextTick();if($==="readable")this._duplexState|=4096,this._readableState.updateNextTick()}if(this._writableState!==null){if($==="drain")this._duplexState|=16777216,this._writableState.updateNextTick()}}class vP0 extends Ru4{constructor($){super();if(this._duplexState=0,this._readableState=null,this._writableState=null,$){if($.open)this._open=$.open;if($.destroy)this._destroy=$.destroy;if($.predestroy)this._predestroy=$.predestroy;if($.signal)$.signal.addEventListener("abort",pu4.bind(this))}this.on("newListener",xu4)}_open($){$(null)}_destroy($){$(null)}_predestroy(){}get readable(){return this._readableState!==null?!0:void 0}get writable(){return this._writableState!==null?!0:void 0}get destroyed(){return(this._duplexState&8)!==0}get destroying(){return(this._duplexState&14)!==0}destroy($){if((this._duplexState&14)===0){if(!$)$=_P0;if(this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null)this._readableState.highWaterMark=0,this._readableState.error=$;if(this._writableState!==null)this._writableState.highWaterMark=0,this._writableState.error=$;if(this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null)this._readableState.updateNextTick();if(this._writableState!==null)this._writableState.updateNextTick()}}}class ja extends vP0{constructor($){super($);if(this._duplexState|=8519681,this._readableState=new Tq$(this,$),$){if(this._readableState.readAhead===!1)this._duplexState&=536739839;if($.read)this._read=$.read;if($.eagerOpen)this._readableState.updateNextTick();if($.encoding)this.setEncoding($.encoding)}}setEncoding($){let Z=new Iu4($),Q=this._readableState.map||yu4;return this._readableState.map=X,this;function X(Y){let G=Z.push(Y);return G===""&&(Y.byteLength!==0||Z.remaining>0)?null:Q(G)}}_read($){$(null)}pipe($,Z){return this._readableState.updateNextTick(),this._readableState.pipe($,Z),$}read(){return this._readableState.updateNextTick(),this._readableState.read()}push($){return this._readableState.updateNextTickIfOpen(),this._readableState.push($)}unshift($){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift($)}resume(){return this._duplexState|=131328,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator($,Z){let Q,X=new ja({...Z,read(G){$.next().then(Y).then(G.bind(null,null)).catch(G)},predestroy(){Q=$.return()},destroy(G){if(!Q)return G(null);Q.then(G.bind(null,null)).catch(G)}});return X;function Y(G){if(G.done)X.push(null);else X.push(G.value)}}static from($,Z){if(mu4($))return $;if($[CP0])return this._fromAsyncIterator($[CP0](),Z);if(!Array.isArray($))$=$===void 0?[]:[$];let Q=0;return new ja({...Z,read(X){this.push(Q===$.length?null:$[Q++]),X(null)}})}static isBackpressured($){return($._duplexState&17422)!==0||$._readableState.buffered>=$._readableState.highWaterMark}static isPaused($){return($._duplexState&256)===0}[CP0](){let $=this,Z=null,Q=null,X=null;return this.on("error",(W)=>{Z=W}),this.on("readable",Y),this.on("close",G),{[CP0](){return this},next(){return new Promise(function(W,H){Q=W,X=H;let F=$.read();if(F!==null)J(F);else if(($._duplexState&8)!==0)J(null)})},return(){return K(null)},throw(W){return K(W)}};function Y(){if(Q!==null)J($.read())}function G(){if(Q!==null)J(null)}function J(W){if(X===null)return;if(Z)X(Z);else if(W===null&&($._duplexState&16384)===0)X(_P0);else Q({value:W,done:W===null});X=Q=null}function K(W){return $.destroy(W),new Promise((H,F)=>{if($._duplexState&8)return H({value:void 0,done:!0});$.once("close",function(){if(W)F(W);else H({value:void 0,done:!0})})})}}}class s51 extends vP0{constructor($){super($);if(this._duplexState|=16385,this._writableState=new a51(this,$),$){if($.writev)this._writev=$.writev;if($.write)this._write=$.write;if($.final)this._final=$.final;if($.eagerOpen)this._writableState.updateNextTick()}}cork(){this._duplexState|=268435456}uncork(){this._duplexState&=268435455,this._writableState.updateNextTick()}_writev($,Z){Z(null)}_write($,Z){this._writableState.autoBatch($,Z)}_final($){$(null)}static isBackpressured($){return($._duplexState&146800654)!==0}static drained($){if($.destroyed)return Promise.resolve(!1);let Z=$._writableState,X=(nu4($)?Math.min(1,Z.queue.length):Z.queue.length)+($._duplexState&67108864?1:0);if(X===0)return Promise.resolve(!0);if(Z.drains===null)Z.drains=[];return new Promise((Y)=>{Z.drains.push({writes:X,resolve:Y})})}write($){return this._writableState.updateNextTick(),this._writableState.push($)}end($){return this._writableState.updateNextTick(),this._writableState.end($),this}}class xP0 extends ja{constructor($){super($);if(this._duplexState=1|this._duplexState&131072,this._writableState=new a51(this,$),$){if($.writev)this._writev=$.writev;if($.write)this._write=$.write;if($.final)this._final=$.final}}cork(){this._duplexState|=268435456}uncork(){this._duplexState&=268435455,this._writableState.updateNextTick()}_writev($,Z){Z(null)}_write($,Z){this._writableState.autoBatch($,Z)}_final($){$(null)}write($){return this._writableState.updateNextTick(),this._writableState.push($)}end($){return this._writableState.updateNextTick(),this._writableState.end($),this}}class e51 extends xP0{constructor($){super($);if(this._transformState=new Rq$(this),$){if($.transform)this._transform=$.transform;if($.flush)this._flush=$.flush}}_write($,Z){if(this._readableState.buffered>=this._readableState.highWaterMark)this._transformState.data=$;else this._transform($,this._transformState.afterTransform)}_read($){if(this._transformState.data!==null){let Z=this._transformState.data;this._transformState.data=null,$(null),this._transform(Z,this._transformState.afterTransform)}else $(null)}destroy($){if(super.destroy($),this._transformState.data!==null)this._transformState.data=null,this._transformState.afterTransform()}_transform($,Z){Z(null,$)}_flush($){$(null)}_final($){this._transformState.afterFinal=$,this._flush(fu4.bind(this))}}class Vq$ extends e51{}function fu4($,Z){let Q=this._transformState.afterFinal;if($)return Q($);if(Z!==null&&Z!==void 0)this.push(Z);this.push(null),Q(null)}function bu4(...$){return new Promise((Z,Q)=>{return kq$(...$,(X)=>{if(X)return Q(X);Z()})})}function kq$($,...Z){let Q=Array.isArray($)?[...$,...Z]:[$,...Z],X=Q.length&&typeof Q[Q.length-1]==="function"?Q.pop():null;if(Q.length<2)throw Error("Pipeline requires at least 2 streams");let Y=Q[0],G=null,J=null;for(let H=1;H<Q.length;H++){if(G=Q[H],za(Y))Y.pipe(G,W);else K(Y,!0,H>1,W),Y.pipe(G);Y=G}if(X){let H=!1,F=za(G)||!!(G._writableState&&G._writableState.autoDestroy);if(G.on("error",(N)=>{if(J===null)J=N}),G.on("finish",()=>{if(H=!0,!F)X(J)}),F)G.on("close",()=>X(J||(H?null:o51)))}return G;function K(H,F,N,U){H.on("error",U),H.on("close",B);function B(){if(F&&H._readableState&&!H._readableState.ended)return U(o51);if(N&&H._writableState&&!H._writableState.ended)return U(o51)}}function W(H){if(!H||J)return;J=H;for(let F of Q)F.destroy(H)}}function yu4($){return $}function Sq$($){return!!$._readableState||!!$._writableState}function za($){return typeof $._duplexState==="number"&&Sq$($)}function gu4($){return!!$._readableState&&$._readableState.ending}function hu4($){return!!$._readableState&&$._readableState.ended}function uu4($){return!!$._writableState&&$._writableState.ending}function cu4($){return!!$._writableState&&$._writableState.ended}function lu4($,Z={}){let Q=$._readableState&&$._readableState.error||$._writableState&&$._writableState.error;return!Z.all&&Q===_P0?null:Q}function mu4($){return za($)&&$.readable}function du4($){return($._duplexState&1)!==1||($._duplexState&4)===4||($._duplexState&33587200)!==0}function iu4($){return typeof $==="object"&&$!==null&&typeof $.byteLength==="number"}function Cq$($){return iu4($)?$.byteLength:1024}function Pq$(){}function pu4(){this.destroy(Error("Stream aborted."))}function nu4($){return $._writev!==s51.prototype._writev&&$._writev!==xP0.prototype._writev}_q$.exports={pipeline:kq$,pipelinePromise:bu4,isStream:Sq$,isStreamx:za,isEnding:gu4,isEnded:hu4,isFinishing:uu4,isFinished:cu4,isDisturbed:du4,getStreamError:lu4,Stream:vP0,Writable:s51,Readable:ja,Duplex:xP0,Transform:e51,PassThrough:Vq$}});var Q91=v((Gc4)=>{var c4=qu(),vq$=c4.from([117,115,116,97,114,0]),tu4=c4.from([48,48]),ou4=c4.from([117,115,116,97,114,32]),ru4=c4.from([32,0]);Gc4.decodeLongPath=function(Z,Q){return Mu(Z,0,Z.length,Q)};Gc4.encodePax=function(Z){let Q="";if(Z.name)Q+=Z91(" path="+Z.name+`
2369
2369
  `);if(Z.linkname)Q+=Z91(" linkpath="+Z.linkname+`
2370
2370
  `);let X=Z.pax;if(X)for(let Y in X)Q+=Z91(" "+Y+"="+X[Y]+`
2371
- `);return c4.from(Q)};Gc4.decodePax=function(Z){let Q={};while(Z.length){let X=0;while(X<Z.length&&Z[X]!==32)X++;let Y=parseInt(c4.toString(Z.subarray(0,X)),10);if(!Y)return Q;let G=c4.toString(Z.subarray(X+1,Y-1)),J=G.indexOf("=");if(J===-1)return Q;Q[G.slice(0,J)]=G.slice(J+1),Z=Z.subarray(Y)}return Q};Gc4.encode=function(Z){let Q=c4.alloc(512),X=Z.name,Y="";if(Z.typeflag===5&&X[X.length-1]!=="/")X+="/";if(c4.byteLength(X)!==X.length)return null;while(c4.byteLength(X)>100){let G=X.indexOf("/");if(G===-1)return null;Y+=Y?"/"+X.slice(0,G):X.slice(0,G),X=X.slice(G+1)}if(c4.byteLength(X)>100||c4.byteLength(Y)>155)return null;if(Z.linkname&&c4.byteLength(Z.linkname)>100)return null;if(c4.write(Q,X),c4.write(Q,OD(Z.mode&4095,6),100),c4.write(Q,OD(Z.uid,6),108),c4.write(Q,OD(Z.gid,6),116),Xc4(Z.size,Q,124),c4.write(Q,OD(Z.mtime.getTime()/1000|0,11),136),Q[156]=48+Zc4(Z.type),Z.linkname)c4.write(Q,Z.linkname,157);if(c4.copy(vq$,Q,257),c4.copy(tu4,Q,263),Z.uname)c4.write(Q,Z.uname,265);if(Z.gname)c4.write(Q,Z.gname,297);if(c4.write(Q,OD(Z.devmajor||0,6),329),c4.write(Q,OD(Z.devminor||0,6),337),Y)c4.write(Q,Y,345);return c4.write(Q,OD(fq$(Q),6),148),Q};Gc4.decode=function(Z,Q,X){let Y=Z[156]===0?0:Z[156]-48,G=Mu(Z,0,100,Q),J=BD(Z,100,8),K=BD(Z,108,8),W=BD(Z,116,8),H=BD(Z,124,12),F=BD(Z,136,12),N=$c4(Y),U=Z[157]===0?null:Mu(Z,157,100,Q),B=Mu(Z,265,32),O=Mu(Z,297,32),D=BD(Z,329,8),w=BD(Z,337,8),E=fq$(Z);if(E===256)return null;if(E!==BD(Z,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(au4(Z)){if(Z[345])G=Mu(Z,345,155,Q)+"/"+G}else if(su4(Z));else if(!X)throw Error("Invalid tar header: unknown format.");if(Y===0&&G&&G[G.length-1]==="/")Y=5;return{name:G,mode:J,uid:K,gid:W,size:H,mtime:new Date(1000*F),type:N,linkname:U,uname:B,gname:O,devmajor:D,devminor:w,pax:null}};function au4($){return c4.equals(vq$,$.subarray(257,263))}function su4($){return c4.equals(ou4,$.subarray(257,263))&&c4.equals(ru4,$.subarray(263,265))}function eu4($,Z,Q){if(typeof $!=="number")return Q;if($=~~$,$>=Z)return Z;if($>=0)return $;if($+=Z,$>=0)return $;return 0}function $c4($){switch($){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function Zc4($){switch($){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function xq$($,Z,Q,X){for(;Q<X;Q++)if($[Q]===Z)return Q;return X}function fq$($){let Z=256;for(let Q=0;Q<148;Q++)Z+=$[Q];for(let Q=156;Q<512;Q++)Z+=$[Q];return Z}function OD($,Z){if($=$.toString(8),$.length>Z)return"7777777777777777777".slice(0,Z)+" ";return"0000000000000000000".slice(0,Z-$.length)+$+" "}function Qc4($,Z,Q){Z[Q]=128;for(let X=11;X>0;X--)Z[Q+X]=$&255,$=Math.floor($/256)}function Xc4($,Z,Q){if($.toString(8).length>11)Qc4($,Z,Q);else c4.write(Z,OD($,11),Q)}function Yc4($){let Z;if($[0]===128)Z=!0;else if($[0]===255)Z=!1;else return null;let Q=[],X;for(X=$.length-1;X>0;X--){let J=$[X];if(Z)Q.push(J);else Q.push(255-J)}let Y=0,G=Q.length;for(X=0;X<G;X++)Y+=Q[X]*Math.pow(256,X);return Z?Y:-1*Y}function BD($,Z,Q){if($=$.subarray(Z,Z+Q),Z=0,$[Z]&128)return Yc4($);else{while(Z<$.length&&$[Z]===32)Z++;let X=eu4(xq$($,32,Z,$.length),$.length,$.length);while(Z<X&&$[Z]===0)Z++;if(X===Z)return 0;return parseInt(c4.toString($.subarray(Z,X)),8)}}function Mu($,Z,Q,X){return c4.toString($.subarray(Z,xq$($,0,Z,Z+Q)),X)}function Z91($){let Z=c4.byteLength($),Q=Math.floor(Math.log(Z)/Math.log(10))+1;if(Z+Q>=Math.pow(10,Q))Q++;return Z+Q+$}});var mq$=v((O6Z,lq$)=>{var{Writable:Nc4,Readable:Uc4,getStreamError:bq$}=$91(),Bc4=t51(),yq$=qu(),Vu=Q91(),Oc4=yq$.alloc(0);class gq${constructor(){this.buffered=0,this.shifted=0,this.queue=new Bc4,this._offset=0}push($){this.buffered+=$.byteLength,this.queue.push($)}shiftFirst($){return this._buffered===0?null:this._next($)}shift($){if($>this.buffered)return null;if($===0)return Oc4;let Z=this._next($);if($===Z.byteLength)return Z;let Q=[Z];while(($-=Z.byteLength)>0)Z=this._next($),Q.push(Z);return yq$.concat(Q)}_next($){let Z=this.queue.peek(),Q=Z.byteLength-this._offset;if($>=Q){let X=this._offset?Z.subarray(this._offset,Z.byteLength):Z;return this.queue.shift(),this._offset=0,this.buffered-=Q,this.shifted+=Q,X}return this.buffered-=$,this.shifted+=$,Z.subarray(this._offset,this._offset+=$)}}class hq$ extends Uc4{constructor($,Z,Q){super();this.header=Z,this.offset=Q,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(bq$(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=cq$(this.header.size),this._parent._update()}_destroy($){this._detach(),$(null)}}class uq$ extends Nc4{constructor($){super($);if(!$)$={};this._buffer=new gq$,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=X91,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=$.filenameEncoding||"utf-8",this._allowUnknownFormat=!!$.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock($){if(this._locked=!1,$){this.destroy($),this._continueWrite($);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=Vu.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch($){return this._continueWrite($),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}if(this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory")return this.emit("entry",this._header,this._createStream(),this._unlockBound),!0;return this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0}_applyLongHeaders(){if(this._gnuLongPath)this._header.name=this._gnuLongPath,this._gnuLongPath=null;if(this._gnuLongLinkPath)this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null;if(this._pax){if(this._pax.path)this._header.name=this._pax.path;if(this._pax.linkpath)this._header.linkname=this._pax.linkpath;if(this._pax.size)this._header.size=parseInt(this._pax.size,10);this._header.pax=this._pax,this._pax=null}}_decodeLongHeader($){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=Vu.decodeLongPath($,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=Vu.decodeLongPath($,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=Vu.decodePax($);break;case"pax-header":this._pax=this._paxGlobal===null?Vu.decodePax($):Object.assign({},this._paxGlobal,Vu.decodePax($));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=cq$(this._header.size);let $=this._buffer.shift(this._header.size);try{this._decodeLongHeader($)}catch(Z){return this._continueWrite(Z),!1}return!0}_consumeStream(){let $=this._buffer.shiftFirst(this._missing);if($===null)return!1;this._missing-=$.byteLength;let Z=this._stream.push($);if(this._missing===0){if(this._stream.push(null),Z)this._stream._detach();return Z&&this._locked===!1}return Z}_createStream(){return new hq$(this,this._header,this._offset)}_update(){while(this._buffer.buffered>0&&!this.destroying){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let $=this._buffer.shiftFirst(this._missing);if($!==null)this._missing-=$.byteLength;continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite($){let Z=this._callback;this._callback=X91,Z($)}_write($,Z){this._callback=Z,this._buffer.push($),this._update()}_final($){this._finished=this._missing===0&&this._buffer.buffered===0,$(this._finished?null:Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy($){if(this._stream)this._stream.destroy(bq$(this));$(null)}[Symbol.asyncIterator](){let $=null,Z=null,Q=null,X=null,Y=null,G=this;return this.on("entry",W),this.on("error",(N)=>{$=N}),this.on("close",H),{[Symbol.asyncIterator](){return this},next(){return new Promise(K)},return(){return F(null)},throw(N){return F(N)}};function J(N){if(!Y)return;let U=Y;Y=null,U(N)}function K(N,U){if($)return U($);if(X){N({value:X,done:!1}),X=null;return}if(Z=N,Q=U,J(null),G._finished&&Z)Z({value:void 0,done:!0}),Z=Q=null}function W(N,U,B){if(Y=B,U.on("error",X91),Z)Z({value:U,done:!1}),Z=Q=null;else X=U}function H(){if(J($),!Z)return;if($)Q($);else Z({value:void 0,done:!0});Z=Q=null}function F(N){return G.destroy(N),J(N),new Promise((U,B)=>{if(G.destroyed)return U({value:void 0,done:!0});G.once("close",function(){if(N)B(N);else U({value:void 0,done:!0})})})}}}lq$.exports=function(Z){return new uq$(Z)};function X91(){}function cq$($){return $&=511,$&&512-$}});var iq$=v((L6Z,Y91)=>{var dq$={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{Y91.exports=K0("fs").constants||dq$}catch{Y91.exports=dq$}});var sq$=v((D6Z,aq$)=>{var{Readable:Lc4,Writable:Dc4,getStreamError:pq$}=$91(),Hv=qu(),ku=iq$(),fP0=Q91(),nq$=Hv.alloc(1024);class tq$ extends Dc4{constructor($,Z,Q){super({mapWritable:Ec4,eagerOpen:!0});if(this.written=0,this.header=Z,this._callback=Q,this._linkname=null,this._isLinkname=Z.type==="symlink"&&!Z.linkname,this._isVoid=Z.type!=="file"&&Z.type!=="contiguous-file",this._finished=!1,this._pack=$,this._openCallback=null,this._pack._stream===null)this._pack._stream=this;else this._pack._pending.push(this)}_open($){if(this._openCallback=$,this._pack._stream===this)this._continueOpen()}_continuePack($){if(this._callback===null)return;let Z=this._callback;this._callback=null,Z($)}_continueOpen(){if(this._pack._stream===null)this._pack._stream=this;let $=this._openCallback;if(this._openCallback=null,$===null)return;if(this._pack.destroying)return $(Error("pack stream destroyed"));if(this._pack._finalized)return $(Error("pack stream is already finalized"));if(this._pack._stream=this,!this._isLinkname)this._pack._encode(this.header);if(this._isVoid)this._finish(),this._continuePack(null);$(null)}_write($,Z){if(this._isLinkname)return this._linkname=this._linkname?Hv.concat([this._linkname,$]):$,Z(null);if(this._isVoid){if($.byteLength>0)return Z(Error("No body allowed for this entry"));return Z()}if(this.written+=$.byteLength,this._pack.push($))return Z();this._pack._drain=Z}_finish(){if(this._finished)return;if(this._finished=!0,this._isLinkname)this.header.linkname=this._linkname?Hv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);rq$(this._pack,this.header.size),this._pack._done(this)}_final($){if(this.written!==this.header.size)return $(Error("Size mismatch"));this._finish(),$(null)}_getError(){return pq$(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy($){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),$()}}class oq$ extends Lc4{constructor($){super($);this._drain=G91,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry($,Z,Q){if(this._finalized||this.destroying)throw Error("already finalized or destroyed");if(typeof Z==="function")Q=Z,Z=null;if(!Q)Q=G91;if(!$.size||$.type==="symlink")$.size=0;if(!$.type)$.type=wc4($.mode);if(!$.mode)$.mode=$.type==="directory"?493:420;if(!$.uid)$.uid=0;if(!$.gid)$.gid=0;if(!$.mtime)$.mtime=new Date;if(typeof Z==="string")Z=Hv.from(Z);let X=new tq$(this,$,Q);if(Hv.isBuffer(Z))return $.size=Z.byteLength,X.write(Z),X.end(),X;if(X._isVoid)return X;return X}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}if(this._finalized)return;this._finalized=!0,this.push(nq$),this.push(null)}_done($){if($!==this._stream)return;if(this._stream=null,this._finalizing)this.finalize();if(this._pending.length)this._pending.shift()._continueOpen()}_encode($){if(!$.pax){let Z=fP0.encode($);if(Z){this.push(Z);return}}this._encodePax($)}_encodePax($){let Z=fP0.encodePax({name:$.name,linkname:$.linkname,pax:$.pax}),Q={name:"PaxHeader",mode:$.mode,uid:$.uid,gid:$.gid,size:Z.byteLength,mtime:$.mtime,type:"pax-header",linkname:$.linkname&&"PaxHeader",uname:$.uname,gname:$.gname,devmajor:$.devmajor,devminor:$.devminor};this.push(fP0.encode(Q)),this.push(Z),rq$(this,Z.byteLength),Q.size=$.size,Q.type=$.type,this.push(fP0.encode(Q))}_doDrain(){let $=this._drain;this._drain=G91,$()}_predestroy(){let $=pq$(this);if(this._stream)this._stream.destroy($);while(this._pending.length){let Z=this._pending.shift();Z.destroy($),Z._continueOpen()}this._doDrain()}_read($){this._doDrain(),$()}}aq$.exports=function(Z){return new oq$(Z)};function wc4($){switch($&ku.S_IFMT){case ku.S_IFBLK:return"block-device";case ku.S_IFCHR:return"character-device";case ku.S_IFDIR:return"directory";case ku.S_IFIFO:return"fifo";case ku.S_IFLNK:return"symlink"}return"file"}function G91(){}function rq$($,Z){if(Z&=511,Z)$.push(nq$.subarray(0,512-Z))}function Ec4($){return Hv.isBuffer($)?$:Hv.from($)}});var eq$=v((jc4)=>{jc4.extract=mq$();jc4.pack=sq$()});var QM$=v((E6Z,ZM$)=>{ZM$.exports=$M$;function $M$($,Z){if($&&Z)return $M$($)(Z);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(X){Q[X]=$[X]}),Q;function Q(){var X=Array(arguments.length);for(var Y=0;Y<X.length;Y++)X[Y]=arguments[Y];var G=$.apply(this,X),J=X[X.length-1];if(typeof G==="function"&&G!==J)Object.keys(J).forEach(function(K){G[K]=J[K]});return G}}});var K91=v((j6Z,J91)=>{var XM$=QM$();J91.exports=XM$(bP0);J91.exports.strict=XM$(YM$);bP0.proto=bP0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return bP0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return YM$(this)},configurable:!0})});function bP0($){var Z=function(){if(Z.called)return Z.value;return Z.called=!0,Z.value=$.apply(this,arguments)};return Z.called=!1,Z}function YM$($){var Z=function(){if(Z.called)throw Error(Z.onceError);return Z.called=!0,Z.value=$.apply(this,arguments)},Q=$.name||"Function wrapped with `once`";return Z.onceError=Q+" shouldn't be called more than once",Z.called=!1,Z}});var KM$=v((z6Z,JM$)=>{var Ac4=K91(),Tc4=function(){},Rc4=global.Bare?queueMicrotask:process.nextTick.bind(process),Ic4=function($){return $.setHeader&&typeof $.abort==="function"},qc4=function($){return $.stdio&&Array.isArray($.stdio)&&$.stdio.length===3},GM$=function($,Z,Q){if(typeof Z==="function")return GM$($,null,Z);if(!Z)Z={};Q=Ac4(Q||Tc4);var{_writableState:X,_readableState:Y}=$,G=Z.readable||Z.readable!==!1&&$.readable,J=Z.writable||Z.writable!==!1&&$.writable,K=!1,W=function(){if(!$.writable)H()},H=function(){if(J=!1,!G)Q.call($)},F=function(){if(G=!1,!J)Q.call($)},N=function(w){Q.call($,w?Error("exited with error code: "+w):null)},U=function(w){Q.call($,w)},B=function(){Rc4(O)},O=function(){if(K)return;if(G&&!(Y&&(Y.ended&&!Y.destroyed)))return Q.call($,Error("premature close"));if(J&&!(X&&(X.ended&&!X.destroyed)))return Q.call($,Error("premature close"))},D=function(){$.req.on("finish",H)};if(Ic4($))if($.on("complete",H),$.on("abort",B),$.req)D();else $.on("request",D);else if(J&&!X)$.on("end",W),$.on("close",W);if(qc4($))$.on("exit",N);if($.on("end",F),$.on("finish",H),Z.error!==!1)$.on("error",U);return $.on("close",B),function(){if(K=!0,$.removeListener("complete",H),$.removeListener("abort",B),$.removeListener("request",D),$.req)$.req.removeListener("finish",H);$.removeListener("end",W),$.removeListener("close",W),$.removeListener("finish",H),$.removeListener("exit",N),$.removeListener("end",F),$.removeListener("error",U),$.removeListener("close",B)}};JM$.exports=GM$});var FM$=v((P6Z,HM$)=>{var Mc4=K91(),Vc4=KM$(),yP0;try{yP0=K0("fs")}catch($){}var Pa=function(){},kc4=typeof process>"u"?!1:/^v?\.0/.test(process.version),gP0=function($){return typeof $==="function"},Sc4=function($){if(!kc4)return!1;if(!yP0)return!1;return($ instanceof(yP0.ReadStream||Pa)||$ instanceof(yP0.WriteStream||Pa))&&gP0($.close)},Cc4=function($){return $.setHeader&&gP0($.abort)},_c4=function($,Z,Q,X){X=Mc4(X);var Y=!1;$.on("close",function(){Y=!0}),Vc4($,{readable:Z,writable:Q},function(J){if(J)return X(J);Y=!0,X()});var G=!1;return function(J){if(Y)return;if(G)return;if(G=!0,Sc4($))return $.close(Pa);if(Cc4($))return $.abort();if(gP0($.destroy))return $.destroy();X(J||Error("stream was destroyed"))}},WM$=function($){$()},vc4=function($,Z){return $.pipe(Z)},xc4=function(){var $=Array.prototype.slice.call(arguments),Z=gP0($[$.length-1]||Pa)&&$.pop()||Pa;if(Array.isArray($[0]))$=$[0];if($.length<2)throw Error("pump requires two streams per minimum");var Q,X=$.map(function(Y,G){var J=G<$.length-1,K=G>0;return _c4(Y,J,K,function(W){if(!Q)Q=W;if(W)X.forEach(WM$);if(J)return;X.forEach(WM$),Z(Q)})});return $.reduce(vc4)};HM$.exports=xc4});var jM$=v((gc4)=>{var NM$=eq$(),UM$=FM$(),BM$=K0("fs"),E9=K0("path"),Aa=(global.Bare?global.Bare.platform:process.platform)==="win32";gc4.pack=function(Z,Q){if(!Z)Z=".";if(!Q)Q={};let X=Q.fs||BM$,Y=Q.ignore||Q.filter||Ta,G=Q.mapStream||wM$,J=yc4(X,Q.dereference?X.stat:X.lstat,Z,Y,Q.entries,Q.sort),K=Q.strict!==!1,W=typeof Q.umask==="number"?~Q.umask:~OM$(),H=Q.pack||NM$.pack(),F=Q.finish||Ta,N=Q.map||Ta,U=typeof Q.dmode==="number"?Q.dmode:0,B=typeof Q.fmode==="number"?Q.fmode:0;if(Q.strip)N=EM$(N,Q.strip);if(Q.readable)U|=parseInt(555,8),B|=parseInt(444,8);if(Q.writable)U|=parseInt(333,8),B|=parseInt(222,8);w();function O(E,j){X.readlink(E9.join(Z,E),function(z,A){if(z)return H.destroy(z);j.linkname=W91(A),H.entry(j,w)})}function D(E,j,z){if(H.destroyed)return;if(E)return H.destroy(E);if(!j){if(Q.finalize!==!1)H.finalize();return F(H)}if(z.isSocket())return w();let A={name:W91(j),mode:(z.mode|(z.isDirectory()?U:B))&W,mtime:z.mtime,size:z.size,type:"file",uid:z.uid,gid:z.gid};if(z.isDirectory())return A.size=0,A.type="directory",A=N(A)||A,H.entry(A,w);if(z.isSymbolicLink())return A.size=0,A.type="symlink",A=N(A)||A,O(j,A);if(A=N(A)||A,!z.isFile()){if(K)return H.destroy(Error("unsupported type for "+j));return w()}let P=H.entry(A,w),I=G(X.createReadStream(E9.join(Z,j),{start:0,end:A.size>0?A.size-1:A.size}),A);I.on("error",function(q){P.destroy(q)}),UM$(I,P)}function w(E){if(E)return H.destroy(E);J(D)}return H};function fc4($){return $.length?$[$.length-1]:null}function bc4(){return!global.Bare&&process.getuid?process.getuid():-1}function OM$(){return!global.Bare&&process.umask?process.umask():0}gc4.extract=function(Z,Q){if(!Z)Z=".";if(!Q)Q={};Z=E9.resolve(Z);let X=Q.fs||BM$,Y=Q.ignore||Q.filter||Ta,G=Q.mapStream||wM$,J=Q.chown!==!1&&!Aa&&bc4()===0,K=Q.extract||NM$.extract(),W=[],H=new Date,F=typeof Q.umask==="number"?~Q.umask:~OM$(),N=Q.strict!==!1,U=Q.validateSymlinks!==!1,B=Q.map||Ta,O=typeof Q.dmode==="number"?Q.dmode:0,D=typeof Q.fmode==="number"?Q.fmode:0;if(Q.strip)B=EM$(B,Q.strip);if(Q.readable)O|=parseInt(555,8),D|=parseInt(444,8);if(Q.writable)O|=parseInt(333,8),D|=parseInt(222,8);if(K.on("entry",w),Q.finish)K.on("finish",Q.finish);return K;function w(P,I,q){P=B(P)||P,P.name=W91(P.name);let M=E9.join(Z,E9.join("/",P.name));if(Y(M,P))return I.resume(),q();let S=E9.join(M,".")===E9.join(Z,".")?Z:E9.dirname(M);DM$(X,S,E9.join(Z,"."),function(p,Y0){if(p)return q(p);if(!Y0)return q(Error(S+" is not a valid path"));if(P.type==="directory")return W.push([M,P.mtime]),A(M,{fs:X,own:J,uid:P.uid,gid:P.gid,mode:P.mode},m);A(S,{fs:X,own:J,uid:P.uid,gid:P.gid,mode:493},function(L0){if(L0)return q(L0);switch(P.type){case"file":return y();case"link":return b();case"symlink":return f()}if(N)return q(Error("unsupported type for "+M+" ("+P.type+")"));I.resume(),q()})});function m(p){if(p)return q(p);j(M,P,function(Y0){if(Y0)return q(Y0);if(Aa)return q();z(M,P,q)})}function f(){if(Aa)return q();X.unlink(M,function(){let p=E9.resolve(E9.dirname(M),P.linkname);if(!l(p)&&U)return q(Error(M+" is not a valid symlink"));LM$(X,p,E9.join(Z,"."),function(Y0,L0){if(Y0)return q(Y0);if(!L0&&U)return q(Error(M+" is not a valid symlink"));X.symlink(P.linkname,M,m)})})}function b(){if(Aa)return q();X.unlink(M,function(){let p=E9.join(Z,E9.join("/",P.linkname));X.realpath(p,function(Y0,L0){if(Y0||!l(L0))return q(Error(M+" is not a valid hardlink"));X.link(L0,M,function(r){if(r&&r.code==="EPERM"&&Q.hardlinkAsFilesFallback)return I=X.createReadStream(L0),y();m(r)})})})}function l(p){return p===Z||p.startsWith(Z+E9.sep)}function y(){let p=X.createWriteStream(M),Y0=G(I,P);p.on("error",function(L0){Y0.destroy(L0)}),UM$(Y0,p,function(L0){if(L0)return q(L0);p.on("close",m)})}}function E(P,I){let q;while((q=fc4(W))&&P.slice(0,q[0].length)!==q[0])W.pop();if(!q)return I();X.utimes(q[0],H,q[1],I)}function j(P,I,q){if(Q.utimes===!1)return q();if(I.type==="directory")return X.utimes(P,H,I.mtime,q);if(I.type==="symlink")return E(P,q);X.utimes(P,H,I.mtime,function(M){if(M)return q(M);E(P,q)})}function z(P,I,q){let M=I.type==="symlink",S=M?X.lchmod:X.chmod,m=M?X.lchown:X.chown;if(!S)return q();let f=(I.mode|(I.type==="directory"?O:D))&F;if(m&&J)m.call(X,P,I.uid,I.gid,b);else b(null);function b(l){if(l)return q(l);if(!S)return q();S.call(X,P,f,q)}}function A(P,I,q){X.stat(P,function(M){if(!M)return q(null);if(M.code!=="ENOENT")return q(M);X.mkdir(P,{mode:I.mode,recursive:!0},function(S,m){if(S)return q(S);z(P,I,q)})})}};function LM$($,Z,Q,X){if(Z===Q)return X(null,!0);if(!Z.startsWith(Q+E9.sep))return X(null,!1);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return X(Y);if(Y||!G.isSymbolicLink())return LM$($,E9.join(Z,".."),Q,X);X(null,!1)})}function DM$($,Z,Q,X){if(Z===Q)return X(null,!0);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return X(Y);if(Y||G.isDirectory())return DM$($,E9.join(Z,".."),Q,X);X(null,!1)})}function Ta(){}function wM$($){return $}function W91($){return Aa?$.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):$}function yc4($,Z,Q,X,Y,G){if(!Y)Y=["."];let J=Y.slice(0);return function(W){if(!J.length)return W(null);let H=J.shift(),F=E9.join(Q,H);Z.call($,F,function(N,U){if(N)return W(Y.indexOf(H)===-1&&N.code==="ENOENT"?null:N);if(!U.isDirectory())return W(null,H,U);$.readdir(F,function(B,O){if(B)return W(B);if(G)O.sort();for(let D=0;D<O.length;D++)if(!X(E9.join(Q,H,O[D])))J.push(E9.join(H,O[D]));W(null,H,U)})})}}function EM$($,Z){return function(Q){Q.name=Q.name.split("/").slice(Z).join("/");let X=Q.linkname;if(X&&(Q.type==="link"||E9.isAbsolute(X)))Q.linkname=X.split("/").slice(Z).join("/");return $(Q)}}});var cc4,lc4;var zM$=L(()=>{p51();cc4=k(Kq$(),1),lc4=k(jM$(),1)});var hP0=()=>{};var PM$=L(()=>{sz0()});var AM$=L(()=>{qP0();IP0();hP0()});var TM$=()=>{};var RM$=()=>{};var IM$=L(()=>{lI$();d51();qP0();nI$();l51();p51();tI$();oI$();rI$();aI$();m51();sI$();zM$();hP0();PM$();AM$();TM$();RM$();hP0()});var uP0=L(()=>{J4();n41()});async function lP0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(mc4)});if(!Z.ok)return null;let Q=await Z.json();if(typeof Q==="object"&&Q!==null&&typeof Q.bootId==="string"&&typeof Q.ready==="boolean"&&Q.setup&&typeof Q.setup.running==="boolean"&&typeof Q.setup.done==="boolean")return Q;return null}catch{return null}}async function F91($){for(let Z=0;Z<qM$;Z++){if(await lP0($)!==null)return;let Q=(Math.random()*2-1)*dc4;await W$(MM$+Q)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${qM$*MM$/1000}s`)}async function Fv($,Z,Q,X,Y){return ic4($,Z,"POST",Q,X,Y)}async function ic4($,Z,Q,X,Y,G){let J={...X};if(Y&&Y.rotateToken!==void 0)J.auth=Y;let K=await fetch(`${$}/_sandbox/config`,{method:Q,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify(J),signal:AbortSignal.timeout(G?.timeoutMs??H91)}),W=await K.text();if(!K.ok)throw new cP0(K.status,W);return JSON.parse(W)}async function VM$($,Z,Q){let X=await fetch(`${$}/_sandbox/setup/${Q}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(H91)});if(!X.ok)throw Error(`sandbox daemon /_sandbox/setup/${Q} returned ${X.status}: ${await X.text()}`)}async function kM$($,Z,Q){let X=await fetch(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:Q,signal:AbortSignal.timeout(H91)}),Y=await X.text();if(!X.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${X.status}: ${Y}`);return JSON.parse(Y)}async function Ra($,Z,Q,X){let Y=new Headers(X.headers);for(let K of pc4)Y.delete(K);Y.set("authorization",`Bearer ${Z}`);let G=X.method!=="GET"&&X.method!=="HEAD",J=`${$}${Q.startsWith("/")?Q:`/${Q}`}`;return fetch(J,{method:X.method,headers:Y,body:G?X.body:void 0,redirect:"manual",signal:X.signal,duplex:G?"half":void 0})}var cP0,mc4=500,H91=30000,qM$=25,MM$=200,dc4=50,pc4;var SM$=L(()=>{uP0();cP0=class cP0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};pc4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*vM$($){let Z=$.now??(()=>Date.now()),Q=Z(),X=$.schedulingTimeoutMs??tc4,Y={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:Q},G=[],J=null,K=!1,W=(j)=>{if(K)return;if(J){let z=J;J=null,z(j)}else G.push(j)},H=()=>{if(G.length>0)return Promise.resolve(G.shift());if(K)return Promise.resolve(null);return new Promise((j)=>{J=j})},F=()=>{if(K)return;if(K=!0,J){let j=J;J=null,j(null)}},N=new AbortController,U=()=>{N.abort(),F()};if($.signal)if($.signal.aborted)N.abort(),F();else $.signal.addEventListener("abort",U,{once:!0});let B=Math.max(0,X-(Z()-Q)),O=setTimeout(()=>W("tick"),B+100),D,w=new Promise((j)=>{D=j}),E=Promise.allSettled([oc4($.kc,$.namespace,$.claimName,N.signal,Y,W,Z,D),ac4($.kc,$.namespace,$.claimName,N.signal,Y,W),sc4($.kc,$.namespace,$.claimName,w,N.signal,Y,W,Z)]);try{let j=null,z=-1,A=CM$(Y,X,Z);if(j=U91(A),!N91(A))z=_M$(A);if(yield A,N91(A))return;while(!K){if(await H()===null)break;let I=CM$(Y,X,Z);if(N91(I)){let S=U91(I);if(S!==j)j=S,yield I;return}let q=_M$(I);if(q<z)continue;let M=U91(I);if(M!==j)j=M,z=q,yield I}}finally{if(clearTimeout(O),N.abort(),$.signal)$.signal.removeEventListener("abort",U);F(),await E.catch(()=>{})}}function CM$($,Z,Q){let{pod:X,sandbox:Y,events:G,startedAt:J}=$;if(Y.ready)return{kind:"ready"};let K=X.containerWaitingReason;if(K==="ImagePullBackOff"||K==="ErrImagePull")return{kind:"failed",reason:"image-pull-backoff",message:"Sandbox image failed to download. The cluster may be missing pull credentials or the image tag may not exist."};if(K==="CrashLoopBackOff")return{kind:"failed",reason:"crash-loop-backoff",message:"Sandbox crashed during startup and is now in CrashLoopBackOff. Check pod logs."};if(!X.scheduled&&G.lastFailedSchedulingAt!==void 0&&Q()-J>Z)return{kind:"failed",reason:"scheduling-timeout",message:G.failedSchedulingMessage??`Pod could not be scheduled within ${Math.round(Z/1000)}s.`};if(X.containerRunning&&!X.containerReady)return{kind:"warming-daemon",since:J};if(G.hasPulling&&!G.hasPulled)return{kind:"pulling-image",since:J};if(K==="ContainerCreating"||K==="PodInitializing"||X.scheduled&&!X.containerRunning)return{kind:"starting-container",since:J};if(X.scheduledFalseReason==="Unschedulable"||G.lastFailedSchedulingAt!==void 0&&!X.scheduled)return{kind:"waiting-for-capacity",since:J,message:G.failedSchedulingMessage??X.scheduledFalseMessage,nodeClaim:G.nominatedNodeClaim};return{kind:"claiming",since:J}}function N91($){return $.kind==="ready"||$.kind==="failed"}function _M$($){switch($.kind){case"claiming":return 0;case"waiting-for-capacity":return 1;case"pulling-image":return 2;case"starting-container":return 3;case"warming-daemon":return 4;case"ready":case"failed":return 99}}function U91($){switch($.kind){case"claiming":case"pulling-image":case"starting-container":case"warming-daemon":return $.kind;case"waiting-for-capacity":return`waiting-for-capacity:${$.message??""}:${$.nodeClaim??""}`;case"ready":return"ready";case"failed":return`failed:${$.reason}:${$.message}`}}async function oc4($,Z,Q,X,Y,G,J,K){let W=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${nc4}=${Q}`)}`;return mP0({kc:$,path:W,signal:X,label:`pod/${Q}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let F=H.object;if(F.metadata?.name)K(F.metadata.name);rc4(F,Y,J),G("pod")}})}function rc4($,Z,Q){let Y=($.status?.conditions??[]).find((J)=>J.type==="PodScheduled");if(Y?.status==="True")Z.pod.scheduled=!0,Z.pod.scheduledFalseReason=void 0,Z.pod.scheduledFalseMessage=void 0;else if(Y?.status==="False")Z.pod.scheduled=!1,Z.pod.scheduledFalseReason=Y.reason,Z.pod.scheduledFalseMessage=Y.message;let G=($.status?.containerStatuses??[]).find((J)=>J.name===w9.MAIN_CONTAINER_NAME);if(G)Z.pod.containerWaitingReason=G.state?.waiting?.reason,Z.pod.containerRunning=!!G.state?.running,Z.pod.containerReady=G.ready===!0}async function ac4($,Z,Q,X,Y,G){let J=`/apis/${w9.CLAIM_API_GROUP}/${w9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${w9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${Q}`)}`;return mP0({kc:$,path:J,signal:X,label:`sandboxclaim/${Q}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let H=K.object.status?.conditions?.find((F)=>F.type==="Ready");if(!H)return;if(H.status==="True")Y.sandbox.ready=!0,Y.sandbox.notReadyReason=void 0,Y.sandbox.notReadyMessage=void 0;else Y.sandbox.ready=!1,Y.sandbox.notReadyReason=H.reason,Y.sandbox.notReadyMessage=H.message;G("sandbox")}})}async function sc4($,Z,Q,X,Y,G,J,K){let W=await Promise.race([X,new Promise((F)=>{if(Y.aborted){F(Q);return}Y.addEventListener("abort",()=>F(Q),{once:!0})})]);if(Y.aborted)return;let H=`/api/v1/namespaces/${encodeURIComponent(Z)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${W},involvedObject.kind=Pod`)}`;return mP0({kc:$,path:H,signal:Y,label:`events/${Q}`,onEvent:(F)=>{if(F.type!=="ADDED"&&F.type!=="MODIFIED")return;let N=F.object,U=N.reason;if(!U)return;switch(U){case"Pulling":G.events.hasPulling=!0;break;case"Pulled":G.events.hasPulling=!0,G.events.hasPulled=!0;break;case"FailedScheduling":G.events.lastFailedSchedulingAt=K(),G.events.failedSchedulingMessage=N.message;break;case"Nominated":{let B=N.message?.match(/nodeclaim\/([\w-]+)/);if(B)G.events.nominatedNodeClaim=B[1];break}default:return}J("event")}})}async function xM$($){let{kc:Z,namespace:Q,labelSelector:X,signal:Y,onDelete:G}=$,J=`/apis/${w9.CLAIM_API_GROUP}/${w9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Q)}/${w9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(X)}`;return mP0({kc:Z,path:J,signal:Y,label:"sandboxclaim-reaper",onEvent:(K)=>{if(K.type!=="DELETED")return;let W=K.object.metadata?.name;if(W)G(W)}})}async function mP0($){let{kc:Z,path:Q,signal:X,label:Y,onEvent:G}=$,J=0;while(!X.aborted){try{let W=await RG(Z,{method:"GET",path:Q,signal:X,headers:{accept:"application/json"},stream:!0});if(!W.ok||!W.body){try{await W.body?.cancel()}catch{}if(W.status===401||W.status===403){console.warn(`[lifecycle-watcher] ${Y} stopped: watch denied (${W.status} ${W.statusText}). `+"The kubeconfig in use cannot watch SandboxClaims \u2014 if you are running locally, "+"this provider should not be active (check STUDIO_AGENT_SANDBOX_ENABLED).");return}throw Error(`watch handshake failed: ${W.status} ${W.statusText}`)}J=0;for await(let H of D61(W.body)){if(X.aborted)return;try{G(H)}catch(F){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${F instanceof Error?F.message:String(F)}`)}}}catch(W){if(X.aborted)return;let H=W instanceof Error?W.message:String(W);console.warn(`[lifecycle-watcher] ${Y} watch ended: ${H}`)}if(X.aborted)return;let K=N7(5000,250,J,2,0);J+=1,await W$(K,{signal:X}).catch(()=>{})}}var nc4="studio.decocms.com/sandbox-handle",tc4=300000;var fM$=L(()=>{J4();jK0();TK0()});import{z as iJ}from"zod";function bM$($){if(!$||$.trim()==="")return[];let Z=iJ.array(ec4).parse(JSON.parse($)),Q=new Set;for(let X of Z){if(Q.has(X.name))throw Error(`STUDIO_SANDBOX_TENANT_POOLS: duplicate pool name ${X.name}`);Q.add(X.name)}return Z}function $l4($){try{let[Z,Q]=new URL($).pathname.replace(/^\/+/,"").split("/"),X=Q?.replace(/\.git$/,"");return Z&&X?`${Z}/${X}`.toLowerCase():null}catch{return null}}function yM$($,Z){let{orgId:Q,cloneUrl:X}=Z;if(Z.purpose==="harness-run")return null;if(!Q||!X)return null;let Y=$l4(X);if(!Y)return null;return $.find((G)=>G.orgId===Q&&G.repo.toLowerCase()===Y)??null}function gM$($,Z,Q){return $?.name??(Z?Q:"none")}function Zl4($,Z){return $==="harness-run"?`${Z}-medium`:Z}async function hM$($){let Z=Zl4($.purpose,$.templateName);if(Z===$.templateName)return{name:Z,probe:$.probe};let Q=$.probe!==null&&$.now-$.probe.checkedAt<$.ttlMs?$.probe:{checkedAt:$.now,present:await $.exists(Z)};if(Q.present)return{name:Z,probe:Q};if($.probe?.present!==!1)$.onAbsent?.(Z);return{name:$.templateName,probe:Q}}function uM$($,Z,Q){let X=Q.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===X)}function cM$($){return`https://github.com/${$.repo}.git`}var ec4;var B91=L(()=>{ec4=iJ.object({name:iJ.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:iJ.string().min(1),repo:iJ.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:iJ.string().min(1).optional(),branch:iJ.string().min(1).default("main"),workload:iJ.object({runtime:iJ.enum(["node","bun","deno"]).default("node"),packageManager:iJ.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:iJ.string().optional(),devPort:iJ.number().int().positive().optional()}).default({runtime:"node"})})});async function lM$($,Z,Q){let X=new Map;for(let Y of $){let G=Z(Y);if(!G)continue;let J=X.get(G);if(J)J.push(Y);else X.set(G,[Y])}await Promise.allSettled([...X.values()].map(async(Y)=>{for(let G of Y)await Q(G).catch(()=>{})}))}import{createHash as Ql4,randomBytes as Xl4,randomUUID as Yl4}from"crypto";import*as oM$ from"net";import{PassThrough as Gl4}from"stream";function mM$($){if($ instanceof Error)return $.message;if($&&typeof $==="object"){let Z=$;if(Z.error instanceof Error)return Z.error.message;if(typeof Z.message==="string"&&Z.message)return Z.message}return String($)}class z91{records=new Map;inflight=new ZK0;activeGauge=new $K0;stateStore;previewUrlPattern;kubeConfig;capacityProbe;portForward;namespace;sandboxTemplateName;envName;tokenGenerator;idleTtlMs;metrics;previewGateway;sentinelToken;mintCloneUrl;mintOrgFsConfig;tenantPools;tenantPoolRefreshMs;poolPods=new Map;mediumTemplateProbe=null;dirtyPools=new Set;closed=!1;claimWatchAbort=new AbortController;constructor($={}){this.stateStore=$.stateStore??null,this.previewUrlPattern=$.previewUrlPattern??null,this.kubeConfig=$.kubeConfig??jl4(),this.portForward=new n51(this.kubeConfig),this.namespace=$.namespace??Jl4,this.sandboxTemplateName=$.sandboxTemplateName??Kl4,this.envName=Il4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>Xl4(Hl4).toString("hex")),this.idleTtlMs=$.idleTtlMs??Nl4,this.metrics=$.meter?El4($.meter):null,this.previewGateway=$.previewGateway&&$.previewUrlPattern?{...$.previewGateway}:null;let Z=$.sentinelToken?.trim()??"";if(this.sentinelToken=Z.length>0?Z:null,this.mintCloneUrl=$.mintCloneUrl,this.mintOrgFsConfig=$.mintOrgFsConfig,this.tenantPools=this.sentinelToken!==null?$.tenantPools??[]:[],this.sentinelToken===null&&($.tenantPools?.length??0)>0)console.warn(`[${B6}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??Bl4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${PX.env}=${this.envName}`]:[]].join(",");xM$({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let Q=vz($);if(Q.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(Q,()=>QK0(this.stateStore,$,(X)=>this.ensureLocked($,Q,Z,X)))}async delete($){let Z=await this.getRecord($);if(this.records.delete($),Z)this.dropRecord(Z);if(await this.deleteHttpRouteIfManaged($).catch((Q)=>{console.warn(`[${B6}] HTTPRoute delete failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`)}),await Lu(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id);else await this.stateStore.deleteByHandle($)}lastTermination($){return lP$(this.kubeConfig,this.namespace,PX.sandboxHandle,$,w9.MAIN_CONTAINER_NAME)}async alive($){return await sN(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return vM$({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=eP$(this.kubeConfig,this.namespace),this.capacityProbe()}async getPreviewUrl($){let Z=await this.getRecord($);if(!Z)return null;return this.composePreviewUrl(Z)}async proxyDaemonRequest($,Z,Q){let X=await this.getRecord($);if(!X&&this.previewUrlPattern&&this.stateStore){let W=await this.stateStore.getByHandle($),H=W?.state,F=H?.token;if(W&&F){let U=`http://${H?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${GU}`;try{let B=await Ra(U,F,Z,Q);if(B.status!==404)return B;try{await B.body?.cancel()}catch{}}catch{}}}if(!X)X=await this.resurrectByHandle($);if(!X)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let Y=X,G=performance.now(),J=0,K=!(Q.body instanceof ReadableStream);try{let W=await Ra(X.daemonUrl,X.token,Z,Q);if(W.status===401&&K){this.invalidateRecord($);let H=await this.getRecord($).catch(()=>null)??await this.resurrectByHandle($).catch(()=>null);if(H){try{await W.body?.cancel()}catch{}Y=H,W=await Ra(H.daemonUrl,H.token,Z,Q)}}return J=W.status,W}catch(W){if(!K)throw W;this.invalidateRecord($);let H=await this.resurrectByHandle($)??await this.getRecord($).catch(()=>null);if(!H)throw W;Y=H;let F=await Ra(H.daemonUrl,H.token,Z,Q);return J=F.status,F}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let Q=await sN(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Q||Q.metadata?.deletionTimestamp)return!1;return await this.inflight.run(Z,async()=>{let Y=this.records.get(Z);if(Y)return this.toSandbox(Y);let G=await this.adopt($,Z,Q);if(!G)throw Error(`cannot adopt live claim ${Z}`);return QK0(this.stateStore,$,(J)=>this.finish(G,J,!0,!0,"adopt"))}).catch(()=>null)!=null}async resolvePreviewUpstreamUrl($){if(this.previewUrlPattern)return`http://${await this.resolveServiceNameForHandle($)}.${this.namespace}.svc.cluster.local:${GU}`;let Z=await this.getRecord($);if(Z)return Z.daemonUrl;let Q=await this.resurrectByHandle($);return Q?Q.daemonUrl:null}async resolveServiceNameForHandle($){let Z=this.records.get($);if(Z)return Z.adoptedSandboxName;if(this.stateStore){let X=(await this.stateStore.getByHandle($).catch(()=>null))?.state?.adoptedSandboxName;if(X)return X}return $}async proxyPreviewRequest($,Z){let Q=performance.now(),X=this.records.get($)??null,Y=0;try{let G=await this.resolvePreviewUpstreamUrl($);if(!G){Y=404;let O=L91(404,{error:"sandbox not found"});return O.headers.set(Uv,"1"),O}let J=new URL(Z.url);if((J.pathname==="/_sandbox"||J.pathname.startsWith("/_sandbox/"))&&Z.method!=="GET")return Y=404,L91(404,{error:"not found"});let W=(O)=>`${O}${J.pathname}${J.search}`,H=new Headers(Z.headers);for(let O of Dl4)H.delete(O);let F=Z.method!=="GET"&&Z.method!=="HEAD",N={method:Z.method,headers:H,body:F?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:F?"half":void 0},U;try{U=await fetch(W(G),N)}catch(O){let D=`${G}${J.pathname}`;if(console.warn(`[${B6}] preview fetch to ${D} failed: ${O instanceof Error?O.message:String(O)}`),Z.method==="GET"||Z.method==="HEAD"){if(this.invalidateRecord($),await this.resurrectByHandle($).catch(()=>null)){let j=await this.resolvePreviewUpstreamUrl($);if(j)try{U=await fetch(W(j),N);let z=new Headers;for(let[A,P]of U.headers.entries())if(!pM$.includes(A.toLowerCase()))z.set(A,P);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:z})}catch(z){console.warn(`[${B6}] preview fetch retry to ${D} failed: ${z instanceof Error?z.message:String(z)}`)}}}else this.invalidateRecord($);Y=502;let w=L91(502,{error:"sandbox daemon unreachable"});return w.headers.set(Uv,"1"),w}let B=new Headers;for(let[O,D]of U.headers.entries())if(!pM$.includes(O.toLowerCase()))B.set(O,D);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:B})}finally{this.recordProxyDuration("preview",Y,X,performance.now()-Q,$)}}async ensureLocked($,Z,Q,X){if(Q.image)console.warn(`[${B6}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${Q.image}`);if(X){let J=await X.get($);if(J){let K=await this.rehydrate($,Z,J);if(K)return await this.refreshDaemonGitCredential(K,Q),await this.relayOrgFsConfig(K.daemonUrl,K.token,Q.orgFsConfigJson),this.finish(K,X,!1,!0,"resume");await X.delete($)}}let Y=await sN(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await PK0(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${B6}] wait for terminating claim ${Z} failed: ${J instanceof Error?J.message:String(J)}`)});else{let J=await this.adopt($,Z,Y).catch((K)=>{return console.warn(`[${B6}] adopt ${Z} failed, recreating: ${K instanceof Error?K.message:String(K)}`),null});if(J)return await this.refreshDaemonGitCredential(J,Q),await this.relayOrgFsConfig(J.daemonUrl,J.token,Q.orgFsConfigJson),this.finish(J,X,!0,!0,"adopt");await Lu(this.kubeConfig,this.namespace,Z).catch(()=>{}),await PK0(this.kubeConfig,this.namespace,Z).catch((K)=>{console.warn(`[${B6}] wait for deleted claim ${Z} failed: ${K instanceof Error?K.message:String(K)}`)})}let G=await this.provision($,Z,Q);return this.finish(G,X,!0,!1,"fresh")}async finish($,Z,Q,X,Y){let G=this.records.get($.handle),J=G!==void 0;if(G&&G.daemonForward!==$.daemonForward)this.closeForwarder(G.daemonForward);if(this.records.set($.handle,$),Q)await this.persist(Z,$);if(X)await AK0(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((K)=>console.warn(`[${B6}] TTL refresh failed for ${$.handle}: ${K instanceof Error?K.message:String(K)}`));if(this.metrics){let K=w91($.tenant);if(this.metrics.ensureOutcome.add(1,{...K,outcome:Y}),!J)this.metrics.active.add(1,K),this.activeGauge.markCounted($.handle)}return this.toSandbox($)}buildEnvMap($,Z){let Q={},X=[];for(let[Y,G]of Object.entries($.env??{}))if(Fl4.has(Y))X.push(Y);else Q[Y]=G;if(X.length>0)console.warn(`[${B6}] opts.env keys overlap reserved bootstrap names and were dropped: ${X.join(",")}`);return{...Q,DAEMON_TOKEN:Z.token,DAEMON_BOOT_ID:Z.daemonBootId,APP_ROOT:Z.workdir,PROXY_PORT:String(GU)}}async resolveTemplateName($){let{name:Z,probe:Q}=await hM$({purpose:$,templateName:this.sandboxTemplateName,probe:this.mediumTemplateProbe,now:Date.now(),ttlMs:Wl4,exists:(X)=>gP$(this.kubeConfig,this.namespace,X),onAbsent:(X)=>console.warn(`[${B6}] SandboxTemplate ${X} not found (or not readable) \u2014 harness-run claims fall back to ${this.sandboxTemplateName}. Upgrade the sandbox-env chart to the version that renders it.`)});return this.mediumTemplateProbe=Q,Z}buildClaim($,Z,Q,X){let Y=this.sentinelToken!==null,G=yM$(this.tenantPools,{orgId:Z.tenant?.orgId,cloneUrl:Z.repo?.cloneUrl,purpose:Z.purpose}),J=Y?[]:Object.entries(this.buildEnvMap(Z,Q)).sort(([H],[F])=>H<F?-1:H>F?1:0).map(([H,F])=>({name:H,value:F})),K=Vl4(Z),W=Object.keys(K).length>0;return{apiVersion:`${w9.CLAIM_API_GROUP}/${w9.CLAIM_API_VERSION}`,kind:"SandboxClaim",metadata:{name:$,namespace:this.namespace,labels:{"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[PX.env]:this.envName}:{},...D91(Z.tenant)},...W?{annotations:K}:{}},spec:{sandboxTemplateRef:{name:X},additionalPodMetadata:{labels:D91(Z.tenant,{[PX.role]:"claimed",[PX.sandboxHandle]:$,...this.envName?{[PX.env]:this.envName}:{}}),...W?{annotations:K}:{}},env:J,warmpool:gM$(G,Y,X),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,Q){let X=this.tokenGenerator(),Y=Yl4(),G=O91,J=this.buildClaim(Z,Q,{token:X,daemonBootId:Y,workdir:G},await this.resolveTemplateName(Q.purpose));try{await B61(this.kubeConfig,this.namespace,J)}catch(U){if(U instanceof Xa)await PK0(this.kubeConfig,this.namespace,Z),await B61(this.kubeConfig,this.namespace,J);else throw U}let K;try{K=await hP$(this.kubeConfig,this.namespace,Z),await aP$(this.kubeConfig,this.namespace,K)}catch(U){throw await Lu(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}try{await this.ensureServicePortForAdoptedSandbox(K),await this.ensureHttpRouteForHandle(Z,K,Q.tenant??null)}catch(U){throw await Lu(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}let W=await this.openForwarder(K,GU,Z),H=`http://127.0.0.1:${W.localPort}`,F=this.workloadConfigPayload(Q),N=Y;try{if(await F91(H),this.sentinelToken!==null){let U=await lP0(H);if(U)N=U.bootId;await Fv(H,this.sentinelToken,F??{},{rotateToken:X})}else if(F)await Fv(H,X,F);await this.relayOrgFsConfig(H,X,Q.orgFsConfigJson)}catch(U){throw this.closeForwarder(W),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await Lu(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}return{id:$,handle:Z,adoptedSandboxName:K,token:X,workdir:G,daemonUrl:H,daemonForward:W,workload:Q.workload??null,daemonBootId:N,tenant:Q.tenant??null,ensureOpts:vl4(Q)}}workloadConfigPayload($){return YK0({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,extraRepos:$?.extraRepos??[],port:$?.workload?.devPort??dM$,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,Q){if(!Q)return;await kM$($,Z,Q).catch((X)=>console.warn("[org-fs] sidecar config relay failed",X))}async refreshDaemonGitCredential($,Z){let Q=t41(Z);if(!Q)return;try{await Fv($.daemonUrl,$.token,Q)}catch(X){console.warn(`[${B6}] git credential refresh failed for ${$.handle}: ${X instanceof Error?X.message:String(X)}`)}}async withFreshCloneUrl($,Z){if(!this.mintCloneUrl)return $;try{let Q=await this.mintCloneUrl($,Z!==void 0?{bufferMs:Z}:void 0);return Q?{...$,cloneUrl:Q}:$}catch(Q){return console.warn(`[${B6}] clone credential re-mint failed: ${Q instanceof Error?Q.message:String(Q)}`),$}}async withFreshCredentials($){return{...$,...$.repo?{repo:await this.withFreshCloneUrl($.repo)}:{},...$.orgFsConfigJson?{orgFsConfigJson:await _l4($,this.mintOrgFsConfig)}:{}}}startCredentialRefresher(){if(!this.mintCloneUrl)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){if(await W$(Ol4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${B6}] periodic credential refresh failed: ${Z instanceof Error?Z.message:String(Z)}`)}}})()}startTenantPoolReconciler(){if(this.tenantPools.length===0)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){try{await this.reconcileTenantPools()}catch(Z){console.warn(`[${B6}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await W$(Ul4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let Q=uM$(this.tenantPools,$,Z);for(let X of Q)this.dirtyPools.add(X.name);return Q.map((X)=>X.name)}async reconcileTenantPools(){for(let $ of this.tenantPools){let Z=await uP$(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${B6}] tenant pool ${$.name}: no SandboxWarmPool (or no selector yet) in ${this.namespace}`);continue}let Q=this.dirtyPools.delete($.name),X=Z.filter((Y)=>!Y.labels[PX.sandboxHandle]);for(let[Y]of this.poolPods)if(!Z.some((G)=>G.uid===Y))this.poolPods.delete(Y);for(let Y of X){if(this.claimWatchAbort.signal.aborted)return;await this.warmPoolPod($,Y,Q)}this.recordPoolDepth($,Z,X)}}recordPoolDepth($,Z,Q){let X=this.metrics?.poolPods;if(!X)return;let Y=0,G=0;for(let K of Q){let W=this.poolPods.get(K.uid);if(!W)continue;if(W.failures>=dP0)G++;else if(W.lastConfigAt>0)Y++}let J={pool:$.name,org:$.orgId};X.record(Y,{...J,state:"ready"}),X.record(Z.length-Q.length,{...J,state:"bound"}),X.record(Q.length-Y-G,{...J,state:"pending"}),X.record(G,{...J,state:"failed"})}async warmPoolPod($,Z,Q){let X=this.poolPods.get(Z.uid);if(X&&X.failures>=dP0){if(Date.now()-X.lastFailureAt<iM$)return;this.poolPods.set(Z.uid,{...X,failures:0})}let Y=Q||X!==void 0&&Date.now()-X.lastConfigAt>=this.tenantPoolRefreshMs;if(X&&!Y)return;let G={cloneUrl:cM$($),connectionId:$.connectionId,branch:$.branch,userName:"",userEmail:""},J=await this.withFreshCloneUrl(G);if($.connectionId&&J.cloneUrl===G.cloneUrl){this.recordPoolFailure(Z,$,"clone credential mint failed");return}let K=await this.openForwarder(Z.name,GU,Z.name).catch(()=>null);if(!K){this.recordPoolFailure(Z,$,"port-forward failed");return}let W=`http://127.0.0.1:${K.localPort}`;try{await F91(W);let H=this.sentinelToken;if(!H)return;if(!await this.isPoolPodUnbound(Z))return;let F=YK0({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??dM$})??{},{transition:N}=await Fv(W,H,F);if(Y&&N!=="bootstrap"&&await this.isPoolPodUnbound(Z))await VM$(W,H,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${B6}] tenant pool ${$.name}: warmed ${Z.name} (${N})`)}catch(H){this.recordPoolFailure(Z,$,H instanceof Error?H.message:String(H))}finally{this.closeForwarder(K)}}isPoolPodUnbound($){return cP$(this.kubeConfig,this.namespace,$.name,PX.sandboxHandle)}recordPoolFailure($,Z,Q){let X=this.poolPods.get($.uid),Y=(X?.failures??0)+1;this.poolPods.set($.uid,{lastConfigAt:X?.lastConfigAt??0,lastFailureAt:Date.now(),failures:Y});let G=Y>=dP0?` \u2014 backing off ${iM$/60000}min`:"";console.warn(`[${B6}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${dP0})${G}: ${Q}`)}async refreshAllGitCredentials(){await lM$(this.records.values(),($)=>$.ensureOpts?.repo?.connectionId,async($)=>{if(this.claimWatchAbort.signal.aborted)return;let Z=$.ensureOpts?.repo;if(!Z)return;let Q=await this.withFreshCloneUrl(Z,Ll4);await this.refreshDaemonGitCredential($,{...$.ensureOpts,repo:Q}),$.ensureOpts={...$.ensureOpts,repo:Q}})}async rebootstrapDaemon($,Z,Q){if(this.sentinelToken===null)return!1;let X=this.workloadConfigPayload(Q)??{};try{return await Fv($,this.sentinelToken,X,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,Q?.orgFsConfigJson),!0}catch(Y){if(Y instanceof cP0&&Y.status===401)try{return await Fv($,Z,X,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,Q?.orgFsConfigJson),!0}catch(G){return console.warn(`[${B6}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${B6}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await rP$(this.kubeConfig,this.namespace,$,{name:"daemon",port:GU,targetPort:GU})}async ensureHttpRouteForHandle($,Z,Q){if(!this.previewGateway||!this.previewUrlPattern)return;let X=xl4(this.previewUrlPattern,$);if(!X)throw new zZ(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${L61.API_GROUP}/${L61.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:D91(Q??void 0,{[PX.role]:"claimed",[PX.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[PX.env]:this.envName}:{}})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[X],rules:[{backendRefs:[{group:"",kind:"Service",name:Z,port:GU}]}]}};await nP$(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await tP$(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,Q){let X=Q.state;if(!X.adoptedSandboxName&&!X.podName||!X.token)return null;let Y=await sN(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!nM$(Y))return null;let G=Y.status?.sandbox?.name??X.adoptedSandboxName??X.podName??Z,J=await this.openAndProbeDaemon(G,Z);if(!J)return null;if(X.daemonBootId&&X.daemonBootId!==J.bootId){if(this.sentinelToken!==null){let K=X.ensureOpts?await this.withFreshCredentials(X.ensureOpts):null;if(!await this.rebootstrapDaemon(J.daemonUrl,X.token,K))return this.closeForwarder(J.daemonForward),null}else console.warn(`[${B6}] daemon restart detected (handle=${Z}): stored bootId=${X.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,{handle:Z,state:{...X,daemonBootId:J.bootId}}).catch((K)=>console.warn(`[${B6}] bootId persist failed for ${Z}: ${K instanceof Error?K.message:String(K)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:X.token,workdir:X.workdir??O91,daemonUrl:J.daemonUrl,daemonForward:J.daemonForward,workload:X.workload??null,daemonBootId:J.bootId,tenant:X.tenant??null,ensureOpts:X.ensureOpts??null}}async adopt($,Z,Q){if(!nM$(Q))return null;let X=Q.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=zl4(Q);if(!Y)return null;let G=await this.openAndProbeDaemon(X,Z);if(!G)return null;let J=kl4(Q);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(X).catch((K)=>{console.warn(`[${B6}] Service port backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)}),await this.ensureHttpRouteForHandle(Z,X,J).catch((K)=>{console.warn(`[${B6}] HTTPRoute backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)});return{id:$,handle:Z,adoptedSandboxName:X,token:Y,workdir:O91,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let Q=await this.openForwarder($,GU,Z).catch(()=>null);if(!Q)return null;let X=`http://127.0.0.1:${Q.localPort}`,Y=await lP0(X);if(!Y)return this.closeForwarder(Q),null;return{daemonForward:Q,daemonUrl:X,bootId:Y.bootId}}async getRecord($){let Z=this.records.get($);if(Z)return Z;if(!this.stateStore)return null;let Q=await this.stateStore.getByHandle($);if(!Q)return null;let X=await this.rehydrate(Q.id,$,Q);if(X)this.records.set($,X);return X}async resurrectByHandle($){if(!this.stateStore)return null;let Z=await this.stateStore.getByHandle($);if(!Z)return null;let Q=Z.state.ensureOpts;if(!Q)return null;let X=await this.withFreshCredentials(Q);if(vz(Z.id)!==$)return null;return await this.ensure(Z.id,X),this.records.get($)??null}invalidateRecord($){let Z=this.records.get($);if(!Z)return;this.records.delete($),this.dropRecord(Z)}dropRecord($){if(this.closeForwarder($.daemonForward),this.metrics&&this.activeGauge.consume($.handle))this.metrics.active.add(-1,w91($.tenant))}recordProxyDuration($,Z,Q,X,Y){if(!this.metrics)return;this.metrics.proxyDurationMs.record(X,{...w91(Q?.tenant??null),source:$,sandbox_handle:Q?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return XK0(this.previewUrlPattern,$.handle);return`http://127.0.0.1:${$.daemonForward.localPort}/`}toSandbox($){return{handle:$.handle,workdir:$.workdir,previewUrl:this.composePreviewUrl($)}}async persist($,Z){if(!$)return;let Q={adoptedSandboxName:Z.adoptedSandboxName,token:Z.token,workdir:Z.workdir,workload:Z.workload,daemonBootId:Z.daemonBootId,tenant:Z.tenant,...Z.ensureOpts?{ensureOpts:Z.ensureOpts}:{}};await $.put(Z.id,{handle:Z.handle,state:Q})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let Q=await sN(this.kubeConfig,this.namespace,$);if(!Q)return;let X=Sl4(Q.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!X)return;await AK0(this.kubeConfig,this.namespace,$,X).catch((Y)=>console.warn(`[${B6}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await sN(this.kubeConfig,this.namespace,$);if(!Z)return;let Q=Cl4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!Q)return;await AK0(this.kubeConfig,this.namespace,$,Q).catch((X)=>console.warn(`[${B6}] TTL renew failed for ${$}: ${X instanceof Error?X.message:String(X)}`))}openForwarder($,Z,Q=$){let X=Pl4(Q,Z);return new Promise((Y,G)=>{let J=(K,W)=>{let H=oM$.createServer((F)=>this.handleForwardedConnection(F,$,Z,Q));H.once("error",(F)=>{if(F.code==="EADDRINUSE"&&W<wl4){try{H.close()}catch{}let N=E91+(K-E91+1)%rM$;J(N,W+1);return}G(F)}),H.listen(K,"127.0.0.1",()=>{let F=H.address();if(!F||typeof F==="string"){H.close(),G(Error("port-forward listener failed to bind"));return}Y({server:H,localPort:F.port})})};J(X,0)})}handleForwardedConnection($,Z,Q,X){let Y=new Gl4,G=null,J=!1,K=()=>{if(J)return;if(J=!0,Y.destroy(),G)try{G.close()}catch{}if(!$.destroyed)$.destroy()};$.pipe(Y),$.on("error",K),$.on("close",K),this.portForward.portForward(this.namespace,Z,[Q],$,null,Y).then((W)=>{let H=typeof W==="function"?W():W;if(!H){K();return}if(G=H,G.on("close",K),G.on("error",(F)=>{console.warn(`[${B6}] port-forward to ${Z}:${Q} dropped mid-connection: ${mM$(F)}`,JSON.stringify(j91(F))),this.invalidateRecord(X),K()}),J)try{G.close()}catch{}}).catch((W)=>{console.warn(`[${B6}] port-forward to ${Z}:${Q} failed: ${mM$(W)}`,JSON.stringify(j91(W))),this.invalidateRecord(X),K()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${B6}] port-forward close on :${$.localPort} errored: ${Z instanceof Error?Z.message:String(Z)}`)})}close(){if(this.closed)return;this.closed=!0,this.claimWatchAbort.abort();for(let $ of this.records.values())this.dropRecord($);this.records.clear()}}function El4($){return{active:$.createUpDownCounter("studio.sandbox.active",{description:"Active sandbox count, by runner kind, owning org, and daemon impl. Cross-checks the cAdvisor-derived count from the cluster \u2014 divergence between the two indicates orphaned claims (studio deleted but K8s didn't reap) or unattributed pods.",unit:"{sandbox}"}),ensureOutcome:$.createCounter("studio.sandbox.ensure.outcome",{description:"Outcome of each ensure() call: fresh provision, resume from state-store after restart, or adopt of a cluster-side claim studio didn't know about. Cold-start ratio is the primary input for warm-pool sizing.",unit:"{call}"}),proxyDurationMs:$.createHistogram("studio.sandbox.proxy.duration_ms",{description:"Wall-clock latency of studio-mediated requests to the sandbox daemon: tool exec proxies (source=daemon) and preview iframe traffic (source=preview).",unit:"ms"}),poolPods:$.createGauge("studio.sandbox.pool.pods",{description:"Tenant warm pool depth by pool and state: ready (warmed and unbound \u2014 what a claim can actually bind instantly), bound (serving a user), pending (unbound, not yet warmed), failed (gave up after repeated bootstrap failures). Alert on sustained ready=0: a pool that is always empty is doing nothing while costing N pods.",unit:"{pod}"})}}function j91($){let Z=[],Q=$;for(let X=0;X<5&&Q instanceof Error;X++){let Y=Q;if(Z.push({name:Y.name,message:Y.message,...Y.code!==void 0?{code:Y.code}:{},...Y.errno!==void 0?{errno:Y.errno}:{}}),Y.cause===Q)break;Q=Y.cause}if(Q!==void 0&&!(Q instanceof Error)&&Q!==null){let X=Q,Y=X.error instanceof Error?j91(X.error).chain:void 0;Z.push({nonError:String(Q),...typeof X.type==="string"?{type:X.type}:{},...typeof X.message==="string"?{message:X.message}:{},...X.code!==void 0?{code:X.code}:{},...typeof X.reason==="string"?{reason:X.reason}:{},...Y?{error:Y}:{},...Y===void 0&&X.error!==void 0?{rawError:String(X.error)}:{},keys:Object.keys(X)})}return{chain:Z}}function jl4(){let $=new TP0;return $.loadFromDefault(),$}function nM$($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function zl4($){let Z=$.spec?.env;if(!Z)return null;for(let Q of Z)if(Q.name==="DAEMON_TOKEN"&&Q.value)return Q.value;return null}function Pl4($,Z){let Q=Ql4("sha256").update(`${$}:${Z}`).digest();return E91+Q.readUInt32BE(0)%rM$}function L91($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function tM$($){let Z=$.slice(0,Tl4);return Al4.test(Z)?Z:""}function Il4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!Rl4.test(Z))throw Error(`AgentSandboxProvider: envName=${JSON.stringify(Z)} is not a valid DNS-label-safe environment name (lowercase alphanumeric or '-', starts with a letter, ends alphanumeric, \u226432 chars). Studio sets this from STUDIO_ENV; check the studio chart's configMap.`);return Z}function D91($,Z={}){let Q={...Z};if($){let X=tM$($.orgId),Y=tM$($.userId);if(X)Q[PX.orgId]=X;if(Y)Q[PX.userId]=Y}return Q}function Nv($){let Z="";for(let Q of $){let X=Q.codePointAt(0)??0;Z+=X<32||X===127?" ":Q}return Z.slice(0,ql4)}function Ml4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function Vl4($){let Z={},Q=$.tenant;if(Q?.orgSlug)Z[vK.orgSlug]=Nv(Q.orgSlug);if(Q?.orgName)Z[vK.orgName]=Nv(Q.orgName);if(Q?.userEmail)Z[vK.userEmail]=Nv(Q.userEmail);if(Q?.userName)Z[vK.userName]=Nv(Q.userName);let X=$.repo;if(X){if(X.displayName)Z[vK.gitRepo]=Nv(X.displayName);let Y=Ml4(X.cloneUrl);if(Y)Z[vK.gitRepoUrl]=Nv(Y);let G=$.branch??X.branch;if(G)Z[vK.gitBranch]=Nv(G)}return Z}function kl4($){let Z=$.metadata?.labels;if(!Z)return null;let Q=Z[PX.orgId],X=Z[PX.userId];if(!Q||!X)return null;let Y=$.metadata?.annotations??{};return{orgId:Q,userId:X,orgSlug:Y[vK.orgSlug],orgName:Y[vK.orgName],userEmail:Y[vK.userEmail],userName:Y[vK.userName]}}function Sl4($,Z){if($){let Q=new Date($).getTime();if(Number.isFinite(Q)&&Q<=Z.getTime())return null}return Z.toISOString()}function Cl4($,Z){if($){let Q=new Date($).getTime();if(Number.isFinite(Q)&&Q>=Z.getTime())return null}return Z.toISOString()}function w91($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:"agent-sandbox"}}async function _l4($,Z){if(!Z||!$.tenant)return $.orgFsConfigJson;try{return await Z($.tenant)??$.orgFsConfigJson}catch(Q){return console.warn(`[${B6}] org-fs credential re-mint failed: ${Q instanceof Error?Q.message:String(Q)}`),$.orgFsConfigJson}}function vl4($){let Z={};if($.branch)Z.branch=$.branch;if($.repo)Z.repo=$.repo;if($.workload)Z.workload=$.workload;if($.env&&Object.keys($.env).length>0)Z.env=$.env;if($.tenant)Z.tenant=$.tenant;if($.cloneOnly)Z.cloneOnly=!0;if($.purpose)Z.purpose=$.purpose;if($.orgFsConfigJson)Z.orgFsConfigJson=$.orgFsConfigJson;return Object.keys(Z).length>0?Z:null}function xl4($,Z){try{return new URL(XK0($,Z)).hostname||null}catch{return null}}var B6="AgentSandboxProvider",Uv="x-sandbox-preview-not-ready",Jl4="agent-sandbox-system",Kl4="studio-sandbox",Wl4=300000,GU=9000,dM$=3000,O91="/app",Hl4=32,Fl4,Nl4=900000,Ul4=60000,Bl4=1800000,dP0=3,iM$=1800000,Ol4=900000,Ll4=1800000,Dl4,pM$,E91=40000,rM$=1e4,wl4=256,PX,vK,Al4,Tl4=63,Rl4,ql4=253;var aM$=L(()=>{J4();$A$();IM$();SM$();o41();TK0();jK0();fM$();B91();Fl4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),Dl4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],pM$=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];PX={role:"studio.decocms.com/role",sandboxHandle:"studio.decocms.com/sandbox-handle",orgId:"studio.decocms.com/org-id",userId:"studio.decocms.com/user-id",env:"studio.decocms.com/env"},vK={orgSlug:"studio.decocms.com/org-slug",orgName:"studio.decocms.com/org-name",userEmail:"studio.decocms.com/user-email",userName:"studio.decocms.com/user-name",gitRepo:"studio.decocms.com/git-repo",gitRepoUrl:"studio.decocms.com/git-repo-url",gitBranch:"studio.decocms.com/git-branch"},Al4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;Rl4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var sM$={};Q0(sM$,{parseTenantPools:()=>bM$,PREVIEW_NOT_READY_HEADER:()=>Uv,AgentSandboxProvider:()=>z91});var P91=L(()=>{aM$();B91()});var ZV$={};Q0(ZV$,{subscribeLifecycle:()=>M91,getOrInitSharedRunner:()=>q91,getAgentSandboxProviderForTeardown:()=>I91,getAgentSandboxProvider:()=>AX,__resetSharedLifecyclesForTesting:()=>dl4});function T91($){let Z=Ia[eM$];if(Z)return Promise.resolve(Z);let Q=Ia[A91];if(Q)return Q;let X=$().then((Y)=>{return Ia[eM$]=Y,Y}).finally(()=>{delete Ia[A91]});return Ia[A91]=X,X}function fl4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function bl4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function yl4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function gl4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function hl4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME?.trim(),Z=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE?.trim();if(!$&&!Z)return;if(!$||!Z)throw Error("STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME and STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE must both be set, or both unset. Half-configured per-claim HTTPRoute routing would silently fail to attach.");return{name:$,namespace:Z}}async function R91($){let Z=new $a($),Q=fl4(),{AgentSandboxProvider:X,parseTenantPools:Y}=await Promise.resolve().then(() => (P91(),sM$)),G=new JG(y0().encryptionKey);return new X({stateStore:Z,previewUrlPattern:Q,sandboxTemplateName:bl4(),envName:yl4(),previewGateway:hl4(),sentinelToken:gl4(),tenantPools:Y(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:P$,mintCloneUrl:async(J,K)=>{if(!J.connectionId)return null;let W=xP$(J.cloneUrl);if(!W)return null;let{cloneUrl:H}=await MH(J.connectionId,W.owner,W.name,$,G,{bufferMs:K?.bufferMs});return H},mintOrgFsConfig:async(J)=>{if(!J.orgSlug)return null;return await EK0({boundAuth:{apiKey:{create:(W)=>J8.api.createApiKey({body:{...W,userId:J.userId}})}},storage:{orgRepoSyncs:new yz($)}},{orgSlug:J.orgSlug,orgId:J.orgId,baseUrl:m9()})??null}})}function AX($){if(!y0().agentSandboxEnabled)throw Error("Agent sandbox is disabled. Set STUDIO_AGENT_SANDBOX_ENABLED=true to enable it.");return T91(()=>R91($.db))}function I91($){return T91(()=>R91($.db))}async function q91(){if(!y0().agentSandboxEnabled)return null;return T91(()=>R91(H8().db))}function M91($,Z,Q){let X=LD.get(Z);if(X){if(X.terminated){if(X.lastPhase)try{Q(X.lastPhase)}catch{}return{unsubscribe:ll4}}if(X.listeners.add(Q),X.lastPhase)try{Q(X.lastPhase)}catch{}return $V$(Z,X,Q)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([Q]),abort:Y};return LD.set(Z,G),ml4($,Z,G),$V$(Z,G,Q)}function ll4(){}function $V$($,Z,Q){return{unsubscribe(){if(LD.get($)!==Z)return;if(Z.listeners.delete(Q),Z.listeners.size===0)LD.delete($),Z.abort.abort()}}}async function ml4($,Z,Q){let X=null;try{for await(let Y of $.watchClaimLifecycle(Z,Q.abort.signal)){if(Q.abort.signal.aborted)break;Q.lastPhase=Y;let G=Y.kind==="ready"||Y.kind==="failed";if(G)Q.terminated=!0;let J=Array.from(Q.listeners);for(let K of J)try{K(Y)}catch{}if(G)break}}catch(Y){X=Y}finally{if(!Q.terminated&&!Q.abort.signal.aborted&&Q.listeners.size>0){let Y={kind:"failed",reason:"unknown",message:X instanceof Error?X.message:"Lifecycle watcher ended unexpectedly"};Q.lastPhase=Y,Q.terminated=!0;for(let G of Array.from(Q.listeners))try{G(Y)}catch{}}if(LD.get(Z)===Q)LD.delete(Z)}}function dl4(){for(let $ of LD.values())$.abort.abort();LD.clear()}var eM$,A91,Ia,ul4,cl4,LD;var xK=L(()=>{QQ();x6();W61();Uu();Xj();R$();Ou();wG();p5();eM$=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-runner"),A91=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-inflight"),Ia=globalThis;ul4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),cl4=globalThis,LD=cl4[ul4]??=new Map});async function qa($,Z,Q){try{await $.storage.threads.stampRuntimeIfAbsent(Z,Q)}catch(X){console.warn(`[stampRuntimeIfAbsent] ${Z}: ${X instanceof Error?X.message:String(X)}`)}}function QV$($){let Z=$?.trim();if(!Z)return null;try{let Q=new URL(Z);if(Q.protocol!=="http:"&&Q.protocol!=="https:")return null;return Q.href}catch{return null}}function iP0($){return QV$($?.previewServerUrl)??QV$($?.productionUrl)}function Bv($){return $==="cms"||$==="sandbox"?$:null}function il4($){return!!iP0($)&&$?.fastPreview===!0}function pP0($){return il4($)?"cms":"sandbox"}var V91;var Su=L(()=>{V91=["cms","sandbox"]});function XV$($){let{current:Z,detached:Q,base:X}=$.status??{};if(typeof Z!=="string"||Z.length===0)return null;if(Q===!0)return null;if(Z===$.requestedRef)return null;if(pl4.has(Z))return null;if(typeof X==="string"&&X.length>0&&Z===X)return null;return Z}function nP0($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var pl4;var tP0=L(()=>{pl4=new Set(["main","master","trunk","develop","HEAD"])});import{z as JU}from"zod";async function Cu($,Z){s(Z);let Q=a(Z),X=a0(Z);if(!X)throw Error("User ID required");let Y=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!Y||Y.organization_id!==Q.id)throw Error("Virtual MCP not found");let G=Y.metadata??{},J=await xz(Z,$.branch,X),K=qH(b9(G),J,$.branch),W=await AX(Z);if(K){if(await W.alive(K.sandboxHandle).catch(()=>!0))return K;await sL(Z.storage.virtualMcps,$.virtualMcpId,X,J,$.branch).catch((O)=>{console.warn("[ensureSandbox] failed to reap stale entry",O)})}let H=cJ($.branch)??Z.metadata?.threadId;if(H)qa(Z,H,"sandbox");let N=await $D(Z,H)??G.githubRepo??null,{entry:U}=await GV$({ctx:Z,userId:X,sandboxUserId:J,orgId:Q.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:N,threadRepos:await $61(Z,H),existing:null,runner:W,...$.purpose?{purpose:$.purpose}:{}});return U}async function nl4($){let Z=$.primary?`${$.primary.owner}/${$.primary.name}`.toLowerCase():null,Q=$.repos.filter((G)=>`${G.owner}/${G.name}`.toLowerCase()!==Z),X=nr(Q),Y=[];for(let[G,J]of Q.entries()){if(!J.connectionId)continue;try{let{cloneUrl:K}=await MH(J.connectionId,J.owner,J.name,$.ctx.db,$.ctx.vault);Y.push({cloneUrl:K,connectionId:J.connectionId,userName:$.gitUserName,userEmail:$.gitUserEmail,displayName:`${J.owner}/${J.name}`,directoryName:X[G],submoduleCredentials:[]})}catch(K){console.warn(`[provisionSandbox] skipping secondary ${J.owner}/${J.name}:`,K instanceof Error?K.message:K)}}return Y}async function GV$($){let{ctx:Z,userId:Q,sandboxUserId:X,orgId:Y,virtualMcpId:G,branch:J,metadata:K,threadRepos:W,existing:H,runner:F,purpose:N}=$,U=N==="harness-run",B=$.githubRepo?await tl4({ctx:Z,orgId:Y,virtualMcpId:G,userId:Q,githubRepo:$.githubRepo}):null,{runtime:O,packageManager:D,port:w,packageManagerPath:E}=UP$(K),j;if(B){if(B.connectionId)await XD({ctx:Z,connectionId:B.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(q0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:B.connectionId,error:q0.message})}});let{cloneUrl:r,gitUserName:t,gitUserEmail:D0}=B.connectionId?await MH(B.connectionId,B.owner,B.name,Z.db,Z.vault):PP$(B.owner,B.name);if(!D){let q0=B.connectionId?await RP$(B.connectionId,B.owner,B.name,Z.db,Z.vault):await IP$(B.owner,B.name);if(q0)D=q0.packageManager,O=tr[q0.packageManager].runtime,w=q0.devPort??w,await ol4(Z,G,Q,q0.packageManager,q0.devPort)}let e=y0().sandboxStickyHeadRefEnabled,E0=nP0({branch:J,derivedRef:aN(J),recordedHeadRef:e?await JP$(Z,cJ(J)):null,sticky:e}),u0=await LP$({ctx:Z,orgId:Y,userId:Q,entries:FP$(K)});j={cloneUrl:r,...B.connectionId?{connectionId:B.connectionId}:{},userName:t,userEmail:D0,branch:E0,displayName:`${B.owner}/${B.name}`,submoduleCredentials:u0}}let z=await nl4({ctx:Z,orgId:Y,repos:W??[],primary:B,gitUserName:j?.userName??"",gitUserEmail:j?.userEmail??""}),A=O&&D&&!U?{runtime:O,packageManager:D,...w!==null?{devPort:Number(w)}:{},...E?{packageManagerPath:E}:{}}:void 0,P=dr({orgId:Y,virtualMcpId:G,branch:J}),I=!y0().orgFsMountsDisabled,q;if(I){let r=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(r)q=await EK0(Z,{orgSlug:r,orgId:Y,baseUrl:m9()})}await al4(F);let M=await F.ensure({userId:X,projectRef:P},{branch:J,repo:j,extraRepos:z,workload:A,cloneOnly:U,...N?{purpose:N}:{},tenant:{orgId:Y,userId:X,...Z.organization?.slug?{orgSlug:Z.organization.slug}:{},...Z.organization?.name?{orgName:Z.organization.name}:{},...Z.auth.user?.email?{userEmail:Z.auth.user.email}:{},...Z.auth.user?.name?{userName:Z.auth.user.name}:{}},...q?{orgFsConfigJson:q}:{}}),S=Fu(K);await WK0({ctx:Z,runner:F,handle:M.handle,orgId:Y,userId:Q,entries:S});let f=!!H&&H.sandboxHandle===M.handle&&H?.createdAt?H.createdAt:Date.now(),b=K.runtime?.selected??null,l=K.runtime?.port??null,y=K.runtime?.path??null,p={sandboxHandle:M.handle,previewUrl:M.previewUrl,createdAt:f,startedWith:{packageManager:b,port:l,path:y}};await oz$(Z.storage.virtualMcps,G,Q,X,J,p);let Y0=cJ(J)??Z.metadata?.threadId;if(Y0)await WP$(Z,Y0,X,J,p);let L0=!H||H.sandboxHandle!==M.handle;return{entry:p,isNewVm:L0}}async function tl4($){let{ctx:Z,orgId:Q,virtualMcpId:X,userId:Y,githubRepo:G}=$;if(!G.connectionId)return G;if(await Z.storage.connections.findById(G.connectionId,Q))return G;let{items:K}=await Z.storage.connections.list(Q),W=O30(K,G.owner,G.name);if(!W)return console.warn("[provisionSandbox] recorded repo connection no longer exists and no live connection covers the repo",{virtualMcpId:X,connectionId:G.connectionId}),G;console.warn("[provisionSandbox] healed dangling repo connection",{virtualMcpId:X,staleConnectionId:G.connectionId,connectionId:W.id});try{let F=(await Z.storage.virtualMcps.findById(X))?.metadata??{},N=F.githubRepo;if(N?.connectionId===G.connectionId){let U=y5(W);await Z.storage.virtualMcps.update(X,Y,{metadata:{...F,githubRepo:{...N,connectionId:W.id,...U?{installationId:U.installationId}:{}}}})}}catch(H){console.warn("[provisionSandbox] failed to persist healed repo connection",{virtualMcpId:X,error:H.message})}return{...G,connectionId:W.id}}async function ol4($,Z,Q,X,Y){let G=await $.storage.virtualMcps.findById(Z);if(!G)return;let J=G.metadata??{};await $.storage.virtualMcps.update(Z,Q,{metadata:{...J,runtime:{selected:X,port:Y}}})}async function al4($){let Z=Date.now()+YV$,Q=!1;while(!await $.hasSchedulableCapacity()){if(Date.now()>=Z)throw Error(`sandbox provisioning failed: the cluster has had no room to schedule another sandbox for ${Math.round(YV$/1000)}s`);if(!Q)Q=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await W$(rl4)}}var k91,YV$=150000,rl4=5000;var Ma=L(()=>{pr();J4();S0();or();Y61();DP$();EY();GY();Uu();MP$();a41();xK();Su();kK();tP0();R$();p5();Ou();EY();k91=c({name:"SANDBOX_START",description:"Start a sandbox with the connected GitHub repo and dev server.",annotations:{title:"Start VM Preview",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:JU.object({virtualMcpId:JU.string().describe("Virtual MCP ID"),branch:JU.string().min(1).optional().describe("Git branch to check out. Pass the thread's branch whenever the caller has one: when omitted the handler mints a fresh `<user-slug>-<timestamp>` name, which becomes a SEPARATE sandbox from the one the thread's own branch resolves to. The resolved branch is returned in the response so callers can persist it."),threadId:JU.string().optional().describe("The session asking for a sandbox. A thread stamped `cms` is refused \u2014 that session reads and writes over the decofile API and a pod would be invisible to it. Optional: an unstamped (legacy) thread is always allowed, and so is a caller with no thread.")}),outputSchema:JU.object({previewUrl:JU.string().nullable(),sandboxHandle:JU.string(),branch:JU.string(),isNewVm:JU.boolean()}),handler:async($,Z)=>{s(Z);let Q=a(Z);await Z.access.check();let X=$.branch??UK0(NK0(Z.auth.user)),Y=cJ(X)??$.threadId??Z.metadata?.threadId;if(Y){let D=await Z.storage.threads.get(Y).catch(()=>null);if(Bv(D?.metadata?.runtime)==="cms")throw Error("This chat is a CMS session and does not use a sandbox. Start a coding session to get one.")}let G=a0(Z);if(!G)throw Error("User ID required");let J=await xz(Z,X,G),K=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!K||K.organization_id!==Q.id)throw Error("Virtual MCP not found");let W=K.metadata??{},H=await AX(Z),F=qH(b9(W),J,X),U=await $D(Z,cJ(X)??Z.metadata?.threadId)??W.githubRepo??null,{entry:B,isNewVm:O}=await GV$({ctx:Z,userId:G,sandboxUserId:J,orgId:Q.id,virtualMcpId:$.virtualMcpId,branch:X,metadata:W,githubRepo:U,threadRepos:await $61(Z,cJ(X)??Z.metadata?.threadId),existing:F,runner:H});if(Y)qa(Z,Y,"sandbox");return{...B,branch:X,isNewVm:O}}})});function sl4($){let{publicUrl:Z,agentId:Q,organization:X,target:Y,threadId:G}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${encodeURIComponent(Q)}`;if(!X.slug)throw new KV$(X.id,Y);if(Y==="task-run"){if(!G)throw Error("a task-run MCP endpoint is scoped to a run: threadId is required");return`${Z}/api/${X.slug}/mcp/task-run/${encodeURIComponent(G)}`}return`${Z}/api/${X.slug}/mcp/self`}async function oP0($,Z,Q,X,Y="agent-tools",G,J={"*":["*"]}){let K=sl4({publicUrl:m9(),agentId:Z,organization:Q,target:Y,...G?{threadId:G}:{}}),W=await $.boundAuth.apiKey.create({name:X,permissions:J,expiresIn:JV$,metadata:{organization:{id:Q.id,slug:Q.slug,name:Q.name}}});return{url:K,headers:{Authorization:`Bearer ${W.key}`,"x-org-id":Q.id},expiresAt:Date.now()+JV$*1000}}function WV$($){let{publicUrl:Z,organizationSlug:Q,headers:X,connections:Y}=$,G=new Set;return Y.map((J)=>{let K=el4(J.slug??J.title??"")||"mcp",W=K;for(let H=2;G.has(W);H++)W=`${K}-${H}`;return G.add(W),{name:W,url:`${Z}/api/${Q}/mcp/${encodeURIComponent(J.id)}`,headers:X}})}function el4($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function HV$($){return{self:[...$.toolNames],...$.grants}}var JV$=3600,KV$;var S91=L(()=>{p5();KV$=class KV$ extends Error{constructor($,Z){super(`cannot mint a "${Z}" MCP endpoint for organization "${$}": the org-scoped path needs the org slug, which was not loaded.`);this.name="MissingOrganizationSlugError"}}});async function $m4($,Z,Q,X){try{let Y=$.organization;if(!Y)return;let G=await oP0($,X.virtualMcpId,Y,"tool-scripting"),J=await Z.proxyDaemonRequest(Q,"/_sandbox/tools/sync",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify(G)});if(!J.ok)console.warn("[agent-sandbox-fs] tools/sync failed",J.status,await J.text().catch(()=>""))}catch(Y){console.warn("[agent-sandbox-fs] tools/sync failed",Y)}}async function _u($,Z){let Q=await AX($),X=null,Y=()=>{if(!X){if(X=Cu({virtualMcpId:Z.virtualMcpId,branch:Z.branch},$).then((K)=>K.sandboxHandle),X.catch(()=>{X=null}),Z.syncTools)X.then((K)=>$m4($,Q,K,{virtualMcpId:Z.virtualMcpId})).catch(()=>{})}return X},G=Z.branch==="ephemeral";return r41(Q,{ensureHandle:Y,invalidateHandle:async(K)=>{if(X=null,!G&&!K?.force)return;try{await sL($.storage.virtualMcps,Z.virtualMcpId,Z.userId,Z.userId,Z.branch)}catch(W){console.warn("[agent-sandbox-fs] failed to reap vmMap entry",W)}},canAutoRestart:G,threadId:Z.threadId})}async function FV$($,Z){try{let Q=await _u($,Z),{stdout:X}=await Q.onBash("test -d .deco && echo __DECO_SITE__");return X.includes("__DECO_SITE__")}catch(Q){return console.warn("[agent-sandbox-fs] .deco probe failed; assuming deco site",Q),!0}}var rP0=L(()=>{pr();S91();xK();Ma();EY()});import{z as NV$}from"zod";function vu($){let Z=[];for(let Q of $){if(Q.status!=="active")continue;let X=y5(Q);if(!X)continue;Z.push({connectionId:Q.id,owner:X.owner,repo:X.repo,installationId:X.installationId})}return Z}async function Qm4($,Z){let{items:Q}=await $.storage.connections.list(Z,{slug:"mcp-github"});return vu(Q)}function Xm4($){let Z=$.split(`
2371
+ `);return c4.from(Q)};Gc4.decodePax=function(Z){let Q={};while(Z.length){let X=0;while(X<Z.length&&Z[X]!==32)X++;let Y=parseInt(c4.toString(Z.subarray(0,X)),10);if(!Y)return Q;let G=c4.toString(Z.subarray(X+1,Y-1)),J=G.indexOf("=");if(J===-1)return Q;Q[G.slice(0,J)]=G.slice(J+1),Z=Z.subarray(Y)}return Q};Gc4.encode=function(Z){let Q=c4.alloc(512),X=Z.name,Y="";if(Z.typeflag===5&&X[X.length-1]!=="/")X+="/";if(c4.byteLength(X)!==X.length)return null;while(c4.byteLength(X)>100){let G=X.indexOf("/");if(G===-1)return null;Y+=Y?"/"+X.slice(0,G):X.slice(0,G),X=X.slice(G+1)}if(c4.byteLength(X)>100||c4.byteLength(Y)>155)return null;if(Z.linkname&&c4.byteLength(Z.linkname)>100)return null;if(c4.write(Q,X),c4.write(Q,OD(Z.mode&4095,6),100),c4.write(Q,OD(Z.uid,6),108),c4.write(Q,OD(Z.gid,6),116),Xc4(Z.size,Q,124),c4.write(Q,OD(Z.mtime.getTime()/1000|0,11),136),Q[156]=48+Zc4(Z.type),Z.linkname)c4.write(Q,Z.linkname,157);if(c4.copy(vq$,Q,257),c4.copy(tu4,Q,263),Z.uname)c4.write(Q,Z.uname,265);if(Z.gname)c4.write(Q,Z.gname,297);if(c4.write(Q,OD(Z.devmajor||0,6),329),c4.write(Q,OD(Z.devminor||0,6),337),Y)c4.write(Q,Y,345);return c4.write(Q,OD(fq$(Q),6),148),Q};Gc4.decode=function(Z,Q,X){let Y=Z[156]===0?0:Z[156]-48,G=Mu(Z,0,100,Q),J=BD(Z,100,8),K=BD(Z,108,8),W=BD(Z,116,8),H=BD(Z,124,12),F=BD(Z,136,12),N=$c4(Y),U=Z[157]===0?null:Mu(Z,157,100,Q),B=Mu(Z,265,32),O=Mu(Z,297,32),D=BD(Z,329,8),w=BD(Z,337,8),E=fq$(Z);if(E===256)return null;if(E!==BD(Z,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(au4(Z)){if(Z[345])G=Mu(Z,345,155,Q)+"/"+G}else if(su4(Z));else if(!X)throw Error("Invalid tar header: unknown format.");if(Y===0&&G&&G[G.length-1]==="/")Y=5;return{name:G,mode:J,uid:K,gid:W,size:H,mtime:new Date(1000*F),type:N,linkname:U,uname:B,gname:O,devmajor:D,devminor:w,pax:null}};function au4($){return c4.equals(vq$,$.subarray(257,263))}function su4($){return c4.equals(ou4,$.subarray(257,263))&&c4.equals(ru4,$.subarray(263,265))}function eu4($,Z,Q){if(typeof $!=="number")return Q;if($=~~$,$>=Z)return Z;if($>=0)return $;if($+=Z,$>=0)return $;return 0}function $c4($){switch($){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function Zc4($){switch($){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function xq$($,Z,Q,X){for(;Q<X;Q++)if($[Q]===Z)return Q;return X}function fq$($){let Z=256;for(let Q=0;Q<148;Q++)Z+=$[Q];for(let Q=156;Q<512;Q++)Z+=$[Q];return Z}function OD($,Z){if($=$.toString(8),$.length>Z)return"7777777777777777777".slice(0,Z)+" ";return"0000000000000000000".slice(0,Z-$.length)+$+" "}function Qc4($,Z,Q){Z[Q]=128;for(let X=11;X>0;X--)Z[Q+X]=$&255,$=Math.floor($/256)}function Xc4($,Z,Q){if($.toString(8).length>11)Qc4($,Z,Q);else c4.write(Z,OD($,11),Q)}function Yc4($){let Z;if($[0]===128)Z=!0;else if($[0]===255)Z=!1;else return null;let Q=[],X;for(X=$.length-1;X>0;X--){let J=$[X];if(Z)Q.push(J);else Q.push(255-J)}let Y=0,G=Q.length;for(X=0;X<G;X++)Y+=Q[X]*Math.pow(256,X);return Z?Y:-1*Y}function BD($,Z,Q){if($=$.subarray(Z,Z+Q),Z=0,$[Z]&128)return Yc4($);else{while(Z<$.length&&$[Z]===32)Z++;let X=eu4(xq$($,32,Z,$.length),$.length,$.length);while(Z<X&&$[Z]===0)Z++;if(X===Z)return 0;return parseInt(c4.toString($.subarray(Z,X)),8)}}function Mu($,Z,Q,X){return c4.toString($.subarray(Z,xq$($,0,Z,Z+Q)),X)}function Z91($){let Z=c4.byteLength($),Q=Math.floor(Math.log(Z)/Math.log(10))+1;if(Z+Q>=Math.pow(10,Q))Q++;return Z+Q+$}});var mq$=v((O6Z,lq$)=>{var{Writable:Nc4,Readable:Uc4,getStreamError:bq$}=$91(),Bc4=t51(),yq$=qu(),Vu=Q91(),Oc4=yq$.alloc(0);class gq${constructor(){this.buffered=0,this.shifted=0,this.queue=new Bc4,this._offset=0}push($){this.buffered+=$.byteLength,this.queue.push($)}shiftFirst($){return this._buffered===0?null:this._next($)}shift($){if($>this.buffered)return null;if($===0)return Oc4;let Z=this._next($);if($===Z.byteLength)return Z;let Q=[Z];while(($-=Z.byteLength)>0)Z=this._next($),Q.push(Z);return yq$.concat(Q)}_next($){let Z=this.queue.peek(),Q=Z.byteLength-this._offset;if($>=Q){let X=this._offset?Z.subarray(this._offset,Z.byteLength):Z;return this.queue.shift(),this._offset=0,this.buffered-=Q,this.shifted+=Q,X}return this.buffered-=$,this.shifted+=$,Z.subarray(this._offset,this._offset+=$)}}class hq$ extends Uc4{constructor($,Z,Q){super();this.header=Z,this.offset=Q,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(bq$(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=cq$(this.header.size),this._parent._update()}_destroy($){this._detach(),$(null)}}class uq$ extends Nc4{constructor($){super($);if(!$)$={};this._buffer=new gq$,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=X91,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=$.filenameEncoding||"utf-8",this._allowUnknownFormat=!!$.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock($){if(this._locked=!1,$){this.destroy($),this._continueWrite($);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=Vu.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch($){return this._continueWrite($),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}if(this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory")return this.emit("entry",this._header,this._createStream(),this._unlockBound),!0;return this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0}_applyLongHeaders(){if(this._gnuLongPath)this._header.name=this._gnuLongPath,this._gnuLongPath=null;if(this._gnuLongLinkPath)this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null;if(this._pax){if(this._pax.path)this._header.name=this._pax.path;if(this._pax.linkpath)this._header.linkname=this._pax.linkpath;if(this._pax.size)this._header.size=parseInt(this._pax.size,10);this._header.pax=this._pax,this._pax=null}}_decodeLongHeader($){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=Vu.decodeLongPath($,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=Vu.decodeLongPath($,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=Vu.decodePax($);break;case"pax-header":this._pax=this._paxGlobal===null?Vu.decodePax($):Object.assign({},this._paxGlobal,Vu.decodePax($));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=cq$(this._header.size);let $=this._buffer.shift(this._header.size);try{this._decodeLongHeader($)}catch(Z){return this._continueWrite(Z),!1}return!0}_consumeStream(){let $=this._buffer.shiftFirst(this._missing);if($===null)return!1;this._missing-=$.byteLength;let Z=this._stream.push($);if(this._missing===0){if(this._stream.push(null),Z)this._stream._detach();return Z&&this._locked===!1}return Z}_createStream(){return new hq$(this,this._header,this._offset)}_update(){while(this._buffer.buffered>0&&!this.destroying){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let $=this._buffer.shiftFirst(this._missing);if($!==null)this._missing-=$.byteLength;continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite($){let Z=this._callback;this._callback=X91,Z($)}_write($,Z){this._callback=Z,this._buffer.push($),this._update()}_final($){this._finished=this._missing===0&&this._buffer.buffered===0,$(this._finished?null:Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy($){if(this._stream)this._stream.destroy(bq$(this));$(null)}[Symbol.asyncIterator](){let $=null,Z=null,Q=null,X=null,Y=null,G=this;return this.on("entry",W),this.on("error",(N)=>{$=N}),this.on("close",H),{[Symbol.asyncIterator](){return this},next(){return new Promise(K)},return(){return F(null)},throw(N){return F(N)}};function J(N){if(!Y)return;let U=Y;Y=null,U(N)}function K(N,U){if($)return U($);if(X){N({value:X,done:!1}),X=null;return}if(Z=N,Q=U,J(null),G._finished&&Z)Z({value:void 0,done:!0}),Z=Q=null}function W(N,U,B){if(Y=B,U.on("error",X91),Z)Z({value:U,done:!1}),Z=Q=null;else X=U}function H(){if(J($),!Z)return;if($)Q($);else Z({value:void 0,done:!0});Z=Q=null}function F(N){return G.destroy(N),J(N),new Promise((U,B)=>{if(G.destroyed)return U({value:void 0,done:!0});G.once("close",function(){if(N)B(N);else U({value:void 0,done:!0})})})}}}lq$.exports=function(Z){return new uq$(Z)};function X91(){}function cq$($){return $&=511,$&&512-$}});var iq$=v((L6Z,Y91)=>{var dq$={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{Y91.exports=K0("fs").constants||dq$}catch{Y91.exports=dq$}});var sq$=v((D6Z,aq$)=>{var{Readable:Lc4,Writable:Dc4,getStreamError:pq$}=$91(),Hv=qu(),ku=iq$(),fP0=Q91(),nq$=Hv.alloc(1024);class tq$ extends Dc4{constructor($,Z,Q){super({mapWritable:Ec4,eagerOpen:!0});if(this.written=0,this.header=Z,this._callback=Q,this._linkname=null,this._isLinkname=Z.type==="symlink"&&!Z.linkname,this._isVoid=Z.type!=="file"&&Z.type!=="contiguous-file",this._finished=!1,this._pack=$,this._openCallback=null,this._pack._stream===null)this._pack._stream=this;else this._pack._pending.push(this)}_open($){if(this._openCallback=$,this._pack._stream===this)this._continueOpen()}_continuePack($){if(this._callback===null)return;let Z=this._callback;this._callback=null,Z($)}_continueOpen(){if(this._pack._stream===null)this._pack._stream=this;let $=this._openCallback;if(this._openCallback=null,$===null)return;if(this._pack.destroying)return $(Error("pack stream destroyed"));if(this._pack._finalized)return $(Error("pack stream is already finalized"));if(this._pack._stream=this,!this._isLinkname)this._pack._encode(this.header);if(this._isVoid)this._finish(),this._continuePack(null);$(null)}_write($,Z){if(this._isLinkname)return this._linkname=this._linkname?Hv.concat([this._linkname,$]):$,Z(null);if(this._isVoid){if($.byteLength>0)return Z(Error("No body allowed for this entry"));return Z()}if(this.written+=$.byteLength,this._pack.push($))return Z();this._pack._drain=Z}_finish(){if(this._finished)return;if(this._finished=!0,this._isLinkname)this.header.linkname=this._linkname?Hv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);rq$(this._pack,this.header.size),this._pack._done(this)}_final($){if(this.written!==this.header.size)return $(Error("Size mismatch"));this._finish(),$(null)}_getError(){return pq$(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy($){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),$()}}class oq$ extends Lc4{constructor($){super($);this._drain=G91,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry($,Z,Q){if(this._finalized||this.destroying)throw Error("already finalized or destroyed");if(typeof Z==="function")Q=Z,Z=null;if(!Q)Q=G91;if(!$.size||$.type==="symlink")$.size=0;if(!$.type)$.type=wc4($.mode);if(!$.mode)$.mode=$.type==="directory"?493:420;if(!$.uid)$.uid=0;if(!$.gid)$.gid=0;if(!$.mtime)$.mtime=new Date;if(typeof Z==="string")Z=Hv.from(Z);let X=new tq$(this,$,Q);if(Hv.isBuffer(Z))return $.size=Z.byteLength,X.write(Z),X.end(),X;if(X._isVoid)return X;return X}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}if(this._finalized)return;this._finalized=!0,this.push(nq$),this.push(null)}_done($){if($!==this._stream)return;if(this._stream=null,this._finalizing)this.finalize();if(this._pending.length)this._pending.shift()._continueOpen()}_encode($){if(!$.pax){let Z=fP0.encode($);if(Z){this.push(Z);return}}this._encodePax($)}_encodePax($){let Z=fP0.encodePax({name:$.name,linkname:$.linkname,pax:$.pax}),Q={name:"PaxHeader",mode:$.mode,uid:$.uid,gid:$.gid,size:Z.byteLength,mtime:$.mtime,type:"pax-header",linkname:$.linkname&&"PaxHeader",uname:$.uname,gname:$.gname,devmajor:$.devmajor,devminor:$.devminor};this.push(fP0.encode(Q)),this.push(Z),rq$(this,Z.byteLength),Q.size=$.size,Q.type=$.type,this.push(fP0.encode(Q))}_doDrain(){let $=this._drain;this._drain=G91,$()}_predestroy(){let $=pq$(this);if(this._stream)this._stream.destroy($);while(this._pending.length){let Z=this._pending.shift();Z.destroy($),Z._continueOpen()}this._doDrain()}_read($){this._doDrain(),$()}}aq$.exports=function(Z){return new oq$(Z)};function wc4($){switch($&ku.S_IFMT){case ku.S_IFBLK:return"block-device";case ku.S_IFCHR:return"character-device";case ku.S_IFDIR:return"directory";case ku.S_IFIFO:return"fifo";case ku.S_IFLNK:return"symlink"}return"file"}function G91(){}function rq$($,Z){if(Z&=511,Z)$.push(nq$.subarray(0,512-Z))}function Ec4($){return Hv.isBuffer($)?$:Hv.from($)}});var eq$=v((jc4)=>{jc4.extract=mq$();jc4.pack=sq$()});var QM$=v((E6Z,ZM$)=>{ZM$.exports=$M$;function $M$($,Z){if($&&Z)return $M$($)(Z);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(X){Q[X]=$[X]}),Q;function Q(){var X=Array(arguments.length);for(var Y=0;Y<X.length;Y++)X[Y]=arguments[Y];var G=$.apply(this,X),J=X[X.length-1];if(typeof G==="function"&&G!==J)Object.keys(J).forEach(function(K){G[K]=J[K]});return G}}});var K91=v((j6Z,J91)=>{var XM$=QM$();J91.exports=XM$(bP0);J91.exports.strict=XM$(YM$);bP0.proto=bP0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return bP0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return YM$(this)},configurable:!0})});function bP0($){var Z=function(){if(Z.called)return Z.value;return Z.called=!0,Z.value=$.apply(this,arguments)};return Z.called=!1,Z}function YM$($){var Z=function(){if(Z.called)throw Error(Z.onceError);return Z.called=!0,Z.value=$.apply(this,arguments)},Q=$.name||"Function wrapped with `once`";return Z.onceError=Q+" shouldn't be called more than once",Z.called=!1,Z}});var KM$=v((z6Z,JM$)=>{var Ac4=K91(),Tc4=function(){},Rc4=global.Bare?queueMicrotask:process.nextTick.bind(process),Ic4=function($){return $.setHeader&&typeof $.abort==="function"},qc4=function($){return $.stdio&&Array.isArray($.stdio)&&$.stdio.length===3},GM$=function($,Z,Q){if(typeof Z==="function")return GM$($,null,Z);if(!Z)Z={};Q=Ac4(Q||Tc4);var{_writableState:X,_readableState:Y}=$,G=Z.readable||Z.readable!==!1&&$.readable,J=Z.writable||Z.writable!==!1&&$.writable,K=!1,W=function(){if(!$.writable)H()},H=function(){if(J=!1,!G)Q.call($)},F=function(){if(G=!1,!J)Q.call($)},N=function(w){Q.call($,w?Error("exited with error code: "+w):null)},U=function(w){Q.call($,w)},B=function(){Rc4(O)},O=function(){if(K)return;if(G&&!(Y&&(Y.ended&&!Y.destroyed)))return Q.call($,Error("premature close"));if(J&&!(X&&(X.ended&&!X.destroyed)))return Q.call($,Error("premature close"))},D=function(){$.req.on("finish",H)};if(Ic4($))if($.on("complete",H),$.on("abort",B),$.req)D();else $.on("request",D);else if(J&&!X)$.on("end",W),$.on("close",W);if(qc4($))$.on("exit",N);if($.on("end",F),$.on("finish",H),Z.error!==!1)$.on("error",U);return $.on("close",B),function(){if(K=!0,$.removeListener("complete",H),$.removeListener("abort",B),$.removeListener("request",D),$.req)$.req.removeListener("finish",H);$.removeListener("end",W),$.removeListener("close",W),$.removeListener("finish",H),$.removeListener("exit",N),$.removeListener("end",F),$.removeListener("error",U),$.removeListener("close",B)}};JM$.exports=GM$});var FM$=v((P6Z,HM$)=>{var Mc4=K91(),Vc4=KM$(),yP0;try{yP0=K0("fs")}catch($){}var Pa=function(){},kc4=typeof process>"u"?!1:/^v?\.0/.test(process.version),gP0=function($){return typeof $==="function"},Sc4=function($){if(!kc4)return!1;if(!yP0)return!1;return($ instanceof(yP0.ReadStream||Pa)||$ instanceof(yP0.WriteStream||Pa))&&gP0($.close)},Cc4=function($){return $.setHeader&&gP0($.abort)},_c4=function($,Z,Q,X){X=Mc4(X);var Y=!1;$.on("close",function(){Y=!0}),Vc4($,{readable:Z,writable:Q},function(J){if(J)return X(J);Y=!0,X()});var G=!1;return function(J){if(Y)return;if(G)return;if(G=!0,Sc4($))return $.close(Pa);if(Cc4($))return $.abort();if(gP0($.destroy))return $.destroy();X(J||Error("stream was destroyed"))}},WM$=function($){$()},vc4=function($,Z){return $.pipe(Z)},xc4=function(){var $=Array.prototype.slice.call(arguments),Z=gP0($[$.length-1]||Pa)&&$.pop()||Pa;if(Array.isArray($[0]))$=$[0];if($.length<2)throw Error("pump requires two streams per minimum");var Q,X=$.map(function(Y,G){var J=G<$.length-1,K=G>0;return _c4(Y,J,K,function(W){if(!Q)Q=W;if(W)X.forEach(WM$);if(J)return;X.forEach(WM$),Z(Q)})});return $.reduce(vc4)};HM$.exports=xc4});var jM$=v((gc4)=>{var NM$=eq$(),UM$=FM$(),BM$=K0("fs"),E9=K0("path"),Aa=(global.Bare?global.Bare.platform:process.platform)==="win32";gc4.pack=function(Z,Q){if(!Z)Z=".";if(!Q)Q={};let X=Q.fs||BM$,Y=Q.ignore||Q.filter||Ta,G=Q.mapStream||wM$,J=yc4(X,Q.dereference?X.stat:X.lstat,Z,Y,Q.entries,Q.sort),K=Q.strict!==!1,W=typeof Q.umask==="number"?~Q.umask:~OM$(),H=Q.pack||NM$.pack(),F=Q.finish||Ta,N=Q.map||Ta,U=typeof Q.dmode==="number"?Q.dmode:0,B=typeof Q.fmode==="number"?Q.fmode:0;if(Q.strip)N=EM$(N,Q.strip);if(Q.readable)U|=parseInt(555,8),B|=parseInt(444,8);if(Q.writable)U|=parseInt(333,8),B|=parseInt(222,8);w();function O(E,j){X.readlink(E9.join(Z,E),function(z,A){if(z)return H.destroy(z);j.linkname=W91(A),H.entry(j,w)})}function D(E,j,z){if(H.destroyed)return;if(E)return H.destroy(E);if(!j){if(Q.finalize!==!1)H.finalize();return F(H)}if(z.isSocket())return w();let A={name:W91(j),mode:(z.mode|(z.isDirectory()?U:B))&W,mtime:z.mtime,size:z.size,type:"file",uid:z.uid,gid:z.gid};if(z.isDirectory())return A.size=0,A.type="directory",A=N(A)||A,H.entry(A,w);if(z.isSymbolicLink())return A.size=0,A.type="symlink",A=N(A)||A,O(j,A);if(A=N(A)||A,!z.isFile()){if(K)return H.destroy(Error("unsupported type for "+j));return w()}let P=H.entry(A,w),I=G(X.createReadStream(E9.join(Z,j),{start:0,end:A.size>0?A.size-1:A.size}),A);I.on("error",function(q){P.destroy(q)}),UM$(I,P)}function w(E){if(E)return H.destroy(E);J(D)}return H};function fc4($){return $.length?$[$.length-1]:null}function bc4(){return!global.Bare&&process.getuid?process.getuid():-1}function OM$(){return!global.Bare&&process.umask?process.umask():0}gc4.extract=function(Z,Q){if(!Z)Z=".";if(!Q)Q={};Z=E9.resolve(Z);let X=Q.fs||BM$,Y=Q.ignore||Q.filter||Ta,G=Q.mapStream||wM$,J=Q.chown!==!1&&!Aa&&bc4()===0,K=Q.extract||NM$.extract(),W=[],H=new Date,F=typeof Q.umask==="number"?~Q.umask:~OM$(),N=Q.strict!==!1,U=Q.validateSymlinks!==!1,B=Q.map||Ta,O=typeof Q.dmode==="number"?Q.dmode:0,D=typeof Q.fmode==="number"?Q.fmode:0;if(Q.strip)B=EM$(B,Q.strip);if(Q.readable)O|=parseInt(555,8),D|=parseInt(444,8);if(Q.writable)O|=parseInt(333,8),D|=parseInt(222,8);if(K.on("entry",w),Q.finish)K.on("finish",Q.finish);return K;function w(P,I,q){P=B(P)||P,P.name=W91(P.name);let M=E9.join(Z,E9.join("/",P.name));if(Y(M,P))return I.resume(),q();let S=E9.join(M,".")===E9.join(Z,".")?Z:E9.dirname(M);DM$(X,S,E9.join(Z,"."),function(p,Y0){if(p)return q(p);if(!Y0)return q(Error(S+" is not a valid path"));if(P.type==="directory")return W.push([M,P.mtime]),A(M,{fs:X,own:J,uid:P.uid,gid:P.gid,mode:P.mode},m);A(S,{fs:X,own:J,uid:P.uid,gid:P.gid,mode:493},function(L0){if(L0)return q(L0);switch(P.type){case"file":return y();case"link":return b();case"symlink":return f()}if(N)return q(Error("unsupported type for "+M+" ("+P.type+")"));I.resume(),q()})});function m(p){if(p)return q(p);j(M,P,function(Y0){if(Y0)return q(Y0);if(Aa)return q();z(M,P,q)})}function f(){if(Aa)return q();X.unlink(M,function(){let p=E9.resolve(E9.dirname(M),P.linkname);if(!l(p)&&U)return q(Error(M+" is not a valid symlink"));LM$(X,p,E9.join(Z,"."),function(Y0,L0){if(Y0)return q(Y0);if(!L0&&U)return q(Error(M+" is not a valid symlink"));X.symlink(P.linkname,M,m)})})}function b(){if(Aa)return q();X.unlink(M,function(){let p=E9.join(Z,E9.join("/",P.linkname));X.realpath(p,function(Y0,L0){if(Y0||!l(L0))return q(Error(M+" is not a valid hardlink"));X.link(L0,M,function(r){if(r&&r.code==="EPERM"&&Q.hardlinkAsFilesFallback)return I=X.createReadStream(L0),y();m(r)})})})}function l(p){return p===Z||p.startsWith(Z+E9.sep)}function y(){let p=X.createWriteStream(M),Y0=G(I,P);p.on("error",function(L0){Y0.destroy(L0)}),UM$(Y0,p,function(L0){if(L0)return q(L0);p.on("close",m)})}}function E(P,I){let q;while((q=fc4(W))&&P.slice(0,q[0].length)!==q[0])W.pop();if(!q)return I();X.utimes(q[0],H,q[1],I)}function j(P,I,q){if(Q.utimes===!1)return q();if(I.type==="directory")return X.utimes(P,H,I.mtime,q);if(I.type==="symlink")return E(P,q);X.utimes(P,H,I.mtime,function(M){if(M)return q(M);E(P,q)})}function z(P,I,q){let M=I.type==="symlink",S=M?X.lchmod:X.chmod,m=M?X.lchown:X.chown;if(!S)return q();let f=(I.mode|(I.type==="directory"?O:D))&F;if(m&&J)m.call(X,P,I.uid,I.gid,b);else b(null);function b(l){if(l)return q(l);if(!S)return q();S.call(X,P,f,q)}}function A(P,I,q){X.stat(P,function(M){if(!M)return q(null);if(M.code!=="ENOENT")return q(M);X.mkdir(P,{mode:I.mode,recursive:!0},function(S,m){if(S)return q(S);z(P,I,q)})})}};function LM$($,Z,Q,X){if(Z===Q)return X(null,!0);if(!Z.startsWith(Q+E9.sep))return X(null,!1);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return X(Y);if(Y||!G.isSymbolicLink())return LM$($,E9.join(Z,".."),Q,X);X(null,!1)})}function DM$($,Z,Q,X){if(Z===Q)return X(null,!0);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return X(Y);if(Y||G.isDirectory())return DM$($,E9.join(Z,".."),Q,X);X(null,!1)})}function Ta(){}function wM$($){return $}function W91($){return Aa?$.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):$}function yc4($,Z,Q,X,Y,G){if(!Y)Y=["."];let J=Y.slice(0);return function(W){if(!J.length)return W(null);let H=J.shift(),F=E9.join(Q,H);Z.call($,F,function(N,U){if(N)return W(Y.indexOf(H)===-1&&N.code==="ENOENT"?null:N);if(!U.isDirectory())return W(null,H,U);$.readdir(F,function(B,O){if(B)return W(B);if(G)O.sort();for(let D=0;D<O.length;D++)if(!X(E9.join(Q,H,O[D])))J.push(E9.join(H,O[D]));W(null,H,U)})})}}function EM$($,Z){return function(Q){Q.name=Q.name.split("/").slice(Z).join("/");let X=Q.linkname;if(X&&(Q.type==="link"||E9.isAbsolute(X)))Q.linkname=X.split("/").slice(Z).join("/");return $(Q)}}});var cc4,lc4;var zM$=L(()=>{p51();cc4=k(Kq$(),1),lc4=k(jM$(),1)});var hP0=()=>{};var PM$=L(()=>{sz0()});var AM$=L(()=>{qP0();IP0();hP0()});var TM$=()=>{};var RM$=()=>{};var IM$=L(()=>{lI$();d51();qP0();nI$();l51();p51();tI$();oI$();rI$();aI$();m51();sI$();zM$();hP0();PM$();AM$();TM$();RM$();hP0()});var uP0=L(()=>{J4();n41()});async function lP0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(mc4)});if(!Z.ok)return null;let Q=await Z.json();if(typeof Q==="object"&&Q!==null&&typeof Q.bootId==="string"&&typeof Q.ready==="boolean"&&Q.setup&&typeof Q.setup.running==="boolean"&&typeof Q.setup.done==="boolean")return Q;return null}catch{return null}}async function F91($){for(let Z=0;Z<qM$;Z++){if(await lP0($)!==null)return;let Q=(Math.random()*2-1)*dc4;await W$(MM$+Q)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${qM$*MM$/1000}s`)}async function Fv($,Z,Q,X,Y){return ic4($,Z,"POST",Q,X,Y)}async function ic4($,Z,Q,X,Y,G){let J={...X};if(Y&&Y.rotateToken!==void 0)J.auth=Y;let K=await fetch(`${$}/_sandbox/config`,{method:Q,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify(J),signal:AbortSignal.timeout(G?.timeoutMs??H91)}),W=await K.text();if(!K.ok)throw new cP0(K.status,W);return JSON.parse(W)}async function VM$($,Z,Q){let X=await fetch(`${$}/_sandbox/setup/${Q}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(H91)});if(!X.ok)throw Error(`sandbox daemon /_sandbox/setup/${Q} returned ${X.status}: ${await X.text()}`)}async function kM$($,Z,Q){let X=await fetch(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:Q,signal:AbortSignal.timeout(H91)}),Y=await X.text();if(!X.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${X.status}: ${Y}`);return JSON.parse(Y)}async function Ra($,Z,Q,X){let Y=new Headers(X.headers);for(let K of pc4)Y.delete(K);Y.set("authorization",`Bearer ${Z}`);let G=X.method!=="GET"&&X.method!=="HEAD",J=`${$}${Q.startsWith("/")?Q:`/${Q}`}`;return fetch(J,{method:X.method,headers:Y,body:G?X.body:void 0,redirect:"manual",signal:X.signal,duplex:G?"half":void 0})}var cP0,mc4=500,H91=30000,qM$=25,MM$=200,dc4=50,pc4;var SM$=L(()=>{uP0();cP0=class cP0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};pc4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*vM$($){let Z=$.now??(()=>Date.now()),Q=Z(),X=$.schedulingTimeoutMs??tc4,Y={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:Q},G=[],J=null,K=!1,W=(j)=>{if(K)return;if(J){let z=J;J=null,z(j)}else G.push(j)},H=()=>{if(G.length>0)return Promise.resolve(G.shift());if(K)return Promise.resolve(null);return new Promise((j)=>{J=j})},F=()=>{if(K)return;if(K=!0,J){let j=J;J=null,j(null)}},N=new AbortController,U=()=>{N.abort(),F()};if($.signal)if($.signal.aborted)N.abort(),F();else $.signal.addEventListener("abort",U,{once:!0});let B=Math.max(0,X-(Z()-Q)),O=setTimeout(()=>W("tick"),B+100),D,w=new Promise((j)=>{D=j}),E=Promise.allSettled([oc4($.kc,$.namespace,$.claimName,N.signal,Y,W,Z,D),ac4($.kc,$.namespace,$.claimName,N.signal,Y,W),sc4($.kc,$.namespace,$.claimName,w,N.signal,Y,W,Z)]);try{let j=null,z=-1,A=CM$(Y,X,Z);if(j=U91(A),!N91(A))z=_M$(A);if(yield A,N91(A))return;while(!K){if(await H()===null)break;let I=CM$(Y,X,Z);if(N91(I)){let S=U91(I);if(S!==j)j=S,yield I;return}let q=_M$(I);if(q<z)continue;let M=U91(I);if(M!==j)j=M,z=q,yield I}}finally{if(clearTimeout(O),N.abort(),$.signal)$.signal.removeEventListener("abort",U);F(),await E.catch(()=>{})}}function CM$($,Z,Q){let{pod:X,sandbox:Y,events:G,startedAt:J}=$;if(Y.ready)return{kind:"ready"};let K=X.containerWaitingReason;if(K==="ImagePullBackOff"||K==="ErrImagePull")return{kind:"failed",reason:"image-pull-backoff",message:"Sandbox image failed to download. The cluster may be missing pull credentials or the image tag may not exist."};if(K==="CrashLoopBackOff")return{kind:"failed",reason:"crash-loop-backoff",message:"Sandbox crashed during startup and is now in CrashLoopBackOff. Check pod logs."};if(!X.scheduled&&G.lastFailedSchedulingAt!==void 0&&Q()-J>Z)return{kind:"failed",reason:"scheduling-timeout",message:G.failedSchedulingMessage??`Pod could not be scheduled within ${Math.round(Z/1000)}s.`};if(X.containerRunning&&!X.containerReady)return{kind:"warming-daemon",since:J};if(G.hasPulling&&!G.hasPulled)return{kind:"pulling-image",since:J};if(K==="ContainerCreating"||K==="PodInitializing"||X.scheduled&&!X.containerRunning)return{kind:"starting-container",since:J};if(X.scheduledFalseReason==="Unschedulable"||G.lastFailedSchedulingAt!==void 0&&!X.scheduled)return{kind:"waiting-for-capacity",since:J,message:G.failedSchedulingMessage??X.scheduledFalseMessage,nodeClaim:G.nominatedNodeClaim};return{kind:"claiming",since:J}}function N91($){return $.kind==="ready"||$.kind==="failed"}function _M$($){switch($.kind){case"claiming":return 0;case"waiting-for-capacity":return 1;case"pulling-image":return 2;case"starting-container":return 3;case"warming-daemon":return 4;case"ready":case"failed":return 99}}function U91($){switch($.kind){case"claiming":case"pulling-image":case"starting-container":case"warming-daemon":return $.kind;case"waiting-for-capacity":return`waiting-for-capacity:${$.message??""}:${$.nodeClaim??""}`;case"ready":return"ready";case"failed":return`failed:${$.reason}:${$.message}`}}async function oc4($,Z,Q,X,Y,G,J,K){let W=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${nc4}=${Q}`)}`;return mP0({kc:$,path:W,signal:X,label:`pod/${Q}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let F=H.object;if(F.metadata?.name)K(F.metadata.name);rc4(F,Y,J),G("pod")}})}function rc4($,Z,Q){let Y=($.status?.conditions??[]).find((J)=>J.type==="PodScheduled");if(Y?.status==="True")Z.pod.scheduled=!0,Z.pod.scheduledFalseReason=void 0,Z.pod.scheduledFalseMessage=void 0;else if(Y?.status==="False")Z.pod.scheduled=!1,Z.pod.scheduledFalseReason=Y.reason,Z.pod.scheduledFalseMessage=Y.message;let G=($.status?.containerStatuses??[]).find((J)=>J.name===w9.MAIN_CONTAINER_NAME);if(G)Z.pod.containerWaitingReason=G.state?.waiting?.reason,Z.pod.containerRunning=!!G.state?.running,Z.pod.containerReady=G.ready===!0}async function ac4($,Z,Q,X,Y,G){let J=`/apis/${w9.CLAIM_API_GROUP}/${w9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${w9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${Q}`)}`;return mP0({kc:$,path:J,signal:X,label:`sandboxclaim/${Q}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let H=K.object.status?.conditions?.find((F)=>F.type==="Ready");if(!H)return;if(H.status==="True")Y.sandbox.ready=!0,Y.sandbox.notReadyReason=void 0,Y.sandbox.notReadyMessage=void 0;else Y.sandbox.ready=!1,Y.sandbox.notReadyReason=H.reason,Y.sandbox.notReadyMessage=H.message;G("sandbox")}})}async function sc4($,Z,Q,X,Y,G,J,K){let W=await Promise.race([X,new Promise((F)=>{if(Y.aborted){F(Q);return}Y.addEventListener("abort",()=>F(Q),{once:!0})})]);if(Y.aborted)return;let H=`/api/v1/namespaces/${encodeURIComponent(Z)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${W},involvedObject.kind=Pod`)}`;return mP0({kc:$,path:H,signal:Y,label:`events/${Q}`,onEvent:(F)=>{if(F.type!=="ADDED"&&F.type!=="MODIFIED")return;let N=F.object,U=N.reason;if(!U)return;switch(U){case"Pulling":G.events.hasPulling=!0;break;case"Pulled":G.events.hasPulling=!0,G.events.hasPulled=!0;break;case"FailedScheduling":G.events.lastFailedSchedulingAt=K(),G.events.failedSchedulingMessage=N.message;break;case"Nominated":{let B=N.message?.match(/nodeclaim\/([\w-]+)/);if(B)G.events.nominatedNodeClaim=B[1];break}default:return}J("event")}})}async function xM$($){let{kc:Z,namespace:Q,labelSelector:X,signal:Y,onDelete:G}=$,J=`/apis/${w9.CLAIM_API_GROUP}/${w9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Q)}/${w9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(X)}`;return mP0({kc:Z,path:J,signal:Y,label:"sandboxclaim-reaper",onEvent:(K)=>{if(K.type!=="DELETED")return;let W=K.object.metadata?.name;if(W)G(W)}})}async function mP0($){let{kc:Z,path:Q,signal:X,label:Y,onEvent:G}=$,J=0;while(!X.aborted){try{let W=await RG(Z,{method:"GET",path:Q,signal:X,headers:{accept:"application/json"},stream:!0});if(!W.ok||!W.body){try{await W.body?.cancel()}catch{}if(W.status===401||W.status===403){console.warn(`[lifecycle-watcher] ${Y} stopped: watch denied (${W.status} ${W.statusText}). `+"The kubeconfig in use cannot watch SandboxClaims \u2014 if you are running locally, "+"this provider should not be active (check STUDIO_AGENT_SANDBOX_ENABLED).");return}throw Error(`watch handshake failed: ${W.status} ${W.statusText}`)}J=0;for await(let H of D61(W.body)){if(X.aborted)return;try{G(H)}catch(F){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${F instanceof Error?F.message:String(F)}`)}}}catch(W){if(X.aborted)return;let H=W instanceof Error?W.message:String(W);console.warn(`[lifecycle-watcher] ${Y} watch ended: ${H}`)}if(X.aborted)return;let K=N7(5000,250,J,2,0);J+=1,await W$(K,{signal:X}).catch(()=>{})}}var nc4="studio.decocms.com/sandbox-handle",tc4=300000;var fM$=L(()=>{J4();jK0();TK0()});import{z as iJ}from"zod";function bM$($){if(!$||$.trim()==="")return[];let Z=iJ.array(ec4).parse(JSON.parse($)),Q=new Set;for(let X of Z){if(Q.has(X.name))throw Error(`STUDIO_SANDBOX_TENANT_POOLS: duplicate pool name ${X.name}`);Q.add(X.name)}return Z}function $l4($){try{let[Z,Q]=new URL($).pathname.replace(/^\/+/,"").split("/"),X=Q?.replace(/\.git$/,"");return Z&&X?`${Z}/${X}`.toLowerCase():null}catch{return null}}function yM$($,Z){let{orgId:Q,cloneUrl:X}=Z;if(Z.purpose==="harness-run")return null;if(!Q||!X)return null;let Y=$l4(X);if(!Y)return null;return $.find((G)=>G.orgId===Q&&G.repo.toLowerCase()===Y)??null}function gM$($,Z,Q){return $?.name??(Z?Q:"none")}function Zl4($,Z){return $==="harness-run"?`${Z}-medium`:Z}async function hM$($){let Z=Zl4($.purpose,$.templateName);if(Z===$.templateName)return{name:Z,probe:$.probe};let Q=$.probe!==null&&$.now-$.probe.checkedAt<$.ttlMs?$.probe:{checkedAt:$.now,present:await $.exists(Z)};if(Q.present)return{name:Z,probe:Q};if($.probe?.present!==!1)$.onAbsent?.(Z);return{name:$.templateName,probe:Q}}function uM$($,Z,Q){let X=Q.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===X)}function cM$($){return`https://github.com/${$.repo}.git`}var ec4;var B91=L(()=>{ec4=iJ.object({name:iJ.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:iJ.string().min(1),repo:iJ.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:iJ.string().min(1).optional(),branch:iJ.string().min(1).default("main"),workload:iJ.object({runtime:iJ.enum(["node","bun","deno"]).default("node"),packageManager:iJ.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:iJ.string().optional(),devPort:iJ.number().int().positive().optional()}).default({runtime:"node"})})});async function lM$($,Z,Q){let X=new Map;for(let Y of $){let G=Z(Y);if(!G)continue;let J=X.get(G);if(J)J.push(Y);else X.set(G,[Y])}await Promise.allSettled([...X.values()].map(async(Y)=>{for(let G of Y)await Q(G).catch(()=>{})}))}import{createHash as Ql4,randomBytes as Xl4,randomUUID as Yl4}from"crypto";import*as oM$ from"net";import{PassThrough as Gl4}from"stream";function mM$($){if($ instanceof Error)return $.message;if($&&typeof $==="object"){let Z=$;if(Z.error instanceof Error)return Z.error.message;if(typeof Z.message==="string"&&Z.message)return Z.message}return String($)}class z91{records=new Map;inflight=new ZK0;activeGauge=new $K0;stateStore;previewUrlPattern;kubeConfig;capacityProbe;portForward;namespace;sandboxTemplateName;envName;tokenGenerator;idleTtlMs;metrics;previewGateway;sentinelToken;mintCloneUrl;mintOrgFsConfig;tenantPools;tenantPoolRefreshMs;poolPods=new Map;mediumTemplateProbe=null;dirtyPools=new Set;closed=!1;claimWatchAbort=new AbortController;constructor($={}){this.stateStore=$.stateStore??null,this.previewUrlPattern=$.previewUrlPattern??null,this.kubeConfig=$.kubeConfig??jl4(),this.portForward=new n51(this.kubeConfig),this.namespace=$.namespace??Jl4,this.sandboxTemplateName=$.sandboxTemplateName??Kl4,this.envName=Il4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>Xl4(Hl4).toString("hex")),this.idleTtlMs=$.idleTtlMs??Nl4,this.metrics=$.meter?El4($.meter):null,this.previewGateway=$.previewGateway&&$.previewUrlPattern?{...$.previewGateway}:null;let Z=$.sentinelToken?.trim()??"";if(this.sentinelToken=Z.length>0?Z:null,this.mintCloneUrl=$.mintCloneUrl,this.mintOrgFsConfig=$.mintOrgFsConfig,this.tenantPools=this.sentinelToken!==null?$.tenantPools??[]:[],this.sentinelToken===null&&($.tenantPools?.length??0)>0)console.warn(`[${B6}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??Bl4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${PX.env}=${this.envName}`]:[]].join(",");xM$({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let Q=vz($);if(Q.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(Q,()=>QK0(this.stateStore,$,(X)=>this.ensureLocked($,Q,Z,X)))}async delete($){let Z=await this.getRecord($);if(this.records.delete($),Z)this.dropRecord(Z);if(await this.deleteHttpRouteIfManaged($).catch((Q)=>{console.warn(`[${B6}] HTTPRoute delete failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`)}),await Lu(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id);else await this.stateStore.deleteByHandle($)}lastTermination($){return lP$(this.kubeConfig,this.namespace,PX.sandboxHandle,$,w9.MAIN_CONTAINER_NAME)}async alive($){return await sN(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return vM$({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=eP$(this.kubeConfig,this.namespace),this.capacityProbe()}async getPreviewUrl($){let Z=await this.getRecord($);if(!Z)return null;return this.composePreviewUrl(Z)}async proxyDaemonRequest($,Z,Q){let X=await this.getRecord($);if(!X&&this.previewUrlPattern&&this.stateStore){let W=await this.stateStore.getByHandle($),H=W?.state,F=H?.token;if(W&&F){let U=`http://${H?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${GU}`;try{let B=await Ra(U,F,Z,Q);if(B.status!==404)return B;try{await B.body?.cancel()}catch{}}catch{}}}if(!X)X=await this.resurrectByHandle($);if(!X)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let Y=X,G=performance.now(),J=0,K=!(Q.body instanceof ReadableStream);try{let W=await Ra(X.daemonUrl,X.token,Z,Q);if(W.status===401&&K){this.invalidateRecord($);let H=await this.getRecord($).catch(()=>null)??await this.resurrectByHandle($).catch(()=>null);if(H){try{await W.body?.cancel()}catch{}Y=H,W=await Ra(H.daemonUrl,H.token,Z,Q)}}return J=W.status,W}catch(W){if(!K)throw W;this.invalidateRecord($);let H=await this.resurrectByHandle($)??await this.getRecord($).catch(()=>null);if(!H)throw W;Y=H;let F=await Ra(H.daemonUrl,H.token,Z,Q);return J=F.status,F}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let Q=await sN(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Q||Q.metadata?.deletionTimestamp)return!1;return await this.inflight.run(Z,async()=>{let Y=this.records.get(Z);if(Y)return this.toSandbox(Y);let G=await this.adopt($,Z,Q);if(!G)throw Error(`cannot adopt live claim ${Z}`);return QK0(this.stateStore,$,(J)=>this.finish(G,J,!0,!0,"adopt"))}).catch(()=>null)!=null}async resolvePreviewUpstreamUrl($){if(this.previewUrlPattern)return`http://${await this.resolveServiceNameForHandle($)}.${this.namespace}.svc.cluster.local:${GU}`;let Z=await this.getRecord($);if(Z)return Z.daemonUrl;let Q=await this.resurrectByHandle($);return Q?Q.daemonUrl:null}async resolveServiceNameForHandle($){let Z=this.records.get($);if(Z)return Z.adoptedSandboxName;if(this.stateStore){let X=(await this.stateStore.getByHandle($).catch(()=>null))?.state?.adoptedSandboxName;if(X)return X}return $}async proxyPreviewRequest($,Z){let Q=performance.now(),X=this.records.get($)??null,Y=0;try{let G=await this.resolvePreviewUpstreamUrl($);if(!G){Y=404;let O=L91(404,{error:"sandbox not found"});return O.headers.set(Uv,"1"),O}let J=new URL(Z.url);if((J.pathname==="/_sandbox"||J.pathname.startsWith("/_sandbox/"))&&Z.method!=="GET")return Y=404,L91(404,{error:"not found"});let W=(O)=>`${O}${J.pathname}${J.search}`,H=new Headers(Z.headers);for(let O of Dl4)H.delete(O);let F=Z.method!=="GET"&&Z.method!=="HEAD",N={method:Z.method,headers:H,body:F?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:F?"half":void 0},U;try{U=await fetch(W(G),N)}catch(O){let D=`${G}${J.pathname}`;if(console.warn(`[${B6}] preview fetch to ${D} failed: ${O instanceof Error?O.message:String(O)}`),Z.method==="GET"||Z.method==="HEAD"){if(this.invalidateRecord($),await this.resurrectByHandle($).catch(()=>null)){let j=await this.resolvePreviewUpstreamUrl($);if(j)try{U=await fetch(W(j),N);let z=new Headers;for(let[A,P]of U.headers.entries())if(!pM$.includes(A.toLowerCase()))z.set(A,P);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:z})}catch(z){console.warn(`[${B6}] preview fetch retry to ${D} failed: ${z instanceof Error?z.message:String(z)}`)}}}else this.invalidateRecord($);Y=502;let w=L91(502,{error:"sandbox daemon unreachable"});return w.headers.set(Uv,"1"),w}let B=new Headers;for(let[O,D]of U.headers.entries())if(!pM$.includes(O.toLowerCase()))B.set(O,D);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:B})}finally{this.recordProxyDuration("preview",Y,X,performance.now()-Q,$)}}async ensureLocked($,Z,Q,X){if(Q.image)console.warn(`[${B6}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${Q.image}`);if(X){let J=await X.get($);if(J){let K=await this.rehydrate($,Z,J);if(K)return await this.refreshDaemonGitCredential(K,Q),await this.relayOrgFsConfig(K.daemonUrl,K.token,Q.orgFsConfigJson),this.finish(K,X,!1,!0,"resume");await X.delete($)}}let Y=await sN(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await PK0(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${B6}] wait for terminating claim ${Z} failed: ${J instanceof Error?J.message:String(J)}`)});else{let J=await this.adopt($,Z,Y).catch((K)=>{return console.warn(`[${B6}] adopt ${Z} failed, recreating: ${K instanceof Error?K.message:String(K)}`),null});if(J)return await this.refreshDaemonGitCredential(J,Q),await this.relayOrgFsConfig(J.daemonUrl,J.token,Q.orgFsConfigJson),this.finish(J,X,!0,!0,"adopt");await Lu(this.kubeConfig,this.namespace,Z).catch(()=>{}),await PK0(this.kubeConfig,this.namespace,Z).catch((K)=>{console.warn(`[${B6}] wait for deleted claim ${Z} failed: ${K instanceof Error?K.message:String(K)}`)})}let G=await this.provision($,Z,Q);return this.finish(G,X,!0,!1,"fresh")}async finish($,Z,Q,X,Y){let G=this.records.get($.handle),J=G!==void 0;if(G&&G.daemonForward!==$.daemonForward)this.closeForwarder(G.daemonForward);if(this.records.set($.handle,$),Q)await this.persist(Z,$);if(X)await AK0(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((K)=>console.warn(`[${B6}] TTL refresh failed for ${$.handle}: ${K instanceof Error?K.message:String(K)}`));if(this.metrics){let K=w91($.tenant);if(this.metrics.ensureOutcome.add(1,{...K,outcome:Y}),!J)this.metrics.active.add(1,K),this.activeGauge.markCounted($.handle)}return this.toSandbox($)}buildEnvMap($,Z){let Q={},X=[];for(let[Y,G]of Object.entries($.env??{}))if(Fl4.has(Y))X.push(Y);else Q[Y]=G;if(X.length>0)console.warn(`[${B6}] opts.env keys overlap reserved bootstrap names and were dropped: ${X.join(",")}`);return{...Q,DAEMON_TOKEN:Z.token,DAEMON_BOOT_ID:Z.daemonBootId,APP_ROOT:Z.workdir,PROXY_PORT:String(GU)}}async resolveTemplateName($){let{name:Z,probe:Q}=await hM$({purpose:$,templateName:this.sandboxTemplateName,probe:this.mediumTemplateProbe,now:Date.now(),ttlMs:Wl4,exists:(X)=>gP$(this.kubeConfig,this.namespace,X),onAbsent:(X)=>console.warn(`[${B6}] SandboxTemplate ${X} not found (or not readable) \u2014 harness-run claims fall back to ${this.sandboxTemplateName}. Upgrade the sandbox-env chart to the version that renders it.`)});return this.mediumTemplateProbe=Q,Z}buildClaim($,Z,Q,X){let Y=this.sentinelToken!==null,G=yM$(this.tenantPools,{orgId:Z.tenant?.orgId,cloneUrl:Z.repo?.cloneUrl,purpose:Z.purpose}),J=Y?[]:Object.entries(this.buildEnvMap(Z,Q)).sort(([H],[F])=>H<F?-1:H>F?1:0).map(([H,F])=>({name:H,value:F})),K=Vl4(Z),W=Object.keys(K).length>0;return{apiVersion:`${w9.CLAIM_API_GROUP}/${w9.CLAIM_API_VERSION}`,kind:"SandboxClaim",metadata:{name:$,namespace:this.namespace,labels:{"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[PX.env]:this.envName}:{},...D91(Z.tenant)},...W?{annotations:K}:{}},spec:{sandboxTemplateRef:{name:X},additionalPodMetadata:{labels:D91(Z.tenant,{[PX.role]:"claimed",[PX.sandboxHandle]:$,...this.envName?{[PX.env]:this.envName}:{}}),...W?{annotations:K}:{}},env:J,warmpool:gM$(G,Y,X),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,Q){let X=this.tokenGenerator(),Y=Yl4(),G=O91,J=this.buildClaim(Z,Q,{token:X,daemonBootId:Y,workdir:G},await this.resolveTemplateName(Q.purpose));try{await B61(this.kubeConfig,this.namespace,J)}catch(U){if(U instanceof Xa)await PK0(this.kubeConfig,this.namespace,Z),await B61(this.kubeConfig,this.namespace,J);else throw U}let K;try{K=await hP$(this.kubeConfig,this.namespace,Z),await aP$(this.kubeConfig,this.namespace,K)}catch(U){throw await Lu(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}try{await this.ensureServicePortForAdoptedSandbox(K),await this.ensureHttpRouteForHandle(Z,K,Q.tenant??null)}catch(U){throw await Lu(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}let W=await this.openForwarder(K,GU,Z),H=`http://127.0.0.1:${W.localPort}`,F=this.workloadConfigPayload(Q),N=Y;try{if(await F91(H),this.sentinelToken!==null){let U=await lP0(H);if(U)N=U.bootId;await Fv(H,this.sentinelToken,F??{},{rotateToken:X})}else if(F)await Fv(H,X,F);await this.relayOrgFsConfig(H,X,Q.orgFsConfigJson)}catch(U){throw this.closeForwarder(W),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await Lu(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}return{id:$,handle:Z,adoptedSandboxName:K,token:X,workdir:G,daemonUrl:H,daemonForward:W,workload:Q.workload??null,daemonBootId:N,tenant:Q.tenant??null,ensureOpts:vl4(Q)}}workloadConfigPayload($){return YK0({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,extraRepos:$?.extraRepos??[],port:$?.workload?.devPort??dM$,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,Q){if(!Q)return;await kM$($,Z,Q).catch((X)=>console.warn("[org-fs] sidecar config relay failed",X))}async refreshDaemonGitCredential($,Z){let Q=t41(Z);if(!Q)return;try{await Fv($.daemonUrl,$.token,Q)}catch(X){console.warn(`[${B6}] git credential refresh failed for ${$.handle}: ${X instanceof Error?X.message:String(X)}`)}}async withFreshCloneUrl($,Z){if(!this.mintCloneUrl)return $;try{let Q=await this.mintCloneUrl($,Z!==void 0?{bufferMs:Z}:void 0);return Q?{...$,cloneUrl:Q}:$}catch(Q){return console.warn(`[${B6}] clone credential re-mint failed: ${Q instanceof Error?Q.message:String(Q)}`),$}}async withFreshCredentials($){return{...$,...$.repo?{repo:await this.withFreshCloneUrl($.repo)}:{},...$.orgFsConfigJson?{orgFsConfigJson:await _l4($,this.mintOrgFsConfig)}:{}}}startCredentialRefresher(){if(!this.mintCloneUrl)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){if(await W$(Ol4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${B6}] periodic credential refresh failed: ${Z instanceof Error?Z.message:String(Z)}`)}}})()}startTenantPoolReconciler(){if(this.tenantPools.length===0)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){try{await this.reconcileTenantPools()}catch(Z){console.warn(`[${B6}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await W$(Ul4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let Q=uM$(this.tenantPools,$,Z);for(let X of Q)this.dirtyPools.add(X.name);return Q.map((X)=>X.name)}async reconcileTenantPools(){for(let $ of this.tenantPools){let Z=await uP$(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${B6}] tenant pool ${$.name}: no SandboxWarmPool (or no selector yet) in ${this.namespace}`);continue}let Q=this.dirtyPools.delete($.name),X=Z.filter((Y)=>!Y.labels[PX.sandboxHandle]);for(let[Y]of this.poolPods)if(!Z.some((G)=>G.uid===Y))this.poolPods.delete(Y);for(let Y of X){if(this.claimWatchAbort.signal.aborted)return;await this.warmPoolPod($,Y,Q)}this.recordPoolDepth($,Z,X)}}recordPoolDepth($,Z,Q){let X=this.metrics?.poolPods;if(!X)return;let Y=0,G=0;for(let K of Q){let W=this.poolPods.get(K.uid);if(!W)continue;if(W.failures>=dP0)G++;else if(W.lastConfigAt>0)Y++}let J={pool:$.name,org:$.orgId};X.record(Y,{...J,state:"ready"}),X.record(Z.length-Q.length,{...J,state:"bound"}),X.record(Q.length-Y-G,{...J,state:"pending"}),X.record(G,{...J,state:"failed"})}async warmPoolPod($,Z,Q){let X=this.poolPods.get(Z.uid);if(X&&X.failures>=dP0){if(Date.now()-X.lastFailureAt<iM$)return;this.poolPods.set(Z.uid,{...X,failures:0})}let Y=Q||X!==void 0&&Date.now()-X.lastConfigAt>=this.tenantPoolRefreshMs;if(X&&!Y)return;let G={cloneUrl:cM$($),connectionId:$.connectionId,branch:$.branch,userName:"",userEmail:""},J=await this.withFreshCloneUrl(G);if($.connectionId&&J.cloneUrl===G.cloneUrl){this.recordPoolFailure(Z,$,"clone credential mint failed");return}let K=await this.openForwarder(Z.name,GU,Z.name).catch(()=>null);if(!K){this.recordPoolFailure(Z,$,"port-forward failed");return}let W=`http://127.0.0.1:${K.localPort}`;try{await F91(W);let H=this.sentinelToken;if(!H)return;if(!await this.isPoolPodUnbound(Z))return;let F=YK0({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??dM$})??{},{transition:N}=await Fv(W,H,F);if(Y&&N!=="bootstrap"&&await this.isPoolPodUnbound(Z))await VM$(W,H,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${B6}] tenant pool ${$.name}: warmed ${Z.name} (${N})`)}catch(H){this.recordPoolFailure(Z,$,H instanceof Error?H.message:String(H))}finally{this.closeForwarder(K)}}isPoolPodUnbound($){return cP$(this.kubeConfig,this.namespace,$.name,PX.sandboxHandle)}recordPoolFailure($,Z,Q){let X=this.poolPods.get($.uid),Y=(X?.failures??0)+1;this.poolPods.set($.uid,{lastConfigAt:X?.lastConfigAt??0,lastFailureAt:Date.now(),failures:Y});let G=Y>=dP0?` \u2014 backing off ${iM$/60000}min`:"";console.warn(`[${B6}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${dP0})${G}: ${Q}`)}async refreshAllGitCredentials(){await lM$(this.records.values(),($)=>$.ensureOpts?.repo?.connectionId,async($)=>{if(this.claimWatchAbort.signal.aborted)return;let Z=$.ensureOpts?.repo;if(!Z)return;let Q=await this.withFreshCloneUrl(Z,Ll4);await this.refreshDaemonGitCredential($,{...$.ensureOpts,repo:Q}),$.ensureOpts={...$.ensureOpts,repo:Q}})}async rebootstrapDaemon($,Z,Q){if(this.sentinelToken===null)return!1;let X=this.workloadConfigPayload(Q)??{};try{return await Fv($,this.sentinelToken,X,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,Q?.orgFsConfigJson),!0}catch(Y){if(Y instanceof cP0&&Y.status===401)try{return await Fv($,Z,X,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,Q?.orgFsConfigJson),!0}catch(G){return console.warn(`[${B6}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${B6}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await rP$(this.kubeConfig,this.namespace,$,{name:"daemon",port:GU,targetPort:GU})}async ensureHttpRouteForHandle($,Z,Q){if(!this.previewGateway||!this.previewUrlPattern)return;let X=xl4(this.previewUrlPattern,$);if(!X)throw new zZ(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${L61.API_GROUP}/${L61.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:D91(Q??void 0,{[PX.role]:"claimed",[PX.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[PX.env]:this.envName}:{}})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[X],rules:[{backendRefs:[{group:"",kind:"Service",name:Z,port:GU}]}]}};await nP$(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await tP$(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,Q){let X=Q.state;if(!X.adoptedSandboxName&&!X.podName||!X.token)return null;let Y=await sN(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!nM$(Y))return null;let G=Y.status?.sandbox?.name??X.adoptedSandboxName??X.podName??Z,J=await this.openAndProbeDaemon(G,Z);if(!J)return null;if(X.daemonBootId&&X.daemonBootId!==J.bootId){if(this.sentinelToken!==null){let K=X.ensureOpts?await this.withFreshCredentials(X.ensureOpts):null;if(!await this.rebootstrapDaemon(J.daemonUrl,X.token,K))return this.closeForwarder(J.daemonForward),null}else console.warn(`[${B6}] daemon restart detected (handle=${Z}): stored bootId=${X.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,{handle:Z,state:{...X,daemonBootId:J.bootId}}).catch((K)=>console.warn(`[${B6}] bootId persist failed for ${Z}: ${K instanceof Error?K.message:String(K)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:X.token,workdir:X.workdir??O91,daemonUrl:J.daemonUrl,daemonForward:J.daemonForward,workload:X.workload??null,daemonBootId:J.bootId,tenant:X.tenant??null,ensureOpts:X.ensureOpts??null}}async adopt($,Z,Q){if(!nM$(Q))return null;let X=Q.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=zl4(Q);if(!Y)return null;let G=await this.openAndProbeDaemon(X,Z);if(!G)return null;let J=kl4(Q);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(X).catch((K)=>{console.warn(`[${B6}] Service port backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)}),await this.ensureHttpRouteForHandle(Z,X,J).catch((K)=>{console.warn(`[${B6}] HTTPRoute backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)});return{id:$,handle:Z,adoptedSandboxName:X,token:Y,workdir:O91,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let Q=await this.openForwarder($,GU,Z).catch(()=>null);if(!Q)return null;let X=`http://127.0.0.1:${Q.localPort}`,Y=await lP0(X);if(!Y)return this.closeForwarder(Q),null;return{daemonForward:Q,daemonUrl:X,bootId:Y.bootId}}async getRecord($){let Z=this.records.get($);if(Z)return Z;if(!this.stateStore)return null;let Q=await this.stateStore.getByHandle($);if(!Q)return null;let X=await this.rehydrate(Q.id,$,Q);if(X)this.records.set($,X);return X}async resurrectByHandle($){if(!this.stateStore)return null;let Z=await this.stateStore.getByHandle($);if(!Z)return null;let Q=Z.state.ensureOpts;if(!Q)return null;let X=await this.withFreshCredentials(Q);if(vz(Z.id)!==$)return null;return await this.ensure(Z.id,X),this.records.get($)??null}invalidateRecord($){let Z=this.records.get($);if(!Z)return;this.records.delete($),this.dropRecord(Z)}dropRecord($){if(this.closeForwarder($.daemonForward),this.metrics&&this.activeGauge.consume($.handle))this.metrics.active.add(-1,w91($.tenant))}recordProxyDuration($,Z,Q,X,Y){if(!this.metrics)return;this.metrics.proxyDurationMs.record(X,{...w91(Q?.tenant??null),source:$,sandbox_handle:Q?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return XK0(this.previewUrlPattern,$.handle);return`http://127.0.0.1:${$.daemonForward.localPort}/`}toSandbox($){return{handle:$.handle,workdir:$.workdir,previewUrl:this.composePreviewUrl($)}}async persist($,Z){if(!$)return;let Q={adoptedSandboxName:Z.adoptedSandboxName,token:Z.token,workdir:Z.workdir,workload:Z.workload,daemonBootId:Z.daemonBootId,tenant:Z.tenant,...Z.ensureOpts?{ensureOpts:Z.ensureOpts}:{}};await $.put(Z.id,{handle:Z.handle,state:Q})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let Q=await sN(this.kubeConfig,this.namespace,$);if(!Q)return;let X=Sl4(Q.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!X)return;await AK0(this.kubeConfig,this.namespace,$,X).catch((Y)=>console.warn(`[${B6}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await sN(this.kubeConfig,this.namespace,$);if(!Z)return;let Q=Cl4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!Q)return;await AK0(this.kubeConfig,this.namespace,$,Q).catch((X)=>console.warn(`[${B6}] TTL renew failed for ${$}: ${X instanceof Error?X.message:String(X)}`))}openForwarder($,Z,Q=$){let X=Pl4(Q,Z);return new Promise((Y,G)=>{let J=(K,W)=>{let H=oM$.createServer((F)=>this.handleForwardedConnection(F,$,Z,Q));H.once("error",(F)=>{if(F.code==="EADDRINUSE"&&W<wl4){try{H.close()}catch{}let N=E91+(K-E91+1)%rM$;J(N,W+1);return}G(F)}),H.listen(K,"127.0.0.1",()=>{let F=H.address();if(!F||typeof F==="string"){H.close(),G(Error("port-forward listener failed to bind"));return}Y({server:H,localPort:F.port})})};J(X,0)})}handleForwardedConnection($,Z,Q,X){let Y=new Gl4,G=null,J=!1,K=()=>{if(J)return;if(J=!0,Y.destroy(),G)try{G.close()}catch{}if(!$.destroyed)$.destroy()};$.pipe(Y),$.on("error",K),$.on("close",K),this.portForward.portForward(this.namespace,Z,[Q],$,null,Y).then((W)=>{let H=typeof W==="function"?W():W;if(!H){K();return}if(G=H,G.on("close",K),G.on("error",(F)=>{console.warn(`[${B6}] port-forward to ${Z}:${Q} dropped mid-connection: ${mM$(F)}`,JSON.stringify(j91(F))),this.invalidateRecord(X),K()}),J)try{G.close()}catch{}}).catch((W)=>{console.warn(`[${B6}] port-forward to ${Z}:${Q} failed: ${mM$(W)}`,JSON.stringify(j91(W))),this.invalidateRecord(X),K()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${B6}] port-forward close on :${$.localPort} errored: ${Z instanceof Error?Z.message:String(Z)}`)})}close(){if(this.closed)return;this.closed=!0,this.claimWatchAbort.abort();for(let $ of this.records.values())this.dropRecord($);this.records.clear()}}function El4($){return{active:$.createUpDownCounter("studio.sandbox.active",{description:"Active sandbox count, by runner kind, owning org, and daemon impl. Cross-checks the cAdvisor-derived count from the cluster \u2014 divergence between the two indicates orphaned claims (studio deleted but K8s didn't reap) or unattributed pods.",unit:"{sandbox}"}),ensureOutcome:$.createCounter("studio.sandbox.ensure.outcome",{description:"Outcome of each ensure() call: fresh provision, resume from state-store after restart, or adopt of a cluster-side claim studio didn't know about. Cold-start ratio is the primary input for warm-pool sizing.",unit:"{call}"}),proxyDurationMs:$.createHistogram("studio.sandbox.proxy.duration_ms",{description:"Wall-clock latency of studio-mediated requests to the sandbox daemon: tool exec proxies (source=daemon) and preview iframe traffic (source=preview).",unit:"ms"}),poolPods:$.createGauge("studio.sandbox.pool.pods",{description:"Tenant warm pool depth by pool and state: ready (warmed and unbound \u2014 what a claim can actually bind instantly), bound (serving a user), pending (unbound, not yet warmed), failed (gave up after repeated bootstrap failures). Alert on sustained ready=0: a pool that is always empty is doing nothing while costing N pods.",unit:"{pod}"})}}function j91($){let Z=[],Q=$;for(let X=0;X<5&&Q instanceof Error;X++){let Y=Q;if(Z.push({name:Y.name,message:Y.message,...Y.code!==void 0?{code:Y.code}:{},...Y.errno!==void 0?{errno:Y.errno}:{}}),Y.cause===Q)break;Q=Y.cause}if(Q!==void 0&&!(Q instanceof Error)&&Q!==null){let X=Q,Y=X.error instanceof Error?j91(X.error).chain:void 0;Z.push({nonError:String(Q),...typeof X.type==="string"?{type:X.type}:{},...typeof X.message==="string"?{message:X.message}:{},...X.code!==void 0?{code:X.code}:{},...typeof X.reason==="string"?{reason:X.reason}:{},...Y?{error:Y}:{},...Y===void 0&&X.error!==void 0?{rawError:String(X.error)}:{},keys:Object.keys(X)})}return{chain:Z}}function jl4(){let $=new TP0;return $.loadFromDefault(),$}function nM$($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function zl4($){let Z=$.spec?.env;if(!Z)return null;for(let Q of Z)if(Q.name==="DAEMON_TOKEN"&&Q.value)return Q.value;return null}function Pl4($,Z){let Q=Ql4("sha256").update(`${$}:${Z}`).digest();return E91+Q.readUInt32BE(0)%rM$}function L91($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function tM$($){let Z=$.slice(0,Tl4);return Al4.test(Z)?Z:""}function Il4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!Rl4.test(Z))throw Error(`AgentSandboxProvider: envName=${JSON.stringify(Z)} is not a valid DNS-label-safe environment name (lowercase alphanumeric or '-', starts with a letter, ends alphanumeric, \u226432 chars). Studio sets this from STUDIO_ENV; check the studio chart's configMap.`);return Z}function D91($,Z={}){let Q={...Z};if($){let X=tM$($.orgId),Y=tM$($.userId);if(X)Q[PX.orgId]=X;if(Y)Q[PX.userId]=Y}return Q}function Nv($){let Z="";for(let Q of $){let X=Q.codePointAt(0)??0;Z+=X<32||X===127?" ":Q}return Z.slice(0,ql4)}function Ml4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function Vl4($){let Z={},Q=$.tenant;if(Q?.orgSlug)Z[vK.orgSlug]=Nv(Q.orgSlug);if(Q?.orgName)Z[vK.orgName]=Nv(Q.orgName);if(Q?.userEmail)Z[vK.userEmail]=Nv(Q.userEmail);if(Q?.userName)Z[vK.userName]=Nv(Q.userName);let X=$.repo;if(X){if(X.displayName)Z[vK.gitRepo]=Nv(X.displayName);let Y=Ml4(X.cloneUrl);if(Y)Z[vK.gitRepoUrl]=Nv(Y);let G=$.branch??X.branch;if(G)Z[vK.gitBranch]=Nv(G)}return Z}function kl4($){let Z=$.metadata?.labels;if(!Z)return null;let Q=Z[PX.orgId],X=Z[PX.userId];if(!Q||!X)return null;let Y=$.metadata?.annotations??{};return{orgId:Q,userId:X,orgSlug:Y[vK.orgSlug],orgName:Y[vK.orgName],userEmail:Y[vK.userEmail],userName:Y[vK.userName]}}function Sl4($,Z){if($){let Q=new Date($).getTime();if(Number.isFinite(Q)&&Q<=Z.getTime())return null}return Z.toISOString()}function Cl4($,Z){if($){let Q=new Date($).getTime();if(Number.isFinite(Q)&&Q>=Z.getTime())return null}return Z.toISOString()}function w91($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:"agent-sandbox"}}async function _l4($,Z){if(!Z||!$.tenant)return $.orgFsConfigJson;try{return await Z($.tenant)??$.orgFsConfigJson}catch(Q){return console.warn(`[${B6}] org-fs credential re-mint failed: ${Q instanceof Error?Q.message:String(Q)}`),$.orgFsConfigJson}}function vl4($){let Z={};if($.branch)Z.branch=$.branch;if($.repo)Z.repo=$.repo;if($.workload)Z.workload=$.workload;if($.env&&Object.keys($.env).length>0)Z.env=$.env;if($.tenant)Z.tenant=$.tenant;if($.cloneOnly)Z.cloneOnly=!0;if($.purpose)Z.purpose=$.purpose;if($.orgFsConfigJson)Z.orgFsConfigJson=$.orgFsConfigJson;return Object.keys(Z).length>0?Z:null}function xl4($,Z){try{return new URL(XK0($,Z)).hostname||null}catch{return null}}var B6="AgentSandboxProvider",Uv="x-sandbox-preview-not-ready",Jl4="agent-sandbox-system",Kl4="studio-sandbox",Wl4=300000,GU=9000,dM$=3000,O91="/app",Hl4=32,Fl4,Nl4=900000,Ul4=60000,Bl4=1800000,dP0=3,iM$=1800000,Ol4=900000,Ll4=1800000,Dl4,pM$,E91=40000,rM$=1e4,wl4=256,PX,vK,Al4,Tl4=63,Rl4,ql4=253;var aM$=L(()=>{J4();$A$();IM$();SM$();o41();TK0();jK0();fM$();B91();Fl4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),Dl4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],pM$=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];PX={role:"studio.decocms.com/role",sandboxHandle:"studio.decocms.com/sandbox-handle",orgId:"studio.decocms.com/org-id",userId:"studio.decocms.com/user-id",env:"studio.decocms.com/env"},vK={orgSlug:"studio.decocms.com/org-slug",orgName:"studio.decocms.com/org-name",userEmail:"studio.decocms.com/user-email",userName:"studio.decocms.com/user-name",gitRepo:"studio.decocms.com/git-repo",gitRepoUrl:"studio.decocms.com/git-repo-url",gitBranch:"studio.decocms.com/git-branch"},Al4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;Rl4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var sM$={};Q0(sM$,{parseTenantPools:()=>bM$,PREVIEW_NOT_READY_HEADER:()=>Uv,AgentSandboxProvider:()=>z91});var P91=L(()=>{aM$();B91()});var ZV$={};Q0(ZV$,{subscribeLifecycle:()=>M91,getOrInitSharedRunner:()=>q91,getAgentSandboxProviderForTeardown:()=>I91,getAgentSandboxProvider:()=>AX,__resetSharedLifecyclesForTesting:()=>dl4});function T91($){let Z=Ia[eM$];if(Z)return Promise.resolve(Z);let Q=Ia[A91];if(Q)return Q;let X=$().then((Y)=>{return Ia[eM$]=Y,Y}).finally(()=>{delete Ia[A91]});return Ia[A91]=X,X}function fl4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function bl4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function yl4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function gl4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function hl4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME?.trim(),Z=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE?.trim();if(!$&&!Z)return;if(!$||!Z)throw Error("STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME and STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE must both be set, or both unset. Half-configured per-claim HTTPRoute routing would silently fail to attach.");return{name:$,namespace:Z}}async function R91($){let Z=new $a($),Q=fl4(),{AgentSandboxProvider:X,parseTenantPools:Y}=await Promise.resolve().then(() => (P91(),sM$)),G=new JG(y0().encryptionKey);return new X({stateStore:Z,previewUrlPattern:Q,sandboxTemplateName:bl4(),envName:yl4(),previewGateway:hl4(),sentinelToken:gl4(),tenantPools:Y(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:P$,mintCloneUrl:async(J,K)=>{if(!J.connectionId)return null;let W=xP$(J.cloneUrl);if(!W)return null;let{cloneUrl:H}=await MH(J.connectionId,W.owner,W.name,$,G,{bufferMs:K?.bufferMs});return H},mintOrgFsConfig:async(J)=>{if(!J.orgSlug)return null;return await EK0({boundAuth:{apiKey:{create:(W)=>J8.api.createApiKey({body:{...W,userId:J.userId}})}},storage:{orgRepoSyncs:new yz($)}},{orgSlug:J.orgSlug,orgId:J.orgId,baseUrl:m9()})??null}})}function AX($){if(!y0().agentSandboxEnabled)throw Error("Agent sandbox is disabled. Set STUDIO_AGENT_SANDBOX_ENABLED=true to enable it.");return T91(()=>R91($.db))}function I91($){return T91(()=>R91($.db))}async function q91(){if(!y0().agentSandboxEnabled)return null;return T91(()=>R91(H8().db))}function M91($,Z,Q){let X=LD.get(Z);if(X){if(X.terminated){if(X.lastPhase)try{Q(X.lastPhase)}catch{}return{unsubscribe:ll4}}if(X.listeners.add(Q),X.lastPhase)try{Q(X.lastPhase)}catch{}return $V$(Z,X,Q)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([Q]),abort:Y};return LD.set(Z,G),ml4($,Z,G),$V$(Z,G,Q)}function ll4(){}function $V$($,Z,Q){return{unsubscribe(){if(LD.get($)!==Z)return;if(Z.listeners.delete(Q),Z.listeners.size===0)LD.delete($),Z.abort.abort()}}}async function ml4($,Z,Q){let X=null;try{for await(let Y of $.watchClaimLifecycle(Z,Q.abort.signal)){if(Q.abort.signal.aborted)break;Q.lastPhase=Y;let G=Y.kind==="ready"||Y.kind==="failed";if(G)Q.terminated=!0;let J=Array.from(Q.listeners);for(let K of J)try{K(Y)}catch{}if(G)break}}catch(Y){X=Y}finally{if(!Q.terminated&&!Q.abort.signal.aborted&&Q.listeners.size>0){let Y={kind:"failed",reason:"unknown",message:X instanceof Error?X.message:"Lifecycle watcher ended unexpectedly"};Q.lastPhase=Y,Q.terminated=!0;for(let G of Array.from(Q.listeners))try{G(Y)}catch{}}if(LD.get(Z)===Q)LD.delete(Z)}}function dl4(){for(let $ of LD.values())$.abort.abort();LD.clear()}var eM$,A91,Ia,ul4,cl4,LD;var xK=L(()=>{QQ();x6();W61();Uu();Xj();R$();Ou();wG();p5();eM$=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-runner"),A91=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-inflight"),Ia=globalThis;ul4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),cl4=globalThis,LD=cl4[ul4]??=new Map});async function qa($,Z,Q){try{await $.storage.threads.stampRuntimeIfAbsent(Z,Q)}catch(X){console.warn(`[stampRuntimeIfAbsent] ${Z}: ${X instanceof Error?X.message:String(X)}`)}}function QV$($){let Z=$?.trim();if(!Z)return null;try{let Q=new URL(Z);if(Q.protocol!=="http:"&&Q.protocol!=="https:")return null;return Q.href}catch{return null}}function iP0($){return QV$($?.previewServerUrl)??QV$($?.productionUrl)}function Bv($){return $==="cms"||$==="sandbox"?$:null}function il4($){return!!iP0($)&&$?.fastPreview===!0}function pP0($){return il4($)?"cms":"sandbox"}var V91;var Su=L(()=>{V91=["cms","sandbox"]});function XV$($){let{current:Z,detached:Q,base:X}=$.status??{};if(typeof Z!=="string"||Z.length===0)return null;if(Q===!0)return null;if(Z===$.requestedRef)return null;if(pl4.has(Z))return null;if(typeof X==="string"&&X.length>0&&Z===X)return null;return Z}function nP0($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var pl4;var tP0=L(()=>{pl4=new Set(["main","master","trunk","develop","HEAD"])});import{z as JU}from"zod";async function Cu($,Z){s(Z);let Q=a(Z),X=a0(Z);if(!X)throw Error("User ID required");let Y=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!Y||Y.organization_id!==Q.id)throw Error("Virtual MCP not found");let G=Y.metadata??{},J=await xz(Z,$.branch,X),K=qH(b9(G),J,$.branch),W=await AX(Z);if(K){if(await W.alive(K.sandboxHandle).catch(()=>!0))return K;await sL(Z.storage.virtualMcps,$.virtualMcpId,X,J,$.branch).catch((O)=>{console.warn("[ensureSandbox] failed to reap stale entry",O)})}let H=cJ($.branch)??Z.metadata?.threadId;if(H)qa(Z,H,"sandbox");let N=await $D(Z,H)??G.githubRepo??null;await $.onColdStart?.().catch(()=>{});let{entry:U}=await GV$({ctx:Z,userId:X,sandboxUserId:J,orgId:Q.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:N,threadRepos:await $61(Z,H),existing:null,runner:W,...$.purpose?{purpose:$.purpose}:{}});return U}async function nl4($){let Z=$.primary?`${$.primary.owner}/${$.primary.name}`.toLowerCase():null,Q=$.repos.filter((G)=>`${G.owner}/${G.name}`.toLowerCase()!==Z),X=nr(Q),Y=[];for(let[G,J]of Q.entries()){if(!J.connectionId)continue;try{let{cloneUrl:K}=await MH(J.connectionId,J.owner,J.name,$.ctx.db,$.ctx.vault);Y.push({cloneUrl:K,connectionId:J.connectionId,userName:$.gitUserName,userEmail:$.gitUserEmail,displayName:`${J.owner}/${J.name}`,directoryName:X[G],submoduleCredentials:[]})}catch(K){console.warn(`[provisionSandbox] skipping secondary ${J.owner}/${J.name}:`,K instanceof Error?K.message:K)}}return Y}async function GV$($){let{ctx:Z,userId:Q,sandboxUserId:X,orgId:Y,virtualMcpId:G,branch:J,metadata:K,threadRepos:W,existing:H,runner:F,purpose:N}=$,U=N==="harness-run",B=$.githubRepo?await tl4({ctx:Z,orgId:Y,virtualMcpId:G,userId:Q,githubRepo:$.githubRepo}):null,{runtime:O,packageManager:D,port:w,packageManagerPath:E}=UP$(K),j;if(B){if(B.connectionId)await XD({ctx:Z,connectionId:B.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(q0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:B.connectionId,error:q0.message})}});let{cloneUrl:r,gitUserName:t,gitUserEmail:D0}=B.connectionId?await MH(B.connectionId,B.owner,B.name,Z.db,Z.vault):PP$(B.owner,B.name);if(!D){let q0=B.connectionId?await RP$(B.connectionId,B.owner,B.name,Z.db,Z.vault):await IP$(B.owner,B.name);if(q0)D=q0.packageManager,O=tr[q0.packageManager].runtime,w=q0.devPort??w,await ol4(Z,G,Q,q0.packageManager,q0.devPort)}let e=y0().sandboxStickyHeadRefEnabled,E0=nP0({branch:J,derivedRef:aN(J),recordedHeadRef:e?await JP$(Z,cJ(J)):null,sticky:e}),u0=await LP$({ctx:Z,orgId:Y,userId:Q,entries:FP$(K)});j={cloneUrl:r,...B.connectionId?{connectionId:B.connectionId}:{},userName:t,userEmail:D0,branch:E0,displayName:`${B.owner}/${B.name}`,submoduleCredentials:u0}}let z=await nl4({ctx:Z,orgId:Y,repos:W??[],primary:B,gitUserName:j?.userName??"",gitUserEmail:j?.userEmail??""}),A=O&&D&&!U?{runtime:O,packageManager:D,...w!==null?{devPort:Number(w)}:{},...E?{packageManagerPath:E}:{}}:void 0,P=dr({orgId:Y,virtualMcpId:G,branch:J}),I=!y0().orgFsMountsDisabled,q;if(I){let r=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(r)q=await EK0(Z,{orgSlug:r,orgId:Y,baseUrl:m9()})}await al4(F);let M=await F.ensure({userId:X,projectRef:P},{branch:J,repo:j,extraRepos:z,workload:A,cloneOnly:U,...N?{purpose:N}:{},tenant:{orgId:Y,userId:X,...Z.organization?.slug?{orgSlug:Z.organization.slug}:{},...Z.organization?.name?{orgName:Z.organization.name}:{},...Z.auth.user?.email?{userEmail:Z.auth.user.email}:{},...Z.auth.user?.name?{userName:Z.auth.user.name}:{}},...q?{orgFsConfigJson:q}:{}}),S=Fu(K);await WK0({ctx:Z,runner:F,handle:M.handle,orgId:Y,userId:Q,entries:S});let f=!!H&&H.sandboxHandle===M.handle&&H?.createdAt?H.createdAt:Date.now(),b=K.runtime?.selected??null,l=K.runtime?.port??null,y=K.runtime?.path??null,p={sandboxHandle:M.handle,previewUrl:M.previewUrl,createdAt:f,startedWith:{packageManager:b,port:l,path:y}};await oz$(Z.storage.virtualMcps,G,Q,X,J,p);let Y0=cJ(J)??Z.metadata?.threadId;if(Y0)await WP$(Z,Y0,X,J,p);let L0=!H||H.sandboxHandle!==M.handle;return{entry:p,isNewVm:L0}}async function tl4($){let{ctx:Z,orgId:Q,virtualMcpId:X,userId:Y,githubRepo:G}=$;if(!G.connectionId)return G;if(await Z.storage.connections.findById(G.connectionId,Q))return G;let{items:K}=await Z.storage.connections.list(Q),W=O30(K,G.owner,G.name);if(!W)return console.warn("[provisionSandbox] recorded repo connection no longer exists and no live connection covers the repo",{virtualMcpId:X,connectionId:G.connectionId}),G;console.warn("[provisionSandbox] healed dangling repo connection",{virtualMcpId:X,staleConnectionId:G.connectionId,connectionId:W.id});try{let F=(await Z.storage.virtualMcps.findById(X))?.metadata??{},N=F.githubRepo;if(N?.connectionId===G.connectionId){let U=y5(W);await Z.storage.virtualMcps.update(X,Y,{metadata:{...F,githubRepo:{...N,connectionId:W.id,...U?{installationId:U.installationId}:{}}}})}}catch(H){console.warn("[provisionSandbox] failed to persist healed repo connection",{virtualMcpId:X,error:H.message})}return{...G,connectionId:W.id}}async function ol4($,Z,Q,X,Y){let G=await $.storage.virtualMcps.findById(Z);if(!G)return;let J=G.metadata??{};await $.storage.virtualMcps.update(Z,Q,{metadata:{...J,runtime:{selected:X,port:Y}}})}async function al4($){let Z=Date.now()+YV$,Q=!1;while(!await $.hasSchedulableCapacity()){if(Date.now()>=Z)throw Error(`sandbox provisioning failed: the cluster has had no room to schedule another sandbox for ${Math.round(YV$/1000)}s`);if(!Q)Q=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await W$(rl4)}}var k91,YV$=150000,rl4=5000;var Ma=L(()=>{pr();J4();S0();or();Y61();DP$();EY();GY();Uu();MP$();a41();xK();Su();kK();tP0();R$();p5();Ou();EY();k91=c({name:"SANDBOX_START",description:"Start a sandbox with the connected GitHub repo and dev server.",annotations:{title:"Start VM Preview",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:JU.object({virtualMcpId:JU.string().describe("Virtual MCP ID"),branch:JU.string().min(1).optional().describe("Git branch to check out. Pass the thread's branch whenever the caller has one: when omitted the handler mints a fresh `<user-slug>-<timestamp>` name, which becomes a SEPARATE sandbox from the one the thread's own branch resolves to. The resolved branch is returned in the response so callers can persist it."),threadId:JU.string().optional().describe("The session asking for a sandbox. A thread stamped `cms` is refused \u2014 that session reads and writes over the decofile API and a pod would be invisible to it. Optional: an unstamped (legacy) thread is always allowed, and so is a caller with no thread.")}),outputSchema:JU.object({previewUrl:JU.string().nullable(),sandboxHandle:JU.string(),branch:JU.string(),isNewVm:JU.boolean()}),handler:async($,Z)=>{s(Z);let Q=a(Z);await Z.access.check();let X=$.branch??UK0(NK0(Z.auth.user)),Y=cJ(X)??$.threadId??Z.metadata?.threadId;if(Y){let D=await Z.storage.threads.get(Y).catch(()=>null);if(Bv(D?.metadata?.runtime)==="cms")throw Error("This chat is a CMS session and does not use a sandbox. Start a coding session to get one.")}let G=a0(Z);if(!G)throw Error("User ID required");let J=await xz(Z,X,G),K=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!K||K.organization_id!==Q.id)throw Error("Virtual MCP not found");let W=K.metadata??{},H=await AX(Z),F=qH(b9(W),J,X),U=await $D(Z,cJ(X)??Z.metadata?.threadId)??W.githubRepo??null,{entry:B,isNewVm:O}=await GV$({ctx:Z,userId:G,sandboxUserId:J,orgId:Q.id,virtualMcpId:$.virtualMcpId,branch:X,metadata:W,githubRepo:U,threadRepos:await $61(Z,cJ(X)??Z.metadata?.threadId),existing:F,runner:H});if(Y)qa(Z,Y,"sandbox");return{...B,branch:X,isNewVm:O}}})});function sl4($){let{publicUrl:Z,agentId:Q,organization:X,target:Y,threadId:G}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${encodeURIComponent(Q)}`;if(!X.slug)throw new KV$(X.id,Y);if(Y==="task-run"){if(!G)throw Error("a task-run MCP endpoint is scoped to a run: threadId is required");return`${Z}/api/${X.slug}/mcp/task-run/${encodeURIComponent(G)}`}return`${Z}/api/${X.slug}/mcp/self`}async function oP0($,Z,Q,X,Y="agent-tools",G,J={"*":["*"]}){let K=sl4({publicUrl:m9(),agentId:Z,organization:Q,target:Y,...G?{threadId:G}:{}}),W=await $.boundAuth.apiKey.create({name:X,permissions:J,expiresIn:JV$,metadata:{organization:{id:Q.id,slug:Q.slug,name:Q.name}}});return{url:K,headers:{Authorization:`Bearer ${W.key}`,"x-org-id":Q.id},expiresAt:Date.now()+JV$*1000}}function WV$($){let{publicUrl:Z,organizationSlug:Q,headers:X,connections:Y}=$,G=new Set;return Y.map((J)=>{let K=el4(J.slug??J.title??"")||"mcp",W=K;for(let H=2;G.has(W);H++)W=`${K}-${H}`;return G.add(W),{name:W,url:`${Z}/api/${Q}/mcp/${encodeURIComponent(J.id)}`,headers:X}})}function el4($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function HV$($){return{self:[...$.toolNames],...$.grants}}var JV$=3600,KV$;var S91=L(()=>{p5();KV$=class KV$ extends Error{constructor($,Z){super(`cannot mint a "${Z}" MCP endpoint for organization "${$}": the org-scoped path needs the org slug, which was not loaded.`);this.name="MissingOrganizationSlugError"}}});async function $m4($,Z,Q,X){try{let Y=$.organization;if(!Y)return;let G=await oP0($,X.virtualMcpId,Y,"tool-scripting"),J=await Z.proxyDaemonRequest(Q,"/_sandbox/tools/sync",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify(G)});if(!J.ok)console.warn("[agent-sandbox-fs] tools/sync failed",J.status,await J.text().catch(()=>""))}catch(Y){console.warn("[agent-sandbox-fs] tools/sync failed",Y)}}async function _u($,Z){let Q=await AX($),X=null,Y=()=>{if(!X){if(X=Cu({virtualMcpId:Z.virtualMcpId,branch:Z.branch},$).then((K)=>K.sandboxHandle),X.catch(()=>{X=null}),Z.syncTools)X.then((K)=>$m4($,Q,K,{virtualMcpId:Z.virtualMcpId})).catch(()=>{})}return X},G=Z.branch==="ephemeral";return r41(Q,{ensureHandle:Y,invalidateHandle:async(K)=>{if(X=null,!G&&!K?.force)return;try{await sL($.storage.virtualMcps,Z.virtualMcpId,Z.userId,Z.userId,Z.branch)}catch(W){console.warn("[agent-sandbox-fs] failed to reap vmMap entry",W)}},canAutoRestart:G,threadId:Z.threadId})}async function FV$($,Z){try{let Q=await _u($,Z),{stdout:X}=await Q.onBash("test -d .deco && echo __DECO_SITE__");return X.includes("__DECO_SITE__")}catch(Q){return console.warn("[agent-sandbox-fs] .deco probe failed; assuming deco site",Q),!0}}var rP0=L(()=>{pr();S91();xK();Ma();EY()});import{z as NV$}from"zod";function vu($){let Z=[];for(let Q of $){if(Q.status!=="active")continue;let X=y5(Q);if(!X)continue;Z.push({connectionId:Q.id,owner:X.owner,repo:X.repo,installationId:X.installationId})}return Z}async function Qm4($,Z){let{items:Q}=await $.storage.connections.list(Z,{slug:"mcp-github"});return vu(Q)}function Xm4($){let Z=$.split(`
2372
2372
  `).map((X)=>X.trim()).filter((X)=>X&&X!==".git"&&X!=="__CLONED__"),Q=Z.length>0;return{cloned:Q,listing:Q?Z.join(`
2373
2373
  `):""}}function Ym4($){let Z="Load a GitHub repository into this conversation's sandbox so the file tools (read/write/edit/bash/grep/glob) and dev server operate on that repo, and open its live Preview. Waits until the repo is cloned before returning. Calling it again switches the repo. File tools operate on the loaded repo from your NEXT message (this turn's tools are still bound to the previous workspace), so after loading, prefer the file listing this tool returns over re-running bash in the same turn.",Q=$.map((X)=>`- ${X.owner}/${X.repo} (connectionId: ${X.connectionId})`).join(`
2374
2374
  `);return`${Z}
@@ -2856,7 +2856,7 @@ Usage notes:
2856
2856
  `+`- Every subtask call starts FRESH \u2014 no conversation history, no prior runs. Always include full context in the prompt and state exactly what to return (the specific answer/list/paths you need, not a raw dump); never use continuation phrases like 'continue' or 'as before'.
2857
2857
  `+`- Clearly tell the subagent whether you expect it to take action or just research.
2858
2858
  - To parallelize independent searches, launch multiple subtask calls in the same message.
2859
- - The subagent's output should generally be trusted.`;Oo4={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}});function jv$($){let Z={},Q=$.split(/\r?\n/);for(let X=0;X<Q.length;X++){let Y=(Q[X]??"").trim();if(!Y||Y.startsWith("#"))continue;if(Y.startsWith("export "))Y=Y.slice(7).trim();let G=Y.indexOf("=");if(G<0)throw Error(`Line ${X+1}: missing '='`);let J=Y.slice(0,G).trim();if(!Lo4.test(J))throw Error(`Line ${X+1}: invalid key "${J}"`);let K=Y.slice(G+1).trim();if(K.length>=2&&(K.startsWith('"')&&K.endsWith('"')||K.startsWith("'")&&K.endsWith("'")))K=K.slice(1,-1);Z[J]=K}return Z}var Lo4;var zv$=L(()=>{Lo4=/^[A-Za-z_][A-Za-z0-9_]*$/});async function Av$($){let Z=$.organization?.id;if(!Z)return{};try{let{value:Q}=await $.storage.secrets.resolveByName({organizationId:Z,scope:{kind:"organization"},name:Pv$});return jv$(Q)}catch(Q){if(Q?.name!=="SecretNotFoundError")console.warn(`[org-run-env] ignoring the ${Pv$} secret: ${Q instanceof Error?Q.message:String(Q)}`);return{}}}function Tv$($,Z){return{...$,...Z}}var Pv$="TASK_RUN_ENV";var Rv$=L(()=>{zv$()});async function*Iv$($,Z,Q){let X=!1;for await(let Y of $){if(yield Y,X||!Z)continue;if(Y.type!=="start")continue;X=!0,yield{type:"message-metadata",messageMetadata:{models:{thinking:{id:Z,title:Z,provider:Q}}}}}}function qv$($){let{role:Z,roleStatements:Q,connectionIds:X}=$;if(NQ(Z??void 0))return Object.fromEntries(X.map((G)=>[G,["*"]]));let Y={};for(let G of X){let J=new Set;for(let K of Q)for(let W of K[G]??[])J.add(W);if(J.size===0)continue;Y[G]=J.has("*")?["*"]:[...J]}return Y}function Mv$($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}var Vv$=L(()=>{QY()});function fv($){return $==="decopilot"||$==="claude-code"}function wo4($){return{type:"data-run-status",id:"run-status",data:{stage:$}}}function kv$($){if(!$||typeof $!=="object")return!1;return $.type==="data-run-status"}async function _G($){let{streamBuffer:Z,harnessId:Q,taskId:X,stage:Y}=$;if(!Z||!fv(Q))return;try{await Z.publishRawChunk(X,wo4(Y))}catch{}}var Do4,Ys,jWZ;var bv=L(()=>{Do4=["waiting-runner","starting-run","starting-sandbox","waiting-capacity","gathering-context","preparing-tools","starting-assistant","analyzing-scope","retrying-provider"],Ys=["gathering-context","preparing-tools","starting-assistant","analyzing-scope"],jWZ=new Set(Do4)});function Gs($){return $ instanceof Error&&$.superseded===!0}function xv$($){return $===404||$===410||$>=500}function Kc($){return $===yv}class o71{ctx;virtualMcpId;branch;credential;resume;interactive;streamBuffer;constructor($){this.ctx=$.ctx,this.virtualMcpId=$.virtualMcpId,this.branch=$.branch,this.credential=$.credential,this.resume=$.resume??null,this.interactive=$.interactive??!1,this.streamBuffer=$.streamBuffer}dispatch($){return this.stream($)}async resolveWorkspace($){let Z=await $D(this.ctx,$);if(!Z)return this.branch===rN($)?{cwd:Sv$,branch:aN(this.branch)}:{cwd:null};return{cwd:Sv$,repo:{owner:Z.owner,name:Z.name,connectedGithub:Boolean(Z.connectionId)},branch:this.branch.startsWith("thread:")?aN(this.branch):this.branch}}async mcpForRun($,Z,Q){let X=await this.orgMcpConnections($),Y=await this.dispatcherConnectionGrants($.id,Q,X.map((W)=>W.id)),G=X.filter((W)=>(W.id in Y)),J=await oP0(this.ctx,this.virtualMcpId,$,`${yv}-run`,"task-run",Z,HV$({toolNames:C91,grants:Y}));if(G.length===0||!$.slug)return{mcp:J};let K=WV$({publicUrl:m9(),organizationSlug:$.slug,headers:J.headers,connections:G});return console.log(`[${yv}] org mcps: ${K.map((W)=>W.name).join(" ")||"none"}${X.length===G.length?"":` (${X.length-G.length} withheld \u2014 the `+"dispatching user has no grant for them)"}`),{mcp:J,orgMcps:K}}async dispatcherConnectionGrants($,Z,Q){if(Q.length===0)return{};let Y=(await this.ctx.db.selectFrom("member").select(["role"]).where("organizationId","=",$).where("userId","=",Z).executeTakeFirst())?.role,G=NQ(Y??void 0)?[]:(await Promise.all(Mv$(Y).map((J)=>Js(this.ctx.db,$,J)))).filter((J)=>Boolean(J));return qv$({role:Y,roleStatements:G,connectionIds:Q})}async orgMcpConnections($){if(!$.slug)return[];let[Z,Q]=await Promise.all([this.ctx.storage.organizationSettings.get($.id),this.ctx.storage.virtualMcps.findById(this.virtualMcpId).catch(()=>null)]),X=DG(Z?.flags,"coding_agent_org_mcps"),Y=new Set((Q?.connections??[]).map((J)=>J.connection_id));if(!X&&Y.size===0)return[];let{items:G}=await this.ctx.storage.connections.list($.id);return _o4({organizationId:$.id,orgWide:X,ownIds:Y,connections:G})}async*stream($){if(!this.credential)throw Error(`the ${yv} harness needs a resolved model credential; this run has none (check the agent's thinking model)`);let Z=uV$(this.credential,gV$(this.ctx.metadata?.runMetadata?.[JA0])),Q=this.ctx.organization;if(!Q)throw Error(`the ${yv} harness needs an organization on the context to mint its MCP endpoint; this run has none`);let X=Tv$(await Av$(this.ctx),Z),Y=await AX(this.ctx),G={...$,...await this.mcpForRun(Q,$.threadId,$.user.id),workspace:await this.resolveWorkspace($.threadId)},J=$.threadId,{ctx:K,virtualMcpId:W,branch:H,interactive:F,streamBuffer:N}=this,U=this.credential.providerId,B=null,O=(D)=>async function*(){await _G({streamBuffer:N,harnessId:yv,taskId:J,stage:"starting-sandbox"});let w=await Cu({virtualMcpId:W,branch:H,purpose:F?"interactive":"harness-run"},K);B=w.sandboxHandle,await Io4(Y,w.sandboxHandle,X),yield*Iv$(ko4({provider:Y,handle:w.sandboxHandle,input:D?{...G,resume:D}:G,runId:J,signal:$.signal}),D?null:Z.CLAUDE_CODE_MODEL,U)}();try{yield*Po4({runId:J,resume:this.resume,aborted:()=>$.signal?.aborted===!0,dispatchOnce:O,lastHandle:()=>B,describeTermination:async(D)=>D===null?null:To4(await Y.lastTermination(D))})}finally{if(B&&!this.interactive&&y0().sandboxReleaseOnRunEndEnabled)await Y.releaseAfter(B,y0().sandboxReleaseGraceMs).catch(()=>{})}}}async function*Po4($){let Z=$.maxAttempts??Eo4,Q=$.maxTotalAttempts??jo4,X=$.resume,Y=X!==null,G=0;for(let J=1;;J++){let K=!1;try{for await(let W of $.dispatchOnce(X)){if(K=!0,W.type==="start"){if(Y)continue;Y=!0}yield W}return}catch(W){if($.aborted())throw W;G=K?0:G+1;let H=W instanceof RY?await $.describeTermination?.($.lastHandle?.()??null).catch(()=>null)??null:null;if(Gs(W)||!(W instanceof RY)||G>=Z||J>=Q){if(H&&W instanceof RY)throw new RY(W.reason,H);throw W}console.warn("[sandbox-dispatch] sandbox lost mid-run; continuing",{runId:$.runId,attempt:J,progressed:K,reason:W.message,termination:H}),X={reason:Ao4(W.message,H)}}}}function Ao4($,Z){let Q=`the sandbox running the previous attempt stopped answering (${$})`;if(!Z)return Q;return`${Q}. ${Z}. A replacement sandbox has been started from the last state pushed to the branch. Tell the user this happened, re-read the files you had been editing rather than trusting your memory of them, and if a step needs more memory than the sandbox has, split it instead of repeating what was killed`}function To4($){if(!$)return null;if($.oomKilled)return`it was killed by the kernel for exceeding its memory limit${$.memoryLimit?` (memory limit ${$.memoryLimit})`:""} \u2014 OOMKilled`;if($.reason==="Completed")return null;let Z=$.exitCode===void 0?"":` (exit code ${$.exitCode})`;return`the sandbox container terminated with reason ${$.reason}${Z}`}async function Io4($,Z,Q){let X;try{X=await $.proxyDaemonRequest(Z,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({env:Q}),signal:AbortSignal.timeout(Ro4)})}catch(Y){throw new RY(`could not push the model env to the sandbox: ${Y instanceof Error?Y.message:String(Y)}`)}if(!X.ok){let Y=`failed to push model env to the sandbox (${X.status} ${X.statusText})`;if(xv$(X.status))throw new RY(Y);throw Error(Y)}}function qo4($){let{signal:Z,...Q}=$;return Q}function Vo4($,Z){let Q=()=>void $.renewTtl(Z).catch((Y)=>console.warn(`[sandbox-dispatch] TTL renew failed for ${Z}: ${Y instanceof Error?Y.message:String(Y)}`));Q();let X=setInterval(Q,Mo4);return X.unref?.(),()=>clearInterval(X)}async function*ko4($){let Z=Date.now(),Q=qo4($.input),X=(H=!1)=>$.provider.proxyDaemonRequest($.handle,"/_sandbox/dispatch",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({...H?{harnessId:yv}:{},runId:$.runId,input:Q}),...$.signal?{signal:$.signal}:{}}),Y;try{if(Y=await X(),Y.status===400){let H=await Y.clone().json().catch(()=>null);if(typeof H==="object"&&H!==null&&"error"in H&&H.error==="missing_harness_id")Y=await X(!0)}}catch(H){if($.signal?.aborted)throw H;throw new RY(`could not reach the sandbox daemon: ${H instanceof Error?H.message:String(H)}`)}if(!Y.ok){let H=await Y.text().catch(()=>Y.statusText),F=`sandbox dispatch failed (${Y.status}): ${H.slice(0,512)}`;if(xv$(Y.status))throw new RY(F);throw Error(F)}if(!Y.body)throw new RY("dispatch returned no body");let G=Vo4($.provider,$.handle),J=0,K=null,W=!1;try{for await(let H of Co4(Y.body,$.signal)){let F=cV$.safeParse(H);if(!F.success)throw Error(`sandbox dispatch returned a malformed frame: ${F.error.message}`);if(J+=F.data.chunks.length,yield*F.data.chunks,K??=F.data.error,F.data.done)W=!0}}finally{G()}if(console.log("[sandbox-dispatch] run ended",{runId:$.runId,handle:$.handle,chunks:J,elapsedMs:Date.now()-Z,done:W,error:K?.code??null}),!W&&!K)throw new RY(`the sandbox stopped streaming after ${J} chunks without finishing the run`);if(K)throw So4(K.code,K.message)}function So4($,Z){if($===zo4)return new vv$(Z);if($===mV$)return new RY(Z);return Error(`${$}: ${Z}`)}async function*Co4($,Z){let Q=new TextDecoder,X="",Y=function*(J){let K=X.split(`
2859
+ - The subagent's output should generally be trusted.`;Oo4={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}});function jv$($){let Z={},Q=$.split(/\r?\n/);for(let X=0;X<Q.length;X++){let Y=(Q[X]??"").trim();if(!Y||Y.startsWith("#"))continue;if(Y.startsWith("export "))Y=Y.slice(7).trim();let G=Y.indexOf("=");if(G<0)throw Error(`Line ${X+1}: missing '='`);let J=Y.slice(0,G).trim();if(!Lo4.test(J))throw Error(`Line ${X+1}: invalid key "${J}"`);let K=Y.slice(G+1).trim();if(K.length>=2&&(K.startsWith('"')&&K.endsWith('"')||K.startsWith("'")&&K.endsWith("'")))K=K.slice(1,-1);Z[J]=K}return Z}var Lo4;var zv$=L(()=>{Lo4=/^[A-Za-z_][A-Za-z0-9_]*$/});async function Av$($){let Z=$.organization?.id;if(!Z)return{};try{let{value:Q}=await $.storage.secrets.resolveByName({organizationId:Z,scope:{kind:"organization"},name:Pv$});return jv$(Q)}catch(Q){if(Q?.name!=="SecretNotFoundError")console.warn(`[org-run-env] ignoring the ${Pv$} secret: ${Q instanceof Error?Q.message:String(Q)}`);return{}}}function Tv$($,Z){return{...$,...Z}}var Pv$="TASK_RUN_ENV";var Rv$=L(()=>{zv$()});async function*Iv$($,Z,Q){let X=!1;for await(let Y of $){if(yield Y,X||!Z)continue;if(Y.type!=="start")continue;X=!0,yield{type:"message-metadata",messageMetadata:{models:{thinking:{id:Z,title:Z,provider:Q}}}}}}function qv$($){let{role:Z,roleStatements:Q,connectionIds:X}=$;if(NQ(Z??void 0))return Object.fromEntries(X.map((G)=>[G,["*"]]));let Y={};for(let G of X){let J=new Set;for(let K of Q)for(let W of K[G]??[])J.add(W);if(J.size===0)continue;Y[G]=J.has("*")?["*"]:[...J]}return Y}function Mv$($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}var Vv$=L(()=>{QY()});function fv($){return $==="decopilot"||$==="claude-code"}function wo4($){return{type:"data-run-status",id:"run-status",data:{stage:$}}}function kv$($){if(!$||typeof $!=="object")return!1;return $.type==="data-run-status"}async function _G($){let{streamBuffer:Z,harnessId:Q,taskId:X,stage:Y}=$;if(!Z||!fv(Q))return;try{await Z.publishRawChunk(X,wo4(Y))}catch{}}var Do4,Ys,jWZ;var bv=L(()=>{Do4=["waiting-runner","starting-run","starting-sandbox","waiting-capacity","gathering-context","preparing-tools","starting-assistant","analyzing-scope","retrying-provider"],Ys=["gathering-context","preparing-tools","starting-assistant","analyzing-scope"],jWZ=new Set(Do4)});function Gs($){return $ instanceof Error&&$.superseded===!0}function xv$($){return $===404||$===410||$>=500}function Kc($){return $===yv}class o71{ctx;virtualMcpId;branch;credential;resume;interactive;streamBuffer;constructor($){this.ctx=$.ctx,this.virtualMcpId=$.virtualMcpId,this.branch=$.branch,this.credential=$.credential,this.resume=$.resume??null,this.interactive=$.interactive??!1,this.streamBuffer=$.streamBuffer}dispatch($){return this.stream($)}async resolveWorkspace($){let Z=await $D(this.ctx,$);if(!Z)return this.branch===rN($)?{cwd:Sv$,branch:aN(this.branch)}:{cwd:null};return{cwd:Sv$,repo:{owner:Z.owner,name:Z.name,connectedGithub:Boolean(Z.connectionId)},branch:this.branch.startsWith("thread:")?aN(this.branch):this.branch}}async mcpForRun($,Z,Q){let X=await this.orgMcpConnections($),Y=await this.dispatcherConnectionGrants($.id,Q,X.map((W)=>W.id)),G=X.filter((W)=>(W.id in Y)),J=await oP0(this.ctx,this.virtualMcpId,$,`${yv}-run`,"task-run",Z,HV$({toolNames:C91,grants:Y}));if(G.length===0||!$.slug)return{mcp:J};let K=WV$({publicUrl:m9(),organizationSlug:$.slug,headers:J.headers,connections:G});return console.log(`[${yv}] org mcps: ${K.map((W)=>W.name).join(" ")||"none"}${X.length===G.length?"":` (${X.length-G.length} withheld \u2014 the `+"dispatching user has no grant for them)"}`),{mcp:J,orgMcps:K}}async dispatcherConnectionGrants($,Z,Q){if(Q.length===0)return{};let Y=(await this.ctx.db.selectFrom("member").select(["role"]).where("organizationId","=",$).where("userId","=",Z).executeTakeFirst())?.role,G=NQ(Y??void 0)?[]:(await Promise.all(Mv$(Y).map((J)=>Js(this.ctx.db,$,J)))).filter((J)=>Boolean(J));return qv$({role:Y,roleStatements:G,connectionIds:Q})}async orgMcpConnections($){if(!$.slug)return[];let[Z,Q]=await Promise.all([this.ctx.storage.organizationSettings.get($.id),this.ctx.storage.virtualMcps.findById(this.virtualMcpId).catch(()=>null)]),X=DG(Z?.flags,"coding_agent_org_mcps"),Y=new Set((Q?.connections??[]).map((J)=>J.connection_id));if(!X&&Y.size===0)return[];let{items:G}=await this.ctx.storage.connections.list($.id);return _o4({organizationId:$.id,orgWide:X,ownIds:Y,connections:G})}async*stream($){if(!this.credential)throw Error(`the ${yv} harness needs a resolved model credential; this run has none (check the agent's thinking model)`);let Z=uV$(this.credential,gV$(this.ctx.metadata?.runMetadata?.[JA0])),Q=this.ctx.organization;if(!Q)throw Error(`the ${yv} harness needs an organization on the context to mint its MCP endpoint; this run has none`);let X=Tv$(await Av$(this.ctx),Z),Y=await AX(this.ctx),G={...$,...await this.mcpForRun(Q,$.threadId,$.user.id),workspace:await this.resolveWorkspace($.threadId)},J=$.threadId,{ctx:K,virtualMcpId:W,branch:H,interactive:F,streamBuffer:N}=this,U=this.credential.providerId,B=null,O=(D)=>async function*(){let w=await Cu({virtualMcpId:W,branch:H,purpose:F?"interactive":"harness-run",onColdStart:()=>_G({streamBuffer:N,harnessId:yv,taskId:J,stage:"starting-sandbox"})},K);B=w.sandboxHandle,await Io4(Y,w.sandboxHandle,X),yield*Iv$(ko4({provider:Y,handle:w.sandboxHandle,input:D?{...G,resume:D}:G,runId:J,signal:$.signal}),D?null:Z.CLAUDE_CODE_MODEL,U)}();try{yield*Po4({runId:J,resume:this.resume,aborted:()=>$.signal?.aborted===!0,dispatchOnce:O,lastHandle:()=>B,describeTermination:async(D)=>D===null?null:To4(await Y.lastTermination(D))})}finally{if(B&&!this.interactive&&y0().sandboxReleaseOnRunEndEnabled)await Y.releaseAfter(B,y0().sandboxReleaseGraceMs).catch(()=>{})}}}async function*Po4($){let Z=$.maxAttempts??Eo4,Q=$.maxTotalAttempts??jo4,X=$.resume,Y=X!==null,G=0;for(let J=1;;J++){let K=!1;try{for await(let W of $.dispatchOnce(X)){if(K=!0,W.type==="start"){if(Y)continue;Y=!0}yield W}return}catch(W){if($.aborted())throw W;G=K?0:G+1;let H=W instanceof RY?await $.describeTermination?.($.lastHandle?.()??null).catch(()=>null)??null:null;if(Gs(W)||!(W instanceof RY)||G>=Z||J>=Q){if(H&&W instanceof RY)throw new RY(W.reason,H);throw W}console.warn("[sandbox-dispatch] sandbox lost mid-run; continuing",{runId:$.runId,attempt:J,progressed:K,reason:W.message,termination:H}),X={reason:Ao4(W.message,H)}}}}function Ao4($,Z){let Q=`the sandbox running the previous attempt stopped answering (${$})`;if(!Z)return Q;return`${Q}. ${Z}. A replacement sandbox has been started from the last state pushed to the branch. Tell the user this happened, re-read the files you had been editing rather than trusting your memory of them, and if a step needs more memory than the sandbox has, split it instead of repeating what was killed`}function To4($){if(!$)return null;if($.oomKilled)return`it was killed by the kernel for exceeding its memory limit${$.memoryLimit?` (memory limit ${$.memoryLimit})`:""} \u2014 OOMKilled`;if($.reason==="Completed")return null;let Z=$.exitCode===void 0?"":` (exit code ${$.exitCode})`;return`the sandbox container terminated with reason ${$.reason}${Z}`}async function Io4($,Z,Q){let X;try{X=await $.proxyDaemonRequest(Z,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({env:Q}),signal:AbortSignal.timeout(Ro4)})}catch(Y){throw new RY(`could not push the model env to the sandbox: ${Y instanceof Error?Y.message:String(Y)}`)}if(!X.ok){let Y=`failed to push model env to the sandbox (${X.status} ${X.statusText})`;if(xv$(X.status))throw new RY(Y);throw Error(Y)}}function qo4($){let{signal:Z,...Q}=$;return Q}function Vo4($,Z){let Q=()=>void $.renewTtl(Z).catch((Y)=>console.warn(`[sandbox-dispatch] TTL renew failed for ${Z}: ${Y instanceof Error?Y.message:String(Y)}`));Q();let X=setInterval(Q,Mo4);return X.unref?.(),()=>clearInterval(X)}async function*ko4($){let Z=Date.now(),Q=qo4($.input),X=(H=!1)=>$.provider.proxyDaemonRequest($.handle,"/_sandbox/dispatch",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({...H?{harnessId:yv}:{},runId:$.runId,input:Q}),...$.signal?{signal:$.signal}:{}}),Y;try{if(Y=await X(),Y.status===400){let H=await Y.clone().json().catch(()=>null);if(typeof H==="object"&&H!==null&&"error"in H&&H.error==="missing_harness_id")Y=await X(!0)}}catch(H){if($.signal?.aborted)throw H;throw new RY(`could not reach the sandbox daemon: ${H instanceof Error?H.message:String(H)}`)}if(!Y.ok){let H=await Y.text().catch(()=>Y.statusText),F=`sandbox dispatch failed (${Y.status}): ${H.slice(0,512)}`;if(xv$(Y.status))throw new RY(F);throw Error(F)}if(!Y.body)throw new RY("dispatch returned no body");let G=Vo4($.provider,$.handle),J=0,K=null,W=!1;try{for await(let H of Co4(Y.body,$.signal)){let F=cV$.safeParse(H);if(!F.success)throw Error(`sandbox dispatch returned a malformed frame: ${F.error.message}`);if(J+=F.data.chunks.length,yield*F.data.chunks,K??=F.data.error,F.data.done)W=!0}}finally{G()}if(console.log("[sandbox-dispatch] run ended",{runId:$.runId,handle:$.handle,chunks:J,elapsedMs:Date.now()-Z,done:W,error:K?.code??null}),!W&&!K)throw new RY(`the sandbox stopped streaming after ${J} chunks without finishing the run`);if(K)throw So4(K.code,K.message)}function So4($,Z){if($===zo4)return new vv$(Z);if($===mV$)return new RY(Z);return Error(`${$}: ${Z}`)}async function*Co4($,Z){let Q=new TextDecoder,X="",Y=function*(J){let K=X.split(`
2860
2860
  `);X=J?K.pop()??"":"";for(let W of K){if(W.trim().length===0)continue;try{yield JSON.parse(W)}catch(H){throw Error(`sandbox dispatch produced a non-JSON line: ${H instanceof Error?H.message:String(H)} (line: ${W.slice(0,256)})`)}}},G=$[Symbol.asyncIterator]();try{for(;;){let J=new AbortController,K=G.next().then((F)=>{return J.abort(),F}),W=W$(Cv$,{signal:J.signal}).then(()=>"silent").catch(()=>"read-won"),H=await Promise.race([K,W]).catch((F)=>{if(Z?.aborted)throw F;let N=F instanceof Error?F.message:String(F);if(!t71(N))throw F;throw new RY(`the sandbox stream broke mid-run: ${N}`)});if(H==="silent"){if(Z?.aborted)return;throw new RY(`no output from the sandbox for ${Cv$/1000}s (its keepalive is every 15s, so the pod is gone)`)}if(H==="read-won")continue;if(H.done)break;if(X+=Q.decode(H.value,{stream:!0}),yield*Y(!0),X.length>_v$)throw Error(`sandbox dispatch produced a line over ${_v$} chars without a newline \u2014 refusing to buffer it further`)}X+=Q.decode(),yield*Y(!1)}finally{await G.return?.().catch(()=>{})}}function _o4($){return $.connections.filter((Z)=>($.orgWide||$.ownIds.has(Z.id))&&Z.status==="active"&&!vo4($.organizationId,Z.id))}function vo4($,Z){return[y8.SELF,y8.REGISTRY,y8.COMMUNITY_REGISTRY,y8.DEV_ASSETS,y8.COMMERCE_DISCOVERY].some((Q)=>Q($)===Z)}var Sv$="/repo",yv="claude-code",Eo4=2,jo4=5,Cv$=90000,_v$=67108864,RY,vv$,zo4="superseded",Ro4=30000,Mo4=300000;var RT0=L(()=>{J4();lV$();g71();KA0();Rv$();S91();rZ();g8();QY();qD();Vv$();DD();p5();xK();R$();Ma();bv();kK();RY=class RY extends Error{reason;constructor($,Z){super(`${WA0} ${$}${Z?` \u2014 ${Z}`:""}`);this.name="SandboxUnreachableError",this.reason=$}};vv$=class vv$ extends Error{superseded=!0;constructor($){super($);this.name="RunSupersededError"}}});function r71($){if($.providerId==="openai-compatible")try{let Z=JSON.parse($.apiKey);return{kind:"secret",providerId:$.providerId,apiKey:Z.apiKey??"",modelId:$.modelId,...Z.baseUrl?{baseUrl:Z.baseUrl}:{}}}catch{return{kind:"secret",providerId:$.providerId,apiKey:$.apiKey,modelId:$.modelId}}return{kind:"secret",providerId:$.providerId,apiKey:$.apiKey,modelId:$.modelId}}var fv$=L(()=>{tW();Gg()});var bv$=L(()=>{fv$()});import{z as Ks}from"zod/v4";import{z as V}from"zod/v4";import{z as F1}from"zod/v4";import{z as AZ}from"zod/v4";import{z as $3}from"zod/v4";import{z as y9}from"zod/v4";import{z as g9}from"zod/v4";import{z as V6}from"zod/v4";import{z as k6}from"zod/v4";import{z as cK}from"zod/v4";import{z as Q$}from"zod/v4";import{z as y1}from"zod/v4";import{z as gv}from"zod/v4";import{z as $Q1}from"zod/v4";import{z as ZQ1}from"zod/v4";import{z as Ws}from"zod/v4";import{z as eJ}from"zod/v4";import{z as S7}from"zod/v4";import{z as c6}from"zod/v4";import{z as uH}from"zod/v4";import{z as cH}from"zod/v4";import{z as lH}from"zod/v4";import{z as hv}from"zod/v4";function ho4($){var Z;let Q=$==null?void 0:$.anthropic;return(Z=Q==null?void 0:Q.cacheControl)!=null?Z:Q==null?void 0:Q.cache_control}async function Ur4({tools:$,toolChoice:Z,disableParallelToolUse:Q,cacheControlValidator:X,supportsStructuredOutput:Y,supportsStrictTools:G,defaultEagerInputStreaming:J=!1}){var K,W;$=($==null?void 0:$.length)?$:void 0;let H=[],F=new Set,N=X||new QQ1;if($==null)return{tools:void 0,toolChoice:void 0,toolWarnings:H,betas:F};let U=[];for(let O of $)switch(O.type){case"function":{let D=N.getCacheControl(O.providerOptions,{type:"tool definition",canCache:!0}),w=(K=O.providerOptions)==null?void 0:K.anthropic,E=(W=w==null?void 0:w.eagerInputStreaming)!=null?W:J,j=w==null?void 0:w.deferLoading,z=w==null?void 0:w.allowedCallers;if(!G&&O.strict!=null)H.push({type:"unsupported",feature:"strict",details:`Tool '${O.name}' has strict: ${O.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`});if(U.push({name:O.name,description:O.description,input_schema:O.inputSchema,cache_control:D,...E?{eager_input_streaming:!0}:{},...G===!0&&O.strict!=null?{strict:O.strict}:{},...j!=null?{defer_loading:j}:{},...z!=null?{allowed_callers:z}:{},...O.inputExamples!=null?{input_examples:O.inputExamples.map((A)=>A.input)}:{}}),Y===!0)F.add("structured-outputs-2025-11-13");if(O.inputExamples!=null||z!=null)F.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(O.id){case"anthropic.code_execution_20250522":{F.add("code-execution-2025-05-22"),U.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{F.add("code-execution-2025-08-25"),U.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{U.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"computer",type:"computer_20250124",display_width_px:O.args.displayWidthPx,display_height_px:O.args.displayHeightPx,display_number:O.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{F.add("computer-use-2025-11-24"),U.push({name:"computer",type:"computer_20251124",display_width_px:O.args.displayWidthPx,display_height_px:O.args.displayHeightPx,display_number:O.args.displayNumber,enable_zoom:O.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"computer",type:"computer_20241022",display_width_px:O.args.displayWidthPx,display_height_px:O.args.displayHeightPx,display_number:O.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{F.add("computer-use-2025-01-24"),U.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let D=await l$({value:O.args,schema:do4});U.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:D.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{F.add("context-management-2025-06-27"),U.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{F.add("web-fetch-2025-09-10");let D=await l$({value:O.args,schema:Wr4});U.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,citations:D.citations,max_content_tokens:D.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{F.add("code-execution-web-tools-2026-02-09");let D=await l$({value:O.args,schema:Xr4});U.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,citations:D.citations,max_content_tokens:D.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let D=await l$({value:O.args,schema:eo4});U.push({type:"web_search_20250305",name:"web_search",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,user_location:D.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{F.add("code-execution-web-tools-2026-02-09");let D=await l$({value:O.args,schema:to4});U.push({type:"web_search_20260209",name:"web_search",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,user_location:D.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{U.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{U.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}case"anthropic.advisor_20260301":{F.add("advisor-tool-2026-03-01");let D=await l$({value:O.args,schema:uo4});U.push({type:"advisor_20260301",name:"advisor",model:D.model,...D.maxUses!==void 0&&{max_uses:D.maxUses},...D.caching!==void 0&&{caching:D.caching}});break}default:{H.push({type:"unsupported",feature:`provider-defined tool ${O.id}`});break}}break}default:{H.push({type:"unsupported",feature:`tool ${O}`});break}}if(Z==null)return{tools:U,toolChoice:Q?{type:"auto",disable_parallel_tool_use:Q}:void 0,toolWarnings:H,betas:F};let B=Z.type;switch(B){case"auto":return{tools:U,toolChoice:{type:"auto",disable_parallel_tool_use:Q},toolWarnings:H,betas:F};case"required":return{tools:U,toolChoice:{type:"any",disable_parallel_tool_use:Q},toolWarnings:H,betas:F};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:H,betas:F};case"tool":return{tools:U,toolChoice:{type:"tool",name:Z.toolName,disable_parallel_tool_use:Q},toolWarnings:H,betas:F};default:throw new y4({functionality:`tool choice type: ${B}`})}}function cv$({usage:$,rawUsage:Z}){var Q,X,Y;let G=(Q=$.cache_creation_input_tokens)!=null?Q:0,J=(X=$.cache_read_input_tokens)!=null?X:0,K,W,H=(Y=$.iterations)==null?void 0:Y.some((F)=>F.type==="fallback_message");if($.iterations&&$.iterations.length>0&&!H){let F=$.iterations.filter((N)=>N.type==="compaction"||N.type==="message");if(F.length>0){let N=F.reduce((U,B)=>({input:U.input+B.input_tokens,output:U.output+B.output_tokens}),{input:0,output:0});K=N.input,W=N.output}else K=$.input_tokens,W=$.output_tokens}else K=$.input_tokens,W=$.output_tokens;return{inputTokens:{total:K+G+J,noCache:K,cacheRead:J,cacheWrite:G},outputTokens:{total:W,text:void 0,reasoning:void 0},raw:Z!=null?Z:$}}function Ir4($){if(typeof $==="string")return new TextDecoder().decode(_9($));if($ instanceof Uint8Array)return new TextDecoder().decode($);if($ instanceof URL)throw new y4({functionality:"URL-based text documents are not supported for citations"});throw new y4({functionality:`unsupported data type for text documents: ${typeof $}`})}function a71($){return $ instanceof URL||qr4($)}function qr4($){return typeof $==="string"&&/^https?:\/\//i.test($)}function s71($){return $ instanceof URL?$.toString():$}async function lv$($){if(typeof $==="string"){let Z=await sZ({text:$});if(Z.success&&typeof Z.value==="object"&&Z.value!==null)return Z.value;return{errorCode:"unavailable"}}if(typeof $==="object"&&$!==null)return $;return{}}async function Mr4({prompt:$,sendReasoning:Z,warnings:Q,cacheControlValidator:X,toolNameMapping:Y}){var G,J,K,W,H,F,N,U,B,O,D,w,E,j,z,A,P,I,q,M,S;let m=new Set,f=Vr4($),b=X||new QQ1,l=void 0,y=[];async function p(L0){var r,t;let D0=await Q4({provider:"anthropic",providerOptions:L0,schema:gv$});return(t=(r=D0==null?void 0:D0.citations)==null?void 0:r.enabled)!=null?t:!1}async function Y0(L0){let r=await Q4({provider:"anthropic",providerOptions:L0,schema:gv$});return{title:r==null?void 0:r.title,context:r==null?void 0:r.context}}for(let L0=0;L0<f.length;L0++){let r=f[L0],t=L0===f.length-1,D0=r.type;switch(D0){case"system":{let e=r.messages.map(({content:E0,providerOptions:u0})=>({type:"text",text:E0,cache_control:b.getCacheControl(u0,{type:"system message",canCache:!0})}));if(l==null)l=e;else y.push({role:"system",content:e}),m.add("mid-conversation-system-2026-04-07");break}case"user":{let e=[];for(let E0 of r.messages){let{role:u0,content:q0}=E0;switch(u0){case"user":{for(let m0=0;m0<q0.length;m0++){let J0=q0[m0],j0=m0===q0.length-1,P0=(G=b.getCacheControl(J0.providerOptions,{type:"user message part",canCache:!0}))!=null?G:j0?b.getCacheControl(E0.providerOptions,{type:"user message",canCache:!0}):void 0;switch(J0.type){case"text":{e.push({type:"text",text:J0.text,cache_control:P0});break}case"file":{if(J0.mediaType.startsWith("image/"))e.push({type:"image",source:a71(J0.data)?{type:"url",url:s71(J0.data)}:{type:"base64",media_type:J0.mediaType==="image/*"?"image/jpeg":J0.mediaType,data:EZ(J0.data)},cache_control:P0});else if(J0.mediaType==="application/pdf"){m.add("pdfs-2024-09-25");let M0=await p(J0.providerOptions),X0=await Y0(J0.providerOptions);e.push({type:"document",source:a71(J0.data)?{type:"url",url:s71(J0.data)}:{type:"base64",media_type:"application/pdf",data:EZ(J0.data)},title:(J=X0.title)!=null?J:J0.filename,...X0.context&&{context:X0.context},...M0&&{citations:{enabled:!0}},cache_control:P0})}else if(J0.mediaType==="text/plain"){let M0=await p(J0.providerOptions),X0=await Y0(J0.providerOptions);e.push({type:"document",source:a71(J0.data)?{type:"url",url:s71(J0.data)}:{type:"text",media_type:"text/plain",data:Ir4(J0.data)},title:(K=X0.title)!=null?K:J0.filename,...X0.context&&{context:X0.context},...M0&&{citations:{enabled:!0}},cache_control:P0})}else throw new y4({functionality:`media type: ${J0.mediaType}`});break}}}break}case"tool":{for(let m0=0;m0<q0.length;m0++){let J0=q0[m0];if(J0.type==="tool-approval-response")continue;let j0=J0.output,P0="providerOptions"in j0?j0.providerOptions:j0.type==="content"?(W=j0.value.find((V0)=>V0.providerOptions!=null))==null?void 0:W.providerOptions:void 0,M0=m0===q0.length-1,X0=(F=(H=b.getCacheControl(J0.providerOptions,{type:"tool result part",canCache:!0}))!=null?H:b.getCacheControl(P0,{type:"tool result output",canCache:!0}))!=null?F:M0?b.getCacheControl(E0.providerOptions,{type:"tool result message",canCache:!0}):void 0,G0;switch(j0.type){case"content":G0=j0.value.map((V0)=>{var N0;switch(V0.type){case"text":return{type:"text",text:V0.text};case"image-data":return{type:"image",source:{type:"base64",media_type:V0.mediaType,data:V0.data}};case"image-url":return{type:"image",source:{type:"url",url:V0.url}};case"file-url":return{type:"document",source:{type:"url",url:V0.url}};case"file-data":{if(V0.mediaType==="application/pdf")return m.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:V0.mediaType,data:V0.data}};Q.push({type:"other",message:`unsupported tool content part type: ${V0.type} with media type: ${V0.mediaType}`});return}case"custom":{let O0=(N0=V0.providerOptions)==null?void 0:N0.anthropic;if((O0==null?void 0:O0.type)==="tool-reference")return{type:"tool_reference",tool_name:O0.toolName};Q.push({type:"other",message:"unsupported custom tool content part"});return}default:{Q.push({type:"other",message:`unsupported tool content part type: ${V0.type}`});return}}}).filter(Pz);break;case"text":case"error-text":G0=j0.value;break;case"execution-denied":G0=(N=j0.reason)!=null?N:"Tool execution denied.";break;case"json":case"error-json":default:G0=JSON.stringify(j0.value);break}e.push({type:"tool_result",tool_use_id:J0.toolCallId,content:G0,is_error:j0.type==="error-text"||j0.type==="error-json"?!0:void 0,cache_control:X0})}break}default:throw Error(`Unsupported role: ${u0}`)}}y.push({role:"user",content:e});break}case"assistant":{let e=[],E0=new Set;for(let u0=0;u0<r.messages.length;u0++){let q0=r.messages[u0],m0=u0===r.messages.length-1,{content:J0}=q0;for(let j0=0;j0<J0.length;j0++){let P0=J0[j0],M0=j0===J0.length-1,X0=(U=b.getCacheControl(P0.providerOptions,{type:"assistant message part",canCache:!0}))!=null?U:M0?b.getCacheControl(q0.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(P0.type){case"text":{let G0=(B=P0.providerOptions)==null?void 0:B.anthropic;if((G0==null?void 0:G0.type)==="compaction")e.push({type:"compaction",content:P0.text,cache_control:X0});else e.push({type:"text",text:t&&m0&&M0?P0.text.trim():P0.text,cache_control:X0});break}case"reasoning":{if(Z){let G0=await Q4({provider:"anthropic",providerOptions:P0.providerOptions,schema:go4});if(G0!=null)if(G0.signature!=null)b.getCacheControl(P0.providerOptions,{type:"thinking block",canCache:!1}),e.push({type:"thinking",thinking:P0.text,signature:G0.signature});else if(G0.redactedData!=null)b.getCacheControl(P0.providerOptions,{type:"redacted thinking block",canCache:!1}),e.push({type:"redacted_thinking",data:G0.redactedData});else Q.push({type:"other",message:"unsupported reasoning metadata"});else Q.push({type:"other",message:"unsupported reasoning metadata"})}else Q.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(P0.providerExecuted){let N0=Y.toProviderToolName(P0.toolName);if(((D=(O=P0.providerOptions)==null?void 0:O.anthropic)==null?void 0:D.type)==="mcp-tool-use"){E0.add(P0.toolCallId);let P1=(E=(w=P0.providerOptions)==null?void 0:w.anthropic)==null?void 0:E.serverName;if(P1==null||typeof P1!=="string"){Q.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}e.push({type:"mcp_tool_use",id:P0.toolCallId,name:P0.toolName,input:P0.input,server_name:P1,cache_control:X0})}else if(N0==="code_execution"&&P0.input!=null&&typeof P0.input==="object"&&"type"in P0.input&&typeof P0.input.type==="string"&&(P0.input.type==="bash_code_execution"||P0.input.type==="text_editor_code_execution"))e.push({type:"server_tool_use",id:P0.toolCallId,name:P0.input.type,input:P0.input,cache_control:X0});else if(N0==="code_execution"&&P0.input!=null&&typeof P0.input==="object"&&"type"in P0.input&&P0.input.type==="programmatic-tool-call"){let{type:P1,...v0}=P0.input;e.push({type:"server_tool_use",id:P0.toolCallId,name:"code_execution",input:v0,cache_control:X0})}else if(N0==="code_execution"||N0==="web_fetch"||N0==="web_search")e.push({type:"server_tool_use",id:P0.toolCallId,name:N0,input:P0.input,cache_control:X0});else if(N0==="tool_search_tool_regex"||N0==="tool_search_tool_bm25")e.push({type:"server_tool_use",id:P0.toolCallId,name:N0,input:P0.input,cache_control:X0});else if(N0==="advisor")e.push({type:"server_tool_use",id:P0.toolCallId,name:"advisor",input:{},cache_control:X0});else Q.push({type:"other",message:`provider executed tool call for tool ${P0.toolName} is not supported`});break}let G0=(j=P0.providerOptions)==null?void 0:j.anthropic,V0=(G0==null?void 0:G0.caller)?(G0.caller.type==="code_execution_20250825"||G0.caller.type==="code_execution_20260120")&&G0.caller.toolId?{type:G0.caller.type,tool_id:G0.caller.toolId}:G0.caller.type==="direct"?{type:"direct"}:void 0:void 0;e.push({type:"tool_use",id:P0.toolCallId,name:P0.toolName,input:P0.input,...V0&&{caller:V0},cache_control:X0});break}case"tool-result":{let G0=Y.toProviderToolName(P0.toolName);if(E0.has(P0.toolCallId)){let V0=P0.output;if(V0.type!=="json"&&V0.type!=="error-json"){Q.push({type:"other",message:`provider executed tool result output type ${V0.type} for tool ${P0.toolName} is not supported`});break}e.push({type:"mcp_tool_result",tool_use_id:P0.toolCallId,is_error:V0.type==="error-json",content:V0.value,cache_control:X0})}else if(G0==="code_execution"){let V0=P0.output;if(V0.type==="error-text"||V0.type==="error-json"){let N0={};try{if(typeof V0.value==="string")N0=JSON.parse(V0.value);else if(typeof V0.value==="object"&&V0.value!==null)N0=V0.value}catch(O0){}if(N0.type==="code_execution_tool_result_error")e.push({type:"code_execution_tool_result",tool_use_id:P0.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(z=N0.errorCode)!=null?z:"unknown"},cache_control:X0});else e.push({type:"bash_code_execution_tool_result",tool_use_id:P0.toolCallId,cache_control:X0,content:{type:"bash_code_execution_tool_result_error",error_code:(A=N0.errorCode)!=null?A:"unknown"}});break}if(V0.type!=="json"){Q.push({type:"other",message:`provider executed tool result output type ${V0.type} for tool ${P0.toolName} is not supported`});break}if(V0.value==null||typeof V0.value!=="object"||!("type"in V0.value)||typeof V0.value.type!=="string"){Q.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${P0.toolName}`});break}if(V0.value.type==="code_execution_result"){let N0=await l$({value:V0.value,schema:av$});e.push({type:"code_execution_tool_result",tool_use_id:P0.toolCallId,content:{type:N0.type,stdout:N0.stdout,stderr:N0.stderr,return_code:N0.return_code,content:(P=N0.content)!=null?P:[]},cache_control:X0})}else if(V0.value.type==="encrypted_code_execution_result"){let N0=await l$({value:V0.value,schema:ev$});if(N0.type==="encrypted_code_execution_result")e.push({type:"code_execution_tool_result",tool_use_id:P0.toolCallId,content:{type:N0.type,encrypted_stdout:N0.encrypted_stdout,stderr:N0.stderr,return_code:N0.return_code,content:(I=N0.content)!=null?I:[]},cache_control:X0})}else{let N0=await l$({value:V0.value,schema:sv$});if(N0.type==="code_execution_result")e.push({type:"code_execution_tool_result",tool_use_id:P0.toolCallId,content:{type:N0.type,stdout:N0.stdout,stderr:N0.stderr,return_code:N0.return_code,content:(q=N0.content)!=null?q:[]},cache_control:X0});else if(N0.type==="bash_code_execution_result"||N0.type==="bash_code_execution_tool_result_error")e.push({type:"bash_code_execution_tool_result",tool_use_id:P0.toolCallId,cache_control:X0,content:N0});else e.push({type:"text_editor_code_execution_tool_result",tool_use_id:P0.toolCallId,cache_control:X0,content:N0})}break}if(G0==="web_fetch"){let V0=P0.output;if(V0.type==="error-json"){e.push({type:"web_fetch_tool_result",tool_use_id:P0.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(M=(await lv$(V0.value)).errorCode)!=null?M:"unavailable"},cache_control:X0});break}if(V0.type!=="json"){Q.push({type:"other",message:`provider executed tool result output type ${V0.type} for tool ${P0.toolName} is not supported`});break}let N0=await l$({value:V0.value,schema:rv$});e.push({type:"web_fetch_tool_result",tool_use_id:P0.toolCallId,content:{type:"web_fetch_result",url:N0.url,retrieved_at:N0.retrievedAt,content:{type:"document",title:N0.content.title,citations:N0.content.citations,source:{type:N0.content.source.type,media_type:N0.content.source.mediaType,data:N0.content.source.data}}},cache_control:X0});break}if(G0==="web_search"){let V0=P0.output;if(V0.type==="error-json"){e.push({type:"web_search_tool_result",tool_use_id:P0.toolCallId,content:{type:"web_search_tool_result_error",error_code:(S=(await lv$(V0.value)).errorCode)!=null?S:"unavailable"},cache_control:X0});break}if(V0.type!=="json"){Q.push({type:"other",message:`provider executed tool result output type ${V0.type} for tool ${P0.toolName} is not supported`});break}let N0=await l$({value:V0.value,schema:ov$});e.push({type:"web_search_tool_result",tool_use_id:P0.toolCallId,content:N0.map((O0)=>({url:O0.url,title:O0.title,page_age:O0.pageAge,encrypted_content:O0.encryptedContent,type:O0.type})),cache_control:X0});break}if(G0==="tool_search_tool_regex"||G0==="tool_search_tool_bm25"){let V0=P0.output;if(V0.type!=="json"){Q.push({type:"other",message:`provider executed tool result output type ${V0.type} for tool ${P0.toolName} is not supported`});break}let O0=(await l$({value:V0.value,schema:$x$})).map((P1)=>({type:"tool_reference",tool_name:P1.toolName}));e.push({type:"tool_search_tool_result",tool_use_id:P0.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:O0},cache_control:X0});break}if(G0==="advisor"){let V0=P0.output;if(V0.type!=="json"&&V0.type!=="error-json"){Q.push({type:"other",message:`provider executed tool result output type ${V0.type} for tool ${P0.toolName} is not supported`});break}let N0=await l$({value:V0.value,schema:tv$});if(N0.type==="advisor_result")e.push({type:"advisor_tool_result",tool_use_id:P0.toolCallId,content:{type:"advisor_result",text:N0.text},cache_control:X0});else if(N0.type==="advisor_redacted_result")e.push({type:"advisor_tool_result",tool_use_id:P0.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:N0.encryptedContent},cache_control:X0});else e.push({type:"advisor_tool_result",tool_use_id:P0.toolCallId,content:{type:"advisor_tool_result_error",error_code:N0.errorCode},cache_control:X0});break}Q.push({type:"other",message:`provider executed tool result for tool ${P0.toolName} is not supported`});break}}}}y.push({role:"assistant",content:e});break}default:throw Error(`content type: ${D0}`)}}return{prompt:{system:l,messages:y},betas:m}}function Vr4($){let Z=[],Q=void 0;for(let X of $){let{role:Y}=X;switch(Y){case"system":{if((Q==null?void 0:Q.type)!=="system")Q={type:"system",messages:[]},Z.push(Q);Q.messages.push(X);break}case"assistant":{if((Q==null?void 0:Q.type)!=="assistant")Q={type:"assistant",messages:[]},Z.push(Q);Q.messages.push(X);break}case"user":{if((Q==null?void 0:Q.type)!=="user")Q={type:"user",messages:[]},Z.push(Q);Q.messages.push(X);break}case"tool":{if((Q==null?void 0:Q.type)!=="user")Q={type:"user",messages:[]},Z.push(Q);Q.messages.push(X);break}default:throw Error(`Unsupported role: ${Y}`)}}return Z}function e71({finishReason:$,isJsonResponseFromTool:Z}){switch($){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return Z?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}function Sr4($){return Qx$($)}function SD($){if(typeof $==="boolean"||!xr4($))return $;return Qx$($)}function Qx$($){let Z={},Q=$;if($.$ref!=null)return{$ref:$.$ref};if($.$schema!=null)Z.$schema=$.$schema;if($.$id!=null)Z.$id=$.$id;if($.title!=null)Z.title=$.title;if($.description!=null)Z.description=$.description;if($.default!==void 0)Z.default=$.default;if($.const!==void 0)Z.const=$.const;if($.enum!=null)Z.enum=$.enum;if($.type!=null)Z.type=$.type;if($.anyOf!=null)Z.anyOf=$.anyOf.map(SD);else if($.oneOf!=null)Z.anyOf=$.oneOf.map(SD);if($.allOf!=null)Z.allOf=$.allOf.map(SD);if($.definitions!=null)Z.definitions=Object.fromEntries(Object.entries($.definitions).map(([Y,G])=>[Y,SD(G)]));if(Q.$defs!=null){let Y=Z;Y.$defs=Object.fromEntries(Object.entries(Q.$defs).map(([G,J])=>[G,SD(J)]))}if($.type==="object"||$.properties!=null){if($.properties!=null)Z.properties=Object.fromEntries(Object.entries($.properties).map(([Y,G])=>[Y,SD(G)]));if(Z.additionalProperties=!1,$.required!=null)Z.required=$.required}if($.items!=null)Z.items=Array.isArray($.items)?$.items.map(SD):SD($.items);if(typeof $.format==="string"&&Zx$.has($.format))Z.format=$.format;let X=Cr4($);if(X!=null)Z.description=Z.description==null?X:`${Z.description}
2861
2861
  ${X}`;return Z}function Cr4($){let Z=kr4.flatMap((Q)=>{let X=$[Q];if(X==null||X===!1)return[];return`${_r4(Q)}: ${vr4(X)}`});if(typeof $.format==="string"&&!Zx$.has($.format))Z.push(`format: ${$.format}`);return Z.length===0?void 0:`${Z.join("; ")}.`}function _r4($){return $.replace(/[A-Z]/g,(Z)=>` ${Z.toLowerCase()}`)}function vr4($){if(typeof $==="string")return $;return JSON.stringify($)}function xr4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function mv$($,Z,Q){var X;if($.type==="web_search_result_location")return{type:"source",sourceType:"url",id:Q(),url:$.url,title:$.title,providerMetadata:{anthropic:{citedText:$.cited_text,encryptedIndex:$.encrypted_index}}};if($.type!=="page_location"&&$.type!=="char_location")return;let Y=Z[$.document_index];if(!Y)return;return{type:"source",sourceType:"document",id:Q(),mediaType:Y.mediaType,title:(X=$.document_title)!=null?X:Y.title,filename:Y.filename,providerMetadata:{anthropic:$.type==="page_location"?{citedText:$.cited_text,startPageNumber:$.start_page_number,endPageNumber:$.end_page_number}:{citedText:$.cited_text,startCharIndex:$.start_char_index,endCharIndex:$.end_char_index}}}}function br4($){if($.includes("claude-opus-4-8")||$.includes("claude-opus-4-7")||$.includes("claude-fable-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,isKnownModel:!0};else if($.includes("claude-sonnet-4-6")||$.includes("claude-opus-4-6"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-sonnet-4-5")||$.includes("claude-opus-4-5")||$.includes("claude-haiku-4-5"))return{maxOutputTokens:64000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-opus-4-1"))return{maxOutputTokens:32000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-sonnet-4-"))return{maxOutputTokens:64000,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-opus-4-"))return{maxOutputTokens:32000,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-3-haiku"))return{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else return{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!1}}function dv$($){if(!$)return!1;let Z=!1,Q=!1;for(let X of $){if("type"in X&&(X.type==="web_fetch_20260209"||X.type==="web_search_20260209")){Z=!0;continue}if(X.name==="code_execution"){Q=!0;break}}return Z&&!Q}function iv$($){return $?{appliedEdits:$.applied_edits.map((Z)=>{switch(Z.type){case"clear_tool_uses_20250919":return{type:Z.type,clearedToolUses:Z.cleared_tool_uses,clearedInputTokens:Z.cleared_input_tokens};case"clear_thinking_20251015":return{type:Z.type,clearedThinkingTurns:Z.cleared_thinking_turns,clearedInputTokens:Z.cleared_input_tokens};case"compact_20260112":return{type:Z.type}}}).filter((Z)=>Z!==void 0)}:null}function pv$($){if($==null)return;return{type:$.type,...$.category!=null?{category:$.category}:{},...$.explanation!=null?{explanation:$.explanation}:{},...$.recommended_model!=null?{recommendedModel:$.recommended_model}:{}}}function Hs($={}){var Z,Q;let X=(Z=dL(zH({settingValue:$.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?Z:"https://api.anthropic.com/v1",Y=(Q=$.name)!=null?Q:"anthropic.messages";if($.apiKey&&$.authToken)throw new cL({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let G=()=>{let W=$.authToken?{Authorization:`Bearer ${$.authToken}`}:{"x-api-key":$u({apiKey:$.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return e4({"anthropic-version":"2023-06-01",...W,...$.headers},`ai-sdk/anthropic/${xo4}`)},J=(W)=>{var H;return new fr4(W,{provider:Y,baseURL:X,headers:G,fetch:$.fetch,generateId:(H=$.generateId)!=null?H:d8,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},K=function(W){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return J(W)};return K.specificationVersion="v3",K.languageModel=J,K.chat=J,K.messages=J,K.embeddingModel=(W)=>{throw new s5({modelId:W,modelType:"embeddingModel"})},K.textEmbeddingModel=K.embeddingModel,K.imageModel=(W)=>{throw new s5({modelId:W,modelType:"imageModel"})},K.tools=Ga4,K}var xo4="3.0.85",fo4,yv$,nv$,bo4,yo4,go4,gv$,hv$,uv$=4,QQ1=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl($,Z){let Q=ho4($);if(!Q)return;if(!Z.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${Z.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>uv$){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${uv$} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return Q}getWarnings(){return this.warnings}},uo4,tv$,co4,lo4,mo4=($)=>{return lo4($)},do4,io4,po4,no4=($={})=>{return po4($)},to4,oo4,ro4,ao4,so4=($={})=>{return ao4($)},eo4,ov$,$r4,Zr4,Qr4=($={})=>{return Zr4($)},Xr4,Yr4,Gr4,Jr4,Kr4=($={})=>{return Jr4($)},Wr4,rv$,Hr4,Fr4,Nr4=($={})=>{return Fr4($)},av$,Br4,Or4,Lr4=($={})=>{return Or4($)},sv$,Dr4,wr4,Er4=($={})=>{return wr4($)},ev$,jr4,zr4,Pr4=($={})=>{return zr4($)},$x$,Ar4,Tr4,Rr4=($={})=>{return Tr4($)},Zx$,kr4,fr4=class{constructor($,Z){this.specificationVersion="v3";var Q;this.modelId=$,this.config=Z,this.generateId=(Q=Z.generateId)!=null?Q:d8}supportsUrl($){return $.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let $=this.config.provider,Z=$.indexOf(".");return Z===-1?$:$.substring(0,Z)}get supportedUrls(){var $,Z,Q;return(Q=(Z=($=this.config).supportedUrls)==null?void 0:Z.call($))!=null?Q:{}}async getArgs({userSuppliedBetas:$,prompt:Z,maxOutputTokens:Q,temperature:X,topP:Y,topK:G,frequencyPenalty:J,presencePenalty:K,stopSequences:W,responseFormat:H,seed:F,tools:N,toolChoice:U,providerOptions:B,stream:O}){var D,w,E,j,z,A,P,I,q,M;let S=[];if(J!=null)S.push({type:"unsupported",feature:"frequencyPenalty"});if(K!=null)S.push({type:"unsupported",feature:"presencePenalty"});if(F!=null)S.push({type:"unsupported",feature:"seed"});if(X!=null&&X>1)S.push({type:"unsupported",feature:"temperature",details:`${X} exceeds anthropic maximum of 1.0. clamped to 1.0`}),X=1;else if(X!=null&&X<0)S.push({type:"unsupported",feature:"temperature",details:`${X} is below anthropic minimum of 0. clamped to 0`}),X=0;if((H==null?void 0:H.type)==="json"){if(H.schema==null)S.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."})}let m=this.providerOptionsName,f=await Q4({provider:"anthropic",providerOptions:B,schema:hv$}),b=m!=="anthropic"?await Q4({provider:m,providerOptions:B,schema:hv$}):null,l=b!=null,y=Object.assign({},f!=null?f:{},b!=null?b:{}),{maxOutputTokens:p,supportsStructuredOutput:Y0,rejectsSamplingParameters:L0,isKnownModel:r}=br4(this.modelId);if(L0){if(X!=null)S.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),X=void 0;if(G!=null)S.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),G=void 0;if(Y!=null)S.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),Y=void 0}let t=r||this.modelId.startsWith("claude-"),D0=((D=this.config.supportsNativeStructuredOutput)!=null?D:!0)&&Y0,e=((w=this.config.supportsStrictTools)!=null?w:!0)&&Y0,E0=(E=y==null?void 0:y.structuredOutputMode)!=null?E:"auto",u0=E0==="outputFormat"||E0==="auto"&&D0,q0=(H==null?void 0:H.type)==="json"&&H.schema!=null&&!u0?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:H.schema}:void 0,m0=y==null?void 0:y.contextManagement,J0=new QQ1,j0=M30({tools:N,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25","anthropic.advisor_20260301":"advisor"}}),{prompt:P0,betas:M0}=await Mr4({prompt:Z,sendReasoning:(j=y==null?void 0:y.sendReasoning)!=null?j:!0,warnings:S,cacheControlValidator:J0,toolNameMapping:j0}),X0=(z=y==null?void 0:y.thinking)==null?void 0:z.type,G0=X0==="enabled"||X0==="adaptive",V0=X0==="enabled"?(A=y==null?void 0:y.thinking)==null?void 0:A.budgetTokens:void 0,N0=X0==="adaptive"?(P=y==null?void 0:y.thinking)==null?void 0:P.display:void 0,O0=Q!=null?Q:p,P1={model:this.modelId,max_tokens:O0,temperature:X,top_k:G,top_p:Y,stop_sequences:W,...G0&&{thinking:{type:X0,...V0!=null&&{budget_tokens:V0},...N0!=null&&{display:N0}}},...((y==null?void 0:y.effort)||(y==null?void 0:y.taskBudget)||u0&&(H==null?void 0:H.type)==="json"&&H.schema!=null)&&{output_config:{...(y==null?void 0:y.effort)&&{effort:y.effort},...(y==null?void 0:y.taskBudget)&&{task_budget:{type:y.taskBudget.type,total:y.taskBudget.total,...y.taskBudget.remaining!=null&&{remaining:y.taskBudget.remaining}}},...u0&&(H==null?void 0:H.type)==="json"&&H.schema!=null&&{format:{type:"json_schema",schema:Sr4(H.schema)}}}},...(y==null?void 0:y.speed)&&{speed:y.speed},...(y==null?void 0:y.inferenceGeo)&&{inference_geo:y.inferenceGeo},...(y==null?void 0:y.fallbacks)&&y.fallbacks.length>0&&{fallbacks:y.fallbacks},...(y==null?void 0:y.cacheControl)&&{cache_control:y.cacheControl},...((I=y==null?void 0:y.metadata)==null?void 0:I.userId)!=null&&{metadata:{user_id:y.metadata.userId}},...(y==null?void 0:y.mcpServers)&&y.mcpServers.length>0&&{mcp_servers:y.mcpServers.map((_0)=>({type:_0.type,name:_0.name,url:_0.url,authorization_token:_0.authorizationToken,tool_configuration:_0.toolConfiguration?{allowed_tools:_0.toolConfiguration.allowedTools,enabled:_0.toolConfiguration.enabled}:void 0}))},...(y==null?void 0:y.container)&&{container:y.container.skills&&y.container.skills.length>0?{id:y.container.id,skills:y.container.skills.map((_0)=>({type:_0.type,skill_id:_0.skillId,version:_0.version}))}:y.container.id},system:P0.system,messages:P0.messages,...m0&&{context_management:{edits:m0.edits.map((_0)=>{let c1=_0.type;switch(c1){case"clear_tool_uses_20250919":return{type:_0.type,..._0.trigger!==void 0&&{trigger:_0.trigger},..._0.keep!==void 0&&{keep:_0.keep},..._0.clearAtLeast!==void 0&&{clear_at_least:_0.clearAtLeast},..._0.clearToolInputs!==void 0&&{clear_tool_inputs:_0.clearToolInputs},..._0.excludeTools!==void 0&&{exclude_tools:_0.excludeTools}};case"clear_thinking_20251015":return{type:_0.type,..._0.keep!==void 0&&{keep:_0.keep}};case"compact_20260112":return{type:_0.type,..._0.trigger!==void 0&&{trigger:_0.trigger},..._0.pauseAfterCompaction!==void 0&&{pause_after_compaction:_0.pauseAfterCompaction},..._0.instructions!==void 0&&{instructions:_0.instructions}};default:S.push({type:"other",message:`Unknown context management strategy: ${c1}`});return}}).filter((_0)=>_0!==void 0)}}};if(G0){if(X0==="enabled"&&V0==null)S.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),P1.thinking={type:"enabled",budget_tokens:1024},V0=1024;if(P1.temperature!=null)P1.temperature=void 0,S.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(G!=null)P1.top_k=void 0,S.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(Y!=null)P1.top_p=void 0,S.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});P1.max_tokens=O0+(V0!=null?V0:0)}else if(t&&Y!=null&&X!=null)S.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),P1.top_p=void 0;if(r&&P1.max_tokens>p){if(Q!=null)S.push({type:"unsupported",feature:"maxOutputTokens",details:`${P1.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${p} max output tokens. The max output tokens have been limited to ${p}.`});P1.max_tokens=p}if((y==null?void 0:y.mcpServers)&&y.mcpServers.length>0)M0.add("mcp-client-2025-04-04");if(m0){if(M0.add("context-management-2025-06-27"),m0.edits.some((_0)=>_0.type==="compact_20260112"))M0.add("compact-2026-01-12")}if((y==null?void 0:y.container)&&y.container.skills&&y.container.skills.length>0){if(M0.add("code-execution-2025-08-25"),M0.add("skills-2025-10-02"),M0.add("files-api-2025-04-14"),!(N==null?void 0:N.some((_0)=>_0.type==="provider"&&(_0.id==="anthropic.code_execution_20250825"||_0.id==="anthropic.code_execution_20260120"))))S.push({type:"other",message:"code execution tool is required when using skills"})}if(y==null?void 0:y.taskBudget)M0.add("task-budgets-2026-03-13");if((y==null?void 0:y.speed)==="fast")M0.add("fast-mode-2026-02-01");if((y==null?void 0:y.fallbacks)&&y.fallbacks.length>0)M0.add("server-side-fallback-2026-06-01");let v0=O&&((q=y==null?void 0:y.toolStreaming)!=null?q:!0),{tools:n0,toolChoice:o,toolWarnings:f0,betas:Q1}=await Ur4(q0!=null?{tools:[...N!=null?N:[],q0],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:J0,supportsStructuredOutput:!1,supportsStrictTools:e,defaultEagerInputStreaming:v0}:{tools:N!=null?N:[],toolChoice:U,disableParallelToolUse:y==null?void 0:y.disableParallelToolUse,cacheControlValidator:J0,supportsStructuredOutput:D0,supportsStrictTools:e,defaultEagerInputStreaming:v0}),k1=J0.getWarnings();return{args:{...P1,tools:n0,tool_choice:o,stream:O===!0?!0:void 0},warnings:[...S,...f0,...k1],betas:new Set([...M0,...Q1,...$,...(M=y==null?void 0:y.anthropicBeta)!=null?M:[]]),usesJsonResponseTool:q0!=null,toolNameMapping:j0,providerOptionsName:m,usedCustomProviderKey:l}}async getHeaders({betas:$,headers:Z}){return $8(await g$(this.config.headers),Z,$.size>0?{"anthropic-beta":Array.from($).join(",")}:{})}async getBetasFromHeaders($){var Z,Q;let Y=(Z=(await g$(this.config.headers))["anthropic-beta"])!=null?Z:"",G=(Q=$==null?void 0:$["anthropic-beta"])!=null?Q:"";return new Set([...Y.toLowerCase().split(","),...G.toLowerCase().split(",")].map((J)=>J.trim()).filter((J)=>J!==""))}buildRequestUrl($){var Z,Q,X;return(X=(Q=(Z=this.config).buildRequestUrl)==null?void 0:Q.call(Z,this.config.baseURL,$))!=null?X:`${this.config.baseURL}/messages`}transformRequestBody($,Z){var Q,X,Y;return(Y=(X=(Q=this.config).transformRequestBody)==null?void 0:X.call(Q,$,Z))!=null?Y:$}extractCitationDocuments($){let Z=(Q)=>{var X,Y;if(Q.type!=="file")return!1;if(Q.mediaType!=="application/pdf"&&Q.mediaType!=="text/plain")return!1;let G=(X=Q.providerOptions)==null?void 0:X.anthropic,J=G==null?void 0:G.citations;return(Y=J==null?void 0:J.enabled)!=null?Y:!1};return $.filter((Q)=>Q.role==="user").flatMap((Q)=>Q.content).filter(Z).map((Q)=>{var X;let Y=Q;return{title:(X=Y.filename)!=null?X:"Untitled Document",filename:Y.filename,mediaType:Y.mediaType}})}async doGenerate($){var Z,Q,X,Y,G,J,K;let{args:W,warnings:H,betas:F,usesJsonResponseTool:N,toolNameMapping:U,providerOptionsName:B,usedCustomProviderKey:O}=await this.getArgs({...$,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders($.headers)}),D=[...this.extractCitationDocuments($.prompt)],w=dv$(W.tools),{responseHeaders:E,value:j,rawValue:z}=await z8({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:F,headers:$.headers}),body:this.transformRequestBody(W,F),failedResponseHandler:yv$,successfulResponseHandler:G8(bo4),abortSignal:$.abortSignal,fetch:this.config.fetch}),A=[],P={},I={},q=!1;for(let M of j.content)switch(M.type){case"text":{if(!N){if(A.push({type:"text",text:M.text}),M.citations)for(let S of M.citations){let m=mv$(S,D,this.generateId);if(m)A.push(m)}}break}case"thinking":{A.push({type:"reasoning",text:M.thinking,providerMetadata:{anthropic:{signature:M.signature}}});break}case"redacted_thinking":{A.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:M.data}}});break}case"compaction":{A.push({type:"text",text:M.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(N&&M.name==="json")q=!0,A.push({type:"text",text:JSON.stringify(M.input)});else{let m=M.caller,f=m?{type:m.type,toolId:"tool_id"in m?m.tool_id:void 0}:void 0;A.push({type:"tool-call",toolCallId:M.id,toolName:M.name,input:JSON.stringify(M.input),...f&&{providerMetadata:{anthropic:{caller:f}}}})}break}case"server_tool_use":{if(M.name==="text_editor_code_execution"||M.name==="bash_code_execution")A.push({type:"tool-call",toolCallId:M.id,toolName:U.toCustomToolName("code_execution"),input:JSON.stringify({type:M.name,...M.input}),providerExecuted:!0,...w?{dynamic:!0}:{}});else if(M.name==="web_search"||M.name==="code_execution"||M.name==="web_fetch"){let S=M.name==="code_execution"&&M.input!=null&&typeof M.input==="object"&&"code"in M.input&&!("type"in M.input)?{type:"programmatic-tool-call",...M.input}:M.input;A.push({type:"tool-call",toolCallId:M.id,toolName:U.toCustomToolName(M.name),input:JSON.stringify(S),providerExecuted:!0,...w&&M.name==="code_execution"?{dynamic:!0}:{}})}else if(M.name==="tool_search_tool_regex"||M.name==="tool_search_tool_bm25")I[M.id]=M.name,A.push({type:"tool-call",toolCallId:M.id,toolName:U.toCustomToolName(M.name),input:JSON.stringify(M.input),providerExecuted:!0});else if(M.name==="advisor")A.push({type:"tool-call",toolCallId:M.id,toolName:U.toCustomToolName("advisor"),input:JSON.stringify(M.input),providerExecuted:!0});break}case"mcp_tool_use":{P[M.id]={type:"tool-call",toolCallId:M.id,toolName:M.name,input:JSON.stringify(M.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:M.server_name}}},A.push(P[M.id]);break}case"mcp_tool_result":{A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:P[M.tool_use_id].toolName,isError:M.is_error,result:M.content,dynamic:!0,providerMetadata:P[M.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{if(M.content.type==="web_fetch_result")D.push({title:(Z=M.content.content.title)!=null?Z:M.content.url,mediaType:M.content.content.source.media_type}),A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:M.content.url,retrievedAt:M.content.retrieved_at,content:{type:M.content.content.type,title:M.content.content.title,citations:M.content.content.citations,source:{type:M.content.content.source.type,mediaType:M.content.content.source.media_type,data:M.content.content.source.data}}}});else if(M.content.type==="web_fetch_tool_result_error")A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:M.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(M.content)){A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName("web_search"),result:M.content.map((S)=>{var m;return{url:S.url,title:S.title,pageAge:(m=S.page_age)!=null?m:null,encryptedContent:S.encrypted_content,type:S.type}})});for(let S of M.content)A.push({type:"source",sourceType:"url",id:this.generateId(),url:S.url,title:S.title,providerMetadata:{anthropic:{pageAge:(Q=S.page_age)!=null?Q:null}}})}else A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:M.content.error_code}});break}case"code_execution_tool_result":{if(M.content.type==="code_execution_result")A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:{type:M.content.type,stdout:M.content.stdout,stderr:M.content.stderr,return_code:M.content.return_code,content:(X=M.content.content)!=null?X:[]}});else if(M.content.type==="encrypted_code_execution_result")A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:{type:M.content.type,encrypted_stdout:M.content.encrypted_stdout,stderr:M.content.stderr,return_code:M.content.return_code,content:(Y=M.content.content)!=null?Y:[]}});else if(M.content.type==="code_execution_tool_result_error")A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:M.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:M.content});break}case"tool_search_tool_result":{let S=I[M.tool_use_id];if(S==null){let m=U.toCustomToolName("tool_search_tool_bm25"),f=U.toCustomToolName("tool_search_tool_regex");if(m!=="tool_search_tool_bm25")S="tool_search_tool_bm25";else if(f!=="tool_search_tool_regex")S="tool_search_tool_regex";else S="tool_search_tool_regex"}if(M.content.type==="tool_search_tool_search_result")A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName(S),result:M.content.tool_references.map((m)=>({type:m.type,toolName:m.tool_name}))});else A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:U.toCustomToolName(S),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:M.content.error_code}});break}case"advisor_tool_result":{let S=U.toCustomToolName("advisor");if(M.content.type==="advisor_result")A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:S,result:{type:"advisor_result",text:M.content.text}});else if(M.content.type==="advisor_redacted_result")A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:S,result:{type:"advisor_redacted_result",encryptedContent:M.content.encrypted_content}});else A.push({type:"tool-result",toolCallId:M.tool_use_id,toolName:S,isError:!0,result:{type:"advisor_tool_result_error",errorCode:M.content.error_code}});break}case"fallback":break}return{content:A,finishReason:{unified:e71({finishReason:j.stop_reason,isJsonResponseFromTool:q}),raw:(G=j.stop_reason)!=null?G:void 0},usage:cv$({usage:j.usage}),request:{body:W},response:{id:(J=j.id)!=null?J:void 0,modelId:(K=j.model)!=null?K:void 0,headers:E,body:z},warnings:H,providerMetadata:(()=>{var M,S,m,f,b;let l=pv$(j.stop_details),y={usage:j.usage,cacheCreationInputTokens:(M=j.usage.cache_creation_input_tokens)!=null?M:null,stopSequence:(S=j.stop_sequence)!=null?S:null,...l!=null?{stopDetails:l}:{},iterations:j.usage.iterations?j.usage.iterations.map((Y0)=>({type:Y0.type,...Y0.model!=null?{model:Y0.model}:{},inputTokens:Y0.input_tokens,outputTokens:Y0.output_tokens,...Y0.cache_creation_input_tokens?{cacheCreationInputTokens:Y0.cache_creation_input_tokens}:{},...Y0.cache_read_input_tokens?{cacheReadInputTokens:Y0.cache_read_input_tokens}:{}})):null,container:j.container?{expiresAt:j.container.expires_at,id:j.container.id,skills:(f=(m=j.container.skills)==null?void 0:m.map((Y0)=>({type:Y0.type,skillId:Y0.skill_id,version:Y0.version})))!=null?f:null}:null,contextManagement:(b=iv$(j.context_management))!=null?b:null},p={anthropic:y};if(O&&B!=="anthropic")p[B]=y;return p})()}}async doStream($){var Z,Q;let{args:X,warnings:Y,betas:G,usesJsonResponseTool:J,toolNameMapping:K,providerOptionsName:W,usedCustomProviderKey:H}=await this.getArgs({...$,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders($.headers)}),F=[...this.extractCitationDocuments($.prompt)],N=dv$(X.tools),U=this.buildRequestUrl(!0),{responseHeaders:B,value:O}=await z8({url:U,headers:await this.getHeaders({betas:G,headers:$.headers}),body:this.transformRequestBody(X,G),failedResponseHandler:yv$,successfulResponseHandler:wQ(yo4),abortSignal:$.abortSignal,fetch:this.config.fetch}),D={unified:"other",raw:void 0},w={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},E={},j={},z={},A=null,P=void 0,I=null,q=null,M=void 0,S=null,m=!1,f=void 0,b=this.generateId,l=O.pipeThrough(new TransformStream({start(L0){L0.enqueue({type:"stream-start",warnings:Y})},transform(L0,r){var t,D0,e,E0,u0,q0,m0,J0,j0,P0,M0,X0,G0,V0;if($.includeRawChunks)r.enqueue({type:"raw",rawValue:L0.rawValue});if(!L0.success){r.enqueue({type:"error",error:L0.error});return}let N0=L0.value;switch(N0.type){case"ping":return;case"content_block_start":{let O0=N0.content_block,P1=O0.type;if(P1==="fallback")return;switch(f=P1,P1){case"text":{if(J)return;E[N0.index]={type:"text"},r.enqueue({type:"text-start",id:String(N0.index)});return}case"thinking":{E[N0.index]={type:"reasoning"},r.enqueue({type:"reasoning-start",id:String(N0.index)});return}case"redacted_thinking":{E[N0.index]={type:"reasoning"},r.enqueue({type:"reasoning-start",id:String(N0.index),providerMetadata:{anthropic:{redactedData:O0.data}}});return}case"compaction":{E[N0.index]={type:"text"},r.enqueue({type:"text-start",id:String(N0.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(J&&O0.name==="json")m=!0,E[N0.index]={type:"text"},r.enqueue({type:"text-start",id:String(N0.index)});else{let n0=O0.caller,o=n0?{type:n0.type,toolId:"tool_id"in n0?n0.tool_id:void 0}:void 0,Q1=O0.input&&Object.keys(O0.input).length>0?JSON.stringify(O0.input):"";E[N0.index]={type:"tool-call",toolCallId:O0.id,toolName:O0.name,input:Q1,firstDelta:Q1.length===0,...o&&{caller:o}},r.enqueue({type:"tool-input-start",id:O0.id,toolName:O0.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(O0.name)){let v0=O0.name==="text_editor_code_execution"||O0.name==="bash_code_execution"?"code_execution":O0.name,n0=K.toCustomToolName(v0),o=O0.input!=null&&typeof O0.input==="object"&&Object.keys(O0.input).length>0?JSON.stringify(O0.input):"";E[N0.index]={type:"tool-call",toolCallId:O0.id,toolName:n0,input:o,providerExecuted:!0,...N&&v0==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:v0},r.enqueue({type:"tool-input-start",id:O0.id,toolName:n0,providerExecuted:!0,...N&&v0==="code_execution"?{dynamic:!0}:{}})}else if(O0.name==="tool_search_tool_regex"||O0.name==="tool_search_tool_bm25"){z[O0.id]=O0.name;let v0=K.toCustomToolName(O0.name);E[N0.index]={type:"tool-call",toolCallId:O0.id,toolName:v0,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:O0.name},r.enqueue({type:"tool-input-start",id:O0.id,toolName:v0,providerExecuted:!0})}else if(O0.name==="advisor"){let v0=K.toCustomToolName("advisor");E[N0.index]={type:"tool-call",toolCallId:O0.id,toolName:v0,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:O0.name},r.enqueue({type:"tool-input-start",id:O0.id,toolName:v0,providerExecuted:!0})}return}case"web_fetch_tool_result":{if(O0.content.type==="web_fetch_result")F.push({title:(t=O0.content.content.title)!=null?t:O0.content.url,mediaType:O0.content.content.source.media_type}),r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:O0.content.url,retrievedAt:O0.content.retrieved_at,content:{type:O0.content.content.type,title:O0.content.content.title,citations:O0.content.content.citations,source:{type:O0.content.content.source.type,mediaType:O0.content.content.source.media_type,data:O0.content.content.source.data}}}});else if(O0.content.type==="web_fetch_tool_result_error")r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:O0.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(O0.content)){r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName("web_search"),result:O0.content.map((v0)=>{var n0;return{url:v0.url,title:v0.title,pageAge:(n0=v0.page_age)!=null?n0:null,encryptedContent:v0.encrypted_content,type:v0.type}})});for(let v0 of O0.content)r.enqueue({type:"source",sourceType:"url",id:b(),url:v0.url,title:v0.title,providerMetadata:{anthropic:{pageAge:(D0=v0.page_age)!=null?D0:null}}})}else r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:O0.content.error_code}});return}case"code_execution_tool_result":{if(O0.content.type==="code_execution_result")r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName("code_execution"),result:{type:O0.content.type,stdout:O0.content.stdout,stderr:O0.content.stderr,return_code:O0.content.return_code,content:(e=O0.content.content)!=null?e:[]}});else if(O0.content.type==="encrypted_code_execution_result")r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName("code_execution"),result:{type:O0.content.type,encrypted_stdout:O0.content.encrypted_stdout,stderr:O0.content.stderr,return_code:O0.content.return_code,content:(E0=O0.content.content)!=null?E0:[]}});else if(O0.content.type==="code_execution_tool_result_error")r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:O0.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName("code_execution"),result:O0.content});return}case"tool_search_tool_result":{let v0=z[O0.tool_use_id];if(v0==null){let n0=K.toCustomToolName("tool_search_tool_bm25"),o=K.toCustomToolName("tool_search_tool_regex");if(n0!=="tool_search_tool_bm25")v0="tool_search_tool_bm25";else if(o!=="tool_search_tool_regex")v0="tool_search_tool_regex";else v0="tool_search_tool_regex"}if(O0.content.type==="tool_search_tool_search_result")r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName(v0),result:O0.content.tool_references.map((n0)=>({type:n0.type,toolName:n0.tool_name}))});else r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:K.toCustomToolName(v0),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:O0.content.error_code}});return}case"advisor_tool_result":{let v0=K.toCustomToolName("advisor");if(O0.content.type==="advisor_result")r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:v0,result:{type:"advisor_result",text:O0.content.text}});else if(O0.content.type==="advisor_redacted_result")r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:v0,result:{type:"advisor_redacted_result",encryptedContent:O0.content.encrypted_content}});else r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:v0,isError:!0,result:{type:"advisor_tool_result_error",errorCode:O0.content.error_code}});return}case"mcp_tool_use":{j[O0.id]={type:"tool-call",toolCallId:O0.id,toolName:O0.name,input:JSON.stringify(O0.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:O0.server_name}}},r.enqueue(j[O0.id]);return}case"mcp_tool_result":{r.enqueue({type:"tool-result",toolCallId:O0.tool_use_id,toolName:j[O0.tool_use_id].toolName,isError:O0.is_error,result:O0.content,dynamic:!0,providerMetadata:j[O0.tool_use_id].providerMetadata});return}default:throw Error(`Unsupported content block type: ${P1}`)}}case"content_block_stop":{if(E[N0.index]!=null){let O0=E[N0.index];switch(O0.type){case"text":{r.enqueue({type:"text-end",id:String(N0.index)});break}case"reasoning":{r.enqueue({type:"reasoning-end",id:String(N0.index)});break}case"tool-call":if(!(J&&O0.toolName==="json")){r.enqueue({type:"tool-input-end",id:O0.toolCallId});let v0=O0.input===""?"{}":O0.input;if(O0.providerToolName==="code_execution")try{let n0=JSON.parse(v0);if(n0!=null&&typeof n0==="object"&&"code"in n0&&!("type"in n0))v0=JSON.stringify({type:"programmatic-tool-call",...n0})}catch(n0){}r.enqueue({type:"tool-call",toolCallId:O0.toolCallId,toolName:O0.toolName,input:v0,providerExecuted:O0.providerExecuted,...N&&O0.providerToolName==="code_execution"?{dynamic:!0}:{},...O0.caller&&{providerMetadata:{anthropic:{caller:O0.caller}}}})}break}delete E[N0.index]}f=void 0;return}case"content_block_delta":{let O0=N0.delta.type;switch(O0){case"text_delta":{if(J)return;r.enqueue({type:"text-delta",id:String(N0.index),delta:N0.delta.text});return}case"thinking_delta":{r.enqueue({type:"reasoning-delta",id:String(N0.index),delta:N0.delta.thinking});return}case"signature_delta":{if(f==="thinking")r.enqueue({type:"reasoning-delta",id:String(N0.index),delta:"",providerMetadata:{anthropic:{signature:N0.delta.signature}}});return}case"compaction_delta":{if(N0.delta.content!=null)r.enqueue({type:"text-delta",id:String(N0.index),delta:N0.delta.content});return}case"input_json_delta":{let P1=E[N0.index],v0=N0.delta.partial_json;if(v0.length===0)return;if(m){if((P1==null?void 0:P1.type)!=="text")return;r.enqueue({type:"text-delta",id:String(N0.index),delta:v0})}else{if((P1==null?void 0:P1.type)!=="tool-call")return;if(P1.firstDelta&&P1.providerToolName==="code_execution")v0=`{"type": "programmatic-tool-call",${v0.substring(1)}`;r.enqueue({type:"tool-input-delta",id:P1.toolCallId,delta:v0}),P1.input+=v0,P1.firstDelta=!1}return}case"citations_delta":{let P1=N0.delta.citation,v0=mv$(P1,F,b);if(v0)r.enqueue(v0);return}default:throw Error(`Unsupported delta type: ${O0}`)}}case"message_start":{if(w.input_tokens=N0.message.usage.input_tokens,w.cache_read_input_tokens=(u0=N0.message.usage.cache_read_input_tokens)!=null?u0:0,w.cache_creation_input_tokens=(q0=N0.message.usage.cache_creation_input_tokens)!=null?q0:0,P={...N0.message.usage},I=(m0=N0.message.usage.cache_creation_input_tokens)!=null?m0:null,N0.message.container!=null)S={expiresAt:N0.message.container.expires_at,id:N0.message.container.id,skills:null};if(N0.message.stop_reason!=null)D={unified:e71({finishReason:N0.message.stop_reason,isJsonResponseFromTool:m}),raw:N0.message.stop_reason};if(r.enqueue({type:"response-metadata",id:(J0=N0.message.id)!=null?J0:void 0,modelId:(j0=N0.message.model)!=null?j0:void 0}),N0.message.content!=null)for(let O0=0;O0<N0.message.content.length;O0++){let P1=N0.message.content[O0];if(P1.type==="tool_use"){let v0=P1.caller,n0=v0?{type:v0.type,toolId:"tool_id"in v0?v0.tool_id:void 0}:void 0;r.enqueue({type:"tool-input-start",id:P1.id,toolName:P1.name});let o=JSON.stringify((P0=P1.input)!=null?P0:{});r.enqueue({type:"tool-input-delta",id:P1.id,delta:o}),r.enqueue({type:"tool-input-end",id:P1.id}),r.enqueue({type:"tool-call",toolCallId:P1.id,toolName:P1.name,input:o,...n0&&{providerMetadata:{anthropic:{caller:n0}}}})}}return}case"message_delta":{if(N0.usage.input_tokens!=null&&w.input_tokens!==N0.usage.input_tokens)w.input_tokens=N0.usage.input_tokens;if(w.output_tokens=N0.usage.output_tokens,N0.usage.cache_read_input_tokens!=null)w.cache_read_input_tokens=N0.usage.cache_read_input_tokens;if(N0.usage.cache_creation_input_tokens!=null)w.cache_creation_input_tokens=N0.usage.cache_creation_input_tokens,I=N0.usage.cache_creation_input_tokens;if(N0.usage.iterations!=null)w.iterations=N0.usage.iterations;if(D={unified:e71({finishReason:N0.delta.stop_reason,isJsonResponseFromTool:m}),raw:(M0=N0.delta.stop_reason)!=null?M0:void 0},q=(X0=N0.delta.stop_sequence)!=null?X0:null,M=pv$(N0.delta.stop_details),S=N0.delta.container!=null?{expiresAt:N0.delta.container.expires_at,id:N0.delta.container.id,skills:(V0=(G0=N0.delta.container.skills)==null?void 0:G0.map((O0)=>({type:O0.type,skillId:O0.skill_id,version:O0.version})))!=null?V0:null}:null,N0.context_management)A=iv$(N0.context_management);P={...P,...N0.usage};return}case"message_stop":{let O0={usage:P!=null?P:null,cacheCreationInputTokens:I,stopSequence:q,...M!=null?{stopDetails:M}:{},iterations:w.iterations?w.iterations.map((v0)=>({type:v0.type,...v0.model!=null?{model:v0.model}:{},inputTokens:v0.input_tokens,outputTokens:v0.output_tokens,...v0.cache_creation_input_tokens?{cacheCreationInputTokens:v0.cache_creation_input_tokens}:{},...v0.cache_read_input_tokens?{cacheReadInputTokens:v0.cache_read_input_tokens}:{}})):null,container:S,contextManagement:A},P1={anthropic:O0};if(H&&W!=="anthropic")P1[W]=O0;r.enqueue({type:"finish",finishReason:D,usage:cv$({usage:w,rawUsage:P}),providerMetadata:P1});return}case"error":{r.enqueue({type:"error",error:N0.error});return}default:throw Error(`Unsupported chunk type: ${N0}`)}}})),[y,p]=l.tee(),Y0=y.getReader();try{await Y0.read();let L0=await Y0.read();if(((Z=L0.value)==null?void 0:Z.type)==="raw")L0=await Y0.read();if(((Q=L0.value)==null?void 0:Q.type)==="error"){let r=L0.value.error;throw new H4({message:r.message,url:U,requestBodyValues:X,statusCode:r.type==="overloaded_error"?529:500,responseHeaders:B,responseBody:JSON.stringify(r),isRetryable:r.type==="overloaded_error"})}}finally{Y0.cancel().catch(()=>{}),Y0.releaseLock()}return{stream:p,request:{body:X},response:{headers:B}}}},yr4,gr4,hr4,ur4,cr4,lr4,mr4,dr4,ir4,pr4,nr4,tr4,or4,rr4,ar4,sr4,er4,$a4,Za4,Qa4,Xa4,Ya4=($={})=>{return Xa4($)},Ga4,nHZ;var XQ1=L(()=>{$$();h0();$$();h0();h0();h0();$$();h0();h0();h0();h0();h0();h0();h0();$$();h0();h0();h0();h0();h0();h0();h0();h0();h0();h0();h0();h0();h0();h0();h0();fo4=w0(()=>Z0(Ks.object({type:Ks.literal("error"),error:Ks.object({type:Ks.string(),message:Ks.string()})}))),yv$=h5({errorSchema:fo4,errorToMessage:($)=>$.error.message}),nv$=V.object({type:V.string(),category:V.string().nullish(),explanation:V.string().nullish(),recommended_model:V.string().nullish()}),bo4=w0(()=>Z0(V.object({type:V.literal("message"),id:V.string().nullish(),model:V.string().nullish(),content:V.array(V.discriminatedUnion("type",[V.object({type:V.literal("text"),text:V.string(),citations:V.array(V.discriminatedUnion("type",[V.object({type:V.literal("web_search_result_location"),cited_text:V.string(),url:V.string(),title:V.string(),encrypted_index:V.string()}),V.object({type:V.literal("page_location"),cited_text:V.string(),document_index:V.number(),document_title:V.string().nullable(),start_page_number:V.number(),end_page_number:V.number()}),V.object({type:V.literal("char_location"),cited_text:V.string(),document_index:V.number(),document_title:V.string().nullable(),start_char_index:V.number(),end_char_index:V.number()})])).optional()}),V.object({type:V.literal("thinking"),thinking:V.string(),signature:V.string()}),V.object({type:V.literal("redacted_thinking"),data:V.string()}),V.object({type:V.literal("compaction"),content:V.string()}),V.object({type:V.literal("tool_use"),id:V.string(),name:V.string(),input:V.unknown(),caller:V.union([V.object({type:V.literal("code_execution_20250825"),tool_id:V.string()}),V.object({type:V.literal("code_execution_20260120"),tool_id:V.string()}),V.object({type:V.literal("direct")})]).optional()}),V.object({type:V.literal("server_tool_use"),id:V.string(),name:V.string(),input:V.record(V.string(),V.unknown()).nullish(),caller:V.union([V.object({type:V.literal("code_execution_20260120"),tool_id:V.string()}),V.object({type:V.literal("direct")})]).optional()}),V.object({type:V.literal("mcp_tool_use"),id:V.string(),name:V.string(),input:V.unknown(),server_name:V.string()}),V.object({type:V.literal("mcp_tool_result"),tool_use_id:V.string(),is_error:V.boolean(),content:V.array(V.union([V.string(),V.object({type:V.literal("text"),text:V.string()})]))}),V.object({type:V.literal("web_fetch_tool_result"),tool_use_id:V.string(),content:V.union([V.object({type:V.literal("web_fetch_result"),url:V.string(),retrieved_at:V.string(),content:V.object({type:V.literal("document"),title:V.string().nullable(),citations:V.object({enabled:V.boolean()}).optional(),source:V.union([V.object({type:V.literal("base64"),media_type:V.literal("application/pdf"),data:V.string()}),V.object({type:V.literal("text"),media_type:V.literal("text/plain"),data:V.string()})])})}),V.object({type:V.literal("web_fetch_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("web_search_tool_result"),tool_use_id:V.string(),content:V.union([V.array(V.object({type:V.literal("web_search_result"),url:V.string(),title:V.string(),encrypted_content:V.string(),page_age:V.string().nullish()})),V.object({type:V.literal("web_search_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("code_execution_tool_result"),tool_use_id:V.string(),content:V.union([V.object({type:V.literal("code_execution_result"),stdout:V.string(),stderr:V.string(),return_code:V.number(),content:V.array(V.object({type:V.literal("code_execution_output"),file_id:V.string()})).optional().default([])}),V.object({type:V.literal("encrypted_code_execution_result"),encrypted_stdout:V.string(),stderr:V.string(),return_code:V.number(),content:V.array(V.object({type:V.literal("code_execution_output"),file_id:V.string()})).optional().default([])}),V.object({type:V.literal("code_execution_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("bash_code_execution_tool_result"),tool_use_id:V.string(),content:V.discriminatedUnion("type",[V.object({type:V.literal("bash_code_execution_result"),content:V.array(V.object({type:V.literal("bash_code_execution_output"),file_id:V.string()})),stdout:V.string(),stderr:V.string(),return_code:V.number()}),V.object({type:V.literal("bash_code_execution_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("text_editor_code_execution_tool_result"),tool_use_id:V.string(),content:V.discriminatedUnion("type",[V.object({type:V.literal("text_editor_code_execution_tool_result_error"),error_code:V.string()}),V.object({type:V.literal("text_editor_code_execution_view_result"),content:V.string(),file_type:V.string(),num_lines:V.number().nullable(),start_line:V.number().nullable(),total_lines:V.number().nullable()}),V.object({type:V.literal("text_editor_code_execution_create_result"),is_file_update:V.boolean()}),V.object({type:V.literal("text_editor_code_execution_str_replace_result"),lines:V.array(V.string()).nullable(),new_lines:V.number().nullable(),new_start:V.number().nullable(),old_lines:V.number().nullable(),old_start:V.number().nullable()})])}),V.object({type:V.literal("tool_search_tool_result"),tool_use_id:V.string(),content:V.union([V.object({type:V.literal("tool_search_tool_search_result"),tool_references:V.array(V.object({type:V.literal("tool_reference"),tool_name:V.string()}))}),V.object({type:V.literal("tool_search_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("advisor_tool_result"),tool_use_id:V.string(),content:V.discriminatedUnion("type",[V.object({type:V.literal("advisor_result"),text:V.string()}),V.object({type:V.literal("advisor_redacted_result"),encrypted_content:V.string()}),V.object({type:V.literal("advisor_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("fallback")})])),stop_reason:V.string().nullish(),stop_sequence:V.string().nullish(),stop_details:nv$.nullish(),usage:V.looseObject({input_tokens:V.number(),output_tokens:V.number(),cache_creation_input_tokens:V.number().nullish(),cache_read_input_tokens:V.number().nullish(),iterations:V.array(V.object({type:V.union([V.literal("compaction"),V.literal("message"),V.literal("advisor_message"),V.literal("fallback_message")]),model:V.string().nullish(),input_tokens:V.number(),output_tokens:V.number(),cache_creation_input_tokens:V.number().nullish(),cache_read_input_tokens:V.number().nullish()})).nullish()}),container:V.object({expires_at:V.string(),id:V.string(),skills:V.array(V.object({type:V.union([V.literal("anthropic"),V.literal("custom")]),skill_id:V.string(),version:V.string()})).nullish()}).nullish(),context_management:V.object({applied_edits:V.array(V.union([V.object({type:V.literal("clear_tool_uses_20250919"),cleared_tool_uses:V.number(),cleared_input_tokens:V.number()}),V.object({type:V.literal("clear_thinking_20251015"),cleared_thinking_turns:V.number(),cleared_input_tokens:V.number()}),V.object({type:V.literal("compact_20260112")})]))}).nullish()}))),yo4=w0(()=>Z0(V.discriminatedUnion("type",[V.object({type:V.literal("message_start"),message:V.object({id:V.string().nullish(),model:V.string().nullish(),role:V.string().nullish(),usage:V.looseObject({input_tokens:V.number(),cache_creation_input_tokens:V.number().nullish(),cache_read_input_tokens:V.number().nullish()}),content:V.array(V.discriminatedUnion("type",[V.object({type:V.literal("tool_use"),id:V.string(),name:V.string(),input:V.unknown(),caller:V.union([V.object({type:V.literal("code_execution_20250825"),tool_id:V.string()}),V.object({type:V.literal("code_execution_20260120"),tool_id:V.string()}),V.object({type:V.literal("direct")})]).optional()})])).nullish(),stop_reason:V.string().nullish(),container:V.object({expires_at:V.string(),id:V.string()}).nullish()})}),V.object({type:V.literal("content_block_start"),index:V.number(),content_block:V.discriminatedUnion("type",[V.object({type:V.literal("text"),text:V.string()}),V.object({type:V.literal("thinking"),thinking:V.string()}),V.object({type:V.literal("tool_use"),id:V.string(),name:V.string(),input:V.record(V.string(),V.unknown()).optional(),caller:V.union([V.object({type:V.literal("code_execution_20250825"),tool_id:V.string()}),V.object({type:V.literal("code_execution_20260120"),tool_id:V.string()}),V.object({type:V.literal("direct")})]).optional()}),V.object({type:V.literal("redacted_thinking"),data:V.string()}),V.object({type:V.literal("compaction"),content:V.string().nullish()}),V.object({type:V.literal("server_tool_use"),id:V.string(),name:V.string(),input:V.record(V.string(),V.unknown()).nullish(),caller:V.union([V.object({type:V.literal("code_execution_20260120"),tool_id:V.string()}),V.object({type:V.literal("direct")})]).optional()}),V.object({type:V.literal("mcp_tool_use"),id:V.string(),name:V.string(),input:V.unknown(),server_name:V.string()}),V.object({type:V.literal("mcp_tool_result"),tool_use_id:V.string(),is_error:V.boolean(),content:V.array(V.union([V.string(),V.object({type:V.literal("text"),text:V.string()})]))}),V.object({type:V.literal("web_fetch_tool_result"),tool_use_id:V.string(),content:V.union([V.object({type:V.literal("web_fetch_result"),url:V.string(),retrieved_at:V.string(),content:V.object({type:V.literal("document"),title:V.string().nullable(),citations:V.object({enabled:V.boolean()}).optional(),source:V.union([V.object({type:V.literal("base64"),media_type:V.literal("application/pdf"),data:V.string()}),V.object({type:V.literal("text"),media_type:V.literal("text/plain"),data:V.string()})])})}),V.object({type:V.literal("web_fetch_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("web_search_tool_result"),tool_use_id:V.string(),content:V.union([V.array(V.object({type:V.literal("web_search_result"),url:V.string(),title:V.string(),encrypted_content:V.string(),page_age:V.string().nullish()})),V.object({type:V.literal("web_search_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("code_execution_tool_result"),tool_use_id:V.string(),content:V.union([V.object({type:V.literal("code_execution_result"),stdout:V.string(),stderr:V.string(),return_code:V.number(),content:V.array(V.object({type:V.literal("code_execution_output"),file_id:V.string()})).optional().default([])}),V.object({type:V.literal("encrypted_code_execution_result"),encrypted_stdout:V.string(),stderr:V.string(),return_code:V.number(),content:V.array(V.object({type:V.literal("code_execution_output"),file_id:V.string()})).optional().default([])}),V.object({type:V.literal("code_execution_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("bash_code_execution_tool_result"),tool_use_id:V.string(),content:V.discriminatedUnion("type",[V.object({type:V.literal("bash_code_execution_result"),content:V.array(V.object({type:V.literal("bash_code_execution_output"),file_id:V.string()})),stdout:V.string(),stderr:V.string(),return_code:V.number()}),V.object({type:V.literal("bash_code_execution_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("text_editor_code_execution_tool_result"),tool_use_id:V.string(),content:V.discriminatedUnion("type",[V.object({type:V.literal("text_editor_code_execution_tool_result_error"),error_code:V.string()}),V.object({type:V.literal("text_editor_code_execution_view_result"),content:V.string(),file_type:V.string(),num_lines:V.number().nullable(),start_line:V.number().nullable(),total_lines:V.number().nullable()}),V.object({type:V.literal("text_editor_code_execution_create_result"),is_file_update:V.boolean()}),V.object({type:V.literal("text_editor_code_execution_str_replace_result"),lines:V.array(V.string()).nullable(),new_lines:V.number().nullable(),new_start:V.number().nullable(),old_lines:V.number().nullable(),old_start:V.number().nullable()})])}),V.object({type:V.literal("tool_search_tool_result"),tool_use_id:V.string(),content:V.union([V.object({type:V.literal("tool_search_tool_search_result"),tool_references:V.array(V.object({type:V.literal("tool_reference"),tool_name:V.string()}))}),V.object({type:V.literal("tool_search_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("advisor_tool_result"),tool_use_id:V.string(),content:V.discriminatedUnion("type",[V.object({type:V.literal("advisor_result"),text:V.string()}),V.object({type:V.literal("advisor_redacted_result"),encrypted_content:V.string()}),V.object({type:V.literal("advisor_tool_result_error"),error_code:V.string()})])}),V.object({type:V.literal("fallback")})])}),V.object({type:V.literal("content_block_delta"),index:V.number(),delta:V.discriminatedUnion("type",[V.object({type:V.literal("input_json_delta"),partial_json:V.string()}),V.object({type:V.literal("text_delta"),text:V.string()}),V.object({type:V.literal("thinking_delta"),thinking:V.string()}),V.object({type:V.literal("signature_delta"),signature:V.string()}),V.object({type:V.literal("compaction_delta"),content:V.string().nullish()}),V.object({type:V.literal("citations_delta"),citation:V.discriminatedUnion("type",[V.object({type:V.literal("web_search_result_location"),cited_text:V.string(),url:V.string(),title:V.string(),encrypted_index:V.string()}),V.object({type:V.literal("page_location"),cited_text:V.string(),document_index:V.number(),document_title:V.string().nullable(),start_page_number:V.number(),end_page_number:V.number()}),V.object({type:V.literal("char_location"),cited_text:V.string(),document_index:V.number(),document_title:V.string().nullable(),start_char_index:V.number(),end_char_index:V.number()})])})])}),V.object({type:V.literal("content_block_stop"),index:V.number()}),V.object({type:V.literal("error"),error:V.object({type:V.string(),message:V.string()})}),V.object({type:V.literal("message_delta"),delta:V.object({stop_reason:V.string().nullish(),stop_sequence:V.string().nullish(),stop_details:nv$.nullish(),container:V.object({expires_at:V.string(),id:V.string(),skills:V.array(V.object({type:V.union([V.literal("anthropic"),V.literal("custom")]),skill_id:V.string(),version:V.string()})).nullish()}).nullish()}),usage:V.looseObject({input_tokens:V.number().nullish(),output_tokens:V.number(),cache_creation_input_tokens:V.number().nullish(),cache_read_input_tokens:V.number().nullish(),iterations:V.array(V.object({type:V.union([V.literal("compaction"),V.literal("message"),V.literal("advisor_message"),V.literal("fallback_message")]),model:V.string().nullish(),input_tokens:V.number(),output_tokens:V.number(),cache_creation_input_tokens:V.number().nullish(),cache_read_input_tokens:V.number().nullish()})).nullish()}),context_management:V.object({applied_edits:V.array(V.union([V.object({type:V.literal("clear_tool_uses_20250919"),cleared_tool_uses:V.number(),cleared_input_tokens:V.number()}),V.object({type:V.literal("clear_thinking_20251015"),cleared_thinking_turns:V.number(),cleared_input_tokens:V.number()}),V.object({type:V.literal("compact_20260112")})]))}).nullish()}),V.object({type:V.literal("message_stop")}),V.object({type:V.literal("ping")})]))),go4=w0(()=>Z0(V.object({signature:V.string().optional(),redactedData:V.string().optional()}))),gv$=F1.object({citations:F1.object({enabled:F1.boolean()}).optional(),title:F1.string().optional(),context:F1.string().optional()}),hv$=F1.object({sendReasoning:F1.boolean().optional(),structuredOutputMode:F1.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:F1.discriminatedUnion("type",[F1.object({type:F1.literal("adaptive"),display:F1.enum(["omitted","summarized"]).optional()}),F1.object({type:F1.literal("enabled"),budgetTokens:F1.number().optional()}),F1.object({type:F1.literal("disabled")})]).optional(),disableParallelToolUse:F1.boolean().optional(),cacheControl:F1.object({type:F1.literal("ephemeral"),ttl:F1.union([F1.literal("5m"),F1.literal("1h")]).optional()}).optional(),metadata:F1.object({userId:F1.string().optional()}).optional(),mcpServers:F1.array(F1.object({type:F1.literal("url"),name:F1.string(),url:F1.string(),authorizationToken:F1.string().nullish(),toolConfiguration:F1.object({enabled:F1.boolean().nullish(),allowedTools:F1.array(F1.string()).nullish()}).nullish()})).optional(),container:F1.object({id:F1.string().optional(),skills:F1.array(F1.object({type:F1.union([F1.literal("anthropic"),F1.literal("custom")]),skillId:F1.string(),version:F1.string().optional()})).optional()}).optional(),toolStreaming:F1.boolean().optional(),effort:F1.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:F1.object({type:F1.literal("tokens"),total:F1.number().int().min(20000),remaining:F1.number().int().min(0).optional()}).optional(),speed:F1.enum(["fast","standard"]).optional(),inferenceGeo:F1.enum(["us","global"]).optional(),fallbacks:F1.array(F1.object({model:F1.string(),max_tokens:F1.number().int().optional(),thinking:F1.record(F1.string(),F1.unknown()).optional(),output_config:F1.record(F1.string(),F1.unknown()).optional(),speed:F1.enum(["fast","standard"]).optional()})).optional(),anthropicBeta:F1.array(F1.string()).optional(),contextManagement:F1.object({edits:F1.array(F1.discriminatedUnion("type",[F1.object({type:F1.literal("clear_tool_uses_20250919"),trigger:F1.discriminatedUnion("type",[F1.object({type:F1.literal("input_tokens"),value:F1.number()}),F1.object({type:F1.literal("tool_uses"),value:F1.number()})]).optional(),keep:F1.object({type:F1.literal("tool_uses"),value:F1.number()}).optional(),clearAtLeast:F1.object({type:F1.literal("input_tokens"),value:F1.number()}).optional(),clearToolInputs:F1.boolean().optional(),excludeTools:F1.array(F1.string()).optional()}),F1.object({type:F1.literal("clear_thinking_20251015"),keep:F1.union([F1.literal("all"),F1.object({type:F1.literal("thinking_turns"),value:F1.number()})]).optional()}),F1.object({type:F1.literal("compact_20260112"),trigger:F1.object({type:F1.literal("input_tokens"),value:F1.number()}).optional(),pauseAfterCompaction:F1.boolean().optional(),instructions:F1.string().optional()})]))}).optional()});uo4=w0(()=>Z0(AZ.object({model:AZ.string(),maxUses:AZ.number().optional(),caching:AZ.object({type:AZ.literal("ephemeral"),ttl:AZ.union([AZ.literal("5m"),AZ.literal("1h")])}).optional()}))),tv$=w0(()=>Z0(AZ.discriminatedUnion("type",[AZ.object({type:AZ.literal("advisor_result"),text:AZ.string()}),AZ.object({type:AZ.literal("advisor_redacted_result"),encryptedContent:AZ.string()}),AZ.object({type:AZ.literal("advisor_tool_result_error"),errorCode:AZ.string()})]))),co4=w0(()=>Z0(AZ.object({}).strict())),lo4=Z8({id:"anthropic.advisor_20260301",inputSchema:co4,outputSchema:tv$,supportsDeferredResults:!0}),do4=w0(()=>Z0($3.object({maxCharacters:$3.number().optional()}))),io4=w0(()=>Z0($3.object({command:$3.enum(["view","create","str_replace","insert"]),path:$3.string(),file_text:$3.string().optional(),insert_line:$3.number().int().optional(),new_str:$3.string().optional(),insert_text:$3.string().optional(),old_str:$3.string().optional(),view_range:$3.array($3.number().int()).optional()}))),po4=g4({id:"anthropic.text_editor_20250728",inputSchema:io4}),to4=w0(()=>Z0(y9.object({maxUses:y9.number().optional(),allowedDomains:y9.array(y9.string()).optional(),blockedDomains:y9.array(y9.string()).optional(),userLocation:y9.object({type:y9.literal("approximate"),city:y9.string().optional(),region:y9.string().optional(),country:y9.string().optional(),timezone:y9.string().optional()}).optional()}))),oo4=w0(()=>Z0(y9.array(y9.object({url:y9.string(),title:y9.string().nullable(),pageAge:y9.string().nullable(),encryptedContent:y9.string(),type:y9.literal("web_search_result")})))),ro4=w0(()=>Z0(y9.object({query:y9.string()}))),ao4=Z8({id:"anthropic.web_search_20260209",inputSchema:ro4,outputSchema:oo4,supportsDeferredResults:!0}),eo4=w0(()=>Z0(g9.object({maxUses:g9.number().optional(),allowedDomains:g9.array(g9.string()).optional(),blockedDomains:g9.array(g9.string()).optional(),userLocation:g9.object({type:g9.literal("approximate"),city:g9.string().optional(),region:g9.string().optional(),country:g9.string().optional(),timezone:g9.string().optional()}).optional()}))),ov$=w0(()=>Z0(g9.array(g9.object({url:g9.string(),title:g9.string().nullable(),pageAge:g9.string().nullable(),encryptedContent:g9.string(),type:g9.literal("web_search_result")})))),$r4=w0(()=>Z0(g9.object({query:g9.string()}))),Zr4=Z8({id:"anthropic.web_search_20250305",inputSchema:$r4,outputSchema:ov$,supportsDeferredResults:!0}),Xr4=w0(()=>Z0(V6.object({maxUses:V6.number().optional(),allowedDomains:V6.array(V6.string()).optional(),blockedDomains:V6.array(V6.string()).optional(),citations:V6.object({enabled:V6.boolean()}).optional(),maxContentTokens:V6.number().optional()}))),Yr4=w0(()=>Z0(V6.object({type:V6.literal("web_fetch_result"),url:V6.string(),content:V6.object({type:V6.literal("document"),title:V6.string().nullable(),citations:V6.object({enabled:V6.boolean()}).optional(),source:V6.union([V6.object({type:V6.literal("base64"),mediaType:V6.literal("application/pdf"),data:V6.string()}),V6.object({type:V6.literal("text"),mediaType:V6.literal("text/plain"),data:V6.string()})])}),retrievedAt:V6.string().nullable()}))),Gr4=w0(()=>Z0(V6.object({url:V6.string()}))),Jr4=Z8({id:"anthropic.web_fetch_20260209",inputSchema:Gr4,outputSchema:Yr4,supportsDeferredResults:!0}),Wr4=w0(()=>Z0(k6.object({maxUses:k6.number().optional(),allowedDomains:k6.array(k6.string()).optional(),blockedDomains:k6.array(k6.string()).optional(),citations:k6.object({enabled:k6.boolean()}).optional(),maxContentTokens:k6.number().optional()}))),rv$=w0(()=>Z0(k6.object({type:k6.literal("web_fetch_result"),url:k6.string(),content:k6.object({type:k6.literal("document"),title:k6.string().nullable(),citations:k6.object({enabled:k6.boolean()}).optional(),source:k6.union([k6.object({type:k6.literal("base64"),mediaType:k6.literal("application/pdf"),data:k6.string()}),k6.object({type:k6.literal("text"),mediaType:k6.literal("text/plain"),data:k6.string()})])}),retrievedAt:k6.string().nullable()}))),Hr4=w0(()=>Z0(k6.object({url:k6.string()}))),Fr4=Z8({id:"anthropic.web_fetch_20250910",inputSchema:Hr4,outputSchema:rv$,supportsDeferredResults:!0});av$=w0(()=>Z0(cK.object({type:cK.literal("code_execution_result"),stdout:cK.string(),stderr:cK.string(),return_code:cK.number(),content:cK.array(cK.object({type:cK.literal("code_execution_output"),file_id:cK.string()})).optional().default([])}))),Br4=w0(()=>Z0(cK.object({code:cK.string()}))),Or4=Z8({id:"anthropic.code_execution_20250522",inputSchema:Br4,outputSchema:av$}),sv$=w0(()=>Z0(Q$.discriminatedUnion("type",[Q$.object({type:Q$.literal("code_execution_result"),stdout:Q$.string(),stderr:Q$.string(),return_code:Q$.number(),content:Q$.array(Q$.object({type:Q$.literal("code_execution_output"),file_id:Q$.string()})).optional().default([])}),Q$.object({type:Q$.literal("bash_code_execution_result"),content:Q$.array(Q$.object({type:Q$.literal("bash_code_execution_output"),file_id:Q$.string()})),stdout:Q$.string(),stderr:Q$.string(),return_code:Q$.number()}),Q$.object({type:Q$.literal("bash_code_execution_tool_result_error"),error_code:Q$.string()}),Q$.object({type:Q$.literal("text_editor_code_execution_tool_result_error"),error_code:Q$.string()}),Q$.object({type:Q$.literal("text_editor_code_execution_view_result"),content:Q$.string(),file_type:Q$.string(),num_lines:Q$.number().nullable(),start_line:Q$.number().nullable(),total_lines:Q$.number().nullable()}),Q$.object({type:Q$.literal("text_editor_code_execution_create_result"),is_file_update:Q$.boolean()}),Q$.object({type:Q$.literal("text_editor_code_execution_str_replace_result"),lines:Q$.array(Q$.string()).nullable(),new_lines:Q$.number().nullable(),new_start:Q$.number().nullable(),old_lines:Q$.number().nullable(),old_start:Q$.number().nullable()})]))),Dr4=w0(()=>Z0(Q$.discriminatedUnion("type",[Q$.object({type:Q$.literal("programmatic-tool-call"),code:Q$.string()}),Q$.object({type:Q$.literal("bash_code_execution"),command:Q$.string()}),Q$.discriminatedUnion("command",[Q$.object({type:Q$.literal("text_editor_code_execution"),command:Q$.literal("view"),path:Q$.string()}),Q$.object({type:Q$.literal("text_editor_code_execution"),command:Q$.literal("create"),path:Q$.string(),file_text:Q$.string().nullish()}),Q$.object({type:Q$.literal("text_editor_code_execution"),command:Q$.literal("str_replace"),path:Q$.string(),old_str:Q$.string(),new_str:Q$.string()})])]))),wr4=Z8({id:"anthropic.code_execution_20250825",inputSchema:Dr4,outputSchema:sv$,supportsDeferredResults:!0}),ev$=w0(()=>Z0(y1.discriminatedUnion("type",[y1.object({type:y1.literal("code_execution_result"),stdout:y1.string(),stderr:y1.string(),return_code:y1.number(),content:y1.array(y1.object({type:y1.literal("code_execution_output"),file_id:y1.string()})).optional().default([])}),y1.object({type:y1.literal("encrypted_code_execution_result"),encrypted_stdout:y1.string(),stderr:y1.string(),return_code:y1.number(),content:y1.array(y1.object({type:y1.literal("code_execution_output"),file_id:y1.string()})).optional().default([])}),y1.object({type:y1.literal("bash_code_execution_result"),content:y1.array(y1.object({type:y1.literal("bash_code_execution_output"),file_id:y1.string()})),stdout:y1.string(),stderr:y1.string(),return_code:y1.number()}),y1.object({type:y1.literal("bash_code_execution_tool_result_error"),error_code:y1.string()}),y1.object({type:y1.literal("text_editor_code_execution_tool_result_error"),error_code:y1.string()}),y1.object({type:y1.literal("text_editor_code_execution_view_result"),content:y1.string(),file_type:y1.string(),num_lines:y1.number().nullable(),start_line:y1.number().nullable(),total_lines:y1.number().nullable()}),y1.object({type:y1.literal("text_editor_code_execution_create_result"),is_file_update:y1.boolean()}),y1.object({type:y1.literal("text_editor_code_execution_str_replace_result"),lines:y1.array(y1.string()).nullable(),new_lines:y1.number().nullable(),new_start:y1.number().nullable(),old_lines:y1.number().nullable(),old_start:y1.number().nullable()})]))),jr4=w0(()=>Z0(y1.discriminatedUnion("type",[y1.object({type:y1.literal("programmatic-tool-call"),code:y1.string()}),y1.object({type:y1.literal("bash_code_execution"),command:y1.string()}),y1.discriminatedUnion("command",[y1.object({type:y1.literal("text_editor_code_execution"),command:y1.literal("view"),path:y1.string()}),y1.object({type:y1.literal("text_editor_code_execution"),command:y1.literal("create"),path:y1.string(),file_text:y1.string().nullish()}),y1.object({type:y1.literal("text_editor_code_execution"),command:y1.literal("str_replace"),path:y1.string(),old_str:y1.string(),new_str:y1.string()})])]))),zr4=Z8({id:"anthropic.code_execution_20260120",inputSchema:jr4,outputSchema:ev$,supportsDeferredResults:!0}),$x$=w0(()=>Z0(gv.array(gv.object({type:gv.literal("tool_reference"),toolName:gv.string()})))),Ar4=w0(()=>Z0(gv.object({pattern:gv.string(),limit:gv.number().optional()}))),Tr4=Z8({id:"anthropic.tool_search_regex_20251119",inputSchema:Ar4,outputSchema:$x$,supportsDeferredResults:!0});Zx$=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),kr4=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];yr4=w0(()=>Z0($Q1.object({command:$Q1.string(),restart:$Q1.boolean().optional()}))),gr4=g4({id:"anthropic.bash_20241022",inputSchema:yr4}),hr4=w0(()=>Z0(ZQ1.object({command:ZQ1.string(),restart:ZQ1.boolean().optional()}))),ur4=g4({id:"anthropic.bash_20250124",inputSchema:hr4}),cr4=w0(()=>Z0(Ws.object({action:Ws.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:Ws.array(Ws.number().int()).optional(),text:Ws.string().optional()}))),lr4=g4({id:"anthropic.computer_20241022",inputSchema:cr4}),mr4=w0(()=>Z0(eJ.object({action:eJ.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:eJ.tuple([eJ.number().int(),eJ.number().int()]).optional(),duration:eJ.number().optional(),scroll_amount:eJ.number().optional(),scroll_direction:eJ.enum(["up","down","left","right"]).optional(),start_coordinate:eJ.tuple([eJ.number().int(),eJ.number().int()]).optional(),text:eJ.string().optional()}))),dr4=g4({id:"anthropic.computer_20250124",inputSchema:mr4}),ir4=w0(()=>Z0(S7.object({action:S7.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:S7.tuple([S7.number().int(),S7.number().int()]).optional(),duration:S7.number().optional(),region:S7.tuple([S7.number().int(),S7.number().int(),S7.number().int(),S7.number().int()]).optional(),scroll_amount:S7.number().optional(),scroll_direction:S7.enum(["up","down","left","right"]).optional(),start_coordinate:S7.tuple([S7.number().int(),S7.number().int()]).optional(),text:S7.string().optional()}))),pr4=g4({id:"anthropic.computer_20251124",inputSchema:ir4}),nr4=w0(()=>Z0(c6.discriminatedUnion("command",[c6.object({command:c6.literal("view"),path:c6.string(),view_range:c6.tuple([c6.number(),c6.number()]).optional()}),c6.object({command:c6.literal("create"),path:c6.string(),file_text:c6.string()}),c6.object({command:c6.literal("str_replace"),path:c6.string(),old_str:c6.string(),new_str:c6.string()}),c6.object({command:c6.literal("insert"),path:c6.string(),insert_line:c6.number(),insert_text:c6.string()}),c6.object({command:c6.literal("delete"),path:c6.string()}),c6.object({command:c6.literal("rename"),old_path:c6.string(),new_path:c6.string()})]))),tr4=g4({id:"anthropic.memory_20250818",inputSchema:nr4}),or4=w0(()=>Z0(uH.object({command:uH.enum(["view","create","str_replace","insert","undo_edit"]),path:uH.string(),file_text:uH.string().optional(),insert_line:uH.number().int().optional(),new_str:uH.string().optional(),insert_text:uH.string().optional(),old_str:uH.string().optional(),view_range:uH.array(uH.number().int()).optional()}))),rr4=g4({id:"anthropic.text_editor_20241022",inputSchema:or4}),ar4=w0(()=>Z0(cH.object({command:cH.enum(["view","create","str_replace","insert","undo_edit"]),path:cH.string(),file_text:cH.string().optional(),insert_line:cH.number().int().optional(),new_str:cH.string().optional(),insert_text:cH.string().optional(),old_str:cH.string().optional(),view_range:cH.array(cH.number().int()).optional()}))),sr4=g4({id:"anthropic.text_editor_20250124",inputSchema:ar4}),er4=w0(()=>Z0(lH.object({command:lH.enum(["view","create","str_replace","insert"]),path:lH.string(),file_text:lH.string().optional(),insert_line:lH.number().int().optional(),new_str:lH.string().optional(),insert_text:lH.string().optional(),old_str:lH.string().optional(),view_range:lH.array(lH.number().int()).optional()}))),$a4=g4({id:"anthropic.text_editor_20250429",inputSchema:er4}),Za4=w0(()=>Z0(hv.array(hv.object({type:hv.literal("tool_reference"),toolName:hv.string()})))),Qa4=w0(()=>Z0(hv.object({query:hv.string(),limit:hv.number().optional()}))),Xa4=Z8({id:"anthropic.tool_search_bm25_20251119",inputSchema:Qa4,outputSchema:Za4,supportsDeferredResults:!0}),Ga4={advisor_20260301:mo4,bash_20241022:gr4,bash_20250124:ur4,codeExecution_20250522:Lr4,codeExecution_20250825:Er4,codeExecution_20260120:Pr4,computer_20241022:lr4,computer_20250124:dr4,computer_20251124:pr4,memory_20250818:tr4,textEditor_20241022:rr4,textEditor_20250124:sr4,textEditor_20250429:$a4,textEditor_20250728:no4,webFetch_20250910:Nr4,webFetch_20260209:Kr4,webSearch_20250305:Qr4,webSearch_20260209:so4,toolSearchRegex_20251119:Rr4,toolSearchBm25_20251119:Ya4};nHZ=Hs()});import{z as zU}from"zod/v4";import{z as Fs}from"zod/v4";import{z as qQ}from"zod/v4";import{z as c0}from"zod/v4";import{z as O6}from"zod/v4";import{z as Wc}from"zod/v4";import{z as Ca4}from"zod/v4";import{z as Ns}from"zod/v4";import{z as ba4}from"zod/v4";import{z as uv}from"zod/v4";import{z as ua4}from"zod/v4";import{z as YQ1}from"zod/v4";import{z as cv}from"zod/v4";import{z as j9}from"zod/v4";import{z as B0}from"zod/v4";import{z as t1}from"zod/v4";function Xx$($){var Z,Q,X,Y;if($==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let G=(Z=$.promptTokenCount)!=null?Z:0,J=(Q=$.candidatesTokenCount)!=null?Q:0,K=(X=$.cachedContentTokenCount)!=null?X:0,W=(Y=$.thoughtsTokenCount)!=null?Y:0;return{inputTokens:{total:G,noCache:G-K,cacheRead:K,cacheWrite:void 0},outputTokens:{total:J+W,text:J,reasoning:W},raw:$}}function lK($,Z=!0){if($==null)return;if(Ba4($)){if(Z)return;if(typeof $==="object"&&$.description)return{type:"object",description:$.description};return{type:"object"}}if(typeof $==="boolean")return{type:"boolean",properties:{}};let{type:Q,description:X,required:Y,properties:G,items:J,allOf:K,anyOf:W,oneOf:H,format:F,const:N,minLength:U,enum:B}=$,O={};if(X)O.description=X;if(Y)O.required=Y;if(F)O.format=F;if(N!==void 0)O.enum=[N];if(Q)if(Array.isArray(Q)){let D=Q.includes("null"),w=Q.filter((E)=>E!=="null");if(w.length===0)O.type="null";else if(O.anyOf=w.map((E)=>({type:E})),D)O.nullable=!0}else O.type=Q;if(B!==void 0)O.enum=B;if(G!=null)O.properties=Object.entries(G).reduce((D,[w,E])=>{return D[w]=lK(E,!1),D},{});if(J)O.items=Array.isArray(J)?J.map((D)=>lK(D,!1)):lK(J,!1);if(K)O.allOf=K.map((D)=>lK(D,!1));if(W)if(W.some((D)=>typeof D==="object"&&(D==null?void 0:D.type)==="null")){let D=W.filter((w)=>!(typeof w==="object"&&(w==null?void 0:w.type)==="null"));if(D.length===1){let w=lK(D[0],!1);if(typeof w==="object")O.nullable=!0,Object.assign(O,w)}else O.anyOf=D.map((w)=>lK(w,!1)),O.nullable=!0}else O.anyOf=W.map((D)=>lK(D,!1));if(H)O.oneOf=H.map((D)=>lK(D,!1));if(U!==void 0)O.minLength=U;return O}function Ba4($){return $!=null&&typeof $==="object"&&$.type==="object"&&($.properties==null||Object.keys($.properties).length===0)&&!$.additionalProperties}function Yx$($,Z){let Q=[Z,"google","googleVertex","vertex"].filter((X,Y,G)=>{return G.indexOf(X)===Y});for(let X of Q){let Y=$==null?void 0:$[X];if(Y!=null)return Y}}function Da4($){let Z=La4.exec($);if(Z==null)return;return{mediaType:Z[1],data:Z[2]}}function wa4($){let Z=Da4($);if(Z==null)return;return{inlineData:{mimeType:Z.mediaType,data:Z.data}}}function Ea4($,Z,Q,X){let Y=[],G=[];for(let J of Q)switch(J.type){case"text":{G.push(J.text);break}case"image-data":case"file-data":{Y.push({inlineData:{mimeType:J.mediaType,data:J.data}});break}case"image-url":case"file-url":{let K=wa4(J.url);if(K!=null)Y.push(K);else G.push(JSON.stringify(J));break}default:{G.push(JSON.stringify(J));break}}$.push({functionResponse:{...X!=null?{id:X}:{},name:Z,response:{name:Z,content:G.length>0?G.join(`
2862
2862
  `):"Tool executed successfully."},...Y.length>0?{parts:Y}:{}}})}function ja4($,Z,Q,X){for(let Y of Q)switch(Y.type){case"text":$.push({functionResponse:{...X!=null?{id:X}:{},name:Z,response:{name:Z,content:Y.text}}});break;case"image-data":$.push({inlineData:{mimeType:String(Y.mediaType),data:String(Y.data)}},{text:"Tool executed successfully and returned this image as a response"});break;default:$.push({text:JSON.stringify(Y)});break}}function za4($,Z){var Q,X,Y,G,J;let K=[],W=[],H=!0,F=(Q=Z==null?void 0:Z.isGemmaModel)!=null?Q:!1,N=(X=Z==null?void 0:Z.isGemini3Model)!=null?X:!1,U=(Y=Z==null?void 0:Z.providerOptionsName)!=null?Y:"google",B=(G=Z==null?void 0:Z.supportsFunctionResponseParts)!=null?G:!0,O=Z==null?void 0:Z.onWarning,D=!1,w=[],E=(j)=>{return w.push(j),D=!0,Oa4};for(let{role:j,content:z}of $)switch(j){case"system":{if(!H)throw new y4({functionality:"system messages are only supported at the beginning of the conversation"});K.push({text:z});break}case"user":{H=!1;let A=[];for(let P of z)switch(P.type){case"text":{A.push({text:P.text});break}case"file":{let I=P.mediaType==="image/*"?"image/jpeg":P.mediaType;A.push(P.data instanceof URL?{fileData:{mimeType:I,fileUri:P.data.toString()}}:{inlineData:{mimeType:I,data:EZ(P.data)}});break}}W.push({role:"user",parts:A});break}case"assistant":{H=!1,W.push({role:"model",parts:z.map((A)=>{let P=Yx$(A.providerOptions,U),I=(P==null?void 0:P.thoughtSignature)!=null?String(P.thoughtSignature):void 0;switch(A.type){case"text":return A.text.length===0?void 0:{text:A.text,thoughtSignature:I};case"reasoning":return A.text.length===0?void 0:{text:A.text,thought:!0,thoughtSignature:I};case"file":{if(A.data instanceof URL)throw new y4({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:A.mediaType,data:EZ(A.data)},...(P==null?void 0:P.thought)===!0?{thought:!0}:{},thoughtSignature:I}}case"tool-call":{let q=(P==null?void 0:P.serverToolCallId)!=null?String(P.serverToolCallId):void 0,M=(P==null?void 0:P.serverToolType)!=null?String(P.serverToolType):void 0,S=I!=null?I:N?E(A.toolName):void 0;if(q&&M)return{toolCall:{toolType:M,args:typeof A.input==="string"?JSON.parse(A.input):A.input,id:q},thoughtSignature:S};return{functionCall:{...A.toolCallId!=null?{id:A.toolCallId}:{},name:A.toolName,args:A.input},thoughtSignature:S}}case"tool-result":{let q=(P==null?void 0:P.serverToolCallId)!=null?String(P.serverToolCallId):void 0,M=(P==null?void 0:P.serverToolType)!=null?String(P.serverToolType):void 0;if(q&&M)return{toolResponse:{toolType:M,response:A.output.type==="json"?A.output.value:{},id:q},thoughtSignature:I};return}}}).filter((A)=>A!==void 0)});break}case"tool":{H=!1;let A=[];for(let P of z){if(P.type==="tool-approval-response")continue;let I=Yx$(P.providerOptions,U),q=(I==null?void 0:I.serverToolCallId)!=null?String(I.serverToolCallId):void 0,M=(I==null?void 0:I.serverToolType)!=null?String(I.serverToolType):void 0;if(q&&M){let m=(I==null?void 0:I.thoughtSignature)!=null?String(I.thoughtSignature):void 0;if(W.length>0){let f=W[W.length-1];if(f.role==="model"){f.parts.push({toolResponse:{toolType:M,response:P.output.type==="json"?P.output.value:{},id:q},thoughtSignature:m});continue}}}let S=P.output;if(S.type==="content")if(B)Ea4(A,P.toolName,S.value,P.toolCallId);else ja4(A,P.toolName,S.value,P.toolCallId);else A.push({functionResponse:{...P.toolCallId!=null?{id:P.toolCallId}:{},name:P.toolName,response:{name:P.toolName,content:S.type==="execution-denied"?(J=S.reason)!=null?J:"Tool execution denied.":S.value}}})}W.push({role:"user",parts:A});break}}if(F&&K.length>0&&W.length>0&&W[0].role==="user"){let j=K.map((z)=>z.text).join(`