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
@@ -976,7 +976,7 @@ Caused by: ${Z.stack}`}};Fn=class Fn extends FZ{constructor($,Z){super($,Z);this
976
976
  `).some((X)=>X.indexOf("(https.js:")!==-1||X.indexOf("node:https:")!==-1)}incrementSockets($){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[$])this.sockets[$]=[];let Z=new IJ4.Socket({writable:!1});return this.sockets[$].push(Z),this.totalSocketCount++,Z}decrementSockets($,Z){if(!this.sockets[$]||Z===null)return;let X=this.sockets[$],Q=X.indexOf(Z);if(Q!==-1){if(X.splice(Q,1),this.totalSocketCount--,X.length===0)delete this.sockets[$]}}getName($){if(this.isSecureEndpoint($))return qJ4.Agent.prototype.getName.call(this,$);return super.getName($)}createSocket($,Z,X){let Q={...Z,secureEndpoint:this.isSecureEndpoint(Z)},Y=this.getName(Q),G=this.incrementSockets(Y);Promise.resolve().then(()=>this.connect($,Q)).then((J)=>{if(this.decrementSockets(Y,G),J instanceof LQ$.Agent)try{return J.addRequest($,Q)}catch(K){return X(K)}this[kW].currentSocket=J,super.createSocket($,Z,X)},(J)=>{this.decrementSockets(Y,G),X(J)})}createConnection(){let $=this[kW].currentSocket;if(this[kW].currentSocket=void 0,!$)throw Error("No socket was returned in the `connect()` function");return $}get defaultPort(){return this[kW].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort($){if(this[kW])this[kW].defaultPort=$}get protocol(){return this[kW].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol($){if(this[kW])this[kW].protocol=$}}oY.Agent=jQ$});var PQ$=_((XJ)=>{var MJ4=XJ&&XJ.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),kJ4=XJ&&XJ.__setModuleDefault||(Object.create?function($,Z){Object.defineProperty($,"default",{enumerable:!0,value:Z})}:function($,Z){$.default=Z}),fp0=XJ&&XJ.__importStar||function($){if($&&$.__esModule)return $;var Z={};if($!=null){for(var X in $)if(X!=="default"&&Object.prototype.hasOwnProperty.call($,X))MJ4(Z,$,X)}return kJ4(Z,$),Z},VJ4=XJ&&XJ.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(XJ,"__esModule",{value:!0});XJ.SocksProxyAgent=void 0;var SJ4=UQ$(),CJ4=zQ$(),_J4=VJ4(j0("debug")),vJ4=fp0(j0("dns")),fJ4=fp0(j0("net")),bJ4=fp0(j0("tls")),xJ4=j0("url"),LO0=(0,_J4.default)("socks-proxy-agent"),yJ4=($)=>{if($.servername===void 0&&$.host&&!fJ4.isIP($.host))return{...$,servername:$.host};return $};function gJ4($){let Z=!1,X=5,Q=$.hostname,Y=parseInt($.port,10)||1080;switch($.protocol.replace(":","")){case"socks4":Z=!0,X=4;break;case"socks4a":X=4;break;case"socks5":Z=!0,X=5;break;case"socks":X=5;break;case"socks5h":X=5;break;default:throw TypeError(`A "socks" protocol must be specified! Got: ${String($.protocol)}`)}let G={host:Q,port:Y,type:X};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 bp0 extends CJ4.Agent{constructor($,Z){super(Z);let X=typeof $==="string"?new xJ4.URL($):$,{proxy:Q,lookup:Y}=gJ4(X);this.shouldLookup=Y,this.proxy=Q,this.timeout=Z?.timeout??null,this.socketOptions=Z?.socketOptions??null}async connect($,Z){let{shouldLookup:X,proxy:Q,timeout:Y}=this;if(!Z.host)throw Error("No `host` defined!");let{host:G}=Z,{port:J,lookup:K=vJ4.lookup}=Z;if(X)G=await new Promise((N,U)=>{K(G,{},(B,O)=>{if(B)U(B);else N(O)})});let W={proxy:Q,destination:{host:G,port:typeof J==="number"?J:parseInt(J,10)},command:"connect",timeout:Y??void 0,socket_options:this.socketOptions??void 0},F=(N)=>{if($.destroy(),H.destroy(),N)N.destroy()};LO0("Creating socks proxy connection: %o",W);let{socket:H}=await SJ4.SocksClient.createConnection(W);if(LO0("Successfully created socks proxy connection"),Y!==null)H.setTimeout(Y),H.on("timeout",()=>F());if(Z.secureEndpoint){LO0("Upgrading socket connection to TLS");let N=bJ4.connect({...hJ4(yJ4(Z),"host","path","port"),socket:H});return N.once("error",(U)=>{LO0("Socket TLS error",U.message),F(N)}),N}return H}}bp0.protocols=["socks","socks4","socks4a","socks5","socks5h"];XJ.SocksProxyAgent=bp0;function hJ4($,...Z){let X={},Q;for(Q in $)if(!Z.includes(Q))X[Q]=$[Q];return X}});var qQ$=_((Nz9,IQ$)=>{var xp0=j0("https"),yp0=j0("http"),{URL:AQ$}=j0("url");class TQ$ extends yp0.Agent{constructor($){let{proxy:Z,proxyRequestOptions:X,...Q}=$;super(Q);this.proxy=typeof Z==="string"?new AQ$(Z):Z,this.proxyRequestOptions=X||{}}createConnection($,Z){let X={...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");X.headers["proxy-authorization"]=`Basic ${Y}`}if(this.proxy.protocol==="https:")X.servername=this.proxy.hostname;let Q=(this.proxy.protocol==="http:"?yp0:xp0).request(X);Q.once("connect",(Y,G,J)=>{if(Q.removeAllListeners(),G.removeAllListeners(),Y.statusCode===200)Z(null,G);else G.destroy(),Z(Error(`Bad response: ${Y.statusCode}`),null)}),Q.once("timeout",()=>{Q.destroy(Error("Proxy timeout"))}),Q.once("error",(Y)=>{Q.removeAllListeners(),Z(Y,null)}),Q.end()}}class RQ$ extends xp0.Agent{constructor($){let{proxy:Z,proxyRequestOptions:X,...Q}=$;super(Q);this.proxy=typeof Z==="string"?new AQ$(Z):Z,this.proxyRequestOptions=X||{}}createConnection($,Z){let X={...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");X.headers["proxy-authorization"]=`Basic ${Y}`}if(this.proxy.protocol==="https:")X.servername=this.proxy.hostname;let Q=(this.proxy.protocol==="http:"?yp0:xp0).request(X);Q.once("connect",(Y,G,J)=>{if(Q.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)}),Q.once("timeout",()=>{Q.destroy(Error("Proxy timeout"))}),Q.once("error",(Y)=>{Q.removeAllListeners(),Z(Y,null)}),Q.end()}}IQ$.exports={HttpProxyAgent:TQ$,HttpsProxyAgent:RQ$}});var gp0,MQ$,kQ$;var VQ$=D(()=>{gp0=V(qQ$(),1),MQ$=gp0.default.HttpProxyAgent,kQ$=gp0.default.HttpsProxyAgent});import iH from"fs";import uJ4 from"https";import cJ4 from"http";import lJ4 from"net";import GC from"path";import{Headers as dJ4}from"node-fetch";import wO0 from"child_process";function hp0($){try{return iH.accessSync($),!0}catch{return!1}}class EO0{addAuthenticator($){this.custom_authenticators.push($)}constructor(){this.authenticators=[new hi0,new di0,new ci0,new li0,new Rn],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 lp0(this.contexts,$,"context")}getCurrentCluster(){let $=this.getCurrentContextObject();if(!$)return null;return this.getCluster($.cluster)}getCluster($){return lp0(this.clusters,$,"cluster")}getCurrentUser(){let $=this.getCurrentContextObject();if(!$)return null;return this.getUser($.user)}getUser($){return lp0(this.users,$,"user")}loadFromFile($,Z){let X=GC.dirname($);this.loadFromString(iH.readFileSync($).toString("utf-8"),Z),this.makePathsAbsolute(X)}async applyToFetchOptions($){await this.applyToHTTPSOptions($);let Z=new dJ4;for(let[X,Q]of Object.entries($.headers||{}))if(Array.isArray(Q))Q.forEach((Y)=>{Z.append(X,Y)});else if(typeof Q==="number"||typeof Q==="string")Z.set(X,Q.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(),X=this.getCurrentCluster();if(await this.applyOptions($),Z&&Z.username)$.auth=`${Z.username}:${Z.password}`;let Q={};if(Q.ca=$.ca,Q.cert=$.cert,Q.key=$.key,Q.pfx=$.pfx,Q.passphrase=$.passphrase,$.rejectUnauthorized!==void 0)Q.rejectUnauthorized=$.rejectUnauthorized;Q.timeout=$.timeout,Q.servername=$.servername,Q.ciphers=$.ciphers,Q.honorCipherOrder=$.honorCipherOrder,Q.ecdhCurve=$.ecdhCurve,Q.clientCertEngine=$.clientCertEngine,Q.crl=$.crl,Q.dhparam=$.dhparam,Q.secureOptions=$.secureOptions,Q.secureProtocol=$.secureProtocol,Q.sessionIdContext=$.sessionIdContext,$.agent=this.createAgent(X,Q)}async applySecurityAuthentication($){let Z=this.getCurrentCluster(),X=this.getCurrentUser(),Q={},Y={};if(await this.applyOptions(Y),Z&&Z.skipTLSVerify)Q.rejectUnauthorized=!1;if(Z&&Z.tlsServerName)Q.servername=Z.tlsServerName;if(X&&X.username){let J=Buffer.from(`${X.username}:${X.password}`).toString("base64");$.setHeaderParam("Authorization",`Basic ${J}`)}let G=Y.headers||{};if(Object.entries(G).forEach(([J,K])=>{$.setHeaderParam(J,`${K}`)}),Q.ca=Y.ca,Q.cert=Y.cert,Q.key=Y.key,Q.pfx=Y.pfx,Q.passphrase=Y.passphrase,Y.rejectUnauthorized!==void 0)Q.rejectUnauthorized=Y.rejectUnauthorized;$.setAgent(this.createAgent(Z,Q))}getName(){return"kubeconfig authentication"}loadFromString($,Z){let X=fi0.load($);this.clusters=XZ$(X.clusters,Z),this.contexts=JZ$(X.contexts,Z),this.users=YZ$(X.users,Z),this.currentContext=X["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,X=process.env.KUBERNETES_SERVICE_PORT,Q="inCluster",Y="inClusterUser",G="inClusterContext",J="https";if(X==="80"||X==="8080"||X==="8001")J="http";let K=Z;if(Z&&lJ4.isIPv6(Z))K=`[${Z}]`;this.clusters=[{name:"inCluster",caFile:`${$}${mJ4}`,server:`${J}://${K}:${X}`,skipTLSVerify:!1}],this.users=[{name:"inClusterUser",authProvider:{name:"tokenFile",config:{tokenFile:`${$}${SQ$}`}}}];let W=`${$}${iJ4}`,F;if(hp0(W))F=iH.readFileSync(W).toString("utf-8");this.contexts=[{cluster:"inCluster",name:"inClusterContext",user:"inClusterUser",namespace:F}],this.currentContext="inClusterContext"}mergeConfig($,Z=!1){if(!Z&&$.currentContext)this.currentContext=$.currentContext;$.clusters.forEach((X)=>{this.addCluster(X)}),$.users.forEach((X)=>{this.addUser(X)}),$.contexts.forEach((X)=>{this.addContext(X)})}addCluster($){if(!this.clusters)this.clusters=[];this.clusters.forEach((Z,X)=>{if(Z.name===$.name)throw Error(`Duplicate cluster: ${Z.name}`)}),this.clusters.push($)}addUser($){if(!this.users)this.users=[];this.users.forEach((Z,X)=>{if(Z.name===$.name)throw Error(`Duplicate user: ${Z.name}`)}),this.users.push($)}addContext($){if(!this.contexts)this.contexts=[];this.contexts.forEach((Z,X)=>{if(Z.name===$.name)throw Error(`Duplicate context: ${Z.name}`)}),this.contexts.push($)}loadFromDefault($,Z=!1,X=process.platform){if(process.env.KUBECONFIG&&process.env.KUBECONFIG.length>0){let Y=process.env.KUBECONFIG.split(GC.delimiter).filter((G)=>G);this.loadFromFile(Y[0],$);for(let G=1;G<Y.length;G++){let J=new EO0;J.loadFromFile(Y[G],$),this.mergeConfig(J,Z)}return}let Q=pJ4(X);if(Q){let Y=GC.join(Q,".kube","config");if(hp0(Y)){this.loadFromFile(Y,$);return}}if(X==="win32"){try{let Y=wO0.spawnSync("wsl.exe",["bash","-c","printenv KUBECONFIG"]);if(Y.status===0&&Y.stdout.length>0){let G=wO0.spawnSync("wsl.exe",["cat",Y.stdout.toString("utf8")]);if(G.status===0){this.loadFromString(G.stdout.toString("utf8"),$);return}}}catch{}try{let Y=wO0.spawnSync("wsl.exe",["cat","~/.kube/config"]);if(Y.status===0){this.loadFromString(Y.stdout.toString("utf8"),$);let G=wO0.spawnSync("wsl.exe",["wslpath","-w","~/.kube"]);if(G.status===0)this.makePathsAbsolute(G.stdout.toString("utf8"));return}}catch{}}if(hp0(SQ$)){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 X={default:this},Q=new cB0(Z.server,{}),Y=ri0({baseServer:Q,authMethods:X});return new $(Y)}makePathsAbsolute($){this.clusters.forEach((Z)=>{if(Z.caFile)Z.caFile=up0($,Z.caFile)}),this.users.forEach((Z)=>{if(Z.certFile)Z.certFile=up0($,Z.certFile);if(Z.keyFile)Z.keyFile=up0($,Z.keyFile)})}exportConfig(){let $={apiVersion:"v1",kind:"Config",clusters:this.clusters.map(QZ$),users:this.users.map(GZ$),contexts:this.contexts.map(KZ$),preferences:{},"current-context":this.getCurrentContext()};return JSON.stringify($)}getCurrentContextObject(){return this.getContextObject(this.currentContext)}createAgent($,Z){var X,Q;let Y;if($&&$.proxyUrl)if($.proxyUrl.startsWith("socks"))Y=new _Q$.SocksProxyAgent($.proxyUrl,Z);else if($.server.startsWith("https")){let G=Z;G.proxy=$.proxyUrl,Y=new kQ$(G)}else if($.server.startsWith("http")){let G=Z;G.proxy=$.proxyUrl,Y=new MQ$(G)}else throw Error("Unsupported proxy type");else if(((X=$===null||$===void 0?void 0:$.server)===null||X===void 0?void 0:X.startsWith("http:"))&&$.skipTLSVerify)Y=new cJ4.Agent(Z);else if(((Q=$===null||$===void 0?void 0:$.server)===null||Q===void 0?void 0:Q.startsWith("http:"))&&!$.skipTLSVerify)throw Error("HTTP protocol is not allowed when skipTLSVerify is not set or false");else Y=new uJ4.Agent(Z);return Y}applyHTTPSOptions($){var Z;let X=this.getCurrentCluster(),Q=this.getCurrentUser();if(!Q)return;if(X!=null&&X.skipTLSVerify)$.rejectUnauthorized=!1;if(X!=null&&X.tlsServerName)$.servername=X.tlsServerName;let Y=X!=null?cp0(X.caFile,X.caData):null;if(Y)$.ca=Y;let G=cp0(Q.certFile,Q.certData);if(G)$.cert=G;let J=cp0(Q.keyFile,Q.keyData);if(J)$.key=J;if(Q.impersonateUser!=null)(Z=$.headers)!==null&&Z!==void 0||($.headers={}),$.headers["Impersonate-User"]=Q.impersonateUser}async applyAuthorizationHeader($){let Z=this.getCurrentUser();if(!Z)return;let X=this.authenticators.find((Q)=>{return Q.isAuthProvider(Z)});if(!X)X=this.custom_authenticators.find((Q)=>{return Q.isAuthProvider(Z)});if(!$.headers)$.headers={};if(X)await X.applyAuthentication(Z,$);if(Z.token)$.headers.Authorization=`Bearer ${Z.token}`}async applyOptions($){this.applyHTTPSOptions($),await this.applyAuthorizationHeader($)}}function up0($,Z){if(!$||GC.isAbsolute(Z))return Z;return GC.join($,Z)}function cp0($,Z){if($)return iH.readFileSync($);if(Z)return Buffer.from(Z,"base64");return null}function CQ$($){return $.reduce((Z,X)=>{if(X&&!Z.includes(X))return Z.concat(X);else return Z},[])}function pJ4($=process.platform){if($!=="win32"){if(process.env.HOME)try{return iH.accessSync(process.env.HOME),process.env.HOME}catch{}return null}let Z=process.env.HOMEDRIVE&&process.env.HOMEPATH?GC.join(process.env.HOMEDRIVE,process.env.HOMEPATH):"",X=process.env.HOME||"",Q=process.env.USERPROFILE||"",Y=CQ$([X,Z,Q]),G=CQ$([X,Q,Z]);for(let J of Y)try{return iH.accessSync(GC.join(J,".kube","config")),J}catch{}for(let J of G)try{return iH.accessSync(J,iH.constants.W_OK),J}catch{}for(let J of G)try{return iH.accessSync(J),J}catch{}return G[0]||null}function lp0($,Z,X){if(!$)return null;for(let Q of $)if(Q.name===Z){if(Q[X])return Q[X].name=Z,Q[X];return Q}return null}var _Q$,dp0="/var/run/secrets/kubernetes.io/serviceaccount",mJ4,SQ$,iJ4;var vQ$=D(()=>{bi0();ZZ$();WZ$();FZ$();HZ$();NZ$();nB0();DX$();VQ$();_Q$=V(PQ$(),1),mJ4=dp0+"/ca.crt",SQ$=dp0+"/token",iJ4=dp0+"/namespace"});import{STATUS_CODES as nJ4}from"http";import{createInterface as tJ4}from"readline";import oJ4 from"node-fetch";class mp0{constructor($){this.config=$}async watch($,Z,X,Q){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 F=!1,H=(N)=>{if(!F)F=!0,K.abort(),Q(N)};try{let N=await oJ4(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",H),U.on("close",()=>H(null)),U.on("finish",()=>H(null));let B=tJ4(U);B.on("error",H),B.on("close",()=>H(null)),B.on("finish",()=>H(null)),B.on("line",(O)=>{try{let L=JSON.parse(O.toString());X(L.type,L.object,L)}catch{}})}else{let U=N.statusText||nJ4[N.status]||"Internal Server Error",B=Error(U);throw B.statusCode=N.status,B}}catch(N){H(N)}return K}}var ip0=D(()=>{mp0.SERVER_SIDE_CLOSE={error:"Connection closed on server"}});var pp0=D(()=>{np0();ip0()});class g3{serialize(){let $={};for(let Z of g3.attributeTypeMap)if(this[Z.baseName]!==void 0)$[Z.name]=P1.serialize(this[Z.baseName],Z.type,Z.format);for(let[Z,X]of Object.entries(this)){if(g3.attributeTypeMap.find((Q)=>Q.name===Z))continue;$[Z]=X}return $}static fromUnknown($){if(!jO0($))throw Error(`Unable to deseriliaze non-Kubernetes object ${$}.`);let Z=new g3;for(let X of g3.attributeTypeMap)if($[X.baseName]!==void 0)Z[X.name]=P1.deserialize($[X.baseName],X.type,X.format);for(let[X,Q]of Object.entries($)){if(g3.attributeTypeMap.find((Y)=>Y.name===X))continue;Z[X]=Q}return Z}}var jO0=($)=>!!$&&typeof $==="object"&&("apiVersion"in $)&&("kind"in $),fQ$=({group:$,version:Z})=>[$,Z].join("/"),rJ4=($)=>{let[Z,X]=$.apiVersion.split("/");return{kind:$.kind,group:X?Z:"",version:X?X:Z}},VO;var zO0=D(()=>{o1();g3.attributeTypeMap=[{name:"apiVersion",baseName:"apiVersion",type:"string",format:""},{name:"kind",baseName:"kind",type:"string",format:""},{name:"metadata",baseName:"metadata",type:"V1ObjectMeta",format:""}];VO=class VO extends P1{static registerModel($,Z){var X,Q;let Y=fQ$($),G=(X=(Q=this.modelRegistry)[Y])!==null&&X!==void 0?X:Q[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(!jO0($))return;let X=rJ4($);return(Z=VO.modelRegistry[fQ$(X)])===null||Z===void 0?void 0:Z[X.kind]}static serialize($,Z,X=""){let Q=VO.getSerializerForObject($);if(Q)return Q.serialize($,Z,X);if($ instanceof g3)return $.serialize();let Y=P1.serialize($,Z,X);if(Y!==$)return Y;if(!jO0($))return Y;let G={};for(let J of g3.attributeTypeMap)if($[J.baseName]!==void 0)G[J.name]=P1.serialize($[J.baseName],J.type,J.format);for(let[J,K]of Object.entries($)){if(g3.attributeTypeMap.find((W)=>W.name===J))continue;G[J]=K}return G}static deserialize($,Z,X=""){let Q=VO.getSerializerForObject($);if(Q)return Q.deserialize($,Z,X);let Y=P1.deserialize($,Z,X);if(Y!==$)return Y;if(!jO0($))return Y;return g3.fromUnknown($)}};VO.modelRegistry={}});var np0=D(()=>{pp0();zO0()});var PO0=D(()=>{nB0()});var tp0=()=>{};import bQ$ from"ws"with{type:"jsx"};class w5{static supportsClose($){return $==="v5.channel.k8s.io"}static closeStream($,Z){switch($){case w5.StdinStream:Z.stdin.pause();break;case w5.StdoutStream:Z.stdout.end();break;case w5.StderrStream:Z.stderr.end();break}}static handleStandardStreams($,Z,X,Q){if(Z.length<1)return null;if(X&&$===w5.StdoutStream)X.write(Z);else if(Q&&$===w5.StderrStream)Q.write(Z);else if($===w5.StatusStream){if(X&&X!==process.stdout)X.end();if(Q&&Q!==process.stderr)Q.end();return JSON.parse(Z.toString("utf8"))}else throw Error("Unknown stream: "+$);return null}static handleStandardInput($,Z,X=0){return Z.on("data",(Q)=>{$.send(yQ$(X,Q,Z.readableEncoding))}),Z.on("end",()=>{if(w5.supportsClose($.protocol)){let Q=Buffer.alloc(2);Q.writeUint8(this.CloseStream,0),Q.writeUint8(this.StdinStream,1),$.send(Q);return}$.close()}),!0}static async processData($,Z,X,Q=0,Y=3,G){let J=yQ$(Q,$,G),K=0;for(;K<Y;++K)if(Z!==null&&Z.readyState===bQ$.OPEN){Z.send(J);break}else Z=await X();if(K>=Y)throw Error("can't send data to ws");return Z}static restartableHandleStandardInput($,Z,X=0,Q=3,Y=!1){if(Q<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 w5.processData(K,J,$,X,Q,Z.readableEncoding)})}),Y)Z.on("flush",async()=>{await G});return Z.on("end",()=>{if(J!==null)J.close()}),()=>J}constructor($,Z,X={stdin:process.stdin,stdout:process.stdout,stderr:process.stderr}){this.config=$,this.socketFactory=Z,this.streams=X}async connect($,Z,X){let Q=this.config.getCurrentCluster();if(!Q)throw Error("No cluster is defined.");let Y=Q.server,G=Y.startsWith("https://"),J=G?Y.substr(8):Y.substr(7),W=`${G?"wss":"ws"}://${J}${$}`,F={};return await this.config.applyToHTTPSOptions(F),await new Promise((H,N)=>{let U=this.socketFactory?this.socketFactory(W,xQ$,F):new bQ$(W,xQ$,F),B=!1;U.onopen=()=>{B=!0,H(U)},U.onerror=(O)=>{if(!B)N(O)},U.onmessage=({data:O})=>{if(typeof O==="string"){if(O.charCodeAt(0)===w5.CloseStream)w5.closeStream(O.charCodeAt(1),this.streams);if(Z&&!Z(O))U.close()}else if(O instanceof Buffer){let L=O.readUint8(0);if(L===w5.CloseStream)w5.closeStream(O.readInt8(1),this.streams);if(X&&!X(L,O.slice(1)))U.close()}}})}}function yQ$($,Z,X){let Q;if(Z instanceof Buffer)Q=Buffer.alloc(Z.length+1),Z.copy(Q,1);else{X!==null&&X!==void 0||(X="utf-8");let Y=Buffer.byteLength(Z,X);Q=Buffer.alloc(Y+1),Q.write(Z,1,Y,X)}return Q.writeInt8($,0),Q}var xQ$;var AO0=D(()=>{xQ$=["v5.channel.k8s.io","v4.channel.k8s.io","v3.channel.k8s.io","v2.channel.k8s.io","channel.k8s.io"];w5.StdinStream=0;w5.StdoutStream=1;w5.StderrStream=2;w5.StatusStream=3;w5.ResizeStream=4;w5.CloseStream=255});var gQ$=D(()=>{tp0();AO0()});var op0=D(()=>{tp0();AO0()});import eJ4 from"querystring";class rp0{constructor($,Z,X){this.handler=X||new w5($),this.disconnectOnErr=Z===void 0?!0:Z}async portForward($,Z,X,Q,Y,G,J=0){if(X.length===0)throw Error("You must provide at least one port to forward to.");if(X.length>1)throw Error("Only one port is currently supported for port-forward");let K={ports:X[0]},W=eJ4.stringify(K),F=[];X.forEach((U,B)=>{F[B*2]=!0,F[B*2+1]=!0});let H=`/api/v1/namespaces/${$}/pods/${Z}/portforward?${W}`,N=()=>{return this.handler.connect(H,null,(U,B)=>{if(U>=X.length*2)return!this.disconnectOnErr;if(F[U])B=B.slice(2),F[U]=!1;if(U%2===1){if(Y)Y.write(B)}else Q.write(B);return!0})};if(J<1){let U=await N();return w5.handleStandardInput(U,G,0),U}return w5.restartableHandleStandardInput(N,G,0,J)}}var hQ$=D(()=>{AO0()});var uQ$=()=>{};var cQ$=D(()=>{bi0();zO0()});var lQ$=D(()=>{PO0()});var dQ$=()=>{};var TO0=_((MP9,mQ$)=>{mQ$.exports={DEFAULT_INITIAL_SIZE:8192,DEFAULT_INCREMENT_AMOUNT:8192,DEFAULT_FREQUENCY:1,DEFAULT_CHUNK_SIZE:1024}});var nQ$=_((kP9,pQ$)=>{var iQ$=j0("stream"),RO0=TO0(),X34=j0("util"),Q34=pQ$.exports=function($){var Z=this;$=$||{},iQ$.Readable.call(this,$),this.stopped=!1;var X=$.hasOwnProperty("frequency")?$.frequency:RO0.DEFAULT_FREQUENCY,Q=$.chunkSize||RO0.DEFAULT_CHUNK_SIZE,Y=$.initialSize||RO0.DEFAULT_INITIAL_SIZE,G=$.incrementAmount||RO0.DEFAULT_INCREMENT_AMOUNT,J=0,K=new Buffer(Y),W=!1,F=function(){var U=Math.min(Q,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)F.timeout=setTimeout(F,X);else F.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 H=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(!F.timeout&&W)F.timeout=setTimeout(F,X)};this.put=function(U,B){if(Z.stopped)throw Error("Tried to write data to a stopped ReadableStreamBuffer");if(Buffer.isBuffer(U))H(U.length),U.copy(K,J,0),J+=U.length;else{U=U+"";var O=Buffer.byteLength(U);H(O),K.write(U,J,B||"utf8"),J+=O}N()},this._read=function(){W=!0,N()}};X34.inherits(Q34,iQ$.Readable)});var aQ$=_((VP9,rQ$)=>{var Y34=j0("util"),oQ$=j0("stream"),tQ$=TO0(),G34=rQ$.exports=function($){$=$||{},$.decodeStrings=!0,oQ$.Writable.call(this,$);var Z=$.initialSize||tQ$.DEFAULT_INITIAL_SIZE,X=$.incrementAmount||tQ$.DEFAULT_INCREMENT_AMOUNT,Q=new Buffer(Z),Y=0;this.size=function(){return Y},this.maxSize=function(){return Q.length},this.getContents=function(J){if(!Y)return!1;var K=new Buffer(Math.min(J||Y,Y));if(Q.copy(K,0,0,K.length),K.length<Y)Q.copy(Q,0,K.length);return Y-=K.length,K},this.getContentsAsString=function(J,K){if(!Y)return!1;var W=Q.toString(J||"utf8",0,Math.min(K||Y,Y)),F=Buffer.byteLength(W);if(F<Y)Q.copy(Q,0,F);return Y-=F,W};var G=function(J){if(Q.length-Y<J){var K=Math.ceil((J-(Q.length-Y))/X),W=new Buffer(Q.length+X*K);Q.copy(W,0,0,Y),Q=W}};this._write=function(J,K,W){G(J.length),J.copy(Q,Y,0),Y+=J.length,W()}};Y34.inherits(G34,oQ$.Writable)});var sQ$=_((SP9,IO0)=>{IO0.exports=TO0();IO0.exports.ReadableStreamBuffer=nQ$();IO0.exports.WritableStreamBuffer=aQ$()});var $Y$=_((CP9,eQ$)=>{eQ$.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 ap0=_((_P9,XY$)=>{var ZY$=$Y$();XY$.exports=class{constructor(Z){this.hwm=Z||16,this.head=new ZY$(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 X=this.head;this.head=X.next=new ZY$(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 X=this.tail.next;return this.tail.next=null,this.tail=X,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 by=_((vP9,QY$)=>{function J34($){return Buffer.isBuffer($)||$ instanceof Uint8Array}function K34($){return Buffer.isEncoding($)}function W34($,Z,X){return Buffer.alloc($,Z,X)}function F34($){return Buffer.allocUnsafe($)}function H34($){return Buffer.allocUnsafeSlow($)}function N34($,Z){return Buffer.byteLength($,Z)}function U34($,Z){return Buffer.compare($,Z)}function B34($,Z){return Buffer.concat($,Z)}function O34($,Z,X,Q,Y){return C6($).copy(Z,X,Q,Y)}function D34($,Z){return C6($).equals(Z)}function L34($,Z,X,Q,Y){return C6($).fill(Z,X,Q,Y)}function w34($,Z,X){return Buffer.from($,Z,X)}function E34($,Z,X,Q){return C6($).includes(Z,X,Q)}function j34($,Z,X,Q){return C6($).indexOf(Z,X,Q)}function z34($,Z,X,Q){return C6($).lastIndexOf(Z,X,Q)}function P34($){return C6($).swap16()}function A34($){return C6($).swap32()}function T34($){return C6($).swap64()}function C6($){if(Buffer.isBuffer($))return $;return Buffer.from($.buffer,$.byteOffset,$.byteLength)}function R34($,Z,X,Q){return C6($).toString(Z,X,Q)}function I34($,Z,X,Q,Y){return C6($).write(Z,X,Q,Y)}function q34($,Z){return C6($).readDoubleBE(Z)}function M34($,Z){return C6($).readDoubleLE(Z)}function k34($,Z){return C6($).readFloatBE(Z)}function V34($,Z){return C6($).readFloatLE(Z)}function S34($,Z){return C6($).readInt32BE(Z)}function C34($,Z){return C6($).readInt32LE(Z)}function _34($,Z){return C6($).readUInt32BE(Z)}function v34($,Z){return C6($).readUInt32LE(Z)}function f34($,Z,X){return C6($).writeDoubleBE(Z,X)}function b34($,Z,X){return C6($).writeDoubleLE(Z,X)}function x34($,Z,X){return C6($).writeFloatBE(Z,X)}function y34($,Z,X){return C6($).writeFloatLE(Z,X)}function g34($,Z,X){return C6($).writeInt32BE(Z,X)}function h34($,Z,X){return C6($).writeInt32LE(Z,X)}function u34($,Z,X){return C6($).writeUInt32BE(Z,X)}function c34($,Z,X){return C6($).writeUInt32LE(Z,X)}QY$.exports={isBuffer:J34,isEncoding:K34,alloc:W34,allocUnsafe:F34,allocUnsafeSlow:H34,byteLength:N34,compare:U34,concat:B34,copy:O34,equals:D34,fill:L34,from:w34,includes:E34,indexOf:j34,lastIndexOf:z34,swap16:P34,swap32:A34,swap64:T34,toBuffer:C6,toString:R34,write:I34,readDoubleBE:q34,readDoubleLE:M34,readFloatBE:k34,readFloatLE:V34,readInt32BE:S34,readInt32LE:C34,readUInt32BE:_34,readUInt32LE:v34,writeDoubleBE:f34,writeDoubleLE:b34,writeFloatBE:x34,writeFloatLE:y34,writeInt32BE:g34,writeInt32LE:h34,writeUInt32BE:u34,writeUInt32LE:c34}});var GY$=_((fP9,YY$)=>{var l34=by();YY$.exports=class{constructor(Z){this.encoding=Z}get remaining(){return 0}decode(Z){return l34.toString(Z,this.encoding)}flush(){return""}}});var FY$=_((bP9,WY$)=>{var JY$=by();WY$.exports=class{constructor(){this._reset()}get remaining(){return this.bytesSeen}decode(Z){if(Z.byteLength===0)return"";if(this.bytesNeeded===0&&KY$(Z,0)===0)return this.bytesSeen=d34(Z),JY$.toString(Z,"utf8");let X="",Q=0;if(this.bytesNeeded>0){while(Q<Z.byteLength){let J=Z[Q];if(J<this.lowerBoundary||J>this.upperBoundary){X+="\uFFFD",this._reset();break}if(this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|J&63,this.bytesSeen++,Q++,this.bytesSeen===this.bytesNeeded){X+=String.fromCodePoint(this.codePoint),this._reset();break}}if(this.bytesNeeded>0)return X}let Y=KY$(Z,Q),G=Z.byteLength-Y;if(G>Q)X+=JY$.toString(Z,"utf8",Q,G);for(let J=G;J<Z.byteLength;J++){let K=Z[J];if(this.bytesNeeded===0){if(K<=127)this.bytesSeen=0,X+=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,X+="\uFFFD";continue}if(K<this.lowerBoundary||K>this.upperBoundary){X+="\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)X+=String.fromCodePoint(this.codePoint),this._reset()}return X}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 KY$($,Z){let X=$.byteLength;if(X<=Z)return 0;let Q=Math.max(Z,X-4),Y=X-1;while(Y>Q&&($[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=X-Y;return K<J?K:0}function d34($){let Z=$.byteLength;if(Z===0)return 0;let X=$[Z-1];if(X<=127)return 0;if((X&192)!==128)return 1;let Q=Math.max(0,Z-4),Y=Z-2;while(Y>=Q&&($[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 NY$=_((xP9,HY$)=>{var m34=GY$(),i34=FY$();HY$.exports=class{constructor(Z="utf8"){switch(this.encoding=p34(Z),this.encoding){case"utf8":this.decoder=new i34;break;case"utf16le":case"base64":throw Error("Unsupported encoding: "+this.encoding);default:this.decoder=new m34(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 X="";if(Z)X=this.push(Z);return X+=this.decoder.flush(),X}};function p34($){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 Qn0=_((yP9,TY$)=>{var{EventEmitter:n34}=j0("events"),MO0=Error("Stream was destroyed"),sp0=Error("Premature close"),BY$=ap0(),t34=NY$(),ep0=typeof queueMicrotask>"u"?($)=>global.process.nextTick($):queueMicrotask,qO0=Symbol.asyncIterator||Symbol("asyncIterator");class $n0{constructor($,{highWaterMark:Z=16384,map:X=null,mapWritable:Q,byteLength:Y,byteLengthWritable:G}={}){this.stream=$,this.queue=new BY$,this.highWaterMark=Z,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=G||Y||AY$,this.map=Q||X,this.afterWrite=a34.bind(this),this.afterUpdateNextTick=$K4.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 X=[],Q=this.stream;X.push($);while((Q._duplexState&270794767)===2359296)X.push(Q._writableState.shift());if((Q._duplexState&15)!==0)return Z(null);Q._writev(X,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(r34.bind(this));return}if(($._duplexState&14)===4){if(($._duplexState&33587200)===0)$._duplexState|=262160,$._destroy(wY$.bind(this));return}if(($._duplexState&33587215)===1)$._duplexState=($._duplexState|262160)&536870910,$._open(EY$.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)ep0(this.afterUpdateNextTick)}}class OY${constructor($,{highWaterMark:Z=16384,map:X=null,mapReadable:Q,byteLength:Y,byteLengthReadable:G}={}){this.stream=$,this.queue=new BY$,this.highWaterMark=Z===0?1:Z,this.buffered=0,this.readAhead=Z>0,this.error=null,this.pipeline=null,this.byteLength=G||Y||AY$,this.map=Q||X,this.pipeTo=null,this.afterRead=s34.bind(this),this.afterUpdateNextTick=e34.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 LY$(this.stream,$,Z),Z)this.stream.on("error",UY$);if(Mn($)){if($._writableState.pipeline=this.pipeline,Z)$.on("error",UY$);$.on("finish",this.pipeline.finished.bind(this.pipeline))}else{let X=this.pipeline.done.bind(this.pipeline,$),Q=this.pipeline.done.bind(this.pipeline,$,null);$.on("error",X),$.on("close",Q),$.on("finish",this.pipeline.finished.bind(this.pipeline))}$.on("drain",o34.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 X=0;X<Z.length-1;X++){let Q=Z[X];this.buffered+=this.byteLength(Q),this.queue.push(Q)}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(wY$.bind(this));return}if(($._duplexState&33587215)===1)$._duplexState=($._duplexState|262160)&536870910,$._open(EY$.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)ep0(this.afterUpdateNextTick)}updateNextTick(){if((this.stream._duplexState&32768)!==0)return;if(this.stream._duplexState|=32768,(this.stream._duplexState&32)===0)ep0(this.afterUpdateNextTick)}}class DY${constructor($){this.data=null,this.afterTransform=XK4.bind($),this.afterFinal=null}}class LY${constructor($,Z,X){this.from=$,this.to=Z,this.afterPipe=X,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 o34(){this.stream._duplexState|=512,this.updateCallback()}function r34($){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 wY$($){let Z=this.stream;if(!$&&this.error!==MO0)$=this.error;if($)Z.emit("error",$);Z._duplexState|=8,Z.emit("close");let{_readableState:X,_writableState:Q}=Z;if(X!==null&&X.pipeline!==null)X.pipeline.done(Z,$);if(Q!==null){while(Q.drains!==null&&Q.drains.length>0)Q.drains.shift().resolve(!1);if(Q.pipeline!==null)Q.pipeline.done(Z,$)}}function a34($){let Z=this.stream;if($)Z.destroy($);if(Z._duplexState&=469499903,this.drains!==null)ZK4(this.drains);if((Z._duplexState&6553615)===4194304){if(Z._duplexState&=532676607,(Z._duplexState&16777216)===16777216)Z.emit("drain")}this.updateCallback()}function s34($){if($)this.stream.destroy($);if(this.stream._duplexState&=536870895,this.readAhead===!1&&(this.stream._duplexState&256)===0)this.stream._duplexState&=536739839;this.updateCallback()}function e34(){if((this.stream._duplexState&32)===0)this.stream._duplexState&=536838143,this.update()}function $K4(){if((this.stream._duplexState&524288)===0)this.stream._duplexState&=503316479,this.update()}function ZK4($){for(let Z=0;Z<$.length;Z++)if(--$[Z].writes===0)$.shift().resolve(!0),Z--}function EY$($){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 XK4($,Z){if(Z!==void 0&&Z!==null)this.push(Z);this._writableState.afterWrite($)}function QK4($){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 kO0 extends n34{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",DK4.bind(this))}this.on("newListener",QK4)}_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(!$)$=MO0;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 qn extends kO0{constructor($){super($);if(this._duplexState|=8519681,this._readableState=new OY$(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 t34($),X=this._readableState.map||JK4;return this._readableState.map=Q,this;function Q(Y){let G=Z.push(Y);return G===""&&(Y.byteLength!==0||Z.remaining>0)?null:X(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 X,Q=new qn({...Z,read(G){$.next().then(Y).then(G.bind(null,null)).catch(G)},predestroy(){X=$.return()},destroy(G){if(!X)return G(null);X.then(G.bind(null,null)).catch(G)}});return Q;function Y(G){if(G.done)Q.push(null);else Q.push(G.value)}}static from($,Z){if(UK4($))return $;if($[qO0])return this._fromAsyncIterator($[qO0](),Z);if(!Array.isArray($))$=$===void 0?[]:[$];let X=0;return new qn({...Z,read(Q){this.push(X===$.length?null:$[X++]),Q(null)}})}static isBackpressured($){return($._duplexState&17422)!==0||$._readableState.buffered>=$._readableState.highWaterMark}static isPaused($){return($._duplexState&256)===0}[qO0](){let $=this,Z=null,X=null,Q=null;return this.on("error",(W)=>{Z=W}),this.on("readable",Y),this.on("close",G),{[qO0](){return this},next(){return new Promise(function(W,F){X=W,Q=F;let H=$.read();if(H!==null)J(H);else if(($._duplexState&8)!==0)J(null)})},return(){return K(null)},throw(W){return K(W)}};function Y(){if(X!==null)J($.read())}function G(){if(X!==null)J(null)}function J(W){if(Q===null)return;if(Z)Q(Z);else if(W===null&&($._duplexState&16384)===0)Q(MO0);else X({value:W,done:W===null});Q=X=null}function K(W){return $.destroy(W),new Promise((F,H)=>{if($._duplexState&8)return F({value:void 0,done:!0});$.once("close",function(){if(W)H(W);else F({value:void 0,done:!0})})})}}}class Zn0 extends kO0{constructor($){super($);if(this._duplexState|=16385,this._writableState=new $n0(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,Q=(LK4($)?Math.min(1,Z.queue.length):Z.queue.length)+($._duplexState&67108864?1:0);if(Q===0)return Promise.resolve(!0);if(Z.drains===null)Z.drains=[];return new Promise((Y)=>{Z.drains.push({writes:Q,resolve:Y})})}write($){return this._writableState.updateNextTick(),this._writableState.push($)}end($){return this._writableState.updateNextTick(),this._writableState.end($),this}}class VO0 extends qn{constructor($){super($);if(this._duplexState=1|this._duplexState&131072,this._writableState=new $n0(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 Xn0 extends VO0{constructor($){super($);if(this._transformState=new DY$(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(YK4.bind(this))}}class jY$ extends Xn0{}function YK4($,Z){let X=this._transformState.afterFinal;if($)return X($);if(Z!==null&&Z!==void 0)this.push(Z);this.push(null),X(null)}function GK4(...$){return new Promise((Z,X)=>{return zY$(...$,(Q)=>{if(Q)return X(Q);Z()})})}function zY$($,...Z){let X=Array.isArray($)?[...$,...Z]:[$,...Z],Q=X.length&&typeof X[X.length-1]==="function"?X.pop():null;if(X.length<2)throw Error("Pipeline requires at least 2 streams");let Y=X[0],G=null,J=null;for(let F=1;F<X.length;F++){if(G=X[F],Mn(Y))Y.pipe(G,W);else K(Y,!0,F>1,W),Y.pipe(G);Y=G}if(Q){let F=!1,H=Mn(G)||!!(G._writableState&&G._writableState.autoDestroy);if(G.on("error",(N)=>{if(J===null)J=N}),G.on("finish",()=>{if(F=!0,!H)Q(J)}),H)G.on("close",()=>Q(J||(F?null:sp0)))}return G;function K(F,H,N,U){F.on("error",U),F.on("close",B);function B(){if(H&&F._readableState&&!F._readableState.ended)return U(sp0);if(N&&F._writableState&&!F._writableState.ended)return U(sp0)}}function W(F){if(!F||J)return;J=F;for(let H of X)H.destroy(F)}}function JK4($){return $}function PY$($){return!!$._readableState||!!$._writableState}function Mn($){return typeof $._duplexState==="number"&&PY$($)}function KK4($){return!!$._readableState&&$._readableState.ending}function WK4($){return!!$._readableState&&$._readableState.ended}function FK4($){return!!$._writableState&&$._writableState.ending}function HK4($){return!!$._writableState&&$._writableState.ended}function NK4($,Z={}){let X=$._readableState&&$._readableState.error||$._writableState&&$._writableState.error;return!Z.all&&X===MO0?null:X}function UK4($){return Mn($)&&$.readable}function BK4($){return($._duplexState&1)!==1||($._duplexState&4)===4||($._duplexState&33587200)!==0}function OK4($){return typeof $==="object"&&$!==null&&typeof $.byteLength==="number"}function AY$($){return OK4($)?$.byteLength:1024}function UY$(){}function DK4(){this.destroy(Error("Stream aborted."))}function LK4($){return $._writev!==Zn0.prototype._writev&&$._writev!==VO0.prototype._writev}TY$.exports={pipeline:zY$,pipelinePromise:GK4,isStream:PY$,isStreamx:Mn,isEnding:KK4,isEnded:WK4,isFinishing:FK4,isFinished:HK4,isDisturbed:BK4,getStreamError:NK4,Stream:kO0,Writable:Zn0,Readable:qn,Duplex:VO0,Transform:Xn0,PassThrough:jY$}});var Gn0=_((kK4)=>{var y4=by(),RY$=y4.from([117,115,116,97,114,0]),wK4=y4.from([48,48]),EK4=y4.from([117,115,116,97,114,32]),jK4=y4.from([32,0]);kK4.decodeLongPath=function(Z,X){return xy(Z,0,Z.length,X)};kK4.encodePax=function(Z){let X="";if(Z.name)X+=Yn0(" path="+Z.name+`
977
977
  `);if(Z.linkname)X+=Yn0(" linkpath="+Z.linkname+`
978
978
  `);let Q=Z.pax;if(Q)for(let Y in Q)X+=Yn0(" "+Y+"="+Q[Y]+`
979
- `);return y4.from(X)};kK4.decodePax=function(Z){let X={};while(Z.length){let Q=0;while(Q<Z.length&&Z[Q]!==32)Q++;let Y=parseInt(y4.toString(Z.subarray(0,Q)),10);if(!Y)return X;let G=y4.toString(Z.subarray(Q+1,Y-1)),J=G.indexOf("=");if(J===-1)return X;X[G.slice(0,J)]=G.slice(J+1),Z=Z.subarray(Y)}return X};kK4.encode=function(Z){let X=y4.alloc(512),Q=Z.name,Y="";if(Z.typeflag===5&&Q[Q.length-1]!=="/")Q+="/";if(y4.byteLength(Q)!==Q.length)return null;while(y4.byteLength(Q)>100){let G=Q.indexOf("/");if(G===-1)return null;Y+=Y?"/"+Q.slice(0,G):Q.slice(0,G),Q=Q.slice(G+1)}if(y4.byteLength(Q)>100||y4.byteLength(Y)>155)return null;if(Z.linkname&&y4.byteLength(Z.linkname)>100)return null;if(y4.write(X,Q),y4.write(X,CO(Z.mode&4095,6),100),y4.write(X,CO(Z.uid,6),108),y4.write(X,CO(Z.gid,6),116),qK4(Z.size,X,124),y4.write(X,CO(Z.mtime.getTime()/1000|0,11),136),X[156]=48+RK4(Z.type),Z.linkname)y4.write(X,Z.linkname,157);if(y4.copy(RY$,X,257),y4.copy(wK4,X,263),Z.uname)y4.write(X,Z.uname,265);if(Z.gname)y4.write(X,Z.gname,297);if(y4.write(X,CO(Z.devmajor||0,6),329),y4.write(X,CO(Z.devminor||0,6),337),Y)y4.write(X,Y,345);return y4.write(X,CO(qY$(X),6),148),X};kK4.decode=function(Z,X,Q){let Y=Z[156]===0?0:Z[156]-48,G=xy(Z,0,100,X),J=SO(Z,100,8),K=SO(Z,108,8),W=SO(Z,116,8),F=SO(Z,124,12),H=SO(Z,136,12),N=TK4(Y),U=Z[157]===0?null:xy(Z,157,100,X),B=xy(Z,265,32),O=xy(Z,297,32),L=SO(Z,329,8),w=SO(Z,337,8),E=qY$(Z);if(E===256)return null;if(E!==SO(Z,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(zK4(Z)){if(Z[345])G=xy(Z,345,155,X)+"/"+G}else if(PK4(Z));else if(!Q)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:F,mtime:new Date(1000*H),type:N,linkname:U,uname:B,gname:O,devmajor:L,devminor:w,pax:null}};function zK4($){return y4.equals(RY$,$.subarray(257,263))}function PK4($){return y4.equals(EK4,$.subarray(257,263))&&y4.equals(jK4,$.subarray(263,265))}function AK4($,Z,X){if(typeof $!=="number")return X;if($=~~$,$>=Z)return Z;if($>=0)return $;if($+=Z,$>=0)return $;return 0}function TK4($){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 RK4($){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 IY$($,Z,X,Q){for(;X<Q;X++)if($[X]===Z)return X;return Q}function qY$($){let Z=256;for(let X=0;X<148;X++)Z+=$[X];for(let X=156;X<512;X++)Z+=$[X];return Z}function CO($,Z){if($=$.toString(8),$.length>Z)return"7777777777777777777".slice(0,Z)+" ";return"0000000000000000000".slice(0,Z-$.length)+$+" "}function IK4($,Z,X){Z[X]=128;for(let Q=11;Q>0;Q--)Z[X+Q]=$&255,$=Math.floor($/256)}function qK4($,Z,X){if($.toString(8).length>11)IK4($,Z,X);else y4.write(Z,CO($,11),X)}function MK4($){let Z;if($[0]===128)Z=!0;else if($[0]===255)Z=!1;else return null;let X=[],Q;for(Q=$.length-1;Q>0;Q--){let J=$[Q];if(Z)X.push(J);else X.push(255-J)}let Y=0,G=X.length;for(Q=0;Q<G;Q++)Y+=X[Q]*Math.pow(256,Q);return Z?Y:-1*Y}function SO($,Z,X){if($=$.subarray(Z,Z+X),Z=0,$[Z]&128)return MK4($);else{while(Z<$.length&&$[Z]===32)Z++;let Q=AK4(IY$($,32,Z,$.length),$.length,$.length);while(Z<Q&&$[Z]===0)Z++;if(Q===Z)return 0;return parseInt(y4.toString($.subarray(Z,Q)),8)}}function xy($,Z,X,Q){return y4.toString($.subarray(Z,IY$($,0,Z,Z+X)),Q)}function Yn0($){let Z=y4.byteLength($),X=Math.floor(Math.log(Z)/Math.log(10))+1;if(Z+X>=Math.pow(10,X))X++;return Z+X+$}});var fY$=_((hP9,vY$)=>{var{Writable:fK4,Readable:bK4,getStreamError:MY$}=Qn0(),xK4=ap0(),kY$=by(),yy=Gn0(),yK4=kY$.alloc(0);class VY${constructor(){this.buffered=0,this.shifted=0,this.queue=new xK4,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 yK4;let Z=this._next($);if($===Z.byteLength)return Z;let X=[Z];while(($-=Z.byteLength)>0)Z=this._next($),X.push(Z);return kY$.concat(X)}_next($){let Z=this.queue.peek(),X=Z.byteLength-this._offset;if($>=X){let Q=this._offset?Z.subarray(this._offset,Z.byteLength):Z;return this.queue.shift(),this._offset=0,this.buffered-=X,this.shifted+=X,Q}return this.buffered-=$,this.shifted+=$,Z.subarray(this._offset,this._offset+=$)}}class SY$ extends bK4{constructor($,Z,X){super();this.header=Z,this.offset=X,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(MY$(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=_Y$(this.header.size),this._parent._update()}_destroy($){this._detach(),$(null)}}class CY$ extends fK4{constructor($){super($);if(!$)$={};this._buffer=new VY$,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=Jn0,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=yy.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=yy.decodeLongPath($,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=yy.decodeLongPath($,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=yy.decodePax($);break;case"pax-header":this._pax=this._paxGlobal===null?yy.decodePax($):Object.assign({},this._paxGlobal,yy.decodePax($));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=_Y$(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 SY$(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=Jn0,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(MY$(this));$(null)}[Symbol.asyncIterator](){let $=null,Z=null,X=null,Q=null,Y=null,G=this;return this.on("entry",W),this.on("error",(N)=>{$=N}),this.on("close",F),{[Symbol.asyncIterator](){return this},next(){return new Promise(K)},return(){return H(null)},throw(N){return H(N)}};function J(N){if(!Y)return;let U=Y;Y=null,U(N)}function K(N,U){if($)return U($);if(Q){N({value:Q,done:!1}),Q=null;return}if(Z=N,X=U,J(null),G._finished&&Z)Z({value:void 0,done:!0}),Z=X=null}function W(N,U,B){if(Y=B,U.on("error",Jn0),Z)Z({value:U,done:!1}),Z=X=null;else Q=U}function F(){if(J($),!Z)return;if($)X($);else Z({value:void 0,done:!0});Z=X=null}function H(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})})})}}}vY$.exports=function(Z){return new CY$(Z)};function Jn0(){}function _Y$($){return $&=511,$&&512-$}});var xY$=_((uP9,Kn0)=>{var bY$={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{Kn0.exports=j0("fs").constants||bY$}catch{Kn0.exports=bY$}});var dY$=_((cP9,lY$)=>{var{Readable:gK4,Writable:hK4,getStreamError:yY$}=Qn0(),JC=by(),gy=xY$(),SO0=Gn0(),gY$=JC.alloc(1024);class hY$ extends hK4{constructor($,Z,X){super({mapWritable:cK4,eagerOpen:!0});if(this.written=0,this.header=Z,this._callback=X,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?JC.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?JC.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);cY$(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 yY$(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy($){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),$()}}class uY$ extends gK4{constructor($){super($);this._drain=Wn0,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry($,Z,X){if(this._finalized||this.destroying)throw Error("already finalized or destroyed");if(typeof Z==="function")X=Z,Z=null;if(!X)X=Wn0;if(!$.size||$.type==="symlink")$.size=0;if(!$.type)$.type=uK4($.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=JC.from(Z);let Q=new hY$(this,$,X);if(JC.isBuffer(Z))return $.size=Z.byteLength,Q.write(Z),Q.end(),Q;if(Q._isVoid)return Q;return Q}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}if(this._finalized)return;this._finalized=!0,this.push(gY$),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=SO0.encode($);if(Z){this.push(Z);return}}this._encodePax($)}_encodePax($){let Z=SO0.encodePax({name:$.name,linkname:$.linkname,pax:$.pax}),X={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(SO0.encode(X)),this.push(Z),cY$(this,Z.byteLength),X.size=$.size,X.type=$.type,this.push(SO0.encode(X))}_doDrain(){let $=this._drain;this._drain=Wn0,$()}_predestroy(){let $=yY$(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(),$()}}lY$.exports=function(Z){return new uY$(Z)};function uK4($){switch($&gy.S_IFMT){case gy.S_IFBLK:return"block-device";case gy.S_IFCHR:return"character-device";case gy.S_IFDIR:return"directory";case gy.S_IFIFO:return"fifo";case gy.S_IFLNK:return"symlink"}return"file"}function Wn0(){}function cY$($,Z){if(Z&=511,Z)$.push(gY$.subarray(0,512-Z))}function cK4($){return JC.isBuffer($)?$:JC.from($)}});var mY$=_((lK4)=>{lK4.extract=fY$();lK4.pack=dY$()});var nY$=_((dP9,pY$)=>{pY$.exports=iY$;function iY$($,Z){if($&&Z)return iY$($)(Z);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(Q){X[Q]=$[Q]}),X;function X(){var Q=Array(arguments.length);for(var Y=0;Y<Q.length;Y++)Q[Y]=arguments[Y];var G=$.apply(this,Q),J=Q[Q.length-1];if(typeof G==="function"&&G!==J)Object.keys(J).forEach(function(K){G[K]=J[K]});return G}}});var Hn0=_((mP9,Fn0)=>{var tY$=nY$();Fn0.exports=tY$(CO0);Fn0.exports.strict=tY$(oY$);CO0.proto=CO0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return CO0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return oY$(this)},configurable:!0})});function CO0($){var Z=function(){if(Z.called)return Z.value;return Z.called=!0,Z.value=$.apply(this,arguments)};return Z.called=!1,Z}function oY$($){var Z=function(){if(Z.called)throw Error(Z.onceError);return Z.called=!0,Z.value=$.apply(this,arguments)},X=$.name||"Function wrapped with `once`";return Z.onceError=X+" shouldn't be called more than once",Z.called=!1,Z}});var sY$=_((iP9,aY$)=>{var iK4=Hn0(),pK4=function(){},nK4=global.Bare?queueMicrotask:process.nextTick.bind(process),tK4=function($){return $.setHeader&&typeof $.abort==="function"},oK4=function($){return $.stdio&&Array.isArray($.stdio)&&$.stdio.length===3},rY$=function($,Z,X){if(typeof Z==="function")return rY$($,null,Z);if(!Z)Z={};X=iK4(X||pK4);var{_writableState:Q,_readableState:Y}=$,G=Z.readable||Z.readable!==!1&&$.readable,J=Z.writable||Z.writable!==!1&&$.writable,K=!1,W=function(){if(!$.writable)F()},F=function(){if(J=!1,!G)X.call($)},H=function(){if(G=!1,!J)X.call($)},N=function(w){X.call($,w?Error("exited with error code: "+w):null)},U=function(w){X.call($,w)},B=function(){nK4(O)},O=function(){if(K)return;if(G&&!(Y&&(Y.ended&&!Y.destroyed)))return X.call($,Error("premature close"));if(J&&!(Q&&(Q.ended&&!Q.destroyed)))return X.call($,Error("premature close"))},L=function(){$.req.on("finish",F)};if(tK4($))if($.on("complete",F),$.on("abort",B),$.req)L();else $.on("request",L);else if(J&&!Q)$.on("end",W),$.on("close",W);if(oK4($))$.on("exit",N);if($.on("end",H),$.on("finish",F),Z.error!==!1)$.on("error",U);return $.on("close",B),function(){if(K=!0,$.removeListener("complete",F),$.removeListener("abort",B),$.removeListener("request",L),$.req)$.req.removeListener("finish",F);$.removeListener("end",W),$.removeListener("close",W),$.removeListener("finish",F),$.removeListener("exit",N),$.removeListener("end",H),$.removeListener("error",U),$.removeListener("close",B)}};aY$.exports=rY$});var ZG$=_((pP9,$G$)=>{var rK4=Hn0(),aK4=sY$(),_O0;try{_O0=j0("fs")}catch($){}var kn=function(){},sK4=typeof process>"u"?!1:/^v?\.0/.test(process.version),vO0=function($){return typeof $==="function"},eK4=function($){if(!sK4)return!1;if(!_O0)return!1;return($ instanceof(_O0.ReadStream||kn)||$ instanceof(_O0.WriteStream||kn))&&vO0($.close)},$W4=function($){return $.setHeader&&vO0($.abort)},ZW4=function($,Z,X,Q){Q=rK4(Q);var Y=!1;$.on("close",function(){Y=!0}),aK4($,{readable:Z,writable:X},function(J){if(J)return Q(J);Y=!0,Q()});var G=!1;return function(J){if(Y)return;if(G)return;if(G=!0,eK4($))return $.close(kn);if($W4($))return $.abort();if(vO0($.destroy))return $.destroy();Q(J||Error("stream was destroyed"))}},eY$=function($){$()},XW4=function($,Z){return $.pipe(Z)},QW4=function(){var $=Array.prototype.slice.call(arguments),Z=vO0($[$.length-1]||kn)&&$.pop()||kn;if(Array.isArray($[0]))$=$[0];if($.length<2)throw Error("pump requires two streams per minimum");var X,Q=$.map(function(Y,G){var J=G<$.length-1,K=G>0;return ZW4(Y,J,K,function(W){if(!X)X=W;if(W)Q.forEach(eY$);if(J)return;Q.forEach(eY$),Z(X)})});return $.reduce(XW4)};$G$.exports=QW4});var HG$=_((KW4)=>{var XG$=mY$(),QG$=ZG$(),YG$=j0("fs"),K9=j0("path"),Vn=(global.Bare?global.Bare.platform:process.platform)==="win32";KW4.pack=function(Z,X){if(!Z)Z=".";if(!X)X={};let Q=X.fs||YG$,Y=X.ignore||X.filter||Sn,G=X.mapStream||WG$,J=JW4(Q,X.dereference?Q.stat:Q.lstat,Z,Y,X.entries,X.sort),K=X.strict!==!1,W=typeof X.umask==="number"?~X.umask:~GG$(),F=X.pack||XG$.pack(),H=X.finish||Sn,N=X.map||Sn,U=typeof X.dmode==="number"?X.dmode:0,B=typeof X.fmode==="number"?X.fmode:0;if(X.strip)N=FG$(N,X.strip);if(X.readable)U|=parseInt(555,8),B|=parseInt(444,8);if(X.writable)U|=parseInt(333,8),B|=parseInt(222,8);w();function O(E,j){Q.readlink(K9.join(Z,E),function(z,A){if(z)return F.destroy(z);j.linkname=Nn0(A),F.entry(j,w)})}function L(E,j,z){if(F.destroyed)return;if(E)return F.destroy(E);if(!j){if(X.finalize!==!1)F.finalize();return H(F)}if(z.isSocket())return w();let A={name:Nn0(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,F.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 F.destroy(Error("unsupported type for "+j));return w()}let P=F.entry(A,w),I=G(Q.createReadStream(K9.join(Z,j),{start:0,end:A.size>0?A.size-1:A.size}),A);I.on("error",function(q){P.destroy(q)}),QG$(I,P)}function w(E){if(E)return F.destroy(E);J(L)}return F};function YW4($){return $.length?$[$.length-1]:null}function GW4(){return!global.Bare&&process.getuid?process.getuid():-1}function GG$(){return!global.Bare&&process.umask?process.umask():0}KW4.extract=function(Z,X){if(!Z)Z=".";if(!X)X={};Z=K9.resolve(Z);let Q=X.fs||YG$,Y=X.ignore||X.filter||Sn,G=X.mapStream||WG$,J=X.chown!==!1&&!Vn&&GW4()===0,K=X.extract||XG$.extract(),W=[],F=new Date,H=typeof X.umask==="number"?~X.umask:~GG$(),N=X.strict!==!1,U=X.validateSymlinks!==!1,B=X.map||Sn,O=typeof X.dmode==="number"?X.dmode:0,L=typeof X.fmode==="number"?X.fmode:0;if(X.strip)B=FG$(B,X.strip);if(X.readable)O|=parseInt(555,8),L|=parseInt(444,8);if(X.writable)O|=parseInt(333,8),L|=parseInt(222,8);if(K.on("entry",w),X.finish)K.on("finish",X.finish);return K;function w(P,I,q){P=B(P)||P,P.name=Nn0(P.name);let k=K9.join(Z,K9.join("/",P.name));if(Y(k,P))return I.resume(),q();let S=K9.join(k,".")===K9.join(Z,".")?Z:K9.dirname(k);KG$(Q,S,K9.join(Z,"."),function(o,U0){if(o)return q(o);if(!U0)return q(Error(S+" is not a valid path"));if(P.type==="directory")return W.push([k,P.mtime]),A(k,{fs:Q,own:J,uid:P.uid,gid:P.gid,mode:P.mode},m);A(S,{fs:Q,own:J,uid:P.uid,gid:P.gid,mode:493},function(E0){if(E0)return q(E0);switch(P.type){case"file":return u();case"link":return b();case"symlink":return f()}if(N)return q(Error("unsupported type for "+k+" ("+P.type+")"));I.resume(),q()})});function m(o){if(o)return q(o);j(k,P,function(U0){if(U0)return q(U0);if(Vn)return q();z(k,P,q)})}function f(){if(Vn)return q();Q.unlink(k,function(){let o=K9.resolve(K9.dirname(k),P.linkname);if(!i(o)&&U)return q(Error(k+" is not a valid symlink"));JG$(Q,o,K9.join(Z,"."),function(U0,E0){if(U0)return q(U0);if(!E0&&U)return q(Error(k+" is not a valid symlink"));Q.symlink(P.linkname,k,m)})})}function b(){if(Vn)return q();Q.unlink(k,function(){let o=K9.join(Z,K9.join("/",P.linkname));Q.realpath(o,function(U0,E0){if(U0||!i(E0))return q(Error(k+" is not a valid hardlink"));Q.link(E0,k,function(s){if(s&&s.code==="EPERM"&&X.hardlinkAsFilesFallback)return I=Q.createReadStream(E0),u();m(s)})})})}function i(o){return o===Z||o.startsWith(Z+K9.sep)}function u(){let o=Q.createWriteStream(k),U0=G(I,P);o.on("error",function(E0){U0.destroy(E0)}),QG$(U0,o,function(E0){if(E0)return q(E0);o.on("close",m)})}}function E(P,I){let q;while((q=YW4(W))&&P.slice(0,q[0].length)!==q[0])W.pop();if(!q)return I();Q.utimes(q[0],F,q[1],I)}function j(P,I,q){if(X.utimes===!1)return q();if(I.type==="directory")return Q.utimes(P,F,I.mtime,q);if(I.type==="symlink")return E(P,q);Q.utimes(P,F,I.mtime,function(k){if(k)return q(k);E(P,q)})}function z(P,I,q){let k=I.type==="symlink",S=k?Q.lchmod:Q.chmod,m=k?Q.lchown:Q.chown;if(!S)return q();let f=(I.mode|(I.type==="directory"?O:L))&H;if(m&&J)m.call(Q,P,I.uid,I.gid,b);else b(null);function b(i){if(i)return q(i);if(!S)return q();S.call(Q,P,f,q)}}function A(P,I,q){Q.stat(P,function(k){if(!k)return q(null);if(k.code!=="ENOENT")return q(k);Q.mkdir(P,{mode:I.mode,recursive:!0},function(S,m){if(S)return q(S);z(P,I,q)})})}};function JG$($,Z,X,Q){if(Z===X)return Q(null,!0);if(!Z.startsWith(X+K9.sep))return Q(null,!1);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return Q(Y);if(Y||!G.isSymbolicLink())return JG$($,K9.join(Z,".."),X,Q);Q(null,!1)})}function KG$($,Z,X,Q){if(Z===X)return Q(null,!0);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return Q(Y);if(Y||G.isDirectory())return KG$($,K9.join(Z,".."),X,Q);Q(null,!1)})}function Sn(){}function WG$($){return $}function Nn0($){return Vn?$.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):$}function JW4($,Z,X,Q,Y,G){if(!Y)Y=["."];let J=Y.slice(0);return function(W){if(!J.length)return W(null);let F=J.shift(),H=K9.join(X,F);Z.call($,H,function(N,U){if(N)return W(Y.indexOf(F)===-1&&N.code==="ENOENT"?null:N);if(!U.isDirectory())return W(null,F,U);$.readdir(H,function(B,O){if(B)return W(B);if(G)O.sort();for(let L=0;L<O.length;L++)if(!Q(K9.join(X,F,O[L])))J.push(K9.join(F,O[L]));W(null,F,U)})})}}function FG$($,Z){return function(X){X.name=X.name.split("/").slice(Z).join("/");let Q=X.linkname;if(Q&&(X.type==="link"||K9.isAbsolute(Q)))X.linkname=Q.split("/").slice(Z).join("/");return $(X)}}});var HW4,NW4;var NG$=D(()=>{op0();HW4=V(sQ$(),1),NW4=V(HG$(),1)});var fO0=()=>{};var UG$=D(()=>{nB0()});var BG$=D(()=>{PO0();zO0();fO0()});var OG$=()=>{};var DG$=()=>{};var LG$=D(()=>{vQ$();np0();PO0();gQ$();ip0();op0();hQ$();uQ$();cQ$();lQ$();pp0();dQ$();NG$();fO0();UG$();BG$();OG$();DG$();fO0()});var bO0=D(()=>{K4();rm0()});async function yO0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(UW4)});if(!Z.ok)return null;let X=await Z.json();if(typeof X==="object"&&X!==null&&typeof X.bootId==="string"&&typeof X.ready==="boolean"&&X.setup&&typeof X.setup.running==="boolean"&&typeof X.setup.done==="boolean")return X;return null}catch{return null}}async function Bn0($){for(let Z=0;Z<wG$;Z++){if(await yO0($)!==null)return;let X=(Math.random()*2-1)*BW4;await L$(EG$+X)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${wG$*EG$/1000}s`)}async function KC($,Z,X,Q,Y){return OW4($,Z,"POST",X,Q,Y)}async function OW4($,Z,X,Q,Y,G){let J={...Q};if(Y&&Y.rotateToken!==void 0)J.auth=Y;let K=await fetch(`${$}/_sandbox/config`,{method:X,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify(J),signal:AbortSignal.timeout(G?.timeoutMs??Un0)}),W=await K.text();if(!K.ok)throw new xO0(K.status,W);return JSON.parse(W)}async function jG$($,Z,X){let Q=await fetch(`${$}/_sandbox/setup/${X}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(Un0)});if(!Q.ok)throw Error(`sandbox daemon /_sandbox/setup/${X} returned ${Q.status}: ${await Q.text()}`)}async function zG$($,Z,X){let Q=await fetch(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:X,signal:AbortSignal.timeout(Un0)}),Y=await Q.text();if(!Q.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${Q.status}: ${Y}`);return JSON.parse(Y)}async function Cn($,Z,X,Q){let Y=new Headers(Q.headers);for(let K of DW4)Y.delete(K);Y.set("authorization",`Bearer ${Z}`);let G=Q.method!=="GET"&&Q.method!=="HEAD",J=`${$}${X.startsWith("/")?X:`/${X}`}`;return fetch(J,{method:Q.method,headers:Y,body:G?Q.body:void 0,redirect:"manual",signal:Q.signal,duplex:G?"half":void 0})}var xO0,UW4=500,Un0=30000,wG$=25,EG$=200,BW4=50,DW4;var PG$=D(()=>{bO0();xO0=class xO0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};DW4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*RG$($){let Z=$.now??(()=>Date.now()),X=Z(),Q=$.schedulingTimeoutMs??wW4,Y={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:X},G=[],J=null,K=!1,W=(j)=>{if(K)return;if(J){let z=J;J=null,z(j)}else G.push(j)},F=()=>{if(G.length>0)return Promise.resolve(G.shift());if(K)return Promise.resolve(null);return new Promise((j)=>{J=j})},H=()=>{if(K)return;if(K=!0,J){let j=J;J=null,j(null)}},N=new AbortController,U=()=>{N.abort(),H()};if($.signal)if($.signal.aborted)N.abort(),H();else $.signal.addEventListener("abort",U,{once:!0});let B=Math.max(0,Q-(Z()-X)),O=setTimeout(()=>W("tick"),B+100),L,w=new Promise((j)=>{L=j}),E=Promise.allSettled([EW4($.kc,$.namespace,$.claimName,N.signal,Y,W,Z,L),zW4($.kc,$.namespace,$.claimName,N.signal,Y,W),PW4($.kc,$.namespace,$.claimName,w,N.signal,Y,W,Z)]);try{let j=null,z=-1,A=AG$(Y,Q,Z);if(j=Dn0(A),!On0(A))z=TG$(A);if(yield A,On0(A))return;while(!K){if(await F()===null)break;let I=AG$(Y,Q,Z);if(On0(I)){let S=Dn0(I);if(S!==j)j=S,yield I;return}let q=TG$(I);if(q<z)continue;let k=Dn0(I);if(k!==j)j=k,z=q,yield I}}finally{if(clearTimeout(O),N.abort(),$.signal)$.signal.removeEventListener("abort",U);H(),await E.catch(()=>{})}}function AG$($,Z,X){let{pod:Q,sandbox:Y,events:G,startedAt:J}=$;if(Y.ready)return{kind:"ready"};let K=Q.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(!Q.scheduled&&G.lastFailedSchedulingAt!==void 0&&X()-J>Z)return{kind:"failed",reason:"scheduling-timeout",message:G.failedSchedulingMessage??`Pod could not be scheduled within ${Math.round(Z/1000)}s.`};if(Q.containerRunning&&!Q.containerReady)return{kind:"warming-daemon",since:J};if(G.hasPulling&&!G.hasPulled)return{kind:"pulling-image",since:J};if(K==="ContainerCreating"||K==="PodInitializing"||Q.scheduled&&!Q.containerRunning)return{kind:"starting-container",since:J};if(Q.scheduledFalseReason==="Unschedulable"||G.lastFailedSchedulingAt!==void 0&&!Q.scheduled)return{kind:"waiting-for-capacity",since:J,message:G.failedSchedulingMessage??Q.scheduledFalseMessage,nodeClaim:G.nominatedNodeClaim};return{kind:"claiming",since:J}}function On0($){return $.kind==="ready"||$.kind==="failed"}function TG$($){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 Dn0($){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 EW4($,Z,X,Q,Y,G,J,K){let W=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${LW4}=${X}`)}`;return gO0({kc:$,path:W,signal:Q,label:`pod/${X}`,onEvent:(F)=>{if(F.type!=="ADDED"&&F.type!=="MODIFIED")return;let H=F.object;if(H.metadata?.name)K(H.metadata.name);jW4(H,Y,J),G("pod")}})}function jW4($,Z,X){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===J9.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 zW4($,Z,X,Q,Y,G){let J=`/apis/${J9.CLAIM_API_GROUP}/${J9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${J9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`;return gO0({kc:$,path:J,signal:Q,label:`sandboxclaim/${X}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let F=K.object.status?.conditions?.find((H)=>H.type==="Ready");if(!F)return;if(F.status==="True")Y.sandbox.ready=!0,Y.sandbox.notReadyReason=void 0,Y.sandbox.notReadyMessage=void 0;else Y.sandbox.ready=!1,Y.sandbox.notReadyReason=F.reason,Y.sandbox.notReadyMessage=F.message;G("sandbox")}})}async function PW4($,Z,X,Q,Y,G,J,K){let W=await Promise.race([Q,new Promise((H)=>{if(Y.aborted){H(X);return}Y.addEventListener("abort",()=>H(X),{once:!0})})]);if(Y.aborted)return;let F=`/api/v1/namespaces/${encodeURIComponent(Z)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${W},involvedObject.kind=Pod`)}`;return gO0({kc:$,path:F,signal:Y,label:`events/${X}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let N=H.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 IG$($){let{kc:Z,namespace:X,labelSelector:Q,signal:Y,onDelete:G}=$,J=`/apis/${J9.CLAIM_API_GROUP}/${J9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(X)}/${J9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(Q)}`;return gO0({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 gO0($){let{kc:Z,path:X,signal:Q,label:Y,onEvent:G}=$,J=0;while(!Q.aborted){try{let W=await pY(Z,{method:"GET",path:X,signal:Q,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 F of ji0(W.body)){if(Q.aborted)return;try{G(F)}catch(H){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${H instanceof Error?H.message:String(H)}`)}}}catch(W){if(Q.aborted)return;let F=W instanceof Error?W.message:String(W);console.warn(`[lifecycle-watcher] ${Y} watch ended: ${F}`)}if(Q.aborted)return;let K=aZ(5000,250,J,2,0);J+=1,await L$(K,{signal:Q}).catch(()=>{})}}var LW4="studio.decocms.com/sandbox-handle",wW4=300000;var qG$=D(()=>{K4();O70();E70()});import{z as QJ}from"zod";function MG$($){if(!$||$.trim()==="")return[];let Z=QJ.array(AW4).parse(JSON.parse($)),X=new Set;for(let Q of Z){if(X.has(Q.name))throw Error(`STUDIO_SANDBOX_TENANT_POOLS: duplicate pool name ${Q.name}`);X.add(Q.name)}return Z}function TW4($){try{let[Z,X]=new URL($).pathname.replace(/^\/+/,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?`${Z}/${Q}`.toLowerCase():null}catch{return null}}function kG$($,Z){let{orgId:X,cloneUrl:Q}=Z;if(Z.purpose==="harness-run")return null;if(!X||!Q)return null;let Y=TW4(Q);if(!Y)return null;return $.find((G)=>G.orgId===X&&G.repo.toLowerCase()===Y)??null}function VG$($,Z,X){return $?.name??(Z?X:"none")}function RW4($,Z){return $==="harness-run"?`${Z}-medium`:Z}async function SG$($){let Z=RW4($.purpose,$.templateName);if(Z===$.templateName)return{name:Z,probe:$.probe};let X=$.probe!==null&&$.now-$.probe.checkedAt<$.ttlMs?$.probe:{checkedAt:$.now,present:await $.exists(Z)};if(X.present)return{name:Z,probe:X};if($.probe?.present!==!1)$.onAbsent?.(Z);return{name:$.templateName,probe:X}}function CG$($,Z,X){let Q=X.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===Q)}function _G$($){return`https://github.com/${$.repo}.git`}var AW4;var Ln0=D(()=>{AW4=QJ.object({name:QJ.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:QJ.string().min(1),repo:QJ.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:QJ.string().min(1).optional(),branch:QJ.string().min(1).default("main"),workload:QJ.object({runtime:QJ.enum(["node","bun","deno"]).default("node"),packageManager:QJ.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:QJ.string().optional(),devPort:QJ.number().int().positive().optional()}).default({runtime:"node"})})});async function vG$($,Z,X){let Q=new Map;for(let Y of $){let G=Z(Y);if(!G)continue;let J=Q.get(G);if(J)J.push(Y);else Q.set(G,[Y])}await Promise.allSettled([...Q.values()].map(async(Y)=>{for(let G of Y)await X(G).catch(()=>{})}))}import{createHash as IW4,randomBytes as qW4,randomUUID as MW4}from"crypto";import*as uG$ from"net";import{PassThrough as kW4}from"stream";function fG$($){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 Tn0{records=new Map;inflight=new rZ0;activeGauge=new oZ0;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??lW4(),this.portForward=new rp0(this.kubeConfig),this.namespace=$.namespace??VW4,this.sandboxTemplateName=$.sandboxTemplateName??SW4,this.envName=tW4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>qW4(_W4).toString("hex")),this.idleTtlMs=$.idleTtlMs??fW4,this.metrics=$.meter?cW4($.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(`[${K6}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??xW4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${eX.env}=${this.envName}`]:[]].join(",");IG$({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let X=SE($);if(X.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(X,()=>aZ0(this.stateStore,$,(Q)=>this.ensureLocked($,X,Z,Q)))}async delete($){let Z=await this.getRecord($);if(this.records.delete($),Z)this.dropRecord(Z);if(await this.deleteHttpRouteIfManaged($).catch((X)=>{console.warn(`[${K6}] HTTPRoute delete failed for ${$}: ${X instanceof Error?X.message:String(X)}`)}),await Ry(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id);else await this.stateStore.deleteByHandle($)}lastTermination($){return v5$(this.kubeConfig,this.namespace,eX.sandboxHandle,$,J9.MAIN_CONTAINER_NAME)}async alive($){return await hH(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return RG$({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=m5$(this.kubeConfig,this.namespace),this.capacityProbe()}async getPreviewUrl($){let Z=await this.getRecord($);if(!Z)return null;return this.composePreviewUrl(Z)}async proxyDaemonRequest($,Z,X){let Q=await this.getRecord($);if(!Q&&this.previewUrlPattern&&this.stateStore){let W=await this.stateStore.getByHandle($),F=W?.state,H=F?.token;if(W&&H){let U=`http://${F?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${pH}`;try{let B=await Cn(U,H,Z,X);if(B.status!==404)return B;try{await B.body?.cancel()}catch{}}catch{}}}if(!Q)Q=await this.resurrectByHandle($);if(!Q)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let Y=Q,G=performance.now(),J=0,K=!(X.body instanceof ReadableStream);try{let W=await Cn(Q.daemonUrl,Q.token,Z,X);if(W.status===401&&K){this.invalidateRecord($);let F=await this.getRecord($).catch(()=>null)??await this.resurrectByHandle($).catch(()=>null);if(F){try{await W.body?.cancel()}catch{}Y=F,W=await Cn(F.daemonUrl,F.token,Z,X)}}return J=W.status,W}catch(W){if(!K)throw W;this.invalidateRecord($);let F=await this.resurrectByHandle($)??await this.getRecord($).catch(()=>null);if(!F)throw W;Y=F;let H=await Cn(F.daemonUrl,F.token,Z,X);return J=H.status,H}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let X=await hH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!X||X.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,X);if(!G)throw Error(`cannot adopt live claim ${Z}`);return aZ0(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:${pH}`;let Z=await this.getRecord($);if(Z)return Z.daemonUrl;let X=await this.resurrectByHandle($);return X?X.daemonUrl:null}async resolveServiceNameForHandle($){let Z=this.records.get($);if(Z)return Z.adoptedSandboxName;if(this.stateStore){let Q=(await this.stateStore.getByHandle($).catch(()=>null))?.state?.adoptedSandboxName;if(Q)return Q}return $}async proxyPreviewRequest($,Z){let X=performance.now(),Q=this.records.get($)??null,Y=0;try{let G=await this.resolvePreviewUpstreamUrl($);if(!G){Y=404;let O=En0(404,{error:"sandbox not found"});return O.headers.set(FC,"1"),O}let J=new URL(Z.url);if((J.pathname==="/_sandbox"||J.pathname.startsWith("/_sandbox/"))&&Z.method!=="GET")return Y=404,En0(404,{error:"not found"});let W=(O)=>`${O}${J.pathname}${J.search}`,F=new Headers(Z.headers);for(let O of hW4)F.delete(O);let H=Z.method!=="GET"&&Z.method!=="HEAD",N={method:Z.method,headers:F,body:H?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:H?"half":void 0},U;try{U=await fetch(W(G),N)}catch(O){let L=`${G}${J.pathname}`;if(console.warn(`[${K6}] preview fetch to ${L} 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(!yG$.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(`[${K6}] preview fetch retry to ${L} failed: ${z instanceof Error?z.message:String(z)}`)}}}else this.invalidateRecord($);Y=502;let w=En0(502,{error:"sandbox daemon unreachable"});return w.headers.set(FC,"1"),w}let B=new Headers;for(let[O,L]of U.headers.entries())if(!yG$.includes(O.toLowerCase()))B.set(O,L);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:B})}finally{this.recordProxyDuration("preview",Y,Q,performance.now()-X,$)}}async ensureLocked($,Z,X,Q){if(X.image)console.warn(`[${K6}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${X.image}`);if(Q){let J=await Q.get($);if(J){let K=await this.rehydrate($,Z,J);if(K)return await this.refreshDaemonGitCredential(K,X),await this.relayOrgFsConfig(K.daemonUrl,K.token,X.orgFsConfigJson),this.finish(K,Q,!1,!0,"resume");await Q.delete($)}}let Y=await hH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await L70(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${K6}] 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(`[${K6}] adopt ${Z} failed, recreating: ${K instanceof Error?K.message:String(K)}`),null});if(J)return await this.refreshDaemonGitCredential(J,X),await this.relayOrgFsConfig(J.daemonUrl,J.token,X.orgFsConfigJson),this.finish(J,Q,!0,!0,"adopt");await Ry(this.kubeConfig,this.namespace,Z).catch(()=>{}),await L70(this.kubeConfig,this.namespace,Z).catch((K)=>{console.warn(`[${K6}] wait for deleted claim ${Z} failed: ${K instanceof Error?K.message:String(K)}`)})}let G=await this.provision($,Z,X);return this.finish(G,Q,!0,!1,"fresh")}async finish($,Z,X,Q,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,$),X)await this.persist(Z,$);if(Q)await w70(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((K)=>console.warn(`[${K6}] TTL refresh failed for ${$.handle}: ${K instanceof Error?K.message:String(K)}`));if(this.metrics){let K=zn0($.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 X={},Q=[];for(let[Y,G]of Object.entries($.env??{}))if(vW4.has(Y))Q.push(Y);else X[Y]=G;if(Q.length>0)console.warn(`[${K6}] opts.env keys overlap reserved bootstrap names and were dropped: ${Q.join(",")}`);return{...X,DAEMON_TOKEN:Z.token,DAEMON_BOOT_ID:Z.daemonBootId,APP_ROOT:Z.workdir,PROXY_PORT:String(pH)}}async resolveTemplateName($){let{name:Z,probe:X}=await SG$({purpose:$,templateName:this.sandboxTemplateName,probe:this.mediumTemplateProbe,now:Date.now(),ttlMs:CW4,exists:(Q)=>V5$(this.kubeConfig,this.namespace,Q),onAbsent:(Q)=>console.warn(`[${K6}] SandboxTemplate ${Q} 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=X,Z}buildClaim($,Z,X,Q){let Y=this.sentinelToken!==null,G=kG$(this.tenantPools,{orgId:Z.tenant?.orgId,cloneUrl:Z.repo?.cloneUrl,purpose:Z.purpose}),J=Y?[]:Object.entries(this.buildEnvMap(Z,X)).sort(([F],[H])=>F<H?-1:F>H?1:0).map(([F,H])=>({name:F,value:H})),K=aW4(Z),W=Object.keys(K).length>0;return{apiVersion:`${J9.CLAIM_API_GROUP}/${J9.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?{[eX.env]:this.envName}:{},...jn0(Z.tenant)},...W?{annotations:K}:{}},spec:{sandboxTemplateRef:{name:Q},additionalPodMetadata:{labels:jn0(Z.tenant,{[eX.role]:"claimed",[eX.sandboxHandle]:$,...this.envName?{[eX.env]:this.envName}:{}}),...W?{annotations:K}:{}},env:J,warmpool:VG$(G,Y,Q),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,X){let Q=this.tokenGenerator(),Y=MW4(),G=wn0,J=this.buildClaim(Z,X,{token:Q,daemonBootId:Y,workdir:G},await this.resolveTemplateName(X.purpose));try{await Li0(this.kubeConfig,this.namespace,J)}catch(U){if(U instanceof Hn)await L70(this.kubeConfig,this.namespace,Z),await Li0(this.kubeConfig,this.namespace,J);else throw U}let K;try{K=await S5$(this.kubeConfig,this.namespace,Z),await l5$(this.kubeConfig,this.namespace,K)}catch(U){throw await Ry(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}try{await this.ensureServicePortForAdoptedSandbox(K),await this.ensureHttpRouteForHandle(Z,K,X.tenant??null)}catch(U){throw await Ry(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}let W=await this.openForwarder(K,pH,Z),F=`http://127.0.0.1:${W.localPort}`,H=this.workloadConfigPayload(X),N=Y;try{if(await Bn0(F),this.sentinelToken!==null){let U=await yO0(F);if(U)N=U.bootId;await KC(F,this.sentinelToken,H??{},{rotateToken:Q})}else if(H)await KC(F,Q,H);await this.relayOrgFsConfig(F,Q,X.orgFsConfigJson)}catch(U){throw this.closeForwarder(W),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await Ry(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}return{id:$,handle:Z,adoptedSandboxName:K,token:Q,workdir:G,daemonUrl:F,daemonForward:W,workload:X.workload??null,daemonBootId:N,tenant:X.tenant??null,ensureOpts:XF4(X)}}workloadConfigPayload($){return eZ0({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,extraRepos:$?.extraRepos??[],port:$?.workload?.devPort??bG$,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,X){if(!X)return;await zG$($,Z,X).catch((Q)=>console.warn("[org-fs] sidecar config relay failed",Q))}async refreshDaemonGitCredential($,Z){let X=am0(Z);if(!X)return;try{await KC($.daemonUrl,$.token,X)}catch(Q){console.warn(`[${K6}] git credential refresh failed for ${$.handle}: ${Q instanceof Error?Q.message:String(Q)}`)}}async withFreshCloneUrl($,Z){if(!this.mintCloneUrl)return $;try{let X=await this.mintCloneUrl($,Z!==void 0?{bufferMs:Z}:void 0);return X?{...$,cloneUrl:X}:$}catch(X){return console.warn(`[${K6}] clone credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$}}async withFreshCredentials($){return{...$,...$.repo?{repo:await this.withFreshCloneUrl($.repo)}:{},...$.orgFsConfigJson?{orgFsConfigJson:await ZF4($,this.mintOrgFsConfig)}:{}}}startCredentialRefresher(){if(!this.mintCloneUrl)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){if(await L$(yW4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${K6}] 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(`[${K6}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await L$(bW4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let X=CG$(this.tenantPools,$,Z);for(let Q of X)this.dirtyPools.add(Q.name);return X.map((Q)=>Q.name)}async reconcileTenantPools(){for(let $ of this.tenantPools){let Z=await C5$(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${K6}] tenant pool ${$.name}: no SandboxWarmPool (or no selector yet) in ${this.namespace}`);continue}let X=this.dirtyPools.delete($.name),Q=Z.filter((Y)=>!Y.labels[eX.sandboxHandle]);for(let[Y]of this.poolPods)if(!Z.some((G)=>G.uid===Y))this.poolPods.delete(Y);for(let Y of Q){if(this.claimWatchAbort.signal.aborted)return;await this.warmPoolPod($,Y,X)}this.recordPoolDepth($,Z,Q)}}recordPoolDepth($,Z,X){let Q=this.metrics?.poolPods;if(!Q)return;let Y=0,G=0;for(let K of X){let W=this.poolPods.get(K.uid);if(!W)continue;if(W.failures>=hO0)G++;else if(W.lastConfigAt>0)Y++}let J={pool:$.name,org:$.orgId};Q.record(Y,{...J,state:"ready"}),Q.record(Z.length-X.length,{...J,state:"bound"}),Q.record(X.length-Y-G,{...J,state:"pending"}),Q.record(G,{...J,state:"failed"})}async warmPoolPod($,Z,X){let Q=this.poolPods.get(Z.uid);if(Q&&Q.failures>=hO0){if(Date.now()-Q.lastFailureAt<xG$)return;this.poolPods.set(Z.uid,{...Q,failures:0})}let Y=X||Q!==void 0&&Date.now()-Q.lastConfigAt>=this.tenantPoolRefreshMs;if(Q&&!Y)return;let G={cloneUrl:_G$($),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,pH,Z.name).catch(()=>null);if(!K){this.recordPoolFailure(Z,$,"port-forward failed");return}let W=`http://127.0.0.1:${K.localPort}`;try{await Bn0(W);let F=this.sentinelToken;if(!F)return;if(!await this.isPoolPodUnbound(Z))return;let H=eZ0({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??bG$})??{},{transition:N}=await KC(W,F,H);if(Y&&N!=="bootstrap"&&await this.isPoolPodUnbound(Z))await jG$(W,F,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${K6}] tenant pool ${$.name}: warmed ${Z.name} (${N})`)}catch(F){this.recordPoolFailure(Z,$,F instanceof Error?F.message:String(F))}finally{this.closeForwarder(K)}}isPoolPodUnbound($){return _5$(this.kubeConfig,this.namespace,$.name,eX.sandboxHandle)}recordPoolFailure($,Z,X){let Q=this.poolPods.get($.uid),Y=(Q?.failures??0)+1;this.poolPods.set($.uid,{lastConfigAt:Q?.lastConfigAt??0,lastFailureAt:Date.now(),failures:Y});let G=Y>=hO0?` \u2014 backing off ${xG$/60000}min`:"";console.warn(`[${K6}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${hO0})${G}: ${X}`)}async refreshAllGitCredentials(){await vG$(this.records.values(),($)=>$.ensureOpts?.repo?.connectionId,async($)=>{if(this.claimWatchAbort.signal.aborted)return;let Z=$.ensureOpts?.repo;if(!Z)return;let X=await this.withFreshCloneUrl(Z,gW4);await this.refreshDaemonGitCredential($,{...$.ensureOpts,repo:X}),$.ensureOpts={...$.ensureOpts,repo:X}})}async rebootstrapDaemon($,Z,X){if(this.sentinelToken===null)return!1;let Q=this.workloadConfigPayload(X)??{};try{return await KC($,this.sentinelToken,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(Y){if(Y instanceof xO0&&Y.status===401)try{return await KC($,Z,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(G){return console.warn(`[${K6}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${K6}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await c5$(this.kubeConfig,this.namespace,$,{name:"daemon",port:pH,targetPort:pH})}async ensureHttpRouteForHandle($,Z,X){if(!this.previewGateway||!this.previewUrlPattern)return;let Q=QF4(this.previewUrlPattern,$);if(!Q)throw new FZ(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${Ei0.API_GROUP}/${Ei0.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:jn0(X??void 0,{[eX.role]:"claimed",[eX.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[eX.env]:this.envName}:{}})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[Q],rules:[{backendRefs:[{group:"",kind:"Service",name:Z,port:pH}]}]}};await g5$(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await h5$(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,X){let Q=X.state;if(!Q.adoptedSandboxName&&!Q.podName||!Q.token)return null;let Y=await hH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!gG$(Y))return null;let G=Y.status?.sandbox?.name??Q.adoptedSandboxName??Q.podName??Z,J=await this.openAndProbeDaemon(G,Z);if(!J)return null;if(Q.daemonBootId&&Q.daemonBootId!==J.bootId){if(this.sentinelToken!==null){let K=Q.ensureOpts?await this.withFreshCredentials(Q.ensureOpts):null;if(!await this.rebootstrapDaemon(J.daemonUrl,Q.token,K))return this.closeForwarder(J.daemonForward),null}else console.warn(`[${K6}] daemon restart detected (handle=${Z}): stored bootId=${Q.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,{handle:Z,state:{...Q,daemonBootId:J.bootId}}).catch((K)=>console.warn(`[${K6}] bootId persist failed for ${Z}: ${K instanceof Error?K.message:String(K)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:Q.token,workdir:Q.workdir??wn0,daemonUrl:J.daemonUrl,daemonForward:J.daemonForward,workload:Q.workload??null,daemonBootId:J.bootId,tenant:Q.tenant??null,ensureOpts:Q.ensureOpts??null}}async adopt($,Z,X){if(!gG$(X))return null;let Q=X.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=dW4(X);if(!Y)return null;let G=await this.openAndProbeDaemon(Q,Z);if(!G)return null;let J=sW4(X);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(Q).catch((K)=>{console.warn(`[${K6}] Service port backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)}),await this.ensureHttpRouteForHandle(Z,Q,J).catch((K)=>{console.warn(`[${K6}] HTTPRoute backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)});return{id:$,handle:Z,adoptedSandboxName:Q,token:Y,workdir:wn0,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let X=await this.openForwarder($,pH,Z).catch(()=>null);if(!X)return null;let Q=`http://127.0.0.1:${X.localPort}`,Y=await yO0(Q);if(!Y)return this.closeForwarder(X),null;return{daemonForward:X,daemonUrl:Q,bootId:Y.bootId}}async getRecord($){let Z=this.records.get($);if(Z)return Z;if(!this.stateStore)return null;let X=await this.stateStore.getByHandle($);if(!X)return null;let Q=await this.rehydrate(X.id,$,X);if(Q)this.records.set($,Q);return Q}async resurrectByHandle($){if(!this.stateStore)return null;let Z=await this.stateStore.getByHandle($);if(!Z)return null;let X=Z.state.ensureOpts;if(!X)return null;let Q=await this.withFreshCredentials(X);if(SE(Z.id)!==$)return null;return await this.ensure(Z.id,Q),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,zn0($.tenant))}recordProxyDuration($,Z,X,Q,Y){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...zn0(X?.tenant??null),source:$,sandbox_handle:X?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return sZ0(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 X={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:X})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let X=await hH(this.kubeConfig,this.namespace,$);if(!X)return;let Q=eW4(X.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!Q)return;await w70(this.kubeConfig,this.namespace,$,Q).catch((Y)=>console.warn(`[${K6}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await hH(this.kubeConfig,this.namespace,$);if(!Z)return;let X=$F4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!X)return;await w70(this.kubeConfig,this.namespace,$,X).catch((Q)=>console.warn(`[${K6}] TTL renew failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`))}openForwarder($,Z,X=$){let Q=mW4(X,Z);return new Promise((Y,G)=>{let J=(K,W)=>{let F=uG$.createServer((H)=>this.handleForwardedConnection(H,$,Z,X));F.once("error",(H)=>{if(H.code==="EADDRINUSE"&&W<uW4){try{F.close()}catch{}let N=Pn0+(K-Pn0+1)%cG$;J(N,W+1);return}G(H)}),F.listen(K,"127.0.0.1",()=>{let H=F.address();if(!H||typeof H==="string"){F.close(),G(Error("port-forward listener failed to bind"));return}Y({server:F,localPort:H.port})})};J(Q,0)})}handleForwardedConnection($,Z,X,Q){let Y=new kW4,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,[X],$,null,Y).then((W)=>{let F=typeof W==="function"?W():W;if(!F){K();return}if(G=F,G.on("close",K),G.on("error",(H)=>{console.warn(`[${K6}] port-forward to ${Z}:${X} dropped mid-connection: ${fG$(H)}`,JSON.stringify(An0(H))),this.invalidateRecord(Q),K()}),J)try{G.close()}catch{}}).catch((W)=>{console.warn(`[${K6}] port-forward to ${Z}:${X} failed: ${fG$(W)}`,JSON.stringify(An0(W))),this.invalidateRecord(Q),K()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${K6}] 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 cW4($){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 An0($){let Z=[],X=$;for(let Q=0;Q<5&&X instanceof Error;Q++){let Y=X;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===X)break;X=Y.cause}if(X!==void 0&&!(X instanceof Error)&&X!==null){let Q=X,Y=Q.error instanceof Error?An0(Q.error).chain:void 0;Z.push({nonError:String(X),...typeof Q.type==="string"?{type:Q.type}:{},...typeof Q.message==="string"?{message:Q.message}:{},...Q.code!==void 0?{code:Q.code}:{},...typeof Q.reason==="string"?{reason:Q.reason}:{},...Y?{error:Y}:{},...Y===void 0&&Q.error!==void 0?{rawError:String(Q.error)}:{},keys:Object.keys(Q)})}return{chain:Z}}function lW4(){let $=new EO0;return $.loadFromDefault(),$}function gG$($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function dW4($){let Z=$.spec?.env;if(!Z)return null;for(let X of Z)if(X.name==="DAEMON_TOKEN"&&X.value)return X.value;return null}function mW4($,Z){let X=IW4("sha256").update(`${$}:${Z}`).digest();return Pn0+X.readUInt32BE(0)%cG$}function En0($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function hG$($){let Z=$.slice(0,pW4);return iW4.test(Z)?Z:""}function tW4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!nW4.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 jn0($,Z={}){let X={...Z};if($){let Q=hG$($.orgId),Y=hG$($.userId);if(Q)X[eX.orgId]=Q;if(Y)X[eX.userId]=Y}return X}function WC($){let Z="";for(let X of $){let Q=X.codePointAt(0)??0;Z+=Q<32||Q===127?" ":X}return Z.slice(0,oW4)}function rW4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function aW4($){let Z={},X=$.tenant;if(X?.orgSlug)Z[h3.orgSlug]=WC(X.orgSlug);if(X?.orgName)Z[h3.orgName]=WC(X.orgName);if(X?.userEmail)Z[h3.userEmail]=WC(X.userEmail);if(X?.userName)Z[h3.userName]=WC(X.userName);let Q=$.repo;if(Q){if(Q.displayName)Z[h3.gitRepo]=WC(Q.displayName);let Y=rW4(Q.cloneUrl);if(Y)Z[h3.gitRepoUrl]=WC(Y);let G=$.branch??Q.branch;if(G)Z[h3.gitBranch]=WC(G)}return Z}function sW4($){let Z=$.metadata?.labels;if(!Z)return null;let X=Z[eX.orgId],Q=Z[eX.userId];if(!X||!Q)return null;let Y=$.metadata?.annotations??{};return{orgId:X,userId:Q,orgSlug:Y[h3.orgSlug],orgName:Y[h3.orgName],userEmail:Y[h3.userEmail],userName:Y[h3.userName]}}function eW4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X<=Z.getTime())return null}return Z.toISOString()}function $F4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X>=Z.getTime())return null}return Z.toISOString()}function zn0($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:"agent-sandbox"}}async function ZF4($,Z){if(!Z||!$.tenant)return $.orgFsConfigJson;try{return await Z($.tenant)??$.orgFsConfigJson}catch(X){return console.warn(`[${K6}] org-fs credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$.orgFsConfigJson}}function XF4($){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 QF4($,Z){try{return new URL(sZ0($,Z)).hostname||null}catch{return null}}var K6="AgentSandboxProvider",FC="x-sandbox-preview-not-ready",VW4="agent-sandbox-system",SW4="studio-sandbox",CW4=300000,pH=9000,bG$=3000,wn0="/app",_W4=32,vW4,fW4=900000,bW4=60000,xW4=1800000,hO0=3,xG$=1800000,yW4=900000,gW4=1800000,hW4,yG$,Pn0=40000,cG$=1e4,uW4=256,eX,h3,iW4,pW4=63,nW4,oW4=253;var lG$=D(()=>{K4();i5$();LG$();PG$();sm0();E70();O70();qG$();Ln0();vW4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),hW4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],yG$=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];eX={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"},h3={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"},iW4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;nW4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var dG$={};J4(dG$,{parseTenantPools:()=>MG$,PREVIEW_NOT_READY_HEADER:()=>FC,AgentSandboxProvider:()=>Tn0});var Rn0=D(()=>{lG$();Ln0()});var pG$={};J4(pG$,{subscribeLifecycle:()=>Sn0,getOrInitSharedRunner:()=>Vn0,getAgentSandboxProviderForTeardown:()=>kn0,getAgentSandboxProvider:()=>$Q,__resetSharedLifecyclesForTesting:()=>BF4});function qn0($){let Z=_n[mG$];if(Z)return Promise.resolve(Z);let X=_n[In0];if(X)return X;let Q=$().then((Y)=>{return _n[mG$]=Y,Y}).finally(()=>{delete _n[In0]});return _n[In0]=Q,Q}function YF4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function GF4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function JF4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function KF4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function WF4(){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 Mn0($){let Z=new Kn($),X=YF4(),{AgentSandboxProvider:Q,parseTenantPools:Y}=await Promise.resolve().then(() => (Rn0(),dG$)),G=new kY(b0().encryptionKey);return new Q({stateStore:Z,previewUrlPattern:X,sandboxTemplateName:GF4(),envName:JF4(),previewGateway:WF4(),sentinelToken:KF4(),tenantPools:Y(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:w$,mintCloneUrl:async(J,K)=>{if(!J.connectionId)return null;let W=I5$(J.cloneUrl);if(!W)return null;let{cloneUrl:F}=await TW(J.connectionId,W.owner,W.name,$,G,{bufferMs:K?.bufferMs});return F},mintOrgFsConfig:async(J)=>{if(!J.orgSlug)return null;return await B70({boundAuth:{apiKey:{create:(W)=>X8.api.createApiKey({body:{...W,userId:J.userId}})}},storage:{orgRepoSyncs:new fE($)}},{orgSlug:J.orgSlug,orgId:J.orgId,baseUrl:f9()})??null}})}function $Q($){if(!b0().agentSandboxEnabled)throw Error("Agent sandbox is disabled. Set STUDIO_AGENT_SANDBOX_ENABLED=true to enable it.");return qn0(()=>Mn0($.db))}function kn0($){return qn0(()=>Mn0($.db))}async function Vn0(){if(!b0().agentSandboxEnabled)return null;return qn0(()=>Mn0(r8().db))}function Sn0($,Z,X){let Q=_O.get(Z);if(Q){if(Q.terminated){if(Q.lastPhase)try{X(Q.lastPhase)}catch{}return{unsubscribe:NF4}}if(Q.listeners.add(X),Q.lastPhase)try{X(Q.lastPhase)}catch{}return iG$(Z,Q,X)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([X]),abort:Y};return _O.set(Z,G),UF4($,Z,G),iG$(Z,G,X)}function NF4(){}function iG$($,Z,X){return{unsubscribe(){if(_O.get($)!==Z)return;if(Z.listeners.delete(X),Z.listeners.size===0)_O.delete($),Z.abort.abort()}}}async function UF4($,Z,X){let Q=null;try{for await(let Y of $.watchClaimLifecycle(Z,X.abort.signal)){if(X.abort.signal.aborted)break;X.lastPhase=Y;let G=Y.kind==="ready"||Y.kind==="failed";if(G)X.terminated=!0;let J=Array.from(X.listeners);for(let K of J)try{K(Y)}catch{}if(G)break}}catch(Y){Q=Y}finally{if(!X.terminated&&!X.abort.signal.aborted&&X.listeners.size>0){let Y={kind:"failed",reason:"unknown",message:Q instanceof Error?Q.message:"Lifecycle watcher ended unexpectedly"};X.lastPhase=Y,X.terminated=!0;for(let G of Array.from(X.listeners))try{G(Y)}catch{}}if(_O.get(Z)===X)_O.delete(Z)}}function BF4(){for(let $ of _O.values())$.abort.abort();_O.clear()}var mG$,In0,_n,FF4,HF4,_O;var u3=D(()=>{lG();I6();Ni0();Py();eL();R$();Ty();hY();$9();mG$=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-runner"),In0=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-inflight"),_n=globalThis;FF4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),HF4=globalThis,_O=HF4[FF4]??=new Map});async function vn($,Z,X){try{await $.storage.threads.stampRuntimeIfAbsent(Z,X)}catch(Q){console.warn(`[stampRuntimeIfAbsent] ${Z}: ${Q instanceof Error?Q.message:String(Q)}`)}}function nG$($){let Z=$?.trim();if(!Z)return null;try{let X=new URL(Z);if(X.protocol!=="http:"&&X.protocol!=="https:")return null;return X.href}catch{return null}}function uO0($){return nG$($?.previewServerUrl)??nG$($?.productionUrl)}function HC($){return $==="cms"||$==="sandbox"?$:null}function OF4($){return!!uO0($)&&$?.fastPreview===!0}function cO0($){return OF4($)?"cms":"sandbox"}var Cn0;var hy=D(()=>{Cn0=["cms","sandbox"]});function tG$($){let{current:Z,detached:X,base:Q}=$.status??{};if(typeof Z!=="string"||Z.length===0)return null;if(X===!0)return null;if(Z===$.requestedRef)return null;if(DF4.has(Z))return null;if(typeof Q==="string"&&Q.length>0&&Z===Q)return null;return Z}function lO0($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var DF4;var dO0=D(()=>{DF4=new Set(["main","master","trunk","develop","HEAD"])});import{z as nH}from"zod";async function uy($,Z){r(Z);let X=t(Z),Q=o0(Z);if(!Q)throw Error("User ID required");let Y=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!Y||Y.organization_id!==X.id)throw Error("Virtual MCP not found");let G=Y.metadata??{},J=await CE(Z,$.branch,Q),K=AW(I9(G),J,$.branch),W=await $Q(Z);if(K){if(await W.alive(K.sandboxHandle).catch(()=>!0))return K;await DO(Z.storage.virtualMcps,$.virtualMcpId,Q,J,$.branch).catch((O)=>{console.warn("[ensureSandbox] failed to reap stale entry",O)})}let F=eG($.branch)??Z.metadata?.threadId;if(F)vn(Z,F,"sandbox");let N=await wO(Z,F)??G.githubRepo??null,{entry:U}=await rG$({ctx:Z,userId:Q,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:N,threadRepos:await Qi0(Z,F),existing:null,runner:W,...$.purpose?{purpose:$.purpose}:{}});return U}async function LF4($){let Z=$.primary?`${$.primary.owner}/${$.primary.name}`.toLowerCase():null,X=$.repos.filter((G)=>`${G.owner}/${G.name}`.toLowerCase()!==Z),Q=$n(X),Y=[];for(let[G,J]of X.entries()){if(!J.connectionId)continue;try{let{cloneUrl:K}=await TW(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:Q[G],submoduleCredentials:[]})}catch(K){console.warn(`[provisionSandbox] skipping secondary ${J.owner}/${J.name}:`,K instanceof Error?K.message:K)}}return Y}async function rG$($){let{ctx:Z,userId:X,sandboxUserId:Q,orgId:Y,virtualMcpId:G,branch:J,metadata:K,threadRepos:W,existing:F,runner:H,purpose:N}=$,U=N==="harness-run",B=$.githubRepo?await wF4({ctx:Z,orgId:Y,virtualMcpId:G,userId:X,githubRepo:$.githubRepo}):null,{runtime:O,packageManager:L,port:w,packageManagerPath:E}=Q5$(K),j;if(B){if(B.connectionId)await zO({ctx:Z,connectionId:B.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(R0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:B.connectionId,error:R0.message})}});let{cloneUrl:s,gitUserName:a,gitUserEmail:z0}=B.connectionId?await TW(B.connectionId,B.owner,B.name,Z.db,Z.vault):U5$(B.owner,B.name);if(!L){let R0=B.connectionId?await D5$(B.connectionId,B.owner,B.name,Z.db,Z.vault):await L5$(B.owner,B.name);if(R0)L=R0.packageManager,O=Zn[R0.packageManager].runtime,w=R0.devPort??w,await EF4(Z,G,X,R0.packageManager,R0.devPort)}let X0=b0().sandboxStickyHeadRefEnabled,P0=lO0({branch:J,derivedRef:gH(J),recordedHeadRef:X0?await a6$(Z,eG(J)):null,sticky:X0}),g0=await J5$({ctx:Z,orgId:Y,userId:X,entries:Z5$(K)});j={cloneUrl:s,...B.connectionId?{connectionId:B.connectionId}:{},userName:a,userEmail:z0,branch:P0,displayName:`${B.owner}/${B.name}`,submoduleCredentials:g0}}let z=await LF4({ctx:Z,orgId:Y,repos:W??[],primary:B,gitUserName:j?.userName??"",gitUserEmail:j?.userEmail??""}),A=O&&L&&!U?{runtime:O,packageManager:L,...w!==null?{devPort:Number(w)}:{},...E?{packageManagerPath:E}:{}}:void 0,P=ap({orgId:Y,virtualMcpId:G,branch:J}),I=!b0().orgFsMountsDisabled,q;if(I){let s=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(s)q=await B70(Z,{orgSlug:s,orgId:Y,baseUrl:f9()})}await zF4(H);let k=await H.ensure({userId:Q,projectRef:P},{branch:J,repo:j,extraRepos:z,workload:A,cloneOnly:U,...N?{purpose:N}:{},tenant:{orgId:Y,userId:Q,...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=jy(K);await Q70({ctx:Z,runner:H,handle:k.handle,orgId:Y,userId:X,entries:S});let f=!!F&&F.sandboxHandle===k.handle&&F?.createdAt?F.createdAt:Date.now(),b=K.runtime?.selected??null,i=K.runtime?.port??null,u=K.runtime?.path??null,o={sandboxHandle:k.handle,previewUrl:k.previewUrl,createdAt:f,startedWith:{packageManager:b,port:i,path:u}};await u6$(Z.storage.virtualMcps,G,X,Q,J,o);let U0=eG(J)??Z.metadata?.threadId;if(U0)await e6$(Z,U0,Q,J,o);let E0=!F||F.sandboxHandle!==k.handle;return{entry:o,isNewVm:E0}}async function wF4($){let{ctx:Z,orgId:X,virtualMcpId:Q,userId:Y,githubRepo:G}=$;if(!G.connectionId)return G;if(await Z.storage.connections.findById(G.connectionId,X))return G;let{items:K}=await Z.storage.connections.list(X),W=FZ0(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:Q,connectionId:G.connectionId}),G;console.warn("[provisionSandbox] healed dangling repo connection",{virtualMcpId:Q,staleConnectionId:G.connectionId,connectionId:W.id});try{let H=(await Z.storage.virtualMcps.findById(Q))?.metadata??{},N=H.githubRepo;if(N?.connectionId===G.connectionId){let U=M5(W);await Z.storage.virtualMcps.update(Q,Y,{metadata:{...H,githubRepo:{...N,connectionId:W.id,...U?{installationId:U.installationId}:{}}}})}}catch(F){console.warn("[provisionSandbox] failed to persist healed repo connection",{virtualMcpId:Q,error:F.message})}return{...G,connectionId:W.id}}async function EF4($,Z,X,Q,Y){let G=await $.storage.virtualMcps.findById(Z);if(!G)return;let J=G.metadata??{};await $.storage.virtualMcps.update(Z,X,{metadata:{...J,runtime:{selected:Q,port:Y}}})}async function zF4($){let Z=Date.now()+oG$,X=!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(oG$/1000)}s`);if(!X)X=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await L$(jF4)}}var _n0,oG$=150000,jF4=5000;var fn=D(()=>{ep();K4();k0();Xn();Ki0();K5$();iQ();_Q();Py();E5$();$i0();u3();hy();b3();dO0();R$();$9();Ty();iQ();_n0=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:nH.object({virtualMcpId:nH.string().describe("Virtual MCP ID"),branch:nH.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:nH.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:nH.object({previewUrl:nH.string().nullable(),sandboxHandle:nH.string(),branch:nH.string(),isNewVm:nH.boolean()}),handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=$.branch??K70(J70(Z.auth.user)),Y=eG(Q)??$.threadId??Z.metadata?.threadId;if(Y){let L=await Z.storage.threads.get(Y).catch(()=>null);if(HC(L?.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=o0(Z);if(!G)throw Error("User ID required");let J=await CE(Z,Q,G),K=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!K||K.organization_id!==X.id)throw Error("Virtual MCP not found");let W=K.metadata??{},F=await $Q(Z),H=AW(I9(W),J,Q),U=await wO(Z,eG(Q)??Z.metadata?.threadId)??W.githubRepo??null,{entry:B,isNewVm:O}=await rG$({ctx:Z,userId:G,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:Q,metadata:W,githubRepo:U,threadRepos:await Qi0(Z,eG(Q)??Z.metadata?.threadId),existing:H,runner:F});if(Y)vn(Z,Y,"sandbox");return{...B,branch:Q,isNewVm:O}}})});function PF4($){let{publicUrl:Z,agentId:X,organization:Q,target:Y,threadId:G}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${encodeURIComponent(X)}`;if(!Q.slug)throw new sG$(Q.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/${Q.slug}/mcp/task-run/${encodeURIComponent(G)}`}return`${Z}/api/${Q.slug}/mcp/self`}async function mO0($,Z,X,Q,Y="agent-tools",G,J={"*":["*"]}){let K=PF4({publicUrl:f9(),agentId:Z,organization:X,target:Y,...G?{threadId:G}:{}}),W=await $.boundAuth.apiKey.create({name:Q,permissions:J,expiresIn:aG$,metadata:{organization:{id:X.id,slug:X.slug,name:X.name}}});return{url:K,headers:{Authorization:`Bearer ${W.key}`,"x-org-id":X.id},expiresAt:Date.now()+aG$*1000}}function eG$($){let{publicUrl:Z,organizationSlug:X,headers:Q,connections:Y}=$,G=new Set;return Y.map((J)=>{let K=AF4(J.slug??J.title??"")||"mcp",W=K;for(let F=2;G.has(W);F++)W=`${K}-${F}`;return G.add(W),{name:W,url:`${Z}/api/${X}/mcp/${encodeURIComponent(J.id)}`,headers:Q}})}function AF4($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function $J$($){return{self:[...$.toolNames],...$.grants}}var aG$=3600,sG$;var vn0=D(()=>{$9();sG$=class sG$ 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 TF4($,Z,X,Q){try{let Y=$.organization;if(!Y)return;let G=await mO0($,Q.virtualMcpId,Y,"tool-scripting"),J=await Z.proxyDaemonRequest(X,"/_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 cy($,Z){let X=await $Q($),Q=null,Y=()=>{if(!Q){if(Q=uy({virtualMcpId:Z.virtualMcpId,branch:Z.branch},$).then((K)=>K.sandboxHandle),Q.catch(()=>{Q=null}),Z.syncTools)Q.then((K)=>TF4($,X,K,{virtualMcpId:Z.virtualMcpId})).catch(()=>{})}return Q},G=Z.branch==="ephemeral";return em0(X,{ensureHandle:Y,invalidateHandle:async(K)=>{if(Q=null,!G&&!K?.force)return;try{await DO($.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 ZJ$($,Z){try{let X=await cy($,Z),{stdout:Q}=await X.onBash("test -d .deco && echo __DECO_SITE__");return Q.includes("__DECO_SITE__")}catch(X){return console.warn("[agent-sandbox-fs] .deco probe failed; assuming deco site",X),!0}}var iO0=D(()=>{ep();vn0();u3();fn();iQ()});import{z as XJ$}from"zod";function ly($){let Z=[];for(let X of $){if(X.status!=="active")continue;let Q=M5(X);if(!Q)continue;Z.push({connectionId:X.id,owner:Q.owner,repo:Q.repo,installationId:Q.installationId})}return Z}async function IF4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return ly(X)}function qF4($){let Z=$.split(`
979
+ `);return y4.from(X)};kK4.decodePax=function(Z){let X={};while(Z.length){let Q=0;while(Q<Z.length&&Z[Q]!==32)Q++;let Y=parseInt(y4.toString(Z.subarray(0,Q)),10);if(!Y)return X;let G=y4.toString(Z.subarray(Q+1,Y-1)),J=G.indexOf("=");if(J===-1)return X;X[G.slice(0,J)]=G.slice(J+1),Z=Z.subarray(Y)}return X};kK4.encode=function(Z){let X=y4.alloc(512),Q=Z.name,Y="";if(Z.typeflag===5&&Q[Q.length-1]!=="/")Q+="/";if(y4.byteLength(Q)!==Q.length)return null;while(y4.byteLength(Q)>100){let G=Q.indexOf("/");if(G===-1)return null;Y+=Y?"/"+Q.slice(0,G):Q.slice(0,G),Q=Q.slice(G+1)}if(y4.byteLength(Q)>100||y4.byteLength(Y)>155)return null;if(Z.linkname&&y4.byteLength(Z.linkname)>100)return null;if(y4.write(X,Q),y4.write(X,CO(Z.mode&4095,6),100),y4.write(X,CO(Z.uid,6),108),y4.write(X,CO(Z.gid,6),116),qK4(Z.size,X,124),y4.write(X,CO(Z.mtime.getTime()/1000|0,11),136),X[156]=48+RK4(Z.type),Z.linkname)y4.write(X,Z.linkname,157);if(y4.copy(RY$,X,257),y4.copy(wK4,X,263),Z.uname)y4.write(X,Z.uname,265);if(Z.gname)y4.write(X,Z.gname,297);if(y4.write(X,CO(Z.devmajor||0,6),329),y4.write(X,CO(Z.devminor||0,6),337),Y)y4.write(X,Y,345);return y4.write(X,CO(qY$(X),6),148),X};kK4.decode=function(Z,X,Q){let Y=Z[156]===0?0:Z[156]-48,G=xy(Z,0,100,X),J=SO(Z,100,8),K=SO(Z,108,8),W=SO(Z,116,8),F=SO(Z,124,12),H=SO(Z,136,12),N=TK4(Y),U=Z[157]===0?null:xy(Z,157,100,X),B=xy(Z,265,32),O=xy(Z,297,32),L=SO(Z,329,8),w=SO(Z,337,8),E=qY$(Z);if(E===256)return null;if(E!==SO(Z,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(zK4(Z)){if(Z[345])G=xy(Z,345,155,X)+"/"+G}else if(PK4(Z));else if(!Q)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:F,mtime:new Date(1000*H),type:N,linkname:U,uname:B,gname:O,devmajor:L,devminor:w,pax:null}};function zK4($){return y4.equals(RY$,$.subarray(257,263))}function PK4($){return y4.equals(EK4,$.subarray(257,263))&&y4.equals(jK4,$.subarray(263,265))}function AK4($,Z,X){if(typeof $!=="number")return X;if($=~~$,$>=Z)return Z;if($>=0)return $;if($+=Z,$>=0)return $;return 0}function TK4($){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 RK4($){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 IY$($,Z,X,Q){for(;X<Q;X++)if($[X]===Z)return X;return Q}function qY$($){let Z=256;for(let X=0;X<148;X++)Z+=$[X];for(let X=156;X<512;X++)Z+=$[X];return Z}function CO($,Z){if($=$.toString(8),$.length>Z)return"7777777777777777777".slice(0,Z)+" ";return"0000000000000000000".slice(0,Z-$.length)+$+" "}function IK4($,Z,X){Z[X]=128;for(let Q=11;Q>0;Q--)Z[X+Q]=$&255,$=Math.floor($/256)}function qK4($,Z,X){if($.toString(8).length>11)IK4($,Z,X);else y4.write(Z,CO($,11),X)}function MK4($){let Z;if($[0]===128)Z=!0;else if($[0]===255)Z=!1;else return null;let X=[],Q;for(Q=$.length-1;Q>0;Q--){let J=$[Q];if(Z)X.push(J);else X.push(255-J)}let Y=0,G=X.length;for(Q=0;Q<G;Q++)Y+=X[Q]*Math.pow(256,Q);return Z?Y:-1*Y}function SO($,Z,X){if($=$.subarray(Z,Z+X),Z=0,$[Z]&128)return MK4($);else{while(Z<$.length&&$[Z]===32)Z++;let Q=AK4(IY$($,32,Z,$.length),$.length,$.length);while(Z<Q&&$[Z]===0)Z++;if(Q===Z)return 0;return parseInt(y4.toString($.subarray(Z,Q)),8)}}function xy($,Z,X,Q){return y4.toString($.subarray(Z,IY$($,0,Z,Z+X)),Q)}function Yn0($){let Z=y4.byteLength($),X=Math.floor(Math.log(Z)/Math.log(10))+1;if(Z+X>=Math.pow(10,X))X++;return Z+X+$}});var fY$=_((hP9,vY$)=>{var{Writable:fK4,Readable:bK4,getStreamError:MY$}=Qn0(),xK4=ap0(),kY$=by(),yy=Gn0(),yK4=kY$.alloc(0);class VY${constructor(){this.buffered=0,this.shifted=0,this.queue=new xK4,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 yK4;let Z=this._next($);if($===Z.byteLength)return Z;let X=[Z];while(($-=Z.byteLength)>0)Z=this._next($),X.push(Z);return kY$.concat(X)}_next($){let Z=this.queue.peek(),X=Z.byteLength-this._offset;if($>=X){let Q=this._offset?Z.subarray(this._offset,Z.byteLength):Z;return this.queue.shift(),this._offset=0,this.buffered-=X,this.shifted+=X,Q}return this.buffered-=$,this.shifted+=$,Z.subarray(this._offset,this._offset+=$)}}class SY$ extends bK4{constructor($,Z,X){super();this.header=Z,this.offset=X,this._parent=$}_read($){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();$(null)}_predestroy(){this._parent.destroy(MY$(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=_Y$(this.header.size),this._parent._update()}_destroy($){this._detach(),$(null)}}class CY$ extends fK4{constructor($){super($);if(!$)$={};this._buffer=new VY$,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=Jn0,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=yy.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=yy.decodeLongPath($,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=yy.decodeLongPath($,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=yy.decodePax($);break;case"pax-header":this._pax=this._paxGlobal===null?yy.decodePax($):Object.assign({},this._paxGlobal,yy.decodePax($));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=_Y$(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 SY$(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=Jn0,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(MY$(this));$(null)}[Symbol.asyncIterator](){let $=null,Z=null,X=null,Q=null,Y=null,G=this;return this.on("entry",W),this.on("error",(N)=>{$=N}),this.on("close",F),{[Symbol.asyncIterator](){return this},next(){return new Promise(K)},return(){return H(null)},throw(N){return H(N)}};function J(N){if(!Y)return;let U=Y;Y=null,U(N)}function K(N,U){if($)return U($);if(Q){N({value:Q,done:!1}),Q=null;return}if(Z=N,X=U,J(null),G._finished&&Z)Z({value:void 0,done:!0}),Z=X=null}function W(N,U,B){if(Y=B,U.on("error",Jn0),Z)Z({value:U,done:!1}),Z=X=null;else Q=U}function F(){if(J($),!Z)return;if($)X($);else Z({value:void 0,done:!0});Z=X=null}function H(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})})})}}}vY$.exports=function(Z){return new CY$(Z)};function Jn0(){}function _Y$($){return $&=511,$&&512-$}});var xY$=_((uP9,Kn0)=>{var bY$={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{Kn0.exports=j0("fs").constants||bY$}catch{Kn0.exports=bY$}});var dY$=_((cP9,lY$)=>{var{Readable:gK4,Writable:hK4,getStreamError:yY$}=Qn0(),JC=by(),gy=xY$(),SO0=Gn0(),gY$=JC.alloc(1024);class hY$ extends hK4{constructor($,Z,X){super({mapWritable:cK4,eagerOpen:!0});if(this.written=0,this.header=Z,this._callback=X,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?JC.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?JC.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);cY$(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 yY$(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy($){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),$()}}class uY$ extends gK4{constructor($){super($);this._drain=Wn0,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry($,Z,X){if(this._finalized||this.destroying)throw Error("already finalized or destroyed");if(typeof Z==="function")X=Z,Z=null;if(!X)X=Wn0;if(!$.size||$.type==="symlink")$.size=0;if(!$.type)$.type=uK4($.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=JC.from(Z);let Q=new hY$(this,$,X);if(JC.isBuffer(Z))return $.size=Z.byteLength,Q.write(Z),Q.end(),Q;if(Q._isVoid)return Q;return Q}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}if(this._finalized)return;this._finalized=!0,this.push(gY$),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=SO0.encode($);if(Z){this.push(Z);return}}this._encodePax($)}_encodePax($){let Z=SO0.encodePax({name:$.name,linkname:$.linkname,pax:$.pax}),X={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(SO0.encode(X)),this.push(Z),cY$(this,Z.byteLength),X.size=$.size,X.type=$.type,this.push(SO0.encode(X))}_doDrain(){let $=this._drain;this._drain=Wn0,$()}_predestroy(){let $=yY$(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(),$()}}lY$.exports=function(Z){return new uY$(Z)};function uK4($){switch($&gy.S_IFMT){case gy.S_IFBLK:return"block-device";case gy.S_IFCHR:return"character-device";case gy.S_IFDIR:return"directory";case gy.S_IFIFO:return"fifo";case gy.S_IFLNK:return"symlink"}return"file"}function Wn0(){}function cY$($,Z){if(Z&=511,Z)$.push(gY$.subarray(0,512-Z))}function cK4($){return JC.isBuffer($)?$:JC.from($)}});var mY$=_((lK4)=>{lK4.extract=fY$();lK4.pack=dY$()});var nY$=_((dP9,pY$)=>{pY$.exports=iY$;function iY$($,Z){if($&&Z)return iY$($)(Z);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(Q){X[Q]=$[Q]}),X;function X(){var Q=Array(arguments.length);for(var Y=0;Y<Q.length;Y++)Q[Y]=arguments[Y];var G=$.apply(this,Q),J=Q[Q.length-1];if(typeof G==="function"&&G!==J)Object.keys(J).forEach(function(K){G[K]=J[K]});return G}}});var Hn0=_((mP9,Fn0)=>{var tY$=nY$();Fn0.exports=tY$(CO0);Fn0.exports.strict=tY$(oY$);CO0.proto=CO0(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return CO0(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return oY$(this)},configurable:!0})});function CO0($){var Z=function(){if(Z.called)return Z.value;return Z.called=!0,Z.value=$.apply(this,arguments)};return Z.called=!1,Z}function oY$($){var Z=function(){if(Z.called)throw Error(Z.onceError);return Z.called=!0,Z.value=$.apply(this,arguments)},X=$.name||"Function wrapped with `once`";return Z.onceError=X+" shouldn't be called more than once",Z.called=!1,Z}});var sY$=_((iP9,aY$)=>{var iK4=Hn0(),pK4=function(){},nK4=global.Bare?queueMicrotask:process.nextTick.bind(process),tK4=function($){return $.setHeader&&typeof $.abort==="function"},oK4=function($){return $.stdio&&Array.isArray($.stdio)&&$.stdio.length===3},rY$=function($,Z,X){if(typeof Z==="function")return rY$($,null,Z);if(!Z)Z={};X=iK4(X||pK4);var{_writableState:Q,_readableState:Y}=$,G=Z.readable||Z.readable!==!1&&$.readable,J=Z.writable||Z.writable!==!1&&$.writable,K=!1,W=function(){if(!$.writable)F()},F=function(){if(J=!1,!G)X.call($)},H=function(){if(G=!1,!J)X.call($)},N=function(w){X.call($,w?Error("exited with error code: "+w):null)},U=function(w){X.call($,w)},B=function(){nK4(O)},O=function(){if(K)return;if(G&&!(Y&&(Y.ended&&!Y.destroyed)))return X.call($,Error("premature close"));if(J&&!(Q&&(Q.ended&&!Q.destroyed)))return X.call($,Error("premature close"))},L=function(){$.req.on("finish",F)};if(tK4($))if($.on("complete",F),$.on("abort",B),$.req)L();else $.on("request",L);else if(J&&!Q)$.on("end",W),$.on("close",W);if(oK4($))$.on("exit",N);if($.on("end",H),$.on("finish",F),Z.error!==!1)$.on("error",U);return $.on("close",B),function(){if(K=!0,$.removeListener("complete",F),$.removeListener("abort",B),$.removeListener("request",L),$.req)$.req.removeListener("finish",F);$.removeListener("end",W),$.removeListener("close",W),$.removeListener("finish",F),$.removeListener("exit",N),$.removeListener("end",H),$.removeListener("error",U),$.removeListener("close",B)}};aY$.exports=rY$});var ZG$=_((pP9,$G$)=>{var rK4=Hn0(),aK4=sY$(),_O0;try{_O0=j0("fs")}catch($){}var kn=function(){},sK4=typeof process>"u"?!1:/^v?\.0/.test(process.version),vO0=function($){return typeof $==="function"},eK4=function($){if(!sK4)return!1;if(!_O0)return!1;return($ instanceof(_O0.ReadStream||kn)||$ instanceof(_O0.WriteStream||kn))&&vO0($.close)},$W4=function($){return $.setHeader&&vO0($.abort)},ZW4=function($,Z,X,Q){Q=rK4(Q);var Y=!1;$.on("close",function(){Y=!0}),aK4($,{readable:Z,writable:X},function(J){if(J)return Q(J);Y=!0,Q()});var G=!1;return function(J){if(Y)return;if(G)return;if(G=!0,eK4($))return $.close(kn);if($W4($))return $.abort();if(vO0($.destroy))return $.destroy();Q(J||Error("stream was destroyed"))}},eY$=function($){$()},XW4=function($,Z){return $.pipe(Z)},QW4=function(){var $=Array.prototype.slice.call(arguments),Z=vO0($[$.length-1]||kn)&&$.pop()||kn;if(Array.isArray($[0]))$=$[0];if($.length<2)throw Error("pump requires two streams per minimum");var X,Q=$.map(function(Y,G){var J=G<$.length-1,K=G>0;return ZW4(Y,J,K,function(W){if(!X)X=W;if(W)Q.forEach(eY$);if(J)return;Q.forEach(eY$),Z(X)})});return $.reduce(XW4)};$G$.exports=QW4});var HG$=_((KW4)=>{var XG$=mY$(),QG$=ZG$(),YG$=j0("fs"),K9=j0("path"),Vn=(global.Bare?global.Bare.platform:process.platform)==="win32";KW4.pack=function(Z,X){if(!Z)Z=".";if(!X)X={};let Q=X.fs||YG$,Y=X.ignore||X.filter||Sn,G=X.mapStream||WG$,J=JW4(Q,X.dereference?Q.stat:Q.lstat,Z,Y,X.entries,X.sort),K=X.strict!==!1,W=typeof X.umask==="number"?~X.umask:~GG$(),F=X.pack||XG$.pack(),H=X.finish||Sn,N=X.map||Sn,U=typeof X.dmode==="number"?X.dmode:0,B=typeof X.fmode==="number"?X.fmode:0;if(X.strip)N=FG$(N,X.strip);if(X.readable)U|=parseInt(555,8),B|=parseInt(444,8);if(X.writable)U|=parseInt(333,8),B|=parseInt(222,8);w();function O(E,j){Q.readlink(K9.join(Z,E),function(z,A){if(z)return F.destroy(z);j.linkname=Nn0(A),F.entry(j,w)})}function L(E,j,z){if(F.destroyed)return;if(E)return F.destroy(E);if(!j){if(X.finalize!==!1)F.finalize();return H(F)}if(z.isSocket())return w();let A={name:Nn0(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,F.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 F.destroy(Error("unsupported type for "+j));return w()}let P=F.entry(A,w),I=G(Q.createReadStream(K9.join(Z,j),{start:0,end:A.size>0?A.size-1:A.size}),A);I.on("error",function(q){P.destroy(q)}),QG$(I,P)}function w(E){if(E)return F.destroy(E);J(L)}return F};function YW4($){return $.length?$[$.length-1]:null}function GW4(){return!global.Bare&&process.getuid?process.getuid():-1}function GG$(){return!global.Bare&&process.umask?process.umask():0}KW4.extract=function(Z,X){if(!Z)Z=".";if(!X)X={};Z=K9.resolve(Z);let Q=X.fs||YG$,Y=X.ignore||X.filter||Sn,G=X.mapStream||WG$,J=X.chown!==!1&&!Vn&&GW4()===0,K=X.extract||XG$.extract(),W=[],F=new Date,H=typeof X.umask==="number"?~X.umask:~GG$(),N=X.strict!==!1,U=X.validateSymlinks!==!1,B=X.map||Sn,O=typeof X.dmode==="number"?X.dmode:0,L=typeof X.fmode==="number"?X.fmode:0;if(X.strip)B=FG$(B,X.strip);if(X.readable)O|=parseInt(555,8),L|=parseInt(444,8);if(X.writable)O|=parseInt(333,8),L|=parseInt(222,8);if(K.on("entry",w),X.finish)K.on("finish",X.finish);return K;function w(P,I,q){P=B(P)||P,P.name=Nn0(P.name);let k=K9.join(Z,K9.join("/",P.name));if(Y(k,P))return I.resume(),q();let S=K9.join(k,".")===K9.join(Z,".")?Z:K9.dirname(k);KG$(Q,S,K9.join(Z,"."),function(o,U0){if(o)return q(o);if(!U0)return q(Error(S+" is not a valid path"));if(P.type==="directory")return W.push([k,P.mtime]),A(k,{fs:Q,own:J,uid:P.uid,gid:P.gid,mode:P.mode},m);A(S,{fs:Q,own:J,uid:P.uid,gid:P.gid,mode:493},function(E0){if(E0)return q(E0);switch(P.type){case"file":return u();case"link":return b();case"symlink":return f()}if(N)return q(Error("unsupported type for "+k+" ("+P.type+")"));I.resume(),q()})});function m(o){if(o)return q(o);j(k,P,function(U0){if(U0)return q(U0);if(Vn)return q();z(k,P,q)})}function f(){if(Vn)return q();Q.unlink(k,function(){let o=K9.resolve(K9.dirname(k),P.linkname);if(!i(o)&&U)return q(Error(k+" is not a valid symlink"));JG$(Q,o,K9.join(Z,"."),function(U0,E0){if(U0)return q(U0);if(!E0&&U)return q(Error(k+" is not a valid symlink"));Q.symlink(P.linkname,k,m)})})}function b(){if(Vn)return q();Q.unlink(k,function(){let o=K9.join(Z,K9.join("/",P.linkname));Q.realpath(o,function(U0,E0){if(U0||!i(E0))return q(Error(k+" is not a valid hardlink"));Q.link(E0,k,function(s){if(s&&s.code==="EPERM"&&X.hardlinkAsFilesFallback)return I=Q.createReadStream(E0),u();m(s)})})})}function i(o){return o===Z||o.startsWith(Z+K9.sep)}function u(){let o=Q.createWriteStream(k),U0=G(I,P);o.on("error",function(E0){U0.destroy(E0)}),QG$(U0,o,function(E0){if(E0)return q(E0);o.on("close",m)})}}function E(P,I){let q;while((q=YW4(W))&&P.slice(0,q[0].length)!==q[0])W.pop();if(!q)return I();Q.utimes(q[0],F,q[1],I)}function j(P,I,q){if(X.utimes===!1)return q();if(I.type==="directory")return Q.utimes(P,F,I.mtime,q);if(I.type==="symlink")return E(P,q);Q.utimes(P,F,I.mtime,function(k){if(k)return q(k);E(P,q)})}function z(P,I,q){let k=I.type==="symlink",S=k?Q.lchmod:Q.chmod,m=k?Q.lchown:Q.chown;if(!S)return q();let f=(I.mode|(I.type==="directory"?O:L))&H;if(m&&J)m.call(Q,P,I.uid,I.gid,b);else b(null);function b(i){if(i)return q(i);if(!S)return q();S.call(Q,P,f,q)}}function A(P,I,q){Q.stat(P,function(k){if(!k)return q(null);if(k.code!=="ENOENT")return q(k);Q.mkdir(P,{mode:I.mode,recursive:!0},function(S,m){if(S)return q(S);z(P,I,q)})})}};function JG$($,Z,X,Q){if(Z===X)return Q(null,!0);if(!Z.startsWith(X+K9.sep))return Q(null,!1);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return Q(Y);if(Y||!G.isSymbolicLink())return JG$($,K9.join(Z,".."),X,Q);Q(null,!1)})}function KG$($,Z,X,Q){if(Z===X)return Q(null,!0);$.lstat(Z,function(Y,G){if(Y&&Y.code!=="ENOENT"&&Y.code!=="EPERM")return Q(Y);if(Y||G.isDirectory())return KG$($,K9.join(Z,".."),X,Q);Q(null,!1)})}function Sn(){}function WG$($){return $}function Nn0($){return Vn?$.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):$}function JW4($,Z,X,Q,Y,G){if(!Y)Y=["."];let J=Y.slice(0);return function(W){if(!J.length)return W(null);let F=J.shift(),H=K9.join(X,F);Z.call($,H,function(N,U){if(N)return W(Y.indexOf(F)===-1&&N.code==="ENOENT"?null:N);if(!U.isDirectory())return W(null,F,U);$.readdir(H,function(B,O){if(B)return W(B);if(G)O.sort();for(let L=0;L<O.length;L++)if(!Q(K9.join(X,F,O[L])))J.push(K9.join(F,O[L]));W(null,F,U)})})}}function FG$($,Z){return function(X){X.name=X.name.split("/").slice(Z).join("/");let Q=X.linkname;if(Q&&(X.type==="link"||K9.isAbsolute(Q)))X.linkname=Q.split("/").slice(Z).join("/");return $(X)}}});var HW4,NW4;var NG$=D(()=>{op0();HW4=V(sQ$(),1),NW4=V(HG$(),1)});var fO0=()=>{};var UG$=D(()=>{nB0()});var BG$=D(()=>{PO0();zO0();fO0()});var OG$=()=>{};var DG$=()=>{};var LG$=D(()=>{vQ$();np0();PO0();gQ$();ip0();op0();hQ$();uQ$();cQ$();lQ$();pp0();dQ$();NG$();fO0();UG$();BG$();OG$();DG$();fO0()});var bO0=D(()=>{K4();rm0()});async function yO0($){try{let Z=await fetch(`${$}/health`,{signal:AbortSignal.timeout(UW4)});if(!Z.ok)return null;let X=await Z.json();if(typeof X==="object"&&X!==null&&typeof X.bootId==="string"&&typeof X.ready==="boolean"&&X.setup&&typeof X.setup.running==="boolean"&&typeof X.setup.done==="boolean")return X;return null}catch{return null}}async function Bn0($){for(let Z=0;Z<wG$;Z++){if(await yO0($)!==null)return;let X=(Math.random()*2-1)*BW4;await L$(EG$+X)}throw Error(`sandbox daemon at ${$} did not respond on /health within ${wG$*EG$/1000}s`)}async function KC($,Z,X,Q,Y){return OW4($,Z,"POST",X,Q,Y)}async function OW4($,Z,X,Q,Y,G){let J={...Q};if(Y&&Y.rotateToken!==void 0)J.auth=Y;let K=await fetch(`${$}/_sandbox/config`,{method:X,headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify(J),signal:AbortSignal.timeout(G?.timeoutMs??Un0)}),W=await K.text();if(!K.ok)throw new xO0(K.status,W);return JSON.parse(W)}async function jG$($,Z,X){let Q=await fetch(`${$}/_sandbox/setup/${X}`,{method:"POST",headers:{Authorization:`Bearer ${Z}`},signal:AbortSignal.timeout(Un0)});if(!Q.ok)throw Error(`sandbox daemon /_sandbox/setup/${X} returned ${Q.status}: ${await Q.text()}`)}async function zG$($,Z,X){let Q=await fetch(`${$}/_sandbox/orgfs-config`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:X,signal:AbortSignal.timeout(Un0)}),Y=await Q.text();if(!Q.ok)throw Error(`sandbox daemon /_sandbox/orgfs-config returned ${Q.status}: ${Y}`);return JSON.parse(Y)}async function Cn($,Z,X,Q){let Y=new Headers(Q.headers);for(let K of DW4)Y.delete(K);Y.set("authorization",`Bearer ${Z}`);let G=Q.method!=="GET"&&Q.method!=="HEAD",J=`${$}${X.startsWith("/")?X:`/${X}`}`;return fetch(J,{method:Q.method,headers:Y,body:G?Q.body:void 0,redirect:"manual",signal:Q.signal,duplex:G?"half":void 0})}var xO0,UW4=500,Un0=30000,wG$=25,EG$=200,BW4=50,DW4;var PG$=D(()=>{bO0();xO0=class xO0 extends Error{status;constructor($,Z){super(`sandbox daemon /_sandbox/config returned ${$}: ${Z}`);this.status=$;this.name="ConfigRequestError"}};DW4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length"]});async function*RG$($){let Z=$.now??(()=>Date.now()),X=Z(),Q=$.schedulingTimeoutMs??wW4,Y={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:X},G=[],J=null,K=!1,W=(j)=>{if(K)return;if(J){let z=J;J=null,z(j)}else G.push(j)},F=()=>{if(G.length>0)return Promise.resolve(G.shift());if(K)return Promise.resolve(null);return new Promise((j)=>{J=j})},H=()=>{if(K)return;if(K=!0,J){let j=J;J=null,j(null)}},N=new AbortController,U=()=>{N.abort(),H()};if($.signal)if($.signal.aborted)N.abort(),H();else $.signal.addEventListener("abort",U,{once:!0});let B=Math.max(0,Q-(Z()-X)),O=setTimeout(()=>W("tick"),B+100),L,w=new Promise((j)=>{L=j}),E=Promise.allSettled([EW4($.kc,$.namespace,$.claimName,N.signal,Y,W,Z,L),zW4($.kc,$.namespace,$.claimName,N.signal,Y,W),PW4($.kc,$.namespace,$.claimName,w,N.signal,Y,W,Z)]);try{let j=null,z=-1,A=AG$(Y,Q,Z);if(j=Dn0(A),!On0(A))z=TG$(A);if(yield A,On0(A))return;while(!K){if(await F()===null)break;let I=AG$(Y,Q,Z);if(On0(I)){let S=Dn0(I);if(S!==j)j=S,yield I;return}let q=TG$(I);if(q<z)continue;let k=Dn0(I);if(k!==j)j=k,z=q,yield I}}finally{if(clearTimeout(O),N.abort(),$.signal)$.signal.removeEventListener("abort",U);H(),await E.catch(()=>{})}}function AG$($,Z,X){let{pod:Q,sandbox:Y,events:G,startedAt:J}=$;if(Y.ready)return{kind:"ready"};let K=Q.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(!Q.scheduled&&G.lastFailedSchedulingAt!==void 0&&X()-J>Z)return{kind:"failed",reason:"scheduling-timeout",message:G.failedSchedulingMessage??`Pod could not be scheduled within ${Math.round(Z/1000)}s.`};if(Q.containerRunning&&!Q.containerReady)return{kind:"warming-daemon",since:J};if(G.hasPulling&&!G.hasPulled)return{kind:"pulling-image",since:J};if(K==="ContainerCreating"||K==="PodInitializing"||Q.scheduled&&!Q.containerRunning)return{kind:"starting-container",since:J};if(Q.scheduledFalseReason==="Unschedulable"||G.lastFailedSchedulingAt!==void 0&&!Q.scheduled)return{kind:"waiting-for-capacity",since:J,message:G.failedSchedulingMessage??Q.scheduledFalseMessage,nodeClaim:G.nominatedNodeClaim};return{kind:"claiming",since:J}}function On0($){return $.kind==="ready"||$.kind==="failed"}function TG$($){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 Dn0($){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 EW4($,Z,X,Q,Y,G,J,K){let W=`/api/v1/namespaces/${encodeURIComponent(Z)}/pods?watch=true&labelSelector=${encodeURIComponent(`${LW4}=${X}`)}`;return gO0({kc:$,path:W,signal:Q,label:`pod/${X}`,onEvent:(F)=>{if(F.type!=="ADDED"&&F.type!=="MODIFIED")return;let H=F.object;if(H.metadata?.name)K(H.metadata.name);jW4(H,Y,J),G("pod")}})}function jW4($,Z,X){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===J9.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 zW4($,Z,X,Q,Y,G){let J=`/apis/${J9.CLAIM_API_GROUP}/${J9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(Z)}/${J9.CLAIM_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${X}`)}`;return gO0({kc:$,path:J,signal:Q,label:`sandboxclaim/${X}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let F=K.object.status?.conditions?.find((H)=>H.type==="Ready");if(!F)return;if(F.status==="True")Y.sandbox.ready=!0,Y.sandbox.notReadyReason=void 0,Y.sandbox.notReadyMessage=void 0;else Y.sandbox.ready=!1,Y.sandbox.notReadyReason=F.reason,Y.sandbox.notReadyMessage=F.message;G("sandbox")}})}async function PW4($,Z,X,Q,Y,G,J,K){let W=await Promise.race([Q,new Promise((H)=>{if(Y.aborted){H(X);return}Y.addEventListener("abort",()=>H(X),{once:!0})})]);if(Y.aborted)return;let F=`/api/v1/namespaces/${encodeURIComponent(Z)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${W},involvedObject.kind=Pod`)}`;return gO0({kc:$,path:F,signal:Y,label:`events/${X}`,onEvent:(H)=>{if(H.type!=="ADDED"&&H.type!=="MODIFIED")return;let N=H.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 IG$($){let{kc:Z,namespace:X,labelSelector:Q,signal:Y,onDelete:G}=$,J=`/apis/${J9.CLAIM_API_GROUP}/${J9.CLAIM_API_VERSION}/namespaces/${encodeURIComponent(X)}/${J9.CLAIM_PLURAL}?watch=true&labelSelector=${encodeURIComponent(Q)}`;return gO0({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 gO0($){let{kc:Z,path:X,signal:Q,label:Y,onEvent:G}=$,J=0;while(!Q.aborted){try{let W=await pY(Z,{method:"GET",path:X,signal:Q,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 F of ji0(W.body)){if(Q.aborted)return;try{G(F)}catch(H){console.warn(`[lifecycle-watcher] ${Y} onEvent threw: ${H instanceof Error?H.message:String(H)}`)}}}catch(W){if(Q.aborted)return;let F=W instanceof Error?W.message:String(W);console.warn(`[lifecycle-watcher] ${Y} watch ended: ${F}`)}if(Q.aborted)return;let K=aZ(5000,250,J,2,0);J+=1,await L$(K,{signal:Q}).catch(()=>{})}}var LW4="studio.decocms.com/sandbox-handle",wW4=300000;var qG$=D(()=>{K4();O70();E70()});import{z as QJ}from"zod";function MG$($){if(!$||$.trim()==="")return[];let Z=QJ.array(AW4).parse(JSON.parse($)),X=new Set;for(let Q of Z){if(X.has(Q.name))throw Error(`STUDIO_SANDBOX_TENANT_POOLS: duplicate pool name ${Q.name}`);X.add(Q.name)}return Z}function TW4($){try{let[Z,X]=new URL($).pathname.replace(/^\/+/,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?`${Z}/${Q}`.toLowerCase():null}catch{return null}}function kG$($,Z){let{orgId:X,cloneUrl:Q}=Z;if(Z.purpose==="harness-run")return null;if(!X||!Q)return null;let Y=TW4(Q);if(!Y)return null;return $.find((G)=>G.orgId===X&&G.repo.toLowerCase()===Y)??null}function VG$($,Z,X){return $?.name??(Z?X:"none")}function RW4($,Z){return $==="harness-run"?`${Z}-medium`:Z}async function SG$($){let Z=RW4($.purpose,$.templateName);if(Z===$.templateName)return{name:Z,probe:$.probe};let X=$.probe!==null&&$.now-$.probe.checkedAt<$.ttlMs?$.probe:{checkedAt:$.now,present:await $.exists(Z)};if(X.present)return{name:Z,probe:X};if($.probe?.present!==!1)$.onAbsent?.(Z);return{name:$.templateName,probe:X}}function CG$($,Z,X){let Q=X.replace(/^refs\/heads\//,"");return $.filter((Y)=>Y.repo.toLowerCase()===Z.toLowerCase()&&Y.branch===Q)}function _G$($){return`https://github.com/${$.repo}.git`}var AW4;var Ln0=D(()=>{AW4=QJ.object({name:QJ.string().regex(/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/,"pool name must be a DNS label (lowercase alphanumeric and '-')"),orgId:QJ.string().min(1),repo:QJ.string().regex(/^[^/\s]+\/[^/\s]+$/,"repo must be `owner/name`"),connectionId:QJ.string().min(1).optional(),branch:QJ.string().min(1).default("main"),workload:QJ.object({runtime:QJ.enum(["node","bun","deno"]).default("node"),packageManager:QJ.enum(["npm","pnpm","yarn","bun","deno"]).optional(),packageManagerPath:QJ.string().optional(),devPort:QJ.number().int().positive().optional()}).default({runtime:"node"})})});async function vG$($,Z,X){let Q=new Map;for(let Y of $){let G=Z(Y);if(!G)continue;let J=Q.get(G);if(J)J.push(Y);else Q.set(G,[Y])}await Promise.allSettled([...Q.values()].map(async(Y)=>{for(let G of Y)await X(G).catch(()=>{})}))}import{createHash as IW4,randomBytes as qW4,randomUUID as MW4}from"crypto";import*as uG$ from"net";import{PassThrough as kW4}from"stream";function fG$($){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 Tn0{records=new Map;inflight=new rZ0;activeGauge=new oZ0;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??lW4(),this.portForward=new rp0(this.kubeConfig),this.namespace=$.namespace??VW4,this.sandboxTemplateName=$.sandboxTemplateName??SW4,this.envName=tW4($.envName),this.tokenGenerator=$.tokenGenerator??(()=>qW4(_W4).toString("hex")),this.idleTtlMs=$.idleTtlMs??fW4,this.metrics=$.meter?cW4($.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(`[${K6}] tenant pools configured without a sentinel token \u2014 ignoring them (warm-pool mode is off)`);this.tenantPoolRefreshMs=$.tenantPoolRefreshMs??xW4,this.startClaimReaper(),this.startCredentialRefresher(),this.startTenantPoolReconciler()}startClaimReaper(){let $=["app.kubernetes.io/managed-by=studio","app.kubernetes.io/name=studio-sandbox",...this.envName?[`${eX.env}=${this.envName}`]:[]].join(",");IG$({kc:this.kubeConfig,namespace:this.namespace,labelSelector:$,signal:this.claimWatchAbort.signal,onDelete:(Z)=>this.invalidateRecord(Z)})}async ensure($,Z={}){let X=SE($);if(X.startsWith("s-"))throw Error(`ensure: projectRef has no slug source: ${$.projectRef}`);return this.inflight.run(X,()=>aZ0(this.stateStore,$,(Q)=>this.ensureLocked($,X,Z,Q)))}async delete($){let Z=await this.getRecord($);if(this.records.delete($),Z)this.dropRecord(Z);if(await this.deleteHttpRouteIfManaged($).catch((X)=>{console.warn(`[${K6}] HTTPRoute delete failed for ${$}: ${X instanceof Error?X.message:String(X)}`)}),await Ry(this.kubeConfig,this.namespace,$),this.stateStore)if(Z)await this.stateStore.delete(Z.id);else await this.stateStore.deleteByHandle($)}lastTermination($){return v5$(this.kubeConfig,this.namespace,eX.sandboxHandle,$,J9.MAIN_CONTAINER_NAME)}async alive($){return await hH(this.kubeConfig,this.namespace,$)!==void 0}watchClaimLifecycle($,Z){return RG$({kc:this.kubeConfig,namespace:this.namespace,claimName:$,signal:Z})}hasSchedulableCapacity(){return this.capacityProbe??=m5$(this.kubeConfig,this.namespace),this.capacityProbe()}async getPreviewUrl($){let Z=await this.getRecord($);if(!Z)return null;return this.composePreviewUrl(Z)}async proxyDaemonRequest($,Z,X){let Q=await this.getRecord($);if(!Q&&this.previewUrlPattern&&this.stateStore){let W=await this.stateStore.getByHandle($),F=W?.state,H=F?.token;if(W&&H){let U=`http://${F?.adoptedSandboxName??$}.${this.namespace}.svc.cluster.local:${pH}`;try{let B=await Cn(U,H,Z,X);if(B.status!==404)return B;try{await B.body?.cancel()}catch{}}catch{}}}if(!Q)Q=await this.resurrectByHandle($);if(!Q)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let Y=Q,G=performance.now(),J=0,K=!(X.body instanceof ReadableStream);try{let W=await Cn(Q.daemonUrl,Q.token,Z,X);if(W.status===401&&K){this.invalidateRecord($);let F=await this.getRecord($).catch(()=>null)??await this.resurrectByHandle($).catch(()=>null);if(F){try{await W.body?.cancel()}catch{}Y=F,W=await Cn(F.daemonUrl,F.token,Z,X)}}return J=W.status,W}catch(W){if(!K)throw W;this.invalidateRecord($);let F=await this.resurrectByHandle($)??await this.getRecord($).catch(()=>null);if(!F)throw W;Y=F;let H=await Cn(F.daemonUrl,F.token,Z,X);return J=H.status,H}finally{this.recordProxyDuration("daemon",J,Y,performance.now()-G)}}async adoptLiveClaim($,Z){if(this.records.has(Z))return!0;let X=await hH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!X||X.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,X);if(!G)throw Error(`cannot adopt live claim ${Z}`);return aZ0(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:${pH}`;let Z=await this.getRecord($);if(Z)return Z.daemonUrl;let X=await this.resurrectByHandle($);return X?X.daemonUrl:null}async resolveServiceNameForHandle($){let Z=this.records.get($);if(Z)return Z.adoptedSandboxName;if(this.stateStore){let Q=(await this.stateStore.getByHandle($).catch(()=>null))?.state?.adoptedSandboxName;if(Q)return Q}return $}async proxyPreviewRequest($,Z){let X=performance.now(),Q=this.records.get($)??null,Y=0;try{let G=await this.resolvePreviewUpstreamUrl($);if(!G){Y=404;let O=En0(404,{error:"sandbox not found"});return O.headers.set(FC,"1"),O}let J=new URL(Z.url);if((J.pathname==="/_sandbox"||J.pathname.startsWith("/_sandbox/"))&&Z.method!=="GET")return Y=404,En0(404,{error:"not found"});let W=(O)=>`${O}${J.pathname}${J.search}`,F=new Headers(Z.headers);for(let O of hW4)F.delete(O);let H=Z.method!=="GET"&&Z.method!=="HEAD",N={method:Z.method,headers:F,body:H?Z.body:void 0,redirect:"manual",signal:Z.signal,duplex:H?"half":void 0},U;try{U=await fetch(W(G),N)}catch(O){let L=`${G}${J.pathname}`;if(console.warn(`[${K6}] preview fetch to ${L} 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(!yG$.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(`[${K6}] preview fetch retry to ${L} failed: ${z instanceof Error?z.message:String(z)}`)}}}else this.invalidateRecord($);Y=502;let w=En0(502,{error:"sandbox daemon unreachable"});return w.headers.set(FC,"1"),w}let B=new Headers;for(let[O,L]of U.headers.entries())if(!yG$.includes(O.toLowerCase()))B.set(O,L);return Y=U.status,new Response(U.body,{status:U.status,statusText:U.statusText,headers:B})}finally{this.recordProxyDuration("preview",Y,Q,performance.now()-X,$)}}async ensureLocked($,Z,X,Q){if(X.image)console.warn(`[${K6}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${X.image}`);if(Q){let J=await Q.get($);if(J){let K=await this.rehydrate($,Z,J);if(K)return await this.refreshDaemonGitCredential(K,X),await this.relayOrgFsConfig(K.daemonUrl,K.token,X.orgFsConfigJson),this.finish(K,Q,!1,!0,"resume");await Q.delete($)}}let Y=await hH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(Y)if(Y.metadata?.deletionTimestamp)await L70(this.kubeConfig,this.namespace,Z).catch((J)=>{console.warn(`[${K6}] 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(`[${K6}] adopt ${Z} failed, recreating: ${K instanceof Error?K.message:String(K)}`),null});if(J)return await this.refreshDaemonGitCredential(J,X),await this.relayOrgFsConfig(J.daemonUrl,J.token,X.orgFsConfigJson),this.finish(J,Q,!0,!0,"adopt");await Ry(this.kubeConfig,this.namespace,Z).catch(()=>{}),await L70(this.kubeConfig,this.namespace,Z).catch((K)=>{console.warn(`[${K6}] wait for deleted claim ${Z} failed: ${K instanceof Error?K.message:String(K)}`)})}let G=await this.provision($,Z,X);return this.finish(G,Q,!0,!1,"fresh")}async finish($,Z,X,Q,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,$),X)await this.persist(Z,$);if(Q)await w70(this.kubeConfig,this.namespace,$.handle,this.computeShutdownTime()).catch((K)=>console.warn(`[${K6}] TTL refresh failed for ${$.handle}: ${K instanceof Error?K.message:String(K)}`));if(this.metrics){let K=zn0($.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 X={},Q=[];for(let[Y,G]of Object.entries($.env??{}))if(vW4.has(Y))Q.push(Y);else X[Y]=G;if(Q.length>0)console.warn(`[${K6}] opts.env keys overlap reserved bootstrap names and were dropped: ${Q.join(",")}`);return{...X,DAEMON_TOKEN:Z.token,DAEMON_BOOT_ID:Z.daemonBootId,APP_ROOT:Z.workdir,PROXY_PORT:String(pH)}}async resolveTemplateName($){let{name:Z,probe:X}=await SG$({purpose:$,templateName:this.sandboxTemplateName,probe:this.mediumTemplateProbe,now:Date.now(),ttlMs:CW4,exists:(Q)=>V5$(this.kubeConfig,this.namespace,Q),onAbsent:(Q)=>console.warn(`[${K6}] SandboxTemplate ${Q} 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=X,Z}buildClaim($,Z,X,Q){let Y=this.sentinelToken!==null,G=kG$(this.tenantPools,{orgId:Z.tenant?.orgId,cloneUrl:Z.repo?.cloneUrl,purpose:Z.purpose}),J=Y?[]:Object.entries(this.buildEnvMap(Z,X)).sort(([F],[H])=>F<H?-1:F>H?1:0).map(([F,H])=>({name:F,value:H})),K=aW4(Z),W=Object.keys(K).length>0;return{apiVersion:`${J9.CLAIM_API_GROUP}/${J9.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?{[eX.env]:this.envName}:{},...jn0(Z.tenant)},...W?{annotations:K}:{}},spec:{sandboxTemplateRef:{name:Q},additionalPodMetadata:{labels:jn0(Z.tenant,{[eX.role]:"claimed",[eX.sandboxHandle]:$,...this.envName?{[eX.env]:this.envName}:{}}),...W?{annotations:K}:{}},env:J,warmpool:VG$(G,Y,Q),lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision($,Z,X){let Q=this.tokenGenerator(),Y=MW4(),G=wn0,J=this.buildClaim(Z,X,{token:Q,daemonBootId:Y,workdir:G},await this.resolveTemplateName(X.purpose));try{await Li0(this.kubeConfig,this.namespace,J)}catch(U){if(U instanceof Hn)await L70(this.kubeConfig,this.namespace,Z),await Li0(this.kubeConfig,this.namespace,J);else throw U}let K;try{K=await S5$(this.kubeConfig,this.namespace,Z),await l5$(this.kubeConfig,this.namespace,K)}catch(U){throw await Ry(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}try{await this.ensureServicePortForAdoptedSandbox(K),await this.ensureHttpRouteForHandle(Z,K,X.tenant??null)}catch(U){throw await Ry(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}let W=await this.openForwarder(K,pH,Z),F=`http://127.0.0.1:${W.localPort}`,H=this.workloadConfigPayload(X),N=Y;try{if(await Bn0(F),this.sentinelToken!==null){let U=await yO0(F);if(U)N=U.bootId;await KC(F,this.sentinelToken,H??{},{rotateToken:Q})}else if(H)await KC(F,Q,H);await this.relayOrgFsConfig(F,Q,X.orgFsConfigJson)}catch(U){throw this.closeForwarder(W),await this.deleteHttpRouteIfManaged(Z).catch(()=>{}),await Ry(this.kubeConfig,this.namespace,Z).catch(()=>{}),U}return{id:$,handle:Z,adoptedSandboxName:K,token:Q,workdir:G,daemonUrl:F,daemonForward:W,workload:X.workload??null,daemonBootId:N,tenant:X.tenant??null,ensureOpts:XF4(X)}}workloadConfigPayload($){return eZ0({runtime:$?.workload?.runtime??"node",packageManager:$?.workload?.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:$?.repo??null,extraRepos:$?.extraRepos??[],port:$?.workload?.devPort??bG$,tenant:$?.tenant??void 0,...$?{cloneOnly:$.cloneOnly===!0}:{}})}async relayOrgFsConfig($,Z,X){if(!X)return;await zG$($,Z,X).catch((Q)=>console.warn("[org-fs] sidecar config relay failed",Q))}async refreshDaemonGitCredential($,Z){let X=am0(Z);if(!X)return;try{await KC($.daemonUrl,$.token,X)}catch(Q){console.warn(`[${K6}] git credential refresh failed for ${$.handle}: ${Q instanceof Error?Q.message:String(Q)}`)}}async withFreshCloneUrl($,Z){if(!this.mintCloneUrl)return $;try{let X=await this.mintCloneUrl($,Z!==void 0?{bufferMs:Z}:void 0);return X?{...$,cloneUrl:X}:$}catch(X){return console.warn(`[${K6}] clone credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$}}async withFreshCredentials($){return{...$,...$.repo?{repo:await this.withFreshCloneUrl($.repo)}:{},...$.orgFsConfigJson?{orgFsConfigJson:await ZF4($,this.mintOrgFsConfig)}:{}}}startCredentialRefresher(){if(!this.mintCloneUrl)return;let{signal:$}=this.claimWatchAbort;(async()=>{while(!$.aborted){if(await L$(yW4,{signal:$}).catch(()=>{}),$.aborted)break;try{await this.refreshAllGitCredentials()}catch(Z){console.warn(`[${K6}] 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(`[${K6}] tenant pool reconcile failed: ${Z instanceof Error?Z.message:String(Z)}`)}await L$(bW4,{signal:$}).catch(()=>{})}})()}markTenantPoolsDirty($,Z){let X=CG$(this.tenantPools,$,Z);for(let Q of X)this.dirtyPools.add(Q.name);return X.map((Q)=>Q.name)}async reconcileTenantPools(){for(let $ of this.tenantPools){let Z=await C5$(this.kubeConfig,this.namespace,$.name);if(Z===null){console.warn(`[${K6}] tenant pool ${$.name}: no SandboxWarmPool (or no selector yet) in ${this.namespace}`);continue}let X=this.dirtyPools.delete($.name),Q=Z.filter((Y)=>!Y.labels[eX.sandboxHandle]);for(let[Y]of this.poolPods)if(!Z.some((G)=>G.uid===Y))this.poolPods.delete(Y);for(let Y of Q){if(this.claimWatchAbort.signal.aborted)return;await this.warmPoolPod($,Y,X)}this.recordPoolDepth($,Z,Q)}}recordPoolDepth($,Z,X){let Q=this.metrics?.poolPods;if(!Q)return;let Y=0,G=0;for(let K of X){let W=this.poolPods.get(K.uid);if(!W)continue;if(W.failures>=hO0)G++;else if(W.lastConfigAt>0)Y++}let J={pool:$.name,org:$.orgId};Q.record(Y,{...J,state:"ready"}),Q.record(Z.length-X.length,{...J,state:"bound"}),Q.record(X.length-Y-G,{...J,state:"pending"}),Q.record(G,{...J,state:"failed"})}async warmPoolPod($,Z,X){let Q=this.poolPods.get(Z.uid);if(Q&&Q.failures>=hO0){if(Date.now()-Q.lastFailureAt<xG$)return;this.poolPods.set(Z.uid,{...Q,failures:0})}let Y=X||Q!==void 0&&Date.now()-Q.lastConfigAt>=this.tenantPoolRefreshMs;if(Q&&!Y)return;let G={cloneUrl:_G$($),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,pH,Z.name).catch(()=>null);if(!K){this.recordPoolFailure(Z,$,"port-forward failed");return}let W=`http://127.0.0.1:${K.localPort}`;try{await Bn0(W);let F=this.sentinelToken;if(!F)return;if(!await this.isPoolPodUnbound(Z))return;let H=eZ0({runtime:$.workload.runtime,packageManager:$.workload.packageManager?{name:$.workload.packageManager,...$.workload.packageManagerPath?{path:$.workload.packageManagerPath}:{}}:null,repo:J,port:$.workload.devPort??bG$})??{},{transition:N}=await KC(W,F,H);if(Y&&N!=="bootstrap"&&await this.isPoolPodUnbound(Z))await jG$(W,F,"clone");this.poolPods.set(Z.uid,{lastConfigAt:Date.now(),lastFailureAt:0,failures:0}),console.log(`[${K6}] tenant pool ${$.name}: warmed ${Z.name} (${N})`)}catch(F){this.recordPoolFailure(Z,$,F instanceof Error?F.message:String(F))}finally{this.closeForwarder(K)}}isPoolPodUnbound($){return _5$(this.kubeConfig,this.namespace,$.name,eX.sandboxHandle)}recordPoolFailure($,Z,X){let Q=this.poolPods.get($.uid),Y=(Q?.failures??0)+1;this.poolPods.set($.uid,{lastConfigAt:Q?.lastConfigAt??0,lastFailureAt:Date.now(),failures:Y});let G=Y>=hO0?` \u2014 backing off ${xG$/60000}min`:"";console.warn(`[${K6}] tenant pool ${Z.name}: warming ${$.name} failed (${Y}/${hO0})${G}: ${X}`)}async refreshAllGitCredentials(){await vG$(this.records.values(),($)=>$.ensureOpts?.repo?.connectionId,async($)=>{if(this.claimWatchAbort.signal.aborted)return;let Z=$.ensureOpts?.repo;if(!Z)return;let X=await this.withFreshCloneUrl(Z,gW4);await this.refreshDaemonGitCredential($,{...$.ensureOpts,repo:X}),$.ensureOpts={...$.ensureOpts,repo:X}})}async rebootstrapDaemon($,Z,X){if(this.sentinelToken===null)return!1;let Q=this.workloadConfigPayload(X)??{};try{return await KC($,this.sentinelToken,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(Y){if(Y instanceof xO0&&Y.status===401)try{return await KC($,Z,Q,{rotateToken:Z}),await this.relayOrgFsConfig($,Z,X?.orgFsConfigJson),!0}catch(G){return console.warn(`[${K6}] re-bootstrap retry with claim token failed: ${G instanceof Error?G.message:String(G)}`),!1}return console.warn(`[${K6}] re-bootstrap failed: ${Y instanceof Error?Y.message:String(Y)}`),!1}}async ensureServicePortForAdoptedSandbox($){if(!this.previewGateway||!this.previewUrlPattern)return;await c5$(this.kubeConfig,this.namespace,$,{name:"daemon",port:pH,targetPort:pH})}async ensureHttpRouteForHandle($,Z,X){if(!this.previewGateway||!this.previewUrlPattern)return;let Q=QF4(this.previewUrlPattern,$);if(!Q)throw new FZ(`Unable to derive preview hostname for ${$} from pattern: ${this.previewUrlPattern}`);let Y={apiVersion:`${Ei0.API_GROUP}/${Ei0.API_VERSION}`,kind:"HTTPRoute",metadata:{name:$,namespace:this.namespace,labels:jn0(X??void 0,{[eX.role]:"claimed",[eX.sandboxHandle]:$,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...this.envName?{[eX.env]:this.envName}:{}})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[Q],rules:[{backendRefs:[{group:"",kind:"Service",name:Z,port:pH}]}]}};await g5$(this.kubeConfig,this.namespace,Y)}async deleteHttpRouteIfManaged($){if(!this.previewGateway)return;await h5$(this.kubeConfig,this.namespace,$)}async rehydrate($,Z,X){let Q=X.state;if(!Q.adoptedSandboxName&&!Q.podName||!Q.token)return null;let Y=await hH(this.kubeConfig,this.namespace,Z).catch(()=>{return});if(!Y||!gG$(Y))return null;let G=Y.status?.sandbox?.name??Q.adoptedSandboxName??Q.podName??Z,J=await this.openAndProbeDaemon(G,Z);if(!J)return null;if(Q.daemonBootId&&Q.daemonBootId!==J.bootId){if(this.sentinelToken!==null){let K=Q.ensureOpts?await this.withFreshCredentials(Q.ensureOpts):null;if(!await this.rebootstrapDaemon(J.daemonUrl,Q.token,K))return this.closeForwarder(J.daemonForward),null}else console.warn(`[${K6}] daemon restart detected (handle=${Z}): stored bootId=${Q.daemonBootId} live bootId=${J.bootId}`);await this.stateStore?.put($,{handle:Z,state:{...Q,daemonBootId:J.bootId}}).catch((K)=>console.warn(`[${K6}] bootId persist failed for ${Z}: ${K instanceof Error?K.message:String(K)}`))}return{id:$,handle:Z,adoptedSandboxName:G,token:Q.token,workdir:Q.workdir??wn0,daemonUrl:J.daemonUrl,daemonForward:J.daemonForward,workload:Q.workload??null,daemonBootId:J.bootId,tenant:Q.tenant??null,ensureOpts:Q.ensureOpts??null}}async adopt($,Z,X){if(!gG$(X))return null;let Q=X.status?.sandbox?.name??Z;if(this.sentinelToken!==null)return null;let Y=dW4(X);if(!Y)return null;let G=await this.openAndProbeDaemon(Q,Z);if(!G)return null;let J=sW4(X);if(this.previewGateway)await this.ensureServicePortForAdoptedSandbox(Q).catch((K)=>{console.warn(`[${K6}] Service port backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)}),await this.ensureHttpRouteForHandle(Z,Q,J).catch((K)=>{console.warn(`[${K6}] HTTPRoute backfill failed for ${Z}: ${K instanceof Error?K.message:String(K)}`)});return{id:$,handle:Z,adoptedSandboxName:Q,token:Y,workdir:wn0,daemonUrl:G.daemonUrl,daemonForward:G.daemonForward,workload:null,daemonBootId:G.bootId,tenant:J,ensureOpts:null}}async openAndProbeDaemon($,Z){let X=await this.openForwarder($,pH,Z).catch(()=>null);if(!X)return null;let Q=`http://127.0.0.1:${X.localPort}`,Y=await yO0(Q);if(!Y)return this.closeForwarder(X),null;return{daemonForward:X,daemonUrl:Q,bootId:Y.bootId}}async getRecord($){let Z=this.records.get($);if(Z)return Z;if(!this.stateStore)return null;let X=await this.stateStore.getByHandle($);if(!X)return null;let Q=await this.rehydrate(X.id,$,X);if(Q)this.records.set($,Q);return Q}async resurrectByHandle($){if(!this.stateStore)return null;let Z=await this.stateStore.getByHandle($);if(!Z)return null;let X=Z.state.ensureOpts;if(!X)return null;let Q=await this.withFreshCredentials(X);if(SE(Z.id)!==$)return null;return await this.ensure(Z.id,Q),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,zn0($.tenant))}recordProxyDuration($,Z,X,Q,Y){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...zn0(X?.tenant??null),source:$,sandbox_handle:X?.handle??Y??"",status_code:Z||0})}composePreviewUrl($){if(this.previewUrlPattern)return sZ0(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 X={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:X})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}async releaseAfter($,Z){let X=await hH(this.kubeConfig,this.namespace,$);if(!X)return;let Q=eW4(X.spec?.lifecycle?.shutdownTime,new Date(Date.now()+Z));if(!Q)return;await w70(this.kubeConfig,this.namespace,$,Q).catch((Y)=>console.warn(`[${K6}] release failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`))}async renewTtl($){let Z=await hH(this.kubeConfig,this.namespace,$);if(!Z)return;let X=$F4(Z.spec?.lifecycle?.shutdownTime,new Date(Date.now()+this.idleTtlMs));if(!X)return;await w70(this.kubeConfig,this.namespace,$,X).catch((Q)=>console.warn(`[${K6}] TTL renew failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`))}openForwarder($,Z,X=$){let Q=mW4(X,Z);return new Promise((Y,G)=>{let J=(K,W)=>{let F=uG$.createServer((H)=>this.handleForwardedConnection(H,$,Z,X));F.once("error",(H)=>{if(H.code==="EADDRINUSE"&&W<uW4){try{F.close()}catch{}let N=Pn0+(K-Pn0+1)%cG$;J(N,W+1);return}G(H)}),F.listen(K,"127.0.0.1",()=>{let H=F.address();if(!H||typeof H==="string"){F.close(),G(Error("port-forward listener failed to bind"));return}Y({server:F,localPort:H.port})})};J(Q,0)})}handleForwardedConnection($,Z,X,Q){let Y=new kW4,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,[X],$,null,Y).then((W)=>{let F=typeof W==="function"?W():W;if(!F){K();return}if(G=F,G.on("close",K),G.on("error",(H)=>{console.warn(`[${K6}] port-forward to ${Z}:${X} dropped mid-connection: ${fG$(H)}`,JSON.stringify(An0(H))),this.invalidateRecord(Q),K()}),J)try{G.close()}catch{}}).catch((W)=>{console.warn(`[${K6}] port-forward to ${Z}:${X} failed: ${fG$(W)}`,JSON.stringify(An0(W))),this.invalidateRecord(Q),K()})}closeForwarder($){$.server.close((Z)=>{if(Z)console.warn(`[${K6}] 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 cW4($){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 An0($){let Z=[],X=$;for(let Q=0;Q<5&&X instanceof Error;Q++){let Y=X;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===X)break;X=Y.cause}if(X!==void 0&&!(X instanceof Error)&&X!==null){let Q=X,Y=Q.error instanceof Error?An0(Q.error).chain:void 0;Z.push({nonError:String(X),...typeof Q.type==="string"?{type:Q.type}:{},...typeof Q.message==="string"?{message:Q.message}:{},...Q.code!==void 0?{code:Q.code}:{},...typeof Q.reason==="string"?{reason:Q.reason}:{},...Y?{error:Y}:{},...Y===void 0&&Q.error!==void 0?{rawError:String(Q.error)}:{},keys:Object.keys(Q)})}return{chain:Z}}function lW4(){let $=new EO0;return $.loadFromDefault(),$}function gG$($){return Boolean($.status?.conditions?.some((Z)=>Z.type==="Ready"&&Z.status==="True"))}function dW4($){let Z=$.spec?.env;if(!Z)return null;for(let X of Z)if(X.name==="DAEMON_TOKEN"&&X.value)return X.value;return null}function mW4($,Z){let X=IW4("sha256").update(`${$}:${Z}`).digest();return Pn0+X.readUInt32BE(0)%cG$}function En0($,Z){return new Response(JSON.stringify(Z),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function hG$($){let Z=$.slice(0,pW4);return iW4.test(Z)?Z:""}function tW4($){if($===void 0)return null;let Z=$.trim();if(Z==="")return null;if(!nW4.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 jn0($,Z={}){let X={...Z};if($){let Q=hG$($.orgId),Y=hG$($.userId);if(Q)X[eX.orgId]=Q;if(Y)X[eX.userId]=Y}return X}function WC($){let Z="";for(let X of $){let Q=X.codePointAt(0)??0;Z+=Q<32||Q===127?" ":X}return Z.slice(0,oW4)}function rW4($){try{let Z=new URL($);return Z.username="",Z.password="",Z.toString()}catch{return""}}function aW4($){let Z={},X=$.tenant;if(X?.orgSlug)Z[h3.orgSlug]=WC(X.orgSlug);if(X?.orgName)Z[h3.orgName]=WC(X.orgName);if(X?.userEmail)Z[h3.userEmail]=WC(X.userEmail);if(X?.userName)Z[h3.userName]=WC(X.userName);let Q=$.repo;if(Q){if(Q.displayName)Z[h3.gitRepo]=WC(Q.displayName);let Y=rW4(Q.cloneUrl);if(Y)Z[h3.gitRepoUrl]=WC(Y);let G=$.branch??Q.branch;if(G)Z[h3.gitBranch]=WC(G)}return Z}function sW4($){let Z=$.metadata?.labels;if(!Z)return null;let X=Z[eX.orgId],Q=Z[eX.userId];if(!X||!Q)return null;let Y=$.metadata?.annotations??{};return{orgId:X,userId:Q,orgSlug:Y[h3.orgSlug],orgName:Y[h3.orgName],userEmail:Y[h3.userEmail],userName:Y[h3.userName]}}function eW4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X<=Z.getTime())return null}return Z.toISOString()}function $F4($,Z){if($){let X=new Date($).getTime();if(Number.isFinite(X)&&X>=Z.getTime())return null}return Z.toISOString()}function zn0($){return{org_id:$?.orgId??"",user_id:$?.userId??"",runner_kind:"agent-sandbox"}}async function ZF4($,Z){if(!Z||!$.tenant)return $.orgFsConfigJson;try{return await Z($.tenant)??$.orgFsConfigJson}catch(X){return console.warn(`[${K6}] org-fs credential re-mint failed: ${X instanceof Error?X.message:String(X)}`),$.orgFsConfigJson}}function XF4($){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 QF4($,Z){try{return new URL(sZ0($,Z)).hostname||null}catch{return null}}var K6="AgentSandboxProvider",FC="x-sandbox-preview-not-ready",VW4="agent-sandbox-system",SW4="studio-sandbox",CW4=300000,pH=9000,bG$=3000,wn0="/app",_W4=32,vW4,fW4=900000,bW4=60000,xW4=1800000,hO0=3,xG$=1800000,yW4=900000,gW4=1800000,hW4,yG$,Pn0=40000,cG$=1e4,uW4=256,eX,h3,iW4,pW4=63,nW4,oW4=253;var lG$=D(()=>{K4();i5$();LG$();PG$();sm0();E70();O70();qG$();Ln0();vW4=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT"]),hW4=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],yG$=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];eX={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"},h3={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"},iW4=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/;nW4=/^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$/});var dG$={};J4(dG$,{parseTenantPools:()=>MG$,PREVIEW_NOT_READY_HEADER:()=>FC,AgentSandboxProvider:()=>Tn0});var Rn0=D(()=>{lG$();Ln0()});var pG$={};J4(pG$,{subscribeLifecycle:()=>Sn0,getOrInitSharedRunner:()=>Vn0,getAgentSandboxProviderForTeardown:()=>kn0,getAgentSandboxProvider:()=>$Q,__resetSharedLifecyclesForTesting:()=>BF4});function qn0($){let Z=_n[mG$];if(Z)return Promise.resolve(Z);let X=_n[In0];if(X)return X;let Q=$().then((Y)=>{return _n[mG$]=Y,Y}).finally(()=>{delete _n[In0]});return _n[In0]=Q,Q}function YF4(){let $=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return $&&$.trim()!==""?$:void 0}function GF4(){let $=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return $&&$.trim()!==""?$:void 0}function JF4(){let $=process.env.STUDIO_ENV;return $&&$.trim()!==""?$:void 0}function KF4(){let $=process.env.STUDIO_SANDBOX_SENTINEL_TOKEN;return $&&$.trim()!==""?$:void 0}function WF4(){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 Mn0($){let Z=new Kn($),X=YF4(),{AgentSandboxProvider:Q,parseTenantPools:Y}=await Promise.resolve().then(() => (Rn0(),dG$)),G=new kY(b0().encryptionKey);return new Q({stateStore:Z,previewUrlPattern:X,sandboxTemplateName:GF4(),envName:JF4(),previewGateway:WF4(),sentinelToken:KF4(),tenantPools:Y(process.env.STUDIO_SANDBOX_TENANT_POOLS),meter:w$,mintCloneUrl:async(J,K)=>{if(!J.connectionId)return null;let W=I5$(J.cloneUrl);if(!W)return null;let{cloneUrl:F}=await TW(J.connectionId,W.owner,W.name,$,G,{bufferMs:K?.bufferMs});return F},mintOrgFsConfig:async(J)=>{if(!J.orgSlug)return null;return await B70({boundAuth:{apiKey:{create:(W)=>X8.api.createApiKey({body:{...W,userId:J.userId}})}},storage:{orgRepoSyncs:new fE($)}},{orgSlug:J.orgSlug,orgId:J.orgId,baseUrl:f9()})??null}})}function $Q($){if(!b0().agentSandboxEnabled)throw Error("Agent sandbox is disabled. Set STUDIO_AGENT_SANDBOX_ENABLED=true to enable it.");return qn0(()=>Mn0($.db))}function kn0($){return qn0(()=>Mn0($.db))}async function Vn0(){if(!b0().agentSandboxEnabled)return null;return qn0(()=>Mn0(r8().db))}function Sn0($,Z,X){let Q=_O.get(Z);if(Q){if(Q.terminated){if(Q.lastPhase)try{X(Q.lastPhase)}catch{}return{unsubscribe:NF4}}if(Q.listeners.add(X),Q.lastPhase)try{X(Q.lastPhase)}catch{}return iG$(Z,Q,X)}let Y=new AbortController,G={lastPhase:null,terminated:!1,listeners:new Set([X]),abort:Y};return _O.set(Z,G),UF4($,Z,G),iG$(Z,G,X)}function NF4(){}function iG$($,Z,X){return{unsubscribe(){if(_O.get($)!==Z)return;if(Z.listeners.delete(X),Z.listeners.size===0)_O.delete($),Z.abort.abort()}}}async function UF4($,Z,X){let Q=null;try{for await(let Y of $.watchClaimLifecycle(Z,X.abort.signal)){if(X.abort.signal.aborted)break;X.lastPhase=Y;let G=Y.kind==="ready"||Y.kind==="failed";if(G)X.terminated=!0;let J=Array.from(X.listeners);for(let K of J)try{K(Y)}catch{}if(G)break}}catch(Y){Q=Y}finally{if(!X.terminated&&!X.abort.signal.aborted&&X.listeners.size>0){let Y={kind:"failed",reason:"unknown",message:Q instanceof Error?Q.message:"Lifecycle watcher ended unexpectedly"};X.lastPhase=Y,X.terminated=!0;for(let G of Array.from(X.listeners))try{G(Y)}catch{}}if(_O.get(Z)===X)_O.delete(Z)}}function BF4(){for(let $ of _O.values())$.abort.abort();_O.clear()}var mG$,In0,_n,FF4,HF4,_O;var u3=D(()=>{lG();I6();Ni0();Py();eL();R$();Ty();hY();$9();mG$=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-runner"),In0=Symbol.for("decocms.sandbox.lifecycle.agent-sandbox-inflight"),_n=globalThis;FF4=Symbol.for("decocms.sandbox.lifecycle.shared-lifecycles"),HF4=globalThis,_O=HF4[FF4]??=new Map});async function vn($,Z,X){try{await $.storage.threads.stampRuntimeIfAbsent(Z,X)}catch(Q){console.warn(`[stampRuntimeIfAbsent] ${Z}: ${Q instanceof Error?Q.message:String(Q)}`)}}function nG$($){let Z=$?.trim();if(!Z)return null;try{let X=new URL(Z);if(X.protocol!=="http:"&&X.protocol!=="https:")return null;return X.href}catch{return null}}function uO0($){return nG$($?.previewServerUrl)??nG$($?.productionUrl)}function HC($){return $==="cms"||$==="sandbox"?$:null}function OF4($){return!!uO0($)&&$?.fastPreview===!0}function cO0($){return OF4($)?"cms":"sandbox"}var Cn0;var hy=D(()=>{Cn0=["cms","sandbox"]});function tG$($){let{current:Z,detached:X,base:Q}=$.status??{};if(typeof Z!=="string"||Z.length===0)return null;if(X===!0)return null;if(Z===$.requestedRef)return null;if(DF4.has(Z))return null;if(typeof Q==="string"&&Q.length>0&&Z===Q)return null;return Z}function lO0($){if(!$.branch.startsWith("thread:"))return $.branch;if($.sticky&&$.recordedHeadRef)return $.recordedHeadRef;return $.derivedRef}var DF4;var dO0=D(()=>{DF4=new Set(["main","master","trunk","develop","HEAD"])});import{z as nH}from"zod";async function uy($,Z){r(Z);let X=t(Z),Q=o0(Z);if(!Q)throw Error("User ID required");let Y=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!Y||Y.organization_id!==X.id)throw Error("Virtual MCP not found");let G=Y.metadata??{},J=await CE(Z,$.branch,Q),K=AW(I9(G),J,$.branch),W=await $Q(Z);if(K){if(await W.alive(K.sandboxHandle).catch(()=>!0))return K;await DO(Z.storage.virtualMcps,$.virtualMcpId,Q,J,$.branch).catch((O)=>{console.warn("[ensureSandbox] failed to reap stale entry",O)})}let F=eG($.branch)??Z.metadata?.threadId;if(F)vn(Z,F,"sandbox");let N=await wO(Z,F)??G.githubRepo??null;await $.onColdStart?.().catch(()=>{});let{entry:U}=await rG$({ctx:Z,userId:Q,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:$.branch,metadata:G,githubRepo:N,threadRepos:await Qi0(Z,F),existing:null,runner:W,...$.purpose?{purpose:$.purpose}:{}});return U}async function LF4($){let Z=$.primary?`${$.primary.owner}/${$.primary.name}`.toLowerCase():null,X=$.repos.filter((G)=>`${G.owner}/${G.name}`.toLowerCase()!==Z),Q=$n(X),Y=[];for(let[G,J]of X.entries()){if(!J.connectionId)continue;try{let{cloneUrl:K}=await TW(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:Q[G],submoduleCredentials:[]})}catch(K){console.warn(`[provisionSandbox] skipping secondary ${J.owner}/${J.name}:`,K instanceof Error?K.message:K)}}return Y}async function rG$($){let{ctx:Z,userId:X,sandboxUserId:Q,orgId:Y,virtualMcpId:G,branch:J,metadata:K,threadRepos:W,existing:F,runner:H,purpose:N}=$,U=N==="harness-run",B=$.githubRepo?await wF4({ctx:Z,orgId:Y,virtualMcpId:G,userId:X,githubRepo:$.githubRepo}):null,{runtime:O,packageManager:L,port:w,packageManagerPath:E}=Q5$(K),j;if(B){if(B.connectionId)await zO({ctx:Z,connectionId:B.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(R0)=>{console.error("[provisionSandbox] repo-scoped legacy token mint failed",{connectionId:B.connectionId,error:R0.message})}});let{cloneUrl:s,gitUserName:a,gitUserEmail:z0}=B.connectionId?await TW(B.connectionId,B.owner,B.name,Z.db,Z.vault):U5$(B.owner,B.name);if(!L){let R0=B.connectionId?await D5$(B.connectionId,B.owner,B.name,Z.db,Z.vault):await L5$(B.owner,B.name);if(R0)L=R0.packageManager,O=Zn[R0.packageManager].runtime,w=R0.devPort??w,await EF4(Z,G,X,R0.packageManager,R0.devPort)}let X0=b0().sandboxStickyHeadRefEnabled,P0=lO0({branch:J,derivedRef:gH(J),recordedHeadRef:X0?await a6$(Z,eG(J)):null,sticky:X0}),g0=await J5$({ctx:Z,orgId:Y,userId:X,entries:Z5$(K)});j={cloneUrl:s,...B.connectionId?{connectionId:B.connectionId}:{},userName:a,userEmail:z0,branch:P0,displayName:`${B.owner}/${B.name}`,submoduleCredentials:g0}}let z=await LF4({ctx:Z,orgId:Y,repos:W??[],primary:B,gitUserName:j?.userName??"",gitUserEmail:j?.userEmail??""}),A=O&&L&&!U?{runtime:O,packageManager:L,...w!==null?{devPort:Number(w)}:{},...E?{packageManagerPath:E}:{}}:void 0,P=ap({orgId:Y,virtualMcpId:G,branch:J}),I=!b0().orgFsMountsDisabled,q;if(I){let s=Z.organization?.slug??(await Z.db.selectFrom("organization").select(["slug"]).where("id","=",Y).executeTakeFirst())?.slug;if(s)q=await B70(Z,{orgSlug:s,orgId:Y,baseUrl:f9()})}await zF4(H);let k=await H.ensure({userId:Q,projectRef:P},{branch:J,repo:j,extraRepos:z,workload:A,cloneOnly:U,...N?{purpose:N}:{},tenant:{orgId:Y,userId:Q,...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=jy(K);await Q70({ctx:Z,runner:H,handle:k.handle,orgId:Y,userId:X,entries:S});let f=!!F&&F.sandboxHandle===k.handle&&F?.createdAt?F.createdAt:Date.now(),b=K.runtime?.selected??null,i=K.runtime?.port??null,u=K.runtime?.path??null,o={sandboxHandle:k.handle,previewUrl:k.previewUrl,createdAt:f,startedWith:{packageManager:b,port:i,path:u}};await u6$(Z.storage.virtualMcps,G,X,Q,J,o);let U0=eG(J)??Z.metadata?.threadId;if(U0)await e6$(Z,U0,Q,J,o);let E0=!F||F.sandboxHandle!==k.handle;return{entry:o,isNewVm:E0}}async function wF4($){let{ctx:Z,orgId:X,virtualMcpId:Q,userId:Y,githubRepo:G}=$;if(!G.connectionId)return G;if(await Z.storage.connections.findById(G.connectionId,X))return G;let{items:K}=await Z.storage.connections.list(X),W=FZ0(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:Q,connectionId:G.connectionId}),G;console.warn("[provisionSandbox] healed dangling repo connection",{virtualMcpId:Q,staleConnectionId:G.connectionId,connectionId:W.id});try{let H=(await Z.storage.virtualMcps.findById(Q))?.metadata??{},N=H.githubRepo;if(N?.connectionId===G.connectionId){let U=M5(W);await Z.storage.virtualMcps.update(Q,Y,{metadata:{...H,githubRepo:{...N,connectionId:W.id,...U?{installationId:U.installationId}:{}}}})}}catch(F){console.warn("[provisionSandbox] failed to persist healed repo connection",{virtualMcpId:Q,error:F.message})}return{...G,connectionId:W.id}}async function EF4($,Z,X,Q,Y){let G=await $.storage.virtualMcps.findById(Z);if(!G)return;let J=G.metadata??{};await $.storage.virtualMcps.update(Z,X,{metadata:{...J,runtime:{selected:Q,port:Y}}})}async function zF4($){let Z=Date.now()+oG$,X=!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(oG$/1000)}s`);if(!X)X=!0,console.warn("[ensureSandbox] waiting for cluster capacity \u2014 a sandbox pod cannot be scheduled right now");await L$(jF4)}}var _n0,oG$=150000,jF4=5000;var fn=D(()=>{ep();K4();k0();Xn();Ki0();K5$();iQ();_Q();Py();E5$();$i0();u3();hy();b3();dO0();R$();$9();Ty();iQ();_n0=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:nH.object({virtualMcpId:nH.string().describe("Virtual MCP ID"),branch:nH.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:nH.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:nH.object({previewUrl:nH.string().nullable(),sandboxHandle:nH.string(),branch:nH.string(),isNewVm:nH.boolean()}),handler:async($,Z)=>{r(Z);let X=t(Z);await Z.access.check();let Q=$.branch??K70(J70(Z.auth.user)),Y=eG(Q)??$.threadId??Z.metadata?.threadId;if(Y){let L=await Z.storage.threads.get(Y).catch(()=>null);if(HC(L?.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=o0(Z);if(!G)throw Error("User ID required");let J=await CE(Z,Q,G),K=await Z.storage.virtualMcps.findById($.virtualMcpId);if(!K||K.organization_id!==X.id)throw Error("Virtual MCP not found");let W=K.metadata??{},F=await $Q(Z),H=AW(I9(W),J,Q),U=await wO(Z,eG(Q)??Z.metadata?.threadId)??W.githubRepo??null,{entry:B,isNewVm:O}=await rG$({ctx:Z,userId:G,sandboxUserId:J,orgId:X.id,virtualMcpId:$.virtualMcpId,branch:Q,metadata:W,githubRepo:U,threadRepos:await Qi0(Z,eG(Q)??Z.metadata?.threadId),existing:H,runner:F});if(Y)vn(Z,Y,"sandbox");return{...B,branch:Q,isNewVm:O}}})});function PF4($){let{publicUrl:Z,agentId:X,organization:Q,target:Y,threadId:G}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${encodeURIComponent(X)}`;if(!Q.slug)throw new sG$(Q.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/${Q.slug}/mcp/task-run/${encodeURIComponent(G)}`}return`${Z}/api/${Q.slug}/mcp/self`}async function mO0($,Z,X,Q,Y="agent-tools",G,J={"*":["*"]}){let K=PF4({publicUrl:f9(),agentId:Z,organization:X,target:Y,...G?{threadId:G}:{}}),W=await $.boundAuth.apiKey.create({name:Q,permissions:J,expiresIn:aG$,metadata:{organization:{id:X.id,slug:X.slug,name:X.name}}});return{url:K,headers:{Authorization:`Bearer ${W.key}`,"x-org-id":X.id},expiresAt:Date.now()+aG$*1000}}function eG$($){let{publicUrl:Z,organizationSlug:X,headers:Q,connections:Y}=$,G=new Set;return Y.map((J)=>{let K=AF4(J.slug??J.title??"")||"mcp",W=K;for(let F=2;G.has(W);F++)W=`${K}-${F}`;return G.add(W),{name:W,url:`${Z}/api/${X}/mcp/${encodeURIComponent(J.id)}`,headers:Q}})}function AF4($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function $J$($){return{self:[...$.toolNames],...$.grants}}var aG$=3600,sG$;var vn0=D(()=>{$9();sG$=class sG$ 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 TF4($,Z,X,Q){try{let Y=$.organization;if(!Y)return;let G=await mO0($,Q.virtualMcpId,Y,"tool-scripting"),J=await Z.proxyDaemonRequest(X,"/_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 cy($,Z){let X=await $Q($),Q=null,Y=()=>{if(!Q){if(Q=uy({virtualMcpId:Z.virtualMcpId,branch:Z.branch},$).then((K)=>K.sandboxHandle),Q.catch(()=>{Q=null}),Z.syncTools)Q.then((K)=>TF4($,X,K,{virtualMcpId:Z.virtualMcpId})).catch(()=>{})}return Q},G=Z.branch==="ephemeral";return em0(X,{ensureHandle:Y,invalidateHandle:async(K)=>{if(Q=null,!G&&!K?.force)return;try{await DO($.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 ZJ$($,Z){try{let X=await cy($,Z),{stdout:Q}=await X.onBash("test -d .deco && echo __DECO_SITE__");return Q.includes("__DECO_SITE__")}catch(X){return console.warn("[agent-sandbox-fs] .deco probe failed; assuming deco site",X),!0}}var iO0=D(()=>{ep();vn0();u3();fn();iQ()});import{z as XJ$}from"zod";function ly($){let Z=[];for(let X of $){if(X.status!=="active")continue;let Q=M5(X);if(!Q)continue;Z.push({connectionId:X.id,owner:Q.owner,repo:Q.repo,installationId:Q.installationId})}return Z}async function IF4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return ly(X)}function qF4($){let Z=$.split(`
980
980
  `).map((Q)=>Q.trim()).filter((Q)=>Q&&Q!==".git"&&Q!=="__CLONED__"),X=Z.length>0;return{cloned:X,listing:X?Z.join(`
981
981
  `):""}}function MF4($){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.",X=$.map((Q)=>`- ${Q.owner}/${Q.repo} (connectionId: ${Q.connectionId})`).join(`
982
982
  `);return`${Z}
@@ -1464,7 +1464,7 @@ Usage notes:
1464
1464
  `+`- 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'.
1465
1465
  `+`- Clearly tell the subagent whether you expect it to take action or just research.
1466
1466
  - To parallelize independent searches, launch multiple subtask calls in the same message.
1467
- - The subagent's output should generally be trusted.`;yD4={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}});function HH$($){let Z={},X=$.split(/\r?\n/);for(let Q=0;Q<X.length;Q++){let Y=(X[Q]??"").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 ${Q+1}: missing '='`);let J=Y.slice(0,G).trim();if(!gD4.test(J))throw Error(`Line ${Q+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 gD4;var NH$=D(()=>{gD4=/^[A-Za-z_][A-Za-z0-9_]*$/});async function BH$($){let Z=$.organization?.id;if(!Z)return{};try{let{value:X}=await $.storage.secrets.resolveByName({organizationId:Z,scope:{kind:"organization"},name:UH$});return HH$(X)}catch(X){if(X?.name!=="SecretNotFoundError")console.warn(`[org-run-env] ignoring the ${UH$} secret: ${X instanceof Error?X.message:String(X)}`);return{}}}function OH$($,Z){return{...$,...Z}}var UH$="TASK_RUN_ENV";var DH$=D(()=>{NH$()});async function*LH$($,Z,X){let Q=!1;for await(let Y of $){if(yield Y,Q||!Z)continue;if(Y.type!=="start")continue;Q=!0,yield{type:"message-metadata",messageMetadata:{models:{thinking:{id:Z,title:Z,provider:X}}}}}}function wH$($){let{role:Z,roleStatements:X,connectionIds:Q}=$;if(n7(Z??void 0))return Object.fromEntries(Q.map((G)=>[G,["*"]]));let Y={};for(let G of Q){let J=new Set;for(let K of X)for(let W of K[G]??[])J.add(W);if(J.size===0)continue;Y[G]=J.has("*")?["*"]:[...J]}return Y}function EH$($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}var jH$=D(()=>{VQ()});function _C($){return $==="decopilot"||$==="claude-code"}function uD4($){return{type:"data-run-status",id:"run-status",data:{stage:$}}}function zH$($){if(!$||typeof $!=="object")return!1;return $.type==="data-run-status"}async function $G($){let{streamBuffer:Z,harnessId:X,taskId:Q,stage:Y}=$;if(!Z||!_C(X))return;try{await Z.publishRawChunk(Q,uD4(Y))}catch{}}var hD4,Ut,m_9;var vC=D(()=>{hD4=["waiting-runner","starting-run","starting-sandbox","waiting-capacity","gathering-context","preparing-tools","starting-assistant","analyzing-scope","retrying-provider"],Ut=["gathering-context","preparing-tools","starting-assistant","analyzing-scope"],m_9=new Set(hD4)});function Bt($){return $ instanceof Error&&$.superseded===!0}function IH$($){return $===404||$===410||$>=500}function Lg($){return $===fC}class so0{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 wO(this.ctx,$);if(!Z)return this.branch===yH($)?{cwd:PH$,branch:gH(this.branch)}:{cwd:null};return{cwd:PH$,repo:{owner:Z.owner,name:Z.name,connectedGithub:Boolean(Z.connectionId)},branch:this.branch.startsWith("thread:")?gH(this.branch):this.branch}}async mcpForRun($,Z,X){let Q=await this.orgMcpConnections($),Y=await this.dispatcherConnectionGrants($.id,X,Q.map((W)=>W.id)),G=Q.filter((W)=>(W.id in Y)),J=await mO0(this.ctx,this.virtualMcpId,$,`${fC}-run`,"task-run",Z,$J$({toolNames:fn0,grants:Y}));if(G.length===0||!$.slug)return{mcp:J};let K=eG$({publicUrl:f9(),organizationSlug:$.slug,headers:J.headers,connections:G});return console.log(`[${fC}] org mcps: ${K.map((W)=>W.name).join(" ")||"none"}${Q.length===G.length?"":` (${Q.length-G.length} withheld \u2014 the `+"dispatching user has no grant for them)"}`),{mcp:J,orgMcps:K}}async dispatcherConnectionGrants($,Z,X){if(X.length===0)return{};let Y=(await this.ctx.db.selectFrom("member").select(["role"]).where("organizationId","=",$).where("userId","=",Z).executeTakeFirst())?.role,G=n7(Y??void 0)?[]:(await Promise.all(EH$(Y).map((J)=>Ot(this.ctx.db,$,J)))).filter((J)=>Boolean(J));return wH$({role:Y,roleStatements:G,connectionIds:X})}async orgMcpConnections($){if(!$.slug)return[];let[Z,X]=await Promise.all([this.ctx.storage.organizationSettings.get($.id),this.ctx.storage.virtualMcps.findById(this.virtualMcpId).catch(()=>null)]),Q=gY(Z?.flags,"coding_agent_org_mcps"),Y=new Set((X?.connections??[]).map((J)=>J.connection_id));if(!Q&&Y.size===0)return[];let{items:G}=await this.ctx.storage.connections.list($.id);return ZL4({organizationId:$.id,orgWide:Q,ownIds:Y,connections:G})}async*stream($){if(!this.credential)throw Error(`the ${fC} harness needs a resolved model credential; this run has none (check the agent's thinking model)`);let Z=CJ$(this.credential,VJ$(this.ctx.metadata?.runMetadata?.[ZD0])),X=this.ctx.organization;if(!X)throw Error(`the ${fC} harness needs an organization on the context to mint its MCP endpoint; this run has none`);let Q=OH$(await BH$(this.ctx),Z),Y=await $Q(this.ctx),G={...$,...await this.mcpForRun(X,$.threadId,$.user.id),workspace:await this.resolveWorkspace($.threadId)},J=$.threadId,{ctx:K,virtualMcpId:W,branch:F,interactive:H,streamBuffer:N}=this,U=this.credential.providerId,B=null,O=(L)=>async function*(){await $G({streamBuffer:N,harnessId:fC,taskId:J,stage:"starting-sandbox"});let w=await uy({virtualMcpId:W,branch:F,purpose:H?"interactive":"harness-run"},K);B=w.sandboxHandle,await tD4(Y,w.sandboxHandle,Q),yield*LH$(sD4({provider:Y,handle:w.sandboxHandle,input:L?{...G,resume:L}:G,runId:J,signal:$.signal}),L?null:Z.CLAUDE_CODE_MODEL,U)}();try{yield*mD4({runId:J,resume:this.resume,aborted:()=>$.signal?.aborted===!0,dispatchOnce:O,lastHandle:()=>B,describeTermination:async(L)=>L===null?null:pD4(await Y.lastTermination(L))})}finally{if(B&&!this.interactive&&b0().sandboxReleaseOnRunEndEnabled)await Y.releaseAfter(B,b0().sandboxReleaseGraceMs).catch(()=>{})}}}async function*mD4($){let Z=$.maxAttempts??cD4,X=$.maxTotalAttempts??lD4,Q=$.resume,Y=Q!==null,G=0;for(let J=1;;J++){let K=!1;try{for await(let W of $.dispatchOnce(Q)){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 F=W instanceof aQ?await $.describeTermination?.($.lastHandle?.()??null).catch(()=>null)??null:null;if(Bt(W)||!(W instanceof aQ)||G>=Z||J>=X){if(F&&W instanceof aQ)throw new aQ(W.reason,F);throw W}console.warn("[sandbox-dispatch] sandbox lost mid-run; continuing",{runId:$.runId,attempt:J,progressed:K,reason:W.message,termination:F}),Q={reason:iD4(W.message,F)}}}}function iD4($,Z){let X=`the sandbox running the previous attempt stopped answering (${$})`;if(!Z)return X;return`${X}. ${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 pD4($){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 tD4($,Z,X){let Q;try{Q=await $.proxyDaemonRequest(Z,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({env:X}),signal:AbortSignal.timeout(nD4)})}catch(Y){throw new aQ(`could not push the model env to the sandbox: ${Y instanceof Error?Y.message:String(Y)}`)}if(!Q.ok){let Y=`failed to push model env to the sandbox (${Q.status} ${Q.statusText})`;if(IH$(Q.status))throw new aQ(Y);throw Error(Y)}}function oD4($){let{signal:Z,...X}=$;return X}function aD4($,Z){let X=()=>void $.renewTtl(Z).catch((Y)=>console.warn(`[sandbox-dispatch] TTL renew failed for ${Z}: ${Y instanceof Error?Y.message:String(Y)}`));X();let Q=setInterval(X,rD4);return Q.unref?.(),()=>clearInterval(Q)}async function*sD4($){let Z=Date.now(),X=oD4($.input),Q=(F=!1)=>$.provider.proxyDaemonRequest($.handle,"/_sandbox/dispatch",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({...F?{harnessId:fC}:{},runId:$.runId,input:X}),...$.signal?{signal:$.signal}:{}}),Y;try{if(Y=await Q(),Y.status===400){let F=await Y.clone().json().catch(()=>null);if(typeof F==="object"&&F!==null&&"error"in F&&F.error==="missing_harness_id")Y=await Q(!0)}}catch(F){if($.signal?.aborted)throw F;throw new aQ(`could not reach the sandbox daemon: ${F instanceof Error?F.message:String(F)}`)}if(!Y.ok){let F=await Y.text().catch(()=>Y.statusText),H=`sandbox dispatch failed (${Y.status}): ${F.slice(0,512)}`;if(IH$(Y.status))throw new aQ(H);throw Error(H)}if(!Y.body)throw new aQ("dispatch returned no body");let G=aD4($.provider,$.handle),J=0,K=null,W=!1;try{for await(let F of $L4(Y.body,$.signal)){let H=_J$.safeParse(F);if(!H.success)throw Error(`sandbox dispatch returned a malformed frame: ${H.error.message}`);if(J+=H.data.chunks.length,yield*H.data.chunks,K??=H.data.error,H.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 aQ(`the sandbox stopped streaming after ${J} chunks without finishing the run`);if(K)throw eD4(K.code,K.message)}function eD4($,Z){if($===dD4)return new RH$(Z);if($===fJ$)return new aQ(Z);return Error(`${$}: ${Z}`)}async function*$L4($,Z){let X=new TextDecoder,Q="",Y=function*(J){let K=Q.split(`
1467
+ - The subagent's output should generally be trusted.`;yD4={readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}});function HH$($){let Z={},X=$.split(/\r?\n/);for(let Q=0;Q<X.length;Q++){let Y=(X[Q]??"").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 ${Q+1}: missing '='`);let J=Y.slice(0,G).trim();if(!gD4.test(J))throw Error(`Line ${Q+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 gD4;var NH$=D(()=>{gD4=/^[A-Za-z_][A-Za-z0-9_]*$/});async function BH$($){let Z=$.organization?.id;if(!Z)return{};try{let{value:X}=await $.storage.secrets.resolveByName({organizationId:Z,scope:{kind:"organization"},name:UH$});return HH$(X)}catch(X){if(X?.name!=="SecretNotFoundError")console.warn(`[org-run-env] ignoring the ${UH$} secret: ${X instanceof Error?X.message:String(X)}`);return{}}}function OH$($,Z){return{...$,...Z}}var UH$="TASK_RUN_ENV";var DH$=D(()=>{NH$()});async function*LH$($,Z,X){let Q=!1;for await(let Y of $){if(yield Y,Q||!Z)continue;if(Y.type!=="start")continue;Q=!0,yield{type:"message-metadata",messageMetadata:{models:{thinking:{id:Z,title:Z,provider:X}}}}}}function wH$($){let{role:Z,roleStatements:X,connectionIds:Q}=$;if(n7(Z??void 0))return Object.fromEntries(Q.map((G)=>[G,["*"]]));let Y={};for(let G of Q){let J=new Set;for(let K of X)for(let W of K[G]??[])J.add(W);if(J.size===0)continue;Y[G]=J.has("*")?["*"]:[...J]}return Y}function EH$($){return($??"").split(",").map((Z)=>Z.trim()).filter(Boolean)}var jH$=D(()=>{VQ()});function _C($){return $==="decopilot"||$==="claude-code"}function uD4($){return{type:"data-run-status",id:"run-status",data:{stage:$}}}function zH$($){if(!$||typeof $!=="object")return!1;return $.type==="data-run-status"}async function $G($){let{streamBuffer:Z,harnessId:X,taskId:Q,stage:Y}=$;if(!Z||!_C(X))return;try{await Z.publishRawChunk(Q,uD4(Y))}catch{}}var hD4,Ut,m_9;var vC=D(()=>{hD4=["waiting-runner","starting-run","starting-sandbox","waiting-capacity","gathering-context","preparing-tools","starting-assistant","analyzing-scope","retrying-provider"],Ut=["gathering-context","preparing-tools","starting-assistant","analyzing-scope"],m_9=new Set(hD4)});function Bt($){return $ instanceof Error&&$.superseded===!0}function IH$($){return $===404||$===410||$>=500}function Lg($){return $===fC}class so0{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 wO(this.ctx,$);if(!Z)return this.branch===yH($)?{cwd:PH$,branch:gH(this.branch)}:{cwd:null};return{cwd:PH$,repo:{owner:Z.owner,name:Z.name,connectedGithub:Boolean(Z.connectionId)},branch:this.branch.startsWith("thread:")?gH(this.branch):this.branch}}async mcpForRun($,Z,X){let Q=await this.orgMcpConnections($),Y=await this.dispatcherConnectionGrants($.id,X,Q.map((W)=>W.id)),G=Q.filter((W)=>(W.id in Y)),J=await mO0(this.ctx,this.virtualMcpId,$,`${fC}-run`,"task-run",Z,$J$({toolNames:fn0,grants:Y}));if(G.length===0||!$.slug)return{mcp:J};let K=eG$({publicUrl:f9(),organizationSlug:$.slug,headers:J.headers,connections:G});return console.log(`[${fC}] org mcps: ${K.map((W)=>W.name).join(" ")||"none"}${Q.length===G.length?"":` (${Q.length-G.length} withheld \u2014 the `+"dispatching user has no grant for them)"}`),{mcp:J,orgMcps:K}}async dispatcherConnectionGrants($,Z,X){if(X.length===0)return{};let Y=(await this.ctx.db.selectFrom("member").select(["role"]).where("organizationId","=",$).where("userId","=",Z).executeTakeFirst())?.role,G=n7(Y??void 0)?[]:(await Promise.all(EH$(Y).map((J)=>Ot(this.ctx.db,$,J)))).filter((J)=>Boolean(J));return wH$({role:Y,roleStatements:G,connectionIds:X})}async orgMcpConnections($){if(!$.slug)return[];let[Z,X]=await Promise.all([this.ctx.storage.organizationSettings.get($.id),this.ctx.storage.virtualMcps.findById(this.virtualMcpId).catch(()=>null)]),Q=gY(Z?.flags,"coding_agent_org_mcps"),Y=new Set((X?.connections??[]).map((J)=>J.connection_id));if(!Q&&Y.size===0)return[];let{items:G}=await this.ctx.storage.connections.list($.id);return ZL4({organizationId:$.id,orgWide:Q,ownIds:Y,connections:G})}async*stream($){if(!this.credential)throw Error(`the ${fC} harness needs a resolved model credential; this run has none (check the agent's thinking model)`);let Z=CJ$(this.credential,VJ$(this.ctx.metadata?.runMetadata?.[ZD0])),X=this.ctx.organization;if(!X)throw Error(`the ${fC} harness needs an organization on the context to mint its MCP endpoint; this run has none`);let Q=OH$(await BH$(this.ctx),Z),Y=await $Q(this.ctx),G={...$,...await this.mcpForRun(X,$.threadId,$.user.id),workspace:await this.resolveWorkspace($.threadId)},J=$.threadId,{ctx:K,virtualMcpId:W,branch:F,interactive:H,streamBuffer:N}=this,U=this.credential.providerId,B=null,O=(L)=>async function*(){let w=await uy({virtualMcpId:W,branch:F,purpose:H?"interactive":"harness-run",onColdStart:()=>$G({streamBuffer:N,harnessId:fC,taskId:J,stage:"starting-sandbox"})},K);B=w.sandboxHandle,await tD4(Y,w.sandboxHandle,Q),yield*LH$(sD4({provider:Y,handle:w.sandboxHandle,input:L?{...G,resume:L}:G,runId:J,signal:$.signal}),L?null:Z.CLAUDE_CODE_MODEL,U)}();try{yield*mD4({runId:J,resume:this.resume,aborted:()=>$.signal?.aborted===!0,dispatchOnce:O,lastHandle:()=>B,describeTermination:async(L)=>L===null?null:pD4(await Y.lastTermination(L))})}finally{if(B&&!this.interactive&&b0().sandboxReleaseOnRunEndEnabled)await Y.releaseAfter(B,b0().sandboxReleaseGraceMs).catch(()=>{})}}}async function*mD4($){let Z=$.maxAttempts??cD4,X=$.maxTotalAttempts??lD4,Q=$.resume,Y=Q!==null,G=0;for(let J=1;;J++){let K=!1;try{for await(let W of $.dispatchOnce(Q)){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 F=W instanceof aQ?await $.describeTermination?.($.lastHandle?.()??null).catch(()=>null)??null:null;if(Bt(W)||!(W instanceof aQ)||G>=Z||J>=X){if(F&&W instanceof aQ)throw new aQ(W.reason,F);throw W}console.warn("[sandbox-dispatch] sandbox lost mid-run; continuing",{runId:$.runId,attempt:J,progressed:K,reason:W.message,termination:F}),Q={reason:iD4(W.message,F)}}}}function iD4($,Z){let X=`the sandbox running the previous attempt stopped answering (${$})`;if(!Z)return X;return`${X}. ${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 pD4($){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 tD4($,Z,X){let Q;try{Q=await $.proxyDaemonRequest(Z,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({env:X}),signal:AbortSignal.timeout(nD4)})}catch(Y){throw new aQ(`could not push the model env to the sandbox: ${Y instanceof Error?Y.message:String(Y)}`)}if(!Q.ok){let Y=`failed to push model env to the sandbox (${Q.status} ${Q.statusText})`;if(IH$(Q.status))throw new aQ(Y);throw Error(Y)}}function oD4($){let{signal:Z,...X}=$;return X}function aD4($,Z){let X=()=>void $.renewTtl(Z).catch((Y)=>console.warn(`[sandbox-dispatch] TTL renew failed for ${Z}: ${Y instanceof Error?Y.message:String(Y)}`));X();let Q=setInterval(X,rD4);return Q.unref?.(),()=>clearInterval(Q)}async function*sD4($){let Z=Date.now(),X=oD4($.input),Q=(F=!1)=>$.provider.proxyDaemonRequest($.handle,"/_sandbox/dispatch",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({...F?{harnessId:fC}:{},runId:$.runId,input:X}),...$.signal?{signal:$.signal}:{}}),Y;try{if(Y=await Q(),Y.status===400){let F=await Y.clone().json().catch(()=>null);if(typeof F==="object"&&F!==null&&"error"in F&&F.error==="missing_harness_id")Y=await Q(!0)}}catch(F){if($.signal?.aborted)throw F;throw new aQ(`could not reach the sandbox daemon: ${F instanceof Error?F.message:String(F)}`)}if(!Y.ok){let F=await Y.text().catch(()=>Y.statusText),H=`sandbox dispatch failed (${Y.status}): ${F.slice(0,512)}`;if(IH$(Y.status))throw new aQ(H);throw Error(H)}if(!Y.body)throw new aQ("dispatch returned no body");let G=aD4($.provider,$.handle),J=0,K=null,W=!1;try{for await(let F of $L4(Y.body,$.signal)){let H=_J$.safeParse(F);if(!H.success)throw Error(`sandbox dispatch returned a malformed frame: ${H.error.message}`);if(J+=H.data.chunks.length,yield*H.data.chunks,K??=H.data.error,H.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 aQ(`the sandbox stopped streaming after ${J} chunks without finishing the run`);if(K)throw eD4(K.code,K.message)}function eD4($,Z){if($===dD4)return new RH$(Z);if($===fJ$)return new aQ(Z);return Error(`${$}: ${Z}`)}async function*$L4($,Z){let X=new TextDecoder,Q="",Y=function*(J){let K=Q.split(`
1468
1468
  `);Q=J?K.pop()??"":"";for(let W of K){if(W.trim().length===0)continue;try{yield JSON.parse(W)}catch(F){throw Error(`sandbox dispatch produced a non-JSON line: ${F instanceof Error?F.message:String(F)} (line: ${W.slice(0,256)})`)}}},G=$[Symbol.asyncIterator]();try{for(;;){let J=new AbortController,K=G.next().then((H)=>{return J.abort(),H}),W=L$(AH$,{signal:J.signal}).then(()=>"silent").catch(()=>"read-won"),F=await Promise.race([K,W]).catch((H)=>{if(Z?.aborted)throw H;let N=H instanceof Error?H.message:String(H);if(!ao0(N))throw H;throw new aQ(`the sandbox stream broke mid-run: ${N}`)});if(F==="silent"){if(Z?.aborted)return;throw new aQ(`no output from the sandbox for ${AH$/1000}s (its keepalive is every 15s, so the pod is gone)`)}if(F==="read-won")continue;if(F.done)break;if(Q+=X.decode(F.value,{stream:!0}),yield*Y(!0),Q.length>TH$)throw Error(`sandbox dispatch produced a line over ${TH$} chars without a newline \u2014 refusing to buffer it further`)}Q+=X.decode(),yield*Y(!1)}finally{await G.return?.().catch(()=>{})}}function ZL4($){return $.connections.filter((Z)=>($.orgWide||$.ownIds.has(Z.id))&&Z.status==="active"&&!XL4($.organizationId,Z.id))}function XL4($,Z){return[C8.SELF,C8.REGISTRY,C8.COMMUNITY_REGISTRY,C8.DEV_ASSETS,C8.COMMERCE_DISCOVERY].some((X)=>X($)===Z)}var PH$="/repo",fC="claude-code",cD4=2,lD4=5,AH$=90000,TH$=67108864,aQ,RH$,dD4="superseded",nD4=30000,rD4=300000;var jL0=D(()=>{K4();vJ$();co0();XD0();DH$();vn0();xZ();_8();VQ();dO();jH$();vO();$9();u3();R$();fn();vC();b3();aQ=class aQ extends Error{reason;constructor($,Z){super(`${QD0} ${$}${Z?` \u2014 ${Z}`:""}`);this.name="SandboxUnreachableError",this.reason=$}};RH$=class RH$ extends Error{superseded=!0;constructor($){super($);this.name="RunSupersededError"}}});function eo0($){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 qH$=D(()=>{mK();Bb()});var MH$=D(()=>{qH$()});import{z as Dt}from"zod/v4";import{z as M}from"zod/v4";import{z as W1}from"zod/v4";import{z as NZ}from"zod/v4";import{z as UJ}from"zod/v4";import{z as q9}from"zod/v4";import{z as M9}from"zod/v4";import{z as P6}from"zod/v4";import{z as A6}from"zod/v4";import{z as n3}from"zod/v4";import{z as e1}from"zod/v4";import{z as f1}from"zod/v4";import{z as bC}from"zod/v4";import{z as Qr0}from"zod/v4";import{z as Yr0}from"zod/v4";import{z as Lt}from"zod/v4";import{z as NJ}from"zod/v4";import{z as L7}from"zod/v4";import{z as v6}from"zod/v4";import{z as xW}from"zod/v4";import{z as yW}from"zod/v4";import{z as gW}from"zod/v4";import{z as xC}from"zod/v4";function WL4($){var Z;let X=$==null?void 0:$.anthropic;return(Z=X==null?void 0:X.cacheControl)!=null?Z:X==null?void 0:X.cache_control}async function bL4({tools:$,toolChoice:Z,disableParallelToolUse:X,cacheControlValidator:Q,supportsStructuredOutput:Y,supportsStrictTools:G,defaultEagerInputStreaming:J=!1}){var K,W;$=($==null?void 0:$.length)?$:void 0;let F=[],H=new Set,N=Q||new Gr0;if($==null)return{tools:void 0,toolChoice:void 0,toolWarnings:F,betas:H};let U=[];for(let O of $)switch(O.type){case"function":{let L=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)F.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:L,...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)H.add("structured-outputs-2025-11-13");if(O.inputExamples!=null||z!=null)H.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(O.id){case"anthropic.code_execution_20250522":{H.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":{H.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":{H.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":{H.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":{H.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":{H.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":{H.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":{H.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 L=await g$({value:O.args,schema:BL4});U.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:L.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{H.add("computer-use-2025-01-24"),U.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{H.add("computer-use-2024-10-22"),U.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{H.add("context-management-2025-06-27"),U.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{H.add("web-fetch-2025-09-10");let L=await g$({value:O.args,schema:CL4});U.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:L.maxUses,allowed_domains:L.allowedDomains,blocked_domains:L.blockedDomains,citations:L.citations,max_content_tokens:L.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{H.add("code-execution-web-tools-2026-02-09");let L=await g$({value:O.args,schema:qL4});U.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:L.maxUses,allowed_domains:L.allowedDomains,blocked_domains:L.blockedDomains,citations:L.citations,max_content_tokens:L.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let L=await g$({value:O.args,schema:AL4});U.push({type:"web_search_20250305",name:"web_search",max_uses:L.maxUses,allowed_domains:L.allowedDomains,blocked_domains:L.blockedDomains,user_location:L.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{H.add("code-execution-web-tools-2026-02-09");let L=await g$({value:O.args,schema:wL4});U.push({type:"web_search_20260209",name:"web_search",max_uses:L.maxUses,allowed_domains:L.allowedDomains,blocked_domains:L.blockedDomains,user_location:L.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":{H.add("advisor-tool-2026-03-01");let L=await g$({value:O.args,schema:FL4});U.push({type:"advisor_20260301",name:"advisor",model:L.model,...L.maxUses!==void 0&&{max_uses:L.maxUses},...L.caching!==void 0&&{caching:L.caching}});break}default:{F.push({type:"unsupported",feature:`provider-defined tool ${O.id}`});break}}break}default:{F.push({type:"unsupported",feature:`tool ${O}`});break}}if(Z==null)return{tools:U,toolChoice:X?{type:"auto",disable_parallel_tool_use:X}:void 0,toolWarnings:F,betas:H};let B=Z.type;switch(B){case"auto":return{tools:U,toolChoice:{type:"auto",disable_parallel_tool_use:X},toolWarnings:F,betas:H};case"required":return{tools:U,toolChoice:{type:"any",disable_parallel_tool_use:X},toolWarnings:F,betas:H};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:F,betas:H};case"tool":return{tools:U,toolChoice:{type:"tool",name:Z.toolName,disable_parallel_tool_use:X},toolWarnings:F,betas:H};default:throw new v4({functionality:`tool choice type: ${B}`})}}function _H$({usage:$,rawUsage:Z}){var X,Q,Y;let G=(X=$.cache_creation_input_tokens)!=null?X:0,J=(Q=$.cache_read_input_tokens)!=null?Q:0,K,W,F=(Y=$.iterations)==null?void 0:Y.some((H)=>H.type==="fallback_message");if($.iterations&&$.iterations.length>0&&!F){let H=$.iterations.filter((N)=>N.type==="compaction"||N.type==="message");if(H.length>0){let N=H.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 tL4($){if(typeof $==="string")return new TextDecoder().decode(P9($));if($ instanceof Uint8Array)return new TextDecoder().decode($);if($ instanceof URL)throw new v4({functionality:"URL-based text documents are not supported for citations"});throw new v4({functionality:`unsupported data type for text documents: ${typeof $}`})}function $r0($){return $ instanceof URL||oL4($)}function oL4($){return typeof $==="string"&&/^https?:\/\//i.test($)}function Zr0($){return $ instanceof URL?$.toString():$}async function vH$($){if(typeof $==="string"){let Z=await gZ({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 rL4({prompt:$,sendReasoning:Z,warnings:X,cacheControlValidator:Q,toolNameMapping:Y}){var G,J,K,W,F,H,N,U,B,O,L,w,E,j,z,A,P,I,q,k,S;let m=new Set,f=aL4($),b=Q||new Gr0,i=void 0,u=[];async function o(E0){var s,a;let z0=await a8({provider:"anthropic",providerOptions:E0,schema:VH$});return(a=(s=z0==null?void 0:z0.citations)==null?void 0:s.enabled)!=null?a:!1}async function U0(E0){let s=await a8({provider:"anthropic",providerOptions:E0,schema:VH$});return{title:s==null?void 0:s.title,context:s==null?void 0:s.context}}for(let E0=0;E0<f.length;E0++){let s=f[E0],a=E0===f.length-1,z0=s.type;switch(z0){case"system":{let X0=s.messages.map(({content:P0,providerOptions:g0})=>({type:"text",text:P0,cache_control:b.getCacheControl(g0,{type:"system message",canCache:!0})}));if(i==null)i=X0;else u.push({role:"system",content:X0}),m.add("mid-conversation-system-2026-04-07");break}case"user":{let X0=[];for(let P0 of s.messages){let{role:g0,content:R0}=P0;switch(g0){case"user":{for(let c0=0;c0<R0.length;c0++){let Y0=R0[c0],O0=c0===R0.length-1,L0=(G=b.getCacheControl(Y0.providerOptions,{type:"user message part",canCache:!0}))!=null?G:O0?b.getCacheControl(P0.providerOptions,{type:"user message",canCache:!0}):void 0;switch(Y0.type){case"text":{X0.push({type:"text",text:Y0.text,cache_control:L0});break}case"file":{if(Y0.mediaType.startsWith("image/"))X0.push({type:"image",source:$r0(Y0.data)?{type:"url",url:Zr0(Y0.data)}:{type:"base64",media_type:Y0.mediaType==="image/*"?"image/jpeg":Y0.mediaType,data:KZ(Y0.data)},cache_control:L0});else if(Y0.mediaType==="application/pdf"){m.add("pdfs-2024-09-25");let I0=await o(Y0.providerOptions),Z0=await U0(Y0.providerOptions);X0.push({type:"document",source:$r0(Y0.data)?{type:"url",url:Zr0(Y0.data)}:{type:"base64",media_type:"application/pdf",data:KZ(Y0.data)},title:(J=Z0.title)!=null?J:Y0.filename,...Z0.context&&{context:Z0.context},...I0&&{citations:{enabled:!0}},cache_control:L0})}else if(Y0.mediaType==="text/plain"){let I0=await o(Y0.providerOptions),Z0=await U0(Y0.providerOptions);X0.push({type:"document",source:$r0(Y0.data)?{type:"url",url:Zr0(Y0.data)}:{type:"text",media_type:"text/plain",data:tL4(Y0.data)},title:(K=Z0.title)!=null?K:Y0.filename,...Z0.context&&{context:Z0.context},...I0&&{citations:{enabled:!0}},cache_control:L0})}else throw new v4({functionality:`media type: ${Y0.mediaType}`});break}}}break}case"tool":{for(let c0=0;c0<R0.length;c0++){let Y0=R0[c0];if(Y0.type==="tool-approval-response")continue;let O0=Y0.output,L0="providerOptions"in O0?O0.providerOptions:O0.type==="content"?(W=O0.value.find((q0)=>q0.providerOptions!=null))==null?void 0:W.providerOptions:void 0,I0=c0===R0.length-1,Z0=(H=(F=b.getCacheControl(Y0.providerOptions,{type:"tool result part",canCache:!0}))!=null?F:b.getCacheControl(L0,{type:"tool result output",canCache:!0}))!=null?H:I0?b.getCacheControl(P0.providerOptions,{type:"tool result message",canCache:!0}):void 0,Q0;switch(O0.type){case"content":Q0=O0.value.map((q0)=>{var W0;switch(q0.type){case"text":return{type:"text",text:q0.text};case"image-data":return{type:"image",source:{type:"base64",media_type:q0.mediaType,data:q0.data}};case"image-url":return{type:"image",source:{type:"url",url:q0.url}};case"file-url":return{type:"document",source:{type:"url",url:q0.url}};case"file-data":{if(q0.mediaType==="application/pdf")return m.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:q0.mediaType,data:q0.data}};X.push({type:"other",message:`unsupported tool content part type: ${q0.type} with media type: ${q0.mediaType}`});return}case"custom":{let N0=(W0=q0.providerOptions)==null?void 0:W0.anthropic;if((N0==null?void 0:N0.type)==="tool-reference")return{type:"tool_reference",tool_name:N0.toolName};X.push({type:"other",message:"unsupported custom tool content part"});return}default:{X.push({type:"other",message:`unsupported tool content part type: ${q0.type}`});return}}}).filter(EE);break;case"text":case"error-text":Q0=O0.value;break;case"execution-denied":Q0=(N=O0.reason)!=null?N:"Tool execution denied.";break;case"json":case"error-json":default:Q0=JSON.stringify(O0.value);break}X0.push({type:"tool_result",tool_use_id:Y0.toolCallId,content:Q0,is_error:O0.type==="error-text"||O0.type==="error-json"?!0:void 0,cache_control:Z0})}break}default:throw Error(`Unsupported role: ${g0}`)}}u.push({role:"user",content:X0});break}case"assistant":{let X0=[],P0=new Set;for(let g0=0;g0<s.messages.length;g0++){let R0=s.messages[g0],c0=g0===s.messages.length-1,{content:Y0}=R0;for(let O0=0;O0<Y0.length;O0++){let L0=Y0[O0],I0=O0===Y0.length-1,Z0=(U=b.getCacheControl(L0.providerOptions,{type:"assistant message part",canCache:!0}))!=null?U:I0?b.getCacheControl(R0.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(L0.type){case"text":{let Q0=(B=L0.providerOptions)==null?void 0:B.anthropic;if((Q0==null?void 0:Q0.type)==="compaction")X0.push({type:"compaction",content:L0.text,cache_control:Z0});else X0.push({type:"text",text:a&&c0&&I0?L0.text.trim():L0.text,cache_control:Z0});break}case"reasoning":{if(Z){let Q0=await a8({provider:"anthropic",providerOptions:L0.providerOptions,schema:KL4});if(Q0!=null)if(Q0.signature!=null)b.getCacheControl(L0.providerOptions,{type:"thinking block",canCache:!1}),X0.push({type:"thinking",thinking:L0.text,signature:Q0.signature});else if(Q0.redactedData!=null)b.getCacheControl(L0.providerOptions,{type:"redacted thinking block",canCache:!1}),X0.push({type:"redacted_thinking",data:Q0.redactedData});else X.push({type:"other",message:"unsupported reasoning metadata"});else X.push({type:"other",message:"unsupported reasoning metadata"})}else X.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(L0.providerExecuted){let W0=Y.toProviderToolName(L0.toolName);if(((L=(O=L0.providerOptions)==null?void 0:O.anthropic)==null?void 0:L.type)==="mcp-tool-use"){P0.add(L0.toolCallId);let E1=(E=(w=L0.providerOptions)==null?void 0:w.anthropic)==null?void 0:E.serverName;if(E1==null||typeof E1!=="string"){X.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}X0.push({type:"mcp_tool_use",id:L0.toolCallId,name:L0.toolName,input:L0.input,server_name:E1,cache_control:Z0})}else if(W0==="code_execution"&&L0.input!=null&&typeof L0.input==="object"&&"type"in L0.input&&typeof L0.input.type==="string"&&(L0.input.type==="bash_code_execution"||L0.input.type==="text_editor_code_execution"))X0.push({type:"server_tool_use",id:L0.toolCallId,name:L0.input.type,input:L0.input,cache_control:Z0});else if(W0==="code_execution"&&L0.input!=null&&typeof L0.input==="object"&&"type"in L0.input&&L0.input.type==="programmatic-tool-call"){let{type:E1,...C0}=L0.input;X0.push({type:"server_tool_use",id:L0.toolCallId,name:"code_execution",input:C0,cache_control:Z0})}else if(W0==="code_execution"||W0==="web_fetch"||W0==="web_search")X0.push({type:"server_tool_use",id:L0.toolCallId,name:W0,input:L0.input,cache_control:Z0});else if(W0==="tool_search_tool_regex"||W0==="tool_search_tool_bm25")X0.push({type:"server_tool_use",id:L0.toolCallId,name:W0,input:L0.input,cache_control:Z0});else if(W0==="advisor")X0.push({type:"server_tool_use",id:L0.toolCallId,name:"advisor",input:{},cache_control:Z0});else X.push({type:"other",message:`provider executed tool call for tool ${L0.toolName} is not supported`});break}let Q0=(j=L0.providerOptions)==null?void 0:j.anthropic,q0=(Q0==null?void 0:Q0.caller)?(Q0.caller.type==="code_execution_20250825"||Q0.caller.type==="code_execution_20260120")&&Q0.caller.toolId?{type:Q0.caller.type,tool_id:Q0.caller.toolId}:Q0.caller.type==="direct"?{type:"direct"}:void 0:void 0;X0.push({type:"tool_use",id:L0.toolCallId,name:L0.toolName,input:L0.input,...q0&&{caller:q0},cache_control:Z0});break}case"tool-result":{let Q0=Y.toProviderToolName(L0.toolName);if(P0.has(L0.toolCallId)){let q0=L0.output;if(q0.type!=="json"&&q0.type!=="error-json"){X.push({type:"other",message:`provider executed tool result output type ${q0.type} for tool ${L0.toolName} is not supported`});break}X0.push({type:"mcp_tool_result",tool_use_id:L0.toolCallId,is_error:q0.type==="error-json",content:q0.value,cache_control:Z0})}else if(Q0==="code_execution"){let q0=L0.output;if(q0.type==="error-text"||q0.type==="error-json"){let W0={};try{if(typeof q0.value==="string")W0=JSON.parse(q0.value);else if(typeof q0.value==="object"&&q0.value!==null)W0=q0.value}catch(N0){}if(W0.type==="code_execution_tool_result_error")X0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(z=W0.errorCode)!=null?z:"unknown"},cache_control:Z0});else X0.push({type:"bash_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:Z0,content:{type:"bash_code_execution_tool_result_error",error_code:(A=W0.errorCode)!=null?A:"unknown"}});break}if(q0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${q0.type} for tool ${L0.toolName} is not supported`});break}if(q0.value==null||typeof q0.value!=="object"||!("type"in q0.value)||typeof q0.value.type!=="string"){X.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${L0.toolName}`});break}if(q0.value.type==="code_execution_result"){let W0=await g$({value:q0.value,schema:lH$});X0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:W0.type,stdout:W0.stdout,stderr:W0.stderr,return_code:W0.return_code,content:(P=W0.content)!=null?P:[]},cache_control:Z0})}else if(q0.value.type==="encrypted_code_execution_result"){let W0=await g$({value:q0.value,schema:mH$});if(W0.type==="encrypted_code_execution_result")X0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:W0.type,encrypted_stdout:W0.encrypted_stdout,stderr:W0.stderr,return_code:W0.return_code,content:(I=W0.content)!=null?I:[]},cache_control:Z0})}else{let W0=await g$({value:q0.value,schema:dH$});if(W0.type==="code_execution_result")X0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:W0.type,stdout:W0.stdout,stderr:W0.stderr,return_code:W0.return_code,content:(q=W0.content)!=null?q:[]},cache_control:Z0});else if(W0.type==="bash_code_execution_result"||W0.type==="bash_code_execution_tool_result_error")X0.push({type:"bash_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:Z0,content:W0});else X0.push({type:"text_editor_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:Z0,content:W0})}break}if(Q0==="web_fetch"){let q0=L0.output;if(q0.type==="error-json"){X0.push({type:"web_fetch_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(k=(await vH$(q0.value)).errorCode)!=null?k:"unavailable"},cache_control:Z0});break}if(q0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${q0.type} for tool ${L0.toolName} is not supported`});break}let W0=await g$({value:q0.value,schema:cH$});X0.push({type:"web_fetch_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_fetch_result",url:W0.url,retrieved_at:W0.retrievedAt,content:{type:"document",title:W0.content.title,citations:W0.content.citations,source:{type:W0.content.source.type,media_type:W0.content.source.mediaType,data:W0.content.source.data}}},cache_control:Z0});break}if(Q0==="web_search"){let q0=L0.output;if(q0.type==="error-json"){X0.push({type:"web_search_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_search_tool_result_error",error_code:(S=(await vH$(q0.value)).errorCode)!=null?S:"unavailable"},cache_control:Z0});break}if(q0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${q0.type} for tool ${L0.toolName} is not supported`});break}let W0=await g$({value:q0.value,schema:uH$});X0.push({type:"web_search_tool_result",tool_use_id:L0.toolCallId,content:W0.map((N0)=>({url:N0.url,title:N0.title,page_age:N0.pageAge,encrypted_content:N0.encryptedContent,type:N0.type})),cache_control:Z0});break}if(Q0==="tool_search_tool_regex"||Q0==="tool_search_tool_bm25"){let q0=L0.output;if(q0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${q0.type} for tool ${L0.toolName} is not supported`});break}let N0=(await g$({value:q0.value,schema:iH$})).map((E1)=>({type:"tool_reference",tool_name:E1.toolName}));X0.push({type:"tool_search_tool_result",tool_use_id:L0.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:N0},cache_control:Z0});break}if(Q0==="advisor"){let q0=L0.output;if(q0.type!=="json"&&q0.type!=="error-json"){X.push({type:"other",message:`provider executed tool result output type ${q0.type} for tool ${L0.toolName} is not supported`});break}let W0=await g$({value:q0.value,schema:hH$});if(W0.type==="advisor_result")X0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_result",text:W0.text},cache_control:Z0});else if(W0.type==="advisor_redacted_result")X0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:W0.encryptedContent},cache_control:Z0});else X0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_tool_result_error",error_code:W0.errorCode},cache_control:Z0});break}X.push({type:"other",message:`provider executed tool result for tool ${L0.toolName} is not supported`});break}}}}u.push({role:"assistant",content:X0});break}default:throw Error(`content type: ${z0}`)}}return{prompt:{system:i,messages:u},betas:m}}function aL4($){let Z=[],X=void 0;for(let Q of $){let{role:Y}=Q;switch(Y){case"system":{if((X==null?void 0:X.type)!=="system")X={type:"system",messages:[]},Z.push(X);X.messages.push(Q);break}case"assistant":{if((X==null?void 0:X.type)!=="assistant")X={type:"assistant",messages:[]},Z.push(X);X.messages.push(Q);break}case"user":{if((X==null?void 0:X.type)!=="user")X={type:"user",messages:[]},Z.push(X);X.messages.push(Q);break}case"tool":{if((X==null?void 0:X.type)!=="user")X={type:"user",messages:[]},Z.push(X);X.messages.push(Q);break}default:throw Error(`Unsupported role: ${Y}`)}}return Z}function Xr0({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 eL4($){return nH$($)}function nO($){if(typeof $==="boolean"||!Qw4($))return $;return nH$($)}function nH$($){let Z={},X=$;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(nO);else if($.oneOf!=null)Z.anyOf=$.oneOf.map(nO);if($.allOf!=null)Z.allOf=$.allOf.map(nO);if($.definitions!=null)Z.definitions=Object.fromEntries(Object.entries($.definitions).map(([Y,G])=>[Y,nO(G)]));if(X.$defs!=null){let Y=Z;Y.$defs=Object.fromEntries(Object.entries(X.$defs).map(([G,J])=>[G,nO(J)]))}if($.type==="object"||$.properties!=null){if($.properties!=null)Z.properties=Object.fromEntries(Object.entries($.properties).map(([Y,G])=>[Y,nO(G)]));if(Z.additionalProperties=!1,$.required!=null)Z.required=$.required}if($.items!=null)Z.items=Array.isArray($.items)?$.items.map(nO):nO($.items);if(typeof $.format==="string"&&pH$.has($.format))Z.format=$.format;let Q=$w4($);if(Q!=null)Z.description=Z.description==null?Q:`${Z.description}
1469
1469
  ${Q}`;return Z}function $w4($){let Z=sL4.flatMap((X)=>{let Q=$[X];if(Q==null||Q===!1)return[];return`${Zw4(X)}: ${Xw4(Q)}`});if(typeof $.format==="string"&&!pH$.has($.format))Z.push(`format: ${$.format}`);return Z.length===0?void 0:`${Z.join("; ")}.`}function Zw4($){return $.replace(/[A-Z]/g,(Z)=>` ${Z.toLowerCase()}`)}function Xw4($){if(typeof $==="string")return $;return JSON.stringify($)}function Qw4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function fH$($,Z,X){var Q;if($.type==="web_search_result_location")return{type:"source",sourceType:"url",id:X(),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:X(),mediaType:Y.mediaType,title:(Q=$.document_title)!=null?Q: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 Gw4($){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 bH$($){if(!$)return!1;let Z=!1,X=!1;for(let Q of $){if("type"in Q&&(Q.type==="web_fetch_20260209"||Q.type==="web_search_20260209")){Z=!0;continue}if(Q.name==="code_execution"){X=!0;break}}return Z&&!X}function xH$($){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 yH$($){if($==null)return;return{type:$.type,...$.category!=null?{category:$.category}:{},...$.explanation!=null?{explanation:$.explanation}:{},...$.recommended_model!=null?{recommendedModel:$.recommended_model}:{}}}function wt($={}){var Z,X;let Q=(Z=KO(LW({settingValue:$.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?Z:"https://api.anthropic.com/v1",Y=(X=$.name)!=null?X:"anthropic.messages";if($.apiKey&&$.authToken)throw new YO({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":Fy({apiKey:$.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return t4({"anthropic-version":"2023-06-01",...W,...$.headers},`ai-sdk/anthropic/${QL4}`)},J=(W)=>{var F;return new Yw4(W,{provider:Y,baseURL:Q,headers:G,fetch:$.fetch,generateId:(F=$.generateId)!=null?F:g8,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 c5({modelId:W,modelType:"embeddingModel"})},K.textEmbeddingModel=K.embeddingModel,K.imageModel=(W)=>{throw new c5({modelId:W,modelType:"imageModel"})},K.tools=kw4,K}var QL4="3.0.85",YL4,kH$,gH$,GL4,JL4,KL4,VH$,SH$,CH$=4,Gr0=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl($,Z){let X=WL4($);if(!X)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>CH$){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${CH$} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return X}getWarnings(){return this.warnings}},FL4,hH$,HL4,NL4,UL4=($)=>{return NL4($)},BL4,OL4,DL4,LL4=($={})=>{return DL4($)},wL4,EL4,jL4,zL4,PL4=($={})=>{return zL4($)},AL4,uH$,TL4,RL4,IL4=($={})=>{return RL4($)},qL4,ML4,kL4,VL4,SL4=($={})=>{return VL4($)},CL4,cH$,_L4,vL4,fL4=($={})=>{return vL4($)},lH$,xL4,yL4,gL4=($={})=>{return yL4($)},dH$,hL4,uL4,cL4=($={})=>{return uL4($)},mH$,lL4,dL4,mL4=($={})=>{return dL4($)},iH$,iL4,pL4,nL4=($={})=>{return pL4($)},pH$,sL4,Yw4=class{constructor($,Z){this.specificationVersion="v3";var X;this.modelId=$,this.config=Z,this.generateId=(X=Z.generateId)!=null?X:g8}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,X;return(X=(Z=($=this.config).supportedUrls)==null?void 0:Z.call($))!=null?X:{}}async getArgs({userSuppliedBetas:$,prompt:Z,maxOutputTokens:X,temperature:Q,topP:Y,topK:G,frequencyPenalty:J,presencePenalty:K,stopSequences:W,responseFormat:F,seed:H,tools:N,toolChoice:U,providerOptions:B,stream:O}){var L,w,E,j,z,A,P,I,q,k;let S=[];if(J!=null)S.push({type:"unsupported",feature:"frequencyPenalty"});if(K!=null)S.push({type:"unsupported",feature:"presencePenalty"});if(H!=null)S.push({type:"unsupported",feature:"seed"});if(Q!=null&&Q>1)S.push({type:"unsupported",feature:"temperature",details:`${Q} exceeds anthropic maximum of 1.0. clamped to 1.0`}),Q=1;else if(Q!=null&&Q<0)S.push({type:"unsupported",feature:"temperature",details:`${Q} is below anthropic minimum of 0. clamped to 0`}),Q=0;if((F==null?void 0:F.type)==="json"){if(F.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 a8({provider:"anthropic",providerOptions:B,schema:SH$}),b=m!=="anthropic"?await a8({provider:m,providerOptions:B,schema:SH$}):null,i=b!=null,u=Object.assign({},f!=null?f:{},b!=null?b:{}),{maxOutputTokens:o,supportsStructuredOutput:U0,rejectsSamplingParameters:E0,isKnownModel:s}=Gw4(this.modelId);if(E0){if(Q!=null)S.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),Q=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 a=s||this.modelId.startsWith("claude-"),z0=((L=this.config.supportsNativeStructuredOutput)!=null?L:!0)&&U0,X0=((w=this.config.supportsStrictTools)!=null?w:!0)&&U0,P0=(E=u==null?void 0:u.structuredOutputMode)!=null?E:"auto",g0=P0==="outputFormat"||P0==="auto"&&z0,R0=(F==null?void 0:F.type)==="json"&&F.schema!=null&&!g0?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:F.schema}:void 0,c0=u==null?void 0:u.contextManagement,Y0=new Gr0,O0=AZ0({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:L0,betas:I0}=await rL4({prompt:Z,sendReasoning:(j=u==null?void 0:u.sendReasoning)!=null?j:!0,warnings:S,cacheControlValidator:Y0,toolNameMapping:O0}),Z0=(z=u==null?void 0:u.thinking)==null?void 0:z.type,Q0=Z0==="enabled"||Z0==="adaptive",q0=Z0==="enabled"?(A=u==null?void 0:u.thinking)==null?void 0:A.budgetTokens:void 0,W0=Z0==="adaptive"?(P=u==null?void 0:u.thinking)==null?void 0:P.display:void 0,N0=X!=null?X:o,E1={model:this.modelId,max_tokens:N0,temperature:Q,top_k:G,top_p:Y,stop_sequences:W,...Q0&&{thinking:{type:Z0,...q0!=null&&{budget_tokens:q0},...W0!=null&&{display:W0}}},...((u==null?void 0:u.effort)||(u==null?void 0:u.taskBudget)||g0&&(F==null?void 0:F.type)==="json"&&F.schema!=null)&&{output_config:{...(u==null?void 0:u.effort)&&{effort:u.effort},...(u==null?void 0:u.taskBudget)&&{task_budget:{type:u.taskBudget.type,total:u.taskBudget.total,...u.taskBudget.remaining!=null&&{remaining:u.taskBudget.remaining}}},...g0&&(F==null?void 0:F.type)==="json"&&F.schema!=null&&{format:{type:"json_schema",schema:eL4(F.schema)}}}},...(u==null?void 0:u.speed)&&{speed:u.speed},...(u==null?void 0:u.inferenceGeo)&&{inference_geo:u.inferenceGeo},...(u==null?void 0:u.fallbacks)&&u.fallbacks.length>0&&{fallbacks:u.fallbacks},...(u==null?void 0:u.cacheControl)&&{cache_control:u.cacheControl},...((I=u==null?void 0:u.metadata)==null?void 0:I.userId)!=null&&{metadata:{user_id:u.metadata.userId}},...(u==null?void 0:u.mcpServers)&&u.mcpServers.length>0&&{mcp_servers:u.mcpServers.map((S0)=>({type:S0.type,name:S0.name,url:S0.url,authorization_token:S0.authorizationToken,tool_configuration:S0.toolConfiguration?{allowed_tools:S0.toolConfiguration.allowedTools,enabled:S0.toolConfiguration.enabled}:void 0}))},...(u==null?void 0:u.container)&&{container:u.container.skills&&u.container.skills.length>0?{id:u.container.id,skills:u.container.skills.map((S0)=>({type:S0.type,skill_id:S0.skillId,version:S0.version}))}:u.container.id},system:L0.system,messages:L0.messages,...c0&&{context_management:{edits:c0.edits.map((S0)=>{let g1=S0.type;switch(g1){case"clear_tool_uses_20250919":return{type:S0.type,...S0.trigger!==void 0&&{trigger:S0.trigger},...S0.keep!==void 0&&{keep:S0.keep},...S0.clearAtLeast!==void 0&&{clear_at_least:S0.clearAtLeast},...S0.clearToolInputs!==void 0&&{clear_tool_inputs:S0.clearToolInputs},...S0.excludeTools!==void 0&&{exclude_tools:S0.excludeTools}};case"clear_thinking_20251015":return{type:S0.type,...S0.keep!==void 0&&{keep:S0.keep}};case"compact_20260112":return{type:S0.type,...S0.trigger!==void 0&&{trigger:S0.trigger},...S0.pauseAfterCompaction!==void 0&&{pause_after_compaction:S0.pauseAfterCompaction},...S0.instructions!==void 0&&{instructions:S0.instructions}};default:S.push({type:"other",message:`Unknown context management strategy: ${g1}`});return}}).filter((S0)=>S0!==void 0)}}};if(Q0){if(Z0==="enabled"&&q0==null)S.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),E1.thinking={type:"enabled",budget_tokens:1024},q0=1024;if(E1.temperature!=null)E1.temperature=void 0,S.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(G!=null)E1.top_k=void 0,S.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(Y!=null)E1.top_p=void 0,S.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});E1.max_tokens=N0+(q0!=null?q0:0)}else if(a&&Y!=null&&Q!=null)S.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),E1.top_p=void 0;if(s&&E1.max_tokens>o){if(X!=null)S.push({type:"unsupported",feature:"maxOutputTokens",details:`${E1.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${o} max output tokens. The max output tokens have been limited to ${o}.`});E1.max_tokens=o}if((u==null?void 0:u.mcpServers)&&u.mcpServers.length>0)I0.add("mcp-client-2025-04-04");if(c0){if(I0.add("context-management-2025-06-27"),c0.edits.some((S0)=>S0.type==="compact_20260112"))I0.add("compact-2026-01-12")}if((u==null?void 0:u.container)&&u.container.skills&&u.container.skills.length>0){if(I0.add("code-execution-2025-08-25"),I0.add("skills-2025-10-02"),I0.add("files-api-2025-04-14"),!(N==null?void 0:N.some((S0)=>S0.type==="provider"&&(S0.id==="anthropic.code_execution_20250825"||S0.id==="anthropic.code_execution_20260120"))))S.push({type:"other",message:"code execution tool is required when using skills"})}if(u==null?void 0:u.taskBudget)I0.add("task-budgets-2026-03-13");if((u==null?void 0:u.speed)==="fast")I0.add("fast-mode-2026-02-01");if((u==null?void 0:u.fallbacks)&&u.fallbacks.length>0)I0.add("server-side-fallback-2026-06-01");let C0=O&&((q=u==null?void 0:u.toolStreaming)!=null?q:!0),{tools:i0,toolChoice:n,toolWarnings:v0,betas:$1}=await bL4(R0!=null?{tools:[...N!=null?N:[],R0],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:Y0,supportsStructuredOutput:!1,supportsStrictTools:X0,defaultEagerInputStreaming:C0}:{tools:N!=null?N:[],toolChoice:U,disableParallelToolUse:u==null?void 0:u.disableParallelToolUse,cacheControlValidator:Y0,supportsStructuredOutput:z0,supportsStrictTools:X0,defaultEagerInputStreaming:C0}),q1=Y0.getWarnings();return{args:{...E1,tools:i0,tool_choice:n,stream:O===!0?!0:void 0},warnings:[...S,...v0,...q1],betas:new Set([...I0,...$1,...$,...(k=u==null?void 0:u.anthropicBeta)!=null?k:[]]),usesJsonResponseTool:R0!=null,toolNameMapping:O0,providerOptionsName:m,usedCustomProviderKey:i}}async getHeaders({betas:$,headers:Z}){return r$(await f$(this.config.headers),Z,$.size>0?{"anthropic-beta":Array.from($).join(",")}:{})}async getBetasFromHeaders($){var Z,X;let Y=(Z=(await f$(this.config.headers))["anthropic-beta"])!=null?Z:"",G=(X=$==null?void 0:$["anthropic-beta"])!=null?X:"";return new Set([...Y.toLowerCase().split(","),...G.toLowerCase().split(",")].map((J)=>J.trim()).filter((J)=>J!==""))}buildRequestUrl($){var Z,X,Q;return(Q=(X=(Z=this.config).buildRequestUrl)==null?void 0:X.call(Z,this.config.baseURL,$))!=null?Q:`${this.config.baseURL}/messages`}transformRequestBody($,Z){var X,Q,Y;return(Y=(Q=(X=this.config).transformRequestBody)==null?void 0:Q.call(X,$,Z))!=null?Y:$}extractCitationDocuments($){let Z=(X)=>{var Q,Y;if(X.type!=="file")return!1;if(X.mediaType!=="application/pdf"&&X.mediaType!=="text/plain")return!1;let G=(Q=X.providerOptions)==null?void 0:Q.anthropic,J=G==null?void 0:G.citations;return(Y=J==null?void 0:J.enabled)!=null?Y:!1};return $.filter((X)=>X.role==="user").flatMap((X)=>X.content).filter(Z).map((X)=>{var Q;let Y=X;return{title:(Q=Y.filename)!=null?Q:"Untitled Document",filename:Y.filename,mediaType:Y.mediaType}})}async doGenerate($){var Z,X,Q,Y,G,J,K;let{args:W,warnings:F,betas:H,usesJsonResponseTool:N,toolNameMapping:U,providerOptionsName:B,usedCustomProviderKey:O}=await this.getArgs({...$,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders($.headers)}),L=[...this.extractCitationDocuments($.prompt)],w=bH$(W.tools),{responseHeaders:E,value:j,rawValue:z}=await O8({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:H,headers:$.headers}),body:this.transformRequestBody(W,H),failedResponseHandler:kH$,successfulResponseHandler:Z8(GL4),abortSignal:$.abortSignal,fetch:this.config.fetch}),A=[],P={},I={},q=!1;for(let k of j.content)switch(k.type){case"text":{if(!N){if(A.push({type:"text",text:k.text}),k.citations)for(let S of k.citations){let m=fH$(S,L,this.generateId);if(m)A.push(m)}}break}case"thinking":{A.push({type:"reasoning",text:k.thinking,providerMetadata:{anthropic:{signature:k.signature}}});break}case"redacted_thinking":{A.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:k.data}}});break}case"compaction":{A.push({type:"text",text:k.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(N&&k.name==="json")q=!0,A.push({type:"text",text:JSON.stringify(k.input)});else{let m=k.caller,f=m?{type:m.type,toolId:"tool_id"in m?m.tool_id:void 0}:void 0;A.push({type:"tool-call",toolCallId:k.id,toolName:k.name,input:JSON.stringify(k.input),...f&&{providerMetadata:{anthropic:{caller:f}}}})}break}case"server_tool_use":{if(k.name==="text_editor_code_execution"||k.name==="bash_code_execution")A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName("code_execution"),input:JSON.stringify({type:k.name,...k.input}),providerExecuted:!0,...w?{dynamic:!0}:{}});else if(k.name==="web_search"||k.name==="code_execution"||k.name==="web_fetch"){let S=k.name==="code_execution"&&k.input!=null&&typeof k.input==="object"&&"code"in k.input&&!("type"in k.input)?{type:"programmatic-tool-call",...k.input}:k.input;A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName(k.name),input:JSON.stringify(S),providerExecuted:!0,...w&&k.name==="code_execution"?{dynamic:!0}:{}})}else if(k.name==="tool_search_tool_regex"||k.name==="tool_search_tool_bm25")I[k.id]=k.name,A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName(k.name),input:JSON.stringify(k.input),providerExecuted:!0});else if(k.name==="advisor")A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName("advisor"),input:JSON.stringify(k.input),providerExecuted:!0});break}case"mcp_tool_use":{P[k.id]={type:"tool-call",toolCallId:k.id,toolName:k.name,input:JSON.stringify(k.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:k.server_name}}},A.push(P[k.id]);break}case"mcp_tool_result":{A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:P[k.tool_use_id].toolName,isError:k.is_error,result:k.content,dynamic:!0,providerMetadata:P[k.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{if(k.content.type==="web_fetch_result")L.push({title:(Z=k.content.content.title)!=null?Z:k.content.url,mediaType:k.content.content.source.media_type}),A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:k.content.url,retrievedAt:k.content.retrieved_at,content:{type:k.content.content.type,title:k.content.content.title,citations:k.content.content.citations,source:{type:k.content.content.source.type,mediaType:k.content.content.source.media_type,data:k.content.content.source.data}}}});else if(k.content.type==="web_fetch_tool_result_error")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:k.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(k.content)){A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_search"),result:k.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 k.content)A.push({type:"source",sourceType:"url",id:this.generateId(),url:S.url,title:S.title,providerMetadata:{anthropic:{pageAge:(X=S.page_age)!=null?X:null}}})}else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:k.content.error_code}});break}case"code_execution_tool_result":{if(k.content.type==="code_execution_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:{type:k.content.type,stdout:k.content.stdout,stderr:k.content.stderr,return_code:k.content.return_code,content:(Q=k.content.content)!=null?Q:[]}});else if(k.content.type==="encrypted_code_execution_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:{type:k.content.type,encrypted_stdout:k.content.encrypted_stdout,stderr:k.content.stderr,return_code:k.content.return_code,content:(Y=k.content.content)!=null?Y:[]}});else if(k.content.type==="code_execution_tool_result_error")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:k.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:k.content});break}case"tool_search_tool_result":{let S=I[k.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(k.content.type==="tool_search_tool_search_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName(S),result:k.content.tool_references.map((m)=>({type:m.type,toolName:m.tool_name}))});else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName(S),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:k.content.error_code}});break}case"advisor_tool_result":{let S=U.toCustomToolName("advisor");if(k.content.type==="advisor_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:S,result:{type:"advisor_result",text:k.content.text}});else if(k.content.type==="advisor_redacted_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:S,result:{type:"advisor_redacted_result",encryptedContent:k.content.encrypted_content}});else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:S,isError:!0,result:{type:"advisor_tool_result_error",errorCode:k.content.error_code}});break}case"fallback":break}return{content:A,finishReason:{unified:Xr0({finishReason:j.stop_reason,isJsonResponseFromTool:q}),raw:(G=j.stop_reason)!=null?G:void 0},usage:_H$({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:F,providerMetadata:(()=>{var k,S,m,f,b;let i=yH$(j.stop_details),u={usage:j.usage,cacheCreationInputTokens:(k=j.usage.cache_creation_input_tokens)!=null?k:null,stopSequence:(S=j.stop_sequence)!=null?S:null,...i!=null?{stopDetails:i}:{},iterations:j.usage.iterations?j.usage.iterations.map((U0)=>({type:U0.type,...U0.model!=null?{model:U0.model}:{},inputTokens:U0.input_tokens,outputTokens:U0.output_tokens,...U0.cache_creation_input_tokens?{cacheCreationInputTokens:U0.cache_creation_input_tokens}:{},...U0.cache_read_input_tokens?{cacheReadInputTokens:U0.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((U0)=>({type:U0.type,skillId:U0.skill_id,version:U0.version})))!=null?f:null}:null,contextManagement:(b=xH$(j.context_management))!=null?b:null},o={anthropic:u};if(O&&B!=="anthropic")o[B]=u;return o})()}}async doStream($){var Z,X;let{args:Q,warnings:Y,betas:G,usesJsonResponseTool:J,toolNameMapping:K,providerOptionsName:W,usedCustomProviderKey:F}=await this.getArgs({...$,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders($.headers)}),H=[...this.extractCitationDocuments($.prompt)],N=bH$(Q.tools),U=this.buildRequestUrl(!0),{responseHeaders:B,value:O}=await O8({url:U,headers:await this.getHeaders({betas:G,headers:$.headers}),body:this.transformRequestBody(Q,G),failedResponseHandler:kH$,successfulResponseHandler:e7(JL4),abortSignal:$.abortSignal,fetch:this.config.fetch}),L={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,k=void 0,S=null,m=!1,f=void 0,b=this.generateId,i=O.pipeThrough(new TransformStream({start(E0){E0.enqueue({type:"stream-start",warnings:Y})},transform(E0,s){var a,z0,X0,P0,g0,R0,c0,Y0,O0,L0,I0,Z0,Q0,q0;if($.includeRawChunks)s.enqueue({type:"raw",rawValue:E0.rawValue});if(!E0.success){s.enqueue({type:"error",error:E0.error});return}let W0=E0.value;switch(W0.type){case"ping":return;case"content_block_start":{let N0=W0.content_block,E1=N0.type;if(E1==="fallback")return;switch(f=E1,E1){case"text":{if(J)return;E[W0.index]={type:"text"},s.enqueue({type:"text-start",id:String(W0.index)});return}case"thinking":{E[W0.index]={type:"reasoning"},s.enqueue({type:"reasoning-start",id:String(W0.index)});return}case"redacted_thinking":{E[W0.index]={type:"reasoning"},s.enqueue({type:"reasoning-start",id:String(W0.index),providerMetadata:{anthropic:{redactedData:N0.data}}});return}case"compaction":{E[W0.index]={type:"text"},s.enqueue({type:"text-start",id:String(W0.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(J&&N0.name==="json")m=!0,E[W0.index]={type:"text"},s.enqueue({type:"text-start",id:String(W0.index)});else{let i0=N0.caller,n=i0?{type:i0.type,toolId:"tool_id"in i0?i0.tool_id:void 0}:void 0,$1=N0.input&&Object.keys(N0.input).length>0?JSON.stringify(N0.input):"";E[W0.index]={type:"tool-call",toolCallId:N0.id,toolName:N0.name,input:$1,firstDelta:$1.length===0,...n&&{caller:n}},s.enqueue({type:"tool-input-start",id:N0.id,toolName:N0.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(N0.name)){let C0=N0.name==="text_editor_code_execution"||N0.name==="bash_code_execution"?"code_execution":N0.name,i0=K.toCustomToolName(C0),n=N0.input!=null&&typeof N0.input==="object"&&Object.keys(N0.input).length>0?JSON.stringify(N0.input):"";E[W0.index]={type:"tool-call",toolCallId:N0.id,toolName:i0,input:n,providerExecuted:!0,...N&&C0==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:C0},s.enqueue({type:"tool-input-start",id:N0.id,toolName:i0,providerExecuted:!0,...N&&C0==="code_execution"?{dynamic:!0}:{}})}else if(N0.name==="tool_search_tool_regex"||N0.name==="tool_search_tool_bm25"){z[N0.id]=N0.name;let C0=K.toCustomToolName(N0.name);E[W0.index]={type:"tool-call",toolCallId:N0.id,toolName:C0,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:N0.name},s.enqueue({type:"tool-input-start",id:N0.id,toolName:C0,providerExecuted:!0})}else if(N0.name==="advisor"){let C0=K.toCustomToolName("advisor");E[W0.index]={type:"tool-call",toolCallId:N0.id,toolName:C0,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:N0.name},s.enqueue({type:"tool-input-start",id:N0.id,toolName:C0,providerExecuted:!0})}return}case"web_fetch_tool_result":{if(N0.content.type==="web_fetch_result")H.push({title:(a=N0.content.content.title)!=null?a:N0.content.url,mediaType:N0.content.content.source.media_type}),s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:N0.content.url,retrievedAt:N0.content.retrieved_at,content:{type:N0.content.content.type,title:N0.content.content.title,citations:N0.content.content.citations,source:{type:N0.content.content.source.type,mediaType:N0.content.content.source.media_type,data:N0.content.content.source.data}}}});else if(N0.content.type==="web_fetch_tool_result_error")s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:N0.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(N0.content)){s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName("web_search"),result:N0.content.map((C0)=>{var i0;return{url:C0.url,title:C0.title,pageAge:(i0=C0.page_age)!=null?i0:null,encryptedContent:C0.encrypted_content,type:C0.type}})});for(let C0 of N0.content)s.enqueue({type:"source",sourceType:"url",id:b(),url:C0.url,title:C0.title,providerMetadata:{anthropic:{pageAge:(z0=C0.page_age)!=null?z0:null}}})}else s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:N0.content.error_code}});return}case"code_execution_tool_result":{if(N0.content.type==="code_execution_result")s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName("code_execution"),result:{type:N0.content.type,stdout:N0.content.stdout,stderr:N0.content.stderr,return_code:N0.content.return_code,content:(X0=N0.content.content)!=null?X0:[]}});else if(N0.content.type==="encrypted_code_execution_result")s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName("code_execution"),result:{type:N0.content.type,encrypted_stdout:N0.content.encrypted_stdout,stderr:N0.content.stderr,return_code:N0.content.return_code,content:(P0=N0.content.content)!=null?P0:[]}});else if(N0.content.type==="code_execution_tool_result_error")s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:N0.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName("code_execution"),result:N0.content});return}case"tool_search_tool_result":{let C0=z[N0.tool_use_id];if(C0==null){let i0=K.toCustomToolName("tool_search_tool_bm25"),n=K.toCustomToolName("tool_search_tool_regex");if(i0!=="tool_search_tool_bm25")C0="tool_search_tool_bm25";else if(n!=="tool_search_tool_regex")C0="tool_search_tool_regex";else C0="tool_search_tool_regex"}if(N0.content.type==="tool_search_tool_search_result")s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName(C0),result:N0.content.tool_references.map((i0)=>({type:i0.type,toolName:i0.tool_name}))});else s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:K.toCustomToolName(C0),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:N0.content.error_code}});return}case"advisor_tool_result":{let C0=K.toCustomToolName("advisor");if(N0.content.type==="advisor_result")s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:C0,result:{type:"advisor_result",text:N0.content.text}});else if(N0.content.type==="advisor_redacted_result")s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:C0,result:{type:"advisor_redacted_result",encryptedContent:N0.content.encrypted_content}});else s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:C0,isError:!0,result:{type:"advisor_tool_result_error",errorCode:N0.content.error_code}});return}case"mcp_tool_use":{j[N0.id]={type:"tool-call",toolCallId:N0.id,toolName:N0.name,input:JSON.stringify(N0.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:N0.server_name}}},s.enqueue(j[N0.id]);return}case"mcp_tool_result":{s.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:j[N0.tool_use_id].toolName,isError:N0.is_error,result:N0.content,dynamic:!0,providerMetadata:j[N0.tool_use_id].providerMetadata});return}default:throw Error(`Unsupported content block type: ${E1}`)}}case"content_block_stop":{if(E[W0.index]!=null){let N0=E[W0.index];switch(N0.type){case"text":{s.enqueue({type:"text-end",id:String(W0.index)});break}case"reasoning":{s.enqueue({type:"reasoning-end",id:String(W0.index)});break}case"tool-call":if(!(J&&N0.toolName==="json")){s.enqueue({type:"tool-input-end",id:N0.toolCallId});let C0=N0.input===""?"{}":N0.input;if(N0.providerToolName==="code_execution")try{let i0=JSON.parse(C0);if(i0!=null&&typeof i0==="object"&&"code"in i0&&!("type"in i0))C0=JSON.stringify({type:"programmatic-tool-call",...i0})}catch(i0){}s.enqueue({type:"tool-call",toolCallId:N0.toolCallId,toolName:N0.toolName,input:C0,providerExecuted:N0.providerExecuted,...N&&N0.providerToolName==="code_execution"?{dynamic:!0}:{},...N0.caller&&{providerMetadata:{anthropic:{caller:N0.caller}}}})}break}delete E[W0.index]}f=void 0;return}case"content_block_delta":{let N0=W0.delta.type;switch(N0){case"text_delta":{if(J)return;s.enqueue({type:"text-delta",id:String(W0.index),delta:W0.delta.text});return}case"thinking_delta":{s.enqueue({type:"reasoning-delta",id:String(W0.index),delta:W0.delta.thinking});return}case"signature_delta":{if(f==="thinking")s.enqueue({type:"reasoning-delta",id:String(W0.index),delta:"",providerMetadata:{anthropic:{signature:W0.delta.signature}}});return}case"compaction_delta":{if(W0.delta.content!=null)s.enqueue({type:"text-delta",id:String(W0.index),delta:W0.delta.content});return}case"input_json_delta":{let E1=E[W0.index],C0=W0.delta.partial_json;if(C0.length===0)return;if(m){if((E1==null?void 0:E1.type)!=="text")return;s.enqueue({type:"text-delta",id:String(W0.index),delta:C0})}else{if((E1==null?void 0:E1.type)!=="tool-call")return;if(E1.firstDelta&&E1.providerToolName==="code_execution")C0=`{"type": "programmatic-tool-call",${C0.substring(1)}`;s.enqueue({type:"tool-input-delta",id:E1.toolCallId,delta:C0}),E1.input+=C0,E1.firstDelta=!1}return}case"citations_delta":{let E1=W0.delta.citation,C0=fH$(E1,H,b);if(C0)s.enqueue(C0);return}default:throw Error(`Unsupported delta type: ${N0}`)}}case"message_start":{if(w.input_tokens=W0.message.usage.input_tokens,w.cache_read_input_tokens=(g0=W0.message.usage.cache_read_input_tokens)!=null?g0:0,w.cache_creation_input_tokens=(R0=W0.message.usage.cache_creation_input_tokens)!=null?R0:0,P={...W0.message.usage},I=(c0=W0.message.usage.cache_creation_input_tokens)!=null?c0:null,W0.message.container!=null)S={expiresAt:W0.message.container.expires_at,id:W0.message.container.id,skills:null};if(W0.message.stop_reason!=null)L={unified:Xr0({finishReason:W0.message.stop_reason,isJsonResponseFromTool:m}),raw:W0.message.stop_reason};if(s.enqueue({type:"response-metadata",id:(Y0=W0.message.id)!=null?Y0:void 0,modelId:(O0=W0.message.model)!=null?O0:void 0}),W0.message.content!=null)for(let N0=0;N0<W0.message.content.length;N0++){let E1=W0.message.content[N0];if(E1.type==="tool_use"){let C0=E1.caller,i0=C0?{type:C0.type,toolId:"tool_id"in C0?C0.tool_id:void 0}:void 0;s.enqueue({type:"tool-input-start",id:E1.id,toolName:E1.name});let n=JSON.stringify((L0=E1.input)!=null?L0:{});s.enqueue({type:"tool-input-delta",id:E1.id,delta:n}),s.enqueue({type:"tool-input-end",id:E1.id}),s.enqueue({type:"tool-call",toolCallId:E1.id,toolName:E1.name,input:n,...i0&&{providerMetadata:{anthropic:{caller:i0}}}})}}return}case"message_delta":{if(W0.usage.input_tokens!=null&&w.input_tokens!==W0.usage.input_tokens)w.input_tokens=W0.usage.input_tokens;if(w.output_tokens=W0.usage.output_tokens,W0.usage.cache_read_input_tokens!=null)w.cache_read_input_tokens=W0.usage.cache_read_input_tokens;if(W0.usage.cache_creation_input_tokens!=null)w.cache_creation_input_tokens=W0.usage.cache_creation_input_tokens,I=W0.usage.cache_creation_input_tokens;if(W0.usage.iterations!=null)w.iterations=W0.usage.iterations;if(L={unified:Xr0({finishReason:W0.delta.stop_reason,isJsonResponseFromTool:m}),raw:(I0=W0.delta.stop_reason)!=null?I0:void 0},q=(Z0=W0.delta.stop_sequence)!=null?Z0:null,k=yH$(W0.delta.stop_details),S=W0.delta.container!=null?{expiresAt:W0.delta.container.expires_at,id:W0.delta.container.id,skills:(q0=(Q0=W0.delta.container.skills)==null?void 0:Q0.map((N0)=>({type:N0.type,skillId:N0.skill_id,version:N0.version})))!=null?q0:null}:null,W0.context_management)A=xH$(W0.context_management);P={...P,...W0.usage};return}case"message_stop":{let N0={usage:P!=null?P:null,cacheCreationInputTokens:I,stopSequence:q,...k!=null?{stopDetails:k}:{},iterations:w.iterations?w.iterations.map((C0)=>({type:C0.type,...C0.model!=null?{model:C0.model}:{},inputTokens:C0.input_tokens,outputTokens:C0.output_tokens,...C0.cache_creation_input_tokens?{cacheCreationInputTokens:C0.cache_creation_input_tokens}:{},...C0.cache_read_input_tokens?{cacheReadInputTokens:C0.cache_read_input_tokens}:{}})):null,container:S,contextManagement:A},E1={anthropic:N0};if(F&&W!=="anthropic")E1[W]=N0;s.enqueue({type:"finish",finishReason:L,usage:_H$({usage:w,rawUsage:P}),providerMetadata:E1});return}case"error":{s.enqueue({type:"error",error:W0.error});return}default:throw Error(`Unsupported chunk type: ${W0}`)}}})),[u,o]=i.tee(),U0=u.getReader();try{await U0.read();let E0=await U0.read();if(((Z=E0.value)==null?void 0:Z.type)==="raw")E0=await U0.read();if(((X=E0.value)==null?void 0:X.type)==="error"){let s=E0.value.error;throw new Q4({message:s.message,url:U,requestBodyValues:Q,statusCode:s.type==="overloaded_error"?529:500,responseHeaders:B,responseBody:JSON.stringify(s),isRetryable:s.type==="overloaded_error"})}}finally{U0.cancel().catch(()=>{}),U0.releaseLock()}return{stream:o,request:{body:Q},response:{headers:B}}}},Jw4,Kw4,Ww4,Fw4,Hw4,Nw4,Uw4,Bw4,Ow4,Dw4,Lw4,ww4,Ew4,jw4,zw4,Pw4,Aw4,Tw4,Rw4,Iw4,qw4,Mw4=($={})=>{return qw4($)},kw4,Ef9;var Jr0=D(()=>{a1();y0();a1();y0();y0();y0();a1();y0();y0();y0();y0();y0();y0();y0();a1();y0();y0();y0();y0();y0();y0();y0();y0();y0();y0();y0();y0();y0();y0();y0();YL4=B0(()=>$0(Dt.object({type:Dt.literal("error"),error:Dt.object({type:Dt.string(),message:Dt.string()})}))),kH$=V5({errorSchema:YL4,errorToMessage:($)=>$.error.message}),gH$=M.object({type:M.string(),category:M.string().nullish(),explanation:M.string().nullish(),recommended_model:M.string().nullish()}),GL4=B0(()=>$0(M.object({type:M.literal("message"),id:M.string().nullish(),model:M.string().nullish(),content:M.array(M.discriminatedUnion("type",[M.object({type:M.literal("text"),text:M.string(),citations:M.array(M.discriminatedUnion("type",[M.object({type:M.literal("web_search_result_location"),cited_text:M.string(),url:M.string(),title:M.string(),encrypted_index:M.string()}),M.object({type:M.literal("page_location"),cited_text:M.string(),document_index:M.number(),document_title:M.string().nullable(),start_page_number:M.number(),end_page_number:M.number()}),M.object({type:M.literal("char_location"),cited_text:M.string(),document_index:M.number(),document_title:M.string().nullable(),start_char_index:M.number(),end_char_index:M.number()})])).optional()}),M.object({type:M.literal("thinking"),thinking:M.string(),signature:M.string()}),M.object({type:M.literal("redacted_thinking"),data:M.string()}),M.object({type:M.literal("compaction"),content:M.string()}),M.object({type:M.literal("tool_use"),id:M.string(),name:M.string(),input:M.unknown(),caller:M.union([M.object({type:M.literal("code_execution_20250825"),tool_id:M.string()}),M.object({type:M.literal("code_execution_20260120"),tool_id:M.string()}),M.object({type:M.literal("direct")})]).optional()}),M.object({type:M.literal("server_tool_use"),id:M.string(),name:M.string(),input:M.record(M.string(),M.unknown()).nullish(),caller:M.union([M.object({type:M.literal("code_execution_20260120"),tool_id:M.string()}),M.object({type:M.literal("direct")})]).optional()}),M.object({type:M.literal("mcp_tool_use"),id:M.string(),name:M.string(),input:M.unknown(),server_name:M.string()}),M.object({type:M.literal("mcp_tool_result"),tool_use_id:M.string(),is_error:M.boolean(),content:M.array(M.union([M.string(),M.object({type:M.literal("text"),text:M.string()})]))}),M.object({type:M.literal("web_fetch_tool_result"),tool_use_id:M.string(),content:M.union([M.object({type:M.literal("web_fetch_result"),url:M.string(),retrieved_at:M.string(),content:M.object({type:M.literal("document"),title:M.string().nullable(),citations:M.object({enabled:M.boolean()}).optional(),source:M.union([M.object({type:M.literal("base64"),media_type:M.literal("application/pdf"),data:M.string()}),M.object({type:M.literal("text"),media_type:M.literal("text/plain"),data:M.string()})])})}),M.object({type:M.literal("web_fetch_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("web_search_tool_result"),tool_use_id:M.string(),content:M.union([M.array(M.object({type:M.literal("web_search_result"),url:M.string(),title:M.string(),encrypted_content:M.string(),page_age:M.string().nullish()})),M.object({type:M.literal("web_search_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("code_execution_tool_result"),tool_use_id:M.string(),content:M.union([M.object({type:M.literal("code_execution_result"),stdout:M.string(),stderr:M.string(),return_code:M.number(),content:M.array(M.object({type:M.literal("code_execution_output"),file_id:M.string()})).optional().default([])}),M.object({type:M.literal("encrypted_code_execution_result"),encrypted_stdout:M.string(),stderr:M.string(),return_code:M.number(),content:M.array(M.object({type:M.literal("code_execution_output"),file_id:M.string()})).optional().default([])}),M.object({type:M.literal("code_execution_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("bash_code_execution_tool_result"),tool_use_id:M.string(),content:M.discriminatedUnion("type",[M.object({type:M.literal("bash_code_execution_result"),content:M.array(M.object({type:M.literal("bash_code_execution_output"),file_id:M.string()})),stdout:M.string(),stderr:M.string(),return_code:M.number()}),M.object({type:M.literal("bash_code_execution_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("text_editor_code_execution_tool_result"),tool_use_id:M.string(),content:M.discriminatedUnion("type",[M.object({type:M.literal("text_editor_code_execution_tool_result_error"),error_code:M.string()}),M.object({type:M.literal("text_editor_code_execution_view_result"),content:M.string(),file_type:M.string(),num_lines:M.number().nullable(),start_line:M.number().nullable(),total_lines:M.number().nullable()}),M.object({type:M.literal("text_editor_code_execution_create_result"),is_file_update:M.boolean()}),M.object({type:M.literal("text_editor_code_execution_str_replace_result"),lines:M.array(M.string()).nullable(),new_lines:M.number().nullable(),new_start:M.number().nullable(),old_lines:M.number().nullable(),old_start:M.number().nullable()})])}),M.object({type:M.literal("tool_search_tool_result"),tool_use_id:M.string(),content:M.union([M.object({type:M.literal("tool_search_tool_search_result"),tool_references:M.array(M.object({type:M.literal("tool_reference"),tool_name:M.string()}))}),M.object({type:M.literal("tool_search_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("advisor_tool_result"),tool_use_id:M.string(),content:M.discriminatedUnion("type",[M.object({type:M.literal("advisor_result"),text:M.string()}),M.object({type:M.literal("advisor_redacted_result"),encrypted_content:M.string()}),M.object({type:M.literal("advisor_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("fallback")})])),stop_reason:M.string().nullish(),stop_sequence:M.string().nullish(),stop_details:gH$.nullish(),usage:M.looseObject({input_tokens:M.number(),output_tokens:M.number(),cache_creation_input_tokens:M.number().nullish(),cache_read_input_tokens:M.number().nullish(),iterations:M.array(M.object({type:M.union([M.literal("compaction"),M.literal("message"),M.literal("advisor_message"),M.literal("fallback_message")]),model:M.string().nullish(),input_tokens:M.number(),output_tokens:M.number(),cache_creation_input_tokens:M.number().nullish(),cache_read_input_tokens:M.number().nullish()})).nullish()}),container:M.object({expires_at:M.string(),id:M.string(),skills:M.array(M.object({type:M.union([M.literal("anthropic"),M.literal("custom")]),skill_id:M.string(),version:M.string()})).nullish()}).nullish(),context_management:M.object({applied_edits:M.array(M.union([M.object({type:M.literal("clear_tool_uses_20250919"),cleared_tool_uses:M.number(),cleared_input_tokens:M.number()}),M.object({type:M.literal("clear_thinking_20251015"),cleared_thinking_turns:M.number(),cleared_input_tokens:M.number()}),M.object({type:M.literal("compact_20260112")})]))}).nullish()}))),JL4=B0(()=>$0(M.discriminatedUnion("type",[M.object({type:M.literal("message_start"),message:M.object({id:M.string().nullish(),model:M.string().nullish(),role:M.string().nullish(),usage:M.looseObject({input_tokens:M.number(),cache_creation_input_tokens:M.number().nullish(),cache_read_input_tokens:M.number().nullish()}),content:M.array(M.discriminatedUnion("type",[M.object({type:M.literal("tool_use"),id:M.string(),name:M.string(),input:M.unknown(),caller:M.union([M.object({type:M.literal("code_execution_20250825"),tool_id:M.string()}),M.object({type:M.literal("code_execution_20260120"),tool_id:M.string()}),M.object({type:M.literal("direct")})]).optional()})])).nullish(),stop_reason:M.string().nullish(),container:M.object({expires_at:M.string(),id:M.string()}).nullish()})}),M.object({type:M.literal("content_block_start"),index:M.number(),content_block:M.discriminatedUnion("type",[M.object({type:M.literal("text"),text:M.string()}),M.object({type:M.literal("thinking"),thinking:M.string()}),M.object({type:M.literal("tool_use"),id:M.string(),name:M.string(),input:M.record(M.string(),M.unknown()).optional(),caller:M.union([M.object({type:M.literal("code_execution_20250825"),tool_id:M.string()}),M.object({type:M.literal("code_execution_20260120"),tool_id:M.string()}),M.object({type:M.literal("direct")})]).optional()}),M.object({type:M.literal("redacted_thinking"),data:M.string()}),M.object({type:M.literal("compaction"),content:M.string().nullish()}),M.object({type:M.literal("server_tool_use"),id:M.string(),name:M.string(),input:M.record(M.string(),M.unknown()).nullish(),caller:M.union([M.object({type:M.literal("code_execution_20260120"),tool_id:M.string()}),M.object({type:M.literal("direct")})]).optional()}),M.object({type:M.literal("mcp_tool_use"),id:M.string(),name:M.string(),input:M.unknown(),server_name:M.string()}),M.object({type:M.literal("mcp_tool_result"),tool_use_id:M.string(),is_error:M.boolean(),content:M.array(M.union([M.string(),M.object({type:M.literal("text"),text:M.string()})]))}),M.object({type:M.literal("web_fetch_tool_result"),tool_use_id:M.string(),content:M.union([M.object({type:M.literal("web_fetch_result"),url:M.string(),retrieved_at:M.string(),content:M.object({type:M.literal("document"),title:M.string().nullable(),citations:M.object({enabled:M.boolean()}).optional(),source:M.union([M.object({type:M.literal("base64"),media_type:M.literal("application/pdf"),data:M.string()}),M.object({type:M.literal("text"),media_type:M.literal("text/plain"),data:M.string()})])})}),M.object({type:M.literal("web_fetch_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("web_search_tool_result"),tool_use_id:M.string(),content:M.union([M.array(M.object({type:M.literal("web_search_result"),url:M.string(),title:M.string(),encrypted_content:M.string(),page_age:M.string().nullish()})),M.object({type:M.literal("web_search_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("code_execution_tool_result"),tool_use_id:M.string(),content:M.union([M.object({type:M.literal("code_execution_result"),stdout:M.string(),stderr:M.string(),return_code:M.number(),content:M.array(M.object({type:M.literal("code_execution_output"),file_id:M.string()})).optional().default([])}),M.object({type:M.literal("encrypted_code_execution_result"),encrypted_stdout:M.string(),stderr:M.string(),return_code:M.number(),content:M.array(M.object({type:M.literal("code_execution_output"),file_id:M.string()})).optional().default([])}),M.object({type:M.literal("code_execution_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("bash_code_execution_tool_result"),tool_use_id:M.string(),content:M.discriminatedUnion("type",[M.object({type:M.literal("bash_code_execution_result"),content:M.array(M.object({type:M.literal("bash_code_execution_output"),file_id:M.string()})),stdout:M.string(),stderr:M.string(),return_code:M.number()}),M.object({type:M.literal("bash_code_execution_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("text_editor_code_execution_tool_result"),tool_use_id:M.string(),content:M.discriminatedUnion("type",[M.object({type:M.literal("text_editor_code_execution_tool_result_error"),error_code:M.string()}),M.object({type:M.literal("text_editor_code_execution_view_result"),content:M.string(),file_type:M.string(),num_lines:M.number().nullable(),start_line:M.number().nullable(),total_lines:M.number().nullable()}),M.object({type:M.literal("text_editor_code_execution_create_result"),is_file_update:M.boolean()}),M.object({type:M.literal("text_editor_code_execution_str_replace_result"),lines:M.array(M.string()).nullable(),new_lines:M.number().nullable(),new_start:M.number().nullable(),old_lines:M.number().nullable(),old_start:M.number().nullable()})])}),M.object({type:M.literal("tool_search_tool_result"),tool_use_id:M.string(),content:M.union([M.object({type:M.literal("tool_search_tool_search_result"),tool_references:M.array(M.object({type:M.literal("tool_reference"),tool_name:M.string()}))}),M.object({type:M.literal("tool_search_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("advisor_tool_result"),tool_use_id:M.string(),content:M.discriminatedUnion("type",[M.object({type:M.literal("advisor_result"),text:M.string()}),M.object({type:M.literal("advisor_redacted_result"),encrypted_content:M.string()}),M.object({type:M.literal("advisor_tool_result_error"),error_code:M.string()})])}),M.object({type:M.literal("fallback")})])}),M.object({type:M.literal("content_block_delta"),index:M.number(),delta:M.discriminatedUnion("type",[M.object({type:M.literal("input_json_delta"),partial_json:M.string()}),M.object({type:M.literal("text_delta"),text:M.string()}),M.object({type:M.literal("thinking_delta"),thinking:M.string()}),M.object({type:M.literal("signature_delta"),signature:M.string()}),M.object({type:M.literal("compaction_delta"),content:M.string().nullish()}),M.object({type:M.literal("citations_delta"),citation:M.discriminatedUnion("type",[M.object({type:M.literal("web_search_result_location"),cited_text:M.string(),url:M.string(),title:M.string(),encrypted_index:M.string()}),M.object({type:M.literal("page_location"),cited_text:M.string(),document_index:M.number(),document_title:M.string().nullable(),start_page_number:M.number(),end_page_number:M.number()}),M.object({type:M.literal("char_location"),cited_text:M.string(),document_index:M.number(),document_title:M.string().nullable(),start_char_index:M.number(),end_char_index:M.number()})])})])}),M.object({type:M.literal("content_block_stop"),index:M.number()}),M.object({type:M.literal("error"),error:M.object({type:M.string(),message:M.string()})}),M.object({type:M.literal("message_delta"),delta:M.object({stop_reason:M.string().nullish(),stop_sequence:M.string().nullish(),stop_details:gH$.nullish(),container:M.object({expires_at:M.string(),id:M.string(),skills:M.array(M.object({type:M.union([M.literal("anthropic"),M.literal("custom")]),skill_id:M.string(),version:M.string()})).nullish()}).nullish()}),usage:M.looseObject({input_tokens:M.number().nullish(),output_tokens:M.number(),cache_creation_input_tokens:M.number().nullish(),cache_read_input_tokens:M.number().nullish(),iterations:M.array(M.object({type:M.union([M.literal("compaction"),M.literal("message"),M.literal("advisor_message"),M.literal("fallback_message")]),model:M.string().nullish(),input_tokens:M.number(),output_tokens:M.number(),cache_creation_input_tokens:M.number().nullish(),cache_read_input_tokens:M.number().nullish()})).nullish()}),context_management:M.object({applied_edits:M.array(M.union([M.object({type:M.literal("clear_tool_uses_20250919"),cleared_tool_uses:M.number(),cleared_input_tokens:M.number()}),M.object({type:M.literal("clear_thinking_20251015"),cleared_thinking_turns:M.number(),cleared_input_tokens:M.number()}),M.object({type:M.literal("compact_20260112")})]))}).nullish()}),M.object({type:M.literal("message_stop")}),M.object({type:M.literal("ping")})]))),KL4=B0(()=>$0(M.object({signature:M.string().optional(),redactedData:M.string().optional()}))),VH$=W1.object({citations:W1.object({enabled:W1.boolean()}).optional(),title:W1.string().optional(),context:W1.string().optional()}),SH$=W1.object({sendReasoning:W1.boolean().optional(),structuredOutputMode:W1.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:W1.discriminatedUnion("type",[W1.object({type:W1.literal("adaptive"),display:W1.enum(["omitted","summarized"]).optional()}),W1.object({type:W1.literal("enabled"),budgetTokens:W1.number().optional()}),W1.object({type:W1.literal("disabled")})]).optional(),disableParallelToolUse:W1.boolean().optional(),cacheControl:W1.object({type:W1.literal("ephemeral"),ttl:W1.union([W1.literal("5m"),W1.literal("1h")]).optional()}).optional(),metadata:W1.object({userId:W1.string().optional()}).optional(),mcpServers:W1.array(W1.object({type:W1.literal("url"),name:W1.string(),url:W1.string(),authorizationToken:W1.string().nullish(),toolConfiguration:W1.object({enabled:W1.boolean().nullish(),allowedTools:W1.array(W1.string()).nullish()}).nullish()})).optional(),container:W1.object({id:W1.string().optional(),skills:W1.array(W1.object({type:W1.union([W1.literal("anthropic"),W1.literal("custom")]),skillId:W1.string(),version:W1.string().optional()})).optional()}).optional(),toolStreaming:W1.boolean().optional(),effort:W1.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:W1.object({type:W1.literal("tokens"),total:W1.number().int().min(20000),remaining:W1.number().int().min(0).optional()}).optional(),speed:W1.enum(["fast","standard"]).optional(),inferenceGeo:W1.enum(["us","global"]).optional(),fallbacks:W1.array(W1.object({model:W1.string(),max_tokens:W1.number().int().optional(),thinking:W1.record(W1.string(),W1.unknown()).optional(),output_config:W1.record(W1.string(),W1.unknown()).optional(),speed:W1.enum(["fast","standard"]).optional()})).optional(),anthropicBeta:W1.array(W1.string()).optional(),contextManagement:W1.object({edits:W1.array(W1.discriminatedUnion("type",[W1.object({type:W1.literal("clear_tool_uses_20250919"),trigger:W1.discriminatedUnion("type",[W1.object({type:W1.literal("input_tokens"),value:W1.number()}),W1.object({type:W1.literal("tool_uses"),value:W1.number()})]).optional(),keep:W1.object({type:W1.literal("tool_uses"),value:W1.number()}).optional(),clearAtLeast:W1.object({type:W1.literal("input_tokens"),value:W1.number()}).optional(),clearToolInputs:W1.boolean().optional(),excludeTools:W1.array(W1.string()).optional()}),W1.object({type:W1.literal("clear_thinking_20251015"),keep:W1.union([W1.literal("all"),W1.object({type:W1.literal("thinking_turns"),value:W1.number()})]).optional()}),W1.object({type:W1.literal("compact_20260112"),trigger:W1.object({type:W1.literal("input_tokens"),value:W1.number()}).optional(),pauseAfterCompaction:W1.boolean().optional(),instructions:W1.string().optional()})]))}).optional()});FL4=B0(()=>$0(NZ.object({model:NZ.string(),maxUses:NZ.number().optional(),caching:NZ.object({type:NZ.literal("ephemeral"),ttl:NZ.union([NZ.literal("5m"),NZ.literal("1h")])}).optional()}))),hH$=B0(()=>$0(NZ.discriminatedUnion("type",[NZ.object({type:NZ.literal("advisor_result"),text:NZ.string()}),NZ.object({type:NZ.literal("advisor_redacted_result"),encryptedContent:NZ.string()}),NZ.object({type:NZ.literal("advisor_tool_result_error"),errorCode:NZ.string()})]))),HL4=B0(()=>$0(NZ.object({}).strict())),NL4=a$({id:"anthropic.advisor_20260301",inputSchema:HL4,outputSchema:hH$,supportsDeferredResults:!0}),BL4=B0(()=>$0(UJ.object({maxCharacters:UJ.number().optional()}))),OL4=B0(()=>$0(UJ.object({command:UJ.enum(["view","create","str_replace","insert"]),path:UJ.string(),file_text:UJ.string().optional(),insert_line:UJ.number().int().optional(),new_str:UJ.string().optional(),insert_text:UJ.string().optional(),old_str:UJ.string().optional(),view_range:UJ.array(UJ.number().int()).optional()}))),DL4=f4({id:"anthropic.text_editor_20250728",inputSchema:OL4}),wL4=B0(()=>$0(q9.object({maxUses:q9.number().optional(),allowedDomains:q9.array(q9.string()).optional(),blockedDomains:q9.array(q9.string()).optional(),userLocation:q9.object({type:q9.literal("approximate"),city:q9.string().optional(),region:q9.string().optional(),country:q9.string().optional(),timezone:q9.string().optional()}).optional()}))),EL4=B0(()=>$0(q9.array(q9.object({url:q9.string(),title:q9.string().nullable(),pageAge:q9.string().nullable(),encryptedContent:q9.string(),type:q9.literal("web_search_result")})))),jL4=B0(()=>$0(q9.object({query:q9.string()}))),zL4=a$({id:"anthropic.web_search_20260209",inputSchema:jL4,outputSchema:EL4,supportsDeferredResults:!0}),AL4=B0(()=>$0(M9.object({maxUses:M9.number().optional(),allowedDomains:M9.array(M9.string()).optional(),blockedDomains:M9.array(M9.string()).optional(),userLocation:M9.object({type:M9.literal("approximate"),city:M9.string().optional(),region:M9.string().optional(),country:M9.string().optional(),timezone:M9.string().optional()}).optional()}))),uH$=B0(()=>$0(M9.array(M9.object({url:M9.string(),title:M9.string().nullable(),pageAge:M9.string().nullable(),encryptedContent:M9.string(),type:M9.literal("web_search_result")})))),TL4=B0(()=>$0(M9.object({query:M9.string()}))),RL4=a$({id:"anthropic.web_search_20250305",inputSchema:TL4,outputSchema:uH$,supportsDeferredResults:!0}),qL4=B0(()=>$0(P6.object({maxUses:P6.number().optional(),allowedDomains:P6.array(P6.string()).optional(),blockedDomains:P6.array(P6.string()).optional(),citations:P6.object({enabled:P6.boolean()}).optional(),maxContentTokens:P6.number().optional()}))),ML4=B0(()=>$0(P6.object({type:P6.literal("web_fetch_result"),url:P6.string(),content:P6.object({type:P6.literal("document"),title:P6.string().nullable(),citations:P6.object({enabled:P6.boolean()}).optional(),source:P6.union([P6.object({type:P6.literal("base64"),mediaType:P6.literal("application/pdf"),data:P6.string()}),P6.object({type:P6.literal("text"),mediaType:P6.literal("text/plain"),data:P6.string()})])}),retrievedAt:P6.string().nullable()}))),kL4=B0(()=>$0(P6.object({url:P6.string()}))),VL4=a$({id:"anthropic.web_fetch_20260209",inputSchema:kL4,outputSchema:ML4,supportsDeferredResults:!0}),CL4=B0(()=>$0(A6.object({maxUses:A6.number().optional(),allowedDomains:A6.array(A6.string()).optional(),blockedDomains:A6.array(A6.string()).optional(),citations:A6.object({enabled:A6.boolean()}).optional(),maxContentTokens:A6.number().optional()}))),cH$=B0(()=>$0(A6.object({type:A6.literal("web_fetch_result"),url:A6.string(),content:A6.object({type:A6.literal("document"),title:A6.string().nullable(),citations:A6.object({enabled:A6.boolean()}).optional(),source:A6.union([A6.object({type:A6.literal("base64"),mediaType:A6.literal("application/pdf"),data:A6.string()}),A6.object({type:A6.literal("text"),mediaType:A6.literal("text/plain"),data:A6.string()})])}),retrievedAt:A6.string().nullable()}))),_L4=B0(()=>$0(A6.object({url:A6.string()}))),vL4=a$({id:"anthropic.web_fetch_20250910",inputSchema:_L4,outputSchema:cH$,supportsDeferredResults:!0});lH$=B0(()=>$0(n3.object({type:n3.literal("code_execution_result"),stdout:n3.string(),stderr:n3.string(),return_code:n3.number(),content:n3.array(n3.object({type:n3.literal("code_execution_output"),file_id:n3.string()})).optional().default([])}))),xL4=B0(()=>$0(n3.object({code:n3.string()}))),yL4=a$({id:"anthropic.code_execution_20250522",inputSchema:xL4,outputSchema:lH$}),dH$=B0(()=>$0(e1.discriminatedUnion("type",[e1.object({type:e1.literal("code_execution_result"),stdout:e1.string(),stderr:e1.string(),return_code:e1.number(),content:e1.array(e1.object({type:e1.literal("code_execution_output"),file_id:e1.string()})).optional().default([])}),e1.object({type:e1.literal("bash_code_execution_result"),content:e1.array(e1.object({type:e1.literal("bash_code_execution_output"),file_id:e1.string()})),stdout:e1.string(),stderr:e1.string(),return_code:e1.number()}),e1.object({type:e1.literal("bash_code_execution_tool_result_error"),error_code:e1.string()}),e1.object({type:e1.literal("text_editor_code_execution_tool_result_error"),error_code:e1.string()}),e1.object({type:e1.literal("text_editor_code_execution_view_result"),content:e1.string(),file_type:e1.string(),num_lines:e1.number().nullable(),start_line:e1.number().nullable(),total_lines:e1.number().nullable()}),e1.object({type:e1.literal("text_editor_code_execution_create_result"),is_file_update:e1.boolean()}),e1.object({type:e1.literal("text_editor_code_execution_str_replace_result"),lines:e1.array(e1.string()).nullable(),new_lines:e1.number().nullable(),new_start:e1.number().nullable(),old_lines:e1.number().nullable(),old_start:e1.number().nullable()})]))),hL4=B0(()=>$0(e1.discriminatedUnion("type",[e1.object({type:e1.literal("programmatic-tool-call"),code:e1.string()}),e1.object({type:e1.literal("bash_code_execution"),command:e1.string()}),e1.discriminatedUnion("command",[e1.object({type:e1.literal("text_editor_code_execution"),command:e1.literal("view"),path:e1.string()}),e1.object({type:e1.literal("text_editor_code_execution"),command:e1.literal("create"),path:e1.string(),file_text:e1.string().nullish()}),e1.object({type:e1.literal("text_editor_code_execution"),command:e1.literal("str_replace"),path:e1.string(),old_str:e1.string(),new_str:e1.string()})])]))),uL4=a$({id:"anthropic.code_execution_20250825",inputSchema:hL4,outputSchema:dH$,supportsDeferredResults:!0}),mH$=B0(()=>$0(f1.discriminatedUnion("type",[f1.object({type:f1.literal("code_execution_result"),stdout:f1.string(),stderr:f1.string(),return_code:f1.number(),content:f1.array(f1.object({type:f1.literal("code_execution_output"),file_id:f1.string()})).optional().default([])}),f1.object({type:f1.literal("encrypted_code_execution_result"),encrypted_stdout:f1.string(),stderr:f1.string(),return_code:f1.number(),content:f1.array(f1.object({type:f1.literal("code_execution_output"),file_id:f1.string()})).optional().default([])}),f1.object({type:f1.literal("bash_code_execution_result"),content:f1.array(f1.object({type:f1.literal("bash_code_execution_output"),file_id:f1.string()})),stdout:f1.string(),stderr:f1.string(),return_code:f1.number()}),f1.object({type:f1.literal("bash_code_execution_tool_result_error"),error_code:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution_tool_result_error"),error_code:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution_view_result"),content:f1.string(),file_type:f1.string(),num_lines:f1.number().nullable(),start_line:f1.number().nullable(),total_lines:f1.number().nullable()}),f1.object({type:f1.literal("text_editor_code_execution_create_result"),is_file_update:f1.boolean()}),f1.object({type:f1.literal("text_editor_code_execution_str_replace_result"),lines:f1.array(f1.string()).nullable(),new_lines:f1.number().nullable(),new_start:f1.number().nullable(),old_lines:f1.number().nullable(),old_start:f1.number().nullable()})]))),lL4=B0(()=>$0(f1.discriminatedUnion("type",[f1.object({type:f1.literal("programmatic-tool-call"),code:f1.string()}),f1.object({type:f1.literal("bash_code_execution"),command:f1.string()}),f1.discriminatedUnion("command",[f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("view"),path:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("create"),path:f1.string(),file_text:f1.string().nullish()}),f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("str_replace"),path:f1.string(),old_str:f1.string(),new_str:f1.string()})])]))),dL4=a$({id:"anthropic.code_execution_20260120",inputSchema:lL4,outputSchema:mH$,supportsDeferredResults:!0}),iH$=B0(()=>$0(bC.array(bC.object({type:bC.literal("tool_reference"),toolName:bC.string()})))),iL4=B0(()=>$0(bC.object({pattern:bC.string(),limit:bC.number().optional()}))),pL4=a$({id:"anthropic.tool_search_regex_20251119",inputSchema:iL4,outputSchema:iH$,supportsDeferredResults:!0});pH$=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),sL4=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];Jw4=B0(()=>$0(Qr0.object({command:Qr0.string(),restart:Qr0.boolean().optional()}))),Kw4=f4({id:"anthropic.bash_20241022",inputSchema:Jw4}),Ww4=B0(()=>$0(Yr0.object({command:Yr0.string(),restart:Yr0.boolean().optional()}))),Fw4=f4({id:"anthropic.bash_20250124",inputSchema:Ww4}),Hw4=B0(()=>$0(Lt.object({action:Lt.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:Lt.array(Lt.number().int()).optional(),text:Lt.string().optional()}))),Nw4=f4({id:"anthropic.computer_20241022",inputSchema:Hw4}),Uw4=B0(()=>$0(NJ.object({action:NJ.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:NJ.tuple([NJ.number().int(),NJ.number().int()]).optional(),duration:NJ.number().optional(),scroll_amount:NJ.number().optional(),scroll_direction:NJ.enum(["up","down","left","right"]).optional(),start_coordinate:NJ.tuple([NJ.number().int(),NJ.number().int()]).optional(),text:NJ.string().optional()}))),Bw4=f4({id:"anthropic.computer_20250124",inputSchema:Uw4}),Ow4=B0(()=>$0(L7.object({action:L7.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:L7.tuple([L7.number().int(),L7.number().int()]).optional(),duration:L7.number().optional(),region:L7.tuple([L7.number().int(),L7.number().int(),L7.number().int(),L7.number().int()]).optional(),scroll_amount:L7.number().optional(),scroll_direction:L7.enum(["up","down","left","right"]).optional(),start_coordinate:L7.tuple([L7.number().int(),L7.number().int()]).optional(),text:L7.string().optional()}))),Dw4=f4({id:"anthropic.computer_20251124",inputSchema:Ow4}),Lw4=B0(()=>$0(v6.discriminatedUnion("command",[v6.object({command:v6.literal("view"),path:v6.string(),view_range:v6.tuple([v6.number(),v6.number()]).optional()}),v6.object({command:v6.literal("create"),path:v6.string(),file_text:v6.string()}),v6.object({command:v6.literal("str_replace"),path:v6.string(),old_str:v6.string(),new_str:v6.string()}),v6.object({command:v6.literal("insert"),path:v6.string(),insert_line:v6.number(),insert_text:v6.string()}),v6.object({command:v6.literal("delete"),path:v6.string()}),v6.object({command:v6.literal("rename"),old_path:v6.string(),new_path:v6.string()})]))),ww4=f4({id:"anthropic.memory_20250818",inputSchema:Lw4}),Ew4=B0(()=>$0(xW.object({command:xW.enum(["view","create","str_replace","insert","undo_edit"]),path:xW.string(),file_text:xW.string().optional(),insert_line:xW.number().int().optional(),new_str:xW.string().optional(),insert_text:xW.string().optional(),old_str:xW.string().optional(),view_range:xW.array(xW.number().int()).optional()}))),jw4=f4({id:"anthropic.text_editor_20241022",inputSchema:Ew4}),zw4=B0(()=>$0(yW.object({command:yW.enum(["view","create","str_replace","insert","undo_edit"]),path:yW.string(),file_text:yW.string().optional(),insert_line:yW.number().int().optional(),new_str:yW.string().optional(),insert_text:yW.string().optional(),old_str:yW.string().optional(),view_range:yW.array(yW.number().int()).optional()}))),Pw4=f4({id:"anthropic.text_editor_20250124",inputSchema:zw4}),Aw4=B0(()=>$0(gW.object({command:gW.enum(["view","create","str_replace","insert"]),path:gW.string(),file_text:gW.string().optional(),insert_line:gW.number().int().optional(),new_str:gW.string().optional(),insert_text:gW.string().optional(),old_str:gW.string().optional(),view_range:gW.array(gW.number().int()).optional()}))),Tw4=f4({id:"anthropic.text_editor_20250429",inputSchema:Aw4}),Rw4=B0(()=>$0(xC.array(xC.object({type:xC.literal("tool_reference"),toolName:xC.string()})))),Iw4=B0(()=>$0(xC.object({query:xC.string(),limit:xC.number().optional()}))),qw4=a$({id:"anthropic.tool_search_bm25_20251119",inputSchema:Iw4,outputSchema:Rw4,supportsDeferredResults:!0}),kw4={advisor_20260301:UL4,bash_20241022:Kw4,bash_20250124:Fw4,codeExecution_20250522:gL4,codeExecution_20250825:cL4,codeExecution_20260120:mL4,computer_20241022:Nw4,computer_20250124:Bw4,computer_20251124:Dw4,memory_20250818:ww4,textEditor_20241022:jw4,textEditor_20250124:Pw4,textEditor_20250429:Tw4,textEditor_20250728:LL4,webFetch_20250910:fL4,webFetch_20260209:SL4,webSearch_20250305:IL4,webSearch_20260209:PL4,toolSearchRegex_20251119:nL4,toolSearchBm25_20251119:Mw4};Ef9=wt()});import{z as KN}from"zod/v4";import{z as Et}from"zod/v4";import{z as WX}from"zod/v4";import{z as h0}from"zod/v4";import{z as W6}from"zod/v4";import{z as wg}from"zod/v4";import{z as $E4}from"zod/v4";import{z as jt}from"zod/v4";import{z as GE4}from"zod/v4";import{z as yC}from"zod/v4";import{z as FE4}from"zod/v4";import{z as Kr0}from"zod/v4";import{z as gC}from"zod/v4";import{z as W9}from"zod/v4";import{z as H0}from"zod/v4";import{z as i1}from"zod/v4";function tH$($){var Z,X,Q,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=(X=$.candidatesTokenCount)!=null?X:0,K=(Q=$.cachedContentTokenCount)!=null?Q: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 t3($,Z=!0){if($==null)return;if(xw4($)){if(Z)return;if(typeof $==="object"&&$.description)return{type:"object",description:$.description};return{type:"object"}}if(typeof $==="boolean")return{type:"boolean",properties:{}};let{type:X,description:Q,required:Y,properties:G,items:J,allOf:K,anyOf:W,oneOf:F,format:H,const:N,minLength:U,enum:B}=$,O={};if(Q)O.description=Q;if(Y)O.required=Y;if(H)O.format=H;if(N!==void 0)O.enum=[N];if(X)if(Array.isArray(X)){let L=X.includes("null"),w=X.filter((E)=>E!=="null");if(w.length===0)O.type="null";else if(O.anyOf=w.map((E)=>({type:E})),L)O.nullable=!0}else O.type=X;if(B!==void 0)O.enum=B;if(G!=null)O.properties=Object.entries(G).reduce((L,[w,E])=>{return L[w]=t3(E,!1),L},{});if(J)O.items=Array.isArray(J)?J.map((L)=>t3(L,!1)):t3(J,!1);if(K)O.allOf=K.map((L)=>t3(L,!1));if(W)if(W.some((L)=>typeof L==="object"&&(L==null?void 0:L.type)==="null")){let L=W.filter((w)=>!(typeof w==="object"&&(w==null?void 0:w.type)==="null"));if(L.length===1){let w=t3(L[0],!1);if(typeof w==="object")O.nullable=!0,Object.assign(O,w)}else O.anyOf=L.map((w)=>t3(w,!1)),O.nullable=!0}else O.anyOf=W.map((L)=>t3(L,!1));if(F)O.oneOf=F.map((L)=>t3(L,!1));if(U!==void 0)O.minLength=U;return O}function xw4($){return $!=null&&typeof $==="object"&&$.type==="object"&&($.properties==null||Object.keys($.properties).length===0)&&!$.additionalProperties}function oH$($,Z){let X=[Z,"google","googleVertex","vertex"].filter((Q,Y,G)=>{return G.indexOf(Q)===Y});for(let Q of X){let Y=$==null?void 0:$[Q];if(Y!=null)return Y}}function hw4($){let Z=gw4.exec($);if(Z==null)return;return{mediaType:Z[1],data:Z[2]}}function uw4($){let Z=hw4($);if(Z==null)return;return{inlineData:{mimeType:Z.mediaType,data:Z.data}}}function cw4($,Z,X,Q){let Y=[],G=[];for(let J of X)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=uw4(J.url);if(K!=null)Y.push(K);else G.push(JSON.stringify(J));break}default:{G.push(JSON.stringify(J));break}}$.push({functionResponse:{...Q!=null?{id:Q}:{},name:Z,response:{name:Z,content:G.length>0?G.join(`
1470
1470
  `):"Tool executed successfully."},...Y.length>0?{parts:Y}:{}}})}function lw4($,Z,X,Q){for(let Y of X)switch(Y.type){case"text":$.push({functionResponse:{...Q!=null?{id:Q}:{},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 dw4($,Z){var X,Q,Y,G,J;let K=[],W=[],F=!0,H=(X=Z==null?void 0:Z.isGemmaModel)!=null?X:!1,N=(Q=Z==null?void 0:Z.isGemini3Model)!=null?Q:!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,L=!1,w=[],E=(j)=>{return w.push(j),L=!0,yw4};for(let{role:j,content:z}of $)switch(j){case"system":{if(!F)throw new v4({functionality:"system messages are only supported at the beginning of the conversation"});K.push({text:z});break}case"user":{F=!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:KZ(P.data)}});break}}W.push({role:"user",parts:A});break}case"assistant":{F=!1,W.push({role:"model",parts:z.map((A)=>{let P=oH$(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 v4({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:A.mediaType,data:KZ(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,k=(P==null?void 0:P.serverToolType)!=null?String(P.serverToolType):void 0,S=I!=null?I:N?E(A.toolName):void 0;if(q&&k)return{toolCall:{toolType:k,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,k=(P==null?void 0:P.serverToolType)!=null?String(P.serverToolType):void 0;if(q&&k)return{toolResponse:{toolType:k,response:A.output.type==="json"?A.output.value:{},id:q},thoughtSignature:I};return}}}).filter((A)=>A!==void 0)});break}case"tool":{F=!1;let A=[];for(let P of z){if(P.type==="tool-approval-response")continue;let I=oH$(P.providerOptions,U),q=(I==null?void 0:I.serverToolCallId)!=null?String(I.serverToolCallId):void 0,k=(I==null?void 0:I.serverToolType)!=null?String(I.serverToolType):void 0;if(q&&k){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:k,response:P.output.type==="json"?P.output.value:{},id:q},thoughtSignature:m});continue}}}let S=P.output;if(S.type==="content")if(B)cw4(A,P.toolName,S.value,P.toolCallId);else lw4(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(H&&K.length>0&&W.length>0&&W[0].role==="user"){let j=K.map((z)=>z.text).join(`
@@ -2920,7 +2920,7 @@ Respond with the structured verdict and a short reason.`,vc$;var bc$=D(()=>{D4()
2920
2920
  ${G.join(`
2921
2921
  `)}`:Y}function aH6($){let Z=new Set;for(let X of $)for(let Q of X.split(`
2922
2922
  `)){let Y=Q.trim();if(/^Co-authored-by:\s/i.test(Y))Z.add(Y)}return[...Z]}var Ll$=200,lH6=12,mH6,pH6=300,H71=3;var N71=D(()=>{yD();GT0();mH6={aheadBy:0,behindBy:0,files:[]}});function eH6($){if(!$||$.includes(".."))return!1;return sH6.test($)}function El$($){let Z=typeof $.__resolveType==="string"?$.__resolveType:null;if(!Z||!eH6(Z))return null;let{__resolveType:X,...Q}=$;return{resolveType:Z,payload:Q}}function jl$($,Z){return`${$.replace(/\/+$/,"")}/deco/invoke/${Z}`}var sH6;var zl$=D(()=>{sH6=/^[\w./@-]+$/});function Hs($,Z){let X=$?.githubRepo;if(!X?.owner||!X?.name)return null;if(!X.connectionId)return X;if(!Z.includes(X.connectionId))return null;return X}async function Pl$($,Z,X,Q){if(!Q.connectionId)throw new Jv("Push requires a connected GitHub account. Connect mcp-github for this project and restart the sandbox.");let Y=$.organization?.id;if(!Y)throw new Jv(G9);await zO({ctx:$,connectionId:Q.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(H)=>{let N=H instanceof Error?H.message:G9;throw new Jv(N)}});let{cloneUrl:G,gitUserName:J,gitUserEmail:K}=await TW(Q.connectionId,Q.owner,Q.name,$.db,$.vault).catch((H)=>{let{code:N,message:U}=N5$(H instanceof Error?H.message:String(H));throw N?new Jv(U):H}),W=uu($),F=await Z.proxyDaemonRequest(X,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({git:{repository:{cloneUrl:G},identity:{userName:J,userEmail:K}},...W?{operator:W}:{}})});if(!F.ok){let H=await jO(F,$N6).catch(()=>F.statusText);throw Error(`Failed to refresh sandbox git credentials (${F.status}): ${H}`)}}var $N6=10485760,Jv;var U71=D(()=>{ZJ();tA0();Yn();Hi0();Py();Jv=class Jv extends Error{constructor($){super($);this.name="GitPushAuthError"}}});function XN6($){let Z=$.startsWith("thread:")?$.slice(7):$;if(!Z||Z.length>255||Z.includes("..")||Z.startsWith("/")||Z.endsWith("/")||Z.endsWith(".lock")||!ZN6.test(Z))throw Error(`Invalid branch name: ${$}`)}function Kv($){return AbortSignal.any([$.req.raw.signal,AbortSignal.timeout(YN6)])}async function JN6($,Z){let X=$.var.studioContext,Q=eG(Z.branch),Y=$.req.query("thread")??Q,G=Y&&Y===Q?Z.branchThread:Y?await X.storage.threads.get(Y).catch(()=>null):null,J=G?.virtual_mcp_id===Z.virtualMcpId?G:null,K=HC(J?.metadata?.runtime);if(K)return K;let W=cO0(Z.virtualMcpMetadata),F=W==="cms"?await nZ1(X,{claimName:Z.claimName}):"alive",H=W==="cms"&&F!=="alive"?"cms":"sandbox",N=!!J&&(F==="gone"||F==="alive"&&W==="cms");if(N&&J)vn(X,J.id,H);if(W==="cms")console.log("sandbox proxy: no runtime stamp",{route:$.req.path,method:$.req.method,reason:J?"unstamped":"threadless",liveness:F,resolved:H,stamped:N});return H}async function KN6($){let Z=$.get("vmClaim");if(Z.runner)return Z.runner;try{return await $Q($.var.studioContext)}catch{return null}}function Wv($){let{runner:Z}=$.get("vmClaim");if(!Z)return $.json({error:"No sandbox runner configured"},503);return Z}async function iu($){let{virtualMcpMetadata:Z,connectionIds:X}=$.get("vmClaim"),Q=$.var.studioContext,Y=Hs(Z,X);if(!Y)throw new u4(404,"AUTH","repo","Project has no GitHub repository");let G=t(Q);return oA0(Q,G.id,Y)}function B71($,Z){if(Z instanceof $A0)return $.json({error:Z.message},429,{...P5,...Z.retryAfterMs===null?{}:{"Retry-After":String(Math.ceil(Z.retryAfterMs/1000))}});if(Z instanceof u4){let Q=Z.status===404?404:Z.status===409||Z.status===422?409:502;return $.json({error:Z.message},Q,P5)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},502,P5)}async function Rl$($,Z,X){let Q;try{Q=await fetch(Z,X)}catch{return $.json({error:"Preview unreachable"},502)}let Y;try{Y=await Q.text()}catch{return $.json({error:"Preview unreachable"},502)}return new Response(Y,{status:Q.status,headers:{"content-type":Q.headers.get("content-type")??"application/json"}})}async function Il$($){try{let Z=await iu($),X=await JT0(Z,$.get("vmClaim").branch);return $.json(X,200,P5)}catch(Z){return B71($,Z)}}function Ns($,Z){let Q=(FT0.get($)??Promise.resolve()).catch(()=>{}).then(Z),Y=Q.catch(()=>{});return FT0.set($,Y),Y.finally(()=>{if(FT0.get($)===Y)FT0.delete($)}),Q}async function tZ($,Z,X){if(!X?.runner&&$.get("vmClaim").runtime==="cms")return $.json({error:"sandbox not found: this session is sandbox-less"},404,P5);let Q=X?.runner??Wv($);if(Q instanceof Response)return Q;let{claimName:Y,userId:G,projectRef:J}=$.get("vmClaim"),K=X?.method??"POST",W=null,F=new Headers;if(X?.jsonBody!==void 0)W=X.jsonBody,F.set("content-type","application/json");else if(X?.forwardJsonBody)W=await $.req.text(),F.set("content-type","application/json");let H=X?.signal,N={method:K,headers:F,body:W,...H?{signal:H}:{}},U=async()=>{let B=await Q.proxyDaemonRequest(Y,Z,N);if(X?.map404to410&&B.status===404){try{await B.body?.cancel()}catch{}if(await Q.adoptLiveClaim({userId:G,projectRef:J},Y))B=await Q.proxyDaemonRequest(Y,Z,N);if(B.status===404){try{await B.body?.cancel()}catch{}return new Response(JSON.stringify({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."}),{status:410,headers:{"content-type":"application/json",...P5}})}}let O=await B.text(),L=X?.redactRepoDir?WN6(O):O,w=B.headers.get("content-type")??"application/json";return new Response(L,{status:B.status,headers:{"content-type":w,...P5}})};try{if(H){let B=U();return B.catch(()=>{}),await Promise.race([B,new Promise((L,w)=>{if(H.aborted)return w(H.reason);H.addEventListener("abort",()=>w(H.reason),{once:!0})})])}return await U()}catch(B){let O=B instanceof Error?B.message:String(B);return $.json({error:`Daemon unreachable: ${O}`},502)}}function WN6($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&"repoDir"in Z)return JSON.stringify({...Z,repoDir:null})}catch{}return $}async function HT0($,Z,X,Q="GET",Y){let G=await $.proxyDaemonRequest(Z,X,{method:Q,headers:new Headers,body:null});if(G.status===404&&Y){try{await G.body?.cancel()}catch{}if(await $.adoptLiveClaim(Y,Z))G=await $.proxyDaemonRequest(Z,X,{method:Q,headers:new Headers,body:null})}if(G.status===404){try{await G.body?.cancel()}catch{}throw Error("SANDBOX_GONE")}let J=await G.text();if(!G.ok){let K=`Daemon error (${G.status})`;try{K=JSON.parse(J).error??K}catch{}throw Error(K)}return JSON.parse(J)}function FN6($){return ql$.includes($)}var ZN6,Al$=524288,QN6=65536,YN6=1e4,Tl$=2000,GN6,FT0,P5,ql$,Ml$=()=>{let $=new H1;$.use("/:virtualMcpId/:branch/*",GN6),$.post("/:virtualMcpId/:branch/write",(X)=>tZ(X,"/_sandbox/write",{forwardJsonBody:!0,signal:Kv(X)})),$.post("/:virtualMcpId/:branch/unlink",(X)=>tZ(X,"/_sandbox/unlink",{forwardJsonBody:!0,signal:Kv(X)})),$.post("/:virtualMcpId/:branch/mkdir",(X)=>tZ(X,"/_sandbox/mkdir",{forwardJsonBody:!0,signal:Kv(X)})),$.post("/:virtualMcpId/:branch/rename",(X)=>tZ(X,"/_sandbox/rename",{forwardJsonBody:!0,signal:Kv(X)})),$.post("/:virtualMcpId/:branch/read",(X)=>tZ(X,"/_sandbox/read",{forwardJsonBody:!0,signal:Kv(X)})),$.post("/:virtualMcpId/:branch/glob",(X)=>tZ(X,"/_sandbox/glob",{forwardJsonBody:!0,signal:Kv(X)})),$.post("/:virtualMcpId/:branch/grep",(X)=>tZ(X,"/_sandbox/grep",{forwardJsonBody:!0,signal:Kv(X)})),$.post("/:virtualMcpId/:branch/exec/:script",async(X)=>{let Q=X.req.param("script");if(!Q)return X.json({error:"missing script name"},400);return tZ(X,`/_sandbox/exec/${encodeURIComponent(Q)}`)}),$.post("/:virtualMcpId/:branch/exec/:script/kill",async(X)=>{let Q=X.req.param("script");if(!Q)return X.json({error:"missing script name"},400);return tZ(X,`/_sandbox/exec/${encodeURIComponent(Q)}/kill`)}),$.get("/:virtualMcpId/:branch/config",(X)=>tZ(X,"/_sandbox/config",{method:"GET",map404to410:!0,redactRepoDir:!0})),$.put("/:virtualMcpId/:branch/config",(X)=>tZ(X,"/_sandbox/config",{method:"PUT",forwardJsonBody:!0,map404to410:!0})),$.post("/:virtualMcpId/:branch/setup/:step",async(X)=>{let Q=X.req.param("step");if(!Q||!FN6(Q))return X.json({error:`step must be one of: ${ql$.join(", ")}`},400);let Y=X.get("vmClaim"),G=await nZ1(X.var.studioContext,{claimName:Y.claimName})==="gone"?null:await KN6(X);if(!G)return X.json({error:"sandbox not found: nothing is running at this ref"},404,P5);if(Q==="start"){let J=t(X.var.studioContext),K=jy(Y.virtualMcpMetadata);try{await Q70({ctx:X.var.studioContext,runner:G,handle:Y.claimName,orgId:J.id,userId:Y.callerUserId,entries:K})}catch(W){let F=W instanceof Error?W.message:String(W);return X.json({error:`Failed to push env to daemon: ${F}`},502)}}return tZ(X,`/_sandbox/setup/${Q}`,{signal:X.req.raw.signal,map404to410:!0,runner:G})}),$.get("/:virtualMcpId/:branch/events",(X)=>{let Q=X.get("vmClaim");if(!Q.runner)return hN(X,async(Y)=>{await Y.writeSSE({event:"phase",data:JSON.stringify({kind:"failed",reason:"unknown",message:"No sandbox runner configured on this studio instance."})})});return Mc$(X,{ctx:X.var.studioContext,claimName:Q.claimName,runner:Q.runner,virtualMcpId:Q.virtualMcpId,branch:Q.branch,userId:Q.userId,projectRef:Q.projectRef,virtualMcpMetadata:Q.virtualMcpMetadata})}),$.get("/:virtualMcpId/:branch/git/status",(X)=>{if(X.get("vmClaim").runtime==="cms")return Il$(X);return Z(X)});let Z=(X)=>tZ(X,"/_sandbox/git/status",{method:"GET",map404to410:!0,signal:AbortSignal.any([X.req.raw.signal,AbortSignal.timeout(Tl$)])});return $.post("/:virtualMcpId/:branch/git/status",(X)=>{if(X.get("vmClaim").runtime==="cms")return Il$(X);return tZ(X,"/_sandbox/git/status",{map404to410:!0,signal:AbortSignal.any([X.req.raw.signal,AbortSignal.timeout(Tl$)])})}),$.post("/:virtualMcpId/:branch/git/diff",async(X)=>{let Q=X.get("vmClaim");if(Q.runtime==="cms")try{let Y=await X.req.json().catch(()=>({})),G=await iu(X),J=await KT0(G,Q.branch,Y.base);return X.json(J,200,P5)}catch(Y){return B71(X,Y)}return tZ(X,"/_sandbox/git/diff",{forwardJsonBody:!0,map404to410:!0})}),$.post("/:virtualMcpId/:branch/git/publish",async(X)=>{if(X.get("vmClaim").runtime==="cms")return X.json({ok:!0},200,P5);let Q=Wv(X);if(Q instanceof Response)return Q;let{claimName:Y,virtualMcpMetadata:G,connectionIds:J}=X.get("vmClaim"),K=X.var.studioContext;return Ns(Y,async()=>{try{await tZ1(K,Q,Y);let W=Hs(G,J);if(W)await Pl$(K,Q,Y,W)}catch(W){if(W instanceof Jv)return X.json({error:W.message},403,P5);let F=W instanceof Error?W.message:String(W);return X.json({error:F},502,P5)}return tZ(X,"/_sandbox/git/publish",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/discard",async(X)=>{let Q=X.get("vmClaim");if(Q.runtime==="cms")return Ns(Q.claimName,async()=>{let Y=await X.req.json().catch(()=>({})),G=Array.isArray(Y.filepaths)?Y.filepaths.filter((J)=>typeof J==="string"):[];if(G.length===0)return X.json({error:"filepaths is required"},400,P5);try{let J=await iu(X);return await wl$(J,Q.branch,G),X.json({ok:!0},200,P5)}catch(J){let K=J instanceof u4&&J.status===409?409:502,W=J instanceof Error?J.message:String(J);return X.json({error:W},K,P5)}});return Ns(Q.claimName,()=>tZ(X,"/_sandbox/git/discard",{forwardJsonBody:!0,map404to410:!0}))}),$.post("/:virtualMcpId/:branch/git/rebase",async(X)=>{let Q=X.get("vmClaim");if(Q.runtime==="cms")return Ns(Q.claimName,async()=>{try{let K=await X.req.json().catch(()=>({})),W=await iu(X),F=K.base??await W.getDefaultBranch();return await WT0(W,Q.branch,F),X.json({ok:!0},200,P5)}catch(K){return B71(X,K)}});let Y=Wv(X);if(Y instanceof Response)return Y;let{claimName:G}=X.get("vmClaim"),J=X.var.studioContext;return Ns(G,async()=>{try{await tZ1(J,Y,G)}catch(K){let W=K instanceof Error?K.message:String(K);return X.json({error:W},502,P5)}return tZ(X,"/_sandbox/git/rebase",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/suggest-commit",p5({maxSize:Al$,onError:(X)=>X.json({error:"Payload too large"},413,P5)}),async(X)=>{let Q=X.get("vmClaim"),Y=null;if(Q.runtime!=="cms"){let F=Wv(X);if(F instanceof Response)return F;Y=F}let{claimName:G,userId:J,projectRef:K}=Q,W=X.var.studioContext;try{let F=await X.req.json().catch(()=>({})),H=F.status,N=F.diff,U=N!=null&&typeof N.diffs==="object"&&N.diffs!==null,[B,O]=aZ1(H)&&U?[H,N]:Y?await Promise.all([HT0(Y,G,"/_sandbox/git/status","GET",{userId:J,projectRef:K}),HT0(Y,G,"/_sandbox/git/diff","GET",{userId:J,projectRef:K})]):await(async()=>{let w=await iu(X);return Promise.all([JT0(w,Q.branch),KT0(w,Q.branch)])})(),L=await _c$(W,B,O);return X.json(L,200,P5)}catch(F){let H=F instanceof Error?F.message:String(F);if(H==="SANDBOX_GONE")return X.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,P5);return X.json({error:H},502,P5)}}),$.post("/:virtualMcpId/:branch/git/judge-review",p5({maxSize:Al$,onError:(X)=>X.json({error:"Payload too large"},413,P5)}),async(X)=>{let Q=X.get("vmClaim"),Y=null;if(Q.runtime!=="cms"){let F=Wv(X);if(F instanceof Response)return F;Y=F}let{claimName:G,userId:J,projectRef:K}=Q,W=X.var.studioContext;try{let F=await X.req.json().catch(()=>({})),H=F.status,N=F.diff,U=N!=null&&typeof N.diffs==="object"&&N.diffs!==null,[B,O]=aZ1(H)&&U?[H,N]:Y?await Promise.all([HT0(Y,G,"/_sandbox/git/status","GET",{userId:J,projectRef:K}),HT0(Y,G,"/_sandbox/git/diff","GET",{userId:J,projectRef:K})]):await(async()=>{let w=await iu(X);return Promise.all([JT0(w,Q.branch),KT0(w,Q.branch)])})(),L=await fc$(W,B,O,typeof F.language==="string"?F.language:void 0);return X.json(L,200,P5)}catch(F){let H=F instanceof Error?F.message:String(F);if(H==="SANDBOX_GONE")return X.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,P5);return X.json({error:H},502,P5)}}),$.get("/:virtualMcpId/:branch/preview-fetch",async(X)=>{let Q=Wv(X);if(Q instanceof Response)return Q;let{claimName:Y}=X.get("vmClaim"),G=X.req.query("path");if(!G||!G.startsWith("/")||G.startsWith("//")||G.includes("..")||G.includes("\\"))return X.json({error:"Path not allowed"},403);let J;try{J=await Q.getPreviewUrl(Y)}catch{return X.json({error:"Preview not available"},502)}if(!J)return X.json({error:"Preview not available"},502);let K=J.replace(/\/+$/,"");return Rl$(X,`${K}${G}`)}),$.post("/:virtualMcpId/:branch/preview-invoke",p5({maxSize:QN6,onError:(X)=>X.json({error:"Payload too large"},413)}),async(X)=>{let Q=Wv(X);if(Q instanceof Response)return Q;let{claimName:Y}=X.get("vmClaim"),G;try{G=await Q.getPreviewUrl(Y)}catch{return X.json({error:"Preview not available"},502)}if(!G)return X.json({error:"Preview not available"},502);let J;try{J=await X.req.json()}catch{return X.json({error:"Invalid JSON body"},400)}if(!J||typeof J!=="object"||Array.isArray(J))return X.json({error:"Invalid JSON body"},400);let K=El$(J);if(!K)return X.json({error:"Invalid or missing __resolveType"},400);let W=jl$(G,K.resolveType);return Rl$(X,W,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(K.payload),signal:AbortSignal.timeout(30000)})}),$};var kl$=D(()=>{U8();BF();hu();pZ1();ep();Rc$();b3();hy();Ic$();u3();qc$();kc$();Ki0();Xn();$71();bc$();X71();yD();N71();zl$();U71();ZN6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;GN6=nA0(async($,Z)=>{let X=$.var.studioContext;try{r(X)}catch{return $.json({error:"Unauthorized"},401)}let Q=o0(X);if(!Q)return $.json({error:"Unauthorized"},401);let Y;try{Y=t(X)}catch{return $.json({error:"Organization scope required"},403)}let G=$.req.param("virtualMcpId"),J=$.req.param("branch");if(!G||!J)return $.json({error:"virtualMcpId and branch are required"},400);try{XN6(J)}catch(L){let w=L instanceof Error?L.message:String(L);return $.json({error:w},400)}let K=await X.storage.virtualMcps.findById(G);if(!K||K.organization_id!==Y.id)return $.json({error:"Virtual MCP not found"},404);let W=ap({orgId:Y.id,virtualMcpId:G,branch:J}),F=await Zi0(X,J),H=Xi0(F,Q),N=Tc$({userId:H,projectRef:W}),U=K.metadata??null,B=await JN6($,{claimName:N,branch:J,virtualMcpId:G,sandboxUserId:H,virtualMcpMetadata:U,branchThread:F});if(B==="cms")return $.set("vmClaim",{claimName:N,callerUserId:Q,runner:null,virtualMcpId:G,branch:J,userId:H,projectRef:W,virtualMcpMetadata:U,connectionIds:K.connections?.map((L)=>L.connection_id)??[],runtime:B}),Z();let O;try{O=await $Q(X)}catch{O=null}if(!O)return $.json({error:"No sandbox runner found"},404);return $.set("vmClaim",{claimName:N,callerUserId:Q,runner:O,virtualMcpId:G,branch:J,userId:H,projectRef:W,virtualMcpMetadata:U,connectionIds:K.connections?.map((L)=>L.connection_id)??[],runtime:B}),Z()});FT0=new Map;P5={"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache"};ql$=["clone","install","start"]});function Vl$($,Z,X){let Q=O71.get($);if(!Q)Q={pending:null,running:!1},O71.set($,Q);if(!Q.pending)Q.pending={set:new Map,del:new Set,deps:Z,resolvers:[],rejecters:[]};let Y=Q.pending;Y.deps=Z;for(let[J,K]of Object.entries(X.set??{}))Y.set.set(J,K),Y.del.delete(J);for(let J of X.delete??[])Y.del.add(J),Y.set.delete(J);let G=new Promise((J,K)=>{Y.resolvers.push(J),Y.rejecters.push(K)});if(!Q.running)NN6($,Q);return G}async function NN6($,Z){Z.running=!0;try{while(Z.pending){let X=Z.pending;Z.pending=null;try{let Q=await UN6(X);for(let Y of X.resolvers)Y(Q)}catch(Q){for(let Y of X.rejecters)Y(Q)}}}finally{if(Z.running=!1,!Z.pending)O71.delete($)}}async function UN6($){let{client:Z,branch:X,packagePath:Q}=$.deps;for(let Y=0;;Y++){let G=await mu(Z,X),J=await Z.getCommitTreeSha(G),K=await Z.getTreeRecursive(J),W=W71(K,Q),F=[],H=new Map(W.map((O)=>[O.path,{stem:O.stem,sha:O.sha}]));for(let[O,L]of $.set){let w=F71(W,O),E=`${JSON.stringify(L,null,2)}
2923
- `,j=await Z.createBlob(E);await Bl$(Z.owner,Z.repo,j,E);let z=w[0]??`${YT0(Q)}/${Q71(O)}.json`;F.push({path:z,mode:"100644",type:"blob",sha:j});let A=z.slice(z.lastIndexOf("/")+1,-5);H.set(z,{stem:A,sha:j,content:E});for(let P of w.slice(1))F.push({path:P,mode:"100644",type:"blob",sha:null}),H.delete(P)}for(let O of $.del)for(let L of F71(W,O))F.push({path:L,mode:"100644",type:"blob",sha:null}),H.delete(L);if(F.length===0)return G;let N=Q?`${Q}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(K.some((O)=>O.type==="blob"&&O.path===N)){let O=await Promise.all([...H.values()].map(async(j)=>({stem:j.stem,content:j.content??await Z.getBlobText(j.sha)}))),{decofile:L,skipped:w}=Js(O);if(w.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:`${Z.owner}/${Z.repo}`,branch:X,packagePath:Q,blocks:w.map((j)=>j.key)});let E=await Z.createBlob(L);F.push({path:N,mode:"100644",type:"blob",sha:E})}let U=await Z.createTree(J,F),B=await Z.createCommit({message:BN6($),treeSha:U,parentShas:[G]});try{return await Z.updateRef(X,B),B}catch(O){if(!(O instanceof u4&&O.status===422)||Y>=HN6-1)throw O;await L$(aZ(2000,200,Y,2,0.5))}}}function BN6($){let Z=(Y)=>{let G=Y.slice(0,3).join(", ");return Y.length>3?`${G} (+${Y.length-3} more)`:G},X=[];if($.set.size>0)X.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)X.push(`delete ${Z([...$.del])}`);let Q=`chore(decofile): ${X.join("; ")}`;return om0(Q,$.deps.coAuthor)}var HN6=3,O71;var Sl$=D(()=>{bO0();aA0();K4();yD();GT0();O71=new Map});import{createHmac as Cl$,randomBytes as ON6,timingSafeEqual as DN6}from"crypto";function _l$(){if(NT0)return NT0;let $;try{let Z=b0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return NT0=$?Buffer.from($):ON6(32),NT0}function D71($){let Z=$.nowMs??Date.now(),X={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+LN6)/1000)},Q=Buffer.from(JSON.stringify(X)).toString("base64url"),Y=Cl$("sha256",_l$()).update(Q).digest("base64url");return`${Q}.${Y}`}function vl$($,Z){let X=$.indexOf(".");if(X<0)return!1;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(Cl$("sha256",_l$()).update(Q).digest("base64url"));if(Y.length!==G.length||!DN6(Y,G))return!1;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return!1}let K=Math.floor((Z.nowMs??Date.now())/1000);return J.o===Z.organizationId&&J.m===Z.virtualMcpId&&J.b===Z.branch&&typeof J.e==="number"&&J.e>=K}var LN6=21600000,NT0=null;var fl$=D(()=>{R$()});import{z as pu}from"zod";function EN6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&wN6.test($)}function hl$($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function Us($){let Z=$.get("decofileScope");return oA0($.var.studioContext,Z.organizationId,Z.githubRepo)}function Bs($,Z){if(Z instanceof u4){let Q=Z.status===404?404:Z.status===409?409:Z.status===422?409:502;return $.json({error:Z.message},Q)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},500)}function ul$(){let $=new H1;return $.use("/:virtualMcpId/:branch",gl$),$.use("/:virtualMcpId/:branch/*",gl$),$.get("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Us(Z),Y=await Ol$(Q,X.branch,X.packagePath,{createBranchIfMissing:!!X.userId}),G={ETag:`"${Y.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${Y.sha}"`)return Z.body(null,304,G);if(!X.userId)return Z.body(Y.decofile,200,{...G,"content-type":"application/json"});let J=D71({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.body(`{"version":${JSON.stringify(Y.sha)},"token":${JSON.stringify(J)},"apiHost":${JSON.stringify(hl$(Z))},"decofile":${Y.decofile}}`,200,{...G,"content-type":"application/json"})}catch(Q){return Bs(Z,Q)}}),$.get("/:virtualMcpId/:branch/meta",async(Z)=>{let X=Z.get("decofileScope"),Q=X.packagePath?`${X.packagePath}/.deco/meta.gen.json`:".deco/meta.gen.json";try{let Y=await Us(Z),G=await Y.getFileTextAtRef(X.branch,Q);if(G===null){let J=await Y.getDefaultBranch();if(J!==X.branch)G=await Y.getFileTextAtRef(J,Q)}if(G===null)return Z.json({error:"meta.gen.json not committed"},404);return Z.body(G,200,{"content-type":"application/json","Cache-Control":"no-store","Access-Control-Allow-Origin":"*"})}catch(Y){return Bs(Z,Y)}}),$.patch("/:virtualMcpId/:branch",zN6,async(Z)=>{let X=Z.get("decofileScope"),Q=Z.var.studioContext,Y=PN6.safeParse(await Z.req.json().catch(()=>null));if(!Y.success)return Z.json({error:"Invalid body",details:Y.error.issues},400);let G=Y.data;for(let J of[...Object.keys(G.set??{}),...G.delete??[]])try{rA0(J)}catch(K){let W=K instanceof Error?K.message:String(K);return Z.json({error:W},400)}for(let[J,K]of Object.entries(G.set??{}))if(typeof K!=="object"||K===null||Array.isArray(K))return Z.json({error:`Block "${J}" must be a JSON object`},400);try{let J=await Us(Z),K=await Vl$(`${X.organizationId}/${X.virtualMcpId}/${X.branch}`,{client:J,branch:X.branch,packagePath:X.packagePath,coAuthor:uu(Q)},G),W=D71({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.json({version:K,token:W,apiHost:hl$(Z)})}catch(J){return Bs(Z,J)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Us(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({error:"Branch is already the default branch"},400);let G=`chore(decofile): publish ${X.branch}`;try{let J;try{J=await Q.mergeBranch(Y,X.branch,G)}catch(K){if(!(K instanceof u4&&K.status===409))throw K;await WT0(Q,X.branch,Y),J=await Q.mergeBranch(Y,X.branch,G)}return J?Z.json({result:"merged",sha:J}):Z.json({result:"up-to-date"})}catch(J){if(J instanceof u4&&J.status===409)return Z.json({error:"merge-conflict"},409);if(J instanceof u4&&J.status===405){let W=await Q.findOpenPullRequest(Y,X.branch)??await Q.createPullRequest({base:Y,head:X.branch,title:`Publish ${X.branch}`});return Z.json({result:"pull-request",number:W.number,url:W.html_url})}throw J}}catch(Q){return Bs(Z,Q)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Us(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});try{let{aheadBy:G,behindBy:J}=await Q.compare(Y,X.branch);return Z.json({baseBranch:Y,aheadBy:G,behindBy:J})}catch(G){if(G instanceof u4&&G.status===404)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});throw G}}catch(Q){return Bs(Z,Q)}}),$}var wN6,bl$=500,xl$=1048576,yl$=1024,jN6=8388608,zN6,PN6,gl$;var cl$=D(()=>{aA0();U8();BF();pZ1();tA0();U71();X71();Sl$();fl$();N71();yD();GT0();wN6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;zN6=p5({maxSize:jN6,onError:($)=>$.json({error:"Payload too large"},413)}),PN6=pu.object({set:pu.record(pu.string(),pu.unknown()).optional(),delete:pu.array(pu.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}).refine(($)=>Object.keys($.set??{}).length+($.delete?.length??0)<=bl$,{message:`Patch cannot touch more than ${bl$} blocks`}).refine(($)=>Object.values($.set??{}).every((Z)=>JSON.stringify(Z).length<=xl$),{message:`Each block must be at most ${xl$} bytes`}).refine(($)=>[...Object.keys($.set??{}),...$.delete??[]].every((Z)=>Z.length<=yl$),{message:`Each block key must be at most ${yl$} characters`}),gl$=nA0(async($,Z)=>{let X=$.var.studioContext,Q=X.organization;if(!Q)return $.json({error:"Organization scope required"},500);let Y=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!Y||!G)return $.json({error:"virtualMcpId and branch are required"},400);if(!EN6(G))return $.json({error:`Invalid branch name: ${G}`},400);let J=X.auth?.user?.id??null;if(!J){let B=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!B||!vl$(B,{organizationId:Q.id,virtualMcpId:Y,branch:G}))return $.json({error:"Unauthorized"},401)}let K=await X.storage.virtualMcps.findById(Y);if(!K||K.organization_id!==Q.id)return $.json({error:"Virtual MCP not found"},404);let W=K.metadata??null;if(!uO0(W))return $.json({error:"Project has no preview server configured"},404);let H=K.connections?.map((B)=>B.connection_id)??[],N=Hs(W,H);if(!N)return $.json({error:"Project has no GitHub repository"},404);let U=W?.runtime;return $.set("decofileScope",{organizationId:Q.id,virtualMcpId:Y,branch:G,packagePath:U?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:N,userId:J}),Z()})});var ll$=($)=>{let Z=new H1;if(Z.use("*",r_),Z.route("/",HA0()),Z.route("/",Yg$()),Z.route("/",Hc$()),Z.route("/",Kc$()),Z.route("/",mA0()),Z.route("/tools",wc$()),Z.route("/",Oc$()),Z.route("/",uu$({kvStorage:$.kvStorage})),Z.route("/",gu$()),Z.route("/fs",$c$({getConnection:$.getNatsConnection})),Z.route("/sandbox",Ml$()),Z.route("/decofile",ul$()),Z.route("/",Yc$()),Z.route("/deco-sites",UA0()),Z.route("/sso",YA0()),Z.route("/",iA0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",ry$()),$.mountDevAssets)Z.route("/dev-assets",BA0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",Lb$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",Xc$()),Z.route("/mcp",Ow0()),Z.route("/mcp/self",dA0()),Z.route("/mcp",ww0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var dl$=D(()=>{U8();O91();ay$();E91();OA0();_a();U91();hu$();cu$();Zc$();ht();J91();Ew0();hZ1();Qc$();Gc$();Wc$();Nc$();Dc$();cZ1();Ec$();lZ1();Dw0();kl$();cl$()});function AN6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var TN6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},ml$=()=>{let $=new H1;return $.use("*",TN6),$.get("/",async(Z)=>{let X=b0(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await nZ(Q,Y,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:AN6(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var il$=D(()=>{U8();R$();WP0()});import{z as M1}from"zod";function EF($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function vN6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let X=$.substring(0,Z),Q=$.substring(Z+1);if(!X||!Q)return null;return{credentialId:X,modelId:Q}}function fN6($,Z,X){try{return JSON.parse($)}catch{throw new tl$(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function bN6($){let Z={};for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Q of X.tool_calls)Z[Q.id]=Q.function.name;return $.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};return{type:"image",image:Y.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((Y)=>({type:"tool-call",toolCallId:Y.id,toolName:Y.function.name,input:fN6(Y.function.arguments,Y.id,Y.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let Q=Z[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:Q,output:{type:"text",value:X.content}}]}}})}function xN6($){let Z=$.map((X)=>{let Q=X.function.parameters?dY(X.function.parameters):dY({type:"object",properties:{}});return[X.function.name,I$({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function yN6($){if(!$)return;return{openai:{response_format:$}}}function gN6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function pl$($,Z,X,Q,Y,G){let J={model:$,messages:Z,tools:X,temperature:Q.temperature,maxTokens:Q.max_tokens,topP:Q.top_p,frequencyPenalty:Q.frequency_penalty,presencePenalty:Q.presence_penalty,stopSequences:Q.stop?Array.isArray(Q.stop)?Q.stop:[Q.stop]:void 0,abortSignal:G};return Y?{...J,providerOptions:Y}:J}function nl$($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var RN6=256,IN6,qN6,MN6,kN6,VN6,SN6,CN6,_N6,tl$,ol$,rl$;var al$=D(()=>{D4();U8();hu();jN();IN6=M1.object({type:M1.literal("function"),function:M1.object({name:M1.string(),description:M1.string().optional(),parameters:M1.record(M1.string(),M1.unknown()).optional()})}),qN6=M1.object({id:M1.string(),type:M1.literal("function"),function:M1.object({name:M1.string(),arguments:M1.string()})}),MN6=M1.discriminatedUnion("role",[M1.object({role:M1.literal("system"),content:M1.string(),name:M1.string().optional()}),M1.object({role:M1.literal("user"),content:M1.union([M1.string(),M1.array(M1.union([M1.object({type:M1.literal("text"),text:M1.string()}),M1.object({type:M1.literal("image_url"),image_url:M1.object({url:M1.string(),detail:M1.string().optional()})})]))]),name:M1.string().optional()}),M1.object({role:M1.literal("assistant"),content:M1.string().nullable().optional(),name:M1.string().optional(),tool_calls:M1.array(qN6).optional()}),M1.object({role:M1.literal("tool"),content:M1.string(),tool_call_id:M1.string()})]),kN6=M1.object({type:M1.literal("text")}),VN6=M1.object({type:M1.literal("json_object")}),SN6=M1.object({type:M1.literal("json_schema"),json_schema:M1.object({name:M1.string(),description:M1.string().optional(),schema:M1.record(M1.string(),M1.unknown()),strict:M1.boolean().optional()})}),CN6=M1.union([kN6,VN6,SN6]),_N6=M1.object({model:M1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:M1.array(MN6),stream:M1.boolean().optional().default(!1),temperature:M1.number().min(0).max(2).optional(),max_tokens:M1.number().positive().optional(),top_p:M1.number().min(0).max(1).optional(),frequency_penalty:M1.number().min(-2).max(2).optional(),presence_penalty:M1.number().min(-2).max(2).optional(),stop:M1.union([M1.string(),M1.array(M1.string())]).optional(),tools:M1.array(IN6).optional(),tool_choice:M1.union([M1.literal("auto"),M1.literal("none"),M1.literal("required"),M1.object({type:M1.literal("function"),function:M1.object({name:M1.string()})})]).optional(),response_format:CN6.optional(),user:M1.string().optional()});tl$=class tl$ extends Error{constructor($){super($);this.name="MessageConversionError"}};ol$=new H1;ol$.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(EF("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(EF("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==X)return $.json(EF("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=_N6.safeParse(Q);if(!Y.success){let w=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(EF(`Invalid request: ${w.message}`,"invalid_request_error",w.path.length>0?w.path.join("."):null),400)}let G=Y.data,J=vN6(G.model);if(!J)return $.json(EF("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:K}=J,{modelId:W}=J;if(!K){let E=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((j)=>Zw(j.providerId));if(!E)return $.json(EF("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);K=E.id}let F;try{F=await Z.aiProviders.activate(K,Z.organization.id)}catch{return $.json(EF(`AI provider credential not found or inaccessible: ${K}`,"invalid_request_error","model"),404)}let H=F.aiSdk.languageModel(W),N=bN6(G.messages),U=G.tools?xN6(G.tools):void 0,B=yN6(G.response_format),O=gN6(),L=Math.floor(Date.now()/1000);if(G.stream)return hN($,async(w)=>{let E=pl$(H,N,U,G,B,$.req.raw.signal);try{let j=OO(E),z=!1,A=0,P="",I=async()=>{if(P.length===0)return;let q=P;P="",await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{content:q},finish_reason:null}]})})};for await(let q of j.fullStream){if(!z&&(q.type==="text-delta"||q.type==="tool-call"))await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(q.type==="text-delta"){if(P+=q.text,P.length>=RN6)await I()}else if(q.type==="tool-call"){await I();let k=A++;await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:k,id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.input)}}]},finish_reason:null}]})})}else if(q.type==="finish")await I(),await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{},finish_reason:nl$(q.finishReason)}],usage:q.totalUsage?{prompt_tokens:q.totalUsage.inputTokens??0,completion_tokens:q.totalUsage.outputTokens??0,total_tokens:q.totalUsage.totalTokens??0}:void 0})})}await I(),await w.writeSSE({data:"[DONE]"})}catch(j){let z=j;console.error("[openai-compat:stream] Error:",z.message),await w.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let w=pl$(H,N,U,G,B,$.req.raw.signal),E=await UO(w),j={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)j.tool_calls=E.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),j.content=null;return $.json({id:O,object:"chat.completion",created:L,model:G.model,choices:[{index:0,message:j,finish_reason:nl$(E.finishReason)}],usage:{prompt_tokens:E.usage?.inputTokens??0,completion_tokens:E.usage?.outputTokens??0,total_tokens:E.usage?.totalTokens??0}})}}catch(Q){let Y=Q;if(Y.name==="AbortError")return $.json(EF("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(EF(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(EF(Y.message,"server_error"),500)}});rl$=ol$});function hN6($){if(typeof $!=="object"||$===null)return!1;let X=$.githubRepo?.url;return typeof X==="string"&&X.length>0}function sl$(){let $=new H1;return $.use("*",async(Z,X)=>{await X(),Z.header("Cache-Control","private, no-store"),Z.header("Vary","Cookie")}),$.get("/",async(Z)=>{let X=Z.get("studioContext"),Q=o0(X);if(!Q)return Z.json({error:"Authentication required"},401);let G=(Z.req.query("site")??"").trim().toLowerCase();if(!tG(G))return Z.json({error:"Invalid site slug"},400);let J=await X.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.id as id","organization.slug as slug","organization.name as name","organization.metadata as metadata"]).where("member.userId","=",Q).execute(),K=[];for(let F of J){if(!F.slug||_Z(F))continue;let H=await X.storage.virtualMcps.list(F.id);for(let N of H){if(ms1(N)!==G)continue;if(!hN6(N.metadata))continue;K.push({orgSlug:F.slug,orgName:F.name??F.slug,project:{id:N.id,title:N.title,icon:N.icon??null}})}}let W={matches:K};return Z.json(W)}),$}var el$=D(()=>{U8();rB()});var Zd$;var $d$=D(()=>{Zd$={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"}}});function lN6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??cN6}}var Xd$,cN6="https://ph.studio.decocms.com",Qd$;var Yd$=D(()=>{U8();y50();CC();$9();R$();a51();$d$();Xd$=new H1;Xd$.get("/",($)=>{let Z={version:Zd$.version,theme:Oi1(),...jH().logo&&{logo:jH().logo},...GN()&&{internalUrl:mC1()},...b0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!b0().firecrawlApiKey,auth:Jy$(),posthog:lN6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:Ps()}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});Qd$=Xd$});function nu($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function L71($){return(nu($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function Jd$($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(nu($))}&sz=${Z}`}function Gd$($,Z){let X=$.trim();if(X.length<=Z)return X;let Q=X.slice(0,Z-1),Y=Q.lastIndexOf(" ");return`${(Y>Z*0.6?Q.slice(0,Y):Q).trimEnd()}\u2026`}function Kd$($){let{brand:Z,domain:X,score:Q,verdict:Y}=$,G=typeof Q==="number"?`${Z} commerce report \u2014 ${Math.round(Q)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=`See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,K=Y?.trim()?Gd$(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):Gd$(`How does ${X} really perform? ${J}`,200);return{title:G,description:K}}import{z as l0}from"zod";var Fv,dN6,mN6,iN6,pN6,Wd$;var Fd$=D(()=>{Fv=l0.enum(["good","bad","neutral"]),dN6=l0.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},l0.object({kind:l0.enum(["text","number","sparkline","badge","score"]).catch("text"),value:l0.coerce.string().optional(),tone:Fv.optional(),muted:l0.boolean().optional(),delta:l0.coerce.string().optional(),deltaDir:l0.enum(["up","down","neutral"]).optional(),points:l0.array(l0.coerce.number()).optional(),label:l0.coerce.string().optional()}).transform(($)=>{if($.kind==="badge"&&$.label==null)$.label=$.value??"";if($.kind==="score"){let Z=Number($.value);if(Number.isNaN(Z))return{...$,kind:"text"}}return $})),mN6=l0.preprocess(($)=>{let Z=$;if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Array.isArray(Z.cells))Z=Z.cells;if(Array.isArray(Z)&&Z.length===1&&Array.isArray(Z[0]))Z=Z[0];if(Array.isArray(Z))return Z;if(Z&&typeof Z==="object")return Object.values(Z);return Z},l0.array(dN6)),iN6={key:l0.coerce.string(),title:l0.coerce.string(),eyebrow:l0.coerce.string().optional(),headline:l0.coerce.string(),annotation:l0.coerce.string().optional(),methodology:l0.coerce.string().optional(),sources:l0.array(l0.object({name:l0.coerce.string(),logoUrl:l0.coerce.string()})).optional()},pN6=l0.discriminatedUnion("template",[l0.object({template:l0.literal("cover"),score:l0.object({value:l0.coerce.number(),max:l0.coerce.number().optional(),grade:l0.coerce.string().optional(),label:l0.coerce.string().optional()}).optional(),brandImage:l0.coerce.string().optional(),screenshot:l0.coerce.string().optional(),mobileScreenshot:l0.coerce.string().optional()}),l0.object({template:l0.literal("cta"),ctaUrl:l0.coerce.string().optional(),ctaLabel:l0.coerce.string().optional(),bullets:l0.array(l0.coerce.string()).optional()}),l0.object({template:l0.literal("series"),points:l0.array(l0.coerce.number()).min(2),xLabels:l0.array(l0.coerce.string()).min(1),unit:l0.coerce.string().optional(),callout:l0.object({index:l0.coerce.number(),value:l0.coerce.string(),tone:Fv.optional()})}),l0.object({template:l0.literal("threshold"),value:l0.coerce.string().default(""),metricLabel:l0.coerce.string().optional(),ratio:l0.coerce.number(),thresholdRatio:l0.coerce.number().optional(),thresholdLabel:l0.coerce.string().default(""),tone:Fv.optional()}),l0.object({template:l0.literal("stats"),stats:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),tone:Fv.optional()})).min(1)}),l0.object({template:l0.literal("bars"),items:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),ratio:l0.coerce.number(),tone:Fv.optional()})).min(1)}),l0.object({template:l0.literal("gauges"),gauges:l0.array(l0.object({label:l0.coerce.string(),value:l0.coerce.string(),status:l0.enum(["good","warn","bad"]).catch("warn"),caption:l0.coerce.string().optional(),ratio:l0.coerce.number().optional()})).min(1)}),l0.object({template:l0.literal("checklist"),checks:l0.array(l0.object({label:l0.coerce.string(),status:l0.enum(["pass","fail","warn"]).catch("fail"),value:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("table"),columns:l0.array(l0.object({label:l0.coerce.string(),align:l0.enum(["left","right"]).optional()})).min(1),rows:l0.array(mN6).min(1),highlightRow:l0.coerce.number().optional()}),l0.object({template:l0.literal("products"),products:l0.array(l0.object({name:l0.coerce.string(),price:l0.coerce.string().optional(),image:l0.coerce.string().optional(),url:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("list"),entries:l0.array(l0.object({label:l0.coerce.string(),severity:l0.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:l0.coerce.number().optional()}),l0.object({template:l0.literal("keywords"),volumeLabel:l0.coerce.string().optional(),keywords:l0.array(l0.object({term:l0.coerce.string(),volume:l0.coerce.string(),position:l0.coerce.number().catch(0)})).min(1)}),l0.object({template:l0.literal("competitor"),metricLabel:l0.coerce.string().optional(),competitors:l0.array(l0.object({name:l0.coerce.string(),value:l0.coerce.string(),tone:Fv.optional(),isYou:l0.boolean().optional()})).min(1)}),l0.object({template:l0.literal("scorecard"),rivalLabel:l0.coerce.string().optional(),dimensions:l0.array(l0.object({label:l0.coerce.string(),you:l0.coerce.string(),rival:l0.coerce.string().optional(),rivalName:l0.coerce.string().optional(),tone:Fv.optional()})).min(1)})]),Wd$=l0.object({...iN6,template:pN6})});function UT0($){let Z=[],X=[...$.sections].sort((Y,G)=>Y.position-G.position).map((Y)=>{let G=Wd$.safeParse(Y.props);if(G.success)return G.data;let J=G.error.issues[0];return Z.push({section_type:Y.section_type,position:Y.position,reason:J?`${J.path.join(".")||"(root)"}: ${J.message}`:"contract violation"}),null}).filter((Y)=>Y!==null),Q=X.filter((Y)=>Y.template.template!=="cover"&&Y.template.template!=="cta").map((Y)=>({key:Y.key,title:Y.title}));return{deck:{meta:{...$.meta,scores:$.summary?.scores,scannedAt:$.scanned_at,toc:Q},slides:X},drops:Z}}var w71=D(()=>{Fd$()});import{join as Hd$}from"path";async function tN6($){try{let Z=await fetch(`${GW({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(nN6)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=UT0(X);if(!Q.slides.length)return null;let Y=Q.slides.find((K)=>K.template.template==="cover"),G=Y?.template,J=G&&G.template==="cover"?G:void 0;return{brand:Q.meta.brand?.trim()||L71($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function OG($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function oN6($,Z){let X=nu($),Q=Z?.brand?.trim()||L71(X),Y=Jd$(X,128),J=`${(b0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:K,description:W}=Kd$({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),F=`${J}/og.png`,H=`${Q} commerce report by decocms`;return[`<title>${OG(K)}</title>`,`<meta name="description" content="${OG(W)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${OG(K)}" />`,`<meta property="og:description" content="${OG(W)}" />`,`<meta property="og:url" content="${OG(J)}" />`,`<meta property="og:image" content="${OG(F)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${OG(H)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${OG(K)}" />`,`<meta name="twitter:description" content="${OG(W)}" />`,`<meta name="twitter:image" content="${OG(F)}" />`,`<meta name="twitter:image:alt" content="${OG(H)}" />`,`<link rel="canonical" href="${OG(J)}" />`,`<link rel="icon" href="${OG(Y)}" sizes="any" />`].join(`
2923
+ `,j=await Z.createBlob(E);await Bl$(Z.owner,Z.repo,j,E);let z=w[0]??`${YT0(Q)}/${Q71(O)}.json`;F.push({path:z,mode:"100644",type:"blob",sha:j});let A=z.slice(z.lastIndexOf("/")+1,-5);H.set(z,{stem:A,sha:j,content:E});for(let P of w.slice(1))F.push({path:P,mode:"100644",type:"blob",sha:null}),H.delete(P)}for(let O of $.del)for(let L of F71(W,O))F.push({path:L,mode:"100644",type:"blob",sha:null}),H.delete(L);if(F.length===0)return G;let N=Q?`${Q}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(K.some((O)=>O.type==="blob"&&O.path===N)){let O=await Promise.all([...H.values()].map(async(j)=>({stem:j.stem,content:j.content??await Z.getBlobText(j.sha)}))),{decofile:L,skipped:w}=Js(O);if(w.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:`${Z.owner}/${Z.repo}`,branch:X,packagePath:Q,blocks:w.map((j)=>j.key)});let E=await Z.createBlob(L);F.push({path:N,mode:"100644",type:"blob",sha:E})}let U=await Z.createTree(J,F),B=await Z.createCommit({message:BN6($),treeSha:U,parentShas:[G]});try{return await Z.updateRef(X,B),B}catch(O){if(!(O instanceof u4&&O.status===422)||Y>=HN6-1)throw O;await L$(aZ(2000,200,Y,2,0.5))}}}function BN6($){let Z=(Y)=>{let G=Y.slice(0,3).join(", ");return Y.length>3?`${G} (+${Y.length-3} more)`:G},X=[];if($.set.size>0)X.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)X.push(`delete ${Z([...$.del])}`);let Q=`chore(decofile): ${X.join("; ")}`;return om0(Q,$.deps.coAuthor)}var HN6=3,O71;var Sl$=D(()=>{bO0();aA0();K4();yD();GT0();O71=new Map});import{createHmac as Cl$,randomBytes as ON6,timingSafeEqual as DN6}from"crypto";function _l$(){if(NT0)return NT0;let $;try{let Z=b0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return NT0=$?Buffer.from($):ON6(32),NT0}function D71($){let Z=$.nowMs??Date.now(),X={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+LN6)/1000)},Q=Buffer.from(JSON.stringify(X)).toString("base64url"),Y=Cl$("sha256",_l$()).update(Q).digest("base64url");return`${Q}.${Y}`}function vl$($,Z){let X=$.indexOf(".");if(X<0)return!1;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(Cl$("sha256",_l$()).update(Q).digest("base64url"));if(Y.length!==G.length||!DN6(Y,G))return!1;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return!1}let K=Math.floor((Z.nowMs??Date.now())/1000);return J.o===Z.organizationId&&J.m===Z.virtualMcpId&&J.b===Z.branch&&typeof J.e==="number"&&J.e>=K}var LN6=21600000,NT0=null;var fl$=D(()=>{R$()});import{z as pu}from"zod";function EN6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&wN6.test($)}function hl$($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function Us($){let Z=$.get("decofileScope");return oA0($.var.studioContext,Z.organizationId,Z.githubRepo)}function Bs($,Z){if(Z instanceof u4){let Q=Z.status===404?404:Z.status===409?409:Z.status===422?409:502;return $.json({error:Z.message},Q)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},500)}function ul$(){let $=new H1;return $.use("/:virtualMcpId/:branch",gl$),$.use("/:virtualMcpId/:branch/*",gl$),$.get("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Us(Z),Y=await Ol$(Q,X.branch,X.packagePath,{createBranchIfMissing:!!X.userId}),G={ETag:`"${Y.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${Y.sha}"`)return Z.body(null,304,G);if(!X.userId)return Z.body(Y.decofile,200,{...G,"content-type":"application/json"});let J=D71({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.body(`{"version":${JSON.stringify(Y.sha)},"token":${JSON.stringify(J)},"apiHost":${JSON.stringify(hl$(Z))},"decofile":${Y.decofile}}`,200,{...G,"content-type":"application/json"})}catch(Q){return Bs(Z,Q)}}),$.get("/:virtualMcpId/:branch/meta",async(Z)=>{let X=Z.get("decofileScope"),Q=X.packagePath?`${X.packagePath}/.deco/meta.gen.json`:".deco/meta.gen.json";try{let Y=await Us(Z),G=await Y.getFileTextAtRef(X.branch,Q);if(G===null){let J=await Y.getDefaultBranch();if(J!==X.branch)G=await Y.getFileTextAtRef(J,Q)}if(G===null)return Z.json({error:"meta.gen.json not committed"},404);return Z.body(G,200,{"content-type":"application/json","Cache-Control":"no-store","Access-Control-Allow-Origin":"*"})}catch(Y){return Bs(Z,Y)}}),$.patch("/:virtualMcpId/:branch",zN6,async(Z)=>{let X=Z.get("decofileScope"),Q=Z.var.studioContext,Y=PN6.safeParse(await Z.req.json().catch(()=>null));if(!Y.success)return Z.json({error:"Invalid body",details:Y.error.issues},400);let G=Y.data;for(let J of[...Object.keys(G.set??{}),...G.delete??[]])try{rA0(J)}catch(K){let W=K instanceof Error?K.message:String(K);return Z.json({error:W},400)}for(let[J,K]of Object.entries(G.set??{}))if(typeof K!=="object"||K===null||Array.isArray(K))return Z.json({error:`Block "${J}" must be a JSON object`},400);try{let J=await Us(Z),K=await Vl$(`${X.organizationId}/${X.virtualMcpId}/${X.branch}`,{client:J,branch:X.branch,packagePath:X.packagePath,coAuthor:uu(Q)},G),W=D71({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.json({version:K,token:W,apiHost:hl$(Z)})}catch(J){return Bs(Z,J)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Us(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({error:"Branch is already the default branch"},400);let G=`chore(decofile): publish ${X.branch}`;try{let J;try{J=await Q.mergeBranch(Y,X.branch,G)}catch(K){if(!(K instanceof u4&&K.status===409))throw K;await WT0(Q,X.branch,Y),J=await Q.mergeBranch(Y,X.branch,G)}return J?Z.json({result:"merged",sha:J}):Z.json({result:"up-to-date"})}catch(J){if(J instanceof u4&&J.status===409)return Z.json({error:"merge-conflict"},409);if(J instanceof u4&&J.status===405){let W=await Q.findOpenPullRequest(Y,X.branch)??await Q.createPullRequest({base:Y,head:X.branch,title:`Publish ${X.branch}`});return Z.json({result:"pull-request",number:W.number,url:W.html_url})}throw J}}catch(Q){return Bs(Z,Q)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await Us(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});try{let{aheadBy:G,behindBy:J}=await Q.compare(Y,X.branch);return Z.json({baseBranch:Y,aheadBy:G,behindBy:J})}catch(G){if(G instanceof u4&&G.status===404)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});throw G}}catch(Q){return Bs(Z,Q)}}),$}var wN6,bl$=500,xl$=1048576,yl$=1024,jN6=8388608,zN6,PN6,gl$;var cl$=D(()=>{aA0();U8();BF();pZ1();tA0();U71();X71();Sl$();fl$();N71();yD();GT0();wN6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;zN6=p5({maxSize:jN6,onError:($)=>$.json({error:"Payload too large"},413)}),PN6=pu.object({set:pu.record(pu.string(),pu.unknown()).optional(),delete:pu.array(pu.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}).refine(($)=>Object.keys($.set??{}).length+($.delete?.length??0)<=bl$,{message:`Patch cannot touch more than ${bl$} blocks`}).refine(($)=>Object.values($.set??{}).every((Z)=>JSON.stringify(Z).length<=xl$),{message:`Each block must be at most ${xl$} bytes`}).refine(($)=>[...Object.keys($.set??{}),...$.delete??[]].every((Z)=>Z.length<=yl$),{message:`Each block key must be at most ${yl$} characters`}),gl$=nA0(async($,Z)=>{let X=$.var.studioContext,Q=X.organization;if(!Q)return $.json({error:"Organization scope required"},500);let Y=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!Y||!G)return $.json({error:"virtualMcpId and branch are required"},400);if(!EN6(G))return $.json({error:`Invalid branch name: ${G}`},400);let J=X.auth?.user?.id??null;if(!J){let B=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!B||!vl$(B,{organizationId:Q.id,virtualMcpId:Y,branch:G}))return $.json({error:"Unauthorized"},401)}let K=await X.storage.virtualMcps.findById(Y);if(!K||K.organization_id!==Q.id)return $.json({error:"Virtual MCP not found"},404);let W=K.metadata??null;if(!uO0(W))return $.json({error:"Project has no preview server configured"},404);let H=K.connections?.map((B)=>B.connection_id)??[],N=Hs(W,H);if(!N)return $.json({error:"Project has no GitHub repository"},404);let U=W?.runtime;return $.set("decofileScope",{organizationId:Q.id,virtualMcpId:Y,branch:G,packagePath:U?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:N,userId:J}),Z()})});var ll$=($)=>{let Z=new H1;if(Z.use("*",r_),Z.route("/",HA0()),Z.route("/",Yg$()),Z.route("/",Hc$()),Z.route("/",Kc$()),Z.route("/",mA0()),Z.route("/tools",wc$()),Z.route("/",Oc$()),Z.route("/",uu$({kvStorage:$.kvStorage})),Z.route("/",gu$()),Z.route("/fs",$c$({getConnection:$.getNatsConnection})),Z.route("/sandbox",Ml$()),Z.route("/decofile",ul$()),Z.route("/",Yc$()),Z.route("/deco-sites",UA0()),Z.route("/sso",YA0()),Z.route("/",iA0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",ry$()),$.mountDevAssets)Z.route("/dev-assets",BA0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",Lb$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",Xc$()),Z.route("/mcp",Ow0()),Z.route("/mcp/self",dA0()),Z.route("/mcp",ww0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var dl$=D(()=>{U8();O91();ay$();E91();OA0();_a();U91();hu$();cu$();Zc$();ht();J91();Ew0();hZ1();Qc$();Gc$();Wc$();Nc$();Dc$();cZ1();Ec$();lZ1();Dw0();kl$();cl$()});function AN6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var TN6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},ml$=()=>{let $=new H1;return $.use("*",TN6),$.get("/",async(Z)=>{let X=b0(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await nZ(Q,Y,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:AN6(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var il$=D(()=>{U8();R$();WP0()});import{z as M1}from"zod";function EF($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function vN6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let X=$.substring(0,Z),Q=$.substring(Z+1);if(!X||!Q)return null;return{credentialId:X,modelId:Q}}function fN6($,Z,X){try{return JSON.parse($)}catch{throw new tl$(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function bN6($){let Z={};for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Q of X.tool_calls)Z[Q.id]=Q.function.name;return $.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};return{type:"image",image:Y.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((Y)=>({type:"tool-call",toolCallId:Y.id,toolName:Y.function.name,input:fN6(Y.function.arguments,Y.id,Y.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let Q=Z[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:Q,output:{type:"text",value:X.content}}]}}})}function xN6($){let Z=$.map((X)=>{let Q=X.function.parameters?dY(X.function.parameters):dY({type:"object",properties:{}});return[X.function.name,I$({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function yN6($){if(!$)return;return{openai:{response_format:$}}}function gN6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function pl$($,Z,X,Q,Y,G){let J={model:$,messages:Z,tools:X,temperature:Q.temperature,maxTokens:Q.max_tokens,topP:Q.top_p,frequencyPenalty:Q.frequency_penalty,presencePenalty:Q.presence_penalty,stopSequences:Q.stop?Array.isArray(Q.stop)?Q.stop:[Q.stop]:void 0,abortSignal:G};return Y?{...J,providerOptions:Y}:J}function nl$($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var RN6=256,IN6,qN6,MN6,kN6,VN6,SN6,CN6,_N6,tl$,ol$,rl$;var al$=D(()=>{D4();U8();hu();jN();IN6=M1.object({type:M1.literal("function"),function:M1.object({name:M1.string(),description:M1.string().optional(),parameters:M1.record(M1.string(),M1.unknown()).optional()})}),qN6=M1.object({id:M1.string(),type:M1.literal("function"),function:M1.object({name:M1.string(),arguments:M1.string()})}),MN6=M1.discriminatedUnion("role",[M1.object({role:M1.literal("system"),content:M1.string(),name:M1.string().optional()}),M1.object({role:M1.literal("user"),content:M1.union([M1.string(),M1.array(M1.union([M1.object({type:M1.literal("text"),text:M1.string()}),M1.object({type:M1.literal("image_url"),image_url:M1.object({url:M1.string(),detail:M1.string().optional()})})]))]),name:M1.string().optional()}),M1.object({role:M1.literal("assistant"),content:M1.string().nullable().optional(),name:M1.string().optional(),tool_calls:M1.array(qN6).optional()}),M1.object({role:M1.literal("tool"),content:M1.string(),tool_call_id:M1.string()})]),kN6=M1.object({type:M1.literal("text")}),VN6=M1.object({type:M1.literal("json_object")}),SN6=M1.object({type:M1.literal("json_schema"),json_schema:M1.object({name:M1.string(),description:M1.string().optional(),schema:M1.record(M1.string(),M1.unknown()),strict:M1.boolean().optional()})}),CN6=M1.union([kN6,VN6,SN6]),_N6=M1.object({model:M1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:M1.array(MN6),stream:M1.boolean().optional().default(!1),temperature:M1.number().min(0).max(2).optional(),max_tokens:M1.number().positive().optional(),top_p:M1.number().min(0).max(1).optional(),frequency_penalty:M1.number().min(-2).max(2).optional(),presence_penalty:M1.number().min(-2).max(2).optional(),stop:M1.union([M1.string(),M1.array(M1.string())]).optional(),tools:M1.array(IN6).optional(),tool_choice:M1.union([M1.literal("auto"),M1.literal("none"),M1.literal("required"),M1.object({type:M1.literal("function"),function:M1.object({name:M1.string()})})]).optional(),response_format:CN6.optional(),user:M1.string().optional()});tl$=class tl$ extends Error{constructor($){super($);this.name="MessageConversionError"}};ol$=new H1;ol$.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(EF("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(EF("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==X)return $.json(EF("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=_N6.safeParse(Q);if(!Y.success){let w=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(EF(`Invalid request: ${w.message}`,"invalid_request_error",w.path.length>0?w.path.join("."):null),400)}let G=Y.data,J=vN6(G.model);if(!J)return $.json(EF("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:K}=J,{modelId:W}=J;if(!K){let E=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((j)=>Zw(j.providerId));if(!E)return $.json(EF("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);K=E.id}let F;try{F=await Z.aiProviders.activate(K,Z.organization.id)}catch{return $.json(EF(`AI provider credential not found or inaccessible: ${K}`,"invalid_request_error","model"),404)}let H=F.aiSdk.languageModel(W),N=bN6(G.messages),U=G.tools?xN6(G.tools):void 0,B=yN6(G.response_format),O=gN6(),L=Math.floor(Date.now()/1000);if(G.stream)return hN($,async(w)=>{let E=pl$(H,N,U,G,B,$.req.raw.signal);try{let j=OO(E),z=!1,A=0,P="",I=async()=>{if(P.length===0)return;let q=P;P="",await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{content:q},finish_reason:null}]})})};for await(let q of j.fullStream){if(!z&&(q.type==="text-delta"||q.type==="tool-call"))await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(q.type==="text-delta"){if(P+=q.text,P.length>=RN6)await I()}else if(q.type==="tool-call"){await I();let k=A++;await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:k,id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.input)}}]},finish_reason:null}]})})}else if(q.type==="finish")await I(),await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{},finish_reason:nl$(q.finishReason)}],usage:q.totalUsage?{prompt_tokens:q.totalUsage.inputTokens??0,completion_tokens:q.totalUsage.outputTokens??0,total_tokens:q.totalUsage.totalTokens??0}:void 0})})}await I(),await w.writeSSE({data:"[DONE]"})}catch(j){let z=j;console.error("[openai-compat:stream] Error:",z.message),await w.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let w=pl$(H,N,U,G,B,$.req.raw.signal),E=await UO(w),j={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)j.tool_calls=E.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),j.content=null;return $.json({id:O,object:"chat.completion",created:L,model:G.model,choices:[{index:0,message:j,finish_reason:nl$(E.finishReason)}],usage:{prompt_tokens:E.usage?.inputTokens??0,completion_tokens:E.usage?.outputTokens??0,total_tokens:E.usage?.totalTokens??0}})}}catch(Q){let Y=Q;if(Y.name==="AbortError")return $.json(EF("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(EF(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(EF(Y.message,"server_error"),500)}});rl$=ol$});function hN6($){if(typeof $!=="object"||$===null)return!1;let X=$.githubRepo?.url;return typeof X==="string"&&X.length>0}function sl$(){let $=new H1;return $.use("*",async(Z,X)=>{await X(),Z.header("Cache-Control","private, no-store"),Z.header("Vary","Cookie")}),$.get("/",async(Z)=>{let X=Z.get("studioContext"),Q=o0(X);if(!Q)return Z.json({error:"Authentication required"},401);let G=(Z.req.query("site")??"").trim().toLowerCase();if(!tG(G))return Z.json({error:"Invalid site slug"},400);let J=await X.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.id as id","organization.slug as slug","organization.name as name","organization.metadata as metadata"]).where("member.userId","=",Q).execute(),K=[];for(let F of J){if(!F.slug||_Z(F))continue;let H=await X.storage.virtualMcps.list(F.id);for(let N of H){if(ms1(N)!==G)continue;if(!hN6(N.metadata))continue;K.push({orgSlug:F.slug,orgName:F.name??F.slug,project:{id:N.id,title:N.title,icon:N.icon??null}})}}let W={matches:K};return Z.json(W)}),$}var el$=D(()=>{U8();rB()});var Zd$;var $d$=D(()=>{Zd$={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"}}});function lN6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??cN6}}var Xd$,cN6="https://ph.studio.decocms.com",Qd$;var Yd$=D(()=>{U8();y50();CC();$9();R$();a51();$d$();Xd$=new H1;Xd$.get("/",($)=>{let Z={version:Zd$.version,theme:Oi1(),...jH().logo&&{logo:jH().logo},...GN()&&{internalUrl:mC1()},...b0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!b0().firecrawlApiKey,auth:Jy$(),posthog:lN6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:Ps()}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});Qd$=Xd$});function nu($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function L71($){return(nu($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function Jd$($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(nu($))}&sz=${Z}`}function Gd$($,Z){let X=$.trim();if(X.length<=Z)return X;let Q=X.slice(0,Z-1),Y=Q.lastIndexOf(" ");return`${(Y>Z*0.6?Q.slice(0,Y):Q).trimEnd()}\u2026`}function Kd$($){let{brand:Z,domain:X,score:Q,verdict:Y}=$,G=typeof Q==="number"?`${Z} commerce report \u2014 ${Math.round(Q)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=`See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,K=Y?.trim()?Gd$(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):Gd$(`How does ${X} really perform? ${J}`,200);return{title:G,description:K}}import{z as l0}from"zod";var Fv,dN6,mN6,iN6,pN6,Wd$;var Fd$=D(()=>{Fv=l0.enum(["good","bad","neutral"]),dN6=l0.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},l0.object({kind:l0.enum(["text","number","sparkline","badge","score"]).catch("text"),value:l0.coerce.string().optional(),tone:Fv.optional(),muted:l0.boolean().optional(),delta:l0.coerce.string().optional(),deltaDir:l0.enum(["up","down","neutral"]).optional(),points:l0.array(l0.coerce.number()).optional(),label:l0.coerce.string().optional()}).transform(($)=>{if($.kind==="badge"&&$.label==null)$.label=$.value??"";if($.kind==="score"){let Z=Number($.value);if(Number.isNaN(Z))return{...$,kind:"text"}}return $})),mN6=l0.preprocess(($)=>{let Z=$;if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Array.isArray(Z.cells))Z=Z.cells;if(Array.isArray(Z)&&Z.length===1&&Array.isArray(Z[0]))Z=Z[0];if(Array.isArray(Z))return Z;if(Z&&typeof Z==="object")return Object.values(Z);return Z},l0.array(dN6)),iN6={key:l0.coerce.string(),title:l0.coerce.string(),eyebrow:l0.coerce.string().optional(),headline:l0.coerce.string(),annotation:l0.coerce.string().optional(),methodology:l0.coerce.string().optional(),sources:l0.array(l0.object({name:l0.coerce.string(),logoUrl:l0.coerce.string()})).optional()},pN6=l0.discriminatedUnion("template",[l0.object({template:l0.literal("cover"),score:l0.object({value:l0.coerce.number(),max:l0.coerce.number().optional(),grade:l0.coerce.string().optional(),label:l0.coerce.string().optional()}).optional(),brandImage:l0.coerce.string().optional(),screenshot:l0.coerce.string().optional(),mobileScreenshot:l0.coerce.string().optional()}),l0.object({template:l0.literal("cta"),ctaUrl:l0.coerce.string().optional(),ctaLabel:l0.coerce.string().optional(),bullets:l0.array(l0.coerce.string()).optional()}),l0.object({template:l0.literal("series"),points:l0.array(l0.coerce.number()).min(2),xLabels:l0.array(l0.coerce.string()).min(1),unit:l0.coerce.string().optional(),callout:l0.object({index:l0.coerce.number(),value:l0.coerce.string(),tone:Fv.optional()})}),l0.object({template:l0.literal("threshold"),value:l0.coerce.string().default(""),metricLabel:l0.coerce.string().optional(),ratio:l0.coerce.number(),thresholdRatio:l0.coerce.number().optional(),thresholdLabel:l0.coerce.string().default(""),tone:Fv.optional()}),l0.object({template:l0.literal("stats"),stats:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),tone:Fv.optional()})).min(1)}),l0.object({template:l0.literal("bars"),items:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),ratio:l0.coerce.number(),tone:Fv.optional()})).min(1)}),l0.object({template:l0.literal("gauges"),gauges:l0.array(l0.object({label:l0.coerce.string(),value:l0.coerce.string(),status:l0.enum(["good","warn","bad"]).catch("warn"),caption:l0.coerce.string().optional(),ratio:l0.coerce.number().optional()})).min(1)}),l0.object({template:l0.literal("checklist"),checks:l0.array(l0.object({label:l0.coerce.string(),status:l0.enum(["pass","fail","warn"]).catch("fail"),value:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("table"),columns:l0.array(l0.object({label:l0.coerce.string(),align:l0.enum(["left","right"]).optional()})).min(1),rows:l0.array(mN6).min(1),highlightRow:l0.coerce.number().optional()}),l0.object({template:l0.literal("products"),products:l0.array(l0.object({name:l0.coerce.string(),price:l0.coerce.string().optional(),image:l0.coerce.string().optional(),url:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("list"),entries:l0.array(l0.object({label:l0.coerce.string(),severity:l0.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:l0.coerce.number().optional()}),l0.object({template:l0.literal("keywords"),volumeLabel:l0.coerce.string().optional(),keywords:l0.array(l0.object({term:l0.coerce.string(),volume:l0.coerce.string(),position:l0.coerce.number().catch(0)})).min(1)}),l0.object({template:l0.literal("competitor"),metricLabel:l0.coerce.string().optional(),competitors:l0.array(l0.object({name:l0.coerce.string(),value:l0.coerce.string(),tone:Fv.optional(),isYou:l0.boolean().optional()})).min(1)}),l0.object({template:l0.literal("scorecard"),rivalLabel:l0.coerce.string().optional(),dimensions:l0.array(l0.object({label:l0.coerce.string(),you:l0.coerce.string(),rival:l0.coerce.string().optional(),rivalName:l0.coerce.string().optional(),tone:Fv.optional()})).min(1)})]),Wd$=l0.object({...iN6,template:pN6})});function UT0($){let Z=[],X=[...$.sections].sort((Y,G)=>Y.position-G.position).map((Y)=>{let G=Wd$.safeParse(Y.props);if(G.success)return G.data;let J=G.error.issues[0];return Z.push({section_type:Y.section_type,position:Y.position,reason:J?`${J.path.join(".")||"(root)"}: ${J.message}`:"contract violation"}),null}).filter((Y)=>Y!==null),Q=X.filter((Y)=>Y.template.template!=="cover"&&Y.template.template!=="cta").map((Y)=>({key:Y.key,title:Y.title}));return{deck:{meta:{...$.meta,scores:$.summary?.scores,scannedAt:$.scanned_at,toc:Q},slides:X},drops:Z}}var w71=D(()=>{Fd$()});import{join as Hd$}from"path";async function tN6($){try{let Z=await fetch(`${GW({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(nN6)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=UT0(X);if(!Q.slides.length)return null;let Y=Q.slides.find((K)=>K.template.template==="cover"),G=Y?.template,J=G&&G.template==="cover"?G:void 0;return{brand:Q.meta.brand?.trim()||L71($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function OG($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function oN6($,Z){let X=nu($),Q=Z?.brand?.trim()||L71(X),Y=Jd$(X,128),J=`${(b0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:K,description:W}=Kd$({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),F=`${J}/og.png`,H=`${Q} commerce report by decocms`;return[`<title>${OG(K)}</title>`,`<meta name="description" content="${OG(W)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${OG(K)}" />`,`<meta property="og:description" content="${OG(W)}" />`,`<meta property="og:url" content="${OG(J)}" />`,`<meta property="og:image" content="${OG(F)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${OG(H)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${OG(K)}" />`,`<meta name="twitter:description" content="${OG(W)}" />`,`<meta name="twitter:image" content="${OG(F)}" />`,`<meta name="twitter:image:alt" content="${OG(H)}" />`,`<link rel="canonical" href="${OG(J)}" />`,`<link rel="icon" href="${OG(Y)}" sizes="any" />`].join(`
2924
2924
  `)}function rN6($,Z){return $.replace(/<title>[\s\S]*?<\/title>\s*/i,"").replace(/<meta\s+name="(?:description|twitter:[^"]*)"[^>]*>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*>\s*/gi,"").replace(/<link\s+rel="icon"[^>]*>\s*/gi,"").replace("</head>",` ${Z}
2925
2925
  </head>`)}function Nd$($){let Z=new H1;return Z.get("/:domain/og.png",async(X)=>{let Q=nu(X.req.param("domain")),Y=async()=>{let G=$?Bun.file(Hd$($,"report-og-fallback.png")):null;if(!G||!await G.exists())return X.notFound();return X.body(new Uint8Array(await G.arrayBuffer()),200,{"Content-Type":"image/png","Cache-Control":"public, max-age=0, s-maxage=3600"})};try{let G=await fetch(`${GW({})}/api/v2/public/diagnostics/${encodeURIComponent(Q)}/og.png`,{signal:AbortSignal.timeout(aN6)}),J=G.headers.get("content-type")??"";if(!G.ok||!J.startsWith("image/")||!G.body)return Y();return X.body(G.body,200,{"Content-Type":J,"Cache-Control":"public, max-age=0, s-maxage=604800"})}catch{return Y()}}),Z.get("/:domain",async(X)=>{let Q=X.req.param("domain"),Y=$?Hd$($,"index.html"):null,G=Y?Bun.file(Y):null;if(!G||!await G.exists())return X.notFound();let J=await G.text();try{let K=await tN6(nu(Q)),W=oN6(Q,K);return X.html(rN6(J,W),200,{"Cache-Control":"public, max-age=0, s-maxage=300"})}catch{return X.html(J)}}),Z}var nN6=2500,aN6=1e4;var Ud$=D(()=>{U8();w71();GE();R$()});function Os($,Z){return fetch(`${GW({})}${$}`,Z)}async function sN6($,Z,X){let Q=new URLSearchParams;if(Z)Q.set("pw",Z);if(X)Q.set("lang",X);let Y=Q.toString()?`?${Q.toString()}`:"",G=await Os(`/api/v2/public/diagnostics/${encodeURIComponent($)}${Y}`,{headers:{Accept:"application/json"}});if(G.status===404)return{status:"not_found",deck:null,scanned_at:null,drops:[]};if(!G.ok)throw Error(`report read HTTP ${G.status}`);let J=await G.json(),{deck:K,drops:W}=UT0(J);return{status:K.slides.length?"ready":"empty",deck:K,scanned_at:J.scanned_at,drops:W}}var eN6,cN,Bd$=async($,Z)=>{if(!$.get("reportUser"))return $.json({error:"Authentication required"},401);await Z();return},Od$;var Dd$=D(()=>{U8();hY();GE();w71();eN6=new Set(["complete","errored","terminated","unknown"]),cN=new H1;cN.use("*",async($,Z)=>{let X=await X8.api.getSession({headers:$.req.raw.headers});$.set("reportUser",X?.user?.id?{email:X.user.email}:void 0),await Z(),$.header("Cache-Control","private, no-store"),$.header("Vary","Cookie");return});cN.use("/link-token/*",Bd$);cN.use("/suggest",Bd$);cN.get("/site/:domain",async($)=>{let Z=$.req.param("domain").trim();if(!Z)return $.json({error:"domain is required"},400);let X=$.get("reportUser"),Q=$.req.query("key")?.trim()||void 0,Y=$.req.query("lang")?.trim()||void 0;try{let G=await sN6(Z,Q,Y);if($.header("Cache-Control","private, no-store"),X||!G.deck)return $.json(G);return $.json({...G,deck:{...G.deck,slides:G.deck.slides.slice(0,1)},truncated:G.status==="ready"})}catch{return $.json({error:"report read failed"},502)}});cN.post("/run",async($)=>{let Z=$.get("reportUser"),X;try{X=await $.req.json()}catch{return $.json({error:"invalid JSON"},400)}let Q=typeof X.domain==="string"?X.domain.trim():"";if(!Q)return $.json({error:"domain is required"},400);let Y=Z?.email,G=typeof X.distinctId==="string"&&X.distinctId.trim()&&X.distinctId.length<=200?X.distinctId.trim():void 0;try{let J=await Os("/api/v2/diagnostics/run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${YE({})}`},body:JSON.stringify({url:Q,...Y?{email:Y}:{},distinct_id:G})});if(!J.ok)return $.json({error:`run HTTP ${J.status}`},502);let K=await J.json(),W=K.blocked?{state:"blocked"}:K.status==="fresh"?{state:"fresh"}:K.mode==="sync"?{state:"sync"}:{state:"running",id:K.id??null};return $.json(W)}catch{return $.json({error:"run failed"},502)}});cN.get("/status",async($)=>{let Z=$.req.query("id");if(!Z)return $.json({error:"id is required"},400);try{let X=await Os(`/api/v2/diagnostics/status?id=${encodeURIComponent(Z)}`,{headers:{Authorization:`Bearer ${YE({})}`}});if(!X.ok)return $.json({error:`status HTTP ${X.status}`},502);let Y=(await X.json()).status??"unknown",G={done:eN6.has(Y),status:Y};return $.json(G)}catch{return $.json({error:"status failed"},502)}});cN.get("/link-token/:id",async($)=>{let Z=$.req.param("id");try{let X=await Os(`/api/v2/public/link-tokens/${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(X.status===404)return $.json(null);if(!X.ok)return $.json({error:`link token HTTP ${X.status}`},502);return $.json(await X.json())}catch{return $.json({error:"link token resolve failed"},502)}});cN.get("/suggest",async($)=>{let Z=($.req.query("q")??"").trim().slice(0,64);if(Z.length<2)return $.json({suggestions:[]});try{let X=await Os(`/api/v2/public/suggest?q=${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(!X.ok)return $.json({suggestions:[]});let Q=await X.json();return $.json({suggestions:Array.isArray(Q.suggestions)?Q.suggestions:[]})}catch{return $.json({suggestions:[]})}});Od$=cN});import{createHmac as $U6,timingSafeEqual as ZU6}from"crypto";function wd$($,Z,X,Q=Date.now()){if(!Z||!X)return!1;let Y,G=[];for(let F of Z.split(",")){let H=F.indexOf("=");if(H<=0)continue;let N=F.slice(0,H).trim(),U=F.slice(H+1).trim();if(N==="t")Y=U;else if(N==="v1")G.push(U)}if(!Y||G.length===0)return!1;let J=Number(Y);if(!Number.isFinite(J)||Math.abs(Q/1000-J)>XU6)return!1;let K=$U6("sha256",X).update(`${Y}.${$}`).digest("hex"),W=Buffer.from(K,"hex");return G.some((F)=>{let H=Buffer.from(F,"hex");return W.length===H.length&&ZU6(W,H)})}function Ed$($){let Z;try{Z=JSON.parse($)}catch{return null}let X=fJ(Z),Q=fJ(fJ(X?.data)?.object);if(!X||typeof X.type!=="string"||!Q)return null;return{id:jF(X.id),type:X.type,created:typeof X.created==="number"?X.created:void 0,livemode:typeof X.livemode==="boolean"?X.livemode:void 0,data:{object:Q}}}function jd$($){switch($){case"active":case"trialing":return"active";case"past_due":return"past_due";default:return"canceled"}}function jF($){return typeof $==="string"?$:void 0}function fJ($){return typeof $==="object"&&$!==null?$:void 0}function BT0($){return typeof $==="number"?new Date($*1000):null}function z71($){return jF($)??jF(fJ($)?.id)}function QU6($){return z71($.subscription)??jF(fJ(fJ($.parent)?.subscription_details)?.subscription)}function YU6($){let Z=BT0($.current_period_end);if(Z)return Z;let X=fJ($.items)?.data;if(!Array.isArray(X))return null;let Q=0;for(let Y of X){let G=fJ(Y)?.current_period_end;if(typeof G==="number"&&G>Q)Q=G}return Q>0?new Date(Q*1000):null}function E71($,Z){let X=BT0($.created);return!!X&&!!Z.lastStripeEventAt&&X<Z.lastStripeEventAt}function j71($,Z){let X=BT0($.created);if(!X)return;return Z.lastStripeEventAt&&Z.lastStripeEventAt>X?void 0:X}async function GU6($,Z){let X=Z.data.object;switch(Z.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":{let Q=jF(fJ(X.metadata)?.orgId);if(!Q)return{handled:!1,reason:"no orgId"};if(jF(fJ(X.metadata)?.kind)==="topup"){if(X.mode!=="payment")return{handled:!1,reason:"topup with wrong mode"};if(jF(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let J=jF(X.id);if(!J)return console.error("stripe webhook: topup session without id",{eventId:Z.id,organizationId:Q}),{handled:!1,reason:"topup session without id"};let K=Number(fJ(X.metadata)?.creditCents);if(!Number.isInteger(K)||K<=0)return console.error("stripe webhook: paid topup with bad metadata \u2014 credit NOT applied",{eventId:Z.id,organizationId:Q,creditCents:fJ(X.metadata)?.creditCents}),{handled:!1,reason:"bad topup metadata"};return{handled:!0,organizationId:Q,topUp:{creditCents:K,referenceId:`stripe-topup:${J}`}}}if(X.mode!=="subscription")return{handled:!1,reason:"not a subscription checkout"};if(jF(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let Y=await $.getBilling(Q);if(!Y)return{handled:!1,reason:"unknown org"};let G=z71(X.subscription);if(Y.stripeSubscriptionId&&G&&Y.stripeSubscriptionId!==G)return console.error("stripe webhook: refused checkout rebind",{organizationId:Q,eventId:Z.id}),{handled:!1,reason:"org already bound to another subscription",orphanSubscriptionId:G};if(E71(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Q,{stripeCustomerId:z71(X.customer),stripeSubscriptionId:G,status:"active",lastStripeEventAt:j71(Z,Y)}),{handled:!0,organizationId:Q}}case"customer.subscription.updated":case"customer.subscription.deleted":{let Q=jF(X.id);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};let G=Z.type==="customer.subscription.deleted";if(!G&&E71(Z,Y))return{handled:!1,reason:"stale event"};let J=G?"canceled":jd$(X.status);return await $.updateStripeState(Y.organizationId,{status:J,currentPeriodEnd:YU6(X),...G&&{stripeSubscriptionId:null},lastStripeEventAt:j71(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}case"invoice.paid":{let Q=QU6(X);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};if(E71(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Y.organizationId,{status:"active",currentPeriodEnd:BT0(X.period_end),lastStripeEventAt:j71(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}default:return{handled:!1,reason:`unhandled event ${Z.type}`}}}function JU6($,Z){if(!Z.handled||$.livemode===!1)return null;let X=$.data.object;if(Z.topUp)return{name:"credits_topup_succeeded",organizationId:Z.organizationId,properties:{credit_cents:Z.topUp.creditCents}};switch($.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":return{name:"subscription_started",organizationId:Z.organizationId,properties:{}};case"customer.subscription.deleted":return{name:"subscription_canceled",organizationId:Z.organizationId,properties:{}};case"customer.subscription.updated":return{name:"subscription_updated",organizationId:Z.organizationId,properties:{status:jd$(X.status),...typeof X.cancel_at_period_end==="boolean"?{cancel_at_period_end:X.cancel_at_period_end}:{}}};case"invoice.paid":if(X.billing_reason==="subscription_create")return null;return{name:"subscription_renewed",organizationId:Z.organizationId,properties:{}};default:return null}}function Ld$($,Z){let X=JU6($,Z);if(!X)return;fY({event:X.name,organizationId:X.organizationId,...$.id?{uuid:An1(`stripe:${$.id}:${X.name}`)}:{},...$.created?{timestamp:new Date($.created*1000)}:{},properties:X.properties})}async function zd$($){let Z=new ZW(r8().db),X=await GU6(Z,$);if(!(X.handled&&X.topUp))Ld$($,X);if(X.handled&&X.topUp)await hE$({organizationId:X.organizationId,amountCents:X.topUp.creditCents,referenceId:X.topUp.referenceId}),Ld$($,X);if(!X.handled&&X.orphanSubscriptionId)try{await ce1(X.orphanSubscriptionId),console.error("stripe webhook: canceled orphan subscription",{subscriptionId:X.orphanSubscriptionId,eventId:$.id})}catch(Q){if(!(Q instanceof uY&&(Q.status===400||Q.status===404)))throw Q}return X}var XU6=300;var Pd$=D(()=>{lG();C4();L50();OE();_01()});var KU6=1048576,P71;var Ad$=D(()=>{U8();BF();R$();Pd$();P71=new H1;P71.post("/webhook",p5({maxSize:KU6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=b0().stripeWebhookSecret;if(!Z)return $.json({error:"stripe billing not configured"},503);let X=await $.req.text();if(!wd$(X,$.req.header("stripe-signature"),Z))return $.json({error:"invalid signature"},400);let Y=Ed$(X);if(!Y)return $.json({error:"invalid payload"},400);let G=await zd$(Y);return console.log("stripe webhook",{eventId:Y.id,type:Y.type,livemode:Y.livemode,...G}),$.json({received:!0})})});import{timingSafeEqual as WU6}from"crypto";function HU6($,Z,X){if(!Z?.startsWith("sha256="))return!1;let Q=new Bun.CryptoHasher("sha256",X).update($).digest("hex"),Y=Z.slice(7);if(Y.length!==Q.length)return!1;return WU6(Buffer.from(Y),Buffer.from(Q))}var FU6=5242880,A71;var Td$=D(()=>{U8();BF();u3();A71=new H1;A71.post("/webhook",p5({maxSize:FU6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=process.env.GITHUB_WEBHOOK_SECRET;if(!Z)return $.json({error:"github webhook not configured"},503);let X=await $.req.text();if(!HU6(X,$.req.header("x-hub-signature-256"),Z))return $.json({error:"invalid signature"},400);if($.req.header("x-github-event")!=="push")return $.json({ok:!0,ignored:"event"});let Q;try{Q=JSON.parse(X)}catch{return $.json({error:"invalid payload"},400)}let Y=Q.ref,G=Q.repository?.full_name;if(!Y||!G)return $.json({ok:!0,ignored:"shape"});let K=(await Vn0())?.markTenantPoolsDirty(G,Y)??[];return $.json({ok:!0,pools:K})})});function Rd$($,Z){if(Z.startsWith("text/html")||Z.startsWith("image/svg"))$.set("Content-Security-Policy","sandbox allow-scripts allow-modals allow-same-origin")}var Id$,NU6,UU6,qd$;var Md$=D(()=>{U8();E3();Og();rx();Id$=new H1,NU6=["range","if-none-match","if-modified-since"],UU6=["content-type","content-length","content-range","accept-ranges","etag","last-modified"];Id$.get("/:org/files/*",async($)=>{let Z=$.get("studioContext"),X=Z.organization?.id;if(!Z.auth?.user?.id){if(zu($))return $.redirect(`/login?next=${encodeURIComponent($.req.path)}`,302);throw new $$(401,{message:"Authentication required"})}if(!X)throw new $$(401,{message:"Organization context required"});let Q=$.req.path.replace(/^.*\/files\//,"");if(!Q)throw new $$(400,{message:"Missing file key"});let Y=await Ht(Q,Z);if(!Y)throw new $$(503,{message:"Object storage not configured"});if(Y.startsWith("data:")&&pG()){let W=Y.match(/^data:([^;]+);base64,(.+)$/s);if(!W)throw new $$(500,{message:"Invalid data URL from storage"});let[,F,H]=W,N=Buffer.from(H,"base64"),U=new Headers({"Content-Type":F,"Cache-Control":"private, max-age=86400"});return Rd$(U,F),new Response(N,{status:200,headers:U})}let G=new Headers;for(let W of NU6){let F=$.req.header(W);if(F)G.set(W,F)}let J=await fetch(Y,{headers:G});if(J.status===403||J.status===404)throw new $$(404,{message:"File not found"});if(!J.ok&&J.status!==304&&J.status!==416)throw console.error(`[files] upstream storage error ${J.status} for key:`,Q),new $$(502,{message:"Upstream storage error"});let K=new Headers;for(let W of UU6){let F=J.headers.get(W);if(F)K.set(W,F)}return K.set("Cache-Control","private, max-age=86400"),Rd$(K,K.get("content-type")??""),new Response(J.body,{status:J.status,headers:K})});qd$=Id$});var Ds=_((Hv)=>{var BU6=Hv&&Hv.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),OU6=Hv&&Hv.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))BU6(Z,$,X)};Object.defineProperty(Hv,"__esModule",{value:!0});OU6(jY(),Hv)});var Sd$=_((kd$)=>{Object.defineProperty(kd$,"__esModule",{value:!0});kd$.version=void 0;kd$.version="3.4.0"});var vd$=_((zF)=>{var DU6=zF&&zF.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(zF,"__esModule",{value:!0});zF.NodeTransport=zF.VERSION=void 0;zF.nodeResolveHost=PU6;var s6=Ds(),LU6=j0("net"),T71=j0("tls"),wU6=j0("path"),Cd$=j0("fs"),EU6=DU6(j0("dns")),jU6=Sd$();zF.VERSION=jU6.version;var zU6="nats.js";class _d${socket;version;lang;yields=[];signal=(0,s6.deferred)();closedNotification=(0,s6.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=zU6,this.version=zF.VERSION}async connect($,Z){this.tlsName=$.tlsName,this.options=Z;let{tls:X}=this.options,{handshakeFirst:Q}=X||{};try{if(Q===!0)this.socket=await this.tlsFirst($);else this.socket=await this.dial($);if(this.done)this.socket?.destroy();let Y=await this.peekInfo();(0,s6.checkOptions)(Y,Z);let{tls_required:G,tls_available:J}=Y,K=J===!0&&Z.tls!==null;if(!Q&&(G||K))this.socket=await this.startTLS();if(this.done)this.socket?.destroy();if(G&&this.socket.encrypted!==!0)throw s6.errors.InvalidArgumentError.format("tls","is not available on this server");return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(Y){let G=Y;if(!G)G=new s6.errors.ConnectionError("error connecting - node provided an undefined error");let{code:J}=G,K=J==="ECONNREFUSED"?new s6.errors.ConnectionError("connection refused",{cause:G}):G;throw this.socket?.destroy(),K}}dial($){let Z=(0,s6.deferred)(),X,Q=(0,LU6.createConnection)($.port,$.hostname,()=>{Z.resolve(Q),Q.removeAllListeners()});return Q.on("error",(Y)=>{X=Y}),Q.on("close",()=>{Q.removeAllListeners(),Z.reject(X)}),Q.setNoDelay(!0),Z}get isClosed(){return this.done}close($){return this._closed($,!1)}peekInfo(){let $=(0,s6.deferred)(),Z;return this.socket.on("data",(X)=>{this.yields.push(X);let Q=s6.DataBuffer.concat(...this.yields),Y=(0,s6.extractProtocolMessage)(Q);if(Y!=="")try{let G=s6.INFO.exec(Y);if(!G)throw Error("unexpected response from server");let J=JSON.parse(G[1]);$.resolve(J)}catch(G){$.reject(G)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(X)=>{Z=X}),this.socket.on("close",()=>{this.socket.removeAllListeners(),$.reject(Z)}),$}loadFile($){if(!$)return Promise.resolve();let Z=(0,s6.deferred)();try{if($=(0,wU6.resolve)($),!(0,Cd$.existsSync)($))Z.reject(Error(`${$} doesn't exist`));(0,Cd$.readFile)($,(X,Q)=>{if(X)return Z.reject(X);Z.resolve(Q)})}catch(X){Z.reject(X)}return Z}async loadClientCerts(){let $={},{certFile:Z,cert:X,caFile:Q,ca:Y,keyFile:G,key:J}=this.options.tls;try{if(Z){let K=await this.loadFile(Z);if(K)$.cert=K}else if(X)$.cert=X;if(G){let K=await this.loadFile(G);if(K)$.key=K}else if(J)$.key=J;if(Q){let K=await this.loadFile(Q);if(K)$.ca=[K]}else if(Y)$.ca=Y;return Promise.resolve($)}catch(K){return Promise.reject(K)}}async tlsFirst($){let Z,X={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)X.socket=this.socket;if(typeof this.options.tls==="object")try{let Y=await this.loadClientCerts()||{};X=(0,s6.extend)(X,this.options.tls,Y)}catch(Y){return Promise.reject(new s6.errors.ConnectionError(Y.message,{cause:Y}))}let Q=(0,s6.deferred)();try{let Y=(0,T71.connect)($.port,$.hostname,X,()=>{Y.removeAllListeners(),Q.resolve(Y)});Y.on("error",(G)=>{Z=G}),Y.on("secureConnect",()=>{if(X.rejectUnauthorized===!1)return;if(!Y.authorized)throw Y.authorizationError}),Y.on("close",()=>{Q.reject(Z),Y.removeAllListeners()}),Y.setNoDelay(!0)}catch(Y){Q.reject(new s6.errors.ConnectionError(Y.message,{cause:Y}))}return Q}async startTLS(){let $,Z={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let Q=await this.loadClientCerts()||{};Z=(0,s6.extend)(Z,this.options.tls,Q)}catch(Q){return Promise.reject(new s6.errors.ConnectionError(Q.message,{cause:Q}))}let X=(0,s6.deferred)();try{let Q=(0,T71.connect)(Z,()=>{Q.removeAllListeners(),X.resolve(Q)});Q.on("error",(Y)=>{$=Y}),Q.on("secureConnect",()=>{if(Z.rejectUnauthorized===!1)return;if(!Q.authorized)throw Q.authorizationError}),Q.on("close",()=>{X.reject($),Q.removeAllListeners()})}catch(Q){X.reject(new s6.errors.ConnectionError(Q.message,{cause:Q}))}return X}setupHandlers(){let $;this.socket.on("data",(Z)=>{return this.yields.push(Z),this.signal.resolve()}),this.socket.on("error",(Z)=>{$=Z}),this.socket.on("end",()=>{if(this.socket?.destroyed)return;this.socket?.write(new Uint8Array(0),()=>{this.socket?.end()})}),this.socket.on("close",()=>{this._closed($,!1)})}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.yields.length===0)await this.signal;let $=this.yields;this.yields=[];for(let Z=0;Z<$.length;Z++){if(this.options.debug)console.info(`> ${(0,s6.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,s6.deferred)()}}discard(){if(this.done=!0,this.socket)try{this.socket.removeAllListeners(),this.socket.destroy()}catch{}}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof T71.TLSSocket}_send($){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,s6.render)($)}`);let Z=(0,s6.deferred)();try{this.socket.write($,(X)=>{if(X){if(this.options.debug)console.error(`!!! ${(0,s6.render)($)}: ${X}`);return Z.reject(X)}return Z.resolve()})}catch(X){if(this.options.debug)console.error(`!!! ${(0,s6.render)($)}: ${X}`);Z.reject(X)}return Z}send($){this._send($).catch((X)=>{})}async _closed($,Z=!0){if(!this.connected)return;if(this.done){this.socket?.destroy();return}if(this.closeError=$,!$&&this.socket&&Z)try{await this._send(new TextEncoder().encode(""))}catch(X){if(this.options.debug)console.log("transport close terminated with an error",X)}try{if(this.socket)this.socket.removeAllListeners(),this.socket?.destroy(),this.socket=void 0}catch(X){console.log(X)}this.done=!0,this.closedNotification.resolve(this.closeError)}closed(){return this.closedNotification}}zF.NodeTransport=_d$;function PU6($){let Z=(0,s6.deferred)();return EU6.default.lookup($,{all:!0},(X,Q)=>{if(X){Z.reject(X);return}let Y=[];for(let G of Q)Y.push(G.address);if(Y.length===0)Y.push($);Z.resolve(Y)}),Z}});var gd$=_((yd$)=>{Object.defineProperty(yd$,"__esModule",{value:!0});yd$.connect=AU6;var fd$=vd$(),bd$=Ds(),xd$=Ds();function AU6($={}){if((0,xd$.hasWsProtocol)($))return Promise.reject(xd$.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,bd$.setTransportFactory)({factory:()=>{return new fd$.NodeTransport},dnsResolveFn:fd$.nodeResolveHost}),bd$.NatsConnectionImpl.connect($)}});var hd$=_((lN)=>{var RU6=lN&&lN.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),IU6=lN&&lN.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))RU6(Z,$,X)};Object.defineProperty(lN,"__esModule",{value:!0});lN.connect=void 0;var qU6=gd$();Object.defineProperty(lN,"connect",{enumerable:!0,get:function(){return qU6.connect}});IU6(Ds(),lN)});function dd$($){let Z=$?.connectFn??SU6,X=null,Q=null,Y=!1,G=!1,J=!1,K=[];function W(){return X!==null&&!X.isClosed()&&!X.isDraining()&&!J}function F(){console.log(`[NatsProvider] fireReady: ${K.length} callbacks`);for(let U of K)try{U()}catch{}}function H(U){(async()=>{for await(let B of U.status())if(B.type==="disconnect")console.log("[NatsProvider] Disconnected"),J=!0;else if(B.type==="reconnect")console.log("[NatsProvider] Reconnected, re-firing ready callbacks"),J=!1,Q=null,F()})().catch(()=>{})}async function N(U,B){let O=0;while(!G)try{X=await Z({servers:U,timeout:VU6,reconnect:!0,maxReconnectAttempts:-1,...B?{authenticator:B}:{}}),console.log(`[NatsProvider] Connected to ${X.getServer()} after ${O} attempt(s)`),Q=null,J=!1,H(X),F();return}catch{O++;let L=aZ(kU6,MU6,O-1,2,0.5);await L$(L)}}return{init(U,B){if(Y)return;Y=!0,G=!1;let O=B?.creds?ud$.credsAuthenticator(new TextEncoder().encode(B.creds)):void 0;N(U,O).catch(()=>{})},isConnected(){return W()},getConnection(){return W()?X:null},getJetStream(){if(!W())return null;if(!Q)Q=ld$.jetstream(X);return Q},onReady(U){if(K.push(U),W())try{U()}catch{}},async drain(){if(G=!0,Y=!1,Q=null,J=!1,X){let U=X;X=null,await U.drain().catch(()=>{})}}}}function SU6($){return cd$.connect($)}var ud$,cd$,ld$,MU6=100,kU6=3000,VU6=3000;var md$=D(()=>{K4();ud$=V(Ec(),1),cd$=V(hd$(),1),ld$=V(WL(),1)});function R71($,Z){return`${$}.${Z}`}class I71{cache;constructor($){this.cache=Zu({ttlMs:$?.ttlMs??CU6,maxSize:$?.maxSize??_U6})}async get($,Z){return this.cache.get(R71($,Z))??null}async set($,Z,X){this.cache.set(R71($,Z),X)}async invalidate($,Z){this.cache.delete(R71($,Z))}teardown(){this.cache.clear()}}var CU6=600000,_U6=5000;var id$=()=>{};function OT0($,Z){return`${$}:${Z}`}function q71($){let Z=Zu({ttlMs:$?.ttlMs??vU6,maxSize:$?.maxSize??fU6}),X=$?.getConnection,Q=crypto.randomUUID(),Y=new TextEncoder,G=new TextDecoder,J=null;function K(W,F){let H=X?.();if(!H)return;try{H.publish(pd$,Y.encode(JSON.stringify({organizationId:W,keyId:F,originId:Q})))}catch(N){console.warn("[ProviderKeyCache] Publish failed (non-critical):",N)}}return{get(W,F){return Z.get(OT0(W,F))},set(W,F,H){Z.set(OT0(W,F),H)},invalidate(W,F){Z.delete(OT0(W,F)),K(W,F)},start(){if(J)return;let W=X?.();if(!W)return;J=W.subscribe(pd$),(async()=>{for await(let F of J)try{let H=JSON.parse(G.decode(F.data));if(H.originId===Q)continue;Z.delete(OT0(H.organizationId,H.keyId))}catch{}})().catch(console.error)},teardown(){J?.unsubscribe(),J=null,Z.clear()}}}var pd$="studio.ai-provider-keys.invalidate",vU6=30000,fU6=5000;var nd$=()=>{};class M71{options;subscription=null;onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();constructor($){this.options=$}async start($){if($)this.onCancel=$;if(this.subscription)return;if(!this.onCancel)return;let Z=this.options.getConnection();if(!Z)return;let X=new TextDecoder,Q=Z.subscribe("studio.decopilot.cancel");this.subscription=Q,(async()=>{for await(let Y of Q)try{let G=JSON.parse(X.decode(Y.data));if(G.originId===this.originId)continue;this.onCancel?.(G.taskId)}catch{}})().catch(console.error)}broadcast($){if(/[.*>\s]/.test($)){console.warn("[NatsCancelBroadcast] Invalid threadId, skipping broadcast");return}this.onCancel?.($);try{let Z=this.options.getConnection();if(!Z)return;let X=this.encoder.encode(JSON.stringify({taskId:$,originId:this.originId}));Z.publish("studio.decopilot.cancel",X)}catch(Z){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",Z)}}async stop(){this.subscription?.unsubscribe(),this.subscription=null,this.onCancel=null}}var td$=($)=>{let Z;return()=>Z??=$()},k71,V71;var od$=D(()=>{I6();k71=td$(()=>w$.createHistogram("decopilot.stream.encode_ms",{description:"Per-chunk JSON.stringify+encode time for decopilot stream",unit:"ms"})),V71=td$(()=>w$.createCounter("decopilot.stream.published_chunks",{description:"Logical decopilot stream chunks published to JetStream",unit:"{chunks}"}))});function cU6($=DT0){return{name:FN,subjects:[`${rr0}.>`],storage:DK.StorageType.File,max_age:yU6,max_bytes:hU6,max_msgs_per_subject:uU6,discard:DK.DiscardPolicy.Old,retention:DK.RetentionPolicy.Limits,duplicate_window:gU6,num_replicas:$}}class sd${chunks=0;encodeMs=0;maxMs=0;bytes=0;windowStart=performance.now();constructor(){setInterval(()=>this.flush(),1e4).unref?.()}record($,Z){if(this.chunks++,this.encodeMs+=$,$>this.maxMs)this.maxMs=$;this.bytes+=Z}flush(){let $=performance.now(),Z=$-this.windowStart;if(this.chunks>0&&Z>0)console.warn(JSON.stringify({msg:"stream-encode-trace",windowMs:Math.round(Z),chunks:this.chunks,encodeMs:Math.round(this.encodeMs),pctOfLoop:+(this.encodeMs/Z*100).toFixed(1),maxChunkMs:+this.maxMs.toFixed(2),mbEncoded:+(this.bytes/1048576).toFixed(2)}));this.chunks=0,this.encodeMs=0,this.maxMs=0,this.bytes=0,this.windowStart=$}}function rd$($){let Z=ad$.headers();for(let[X,Q]of Object.entries($))Z.set(X,Q);return Z}function iU6($,Z){let X=0;return{publish(Q,Y,G,J){Q.publish(Y,G,J?{headers:J}:void 0).catch((K)=>{if(X++,xU6().add(1,{"org.id":Z??"unknown"}),X===1||X%100===0)console.warn(`[Decopilot] JetStream publish failed for thread ${$} (${X} total):`,K)})},get errorCount(){return X}}}function pU6($){if(!($ instanceof Error))return!1;if(/non-clustered/i.test($.message))return!0;return/replicas?\b/i.test($.message)&&/not supported|can ?not|exceed|insufficient|greater than/i.test($.message)}class S71{options;js=null;jsm=null;constructor($){this.options=$}async init(){let $=this.options.getConnection();if(!$){console.log("[Decopilot] StreamBuffer.init skipped: NATS not connected yet");return}let Z=async(Q,Y)=>{let G=cU6(Y);try{await Q.streams.info(FN),await Q.streams.update(FN,G)}catch(J){if(J instanceof Error&&J.message.includes("stream not found"))await Q.streams.add(G);else if(J instanceof Error&&/can ?not change.*storage|storage type/i.test(J.message))await Q.streams.delete(FN),await Q.streams.add(G);else throw J}},X=await y6(async()=>{let Q=this.options.getJetStreamManager?await this.options.getJetStreamManager():await DK.jetstreamManager($);try{await Z(Q,DT0)}catch(Y){if(DT0<=1||!pU6(Y))throw Y;console.warn(`[Decopilot] StreamBuffer: NATS rejected num_replicas=${DT0} (${Y.message}); falling back to an unreplicated stream`),await Z(Q,1)}return Q},{maxAttempts:5,minTimeout:250,maxTimeout:4000,jitter:0.5,isRetriable:Ig});this.js=this.options.getJetStream(),this.jsm=X,console.log(`[Decopilot] StreamBuffer.init ${this.js?"ready":"degraded (js=null)"}`)}pump($,Z,X,Q){let Y=this.js;if(!Y)return console.warn(`[Decopilot] pump: JetStream client unavailable for thread ${Z}; chunks NOT published to NATS`),Promise.resolve();let G=iU6(Z,Q),J=!1,K=()=>{if(J)return;J=!0;let F=SB$(Z);Y.publish(F.subject,F.data).catch(()=>{})};X.addEventListener("abort",K,{once:!0});let W=(F)=>{let H=performance.now(),N=sr0(F,{runId:Z}),U=performance.now()-H;k71().record(U),V71().add(1,{"org.id":Q??"unknown"}),mU6?.record(U,N.reduce((B,O)=>B+O.data.length,0));for(let B of N)G.publish(Y,B.subject,B.data,B.headers?rd$(B.headers):void 0)};return(async()=>{let F=$.getReader(),H=0,N=0,U;try{while(!0){let{done:B,value:O}=await F.read();if(B)break;if(W(O),N++,++H>=64)H=0,await new Promise((L)=>setImmediate(L))}}catch(B){U=B,console.warn(`[Decopilot] stream pump error for thread ${Z}:`,B?.message??B)}finally{if(F.releaseLock(),K(),dU6)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"pump-done",taskId:Z,publishedChunks:N,publishErrors:G.errorCount}))}if(U!==void 0)throw U})()}async publishSerialized($,Z){try{return await y6(()=>$.publish(Z.subject,Z.data,{...Z.headers?{headers:rd$(Z.headers)}:{},...Z.msgId?{msgID:Z.msgId}:{}}),{maxAttempts:6,minTimeout:250,maxTimeout:5000,jitter:0.5,isRetriable:Ig}),!0}catch(X){return console.error(`[Decopilot] publish failed after retries subject=${Z.subject}`,X),!1}}async publishRawChunk($,Z,X){let Q=this.js;if(!Q)return!1;let Y=performance.now(),G=sr0(Z,{runId:$,dedup:X});k71().record(performance.now()-Y),V71().add(1);for(let J of G)if(!await this.publishSerialized(Q,J))return!1;return!0}async publishDone($,Z,X){let Q=this.js;if(!Q)return!1;let Y=VB$({runId:$,fenceToken:Z,finalSeq:X});return await this.publishSerialized(Q,Y)}async createTailStream($,Z,X){let Q=this.js;if(!Q)return console.warn(`[Decopilot] createTailStream: JetStream client unavailable for thread ${$}; no live tail`),null;let Y=X?.deliverPolicy==="new"?DK.DeliverPolicy.New:DK.DeliverPolicy.All,G=X?.closeOnDone??!1,J=sO($),K;try{K=await y6(async()=>{return(await Q.consumers.get(FN,{filter_subjects:J,deliver_policy:Y})).consume()},{maxAttempts:6,minTimeout:250,maxTimeout:5000,jitter:0.5,isRetriable:Ig})}catch(L){return console.warn("[Decopilot] JetStream tail unavailable (non-critical):",L?.message??L),null}let H=tL0({messages:async function*(){try{for await(let L of K)yield{subject:L.subject,data:L.data,headers:L.headers}}finally{K.stop()}}(),onCancel:()=>K.stop()}).pipeThrough(mL0()).pipeThrough(iL0()).getReader(),N=!1,U=()=>{if(N)return;N=!0;try{H.releaseLock()}catch{}},B=!1,O=()=>{if(B)return;B=!0,K.stop(),H.cancel().catch(()=>{}),U()};return Z?.addEventListener("abort",O,{once:!0}),new ReadableStream({async pull(L){for(;;){let{done:w,value:E}=await H.read();if(w){O(),L.close();return}let j=E;if(j.kind==="done"){if(G){O(),L.close();return}continue}L.enqueue(j.chunk);return}},cancel(){O()}})}purge($){if(!this.jsm)return;this.jsm.streams.purge(FN,{filter:sO($)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null}}var DK,ad$,bU6=($)=>{let Z;return()=>Z??=$()},xU6,yU6=86400000000000,gU6=120000000000,hU6=4294967296,DT0,uU6=500000,lU6,dU6,mU6;var ed$=D(()=>{K4();er0();oL0();pL0();I6();od$();DK=V(WL(),1),ad$=V(Ec(),1),xU6=bU6(()=>w$.createCounter("decopilot.stream.publish_errors",{description:"Number of JetStream publish failures for decopilot stream chunks",unit:"{errors}"})),DT0=Math.max(1,Number(process.env.DECOPILOT_STREAM_REPLICAS??3)||3);lU6=process.env.STREAM_ENCODE_TRACE==="1",dU6=process.env.DECOPILOT_STREAM_TRACE==="1";mU6=lU6?new sd$:null});function LT0($,Z,X,Q){if(!Q)return!1;return $.emit(Z,gK(X,Q.status,{title:Q.title??void 0,virtualMcpId:Q.virtual_mcp_id??void 0,createdBy:Q.created_by??void 0,triggerId:Q.trigger_id??null,branch:Q.branch??null,harnessId:Q.harness_id??void 0,createdAt:Q.created_at,updatedAt:Q.updated_at})),!0}var $m$=D(()=>{_8()});class C71{storage;options;timer=null;constructor($,Z={}){this.storage=$;this.options=Z}start(){if(this.timer)return;let $=this.options.intervalMs??300000;this.timer=setInterval(()=>{this.runOnce()},$)}async runOnce(){let $=this.options.staleAfterMs??3600000;try{let Z=await this.storage.sweepAbandoned($);if(Z>0)console.log(`[async-research-sweeper] marked ${Z} stale jobs as abandoned`);return Z}catch(Z){return console.error("[async-research-sweeper] sweep failed",Z),0}}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}async function Zm$($,Z,X){let Q=Z.organizationId;if(Z.status!=="in_review")return!1;if(!MC(X))return!1;if(await $.storage.taskBoard.hasHumanRejectedDone(Z.id,Q))return!1;let Y=await $.storage.organizationSettings.get(Q),G=OW(Y?.flags),J=await $.storage.taskBoard.update(Z.id,Q,{status:G},Z.updatedBy);return await z6($,{taskBoardItemId:Z.id,action:"status_changed",actorId:null,data:{from:Z.status,to:G,reason:"pr_merged"}}),u$(Q,J),console.log(`[task-board-review-sweeper] ${Z.id}: linked PR already merged \u2014 moved to ${G}`),!0}var Xm$=D(()=>{m6();KX();Ng();E5()});function eU6($){return $ instanceof nX}function $B6($,Z){return Z-$>=aU6}class _71{taskBoard;contextFactory;billing;options;timer=null;running=!1;cursor=null;constructor($,Z,X,Q={}){this.taskBoard=$;this.contextFactory=Z;this.billing=X;this.options=Q}start(){if(this.timer)return;let $=this.options.intervalMs??nU6;this.timer=setInterval(()=>{this.runOnce()},$),this.timer.unref()}async runOnce(){if(this.running)return 0;this.running=!0;let $=0;try{let Z=this.options.batchSize??oU6,X=this.options.itemIntervalMs??tU6,Q=new Date(Date.now()-X),Y=await this.taskBoard.listItemsPendingReview(Z,this.cursor,Q),G=Y.at(-1);this.cursor=Y.length===Z&&G?{updatedAt:G.updatedAt,id:G.id}:null;for(let{id:J,organizationId:K}of Y)try{if(await this.reconcileItem(J,K,Q))$++}catch(W){console.error(`[task-board-review-sweeper] ${J} failed`,W)}await this.reapNeverStartedThreads(Z),$+=await this.dispatchDueRetries(Z),await this.reactToUnhandledFailures(Z)}catch(Z){console.error("[task-board-review-sweeper] sweep failed",Z)}finally{this.running=!1}return $}async reapNeverStartedThreads($){try{let Z=await this.taskBoard.failNeverStartedLinkedThreads($,new Date(Date.now()-wt0),Lo0);for(let X of Z)console.warn(`[task-board-review-sweeper] failed never-started thread ${X.threadId} on ${X.itemId}`)}catch(Z){console.error("[task-board-review-sweeper] reaping failed",Z)}}async reactToUnhandledFailures($){let Z=await this.taskBoard.listItemsStuckAfterFailure($,new Date(Date.now()-sU6));for(let{id:X,organizationId:Q,threadId:Y}of Z)try{console.warn(`[task-board-review-sweeper] reacting to an unhandled failure on ${X}`),await Oo0(this.taskBoard,Y,Q),await Do0(this.taskBoard,this.billing,Y,Q)}catch(G){console.error(`[task-board-review-sweeper] unhandled-failure reaction for ${X} failed`,G)}}async dispatchDueRetries($){let Z=0,X=await this.taskBoard.listItemsDueForRetry($,new Date);for(let{id:Q,organizationId:Y,attempts:G}of X)try{if(!await this.taskBoard.claimDueRetry(Q,Y,new Date))continue;let J=await this.taskBoard.getById(Q,Y);if(!J||J.status!=="in_progress"||J.assigneeId!==Y8)continue;let K=await this.contextFactory(Y,J.assignedBy??J.createdBy);if(!K)continue;await QN(K,J,{runClass:"retry"}),Z++,console.warn(`[task-board-review-sweeper] re-dispatched ${Q} after a failure (attempt ${G})`)}catch(J){if(console.error(`[task-board-review-sweeper] retry dispatch for ${Q} failed`,J),eU6(J)){await this.returnToTodo(Q,Y,J instanceof Error?J.message:String(J));continue}await this.taskBoard.scheduleRunRetry(Q,Y,G,new Date(Date.now()+rU6)).catch((K)=>console.error(`[task-board-review-sweeper] re-arming ${Q} failed`,K))}return Z}async returnToTodo($,Z,X){try{let Q=await this.taskBoard.getById($,Z);if(!Q||Q.status!=="in_progress")return;let Y=await this.taskBoard.returnToTodoAfterFailure($,Z,Q.updatedBy);if(!Y)return;await this.taskBoard.recordActivity({taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:"in_progress",to:"todo",reason:X}}).catch(()=>{}),u$(Z,Y)}catch(Q){console.error(`[task-board-review-sweeper] returning ${$} to todo failed`,Q)}}async handOffReviewWithoutPr($,Z){let X=await this.taskBoard.listActivity(Z.id,Z.organizationId);if(!$B6(CH(X),Date.now()))return;await bW($,Z,"no pull request is linked to this task \u2014 there is nothing for a "+"reviewer to review")}async reconcileItem($,Z,X){if(!await this.taskBoard.claimSweep($,Z,X))return!1;let Q=await this.taskBoard.getById($,Z);if(!Q)return!1;if(Q.status!=="in_review")return!1;let Y=Q.assigneeId===Y8,G=await this.taskBoard.listPrs($,Z),J=await this.contextFactory(Z,Q.assignedBy??Q.createdBy);if(!J)return!1;if(G.length===0){if(Y)await this.handOffReviewWithoutPr(J,Q);return!1}let K=await Promise.all(G.map(async(W)=>({...W,...await Bg(Z,W)})));if(K.every((W)=>W.state===null))console.warn(`[task-board-review-sweeper] ${$}: no live PR state from GitHub (${K.length} PR(s)) \u2014 proceeding on unknown`);if(await Zm$(J,Q,K))return!0;if(await LO$(J,Q))return!0;if(!Y)return!1;if(!bo0(K))return!1;return await JL0(J,Q,{previewMatchesHead:xo0(K)}),!0}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}var nU6=60000,tU6=300000,oU6=50,rU6=60000,aU6=900000,sU6=120000;var Qm$=D(()=>{m6();qo0();ZN();Ct();Xm$();E5();rG();wo0();eY();Jt()});import{readdir as ZB6,rm as wT0}from"fs/promises";import{join as ET0}from"path";async function jT0($){let Z=new Date;Z.setUTCDate(Z.getUTCDate()-XB6),Z.setUTCHours(0,0,0,0);let X=0;try{let Q=await Nv($);for(let Y of Q)if(/^\d{4}$/.test(Y))X+=await Ym$($,Y,Z);else if(!Y.startsWith(".")){let G=ET0($,Y),J=await Nv(G);for(let W of J){if(!/^\d{4}$/.test(W))continue;X+=await Ym$(G,W,Z)}if((await Nv(G)).length===0)await wT0(G,{recursive:!0,force:!0})}}catch(Q){console.warn("monitoring retention cleanup failed:",Q)}return X}async function Ym$($,Z,X){let Q=0,Y=ET0($,Z),G=await Nv(Y);for(let K of G){if(!/^\d{2}$/.test(K))continue;let W=ET0(Y,K),F=await Nv(W);for(let N of F){if(!/^\d{2}$/.test(N))continue;let U=new Date(`${Z}-${K}-${N}T00:00:00Z`);if(isNaN(U.getTime()))continue;if(U<X){let B=ET0(W,N);await wT0(B,{recursive:!0,force:!0}),Q++}}if((await Nv(W)).length===0)await wT0(W,{recursive:!0,force:!0})}if((await Nv(Y)).length===0)await wT0(Y,{recursive:!0,force:!0});return Q}async function Nv($){try{return(await ZB6($)).filter((X)=>!X.startsWith("."))}catch{return[]}}var XB6=30;var v71=()=>{};import{DBOS as f71,SchedulerMode as QB6}from"@dbos-inc/dbos-sdk";async function GB6(){let $=[xJ(),Uv(),RF()],Z=0;for(let X of $)try{Z+=await jT0(X)}catch(Q){console.error("[monitoring-retention] cleanup failed:",Q)}return console.log(`[monitoring-retention] deleted ${Z} day-dir(s) across ${$.length} signal dir(s)`),{deleted:Z,dirs:$.length}}async function JB6($,Z){await f71.runStep(()=>GB6(),{name:"monitoringRetention"})}function Jm$(){if(Gm$)return;Gm$=!0;let $=f71.registerWorkflow(JB6,{name:"monitoringRetentionWorkflow"});f71.registerScheduled($,{name:"monitoringRetentionWorkflow",crontab:YB6,mode:QB6.ExactlyOncePerIntervalWhenActive})}var YB6="23 4 * * *",Gm$=!1;var Km$=D(()=>{DY();v71()});function Wm$($){return async(Z,X)=>{let Q=await $.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",X).where("member.organizationId","=",Z).executeTakeFirst();if(!Q)return console.warn(`[automationContextFactory] User ${X} not found in org ${Z} \u2014 returning null`),null;let Y=await FJ.create();Y.auth.user={id:X,role:Q.role},Y.organization={id:Q.orgId,slug:Q.orgSlug,name:Q.orgName};let G=await Ot($.db,Z,Q.role);return Y.boundAuth=f51({auth:Y.authInstance,headers:new Headers,role:Q.role,permissions:G,userId:X}),Y.access=new lw(X,void 0,Y.boundAuth,Q.role,"self"),lO(Y,{id:Q.orgId,slug:Q.orgSlug}),Y}}var Fm$=D(()=>{dw();dO()});function KB6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function WB6(){return{services:KB6(),migrationsStatus:"pending",serverUrl:null,logs:[]}}function HB6(){for(let $ of FB6)$()}function Hm$($){let Z=[...b71.logs,$];b71={...b71,logs:Z.length>500?Z.slice(-500):Z},HB6()}function x71(){return NB6}var b71,FB6,NB6=!1;var y71=D(()=>{b71=WB6(),FB6=new Set});import{EventEmitter as UB6}from"events";var g71;var Nm$=D(()=>{y71();g71=new UB6;g71.on("request",($)=>{Hm$($)})});function Um$(){return async($,Z)=>{let X=Date.now(),Q=$.req.method,Y=$.req.path;if(Y==="/api/auth/get-session"||Y.includes("favicon")){await Z();return}let G="",J=!1;if(Y.startsWith("/mcp")&&Q==="POST"){J=!0;try{if($.req.header("Content-Type")?.includes("application/json")){let U=await $.req.raw.clone().json();if(U.method==="tools/call"&&U.params?.name){let B=tu(U.params.name),O=U.params.arguments||{},L=Object.keys(O).map((E)=>tu(E)),w=L.length>0?L.slice(0,3).join(",")+(L.length>3?"\u2026":""):"";G=`${J5.tool}${B}${J5.dim}(${w})${J5.reset}`}else if(U.method)G=`${J5.dim}${tu(U.method)}${J5.reset}`}}catch{}}let K=tu(Y);if(Y.startsWith("/mcp/conn_")){let H=Y.split("/")[2]??"";K=`/mcp/${J5.mcp}${tu(H.slice(0,12))}\u2026${J5.reset}`}else if(Y==="/mcp")K=`${J5.mcp}/mcp${J5.reset}`;else if(Y==="/mcp/registry")K=`${J5.mcp}/mcp/registry${J5.reset}`;let W=OB6(Q),F=J?"\u25C0":"\u2190";if(!x71())console.log(`${J5.dim}${F}${J5.reset} ${W}${Q}${J5.reset} ${K}${G?` ${G}`:""}`);try{await Z()}finally{let H=Date.now()-X,N=$.res.status,U=BB6(N),B=H<1000?`${H}ms`:`${(H/1000).toFixed(1)}s`,O=J?"\u25B6":"\u2192";if(!x71())console.log(`${J5.dim}${O}${J5.reset} ${W}${Q}${J5.reset} ${K}${G?` ${G}`:""} ${U}${N}${J5.reset} ${J5.duration}${B}${J5.reset}`);g71.emit("request",{method:Q,path:tu(Y),status:N,duration:H,timestamp:new Date})}}}var J5,BB6=($)=>{if($>=500)return J5.serverError;if($>=400)return J5.clientError;if($>=300)return J5.redirect;return J5.ok},OB6=($)=>{return J5[$]||J5.reset},tu=($)=>{return $.replace(/\r/g,"").replace(/\n/g,"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"")};var Bm$=D(()=>{y71();Nm$();J5={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",GET:"\x1B[36m",POST:"\x1B[33m",PUT:"\x1B[35m",DELETE:"\x1B[31m",ok:"\x1B[32m",redirect:"\x1B[36m",clientError:"\x1B[33m",serverError:"\x1B[31m",mcp:"\x1B[35m",tool:"\x1B[96m",duration:"\x1B[90m"}});import{createHmac as wm$}from"crypto";import{mkdir as DB6,readdir as LB6,rm as Om$,stat as Em$}from"fs/promises";import{join as u71,relative as wB6}from"path";import{z as P$}from"zod";function zm$($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return u71(EB6,Z)}function Pm$($){return $.replace(/^\/+/,"").replace(/\.\./g,"")}function h71($,Z){let X=zm$($),Q=Pm$(Z);return u71(X,Q)}function jB6($,Z,X,Q){let Y=b0().encryptionKey||"dev-secret",G=`${$}:${Z}:${X}:${Q}`;return wm$("sha256",Y).update(G).digest("hex")}function Lm$($,Z,X,Q,Y){let G=Math.floor(Date.now()/1000)+Q,J=jB6(Z,X,G,Y),K=new URL(`/api/dev-assets/${Z}/${Pm$(X)}`,$);return K.searchParams.set("expires",G.toString()),K.searchParams.set("signature",J),K.searchParams.set("method",Y),K.toString()}function Am$($,Z,X){let Q=`${$}:${Z.getTime()}:${X}`;return`"${wm$("md5","etag").update(Q).digest("hex")}"`}async function Tm$($,Z,X,Q,Y){try{let G=await LB6($,{withFileTypes:!0});for(let J of G){let K=u71($,J.name),F=wB6(Z,K).replace(/\\/g,"/");if(X&&!F.startsWith(X))continue;if(J.isDirectory())if(Q){let H=F+"/";if(!X||H.startsWith(X)){if(!(X?F.slice(X.length):F).includes("/"))Y.commonPrefixes.add(H)}}else await Tm$(K,Z,X,Q,Y);else if(J.isFile()){if(Q&&X){let H=F.slice(X.length);if(H.includes(Q)){let N=H.indexOf(Q),U=X+H.slice(0,N+1);Y.commonPrefixes.add(U);continue}}try{let H=await Em$(K);Y.objects.push({key:F,size:H.size,lastModified:H.mtime.toISOString(),etag:Am$(K,H.mtime,H.size)})}catch{}}}}catch{}}function Rm$($,Z){let Q=t($).id;return[{name:"LIST_OBJECTS",description:"List objects in the local assets directory with pagination support",inputSchema:P$.object({prefix:P$.string().optional(),maxKeys:P$.number().optional().default(1000),continuationToken:P$.string().optional(),delimiter:P$.string().optional()}),outputSchema:P$.object({objects:P$.array(P$.object({key:P$.string(),size:P$.number(),lastModified:P$.string(),etag:P$.string()})),nextContinuationToken:P$.string().optional(),isTruncated:P$.boolean(),commonPrefixes:P$.array(P$.string()).optional()}),handler:async(Y)=>{let G=Y,J=G.prefix||"",K=G.maxKeys??1000,W=G.delimiter,F=G.continuationToken,H=zm$(Q);await DB6(H,{recursive:!0});let N={objects:[],commonPrefixes:new Set};await Tm$(H,H,J,W,N),N.objects.sort((w,E)=>w.key.localeCompare(E.key));let U=0;if(F){if(U=N.objects.findIndex((w)=>w.key>F),U===-1)U=N.objects.length}let B=N.objects.slice(U,U+K),O=U+K<N.objects.length,L=O?B[B.length-1]?.key:void 0;return{objects:B,isTruncated:O,nextContinuationToken:L,commonPrefixes:Array.from(N.commonPrefixes).sort()}}},{name:"GET_OBJECT_METADATA",description:"Get metadata for a file in the local assets directory",inputSchema:P$.object({key:P$.string()}),outputSchema:P$.object({contentType:P$.string().optional(),contentLength:P$.number(),lastModified:P$.string(),etag:P$.string(),metadata:P$.record(P$.string(),P$.string()).optional()}),handler:async(Y)=>{let G=Y,J=h71(Q,G.key),K=await Em$(J);return{contentType:z91(G.key),contentLength:K.size,lastModified:K.mtime.toISOString(),etag:Am$(J,K.mtime,K.size)}}},{name:"GET_PRESIGNED_URL",description:"Generate a presigned URL for downloading a file from local storage",inputSchema:P$.object({key:P$.string(),expiresIn:P$.number().optional()}),outputSchema:P$.object({url:P$.string(),expiresIn:P$.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??Dm$;return{url:Lm$(Z,Q,G.key,J,"GET"),expiresIn:J}}},{name:"PUT_PRESIGNED_URL",description:"Generate a presigned URL for uploading a file to local storage",inputSchema:P$.object({key:P$.string(),expiresIn:P$.number().optional(),contentType:P$.string().optional()}),outputSchema:P$.object({url:P$.string(),expiresIn:P$.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??Dm$;return{url:Lm$(Z,Q,G.key,J,"PUT"),expiresIn:J}}},{name:"DELETE_OBJECT",description:"Delete a single file from local storage",inputSchema:P$.object({key:P$.string()}),outputSchema:P$.object({success:P$.boolean(),key:P$.string()}),handler:async(Y)=>{let G=Y,J=h71(Q,G.key);try{return await Om$(J),{success:!0,key:G.key}}catch{return{success:!1,key:G.key}}}},{name:"DELETE_OBJECTS",description:"Delete multiple files from local storage",inputSchema:P$.object({keys:P$.array(P$.string()).max(1000)}),outputSchema:P$.object({deleted:P$.array(P$.string()),errors:P$.array(P$.object({key:P$.string(),message:P$.string()}))}),handler:async(Y)=>{let G=Y,J=[],K=[];return await Promise.all(G.keys.map(async(W)=>{let F=h71(Q,W);try{await Om$(F),J.push(W)}catch(H){K.push({key:W,message:H instanceof Error?H.message:"Unknown error"})}})),{deleted:J,errors:K}}}]}async function c71($,Z,X){let Q=Rm$(Z,X),Y=new iK({name:"dev-assets-mcp",version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:N5});for(let J of Q){let K="shape"in J.inputSchema?J.inputSchema.shape:P$.object({}).shape,W=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:P$.object({}).shape;Y.registerTool(J.name,{description:J.description??"",inputSchema:K,outputSchema:W,annotations:J.annotations,_meta:J._meta},async(F)=>{try{let H=await J.handler(F);return{content:[{type:"text",text:JSON.stringify(H)}],structuredContent:H}}catch(H){return{content:[{type:"text",text:`Error: ${H.message}`}],isError:!0}}})}let G=new YQ({enableJsonResponse:$.headers.get("Accept")?.includes("application/json")??!1});return await Y.connect(G),EJ(Y,G,$,"mcp:dev-assets")}async function Im$($,Z,X,Q){let G=Rm$(X,Q).find((J)=>J.name===$);if(!G)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};try{let J=await G.handler(Z);return{content:[{type:"text",text:JSON.stringify(J)}]}}catch(J){return{content:[{type:"text",text:J instanceof Error?J.message:String(J)}],isError:!0}}}var EB6="./data/assets",Dm$=3600,jm$,qm$;var Mm$=D(()=>{R$();Cg();U8();cd();oC();gX();OA0();jm$=new H1;jm$.all("/",async($)=>{let Z=$.get("studioContext"),X=new URL($.req.url),Q=`${X.protocol}//${X.host}`;return c71($.req.raw,Z,Q)});qm$=jm$});var km$={};J4(km$,{mountDevRoutes:()=>zB6});function zB6($,Z){$.all("/mcp/:connectionId{.*_dev-assets$}",Z,async(Q)=>{let Y=Q.get("studioContext"),G=new URL(Q.req.url),J=`${G.protocol}//${G.host}`;return c71(Q.req.raw,Y,J)}),$.all("/mcp/:connectionId{.*_dev-assets$}/call-tool/:toolName",Z,async(Q)=>{let Y=Q.get("studioContext"),G=new URL(Q.req.url),J=`${G.protocol}//${G.host}`,K=Q.req.param("toolName");if(!K)return Q.json({error:"Missing tool name"},400);let W=await Q.req.json(),F=await Im$(K,W,Y,J);if(F.isError)return Q.json(F.content,500);return Q.json(F.content)}),$.use("/mcp/dev-assets",Z),$.route("/mcp/dev-assets",qm$);let X=new H1;X.use("*",BK({mountPath:"/api/dev-assets"})),X.route("/",BA0({orgFromPath:!1})),$.route("/api/dev-assets",X)}var Vm$=D(()=>{U8();B91();OA0();Mm$()});import{sql as PB6}from"kysely";import{randomUUID as Sm$}from"crypto";import{z as AB6}from"zod";async function RB6($){let Z=new Date().toISOString(),X=Sm$(),Q=C8.SELF($.organizationId),Y="registry.publish_request.created",G={requestId:$.request.id,requestedId:$.request.requested_id,title:$.request.title,status:$.request.status,createdAt:$.request.created_at,requester:{name:$.request.requester_name,email:$.request.requester_email}};await $.db.insertInto("events").values({id:X,organization_id:$.organizationId,type:"registry.publish_request.created",source:Q,specversion:"1.0",subject:$.request.id,time:Z,datacontenttype:"application/json",dataschema:null,data:JSON.stringify(G),cron:null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Z,updated_at:Z}).execute();let J=await $.db.selectFrom("event_subscriptions").select(["id"]).where("organization_id","=",$.organizationId).where("enabled","=",1).where("event_type","=","registry.publish_request.created").where((K)=>K.or([K("publisher","is",null),K("publisher","=",Q)])).execute();if(J.length>0)await $.db.insertInto("event_deliveries").values(J.map((K)=>({id:Sm$(),event_id:X,subscription_id:K.id,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:null,created_at:Z}))).execute();try{await PB6`SELECT
2926
2926
  pg_notify('studio_events', ${X}),