decocms 4.242.0 → 4.242.2
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-OA_Xgxae.js → AlertCircle-BLjRxtCg.js} +1 -1
- package/dist/client/assets/{AreaChart-B3t4IZGK.js → AreaChart-CA8B3Hpq.js} +1 -1
- package/dist/client/assets/{ArrowLeft-Bj878W3V.js → ArrowLeft-4DPAq3FZ.js} +1 -1
- package/dist/client/assets/{ArrowUp-B_Ogt5Bs.js → ArrowUp-BlEU92Im.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-DdbbfVn8.js → ArrowUpRight-C9RBdXzS.js} +1 -1
- package/dist/client/assets/{Check-CMT2e4zx.js → Check-DmmvaREF.js} +1 -1
- package/dist/client/assets/{CheckCircle-gZ5JjB4Q.js → CheckCircle-BkWleJAQ.js} +1 -1
- package/dist/client/assets/{ChevronDown-BAGloG2T.js → ChevronDown-DNdWMHBq.js} +1 -1
- package/dist/client/assets/{ChevronRight-BxiopOGy.js → ChevronRight-9kh8mw1-.js} +1 -1
- package/dist/client/assets/{ChevronUp-Be5aSS_l.js → ChevronUp-BiwzfQ34.js} +1 -1
- package/dist/client/assets/{Copy01-B5R4BK3-.js → Copy01-BSyOJtDU.js} +1 -1
- package/dist/client/assets/{CreditCard01-Csi9E-Aa.js → CreditCard01-DoI0r0lf.js} +1 -1
- package/dist/client/assets/{DotsVertical-o1P2HUBd.js → DotsVertical-B6vdrZcL.js} +1 -1
- package/dist/client/assets/{Download01-Bi4zydbv.js → Download01-BgrKWanC.js} +1 -1
- package/dist/client/assets/{Eye-Dw70tCIt.js → Eye-BYu9YoCE.js} +1 -1
- package/dist/client/assets/{FilterLines-BV5dy6zy.js → FilterLines-CCtu81Kl.js} +1 -1
- package/dist/client/assets/{Globe01-Be2lzaJE.js → Globe01-C1UG-2uT.js} +1 -1
- package/dist/client/assets/{Globe04-BYcZMCai.js → Globe04-Cxhs4JQB.js} +1 -1
- package/dist/client/assets/{HardDrive-DPjNzSR0.js → HardDrive-B12yjnMo.js} +1 -1
- package/dist/client/assets/{Key01-DPQmQfkN.js → Key01-BukaugKD.js} +1 -1
- package/dist/client/assets/{LayoutLeft-BFlLc3yK.js → LayoutLeft-DrPXFVcs.js} +1 -1
- package/dist/client/assets/{LinkExternal01-CvisxN0x.js → LinkExternal01-ndPw69oF.js} +1 -1
- package/dist/client/assets/{LockUnlocked01-BNhVELFx.js → LockUnlocked01-QOtE0O6M.js} +1 -1
- package/dist/client/assets/{LogOut01-z3eymNVW.js → LogOut01-Bbc7nVd2.js} +1 -1
- package/dist/client/assets/{Monitor01-knbEfQCK.js → Monitor01-CRJNkg5D.js} +1 -1
- package/dist/client/assets/{Palette-Cv2QhspQ.js → Palette-BN_nVtlo.js} +1 -1
- package/dist/client/assets/{Play-CKPRqLek.js → Play-bVmySP8F.js} +1 -1
- package/dist/client/assets/{Plus-ReH2aZwZ.js → Plus-D5q8r_KL.js} +1 -1
- package/dist/client/assets/{SearchLg-D4xC08o7.js → SearchLg-rLVtLHTP.js} +1 -1
- package/dist/client/assets/{SearchMd-DDePBtGa.js → SearchMd-Bp11Ucvw.js} +1 -1
- package/dist/client/assets/{Settings02-CnDSUjds.js → Settings02-B_z0TMYn.js} +1 -1
- package/dist/client/assets/{Share07-JY7Ppznk.js → Share07-W-6cq5W5.js} +1 -1
- package/dist/client/assets/{Shield01-Bq9Hu5m-.js → Shield01-KwFVdxDC.js} +1 -1
- package/dist/client/assets/{Stars01-B09_2VWZ.js → Stars01-D0mCYLdv.js} +1 -1
- package/dist/client/assets/{Stars02-DbHrUSo_.js → Stars02-kTE1_Iz0.js} +1 -1
- package/dist/client/assets/{Sun-DKrq03DV.js → Sun-BDMTS65q.js} +1 -1
- package/dist/client/assets/{SwitchHorizontal01-C-2yxUhm.js → SwitchHorizontal01-DfPnwT9V.js} +1 -1
- package/dist/client/assets/{Tool01-TP5Jac7n.js → Tool01-Ch6hlwSh.js} +1 -1
- package/dist/client/assets/{Tool02-Fviazu_x.js → Tool02-BxxsZkJA.js} +1 -1
- package/dist/client/assets/{Trash01-F1ZVNiG8.js → Trash01-BKz4fodI.js} +1 -1
- package/dist/client/assets/{TrendUp01-DdMpJ8BE.js → TrendUp01-BjzF1ujp.js} +1 -1
- package/dist/client/assets/{Upload01-CJonfWP0.js → Upload01-CXZS5Xwb.js} +1 -1
- package/dist/client/assets/{User01-DIXU-F24.js → User01-y6pFDwBd.js} +1 -1
- package/dist/client/assets/{Users01-H4NSKLik.js → Users01-jj6G1H_Q.js} +1 -1
- package/dist/client/assets/{Users03-BApXAl1K.js → Users03-B84s50Qe.js} +1 -1
- package/dist/client/assets/{X-DkqPNltJ.js → X-1tpdcA57.js} +1 -1
- package/dist/client/assets/{XCircle-LPLu2Ugo.js → XCircle-DMCkoBS4.js} +1 -1
- package/dist/client/assets/{XClose-DN1btb9v.js → XClose-B923cVgj.js} +1 -1
- package/dist/client/assets/{YAxis-D2jFs_Zl.js → YAxis-BbymNVh5.js} +1 -1
- package/dist/client/assets/{Zap-Bq44Kpjo.js → Zap-BQaeLyOX.js} +1 -1
- package/dist/client/assets/{ZapSquare-CCZ1UWTj.js → ZapSquare-B9aIlv3d.js} +1 -1
- package/dist/client/assets/{access-gate-BKLN_e4p.js → access-gate-8Cz30Bir.js} +1 -1
- package/dist/client/assets/{agent-icon-B0yFK7HS.js → agent-icon-CV9SA5HA.js} +1 -1
- package/dist/client/assets/{agents-list-BpeX8ogw.js → agents-list-pqZ-9MWi.js} +1 -1
- package/dist/client/assets/{ai-providers-zsieHuP5.js → ai-providers-DxyjtoAT.js} +1 -1
- package/dist/client/assets/{alert-dialog-BK4E81sc.js → alert-dialog-BpwE-DrS.js} +1 -1
- package/dist/client/assets/{alert-D-iEC1_A.js → alert-j4K7O3iH.js} +1 -1
- package/dist/client/assets/{api-keys-BUFuLWKJ.js → api-keys-Dxeqjeid.js} +1 -1
- package/dist/client/assets/{app-editor-G-Fetpn3.js → app-editor-D9jMqb2B.js} +1 -1
- package/dist/client/assets/{auth-DV6xLx0V.js → auth-DUWfQtFk.js} +1 -1
- package/dist/client/assets/{auth-catchall-ClqYt2w6.js → auth-catchall-DzFUjdds.js} +1 -1
- package/dist/client/assets/{auth-entry-Bb-3qijm.js → auth-entry-Ce6CuYbZ.js} +1 -1
- package/dist/client/assets/{auth-split-layout-Bz9fODq-.js → auth-split-layout-BYfGawU4.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-DIpLnC79.js → authenticate-and-persist-oauth-DxByWe6U.js} +1 -1
- package/dist/client/assets/{automation-list-row-CfYfdS3B.js → automation-list-row-BM7KHgfL.js} +1 -1
- package/dist/client/assets/{automation-runs-BjCS_bN-.js → automation-runs-DFhDj2sR.js} +1 -1
- package/dist/client/assets/{automations-Daf72kPX.js → automations-De_hPliJ.js} +1 -1
- package/dist/client/assets/{avatar-Dd0aFZLo.js → avatar-DLABdBS5.js} +1 -1
- package/dist/client/assets/{badge-BTKri9ol.js → badge-Dmi1Edkl.js} +1 -1
- package/dist/client/assets/{billing-B_nO_8Rp.js → billing-pQt5Wccx.js} +1 -1
- package/dist/client/assets/{block-document-cDFncdAC.js → block-document-D0USNHwK.js} +1 -1
- package/dist/client/assets/{buckets-DDlznnuu.js → buckets-CHfLvih1.js} +1 -1
- package/dist/client/assets/{bulk-category-panel--Ja9Hvn9.js → bulk-category-panel-BWXfpmvm.js} +1 -1
- package/dist/client/assets/{capability-load-error-Sj9vtxLg.js → capability-load-error-CWzCLzJM.js} +1 -1
- package/dist/client/assets/{card-CO3Gp4wa.js → card-pQ1UNz7f.js} +1 -1
- package/dist/client/assets/{cards-CiEt4liY.js → cards-Bj2o7opa.js} +1 -1
- package/dist/client/assets/{category-editor-CKCDemPK.js → category-editor-wCbxNnON.js} +1 -1
- package/dist/client/assets/{chart-DlgZxo61.js → chart-CDj0WlGN.js} +1 -1
- package/dist/client/assets/{chat-context-Dim5Kpjs.js → chat-context-DGqU4TNb.js} +1 -1
- package/dist/client/assets/{checkbox-Bq2RLHI-.js → checkbox-BZSdoD6r.js} +1 -1
- package/dist/client/assets/{choose-editor-C8iiJbTE.js → choose-editor-C9QohQqE.js} +1 -1
- package/dist/client/assets/{cli-auth-success-DccI5BUU.js → cli-auth-success-BvlVq2Y8.js} +1 -1
- package/dist/client/assets/{collection-detail-CTpOo-Cq.js → collection-detail-rgWATjwV.js} +1 -1
- package/dist/client/assets/{collection-display-button-CQoB3psU.js → collection-display-button-tVJ931UZ.js} +1 -1
- package/dist/client/assets/{collection-search-CLDo0_wU.js → collection-search-D-gCLHmQ.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-C4QiBaaK.js → collection-table-wrapper-BG9uTgkm.js} +1 -1
- package/dist/client/assets/{collection-tabs-QiJpg8-m.js → collection-tabs-RgVTGYAL.js} +1 -1
- package/dist/client/assets/{command-D0BCYMmo.js → command-1iBMuqnC.js} +1 -1
- package/dist/client/assets/{commerce-onboarding-C9mNjhfK.js → commerce-onboarding-2n8teMae.js} +1 -1
- package/dist/client/assets/{connect-BTJkoTvQ.js → connect-CtMyB9A1.js} +1 -1
- package/dist/client/assets/{connection-C0luFoIo.js → connection-DiQYN4WI.js} +1 -1
- package/dist/client/assets/{connection-card-DjZun6aQ.js → connection-card-B7oew6Sj.js} +1 -1
- package/dist/client/assets/{connection-detail-CCw9_8Ru.js → connection-detail-Z_OJ-BIW.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-zUyRyg80.js → connection-form-helpers-BL37f2pG.js} +1 -1
- package/dist/client/assets/{connections-BPnMajDw.js → connections-Bq7431v_.js} +1 -1
- package/dist/client/assets/{decopilot-sse-pool-CjR-weN-.js → decopilot-sse-pool-DxUDV3kB.js} +1 -1
- package/dist/client/assets/{dialog-BvT1iZkN.js → dialog-DYbfOzPC.js} +1 -1
- package/dist/client/assets/{domain-settings-D1dNJG0W.js → domain-settings-DB1_-ET2.js} +1 -1
- package/dist/client/assets/{drawer-CIQDOopl.js → drawer-DfpL6ei_.js} +1 -1
- package/dist/client/assets/{dropdown-menu-CA_WOS9d.js → dropdown-menu-DD28on4T.js} +1 -1
- package/dist/client/assets/{empty-state-D59PlXBG.js → empty-state-B0vBNoRU.js} +1 -1
- package/dist/client/assets/{extract-connection-data-DyUpsVRG.js → extract-connection-data-D0xv_Xpw.js} +1 -1
- package/dist/client/assets/{file-explorer-DIa030iv.js → file-explorer-BgAirbWR.js} +1 -1
- package/dist/client/assets/{file-type-icon-BDcBx01E.js → file-type-icon-Bv7bwy1X.js} +1 -1
- package/dist/client/assets/{form--h1PKrUM.js → form-B8WNeuMM.js} +1 -1
- package/dist/client/assets/{general-oJqr4rfs.js → general-BzdEqWOs.js} +1 -1
- package/dist/client/assets/{github-repo-picker-D4PcEAXK.js → github-repo-picker-6YNSKnAB.js} +1 -1
- package/dist/client/assets/{hooks-BV3A8lyq.js → hooks-BH5ncP0o.js} +1 -1
- package/dist/client/assets/{index-BxQabQAR.js → index-B01cmNcm.js} +1 -1
- package/dist/client/assets/{index-3Y41KS-z.js → index-BknjSN7Q.js} +1 -1
- package/dist/client/assets/{index-4I_19OQD.js → index-CWPWY8A2.js} +1 -1
- package/dist/client/assets/{index-CxdoykHj.js → index-CWr5yogT.js} +3 -3
- package/dist/client/assets/{index-BOAHTwyz.js → index-Cnu-uVYE.js} +35 -35
- package/dist/client/assets/{index-2V10wexl.js → index-CvagHRqr.js} +1 -1
- package/dist/client/assets/{index-CrkmMP84.js → index-D3MvvsdR.js} +1 -1
- package/dist/client/assets/{index-CMIkQ5Yf.js → index-D3vycpy0.js} +1 -1
- package/dist/client/assets/{index-BElhtFCe.js → index-DSYKgx16.js} +1 -1
- package/dist/client/assets/{index-Df1buANY.js → index-llVAr4bS.js} +1 -1
- package/dist/client/assets/{index-redirect-DIkRyUCf.js → index-redirect-BHE5x8Ah.js} +1 -1
- package/dist/client/assets/{infra-billing-DoNaREw7.js → infra-billing-BUuSz5bV.js} +1 -1
- package/dist/client/assets/{input-IWz3ijAk.js → input-BwBLAcU4.js} +1 -1
- package/dist/client/assets/{integration-icon-Fcw0xRvp.js → integration-icon-vMqCOva6.js} +1 -1
- package/dist/client/assets/{invite-member-dialog-B0WeE4-O.js → invite-member-dialog-DhlH9sKX.js} +1 -1
- package/dist/client/assets/{label-DPoipEh8.js → label-L3jOsH6N.js} +1 -1
- package/dist/client/assets/{layout-CSNTkg3u.js → layout-Cys6ogu0.js} +1 -1
- package/dist/client/assets/{login-D3hpE_vI.js → login-CFzoSPvf.js} +1 -1
- package/dist/client/assets/{mcp-oauth-Cn_KGHuG.js → mcp-oauth-D80_H96F.js} +1 -1
- package/dist/client/assets/{members-R890Fi-A.js → members-BKDp7yW6.js} +1 -1
- package/dist/client/assets/{monaco-editor-CXPGZqnf.js → monaco-editor-DAZ7H6GV.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-CSh6_bj5.js → monitoring-stats-row-3LrHb9nO.js} +1 -1
- package/dist/client/assets/{multi-select-BD9_lioJ.js → multi-select-C4vrBfBX.js} +1 -1
- package/dist/client/assets/{oauth-callback-x7Ux0dwp.js → oauth-callback-Cto4zhfM.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-Djtf7Xfo.js → oauth-callback-ai-provider-Br3BeFpb.js} +1 -1
- package/dist/client/assets/{onboarding-CwvrulPI.js → onboarding-oEhIHOlU.js} +1 -1
- package/dist/client/assets/{org-layout-Cwut9el0.js → org-layout-Dyx0ZMPc.js} +1 -1
- package/dist/client/assets/{organization-choice-L3y73JLF.js → organization-choice-CIo1vTrz.js} +1 -1
- package/dist/client/assets/{orgs-DufSuUB1.js → orgs-DNiAvqgw.js} +1 -1
- package/dist/client/assets/{page-seo-form-x9JB9IFC.js → page-seo-form-BkGoe1rY.js} +1 -1
- package/dist/client/assets/{popover-BxBMxXvF.js → popover-DwADEOUa.js} +1 -1
- package/dist/client/assets/{post-editor-D6H5Tfxw.js → post-editor-DLMpYcNq.js} +1 -1
- package/dist/client/assets/{primitives-Cngl53Ht.js → primitives-Br8uKVR3.js} +1 -1
- package/dist/client/assets/{profile-DyErg-wl.js → profile-vhnHD8qW.js} +1 -1
- package/dist/client/assets/{project-app-view-Dcb2DR9v.js → project-app-view-CYxQ2muC.js} +1 -1
- package/dist/client/assets/record-editor-Cp-acnY_.js +1 -0
- package/dist/client/assets/redirect-editor-D-6AASqj.js +1 -0
- package/dist/client/assets/registry-C7xHW0Tg.js +2 -0
- package/dist/client/assets/{registry-layout-B5v503kG.js → registry-layout-DUl6hNhd.js} +1 -1
- package/dist/client/assets/{reports-C_54T4ka.js → reports-COSkzA4A.js} +1 -1
- package/dist/client/assets/{require-capability-Bccnkgm3.js → require-capability-D5-lnGcd.js} +1 -1
- package/dist/client/assets/{required-auth-layout-DDjsC9m1.js → required-auth-layout-CTaIYIP8.js} +1 -1
- package/dist/client/assets/{reset-password-YCBw1i8I.js → reset-password-aiRP5Ays.js} +1 -1
- package/dist/client/assets/{roles-CzC20CxQ.js → roles-CemfFg5d.js} +1 -1
- package/dist/client/assets/{search-input-Dxt3pHZ9.js → search-input-WQSq4YL_.js} +1 -1
- package/dist/client/assets/{secrets-oYZxyZgj.js → secrets-CGJllEqD.js} +1 -1
- package/dist/client/assets/{sections-editor-CiEA967h.js → sections-editor-DylFjjZJ.js} +1 -1
- package/dist/client/assets/{select-BU9cYUOw.js → select-CBSZ0Lug.js} +1 -1
- package/dist/client/assets/{select-model-ttfe4Rt_.js → select-model-BsfCtu4R.js} +1 -1
- package/dist/client/assets/{self-tool-result-Cxm8Hjf2.js → self-tool-result-DNAq-vwW.js} +1 -1
- package/dist/client/assets/{seo-editor-cL6msN_C.js → seo-editor-CaCy-khG.js} +1 -1
- package/dist/client/assets/{settings-layout-BfD6Jy4Z.js → settings-layout-BUm34cp5.js} +1 -1
- package/dist/client/assets/{settings-section-C5YOMvmU.js → settings-section-dcT_loqd.js} +1 -1
- package/dist/client/assets/{settings-subnav-Da-whTO7.js → settings-subnav-DDOL5KMy.js} +1 -1
- package/dist/client/assets/{shell-controls-BKtAWxUx.js → shell-controls-BmjqugkY.js} +1 -1
- package/dist/client/assets/{shell-layout-BbE0C0cD.js → shell-layout-CWaRwowP.js} +1 -1
- package/dist/client/assets/{sidebar-B3pDm7Pe.js → sidebar-Vbdz435r.js} +1 -1
- package/dist/client/assets/{skeleton-Bbry0VZf.js → skeleton-Doum5PuE.js} +1 -1
- package/dist/client/assets/{spinner-CDJ3ZEfQ.js → spinner-mYPpwvbF.js} +1 -1
- package/dist/client/assets/{sso-CmtHXgC5.js → sso-CB4rcaK-.js} +1 -1
- package/dist/client/assets/{store-Dz9GVgy-.js → store-DUvebUaH.js} +1 -1
- package/dist/client/assets/store-registry-Di-zm9xf.js +2 -0
- package/dist/client/assets/{studio-tools-Og9VKB_F.js → studio-tools-D1WTrFr3.js} +1 -1
- package/dist/client/assets/{switch-CRt_YU5x.js → switch-WxAjh6LN.js} +1 -1
- package/dist/client/assets/{synced-repos-BQmjVUTH.js → synced-repos-aMHOq-mr.js} +1 -1
- package/dist/client/assets/{tab-id-DYz7tp_l.js → tab-id-BONWRXY7.js} +1 -1
- package/dist/client/assets/{table-BGzWGdLS.js → table-UKOQwvgs.js} +1 -1
- package/dist/client/assets/{tabs-BlNW0H5p.js → tabs-BAYBhY-B.js} +1 -1
- package/dist/client/assets/{tasks-daMWaZPA.js → tasks-nH_8KZqG.js} +1 -1
- package/dist/client/assets/{textarea-C9EZ0E9V.js → textarea-DVsSqFc7.js} +1 -1
- package/dist/client/assets/{toggle-group-CYSDPqxJ.js → toggle-group-D6mnwc67.js} +1 -1
- package/dist/client/assets/{toolbar-aAFbyu8K.js → toolbar-DZTLMAXr.js} +1 -1
- package/dist/client/assets/{tooltip-CaQ9sY8_.js → tooltip-sh5Vcy5o.js} +1 -1
- package/dist/client/assets/{track-D_PV18Wq.js → track-CKQNca1N.js} +1 -1
- package/dist/client/assets/{types-BQB-251e.js → types-C3iOdauk.js} +1 -1
- package/dist/client/assets/{use-ai-providers-CGXXNhqS.js → use-ai-providers-CkzENZaN.js} +1 -1
- package/dist/client/assets/{use-api-keys-CegWT4V8.js → use-api-keys-D4YfcKbJ.js} +1 -1
- package/dist/client/assets/{use-automations--HYw3r0-.js → use-automations-C4J3LwJ2.js} +1 -1
- package/dist/client/assets/{use-autosave-DV5VqxFG.js → use-autosave-Dkw6F1L0.js} +1 -1
- package/dist/client/assets/{use-capability-DjTUHWtW.js → use-capability-CL8dQHM2.js} +1 -1
- package/dist/client/assets/{use-clock-tick-XLNRdIBf.js → use-clock-tick-M8gtO9os.js} +1 -1
- package/dist/client/assets/{use-commerce-diagnostic-DezeehbT.js → use-commerce-diagnostic-DN1X4IW5.js} +1 -1
- package/dist/client/assets/{use-connection-DZz2ZZPf.js → use-connection-VGDVVQ1z.js} +1 -1
- package/dist/client/assets/{use-copy-jkQu5jEB.js → use-copy-mgcX5rsE.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-D53tZNei.js → use-create-virtual-mcp-Bb0Ipg7x.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-BE1Cew-t.js → use-debounced-autosave-CSRoYyDm.js} +1 -1
- package/dist/client/assets/{use-debounced-value-thuhwWic.js → use-debounced-value-E15h5LD3.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-DmLd5gM8.js → use-decopilot-events-9PMCbvpN.js} +1 -1
- package/dist/client/assets/{use-delete-connection-DtxY0vUf.js → use-delete-connection-CGA2fNyP.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-86QFYTkN.js → use-deployment-admin-DNmprhu5.js} +1 -1
- package/dist/client/assets/{use-file-configs-DrlpJBOr.js → use-file-configs-hzSNmpOq.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-6RVVg-bb.js → use-infinite-scroll-vVtYR3JQ.js} +1 -1
- package/dist/client/assets/{use-join-requests-CBhytJNM.js → use-join-requests-JyJucFLT.js} +1 -1
- package/dist/client/assets/{use-mcp-client-XKg7n-vV.js → use-mcp-client-Xm6nDmkT.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-DS316RVy.js → use-mcp-tools-HjqcWuQ-.js} +1 -1
- package/dist/client/assets/{use-members-Dj6l-4gj.js → use-members-z3sg-hyj.js} +1 -1
- package/dist/client/assets/{use-mobile-DDvT_7Nz.js → use-mobile-HeXjiu3p.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-D-Vda_zm.js → use-navigate-to-agent-DYKLjse3.js} +1 -1
- package/dist/client/assets/{use-open-billing-url-jOJ4F-Z9.js → use-open-billing-url-B-BgSqMX.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-B6i1wLZW.js → use-org-auth-client-CsEC-8-N.js} +1 -1
- package/dist/client/assets/{use-org-repo-syncs-DiyIDW94.js → use-org-repo-syncs-CWwFdJOO.js} +1 -1
- package/dist/client/assets/{use-org-sso-BASg43Ua.js → use-org-sso-AZ9iXYy7.js} +1 -1
- package/dist/client/assets/{use-organization-roles-6kWbAHps.js → use-organization-roles-oMLLQKe1.js} +1 -1
- package/dist/client/assets/{use-organization-settings-SO2wPhYg.js → use-organization-settings-pLz4lAB-.js} +1 -1
- package/dist/client/assets/{use-registry-connections-DpMbZhe9.js → use-registry-connections-DgQVTAzb.js} +1 -1
- package/dist/client/assets/{use-secrets-WxwBMboj.js → use-secrets-DZNeLfQZ.js} +1 -1
- package/dist/client/assets/{use-section-preview-base-COAeFupQ.js → use-section-preview-base-D3BRL2b2.js} +1 -1
- package/dist/client/assets/{use-settings-tabs-AkY3Wq-D.js → use-settings-tabs-CcNnEhAR.js} +1 -1
- package/dist/client/assets/{use-status-sounds-DojspfhT.js → use-status-sounds-B4kDHcys.js} +1 -1
- package/dist/client/assets/{use-tags-YHeG20vt.js → use-tags-CyfUnJtt.js} +1 -1
- package/dist/client/assets/{use-view-mode-CiQg5GKL.js → use-view-mode-DYjx6Ji4.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-DgT1kzXu.js → use-virtual-mcp-DlpcZhPC.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-P2P-hfvq.js +1 -0
- package/dist/client/assets/{useRouterState-CPD4cmC1.js → useRouterState-CmHV9E7D.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-Bm6Pr5PC.js +1 -0
- package/dist/client/assets/{users-BGHok0OQ.js → users-PcUYJwI1.js} +1 -1
- package/dist/client/assets/{variant-calendar-C27HmKaD.js → variant-calendar-BJx8Xiwa.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-DI56bUUR.js → view-mode-toggle-B4YcCrH-.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +3 -3
- package/dist/server/server.js +3 -3
- package/package.json +1 -1
- package/dist/client/assets/record-editor-QTV3g4_5.js +0 -1
- package/dist/client/assets/redirect-editor-Bnd6op8H.js +0 -1
- package/dist/client/assets/registry-zt706fGx.js +0 -2
- package/dist/client/assets/store-registry-BXWbmknF.js +0 -2
- package/dist/client/assets/useInfiniteQuery-35o_ktO7.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-D7Nok0q9.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -1371,7 +1371,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var Gi1=w(()=>{wf()});f
|
|
|
1371
1371
|
`.execute($);if(Number(W.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${J}/${K}, keeping in old table`);continue}}await db`
|
|
1372
1372
|
DELETE FROM kysely_migration WHERE name = ${X}
|
|
1373
1373
|
`.execute($)}}async function To1($){await Fp6($),await Bp6($);let Z=new Po1({db:$,provider:{getMigrations:()=>Promise.resolve(Ei0)}}),{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 Op6($){let{keepOpen:Z=!1,database:X,skipBetterAuth:Q=!1}=$??{},Y="skipped";if(!Q&&!X)Y=await cc0();let G=X??F6(),J=async()=>{if(!Z&&!X)await gB(G).catch((K)=>{console.warn("Warning: Error closing database:",K)})};try{let K=await To1(G.db);return await J(),{betterAuth:Y,kysely:K}}catch(K){throw await J(),K}}async function wp6(){let $=F6(),Z=new Po1({db:$.db,provider:{getMigrations:()=>Promise.resolve(Ei0)}}),{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 Io1=w(()=>{jo1();lc0();QX()});async function EZ0($){let Z={...process.env},X=H80($,Z);console.log(hw1(X.settings.encryptionKey));let Q=X.settings.betterAuthSecret||(X.settings.localMode?fn1(X.settings.dataDir):""),{ensureServices:Y}=await Promise.resolve().then(() => (q90(),I90)),{outputs:G,services:J}=await Y({home:X.settings.dataDir,externalDatabaseUrl:X.externalDatabaseUrl,externalNatsUrl:X.externalNatsUrl});if(!X.skipMigrations){let{migrateBetterAuth:W}=await Promise.resolve().then(() => (lc0(),yn1));await W(G.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (QX(),$n1)),{migrateToLatest:N}=await Promise.resolve().then(() => (Io1(),Ro1)),U=H(G.databaseUrl);await N({keepOpen:!0,database:U,skipBetterAuth:!0})}let K={...X.settings,betterAuthSecret:Q,databaseUrl:G.databaseUrl,natsUrls:G.natsUrls,...G.s3?{s3Endpoint:G.s3.endpoint,s3Bucket:G.s3.bucket,s3AccessKeyId:G.s3.accessKeyId,s3SecretAccessKey:G.s3.secretAccessKey,s3ForcePathStyle:G.s3.forcePathStyle}:{},...G.natsTunnel?{natsPublicUrl:G.natsTunnel.publicUrl,natsAccountJwt:G.natsTunnel.accountJwt,natsAccountSigningKey:G.natsTunnel.accountSigningKey,natsOperatorJwt:G.natsTunnel.operatorJwt,natsTunnelPublicEnabled:!0,natsCredsPath:G.natsTunnel.credsPath}:{}};return Ji1(K),{settings:K,services:J.map((W)=>({name:W.name==="PostgreSQL"?"Postgres":W.name,port:W.port})),managedServiceNames:J.filter((W)=>W.owner==="managed").map((W)=>W.name)}}var zi0=w(()=>{wf();bn1();C8()});var Vo1={};F0(Vo1,{updateService:()=>DE,subscribeCliState:()=>Ai0,setTuiConsoleIntercepted:()=>zZ0,setServerUrl:()=>Ci,setMigrationsDone:()=>Si,setDevMode:()=>Ep6,resetCliStateForTests:()=>Lp6,isTuiConsoleIntercepted:()=>jZ0,getCliState:()=>Pi0,addLogEntry:()=>dB});function qo1(){return{services:[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}],migrationsStatus:"pending",serverUrl:null,logs:[]}}function Lp6(){cQ=qo1()}function Dp6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function ki(){for(let $ of ji0)$()}function Pi0(){return cQ}function Ai0($){return ji0.add($),()=>ji0.delete($)}function DE($){cQ={...cQ,services:cQ.services.map((Z)=>Z.name===$.name?$:Z)},ki()}function Si(){cQ={...cQ,migrationsStatus:"done"},ki()}function Ci($){cQ={...cQ,serverUrl:$},ki()}function dB($){let Z=[...cQ.logs,$];cQ={...cQ,logs:Z.length>500?Z.slice(-500):Z},ki()}function Ep6(){cQ={...cQ,services:[...Dp6(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},ki()}function zZ0($){Mo1=$}function jZ0(){return Mo1}var cQ,ji0,Mo1=!1;var EE=w(()=>{cQ=qo1();ji0=new Set});import{createServer as ko1}from"net";function zp6($){return new Promise((Z)=>{let X=ko1();X.once("error",()=>Z(!1)),X.listen($,"0.0.0.0",()=>{X.close(()=>Z(!0))})})}async function _i($){if(await zp6($))return $;let Z=await new Promise((X,Q)=>{let Y=ko1();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 Ti0=()=>{};function vi($){return $.replace(/\x1b\[[0-9;]*m/g,"")}var Ri0={};F0(Ri0,{startDevServer:()=>Pp6});import{join as jp6}from"path";function So1($){let Z=$.getReader(),X=new TextDecoder,Q="";function Y(){let G=Q.split(`
|
|
1374
|
-
`);Q=G.pop()??"";for(let J of G){let K=vi(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;dB({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=vi(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)dB({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function Pp6($){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 _i(Number(Y)+1):await _i(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await EZ0({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)DE({name:L.name,status:"ready",port:L.port});Si();let N=jp6(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.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.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)So1(F.stdout),So1(F.stderr);Ci(G),DE({name:"Vite",status:"ready",port:Number(Y)}),DE({name:"API",status:"ready",port:Number(K.port)});let O=async(L)=>{if(F.kill(L),await F.exited,H.length>0){let{stopServices:D}=await Promise.resolve().then(() => (q90(),I90));await D(K.dataDir)}};return process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM")),{port:Number(Y),process:F}}var Ii0=w(()=>{zi0();EE();Ti0()});var PZ0;var qi0=w(()=>{PZ0={name:"decocms",version:"4.242.0",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^2.9.1","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^3.0.10","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@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 Tp6,Text as Co1}from"ink";import{jsx as Rp6,jsxs as _o1}from"react/jsx-runtime";function vo1({version:$}){return _o1(Tp6,{flexDirection:"column",marginTop:1,children:[o90.map((Z,X)=>Rp6(Co1,{color:r90[X],children:Z},X)),_o1(Co1,{dimColor:!0,children:[" v",$]})]})}var xo1=w(()=>{Ei()});import{Box as zE,Text as mB}from"ink";import{Spinner as Ip6}from"@inkjs/ui";import{jsx as sY,jsxs as mb}from"react/jsx-runtime";function fo1({status:$}){if($==="pending")return sY(Ip6,{label:""});return sY(mB,{color:"green",children:"\u2713"})}function qp6($){return`${$.name}: ${$.port||"...."}`}function bo1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return mb(zE,{flexDirection:"column",paddingBottom:1,children:[sY(vo1,{version:PZ0.version}),sY(zE,{marginBottom:1,children:sY(mB,{dimColor:!0,children:"\u2500".repeat(80)})}),sY(zE,{children:mb(mB,{dimColor:!0,children:["Home: ",X]})}),mb(zE,{gap:2,children:[$.map((Y)=>mb(zE,{gap:1,children:[sY(mB,{children:qp6(Y)}),sY(fo1,{status:Y.status})]},Y.name)),mb(zE,{gap:1,children:[sY(mB,{children:"Migrations"}),sY(fo1,{status:Z})]})]}),sY(zE,{children:Q?mb(mB,{children:["Open in browser: ",sY(mB,{color:"cyan",children:Q})]}):sY(mB,{dimColor:!0,children:"Starting..."})})]})}var yo1=w(()=>{qi0();xo1()});import{Box as Mp6,Text as xi}from"ink";import{jsx as Mi0,jsxs as Vi0}from"react/jsx-runtime";function Vp6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function go1({logs:$}){return Mi0(Mp6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return Mi0(xi,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return Vi0(xi,{children:[Vi0(xi,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),Mi0(xi,{color:Vp6(Z.status),children:Z.status}),Vi0(xi,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var ho1=()=>{};var ki0={};F0(ki0,{App:()=>Cp6});import{Box as kp6}from"ink";import{useSyncExternalStore as Sp6}from"react";import{jsx as uo1,jsxs as _p6}from"react/jsx-runtime";function Cp6({home:$}){let Z=Sp6(Ai0,Pi0);return _p6(kp6,{flexDirection:"column",children:[uo1(bo1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),uo1(go1,{logs:Z.logs})]})}var Si0=w(()=>{yo1();ho1();EE()});var vJ="thread-gate",aN="decopilot-hosted-harness",sN="decopilot-hosted-harness-sandboxed",F3="automations",iB="background-tools",jE="task-board-github-reads",PE="jira-push";var co1="7";function lo1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:co1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var do1=()=>{};function vp6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function Ci0($,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 mo1(){let $=vp6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:Ci0($,"--cpu-prof-dir")??process.cwd(),name:Ci0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(Ci0($,"--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 io1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=BE();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(()=>{}),AZ0=setInterval(()=>void Z().catch(()=>{}),$),AZ0.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(AZ0)clearInterval(AZ0)}}var AZ0;var no1=()=>{};import*as xp6 from"bun:jsc";function po1(){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{fp6()}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=bp6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let N of K){let U=N.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??N.frames[0];if(!U)continue;let F=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${U.name??"?"} @ ${F}:${U.line??"?"}`;W.set(B,(W.get(B)??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 fp6,bp6;var to1=w(()=>{({startSamplingProfiler:fp6,samplingProfilerStackTraces:bp6}=xp6)});function oo1(){mo1();let $=[io1(),ni1(),po1()];return()=>{for(let Z of $)Z()}}var ro1=w(()=>{Cc0();no1();to1()});var AE=_((ao1)=>{Object.defineProperty(ao1,"__esModule",{value:!0});ao1.RepublishHeaders=ao1.DirectMsgHeaders=ao1.JsHeaders=ao1.AdvisoryKind=void 0;ao1.isOrderedPushConsumerOptions=yp6;ao1.isPullConsumer=gp6;ao1.isPushConsumer=hp6;ao1.isBoundPushConsumerOptions=up6;function yp6($){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 gp6($){return $.isPullConsumer()}function hp6($){return $.isPushConsumer()}function up6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}ao1.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"};ao1.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"};ao1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};ao1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var eY=_((eo1)=>{Object.defineProperty(eo1,"__esModule",{value:!0});eo1.TD=eo1.TE=eo1.Empty=void 0;eo1.encode=op6;eo1.decode=rp6;eo1.Empty=new Uint8Array(0);eo1.TE=new TextEncoder;eo1.TD=new TextDecoder;function tp6(...$){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 op6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(eo1.TE.encode($[X]));if(Z.length===0)return eo1.Empty;if(Z.length===1)return Z[0];return tp6(...Z)}function rp6($){if(!$||$.length===0)return"";return eo1.TD.decode($)}});var $G=_((Xr1)=>{Object.defineProperty(Xr1,"__esModule",{value:!0});Xr1.errors=Xr1.PermissionViolationError=Xr1.NoRespondersError=Xr1.TimeoutError=Xr1.RequestError=Xr1.ProtocolError=Xr1.ConnectionError=Xr1.DrainingConnectionError=Xr1.ClosedConnectionError=Xr1.AuthorizationError=Xr1.UserAuthenticationExpiredError=Xr1.InvalidOperationError=Xr1.InvalidArgumentError=Xr1.InvalidSubjectError=void 0;class vi0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}Xr1.InvalidSubjectError=vi0;class TZ0 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 TZ0(`${$} ${Z}`,X)}}Xr1.InvalidArgumentError=TZ0;class xi0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}Xr1.InvalidOperationError=xi0;class RZ0 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new RZ0($);return null}}Xr1.UserAuthenticationExpiredError=RZ0;class IZ0 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 IZ0($);return null}}Xr1.AuthorizationError=IZ0;class fi0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Xr1.ClosedConnectionError=fi0;class bi0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Xr1.DrainingConnectionError=bi0;class yi0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}Xr1.ConnectionError=yi0;class gi0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}Xr1.ProtocolError=gi0;class hi0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof qZ0}}Xr1.RequestError=hi0;class ui0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}Xr1.TimeoutError=ui0;class qZ0 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}Xr1.NoRespondersError=qZ0;class MZ0 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 MZ0($,X,Q,Y)}}Xr1.PermissionViolationError=MZ0;Xr1.errors={AuthorizationError:IZ0,ClosedConnectionError:fi0,ConnectionError:yi0,DrainingConnectionError:bi0,InvalidArgumentError:TZ0,InvalidOperationError:xi0,InvalidSubjectError:vi0,NoRespondersError:qZ0,PermissionViolationError:MZ0,ProtocolError:gi0,RequestError:hi0,TimeoutError:ui0,UserAuthenticationExpiredError:RZ0}});var xJ=_((Kr1)=>{Object.defineProperty(Kr1,"__esModule",{value:!0});Kr1.SimpleMutex=Kr1.Perf=void 0;Kr1.extend=Bt6;Kr1.render=Ot6;Kr1.timeout=wt6;Kr1.delay=Lt6;Kr1.deadline=Dt6;Kr1.deferred=li0;Kr1.debugDeferred=Et6;Kr1.shuffle=zt6;Kr1.collect=jt6;Kr1.jitter=Jr1;Kr1.backoff=Pt6;Kr1.nanos=At6;Kr1.millis=Tt6;Kr1.randomToken=qt6;var Ft6=eY(),ci0=$G();function Bt6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Ot6($){return Ft6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function wt6($,Z=!0){let X=Z?new ci0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new ci0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function Lt6($=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 Dt6($,Z=1000){let X=li0(),Q=setTimeout(()=>{X.reject(new ci0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function li0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function Et6(){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 zt6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function jt6($){let Z=[];for await(let X of $)Z.push(X);return Z}class Yr1{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})}),$}}Kr1.Perf=Yr1;class Gr1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=li0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}Kr1.SimpleMutex=Gr1;function Jr1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function Pt6($=[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 Jr1(X>Z?$[Z]:$[X])}}}function At6($){return $*1e6}function Tt6($){return Math.floor($/1e6)}var Rt6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",eN=new Uint8Array(62);for(let $=0;$<62;$++)eN[$]=Rt6.charCodeAt($);var It6=218340105584896;function qt6(){let $=Math.floor(Math.random()*It6),Z=$%62,X=eN[Z];$=($-Z)/62,Z=$%62;let Q=eN[Z];$=($-Z)/62,Z=$%62;let Y=eN[Z];$=($-Z)/62,Z=$%62;let G=eN[Z];$=($-Z)/62,Z=$%62;let J=eN[Z];$=($-Z)/62,Z=$%62;let K=eN[Z];$=($-Z)/62,Z=$%62;let W=eN[Z];$=($-Z)/62;let H=eN[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var wr1=_((Br1)=>{Object.defineProperty(Br1,"__esModule",{value:!0});Br1.nuid=Br1.NuidImpl=void 0;var lt6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",nB=62,kZ0=12,Ur1=10,Hr1=33,dt6=333,Nr1=kZ0+Ur1,mi0=new Uint8Array(nB);for(let $=0;$<nB;$++)mi0[$]=lt6.charCodeAt($);var VZ0=4294967296,Fr1=BigInt(nB)**BigInt(Ur1),fi=Number(Fr1/(1n<<32n)),di0=Number(Fr1%(1n<<32n));function mt6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function it6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else mt6($)}class ii0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Nr1),this.cbuf=new Uint8Array(kZ0),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(fi+1)),this.seqLo=Math.floor(Math.random()*VZ0);while($++<8&&this.seqHi===fi&&this.seqLo>=di0);if(this.seqHi===fi&&this.seqLo>=di0)this.seqLo=0;this.inc=Math.random()*(dt6-Hr1)+Hr1|0}setPre(){it6(this.cbuf);for(let $=0;$<kZ0;$++)this.buf[$]=mi0[this.cbuf[$]%nB]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=Nr1-1;X>=kZ0;X--){let Q=Math.floor($/nB),G=($-Q*nB)*VZ0+Z,J=Math.floor(G/nB),K=G-J*nB;this.buf[X]=mi0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=VZ0)this.seqLo-=VZ0,this.seqHi+=1;if(this.seqHi>fi||this.seqHi===fi&&this.seqLo>=di0)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()}}Br1.NuidImpl=ii0;Br1.nuid=new ii0});var zr1=_((Dr1)=>{Object.defineProperty(Dr1,"__esModule",{value:!0});Dr1.nuid=Dr1.Nuid=void 0;var Lr1=wr1();Dr1.Nuid=Lr1.NuidImpl;Dr1.nuid=Lr1.nuid});var CZ0=_((SZ0)=>{Object.defineProperty(SZ0,"__esModule",{value:!0});SZ0.nuid=SZ0.Nuid=void 0;var jr1=zr1();Object.defineProperty(SZ0,"Nuid",{enumerable:!0,get:function(){return jr1.Nuid}});Object.defineProperty(SZ0,"nuid",{enumerable:!0,get:function(){return jr1.nuid}})});var pB=_((Pr1)=>{Object.defineProperty(Pr1,"__esModule",{value:!0});Pr1.DEFAULT_HOST=Pr1.DEFAULT_PORT=Pr1.Match=void 0;Pr1.syncIterator=at6;Pr1.createInbox=st6;var ot6=CZ0(),rt6=$G();Pr1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function at6($){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 st6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw rt6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${ot6.nuid.next()}`}Pr1.DEFAULT_PORT=4222;Pr1.DEFAULT_HOST="127.0.0.1"});var bi=_((Ir1)=>{Object.defineProperty(Ir1,"__esModule",{value:!0});Ir1.DataBuffer=void 0;var Tr1=eY();class Rr1{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 Tr1.TE.encode($)}static toAscii($){return Tr1.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}}Ir1.DataBuffer=Rr1});var TE=_((Vr1)=>{Object.defineProperty(Vr1,"__esModule",{value:!0});Vr1.LF=Vr1.CR=Vr1.CRLF=Vr1.CR_LF_LEN=Vr1.CR_LF=void 0;Vr1.setTransportFactory=Jo6;Vr1.defaultPort=Ko6;Vr1.getUrlParseFn=Wo6;Vr1.newTransport=Ho6;Vr1.getResolveFn=No6;Vr1.protoLen=Mr1;Vr1.extractProtocolMessage=Uo6;var Qo6=eY(),Yo6=pB(),Go6=bi(),ZG;function Jo6($){ZG=$}function Ko6(){return ZG!==void 0&&ZG.defaultPort!==void 0?ZG.defaultPort:Yo6.DEFAULT_PORT}function Wo6(){return ZG!==void 0&&ZG.urlParseFn?ZG.urlParseFn:void 0}function Ho6(){if(!ZG||typeof ZG.factory!=="function")throw Error("transport fn is not set");return ZG.factory()}function No6(){return ZG!==void 0&&ZG.dnsResolveFn?ZG.dnsResolveFn:void 0}Vr1.CR_LF=`\r
|
|
1374
|
+
`);Q=G.pop()??"";for(let J of G){let K=vi(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;dB({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=vi(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)dB({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function Pp6($){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 _i(Number(Y)+1):await _i(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await EZ0({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)DE({name:L.name,status:"ready",port:L.port});Si();let N=jp6(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.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.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)So1(F.stdout),So1(F.stderr);Ci(G),DE({name:"Vite",status:"ready",port:Number(Y)}),DE({name:"API",status:"ready",port:Number(K.port)});let O=async(L)=>{if(F.kill(L),await F.exited,H.length>0){let{stopServices:D}=await Promise.resolve().then(() => (q90(),I90));await D(K.dataDir)}};return process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM")),{port:Number(Y),process:F}}var Ii0=w(()=>{zi0();EE();Ti0()});var PZ0;var qi0=w(()=>{PZ0={name:"decocms",version:"4.242.2",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^2.9.1","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^3.0.10","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@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 Tp6,Text as Co1}from"ink";import{jsx as Rp6,jsxs as _o1}from"react/jsx-runtime";function vo1({version:$}){return _o1(Tp6,{flexDirection:"column",marginTop:1,children:[o90.map((Z,X)=>Rp6(Co1,{color:r90[X],children:Z},X)),_o1(Co1,{dimColor:!0,children:[" v",$]})]})}var xo1=w(()=>{Ei()});import{Box as zE,Text as mB}from"ink";import{Spinner as Ip6}from"@inkjs/ui";import{jsx as sY,jsxs as mb}from"react/jsx-runtime";function fo1({status:$}){if($==="pending")return sY(Ip6,{label:""});return sY(mB,{color:"green",children:"\u2713"})}function qp6($){return`${$.name}: ${$.port||"...."}`}function bo1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return mb(zE,{flexDirection:"column",paddingBottom:1,children:[sY(vo1,{version:PZ0.version}),sY(zE,{marginBottom:1,children:sY(mB,{dimColor:!0,children:"\u2500".repeat(80)})}),sY(zE,{children:mb(mB,{dimColor:!0,children:["Home: ",X]})}),mb(zE,{gap:2,children:[$.map((Y)=>mb(zE,{gap:1,children:[sY(mB,{children:qp6(Y)}),sY(fo1,{status:Y.status})]},Y.name)),mb(zE,{gap:1,children:[sY(mB,{children:"Migrations"}),sY(fo1,{status:Z})]})]}),sY(zE,{children:Q?mb(mB,{children:["Open in browser: ",sY(mB,{color:"cyan",children:Q})]}):sY(mB,{dimColor:!0,children:"Starting..."})})]})}var yo1=w(()=>{qi0();xo1()});import{Box as Mp6,Text as xi}from"ink";import{jsx as Mi0,jsxs as Vi0}from"react/jsx-runtime";function Vp6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function go1({logs:$}){return Mi0(Mp6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return Mi0(xi,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return Vi0(xi,{children:[Vi0(xi,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),Mi0(xi,{color:Vp6(Z.status),children:Z.status}),Vi0(xi,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var ho1=()=>{};var ki0={};F0(ki0,{App:()=>Cp6});import{Box as kp6}from"ink";import{useSyncExternalStore as Sp6}from"react";import{jsx as uo1,jsxs as _p6}from"react/jsx-runtime";function Cp6({home:$}){let Z=Sp6(Ai0,Pi0);return _p6(kp6,{flexDirection:"column",children:[uo1(bo1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),uo1(go1,{logs:Z.logs})]})}var Si0=w(()=>{yo1();ho1();EE()});var vJ="thread-gate",aN="decopilot-hosted-harness",sN="decopilot-hosted-harness-sandboxed",F3="automations",iB="background-tools",jE="task-board-github-reads",PE="jira-push";var co1="7";function lo1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:co1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var do1=()=>{};function vp6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function Ci0($,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 mo1(){let $=vp6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:Ci0($,"--cpu-prof-dir")??process.cwd(),name:Ci0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(Ci0($,"--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 io1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=BE();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(()=>{}),AZ0=setInterval(()=>void Z().catch(()=>{}),$),AZ0.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(AZ0)clearInterval(AZ0)}}var AZ0;var no1=()=>{};import*as xp6 from"bun:jsc";function po1(){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{fp6()}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=bp6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let N of K){let U=N.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??N.frames[0];if(!U)continue;let F=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${U.name??"?"} @ ${F}:${U.line??"?"}`;W.set(B,(W.get(B)??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 fp6,bp6;var to1=w(()=>{({startSamplingProfiler:fp6,samplingProfilerStackTraces:bp6}=xp6)});function oo1(){mo1();let $=[io1(),ni1(),po1()];return()=>{for(let Z of $)Z()}}var ro1=w(()=>{Cc0();no1();to1()});var AE=_((ao1)=>{Object.defineProperty(ao1,"__esModule",{value:!0});ao1.RepublishHeaders=ao1.DirectMsgHeaders=ao1.JsHeaders=ao1.AdvisoryKind=void 0;ao1.isOrderedPushConsumerOptions=yp6;ao1.isPullConsumer=gp6;ao1.isPushConsumer=hp6;ao1.isBoundPushConsumerOptions=up6;function yp6($){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 gp6($){return $.isPullConsumer()}function hp6($){return $.isPushConsumer()}function up6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}ao1.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"};ao1.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"};ao1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};ao1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var eY=_((eo1)=>{Object.defineProperty(eo1,"__esModule",{value:!0});eo1.TD=eo1.TE=eo1.Empty=void 0;eo1.encode=op6;eo1.decode=rp6;eo1.Empty=new Uint8Array(0);eo1.TE=new TextEncoder;eo1.TD=new TextDecoder;function tp6(...$){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 op6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(eo1.TE.encode($[X]));if(Z.length===0)return eo1.Empty;if(Z.length===1)return Z[0];return tp6(...Z)}function rp6($){if(!$||$.length===0)return"";return eo1.TD.decode($)}});var $G=_((Xr1)=>{Object.defineProperty(Xr1,"__esModule",{value:!0});Xr1.errors=Xr1.PermissionViolationError=Xr1.NoRespondersError=Xr1.TimeoutError=Xr1.RequestError=Xr1.ProtocolError=Xr1.ConnectionError=Xr1.DrainingConnectionError=Xr1.ClosedConnectionError=Xr1.AuthorizationError=Xr1.UserAuthenticationExpiredError=Xr1.InvalidOperationError=Xr1.InvalidArgumentError=Xr1.InvalidSubjectError=void 0;class vi0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}Xr1.InvalidSubjectError=vi0;class TZ0 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 TZ0(`${$} ${Z}`,X)}}Xr1.InvalidArgumentError=TZ0;class xi0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}Xr1.InvalidOperationError=xi0;class RZ0 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new RZ0($);return null}}Xr1.UserAuthenticationExpiredError=RZ0;class IZ0 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 IZ0($);return null}}Xr1.AuthorizationError=IZ0;class fi0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Xr1.ClosedConnectionError=fi0;class bi0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Xr1.DrainingConnectionError=bi0;class yi0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}Xr1.ConnectionError=yi0;class gi0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}Xr1.ProtocolError=gi0;class hi0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof qZ0}}Xr1.RequestError=hi0;class ui0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}Xr1.TimeoutError=ui0;class qZ0 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}Xr1.NoRespondersError=qZ0;class MZ0 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 MZ0($,X,Q,Y)}}Xr1.PermissionViolationError=MZ0;Xr1.errors={AuthorizationError:IZ0,ClosedConnectionError:fi0,ConnectionError:yi0,DrainingConnectionError:bi0,InvalidArgumentError:TZ0,InvalidOperationError:xi0,InvalidSubjectError:vi0,NoRespondersError:qZ0,PermissionViolationError:MZ0,ProtocolError:gi0,RequestError:hi0,TimeoutError:ui0,UserAuthenticationExpiredError:RZ0}});var xJ=_((Kr1)=>{Object.defineProperty(Kr1,"__esModule",{value:!0});Kr1.SimpleMutex=Kr1.Perf=void 0;Kr1.extend=Bt6;Kr1.render=Ot6;Kr1.timeout=wt6;Kr1.delay=Lt6;Kr1.deadline=Dt6;Kr1.deferred=li0;Kr1.debugDeferred=Et6;Kr1.shuffle=zt6;Kr1.collect=jt6;Kr1.jitter=Jr1;Kr1.backoff=Pt6;Kr1.nanos=At6;Kr1.millis=Tt6;Kr1.randomToken=qt6;var Ft6=eY(),ci0=$G();function Bt6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Ot6($){return Ft6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function wt6($,Z=!0){let X=Z?new ci0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new ci0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function Lt6($=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 Dt6($,Z=1000){let X=li0(),Q=setTimeout(()=>{X.reject(new ci0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function li0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function Et6(){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 zt6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function jt6($){let Z=[];for await(let X of $)Z.push(X);return Z}class Yr1{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})}),$}}Kr1.Perf=Yr1;class Gr1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=li0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}Kr1.SimpleMutex=Gr1;function Jr1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function Pt6($=[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 Jr1(X>Z?$[Z]:$[X])}}}function At6($){return $*1e6}function Tt6($){return Math.floor($/1e6)}var Rt6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",eN=new Uint8Array(62);for(let $=0;$<62;$++)eN[$]=Rt6.charCodeAt($);var It6=218340105584896;function qt6(){let $=Math.floor(Math.random()*It6),Z=$%62,X=eN[Z];$=($-Z)/62,Z=$%62;let Q=eN[Z];$=($-Z)/62,Z=$%62;let Y=eN[Z];$=($-Z)/62,Z=$%62;let G=eN[Z];$=($-Z)/62,Z=$%62;let J=eN[Z];$=($-Z)/62,Z=$%62;let K=eN[Z];$=($-Z)/62,Z=$%62;let W=eN[Z];$=($-Z)/62;let H=eN[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var wr1=_((Br1)=>{Object.defineProperty(Br1,"__esModule",{value:!0});Br1.nuid=Br1.NuidImpl=void 0;var lt6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",nB=62,kZ0=12,Ur1=10,Hr1=33,dt6=333,Nr1=kZ0+Ur1,mi0=new Uint8Array(nB);for(let $=0;$<nB;$++)mi0[$]=lt6.charCodeAt($);var VZ0=4294967296,Fr1=BigInt(nB)**BigInt(Ur1),fi=Number(Fr1/(1n<<32n)),di0=Number(Fr1%(1n<<32n));function mt6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function it6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else mt6($)}class ii0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Nr1),this.cbuf=new Uint8Array(kZ0),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(fi+1)),this.seqLo=Math.floor(Math.random()*VZ0);while($++<8&&this.seqHi===fi&&this.seqLo>=di0);if(this.seqHi===fi&&this.seqLo>=di0)this.seqLo=0;this.inc=Math.random()*(dt6-Hr1)+Hr1|0}setPre(){it6(this.cbuf);for(let $=0;$<kZ0;$++)this.buf[$]=mi0[this.cbuf[$]%nB]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=Nr1-1;X>=kZ0;X--){let Q=Math.floor($/nB),G=($-Q*nB)*VZ0+Z,J=Math.floor(G/nB),K=G-J*nB;this.buf[X]=mi0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=VZ0)this.seqLo-=VZ0,this.seqHi+=1;if(this.seqHi>fi||this.seqHi===fi&&this.seqLo>=di0)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()}}Br1.NuidImpl=ii0;Br1.nuid=new ii0});var zr1=_((Dr1)=>{Object.defineProperty(Dr1,"__esModule",{value:!0});Dr1.nuid=Dr1.Nuid=void 0;var Lr1=wr1();Dr1.Nuid=Lr1.NuidImpl;Dr1.nuid=Lr1.nuid});var CZ0=_((SZ0)=>{Object.defineProperty(SZ0,"__esModule",{value:!0});SZ0.nuid=SZ0.Nuid=void 0;var jr1=zr1();Object.defineProperty(SZ0,"Nuid",{enumerable:!0,get:function(){return jr1.Nuid}});Object.defineProperty(SZ0,"nuid",{enumerable:!0,get:function(){return jr1.nuid}})});var pB=_((Pr1)=>{Object.defineProperty(Pr1,"__esModule",{value:!0});Pr1.DEFAULT_HOST=Pr1.DEFAULT_PORT=Pr1.Match=void 0;Pr1.syncIterator=at6;Pr1.createInbox=st6;var ot6=CZ0(),rt6=$G();Pr1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function at6($){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 st6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw rt6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${ot6.nuid.next()}`}Pr1.DEFAULT_PORT=4222;Pr1.DEFAULT_HOST="127.0.0.1"});var bi=_((Ir1)=>{Object.defineProperty(Ir1,"__esModule",{value:!0});Ir1.DataBuffer=void 0;var Tr1=eY();class Rr1{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 Tr1.TE.encode($)}static toAscii($){return Tr1.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}}Ir1.DataBuffer=Rr1});var TE=_((Vr1)=>{Object.defineProperty(Vr1,"__esModule",{value:!0});Vr1.LF=Vr1.CR=Vr1.CRLF=Vr1.CR_LF_LEN=Vr1.CR_LF=void 0;Vr1.setTransportFactory=Jo6;Vr1.defaultPort=Ko6;Vr1.getUrlParseFn=Wo6;Vr1.newTransport=Ho6;Vr1.getResolveFn=No6;Vr1.protoLen=Mr1;Vr1.extractProtocolMessage=Uo6;var Qo6=eY(),Yo6=pB(),Go6=bi(),ZG;function Jo6($){ZG=$}function Ko6(){return ZG!==void 0&&ZG.defaultPort!==void 0?ZG.defaultPort:Yo6.DEFAULT_PORT}function Wo6(){return ZG!==void 0&&ZG.urlParseFn?ZG.urlParseFn:void 0}function Ho6(){if(!ZG||typeof ZG.factory!=="function")throw Error("transport fn is not set");return ZG.factory()}function No6(){return ZG!==void 0&&ZG.dnsResolveFn?ZG.dnsResolveFn:void 0}Vr1.CR_LF=`\r
|
|
1375
1375
|
`;Vr1.CR_LF_LEN=Vr1.CR_LF.length;Vr1.CRLF=Go6.DataBuffer.fromAscii(Vr1.CR_LF);Vr1.CR=new Uint8Array(Vr1.CRLF)[0];Vr1.LF=new Uint8Array(Vr1.CRLF)[1];function Mr1($){for(let Z=0;Z<$.length;Z++){let X=Z+1;if($.byteLength>X&&$[Z]===Vr1.CR&&$[X]===Vr1.LF)return X+1}return 0}function Uo6($){let Z=Mr1($);if(Z>0){let Q=new Uint8Array($).slice(0,Z);return Qo6.TD.decode(Q)}return""}});var ri0=_((br1)=>{Object.defineProperty(br1,"__esModule",{value:!0});br1.ipV4=vr1;br1.isIP=Ao6;br1.parseIP=xr1;var yi=4,RE=16,_Z0=48,_r1=57,Sr1=65,jo6=70,Cr1=97,Po6=102,oi0=16777215;function vr1($,Z,X,Q){let Y=new Uint8Array(RE);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 Ao6($){return xr1($)!==void 0}function xr1($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return fr1($);case":":return To6($)}return}function fr1($){let Z=new Uint8Array(yi);for(let X=0;X<yi;X++){if($.length===0)return;if(X>0){if($[0]!==".")return;$=$.substring(1)}let{n:Q,c:Y,ok:G}=Ro6($);if(!G||Q>255)return;$=$.substring(Y),Z[X]=Q}return vr1(Z[0],Z[1],Z[2],Z[3])}function To6($){let Z=new Uint8Array(RE),X=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(X=0,$=$.substring(2),$.length===0)return Z}let Q=0;while(Q<RE){let{n:Y,c:G,ok:J}=Io6($);if(!J||Y>65535)return;if(G<$.length&&$[G]==="."){if(X<0&&Q!=RE-yi)return;if(Q+yi>RE)return;let K=fr1($);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+=yi;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<RE){if(X<0)return;let Y=RE-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 Ro6($){let Z=0,X=0;for(Z=0;Z<$.length&&_Z0<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=_r1;Z++)if(X=X*10+($.charCodeAt(Z)-_Z0),X>=oi0)return{n:oi0,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:X,c:Z,ok:!0}}function Io6($){let Z=0,X=0;for(X=0;X<$.length;X++){if(_Z0<=$.charCodeAt(X)&&$.charCodeAt(X)<=_r1)Z*=16,Z+=$.charCodeAt(X)-_Z0;else if(Cr1<=$.charCodeAt(X)&&$.charCodeAt(X)<=Po6)Z*=16,Z+=$.charCodeAt(X)-Cr1+10;else if(Sr1<=$.charCodeAt(X)&&$.charCodeAt(X)<=jo6)Z*=16,Z+=$.charCodeAt(X)-Sr1+10;else break;if(Z>=oi0)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 Xn0=_((gr1)=>{Object.defineProperty(gr1,"__esModule",{value:!0});gr1.Servers=gr1.ServerImpl=void 0;gr1.isIPV4OrHostname=yr1;gr1.hostPort=Zn0;var ai0=TE(),si0=xJ(),ei0=ri0(),ko6=pB(),So6=$G();function yr1($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function $n0($){return!yr1($)}function Co6($){let X=$.toUpperCase().indexOf("::FFFF:");if(X!==-1&&$.indexOf(".")!==-1){let Q=$.substring(X+7);return Q=Q.replace("[",""),Q.replace("]","")}return $}function Zn0($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=Co6($),$n0($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=$n0($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),X=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):ko6.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 ib{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let X=Zn0($);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,ei0.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}://${$n0(Q)?"["+Q+"]":Q}`);G.port=`${this.port}`;let J=new ib(G.host,!1);J.tlsName=this.hostname,Z.push(J)}}if($.randomize)(0,si0.shuffle)(Z);return this.resolves=Z,Z}}gr1.ServerImpl=ib;class vZ0{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw So6.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,ai0.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}=Zn0(Y),J=X.get(G);if(J)J.gossiped=!1,Q.push(J);else Q.push(new ib(Y))}if(this.randomize)(0,si0.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,ei0.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,ai0.getUrlParseFn)();$=X?X($):$;let Q=new ib($,Z);if((0,ei0.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 vZ0.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return vZ0.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,ai0.getUrlParseFn)(),G=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((K)=>{K=Y?Y(K,Z):K;let W=new ib(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,si0.shuffle)(W),this.servers=K?[K,...W]:W}return{added:X,deleted:Q}}}gr1.Servers=vZ0});var xZ0=_((lr1)=>{Object.defineProperty(lr1,"__esModule",{value:!0});lr1.QueuedIteratorImpl=void 0;var Qn0=xJ(),ur1=$G();class cr1{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,Qn0.deferred)(),this.yields=[],this.iterClosed=(0,Qn0.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 ur1.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new ur1.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,Qn0.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}}lr1.QueuedIteratorImpl=cr1});var Yn0=_((nr1)=>{Object.defineProperty(nr1,"__esModule",{value:!0});nr1.MuxSubscription=void 0;var fo6=pB(),mr1=$G();class ir1{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,fo6.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 mr1.NoRespondersError(Q.requestSubject):null;Q.resolver($,Z)}}}}close(){let $=new mr1.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}nr1.MuxSubscription=ir1});var Gn0=_((or1)=>{Object.defineProperty(or1,"__esModule",{value:!0});or1.Heartbeat=void 0;var bo6=xJ();class tr1{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,bo6.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})}}or1.Heartbeat=tr1});var Wn0=_(($a1)=>{Object.defineProperty($a1,"__esModule",{value:!0});$a1.DenoBuffer=$a1.MAX_SIZE=$a1.AssertionError=void 0;$a1.assert=sr1;$a1.concat=er1;$a1.append=go6;$a1.readAll=ho6;$a1.writeAll=uo6;var yo6=eY();class Jn0 extends Error{constructor($){super($);this.name="AssertionError"}}$a1.AssertionError=Jn0;function sr1($,Z="Assertion failed."){if(!$)throw new Jn0(Z)}var ar1=32768;$a1.MAX_SIZE=4294967294;function fZ0($,Z,X=0){let Q=Z.byteLength-X;if($.byteLength>Q)$=$.subarray(0,Q);return Z.set($,X),$.byteLength}function er1($,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 go6($,Z){return er1($,Uint8Array.of(Z))}class Kn0{_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($){sr1($<=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=fZ0(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write(yo6.TE.encode($))}write($){let Z=this._grow($.byteLength);return fZ0($,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)fZ0(this._buf.subarray(this._off),this._buf);else if(Q+$>$a1.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*Q+$,$a1.MAX_SIZE));fZ0(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,$a1.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(ar1);while(!0){let Q=this.capacity-this.length<ar1,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}}}$a1.DenoBuffer=Kn0;function ho6($){let Z=new Kn0;return Z.readFrom($),Z.bytes()}function uo6($,Z){let X=0;while(X<Z.length)X+=$.write(Z.subarray(X))}});var Un0=_((Ga1)=>{Object.defineProperty(Ga1,"__esModule",{value:!0});Ga1.cc=Ga1.State=Ga1.Parser=Ga1.Kind=void 0;Ga1.describe=po6;var Hn0=Wn0(),Nn0=eY();Ga1.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function po6($){let Z,X="";switch($.kind){case Ga1.Kind.MSG:Z="MSG";break;case Ga1.Kind.OK:Z="OK";break;case Ga1.Kind.ERR:Z="ERR",X=Nn0.TD.decode($.data);break;case Ga1.Kind.PING:Z="PING";break;case Ga1.Kind.PONG:Z="PONG";break;case Ga1.Kind.INFO:Z="INFO",X=Nn0.TD.decode($.data)}return`${Z}: ${X}`}function Xa1(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var Qa1=48,to6=57,nb=67108864;class Ya1{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=Ga1.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 Ga1.State.OP_START:switch(X){case Ga1.cc.M:case Ga1.cc.m:this.state=Ga1.State.OP_M,this.hdr=-1,this.ma=Xa1();break;case Ga1.cc.H:case Ga1.cc.h:this.state=Ga1.State.OP_H,this.hdr=0,this.ma=Xa1();break;case Ga1.cc.P:case Ga1.cc.p:this.state=Ga1.State.OP_P;break;case Ga1.cc.PLUS:this.state=Ga1.State.OP_PLUS;break;case Ga1.cc.MINUS:this.state=Ga1.State.OP_MINUS;break;case Ga1.cc.I:case Ga1.cc.i:this.state=Ga1.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_H:switch(X){case Ga1.cc.M:case Ga1.cc.m:this.state=Ga1.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_M:switch(X){case Ga1.cc.S:case Ga1.cc.s:this.state=Ga1.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_MS:switch(X){case Ga1.cc.G:case Ga1.cc.g:this.state=Ga1.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_MSG:switch(X){case Ga1.cc.SPACE:case Ga1.cc.TAB:this.state=Ga1.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_MSG_SPC:switch(X){case Ga1.cc.SPACE:case Ga1.cc.TAB:continue;default:this.state=Ga1.State.MSG_ARG,this.as=Z}break;case Ga1.State.MSG_ARG:switch(X){case Ga1.cc.CR:this.drop=1;break;case Ga1.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=Ga1.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;case Ga1.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let Q=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:Ga1.Kind.MSG,msg:this.ma,data:Q}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Ga1.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:Ga1.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Ga1.State.MSG_END;break;case Ga1.State.MSG_END:switch(X){case Ga1.cc.NL:this.drop=0,this.as=Z+1,this.state=Ga1.State.OP_START;break;default:continue}break;case Ga1.State.OP_PLUS:switch(X){case Ga1.cc.O:case Ga1.cc.o:this.state=Ga1.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_PLUS_O:switch(X){case Ga1.cc.K:case Ga1.cc.k:this.state=Ga1.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_PLUS_OK:switch(X){case Ga1.cc.NL:this.dispatcher.push({kind:Ga1.Kind.OK}),this.drop=0,this.state=Ga1.State.OP_START;break}break;case Ga1.State.OP_MINUS:switch(X){case Ga1.cc.E:case Ga1.cc.e:this.state=Ga1.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_MINUS_E:switch(X){case Ga1.cc.R:case Ga1.cc.r:this.state=Ga1.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_MINUS_ER:switch(X){case Ga1.cc.R:case Ga1.cc.r:this.state=Ga1.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_MINUS_ERR:switch(X){case Ga1.cc.SPACE:case Ga1.cc.TAB:this.state=Ga1.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_MINUS_ERR_SPC:switch(X){case Ga1.cc.SPACE:case Ga1.cc.TAB:continue;default:this.state=Ga1.State.MINUS_ERR_ARG,this.as=Z}break;case Ga1.State.MINUS_ERR_ARG:switch(X){case Ga1.cc.CR:this.drop=1;break;case Ga1.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:Ga1.Kind.ERR,data:Q}),this.drop=0,this.as=Z+1,this.state=Ga1.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(X))}break;case Ga1.State.OP_P:switch(X){case Ga1.cc.I:case Ga1.cc.i:this.state=Ga1.State.OP_PI;break;case Ga1.cc.O:case Ga1.cc.o:this.state=Ga1.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_PO:switch(X){case Ga1.cc.N:case Ga1.cc.n:this.state=Ga1.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_PON:switch(X){case Ga1.cc.G:case Ga1.cc.g:this.state=Ga1.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_PONG:switch(X){case Ga1.cc.NL:this.dispatcher.push({kind:Ga1.Kind.PONG}),this.drop=0,this.state=Ga1.State.OP_START;break}break;case Ga1.State.OP_PI:switch(X){case Ga1.cc.N:case Ga1.cc.n:this.state=Ga1.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_PIN:switch(X){case Ga1.cc.G:case Ga1.cc.g:this.state=Ga1.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_PING:switch(X){case Ga1.cc.NL:this.dispatcher.push({kind:Ga1.Kind.PING}),this.drop=0,this.state=Ga1.State.OP_START;break}break;case Ga1.State.OP_I:switch(X){case Ga1.cc.N:case Ga1.cc.n:this.state=Ga1.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_IN:switch(X){case Ga1.cc.F:case Ga1.cc.f:this.state=Ga1.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_INF:switch(X){case Ga1.cc.O:case Ga1.cc.o:this.state=Ga1.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_INFO:switch(X){case Ga1.cc.SPACE:case Ga1.cc.TAB:this.state=Ga1.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case Ga1.State.OP_INFO_SPC:switch(X){case Ga1.cc.SPACE:case Ga1.cc.TAB:continue;default:this.state=Ga1.State.INFO_ARG,this.as=Z}break;case Ga1.State.INFO_ARG:switch(X){case Ga1.cc.CR:this.drop=1;break;case Ga1.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:Ga1.Kind.INFO,data:Q}),this.drop=0,this.as=Z+1,this.state=Ga1.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;default:throw this.fail($.subarray(Z))}}if((this.state===Ga1.State.MSG_ARG||this.state===Ga1.State.MINUS_ERR_ARG||this.state===Ga1.State.INFO_ARG)&&!this.argBuf)this.argBuf=new Hn0.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===Ga1.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new Hn0.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 Hn0.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 Ga1.cc.SPACE:case Ga1.cc.TAB:case Ga1.cc.CR:case Ga1.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],nb);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],nb);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}: ${Nn0.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],X=-1;for(let Q=0;Q<$.length;Q++)switch($[Q]){case Ga1.cc.SPACE:case Ga1.cc.TAB:case Ga1.cc.CR:case Ga1.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],nb),this.ma.size=this.protoParseInt(Z[3],nb);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],nb),this.ma.size=this.protoParseInt(Z[4],nb);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]<Qa1||$[Q]>to6)return-1;X=X*10+($[Q]-Qa1)}return Z!==void 0&&X>Z?-1:X}}Ga1.Parser=Ya1;Ga1.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};Ga1.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 gZ0=_((Ka1)=>{Object.defineProperty(Ka1,"__esModule",{value:!0});Ka1.MsgHdrsImpl=void 0;Ka1.canonicalMIMEHeaderKey=Bn0;Ka1.headers=ao6;var Ja1=eY(),fJ=pB(),yZ0=$G();function Bn0($){let N=!0,U=Array($.length);for(let F=0;F<$.length;F++){let B=$.charCodeAt(F);if(B===58||B<33||B>126)throw yZ0.InvalidArgumentError.format("header",`'${$[F]}' is not a valid character in a header name`);if(N&&97<=B&&B<=122)B-=32;else if(!N&&65<=B&&B<=90)B+=32;U[F]=B,N=B==45}return String.fromCharCode(...U)}function ao6($=0,Z=""){if($===0&&Z!=="")throw yZ0.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw yZ0.InvalidArgumentError.format("description","is required");return new pb($,Z)}var Fn0="NATS/1.0";class pb{_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 pb,Q=Ja1.TD.decode($).split(`\r
|
|
1376
1376
|
`),Y=Q[0];if(Y!==Fn0){let G=Y.replace(Fn0,"").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 $=Fn0;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
|
|
1377
1377
|
${Z}: ${X[Q]}`;return`${$}\r
|
|
@@ -1425,7 +1425,7 @@ You are running the brand-context onboarding for the user's organization. Your o
|
|
|
1425
1425
|
4. Do NOT call any other tools in this thread. Do NOT call \`brand_context_setup\` more than once.
|
|
1426
1426
|
|
|
1427
1427
|
If the tool returns an error, surface the error message to the user and ask whether they want to try a different URL.
|
|
1428
|
-
`.trim();B98=HG("site-diagnostics_"),wL5=B98.is,LL5=B98.get,O98=HG("commerce-discovery_"),DL5=O98.is,NQ0=O98.get;LU={AGENT_MANAGER:HG("studio-agent-manager_"),AUTOMATION_MANAGER:HG("studio-automation-manager_"),CONNECTION_MANAGER:HG("studio-connection-manager_"),API_KEY_MANAGER:HG("studio-api-key-manager_"),STORE_MANAGER:HG("studio-store-manager_"),BRAND_MANAGER:HG("studio-brand-manager_"),TASK_MANAGER:HG("studio-task-manager_"),USAGE_MANAGER:HG("studio-usage-manager_")},HX={AGENT_MANAGER:LU.AGENT_MANAGER.get,AUTOMATION_MANAGER:LU.AUTOMATION_MANAGER.get,CONNECTION_MANAGER:LU.CONNECTION_MANAGER.get,API_KEY_MANAGER:LU.API_KEY_MANAGER.get,STORE_MANAGER:LU.STORE_MANAGER.get,BRAND_MANAGER:LU.BRAND_MANAGER.get,TASK_MANAGER:LU.TASK_MANAGER.get,USAGE_MANAGER:LU.USAGE_MANAGER.get}});function j98($){return $.toLowerCase().replace(/[^a-z0-9]/g,"")}function IQ4($){return j98($).includes("deepresearch")}function P98($){let Z=j98($);if(Z.includes("deepresearch"))return!1;return qQ4.some((X)=>Z.includes(X))}function MQ4($){return $.asyncResearch!==!0&&P98($.modelId)}function VQ4($){return $.asyncResearch===!0||IQ4($.modelId)||P98($.modelId)}function my($,Z,X,Q){for(let Y of X){let G=$.find((J)=>J.modelId===Y);if(G)return{keyId:Z,modelId:G.modelId,title:G.title}}for(let Y of X){let G=$.find((J)=>J.modelId.includes(Y));if(G)return{keyId:Z,modelId:G.modelId,title:G.title}}if(Q){let Y=$.find(Q);if(Y)return{keyId:Z,modelId:Y.modelId,title:Y.title}}return null}function A98($,Z){let X={chat:{fast:null,smart:null,thinking:null},image:null,webSearch:null,deepResearch:null};for(let Q of $){let Y=Z[Q.id]??[],G=Q.providerId;if(!X.chat.fast)X.chat.fast=my(Y,Q.id,zQ4[G]??[]);if(!X.chat.smart)X.chat.smart=my(Y,Q.id,jQ4[G]??[]);if(!X.chat.thinking)X.chat.thinking=my(Y,Q.id,PQ4[G]??[]);if(!X.image)X.image=my(Y,Q.id,AQ4[G]??[],(J)=>J.capabilities?.includes("image")===!0);if(!X.webSearch)X.webSearch=my(Y,Q.id,TQ4[G]??[],MQ4);if(!X.deepResearch)X.deepResearch=my(Y,Q.id,RQ4[G]??[],VQ4)}return X}var zQ4,jQ4,PQ4,AQ4,TQ4,RQ4,qQ4;var T98=w(()=>{zQ4={anthropic:["claude-haiku-4-5","claude-haiku"],openrouter:["qwen/qwen3.5-flash","anthropic/claude-haiku-4.5","anthropic/claude-haiku","google/gemini-3-flash"],deco:["qwen/qwen3.5-flash","anthropic/claude-haiku"],llmapi:["claude-haiku-4-5","claude-haiku","gpt-4o-mini"],google:["gemini-2.5-flash","gemini-3-flash"]},jQ4={anthropic:["claude-sonnet-5","claude-sonnet"],openrouter:["anthropic/claude-sonnet-5","anthropic/claude-sonnet","anthropic/claude-opus-4.8","google/gemini-3-pro"],deco:["anthropic/claude-sonnet-5","anthropic/claude-sonnet","anthropic/claude"],llmapi:["claude-sonnet-4-6","claude-sonnet"],google:["gemini-3-pro","gemini-3-flash"]},PQ4={anthropic:["claude-opus-4-8","claude-sonnet-5","claude-sonnet","claude-fable-5"],openrouter:["anthropic/claude-opus-4.8:extended","anthropic/claude-opus-4.8","anthropic/claude-sonnet-5:extended","anthropic/claude-sonnet-5","google/gemini-3-pro","anthropic/claude-fable-5"],deco:["anthropic/claude-opus","anthropic/claude-sonnet-4.6","anthropic/claude-sonnet","anthropic/claude-fable"],llmapi:["claude-opus-4-8","claude-opus","claude-sonnet-4-6"],google:["gemini-3-pro"]},AQ4={openrouter:["openai/gpt-image-1","google/gemini-2.0-flash-image"],deco:["openai/gpt-image-1","google/gemini-2.0-flash-image"],llmapi:["gemini-2.5-flash-image","gpt-image-1"],google:["gemini-2.0-flash-image"]},TQ4={openrouter:["perplexity/sonar","perplexity/sonar-pro"],deco:["perplexity/sonar","perplexity/sonar-pro"]},RQ4={openrouter:["perplexity/deep-research","perplexity/sonar-pro"],deco:["perplexity/deep-research","perplexity/sonar-pro"]};qQ4=["sonar","searchpreview","online"]});function UQ0($){if(!$)return;let Z={};for(let X in $){let Q=$[X];if(typeof Q==="object"&&Q!==null){let Y={};for(let G of kQ4)if(G in Q)Y[G]=Q[G];Z[X]=Y}}return Object.keys(Z).length>0?Z:void 0}var kQ4;var R98=w(()=>{kQ4=["usage","cost","model"]});var A6=w(()=>{d70();z98();T98();R98()});function FQ0($){return $.toLowerCase().trim().replace(/\//g,"-").replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function PO($){if($.app_name)return $.app_name;if($.connection_url)try{let Z=new URL($.connection_url),Q=((Z.port?`${Z.hostname}-${Z.port}`:Z.hostname)+Z.pathname).replace(/\/+$/,"");return FQ0(Q)}catch{return FQ0($.connection_url)}if($.title)return FQ0($.title);return $.id??"unknown"}var BQ0=()=>{};var iy=300000,OQ0=5000,_r0=3,vr0=30000,I98=65000,wQ0=1000,ny=3,q98=5,M98=60000,V98=300000,xr0=60000;function k98(){if(DU.size<wQ0)return;let $=null,Z=1/0;for(let[X,Q]of DU)if(Q.lastFailureAt<Z)Z=Q.lastFailureAt,$=X;if($)DU.delete($)}function S98($){let Z=DU.get($);if(!Z)return k98(),DU.set($,{consecutiveFailures:1,disabled:!1,lastFailureAt:Date.now()}),{consecutiveFailures:1,thresholdCrossed:1>=ny};return Z.consecutiveFailures++,Z.lastFailureAt=Date.now(),{consecutiveFailures:Z.consecutiveFailures,thresholdCrossed:Z.consecutiveFailures>=ny}}function fr0($){let Z=DU.get($);if(Z){Z.disabled=!0;return}k98(),DU.set($,{consecutiveFailures:ny,disabled:!0,lastFailureAt:Date.now()})}function C98($){return DU.get($)?.disabled??!1}function _98($){DU.delete($)}var DU;var v98=w(()=>{DU=new Map});import{sql as a8}from"kysely";function f98($){if($.length===0)return null;let Z=$[0];if($.length===1&&CQ4.has(Z))return a8.ref(Z);if($.length===2&&x98.has(Z)){let X=$[1];return a8`${a8.ref(Z)}->>${a8.lit(X)}`}if($.length>2&&x98.has(Z)){let X=`{${$.slice(1).join(",")}}`;return a8`${a8.ref(Z)}#>>${a8.lit(X)}`}return null}function b98($){if("conditions"in $){let{operator:G,conditions:J}=$;if(J.length===0)return a8`true`;let K=J.map((W)=>b98(W));switch(G){case"and":return a8`(${a8.join(K,a8` AND `)})`;case"or":return a8`(${a8.join(K,a8` OR `)})`;case"not":return a8`NOT (${a8.join(K,a8` AND `)})`;default:return a8`true`}}let{field:Z,operator:X,value:Q}=$,Y=f98(Z);if(!Y)return a8`true`;switch(X){case"eq":return Q===null?a8`${Y} IS NULL`:a8`${Y} = ${a8.val(Q)}`;case"gt":return a8`${Y} > ${a8.val(Q)}`;case"gte":return a8`${Y} >= ${a8.val(Q)}`;case"lt":return a8`${Y} < ${a8.val(Q)}`;case"lte":return a8`${Y} <= ${a8.val(Q)}`;case"in":if(!Array.isArray(Q)||Q.length===0)return a8`false`;return a8`${Y} IN (${a8.join(Q.map((G)=>a8.val(G)))})`;case"like":return a8`${Y} ILIKE ${a8.val(Q)}`;case"contains":{let G=String(Q).replace(/[%_\\]/g,"\\$&");return a8`${Y} ILIKE ${a8.val(`%${G}%`)}`}default:return a8`true`}}class Kp{db;vault;constructor($,Z){this.db=$;this.vault=Z}async create($){let Z=$.id??Q4("conn"),X=new Date().toISOString(),Q=await this.findById(Z);if(Q){if(Q.organization_id!==$.organization_id)throw Error("Connection ID already exists");return this.update(Z,$)}let Y=PO($),G=await this.serializeConnection({...$,id:$.id??Z,slug:Y,status:"active",created_at:X,updated_at:X}),J=await this.db.insertInto("connections").values(G).returningAll().executeTakeFirst();if(!J)throw Error(`Failed to create connection with id: ${Z}`);return this.deserializeConnection(J)}async createNew($){let Z=$.id??Q4("conn"),X=new Date().toISOString(),Q=PO($),Y=await this.serializeConnection({...$,id:Z,slug:Q,status:"active",created_at:X,updated_at:X}),G;try{G=await this.db.insertInto("connections").values(Y).returningAll().executeTakeFirst()}catch(J){if(J instanceof Error&&(J.message.includes("duplicate key")||J.message.includes("unique constraint")))throw Error("Connection ID already exists");throw J}if(!G)throw Error(`Failed to create connection with id: ${Z}`);return this.deserializeConnection(G)}async findById($,Z){let X=z3($);if(X)return E98(Z??X);let Q=this.db.selectFrom("connections").selectAll().where("id","=",$);if(Z)Q=Q.where("organization_id","=",Z);let Y=await Q.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async list($,Z){let X=this.db.selectFrom("connections").selectAll().where("organization_id","=",$);if(!Z?.includeVirtual)X=X.where("connection_type","!=","VIRTUAL");if(Z?.slug)X=X.where("slug","=",Z.slug);if(Z?.where)X=X.where(b98(Z.where));let G=(await this.db.selectFrom(X.as("filtered")).select(a8`count(*)::int`.as("count")).executeTakeFirst())?.count??0;if(Z?.orderBy&&Z.orderBy.length>0)for(let W of Z.orderBy){let H=f98(W.field);if(!H)continue;let N=W.direction==="desc"?a8`desc`:a8`asc`,U=W.nulls==="first"?a8`nulls first`:a8`nulls last`;X=X.orderBy(a8`${H} ${N} ${U}`)}if(Z?.limit)X=X.limit(Z.limit);if(Z?.offset)X=X.offset(Z.offset);let J=await X.execute();return{items:await Promise.all(J.map((W)=>this.deserializeConnection(W))),totalCount:G}}async update($,Z){if(Object.keys(Z).length===0){let J=await this.findById($);if(!J)throw Error("Connection not found");return J}let X={...Z},Q=await this.db.selectFrom("connections").select(["app_name","connection_url","title"]).where("id","=",$).executeTakeFirst();if(Q){let J=(K)=>Z[K]===void 0?Q[K]:Z[K];X.slug=PO({app_name:J("app_name"),connection_url:J("connection_url"),title:J("title"),id:$})}let Y=await this.serializeConnection({...X,updated_at:new Date().toISOString()}),G=await this.db.updateTable("connections").set(Y).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Connection not found after update");return this.deserializeConnection(G)}async isReferencedByThread($){return await this.db.selectFrom("threads").select("id").where(a8`metadata -> 'githubRepo' ->> 'connectionId' = ${$}`).limit(1).executeTakeFirst()!==void 0}async delete($){await this.db.deleteFrom("connections").where("id","=",$).execute()}async testConnection($,Z){let X=await this.findById($);if(!X)throw Error("Connection not found");let Q=Date.now();if(X.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-Q};if(!X.connection_url)return{healthy:!1,latencyMs:Date.now()-Q};try{if(await ly(X.connection_url))return{healthy:!1,latencyMs:Date.now()-Q};let G=X.connection_headers,J=new AbortController,K=setTimeout(()=>J.abort(),1e4),W;try{W=await dy()(X.connection_url,{method:"POST",signal:J.signal,headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...G?.headers,...Z},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})})}finally{clearTimeout(K)}return{healthy:W.ok||W.status===404,latencyMs:Date.now()-Q}}catch{return{healthy:!1,latencyMs:Date.now()-Q}}}async serializeConnection($){let Z={};for(let[X,Q]of Object.entries($)){if(Q===void 0)continue;if(X==="tools")continue;if(X==="connection_token"&&Q)Z[X]=await this.vault.encrypt(Q);else if(X==="configuration_state"&&Q){let Y=JSON.stringify(Q);Z[X]=await this.vault.encrypt(Y)}else if(X==="connection_headers"&&Q){let Y=Q;if(fW(Y)&&Y.envVars){let G={};for(let[J,K]of Object.entries(Y.envVars))G[J]=await this.vault.encrypt(K);Z[X]=JSON.stringify({...Y,envVars:G})}else Z[X]=JSON.stringify(Y)}else if(SQ4.includes(X))Z[X]=Q?JSON.stringify(Q):null;else Z[X]=Q}return Z}async handleDecryptFailures($,Z){let X=`connection ${$.id} (org: ${$.organization_id}, type: ${$.connection_type}, title: ${$.title})`;if(C98($.id))return;if($.status!=="active"){fr0($.id);return}let{thresholdCrossed:Q}=S98($.id);if(!Q){for(let{label:Y,error:G}of Z)console.error(`Failed to decrypt ${Y} for ${X}:`,G);return}try{await this.db.updateTable("connections").set({status:"error"}).where("id","=",$.id).execute(),fr0($.id),console.error(`Disabled ${X} after ${ny} consecutive decryption failures.`,Z[0]?.error)}catch(Y){console.error(`Failed to disable ${X} after decryption failures:`,Y)}}async deserializeConnection($){let Z=[],X=null;if($.connection_token)try{X=await this.vault.decrypt($.connection_token)}catch(J){Z.push({label:"connection token",error:J})}let Q=null;if($.configuration_state)try{let J=await this.vault.decrypt($.configuration_state);Q=JSON.parse(J)}catch(J){Z.push({label:"configuration state",error:J})}if(Z.length>0)await this.handleDecryptFailures($,Z);else if($.connection_token||$.configuration_state)_98($.id);let Y=null;if($.connection_headers)try{let J=JSON.parse($.connection_headers);if(fW(J)&&J.envVars){let K={};for(let[W,H]of Object.entries(J.envVars))try{K[W]=await this.vault.decrypt(H)}catch{K[W]=H}Y={...J,envVars:K}}else Y=J}catch(J){console.error(`Failed to parse connection_headers for connection ${$.id} (org: ${$.organization_id}, type: ${$.connection_type}, title: ${$.title}):`,J)}let G=(J)=>{if(J===null)return null;if(typeof J==="string")try{return JSON.parse(J)}catch{return null}return J};return{id:$.id,organization_id:$.organization_id,created_by:$.created_by,updated_by:$.updated_by??void 0,title:$.title,description:$.description,icon:$.icon,app_name:$.app_name,app_id:$.app_id,slug:$.slug,connection_type:$.connection_type,connection_url:$.connection_url,connection_token:X,connection_headers:Y,oauth_config:G($.oauth_config),configuration_state:Q,configuration_scopes:G($.configuration_scopes),metadata:G($.metadata),tools:null,bindings:G($.bindings),status:$.status,created_at:$.created_at,updated_at:$.updated_at}}}var SQ4,CQ4,x98;var br0=w(()=>{yW();Jp();GQ();A6();BQ0();v98();SQ4=["connection_headers","oauth_config","configuration_scopes","metadata","bindings"],CQ4=new Set(["id","organization_id","created_by","updated_by","title","description","icon","app_name","app_id","slug","connection_type","connection_url","status","created_at","updated_at"]),x98=new Set(["metadata","configuration_scopes","bindings"])});import{createHash as _Q4,randomBytes as vQ4,timingSafeEqual as lL5}from"crypto";function fQ4($){return $.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function gr0($){return _Q4("sha256").update($).digest("hex")}function h98($){let Z=yr0.length+1,X=Z+g98;if(!$.startsWith(`${yr0}_`)||$.length<=X+1||$[X]!=="_")return null;let Q=$.slice(Z,X),Y=$.slice(X+1);if(!y98.test(Q)||!y98.test(Y))return null;return Q}function u98(){let $=fQ4(vQ4(xQ4)),Z=$.slice(0,g98),X=`${yr0}_${Z}_${$}`;return{plaintext:X,prefix:Z,hash:gr0(X)}}var yr0="stv",xQ4=32,g98=12,y98;var c98=w(()=>{y98=/^[A-Za-z0-9_-]+$/});function l98($){return{id:$.id,organizationId:$.organization_id,subjectConnectionId:$.subject_connection_id,tokenHash:$.token_hash,tokenPrefix:$.token_prefix,name:$.name,revokedAt:$.revoked_at,lastUsedAt:$.last_used_at,createdAt:$.created_at,updatedAt:$.updated_at}}class hr0{db;constructor($){this.db=$}async createOrRotateWorkloadToken($){let Z=$.name??"default";return await this.db.transaction().execute(async(Q)=>{if(!await Q.selectFrom("connections").select("id").where("id","=",$.subjectConnectionId).where("organization_id","=",$.organizationId).executeTakeFirst())throw Error("Subject connection not found in organization");let G=u98(),J=new Date().toISOString();await Q.updateTable("connection_workload_tokens").set({revoked_at:J,updated_at:J}).where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("name","=",Z).where("revoked_at","is",null).execute();let K=await Q.insertInto("connection_workload_tokens").values({id:Q4("cwt"),organization_id:$.organizationId,subject_connection_id:$.subjectConnectionId,token_hash:G.hash,token_prefix:G.prefix,name:Z,revoked_at:null,last_used_at:null,created_at:J,updated_at:J}).returningAll().executeTakeFirstOrThrow();return{plaintextToken:G.plaintext,record:l98(K)}})}async findActiveWorkloadToken($){let Z=await this.db.selectFrom("connection_workload_tokens").selectAll().where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("name","=",$.name??"default").where("revoked_at","is",null).executeTakeFirst();return Z?l98(Z):null}async revokeWorkloadToken($){let Z=new Date().toISOString();await this.db.updateTable("connection_workload_tokens").set({revoked_at:Z,updated_at:Z}).where("id","=",$.tokenId).where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("revoked_at","is",null).execute()}async authenticateWorkloadToken($){let Z=h98($);if(!Z)return null;let X=gr0($),Q=await this.db.selectFrom("connection_workload_tokens").select(["id","organization_id","subject_connection_id","token_prefix"]).where("token_prefix","=",Z).where("token_hash","=",X).where("revoked_at","is",null).executeTakeFirst();if(!Q)return null;let Y=new Date().toISOString();return await this.db.updateTable("connection_workload_tokens").set({last_used_at:Y,updated_at:Y}).where("id","=",Q.id).execute(),{tokenId:Q.id,tokenPrefix:Q.token_prefix,organizationId:Q.organization_id,subjectConnectionId:Q.subject_connection_id}}async replaceGrantsForSubject($){await this.db.transaction().execute(async(Z)=>{if(!await Z.selectFrom("connections").select("id").where("id","=",$.subjectConnectionId).where("organization_id","=",$.organizationId).executeTakeFirst())throw Error("Referenced connection not found in organization");let Q=[...new Set($.grants.map((J)=>J.targetConnectionId))];if(Q.length>0){if((await Z.selectFrom("connections").select("id").where("organization_id","=",$.organizationId).where("id","in",Q).execute()).length!==Q.length)throw Error("Referenced connection not found in organization")}if(await Z.deleteFrom("connection_credential_grants").where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).execute(),$.grants.length===0)return;let Y=new Date().toISOString(),G=$.grants.map((J)=>({id:Q4("ccg"),organization_id:$.organizationId,subject_connection_id:$.subjectConnectionId,target_connection_id:J.targetConnectionId,scope:J.scope,created_by:$.createdBy,created_at:Y,updated_at:Y}));await Z.insertInto("connection_credential_grants").values(G).execute()})}async hasGrant($){return!!await this.db.selectFrom("connection_credential_grants").select("id").where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("target_connection_id","=",$.targetConnectionId).where("scope","=",$.scope).executeTakeFirst()}}var LQ0="credential:access-token:read",DQ0="credential:configuration:read";var EQ0=w(()=>{GQ();c98()});class py{db;constructor($){this.db=$}async create($,Z,X,Q){let Y=Q?.id??Q4("vir"),G=new Date().toISOString();await this.db.transaction().execute(async(K)=>{if(await K.insertInto("connections").values({id:Y,organization_id:$,created_by:Z,title:X.title,description:X.description??null,icon:X.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",pinned:X.pinned??!1,connection_url:`virtual://${Y}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata?JSON.stringify(X.metadata):null,bindings:null,status:X.status??"active",created_at:G,updated_at:G}).execute(),X.connections.length>0)await K.insertInto("connection_aggregations").values(X.connections.map((W)=>({id:Q4("agg"),parent_connection_id:Y,child_connection_id:W.connection_id,selected_tools:W.selected_tools?JSON.stringify(W.selected_tools):null,selected_resources:W.selected_resources?JSON.stringify(W.selected_resources):null,selected_prompts:W.selected_prompts?JSON.stringify(W.selected_prompts):null,dependency_mode:"direct",created_at:G}))).execute()});let J=await this.findById(Y);if(!J)throw Error(`Failed to create virtual MCP with id: ${Y}`);return J}async findById($,Z){let X=z3($);if(X)return{...Cr0(Z??X),pinned:!1,connections:[]};let Q=HQ0($);if(Q)return{...F98(Z??Q),pinned:!1,connections:[]};return this.findByIdInternal(this.db,$)}async findByIdInternal($,Z){let X=await $.selectFrom("connections").selectAll().where("id","=",Z).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!X)return null;let Q=await $.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",Z).where("dependency_mode","=","direct").execute();return this.deserializeVirtualMCPEntity(X,Q)}async list($,Z){let X=this.db.selectFrom("connections").selectAll().where("organization_id","=",$).where("connection_type","=","VIRTUAL");if(Z?.pinnedOnly)X=X.where("pinned","=",!0);let Q=await X.execute(),Y=Q.map((K)=>K.id);if(Y.length===0)return[];let G=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Y).where("dependency_mode","=","direct").execute(),J=new Map;for(let K of G){let W=J.get(K.parent_connection_id)??[];W.push(K),J.set(K.parent_connection_id,W)}return Q.map((K)=>this.deserializeVirtualMCPEntity(K,J.get(K.id)??[]))}async listByIds($,Z){if(Z.length===0)return[];let X=await this.db.selectFrom("connections").selectAll().where("id","in",Z).where("organization_id","=",$).where("connection_type","=","VIRTUAL").execute();if(X.length===0)return[];let Q=X.map((J)=>J.id),Y=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Q).where("dependency_mode","=","direct").execute(),G=new Map;for(let J of Y){let K=G.get(J.parent_connection_id)??[];K.push(J),G.set(J.parent_connection_id,K)}return X.map((J)=>this.deserializeVirtualMCPEntity(J,G.get(J.id)??[]))}async listByConnectionId($,Z){let Q=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",Z).execute()).map((W)=>W.parent_connection_id);if(Q.length===0)return[];let Y=await this.db.selectFrom("connections").selectAll().where("id","in",Q).where("organization_id","=",$).where("connection_type","=","VIRTUAL").execute();if(Y.length===0)return[];let G=Y.map((W)=>W.id),J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",G).where("dependency_mode","=","direct").execute(),K=new Map;for(let W of J){let H=K.get(W.parent_connection_id)??[];H.push(W),K.set(W.parent_connection_id,H)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,K.get(W.id)??[]))}async update($,Z,X){let Q=new Date().toISOString(),Y={updated_at:Q,updated_by:Z};if(X.title!==void 0)Y.title=X.title;if(X.description!==void 0)Y.description=X.description;if(X.icon!==void 0)Y.icon=X.icon;if(X.status!==void 0)Y.status=X.status;if(X.pinned!==void 0)Y.pinned=X.pinned;if(X.metadata!==void 0)Y.metadata=X.metadata?JSON.stringify(X.metadata):null;let G=[];await this.db.transaction().execute(async(K)=>{if(await K.updateTable("connections").set(Y).where("id","=",$).where("connection_type","=","VIRTUAL").execute(),X.connections!==void 0){let W=await K.selectFrom("connection_aggregations").select("child_connection_id").where("parent_connection_id","=",$).where("dependency_mode","=","direct").execute(),H=new Set(W.map((U)=>U.child_connection_id));if(await K.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).where("dependency_mode","=","direct").execute(),X.connections.length>0)await K.insertInto("connection_aggregations").values(X.connections.map((U)=>({id:Q4("agg"),parent_connection_id:$,child_connection_id:U.connection_id,selected_tools:U.selected_tools?JSON.stringify(U.selected_tools):null,selected_resources:U.selected_resources?JSON.stringify(U.selected_resources):null,selected_prompts:U.selected_prompts?JSON.stringify(U.selected_prompts):null,dependency_mode:"direct",created_at:Q}))).execute();let N=new Set(X.connections.map((U)=>U.connection_id));for(let U of H)if(!N.has(U))G.push(U)}});for(let K of G)await this.cleanOrphanedPinnedViews([$],K);let J=await this.findById($);if(!J)throw Error("Virtual MCP not found after update");return J}async delete($){await this.db.transaction().execute(async(Z)=>{await Z.deleteFrom("threads").where("virtual_mcp_id","=",$).execute(),await Z.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).execute(),await Z.deleteFrom("connections").where("id","=",$).where("connection_type","=","VIRTUAL").execute()})}async removeConnectionReferences($){let Z=await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",$).execute();await this.db.deleteFrom("connection_aggregations").where("child_connection_id","=",$).execute(),await this.cleanOrphanedPinnedViews(Z.map((X)=>X.parent_connection_id),$)}async cleanOrphanedPinnedViews($,Z){for(let X of $){let Q=await this.db.selectFrom("connections").select("metadata").where("id","=",X).executeTakeFirst();if(!Q?.metadata)continue;let Y;try{Y=typeof Q.metadata==="string"?JSON.parse(Q.metadata):Q.metadata}catch{continue}let G=Y?.ui?.pinnedViews;if(!Array.isArray(G))continue;let J=G.filter((H)=>H.connectionId!==Z);if(J.length===G.length)continue;let K=Y.ui??{},W={...Y,ui:{...K,pinnedViews:J.length>0?J:null}};await this.db.updateTable("connections").set({metadata:JSON.stringify(W)}).where("id","=",X).execute()}}deserializeVirtualMCPEntity($,Z){let X=$.created_at instanceof Date?$.created_at.toISOString():$.created_at,Q=$.updated_at instanceof Date?$.updated_at.toISOString():$.updated_at,Y=$.status==="active"?"active":"inactive",G=this.parseJson($.metadata),{sandboxMap:J,...K}=G??{},W=J!==void 0?Qt0(J):void 0;return{id:$.id,organization_id:$.organization_id,title:$.title,description:$.description,icon:$.icon,status:Y,pinned:$.pinned,created_at:X,updated_at:Q,created_by:$.created_by,updated_by:$.updated_by??void 0,metadata:{...K,instructions:G?.instructions??null,...W!==void 0?{sandboxMap:W}:{}},connections:Z.map((H)=>({connection_id:H.child_connection_id,selected_tools:this.parseJson(H.selected_tools),selected_resources:this.parseJson(H.selected_resources),selected_prompts:this.parseJson(H.selected_prompts)}))}}parseJson($){if($===null)return null;if(typeof $==="string")try{return JSON.parse($)}catch{return null}return $}}function d98($){let Z=new Map,X=(Q,Y)=>{let G=Z.get(Q);if(G)return G;let J=Y();return Z.set(Q,J),J};return new Proxy($,{get(Q,Y,G){if(Y==="list")return(J,K)=>X(`list:${J}:${K?.pinnedOnly?1:0}`,()=>Q.list(J,K));if(Y==="create"||Y==="update"||Y==="delete"||Y==="removeConnectionReferences")return(...J)=>{return Z.clear(),Q[Y](...J)};return Reflect.get(Q,Y,G)}})}var ur0=w(()=>{GQ();A6()});function eE($){let Z=String($??"");if(Z&&!Z.includes("T"))return Z.replace(" ","T")+"Z";return Z}function R8($){return $.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/'/g,"''")}function o6($){let Z=Number($??0);return Number.isFinite(Z)?Z:0}function yQ4($){if(!bQ4.has($))throw Error(`Invalid groupByColumn: ${$}`);return $}function cr0($){if(!gQ4.test($))throw Error(`Invalid JSONPath: ${$}`);if($.startsWith("$."))return $;if($.startsWith("."))return`$${$}`;return`$.${$}`}function ir0($){return $.replace(/^\$\./,"").split(".").map((X)=>`'${R8(X)}'`).join(", ")}function cQ4($){let Z=hQ4.exec($);if(!Z||!Z[1]||!Z[2])throw Error(`Invalid interval: ${$}`);let X=parseInt(Z[1],10),Q=Z[2],Y=uQ4[Q];if(X<1||X>Y)throw Error(`Invalid interval amount: ${X}${Q} (max ${Y}${Q})`);return{amount:X,unit:Q}}function AO($,Z,X="timestamp"){let{amount:Q,unit:Y}=cQ4($),J={m:"MINUTE",h:"HOUR",d:"DAY"}[Y];if(Z==="duckdb")return`time_bucket(INTERVAL '${Q} ${J}', CAST(${X} AS TIMESTAMP))`;return`toStartOfInterval(${X}, INTERVAL ${Q} ${J})`}function Wp($,Z,X){if(X==="duckdb")return`json_extract_string(${$}, '${Z}')`;let Q=ir0(Z);return`JSONExtractString(${$}, ${Q})`}function lQ4($,Z,X){if(X==="duckdb")return`CAST(json_extract_string(${$}, '${Z}') AS DOUBLE)`;let Q=ir0(Z);return`JSONExtractFloat(${$}, ${Q})`}function m98($,Z,X){if(X==="duckdb")return`TRY_CAST(json_extract_string(${$}, '${Z}') AS DOUBLE)`;let Q=ir0(Z);return`toFloat64OrZero(JSONExtractString(${$}, ${Q}))`}function lr0($){if($===null||$===void 0)return{};if(typeof $==="object")return $;let Z=String($);try{return JSON.parse(Z)}catch{return{_decocms_truncated:Z}}}function dr0($){return{id:String($.id??""),organizationId:String($.organization_id??""),connectionId:String($.connection_id??""),toolName:String($.tool_name??""),input:lr0($.input),output:lr0($.output),isError:$.is_error===1||$.is_error===!0||$.is_error==="1"||typeof $.is_error==="bigint"&&$.is_error===1n,errorMessage:$.error_message!=null?String($.error_message):null,durationMs:Number($.duration_ms??0),timestamp:(()=>{if($.timestamp instanceof Date)return $.timestamp.toISOString();let Z=String($.timestamp??""),X=new Date(Z.includes("T")?Z:Z.replace(" ","T")+"Z");return Number.isNaN(X.getTime())?Z:X.toISOString()})(),userId:$.user_id!=null?String($.user_id):null,requestId:String($.request_id??""),userAgent:$.user_agent!=null?String($.user_agent):null,virtualMcpId:$.virtual_mcp_id!=null?String($.virtual_mcp_id):null,properties:$.properties?lr0($.properties):null}}function t98($,Z){let X=[];if($.properties)for(let[Q,Y]of Object.entries($.properties)){let G=R8(Q),J=R8(Y);if(Z==="duckdb")X.push(`json_extract_string(properties, '$.${G}') = '${J}'`);else X.push(`JSONExtractString(properties, '${G}') = '${J}'`)}if($.propertyKeys)for(let Q of $.propertyKeys){let Y=R8(Q);if(Z==="duckdb")X.push(`json_extract_string(properties, '$.${Y}') IS NOT NULL AND json_extract_string(properties, '$.${Y}') != ''`);else X.push(`JSONExtractString(properties, '${Y}') IS NOT NULL AND JSONExtractString(properties, '${Y}') != ''`)}if($.propertyPatterns)for(let[Q,Y]of Object.entries($.propertyPatterns)){let G=R8(Q),J=R8(Y);if(Z==="duckdb")X.push(`json_extract_string(properties, '$.${G}') ILIKE '${J}'`);else X.push(`JSONExtractString(properties, '${G}') ILIKE '${J}'`)}if($.propertyInValues)for(let[Q,Y]of Object.entries($.propertyInValues)){let G=R8(Q),J=R8(Y);if(Z==="duckdb")X.push(`list_contains(string_split(json_extract_string(properties, '$.${G}'), ','), '${J}')`);else X.push(`has(splitByChar(',', JSONExtractString(properties, '${G}')), '${J}')`)}return X}function n98($,Z){let X=[];if(P3(X,Z?.startDate,$),!Z)return X;if(Z.connectionIds?.length){let Q=Z.connectionIds.map((Y)=>`'${R8(Y)}'`).join(",");X.push(`connection_id IN (${Q})`)}if(Z.toolNames?.length){let Q=Z.toolNames.map((Y)=>`'${R8(Y)}'`).join(",");X.push(`tool_name IN (${Q})`)}if(Z.virtualMcpIds?.length){let Q=Z.virtualMcpIds.map((Y)=>`'${R8(Y)}'`).join(",");X.push(`virtual_mcp_id IN (${Q})`)}if(Z.endDate)X.push(j3(Z.endDate,$));if(Z.propertyFilters)X.push(...t98(Z.propertyFilters,$));return X}function p98($,Z,X="timestamp"){if(Z==="duckdb")return`CAST(${X} AS TIMESTAMP) >= TIMESTAMP '${$.toISOString()}'`;if(X==="bucket")return`${X} >= parseDateTimeBestEffort('${$.toISOString()}')`;return`${X} >= parseDateTime64BestEffort('${$.toISOString()}', 9)`}function j3($,Z,X="timestamp"){if(Z==="duckdb")return`CAST(${X} AS TIMESTAMP) <= TIMESTAMP '${$.toISOString()}'`;if(X==="bucket")return`${X} <= parseDateTimeBestEffort('${$.toISOString()}')`;return`${X} <= parseDateTime64BestEffort('${$.toISOString()}', 9)`}function P3($,Z,X,Q="timestamp"){if(Z)$.push(p98(Z,X,Q));else if(X==="clickhouse")$.push(p98(new Date(Date.now()-dQ4),X,Q))}class nr0{engine;sourceFactory;metricEngine;metricSourceFactory;dialect;metricsFromLogs;constructor($,Z,X,Q,Y="clickhouse",G=!1){this.engine=$;this.sourceFactory=Z;this.metricEngine=X;this.metricSourceFactory=Q;this.dialect=Y;this.metricsFromLogs=G}async query($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),X=[`organization_id = '${R8($.organizationId)}'`];if($.connectionId)X.push(`connection_id = '${R8($.connectionId)}'`);if($.excludeConnectionIds?.length){let F=$.excludeConnectionIds.map((B)=>`'${R8(B)}'`).join(",");X.push(`connection_id NOT IN (${F})`)}if($.virtualMcpId)X.push(`virtual_mcp_id = '${R8($.virtualMcpId)}'`);if($.toolName)X.push(`tool_name = '${R8($.toolName)}'`);if($.isError!==void 0)X.push(`is_error = ${$.isError?1:0}`);if(P3(X,$.startDate,this.dialect),$.endDate)X.push(j3($.endDate,this.dialect));if($.propertyFilters)X.push(...t98($.propertyFilters,this.dialect));let Q=1000,Y=Math.min(Math.max(1,Math.floor($.limit??50)),Q),G=Math.max(0,Math.floor($.offset??0)),J=X.join(" AND ");if(this.dialect==="duckdb"){let F=`SELECT ${i98}, count(*) OVER () AS _total FROM ${Z} WHERE ${J} ORDER BY timestamp DESC LIMIT ${Y} OFFSET ${G}`,B=await this.engine.query(F);if(B.length===0)return{logs:[],total:0};let O=Number(B[0]._total??0);return{logs:B.map(dr0),total:O}}let K=`SELECT count(*) AS total FROM ${Z} WHERE ${J}`,W=`SELECT ${i98} FROM ${Z} WHERE ${J} ORDER BY timestamp DESC LIMIT ${Y} OFFSET ${G}`,[H,N]=await Promise.all([this.engine.query(K),this.engine.query(W)]),U=Number(H[0]?.total??0);return{logs:N.map(dr0),total:U}}async getById($,Z){if(!$||!Z)return null;let Q=`SELECT * FROM ${this.sourceFactory($)} WHERE organization_id = '${R8($)}' AND id = '${R8(Z)}' LIMIT 1`,Y=await this.engine.query(Q);if(Y.length===0)return null;return dr0(Y[0])}async getStats($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),X=[`organization_id = '${R8($.organizationId)}'`];if(P3(X,$.startDate,this.dialect),$.endDate)X.push(j3($.endDate,this.dialect));let Q=`SELECT count(*) AS total_calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1.0 ELSE 0.0 END) / NULLIF(count(*), 0), 0) AS error_rate, coalesce(avg(duration_ms), 0) AS avg_duration_ms FROM ${Z} WHERE ${X.join(" AND ")}`,G=(await this.engine.query(Q))[0]??{};return{totalCalls:Number(G.total_calls??0),errorRate:Number(G.error_rate??0),avgDurationMs:Number(G.avg_duration_ms??0)}}async queryToolCallHeatmap($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),X=[`organization_id = '${R8($.organizationId)}'`,"type = 'tool_call'"];if($.filters?.virtualMcpIds?.length){let J=$.filters.virtualMcpIds.map((K)=>`'${R8(K)}'`).join(",");X.push(`virtual_mcp_id IN (${J})`)}if($.filters?.excludeConnectionIds?.length){let J=$.filters.excludeConnectionIds.map((K)=>`'${R8(K)}'`).join(",");X.push(`connection_id NOT IN (${J})`)}if(P3(X,$.startDate,this.dialect),$.endDate)X.push(j3($.endDate,this.dialect));let Q=Math.min(Math.max(1,Math.floor($.limit??500)),1000),Y=`SELECT virtual_mcp_id, tool_name, count(*) AS calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1 ELSE 0 END), 0) AS errors, coalesce(sum(length(output)), 0) AS output_size FROM ${Z} WHERE ${X.join(" AND ")} GROUP BY virtual_mcp_id, tool_name ORDER BY calls DESC LIMIT ${Q}`;return{cells:(await this.engine.query(Y)).map((J)=>({virtualMcpId:J.virtual_mcp_id?String(J.virtual_mcp_id):null,toolName:String(J.tool_name??""),calls:Number(J.calls??0),errors:Number(J.errors??0),outputSize:Number(J.output_size??0)}))}}async queryLlmUsageStats($){let Z={totalCalls:0,totalErrors:0,avgDurationMs:0,p50DurationMs:0,p95DurationMs:0,totalInputTokens:0,totalOutputTokens:0,totalTokens:0,totalCostUsd:0,topTools:[],timeseries:[]};if(!$.organizationId||!$.connectionId)return Z;let X=this.dialect,Q=X==="clickhouse",Y=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),G=AO($.interval,X,"timestamp"),J=(E)=>`coalesce(${m98("properties",`$.${E}`,X)}, 0)`,K=Q?"count()":"count(*)",W=Q?"countIf(is_error = 1)":"count(*) FILTER (WHERE is_error = 1)",H=(E)=>Q?`quantile(${E})(duration_ms)`:`quantile_cont(duration_ms, ${E})`,N=[`organization_id = '${R8($.organizationId)}'`,`connection_id = '${R8($.connectionId)}'`];if(P3(N,$.startDate,X),$.endDate)N.push(j3($.endDate,X));if($.userIds?.length){let E=$.userIds.slice(0,100).map((z)=>`'${R8(z)}'`).join(",");N.push(`user_id IN (${E})`)}let U=N.join(" AND "),F=Math.min(Math.max(1,Math.floor($.topN??5)),20),B=`${K} AS calls,
|
|
1428
|
+
`.trim();B98=HG("site-diagnostics_"),wL5=B98.is,LL5=B98.get,O98=HG("commerce-discovery_"),DL5=O98.is,NQ0=O98.get;LU={AGENT_MANAGER:HG("studio-agent-manager_"),AUTOMATION_MANAGER:HG("studio-automation-manager_"),CONNECTION_MANAGER:HG("studio-connection-manager_"),API_KEY_MANAGER:HG("studio-api-key-manager_"),STORE_MANAGER:HG("studio-store-manager_"),BRAND_MANAGER:HG("studio-brand-manager_"),TASK_MANAGER:HG("studio-task-manager_"),USAGE_MANAGER:HG("studio-usage-manager_")},HX={AGENT_MANAGER:LU.AGENT_MANAGER.get,AUTOMATION_MANAGER:LU.AUTOMATION_MANAGER.get,CONNECTION_MANAGER:LU.CONNECTION_MANAGER.get,API_KEY_MANAGER:LU.API_KEY_MANAGER.get,STORE_MANAGER:LU.STORE_MANAGER.get,BRAND_MANAGER:LU.BRAND_MANAGER.get,TASK_MANAGER:LU.TASK_MANAGER.get,USAGE_MANAGER:LU.USAGE_MANAGER.get}});function j98($){return $.toLowerCase().replace(/[^a-z0-9]/g,"")}function IQ4($){return j98($).includes("deepresearch")}function P98($){let Z=j98($);if(Z.includes("deepresearch"))return!1;return qQ4.some((X)=>Z.includes(X))}function MQ4($){return $.asyncResearch!==!0&&P98($.modelId)}function VQ4($){return $.asyncResearch===!0||IQ4($.modelId)||P98($.modelId)}function my($,Z,X,Q){for(let Y of X){let G=$.find((J)=>J.modelId===Y);if(G)return{keyId:Z,modelId:G.modelId,title:G.title}}for(let Y of X){let G=$.find((J)=>J.modelId.includes(Y));if(G)return{keyId:Z,modelId:G.modelId,title:G.title}}if(Q){let Y=$.find(Q);if(Y)return{keyId:Z,modelId:Y.modelId,title:Y.title}}return null}function A98($,Z){let X={chat:{fast:null,smart:null,thinking:null},image:null,webSearch:null,deepResearch:null};for(let Q of $){let Y=Z[Q.id]??[],G=Q.providerId;if(!X.chat.fast)X.chat.fast=my(Y,Q.id,zQ4[G]??[]);if(!X.chat.smart)X.chat.smart=my(Y,Q.id,jQ4[G]??[]);if(!X.chat.thinking)X.chat.thinking=my(Y,Q.id,PQ4[G]??[]);if(!X.image)X.image=my(Y,Q.id,AQ4[G]??[],(J)=>J.capabilities?.includes("image")===!0);if(!X.webSearch)X.webSearch=my(Y,Q.id,TQ4[G]??[],MQ4);if(!X.deepResearch)X.deepResearch=my(Y,Q.id,RQ4[G]??[],VQ4)}return X}var zQ4,jQ4,PQ4,AQ4,TQ4,RQ4,qQ4;var T98=w(()=>{zQ4={anthropic:["claude-haiku-4-5","claude-haiku"],openrouter:["qwen/qwen3.5-flash","anthropic/claude-haiku-4.5","anthropic/claude-haiku","google/gemini-3-flash"],deco:["qwen/qwen3.5-flash","anthropic/claude-haiku"],llmapi:["claude-haiku-4-5","claude-haiku","gpt-4o-mini"],google:["gemini-2.5-flash","gemini-3-flash"]},jQ4={anthropic:["claude-sonnet-5","claude-sonnet"],openrouter:["anthropic/claude-sonnet-5","anthropic/claude-sonnet","anthropic/claude-opus-4.8","google/gemini-3-pro"],deco:["anthropic/claude-sonnet-5","anthropic/claude-sonnet","anthropic/claude"],llmapi:["claude-sonnet-4-6","claude-sonnet"],google:["gemini-3-pro","gemini-3-flash"]},PQ4={anthropic:["claude-opus-4-8","claude-sonnet-5","claude-sonnet","claude-fable-5"],openrouter:["anthropic/claude-opus-4.8:extended","anthropic/claude-opus-4.8","anthropic/claude-sonnet-5:extended","anthropic/claude-sonnet-5","google/gemini-3-pro","anthropic/claude-fable-5"],deco:["anthropic/claude-opus","anthropic/claude-sonnet-4.6","anthropic/claude-sonnet","anthropic/claude-fable"],llmapi:["claude-opus-4-8","claude-opus","claude-sonnet-4-6"],google:["gemini-3-pro"]},AQ4={openrouter:["openai/gpt-image-1","google/gemini-2.0-flash-image"],deco:["openai/gpt-image-1","google/gemini-2.0-flash-image"],llmapi:["gemini-2.5-flash-image","gpt-image-1"],google:["gemini-2.0-flash-image"]},TQ4={openrouter:["perplexity/sonar","perplexity/sonar-pro"],deco:["perplexity/sonar","perplexity/sonar-pro"]},RQ4={openrouter:["perplexity/deep-research","perplexity/sonar-pro"],deco:["perplexity/deep-research","perplexity/sonar-pro"]};qQ4=["sonar","searchpreview","online"]});function UQ0($){if(!$)return;let Z={};for(let X in $){let Q=$[X];if(typeof Q==="object"&&Q!==null){let Y={};for(let G of kQ4)if(G in Q)Y[G]=Q[G];Z[X]=Y}}return Object.keys(Z).length>0?Z:void 0}var kQ4;var R98=w(()=>{kQ4=["usage","cost","model"]});var A6=w(()=>{d70();z98();T98();R98()});function FQ0($){return $.toLowerCase().trim().replace(/\//g,"-").replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function PO($){if($.app_name)return $.app_name;if($.connection_url)try{let Z=new URL($.connection_url),Q=((Z.port?`${Z.hostname}-${Z.port}`:Z.hostname)+Z.pathname).replace(/\/+$/,"");return FQ0(Q)}catch{return FQ0($.connection_url)}if($.title)return FQ0($.title);return $.id??"unknown"}var BQ0=()=>{};var iy=300000,OQ0=5000,_r0=3,vr0=30000,I98=65000,wQ0=1000,ny=3,q98=5,M98=60000,V98=300000,xr0=60000;function k98(){if(DU.size<wQ0)return;let $=null,Z=1/0;for(let[X,Q]of DU)if(Q.lastFailureAt<Z)Z=Q.lastFailureAt,$=X;if($)DU.delete($)}function S98($){let Z=DU.get($);if(!Z)return k98(),DU.set($,{consecutiveFailures:1,disabled:!1,lastFailureAt:Date.now()}),{consecutiveFailures:1,thresholdCrossed:1>=ny};return Z.consecutiveFailures++,Z.lastFailureAt=Date.now(),{consecutiveFailures:Z.consecutiveFailures,thresholdCrossed:Z.consecutiveFailures>=ny}}function fr0($){let Z=DU.get($);if(Z){Z.disabled=!0;return}k98(),DU.set($,{consecutiveFailures:ny,disabled:!0,lastFailureAt:Date.now()})}function C98($){return DU.get($)?.disabled??!1}function _98($){DU.delete($)}var DU;var v98=w(()=>{DU=new Map});import{sql as a8}from"kysely";function f98($){if($.length===0)return null;let Z=$[0];if($.length===1&&CQ4.has(Z))return a8.ref(Z);if($.length===2&&x98.has(Z)){let X=$[1];return a8`${a8.ref(Z)}->>${a8.lit(X)}`}if($.length>2&&x98.has(Z)){let X=`{${$.slice(1).join(",")}}`;return a8`${a8.ref(Z)}#>>${a8.lit(X)}`}return null}function b98($){if("conditions"in $){let{operator:G,conditions:J}=$;if(J.length===0)return a8`true`;let K=J.map((W)=>b98(W));switch(G){case"and":return a8`(${a8.join(K,a8` AND `)})`;case"or":return a8`(${a8.join(K,a8` OR `)})`;case"not":return a8`NOT (${a8.join(K,a8` AND `)})`;default:return a8`true`}}let{field:Z,operator:X,value:Q}=$,Y=f98(Z);if(!Y)return a8`true`;switch(X){case"eq":return Q===null?a8`${Y} IS NULL`:a8`${Y} = ${a8.val(Q)}`;case"gt":return a8`${Y} > ${a8.val(Q)}`;case"gte":return a8`${Y} >= ${a8.val(Q)}`;case"lt":return a8`${Y} < ${a8.val(Q)}`;case"lte":return a8`${Y} <= ${a8.val(Q)}`;case"in":if(!Array.isArray(Q)||Q.length===0)return a8`false`;return a8`${Y} IN (${a8.join(Q.map((G)=>a8.val(G)))})`;case"like":return a8`${Y} ILIKE ${a8.val(Q)}`;case"contains":{let G=String(Q).replace(/[%_\\]/g,"\\$&");return a8`${Y} ILIKE ${a8.val(`%${G}%`)}`}default:return a8`true`}}class Kp{db;vault;constructor($,Z){this.db=$;this.vault=Z}async create($){let Z=$.id??Q4("conn"),X=new Date().toISOString(),Q=await this.db.selectFrom("connections").select("organization_id").where("id","=",Z).executeTakeFirst();if(Q){if(Q.organization_id!==$.organization_id)throw Error("Connection ID already exists");return this.update(Z,$)}let Y=PO($),G=await this.serializeConnection({...$,id:$.id??Z,slug:Y,status:"active",created_at:X,updated_at:X}),J=await this.db.insertInto("connections").values(G).returningAll().executeTakeFirst();if(!J)throw Error(`Failed to create connection with id: ${Z}`);return this.deserializeConnection(J)}async createNew($){let Z=$.id??Q4("conn"),X=new Date().toISOString(),Q=PO($),Y=await this.serializeConnection({...$,id:Z,slug:Q,status:"active",created_at:X,updated_at:X}),G;try{G=await this.db.insertInto("connections").values(Y).returningAll().executeTakeFirst()}catch(J){if(J instanceof Error&&(J.message.includes("duplicate key")||J.message.includes("unique constraint")))throw Error("Connection ID already exists");throw J}if(!G)throw Error(`Failed to create connection with id: ${Z}`);return this.deserializeConnection(G)}async findById($,Z){let X=z3($);if(X)return E98(Z??X);let Q=this.db.selectFrom("connections").selectAll().where("id","=",$);if(Z)Q=Q.where("organization_id","=",Z);let Y=await Q.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async list($,Z){let X=this.db.selectFrom("connections").selectAll().where("organization_id","=",$);if(!Z?.includeVirtual)X=X.where("connection_type","!=","VIRTUAL");if(Z?.slug)X=X.where("slug","=",Z.slug);if(Z?.where)X=X.where(b98(Z.where));let G=(await this.db.selectFrom(X.as("filtered")).select(a8`count(*)::int`.as("count")).executeTakeFirst())?.count??0;if(Z?.orderBy&&Z.orderBy.length>0)for(let W of Z.orderBy){let H=f98(W.field);if(!H)continue;let N=W.direction==="desc"?a8`desc`:a8`asc`,U=W.nulls==="first"?a8`nulls first`:a8`nulls last`;X=X.orderBy(a8`${H} ${N} ${U}`)}if(Z?.limit)X=X.limit(Z.limit);if(Z?.offset)X=X.offset(Z.offset);let J=await X.execute();return{items:await Promise.all(J.map((W)=>this.deserializeConnection(W))),totalCount:G}}async update($,Z){if(Object.keys(Z).length===0){let J=await this.findById($);if(!J)throw Error("Connection not found");return J}let X={...Z},Q=await this.db.selectFrom("connections").select(["app_name","connection_url","title"]).where("id","=",$).executeTakeFirst();if(Q){let J=(K)=>Z[K]===void 0?Q[K]:Z[K];X.slug=PO({app_name:J("app_name"),connection_url:J("connection_url"),title:J("title"),id:$})}let Y=await this.serializeConnection({...X,updated_at:new Date().toISOString()}),G=await this.db.updateTable("connections").set(Y).where("id","=",$).returningAll().executeTakeFirst();if(!G)throw Error("Connection not found after update");return this.deserializeConnection(G)}async isReferencedByThread($){return await this.db.selectFrom("threads").select("id").where(a8`metadata -> 'githubRepo' ->> 'connectionId' = ${$}`).limit(1).executeTakeFirst()!==void 0}async delete($){await this.db.deleteFrom("connections").where("id","=",$).execute()}async testConnection($,Z){let X=await this.findById($);if(!X)throw Error("Connection not found");let Q=Date.now();if(X.connection_type==="STDIO")return{healthy:!0,latencyMs:Date.now()-Q};if(!X.connection_url)return{healthy:!1,latencyMs:Date.now()-Q};try{if(await ly(X.connection_url))return{healthy:!1,latencyMs:Date.now()-Q};let G=X.connection_headers,J=new AbortController,K=setTimeout(()=>J.abort(),1e4),W;try{W=await dy()(X.connection_url,{method:"POST",signal:J.signal,headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...G?.headers,...Z},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})})}finally{clearTimeout(K)}return{healthy:W.ok||W.status===404,latencyMs:Date.now()-Q}}catch{return{healthy:!1,latencyMs:Date.now()-Q}}}async serializeConnection($){let Z={};for(let[X,Q]of Object.entries($)){if(Q===void 0)continue;if(X==="tools")continue;if(X==="connection_token"&&Q)Z[X]=await this.vault.encrypt(Q);else if(X==="configuration_state"&&Q){let Y=JSON.stringify(Q);Z[X]=await this.vault.encrypt(Y)}else if(X==="connection_headers"&&Q){let Y=Q;if(fW(Y)&&Y.envVars){let G={};for(let[J,K]of Object.entries(Y.envVars))G[J]=await this.vault.encrypt(K);Z[X]=JSON.stringify({...Y,envVars:G})}else Z[X]=JSON.stringify(Y)}else if(SQ4.includes(X))Z[X]=Q?JSON.stringify(Q):null;else Z[X]=Q}return Z}async handleDecryptFailures($,Z){let X=`connection ${$.id} (org: ${$.organization_id}, type: ${$.connection_type}, title: ${$.title})`;if(C98($.id))return;if($.status!=="active"){fr0($.id);return}let{thresholdCrossed:Q}=S98($.id);if(!Q){for(let{label:Y,error:G}of Z)console.error(`Failed to decrypt ${Y} for ${X}:`,G);return}try{await this.db.updateTable("connections").set({status:"error"}).where("id","=",$.id).execute(),fr0($.id),console.error(`Disabled ${X} after ${ny} consecutive decryption failures.`,Z[0]?.error)}catch(Y){console.error(`Failed to disable ${X} after decryption failures:`,Y)}}async deserializeConnection($){let Z=[],X=null;if($.connection_token)try{X=await this.vault.decrypt($.connection_token)}catch(J){Z.push({label:"connection token",error:J})}let Q=null;if($.configuration_state)try{let J=await this.vault.decrypt($.configuration_state);Q=JSON.parse(J)}catch(J){Z.push({label:"configuration state",error:J})}if(Z.length>0)await this.handleDecryptFailures($,Z);else if($.connection_token||$.configuration_state)_98($.id);let Y=null;if($.connection_headers)try{let J=JSON.parse($.connection_headers);if(fW(J)&&J.envVars){let K={};for(let[W,H]of Object.entries(J.envVars))try{K[W]=await this.vault.decrypt(H)}catch{K[W]=H}Y={...J,envVars:K}}else Y=J}catch(J){console.error(`Failed to parse connection_headers for connection ${$.id} (org: ${$.organization_id}, type: ${$.connection_type}, title: ${$.title}):`,J)}let G=(J)=>{if(J===null)return null;if(typeof J==="string")try{return JSON.parse(J)}catch{return null}return J};return{id:$.id,organization_id:$.organization_id,created_by:$.created_by,updated_by:$.updated_by??void 0,title:$.title,description:$.description,icon:$.icon,app_name:$.app_name,app_id:$.app_id,slug:$.slug,connection_type:$.connection_type,connection_url:$.connection_url,connection_token:X,connection_headers:Y,oauth_config:G($.oauth_config),configuration_state:Q,configuration_scopes:G($.configuration_scopes),metadata:G($.metadata),tools:null,bindings:G($.bindings),status:$.status,created_at:$.created_at,updated_at:$.updated_at}}}var SQ4,CQ4,x98;var br0=w(()=>{yW();Jp();GQ();A6();BQ0();v98();SQ4=["connection_headers","oauth_config","configuration_scopes","metadata","bindings"],CQ4=new Set(["id","organization_id","created_by","updated_by","title","description","icon","app_name","app_id","slug","connection_type","connection_url","status","created_at","updated_at"]),x98=new Set(["metadata","configuration_scopes","bindings"])});import{createHash as _Q4,randomBytes as vQ4,timingSafeEqual as lL5}from"crypto";function fQ4($){return $.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function gr0($){return _Q4("sha256").update($).digest("hex")}function h98($){let Z=yr0.length+1,X=Z+g98;if(!$.startsWith(`${yr0}_`)||$.length<=X+1||$[X]!=="_")return null;let Q=$.slice(Z,X),Y=$.slice(X+1);if(!y98.test(Q)||!y98.test(Y))return null;return Q}function u98(){let $=fQ4(vQ4(xQ4)),Z=$.slice(0,g98),X=`${yr0}_${Z}_${$}`;return{plaintext:X,prefix:Z,hash:gr0(X)}}var yr0="stv",xQ4=32,g98=12,y98;var c98=w(()=>{y98=/^[A-Za-z0-9_-]+$/});function l98($){return{id:$.id,organizationId:$.organization_id,subjectConnectionId:$.subject_connection_id,tokenHash:$.token_hash,tokenPrefix:$.token_prefix,name:$.name,revokedAt:$.revoked_at,lastUsedAt:$.last_used_at,createdAt:$.created_at,updatedAt:$.updated_at}}class hr0{db;constructor($){this.db=$}async createOrRotateWorkloadToken($){let Z=$.name??"default";return await this.db.transaction().execute(async(Q)=>{if(!await Q.selectFrom("connections").select("id").where("id","=",$.subjectConnectionId).where("organization_id","=",$.organizationId).executeTakeFirst())throw Error("Subject connection not found in organization");let G=u98(),J=new Date().toISOString();await Q.updateTable("connection_workload_tokens").set({revoked_at:J,updated_at:J}).where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("name","=",Z).where("revoked_at","is",null).execute();let K=await Q.insertInto("connection_workload_tokens").values({id:Q4("cwt"),organization_id:$.organizationId,subject_connection_id:$.subjectConnectionId,token_hash:G.hash,token_prefix:G.prefix,name:Z,revoked_at:null,last_used_at:null,created_at:J,updated_at:J}).returningAll().executeTakeFirstOrThrow();return{plaintextToken:G.plaintext,record:l98(K)}})}async findActiveWorkloadToken($){let Z=await this.db.selectFrom("connection_workload_tokens").selectAll().where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("name","=",$.name??"default").where("revoked_at","is",null).executeTakeFirst();return Z?l98(Z):null}async revokeWorkloadToken($){let Z=new Date().toISOString();await this.db.updateTable("connection_workload_tokens").set({revoked_at:Z,updated_at:Z}).where("id","=",$.tokenId).where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("revoked_at","is",null).execute()}async authenticateWorkloadToken($){let Z=h98($);if(!Z)return null;let X=gr0($),Q=await this.db.selectFrom("connection_workload_tokens").select(["id","organization_id","subject_connection_id","token_prefix"]).where("token_prefix","=",Z).where("token_hash","=",X).where("revoked_at","is",null).executeTakeFirst();if(!Q)return null;let Y=new Date().toISOString();return await this.db.updateTable("connection_workload_tokens").set({last_used_at:Y,updated_at:Y}).where("id","=",Q.id).execute(),{tokenId:Q.id,tokenPrefix:Q.token_prefix,organizationId:Q.organization_id,subjectConnectionId:Q.subject_connection_id}}async replaceGrantsForSubject($){await this.db.transaction().execute(async(Z)=>{if(!await Z.selectFrom("connections").select("id").where("id","=",$.subjectConnectionId).where("organization_id","=",$.organizationId).executeTakeFirst())throw Error("Referenced connection not found in organization");let Q=[...new Set($.grants.map((J)=>J.targetConnectionId))];if(Q.length>0){if((await Z.selectFrom("connections").select("id").where("organization_id","=",$.organizationId).where("id","in",Q).execute()).length!==Q.length)throw Error("Referenced connection not found in organization")}if(await Z.deleteFrom("connection_credential_grants").where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).execute(),$.grants.length===0)return;let Y=new Date().toISOString(),G=$.grants.map((J)=>({id:Q4("ccg"),organization_id:$.organizationId,subject_connection_id:$.subjectConnectionId,target_connection_id:J.targetConnectionId,scope:J.scope,created_by:$.createdBy,created_at:Y,updated_at:Y}));await Z.insertInto("connection_credential_grants").values(G).execute()})}async hasGrant($){return!!await this.db.selectFrom("connection_credential_grants").select("id").where("organization_id","=",$.organizationId).where("subject_connection_id","=",$.subjectConnectionId).where("target_connection_id","=",$.targetConnectionId).where("scope","=",$.scope).executeTakeFirst()}}var LQ0="credential:access-token:read",DQ0="credential:configuration:read";var EQ0=w(()=>{GQ();c98()});class py{db;constructor($){this.db=$}async create($,Z,X,Q){let Y=Q?.id??Q4("vir"),G=new Date().toISOString();await this.db.transaction().execute(async(K)=>{if(await K.insertInto("connections").values({id:Y,organization_id:$,created_by:Z,title:X.title,description:X.description??null,icon:X.icon??null,app_name:null,app_id:null,connection_type:"VIRTUAL",pinned:X.pinned??!1,connection_url:`virtual://${Y}`,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:X.metadata?JSON.stringify(X.metadata):null,bindings:null,status:X.status??"active",created_at:G,updated_at:G}).execute(),X.connections.length>0)await K.insertInto("connection_aggregations").values(X.connections.map((W)=>({id:Q4("agg"),parent_connection_id:Y,child_connection_id:W.connection_id,selected_tools:W.selected_tools?JSON.stringify(W.selected_tools):null,selected_resources:W.selected_resources?JSON.stringify(W.selected_resources):null,selected_prompts:W.selected_prompts?JSON.stringify(W.selected_prompts):null,dependency_mode:"direct",created_at:G}))).execute()});let J=await this.findById(Y);if(!J)throw Error(`Failed to create virtual MCP with id: ${Y}`);return J}async findById($,Z){let X=z3($);if(X)return{...Cr0(Z??X),pinned:!1,connections:[]};let Q=HQ0($);if(Q)return{...F98(Z??Q),pinned:!1,connections:[]};return this.findByIdInternal(this.db,$)}async findByIdInternal($,Z){let X=await $.selectFrom("connections").selectAll().where("id","=",Z).where("connection_type","=","VIRTUAL").executeTakeFirst();if(!X)return null;let Q=await $.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","=",Z).where("dependency_mode","=","direct").execute();return this.deserializeVirtualMCPEntity(X,Q)}async list($,Z){let X=this.db.selectFrom("connections").selectAll().where("organization_id","=",$).where("connection_type","=","VIRTUAL");if(Z?.pinnedOnly)X=X.where("pinned","=",!0);let Q=await X.execute(),Y=Q.map((K)=>K.id);if(Y.length===0)return[];let G=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Y).where("dependency_mode","=","direct").execute(),J=new Map;for(let K of G){let W=J.get(K.parent_connection_id)??[];W.push(K),J.set(K.parent_connection_id,W)}return Q.map((K)=>this.deserializeVirtualMCPEntity(K,J.get(K.id)??[]))}async listByIds($,Z){if(Z.length===0)return[];let X=await this.db.selectFrom("connections").selectAll().where("id","in",Z).where("organization_id","=",$).where("connection_type","=","VIRTUAL").execute();if(X.length===0)return[];let Q=X.map((J)=>J.id),Y=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",Q).where("dependency_mode","=","direct").execute(),G=new Map;for(let J of Y){let K=G.get(J.parent_connection_id)??[];K.push(J),G.set(J.parent_connection_id,K)}return X.map((J)=>this.deserializeVirtualMCPEntity(J,G.get(J.id)??[]))}async listByConnectionId($,Z){let Q=(await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",Z).execute()).map((W)=>W.parent_connection_id);if(Q.length===0)return[];let Y=await this.db.selectFrom("connections").selectAll().where("id","in",Q).where("organization_id","=",$).where("connection_type","=","VIRTUAL").execute();if(Y.length===0)return[];let G=Y.map((W)=>W.id),J=await this.db.selectFrom("connection_aggregations").selectAll().where("parent_connection_id","in",G).where("dependency_mode","=","direct").execute(),K=new Map;for(let W of J){let H=K.get(W.parent_connection_id)??[];H.push(W),K.set(W.parent_connection_id,H)}return Y.map((W)=>this.deserializeVirtualMCPEntity(W,K.get(W.id)??[]))}async update($,Z,X){let Q=new Date().toISOString(),Y={updated_at:Q,updated_by:Z};if(X.title!==void 0)Y.title=X.title;if(X.description!==void 0)Y.description=X.description;if(X.icon!==void 0)Y.icon=X.icon;if(X.status!==void 0)Y.status=X.status;if(X.pinned!==void 0)Y.pinned=X.pinned;if(X.metadata!==void 0)Y.metadata=X.metadata?JSON.stringify(X.metadata):null;let G=[];await this.db.transaction().execute(async(K)=>{if(await K.updateTable("connections").set(Y).where("id","=",$).where("connection_type","=","VIRTUAL").execute(),X.connections!==void 0){let W=await K.selectFrom("connection_aggregations").select("child_connection_id").where("parent_connection_id","=",$).where("dependency_mode","=","direct").execute(),H=new Set(W.map((U)=>U.child_connection_id));if(await K.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).where("dependency_mode","=","direct").execute(),X.connections.length>0)await K.insertInto("connection_aggregations").values(X.connections.map((U)=>({id:Q4("agg"),parent_connection_id:$,child_connection_id:U.connection_id,selected_tools:U.selected_tools?JSON.stringify(U.selected_tools):null,selected_resources:U.selected_resources?JSON.stringify(U.selected_resources):null,selected_prompts:U.selected_prompts?JSON.stringify(U.selected_prompts):null,dependency_mode:"direct",created_at:Q}))).execute();let N=new Set(X.connections.map((U)=>U.connection_id));for(let U of H)if(!N.has(U))G.push(U)}});for(let K of G)await this.cleanOrphanedPinnedViews([$],K);let J=await this.findById($);if(!J)throw Error("Virtual MCP not found after update");return J}async delete($){await this.db.transaction().execute(async(Z)=>{await Z.deleteFrom("threads").where("virtual_mcp_id","=",$).execute(),await Z.deleteFrom("connection_aggregations").where("parent_connection_id","=",$).execute(),await Z.deleteFrom("connections").where("id","=",$).where("connection_type","=","VIRTUAL").execute()})}async removeConnectionReferences($){let Z=await this.db.selectFrom("connection_aggregations").select("parent_connection_id").where("child_connection_id","=",$).execute();await this.db.deleteFrom("connection_aggregations").where("child_connection_id","=",$).execute(),await this.cleanOrphanedPinnedViews(Z.map((X)=>X.parent_connection_id),$)}async cleanOrphanedPinnedViews($,Z){for(let X of $){let Q=await this.db.selectFrom("connections").select("metadata").where("id","=",X).executeTakeFirst();if(!Q?.metadata)continue;let Y;try{Y=typeof Q.metadata==="string"?JSON.parse(Q.metadata):Q.metadata}catch{continue}let G=Y?.ui?.pinnedViews;if(!Array.isArray(G))continue;let J=G.filter((H)=>H.connectionId!==Z);if(J.length===G.length)continue;let K=Y.ui??{},W={...Y,ui:{...K,pinnedViews:J.length>0?J:null}};await this.db.updateTable("connections").set({metadata:JSON.stringify(W)}).where("id","=",X).execute()}}deserializeVirtualMCPEntity($,Z){let X=$.created_at instanceof Date?$.created_at.toISOString():$.created_at,Q=$.updated_at instanceof Date?$.updated_at.toISOString():$.updated_at,Y=$.status==="active"?"active":"inactive",G=this.parseJson($.metadata),{sandboxMap:J,...K}=G??{},W=J!==void 0?Qt0(J):void 0;return{id:$.id,organization_id:$.organization_id,title:$.title,description:$.description,icon:$.icon,status:Y,pinned:$.pinned,created_at:X,updated_at:Q,created_by:$.created_by,updated_by:$.updated_by??void 0,metadata:{...K,instructions:G?.instructions??null,...W!==void 0?{sandboxMap:W}:{}},connections:Z.map((H)=>({connection_id:H.child_connection_id,selected_tools:this.parseJson(H.selected_tools),selected_resources:this.parseJson(H.selected_resources),selected_prompts:this.parseJson(H.selected_prompts)}))}}parseJson($){if($===null)return null;if(typeof $==="string")try{return JSON.parse($)}catch{return null}return $}}function d98($){let Z=new Map,X=(Q,Y)=>{let G=Z.get(Q);if(G)return G;let J=Y();return Z.set(Q,J),J};return new Proxy($,{get(Q,Y,G){if(Y==="list")return(J,K)=>X(`list:${J}:${K?.pinnedOnly?1:0}`,()=>Q.list(J,K));if(Y==="create"||Y==="update"||Y==="delete"||Y==="removeConnectionReferences")return(...J)=>{return Z.clear(),Q[Y](...J)};return Reflect.get(Q,Y,G)}})}var ur0=w(()=>{GQ();A6()});function eE($){let Z=String($??"");if(Z&&!Z.includes("T"))return Z.replace(" ","T")+"Z";return Z}function R8($){return $.replace(/\0/g,"").replace(/\\/g,"\\\\").replace(/'/g,"''")}function o6($){let Z=Number($??0);return Number.isFinite(Z)?Z:0}function yQ4($){if(!bQ4.has($))throw Error(`Invalid groupByColumn: ${$}`);return $}function cr0($){if(!gQ4.test($))throw Error(`Invalid JSONPath: ${$}`);if($.startsWith("$."))return $;if($.startsWith("."))return`$${$}`;return`$.${$}`}function ir0($){return $.replace(/^\$\./,"").split(".").map((X)=>`'${R8(X)}'`).join(", ")}function cQ4($){let Z=hQ4.exec($);if(!Z||!Z[1]||!Z[2])throw Error(`Invalid interval: ${$}`);let X=parseInt(Z[1],10),Q=Z[2],Y=uQ4[Q];if(X<1||X>Y)throw Error(`Invalid interval amount: ${X}${Q} (max ${Y}${Q})`);return{amount:X,unit:Q}}function AO($,Z,X="timestamp"){let{amount:Q,unit:Y}=cQ4($),J={m:"MINUTE",h:"HOUR",d:"DAY"}[Y];if(Z==="duckdb")return`time_bucket(INTERVAL '${Q} ${J}', CAST(${X} AS TIMESTAMP))`;return`toStartOfInterval(${X}, INTERVAL ${Q} ${J})`}function Wp($,Z,X){if(X==="duckdb")return`json_extract_string(${$}, '${Z}')`;let Q=ir0(Z);return`JSONExtractString(${$}, ${Q})`}function lQ4($,Z,X){if(X==="duckdb")return`CAST(json_extract_string(${$}, '${Z}') AS DOUBLE)`;let Q=ir0(Z);return`JSONExtractFloat(${$}, ${Q})`}function m98($,Z,X){if(X==="duckdb")return`TRY_CAST(json_extract_string(${$}, '${Z}') AS DOUBLE)`;let Q=ir0(Z);return`toFloat64OrZero(JSONExtractString(${$}, ${Q}))`}function lr0($){if($===null||$===void 0)return{};if(typeof $==="object")return $;let Z=String($);try{return JSON.parse(Z)}catch{return{_decocms_truncated:Z}}}function dr0($){return{id:String($.id??""),organizationId:String($.organization_id??""),connectionId:String($.connection_id??""),toolName:String($.tool_name??""),input:lr0($.input),output:lr0($.output),isError:$.is_error===1||$.is_error===!0||$.is_error==="1"||typeof $.is_error==="bigint"&&$.is_error===1n,errorMessage:$.error_message!=null?String($.error_message):null,durationMs:Number($.duration_ms??0),timestamp:(()=>{if($.timestamp instanceof Date)return $.timestamp.toISOString();let Z=String($.timestamp??""),X=new Date(Z.includes("T")?Z:Z.replace(" ","T")+"Z");return Number.isNaN(X.getTime())?Z:X.toISOString()})(),userId:$.user_id!=null?String($.user_id):null,requestId:String($.request_id??""),userAgent:$.user_agent!=null?String($.user_agent):null,virtualMcpId:$.virtual_mcp_id!=null?String($.virtual_mcp_id):null,properties:$.properties?lr0($.properties):null}}function t98($,Z){let X=[];if($.properties)for(let[Q,Y]of Object.entries($.properties)){let G=R8(Q),J=R8(Y);if(Z==="duckdb")X.push(`json_extract_string(properties, '$.${G}') = '${J}'`);else X.push(`JSONExtractString(properties, '${G}') = '${J}'`)}if($.propertyKeys)for(let Q of $.propertyKeys){let Y=R8(Q);if(Z==="duckdb")X.push(`json_extract_string(properties, '$.${Y}') IS NOT NULL AND json_extract_string(properties, '$.${Y}') != ''`);else X.push(`JSONExtractString(properties, '${Y}') IS NOT NULL AND JSONExtractString(properties, '${Y}') != ''`)}if($.propertyPatterns)for(let[Q,Y]of Object.entries($.propertyPatterns)){let G=R8(Q),J=R8(Y);if(Z==="duckdb")X.push(`json_extract_string(properties, '$.${G}') ILIKE '${J}'`);else X.push(`JSONExtractString(properties, '${G}') ILIKE '${J}'`)}if($.propertyInValues)for(let[Q,Y]of Object.entries($.propertyInValues)){let G=R8(Q),J=R8(Y);if(Z==="duckdb")X.push(`list_contains(string_split(json_extract_string(properties, '$.${G}'), ','), '${J}')`);else X.push(`has(splitByChar(',', JSONExtractString(properties, '${G}')), '${J}')`)}return X}function n98($,Z){let X=[];if(P3(X,Z?.startDate,$),!Z)return X;if(Z.connectionIds?.length){let Q=Z.connectionIds.map((Y)=>`'${R8(Y)}'`).join(",");X.push(`connection_id IN (${Q})`)}if(Z.toolNames?.length){let Q=Z.toolNames.map((Y)=>`'${R8(Y)}'`).join(",");X.push(`tool_name IN (${Q})`)}if(Z.virtualMcpIds?.length){let Q=Z.virtualMcpIds.map((Y)=>`'${R8(Y)}'`).join(",");X.push(`virtual_mcp_id IN (${Q})`)}if(Z.endDate)X.push(j3(Z.endDate,$));if(Z.propertyFilters)X.push(...t98(Z.propertyFilters,$));return X}function p98($,Z,X="timestamp"){if(Z==="duckdb")return`CAST(${X} AS TIMESTAMP) >= TIMESTAMP '${$.toISOString()}'`;if(X==="bucket")return`${X} >= parseDateTimeBestEffort('${$.toISOString()}')`;return`${X} >= parseDateTime64BestEffort('${$.toISOString()}', 9)`}function j3($,Z,X="timestamp"){if(Z==="duckdb")return`CAST(${X} AS TIMESTAMP) <= TIMESTAMP '${$.toISOString()}'`;if(X==="bucket")return`${X} <= parseDateTimeBestEffort('${$.toISOString()}')`;return`${X} <= parseDateTime64BestEffort('${$.toISOString()}', 9)`}function P3($,Z,X,Q="timestamp"){if(Z)$.push(p98(Z,X,Q));else if(X==="clickhouse")$.push(p98(new Date(Date.now()-dQ4),X,Q))}class nr0{engine;sourceFactory;metricEngine;metricSourceFactory;dialect;metricsFromLogs;constructor($,Z,X,Q,Y="clickhouse",G=!1){this.engine=$;this.sourceFactory=Z;this.metricEngine=X;this.metricSourceFactory=Q;this.dialect=Y;this.metricsFromLogs=G}async query($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),X=[`organization_id = '${R8($.organizationId)}'`];if($.connectionId)X.push(`connection_id = '${R8($.connectionId)}'`);if($.excludeConnectionIds?.length){let F=$.excludeConnectionIds.map((B)=>`'${R8(B)}'`).join(",");X.push(`connection_id NOT IN (${F})`)}if($.virtualMcpId)X.push(`virtual_mcp_id = '${R8($.virtualMcpId)}'`);if($.toolName)X.push(`tool_name = '${R8($.toolName)}'`);if($.isError!==void 0)X.push(`is_error = ${$.isError?1:0}`);if(P3(X,$.startDate,this.dialect),$.endDate)X.push(j3($.endDate,this.dialect));if($.propertyFilters)X.push(...t98($.propertyFilters,this.dialect));let Q=1000,Y=Math.min(Math.max(1,Math.floor($.limit??50)),Q),G=Math.max(0,Math.floor($.offset??0)),J=X.join(" AND ");if(this.dialect==="duckdb"){let F=`SELECT ${i98}, count(*) OVER () AS _total FROM ${Z} WHERE ${J} ORDER BY timestamp DESC LIMIT ${Y} OFFSET ${G}`,B=await this.engine.query(F);if(B.length===0)return{logs:[],total:0};let O=Number(B[0]._total??0);return{logs:B.map(dr0),total:O}}let K=`SELECT count(*) AS total FROM ${Z} WHERE ${J}`,W=`SELECT ${i98} FROM ${Z} WHERE ${J} ORDER BY timestamp DESC LIMIT ${Y} OFFSET ${G}`,[H,N]=await Promise.all([this.engine.query(K),this.engine.query(W)]),U=Number(H[0]?.total??0);return{logs:N.map(dr0),total:U}}async getById($,Z){if(!$||!Z)return null;let Q=`SELECT * FROM ${this.sourceFactory($)} WHERE organization_id = '${R8($)}' AND id = '${R8(Z)}' LIMIT 1`,Y=await this.engine.query(Q);if(Y.length===0)return null;return dr0(Y[0])}async getStats($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),X=[`organization_id = '${R8($.organizationId)}'`];if(P3(X,$.startDate,this.dialect),$.endDate)X.push(j3($.endDate,this.dialect));let Q=`SELECT count(*) AS total_calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1.0 ELSE 0.0 END) / NULLIF(count(*), 0), 0) AS error_rate, coalesce(avg(duration_ms), 0) AS avg_duration_ms FROM ${Z} WHERE ${X.join(" AND ")}`,G=(await this.engine.query(Q))[0]??{};return{totalCalls:Number(G.total_calls??0),errorRate:Number(G.error_rate??0),avgDurationMs:Number(G.avg_duration_ms??0)}}async queryToolCallHeatmap($){if(!$.organizationId)throw Error("organizationId is required");let Z=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),X=[`organization_id = '${R8($.organizationId)}'`,"type = 'tool_call'"];if($.filters?.virtualMcpIds?.length){let J=$.filters.virtualMcpIds.map((K)=>`'${R8(K)}'`).join(",");X.push(`virtual_mcp_id IN (${J})`)}if($.filters?.excludeConnectionIds?.length){let J=$.filters.excludeConnectionIds.map((K)=>`'${R8(K)}'`).join(",");X.push(`connection_id NOT IN (${J})`)}if(P3(X,$.startDate,this.dialect),$.endDate)X.push(j3($.endDate,this.dialect));let Q=Math.min(Math.max(1,Math.floor($.limit??500)),1000),Y=`SELECT virtual_mcp_id, tool_name, count(*) AS calls, coalesce(sum(CASE WHEN is_error = 1 THEN 1 ELSE 0 END), 0) AS errors, coalesce(sum(length(output)), 0) AS output_size FROM ${Z} WHERE ${X.join(" AND ")} GROUP BY virtual_mcp_id, tool_name ORDER BY calls DESC LIMIT ${Q}`;return{cells:(await this.engine.query(Y)).map((J)=>({virtualMcpId:J.virtual_mcp_id?String(J.virtual_mcp_id):null,toolName:String(J.tool_name??""),calls:Number(J.calls??0),errors:Number(J.errors??0),outputSize:Number(J.output_size??0)}))}}async queryLlmUsageStats($){let Z={totalCalls:0,totalErrors:0,avgDurationMs:0,p50DurationMs:0,p95DurationMs:0,totalInputTokens:0,totalOutputTokens:0,totalTokens:0,totalCostUsd:0,topTools:[],timeseries:[]};if(!$.organizationId||!$.connectionId)return Z;let X=this.dialect,Q=X==="clickhouse",Y=this.sourceFactory($.organizationId,{startDate:$.startDate,endDate:$.endDate}),G=AO($.interval,X,"timestamp"),J=(E)=>`coalesce(${m98("properties",`$.${E}`,X)}, 0)`,K=Q?"count()":"count(*)",W=Q?"countIf(is_error = 1)":"count(*) FILTER (WHERE is_error = 1)",H=(E)=>Q?`quantile(${E})(duration_ms)`:`quantile_cont(duration_ms, ${E})`,N=[`organization_id = '${R8($.organizationId)}'`,`connection_id = '${R8($.connectionId)}'`];if(P3(N,$.startDate,X),$.endDate)N.push(j3($.endDate,X));if($.userIds?.length){let E=$.userIds.slice(0,100).map((z)=>`'${R8(z)}'`).join(",");N.push(`user_id IN (${E})`)}let U=N.join(" AND "),F=Math.min(Math.max(1,Math.floor($.topN??5)),20),B=`${K} AS calls,
|
|
1429
1429
|
${W} AS errors,
|
|
1430
1430
|
avg(duration_ms) AS avg,
|
|
1431
1431
|
sum(${J("input_tokens")}) AS in_tok,
|
|
@@ -2794,7 +2794,7 @@ ${JC8(Z.content)}
|
|
|
2794
2794
|
`)X--;return $.slice(Z,X)}function Ln4($){let Z=[],X=0;while(X<$.length){let Q=Dn4($,X),Y=KC8($,X,"{noformat}"),G=KC8($,X,"{quote}"),J=[];if(Q)J.push({type:"code",...Q});if(Y)J.push({type:"code",lang:"",...Y});if(G)J.push({type:"quote",...G});let K=J.sort((W,H)=>W.start-H.start)[0];if(!K){Z.push({type:"text",content:$.slice(X)});break}if(K.start>X)Z.push({type:"text",content:$.slice(X,K.start)});Z.push(K),X=K.end}return Z}function Dn4($,Z){for(let X=$.indexOf("{code",Z);X!==-1;){let Q=$.indexOf("}",X);if(Q===-1)return null;let Y=$.slice(X+5,Q);if(Y===""||Y.startsWith(":")){let G=$.indexOf("{code}",Q+1);if(G===-1)return null;let J=Y.startsWith(":")?Y.slice(1).split("|")[0]??"":"";return{start:X,end:G+6,content:$.slice(Q+1,G),lang:J}}X=$.indexOf("{code",X+1)}return null}function KC8($,Z,X){let Q=$.indexOf(X,Z);if(Q===-1)return null;let Y=$.indexOf(X,Q+X.length);if(Y===-1)return null;return{start:Q,end:Y+X.length,content:$.slice(Q+X.length,Y)}}function WC8($){return $.split(`
|
|
2795
2795
|
`).map(zn4).join(`
|
|
2796
2796
|
`)}function r91($,Z){let X=0;while($[X]===Z)X++;return X}function En4($){let Z=$.trim();return Z.length>=4&&r91(Z,"-")===Z.length}function zn4($){let Z=$[1]??"";if($[0]==="h"&&Z>="1"&&Z<="6"&&$[2]===".")return`${"#".repeat(Number(Z))} ${wv($.slice(3).trimStart())}`;if(En4($))return"---";let X=r91($,"*");if(X>0&&$[X]===" ")return`${X===1?"*":`${" ".repeat(X-1)}-`} ${wv($.slice(X+1))}`;let Q=r91($,"#");if(Q>0&&$[Q]===" ")return`${" ".repeat(Q-1)}1. ${wv($.slice(Q+1))}`;let Y=$.trimEnd();if(Y.startsWith("||")&&Y.endsWith("||")&&Y.length>4){let G=Y.slice(2,-2).split("||");return`${`| ${G.map((K)=>wv(K.trim())).join(" | ")} |`}
|
|
2797
|
-
|${G.map(()=>" --- ").join("|")}|`}if(Y.startsWith("|")&&Y.endsWith("|")&&Y.length>2)return`| ${Y.slice(1,-1).split("|").map((J)=>wv(J.trim())).join(" | ")} |`;return wv($)}function o91($){return($.startsWith("http://")||$.startsWith("https://"))&&!$.includes(" ")}function wv($){let Z="",X=0;while(X<$.length){let Q=$[X]??"";if(Q==="{"){if($.startsWith("{{",X)){let Y=$.indexOf("}}",X+2);if(Y!==-1){Z+=`\`${$.slice(X+2,Y)}\``,X=Y+2;continue}}if($.startsWith("{color",X)){let Y=$.indexOf("}",X);if(Y!==-1){X=Y+1;continue}}}else if(Q==="["){let Y=$.indexOf("]",X);if(Y!==-1){let G=$.slice(X+1,Y),J=G.indexOf("|");if(J!==-1&&o91(G.slice(J+1))){Z+=`[${G.slice(0,J)}](${G.slice(J+1)})`,X=Y+1;continue}if(o91(G)){Z+=G,X=Y+1;continue}}}else if(Q==="!"){let Y=$.indexOf("!",X+1);if(Y!==-1){let G=$.slice(X+1,Y),J=G.indexOf("|"),K=J===-1?G:G.slice(0,J);if(o91(K)){Z+=``,X=Y+1;continue}}}else if(Q==="*"||Q==="_"){let Y=An4($,X,Q,Z.slice(-1)||" ");if(Y){Z+=Y.text,X=Y.next;continue}}Z+=Q,X++}return Z}function An4($,Z,X,Q){if(!jn4.includes(Q))return null;let Y=$[Z+1];if(!Y||Y===" "||Y===X)return null;for(let G=Z+2;G<$.length;G++){if($[G]!==X||$[G-1]===" ")continue;let J=$[G+1];if(J!==void 0&&!Pn4.includes(J))continue;let K=wv($.slice(Z+1,G));return{text:X==="*"?`**${K}**`:`*${K}*`,next:G+1}}return null}var jn4=" ([{>",Pn4=` )]}.,:;!?{["'`;function In4($){let Z=$ instanceof Error?$.message:String($);if(Z.includes("AbortError")||Z.includes("fetch")||Z.includes("timeout")||Z.includes("network")||Z.includes("ECONNREFUSED")||Z.includes("ECONNRESET"))return!0;let X=Z.match(/failed \((\d+)\)/);if(X&&X[1]){let Q=parseInt(X[1],10);return Q>=500||Q===429}return!0}function s91($){let Z=$.trim().replace(/\/+$/,""),X=/^https?:\/\//i.test(Z)?Z:`https://${Z}`,Q;try{Q=new URL(X).hostname.toLowerCase()}catch{throw Error(`Invalid Jira site URL: ${$}`)}if(!qn4.test(Q))throw Error(`Invalid Jira site URL: ${$} \u2014 expected <your-site>.atlassian.net`);return`https://${Q}`}function a91($){if(!/^\d+$/.test($))throw Error(`Invalid Jira board id: ${$}`);return $}class yK{baseUrl;authHeader;constructor($,Z,X){this.baseUrl=s91($),this.authHeader=`Basic ${Buffer.from(`${Z}:${X}`).toString("base64")}`}async request($,Z){
|
|
2797
|
+
|${G.map(()=>" --- ").join("|")}|`}if(Y.startsWith("|")&&Y.endsWith("|")&&Y.length>2)return`| ${Y.slice(1,-1).split("|").map((J)=>wv(J.trim())).join(" | ")} |`;return wv($)}function o91($){return($.startsWith("http://")||$.startsWith("https://"))&&!$.includes(" ")}function wv($){let Z="",X=0;while(X<$.length){let Q=$[X]??"";if(Q==="{"){if($.startsWith("{{",X)){let Y=$.indexOf("}}",X+2);if(Y!==-1){Z+=`\`${$.slice(X+2,Y)}\``,X=Y+2;continue}}if($.startsWith("{color",X)){let Y=$.indexOf("}",X);if(Y!==-1){X=Y+1;continue}}}else if(Q==="["){let Y=$.indexOf("]",X);if(Y!==-1){let G=$.slice(X+1,Y),J=G.indexOf("|");if(J!==-1&&o91(G.slice(J+1))){Z+=`[${G.slice(0,J)}](${G.slice(J+1)})`,X=Y+1;continue}if(o91(G)){Z+=G,X=Y+1;continue}}}else if(Q==="!"){let Y=$.indexOf("!",X+1);if(Y!==-1){let G=$.slice(X+1,Y),J=G.indexOf("|"),K=J===-1?G:G.slice(0,J);if(o91(K)){Z+=``,X=Y+1;continue}}}else if(Q==="*"||Q==="_"){let Y=An4($,X,Q,Z.slice(-1)||" ");if(Y){Z+=Y.text,X=Y.next;continue}}Z+=Q,X++}return Z}function An4($,Z,X,Q){if(!jn4.includes(Q))return null;let Y=$[Z+1];if(!Y||Y===" "||Y===X)return null;for(let G=Z+2;G<$.length;G++){if($[G]!==X||$[G-1]===" ")continue;let J=$[G+1];if(J!==void 0&&!Pn4.includes(J))continue;let K=wv($.slice(Z+1,G));return{text:X==="*"?`**${K}**`:`*${K}*`,next:G+1}}return null}var jn4=" ([{>",Pn4=` )]}.,:;!?{["'`;function In4($){let Z=$ instanceof Error?$.message:String($);if(Z.includes("AbortError")||Z.includes("fetch")||Z.includes("timeout")||Z.includes("network")||Z.includes("ECONNREFUSED")||Z.includes("ECONNRESET"))return!0;let X=Z.match(/failed \((\d+)\)/);if(X&&X[1]){let Q=parseInt(X[1],10);return Q>=500||Q===429}return!0}function s91($){let Z=$.trim().replace(/\/+$/,""),X=/^https?:\/\//i.test(Z)?Z:`https://${Z}`,Q;try{Q=new URL(X).hostname.toLowerCase()}catch{throw Error(`Invalid Jira site URL: ${$}`)}if(!qn4.test(Q))throw Error(`Invalid Jira site URL: ${$} \u2014 expected <your-site>.atlassian.net`);return`https://${Q}`}function a91($){if(!/^\d+$/.test($))throw Error(`Invalid Jira board id: ${$}`);return $}class yK{baseUrl;authHeader;constructor($,Z,X){this.baseUrl=s91($),this.authHeader=`Basic ${Buffer.from(`${Z}:${X}`).toString("base64")}`}async request($,Z,{idempotent:X=!0}={}){let Q=async()=>{let Y=await fetch(`${this.baseUrl}${$}`,{...Z,headers:{Authorization:this.authHeader,Accept:"application/json",...Z?.body?{"Content-Type":"application/json"}:{}},signal:AbortSignal.timeout(Tn4)}),G=await Y.text().catch(()=>"");if(!Y.ok)throw Error(`Jira ${$} failed (${Y.status}): ${G.slice(0,300)}`);return G===""?void 0:JSON.parse(G)};if(!X)return Q();return j5(Q,{maxAttempts:3,minTimeout:100,maxTimeout:5000,multiplier:2,jitter:1,isRetriable:In4})}async myself(){return this.request("/rest/api/3/myself")}async listBoards(){let $=[],Z=0;while($.length<200){let X=await this.request(`/rest/agile/1.0/board?startAt=${Z}&maxResults=50`);if($.push(...X.values.map((Q)=>({id:Q.id,name:Q.name,type:Q.type,projectKey:Q.location?.projectKey}))),X.isLast||X.values.length===0)break;Z+=X.values.length}return $}async getBoardColumns($){let Z=await this.request(`/rest/agile/1.0/board/${a91($)}/configuration`),X=new Map,Q=[];for(let Y of Z.columnConfig?.columns??[]){let G=[];for(let J of Y.statuses??[]){if(!X.has(J.id)){let K=await this.request(`/rest/api/3/status/${encodeURIComponent(J.id)}`);X.set(J.id,K.name)}G.push(X.get(J.id)??J.id)}Q.push({name:Y.name,statuses:G})}return Q}async listBoardIssues($){let Z=new URLSearchParams({startAt:String($.startAt),maxResults:"100",jql:$.jql,fields:Rn4}),X=await this.request(`/rest/agile/1.0/board/${a91($.boardId)}/issue?${Z}`);return{issues:X.issues??[],total:X.total}}async listBacklogIssueIds($){let Z=new Set,X=0;while(Z.size<5000){let Q=await this.request(`/rest/agile/1.0/board/${a91($)}/backlog?startAt=${X}&maxResults=100&fields=id`);for(let Y of Q.issues??[])Z.add(Y.id);if(X+=Q.issues?.length??0,X>=Q.total||(Q.issues?.length??0)===0)break}return Z}async listTransitions($){return(await this.request(`/rest/api/3/issue/${encodeURIComponent($)}/transitions`)).transitions??[]}async getStatusName($){return(await this.request(`/rest/api/3/issue/${encodeURIComponent($)}?fields=status`)).fields?.status?.name??null}async transitionIssue($,Z){await this.request(`/rest/api/3/issue/${encodeURIComponent($)}/transitions`,{method:"POST",body:JSON.stringify({transition:{id:Z}})},{idempotent:!1})}async listComments($){let Z=[],X=0;while(Z.length<1000){let Q=await this.request(`/rest/api/3/issue/${encodeURIComponent($)}/comment?startAt=${X}&maxResults=100&orderBy=created`);if(Z.push(...Q.comments),Z.length>=Q.total||Q.comments.length===0)break;X+=Q.comments.length}return Z}async addComment($,Z){return this.request(`/rest/api/3/issue/${encodeURIComponent($)}/comment`,{method:"POST",body:JSON.stringify({body:Mn4(Z)})},{idempotent:!1})}}function Mn4($){let Z=$.split(`
|
|
2798
2798
|
`).filter((X)=>X.trim()!=="");return{type:"doc",version:1,content:Z.length>0?Z.map((X)=>({type:"paragraph",content:[{type:"text",text:X}]})):[{type:"paragraph",content:[]}]}}function HA0($){if(typeof $==="string")return HC8($);if(!$||typeof $!=="object")return"";let Z=$;if(Z.type==="text")return Z.text??"";if(Z.type==="hardBreak")return`
|
|
2799
2799
|
`;let X=(Array.isArray(Z.content)?Z.content:[]).map(HA0);if(Z.type==="doc")return X.filter((Q)=>Q.trim()!=="").join(`
|
|
2800
2800
|
|