decocms 4.170.5 → 4.170.7
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.
- package/dist/client/assets/{AlertCircle-gzo_-x3z.js → AlertCircle-CulgZ8QJ.js} +1 -1
- package/dist/client/assets/{AreaChart-_9Ynw757.js → AreaChart-CjNWeGy-.js} +1 -1
- package/dist/client/assets/{ArrowUp-C0cW408V.js → ArrowUp-BNlXyeba.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-389Vl4HC.js → ArrowUpRight-LKpl92jJ.js} +1 -1
- package/dist/client/assets/{Check-CLM0la3Y.js → Check-BARPKH4i.js} +1 -1
- package/dist/client/assets/{CheckCircle-DX4-P0Dd.js → CheckCircle-D1nzBDyQ.js} +1 -1
- package/dist/client/assets/{ChevronDown-DINON_pr.js → ChevronDown-DWFAk7Sj.js} +1 -1
- package/dist/client/assets/{ChevronRight-Dx2lA6cX.js → ChevronRight-D2we6V0w.js} +1 -1
- package/dist/client/assets/{ChevronUp-BWzv1z0D.js → ChevronUp-BUAALiuR.js} +1 -1
- package/dist/client/assets/{Copy01-BvA-EFS1.js → Copy01-BfeEcGku.js} +1 -1
- package/dist/client/assets/{CpuChip01-KVTCt761.js → CpuChip01-T6rvb3sG.js} +1 -1
- package/dist/client/assets/{DotsVertical-C888pj8D.js → DotsVertical-B-CRgbLm.js} +1 -1
- package/dist/client/assets/{Eye-MLGGj09V.js → Eye-BCIudvRR.js} +1 -1
- package/dist/client/assets/{FilterLines-6xkm0O-J.js → FilterLines-P6wvStsn.js} +1 -1
- package/dist/client/assets/{HardDrive-DGX57AcC.js → HardDrive-BTCEoaQS.js} +1 -1
- package/dist/client/assets/{Key01-BlGiYfWf.js → Key01-BgjJ_7Tp.js} +1 -1
- package/dist/client/assets/{LayoutLeft-BtiIaoty.js → LayoutLeft-BXm6OADq.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BigORVep.js → LinkExternal01-BSoFyTEM.js} +1 -1
- package/dist/client/assets/{LogOut01-B3pZanni.js → LogOut01-BFFFOC3O.js} +1 -1
- package/dist/client/assets/{Monitor01-D6b9qmPv.js → Monitor01-vTIk29qo.js} +1 -1
- package/dist/client/assets/{Palette-TKHVb5of.js → Palette-Bj8tHSPy.js} +1 -1
- package/dist/client/assets/{Play-XSm9r8Qa.js → Play-C7jD9LUn.js} +1 -1
- package/dist/client/assets/{Plus-Bh8zJmIG.js → Plus-C0UcTMnT.js} +1 -1
- package/dist/client/assets/{SearchLg-DNBvRLkj.js → SearchLg-CmIsAQ3X.js} +1 -1
- package/dist/client/assets/{SearchMd-X0x2LRgh.js → SearchMd-D9uAX6WE.js} +1 -1
- package/dist/client/assets/{Settings02-s1zQ1I9W.js → Settings02-DlOlugQT.js} +1 -1
- package/dist/client/assets/{Shield01-BzzTBuJD.js → Shield01-CL48sD_B.js} +1 -1
- package/dist/client/assets/{Star01-BpVHERC0.js → Star01-3tCE1-gw.js} +1 -1
- package/dist/client/assets/{Stars01-Cas-QlDJ.js → Stars01-9A2GWUug.js} +1 -1
- package/dist/client/assets/{Stars02-Bsad4A3M.js → Stars02-DDwOVsF7.js} +1 -1
- package/dist/client/assets/{Sun-SrsveKFC.js → Sun-JQjP1oZn.js} +1 -1
- package/dist/client/assets/{SwitchHorizontal01-BYnOaIm8.js → SwitchHorizontal01-Dhz2JYYr.js} +1 -1
- package/dist/client/assets/{Tool01-wraivp9C.js → Tool01-CdS8kLw-.js} +1 -1
- package/dist/client/assets/{Tool02-ClnVq9EE.js → Tool02-BBoyH47I.js} +1 -1
- package/dist/client/assets/{Trash01-DrR2pHzg.js → Trash01-CbhzcTt3.js} +1 -1
- package/dist/client/assets/{TrendUp01-CsKuOvpd.js → TrendUp01-CbREjIPK.js} +1 -1
- package/dist/client/assets/{Upload01-DWQqscqn.js → Upload01-BdeHM4jD.js} +1 -1
- package/dist/client/assets/{User01-Bumfk6Z_.js → User01-onkDisHt.js} +1 -1
- package/dist/client/assets/{Users01-DbRnrIwh.js → Users01-LJDrZYeK.js} +1 -1
- package/dist/client/assets/{Users03-Yga5VyFl.js → Users03-DlmIRsEe.js} +1 -1
- package/dist/client/assets/{X-BZ2BPU3G.js → X-Bnb6DHrx.js} +1 -1
- package/dist/client/assets/{XCircle-BP-z0q6k.js → XCircle-BN8DdobH.js} +1 -1
- package/dist/client/assets/{XClose-BTrScbR4.js → XClose-BvANZj6r.js} +1 -1
- package/dist/client/assets/{Zap-BU2q9C3u.js → Zap-BAm5KmZ-.js} +1 -1
- package/dist/client/assets/{ZapSquare-BxHUWUR-.js → ZapSquare-ISMHG_Ar.js} +1 -1
- package/dist/client/assets/{access-gate-YtOYIDMU.js → access-gate-B3wLJ69M.js} +1 -1
- package/dist/client/assets/{add-section-modal-iCGcgaOO.js → add-section-modal-BnhGEfv-.js} +1 -1
- package/dist/client/assets/{agent-icon-DC3dfqFv.js → agent-icon-DtkqR39Z.js} +1 -1
- package/dist/client/assets/{agents-list-DBipF7pH.js → agents-list-PJ_bNLJj.js} +1 -1
- package/dist/client/assets/{ai-providers-DHS_e9Ik.js → ai-providers-C4NY0EwA.js} +1 -1
- package/dist/client/assets/{alert-CEFtGQA2.js → alert-CHK1X07R.js} +1 -1
- package/dist/client/assets/{alert-dialog-D0zoSyyW.js → alert-dialog-CK85XiHH.js} +1 -1
- package/dist/client/assets/{app-editor-BKWLYJvm.js → app-editor-Cj7ZjZIH.js} +1 -1
- package/dist/client/assets/{auth-DDLn_D0F.js → auth-CUkNJsYC.js} +1 -1
- package/dist/client/assets/{auth-catchall-D6ahZ37C.js → auth-catchall-DdjpG5hQ.js} +1 -1
- package/dist/client/assets/{auth-entry-iRGfcip6.js → auth-entry-DjFBaL_w.js} +1 -1
- package/dist/client/assets/{auth-split-layout-BeCVEhr8.js → auth-split-layout-Bz3Ntgbd.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-BOKkdNv7.js → authenticate-and-persist-oauth--qKVSpxv.js} +1 -1
- package/dist/client/assets/{automation-list-row-CVNhE-L8.js → automation-list-row-CX3W9QjV.js} +1 -1
- package/dist/client/assets/{automation-runs-CZbtRwYO.js → automation-runs-B8ZpZPVI.js} +1 -1
- package/dist/client/assets/{automations-DGr7iJd0.js → automations-Bzc-usOW.js} +1 -1
- package/dist/client/assets/{avatar-NGPhpOoY.js → avatar-aQxHuIYg.js} +1 -1
- package/dist/client/assets/{badge-BIeS4b6H.js → badge-CoVICL7-.js} +1 -1
- package/dist/client/assets/{block-document-BMaqYj0F.js → block-document-Ddgx5l89.js} +1 -1
- package/dist/client/assets/{brand-context-BDFu06eT.js → brand-context-DV2evLJc.js} +1 -1
- package/dist/client/assets/{buckets-COWuvzWm.js → buckets-CO8ytaDl.js} +1 -1
- package/dist/client/assets/{bulk-category-panel-Ba7UAe-h.js → bulk-category-panel-Z-ncC8dg.js} +1 -1
- package/dist/client/assets/{calendar-C7h02JcY.js → calendar-CPOzEjNP.js} +1 -1
- package/dist/client/assets/{capability-load-error-B5lcX_7A.js → capability-load-error-DEcgvDg0.js} +1 -1
- package/dist/client/assets/{card-YVZkOG-R.js → card-DkOcnaGU.js} +1 -1
- package/dist/client/assets/{category-editor-BdyuJrfI.js → category-editor-D7hycPUc.js} +1 -1
- package/dist/client/assets/{chat-context-B3szAAI1.js → chat-context-ClBVfA1X.js} +1 -1
- package/dist/client/assets/{checkbox-BchGlhXb.js → checkbox-DQk7Hn7H.js} +1 -1
- package/dist/client/assets/{cli-auth-success-C6666XNO.js → cli-auth-success-DfFnrNz5.js} +1 -1
- package/dist/client/assets/{collection-detail-BhwrG9Yk.js → collection-detail-C9mrOEh9.js} +1 -1
- package/dist/client/assets/{collection-display-button-7LWe3tBa.js → collection-display-button-CsVUXmTq.js} +1 -1
- package/dist/client/assets/{collection-search-B_4teNDf.js → collection-search-BBHvvNML.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-DfrVnHvE.js → collection-table-wrapper-BitF3J_w.js} +1 -1
- package/dist/client/assets/{collection-tabs-C86bYOYO.js → collection-tabs-33-bqtiz.js} +1 -1
- package/dist/client/assets/{command-BDWLAlyk.js → command-mKOrJzrZ.js} +1 -1
- package/dist/client/assets/{commerce-onboarding-vPbADTmX.js → commerce-onboarding-BdFh7WdD.js} +1 -1
- package/dist/client/assets/{companions-core-BW6LR4GA.js → companions-core-B3zttn60.js} +1 -1
- package/dist/client/assets/{connect-C2T-Ejjt.js → connect-DJcsNXGq.js} +1 -1
- package/dist/client/assets/{connection-CQ93KUOx.js → connection-Dvuv7or_.js} +1 -1
- package/dist/client/assets/{connection-card-CTal3YHV.js → connection-card-Cb2sDtSe.js} +1 -1
- package/dist/client/assets/{connection-detail-C82kmyrp.js → connection-detail-DWiKqpES.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-COmopVau.js → connection-form-helpers-BNRb0RFO.js} +1 -1
- package/dist/client/assets/{connections-DUECGsZI.js → connections-CZxmMVwl.js} +1 -1
- package/dist/client/assets/{decopilot-sse-pool-C4w4I6oB.js → decopilot-sse-pool-qN274emC.js} +1 -1
- package/dist/client/assets/{dialog-D8ueI2VW.js → dialog-OnmvFj6U.js} +1 -1
- package/dist/client/assets/{domain-settings-Toz6E9nJ.js → domain-settings-CzTLtd6K.js} +1 -1
- package/dist/client/assets/{drawer-BY0A9pFr.js → drawer-Bbx4sGLc.js} +1 -1
- package/dist/client/assets/{dropdown-menu-Cq-nWA7u.js → dropdown-menu-BLoiIT66.js} +1 -1
- package/dist/client/assets/{empty-state-COXPqBJO.js → empty-state-B7EoOp90.js} +1 -1
- package/dist/client/assets/{extract-connection-data-fs4bU9No.js → extract-connection-data-DPxnrIHs.js} +1 -1
- package/dist/client/assets/{file-explorer-CYcu1zWB.js → file-explorer-DV-Ii_1B.js} +1 -1
- package/dist/client/assets/{form-BoQflR94.js → form-B1FGpjqQ.js} +1 -1
- package/dist/client/assets/{general-_TVeej2O.js → general-CevDlV2t.js} +1 -1
- package/dist/client/assets/{github-repo-picker-D8_6aQEB.js → github-repo-picker-8IfA3bqL.js} +1 -1
- package/dist/client/assets/{hooks-_3sG3z0_.js → hooks-DkiICRiM.js} +4 -4
- package/dist/client/assets/{index-Dko5XGXY.js → index-0NQAslei.js} +1 -1
- package/dist/client/assets/{index-B05rYM4y.js → index-55ijbTTK.js} +1 -1
- package/dist/client/assets/{index-BfBs0BeB.js → index-Btt82SFt.js} +1 -1
- package/dist/client/assets/{index-DtmiDi9E.js → index-C5Cl4k32.js} +1 -1
- package/dist/client/assets/{index-C9mGXq2-.js → index-CYXzKIGv.js} +1 -1
- package/dist/client/assets/{index-Bn-XPar9.js → index-Cb4Y0Iqz.js} +1 -1
- package/dist/client/assets/{index-DqSQ1jQ9.js → index-CzLUG8CI.js} +5 -5
- package/dist/client/assets/{index-5Yg3goAM.js → index-DD19Xgi9.js} +3 -3
- package/dist/client/assets/{index-C8-h75dI.js → index-DYJY_3X1.js} +3 -3
- package/dist/client/assets/{index-D3lhm6Hg.js → index-Dp2RJDLw.js} +1 -1
- package/dist/client/assets/{index-D-gE7NOw.js → index-WRi6IFVD.js} +1 -1
- package/dist/client/assets/{index-redirect-DkYaA-CT.js → index-redirect-DHYukAPh.js} +1 -1
- package/dist/client/assets/{input-DnwPLJY3.js → input-B-xxZOKU.js} +1 -1
- package/dist/client/assets/{integration-icon-DDSjcXFE.js → integration-icon-B63LIXOn.js} +1 -1
- package/dist/client/assets/{invite-member-dialog-C9KEZxRs.js → invite-member-dialog-CzB9sdOr.js} +1 -1
- package/dist/client/assets/{label-Dz4PHAHi.js → label-DVBVPZn_.js} +1 -1
- package/dist/client/assets/{layout-ZGd5PNA9.js → layout-D-p7eb8T.js} +1 -1
- package/dist/client/assets/{login-Bh4DqUD-.js → login-Cb_sr0ld.js} +1 -1
- package/dist/client/assets/{mcp-oauth-CBj3LmGF.js → mcp-oauth-DSZxQ3KG.js} +1 -1
- package/dist/client/assets/{members-D6umlfRw.js → members-CpL2kgGq.js} +1 -1
- package/dist/client/assets/{monaco-editor-DTtHvV5x.js → monaco-editor-DOx5PZhj.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-CBgmx9r1.js → monitoring-stats-row-WdbL1buD.js} +1 -1
- package/dist/client/assets/{multi-select-DV-FYfEX.js → multi-select-CmB0E9HL.js} +1 -1
- package/dist/client/assets/{oauth-callback-Hkp9Dzjx.js → oauth-callback-DC7VgOoE.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-FUSf6D69.js → oauth-callback-ai-provider-DkHQn1xC.js} +1 -1
- package/dist/client/assets/{onboarding-DQIx3MCC.js → onboarding-CP4Xl5BT.js} +1 -1
- package/dist/client/assets/{org-layout-CTAq1JGA.js → org-layout-Bp_cOzYu.js} +1 -1
- package/dist/client/assets/{organization-choice-B7ZUXztb.js → organization-choice-DEYQjW76.js} +1 -1
- package/dist/client/assets/{orgs-D7HO_O3F.js → orgs-Cg-7TNHk.js} +1 -1
- package/dist/client/assets/{page-seo-form-DqSoOibj.js → page-seo-form-D8Jl7JDX.js} +1 -1
- package/dist/client/assets/{popover-JIXPtdZp.js → popover-CN7lQbJb.js} +1 -1
- package/dist/client/assets/{post-editor-C4dnPbaj.js → post-editor-DnAqMACi.js} +1 -1
- package/dist/client/assets/{primitives-CthJN9Xq.js → primitives-DM0CO-PV.js} +1 -1
- package/dist/client/assets/{profile-CT1pWdUL.js → profile-TxFzmEwf.js} +1 -1
- package/dist/client/assets/project-app-view-wfKsnkAj.js +1 -0
- package/dist/client/assets/record-editor-BhH6MPJd.js +1 -0
- package/dist/client/assets/{redirect-editor-Wvl9eZiF.js → redirect-editor-DI1TVrRf.js} +1 -1
- package/dist/client/assets/{registry-layout-B3RTNkb5.js → registry-layout-Dd9v-lxw.js} +1 -1
- package/dist/client/assets/registry-xKh7pW67.js +2 -0
- package/dist/client/assets/{reports-Bj9DLrVQ.js → reports-DT7pxKAL.js} +1 -1
- package/dist/client/assets/{require-capability-Cpo5r31M.js → require-capability-DEPjYfTb.js} +1 -1
- package/dist/client/assets/{required-auth-layout-BV2G4m9x.js → required-auth-layout-CvEEOnW2.js} +1 -1
- package/dist/client/assets/{reset-password-D5IEem6v.js → reset-password-Zr4erJ5H.js} +1 -1
- package/dist/client/assets/{roles-Zn8-U7Eu.js → roles-D4AXY1O0.js} +1 -1
- package/dist/client/assets/{search-input-D4mUq47Q.js → search-input-B7HrisdG.js} +1 -1
- package/dist/client/assets/{secrets-BPgSegt7.js → secrets-BiVb_h2W.js} +1 -1
- package/dist/client/assets/{sections-editor-WFcTggpX.js → sections-editor-B4XrZ9ZW.js} +1 -1
- package/dist/client/assets/{select-CyTk3WKd.js → select-Bo0WA9yd.js} +1 -1
- package/dist/client/assets/{select-model-B1qH14xl.js → select-model-UN_W2kWz.js} +1 -1
- package/dist/client/assets/{self-tool-result-HNl3Y6KJ.js → self-tool-result-ofSJsTC6.js} +1 -1
- package/dist/client/assets/{seo-editor-DRqQ6K9e.js → seo-editor-EBMN1tFp.js} +1 -1
- package/dist/client/assets/{settings-layout-CSIierZP.js → settings-layout-CTCpMgqD.js} +1 -1
- package/dist/client/assets/{settings-section-B1rKFig5.js → settings-section-SjYGvsuZ.js} +1 -1
- package/dist/client/assets/{shell-controls-kKSiE567.js → shell-controls-BAqugCQv.js} +1 -1
- package/dist/client/assets/{shell-layout-BjAMUhq-.js → shell-layout-ygdVGNeq.js} +1 -1
- package/dist/client/assets/{sidebar-hT0AaBlz.js → sidebar-Cw1n8cPE.js} +1 -1
- package/dist/client/assets/{skeleton-diLgCbAK.js → skeleton-C3mqHUgK.js} +1 -1
- package/dist/client/assets/{spinner-BXyPxhUA.js → spinner-JIyCKCZR.js} +1 -1
- package/dist/client/assets/{sso-DHYTXiKF.js → sso-DxGDFKtg.js} +1 -1
- package/dist/client/assets/{store-Byniq0_6.js → store-UE0DxGe6.js} +1 -1
- package/dist/client/assets/store-registry-CsVvMWKp.js +2 -0
- package/dist/client/assets/{studio-tools-B8xlYiem.js → studio-tools-BuHDDhrj.js} +1 -1
- package/dist/client/assets/{switch-B_XoLDaj.js → switch-D0rt9_tw.js} +1 -1
- package/dist/client/assets/{tab-id-wz3HFdBf.js → tab-id-DojsBlVG.js} +1 -1
- package/dist/client/assets/{table-7cFxNKIK.js → table-B9vqd95o.js} +1 -1
- package/dist/client/assets/{tabs-CvNJe1sM.js → tabs-D_KaPDCJ.js} +1 -1
- package/dist/client/assets/{textarea-DHbdkvCP.js → textarea-DyydMtzS.js} +1 -1
- package/dist/client/assets/{toggle-group-B_KDI0SZ.js → toggle-group-_sacxwJk.js} +1 -1
- package/dist/client/assets/{toolbar-QPwChcEt.js → toolbar-Bnk-Y6Bk.js} +1 -1
- package/dist/client/assets/{tooltip-Dn_VvtuJ.js → tooltip-Bg4lifNX.js} +1 -1
- package/dist/client/assets/{use-ai-providers-D4ysWEu3.js → use-ai-providers-BdqwOZhV.js} +1 -1
- package/dist/client/assets/{use-automations-BtGdGq_c.js → use-automations-DPh61wGk.js} +1 -1
- package/dist/client/assets/{use-autosave-BPXDs5fy.js → use-autosave-CNMKkcAa.js} +1 -1
- package/dist/client/assets/{use-capability-DMm-Pp2s.js → use-capability-C6EbtzXu.js} +1 -1
- package/dist/client/assets/{use-clock-tick-C4tOB__G.js → use-clock-tick-DIxeJR8K.js} +1 -1
- package/dist/client/assets/{use-connection-C5PDzO_5.js → use-connection-DEaoKOVa.js} +1 -1
- package/dist/client/assets/{use-copy-nC75B6-1.js → use-copy-BId4eX5b.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-NUDsfFE8.js → use-create-virtual-mcp-D9UPJWo2.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-Clcn-q8L.js → use-debounced-autosave-B3VRqTYF.js} +1 -1
- package/dist/client/assets/{use-debounced-value-C_0Op-tH.js → use-debounced-value-i9ZCSUX-.js} +1 -1
- package/dist/client/assets/{use-deco-credits-CIkz69xa.js → use-deco-credits-B_NEq58J.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-BiUyxA0j.js → use-decopilot-events-CYCBMba3.js} +1 -1
- package/dist/client/assets/{use-delete-connection-CaQzuIfK.js → use-delete-connection-DGEuPXeT.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-C5g6fGp9.js → use-deployment-admin-CUuCBSxD.js} +1 -1
- package/dist/client/assets/{use-file-configs-DSV2PtBu.js → use-file-configs-OhwXVJ_Q.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-B3EB-9vB.js → use-infinite-scroll-BwgDaFz3.js} +1 -1
- package/dist/client/assets/{use-join-requests-lrG-2Mol.js → use-join-requests-BtZRjEAs.js} +1 -1
- package/dist/client/assets/{use-mcp-auth-status-C4tXpT4p.js → use-mcp-auth-status-DIV1qXsR.js} +1 -1
- package/dist/client/assets/{use-mcp-client-DMZgzGJF.js → use-mcp-client-C6u6uWMn.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-v7NQpvSy.js → use-mcp-tools-BKnN90LQ.js} +1 -1
- package/dist/client/assets/{use-members-BDMSaAaw.js → use-members-BhDGuSrv.js} +1 -1
- package/dist/client/assets/{use-mobile-BVbHB6rb.js → use-mobile-CuBbFzjG.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-DTTYu2TB.js → use-navigate-to-agent-CfiKyTiO.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-BIJOv5x_.js → use-org-auth-client-BdUdgOJA.js} +1 -1
- package/dist/client/assets/{use-org-sso-zK8BiEd_.js → use-org-sso-BeUUySr2.js} +1 -1
- package/dist/client/assets/{use-organization-roles-Bab30awN.js → use-organization-roles-DWzU2COa.js} +1 -1
- package/dist/client/assets/{use-organization-settings-DjTTiqe7.js → use-organization-settings-DCilCh9D.js} +1 -1
- package/dist/client/assets/{use-registry-connections-BVBkXnlB.js → use-registry-connections-DY5HXeca.js} +1 -1
- package/dist/client/assets/{use-secrets-BbA-QVhO.js → use-secrets-DyfpPIKJ.js} +1 -1
- package/dist/client/assets/{use-status-sounds-Cb0MpDFe.js → use-status-sounds-CtR-iJrK.js} +1 -1
- package/dist/client/assets/{use-tags-eTLFmYa-.js → use-tags-DB7y1K_X.js} +1 -1
- package/dist/client/assets/{use-view-mode-Bf8hHsxz.js → use-view-mode-D8FPxdi1.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-gX2uZE8t.js → use-virtual-mcp-CtAFuCva.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-CXglgl_n.js +1 -0
- package/dist/client/assets/{useQueries-BxWoj-5a.js → useQueries--YSCqaIN.js} +1 -1
- package/dist/client/assets/{useRouterState-AxGL5xPY.js → useRouterState-DTAdOPb-.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-B6E2NwfD.js +1 -0
- package/dist/client/assets/{users-DBdY3lw0.js → users-DWvE_C1K.js} +1 -1
- package/dist/client/assets/{variant-calendar-ZQ9hhnuZ.js → variant-calendar-CGU8zbxv.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-DWd-x-3A.js → view-mode-toggle-DlDm54jJ.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +6 -6
- package/dist/server/server.js +6 -6
- package/package.json +1 -1
- package/dist/client/assets/project-app-view-DGoBol10.js +0 -1
- package/dist/client/assets/record-editor-BfjdRDyk.js +0 -1
- package/dist/client/assets/registry-BlhVY720.js +0 -2
- package/dist/client/assets/store-registry-VejKmgG4.js +0 -2
- package/dist/client/assets/useInfiniteQuery-HDvZgENX.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CtXCWGEg.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -1256,7 +1256,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var qh1=O(()=>{ex()});f
|
|
|
1256
1256
|
`.execute($);if(Number(W.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${J}/${K}, keeping in old table`);continue}}await qf`
|
|
1257
1257
|
DELETE FROM kysely_migration WHERE name = ${X}
|
|
1258
1258
|
`.execute($)}}async function Md1($){await Ny6($),await Uy6($);let Z=new Rd1({db:$,provider:{getMigrations:()=>Promise.resolve(Mc0)}}),{error:X,results:Q}=await Z.migrateToLatest(),Y=0;if(Q?.forEach((G)=>{if(G.status==="Success")Y++;else if(G.status==="Error")console.error(`Failed to execute migration "${G.migrationName}"`)}),X)throw console.error("Failed to migrate"),console.error(X),X;return Y}async function Fy6($){let{keepOpen:Z=!1,database:X,skipBetterAuth:Q=!1}=$??{},Y="skipped";if(!Q&&!X)Y=await wg0();let G=X??w6(),J=async()=>{if(!Z&&!X)await gF(G).catch((K)=>{console.warn("Warning: Error closing database:",K)})};try{let K=await Md1(G.db);return await J(),{betterAuth:Y,kysely:K}}catch(K){throw await J(),K}}async function wy6(){let $=w6(),Z=new Rd1({db:$.db,provider:{getMigrations:()=>Promise.resolve(Mc0)}}),{error:X,results:Q}=await Z.migrateDown();if(Q?.forEach((Y)=>{if(Y.status==="Success")console.log(`\u2705 Migration "${Y.migrationName}" rolled back successfully`);else if(Y.status==="Error")console.error(`\u274C Failed to rollback migration "${Y.migrationName}"`)}),X)throw console.error("Failed to rollback migration"),console.error(X),X}var Sd1=O(()=>{Id1();Bg0();d7()});async function W50($){let Z={...process.env},X=Y00($,Z);console.log(JN1(X.settings.encryptionKey));let{ensureServices:Q}=await Promise.resolve().then(() => (P$0(),j$0)),{outputs:Y,services:G}=await Q({home:X.settings.dataDir,externalDatabaseUrl:X.externalDatabaseUrl,externalNatsUrl:X.externalNatsUrl});if(!X.skipMigrations){let{migrateBetterAuth:K}=await Promise.resolve().then(() => (Bg0(),Qc1));await K(Y.databaseUrl);let{createDatabase:W}=await Promise.resolve().then(() => (d7(),Pu1)),{migrateToLatest:H}=await Promise.resolve().then(() => (Sd1(),kd1)),N=W(Y.databaseUrl);await H({keepOpen:!0,database:N,skipBetterAuth:!0})}let J={...X.settings,databaseUrl:Y.databaseUrl,natsUrls:Y.natsUrls,...Y.s3?{s3Endpoint:Y.s3.endpoint,s3Bucket:Y.s3.bucket,s3AccessKeyId:Y.s3.accessKeyId,s3SecretAccessKey:Y.s3.secretAccessKey,s3ForcePathStyle:Y.s3.forcePathStyle}:{},...Y.natsTunnel?{natsPublicUrl:Y.natsTunnel.publicUrl,natsAccountJwt:Y.natsTunnel.accountJwt,natsAccountSigningKey:Y.natsTunnel.accountSigningKey,natsOperatorJwt:Y.natsTunnel.operatorJwt,natsTunnelPublicEnabled:!0,natsCredsPath:Y.natsTunnel.credsPath}:{}};return Mh1(J),{settings:J,services:G.map((K)=>({name:K.name==="PostgreSQL"?"Postgres":K.name,port:K.port})),managedServiceNames:G.filter((K)=>K.owner==="managed").map((K)=>K.name)}}var kc0=O(()=>{ex();c8()});var _d1={};z0(_d1,{updateService:()=>OD,subscribeCliState:()=>Cc0,setTuiConsoleIntercepted:()=>H50,setServerUrl:()=>od,setMigrationsDone:()=>td,setDevMode:()=>Ly6,resetCliStateForTests:()=>By6,isTuiConsoleIntercepted:()=>N50,getCliState:()=>Vc0,addLogEntry:()=>dF});function Vd1(){return{services:[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}],migrationsStatus:"pending",serverUrl:null,logs:[]}}function By6(){TQ=Vd1()}function Oy6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function pd(){for(let $ of Sc0)$()}function Vc0(){return TQ}function Cc0($){return Sc0.add($),()=>Sc0.delete($)}function OD($){TQ={...TQ,services:TQ.services.map((Z)=>Z.name===$.name?$:Z)},pd()}function td(){TQ={...TQ,migrationsStatus:"done"},pd()}function od($){TQ={...TQ,serverUrl:$},pd()}function dF($){let Z=[...TQ.logs,$];TQ={...TQ,logs:Z.length>500?Z.slice(-500):Z},pd()}function Ly6(){TQ={...TQ,services:[...Oy6(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},pd()}function H50($){Cd1=$}function N50(){return Cd1}var TQ,Sc0,Cd1=!1;var LD=O(()=>{TQ=Vd1();Sc0=new Set});import{createServer as xd1}from"net";function Dy6($){return new Promise((Z)=>{let X=xd1();X.once("error",()=>Z(!1)),X.listen($,"0.0.0.0",()=>{X.close(()=>Z(!0))})})}async function rd($){if(await Dy6($))return $;let Z=await new Promise((X,Q)=>{let Y=xd1();Y.once("error",Q),Y.listen(0,"0.0.0.0",()=>{let G=Y.address(),J=typeof G==="object"&&G?G.port:0;Y.close(()=>X(J))})});return console.warn(`Port ${$} is in use, using port ${Z} instead.`),Z}var _c0=()=>{};function ad($){return $.replace(/\x1b\[[0-9;]*m/g,"")}var xc0={};z0(xc0,{startDevServer:()=>zy6});import{join as Ey6}from"path";function vd1($){let Z=$.getReader(),X=new TextDecoder,Q="";function Y(){let G=Q.split(`
|
|
1259
|
-
`);Q=G.pop()??"";for(let J of G){let K=ad(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;dF({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{for(;;){let{done:G,value:J}=await Z.read();if(G)break;Q+=X.decode(J,{stream:!0}),Y()}if(Q.trim()){let G=ad(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)dF({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function zy6($){let{baseUrl:Z,noTui:X}=$,Q=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=Q?process.env.PORT:$.vitePort,G=Z||`http://localhost:${Y}`,J=Q?await rd(Number(Y)+1):await rd(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await W50({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)OD({name:L.name,status:"ready",port:L.port});td();let N=Ey6(import.meta.dir,"..","..","..","..",".."),U=X===!0,F=Bun.spawn(["bun","run","dev:servers"],{cwd:N,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:G,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsPublicUrl&&K.natsAccountJwt&&K.natsAccountSigningKey?{NATS_PUBLIC_URL:K.natsPublicUrl,NATS_ACCOUNT_JWT:K.natsAccountJwt,NATS_ACCOUNT_SIGNING_KEY:K.natsAccountSigningKey,NATS_OPERATOR_JWT:K.natsOperatorJwt??"",NATS_TUNNEL_PUBLIC_ENABLED:"true",...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)vd1(F.stdout),vd1(F.stderr);od(G),OD({name:"Vite",status:"ready",port:Number(Y)}),OD({name:"API",status:"ready",port:Number(K.port)});let B=async(L)=>{if(F.kill(L),await F.exited,H.length>0){let{stopServices:D}=await Promise.resolve().then(() => (P$0(),j$0));await D(K.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(Y),process:F}}var vc0=O(()=>{kc0();LD();_c0()});var U50;var fc0=O(()=>{U50={name:"decocms",version:"4.170.5",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",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.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","@nats-io/jwt":"0.0.10-5","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as Py6,Text as fd1}from"ink";import{jsx as Ay6,jsxs as bd1}from"react/jsx-runtime";function yd1({version:$}){return bd1(Py6,{flexDirection:"column",marginTop:1,children:[l$0.map((Z,X)=>Ay6(fd1,{color:d$0[X],children:Z},X)),bd1(fd1,{dimColor:!0,children:[" v",$]})]})}var gd1=O(()=>{bd()});import{Box as DD,Text as mF}from"ink";import{Spinner as Ty6}from"@inkjs/ui";import{jsx as VY,jsxs as Mf}from"react/jsx-runtime";function hd1({status:$}){if($==="pending")return VY(Ty6,{label:""});return VY(mF,{color:"green",children:"\u2713"})}function Iy6($){return`${$.name}: ${$.port||"...."}`}function ud1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return Mf(DD,{flexDirection:"column",paddingBottom:1,children:[VY(yd1,{version:U50.version}),VY(DD,{marginBottom:1,children:VY(mF,{dimColor:!0,children:"\u2500".repeat(80)})}),VY(DD,{children:Mf(mF,{dimColor:!0,children:["Home: ",X]})}),Mf(DD,{gap:2,children:[$.map((Y)=>Mf(DD,{gap:1,children:[VY(mF,{children:Iy6(Y)}),VY(hd1,{status:Y.status})]},Y.name)),Mf(DD,{gap:1,children:[VY(mF,{children:"Migrations"}),VY(hd1,{status:Z})]})]}),VY(DD,{children:Q?Mf(mF,{children:["Open in browser: ",VY(mF,{color:"cyan",children:Q})]}):VY(mF,{dimColor:!0,children:"Starting..."})})]})}var cd1=O(()=>{fc0();gd1()});import{Box as Ry6,Text as sd}from"ink";import{jsx as bc0,jsxs as yc0}from"react/jsx-runtime";function qy6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function ld1({logs:$}){return bc0(Ry6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return bc0(sd,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return yc0(sd,{children:[yc0(sd,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),bc0(sd,{color:qy6(Z.status),children:Z.status}),yc0(sd,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var dd1=()=>{};var gc0={};z0(gc0,{App:()=>Sy6});import{Box as My6}from"ink";import{useSyncExternalStore as ky6}from"react";import{jsx as md1,jsxs as Vy6}from"react/jsx-runtime";function Sy6({home:$}){let Z=ky6(Cc0,Vc0);return Vy6(My6,{flexDirection:"column",children:[md1(ud1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),md1(ld1,{logs:Z.logs})]})}var hc0=O(()=>{cd1();dd1();LD()});var e3="thread-gate",JN="decopilot-hosted-harness",uG="automations",iF="background-tools";var id1="7";function nd1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:id1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var pd1=()=>{};function Cy6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function uc0($,Z){for(let X=0;X<$.length;X++){let Q=$[X];if(Q===void 0)continue;if(Q===Z)return $[X+1];if(Q.startsWith(`${Z}=`))return Q.slice(Z.length+1)}return}function td1(){let $=Cy6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:uc0($,"--cpu-prof-dir")??process.cwd(),name:uc0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(uc0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function od1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=UD();if(!X)return;let Q={};try{let{heapStats:Y}=await import("bun:jsc"),G=Y(),J=Object.entries(G.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);Q={objectCount:G.objectCount,heapSize:G.heapSize,top:Object.fromEntries(J)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:X.rss,heapUsed:X.heapUsed,heapTotal:X.heapTotal,external:X.external,arrayBuffers:X.arrayBuffers,...Q}))};return Z().catch(()=>{}),F50=setInterval(()=>void Z().catch(()=>{}),$),F50.unref?.(),process.on("SIGUSR2",()=>{try{let X=Bun.generateHeapSnapshot("v8"),Q=typeof X==="string"?X:JSON.stringify(X),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,Q),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(X){console.error("[heap-watch] snapshot failed:",X)}}),()=>{if(F50)clearInterval(F50)}}var F50;var rd1=()=>{};import*as _y6 from"bun:jsc";function ad1(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{xy6()}catch(G){return console.error("[stall-watchdog] failed to start sampling profiler:",G),()=>{}}let X,Q=performance.now()+Z,Y=()=>{let G=performance.now(),J=G-Q;Q=G+Z;let K=[];try{K=vy6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let N of K){let U=N.frames.find((B)=>B.sourceURL&&!/Unknown Executable/.test(B.category??""))??N.frames[0];if(!U)continue;let F=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),w=`${U.name??"?"} @ ${F}:${U.line??"?"}`;W.set(w,(W.get(w)??0)+1)}let H=[...W.entries()].sort((N,U)=>U[1]-N[1]).slice(0,8).map(([N,U])=>({frame:N,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(J),samplesInWindow:K.length,top:H}))}X=setTimeout(Y,Z),X.unref?.()};return X=setTimeout(Y,Z),X.unref?.(),()=>{if(X)clearTimeout(X)}}var xy6,vy6;var sd1=O(()=>{({startSamplingProfiler:xy6,samplingProfilerStackTraces:vy6}=_y6)});function ed1(){td1();let $=[od1(),wu1(),ad1()];return()=>{for(let Z of $)Z()}}var $m1=O(()=>{Qg0();rd1();sd1()});var ED=_((Zm1)=>{Object.defineProperty(Zm1,"__esModule",{value:!0});Zm1.RepublishHeaders=Zm1.DirectMsgHeaders=Zm1.JsHeaders=Zm1.AdvisoryKind=void 0;Zm1.isOrderedPushConsumerOptions=fy6;Zm1.isPullConsumer=by6;Zm1.isPushConsumer=yy6;Zm1.isBoundPushConsumerOptions=gy6;function fy6($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function by6($){return $.isPullConsumer()}function yy6($){return $.isPushConsumer()}function gy6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}Zm1.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};Zm1.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};Zm1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};Zm1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var CY=_((Qm1)=>{Object.defineProperty(Qm1,"__esModule",{value:!0});Qm1.TD=Qm1.TE=Qm1.Empty=void 0;Qm1.encode=py6;Qm1.decode=ty6;Qm1.Empty=new Uint8Array(0);Qm1.TE=new TextEncoder;Qm1.TD=new TextDecoder;function ny6(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}function py6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(Qm1.TE.encode($[X]));if(Z.length===0)return Qm1.Empty;if(Z.length===1)return Z[0];return ny6(...Z)}function ty6($){if(!$||$.length===0)return"";return Qm1.TD.decode($)}});var _Y=_((Jm1)=>{Object.defineProperty(Jm1,"__esModule",{value:!0});Jm1.errors=Jm1.PermissionViolationError=Jm1.NoRespondersError=Jm1.TimeoutError=Jm1.RequestError=Jm1.ProtocolError=Jm1.ConnectionError=Jm1.DrainingConnectionError=Jm1.ClosedConnectionError=Jm1.AuthorizationError=Jm1.UserAuthenticationExpiredError=Jm1.InvalidOperationError=Jm1.InvalidArgumentError=Jm1.InvalidSubjectError=void 0;class lc0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}Jm1.InvalidSubjectError=lc0;class w50 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,X){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((Q)=>`'${Q}'`),$=$.join(",");else $=`'${$}'`;return new w50(`${$} ${Z}`,X)}}Jm1.InvalidArgumentError=w50;class dc0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}Jm1.InvalidOperationError=dc0;class B50 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new B50($);return null}}Jm1.UserAuthenticationExpiredError=B50;class O50 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],X=$.toLowerCase();for(let Q=0;Q<Z.length;Q++)if(X.indexOf(Z[Q])!==-1)return new O50($);return null}}Jm1.AuthorizationError=O50;class mc0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Jm1.ClosedConnectionError=mc0;class ic0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Jm1.DrainingConnectionError=ic0;class nc0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}Jm1.ConnectionError=nc0;class pc0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}Jm1.ProtocolError=pc0;class tc0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof L50}}Jm1.RequestError=tc0;class oc0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}Jm1.TimeoutError=oc0;class L50 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}Jm1.NoRespondersError=L50;class D50 extends Error{operation;subject;queue;constructor($,Z,X,Q,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=X,this.queue=Q}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let X="publish",Q="",Y=void 0,G=$.match(/(Publish|Subscription) to "(\S+)"/);if(G){if(X=G[1].toLowerCase(),Q=G[2],X==="subscription"){let J=$.match(/using queue "(\S+)"/);if(J)Y=J[1]}}return new D50($,X,Q,Y)}}Jm1.PermissionViolationError=D50;Jm1.errors={AuthorizationError:O50,ClosedConnectionError:mc0,ConnectionError:nc0,DrainingConnectionError:ic0,InvalidArgumentError:w50,InvalidOperationError:dc0,InvalidSubjectError:lc0,NoRespondersError:L50,PermissionViolationError:D50,ProtocolError:pc0,RequestError:tc0,TimeoutError:oc0,UserAuthenticationExpiredError:B50}});var $J=_((Um1)=>{Object.defineProperty(Um1,"__esModule",{value:!0});Um1.SimpleMutex=Um1.Perf=void 0;Um1.extend=Ug6;Um1.render=Fg6;Um1.timeout=wg6;Um1.delay=Bg6;Um1.deadline=Og6;Um1.deferred=ac0;Um1.debugDeferred=Lg6;Um1.shuffle=Dg6;Um1.collect=Eg6;Um1.jitter=Nm1;Um1.backoff=zg6;Um1.nanos=jg6;Um1.millis=Pg6;Um1.randomToken=Ig6;var Ng6=CY(),rc0=_Y();function Ug6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Fg6($){return Ng6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function wg6($,Z=!0){let X=Z?new rc0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new rc0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function Bg6($=0){let Z,X=new Promise((Q)=>{let Y=setTimeout(()=>{Q()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),Q()}}});return Object.assign(X,Z)}async function Og6($,Z=1000){let X=ac0(),Q=setTimeout(()=>{X.reject(new rc0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function ac0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function Lg6(){let $={},Z=new Promise((X,Q)=>{$={resolve:(Y)=>{console.trace("resolve",Y),X(Y)},reject:(Y)=>{console.trace("reject"),Q(Y)}}});return Object.assign(Z,$)}function Dg6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function Eg6($){let Z=[];for await(let X of $)Z.push(X);return Z}class Wm1{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,X){let Q=this.timers.get(Z);if(Q===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(X);if(Y===void 0)throw Error(`${X} is not defined`);this.measures.set($,Y-Q)}getEntries(){let $=[];return this.measures.forEach((Z,X)=>{$.push({name:X,duration:Z})}),$}}Um1.Perf=Wm1;class Hm1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=ac0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}Um1.SimpleMutex=Hm1;function Nm1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function zg6($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(X){return Nm1(X>Z?$[Z]:$[X])}}}function jg6($){return $*1e6}function Pg6($){return Math.floor($/1e6)}var Ag6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",KN=new Uint8Array(62);for(let $=0;$<62;$++)KN[$]=Ag6.charCodeAt($);var Tg6=218340105584896;function Ig6(){let $=Math.floor(Math.random()*Tg6),Z=$%62,X=KN[Z];$=($-Z)/62,Z=$%62;let Q=KN[Z];$=($-Z)/62,Z=$%62;let Y=KN[Z];$=($-Z)/62,Z=$%62;let G=KN[Z];$=($-Z)/62,Z=$%62;let J=KN[Z];$=($-Z)/62,Z=$%62;let K=KN[Z];$=($-Z)/62,Z=$%62;let W=KN[Z];$=($-Z)/62;let H=KN[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var zm1=_((Dm1)=>{Object.defineProperty(Dm1,"__esModule",{value:!0});Dm1.nuid=Dm1.NuidImpl=void 0;var ug6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",nF=62,z50=12,Om1=10,wm1=33,cg6=333,Bm1=z50+Om1,ec0=new Uint8Array(nF);for(let $=0;$<nF;$++)ec0[$]=ug6.charCodeAt($);var E50=4294967296,Lm1=BigInt(nF)**BigInt(Om1),ed=Number(Lm1/(1n<<32n)),sc0=Number(Lm1%(1n<<32n));function lg6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function dg6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else lg6($)}class $l0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Bm1),this.cbuf=new Uint8Array(z50),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(ed+1)),this.seqLo=Math.floor(Math.random()*E50);while($++<8&&this.seqHi===ed&&this.seqLo>=sc0);if(this.seqHi===ed&&this.seqLo>=sc0)this.seqLo=0;this.inc=Math.random()*(cg6-wm1)+wm1|0}setPre(){dg6(this.cbuf);for(let $=0;$<z50;$++)this.buf[$]=ec0[this.cbuf[$]%nF]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=Bm1-1;X>=z50;X--){let Q=Math.floor($/nF),G=($-Q*nF)*E50+Z,J=Math.floor(G/nF),K=G-J*nF;this.buf[X]=ec0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=E50)this.seqLo-=E50,this.seqHi+=1;if(this.seqHi>ed||this.seqHi===ed&&this.seqLo>=sc0)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}Dm1.NuidImpl=$l0;Dm1.nuid=new $l0});var Tm1=_((Pm1)=>{Object.defineProperty(Pm1,"__esModule",{value:!0});Pm1.nuid=Pm1.Nuid=void 0;var jm1=zm1();Pm1.Nuid=jm1.NuidImpl;Pm1.nuid=jm1.nuid});var P50=_((j50)=>{Object.defineProperty(j50,"__esModule",{value:!0});j50.nuid=j50.Nuid=void 0;var Im1=Tm1();Object.defineProperty(j50,"Nuid",{enumerable:!0,get:function(){return Im1.Nuid}});Object.defineProperty(j50,"nuid",{enumerable:!0,get:function(){return Im1.nuid}})});var pF=_((Rm1)=>{Object.defineProperty(Rm1,"__esModule",{value:!0});Rm1.DEFAULT_HOST=Rm1.DEFAULT_PORT=Rm1.Match=void 0;Rm1.syncIterator=og6;Rm1.createInbox=rg6;var pg6=P50(),tg6=_Y();Rm1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function og6($){let Z=$[Symbol.asyncIterator]();return{async next(){let X=await Z.next();if(X.done)return Promise.resolve(null);return Promise.resolve(X.value)}}}function rg6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw tg6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${pg6.nuid.next()}`}Rm1.DEFAULT_PORT=4222;Rm1.DEFAULT_HOST="127.0.0.1"});var $m=_((Sm1)=>{Object.defineProperty(Sm1,"__esModule",{value:!0});Sm1.DataBuffer=void 0;var Mm1=CY();class km1{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}static fromAscii($){if(!$)$="";return Mm1.TE.encode($)}static toAscii($){return Mm1.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let X=0;X<this.buffers.length;X++)$.set(this.buffers[X],Z),Z+=this.buffers[X].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let X=this.byteLength;if($===void 0||$>X)$=X;let Q=Z.subarray(0,$);if(X>$)this.buffers.push(Z.subarray($));return this.byteLength=X-$,Q}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let X=0;X<Z.length;X++)if(Z[X]&&Z[X].length)this.buffers.push(Z[X]),this.byteLength+=Z[X].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}Sm1.DataBuffer=km1});var zD=_((_m1)=>{Object.defineProperty(_m1,"__esModule",{value:!0});_m1.LF=_m1.CR=_m1.CRLF=_m1.CR_LF_LEN=_m1.CR_LF=void 0;_m1.setTransportFactory=Yh6;_m1.defaultPort=Gh6;_m1.getUrlParseFn=Jh6;_m1.newTransport=Kh6;_m1.getResolveFn=Wh6;_m1.protoLen=Cm1;_m1.extractProtocolMessage=Hh6;var Zh6=CY(),Xh6=pF(),Qh6=$m(),xY;function Yh6($){xY=$}function Gh6(){return xY!==void 0&&xY.defaultPort!==void 0?xY.defaultPort:Xh6.DEFAULT_PORT}function Jh6(){return xY!==void 0&&xY.urlParseFn?xY.urlParseFn:void 0}function Kh6(){if(!xY||typeof xY.factory!=="function")throw Error("transport fn is not set");return xY.factory()}function Wh6(){return xY!==void 0&&xY.dnsResolveFn?xY.dnsResolveFn:void 0}_m1.CR_LF=`\r
|
|
1259
|
+
`);Q=G.pop()??"";for(let J of G){let K=ad(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;dF({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{for(;;){let{done:G,value:J}=await Z.read();if(G)break;Q+=X.decode(J,{stream:!0}),Y()}if(Q.trim()){let G=ad(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)dF({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function zy6($){let{baseUrl:Z,noTui:X}=$,Q=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=Q?process.env.PORT:$.vitePort,G=Z||`http://localhost:${Y}`,J=Q?await rd(Number(Y)+1):await rd(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await W50({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)OD({name:L.name,status:"ready",port:L.port});td();let N=Ey6(import.meta.dir,"..","..","..","..",".."),U=X===!0,F=Bun.spawn(["bun","run","dev:servers"],{cwd:N,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:G,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsPublicUrl&&K.natsAccountJwt&&K.natsAccountSigningKey?{NATS_PUBLIC_URL:K.natsPublicUrl,NATS_ACCOUNT_JWT:K.natsAccountJwt,NATS_ACCOUNT_SIGNING_KEY:K.natsAccountSigningKey,NATS_OPERATOR_JWT:K.natsOperatorJwt??"",NATS_TUNNEL_PUBLIC_ENABLED:"true",...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)vd1(F.stdout),vd1(F.stderr);od(G),OD({name:"Vite",status:"ready",port:Number(Y)}),OD({name:"API",status:"ready",port:Number(K.port)});let B=async(L)=>{if(F.kill(L),await F.exited,H.length>0){let{stopServices:D}=await Promise.resolve().then(() => (P$0(),j$0));await D(K.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(Y),process:F}}var vc0=O(()=>{kc0();LD();_c0()});var U50;var fc0=O(()=>{U50={name:"decocms",version:"4.170.7",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",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.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","@nats-io/jwt":"0.0.10-5","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as Py6,Text as fd1}from"ink";import{jsx as Ay6,jsxs as bd1}from"react/jsx-runtime";function yd1({version:$}){return bd1(Py6,{flexDirection:"column",marginTop:1,children:[l$0.map((Z,X)=>Ay6(fd1,{color:d$0[X],children:Z},X)),bd1(fd1,{dimColor:!0,children:[" v",$]})]})}var gd1=O(()=>{bd()});import{Box as DD,Text as mF}from"ink";import{Spinner as Ty6}from"@inkjs/ui";import{jsx as VY,jsxs as Mf}from"react/jsx-runtime";function hd1({status:$}){if($==="pending")return VY(Ty6,{label:""});return VY(mF,{color:"green",children:"\u2713"})}function Iy6($){return`${$.name}: ${$.port||"...."}`}function ud1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return Mf(DD,{flexDirection:"column",paddingBottom:1,children:[VY(yd1,{version:U50.version}),VY(DD,{marginBottom:1,children:VY(mF,{dimColor:!0,children:"\u2500".repeat(80)})}),VY(DD,{children:Mf(mF,{dimColor:!0,children:["Home: ",X]})}),Mf(DD,{gap:2,children:[$.map((Y)=>Mf(DD,{gap:1,children:[VY(mF,{children:Iy6(Y)}),VY(hd1,{status:Y.status})]},Y.name)),Mf(DD,{gap:1,children:[VY(mF,{children:"Migrations"}),VY(hd1,{status:Z})]})]}),VY(DD,{children:Q?Mf(mF,{children:["Open in browser: ",VY(mF,{color:"cyan",children:Q})]}):VY(mF,{dimColor:!0,children:"Starting..."})})]})}var cd1=O(()=>{fc0();gd1()});import{Box as Ry6,Text as sd}from"ink";import{jsx as bc0,jsxs as yc0}from"react/jsx-runtime";function qy6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function ld1({logs:$}){return bc0(Ry6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return bc0(sd,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return yc0(sd,{children:[yc0(sd,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),bc0(sd,{color:qy6(Z.status),children:Z.status}),yc0(sd,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var dd1=()=>{};var gc0={};z0(gc0,{App:()=>Sy6});import{Box as My6}from"ink";import{useSyncExternalStore as ky6}from"react";import{jsx as md1,jsxs as Vy6}from"react/jsx-runtime";function Sy6({home:$}){let Z=ky6(Cc0,Vc0);return Vy6(My6,{flexDirection:"column",children:[md1(ud1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),md1(ld1,{logs:Z.logs})]})}var hc0=O(()=>{cd1();dd1();LD()});var e3="thread-gate",JN="decopilot-hosted-harness",uG="automations",iF="background-tools";var id1="7";function nd1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:id1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var pd1=()=>{};function Cy6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function uc0($,Z){for(let X=0;X<$.length;X++){let Q=$[X];if(Q===void 0)continue;if(Q===Z)return $[X+1];if(Q.startsWith(`${Z}=`))return Q.slice(Z.length+1)}return}function td1(){let $=Cy6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:uc0($,"--cpu-prof-dir")??process.cwd(),name:uc0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(uc0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function od1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=UD();if(!X)return;let Q={};try{let{heapStats:Y}=await import("bun:jsc"),G=Y(),J=Object.entries(G.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);Q={objectCount:G.objectCount,heapSize:G.heapSize,top:Object.fromEntries(J)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:X.rss,heapUsed:X.heapUsed,heapTotal:X.heapTotal,external:X.external,arrayBuffers:X.arrayBuffers,...Q}))};return Z().catch(()=>{}),F50=setInterval(()=>void Z().catch(()=>{}),$),F50.unref?.(),process.on("SIGUSR2",()=>{try{let X=Bun.generateHeapSnapshot("v8"),Q=typeof X==="string"?X:JSON.stringify(X),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,Q),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(X){console.error("[heap-watch] snapshot failed:",X)}}),()=>{if(F50)clearInterval(F50)}}var F50;var rd1=()=>{};import*as _y6 from"bun:jsc";function ad1(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{xy6()}catch(G){return console.error("[stall-watchdog] failed to start sampling profiler:",G),()=>{}}let X,Q=performance.now()+Z,Y=()=>{let G=performance.now(),J=G-Q;Q=G+Z;let K=[];try{K=vy6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let N of K){let U=N.frames.find((B)=>B.sourceURL&&!/Unknown Executable/.test(B.category??""))??N.frames[0];if(!U)continue;let F=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),w=`${U.name??"?"} @ ${F}:${U.line??"?"}`;W.set(w,(W.get(w)??0)+1)}let H=[...W.entries()].sort((N,U)=>U[1]-N[1]).slice(0,8).map(([N,U])=>({frame:N,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(J),samplesInWindow:K.length,top:H}))}X=setTimeout(Y,Z),X.unref?.()};return X=setTimeout(Y,Z),X.unref?.(),()=>{if(X)clearTimeout(X)}}var xy6,vy6;var sd1=O(()=>{({startSamplingProfiler:xy6,samplingProfilerStackTraces:vy6}=_y6)});function ed1(){td1();let $=[od1(),wu1(),ad1()];return()=>{for(let Z of $)Z()}}var $m1=O(()=>{Qg0();rd1();sd1()});var ED=_((Zm1)=>{Object.defineProperty(Zm1,"__esModule",{value:!0});Zm1.RepublishHeaders=Zm1.DirectMsgHeaders=Zm1.JsHeaders=Zm1.AdvisoryKind=void 0;Zm1.isOrderedPushConsumerOptions=fy6;Zm1.isPullConsumer=by6;Zm1.isPushConsumer=yy6;Zm1.isBoundPushConsumerOptions=gy6;function fy6($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function by6($){return $.isPullConsumer()}function yy6($){return $.isPushConsumer()}function gy6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}Zm1.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};Zm1.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};Zm1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};Zm1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var CY=_((Qm1)=>{Object.defineProperty(Qm1,"__esModule",{value:!0});Qm1.TD=Qm1.TE=Qm1.Empty=void 0;Qm1.encode=py6;Qm1.decode=ty6;Qm1.Empty=new Uint8Array(0);Qm1.TE=new TextEncoder;Qm1.TD=new TextDecoder;function ny6(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}function py6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(Qm1.TE.encode($[X]));if(Z.length===0)return Qm1.Empty;if(Z.length===1)return Z[0];return ny6(...Z)}function ty6($){if(!$||$.length===0)return"";return Qm1.TD.decode($)}});var _Y=_((Jm1)=>{Object.defineProperty(Jm1,"__esModule",{value:!0});Jm1.errors=Jm1.PermissionViolationError=Jm1.NoRespondersError=Jm1.TimeoutError=Jm1.RequestError=Jm1.ProtocolError=Jm1.ConnectionError=Jm1.DrainingConnectionError=Jm1.ClosedConnectionError=Jm1.AuthorizationError=Jm1.UserAuthenticationExpiredError=Jm1.InvalidOperationError=Jm1.InvalidArgumentError=Jm1.InvalidSubjectError=void 0;class lc0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}Jm1.InvalidSubjectError=lc0;class w50 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,X){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((Q)=>`'${Q}'`),$=$.join(",");else $=`'${$}'`;return new w50(`${$} ${Z}`,X)}}Jm1.InvalidArgumentError=w50;class dc0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}Jm1.InvalidOperationError=dc0;class B50 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new B50($);return null}}Jm1.UserAuthenticationExpiredError=B50;class O50 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],X=$.toLowerCase();for(let Q=0;Q<Z.length;Q++)if(X.indexOf(Z[Q])!==-1)return new O50($);return null}}Jm1.AuthorizationError=O50;class mc0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Jm1.ClosedConnectionError=mc0;class ic0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Jm1.DrainingConnectionError=ic0;class nc0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}Jm1.ConnectionError=nc0;class pc0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}Jm1.ProtocolError=pc0;class tc0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof L50}}Jm1.RequestError=tc0;class oc0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}Jm1.TimeoutError=oc0;class L50 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}Jm1.NoRespondersError=L50;class D50 extends Error{operation;subject;queue;constructor($,Z,X,Q,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=X,this.queue=Q}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let X="publish",Q="",Y=void 0,G=$.match(/(Publish|Subscription) to "(\S+)"/);if(G){if(X=G[1].toLowerCase(),Q=G[2],X==="subscription"){let J=$.match(/using queue "(\S+)"/);if(J)Y=J[1]}}return new D50($,X,Q,Y)}}Jm1.PermissionViolationError=D50;Jm1.errors={AuthorizationError:O50,ClosedConnectionError:mc0,ConnectionError:nc0,DrainingConnectionError:ic0,InvalidArgumentError:w50,InvalidOperationError:dc0,InvalidSubjectError:lc0,NoRespondersError:L50,PermissionViolationError:D50,ProtocolError:pc0,RequestError:tc0,TimeoutError:oc0,UserAuthenticationExpiredError:B50}});var $J=_((Um1)=>{Object.defineProperty(Um1,"__esModule",{value:!0});Um1.SimpleMutex=Um1.Perf=void 0;Um1.extend=Ug6;Um1.render=Fg6;Um1.timeout=wg6;Um1.delay=Bg6;Um1.deadline=Og6;Um1.deferred=ac0;Um1.debugDeferred=Lg6;Um1.shuffle=Dg6;Um1.collect=Eg6;Um1.jitter=Nm1;Um1.backoff=zg6;Um1.nanos=jg6;Um1.millis=Pg6;Um1.randomToken=Ig6;var Ng6=CY(),rc0=_Y();function Ug6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Fg6($){return Ng6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function wg6($,Z=!0){let X=Z?new rc0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new rc0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function Bg6($=0){let Z,X=new Promise((Q)=>{let Y=setTimeout(()=>{Q()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),Q()}}});return Object.assign(X,Z)}async function Og6($,Z=1000){let X=ac0(),Q=setTimeout(()=>{X.reject(new rc0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function ac0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function Lg6(){let $={},Z=new Promise((X,Q)=>{$={resolve:(Y)=>{console.trace("resolve",Y),X(Y)},reject:(Y)=>{console.trace("reject"),Q(Y)}}});return Object.assign(Z,$)}function Dg6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function Eg6($){let Z=[];for await(let X of $)Z.push(X);return Z}class Wm1{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,X){let Q=this.timers.get(Z);if(Q===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(X);if(Y===void 0)throw Error(`${X} is not defined`);this.measures.set($,Y-Q)}getEntries(){let $=[];return this.measures.forEach((Z,X)=>{$.push({name:X,duration:Z})}),$}}Um1.Perf=Wm1;class Hm1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=ac0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}Um1.SimpleMutex=Hm1;function Nm1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function zg6($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(X){return Nm1(X>Z?$[Z]:$[X])}}}function jg6($){return $*1e6}function Pg6($){return Math.floor($/1e6)}var Ag6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",KN=new Uint8Array(62);for(let $=0;$<62;$++)KN[$]=Ag6.charCodeAt($);var Tg6=218340105584896;function Ig6(){let $=Math.floor(Math.random()*Tg6),Z=$%62,X=KN[Z];$=($-Z)/62,Z=$%62;let Q=KN[Z];$=($-Z)/62,Z=$%62;let Y=KN[Z];$=($-Z)/62,Z=$%62;let G=KN[Z];$=($-Z)/62,Z=$%62;let J=KN[Z];$=($-Z)/62,Z=$%62;let K=KN[Z];$=($-Z)/62,Z=$%62;let W=KN[Z];$=($-Z)/62;let H=KN[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var zm1=_((Dm1)=>{Object.defineProperty(Dm1,"__esModule",{value:!0});Dm1.nuid=Dm1.NuidImpl=void 0;var ug6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",nF=62,z50=12,Om1=10,wm1=33,cg6=333,Bm1=z50+Om1,ec0=new Uint8Array(nF);for(let $=0;$<nF;$++)ec0[$]=ug6.charCodeAt($);var E50=4294967296,Lm1=BigInt(nF)**BigInt(Om1),ed=Number(Lm1/(1n<<32n)),sc0=Number(Lm1%(1n<<32n));function lg6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function dg6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else lg6($)}class $l0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Bm1),this.cbuf=new Uint8Array(z50),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(ed+1)),this.seqLo=Math.floor(Math.random()*E50);while($++<8&&this.seqHi===ed&&this.seqLo>=sc0);if(this.seqHi===ed&&this.seqLo>=sc0)this.seqLo=0;this.inc=Math.random()*(cg6-wm1)+wm1|0}setPre(){dg6(this.cbuf);for(let $=0;$<z50;$++)this.buf[$]=ec0[this.cbuf[$]%nF]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=Bm1-1;X>=z50;X--){let Q=Math.floor($/nF),G=($-Q*nF)*E50+Z,J=Math.floor(G/nF),K=G-J*nF;this.buf[X]=ec0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=E50)this.seqLo-=E50,this.seqHi+=1;if(this.seqHi>ed||this.seqHi===ed&&this.seqLo>=sc0)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}Dm1.NuidImpl=$l0;Dm1.nuid=new $l0});var Tm1=_((Pm1)=>{Object.defineProperty(Pm1,"__esModule",{value:!0});Pm1.nuid=Pm1.Nuid=void 0;var jm1=zm1();Pm1.Nuid=jm1.NuidImpl;Pm1.nuid=jm1.nuid});var P50=_((j50)=>{Object.defineProperty(j50,"__esModule",{value:!0});j50.nuid=j50.Nuid=void 0;var Im1=Tm1();Object.defineProperty(j50,"Nuid",{enumerable:!0,get:function(){return Im1.Nuid}});Object.defineProperty(j50,"nuid",{enumerable:!0,get:function(){return Im1.nuid}})});var pF=_((Rm1)=>{Object.defineProperty(Rm1,"__esModule",{value:!0});Rm1.DEFAULT_HOST=Rm1.DEFAULT_PORT=Rm1.Match=void 0;Rm1.syncIterator=og6;Rm1.createInbox=rg6;var pg6=P50(),tg6=_Y();Rm1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function og6($){let Z=$[Symbol.asyncIterator]();return{async next(){let X=await Z.next();if(X.done)return Promise.resolve(null);return Promise.resolve(X.value)}}}function rg6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw tg6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${pg6.nuid.next()}`}Rm1.DEFAULT_PORT=4222;Rm1.DEFAULT_HOST="127.0.0.1"});var $m=_((Sm1)=>{Object.defineProperty(Sm1,"__esModule",{value:!0});Sm1.DataBuffer=void 0;var Mm1=CY();class km1{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}static fromAscii($){if(!$)$="";return Mm1.TE.encode($)}static toAscii($){return Mm1.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let X=0;X<this.buffers.length;X++)$.set(this.buffers[X],Z),Z+=this.buffers[X].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let X=this.byteLength;if($===void 0||$>X)$=X;let Q=Z.subarray(0,$);if(X>$)this.buffers.push(Z.subarray($));return this.byteLength=X-$,Q}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let X=0;X<Z.length;X++)if(Z[X]&&Z[X].length)this.buffers.push(Z[X]),this.byteLength+=Z[X].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}Sm1.DataBuffer=km1});var zD=_((_m1)=>{Object.defineProperty(_m1,"__esModule",{value:!0});_m1.LF=_m1.CR=_m1.CRLF=_m1.CR_LF_LEN=_m1.CR_LF=void 0;_m1.setTransportFactory=Yh6;_m1.defaultPort=Gh6;_m1.getUrlParseFn=Jh6;_m1.newTransport=Kh6;_m1.getResolveFn=Wh6;_m1.protoLen=Cm1;_m1.extractProtocolMessage=Hh6;var Zh6=CY(),Xh6=pF(),Qh6=$m(),xY;function Yh6($){xY=$}function Gh6(){return xY!==void 0&&xY.defaultPort!==void 0?xY.defaultPort:Xh6.DEFAULT_PORT}function Jh6(){return xY!==void 0&&xY.urlParseFn?xY.urlParseFn:void 0}function Kh6(){if(!xY||typeof xY.factory!=="function")throw Error("transport fn is not set");return xY.factory()}function Wh6(){return xY!==void 0&&xY.dnsResolveFn?xY.dnsResolveFn:void 0}_m1.CR_LF=`\r
|
|
1260
1260
|
`;_m1.CR_LF_LEN=_m1.CR_LF.length;_m1.CRLF=Qh6.DataBuffer.fromAscii(_m1.CR_LF);_m1.CR=new Uint8Array(_m1.CRLF)[0];_m1.LF=new Uint8Array(_m1.CRLF)[1];function Cm1($){for(let Z=0;Z<$.length;Z++){let X=Z+1;if($.byteLength>X&&$[Z]===_m1.CR&&$[X]===_m1.LF)return X+1}return 0}function Hh6($){let Z=Cm1($);if(Z>0){let Q=new Uint8Array($).slice(0,Z);return Zh6.TD.decode(Q)}return""}});var Gl0=_((um1)=>{Object.defineProperty(um1,"__esModule",{value:!0});um1.ipV4=ym1;um1.isIP=jh6;um1.parseIP=gm1;var Zm=4,jD=16,A50=48,bm1=57,vm1=65,Eh6=70,fm1=97,zh6=102,Yl0=16777215;function ym1($,Z,X,Q){let Y=new Uint8Array(jD);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((J,K)=>{Y[K]=J}),Y[12]=$,Y[13]=Z,Y[14]=X,Y[15]=Q,Y}function jh6($){return gm1($)!==void 0}function gm1($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return hm1($);case":":return Ph6($)}return}function hm1($){let Z=new Uint8Array(Zm);for(let X=0;X<Zm;X++){if($.length===0)return;if(X>0){if($[0]!==".")return;$=$.substring(1)}let{n:Q,c:Y,ok:G}=Ah6($);if(!G||Q>255)return;$=$.substring(Y),Z[X]=Q}return ym1(Z[0],Z[1],Z[2],Z[3])}function Ph6($){let Z=new Uint8Array(jD),X=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(X=0,$=$.substring(2),$.length===0)return Z}let Q=0;while(Q<jD){let{n:Y,c:G,ok:J}=Th6($);if(!J||Y>65535)return;if(G<$.length&&$[G]==="."){if(X<0&&Q!=jD-Zm)return;if(Q+Zm>jD)return;let K=hm1($);if(K===void 0)return;Z[Q]=K[12],Z[Q+1]=K[13],Z[Q+2]=K[14],Z[Q+3]=K[15],$="",Q+=Zm;break}if(Z[Q]=Y>>8,Z[Q+1]=Y,Q+=2,$=$.substring(G),$.length===0)break;if($[0]!==":"||$.length==1)return;if($=$.substring(1),$[0]===":"){if(X>=0)return;if(X=Q,$=$.substring(1),$.length===0)break}}if($.length!==0)return;if(Q<jD){if(X<0)return;let Y=jD-Q;for(let G=Q-1;G>=X;G--)Z[G+Y]=Z[G];for(let G=X+Y-1;G>=X;G--)Z[G]=0}else if(X>=0)return;return Z}function Ah6($){let Z=0,X=0;for(Z=0;Z<$.length&&A50<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=bm1;Z++)if(X=X*10+($.charCodeAt(Z)-A50),X>=Yl0)return{n:Yl0,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:X,c:Z,ok:!0}}function Th6($){let Z=0,X=0;for(X=0;X<$.length;X++){if(A50<=$.charCodeAt(X)&&$.charCodeAt(X)<=bm1)Z*=16,Z+=$.charCodeAt(X)-A50;else if(fm1<=$.charCodeAt(X)&&$.charCodeAt(X)<=zh6)Z*=16,Z+=$.charCodeAt(X)-fm1+10;else if(vm1<=$.charCodeAt(X)&&$.charCodeAt(X)<=Eh6)Z*=16,Z+=$.charCodeAt(X)-vm1+10;else break;if(Z>=Yl0)return{n:0,c:X,ok:!1}}if(X===0)return{n:0,c:X,ok:!1};return{n:Z,c:X,ok:!0}}});var Ul0=_((lm1)=>{Object.defineProperty(lm1,"__esModule",{value:!0});lm1.Servers=lm1.ServerImpl=void 0;lm1.isIPV4OrHostname=cm1;lm1.hostPort=Nl0;var Jl0=zD(),Kl0=$J(),Wl0=Gl0(),Mh6=pF(),kh6=_Y();function cm1($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function Hl0($){return!cm1($)}function Sh6($){let X=$.toUpperCase().indexOf("::FFFF:");if(X!==-1&&$.indexOf(".")!==-1){let Q=$.substring(X+7);return Q=Q.replace("[",""),Q.replace("]","")}return $}function Nl0($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=Sh6($),Hl0($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=Hl0($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),X=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):Mh6.DEFAULT_PORT,Y=new URL(`${X===80?"https":"http"}://${$}`);Y.port=`${X}`;let G=Y.hostname;if(G.charAt(0)==="[")G=G.substring(1,G.length-1);return{listen:Y.host,hostname:G,port:X}}class kf{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let X=Nl0($);this.listen=X.listen,this.hostname=X.hostname,this.port=X.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=Z}toString(){return this.listen}async resolve($){if(!$.fn||$.resolve===!1)return[this];let Z=[];if((0,Wl0.isIP)(this.hostname))return[this];else{let X=await $.fn(this.hostname);if($.debug)console.log(`resolve ${this.hostname} = ${X.join(",")}`);for(let Q of X){let Y=this.port===80?"https":"http",G=new URL(`${Y}://${Hl0(Q)?"["+Q+"]":Q}`);G.port=`${this.port}`;let J=new kf(G.host,!1);J.tlsName=this.hostname,Z.push(J)}}if($.randomize)(0,Kl0.shuffle)(Z);return this.resolves=Z,Z}}lm1.ServerImpl=kf;class T50{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw kh6.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,Jl0.getUrlParseFn)(),X=new Map;for(let Y of this.servers)X.set(Y.listen,Y);let Q=[];for(let Y of $){Y=Z?Z(Y):Y;let{listen:G}=Nl0(Y),J=X.get(G);if(J)J.gossiped=!1,Q.push(J);else Q.push(new kf(Y))}if(this.randomize)(0,Kl0.shuffle)(Q);if(this.servers=Q,this.currentServer===void 0||!Q.includes(this.currentServer))this.currentServer=Q[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let $=this.getCurrentServer();if(!(0,Wl0.isIP)($.hostname))this.tlsName=$.hostname,this.servers.forEach((Z)=>{if(Z.gossiped)Z.tlsName=this.tlsName})}getCurrentServer(){return this.currentServer}addServer($,Z=!1){let X=(0,Jl0.getUrlParseFn)();$=X?X($):$;let Q=new kf($,Z);if((0,Wl0.isIP)(Q.hostname))Q.tlsName=this.tlsName;this.servers.push(Q)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;let $=this.servers.shift();if($)this.servers.push($),this.currentServer=$;return $}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer($){if($){let Z=this.servers.indexOf($);this.servers.splice(Z,1)}}snapshot(){return T50.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return T50.freezeAll([$,...this.servers.slice(0,Z),...this.servers.slice(Z+1)])}static freezeAll($){return $.map((Z)=>Object.freeze({hostname:Z.hostname,port:Z.port,listen:Z.listen,src:Z.src,tlsName:Z.tlsName,reconnects:Z.reconnects,lastConnect:Z.lastConnect,gossiped:Z.gossiped,didConnect:Z.didConnect}))}find($){return this.servers.find((Z)=>Z.listen===$.listen)}setCurrent($){this.currentServer=$}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update($,Z){let X=[],Q=[],Y=(0,Jl0.getUrlParseFn)(),G=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((K)=>{K=Y?Y(K,Z):K;let W=new kf(K,!0);G.set(K,W)});let J=[];if(this.servers.forEach((K,W)=>{let H=K.listen;if(K.gossiped&&this.currentServer.listen!==H&&G.get(H)===void 0)J.push(W);G.delete(H)}),J.reverse(),J.forEach((K)=>{let W=this.servers.splice(K,1);Q=Q.concat(W[0].listen)}),G.forEach((K,W)=>{this.servers.push(K),X.push(W)}),this.randomize&&X.length>0){let K=this.currentServer,W=this.servers.filter((H)=>H!==K);(0,Kl0.shuffle)(W),this.servers=K?[K,...W]:W}return{added:X,deleted:Q}}}lm1.Servers=T50});var I50=_((nm1)=>{Object.defineProperty(nm1,"__esModule",{value:!0});nm1.QueuedIteratorImpl=void 0;var Fl0=$J(),mm1=_Y();class im1{inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ctx;_data;err;time;profile;yielding;didBreak;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=(0,Fl0.deferred)(),this.yields=[],this.iterClosed=(0,Fl0.deferred)(),this.time=0,this.yielding=!1,this.didBreak=!1,this.profile=!1}[Symbol.asyncIterator](){return this.iterate()}push($){if(this.done)return;if(this.didBreak){if(typeof $==="function"){let Z=$;try{Z()}catch(X){}}return}if(typeof $==="function")this.pendingFiltered++;this.yields.push($),this.signal.resolve()}async*iterate(){if(this.noIterator)throw new mm1.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new mm1.InvalidOperationError("iterator is already yielding");this.yielding=!0;try{while(!0){if(this.yields.length===0)await this.signal;if(this.err)throw this.err;let $=this.yields;this.inflight=$.length,this.yields=[];for(let Z=0;Z<$.length;Z++){if(typeof $[Z]==="function"){this.pendingFiltered--;let Q=$[Z];try{Q()}catch(Y){throw Y}if(this.err)throw this.err;continue}this.processed++,this.inflight--;let X=this.profile?Date.now():0;yield $[Z],this.time=this.profile?Date.now()-X:0}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,Fl0.deferred)()}}finally{this.didBreak=!0,this.stop()}}stop($){if(this.done)return;this.err=$,this.done=!0,this.signal.resolve(),this.iterClosed.resolve($)}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}nm1.QueuedIteratorImpl=im1});var wl0=_((rm1)=>{Object.defineProperty(rm1,"__esModule",{value:!0});rm1.MuxSubscription=void 0;var xh6=pF(),tm1=_Y();class om1{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,xh6.createInbox)($)}.`,this.baseInbox}add($){if(!isNaN($.received))$.received=0;this.reqs.set($.token,$)}get($){return this.reqs.get($)}cancel($){this.reqs.delete($.token)}getToken($){let Z=$.subject||"";if(Z.indexOf(this.baseInbox)===0)return Z.substring(this.baseInbox.length);return null}all(){return Array.from(this.reqs.values())}handleError($,Z){if($)return this.all().forEach((X)=>{X.resolver(Z,{})}),!0;if(Z.operation==="publish"){let X=this.all().find((Q)=>{return Q.requestSubject===Z.subject});if(X)return X.resolver(Z,{}),!0}return!1}dispatcher(){return($,Z)=>{let X=this.getToken(Z);if(X){let Q=this.get(X);if(Q){if($===null)$=Z?.data?.length===0&&Z.headers?.code===503?new tm1.NoRespondersError(Q.requestSubject):null;Q.resolver($,Z)}}}}close(){let $=new tm1.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}rm1.MuxSubscription=om1});var Bl0=_((em1)=>{Object.defineProperty(em1,"__esModule",{value:!0});em1.Heartbeat=void 0;var vh6=$J();class sm1{ph;interval;maxOut;timer;pendings;constructor($,Z,X){this.ph=$,this.interval=Z,this.maxOut=X,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel($){if(this.timer)clearTimeout(this.timer),this.timer=void 0;if(this._reset(),$)this.ph.disconnect()}_schedule(){this.timer=setTimeout(()=>{if(this.ph.dispatchStatus({type:"ping",pendingPings:this.pendings.length+1}),this.pendings.length===this.maxOut){this.cancel(!0);return}let $=(0,vh6.deferred)();this.ph.flush($).then(()=>{this._reset()}).catch(()=>{this.cancel()}),this.pendings.push($),this._schedule()},this.interval)}_reset(){this.pendings=this.pendings.filter(($)=>{return $.resolve(),!1})}}em1.Heartbeat=sm1});var Dl0=_((Yi1)=>{Object.defineProperty(Yi1,"__esModule",{value:!0});Yi1.DenoBuffer=Yi1.MAX_SIZE=Yi1.AssertionError=void 0;Yi1.assert=Xi1;Yi1.concat=Qi1;Yi1.append=bh6;Yi1.readAll=yh6;Yi1.writeAll=gh6;var fh6=CY();class Ol0 extends Error{constructor($){super($);this.name="AssertionError"}}Yi1.AssertionError=Ol0;function Xi1($,Z="Assertion failed."){if(!$)throw new Ol0(Z)}var Zi1=32768;Yi1.MAX_SIZE=4294967294;function R50($,Z,X=0){let Q=Z.byteLength-X;if($.byteLength>Q)$=$.subarray(0,Q);return Z.set($,X),$.byteLength}function Qi1($,Z){if($===void 0&&Z===void 0)return new Uint8Array(0);if($===void 0)return Z;if(Z===void 0)return $;let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function bh6($,Z){return Qi1($,Uint8Array.of(Z))}class Ll0{_buf;_off;constructor($){if(this._off=0,$==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array($)}bytes($={copy:!0}){if($.copy===!1)return this._buf.subarray(this._off);return this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate($){if($===0){this.reset();return}if($<0||$>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+$)}reset(){this._reslice(0),this._off=0}_tryGrowByReslice($){let Z=this._buf.byteLength;if($<=this.capacity-Z)return this._reslice(Z+$),Z;return-1}_reslice($){Xi1($<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,$)}readByte(){let $=new Uint8Array(1);if(this.read($))return $[0];return null}read($){if(this.empty()){if(this.reset(),$.byteLength===0)return 0;return null}let Z=R50(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write(fh6.TE.encode($))}write($){let Z=this._grow($.byteLength);return R50($,this._buf,Z)}_grow($){let Z=this.length;if(Z===0&&this._off!==0)this.reset();let X=this._tryGrowByReslice($);if(X>=0)return X;let Q=this.capacity;if($<=Math.floor(Q/2)-Z)R50(this._buf.subarray(this._off),this._buf);else if(Q+$>Yi1.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*Q+$,Yi1.MAX_SIZE));R50(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,Yi1.MAX_SIZE)),Z}grow($){if($<0)throw Error("Buffer._grow: negative count");let Z=this._grow($);this._reslice(Z)}readFrom($){let Z=0,X=new Uint8Array(Zi1);while(!0){let Q=this.capacity-this.length<Zi1,Y=Q?X:new Uint8Array(this._buf.buffer,this.length),G=$.read(Y);if(G===null)return Z;if(Q)this.write(Y.subarray(0,G));else this._reslice(this.length+G);Z+=G}}}Yi1.DenoBuffer=Ll0;function yh6($){let Z=new Ll0;return Z.readFrom($),Z.bytes()}function gh6($,Z){let X=0;while(X<Z.length)X+=$.write(Z.subarray(X))}});var jl0=_((Hi1)=>{Object.defineProperty(Hi1,"__esModule",{value:!0});Hi1.cc=Hi1.State=Hi1.Parser=Hi1.Kind=void 0;Hi1.describe=ih6;var El0=Dl0(),zl0=CY();Hi1.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function ih6($){let Z,X="";switch($.kind){case Hi1.Kind.MSG:Z="MSG";break;case Hi1.Kind.OK:Z="OK";break;case Hi1.Kind.ERR:Z="ERR",X=zl0.TD.decode($.data);break;case Hi1.Kind.PING:Z="PING";break;case Hi1.Kind.PONG:Z="PONG";break;case Hi1.Kind.INFO:Z="INFO",X=zl0.TD.decode($.data)}return`${Z}: ${X}`}function Ji1(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var Ki1=48,nh6=57,Sf=67108864;class Wi1{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=Hi1.State.OP_START,this.as=0,this.drop=0,this.hdr=0}parse($){let Z;for(Z=0;Z<$.length;Z++){let X=$[Z];switch(this.state){case Hi1.State.OP_START:switch(X){case Hi1.cc.M:case Hi1.cc.m:this.state=Hi1.State.OP_M,this.hdr=-1,this.ma=Ji1();break;case Hi1.cc.H:case Hi1.cc.h:this.state=Hi1.State.OP_H,this.hdr=0,this.ma=Ji1();break;case Hi1.cc.P:case Hi1.cc.p:this.state=Hi1.State.OP_P;break;case Hi1.cc.PLUS:this.state=Hi1.State.OP_PLUS;break;case Hi1.cc.MINUS:this.state=Hi1.State.OP_MINUS;break;case Hi1.cc.I:case Hi1.cc.i:this.state=Hi1.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_H:switch(X){case Hi1.cc.M:case Hi1.cc.m:this.state=Hi1.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_M:switch(X){case Hi1.cc.S:case Hi1.cc.s:this.state=Hi1.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_MS:switch(X){case Hi1.cc.G:case Hi1.cc.g:this.state=Hi1.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_MSG:switch(X){case Hi1.cc.SPACE:case Hi1.cc.TAB:this.state=Hi1.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_MSG_SPC:switch(X){case Hi1.cc.SPACE:case Hi1.cc.TAB:continue;default:this.state=Hi1.State.MSG_ARG,this.as=Z}break;case Hi1.State.MSG_ARG:switch(X){case Hi1.cc.CR:this.drop=1;break;case Hi1.cc.NL:{let Q=this.argBuf?this.argBuf.bytes():$.subarray(this.as,Z-this.drop);this.processMsgArgs(Q),this.drop=0,this.as=Z+1,this.state=Hi1.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;case Hi1.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let Q=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:Hi1.Kind.MSG,msg:this.ma,data:Q}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Hi1.State.MSG_END}else{let Q=this.ma.size-this.msgBuf.length,Y=$.length-Z;if(Y<Q)Q=Y;if(Q>0)this.msgBuf.write($.subarray(Z,Z+Q)),Z=Z+Q-1;else this.msgBuf.writeByte(X)}else if(Z-this.as>=this.ma.size)this.dispatcher.push({kind:Hi1.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Hi1.State.MSG_END;break;case Hi1.State.MSG_END:switch(X){case Hi1.cc.NL:this.drop=0,this.as=Z+1,this.state=Hi1.State.OP_START;break;default:continue}break;case Hi1.State.OP_PLUS:switch(X){case Hi1.cc.O:case Hi1.cc.o:this.state=Hi1.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_PLUS_O:switch(X){case Hi1.cc.K:case Hi1.cc.k:this.state=Hi1.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_PLUS_OK:switch(X){case Hi1.cc.NL:this.dispatcher.push({kind:Hi1.Kind.OK}),this.drop=0,this.state=Hi1.State.OP_START;break}break;case Hi1.State.OP_MINUS:switch(X){case Hi1.cc.E:case Hi1.cc.e:this.state=Hi1.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_MINUS_E:switch(X){case Hi1.cc.R:case Hi1.cc.r:this.state=Hi1.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_MINUS_ER:switch(X){case Hi1.cc.R:case Hi1.cc.r:this.state=Hi1.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_MINUS_ERR:switch(X){case Hi1.cc.SPACE:case Hi1.cc.TAB:this.state=Hi1.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_MINUS_ERR_SPC:switch(X){case Hi1.cc.SPACE:case Hi1.cc.TAB:continue;default:this.state=Hi1.State.MINUS_ERR_ARG,this.as=Z}break;case Hi1.State.MINUS_ERR_ARG:switch(X){case Hi1.cc.CR:this.drop=1;break;case Hi1.cc.NL:{let Q;if(this.argBuf)Q=this.argBuf.bytes(),this.argBuf=void 0;else Q=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:Hi1.Kind.ERR,data:Q}),this.drop=0,this.as=Z+1,this.state=Hi1.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(X))}break;case Hi1.State.OP_P:switch(X){case Hi1.cc.I:case Hi1.cc.i:this.state=Hi1.State.OP_PI;break;case Hi1.cc.O:case Hi1.cc.o:this.state=Hi1.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_PO:switch(X){case Hi1.cc.N:case Hi1.cc.n:this.state=Hi1.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_PON:switch(X){case Hi1.cc.G:case Hi1.cc.g:this.state=Hi1.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_PONG:switch(X){case Hi1.cc.NL:this.dispatcher.push({kind:Hi1.Kind.PONG}),this.drop=0,this.state=Hi1.State.OP_START;break}break;case Hi1.State.OP_PI:switch(X){case Hi1.cc.N:case Hi1.cc.n:this.state=Hi1.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_PIN:switch(X){case Hi1.cc.G:case Hi1.cc.g:this.state=Hi1.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_PING:switch(X){case Hi1.cc.NL:this.dispatcher.push({kind:Hi1.Kind.PING}),this.drop=0,this.state=Hi1.State.OP_START;break}break;case Hi1.State.OP_I:switch(X){case Hi1.cc.N:case Hi1.cc.n:this.state=Hi1.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_IN:switch(X){case Hi1.cc.F:case Hi1.cc.f:this.state=Hi1.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_INF:switch(X){case Hi1.cc.O:case Hi1.cc.o:this.state=Hi1.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_INFO:switch(X){case Hi1.cc.SPACE:case Hi1.cc.TAB:this.state=Hi1.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case Hi1.State.OP_INFO_SPC:switch(X){case Hi1.cc.SPACE:case Hi1.cc.TAB:continue;default:this.state=Hi1.State.INFO_ARG,this.as=Z}break;case Hi1.State.INFO_ARG:switch(X){case Hi1.cc.CR:this.drop=1;break;case Hi1.cc.NL:{let Q;if(this.argBuf)Q=this.argBuf.bytes(),this.argBuf=void 0;else Q=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:Hi1.Kind.INFO,data:Q}),this.drop=0,this.as=Z+1,this.state=Hi1.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;default:throw this.fail($.subarray(Z))}}if((this.state===Hi1.State.MSG_ARG||this.state===Hi1.State.MINUS_ERR_ARG||this.state===Hi1.State.INFO_ARG)&&!this.argBuf)this.argBuf=new El0.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===Hi1.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new El0.DenoBuffer($.subarray(this.as))}}cloneMsgArg(){let $=this.ma.subject.length,Z=this.ma.reply?this.ma.reply.length:0,X=new Uint8Array($+Z);if(X.set(this.ma.subject),this.ma.reply)X.set(this.ma.reply,$);if(this.argBuf=new El0.DenoBuffer(X),this.ma.subject=X.subarray(0,$),this.ma.reply)this.ma.reply=X.subarray($)}processMsgArgs($){if(this.hdr>=0)return this.processHeaderMsgArgs($);let Z=[],X=-1;for(let Q=0;Q<$.length;Q++)switch($[Q]){case Hi1.cc.SPACE:case Hi1.cc.TAB:case Hi1.cc.CR:case Hi1.cc.NL:if(X>=0)Z.push($.subarray(X,Q)),X=-1;break;default:if(X<0)X=Q}if(X>=0)Z.push($.subarray(X));switch(Z.length){case 3:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.size=this.protoParseInt(Z[2],Sf);break;case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.size=this.protoParseInt(Z[3],Sf);break;default:throw this.fail($,"processMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processMsgArgs Bad or Missing Sid Error");if(this.ma.size<0)throw this.fail($,"processMsgArgs Bad or Missing Size Error")}fail($,Z=""){if(!Z)Z=`parse error [${this.state}]`;else Z=`${Z} [${this.state}]`;return Error(`${Z}: ${zl0.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],X=-1;for(let Q=0;Q<$.length;Q++)switch($[Q]){case Hi1.cc.SPACE:case Hi1.cc.TAB:case Hi1.cc.CR:case Hi1.cc.NL:if(X>=0)Z.push($.subarray(X,Q)),X=-1;break;default:if(X<0)X=Q}if(X>=0)Z.push($.subarray(X));switch(Z.length){case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.hdr=this.protoParseInt(Z[2],Sf),this.ma.size=this.protoParseInt(Z[3],Sf);break;case 5:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.hdr=this.protoParseInt(Z[3],Sf),this.ma.size=this.protoParseInt(Z[4],Sf);break;default:throw this.fail($,"processHeaderMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Sid Error");if(this.ma.hdr<0||this.ma.hdr>this.ma.size)throw this.fail($,"processHeaderMsgArgs Bad or Missing Header Size Error");if(this.ma.size<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Size Error")}protoParseInt($,Z){if($.length===0||$.length>15)return-1;let X=0;for(let Q=0;Q<$.length;Q++){if($[Q]<Ki1||$[Q]>nh6)return-1;X=X*10+($[Q]-Ki1)}return Z!==void 0&&X>Z?-1:X}}Hi1.Parser=Wi1;Hi1.State={OP_START:0,OP_PLUS:1,OP_PLUS_O:2,OP_PLUS_OK:3,OP_MINUS:4,OP_MINUS_E:5,OP_MINUS_ER:6,OP_MINUS_ERR:7,OP_MINUS_ERR_SPC:8,MINUS_ERR_ARG:9,OP_M:10,OP_MS:11,OP_MSG:12,OP_MSG_SPC:13,MSG_ARG:14,MSG_PAYLOAD:15,MSG_END:16,OP_H:17,OP_P:18,OP_PI:19,OP_PIN:20,OP_PING:21,OP_PO:22,OP_PON:23,OP_PONG:24,OP_I:25,OP_IN:26,OP_INF:27,OP_INFO:28,OP_INFO_SPC:29,INFO_ARG:30};Hi1.cc={CR:13,E:69,e:101,F:70,f:102,G:71,g:103,H:72,h:104,I:73,i:105,K:75,k:107,M:77,m:109,MINUS:45,N:78,n:110,NL:10,O:79,o:111,P:80,p:112,PLUS:43,R:82,r:114,S:83,s:115,SPACE:32,TAB:9}});var k50=_((Ui1)=>{Object.defineProperty(Ui1,"__esModule",{value:!0});Ui1.MsgHdrsImpl=void 0;Ui1.canonicalMIMEHeaderKey=Al0;Ui1.headers=oh6;var Ni1=CY(),ZJ=pF(),M50=_Y();function Al0($){let N=!0,U=Array($.length);for(let F=0;F<$.length;F++){let w=$.charCodeAt(F);if(w===58||w<33||w>126)throw M50.InvalidArgumentError.format("header",`'${$[F]}' is not a valid character in a header name`);if(N&&97<=w&&w<=122)w-=32;else if(!N&&65<=w&&w<=90)w+=32;U[F]=w,N=w==45}return String.fromCharCode(...U)}function oh6($=0,Z=""){if($===0&&Z!=="")throw M50.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw M50.InvalidArgumentError.format("description","is required");return new Vf($,Z)}var Pl0="NATS/1.0";class Vf{_code;headers;_description;constructor($=0,Z=""){this._code=$,this._description=Z,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals($){if($&&this.headers.size===$.headers.size&&this._code===$._code){for(let[Z,X]of this.headers){let Q=$.values(Z);if(X.length!==Q.length)return!1;let Y=[...X].sort(),G=[...Q].sort();for(let J=0;J<Y.length;J++)if(Y[J]!==G[J])return!1}return!0}return!1}static decode($){let Z=new Vf,Q=Ni1.TD.decode($).split(`\r
|
|
1261
1261
|
`),Y=Q[0];if(Y!==Pl0){let G=Y.replace(Pl0,"").trim();if(G.length>0){if(Z._code=parseInt(G,10),isNaN(Z._code))Z._code=0;let J=Z._code.toString();G=G.replace(J,""),Z._description=G.trim()}}if(Q.length>=1)Q.slice(1).map((G)=>{if(G){let J=G.indexOf(":");if(J>-1){let K=G.slice(0,J),W=G.slice(J+1).trim();Z.append(K,W)}}});return Z}toString(){if(this.headers.size===0&&this._code===0)return"";let $=Pl0;if(this._code>0&&this._description!=="")$+=` ${this._code} ${this._description}`;for(let[Z,X]of this.headers)for(let Q=0;Q<X.length;Q++)$=`${$}\r
|
|
1262
1262
|
${Z}: ${X[Q]}`;return`${$}\r
|
|
@@ -1280,7 +1280,7 @@ ${K}`;N(D);return}if(J(null,E),X.strategy==="count"){if(W--,W===0)N()}if(X.strat
|
|
|
1280
1280
|
`}static header(){return`Test,Date,Lang,Version,Count,MsgPayload,Bytes,Millis,Async
|
|
1281
1281
|
`}}An1.Metric=rF;class zn1{nc;callbacks;msgs;size;subject;asyncRequests;pub;sub;req;rep;perf;payload;constructor($,Z={msgs:1e5,size:128,subject:"",asyncRequests:!1,pub:!1,sub:!1,req:!1,rep:!1}){if(this.nc=$,this.callbacks=Z.callbacks||!1,this.msgs=Z.msgs||0,this.size=Z.size||0,this.subject=Z.subject||kc6.nuid.next(),this.asyncRequests=Z.asyncRequests||!1,this.pub=Z.pub||!1,this.sub=Z.sub||!1,this.req=Z.req||!1,this.rep=Z.rep||!1,this.perf=new il0.Perf,this.payload=this.size?new Uint8Array(this.size):Mc6.Empty,!this.pub&&!this.sub&&!this.req&&!this.rep)throw Error("no options selected")}async run(){if(this.nc.closed().then(($)=>{if($)throw $}),this.callbacks)await this.runCallbacks();else await this.runAsync();return this.processMetrics()}processMetrics(){let $=this.nc,{lang:Z,version:X}=$.protocol.transport;if(this.pub&&this.sub)this.perf.measure("pubsub","pubStart","subStop");if(this.req&&this.rep)this.perf.measure("reqrep","reqStart","reqStop");let Q=this.perf.getEntries(),Y=Q.find((F)=>F.name==="pubsub"),G=Q.find((F)=>F.name==="reqrep"),J=Q.find((F)=>F.name==="req"),K=Q.find((F)=>F.name==="rep"),W=Q.find((F)=>F.name==="pub"),H=Q.find((F)=>F.name==="sub"),N=this.nc.stats(),U=[];if(Y){let{name:F,duration:w}=Y,B=new rF(F,w);B.msgs=this.msgs*2,B.bytes=N.inBytes+N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(G){let{name:F,duration:w}=G,B=new rF(F,w);B.msgs=this.msgs*2,B.bytes=N.inBytes+N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(W){let{name:F,duration:w}=W,B=new rF(F,w);B.msgs=this.msgs,B.bytes=N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(H){let{name:F,duration:w}=H,B=new rF(F,w);B.msgs=this.msgs,B.bytes=N.inBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(K){let{name:F,duration:w}=K,B=new rF(F,w);B.msgs=this.msgs,B.bytes=N.inBytes+N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(J){let{name:F,duration:w}=J,B=new rF(F,w);B.msgs=this.msgs,B.bytes=N.inBytes+N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}return U}async runCallbacks(){let $=[];if(this.sub){let Z=(0,il0.deferred)();$.push(Z);let X=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:()=>{if(X++,X===1)this.perf.mark("subStart");if(X===this.msgs)this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop"),Z.resolve()}})}if(this.rep){let Z=(0,il0.deferred)();$.push(Z);let X=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:(Q,Y)=>{if(Y.respond(this.payload),X++,X===1)this.perf.mark("repStart");if(X===this.msgs)this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop"),Z.resolve()}})}if(this.pub){let Z=(async()=>{this.perf.mark("pubStart");for(let X=0;X<this.msgs;X++)this.nc.publish(this.subject,this.payload);await this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")})();$.push(Z)}if(this.req){let Z=(async()=>{if(this.asyncRequests){this.perf.mark("reqStart");let X=[];for(let Q=0;Q<this.msgs;Q++)X.push(this.nc.request(this.subject,this.payload,{timeout:20000}));await Promise.all(X),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let X=0;X<this.msgs;X++)await this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}})();$.push(Z)}await Promise.all($)}async runAsync(){let $=[];if(this.rep){let Z=!1,X=this.nc.subscribe(this.subject,{max:this.msgs}),Q=(async()=>{for await(let Y of X){if(!Z)this.perf.mark("repStart"),Z=!0;Y.respond(this.payload)}await this.nc.flush(),this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop")})();$.push(Q)}if(this.sub){let Z=!1,X=this.nc.subscribe(this.subject,{max:this.msgs}),Q=(async()=>{for await(let Y of X)if(!Z)this.perf.mark("subStart"),Z=!0;this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop")})();$.push(Q)}if(this.pub){let Z=(async()=>{this.perf.mark("pubStart");for(let X=0;X<this.msgs;X++)this.nc.publish(this.subject,this.payload);await this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")})();$.push(Z)}if(this.req){let Z=(async()=>{if(this.asyncRequests){this.perf.mark("reqStart");let X=[];for(let Q=0;Q<this.msgs;Q++)X.push(this.nc.request(this.subject,this.payload,{timeout:20000}));await Promise.all(X),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let X=0;X<this.msgs;X++)await this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}})();$.push(Z)}await Promise.all($)}}An1.Bench=zn1;function jn1($,Z){return`${Pn1($/Z)}/sec`}function Sc6($,Z){return`${Math.floor($/Z)} msgs/sec`}function Pn1($,Z=!1){let X=Z?1000:1024,Q=Z?["k","M","G","T","P","E"]:["K","M","G","T","P","E"],Y=Z?"iB":"B";if($<X)return`${$.toFixed(2)} ${Y}`;let G=parseInt(Math.log($)/Math.log(X)+""),J=parseInt(G-1+"");return`${($/Math.pow(X,G)).toFixed(2)} ${Q[J]}${Y}`}function Vc6($){return $.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}});var kn1=_((qn1)=>{Object.defineProperty(qn1,"__esModule",{value:!0});qn1.IdleHeartbeatMonitor=void 0;class Rn1{interval;maxOut;cancelAfter;timer;autoCancelTimer;last;missed;count;callback;constructor($,Z,X={maxOut:2}){this.interval=$,this.maxOut=X?.maxOut||2,this.cancelAfter=X?.cancelAfter||0,this.last=Date.now(),this.missed=0,this.count=0,this.callback=Z,this._schedule()}cancel(){if(this.autoCancelTimer)clearTimeout(this.autoCancelTimer);if(this.timer)clearInterval(this.timer);this.timer=0,this.autoCancelTimer=0,this.missed=0}work(){this.last=Date.now(),this.missed=0}_change($,Z=0,X=2){this.interval=$,this.maxOut=X,this.cancelAfter=Z,this.restart()}restart(){this.cancel(),this._schedule()}_schedule(){if(this.cancelAfter>0)this.autoCancelTimer=setTimeout(()=>{this.cancel()},this.cancelAfter);this.timer=setInterval(()=>{if(this.count++,Date.now()-this.last>this.interval)this.missed++;if(this.missed>=this.maxOut)try{if(this.callback(this.missed)===!0)this.cancel()}catch($){console.log($)}},this.interval)}}qn1.IdleHeartbeatMonitor=Rn1});var Cn1=_((Sn1)=>{Object.defineProperty(Sn1,"__esModule",{value:!0});Sn1.version=void 0;Sn1.version="3.4.0"});var yn1=_((fn1)=>{Object.defineProperty(fn1,"__esModule",{value:!0});fn1.WsTransport=void 0;fn1.wsUrlParseFn=vn1;fn1.wsconnect=lc6;var WN=$J(),_n1=zD(),fc6=Wm(),bc6=$m(),yc6=Hm(),gc6=ll0(),hc6=Cn1(),xn1=_Y(),uc6=hc6.version,cc6="nats.ws";class nl0{version;lang;closeError;connected;done;socket;options;socketClosed;encrypted;peeked;yields;signal;closedNotification;constructor(){this.version=uc6,this.lang=cc6,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=(0,WN.deferred)(),this.closedNotification=(0,WN.deferred)()}async connect($,Z){let Q=(0,WN.deferred)();this.options=Z;let Y=$.src;if(Z.wsFactory){let{socket:G,encrypted:J}=await Z.wsFactory($.src,Z);this.socket=G,this.encrypted=J}else this.encrypted=Y.indexOf("wss://")===0,this.socket=new WebSocket(Y);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{if(this.done)this._closed(Error("aborted"))},this.socket.onmessage=(G)=>{if(this.done)return;if(this.yields.push(new Uint8Array(G.data)),this.peeked){this.signal.resolve();return}let J=bc6.DataBuffer.concat(...this.yields),K=(0,_n1.extractProtocolMessage)(J);if(K!==""){let W=yc6.INFO.exec(K);if(!W){if(Z.debug)console.error("!!!",(0,WN.render)(J));Q.reject(Error("unexpected response from server"));return}try{let H=JSON.parse(W[1]);(0,fc6.checkOptions)(H,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),Q.resolve()}catch(H){Q.reject(H);return}}},this.socket.onclose=(G)=>{let J;if(!G.wasClean&&G.reason!=="")J=Error(G.reason);this._closed(J),this._cleanup()},this.socket.onerror=(G)=>{if(this.done)return;let J=G,K=new xn1.errors.ConnectionError(J.message);Q.reject(K),this._cleanup()},Q}_cleanup(){if(this.socketClosed===!1)this.socketClosed=!0,this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.closedNotification.resolve(this.closeError)}disconnect(){this._closed(void 0,!0)}async _closed($,Z=!0){if(this.done){try{this.socket.close()}catch(X){}return}if(this.closeError=$,!$)while(!this.socketClosed&&this.socket.bufferedAmount>0)await(0,WN.delay)(100);this.done=!0;try{this.socket.close()}catch(X){}return this.closedNotification}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.done)return;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,WN.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,WN.deferred)()}}isEncrypted(){return this.connected&&this.encrypted}send($){if(this.done)return;try{if(this.socket.send($.buffer),this.options.debug)console.info(`< ${(0,WN.render)($)}`);return}catch(Z){if(this.options.debug)console.error(`!!! ${(0,WN.render)($)}: ${Z}`)}}close($){return this._closed($,!1)}closed(){return this.closedNotification}discard(){this.socket?.close()}}fn1.WsTransport=nl0;function vn1($,Z){if(!/^(.*:\/\/)(.*)/.test($))if(typeof Z==="boolean")$=`${Z===!0?"https":"http"}://${$}`;else $=`https://${$}`;let Q=new URL($),Y=Q.protocol.toLowerCase();if(Y==="ws:")Z=!1;if(Y==="wss:")Z=!0;if(Y!=="https:"&&Y!=="http")$=$.replace(/^(.*:\/\/)(.*)/gm,"$2"),Q=new URL(`http://${$}`);let G,J,K=Q.hostname,W=Q.pathname,H=Q.search||"";switch(Y){case"http:":case"ws:":case"nats:":J=Q.port||"80",G="ws:";break;case"https:":case"wss:":case"tls:":J=Q.port||"443",G="wss:";break;default:J=Q.port||Z===!0?"443":"80",G=Z===!0?"wss:":"ws:";break}return`${G}//${K}:${J}${W}${H}`}function lc6($={}){return(0,_n1.setTransportFactory)({defaultPort:443,urlParseFn:vn1,factory:()=>{if($.tls)throw xn1.InvalidArgumentError.format("tls","is not configurable on w3c websocket connections");return new nl0}}),gc6.NatsConnectionImpl.connect($)}});var vY=_((b0)=>{var ic6=b0&&b0.__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]}),nc6=b0&&b0.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))ic6(Z,$,X)};Object.defineProperty(b0,"__esModule",{value:!0});b0.Metric=b0.Bench=b0.writeAll=b0.readAll=b0.MAX_SIZE=b0.DenoBuffer=b0.State=b0.Parser=b0.Kind=b0.describe=b0.QueuedIteratorImpl=b0.usernamePasswordAuthenticator=b0.tokenAuthenticator=b0.nkeyAuthenticator=b0.jwtAuthenticator=b0.credsAuthenticator=b0.RequestOne=b0.parseOptions=b0.hasWsProtocol=b0.defaultOptions=b0.DEFAULT_MAX_RECONNECT_ATTEMPTS=b0.checkUnsupportedOption=b0.checkOptions=b0.buildAuthenticator=b0.DataBuffer=b0.MuxSubscription=b0.Heartbeat=b0.MsgHdrsImpl=b0.headers=b0.canonicalMIMEHeaderKey=b0.timeout=b0.SimpleMutex=b0.render=b0.nanos=b0.millis=b0.extend=b0.delay=b0.deferred=b0.deadline=b0.collect=b0.backoff=b0.ProtocolHandler=b0.INFO=b0.Connect=b0.setTransportFactory=b0.getResolveFn=b0.MsgImpl=b0.nuid=b0.Nuid=b0.NatsConnectionImpl=void 0;b0.UserAuthenticationExpiredError=b0.TimeoutError=b0.RequestError=b0.ProtocolError=b0.PermissionViolationError=b0.NoRespondersError=b0.InvalidSubjectError=b0.InvalidOperationError=b0.InvalidArgumentError=b0.errors=b0.DrainingConnectionError=b0.ConnectionError=b0.ClosedConnectionError=b0.AuthorizationError=b0.wsUrlParseFn=b0.wsconnect=b0.Servers=b0.isIPV4OrHostname=b0.IdleHeartbeatMonitor=b0.Subscriptions=b0.SubscriptionImpl=b0.syncIterator=b0.Match=b0.createInbox=b0.protoLen=b0.extractProtocolMessage=b0.Empty=b0.parseSemVer=b0.Features=b0.Feature=b0.compare=b0.parseIP=b0.isIP=b0.ipV4=b0.TE=b0.TD=void 0;var pc6=ll0();Object.defineProperty(b0,"NatsConnectionImpl",{enumerable:!0,get:function(){return pc6.NatsConnectionImpl}});var gn1=P50();Object.defineProperty(b0,"Nuid",{enumerable:!0,get:function(){return gn1.Nuid}});Object.defineProperty(b0,"nuid",{enumerable:!0,get:function(){return gn1.nuid}});var tc6=Tl0();Object.defineProperty(b0,"MsgImpl",{enumerable:!0,get:function(){return tc6.MsgImpl}});var hn1=zD();Object.defineProperty(b0,"getResolveFn",{enumerable:!0,get:function(){return hn1.getResolveFn}});Object.defineProperty(b0,"setTransportFactory",{enumerable:!0,get:function(){return hn1.setTransportFactory}});var pl0=Hm();Object.defineProperty(b0,"Connect",{enumerable:!0,get:function(){return pl0.Connect}});Object.defineProperty(b0,"INFO",{enumerable:!0,get:function(){return pl0.INFO}});Object.defineProperty(b0,"ProtocolHandler",{enumerable:!0,get:function(){return pl0.ProtocolHandler}});var QJ=$J();Object.defineProperty(b0,"backoff",{enumerable:!0,get:function(){return QJ.backoff}});Object.defineProperty(b0,"collect",{enumerable:!0,get:function(){return QJ.collect}});Object.defineProperty(b0,"deadline",{enumerable:!0,get:function(){return QJ.deadline}});Object.defineProperty(b0,"deferred",{enumerable:!0,get:function(){return QJ.deferred}});Object.defineProperty(b0,"delay",{enumerable:!0,get:function(){return QJ.delay}});Object.defineProperty(b0,"extend",{enumerable:!0,get:function(){return QJ.extend}});Object.defineProperty(b0,"millis",{enumerable:!0,get:function(){return QJ.millis}});Object.defineProperty(b0,"nanos",{enumerable:!0,get:function(){return QJ.nanos}});Object.defineProperty(b0,"render",{enumerable:!0,get:function(){return QJ.render}});Object.defineProperty(b0,"SimpleMutex",{enumerable:!0,get:function(){return QJ.SimpleMutex}});Object.defineProperty(b0,"timeout",{enumerable:!0,get:function(){return QJ.timeout}});var tl0=k50();Object.defineProperty(b0,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return tl0.canonicalMIMEHeaderKey}});Object.defineProperty(b0,"headers",{enumerable:!0,get:function(){return tl0.headers}});Object.defineProperty(b0,"MsgHdrsImpl",{enumerable:!0,get:function(){return tl0.MsgHdrsImpl}});var oc6=Bl0();Object.defineProperty(b0,"Heartbeat",{enumerable:!0,get:function(){return oc6.Heartbeat}});var rc6=wl0();Object.defineProperty(b0,"MuxSubscription",{enumerable:!0,get:function(){return rc6.MuxSubscription}});var ac6=$m();Object.defineProperty(b0,"DataBuffer",{enumerable:!0,get:function(){return ac6.DataBuffer}});var RD=Wm();Object.defineProperty(b0,"buildAuthenticator",{enumerable:!0,get:function(){return RD.buildAuthenticator}});Object.defineProperty(b0,"checkOptions",{enumerable:!0,get:function(){return RD.checkOptions}});Object.defineProperty(b0,"checkUnsupportedOption",{enumerable:!0,get:function(){return RD.checkUnsupportedOption}});Object.defineProperty(b0,"DEFAULT_MAX_RECONNECT_ATTEMPTS",{enumerable:!0,get:function(){return RD.DEFAULT_MAX_RECONNECT_ATTEMPTS}});Object.defineProperty(b0,"defaultOptions",{enumerable:!0,get:function(){return RD.defaultOptions}});Object.defineProperty(b0,"hasWsProtocol",{enumerable:!0,get:function(){return RD.hasWsProtocol}});Object.defineProperty(b0,"parseOptions",{enumerable:!0,get:function(){return RD.parseOptions}});var sc6=ul0();Object.defineProperty(b0,"RequestOne",{enumerable:!0,get:function(){return sc6.RequestOne}});var Nm=_l0();Object.defineProperty(b0,"credsAuthenticator",{enumerable:!0,get:function(){return Nm.credsAuthenticator}});Object.defineProperty(b0,"jwtAuthenticator",{enumerable:!0,get:function(){return Nm.jwtAuthenticator}});Object.defineProperty(b0,"nkeyAuthenticator",{enumerable:!0,get:function(){return Nm.nkeyAuthenticator}});Object.defineProperty(b0,"tokenAuthenticator",{enumerable:!0,get:function(){return Nm.tokenAuthenticator}});Object.defineProperty(b0,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return Nm.usernamePasswordAuthenticator}});nc6(Vl0(),b0);var ec6=I50();Object.defineProperty(b0,"QueuedIteratorImpl",{enumerable:!0,get:function(){return ec6.QueuedIteratorImpl}});var m50=jl0();Object.defineProperty(b0,"describe",{enumerable:!0,get:function(){return m50.describe}});Object.defineProperty(b0,"Kind",{enumerable:!0,get:function(){return m50.Kind}});Object.defineProperty(b0,"Parser",{enumerable:!0,get:function(){return m50.Parser}});Object.defineProperty(b0,"State",{enumerable:!0,get:function(){return m50.State}});var i50=Dl0();Object.defineProperty(b0,"DenoBuffer",{enumerable:!0,get:function(){return i50.DenoBuffer}});Object.defineProperty(b0,"MAX_SIZE",{enumerable:!0,get:function(){return i50.MAX_SIZE}});Object.defineProperty(b0,"readAll",{enumerable:!0,get:function(){return i50.readAll}});Object.defineProperty(b0,"writeAll",{enumerable:!0,get:function(){return i50.writeAll}});var un1=In1();Object.defineProperty(b0,"Bench",{enumerable:!0,get:function(){return un1.Bench}});Object.defineProperty(b0,"Metric",{enumerable:!0,get:function(){return un1.Metric}});var cn1=CY();Object.defineProperty(b0,"TD",{enumerable:!0,get:function(){return cn1.TD}});Object.defineProperty(b0,"TE",{enumerable:!0,get:function(){return cn1.TE}});var ol0=Gl0();Object.defineProperty(b0,"ipV4",{enumerable:!0,get:function(){return ol0.ipV4}});Object.defineProperty(b0,"isIP",{enumerable:!0,get:function(){return ol0.isIP}});Object.defineProperty(b0,"parseIP",{enumerable:!0,get:function(){return ol0.parseIP}});var n50=C50();Object.defineProperty(b0,"compare",{enumerable:!0,get:function(){return n50.compare}});Object.defineProperty(b0,"Feature",{enumerable:!0,get:function(){return n50.Feature}});Object.defineProperty(b0,"Features",{enumerable:!0,get:function(){return n50.Features}});Object.defineProperty(b0,"parseSemVer",{enumerable:!0,get:function(){return n50.parseSemVer}});var $l6=ml0();Object.defineProperty(b0,"Empty",{enumerable:!0,get:function(){return $l6.Empty}});var ln1=zD();Object.defineProperty(b0,"extractProtocolMessage",{enumerable:!0,get:function(){return ln1.extractProtocolMessage}});Object.defineProperty(b0,"protoLen",{enumerable:!0,get:function(){return ln1.protoLen}});var rl0=pF();Object.defineProperty(b0,"createInbox",{enumerable:!0,get:function(){return rl0.createInbox}});Object.defineProperty(b0,"Match",{enumerable:!0,get:function(){return rl0.Match}});Object.defineProperty(b0,"syncIterator",{enumerable:!0,get:function(){return rl0.syncIterator}});var dn1=Hm();Object.defineProperty(b0,"SubscriptionImpl",{enumerable:!0,get:function(){return dn1.SubscriptionImpl}});Object.defineProperty(b0,"Subscriptions",{enumerable:!0,get:function(){return dn1.Subscriptions}});var Zl6=kn1();Object.defineProperty(b0,"IdleHeartbeatMonitor",{enumerable:!0,get:function(){return Zl6.IdleHeartbeatMonitor}});var mn1=Ul0();Object.defineProperty(b0,"isIPV4OrHostname",{enumerable:!0,get:function(){return mn1.isIPV4OrHostname}});Object.defineProperty(b0,"Servers",{enumerable:!0,get:function(){return mn1.Servers}});var in1=yn1();Object.defineProperty(b0,"wsconnect",{enumerable:!0,get:function(){return in1.wsconnect}});Object.defineProperty(b0,"wsUrlParseFn",{enumerable:!0,get:function(){return in1.wsUrlParseFn}});var qQ=_Y();Object.defineProperty(b0,"AuthorizationError",{enumerable:!0,get:function(){return qQ.AuthorizationError}});Object.defineProperty(b0,"ClosedConnectionError",{enumerable:!0,get:function(){return qQ.ClosedConnectionError}});Object.defineProperty(b0,"ConnectionError",{enumerable:!0,get:function(){return qQ.ConnectionError}});Object.defineProperty(b0,"DrainingConnectionError",{enumerable:!0,get:function(){return qQ.DrainingConnectionError}});Object.defineProperty(b0,"errors",{enumerable:!0,get:function(){return qQ.errors}});Object.defineProperty(b0,"InvalidArgumentError",{enumerable:!0,get:function(){return qQ.InvalidArgumentError}});Object.defineProperty(b0,"InvalidOperationError",{enumerable:!0,get:function(){return qQ.InvalidOperationError}});Object.defineProperty(b0,"InvalidSubjectError",{enumerable:!0,get:function(){return qQ.InvalidSubjectError}});Object.defineProperty(b0,"NoRespondersError",{enumerable:!0,get:function(){return qQ.NoRespondersError}});Object.defineProperty(b0,"PermissionViolationError",{enumerable:!0,get:function(){return qQ.PermissionViolationError}});Object.defineProperty(b0,"ProtocolError",{enumerable:!0,get:function(){return qQ.ProtocolError}});Object.defineProperty(b0,"RequestError",{enumerable:!0,get:function(){return qQ.RequestError}});Object.defineProperty(b0,"TimeoutError",{enumerable:!0,get:function(){return qQ.TimeoutError}});Object.defineProperty(b0,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return qQ.UserAuthenticationExpiredError}})});var HN=_((pn1)=>{Object.defineProperty(pn1,"__esModule",{value:!0});pn1.jserrors=pn1.StreamNotFoundError=pn1.ConsumerNotFoundError=pn1.JetStreamApiError=pn1.InvalidNameError=pn1.JetStreamApiCodes=pn1.JetStreamStatus=pn1.JetStreamStatusError=pn1.JetStreamError=pn1.JetStreamNotEnabled=void 0;pn1.isMessageNotFound=Xl6;var nn1=ED();class al0 extends Error{constructor($,Z){super($,Z);this.name="JetStreamNotEnabled"}}pn1.JetStreamNotEnabled=al0;class p50 extends Error{constructor($,Z){super($,Z);this.name="JetStreamError"}}pn1.JetStreamError=p50;class sl0 extends p50{code;constructor($,Z,X){super($,X);this.code=Z,this.name="JetStreamStatusError"}}pn1.JetStreamStatusError=sl0;class el0{msg;_description;constructor($){this.msg=$,this._description=""}static maybeParseStatus($){let Z=new el0($);return Z.code===0?null:Z}toError(){return new sl0(this.description,this.code)}debug(){console.log({subject:this.msg.subject,reply:this.msg.reply,description:this.description,status:this.code,headers:this.msg.headers})}get code(){return this.msg.headers?.code||0}get description(){if(this._description===""){if(this._description=this.msg.headers?.description?.toLowerCase()||"",this._description==="")this._description=this.code===503?"no responders":"unknown"}return this._description}isIdleHeartbeat(){return this.code===100&&this.description==="idle heartbeat"}isFlowControlRequest(){return this.code===100&&this.description==="flowcontrol request"}parseHeartbeat(){if(this.isIdleHeartbeat())return{type:"heartbeat",lastConsumerSequence:parseInt(this.msg.headers?.get("Nats-Last-Consumer")||"0"),lastStreamSequence:parseInt(this.msg.headers?.get("Nats-Last-Stream")||"0")};return null}isRequestTimeout(){return this.code===408&&this.description==="request timeout"}parseDiscard(){let $={msgsLeft:0,bytesLeft:0},Z=this.msg.headers?.get(nn1.JsHeaders.PendingMessagesHdr);if(Z)$.msgsLeft=parseInt(Z);let X=this.msg.headers?.get(nn1.JsHeaders.PendingBytesHdr);if(X)$.bytesLeft=parseInt(X);return $}isBadRequest(){return this.code===400}isConsumerDeleted(){return this.code===409&&this.description==="consumer deleted"}isStreamDeleted(){return this.code===409&&this.description==="stream deleted"}isIdleHeartbeatMissed(){return this.code===409&&this.description==="idle heartbeats missed"}isMaxWaitingExceeded(){return this.code===409&&this.description==="exceeded maxwaiting"}isConsumerIsPushBased(){return this.code===409&&this.description==="consumer is push based"}isExceededMaxWaiting(){return this.code===409&&this.description.includes("exceeded maxwaiting")}isExceededMaxRequestBatch(){return this.code===409&&this.description.includes("exceeded maxrequestbatch")}isExceededMaxExpires(){return this.code===409&&this.description.includes("exceeded maxrequestexpires")}isExceededLimit(){return this.isExceededMaxExpires()||this.isExceededMaxWaiting()||this.isExceededMaxRequestBatch()||this.isMessageSizeExceedsMaxBytes()}isMessageNotFound(){return this.code===404&&this.description==="message not found"}isNoResults(){return this.code===404&&this.description==="no results"}isMessageSizeExceedsMaxBytes(){return this.code===409&&this.description==="message size exceeds maxbytes"}isEndOfBatch(){return this.code===204&&this.description==="eob"}}pn1.JetStreamStatus=el0;pn1.JetStreamApiCodes={ConsumerNotFound:10014,StreamNotFound:10059,JetStreamNotEnabledForAccount:10039,StreamWrongLastSequence:10071,StreamWrongLastSequenceUnknown:10164,NoMessageFound:10037};function Xl6($){return $ instanceof vf&&$.code===pn1.JetStreamApiCodes.NoMessageFound}class $d0 extends Error{constructor($="",Z){super($,Z);this.name="InvalidNameError"}}pn1.InvalidNameError=$d0;class vf extends Error{#$;constructor($,Z){super($.description,Z);this.#$=$,this.name="JetStreamApiError"}get code(){return this.#$.err_code}get status(){return this.#$.code}apiError(){return Object.assign({},this.#$)}}pn1.JetStreamApiError=vf;class Zd0 extends vf{constructor($,Z){super($,Z);this.name="ConsumerNotFoundError"}}pn1.ConsumerNotFoundError=Zd0;class t50 extends vf{constructor($,Z){super($,Z);this.name="StreamNotFoundError"}static fromMessage($){return new t50({err_code:pn1.JetStreamApiCodes.StreamNotFound,description:$,code:404})}}pn1.StreamNotFoundError=t50;pn1.jserrors={InvalidNameError:$d0,ConsumerNotFoundError:Zd0,StreamNotFoundError:t50,JetStreamError:p50,JetStreamApiError:vf,JetStreamNotEnabled:al0}});var ff=_((sn1)=>{Object.defineProperty(sn1,"__esModule",{value:!0});sn1.BaseApiClientImpl=void 0;sn1.parseJsResponse=on1;sn1.defaultJsOptions=rn1;var NN=vY(),Fl6=ED(),iK=HN(),wl6="$JS.API",Bl6=5000;function on1($){let Z=JSON.parse(new TextDecoder().decode($.data)),X=Z;if(X.error)switch(X.error.err_code){case iK.JetStreamApiCodes.ConsumerNotFound:throw new iK.ConsumerNotFoundError(X.error);case iK.JetStreamApiCodes.StreamNotFound:throw new iK.StreamNotFoundError(X.error);case iK.JetStreamApiCodes.JetStreamNotEnabledForAccount:{let Q=new iK.JetStreamApiError(X.error);throw new iK.JetStreamNotEnabled(Q.message,{cause:Q})}default:throw new iK.JetStreamApiError(X.error)}return Z}function rn1($){if($=$||{},$.domain)$.apiPrefix=`$JS.${$.domain}.API`,delete $.domain;return(0,NN.extend)({apiPrefix:wl6,timeout:Bl6},$)}class an1{nc;opts;prefix;timeout;constructor($,Z){this.nc=$,Z=Z||{},Z.watcherPrefix=Z.watcherPrefix||this.nc.options.inboxPrefix,this.opts=rn1(Z),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout}getOptions(){return Object.assign({},this.opts)}sendRequiredApiLevel(){return this.opts.sendRequiredApiLevel===!0}_parseOpts(){let $=this.opts.apiPrefix;if(!$||$.length===0)throw NN.errors.InvalidArgumentError.format("prefix","cannot be empty");if($[$.length-1]===".")$=$.substr(0,$.length-1);this.opts.apiPrefix=$,(0,NN.createInbox)(this.opts.watcherPrefix)}async _request($,Z=null,X){let{retries:Q,minApiVersion:Y,...G}=X??{},J={...G,timeout:this.timeout},K=NN.Empty;if(Z)K=new TextEncoder().encode(JSON.stringify(Z));if(typeof Y==="number"){let N=J.headers??(0,NN.headers)();N.set(Fl6.JsHeaders.RequiredApiLevel,Y.toString()),J.headers=N}let W=Q||1;W=W===-1?Number.MAX_SAFE_INTEGER:W;let H=(0,NN.backoff)();for(let N=0;N<W;N++)try{let U=await this.nc.request($,K,J);return this.parseJsResponse(U)}catch(U){let F=U instanceof NN.RequestError?U:null;if((U instanceof NN.errors.TimeoutError||F?.isNoResponders())&&N+1<W)await(0,NN.delay)(H.backoff(N));else throw F?.isNoResponders()?new iK.JetStreamNotEnabled("jetstream is not enabled",{cause:U}):U}}async findStream($){let Z={subject:$},Q=await this._request(`${this.prefix}.STREAM.NAMES`,Z);if(!Q.streams||Q.streams.length!==1)throw iK.StreamNotFoundError.fromMessage("no stream matches subject");return Q.streams[0]}getConnection(){return this.nc}parseJsResponse($){return on1($)}}sn1.BaseApiClientImpl=an1});var o50=_((Zp1)=>{Object.defineProperty(Zp1,"__esModule",{value:!0});Zp1.ListerImpl=void 0;var Dl6=vY();class $p1{err;offset;pageInfo;subject;jsm;filter;payload;constructor($,Z,X,Q){if(!$)throw Dl6.errors.InvalidArgumentError.format("subject","is required");this.subject=$,this.jsm=X,this.offset=0,this.pageInfo={},this.filter=Z,this.payload=Q||{}}async next(){if(this.err)return[];if(this.pageInfo&&this.offset>=this.pageInfo.total)return[];let $={offset:this.offset};if(this.payload)Object.assign($,this.payload);try{let Z=await this.jsm._request(this.subject,$,{timeout:this.jsm.timeout});this.pageInfo=Z;let X=this.countResponse(Z);if(X===0)return[];return this.offset+=X,this.filter(Z)}catch(Z){throw this.err=Z,Z}}countResponse($){switch($?.type){case"io.nats.jetstream.api.v1.stream_names_response":case"io.nats.jetstream.api.v1.stream_list_response":return $.streams?.length||0;case"io.nats.jetstream.api.v1.consumer_list_response":return $.consumers?.length||0;default:return console.error(`jslister.ts: unknown API response for paged output: ${$?.type}`),$.streams?.length||0}}async*[Symbol.asyncIterator](){let $=await this.next();while($.length>0){for(let Z of $)yield Z;$=await this.next()}}}Zp1.ListerImpl=$p1});var bf=_((Yp1)=>{Object.defineProperty(Yp1,"__esModule",{value:!0});Yp1.validateDurableName=zl6;Yp1.validateStreamName=jl6;Yp1.minValidation=Qd0;Yp1.validateName=Pl6;Yp1.validName=Qp1;var El6=HN();function zl6($){return Qd0("durable",$)}function jl6($){return Qd0("stream",$)}function Qd0($,Z=""){if(Z==="")throw Error(`${$} name required`);return[".","*",">","/","\\"," ","\t",`
|
|
1282
1282
|
`,"\r"].forEach((Q)=>{if(Z.indexOf(Q)!==-1){switch(Q){case`
|
|
1283
|
-
`:Q="\\n";break;case"\r":Q="\\r";break;case"\t":Q="\\t";break;default:}throw new El6.InvalidNameError(`${$} name ('${Z}') cannot contain '${Q}'`)}}),""}function Pl6($,Z=""){if(Z==="")throw Error(`${$} name required`);let X=Qp1(Z);if(X.length)throw Error(`invalid ${$} name - ${$} name ${X}`)}function Qp1($=""){if($==="")throw Error("name required");let Z=/^[-\w]+$/g;if($.match(Z)===null){for(let Q of $.split(""))if(Q.match(Z)===null)return`cannot contain '${Q}'`}return""}});var Um=_((E6)=>{Object.defineProperty(E6,"__esModule",{value:!0});E6.wsconnect=E6.usernamePasswordAuthenticator=E6.UserAuthenticationExpiredError=E6.tokenAuthenticator=E6.TimeoutError=E6.syncIterator=E6.RequestError=E6.ProtocolError=E6.PermissionViolationError=E6.nuid=E6.Nuid=E6.NoRespondersError=E6.nkeys=E6.nkeyAuthenticator=E6.nanos=E6.MsgHdrsImpl=E6.millis=E6.Metric=E6.Match=E6.jwtAuthenticator=E6.InvalidSubjectError=E6.InvalidOperationError=E6.InvalidArgumentError=E6.headers=E6.hasWsProtocol=E6.errors=E6.Empty=E6.DrainingConnectionError=E6.delay=E6.deferred=E6.deadline=E6.credsAuthenticator=E6.createInbox=E6.ConnectionError=E6.ClosedConnectionError=E6.canonicalMIMEHeaderKey=E6.buildAuthenticator=E6.Bench=E6.backoff=E6.AuthorizationError=void 0;var f6=vY();Object.defineProperty(E6,"AuthorizationError",{enumerable:!0,get:function(){return f6.AuthorizationError}});Object.defineProperty(E6,"backoff",{enumerable:!0,get:function(){return f6.backoff}});Object.defineProperty(E6,"Bench",{enumerable:!0,get:function(){return f6.Bench}});Object.defineProperty(E6,"buildAuthenticator",{enumerable:!0,get:function(){return f6.buildAuthenticator}});Object.defineProperty(E6,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return f6.canonicalMIMEHeaderKey}});Object.defineProperty(E6,"ClosedConnectionError",{enumerable:!0,get:function(){return f6.ClosedConnectionError}});Object.defineProperty(E6,"ConnectionError",{enumerable:!0,get:function(){return f6.ConnectionError}});Object.defineProperty(E6,"createInbox",{enumerable:!0,get:function(){return f6.createInbox}});Object.defineProperty(E6,"credsAuthenticator",{enumerable:!0,get:function(){return f6.credsAuthenticator}});Object.defineProperty(E6,"deadline",{enumerable:!0,get:function(){return f6.deadline}});Object.defineProperty(E6,"deferred",{enumerable:!0,get:function(){return f6.deferred}});Object.defineProperty(E6,"delay",{enumerable:!0,get:function(){return f6.delay}});Object.defineProperty(E6,"DrainingConnectionError",{enumerable:!0,get:function(){return f6.DrainingConnectionError}});Object.defineProperty(E6,"Empty",{enumerable:!0,get:function(){return f6.Empty}});Object.defineProperty(E6,"errors",{enumerable:!0,get:function(){return f6.errors}});Object.defineProperty(E6,"hasWsProtocol",{enumerable:!0,get:function(){return f6.hasWsProtocol}});Object.defineProperty(E6,"headers",{enumerable:!0,get:function(){return f6.headers}});Object.defineProperty(E6,"InvalidArgumentError",{enumerable:!0,get:function(){return f6.InvalidArgumentError}});Object.defineProperty(E6,"InvalidOperationError",{enumerable:!0,get:function(){return f6.InvalidOperationError}});Object.defineProperty(E6,"InvalidSubjectError",{enumerable:!0,get:function(){return f6.InvalidSubjectError}});Object.defineProperty(E6,"jwtAuthenticator",{enumerable:!0,get:function(){return f6.jwtAuthenticator}});Object.defineProperty(E6,"Match",{enumerable:!0,get:function(){return f6.Match}});Object.defineProperty(E6,"Metric",{enumerable:!0,get:function(){return f6.Metric}});Object.defineProperty(E6,"millis",{enumerable:!0,get:function(){return f6.millis}});Object.defineProperty(E6,"MsgHdrsImpl",{enumerable:!0,get:function(){return f6.MsgHdrsImpl}});Object.defineProperty(E6,"nanos",{enumerable:!0,get:function(){return f6.nanos}});Object.defineProperty(E6,"nkeyAuthenticator",{enumerable:!0,get:function(){return f6.nkeyAuthenticator}});Object.defineProperty(E6,"nkeys",{enumerable:!0,get:function(){return f6.nkeys}});Object.defineProperty(E6,"NoRespondersError",{enumerable:!0,get:function(){return f6.NoRespondersError}});Object.defineProperty(E6,"Nuid",{enumerable:!0,get:function(){return f6.Nuid}});Object.defineProperty(E6,"nuid",{enumerable:!0,get:function(){return f6.nuid}});Object.defineProperty(E6,"PermissionViolationError",{enumerable:!0,get:function(){return f6.PermissionViolationError}});Object.defineProperty(E6,"ProtocolError",{enumerable:!0,get:function(){return f6.ProtocolError}});Object.defineProperty(E6,"RequestError",{enumerable:!0,get:function(){return f6.RequestError}});Object.defineProperty(E6,"syncIterator",{enumerable:!0,get:function(){return f6.syncIterator}});Object.defineProperty(E6,"TimeoutError",{enumerable:!0,get:function(){return f6.TimeoutError}});Object.defineProperty(E6,"tokenAuthenticator",{enumerable:!0,get:function(){return f6.tokenAuthenticator}});Object.defineProperty(E6,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return f6.UserAuthenticationExpiredError}});Object.defineProperty(E6,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return f6.usernamePasswordAuthenticator}});Object.defineProperty(E6,"wsconnect",{enumerable:!0,get:function(){return f6.wsconnect}})});var qD=_((Gp1)=>{Object.defineProperty(Gp1,"__esModule",{value:!0});Gp1.PubHeaders=Gp1.PriorityPolicy=Gp1.ConsumerApiAction=Gp1.PersistMode=Gp1.StoreCompression=Gp1.ReplayPolicy=Gp1.AckPolicy=Gp1.DeliverPolicy=Gp1.StorageType=Gp1.DiscardPolicy=Gp1.RetentionPolicy=void 0;Gp1.defaultConsumer=Sl6;var kl6=Um();Gp1.RetentionPolicy={Limits:"limits",Interest:"interest",Workqueue:"workqueue"};Gp1.DiscardPolicy={Old:"old",New:"new"};Gp1.StorageType={File:"file",Memory:"memory"};Gp1.DeliverPolicy={All:"all",Last:"last",New:"new",StartSequence:"by_start_sequence",StartTime:"by_start_time",LastPerSubject:"last_per_subject"};Gp1.AckPolicy={None:"none",All:"all",Explicit:"explicit",FlowControl:"flow_control",NotSet:""};Gp1.ReplayPolicy={Instant:"instant",Original:"original"};Gp1.StoreCompression={None:"none",S2:"s2"};Gp1.PersistMode={Default:"default",Async:"async"};Gp1.ConsumerApiAction={CreateOrUpdate:"",Update:"update",Create:"create"};Gp1.PriorityPolicy={None:"none",Overflow:"overflow",PinnedClient:"pinned_client",Prioritized:"prioritized"};function Sl6($,Z={}){return Object.assign({name:$,deliver_policy:Gp1.DeliverPolicy.All,ack_policy:Gp1.AckPolicy.Explicit,ack_wait:(0,kl6.nanos)(30000),replay_policy:Gp1.ReplayPolicy.Instant},Z)}Gp1.PubHeaders={MsgIdHdr:"Nats-Msg-Id",ExpectedStreamHdr:"Nats-Expected-Stream",ExpectedLastSeqHdr:"Nats-Expected-Last-Sequence",ExpectedLastMsgIdHdr:"Nats-Expected-Last-Msg-Id",ExpectedLastSubjectSequenceHdr:"Nats-Expected-Last-Subject-Sequence",ExpectedLastSubjectSequenceSubjectHdr:"Nats-Expected-Last-Subject-Sequence-Subject",MessageTTL:"Nats-TTL",Schedule:"Nats-Schedule",ScheduleTarget:"Nats-Schedule-Target",ScheduleSource:"Nats-Schedule-Source",ScheduleTTL:"Nats-Schedule-TTL",ScheduleTimeZone:"Nats-Schedule-Time-Zone",ScheduleRollup:"Nats-Schedule-Rollup",Scheduler:"Nats-Scheduler",ScheduleNext:"Nats-Schedule-Next"}});var Yd0=_((Fp1)=>{Object.defineProperty(Fp1,"__esModule",{value:!0});Fp1.ConsumerAPIImpl=void 0;var gl6=ff(),hl6=o50(),YJ=bf(),m7=vY(),UN=qD();class Np1 extends gl6.BaseApiClientImpl{constructor($,Z){super($,Z)}async addUpdate($,Z,X,Q){if((0,YJ.validateStreamName)($),X=X||{},Z.deliver_group&&Z.flow_control)throw m7.InvalidArgumentError.format(["flow_control","deliver_group"],"are mutually exclusive");if(Z.deliver_group&&Z.idle_heartbeat)throw m7.InvalidArgumentError.format(["idle_heartbeat","deliver_group"],"are mutually exclusive");if(Up1(Z)){let{min:w,ok:B}=this.nc.features.get(m7.Feature.JS_PRIORITY_GROUPS);if(!B)throw Error(`priority_groups require server ${w}`);if(Z.deliver_subject)throw m7.InvalidArgumentError.format("deliver_subject","cannot be set when using priority groups");ul6(Z)}let Y={};if(Y.config=Z,Y.stream_name=$,Y.action=X.action||UN.ConsumerApiAction.Create,Y.pedantic=X.pedantic||!1,Y.config.durable_name)(0,YJ.validateDurableName)(Y.config.durable_name);let G=this.nc,{min:J,ok:K}=G.features.get(m7.Feature.JS_NEW_CONSUMER_CREATE_API),W=Z.name===""?void 0:Z.name;if(W&&!K)throw m7.InvalidArgumentError.format("name",`requires server ${J}`);if(W)try{(0,YJ.minValidation)("name",W)}catch(w){let B=w.message,L=B.indexOf("cannot contain");if(L!==-1)throw Error(`consumer 'name' ${B.substring(L)}`);throw w}let H,N="";if(Array.isArray(Z.filter_subjects)){let{min:w,ok:B}=G.features.get(m7.Feature.JS_MULTIPLE_CONSUMER_FILTER);if(!B)throw m7.InvalidArgumentError.format("filter_subjects",`requires server ${w}`);K=!1}if(Z.metadata){let{min:w,ok:B}=G.features.get(m7.Feature.JS_STREAM_CONSUMER_METADATA);if(!B)throw m7.InvalidArgumentError.format("metadata",`requires server ${w}`)}if(K)N=Z.name??Z.durable_name??"";if(N!==""){let w=Z.filter_subject??void 0;if(w===">")w=void 0;H=w!==void 0?`${this.prefix}.CONSUMER.CREATE.${$}.${N}.${w}`:`${this.prefix}.CONSUMER.CREATE.${$}.${N}`}else H=Z.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${$}.${Z.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${$}`;let U=Q??Y.config;return await this._request(H,Y,{...X,...this.requiredApiOpts(U)})}minConsumerApi($){if($.ack_policy===UN.AckPolicy.FlowControl)return 4;if(typeof $.pause_until==="string"&&$.pause_until!=="")return 1;if($.priority_policy!==void 0&&$.priority_policy!==UN.PriorityPolicy.None)return 1;if(typeof $.priority_timeout==="number"&&$.priority_timeout>0)return 1;if(Array.isArray($.priority_groups)&&$.priority_groups.length>0)return 1;return 0}requiredApiOpts($){if(!this.sendRequiredApiLevel())return{};let Z=this.minConsumerApi($);return Z>0?{minApiVersion:Z}:{}}add($,Z,X){X=X||{};let Q=UN.ConsumerApiAction.Create;if(typeof X==="string")Q=X,X={};let Y=Object.assign({},{action:Q},X);return this.addUpdate($,Z,Y)}async update($,Z,X){let Q=await this.info($,Z),Y=X;return this.addUpdate($,Object.assign(Q.config,Y),{action:UN.ConsumerApiAction.Update},Y)}async info($,Z){return(0,YJ.validateStreamName)($),(0,YJ.validateDurableName)(Z),await this._request(`${this.prefix}.CONSUMER.INFO.${$}.${Z}`)}async delete($,Z){return(0,YJ.validateStreamName)($),(0,YJ.validateDurableName)(Z),(await this._request(`${this.prefix}.CONSUMER.DELETE.${$}.${Z}`)).success}list($){(0,YJ.validateStreamName)($);let Z=(Q)=>{return Q.consumers},X=`${this.prefix}.CONSUMER.LIST.${$}`;return new hl6.ListerImpl(X,Z,this)}pause($,Z,X){let Q=`${this.prefix}.CONSUMER.PAUSE.${$}.${Z}`,Y={pause_until:X.toISOString()};return this._request(Q,Y)}resume($,Z){return this.pause($,Z,new Date(0))}unpin($,Z,X){let Q=`${this.prefix}.CONSUMER.UNPIN.${$}.${Z}`;return this._request(Q,{group:X})}async reset($,Z,X){(0,YJ.validateStreamName)($),(0,YJ.validateDurableName)(Z);let Q=this.nc,{min:Y,ok:G}=Q.features.get(m7.Feature.JS_CONSUMER_RESET);if(!G)throw Error(`consumer reset requires server ${Y}`);if(typeof X==="number"&&(!Number.isInteger(X)||X<0))throw m7.InvalidArgumentError.format("seq","must be a non-negative integer");let J=`${this.prefix}.CONSUMER.RESET.${$}.${Z}`,K=typeof X==="number"?{seq:X}:void 0;return await this._request(J,K)}}Fp1.ConsumerAPIImpl=Np1;function Up1($){let Z=$;return Z&&Z.priority_groups!==void 0||Z.priority_policy!==void 0}function ul6($){if(Up1($)){if(!Array.isArray($.priority_groups))throw m7.InvalidArgumentError.format(["priority_groups"],"must be an array");if($.priority_groups.length===0)throw m7.InvalidArgumentError.format(["priority_groups"],"must have at least one group");if($.priority_groups.forEach((Z)=>{if((0,YJ.minValidation)("priority_group",Z),Z.length>16)throw m7.errors.InvalidArgumentError.format("group","must be 16 characters or less")}),$.priority_policy!==UN.PriorityPolicy.None&&$.priority_policy!==UN.PriorityPolicy.Overflow&&$.priority_policy!==UN.PriorityPolicy.PinnedClient&&$.priority_policy!==UN.PriorityPolicy.Prioritized)throw m7.InvalidArgumentError.format(["priority_policy"],"must be 'none', 'prioritized', 'overflow', or 'pinned_client'")}}});var Kd0=_((Op1)=>{Object.defineProperty(Op1,"__esModule",{value:!0});Op1.JsMsgImpl=Op1.ACK=void 0;Op1.toJsMsg=il6;Op1.parseInfo=Bp1;var yf=vY();Op1.ACK=Uint8Array.of(43,65,67,75);var cl6=Uint8Array.of(45,78,65,75),Fm=Uint8Array.of(43,87,80,73),ll6=Uint8Array.of(43,78,88,84),dl6=Uint8Array.of(43,84,69,82,77),ml6=Uint8Array.of(32);function il6($,Z=5000){return new Jd0($,Z)}function Bp1($){let Z=$.split(".");if(Z.length===9)Z.splice(2,0,"_","");if(Z.length<11||Z[0]!=="$JS"||Z[1]!=="ACK")throw Error("unable to parse delivery info - not a jetstream message");let X={};return X.domain=Z[2]==="_"?"":Z[2],X.account_hash=Z[3],X.stream=Z[4],X.consumer=Z[5],X.deliveryCount=parseInt(Z[6],10),X.redelivered=X.deliveryCount>1,X.streamSequence=parseInt(Z[7],10),X.deliverySequence=parseInt(Z[8],10),X.timestampNanos=parseInt(Z[9],10),X.pending=parseInt(Z[10],10),X}function nl6($){let Z=$.split(".");if(Z.length===9)Z.splice(2,0,"_","");if(Z.length<11||Z[0]!=="$JS"||Z[1]!=="ACK")throw Error("unable to parse delivery info - not a jetstream message");return BigInt(Z[9])}class Jd0{msg;di;didAck;timeout;constructor($,Z){this.msg=$,this.didAck=!1,this.timeout=Z}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){if(!this.di)this.di=Bp1(this.reply);return this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}get time(){let $=(0,yf.millis)(this.info.timestampNanos);return new Date($)}get timestamp(){return this.time.toISOString()}get timestampNanos(){return nl6(this.reply)}doAck($){if(!this.didAck)this.didAck=!this.isWIP($),this.msg.respond($)}isWIP($){return $.length===4&&$[0]===Fm[0]&&$[1]===Fm[1]&&$[2]===Fm[2]&&$[3]===Fm[3]}async ackAck($){let Z=(0,yf.deferred)();if(!this.didAck)if(this.didAck=!0,this.msg.reply){$=$||{},$.timeout=$.timeout||this.timeout;let Q=this.msg.publisher,Y=!Q.options?.noAsyncTraces,G=new yf.RequestOne(Q.muxSubscriptions,this.msg.reply,{timeout:$.timeout},Y);Q.request(G);try{Q.publish(this.msg.reply,Op1.ACK,{reply:`${Q.muxSubscriptions.baseInbox}${G.token}`})}catch(J){G.cancel(J)}try{await Promise.race([G.timer,G.deferred]),Z.resolve(!0)}catch(J){G.cancel(J),Z.reject(J)}}else Z.resolve(!1);else Z.resolve(!1);return Z}ack(){this.doAck(Op1.ACK)}nak($){let Z=cl6;if($)Z=new TextEncoder().encode(`-NAK ${JSON.stringify({delay:(0,yf.nanos)($)})}`);this.doAck(Z)}working(){this.doAck(Fm)}next($,Z={batch:1}){let X={};if(X.batch=Z.batch||1,X.no_wait=Z.no_wait||!1,Z.expires&&Z.expires>0)X.expires=(0,yf.nanos)(Z.expires);let Q=new TextEncoder().encode(JSON.stringify(X)),Y=yf.DataBuffer.concat(ll6,ml6,Q),G=$?{reply:$}:void 0;this.msg.respond(Y,G)}term($=""){let Z=dl6;if($?.length>0)Z=new TextEncoder().encode(`+TERM ${$}`);this.doAck(Z)}json(){return this.msg.json()}string(){return this.msg.string()}}Op1.JsMsgImpl=Jd0});var Rp1=_((Tp1)=>{Object.defineProperty(Tp1,"__esModule",{value:!0});Tp1.PullConsumerImpl=Tp1.PullConsumerMessagesImpl=Tp1.PullConsumerType=void 0;Tp1.isOverflowOptions=wm;Tp1.isPrioritizedOptions=r50;Tp1.validateOverflowPullOptions=Pp1;Tp1.validatePrioritizedPullOptions=Ap1;var L$=vY(),ol6=Kd0(),Dp1=qD(),Ep1=HN(),zp1=bf();Tp1.PullConsumerType={Unset:"",Consume:"consume",Fetch:"fetch"};function wm($){let Z=$;return Z&&typeof Z.group==="string"||typeof Z.min_pending==="number"||typeof Z.min_ack_pending==="number"}function r50($){let Z=$;return Z&&typeof Z.group==="string"&&typeof Z.priority==="number"}class a50 extends L$.QueuedIteratorImpl{consumer;opts;sub;monitor;pending;isConsume;callback;listeners;statusIterator;abortOnMissingResource;bind;inboxPrefix;inbox;cancelables;inReset;closeListener;isPinned;isPriority;natsPinId;constructor($,Z,X=!1){super();if(this.consumer=$,this.isConsume=X,this.cancelables=[],this.inboxPrefix=(0,L$.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,this.inReset=!1,this.isPinned=!1,this.isPriority=!1,this.natsPinId="",this.consumer.ordered){if(wm(Z))throw L$.errors.InvalidArgumentError.format(["group","min_pending","min_ack_pending"],"cannot be specified for ordered consumers");if(this.consumer.orderedConsumerState===void 0){let Y={},G=$.opts;Y.namePrefix=G.name_prefix??`oc_${L$.nuid.next()}`,Y.opts=G,Y.cursor={stream_seq:1,deliver_seq:0};let J=$._info.config.opt_start_seq||0;Y.cursor.stream_seq=J>0?J-1:0,Y.createFails=0,this.consumer.orderedConsumerState=Y}}let Q=Z;if(this.opts=this.parseOptions(Z,this.isConsume),this.callback=Q.callback||null,this.noIterator=typeof this.callback==="function",this.monitor=null,this.pending={msgs:0,bytes:0,requests:0},this.listeners=[],this.abortOnMissingResource=Q.abort_on_missing_resource===!0,this.bind=Q.bind===!0,Q.group){let{min_pending:Y,min_ack_pending:G}=Q;this.isPinned=Y===void 0&&G===void 0;let{priority:J}=Q;this.isPriority=typeof J==="number"}this.closeListener={connectionClosedCallback:()=>{this._push(()=>{this.stop()})}},this.consumer.api.nc.addCloseListener(this.closeListener),this.start()}start(){let{max_messages:$,max_bytes:Z,idle_heartbeat:X,threshold_bytes:Q,threshold_messages:Y}=this.opts;if(this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(G,J)=>{if(G){this.stop(G);return}if(this.monitor?.work(),this.consumer.ordered?J.subject.indexOf(this?.inboxPrefix)===0:J.subject===this.inbox){if(J.subject!==this.sub.getSubject())return;let W=new Ep1.JetStreamStatus(J),H=W.parseHeartbeat();if(H){this.notify(H);return}let{code:N,description:U}=W,{msgsLeft:F,bytesLeft:w}=W.parseDiscard();if(F&&F>0||w&&w>0)this.pending.msgs-=F,this.pending.bytes-=w,this.pending.requests--,this.notify({type:"discard",messagesLeft:F,bytesLeft:w});switch(N){case 400:this.stop(W.toError());return;case 409:{let B=this.handle409(W);if(B){this.stop(B);return}if(W.isMessageSizeExceedsMaxBytes()&&this.yields.length>0)break;return}case 423:this.natsPinId="",this.notify({type:"consumer_unpinned"});break;case 503:if(this.notify({type:"no_responders",code:N}),this.consumer.ordered){let B=this.consumer.orderedConsumerState;B.needsReset=!0}if(!this.isConsume){this.stop(W.toError());return}break;default:this.notify({type:"debug",code:N,description:U})}}else{let W=(0,ol6.toJsMsg)(J,this.consumer.api.timeout);if(this.isPinned){let H=W?.headers?.get("Nats-Pin-Id");if(H&&this.natsPinId==="")this.natsPinId=H,this.notify({type:"consumer_pinned",id:H})}if(this.consumer.ordered){let H=this.consumer.orderedConsumerState.cursor,N=W.info.deliverySequence,U=W.info.streamSequence,F=H.deliver_seq+1;if(N!==F){this.reset();return}H.deliver_seq=N,H.stream_seq=U}if(this._push(W),this.received++,this.pending.msgs)this.pending.msgs--;if(this.pending.bytes)this.pending.bytes-=J.size()}if(this.pending.msgs===0&&this.pending.bytes===0)this.pending.requests=0;if(this.isConsume){if($&&this.pending.msgs<=Y||Z&&this.pending.bytes<=Q){let W=this.pullOptions();this.pull(W)}}else if(this.pending.requests===0)this._push(()=>{this.stop()})}}),X)this.monitor=new L$.IdleHeartbeatMonitor(X,(G)=>{if(this.notify({type:"heartbeats_missed",count:G}),!this.isConsume&&!this.consumer.ordered)return this.stop(new Ep1.JetStreamError("heartbeats missed")),!0;return this.resetPending().then(()=>{}).catch(()=>{}),!1},{maxOut:2});(async()=>{let G=this.consumer.api.nc.status();this.statusIterator=G;for await(let J of G)switch(J.type){case"disconnect":this.monitor?.cancel();break;case"reconnect":this.resetPending().then((K)=>{if(K)this.monitor?.restart()}).catch(()=>{});break;default:}})(),this.sub.closed.then(()=>{if(this.sub.isDraining())this._push(()=>{this.stop()})}),this.pull(this.pullOptions())}handle409($){let{code:Z,description:X}=$;if($.isConsumerDeleted())this.notify({type:"consumer_deleted",code:Z,description:X});else if($.isExceededLimit())this.notify({type:"exceeded_limits",code:Z,description:X});if(!this.isConsume)return $.toError();if($.isConsumerDeleted()&&this.abortOnMissingResource)return $.toError();return null}reset(){this.monitor?.cancel();let $=this.consumer.orderedConsumerState,{name:Z}=this.consumer._info?.config;if(Z)this.notify({type:"reset",name:Z}),this.consumer.api.delete(this.consumer.stream,Z).catch(()=>{});let X=this.consumer.getConsumerOpts();this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,$.cursor.deliver_seq=0,this.consumer.name=X.name,this.consumer.api.nc._resub(this.sub,this.inbox),this.consumer.api.add(this.consumer.stream,X).then((Q)=>{$.createFails=0,this.consumer._info=Q,this.notify({type:"ordered_consumer_recreated",name:Q.name}),this.monitor?.restart(),this.pull(this.pullOptions())}).catch((Q)=>{if($.createFails++,Q.message==="stream not found"){if(this.notify({type:"stream_not_found",consumerCreateFails:$.createFails,name:this.consumer.stream}),this.abortOnMissingResource){this.stop(Q);return}}if($.createFails>=30&&this.received===0)this.stop(Q);let Y=(0,L$.backoff)(),G=(0,L$.delay)(Y.backoff($.createFails));G.then(()=>{let J=this.cancelables.indexOf(G);if(J!==-1)this.cancelables=this.cancelables.splice(J,J);if(!this.done)this.reset()}).catch((J)=>{}),this.cancelables.push(G)})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let X=$;this.callback(X)}else Z()}catch(X){this.stop(X)}}}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let X=Z;if(!X.done)X.push($)})})()}async resetPending(){if(this.inReset)return Promise.resolve(!0);this.inReset=!0;let Z=await(this.bind?this.resetPendingNoInfo():this.resetPendingWithInfo());return this.inReset=!1,Z}resetPendingNoInfo(){return this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),Promise.resolve(!0)}async resetPendingWithInfo(){let $=0,Z=0,X=(0,L$.backoff)([this.opts.expires||30000]),Q=0;while(!0){if(this.done)return!1;if(this.consumer.api.nc.isClosed())return!1;try{return await this.consumer.info(),$=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(Y){if(Y instanceof L$.errors.ClosedConnectionError)return this.stop(Y),!1;if(Y.message==="stream not found"){if(Z++,this.notify({type:"stream_not_found",name:this.consumer.stream}),!this.isConsume||this.abortOnMissingResource)return this.stop(Y),!1}else if(Y.message==="consumer not found"){if($++,this.notify({type:"consumer_not_found",name:this.consumer.name,stream:this.consumer.stream,count:$}),!this.isConsume||this.abortOnMissingResource){if(this.consumer.ordered){let K=this.consumer.orderedConsumerState;K.needsReset=!0}return this.stop(Y),!1}if(this.consumer.ordered)return this.reset(),!1}else $=0,Z=0;let G=X.backoff(Q),J=(0,L$.delay)(G);await Promise.race([J,this.consumer.api.nc.closed()]),J.cancel(),Q++}}}pull($){this.pending.bytes+=$.max_bytes??0,this.pending.msgs+=$.batch??0,this.pending.requests++;let Z=this.consumer.api.nc,X=`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer._info.name}`;this._push(()=>{Z.publish(X,JSON.stringify($),{reply:this.inbox}),this.notify({type:"next",options:$})})}pullOptions(){let $=this.opts.max_messages-this.pending.msgs,Z=this.opts.max_bytes-this.pending.bytes,X=(0,L$.nanos)(this.opts.idle_heartbeat),Q=(0,L$.nanos)(this.opts.expires),Y={batch:$,max_bytes:Z,idle_heartbeat:X,expires:Q};if(this.isPinned&&this.natsPinId!=="")Y.id=this.natsPinId;if(wm(this.opts)){if(Y.group=this.opts.group,this.opts.min_pending)Y.min_pending=this.opts.min_pending;if(this.opts.min_ack_pending)Y.min_ack_pending=this.opts.min_ack_pending}if(r50(this.opts))Y.group=this.opts.group,Y.priority=this.opts.priority;return Y}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}clearTimers(){this.monitor?.cancel(),this.monitor=null}stop($){if(this.done)return;this.consumer.api.nc.removeCloseListener(this.closeListener),this.sub?.unsubscribe(),this.clearTimers(),this.statusIterator?.stop(),this._push(()=>{super.stop($),this.listeners.forEach((Z)=>{Z.stop()})})}parseOptions($,Z=!1){let X=$||{};if(X.max_messages=X.max_messages||0,X.max_bytes=X.max_bytes||0,X.max_messages!==0&&X.max_bytes!==0)throw L$.errors.InvalidArgumentError.format(["max_messages","max_bytes"],"are mutually exclusive");if(X.max_messages===0)X.max_messages=100;if(X.expires=X.expires||30000,X.expires<1000)throw L$.errors.InvalidArgumentError.format("expires","must be at least 1000ms");if(X.idle_heartbeat=X.idle_heartbeat||X.expires/2,X.idle_heartbeat=X.idle_heartbeat>30000?30000:X.idle_heartbeat,X.idle_heartbeat<500)X.idle_heartbeat=500;if(Z){let Q=Math.round(X.max_messages*0.75)||1;X.threshold_messages=X.threshold_messages||Q;let Y=Math.round(X.max_bytes*0.75)||1;X.threshold_bytes=X.threshold_bytes||Y}if(wm($)){let{min:Q,ok:Y}=this.consumer.api.nc.features.get(L$.Feature.JS_PRIORITY_GROUPS);if(!Y)throw Error(`priority_groups require server ${Q}`);if(Pp1($),$.group)X.group=$.group;if($.min_ack_pending)X.min_ack_pending=$.min_ack_pending;if($.min_pending)X.min_pending=$.min_pending}else if(r50($)){if(Ap1($),$.group)X.group=$.group;if(typeof $.priority==="number")X.priority=$.priority}return X}status(){let $=new L$.QueuedIteratorImpl;return this.listeners.push($),$}}Tp1.PullConsumerMessagesImpl=a50;class jp1{api;_info;stream;name;opts;type;messages;ordered;serial;orderedConsumerState;constructor($,Z,X=null){this.api=$,this._info=Z,this.name=Z.name,this.stream=Z.stream_name,this.ordered=X!==null,this.opts=X||{},this.serial=1,this.type=Tp1.PullConsumerType.Unset}debug(){console.log({serial:this.serial,cursor:this.orderedConsumerState?.cursor})}isPullConsumer(){return!0}isPushConsumer(){return!1}consume($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.bind)return Promise.reject(L$.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===Tp1.PullConsumerType.Fetch)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer initialized as fetch"));if(this.type===Tp1.PullConsumerType.Consume)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer doesn't support concurrent consume"));this.type=Tp1.PullConsumerType.Consume}return Promise.resolve(new a50(this,$,!0))}async fetch($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.group)return Promise.reject(L$.errors.InvalidArgumentError.format("group","ordered consumers don't support priority groups"));if($.bind)return Promise.reject(L$.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===Tp1.PullConsumerType.Consume)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer already initialized as consume"));if(this.messages?.done===!1)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer doesn't support concurrent fetch"));if(this.ordered){if(this.orderedConsumerState?.cursor?.deliver_seq)this._info.config.opt_start_seq=this.orderedConsumerState?.cursor.stream_seq+1;if(this.orderedConsumerState?.needsReset===!0)await this._reset()}this.type=Tp1.PullConsumerType.Fetch}let Z=new a50(this,$);if(this.ordered)this.messages=Z;return Promise.resolve(Z)}async next($={expires:30000}){$={...$};let Z=$;Z.max_messages=1;let X=await this.fetch(Z);try{for await(let Q of X)return Q}catch(Q){return Promise.reject(Q)}return null}delete(){let{stream_name:$,name:Z}=this._info;return this.api.delete($,Z)}getConsumerOpts(){let $=this.orderedConsumerState;this.serial++,this.name=`${$.namePrefix}_${this.serial}`;let Z=Object.assign({},this._info.config,{name:this.name,deliver_policy:Dp1.DeliverPolicy.StartSequence,opt_start_seq:$.cursor.stream_seq+1,ack_policy:Dp1.AckPolicy.None,inactive_threshold:(0,L$.nanos)(300000),num_replicas:1});return delete Z.metadata,Z}async _reset(){if(this.messages===void 0)throw Error("not possible to reset");this.delete().catch(()=>{});let $=this.getConsumerOpts(),Z=await this.api.add(this.stream,$);return this._info=Z,Z}async info($=!1){if($)return Promise.resolve(this._info);let{stream_name:Z,name:X}=this._info;return this._info=await this.api.info(Z,X),this._info}}Tp1.PullConsumerImpl=jp1;function Pp1($){if(wm($)){if((0,zp1.minValidation)("group",$.group),$.group.length>16)throw L$.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{min_pending:Z,min_ack_pending:X}=$;if(Z&&typeof Z!=="number")throw L$.errors.InvalidArgumentError.format(["min_pending"],"must be a number");if(X&&typeof X!=="number")throw L$.errors.InvalidArgumentError.format(["min_ack_pending"],"must be a number")}}function Ap1($){if(r50($)){if((0,zp1.minValidation)("group",$.group),$.group.length>16)throw L$.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{priority:Z}=$;if(Z&&typeof Z!=="number")throw L$.errors.InvalidArgumentError.format(["priority"],"must be a number")}}});var Vp1=_((kp1)=>{Object.defineProperty(kp1,"__esModule",{value:!0});kp1.PushConsumerImpl=kp1.PushConsumerMessagesImpl=void 0;var Zd6=Kd0(),qp1=qD(),Wd0=ED(),bX=vY(),Xd6=HN();class Hd0 extends bX.QueuedIteratorImpl{consumer;sub;monitor;listeners;abortOnMissingResource;callback;ordered;cursor;namePrefix;deliverPrefix;serial;createFails;statusIterator;cancelables;constructor($,Z={},X={}){super();if(this.consumer=$,this.monitor=null,this.listeners=[],this.cancelables=[],this.abortOnMissingResource=Z.abort_on_missing_resource===!0,this.callback=Z.callback||null,this.noIterator=this.callback!==null,this.namePrefix=null,this.deliverPrefix=null,this.ordered=X.ordered===!0,this.serial=1,this.ordered){this.namePrefix=X.name_prefix??`oc_${bX.nuid.next()}`,this.deliverPrefix=X.deliver_prefix??(0,bX.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.cursor={stream_seq:1,deliver_seq:0};let Q=$._info.config.opt_start_seq||0;this.cursor.stream_seq=Q>0?Q-1:0,this.createFails=0}this.start()}reset(){let{name:$}=this.consumer._info?.config;if($)this.consumer.api.delete(this.consumer.stream,$).catch(()=>{});let Z=this.getConsumerOpts();this.cursor.deliver_seq=0,this.consumer.name=Z.name,this.consumer.serial=this.serial,this.consumer.api.nc._resub(this.sub,Z.deliver_subject),this.consumer.api.add(this.consumer.stream,Z).then((X)=>{this.createFails=0,this.consumer._info=X,this.notify({type:"ordered_consumer_recreated",name:X.name})}).catch((X)=>{if(this.createFails++,X.message==="stream not found"){if(this.notify({type:"stream_not_found",name:this.consumer.stream,consumerCreateFails:this.createFails}),this.abortOnMissingResource){this.stop(X);return}}if(this.createFails>=30&&this.received===0)this.stop(X);let Q=(0,bX.backoff)(),Y=(0,bX.delay)(Q.backoff(this.createFails));Y.then(()=>{if(!this.done)this.reset()}).catch(()=>{}).finally(()=>{let G=this.cancelables.indexOf(Y);if(G!==-1)this.cancelables=this.cancelables.splice(G,G)}),this.cancelables.push(Y)})}getConsumerOpts(){let $=Object.assign({},this.consumer._info.config);this.serial++;let Z=`${this.namePrefix}_${this.serial}`;return Object.assign($,{name:Z,deliver_policy:qp1.DeliverPolicy.StartSequence,opt_start_seq:this.cursor.stream_seq+1,ack_policy:qp1.AckPolicy.None,inactive_threshold:(0,bX.nanos)(300000),num_replicas:1,flow_control:!0,idle_heartbeat:(0,bX.nanos)(30000),deliver_subject:`${this.deliverPrefix}.${this.serial}`})}closed(){return this.iterClosed}close(){return this.stop(),this.iterClosed}stop($){if(this.done)return;this.statusIterator?.stop(),this.monitor?.cancel(),this.monitor=null,this.cancelables.forEach((Z)=>{Z.cancel()}),Promise.all(this.cancelables).then(()=>{this.cancelables=[]}).catch(()=>{}).finally(()=>{this._push(()=>{super.stop($),this.listeners.forEach((Z)=>{Z.stop()})})})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let X=$;this.received++,this.callback(X),this.processed++}else Z()}catch(X){this.stop(X)}}}status(){let $=new bX.QueuedIteratorImpl;return this.listeners.push($),$}start(){let{deliver_subject:$,deliver_group:Z,idle_heartbeat:X}=this.consumer._info.config;if(!$)throw Error("bad consumer info");if(X){let Q=(0,bX.millis)(X);this.monitor=new bX.IdleHeartbeatMonitor(Q,(Y)=>{if(this.notify({type:"heartbeats_missed",count:Y}),this.ordered)this.reset();return!1},{maxOut:2}),(async()=>{this.statusIterator=this.consumer.api.nc.status();for await(let Y of this.statusIterator)switch(Y.type){case"disconnect":this.monitor?.cancel();break;case"reconnect":this.monitor?.restart();break;default:}})()}this.sub=this.consumer.api.nc.subscribe($,{queue:Z,callback:(Q,Y)=>{if(Q){this.stop(Q);return}if(this.monitor?.work(),this.ordered?Y.subject.indexOf(this?.deliverPrefix)===0:Y.subject===$){if(Y.subject!==this.sub.getSubject())return;let J=new Xd6.JetStreamStatus(Y);if(J.isFlowControlRequest()){this._push(()=>{Y.respond(),this.notify({type:"flow_control"})});return}if(J.isIdleHeartbeat()){let H=parseInt(Y.headers?.get(Wd0.JsHeaders.LastConsumerSeqHdr)||"0"),N=parseInt(Y.headers?.get(Wd0.JsHeaders.LastStreamSeqHdr)??"0");this.notify({type:"heartbeat",lastStreamSequence:N,lastConsumerSequence:H});let U=Y.headers?.get(Wd0.JsHeaders.ConsumerStalledHdr);if(typeof U==="string"&&U!=="")Y.publisher.publish(U,bX.Empty);return}let{code:K,description:W}=J;if(J.isConsumerDeleted())this.notify({type:"consumer_deleted",code:K,description:W});if(this.abortOnMissingResource){this._push(()=>{this.stop(J.toError())});return}}else{let J=(0,Zd6.toJsMsg)(Y);if(this.ordered){let K=J.info.deliverySequence;if(K!==this.cursor.deliver_seq+1){this.reset();return}this.cursor.deliver_seq=K,this.cursor.stream_seq=J.info.streamSequence}this._push(J)}}}),this.sub.closed.then(()=>{this._push(()=>{this.stop()})}),this.closed().then(()=>{this.sub?.unsubscribe()})}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let X=Z;if(!X.done)X.push($)})})()}}kp1.PushConsumerMessagesImpl=Hd0;class Mp1{api;_info;stream;name;bound;ordered;started;serial;opts;constructor($,Z,X={}){if(this.api=$,this._info=Z,this.stream=Z.stream_name,this.name=Z.name,this.bound=X.bound===!0,this.started=!1,this.opts=X,this.serial=0,this.ordered=X.ordered||!1,this.ordered)this.serial=1}consume($={}){if($={...$},this.started)return Promise.reject(new bX.errors.InvalidOperationError("consumer already started"));if(!this._info.config.deliver_subject)return Promise.reject(Error("deliver_subject is not set, not a push consumer"));if(!this._info.config.deliver_group&&this._info.push_bound)return Promise.reject(new bX.errors.InvalidOperationError("consumer is already bound"));let Z=new Hd0(this,$,this.opts);return this.started=!0,Z.closed().then(()=>{this.started=!1}),Promise.resolve(Z)}delete(){if(this.bound)return Promise.reject(new bX.errors.InvalidOperationError("bound consumers cannot delete"));let{stream_name:$,name:Z}=this._info;return this.api.delete($,Z)}async info($){if(this.bound)return Promise.reject(new bX.errors.InvalidOperationError("bound consumers cannot info"));if($)return Promise.resolve(this._info);let Z=await this.api.info(this.stream,this.name);return this._info=Z,Z}isPullConsumer(){return!1}isPushConsumer(){return!0}}kp1.PushConsumerImpl=Mp1});var yp1=_((fp1)=>{Object.defineProperty(fp1,"__esModule",{value:!0});fp1.StreamsImpl=fp1.StoredMsgImpl=fp1.StreamAPIImpl=fp1.StreamImpl=fp1.ConsumersImpl=void 0;fp1.convertStreamSourceDomain=Bm;var E9=vY(),Yd6=ff(),Cp1=o50(),GJ=bf(),_p1=ED(),fY=qD(),Nd0=Rp1(),Ud0=Yd0(),Fd0=Vp1(),xp1=HN();function Bm($){if($===void 0)return;let{domain:Z}=$;if(Z===void 0)return $;let X=Object.assign({},$);if(delete X.domain,Z==="")return X;if(X.external)throw E9.InvalidArgumentError.format(["domain","external"],"are mutually exclusive");return X.external={api:`$JS.${Z}.API`},X}class s50{api;notified;constructor($){this.api=$,this.notified=!1}checkVersion(){let $=this.api.nc.features.get(E9.Feature.JS_SIMPLIFICATION);if(!$.ok)return Promise.reject(Error(`consumers framework is only supported on servers ${$.min} or better`));return Promise.resolve()}async getPushConsumer($,Z){if(await this.checkVersion(),(0,GJ.minValidation)("stream",$),typeof Z==="string"){(0,GJ.minValidation)("name",Z);let X=await this.api.info($,Z);if(typeof X.config.deliver_subject!=="string")return Promise.reject(Error("not a push consumer"));return new Fd0.PushConsumerImpl(this.api,X)}else if(Z===void 0)return this.getOrderedPushConsumer($);else if((0,_p1.isOrderedPushConsumerOptions)(Z)){let X=Z;return this.getOrderedPushConsumer($,X)}return Promise.reject(Error("unsupported push consumer type"))}async getOrderedPushConsumer($,Z={}){Z=Object.assign({},Z);let{name_prefix:X,deliver_prefix:Q,filter_subjects:Y}=Z;if(delete Z.deliver_prefix,delete Z.name_prefix,delete Z.filter_subjects,typeof Z.opt_start_seq==="number")Z.deliver_policy=fY.DeliverPolicy.StartSequence;if(typeof Z.opt_start_time==="string")Z.deliver_policy=fY.DeliverPolicy.StartTime;X=X||`oc_${E9.nuid.next()}`,(0,GJ.minValidation)("name_prefix",X),Q=Q||(0,E9.createInbox)(this.api.getOptions().watcherPrefix);let G=Object.assign({},Z);if(G.ack_policy=fY.AckPolicy.None,G.inactive_threshold=(0,E9.nanos)(300000),G.num_replicas=1,G.max_deliver=1,G.flow_control=!0,G.idle_heartbeat=(0,E9.nanos)(30000),Array.isArray(Y))G.filter_subjects=Y;if(typeof Y==="string")G.filter_subject=Y;if(typeof G.filter_subjects>"u"&&typeof G.filter_subject>"u")G.filter_subject=">";G.name=`${X}_1`,G.deliver_subject=`${Q}.1`;let J=await this.api.add($,G),K={name_prefix:X,deliver_prefix:Q,ordered:!0};return new Fd0.PushConsumerImpl(this.api,J,K)}getBoundPushConsumer($){if((0,_p1.isBoundPushConsumerOptions)($)){let Z={config:$};return Promise.resolve(new Fd0.PushConsumerImpl(this.api,Z,{bound:!0}))}else return Promise.reject(E9.errors.InvalidArgumentError.format("deliver_subject","is required"))}async get($,Z){if(await this.checkVersion(),typeof Z==="string"){let X=await this.api.info($,Z);if(typeof X.config.deliver_subject==="string")return Promise.reject(Error("not a pull consumer"));else return new Nd0.PullConsumerImpl(this.api,X)}else return this.ordered($,Z)}getConsumerFromInfo($){if(typeof $.config.deliver_subject==="string")throw Error("not a pull consumer");return new Nd0.PullConsumerImpl(this.api,$)}async ordered($,Z={}){await this.checkVersion();let X=this.api;if(await new wd0(X.nc,X.opts).info($),typeof Z.name_prefix==="string")(0,GJ.minValidation)("name_prefix",Z.name_prefix);Z.name_prefix=Z.name_prefix||E9.nuid.next();let G={name:`${Z.name_prefix}_1`,deliver_policy:fY.DeliverPolicy.StartSequence,opt_start_seq:Z.opt_start_seq||1,ack_policy:fY.AckPolicy.None,inactive_threshold:(0,E9.nanos)(300000),num_replicas:1,max_deliver:1,mem_storage:!0};if(Z.headers_only===!0)G.headers_only=!0;if(Array.isArray(Z.filter_subjects))G.filter_subjects=Z.filter_subjects;if(typeof Z.filter_subjects==="string")G.filter_subject=Z.filter_subjects;if(Z.replay_policy)G.replay_policy=Z.replay_policy;if(G.deliver_policy=Z.deliver_policy||fY.DeliverPolicy.StartSequence,Z.deliver_policy===fY.DeliverPolicy.All||Z.deliver_policy===fY.DeliverPolicy.LastPerSubject||Z.deliver_policy===fY.DeliverPolicy.New||Z.deliver_policy===fY.DeliverPolicy.Last)delete G.opt_start_seq,G.deliver_policy=Z.deliver_policy;if(G.deliver_policy===fY.DeliverPolicy.LastPerSubject){if(typeof G.filter_subjects>"u"&&typeof G.filter_subject>"u")G.filter_subject=">"}if(Z.opt_start_time)delete G.opt_start_seq,G.deliver_policy=fY.DeliverPolicy.StartTime,G.opt_start_time=Z.opt_start_time;if(Z.inactive_threshold)G.inactive_threshold=(0,E9.nanos)(Z.inactive_threshold);let J=await this.api.add($,G);return Promise.resolve(new Nd0.PullConsumerImpl(this.api,J,Z))}}fp1.ConsumersImpl=s50;class Om{api;_info;constructor($,Z){this.api=$,this._info=Z}get name(){return this._info.config.name}alternates(){return this.info().then(($)=>{return $.alternates?$.alternates:[]})}async best(){if(await this.info(),this._info.alternates){let $=await this.api.info(this._info.alternates[0].name);return new Om(this.api,$)}else return this}info($=!1,Z){if($)return Promise.resolve(this._info);return this.api.info(this.name,Z).then((X)=>{return this._info=X,this._info})}getConsumer($){return new s50(new Ud0.ConsumerAPIImpl(this.api.nc,this.api.opts)).get(this.name,$)}getPushConsumer($){return new s50(new Ud0.ConsumerAPIImpl(this.api.nc,this.api.opts)).getPushConsumer(this.name,$)}getMessage($){return this.api.getMessage(this.name,$)}deleteMessage($,Z=!0){return this.api.deleteMessage(this.name,$,Z)}resetConsumer($,Z){return new Ud0.ConsumerAPIImpl(this.api.nc,this.api.opts).reset(this.name,$,Z)}}fp1.StreamImpl=Om;class wd0 extends Yd6.BaseApiClientImpl{constructor($,Z){super($,Z)}checkStreamConfigVersions($){let Z=this.nc;if($.metadata){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_STREAM_CONSUMER_METADATA);if(!Y)throw Error(`stream 'metadata' requires server ${Q}`)}if($.first_seq){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_STREAM_FIRST_SEQ);if(!Y)throw Error(`stream 'first_seq' requires server ${Q}`)}if($.subject_transform){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_STREAM_SUBJECT_TRANSFORM);if(!Y)throw Error(`stream 'subject_transform' requires server ${Q}`)}if($.compression){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_STREAM_COMPRESSION);if(!Y)throw Error(`stream 'compression' requires server ${Q}`)}if($.consumer_limits){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_DEFAULT_CONSUMER_LIMITS);if(!Y)throw Error(`stream 'consumer_limits' requires server ${Q}`)}function X(Q,Y){if((Y?.subject_transforms?.length||0)>0){let{min:J,ok:K}=Z.features.get(E9.Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!K)throw Error(`${Q} 'subject_transforms' requires server ${J}`)}}if($.sources)$.sources.forEach((Q)=>{X("stream sources",Q)});if($.mirror)X("stream mirror",$.mirror)}minStreamApi($){if($.allow_batched===!0||$.mirror?.consumer||$.sources?.some((Z)=>Z.consumer))return 4;if($.allow_msg_counter===!0||$.allow_atomic===!0||$.allow_msg_schedules===!0||$.persist_mode===fY.PersistMode.Async)return 2;if($.allow_msg_ttl===!0||typeof $.subject_delete_marker_ttl==="number"&&$.subject_delete_marker_ttl>0)return 1;return 0}requiredApiOpts($){if(!this.sendRequiredApiLevel())return{};let Z=this.minStreamApi($);return Z>0?{minApiVersion:Z}:{}}async add($){this.checkStreamConfigVersions($),(0,GJ.validateStreamName)($.name),$.mirror=Bm($.mirror),$.sources=$.sources?.map(Bm);let X=await this._request(`${this.prefix}.STREAM.CREATE.${$.name}`,$,this.requiredApiOpts($));return this._fixInfo(X),X}async delete($){return(0,GJ.validateStreamName)($),(await this._request(`${this.prefix}.STREAM.DELETE.${$}`)).success}async update($,Z={}){if(typeof $==="object"){let J=$;$=J.name,Z=J,console.trace("\x1B[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. \x1B[0m")}this.checkStreamConfigVersions(Z),(0,GJ.validateStreamName)($);let X=await this.info($),Q=Object.assign(X.config,Z);Q.mirror=Bm(Q.mirror),Q.sources=Q.sources?.map(Bm);let G=await this._request(`${this.prefix}.STREAM.UPDATE.${$}`,Q,this.requiredApiOpts(Z));return this._fixInfo(G),G}async info($,Z){(0,GJ.validateStreamName)($);let X=`${this.prefix}.STREAM.INFO.${$}`,Y=await this._request(X,Z),{total:G,limit:J}=Y,K=Y.state.subjects?Object.getOwnPropertyNames(Y.state.subjects).length:1;if(G&&G>K){let W=[Y],H=Z||{},N=0;while(G>K){N++,H.offset=J*N;let F=await this._request(X,H);G=F.total,W.push(F);let w=Object.getOwnPropertyNames(F.state.subjects).length;if(K+=w,w<J)break}let U={};for(let F=0;F<W.length;F++)if(Y=W[F],Y.state.subjects)U=Object.assign(U,Y.state.subjects);Y.offset=0,Y.total=0,Y.limit=0,Y.state.subjects=U}return this._fixInfo(Y),Y}list($=""){let Z=$?.length?{subject:$}:{},X=(Y)=>{let G=Y;return G.streams.forEach((J)=>{this._fixInfo(J)}),G.streams},Q=`${this.prefix}.STREAM.LIST`;return new Cp1.ListerImpl(Q,X,this,Z)}_fixInfo($){$.config.sealed=$.config.sealed||!1,$.config.deny_delete=$.config.deny_delete||!1,$.config.deny_purge=$.config.deny_purge||!1,$.config.allow_rollup_hdrs=$.config.allow_rollup_hdrs||!1}async purge($,Z){if(Z){let{keep:Q,seq:Y}=Z;if(typeof Q==="number"&&typeof Y==="number")throw E9.InvalidArgumentError.format(["keep","seq"],"are mutually exclusive")}return(0,GJ.validateStreamName)($),await this._request(`${this.prefix}.STREAM.PURGE.${$}`,Z)}async deleteMessage($,Z,X=!0){(0,GJ.validateStreamName)($);let Q={seq:Z};if(!X)Q.no_erase=!0;return(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${$}`,Q)).success}async getMessage($,Z){(0,GJ.validateStreamName)($);try{let Q=await this._request(`${this.prefix}.STREAM.MSG.GET.${$}`,Z);return new Bd0(Q)}catch(X){if(X instanceof xp1.JetStreamApiError&&X.code===xp1.JetStreamApiCodes.NoMessageFound)return null;return Promise.reject(X)}}find($){return this.findStream($)}names($=""){let Z=$?.length?{subject:$}:{},X=(Y)=>{return Y.streams},Q=`${this.prefix}.STREAM.NAMES`;return new Cp1.ListerImpl(Q,X,this,Z)}async get($){let Z=await this.info($);return Promise.resolve(new Om(this,Z))}}fp1.StreamAPIImpl=wd0;class Bd0{_header;smr;static jc;constructor($){this.smr=$}get pending(){return 0}get lastSequence(){return 0}get subject(){return this.smr.message.subject}get seq(){return this.smr.message.seq}get timestamp(){return this.smr.message.time}get time(){return new Date(Date.parse(this.timestamp))}get data(){return this.smr.message.data?this._parse(this.smr.message.data):E9.Empty}get header(){if(!this._header)if(this.smr.message.hdrs){let $=this._parse(this.smr.message.hdrs);this._header=E9.MsgHdrsImpl.decode($)}else this._header=(0,E9.headers)();return this._header}_parse($){let Z=atob($),X=Z.length,Q=new Uint8Array(X);for(let Y=0;Y<X;Y++)Q[Y]=Z.charCodeAt(Y);return Q}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return E9.TD.decode(this.data)}}fp1.StoredMsgImpl=Bd0;class vp1{api;constructor($){this.api=$}get($){return this.api.info($).then((Z)=>{return new Om(this.api,Z)})}}fp1.StreamsImpl=vp1});var Ld0=_((cp1)=>{Object.defineProperty(cp1,"__esModule",{value:!0});cp1.DirectConsumer=cp1.DirectMsgImpl=cp1.DirectStreamAPIImpl=void 0;var Nd6=ff(),gf=ED(),JJ=vY(),gp1=bf(),Od0=HN();class hp1 extends Nd6.BaseApiClientImpl{constructor($,Z){super($,Z)}async getMessage($,Z){if((0,gp1.validateStreamName)($),"start_time"in Z){let{min:H,ok:N}=this.nc.features.get(JJ.Feature.JS_BATCH_DIRECT_GET);if(!N)throw Error(`start_time direct option require server ${H}`)}let X=Z,{last_by_subj:Q}=X;if(Q)X=null;let Y=X?JSON.stringify(X):JJ.Empty,G=this.opts.apiPrefix||"$JS.API",J=Q?`${G}.DIRECT.GET.${$}.${Q}`:`${G}.DIRECT.GET.${$}`,K=await this.nc.request(J,Y,{timeout:this.timeout});if(K.headers?.code!==0){let H=new Od0.JetStreamStatus(K);if(H.isMessageNotFound())return Promise.resolve(null);else return Promise.reject(H.toError())}let W=new e50(K);return Promise.resolve(W)}getBatch($,Z){return Z.batch=Z.batch||1024,this.get($,Z)}getLastMessagesFor($,Z){return this.get($,Z)}get($,Z){Z={...Z};let{min:X,ok:Q}=this.nc.features.get(JJ.Feature.JS_BATCH_DIRECT_GET);if(!Q)return Promise.reject(Error(`batch direct require server ${X}`));(0,gp1.validateStreamName)($);let Y=typeof Z.callback==="function"?Z.callback:null,G=new JJ.QueuedIteratorImpl;function J(L,D){if(L){G.push(()=>{L.err?G.stop(L.err):G.stop()});return}G.push(D)}function K(L,D){let E=Y;if(typeof D==="function"){D();return}E(L,D)}if(Y)G.iterClosed.then((L)=>{W({err:L?L:void 0},{}),U.unsubscribe()});let W=Y?K:J,H=(0,JJ.createInbox)(this.nc.options.inboxPrefix),N=!1,U=this.nc.subscribe(H,{timeout:5000,callback:(L,D)=>{if(L){G.stop(L),U.unsubscribe();return}let E=Od0.JetStreamStatus.maybeParseStatus(D);if(E){if(E.isNoResults())W({},()=>{G.stop()});if(E.isEndOfBatch())W({},()=>{G.stop()});else{let z=E.toError();W({err:z},()=>{G.stop(z)})}return}if(!N)if(typeof D.headers?.get("Nats-Num-Pending")!=="string")U.unsubscribe(),W({},()=>{G.stop()});else N=!0;W(null,new e50(D))}}),w=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${$}`,B=JSON.stringify(Z,(L,D)=>{if((L==="up_to_time"||L==="start_time")&&D instanceof Date)return D.toISOString();return D});return this.nc.publish(w,B,{reply:H}),Promise.resolve(G)}}cp1.DirectStreamAPIImpl=hp1;class e50{data;header;constructor($){if(!$.headers)throw Error("headers expected");this.data=$.data,this.header=$.headers}get subject(){return this.header.last(gf.DirectMsgHeaders.Subject)}get seq(){let $=this.header.last(gf.DirectMsgHeaders.Sequence);return typeof $==="string"?parseInt($):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(gf.DirectMsgHeaders.TimeStamp)}get stream(){return this.header.last(gf.DirectMsgHeaders.Stream)}get lastSequence(){let $=this.header.last(gf.DirectMsgHeaders.LastSequence);return typeof $==="string"?parseInt($):0}get pending(){let $=this.header.last(gf.DirectMsgHeaders.NumPending);return typeof $==="string"?parseInt($):-1}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return JJ.TD.decode(this.data)}}cp1.DirectMsgImpl=e50;function Ud6($){return typeof $==="object"&&"start_time"in $}function Fd6($){return typeof $==="object"&&"max_bytes"in $}class up1{stream;api;cursor;listeners;start;constructor($,Z,X){this.stream=$,this.api=Z,this.cursor={last:0},this.listeners=[],this.start=X}getOptions($){$=$||{};let Z={};if(this.cursor.last===0)if(Ud6(this.start))Z.start_time=this.start.start_time;else Z.seq=this.start.seq||1;else Z.seq=this.cursor.last+1;if(Fd6($))Z.max_bytes=$.max_bytes;else Z.batch=$.batch??100;return Z}status(){let $=new JJ.QueuedIteratorImpl;return this.listeners.push($),$}notify($){if(this.listeners.length>0)(()=>{let Z=[];this.listeners.forEach((X)=>{let Q=X;if(!Q.done)Q.push($);else Z.push(Q)}),this.listeners=this.listeners.filter((X)=>!Z.includes(X))})()}debug(){console.log(this.cursor)}consume($){let Z,X,Q=new JJ.QueuedIteratorImpl;return(async()=>{while(!0){if(this.cursor.pending===0)this.notify({type:"debug",code:0,description:"sleeping for 2500"}),Z=(0,JJ.delay)(2500),await Z;if(Q.done)break;X=(0,JJ.deferred)();let Y=this.getOptions($);this.notify({type:"next",options:Object.assign({},$)}),Y.callback=(J,K)=>{if(J){if(J.err)if(J.err instanceof Od0.JetStreamStatusError)this.notify({type:"debug",code:J.err.code,description:J.err.message});else this.notify({type:"debug",code:0,description:J.err.message});X.resolve()}else if(K.lastSequence>0&&K.lastSequence!==this.cursor.last)G.stop(),X.resolve(),this.notify({type:"reset",name:"direct"});else Q.push(K),Q.received++,this.cursor.last=K.seq,this.cursor.pending=K.pending};let G=await this.api.getBatch(this.stream,Y);Q.iterClosed.then(()=>{G.stop(),Z?.cancel(),X?.resolve()}),await X}})().catch((Y)=>{Q.stop(Y)}),Promise.resolve(Q)}async fetch($){let Z=this.getOptions($),X=new JJ.QueuedIteratorImpl,Q=await this.api.get(this.stream,Object.assign({callback:(Y,G)=>{if(Y)X.push(()=>{Y.err?X.stop(Y.err):X.stop()});else if(G.lastSequence>0&&G.lastSequence!==this.cursor.last)X.push(()=>{X.stop()}),Q.stop();else X.push(G),X.received++,this.cursor.last=G.seq,this.cursor.pending=G.pending}},Z));return X.iterClosed.then(()=>{Q.stop()}),X}async next(){let $=await this.api.getMessage(this.stream,{seq:this.cursor.last+1}),Z=$?.seq;if(Z)this.cursor.last=Z;return $}}cp1.DirectConsumer=up1});var rp1=_((tp1)=>{Object.defineProperty(tp1,"__esModule",{value:!0});tp1.BatchPublisherImpl=tp1.JetStreamClientImpl=tp1.JetStreamManagerImpl=void 0;tp1.startFastIngest=Ld6;tp1.toJetStreamClient=Dd6;tp1.jetstream=Ed0;tp1.jetstreamManager=ip1;tp1.scheduleSpecToHeader=np1;var Dd0=ff(),mp1=Yd0(),u$=vY(),$90=yp1(),yX=qD(),dp1=HN(),Od6=Ld0();function Ld6($,Z,X,Q,Y=5000){let{ackInterval:G,allowGaps:J,inboxPrefix:K,maxOutstandingAcks:W,...H}=Q,N=K??"_INBOX";if(!N||/\s/.test(N)||/[*>]/.test(N))return Promise.reject(Error(`inboxPrefix must be non-empty, no wildcards or whitespace (got "${N}")`));let U={ackInterval:G??10,allowGaps:J,inboxPrefix:N,maxOutstandingAcks:Math.min(3,Math.max(1,W??2))},F=new pp1($,U,Z,Y);return F.start(X,H).then(()=>F)}function Dm($){let Z=$.expect||{},X=$.headers||(0,u$.headers)();if($.msgID)X.set(yX.PubHeaders.MsgIdHdr,$.msgID);if(Z.lastMsgID)X.set(yX.PubHeaders.ExpectedLastMsgIdHdr,Z.lastMsgID);if(Z.streamName)X.set(yX.PubHeaders.ExpectedStreamHdr,Z.streamName);if(typeof Z.lastSequence==="number")X.set(yX.PubHeaders.ExpectedLastSeqHdr,`${Z.lastSequence}`);if(typeof Z.lastSubjectSequence==="number")X.set(yX.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Z.lastSubjectSequence}`);if(Z.lastSubjectSequenceSubject)X.set(yX.PubHeaders.ExpectedLastSubjectSequenceSubjectHdr,Z.lastSubjectSequenceSubject);if($.ttl)X.set(yX.PubHeaders.MessageTTL,`${$.ttl}`);if($.schedule&&$.cancelSchedule)throw Error("schedule and cancelSchedule are mutually exclusive");if($.schedule){let Q=$.schedule;if(Q.specification)X.set(yX.PubHeaders.Schedule,np1(Q.specification));if(Q.target)X.set(yX.PubHeaders.ScheduleTarget,Q.target);if(Q.source)X.set(yX.PubHeaders.ScheduleSource,Q.source);if(Q.ttl)X.set(yX.PubHeaders.ScheduleTTL,Q.ttl);if(Q.timezone)X.set(yX.PubHeaders.ScheduleTimeZone,Q.timezone);if(Q.rollup)X.set(yX.PubHeaders.ScheduleRollup,Q.rollup)}if($.cancelSchedule)X.set(yX.PubHeaders.Scheduler,$.cancelSchedule.scheduleSubject),X.set(yX.PubHeaders.ScheduleNext,"purge");return X}function Dd6($){if(typeof $.nc>"u")return Ed0($);return $}function Ed0($,Z={}){return new jd0($,Z)}async function ip1($,Z={}){let X=new zd0($,Z);if(Z.checkAPI!==!1)try{await X.getAccountInfo()}catch(Q){throw Q}return X}class zd0 extends Dd0.BaseApiClientImpl{streams;consumers;direct;constructor($,Z){super($,Z);this.streams=new $90.StreamAPIImpl($,Z),this.consumers=new mp1.ConsumerAPIImpl($,Z),this.direct=new Od6.DirectStreamAPIImpl($,Z)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return Ed0(this.nc,this.getOptions())}advisories(){let $=new u$.QueuedIteratorImpl;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(Z,X)=>{if(Z)throw Z;try{let Q=this.parseJsResponse(X),Y=Q.type.split("."),G=Y[Y.length-1];$.push({kind:G,data:Q})}catch(Q){$.stop(Q)}}}),$}}tp1.JetStreamManagerImpl=zd0;function np1($){if(typeof $==="string")return $;if($ instanceof Date)return`@at ${$.toISOString()}`;if("at"in $)return`@at ${$.at instanceof Date?$.at.toISOString():$.at}`;if("every"in $)return Ed6($.every),`@every ${$.every}`;if("cron"in $)return $.cron;if("predefined"in $)return $.predefined;throw Error("invalid schedule specification")}function Ed6($){let Z=$.trim(),X=/(\d+(?:\.\d+)?)(ns|us|\u00B5s|ms|s|m|h)/g,Q=0,Y=0,G;while((G=X.exec(Z))!==null){if(G.index!==Y)break;Y+=G[0].length;let J=parseFloat(G[1]),K=G[2];Q+=K==="ns"?J/1e6:K==="us"||K==="\xB5s"?J/1000:K==="ms"?J:K==="s"?J*1000:K==="m"?J*60000:J*3600000}if(Z===""||Y!==Z.length)throw Error(`@every: unrecognized duration format: "${$}"`);if(Q<1000)throw Error("@every interval must be at least 1s")}class jd0 extends Dd0.BaseApiClientImpl{consumers;streams;consumerAPI;streamAPI;constructor($,Z){super($,Z);this.consumerAPI=new mp1.ConsumerAPIImpl($,Z),this.streamAPI=new $90.StreamAPIImpl($,Z),this.consumers=new $90.ConsumersImpl(this.consumerAPI),this.streams=new $90.StreamsImpl(this.streamAPI)}jetstreamManager($){if($===void 0)$=this.opts.checkAPI;let Z=Object.assign({},this.opts,{checkAPI:$});try{(0,u$.createInbox)(Z.watcherPrefix)}catch(X){return Promise.reject(X)}return ip1(this.nc,Z)}get apiPrefix(){return this.prefix}startBatch($,Z,X){let Q=(0,u$.deferred)(),Y=new Pd0(this);return Y.first($,Z,X).then(()=>{Q.resolve(Y)}).catch((G)=>{Q.reject(G)}),Q}async _publish($,Z=u$.Empty,X){if(X=X||{},X={...X},X.cancelSchedule&&X.cancelSchedule.scheduleSubject===$)throw Error("cancelSchedule.scheduleSubject must not equal the publish subject");let Q=Dm(X),Y=X.timeout||this.timeout,G={};if(Y)G.timeout=Y;if(X)G.headers=Q;let{retries:J}=X;J=J||1;let K=(0,u$.backoff)(),W=null;for(let H=0;H<J;H++)try{W=await this.nc.request($,Z,G);break}catch(N){let U=N instanceof u$.RequestError?N:null;if((N instanceof u$.errors.TimeoutError||U?.isNoResponders())&&H+1<J)await(0,u$.delay)(K.backoff(H));else throw U?.isNoResponders()?new dp1.JetStreamNotEnabled("jetstream is not enabled",{cause:N}):N}return W}async publish($,Z=u$.Empty,X){let Q=await this._publish($,Z,X),Y=this.parseJsResponse(Q);if(Y.stream==="")throw new dp1.JetStreamError("invalid ack response");return Y.duplicate=Y.duplicate?Y.duplicate:!1,Y}}tp1.JetStreamClientImpl=jd0;class Pd0{nc;js;id;count;done;constructor($){this.count=0,this.id=u$.nuid.next(),this.js=$,this.nc=this.js.nc,this.done=!1}async first($,Z,X){X=X||{},X.headers=X?.headers||(0,u$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString());let Q=await this.js._publish($,Z,X);if(Q.data.length>0)this.js.parseJsResponse(Q)}add($,Z,X={ack:!1}){if(this.done)throw Error("batch publisher is done");if(X.headers=X?.headers||(0,u$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString()),"ack"in X&&X.ack===!0){let Y=(0,u$.deferred)();return this.js._publish($,Z,{headers:X.headers,timeout:X.timeout}).then((G)=>{if(G.data.length>0)this.js.parseJsResponse(G);Y.resolve()}).catch((G)=>{this.done=!0,Y.reject(G)}),Y}else return this.nc.publish($,Z,{headers:X.headers})}async commit($,Z,X={}){if(this.done)throw Error("batch publisher is done");else this.done=!0;X.headers=X?.headers||(0,u$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString()),X.headers.set("Nats-Batch-Commit","1");let Y=(await this.js._publish($,Z,{headers:X.headers,timeout:X.timeout||0})).json();if(Y.count!==this.count)throw Error("batch didn't contain number of published messages");return Y}}tp1.BatchPublisherImpl=Pd0;var Lm="batch closed",J7={Start:0,Append:1,Final:2,EOB:3,Ping:4};class pp1{batch;nc;batchSubj;gapMode;initialFlow;seq;acked;ackInterval;inboxPrefix;maxOutstandingAcks;defaultTimeout;gapIter;sub;pending;closed;closeErr;startDeferred;closedDeferred;constructor($,Z,X,Q){this.nc=$,this.batchSubj=X,this.gapMode=Z.allowGaps?"ok":"fail",this.initialFlow=Z.ackInterval,this.inboxPrefix=Z.inboxPrefix,this.maxOutstandingAcks=Z.maxOutstandingAcks,this.defaultTimeout=Q,this.batch=u$.nuid.next(),this.seq=0,this.acked=0,this.ackInterval=Z.ackInterval,this.pending=new Map,this.closed=!1,this.startDeferred=(0,u$.deferred)(),this.closedDeferred=(0,u$.deferred)(),this.closedDeferred.catch(()=>{}),this.startDeferred.catch(()=>{});let Y=`${this.inboxPrefix}.${this.batch}.>`;this.sub=this.nc.subscribe(Y,{callback:(G,J)=>this.route(G,J)})}replyFor($,Z){return`${this.inboxPrefix}.${this.batch}.${this.initialFlow}.${this.gapMode}.${Z}.${$}.$FI`}start($,Z){this.seq=1;let X=this.replyFor(J7.Start,1),Q=Z?Dm(Z):void 0;return this.nc.publish(this.batchSubj,$,{reply:X,headers:Q}),this.deadlineOrClose(this.startDeferred,Z?.timeout??this.defaultTimeout)}deadlineOrClose($,Z){return(0,u$.deadline)($,Z).catch((X)=>{if(!this.closed)this.close(X);throw X})}route($,Z){if($){this.close($);return}let X;try{X=(0,Dd0.parseJsResponse)(Z)}catch(J){this.close(J);return}if("batch"in X&&typeof X.batch==="string"){let J=X,K=this.pending.get(Z.subject);if(K&&(K.op===J7.Final||K.op===J7.EOB))K.deferred.resolve(J),this.pending.delete(Z.subject);for(let[,W]of this.pending)if(W.op===J7.Append||W.op===J7.Ping)W.deferred.resolve({batchSeq:W.seq,ackSeq:this.acked});else W.deferred.reject(Error(Lm));this.pending.clear(),this.resolveStart(),this.closedDeferred.resolve(J),this.closed=!0,this.gapIter?.stop(),this.sub.unsubscribe();return}if(X.type==="gap"){if(this.gapIter){let J=X;this.gapIter.push({lastSeq:J.last_seq,seq:J.seq})}return}let Y=X;if(typeof Y.msgs==="number")this.ackInterval=Y.msgs;if(typeof Y.seq==="number"&&Y.seq>this.acked)this.acked=Y.seq;this.resolveStart();let G=this.pending.get(Z.subject);if(G&&(G.op===J7.Append||G.op===J7.Ping))G.deferred.resolve({batchSeq:G.seq,ackSeq:this.acked}),this.pending.delete(Z.subject);for(let[J,K]of this.pending)if(K.op===J7.Append&&K.seq-this.acked<this.ackInterval*this.maxOutstandingAcks)K.deferred.resolve({batchSeq:K.seq,ackSeq:this.acked}),this.pending.delete(J)}resolveStart(){this.startDeferred.resolve()}close($){this.closed=!0,this.closeErr=$;for(let[,Z]of this.pending)Z.deferred.reject($);this.pending.clear(),this.startDeferred.reject($),this.closedDeferred.reject($),this.gapIter?.stop(),this.sub.unsubscribe()}add($,Z,X){if(this.closed)return Promise.reject(Error(Lm));let Q=++this.seq,Y=this.replyFor(J7.Append,Q),G=X?Dm(X):void 0;if(this.nc.publish($,Z,{reply:Y,headers:G}),Q-this.acked<this.ackInterval*this.maxOutstandingAcks)return Promise.resolve({batchSeq:Q,ackSeq:this.acked});let J=(0,u$.deferred)();return this.pending.set(Y,{seq:Q,op:J7.Append,deferred:J}),this.deadlineOrClose(J,X?.timeout??this.defaultTimeout)}last($,Z,X){if(this.closed)return Promise.reject(Error(Lm));let Q=++this.seq,Y=this.replyFor(J7.Final,Q),G=(0,u$.deferred)();this.pending.set(Y,{seq:Q,op:J7.Final,deferred:G});let J=X?Dm(X):void 0;return this.nc.publish($,Z,{reply:Y,headers:J}),this.deadlineOrClose(G,X?.timeout??this.defaultTimeout)}end($){if(this.closed)return Promise.reject(Error(Lm));let Z=++this.seq,X=this.replyFor(J7.EOB,Z),Q=(0,u$.deferred)();this.pending.set(X,{seq:Z,op:J7.EOB,deferred:Q});let Y=$?Dm($):void 0;return this.nc.publish(this.batchSubj,u$.Empty,{reply:X,headers:Y}),this.deadlineOrClose(Q,$?.timeout??this.defaultTimeout)}ping($=this.defaultTimeout){if(this.closed)return Promise.reject(Error(Lm));let Z=this.replyFor(J7.Ping,this.seq),X=this.pending.get(Z);if(X&&X.op===J7.Ping)return(0,u$.deadline)(X.deferred,$);let Q=(0,u$.deferred)();return this.pending.set(Z,{seq:this.seq,op:J7.Ping,deferred:Q}),this.nc.publish(this.batchSubj,u$.Empty,{reply:Z}),this.deadlineOrClose(Q,$)}done(){return this.closedDeferred}gaps(){if(!this.gapIter)this.gapIter=new u$.QueuedIteratorImpl;return this.gapIter}}});var Z90=_((P4)=>{Object.defineProperty(P4,"__esModule",{value:!0});P4.validateStreamName=P4.jserrors=P4.JetStreamStatusError=P4.JetStreamStatus=P4.JetStreamError=P4.JetStreamApiError=P4.JetStreamApiCodes=P4.isMessageNotFound=P4.ListerImpl=P4.StoreCompression=P4.StorageType=P4.RetentionPolicy=P4.ReplayPolicy=P4.PubHeaders=P4.PersistMode=P4.DiscardPolicy=P4.DeliverPolicy=P4.AckPolicy=P4.DirectMsgImpl=P4.BaseApiClientImpl=P4.toJetStreamClient=P4.startFastIngest=P4.jetstreamManager=P4.JetStreamClientImpl=P4.jetstream=P4.RepublishHeaders=P4.JsHeaders=P4.isPushConsumer=P4.isPullConsumer=P4.isOrderedPushConsumerOptions=P4.isBoundPushConsumerOptions=P4.DirectMsgHeaders=P4.AdvisoryKind=void 0;var aF=ED();Object.defineProperty(P4,"AdvisoryKind",{enumerable:!0,get:function(){return aF.AdvisoryKind}});Object.defineProperty(P4,"DirectMsgHeaders",{enumerable:!0,get:function(){return aF.DirectMsgHeaders}});Object.defineProperty(P4,"isBoundPushConsumerOptions",{enumerable:!0,get:function(){return aF.isBoundPushConsumerOptions}});Object.defineProperty(P4,"isOrderedPushConsumerOptions",{enumerable:!0,get:function(){return aF.isOrderedPushConsumerOptions}});Object.defineProperty(P4,"isPullConsumer",{enumerable:!0,get:function(){return aF.isPullConsumer}});Object.defineProperty(P4,"isPushConsumer",{enumerable:!0,get:function(){return aF.isPushConsumer}});Object.defineProperty(P4,"JsHeaders",{enumerable:!0,get:function(){return aF.JsHeaders}});Object.defineProperty(P4,"RepublishHeaders",{enumerable:!0,get:function(){return aF.RepublishHeaders}});var Em=rp1();Object.defineProperty(P4,"jetstream",{enumerable:!0,get:function(){return Em.jetstream}});Object.defineProperty(P4,"JetStreamClientImpl",{enumerable:!0,get:function(){return Em.JetStreamClientImpl}});Object.defineProperty(P4,"jetstreamManager",{enumerable:!0,get:function(){return Em.jetstreamManager}});Object.defineProperty(P4,"startFastIngest",{enumerable:!0,get:function(){return Em.startFastIngest}});Object.defineProperty(P4,"toJetStreamClient",{enumerable:!0,get:function(){return Em.toJetStreamClient}});var qd6=ff();Object.defineProperty(P4,"BaseApiClientImpl",{enumerable:!0,get:function(){return qd6.BaseApiClientImpl}});var Md6=Ld0();Object.defineProperty(P4,"DirectMsgImpl",{enumerable:!0,get:function(){return Md6.DirectMsgImpl}});var FN=qD();Object.defineProperty(P4,"AckPolicy",{enumerable:!0,get:function(){return FN.AckPolicy}});Object.defineProperty(P4,"DeliverPolicy",{enumerable:!0,get:function(){return FN.DeliverPolicy}});Object.defineProperty(P4,"DiscardPolicy",{enumerable:!0,get:function(){return FN.DiscardPolicy}});Object.defineProperty(P4,"PersistMode",{enumerable:!0,get:function(){return FN.PersistMode}});Object.defineProperty(P4,"PubHeaders",{enumerable:!0,get:function(){return FN.PubHeaders}});Object.defineProperty(P4,"ReplayPolicy",{enumerable:!0,get:function(){return FN.ReplayPolicy}});Object.defineProperty(P4,"RetentionPolicy",{enumerable:!0,get:function(){return FN.RetentionPolicy}});Object.defineProperty(P4,"StorageType",{enumerable:!0,get:function(){return FN.StorageType}});Object.defineProperty(P4,"StoreCompression",{enumerable:!0,get:function(){return FN.StoreCompression}});var kd6=o50();Object.defineProperty(P4,"ListerImpl",{enumerable:!0,get:function(){return kd6.ListerImpl}});var kD=HN();Object.defineProperty(P4,"isMessageNotFound",{enumerable:!0,get:function(){return kD.isMessageNotFound}});Object.defineProperty(P4,"JetStreamApiCodes",{enumerable:!0,get:function(){return kD.JetStreamApiCodes}});Object.defineProperty(P4,"JetStreamApiError",{enumerable:!0,get:function(){return kD.JetStreamApiError}});Object.defineProperty(P4,"JetStreamError",{enumerable:!0,get:function(){return kD.JetStreamError}});Object.defineProperty(P4,"JetStreamStatus",{enumerable:!0,get:function(){return kD.JetStreamStatus}});Object.defineProperty(P4,"JetStreamStatusError",{enumerable:!0,get:function(){return kD.JetStreamStatusError}});Object.defineProperty(P4,"jserrors",{enumerable:!0,get:function(){return kD.jserrors}});var Sd6=bf();Object.defineProperty(P4,"validateStreamName",{enumerable:!0,get:function(){return Sd6.validateStreamName}})});var SD=_((Z9)=>{Object.defineProperty(Z9,"__esModule",{value:!0});Z9.StoreCompression=Z9.StorageType=Z9.RetentionPolicy=Z9.RepublishHeaders=Z9.ReplayPolicy=Z9.PubHeaders=Z9.PersistMode=Z9.JsHeaders=Z9.JetStreamError=Z9.JetStreamApiError=Z9.JetStreamApiCodes=Z9.isPushConsumer=Z9.isPullConsumer=Z9.DiscardPolicy=Z9.DirectMsgHeaders=Z9.DeliverPolicy=Z9.AdvisoryKind=Z9.AckPolicy=Z9.jetstreamManager=Z9.jetstream=void 0;var ap1=Z90();Object.defineProperty(Z9,"jetstream",{enumerable:!0,get:function(){return ap1.jetstream}});Object.defineProperty(Z9,"jetstreamManager",{enumerable:!0,get:function(){return ap1.jetstreamManager}});var _Z=Z90();Object.defineProperty(Z9,"AckPolicy",{enumerable:!0,get:function(){return _Z.AckPolicy}});Object.defineProperty(Z9,"AdvisoryKind",{enumerable:!0,get:function(){return _Z.AdvisoryKind}});Object.defineProperty(Z9,"DeliverPolicy",{enumerable:!0,get:function(){return _Z.DeliverPolicy}});Object.defineProperty(Z9,"DirectMsgHeaders",{enumerable:!0,get:function(){return _Z.DirectMsgHeaders}});Object.defineProperty(Z9,"DiscardPolicy",{enumerable:!0,get:function(){return _Z.DiscardPolicy}});Object.defineProperty(Z9,"isPullConsumer",{enumerable:!0,get:function(){return _Z.isPullConsumer}});Object.defineProperty(Z9,"isPushConsumer",{enumerable:!0,get:function(){return _Z.isPushConsumer}});Object.defineProperty(Z9,"JetStreamApiCodes",{enumerable:!0,get:function(){return _Z.JetStreamApiCodes}});Object.defineProperty(Z9,"JetStreamApiError",{enumerable:!0,get:function(){return _Z.JetStreamApiError}});Object.defineProperty(Z9,"JetStreamError",{enumerable:!0,get:function(){return _Z.JetStreamError}});Object.defineProperty(Z9,"JsHeaders",{enumerable:!0,get:function(){return _Z.JsHeaders}});Object.defineProperty(Z9,"PersistMode",{enumerable:!0,get:function(){return _Z.PersistMode}});Object.defineProperty(Z9,"PubHeaders",{enumerable:!0,get:function(){return _Z.PubHeaders}});Object.defineProperty(Z9,"ReplayPolicy",{enumerable:!0,get:function(){return _Z.ReplayPolicy}});Object.defineProperty(Z9,"RepublishHeaders",{enumerable:!0,get:function(){return _Z.RepublishHeaders}});Object.defineProperty(Z9,"RetentionPolicy",{enumerable:!0,get:function(){return _Z.RetentionPolicy}});Object.defineProperty(Z9,"StorageType",{enumerable:!0,get:function(){return _Z.StorageType}});Object.defineProperty(Z9,"StoreCompression",{enumerable:!0,get:function(){return _Z.StoreCompression}})});import{mkdir as _d6,readdir as xd6,readFile as Ad0,stat as X90,unlink as vd6,writeFile as fd6}from"fs/promises";import{createHmac as bd6}from"crypto";import{dirname as yd6,join as zm}from"path";function Td0($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return zm(gd6,Z)}function hf($,Z){return zm(Td0($),bK(Z))}class nK{orgId;baseUrl;constructor($,Z){this.orgId=$;this.baseUrl=Z}async getBytesOrPresign($,Z){let X=hf(this.orgId,$),Q=await X90(X),Y=SZ($);if(Q.size>Z.presignWhenLargerThan)return{error:"FILE_TOO_LARGE",size:Q.size,maxInlineSize:Z.presignWhenLargerThan,presignedUrl:await this.presignedGetUrl($),contentType:Y};let G=await Ad0(X),J=x$0(Y);return{content:J?new TextDecoder().decode(G):Buffer.from(G).toString("base64"),contentType:Y,encoding:J?"utf-8":"base64",size:Q.size,lastModified:Q.mtime}}async getBytes($){let Z=await Ad0(hf(this.orgId,$));return new Uint8Array(Z)}async put($,Z,X){let Q=hf(this.orgId,$);return await _d6(yd6(Q),{recursive:!0}),await fd6(Q,typeof Z==="string"?Buffer.from(Z,"utf-8"):Z),{key:$}}async list($){let Z=$?.prefix?zm(Td0(this.orgId),bK($.prefix)):Td0(this.orgId),X;try{X=await xd6(Z,{withFileTypes:!0})}catch{return{objects:[],isTruncated:!1}}let Q=$?.maxKeys??1000,Y=$?.prefix,G=X.filter((K)=>K.isFile());if($?.delimiter){let K=[],W=X.filter((B)=>B.isDirectory());for(let B of W){let L=Y?`${Y}/${B.name}/`:`${B.name}/`;K.push(L)}K.sort();let H=Q,N=K.slice(0,H);H-=N.length;let U=G.slice(0,H),F=K.length+G.length;return{objects:await Promise.all(U.map(async(B)=>{let L=await X90(zm(Z,B.name));return{key:Y?`${Y}/${B.name}`:B.name,size:L.size,lastModified:L.mtime}})),isTruncated:F>Q,commonPrefixes:N.length>0?N:void 0}}return{objects:await Promise.all(G.slice(0,Q).map(async(K)=>{let W=await X90(zm(Z,K.name));return{key:Y?`${Y}/${K.name}`:K.name,size:W.size,lastModified:W.mtime}})),isTruncated:G.length>Q}}async delete($){await vd6(hf(this.orgId,$))}async head($){let Z=await X90(hf(this.orgId,$));return{contentType:SZ($),size:Z.size,lastModified:Z.mtime}}async presignedGetUrl($,Z,X){if(X?.requireFetchable)throw Error("object storage returned a not fetchable (data:) URL; configure real S3/R2/MinIO for large-payload offload");let Q=hf(this.orgId,$),Y=await Ad0(Q),G=SZ($),J=Buffer.from(Y).toString("base64");return`data:${G};base64,${J}`}async presignedPutUrl($,Z=3600){if(!this.baseUrl)throw Error("baseUrl required for presigned PUT URLs in dev mode");let X=bK($),Q=Math.floor(Date.now()/1000)+Z,Y=J1().encryptionKey||"dev-secret",G=`${this.orgId}:${X}:${Q}:PUT`,J=bd6("sha256",Y).update(G).digest("hex"),K=new URL(`/api/dev-assets/${this.orgId}/${X}`,this.baseUrl);return K.searchParams.set("expires",Q.toString()),K.searchParams.set("signature",J),K.searchParams.set("method","PUT"),K.toString()}}var gd6="./data/assets";var jm=O(()=>{yK();c8()});function uf($){return hd6.test($)&&$!=="."&&$!==".."}function xZ($){if(!uf($))throw Error(`Invalid org-fs volume name: ${JSON.stringify($)}`)}function vZ($){return bK($)}function cf($){let Z=$.lastIndexOf("/");return Z===-1?"":$.slice(0,Z)}function sF($){let Z=cf($);if(Z==="")return[];let X=Z.split("/"),Q=[],Y="";for(let G of X)Y=Y===""?G:`${Y}/${G}`,Q.push(Y);return Q}function pK($,Z){return`${sp1}/${$}/${Z}`}function ep1($){return`${sp1}/${$}/`}var hd6,sp1="_fs";var Pm=O(()=>{yK();hd6=/^[A-Za-z0-9_.-]{1,128}$/});import{createHmac as Id0,randomBytes as Rd0,scrypt as ud6,timingSafeEqual as $t1}from"crypto";import{promisify as cd6}from"util";async function Xt1($){let Z=Rd0(16),X=await Zt1($,Z,ld6);return`scrypt$${Z.toString("hex")}$${X.toString("hex")}`}async function Qt1($,Z){let X=Z.split("$");if(X.length!==3||X[0]!=="scrypt")return!1;let Q=Buffer.from(X[1],"hex"),Y=Buffer.from(X[2],"hex");if(Q.length===0||Y.length===0)return!1;let G;try{G=await Zt1($,Q,Y.length)}catch{return!1}return Y.length===G.length&&$t1(Y,G)}function Yt1(){return Rd0(16).toString("hex")}function Gt1(){if(Q90)return Q90;let $;try{let Z=J1();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return Q90=$?Buffer.from($):Rd0(32),Q90}function Jt1($){let Z=Buffer.from(JSON.stringify($)).toString("base64url"),X=Id0("sha256",Gt1()).update(Z).digest("base64url");return`${Z}.${X}`}function Kt1($,Z){let X=$.indexOf(".");if(X<0)return null;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(Id0("sha256",Gt1()).update(Q).digest("base64url"));if(Y.length!==G.length||!$t1(Y,G))return null;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return null}if(J.o!==Z.org||J.v!==Z.volume||J.s!==Z.secret||typeof J.e!=="number"||J.e<Z.nowSec)return null;return{govPath:J.p}}function qd0($,Z,X){return`fsu_${Id0("sha256","fsunlock-name").update(`${$}:${Z}:${X}`).digest("hex").slice(0,16)}`}var ld6=64,Zt1,Q90=null;var Md0=O(()=>{c8();Zt1=cd6(ud6)});import{createHash as dd6}from"crypto";function Wt1($){return dd6("sha256").update($).digest("hex")}class tK{storage;manifest;organizationId;maxFileBytes;volumeQuotaBytes;constructor($,Z,X,Q={}){this.storage=$;this.manifest=Z;this.organizationId=X;this.maxFileBytes=Q.maxFileBytes??nd6,this.volumeQuotaBytes=Q.volumeQuotaBytes??pd6}async usage($){return xZ($),this.manifest.usage(this.organizationId,$)}async stat($,Z){return xZ($),this.manifest.get(this.organizationId,$,vZ(Z))}async listDir($,Z){return xZ($),this.manifest.listDir(this.organizationId,$,vZ(Z))}async read($,Z){let X=await this.requireFile($,Z);return this.storage.getBytes(pK($,X.path))}async setShareMode($,Z,X,Q){xZ($);let Y=vZ(Z),G=await this.manifest.get(this.organizationId,$,Y);if(!G)throw new VD(`No such path: ${Y}`);let J=null,K=null;if(X==="password"){if(!Q.password)throw new KJ("A password is required to set password mode");J=await Xt1(Q.password),K=Yt1()}let W=await this.manifest.setShareMode({organizationId:this.organizationId,volume:$,path:G.path,readPublic:X!=="private",passwordHash:J,shareSecret:K,actor:Q.actor});if(!W)throw new VD(`No such path: ${G.path}`);return W}async setReadPublic($,Z,X,Q){return this.setShareMode($,Z,X?"public":"private",{actor:Q.actor})}async resolveReadAccess($,Z){xZ($);let X=vZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")return{access:"private"};let Y=await this.manifest.resolveGoverningShare({organizationId:this.organizationId,volume:$,candidatePaths:[X,...sF(X)]});if(!Y)return{access:"private"};if(!Y.passwordHash)return{access:"public"};return{access:"password",govPath:Y.path,secret:Y.secret??"",passwordHash:Y.passwordHash}}async isPubliclyReadable($,Z){xZ($);let X=vZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")return!1;if(Q.readPublic)return!0;return this.manifest.hasPublicAncestorDir(this.organizationId,$,sF(X))}async inheritsPublic($,Z){return xZ($),this.manifest.hasPublicAncestorDir(this.organizationId,$,sF(vZ(Z)))}async childrenInheritPublic($,Z){xZ($);let X=vZ(Z);if(X==="")return!1;return this.manifest.hasPublicAncestorDir(this.organizationId,$,[...sF(X),X])}async recentWithEffectivePublic($){return this.withEffectivePublic(await this.recent($))}async searchWithEffectivePublic($,Z,X,Q){return this.withEffectivePublic(await this.manifest.searchFiles({organizationId:this.organizationId,query:$,limit:Z,volumes:X,pathPrefix:Q?vZ(Q):void 0}))}async withEffectivePublic($){let Z=new Map;for(let Q of $){let Y=Z.get(Q.volume);if(!Y)Y=new Set,Z.set(Q.volume,Y);for(let G of sF(Q.path))Y.add(G)}let X=new Map;return await Promise.all([...Z].map(async([Q,Y])=>{let G=await this.manifest.publicDirPaths({organizationId:this.organizationId,volume:Q,paths:[...Y]});X.set(Q,new Set(G))})),$.map((Q)=>{let Y=X.get(Q.volume),G=!!Y&&sF(Q.path).some((J)=>Y.has(J));return{...Q,effectivePublic:Q.readPublic||G}})}async presignRead($,Z,X){let Q=await this.requireFile($,Z);return this.storage.presignedGetUrl(pK($,Q.path),X)}async write($,Z,X,Q){xZ($);let Y=vZ(Z);if(Y==="")throw new KJ("Cannot write to the volume root");let G=typeof X==="string"?new TextEncoder().encode(X):X;if(G.byteLength>this.maxFileBytes)throw new Am(`File exceeds the ${this.maxFileBytes}-byte per-file limit`);let[J,K]=await Promise.all([Q.skipVolumeQuota?Promise.resolve(null):this.manifest.usage(this.organizationId,$),this.manifest.get(this.organizationId,$,Y)]);if(K?.kind==="dir")throw new KJ(`Cannot write a file at ${Y}: a directory exists there`);if(J){let W=K?.kind==="file"?K.size:0;if(J.bytes-W+G.byteLength>this.volumeQuotaBytes)throw new Am(`Write would exceed the volume quota of ${this.volumeQuotaBytes} bytes`)}return await this.ensureDirs($,Y,Q.actor),await this.storage.put(pK($,Y),G,{contentType:Q.contentType??SZ(Y)}),this.manifest.putFile({organizationId:this.organizationId,volume:$,path:Y,parent:cf(Y),contentHash:Wt1(G),size:G.byteLength,actor:Q.actor,threadId:Q.threadId??null})}async mkdir($,Z,X){xZ($);let Q=vZ(Z);if(Q==="")return;if((await this.manifest.get(this.organizationId,$,Q))?.kind==="file")throw new KJ(`Cannot create a directory at ${Q}: a file exists there`);await this.ensureDirs($,Q,X.actor),await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Q,parent:cf(Q),actor:X.actor})}async delete($,Z,X){xZ($);let Q=vZ(Z);if(Q==="")throw new KJ("Cannot delete the volume root");let Y=await this.manifest.get(this.organizationId,$,Q);if(!Y)return;if(Y.kind==="dir"){let G=await this.manifest.listSubtreeFiles(this.organizationId,$,Q);await Promise.all(G.map((J)=>this.storage.delete(pK($,J.path)))),await this.manifest.tombstoneSubtree(this.organizationId,$,Q,X.actor);return}await this.storage.delete(pK($,Q)),await this.manifest.tombstone(this.organizationId,$,Q,X.actor)}async move($,Z,X,Q){xZ($);let Y=vZ(Z),G=vZ(X);if(Y===""||G==="")throw new KJ("Cannot move the volume root");if(G===Y||G.startsWith(`${Y}/`))throw new KJ(`Cannot move ${Y} onto itself or into its own subtree`);let J=await this.manifest.get(this.organizationId,$,Y);if(!J)throw new VD(`No such path: ${Y}`);if(J.kind==="file"){let H=await this.storage.getBytes(pK($,Y));await this.write($,G,H,{...Q,skipVolumeQuota:!0}),await this.delete($,Y,Q);return}let[K,W]=await Promise.all([this.manifest.listSubtreeFiles(this.organizationId,$,Y),this.manifest.listSubtreeDirs(this.organizationId,$,Y)]);await this.mkdir($,G,Q);for(let H of K){let N=H.path.slice(Y.length+1),U=await this.storage.getBytes(pK($,H.path));await this.write($,`${G}/${N}`,U,{...Q,skipVolumeQuota:!0})}for(let H of W){let N=H.path.slice(Y.length+1);await this.mkdir($,`${G}/${N}`,Q)}await this.delete($,Y,Q)}async filesExist($,Z){xZ($);let X=await this.manifest.liveFilePaths({organizationId:this.organizationId,volume:$,paths:Z.map((Q)=>vZ(Q))});return new Set(X)}async recent($){return this.manifest.recentFiles({organizationId:this.organizationId,limit:$})}async changes($,Z,X=md6){xZ($);let Q=Z||"0";if(!/^\d+$/.test(Q))throw new KJ(`Invalid cursor: ${Z}`);let Y=await this.manifest.changesSince({organizationId:this.organizationId,volume:$,sinceSeq:Q,limit:X}),G=Y.at(-1);return{entries:Y,cursor:G?G.seq:Z||"0",hasMore:Y.length>=X}}async latestSeq($){return xZ($),this.manifest.latestSeq({organizationId:this.organizationId,volume:$})}async backfillFromStorage($,Z){xZ($);let X=ep1($),Q,Y=0;do{let G=await this.storage.list({prefix:X,maxKeys:id6,continuationToken:Q});for(let J of G.objects){let K=J.key.slice(X.length);if(K==="")continue;await this.ensureDirs($,K,Z.actor);let W=await this.storage.getBytes(J.key);await this.manifest.putFile({organizationId:this.organizationId,volume:$,path:K,parent:cf(K),contentHash:Wt1(W),size:W.byteLength,actor:Z.actor}),Y++}Q=G.isTruncated?G.nextContinuationToken:void 0}while(Q);return Y}async requireFile($,Z){xZ($);let X=vZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")throw new VD(`No such file: ${X}`);return Q}async ensureDirs($,Z,X){for(let Q of sF(Z))await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Q,parent:cf(Q),actor:X})}}var md6=500,id6=1000,nd6=524288000,pd6=10737418240,Am,KJ,VD;var lf=O(()=>{yK();Pm();Md0();Am=class Am extends Error{constructor($){super($);this.name="OrgFsQuotaError"}};KJ=class KJ extends Error{constructor($){super($);this.name="OrgFsValidationError"}};VD=class VD extends Error{constructor($){super($);this.name="OrgFsNotFoundError"}}});import{z as wN}from"zod";function eF($){return $.startsWith(Ht1)}function $w($){return`${Ht1}${$}`}function sd6($){let Z=new Map(rd6.map((X)=>[X.set,X]));if($)try{for(let X of ad6.parse(JSON.parse($)))Z.set(X.set,X)}catch(X){console.warn("[org-fs] invalid ORGFS_PUBLIC_SETS \u2014 using built-in defaults only",X)}return[...Z.values()]}function cG(){return sd6(J1().orgFsPublicSetsJson)}function Tm($){let Z=vX(),X=Z?SY(Z,BN):new nK(BN,$.baseUrl);return new tK(X,$.storage.orgFsEntries,BN)}var BN="org_orgfs_public_skills",Ht1="public-",td6,od6,rd6,ad6;var df=O(()=>{c8();uF();jm();lf();td6=wN.object({from:wN.string(),to:wN.string().optional()}),od6=wN.object({set:wN.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/),repo:wN.string().regex(/^[\w.-]+\/[\w.-]+$/),ref:wN.string().min(1),paths:wN.array(td6).min(1)}),rd6=[{set:"core",repo:"decocms/studio",ref:"main",paths:[{from:"packages/sandbox/image/skills"}]},{set:"storefront",repo:"decocms/storefront-skills",ref:"main",paths:[{from:".claude-seo/skills"},{from:".claude-performance/skills"},{from:".claude-deco/skills"}]}],ad6=wN.array(od6).refine(($)=>new Set($.map((Z)=>Z.set)).size===$.length,{message:"duplicate set names"})});import{sql as CD}from"kysely";function kd0($){if($===null)return null;return $ instanceof Date?$.toISOString():String($)}function WJ($){return{organizationId:$.organization_id,volume:$.volume,path:$.path,parent:$.parent,kind:$.kind,contentHash:$.content_hash,size:Number($.size),seq:String($.seq),deletedAt:kd0($.deleted_at),createdBy:$.created_by,createdAt:kd0($.created_at)??"",updatedBy:$.updated_by,updatedAt:kd0($.updated_at)??"",threadId:$.thread_id,readPublic:$.read_public,shareMode:!$.read_public?"private":$.share_password_hash?"password":"public"}}class Rm{db;constructor($){this.db=$}async putFile($){let Z=new Date,X=$.threadId??null,Q=await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z,thread_id:X}).onConflict((Y)=>Y.columns(["organization_id","volume","path"]).doUpdateSet({kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:Y90,read_public:CD`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`,thread_id:CD`coalesce(cast(${X} as text), org_fs_entry.thread_id)`})).returning(HJ).executeTakeFirstOrThrow();return WJ(Q)}async putDir($){let Z=new Date;await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"dir",content_hash:null,size:0,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z}).onConflict((X)=>X.columns(["organization_id","volume","path"]).where("org_fs_entry.deleted_at","is not",null).doUpdateSet({kind:"dir",content_hash:null,size:0,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:Y90,read_public:CD`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`})).execute()}async get($,Z,X){let Q=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("path","=",X).where("deleted_at","is",null).select(HJ).executeTakeFirst();return Q?WJ(Q):null}async listDir($,Z,X){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("parent","=",X).where("deleted_at","is",null).select(HJ).orderBy("path","asc").execute()).map((Y)=>WJ(Y))}async listVolumeDirs($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).select(HJ).execute()).map((Q)=>WJ(Q))}async listVolumeFiles($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select(HJ).execute()).map((Q)=>WJ(Q))}async listSubtreeFiles($,Z,X){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).where("path","like",`${Im(X)}/%`).select(HJ).execute()).map((Y)=>WJ(Y))}async listSubtreeDirs($,Z,X){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).where("path","like",`${Im(X)}/%`).select(HJ).execute()).map((Y)=>WJ(Y))}async tombstone($,Z,X,Q){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Q,updated_at:new Date,seq:Y90}).where("organization_id","=",$).where("volume","=",Z).where("path","=",X).where("deleted_at","is",null).execute()}async tombstoneSubtree($,Z,X,Q){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Q,updated_at:new Date,seq:Y90}).where("organization_id","=",$).where("volume","=",Z).where("deleted_at","is",null).where((Y)=>Y.or([Y("path","=",X),Y("path","like",`${Im(X)}/%`)])).execute()}async setShareMode($){let Z=new Date,X=await this.db.updateTable("org_fs_entry").set({read_public:$.readPublic,share_password_hash:$.passwordHash,share_secret:$.shareSecret,updated_by:$.actor,updated_at:Z}).where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("path","=",$.path).where("deleted_at","is",null).returning(HJ).executeTakeFirst();return X?WJ(X):null}async resolveGoverningShare($){if($.candidatePaths.length===0)return null;let Z=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.candidatePaths).select(["path","share_password_hash","share_secret"]).execute();if(Z.length===0)return null;Z.sort((Q,Y)=>Y.path.length-Q.path.length);let X=Z[0];return{path:X.path,passwordHash:X.share_password_hash,secret:X.share_secret}}async hasPublicAncestorDir($,Z,X){if(X.length===0)return!1;return!!await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",X).select("path").limit(1).executeTakeFirst()}async publicDirPaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.paths).select("path").execute()).map((X)=>X.path)}async usage($,Z){let X=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select((Q)=>[Q.fn.countAll().as("files"),Q.fn.coalesce(Q.fn.sum("size"),CD`0`).as("bytes")]).executeTakeFirst();return{files:Number(X?.files??0),bytes:Number(X?.bytes??0)}}async liveFilePaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","file").where("deleted_at","is",null).where("path","in",$.paths).select(["path"]).execute()).map((X)=>X.path)}async recentFiles($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).select(HJ).orderBy("seq","desc").limit($.limit).execute()).map((X)=>WJ(X))}async searchFiles($){if($.volumes&&$.volumes.length===0)return[];let Z=Im($.query),X=this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).where("path","ilike",`%${Z}%`);if($.volumes)X=X.where("volume","in",$.volumes);if($.pathPrefix)X=X.where("path","like",`${Im($.pathPrefix)}/%`);return(await X.select(HJ).orderBy("seq","desc").limit($.limit).execute()).map((Y)=>WJ(Y))}async changesSince($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("seq",">",CD`cast(${$.sinceSeq} as bigint)`).select(HJ).orderBy("seq","asc").limit($.limit).execute()).map((X)=>WJ(X))}async latestSeq($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).select(CD`max(seq)`.as("seq")).executeTakeFirst())?.seq??"0"}}function Im($){return $.replace(/[\\%_]/g,"\\$&")}var HJ,Y90;var Sd0=O(()=>{HJ=["organization_id","volume","path","parent","kind","content_hash","size","seq","deleted_at","created_by","created_at","updated_by","updated_at","thread_id","read_public","share_password_hash"],Y90=CD`nextval('org_fs_entry_seq')`});import{createHash as ed6}from"crypto";import{gunzipSync as $m6}from"zlib";function Cd0($,Z,X){let Q=Z,Y=Z+X;while(Q<Y&&$[Q]!==0)Q++;return new TextDecoder().decode($.subarray(Z,Q))}function Xm6($,Z,X){let Q=Cd0($,Z,X).trim();return Q===""?0:Number.parseInt(Q,8)}function Qm6($){let Z=new Map,X=0,Q=null,Y=null;while(X+512<=$.length){let G=$.subarray(X,X+512);if(X+=512,G.every((F)=>F===0))break;let J=Cd0(G,0,100),K=Cd0(G,345,155);if(K)J=`${K}/${J}`;let W=Xm6(G,124,12),H=String.fromCharCode(G[156]??0),N=$.subarray(X,X+W);if(X+=Math.ceil(W/512)*512,H==="L"){let F=new TextDecoder().decode(N),w=F.indexOf("\x00");Q=w===-1?F:F.slice(0,w);continue}if(H==="x"){let F=new TextDecoder().decode(N);Y=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(F)?.[1]??null;continue}if(H==="g")continue;let U=Y??Q??J;if(Q=null,Y=null,H==="0"||H==="\x00"||H==="")Z.set(U,new Uint8Array(N))}return Z}async function Ym6($,Z){let X=`https://codeload.github.com/${$}/tar.gz/${encodeURIComponent(Z)}`,Q=await fetch(X,{signal:AbortSignal.timeout(60000)});if(!Q.ok)throw Error(`tarball fetch failed for ${$}@${Z}: HTTP ${Q.status}`);let Y=Number(Q.headers.get("content-length")??0);if(Y>G90)throw Error(`tarball for ${$}@${Z} declares ${Y} bytes (cap ${G90})`);let G=new Uint8Array(await Q.arrayBuffer());if(G.length>G90)throw Error(`tarball for ${$}@${Z} exceeds ${G90} bytes`);let J=Qm6(new Uint8Array($m6(G,{maxOutputLength:Zm6}))),K=new Map;for(let[W,H]of J){let N=W.indexOf("/");if(N===-1)continue;let U=W.slice(N+1);if(U)K.set(U,H)}return K}function Gm6($,Z){let X=new Map;for(let{from:Q,to:Y}of Z){let G=Q===""?"":`${Q.replace(/\/+$/,"")}/`;for(let[J,K]of $){if(!J.startsWith(G))continue;let W=J.slice(G.length);if(!W)continue;let H=vZ(Y?`${Y}/${W}`:W);if(H)X.set(H,K)}}return X}function Jm6($,Z){let X=new Set;for(let G of $){let J=G.split("/");for(let K=1;K<J.length;K++)X.add(J.slice(0,K).join("/"))}let Q=[...Z].filter((G)=>!X.has(G)).sort((G,J)=>G.length-J.length),Y=[];for(let G of Q)if(!Y.some((J)=>G.startsWith(`${J}/`)))Y.push(G);return Y}function Km6($){return ed6("sha256").update($).digest("hex")}async function Wm6($,Z,X){let Q=vX(),Y=Q?SY(Q,BN):new nK(BN,X.baseUrl),G=new Rm($),J=new tK(Y,G,BN),K=$w(Z.set),W=Gm6(await Ym6(Z.repo,Z.ref),Z.paths),H=new Map((await G.listVolumeFiles(BN,K)).map((B)=>[B.path,B.contentHash]));if(W.size===0&&H.size>0)throw Error(`set "${Z.set}" resolved 0 files from ${Z.repo}@${Z.ref} `+`(check paths config) \u2014 refusing to delete the ${H.size} existing files`);let N=0;for(let B of H.keys()){if(W.has(B))continue;await J.delete(K,B,{actor:Vd0}),N++}let U=await G.listVolumeDirs(BN,K);for(let B of Jm6(W.keys(),U.map((L)=>L.path)))await J.delete(K,B,{actor:Vd0});let F=0,w=0;for(let[B,L]of W){if(H.get(B)===Km6(L)){w++;continue}await J.write(K,B,L,{actor:Vd0,contentType:SZ(B),skipVolumeQuota:!0}),F++}return{set:Z.set,written:F,deleted:N,unchanged:w}}async function _d0($,Z,X){try{return await Wm6($,Z,X)}catch(Q){return{set:Z.set,error:Q instanceof Error?Q.message:String(Q)}}}async function Nt1($,Z){let X=[];for(let Q of cG())X.push(await _d0($,Q,Z));return X}var Vd0="system:skill-set-sync",G90=209715200,Zm6=1073741824;var xd0=O(()=>{Sd0();jm();uF();yK();lf();Pm();df()});import{DBOS as J90,SchedulerMode as Hm6}from"@dbos-inc/dbos-sdk";function Ut1($){vd0=$}function Um6(){if(!vd0)throw Error("[org-fs] public-sets sync runtime not initialized \u2014 setPublicSetsSyncRuntime() must run before the workflow fires");return vd0}async function Fm6($,Z){for(let X of cG()){let Q=await J90.runStep(()=>{let Y=Um6();return _d0(Y.db,X,{baseUrl:Y.baseUrl})},{name:`syncPublicSet:${X.set}`});if("error"in Q)console.warn(`[org-fs] public set "${Q.set}" sync failed: ${Q.error}`);else if(Q.written||Q.deleted)console.log(`[org-fs] public set "${Q.set}" synced: +${Q.written} -${Q.deleted} (=${Q.unchanged})`)}}function Ft1(){if(qm)return;qm=J90.registerWorkflow(Fm6,{name:"publicSetsSyncWorkflow"}),J90.registerScheduled(qm,{name:"publicSetsSyncWorkflow",crontab:Nm6,mode:Hm6.ExactlyOncePerIntervalWhenActive})}async function wt1(){if(cG().length===0||!qm)return;let $=new Date,Z=`public-sets-sync-boot:${$.toISOString().slice(0,13)}`;await J90.startWorkflow(qm,{workflowID:Z})($,$)}var Nm6="4-59/10 * * * *",vd0=null,qm=null;var Bt1=O(()=>{df();xd0()});import{z as q8}from"zod";var wm6,Bm6,Om6,Lm6,Dm6,Em6,zm6,jm6,Pm6,Am6,Tm6,Im6,_D;var Mm=O(()=>{wm6=q8.object({prefix:q8.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:q8.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:q8.string().optional().describe("Token for pagination from previous response"),delimiter:q8.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Bm6=q8.object({objects:q8.array(q8.object({key:q8.string().describe("Object key/path"),size:q8.number().describe("Object size in bytes"),lastModified:q8.string().describe("Last modified timestamp"),etag:q8.string().describe("Entity tag for the object")})),nextContinuationToken:q8.string().optional().describe("Token for fetching next page of results"),isTruncated:q8.boolean().describe("Whether there are more results available"),commonPrefixes:q8.array(q8.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Om6=q8.object({key:q8.string().describe("Object key/path to get metadata for")}),Lm6=q8.object({contentType:q8.string().optional().describe("MIME type of the object"),contentLength:q8.number().describe("Size of the object in bytes"),lastModified:q8.string().describe("Last modified timestamp"),etag:q8.string().describe("Entity tag for the object"),metadata:q8.record(q8.string(),q8.string()).optional().describe("Custom metadata key-value pairs")}),Dm6=q8.object({key:q8.string().describe("Object key/path to generate URL for"),expiresIn:q8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),Em6=q8.object({url:q8.string().describe("Presigned URL for downloading the object"),expiresIn:q8.number().describe("Expiration time in seconds that was used")}),zm6=q8.object({key:q8.string().describe("Object key/path for the upload"),expiresIn:q8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:q8.string().optional().describe("MIME type for the object being uploaded")}),jm6=q8.object({url:q8.string().describe("Presigned URL for uploading the object"),expiresIn:q8.number().describe("Expiration time in seconds that was used")}),Pm6=q8.object({key:q8.string().describe("Object key/path to delete")}),Am6=q8.object({success:q8.boolean().describe("Whether the deletion was successful"),key:q8.string().describe("The key that was deleted")}),Tm6=q8.object({keys:q8.array(q8.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Im6=q8.object({deleted:q8.array(q8.string()).describe("Array of successfully deleted keys"),errors:q8.array(q8.object({key:q8.string(),message:q8.string()})).describe("Array of errors for failed deletions")}),_D=[{name:"LIST_OBJECTS",inputSchema:wm6,outputSchema:Bm6},{name:"GET_OBJECT_METADATA",inputSchema:Om6,outputSchema:Lm6},{name:"GET_PRESIGNED_URL",inputSchema:Dm6,outputSchema:Em6},{name:"PUT_PRESIGNED_URL",inputSchema:zm6,outputSchema:jm6},{name:"DELETE_OBJECT",inputSchema:Pm6,outputSchema:Am6},{name:"DELETE_OBJECTS",inputSchema:Tm6,outputSchema:Im6}]});import*as x from"zod/v4";function Vt1($){if($.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${$.params.ref.type}`)}function Ct1($){if($.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${$.params.ref.type}`)}var Zw="2025-11-25",Ot1="2025-03-26",Xw,Qw="io.modelcontextprotocol/related-task",W90="2.0",GZ,Lt1,Dt1,M85,Rm6,qm6,fd0,bY,km,Et1=($)=>km.safeParse($).success,K7,lG,dG,W7,H90,zt1,oK=($)=>zt1.safeParse($).success,jt1,Pt1=($)=>jt1.safeParse($).success,bd0,NJ=($)=>bd0.safeParse($).success,b1,yd0,nf=($)=>yd0.safeParse($).success,yY,k85,ON,Mm6,N90,km6,Sm,mf,At1,Sm6,Vm6,Cm6,_m6,xm6,vm6,U90,gd0=($)=>U90.safeParse($).success,fm6,hd0,F90,Tt1=($)=>F90.safeParse($).success,w90,bm6,ym6,B90,gm6,Vm,Cm,hm6,_m,LN,um6,xm,O90,L90,D90,S85,E90,z90,j90,It1,Rt1,qt1,ud0,Mt1,vm,pf,kt1,cm6,Yw,cd0,Gw,ld0,dd0,lm6,tf,md0,id0,dm6,mm6,im6,nm6,pm6,tm6,om6,rm6,Jw,nd0,am6,of,pd0,td0,od0,sm6,em6,$i6,rd0,Zi6,ad0,sd0,Xi6,Qi6,P90,rf,fm,rK,V85,Yi6,Kw,ed0,St1,bm,Gi6,$m0,Ji6,Ki6,Wi6,Hi6,Ni6,Ui6,Fi6,K90,wi6,Bi6,Zm0,xD,ym,Oi6,Li6,Di6,Ei6,zi6,ji6,Pi6,Ai6,Ti6,Ii6,Ri6,qi6,Mi6,ki6,Si6,Xm0,Vi6,Ci6,Ww,_i6,xi6,vi6,A90,Qm0,fi6,bi6,Ym0,yi6,C85,_85,x85,v85,f85,b85,M1,_t1;var X9=O(()=>{Xw=[Zw,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],GZ=x.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Lt1=x.union([x.string(),x.number().int()]),Dt1=x.string(),M85=x.looseObject({ttl:x.number().optional(),pollInterval:x.number().optional()}),Rm6=x.object({ttl:x.number().optional()}),qm6=x.object({taskId:x.string()}),fd0=x.looseObject({progressToken:Lt1.optional(),[Qw]:qm6.optional()}),bY=x.object({_meta:fd0.optional()}),km=bY.extend({task:Rm6.optional()}),K7=x.object({method:x.string(),params:bY.loose().optional()}),lG=x.object({_meta:fd0.optional()}),dG=x.object({method:x.string(),params:lG.loose().optional()}),W7=x.looseObject({_meta:fd0.optional()}),H90=x.union([x.string(),x.number().int()]),zt1=x.object({jsonrpc:x.literal(W90),id:H90,...K7.shape}).strict(),jt1=x.object({jsonrpc:x.literal(W90),...dG.shape}).strict(),bd0=x.object({jsonrpc:x.literal(W90),id:H90,result:W7}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(b1||(b1={}));yd0=x.object({jsonrpc:x.literal(W90),id:H90.optional(),error:x.object({code:x.number().int(),message:x.string(),data:x.unknown().optional()})}).strict(),yY=x.union([zt1,jt1,bd0,yd0]),k85=x.union([bd0,yd0]),ON=W7.strict(),Mm6=lG.extend({requestId:H90.optional(),reason:x.string().optional()}),N90=dG.extend({method:x.literal("notifications/cancelled"),params:Mm6}),km6=x.object({src:x.string(),mimeType:x.string().optional(),sizes:x.array(x.string()).optional(),theme:x.enum(["light","dark"]).optional()}),Sm=x.object({icons:x.array(km6).optional()}),mf=x.object({name:x.string(),title:x.string().optional()}),At1=mf.extend({...mf.shape,...Sm.shape,version:x.string(),websiteUrl:x.string().optional(),description:x.string().optional()}),Sm6=x.intersection(x.object({applyDefaults:x.boolean().optional()}),x.record(x.string(),x.unknown())),Vm6=x.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},x.intersection(x.object({form:Sm6.optional(),url:GZ.optional()}),x.record(x.string(),x.unknown()).optional())),Cm6=x.looseObject({list:GZ.optional(),cancel:GZ.optional(),requests:x.looseObject({sampling:x.looseObject({createMessage:GZ.optional()}).optional(),elicitation:x.looseObject({create:GZ.optional()}).optional()}).optional()}),_m6=x.looseObject({list:GZ.optional(),cancel:GZ.optional(),requests:x.looseObject({tools:x.looseObject({call:GZ.optional()}).optional()}).optional()}),xm6=x.object({experimental:x.record(x.string(),GZ).optional(),sampling:x.object({context:GZ.optional(),tools:GZ.optional()}).optional(),elicitation:Vm6.optional(),roots:x.object({listChanged:x.boolean().optional()}).optional(),tasks:Cm6.optional(),extensions:x.record(x.string(),GZ).optional()}),vm6=bY.extend({protocolVersion:x.string(),capabilities:xm6,clientInfo:At1}),U90=K7.extend({method:x.literal("initialize"),params:vm6}),fm6=x.object({experimental:x.record(x.string(),GZ).optional(),logging:GZ.optional(),completions:GZ.optional(),prompts:x.object({listChanged:x.boolean().optional()}).optional(),resources:x.object({subscribe:x.boolean().optional(),listChanged:x.boolean().optional()}).optional(),tools:x.object({listChanged:x.boolean().optional()}).optional(),tasks:_m6.optional(),extensions:x.record(x.string(),GZ).optional()}),hd0=W7.extend({protocolVersion:x.string(),capabilities:fm6,serverInfo:At1,instructions:x.string().optional()}),F90=dG.extend({method:x.literal("notifications/initialized"),params:lG.optional()}),w90=K7.extend({method:x.literal("ping"),params:bY.optional()}),bm6=x.object({progress:x.number(),total:x.optional(x.number()),message:x.optional(x.string())}),ym6=x.object({...lG.shape,...bm6.shape,progressToken:Lt1}),B90=dG.extend({method:x.literal("notifications/progress"),params:ym6}),gm6=bY.extend({cursor:Dt1.optional()}),Vm=K7.extend({params:gm6.optional()}),Cm=W7.extend({nextCursor:Dt1.optional()}),hm6=x.enum(["working","input_required","completed","failed","cancelled"]),_m=x.object({taskId:x.string(),status:hm6,ttl:x.union([x.number(),x.null()]),createdAt:x.string(),lastUpdatedAt:x.string(),pollInterval:x.optional(x.number()),statusMessage:x.optional(x.string())}),LN=W7.extend({task:_m}),um6=lG.merge(_m),xm=dG.extend({method:x.literal("notifications/tasks/status"),params:um6}),O90=K7.extend({method:x.literal("tasks/get"),params:bY.extend({taskId:x.string()})}),L90=W7.merge(_m),D90=K7.extend({method:x.literal("tasks/result"),params:bY.extend({taskId:x.string()})}),S85=W7.loose(),E90=Vm.extend({method:x.literal("tasks/list")}),z90=Cm.extend({tasks:x.array(_m)}),j90=K7.extend({method:x.literal("tasks/cancel"),params:bY.extend({taskId:x.string()})}),It1=W7.merge(_m),Rt1=x.object({uri:x.string(),mimeType:x.optional(x.string()),_meta:x.record(x.string(),x.unknown()).optional()}),qt1=Rt1.extend({text:x.string()}),ud0=x.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mt1=Rt1.extend({blob:ud0}),vm=x.enum(["user","assistant"]),pf=x.object({audience:x.array(vm).optional(),priority:x.number().min(0).max(1).optional(),lastModified:x.iso.datetime({offset:!0}).optional()}),kt1=x.object({...mf.shape,...Sm.shape,uri:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string()),size:x.optional(x.number()),annotations:pf.optional(),_meta:x.optional(x.looseObject({}))}),cm6=x.object({...mf.shape,...Sm.shape,uriTemplate:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string()),annotations:pf.optional(),_meta:x.optional(x.looseObject({}))}),Yw=Vm.extend({method:x.literal("resources/list")}),cd0=Cm.extend({resources:x.array(kt1)}),Gw=Vm.extend({method:x.literal("resources/templates/list")}),ld0=Cm.extend({resourceTemplates:x.array(cm6)}),dd0=bY.extend({uri:x.string()}),lm6=dd0,tf=K7.extend({method:x.literal("resources/read"),params:lm6}),md0=W7.extend({contents:x.array(x.union([qt1,Mt1]))}),id0=dG.extend({method:x.literal("notifications/resources/list_changed"),params:lG.optional()}),dm6=dd0,mm6=K7.extend({method:x.literal("resources/subscribe"),params:dm6}),im6=dd0,nm6=K7.extend({method:x.literal("resources/unsubscribe"),params:im6}),pm6=lG.extend({uri:x.string()}),tm6=dG.extend({method:x.literal("notifications/resources/updated"),params:pm6}),om6=x.object({name:x.string(),description:x.optional(x.string()),required:x.optional(x.boolean())}),rm6=x.object({...mf.shape,...Sm.shape,description:x.optional(x.string()),arguments:x.optional(x.array(om6)),_meta:x.optional(x.looseObject({}))}),Jw=Vm.extend({method:x.literal("prompts/list")}),nd0=Cm.extend({prompts:x.array(rm6)}),am6=bY.extend({name:x.string(),arguments:x.record(x.string(),x.string()).optional()}),of=K7.extend({method:x.literal("prompts/get"),params:am6}),pd0=x.object({type:x.literal("text"),text:x.string(),annotations:pf.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),td0=x.object({type:x.literal("image"),data:ud0,mimeType:x.string(),annotations:pf.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),od0=x.object({type:x.literal("audio"),data:ud0,mimeType:x.string(),annotations:pf.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),sm6=x.object({type:x.literal("tool_use"),name:x.string(),id:x.string(),input:x.record(x.string(),x.unknown()),_meta:x.record(x.string(),x.unknown()).optional()}),em6=x.object({type:x.literal("resource"),resource:x.union([qt1,Mt1]),annotations:pf.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),$i6=kt1.extend({type:x.literal("resource_link")}),rd0=x.union([pd0,td0,od0,$i6,em6]),Zi6=x.object({role:vm,content:rd0}),ad0=W7.extend({description:x.string().optional(),messages:x.array(Zi6)}),sd0=dG.extend({method:x.literal("notifications/prompts/list_changed"),params:lG.optional()}),Xi6=x.object({title:x.string().optional(),readOnlyHint:x.boolean().optional(),destructiveHint:x.boolean().optional(),idempotentHint:x.boolean().optional(),openWorldHint:x.boolean().optional()}),Qi6=x.object({taskSupport:x.enum(["required","optional","forbidden"]).optional()}),P90=x.object({...mf.shape,...Sm.shape,description:x.string().optional(),inputSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),GZ).optional(),required:x.array(x.string()).optional()}).catchall(x.unknown()),outputSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),GZ).optional(),required:x.array(x.string()).optional()}).catchall(x.unknown()).optional(),annotations:Xi6.optional(),execution:Qi6.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),rf=Vm.extend({method:x.literal("tools/list")}),fm=Cm.extend({tools:x.array(P90)}),rK=W7.extend({content:x.array(rd0).default([]),structuredContent:x.record(x.string(),x.unknown()).optional(),isError:x.boolean().optional()}),V85=rK.or(W7.extend({toolResult:x.unknown()})),Yi6=km.extend({name:x.string(),arguments:x.record(x.string(),x.unknown()).optional()}),Kw=K7.extend({method:x.literal("tools/call"),params:Yi6}),ed0=dG.extend({method:x.literal("notifications/tools/list_changed"),params:lG.optional()}),St1=x.object({autoRefresh:x.boolean().default(!0),debounceMs:x.number().int().nonnegative().default(300)}),bm=x.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Gi6=bY.extend({level:bm}),$m0=K7.extend({method:x.literal("logging/setLevel"),params:Gi6}),Ji6=lG.extend({level:bm,logger:x.string().optional(),data:x.unknown()}),Ki6=dG.extend({method:x.literal("notifications/message"),params:Ji6}),Wi6=x.object({name:x.string().optional()}),Hi6=x.object({hints:x.array(Wi6).optional(),costPriority:x.number().min(0).max(1).optional(),speedPriority:x.number().min(0).max(1).optional(),intelligencePriority:x.number().min(0).max(1).optional()}),Ni6=x.object({mode:x.enum(["auto","required","none"]).optional()}),Ui6=x.object({type:x.literal("tool_result"),toolUseId:x.string().describe("The unique identifier for the corresponding tool call."),content:x.array(rd0).default([]),structuredContent:x.object({}).loose().optional(),isError:x.boolean().optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Fi6=x.discriminatedUnion("type",[pd0,td0,od0]),K90=x.discriminatedUnion("type",[pd0,td0,od0,sm6,Ui6]),wi6=x.object({role:vm,content:x.union([K90,x.array(K90)]),_meta:x.record(x.string(),x.unknown()).optional()}),Bi6=km.extend({messages:x.array(wi6),modelPreferences:Hi6.optional(),systemPrompt:x.string().optional(),includeContext:x.enum(["none","thisServer","allServers"]).optional(),temperature:x.number().optional(),maxTokens:x.number().int(),stopSequences:x.array(x.string()).optional(),metadata:GZ.optional(),tools:x.array(P90).optional(),toolChoice:Ni6.optional()}),Zm0=K7.extend({method:x.literal("sampling/createMessage"),params:Bi6}),xD=W7.extend({model:x.string(),stopReason:x.optional(x.enum(["endTurn","stopSequence","maxTokens"]).or(x.string())),role:vm,content:Fi6}),ym=W7.extend({model:x.string(),stopReason:x.optional(x.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(x.string())),role:vm,content:x.union([K90,x.array(K90)])}),Oi6=x.object({type:x.literal("boolean"),title:x.string().optional(),description:x.string().optional(),default:x.boolean().optional()}),Li6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),minLength:x.number().optional(),maxLength:x.number().optional(),format:x.enum(["email","uri","date","date-time"]).optional(),default:x.string().optional()}),Di6=x.object({type:x.enum(["number","integer"]),title:x.string().optional(),description:x.string().optional(),minimum:x.number().optional(),maximum:x.number().optional(),default:x.number().optional()}),Ei6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),enum:x.array(x.string()),default:x.string().optional()}),zi6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),oneOf:x.array(x.object({const:x.string(),title:x.string()})),default:x.string().optional()}),ji6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),enum:x.array(x.string()),enumNames:x.array(x.string()).optional(),default:x.string().optional()}),Pi6=x.union([Ei6,zi6]),Ai6=x.object({type:x.literal("array"),title:x.string().optional(),description:x.string().optional(),minItems:x.number().optional(),maxItems:x.number().optional(),items:x.object({type:x.literal("string"),enum:x.array(x.string())}),default:x.array(x.string()).optional()}),Ti6=x.object({type:x.literal("array"),title:x.string().optional(),description:x.string().optional(),minItems:x.number().optional(),maxItems:x.number().optional(),items:x.object({anyOf:x.array(x.object({const:x.string(),title:x.string()}))}),default:x.array(x.string()).optional()}),Ii6=x.union([Ai6,Ti6]),Ri6=x.union([ji6,Pi6,Ii6]),qi6=x.union([Ri6,Oi6,Li6,Di6]),Mi6=km.extend({mode:x.literal("form").optional(),message:x.string(),requestedSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),qi6),required:x.array(x.string()).optional()})}),ki6=km.extend({mode:x.literal("url"),message:x.string(),elicitationId:x.string(),url:x.string().url()}),Si6=x.union([Mi6,ki6]),Xm0=K7.extend({method:x.literal("elicitation/create"),params:Si6}),Vi6=lG.extend({elicitationId:x.string()}),Ci6=dG.extend({method:x.literal("notifications/elicitation/complete"),params:Vi6}),Ww=W7.extend({action:x.enum(["accept","decline","cancel"]),content:x.preprocess(($)=>$===null?void 0:$,x.record(x.string(),x.union([x.string(),x.number(),x.boolean(),x.array(x.string())])).optional())}),_i6=x.object({type:x.literal("ref/resource"),uri:x.string()}),xi6=x.object({type:x.literal("ref/prompt"),name:x.string()}),vi6=bY.extend({ref:x.union([xi6,_i6]),argument:x.object({name:x.string(),value:x.string()}),context:x.object({arguments:x.record(x.string(),x.string()).optional()}).optional()}),A90=K7.extend({method:x.literal("completion/complete"),params:vi6});Qm0=W7.extend({completion:x.looseObject({values:x.array(x.string()).max(100),total:x.optional(x.number().int()),hasMore:x.optional(x.boolean())})}),fi6=x.object({uri:x.string().startsWith("file://"),name:x.string().optional(),_meta:x.record(x.string(),x.unknown()).optional()}),bi6=K7.extend({method:x.literal("roots/list"),params:bY.optional()}),Ym0=W7.extend({roots:x.array(fi6)}),yi6=dG.extend({method:x.literal("notifications/roots/list_changed"),params:lG.optional()}),C85=x.union([w90,U90,A90,$m0,of,Jw,Yw,Gw,tf,mm6,nm6,Kw,rf,O90,D90,E90,j90]),_85=x.union([N90,B90,F90,yi6,xm]),x85=x.union([ON,xD,ym,Ww,Ym0,L90,z90,LN]),v85=x.union([w90,Zm0,Xm0,bi6,O90,D90,E90,j90]),f85=x.union([N90,B90,Ki6,tm6,id0,ed0,sd0,xm,Ci6]),b85=x.union([ON,hd0,Qm0,ad0,nd0,cd0,ld0,md0,rK,fm,L90,z90,LN]);M1=class M1 extends Error{constructor($,Z,X){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=X,this.name="McpError"}static fromError($,Z,X){if($===b1.UrlElicitationRequired&&X){let Q=X;if(Q.elicitations)return new _t1(Q.elicitations,Z)}return new M1($,Z,X)}};_t1=class _t1 extends M1{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(b1.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});import{z as D8}from"zod";function aK($){return $!==null&&$!==void 0&&"command"in $}function af($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function sf($){return`virtual://${$}`}var gi6,xt1,hi6,ui6,ci6,i7,T90,I90;var vt1=O(()=>{X9();gi6=D8.object({authorizationEndpoint:D8.string().url(),tokenEndpoint:D8.string().url(),introspectionEndpoint:D8.string().url().optional(),clientId:D8.string(),clientSecret:D8.string().optional(),scopes:D8.array(D8.string()),grantType:D8.enum(["authorization_code","client_credentials"])}),xt1=D8.object({type:D8.literal("object"),properties:D8.record(D8.string(),D8.unknown()).optional(),required:D8.array(D8.string()).optional()}).catchall(D8.unknown()),hi6=P90.extend({inputSchema:xt1,outputSchema:xt1.optional()}),ui6=D8.object({headers:D8.record(D8.string(),D8.string()).optional()}),ci6=D8.object({command:D8.string().describe("Command to run (e.g., 'npx', 'node')"),args:D8.array(D8.string()).optional().describe("Command arguments"),cwd:D8.string().optional().describe("Working directory"),envVars:D8.record(D8.string(),D8.string()).optional().describe("Environment variables (encrypted in storage)")}),i7=D8.object({id:D8.string().describe("Unique identifier for the connection"),title:D8.string().describe("Human-readable name for the connection"),created_at:D8.string().describe("When the connection was created"),updated_at:D8.string().describe("When the connection was last updated"),created_by:D8.string().describe("User ID who created the connection"),updated_by:D8.string().optional().describe("User ID who last updated the connection"),organization_id:D8.string().describe("Organization ID this connection belongs to"),description:D8.string().nullable().describe("Description of the connection"),icon:D8.string().nullable().describe("Icon URL for the connection"),app_name:D8.string().nullable().describe("Associated app name"),app_id:D8.string().nullable().describe("Associated app ID"),slug:D8.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:D8.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:D8.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:D8.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:D8.union([ci6,ui6]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:gi6.nullable().describe("OAuth configuration"),configuration_state:D8.record(D8.string(),D8.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:D8.array(D8.string()).nullable().optional().describe("Configuration scopes"),metadata:D8.record(D8.string(),D8.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:D8.array(hi6).nullable().describe("Discovered tools from MCP"),bindings:D8.array(D8.string()).nullable().describe("Detected bindings"),status:D8.enum(["active","inactive","error"]).describe("Current status")}),T90=i7.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}).extend({icon:D8.string().nullish()}),I90=i7.partial()});import{z as c0}from"zod";function Jm0($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let X=$?.homeTile;return X?[X]:[]}function Hm0($){return $==="cluster"?"agent-sandbox":$}function lt1($){let Z=pi6.parse($);return Nm0.parse({...Z,sandboxProviderKind:Z.sandboxProviderKind?Hm0(Z.sandboxProviderKind):void 0})}function UJ($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,X={};for(let[Q,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;if(Q!=="cluster"&&Q!=="agent-sandbox"&&Q!=="user-desktop")continue;let G=Hm0(Q);try{if(Q==="cluster"&&X[G])continue;X[G]=lt1(Y)}catch{}}return X}function Um0($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[X,Q]of Object.entries($)){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Y={};for(let[G,J]of Object.entries(Q)){let K=UJ(J);if(Object.keys(K).length>0)Y[G]=K}if(Object.keys(Y).length>0)Z[X]=Y}return Z}var gm,yt1,li6,gt1,ht1,ft1,Gm0,R90,bt1,di6,ut1,mi6,Km0,Wm0,ii6,ni6,ct1,Nm0,pi6,q90,ti6,Fm0,oi6,wm0,n7,Bm0,M90,k90;var dt1=O(()=>{gm=c0.object({connection_id:c0.string().describe("Connection ID"),selected_tools:c0.array(c0.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:c0.array(c0.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:c0.array(c0.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),yt1=gm.extend({selected_tools:gm.shape.selected_tools.optional(),selected_resources:gm.shape.selected_resources.optional(),selected_prompts:gm.shape.selected_prompts.optional()}),li6=c0.object({connectionId:c0.string(),toolName:c0.string(),label:c0.string(),icon:c0.string().nullable().optional()}),gt1=c0.object({id:c0.string().describe("Stable id; used as React key and ?tab= value"),title:c0.string().describe("Tab label"),icon:c0.string().optional().describe("Optional lucide icon name"),view:c0.object({type:c0.literal("ext-app"),appId:c0.string(),args:c0.record(c0.string(),c0.unknown()).optional()})}),ht1=c0.object({defaultMainView:c0.object({type:c0.string(),id:c0.string().optional(),toolName:c0.string().optional()}).nullable().optional(),chatDefaultOpen:c0.boolean().nullable().optional(),cmsDefaultOpen:c0.boolean().nullable().optional(),tabs:c0.array(gt1).optional()}),ft1=c0.object({tileId:c0.string().optional(),connectionId:c0.string().optional().describe("Connection that owns the resource \u2014 the host opens a direct MCP client to this connection so the iframe can call tools by their bare names."),resourceUri:c0.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),toolName:c0.string().optional().describe("Tool name \u2014 identifies which tool's inputSchema to display when editing tile props."),toolInput:c0.record(c0.string(),c0.unknown()).optional().describe("User-configured input props passed to MCPAppRenderer when rendering the tile."),minHeight:c0.number().int().positive().optional(),maxHeight:c0.number().int().positive().optional()}),Gm0=c0.object({banner:c0.string().nullable().optional(),bannerColor:c0.string().nullable().optional(),icon:c0.string().nullable().optional(),themeColor:c0.string().nullable().optional(),pinnedViews:c0.array(li6).nullable().optional(),layout:ht1.nullable().optional(),homeTile:ft1.nullable().optional(),homeTiles:c0.array(ft1).nullable().optional(),homePrompts:c0.array(c0.string()).nullable().optional()});R90=/^[A-Za-z_][A-Za-z0-9_]*$/,bt1=c0.string().min(1).regex(R90,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),di6=c0.discriminatedUnion("kind",[c0.object({key:bt1,kind:c0.literal("literal"),value:c0.string()}),c0.object({key:bt1,kind:c0.literal("secret"),secretId:c0.string().min(1)})]),ut1=/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/,mi6=c0.object({host:c0.string().min(1).regex(ut1).describe("Submodule host, e.g. 'github.com' (bare hostname, no scheme)."),secretId:c0.string().min(1).describe("Vault secret id holding the PAT used to fetch this host.")}),Km0=c0.object({selected:c0.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:c0.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:c0.string().nullable().optional().describe("Optional path (relative to repo root) to the directory containing package.json. Null/absent means repo root. Forwarded as `application.packageManager.path` to the daemon config."),env:c0.array(di6).nullable().optional().describe("Env vars injected on every SANDBOX_START. Literal entries inline their value; secret entries store a secretId that Studio resolves via the credential vault before posting /_sandbox/config."),submoduleCredentials:c0.array(mi6).nullable().optional().describe("Git submodule credentials injected on every SANDBOX_START. Each entry maps a host to a vault secret (PAT) that Studio resolves before posting /_sandbox/config; the daemon uses it to authenticate `git submodule update` for submodules on that host.")}),Wm0=c0.object({url:c0.string().describe("GitHub repository URL"),owner:c0.string().describe("Repository owner"),name:c0.string().describe("Repository name"),installationId:c0.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:c0.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials.")}),ii6=c0.enum(["agent-sandbox","user-desktop"]),ni6=c0.enum(["agent-sandbox","user-desktop","cluster"]);ct1={sandboxHandle:c0.string().describe("Provider-specific handle"),previewUrl:c0.string().nullable().describe("URL where the sandbox's iframe-proxied UI is served, or null when the sandbox has no dev server (blank / tool sandboxes)."),sandboxApiUrl:c0.string().nullable().optional().describe("Daemon's public URL \u2014 what cluster\u2192daemon RPCs target. Equal to previewUrl for user-desktop; null/absent for the agent-sandbox provider (routes through hosted ingress)."),sandboxProviderKind:ii6.optional(),createdAt:c0.number().optional().describe("Epoch ms the entry was first written by SANDBOX_START. Used by the booting overlay to show a stable elapsed timer that survives browser reloads. Optional for backward compatibility with entries written before this field existed."),startedWith:c0.object({packageManager:c0.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:c0.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:c0.string().nullable().optional().describe("metadata.runtime.path at the time of SANDBOX_START")}).optional().describe("Snapshot of metadata.runtime fields (selected/port/path) used at SANDBOX_START. The Preview tab compares the live metadata.runtime against this to decide if a restart is required to apply changes.")},Nm0=c0.object(ct1),pi6=c0.object({...ct1,sandboxProviderKind:ni6.optional()});q90=c0.record(c0.string().describe("userId"),c0.record(c0.string().describe("branch"),c0.record(c0.string().describe("sandboxProviderKind"),Nm0)));ti6=c0.object({id:c0.string().describe("Stable identifier for this knowledge file"),name:c0.string().describe("File name shown in the UI"),kind:c0.enum(["file","skill"]).optional().describe("'file' (a single document) or 'skill' (a Claude Code skill folder containing SKILL.md). Defaults to 'file'."),volume:c0.string().describe("Org filesystem (Library) volume the file lives in"),path:c0.string().describe("Path within the volume"),url:c0.string().describe("Same-origin URL to read the file (display/download)"),contentType:c0.string().nullable().optional().describe("MIME type, used to decide whether to inline the content"),size:c0.number().nullable().optional().describe("File size in bytes"),addedAt:c0.string().describe("ISO timestamp when the file was attached")}),Fm0=c0.array(ti6).nullable().optional().describe("Files attached to the agent as reference knowledge. Surfaced in the system prompt: small text documents are inlined, others are listed as retrievable references."),oi6=c0.enum(["smart","code-review","open"]),wm0=oi6.nullable().optional().describe("Controls when this code agent's changes may be published directly vs. requiring PR review. 'smart' (default) uses AI to judge per change; 'code-review' requires review for any code; 'open' allows direct publish always."),n7=c0.object({id:c0.string().describe("Unique identifier"),title:c0.string().describe("Human-readable name"),description:c0.string().nullable().describe("Description"),icon:c0.string().nullable().describe("Icon URL"),created_at:c0.string().describe("Creation timestamp"),updated_at:c0.string().describe("Last update timestamp"),created_by:c0.string().describe("User ID who created this item"),updated_by:c0.string().optional().describe("User ID who last updated this item"),organization_id:c0.string().describe("Organization ID this item belongs to"),status:c0.enum(["active","inactive"]).describe("Current status"),pinned:c0.boolean().describe("Whether this space is pinned to the sidebar"),metadata:c0.object({instructions:c0.string().nullable().describe("Instructions also used as system prompt"),enabled_plugins:c0.array(c0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:c0.array(c0.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:c0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:Gm0.nullable().optional().describe("UI customization settings"),githubRepo:Wm0.nullable().optional().describe("Linked GitHub repository"),runtime:Km0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:q90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:Fm0,siteSlug:c0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:wm0,productionUrl:c0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:c0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title.")}).loose().describe("Metadata"),connections:c0.array(gm).describe("Connections with their selected tools, resources, and prompts")}),Bm0=c0.object({title:c0.string().min(1).max(120).describe("Short label shown on the chip"),description:c0.string().max(280).optional().describe("One-line subtitle shown under the title"),text:c0.string().min(1).describe("The message sent to the agent when the prompt is clicked")}),M90=c0.object({title:c0.string().min(1).max(255).describe("Name for the virtual MCP"),description:c0.string().nullable().optional().describe("Optional description"),icon:c0.string().nullish().describe("Optional icon URL"),status:c0.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:c0.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:c0.object({instructions:c0.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:c0.array(c0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:c0.array(c0.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:c0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:Gm0.nullable().optional().describe("UI customization settings"),githubRepo:Wm0.nullable().optional().describe("Linked GitHub repository"),runtime:Km0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:q90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:Fm0,siteSlug:c0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:wm0,productionUrl:c0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:c0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title.")}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:c0.array(yt1).describe("Connections to include/exclude (can be empty for exclusion mode)"),prompts:c0.array(Bm0).optional().describe("Optional kickstart prompts to seed on the agent. Each becomes a clickable conversation starter (icebreaker) on the agent. Author them from the agent's role and the tools it will have so they're coherent and immediately useful.")}),k90=c0.object({title:c0.string().min(1).max(255).optional().describe("New name"),description:c0.string().nullable().optional().describe("New description (null to clear)"),icon:c0.string().nullish().describe("New icon URL"),status:c0.enum(["active","inactive"]).optional().describe("New status"),pinned:c0.boolean().optional().describe("Pin/unpin from sidebar"),metadata:c0.object({instructions:c0.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:c0.array(c0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:c0.array(c0.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:c0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:Gm0.nullable().optional().describe("UI customization settings"),githubRepo:Wm0.nullable().optional().describe("Linked GitHub repository"),runtime:Km0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:q90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:Fm0,siteSlug:c0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:wm0,productionUrl:c0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:c0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title.")}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:c0.array(yt1).optional().describe("New connections (replaces existing)"),prompts:c0.array(Bm0).optional().describe("Replace the agent's kickstart prompts with this full set. Omit to leave them unchanged; pass an empty array to remove all. Each becomes a clickable conversation starter (icebreaker).")})});function vD($){return ri6.has($)}var p7,ri6,S90;var mt1=O(()=>{p7=["deco","anthropic","openrouter","llmapi","google","openai-compatible"],ri6=new Set(p7);S90=[...p7,"claude-code","codex"]});function Om0($,Z){return{id:crypto.randomUUID(),type:hm.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function V90($,Z){return{id:crypto.randomUUID(),type:hm.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function sK($,Z,X){return{id:crypto.randomUUID(),type:hm.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...X?.messageId!==void 0&&{message_id:X.messageId},...X?.virtualMcpId!==void 0&&{virtual_mcp_id:X.virtualMcpId},...X?.createdBy!==void 0&&{created_by:X.createdBy},...X?.triggerId!==void 0&&{trigger_id:X.triggerId},...X?.title!==void 0&&{title:X.title},...X?.branch!==void 0&&{branch:X.branch},...X?.createdAt!==void 0&&{created_at:X.createdAt},...X?.updatedAt!==void 0&&{updated_at:X.updatedAt},...X?.metadata!==void 0&&{metadata:X.metadata}},time:new Date().toISOString()}}var it1,ai6,hm,si6;var nt1=O(()=>{it1=["in_progress","requires_action","failed","completed"],ai6=[...it1,"expired"],hm={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},si6=Object.values(hm)});var C90=O(()=>{vt1();dt1();mt1();nt1()});function tt1($){return{id:p4.REGISTRY($),title:"Deco Store",description:"Official deco MCP registry with curated integrations",connection_type:"HTTP",connection_url:"https://studio.decocms.com/org/deco/registry/mcp",icon:"https://assets.decocache.com/decocms/00ccf6c3-9e13-4517-83b0-75ab84554bb9/596364c63320075ca58483660156b6d9de9b526e.png",app_name:"deco-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function ot1(){return{id:"community-registry",title:"MCP Registry",description:"Community MCP registry with thousands of handy MCPs",connection_type:"HTTP",connection_url:"https://sites-registry.deco.site/mcp",icon:"https://assets.decocache.com/decocms/cd7ca472-0f72-463a-b0de-6e44bdd0f9b4/mcp.png",app_name:"mcp-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function rt1($,Z){return{id:p4.SELF(Z),title:"Deco CMS",description:"The MCP for the CMS API",connection_type:"HTTP",connection_url:`${$}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}function at1($,Z){return{id:p4.DEV_ASSETS(Z),title:"Local Files",description:"Local file storage for development. Files are stored in /data/assets/.",connection_type:"HTTP",connection_url:`${$}/mcp/dev-assets`,icon:"https://api.iconify.design/lucide:folder.svg?color=%23888",app_name:"@deco/dev-assets-mcp",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isFixed:!0,devOnly:!0,type:"dev-assets"}}}function gY($){return{is(Z){if(!Z)return null;if(!Z.startsWith($))return null;return Z.slice($.length)||null},get(Z){return`${$}${Z}`}}}function st1($){return{id:$.id,organization_id:$.organizationId,title:$.title,description:$.description,icon:$.icon,status:"active",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),created_by:"system",updated_by:void 0,metadata:{instructions:$.instructions??null,...$.ui?{ui:$.ui}:{}},pinned:!1,connections:[]}}function Dm0($){return st1({id:fD($),organizationId:$,title:"Super Agent",description:"Default agent that aggregates all organization connections",icon:ei6,ui:{layout:{defaultMainView:{type:"overview"},chatDefaultOpen:!0}}})}function Qo1($){return st1({id:$n6($),organizationId:$,title:"Brand context setup",description:"Guided onboarding agent that extracts brand context from a website URL.",icon:"https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",instructions:Zn6})}function Jo1($,Z,X="https://reports.decocms.com/api/v2/mcp"){return{id:p4.COMMERCE_DISCOVERY($),title:"Store Report",description:"Your store's report and diagnostics",connection_type:"HTTP",connection_url:X,icon:"https://github.com/decocms.png",app_name:"commerce-discovery",app_id:null,connection_token:Z,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!1,type:"commerce-discovery"}}}function Ko1($,Z=p4.COMMERCE_DISCOVERY($)){return{title:"Report Agent",description:"Ask anything about your store's report",icon:"https://github.com/decocms.png",status:"active",pinned:!0,metadata:{type:"commerce-discovery",isDefault:!1,ui:{pinnedViews:[{connectionId:Z,toolName:"get_my_diagnostic",label:"Report",icon:"https://github.com/decocms.png"}],layout:{defaultMainView:{type:"ext-apps",id:Z,toolName:"get_my_diagnostic"},chatDefaultOpen:!0}}},connections:[{connection_id:Z,selected_tools:["get_my_diagnostic"],selected_resources:null,selected_prompts:null}]}}function Wo1($){if(!$)return!1;return Object.values(DN).some((Z)=>Z.is($)!==null)}function Ho1($){let Z=Dm0($);return{...Z,id:Z.id,connection_type:"VIRTUAL",connection_url:`virtual://${Z.id}`,app_name:"decopilot",app_id:"decopilot",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"decopilot"},tools:[],bindings:[]}}var p4,pt1="https://reports.decocms.com/api/v2/mcp",_90="get_my_diagnostic",et1,mG,fD,$o1,Zo1,Lm0,ei6="https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",Xo1,x90,$n6,Zn6,Yo1,a85,s85,Go1,e85,v90,DN,t7;var No1=O(()=>{p4={SELF:($)=>`${$}_self`,REGISTRY:($)=>`${$}_registry`,COMMUNITY_REGISTRY:($)=>`${$}_community-registry`,DEV_ASSETS:($)=>`${$}_dev-assets`,SITE_DIAGNOSTICS:($)=>`site-diagnostics_${$}`,COMMERCE_DISCOVERY:($)=>`${$}_commerce-discovery`};et1=gY("decopilot_"),mG=et1.is,fD=et1.get,$o1=gY("dev_"),Zo1=$o1.get,Lm0=$o1.is;Xo1=gY("brand-context-setup_"),x90=Xo1.is,$n6=Xo1.get,Zn6=`
|
|
1283
|
+
`:Q="\\n";break;case"\r":Q="\\r";break;case"\t":Q="\\t";break;default:}throw new El6.InvalidNameError(`${$} name ('${Z}') cannot contain '${Q}'`)}}),""}function Pl6($,Z=""){if(Z==="")throw Error(`${$} name required`);let X=Qp1(Z);if(X.length)throw Error(`invalid ${$} name - ${$} name ${X}`)}function Qp1($=""){if($==="")throw Error("name required");let Z=/^[-\w]+$/g;if($.match(Z)===null){for(let Q of $.split(""))if(Q.match(Z)===null)return`cannot contain '${Q}'`}return""}});var Um=_((E6)=>{Object.defineProperty(E6,"__esModule",{value:!0});E6.wsconnect=E6.usernamePasswordAuthenticator=E6.UserAuthenticationExpiredError=E6.tokenAuthenticator=E6.TimeoutError=E6.syncIterator=E6.RequestError=E6.ProtocolError=E6.PermissionViolationError=E6.nuid=E6.Nuid=E6.NoRespondersError=E6.nkeys=E6.nkeyAuthenticator=E6.nanos=E6.MsgHdrsImpl=E6.millis=E6.Metric=E6.Match=E6.jwtAuthenticator=E6.InvalidSubjectError=E6.InvalidOperationError=E6.InvalidArgumentError=E6.headers=E6.hasWsProtocol=E6.errors=E6.Empty=E6.DrainingConnectionError=E6.delay=E6.deferred=E6.deadline=E6.credsAuthenticator=E6.createInbox=E6.ConnectionError=E6.ClosedConnectionError=E6.canonicalMIMEHeaderKey=E6.buildAuthenticator=E6.Bench=E6.backoff=E6.AuthorizationError=void 0;var f6=vY();Object.defineProperty(E6,"AuthorizationError",{enumerable:!0,get:function(){return f6.AuthorizationError}});Object.defineProperty(E6,"backoff",{enumerable:!0,get:function(){return f6.backoff}});Object.defineProperty(E6,"Bench",{enumerable:!0,get:function(){return f6.Bench}});Object.defineProperty(E6,"buildAuthenticator",{enumerable:!0,get:function(){return f6.buildAuthenticator}});Object.defineProperty(E6,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return f6.canonicalMIMEHeaderKey}});Object.defineProperty(E6,"ClosedConnectionError",{enumerable:!0,get:function(){return f6.ClosedConnectionError}});Object.defineProperty(E6,"ConnectionError",{enumerable:!0,get:function(){return f6.ConnectionError}});Object.defineProperty(E6,"createInbox",{enumerable:!0,get:function(){return f6.createInbox}});Object.defineProperty(E6,"credsAuthenticator",{enumerable:!0,get:function(){return f6.credsAuthenticator}});Object.defineProperty(E6,"deadline",{enumerable:!0,get:function(){return f6.deadline}});Object.defineProperty(E6,"deferred",{enumerable:!0,get:function(){return f6.deferred}});Object.defineProperty(E6,"delay",{enumerable:!0,get:function(){return f6.delay}});Object.defineProperty(E6,"DrainingConnectionError",{enumerable:!0,get:function(){return f6.DrainingConnectionError}});Object.defineProperty(E6,"Empty",{enumerable:!0,get:function(){return f6.Empty}});Object.defineProperty(E6,"errors",{enumerable:!0,get:function(){return f6.errors}});Object.defineProperty(E6,"hasWsProtocol",{enumerable:!0,get:function(){return f6.hasWsProtocol}});Object.defineProperty(E6,"headers",{enumerable:!0,get:function(){return f6.headers}});Object.defineProperty(E6,"InvalidArgumentError",{enumerable:!0,get:function(){return f6.InvalidArgumentError}});Object.defineProperty(E6,"InvalidOperationError",{enumerable:!0,get:function(){return f6.InvalidOperationError}});Object.defineProperty(E6,"InvalidSubjectError",{enumerable:!0,get:function(){return f6.InvalidSubjectError}});Object.defineProperty(E6,"jwtAuthenticator",{enumerable:!0,get:function(){return f6.jwtAuthenticator}});Object.defineProperty(E6,"Match",{enumerable:!0,get:function(){return f6.Match}});Object.defineProperty(E6,"Metric",{enumerable:!0,get:function(){return f6.Metric}});Object.defineProperty(E6,"millis",{enumerable:!0,get:function(){return f6.millis}});Object.defineProperty(E6,"MsgHdrsImpl",{enumerable:!0,get:function(){return f6.MsgHdrsImpl}});Object.defineProperty(E6,"nanos",{enumerable:!0,get:function(){return f6.nanos}});Object.defineProperty(E6,"nkeyAuthenticator",{enumerable:!0,get:function(){return f6.nkeyAuthenticator}});Object.defineProperty(E6,"nkeys",{enumerable:!0,get:function(){return f6.nkeys}});Object.defineProperty(E6,"NoRespondersError",{enumerable:!0,get:function(){return f6.NoRespondersError}});Object.defineProperty(E6,"Nuid",{enumerable:!0,get:function(){return f6.Nuid}});Object.defineProperty(E6,"nuid",{enumerable:!0,get:function(){return f6.nuid}});Object.defineProperty(E6,"PermissionViolationError",{enumerable:!0,get:function(){return f6.PermissionViolationError}});Object.defineProperty(E6,"ProtocolError",{enumerable:!0,get:function(){return f6.ProtocolError}});Object.defineProperty(E6,"RequestError",{enumerable:!0,get:function(){return f6.RequestError}});Object.defineProperty(E6,"syncIterator",{enumerable:!0,get:function(){return f6.syncIterator}});Object.defineProperty(E6,"TimeoutError",{enumerable:!0,get:function(){return f6.TimeoutError}});Object.defineProperty(E6,"tokenAuthenticator",{enumerable:!0,get:function(){return f6.tokenAuthenticator}});Object.defineProperty(E6,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return f6.UserAuthenticationExpiredError}});Object.defineProperty(E6,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return f6.usernamePasswordAuthenticator}});Object.defineProperty(E6,"wsconnect",{enumerable:!0,get:function(){return f6.wsconnect}})});var qD=_((Gp1)=>{Object.defineProperty(Gp1,"__esModule",{value:!0});Gp1.PubHeaders=Gp1.PriorityPolicy=Gp1.ConsumerApiAction=Gp1.PersistMode=Gp1.StoreCompression=Gp1.ReplayPolicy=Gp1.AckPolicy=Gp1.DeliverPolicy=Gp1.StorageType=Gp1.DiscardPolicy=Gp1.RetentionPolicy=void 0;Gp1.defaultConsumer=Sl6;var kl6=Um();Gp1.RetentionPolicy={Limits:"limits",Interest:"interest",Workqueue:"workqueue"};Gp1.DiscardPolicy={Old:"old",New:"new"};Gp1.StorageType={File:"file",Memory:"memory"};Gp1.DeliverPolicy={All:"all",Last:"last",New:"new",StartSequence:"by_start_sequence",StartTime:"by_start_time",LastPerSubject:"last_per_subject"};Gp1.AckPolicy={None:"none",All:"all",Explicit:"explicit",FlowControl:"flow_control",NotSet:""};Gp1.ReplayPolicy={Instant:"instant",Original:"original"};Gp1.StoreCompression={None:"none",S2:"s2"};Gp1.PersistMode={Default:"default",Async:"async"};Gp1.ConsumerApiAction={CreateOrUpdate:"",Update:"update",Create:"create"};Gp1.PriorityPolicy={None:"none",Overflow:"overflow",PinnedClient:"pinned_client",Prioritized:"prioritized"};function Sl6($,Z={}){return Object.assign({name:$,deliver_policy:Gp1.DeliverPolicy.All,ack_policy:Gp1.AckPolicy.Explicit,ack_wait:(0,kl6.nanos)(30000),replay_policy:Gp1.ReplayPolicy.Instant},Z)}Gp1.PubHeaders={MsgIdHdr:"Nats-Msg-Id",ExpectedStreamHdr:"Nats-Expected-Stream",ExpectedLastSeqHdr:"Nats-Expected-Last-Sequence",ExpectedLastMsgIdHdr:"Nats-Expected-Last-Msg-Id",ExpectedLastSubjectSequenceHdr:"Nats-Expected-Last-Subject-Sequence",ExpectedLastSubjectSequenceSubjectHdr:"Nats-Expected-Last-Subject-Sequence-Subject",MessageTTL:"Nats-TTL",Schedule:"Nats-Schedule",ScheduleTarget:"Nats-Schedule-Target",ScheduleSource:"Nats-Schedule-Source",ScheduleTTL:"Nats-Schedule-TTL",ScheduleTimeZone:"Nats-Schedule-Time-Zone",ScheduleRollup:"Nats-Schedule-Rollup",Scheduler:"Nats-Scheduler",ScheduleNext:"Nats-Schedule-Next"}});var Yd0=_((Fp1)=>{Object.defineProperty(Fp1,"__esModule",{value:!0});Fp1.ConsumerAPIImpl=void 0;var gl6=ff(),hl6=o50(),YJ=bf(),m7=vY(),UN=qD();class Np1 extends gl6.BaseApiClientImpl{constructor($,Z){super($,Z)}async addUpdate($,Z,X,Q){if((0,YJ.validateStreamName)($),X=X||{},Z.deliver_group&&Z.flow_control)throw m7.InvalidArgumentError.format(["flow_control","deliver_group"],"are mutually exclusive");if(Z.deliver_group&&Z.idle_heartbeat)throw m7.InvalidArgumentError.format(["idle_heartbeat","deliver_group"],"are mutually exclusive");if(Up1(Z)){let{min:w,ok:B}=this.nc.features.get(m7.Feature.JS_PRIORITY_GROUPS);if(!B)throw Error(`priority_groups require server ${w}`);if(Z.deliver_subject)throw m7.InvalidArgumentError.format("deliver_subject","cannot be set when using priority groups");ul6(Z)}let Y={};if(Y.config=Z,Y.stream_name=$,Y.action=X.action||UN.ConsumerApiAction.Create,Y.pedantic=X.pedantic||!1,Y.config.durable_name)(0,YJ.validateDurableName)(Y.config.durable_name);let G=this.nc,{min:J,ok:K}=G.features.get(m7.Feature.JS_NEW_CONSUMER_CREATE_API),W=Z.name===""?void 0:Z.name;if(W&&!K)throw m7.InvalidArgumentError.format("name",`requires server ${J}`);if(W)try{(0,YJ.minValidation)("name",W)}catch(w){let B=w.message,L=B.indexOf("cannot contain");if(L!==-1)throw Error(`consumer 'name' ${B.substring(L)}`);throw w}let H,N="";if(Array.isArray(Z.filter_subjects)){let{min:w,ok:B}=G.features.get(m7.Feature.JS_MULTIPLE_CONSUMER_FILTER);if(!B)throw m7.InvalidArgumentError.format("filter_subjects",`requires server ${w}`);K=!1}if(Z.metadata){let{min:w,ok:B}=G.features.get(m7.Feature.JS_STREAM_CONSUMER_METADATA);if(!B)throw m7.InvalidArgumentError.format("metadata",`requires server ${w}`)}if(K)N=Z.name??Z.durable_name??"";if(N!==""){let w=Z.filter_subject??void 0;if(w===">")w=void 0;H=w!==void 0?`${this.prefix}.CONSUMER.CREATE.${$}.${N}.${w}`:`${this.prefix}.CONSUMER.CREATE.${$}.${N}`}else H=Z.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${$}.${Z.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${$}`;let U=Q??Y.config;return await this._request(H,Y,{...X,...this.requiredApiOpts(U)})}minConsumerApi($){if($.ack_policy===UN.AckPolicy.FlowControl)return 4;if(typeof $.pause_until==="string"&&$.pause_until!=="")return 1;if($.priority_policy!==void 0&&$.priority_policy!==UN.PriorityPolicy.None)return 1;if(typeof $.priority_timeout==="number"&&$.priority_timeout>0)return 1;if(Array.isArray($.priority_groups)&&$.priority_groups.length>0)return 1;return 0}requiredApiOpts($){if(!this.sendRequiredApiLevel())return{};let Z=this.minConsumerApi($);return Z>0?{minApiVersion:Z}:{}}add($,Z,X){X=X||{};let Q=UN.ConsumerApiAction.Create;if(typeof X==="string")Q=X,X={};let Y=Object.assign({},{action:Q},X);return this.addUpdate($,Z,Y)}async update($,Z,X){let Q=await this.info($,Z),Y=X;return this.addUpdate($,Object.assign(Q.config,Y),{action:UN.ConsumerApiAction.Update},Y)}async info($,Z){return(0,YJ.validateStreamName)($),(0,YJ.validateDurableName)(Z),await this._request(`${this.prefix}.CONSUMER.INFO.${$}.${Z}`)}async delete($,Z){return(0,YJ.validateStreamName)($),(0,YJ.validateDurableName)(Z),(await this._request(`${this.prefix}.CONSUMER.DELETE.${$}.${Z}`)).success}list($){(0,YJ.validateStreamName)($);let Z=(Q)=>{return Q.consumers},X=`${this.prefix}.CONSUMER.LIST.${$}`;return new hl6.ListerImpl(X,Z,this)}pause($,Z,X){let Q=`${this.prefix}.CONSUMER.PAUSE.${$}.${Z}`,Y={pause_until:X.toISOString()};return this._request(Q,Y)}resume($,Z){return this.pause($,Z,new Date(0))}unpin($,Z,X){let Q=`${this.prefix}.CONSUMER.UNPIN.${$}.${Z}`;return this._request(Q,{group:X})}async reset($,Z,X){(0,YJ.validateStreamName)($),(0,YJ.validateDurableName)(Z);let Q=this.nc,{min:Y,ok:G}=Q.features.get(m7.Feature.JS_CONSUMER_RESET);if(!G)throw Error(`consumer reset requires server ${Y}`);if(typeof X==="number"&&(!Number.isInteger(X)||X<0))throw m7.InvalidArgumentError.format("seq","must be a non-negative integer");let J=`${this.prefix}.CONSUMER.RESET.${$}.${Z}`,K=typeof X==="number"?{seq:X}:void 0;return await this._request(J,K)}}Fp1.ConsumerAPIImpl=Np1;function Up1($){let Z=$;return Z&&Z.priority_groups!==void 0||Z.priority_policy!==void 0}function ul6($){if(Up1($)){if(!Array.isArray($.priority_groups))throw m7.InvalidArgumentError.format(["priority_groups"],"must be an array");if($.priority_groups.length===0)throw m7.InvalidArgumentError.format(["priority_groups"],"must have at least one group");if($.priority_groups.forEach((Z)=>{if((0,YJ.minValidation)("priority_group",Z),Z.length>16)throw m7.errors.InvalidArgumentError.format("group","must be 16 characters or less")}),$.priority_policy!==UN.PriorityPolicy.None&&$.priority_policy!==UN.PriorityPolicy.Overflow&&$.priority_policy!==UN.PriorityPolicy.PinnedClient&&$.priority_policy!==UN.PriorityPolicy.Prioritized)throw m7.InvalidArgumentError.format(["priority_policy"],"must be 'none', 'prioritized', 'overflow', or 'pinned_client'")}}});var Kd0=_((Op1)=>{Object.defineProperty(Op1,"__esModule",{value:!0});Op1.JsMsgImpl=Op1.ACK=void 0;Op1.toJsMsg=il6;Op1.parseInfo=Bp1;var yf=vY();Op1.ACK=Uint8Array.of(43,65,67,75);var cl6=Uint8Array.of(45,78,65,75),Fm=Uint8Array.of(43,87,80,73),ll6=Uint8Array.of(43,78,88,84),dl6=Uint8Array.of(43,84,69,82,77),ml6=Uint8Array.of(32);function il6($,Z=5000){return new Jd0($,Z)}function Bp1($){let Z=$.split(".");if(Z.length===9)Z.splice(2,0,"_","");if(Z.length<11||Z[0]!=="$JS"||Z[1]!=="ACK")throw Error("unable to parse delivery info - not a jetstream message");let X={};return X.domain=Z[2]==="_"?"":Z[2],X.account_hash=Z[3],X.stream=Z[4],X.consumer=Z[5],X.deliveryCount=parseInt(Z[6],10),X.redelivered=X.deliveryCount>1,X.streamSequence=parseInt(Z[7],10),X.deliverySequence=parseInt(Z[8],10),X.timestampNanos=parseInt(Z[9],10),X.pending=parseInt(Z[10],10),X}function nl6($){let Z=$.split(".");if(Z.length===9)Z.splice(2,0,"_","");if(Z.length<11||Z[0]!=="$JS"||Z[1]!=="ACK")throw Error("unable to parse delivery info - not a jetstream message");return BigInt(Z[9])}class Jd0{msg;di;didAck;timeout;constructor($,Z){this.msg=$,this.didAck=!1,this.timeout=Z}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){if(!this.di)this.di=Bp1(this.reply);return this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}get time(){let $=(0,yf.millis)(this.info.timestampNanos);return new Date($)}get timestamp(){return this.time.toISOString()}get timestampNanos(){return nl6(this.reply)}doAck($){if(!this.didAck)this.didAck=!this.isWIP($),this.msg.respond($)}isWIP($){return $.length===4&&$[0]===Fm[0]&&$[1]===Fm[1]&&$[2]===Fm[2]&&$[3]===Fm[3]}async ackAck($){let Z=(0,yf.deferred)();if(!this.didAck)if(this.didAck=!0,this.msg.reply){$=$||{},$.timeout=$.timeout||this.timeout;let Q=this.msg.publisher,Y=!Q.options?.noAsyncTraces,G=new yf.RequestOne(Q.muxSubscriptions,this.msg.reply,{timeout:$.timeout},Y);Q.request(G);try{Q.publish(this.msg.reply,Op1.ACK,{reply:`${Q.muxSubscriptions.baseInbox}${G.token}`})}catch(J){G.cancel(J)}try{await Promise.race([G.timer,G.deferred]),Z.resolve(!0)}catch(J){G.cancel(J),Z.reject(J)}}else Z.resolve(!1);else Z.resolve(!1);return Z}ack(){this.doAck(Op1.ACK)}nak($){let Z=cl6;if($)Z=new TextEncoder().encode(`-NAK ${JSON.stringify({delay:(0,yf.nanos)($)})}`);this.doAck(Z)}working(){this.doAck(Fm)}next($,Z={batch:1}){let X={};if(X.batch=Z.batch||1,X.no_wait=Z.no_wait||!1,Z.expires&&Z.expires>0)X.expires=(0,yf.nanos)(Z.expires);let Q=new TextEncoder().encode(JSON.stringify(X)),Y=yf.DataBuffer.concat(ll6,ml6,Q),G=$?{reply:$}:void 0;this.msg.respond(Y,G)}term($=""){let Z=dl6;if($?.length>0)Z=new TextEncoder().encode(`+TERM ${$}`);this.doAck(Z)}json(){return this.msg.json()}string(){return this.msg.string()}}Op1.JsMsgImpl=Jd0});var Rp1=_((Tp1)=>{Object.defineProperty(Tp1,"__esModule",{value:!0});Tp1.PullConsumerImpl=Tp1.PullConsumerMessagesImpl=Tp1.PullConsumerType=void 0;Tp1.isOverflowOptions=wm;Tp1.isPrioritizedOptions=r50;Tp1.validateOverflowPullOptions=Pp1;Tp1.validatePrioritizedPullOptions=Ap1;var L$=vY(),ol6=Kd0(),Dp1=qD(),Ep1=HN(),zp1=bf();Tp1.PullConsumerType={Unset:"",Consume:"consume",Fetch:"fetch"};function wm($){let Z=$;return Z&&typeof Z.group==="string"||typeof Z.min_pending==="number"||typeof Z.min_ack_pending==="number"}function r50($){let Z=$;return Z&&typeof Z.group==="string"&&typeof Z.priority==="number"}class a50 extends L$.QueuedIteratorImpl{consumer;opts;sub;monitor;pending;isConsume;callback;listeners;statusIterator;abortOnMissingResource;bind;inboxPrefix;inbox;cancelables;inReset;closeListener;isPinned;isPriority;natsPinId;constructor($,Z,X=!1){super();if(this.consumer=$,this.isConsume=X,this.cancelables=[],this.inboxPrefix=(0,L$.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,this.inReset=!1,this.isPinned=!1,this.isPriority=!1,this.natsPinId="",this.consumer.ordered){if(wm(Z))throw L$.errors.InvalidArgumentError.format(["group","min_pending","min_ack_pending"],"cannot be specified for ordered consumers");if(this.consumer.orderedConsumerState===void 0){let Y={},G=$.opts;Y.namePrefix=G.name_prefix??`oc_${L$.nuid.next()}`,Y.opts=G,Y.cursor={stream_seq:1,deliver_seq:0};let J=$._info.config.opt_start_seq||0;Y.cursor.stream_seq=J>0?J-1:0,Y.createFails=0,this.consumer.orderedConsumerState=Y}}let Q=Z;if(this.opts=this.parseOptions(Z,this.isConsume),this.callback=Q.callback||null,this.noIterator=typeof this.callback==="function",this.monitor=null,this.pending={msgs:0,bytes:0,requests:0},this.listeners=[],this.abortOnMissingResource=Q.abort_on_missing_resource===!0,this.bind=Q.bind===!0,Q.group){let{min_pending:Y,min_ack_pending:G}=Q;this.isPinned=Y===void 0&&G===void 0;let{priority:J}=Q;this.isPriority=typeof J==="number"}this.closeListener={connectionClosedCallback:()=>{this._push(()=>{this.stop()})}},this.consumer.api.nc.addCloseListener(this.closeListener),this.start()}start(){let{max_messages:$,max_bytes:Z,idle_heartbeat:X,threshold_bytes:Q,threshold_messages:Y}=this.opts;if(this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(G,J)=>{if(G){this.stop(G);return}if(this.monitor?.work(),this.consumer.ordered?J.subject.indexOf(this?.inboxPrefix)===0:J.subject===this.inbox){if(J.subject!==this.sub.getSubject())return;let W=new Ep1.JetStreamStatus(J),H=W.parseHeartbeat();if(H){this.notify(H);return}let{code:N,description:U}=W,{msgsLeft:F,bytesLeft:w}=W.parseDiscard();if(F&&F>0||w&&w>0)this.pending.msgs-=F,this.pending.bytes-=w,this.pending.requests--,this.notify({type:"discard",messagesLeft:F,bytesLeft:w});switch(N){case 400:this.stop(W.toError());return;case 409:{let B=this.handle409(W);if(B){this.stop(B);return}if(W.isMessageSizeExceedsMaxBytes()&&this.yields.length>0)break;return}case 423:this.natsPinId="",this.notify({type:"consumer_unpinned"});break;case 503:if(this.notify({type:"no_responders",code:N}),this.consumer.ordered){let B=this.consumer.orderedConsumerState;B.needsReset=!0}if(!this.isConsume){this.stop(W.toError());return}break;default:this.notify({type:"debug",code:N,description:U})}}else{let W=(0,ol6.toJsMsg)(J,this.consumer.api.timeout);if(this.isPinned){let H=W?.headers?.get("Nats-Pin-Id");if(H&&this.natsPinId==="")this.natsPinId=H,this.notify({type:"consumer_pinned",id:H})}if(this.consumer.ordered){let H=this.consumer.orderedConsumerState.cursor,N=W.info.deliverySequence,U=W.info.streamSequence,F=H.deliver_seq+1;if(N!==F){this.reset();return}H.deliver_seq=N,H.stream_seq=U}if(this._push(W),this.received++,this.pending.msgs)this.pending.msgs--;if(this.pending.bytes)this.pending.bytes-=J.size()}if(this.pending.msgs===0&&this.pending.bytes===0)this.pending.requests=0;if(this.isConsume){if($&&this.pending.msgs<=Y||Z&&this.pending.bytes<=Q){let W=this.pullOptions();this.pull(W)}}else if(this.pending.requests===0)this._push(()=>{this.stop()})}}),X)this.monitor=new L$.IdleHeartbeatMonitor(X,(G)=>{if(this.notify({type:"heartbeats_missed",count:G}),!this.isConsume&&!this.consumer.ordered)return this.stop(new Ep1.JetStreamError("heartbeats missed")),!0;return this.resetPending().then(()=>{}).catch(()=>{}),!1},{maxOut:2});(async()=>{let G=this.consumer.api.nc.status();this.statusIterator=G;for await(let J of G)switch(J.type){case"disconnect":this.monitor?.cancel();break;case"reconnect":this.resetPending().then((K)=>{if(K)this.monitor?.restart()}).catch(()=>{});break;default:}})(),this.sub.closed.then(()=>{if(this.sub.isDraining())this._push(()=>{this.stop()})}),this.pull(this.pullOptions())}handle409($){let{code:Z,description:X}=$;if($.isConsumerDeleted())this.notify({type:"consumer_deleted",code:Z,description:X});else if($.isExceededLimit())this.notify({type:"exceeded_limits",code:Z,description:X});if(!this.isConsume)return $.toError();if($.isConsumerDeleted()&&this.abortOnMissingResource)return $.toError();return null}reset(){this.monitor?.cancel();let $=this.consumer.orderedConsumerState,{name:Z}=this.consumer._info?.config;if(Z)this.notify({type:"reset",name:Z}),this.consumer.api.delete(this.consumer.stream,Z).catch(()=>{});let X=this.consumer.getConsumerOpts();this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,$.cursor.deliver_seq=0,this.consumer.name=X.name,this.consumer.api.nc._resub(this.sub,this.inbox),this.consumer.api.add(this.consumer.stream,X).then((Q)=>{$.createFails=0,this.consumer._info=Q,this.notify({type:"ordered_consumer_recreated",name:Q.name}),this.monitor?.restart(),this.pull(this.pullOptions())}).catch((Q)=>{if($.createFails++,Q.message==="stream not found"){if(this.notify({type:"stream_not_found",consumerCreateFails:$.createFails,name:this.consumer.stream}),this.abortOnMissingResource){this.stop(Q);return}}if($.createFails>=30&&this.received===0)this.stop(Q);let Y=(0,L$.backoff)(),G=(0,L$.delay)(Y.backoff($.createFails));G.then(()=>{let J=this.cancelables.indexOf(G);if(J!==-1)this.cancelables=this.cancelables.splice(J,J);if(!this.done)this.reset()}).catch((J)=>{}),this.cancelables.push(G)})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let X=$;this.callback(X)}else Z()}catch(X){this.stop(X)}}}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let X=Z;if(!X.done)X.push($)})})()}async resetPending(){if(this.inReset)return Promise.resolve(!0);this.inReset=!0;let Z=await(this.bind?this.resetPendingNoInfo():this.resetPendingWithInfo());return this.inReset=!1,Z}resetPendingNoInfo(){return this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),Promise.resolve(!0)}async resetPendingWithInfo(){let $=0,Z=0,X=(0,L$.backoff)([this.opts.expires||30000]),Q=0;while(!0){if(this.done)return!1;if(this.consumer.api.nc.isClosed())return!1;try{return await this.consumer.info(),$=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(Y){if(Y instanceof L$.errors.ClosedConnectionError)return this.stop(Y),!1;if(Y.message==="stream not found"){if(Z++,this.notify({type:"stream_not_found",name:this.consumer.stream}),!this.isConsume||this.abortOnMissingResource)return this.stop(Y),!1}else if(Y.message==="consumer not found"){if($++,this.notify({type:"consumer_not_found",name:this.consumer.name,stream:this.consumer.stream,count:$}),!this.isConsume||this.abortOnMissingResource){if(this.consumer.ordered){let K=this.consumer.orderedConsumerState;K.needsReset=!0}return this.stop(Y),!1}if(this.consumer.ordered)return this.reset(),!1}else $=0,Z=0;let G=X.backoff(Q),J=(0,L$.delay)(G);await Promise.race([J,this.consumer.api.nc.closed()]),J.cancel(),Q++}}}pull($){this.pending.bytes+=$.max_bytes??0,this.pending.msgs+=$.batch??0,this.pending.requests++;let Z=this.consumer.api.nc,X=`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer._info.name}`;this._push(()=>{Z.publish(X,JSON.stringify($),{reply:this.inbox}),this.notify({type:"next",options:$})})}pullOptions(){let $=this.opts.max_messages-this.pending.msgs,Z=this.opts.max_bytes-this.pending.bytes,X=(0,L$.nanos)(this.opts.idle_heartbeat),Q=(0,L$.nanos)(this.opts.expires),Y={batch:$,max_bytes:Z,idle_heartbeat:X,expires:Q};if(this.isPinned&&this.natsPinId!=="")Y.id=this.natsPinId;if(wm(this.opts)){if(Y.group=this.opts.group,this.opts.min_pending)Y.min_pending=this.opts.min_pending;if(this.opts.min_ack_pending)Y.min_ack_pending=this.opts.min_ack_pending}if(r50(this.opts))Y.group=this.opts.group,Y.priority=this.opts.priority;return Y}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}clearTimers(){this.monitor?.cancel(),this.monitor=null}stop($){if(this.done)return;this.consumer.api.nc.removeCloseListener(this.closeListener),this.sub?.unsubscribe(),this.clearTimers(),this.statusIterator?.stop(),this._push(()=>{super.stop($),this.listeners.forEach((Z)=>{Z.stop()})})}parseOptions($,Z=!1){let X=$||{};if(X.max_messages=X.max_messages||0,X.max_bytes=X.max_bytes||0,X.max_messages!==0&&X.max_bytes!==0)throw L$.errors.InvalidArgumentError.format(["max_messages","max_bytes"],"are mutually exclusive");if(X.max_messages===0)X.max_messages=100;if(X.expires=X.expires||30000,X.expires<1000)throw L$.errors.InvalidArgumentError.format("expires","must be at least 1000ms");if(X.idle_heartbeat=X.idle_heartbeat||X.expires/2,X.idle_heartbeat=X.idle_heartbeat>30000?30000:X.idle_heartbeat,X.idle_heartbeat<500)X.idle_heartbeat=500;if(Z){let Q=Math.round(X.max_messages*0.75)||1;X.threshold_messages=X.threshold_messages||Q;let Y=Math.round(X.max_bytes*0.75)||1;X.threshold_bytes=X.threshold_bytes||Y}if(wm($)){let{min:Q,ok:Y}=this.consumer.api.nc.features.get(L$.Feature.JS_PRIORITY_GROUPS);if(!Y)throw Error(`priority_groups require server ${Q}`);if(Pp1($),$.group)X.group=$.group;if($.min_ack_pending)X.min_ack_pending=$.min_ack_pending;if($.min_pending)X.min_pending=$.min_pending}else if(r50($)){if(Ap1($),$.group)X.group=$.group;if(typeof $.priority==="number")X.priority=$.priority}return X}status(){let $=new L$.QueuedIteratorImpl;return this.listeners.push($),$}}Tp1.PullConsumerMessagesImpl=a50;class jp1{api;_info;stream;name;opts;type;messages;ordered;serial;orderedConsumerState;constructor($,Z,X=null){this.api=$,this._info=Z,this.name=Z.name,this.stream=Z.stream_name,this.ordered=X!==null,this.opts=X||{},this.serial=1,this.type=Tp1.PullConsumerType.Unset}debug(){console.log({serial:this.serial,cursor:this.orderedConsumerState?.cursor})}isPullConsumer(){return!0}isPushConsumer(){return!1}consume($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.bind)return Promise.reject(L$.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===Tp1.PullConsumerType.Fetch)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer initialized as fetch"));if(this.type===Tp1.PullConsumerType.Consume)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer doesn't support concurrent consume"));this.type=Tp1.PullConsumerType.Consume}return Promise.resolve(new a50(this,$,!0))}async fetch($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.group)return Promise.reject(L$.errors.InvalidArgumentError.format("group","ordered consumers don't support priority groups"));if($.bind)return Promise.reject(L$.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===Tp1.PullConsumerType.Consume)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer already initialized as consume"));if(this.messages?.done===!1)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer doesn't support concurrent fetch"));if(this.ordered){if(this.orderedConsumerState?.cursor?.deliver_seq)this._info.config.opt_start_seq=this.orderedConsumerState?.cursor.stream_seq+1;if(this.orderedConsumerState?.needsReset===!0)await this._reset()}this.type=Tp1.PullConsumerType.Fetch}let Z=new a50(this,$);if(this.ordered)this.messages=Z;return Promise.resolve(Z)}async next($={expires:30000}){$={...$};let Z=$;Z.max_messages=1;let X=await this.fetch(Z);try{for await(let Q of X)return Q}catch(Q){return Promise.reject(Q)}return null}delete(){let{stream_name:$,name:Z}=this._info;return this.api.delete($,Z)}getConsumerOpts(){let $=this.orderedConsumerState;this.serial++,this.name=`${$.namePrefix}_${this.serial}`;let Z=Object.assign({},this._info.config,{name:this.name,deliver_policy:Dp1.DeliverPolicy.StartSequence,opt_start_seq:$.cursor.stream_seq+1,ack_policy:Dp1.AckPolicy.None,inactive_threshold:(0,L$.nanos)(300000),num_replicas:1});return delete Z.metadata,Z}async _reset(){if(this.messages===void 0)throw Error("not possible to reset");this.delete().catch(()=>{});let $=this.getConsumerOpts(),Z=await this.api.add(this.stream,$);return this._info=Z,Z}async info($=!1){if($)return Promise.resolve(this._info);let{stream_name:Z,name:X}=this._info;return this._info=await this.api.info(Z,X),this._info}}Tp1.PullConsumerImpl=jp1;function Pp1($){if(wm($)){if((0,zp1.minValidation)("group",$.group),$.group.length>16)throw L$.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{min_pending:Z,min_ack_pending:X}=$;if(Z&&typeof Z!=="number")throw L$.errors.InvalidArgumentError.format(["min_pending"],"must be a number");if(X&&typeof X!=="number")throw L$.errors.InvalidArgumentError.format(["min_ack_pending"],"must be a number")}}function Ap1($){if(r50($)){if((0,zp1.minValidation)("group",$.group),$.group.length>16)throw L$.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{priority:Z}=$;if(Z&&typeof Z!=="number")throw L$.errors.InvalidArgumentError.format(["priority"],"must be a number")}}});var Vp1=_((kp1)=>{Object.defineProperty(kp1,"__esModule",{value:!0});kp1.PushConsumerImpl=kp1.PushConsumerMessagesImpl=void 0;var Zd6=Kd0(),qp1=qD(),Wd0=ED(),bX=vY(),Xd6=HN();class Hd0 extends bX.QueuedIteratorImpl{consumer;sub;monitor;listeners;abortOnMissingResource;callback;ordered;cursor;namePrefix;deliverPrefix;serial;createFails;statusIterator;cancelables;constructor($,Z={},X={}){super();if(this.consumer=$,this.monitor=null,this.listeners=[],this.cancelables=[],this.abortOnMissingResource=Z.abort_on_missing_resource===!0,this.callback=Z.callback||null,this.noIterator=this.callback!==null,this.namePrefix=null,this.deliverPrefix=null,this.ordered=X.ordered===!0,this.serial=1,this.ordered){this.namePrefix=X.name_prefix??`oc_${bX.nuid.next()}`,this.deliverPrefix=X.deliver_prefix??(0,bX.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.cursor={stream_seq:1,deliver_seq:0};let Q=$._info.config.opt_start_seq||0;this.cursor.stream_seq=Q>0?Q-1:0,this.createFails=0}this.start()}reset(){let{name:$}=this.consumer._info?.config;if($)this.consumer.api.delete(this.consumer.stream,$).catch(()=>{});let Z=this.getConsumerOpts();this.cursor.deliver_seq=0,this.consumer.name=Z.name,this.consumer.serial=this.serial,this.consumer.api.nc._resub(this.sub,Z.deliver_subject),this.consumer.api.add(this.consumer.stream,Z).then((X)=>{this.createFails=0,this.consumer._info=X,this.notify({type:"ordered_consumer_recreated",name:X.name})}).catch((X)=>{if(this.createFails++,X.message==="stream not found"){if(this.notify({type:"stream_not_found",name:this.consumer.stream,consumerCreateFails:this.createFails}),this.abortOnMissingResource){this.stop(X);return}}if(this.createFails>=30&&this.received===0)this.stop(X);let Q=(0,bX.backoff)(),Y=(0,bX.delay)(Q.backoff(this.createFails));Y.then(()=>{if(!this.done)this.reset()}).catch(()=>{}).finally(()=>{let G=this.cancelables.indexOf(Y);if(G!==-1)this.cancelables=this.cancelables.splice(G,G)}),this.cancelables.push(Y)})}getConsumerOpts(){let $=Object.assign({},this.consumer._info.config);this.serial++;let Z=`${this.namePrefix}_${this.serial}`;return Object.assign($,{name:Z,deliver_policy:qp1.DeliverPolicy.StartSequence,opt_start_seq:this.cursor.stream_seq+1,ack_policy:qp1.AckPolicy.None,inactive_threshold:(0,bX.nanos)(300000),num_replicas:1,flow_control:!0,idle_heartbeat:(0,bX.nanos)(30000),deliver_subject:`${this.deliverPrefix}.${this.serial}`})}closed(){return this.iterClosed}close(){return this.stop(),this.iterClosed}stop($){if(this.done)return;this.statusIterator?.stop(),this.monitor?.cancel(),this.monitor=null,this.cancelables.forEach((Z)=>{Z.cancel()}),Promise.all(this.cancelables).then(()=>{this.cancelables=[]}).catch(()=>{}).finally(()=>{this._push(()=>{super.stop($),this.listeners.forEach((Z)=>{Z.stop()})})})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let X=$;this.received++,this.callback(X),this.processed++}else Z()}catch(X){this.stop(X)}}}status(){let $=new bX.QueuedIteratorImpl;return this.listeners.push($),$}start(){let{deliver_subject:$,deliver_group:Z,idle_heartbeat:X}=this.consumer._info.config;if(!$)throw Error("bad consumer info");if(X){let Q=(0,bX.millis)(X);this.monitor=new bX.IdleHeartbeatMonitor(Q,(Y)=>{if(this.notify({type:"heartbeats_missed",count:Y}),this.ordered)this.reset();return!1},{maxOut:2}),(async()=>{this.statusIterator=this.consumer.api.nc.status();for await(let Y of this.statusIterator)switch(Y.type){case"disconnect":this.monitor?.cancel();break;case"reconnect":this.monitor?.restart();break;default:}})()}this.sub=this.consumer.api.nc.subscribe($,{queue:Z,callback:(Q,Y)=>{if(Q){this.stop(Q);return}if(this.monitor?.work(),this.ordered?Y.subject.indexOf(this?.deliverPrefix)===0:Y.subject===$){if(Y.subject!==this.sub.getSubject())return;let J=new Xd6.JetStreamStatus(Y);if(J.isFlowControlRequest()){this._push(()=>{Y.respond(),this.notify({type:"flow_control"})});return}if(J.isIdleHeartbeat()){let H=parseInt(Y.headers?.get(Wd0.JsHeaders.LastConsumerSeqHdr)||"0"),N=parseInt(Y.headers?.get(Wd0.JsHeaders.LastStreamSeqHdr)??"0");this.notify({type:"heartbeat",lastStreamSequence:N,lastConsumerSequence:H});let U=Y.headers?.get(Wd0.JsHeaders.ConsumerStalledHdr);if(typeof U==="string"&&U!=="")Y.publisher.publish(U,bX.Empty);return}let{code:K,description:W}=J;if(J.isConsumerDeleted())this.notify({type:"consumer_deleted",code:K,description:W});if(this.abortOnMissingResource){this._push(()=>{this.stop(J.toError())});return}}else{let J=(0,Zd6.toJsMsg)(Y);if(this.ordered){let K=J.info.deliverySequence;if(K!==this.cursor.deliver_seq+1){this.reset();return}this.cursor.deliver_seq=K,this.cursor.stream_seq=J.info.streamSequence}this._push(J)}}}),this.sub.closed.then(()=>{this._push(()=>{this.stop()})}),this.closed().then(()=>{this.sub?.unsubscribe()})}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let X=Z;if(!X.done)X.push($)})})()}}kp1.PushConsumerMessagesImpl=Hd0;class Mp1{api;_info;stream;name;bound;ordered;started;serial;opts;constructor($,Z,X={}){if(this.api=$,this._info=Z,this.stream=Z.stream_name,this.name=Z.name,this.bound=X.bound===!0,this.started=!1,this.opts=X,this.serial=0,this.ordered=X.ordered||!1,this.ordered)this.serial=1}consume($={}){if($={...$},this.started)return Promise.reject(new bX.errors.InvalidOperationError("consumer already started"));if(!this._info.config.deliver_subject)return Promise.reject(Error("deliver_subject is not set, not a push consumer"));if(!this._info.config.deliver_group&&this._info.push_bound)return Promise.reject(new bX.errors.InvalidOperationError("consumer is already bound"));let Z=new Hd0(this,$,this.opts);return this.started=!0,Z.closed().then(()=>{this.started=!1}),Promise.resolve(Z)}delete(){if(this.bound)return Promise.reject(new bX.errors.InvalidOperationError("bound consumers cannot delete"));let{stream_name:$,name:Z}=this._info;return this.api.delete($,Z)}async info($){if(this.bound)return Promise.reject(new bX.errors.InvalidOperationError("bound consumers cannot info"));if($)return Promise.resolve(this._info);let Z=await this.api.info(this.stream,this.name);return this._info=Z,Z}isPullConsumer(){return!1}isPushConsumer(){return!0}}kp1.PushConsumerImpl=Mp1});var yp1=_((fp1)=>{Object.defineProperty(fp1,"__esModule",{value:!0});fp1.StreamsImpl=fp1.StoredMsgImpl=fp1.StreamAPIImpl=fp1.StreamImpl=fp1.ConsumersImpl=void 0;fp1.convertStreamSourceDomain=Bm;var E9=vY(),Yd6=ff(),Cp1=o50(),GJ=bf(),_p1=ED(),fY=qD(),Nd0=Rp1(),Ud0=Yd0(),Fd0=Vp1(),xp1=HN();function Bm($){if($===void 0)return;let{domain:Z}=$;if(Z===void 0)return $;let X=Object.assign({},$);if(delete X.domain,Z==="")return X;if(X.external)throw E9.InvalidArgumentError.format(["domain","external"],"are mutually exclusive");return X.external={api:`$JS.${Z}.API`},X}class s50{api;notified;constructor($){this.api=$,this.notified=!1}checkVersion(){let $=this.api.nc.features.get(E9.Feature.JS_SIMPLIFICATION);if(!$.ok)return Promise.reject(Error(`consumers framework is only supported on servers ${$.min} or better`));return Promise.resolve()}async getPushConsumer($,Z){if(await this.checkVersion(),(0,GJ.minValidation)("stream",$),typeof Z==="string"){(0,GJ.minValidation)("name",Z);let X=await this.api.info($,Z);if(typeof X.config.deliver_subject!=="string")return Promise.reject(Error("not a push consumer"));return new Fd0.PushConsumerImpl(this.api,X)}else if(Z===void 0)return this.getOrderedPushConsumer($);else if((0,_p1.isOrderedPushConsumerOptions)(Z)){let X=Z;return this.getOrderedPushConsumer($,X)}return Promise.reject(Error("unsupported push consumer type"))}async getOrderedPushConsumer($,Z={}){Z=Object.assign({},Z);let{name_prefix:X,deliver_prefix:Q,filter_subjects:Y}=Z;if(delete Z.deliver_prefix,delete Z.name_prefix,delete Z.filter_subjects,typeof Z.opt_start_seq==="number")Z.deliver_policy=fY.DeliverPolicy.StartSequence;if(typeof Z.opt_start_time==="string")Z.deliver_policy=fY.DeliverPolicy.StartTime;X=X||`oc_${E9.nuid.next()}`,(0,GJ.minValidation)("name_prefix",X),Q=Q||(0,E9.createInbox)(this.api.getOptions().watcherPrefix);let G=Object.assign({},Z);if(G.ack_policy=fY.AckPolicy.None,G.inactive_threshold=(0,E9.nanos)(300000),G.num_replicas=1,G.max_deliver=1,G.flow_control=!0,G.idle_heartbeat=(0,E9.nanos)(30000),Array.isArray(Y))G.filter_subjects=Y;if(typeof Y==="string")G.filter_subject=Y;if(typeof G.filter_subjects>"u"&&typeof G.filter_subject>"u")G.filter_subject=">";G.name=`${X}_1`,G.deliver_subject=`${Q}.1`;let J=await this.api.add($,G),K={name_prefix:X,deliver_prefix:Q,ordered:!0};return new Fd0.PushConsumerImpl(this.api,J,K)}getBoundPushConsumer($){if((0,_p1.isBoundPushConsumerOptions)($)){let Z={config:$};return Promise.resolve(new Fd0.PushConsumerImpl(this.api,Z,{bound:!0}))}else return Promise.reject(E9.errors.InvalidArgumentError.format("deliver_subject","is required"))}async get($,Z){if(await this.checkVersion(),typeof Z==="string"){let X=await this.api.info($,Z);if(typeof X.config.deliver_subject==="string")return Promise.reject(Error("not a pull consumer"));else return new Nd0.PullConsumerImpl(this.api,X)}else return this.ordered($,Z)}getConsumerFromInfo($){if(typeof $.config.deliver_subject==="string")throw Error("not a pull consumer");return new Nd0.PullConsumerImpl(this.api,$)}async ordered($,Z={}){await this.checkVersion();let X=this.api;if(await new wd0(X.nc,X.opts).info($),typeof Z.name_prefix==="string")(0,GJ.minValidation)("name_prefix",Z.name_prefix);Z.name_prefix=Z.name_prefix||E9.nuid.next();let G={name:`${Z.name_prefix}_1`,deliver_policy:fY.DeliverPolicy.StartSequence,opt_start_seq:Z.opt_start_seq||1,ack_policy:fY.AckPolicy.None,inactive_threshold:(0,E9.nanos)(300000),num_replicas:1,max_deliver:1,mem_storage:!0};if(Z.headers_only===!0)G.headers_only=!0;if(Array.isArray(Z.filter_subjects))G.filter_subjects=Z.filter_subjects;if(typeof Z.filter_subjects==="string")G.filter_subject=Z.filter_subjects;if(Z.replay_policy)G.replay_policy=Z.replay_policy;if(G.deliver_policy=Z.deliver_policy||fY.DeliverPolicy.StartSequence,Z.deliver_policy===fY.DeliverPolicy.All||Z.deliver_policy===fY.DeliverPolicy.LastPerSubject||Z.deliver_policy===fY.DeliverPolicy.New||Z.deliver_policy===fY.DeliverPolicy.Last)delete G.opt_start_seq,G.deliver_policy=Z.deliver_policy;if(G.deliver_policy===fY.DeliverPolicy.LastPerSubject){if(typeof G.filter_subjects>"u"&&typeof G.filter_subject>"u")G.filter_subject=">"}if(Z.opt_start_time)delete G.opt_start_seq,G.deliver_policy=fY.DeliverPolicy.StartTime,G.opt_start_time=Z.opt_start_time;if(Z.inactive_threshold)G.inactive_threshold=(0,E9.nanos)(Z.inactive_threshold);let J=await this.api.add($,G);return Promise.resolve(new Nd0.PullConsumerImpl(this.api,J,Z))}}fp1.ConsumersImpl=s50;class Om{api;_info;constructor($,Z){this.api=$,this._info=Z}get name(){return this._info.config.name}alternates(){return this.info().then(($)=>{return $.alternates?$.alternates:[]})}async best(){if(await this.info(),this._info.alternates){let $=await this.api.info(this._info.alternates[0].name);return new Om(this.api,$)}else return this}info($=!1,Z){if($)return Promise.resolve(this._info);return this.api.info(this.name,Z).then((X)=>{return this._info=X,this._info})}getConsumer($){return new s50(new Ud0.ConsumerAPIImpl(this.api.nc,this.api.opts)).get(this.name,$)}getPushConsumer($){return new s50(new Ud0.ConsumerAPIImpl(this.api.nc,this.api.opts)).getPushConsumer(this.name,$)}getMessage($){return this.api.getMessage(this.name,$)}deleteMessage($,Z=!0){return this.api.deleteMessage(this.name,$,Z)}resetConsumer($,Z){return new Ud0.ConsumerAPIImpl(this.api.nc,this.api.opts).reset(this.name,$,Z)}}fp1.StreamImpl=Om;class wd0 extends Yd6.BaseApiClientImpl{constructor($,Z){super($,Z)}checkStreamConfigVersions($){let Z=this.nc;if($.metadata){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_STREAM_CONSUMER_METADATA);if(!Y)throw Error(`stream 'metadata' requires server ${Q}`)}if($.first_seq){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_STREAM_FIRST_SEQ);if(!Y)throw Error(`stream 'first_seq' requires server ${Q}`)}if($.subject_transform){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_STREAM_SUBJECT_TRANSFORM);if(!Y)throw Error(`stream 'subject_transform' requires server ${Q}`)}if($.compression){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_STREAM_COMPRESSION);if(!Y)throw Error(`stream 'compression' requires server ${Q}`)}if($.consumer_limits){let{min:Q,ok:Y}=Z.features.get(E9.Feature.JS_DEFAULT_CONSUMER_LIMITS);if(!Y)throw Error(`stream 'consumer_limits' requires server ${Q}`)}function X(Q,Y){if((Y?.subject_transforms?.length||0)>0){let{min:J,ok:K}=Z.features.get(E9.Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!K)throw Error(`${Q} 'subject_transforms' requires server ${J}`)}}if($.sources)$.sources.forEach((Q)=>{X("stream sources",Q)});if($.mirror)X("stream mirror",$.mirror)}minStreamApi($){if($.allow_batched===!0||$.mirror?.consumer||$.sources?.some((Z)=>Z.consumer))return 4;if($.allow_msg_counter===!0||$.allow_atomic===!0||$.allow_msg_schedules===!0||$.persist_mode===fY.PersistMode.Async)return 2;if($.allow_msg_ttl===!0||typeof $.subject_delete_marker_ttl==="number"&&$.subject_delete_marker_ttl>0)return 1;return 0}requiredApiOpts($){if(!this.sendRequiredApiLevel())return{};let Z=this.minStreamApi($);return Z>0?{minApiVersion:Z}:{}}async add($){this.checkStreamConfigVersions($),(0,GJ.validateStreamName)($.name),$.mirror=Bm($.mirror),$.sources=$.sources?.map(Bm);let X=await this._request(`${this.prefix}.STREAM.CREATE.${$.name}`,$,this.requiredApiOpts($));return this._fixInfo(X),X}async delete($){return(0,GJ.validateStreamName)($),(await this._request(`${this.prefix}.STREAM.DELETE.${$}`)).success}async update($,Z={}){if(typeof $==="object"){let J=$;$=J.name,Z=J,console.trace("\x1B[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. \x1B[0m")}this.checkStreamConfigVersions(Z),(0,GJ.validateStreamName)($);let X=await this.info($),Q=Object.assign(X.config,Z);Q.mirror=Bm(Q.mirror),Q.sources=Q.sources?.map(Bm);let G=await this._request(`${this.prefix}.STREAM.UPDATE.${$}`,Q,this.requiredApiOpts(Z));return this._fixInfo(G),G}async info($,Z){(0,GJ.validateStreamName)($);let X=`${this.prefix}.STREAM.INFO.${$}`,Y=await this._request(X,Z),{total:G,limit:J}=Y,K=Y.state.subjects?Object.getOwnPropertyNames(Y.state.subjects).length:1;if(G&&G>K){let W=[Y],H=Z||{},N=0;while(G>K){N++,H.offset=J*N;let F=await this._request(X,H);G=F.total,W.push(F);let w=Object.getOwnPropertyNames(F.state.subjects).length;if(K+=w,w<J)break}let U={};for(let F=0;F<W.length;F++)if(Y=W[F],Y.state.subjects)U=Object.assign(U,Y.state.subjects);Y.offset=0,Y.total=0,Y.limit=0,Y.state.subjects=U}return this._fixInfo(Y),Y}list($=""){let Z=$?.length?{subject:$}:{},X=(Y)=>{let G=Y;return G.streams.forEach((J)=>{this._fixInfo(J)}),G.streams},Q=`${this.prefix}.STREAM.LIST`;return new Cp1.ListerImpl(Q,X,this,Z)}_fixInfo($){$.config.sealed=$.config.sealed||!1,$.config.deny_delete=$.config.deny_delete||!1,$.config.deny_purge=$.config.deny_purge||!1,$.config.allow_rollup_hdrs=$.config.allow_rollup_hdrs||!1}async purge($,Z){if(Z){let{keep:Q,seq:Y}=Z;if(typeof Q==="number"&&typeof Y==="number")throw E9.InvalidArgumentError.format(["keep","seq"],"are mutually exclusive")}return(0,GJ.validateStreamName)($),await this._request(`${this.prefix}.STREAM.PURGE.${$}`,Z)}async deleteMessage($,Z,X=!0){(0,GJ.validateStreamName)($);let Q={seq:Z};if(!X)Q.no_erase=!0;return(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${$}`,Q)).success}async getMessage($,Z){(0,GJ.validateStreamName)($);try{let Q=await this._request(`${this.prefix}.STREAM.MSG.GET.${$}`,Z);return new Bd0(Q)}catch(X){if(X instanceof xp1.JetStreamApiError&&X.code===xp1.JetStreamApiCodes.NoMessageFound)return null;return Promise.reject(X)}}find($){return this.findStream($)}names($=""){let Z=$?.length?{subject:$}:{},X=(Y)=>{return Y.streams},Q=`${this.prefix}.STREAM.NAMES`;return new Cp1.ListerImpl(Q,X,this,Z)}async get($){let Z=await this.info($);return Promise.resolve(new Om(this,Z))}}fp1.StreamAPIImpl=wd0;class Bd0{_header;smr;static jc;constructor($){this.smr=$}get pending(){return 0}get lastSequence(){return 0}get subject(){return this.smr.message.subject}get seq(){return this.smr.message.seq}get timestamp(){return this.smr.message.time}get time(){return new Date(Date.parse(this.timestamp))}get data(){return this.smr.message.data?this._parse(this.smr.message.data):E9.Empty}get header(){if(!this._header)if(this.smr.message.hdrs){let $=this._parse(this.smr.message.hdrs);this._header=E9.MsgHdrsImpl.decode($)}else this._header=(0,E9.headers)();return this._header}_parse($){let Z=atob($),X=Z.length,Q=new Uint8Array(X);for(let Y=0;Y<X;Y++)Q[Y]=Z.charCodeAt(Y);return Q}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return E9.TD.decode(this.data)}}fp1.StoredMsgImpl=Bd0;class vp1{api;constructor($){this.api=$}get($){return this.api.info($).then((Z)=>{return new Om(this.api,Z)})}}fp1.StreamsImpl=vp1});var Ld0=_((cp1)=>{Object.defineProperty(cp1,"__esModule",{value:!0});cp1.DirectConsumer=cp1.DirectMsgImpl=cp1.DirectStreamAPIImpl=void 0;var Nd6=ff(),gf=ED(),JJ=vY(),gp1=bf(),Od0=HN();class hp1 extends Nd6.BaseApiClientImpl{constructor($,Z){super($,Z)}async getMessage($,Z){if((0,gp1.validateStreamName)($),"start_time"in Z){let{min:H,ok:N}=this.nc.features.get(JJ.Feature.JS_BATCH_DIRECT_GET);if(!N)throw Error(`start_time direct option require server ${H}`)}let X=Z,{last_by_subj:Q}=X;if(Q)X=null;let Y=X?JSON.stringify(X):JJ.Empty,G=this.opts.apiPrefix||"$JS.API",J=Q?`${G}.DIRECT.GET.${$}.${Q}`:`${G}.DIRECT.GET.${$}`,K=await this.nc.request(J,Y,{timeout:this.timeout});if(K.headers?.code!==0){let H=new Od0.JetStreamStatus(K);if(H.isMessageNotFound())return Promise.resolve(null);else return Promise.reject(H.toError())}let W=new e50(K);return Promise.resolve(W)}getBatch($,Z){return Z.batch=Z.batch||1024,this.get($,Z)}getLastMessagesFor($,Z){return this.get($,Z)}get($,Z){Z={...Z};let{min:X,ok:Q}=this.nc.features.get(JJ.Feature.JS_BATCH_DIRECT_GET);if(!Q)return Promise.reject(Error(`batch direct require server ${X}`));(0,gp1.validateStreamName)($);let Y=typeof Z.callback==="function"?Z.callback:null,G=new JJ.QueuedIteratorImpl;function J(L,D){if(L){G.push(()=>{L.err?G.stop(L.err):G.stop()});return}G.push(D)}function K(L,D){let E=Y;if(typeof D==="function"){D();return}E(L,D)}if(Y)G.iterClosed.then((L)=>{W({err:L?L:void 0},{}),U.unsubscribe()});let W=Y?K:J,H=(0,JJ.createInbox)(this.nc.options.inboxPrefix),N=!1,U=this.nc.subscribe(H,{timeout:5000,callback:(L,D)=>{if(L){G.stop(L),U.unsubscribe();return}let E=Od0.JetStreamStatus.maybeParseStatus(D);if(E){if(E.isNoResults())W({},()=>{G.stop()});if(E.isEndOfBatch())W({},()=>{G.stop()});else{let z=E.toError();W({err:z},()=>{G.stop(z)})}return}if(!N)if(typeof D.headers?.get("Nats-Num-Pending")!=="string")U.unsubscribe(),W({},()=>{G.stop()});else N=!0;W(null,new e50(D))}}),w=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${$}`,B=JSON.stringify(Z,(L,D)=>{if((L==="up_to_time"||L==="start_time")&&D instanceof Date)return D.toISOString();return D});return this.nc.publish(w,B,{reply:H}),Promise.resolve(G)}}cp1.DirectStreamAPIImpl=hp1;class e50{data;header;constructor($){if(!$.headers)throw Error("headers expected");this.data=$.data,this.header=$.headers}get subject(){return this.header.last(gf.DirectMsgHeaders.Subject)}get seq(){let $=this.header.last(gf.DirectMsgHeaders.Sequence);return typeof $==="string"?parseInt($):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(gf.DirectMsgHeaders.TimeStamp)}get stream(){return this.header.last(gf.DirectMsgHeaders.Stream)}get lastSequence(){let $=this.header.last(gf.DirectMsgHeaders.LastSequence);return typeof $==="string"?parseInt($):0}get pending(){let $=this.header.last(gf.DirectMsgHeaders.NumPending);return typeof $==="string"?parseInt($):-1}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return JJ.TD.decode(this.data)}}cp1.DirectMsgImpl=e50;function Ud6($){return typeof $==="object"&&"start_time"in $}function Fd6($){return typeof $==="object"&&"max_bytes"in $}class up1{stream;api;cursor;listeners;start;constructor($,Z,X){this.stream=$,this.api=Z,this.cursor={last:0},this.listeners=[],this.start=X}getOptions($){$=$||{};let Z={};if(this.cursor.last===0)if(Ud6(this.start))Z.start_time=this.start.start_time;else Z.seq=this.start.seq||1;else Z.seq=this.cursor.last+1;if(Fd6($))Z.max_bytes=$.max_bytes;else Z.batch=$.batch??100;return Z}status(){let $=new JJ.QueuedIteratorImpl;return this.listeners.push($),$}notify($){if(this.listeners.length>0)(()=>{let Z=[];this.listeners.forEach((X)=>{let Q=X;if(!Q.done)Q.push($);else Z.push(Q)}),this.listeners=this.listeners.filter((X)=>!Z.includes(X))})()}debug(){console.log(this.cursor)}consume($){let Z,X,Q=new JJ.QueuedIteratorImpl;return(async()=>{while(!0){if(this.cursor.pending===0)this.notify({type:"debug",code:0,description:"sleeping for 2500"}),Z=(0,JJ.delay)(2500),await Z;if(Q.done)break;X=(0,JJ.deferred)();let Y=this.getOptions($);this.notify({type:"next",options:Object.assign({},$)}),Y.callback=(J,K)=>{if(J){if(J.err)if(J.err instanceof Od0.JetStreamStatusError)this.notify({type:"debug",code:J.err.code,description:J.err.message});else this.notify({type:"debug",code:0,description:J.err.message});X.resolve()}else if(K.lastSequence>0&&K.lastSequence!==this.cursor.last)G.stop(),X.resolve(),this.notify({type:"reset",name:"direct"});else Q.push(K),Q.received++,this.cursor.last=K.seq,this.cursor.pending=K.pending};let G=await this.api.getBatch(this.stream,Y);Q.iterClosed.then(()=>{G.stop(),Z?.cancel(),X?.resolve()}),await X}})().catch((Y)=>{Q.stop(Y)}),Promise.resolve(Q)}async fetch($){let Z=this.getOptions($),X=new JJ.QueuedIteratorImpl,Q=await this.api.get(this.stream,Object.assign({callback:(Y,G)=>{if(Y)X.push(()=>{Y.err?X.stop(Y.err):X.stop()});else if(G.lastSequence>0&&G.lastSequence!==this.cursor.last)X.push(()=>{X.stop()}),Q.stop();else X.push(G),X.received++,this.cursor.last=G.seq,this.cursor.pending=G.pending}},Z));return X.iterClosed.then(()=>{Q.stop()}),X}async next(){let $=await this.api.getMessage(this.stream,{seq:this.cursor.last+1}),Z=$?.seq;if(Z)this.cursor.last=Z;return $}}cp1.DirectConsumer=up1});var rp1=_((tp1)=>{Object.defineProperty(tp1,"__esModule",{value:!0});tp1.BatchPublisherImpl=tp1.JetStreamClientImpl=tp1.JetStreamManagerImpl=void 0;tp1.startFastIngest=Ld6;tp1.toJetStreamClient=Dd6;tp1.jetstream=Ed0;tp1.jetstreamManager=ip1;tp1.scheduleSpecToHeader=np1;var Dd0=ff(),mp1=Yd0(),u$=vY(),$90=yp1(),yX=qD(),dp1=HN(),Od6=Ld0();function Ld6($,Z,X,Q,Y=5000){let{ackInterval:G,allowGaps:J,inboxPrefix:K,maxOutstandingAcks:W,...H}=Q,N=K??"_INBOX";if(!N||/\s/.test(N)||/[*>]/.test(N))return Promise.reject(Error(`inboxPrefix must be non-empty, no wildcards or whitespace (got "${N}")`));let U={ackInterval:G??10,allowGaps:J,inboxPrefix:N,maxOutstandingAcks:Math.min(3,Math.max(1,W??2))},F=new pp1($,U,Z,Y);return F.start(X,H).then(()=>F)}function Dm($){let Z=$.expect||{},X=$.headers||(0,u$.headers)();if($.msgID)X.set(yX.PubHeaders.MsgIdHdr,$.msgID);if(Z.lastMsgID)X.set(yX.PubHeaders.ExpectedLastMsgIdHdr,Z.lastMsgID);if(Z.streamName)X.set(yX.PubHeaders.ExpectedStreamHdr,Z.streamName);if(typeof Z.lastSequence==="number")X.set(yX.PubHeaders.ExpectedLastSeqHdr,`${Z.lastSequence}`);if(typeof Z.lastSubjectSequence==="number")X.set(yX.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Z.lastSubjectSequence}`);if(Z.lastSubjectSequenceSubject)X.set(yX.PubHeaders.ExpectedLastSubjectSequenceSubjectHdr,Z.lastSubjectSequenceSubject);if($.ttl)X.set(yX.PubHeaders.MessageTTL,`${$.ttl}`);if($.schedule&&$.cancelSchedule)throw Error("schedule and cancelSchedule are mutually exclusive");if($.schedule){let Q=$.schedule;if(Q.specification)X.set(yX.PubHeaders.Schedule,np1(Q.specification));if(Q.target)X.set(yX.PubHeaders.ScheduleTarget,Q.target);if(Q.source)X.set(yX.PubHeaders.ScheduleSource,Q.source);if(Q.ttl)X.set(yX.PubHeaders.ScheduleTTL,Q.ttl);if(Q.timezone)X.set(yX.PubHeaders.ScheduleTimeZone,Q.timezone);if(Q.rollup)X.set(yX.PubHeaders.ScheduleRollup,Q.rollup)}if($.cancelSchedule)X.set(yX.PubHeaders.Scheduler,$.cancelSchedule.scheduleSubject),X.set(yX.PubHeaders.ScheduleNext,"purge");return X}function Dd6($){if(typeof $.nc>"u")return Ed0($);return $}function Ed0($,Z={}){return new jd0($,Z)}async function ip1($,Z={}){let X=new zd0($,Z);if(Z.checkAPI!==!1)try{await X.getAccountInfo()}catch(Q){throw Q}return X}class zd0 extends Dd0.BaseApiClientImpl{streams;consumers;direct;constructor($,Z){super($,Z);this.streams=new $90.StreamAPIImpl($,Z),this.consumers=new mp1.ConsumerAPIImpl($,Z),this.direct=new Od6.DirectStreamAPIImpl($,Z)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return Ed0(this.nc,this.getOptions())}advisories(){let $=new u$.QueuedIteratorImpl;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(Z,X)=>{if(Z)throw Z;try{let Q=this.parseJsResponse(X),Y=Q.type.split("."),G=Y[Y.length-1];$.push({kind:G,data:Q})}catch(Q){$.stop(Q)}}}),$}}tp1.JetStreamManagerImpl=zd0;function np1($){if(typeof $==="string")return $;if($ instanceof Date)return`@at ${$.toISOString()}`;if("at"in $)return`@at ${$.at instanceof Date?$.at.toISOString():$.at}`;if("every"in $)return Ed6($.every),`@every ${$.every}`;if("cron"in $)return $.cron;if("predefined"in $)return $.predefined;throw Error("invalid schedule specification")}function Ed6($){let Z=$.trim(),X=/(\d+(?:\.\d+)?)(ns|us|\u00B5s|ms|s|m|h)/g,Q=0,Y=0,G;while((G=X.exec(Z))!==null){if(G.index!==Y)break;Y+=G[0].length;let J=parseFloat(G[1]),K=G[2];Q+=K==="ns"?J/1e6:K==="us"||K==="\xB5s"?J/1000:K==="ms"?J:K==="s"?J*1000:K==="m"?J*60000:J*3600000}if(Z===""||Y!==Z.length)throw Error(`@every: unrecognized duration format: "${$}"`);if(Q<1000)throw Error("@every interval must be at least 1s")}class jd0 extends Dd0.BaseApiClientImpl{consumers;streams;consumerAPI;streamAPI;constructor($,Z){super($,Z);this.consumerAPI=new mp1.ConsumerAPIImpl($,Z),this.streamAPI=new $90.StreamAPIImpl($,Z),this.consumers=new $90.ConsumersImpl(this.consumerAPI),this.streams=new $90.StreamsImpl(this.streamAPI)}jetstreamManager($){if($===void 0)$=this.opts.checkAPI;let Z=Object.assign({},this.opts,{checkAPI:$});try{(0,u$.createInbox)(Z.watcherPrefix)}catch(X){return Promise.reject(X)}return ip1(this.nc,Z)}get apiPrefix(){return this.prefix}startBatch($,Z,X){let Q=(0,u$.deferred)(),Y=new Pd0(this);return Y.first($,Z,X).then(()=>{Q.resolve(Y)}).catch((G)=>{Q.reject(G)}),Q}async _publish($,Z=u$.Empty,X){if(X=X||{},X={...X},X.cancelSchedule&&X.cancelSchedule.scheduleSubject===$)throw Error("cancelSchedule.scheduleSubject must not equal the publish subject");let Q=Dm(X),Y=X.timeout||this.timeout,G={};if(Y)G.timeout=Y;if(X)G.headers=Q;let{retries:J}=X;J=J||1;let K=(0,u$.backoff)(),W=null;for(let H=0;H<J;H++)try{W=await this.nc.request($,Z,G);break}catch(N){let U=N instanceof u$.RequestError?N:null;if((N instanceof u$.errors.TimeoutError||U?.isNoResponders())&&H+1<J)await(0,u$.delay)(K.backoff(H));else throw U?.isNoResponders()?new dp1.JetStreamNotEnabled("jetstream is not enabled",{cause:N}):N}return W}async publish($,Z=u$.Empty,X){let Q=await this._publish($,Z,X),Y=this.parseJsResponse(Q);if(Y.stream==="")throw new dp1.JetStreamError("invalid ack response");return Y.duplicate=Y.duplicate?Y.duplicate:!1,Y}}tp1.JetStreamClientImpl=jd0;class Pd0{nc;js;id;count;done;constructor($){this.count=0,this.id=u$.nuid.next(),this.js=$,this.nc=this.js.nc,this.done=!1}async first($,Z,X){X=X||{},X.headers=X?.headers||(0,u$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString());let Q=await this.js._publish($,Z,X);if(Q.data.length>0)this.js.parseJsResponse(Q)}add($,Z,X={ack:!1}){if(this.done)throw Error("batch publisher is done");if(X.headers=X?.headers||(0,u$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString()),"ack"in X&&X.ack===!0){let Y=(0,u$.deferred)();return this.js._publish($,Z,{headers:X.headers,timeout:X.timeout}).then((G)=>{if(G.data.length>0)this.js.parseJsResponse(G);Y.resolve()}).catch((G)=>{this.done=!0,Y.reject(G)}),Y}else return this.nc.publish($,Z,{headers:X.headers})}async commit($,Z,X={}){if(this.done)throw Error("batch publisher is done");else this.done=!0;X.headers=X?.headers||(0,u$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString()),X.headers.set("Nats-Batch-Commit","1");let Y=(await this.js._publish($,Z,{headers:X.headers,timeout:X.timeout||0})).json();if(Y.count!==this.count)throw Error("batch didn't contain number of published messages");return Y}}tp1.BatchPublisherImpl=Pd0;var Lm="batch closed",J7={Start:0,Append:1,Final:2,EOB:3,Ping:4};class pp1{batch;nc;batchSubj;gapMode;initialFlow;seq;acked;ackInterval;inboxPrefix;maxOutstandingAcks;defaultTimeout;gapIter;sub;pending;closed;closeErr;startDeferred;closedDeferred;constructor($,Z,X,Q){this.nc=$,this.batchSubj=X,this.gapMode=Z.allowGaps?"ok":"fail",this.initialFlow=Z.ackInterval,this.inboxPrefix=Z.inboxPrefix,this.maxOutstandingAcks=Z.maxOutstandingAcks,this.defaultTimeout=Q,this.batch=u$.nuid.next(),this.seq=0,this.acked=0,this.ackInterval=Z.ackInterval,this.pending=new Map,this.closed=!1,this.startDeferred=(0,u$.deferred)(),this.closedDeferred=(0,u$.deferred)(),this.closedDeferred.catch(()=>{}),this.startDeferred.catch(()=>{});let Y=`${this.inboxPrefix}.${this.batch}.>`;this.sub=this.nc.subscribe(Y,{callback:(G,J)=>this.route(G,J)})}replyFor($,Z){return`${this.inboxPrefix}.${this.batch}.${this.initialFlow}.${this.gapMode}.${Z}.${$}.$FI`}start($,Z){this.seq=1;let X=this.replyFor(J7.Start,1),Q=Z?Dm(Z):void 0;return this.nc.publish(this.batchSubj,$,{reply:X,headers:Q}),this.deadlineOrClose(this.startDeferred,Z?.timeout??this.defaultTimeout)}deadlineOrClose($,Z){return(0,u$.deadline)($,Z).catch((X)=>{if(!this.closed)this.close(X);throw X})}route($,Z){if($){this.close($);return}let X;try{X=(0,Dd0.parseJsResponse)(Z)}catch(J){this.close(J);return}if("batch"in X&&typeof X.batch==="string"){let J=X,K=this.pending.get(Z.subject);if(K&&(K.op===J7.Final||K.op===J7.EOB))K.deferred.resolve(J),this.pending.delete(Z.subject);for(let[,W]of this.pending)if(W.op===J7.Append||W.op===J7.Ping)W.deferred.resolve({batchSeq:W.seq,ackSeq:this.acked});else W.deferred.reject(Error(Lm));this.pending.clear(),this.resolveStart(),this.closedDeferred.resolve(J),this.closed=!0,this.gapIter?.stop(),this.sub.unsubscribe();return}if(X.type==="gap"){if(this.gapIter){let J=X;this.gapIter.push({lastSeq:J.last_seq,seq:J.seq})}return}let Y=X;if(typeof Y.msgs==="number")this.ackInterval=Y.msgs;if(typeof Y.seq==="number"&&Y.seq>this.acked)this.acked=Y.seq;this.resolveStart();let G=this.pending.get(Z.subject);if(G&&(G.op===J7.Append||G.op===J7.Ping))G.deferred.resolve({batchSeq:G.seq,ackSeq:this.acked}),this.pending.delete(Z.subject);for(let[J,K]of this.pending)if(K.op===J7.Append&&K.seq-this.acked<this.ackInterval*this.maxOutstandingAcks)K.deferred.resolve({batchSeq:K.seq,ackSeq:this.acked}),this.pending.delete(J)}resolveStart(){this.startDeferred.resolve()}close($){this.closed=!0,this.closeErr=$;for(let[,Z]of this.pending)Z.deferred.reject($);this.pending.clear(),this.startDeferred.reject($),this.closedDeferred.reject($),this.gapIter?.stop(),this.sub.unsubscribe()}add($,Z,X){if(this.closed)return Promise.reject(Error(Lm));let Q=++this.seq,Y=this.replyFor(J7.Append,Q),G=X?Dm(X):void 0;if(this.nc.publish($,Z,{reply:Y,headers:G}),Q-this.acked<this.ackInterval*this.maxOutstandingAcks)return Promise.resolve({batchSeq:Q,ackSeq:this.acked});let J=(0,u$.deferred)();return this.pending.set(Y,{seq:Q,op:J7.Append,deferred:J}),this.deadlineOrClose(J,X?.timeout??this.defaultTimeout)}last($,Z,X){if(this.closed)return Promise.reject(Error(Lm));let Q=++this.seq,Y=this.replyFor(J7.Final,Q),G=(0,u$.deferred)();this.pending.set(Y,{seq:Q,op:J7.Final,deferred:G});let J=X?Dm(X):void 0;return this.nc.publish($,Z,{reply:Y,headers:J}),this.deadlineOrClose(G,X?.timeout??this.defaultTimeout)}end($){if(this.closed)return Promise.reject(Error(Lm));let Z=++this.seq,X=this.replyFor(J7.EOB,Z),Q=(0,u$.deferred)();this.pending.set(X,{seq:Z,op:J7.EOB,deferred:Q});let Y=$?Dm($):void 0;return this.nc.publish(this.batchSubj,u$.Empty,{reply:X,headers:Y}),this.deadlineOrClose(Q,$?.timeout??this.defaultTimeout)}ping($=this.defaultTimeout){if(this.closed)return Promise.reject(Error(Lm));let Z=this.replyFor(J7.Ping,this.seq),X=this.pending.get(Z);if(X&&X.op===J7.Ping)return(0,u$.deadline)(X.deferred,$);let Q=(0,u$.deferred)();return this.pending.set(Z,{seq:this.seq,op:J7.Ping,deferred:Q}),this.nc.publish(this.batchSubj,u$.Empty,{reply:Z}),this.deadlineOrClose(Q,$)}done(){return this.closedDeferred}gaps(){if(!this.gapIter)this.gapIter=new u$.QueuedIteratorImpl;return this.gapIter}}});var Z90=_((P4)=>{Object.defineProperty(P4,"__esModule",{value:!0});P4.validateStreamName=P4.jserrors=P4.JetStreamStatusError=P4.JetStreamStatus=P4.JetStreamError=P4.JetStreamApiError=P4.JetStreamApiCodes=P4.isMessageNotFound=P4.ListerImpl=P4.StoreCompression=P4.StorageType=P4.RetentionPolicy=P4.ReplayPolicy=P4.PubHeaders=P4.PersistMode=P4.DiscardPolicy=P4.DeliverPolicy=P4.AckPolicy=P4.DirectMsgImpl=P4.BaseApiClientImpl=P4.toJetStreamClient=P4.startFastIngest=P4.jetstreamManager=P4.JetStreamClientImpl=P4.jetstream=P4.RepublishHeaders=P4.JsHeaders=P4.isPushConsumer=P4.isPullConsumer=P4.isOrderedPushConsumerOptions=P4.isBoundPushConsumerOptions=P4.DirectMsgHeaders=P4.AdvisoryKind=void 0;var aF=ED();Object.defineProperty(P4,"AdvisoryKind",{enumerable:!0,get:function(){return aF.AdvisoryKind}});Object.defineProperty(P4,"DirectMsgHeaders",{enumerable:!0,get:function(){return aF.DirectMsgHeaders}});Object.defineProperty(P4,"isBoundPushConsumerOptions",{enumerable:!0,get:function(){return aF.isBoundPushConsumerOptions}});Object.defineProperty(P4,"isOrderedPushConsumerOptions",{enumerable:!0,get:function(){return aF.isOrderedPushConsumerOptions}});Object.defineProperty(P4,"isPullConsumer",{enumerable:!0,get:function(){return aF.isPullConsumer}});Object.defineProperty(P4,"isPushConsumer",{enumerable:!0,get:function(){return aF.isPushConsumer}});Object.defineProperty(P4,"JsHeaders",{enumerable:!0,get:function(){return aF.JsHeaders}});Object.defineProperty(P4,"RepublishHeaders",{enumerable:!0,get:function(){return aF.RepublishHeaders}});var Em=rp1();Object.defineProperty(P4,"jetstream",{enumerable:!0,get:function(){return Em.jetstream}});Object.defineProperty(P4,"JetStreamClientImpl",{enumerable:!0,get:function(){return Em.JetStreamClientImpl}});Object.defineProperty(P4,"jetstreamManager",{enumerable:!0,get:function(){return Em.jetstreamManager}});Object.defineProperty(P4,"startFastIngest",{enumerable:!0,get:function(){return Em.startFastIngest}});Object.defineProperty(P4,"toJetStreamClient",{enumerable:!0,get:function(){return Em.toJetStreamClient}});var qd6=ff();Object.defineProperty(P4,"BaseApiClientImpl",{enumerable:!0,get:function(){return qd6.BaseApiClientImpl}});var Md6=Ld0();Object.defineProperty(P4,"DirectMsgImpl",{enumerable:!0,get:function(){return Md6.DirectMsgImpl}});var FN=qD();Object.defineProperty(P4,"AckPolicy",{enumerable:!0,get:function(){return FN.AckPolicy}});Object.defineProperty(P4,"DeliverPolicy",{enumerable:!0,get:function(){return FN.DeliverPolicy}});Object.defineProperty(P4,"DiscardPolicy",{enumerable:!0,get:function(){return FN.DiscardPolicy}});Object.defineProperty(P4,"PersistMode",{enumerable:!0,get:function(){return FN.PersistMode}});Object.defineProperty(P4,"PubHeaders",{enumerable:!0,get:function(){return FN.PubHeaders}});Object.defineProperty(P4,"ReplayPolicy",{enumerable:!0,get:function(){return FN.ReplayPolicy}});Object.defineProperty(P4,"RetentionPolicy",{enumerable:!0,get:function(){return FN.RetentionPolicy}});Object.defineProperty(P4,"StorageType",{enumerable:!0,get:function(){return FN.StorageType}});Object.defineProperty(P4,"StoreCompression",{enumerable:!0,get:function(){return FN.StoreCompression}});var kd6=o50();Object.defineProperty(P4,"ListerImpl",{enumerable:!0,get:function(){return kd6.ListerImpl}});var kD=HN();Object.defineProperty(P4,"isMessageNotFound",{enumerable:!0,get:function(){return kD.isMessageNotFound}});Object.defineProperty(P4,"JetStreamApiCodes",{enumerable:!0,get:function(){return kD.JetStreamApiCodes}});Object.defineProperty(P4,"JetStreamApiError",{enumerable:!0,get:function(){return kD.JetStreamApiError}});Object.defineProperty(P4,"JetStreamError",{enumerable:!0,get:function(){return kD.JetStreamError}});Object.defineProperty(P4,"JetStreamStatus",{enumerable:!0,get:function(){return kD.JetStreamStatus}});Object.defineProperty(P4,"JetStreamStatusError",{enumerable:!0,get:function(){return kD.JetStreamStatusError}});Object.defineProperty(P4,"jserrors",{enumerable:!0,get:function(){return kD.jserrors}});var Sd6=bf();Object.defineProperty(P4,"validateStreamName",{enumerable:!0,get:function(){return Sd6.validateStreamName}})});var SD=_((Z9)=>{Object.defineProperty(Z9,"__esModule",{value:!0});Z9.StoreCompression=Z9.StorageType=Z9.RetentionPolicy=Z9.RepublishHeaders=Z9.ReplayPolicy=Z9.PubHeaders=Z9.PersistMode=Z9.JsHeaders=Z9.JetStreamError=Z9.JetStreamApiError=Z9.JetStreamApiCodes=Z9.isPushConsumer=Z9.isPullConsumer=Z9.DiscardPolicy=Z9.DirectMsgHeaders=Z9.DeliverPolicy=Z9.AdvisoryKind=Z9.AckPolicy=Z9.jetstreamManager=Z9.jetstream=void 0;var ap1=Z90();Object.defineProperty(Z9,"jetstream",{enumerable:!0,get:function(){return ap1.jetstream}});Object.defineProperty(Z9,"jetstreamManager",{enumerable:!0,get:function(){return ap1.jetstreamManager}});var _Z=Z90();Object.defineProperty(Z9,"AckPolicy",{enumerable:!0,get:function(){return _Z.AckPolicy}});Object.defineProperty(Z9,"AdvisoryKind",{enumerable:!0,get:function(){return _Z.AdvisoryKind}});Object.defineProperty(Z9,"DeliverPolicy",{enumerable:!0,get:function(){return _Z.DeliverPolicy}});Object.defineProperty(Z9,"DirectMsgHeaders",{enumerable:!0,get:function(){return _Z.DirectMsgHeaders}});Object.defineProperty(Z9,"DiscardPolicy",{enumerable:!0,get:function(){return _Z.DiscardPolicy}});Object.defineProperty(Z9,"isPullConsumer",{enumerable:!0,get:function(){return _Z.isPullConsumer}});Object.defineProperty(Z9,"isPushConsumer",{enumerable:!0,get:function(){return _Z.isPushConsumer}});Object.defineProperty(Z9,"JetStreamApiCodes",{enumerable:!0,get:function(){return _Z.JetStreamApiCodes}});Object.defineProperty(Z9,"JetStreamApiError",{enumerable:!0,get:function(){return _Z.JetStreamApiError}});Object.defineProperty(Z9,"JetStreamError",{enumerable:!0,get:function(){return _Z.JetStreamError}});Object.defineProperty(Z9,"JsHeaders",{enumerable:!0,get:function(){return _Z.JsHeaders}});Object.defineProperty(Z9,"PersistMode",{enumerable:!0,get:function(){return _Z.PersistMode}});Object.defineProperty(Z9,"PubHeaders",{enumerable:!0,get:function(){return _Z.PubHeaders}});Object.defineProperty(Z9,"ReplayPolicy",{enumerable:!0,get:function(){return _Z.ReplayPolicy}});Object.defineProperty(Z9,"RepublishHeaders",{enumerable:!0,get:function(){return _Z.RepublishHeaders}});Object.defineProperty(Z9,"RetentionPolicy",{enumerable:!0,get:function(){return _Z.RetentionPolicy}});Object.defineProperty(Z9,"StorageType",{enumerable:!0,get:function(){return _Z.StorageType}});Object.defineProperty(Z9,"StoreCompression",{enumerable:!0,get:function(){return _Z.StoreCompression}})});import{mkdir as _d6,readdir as xd6,readFile as Ad0,stat as X90,unlink as vd6,writeFile as fd6}from"fs/promises";import{createHmac as bd6}from"crypto";import{dirname as yd6,join as zm}from"path";function Td0($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return zm(gd6,Z)}function hf($,Z){return zm(Td0($),bK(Z))}class nK{orgId;baseUrl;constructor($,Z){this.orgId=$;this.baseUrl=Z}async getBytesOrPresign($,Z){let X=hf(this.orgId,$),Q=await X90(X),Y=SZ($);if(Q.size>Z.presignWhenLargerThan)return{error:"FILE_TOO_LARGE",size:Q.size,maxInlineSize:Z.presignWhenLargerThan,presignedUrl:await this.presignedGetUrl($),contentType:Y};let G=await Ad0(X),J=x$0(Y);return{content:J?new TextDecoder().decode(G):Buffer.from(G).toString("base64"),contentType:Y,encoding:J?"utf-8":"base64",size:Q.size,lastModified:Q.mtime}}async getBytes($){let Z=await Ad0(hf(this.orgId,$));return new Uint8Array(Z)}async put($,Z,X){let Q=hf(this.orgId,$);return await _d6(yd6(Q),{recursive:!0}),await fd6(Q,typeof Z==="string"?Buffer.from(Z,"utf-8"):Z),{key:$}}async list($){let Z=$?.prefix?zm(Td0(this.orgId),bK($.prefix)):Td0(this.orgId),X;try{X=await xd6(Z,{withFileTypes:!0})}catch{return{objects:[],isTruncated:!1}}let Q=$?.maxKeys??1000,Y=$?.prefix,G=X.filter((K)=>K.isFile());if($?.delimiter){let K=[],W=X.filter((B)=>B.isDirectory());for(let B of W){let L=Y?`${Y}/${B.name}/`:`${B.name}/`;K.push(L)}K.sort();let H=Q,N=K.slice(0,H);H-=N.length;let U=G.slice(0,H),F=K.length+G.length;return{objects:await Promise.all(U.map(async(B)=>{let L=await X90(zm(Z,B.name));return{key:Y?`${Y}/${B.name}`:B.name,size:L.size,lastModified:L.mtime}})),isTruncated:F>Q,commonPrefixes:N.length>0?N:void 0}}return{objects:await Promise.all(G.slice(0,Q).map(async(K)=>{let W=await X90(zm(Z,K.name));return{key:Y?`${Y}/${K.name}`:K.name,size:W.size,lastModified:W.mtime}})),isTruncated:G.length>Q}}async delete($){await vd6(hf(this.orgId,$))}async head($){let Z=await X90(hf(this.orgId,$));return{contentType:SZ($),size:Z.size,lastModified:Z.mtime}}async presignedGetUrl($,Z,X){if(X?.requireFetchable)throw Error("object storage returned a not fetchable (data:) URL; configure real S3/R2/MinIO for large-payload offload");let Q=hf(this.orgId,$),Y=await Ad0(Q),G=SZ($),J=Buffer.from(Y).toString("base64");return`data:${G};base64,${J}`}async presignedPutUrl($,Z=3600){if(!this.baseUrl)throw Error("baseUrl required for presigned PUT URLs in dev mode");let X=bK($),Q=Math.floor(Date.now()/1000)+Z,Y=J1().encryptionKey||"dev-secret",G=`${this.orgId}:${X}:${Q}:PUT`,J=bd6("sha256",Y).update(G).digest("hex"),K=new URL(`/api/dev-assets/${this.orgId}/${X}`,this.baseUrl);return K.searchParams.set("expires",Q.toString()),K.searchParams.set("signature",J),K.searchParams.set("method","PUT"),K.toString()}}var gd6="./data/assets";var jm=O(()=>{yK();c8()});function uf($){return hd6.test($)&&$!=="."&&$!==".."}function xZ($){if(!uf($))throw Error(`Invalid org-fs volume name: ${JSON.stringify($)}`)}function vZ($){return bK($)}function cf($){let Z=$.lastIndexOf("/");return Z===-1?"":$.slice(0,Z)}function sF($){let Z=cf($);if(Z==="")return[];let X=Z.split("/"),Q=[],Y="";for(let G of X)Y=Y===""?G:`${Y}/${G}`,Q.push(Y);return Q}function pK($,Z){return`${sp1}/${$}/${Z}`}function ep1($){return`${sp1}/${$}/`}var hd6,sp1="_fs";var Pm=O(()=>{yK();hd6=/^[A-Za-z0-9_.-]{1,128}$/});import{createHmac as Id0,randomBytes as Rd0,scrypt as ud6,timingSafeEqual as $t1}from"crypto";import{promisify as cd6}from"util";async function Xt1($){let Z=Rd0(16),X=await Zt1($,Z,ld6);return`scrypt$${Z.toString("hex")}$${X.toString("hex")}`}async function Qt1($,Z){let X=Z.split("$");if(X.length!==3||X[0]!=="scrypt")return!1;let Q=Buffer.from(X[1],"hex"),Y=Buffer.from(X[2],"hex");if(Q.length===0||Y.length===0)return!1;let G;try{G=await Zt1($,Q,Y.length)}catch{return!1}return Y.length===G.length&&$t1(Y,G)}function Yt1(){return Rd0(16).toString("hex")}function Gt1(){if(Q90)return Q90;let $;try{let Z=J1();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return Q90=$?Buffer.from($):Rd0(32),Q90}function Jt1($){let Z=Buffer.from(JSON.stringify($)).toString("base64url"),X=Id0("sha256",Gt1()).update(Z).digest("base64url");return`${Z}.${X}`}function Kt1($,Z){let X=$.indexOf(".");if(X<0)return null;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(Id0("sha256",Gt1()).update(Q).digest("base64url"));if(Y.length!==G.length||!$t1(Y,G))return null;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return null}if(J.o!==Z.org||J.v!==Z.volume||J.s!==Z.secret||typeof J.e!=="number"||J.e<Z.nowSec)return null;return{govPath:J.p}}function qd0($,Z,X){return`fsu_${Id0("sha256","fsunlock-name").update(`${$}:${Z}:${X}`).digest("hex").slice(0,16)}`}var ld6=64,Zt1,Q90=null;var Md0=O(()=>{c8();Zt1=cd6(ud6)});import{createHash as dd6}from"crypto";function Wt1($){return dd6("sha256").update($).digest("hex")}class tK{storage;manifest;organizationId;maxFileBytes;volumeQuotaBytes;constructor($,Z,X,Q={}){this.storage=$;this.manifest=Z;this.organizationId=X;this.maxFileBytes=Q.maxFileBytes??nd6,this.volumeQuotaBytes=Q.volumeQuotaBytes??pd6}async usage($){return xZ($),this.manifest.usage(this.organizationId,$)}async stat($,Z){return xZ($),this.manifest.get(this.organizationId,$,vZ(Z))}async listDir($,Z){return xZ($),this.manifest.listDir(this.organizationId,$,vZ(Z))}async read($,Z){let X=await this.requireFile($,Z);return this.storage.getBytes(pK($,X.path))}async setShareMode($,Z,X,Q){xZ($);let Y=vZ(Z),G=await this.manifest.get(this.organizationId,$,Y);if(!G)throw new VD(`No such path: ${Y}`);let J=null,K=null;if(X==="password"){if(!Q.password)throw new KJ("A password is required to set password mode");J=await Xt1(Q.password),K=Yt1()}let W=await this.manifest.setShareMode({organizationId:this.organizationId,volume:$,path:G.path,readPublic:X!=="private",passwordHash:J,shareSecret:K,actor:Q.actor});if(!W)throw new VD(`No such path: ${G.path}`);return W}async setReadPublic($,Z,X,Q){return this.setShareMode($,Z,X?"public":"private",{actor:Q.actor})}async resolveReadAccess($,Z){xZ($);let X=vZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")return{access:"private"};let Y=await this.manifest.resolveGoverningShare({organizationId:this.organizationId,volume:$,candidatePaths:[X,...sF(X)]});if(!Y)return{access:"private"};if(!Y.passwordHash)return{access:"public"};return{access:"password",govPath:Y.path,secret:Y.secret??"",passwordHash:Y.passwordHash}}async isPubliclyReadable($,Z){xZ($);let X=vZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")return!1;if(Q.readPublic)return!0;return this.manifest.hasPublicAncestorDir(this.organizationId,$,sF(X))}async inheritsPublic($,Z){return xZ($),this.manifest.hasPublicAncestorDir(this.organizationId,$,sF(vZ(Z)))}async childrenInheritPublic($,Z){xZ($);let X=vZ(Z);if(X==="")return!1;return this.manifest.hasPublicAncestorDir(this.organizationId,$,[...sF(X),X])}async recentWithEffectivePublic($){return this.withEffectivePublic(await this.recent($))}async searchWithEffectivePublic($,Z,X,Q){return this.withEffectivePublic(await this.manifest.searchFiles({organizationId:this.organizationId,query:$,limit:Z,volumes:X,pathPrefix:Q?vZ(Q):void 0}))}async withEffectivePublic($){let Z=new Map;for(let Q of $){let Y=Z.get(Q.volume);if(!Y)Y=new Set,Z.set(Q.volume,Y);for(let G of sF(Q.path))Y.add(G)}let X=new Map;return await Promise.all([...Z].map(async([Q,Y])=>{let G=await this.manifest.publicDirPaths({organizationId:this.organizationId,volume:Q,paths:[...Y]});X.set(Q,new Set(G))})),$.map((Q)=>{let Y=X.get(Q.volume),G=!!Y&&sF(Q.path).some((J)=>Y.has(J));return{...Q,effectivePublic:Q.readPublic||G}})}async presignRead($,Z,X){let Q=await this.requireFile($,Z);return this.storage.presignedGetUrl(pK($,Q.path),X)}async write($,Z,X,Q){xZ($);let Y=vZ(Z);if(Y==="")throw new KJ("Cannot write to the volume root");let G=typeof X==="string"?new TextEncoder().encode(X):X;if(G.byteLength>this.maxFileBytes)throw new Am(`File exceeds the ${this.maxFileBytes}-byte per-file limit`);let[J,K]=await Promise.all([Q.skipVolumeQuota?Promise.resolve(null):this.manifest.usage(this.organizationId,$),this.manifest.get(this.organizationId,$,Y)]);if(K?.kind==="dir")throw new KJ(`Cannot write a file at ${Y}: a directory exists there`);if(J){let W=K?.kind==="file"?K.size:0;if(J.bytes-W+G.byteLength>this.volumeQuotaBytes)throw new Am(`Write would exceed the volume quota of ${this.volumeQuotaBytes} bytes`)}return await this.ensureDirs($,Y,Q.actor),await this.storage.put(pK($,Y),G,{contentType:Q.contentType??SZ(Y)}),this.manifest.putFile({organizationId:this.organizationId,volume:$,path:Y,parent:cf(Y),contentHash:Wt1(G),size:G.byteLength,actor:Q.actor,threadId:Q.threadId??null})}async mkdir($,Z,X){xZ($);let Q=vZ(Z);if(Q==="")return;if((await this.manifest.get(this.organizationId,$,Q))?.kind==="file")throw new KJ(`Cannot create a directory at ${Q}: a file exists there`);await this.ensureDirs($,Q,X.actor),await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Q,parent:cf(Q),actor:X.actor})}async delete($,Z,X){xZ($);let Q=vZ(Z);if(Q==="")throw new KJ("Cannot delete the volume root");let Y=await this.manifest.get(this.organizationId,$,Q);if(!Y)return;if(Y.kind==="dir"){let G=await this.manifest.listSubtreeFiles(this.organizationId,$,Q);await Promise.all(G.map((J)=>this.storage.delete(pK($,J.path)))),await this.manifest.tombstoneSubtree(this.organizationId,$,Q,X.actor);return}await this.storage.delete(pK($,Q)),await this.manifest.tombstone(this.organizationId,$,Q,X.actor)}async move($,Z,X,Q){xZ($);let Y=vZ(Z),G=vZ(X);if(Y===""||G==="")throw new KJ("Cannot move the volume root");if(G===Y||G.startsWith(`${Y}/`))throw new KJ(`Cannot move ${Y} onto itself or into its own subtree`);let J=await this.manifest.get(this.organizationId,$,Y);if(!J)throw new VD(`No such path: ${Y}`);if(J.kind==="file"){let H=await this.storage.getBytes(pK($,Y));await this.write($,G,H,{...Q,skipVolumeQuota:!0}),await this.delete($,Y,Q);return}let[K,W]=await Promise.all([this.manifest.listSubtreeFiles(this.organizationId,$,Y),this.manifest.listSubtreeDirs(this.organizationId,$,Y)]);await this.mkdir($,G,Q);for(let H of K){let N=H.path.slice(Y.length+1),U=await this.storage.getBytes(pK($,H.path));await this.write($,`${G}/${N}`,U,{...Q,skipVolumeQuota:!0})}for(let H of W){let N=H.path.slice(Y.length+1);await this.mkdir($,`${G}/${N}`,Q)}await this.delete($,Y,Q)}async filesExist($,Z){xZ($);let X=await this.manifest.liveFilePaths({organizationId:this.organizationId,volume:$,paths:Z.map((Q)=>vZ(Q))});return new Set(X)}async recent($){return this.manifest.recentFiles({organizationId:this.organizationId,limit:$})}async changes($,Z,X=md6){xZ($);let Q=Z||"0";if(!/^\d+$/.test(Q))throw new KJ(`Invalid cursor: ${Z}`);let Y=await this.manifest.changesSince({organizationId:this.organizationId,volume:$,sinceSeq:Q,limit:X}),G=Y.at(-1);return{entries:Y,cursor:G?G.seq:Z||"0",hasMore:Y.length>=X}}async latestSeq($){return xZ($),this.manifest.latestSeq({organizationId:this.organizationId,volume:$})}async backfillFromStorage($,Z){xZ($);let X=ep1($),Q,Y=0;do{let G=await this.storage.list({prefix:X,maxKeys:id6,continuationToken:Q});for(let J of G.objects){let K=J.key.slice(X.length);if(K==="")continue;await this.ensureDirs($,K,Z.actor);let W=await this.storage.getBytes(J.key);await this.manifest.putFile({organizationId:this.organizationId,volume:$,path:K,parent:cf(K),contentHash:Wt1(W),size:W.byteLength,actor:Z.actor}),Y++}Q=G.isTruncated?G.nextContinuationToken:void 0}while(Q);return Y}async requireFile($,Z){xZ($);let X=vZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")throw new VD(`No such file: ${X}`);return Q}async ensureDirs($,Z,X){for(let Q of sF(Z))await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Q,parent:cf(Q),actor:X})}}var md6=500,id6=1000,nd6=524288000,pd6=10737418240,Am,KJ,VD;var lf=O(()=>{yK();Pm();Md0();Am=class Am extends Error{constructor($){super($);this.name="OrgFsQuotaError"}};KJ=class KJ extends Error{constructor($){super($);this.name="OrgFsValidationError"}};VD=class VD extends Error{constructor($){super($);this.name="OrgFsNotFoundError"}}});import{z as wN}from"zod";function eF($){return $.startsWith(Ht1)}function $w($){return`${Ht1}${$}`}function sd6($){let Z=new Map(rd6.map((X)=>[X.set,X]));if($)try{for(let X of ad6.parse(JSON.parse($)))Z.set(X.set,X)}catch(X){console.warn("[org-fs] invalid ORGFS_PUBLIC_SETS \u2014 using built-in defaults only",X)}return[...Z.values()]}function cG(){return sd6(J1().orgFsPublicSetsJson)}function Tm($){let Z=vX(),X=Z?SY(Z,BN):new nK(BN,$.baseUrl);return new tK(X,$.storage.orgFsEntries,BN)}var BN="org_orgfs_public_skills",Ht1="public-",td6,od6,rd6,ad6;var df=O(()=>{c8();uF();jm();lf();td6=wN.object({from:wN.string(),to:wN.string().optional()}),od6=wN.object({set:wN.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/),repo:wN.string().regex(/^[\w.-]+\/[\w.-]+$/),ref:wN.string().min(1),paths:wN.array(td6).min(1)}),rd6=[{set:"core",repo:"decocms/studio",ref:"main",paths:[{from:"packages/sandbox/image/skills"}]},{set:"storefront",repo:"decocms/storefront-skills",ref:"main",paths:[{from:".claude-seo/skills"},{from:".claude-performance/skills"},{from:".claude-deco/skills"}]}],ad6=wN.array(od6).refine(($)=>new Set($.map((Z)=>Z.set)).size===$.length,{message:"duplicate set names"})});import{sql as CD}from"kysely";function kd0($){if($===null)return null;return $ instanceof Date?$.toISOString():String($)}function WJ($){return{organizationId:$.organization_id,volume:$.volume,path:$.path,parent:$.parent,kind:$.kind,contentHash:$.content_hash,size:Number($.size),seq:String($.seq),deletedAt:kd0($.deleted_at),createdBy:$.created_by,createdAt:kd0($.created_at)??"",updatedBy:$.updated_by,updatedAt:kd0($.updated_at)??"",threadId:$.thread_id,readPublic:$.read_public,shareMode:!$.read_public?"private":$.share_password_hash?"password":"public"}}class Rm{db;constructor($){this.db=$}async putFile($){let Z=new Date,X=$.threadId??null,Q=await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z,thread_id:X}).onConflict((Y)=>Y.columns(["organization_id","volume","path"]).doUpdateSet({kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:Y90,read_public:CD`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`,thread_id:CD`coalesce(cast(${X} as text), org_fs_entry.thread_id)`})).returning(HJ).executeTakeFirstOrThrow();return WJ(Q)}async putDir($){let Z=new Date;await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"dir",content_hash:null,size:0,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z}).onConflict((X)=>X.columns(["organization_id","volume","path"]).where("org_fs_entry.deleted_at","is not",null).doUpdateSet({kind:"dir",content_hash:null,size:0,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:Y90,read_public:CD`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`})).execute()}async get($,Z,X){let Q=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("path","=",X).where("deleted_at","is",null).select(HJ).executeTakeFirst();return Q?WJ(Q):null}async listDir($,Z,X){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("parent","=",X).where("deleted_at","is",null).select(HJ).orderBy("path","asc").execute()).map((Y)=>WJ(Y))}async listVolumeDirs($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).select(HJ).execute()).map((Q)=>WJ(Q))}async listVolumeFiles($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select(HJ).execute()).map((Q)=>WJ(Q))}async listSubtreeFiles($,Z,X){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).where("path","like",`${Im(X)}/%`).select(HJ).execute()).map((Y)=>WJ(Y))}async listSubtreeDirs($,Z,X){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).where("path","like",`${Im(X)}/%`).select(HJ).execute()).map((Y)=>WJ(Y))}async tombstone($,Z,X,Q){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Q,updated_at:new Date,seq:Y90}).where("organization_id","=",$).where("volume","=",Z).where("path","=",X).where("deleted_at","is",null).execute()}async tombstoneSubtree($,Z,X,Q){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Q,updated_at:new Date,seq:Y90}).where("organization_id","=",$).where("volume","=",Z).where("deleted_at","is",null).where((Y)=>Y.or([Y("path","=",X),Y("path","like",`${Im(X)}/%`)])).execute()}async setShareMode($){let Z=new Date,X=await this.db.updateTable("org_fs_entry").set({read_public:$.readPublic,share_password_hash:$.passwordHash,share_secret:$.shareSecret,updated_by:$.actor,updated_at:Z}).where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("path","=",$.path).where("deleted_at","is",null).returning(HJ).executeTakeFirst();return X?WJ(X):null}async resolveGoverningShare($){if($.candidatePaths.length===0)return null;let Z=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.candidatePaths).select(["path","share_password_hash","share_secret"]).execute();if(Z.length===0)return null;Z.sort((Q,Y)=>Y.path.length-Q.path.length);let X=Z[0];return{path:X.path,passwordHash:X.share_password_hash,secret:X.share_secret}}async hasPublicAncestorDir($,Z,X){if(X.length===0)return!1;return!!await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",X).select("path").limit(1).executeTakeFirst()}async publicDirPaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.paths).select("path").execute()).map((X)=>X.path)}async usage($,Z){let X=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select((Q)=>[Q.fn.countAll().as("files"),Q.fn.coalesce(Q.fn.sum("size"),CD`0`).as("bytes")]).executeTakeFirst();return{files:Number(X?.files??0),bytes:Number(X?.bytes??0)}}async liveFilePaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","file").where("deleted_at","is",null).where("path","in",$.paths).select(["path"]).execute()).map((X)=>X.path)}async recentFiles($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).select(HJ).orderBy("seq","desc").limit($.limit).execute()).map((X)=>WJ(X))}async searchFiles($){if($.volumes&&$.volumes.length===0)return[];let Z=Im($.query),X=this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).where("path","ilike",`%${Z}%`);if($.volumes)X=X.where("volume","in",$.volumes);if($.pathPrefix)X=X.where("path","like",`${Im($.pathPrefix)}/%`);return(await X.select(HJ).orderBy("seq","desc").limit($.limit).execute()).map((Y)=>WJ(Y))}async changesSince($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("seq",">",CD`cast(${$.sinceSeq} as bigint)`).select(HJ).orderBy("seq","asc").limit($.limit).execute()).map((X)=>WJ(X))}async latestSeq($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).select(CD`max(seq)`.as("seq")).executeTakeFirst())?.seq??"0"}}function Im($){return $.replace(/[\\%_]/g,"\\$&")}var HJ,Y90;var Sd0=O(()=>{HJ=["organization_id","volume","path","parent","kind","content_hash","size","seq","deleted_at","created_by","created_at","updated_by","updated_at","thread_id","read_public","share_password_hash"],Y90=CD`nextval('org_fs_entry_seq')`});import{createHash as ed6}from"crypto";import{gunzipSync as $m6}from"zlib";function Cd0($,Z,X){let Q=Z,Y=Z+X;while(Q<Y&&$[Q]!==0)Q++;return new TextDecoder().decode($.subarray(Z,Q))}function Xm6($,Z,X){let Q=Cd0($,Z,X).trim();return Q===""?0:Number.parseInt(Q,8)}function Qm6($){let Z=new Map,X=0,Q=null,Y=null;while(X+512<=$.length){let G=$.subarray(X,X+512);if(X+=512,G.every((F)=>F===0))break;let J=Cd0(G,0,100),K=Cd0(G,345,155);if(K)J=`${K}/${J}`;let W=Xm6(G,124,12),H=String.fromCharCode(G[156]??0),N=$.subarray(X,X+W);if(X+=Math.ceil(W/512)*512,H==="L"){let F=new TextDecoder().decode(N),w=F.indexOf("\x00");Q=w===-1?F:F.slice(0,w);continue}if(H==="x"){let F=new TextDecoder().decode(N);Y=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(F)?.[1]??null;continue}if(H==="g")continue;let U=Y??Q??J;if(Q=null,Y=null,H==="0"||H==="\x00"||H==="")Z.set(U,new Uint8Array(N))}return Z}async function Ym6($,Z){let X=`https://codeload.github.com/${$}/tar.gz/${encodeURIComponent(Z)}`,Q=await fetch(X,{signal:AbortSignal.timeout(60000)});if(!Q.ok)throw Error(`tarball fetch failed for ${$}@${Z}: HTTP ${Q.status}`);let Y=Number(Q.headers.get("content-length")??0);if(Y>G90)throw Error(`tarball for ${$}@${Z} declares ${Y} bytes (cap ${G90})`);let G=new Uint8Array(await Q.arrayBuffer());if(G.length>G90)throw Error(`tarball for ${$}@${Z} exceeds ${G90} bytes`);let J=Qm6(new Uint8Array($m6(G,{maxOutputLength:Zm6}))),K=new Map;for(let[W,H]of J){let N=W.indexOf("/");if(N===-1)continue;let U=W.slice(N+1);if(U)K.set(U,H)}return K}function Gm6($,Z){let X=new Map;for(let{from:Q,to:Y}of Z){let G=Q===""?"":`${Q.replace(/\/+$/,"")}/`;for(let[J,K]of $){if(!J.startsWith(G))continue;let W=J.slice(G.length);if(!W)continue;let H=vZ(Y?`${Y}/${W}`:W);if(H)X.set(H,K)}}return X}function Jm6($,Z){let X=new Set;for(let G of $){let J=G.split("/");for(let K=1;K<J.length;K++)X.add(J.slice(0,K).join("/"))}let Q=[...Z].filter((G)=>!X.has(G)).sort((G,J)=>G.length-J.length),Y=[];for(let G of Q)if(!Y.some((J)=>G.startsWith(`${J}/`)))Y.push(G);return Y}function Km6($){return ed6("sha256").update($).digest("hex")}async function Wm6($,Z,X){let Q=vX(),Y=Q?SY(Q,BN):new nK(BN,X.baseUrl),G=new Rm($),J=new tK(Y,G,BN),K=$w(Z.set),W=Gm6(await Ym6(Z.repo,Z.ref),Z.paths),H=new Map((await G.listVolumeFiles(BN,K)).map((B)=>[B.path,B.contentHash]));if(W.size===0&&H.size>0)throw Error(`set "${Z.set}" resolved 0 files from ${Z.repo}@${Z.ref} `+`(check paths config) \u2014 refusing to delete the ${H.size} existing files`);let N=0;for(let B of H.keys()){if(W.has(B))continue;await J.delete(K,B,{actor:Vd0}),N++}let U=await G.listVolumeDirs(BN,K);for(let B of Jm6(W.keys(),U.map((L)=>L.path)))await J.delete(K,B,{actor:Vd0});let F=0,w=0;for(let[B,L]of W){if(H.get(B)===Km6(L)){w++;continue}await J.write(K,B,L,{actor:Vd0,contentType:SZ(B),skipVolumeQuota:!0}),F++}return{set:Z.set,written:F,deleted:N,unchanged:w}}async function _d0($,Z,X){try{return await Wm6($,Z,X)}catch(Q){return{set:Z.set,error:Q instanceof Error?Q.message:String(Q)}}}async function Nt1($,Z){let X=[];for(let Q of cG())X.push(await _d0($,Q,Z));return X}var Vd0="system:skill-set-sync",G90=209715200,Zm6=1073741824;var xd0=O(()=>{Sd0();jm();uF();yK();lf();Pm();df()});import{DBOS as J90,SchedulerMode as Hm6}from"@dbos-inc/dbos-sdk";function Ut1($){vd0=$}function Um6(){if(!vd0)throw Error("[org-fs] public-sets sync runtime not initialized \u2014 setPublicSetsSyncRuntime() must run before the workflow fires");return vd0}async function Fm6($,Z){for(let X of cG()){let Q=await J90.runStep(()=>{let Y=Um6();return _d0(Y.db,X,{baseUrl:Y.baseUrl})},{name:`syncPublicSet:${X.set}`});if("error"in Q)console.warn(`[org-fs] public set "${Q.set}" sync failed: ${Q.error}`);else if(Q.written||Q.deleted)console.log(`[org-fs] public set "${Q.set}" synced: +${Q.written} -${Q.deleted} (=${Q.unchanged})`)}}function Ft1(){if(qm)return;qm=J90.registerWorkflow(Fm6,{name:"publicSetsSyncWorkflow"}),J90.registerScheduled(qm,{name:"publicSetsSyncWorkflow",crontab:Nm6,mode:Hm6.ExactlyOncePerIntervalWhenActive})}async function wt1(){if(cG().length===0||!qm)return;let $=new Date,Z=`public-sets-sync-boot:${$.toISOString().slice(0,13)}`;await J90.startWorkflow(qm,{workflowID:Z})($,$)}var Nm6="4-59/10 * * * *",vd0=null,qm=null;var Bt1=O(()=>{df();xd0()});import{z as q8}from"zod";var wm6,Bm6,Om6,Lm6,Dm6,Em6,zm6,jm6,Pm6,Am6,Tm6,Im6,_D;var Mm=O(()=>{wm6=q8.object({prefix:q8.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:q8.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:q8.string().optional().describe("Token for pagination from previous response"),delimiter:q8.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Bm6=q8.object({objects:q8.array(q8.object({key:q8.string().describe("Object key/path"),size:q8.number().describe("Object size in bytes"),lastModified:q8.string().describe("Last modified timestamp"),etag:q8.string().describe("Entity tag for the object")})),nextContinuationToken:q8.string().optional().describe("Token for fetching next page of results"),isTruncated:q8.boolean().describe("Whether there are more results available"),commonPrefixes:q8.array(q8.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Om6=q8.object({key:q8.string().describe("Object key/path to get metadata for")}),Lm6=q8.object({contentType:q8.string().optional().describe("MIME type of the object"),contentLength:q8.number().describe("Size of the object in bytes"),lastModified:q8.string().describe("Last modified timestamp"),etag:q8.string().describe("Entity tag for the object"),metadata:q8.record(q8.string(),q8.string()).optional().describe("Custom metadata key-value pairs")}),Dm6=q8.object({key:q8.string().describe("Object key/path to generate URL for"),expiresIn:q8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),Em6=q8.object({url:q8.string().describe("Presigned URL for downloading the object"),expiresIn:q8.number().describe("Expiration time in seconds that was used")}),zm6=q8.object({key:q8.string().describe("Object key/path for the upload"),expiresIn:q8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:q8.string().optional().describe("MIME type for the object being uploaded")}),jm6=q8.object({url:q8.string().describe("Presigned URL for uploading the object"),expiresIn:q8.number().describe("Expiration time in seconds that was used")}),Pm6=q8.object({key:q8.string().describe("Object key/path to delete")}),Am6=q8.object({success:q8.boolean().describe("Whether the deletion was successful"),key:q8.string().describe("The key that was deleted")}),Tm6=q8.object({keys:q8.array(q8.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Im6=q8.object({deleted:q8.array(q8.string()).describe("Array of successfully deleted keys"),errors:q8.array(q8.object({key:q8.string(),message:q8.string()})).describe("Array of errors for failed deletions")}),_D=[{name:"LIST_OBJECTS",inputSchema:wm6,outputSchema:Bm6},{name:"GET_OBJECT_METADATA",inputSchema:Om6,outputSchema:Lm6},{name:"GET_PRESIGNED_URL",inputSchema:Dm6,outputSchema:Em6},{name:"PUT_PRESIGNED_URL",inputSchema:zm6,outputSchema:jm6},{name:"DELETE_OBJECT",inputSchema:Pm6,outputSchema:Am6},{name:"DELETE_OBJECTS",inputSchema:Tm6,outputSchema:Im6}]});import*as x from"zod/v4";function Vt1($){if($.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${$.params.ref.type}`)}function Ct1($){if($.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${$.params.ref.type}`)}var Zw="2025-11-25",Ot1="2025-03-26",Xw,Qw="io.modelcontextprotocol/related-task",W90="2.0",GZ,Lt1,Dt1,M85,Rm6,qm6,fd0,bY,km,Et1=($)=>km.safeParse($).success,K7,lG,dG,W7,H90,zt1,oK=($)=>zt1.safeParse($).success,jt1,Pt1=($)=>jt1.safeParse($).success,bd0,NJ=($)=>bd0.safeParse($).success,b1,yd0,nf=($)=>yd0.safeParse($).success,yY,k85,ON,Mm6,N90,km6,Sm,mf,At1,Sm6,Vm6,Cm6,_m6,xm6,vm6,U90,gd0=($)=>U90.safeParse($).success,fm6,hd0,F90,Tt1=($)=>F90.safeParse($).success,w90,bm6,ym6,B90,gm6,Vm,Cm,hm6,_m,LN,um6,xm,O90,L90,D90,S85,E90,z90,j90,It1,Rt1,qt1,ud0,Mt1,vm,pf,kt1,cm6,Yw,cd0,Gw,ld0,dd0,lm6,tf,md0,id0,dm6,mm6,im6,nm6,pm6,tm6,om6,rm6,Jw,nd0,am6,of,pd0,td0,od0,sm6,em6,$i6,rd0,Zi6,ad0,sd0,Xi6,Qi6,P90,rf,fm,rK,V85,Yi6,Kw,ed0,St1,bm,Gi6,$m0,Ji6,Ki6,Wi6,Hi6,Ni6,Ui6,Fi6,K90,wi6,Bi6,Zm0,xD,ym,Oi6,Li6,Di6,Ei6,zi6,ji6,Pi6,Ai6,Ti6,Ii6,Ri6,qi6,Mi6,ki6,Si6,Xm0,Vi6,Ci6,Ww,_i6,xi6,vi6,A90,Qm0,fi6,bi6,Ym0,yi6,C85,_85,x85,v85,f85,b85,M1,_t1;var X9=O(()=>{Xw=[Zw,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],GZ=x.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Lt1=x.union([x.string(),x.number().int()]),Dt1=x.string(),M85=x.looseObject({ttl:x.number().optional(),pollInterval:x.number().optional()}),Rm6=x.object({ttl:x.number().optional()}),qm6=x.object({taskId:x.string()}),fd0=x.looseObject({progressToken:Lt1.optional(),[Qw]:qm6.optional()}),bY=x.object({_meta:fd0.optional()}),km=bY.extend({task:Rm6.optional()}),K7=x.object({method:x.string(),params:bY.loose().optional()}),lG=x.object({_meta:fd0.optional()}),dG=x.object({method:x.string(),params:lG.loose().optional()}),W7=x.looseObject({_meta:fd0.optional()}),H90=x.union([x.string(),x.number().int()]),zt1=x.object({jsonrpc:x.literal(W90),id:H90,...K7.shape}).strict(),jt1=x.object({jsonrpc:x.literal(W90),...dG.shape}).strict(),bd0=x.object({jsonrpc:x.literal(W90),id:H90,result:W7}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(b1||(b1={}));yd0=x.object({jsonrpc:x.literal(W90),id:H90.optional(),error:x.object({code:x.number().int(),message:x.string(),data:x.unknown().optional()})}).strict(),yY=x.union([zt1,jt1,bd0,yd0]),k85=x.union([bd0,yd0]),ON=W7.strict(),Mm6=lG.extend({requestId:H90.optional(),reason:x.string().optional()}),N90=dG.extend({method:x.literal("notifications/cancelled"),params:Mm6}),km6=x.object({src:x.string(),mimeType:x.string().optional(),sizes:x.array(x.string()).optional(),theme:x.enum(["light","dark"]).optional()}),Sm=x.object({icons:x.array(km6).optional()}),mf=x.object({name:x.string(),title:x.string().optional()}),At1=mf.extend({...mf.shape,...Sm.shape,version:x.string(),websiteUrl:x.string().optional(),description:x.string().optional()}),Sm6=x.intersection(x.object({applyDefaults:x.boolean().optional()}),x.record(x.string(),x.unknown())),Vm6=x.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},x.intersection(x.object({form:Sm6.optional(),url:GZ.optional()}),x.record(x.string(),x.unknown()).optional())),Cm6=x.looseObject({list:GZ.optional(),cancel:GZ.optional(),requests:x.looseObject({sampling:x.looseObject({createMessage:GZ.optional()}).optional(),elicitation:x.looseObject({create:GZ.optional()}).optional()}).optional()}),_m6=x.looseObject({list:GZ.optional(),cancel:GZ.optional(),requests:x.looseObject({tools:x.looseObject({call:GZ.optional()}).optional()}).optional()}),xm6=x.object({experimental:x.record(x.string(),GZ).optional(),sampling:x.object({context:GZ.optional(),tools:GZ.optional()}).optional(),elicitation:Vm6.optional(),roots:x.object({listChanged:x.boolean().optional()}).optional(),tasks:Cm6.optional(),extensions:x.record(x.string(),GZ).optional()}),vm6=bY.extend({protocolVersion:x.string(),capabilities:xm6,clientInfo:At1}),U90=K7.extend({method:x.literal("initialize"),params:vm6}),fm6=x.object({experimental:x.record(x.string(),GZ).optional(),logging:GZ.optional(),completions:GZ.optional(),prompts:x.object({listChanged:x.boolean().optional()}).optional(),resources:x.object({subscribe:x.boolean().optional(),listChanged:x.boolean().optional()}).optional(),tools:x.object({listChanged:x.boolean().optional()}).optional(),tasks:_m6.optional(),extensions:x.record(x.string(),GZ).optional()}),hd0=W7.extend({protocolVersion:x.string(),capabilities:fm6,serverInfo:At1,instructions:x.string().optional()}),F90=dG.extend({method:x.literal("notifications/initialized"),params:lG.optional()}),w90=K7.extend({method:x.literal("ping"),params:bY.optional()}),bm6=x.object({progress:x.number(),total:x.optional(x.number()),message:x.optional(x.string())}),ym6=x.object({...lG.shape,...bm6.shape,progressToken:Lt1}),B90=dG.extend({method:x.literal("notifications/progress"),params:ym6}),gm6=bY.extend({cursor:Dt1.optional()}),Vm=K7.extend({params:gm6.optional()}),Cm=W7.extend({nextCursor:Dt1.optional()}),hm6=x.enum(["working","input_required","completed","failed","cancelled"]),_m=x.object({taskId:x.string(),status:hm6,ttl:x.union([x.number(),x.null()]),createdAt:x.string(),lastUpdatedAt:x.string(),pollInterval:x.optional(x.number()),statusMessage:x.optional(x.string())}),LN=W7.extend({task:_m}),um6=lG.merge(_m),xm=dG.extend({method:x.literal("notifications/tasks/status"),params:um6}),O90=K7.extend({method:x.literal("tasks/get"),params:bY.extend({taskId:x.string()})}),L90=W7.merge(_m),D90=K7.extend({method:x.literal("tasks/result"),params:bY.extend({taskId:x.string()})}),S85=W7.loose(),E90=Vm.extend({method:x.literal("tasks/list")}),z90=Cm.extend({tasks:x.array(_m)}),j90=K7.extend({method:x.literal("tasks/cancel"),params:bY.extend({taskId:x.string()})}),It1=W7.merge(_m),Rt1=x.object({uri:x.string(),mimeType:x.optional(x.string()),_meta:x.record(x.string(),x.unknown()).optional()}),qt1=Rt1.extend({text:x.string()}),ud0=x.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mt1=Rt1.extend({blob:ud0}),vm=x.enum(["user","assistant"]),pf=x.object({audience:x.array(vm).optional(),priority:x.number().min(0).max(1).optional(),lastModified:x.iso.datetime({offset:!0}).optional()}),kt1=x.object({...mf.shape,...Sm.shape,uri:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string()),size:x.optional(x.number()),annotations:pf.optional(),_meta:x.optional(x.looseObject({}))}),cm6=x.object({...mf.shape,...Sm.shape,uriTemplate:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string()),annotations:pf.optional(),_meta:x.optional(x.looseObject({}))}),Yw=Vm.extend({method:x.literal("resources/list")}),cd0=Cm.extend({resources:x.array(kt1)}),Gw=Vm.extend({method:x.literal("resources/templates/list")}),ld0=Cm.extend({resourceTemplates:x.array(cm6)}),dd0=bY.extend({uri:x.string()}),lm6=dd0,tf=K7.extend({method:x.literal("resources/read"),params:lm6}),md0=W7.extend({contents:x.array(x.union([qt1,Mt1]))}),id0=dG.extend({method:x.literal("notifications/resources/list_changed"),params:lG.optional()}),dm6=dd0,mm6=K7.extend({method:x.literal("resources/subscribe"),params:dm6}),im6=dd0,nm6=K7.extend({method:x.literal("resources/unsubscribe"),params:im6}),pm6=lG.extend({uri:x.string()}),tm6=dG.extend({method:x.literal("notifications/resources/updated"),params:pm6}),om6=x.object({name:x.string(),description:x.optional(x.string()),required:x.optional(x.boolean())}),rm6=x.object({...mf.shape,...Sm.shape,description:x.optional(x.string()),arguments:x.optional(x.array(om6)),_meta:x.optional(x.looseObject({}))}),Jw=Vm.extend({method:x.literal("prompts/list")}),nd0=Cm.extend({prompts:x.array(rm6)}),am6=bY.extend({name:x.string(),arguments:x.record(x.string(),x.string()).optional()}),of=K7.extend({method:x.literal("prompts/get"),params:am6}),pd0=x.object({type:x.literal("text"),text:x.string(),annotations:pf.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),td0=x.object({type:x.literal("image"),data:ud0,mimeType:x.string(),annotations:pf.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),od0=x.object({type:x.literal("audio"),data:ud0,mimeType:x.string(),annotations:pf.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),sm6=x.object({type:x.literal("tool_use"),name:x.string(),id:x.string(),input:x.record(x.string(),x.unknown()),_meta:x.record(x.string(),x.unknown()).optional()}),em6=x.object({type:x.literal("resource"),resource:x.union([qt1,Mt1]),annotations:pf.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),$i6=kt1.extend({type:x.literal("resource_link")}),rd0=x.union([pd0,td0,od0,$i6,em6]),Zi6=x.object({role:vm,content:rd0}),ad0=W7.extend({description:x.string().optional(),messages:x.array(Zi6)}),sd0=dG.extend({method:x.literal("notifications/prompts/list_changed"),params:lG.optional()}),Xi6=x.object({title:x.string().optional(),readOnlyHint:x.boolean().optional(),destructiveHint:x.boolean().optional(),idempotentHint:x.boolean().optional(),openWorldHint:x.boolean().optional()}),Qi6=x.object({taskSupport:x.enum(["required","optional","forbidden"]).optional()}),P90=x.object({...mf.shape,...Sm.shape,description:x.string().optional(),inputSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),GZ).optional(),required:x.array(x.string()).optional()}).catchall(x.unknown()),outputSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),GZ).optional(),required:x.array(x.string()).optional()}).catchall(x.unknown()).optional(),annotations:Xi6.optional(),execution:Qi6.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),rf=Vm.extend({method:x.literal("tools/list")}),fm=Cm.extend({tools:x.array(P90)}),rK=W7.extend({content:x.array(rd0).default([]),structuredContent:x.record(x.string(),x.unknown()).optional(),isError:x.boolean().optional()}),V85=rK.or(W7.extend({toolResult:x.unknown()})),Yi6=km.extend({name:x.string(),arguments:x.record(x.string(),x.unknown()).optional()}),Kw=K7.extend({method:x.literal("tools/call"),params:Yi6}),ed0=dG.extend({method:x.literal("notifications/tools/list_changed"),params:lG.optional()}),St1=x.object({autoRefresh:x.boolean().default(!0),debounceMs:x.number().int().nonnegative().default(300)}),bm=x.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Gi6=bY.extend({level:bm}),$m0=K7.extend({method:x.literal("logging/setLevel"),params:Gi6}),Ji6=lG.extend({level:bm,logger:x.string().optional(),data:x.unknown()}),Ki6=dG.extend({method:x.literal("notifications/message"),params:Ji6}),Wi6=x.object({name:x.string().optional()}),Hi6=x.object({hints:x.array(Wi6).optional(),costPriority:x.number().min(0).max(1).optional(),speedPriority:x.number().min(0).max(1).optional(),intelligencePriority:x.number().min(0).max(1).optional()}),Ni6=x.object({mode:x.enum(["auto","required","none"]).optional()}),Ui6=x.object({type:x.literal("tool_result"),toolUseId:x.string().describe("The unique identifier for the corresponding tool call."),content:x.array(rd0).default([]),structuredContent:x.object({}).loose().optional(),isError:x.boolean().optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Fi6=x.discriminatedUnion("type",[pd0,td0,od0]),K90=x.discriminatedUnion("type",[pd0,td0,od0,sm6,Ui6]),wi6=x.object({role:vm,content:x.union([K90,x.array(K90)]),_meta:x.record(x.string(),x.unknown()).optional()}),Bi6=km.extend({messages:x.array(wi6),modelPreferences:Hi6.optional(),systemPrompt:x.string().optional(),includeContext:x.enum(["none","thisServer","allServers"]).optional(),temperature:x.number().optional(),maxTokens:x.number().int(),stopSequences:x.array(x.string()).optional(),metadata:GZ.optional(),tools:x.array(P90).optional(),toolChoice:Ni6.optional()}),Zm0=K7.extend({method:x.literal("sampling/createMessage"),params:Bi6}),xD=W7.extend({model:x.string(),stopReason:x.optional(x.enum(["endTurn","stopSequence","maxTokens"]).or(x.string())),role:vm,content:Fi6}),ym=W7.extend({model:x.string(),stopReason:x.optional(x.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(x.string())),role:vm,content:x.union([K90,x.array(K90)])}),Oi6=x.object({type:x.literal("boolean"),title:x.string().optional(),description:x.string().optional(),default:x.boolean().optional()}),Li6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),minLength:x.number().optional(),maxLength:x.number().optional(),format:x.enum(["email","uri","date","date-time"]).optional(),default:x.string().optional()}),Di6=x.object({type:x.enum(["number","integer"]),title:x.string().optional(),description:x.string().optional(),minimum:x.number().optional(),maximum:x.number().optional(),default:x.number().optional()}),Ei6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),enum:x.array(x.string()),default:x.string().optional()}),zi6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),oneOf:x.array(x.object({const:x.string(),title:x.string()})),default:x.string().optional()}),ji6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),enum:x.array(x.string()),enumNames:x.array(x.string()).optional(),default:x.string().optional()}),Pi6=x.union([Ei6,zi6]),Ai6=x.object({type:x.literal("array"),title:x.string().optional(),description:x.string().optional(),minItems:x.number().optional(),maxItems:x.number().optional(),items:x.object({type:x.literal("string"),enum:x.array(x.string())}),default:x.array(x.string()).optional()}),Ti6=x.object({type:x.literal("array"),title:x.string().optional(),description:x.string().optional(),minItems:x.number().optional(),maxItems:x.number().optional(),items:x.object({anyOf:x.array(x.object({const:x.string(),title:x.string()}))}),default:x.array(x.string()).optional()}),Ii6=x.union([Ai6,Ti6]),Ri6=x.union([ji6,Pi6,Ii6]),qi6=x.union([Ri6,Oi6,Li6,Di6]),Mi6=km.extend({mode:x.literal("form").optional(),message:x.string(),requestedSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),qi6),required:x.array(x.string()).optional()})}),ki6=km.extend({mode:x.literal("url"),message:x.string(),elicitationId:x.string(),url:x.string().url()}),Si6=x.union([Mi6,ki6]),Xm0=K7.extend({method:x.literal("elicitation/create"),params:Si6}),Vi6=lG.extend({elicitationId:x.string()}),Ci6=dG.extend({method:x.literal("notifications/elicitation/complete"),params:Vi6}),Ww=W7.extend({action:x.enum(["accept","decline","cancel"]),content:x.preprocess(($)=>$===null?void 0:$,x.record(x.string(),x.union([x.string(),x.number(),x.boolean(),x.array(x.string())])).optional())}),_i6=x.object({type:x.literal("ref/resource"),uri:x.string()}),xi6=x.object({type:x.literal("ref/prompt"),name:x.string()}),vi6=bY.extend({ref:x.union([xi6,_i6]),argument:x.object({name:x.string(),value:x.string()}),context:x.object({arguments:x.record(x.string(),x.string()).optional()}).optional()}),A90=K7.extend({method:x.literal("completion/complete"),params:vi6});Qm0=W7.extend({completion:x.looseObject({values:x.array(x.string()).max(100),total:x.optional(x.number().int()),hasMore:x.optional(x.boolean())})}),fi6=x.object({uri:x.string().startsWith("file://"),name:x.string().optional(),_meta:x.record(x.string(),x.unknown()).optional()}),bi6=K7.extend({method:x.literal("roots/list"),params:bY.optional()}),Ym0=W7.extend({roots:x.array(fi6)}),yi6=dG.extend({method:x.literal("notifications/roots/list_changed"),params:lG.optional()}),C85=x.union([w90,U90,A90,$m0,of,Jw,Yw,Gw,tf,mm6,nm6,Kw,rf,O90,D90,E90,j90]),_85=x.union([N90,B90,F90,yi6,xm]),x85=x.union([ON,xD,ym,Ww,Ym0,L90,z90,LN]),v85=x.union([w90,Zm0,Xm0,bi6,O90,D90,E90,j90]),f85=x.union([N90,B90,Ki6,tm6,id0,ed0,sd0,xm,Ci6]),b85=x.union([ON,hd0,Qm0,ad0,nd0,cd0,ld0,md0,rK,fm,L90,z90,LN]);M1=class M1 extends Error{constructor($,Z,X){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=X,this.name="McpError"}static fromError($,Z,X){if($===b1.UrlElicitationRequired&&X){let Q=X;if(Q.elicitations)return new _t1(Q.elicitations,Z)}return new M1($,Z,X)}};_t1=class _t1 extends M1{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(b1.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});import{z as D8}from"zod";function aK($){return $!==null&&$!==void 0&&"command"in $}function af($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function sf($){return`virtual://${$}`}var gi6,xt1,hi6,ui6,ci6,i7,T90,I90;var vt1=O(()=>{X9();gi6=D8.object({authorizationEndpoint:D8.string().url(),tokenEndpoint:D8.string().url(),introspectionEndpoint:D8.string().url().optional(),clientId:D8.string(),clientSecret:D8.string().optional(),scopes:D8.array(D8.string()),grantType:D8.enum(["authorization_code","client_credentials"])}),xt1=D8.object({type:D8.literal("object"),properties:D8.record(D8.string(),D8.unknown()).optional(),required:D8.array(D8.string()).optional()}).catchall(D8.unknown()),hi6=P90.extend({inputSchema:xt1,outputSchema:xt1.optional()}),ui6=D8.object({headers:D8.record(D8.string(),D8.string()).optional()}),ci6=D8.object({command:D8.string().describe("Command to run (e.g., 'npx', 'node')"),args:D8.array(D8.string()).optional().describe("Command arguments"),cwd:D8.string().optional().describe("Working directory"),envVars:D8.record(D8.string(),D8.string()).optional().describe("Environment variables (encrypted in storage)")}),i7=D8.object({id:D8.string().describe("Unique identifier for the connection"),title:D8.string().describe("Human-readable name for the connection"),created_at:D8.string().describe("When the connection was created"),updated_at:D8.string().describe("When the connection was last updated"),created_by:D8.string().describe("User ID who created the connection"),updated_by:D8.string().optional().describe("User ID who last updated the connection"),organization_id:D8.string().describe("Organization ID this connection belongs to"),description:D8.string().nullable().describe("Description of the connection"),icon:D8.string().nullable().describe("Icon URL for the connection"),app_name:D8.string().nullable().describe("Associated app name"),app_id:D8.string().nullable().describe("Associated app ID"),slug:D8.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:D8.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:D8.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:D8.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:D8.union([ci6,ui6]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:gi6.nullable().describe("OAuth configuration"),configuration_state:D8.record(D8.string(),D8.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:D8.array(D8.string()).nullable().optional().describe("Configuration scopes"),metadata:D8.record(D8.string(),D8.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:D8.array(hi6).nullable().describe("Discovered tools from MCP"),bindings:D8.array(D8.string()).nullable().describe("Detected bindings"),status:D8.enum(["active","inactive","error"]).describe("Current status")}),T90=i7.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}).extend({icon:D8.string().nullish()}),I90=i7.partial()});import{z as c0}from"zod";function Jm0($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let X=$?.homeTile;return X?[X]:[]}function Hm0($){return $==="cluster"?"agent-sandbox":$}function lt1($){let Z=pi6.parse($);return Nm0.parse({...Z,sandboxProviderKind:Z.sandboxProviderKind?Hm0(Z.sandboxProviderKind):void 0})}function UJ($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,X={};for(let[Q,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;if(Q!=="cluster"&&Q!=="agent-sandbox"&&Q!=="user-desktop")continue;let G=Hm0(Q);try{if(Q==="cluster"&&X[G])continue;X[G]=lt1(Y)}catch{}}return X}function Um0($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[X,Q]of Object.entries($)){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Y={};for(let[G,J]of Object.entries(Q)){let K=UJ(J);if(Object.keys(K).length>0)Y[G]=K}if(Object.keys(Y).length>0)Z[X]=Y}return Z}var gm,yt1,li6,gt1,ht1,ft1,Gm0,R90,bt1,di6,ut1,mi6,Km0,Wm0,ii6,ni6,ct1,Nm0,pi6,q90,ti6,Fm0,oi6,wm0,n7,Bm0,M90,k90;var dt1=O(()=>{gm=c0.object({connection_id:c0.string().describe("Connection ID"),selected_tools:c0.array(c0.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:c0.array(c0.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:c0.array(c0.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),yt1=gm.extend({selected_tools:gm.shape.selected_tools.optional(),selected_resources:gm.shape.selected_resources.optional(),selected_prompts:gm.shape.selected_prompts.optional()}),li6=c0.object({connectionId:c0.string(),toolName:c0.string(),label:c0.string(),icon:c0.string().nullable().optional()}),gt1=c0.object({id:c0.string().describe("Stable id; used as React key and ?tab= value"),title:c0.string().describe("Tab label"),icon:c0.string().optional().describe("Optional lucide icon name"),view:c0.object({type:c0.literal("ext-app"),appId:c0.string(),args:c0.record(c0.string(),c0.unknown()).optional()})}),ht1=c0.object({defaultMainView:c0.object({type:c0.string(),id:c0.string().optional(),toolName:c0.string().optional()}).nullable().optional(),chatDefaultOpen:c0.boolean().nullable().optional(),cmsDefaultOpen:c0.boolean().nullable().optional(),tabs:c0.array(gt1).optional()}),ft1=c0.object({tileId:c0.string().optional(),connectionId:c0.string().optional().describe("Connection that owns the resource \u2014 the host opens a direct MCP client to this connection so the iframe can call tools by their bare names."),resourceUri:c0.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),toolName:c0.string().optional().describe("Tool name \u2014 identifies which tool's inputSchema to display when editing tile props."),toolInput:c0.record(c0.string(),c0.unknown()).optional().describe("User-configured input props passed to MCPAppRenderer when rendering the tile."),minHeight:c0.number().int().positive().optional(),maxHeight:c0.number().int().positive().optional()}),Gm0=c0.object({banner:c0.string().nullable().optional(),bannerColor:c0.string().nullable().optional(),icon:c0.string().nullable().optional(),themeColor:c0.string().nullable().optional(),pinnedViews:c0.array(li6).nullable().optional(),layout:ht1.nullable().optional(),homeTile:ft1.nullable().optional(),homeTiles:c0.array(ft1).nullable().optional(),homePrompts:c0.array(c0.string()).nullable().optional()});R90=/^[A-Za-z_][A-Za-z0-9_]*$/,bt1=c0.string().min(1).regex(R90,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),di6=c0.discriminatedUnion("kind",[c0.object({key:bt1,kind:c0.literal("literal"),value:c0.string()}),c0.object({key:bt1,kind:c0.literal("secret"),secretId:c0.string().min(1)})]),ut1=/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/,mi6=c0.object({host:c0.string().min(1).regex(ut1).describe("Submodule host, e.g. 'github.com' (bare hostname, no scheme)."),secretId:c0.string().min(1).describe("Vault secret id holding the PAT used to fetch this host.")}),Km0=c0.object({selected:c0.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:c0.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:c0.string().nullable().optional().describe("Optional path (relative to repo root) to the directory containing package.json. Null/absent means repo root. Forwarded as `application.packageManager.path` to the daemon config."),env:c0.array(di6).nullable().optional().describe("Env vars injected on every SANDBOX_START. Literal entries inline their value; secret entries store a secretId that Studio resolves via the credential vault before posting /_sandbox/config."),submoduleCredentials:c0.array(mi6).nullable().optional().describe("Git submodule credentials injected on every SANDBOX_START. Each entry maps a host to a vault secret (PAT) that Studio resolves before posting /_sandbox/config; the daemon uses it to authenticate `git submodule update` for submodules on that host.")}),Wm0=c0.object({url:c0.string().describe("GitHub repository URL"),owner:c0.string().describe("Repository owner"),name:c0.string().describe("Repository name"),installationId:c0.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:c0.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials.")}),ii6=c0.enum(["agent-sandbox","user-desktop"]),ni6=c0.enum(["agent-sandbox","user-desktop","cluster"]);ct1={sandboxHandle:c0.string().describe("Provider-specific handle"),previewUrl:c0.string().nullable().describe("URL where the sandbox's iframe-proxied UI is served, or null when the sandbox has no dev server (blank / tool sandboxes)."),sandboxApiUrl:c0.string().nullable().optional().describe("Daemon's public URL \u2014 what cluster\u2192daemon RPCs target. Equal to previewUrl for user-desktop; null/absent for the agent-sandbox provider (routes through hosted ingress)."),sandboxProviderKind:ii6.optional(),createdAt:c0.number().optional().describe("Epoch ms the entry was first written by SANDBOX_START. Used by the booting overlay to show a stable elapsed timer that survives browser reloads. Optional for backward compatibility with entries written before this field existed."),startedWith:c0.object({packageManager:c0.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:c0.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:c0.string().nullable().optional().describe("metadata.runtime.path at the time of SANDBOX_START")}).optional().describe("Snapshot of metadata.runtime fields (selected/port/path) used at SANDBOX_START. The Preview tab compares the live metadata.runtime against this to decide if a restart is required to apply changes.")},Nm0=c0.object(ct1),pi6=c0.object({...ct1,sandboxProviderKind:ni6.optional()});q90=c0.record(c0.string().describe("userId"),c0.record(c0.string().describe("branch"),c0.record(c0.string().describe("sandboxProviderKind"),Nm0)));ti6=c0.object({id:c0.string().describe("Stable identifier for this knowledge file"),name:c0.string().describe("File name shown in the UI"),kind:c0.enum(["file","skill"]).optional().describe("'file' (a single document) or 'skill' (a Claude Code skill folder containing SKILL.md). Defaults to 'file'."),volume:c0.string().describe("Org filesystem (Library) volume the file lives in"),path:c0.string().describe("Path within the volume"),url:c0.string().describe("Same-origin URL to read the file (display/download)"),contentType:c0.string().nullable().optional().describe("MIME type, used to decide whether to inline the content"),size:c0.number().nullable().optional().describe("File size in bytes"),addedAt:c0.string().describe("ISO timestamp when the file was attached")}),Fm0=c0.array(ti6).nullable().optional().describe("Files attached to the agent as reference knowledge. Surfaced in the system prompt: small text documents are inlined, others are listed as retrievable references."),oi6=c0.enum(["smart","code-review","open"]),wm0=oi6.nullable().optional().describe("Controls when this code agent's changes may be published directly vs. requiring PR review. 'smart' (default) uses AI to judge per change; 'code-review' requires review for any code; 'open' allows direct publish always."),n7=c0.object({id:c0.string().describe("Unique identifier"),title:c0.string().describe("Human-readable name"),description:c0.string().nullable().describe("Description"),icon:c0.string().nullable().describe("Icon URL"),created_at:c0.string().describe("Creation timestamp"),updated_at:c0.string().describe("Last update timestamp"),created_by:c0.string().describe("User ID who created this item"),updated_by:c0.string().optional().describe("User ID who last updated this item"),organization_id:c0.string().describe("Organization ID this item belongs to"),status:c0.enum(["active","inactive"]).describe("Current status"),pinned:c0.boolean().describe("Whether this space is pinned to the sidebar"),metadata:c0.object({instructions:c0.string().nullable().describe("Instructions also used as system prompt"),enabled_plugins:c0.array(c0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:c0.array(c0.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:c0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:Gm0.nullable().optional().describe("UI customization settings"),githubRepo:Wm0.nullable().optional().describe("Linked GitHub repository"),runtime:Km0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:q90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:Fm0,siteSlug:c0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:wm0,productionUrl:c0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:c0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title.")}).loose().describe("Metadata"),connections:c0.array(gm).describe("Connections with their selected tools, resources, and prompts")}),Bm0=c0.object({title:c0.string().min(1).max(120).describe("Short label shown on the chip"),description:c0.string().max(280).optional().describe("One-line subtitle shown under the title"),text:c0.string().min(1).describe("The message sent to the agent when the prompt is clicked")}),M90=c0.object({title:c0.string().min(1).max(255).describe("Name for the virtual MCP"),description:c0.string().nullable().optional().describe("Optional description"),icon:c0.string().nullish().describe("Optional icon URL"),status:c0.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:c0.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:c0.object({instructions:c0.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:c0.array(c0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:c0.array(c0.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:c0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:Gm0.nullable().optional().describe("UI customization settings"),githubRepo:Wm0.nullable().optional().describe("Linked GitHub repository"),runtime:Km0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:q90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:Fm0,siteSlug:c0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:wm0,productionUrl:c0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:c0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title.")}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:c0.array(yt1).describe("Connections to include/exclude (can be empty for exclusion mode)"),prompts:c0.array(Bm0).optional().describe("Optional kickstart prompts to seed on the agent. Each becomes a clickable conversation starter (icebreaker) on the agent. Author them from the agent's role and the tools it will have so they're coherent and immediately useful.")}),k90=c0.object({title:c0.string().min(1).max(255).optional().describe("New name"),description:c0.string().nullable().optional().describe("New description (null to clear)"),icon:c0.string().nullish().describe("New icon URL"),status:c0.enum(["active","inactive"]).optional().describe("New status"),pinned:c0.boolean().optional().describe("Pin/unpin from sidebar"),metadata:c0.object({instructions:c0.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:c0.array(c0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:c0.array(c0.string()).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:c0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:Gm0.nullable().optional().describe("UI customization settings"),githubRepo:Wm0.nullable().optional().describe("Linked GitHub repository"),runtime:Km0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:q90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:Fm0,siteSlug:c0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:wm0,productionUrl:c0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:c0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title.")}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:c0.array(yt1).optional().describe("New connections (replaces existing)"),prompts:c0.array(Bm0).optional().describe("Replace the agent's kickstart prompts with this full set. Omit to leave them unchanged; pass an empty array to remove all. Each becomes a clickable conversation starter (icebreaker).")})});function vD($){return ri6.has($)}var p7,ri6,S90;var mt1=O(()=>{p7=["deco","anthropic","openrouter","llmapi","google","openai-compatible"],ri6=new Set(p7);S90=[...p7,"claude-code","codex"]});function Om0($,Z){return{id:crypto.randomUUID(),type:hm.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function V90($,Z){return{id:crypto.randomUUID(),type:hm.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function sK($,Z,X){return{id:crypto.randomUUID(),type:hm.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...X?.messageId!==void 0&&{message_id:X.messageId},...X?.virtualMcpId!==void 0&&{virtual_mcp_id:X.virtualMcpId},...X?.createdBy!==void 0&&{created_by:X.createdBy},...X?.triggerId!==void 0&&{trigger_id:X.triggerId},...X?.title!==void 0&&{title:X.title},...X?.branch!==void 0&&{branch:X.branch},...X?.harnessId!==void 0&&{harness_id:X.harnessId},...X?.createdAt!==void 0&&{created_at:X.createdAt},...X?.updatedAt!==void 0&&{updated_at:X.updatedAt},...X?.metadata!==void 0&&{metadata:X.metadata}},time:new Date().toISOString()}}var it1,ai6,hm,si6;var nt1=O(()=>{it1=["in_progress","requires_action","failed","completed"],ai6=[...it1,"expired"],hm={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},si6=Object.values(hm)});var C90=O(()=>{vt1();dt1();mt1();nt1()});function tt1($){return{id:p4.REGISTRY($),title:"Deco Store",description:"Official deco MCP registry with curated integrations",connection_type:"HTTP",connection_url:"https://studio.decocms.com/org/deco/registry/mcp",icon:"https://assets.decocache.com/decocms/00ccf6c3-9e13-4517-83b0-75ab84554bb9/596364c63320075ca58483660156b6d9de9b526e.png",app_name:"deco-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function ot1(){return{id:"community-registry",title:"MCP Registry",description:"Community MCP registry with thousands of handy MCPs",connection_type:"HTTP",connection_url:"https://sites-registry.deco.site/mcp",icon:"https://assets.decocache.com/decocms/cd7ca472-0f72-463a-b0de-6e44bdd0f9b4/mcp.png",app_name:"mcp-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function rt1($,Z){return{id:p4.SELF(Z),title:"Deco CMS",description:"The MCP for the CMS API",connection_type:"HTTP",connection_url:`${$}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}function at1($,Z){return{id:p4.DEV_ASSETS(Z),title:"Local Files",description:"Local file storage for development. Files are stored in /data/assets/.",connection_type:"HTTP",connection_url:`${$}/mcp/dev-assets`,icon:"https://api.iconify.design/lucide:folder.svg?color=%23888",app_name:"@deco/dev-assets-mcp",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isFixed:!0,devOnly:!0,type:"dev-assets"}}}function gY($){return{is(Z){if(!Z)return null;if(!Z.startsWith($))return null;return Z.slice($.length)||null},get(Z){return`${$}${Z}`}}}function st1($){return{id:$.id,organization_id:$.organizationId,title:$.title,description:$.description,icon:$.icon,status:"active",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),created_by:"system",updated_by:void 0,metadata:{instructions:$.instructions??null,...$.ui?{ui:$.ui}:{}},pinned:!1,connections:[]}}function Dm0($){return st1({id:fD($),organizationId:$,title:"Super Agent",description:"Default agent that aggregates all organization connections",icon:ei6,ui:{layout:{defaultMainView:{type:"overview"},chatDefaultOpen:!0}}})}function Qo1($){return st1({id:$n6($),organizationId:$,title:"Brand context setup",description:"Guided onboarding agent that extracts brand context from a website URL.",icon:"https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",instructions:Zn6})}function Jo1($,Z,X="https://reports.decocms.com/api/v2/mcp"){return{id:p4.COMMERCE_DISCOVERY($),title:"Store Report",description:"Your store's report and diagnostics",connection_type:"HTTP",connection_url:X,icon:"https://github.com/decocms.png",app_name:"commerce-discovery",app_id:null,connection_token:Z,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!1,type:"commerce-discovery"}}}function Ko1($,Z=p4.COMMERCE_DISCOVERY($)){return{title:"Report Agent",description:"Ask anything about your store's report",icon:"https://github.com/decocms.png",status:"active",pinned:!0,metadata:{type:"commerce-discovery",isDefault:!1,ui:{pinnedViews:[{connectionId:Z,toolName:"get_my_diagnostic",label:"Report",icon:"https://github.com/decocms.png"}],layout:{defaultMainView:{type:"ext-apps",id:Z,toolName:"get_my_diagnostic"},chatDefaultOpen:!0}}},connections:[{connection_id:Z,selected_tools:["get_my_diagnostic"],selected_resources:null,selected_prompts:null}]}}function Wo1($){if(!$)return!1;return Object.values(DN).some((Z)=>Z.is($)!==null)}function Ho1($){let Z=Dm0($);return{...Z,id:Z.id,connection_type:"VIRTUAL",connection_url:`virtual://${Z.id}`,app_name:"decopilot",app_id:"decopilot",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"decopilot"},tools:[],bindings:[]}}var p4,pt1="https://reports.decocms.com/api/v2/mcp",_90="get_my_diagnostic",et1,mG,fD,$o1,Zo1,Lm0,ei6="https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",Xo1,x90,$n6,Zn6,Yo1,a85,s85,Go1,e85,v90,DN,t7;var No1=O(()=>{p4={SELF:($)=>`${$}_self`,REGISTRY:($)=>`${$}_registry`,COMMUNITY_REGISTRY:($)=>`${$}_community-registry`,DEV_ASSETS:($)=>`${$}_dev-assets`,SITE_DIAGNOSTICS:($)=>`site-diagnostics_${$}`,COMMERCE_DISCOVERY:($)=>`${$}_commerce-discovery`};et1=gY("decopilot_"),mG=et1.is,fD=et1.get,$o1=gY("dev_"),Zo1=$o1.get,Lm0=$o1.is;Xo1=gY("brand-context-setup_"),x90=Xo1.is,$n6=Xo1.get,Zn6=`
|
|
1284
1284
|
You are running the brand-context onboarding for the user's organization. Your only job in this thread is to set up the organization's brand context:
|
|
1285
1285
|
|
|
1286
1286
|
1. If the user hasn't already given you a website URL, ask for it in one short message. Accept whatever URL they give \u2014 don't quibble about format.
|
|
@@ -2419,7 +2419,7 @@ Respond with a JSON object containing the title.`,Fz8=($)=>/[\p{L}\p{N}]/u.test(
|
|
|
2419
2419
|
`);return""}return""}function Lz8($,Z){let X=new Set;for(let Q of $){if(Q.role!=="assistant")continue;for(let Y of Q.parts){let G=Y;if((G.toolName==="enable_tool"||G.toolName==="enable_tools")&&G.result){let J=G.result;if(Array.isArray(J.enabled))for(let K of J.enabled){let W=K.replace(/[^a-zA-Z0-9_]/g,"_");if(Z.has(W))X.add(W);else if(Z.has(K))X.add(K)}}}}return X}function Dz8($){let Z=$.modeConfig.forcedFirstStepTool&&$.modeConfig.forcedFirstStepTool in $.streamTools?$.modeConfig.forcedFirstStepTool:null,X=0;return(Q)=>{let Y=Q.messages,G=X===0;X++;let J=Y;if($.pendingImages.length>0){let H=$.pendingImages.splice(0,$.pendingImages.length),N=[];for(let U of H)if(N.push({type:"text",text:U.label??(U.pageUrl?`[Screenshot of ${U.pageUrl}]`:"[Image]")}),U.url.startsWith("data:")){let F=U.url.match(/^data:([^;]+);base64,(.+)$/s);if(F)N.push({type:"image",image:F[2],mimeType:F[1]})}else N.push({type:"image",image:new URL(U.url)});J=[...Y,{role:"user",content:N}]}let K=[...$.builtInToolNames,...$.hasEnableTool?["enable_tool"]:[],...$.enabledTools];if($.modeConfig.isPlanMode)K=K.filter((H)=>{if($.builtInToolNames.includes(H)||$.hasEnableTool&&H==="enable_tool")return!0;return $.toolAnnotations.get(H)?.readOnlyHint===!0});let W=Z&&G?Z:null;return{activeTools:K,messages:J,...W&&{toolChoice:{type:"tool",toolName:W}}}}}function $q4(){let $=[],Z=!1,X=null;return{push(Q){if(Z)return;if(X){let Y=X;X=null,Y({done:!1,value:Q})}else $.push(Q)},next(){if($.length>0){let Q=$.shift();return Promise.resolve({done:!1,value:Q})}if(Z)return Promise.resolve({done:!0});return new Promise((Q)=>{X=Q})},close(){if(Z=!0,X){let Q=X;X=null,Q({done:!0})}}}}async function*Ez8($){let{input:Z,tools:X,runEngine:Q,extras:Y}=$,G=Y.runContext,{provider:J,titleProvider:K,titleModel:W,registrySignal:H,processedSystemMessages:N,processedMessages:U,originalMessages:F,threadId:w,writer:B,telemetry:L}=Y,D=J61(Z.mode,{isCliAgent:!1}),E,z=!1,j=$q4(),A=Xz8({currentThreadTitle:Y.currentThreadTitle,kind:Y.kind}),P=Oz8(U),R=(()=>{if(!A)return[];let o0=new Set,m1=[],v8=(U$,Y5)=>{if(!Y5||o0.has(Y5.id))return;o0.add(Y5.id),m1.push(()=>I30(U$,Y5))};return v8(K??J,W),v8(J,Z.models.fast),v8(J,Z.models.smart),v8(J,Z.models.thinking),m1})(),S=A?wz8({abortSignal:H,models:R,userMessage:P}):null,M=S?S.promise.then((o0)=>{return o0?eE8(o0):null}).catch((o0)=>{return console.warn("[decopilot:title] title generation failed",WU(o0)),null}):Promise.resolve(null),C=null,m=Y.usageAccumulator??A30();E=Date.now();let v=new Set(Object.keys(X.passthroughTools)),b=Object.keys(X.builtInTools),y=Y.kind==="subtask"||G?.isSubagent===!0?new Set(v):Lz8(F,v),Z0={...X.tools,...X.connectionsBlockTools.length>0?{enable_tool:rE8(y,v,{isPlanMode:D.isPlanMode,toolAnnotations:X.toolAnnotations})}:{}},U0=Dz8({modeConfig:D,streamTools:Z0,builtInToolNames:b,enabledTools:y,toolAnnotations:X.toolAnnotations,pendingImages:Y.pendingImages,hasEnableTool:X.connectionsBlockTools.length>0}),k0=y.size>0?{role:"system",content:`<currently-enabled-tools>
|
|
2420
2420
|
${[...y].sort().join(`
|
|
2421
2421
|
`)}
|
|
2422
|
-
</currently-enabled-tools>`}:null,$0=G?.virtualMcp.metadata,e=Z.workspace.cwd==="/repo"?{repo:Z.workspace.repo,branch:Z.workspace.branch,cwd:Z.workspace.cwd,workspaceKind:"github"}:void 0,I0=await Q({kind:G?.isSubagent?"subagent":"agent",virtualMcp:{id:Z.agent.id,repo:$0?.githubRepo??void 0,delegationTargetIds:$0?.subAgents},mcpClient:X.passthroughClient,provider:J,models:Z.models,messages:U,abortSignal:H,temperature:Z.temperature,planMode:D.isPlanMode,isDecopilot:mG(Z.agent.id)!==null,codingWorkspace:e,systemAgentInstructions:X.serverInstructions,currentThreadId:w,user:{id:Z.user.id,email:Z.user.email},userContext:G?.userContext,writer:B,prepareStep:U0,onStepFinish:Y.onStepFinish,passthroughClient:X.passthroughClient,connectionsData:{tools:X.connectionsBlockTools,connectionTitleMap:X.connectionTitleMap},toolOutputMap:X.toolOutputMap,extraTools:{...X.builtInTools,...X.connectionsBlockTools.length>0&&Z0.enable_tool?{enable_tool:Z0.enable_tool}:{}},additionalSystemMessages:[...N,...k0?[k0]:[]],activeToolNames:[...b,..."enable_tool"in Z0?["enable_tool"]:[],...y],stepLimit:Y.stepLimit??Z.maxAgentSteps}),Q0=I0.result,p0=Promise.resolve(Q0.finishReason).then(async(o0)=>{let[m1,v8,U$,Y5]=await Promise.all([Q0.totalUsage,Q0.usage,Q0.request,Q0.response]);if(await I0.error!==void 0)return;I0.span.setAttribute("decopilot.llm.inputTokens",m1.inputTokens??0),I0.span.setAttribute("decopilot.llm.outputTokens",m1.outputTokens??0),I0.span.setAttribute("decopilot.llm.finishReason",o0);let r=m.cacheTotals();I0.span.setAttribute("decopilot.cache.read_tokens",r.read),I0.span.setAttribute("decopilot.cache.write_tokens",r.write);let Y1=r.input>0?r.read/r.input:0;I0.span.setAttribute("decopilot.cache.hit_ratio",Y1);let $6=Date.now()-(E??Date.now());if(z=!0,L?.recordLlmCall({organizationId:Z.organizationId,modelId:Z.models.thinking.id,durationMs:$6,isError:!1,inputTokens:m1.inputTokens,outputTokens:m1.outputTokens,cacheReadTokens:r.read,cacheWriteTokens:r.write}),L?.monitorLlmCall({organizationId:Z.organizationId,agentId:Z.agent.id,modelId:Z.models.thinking.id,modelTitle:Z.models.thinking.title??Z.models.thinking.id,credentialId:Z.models.thinking.credentialId,taskId:w,durationMs:$6,isError:!1,finishReason:o0,usage:{inputTokens:v8.inputTokens??0,outputTokens:v8.outputTokens??0,totalTokens:v8.totalTokens??0},totalUsage:{inputTokens:m1.inputTokens??0,outputTokens:m1.outputTokens??0,totalTokens:m1.totalTokens??0},cost:m.cost(),request:U$,response:Y5,userId:Z.user.id}),H.aborted)return}).catch(async(o0)=>{let m1=o0 instanceof Error?o0:Error(WU(o0));if(console.error("[decopilot:stream] Error",m1.message),H.aborted)return;if(!z){let v8=Date.now()-(E??Date.now());z=!0,L?.recordLlmCall({organizationId:Z.organizationId,modelId:Z.models.thinking.id,durationMs:v8,isError:!0,errorType:m1.name}),L?.monitorLlmCall({organizationId:Z.organizationId,agentId:Z.agent.id,modelId:Z.models.thinking.id,modelTitle:Z.models.thinking.title??Z.models.thinking.id,credentialId:Z.models.thinking.credentialId,taskId:w,durationMs:v8,isError:!0,errorMessage:m1.message,userId:Z.user.id})}}).catch((o0)=>{console.error("[decopilot:stream] finish metrics failed",o0)}),r0=I0.error.then(async(o0)=>{if(!H.aborted||z)return null;let m1=await Q0.steps;if(!m1.length||z)return null;z=!0;let v8=Date.now()-(E??Date.now()),U$=m1.reduce((Y1,$6)=>({inputTokens:Y1.inputTokens+($6.usage.inputTokens??0),outputTokens:Y1.outputTokens+($6.usage.outputTokens??0),totalTokens:Y1.totalTokens+($6.usage.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),Y5=m1[m1.length-1].usage,o5=m.cacheTotals();if(L?.recordLlmCall({organizationId:Z.organizationId,modelId:Z.models.thinking.id,durationMs:v8,isError:!1,inputTokens:U$.inputTokens,outputTokens:U$.outputTokens,cacheReadTokens:o5.read,cacheWriteTokens:o5.write}),L?.monitorLlmCall({organizationId:Z.organizationId,agentId:Z.agent.id,modelId:Z.models.thinking.id,modelTitle:Z.models.thinking.title??Z.models.thinking.id,credentialId:Z.models.thinking.credentialId,taskId:w,durationMs:v8,isError:!1,finishReason:"abort",usage:{inputTokens:Y5.inputTokens??0,outputTokens:Y5.outputTokens??0,totalTokens:Y5.totalTokens??0},totalUsage:U$,cost:m.cost(),request:void 0,response:void 0,userId:Z.user.id}),U$.totalTokens<=0)return null;let r=m.cost();return{type:"message-metadata",messageMetadata:{usage:{inputTokens:U$.inputTokens,outputTokens:U$.outputTokens,totalTokens:U$.totalTokens,cachedInputTokens:o5.read,inputTokenDetails:{cacheReadTokens:o5.read,cacheWriteTokens:o5.write,noCacheTokens:U$.inputTokens-o5.read-o5.write},...r>0&&{providerMetadata:{openrouter:{usage:{cost:r}}}}}}}}).then((o0)=>o0).catch((o0)=>{return console.error("[decopilot:stream] abort metadata failed",o0),null}),S0=Q0.toUIMessageStream({originalMessages:F,generateMessageId:_p,onError:(o0)=>Jz8(o0),messageMetadata:({part:o0})=>{if(o0.type==="start")return{agent:{id:Z.agent.id??null},models:{credentialId:Z.models.thinking.credentialId,thinking:{...Z.models.thinking,title:Z.models.thinking.title??Z.models.thinking.id,provider:Z.models.thinking.provider??void 0}},created_at:new Date,_request:{systemSections:I0.assembledSystemMessages.map((m1)=>({chars:m1.content.length,preview:m1.content.slice(0,80).replace(/\s+/g," ")})),tools:Object.keys(Z0).length,activeTools:b.length+("enable_tool"in Z0?1:0)+y.size},thread_id:w,...G?.subtaskJobId?{subtaskJobId:G.subtaskJobId}:{},...G?.resumedFromBackground?{resumedFromBackground:!0}:{}};if(o0.type==="reasoning-start"){if(C===null)C=new Date;return{reasoning_start_at:C}}if(o0.type==="reasoning-end")return{reasoning_end_at:new Date};if(o0.type==="finish-step")return m.addStep(o0.usage,o0.providerMetadata),{usage:m.buildStepUsage()};if(o0.type==="finish"){let m1=m.buildFinalUsage({totalUsage:o0.totalUsage,providerKey:Z.models.thinking.provider,fallbackProviderMetadata:o0.providerMetadata});return m1?{usage:m1}:{}}return}})[Symbol.asyncIterator](),C0=Y.sideChunks?.[Symbol.asyncIterator](),q0=!1,X0=S===null,W0=!1,h0=!1,w0=!1,j0=C0===void 0,H1=!1,o=S0.next().then((o0)=>({kind:"main",value:o0})),A0=j.next().then((o0)=>({kind:"queue",value:o0})),v0=C0?C0.next().then((o0)=>({kind:"side",value:o0})):null,F1=M.then((o0)=>({kind:"title",value:o0})),f1=p0.then(()=>({kind:"finish-metrics"})),d8=r0.then((o0)=>({kind:"abort-metadata",value:o0}));try{while(!q0||!X0||!W0||!h0||!w0||!j0){if(q0&&X0&&W0&&h0&&!H1)Y.closeSideChunks?.(),j.close(),H1=!0;let o0=[];if(!w0)o0.push(A0);if(!q0)o0.push(o);if(!X0)o0.push(F1);if(!W0)o0.push(f1);if(!h0)o0.push(d8);if(!j0&&v0)o0.push(v0);let m1=await Promise.race(o0);if(m1.kind==="main"){if(m1.value.done){if(q0=!0,!X0)S?.finish();continue}yield m1.value.value,o=S0.next().then((v8)=>({kind:"main",value:v8}))}else if(m1.kind==="title"){if(X0=!0,m1.value)yield m1.value}else if(m1.kind==="finish-metrics")W0=!0;else if(m1.kind==="abort-metadata"){if(h0=!0,m1.value)yield m1.value}else if(m1.kind==="side"){if(m1.value.done){j0=!0;continue}yield m1.value.value,v0=C0?.next().then((v8)=>({kind:"side",value:v8}))??null}else{if(m1.value.done){w0=!0;continue}yield m1.value.value,A0=j.next().then((v8)=>({kind:"queue",value:v8}))}}}finally{if(!X0)S?.finish();Y.closeSideChunks?.(),await S0.return?.().catch(()=>{}),await C0?.return?.().catch(()=>{}),j.close()}}var zz8=O(()=>{aE8();G61();wa0();K61();Qz8();N61();Bz8();I6()});function jz8($){return $.type==="tool-call"&&$.toolName==="todo_write"&&typeof $.toolCallId==="string"}function Zq4($){return $.type==="tool-result"&&$.toolName==="todo_write"&&typeof $.toolCallId==="string"}function Pz8($){let Z=null;for(let Q=$.length-1;Q>=0&&Z===null;Q--){let G=$[Q].content;if(!Array.isArray(G))continue;for(let J=G.length-1;J>=0;J--){let K=G[J];if(jz8(K)){Z=K.toolCallId;break}}}if(Z===null)return $;let X=Z;return $.map((Q)=>{let Y=Q.content;if(!Array.isArray(Y))return Q;let G=Y.filter((J)=>{if(jz8(J))return J.toolCallId===X;if(Zq4(J))return J.toolCallId===X;return!0});if(G.length===Y.length)return Q;return{...Q,content:G}})}function Az8($){let Z=!1,X=$.map((Q)=>{if(Q.role!=="assistant")return Q;if(!Q.parts.some((G)=>("state"in G)&&G.state==="approval-requested"))return Q;return Z=!0,{...Q,parts:Q.parts.map((G)=>{if(!("state"in G)||G.state!=="approval-requested"||!("approval"in G)||!G.approval)return G;return{...G,state:"output-denied",approval:{...G.approval,approved:!1,reason:"User sent a new message without approving this tool call."}}})}});return Z?X:$}function Xq4($){let[Z,X]=$.reduce((Q,Y)=>{if(Y.role==="system")Q[0].push(Y);else Q[1].push(Y);return Q},[[],[]]);return{systemMessages:Z,messages:X}}async function U61($,Z){let X=$.filter((U)=>U.role!=="assistant"||U.parts&&U.parts.length>0),Q=await Xr({messages:X}),Y=Az8(Q),G=await Zr(Y,{tools:Z.tools,ignoreIncompleteToolCalls:!0}),{systemMessages:J,messages:K}=Xq4(G),W=Pz8(K),N=$61({messages:W,reasoning:"all",emptyMessages:"remove",toolCalls:"none"}).map((U)=>{if(U.role!=="assistant")return U;let F=Array.isArray(U.content)?U.content.filter((w)=>w.type!=="reasoning"&&w.type!=="thinking"&&w.type!=="redacted-reasoning").map((w)=>{let B=w;if("providerOptions"in B||"providerMetadata"in B){let{providerOptions:L,providerMetadata:D,...E}=B;if(B.type==="tool-call"){let z=D?.google,j=L?.google;return{...E,...z?{providerMetadata:{google:z}}:{},...j?{providerOptions:{google:j}}:{}}}return E}return w}):U.content;return{...U,content:Array.isArray(F)&&F.length===0?[{type:"text",text:""}]:F,providerOptions:void 0,providerMetadata:void 0}});return{systemMessages:J,messages:N,originalMessages:Q}}var F61=O(()=>{u4()});function Tz8($){if($<1)throw Error("Semaphore cap must be >= 1");let Z=$,X=[];function Q(Y){return Y.reason??Error("Semaphore acquire aborted")}return{acquire(Y){if(Y?.aborted)return Promise.reject(Q(Y));if(Z>0)return Z-=1,Promise.resolve();return new Promise((G,J)=>{let K={resolve:G,reject:J,cleanup:()=>{}},W=()=>{let H=X.indexOf(K);if(H!==-1)X.splice(H,1);K.cleanup(),J(Q(Y))};if(Y)Y.addEventListener("abort",W,{once:!0}),K.cleanup=()=>Y.removeEventListener("abort",W);X.push(K)})},release(){let Y=X.shift();if(Y){Y.cleanup(),Y.resolve();return}if(Z+=1,Z>$)Z=$},available(){return Z}}}function w61($,Z){Iz8.set($,Z)}function B61($){return Iz8.get($)}function Jh($){let Z=B61($);if(!Z)throw Error("Decopilot requires process-local run context. Dispatch must attach DecopilotRunContext before invoking the Decopilot harness.");return Z}var Iz8;var Kh=O(()=>{Iz8=new WeakMap});function Rz8($,Z){let X=$.modelSources?.thinking??null;if(!X||X.kind!=="secret")throw Error("Decopilot core requires a secret thinking model source. Dispatch must resolve the selected model credential before invoking Decopilot.");let Q=Z(X),Y=(N)=>{let U=$.models[N];if(!U)return;let F=$.modelSources?.[N];if(F&&F.kind!=="secret")throw Error("Decopilot core requires secret modelSources for all resolved slots.");return{model:U,provider:F&&F.kind==="secret"?Z(F):Q}},G=Y("fast"),J=Y("smart"),K=Y("image"),W=Y("webSearch"),H=Y("deepResearch");return{thinking:{model:$.models.thinking,provider:Q},...G?{fast:G}:{},...J?{smart:J}:{},...K?{image:K}:{},...W?{webSearch:W}:{},...H?{deepResearch:H}:{}}}async function*qz8($){let{input:Z,modelRuntime:X,toolRuntime:Q,telemetry:Y}=$,G=B61(Z),J=$.kind==="subtask",K=A30(),W=J?void 0:(D)=>K.addExternal(D),H=await Q.buildEnvironmentTools({input:Z,onChildUsage:W});if(J)Yq4(H);let{systemMessages:N,messages:U,originalMessages:F}=await U61(G?.messages??[Z.userMessage],{windowSize:X3,models:Z.models,tools:H.tools}),w=U,B=Z.models.fast??Z.models.smart??Z.models.thinking,L=(Z.models.fast?X.fast?.provider:void 0)??(Z.models.smart?X.smart?.provider:void 0)??X.thinking.provider;yield*Ez8({input:Z,tools:H,runEngine:Q.runEngine,extras:{provider:X.thinking.provider,titleProvider:L,titleModel:B,registrySignal:Z.signal??new AbortController().signal,processedSystemMessages:N,processedMessages:w,originalMessages:F,threadId:Z.threadId,currentThreadTitle:Z.currentThreadTitle??"",pendingImages:H.pendingImages,writer:H.writer,sideChunks:H.sideChunks,closeSideChunks:H.closeSideChunks,onStepFinish:H.onStepFinish,telemetry:Y,kind:$.kind,stepLimit:J?hN:void 0,usageAccumulator:K,runContext:G}})}function Yq4($){if("subtask"in $.tools){let{subtask:Z,...X}=$.tools;$.tools=X}if("subtask"in $.builtInTools){let{subtask:Z,...X}=$.builtInTools;$.builtInTools=X}}var Qq4=4,Vd5;var Mz8=O(()=>{zz8();F61();hE();G61();Kh();Vd5=Tz8(Qq4)});function Gq4($){return"storage"in $}function kz8($){O61=$}var O61,Sz8;var L61=O(()=>{J81();Mz8();Kh();Sz8={id:"decopilot",create($){return{id:"decopilot",async*stream(Z){let X=Jh(Z),Q=Rz8({models:Z.models,modelSources:X.modelSources},aG0),Y=sG0(),G={};if(!Gq4($))throw Error("[decopilot] a hosted Studio context is required");if(!O61)throw Error("[decopilot] cluster environment builder not registered \u2014 "+"apps/api/src/harnesses must be imported before dispatching the decopilot harness in cluster mode");let J=O61({ctx:$,modelRuntime:Q,sideChannel:Y,cleanup:G});try{yield*qz8({input:Z,modelRuntime:Q,toolRuntime:J.toolRuntime,telemetry:J.telemetry,kind:"main"})}finally{Y.close(),await G.close?.().catch(()=>{})}}}}}});class D61{ctx;harnessId;constructor($){this.ctx=$.ctx,this.harnessId=$.harnessId}dispatch($){if(this.harnessId!=="decopilot")throw Error(`InProcessSandboxClient runs cluster-hosted decopilot only; got "${this.harnessId}" \u2014 CLI harnesses run in the desktop app or are `+"rejected at the gate");return Sz8.create(this.ctx).stream($)}}var Vz8=O(()=>{L61()});import{z as h1}from"zod";var Jq4,ud5,cd5,Cz8,Kq4,Yr,Wq4,Hq4,ld5;var _z8=O(()=>{Jq4=h1.enum(["claude-code","codex","decopilot-sandbox","body-offload"]),ud5=h1.array(h1.string()).catch([]).transform(($)=>$.filter((Z)=>Jq4.safeParse(Z).success)),cd5=h1.discriminatedUnion("type",[h1.object({type:h1.literal("ui-message-chunk"),chunk:h1.unknown()}),h1.object({type:h1.literal("error"),code:h1.string(),message:h1.string()}),h1.object({type:h1.literal("done")})]),Cz8=h1.object({chunks:h1.array(h1.unknown()),done:h1.boolean().nullish().transform(($)=>$??!1),error:h1.object({code:h1.string(),message:h1.string()}).nullish().transform(($)=>$??null)}),Kq4=h1.record(h1.string(),h1.unknown()),Yr=h1.object({id:h1.string(),title:h1.string().optional(),provider:h1.string().nullable().optional(),credentialId:h1.string(),limits:h1.object({contextWindow:h1.number().int().positive().optional(),maxOutputTokens:h1.number().int().positive().optional()}).optional(),capabilities:h1.object({vision:h1.boolean().optional(),text:h1.boolean().optional(),reasoning:h1.boolean().optional()}).optional()}).strict(),Wq4=h1.object({thinking:Yr.extend({title:h1.string()}),fast:Yr.optional(),smart:Yr.optional(),image:Yr.optional(),deepResearch:Yr.optional()}).strict(),Hq4=h1.discriminatedUnion("cwd",[h1.object({cwd:h1.literal("/repo"),repo:h1.object({owner:h1.string(),name:h1.string(),connectedGithub:h1.boolean()}).strict(),branch:h1.string().nullable()}).strict(),h1.object({cwd:h1.null()}).strict()]),ld5=h1.object({harnessId:h1.enum(["decopilot","claude-code","codex"]).optional(),threadId:h1.string(),userMessage:Kq4,harness:h1.object({sessionId:h1.string().optional()}).strict(),workspace:Hq4,models:Wq4,mcp:h1.object({url:h1.string().url(),headers:h1.record(h1.string(),h1.string()),expiresAt:h1.number().int().positive()}).strict(),mode:h1.enum(["default","plan","web-search","gen-image"]),temperature:h1.number(),toolApprovalLevel:h1.enum(["auto","readonly"]),toolAllowlist:h1.array(h1.string()).nullable().optional(),maxAgentSteps:h1.number().int().optional(),user:h1.object({id:h1.string(),email:h1.string()}).strict(),organizationId:h1.string(),organizationSlug:h1.string().optional(),agent:h1.object({id:h1.string(),instructions:h1.string().optional()}).strict(),triggerId:h1.string().optional(),currentThreadTitle:h1.string().optional(),traceparent:h1.string().optional(),runFenceToken:h1.string().optional(),resume:h1.object({reason:h1.string()}).strict().optional()}).strict()});function fz8($){let{providerId:Z,apiKey:X,baseUrl:Q}=$;if(Z==="anthropic")return{CLAUDE_CODE_MODEL:xz8.anthropic,ANTHROPIC_API_KEY:X,ANTHROPIC_AUTH_TOKEN:null,ANTHROPIC_BASE_URL:Q??null};if(Z==="openrouter")return{CLAUDE_CODE_MODEL:xz8.openrouter,ANTHROPIC_API_KEY:"",ANTHROPIC_AUTH_TOKEN:X,ANTHROPIC_BASE_URL:Q??"https://openrouter.ai/api"};throw new vz8(Z)}var xz8,vz8;var bz8=O(()=>{xz8={anthropic:"claude-opus-5",openrouter:"anthropic/claude-opus-5"};vz8=class vz8 extends Error{constructor($){super(`the claude-code harness needs an Anthropic or OpenRouter model credential; this run's model resolves to "${$}". Point the agent's thinking model at an Anthropic or OpenRouter key, or run it with Decopilot.`);this.name="UnsupportedClaudeCodeProviderError"}}});function Nq4($){let{publicUrl:Z,agentId:X,organization:Q,target:Y}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${X}`;if(!Q.slug)throw new gz8(Q.id);return`${Z}/api/${Q.slug}/mcp/self`}async function R30($,Z,X,Q,Y="agent-tools"){let G=Nq4({publicUrl:AQ(),agentId:Z,organization:X,target:Y}),J=await $.boundAuth.apiKey.create({name:Q,permissions:{"*":["*"]},expiresIn:yz8,metadata:{organization:{id:X.id,slug:X.slug,name:X.name}}});return{url:G,headers:{Authorization:`Bearer ${J.key}`,"x-org-id":X.id},expiresAt:Date.now()+yz8*1000}}var yz8=3600,gz8;var E61=O(()=>{XZ();gz8=class gz8 extends Error{constructor($){super(`cannot mint a management MCP endpoint for organization "${$}": the org-scoped path /api/<slug>/mcp/self needs the org slug, which was not loaded.`);this.name="MissingOrganizationSlugError"}}});import{z as Uq4}from"zod";function fz($){return $==="cluster"?"agent-sandbox":$}function z61($){return`${$.userId}:${$.projectRef}`}var Fq4;var q30=O(()=>{Fq4=Uq4.enum(["agent-sandbox","user-desktop"])});class M30{map=new Map;async run($,Z){let X=this.map.get($);if(X)return X;let Q=Z();this.map.set($,Q);try{return await Q}finally{this.map.delete($)}}}function k30($,Z,X,Q){if(!$)return Q(null);if(!$.withLock)return Q($);return $.withLock(Z,X,Q)}import{createHash as wq4}from"crypto";function Oq4($,Z=16){return wq4("sha256").update(z61($)).digest("hex").slice(0,Z)}function Wh($,Z){let X=Oq4($),Q=Lq4(Z);return Q?`${Q}-${X}`:`s-${X}`}function Lq4($){if(!$)return"";return($.split("/").pop()??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Bq4).replace(/-+$/g,"")}var Bq4=24;var hz8=O(()=>{q30()});function S30($,Z){let X=$.replace(/\/+$/,"");if(X.includes("{handle}"))return`${X.replace("{handle}",Z)}/`;try{let Q=new URL(X);return Q.hostname=`${Z}.${Q.hostname}`,`${Q.toString()}/`}catch{return`${X}/${Z}/`}}function Gr($){let Z=$?.userName?.trim();if(!Z||uz8.test(Z))return null;let X=$?.userEmail?.trim();if(!X||uz8.test(X))return{userName:Z};if(!Dq4.test(X))return{userName:Z};return{userName:Z,userEmail:X}}var uz8,Dq4;var j61=O(()=>{uz8=/[\r\n<>]/,Dq4=/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/});function P61($){let Z=$.repo,X=Z?{repository:{cloneUrl:Z.cloneUrl,repoName:Z.displayName??Eq4(Z.cloneUrl),...Z.branch?{branch:Z.branch}:{},...Z.submoduleCredentials&&Z.submoduleCredentials.length>0?{submoduleCredentials:Z.submoduleCredentials}:{}},identity:{userName:Z.userName,userEmail:Z.userEmail}}:void 0,Q=$.tenant,Y=Gr({userName:Q?.userName,userEmail:Q?.userEmail})??void 0,G=$.packageManager?{name:$.packageManager.name,...$.packageManager.path?{path:$.packageManager.path}:{}}:void 0,J=G?{packageManager:G,runtime:$.runtime,...$.port!==void 0?{port:$.port}:{}}:void 0;if(!X&&!J&&!Y&&!$.cloneOnly)return null;return{...X?{git:X}:{},...Y?{operator:Y}:{},...$.cloneOnly!==void 0?{cloneOnly:$.cloneOnly}:{},...J?{application:J}:{}}}function Eq4($){try{let Z=new URL($);return Z.pathname.replace(/^\/+/,"").replace(/\.git$/,"")||Z.hostname}catch{return $}}var cz8=O(()=>{j61()});function zq4($){try{return new URL($).username.length>0}catch{return!1}}function A61($){let Z=$.repo?.cloneUrl;if(!Z||!zq4(Z))return null;return{git:{repository:{cloneUrl:Z}}}}var T61=O(()=>{hz8();cz8()});function Jr($){if("threadId"in $){if(!$.threadId)throw Error("composeSandboxRef: threadId required");return`thread:${$.threadId}`}if(!$.orgId||!$.virtualMcpId||!$.branch)throw Error("composeSandboxRef: orgId, virtualMcpId and branch are all required for agent refs");return`agent:${$.orgId}:${$.virtualMcpId}:${$.branch}`}function jq4($){return(typeof $.timeout==="number"&&$.timeout>0?Math.min($.timeout,120000):30000)+15000}function Pq4($,Z){if($.aborted)return Z.catch(()=>{}),Promise.reject($.reason??Error("aborted"));return new Promise((X,Q)=>{let Y=()=>{Z.catch(()=>{}),Q($.reason??Error("aborted"))};$.addEventListener("abort",Y,{once:!0}),Z.then(X,Q).finally(()=>{$.removeEventListener("abort",Y)})})}async function Aq4($,Z,X,Q,Y="POST",G){let J=G?.timeoutMs??jq4(Q??{}),K=AbortSignal.timeout(J),W=G?.signal?AbortSignal.any([G.signal,K]):K,H,N;try{let F={method:Y,headers:new Headers({"content-type":"application/json"}),body:null,signal:W};if(Y!=="GET"&&Q!==null)F.body=JSON.stringify(Q);({res:H,rawText:N}=await Pq4(W,(async()=>{let w=await $.proxyDaemonRequest(Z,X,F);return{res:w,rawText:await w.text()}})()))}catch(F){if(G?.signal?.aborted)throw F;if(K.aborted)throw Error(`Sandbox ${Y} ${X} timed out after ${Math.round(J/1000)}s \u2014 the sandbox may be overloaded or its filesystem stalled. Retry, or use a smaller operation.`);throw new Kr(F)}let U;try{U=JSON.parse(N)}catch{console.error("[sandbox-fs-hooks] Failed to parse JSON response runner=%s path=%s status=%d rawText=%s",$.kind,X,H.status,N.slice(0,2000));let F=H.status>=500?" (server error)":H.status===0?" (no response)":"";throw Error(`Daemon ${X} returned invalid JSON (HTTP ${H.status}${F}): ${N.slice(0,800)}`)}if(!H.ok){console.error("[sandbox-fs-hooks] Non-OK response runner=%s path=%s status=%d body=%s",$.kind,X,H.status,N.slice(0,2000));let F=U.error??`Daemon ${X} failed (${H.status})`;if(H.status===404&&F==="sandbox not found")throw new Kr(Error(F),!0);throw Error(F)}return U}function Tq4($){let Z=[];for(let X of $.split(`
|
|
2422
|
+
</currently-enabled-tools>`}:null,$0=G?.virtualMcp.metadata,e=Z.workspace.cwd==="/repo"?{repo:Z.workspace.repo,branch:Z.workspace.branch,cwd:Z.workspace.cwd,workspaceKind:"github"}:void 0,I0=await Q({kind:G?.isSubagent?"subagent":"agent",virtualMcp:{id:Z.agent.id,repo:$0?.githubRepo??void 0,delegationTargetIds:$0?.subAgents},mcpClient:X.passthroughClient,provider:J,models:Z.models,messages:U,abortSignal:H,temperature:Z.temperature,planMode:D.isPlanMode,isDecopilot:mG(Z.agent.id)!==null,codingWorkspace:e,systemAgentInstructions:X.serverInstructions,currentThreadId:w,user:{id:Z.user.id,email:Z.user.email},userContext:G?.userContext,writer:B,prepareStep:U0,onStepFinish:Y.onStepFinish,passthroughClient:X.passthroughClient,connectionsData:{tools:X.connectionsBlockTools,connectionTitleMap:X.connectionTitleMap},toolOutputMap:X.toolOutputMap,extraTools:{...X.builtInTools,...X.connectionsBlockTools.length>0&&Z0.enable_tool?{enable_tool:Z0.enable_tool}:{}},additionalSystemMessages:[...N,...k0?[k0]:[]],activeToolNames:[...b,..."enable_tool"in Z0?["enable_tool"]:[],...y],stepLimit:Y.stepLimit??Z.maxAgentSteps}),Q0=I0.result,p0=Promise.resolve(Q0.finishReason).then(async(o0)=>{let[m1,v8,U$,Y5]=await Promise.all([Q0.totalUsage,Q0.usage,Q0.request,Q0.response]);if(await I0.error!==void 0)return;I0.span.setAttribute("decopilot.llm.inputTokens",m1.inputTokens??0),I0.span.setAttribute("decopilot.llm.outputTokens",m1.outputTokens??0),I0.span.setAttribute("decopilot.llm.finishReason",o0);let r=m.cacheTotals();I0.span.setAttribute("decopilot.cache.read_tokens",r.read),I0.span.setAttribute("decopilot.cache.write_tokens",r.write);let Y1=r.input>0?r.read/r.input:0;I0.span.setAttribute("decopilot.cache.hit_ratio",Y1);let $6=Date.now()-(E??Date.now());if(z=!0,L?.recordLlmCall({organizationId:Z.organizationId,modelId:Z.models.thinking.id,durationMs:$6,isError:!1,inputTokens:m1.inputTokens,outputTokens:m1.outputTokens,cacheReadTokens:r.read,cacheWriteTokens:r.write}),L?.monitorLlmCall({organizationId:Z.organizationId,agentId:Z.agent.id,modelId:Z.models.thinking.id,modelTitle:Z.models.thinking.title??Z.models.thinking.id,credentialId:Z.models.thinking.credentialId,taskId:w,durationMs:$6,isError:!1,finishReason:o0,usage:{inputTokens:v8.inputTokens??0,outputTokens:v8.outputTokens??0,totalTokens:v8.totalTokens??0},totalUsage:{inputTokens:m1.inputTokens??0,outputTokens:m1.outputTokens??0,totalTokens:m1.totalTokens??0},cost:m.cost(),request:U$,response:Y5,userId:Z.user.id}),H.aborted)return}).catch(async(o0)=>{let m1=o0 instanceof Error?o0:Error(WU(o0));if(console.error("[decopilot:stream] Error",m1.message),H.aborted)return;if(!z){let v8=Date.now()-(E??Date.now());z=!0,L?.recordLlmCall({organizationId:Z.organizationId,modelId:Z.models.thinking.id,durationMs:v8,isError:!0,errorType:m1.name}),L?.monitorLlmCall({organizationId:Z.organizationId,agentId:Z.agent.id,modelId:Z.models.thinking.id,modelTitle:Z.models.thinking.title??Z.models.thinking.id,credentialId:Z.models.thinking.credentialId,taskId:w,durationMs:v8,isError:!0,errorMessage:m1.message,userId:Z.user.id})}}).catch((o0)=>{console.error("[decopilot:stream] finish metrics failed",o0)}),r0=I0.error.then(async(o0)=>{if(!H.aborted||z)return null;let m1=await Q0.steps;if(!m1.length||z)return null;z=!0;let v8=Date.now()-(E??Date.now()),U$=m1.reduce((Y1,$6)=>({inputTokens:Y1.inputTokens+($6.usage.inputTokens??0),outputTokens:Y1.outputTokens+($6.usage.outputTokens??0),totalTokens:Y1.totalTokens+($6.usage.totalTokens??0)}),{inputTokens:0,outputTokens:0,totalTokens:0}),Y5=m1[m1.length-1].usage,o5=m.cacheTotals();if(L?.recordLlmCall({organizationId:Z.organizationId,modelId:Z.models.thinking.id,durationMs:v8,isError:!1,inputTokens:U$.inputTokens,outputTokens:U$.outputTokens,cacheReadTokens:o5.read,cacheWriteTokens:o5.write}),L?.monitorLlmCall({organizationId:Z.organizationId,agentId:Z.agent.id,modelId:Z.models.thinking.id,modelTitle:Z.models.thinking.title??Z.models.thinking.id,credentialId:Z.models.thinking.credentialId,taskId:w,durationMs:v8,isError:!1,finishReason:"abort",usage:{inputTokens:Y5.inputTokens??0,outputTokens:Y5.outputTokens??0,totalTokens:Y5.totalTokens??0},totalUsage:U$,cost:m.cost(),request:void 0,response:void 0,userId:Z.user.id}),U$.totalTokens<=0)return null;let r=m.cost();return{type:"message-metadata",messageMetadata:{usage:{inputTokens:U$.inputTokens,outputTokens:U$.outputTokens,totalTokens:U$.totalTokens,cachedInputTokens:o5.read,inputTokenDetails:{cacheReadTokens:o5.read,cacheWriteTokens:o5.write,noCacheTokens:U$.inputTokens-o5.read-o5.write},...r>0&&{providerMetadata:{openrouter:{usage:{cost:r}}}}}}}}).then((o0)=>o0).catch((o0)=>{return console.error("[decopilot:stream] abort metadata failed",o0),null}),S0=Q0.toUIMessageStream({originalMessages:F,generateMessageId:_p,onError:(o0)=>Jz8(o0),messageMetadata:({part:o0})=>{if(o0.type==="start")return{agent:{id:Z.agent.id??null},models:{credentialId:Z.models.thinking.credentialId,thinking:{...Z.models.thinking,title:Z.models.thinking.title??Z.models.thinking.id,provider:Z.models.thinking.provider??void 0}},created_at:new Date,_request:{systemSections:I0.assembledSystemMessages.map((m1)=>({chars:m1.content.length,preview:m1.content.slice(0,80).replace(/\s+/g," ")})),tools:Object.keys(Z0).length,activeTools:b.length+("enable_tool"in Z0?1:0)+y.size},thread_id:w,...G?.subtaskJobId?{subtaskJobId:G.subtaskJobId}:{},...G?.resumedFromBackground?{resumedFromBackground:!0}:{}};if(o0.type==="reasoning-start"){if(C===null)C=new Date;return{reasoning_start_at:C}}if(o0.type==="reasoning-end")return{reasoning_end_at:new Date};if(o0.type==="finish-step")return m.addStep(o0.usage,o0.providerMetadata),{usage:m.buildStepUsage()};if(o0.type==="finish"){let m1=m.buildFinalUsage({totalUsage:o0.totalUsage,providerKey:Z.models.thinking.provider,fallbackProviderMetadata:o0.providerMetadata});return m1?{usage:m1}:{}}return}})[Symbol.asyncIterator](),C0=Y.sideChunks?.[Symbol.asyncIterator](),q0=!1,X0=S===null,W0=!1,h0=!1,w0=!1,j0=C0===void 0,H1=!1,o=S0.next().then((o0)=>({kind:"main",value:o0})),A0=j.next().then((o0)=>({kind:"queue",value:o0})),v0=C0?C0.next().then((o0)=>({kind:"side",value:o0})):null,F1=M.then((o0)=>({kind:"title",value:o0})),f1=p0.then(()=>({kind:"finish-metrics"})),d8=r0.then((o0)=>({kind:"abort-metadata",value:o0}));try{while(!q0||!X0||!W0||!h0||!w0||!j0){if(q0&&X0&&W0&&h0&&!H1)Y.closeSideChunks?.(),j.close(),H1=!0;let o0=[];if(!w0)o0.push(A0);if(!q0)o0.push(o);if(!X0)o0.push(F1);if(!W0)o0.push(f1);if(!h0)o0.push(d8);if(!j0&&v0)o0.push(v0);let m1=await Promise.race(o0);if(m1.kind==="main"){if(m1.value.done){if(q0=!0,!X0)S?.finish();continue}yield m1.value.value,o=S0.next().then((v8)=>({kind:"main",value:v8}))}else if(m1.kind==="title"){if(X0=!0,m1.value)yield m1.value}else if(m1.kind==="finish-metrics")W0=!0;else if(m1.kind==="abort-metadata"){if(h0=!0,m1.value)yield m1.value}else if(m1.kind==="side"){if(m1.value.done){j0=!0;continue}yield m1.value.value,v0=C0?.next().then((v8)=>({kind:"side",value:v8}))??null}else{if(m1.value.done){w0=!0;continue}yield m1.value.value,A0=j.next().then((v8)=>({kind:"queue",value:v8}))}}}finally{if(!X0)S?.finish();Y.closeSideChunks?.(),await S0.return?.().catch(()=>{}),await C0?.return?.().catch(()=>{}),j.close()}}var zz8=O(()=>{aE8();G61();wa0();K61();Qz8();N61();Bz8();I6()});function jz8($){return $.type==="tool-call"&&$.toolName==="todo_write"&&typeof $.toolCallId==="string"}function Zq4($){return $.type==="tool-result"&&$.toolName==="todo_write"&&typeof $.toolCallId==="string"}function Pz8($){let Z=null;for(let Q=$.length-1;Q>=0&&Z===null;Q--){let G=$[Q].content;if(!Array.isArray(G))continue;for(let J=G.length-1;J>=0;J--){let K=G[J];if(jz8(K)){Z=K.toolCallId;break}}}if(Z===null)return $;let X=Z;return $.map((Q)=>{let Y=Q.content;if(!Array.isArray(Y))return Q;let G=Y.filter((J)=>{if(jz8(J))return J.toolCallId===X;if(Zq4(J))return J.toolCallId===X;return!0});if(G.length===Y.length)return Q;return{...Q,content:G}})}function Az8($){let Z=!1,X=$.map((Q)=>{if(Q.role!=="assistant")return Q;if(!Q.parts.some((G)=>("state"in G)&&G.state==="approval-requested"))return Q;return Z=!0,{...Q,parts:Q.parts.map((G)=>{if(!("state"in G)||G.state!=="approval-requested"||!("approval"in G)||!G.approval)return G;return{...G,state:"output-denied",approval:{...G.approval,approved:!1,reason:"User sent a new message without approving this tool call."}}})}});return Z?X:$}function Xq4($){let[Z,X]=$.reduce((Q,Y)=>{if(Y.role==="system")Q[0].push(Y);else Q[1].push(Y);return Q},[[],[]]);return{systemMessages:Z,messages:X}}async function U61($,Z){let X=$.filter((U)=>U.role!=="assistant"||U.parts&&U.parts.length>0),Q=await Xr({messages:X}),Y=Az8(Q),G=await Zr(Y,{tools:Z.tools,ignoreIncompleteToolCalls:!0}),{systemMessages:J,messages:K}=Xq4(G),W=Pz8(K),N=$61({messages:W,reasoning:"all",emptyMessages:"remove",toolCalls:"none"}).map((U)=>{if(U.role!=="assistant")return U;let F=Array.isArray(U.content)?U.content.filter((w)=>w.type!=="reasoning"&&w.type!=="thinking"&&w.type!=="redacted-reasoning").map((w)=>{let B=w;if("providerOptions"in B||"providerMetadata"in B){let{providerOptions:L,providerMetadata:D,...E}=B;if(B.type==="tool-call"){let z=D?.google,j=L?.google;return{...E,...z?{providerMetadata:{google:z}}:{},...j?{providerOptions:{google:j}}:{}}}return E}return w}):U.content;return{...U,content:Array.isArray(F)&&F.length===0?[{type:"text",text:""}]:F,providerOptions:void 0,providerMetadata:void 0}});return{systemMessages:J,messages:N,originalMessages:Q}}var F61=O(()=>{u4()});function Tz8($){if($<1)throw Error("Semaphore cap must be >= 1");let Z=$,X=[];function Q(Y){return Y.reason??Error("Semaphore acquire aborted")}return{acquire(Y){if(Y?.aborted)return Promise.reject(Q(Y));if(Z>0)return Z-=1,Promise.resolve();return new Promise((G,J)=>{let K={resolve:G,reject:J,cleanup:()=>{}},W=()=>{let H=X.indexOf(K);if(H!==-1)X.splice(H,1);K.cleanup(),J(Q(Y))};if(Y)Y.addEventListener("abort",W,{once:!0}),K.cleanup=()=>Y.removeEventListener("abort",W);X.push(K)})},release(){let Y=X.shift();if(Y){Y.cleanup(),Y.resolve();return}if(Z+=1,Z>$)Z=$},available(){return Z}}}function w61($,Z){Iz8.set($,Z)}function B61($){return Iz8.get($)}function Jh($){let Z=B61($);if(!Z)throw Error("Decopilot requires process-local run context. Dispatch must attach DecopilotRunContext before invoking the Decopilot harness.");return Z}var Iz8;var Kh=O(()=>{Iz8=new WeakMap});function Rz8($,Z){let X=$.modelSources?.thinking??null;if(!X||X.kind!=="secret")throw Error("Decopilot core requires a secret thinking model source. Dispatch must resolve the selected model credential before invoking Decopilot.");let Q=Z(X),Y=(N)=>{let U=$.models[N];if(!U)return;let F=$.modelSources?.[N];if(F&&F.kind!=="secret")throw Error("Decopilot core requires secret modelSources for all resolved slots.");return{model:U,provider:F&&F.kind==="secret"?Z(F):Q}},G=Y("fast"),J=Y("smart"),K=Y("image"),W=Y("webSearch"),H=Y("deepResearch");return{thinking:{model:$.models.thinking,provider:Q},...G?{fast:G}:{},...J?{smart:J}:{},...K?{image:K}:{},...W?{webSearch:W}:{},...H?{deepResearch:H}:{}}}async function*qz8($){let{input:Z,modelRuntime:X,toolRuntime:Q,telemetry:Y}=$,G=B61(Z),J=$.kind==="subtask",K=A30(),W=J?void 0:(D)=>K.addExternal(D),H=await Q.buildEnvironmentTools({input:Z,onChildUsage:W});if(J)Yq4(H);let{systemMessages:N,messages:U,originalMessages:F}=await U61(G?.messages??[Z.userMessage],{windowSize:X3,models:Z.models,tools:H.tools}),w=U,B=Z.models.fast??Z.models.smart??Z.models.thinking,L=(Z.models.fast?X.fast?.provider:void 0)??(Z.models.smart?X.smart?.provider:void 0)??X.thinking.provider;yield*Ez8({input:Z,tools:H,runEngine:Q.runEngine,extras:{provider:X.thinking.provider,titleProvider:L,titleModel:B,registrySignal:Z.signal??new AbortController().signal,processedSystemMessages:N,processedMessages:w,originalMessages:F,threadId:Z.threadId,currentThreadTitle:Z.currentThreadTitle??"",pendingImages:H.pendingImages,writer:H.writer,sideChunks:H.sideChunks,closeSideChunks:H.closeSideChunks,onStepFinish:H.onStepFinish,telemetry:Y,kind:$.kind,stepLimit:J?hN:void 0,usageAccumulator:K,runContext:G}})}function Yq4($){if("subtask"in $.tools){let{subtask:Z,...X}=$.tools;$.tools=X}if("subtask"in $.builtInTools){let{subtask:Z,...X}=$.builtInTools;$.builtInTools=X}}var Qq4=4,Vd5;var Mz8=O(()=>{zz8();F61();hE();G61();Kh();Vd5=Tz8(Qq4)});function Gq4($){return"storage"in $}function kz8($){O61=$}var O61,Sz8;var L61=O(()=>{J81();Mz8();Kh();Sz8={id:"decopilot",create($){return{id:"decopilot",async*stream(Z){let X=Jh(Z),Q=Rz8({models:Z.models,modelSources:X.modelSources},aG0),Y=sG0(),G={};if(!Gq4($))throw Error("[decopilot] a hosted Studio context is required");if(!O61)throw Error("[decopilot] cluster environment builder not registered \u2014 "+"apps/api/src/harnesses must be imported before dispatching the decopilot harness in cluster mode");let J=O61({ctx:$,modelRuntime:Q,sideChannel:Y,cleanup:G});try{yield*qz8({input:Z,modelRuntime:Q,toolRuntime:J.toolRuntime,telemetry:J.telemetry,kind:"main"})}finally{Y.close(),await G.close?.().catch(()=>{})}}}}}});class D61{ctx;harnessId;constructor($){this.ctx=$.ctx,this.harnessId=$.harnessId}dispatch($){if(this.harnessId!=="decopilot")throw Error(`InProcessSandboxClient runs cluster-hosted decopilot only; got "${this.harnessId}" \u2014 CLI harnesses run in the desktop app or are `+"rejected at the gate");return Sz8.create(this.ctx).stream($)}}var Vz8=O(()=>{L61()});import{z as h1}from"zod";var Jq4,ud5,cd5,Cz8,Kq4,Yr,Wq4,Hq4,ld5;var _z8=O(()=>{Jq4=h1.enum(["claude-code","codex","decopilot-sandbox","body-offload"]),ud5=h1.array(h1.string()).catch([]).transform(($)=>$.filter((Z)=>Jq4.safeParse(Z).success)),cd5=h1.discriminatedUnion("type",[h1.object({type:h1.literal("ui-message-chunk"),chunk:h1.unknown()}),h1.object({type:h1.literal("error"),code:h1.string(),message:h1.string()}),h1.object({type:h1.literal("done")})]),Cz8=h1.object({chunks:h1.array(h1.unknown()),done:h1.boolean().nullish().transform(($)=>$??!1),error:h1.object({code:h1.string(),message:h1.string()}).nullish().transform(($)=>$??null)}),Kq4=h1.record(h1.string(),h1.unknown()),Yr=h1.object({id:h1.string(),title:h1.string().optional(),provider:h1.string().nullable().optional(),credentialId:h1.string(),limits:h1.object({contextWindow:h1.number().int().positive().optional(),maxOutputTokens:h1.number().int().positive().optional()}).optional(),capabilities:h1.object({vision:h1.boolean().optional(),text:h1.boolean().optional(),reasoning:h1.boolean().optional()}).optional()}).strict(),Wq4=h1.object({thinking:Yr.extend({title:h1.string()}),fast:Yr.optional(),smart:Yr.optional(),image:Yr.optional(),deepResearch:Yr.optional()}).strict(),Hq4=h1.discriminatedUnion("cwd",[h1.object({cwd:h1.literal("/repo"),repo:h1.object({owner:h1.string(),name:h1.string(),connectedGithub:h1.boolean()}).strict(),branch:h1.string().nullable()}).strict(),h1.object({cwd:h1.null()}).strict()]),ld5=h1.object({harnessId:h1.enum(["decopilot","claude-code","codex"]).optional(),threadId:h1.string(),userMessage:Kq4,harness:h1.object({sessionId:h1.string().optional()}).strict(),workspace:Hq4,models:Wq4,mcp:h1.object({url:h1.string().url(),headers:h1.record(h1.string(),h1.string()),expiresAt:h1.number().int().positive()}).strict(),mode:h1.enum(["default","plan","web-search","gen-image"]),temperature:h1.number(),toolApprovalLevel:h1.enum(["auto","readonly"]),toolAllowlist:h1.array(h1.string()).nullable().optional(),maxAgentSteps:h1.number().int().optional(),user:h1.object({id:h1.string(),email:h1.string()}).strict(),organizationId:h1.string(),organizationSlug:h1.string().optional(),agent:h1.object({id:h1.string(),instructions:h1.string().optional()}).strict(),triggerId:h1.string().optional(),currentThreadTitle:h1.string().optional(),traceparent:h1.string().optional(),runFenceToken:h1.string().optional(),resume:h1.object({reason:h1.string()}).strict().optional()}).strict()});function fz8($){let{providerId:Z,apiKey:X,baseUrl:Q}=$;if(Z==="anthropic")return{CLAUDE_CODE_MODEL:xz8.anthropic,ANTHROPIC_API_KEY:X,ANTHROPIC_AUTH_TOKEN:null,ANTHROPIC_BASE_URL:Q??null};if(Z==="openrouter"||Z==="deco")return{CLAUDE_CODE_MODEL:xz8.openrouter,ANTHROPIC_API_KEY:"",ANTHROPIC_AUTH_TOKEN:X,ANTHROPIC_BASE_URL:Q??"https://openrouter.ai/api"};throw new vz8(Z)}var xz8,vz8;var bz8=O(()=>{xz8={anthropic:"claude-opus-5",openrouter:"anthropic/claude-opus-5"};vz8=class vz8 extends Error{constructor($){super(`the claude-code harness needs an Anthropic, OpenRouter or Deco model credential; this run's model resolves to "${$}". Point the agent's thinking model at one of those, or run it with Decopilot.`);this.name="UnsupportedClaudeCodeProviderError"}}});function Nq4($){let{publicUrl:Z,agentId:X,organization:Q,target:Y}=$;if(Y==="agent-tools")return`${Z}/mcp/virtual-mcp/${X}`;if(!Q.slug)throw new gz8(Q.id);return`${Z}/api/${Q.slug}/mcp/self`}async function R30($,Z,X,Q,Y="agent-tools"){let G=Nq4({publicUrl:AQ(),agentId:Z,organization:X,target:Y}),J=await $.boundAuth.apiKey.create({name:Q,permissions:{"*":["*"]},expiresIn:yz8,metadata:{organization:{id:X.id,slug:X.slug,name:X.name}}});return{url:G,headers:{Authorization:`Bearer ${J.key}`,"x-org-id":X.id},expiresAt:Date.now()+yz8*1000}}var yz8=3600,gz8;var E61=O(()=>{XZ();gz8=class gz8 extends Error{constructor($){super(`cannot mint a management MCP endpoint for organization "${$}": the org-scoped path /api/<slug>/mcp/self needs the org slug, which was not loaded.`);this.name="MissingOrganizationSlugError"}}});import{z as Uq4}from"zod";function fz($){return $==="cluster"?"agent-sandbox":$}function z61($){return`${$.userId}:${$.projectRef}`}var Fq4;var q30=O(()=>{Fq4=Uq4.enum(["agent-sandbox","user-desktop"])});class M30{map=new Map;async run($,Z){let X=this.map.get($);if(X)return X;let Q=Z();this.map.set($,Q);try{return await Q}finally{this.map.delete($)}}}function k30($,Z,X,Q){if(!$)return Q(null);if(!$.withLock)return Q($);return $.withLock(Z,X,Q)}import{createHash as wq4}from"crypto";function Oq4($,Z=16){return wq4("sha256").update(z61($)).digest("hex").slice(0,Z)}function Wh($,Z){let X=Oq4($),Q=Lq4(Z);return Q?`${Q}-${X}`:`s-${X}`}function Lq4($){if(!$)return"";return($.split("/").pop()??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Bq4).replace(/-+$/g,"")}var Bq4=24;var hz8=O(()=>{q30()});function S30($,Z){let X=$.replace(/\/+$/,"");if(X.includes("{handle}"))return`${X.replace("{handle}",Z)}/`;try{let Q=new URL(X);return Q.hostname=`${Z}.${Q.hostname}`,`${Q.toString()}/`}catch{return`${X}/${Z}/`}}function Gr($){let Z=$?.userName?.trim();if(!Z||uz8.test(Z))return null;let X=$?.userEmail?.trim();if(!X||uz8.test(X))return{userName:Z};if(!Dq4.test(X))return{userName:Z};return{userName:Z,userEmail:X}}var uz8,Dq4;var j61=O(()=>{uz8=/[\r\n<>]/,Dq4=/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/});function P61($){let Z=$.repo,X=Z?{repository:{cloneUrl:Z.cloneUrl,repoName:Z.displayName??Eq4(Z.cloneUrl),...Z.branch?{branch:Z.branch}:{},...Z.submoduleCredentials&&Z.submoduleCredentials.length>0?{submoduleCredentials:Z.submoduleCredentials}:{}},identity:{userName:Z.userName,userEmail:Z.userEmail}}:void 0,Q=$.tenant,Y=Gr({userName:Q?.userName,userEmail:Q?.userEmail})??void 0,G=$.packageManager?{name:$.packageManager.name,...$.packageManager.path?{path:$.packageManager.path}:{}}:void 0,J=G?{packageManager:G,runtime:$.runtime,...$.port!==void 0?{port:$.port}:{}}:void 0;if(!X&&!J&&!Y&&!$.cloneOnly)return null;return{...X?{git:X}:{},...Y?{operator:Y}:{},...$.cloneOnly!==void 0?{cloneOnly:$.cloneOnly}:{},...J?{application:J}:{}}}function Eq4($){try{let Z=new URL($);return Z.pathname.replace(/^\/+/,"").replace(/\.git$/,"")||Z.hostname}catch{return $}}var cz8=O(()=>{j61()});function zq4($){try{return new URL($).username.length>0}catch{return!1}}function A61($){let Z=$.repo?.cloneUrl;if(!Z||!zq4(Z))return null;return{git:{repository:{cloneUrl:Z}}}}var T61=O(()=>{hz8();cz8()});function Jr($){if("threadId"in $){if(!$.threadId)throw Error("composeSandboxRef: threadId required");return`thread:${$.threadId}`}if(!$.orgId||!$.virtualMcpId||!$.branch)throw Error("composeSandboxRef: orgId, virtualMcpId and branch are all required for agent refs");return`agent:${$.orgId}:${$.virtualMcpId}:${$.branch}`}function jq4($){return(typeof $.timeout==="number"&&$.timeout>0?Math.min($.timeout,120000):30000)+15000}function Pq4($,Z){if($.aborted)return Z.catch(()=>{}),Promise.reject($.reason??Error("aborted"));return new Promise((X,Q)=>{let Y=()=>{Z.catch(()=>{}),Q($.reason??Error("aborted"))};$.addEventListener("abort",Y,{once:!0}),Z.then(X,Q).finally(()=>{$.removeEventListener("abort",Y)})})}async function Aq4($,Z,X,Q,Y="POST",G){let J=G?.timeoutMs??jq4(Q??{}),K=AbortSignal.timeout(J),W=G?.signal?AbortSignal.any([G.signal,K]):K,H,N;try{let F={method:Y,headers:new Headers({"content-type":"application/json"}),body:null,signal:W};if(Y!=="GET"&&Q!==null)F.body=JSON.stringify(Q);({res:H,rawText:N}=await Pq4(W,(async()=>{let w=await $.proxyDaemonRequest(Z,X,F);return{res:w,rawText:await w.text()}})()))}catch(F){if(G?.signal?.aborted)throw F;if(K.aborted)throw Error(`Sandbox ${Y} ${X} timed out after ${Math.round(J/1000)}s \u2014 the sandbox may be overloaded or its filesystem stalled. Retry, or use a smaller operation.`);throw new Kr(F)}let U;try{U=JSON.parse(N)}catch{console.error("[sandbox-fs-hooks] Failed to parse JSON response runner=%s path=%s status=%d rawText=%s",$.kind,X,H.status,N.slice(0,2000));let F=H.status>=500?" (server error)":H.status===0?" (no response)":"";throw Error(`Daemon ${X} returned invalid JSON (HTTP ${H.status}${F}): ${N.slice(0,800)}`)}if(!H.ok){console.error("[sandbox-fs-hooks] Non-OK response runner=%s path=%s status=%d body=%s",$.kind,X,H.status,N.slice(0,2000));let F=U.error??`Daemon ${X} failed (${H.status})`;if(H.status===404&&F==="sandbox not found")throw new Kr(Error(F),!0);throw Error(F)}return U}function Tq4($){let Z=[];for(let X of $.split(`
|
|
2423
2423
|
`)){if(!X)continue;let Q=X.indexOf(":");if(Q<0)continue;let Y=X.indexOf(":",Q+1);if(Y<0)continue;let G=X.slice(0,Q),J=Number.parseInt(X.slice(Q+1,Y),10);if(!Number.isFinite(J))continue;Z.push({file:G,line:J,text:X.slice(Y+1)})}return Z}function I61($,Z){let{ensureHandle:X,invalidateHandle:Q,canAutoRestart:Y}=Z,G=(K)=>{let W=K instanceof Error?K.message:String(K);return Y?`Sandbox is unreachable and auto-restart did not recover it: ${W}`:"The sandbox is not running. Ask the user to start it by clicking the server button (left side of the header bar)."},J=async(K,W,H="POST",N)=>{let U=async(w)=>Aq4($,w,K,W,H,{signal:N,timeoutMs:Z.opTimeoutMs}),F=await X();try{return await U(F)}catch(w){if(!(w instanceof Kr))throw w;if(!Y&&!w.gone)throw Error(G(w.cause??w));console.warn(`[sandbox-fs-hooks] daemon ${K} unreachable \u2014 reaping sandbox and retrying once`,w.cause??w);try{await Q({force:w.gone})}catch(L){console.warn("[sandbox-fs-hooks] invalidateHandle failed",L)}let B;try{B=await X()}catch(L){throw Error(`Failed to restart sandbox: ${L instanceof Error?L.message:String(L)}`)}try{return await U(B)}catch(L){if(L instanceof Kr)throw Error(G(L.cause??L));throw L}}};return{onProxy:(K,W,H,N)=>J(K,W,H,N),onRead:async(K)=>{return(await J("/_sandbox/read",{path:K})).content},onWrite:async(K,W)=>{await J("/_sandbox/write",{path:K,content:W})},onEdit:async(K,W)=>{for(let H of W)await J("/_sandbox/edit",{path:K,old_string:H.oldText,new_string:H.newText,replace_all:H.replaceAll===!0})},onBash:async(K,W)=>{return await J("/_sandbox/bash",{command:K,...W?.cwd!==void 0?{cwd:W.cwd}:{},...W?.timeoutMs!==void 0?{timeout:W.timeoutMs}:{}})},onGlob:async(K)=>{return(await J("/_sandbox/glob",{pattern:K})).files},onGrep:async(K,W)=>{let H=await J("/_sandbox/grep",{pattern:K,output_mode:"content",...W?.path!==void 0?{path:W.path}:{},...W?.glob!==void 0?{glob:W.glob}:{},...W?.caseInsensitive?{ignore_case:!0}:{}});return Tq4(H.results)}}}var Kr;var lz8=O(()=>{Kr=class Kr extends Error{code="DAEMON_UNREACHABLE";gone;constructor($,Z=!1){super($ instanceof Error?$.message:"Daemon proxy failed");if(this.gone=Z,$ instanceof Error)this.cause=$}}});function Iq4($){return $==="agent-sandbox"||$==="cluster"||$==="user-desktop"}function bz(){let $=process.env.STUDIO_SANDBOX_PROVIDER,Z=$&&$.length>0?$:"user-desktop";if(!Iq4(Z))throw Error(`Unknown STUDIO_SANDBOX_PROVIDER="${$}" \u2014 expected "agent-sandbox", "cluster", or "user-desktop".`);return fz(Z)}var HU=O(()=>{q30();q30();T61();lz8()});function d5($){if(!$||typeof $!=="object")return{};let Z=$.sandboxMap;if(!Z||typeof Z!=="object")return{};return Z}function sB($,Z,X,Q){let Y=$[Z]?.[X];if(!Y)return null;return UJ(Y)[Q]??null}function Wr($,Z,X,Q,Y){let G=UJ($[Z]?.[X]);return{...$,[Z]:{...$[Z]??{},[X]:{...G,[Q]:Y}}}}async function dz8($,Z,X,Q,Y,G,J){let K=await $.findById(Z);if(!K)return;let W=K.metadata??{},H=Wr(d5(W),Q,Y,G,J);await $.update(Z,X,{metadata:{...W,sandboxMap:H}})}function R61($,Z,X,Q){let Y=UJ($[Z]?.[X]);if(!Y[Q])return null;let G={...Y};delete G[Q];let J={...$[Z]??{}};if(Object.keys(G).length===0)delete J[X];else J[X]=G;let K={...$};if(Object.keys(J).length===0)delete K[Z];else K[Z]=J;return K}async function eB($,Z,X,Q,Y,G){let J=await $.findById(Z);if(!J)return;let K=J.metadata??{},W=R61(d5(K),Q,Y,G);if(!W)return;await $.update(Z,X,{metadata:{...K,sandboxMap:W}})}var QG=O(()=>{I6()});import{createHash as Rq4}from"crypto";import{sql as V30}from"kysely";function qq4($,Z){return Rq4("sha256").update($.userId).update("\x00").update($.projectRef).update("\x00").update(Z).digest().readBigInt64BE(0)}async function iz8($,Z,X){let Q=await $.selectFrom("sandbox_runner_state").select(["handle","state","updated_at"]).where("user_id","=",Z.userId).where("project_ref","=",Z.projectRef).where("sandbox_provider_kind","=",X).executeTakeFirst();if(!Q)return null;return{handle:Q.handle,state:Q.state,updatedAt:Q.updated_at}}async function nz8($,Z,X){let Q=await $.selectFrom("sandbox_runner_state").select(["user_id","project_ref","handle","state","updated_at"]).where("sandbox_provider_kind","=",Z).where("handle","=",X).executeTakeFirst();if(!Q)return null;return{id:{userId:Q.user_id,projectRef:Q.project_ref},handle:Q.handle,state:Q.state,updatedAt:Q.updated_at}}async function pz8($,Z,X,Q){let Y=JSON.stringify(Q.state),G=new Date().toISOString();await $.insertInto("sandbox_runner_state").values({user_id:Z.userId,project_ref:Z.projectRef,sandbox_provider_kind:X,handle:Q.handle,state:Y,updated_at:G}).onConflict((J)=>J.columns(["user_id","project_ref","sandbox_provider_kind"]).doUpdateSet({handle:Q.handle,state:Y,updated_at:G})).execute()}async function tz8($,Z,X){await $.deleteFrom("sandbox_runner_state").where("user_id","=",Z.userId).where("project_ref","=",Z.projectRef).where("sandbox_provider_kind","=",X).execute()}async function oz8($,Z,X){await $.deleteFrom("sandbox_runner_state").where("sandbox_provider_kind","=",Z).where("handle","=",X).execute()}function Mq4($){return{get:(Z,X)=>iz8($,Z,X),getByHandle:(Z,X)=>nz8($,Z,X),put:(Z,X,Q)=>pz8($,Z,X,Q),delete:(Z,X)=>tz8($,Z,X),deleteByHandle:(Z,X)=>oz8($,Z,X)}}class Hr{db;constructor($){this.db=$}get($,Z){return iz8(this.db,$,Z)}getByHandle($,Z){return nz8(this.db,$,Z)}put($,Z,X){return pz8(this.db,$,Z,X)}delete($,Z){return tz8(this.db,$,Z)}deleteByHandle($,Z){return oz8(this.db,$,Z)}async withLock($,Z,X){let Q=qq4($,Z);return this.db.transaction().execute(async(Y)=>{try{await V30`set local statement_timeout = ${V30.lit(mz8)}`.execute(Y),await V30`select pg_advisory_xact_lock(${Q}::bigint)`.execute(Y)}catch(G){if(kq4(G))throw Error(`sandbox advisory lock busy >${mz8}ms for user=${$.userId} projectRef=${$.projectRef} kind=${Z} \u2014 provisioner is slow or stuck; retry shortly`);throw G}return await V30`set local statement_timeout = 0`.execute(Y),X(Mq4(Y))})}}function kq4($){if(!($ instanceof Error))return!1;return $.code==="57014"||/statement timeout/i.test($.message)}var mz8=90000;var q61=()=>{};function az8($,Z){return`${$}::${Z}`}var rz8;var sz8=O(()=>{rz8={githubNotAuthenticated:"GITHUB_NOT_AUTHENTICATED"}});function ez8($,Z){return{cloneUrl:`https://github.com/${$}/${Z}.git`,gitUserName:"Deco Studio",gitUserEmail:"studio@deco.cx"}}async function C30($){let Z=await $.ctx.storage.connections.findById($.connectionId,$.organizationId),X=Z?eX(Z):null;if(!Z||!X?.sourceConnectionId)return;try{await NG0($.ctx,Z,{forceRefresh:$.forceRefresh})}catch(Q){$.onLegacyMintError?.(Q)}}async function Hh($,Z,X,Q,Y,G){let J=new M5(Q,Y),K=await rN({connectionId:$,tokenStorage:J,bufferMs:G?.bufferMs});if(!K.accessToken)throw Error(az8(rz8.githubNotAuthenticated,K.state==="refresh_failed"?NX:"No GitHub token found. Ensure the mcp-github connection is authenticated."));let W=K.accessToken,H=`https://x-access-token:${W}@github.com/${Z}/${X}.git`,N="Deco Studio",U="studio@deco.cx";try{let F=await fetch("https://api.github.com/user",{headers:{Authorization:`token ${W}`,Accept:"application/vnd.github+json"}});if(F.ok){let w=await F.json();N=w.name||w.login,U=w.email||`${w.login}@users.noreply.github.com`}}catch{}return{cloneUrl:H,gitUserName:N,gitUserEmail:U}}var _30=O(()=>{V01();iJ();fB();_W();sz8()});function $j8($){try{let[Z,X]=new URL($).pathname.replace(/^\//,"").split("/"),Q=X?.replace(/\.git$/,"");return Z&&Q?{owner:Z,name:Q}:null}catch{return null}}function Lj8($){return typeof $>"u"||$===null}function Sq4($){return typeof $==="object"&&$!==null}function Vq4($){if(Array.isArray($))return $;else if(Lj8($))return[];return[$]}function Cq4($,Z){var X,Q,Y,G;if(Z){G=Object.keys(Z);for(X=0,Q=G.length;X<Q;X+=1)Y=G[X],$[Y]=Z[Y]}return $}function _q4($,Z){var X="",Q;for(Q=0;Q<Z;Q+=1)X+=$;return X}function xq4($){return $===0&&Number.NEGATIVE_INFINITY===1/$}function Dj8($,Z){var X="",Q=$.reason||"(unknown reason)";if(!$.mark)return Q;if($.mark.name)X+='in "'+$.mark.name+'" ';if(X+="("+($.mark.line+1)+":"+($.mark.column+1)+")",!Z&&$.mark.snippet)X+=`
|
|
2424
2424
|
|
|
2425
2425
|
`+$.mark.snippet;return Q+" "+X}function Ur($,Z){if(Error.call(this),this.name="YAMLException",this.reason=$,this.mark=Z,this.message=Dj8(this,!1),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else this.stack=Error().stack||""}function M61($,Z,X,Q,Y){var G="",J="",K=Math.floor(Y/2)-1;if(Q-Z>K)G=" ... ",Z=Q-K+G.length;if(X-Q>K)J=" ...",X=Q+K-J.length;return{str:G+$.slice(Z,X).replace(/\t/g,"\u2192")+J,pos:Q-Z+G.length}}function k61($,Z){return EZ.repeat(" ",Z-$.length)+$}function uq4($,Z){if(Z=Object.create(Z||null),!$.buffer)return null;if(!Z.maxLength)Z.maxLength=79;if(typeof Z.indent!=="number")Z.indent=1;if(typeof Z.linesBefore!=="number")Z.linesBefore=3;if(typeof Z.linesAfter!=="number")Z.linesAfter=2;var X=/\r?\n|\r|\0/g,Q=[0],Y=[],G,J=-1;while(G=X.exec($.buffer))if(Y.push(G.index),Q.push(G.index+G[0].length),$.position<=G.index&&J<0)J=Q.length-2;if(J<0)J=Q.length-1;var K="",W,H,N=Math.min($.line+Z.linesAfter,Y.length).toString().length,U=Z.maxLength-(Z.indent+N+3);for(W=1;W<=Z.linesBefore;W++){if(J-W<0)break;H=M61($.buffer,Q[J-W],Y[J-W],$.position-(Q[J]-Q[J-W]),U),K=EZ.repeat(" ",Z.indent)+k61(($.line-W+1).toString(),N)+" | "+H.str+`
|
|
@@ -2744,7 +2744,7 @@ ${Z}
|
|
|
2744
2744
|
|
|
2745
2745
|
Use this to continue with the user's request \u2014 do NOT call subtask again for this.`:`The background subtask you started completed but produced no usable output${X==="length"?" (it hit its step limit)":""}. Continue with the user's request without calling subtask again for this.`;return{models:Q,reactionNudge:G}}}};jO.registerWorkflow(Nh4,{name:"backgroundToolWorkflow"})});async function Uh4($,Z,X){let Q=await xh({kind:X.kind,ctx:$,organization:Z,virtualMcp:X.virtualMcp,mcpClient:X.mcpClient,provider:X.provider,models:X.models,messages:X.messages,abortSignal:X.abortSignal,temperature:X.temperature,planMode:X.planMode,isDecopilot:X.isDecopilot,systemAgentInstructions:X.systemAgentInstructions,currentThreadId:X.currentThreadId,user:X.user,userContext:X.userContext,codingWorkspace:X.codingWorkspace,writer:X.writer,subtaskParams:{provider:X.provider,organization:Z,models:X.models,codingWorkspace:X.codingWorkspace},prepareStep:X.prepareStep,onStepFinish:X.onStepFinish,passthroughClient:X.passthroughClient,connectionsData:X.connectionsData,extraTools:X.extraTools,toolOutputMap:X.toolOutputMap,additionalSystemMessages:X.additionalSystemMessages,activeToolNames:X.activeToolNames,stepLimit:X.stepLimit});return{result:Q.result,error:Q.error,span:Q.span,assembledSystemMessages:Q.assembledSystemMessages}}function FS8($){let{ctx:Z,organization:X,modelRuntime:Q,sideChannel:Y,cleanup:G}=$,J=ek8(Z,Y.writer),K=ak8(Z);return{toolRuntime:{buildEnvironmentTools:async({input:N,onChildUsage:U})=>{let F=Jh(N),w=new Map,B=[],{resolveArgs:L,onToolCalled:D,onPrOpened:E}=Ij0(Z,N.threadId),z=await nk8(N,Z,{writer:Y.writer,toolOutputMap:w,pendingImages:B,threadId:N.threadId,resolveArgs:L,onToolCalled:D,onPrOpened:E,mcpForAgent:async(A,P)=>{let R=F.virtualMcp,S=null;if(R.id&&N.user.id&&d5(R.metadata)[N.user.id])S=await D_(Z,R.id,N.user.id,F.branch??void 0).catch(()=>null);return sN(R,Z,P?.superUser??!1,{listTimeoutMs:P?.listTimeoutMs,includeSkillsCatalog:!0,additionalConnections:S?[S]:[]})},provider:Q.thinking.provider,imageProvider:Q.image?.provider??Q.thinking.provider,webSearchProvider:Q.webSearch?.provider??Q.thinking.provider,deepResearchProvider:Q.deepResearch?.provider??Q.thinking.provider,backgroundDispatcher:US8({threadId:N.threadId,orgId:N.organizationId,userId:N.user.id,agentId:N.agent.id,temperature:N.temperature,toolApprovalLevel:N.toolApprovalLevel,branch:F.branch??null}),htmlArtifactBuffer:K,onChildUsage:U}),j={tools:z.tools,passthroughTools:z.passthroughTools,builtInTools:z.builtInTools,connectionsBlockTools:z.connectionsBlockTools,toolAnnotations:z.toolAnnotations,connectionTitleMap:z.connectionTitleMap,serverInstructions:z.serverInstructions,passthroughClient:z.passthroughClient,toolOutputMap:w,writer:Y.writer,pendingImages:B,sideChunks:Y.stream,closeSideChunks:Y.close,onStepFinish:async()=>{await K.flush(),await J.sweep()},close:z.close};return G.close=z.close,j},runEngine:(N)=>Uh4(Z,X,N)},telemetry:{recordLlmCall:(N)=>vq8({ctx:Z,...N}),monitorLlmCall:(N)=>_q8({ctx:Z,...N,requestId:Z.metadata.requestId,userAgent:Z.metadata.userAgent??null})}}}var wS8=O(()=>{xq8();fq8();ig();Wj0();QG();pk8();K51();sk8();$S8();Rj0();lj0();Kh()});function dj0($){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 BS8=O(()=>{KW();nb()});var OS8=O(()=>{BS8()});var LS8=O(()=>{L61();wS8();OS8();kz8(($)=>{let Z=$.ctx;return FS8({...$,ctx:Z,organization:Z.organization})})});function mj0(){return crypto.randomUUID()}function PO($,Z){return`error-${$}:${Z}`}class DS8{thread;organization_id;storage;defaultWindowSize;constructor($){this.thread=$.thread,this.organization_id=$.thread.organization_id,this.storage=$.storage,this.defaultWindowSize=$.defaultWindowSize??50}async loadHistory($){let Z=$??this.defaultWindowSize,{chronological:X,isWindowed:Q}=this.thread.message_storage_version===2?await this.loadWindowedFromParts(Z):await this.loadWindowedFromMessages(Z),Y=X.find((W)=>W.role!=="system");if(!Y||Y.role==="user")return X;let G=Y,J=Q?"[Context: earlier turns in this conversation were truncated. The messages below continue the thread \u2014 pick up from there.]":"[Context: this thread opens with your message \u2014 you spoke first to greet the user, and the user has not spoken before it. Their reply follows.]";return[{id:`${this.thread.id}-msg-prefix`,thread_id:this.thread.id,role:"user",parts:[{type:"text",text:J}],metadata:void 0,created_at:G.created_at,updated_at:G.updated_at},...X]}async loadWindowedFromMessages($){let{messages:Z,total:X}=await this.storage.listMessages(this.thread.id,{limit:$,sort:"desc"});return{chronological:[...Z].reverse(),isWindowed:X>Z.length}}async loadWindowedFromParts($){let{messages:Z,total:X}=await this.storage.messageParts().loadWindow(this.thread.id,{limit:$});return{chronological:Z.map((Y)=>({id:Y.id,thread_id:this.thread.id,role:Y.role,parts:Y.parts,metadata:Y.metadata??void 0,created_at:Y.created_at,updated_at:Y.created_at})),isWindowed:X>Z.length}}}async function ij0($,Z){let{thread_id:X,defaultWindowSize:Q}=Z;if(!X)throw Error("createMemory: thread_id is required");let Y=await $.get(X);if(!Y)throw Error(`Thread not found: ${X}`);return new DS8({thread:Y,storage:$,defaultWindowSize:Q})}function Fh4($,Z){let X=$.filter((G)=>G.parts&&G.parts.length>0),Q=X.findIndex((G)=>G.id===Z.id);return Q>=0?[...X.slice(0,Q),Z]:[...X,Z]}async function wh4($){return[...$.systemMessages,...Fh4($.history,$.userMessage)]}async function ES8($){let Z=$.isSubagent?[]:await(await ij0($.ctx.storage.threads,{thread_id:$.threadId,organization_id:$.ctx.organization?.id??"",userId:$.ctx.auth.user?.id??"",defaultWindowSize:$.windowSize??X3})).loadHistory($.windowSize??X3),X=await wh4({history:Z,userMessage:$.userMessage,systemMessages:$.systemMessages});return jj0(X,$.ctx)}var zS8=O(()=>{FB();Ch()});function nj0($){return{id:$.id,role:$.role,parts:$.parts,metadata:$.metadata??void 0}}var u51=()=>{};function jS8($,Z){let X=$.thinking.capabilities;if(!((X?.vision??!1)||(X?.file??!1))){if(Z.some((G)=>G.parts?.some((J)=>J.type==="file")))throw new W8(400,{message:"This model does not support file uploads. Please change the model and try again."})}}var PS8=O(()=>{wJ()});function pj0($){return $.sandboxProviderKind==="agent-sandbox"&&$.harnessId==="decopilot"}function AS8($){return $.harnessId==="decopilot"&&($.sandboxProviderKind==null||$.sandboxProviderKind==="agent-sandbox")}function Oh4($){return{type:"data-run-status",id:"run-status",data:{stage:$}}}function TS8($){if(!$||typeof $!=="object")return!1;return $.type==="data-run-status"}async function GK($,Z,X){if(!$)return;try{await $.publishRawChunk(Z,Oh4(X))}catch{}}var Bh4,or,g5Z;var gh=O(()=>{Bh4=["waiting-runner","starting-run","waiting-capacity","gathering-context","preparing-tools","starting-assistant","analyzing-scope"],or=["gathering-context","preparing-tools","starting-assistant","analyzing-scope"],g5Z=new Set(Bh4)});function Lh4($){return{type:"data-user-message",data:$}}function IS8($){if(!$||typeof $!=="object")return!1;return $.type==="data-user-message"}async function RS8($,Z,X){if(!$)return;try{await $.publishRawChunk(Z,Lh4(X))}catch{}}class rr{intervalMs;emitFn;sleepFn;controller=null;stopped=!1;constructor($){this.intervalMs=$.intervalMs??Dh4,this.emitFn=$.emit,this.sleepFn=$.sleepFn??m8}arm(){if(this.stopped)return;this.controller?.abort();let $=new AbortController;this.controller=$,this.wait($.signal)}async wait($){try{await this.sleepFn(this.intervalMs,{signal:$})}catch{return}if(this.stopped||$.aborted)return;try{await this.emitFn()}catch{this.stop();return}if(!this.stopped&&!$.aborted)this.arm()}stop(){if(this.stopped)return;this.stopped=!0,this.controller?.abort(),this.controller=null}}function qS8($=Date.now){return{type:"data-liveness",data:{t:$()},transient:!0}}var Dh4=30000;var c51=O(()=>{W5()});function Eh4($=Date.now){return qS8($)}async function*MS8($,Z={}){let X=()=>Eh4(Z.now),Q=null,Y=new rr({intervalMs:Z.intervalMs,sleepFn:Z.sleepFn,emit:()=>Q?.()}),G=$[Symbol.asyncIterator](),J=G.next();try{Y.arm();while(!0){let K=new Promise((H)=>{Q=()=>H("heartbeat")}),W=await Promise.race([J.then((H)=>({kind:"chunk",r:H})),K.then((H)=>({kind:H}))]);if(Q=null,W.kind==="heartbeat"){yield X();continue}if(Y.arm(),W.r.done)return;yield W.r.value,J=G.next()}}finally{Y.stop(),await G.return?.(void 0).catch(()=>{})}}var kS8=O(()=>{c51()});function zh4($){if(!$)return;if(!("models"in $))return;return $.models??void 0}function SS8($,Z){if(!$)return!0;if($.includes("*:*"))return!0;return $.some((X)=>X.startsWith(`${Z}:`))}function JK($,Z,X){if(!$)return!0;return $.includes("*:*")||$.includes(`${Z}:*`)||$.includes(`${Z}:${X}`)}function tj0($,Z){if($===void 0)return Z;let X=Z;if(X.image&&!JK($,X.image.credentialId,X.image.id)){let{image:Q,...Y}=X;X=Y}if(X.webSearch&&!JK($,X.webSearch.credentialId,X.webSearch.id)){let{webSearch:Q,...Y}=X;X=Y}if(X.deepResearch&&!JK($,X.deepResearch.credentialId,X.deepResearch.id)){let{deepResearch:Q,...Y}=X;X=Y}return X}function VS8($){if(!$)return{allowAll:!0,models:{}};if($.includes("*:*"))return{allowAll:!0,models:{}};let Z={};for(let X of $){let Q=X.indexOf(":");if(Q===-1)continue;let Y=X.slice(0,Q),G=X.slice(Q+1);if(!Z[Y])Z[Y]=[];Z[Y].push(G)}return{allowAll:!1,models:Z}}function jh4($){if($.some((X)=>X===void 0))return;let Z=new Set;for(let X of $)for(let Q of X??[])Z.add(Q);return[...Z]}async function KK($,Z,X){if(!X||$3(X))return;let Q=X.split(","),Y=await $.selectFrom("organizationRole").select(["role","permission"]).where("organizationId","=",Z).where("role","in",Q).execute(),G=new Map(Y.map((K)=>[K.role,K.permission])),J=Q.map((K)=>{let W=G.get(K);if(!W)return;try{let H=JSON.parse(W);return zh4(H)}catch{return console.error(`[model-permissions] Failed to parse permissions for role: ${K}`),[]}});return jh4(J)}var hh=O(()=>{Z3()});function uh($,Z){let X=$.capabilities?{...$.capabilities.vision!==void 0?{vision:$.capabilities.vision}:{},...$.capabilities.text!==void 0?{text:$.capabilities.text}:{},...$.capabilities.reasoning!==void 0?{reasoning:$.capabilities.reasoning}:{}}:void 0;return{id:$.id,...$.title!==void 0?{title:$.title}:{},...$.provider!==void 0?{provider:$.provider}:{},credentialId:Z,...$.limits?{limits:$.limits}:{},...X&&Object.keys(X).length>0?{capabilities:X}:{}}}function CS8($){let Z=$.credentialId,X=uh($.thinking,Z);return{thinking:{...X,title:X.title??X.id},...$.fast?{fast:uh($.fast,Z)}:{},...$.smart?{smart:uh($.smart,Z)}:{},...$.image?{image:uh($.image,$.image.credentialId??Z)}:{},...$.webSearch?{webSearch:uh($.webSearch,$.webSearch.credentialId??Z)}:{},...$.deepResearch?{deepResearch:uh($.deepResearch,$.deepResearch.credentialId??Z)}:{}}}function Ph4($,Z=[]){if($==="stop")return"completed";if($==="tool-calls"){let X=Z.some((Y)=>Y.type==="tool-user_ask"&&Y.state==="input-available"),Q=Z.some((Y)=>Y.state==="approval-requested");return X||Q?"requires_action":"completed"}return"failed"}function oj0($,Z=[]){if($==null)return"completed";return Ph4($,Z)}function l51(){return J1().podName}var _S8=O(()=>{c8()});function Ah4($){let Z=null;return new ReadableStream({async pull(X){try{Z??=$().getReader();let{done:Q,value:Y}=await Z.read();if(Q)X.close();else X.enqueue(Y)}catch(Q){X.error(Q)}},async cancel(X){await Z?.cancel(X)}},{highWaterMark:0})}function Th4($){let Z=$.startSeq??0;async function*X(){for await(let Q of $.chunks)yield{seq:++Z,chunk:Q}}return new ReadableStream({async start(Q){try{let Y=await $.loadOriginalMessages?.();await gj0({runId:$.runId,fenceToken:$.fenceToken,chunks:X(),errorMessageId:$.errorMessageId,originalMessages:Y,...$.initialAckSeq!==void 0?{initialAckSeq:$.initialAckSeq}:{},...$.onPublished?{onPublished:$.onPublished}:{}},{streamBuffer:$.streamBuffer,hooks:$.hooks,title:$.title}),Q.close()}catch(Y){Q.error(Y)}}})}async function Ih4($,Z,X,Q){let{keyInfo:Y,apiKey:G}=await $.storage.aiProviderKeys.resolve(X,Z),J=dj0({providerId:Y.providerId,apiKey:G,modelId:Q});if(J.providerId==="openrouter"||J.providerId==="deco")return{...J,extraHeaders:{...J.extraHeaders,"HTTP-Referer":"https://studio.decocms.com","X-Title":"deco"}};return J}function d51($){if(!fS8.includes($))throw Error(`hosted dispatch requires one of ${fS8.join(", ")}; got ${JSON.stringify($)}`)}async function Rh4($,Z,X){if($==="decopilot")return;if((await X.storage.organizationSettings.get(Z))?.flags?.claude_code_sandbox_enabled===!0)return;throw Error(`the ${$} harness is not enabled for this organization (set the claude_code_sandbox_enabled flag to allow it)`)}function bS8($){return!("messages"in $)}function yS8($,Z){if(!$.taskId)throw Error("buildDurableDispatchInput: taskId is required");let X=$.messages.filter((Q)=>Q.role==="system").flatMap((Q)=>Q.parts).filter((Q)=>Q.type==="text"&&typeof Q.text==="string").map((Q)=>Q.text).join(`
|
|
2746
2746
|
|
|
2747
|
-
`).trim();return{models:$.models,agent:$.agent,temperature:$.temperature,toolApprovalLevel:$.toolApprovalLevel,...$.toolAllowlist!==void 0?{toolAllowlist:$.toolAllowlist}:{},...$.maxAgentSteps!==void 0?{maxAgentSteps:$.maxAgentSteps}:{},...$.isSubagent!==void 0?{isSubagent:$.isSubagent}:{},...$.subtaskJobId!==void 0?{subtaskJobId:$.subtaskJobId}:{},...$.resumedFromBackground!==void 0?{resumedFromBackground:$.resumedFromBackground}:{},mode:$.mode,...$.windowSize!==void 0?{windowSize:$.windowSize}:{},...$.triggerId!==void 0?{triggerId:$.triggerId}:{},...$.runMetadata!==void 0?{runMetadata:$.runMetadata}:{},branch:Z.branch??$.branch??null,sandboxProviderKind:$.sandboxProviderKind,harnessId:$.harnessId,organizationId:$.organizationId,userId:$.userId,taskId:$.taskId,messageId:Z.messageId,...Z.runFenceToken!==void 0?{runFenceToken:Z.runFenceToken}:{},...$.isResume!==void 0?{isResume:$.isResume}:{},...X?{systemContext:X}:{}}}function qh4($,Z){let X=$.find((Q)=>Q.id===Z);if(!X)throw new mB("empty_request",`Persisted request message missing for messageId=${Z}`);if(X.role==="system")throw new mB("empty_request",`Persisted message ${Z} has role=system; expected non-system request message`);return X}function Mh4($){let Z=$.models;return{"decopilot.agent.id":$.agent.id,"decopilot.model.id":Z.thinking.id,"decopilot.credential.id":Z.credentialId,"decopilot.organization.id":$.organizationId,"decopilot.user.id":$.userId,"decopilot.thread.id":$.taskId??""}}async function gS8($,Z,X){return Gu1("decopilot.dispatchRunAndWait",async(Q)=>{let{taskId:Y,uiStream:G,registrySignal:J}=await Vh4($,Z,X,Q),K=X.streamBuffer,W=K?await K.createTailStream(Y,$.abortSignal,{deliverPolicy:"new",closeOnDone:!0}):null;if(K&&W){let H=K.pump(G,Y,J,$.organizationId);H.catch(()=>{});let N=W.getReader();try{while(!0){let{done:U}=await N.read();if(U)break}}finally{N.releaseLock()}await H}else{if(K)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"producer-fallback-no-pump",taskId:Y,hasTail:!!W,note:"createTailStream returned null \u2014 draining producer stream directly; projector persistence depends on streamBuffer publish health"}));let H=G.getReader();try{while(!0){let{done:N}=await H.read();if(N)break}}finally{H.releaseLock()}}return{taskId:Y}},Mh4($))}async function kh4($,Z,X,Q){let[Y,G,J]=await Promise.all([$.storage.threads.list(Q,{limit:9,agentId:X}).catch(()=>null),$.storage.interests.getForAgent(Z,X,Q).catch(()=>null),$.storage.virtualMcps.list(Z).catch(()=>null)]),K={};if(Y&&Y.total>0)K.recentThreads={total:Y.total,threads:Y.threads.map((W)=>({id:W.id,title:W.title,updated_at:W.updated_at}))};if(G&&G.interests.length>0)K.interests=G.interests.map((W)=>({title:W.title,summary:W.summary}));if(J)K.agents=J.map((W)=>({id:W.id,name:W.title,description:W.description,status:W.status}));return K}async function Sh4({virtualMcp:$,agentId:Z,organizationId:X,ctx:Q}){return GX0({virtualMcp:$,agentId:Z,organizationId:X,ctx:Q})}async function Vh4($,Z,X,Q){let{runRegistry:Y,streamBuffer:G}=X;d51($.harnessId);let J=$.harnessId;if(await Rh4(J,$.organizationId,Z),!bS8($))$={...$,messages:$.messages.map((H)=>H.id?H:{...H,id:_p()})};let K=!1,W;try{let H=$.models;Q.setAttribute("decopilot.harnessId",J),Z.sandboxPreference="agent-sandbox",Q.setAttribute("decopilot.dispatchTarget.sandboxProviderKind","agent-sandbox");let N=pj0({harnessId:J,sandboxProviderKind:"agent-sandbox"}),U=CS8(H),F=await KK(Z.db,$.organizationId,Z.organization?.role??Z.auth.user?.role);if(!JK(F,U.thinking.credentialId,U.thinking.id))throw Error("Model not allowed for your role");U=tj0(F,U);let w=$.windowSize??X3;if(!$.taskId)throw Error("dispatchRunAndWait: taskId is required");if(N)await GK(G,$.taskId,or[0]);let B=(H1)=>H1?Ih4(Z,$.organizationId,H1.credentialId,H1.id):Promise.resolve(void 0),[L,D,E,z,j,A,P,R,S]=await Promise.all([Z.storage.virtualMcps.findById($.agent.id,$.organizationId),B(U.thinking),B(U.fast),B(U.smart),B(U.image),B(U.webSearch),B(U.deepResearch),ij0(Z.storage.threads,{organization_id:$.organizationId,thread_id:$.taskId,userId:$.userId,defaultWindowSize:w}),kh4(Z,$.organizationId,$.agent.id,$.userId)]);if(N)await GK(G,$.taskId,or[1]);let M=D?{thinking:D,...E?{fast:E}:{},...z?{smart:z}:{},...j?{image:j}:{},...A?{webSearch:A}:{},...P?{deepResearch:P}:{}}:void 0,C=D?aG0(D):null;if(W=R.thread.id,Z.metadata.threadId=R.thread.id,Q.setAttribute("decopilot.thread.id",R.thread.id),R.thread.created_by!==$.userId)throw Error("You are not allowed to write to this thread because you are not the owner");if(C?.asyncResearch){let H1=[["thinking",U.thinking.id]];if(U.fast)H1.push(["fast",U.fast.id]);if(U.smart)H1.push(["smart",U.smart.id]);if(U.image)H1.push(["image",U.image.id]);for(let[o,A0]of H1)if(C.asyncResearch.canHandle(A0))throw Error(`Model "${A0}" can only be used as a Deep Research model. It is not usable as the ${o} model \u2014 set it in the Deep Research slot instead.`)}let v=R.thread.message_storage_version===2?new zX({storage:Z.storage.threads.messageParts(),orgId:$.organizationId,threadId:R.thread.id,runId:R.thread.id}):null;if(!L)throw new mB("agent_not_found","Agent not found");let b=await Sh4({virtualMcp:L,agentId:$.agent.id,organizationId:$.organizationId,ctx:Z});if($.isResume)await Y.execute({type:"RESUME",taskId:R.thread.id,orgId:$.organizationId,userId:$.userId,abortController:new AbortController,podId:l51()});else await Y.execute({type:"START",taskId:R.thread.id,orgId:$.organizationId,userId:$.userId,abortController:new AbortController,podId:l51(),runConfig:{models:$.models,agent:$.agent,temperature:$.temperature,toolApprovalLevel:$.toolApprovalLevel,mode:$.mode,windowSize:$.windowSize,triggerId:$.triggerId},messageId:$.messageId});K=!0,await Z.storage.threads.clearCancelRequested(R.thread.id);let p;if($.runFenceToken)p=$.runFenceToken;else p=mj0(),await Z.storage.threads.setRunFence(R.thread.id,p);let y=Y.getAbortSignal(R.thread.id);if(!y)throw await Y.execute({type:"FINISH",taskId:R.thread.id,threadStatus:"failed"}),Error("Run was cancelled immediately after starting");if($.abortSignal){let H1=$.abortSignal;if(H1.aborted)await Y.execute({type:"CANCEL",taskId:R.thread.id});else H1.addEventListener("abort",()=>{Y.execute({type:"CANCEL",taskId:R.thread.id}).catch(()=>{})},{once:!0})}if(!$.isResume)G?.purge(R.thread.id);let Z0=[],U0,k0;if(bS8($)){if(k0=await R.loadHistory(w),U0=qh4(k0,$.messageId),$.systemContext)Z0=[{id:`system-${$.messageId}`,role:"system",parts:[{type:"text",text:$.systemContext}]}]}else{Z0=$.messages.filter((o)=>o.role==="system");let H1=$.messages.find((o)=>o.role!=="system");if(U0=H1?(await zj0([H1],Z,{threadId:R.thread.id})).find((o)=>o.role!=="system"):void 0,!$.isResume){if(!U0)throw new mB("empty_request","No user message found in input \u2014 expected at least one non-system message");if(v)await v.emitUserMessage(U0).catch((o)=>{console.error("[decopilot:stream] v2 user-message emit failed",o)})}}if(U0)await RS8(G,R.thread.id,U0);let $0=[],e=Z.organization,I0=Date.now(),Q0=U0?(await jj0([U0],Z))[0]:void 0;if(!Q0||!U0)throw new mB("empty_request","No user message found in input \u2014 expected at least one non-system message");jS8($.models,[Q0]);let R0=await ES8({ctx:Z,threadId:R.thread.id,userMessage:U0,windowSize:w,isSubagent:$.isSubagent===!0,systemMessages:Z0}),m0={url:"",headers:{},expiresAt:0},r0=void 0,K0=void 0,S0={cwd:null},C0=typeof b.metadata?.instructions==="string"?b.metadata.instructions:void 0,q0={taskId:$.taskId,isSubagent:$.isSubagent,subtaskJobId:$.subtaskJobId,resumedFromBackground:$.resumedFromBackground,virtualMcp:b,branch:$.branch,messages:R0,modelSources:M,mcpSource:r0,objectStorageSource:K0,userContext:S},X0={harnessId:J,threadId:R.thread.id,userMessage:Q0,harness:{sessionId:void 0},workspace:S0,models:U,mcp:m0,mode:$.mode,temperature:$.temperature,toolApprovalLevel:$.toolApprovalLevel,toolAllowlist:$.toolAllowlist??null,maxAgentSteps:$.maxAgentSteps,user:{id:$.userId,email:Z.auth.user?.email??""},organizationId:$.organizationId,organizationSlug:e.slug,agent:{id:$.agent.id,instructions:C0},triggerId:$.triggerId,currentThreadTitle:R.thread.title,runFenceToken:p};if(N)await GK(G,$.taskId,or[2]);let W0=L_(J),h0=W0?await Z.storage.threads.getAckedSeq(R.thread.id):0;if(h0>0)console.log("[dispatch] resuming a sandbox-hosted turn",{runId:R.thread.id,fromSeq:h0});let w0=async function*(){let H1={...X0,signal:y};if(w61(H1,q0),N)await GK(G,R.thread.id,or[3]);yield*(W0?new m$1({ctx:Z,harnessId:J,virtualMcpId:b.id,...h0>0?{resume:{reason:"the Studio process driving the previous attempt stopped"}}:{},branch:await Nq8(Z,{threadId:R.thread.id,agentRepo:b.metadata?.githubRepo,runBranch:$.branch}),credential:D?{providerId:D.providerId,apiKey:D.apiKey,...D.baseUrl?{baseUrl:D.baseUrl}:{}}:null}):new D61({ctx:Z,harnessId:J})).dispatch(H1)},j0=Ah4(()=>Th4({runId:R.thread.id,fenceToken:p,streamBuffer:G??{publishRawChunk:async()=>!1,publishDone:async()=>!1},chunks:MS8(w0()),...W0?{startSeq:h0,initialAckSeq:h0,onPublished:(H1)=>Z.storage.threads.bumpAckedSeq(R.thread.id,p,H1)}:{},errorMessageId:PO(R.thread.id,p),loadOriginalMessages:v?async()=>(await Z.storage.threads.messageParts().loadWindow(R.thread.id,{limit:1})).messages.map(nj0):void 0,title:{currentThreadTitle:R.thread.title,threadId:R.thread.id,persistTitle:async(H1,o)=>{await Z.storage.threads.update(H1,{title:o})}},hooks:{onStep:()=>{let H1=Y.dispatch({type:"STEP_DONE",taskId:R.thread.id});$0.push(Y.react(H1).catch((o)=>{console.error("[decopilot:stream] onStepFinish reactor failed",o)}))},onFinish:async(H1,o)=>{let A0=$0.length,v0=performance.now();if(await Promise.allSettled($0),xS8.record(performance.now()-v0,{phase:"settle"}),y.aborted)return;await m8(0);let F1=vS8?UD():null,f1=performance.now(),d8=oj0(o,H1?.parts);await Y.execute({type:"FINISH",taskId:R.thread.id,threadStatus:d8});let o0=performance.now()-f1;if(xS8.record(o0,{phase:"save"}),vS8&&F1){let m1=UD()??F1,v8=-1;try{v8=JSON.stringify(H1)?.length??-1}catch{}console.warn(JSON.stringify({msg:"decopilot-finish-trace",threadId:R.thread.id,pendingOps:A0,saveMs:Math.round(o0),parts:H1?.parts?.length??0,messageBytes:v8,rssDelta:m1.rss-F1.rss,heapUsedDelta:m1.heapUsed-F1.heapUsed,externalDelta:m1.external-F1.external}))}},onError:(H1)=>{if(y.aborted){i1.capture({distinctId:$.userId,event:"chat_message_aborted",groups:{organization:$.organizationId},properties:{organization_id:$.organizationId,thread_id:R.thread.id,agent_id:$.agent.id,model_id:U.thinking.id,mode:$.mode,duration_ms:Date.now()-I0,is_resume:$.isResume??!1}});return}console.error("[decopilot] stream error:",WU(H1)),Y.execute({type:"FINISH",taskId:R.thread.id,threadStatus:"failed"}).catch((o)=>{console.error("[decopilot:stream] onError reactor failed",o)})}}}));return{taskId:R.thread.id,uiStream:j0,registrySignal:y}}catch(H){if(K&&W)Y.execute({type:"FINISH",taskId:W,threadStatus:"failed"}).catch((N)=>{console.error("[decopilot:stream] catch-block reactor failed",N)});throw H}}var xS8,vS8,fS8;var rj0=O(()=>{G81();S$();Vz8();Kj0();tW();tb();LS8();Kh();J81();FB();zS8();zO();u51();Ch();PS8();gh();y51();kS8();hh();P5();_S8();W5();xS8=D6.createHistogram("decopilot.finish.duration",{description:"Wall time of onFinish flush segments, tagged by phase",unit:"ms"}),vS8=process.env.DECOPILOT_FINISH_TRACE==="1";fS8=["decopilot","claude-code"]});function hS8($){return TS8($)||IS8($)}async function Ch4($){let Z=$.getReader();try{while(!0){let{done:X}=await Z.read();if(X)break}}finally{Z.releaseLock()}}function _h4($,Z){let X=$.getReader(),Q=!1,Y=()=>{if(Q)return;Q=!0,X.releaseLock()};return new ReadableStream({async pull(G){try{let{done:J,value:K}=await X.read();if(J)Y(),G.close();else G.enqueue(K)}catch(J){Z(J),Y(),G.error(J)}},async cancel(G){await X.cancel(G),Y()}})}async function uS8($){if(!$.chunks&&!$.chunkStream)throw Error("projectChunks requires chunks or chunkStream");let Z=null,X=!1,Q=void 0,Y={inputTokens:0,outputTokens:0,totalTokens:0},G=[],J=null,K=(B)=>{if(J===null)J=B;throw B},W=$.chunks?async function*(){try{for await(let B of $.chunks){if(hS8(B))continue;yield B}}catch(B){throw Z=B,B}}():void 0,H=$.chunkStream?_h4($.chunkStream,(B)=>{Z=B}).pipeThrough(new TransformStream({transform(B,L){if(!hS8(B))L.enqueue(B)}})):void 0,N={emitStepParts:(B)=>$.persistence.emitStepParts(B).catch(K),emitFinal:(B)=>$.persistence.emitFinal(B).catch(K),emitError:(B,L)=>$.persistence.emitError(B,L).catch(K)},{uiStream:U,whenComplete:F}=yj0({chunks:W,chunkStream:H,originalMessages:$.originalMessages??[],title:$.title?{currentThreadTitle:$.title.currentThreadTitle,threadId:$.title.threadId,persistTitle:$.title.persistTitle}:{currentThreadTitle:void 0,threadId:"projector",persistTitle:async()=>{}},persistence:N,sanitizeErrorText:$.sanitizeErrorText,errorMessageId:$.errorMessageId,generateMessageId:$.generateMessageId,hooks:{onUsage:(B)=>{Y={inputTokens:B.inputTokens,outputTokens:B.outputTokens,totalTokens:B.totalTokens}},onError:()=>{X=!0},onFinish:(B,L)=>{Q=L,G=Array.isArray(B.parts)?B.parts.filter((D)=>D!=null&&typeof D==="object"&&("type"in D)):[]}}});if(await Ch4(U).catch(()=>{}),await F,J!==null)throw J;if(Z!==null)throw Z;return{failed:X&&Q===void 0,finishReason:Q,usage:Y,finalParts:G}}var cS8=O(()=>{b51();gh()});var ar=786432;function vh4($){if(/[.*>\s]/.test($))throw Error("Invalid NATS subject token")}function AO($){return vh4($),`${aj0}.${$}`}function lS8($){let Z=`${$.runId}:${$.fenceToken}:${$.seq}`;return $.fragmentIndex===void 0?Z:`${Z}:frag:${$.fragmentIndex}`}function fh4($){return`${$.runId}:${$.fenceToken}:done:${$.finalSeq}`}function dS8($){if(!$)return null;let Z=Number($);return Number.isInteger(Z)&&Z>0?Z:null}function bh4($){if(!$)return null;let Z=Number($);return Number.isInteger(Z)&&Z>=0?Z:null}function yh4($){if(!$)return null;let Z=$.split(":"),[X,Q,Y,G,J]=Z;if(!X||!Q||!Y)return null;if(Y==="done"){let W=dS8(G);return Z.length===4&&W!==null?{kind:"done",runId:X,fenceToken:Q,finalSeq:W}:null}if(Y==="ckpt")return null;let K=dS8(Y);if(K===null)return null;if(Z.length===3)return{kind:"chunk",runId:X,fenceToken:Q,seq:K,fragmentIndex:null};if(Z.length===5&&G==="frag"){let W=bh4(J);return W===null?null:{kind:"chunk",runId:X,fenceToken:Q,seq:K,fragmentIndex:W}}return null}function i51($,Z){let X=AO(Z.runId),Q=m51.encode(JSON.stringify({p:$}));if(Q.length>xh4)return[];if(Q.length<=ar)return[{subject:X,data:Q,msgId:Z.dedup?lS8({runId:Z.runId,...Z.dedup}):void 0}];let Y=Math.ceil(Q.length/ar),G=[];for(let J=0;J<Y;J++)G.push({subject:X,data:Q.slice(J*ar,(J+1)*ar),headers:{[mS8]:String(J),[iS8]:String(Y)},msgId:Z.dedup?lS8({runId:Z.runId,...Z.dedup,fragmentIndex:J}):void 0});return G}function nS8($){return{subject:AO($.runId),data:m51.encode(JSON.stringify({done:!0,finalSeq:$.finalSeq})),msgId:fh4($)}}function pS8($){return{subject:AO($),data:m51.encode(JSON.stringify({done:!0}))}}function gh4($){let Z=$.reduce((Y,G)=>Y+(G?.length??0),0),X=new Uint8Array(Z),Q=0;for(let Y of $){if(!Y)continue;X.set(Y,Q),Q+=Y.length}return X}function sj0(){let $=null;return new TransformStream({transform(Z,X){let Q=Z.headers?.get(iS8);if(!Q){X.enqueue(Z);return}let Y=Number(Q),G=Number(Z.headers?.get(mS8)??"0");if(G===0)$={total:Y,received:0,parts:Array(Y)};else if(!$||$.total!==Y)return;if(!$.parts[G])$.received++;if($.parts[G]=Z.data,$.received<$.total)return;let J=gh4($.parts);$=null,X.enqueue({subject:Z.subject,data:J,headers:Z.headers})}})}function hh4($){return typeof $==="number"&&Number.isInteger($)&&$>0}function ch4($){let Z=yh4($.headers?.get("Nats-Msg-Id")||void 0),X;try{X=JSON.parse(uh4.decode($.data))}catch{return null}if(!X||typeof X!=="object")return null;let Q=X;if(Q.done===!0)return{kind:"done",runId:Z?.kind==="done"?Z.runId:null,fenceToken:Z?.kind==="done"?Z.fenceToken:null,envelopeFinalSeq:hh4(Q.finalSeq)?Q.finalSeq:null,msgIdFinalSeq:Z?.kind==="done"?Z.finalSeq:null};if("p"in Q)return{kind:"chunk",seq:Z?.kind==="chunk"?Z.seq:null,runId:Z?.kind==="chunk"?Z.runId:null,fenceToken:Z?.kind==="chunk"?Z.fenceToken:null,chunk:Q.p};return null}function ej0(){return new TransformStream({transform($,Z){let X=ch4($);if(X)Z.enqueue(X)}})}var aj0="decopilot.stream",mS8="Dp-Frag-Idx",iS8="Dp-Frag-Total",xh4=33554432,m51,uh4;var tS8=O(()=>{m51=new TextEncoder;uh4=new TextDecoder});var $P0=O(()=>{tS8()});var zU="DECOPILOT_STREAMS";var n51=O(()=>{$P0()});function oS8($,Z){return new TransformStream({transform(X,Q){if(X.runId!==$||X.fenceToken!==Z)return;Q.enqueue(X)}})}function rS8(){let $=1;return new TransformStream({transform(Z,X){if(Z.kind==="done"){X.enqueue(Z);return}if(Z.seq===null){X.error(Error("projector chunk missing seq"));return}if(Z.seq<$)return;if(Z.seq>$){X.error(new sr($,Z.seq));return}$++,X.enqueue(Z)}})}function aS8($){let Z=$.getReader(),X=!1,Q=0,Y=()=>{if(X)return;X=!0,Z.releaseLock()};return new ReadableStream({async pull(G){for(;;){let{done:J,value:K}=await Z.read();if(J){await Z.cancel(),Y(),G.error(Error("reader stopped before done"));return}let W=K;if(W.kind==="done"){if(!(W.envelopeFinalSeq!=null&&W.envelopeFinalSeq===W.msgIdFinalSeq))continue;if(W.envelopeFinalSeq!==Q){await Z.cancel(),Y(),G.error(new sr(Q+1,null));return}await Z.cancel(),Y(),G.close();return}Q=W.seq??Q,G.enqueue(W.chunk);return}},async cancel(G){await Z.cancel(G),Y()}})}function lh4($){if(Symbol.asyncIterator in $)return $[Symbol.asyncIterator]();let Z=$[Symbol.iterator]();return{next:async()=>Z.next(),return:async(X)=>Z.return?Z.return(X):{done:!0,value:X}}}function XP0($){let Z=lh4($.messages),X=$.idleTimeoutMs,Q=!1,Y=(G)=>{if(Q)return;Q=!0,Z.return?.(G).catch(()=>{}),$.onCancel?.()};return new ReadableStream({async pull(G){if(X===void 0){let{done:N,value:U}=await Z.next();if(N){G.close();return}G.enqueue(U);return}let J=new AbortController,K=Z.next().then((N)=>{return J.abort(),N}),W=m8(X,{signal:J.signal}).then(()=>"idle").catch(()=>"cancelled"),H=await Promise.race([K,W]);if(H==="idle"){G.error(new ZP0(X));return}if(H==="cancelled")return;if(H.done){G.close();return}G.enqueue(H.value)},async cancel(G){Y(G)}})}var ZP0,sr;var QP0=O(()=>{W5();ZP0=class ZP0 extends Error{idleTimeoutMs;constructor($){super("producer produced no output before timeout");this.idleTimeoutMs=$;this.name="StreamIdleTimeoutError"}};sr=class sr extends Error{expectedSeq;gotSeq;constructor($,Z){super(Z===null?`missing seq ${$} (stream ended at the fenced done)`:`missing seq ${$} (next delivered is ${Z})`);this.expectedSeq=$;this.gotSeq=Z;this.name="StreamGapError"}}});function dh4($){let X=XP0({messages:$.messages,idleTimeoutMs:$.idleTimeoutMs,onCancel:$.onDone}).pipeThrough(sj0()).pipeThrough(ej0()).pipeThrough(oS8($.runId,$.fenceToken)).pipeThrough(rS8());return aS8(X)}async function eS8($){let X=await(await $.js.consumers.get(zU,{filter_subjects:AO($.runId),deliver_policy:sS8.DeliverPolicy.All})).consume();async function*Q(){try{for await(let Y of X)yield{subject:Y.subject,data:Y.data,headers:Y.headers}}finally{X.stop()}}return dh4({messages:Q(),runId:$.runId,fenceToken:$.fenceToken,idleTimeoutMs:$.idleTimeoutMs,onDone:()=>X.stop()})}var sS8;var $V8=O(()=>{n51();QP0();$P0();sS8=k(SD(),1)});async function mh4($){let X=($.requestMessageId?await $.messageParts.maxCreatedAtMsForMessage($.runId,$.requestMessageId):null)??await $.messageParts.maxCreatedAtMsForRun($.runId);return new zX({storage:$.messageParts,orgId:$.orgId,threadId:$.runId,runId:$.runId,baseTimeMs:(X??Date.now())+1})}async function ZV8($){let Z=await mh4($),X=$.replaceFinal?(Q)=>Z.replaceFinal(Q):(Q)=>Z.emitFinal(Q);return{emitStepParts:(Q)=>Z.emitStepParts(Q),emitFinal:X,emitError:(Q,Y)=>Z.emitError(Q,Y)}}var XV8=O(()=>{zO()});function YP0($,Z){ih4.add(1,{"org.id":Z??"unknown"})}var ih4;var QV8=O(()=>{P5();ih4=D6.createCounter("decopilot.projector.poison_runs",{description:"Number of decopilot runs that exhausted retries and were sent to the DLQ",unit:"{runs}"})});class p51{intervalMs;lastBumpMs=new Map;constructor($=3000){this.intervalMs=$}shouldBump($,Z=Date.now()){let X=this.lastBumpMs.get($);if(X!==void 0&&Z-X<this.intervalMs)return!1;return this.lastBumpMs.set($,Z),!0}clear($){this.lastBumpMs.delete($)}}function YV8($,Z,X,Q){return $.pipeThrough(new TransformStream({transform(Y,G){if(X.shouldBump(Z))Q();G.enqueue(Y)},flush(){X.clear(Z)}}))}function nh4($){return`liveness: no stream events for ${Math.round($/60000)}m`}function o51($){return $.runFenceToken!==null&&$.runFenceToken!==$.fenceToken}function JV8($){t51=$}function KV8(){if(!t51)throw Error("[projector-workflow] runtime not initialized \u2014 setProjectorWorkflowRuntime() must run before workflows fire");return t51}function WV8(){return KV8()}async function HV8($,Z,X){let Q=KV8(),Y=Q.getJetStream();if(!Y)throw Error("JetStream unavailable");let G=(await Q.messageParts.loadWindow($.runId,{limit:500})).messages.map(nj0);return{chunkCount:0,attempts:1,outcome:await uS8({chunkStream:YV8(await eS8({js:Y,runId:$.runId,fenceToken:$.fenceToken,idleTimeoutMs:$.idleTimeoutMs}),$.runId,ph4,()=>{Q.bumpProgress({runId:$.runId,orgId:Z}).catch(()=>{})}),persistence:await ZV8({messageParts:Q.messageParts,orgId:Z,runId:$.runId,requestMessageId:$.messageId,replaceFinal:!0}),originalMessages:G,errorMessageId:PO($.runId,$.fenceToken),title:{threadId:$.runId,currentThreadTitle:X,persistTitle:async(K,W)=>{await Q.persistTitle($.runId,Z,W),await Q.onTitleUpdated({runId:$.runId,orgId:Z,title:W})}}})}}async function GV8($,Z,X){let Q=await $.resolveRun(Z).catch(()=>null);return Q!==null&&Q.runFenceToken===X&&["completed","failed","requires_action"].includes(Q.status)}async function NV8($,Z,X){let Q=await th4($,Z);if("skip"in Q)return;let Y=Q.row.orgId,G=Q.row.createdBy??$.runId,J=Q.row.title;try{let{outcome:K}=await X($,Y,J),W=K?.failed?"failed":oj0(K?.finishReason,K?.finalParts);if(W==="failed"){let H=K?.finishReason?`harness reported an error: ${K.finishReason}`:"harness reported an error";if(YP0($.runId,Y),await Z.markRunFailed($.runId,Y,H,"harness"))await Z.recordFailed({runId:$.runId,orgId:Y,distinctId:G,reason:H,kind:"harness"})}else if(W==="requires_action")await Z.markRunRequiresAction($.runId,Y),await Z.clearSynthesizedError($.runId,$.fenceToken);else{if(await Z.completeRunIfNotCompleted($.runId,Y))await Z.recordCompleted({runId:$.runId,orgId:Y,distinctId:G,usage:K?.usage??{inputTokens:0,outputTokens:0,totalTokens:0}});await Z.clearSynthesizedError($.runId,$.fenceToken)}await Z.purgeRun($.runId,$.fenceToken)}catch(K){if(K instanceof sr){if(await GV8(Z,$.runId,$.fenceToken)){await Z.clearSynthesizedError($.runId,$.fenceToken),await Z.purgeRun($.runId,$.fenceToken);return}let F=`stream truncated before projection could replay it: ${K.message}`;if(YP0($.runId,Y),await Z.markRunFailed($.runId,Y,F,"projection"))await Z.recordFailed({runId:$.runId,orgId:Y,distinctId:G,reason:F,kind:"projection"});await Z.purgeRun($.runId,$.fenceToken);return}let W=K instanceof ZP0;if(W&&await GV8(Z,$.runId,$.fenceToken)){await Z.purgeRun($.runId,$.fenceToken);return}let H=W?nh4(K.idleTimeoutMs):K instanceof Error?K.message:String(K),N=W?"liveness":"projection";if(YP0($.runId,Y),await Z.markRunFailed($.runId,Y,H,N))await Z.recordFailed({runId:$.runId,orgId:Y,distinctId:G,reason:H,kind:N});if(W)await Z.clearSynthesizedError($.runId,$.fenceToken);throw K}}async function th4($,Z){let X=await Z.resolveRun($.runId);if(!X)return{skip:"missing"};if(o51({status:X.status,runFenceToken:X.runFenceToken,fenceToken:$.fenceToken}))return{skip:"stale",row:X};if(X.version!==2)return{skip:"legacy-v1",row:X};return{row:X}}var t51=null,ph4;var r51=O(()=>{cS8();$V8();QP0();XV8();QV8();u51();ph4=new p51});function UV8($,Z){switch($.type){case"START":{let X={type:"RUN_STARTED",taskId:$.taskId,orgId:$.orgId,userId:$.userId,abortController:$.abortController,runConfig:$.runConfig,podId:$.podId,messageId:$.messageId};if(Z?.status.tag==="running")return[{type:"PREVIOUS_RUN_ABORTED",taskId:$.taskId,orgId:Z.orgId},X];return[X]}case"STEP_DONE":{if(Z?.status.tag!=="running")return[];return[{type:"STEP_COMPLETED",taskId:$.taskId,orgId:Z.orgId,stepCount:Z.status.stepCount+1}]}case"FINISH":{if(Z==null||Z.status.tag!=="running")return[];let{stepCount:X}=Z.status;if($.threadStatus==="completed")return[{type:"RUN_COMPLETED",taskId:$.taskId,orgId:Z.orgId,stepCount:X}];if($.threadStatus==="requires_action")return[{type:"RUN_REQUIRES_ACTION",taskId:$.taskId,orgId:Z.orgId,stepCount:X}];return[{type:"RUN_FAILED",taskId:$.taskId,orgId:Z.orgId,reason:"error"}]}case"CANCEL":{if(Z?.status.tag!=="running")return[];return[{type:"RUN_FAILED",taskId:$.taskId,orgId:Z.orgId,reason:"cancelled"}]}case"RESUME":{if(Z?.status.tag==="running")return[];return[{type:"RUN_RESUMED",taskId:$.taskId,orgId:$.orgId,userId:$.userId,abortController:$.abortController,podId:$.podId}]}case"FORCE_FAIL":{if($.reason==="ghost")return[{type:"RUN_FAILED",taskId:$.taskId,orgId:Z?.orgId??$.orgId,reason:$.reason,expectedFenceToken:$.expectedFenceToken??null}];if(Z?.status.tag!=="running")return[];return[{type:"RUN_FAILED",taskId:$.taskId,orgId:Z.orgId,reason:$.reason}]}}}function FV8($,Z,X=new Date){switch(Z.type){case"RUN_STARTED":return{taskId:Z.taskId,orgId:Z.orgId,userId:Z.userId,status:{tag:"running",abortController:Z.abortController,stepCount:0,startedAt:X}};case"RUN_RESUMED":return{taskId:Z.taskId,orgId:Z.orgId,userId:Z.userId,status:{tag:"running",abortController:Z.abortController,stepCount:0,startedAt:X}};case"STEP_COMPLETED":if($?.status.tag!=="running")return $;return{...$,status:{...$.status,stepCount:Z.stepCount}};case"RUN_COMPLETED":return;case"RUN_REQUIRES_ACTION":return;case"RUN_FAILED":return;case"PREVIOUS_RUN_ABORTED":return}}async function wV8($,Z,X,Q){let{storage:Y,sseHub:G}=Q,J=await Y.get($,Z);G.emit(Z,sK($,X,{virtualMcpId:J?.virtual_mcp_id??void 0,createdBy:J?.created_by,triggerId:J?.trigger_id,title:J?.title,branch:J?.branch??null,createdAt:J?.created_at,updatedAt:J?.updated_at})),G.emit(Z,V90($,X))}async function rh4($,Z){let{storage:X,sseHub:Q}=Z;switch($.type){case"RUN_STARTED":{await X.update($.taskId,$.orgId,{status:"in_progress",run_config:$.runConfig??null,run_started_at:new Date().toISOString(),last_progress_at:null,failure_reason:null,failure_kind:null});let Y=await X.get($.taskId,$.orgId);Q.emit($.orgId,sK($.taskId,"in_progress",{virtualMcpId:Y?.virtual_mcp_id??void 0,createdBy:Y?.created_by,triggerId:Y?.trigger_id,title:Y?.title,branch:Y?.branch??null,createdAt:Y?.created_at,updatedAt:Y?.updated_at,messageId:$.messageId}));return}case"RUN_RESUMED":{await X.update($.taskId,$.orgId,{status:"in_progress",run_started_at:new Date().toISOString(),last_progress_at:null,failure_reason:null,failure_kind:null});let Y=await X.get($.taskId,$.orgId);Q.emit($.orgId,sK($.taskId,"in_progress",{virtualMcpId:Y?.virtual_mcp_id??void 0,createdBy:Y?.created_by,triggerId:Y?.trigger_id,title:Y?.title,branch:Y?.branch??null,createdAt:Y?.created_at,updatedAt:Y?.updated_at}));return}case"STEP_COMPLETED":Q.emit($.orgId,Om0($.taskId,$.stepCount));return;case"RUN_COMPLETED":await wV8($.taskId,$.orgId,"completed",Z);return;case"RUN_REQUIRES_ACTION":await wV8($.taskId,$.orgId,"requires_action",Z);return;case"RUN_FAILED":{if($.reason==="ghost"){if(!await X.forceFailIfInProgress($.taskId,$.orgId,$.expectedFenceToken))return;await X.update($.taskId,$.orgId,{run_config:null,run_started_at:null})}else{if(!await X.forceFailIfInProgress($.taskId,$.orgId))return;await X.update($.taskId,$.orgId,{run_config:null,run_started_at:null,...$.reason==="reaped"?{failure_reason:oh4,failure_kind:"stall"}:{}})}let Y=await X.get($.taskId,$.orgId);Q.emit($.orgId,sK($.taskId,"failed",{virtualMcpId:Y?.virtual_mcp_id??void 0,createdBy:Y?.created_by,triggerId:Y?.trigger_id,title:Y?.title,branch:Y?.branch??null,createdAt:Y?.created_at,updatedAt:Y?.updated_at})),Q.emit($.orgId,V90($.taskId,"failed"));return}case"PREVIOUS_RUN_ABORTED":return}}async function BV8($,Z){for(let{event:X}of $)await rh4(X,Z)}var oh4="Run stalled \u2014 no progress within the idle timeout window";var OV8=O(()=>{I6()});function LV8($){return $.now-$.lastProgressAt>$.idleTimeoutMs}function DV8($){return Math.max($.persistedLastProgressAt??Number.NEGATIVE_INFINITY,$.currentRunStartedAt)}class s51{deps;clock;states=new Map;reaperTimer=null;constructor($,Z=()=>new Date){this.deps=$;this.clock=Z;this.reaperTimer=setInterval(()=>{this.reapStaleRuns().catch((X)=>{console.error("[RunRegistry] Reaper sweep failed",X)})},ah4)}async execute($){let Z=this.dispatch($);return await this.react(Z),Z}dispatch($){let Z=this.states.get($.taskId),X=UV8($,Z),Q=[];for(let Y of X){let G=this.states.get(Y.taskId);if(Y.type==="PREVIOUS_RUN_ABORTED"||Y.type==="RUN_FAILED"){if(G?.status.tag==="running")G.status.abortController.abort()}let J=FV8(G,Y,this.clock());if(J===void 0)this.states.delete(Y.taskId);else this.states.set(Y.taskId,J);if(Q.push({event:Y,state:J}),sh4.has(Y.type))EV8().add(1,{"org.id":Y.orgId});else if(eh4.has(Y.type)&&G?.status.tag==="running")EV8().add(-1,{"org.id":Y.orgId})}return Q}react($){return BV8($,this.deps)}getAbortSignal($){let Z=this.states.get($);if(Z?.status.tag==="running")return Z.status.abortController.signal;return null}isRunning($){return this.states.get($)?.status.tag==="running"}async stopAll(){for(let[,$]of this.states)if($.status.tag==="running")$.status.abortController.abort();this.states.clear()}dispose(){if(this.reaperTimer)clearInterval(this.reaperTimer),this.reaperTimer=null}async reapStaleRuns(){let $=this.clock().getTime(),Z=[...this.states].filter(([,X])=>X.status.tag==="running");for(let[X,Q]of Z){if(this.states.get(X)?.status.tag!=="running")continue;let G;try{let K=await this.deps.storage.getProgress(X,Q.orgId);G=DV8({persistedLastProgressAt:K?.lastProgressAt??null,currentRunStartedAt:Q.status.startedAt.getTime()})}catch(K){console.warn(`[RunRegistry] Reaper progress read failed for ${X}; skipping`,K);continue}if(!LV8({lastProgressAt:G,now:$,idleTimeoutMs:GP0}))continue;let J=await this.deps.storage.get(X,Q.orgId).catch(()=>null);if(J&&J.status!=="in_progress"){let K=this.states.get(X);if(K?.status.tag==="running")K.status.abortController.abort();this.states.delete(X);continue}console.warn(`[RunRegistry] Reaping stuck run for thread ${X} (idle > ${GP0/60000}m) ...`),$u4().add(1,{"org.id":Q.orgId,reason:"idle_timeout"}),await this.execute({type:"FORCE_FAIL",taskId:X,reason:"reaped"}).catch((K)=>{console.error("[RunRegistry] Reaper execute failed",K)})}}}var ah4=300000,a51,GP0,sh4,eh4,zV8=($)=>{let Z;return()=>Z??=$()},EV8,$u4;var e51=O(()=>{OV8();P5();a51=Number(process.env.RUN_IDLE_TIMEOUT_MS),GP0=Number.isFinite(a51)&&a51>0?a51:600000,sh4=new Set(["RUN_STARTED","RUN_RESUMED"]),eh4=new Set(["RUN_COMPLETED","RUN_FAILED","RUN_REQUIRES_ACTION","PREVIOUS_RUN_ABORTED"]),EV8=zV8(()=>D6.createUpDownCounter("decopilot.stream.inflight",{description:"Number of in-flight decopilot stream requests",unit:"{requests}"})),$u4=zV8(()=>D6.createCounter("decopilot.run.reaped",{description:"Number of decopilot runs force-failed by the progress-based reaper",unit:"{runs}"}))});async function jV8($){let{runId:Z}=$,X=WV8(),Q=await X.resolveRun(Z),Y=$.fenceToken??Q?.runFenceToken;if(!Q||Q.version!==2||Y==null)return;if(o51({status:Q.status,runFenceToken:Q.runFenceToken,fenceToken:Y}))return;if(!X.getJetStream())throw Error("JetStream unavailable for consume step");await NV8({runId:Z,fenceToken:Y,messageId:$.messageId,idleTimeoutMs:$.idleTimeoutMs??GP0},X,HV8)}var PV8=O(()=>{r51();e51()});var JP0,TO,AV8=()=>({active:TO.active,pending:TO.pending,max:JP0}),TV8=($)=>{if(TO.active>=JP0)console.log("[hostedHarness] run parked at concurrency cap",{active:TO.active,pending:TO.pending,max:JP0}),$?.();return TO.acquire()};var $91=O(()=>{N51();c8();P5();JP0=J1().decopilotMaxConcurrentHostedRuns,TO=H51(JP0);D6.createObservableGauge("hosted_runs.active",{description:"Hosted agent-loop runs executing on this pod",unit:"{runs}"}).addCallback(($)=>$.observe(TO.active));D6.createObservableGauge("hosted_runs.pending",{description:"Hosted agent-loop runs parked waiting for a slot on this pod",unit:"{runs}"}).addCallback(($)=>$.observe(TO.pending))});import{DBOS as M_}from"@dbos-inc/dbos-sdk";function Q91($){Z91=$}function RV8(){if(!Z91)throw Error("[hostedHarness] runtime not initialized \u2014 setHostedHarnessRuntime() must run before workflows fire");return Z91}async function Zu4($,Z){let X=RV8(),{request:Q}=$,Y=Z??await X.studioContextFactory(Q.organizationId,Q.userId);if(!Y)throw Error("user membership lost mid-dispatch");if(Q.runMetadata)Y.metadata.runMetadata=Q.runMetadata;let G=new AbortController,J=!1,K=new rr({emit:()=>IV8(X,$)}),W=await TV8(()=>{J=!0,IV8(X,$),K.arm()}).finally(()=>K.stop());try{if(J&&await Xu4($))throw Error("run cancelled while queued for a free runner");if(_h(Y,"in_progress",$.threadId),!Q.runMetadata?.taskBoardItemId)Xk8(Y,$.threadId);await X.dispatchRunFn({...Q,abortSignal:G.signal},Y,X.deps)}finally{W()}}async function Xu4($){try{return(await M_.getWorkflowStatus(Y91($.runId,$.fenceToken)))?.status==="CANCELLED"}catch(Z){return console.error(`[hostedHarness] could not read child status for run=${$.runId} fence=${$.fenceToken}`,Z),!1}}function Qu4($,Z,X,Q=1){let Y=X instanceof Error?X.message:String(X);return{messageId:PO($,Z),errorChunk:{type:"error",errorText:Y},seq:Q,finalSeq:Q}}function Yu4($){if(!($ instanceof Error))return;let Z=$.lastAckSeq;return typeof Z==="number"?Z+1:void 0}async function Gu4($,Z){let X=RV8(),{streamBuffer:Q}=X.deps,{messageId:Y,errorChunk:G,seq:J,finalSeq:K}=Qu4($.runId,$.fenceToken,Z,Yu4(Z));if(!Q){console.error(`[hostedHarness] no streamBuffer configured; dropping terminal error for run=${$.runId} fence=${$.fenceToken} messageId=${Y}`);return}if(!await Q.publishRawChunk($.runId,G,{fenceToken:$.fenceToken,seq:J})){console.error(`[hostedHarness] failed to publish terminal error chunk for run=${$.runId} fence=${$.fenceToken} messageId=${Y}`);return}await Q.publishDone($.runId,$.fenceToken,K)}async function Ju4($){try{await M_.runStep(()=>Zu4($),{name:"runHostedHarness",retriesAllowed:!1})}catch(Z){await M_.runStep(()=>Gu4($,Z),{name:"publishHostedHarnessFailure",retriesAllowed:!0}).catch((X)=>{console.error(`[hostedHarness] could not publish terminal error for run=${$.runId} fence=${$.fenceToken}`,X)})}}function Y91($,Z){return`decopilot-hosted:${$}:${Z}`}async function qV8($){return{workflowID:(await M_.startWorkflow(Ku4,{workflowID:Y91($.runId,$.fenceToken),queueName:JN,enqueueOptions:{queuePartitionKey:$.threadId}})($)).workflowID}}async function G91($,Z){await M_.cancelWorkflow(Y91($,Z))}var X91=1,Z91=null,IV8=($,Z)=>GK($.deps.streamBuffer,Z.runId,"waiting-capacity"),Ku4;var J91=O(()=>{c51();gh();$91();KQ();Ku4=M_.registerWorkflow(Ju4,{name:"hostedHarnessWorkflow",maxRecoveryAttempts:1000})});import{DBOS as ch}from"@dbos-inc/dbos-sdk";function H91($){d51($)}function N91($){K91=$}function Wu4(){if(!K91)throw Error("[threadGate] runtime not initialized \u2014 setThreadGateRuntime() must run before workflows fire");return K91}function Hu4($,Z=mj0){let X=$.runFenceToken;if(X)return{runFenceToken:X,claimedRequest:$,shouldPersistFence:!1};let Q=Z();return{runFenceToken:Q,claimedRequest:{...$,runFenceToken:Q},shouldPersistFence:!0}}async function Nu4($){let Z=Wu4(),{request:X}=$,Q=X.taskId??$.threadId;if(AS8({harnessId:X.harnessId}))await GK(Z.deps.streamBuffer,Q,"starting-run");let Y=await Z.studioContextFactory(X.organizationId,X.userId);if(!Y)throw Error("user membership lost mid-dispatch");H91(X.harnessId);let G=X.taskId??$.threadId,{runFenceToken:J,claimedRequest:K,shouldPersistFence:W}=Hu4(X);if(W)await Y.storage.threads.setRunFence(G,J);return{runFenceToken:J,hostedEnqueue:{runId:Q,fenceToken:J,threadId:$.threadId,request:K}}}async function Uu4($){if($.source!=="user-message")return;let{request:Z}=$;i1.capture({distinctId:Z.userId,event:"chat_message_started",groups:{organization:Z.organizationId},properties:{organization_id:Z.organizationId,agent_id:Z.agent,mode:Z.mode,thread_id:Z.taskId??$.threadId,credential_id:Z.models.credentialId}})}async function Fu4($,Z){if($.source!=="user-message")return;let{request:X}=$;i1.capture({distinctId:X.userId,event:"chat_message_failed",groups:{organization:X.organizationId},properties:{organization_id:X.organizationId,thread_id:X.taskId??$.threadId,agent_id:X.agent,model_id:X.models.thinking.id,mode:X.mode,error_category:"setup",error_message:Z}})}async function KP0($){H91($.request.harnessId),await ch.runStep(()=>Uu4($),{name:"trackMessageStarted"});let Z;try{Z=await ch.runStep(()=>Nu4($),{name:"dispatchRunAndWait",retriesAllowed:!0}),await qV8(Z.hostedEnqueue)}catch(Y){let G=Y instanceof Error?Y.message:String(Y);throw await ch.runStep(()=>Fu4($,G),{name:"trackMessageFailed"}),Y}let X=$.request.taskId??$.threadId,Q="messages"in $.request?void 0:$.request.messageId;return await ch.runStep(()=>jV8({runId:X,fenceToken:Z.runFenceToken,messageId:Q}),{name:"consumeRunProjection"}),{taskId:$.request.taskId??$.threadId}}async function wu4($){return KP0($)}async function EU($,Z){return H91($.request.harnessId),{workflowID:(await ch.startWorkflow(Bu4,{queueName:e3,enqueueOptions:{queuePartitionKey:$.threadId},workflowID:Z?.workflowID})($)).workflowID}}var W91=1,K91=null,Bu4;var MV8=O(()=>{rj0();S$();gh();PV8();J91();Bu4=ch.registerWorkflow(wu4,{name:"threadGateWorkflow",maxRecoveryAttempts:1000})});var q_=O(()=>{MV8();J91()});async function er($,Z,X){let Q=Z.organizationId,Y=Z.assignedBy??Z.createdBy,G=X.harnessId??"decopilot",J=await wX($,"smart"),K=fD(Q),W=await $.storage.threads.create({organization_id:Q,title:X.title,status:"in_progress",virtual_mcp_id:K,message_storage_version:2,harness_id:G,sandbox_provider_kind:"agent-sandbox",created_by:Y}),H={...W.metadata??{},...L_(G)?{read_only:!0}:{},...X.repo?{githubRepo:{url:X.repo.url,owner:X.repo.owner,name:X.repo.name,installationId:X.repo.installationId,connectionId:X.repo.connectionId}}:{}};await $.storage.threads.update(W.id,{metadata:H,...X.repo?{branch:br(W.id,X.repo.connectionId)}:{},updated_by:Y}),await $.storage.taskBoard.linkThread(Z.id,W.id,Q);let N={id:crypto.randomUUID(),role:"user",parts:[{type:"text",text:X.prompt}]};return await new zX({storage:$.storage.threads.messageParts(),orgId:Q,threadId:W.id,runId:W.id}).emitRequestMessage(N),await EU({threadId:W.id,source:"background-tool",request:{messages:[N],models:{credentialId:J.credentialId,thinking:{id:J.modelId,title:J.modelMeta.title}},agent:{id:K},temperature:X.temperature,toolApprovalLevel:"auto",mode:"default",organizationId:Q,userId:Y,harnessId:G,sandboxProviderKind:"agent-sandbox",taskId:W.id,runMetadata:{taskBoardItemId:Z.id}}}),{threadId:W.id}}var U91=O(()=>{dB();q_();zO();I6();tW();Kj0()});function Ou4($){let Z=new Map($.map((G)=>[G.id,G])),X=new Map;for(let G of Fj0($)){let J=kV8(G.owner,G.repo);X.set(J,[...X.get(J)??[],G])}if(X.size!==1)return null;let Q=[...X.values()][0],Y=Q.find((G)=>{let J=Z.get(G.connectionId);return J?HG0(J):!1})??Q[0];return{connectionId:Y.connectionId,owner:Y.owner,name:Y.repo,installationId:Y.installationId,url:`https://github.com/${Y.owner}/${Y.repo}`}}async function SV8($,Z){try{let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"}),Q=Ou4(X);if(!Q){let Y=Fj0(X),G=new Set(Y.map((J)=>kV8(J.owner,J.repo)));console.warn(`[task-board] claude-code skipped for org ${Z}: ${G.size} importable repos (needs exactly 1) \u2014 running Decopilot`)}return Q}catch(X){return console.warn("[task-board] repo lookup for claude-code failed",X),null}}async function VV8($,Z){try{return(await $.storage.organizationSettings.get(Z))?.flags?.claude_code_sandbox_enabled===!0}catch(X){return console.warn("[task-board] org flag lookup failed",X),!1}}function CV8($,Z,X){let Q=["You've been assigned this task. Complete it and finish with a pull request.","","You are running AUTONOMOUSLY \u2014 no human is watching, so drive this to "+"completion yourself. Make reasonable decisions and move on; do not stop to ask for confirmation.","",`Title: ${$.title}`];if($.description)Q.push("","Description:",$.description);if(Q.push("",`The repository ${Z.owner}/${Z.name} is already cloned at your working directory, on its own branch. \`git\` and \`gh\` are authenticated.`,""),X?.resolveConflict&&X.pr)Q.push(`Pull request #${X.pr.number} (${X.pr.url}) is approved but has a MERGE CONFLICT with its base branch.`,`Check that branch out (\`gh pr checkout ${X.pr.number}\`), merge or rebase the base branch into it, resolve the conflicts, and push to update the SAME pull request \u2014 do NOT open a new one. Resolve by preserving BOTH sides' intent; never blindly discard either side, and change only what the conflict requires.`,"");else if(X?.feedback)Q.push(X.pr?`A reviewer requested changes on pull request #${X.pr.number} (${X.pr.url}):`:"A reviewer requested changes on your previous work:",X.feedback,X.pr?`Check that branch out (\`gh pr checkout ${X.pr.number}\`) before editing, address the feedback, then push to update the SAME pull request \u2014 do NOT open a new one.`:"Address this feedback.","");return Q.push("How to finish:","- Make the change, commit it, push the branch, and open a pull request"+(X?.pr?" \u2014 or push to the existing one, per the instruction above.":"."),"- Change only what the task needs. Don't refactor around it.",`- Then move this task to review on the board: call \`mcp__studio__TASK_BOARD_ITEM_UPDATE\` with id "${$.id}" and status "in_review". Pass ONLY the fields you are changing.`,"- If the task turns out to need no code change, say why in your final message and move it to review anyway so a human can close it out.","",`(task id: ${$.id})`),Q.join(`
|
|
2747
|
+
`).trim();return{models:$.models,agent:$.agent,temperature:$.temperature,toolApprovalLevel:$.toolApprovalLevel,...$.toolAllowlist!==void 0?{toolAllowlist:$.toolAllowlist}:{},...$.maxAgentSteps!==void 0?{maxAgentSteps:$.maxAgentSteps}:{},...$.isSubagent!==void 0?{isSubagent:$.isSubagent}:{},...$.subtaskJobId!==void 0?{subtaskJobId:$.subtaskJobId}:{},...$.resumedFromBackground!==void 0?{resumedFromBackground:$.resumedFromBackground}:{},mode:$.mode,...$.windowSize!==void 0?{windowSize:$.windowSize}:{},...$.triggerId!==void 0?{triggerId:$.triggerId}:{},...$.runMetadata!==void 0?{runMetadata:$.runMetadata}:{},branch:Z.branch??$.branch??null,sandboxProviderKind:$.sandboxProviderKind,harnessId:$.harnessId,organizationId:$.organizationId,userId:$.userId,taskId:$.taskId,messageId:Z.messageId,...Z.runFenceToken!==void 0?{runFenceToken:Z.runFenceToken}:{},...$.isResume!==void 0?{isResume:$.isResume}:{},...X?{systemContext:X}:{}}}function qh4($,Z){let X=$.find((Q)=>Q.id===Z);if(!X)throw new mB("empty_request",`Persisted request message missing for messageId=${Z}`);if(X.role==="system")throw new mB("empty_request",`Persisted message ${Z} has role=system; expected non-system request message`);return X}function Mh4($){let Z=$.models;return{"decopilot.agent.id":$.agent.id,"decopilot.model.id":Z.thinking.id,"decopilot.credential.id":Z.credentialId,"decopilot.organization.id":$.organizationId,"decopilot.user.id":$.userId,"decopilot.thread.id":$.taskId??""}}async function gS8($,Z,X){return Gu1("decopilot.dispatchRunAndWait",async(Q)=>{let{taskId:Y,uiStream:G,registrySignal:J}=await Vh4($,Z,X,Q),K=X.streamBuffer,W=K?await K.createTailStream(Y,$.abortSignal,{deliverPolicy:"new",closeOnDone:!0}):null;if(K&&W){let H=K.pump(G,Y,J,$.organizationId);H.catch(()=>{});let N=W.getReader();try{while(!0){let{done:U}=await N.read();if(U)break}}finally{N.releaseLock()}await H}else{if(K)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"producer-fallback-no-pump",taskId:Y,hasTail:!!W,note:"createTailStream returned null \u2014 draining producer stream directly; projector persistence depends on streamBuffer publish health"}));let H=G.getReader();try{while(!0){let{done:N}=await H.read();if(N)break}}finally{H.releaseLock()}}return{taskId:Y}},Mh4($))}async function kh4($,Z,X,Q){let[Y,G,J]=await Promise.all([$.storage.threads.list(Q,{limit:9,agentId:X}).catch(()=>null),$.storage.interests.getForAgent(Z,X,Q).catch(()=>null),$.storage.virtualMcps.list(Z).catch(()=>null)]),K={};if(Y&&Y.total>0)K.recentThreads={total:Y.total,threads:Y.threads.map((W)=>({id:W.id,title:W.title,updated_at:W.updated_at}))};if(G&&G.interests.length>0)K.interests=G.interests.map((W)=>({title:W.title,summary:W.summary}));if(J)K.agents=J.map((W)=>({id:W.id,name:W.title,description:W.description,status:W.status}));return K}async function Sh4({virtualMcp:$,agentId:Z,organizationId:X,ctx:Q}){return GX0({virtualMcp:$,agentId:Z,organizationId:X,ctx:Q})}async function Vh4($,Z,X,Q){let{runRegistry:Y,streamBuffer:G}=X;d51($.harnessId);let J=$.harnessId;if(await Rh4(J,$.organizationId,Z),!bS8($))$={...$,messages:$.messages.map((H)=>H.id?H:{...H,id:_p()})};let K=!1,W;try{let H=$.models;Q.setAttribute("decopilot.harnessId",J),Z.sandboxPreference="agent-sandbox",Q.setAttribute("decopilot.dispatchTarget.sandboxProviderKind","agent-sandbox");let N=pj0({harnessId:J,sandboxProviderKind:"agent-sandbox"}),U=CS8(H),F=await KK(Z.db,$.organizationId,Z.organization?.role??Z.auth.user?.role);if(!JK(F,U.thinking.credentialId,U.thinking.id))throw Error("Model not allowed for your role");U=tj0(F,U);let w=$.windowSize??X3;if(!$.taskId)throw Error("dispatchRunAndWait: taskId is required");if(N)await GK(G,$.taskId,or[0]);let B=(H1)=>H1?Ih4(Z,$.organizationId,H1.credentialId,H1.id):Promise.resolve(void 0),[L,D,E,z,j,A,P,R,S]=await Promise.all([Z.storage.virtualMcps.findById($.agent.id,$.organizationId),B(U.thinking),B(U.fast),B(U.smart),B(U.image),B(U.webSearch),B(U.deepResearch),ij0(Z.storage.threads,{organization_id:$.organizationId,thread_id:$.taskId,userId:$.userId,defaultWindowSize:w}),kh4(Z,$.organizationId,$.agent.id,$.userId)]);if(N)await GK(G,$.taskId,or[1]);let M=D?{thinking:D,...E?{fast:E}:{},...z?{smart:z}:{},...j?{image:j}:{},...A?{webSearch:A}:{},...P?{deepResearch:P}:{}}:void 0,C=D?aG0(D):null;if(W=R.thread.id,Z.metadata.threadId=R.thread.id,Q.setAttribute("decopilot.thread.id",R.thread.id),R.thread.created_by!==$.userId)throw Error("You are not allowed to write to this thread because you are not the owner");if(C?.asyncResearch){let H1=[["thinking",U.thinking.id]];if(U.fast)H1.push(["fast",U.fast.id]);if(U.smart)H1.push(["smart",U.smart.id]);if(U.image)H1.push(["image",U.image.id]);for(let[o,A0]of H1)if(C.asyncResearch.canHandle(A0))throw Error(`Model "${A0}" can only be used as a Deep Research model. It is not usable as the ${o} model \u2014 set it in the Deep Research slot instead.`)}let v=R.thread.message_storage_version===2?new zX({storage:Z.storage.threads.messageParts(),orgId:$.organizationId,threadId:R.thread.id,runId:R.thread.id}):null;if(!L)throw new mB("agent_not_found","Agent not found");let b=await Sh4({virtualMcp:L,agentId:$.agent.id,organizationId:$.organizationId,ctx:Z});if($.isResume)await Y.execute({type:"RESUME",taskId:R.thread.id,orgId:$.organizationId,userId:$.userId,abortController:new AbortController,podId:l51()});else await Y.execute({type:"START",taskId:R.thread.id,orgId:$.organizationId,userId:$.userId,abortController:new AbortController,podId:l51(),runConfig:{models:$.models,agent:$.agent,temperature:$.temperature,toolApprovalLevel:$.toolApprovalLevel,mode:$.mode,windowSize:$.windowSize,triggerId:$.triggerId},messageId:$.messageId});K=!0,await Z.storage.threads.clearCancelRequested(R.thread.id);let p;if($.runFenceToken)p=$.runFenceToken;else p=mj0(),await Z.storage.threads.setRunFence(R.thread.id,p);let y=Y.getAbortSignal(R.thread.id);if(!y)throw await Y.execute({type:"FINISH",taskId:R.thread.id,threadStatus:"failed"}),Error("Run was cancelled immediately after starting");if($.abortSignal){let H1=$.abortSignal;if(H1.aborted)await Y.execute({type:"CANCEL",taskId:R.thread.id});else H1.addEventListener("abort",()=>{Y.execute({type:"CANCEL",taskId:R.thread.id}).catch(()=>{})},{once:!0})}if(!$.isResume)G?.purge(R.thread.id);let Z0=[],U0,k0;if(bS8($)){if(k0=await R.loadHistory(w),U0=qh4(k0,$.messageId),$.systemContext)Z0=[{id:`system-${$.messageId}`,role:"system",parts:[{type:"text",text:$.systemContext}]}]}else{Z0=$.messages.filter((o)=>o.role==="system");let H1=$.messages.find((o)=>o.role!=="system");if(U0=H1?(await zj0([H1],Z,{threadId:R.thread.id})).find((o)=>o.role!=="system"):void 0,!$.isResume){if(!U0)throw new mB("empty_request","No user message found in input \u2014 expected at least one non-system message");if(v)await v.emitUserMessage(U0).catch((o)=>{console.error("[decopilot:stream] v2 user-message emit failed",o)})}}if(U0)await RS8(G,R.thread.id,U0);let $0=[],e=Z.organization,I0=Date.now(),Q0=U0?(await jj0([U0],Z))[0]:void 0;if(!Q0||!U0)throw new mB("empty_request","No user message found in input \u2014 expected at least one non-system message");jS8($.models,[Q0]);let R0=await ES8({ctx:Z,threadId:R.thread.id,userMessage:U0,windowSize:w,isSubagent:$.isSubagent===!0,systemMessages:Z0}),m0={url:"",headers:{},expiresAt:0},r0=void 0,K0=void 0,S0={cwd:null},C0=typeof b.metadata?.instructions==="string"?b.metadata.instructions:void 0,q0={taskId:$.taskId,isSubagent:$.isSubagent,subtaskJobId:$.subtaskJobId,resumedFromBackground:$.resumedFromBackground,virtualMcp:b,branch:$.branch,messages:R0,modelSources:M,mcpSource:r0,objectStorageSource:K0,userContext:S},X0={harnessId:J,threadId:R.thread.id,userMessage:Q0,harness:{sessionId:void 0},workspace:S0,models:U,mcp:m0,mode:$.mode,temperature:$.temperature,toolApprovalLevel:$.toolApprovalLevel,toolAllowlist:$.toolAllowlist??null,maxAgentSteps:$.maxAgentSteps,user:{id:$.userId,email:Z.auth.user?.email??""},organizationId:$.organizationId,organizationSlug:e.slug,agent:{id:$.agent.id,instructions:C0},triggerId:$.triggerId,currentThreadTitle:R.thread.title,runFenceToken:p};if(N)await GK(G,$.taskId,or[2]);let W0=L_(J),h0=W0?await Z.storage.threads.getAckedSeq(R.thread.id):0;if(h0>0)console.log("[dispatch] resuming a sandbox-hosted turn",{runId:R.thread.id,fromSeq:h0});let w0=async function*(){let H1={...X0,signal:y};if(w61(H1,q0),N)await GK(G,R.thread.id,or[3]);yield*(W0?new m$1({ctx:Z,harnessId:J,virtualMcpId:b.id,...h0>0?{resume:{reason:"the Studio process driving the previous attempt stopped"}}:{},branch:await Nq8(Z,{threadId:R.thread.id,agentRepo:b.metadata?.githubRepo,runBranch:$.branch}),credential:D?{providerId:D.providerId,apiKey:D.apiKey,...D.baseUrl?{baseUrl:D.baseUrl}:{}}:null}):new D61({ctx:Z,harnessId:J})).dispatch(H1)},j0=Ah4(()=>Th4({runId:R.thread.id,fenceToken:p,streamBuffer:G??{publishRawChunk:async()=>!1,publishDone:async()=>!1},chunks:MS8(w0()),...W0?{startSeq:h0,initialAckSeq:h0,onPublished:(H1)=>Z.storage.threads.bumpAckedSeq(R.thread.id,p,H1)}:{},errorMessageId:PO(R.thread.id,p),loadOriginalMessages:v?async()=>(await Z.storage.threads.messageParts().loadWindow(R.thread.id,{limit:1})).messages.map(nj0):void 0,title:{currentThreadTitle:R.thread.title,threadId:R.thread.id,persistTitle:async(H1,o)=>{await Z.storage.threads.update(H1,{title:o})}},hooks:{onStep:()=>{let H1=Y.dispatch({type:"STEP_DONE",taskId:R.thread.id});$0.push(Y.react(H1).catch((o)=>{console.error("[decopilot:stream] onStepFinish reactor failed",o)}))},onFinish:async(H1,o)=>{let A0=$0.length,v0=performance.now();if(await Promise.allSettled($0),xS8.record(performance.now()-v0,{phase:"settle"}),y.aborted)return;await m8(0);let F1=vS8?UD():null,f1=performance.now(),d8=oj0(o,H1?.parts);await Y.execute({type:"FINISH",taskId:R.thread.id,threadStatus:d8});let o0=performance.now()-f1;if(xS8.record(o0,{phase:"save"}),vS8&&F1){let m1=UD()??F1,v8=-1;try{v8=JSON.stringify(H1)?.length??-1}catch{}console.warn(JSON.stringify({msg:"decopilot-finish-trace",threadId:R.thread.id,pendingOps:A0,saveMs:Math.round(o0),parts:H1?.parts?.length??0,messageBytes:v8,rssDelta:m1.rss-F1.rss,heapUsedDelta:m1.heapUsed-F1.heapUsed,externalDelta:m1.external-F1.external}))}},onError:(H1)=>{if(y.aborted){i1.capture({distinctId:$.userId,event:"chat_message_aborted",groups:{organization:$.organizationId},properties:{organization_id:$.organizationId,thread_id:R.thread.id,agent_id:$.agent.id,model_id:U.thinking.id,mode:$.mode,duration_ms:Date.now()-I0,is_resume:$.isResume??!1}});return}console.error("[decopilot] stream error:",WU(H1)),Y.execute({type:"FINISH",taskId:R.thread.id,threadStatus:"failed"}).catch((o)=>{console.error("[decopilot:stream] onError reactor failed",o)})}}}));return{taskId:R.thread.id,uiStream:j0,registrySignal:y}}catch(H){if(K&&W)Y.execute({type:"FINISH",taskId:W,threadStatus:"failed"}).catch((N)=>{console.error("[decopilot:stream] catch-block reactor failed",N)});throw H}}var xS8,vS8,fS8;var rj0=O(()=>{G81();S$();Vz8();Kj0();tW();tb();LS8();Kh();J81();FB();zS8();zO();u51();Ch();PS8();gh();y51();kS8();hh();P5();_S8();W5();xS8=D6.createHistogram("decopilot.finish.duration",{description:"Wall time of onFinish flush segments, tagged by phase",unit:"ms"}),vS8=process.env.DECOPILOT_FINISH_TRACE==="1";fS8=["decopilot","claude-code"]});function hS8($){return TS8($)||IS8($)}async function Ch4($){let Z=$.getReader();try{while(!0){let{done:X}=await Z.read();if(X)break}}finally{Z.releaseLock()}}function _h4($,Z){let X=$.getReader(),Q=!1,Y=()=>{if(Q)return;Q=!0,X.releaseLock()};return new ReadableStream({async pull(G){try{let{done:J,value:K}=await X.read();if(J)Y(),G.close();else G.enqueue(K)}catch(J){Z(J),Y(),G.error(J)}},async cancel(G){await X.cancel(G),Y()}})}async function uS8($){if(!$.chunks&&!$.chunkStream)throw Error("projectChunks requires chunks or chunkStream");let Z=null,X=!1,Q=void 0,Y={inputTokens:0,outputTokens:0,totalTokens:0},G=[],J=null,K=(B)=>{if(J===null)J=B;throw B},W=$.chunks?async function*(){try{for await(let B of $.chunks){if(hS8(B))continue;yield B}}catch(B){throw Z=B,B}}():void 0,H=$.chunkStream?_h4($.chunkStream,(B)=>{Z=B}).pipeThrough(new TransformStream({transform(B,L){if(!hS8(B))L.enqueue(B)}})):void 0,N={emitStepParts:(B)=>$.persistence.emitStepParts(B).catch(K),emitFinal:(B)=>$.persistence.emitFinal(B).catch(K),emitError:(B,L)=>$.persistence.emitError(B,L).catch(K)},{uiStream:U,whenComplete:F}=yj0({chunks:W,chunkStream:H,originalMessages:$.originalMessages??[],title:$.title?{currentThreadTitle:$.title.currentThreadTitle,threadId:$.title.threadId,persistTitle:$.title.persistTitle}:{currentThreadTitle:void 0,threadId:"projector",persistTitle:async()=>{}},persistence:N,sanitizeErrorText:$.sanitizeErrorText,errorMessageId:$.errorMessageId,generateMessageId:$.generateMessageId,hooks:{onUsage:(B)=>{Y={inputTokens:B.inputTokens,outputTokens:B.outputTokens,totalTokens:B.totalTokens}},onError:()=>{X=!0},onFinish:(B,L)=>{Q=L,G=Array.isArray(B.parts)?B.parts.filter((D)=>D!=null&&typeof D==="object"&&("type"in D)):[]}}});if(await Ch4(U).catch(()=>{}),await F,J!==null)throw J;if(Z!==null)throw Z;return{failed:X&&Q===void 0,finishReason:Q,usage:Y,finalParts:G}}var cS8=O(()=>{b51();gh()});var ar=786432;function vh4($){if(/[.*>\s]/.test($))throw Error("Invalid NATS subject token")}function AO($){return vh4($),`${aj0}.${$}`}function lS8($){let Z=`${$.runId}:${$.fenceToken}:${$.seq}`;return $.fragmentIndex===void 0?Z:`${Z}:frag:${$.fragmentIndex}`}function fh4($){return`${$.runId}:${$.fenceToken}:done:${$.finalSeq}`}function dS8($){if(!$)return null;let Z=Number($);return Number.isInteger(Z)&&Z>0?Z:null}function bh4($){if(!$)return null;let Z=Number($);return Number.isInteger(Z)&&Z>=0?Z:null}function yh4($){if(!$)return null;let Z=$.split(":"),[X,Q,Y,G,J]=Z;if(!X||!Q||!Y)return null;if(Y==="done"){let W=dS8(G);return Z.length===4&&W!==null?{kind:"done",runId:X,fenceToken:Q,finalSeq:W}:null}if(Y==="ckpt")return null;let K=dS8(Y);if(K===null)return null;if(Z.length===3)return{kind:"chunk",runId:X,fenceToken:Q,seq:K,fragmentIndex:null};if(Z.length===5&&G==="frag"){let W=bh4(J);return W===null?null:{kind:"chunk",runId:X,fenceToken:Q,seq:K,fragmentIndex:W}}return null}function i51($,Z){let X=AO(Z.runId),Q=m51.encode(JSON.stringify({p:$}));if(Q.length>xh4)return[];if(Q.length<=ar)return[{subject:X,data:Q,msgId:Z.dedup?lS8({runId:Z.runId,...Z.dedup}):void 0}];let Y=Math.ceil(Q.length/ar),G=[];for(let J=0;J<Y;J++)G.push({subject:X,data:Q.slice(J*ar,(J+1)*ar),headers:{[mS8]:String(J),[iS8]:String(Y)},msgId:Z.dedup?lS8({runId:Z.runId,...Z.dedup,fragmentIndex:J}):void 0});return G}function nS8($){return{subject:AO($.runId),data:m51.encode(JSON.stringify({done:!0,finalSeq:$.finalSeq})),msgId:fh4($)}}function pS8($){return{subject:AO($),data:m51.encode(JSON.stringify({done:!0}))}}function gh4($){let Z=$.reduce((Y,G)=>Y+(G?.length??0),0),X=new Uint8Array(Z),Q=0;for(let Y of $){if(!Y)continue;X.set(Y,Q),Q+=Y.length}return X}function sj0(){let $=null;return new TransformStream({transform(Z,X){let Q=Z.headers?.get(iS8);if(!Q){X.enqueue(Z);return}let Y=Number(Q),G=Number(Z.headers?.get(mS8)??"0");if(G===0)$={total:Y,received:0,parts:Array(Y)};else if(!$||$.total!==Y)return;if(!$.parts[G])$.received++;if($.parts[G]=Z.data,$.received<$.total)return;let J=gh4($.parts);$=null,X.enqueue({subject:Z.subject,data:J,headers:Z.headers})}})}function hh4($){return typeof $==="number"&&Number.isInteger($)&&$>0}function ch4($){let Z=yh4($.headers?.get("Nats-Msg-Id")||void 0),X;try{X=JSON.parse(uh4.decode($.data))}catch{return null}if(!X||typeof X!=="object")return null;let Q=X;if(Q.done===!0)return{kind:"done",runId:Z?.kind==="done"?Z.runId:null,fenceToken:Z?.kind==="done"?Z.fenceToken:null,envelopeFinalSeq:hh4(Q.finalSeq)?Q.finalSeq:null,msgIdFinalSeq:Z?.kind==="done"?Z.finalSeq:null};if("p"in Q)return{kind:"chunk",seq:Z?.kind==="chunk"?Z.seq:null,runId:Z?.kind==="chunk"?Z.runId:null,fenceToken:Z?.kind==="chunk"?Z.fenceToken:null,chunk:Q.p};return null}function ej0(){return new TransformStream({transform($,Z){let X=ch4($);if(X)Z.enqueue(X)}})}var aj0="decopilot.stream",mS8="Dp-Frag-Idx",iS8="Dp-Frag-Total",xh4=33554432,m51,uh4;var tS8=O(()=>{m51=new TextEncoder;uh4=new TextDecoder});var $P0=O(()=>{tS8()});var zU="DECOPILOT_STREAMS";var n51=O(()=>{$P0()});function oS8($,Z){return new TransformStream({transform(X,Q){if(X.runId!==$||X.fenceToken!==Z)return;Q.enqueue(X)}})}function rS8(){let $=1;return new TransformStream({transform(Z,X){if(Z.kind==="done"){X.enqueue(Z);return}if(Z.seq===null){X.error(Error("projector chunk missing seq"));return}if(Z.seq<$)return;if(Z.seq>$){X.error(new sr($,Z.seq));return}$++,X.enqueue(Z)}})}function aS8($){let Z=$.getReader(),X=!1,Q=0,Y=()=>{if(X)return;X=!0,Z.releaseLock()};return new ReadableStream({async pull(G){for(;;){let{done:J,value:K}=await Z.read();if(J){await Z.cancel(),Y(),G.error(Error("reader stopped before done"));return}let W=K;if(W.kind==="done"){if(!(W.envelopeFinalSeq!=null&&W.envelopeFinalSeq===W.msgIdFinalSeq))continue;if(W.envelopeFinalSeq!==Q){await Z.cancel(),Y(),G.error(new sr(Q+1,null));return}await Z.cancel(),Y(),G.close();return}Q=W.seq??Q,G.enqueue(W.chunk);return}},async cancel(G){await Z.cancel(G),Y()}})}function lh4($){if(Symbol.asyncIterator in $)return $[Symbol.asyncIterator]();let Z=$[Symbol.iterator]();return{next:async()=>Z.next(),return:async(X)=>Z.return?Z.return(X):{done:!0,value:X}}}function XP0($){let Z=lh4($.messages),X=$.idleTimeoutMs,Q=!1,Y=(G)=>{if(Q)return;Q=!0,Z.return?.(G).catch(()=>{}),$.onCancel?.()};return new ReadableStream({async pull(G){if(X===void 0){let{done:N,value:U}=await Z.next();if(N){G.close();return}G.enqueue(U);return}let J=new AbortController,K=Z.next().then((N)=>{return J.abort(),N}),W=m8(X,{signal:J.signal}).then(()=>"idle").catch(()=>"cancelled"),H=await Promise.race([K,W]);if(H==="idle"){G.error(new ZP0(X));return}if(H==="cancelled")return;if(H.done){G.close();return}G.enqueue(H.value)},async cancel(G){Y(G)}})}var ZP0,sr;var QP0=O(()=>{W5();ZP0=class ZP0 extends Error{idleTimeoutMs;constructor($){super("producer produced no output before timeout");this.idleTimeoutMs=$;this.name="StreamIdleTimeoutError"}};sr=class sr extends Error{expectedSeq;gotSeq;constructor($,Z){super(Z===null?`missing seq ${$} (stream ended at the fenced done)`:`missing seq ${$} (next delivered is ${Z})`);this.expectedSeq=$;this.gotSeq=Z;this.name="StreamGapError"}}});function dh4($){let X=XP0({messages:$.messages,idleTimeoutMs:$.idleTimeoutMs,onCancel:$.onDone}).pipeThrough(sj0()).pipeThrough(ej0()).pipeThrough(oS8($.runId,$.fenceToken)).pipeThrough(rS8());return aS8(X)}async function eS8($){let X=await(await $.js.consumers.get(zU,{filter_subjects:AO($.runId),deliver_policy:sS8.DeliverPolicy.All})).consume();async function*Q(){try{for await(let Y of X)yield{subject:Y.subject,data:Y.data,headers:Y.headers}}finally{X.stop()}}return dh4({messages:Q(),runId:$.runId,fenceToken:$.fenceToken,idleTimeoutMs:$.idleTimeoutMs,onDone:()=>X.stop()})}var sS8;var $V8=O(()=>{n51();QP0();$P0();sS8=k(SD(),1)});async function mh4($){let X=($.requestMessageId?await $.messageParts.maxCreatedAtMsForMessage($.runId,$.requestMessageId):null)??await $.messageParts.maxCreatedAtMsForRun($.runId);return new zX({storage:$.messageParts,orgId:$.orgId,threadId:$.runId,runId:$.runId,baseTimeMs:(X??Date.now())+1})}async function ZV8($){let Z=await mh4($),X=$.replaceFinal?(Q)=>Z.replaceFinal(Q):(Q)=>Z.emitFinal(Q);return{emitStepParts:(Q)=>Z.emitStepParts(Q),emitFinal:X,emitError:(Q,Y)=>Z.emitError(Q,Y)}}var XV8=O(()=>{zO()});function YP0($,Z){ih4.add(1,{"org.id":Z??"unknown"})}var ih4;var QV8=O(()=>{P5();ih4=D6.createCounter("decopilot.projector.poison_runs",{description:"Number of decopilot runs that exhausted retries and were sent to the DLQ",unit:"{runs}"})});class p51{intervalMs;lastBumpMs=new Map;constructor($=3000){this.intervalMs=$}shouldBump($,Z=Date.now()){let X=this.lastBumpMs.get($);if(X!==void 0&&Z-X<this.intervalMs)return!1;return this.lastBumpMs.set($,Z),!0}clear($){this.lastBumpMs.delete($)}}function YV8($,Z,X,Q){return $.pipeThrough(new TransformStream({transform(Y,G){if(X.shouldBump(Z))Q();G.enqueue(Y)},flush(){X.clear(Z)}}))}function nh4($){return`liveness: no stream events for ${Math.round($/60000)}m`}function o51($){return $.runFenceToken!==null&&$.runFenceToken!==$.fenceToken}function JV8($){t51=$}function KV8(){if(!t51)throw Error("[projector-workflow] runtime not initialized \u2014 setProjectorWorkflowRuntime() must run before workflows fire");return t51}function WV8(){return KV8()}async function HV8($,Z,X){let Q=KV8(),Y=Q.getJetStream();if(!Y)throw Error("JetStream unavailable");let G=(await Q.messageParts.loadWindow($.runId,{limit:500})).messages.map(nj0);return{chunkCount:0,attempts:1,outcome:await uS8({chunkStream:YV8(await eS8({js:Y,runId:$.runId,fenceToken:$.fenceToken,idleTimeoutMs:$.idleTimeoutMs}),$.runId,ph4,()=>{Q.bumpProgress({runId:$.runId,orgId:Z}).catch(()=>{})}),persistence:await ZV8({messageParts:Q.messageParts,orgId:Z,runId:$.runId,requestMessageId:$.messageId,replaceFinal:!0}),originalMessages:G,errorMessageId:PO($.runId,$.fenceToken),title:{threadId:$.runId,currentThreadTitle:X,persistTitle:async(K,W)=>{await Q.persistTitle($.runId,Z,W),await Q.onTitleUpdated({runId:$.runId,orgId:Z,title:W})}}})}}async function GV8($,Z,X){let Q=await $.resolveRun(Z).catch(()=>null);return Q!==null&&Q.runFenceToken===X&&["completed","failed","requires_action"].includes(Q.status)}async function NV8($,Z,X){let Q=await th4($,Z);if("skip"in Q)return;let Y=Q.row.orgId,G=Q.row.createdBy??$.runId,J=Q.row.title;try{let{outcome:K}=await X($,Y,J),W=K?.failed?"failed":oj0(K?.finishReason,K?.finalParts);if(W==="failed"){let H=K?.finishReason?`harness reported an error: ${K.finishReason}`:"harness reported an error";if(YP0($.runId,Y),await Z.markRunFailed($.runId,Y,H,"harness"))await Z.recordFailed({runId:$.runId,orgId:Y,distinctId:G,reason:H,kind:"harness"})}else if(W==="requires_action")await Z.markRunRequiresAction($.runId,Y),await Z.clearSynthesizedError($.runId,$.fenceToken);else{if(await Z.completeRunIfNotCompleted($.runId,Y))await Z.recordCompleted({runId:$.runId,orgId:Y,distinctId:G,usage:K?.usage??{inputTokens:0,outputTokens:0,totalTokens:0}});await Z.clearSynthesizedError($.runId,$.fenceToken)}await Z.purgeRun($.runId,$.fenceToken)}catch(K){if(K instanceof sr){if(await GV8(Z,$.runId,$.fenceToken)){await Z.clearSynthesizedError($.runId,$.fenceToken),await Z.purgeRun($.runId,$.fenceToken);return}let F=`stream truncated before projection could replay it: ${K.message}`;if(YP0($.runId,Y),await Z.markRunFailed($.runId,Y,F,"projection"))await Z.recordFailed({runId:$.runId,orgId:Y,distinctId:G,reason:F,kind:"projection"});await Z.purgeRun($.runId,$.fenceToken);return}let W=K instanceof ZP0;if(W&&await GV8(Z,$.runId,$.fenceToken)){await Z.purgeRun($.runId,$.fenceToken);return}let H=W?nh4(K.idleTimeoutMs):K instanceof Error?K.message:String(K),N=W?"liveness":"projection";if(YP0($.runId,Y),await Z.markRunFailed($.runId,Y,H,N))await Z.recordFailed({runId:$.runId,orgId:Y,distinctId:G,reason:H,kind:N});if(W)await Z.clearSynthesizedError($.runId,$.fenceToken);throw K}}async function th4($,Z){let X=await Z.resolveRun($.runId);if(!X)return{skip:"missing"};if(o51({status:X.status,runFenceToken:X.runFenceToken,fenceToken:$.fenceToken}))return{skip:"stale",row:X};if(X.version!==2)return{skip:"legacy-v1",row:X};return{row:X}}var t51=null,ph4;var r51=O(()=>{cS8();$V8();QP0();XV8();QV8();u51();ph4=new p51});function UV8($,Z){switch($.type){case"START":{let X={type:"RUN_STARTED",taskId:$.taskId,orgId:$.orgId,userId:$.userId,abortController:$.abortController,runConfig:$.runConfig,podId:$.podId,messageId:$.messageId};if(Z?.status.tag==="running")return[{type:"PREVIOUS_RUN_ABORTED",taskId:$.taskId,orgId:Z.orgId},X];return[X]}case"STEP_DONE":{if(Z?.status.tag!=="running")return[];return[{type:"STEP_COMPLETED",taskId:$.taskId,orgId:Z.orgId,stepCount:Z.status.stepCount+1}]}case"FINISH":{if(Z==null||Z.status.tag!=="running")return[];let{stepCount:X}=Z.status;if($.threadStatus==="completed")return[{type:"RUN_COMPLETED",taskId:$.taskId,orgId:Z.orgId,stepCount:X}];if($.threadStatus==="requires_action")return[{type:"RUN_REQUIRES_ACTION",taskId:$.taskId,orgId:Z.orgId,stepCount:X}];return[{type:"RUN_FAILED",taskId:$.taskId,orgId:Z.orgId,reason:"error"}]}case"CANCEL":{if(Z?.status.tag!=="running")return[];return[{type:"RUN_FAILED",taskId:$.taskId,orgId:Z.orgId,reason:"cancelled"}]}case"RESUME":{if(Z?.status.tag==="running")return[];return[{type:"RUN_RESUMED",taskId:$.taskId,orgId:$.orgId,userId:$.userId,abortController:$.abortController,podId:$.podId}]}case"FORCE_FAIL":{if($.reason==="ghost")return[{type:"RUN_FAILED",taskId:$.taskId,orgId:Z?.orgId??$.orgId,reason:$.reason,expectedFenceToken:$.expectedFenceToken??null}];if(Z?.status.tag!=="running")return[];return[{type:"RUN_FAILED",taskId:$.taskId,orgId:Z.orgId,reason:$.reason}]}}}function FV8($,Z,X=new Date){switch(Z.type){case"RUN_STARTED":return{taskId:Z.taskId,orgId:Z.orgId,userId:Z.userId,status:{tag:"running",abortController:Z.abortController,stepCount:0,startedAt:X}};case"RUN_RESUMED":return{taskId:Z.taskId,orgId:Z.orgId,userId:Z.userId,status:{tag:"running",abortController:Z.abortController,stepCount:0,startedAt:X}};case"STEP_COMPLETED":if($?.status.tag!=="running")return $;return{...$,status:{...$.status,stepCount:Z.stepCount}};case"RUN_COMPLETED":return;case"RUN_REQUIRES_ACTION":return;case"RUN_FAILED":return;case"PREVIOUS_RUN_ABORTED":return}}async function wV8($,Z,X,Q){let{storage:Y,sseHub:G}=Q,J=await Y.get($,Z);G.emit(Z,sK($,X,{virtualMcpId:J?.virtual_mcp_id??void 0,createdBy:J?.created_by,triggerId:J?.trigger_id,title:J?.title,branch:J?.branch??null,harnessId:J?.harness_id??void 0,createdAt:J?.created_at,updatedAt:J?.updated_at})),G.emit(Z,V90($,X))}async function rh4($,Z){let{storage:X,sseHub:Q}=Z;switch($.type){case"RUN_STARTED":{await X.update($.taskId,$.orgId,{status:"in_progress",run_config:$.runConfig??null,run_started_at:new Date().toISOString(),last_progress_at:null,failure_reason:null,failure_kind:null});let Y=await X.get($.taskId,$.orgId);Q.emit($.orgId,sK($.taskId,"in_progress",{virtualMcpId:Y?.virtual_mcp_id??void 0,createdBy:Y?.created_by,triggerId:Y?.trigger_id,title:Y?.title,branch:Y?.branch??null,harnessId:Y?.harness_id??void 0,createdAt:Y?.created_at,updatedAt:Y?.updated_at,messageId:$.messageId}));return}case"RUN_RESUMED":{await X.update($.taskId,$.orgId,{status:"in_progress",run_started_at:new Date().toISOString(),last_progress_at:null,failure_reason:null,failure_kind:null});let Y=await X.get($.taskId,$.orgId);Q.emit($.orgId,sK($.taskId,"in_progress",{virtualMcpId:Y?.virtual_mcp_id??void 0,createdBy:Y?.created_by,triggerId:Y?.trigger_id,title:Y?.title,branch:Y?.branch??null,harnessId:Y?.harness_id??void 0,createdAt:Y?.created_at,updatedAt:Y?.updated_at}));return}case"STEP_COMPLETED":Q.emit($.orgId,Om0($.taskId,$.stepCount));return;case"RUN_COMPLETED":await wV8($.taskId,$.orgId,"completed",Z);return;case"RUN_REQUIRES_ACTION":await wV8($.taskId,$.orgId,"requires_action",Z);return;case"RUN_FAILED":{if($.reason==="ghost"){if(!await X.forceFailIfInProgress($.taskId,$.orgId,$.expectedFenceToken))return;await X.update($.taskId,$.orgId,{run_config:null,run_started_at:null})}else{if(!await X.forceFailIfInProgress($.taskId,$.orgId))return;await X.update($.taskId,$.orgId,{run_config:null,run_started_at:null,...$.reason==="reaped"?{failure_reason:oh4,failure_kind:"stall"}:{}})}let Y=await X.get($.taskId,$.orgId);Q.emit($.orgId,sK($.taskId,"failed",{virtualMcpId:Y?.virtual_mcp_id??void 0,createdBy:Y?.created_by,triggerId:Y?.trigger_id,title:Y?.title,branch:Y?.branch??null,harnessId:Y?.harness_id??void 0,createdAt:Y?.created_at,updatedAt:Y?.updated_at})),Q.emit($.orgId,V90($.taskId,"failed"));return}case"PREVIOUS_RUN_ABORTED":return}}async function BV8($,Z){for(let{event:X}of $)await rh4(X,Z)}var oh4="Run stalled \u2014 no progress within the idle timeout window";var OV8=O(()=>{I6()});function LV8($){return $.now-$.lastProgressAt>$.idleTimeoutMs}function DV8($){return Math.max($.persistedLastProgressAt??Number.NEGATIVE_INFINITY,$.currentRunStartedAt)}class s51{deps;clock;states=new Map;reaperTimer=null;constructor($,Z=()=>new Date){this.deps=$;this.clock=Z;this.reaperTimer=setInterval(()=>{this.reapStaleRuns().catch((X)=>{console.error("[RunRegistry] Reaper sweep failed",X)})},ah4)}async execute($){let Z=this.dispatch($);return await this.react(Z),Z}dispatch($){let Z=this.states.get($.taskId),X=UV8($,Z),Q=[];for(let Y of X){let G=this.states.get(Y.taskId);if(Y.type==="PREVIOUS_RUN_ABORTED"||Y.type==="RUN_FAILED"){if(G?.status.tag==="running")G.status.abortController.abort()}let J=FV8(G,Y,this.clock());if(J===void 0)this.states.delete(Y.taskId);else this.states.set(Y.taskId,J);if(Q.push({event:Y,state:J}),sh4.has(Y.type))EV8().add(1,{"org.id":Y.orgId});else if(eh4.has(Y.type)&&G?.status.tag==="running")EV8().add(-1,{"org.id":Y.orgId})}return Q}react($){return BV8($,this.deps)}getAbortSignal($){let Z=this.states.get($);if(Z?.status.tag==="running")return Z.status.abortController.signal;return null}isRunning($){return this.states.get($)?.status.tag==="running"}async stopAll(){for(let[,$]of this.states)if($.status.tag==="running")$.status.abortController.abort();this.states.clear()}dispose(){if(this.reaperTimer)clearInterval(this.reaperTimer),this.reaperTimer=null}async reapStaleRuns(){let $=this.clock().getTime(),Z=[...this.states].filter(([,X])=>X.status.tag==="running");for(let[X,Q]of Z){if(this.states.get(X)?.status.tag!=="running")continue;let G;try{let K=await this.deps.storage.getProgress(X,Q.orgId);G=DV8({persistedLastProgressAt:K?.lastProgressAt??null,currentRunStartedAt:Q.status.startedAt.getTime()})}catch(K){console.warn(`[RunRegistry] Reaper progress read failed for ${X}; skipping`,K);continue}if(!LV8({lastProgressAt:G,now:$,idleTimeoutMs:GP0}))continue;let J=await this.deps.storage.get(X,Q.orgId).catch(()=>null);if(J&&J.status!=="in_progress"){let K=this.states.get(X);if(K?.status.tag==="running")K.status.abortController.abort();this.states.delete(X);continue}console.warn(`[RunRegistry] Reaping stuck run for thread ${X} (idle > ${GP0/60000}m) ...`),$u4().add(1,{"org.id":Q.orgId,reason:"idle_timeout"}),await this.execute({type:"FORCE_FAIL",taskId:X,reason:"reaped"}).catch((K)=>{console.error("[RunRegistry] Reaper execute failed",K)})}}}var ah4=300000,a51,GP0,sh4,eh4,zV8=($)=>{let Z;return()=>Z??=$()},EV8,$u4;var e51=O(()=>{OV8();P5();a51=Number(process.env.RUN_IDLE_TIMEOUT_MS),GP0=Number.isFinite(a51)&&a51>0?a51:600000,sh4=new Set(["RUN_STARTED","RUN_RESUMED"]),eh4=new Set(["RUN_COMPLETED","RUN_FAILED","RUN_REQUIRES_ACTION","PREVIOUS_RUN_ABORTED"]),EV8=zV8(()=>D6.createUpDownCounter("decopilot.stream.inflight",{description:"Number of in-flight decopilot stream requests",unit:"{requests}"})),$u4=zV8(()=>D6.createCounter("decopilot.run.reaped",{description:"Number of decopilot runs force-failed by the progress-based reaper",unit:"{runs}"}))});async function jV8($){let{runId:Z}=$,X=WV8(),Q=await X.resolveRun(Z),Y=$.fenceToken??Q?.runFenceToken;if(!Q||Q.version!==2||Y==null)return;if(o51({status:Q.status,runFenceToken:Q.runFenceToken,fenceToken:Y}))return;if(!X.getJetStream())throw Error("JetStream unavailable for consume step");await NV8({runId:Z,fenceToken:Y,messageId:$.messageId,idleTimeoutMs:$.idleTimeoutMs??GP0},X,HV8)}var PV8=O(()=>{r51();e51()});var JP0,TO,AV8=()=>({active:TO.active,pending:TO.pending,max:JP0}),TV8=($)=>{if(TO.active>=JP0)console.log("[hostedHarness] run parked at concurrency cap",{active:TO.active,pending:TO.pending,max:JP0}),$?.();return TO.acquire()};var $91=O(()=>{N51();c8();P5();JP0=J1().decopilotMaxConcurrentHostedRuns,TO=H51(JP0);D6.createObservableGauge("hosted_runs.active",{description:"Hosted agent-loop runs executing on this pod",unit:"{runs}"}).addCallback(($)=>$.observe(TO.active));D6.createObservableGauge("hosted_runs.pending",{description:"Hosted agent-loop runs parked waiting for a slot on this pod",unit:"{runs}"}).addCallback(($)=>$.observe(TO.pending))});import{DBOS as M_}from"@dbos-inc/dbos-sdk";function Q91($){Z91=$}function RV8(){if(!Z91)throw Error("[hostedHarness] runtime not initialized \u2014 setHostedHarnessRuntime() must run before workflows fire");return Z91}async function Zu4($,Z){let X=RV8(),{request:Q}=$,Y=Z??await X.studioContextFactory(Q.organizationId,Q.userId);if(!Y)throw Error("user membership lost mid-dispatch");if(Q.runMetadata)Y.metadata.runMetadata=Q.runMetadata;let G=new AbortController,J=!1,K=new rr({emit:()=>IV8(X,$)}),W=await TV8(()=>{J=!0,IV8(X,$),K.arm()}).finally(()=>K.stop());try{if(J&&await Xu4($))throw Error("run cancelled while queued for a free runner");if(_h(Y,"in_progress",$.threadId),!Q.runMetadata?.taskBoardItemId)Xk8(Y,$.threadId);await X.dispatchRunFn({...Q,abortSignal:G.signal},Y,X.deps)}finally{W()}}async function Xu4($){try{return(await M_.getWorkflowStatus(Y91($.runId,$.fenceToken)))?.status==="CANCELLED"}catch(Z){return console.error(`[hostedHarness] could not read child status for run=${$.runId} fence=${$.fenceToken}`,Z),!1}}function Qu4($,Z,X,Q=1){let Y=X instanceof Error?X.message:String(X);return{messageId:PO($,Z),errorChunk:{type:"error",errorText:Y},seq:Q,finalSeq:Q}}function Yu4($){if(!($ instanceof Error))return;let Z=$.lastAckSeq;return typeof Z==="number"?Z+1:void 0}async function Gu4($,Z){let X=RV8(),{streamBuffer:Q}=X.deps,{messageId:Y,errorChunk:G,seq:J,finalSeq:K}=Qu4($.runId,$.fenceToken,Z,Yu4(Z));if(!Q){console.error(`[hostedHarness] no streamBuffer configured; dropping terminal error for run=${$.runId} fence=${$.fenceToken} messageId=${Y}`);return}if(!await Q.publishRawChunk($.runId,G,{fenceToken:$.fenceToken,seq:J})){console.error(`[hostedHarness] failed to publish terminal error chunk for run=${$.runId} fence=${$.fenceToken} messageId=${Y}`);return}await Q.publishDone($.runId,$.fenceToken,K)}async function Ju4($){try{await M_.runStep(()=>Zu4($),{name:"runHostedHarness",retriesAllowed:!1})}catch(Z){await M_.runStep(()=>Gu4($,Z),{name:"publishHostedHarnessFailure",retriesAllowed:!0}).catch((X)=>{console.error(`[hostedHarness] could not publish terminal error for run=${$.runId} fence=${$.fenceToken}`,X)})}}function Y91($,Z){return`decopilot-hosted:${$}:${Z}`}async function qV8($){return{workflowID:(await M_.startWorkflow(Ku4,{workflowID:Y91($.runId,$.fenceToken),queueName:JN,enqueueOptions:{queuePartitionKey:$.threadId}})($)).workflowID}}async function G91($,Z){await M_.cancelWorkflow(Y91($,Z))}var X91=1,Z91=null,IV8=($,Z)=>GK($.deps.streamBuffer,Z.runId,"waiting-capacity"),Ku4;var J91=O(()=>{c51();gh();$91();KQ();Ku4=M_.registerWorkflow(Ju4,{name:"hostedHarnessWorkflow",maxRecoveryAttempts:1000})});import{DBOS as ch}from"@dbos-inc/dbos-sdk";function H91($){d51($)}function N91($){K91=$}function Wu4(){if(!K91)throw Error("[threadGate] runtime not initialized \u2014 setThreadGateRuntime() must run before workflows fire");return K91}function Hu4($,Z=mj0){let X=$.runFenceToken;if(X)return{runFenceToken:X,claimedRequest:$,shouldPersistFence:!1};let Q=Z();return{runFenceToken:Q,claimedRequest:{...$,runFenceToken:Q},shouldPersistFence:!0}}async function Nu4($){let Z=Wu4(),{request:X}=$,Q=X.taskId??$.threadId;if(AS8({harnessId:X.harnessId}))await GK(Z.deps.streamBuffer,Q,"starting-run");let Y=await Z.studioContextFactory(X.organizationId,X.userId);if(!Y)throw Error("user membership lost mid-dispatch");H91(X.harnessId);let G=X.taskId??$.threadId,{runFenceToken:J,claimedRequest:K,shouldPersistFence:W}=Hu4(X);if(W)await Y.storage.threads.setRunFence(G,J);return{runFenceToken:J,hostedEnqueue:{runId:Q,fenceToken:J,threadId:$.threadId,request:K}}}async function Uu4($){if($.source!=="user-message")return;let{request:Z}=$;i1.capture({distinctId:Z.userId,event:"chat_message_started",groups:{organization:Z.organizationId},properties:{organization_id:Z.organizationId,agent_id:Z.agent,mode:Z.mode,thread_id:Z.taskId??$.threadId,credential_id:Z.models.credentialId}})}async function Fu4($,Z){if($.source!=="user-message")return;let{request:X}=$;i1.capture({distinctId:X.userId,event:"chat_message_failed",groups:{organization:X.organizationId},properties:{organization_id:X.organizationId,thread_id:X.taskId??$.threadId,agent_id:X.agent,model_id:X.models.thinking.id,mode:X.mode,error_category:"setup",error_message:Z}})}async function KP0($){H91($.request.harnessId),await ch.runStep(()=>Uu4($),{name:"trackMessageStarted"});let Z;try{Z=await ch.runStep(()=>Nu4($),{name:"dispatchRunAndWait",retriesAllowed:!0}),await qV8(Z.hostedEnqueue)}catch(Y){let G=Y instanceof Error?Y.message:String(Y);throw await ch.runStep(()=>Fu4($,G),{name:"trackMessageFailed"}),Y}let X=$.request.taskId??$.threadId,Q="messages"in $.request?void 0:$.request.messageId;return await ch.runStep(()=>jV8({runId:X,fenceToken:Z.runFenceToken,messageId:Q}),{name:"consumeRunProjection"}),{taskId:$.request.taskId??$.threadId}}async function wu4($){return KP0($)}async function EU($,Z){return H91($.request.harnessId),{workflowID:(await ch.startWorkflow(Bu4,{queueName:e3,enqueueOptions:{queuePartitionKey:$.threadId},workflowID:Z?.workflowID})($)).workflowID}}var W91=1,K91=null,Bu4;var MV8=O(()=>{rj0();S$();gh();PV8();J91();Bu4=ch.registerWorkflow(wu4,{name:"threadGateWorkflow",maxRecoveryAttempts:1000})});var q_=O(()=>{MV8();J91()});async function er($,Z,X){let Q=Z.organizationId,Y=Z.assignedBy??Z.createdBy,G=X.harnessId??"decopilot",J=await wX($,"smart"),K=fD(Q),W=await $.storage.threads.create({organization_id:Q,title:X.title,status:"in_progress",virtual_mcp_id:K,message_storage_version:2,harness_id:G,sandbox_provider_kind:"agent-sandbox",created_by:Y}),H={...W.metadata??{},...L_(G)?{read_only:!0}:{},...X.repo?{githubRepo:{url:X.repo.url,owner:X.repo.owner,name:X.repo.name,installationId:X.repo.installationId,connectionId:X.repo.connectionId}}:{}};await $.storage.threads.update(W.id,{metadata:H,...X.repo?{branch:br(W.id,X.repo.connectionId)}:{},updated_by:Y}),await $.storage.taskBoard.linkThread(Z.id,W.id,Q);let N={id:crypto.randomUUID(),role:"user",parts:[{type:"text",text:X.prompt}]};return await new zX({storage:$.storage.threads.messageParts(),orgId:Q,threadId:W.id,runId:W.id}).emitRequestMessage(N),await EU({threadId:W.id,source:"background-tool",request:{messages:[N],models:{credentialId:J.credentialId,thinking:{id:J.modelId,title:J.modelMeta.title}},agent:{id:K},temperature:X.temperature,toolApprovalLevel:"auto",mode:"default",organizationId:Q,userId:Y,harnessId:G,sandboxProviderKind:"agent-sandbox",taskId:W.id,runMetadata:{taskBoardItemId:Z.id}}}),{threadId:W.id}}var U91=O(()=>{dB();q_();zO();I6();tW();Kj0()});function Ou4($){let Z=new Map($.map((G)=>[G.id,G])),X=new Map;for(let G of Fj0($)){let J=kV8(G.owner,G.repo);X.set(J,[...X.get(J)??[],G])}if(X.size!==1)return null;let Q=[...X.values()][0],Y=Q.find((G)=>{let J=Z.get(G.connectionId);return J?HG0(J):!1})??Q[0];return{connectionId:Y.connectionId,owner:Y.owner,name:Y.repo,installationId:Y.installationId,url:`https://github.com/${Y.owner}/${Y.repo}`}}async function SV8($,Z){try{let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"}),Q=Ou4(X);if(!Q){let Y=Fj0(X),G=new Set(Y.map((J)=>kV8(J.owner,J.repo)));console.warn(`[task-board] claude-code skipped for org ${Z}: ${G.size} importable repos (needs exactly 1) \u2014 running Decopilot`)}return Q}catch(X){return console.warn("[task-board] repo lookup for claude-code failed",X),null}}async function VV8($,Z){try{return(await $.storage.organizationSettings.get(Z))?.flags?.claude_code_sandbox_enabled===!0}catch(X){return console.warn("[task-board] org flag lookup failed",X),!1}}function CV8($,Z,X){let Q=["You've been assigned this task. Complete it and finish with a pull request.","","You are running AUTONOMOUSLY \u2014 no human is watching, so drive this to "+"completion yourself. Make reasonable decisions and move on; do not stop to ask for confirmation.","",`Title: ${$.title}`];if($.description)Q.push("","Description:",$.description);if(Q.push("",`The repository ${Z.owner}/${Z.name} is already cloned at your working directory, on its own branch. \`git\` and \`gh\` are authenticated.`,""),X?.resolveConflict&&X.pr)Q.push(`Pull request #${X.pr.number} (${X.pr.url}) is approved but has a MERGE CONFLICT with its base branch.`,`Check that branch out (\`gh pr checkout ${X.pr.number}\`), merge or rebase the base branch into it, resolve the conflicts, and push to update the SAME pull request \u2014 do NOT open a new one. Resolve by preserving BOTH sides' intent; never blindly discard either side, and change only what the conflict requires.`,"");else if(X?.feedback)Q.push(X.pr?`A reviewer requested changes on pull request #${X.pr.number} (${X.pr.url}):`:"A reviewer requested changes on your previous work:",X.feedback,X.pr?`Check that branch out (\`gh pr checkout ${X.pr.number}\`) before editing, address the feedback, then push to update the SAME pull request \u2014 do NOT open a new one.`:"Address this feedback.","");return Q.push("How to finish:","- Make the change, commit it, push the branch, and open a pull request"+(X?.pr?" \u2014 or push to the existing one, per the instruction above.":"."),"- Change only what the task needs. Don't refactor around it.",`- Then move this task to review on the board: call \`mcp__studio__TASK_BOARD_ITEM_UPDATE\` with id "${$.id}" and status "in_review". Pass ONLY the fields you are changing.`,"- If the task turns out to need no code change, say why in your final message and move it to review anyway so a human can close it out.","",`(task id: ${$.id})`),Q.join(`
|
|
2748
2748
|
`)}var kV8=($,Z)=>`${$}/${Z}`.toLowerCase();var _V8=O(()=>{r$1();_W()});async function lh($,Z){if(Z.assigneeId!==y5)return;await $a($,Z).catch((X)=>{console.error("[task-board] Super Agent enqueue failed",X)})}function Lu4($,Z){return["You've been assigned this task. Complete it.","","You are running AUTONOMOUSLY \u2014 no human is watching this run, so drive it "+"to completion on your own. Use `user_ask` ONLY for a genuine, unresolvable blocker a human must clear (a missing credential/secret, or "+"a decision so ambiguous you truly cannot proceed) \u2014 that should be rare. "+"Do not ask for confirmation of a reasonable choice; make it and move on.","",`Title: ${$.title}`,$.description?`
|
|
2749
2749
|
Description:
|
|
2750
2750
|
${$.description}
|
|
@@ -3922,10 +3922,10 @@ When unsure between the two, lean toward NOT requiring review for small frontend
|
|
|
3922
3922
|
|
|
3923
3923
|
Respond with the structured verdict and a short reason.`,we8;var Oe8=O(()=>{u4();dB();uJ1();aA$=cJ1.object({requiresReview:cJ1.boolean().describe("true if the changes should go through pull-request review"),reason:cJ1.string().describe("One short sentence explaining the decision (max ~120 chars)")});we8={requiresReview:!1,reason:""}});function ZT$($){if(!$||$.includes(".."))return!1;return $T$.test($)}function Le8($){let Z=typeof $.__resolveType==="string"?$.__resolveType:null;if(!Z||!ZT$(Z))return null;let{__resolveType:X,...Q}=$;return{resolveType:Z,payload:Q}}function De8($,Z){return`${$.replace(/\/+$/,"")}/deco/invoke/${Z}`}var $T$;var Ee8=O(()=>{$T$=/^[\w./@-]+$/});function lJ1($){let Z;try{Z=new URL($)}catch{return null}if(!Z.hostname.endsWith(".localhost"))return null;let X=Z.host;return Z.hostname="127.0.0.1",{url:Z.toString(),hostHeader:X}}function ze8($,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 je8($,Z,X,Q){if(!Q.connectionId)throw new Nc("Push requires a connected GitHub account. Connect mcp-github for this project and restart the sandbox.");let Y=$.organization?.id;if(!Y)throw new Nc(NX);await C30({ctx:$,connectionId:Q.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(N)=>{let U=N instanceof Error?N.message:NX;throw new Nc(U)}});let{cloneUrl:G,gitUserName:J,gitUserEmail:K}=await Hh(Q.connectionId,Q.owner,Q.name,$.db,$.vault),W=fR0($),H=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(!H.ok){let N=await OO(H,XT$).catch(()=>H.statusText);throw Error(`Failed to refresh sandbox git credentials (${H.status}): ${N}`)}}var XT$=10485760,Nc;var Pe8=O(()=>{fB();xJ1();gr();_30();Nc=class Nc extends Error{constructor($){super($);this.name="GitPushAuthError"}}});function YT$($){let Z=$.startsWith("thread:")?$.slice(7):$;if(!Z||Z.length>255||Z.includes("..")||Z.startsWith("/")||Z.endsWith("/")||Z.endsWith(".lock")||!QT$.test(Z))throw Error(`Invalid branch name: ${$}`)}function Px($){return AbortSignal.any([$.req.raw.signal,AbortSignal.timeout(JT$)])}function Ax($){let{runner:Z}=$.get("vmClaim");if(!Z)return $.json({error:"No sandbox runner configured"},503);return Z}function dJ1($,Z){let Q=(bR0.get($)??Promise.resolve()).catch(()=>{}).then(Z),Y=Q.catch(()=>{});return bR0.set($,Y),Y.finally(()=>{if(bR0.get($)===Y)bR0.delete($)}),Q}async function oZ($,Z,X){let Q=Ax($);if(Q instanceof Response)return Q;let{claimName:Y,userId:G,projectRef:J}=$.get("vmClaim"),K=X?.method??"POST",W=null,H=new Headers;if(X?.jsonBody!==void 0)W=X.jsonBody,H.set("content-type","application/json");else if(X?.forwardJsonBody)W=await $.req.text(),H.set("content-type","application/json");let N=X?.signal,U={method:K,headers:H,body:W,...N?{signal:N}:{}},F=async()=>{let w=await Q.proxyDaemonRequest(Y,Z,U);if(X?.map404to410&&w.status===404){try{await w.body?.cancel()}catch{}if(await Q.adoptLiveClaim?.({userId:G,projectRef:J},Y))w=await Q.proxyDaemonRequest(Y,Z,U);if(w.status===404){try{await w.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",...DG}})}}let B=await w.text(),L=X?.redactRepoDirUnlessDesktop&&Q.kind!=="user-desktop"?WT$(B):B,D=w.headers.get("content-type")??"application/json";return new Response(L,{status:w.status,headers:{"content-type":D,...DG}})};try{if(N){let w=F();return w.catch(()=>{}),await Promise.race([w,new Promise((L,D)=>{if(N.aborted)return D(N.reason);N.addEventListener("abort",()=>D(N.reason),{once:!0})})])}return await F()}catch(w){let B=w instanceof Error?w.message:String(w);return $.json({error:`Daemon unreachable: ${B}`},502)}}function WT$($){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 yR0($,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)try{let K=JSON.parse(J);throw Error(K.error??`Daemon error (${G.status})`)}catch(K){if(K instanceof Error&&K.message!==J)throw K;throw Error(`Daemon error (${G.status})`)}return JSON.parse(J)}function HT$($){return Ie8.includes($)}var QT$,Ae8=524288,GT$=65536,JT$=1e4,Te8=2000,KT$,bR0,DG,Ie8,Re8=()=>{let $=new S1;return $.use("/:virtualMcpId/:branch/*",KT$),$.post("/:virtualMcpId/:branch/write",(Z)=>oZ(Z,"/_sandbox/write",{forwardJsonBody:!0,signal:Px(Z)})),$.post("/:virtualMcpId/:branch/unlink",(Z)=>oZ(Z,"/_sandbox/unlink",{forwardJsonBody:!0,signal:Px(Z)})),$.post("/:virtualMcpId/:branch/mkdir",(Z)=>oZ(Z,"/_sandbox/mkdir",{forwardJsonBody:!0,signal:Px(Z)})),$.post("/:virtualMcpId/:branch/rename",(Z)=>oZ(Z,"/_sandbox/rename",{forwardJsonBody:!0,signal:Px(Z)})),$.post("/:virtualMcpId/:branch/read",(Z)=>oZ(Z,"/_sandbox/read",{forwardJsonBody:!0,signal:Px(Z)})),$.post("/:virtualMcpId/:branch/glob",(Z)=>oZ(Z,"/_sandbox/glob",{forwardJsonBody:!0,signal:Px(Z)})),$.post("/:virtualMcpId/:branch/grep",(Z)=>oZ(Z,"/_sandbox/grep",{forwardJsonBody:!0,signal:Px(Z)})),$.post("/:virtualMcpId/:branch/exec/:script",async(Z)=>{let X=Z.req.param("script");if(!X)return Z.json({error:"missing script name"},400);return oZ(Z,`/_sandbox/exec/${encodeURIComponent(X)}`)}),$.post("/:virtualMcpId/:branch/exec/:script/kill",async(Z)=>{let X=Z.req.param("script");if(!X)return Z.json({error:"missing script name"},400);return oZ(Z,`/_sandbox/exec/${encodeURIComponent(X)}/kill`)}),$.get("/:virtualMcpId/:branch/config",(Z)=>oZ(Z,"/_sandbox/config",{method:"GET",map404to410:!0,redactRepoDirUnlessDesktop:!0})),$.put("/:virtualMcpId/:branch/config",(Z)=>oZ(Z,"/_sandbox/config",{method:"PUT",forwardJsonBody:!0,map404to410:!0})),$.post("/:virtualMcpId/:branch/setup/:step",async(Z)=>{let X=Z.req.param("step");if(!X||!HT$(X))return Z.json({error:`step must be one of: ${Ie8.join(", ")}`},400);if(X==="start"){let Q=Z.get("vmClaim");if(Q.runner){let Y=H0(Z.var.studioContext),G=Qj0(Q.virtualMcpMetadata);try{await Yj0({ctx:Z.var.studioContext,runner:Q.runner,handle:Q.claimName,orgId:Y.id,userId:Q.callerUserId,entries:G})}catch(J){let K=J instanceof Error?J.message:String(J);return Z.json({error:`Failed to push env to daemon: ${K}`},502)}}}return oZ(Z,`/_sandbox/setup/${X}`,{signal:Z.req.raw.signal,map404to410:!0})}),$.get("/:virtualMcpId/:branch/events",(Z)=>{let X=Z.get("vmClaim");if(!X.runner)return iU(Z,async(Q)=>{await Q.writeSSE({event:"phase",data:JSON.stringify({kind:"failed",reason:"unknown",message:"No sandbox runner configured on this studio instance."})})});return Ke8(Z,{ctx:Z.var.studioContext,claimName:X.claimName,runner:X.runner,virtualMcpId:X.virtualMcpId,branch:X.branch,userId:X.userId,projectRef:X.projectRef,virtualMcpMetadata:X.virtualMcpMetadata})}),$.get("/:virtualMcpId/:branch/git/status",(Z)=>oZ(Z,"/_sandbox/git/status",{method:"GET",map404to410:!0,signal:AbortSignal.any([Z.req.raw.signal,AbortSignal.timeout(Te8)])})),$.post("/:virtualMcpId/:branch/git/status",(Z)=>oZ(Z,"/_sandbox/git/status",{map404to410:!0,signal:AbortSignal.any([Z.req.raw.signal,AbortSignal.timeout(Te8)])})),$.post("/:virtualMcpId/:branch/git/diff",(Z)=>oZ(Z,"/_sandbox/git/diff",{forwardJsonBody:!0,map404to410:!0})),$.post("/:virtualMcpId/:branch/git/publish",async(Z)=>{let X=Ax(Z);if(X instanceof Response)return X;let{claimName:Q,virtualMcpMetadata:Y,connectionIds:G}=Z.get("vmClaim"),J=Z.var.studioContext;return dJ1(Q,async()=>{try{await vJ1(J,X,Q);let K=ze8(Y,G);if(K)await je8(J,X,Q,K)}catch(K){if(K instanceof Nc)return Z.json({error:K.message},403,DG);let W=K instanceof Error?K.message:String(K);return Z.json({error:W},502,DG)}return oZ(Z,"/_sandbox/git/publish",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/discard",(Z)=>{let{claimName:X}=Z.get("vmClaim");return dJ1(X,()=>oZ(Z,"/_sandbox/git/discard",{forwardJsonBody:!0,map404to410:!0}))}),$.post("/:virtualMcpId/:branch/git/rebase",async(Z)=>{let X=Ax(Z);if(X instanceof Response)return X;let{claimName:Q}=Z.get("vmClaim"),Y=Z.var.studioContext;return dJ1(Q,async()=>{try{await vJ1(Y,X,Q)}catch(G){let J=G instanceof Error?G.message:String(G);return Z.json({error:J},502,DG)}return oZ(Z,"/_sandbox/git/rebase",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/suggest-commit",V7({maxSize:Ae8,onError:(Z)=>Z.json({error:"Payload too large"},413,DG)}),async(Z)=>{let X=Ax(Z);if(X instanceof Response)return X;let{claimName:Q,userId:Y,projectRef:G}=Z.get("vmClaim"),J=Z.var.studioContext;try{let K=await Z.req.json().catch(()=>({})),W=K.status,H=K.diff,N=H!=null&&typeof H.diffs==="object"&&H.diffs!==null,[U,F]=yJ1(W)&&N?[W,H]:await Promise.all([yR0(X,Q,"/_sandbox/git/status","GET",{userId:Y,projectRef:G}),yR0(X,Q,"/_sandbox/git/diff","GET",{userId:Y,projectRef:G})]),w=await Fe8(J,U,F);return Z.json(w,200,DG)}catch(K){let W=K instanceof Error?K.message:String(K);if(W==="SANDBOX_GONE")return Z.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,DG);return Z.json({error:W},502,DG)}}),$.post("/:virtualMcpId/:branch/git/judge-review",V7({maxSize:Ae8,onError:(Z)=>Z.json({error:"Payload too large"},413,DG)}),async(Z)=>{let X=Ax(Z);if(X instanceof Response)return X;let{claimName:Q,userId:Y,projectRef:G}=Z.get("vmClaim"),J=Z.var.studioContext;try{let K=await Z.req.json().catch(()=>({})),W=K.status,H=K.diff,N=H!=null&&typeof H.diffs==="object"&&H.diffs!==null,[U,F]=yJ1(W)&&N?[W,H]:await Promise.all([yR0(X,Q,"/_sandbox/git/status","GET",{userId:Y,projectRef:G}),yR0(X,Q,"/_sandbox/git/diff","GET",{userId:Y,projectRef:G})]),w=await Be8(J,U,F,typeof K.language==="string"?K.language:void 0);return Z.json(w,200,DG)}catch(K){let W=K instanceof Error?K.message:String(K);if(W==="SANDBOX_GONE")return Z.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,DG);return Z.json({error:W},502,DG)}}),$.get("/:virtualMcpId/:branch/preview-fetch",async(Z)=>{let X=Ax(Z);if(X instanceof Response)return X;let{claimName:Q}=Z.get("vmClaim"),Y=Z.req.query("path");if(!Y||!Y.startsWith("/")||Y.startsWith("//")||Y.includes("..")||Y.includes("\\"))return Z.json({error:"Path not allowed"},403);let G;try{G=await X.getPreviewUrl(Q)}catch{return Z.json({error:"Preview not available"},502)}if(!G)return Z.json({error:"Preview not available"},502);let J=G.replace(/\/+$/,""),K=lJ1(`${J}${Y}`),W;try{W=await fetch(K?.url??`${J}${Y}`,{...K?{headers:{host:K.hostHeader}}:{}})}catch{return Z.json({error:"Preview unreachable"},502)}let H;try{H=await W.text()}catch{return Z.json({error:"Preview unreachable"},502)}return new Response(H,{status:W.status,headers:{"content-type":W.headers.get("content-type")??"application/json"}})}),$.post("/:virtualMcpId/:branch/preview-invoke",V7({maxSize:GT$,onError:(Z)=>Z.json({error:"Payload too large"},413)}),async(Z)=>{let X=Ax(Z);if(X instanceof Response)return X;let{claimName:Q}=Z.get("vmClaim"),Y;try{Y=await X.getPreviewUrl(Q)}catch{return Z.json({error:"Preview not available"},502)}if(!Y)return Z.json({error:"Preview not available"},502);let G;try{G=await Z.req.json()}catch{return Z.json({error:"Invalid JSON body"},400)}if(!G||typeof G!=="object"||Array.isArray(G))return Z.json({error:"Invalid JSON body"},400);let J=Le8(G);if(!J)return Z.json({error:"Invalid or missing __resolveType"},400);let K=De8(Y,J.resolveType),W=lJ1(K),H;try{H=await fetch(W?.url??K,{method:"POST",headers:{"content-type":"application/json",...W?{host:W.hostHeader}:{}},body:JSON.stringify(J.payload),signal:AbortSignal.timeout(30000)})}catch{return Z.json({error:"Preview unreachable"},502)}let N;try{N=await H.text()}catch{return Z.json({error:"Preview unreachable"},502)}return new Response(N,{status:H.status,headers:{"content-type":H.headers.get("content-type")??"application/json"}})}),$};var qe8=O(()=>{G4();Fx();Hc();Qe8();HU();Ge8();tW();w_();Je8();We8();c$1();yr();uJ1();Oe8();Ee8();Pe8();QT$=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;KT$=Xe8(async($,Z)=>{let X=$.var.studioContext;try{E0(X)}catch{return $.json({error:"Unauthorized"},401)}let Q=_1(X);if(!Q)return $.json({error:"Unauthorized"},401);let Y;try{Y=H0(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{YT$(J)}catch(w){let B=w instanceof Error?w.message:String(w);return $.json({error:B},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=Jr({orgId:Y.id,virtualMcpId:G,branch:J}),H=await B_(X,J,Q),N=Ye8({userId:H,projectRef:W},J),U=K.metadata??null,F;try{F=(await KG(X,{userId:H,branch:J,virtualMcpMetadata:U})).provider}catch{F=null}if(!F)return $.json({error:"No sandbox runner found"},404);return $.set("vmClaim",{claimName:N,callerUserId:Q,runner:F,virtualMcpId:G,branch:J,userId:H,projectRef:W,virtualMcpMetadata:U,connectionIds:K.connections?.map((w)=>w.connection_id)??[]}),Z()});bR0=new Map;DG={"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache"};Ie8=["clone","install","start"]});var Me8=($)=>{let Z=new S1;if(Z.use("*",Ux),Z.route("/",sI0()),Z.route("/",do8()),Z.route("/",ds8()),Z.route("/",cs8()),Z.route("/",_R0()),Z.route("/tools",rs8()),Z.route("/",ps8()),Z.route("/",Rs8({kvStorage:$.kvStorage})),Z.route("/",Ts8()),Z.route("/fs",bs8({getConnection:$.getNatsConnection})),Z.route("/sandbox",Re8()),Z.route("/",gs8()),Z.route("/deco-sites",$R0()),Z.route("/sso",iI0()),Z.route("/",xR0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",fo8()),$.mountDevAssets)Z.route("/dev-assets",ZR0({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.route("/",dU8()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp",RP0()),Z.route("/mcp/self",CR0()),Z.route("/mcp",kP0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var ke8=O(()=>{G4();$31();bo8();G31();XR0();ks();sG1();Is8();qs8();ys8();Uo();dG1();SP0();qJ1();hs8();ls8();ms8();ts8();kJ1();as8();SJ1();qP0();qe8()});function UT$($){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}}))}async function FT$($,Z){let X=await fetch(`${$}/rest/v1/apps?select=name,title,description,logo,category,vendors(alias,url)`,{headers:{apikey:Z,Authorization:`Bearer ${Z}`,Accept:"application/json"},signal:AbortSignal.timeout(NT$)});if(!X.ok){let Q=await X.text().catch(()=>X.statusText);throw console.error(`[deco-apps] Supabase error (${X.status}): ${Q.slice(0,200)}`),Error(`External service error (${X.status})`)}return await X.json()}var NT$=1e4,wT$=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},Se8=()=>{let $=new S1;return $.use("*",wT$),$.get("/",async(Z)=>{let X=J1(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await FT$(Q,Y);return Z.json({apps:UT$(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var Ve8=O(()=>{G4();c8()});import{z as g1}from"zod";function PH($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function TT$($){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 IT$($,Z,X){try{return JSON.parse($)}catch{throw new xe8(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function RT$($){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:IT$(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 qT$($){let Z=$.map((X)=>{let Q=X.function.parameters?tY(X.function.parameters):tY({type:"object",properties:{}});return[X.function.name,h8({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function MT$($){if(!$)return;return{openai:{response_format:$}}}function kT$(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function Ce8($,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 _e8($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var BT$=256,OT$,LT$,DT$,ET$,zT$,jT$,PT$,AT$,xe8,ve8,fe8;var be8=O(()=>{u4();G4();Hc();IU();OT$=g1.object({type:g1.literal("function"),function:g1.object({name:g1.string(),description:g1.string().optional(),parameters:g1.record(g1.string(),g1.unknown()).optional()})}),LT$=g1.object({id:g1.string(),type:g1.literal("function"),function:g1.object({name:g1.string(),arguments:g1.string()})}),DT$=g1.discriminatedUnion("role",[g1.object({role:g1.literal("system"),content:g1.string(),name:g1.string().optional()}),g1.object({role:g1.literal("user"),content:g1.union([g1.string(),g1.array(g1.union([g1.object({type:g1.literal("text"),text:g1.string()}),g1.object({type:g1.literal("image_url"),image_url:g1.object({url:g1.string(),detail:g1.string().optional()})})]))]),name:g1.string().optional()}),g1.object({role:g1.literal("assistant"),content:g1.string().nullable().optional(),name:g1.string().optional(),tool_calls:g1.array(LT$).optional()}),g1.object({role:g1.literal("tool"),content:g1.string(),tool_call_id:g1.string()})]),ET$=g1.object({type:g1.literal("text")}),zT$=g1.object({type:g1.literal("json_object")}),jT$=g1.object({type:g1.literal("json_schema"),json_schema:g1.object({name:g1.string(),description:g1.string().optional(),schema:g1.record(g1.string(),g1.unknown()),strict:g1.boolean().optional()})}),PT$=g1.union([ET$,zT$,jT$]),AT$=g1.object({model:g1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:g1.array(DT$),stream:g1.boolean().optional().default(!1),temperature:g1.number().min(0).max(2).optional(),max_tokens:g1.number().positive().optional(),top_p:g1.number().min(0).max(1).optional(),frequency_penalty:g1.number().min(-2).max(2).optional(),presence_penalty:g1.number().min(-2).max(2).optional(),stop:g1.union([g1.string(),g1.array(g1.string())]).optional(),tools:g1.array(OT$).optional(),tool_choice:g1.union([g1.literal("auto"),g1.literal("none"),g1.literal("required"),g1.object({type:g1.literal("function"),function:g1.object({name:g1.string()})})]).optional(),response_format:PT$.optional(),user:g1.string().optional()});xe8=class xe8 extends Error{constructor($){super($);this.name="MessageConversionError"}};ve8=new S1;ve8.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(PH("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(PH("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(PH("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=AT$.safeParse(Q);if(!Y.success){let D=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(PH(`Invalid request: ${D.message}`,"invalid_request_error",D.path.length>0?D.path.join("."):null),400)}let G=Y.data,J=TT$(G.model);if(!J)return $.json(PH("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((z)=>vD(z.providerId));if(!E)return $.json(PH("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 H;try{H=await Z.aiProviders.activate(K,Z.organization.id)}catch{return $.json(PH(`AI provider credential not found or inaccessible: ${K}`,"invalid_request_error","model"),404)}let N=H.aiSdk.languageModel(W),U=RT$(G.messages),F=G.tools?qT$(G.tools):void 0,w=MT$(G.response_format),B=kT$(),L=Math.floor(Date.now()/1000);if(G.stream)return iU($,async(D)=>{let E=Ce8(N,U,F,G,w,$.req.raw.signal);try{let z=aB(E),j=!1,A=0,P="",R=async()=>{if(P.length===0)return;let S=P;P="",await D.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{content:S},finish_reason:null}]})})};for await(let S of z.fullStream){if(!j&&(S.type==="text-delta"||S.type==="tool-call"))await D.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),j=!0;if(S.type==="text-delta"){if(P+=S.text,P.length>=BT$)await R()}else if(S.type==="tool-call"){await R();let M=A++;await D.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:M,id:S.toolCallId,type:"function",function:{name:S.toolName,arguments:JSON.stringify(S.input)}}]},finish_reason:null}]})})}else if(S.type==="finish")await R(),await D.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:L,model:G.model,choices:[{index:0,delta:{},finish_reason:_e8(S.finishReason)}],usage:S.totalUsage?{prompt_tokens:S.totalUsage.inputTokens??0,completion_tokens:S.totalUsage.outputTokens??0,total_tokens:S.totalUsage.totalTokens??0}:void 0})})}await R(),await D.writeSSE({data:"[DONE]"})}catch(z){let j=z;console.error("[openai-compat:stream] Error:",j.message),await D.writeSSE({data:JSON.stringify({error:{message:j.message,type:"server_error"}})})}});else{let D=Ce8(N,U,F,G,w,$.req.raw.signal),E=await oB(D),z={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)z.tool_calls=E.toolCalls.map((j)=>({id:j.toolCallId,type:"function",function:{name:j.toolName,arguments:JSON.stringify("input"in j?j.input:{})}})),z.content=null;return $.json({id:B,object:"chat.completion",created:L,model:G.model,choices:[{index:0,message:z,finish_reason:_e8(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(PH("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(PH(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(PH(Y.message,"server_error"),500)}});fe8=ve8});function VT$(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??ST$}}var ye8,ST$="https://ph.studio.decocms.com",ge8;var he8=O(()=>{G4();hm0();E_();XZ();c8();gG1();fc0();ye8=new S1;ye8.get("/",($)=>{let Z={version:U50.version,theme:Fr1(),...hD().logo&&{logo:hD().logo},...rW()&&{internalUrl:bu1()},...J1().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!J1().firecrawlApiKey,auth:rt8(),posthog:VT$(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:!rW()&&J1().sandboxProviderKind==="agent-sandbox"}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});ge8=ye8});function Uc($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function mJ1($){return(Uc($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function ce8($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(Uc($))}&sz=${Z}`}function ue8($,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 le8($){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()?ue8(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):ue8(`How does ${X} really perform? ${J}`,200);return{title:G,description:K}}import{z as Z1}from"zod";var Tx,CT$,_T$,xT$,vT$,de8;var me8=O(()=>{Tx=Z1.enum(["good","bad","neutral"]),CT$=Z1.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},Z1.object({kind:Z1.enum(["text","number","sparkline","badge","score"]).catch("text"),value:Z1.coerce.string().optional(),tone:Tx.optional(),muted:Z1.boolean().optional(),delta:Z1.coerce.string().optional(),deltaDir:Z1.enum(["up","down","neutral"]).optional(),points:Z1.array(Z1.coerce.number()).optional(),label:Z1.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 $})),_T$=Z1.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},Z1.array(CT$)),xT$={key:Z1.coerce.string(),title:Z1.coerce.string(),eyebrow:Z1.coerce.string().optional(),headline:Z1.coerce.string(),annotation:Z1.coerce.string().optional(),methodology:Z1.coerce.string().optional(),sources:Z1.array(Z1.object({name:Z1.coerce.string(),logoUrl:Z1.coerce.string()})).optional()},vT$=Z1.discriminatedUnion("template",[Z1.object({template:Z1.literal("cover"),score:Z1.object({value:Z1.coerce.number(),max:Z1.coerce.number().optional(),grade:Z1.coerce.string().optional(),label:Z1.coerce.string().optional()}).optional(),brandImage:Z1.coerce.string().optional(),screenshot:Z1.coerce.string().optional(),mobileScreenshot:Z1.coerce.string().optional()}),Z1.object({template:Z1.literal("cta"),ctaUrl:Z1.coerce.string().optional(),ctaLabel:Z1.coerce.string().optional(),bullets:Z1.array(Z1.coerce.string()).optional()}),Z1.object({template:Z1.literal("series"),points:Z1.array(Z1.coerce.number()).min(2),xLabels:Z1.array(Z1.coerce.string()).min(1),unit:Z1.coerce.string().optional(),callout:Z1.object({index:Z1.coerce.number(),value:Z1.coerce.string(),tone:Tx.optional()})}),Z1.object({template:Z1.literal("threshold"),value:Z1.coerce.string().default(""),metricLabel:Z1.coerce.string().optional(),ratio:Z1.coerce.number(),thresholdRatio:Z1.coerce.number().optional(),thresholdLabel:Z1.coerce.string().default(""),tone:Tx.optional()}),Z1.object({template:Z1.literal("stats"),stats:Z1.array(Z1.object({value:Z1.coerce.string(),label:Z1.coerce.string(),tone:Tx.optional()})).min(1)}),Z1.object({template:Z1.literal("bars"),items:Z1.array(Z1.object({value:Z1.coerce.string(),label:Z1.coerce.string(),ratio:Z1.coerce.number(),tone:Tx.optional()})).min(1)}),Z1.object({template:Z1.literal("gauges"),gauges:Z1.array(Z1.object({label:Z1.coerce.string(),value:Z1.coerce.string(),status:Z1.enum(["good","warn","bad"]).catch("warn"),caption:Z1.coerce.string().optional(),ratio:Z1.coerce.number().optional()})).min(1)}),Z1.object({template:Z1.literal("checklist"),checks:Z1.array(Z1.object({label:Z1.coerce.string(),status:Z1.enum(["pass","fail","warn"]).catch("fail"),value:Z1.coerce.string().optional()})).min(1)}),Z1.object({template:Z1.literal("table"),columns:Z1.array(Z1.object({label:Z1.coerce.string(),align:Z1.enum(["left","right"]).optional()})).min(1),rows:Z1.array(_T$).min(1),highlightRow:Z1.coerce.number().optional()}),Z1.object({template:Z1.literal("products"),products:Z1.array(Z1.object({name:Z1.coerce.string(),price:Z1.coerce.string().optional(),image:Z1.coerce.string().optional(),url:Z1.coerce.string().optional()})).min(1)}),Z1.object({template:Z1.literal("list"),entries:Z1.array(Z1.object({label:Z1.coerce.string(),severity:Z1.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:Z1.coerce.number().optional()}),Z1.object({template:Z1.literal("keywords"),volumeLabel:Z1.coerce.string().optional(),keywords:Z1.array(Z1.object({term:Z1.coerce.string(),volume:Z1.coerce.string(),position:Z1.coerce.number().catch(0)})).min(1)}),Z1.object({template:Z1.literal("competitor"),metricLabel:Z1.coerce.string().optional(),competitors:Z1.array(Z1.object({name:Z1.coerce.string(),value:Z1.coerce.string(),tone:Tx.optional(),isYou:Z1.boolean().optional()})).min(1)}),Z1.object({template:Z1.literal("scorecard"),rivalLabel:Z1.coerce.string().optional(),dimensions:Z1.array(Z1.object({label:Z1.coerce.string(),you:Z1.coerce.string(),rival:Z1.coerce.string().optional(),rivalName:Z1.coerce.string().optional(),tone:Tx.optional()})).min(1)})]),de8=Z1.object({...xT$,template:vT$})});function gR0($){let Z=[],X=[...$.sections].sort((Q,Y)=>Q.position-Y.position).map((Q)=>{let Y=de8.safeParse(Q.props);if(Y.success)return Y.data;let G=Y.error.issues[0];return Z.push({section_type:Q.section_type,position:Q.position,reason:G?`${G.path.join(".")||"(root)"}: ${G.message}`:"contract violation"}),null}).filter((Q)=>Q!==null);return{deck:{meta:{...$.meta,scores:$.summary?.scores},slides:X},drops:Z}}var iJ1=O(()=>{me8()});import{join as ie8}from"path";async function bT$($){try{let Z=await fetch(`${HW({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(fT$)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=gR0(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()||mJ1($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function EG($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}function yT$($,Z){let X=Uc($),Q=Z?.brand?.trim()||mJ1(X),Y=ce8(X,128),J=`${(J1().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:K,description:W}=le8({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),H=`${J}/og.png`,N=`${Q} commerce report by decocms`;return[`<title>${EG(K)}</title>`,`<meta name="description" content="${EG(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="${EG(K)}" />`,`<meta property="og:description" content="${EG(W)}" />`,`<meta property="og:url" content="${EG(J)}" />`,`<meta property="og:image" content="${EG(H)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${EG(N)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${EG(K)}" />`,`<meta name="twitter:description" content="${EG(W)}" />`,`<meta name="twitter:image" content="${EG(H)}" />`,`<meta name="twitter:image:alt" content="${EG(N)}" />`,`<link rel="canonical" href="${EG(J)}" />`,`<link rel="icon" href="${EG(Y)}" sizes="any" />`].join(`
|
|
3924
3924
|
`)}function gT$($,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}
|
|
3925
|
-
</head>`)}function ne8($){let Z=new S1;return Z.get("/:domain/og.png",async(X)=>{let Q=Uc(X.req.param("domain")),Y=async()=>{let G=$?Bun.file(ie8($,"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(`${HW({})}/api/v2/public/diagnostics/${encodeURIComponent(Q)}/og.png`,{signal:AbortSignal.timeout(hT$)}),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=$?ie8($,"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 bT$(Uc(Q)),W=yT$(Q,K);return X.html(gT$(J,W),200,{"Cache-Control":"public, max-age=0, s-maxage=300"})}catch{return X.html(J)}}),Z}var fT$=2500,hT$=1e4;var pe8=O(()=>{G4();iJ1();UE();c8()});function Ze($,Z){return fetch(`${HW({})}${$}`,Z)}async function uT$($,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 Ze(`/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}=gR0(J);return{status:K.slides.length?"ready":"empty",deck:K,scanned_at:J.scanned_at,drops:W}}var cT$,Ix,te8;var oe8=O(()=>{G4();w3();UE();iJ1();cT$=new Set(["complete","errored","terminated","unknown"]),Ix=new S1;Ix.use("*",async($,Z)=>{let X=await M6.api.getSession({headers:$.req.raw.headers});if(!X?.user?.id)return $.json({error:"Authentication required"},401,{"Cache-Control":"private, no-store",Vary:"Cookie"});$.set("reportUser",{email:X.user.email}),await Z(),$.header("Cache-Control","private, no-store"),$.header("Vary","Cookie");return});Ix.get("/site/:domain",async($)=>{let Z=$.req.param("domain").trim();if(!Z)return $.json({error:"domain is required"},400);let X=$.req.query("key")?.trim()||void 0,Q=$.req.query("lang")?.trim()||void 0;try{let Y=await uT$(Z,X,Q);return $.header("Cache-Control","private, no-store"),$.json(Y)}catch{return $.json({error:"report read failed"},502)}});Ix.post("/run",async($)=>{let Z;try{Z=await $.req.json()}catch{return $.json({error:"invalid JSON"},400)}let X=typeof Z.domain==="string"?Z.domain.trim():"";if(!X)return $.json({error:"domain is required"},400);let Q=$.get("reportUser").email,Y=typeof Z.distinctId==="string"&&Z.distinctId.trim()&&Z.distinctId.length<=200?Z.distinctId.trim():void 0;try{let G=await Ze("/api/v2/diagnostics/run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${NE({})}`},body:JSON.stringify({url:X,email:Q,distinct_id:Y})});if(!G.ok)return $.json({error:`run HTTP ${G.status}`},502);let J=await G.json(),K=J.blocked?{state:"blocked"}:J.status==="fresh"?{state:"fresh"}:J.mode==="sync"?{state:"sync"}:{state:"running",id:J.id??null};return $.json(K)}catch{return $.json({error:"run failed"},502)}});Ix.get("/status",async($)=>{let Z=$.req.query("id");if(!Z)return $.json({error:"id is required"},400);try{let X=await Ze(`/api/v2/diagnostics/status?id=${encodeURIComponent(Z)}`,{headers:{Authorization:`Bearer ${NE({})}`}});if(!X.ok)return $.json({error:`status HTTP ${X.status}`},502);let Y=(await X.json()).status??"unknown",G={done:cT$.has(Y),status:Y};return $.json(G)}catch{return $.json({error:"status failed"},502)}});Ix.get("/link-token/:id",async($)=>{let Z=$.req.param("id");try{let X=await Ze(`/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)}});Ix.get("/suggest",async($)=>{let Z=($.req.query("q")??"").trim().slice(0,64);if(Z.length<2)return $.json({suggestions:[]});try{let X=await Ze(`/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:[]})}});te8=Ix});import{createHmac as lT$,timingSafeEqual as dT$}from"crypto";function re8($,Z,X,Q=Date.now()){if(!Z||!X)return!1;let Y,G=[];for(let H of Z.split(",")){let N=H.indexOf("=");if(N<=0)continue;let U=H.slice(0,N).trim(),F=H.slice(N+1).trim();if(U==="t")Y=F;else if(U==="v1")G.push(F)}if(!Y||G.length===0)return!1;let J=Number(Y);if(!Number.isFinite(J)||Math.abs(Q/1000-J)>mT$)return!1;let K=lT$("sha256",X).update(`${Y}.${$}`).digest("hex"),W=Buffer.from(K,"hex");return G.some((H)=>{let N=Buffer.from(H,"hex");return W.length===N.length&&dT$(W,N)})}function ae8($){let Z;try{Z=JSON.parse($)}catch{return null}let X=x3(Z),Q=x3(x3(X?.data)?.object);if(!X||typeof X.type!=="string"||!Q)return null;return{id:AH(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 iT$($){switch($){case"active":case"trialing":return"active";case"past_due":return"past_due";default:return"canceled"}}function AH($){return typeof $==="string"?$:void 0}function x3($){return typeof $==="object"&&$!==null?$:void 0}function hR0($){return typeof $==="number"?new Date($*1000):null}function tJ1($){return AH($)??AH(x3($)?.id)}function nT$($){return tJ1($.subscription)??AH(x3(x3($.parent)?.subscription_details)?.subscription)}function pT$($){let Z=hR0($.current_period_end);if(Z)return Z;let X=x3($.items)?.data;if(!Array.isArray(X))return null;let Q=0;for(let Y of X){let G=x3(Y)?.current_period_end;if(typeof G==="number"&&G>Q)Q=G}return Q>0?new Date(Q*1000):null}function nJ1($,Z){let X=hR0($.created);return!!X&&!!Z.lastStripeEventAt&&X<Z.lastStripeEventAt}function pJ1($,Z){let X=hR0($.created);if(!X)return;return Z.lastStripeEventAt&&Z.lastStripeEventAt>X?void 0:X}async function tT$($,Z){let X=Z.data.object;switch(Z.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":{let Q=AH(x3(X.metadata)?.orgId);if(!Q)return{handled:!1,reason:"no orgId"};if(AH(x3(X.metadata)?.kind)==="topup"){if(X.mode!=="payment")return{handled:!1,reason:"topup with wrong mode"};if(AH(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let J=AH(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(x3(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:x3(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(AH(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=tJ1(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(nJ1(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Q,{stripeCustomerId:tJ1(X.customer),stripeSubscriptionId:G,status:"active",lastStripeEventAt:pJ1(Z,Y)}),{handled:!0,organizationId:Q}}case"customer.subscription.updated":case"customer.subscription.deleted":{let Q=AH(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&&nJ1(Z,Y))return{handled:!1,reason:"stale event"};let J=G?"canceled":iT$(X.status);return await $.updateStripeState(Y.organizationId,{status:J,currentPeriodEnd:pT$(X),...G&&{stripeSubscriptionId:null},lastStripeEventAt:pJ1(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}case"invoice.paid":{let Q=nT$(X);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};if(nJ1(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Y.organizationId,{status:"active",currentPeriodEnd:hR0(X.period_end),lastStripeEventAt:pJ1(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}default:return{handled:!1,reason:`unhandled event ${Z.type}`}}}async function se8($){let Z=new qp(w6().db),X=await tT$(Z,$);if(X.handled&&X.topUp)await N_8({organizationId:X.organizationId,amountCents:X.topUp.creditCents,referenceId:X.topUp.referenceId});if(!X.handled&&X.orphanSubscriptionId)try{await VB8(X.orphanSubscriptionId),console.error("stripe webhook: canceled orphan subscription",{subscriptionId:X.orphanSubscriptionId,eventId:$.id})}catch(Q){if(!(Q instanceof aJ&&(Q.status===400||Q.status===404)))throw Q}return X}var mT$=300;var ee8=O(()=>{d7();yo();qZ1()});var oT$=1048576,oJ1;var $06=O(()=>{G4();Fx();c8();ee8();oJ1=new S1;oJ1.post("/webhook",V7({maxSize:oT$,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=J1().stripeWebhookSecret;if(!Z)return $.json({error:"stripe billing not configured"},503);let X=await $.req.text();if(!re8(X,$.req.header("stripe-signature"),Z))return $.json({error:"invalid signature"},400);let Y=ae8(X);if(!Y)return $.json({error:"invalid payload"},400);let G=await se8(Y);return console.log("stripe webhook",{eventId:Y.id,type:Y.type,livemode:Y.livemode,...G}),$.json({received:!0})})});function Z06($,Z){if(Z.startsWith("text/html")||Z.startsWith("image/svg"))$.set("Content-Security-Policy","sandbox allow-scripts allow-modals allow-same-origin")}var X06,rT$,aT$,Q06;var Y06=O(()=>{G4();wJ();Ch();Zb();X06=new S1,rT$=["range","if-none-match","if-modified-since"],aT$=["content-type","content-length","content-range","accept-ranges","etag","last-modified"];X06.get("/:org/files/*",async($)=>{let Z=$.get("studioContext"),X=Z.organization?.id;if(!Z.auth?.user?.id){if(mu($))return $.redirect(`/login?next=${encodeURIComponent($.req.path)}`,302);throw new W8(401,{message:"Authentication required"})}if(!X)throw new W8(401,{message:"Organization context required"});let Q=$.req.path.replace(/^.*\/files\//,"");if(!Q)throw new W8(400,{message:"Missing file key"});let Y=await dr(Q,Z);if(!Y)throw new W8(503,{message:"Object storage not configured"});if(Y.startsWith("data:")&&FJ()){let W=Y.match(/^data:([^;]+);base64,(.+)$/s);if(!W)throw new W8(500,{message:"Invalid data URL from storage"});let[,H,N]=W,U=Buffer.from(N,"base64"),F=new Headers({"Content-Type":H,"Cache-Control":"private, max-age=86400"});return Z06(F,H),new Response(U,{status:200,headers:F})}let G=new Headers;for(let W of rT$){let H=$.req.header(W);if(H)G.set(W,H)}let J=await fetch(Y,{headers:G});if(J.status===403||J.status===404)throw new W8(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 W8(502,{message:"Upstream storage error"});let K=new Headers;for(let W of aT$){let H=J.headers.get(W);if(H)K.set(W,H)}return K.set("Cache-Control","private, max-age=86400"),Z06(K,K.get("content-type")??""),new Response(J.body,{status:J.status,headers:K})});Q06=X06});var Xe=_((Rx)=>{var sT$=Rx&&Rx.__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]}),eT$=Rx&&Rx.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))sT$(Z,$,X)};Object.defineProperty(Rx,"__esModule",{value:!0});eT$(vY(),Rx)});var K06=_((G06)=>{Object.defineProperty(G06,"__esModule",{value:!0});G06.version=void 0;G06.version="3.4.0"});var N06=_((TH)=>{var $I$=TH&&TH.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(TH,"__esModule",{value:!0});TH.NodeTransport=TH.VERSION=void 0;TH.nodeResolveHost=JI$;var o$=Xe(),ZI$=N0("net"),rJ1=N0("tls"),XI$=N0("path"),W06=N0("fs"),QI$=$I$(N0("dns")),YI$=K06();TH.VERSION=YI$.version;var GI$="nats.js";class H06{socket;version;lang;yields=[];signal=(0,o$.deferred)();closedNotification=(0,o$.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=GI$,this.version=TH.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,o$.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 o$.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 o$.errors.ConnectionError("error connecting - node provided an undefined error");let{code:J}=G,K=J==="ECONNREFUSED"?new o$.errors.ConnectionError("connection refused",{cause:G}):G;throw this.socket?.destroy(),K}}dial($){let Z=(0,o$.deferred)(),X,Q=(0,ZI$.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,o$.deferred)(),Z;return this.socket.on("data",(X)=>{this.yields.push(X);let Q=o$.DataBuffer.concat(...this.yields),Y=(0,o$.extractProtocolMessage)(Q);if(Y!=="")try{let G=o$.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,o$.deferred)();try{if($=(0,XI$.resolve)($),!(0,W06.existsSync)($))Z.reject(Error(`${$} doesn't exist`));(0,W06.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,o$.extend)(X,this.options.tls,Y)}catch(Y){return Promise.reject(new o$.errors.ConnectionError(Y.message,{cause:Y}))}let Q=(0,o$.deferred)();try{let Y=(0,rJ1.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 o$.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,o$.extend)(Z,this.options.tls,Q)}catch(Q){return Promise.reject(new o$.errors.ConnectionError(Q.message,{cause:Q}))}let X=(0,o$.deferred)();try{let Q=(0,rJ1.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 o$.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,o$.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,o$.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 rJ1.TLSSocket}_send($){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,o$.render)($)}`);let Z=(0,o$.deferred)();try{this.socket.write($,(X)=>{if(X){if(this.options.debug)console.error(`!!! ${(0,o$.render)($)}: ${X}`);return Z.reject(X)}return Z.resolve()})}catch(X){if(this.options.debug)console.error(`!!! ${(0,o$.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}}TH.NodeTransport=H06;function JI$($){let Z=(0,o$.deferred)();return QI$.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 O06=_((B06)=>{Object.defineProperty(B06,"__esModule",{value:!0});B06.connect=KI$;var U06=N06(),F06=Xe(),w06=Xe();function KI$($={}){if((0,w06.hasWsProtocol)($))return Promise.reject(w06.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,F06.setTransportFactory)({factory:()=>{return new U06.NodeTransport},dnsResolveFn:U06.nodeResolveHost}),F06.NatsConnectionImpl.connect($)}});var L06=_((nU)=>{var HI$=nU&&nU.__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]}),NI$=nU&&nU.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))HI$(Z,$,X)};Object.defineProperty(nU,"__esModule",{value:!0});nU.connect=void 0;var UI$=O06();Object.defineProperty(nU,"connect",{enumerable:!0,get:function(){return UI$.connect}});NI$(Xe(),nU)});function j06($){let Z=$?.connectFn??OI$,X=null,Q=null,Y=!1,G=!1,J=!1,K=[];function W(){return X!==null&&!X.isClosed()&&!X.isDraining()&&!J}function H(){console.log(`[NatsProvider] fireReady: ${K.length} callbacks`);for(let F of K)try{F()}catch{}}function N(F){(async()=>{for await(let w of F.status())if(w.type==="disconnect")console.log("[NatsProvider] Disconnected"),J=!0;else if(w.type==="reconnect")console.log("[NatsProvider] Reconnected, re-firing ready callbacks"),J=!1,Q=null,H()})().catch(()=>{})}async function U(F,w){let B=0;while(!G)try{X=await Z({servers:F,timeout:BI$,reconnect:!0,maxReconnectAttempts:-1,...w?{authenticator:w}:{}}),console.log(`[NatsProvider] Connected to ${X.getServer()} after ${B} attempt(s)`),Q=null,J=!1,N(X),H();return}catch{B++;let L=zY(wI$,FI$,B-1,2,0.5);await m8(L)}}return{init(F,w){if(Y)return;Y=!0,G=!1;let B=w?.creds?D06.credsAuthenticator(new TextEncoder().encode(w.creds)):void 0;U(F,B).catch(()=>{})},isConnected(){return W()},getConnection(){return W()?X:null},getJetStream(){if(!W())return null;if(!Q)Q=z06.jetstream(X);return Q},onReady(F){if(K.push(F),W())try{F()}catch{}},async drain(){if(G=!0,Y=!1,Q=null,J=!1,X){let F=X;X=null,await F.drain().catch(()=>{})}}}}function OI$($){return E06.connect($)}var D06,E06,z06,FI$=100,wI$=3000,BI$=3000;var P06=O(()=>{W5();D06=k(Um(),1),E06=k(L06(),1),z06=k(SD(),1)});function aJ1($,Z){return`${$}.${Z}`}class sJ1{cache;constructor($){this.cache=cu({ttlMs:$?.ttlMs??LI$,maxSize:$?.maxSize??DI$})}async get($,Z){return this.cache.get(aJ1($,Z))??null}async set($,Z,X){this.cache.set(aJ1($,Z),X)}async invalidate($,Z){this.cache.delete(aJ1($,Z))}teardown(){this.cache.clear()}}var LI$=600000,DI$=5000;var A06=()=>{};function uR0($,Z){return`${$}:${Z}`}function eJ1($){let Z=cu({ttlMs:$?.ttlMs??EI$,maxSize:$?.maxSize??zI$}),X=$?.getConnection,Q=crypto.randomUUID(),Y=new TextEncoder,G=new TextDecoder,J=null;function K(W,H){let N=X?.();if(!N)return;try{N.publish(T06,Y.encode(JSON.stringify({organizationId:W,keyId:H,originId:Q})))}catch(U){console.warn("[ProviderKeyCache] Publish failed (non-critical):",U)}}return{get(W,H){return Z.get(uR0(W,H))},set(W,H,N){Z.set(uR0(W,H),N)},invalidate(W,H){Z.delete(uR0(W,H)),K(W,H)},start(){if(J)return;let W=X?.();if(!W)return;J=W.subscribe(T06),(async()=>{for await(let H of J)try{let N=JSON.parse(G.decode(H.data));if(N.originId===Q)continue;Z.delete(uR0(N.organizationId,N.keyId))}catch{}})().catch(console.error)},teardown(){J?.unsubscribe(),J=null,Z.clear()}}}var T06="studio.ai-provider-keys.invalidate",EI$=30000,zI$=5000;var I06=()=>{};class $K1{options;subscriptions=[];onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();seenMessageIds=new Set;constructor($){this.options=$}async start($){if($)this.onCancel=$;if(this.subscriptions.length>0)return;if(!this.onCancel)return;let Z=this.options.getConnection();if(!Z)return;let X=new TextDecoder;this.subscriptions=R06.map((Q)=>Z.subscribe(Q));for(let Q of this.subscriptions)(async()=>{for await(let Y of Q)try{let G=JSON.parse(X.decode(Y.data));if(G.originId===this.originId)continue;if(G.messageId&&this.hasSeen(G.messageId))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,messageId:crypto.randomUUID()}));for(let Q of R06)Z.publish(Q,X)}catch(Z){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",Z)}}publishControlFrame($,Z){}async stop(){for(let $ of this.subscriptions)$.unsubscribe();this.subscriptions=[],this.seenMessageIds.clear(),this.onCancel=null}hasSeen($){if(this.seenMessageIds.has($))return!0;if(this.seenMessageIds.add($),this.seenMessageIds.size>1000){let Z=this.seenMessageIds.values().next().value;if(Z)this.seenMessageIds.delete(Z)}return!1}}var R06;var q06=O(()=>{R06=["studio.decopilot.cancel","mesh.decopilot.cancel"]});var M06=($)=>{let Z;return()=>Z??=$()},ZK1,XK1;var k06=O(()=>{P5();ZK1=M06(()=>D6.createHistogram("decopilot.stream.encode_ms",{description:"Per-chunk JSON.stringify+encode time for decopilot stream",unit:"ms"})),XK1=M06(()=>D6.createCounter("decopilot.stream.published_chunks",{description:"Logical decopilot stream chunks published to JetStream",unit:"{chunks}"}))});function qI$(){return{name:zU,subjects:[`${aj0}.>`],storage:PK.StorageType.File,max_age:AI$,max_bytes:II$,max_msgs_per_subject:RI$,discard:PK.DiscardPolicy.Old,retention:PK.RetentionPolicy.Limits,duplicate_window:TI$,num_replicas:1}}class C06{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 S06($){let Z=V06.headers();for(let[X,Q]of Object.entries($))Z.set(X,Q);return Z}function VI$($,Z){let X=0;return{publish(Q,Y,G,J){Q.publish(Y,G,J?{headers:J}:void 0).catch((K)=>{if(X++,PI$().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 CI$($){if(!($ instanceof Error))return!1;if($.name==="TimeoutError")return!0;return/timeout|no responders|503/i.test($.message)}class QK1{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=qI$(),X=await rZ(async()=>{let Q=this.options.getJetStreamManager?await this.options.getJetStreamManager():await PK.jetstreamManager($);try{await Q.streams.info(zU),await Q.streams.update(zU,Z)}catch(Y){if(Y instanceof Error&&Y.message.includes("stream not found"))await Q.streams.add(Z);else if(Y instanceof Error&&/can ?not change.*storage|storage type/i.test(Y.message))await Q.streams.delete(zU),await Q.streams.add(Z);else throw Y}return Q},{maxAttempts:5,minTimeout:250,maxTimeout:4000,jitter:0.5,isRetriable:CI$});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=VI$(Z,Q),J=!1,K=()=>{if(J)return;J=!0;let H=pS8(Z);Y.publish(H.subject,H.data).catch(()=>{})};X.addEventListener("abort",K,{once:!0});let W=(H)=>{let N=performance.now(),U=i51(H,{runId:Z}),F=performance.now()-N;if(ZK1().record(F),XK1().add(1,{"org.id":Q??"unknown"}),SI$?.record(F,U.reduce((w,B)=>w+B.data.length,0)),U.length===0){console.warn(`[Decopilot] dropping oversized stream chunk for thread ${Z}`);return}for(let w of U)G.publish(Y,w.subject,w.data,w.headers?S06(w.headers):void 0)};return(async()=>{let H=$.getReader(),N=0,U=0,F;try{while(!0){let{done:w,value:B}=await H.read();if(w)break;if(W(B),U++,++N>=64)N=0,await new Promise((L)=>setImmediate(L))}}catch(w){F=w,console.warn(`[Decopilot] stream pump error for thread ${Z}:`,w?.message??w)}finally{if(H.releaseLock(),K(),kI$)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"pump-done",taskId:Z,publishedChunks:U,publishErrors:G.errorCount}))}if(F!==void 0)throw F})()}async publishRawChunk($,Z,X){let Q=this.js;if(!Q)return!1;let Y=performance.now(),G=i51(Z,{runId:$,dedup:X});if(ZK1().record(performance.now()-Y),XK1().add(1),G.length===0)return console.warn(`[Decopilot] dropping oversized raw chunk for thread ${$} (> MAX_CHUNKED_BYTES)`),!0;for(let J of G)await Q.publish(J.subject,J.data,{...J.headers?{headers:S06(J.headers)}:{},...J.msgId?{msgID:J.msgId}:{}});return!0}async publishDone($,Z,X){let Q=this.js;if(!Q)return!1;let Y=nS8({runId:$,fenceToken:Z,finalSeq:X});return await Q.publish(Y.subject,Y.data,{msgID:Y.msgId}),!0}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"?PK.DeliverPolicy.New:PK.DeliverPolicy.All,G=X?.closeOnDone??!1,J=AO($),K;try{K=await(await Q.consumers.get(zU,{filter_subjects:J,deliver_policy:Y})).consume()}catch(L){return console.warn("[Decopilot] JetStream tail unavailable (non-critical):",L?.message??L),null}let N=XP0({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(sj0()).pipeThrough(ej0()).getReader(),U=!1,F=()=>{if(U)return;U=!0;try{N.releaseLock()}catch{}},w=!1,B=()=>{if(w)return;w=!0,K.stop(),N.cancel().catch(()=>{}),F()};return Z?.addEventListener("abort",B,{once:!0}),new ReadableStream({async pull(L){for(;;){let{done:D,value:E}=await N.read();if(D){B(),L.close();return}let z=E;if(z.kind==="done"){if(G){B(),L.close();return}continue}L.enqueue(z.chunk);return}},cancel(){B()}})}purge($){if(!this.jsm)return;this.jsm.streams.purge(zU,{filter:AO($)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null}}var PK,V06,jI$=($)=>{let Z;return()=>Z??=$()},PI$,AI$=86400000000000,TI$=120000000000,II$=4294967296,RI$=500000,MI$,kI$,SI$;var _06=O(()=>{W5();n51();QP0();$P0();P5();k06();PK=k(SD(),1),V06=k(Um(),1),PI$=jI$(()=>D6.createCounter("decopilot.stream.publish_errors",{description:"Number of JetStream publish failures for decopilot stream chunks",unit:"{errors}"}));MI$=process.env.STREAM_ENCODE_TRACE==="1",kI$=process.env.DECOPILOT_STREAM_TRACE==="1";SI$=MI$?new C06:null});function cR0($,Z,X,Q){if(!Q)return!1;return $.emit(Z,sK(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,createdAt:Q.created_at,updatedAt:Q.updated_at})),!0}var x06=O(()=>{I6()});class YK1{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}}import{readdir as _I$,rm as lR0}from"fs/promises";import{join as dR0}from"path";async function mR0($){let Z=new Date;Z.setUTCDate(Z.getUTCDate()-xI$),Z.setUTCHours(0,0,0,0);let X=0;try{let Q=await qx($);for(let Y of Q)if(/^\d{4}$/.test(Y))X+=await v06($,Y,Z);else if(!Y.startsWith(".")){let G=dR0($,Y),J=await qx(G);for(let W of J){if(!/^\d{4}$/.test(W))continue;X+=await v06(G,W,Z)}if((await qx(G)).length===0)await lR0(G,{recursive:!0,force:!0})}}catch(Q){console.warn("monitoring retention cleanup failed:",Q)}return X}async function v06($,Z,X){let Q=0,Y=dR0($,Z),G=await qx(Y);for(let K of G){if(!/^\d{2}$/.test(K))continue;let W=dR0(Y,K),H=await qx(W);for(let U of H){if(!/^\d{2}$/.test(U))continue;let F=new Date(`${Z}-${K}-${U}T00:00:00Z`);if(isNaN(F.getTime()))continue;if(F<X){let w=dR0(W,U);await lR0(w,{recursive:!0,force:!0}),Q++}}if((await qx(W)).length===0)await lR0(W,{recursive:!0,force:!0})}if((await qx(Y)).length===0)await lR0(Y,{recursive:!0,force:!0});return Q}async function qx($){try{return(await _I$($)).filter((X)=>!X.startsWith("."))}catch{return[]}}var xI$=30;var GK1=()=>{};import{DBOS as JK1,SchedulerMode as vI$}from"@dbos-inc/dbos-sdk";async function bI$(){let $=[o3(),wf(),QN()],Z=0;for(let X of $)try{Z+=await mR0(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 yI$($,Z){await JK1.runStep(()=>bI$(),{name:"monitoringRetention"})}function b06(){if(f06)return;f06=!0;let $=JK1.registerWorkflow(yI$,{name:"monitoringRetentionWorkflow"});JK1.registerScheduled($,{name:"monitoringRetentionWorkflow",crontab:fI$,mode:vI$.ExactlyOncePerIntervalWhenActive})}var fI$="23 4 * * *",f06=!1;var y06=O(()=>{kY();GK1()});function g06($){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 vB.create();Y.auth.user={id:X,role:Q.role},Y.organization={id:Q.orgId,slug:Q.orgSlug,name:Q.orgName};let G=await P01($.db,Z,Q.role);return Y.boundAuth=j01({auth:Y.authInstance,headers:new Headers,role:Q.role,permissions:G,userId:X}),Y.access=new yE(X,void 0,Y.boundAuth,Q.role,"self"),YG0(Y,{id:Q.orgId,slug:Q.orgSlug}),Y}}var h06=O(()=>{gE();Wo()});import{EventEmitter as gI$}from"events";var KK1;var u06=O(()=>{LD();KK1=new gI$;KK1.on("request",($)=>{dF($)})});function c06(){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 F=await $.req.raw.clone().json();if(F.method==="tools/call"&&F.params?.name){let w=Fc(F.params.name),B=F.params.arguments||{},L=Object.keys(B).map((E)=>Fc(E)),D=L.length>0?L.slice(0,3).join(",")+(L.length>3?"\u2026":""):"";G=`${Q5.tool}${w}${Q5.dim}(${D})${Q5.reset}`}else if(F.method)G=`${Q5.dim}${Fc(F.method)}${Q5.reset}`}}catch{}}let K=Fc(Y);if(Y.startsWith("/mcp/conn_")){let N=Y.split("/")[2]??"";K=`/mcp/${Q5.mcp}${Fc(N.slice(0,12))}\u2026${Q5.reset}`}else if(Y==="/mcp")K=`${Q5.mcp}/mcp${Q5.reset}`;else if(Y==="/mcp/registry")K=`${Q5.mcp}/mcp/registry${Q5.reset}`;let W=uI$(Q),H=J?"\u25C0":"\u2190";if(!N50())console.log(`${Q5.dim}${H}${Q5.reset} ${W}${Q}${Q5.reset} ${K}${G?` ${G}`:""}`);try{await Z()}finally{let N=Date.now()-X,U=$.res.status,F=hI$(U),w=N<1000?`${N}ms`:`${(N/1000).toFixed(1)}s`,B=J?"\u25B6":"\u2192";if(!N50())console.log(`${Q5.dim}${B}${Q5.reset} ${W}${Q}${Q5.reset} ${K}${G?` ${G}`:""} ${F}${U}${Q5.reset} ${Q5.duration}${w}${Q5.reset}`);KK1.emit("request",{method:Q,path:Fc(Y),status:U,duration:N,timestamp:new Date})}}}var Q5,hI$=($)=>{if($>=500)return Q5.serverError;if($>=400)return Q5.clientError;if($>=300)return Q5.redirect;return Q5.ok},uI$=($)=>{return Q5[$]||Q5.reset},Fc=($)=>{return $.replace(/\r/g,"").replace(/\n/g,"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"")};var l06=O(()=>{LD();u06();Q5={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 n06}from"crypto";import{mkdir as cI$,readdir as lI$,rm as d06,stat as p06}from"fs/promises";import{join as HK1,relative as dI$}from"path";import{z as I8}from"zod";function o06($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return HK1(mI$,Z)}function r06($){return $.replace(/^\/+/,"").replace(/\.\./g,"")}function WK1($,Z){let X=o06($),Q=r06(Z);return HK1(X,Q)}function iI$($,Z,X,Q){let Y=J1().encryptionKey||"dev-secret",G=`${$}:${Z}:${X}:${Q}`;return n06("sha256",Y).update(G).digest("hex")}function i06($,Z,X,Q,Y){let G=Math.floor(Date.now()/1000)+Q,J=iI$(Z,X,G,Y),K=new URL(`/api/dev-assets/${Z}/${r06(X)}`,$);return K.searchParams.set("expires",G.toString()),K.searchParams.set("signature",J),K.searchParams.set("method",Y),K.toString()}function a06($,Z,X){let Q=`${$}:${Z.getTime()}:${X}`;return`"${n06("md5","etag").update(Q).digest("hex")}"`}async function s06($,Z,X,Q,Y){try{let G=await lI$($,{withFileTypes:!0});for(let J of G){let K=HK1($,J.name),H=dI$(Z,K).replace(/\\/g,"/");if(X&&!H.startsWith(X))continue;if(J.isDirectory())if(Q){let N=H+"/";if(!X||N.startsWith(X)){if(!(X?H.slice(X.length):H).includes("/"))Y.commonPrefixes.add(N)}}else await s06(K,Z,X,Q,Y);else if(J.isFile()){if(Q&&X){let N=H.slice(X.length);if(N.includes(Q)){let U=N.indexOf(Q),F=X+N.slice(0,U+1);Y.commonPrefixes.add(F);continue}}try{let N=await p06(K);Y.objects.push({key:H,size:N.size,lastModified:N.mtime.toISOString(),etag:a06(K,N.mtime,N.size)})}catch{}}}}catch{}}function e06($,Z){let Q=H0($).id;return[{name:"LIST_OBJECTS",description:"List objects in the local assets directory with pagination support",inputSchema:I8.object({prefix:I8.string().optional(),maxKeys:I8.number().optional().default(1000),continuationToken:I8.string().optional(),delimiter:I8.string().optional()}),outputSchema:I8.object({objects:I8.array(I8.object({key:I8.string(),size:I8.number(),lastModified:I8.string(),etag:I8.string()})),nextContinuationToken:I8.string().optional(),isTruncated:I8.boolean(),commonPrefixes:I8.array(I8.string()).optional()}),handler:async(Y)=>{let G=Y,J=G.prefix||"",K=G.maxKeys??1000,W=G.delimiter,H=G.continuationToken,N=o06(Q);await cI$(N,{recursive:!0});let U={objects:[],commonPrefixes:new Set};await s06(N,N,J,W,U),U.objects.sort((D,E)=>D.key.localeCompare(E.key));let F=0;if(H){if(F=U.objects.findIndex((D)=>D.key>H),F===-1)F=U.objects.length}let w=U.objects.slice(F,F+K),B=F+K<U.objects.length,L=B?w[w.length-1]?.key:void 0;return{objects:w,isTruncated:B,nextContinuationToken:L,commonPrefixes:Array.from(U.commonPrefixes).sort()}}},{name:"GET_OBJECT_METADATA",description:"Get metadata for a file in the local assets directory",inputSchema:I8.object({key:I8.string()}),outputSchema:I8.object({contentType:I8.string().optional(),contentLength:I8.number(),lastModified:I8.string(),etag:I8.string(),metadata:I8.record(I8.string(),I8.string()).optional()}),handler:async(Y)=>{let G=Y,J=WK1(Q,G.key),K=await p06(J);return{contentType:K31(G.key),contentLength:K.size,lastModified:K.mtime.toISOString(),etag:a06(J,K.mtime,K.size)}}},{name:"GET_PRESIGNED_URL",description:"Generate a presigned URL for downloading a file from local storage",inputSchema:I8.object({key:I8.string(),expiresIn:I8.number().optional()}),outputSchema:I8.object({url:I8.string(),expiresIn:I8.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??m06;return{url:i06(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:I8.object({key:I8.string(),expiresIn:I8.number().optional(),contentType:I8.string().optional()}),outputSchema:I8.object({url:I8.string(),expiresIn:I8.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??m06;return{url:i06(Z,Q,G.key,J,"PUT"),expiresIn:J}}},{name:"DELETE_OBJECT",description:"Delete a single file from local storage",inputSchema:I8.object({key:I8.string()}),outputSchema:I8.object({success:I8.boolean(),key:I8.string()}),handler:async(Y)=>{let G=Y,J=WK1(Q,G.key);try{return await d06(J),{success:!0,key:G.key}}catch{return{success:!1,key:G.key}}}},{name:"DELETE_OBJECTS",description:"Delete multiple files from local storage",inputSchema:I8.object({keys:I8.array(I8.string()).max(1000)}),outputSchema:I8.object({deleted:I8.array(I8.string()),errors:I8.array(I8.object({key:I8.string(),message:I8.string()}))}),handler:async(Y)=>{let G=Y,J=[],K=[];return await Promise.all(G.keys.map(async(W)=>{let H=WK1(Q,W);try{await d06(H),J.push(W)}catch(N){K.push({key:W,message:N instanceof Error?N.message:"Unknown error"})}})),{deleted:J,errors:K}}}]}async function NK1($,Z,X){let Q=e06(Z,X),Y=new VN({name:"dev-assets-mcp",version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:T5});for(let J of Q){let K="shape"in J.inputSchema?J.inputSchema.shape:I8.object({}).shape,W=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:I8.object({}).shape;Y.registerTool(J.name,{description:J.description??"",inputSchema:K,outputSchema:W,annotations:J.annotations,_meta:J._meta},async(H)=>{try{let N=await J.handler(H);return{content:[{type:"text",text:JSON.stringify(N)}],structuredContent:N}}catch(N){return{content:[{type:"text",text:`Error: ${N.message}`}],isError:!0}}})}let G=new UG({enableJsonResponse:$.headers.get("Accept")?.includes("application/json")??!1});return await Y.connect(G),ZH(Y,G,$,"mcp:dev-assets")}async function $16($,Z,X,Q){let G=e06(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 mI$="./data/assets",m06=3600,t06,Z16;var X16=O(()=>{c8();Ka();G4();mi();nh();pX();XR0();t06=new S1;t06.all("/",async($)=>{let Z=$.get("studioContext"),X=new URL($.req.url),Q=`${X.protocol}//${X.host}`;return NK1($.req.raw,Z,Q)});Z16=t06});var Q16={};z0(Q16,{mountDevRoutes:()=>nI$});function nI$($,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 NK1(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(),H=await $16(K,W,Y,J);if(H.isError)return Q.json(H.content,500);return Q.json(H.content)}),$.use("/mcp/dev-assets",Z),$.route("/mcp/dev-assets",Z16);let X=new S1;X.use("*",zK({mountPath:"/api/dev-assets"})),X.route("/",ZR0({orgFromPath:!1})),$.route("/api/dev-assets",X)}var Y16=O(()=>{G4();eG1();XR0();X16()});import{sql as pI$}from"kysely";import{randomUUID as G16}from"crypto";import{z as tI$}from"zod";async function rI$($){let Z=new Date().toISOString(),X=G16(),Q=p4.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:G16(),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 pI$`SELECT
|
|
3925
|
+
</head>`)}function ne8($){let Z=new S1;return Z.get("/:domain/og.png",async(X)=>{let Q=Uc(X.req.param("domain")),Y=async()=>{let G=$?Bun.file(ie8($,"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(`${HW({})}/api/v2/public/diagnostics/${encodeURIComponent(Q)}/og.png`,{signal:AbortSignal.timeout(hT$)}),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=$?ie8($,"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 bT$(Uc(Q)),W=yT$(Q,K);return X.html(gT$(J,W),200,{"Cache-Control":"public, max-age=0, s-maxage=300"})}catch{return X.html(J)}}),Z}var fT$=2500,hT$=1e4;var pe8=O(()=>{G4();iJ1();UE();c8()});function Ze($,Z){return fetch(`${HW({})}${$}`,Z)}async function uT$($,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 Ze(`/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}=gR0(J);return{status:K.slides.length?"ready":"empty",deck:K,scanned_at:J.scanned_at,drops:W}}var cT$,Ix,te8;var oe8=O(()=>{G4();w3();UE();iJ1();cT$=new Set(["complete","errored","terminated","unknown"]),Ix=new S1;Ix.use("*",async($,Z)=>{let X=await M6.api.getSession({headers:$.req.raw.headers});if(!X?.user?.id)return $.json({error:"Authentication required"},401,{"Cache-Control":"private, no-store",Vary:"Cookie"});$.set("reportUser",{email:X.user.email}),await Z(),$.header("Cache-Control","private, no-store"),$.header("Vary","Cookie");return});Ix.get("/site/:domain",async($)=>{let Z=$.req.param("domain").trim();if(!Z)return $.json({error:"domain is required"},400);let X=$.req.query("key")?.trim()||void 0,Q=$.req.query("lang")?.trim()||void 0;try{let Y=await uT$(Z,X,Q);return $.header("Cache-Control","private, no-store"),$.json(Y)}catch{return $.json({error:"report read failed"},502)}});Ix.post("/run",async($)=>{let Z;try{Z=await $.req.json()}catch{return $.json({error:"invalid JSON"},400)}let X=typeof Z.domain==="string"?Z.domain.trim():"";if(!X)return $.json({error:"domain is required"},400);let Q=$.get("reportUser").email,Y=typeof Z.distinctId==="string"&&Z.distinctId.trim()&&Z.distinctId.length<=200?Z.distinctId.trim():void 0;try{let G=await Ze("/api/v2/diagnostics/run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${NE({})}`},body:JSON.stringify({url:X,email:Q,distinct_id:Y})});if(!G.ok)return $.json({error:`run HTTP ${G.status}`},502);let J=await G.json(),K=J.blocked?{state:"blocked"}:J.status==="fresh"?{state:"fresh"}:J.mode==="sync"?{state:"sync"}:{state:"running",id:J.id??null};return $.json(K)}catch{return $.json({error:"run failed"},502)}});Ix.get("/status",async($)=>{let Z=$.req.query("id");if(!Z)return $.json({error:"id is required"},400);try{let X=await Ze(`/api/v2/diagnostics/status?id=${encodeURIComponent(Z)}`,{headers:{Authorization:`Bearer ${NE({})}`}});if(!X.ok)return $.json({error:`status HTTP ${X.status}`},502);let Y=(await X.json()).status??"unknown",G={done:cT$.has(Y),status:Y};return $.json(G)}catch{return $.json({error:"status failed"},502)}});Ix.get("/link-token/:id",async($)=>{let Z=$.req.param("id");try{let X=await Ze(`/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)}});Ix.get("/suggest",async($)=>{let Z=($.req.query("q")??"").trim().slice(0,64);if(Z.length<2)return $.json({suggestions:[]});try{let X=await Ze(`/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:[]})}});te8=Ix});import{createHmac as lT$,timingSafeEqual as dT$}from"crypto";function re8($,Z,X,Q=Date.now()){if(!Z||!X)return!1;let Y,G=[];for(let H of Z.split(",")){let N=H.indexOf("=");if(N<=0)continue;let U=H.slice(0,N).trim(),F=H.slice(N+1).trim();if(U==="t")Y=F;else if(U==="v1")G.push(F)}if(!Y||G.length===0)return!1;let J=Number(Y);if(!Number.isFinite(J)||Math.abs(Q/1000-J)>mT$)return!1;let K=lT$("sha256",X).update(`${Y}.${$}`).digest("hex"),W=Buffer.from(K,"hex");return G.some((H)=>{let N=Buffer.from(H,"hex");return W.length===N.length&&dT$(W,N)})}function ae8($){let Z;try{Z=JSON.parse($)}catch{return null}let X=x3(Z),Q=x3(x3(X?.data)?.object);if(!X||typeof X.type!=="string"||!Q)return null;return{id:AH(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 iT$($){switch($){case"active":case"trialing":return"active";case"past_due":return"past_due";default:return"canceled"}}function AH($){return typeof $==="string"?$:void 0}function x3($){return typeof $==="object"&&$!==null?$:void 0}function hR0($){return typeof $==="number"?new Date($*1000):null}function tJ1($){return AH($)??AH(x3($)?.id)}function nT$($){return tJ1($.subscription)??AH(x3(x3($.parent)?.subscription_details)?.subscription)}function pT$($){let Z=hR0($.current_period_end);if(Z)return Z;let X=x3($.items)?.data;if(!Array.isArray(X))return null;let Q=0;for(let Y of X){let G=x3(Y)?.current_period_end;if(typeof G==="number"&&G>Q)Q=G}return Q>0?new Date(Q*1000):null}function nJ1($,Z){let X=hR0($.created);return!!X&&!!Z.lastStripeEventAt&&X<Z.lastStripeEventAt}function pJ1($,Z){let X=hR0($.created);if(!X)return;return Z.lastStripeEventAt&&Z.lastStripeEventAt>X?void 0:X}async function tT$($,Z){let X=Z.data.object;switch(Z.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":{let Q=AH(x3(X.metadata)?.orgId);if(!Q)return{handled:!1,reason:"no orgId"};if(AH(x3(X.metadata)?.kind)==="topup"){if(X.mode!=="payment")return{handled:!1,reason:"topup with wrong mode"};if(AH(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let J=AH(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(x3(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:x3(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(AH(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=tJ1(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(nJ1(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Q,{stripeCustomerId:tJ1(X.customer),stripeSubscriptionId:G,status:"active",lastStripeEventAt:pJ1(Z,Y)}),{handled:!0,organizationId:Q}}case"customer.subscription.updated":case"customer.subscription.deleted":{let Q=AH(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&&nJ1(Z,Y))return{handled:!1,reason:"stale event"};let J=G?"canceled":iT$(X.status);return await $.updateStripeState(Y.organizationId,{status:J,currentPeriodEnd:pT$(X),...G&&{stripeSubscriptionId:null},lastStripeEventAt:pJ1(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}case"invoice.paid":{let Q=nT$(X);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};if(nJ1(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Y.organizationId,{status:"active",currentPeriodEnd:hR0(X.period_end),lastStripeEventAt:pJ1(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}default:return{handled:!1,reason:`unhandled event ${Z.type}`}}}async function se8($){let Z=new qp(w6().db),X=await tT$(Z,$);if(X.handled&&X.topUp)await N_8({organizationId:X.organizationId,amountCents:X.topUp.creditCents,referenceId:X.topUp.referenceId});if(!X.handled&&X.orphanSubscriptionId)try{await VB8(X.orphanSubscriptionId),console.error("stripe webhook: canceled orphan subscription",{subscriptionId:X.orphanSubscriptionId,eventId:$.id})}catch(Q){if(!(Q instanceof aJ&&(Q.status===400||Q.status===404)))throw Q}return X}var mT$=300;var ee8=O(()=>{d7();yo();qZ1()});var oT$=1048576,oJ1;var $06=O(()=>{G4();Fx();c8();ee8();oJ1=new S1;oJ1.post("/webhook",V7({maxSize:oT$,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=J1().stripeWebhookSecret;if(!Z)return $.json({error:"stripe billing not configured"},503);let X=await $.req.text();if(!re8(X,$.req.header("stripe-signature"),Z))return $.json({error:"invalid signature"},400);let Y=ae8(X);if(!Y)return $.json({error:"invalid payload"},400);let G=await se8(Y);return console.log("stripe webhook",{eventId:Y.id,type:Y.type,livemode:Y.livemode,...G}),$.json({received:!0})})});function Z06($,Z){if(Z.startsWith("text/html")||Z.startsWith("image/svg"))$.set("Content-Security-Policy","sandbox allow-scripts allow-modals allow-same-origin")}var X06,rT$,aT$,Q06;var Y06=O(()=>{G4();wJ();Ch();Zb();X06=new S1,rT$=["range","if-none-match","if-modified-since"],aT$=["content-type","content-length","content-range","accept-ranges","etag","last-modified"];X06.get("/:org/files/*",async($)=>{let Z=$.get("studioContext"),X=Z.organization?.id;if(!Z.auth?.user?.id){if(mu($))return $.redirect(`/login?next=${encodeURIComponent($.req.path)}`,302);throw new W8(401,{message:"Authentication required"})}if(!X)throw new W8(401,{message:"Organization context required"});let Q=$.req.path.replace(/^.*\/files\//,"");if(!Q)throw new W8(400,{message:"Missing file key"});let Y=await dr(Q,Z);if(!Y)throw new W8(503,{message:"Object storage not configured"});if(Y.startsWith("data:")&&FJ()){let W=Y.match(/^data:([^;]+);base64,(.+)$/s);if(!W)throw new W8(500,{message:"Invalid data URL from storage"});let[,H,N]=W,U=Buffer.from(N,"base64"),F=new Headers({"Content-Type":H,"Cache-Control":"private, max-age=86400"});return Z06(F,H),new Response(U,{status:200,headers:F})}let G=new Headers;for(let W of rT$){let H=$.req.header(W);if(H)G.set(W,H)}let J=await fetch(Y,{headers:G});if(J.status===403||J.status===404)throw new W8(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 W8(502,{message:"Upstream storage error"});let K=new Headers;for(let W of aT$){let H=J.headers.get(W);if(H)K.set(W,H)}return K.set("Cache-Control","private, max-age=86400"),Z06(K,K.get("content-type")??""),new Response(J.body,{status:J.status,headers:K})});Q06=X06});var Xe=_((Rx)=>{var sT$=Rx&&Rx.__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]}),eT$=Rx&&Rx.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))sT$(Z,$,X)};Object.defineProperty(Rx,"__esModule",{value:!0});eT$(vY(),Rx)});var K06=_((G06)=>{Object.defineProperty(G06,"__esModule",{value:!0});G06.version=void 0;G06.version="3.4.0"});var N06=_((TH)=>{var $I$=TH&&TH.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(TH,"__esModule",{value:!0});TH.NodeTransport=TH.VERSION=void 0;TH.nodeResolveHost=JI$;var o$=Xe(),ZI$=N0("net"),rJ1=N0("tls"),XI$=N0("path"),W06=N0("fs"),QI$=$I$(N0("dns")),YI$=K06();TH.VERSION=YI$.version;var GI$="nats.js";class H06{socket;version;lang;yields=[];signal=(0,o$.deferred)();closedNotification=(0,o$.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=GI$,this.version=TH.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,o$.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 o$.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 o$.errors.ConnectionError("error connecting - node provided an undefined error");let{code:J}=G,K=J==="ECONNREFUSED"?new o$.errors.ConnectionError("connection refused",{cause:G}):G;throw this.socket?.destroy(),K}}dial($){let Z=(0,o$.deferred)(),X,Q=(0,ZI$.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,o$.deferred)(),Z;return this.socket.on("data",(X)=>{this.yields.push(X);let Q=o$.DataBuffer.concat(...this.yields),Y=(0,o$.extractProtocolMessage)(Q);if(Y!=="")try{let G=o$.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,o$.deferred)();try{if($=(0,XI$.resolve)($),!(0,W06.existsSync)($))Z.reject(Error(`${$} doesn't exist`));(0,W06.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,o$.extend)(X,this.options.tls,Y)}catch(Y){return Promise.reject(new o$.errors.ConnectionError(Y.message,{cause:Y}))}let Q=(0,o$.deferred)();try{let Y=(0,rJ1.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 o$.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,o$.extend)(Z,this.options.tls,Q)}catch(Q){return Promise.reject(new o$.errors.ConnectionError(Q.message,{cause:Q}))}let X=(0,o$.deferred)();try{let Q=(0,rJ1.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 o$.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,o$.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,o$.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 rJ1.TLSSocket}_send($){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,o$.render)($)}`);let Z=(0,o$.deferred)();try{this.socket.write($,(X)=>{if(X){if(this.options.debug)console.error(`!!! ${(0,o$.render)($)}: ${X}`);return Z.reject(X)}return Z.resolve()})}catch(X){if(this.options.debug)console.error(`!!! ${(0,o$.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}}TH.NodeTransport=H06;function JI$($){let Z=(0,o$.deferred)();return QI$.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 O06=_((B06)=>{Object.defineProperty(B06,"__esModule",{value:!0});B06.connect=KI$;var U06=N06(),F06=Xe(),w06=Xe();function KI$($={}){if((0,w06.hasWsProtocol)($))return Promise.reject(w06.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,F06.setTransportFactory)({factory:()=>{return new U06.NodeTransport},dnsResolveFn:U06.nodeResolveHost}),F06.NatsConnectionImpl.connect($)}});var L06=_((nU)=>{var HI$=nU&&nU.__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]}),NI$=nU&&nU.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))HI$(Z,$,X)};Object.defineProperty(nU,"__esModule",{value:!0});nU.connect=void 0;var UI$=O06();Object.defineProperty(nU,"connect",{enumerable:!0,get:function(){return UI$.connect}});NI$(Xe(),nU)});function j06($){let Z=$?.connectFn??OI$,X=null,Q=null,Y=!1,G=!1,J=!1,K=[];function W(){return X!==null&&!X.isClosed()&&!X.isDraining()&&!J}function H(){console.log(`[NatsProvider] fireReady: ${K.length} callbacks`);for(let F of K)try{F()}catch{}}function N(F){(async()=>{for await(let w of F.status())if(w.type==="disconnect")console.log("[NatsProvider] Disconnected"),J=!0;else if(w.type==="reconnect")console.log("[NatsProvider] Reconnected, re-firing ready callbacks"),J=!1,Q=null,H()})().catch(()=>{})}async function U(F,w){let B=0;while(!G)try{X=await Z({servers:F,timeout:BI$,reconnect:!0,maxReconnectAttempts:-1,...w?{authenticator:w}:{}}),console.log(`[NatsProvider] Connected to ${X.getServer()} after ${B} attempt(s)`),Q=null,J=!1,N(X),H();return}catch{B++;let L=zY(wI$,FI$,B-1,2,0.5);await m8(L)}}return{init(F,w){if(Y)return;Y=!0,G=!1;let B=w?.creds?D06.credsAuthenticator(new TextEncoder().encode(w.creds)):void 0;U(F,B).catch(()=>{})},isConnected(){return W()},getConnection(){return W()?X:null},getJetStream(){if(!W())return null;if(!Q)Q=z06.jetstream(X);return Q},onReady(F){if(K.push(F),W())try{F()}catch{}},async drain(){if(G=!0,Y=!1,Q=null,J=!1,X){let F=X;X=null,await F.drain().catch(()=>{})}}}}function OI$($){return E06.connect($)}var D06,E06,z06,FI$=100,wI$=3000,BI$=3000;var P06=O(()=>{W5();D06=k(Um(),1),E06=k(L06(),1),z06=k(SD(),1)});function aJ1($,Z){return`${$}.${Z}`}class sJ1{cache;constructor($){this.cache=cu({ttlMs:$?.ttlMs??LI$,maxSize:$?.maxSize??DI$})}async get($,Z){return this.cache.get(aJ1($,Z))??null}async set($,Z,X){this.cache.set(aJ1($,Z),X)}async invalidate($,Z){this.cache.delete(aJ1($,Z))}teardown(){this.cache.clear()}}var LI$=600000,DI$=5000;var A06=()=>{};function uR0($,Z){return`${$}:${Z}`}function eJ1($){let Z=cu({ttlMs:$?.ttlMs??EI$,maxSize:$?.maxSize??zI$}),X=$?.getConnection,Q=crypto.randomUUID(),Y=new TextEncoder,G=new TextDecoder,J=null;function K(W,H){let N=X?.();if(!N)return;try{N.publish(T06,Y.encode(JSON.stringify({organizationId:W,keyId:H,originId:Q})))}catch(U){console.warn("[ProviderKeyCache] Publish failed (non-critical):",U)}}return{get(W,H){return Z.get(uR0(W,H))},set(W,H,N){Z.set(uR0(W,H),N)},invalidate(W,H){Z.delete(uR0(W,H)),K(W,H)},start(){if(J)return;let W=X?.();if(!W)return;J=W.subscribe(T06),(async()=>{for await(let H of J)try{let N=JSON.parse(G.decode(H.data));if(N.originId===Q)continue;Z.delete(uR0(N.organizationId,N.keyId))}catch{}})().catch(console.error)},teardown(){J?.unsubscribe(),J=null,Z.clear()}}}var T06="studio.ai-provider-keys.invalidate",EI$=30000,zI$=5000;var I06=()=>{};class $K1{options;subscriptions=[];onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();seenMessageIds=new Set;constructor($){this.options=$}async start($){if($)this.onCancel=$;if(this.subscriptions.length>0)return;if(!this.onCancel)return;let Z=this.options.getConnection();if(!Z)return;let X=new TextDecoder;this.subscriptions=R06.map((Q)=>Z.subscribe(Q));for(let Q of this.subscriptions)(async()=>{for await(let Y of Q)try{let G=JSON.parse(X.decode(Y.data));if(G.originId===this.originId)continue;if(G.messageId&&this.hasSeen(G.messageId))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,messageId:crypto.randomUUID()}));for(let Q of R06)Z.publish(Q,X)}catch(Z){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",Z)}}publishControlFrame($,Z){}async stop(){for(let $ of this.subscriptions)$.unsubscribe();this.subscriptions=[],this.seenMessageIds.clear(),this.onCancel=null}hasSeen($){if(this.seenMessageIds.has($))return!0;if(this.seenMessageIds.add($),this.seenMessageIds.size>1000){let Z=this.seenMessageIds.values().next().value;if(Z)this.seenMessageIds.delete(Z)}return!1}}var R06;var q06=O(()=>{R06=["studio.decopilot.cancel","mesh.decopilot.cancel"]});var M06=($)=>{let Z;return()=>Z??=$()},ZK1,XK1;var k06=O(()=>{P5();ZK1=M06(()=>D6.createHistogram("decopilot.stream.encode_ms",{description:"Per-chunk JSON.stringify+encode time for decopilot stream",unit:"ms"})),XK1=M06(()=>D6.createCounter("decopilot.stream.published_chunks",{description:"Logical decopilot stream chunks published to JetStream",unit:"{chunks}"}))});function qI$(){return{name:zU,subjects:[`${aj0}.>`],storage:PK.StorageType.File,max_age:AI$,max_bytes:II$,max_msgs_per_subject:RI$,discard:PK.DiscardPolicy.Old,retention:PK.RetentionPolicy.Limits,duplicate_window:TI$,num_replicas:1}}class C06{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 S06($){let Z=V06.headers();for(let[X,Q]of Object.entries($))Z.set(X,Q);return Z}function VI$($,Z){let X=0;return{publish(Q,Y,G,J){Q.publish(Y,G,J?{headers:J}:void 0).catch((K)=>{if(X++,PI$().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 CI$($){if(!($ instanceof Error))return!1;if($.name==="TimeoutError")return!0;return/timeout|no responders|503/i.test($.message)}class QK1{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=qI$(),X=await rZ(async()=>{let Q=this.options.getJetStreamManager?await this.options.getJetStreamManager():await PK.jetstreamManager($);try{await Q.streams.info(zU),await Q.streams.update(zU,Z)}catch(Y){if(Y instanceof Error&&Y.message.includes("stream not found"))await Q.streams.add(Z);else if(Y instanceof Error&&/can ?not change.*storage|storage type/i.test(Y.message))await Q.streams.delete(zU),await Q.streams.add(Z);else throw Y}return Q},{maxAttempts:5,minTimeout:250,maxTimeout:4000,jitter:0.5,isRetriable:CI$});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=VI$(Z,Q),J=!1,K=()=>{if(J)return;J=!0;let H=pS8(Z);Y.publish(H.subject,H.data).catch(()=>{})};X.addEventListener("abort",K,{once:!0});let W=(H)=>{let N=performance.now(),U=i51(H,{runId:Z}),F=performance.now()-N;if(ZK1().record(F),XK1().add(1,{"org.id":Q??"unknown"}),SI$?.record(F,U.reduce((w,B)=>w+B.data.length,0)),U.length===0){console.warn(`[Decopilot] dropping oversized stream chunk for thread ${Z}`);return}for(let w of U)G.publish(Y,w.subject,w.data,w.headers?S06(w.headers):void 0)};return(async()=>{let H=$.getReader(),N=0,U=0,F;try{while(!0){let{done:w,value:B}=await H.read();if(w)break;if(W(B),U++,++N>=64)N=0,await new Promise((L)=>setImmediate(L))}}catch(w){F=w,console.warn(`[Decopilot] stream pump error for thread ${Z}:`,w?.message??w)}finally{if(H.releaseLock(),K(),kI$)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"pump-done",taskId:Z,publishedChunks:U,publishErrors:G.errorCount}))}if(F!==void 0)throw F})()}async publishRawChunk($,Z,X){let Q=this.js;if(!Q)return!1;let Y=performance.now(),G=i51(Z,{runId:$,dedup:X});if(ZK1().record(performance.now()-Y),XK1().add(1),G.length===0)return console.warn(`[Decopilot] dropping oversized raw chunk for thread ${$} (> MAX_CHUNKED_BYTES)`),!0;for(let J of G)await Q.publish(J.subject,J.data,{...J.headers?{headers:S06(J.headers)}:{},...J.msgId?{msgID:J.msgId}:{}});return!0}async publishDone($,Z,X){let Q=this.js;if(!Q)return!1;let Y=nS8({runId:$,fenceToken:Z,finalSeq:X});return await Q.publish(Y.subject,Y.data,{msgID:Y.msgId}),!0}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"?PK.DeliverPolicy.New:PK.DeliverPolicy.All,G=X?.closeOnDone??!1,J=AO($),K;try{K=await(await Q.consumers.get(zU,{filter_subjects:J,deliver_policy:Y})).consume()}catch(L){return console.warn("[Decopilot] JetStream tail unavailable (non-critical):",L?.message??L),null}let N=XP0({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(sj0()).pipeThrough(ej0()).getReader(),U=!1,F=()=>{if(U)return;U=!0;try{N.releaseLock()}catch{}},w=!1,B=()=>{if(w)return;w=!0,K.stop(),N.cancel().catch(()=>{}),F()};return Z?.addEventListener("abort",B,{once:!0}),new ReadableStream({async pull(L){for(;;){let{done:D,value:E}=await N.read();if(D){B(),L.close();return}let z=E;if(z.kind==="done"){if(G){B(),L.close();return}continue}L.enqueue(z.chunk);return}},cancel(){B()}})}purge($){if(!this.jsm)return;this.jsm.streams.purge(zU,{filter:AO($)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null}}var PK,V06,jI$=($)=>{let Z;return()=>Z??=$()},PI$,AI$=86400000000000,TI$=120000000000,II$=4294967296,RI$=500000,MI$,kI$,SI$;var _06=O(()=>{W5();n51();QP0();$P0();P5();k06();PK=k(SD(),1),V06=k(Um(),1),PI$=jI$(()=>D6.createCounter("decopilot.stream.publish_errors",{description:"Number of JetStream publish failures for decopilot stream chunks",unit:"{errors}"}));MI$=process.env.STREAM_ENCODE_TRACE==="1",kI$=process.env.DECOPILOT_STREAM_TRACE==="1";SI$=MI$?new C06:null});function cR0($,Z,X,Q){if(!Q)return!1;return $.emit(Z,sK(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 x06=O(()=>{I6()});class YK1{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}}import{readdir as _I$,rm as lR0}from"fs/promises";import{join as dR0}from"path";async function mR0($){let Z=new Date;Z.setUTCDate(Z.getUTCDate()-xI$),Z.setUTCHours(0,0,0,0);let X=0;try{let Q=await qx($);for(let Y of Q)if(/^\d{4}$/.test(Y))X+=await v06($,Y,Z);else if(!Y.startsWith(".")){let G=dR0($,Y),J=await qx(G);for(let W of J){if(!/^\d{4}$/.test(W))continue;X+=await v06(G,W,Z)}if((await qx(G)).length===0)await lR0(G,{recursive:!0,force:!0})}}catch(Q){console.warn("monitoring retention cleanup failed:",Q)}return X}async function v06($,Z,X){let Q=0,Y=dR0($,Z),G=await qx(Y);for(let K of G){if(!/^\d{2}$/.test(K))continue;let W=dR0(Y,K),H=await qx(W);for(let U of H){if(!/^\d{2}$/.test(U))continue;let F=new Date(`${Z}-${K}-${U}T00:00:00Z`);if(isNaN(F.getTime()))continue;if(F<X){let w=dR0(W,U);await lR0(w,{recursive:!0,force:!0}),Q++}}if((await qx(W)).length===0)await lR0(W,{recursive:!0,force:!0})}if((await qx(Y)).length===0)await lR0(Y,{recursive:!0,force:!0});return Q}async function qx($){try{return(await _I$($)).filter((X)=>!X.startsWith("."))}catch{return[]}}var xI$=30;var GK1=()=>{};import{DBOS as JK1,SchedulerMode as vI$}from"@dbos-inc/dbos-sdk";async function bI$(){let $=[o3(),wf(),QN()],Z=0;for(let X of $)try{Z+=await mR0(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 yI$($,Z){await JK1.runStep(()=>bI$(),{name:"monitoringRetention"})}function b06(){if(f06)return;f06=!0;let $=JK1.registerWorkflow(yI$,{name:"monitoringRetentionWorkflow"});JK1.registerScheduled($,{name:"monitoringRetentionWorkflow",crontab:fI$,mode:vI$.ExactlyOncePerIntervalWhenActive})}var fI$="23 4 * * *",f06=!1;var y06=O(()=>{kY();GK1()});function g06($){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 vB.create();Y.auth.user={id:X,role:Q.role},Y.organization={id:Q.orgId,slug:Q.orgSlug,name:Q.orgName};let G=await P01($.db,Z,Q.role);return Y.boundAuth=j01({auth:Y.authInstance,headers:new Headers,role:Q.role,permissions:G,userId:X}),Y.access=new yE(X,void 0,Y.boundAuth,Q.role,"self"),YG0(Y,{id:Q.orgId,slug:Q.orgSlug}),Y}}var h06=O(()=>{gE();Wo()});import{EventEmitter as gI$}from"events";var KK1;var u06=O(()=>{LD();KK1=new gI$;KK1.on("request",($)=>{dF($)})});function c06(){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 F=await $.req.raw.clone().json();if(F.method==="tools/call"&&F.params?.name){let w=Fc(F.params.name),B=F.params.arguments||{},L=Object.keys(B).map((E)=>Fc(E)),D=L.length>0?L.slice(0,3).join(",")+(L.length>3?"\u2026":""):"";G=`${Q5.tool}${w}${Q5.dim}(${D})${Q5.reset}`}else if(F.method)G=`${Q5.dim}${Fc(F.method)}${Q5.reset}`}}catch{}}let K=Fc(Y);if(Y.startsWith("/mcp/conn_")){let N=Y.split("/")[2]??"";K=`/mcp/${Q5.mcp}${Fc(N.slice(0,12))}\u2026${Q5.reset}`}else if(Y==="/mcp")K=`${Q5.mcp}/mcp${Q5.reset}`;else if(Y==="/mcp/registry")K=`${Q5.mcp}/mcp/registry${Q5.reset}`;let W=uI$(Q),H=J?"\u25C0":"\u2190";if(!N50())console.log(`${Q5.dim}${H}${Q5.reset} ${W}${Q}${Q5.reset} ${K}${G?` ${G}`:""}`);try{await Z()}finally{let N=Date.now()-X,U=$.res.status,F=hI$(U),w=N<1000?`${N}ms`:`${(N/1000).toFixed(1)}s`,B=J?"\u25B6":"\u2192";if(!N50())console.log(`${Q5.dim}${B}${Q5.reset} ${W}${Q}${Q5.reset} ${K}${G?` ${G}`:""} ${F}${U}${Q5.reset} ${Q5.duration}${w}${Q5.reset}`);KK1.emit("request",{method:Q,path:Fc(Y),status:U,duration:N,timestamp:new Date})}}}var Q5,hI$=($)=>{if($>=500)return Q5.serverError;if($>=400)return Q5.clientError;if($>=300)return Q5.redirect;return Q5.ok},uI$=($)=>{return Q5[$]||Q5.reset},Fc=($)=>{return $.replace(/\r/g,"").replace(/\n/g,"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"")};var l06=O(()=>{LD();u06();Q5={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 n06}from"crypto";import{mkdir as cI$,readdir as lI$,rm as d06,stat as p06}from"fs/promises";import{join as HK1,relative as dI$}from"path";import{z as I8}from"zod";function o06($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return HK1(mI$,Z)}function r06($){return $.replace(/^\/+/,"").replace(/\.\./g,"")}function WK1($,Z){let X=o06($),Q=r06(Z);return HK1(X,Q)}function iI$($,Z,X,Q){let Y=J1().encryptionKey||"dev-secret",G=`${$}:${Z}:${X}:${Q}`;return n06("sha256",Y).update(G).digest("hex")}function i06($,Z,X,Q,Y){let G=Math.floor(Date.now()/1000)+Q,J=iI$(Z,X,G,Y),K=new URL(`/api/dev-assets/${Z}/${r06(X)}`,$);return K.searchParams.set("expires",G.toString()),K.searchParams.set("signature",J),K.searchParams.set("method",Y),K.toString()}function a06($,Z,X){let Q=`${$}:${Z.getTime()}:${X}`;return`"${n06("md5","etag").update(Q).digest("hex")}"`}async function s06($,Z,X,Q,Y){try{let G=await lI$($,{withFileTypes:!0});for(let J of G){let K=HK1($,J.name),H=dI$(Z,K).replace(/\\/g,"/");if(X&&!H.startsWith(X))continue;if(J.isDirectory())if(Q){let N=H+"/";if(!X||N.startsWith(X)){if(!(X?H.slice(X.length):H).includes("/"))Y.commonPrefixes.add(N)}}else await s06(K,Z,X,Q,Y);else if(J.isFile()){if(Q&&X){let N=H.slice(X.length);if(N.includes(Q)){let U=N.indexOf(Q),F=X+N.slice(0,U+1);Y.commonPrefixes.add(F);continue}}try{let N=await p06(K);Y.objects.push({key:H,size:N.size,lastModified:N.mtime.toISOString(),etag:a06(K,N.mtime,N.size)})}catch{}}}}catch{}}function e06($,Z){let Q=H0($).id;return[{name:"LIST_OBJECTS",description:"List objects in the local assets directory with pagination support",inputSchema:I8.object({prefix:I8.string().optional(),maxKeys:I8.number().optional().default(1000),continuationToken:I8.string().optional(),delimiter:I8.string().optional()}),outputSchema:I8.object({objects:I8.array(I8.object({key:I8.string(),size:I8.number(),lastModified:I8.string(),etag:I8.string()})),nextContinuationToken:I8.string().optional(),isTruncated:I8.boolean(),commonPrefixes:I8.array(I8.string()).optional()}),handler:async(Y)=>{let G=Y,J=G.prefix||"",K=G.maxKeys??1000,W=G.delimiter,H=G.continuationToken,N=o06(Q);await cI$(N,{recursive:!0});let U={objects:[],commonPrefixes:new Set};await s06(N,N,J,W,U),U.objects.sort((D,E)=>D.key.localeCompare(E.key));let F=0;if(H){if(F=U.objects.findIndex((D)=>D.key>H),F===-1)F=U.objects.length}let w=U.objects.slice(F,F+K),B=F+K<U.objects.length,L=B?w[w.length-1]?.key:void 0;return{objects:w,isTruncated:B,nextContinuationToken:L,commonPrefixes:Array.from(U.commonPrefixes).sort()}}},{name:"GET_OBJECT_METADATA",description:"Get metadata for a file in the local assets directory",inputSchema:I8.object({key:I8.string()}),outputSchema:I8.object({contentType:I8.string().optional(),contentLength:I8.number(),lastModified:I8.string(),etag:I8.string(),metadata:I8.record(I8.string(),I8.string()).optional()}),handler:async(Y)=>{let G=Y,J=WK1(Q,G.key),K=await p06(J);return{contentType:K31(G.key),contentLength:K.size,lastModified:K.mtime.toISOString(),etag:a06(J,K.mtime,K.size)}}},{name:"GET_PRESIGNED_URL",description:"Generate a presigned URL for downloading a file from local storage",inputSchema:I8.object({key:I8.string(),expiresIn:I8.number().optional()}),outputSchema:I8.object({url:I8.string(),expiresIn:I8.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??m06;return{url:i06(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:I8.object({key:I8.string(),expiresIn:I8.number().optional(),contentType:I8.string().optional()}),outputSchema:I8.object({url:I8.string(),expiresIn:I8.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??m06;return{url:i06(Z,Q,G.key,J,"PUT"),expiresIn:J}}},{name:"DELETE_OBJECT",description:"Delete a single file from local storage",inputSchema:I8.object({key:I8.string()}),outputSchema:I8.object({success:I8.boolean(),key:I8.string()}),handler:async(Y)=>{let G=Y,J=WK1(Q,G.key);try{return await d06(J),{success:!0,key:G.key}}catch{return{success:!1,key:G.key}}}},{name:"DELETE_OBJECTS",description:"Delete multiple files from local storage",inputSchema:I8.object({keys:I8.array(I8.string()).max(1000)}),outputSchema:I8.object({deleted:I8.array(I8.string()),errors:I8.array(I8.object({key:I8.string(),message:I8.string()}))}),handler:async(Y)=>{let G=Y,J=[],K=[];return await Promise.all(G.keys.map(async(W)=>{let H=WK1(Q,W);try{await d06(H),J.push(W)}catch(N){K.push({key:W,message:N instanceof Error?N.message:"Unknown error"})}})),{deleted:J,errors:K}}}]}async function NK1($,Z,X){let Q=e06(Z,X),Y=new VN({name:"dev-assets-mcp",version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:T5});for(let J of Q){let K="shape"in J.inputSchema?J.inputSchema.shape:I8.object({}).shape,W=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:I8.object({}).shape;Y.registerTool(J.name,{description:J.description??"",inputSchema:K,outputSchema:W,annotations:J.annotations,_meta:J._meta},async(H)=>{try{let N=await J.handler(H);return{content:[{type:"text",text:JSON.stringify(N)}],structuredContent:N}}catch(N){return{content:[{type:"text",text:`Error: ${N.message}`}],isError:!0}}})}let G=new UG({enableJsonResponse:$.headers.get("Accept")?.includes("application/json")??!1});return await Y.connect(G),ZH(Y,G,$,"mcp:dev-assets")}async function $16($,Z,X,Q){let G=e06(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 mI$="./data/assets",m06=3600,t06,Z16;var X16=O(()=>{c8();Ka();G4();mi();nh();pX();XR0();t06=new S1;t06.all("/",async($)=>{let Z=$.get("studioContext"),X=new URL($.req.url),Q=`${X.protocol}//${X.host}`;return NK1($.req.raw,Z,Q)});Z16=t06});var Q16={};z0(Q16,{mountDevRoutes:()=>nI$});function nI$($,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 NK1(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(),H=await $16(K,W,Y,J);if(H.isError)return Q.json(H.content,500);return Q.json(H.content)}),$.use("/mcp/dev-assets",Z),$.route("/mcp/dev-assets",Z16);let X=new S1;X.use("*",zK({mountPath:"/api/dev-assets"})),X.route("/",ZR0({orgFromPath:!1})),$.route("/api/dev-assets",X)}var Y16=O(()=>{G4();eG1();XR0();X16()});import{sql as pI$}from"kysely";import{randomUUID as G16}from"crypto";import{z as tI$}from"zod";async function rI$($){let Z=new Date().toISOString(),X=G16(),Q=p4.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:G16(),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 pI$`SELECT
|
|
3926
3926
|
pg_notify('studio_events', ${X}),
|
|
3927
3927
|
pg_notify('mesh_events', ${X})
|
|
3928
|
-
`.execute($.db)}catch{}}async function aI$($,Z){let Q=(await $.selectFrom("organization").select(["id"]).where("id","=",Z).execute())[0];if(Q?.id)return Q.id;return(await $.selectFrom("organization").select(["id"]).where("slug","=",Z).execute())[0]?.id??null}async function sI$($,Z){let X=await $.selectFrom("virtual_mcp_plugin_configs").innerJoin("connections","connections.id","virtual_mcp_plugin_configs.virtual_mcp_id").select(["virtual_mcp_plugin_configs.settings as settings"]).where("connections.organization_id","=",Z).where("virtual_mcp_plugin_configs.plugin_id","=",Wx).execute();for(let Q of X){let Y=Q.settings,G=typeof Y==="string"?(()=>{try{return JSON.parse(Y)}catch{return{}}})():Y??{};if(G.acceptPublishRequests===!0){let J=G.rateLimitWindow==="minute"?"minute":"hour",K=G.rateLimitMax,W=typeof K==="number"&&Number.isFinite(K)&&K>=1?Math.floor(K):K16;return{acceptPublishRequests:!0,requireApiToken:G.requireApiToken===!0,rateLimitEnabled:G.rateLimitEnabled===void 0?J16:G.rateLimitEnabled===!0,rateLimitWindow:J,rateLimitMax:W}}}return{acceptPublishRequests:!1,requireApiToken:!1,rateLimitEnabled:J16,rateLimitWindow:oI$,rateLimitMax:K16}}async function eI$($,Z,X){let Q=X==="minute"?60000:3600000,Y=new Date(Date.now()-Q).toISOString(),G=await $.selectFrom("private_registry_publish_request").select((J)=>J.fn.countAll().as("count")).where("organization_id","=",Z).where("created_at",">=",Y).executeTakeFirst();return Number(G?.count??0)}async function $R$($,Z,X,Q){let Y=await $.selectFrom("private_registry_item").select(["id","title"]).where("organization_id","=",Z).where((G)=>G.or([G("id","=",X),G("title","=",Q)])).executeTakeFirst();return Y?{id:String(Y.id),title:String(Y.title)}:null}function W16($){let{db:Z,db:X}=$,Q=new oy(X),Y=new ry(X);return async(G)=>{let J=G.req.param("orgRef")??G.req.param("org");if(!J)return G.json({error:"Organization not found"},404);let K=await aI$(Z,J);if(!K)return G.json({error:"Organization not found"},404);let W=await sI$(Z,K);if(!W.acceptPublishRequests)return G.json({error:"Publish requests are not enabled for this registry."},403);if(W.requireApiToken){let w=G.req.header("Authorization"),B=w?.startsWith("Bearer ")?w.slice(7).trim():null;if(!B)return G.json({error:"API key required. Use Authorization: Bearer <key>"},401);if(!await Y.validate(K,B))return G.json({error:"Invalid API key"},401)}if(W.rateLimitEnabled){if(await eI$(X,K,W.rateLimitWindow)>=W.rateLimitMax)return G.json({error:"Too many publish requests. Please try again later.",retryAfterSeconds:W.rateLimitWindow==="minute"?60:3600},429)}let H;try{H=await G.req.json()}catch{return G.json({error:"Invalid JSON body"},400)}let N=Jn8.safeParse(H);if(!N.success)return G.json({error:"Invalid publish request payload",details:tI$.treeifyError(N.error)},400);let U=await $R$(X,K,N.data.data.id,N.data.data.title);if(U)return G.json({error:"A registry item with the same id or title already exists. Please use a different name/id.",conflict:U},409);let F=await Q.createOrUpdate({organization_id:K,requested_id:N.data.data.id,title:N.data.data.title,description:N.data.data.description??null,_meta:N.data.data._meta,server:N.data.data.server,requester_name:N.data.requester?.name??null,requester_email:N.data.requester?.email??null});try{await rI$({db:Z,organizationId:K,request:F})}catch(w){console.warn("[private-registry] failed to emit publish-request event:",w)}return i1.capture({distinctId:N.data.requester?.email??`org:${K}`,event:"registry_publish_request_submitted",groups:{organization:K},properties:{organization_id:K,request_id:F.id,requested_id:F.requested_id,title:N.data.data.title,requester_email:N.data.requester?.email??null}}),G.json({id:F.id,requested_id:F.requested_id,status:F.status},201)}}var J16=!0,oI$="hour",K16=100;var H16=O(()=>{S$();I6();du();tr0();or0();O9()});var N16={};z0(N16,{createPublishRequestHandler:()=>W16,createPublicMCPHandler:()=>Fn8});var U16=O(()=>{lu();H16()});var z16={};z0(z16,{watchHandler:()=>E16,resolveCorsOrigin:()=>D16,isSsoExemptPath:()=>L16,createApp:()=>FR$});import{readFileSync as ZR$}from"fs";import{PrometheusSerializer as XR$}from"@opentelemetry/exporter-prometheus";import{DBOS as wc}from"@dbos-inc/dbos-sdk";import{oAuthDiscoveryMetadata as KR$,oAuthProtectedResourceMetadata as WR$}from"better-auth/plugins";async function QR$($){let Z=$.connect(),X;try{X=await Promise.race([Z,w16(F16)])}catch{return Z.then((Q)=>Q.release(!0)).catch(()=>{}),!1}try{return await Promise.race([X.query("SELECT 1"),w16(F16)]),X.release(),!0}catch{return X.release(!0),!1}}function w16($){return new Promise((Z,X)=>setTimeout(()=>X(Error("pg health-check timeout")),$))}async function YR$($,Z){let{items:X}=await $.storage.connections.list(Z,{where:{field:["connection_url"],operator:"like",value:`${Do1}%`},limit:1}),Q=X[0];if(!Q?.configuration_state)return null;return Q.configuration_state.project_locator}function GR$($){let Z=new URLSearchParams;if($){let[X,Q]=$.split("/");if(X)Z.set("workspace_hint",X);if(Q)Z.set("project_hint",Q)}else Z.set("auto_personal","true");return Z.set("force_new","true"),Z}function L16($){return $.startsWith("/api/org-sso/")||$.startsWith("/api/auth/")||$.startsWith("/api/tools/management")||$.startsWith("/oauth-proxy/")||/^\/api\/[^/]+\/oauth-proxy\//.test($)||$.startsWith(`${hG1}/`)}function D16($,{baseUrl:Z,requestOrigin:X}){let Q;try{Q=new URL($).hostname}catch{return null}if(Q==="localhost"||Q==="127.0.0.1")return $;let Y=Z??X;try{if(new URL(Y).origin===$)return $}catch{}return null}async function FR$($={}){let Z=$.database??w6(),X=!1;U9.stop().catch((o)=>{console.error("[SSEHub] Error stopping previous broadcast (HMR cleanup):",o)});let Q,Y,G=new sJ1,J,K,W,H=null;if($.disableNats)J=eJ1(),Q={get:async()=>null,set:async()=>{},invalidate:async()=>{},teardown:()=>{}},Y=new Wa,K={start:async()=>{},broadcast:()=>{},publishControlFrame:()=>{},stop:async()=>{}},W={init:async()=>{},pump:(o)=>{return(async()=>{let A0=o.getReader();try{while(!0){let{done:v0}=await A0.read();if(v0)break}}catch{}finally{A0.releaseLock()}})()},publishRawChunk:async()=>!1,publishDone:async()=>!1,createTailStream:async()=>null,purge:()=>{},teardown:()=>{}};else{H=j06();let o=J1().natsCredsPath,A0;if(o)try{A0=ZR$(o,"utf8")}catch(f1){console.error(`[app] failed to read NATS_CREDS at ${o}; connecting anonymously`,f1)}H.init(J1().natsUrls,A0?{creds:A0}:void 0);let v0=Qa0()?new it0({getJetStream:()=>H.getJetStream()}):null;v0?.init().catch(()=>{}),Q=v0;let F1=new $Z1({getJetStream:()=>H.getJetStream()});F1.init().catch(()=>{}),Y=F1,J=eJ1({getConnection:()=>H.getConnection()}),K=new $K1({getConnection:()=>H.getConnection()}),W=new QK1({getConnection:()=>H.getConnection(),getJetStream:()=>H.getJetStream()}),Vt8(H),H.onReady(()=>{v0?.init().catch((f1)=>{console.error("[McpListCache] Deferred init failed:",f1)}),F1.init().catch((f1)=>{console.error("[ConnectionCircuitStore] Deferred init failed:",f1)}),J.start(),K38(()=>H.getConnection()),W.init().catch((f1)=>{console.warn("[Decopilot] StreamBuffer init failed (late-join disabled):",f1)})})}if(Bc)await Bc();nt0(Q),ZZ1(Y);let U={storage:new Qg(Z.db),sseHub:U9},F=new s51(U),w=new xp(Z.db),B=new YK1(w);B.start(),K.start((o)=>{fj0(o),F.execute({type:"CANCEL",taskId:o}).catch((A0)=>{console.error("[Decopilot] CancelBroadcast execute failed:",A0)})}).catch((o)=>{console.error("[Decopilot] CancelBroadcast start failed:",o)}),H?.onReady(()=>{K.start().catch((o)=>{console.error("[CancelBroadcast] Deferred start failed:",o)})});let L=()=>H?.getConnection()??null;nG1(L),H?.onReady(()=>nG1(L)),W.init().catch((o)=>{console.warn("[Decopilot] StreamBuffer init failed, attach/late-join disabled:",o)}),Bc=async()=>{await F.stopAll(),F.dispose(),B.dispose(),K.stop().catch(()=>{}),Do8(),W.teardown(),Q?.teardown(),G.teardown(),J.teardown(),W38(),Y.teardown(),nt0(null),ZZ1(null)};let D=new S1;if(D.use("*",xm0({enabled:(o)=>Yb(o,"debug")==="1"})),D.use("*",ty0),D.use("/*",Xr1({origin:(o,A0)=>D16(o,{baseUrl:J1().baseUrl,requestOrigin:new URL(A0.req.url).origin}),credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"],exposeHeaders:["WWW-Authenticate"]})),D.use("*",async(o,A0)=>{if(await A0(),o.req.path.includes("/files/"))return;if(o.req.path.includes("/fs/")&&o.req.path.endsWith("/read"))return;o.header("X-Frame-Options","DENY"),o.header("Content-Security-Policy","frame-ancestors 'none'")}),!J1().noTui)D.use("*",c06());D.use("*",async(o,A0)=>{if(await A0(),Td(o.req.path))return;if(o.res.status>=500){let F1=await o.res.clone().text();console.error(`[5xx Response] ${o.req.method} ${o.req.path} - ${o.res.status}:`,F1)}}),D.get(Y7.HEALTH,(o)=>{if(X)return o.json({status:"shutting_down"},503);return o.json({status:"ok"})}),D.get(Y7.HEALTH_LIVE,(o)=>{return o.json({status:"ok"})}),D.get(Y7.HEALTH_READY,async(o)=>{if(X)return o.json({status:"shutting_down"},503);let A0={};if(A0.postgres={status:await QR$(Z.pool)?"up":"down"},H)A0.nats=H.isConnected()?{status:"up"}:{status:"down"};else A0.nats={status:"down"};let v0=A0.postgres.status==="up",F1=v0?200:503;return o.json({status:v0?"ready":"not_ready",services:A0},F1)}),D.get(Y7.METRICS,async(o)=>{try{let A0=await sy0.collect(),v0=JR$.serialize(A0.resourceMetrics);return o.text(v0,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch(A0){return console.error("Failed to collect metrics:",A0),o.text("# Error collecting metrics",500)}}),D.get(`${Y7.DBOS_QUEUE_DEPTH_PREFIX}:queueName`,async(o)=>{let A0=o.req.param("queueName");if(!HR$.has(A0))return o.json({error:`Unknown queue: ${A0}`},404);let v0=await wc.listQueuedWorkflows({queueName:A0,status:"ENQUEUED"});return o.json({queue_length:v0.length})}),D.get(Y7.HOSTED_RUN_PENDING,(o)=>{let{active:A0,pending:v0,max:F1}=AV8();return o.json({pending:v0,active:A0,max:F1})}),D.route("/api/config",ge8),D.route("/api/_reports",te8),D.route("/api/_stripe",oJ1),D.route("/report",ne8($.clientDir)),D.route("/api/auth/custom",at8),D.route("/api/auth/desktop",$o8),D.all("/api/auth/admin/*",Yo8),D.all("/api/auth/*",async(o)=>{return await M6.handler(o.req.raw)});let E=lU8();E.use("/.well-known/oauth-protected-resource/mcp/:connectionId",Nx),E.use("/mcp/:connectionId/.well-known/oauth-protected-resource",Nx),D.route("/",E),D.get("/.well-known/oauth-protected-resource/api/:org/mcp/:connectionId",Ho),D.route("/",nU8()),D.use("/oauth-proxy/:connectionId/*",Nx),D.all("/oauth-proxy/:connectionId/*",B16);let z=async(o)=>{let v0=await NR$()(o.req.raw),F1=await v0.json();return Response.json(F1,v0)};D.use("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",Nx),D.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",z);let j=async(o)=>{let v0=await UR$()(o.req.raw),F1=await v0.json();return Response.json(F1,v0)};D.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",j);let A=Mt8({ttlMs:120000}),P=await MU8({db:Z.db,auth:M6,encryption:{key:J1().encryptionKey},observability:{tracer:fF,meter:D6},modelListCache:G,providerKeyCache:J,memberRoleCache:A});vB.set(P);let R=new TN(J1().encryptionKey);Ut1({db:Z.db,baseUrl:AQ()});let S=LQ0(Z.db),M=new Tp(Z.db),C=g06({db:Z.db});o91({storage:S,studioContextFactory:C}),N91({studioContextFactory:C,deps:{runRegistry:F,cancelBroadcast:K,streamBuffer:W,sseHub:U9}}),Q91({dispatchRunFn:gS8,studioContextFactory:C,deps:{runRegistry:F,cancelBroadcast:K,streamBuffer:W,sseHub:U9}});let m=new Qg(Z.db),v=new cE(Z.db);JV8({getJetStream:()=>H?.getJetStream()??null,getJetStreamManager:async()=>{let o=H?.getConnection();return o?await O16.jetstreamManager(o):null},messageParts:m.messageParts(),resolveRun:async(o)=>{let A0=await Z.db.selectFrom("threads").select(["organization_id","created_by","message_storage_version","status","run_fence_token","title"]).where("id","=",o).executeTakeFirst();return A0?{orgId:A0.organization_id,createdBy:A0.created_by,version:A0.message_storage_version??1,status:A0.status,runFenceToken:A0.run_fence_token,title:A0.title??null}:null},completeRunIfNotCompleted:async(o,A0)=>{let v0=await m.completeRunIfNotCompleted(o,A0);if(cR0(U9,A0,o,v0),v0)await mr(v,o,A0),E91({contextFactory:C,taskBoard:v,threadId:o,orgId:A0});return v0},markRunRequiresAction:async(o,A0)=>{let v0=await m.requiresActionIfInProgress(o,A0);return cR0(U9,A0,o,v0),v0},markRunFailed:async(o,A0,v0,F1)=>{let f1=await m.markRunFailed(o,A0,v0,F1);if(cR0(U9,A0,o,f1),f1)await mr(v,o,A0),E91({contextFactory:C,taskBoard:v,threadId:o,orgId:A0});return f1},clearSynthesizedError:async(o,A0)=>{await m.messageParts().replaceMessageParts(o,PO(o,A0),[])},persistTitle:(o,A0,v0)=>m.update(o,A0,{title:v0}),onTitleUpdated:async({runId:o,orgId:A0,title:v0})=>{let F1=await m.get(o,A0).catch(()=>null);U9.emit(A0,sK(o,F1?.status??"in_progress",{title:v0,virtualMcpId:F1?.virtual_mcp_id??void 0,createdBy:F1?.created_by,triggerId:F1?.trigger_id,branch:F1?.branch??null,createdAt:F1?.created_at,updatedAt:F1?.updated_at}))},bumpProgress:async({runId:o,orgId:A0})=>{await m.bumpProgress(o,A0)},recordCompleted:async({runId:o,orgId:A0,distinctId:v0,usage:F1})=>{i1.capture({distinctId:v0,event:"chat_message_completed",groups:{organization:A0},properties:{organization_id:A0,thread_id:o,transport:"projector",input_tokens:F1.inputTokens,output_tokens:F1.outputTokens,total_tokens:F1.totalTokens}})},recordFailed:async({runId:o,orgId:A0,distinctId:v0,reason:F1,kind:f1})=>{i1.capture({distinctId:v0,event:"chat_message_failed",groups:{organization:A0},properties:{organization_id:A0,thread_id:o,transport:"projector",error_category:f1,error_message:F1}})},purgeRun:async(o)=>{W.purge(o)}}),JS8({studioContextFactory:C,systemDatabaseUrl:Yg0(J1().databaseUrl,J1().databasePgSsl),streamBuffer:W}),b06(),Ft1();let b=async(o,A0,v0)=>{let F1=await S.findById(o,A0);if(!F1)throw Error("Automation not found");return s91({automationId:F1.id,organizationId:F1.organization_id,triggerId:null})},p=new iu(S,({automation:o,trigger:A0,contextMessages:v0,idempotencyKey:F1})=>Ja({automationId:o.id,organizationId:o.organization_id,triggerId:A0.id,contextMessages:v0},{idempotencyKey:F1})),y=[o3(),wf(),QN()];for(let o of y)mR0(o).then(()=>{}).catch((A0)=>console.error("[monitoring] Retention cleanup failed:",A0));let Z0=()=>Z.db.deleteFrom("apikey").where("expiresAt","<",new Date).execute().then(()=>{}).catch((o)=>console.error("[auth] Expired API key cleanup failed:",o));Z0(),setInterval(Z0,86400000).unref(),D.use("*",async(o,A0)=>{if(ny0(o.req.path))return A0();let v0={measure:async(f1,d8)=>{iG(o,f1);try{return await d8()}finally{hY(o,f1)}}},F1=await vB.create(o.req.raw,{timings:v0});F1.automationRunner=b,o.set("studioContext",F1);try{await A0()}finally{let f1=F1.pendingRevalidations;if(f1.length>0)Promise.race([Promise.allSettled(f1),m8(30000)]).catch((o0)=>console.error("[studio] revalidation cleanup error:",o0))}}),D.use("/api/:org/decopilot/*",Ux),D.use("/api/:org/v1/*",Ux),D.use("/api/:org/files/*",Ux),D.use("*",async(o,A0)=>{if(L16(o.req.path))return A0();let v0=o.get("studioContext");if(!v0?.organization?.id||!v0?.auth?.user?.id)return A0();if(!(await v0.storage.orgSsoConfig.getByOrgId(v0.organization.id))?.enforced)return A0();if(!await v0.storage.orgSsoSessions.isValid(v0.auth.user.id,v0.organization.id))return o.json({error:"SSO authentication required for this organization"},403);return A0()});let U0=new S1;U0.use("*",zK({mountPath:"/api/org-sso"})),U0.route("/",iI0()),D.route("/api/org-sso",U0),D.get("/api/tools/management",(o)=>{return o.json({tools:fm0,grouped:gD()})}),D.use("/mcp/*",async(o,A0)=>{iG(o,"mcp");try{return await A0()}finally{hY(o,"mcp")}});let k0=async(o,A0)=>{let v0=o.var.studioContext;if(!v0.auth.user?.id&&!v0.auth.apiKey?.id){let F1=new URL(o.req.url),f1=o.req.header("x-forwarded-proto")?.split(",")[0]?.trim(),d8=f1?`${f1}://${F1.host}`:F1.origin;return o.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${d8}${F1.pathname}/.well-known/oauth-protected-resource"`}})}return await A0()};if(D.use("/mcp/:connectionId?",k0),D.use("/mcp/gateway/:virtualMcpId?",k0),D.use("/mcp/virtual-mcp/:virtualMcpId?",k0),D.use("/mcp/self",k0),FJ()){let{mountDevRoutes:o}=(Y16(),rR0(Q16));o(D,k0)}let $0=new S1;$0.use("*",zK({mountPath:"/mcp"})),$0.route("/",RP0()),D.route("/mcp",$0);let e=new S1;e.use("*",zK({mountPath:"/mcp/self"})),e.route("/",CR0()),D.route("/mcp/self",e);let I0=new S1;I0.use("*",zK({mountPath:"/mcp"})),I0.route("/",kP0()),D.route("/mcp",I0),D.use("/api/:org/models/*",async(o,A0)=>{iG(o,"llm_models");try{return await A0()}finally{hY(o,"llm_models")}});let Q0=aG1({cancelBroadcast:K,streamBuffer:W,runRegistry:F});D.route("/api",Q0),D.use("/api/:org/files/*",Ux),D.route("/api",Q06);let R0=new S1;R0.use("*",zK({mountPath:"/api"})),R0.route("/",_R0()),D.route("/api",R0),D.route("/api",fe8);let p0=new S1;p0.use("*",zK({mountPath:"/api"})),p0.route("/",xR0({tokenStorage:M,automationEventDispatcher:p})),D.route("/api",p0);let m0=new Rp(Z.db),r0=new S1;r0.use("*",zK({mountPath:"/api"})),r0.route("/",sI0()),D.route("/api",r0),D.route("/api/deco-sites",uo8()),D.route("/api/deco-apps",Se8());let K0=new S1;K0.use("*",zK({mountPath:"/api/deco-sites"})),K0.route("/",$R0()),D.route("/api/deco-sites",K0);let{createPublishRequestHandler:S0,createPublicMCPHandler:C0}=await Promise.resolve().then(() => (U16(),N16)),q0={db:Z.db,vault:{encrypt:(o)=>R.encrypt(o),decrypt:(o)=>R.decrypt(o)}},X0=S0(q0),W0=C0(q0);D.use("/org/:orgRef/registry/publish-request",Nx),D.post("/org/:orgRef/registry/publish-request",X0),D.use("/org/:orgSlug/registry/*",Nx),D.all("/org/:orgSlug/registry/*",W0),D.post("/api/:org/registry/publish-request",X0),D.all("/api/:org/registry/*",W0),D.route(hG1,Go8());let h0=Me8({kvStorage:m0,runRegistry:F,streamBuffer:W,sseHub:U9,cancelBroadcast:K,tokenStorage:M,automationEventDispatcher:p,mountDevAssets:FJ(),mcpAuth:k0,oauthProxyHandler:B16,watchHandler:E16,betterAuthProtectedResourceHandler:z,getNatsConnection:()=>H?.getConnection()??null});return D.route("/api/:org",h0),D.notFound((o)=>{return o.json({error:"Not Found",path:o.req.path},404)}),D.onError(Mo8),Object.assign(D,{markShuttingDown:()=>{X=!0},shutdown:async()=>{if(console.log("[shutdown] Stopping workers..."),await Promise.allSettled([U9.stop(),Bc?Promise.resolve(Bc()).finally(()=>{Bc=null}):Promise.resolve()]),H)await H.drain().catch((o)=>console.error("[shutdown] NATS drain error:",o));console.log("[shutdown] Flushing telemetry..."),await yG().catch((o)=>console.error("[shutdown] Telemetry flush error:",o)),console.log("[shutdown] Closing database..."),await gF(Z).catch((o)=>console.error("[shutdown] Database close error:",o)),console.log("[shutdown] Cleanup complete.")},initDbos:async()=>{await wc.registerQueue(uG,{partitionQueue:!0,concurrency:n91,minPollingIntervalMs:p91}),await wc.registerQueue(e3,{partitionQueue:!0,concurrency:W91}),await wc.registerQueue(JN,{partitionQueue:!0,concurrency:X91}),await wc.registerQueue(iF,{partitionQueue:!0,concurrency:GS8}),await Z31(S),await Promise.allSettled(["automations-gate","automations-global"].map((o)=>wc.deleteQueue(o))),await t91(Z.pool),n98().catch((o)=>{console.error("[studio-pack-backfill] failed:",o)}),wt1().catch((o)=>{console.error("[org-fs] public-sets boot sync kick failed:",o)})}})}var O16,F16=5000,Bc=null,B16=async($)=>{let Z=$.req.param("connectionId");if(!Z)return $.json({error:"Missing connectionId"},400);let X=$.req.path.split("/").filter(Boolean),Q=X[X.length-1],Y=$.get("studioContext");if(!Y)Y=await vB.create($.req.raw),$.set("studioContext",Y);let G=$.req.param("org")?Y.organization?.id:void 0,J=await Y.storage.connections.findById(Z,G);if(!J?.connection_url)return $.json({error:"Connection not found"},404);let K=await ug(J.connection_url),W,H=new URL(J.connection_url),U=(typeof J.metadata?.oauthResource==="string"&&J.metadata.oauthResource.length>0?J.metadata.oauthResource:void 0)??J.connection_url;if(K.ok)W=(await K.json()).authorization_servers?.[0];if(!W)W=H.origin;let F=await No(W);if(!F.ok)return $.json({error:"Failed to get auth server metadata"},502);let w=await F.json(),B;if(Q==="authorize")B=w.authorization_endpoint;else if(Q==="token")B=w.token_endpoint;else if(Q==="register")B=w.registration_endpoint;if(!B)return $.json({error:`Unknown OAuth endpoint: ${Q}`},404);let L=new URL(B),D=new URL($.req.url);if(L.search=D.search,Q==="authorize"){let m=L.searchParams.get("redirect_uri");if(m){let v=J1().baseUrl??D.origin;try{let b=new URL(m),p=new URL(v);if(!(b.origin===p.origin||b.hostname==="localhost"))return $.json({error:"invalid_request",error_description:"redirect_uri is not allowed"},400)}catch{return $.json({error:"invalid_request",error_description:"redirect_uri is malformed"},400)}L.searchParams.set("redirect_uri",m)}if(L.searchParams.has("resource"))L.searchParams.set("resource",U);if(Eo1(J.connection_url))try{let v=await YR$(Y,J.organization_id),b=GR$(v);for(let[p,y]of b)L.searchParams.set(p,y)}catch(v){console.warn("[oauth-proxy] Failed to get smart OAuth params, proceeding without:",v)}return $.redirect(L.toString(),302)}let E={Accept:$.req.header("Accept")||"application/json"},z=$.req.header("Content-Type");if(z)E["Content-Type"]=z;let j=$.req.header("Authorization");if(j)E.Authorization=j;let A,P=null,R=null;if($.req.method!=="GET"&&$.req.method!=="HEAD")if(Q==="token"&&z?.includes("application/x-www-form-urlencoded")){if(j?.toLowerCase().startsWith("basic "))try{let y=atob(j.slice(6).trim()),Z0=y.indexOf(":");if(Z0!==-1){let U0=decodeURIComponent(y.slice(0,Z0)),k0=decodeURIComponent(y.slice(Z0+1));P=U0||null,R=k0||null}}catch{}let m=await $.req.formData();if(m.has("resource"))m.set("resource",U);let v=m.get("client_id"),b=m.get("client_secret");if(typeof v==="string"&&v)P=v;if(typeof b==="string"&&b)R=b;let p=new URLSearchParams;for(let[y,Z0]of m.entries())p.append(y,Z0.toString());A=p.toString()}else if(Q==="register"&&z?.toLowerCase().includes("application/json")){let m=await Y.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",J.organization_id).executeTakeFirst(),v=await $.req.text(),b={};try{b=v?JSON.parse(v):{}}catch{A=v}let p=typeof b==="object"&&b!==null&&!Array.isArray(b);if(A===void 0&&!p)A=v;if(A===void 0){let y=b,Z0=y.metadata&&typeof y.metadata==="object"?y.metadata:{};y.metadata={...Z0,organization_id:J.organization_id,...m?.slug?{organization_slug:m.slug}:{},...m?.name?{organization_name:m.name}:{}},A=JSON.stringify(y),E["Content-Type"]="application/json"}}else A=$.req.raw.body??void 0;let S=await fetch(L.toString(),{method:$.req.method,headers:E,body:A,duplex:"half",redirect:"manual"}),M=new Headers,C=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[m,v]of S.headers.entries())if(!C.includes(m.toLowerCase()))M.set(m,v);if(Q==="token"&&S.ok){let m=await S.text();try{let v=JSON.parse(m);if(typeof v.access_token==="string"&&v.access_token){let b=typeof v.expires_in==="number"?new Date(Date.now()+v.expires_in*1000):null,p=null;try{p=await cg(J.connection_url)??B}catch{p=B}let y={connectionId:Z,accessToken:v.access_token,refreshToken:typeof v.refresh_token==="string"?v.refresh_token:null,scope:typeof v.scope==="string"?v.scope:null,expiresAt:b,clientId:P,clientSecret:R,tokenEndpoint:p};await new M5(Y.db,Y.vault).upsert(y)}}catch(v){console.error("[oauth-proxy] failed to persist downstream token:",v)}return new Response(m,{status:S.status,statusText:S.statusText,headers:M})}return new Response(S.body,{status:S.status,statusText:S.statusText,headers:M})},E16=async($)=>{let Z=$.var.studioContext;if(!(Z.auth.user?.id??Z.auth.apiKey?.userId))return $.json({error:"Unauthorized"},401);let Q=Z.organization?.id;if(!Q)return $.json({error:"organization id missing"},400);let Y=$.req.query("types"),G=Y?Y.split(",").map((K)=>K.trim()).filter(Boolean):null,J=crypto.randomUUID();return iU($,async(K)=>{if(await K.writeSSE({event:"connected",data:JSON.stringify({listenerId:J,organizationId:Q,typePatterns:G,connectedAt:new Date().toISOString()})}),!U9.add({id:J,organizationId:Q,typePatterns:G?.length?G:null,push:(N)=>{K.writeSSE({id:N.id,event:N.type,data:JSON.stringify(N)}).catch(()=>{U9.remove(Q,J)})}})){await K.writeSSE({event:"error",data:JSON.stringify({error:"Too many connections",message:"SSE connection limit reached. Try again later."})});return}let H=setInterval(()=>{K.writeSSE({event:"keepalive",data:""}).catch(()=>{clearInterval(H)})},30000);await new Promise((N)=>{K.onAbort(()=>{clearInterval(H),U9.remove(Q,J),N()})})})},JR$,HR$,NR$=()=>WR$(M6),UR$=()=>KR$(M6);var j16=O(()=>{W5();c8();Bt1();XZ();Zb();I6();G4();o90();Qr1();vm0();w3();Wo();CG1();d7();P5();S$();gG1();Zo8();Jo8();dG1();Ro8();sG1();iJ();GG0();eG1();ko8();$31();ke8();G31();Ve8();qP0();Uo();be8();SP0();SJ1();he8();pe8();oe8();$06();Y06();kJ1();qJ1();M$0();wi();P06();dY();gQ0();Sp();QZ1();A06();I06();q06();pG1();_06();e51();x06();Da0();bp();KQ();j91();Aa0();y06();WX0();GK1();kY();X31();q_();$91();r51();WX0();rj0();gr0();hr0();h06();Gb();l06();Hc();CG1();lj0();bj0();O16=k(SD(),1);JR$=new XR$,HR$=new Set([uG,e3,JN,iF])});var I16={};z0(I16,{resolveClientDir:()=>zR$,resolveAssetPathWithTraversalCheck:()=>T16,isPathWithinDirectory:()=>A16,createAssetHandler:()=>jR$});import{resolve as Qe,dirname as wR$,join as BR$,extname as OR$,basename as LR$,sep as P16}from"path";function DR$($,Z){if($===Z||LR$($)==="index.html")return{"Cache-Control":"no-cache"};if($.includes(`${P16}assets${P16}`))return{"Cache-Control":"public, max-age=31536000, immutable"};return{}}function A16($,Z){let X=Qe(Z),Q=Qe($);return Q===X||Q.startsWith(X+"/")}function T16({requestPath:$,clientDir:Z}){let X=$.startsWith("/")?$.slice(1):$,Q=Qe(Z,X);if(!A16(Q,Z))return null;return Q}function zR$($,Z="../client"){let X=new URL($),Q=wR$(X.pathname);return Qe(Q,Z)}function jR$($={}){let{env:Z="production",clientDir:X=ER$,isServerPath:Q=()=>!1}=$;if(Z==="development")return async function(G){return null};return async function(G){if(G.method!=="GET")return null;let J=new URL(G.url),K;try{K=decodeURIComponent(J.pathname)}catch{return null}if(Q(K))return null;let W=T16({requestPath:K,clientDir:X});if(!W)return null;let H=BR$(W,"index.html"),N=Qe(X,"index.html"),U=G.headers.get("accept"),w=U?.includes("text/html")||U?.includes("*/*")&&["",".html"].includes(OR$(W))?[H,N]:[];for(let B of[W,...w])try{let L=Bun.file(B);if(await L.exists())return new Response(L,{headers:DR$(B,N)})}catch{}if(K.includes("/assets/"))return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});return null}}var ER$="./dist/client";var R16=()=>{};var q16={};z0(q16,{tryUpgradePreviewWs:()=>MR$,tryHandlePreviewHttp:()=>qR$,previewWebSocketHandler:()=>kR$,parsePreviewBaseDomain:()=>RR$,isPreviewWsData:()=>iR0,extractHandleFromHost:()=>UK1});function TR$($){if($.method!=="GET")return!1;return($.headers.get("accept")??"").includes("text/html")}function IR$(){return new Response(AR$,{status:503,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","retry-after":"1","access-control-allow-origin":"*"}})}function RR$($){if(!$||$.trim()==="")return null;let Z=$.includes("{handle}")?$.replace("{handle}","__handle__"):$,X;try{X=new URL(Z)}catch{return null}let Q=X.hostname;if($.includes("{handle}")){let Y=Q.indexOf(".");if(Y<=0||Y===Q.length-1)return null;return Q.slice(Y+1)}return Q}function UK1($,Z){if(!$||!Z)return null;let X=$.indexOf(":"),Q=(X>=0?$.slice(0,X):$).toLowerCase(),G=`.${Z.toLowerCase().replace(/^\.+|\.+$/g,"")}`;if(!Q.endsWith(G))return null;let J=Q.slice(0,Q.length-G.length);if(!J||J.includes("."))return null;return J}async function qR$($,Z){let X=UK1($.headers.get("host"),Z.baseDomain);if(!X)return null;let Q=await Z.getRunner();if(!Q)return Ge(503,"preview proxy not configured");let Y=await Q.proxyPreviewRequest(X,$);if(Y.headers.get(F_)&&TR$($))return IR$();return Y.headers.delete(F_),Y}function Ge($,Z){return new Response(JSON.stringify({error:Z}),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function iR0($){return typeof $==="object"&&$!==null&&$.kind==="preview"}async function MR$($,Z,X){if(($.headers.get("upgrade")??"").toLowerCase()!=="websocket")return null;let Q=UK1($.headers.get("host"),X.baseDomain);if(!Q)return null;let Y=await X.getRunner();if(!Y)return Ge(503,"preview proxy not configured");let G=await Y.resolvePreviewUpstreamUrl(Q);if(!G)return Ge(404,"sandbox not found");let J=new URL($.url);if(J.pathname.startsWith("/_sandbox")||J.pathname.startsWith("/_decopilot_vm"))return Ge(404,"not found");let K=`${G.replace(/^http/,"ws")}${J.pathname}${J.search}`,W=$.headers.get("sec-websocket-protocol"),H=W?W.split(",").map((F)=>F.trim()).filter(Boolean):[],N={kind:"preview",upstreamUrl:K,upstreamProtocols:H,pending:[],upstream:null,closed:!1};if(!Z.upgrade($,{data:N}))return Ge(426,"upgrade failed");return}function Ye($,Z,X,Q){if(Z.closed)return;Z.closed=!0;try{$.close(X,Q)}catch{}try{Z.upstream?.close()}catch{}}var PR$=256,AR$='<!DOCTYPE html><html><head><meta charset="utf-8"><title>Connecting\u2026</title><style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#fafafa;color:#555}div{text-align:center;max-width:420px;padding:24px}h3{margin:0 0 8px}p{margin:0;font-size:14px;color:#999;line-height:1.5}</style></head><body><div><h3>Connecting to sandbox\u2026</h3><p>Waiting for the sandbox to come online. This page refreshes automatically.</p></div><script>setTimeout(function(){window.location.reload()},1500)</script></body></html>',kR$;var M16=O(()=>{f$1();kR$={open($){let Z=$.data;if(!iR0(Z))return;let X;try{X=Z.upstreamProtocols.length>0?new WebSocket(Z.upstreamUrl,Z.upstreamProtocols):new WebSocket(Z.upstreamUrl)}catch(Q){console.warn(`[preview-ws] failed to dial upstream ${Z.upstreamUrl}: ${Q instanceof Error?Q.message:String(Q)}`),Ye($,Z,1011,"upstream connect failed");return}X.binaryType="arraybuffer",Z.upstream=X,X.addEventListener("open",()=>{while(Z.pending.length>0){let Q=Z.pending.shift();if(Q!==void 0)X.send(Q)}}),X.addEventListener("message",(Q)=>{if(Z.closed)return;$.send(Q.data)}),X.addEventListener("close",(Q)=>{Ye($,Z,Q.code||1000,Q.reason||"")}),X.addEventListener("error",()=>{Ye($,Z,1011,"upstream error")})},message($,Z){let X=$.data;if(!iR0(X))return;let Q=X.upstream;if(Q&&Q.readyState===WebSocket.OPEN){Q.send(Z);return}if(X.pending.length>=PR$){Ye($,X,1011,"preview ws backlog overflow");return}X.pending.push(Z)},close($){let Z=$.data;if(!iR0(Z))return;Ye($,Z,1000,"")}}});var pR$={};import{existsSync as bR$}from"fs";function _16($,Z){if(!Z)return $;let X=new URL($);if(!X.searchParams.has("sslmode"))X.searchParams.set("sslmode","verify-full");return X.toString()}function hR$($){let Z=new Headers($.headers);for(let[X,Q]of Object.entries(gR$))Z.set(X,Q);return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}async function nR$($){let Z;try{Z=await SR$.create({systemDatabaseUrl:_16(v3.databaseUrl,v3.databasePgSsl),systemDatabaseSchemaName:"dbos"});let X=await Z.listWorkflows({status:"PENDING",queueName:e3,executorId:$,loadInput:!1,loadOutput:!1});if(X.length===0){console.log(`[shutdown] no in-flight thread-gate gates to hand off (executor ${$})`);return}let Q=X.map((Y)=>Y.workflowID);await Z.resumeWorkflows(Q,{queueName:e3}),console.log(`[shutdown] re-enqueued ${Q.length} in-flight thread-gate gate(s) for re-adoption by a live executor (from ${$}):`,Q)}catch(X){console.error("[shutdown] thread-gate handoff failed:",X)}finally{await Z?.destroy().catch(()=>{})}}async function pR0($){if(C16)return;C16=!0,console.log(`
|
|
3928
|
+
`.execute($.db)}catch{}}async function aI$($,Z){let Q=(await $.selectFrom("organization").select(["id"]).where("id","=",Z).execute())[0];if(Q?.id)return Q.id;return(await $.selectFrom("organization").select(["id"]).where("slug","=",Z).execute())[0]?.id??null}async function sI$($,Z){let X=await $.selectFrom("virtual_mcp_plugin_configs").innerJoin("connections","connections.id","virtual_mcp_plugin_configs.virtual_mcp_id").select(["virtual_mcp_plugin_configs.settings as settings"]).where("connections.organization_id","=",Z).where("virtual_mcp_plugin_configs.plugin_id","=",Wx).execute();for(let Q of X){let Y=Q.settings,G=typeof Y==="string"?(()=>{try{return JSON.parse(Y)}catch{return{}}})():Y??{};if(G.acceptPublishRequests===!0){let J=G.rateLimitWindow==="minute"?"minute":"hour",K=G.rateLimitMax,W=typeof K==="number"&&Number.isFinite(K)&&K>=1?Math.floor(K):K16;return{acceptPublishRequests:!0,requireApiToken:G.requireApiToken===!0,rateLimitEnabled:G.rateLimitEnabled===void 0?J16:G.rateLimitEnabled===!0,rateLimitWindow:J,rateLimitMax:W}}}return{acceptPublishRequests:!1,requireApiToken:!1,rateLimitEnabled:J16,rateLimitWindow:oI$,rateLimitMax:K16}}async function eI$($,Z,X){let Q=X==="minute"?60000:3600000,Y=new Date(Date.now()-Q).toISOString(),G=await $.selectFrom("private_registry_publish_request").select((J)=>J.fn.countAll().as("count")).where("organization_id","=",Z).where("created_at",">=",Y).executeTakeFirst();return Number(G?.count??0)}async function $R$($,Z,X,Q){let Y=await $.selectFrom("private_registry_item").select(["id","title"]).where("organization_id","=",Z).where((G)=>G.or([G("id","=",X),G("title","=",Q)])).executeTakeFirst();return Y?{id:String(Y.id),title:String(Y.title)}:null}function W16($){let{db:Z,db:X}=$,Q=new oy(X),Y=new ry(X);return async(G)=>{let J=G.req.param("orgRef")??G.req.param("org");if(!J)return G.json({error:"Organization not found"},404);let K=await aI$(Z,J);if(!K)return G.json({error:"Organization not found"},404);let W=await sI$(Z,K);if(!W.acceptPublishRequests)return G.json({error:"Publish requests are not enabled for this registry."},403);if(W.requireApiToken){let w=G.req.header("Authorization"),B=w?.startsWith("Bearer ")?w.slice(7).trim():null;if(!B)return G.json({error:"API key required. Use Authorization: Bearer <key>"},401);if(!await Y.validate(K,B))return G.json({error:"Invalid API key"},401)}if(W.rateLimitEnabled){if(await eI$(X,K,W.rateLimitWindow)>=W.rateLimitMax)return G.json({error:"Too many publish requests. Please try again later.",retryAfterSeconds:W.rateLimitWindow==="minute"?60:3600},429)}let H;try{H=await G.req.json()}catch{return G.json({error:"Invalid JSON body"},400)}let N=Jn8.safeParse(H);if(!N.success)return G.json({error:"Invalid publish request payload",details:tI$.treeifyError(N.error)},400);let U=await $R$(X,K,N.data.data.id,N.data.data.title);if(U)return G.json({error:"A registry item with the same id or title already exists. Please use a different name/id.",conflict:U},409);let F=await Q.createOrUpdate({organization_id:K,requested_id:N.data.data.id,title:N.data.data.title,description:N.data.data.description??null,_meta:N.data.data._meta,server:N.data.data.server,requester_name:N.data.requester?.name??null,requester_email:N.data.requester?.email??null});try{await rI$({db:Z,organizationId:K,request:F})}catch(w){console.warn("[private-registry] failed to emit publish-request event:",w)}return i1.capture({distinctId:N.data.requester?.email??`org:${K}`,event:"registry_publish_request_submitted",groups:{organization:K},properties:{organization_id:K,request_id:F.id,requested_id:F.requested_id,title:N.data.data.title,requester_email:N.data.requester?.email??null}}),G.json({id:F.id,requested_id:F.requested_id,status:F.status},201)}}var J16=!0,oI$="hour",K16=100;var H16=O(()=>{S$();I6();du();tr0();or0();O9()});var N16={};z0(N16,{createPublishRequestHandler:()=>W16,createPublicMCPHandler:()=>Fn8});var U16=O(()=>{lu();H16()});var z16={};z0(z16,{watchHandler:()=>E16,resolveCorsOrigin:()=>D16,isSsoExemptPath:()=>L16,createApp:()=>FR$});import{readFileSync as ZR$}from"fs";import{PrometheusSerializer as XR$}from"@opentelemetry/exporter-prometheus";import{DBOS as wc}from"@dbos-inc/dbos-sdk";import{oAuthDiscoveryMetadata as KR$,oAuthProtectedResourceMetadata as WR$}from"better-auth/plugins";async function QR$($){let Z=$.connect(),X;try{X=await Promise.race([Z,w16(F16)])}catch{return Z.then((Q)=>Q.release(!0)).catch(()=>{}),!1}try{return await Promise.race([X.query("SELECT 1"),w16(F16)]),X.release(),!0}catch{return X.release(!0),!1}}function w16($){return new Promise((Z,X)=>setTimeout(()=>X(Error("pg health-check timeout")),$))}async function YR$($,Z){let{items:X}=await $.storage.connections.list(Z,{where:{field:["connection_url"],operator:"like",value:`${Do1}%`},limit:1}),Q=X[0];if(!Q?.configuration_state)return null;return Q.configuration_state.project_locator}function GR$($){let Z=new URLSearchParams;if($){let[X,Q]=$.split("/");if(X)Z.set("workspace_hint",X);if(Q)Z.set("project_hint",Q)}else Z.set("auto_personal","true");return Z.set("force_new","true"),Z}function L16($){return $.startsWith("/api/org-sso/")||$.startsWith("/api/auth/")||$.startsWith("/api/tools/management")||$.startsWith("/oauth-proxy/")||/^\/api\/[^/]+\/oauth-proxy\//.test($)||$.startsWith(`${hG1}/`)}function D16($,{baseUrl:Z,requestOrigin:X}){let Q;try{Q=new URL($).hostname}catch{return null}if(Q==="localhost"||Q==="127.0.0.1")return $;let Y=Z??X;try{if(new URL(Y).origin===$)return $}catch{}return null}async function FR$($={}){let Z=$.database??w6(),X=!1;U9.stop().catch((o)=>{console.error("[SSEHub] Error stopping previous broadcast (HMR cleanup):",o)});let Q,Y,G=new sJ1,J,K,W,H=null;if($.disableNats)J=eJ1(),Q={get:async()=>null,set:async()=>{},invalidate:async()=>{},teardown:()=>{}},Y=new Wa,K={start:async()=>{},broadcast:()=>{},publishControlFrame:()=>{},stop:async()=>{}},W={init:async()=>{},pump:(o)=>{return(async()=>{let A0=o.getReader();try{while(!0){let{done:v0}=await A0.read();if(v0)break}}catch{}finally{A0.releaseLock()}})()},publishRawChunk:async()=>!1,publishDone:async()=>!1,createTailStream:async()=>null,purge:()=>{},teardown:()=>{}};else{H=j06();let o=J1().natsCredsPath,A0;if(o)try{A0=ZR$(o,"utf8")}catch(f1){console.error(`[app] failed to read NATS_CREDS at ${o}; connecting anonymously`,f1)}H.init(J1().natsUrls,A0?{creds:A0}:void 0);let v0=Qa0()?new it0({getJetStream:()=>H.getJetStream()}):null;v0?.init().catch(()=>{}),Q=v0;let F1=new $Z1({getJetStream:()=>H.getJetStream()});F1.init().catch(()=>{}),Y=F1,J=eJ1({getConnection:()=>H.getConnection()}),K=new $K1({getConnection:()=>H.getConnection()}),W=new QK1({getConnection:()=>H.getConnection(),getJetStream:()=>H.getJetStream()}),Vt8(H),H.onReady(()=>{v0?.init().catch((f1)=>{console.error("[McpListCache] Deferred init failed:",f1)}),F1.init().catch((f1)=>{console.error("[ConnectionCircuitStore] Deferred init failed:",f1)}),J.start(),K38(()=>H.getConnection()),W.init().catch((f1)=>{console.warn("[Decopilot] StreamBuffer init failed (late-join disabled):",f1)})})}if(Bc)await Bc();nt0(Q),ZZ1(Y);let U={storage:new Qg(Z.db),sseHub:U9},F=new s51(U),w=new xp(Z.db),B=new YK1(w);B.start(),K.start((o)=>{fj0(o),F.execute({type:"CANCEL",taskId:o}).catch((A0)=>{console.error("[Decopilot] CancelBroadcast execute failed:",A0)})}).catch((o)=>{console.error("[Decopilot] CancelBroadcast start failed:",o)}),H?.onReady(()=>{K.start().catch((o)=>{console.error("[CancelBroadcast] Deferred start failed:",o)})});let L=()=>H?.getConnection()??null;nG1(L),H?.onReady(()=>nG1(L)),W.init().catch((o)=>{console.warn("[Decopilot] StreamBuffer init failed, attach/late-join disabled:",o)}),Bc=async()=>{await F.stopAll(),F.dispose(),B.dispose(),K.stop().catch(()=>{}),Do8(),W.teardown(),Q?.teardown(),G.teardown(),J.teardown(),W38(),Y.teardown(),nt0(null),ZZ1(null)};let D=new S1;if(D.use("*",xm0({enabled:(o)=>Yb(o,"debug")==="1"})),D.use("*",ty0),D.use("/*",Xr1({origin:(o,A0)=>D16(o,{baseUrl:J1().baseUrl,requestOrigin:new URL(A0.req.url).origin}),credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"],exposeHeaders:["WWW-Authenticate"]})),D.use("*",async(o,A0)=>{if(await A0(),o.req.path.includes("/files/"))return;if(o.req.path.includes("/fs/")&&o.req.path.endsWith("/read"))return;o.header("X-Frame-Options","DENY"),o.header("Content-Security-Policy","frame-ancestors 'none'")}),!J1().noTui)D.use("*",c06());D.use("*",async(o,A0)=>{if(await A0(),Td(o.req.path))return;if(o.res.status>=500){let F1=await o.res.clone().text();console.error(`[5xx Response] ${o.req.method} ${o.req.path} - ${o.res.status}:`,F1)}}),D.get(Y7.HEALTH,(o)=>{if(X)return o.json({status:"shutting_down"},503);return o.json({status:"ok"})}),D.get(Y7.HEALTH_LIVE,(o)=>{return o.json({status:"ok"})}),D.get(Y7.HEALTH_READY,async(o)=>{if(X)return o.json({status:"shutting_down"},503);let A0={};if(A0.postgres={status:await QR$(Z.pool)?"up":"down"},H)A0.nats=H.isConnected()?{status:"up"}:{status:"down"};else A0.nats={status:"down"};let v0=A0.postgres.status==="up",F1=v0?200:503;return o.json({status:v0?"ready":"not_ready",services:A0},F1)}),D.get(Y7.METRICS,async(o)=>{try{let A0=await sy0.collect(),v0=JR$.serialize(A0.resourceMetrics);return o.text(v0,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch(A0){return console.error("Failed to collect metrics:",A0),o.text("# Error collecting metrics",500)}}),D.get(`${Y7.DBOS_QUEUE_DEPTH_PREFIX}:queueName`,async(o)=>{let A0=o.req.param("queueName");if(!HR$.has(A0))return o.json({error:`Unknown queue: ${A0}`},404);let v0=await wc.listQueuedWorkflows({queueName:A0,status:"ENQUEUED"});return o.json({queue_length:v0.length})}),D.get(Y7.HOSTED_RUN_PENDING,(o)=>{let{active:A0,pending:v0,max:F1}=AV8();return o.json({pending:v0,active:A0,max:F1})}),D.route("/api/config",ge8),D.route("/api/_reports",te8),D.route("/api/_stripe",oJ1),D.route("/report",ne8($.clientDir)),D.route("/api/auth/custom",at8),D.route("/api/auth/desktop",$o8),D.all("/api/auth/admin/*",Yo8),D.all("/api/auth/*",async(o)=>{return await M6.handler(o.req.raw)});let E=lU8();E.use("/.well-known/oauth-protected-resource/mcp/:connectionId",Nx),E.use("/mcp/:connectionId/.well-known/oauth-protected-resource",Nx),D.route("/",E),D.get("/.well-known/oauth-protected-resource/api/:org/mcp/:connectionId",Ho),D.route("/",nU8()),D.use("/oauth-proxy/:connectionId/*",Nx),D.all("/oauth-proxy/:connectionId/*",B16);let z=async(o)=>{let v0=await NR$()(o.req.raw),F1=await v0.json();return Response.json(F1,v0)};D.use("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",Nx),D.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",z);let j=async(o)=>{let v0=await UR$()(o.req.raw),F1=await v0.json();return Response.json(F1,v0)};D.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",j);let A=Mt8({ttlMs:120000}),P=await MU8({db:Z.db,auth:M6,encryption:{key:J1().encryptionKey},observability:{tracer:fF,meter:D6},modelListCache:G,providerKeyCache:J,memberRoleCache:A});vB.set(P);let R=new TN(J1().encryptionKey);Ut1({db:Z.db,baseUrl:AQ()});let S=LQ0(Z.db),M=new Tp(Z.db),C=g06({db:Z.db});o91({storage:S,studioContextFactory:C}),N91({studioContextFactory:C,deps:{runRegistry:F,cancelBroadcast:K,streamBuffer:W,sseHub:U9}}),Q91({dispatchRunFn:gS8,studioContextFactory:C,deps:{runRegistry:F,cancelBroadcast:K,streamBuffer:W,sseHub:U9}});let m=new Qg(Z.db),v=new cE(Z.db);JV8({getJetStream:()=>H?.getJetStream()??null,getJetStreamManager:async()=>{let o=H?.getConnection();return o?await O16.jetstreamManager(o):null},messageParts:m.messageParts(),resolveRun:async(o)=>{let A0=await Z.db.selectFrom("threads").select(["organization_id","created_by","message_storage_version","status","run_fence_token","title"]).where("id","=",o).executeTakeFirst();return A0?{orgId:A0.organization_id,createdBy:A0.created_by,version:A0.message_storage_version??1,status:A0.status,runFenceToken:A0.run_fence_token,title:A0.title??null}:null},completeRunIfNotCompleted:async(o,A0)=>{let v0=await m.completeRunIfNotCompleted(o,A0);if(cR0(U9,A0,o,v0),v0)await mr(v,o,A0),E91({contextFactory:C,taskBoard:v,threadId:o,orgId:A0});return v0},markRunRequiresAction:async(o,A0)=>{let v0=await m.requiresActionIfInProgress(o,A0);return cR0(U9,A0,o,v0),v0},markRunFailed:async(o,A0,v0,F1)=>{let f1=await m.markRunFailed(o,A0,v0,F1);if(cR0(U9,A0,o,f1),f1)await mr(v,o,A0),E91({contextFactory:C,taskBoard:v,threadId:o,orgId:A0});return f1},clearSynthesizedError:async(o,A0)=>{await m.messageParts().replaceMessageParts(o,PO(o,A0),[])},persistTitle:(o,A0,v0)=>m.update(o,A0,{title:v0}),onTitleUpdated:async({runId:o,orgId:A0,title:v0})=>{let F1=await m.get(o,A0).catch(()=>null);U9.emit(A0,sK(o,F1?.status??"in_progress",{title:v0,virtualMcpId:F1?.virtual_mcp_id??void 0,createdBy:F1?.created_by,triggerId:F1?.trigger_id,branch:F1?.branch??null,harnessId:F1?.harness_id??void 0,createdAt:F1?.created_at,updatedAt:F1?.updated_at}))},bumpProgress:async({runId:o,orgId:A0})=>{await m.bumpProgress(o,A0)},recordCompleted:async({runId:o,orgId:A0,distinctId:v0,usage:F1})=>{i1.capture({distinctId:v0,event:"chat_message_completed",groups:{organization:A0},properties:{organization_id:A0,thread_id:o,transport:"projector",input_tokens:F1.inputTokens,output_tokens:F1.outputTokens,total_tokens:F1.totalTokens}})},recordFailed:async({runId:o,orgId:A0,distinctId:v0,reason:F1,kind:f1})=>{i1.capture({distinctId:v0,event:"chat_message_failed",groups:{organization:A0},properties:{organization_id:A0,thread_id:o,transport:"projector",error_category:f1,error_message:F1}})},purgeRun:async(o)=>{W.purge(o)}}),JS8({studioContextFactory:C,systemDatabaseUrl:Yg0(J1().databaseUrl,J1().databasePgSsl),streamBuffer:W}),b06(),Ft1();let b=async(o,A0,v0)=>{let F1=await S.findById(o,A0);if(!F1)throw Error("Automation not found");return s91({automationId:F1.id,organizationId:F1.organization_id,triggerId:null})},p=new iu(S,({automation:o,trigger:A0,contextMessages:v0,idempotencyKey:F1})=>Ja({automationId:o.id,organizationId:o.organization_id,triggerId:A0.id,contextMessages:v0},{idempotencyKey:F1})),y=[o3(),wf(),QN()];for(let o of y)mR0(o).then(()=>{}).catch((A0)=>console.error("[monitoring] Retention cleanup failed:",A0));let Z0=()=>Z.db.deleteFrom("apikey").where("expiresAt","<",new Date).execute().then(()=>{}).catch((o)=>console.error("[auth] Expired API key cleanup failed:",o));Z0(),setInterval(Z0,86400000).unref(),D.use("*",async(o,A0)=>{if(ny0(o.req.path))return A0();let v0={measure:async(f1,d8)=>{iG(o,f1);try{return await d8()}finally{hY(o,f1)}}},F1=await vB.create(o.req.raw,{timings:v0});F1.automationRunner=b,o.set("studioContext",F1);try{await A0()}finally{let f1=F1.pendingRevalidations;if(f1.length>0)Promise.race([Promise.allSettled(f1),m8(30000)]).catch((o0)=>console.error("[studio] revalidation cleanup error:",o0))}}),D.use("/api/:org/decopilot/*",Ux),D.use("/api/:org/v1/*",Ux),D.use("/api/:org/files/*",Ux),D.use("*",async(o,A0)=>{if(L16(o.req.path))return A0();let v0=o.get("studioContext");if(!v0?.organization?.id||!v0?.auth?.user?.id)return A0();if(!(await v0.storage.orgSsoConfig.getByOrgId(v0.organization.id))?.enforced)return A0();if(!await v0.storage.orgSsoSessions.isValid(v0.auth.user.id,v0.organization.id))return o.json({error:"SSO authentication required for this organization"},403);return A0()});let U0=new S1;U0.use("*",zK({mountPath:"/api/org-sso"})),U0.route("/",iI0()),D.route("/api/org-sso",U0),D.get("/api/tools/management",(o)=>{return o.json({tools:fm0,grouped:gD()})}),D.use("/mcp/*",async(o,A0)=>{iG(o,"mcp");try{return await A0()}finally{hY(o,"mcp")}});let k0=async(o,A0)=>{let v0=o.var.studioContext;if(!v0.auth.user?.id&&!v0.auth.apiKey?.id){let F1=new URL(o.req.url),f1=o.req.header("x-forwarded-proto")?.split(",")[0]?.trim(),d8=f1?`${f1}://${F1.host}`:F1.origin;return o.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${d8}${F1.pathname}/.well-known/oauth-protected-resource"`}})}return await A0()};if(D.use("/mcp/:connectionId?",k0),D.use("/mcp/gateway/:virtualMcpId?",k0),D.use("/mcp/virtual-mcp/:virtualMcpId?",k0),D.use("/mcp/self",k0),FJ()){let{mountDevRoutes:o}=(Y16(),rR0(Q16));o(D,k0)}let $0=new S1;$0.use("*",zK({mountPath:"/mcp"})),$0.route("/",RP0()),D.route("/mcp",$0);let e=new S1;e.use("*",zK({mountPath:"/mcp/self"})),e.route("/",CR0()),D.route("/mcp/self",e);let I0=new S1;I0.use("*",zK({mountPath:"/mcp"})),I0.route("/",kP0()),D.route("/mcp",I0),D.use("/api/:org/models/*",async(o,A0)=>{iG(o,"llm_models");try{return await A0()}finally{hY(o,"llm_models")}});let Q0=aG1({cancelBroadcast:K,streamBuffer:W,runRegistry:F});D.route("/api",Q0),D.use("/api/:org/files/*",Ux),D.route("/api",Q06);let R0=new S1;R0.use("*",zK({mountPath:"/api"})),R0.route("/",_R0()),D.route("/api",R0),D.route("/api",fe8);let p0=new S1;p0.use("*",zK({mountPath:"/api"})),p0.route("/",xR0({tokenStorage:M,automationEventDispatcher:p})),D.route("/api",p0);let m0=new Rp(Z.db),r0=new S1;r0.use("*",zK({mountPath:"/api"})),r0.route("/",sI0()),D.route("/api",r0),D.route("/api/deco-sites",uo8()),D.route("/api/deco-apps",Se8());let K0=new S1;K0.use("*",zK({mountPath:"/api/deco-sites"})),K0.route("/",$R0()),D.route("/api/deco-sites",K0);let{createPublishRequestHandler:S0,createPublicMCPHandler:C0}=await Promise.resolve().then(() => (U16(),N16)),q0={db:Z.db,vault:{encrypt:(o)=>R.encrypt(o),decrypt:(o)=>R.decrypt(o)}},X0=S0(q0),W0=C0(q0);D.use("/org/:orgRef/registry/publish-request",Nx),D.post("/org/:orgRef/registry/publish-request",X0),D.use("/org/:orgSlug/registry/*",Nx),D.all("/org/:orgSlug/registry/*",W0),D.post("/api/:org/registry/publish-request",X0),D.all("/api/:org/registry/*",W0),D.route(hG1,Go8());let h0=Me8({kvStorage:m0,runRegistry:F,streamBuffer:W,sseHub:U9,cancelBroadcast:K,tokenStorage:M,automationEventDispatcher:p,mountDevAssets:FJ(),mcpAuth:k0,oauthProxyHandler:B16,watchHandler:E16,betterAuthProtectedResourceHandler:z,getNatsConnection:()=>H?.getConnection()??null});return D.route("/api/:org",h0),D.notFound((o)=>{return o.json({error:"Not Found",path:o.req.path},404)}),D.onError(Mo8),Object.assign(D,{markShuttingDown:()=>{X=!0},shutdown:async()=>{if(console.log("[shutdown] Stopping workers..."),await Promise.allSettled([U9.stop(),Bc?Promise.resolve(Bc()).finally(()=>{Bc=null}):Promise.resolve()]),H)await H.drain().catch((o)=>console.error("[shutdown] NATS drain error:",o));console.log("[shutdown] Flushing telemetry..."),await yG().catch((o)=>console.error("[shutdown] Telemetry flush error:",o)),console.log("[shutdown] Closing database..."),await gF(Z).catch((o)=>console.error("[shutdown] Database close error:",o)),console.log("[shutdown] Cleanup complete.")},initDbos:async()=>{await wc.registerQueue(uG,{partitionQueue:!0,concurrency:n91,minPollingIntervalMs:p91}),await wc.registerQueue(e3,{partitionQueue:!0,concurrency:W91}),await wc.registerQueue(JN,{partitionQueue:!0,concurrency:X91}),await wc.registerQueue(iF,{partitionQueue:!0,concurrency:GS8}),await Z31(S),await Promise.allSettled(["automations-gate","automations-global"].map((o)=>wc.deleteQueue(o))),await t91(Z.pool),n98().catch((o)=>{console.error("[studio-pack-backfill] failed:",o)}),wt1().catch((o)=>{console.error("[org-fs] public-sets boot sync kick failed:",o)})}})}var O16,F16=5000,Bc=null,B16=async($)=>{let Z=$.req.param("connectionId");if(!Z)return $.json({error:"Missing connectionId"},400);let X=$.req.path.split("/").filter(Boolean),Q=X[X.length-1],Y=$.get("studioContext");if(!Y)Y=await vB.create($.req.raw),$.set("studioContext",Y);let G=$.req.param("org")?Y.organization?.id:void 0,J=await Y.storage.connections.findById(Z,G);if(!J?.connection_url)return $.json({error:"Connection not found"},404);let K=await ug(J.connection_url),W,H=new URL(J.connection_url),U=(typeof J.metadata?.oauthResource==="string"&&J.metadata.oauthResource.length>0?J.metadata.oauthResource:void 0)??J.connection_url;if(K.ok)W=(await K.json()).authorization_servers?.[0];if(!W)W=H.origin;let F=await No(W);if(!F.ok)return $.json({error:"Failed to get auth server metadata"},502);let w=await F.json(),B;if(Q==="authorize")B=w.authorization_endpoint;else if(Q==="token")B=w.token_endpoint;else if(Q==="register")B=w.registration_endpoint;if(!B)return $.json({error:`Unknown OAuth endpoint: ${Q}`},404);let L=new URL(B),D=new URL($.req.url);if(L.search=D.search,Q==="authorize"){let m=L.searchParams.get("redirect_uri");if(m){let v=J1().baseUrl??D.origin;try{let b=new URL(m),p=new URL(v);if(!(b.origin===p.origin||b.hostname==="localhost"))return $.json({error:"invalid_request",error_description:"redirect_uri is not allowed"},400)}catch{return $.json({error:"invalid_request",error_description:"redirect_uri is malformed"},400)}L.searchParams.set("redirect_uri",m)}if(L.searchParams.has("resource"))L.searchParams.set("resource",U);if(Eo1(J.connection_url))try{let v=await YR$(Y,J.organization_id),b=GR$(v);for(let[p,y]of b)L.searchParams.set(p,y)}catch(v){console.warn("[oauth-proxy] Failed to get smart OAuth params, proceeding without:",v)}return $.redirect(L.toString(),302)}let E={Accept:$.req.header("Accept")||"application/json"},z=$.req.header("Content-Type");if(z)E["Content-Type"]=z;let j=$.req.header("Authorization");if(j)E.Authorization=j;let A,P=null,R=null;if($.req.method!=="GET"&&$.req.method!=="HEAD")if(Q==="token"&&z?.includes("application/x-www-form-urlencoded")){if(j?.toLowerCase().startsWith("basic "))try{let y=atob(j.slice(6).trim()),Z0=y.indexOf(":");if(Z0!==-1){let U0=decodeURIComponent(y.slice(0,Z0)),k0=decodeURIComponent(y.slice(Z0+1));P=U0||null,R=k0||null}}catch{}let m=await $.req.formData();if(m.has("resource"))m.set("resource",U);let v=m.get("client_id"),b=m.get("client_secret");if(typeof v==="string"&&v)P=v;if(typeof b==="string"&&b)R=b;let p=new URLSearchParams;for(let[y,Z0]of m.entries())p.append(y,Z0.toString());A=p.toString()}else if(Q==="register"&&z?.toLowerCase().includes("application/json")){let m=await Y.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",J.organization_id).executeTakeFirst(),v=await $.req.text(),b={};try{b=v?JSON.parse(v):{}}catch{A=v}let p=typeof b==="object"&&b!==null&&!Array.isArray(b);if(A===void 0&&!p)A=v;if(A===void 0){let y=b,Z0=y.metadata&&typeof y.metadata==="object"?y.metadata:{};y.metadata={...Z0,organization_id:J.organization_id,...m?.slug?{organization_slug:m.slug}:{},...m?.name?{organization_name:m.name}:{}},A=JSON.stringify(y),E["Content-Type"]="application/json"}}else A=$.req.raw.body??void 0;let S=await fetch(L.toString(),{method:$.req.method,headers:E,body:A,duplex:"half",redirect:"manual"}),M=new Headers,C=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[m,v]of S.headers.entries())if(!C.includes(m.toLowerCase()))M.set(m,v);if(Q==="token"&&S.ok){let m=await S.text();try{let v=JSON.parse(m);if(typeof v.access_token==="string"&&v.access_token){let b=typeof v.expires_in==="number"?new Date(Date.now()+v.expires_in*1000):null,p=null;try{p=await cg(J.connection_url)??B}catch{p=B}let y={connectionId:Z,accessToken:v.access_token,refreshToken:typeof v.refresh_token==="string"?v.refresh_token:null,scope:typeof v.scope==="string"?v.scope:null,expiresAt:b,clientId:P,clientSecret:R,tokenEndpoint:p};await new M5(Y.db,Y.vault).upsert(y)}}catch(v){console.error("[oauth-proxy] failed to persist downstream token:",v)}return new Response(m,{status:S.status,statusText:S.statusText,headers:M})}return new Response(S.body,{status:S.status,statusText:S.statusText,headers:M})},E16=async($)=>{let Z=$.var.studioContext;if(!(Z.auth.user?.id??Z.auth.apiKey?.userId))return $.json({error:"Unauthorized"},401);let Q=Z.organization?.id;if(!Q)return $.json({error:"organization id missing"},400);let Y=$.req.query("types"),G=Y?Y.split(",").map((K)=>K.trim()).filter(Boolean):null,J=crypto.randomUUID();return iU($,async(K)=>{if(await K.writeSSE({event:"connected",data:JSON.stringify({listenerId:J,organizationId:Q,typePatterns:G,connectedAt:new Date().toISOString()})}),!U9.add({id:J,organizationId:Q,typePatterns:G?.length?G:null,push:(N)=>{K.writeSSE({id:N.id,event:N.type,data:JSON.stringify(N)}).catch(()=>{U9.remove(Q,J)})}})){await K.writeSSE({event:"error",data:JSON.stringify({error:"Too many connections",message:"SSE connection limit reached. Try again later."})});return}let H=setInterval(()=>{K.writeSSE({event:"keepalive",data:""}).catch(()=>{clearInterval(H)})},30000);await new Promise((N)=>{K.onAbort(()=>{clearInterval(H),U9.remove(Q,J),N()})})})},JR$,HR$,NR$=()=>WR$(M6),UR$=()=>KR$(M6);var j16=O(()=>{W5();c8();Bt1();XZ();Zb();I6();G4();o90();Qr1();vm0();w3();Wo();CG1();d7();P5();S$();gG1();Zo8();Jo8();dG1();Ro8();sG1();iJ();GG0();eG1();ko8();$31();ke8();G31();Ve8();qP0();Uo();be8();SP0();SJ1();he8();pe8();oe8();$06();Y06();kJ1();qJ1();M$0();wi();P06();dY();gQ0();Sp();QZ1();A06();I06();q06();pG1();_06();e51();x06();Da0();bp();KQ();j91();Aa0();y06();WX0();GK1();kY();X31();q_();$91();r51();WX0();rj0();gr0();hr0();h06();Gb();l06();Hc();CG1();lj0();bj0();O16=k(SD(),1);JR$=new XR$,HR$=new Set([uG,e3,JN,iF])});var I16={};z0(I16,{resolveClientDir:()=>zR$,resolveAssetPathWithTraversalCheck:()=>T16,isPathWithinDirectory:()=>A16,createAssetHandler:()=>jR$});import{resolve as Qe,dirname as wR$,join as BR$,extname as OR$,basename as LR$,sep as P16}from"path";function DR$($,Z){if($===Z||LR$($)==="index.html")return{"Cache-Control":"no-cache"};if($.includes(`${P16}assets${P16}`))return{"Cache-Control":"public, max-age=31536000, immutable"};return{}}function A16($,Z){let X=Qe(Z),Q=Qe($);return Q===X||Q.startsWith(X+"/")}function T16({requestPath:$,clientDir:Z}){let X=$.startsWith("/")?$.slice(1):$,Q=Qe(Z,X);if(!A16(Q,Z))return null;return Q}function zR$($,Z="../client"){let X=new URL($),Q=wR$(X.pathname);return Qe(Q,Z)}function jR$($={}){let{env:Z="production",clientDir:X=ER$,isServerPath:Q=()=>!1}=$;if(Z==="development")return async function(G){return null};return async function(G){if(G.method!=="GET")return null;let J=new URL(G.url),K;try{K=decodeURIComponent(J.pathname)}catch{return null}if(Q(K))return null;let W=T16({requestPath:K,clientDir:X});if(!W)return null;let H=BR$(W,"index.html"),N=Qe(X,"index.html"),U=G.headers.get("accept"),w=U?.includes("text/html")||U?.includes("*/*")&&["",".html"].includes(OR$(W))?[H,N]:[];for(let B of[W,...w])try{let L=Bun.file(B);if(await L.exists())return new Response(L,{headers:DR$(B,N)})}catch{}if(K.includes("/assets/"))return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});return null}}var ER$="./dist/client";var R16=()=>{};var q16={};z0(q16,{tryUpgradePreviewWs:()=>MR$,tryHandlePreviewHttp:()=>qR$,previewWebSocketHandler:()=>kR$,parsePreviewBaseDomain:()=>RR$,isPreviewWsData:()=>iR0,extractHandleFromHost:()=>UK1});function TR$($){if($.method!=="GET")return!1;return($.headers.get("accept")??"").includes("text/html")}function IR$(){return new Response(AR$,{status:503,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","retry-after":"1","access-control-allow-origin":"*"}})}function RR$($){if(!$||$.trim()==="")return null;let Z=$.includes("{handle}")?$.replace("{handle}","__handle__"):$,X;try{X=new URL(Z)}catch{return null}let Q=X.hostname;if($.includes("{handle}")){let Y=Q.indexOf(".");if(Y<=0||Y===Q.length-1)return null;return Q.slice(Y+1)}return Q}function UK1($,Z){if(!$||!Z)return null;let X=$.indexOf(":"),Q=(X>=0?$.slice(0,X):$).toLowerCase(),G=`.${Z.toLowerCase().replace(/^\.+|\.+$/g,"")}`;if(!Q.endsWith(G))return null;let J=Q.slice(0,Q.length-G.length);if(!J||J.includes("."))return null;return J}async function qR$($,Z){let X=UK1($.headers.get("host"),Z.baseDomain);if(!X)return null;let Q=await Z.getRunner();if(!Q)return Ge(503,"preview proxy not configured");let Y=await Q.proxyPreviewRequest(X,$);if(Y.headers.get(F_)&&TR$($))return IR$();return Y.headers.delete(F_),Y}function Ge($,Z){return new Response(JSON.stringify({error:Z}),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function iR0($){return typeof $==="object"&&$!==null&&$.kind==="preview"}async function MR$($,Z,X){if(($.headers.get("upgrade")??"").toLowerCase()!=="websocket")return null;let Q=UK1($.headers.get("host"),X.baseDomain);if(!Q)return null;let Y=await X.getRunner();if(!Y)return Ge(503,"preview proxy not configured");let G=await Y.resolvePreviewUpstreamUrl(Q);if(!G)return Ge(404,"sandbox not found");let J=new URL($.url);if(J.pathname.startsWith("/_sandbox")||J.pathname.startsWith("/_decopilot_vm"))return Ge(404,"not found");let K=`${G.replace(/^http/,"ws")}${J.pathname}${J.search}`,W=$.headers.get("sec-websocket-protocol"),H=W?W.split(",").map((F)=>F.trim()).filter(Boolean):[],N={kind:"preview",upstreamUrl:K,upstreamProtocols:H,pending:[],upstream:null,closed:!1};if(!Z.upgrade($,{data:N}))return Ge(426,"upgrade failed");return}function Ye($,Z,X,Q){if(Z.closed)return;Z.closed=!0;try{$.close(X,Q)}catch{}try{Z.upstream?.close()}catch{}}var PR$=256,AR$='<!DOCTYPE html><html><head><meta charset="utf-8"><title>Connecting\u2026</title><style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#fafafa;color:#555}div{text-align:center;max-width:420px;padding:24px}h3{margin:0 0 8px}p{margin:0;font-size:14px;color:#999;line-height:1.5}</style></head><body><div><h3>Connecting to sandbox\u2026</h3><p>Waiting for the sandbox to come online. This page refreshes automatically.</p></div><script>setTimeout(function(){window.location.reload()},1500)</script></body></html>',kR$;var M16=O(()=>{f$1();kR$={open($){let Z=$.data;if(!iR0(Z))return;let X;try{X=Z.upstreamProtocols.length>0?new WebSocket(Z.upstreamUrl,Z.upstreamProtocols):new WebSocket(Z.upstreamUrl)}catch(Q){console.warn(`[preview-ws] failed to dial upstream ${Z.upstreamUrl}: ${Q instanceof Error?Q.message:String(Q)}`),Ye($,Z,1011,"upstream connect failed");return}X.binaryType="arraybuffer",Z.upstream=X,X.addEventListener("open",()=>{while(Z.pending.length>0){let Q=Z.pending.shift();if(Q!==void 0)X.send(Q)}}),X.addEventListener("message",(Q)=>{if(Z.closed)return;$.send(Q.data)}),X.addEventListener("close",(Q)=>{Ye($,Z,Q.code||1000,Q.reason||"")}),X.addEventListener("error",()=>{Ye($,Z,1011,"upstream error")})},message($,Z){let X=$.data;if(!iR0(X))return;let Q=X.upstream;if(Q&&Q.readyState===WebSocket.OPEN){Q.send(Z);return}if(X.pending.length>=PR$){Ye($,X,1011,"preview ws backlog overflow");return}X.pending.push(Z)},close($){let Z=$.data;if(!iR0(Z))return;Ye($,Z,1000,"")}}});var pR$={};import{existsSync as bR$}from"fs";function _16($,Z){if(!Z)return $;let X=new URL($);if(!X.searchParams.has("sslmode"))X.searchParams.set("sslmode","verify-full");return X.toString()}function hR$($){let Z=new Headers($.headers);for(let[X,Q]of Object.entries(gR$))Z.set(X,Q);return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}async function nR$($){let Z;try{Z=await SR$.create({systemDatabaseUrl:_16(v3.databaseUrl,v3.databasePgSsl),systemDatabaseSchemaName:"dbos"});let X=await Z.listWorkflows({status:"PENDING",queueName:e3,executorId:$,loadInput:!1,loadOutput:!1});if(X.length===0){console.log(`[shutdown] no in-flight thread-gate gates to hand off (executor ${$})`);return}let Q=X.map((Y)=>Y.workflowID);await Z.resumeWorkflows(Q,{queueName:e3}),console.log(`[shutdown] re-enqueued ${Q.length} in-flight thread-gate gate(s) for re-adoption by a live executor (from ${$}):`,Q)}catch(X){console.error("[shutdown] thread-gate handoff failed:",X)}finally{await Z?.destroy().catch(()=>{})}}async function pR0($){if(C16)return;C16=!0,console.log(`
|
|
3929
3929
|
[shutdown] Received ${$}, shutting down gracefully...`);let Z=Number(process.env.SHUTDOWN_GRACE_SECONDS??60)*1000,X=Math.max(Z-5000,1e4),Q=setTimeout(()=>{console.error(`[shutdown] Timed out after ${X}ms, forcing exit.`),process.exit(1)},X);Q.unref?.();let Y=0;try{iR$(),nR0.markShuttingDown();let G=GN1(v3.dispatchRole,X,process.env.SHUTDOWN_DRAIN_MS);await m8(G),await mR$.stop(!0);let J=Je.executorID;await Je.shutdown(),await nR$(J),await nR0.shutdown()}catch(G){console.error("[shutdown] Error during shutdown:",G),Y=1}clearTimeout(Q),process.exit(Y)}var v3,Je,SR$,VR$,CR$,_R$,xR$,vR$,x16,fR$,k16,v16,yR$,gR$,uR$,cR$,lR$,FK1,wK1,dR$,f16,S16,nR0,BK1,V16,OK1=5,LK1=0,mR$,iR$,C16=!1;var b16=O(async()=>{W5();pd1();c8();ex();P5();$m1();v3=J1();Qu1();({DBOS:Je,DBOSClient:SR$}=await import("@dbos-inc/dbos-sdk"));VR$=[uG,e3,JN,iF],CR$=v3.dispatchRole==="worker"?VR$:v3.dispatchRole==="api"?[]:void 0;Je.setConfig(nd1({systemDatabaseUrl:_16(v3.databaseUrl,v3.databasePgSsl),poolSize:v3.dbosPoolSize,executorID:v3.podName,listenQueues:CR$}));({createApp:_R$}=await Promise.resolve().then(() => (j16(),z16))),{isServerPath:xR$}=await Promise.resolve().then(() => (M$0(),uh1)),{createAssetHandler:vR$,resolveClientDir:x16}=await Promise.resolve().then(() => (R16(),I16)),fR$=v3.port,k16=x16(import.meta.url,"../client"),v16=bR$(k16)?k16:x16(import.meta.url,"../dist/client"),yR$=vR$({clientDir:v16,isServerPath:xR$}),gR$={"X-Frame-Options":"DENY","Content-Security-Policy":"frame-ancestors 'none'"};({parsePreviewBaseDomain:uR$,tryHandlePreviewHttp:cR$,tryUpgradePreviewWs:lR$,previewWebSocketHandler:FK1,isPreviewWsData:wK1}=await Promise.resolve().then(() => (M16(),q16))),{getOrInitSharedRunner:dR$}=await Promise.resolve().then(() => (Xj0(),Jq8)),f16=uR$(process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN),S16={baseDomain:f16??"",getRunner:dR$},nR0=await _R$({clientDir:v16}),BK1=process.env.DBOS_CONDUCTOR_KEY?.trim(),V16=process.env.DBOS_CONDUCTOR_URL?.trim();await Je.launch({...BK1?{conductorKey:BK1}:{},...BK1&&V16?{conductorURL:V16}:{}});console.log(`[dbos] application version: ${Je.applicationVersion}`);await rZ(async()=>{LK1++;try{return await nR0.initDbos()}catch($){let Z=LK1>=OK1?"giving up":"retrying";throw console.warn(`[dbos] initDbos attempt ${LK1}/${OK1} failed, ${Z}`,$),$}},{maxAttempts:OK1,minTimeout:1000,maxTimeout:1e4,jitter:0.5});if(!v3.isCli){let{bannerLines:$}=await Promise.resolve().then(() => (bd(),m$0));console.log("");for(let Z of $())console.log(Z)}mR$=Bun.serve({idleTimeout:0,port:fR$,hostname:"0.0.0.0",fetch:async($,Z)=>{if(f16){let Q=await lR$($,Z,S16);if(Q===void 0)return;if(Q)return Q;let Y=await cR$($,S16);if(Y)return Y}let X=await yR$($);if(X)return hR$(X);return nR0.fetch($,{server:Z})},websocket:{open($){if(wK1($.data))FK1.open($)},message($,Z){if(wK1($.data))FK1.message($,Z)},close($){if(wK1($.data))FK1.close($)}},development:!1}),iR$=ed1();if(v3.localMode)Promise.resolve().then(() => (E_(),Ej0)).then(async({seedLocalMode:$,markSeedComplete:Z})=>{try{let X=await $()}catch(X){console.error("Failed to seed local mode:",X)}finally{Z()}}).catch(async($)=>{console.error("Failed to load local-mode module:",$);try{let{markSeedComplete:Z}=await Promise.resolve().then(() => (E_(),Ej0));Z()}catch{}});process.on("SIGTERM",()=>pR0("SIGTERM"));process.on("SIGINT",()=>pR0("SIGINT"));process.on("SIGHUP",()=>pR0("SIGHUP"));process.on("unhandledRejection",($)=>{console.error("[process] Unhandled rejection:",$)});process.on("uncaughtException",($)=>{console.error("[process] Uncaught exception:",$),pR0("uncaughtException")})});var DK1={};z0(DK1,{startServer:()=>oR$,interceptConsoleForTui:()=>tR$});function tR$(){let{log:$,warn:Z,error:X}=console;function Q(...Y){let G=Y.map((J)=>typeof J==="string"?J:Bun.inspect(J)).join(" ");for(let J of G.split(`
|
|
3930
3930
|
`)){let K=ad(J).trim();if(!K)continue;dF({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}return console.log=Q,console.warn=Q,console.error=Q,H50(!0),()=>{console.log=$,console.warn=Z,console.error=X,H50(!1)}}async function oR$($){let Z=await rd(Number($.port)),{settings:X,services:Q}=await W50({port:String(Z),home:$.home,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui});for(let Y of Q)OD({name:Y.name,status:"ready",port:Y.port});td(),await b16().then(() => pR$),od(`http://localhost:${X.port}`)}var EK1=O(()=>{kc0();LD();_c0()});import{parseArgs as rR$}from"util";import{homedir as zK1}from"os";import{join as g16}from"path";function aR0($){if($.noTui)return!1;return $.isTty===!0}function sR0($,Z){if(Z===void 0)return;let X=Number(Z);if(!Number.isSafeInteger(X)||X<=0)throw Error(`Invalid --${$} "${Z}" \u2014 must be a positive integer.`);return X}var{values:C9,positionals:Ke}=rR$({args:process.argv.slice(2),options:{port:{type:"string",short:"p",default:process.env.PORT||"3000"},"vite-port":{type:"string",default:process.env.VITE_PORT||"4000"},home:{type:"string"},"base-url":{type:"string"},help:{type:"boolean",short:"h",default:!1},version:{type:"boolean",short:"v",default:!1},"skip-migrations":{type:"boolean",default:!1},"no-tui":{type:"boolean",default:!1},"no-local-mode":{type:"boolean",default:!1},prune:{type:"boolean",default:!1},target:{type:"string"},env:{type:"string",short:"e"},"dry-run":{type:"boolean",default:!1},batch:{type:"string"},limit:{type:"string"},org:{type:"string"}},allowPositionals:!0});if(C9.help)console.log(`
|
|
3931
3931
|
Deco CMS \u2014 Open-source control plane for your AI agents
|