decocms 2.310.2 → 2.310.3
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-Bjs1DRoe.js → AlertCircle-B72APkrz.js} +1 -1
- package/dist/client/assets/{ArrowNarrowLeft-4-qtN4yo.js → ArrowNarrowLeft-Dz0P9WNF.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-TOJd4tk1.js → ArrowUpRight-CCQZEQ7k.js} +1 -1
- package/dist/client/assets/{Check-uCeCY94f.js → Check-CUpq9BBu.js} +1 -1
- package/dist/client/assets/{CheckCircle-BYjzCjZv.js → CheckCircle-DTCxFilU.js} +1 -1
- package/dist/client/assets/{ChevronDown-BCKKMGkp.js → ChevronDown-D5WF5tyi.js} +1 -1
- package/dist/client/assets/{ChevronRight-CBRO8ebn.js → ChevronRight-DwbV0YDZ.js} +1 -1
- package/dist/client/assets/{ChevronUp-CImlARUB.js → ChevronUp-CDMPc0ql.js} +1 -1
- package/dist/client/assets/{Container-UmsQv9ox.js → Container-BioZd28q.js} +1 -1
- package/dist/client/assets/{DotsVertical-DYz9Xowp.js → DotsVertical-D8wcDPCU.js} +1 -1
- package/dist/client/assets/{LinkExternal01-MfoA7_8K.js → LinkExternal01-CKpEz_fF.js} +1 -1
- package/dist/client/assets/{Lock01-DY0dR_EF.js → Lock01-CHfwR6Qi.js} +1 -1
- package/dist/client/assets/{Palette-CYlPasQS.js → Palette-brLBiHpP.js} +1 -1
- package/dist/client/assets/{Play-BOunn_Vy.js → Play-DRCdZRLW.js} +1 -1
- package/dist/client/assets/{Plus-DJQM2qca.js → Plus-DNkjVBwq.js} +1 -1
- package/dist/client/assets/{RefreshCcw01-fb__YhOw.js → RefreshCcw01-CdP9yH0w.js} +1 -1
- package/dist/client/assets/{SearchMd-Bv6wAjVm.js → SearchMd-JqX1mLMq.js} +1 -1
- package/dist/client/assets/{Settings02-ZxqKPBpN.js → Settings02-D1Jfvo1d.js} +1 -1
- package/dist/client/assets/{Shield01-DLP8JywO.js → Shield01-D5fQpAyA.js} +1 -1
- package/dist/client/assets/{Star01-DO3o-Tm0.js → Star01-Y834gtsL.js} +1 -1
- package/dist/client/assets/{Sun-CZnXZvsq.js → Sun-BgOSswUu.js} +1 -1
- package/dist/client/assets/{Tool01-D8__PXyN.js → Tool01-CXQZ3p7Z.js} +1 -1
- package/dist/client/assets/{Trash01-CaQDsaot.js → Trash01-B8-uqWxa.js} +1 -1
- package/dist/client/assets/{User01-oR5RStEl.js → User01-Cxb6YtJq.js} +1 -1
- package/dist/client/assets/{Users03-BsIZE4Pm.js → Users03-CXkopkPu.js} +1 -1
- package/dist/client/assets/{X-vjP4Msb7.js → X-CdXDgTcN.js} +1 -1
- package/dist/client/assets/{XCircle-Bjg8qJ8l.js → XCircle-CjR4LC4r.js} +1 -1
- package/dist/client/assets/{XClose-CaKKQVXU.js → XClose-zqTFiPq2.js} +1 -1
- package/dist/client/assets/{Zap-CSBwa9kl.js → Zap--FKeiDFf.js} +1 -1
- package/dist/client/assets/{ZapSquare-B2TPVAEq.js → ZapSquare-CliIuzcs.js} +1 -1
- package/dist/client/assets/{accordion-BtvBKlj9.js → accordion-BBKL1fM-.js} +1 -1
- package/dist/client/assets/{agent-icon-BwpnpUbm.js → agent-icon-CaG-DX2m.js} +1 -1
- package/dist/client/assets/{agents-list-DO7W3l8_.js → agents-list-BUqQO9y3.js} +1 -1
- package/dist/client/assets/ai-providers-BvV5AI1b.js +1 -0
- package/dist/client/assets/{alert-dialog-C-BRVgvu.js → alert-dialog-B-P8jHly.js} +1 -1
- package/dist/client/assets/{auth-catchall-CutI2kmj.js → auth-catchall-CyIMPFaS.js} +1 -1
- package/dist/client/assets/{automation-list-row-DAEvSBmb.js → automation-list-row-Qk3UXtKg.js} +1 -1
- package/dist/client/assets/{automations-CgXPCVHi.js → automations-CkkIdwK3.js} +1 -1
- package/dist/client/assets/{avatar-DMfNBsEa.js → avatar-CYyuZ3vB.js} +1 -1
- package/dist/client/assets/{badge-IDvBfH3R.js → badge-C-R5WeFR.js} +1 -1
- package/dist/client/assets/{brand-context-BJ_Ok-7-.js → brand-context-BqPn2XVA.js} +1 -1
- package/dist/client/assets/{card-CvuzGHjO.js → card-BWjsP1pO.js} +1 -1
- package/dist/client/assets/{chat-context-CErwb6k6.js → chat-context-D7DJNKEQ.js} +1 -1
- package/dist/client/assets/{checkbox-Dl75QnG7.js → checkbox-DRyB8BVf.js} +1 -1
- package/dist/client/assets/{collection-detail-D1GYoMQ-.js → collection-detail-BiG3-7wS.js} +1 -1
- package/dist/client/assets/{collection-display-button-DuQih4HO.js → collection-display-button-D0yyhe94.js} +1 -1
- package/dist/client/assets/{collection-search-FABAZQZ-.js → collection-search-BtC9EgTH.js} +1 -1
- package/dist/client/assets/{collection-search-BbV_T-EE.js → collection-search-CVa4reVh.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-BOjY1N-o.js → collection-table-wrapper-C2Zi2ikn.js} +1 -1
- package/dist/client/assets/{collection-tabs-D9DYouIo.js → collection-tabs-8bicuWoG.js} +1 -1
- package/dist/client/assets/{collections-CWT6-czY.js → collections-ZqRHYd6U.js} +1 -1
- package/dist/client/assets/{command-BcVlajkv.js → command-BUJHwA-d.js} +1 -1
- package/dist/client/assets/{connection-card-5Wnkn35H.js → connection-card-CiNzXirJ.js} +1 -1
- package/dist/client/assets/{connection-detail-9LTY8cEq.js → connection-detail-DQFCqOq5.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-D_o8vWS8.js → connection-form-helpers-BFnOvbFy.js} +1 -1
- package/dist/client/assets/{connections-B0_zSoBW.js → connections-BzqA2cUL.js} +1 -1
- package/dist/client/assets/{constants-Ccic_WNi.js → constants-BmLTAQzq.js} +1 -1
- package/dist/client/assets/{constants-BgsGWL53.js → constants-Df56C9B1.js} +1 -1
- package/dist/client/assets/{dialog-BG4etlBR.js → dialog-HqMwvS0c.js} +1 -1
- package/dist/client/assets/{domain-settings-DrdMk60b.js → domain-settings-8zUtZk7o.js} +1 -1
- package/dist/client/assets/{drawer-Buc4-066.js → drawer-hkToOxOG.js} +1 -1
- package/dist/client/assets/{dropdown-menu-C5QgSZ0t.js → dropdown-menu-CD1YJIi0.js} +1 -1
- package/dist/client/assets/{dynamic-plugin-layout-CaV8IAmp.js → dynamic-plugin-layout--sGvQXk2.js} +1 -1
- package/dist/client/assets/{empty-state-CcdlS-eW.js → empty-state-B29HN9Vl.js} +1 -1
- package/dist/client/assets/{empty-state-CAqrQ-6W.js → empty-state-CElAqeAn.js} +1 -1
- package/dist/client/assets/{extract-connection-data-DbON8nO3.js → extract-connection-data-DYXiFLZH.js} +1 -1
- package/dist/client/assets/{features-ByRqjbyV.js → features-Dvru3uGD.js} +1 -1
- package/dist/client/assets/{form-BbDzJOpZ.js → form-CKajJk24.js} +1 -1
- package/dist/client/assets/{general-e5vvtodI.js → general-D8u2dVV2.js} +1 -1
- package/dist/client/assets/{index-CAEMKqmE.js → index--52kuhAD.js} +1 -1
- package/dist/client/assets/{index-BdxUoNpQ.js → index-BPbckF-i.js} +3 -3
- package/dist/client/assets/{index-C6BloEPE.js → index-BPgW_PVH.js} +1 -1
- package/dist/client/assets/index-BTded5vd.js +1 -0
- package/dist/client/assets/{index-BYF0TDJs.js → index-Boo37gVZ.js} +1 -1
- package/dist/client/assets/{index-17qzAK95.js → index-CHpjwsZ-.js} +1 -1
- package/dist/client/assets/{index-Bt0njY-h.js → index-CMbhqARA.js} +1 -1
- package/dist/client/assets/{index-DDAuFNoU.js → index-CO402MfB.js} +1 -1
- package/dist/client/assets/{index-BZSXOPw-.js → index-CgQG3OxM.js} +1 -1
- package/dist/client/assets/{index-BBwsyhew.js → index-ClxNnAsp.js} +1 -1
- package/dist/client/assets/{index-Bu6OchAc.js → index-CnR4TnGO.js} +1 -1
- package/dist/client/assets/{index-Bo98JLt6.js → index-D7rGFiVq.js} +1 -1
- package/dist/client/assets/{index-B-lZvo-3.js → index-D9-ppQFz.js} +1 -1
- package/dist/client/assets/{index-DwFLYZMx.js → index-DVk4aJ0j.js} +1 -1
- package/dist/client/assets/{index-viV87izi.js → index-Y4klGMPr.js} +1 -1
- package/dist/client/assets/{index-CsPnm66A.js → index-k8njt3_A.js} +2 -2
- package/dist/client/assets/{infiniteQueryObserver-BD3sb9pN.js → infiniteQueryObserver-IG8f9wWg.js} +1 -1
- package/dist/client/assets/{input-BOyPyslv.js → input-DrFzs1Yw.js} +1 -1
- package/dist/client/assets/{integration-icon-BXKm0FXI.js → integration-icon-DUMCOZJc.js} +1 -1
- package/dist/client/assets/{label-C1HjlN95.js → label-0J4Z8Ji8.js} +1 -1
- package/dist/client/assets/{layout-BoLVBNZl.js → layout-zbF9c9kI.js} +1 -1
- package/dist/client/assets/{lean-canvas-recruit-modal-BXaOF7Ji.js → lean-canvas-recruit-modal-D2QgFiqW.js} +1 -1
- package/dist/client/assets/{login-BNbNZ57q.js → login-m1plet6k.js} +1 -1
- package/dist/client/assets/{members-CZREN_th.js → members-DsVQeYYP.js} +1 -1
- package/dist/client/assets/{monaco-editor-3btV5byi.js → monaco-editor-Br1M5lwR.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-TeqbUQfb.js → monitoring-stats-row-BtBHpMXc.js} +1 -1
- package/dist/client/assets/{oauth-callback-CASHqw5B.js → oauth-callback-D6DOFeyW.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-DRX_3ZGd.js → oauth-callback-ai-provider-wUhwntlH.js} +1 -1
- package/dist/client/assets/{onboarding-snq0kuQC.js → onboarding-dml5YruP.js} +1 -1
- package/dist/client/assets/{org-layout-BlsnG8tD.js → org-layout-QSP-N9k0.js} +1 -1
- package/dist/client/assets/{org-plugin-layout-CkIHlyUf.js → org-plugin-layout-ZONr0rlX.js} +1 -1
- package/dist/client/assets/{pair-DoCidCoS.js → pair-mf97TAS_.js} +2 -2
- package/dist/client/assets/{plugin-empty-state-BEExeVzS.js → plugin-empty-state-CFxEUNdF.js} +1 -1
- package/dist/client/assets/{plugin-header-DONB160y.js → plugin-header-HXnwUdYS.js} +1 -1
- package/dist/client/assets/{plugin-layout-LrDjSSJL.js → plugin-layout-ZwMLw5wK.js} +1 -1
- package/dist/client/assets/{popover-DJTDvTFH.js → popover-DUMNq33j.js} +1 -1
- package/dist/client/assets/{profile-DvNhWfFq.js → profile-CyqjRQfg.js} +1 -1
- package/dist/client/assets/{project-app-view-DH36c9up.js → project-app-view-Di4yF5Oz.js} +1 -1
- package/dist/client/assets/registry-DgOCTdY8.js +2 -0
- package/dist/client/assets/{registry-layout-cP1e-tCx.js → registry-layout-B2U_9fgO.js} +1 -1
- package/dist/client/assets/{required-auth-layout-Aj03mUWl.js → required-auth-layout-PH0-_blQ.js} +1 -1
- package/dist/client/assets/{reset-password-DaTq0ZPl.js → reset-password-5ioWEbN5.js} +1 -1
- package/dist/client/assets/{roles-BevJu7Hb.js → roles-4ojRgHgc.js} +1 -1
- package/dist/client/assets/{scroll-area-Dlh0OJL1.js → scroll-area-D_tsHfC-.js} +1 -1
- package/dist/client/assets/{search-input-BbuJZtoW.js → search-input-Boj5tfQn.js} +1 -1
- package/dist/client/assets/{select-BkJAPRFR.js → select-B3lWwv9y.js} +1 -1
- package/dist/client/assets/{select-model-Cx6hCHLC.js → select-model-C-fLwr4k.js} +1 -1
- package/dist/client/assets/{settings-layout-BBbpwWqq.js → settings-layout-U-ZhWkRq.js} +1 -1
- package/dist/client/assets/{settings-section-OhWt9Ooj.js → settings-section-qufbNRCL.js} +1 -1
- package/dist/client/assets/{shell-layout-CwAongAC.js → shell-layout-G8D-0WXl.js} +1 -1
- package/dist/client/assets/{skeleton-BkdIXnLT.js → skeleton-BfKJMKYc.js} +1 -1
- package/dist/client/assets/{sso-BpRBatM1.js → sso-BdojNoX2.js} +1 -1
- package/dist/client/assets/{store-CE6jKSPr.js → store-DGVb_5C1.js} +1 -1
- package/dist/client/assets/store-registry-KlW3QwUJ.js +2 -0
- package/dist/client/assets/{switch-Bipu3FI7.js → switch-YLfAn92x.js} +1 -1
- package/dist/client/assets/{table-Bk_qf725.js → table-wHPRdxYv.js} +1 -1
- package/dist/client/assets/{tabs-BZ0uT4sS.js → tabs-8aX3BTo-.js} +1 -1
- package/dist/client/assets/{task-status-DiRItLYw.js → task-status-CY3ltf_M.js} +1 -1
- package/dist/client/assets/{textarea-BrWSFj_2.js → textarea-BJZt5-vN.js} +1 -1
- package/dist/client/assets/{toggle-group-CG-UehNQ.js → toggle-group-C_B32Tm8.js} +1 -1
- package/dist/client/assets/{tools-list-BRI0XzAw.js → tools-list-bxPeEc0p.js} +1 -1
- package/dist/client/assets/{tooltip-DKSC_TlS.js → tooltip-B26xbtws.js} +1 -1
- package/dist/client/assets/{types-ClrLgxxx.js → types-DfgXo_cD.js} +1 -1
- package/dist/client/assets/{use-ai-providers-DeSA23rL.js → use-ai-providers-CnyJW7s-.js} +1 -1
- package/dist/client/assets/{use-collections-P_xycvTV.js → use-collections-D66SnH5Q.js} +1 -1
- package/dist/client/assets/{use-connection-BPL4_0km.js → use-connection-9VrA1Bg7.js} +1 -1
- package/dist/client/assets/{use-copy-CTq_kAqD.js → use-copy-DpxSUjqd.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-D1V6z6nu.js → use-create-virtual-mcp-DBfs4FWm.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-BN0dAXmt.js → use-debounced-autosave-Ja8PcJv_.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-FPrAaowc.js → use-decopilot-events-DjAxcjIH.js} +1 -1
- package/dist/client/assets/{use-delete-connection-BnyXIIOY.js → use-delete-connection-7Blp6D0s.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-CRwUMH1o.js → use-infinite-scroll-IwyU_OvC.js} +1 -1
- package/dist/client/assets/{use-list-state-41gWh47f.js → use-list-state-Dk2QFrYd.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-BItotVJ3.js → use-mcp-tools-C7yIpDHe.js} +1 -1
- package/dist/client/assets/{use-members-CI97myG6.js → use-members-Bg4ZFsu9.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-CVA2Amec.js → use-navigate-to-agent-BehsrrsA.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-C8ofbFUE.js → use-org-auth-client-mkgKwCAh.js} +1 -1
- package/dist/client/assets/{use-org-sso-BxOse5AC.js → use-org-sso-Xv4QV2bL.js} +1 -1
- package/dist/client/assets/{use-organization-roles-5CJlDHYt.js → use-organization-roles-BmH8DM7C.js} +1 -1
- package/dist/client/assets/{use-organization-settings-DkdX8Pu1.js → use-organization-settings-Coi7Ggqq.js} +1 -1
- package/dist/client/assets/{use-registry-connections-BOLgJOOJ.js → use-registry-connections-_83vUYHS.js} +1 -1
- package/dist/client/assets/{use-status-sounds-C2j9qKjC.js → use-status-sounds-DLYnzZvv.js} +1 -1
- package/dist/client/assets/{use-tasks-B1tiIeuc.js → use-tasks-CUt44N_R.js} +1 -1
- package/dist/client/assets/{use-view-mode-ZXMMFhU_.js → use-view-mode-CZXZPLm6.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-BAEgLpb5.js → use-virtual-mcp-BlYQqAfZ.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-BJ1I2JSf.js +1 -0
- package/dist/client/assets/useSuspenseInfiniteQuery-BpfkmtaB.js +1 -0
- package/dist/client/assets/{user-CHucb2Kt.js → user-BFqIXUgg.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-DR7xk3lS.js → view-mode-toggle-BC7A6oBR.js} +1 -1
- package/dist/client/assets/{workflow-BYv_2auF.js → workflow-B3ajRQIi.js} +1 -1
- package/dist/client/assets/workflow-detail-l83JU-Mp.js +1 -0
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +4 -4
- package/dist/server/node_modules/pg-int8/LICENSE +13 -0
- package/dist/server/node_modules/pg-int8/README.md +16 -0
- package/dist/server/node_modules/pg-int8/index.js +100 -0
- package/dist/server/node_modules/pg-int8/package.json +24 -0
- package/dist/server/node_modules/postgres-array/index.d.ts +4 -0
- package/dist/server/node_modules/postgres-array/index.js +97 -0
- package/dist/server/node_modules/postgres-array/license +21 -0
- package/dist/server/node_modules/postgres-array/package.json +35 -0
- package/dist/server/node_modules/postgres-array/readme.md +43 -0
- package/dist/server/node_modules/postgres-bytea/index.js +33 -0
- package/dist/server/node_modules/postgres-bytea/license +21 -0
- package/dist/server/node_modules/postgres-bytea/package.json +34 -0
- package/dist/server/node_modules/postgres-bytea/readme.md +34 -0
- package/dist/server/node_modules/postgres-date/index.js +116 -0
- package/dist/server/node_modules/postgres-date/license +21 -0
- package/dist/server/node_modules/postgres-date/package.json +33 -0
- package/dist/server/node_modules/postgres-date/readme.md +49 -0
- package/dist/server/node_modules/postgres-interval/index.d.ts +20 -0
- package/dist/server/node_modules/postgres-interval/index.js +125 -0
- package/dist/server/node_modules/postgres-interval/license +21 -0
- package/dist/server/node_modules/postgres-interval/package.json +36 -0
- package/dist/server/node_modules/postgres-interval/readme.md +48 -0
- package/dist/server/node_modules/split2/LICENSE +13 -0
- package/dist/server/node_modules/split2/README.md +85 -0
- package/dist/server/node_modules/split2/bench.js +27 -0
- package/dist/server/node_modules/split2/index.js +141 -0
- package/dist/server/node_modules/split2/package.json +39 -0
- package/dist/server/node_modules/split2/test.js +409 -0
- package/dist/server/server.js +3 -3
- package/package.json +1 -1
- package/dist/client/assets/ai-providers-CHwiNXP4.js +0 -1
- package/dist/client/assets/index-7mXC8lS4.js +0 -1
- package/dist/client/assets/registry-BZEongCI.js +0 -2
- package/dist/client/assets/store-registry-MTXbjb_8.js +0 -2
- package/dist/client/assets/useInfiniteQuery-Y9Nb1sum.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CIGmGEj7.js +0 -1
- package/dist/client/assets/workflow-detail-D3A--f-7.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -1643,7 +1643,7 @@ AS SELECT
|
|
|
1643
1643
|
FROM monitoring_metrics
|
|
1644
1644
|
GROUP BY organization_id, name, bucket, connection_id, tool_name, status
|
|
1645
1645
|
`}),console.log("[clickhouse-schema] monitoring_metrics_rollup_1m_mv view ready")}finally{await G.close()}}catch(Y){console.error("[clickhouse-schema] Failed to create rollup DDL (queries will fall back to raw table):",Y)}}async function cA1(X){let Y={...process.env},G=s$1(X,Y),Q=G.settings.encryptionKey;console.log(`[settings] ENCRYPTION_KEY = ${JSON.stringify(Q)} (${Q.length} chars)`);let{ensureServices:J}=await Promise.resolve().then(() => (u$1(),g$1)),{outputs:W,services:Z}=await J({home:G.settings.dataDir,externalDatabaseUrl:G.externalDatabaseUrl,externalNatsUrl:G.externalNatsUrl});if(!G.skipMigrations){let{migrateBetterAuth:K}=await Promise.resolve().then(() => (XW0(),Qg4));await K(W.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (ZU(),Gg4)),{migrateToLatest:U}=await Promise.resolve().then(() => (Fs4(),Hs4)),B=H(W.databaseUrl);await U({keepOpen:!0,database:B,skipBetterAuth:!0})}if(G.settings.clickhouseUrl){let{ensureClickHouseRollup:K}=await Promise.resolve().then(() => U16);await K(G.settings.clickhouseUrl)}let $={...G.settings,databaseUrl:W.databaseUrl,natsUrls:W.natsUrls};return yt1($),{settings:$,services:Z.map((K)=>({name:K.name==="PostgreSQL"?"Postgres":K.name,port:K.port})),managedServiceNames:Z.filter((K)=>K.owner==="managed").map((K)=>K.name)}}var SN0=w(()=>{bt1();l9()});var nA1={};T0(nA1,{updateService:()=>Ya,toggleViewMode:()=>CN0,toggleVibeState:()=>_N0,toggleLogFlow:()=>vN0,subscribeCliState:()=>CX1,setVibe:()=>et5,setTuiConsoleIntercepted:()=>iA1,setServerUrl:()=>_X1,setMigrationsDone:()=>vX1,setEnv:()=>fX1,setDevMode:()=>ot5,setDataDir:()=>st5,isTuiConsoleIntercepted:()=>pA1,getCliState:()=>kX1,addLogEntry:()=>Wz});function TU(){for(let X of kN0)X()}function kX1(){return e9}function CX1(X){return kN0.add(X),()=>kN0.delete(X)}function Ya(X){e9={...e9,services:e9.services.map((Y)=>Y.name===X.name?X:Y)},TU()}function vX1(){e9={...e9,migrationsStatus:"done"},TU()}function _X1(X){e9={...e9,serverUrl:X},TU()}function fX1(X){e9={...e9,env:X},TU()}function Wz(X){let Y=[...e9.logs,X];e9={...e9,logs:Y.length>500?Y.slice(-500):Y},TU()}function ot5(){e9={...e9,services:[...e9.services,{name:"Vite",status:"pending",port:0}]},TU()}function CN0(){e9={...e9,viewMode:e9.viewMode==="requests"?"config":"requests"},TU()}function vN0(){e9={...e9,logFlow:!e9.logFlow},TU()}function st5(X){e9={...e9,dataDir:X},TU()}function et5(X){e9={...e9,vibe:X},TU()}function _N0(){e9={...e9,vibe:!e9.vibe},TU()}function iA1(X){B16=X}function pA1(){return B16}var e9,kN0,B16=!1;var $z=w(()=>{e9={services:[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}],migrationsStatus:"pending",serverUrl:null,env:null,logs:[],viewMode:"requests",logFlow:!1,vibe:!1,dataDir:null},kN0=new Set});import{createServer as N16}from"net";function Xa5(X){return new Promise((Y)=>{let G=N16();G.once("error",()=>Y(!1)),G.listen(X,"0.0.0.0",()=>{G.close(()=>Y(!0))})})}async function tA1(X){if(await Xa5(X))return X;let Y=await new Promise((G,Q)=>{let J=N16();J.once("error",Q),J.listen(0,"0.0.0.0",()=>{let W=J.address(),Z=typeof W==="object"&&W?W.port:0;J.close(()=>G(Z))})});return console.warn(`Port ${X} is in use, using port ${Y} instead.`),Y}var fN0=()=>{};var bN0={};T0(bN0,{startDevServer:()=>Ga5});import{join as Ya5}from"path";function z16(X){return X.replace(/\x1b\[[0-9;]*m/g,"")}function O16(X){let Y=X.getReader(),G=new TextDecoder,Q="";function J(){let W=Q.split(`
|
|
1646
|
-
`);Q=W.pop()??"";for(let Z of W){let $=z16(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;Wz({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:$})}}(async()=>{for(;;){let{done:W,value:Z}=await Y.read();if(W)break;Q+=G.decode(Z,{stream:!0}),J()}if(Q.trim()){let W=z16(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)Wz({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function Ga5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await tA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await cA1({port:String(J),home:X.home,baseUrl:X.baseUrl,localMode:X.localMode,skipMigrations:X.skipMigrations,noTui:X.noTui,vitePort:X.vitePort});for(let z of Z)Ya({name:z.name,status:"ready",port:z.port});fX1(W),vX1();let K=Ya5(import.meta.dir,"..","..","..","..",".."),H=Q===!0,U=Bun.spawn(["bun","run","--cwd=apps/mesh","dev:servers"],{cwd:K,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.baseUrl?{BASE_URL:W.baseUrl}:{}},stdio:["inherit",H?"inherit":"pipe",H?"inherit":"pipe"]});if(!H)O16(U.stdout),O16(U.stderr);let B=G||`http://localhost:${W.port}`;_X1(B),Ya({name:"Vite",status:"ready",port:Number(Y)});let N=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (u$1(),g$1));await O(W.dataDir)}};return process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM")),{port:Number(W.port),process:U}}var yN0=w(()=>{SN0();$z();fN0()});import{Box as xN0,Text as hN0}from"ink";import{jsx as w16,jsxs as aA1}from"react/jsx-runtime";function D16(X){if(!X)return"not set";try{let Y=new URL(X);if(Y.password)Y.password="***";if(Y.username&&Y.username.length>3)Y.username=Y.username.slice(0,3)+"***";return Y.pathname="/",Y.search="",Y.hash="",Y.toString()}catch{if(X.length<=10)return X;return X.slice(0,6)+"***"+X.slice(-4)}}function Za5(X,Y){if(Qa5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Ja5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>D16(W)).join(", "),color:"cyan"}}let Q=D16(Y);return Q==="not set"?{text:Q,dimColor:!0}:{text:Q,color:"cyan"}}if(Y===void 0||Y===null||Y==="")return{text:"not set",dimColor:!0};let G=String(Y);if(G==="true")return{text:G,color:"green"};if(G==="false")return{text:G,color:"yellow"};try{return new URL(G),{text:G,color:"cyan"}}catch{return{text:G}}}function Wa5(X){return[{title:"Core",entries:[{key:"NODE_ENV",value:X.nodeEnv},{key:"PORT",value:X.port},{key:"BASE_URL",value:X.baseUrl??`http://localhost:${X.port}`},{key:"DATA_DIR",value:X.dataDir}]},{title:"Database",entries:[{key:"DATABASE_URL",value:X.databaseUrl},{key:"DATABASE_PG_SSL",value:X.databasePgSsl}]},{title:"Auth & Secrets",entries:[{key:"BETTER_AUTH_SECRET",value:X.betterAuthSecret},{key:"ENCRYPTION_KEY",value:X.encryptionKey},{key:"MESH_JWT_SECRET",value:X.meshJwtSecret},{key:"STUDIO_PROVISION_SECRET_KEY",value:X.studioProvisionSecretKey},{key:"DISABLE_RATE_LIMIT",value:X.disableRateLimit}]},{title:"Auth Providers",entries:[{key:"AUTH_EMAIL_PASSWORD_ENABLED",value:process.env.AUTH_EMAIL_PASSWORD_ENABLED??"true"},{key:"AUTH_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_GOOGLE_CLIENT_ID},{key:"AUTH_GITHUB_CLIENT_ID",value:!!process.env.AUTH_GITHUB_CLIENT_ID},{key:"AUTH_RESEND_API_KEY",value:!!process.env.AUTH_RESEND_API_KEY},{key:"AUTH_SENDGRID_API_KEY",value:!!process.env.AUTH_SENDGRID_API_KEY},{key:"AUTH_SSO_MS_CLIENT_ID",value:!!process.env.AUTH_SSO_MS_CLIENT_ID},{key:"AUTH_SSO_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_SSO_GOOGLE_CLIENT_ID},{key:"AUTH_MAGIC_LINK_ENABLED",value:process.env.AUTH_MAGIC_LINK_ENABLED==="true"},{key:"AUTH_EMAIL_OTP_ENABLED",value:process.env.AUTH_EMAIL_OTP_ENABLED==="true"}]},{title:"Observability",entries:[{key:"CLICKHOUSE_URL",value:X.clickhouseUrl},{key:"OTEL_SERVICE_NAME",value:X.otelServiceName}]},{title:"Event Bus & Networking",entries:[{key:"NATS_URL",value:X.natsUrls}]},{title:"Config Files",entries:[{key:"CONFIG_PATH",value:X.configPath}]},{title:"AI Gateway",entries:[{key:"DECO_AI_GATEWAY_ENABLED",value:X.aiGatewayEnabled},{key:"DECO_AI_GATEWAY_URL",value:X.aiGatewayUrl}]}]}function L16({env:X}){let Y=Wa5(X);return w16(xN0,{flexDirection:"column",children:Y.map((G)=>aA1(xN0,{flexDirection:"column",marginTop:1,children:[aA1(hN0,{dimColor:!0,children:[" ","\u2500\u2500 ",G.title," ","\u2500".repeat(Math.max(0,38-G.title.length))]}),G.entries.map(({key:Q,value:J})=>{let W=Za5(Q,J);return aA1(xN0,{children:[aA1(hN0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),w16(hN0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Qa5,Ja5;var E16=w(()=>{Qa5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Ja5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var gN0;var P16=w(()=>{gN0={name:"decocms",version:"2.310.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/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@deco-cx/warp-node":"^0.3.20","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","node-pty":"^1.0.0","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as IU,Text as RX}from"ink";import{Spinner as Ka5}from"@inkjs/ui";import{useSyncExternalStore as q16}from"react";import{jsx as TY,jsxs as sQ}from"react/jsx-runtime";function Na5(X,Y){if(!X||!Ba5.has(X))return X;let G=uN0[Y]??uN0[uN0.length-1];return X==="#875f00"?G[0]:G[1]}function A16({status:X}){if(X==="pending")return TY(Ka5,{label:""});return TY(RX,{color:"green",children:"\u2713"})}function T16({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=q16(lm0,um0),Z=q16(nm0,pm0);return sQ(IU,{flexDirection:"column",paddingBottom:1,children:[J?sQ(IU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((N,z)=>N+z.text.length,0),B=Math.max(0,Ua5-U);return sQ(IU,{flexDirection:"row",children:[$.map((N,z)=>{let O=Na5(N.color,K);return O?TY(RX,{color:O,children:N.text},z):TY(RX,{children:N.text},z)}),TY(RX,{children:" ".repeat(B+2)}),H?.map((N,z)=>N.color?TY(RX,{color:N.color,children:N.char},z):TY(RX,{children:N.char},z))]},K)}),sQ(RX,{dimColor:!0,children:[" v",gN0.version]})]}):sQ(IU,{flexDirection:"column",marginTop:1,children:[Ha5.map(($,K)=>TY(RX,{color:Fa5[K],children:$},K)),sQ(RX,{dimColor:!0,children:[" v",gN0.version]})]}),TY(IU,{marginBottom:1,children:TY(RX,{dimColor:!0,children:"\u2500".repeat(80)})}),TY(IU,{children:sQ(RX,{dimColor:!0,children:["Home: ",G]})}),sQ(IU,{gap:2,children:[X.map(($)=>sQ(IU,{gap:1,children:[sQ(RX,{children:[$.name," :",$.port||"...."]}),TY(A16,{status:$.status})]},$.name)),sQ(IU,{gap:1,children:[TY(RX,{children:"Migrations"}),TY(A16,{status:Y})]})]}),TY(IU,{children:Q?sQ(RX,{children:["Open in browser: ",TY(RX,{color:"cyan",children:Q})]}):TY(RX,{dimColor:!0,children:"Starting..."})}),sQ(IU,{gap:2,children:[sQ(RX,{dimColor:!0,children:[TY(RX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),sQ(RX,{dimColor:!0,children:[TY(RX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),sQ(RX,{dimColor:!0,children:[TY(RX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&sQ(RX,{dimColor:!0,children:[TY(RX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Ha5,Fa5,uN0,Ua5=30,Ba5;var I16=w(()=>{P16();It1();kt1();Ha5=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 ","\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588 \u2591 \u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591 \u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 ","\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 "],Fa5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],uN0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Ba5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as za5}from"react";function Oa5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==rA1.rows||Y!==rA1.columns)rA1={rows:X,columns:Y};return rA1}function Da5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function V16(){return za5(Da5,Oa5)}var rA1;var j16=w(()=>{rA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as wa5,Text as bX1}from"ink";import{useSyncExternalStore as La5}from"react";import{jsx as lN0,jsxs as mN0}from"react/jsx-runtime";function Ea5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function M16({logs:X,headerHeight:Y}){let{rows:G}=V16(),{logFlow:Q}=La5(CX1,kX1),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return lN0(wa5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return lN0(bX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return mN0(bX1,{children:[mN0(bX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),lN0(bX1,{color:Ea5(Z.status),children:Z.status}),mN0(bX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var R16=w(()=>{$z();j16()});var dN0={};T0(dN0,{App:()=>ja5});import{Box as Pa5,Text as qa5,useInput as Aa5}from"ink";import{useSyncExternalStore as Ta5}from"react";import{jsx as oA1,jsxs as Ma5}from"react/jsx-runtime";function ja5({home:X}){let Y=Ta5(CX1,kX1);return Aa5((G)=>{if(G==="k"||G==="K")CN0();if(G==="l"||G==="L")vN0();if((G==="v"||G==="V")&&Y.dataDir)ft1(Y.dataDir),_N0();if((G==="n"||G==="N")&&Y.vibe)_t1()}),Ma5(Pa5,{flexDirection:"column",children:[oA1(T16,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?oA1(L16,{env:Y.env}):oA1(qa5,{dimColor:!0,children:"Loading configuration..."}):oA1(M16,{logs:Y.logs,headerHeight:Y.vibe?Va5:Ia5})]})}var Ia5=15,Va5=19;var cN0=w(()=>{E16();I16();R16();$z();fd()});function S16(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,OTEL_EXPORTER_OTLP_ENDPOINT:process.env.OTEL_EXPORTER_OTLP_ENDPOINT,OTEL_EXPORTER_OTLP_PROTOCOL:process.env.OTEL_EXPORTER_OTLP_PROTOCOL,OTEL_RESOURCE_ATTRIBUTES:process.env.OTEL_RESOURCE_ATTRIBUTES,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,STUDIO_SANDBOX_TEMPLATE_NAME:process.env.STUDIO_SANDBOX_TEMPLATE_NAME,STUDIO_ENV:process.env.STUDIO_ENV,STUDIO_SANDBOX_PREVIEW_URL_PATTERN:process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE,STUDIO_SANDBOX_SENTINEL_TOKEN:process.env.STUDIO_SANDBOX_SENTINEL_TOKEN,KUBERNETES_SERVICE_HOST:process.env.KUBERNETES_SERVICE_HOST,KUBERNETES_SERVICE_PORT:process.env.KUBERNETES_SERVICE_PORT,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}var yj=k((_a5)=>{_a5.HttpAuthLocation=void 0;(function(X){X.HEADER="header",X.QUERY="query"})(_a5.HttpAuthLocation||(_a5.HttpAuthLocation={}));_a5.HttpApiKeyAuthLocation=void 0;(function(X){X.HEADER="header",X.QUERY="query"})(_a5.HttpApiKeyAuthLocation||(_a5.HttpApiKeyAuthLocation={}));_a5.EndpointURLScheme=void 0;(function(X){X.HTTP="http",X.HTTPS="https"})(_a5.EndpointURLScheme||(_a5.EndpointURLScheme={}));_a5.AlgorithmId=void 0;(function(X){X.MD5="md5",X.CRC32="crc32",X.CRC32C="crc32c",X.SHA1="sha1",X.SHA256="sha256"})(_a5.AlgorithmId||(_a5.AlgorithmId={}));var Ra5=(X)=>{let Y=[];if(X.sha256!==void 0)Y.push({algorithmId:()=>_a5.AlgorithmId.SHA256,checksumConstructor:()=>X.sha256});if(X.md5!=null)Y.push({algorithmId:()=>_a5.AlgorithmId.MD5,checksumConstructor:()=>X.md5});return{addChecksumAlgorithm(G){Y.push(G)},checksumAlgorithms(){return Y}}},Sa5=(X)=>{let Y={};return X.checksumAlgorithms().forEach((G)=>{Y[G.algorithmId()]=G.checksumConstructor()}),Y},ka5=(X)=>{return Ra5(X)},Ca5=(X)=>{return Sa5(X)};_a5.FieldPosition=void 0;(function(X){X[X.HEADER=0]="HEADER",X[X.TRAILER=1]="TRAILER"})(_a5.FieldPosition||(_a5.FieldPosition={}));var va5="__smithy_context";_a5.IniSectionType=void 0;(function(X){X.PROFILE="profile",X.SSO_SESSION="sso-session",X.SERVICES="services"})(_a5.IniSectionType||(_a5.IniSectionType={}));_a5.RequestHandlerProtocol=void 0;(function(X){X.HTTP_0_9="http/0.9",X.HTTP_1_0="http/1.0",X.TDS_8_0="tds/8.0"})(_a5.RequestHandlerProtocol||(_a5.RequestHandlerProtocol={}));_a5.SMITHY_CONTEXT_KEY=va5;_a5.getDefaultClientConfiguration=ka5;_a5.resolveDefaultRuntimeConfig=Ca5});var u7=k((ma5)=>{var xa5=yj(),ha5=(X)=>{return{setHttpHandler(Y){X.httpHandler=Y},httpHandler(){return X.httpHandler},updateHttpClientConfig(Y,G){X.httpHandler?.updateHttpClientConfig(Y,G)},httpHandlerConfigs(){return X.httpHandler.httpHandlerConfigs()}}},ga5=(X)=>{return{httpHandler:X.httpHandler()}};class k16{name;kind;values;constructor({name:X,kind:Y=xa5.FieldPosition.HEADER,values:G=[]}){this.name=X,this.kind=Y,this.values=G}add(X){this.values.push(X)}set(X){this.values=X}remove(X){this.values=this.values.filter((Y)=>Y!==X)}toString(){return this.values.map((X)=>X.includes(",")||X.includes(" ")?`"${X}"`:X).join(", ")}get(){return this.values}}class C16{entries={};encoding;constructor({fields:X=[],encoding:Y="utf-8"}){X.forEach(this.setField.bind(this)),this.encoding=Y}setField(X){this.entries[X.name.toLowerCase()]=X}getField(X){return this.entries[X.toLowerCase()]}removeField(X){delete this.entries[X.toLowerCase()]}getByType(X){return Object.values(this.entries).filter((Y)=>Y.kind===X)}}class sA1{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(X){this.method=X.method||"GET",this.hostname=X.hostname||"localhost",this.port=X.port,this.query=X.query||{},this.headers=X.headers||{},this.body=X.body,this.protocol=X.protocol?X.protocol.slice(-1)!==":"?`${X.protocol}:`:X.protocol:"https:",this.path=X.path?X.path.charAt(0)!=="/"?`/${X.path}`:X.path:"/",this.username=X.username,this.password=X.password,this.fragment=X.fragment}static clone(X){let Y=new sA1({...X,headers:{...X.headers}});if(Y.query)Y.query=ua5(Y.query);return Y}static isInstance(X){if(!X)return!1;let Y=X;return"method"in Y&&"protocol"in Y&&"hostname"in Y&&"path"in Y&&typeof Y.query==="object"&&typeof Y.headers==="object"}clone(){return sA1.clone(this)}}function ua5(X){return Object.keys(X).reduce((Y,G)=>{let Q=X[G];return{...Y,[G]:Array.isArray(Q)?[...Q]:Q}},{})}class v16{statusCode;reason;headers;body;constructor(X){this.statusCode=X.statusCode,this.reason=X.reason,this.headers=X.headers||{},this.body=X.body}static isInstance(X){if(!X)return!1;let Y=X;return typeof Y.statusCode==="number"&&typeof Y.headers==="object"}}function la5(X){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(X)}ma5.Field=k16;ma5.Fields=C16;ma5.HttpRequest=sA1;ma5.HttpResponse=v16;ma5.getHttpHandlerExtensionConfiguration=ha5;ma5.isValidHostname=la5;ma5.resolveHttpHandlerRuntimeConfig=ga5});function ra5(X){return(Y)=>async(G)=>{let{request:Q}=G;if(X.expectContinueHeader!==!1&&_16.HttpRequest.isInstance(Q)&&Q.body&&X.runtime==="node"&&X.requestHandler?.constructor?.name!=="FetchHttpHandler"){let J=!0;if(typeof X.expectContinueHeader==="number")try{J=(Number(Q.headers?.["content-length"])??X.bodyLengthChecker?.(Q.body)??1/0)>=X.expectContinueHeader}catch(W){}else J=!!X.expectContinueHeader;if(J)Q.headers.Expect="100-continue"}return Y({...G,request:Q})}}var _16,oa5,f16=(X)=>({applyToStack:(Y)=>{Y.add(ra5(X),oa5)}});var b16=w(()=>{_16=X1(u7(),1);oa5={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0}});var wH,eA1,xj,XT1,E9,y16,xX1;var LH=w(()=>{wH={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"},eA1=wH.WHEN_SUPPORTED,xj={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"},XT1=wH.WHEN_SUPPORTED;(function(X){X.MD5="MD5",X.CRC32="CRC32",X.CRC32C="CRC32C",X.CRC64NVME="CRC64NVME",X.SHA1="SHA1",X.SHA256="SHA256"})(E9||(E9={}));(function(X){X.HEADER="header",X.TRAILER="trailer"})(y16||(y16={}));xX1=E9.CRC32});var kq,Ga=(X,Y,G,Q)=>{if(!(Y in X))return;let J=X[Y].toUpperCase();if(!Object.values(G).includes(J))throw TypeError(`Cannot load ${Q} '${Y}'. Expected one of ${Object.values(G)}, got '${X[Y]}'.`);return J};var oN0=w(()=>{(function(X){X.ENV="env",X.CONFIG="shared config entry"})(kq||(kq={}))});var sa5="AWS_REQUEST_CHECKSUM_CALCULATION",ea5="request_checksum_calculation",x16;var h16=w(()=>{LH();oN0();x16={environmentVariableSelector:(X)=>Ga(X,sa5,wH,kq.ENV),configFileSelector:(X)=>Ga(X,ea5,wH,kq.CONFIG),default:eA1}});var Xr5="AWS_RESPONSE_CHECKSUM_VALIDATION",Yr5="response_checksum_validation",g16;var u16=w(()=>{LH();oN0();g16={environmentVariableSelector:(X)=>Ga(X,Xr5,xj,kq.ENV),configFileSelector:(X)=>Ga(X,Yr5,xj,kq.CONFIG),default:XT1}});var eN0=k((Ur5)=>{var Gr5=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],Qr5=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Jr5=["TimeoutError","RequestTimeout","RequestTimeoutException"],Zr5=[500,502,503,504],Wr5=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],$r5=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"],l16=(X)=>X?.$retryable!==void 0,Kr5=(X)=>Gr5.includes(X.name),m16=(X)=>X.$metadata?.clockSkewCorrected,d16=(X)=>{let Y=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(X&&X instanceof TypeError))return!1;return Y.has(X.message)},Hr5=(X)=>X.$metadata?.httpStatusCode===429||Qr5.includes(X.name)||X.$retryable?.throttling==!0,sN0=(X,Y=0)=>l16(X)||m16(X)||X.name==="InvalidSignatureException"&&X.message?.includes("Signature expired")||Jr5.includes(X.name)||Wr5.includes(X?.code||"")||$r5.includes(X?.code||"")||Zr5.includes(X.$metadata?.httpStatusCode||0)||d16(X)||c16(X)||X.cause!==void 0&&Y<=10&&sN0(X.cause,Y+1),Fr5=(X)=>{if(X.$metadata?.httpStatusCode!==void 0){let Y=X.$metadata.httpStatusCode;if(500<=Y&&Y<=599&&!sN0(X))return!0;return!1}return!1};function c16(X){return X.code==="ERR_HTTP2_STREAM_ERROR"&&X.message.includes("NGHTTP2_REFUSED_STREAM")}Ur5.isBrowserNetworkError=d16;Ur5.isClockSkewCorrectedError=m16;Ur5.isClockSkewError=Kr5;Ur5.isNodeJsHttp2TransientError=c16;Ur5.isRetryableByTrait=l16;Ur5.isServerError=Fr5;Ur5.isThrottlingError=Hr5;Ur5.isTransientError=sN0});var Dw=k((Rr5)=>{var Pr5=eN0();Rr5.RETRY_MODES=void 0;(function(X){X.STANDARD="standard",X.ADAPTIVE="adaptive"})(Rr5.RETRY_MODES||(Rr5.RETRY_MODES={}));var GT1=3,qr5=Rr5.RETRY_MODES.STANDARD;class QT1{static setTimeoutFn=setTimeout;beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(X){this.beta=X?.beta??0.7,this.minCapacity=X?.minCapacity??1,this.minFillRate=X?.minFillRate??0.5,this.scaleConstant=X?.scaleConstant??0.4,this.smooth=X?.smooth??0.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(X){let Y;this.updateMeasuredRate();let G=X;if(G?.errorType==="THROTTLING"||Pr5.isThrottlingError(G?.error??X)){let W=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=W,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),Y=this.cubicThrottle(W),this.enableTokenBucket()}else this.calculateTimeWindow(),Y=this.cubicSuccess(this.getCurrentTimeInSeconds());let J=Math.min(Y,2*this.measuredTxRate);this.updateTokenBucketRate(J)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(X){if(!this.enabled)return;if(this.refillTokenBucket(),X>this.availableTokens){let Y=(X-this.availableTokens)/this.fillRate*1000;await new Promise((G)=>QT1.setTimeoutFn(G,Y))}this.availableTokens=this.availableTokens-X}refillTokenBucket(){let X=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=X;return}let Y=(X-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+Y),this.lastTimestamp=X}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(X){return this.getPrecise(X*this.beta)}cubicSuccess(X){return this.getPrecise(this.scaleConstant*Math.pow(X-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(X){this.refillTokenBucket(),this.fillRate=Math.max(X,this.minFillRate),this.maxCapacity=Math.max(X,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let X=this.getCurrentTimeInSeconds(),Y=Math.floor(X*2)/2;if(this.requestCount++,Y>this.lastTxRateBucket){let G=this.requestCount/(Y-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(G*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=Y}}getPrecise(X){return parseFloat(X.toFixed(8))}}var Ar5=100,Gz0=20000,Tr5=500,Xz0=500,Ir5=5,Vr5=10,i16=1,jr5="amz-sdk-invocation-id",Mr5="amz-sdk-request";class eQ{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return eQ.v2026?50:100}static throttlingDelay(){return eQ.v2026?1000:500}static cost(){return eQ.v2026?14:5}static throttlingCost(){return eQ.v2026?5:10}static modifiedCostType(){return eQ.v2026?"THROTTLING":"TRANSIENT"}}class p16{x=eQ.delay();computeNextBackoffDelay(X){let Y=Math.random(),G=2,Q=Y*Math.min(this.x*2**X,Gz0);return Math.floor(Q)}setDelayBase(X){this.x=X}}class Yz0{delay;count;cost;longPoll;constructor(X,Y,G,Q){this.delay=X,this.count=Y,this.cost=G,this.longPoll=Q}getRetryCount(){return this.count}getRetryDelay(){return Math.min(Gz0,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var YT1={incompatible:1,attempts:2,capacity:3};class hX1{mode=Rr5.RETRY_MODES.STANDARD;capacity=Xz0;retryBackoffStrategy;maxAttemptsProvider;baseDelay;constructor(X){if(typeof X==="number")this.maxAttemptsProvider=async()=>X;else if(typeof X==="function")this.maxAttemptsProvider=X;else if(X&&typeof X==="object")this.maxAttemptsProvider=async()=>X.maxAttempts,this.baseDelay=X.baseDelay,this.retryBackoffStrategy=X.backoff;this.maxAttemptsProvider??=async()=>GT1,this.baseDelay??=eQ.delay(),this.retryBackoffStrategy??=new p16}async acquireInitialRetryToken(X){return new Yz0(eQ.delay(),0,void 0,eQ.v2026&&X.includes(":longpoll"))}async refreshRetryTokenForRetry(X,Y){let G=await this.getMaxAttempts(),Q=this.retryCode(X,Y,G),J=Q===0,W=X.isLongPoll?.();if(J||W){let Z=Y.errorType;this.retryBackoffStrategy.setDelayBase(Z==="THROTTLING"?eQ.throttlingDelay():this.baseDelay);let $=this.retryBackoffStrategy.computeNextBackoffDelay(X.getRetryCount()),K=$;if(Y.retryAfterHint instanceof Date)K=Math.max($,Math.min(Y.retryAfterHint.getTime()-Date.now(),$+5000));if(!J)throw Object.assign(Error("No retry token available"),{$backoff:eQ.v2026&&Q===YT1.capacity&&W?K:0});else{let H=this.getCapacityCost(Z);return this.capacity-=H,new Yz0(K,X.getRetryCount()+1,H,X.isLongPoll?.()??!1)}}throw Error("No retry token available")}recordSuccess(X){this.capacity=Math.min(Xz0,this.capacity+(X.getRetryCost()??i16))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(X){return console.warn(`Max attempts provider could not resolve. Using default of ${GT1}`),GT1}}retryCode(X,Y,G){let Q=X.getRetryCount()+1,J=this.isRetryableError(Y.errorType)?0:YT1.incompatible,W=Q<G?0:YT1.attempts,Z=this.capacity>=this.getCapacityCost(Y.errorType)?0:YT1.capacity;return J||W||Z}getCapacityCost(X){return X===eQ.modifiedCostType()?eQ.throttlingCost():eQ.cost()}isRetryableError(X){return X==="THROTTLING"||X==="TRANSIENT"}}class n16{mode=Rr5.RETRY_MODES.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(X,Y){let{rateLimiter:G}=Y??{};this.rateLimiter=G??new QT1,this.standardRetryStrategy=Y?new hX1({maxAttempts:typeof X==="number"?X:3,...Y}):new hX1(X)}async acquireInitialRetryToken(X){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(X)}async refreshRetryTokenForRetry(X,Y){return this.rateLimiter.updateClientSendingRate(Y),this.standardRetryStrategy.refreshRetryTokenForRetry(X,Y)}recordSuccess(X){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(X)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}class t16 extends hX1{computeNextBackoffDelay;constructor(X,Y=eQ.delay()){super(typeof X==="function"?X:async()=>X);if(typeof Y==="number")this.computeNextBackoffDelay=()=>Y;else this.computeNextBackoffDelay=Y}async refreshRetryTokenForRetry(X,Y){let G=await super.refreshRetryTokenForRetry(X,Y);return G.getRetryDelay=()=>this.computeNextBackoffDelay(G.getRetryCount()),G}}Rr5.AdaptiveRetryStrategy=n16;Rr5.ConfiguredRetryStrategy=t16;Rr5.DEFAULT_MAX_ATTEMPTS=GT1;Rr5.DEFAULT_RETRY_DELAY_BASE=Ar5;Rr5.DEFAULT_RETRY_MODE=qr5;Rr5.DefaultRateLimiter=QT1;Rr5.INITIAL_RETRY_TOKENS=Xz0;Rr5.INVOCATION_ID_HEADER=jr5;Rr5.MAXIMUM_RETRY_DELAY=Gz0;Rr5.NO_RETRY_INCREMENT=i16;Rr5.REQUEST_HEADER=Mr5;Rr5.RETRY_COST=Ir5;Rr5.Retry=eQ;Rr5.StandardRetryStrategy=hX1;Rr5.THROTTLING_RETRY_DELAY_BASE=Tr5;Rr5.TIMEOUT_RETRY_COST=Vr5});var WX=k((er5)=>{var ir5=Dw(),Qz0={warningEmitted:!1},pr5=(X)=>{if(X&&!Qz0.warningEmitted&&parseInt(X.substring(1,X.indexOf(".")))<20)Qz0.warningEmitted=!0,process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
|
|
1646
|
+
`);Q=W.pop()??"";for(let Z of W){let $=z16(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;Wz({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:$})}}(async()=>{for(;;){let{done:W,value:Z}=await Y.read();if(W)break;Q+=G.decode(Z,{stream:!0}),J()}if(Q.trim()){let W=z16(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)Wz({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function Ga5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await tA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await cA1({port:String(J),home:X.home,baseUrl:X.baseUrl,localMode:X.localMode,skipMigrations:X.skipMigrations,noTui:X.noTui,vitePort:X.vitePort});for(let z of Z)Ya({name:z.name,status:"ready",port:z.port});fX1(W),vX1();let K=Ya5(import.meta.dir,"..","..","..","..",".."),H=Q===!0,U=Bun.spawn(["bun","run","--cwd=apps/mesh","dev:servers"],{cwd:K,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.baseUrl?{BASE_URL:W.baseUrl}:{}},stdio:["inherit",H?"inherit":"pipe",H?"inherit":"pipe"]});if(!H)O16(U.stdout),O16(U.stderr);let B=G||`http://localhost:${W.port}`;_X1(B),Ya({name:"Vite",status:"ready",port:Number(Y)});let N=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (u$1(),g$1));await O(W.dataDir)}};return process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM")),{port:Number(W.port),process:U}}var yN0=w(()=>{SN0();$z();fN0()});import{Box as xN0,Text as hN0}from"ink";import{jsx as w16,jsxs as aA1}from"react/jsx-runtime";function D16(X){if(!X)return"not set";try{let Y=new URL(X);if(Y.password)Y.password="***";if(Y.username&&Y.username.length>3)Y.username=Y.username.slice(0,3)+"***";return Y.pathname="/",Y.search="",Y.hash="",Y.toString()}catch{if(X.length<=10)return X;return X.slice(0,6)+"***"+X.slice(-4)}}function Za5(X,Y){if(Qa5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Ja5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>D16(W)).join(", "),color:"cyan"}}let Q=D16(Y);return Q==="not set"?{text:Q,dimColor:!0}:{text:Q,color:"cyan"}}if(Y===void 0||Y===null||Y==="")return{text:"not set",dimColor:!0};let G=String(Y);if(G==="true")return{text:G,color:"green"};if(G==="false")return{text:G,color:"yellow"};try{return new URL(G),{text:G,color:"cyan"}}catch{return{text:G}}}function Wa5(X){return[{title:"Core",entries:[{key:"NODE_ENV",value:X.nodeEnv},{key:"PORT",value:X.port},{key:"BASE_URL",value:X.baseUrl??`http://localhost:${X.port}`},{key:"DATA_DIR",value:X.dataDir}]},{title:"Database",entries:[{key:"DATABASE_URL",value:X.databaseUrl},{key:"DATABASE_PG_SSL",value:X.databasePgSsl}]},{title:"Auth & Secrets",entries:[{key:"BETTER_AUTH_SECRET",value:X.betterAuthSecret},{key:"ENCRYPTION_KEY",value:X.encryptionKey},{key:"MESH_JWT_SECRET",value:X.meshJwtSecret},{key:"STUDIO_PROVISION_SECRET_KEY",value:X.studioProvisionSecretKey},{key:"DISABLE_RATE_LIMIT",value:X.disableRateLimit}]},{title:"Auth Providers",entries:[{key:"AUTH_EMAIL_PASSWORD_ENABLED",value:process.env.AUTH_EMAIL_PASSWORD_ENABLED??"true"},{key:"AUTH_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_GOOGLE_CLIENT_ID},{key:"AUTH_GITHUB_CLIENT_ID",value:!!process.env.AUTH_GITHUB_CLIENT_ID},{key:"AUTH_RESEND_API_KEY",value:!!process.env.AUTH_RESEND_API_KEY},{key:"AUTH_SENDGRID_API_KEY",value:!!process.env.AUTH_SENDGRID_API_KEY},{key:"AUTH_SSO_MS_CLIENT_ID",value:!!process.env.AUTH_SSO_MS_CLIENT_ID},{key:"AUTH_SSO_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_SSO_GOOGLE_CLIENT_ID},{key:"AUTH_MAGIC_LINK_ENABLED",value:process.env.AUTH_MAGIC_LINK_ENABLED==="true"},{key:"AUTH_EMAIL_OTP_ENABLED",value:process.env.AUTH_EMAIL_OTP_ENABLED==="true"}]},{title:"Observability",entries:[{key:"CLICKHOUSE_URL",value:X.clickhouseUrl},{key:"OTEL_SERVICE_NAME",value:X.otelServiceName}]},{title:"Event Bus & Networking",entries:[{key:"NATS_URL",value:X.natsUrls}]},{title:"Config Files",entries:[{key:"CONFIG_PATH",value:X.configPath}]},{title:"AI Gateway",entries:[{key:"DECO_AI_GATEWAY_ENABLED",value:X.aiGatewayEnabled},{key:"DECO_AI_GATEWAY_URL",value:X.aiGatewayUrl}]}]}function L16({env:X}){let Y=Wa5(X);return w16(xN0,{flexDirection:"column",children:Y.map((G)=>aA1(xN0,{flexDirection:"column",marginTop:1,children:[aA1(hN0,{dimColor:!0,children:[" ","\u2500\u2500 ",G.title," ","\u2500".repeat(Math.max(0,38-G.title.length))]}),G.entries.map(({key:Q,value:J})=>{let W=Za5(Q,J);return aA1(xN0,{children:[aA1(hN0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),w16(hN0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Qa5,Ja5;var E16=w(()=>{Qa5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Ja5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var gN0;var P16=w(()=>{gN0={name:"decocms",version:"2.310.3",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/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","db:migrate":"bun run ./dist/server/migrate.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts",test:"bun test","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@deco-cx/warp-node":"^0.3.20","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","node-pty":"^1.0.0","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as IU,Text as RX}from"ink";import{Spinner as Ka5}from"@inkjs/ui";import{useSyncExternalStore as q16}from"react";import{jsx as TY,jsxs as sQ}from"react/jsx-runtime";function Na5(X,Y){if(!X||!Ba5.has(X))return X;let G=uN0[Y]??uN0[uN0.length-1];return X==="#875f00"?G[0]:G[1]}function A16({status:X}){if(X==="pending")return TY(Ka5,{label:""});return TY(RX,{color:"green",children:"\u2713"})}function T16({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=q16(lm0,um0),Z=q16(nm0,pm0);return sQ(IU,{flexDirection:"column",paddingBottom:1,children:[J?sQ(IU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((N,z)=>N+z.text.length,0),B=Math.max(0,Ua5-U);return sQ(IU,{flexDirection:"row",children:[$.map((N,z)=>{let O=Na5(N.color,K);return O?TY(RX,{color:O,children:N.text},z):TY(RX,{children:N.text},z)}),TY(RX,{children:" ".repeat(B+2)}),H?.map((N,z)=>N.color?TY(RX,{color:N.color,children:N.char},z):TY(RX,{children:N.char},z))]},K)}),sQ(RX,{dimColor:!0,children:[" v",gN0.version]})]}):sQ(IU,{flexDirection:"column",marginTop:1,children:[Ha5.map(($,K)=>TY(RX,{color:Fa5[K],children:$},K)),sQ(RX,{dimColor:!0,children:[" v",gN0.version]})]}),TY(IU,{marginBottom:1,children:TY(RX,{dimColor:!0,children:"\u2500".repeat(80)})}),TY(IU,{children:sQ(RX,{dimColor:!0,children:["Home: ",G]})}),sQ(IU,{gap:2,children:[X.map(($)=>sQ(IU,{gap:1,children:[sQ(RX,{children:[$.name," :",$.port||"...."]}),TY(A16,{status:$.status})]},$.name)),sQ(IU,{gap:1,children:[TY(RX,{children:"Migrations"}),TY(A16,{status:Y})]})]}),TY(IU,{children:Q?sQ(RX,{children:["Open in browser: ",TY(RX,{color:"cyan",children:Q})]}):TY(RX,{dimColor:!0,children:"Starting..."})}),sQ(IU,{gap:2,children:[sQ(RX,{dimColor:!0,children:[TY(RX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),sQ(RX,{dimColor:!0,children:[TY(RX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),sQ(RX,{dimColor:!0,children:[TY(RX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&sQ(RX,{dimColor:!0,children:[TY(RX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Ha5,Fa5,uN0,Ua5=30,Ba5;var I16=w(()=>{P16();It1();kt1();Ha5=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 ","\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588 \u2591 \u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591 \u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 ","\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 "],Fa5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],uN0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Ba5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as za5}from"react";function Oa5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==rA1.rows||Y!==rA1.columns)rA1={rows:X,columns:Y};return rA1}function Da5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function V16(){return za5(Da5,Oa5)}var rA1;var j16=w(()=>{rA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as wa5,Text as bX1}from"ink";import{useSyncExternalStore as La5}from"react";import{jsx as lN0,jsxs as mN0}from"react/jsx-runtime";function Ea5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function M16({logs:X,headerHeight:Y}){let{rows:G}=V16(),{logFlow:Q}=La5(CX1,kX1),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return lN0(wa5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return lN0(bX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return mN0(bX1,{children:[mN0(bX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),lN0(bX1,{color:Ea5(Z.status),children:Z.status}),mN0(bX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var R16=w(()=>{$z();j16()});var dN0={};T0(dN0,{App:()=>ja5});import{Box as Pa5,Text as qa5,useInput as Aa5}from"ink";import{useSyncExternalStore as Ta5}from"react";import{jsx as oA1,jsxs as Ma5}from"react/jsx-runtime";function ja5({home:X}){let Y=Ta5(CX1,kX1);return Aa5((G)=>{if(G==="k"||G==="K")CN0();if(G==="l"||G==="L")vN0();if((G==="v"||G==="V")&&Y.dataDir)ft1(Y.dataDir),_N0();if((G==="n"||G==="N")&&Y.vibe)_t1()}),Ma5(Pa5,{flexDirection:"column",children:[oA1(T16,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?oA1(L16,{env:Y.env}):oA1(qa5,{dimColor:!0,children:"Loading configuration..."}):oA1(M16,{logs:Y.logs,headerHeight:Y.vibe?Va5:Ia5})]})}var Ia5=15,Va5=19;var cN0=w(()=>{E16();I16();R16();$z();fd()});function S16(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,OTEL_EXPORTER_OTLP_ENDPOINT:process.env.OTEL_EXPORTER_OTLP_ENDPOINT,OTEL_EXPORTER_OTLP_PROTOCOL:process.env.OTEL_EXPORTER_OTLP_PROTOCOL,OTEL_RESOURCE_ATTRIBUTES:process.env.OTEL_RESOURCE_ATTRIBUTES,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,STUDIO_SANDBOX_TEMPLATE_NAME:process.env.STUDIO_SANDBOX_TEMPLATE_NAME,STUDIO_ENV:process.env.STUDIO_ENV,STUDIO_SANDBOX_PREVIEW_URL_PATTERN:process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE,STUDIO_SANDBOX_SENTINEL_TOKEN:process.env.STUDIO_SANDBOX_SENTINEL_TOKEN,KUBERNETES_SERVICE_HOST:process.env.KUBERNETES_SERVICE_HOST,KUBERNETES_SERVICE_PORT:process.env.KUBERNETES_SERVICE_PORT,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}var yj=k((_a5)=>{_a5.HttpAuthLocation=void 0;(function(X){X.HEADER="header",X.QUERY="query"})(_a5.HttpAuthLocation||(_a5.HttpAuthLocation={}));_a5.HttpApiKeyAuthLocation=void 0;(function(X){X.HEADER="header",X.QUERY="query"})(_a5.HttpApiKeyAuthLocation||(_a5.HttpApiKeyAuthLocation={}));_a5.EndpointURLScheme=void 0;(function(X){X.HTTP="http",X.HTTPS="https"})(_a5.EndpointURLScheme||(_a5.EndpointURLScheme={}));_a5.AlgorithmId=void 0;(function(X){X.MD5="md5",X.CRC32="crc32",X.CRC32C="crc32c",X.SHA1="sha1",X.SHA256="sha256"})(_a5.AlgorithmId||(_a5.AlgorithmId={}));var Ra5=(X)=>{let Y=[];if(X.sha256!==void 0)Y.push({algorithmId:()=>_a5.AlgorithmId.SHA256,checksumConstructor:()=>X.sha256});if(X.md5!=null)Y.push({algorithmId:()=>_a5.AlgorithmId.MD5,checksumConstructor:()=>X.md5});return{addChecksumAlgorithm(G){Y.push(G)},checksumAlgorithms(){return Y}}},Sa5=(X)=>{let Y={};return X.checksumAlgorithms().forEach((G)=>{Y[G.algorithmId()]=G.checksumConstructor()}),Y},ka5=(X)=>{return Ra5(X)},Ca5=(X)=>{return Sa5(X)};_a5.FieldPosition=void 0;(function(X){X[X.HEADER=0]="HEADER",X[X.TRAILER=1]="TRAILER"})(_a5.FieldPosition||(_a5.FieldPosition={}));var va5="__smithy_context";_a5.IniSectionType=void 0;(function(X){X.PROFILE="profile",X.SSO_SESSION="sso-session",X.SERVICES="services"})(_a5.IniSectionType||(_a5.IniSectionType={}));_a5.RequestHandlerProtocol=void 0;(function(X){X.HTTP_0_9="http/0.9",X.HTTP_1_0="http/1.0",X.TDS_8_0="tds/8.0"})(_a5.RequestHandlerProtocol||(_a5.RequestHandlerProtocol={}));_a5.SMITHY_CONTEXT_KEY=va5;_a5.getDefaultClientConfiguration=ka5;_a5.resolveDefaultRuntimeConfig=Ca5});var u7=k((ma5)=>{var xa5=yj(),ha5=(X)=>{return{setHttpHandler(Y){X.httpHandler=Y},httpHandler(){return X.httpHandler},updateHttpClientConfig(Y,G){X.httpHandler?.updateHttpClientConfig(Y,G)},httpHandlerConfigs(){return X.httpHandler.httpHandlerConfigs()}}},ga5=(X)=>{return{httpHandler:X.httpHandler()}};class k16{name;kind;values;constructor({name:X,kind:Y=xa5.FieldPosition.HEADER,values:G=[]}){this.name=X,this.kind=Y,this.values=G}add(X){this.values.push(X)}set(X){this.values=X}remove(X){this.values=this.values.filter((Y)=>Y!==X)}toString(){return this.values.map((X)=>X.includes(",")||X.includes(" ")?`"${X}"`:X).join(", ")}get(){return this.values}}class C16{entries={};encoding;constructor({fields:X=[],encoding:Y="utf-8"}){X.forEach(this.setField.bind(this)),this.encoding=Y}setField(X){this.entries[X.name.toLowerCase()]=X}getField(X){return this.entries[X.toLowerCase()]}removeField(X){delete this.entries[X.toLowerCase()]}getByType(X){return Object.values(this.entries).filter((Y)=>Y.kind===X)}}class sA1{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(X){this.method=X.method||"GET",this.hostname=X.hostname||"localhost",this.port=X.port,this.query=X.query||{},this.headers=X.headers||{},this.body=X.body,this.protocol=X.protocol?X.protocol.slice(-1)!==":"?`${X.protocol}:`:X.protocol:"https:",this.path=X.path?X.path.charAt(0)!=="/"?`/${X.path}`:X.path:"/",this.username=X.username,this.password=X.password,this.fragment=X.fragment}static clone(X){let Y=new sA1({...X,headers:{...X.headers}});if(Y.query)Y.query=ua5(Y.query);return Y}static isInstance(X){if(!X)return!1;let Y=X;return"method"in Y&&"protocol"in Y&&"hostname"in Y&&"path"in Y&&typeof Y.query==="object"&&typeof Y.headers==="object"}clone(){return sA1.clone(this)}}function ua5(X){return Object.keys(X).reduce((Y,G)=>{let Q=X[G];return{...Y,[G]:Array.isArray(Q)?[...Q]:Q}},{})}class v16{statusCode;reason;headers;body;constructor(X){this.statusCode=X.statusCode,this.reason=X.reason,this.headers=X.headers||{},this.body=X.body}static isInstance(X){if(!X)return!1;let Y=X;return typeof Y.statusCode==="number"&&typeof Y.headers==="object"}}function la5(X){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(X)}ma5.Field=k16;ma5.Fields=C16;ma5.HttpRequest=sA1;ma5.HttpResponse=v16;ma5.getHttpHandlerExtensionConfiguration=ha5;ma5.isValidHostname=la5;ma5.resolveHttpHandlerRuntimeConfig=ga5});function ra5(X){return(Y)=>async(G)=>{let{request:Q}=G;if(X.expectContinueHeader!==!1&&_16.HttpRequest.isInstance(Q)&&Q.body&&X.runtime==="node"&&X.requestHandler?.constructor?.name!=="FetchHttpHandler"){let J=!0;if(typeof X.expectContinueHeader==="number")try{J=(Number(Q.headers?.["content-length"])??X.bodyLengthChecker?.(Q.body)??1/0)>=X.expectContinueHeader}catch(W){}else J=!!X.expectContinueHeader;if(J)Q.headers.Expect="100-continue"}return Y({...G,request:Q})}}var _16,oa5,f16=(X)=>({applyToStack:(Y)=>{Y.add(ra5(X),oa5)}});var b16=w(()=>{_16=X1(u7(),1);oa5={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0}});var wH,eA1,xj,XT1,E9,y16,xX1;var LH=w(()=>{wH={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"},eA1=wH.WHEN_SUPPORTED,xj={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"},XT1=wH.WHEN_SUPPORTED;(function(X){X.MD5="MD5",X.CRC32="CRC32",X.CRC32C="CRC32C",X.CRC64NVME="CRC64NVME",X.SHA1="SHA1",X.SHA256="SHA256"})(E9||(E9={}));(function(X){X.HEADER="header",X.TRAILER="trailer"})(y16||(y16={}));xX1=E9.CRC32});var kq,Ga=(X,Y,G,Q)=>{if(!(Y in X))return;let J=X[Y].toUpperCase();if(!Object.values(G).includes(J))throw TypeError(`Cannot load ${Q} '${Y}'. Expected one of ${Object.values(G)}, got '${X[Y]}'.`);return J};var oN0=w(()=>{(function(X){X.ENV="env",X.CONFIG="shared config entry"})(kq||(kq={}))});var sa5="AWS_REQUEST_CHECKSUM_CALCULATION",ea5="request_checksum_calculation",x16;var h16=w(()=>{LH();oN0();x16={environmentVariableSelector:(X)=>Ga(X,sa5,wH,kq.ENV),configFileSelector:(X)=>Ga(X,ea5,wH,kq.CONFIG),default:eA1}});var Xr5="AWS_RESPONSE_CHECKSUM_VALIDATION",Yr5="response_checksum_validation",g16;var u16=w(()=>{LH();oN0();g16={environmentVariableSelector:(X)=>Ga(X,Xr5,xj,kq.ENV),configFileSelector:(X)=>Ga(X,Yr5,xj,kq.CONFIG),default:XT1}});var eN0=k((Ur5)=>{var Gr5=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],Qr5=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],Jr5=["TimeoutError","RequestTimeout","RequestTimeoutException"],Zr5=[500,502,503,504],Wr5=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],$r5=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"],l16=(X)=>X?.$retryable!==void 0,Kr5=(X)=>Gr5.includes(X.name),m16=(X)=>X.$metadata?.clockSkewCorrected,d16=(X)=>{let Y=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(X&&X instanceof TypeError))return!1;return Y.has(X.message)},Hr5=(X)=>X.$metadata?.httpStatusCode===429||Qr5.includes(X.name)||X.$retryable?.throttling==!0,sN0=(X,Y=0)=>l16(X)||m16(X)||X.name==="InvalidSignatureException"&&X.message?.includes("Signature expired")||Jr5.includes(X.name)||Wr5.includes(X?.code||"")||$r5.includes(X?.code||"")||Zr5.includes(X.$metadata?.httpStatusCode||0)||d16(X)||c16(X)||X.cause!==void 0&&Y<=10&&sN0(X.cause,Y+1),Fr5=(X)=>{if(X.$metadata?.httpStatusCode!==void 0){let Y=X.$metadata.httpStatusCode;if(500<=Y&&Y<=599&&!sN0(X))return!0;return!1}return!1};function c16(X){return X.code==="ERR_HTTP2_STREAM_ERROR"&&X.message.includes("NGHTTP2_REFUSED_STREAM")}Ur5.isBrowserNetworkError=d16;Ur5.isClockSkewCorrectedError=m16;Ur5.isClockSkewError=Kr5;Ur5.isNodeJsHttp2TransientError=c16;Ur5.isRetryableByTrait=l16;Ur5.isServerError=Fr5;Ur5.isThrottlingError=Hr5;Ur5.isTransientError=sN0});var Dw=k((Rr5)=>{var Pr5=eN0();Rr5.RETRY_MODES=void 0;(function(X){X.STANDARD="standard",X.ADAPTIVE="adaptive"})(Rr5.RETRY_MODES||(Rr5.RETRY_MODES={}));var GT1=3,qr5=Rr5.RETRY_MODES.STANDARD;class QT1{static setTimeoutFn=setTimeout;beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(X){this.beta=X?.beta??0.7,this.minCapacity=X?.minCapacity??1,this.minFillRate=X?.minFillRate??0.5,this.scaleConstant=X?.scaleConstant??0.4,this.smooth=X?.smooth??0.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(X){let Y;this.updateMeasuredRate();let G=X;if(G?.errorType==="THROTTLING"||Pr5.isThrottlingError(G?.error??X)){let W=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=W,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),Y=this.cubicThrottle(W),this.enableTokenBucket()}else this.calculateTimeWindow(),Y=this.cubicSuccess(this.getCurrentTimeInSeconds());let J=Math.min(Y,2*this.measuredTxRate);this.updateTokenBucketRate(J)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(X){if(!this.enabled)return;if(this.refillTokenBucket(),X>this.availableTokens){let Y=(X-this.availableTokens)/this.fillRate*1000;await new Promise((G)=>QT1.setTimeoutFn(G,Y))}this.availableTokens=this.availableTokens-X}refillTokenBucket(){let X=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=X;return}let Y=(X-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+Y),this.lastTimestamp=X}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(X){return this.getPrecise(X*this.beta)}cubicSuccess(X){return this.getPrecise(this.scaleConstant*Math.pow(X-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(X){this.refillTokenBucket(),this.fillRate=Math.max(X,this.minFillRate),this.maxCapacity=Math.max(X,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let X=this.getCurrentTimeInSeconds(),Y=Math.floor(X*2)/2;if(this.requestCount++,Y>this.lastTxRateBucket){let G=this.requestCount/(Y-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(G*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=Y}}getPrecise(X){return parseFloat(X.toFixed(8))}}var Ar5=100,Gz0=20000,Tr5=500,Xz0=500,Ir5=5,Vr5=10,i16=1,jr5="amz-sdk-invocation-id",Mr5="amz-sdk-request";class eQ{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return eQ.v2026?50:100}static throttlingDelay(){return eQ.v2026?1000:500}static cost(){return eQ.v2026?14:5}static throttlingCost(){return eQ.v2026?5:10}static modifiedCostType(){return eQ.v2026?"THROTTLING":"TRANSIENT"}}class p16{x=eQ.delay();computeNextBackoffDelay(X){let Y=Math.random(),G=2,Q=Y*Math.min(this.x*2**X,Gz0);return Math.floor(Q)}setDelayBase(X){this.x=X}}class Yz0{delay;count;cost;longPoll;constructor(X,Y,G,Q){this.delay=X,this.count=Y,this.cost=G,this.longPoll=Q}getRetryCount(){return this.count}getRetryDelay(){return Math.min(Gz0,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var YT1={incompatible:1,attempts:2,capacity:3};class hX1{mode=Rr5.RETRY_MODES.STANDARD;capacity=Xz0;retryBackoffStrategy;maxAttemptsProvider;baseDelay;constructor(X){if(typeof X==="number")this.maxAttemptsProvider=async()=>X;else if(typeof X==="function")this.maxAttemptsProvider=X;else if(X&&typeof X==="object")this.maxAttemptsProvider=async()=>X.maxAttempts,this.baseDelay=X.baseDelay,this.retryBackoffStrategy=X.backoff;this.maxAttemptsProvider??=async()=>GT1,this.baseDelay??=eQ.delay(),this.retryBackoffStrategy??=new p16}async acquireInitialRetryToken(X){return new Yz0(eQ.delay(),0,void 0,eQ.v2026&&X.includes(":longpoll"))}async refreshRetryTokenForRetry(X,Y){let G=await this.getMaxAttempts(),Q=this.retryCode(X,Y,G),J=Q===0,W=X.isLongPoll?.();if(J||W){let Z=Y.errorType;this.retryBackoffStrategy.setDelayBase(Z==="THROTTLING"?eQ.throttlingDelay():this.baseDelay);let $=this.retryBackoffStrategy.computeNextBackoffDelay(X.getRetryCount()),K=$;if(Y.retryAfterHint instanceof Date)K=Math.max($,Math.min(Y.retryAfterHint.getTime()-Date.now(),$+5000));if(!J)throw Object.assign(Error("No retry token available"),{$backoff:eQ.v2026&&Q===YT1.capacity&&W?K:0});else{let H=this.getCapacityCost(Z);return this.capacity-=H,new Yz0(K,X.getRetryCount()+1,H,X.isLongPoll?.()??!1)}}throw Error("No retry token available")}recordSuccess(X){this.capacity=Math.min(Xz0,this.capacity+(X.getRetryCost()??i16))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(X){return console.warn(`Max attempts provider could not resolve. Using default of ${GT1}`),GT1}}retryCode(X,Y,G){let Q=X.getRetryCount()+1,J=this.isRetryableError(Y.errorType)?0:YT1.incompatible,W=Q<G?0:YT1.attempts,Z=this.capacity>=this.getCapacityCost(Y.errorType)?0:YT1.capacity;return J||W||Z}getCapacityCost(X){return X===eQ.modifiedCostType()?eQ.throttlingCost():eQ.cost()}isRetryableError(X){return X==="THROTTLING"||X==="TRANSIENT"}}class n16{mode=Rr5.RETRY_MODES.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(X,Y){let{rateLimiter:G}=Y??{};this.rateLimiter=G??new QT1,this.standardRetryStrategy=Y?new hX1({maxAttempts:typeof X==="number"?X:3,...Y}):new hX1(X)}async acquireInitialRetryToken(X){return await this.rateLimiter.getSendToken(),this.standardRetryStrategy.acquireInitialRetryToken(X)}async refreshRetryTokenForRetry(X,Y){return this.rateLimiter.updateClientSendingRate(Y),this.standardRetryStrategy.refreshRetryTokenForRetry(X,Y)}recordSuccess(X){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(X)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}class t16 extends hX1{computeNextBackoffDelay;constructor(X,Y=eQ.delay()){super(typeof X==="function"?X:async()=>X);if(typeof Y==="number")this.computeNextBackoffDelay=()=>Y;else this.computeNextBackoffDelay=Y}async refreshRetryTokenForRetry(X,Y){let G=await super.refreshRetryTokenForRetry(X,Y);return G.getRetryDelay=()=>this.computeNextBackoffDelay(G.getRetryCount()),G}}Rr5.AdaptiveRetryStrategy=n16;Rr5.ConfiguredRetryStrategy=t16;Rr5.DEFAULT_MAX_ATTEMPTS=GT1;Rr5.DEFAULT_RETRY_DELAY_BASE=Ar5;Rr5.DEFAULT_RETRY_MODE=qr5;Rr5.DefaultRateLimiter=QT1;Rr5.INITIAL_RETRY_TOKENS=Xz0;Rr5.INVOCATION_ID_HEADER=jr5;Rr5.MAXIMUM_RETRY_DELAY=Gz0;Rr5.NO_RETRY_INCREMENT=i16;Rr5.REQUEST_HEADER=Mr5;Rr5.RETRY_COST=Ir5;Rr5.Retry=eQ;Rr5.StandardRetryStrategy=hX1;Rr5.THROTTLING_RETRY_DELAY_BASE=Tr5;Rr5.TIMEOUT_RETRY_COST=Vr5});var WX=k((er5)=>{var ir5=Dw(),Qz0={warningEmitted:!1},pr5=(X)=>{if(X&&!Qz0.warningEmitted&&parseInt(X.substring(1,X.indexOf(".")))<20)Qz0.warningEmitted=!0,process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will
|
|
1647
1647
|
no longer support Node.js ${X} in January 2026.
|
|
1648
1648
|
|
|
1649
1649
|
To continue receiving updates to AWS services, bug fixes, and security
|
|
@@ -7145,7 +7145,7 @@ Caused by: ${Y.stack}`}};tm=class tm extends sY{constructor(X,Y){super(X,Y);this
|
|
|
7145
7145
|
ORDER BY d.created_at ASC
|
|
7146
7146
|
LIMIT ${X}
|
|
7147
7147
|
FOR UPDATE OF d SKIP LOCKED
|
|
7148
|
-
)`).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id);if(Q.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Q).where("d.status","=","processing").execute()).map((W)=>({delivery:{id:W.delivery_id,eventId:W.event_id,subscriptionId:W.subscription_id,status:W.delivery_status,attempts:W.delivery_attempts,lastError:W.delivery_last_error,deliveredAt:W.delivered_at,nextRetryAt:W.delivery_next_retry_at,createdAt:W.delivery_created_at},event:{id:W.event_id,organizationId:W.organization_id,type:W.type,source:W.source,specversion:W.specversion,subject:W.subject,time:W.time,datacontenttype:W.datacontenttype,dataschema:W.dataschema,data:W.data?JSON.parse(W.data):null,cron:W.cron,status:W.event_status,attempts:W.event_attempts,lastError:W.event_last_error,nextRetryAt:W.next_retry_at,createdAt:W.event_created_at,updatedAt:W.event_updated_at},subscription:{id:W.subscription_id,organizationId:W.organization_id,connectionId:W.connection_id,publisher:W.publisher,eventType:W.event_type,filter:W.filter,enabled:Boolean(W.enabled),createdAt:W.subscription_created_at,updatedAt:W.subscription_updated_at}}))}async markDeliveriesDelivered(X){if(X.length===0)return;let Y=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Y}).where("id","in",X).execute()}async markDeliveriesPermanentlyFailed(X,Y){if(X.length===0)return;await this.db.updateTable("event_deliveries").set({status:"failed",last_error:Y,next_retry_at:null}).where("id","in",X).execute()}async markDeliveriesFailed(X,Y,G=20,Q=1000,J=3600000){if(X.length===0)return;for(let W of X){let Z=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!Z)continue;let $=Z.attempts+1;if($>=G)await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let K=Math.min(Q*Math.pow(2,$-1),J),H=new Date(Date.now()+K).toISOString();await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(X){let Y=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",X).execute();if(Y.length===0)return;let G=Y.every((W)=>W.status==="delivered"),Q=Y.some((W)=>W.status==="failed"),J=Y.some((W)=>W.status==="pending"||W.status==="processing");if(G)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",X).execute();else if(Q&&!J)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",X).execute()}async resetStuckDeliveries(){if((await B1`SELECT pg_try_advisory_lock(hashtext('event_bus_reset_stuck')) as locked`.execute(this.db)).rows[0]?.locked!==!0)return 0;try{let G=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(G.numUpdatedRows??0)}finally{await B1`SELECT pg_advisory_unlock(hashtext('event_bus_reset_stuck'))`.execute(this.db)}}async getEvent(X,Y){let G=await this.db.selectFrom("events").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async findActiveCronEvent(X,Y,G,Q){let J=await this.db.selectFrom("events").selectAll().where("organization_id","=",X).where("type","=",Y).where("source","=",G).where("cron","=",Q).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!J)return null;return{id:J.id,organizationId:J.organization_id,type:J.type,source:J.source,specversion:J.specversion,subject:J.subject,time:J.time,datacontenttype:J.datacontenttype,dataschema:J.dataschema,data:J.data?JSON.parse(J.data):null,cron:J.cron,status:J.status,attempts:J.attempts,lastError:J.last_error,nextRetryAt:J.next_retry_at,createdAt:J.created_at,updatedAt:J.updated_at}}async findOrphanedCronEvents(){return(await this.db.selectFrom("events").selectAll().where("cron","is not",null).where("status","=","delivered").where((Y)=>Y.not(Y.exists(Y.selectFrom("event_deliveries").select("id").whereRef("event_deliveries.event_id","=","events.id").where("event_deliveries.status","in",["pending","processing"])))).execute()).map((Y)=>({id:Y.id,organizationId:Y.organization_id,type:Y.type,source:Y.source,specversion:Y.specversion,subject:Y.subject,time:Y.time,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema,data:Y.data?JSON.parse(Y.data):null,cron:Y.cron,status:Y.status,attempts:Y.attempts,lastError:Y.last_error,nextRetryAt:Y.next_retry_at,createdAt:Y.created_at,updatedAt:Y.updated_at}))}async cancelEvent(X,Y,G){let Q=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",X).where("organization_id","=",Y).where("source","=",G).where("status","in",["pending","processing"]).executeTakeFirst();if((Q.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",X).where("status","in",["pending","processing"]).execute();return{success:(Q.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(X,Y){if(X.length===0)return;let G=new Date(Date.now()+Y).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:G}).where("id","in",X).execute()}async ackDelivery(X,Y,G){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",X).where("organization_id","=",Y).executeTakeFirst())return{success:!1};let W=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",X).where("status","in",["pending","processing"]).where((Z)=>Z.exists(Z.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",G).where("event_subscriptions.organization_id","=",Y))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(X);return{success:W}}async syncSubscriptions(X){let{organizationId:Y,connectionId:G,subscriptions:Q}=X,J=(P,q)=>{return`${P}::${q??""}`},W=await this.listSubscriptions(Y,G),Z=new Map;for(let P of W)Z.set(J(P.eventType,P.publisher),P);let $=new Map;for(let P of Q)$.set(J(P.eventType,P.publisher),P);let K=new Date().toISOString(),H=[],U=[],B=[],N=0;for(let[P,q]of $){let j=Z.get(P);if(!j)H.push({id:crypto.randomUUID(),organization_id:Y,connection_id:G,event_type:q.eventType,publisher:q.publisher??null,filter:q.filter??null,enabled:!0,created_at:K,updated_at:K});else{let M=j.filter??null,I=q.filter??null;if(M!==I)U.push({id:j.id,filter:I});else N++}}for(let[P,q]of Z)if(!$.has(P))B.push(q.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(U.length>0)await Promise.all(U.map((P)=>this.db.updateTable("event_subscriptions").set({filter:P.filter,updated_at:K}).where("id","=",P.id).execute()));if(B.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",B).execute();let z=H.length,O=U.length,D=B.length,E=await this.listSubscriptions(Y,G);return{created:z,updated:O,deleted:D,unchanged:N,subscriptions:E}}}function YW8(X){return new XW8(X)}var GW8=w(()=>{B6()});class QW8{listeners=new Map;totalCount=0;strategy=null;started=!1;async start(X){if(this.started){if(!X)return;await this.stop()}this.strategy=X,await this.strategy.start((Y,G)=>this.localEmit(Y,G)),this.started=!0}async stop(){if(!this.started||!this.strategy)return;await this.strategy.stop(),this.started=!1}add(X){if(this.totalCount>=500)return console.warn("[SSEHub] Total connection limit reached (500)"),null;let Y=this.listeners.get(X.organizationId);if(!Y)Y=new Map,this.listeners.set(X.organizationId,Y);if(Y.size>=50)return console.warn(`[SSEHub] Per-org connection limit reached for ${X.organizationId} (50)`),null;return Y.set(X.id,X),this.totalCount++,X.id}remove(X,Y){let G=this.listeners.get(X);if(!G)return;if(G.delete(Y)){if(this.totalCount--,G.size===0)this.listeners.delete(X)}}emit(X,Y){if(this.strategy)this.strategy.broadcast(X,Y);else this.localEmit(X,Y)}countForOrg(X){return this.listeners.get(X)?.size??0}get count(){return this.totalCount}localEmit(X,Y){let G=this.listeners.get(X);if(!G||G.size===0)return;for(let Q of G.values()){if(Q.typePatterns&&!U$7(Y.type,Q.typePatterns))continue;try{Q.push(Y)}catch{this.remove(X,Q.id)}}}}function U$7(X,Y){for(let G of Y){if(G===X)return!0;if(G.endsWith(".*")){let Q=G.slice(0,-1);if(X.startsWith(Q))return!0}}return!1}function JW8(X){return{id:X.id,type:X.type,source:X.source,subject:X.subject,data:X.data?B$7(X.data):void 0,time:X.time}}function B$7(X){if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X}var zK;var Mi1=w(()=>{zK=new QW8});function ZW8(X){if(typeof X==="object"&&X!==null){let Q=X,J=Q.status??Q.code;if(typeof J==="number"&&N$7.has(J))return!0}let Y=X instanceof Error?X.message:typeof X==="string"?X:"";if(!Y)return!1;let G=Y.toLowerCase();if(/\b401\b/.test(G))return!0;return z$7.some((Q)=>G.includes(Q))}function WW8(X){let Y=X instanceof Error?X.message:typeof X==="string"?X:"";if(!Y)return!1;let G=Y.toLowerCase();return O$7.some((Q)=>G.includes(Q))}var N$7,z$7,O$7,LW1;var vx0=w(()=>{N$7=new Set([401]),z$7=["unauthorized","invalid_token","invalid api key","api key required","api-key required"],O$7=["tool on_events not found","tool not found"];LW1=class LW1 extends Error{constructor(X){super(X);this.name="PermanentDeliveryError"}}});var Ri1;var _x0=w(()=>{Ri1={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function D$7(X){return X.endsWith("_self")}function w$7(X){return X.slice(0,-5)}function $W8(){return async(X,Y)=>{try{if(D$7(X)){let Z=w$7(X),$=await GB.create(),K={organizationId:Z,connectionId:X,publish:async(B,N,z,O)=>{await $.eventBus.publish(Z,X,{type:B,subject:N,data:z,deliverAt:O?.deliverAt})},createMCPProxy:async(B)=>{let N={...$,getOrCreateClient:Co()},z=await sM0(B,N);return{callTool:async(O,D,E)=>{let P=await z.callTool(O,D,E);return{content:P.content,structuredContent:P.structuredContent,isError:P.isError}},close:()=>z.close()}}},H=Y.filter((B)=>B.type==="registry.monitor.scheduled");if(H.length>0){let{parseMonitorConfig:B}=await Promise.resolve().then(() => (aH(),bn6)),N=await K.createMCPProxy(X);try{for(let z of H){let O=z.data&&typeof z.data==="object"?z.data:{},D=O.config&&typeof O.config==="object"?O.config:{},E=B(D);await N.callTool({name:"REGISTRY_MONITOR_RUN_START",arguments:{config:E}})}}finally{await N.close()}if(H.length===Y.length)return{success:!0}}if(await eo4(Y,K))return{success:!0}}let G=await GB.create(),Q=await sM0(X,G),W=await Tj0.forClient(CJ1(Q)).ON_EVENTS({events:Y});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(G){let Q=G instanceof Error?G.message:String(G);if(console.error(`[EventBus] Failed to notify connection ${X}:`,Q),ZW8(G)||WW8(G))throw new LW1(Q);return{success:!1,error:Q}}}}var KW8=w(()=>{xZ1();pt();dR1();LQ1();gR1();vx0()});function HW8(X){return{specversion:"1.0",id:X.id,source:X.source,type:X.type,time:X.time,subject:X.subject??void 0,datacontenttype:X.datacontenttype,dataschema:X.dataschema??void 0,data:X.data??void 0}}function L$7(X){let Y=new Map;for(let Q of X){let J=Q.subscription.connectionId,W=Y.get(J);if(W){if(W.deliveryIds.push(Q.delivery.id),!W.seenEventIds.has(Q.event.id))W.seenEventIds.add(Q.event.id),W.events.push(HW8(Q.event))}else Y.set(J,{connectionId:Q.subscription.connectionId,deliveryIds:[Q.delivery.id],events:[HW8(Q.event)],seenEventIds:new Set([Q.event.id])})}let G=new Map;for(let[Q,J]of Y)G.set(Q,{connectionId:J.connectionId,deliveryIds:J.deliveryIds,events:J.events});return G}class fx0{storage;notifySubscriber;running=!1;processing=!1;pendingNotify=!1;config;eventTriggerEngine;constructor(X,Y,G){this.storage=X;this.notifySubscriber=G??$W8(),this.config={...Ri1,...Y}}setEventTriggerEngine(X){this.eventTriggerEngine=X}async start(){if(this.running)return;await this.storage.resetStuckDeliveries();let X=await this.storage.findOrphanedCronEvents();for(let Y of X)await this.scheduleNextCronDelivery(Y);this.running=!0}stop(){this.running=!1}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing){this.pendingNotify=!0;return}this.processing=!0;try{do this.pendingNotify=!1,await this.processEvents();while(this.pendingNotify)}catch(X){console.error("[EventBus] Error processing events:",X)}finally{this.processing=!1}}async processEvents(){let X=await this.storage.claimPendingDeliveries(this.config.batchSize);if(X.length===0)return;let Y=L$7(X),G=await Promise.allSettled(Array.from(Y.entries()).map(async([W,Z])=>{let $=new Set;try{let H=await this.notifySubscriber(Z.connectionId,Z.events);if(H.results&&Object.keys(H.results).length>0)await this.processPerEventResults(Z,H);else if(H.success)await this.storage.markDeliveriesDelivered(Z.deliveryIds);else if(H.retryAfter&&H.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(Z.deliveryIds,H.retryAfter);else await this.storage.markDeliveriesFailed(Z.deliveryIds,H.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(H){if(H instanceof LW1){await this.storage.markDeliveriesPermanentlyFailed(Z.deliveryIds,H.message);for(let U of Z.events)$.add(U.id)}else{let U=H instanceof Error?H.message:String(H);console.error(`[EventBus] Failed to notify subscription ${W}:`,U),await this.storage.markDeliveriesFailed(Z.deliveryIds,U,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}let K=new Set;for(let H of X)if(Z.deliveryIds.includes(H.delivery.id))K.add(H.event.id);return{eventIds:K,permanentlyFailed:$}})),Q=new Set,J=new Set;for(let W of G)if(W.status==="fulfilled"){for(let Z of W.value.eventIds)Q.add(Z);for(let Z of W.value.permanentlyFailed)J.add(Z)}for(let W of Q)try{await this.storage.updateEventStatus(W);let Z=X.find(($)=>$.event.id===W)?.event;if(Z?.cron&&!J.has(W))await this.scheduleNextCronDelivery(Z)}catch(Z){console.error(`[EventBus] Failed to update event status ${W}:`,Z)}if(this.eventTriggerEngine){let W=new Set,Z=[];for(let $ of X){if($.delivery.attempts>0)continue;if(!W.has($.event.id))W.add($.event.id),Z.push({source:$.event.source,type:$.event.type,data:$.event.data,organizationId:$.event.organizationId})}if(Z.length>0)this.eventTriggerEngine.notifyEvents(Z)}}async processPerEventResults(X,Y){let G=[],Q=new Map,J=[],W=new Map;for(let Z=0;Z<X.events.length;Z++){let $=X.events?.[Z];if(!$)continue;let K=X.deliveryIds?.[Z];if(!K)continue;W.set($.id,K)}for(let Z of X.events){let $=W.get(Z.id);if(!$)continue;let K=Y.results?.[Z.id];if(K)if(K.success)G.push($);else if(K.retryAfter&&K.retryAfter>0){let H=Q.get(K.retryAfter)||[];H.push($),Q.set(K.retryAfter,H)}else J.push({deliveryId:$,error:K.error||"Event processing failed"});else if(Y.success)G.push($);else if(Y.retryAfter&&Y.retryAfter>0){let H=Q.get(Y.retryAfter)||[];H.push($),Q.set(Y.retryAfter,H)}else J.push({deliveryId:$,error:Y.error||"Batch processing failed"})}if(G.length>0)await this.storage.markDeliveriesDelivered(G);for(let[Z,$]of Q)await this.storage.scheduleRetryWithoutAttemptIncrement($,Z);if(J.length>0){let Z=new Map;for(let{deliveryId:$,error:K}of J){let H=Z.get(K)||[];H.push($),Z.set(K,H)}for(let[$,K]of Z)await this.storage.markDeliveriesFailed(K,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(X){if(!X.cron)return;try{let G=new LL(X.cron,{timezone:"UTC"}).nextRun();if(!G)return;let Q=G.toISOString(),J=await this.storage.getMatchingSubscriptions(X);if(J.length===0)return;await this.storage.createDeliveries(X.id,J.map((W)=>W.id),Q)}catch(Y){console.error(`[EventBus] Failed to schedule next cron delivery for event ${X.id}:`,Y)}}}var FW8=w(()=>{Q31();vx0();_x0();KW8()});class bx0{storage;worker;notifyStrategy;running=!1;constructor(X){this.storage=X.storage,this.notifyStrategy=X.notifyStrategy,this.worker=new fx0(this.storage,X.config)}setEventTriggerEngine(X){this.worker.setEventTriggerEngine(X)}async publish(X,Y,G){if(G.deliverAt&&G.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let Q;if(G.cron){try{let U=new LL(G.cron,{timezone:"UTC"}).nextRun();if(!U)throw Error("Cron expression does not produce a next run time");Q=U.toISOString()}catch(H){throw Error(`Invalid cron expression: ${H instanceof Error?H.message:String(H)}`)}let K=await this.storage.findActiveCronEvent(X,G.type,Y,G.cron);if(K)return K}let J=crypto.randomUUID(),W=new Date().toISOString(),Z=await this.storage.publishEvent({id:J,organizationId:X,type:G.type,source:Y,subject:G.subject,time:W,data:G.data,cron:G.cron});zK.emit(X,JW8(Z));let $=await this.storage.getMatchingSubscriptions(Z);if($.length>0){let K=G.deliverAt??Q;await this.storage.createDeliveries(J,$.map((U)=>U.id),K);let H=K!=null&&new Date(K).getTime()<=Date.now();if(this.notifyStrategy&&(!K||H))await this.notifyStrategy.notify(J).catch((U)=>{console.warn("[EventBus] Notify failed (non-critical):",U)})}return Z}async subscribe(X,Y){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:X,connectionId:Y.connectionId,publisher:Y.publisher,eventType:Y.eventType,filter:Y.filter})}async unsubscribe(X,Y){return this.storage.unsubscribe(Y,X)}async listSubscriptions(X,Y){return this.storage.listSubscriptions(X,Y)}async getSubscription(X,Y){return this.storage.getSubscription(Y,X)}async getEvent(X,Y){return this.storage.getEvent(Y,X)}async cancelEvent(X,Y,G){return this.storage.cancelEvent(Y,X,G)}async ackEvent(X,Y,G){return this.storage.ackDelivery(Y,X,G)}async syncSubscriptions(X,Y){return this.storage.syncSubscriptions({organizationId:X,...Y})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing after notify:",X)})});await this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing pending events on startup:",X)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(X){console.error("[EventBus] Error stopping notify strategy:",X)}}isRunning(){return this.running}}var UW8=w(()=>{Q31();Mi1();FW8()});class yx0{options;sub=null;onNotify=null;encoder=new TextEncoder;constructor(X){this.options=X}async start(X){if(this.sub)return;if(X)this.onNotify=X;if(!this.onNotify)return;let Y=this.options.getConnection();if(!Y)return;this.sub=Y.subscribe("mesh.events.notify"),(async()=>{for await(let G of this.sub)this.onNotify?.()})().catch((G)=>{console.error("[NatsNotify] Subscription error:",G)})}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onNotify=null}async notify(X){try{let Y=this.options.getConnection();if(!Y)return;Y.publish("mesh.events.notify",this.encoder.encode(X))}catch(Y){console.warn("[NatsNotify] Publish failed (non-critical):",Y)}}}class xx0{options;sub=null;localEmit=null;originId=crypto.randomUUID();encoder=new TextEncoder;constructor(X){this.options=X}async start(X){if(X)this.localEmit=X;if(this.sub)return;if(!this.localEmit)return;let Y=this.options.getConnection();if(!Y)return;this.sub=Y.subscribe("mesh.sse.broadcast");let G=new TextDecoder;(async()=>{for await(let Q of this.sub)try{let J=JSON.parse(G.decode(Q.data));if(typeof J?.originId!=="string"||typeof J?.organizationId!=="string"||typeof J?.event?.id!=="string"||typeof J?.event?.type!=="string")continue;if(J.originId===this.originId)continue;this.localEmit?.(J.organizationId,J.event)}catch{}})().catch((Q)=>{console.error("[NatsSSEBroadcast] Subscription error:",Q)})}broadcast(X,Y){this.localEmit?.(X,Y);let G={originId:this.originId,organizationId:X,event:Y};try{let Q=this.options.getConnection();if(!Q)return;Q.publish("mesh.sse.broadcast",this.encoder.encode(JSON.stringify(G)))}catch(Q){console.warn("[NatsSSEBroadcast] Publish failed (non-critical):",Q)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.localEmit=null}}function BW8(...X){return{async start(Y){await Promise.all(X.map((G)=>G.start(Y)))},async stop(){await Promise.all(X.map((Y)=>Y.stop().catch((G)=>{console.error("[NotifyStrategy] Error stopping strategy:",G)})))},async notify(Y){await Promise.all(X.map((G)=>G.notify(Y).catch((Q)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",Q)})))}}}class hx0{intervalMs;timer=null;onNotify=null;constructor(X){this.intervalMs=X}async start(X){if(this.timer)return;this.onNotify=X,this.scheduleNext()}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null;this.onNotify=null}async notify(X){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}async function NW8(X,Y,G=5){for(let Q=1;Q<=G;Q++)try{await Y();return}catch(J){if(Q===G){console.error(`${X} Deferred start failed:`,J);return}let W=Math.min(1000*2**(Q-1),1e4);console.warn(`${X} Start attempt ${Q}/${G} failed, retrying in ${W}ms`),await new Promise((Z)=>setTimeout(Z,W))}}function zW8(X,Y,G){let Q=YW8(X.db),J=G?.pollIntervalMs??Ri1.pollIntervalMs,W=new yx0({getConnection:()=>Y.getConnection()}),Z=BW8(new hx0(J),W),$=new xx0({getConnection:()=>Y.getConnection()});return zK.start($).catch((K)=>{console.error("[SSEHub] Failed to start broadcast strategy:",K)}),Y.onReady(()=>{NW8("[NatsNotify]",()=>W.start()),NW8("[NatsSSEBroadcast]",()=>$.start())}),new bx0({storage:Q,config:G,notifyStrategy:Z})}var gx0=w(()=>{GW8();UW8();_x0();Mi1();Mi1()});var OW8=()=>{};var ux0=()=>{};var DW8=()=>{};var E$7,V9Q;var wW8=w(()=>{OW8();ux0();JA();DW8();E$7={br:".br",zstd:".zst",gzip:".gz"},V9Q=Object.keys(E$7)});var LW8=w(()=>{wW8()});var EW8=()=>{};var PW8=w(()=>{EW8()});var qW8=()=>{};var AW8=w(()=>{YI0()});var lx0=w(()=>{ZA();AW8()});var mx0="x-hono-disable-ssg",c9Q;var dx0=w(()=>{lx0();c9Q=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[mx0]:"true"}})}catch{return null}})()});var TW8=w(()=>{yV1()});var cx0=w(()=>{TW8()});var IW8=w(()=>{PW8();qW8();ux0();dx0();cx0();lx0()});var VW8=w(()=>{dx0();cx0();IW8()});var j7Q;var jW8=w(()=>{VW8();({write:j7Q}=Bun)});var A$7=class{#X;constructor(X){this.#X=X,this.raw=X.raw,this.url=X.url?new URL(X.url):null,this.protocol=X.protocol??null}send(X,Y){this.#X.send(X,Y??{})}raw;binaryType="arraybuffer";get readyState(){return this.#X.readyState}url;protocol;close(X,Y){this.#X.close(X,Y)}},MW8=(X)=>{return(...Y)=>{if(typeof Y[0]==="function"){let[G,Q]=Y;return async function(W,Z){let $=await G(W),K=await X(W,$,Q);if(K)return K;await Z()}}else{let[G,Q,J]=Y;return(async()=>{let W=await X(G,Q,J);if(!W)throw Error("Failed to upgrade WebSocket");return W})()}}};var RW8=()=>{};var EW1=(X)=>("server"in X.env)?X.env.server:X.env;var Si1=()=>{};var T$7;var SW8=w(()=>{RW8();Si1();T$7=MW8((X,Y)=>{let G=EW1(X);if(!G)throw TypeError("env has to include the 2nd argument of fetch.");if(G.upgrade(X.req.raw,{data:{events:Y,url:new URL(X.req.url),protocol:X.req.url}}))return new Response(null);return})});var ix0=(X)=>{let Y=EW1(X);if(!Y)throw TypeError("env has to include the 2nd argument of fetch.");if(typeof Y.requestIP!=="function")throw TypeError("server.requestIP is not a function.");let G=Y.requestIP(X.req.raw);if(!G)return{remote:{}};return{remote:{address:G.address,addressType:G.family==="IPv6"||G.family==="IPv4"?G.family:void 0,port:G.port}}};var kW8=w(()=>{Si1()});var CW8=w(()=>{LW8();jW8();SW8();kW8();Si1()});var vW8;var _W8=w(()=>{vW8={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/decocms/e02ce92e-6684-41a6-acfc-432977eb4878/github.png"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}}});var Ci1={};T0(Ci1,{waitForSeed:()=>k$7,seedLocalMode:()=>M$7,markSeedComplete:()=>S$7,isLocalMode:()=>om,getLocalAdminUser:()=>px0,getLocalAdminPassword:()=>ki1});import{userInfo as I$7}from"os";async function ki1(){return u4().betterAuthSecret||"local-mode-default"}function fW8(){try{return I$7().username||"local"}catch{return"local"}}function V$7(X){return X.charAt(0).toUpperCase()+X.slice(1)}async function j$7(){let X=a7(),Y=await X.db.selectFrom("user").select(X.db.fn.countAll().as("count")).executeTakeFirst();return Number(Y?.count??0)===0}async function M$7(){if(!await j$7())return!1;let Y=fW8(),G=`${Y}@localhost.mesh`,Q=V$7(Y),J=await ki1(),W=await kY.api.signUpEmail({body:{email:G,password:J,name:Q}});if(!W?.user?.id)throw Error("Failed to create local admin user");let Z=W.user.id,$=a7();await $.db.updateTable("user").set({role:"admin"}).where("id","=",Z).execute();let K=`${Y}-local`.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),H=`${Q} Local`;return await $.db.updateTable("organization").set({name:H,slug:K}).where("id","in",(U)=>U.selectFrom("member").select("organizationId").where("userId","=",Z)).execute(),!0}async function px0(){let X=a7(),Y=`${fW8()}@localhost.mesh`;return X.db.selectFrom("user").where("email","=",Y).selectAll().executeTakeFirst()}function om(){return u4().localMode}function S$7(){bW8()}function k$7(){return R$7}var bW8,R$7;var es=w(()=>{ZU();l9();aR();R$7=new Promise((X)=>{if(bW8=X,!om())X()})});function yW8(){let X=Object.keys(r5.socialProviders??{}),Y=X.length>0,G=X.map((J)=>({name:J,icon:vW8[J].icon})),Q=u4().localMode;return{emailAndPassword:{enabled:r5.emailAndPassword?.enabled??!1},magicLink:{enabled:r5.magicLinkConfig?.enabled??!1},emailOtp:{enabled:r5.emailOtpConfig?.enabled??!1},resetPassword:{enabled:ji1},socialProviders:{enabled:Y,providers:G},sso:r5.ssoConfig?{enabled:!0,providerId:r5.ssoConfig.providerId}:{enabled:!1},stdioEnabled:Q,localMode:om()}}var PW1,xW8;var nx0=w(()=>{iX();CW8();CX();l9();aR();ZU();ZC0();hM0();_W8();es();PW1=new A6;PW1.post("/local-session",async(X)=>{if(!om())return X.json({success:!1,error:"Local mode is not active"},403);let Y;try{Y=ix0(X).remote.address}catch{}if(!(Y==="127.0.0.1"||Y==="::1"||Y==="::ffff:127.0.0.1"))return X.json({success:!1,error:"Forbidden"},403);try{let{waitForSeed:Q}=await Promise.resolve().then(() => (es(),Ci1));await Q();let{auth:J}=await Promise.resolve().then(() => (aR(),s38)),W=await px0();if(!W)return X.json({success:!1,error:"Local admin user not found"},500);let Z=await ki1();return await J.api.signInEmail({body:{email:W.email,password:Z},asResponse:!0})}catch(Q){return console.error("Failed to create local session:",Q),X.json({success:!1,error:Q instanceof Error?Q.message:"Failed to create local session"},500)}});PW1.get("/domain-lookup",async(X)=>{let Y=await kY.api.getSession({headers:X.req.raw.headers});if(!Y?.user)return X.json({success:!1,error:"Authentication required"},401);if(!Y.user.emailVerified)return X.json({found:!1});let G=Y.user.email?.split("@")[1]?.toLowerCase();if(!G||$T.has(G))return X.json({found:!1});try{let J=await new mw(a7().db).getByDomain(G);if(!J)return X.json({found:!1});let W=await a7().db.selectFrom("organization").select(["name","slug"]).where("id","=",J.organizationId).executeTakeFirst();return X.json({found:!0,autoJoinEnabled:J.autoJoinEnabled,organization:W?{name:W.name,slug:W.slug}:null})}catch(Q){return console.error("[Auth] Domain lookup failed:",Q),X.json({success:!1,error:"Domain lookup failed"},500)}});PW1.post("/domain-join",async(X)=>{let Y=await kY.api.getSession({headers:X.req.raw.headers});if(!Y?.user)return X.json({success:!1,error:"Authentication required"},401);if(!Y.user.emailVerified)return X.json({success:!1,error:"Email must be verified to join"},403);let G=Y.user.email?.split("@")[1]?.toLowerCase();if(!G||$T.has(G))return X.json({success:!1,error:"Generic email domains cannot auto-join"},403);try{let J=await new mw(a7().db).getByDomain(G);if(!J||!J.autoJoinEnabled)return X.json({success:!1,error:"Auto-join is not available for this domain"},403);let W=await a7().db.selectFrom("organization").select(["id","slug"]).where("id","=",J.organizationId).executeTakeFirst();if(!W)return X.json({success:!1,error:"Organization not found"},404);try{await kY.api.addMember({body:{userId:Y.user.id,role:"user",organizationId:W.id}})}catch(Z){if(!(Z instanceof Error?Z.message.toLowerCase():"").includes("already a member"))return console.error("[Auth] Domain join addMember failed:",Z),X.json({success:!1,error:"Failed to join organization"},500)}return M6.capture({distinctId:Y.user.id,event:"organization_domain_joined",groups:{organization:W.id},properties:{organization_id:W.id,organization_slug:W.slug,email_domain:G}}),X.json({success:!0,slug:W.slug})}catch(Q){return M6.captureException(Q,Y.user.id),console.error("[Auth] Domain join failed:",Q),X.json({success:!1,error:"Failed to join organization"},500)}});PW1.post("/domain-setup",async(X)=>{let Y=await kY.api.getSession({headers:X.req.raw.headers});if(!Y?.user)return X.json({success:!1,error:"Authentication required"},401);if(!Y.user.emailVerified)return X.json({success:!1,error:"Email must be verified"},403);let G=Y.user.email?.split("@")[1]?.toLowerCase();if(!G||$T.has(G))return X.json({success:!1,error:"Corporate email required"},403);try{let Q=a7().db,J=new mw(Q),W=await J.getByDomain(G);if(W){let N=await Q.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.slug"]).where("member.userId","=",Y.user.id).where("member.organizationId","=",W.organizationId).executeTakeFirst();if(N)return X.json({success:!0,slug:N.slug,alreadyExists:!0});return X.json({success:!1,error:"This domain is already claimed. Ask an admin for an invitation."},403)}let Z=G.split(".")[0]??G,$=Z.charAt(0).toUpperCase()+Z.slice(1),K=Z.toLowerCase().replace(/[^a-z0-9-]/g,""),H=null;for(let z=0;z<3;z++){let O=z===0?"":`-${Math.random().toString(36).slice(2,6)}`,D=z===0?$:`${$}${O}`,E=`${K}${O}`;try{H=await kY.api.createOrganization({body:{name:D,slug:E,userId:Y.user.id}});break}catch(P){if(!(P instanceof Error&&("body"in P)&&P.body?.code==="ORGANIZATION_ALREADY_EXISTS")||z===2)throw P}}if(!H?.id)throw Error("Failed to create organization");let U=H.id;try{await J.setDomain(U,G,!0)}catch(N){if(N instanceof Error&&N.message.includes("already claimed")){try{await kY.api.deleteOrganization({headers:X.req.raw.headers,body:{organizationId:U}})}catch{console.error("[Auth] Failed to clean up orphaned org after domain race:",U)}return X.json({success:!1,error:"This domain was just claimed by another user. Please refresh and try again."},409)}throw N}let B=!1;try{let N=u4().firecrawlApiKey;if(N){let z=await dS1(G,N,$);if(z){let O=new kJ1(a7().db),D=await O.create(U,z);await O.setDefault(D.id,U),B=!0;let E=z.favicon??z.logo??null,P={};if(z.name!==$)P.name=z.name;if(E)P.logo=E;if(Object.keys(P).length>0)await kY.api.updateOrganization({headers:X.req.raw.headers,body:{organizationId:U,data:P}})}}}catch(N){console.error("[Auth] Brand extraction failed (non-fatal):",N)}return M6.identify({distinctId:Y.user.id,properties:{email:Y.user.email,$set:{email:Y.user.email},$set_once:{first_organization_created_at:new Date().toISOString()}}}),M6.groupIdentify({groupType:"organization",groupKey:U,properties:{name:H.slug??K,slug:H.slug??K,email_domain:G,brand_extracted:B,created_at:new Date().toISOString()}}),M6.capture({distinctId:Y.user.id,event:"organization_created",groups:{organization:U},properties:{organization_id:U,organization_slug:H.slug??K,email_domain:G,brand_extracted:B}}),X.json({success:!0,slug:H.slug??K,brandExtracted:B})}catch(Q){return M6.captureException(Q,Y.user?.id),console.error("[Auth] Domain setup failed:",Q),X.json({success:!1,error:"Failed to set up organization"},500)}});xW8=PW1});function C$7(X){X.get("/status",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!await ax0(G,G.auth.user.id,Q))return Y.json({error:"Not a member of this organization"},403);let W=await G.storage.orgSsoConfig.getByOrgId(Q);if(!W||!W.enforced)return Y.json({ssoRequired:!1});let Z=await G.storage.orgSsoSessions.isValid(G.auth.user.id,Q);return Y.json({ssoRequired:!0,authenticated:Z,issuer:W.issuer,domain:W.domain})}),X.get("/authorize",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!await ax0(G,G.auth.user.id,Q))return Y.json({error:"Not a member of this organization"},403);let W=await G.storage.orgSsoConfig.getByOrgId(Q);if(!W)return Y.json({error:"SSO not configured for this organization"},404);let Z=await tx0(W.issuer,W.discoveryEndpoint),$=v$7(),K=await _$7($),H=crypto.randomUUID(),U=JSON.stringify({state:H,codeVerifier:$,orgId:Q,userId:G.auth.user.id});KI0(Y,"org_sso_state",U,{httpOnly:!0,secure:!0,sameSite:"Lax",path:"/api/org-sso/callback",maxAge:600});let B=new URLSearchParams({response_type:"code",client_id:W.clientId,redirect_uri:`${G.baseUrl}/api/org-sso/callback`,scope:W.scopes.join(" "),state:H,code_challenge:K,code_challenge_method:"S256"}),N=`${Z.authorization_endpoint}?${B.toString()}`;return Y.redirect(N)}),X.get("/callback",async(Y)=>{let G=Y.get("meshContext"),Q=Y.req.query("code"),J=Y.req.query("state"),W=Y.req.query("error");if(W)return Y.redirect(`/?sso_error=${encodeURIComponent(W)}`);if(!Q||!J)return Y.redirect("/?sso_error=missing_code_or_state");let Z=cV1(Y,"org_sso_state");if(!Z)return Y.redirect("/?sso_error=state_expired");KI0(Y,"org_sso_state","",{httpOnly:!0,secure:!0,sameSite:"Lax",path:"/api/org-sso/callback",maxAge:0});let $;try{$=JSON.parse(Z)}catch{return Y.redirect("/?sso_error=invalid_state")}if($.state!==J)return Y.redirect("/?sso_error=state_mismatch");if(!G.auth.user||G.auth.user.id!==$.userId)return Y.redirect("/?sso_error=session_expired");let K=await G.storage.orgSsoConfig.getByOrgId($.orgId);if(!K)return Y.redirect("/?sso_error=sso_not_configured");let H=await tx0(K.issuer,K.discoveryEndpoint),U=await fetch(H.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Q,redirect_uri:`${G.baseUrl}/api/org-sso/callback`,client_id:K.clientId,client_secret:K.clientSecret,code_verifier:$.codeVerifier})});if(!U.ok)return console.error("[org-sso] Token exchange failed:",await U.text()),Y.redirect("/?sso_error=token_exchange_failed");let B=await U.json();if(!B.id_token)return Y.redirect("/?sso_error=no_id_token");try{let O=lI(new URL(H.jwks_uri)),{payload:D}=await f7(B.id_token,O,{issuer:K.issuer,audience:K.clientId}),E=D.email?.toLowerCase(),P=G.auth.user.email?.toLowerCase();if(!E||E!==P)return console.error(`[org-sso] Email mismatch: token=${E}, user=${P}`),Y.redirect("/?sso_error=email_mismatch")}catch(O){return console.error("[org-sso] ID token verification failed:",O),Y.redirect("/?sso_error=token_verification_failed")}await G.storage.orgSsoSessions.upsert(G.auth.user.id,$.orgId);let N=await ax0(G,G.auth.user.id,$.orgId),z=N?.orgSlug?`/${N.orgSlug}`:"/";return Y.redirect(z)}),X.get("/config",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!f$7(G))return Y.json({error:"Admin role required"},403);let J=await G.storage.orgSsoConfig.getByOrgId(Q);if(!J)return Y.json({configured:!1});return Y.json({configured:!0,config:G.storage.orgSsoConfig.toPublic(J)})}),X.post("/config",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!rx0(G))return Y.json({error:"Owner role required"},403);let J=await Y.req.json();if(!J.issuer||!J.clientId||!J.domain)return Y.json({error:"issuer, clientId, and domain are required"},400);let W=await G.storage.orgSsoConfig.getByOrgId(Q);if(!W&&!J.clientSecret)return Y.json({error:"clientSecret is required for initial SSO setup"},400);let Z=J.clientSecret||W?.clientSecret||"";try{await tx0(J.issuer,J.discoveryEndpoint)}catch(K){return Y.json({error:"Failed to reach OIDC discovery endpoint",details:K instanceof Error?K.message:String(K)},400)}let $=await G.storage.orgSsoConfig.upsert(Q,{issuer:J.issuer,clientId:J.clientId,clientSecret:Z,discoveryEndpoint:J.discoveryEndpoint,scopes:J.scopes,domain:J.domain,enforced:J.enforced});return Y.json({success:!0,config:G.storage.orgSsoConfig.toPublic($)})}),X.post("/config/enforce",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!rx0(G))return Y.json({error:"Owner role required"},403);let J=await Y.req.json();if(!await G.storage.orgSsoConfig.getByOrgId(Q))return Y.json({error:"SSO must be configured before enforcing"},400);return await G.storage.orgSsoConfig.setEnforced(Q,J.enforced),Y.json({success:!0,enforced:J.enforced})}),X.delete("/config",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!rx0(G))return Y.json({error:"Owner role required"},403);return await G.storage.orgSsoConfig.delete(Q),Y.json({success:!0})})}function vi1(X){let Y;try{Y=new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}let G=u4().localMode;if(Y.protocol!=="https:"&&!(G&&Y.protocol==="http:"))throw Error(`OIDC URL must use HTTPS: ${X}`);let Q=Y.hostname,J=[/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^0\./,/^\[::1\]$/,/^\[fd/,/^\[fe80:/,/^localhost$/i],W=/^127\.|^\[::1\]$|^localhost$/i.test(Q);if(G&&W)return;for(let Z of J)if(Z.test(Q))throw Error(`OIDC URL must not point to a private network address: ${Q}`)}async function tx0(X,Y){let G=Y||X,Q=hW8.get(G);if(Q&&Q.expiresAt>Date.now())return Q.doc;let J=Y||`${X.replace(/\/$/,"")}/.well-known/openid-configuration`;vi1(J);let W=await fetch(J);if(!W.ok)throw Error(`OIDC discovery failed: ${W.status} ${W.statusText}`);let Z=await W.json();if(!Z.authorization_endpoint||!Z.token_endpoint||!Z.jwks_uri)throw Error("OIDC discovery document missing required endpoints");return vi1(Z.authorization_endpoint),vi1(Z.token_endpoint),vi1(Z.jwks_uri),hW8.set(G,{doc:Z,expiresAt:Date.now()+3600000}),Z}function v$7(){let X=new Uint8Array(32);return crypto.getRandomValues(X),btoa(String.fromCharCode(...X)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _$7(X){let G=new TextEncoder().encode(X),Q=await crypto.subtle.digest("SHA-256",G);return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ax0(X,Y,G){return await X.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.slug as orgSlug","member.role"]).where("member.userId","=",Y).where("member.organizationId","=",G).executeTakeFirst()??null}function f$7(X){let Y=X.auth.user?.role;if(!Y)return!1;return ko.includes(Y)}function rx0(X){return X.auth.user?.role==="owner"}var _i1=()=>{let X=new A6;return C$7(X),X},hW8;var ox0=w(()=>{iX();HI0();RJ();l9();vJ1();hW8=new Map});function gW8(X){let Y=X.filter((Q)=>Q.role==="system"),G=X.find((Q)=>Q.role!=="system");return{systemMessages:Y,requestMessage:G}}function b$7(X){let Y=!1,G=X.map((Q)=>{if(Q.role!=="assistant")return Q;if(!Q.parts.some((W)=>("state"in W)&&W.state==="approval-requested"))return Q;return Y=!0,{...Q,parts:Q.parts.map((W)=>{if(!("state"in W)||W.state!=="approval-requested"||!("approval"in W)||!W.approval)return W;return{...W,state:"output-denied",approval:{...W.approval,approved:!1,reason:"User sent a new message without approving this tool call."}}})}});return Y?G:X}function y$7(X){let[Y,G]=X.reduce((Q,J)=>{if(J.role==="system")Q[0].push(J);else Q[1].push(J);return Q},[[],[]]);return{systemMessages:Y,messages:G}}async function x$7(X,Y){return await X.loadHistory(Y)}function h$7(X,Y){let G=X.filter((W)=>W.parts&&W.parts.length>0);if(!Y)return G;let Q=G.findIndex((W)=>W.id===Y.id);return Q>=0?[...G.slice(0,Q),Y]:[...G,Y]}async function uW8(X,Y,G,Q){let J=await x$7(X,Q),W=h$7(J,Y);return[...G,...W]}async function lW8(X,Y){let G=X.filter((U)=>U.role!=="assistant"||U.parts&&U.parts.length>0),Q=await j31({messages:G}),J=b$7(Q),W=await V31(J,{tools:Y.tools,ignoreIncompleteToolCalls:!0}),{systemMessages:Z,messages:$}=y$7(W),H=d_0({messages:$,reasoning:"all",emptyMessages:"remove",toolCalls:"none"}).map((U)=>{if(U.role!=="assistant")return U;let B=Array.isArray(U.content)?U.content.filter((N)=>N.type!=="reasoning"&&N.type!=="thinking"&&N.type!=="redacted-reasoning").map((N)=>{let z=N;if("providerOptions"in z||"providerMetadata"in z){let{providerOptions:O,providerMetadata:D,...E}=z;if(z.type==="tool-call"){let P=D?.google,q=O?.google;return{...E,...P?{providerMetadata:{google:P}}:{},...q?{providerOptions:{google:q}}:{}}}return E}return N}):U.content;return{...U,content:Array.isArray(B)&&B.length===0?[{type:"text",text:""}]:B,providerOptions:void 0,providerMetadata:void 0}});return{systemMessages:Z,messages:H,originalMessages:Q}}var sx0=w(()=>{xX()});function OK(X){return`mesh-storage://${X}`}function sm(X){if(!X.startsWith("mesh-storage://"))return null;return X.slice(15)}function ex0(){return/mesh-storage:\/\/([^\s"'<>[\]]+)/g}function g$7(X,Y,G){return`${X}/api/${Y}/files/${G}`}function l$7(X){return X.type==="file"&&"mediaType"in X&&typeof X.mediaType==="string"&&u$7.has(X.mediaType)}function mW8(X){let Y=X.match(/^data:([^;]+);base64,(.+)$/s);if(!Y)return null;let[,G,Q]=Y;try{let J=atob(Q),W=new Uint8Array(J.length);for(let Z=0;Z<J.length;Z++)W[Z]=J.charCodeAt(Z);return{mimeType:G,bytes:W}}catch{return null}}function dW8(X){return{"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","application/pdf":"pdf","text/plain":"txt","text/html":"html","application/json":"json"}[X]??"bin"}async function cW8(X,Y,G,Q){if(!Q.objectStorage)return null;try{return await Q.objectStorage.put(Y,X,{contentType:G}),Y}catch(J){return console.error("[file-materializer] Failed to upload file:",J),null}}async function em(X,Y){if(!Y.objectStorage)return null;try{return await Y.objectStorage.presignedGetUrl(X,m$7)}catch(G){return console.error("[file-materializer] Failed to generate presigned URL:",G),null}}async function iW8(X,Y){if(!Y.organization)return X;let G=Y.organization.id,Q=X.findLastIndex((O)=>O.role==="user");if(Q===-1)return X;let J=X[Q],W=J.parts.filter((O)=>O.type==="file"&&("url"in O)&&typeof O.url==="string"&&O.url.startsWith("data:"));if(W.length===0)return X;let $=(await Promise.all(W.map(async(O)=>{if(O.type!=="file"||!("url"in O)||typeof O.url!=="string")return null;let D=mW8(O.url);if(!D)return null;let E=dW8(D.mimeType),P=`chat-uploads/${crypto.randomUUID()}.${E}`,q=await cW8(D.bytes,P,D.mimeType,Y);if(!q)return null;let j="filename"in O&&typeof O.filename==="string"?O.filename:P;return{dataUrl:O.url,meshStorageUrl:OK(q),redirectUrl:g$7(Y.baseUrl,G,q),filename:j}}))).filter((O)=>O!==null);if($.length===0)return X;let H=`[Uploaded files \u2014 use these URLs when calling tools]
|
|
7148
|
+
)`).where("status","=","pending").returning(["id"]).execute()).map((W)=>W.id);if(Q.length===0)return[];return(await this.db.selectFrom("event_deliveries as d").innerJoin("events as e","e.id","d.event_id").innerJoin("event_subscriptions as s","s.id","d.subscription_id").select(["d.id as delivery_id","d.event_id","d.subscription_id","d.status as delivery_status","d.attempts as delivery_attempts","d.last_error as delivery_last_error","d.delivered_at","d.next_retry_at as delivery_next_retry_at","d.created_at as delivery_created_at","e.organization_id","e.type","e.source","e.specversion","e.subject","e.time","e.datacontenttype","e.dataschema","e.data","e.cron","e.status as event_status","e.attempts as event_attempts","e.last_error as event_last_error","e.next_retry_at","e.created_at as event_created_at","e.updated_at as event_updated_at","s.connection_id","s.publisher","s.event_type","s.filter","s.enabled","s.created_at as subscription_created_at","s.updated_at as subscription_updated_at"]).where("d.id","in",Q).where("d.status","=","processing").execute()).map((W)=>({delivery:{id:W.delivery_id,eventId:W.event_id,subscriptionId:W.subscription_id,status:W.delivery_status,attempts:W.delivery_attempts,lastError:W.delivery_last_error,deliveredAt:W.delivered_at,nextRetryAt:W.delivery_next_retry_at,createdAt:W.delivery_created_at},event:{id:W.event_id,organizationId:W.organization_id,type:W.type,source:W.source,specversion:W.specversion,subject:W.subject,time:W.time,datacontenttype:W.datacontenttype,dataschema:W.dataschema,data:W.data?JSON.parse(W.data):null,cron:W.cron,status:W.event_status,attempts:W.event_attempts,lastError:W.event_last_error,nextRetryAt:W.next_retry_at,createdAt:W.event_created_at,updatedAt:W.event_updated_at},subscription:{id:W.subscription_id,organizationId:W.organization_id,connectionId:W.connection_id,publisher:W.publisher,eventType:W.event_type,filter:W.filter,enabled:Boolean(W.enabled),createdAt:W.subscription_created_at,updatedAt:W.subscription_updated_at}}))}async markDeliveriesDelivered(X){if(X.length===0)return;let Y=new Date().toISOString();await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:Y}).where("id","in",X).execute()}async markDeliveriesPermanentlyFailed(X,Y){if(X.length===0)return;await this.db.updateTable("event_deliveries").set({status:"failed",last_error:Y,next_retry_at:null}).where("id","in",X).execute()}async markDeliveriesFailed(X,Y,G=20,Q=1000,J=3600000){if(X.length===0)return;for(let W of X){let Z=await this.db.selectFrom("event_deliveries").select(["attempts"]).where("id","=",W).executeTakeFirst();if(!Z)continue;let $=Z.attempts+1;if($>=G)await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"failed",next_retry_at:null}).where("id","=",W).execute();else{let K=Math.min(Q*Math.pow(2,$-1),J),H=new Date(Date.now()+K).toISOString();await this.db.updateTable("event_deliveries").set({attempts:$,last_error:Y,status:"pending",next_retry_at:H}).where("id","=",W).execute()}}}async updateEventStatus(X){let Y=await this.db.selectFrom("event_deliveries").select(["status"]).where("event_id","=",X).execute();if(Y.length===0)return;let G=Y.every((W)=>W.status==="delivered"),Q=Y.some((W)=>W.status==="failed"),J=Y.some((W)=>W.status==="pending"||W.status==="processing");if(G)await this.db.updateTable("events").set({status:"delivered",updated_at:new Date().toISOString()}).where("id","=",X).execute();else if(Q&&!J)await this.db.updateTable("events").set({status:"failed",updated_at:new Date().toISOString()}).where("id","=",X).execute()}async resetStuckDeliveries(){if((await B1`SELECT pg_try_advisory_lock(hashtext('event_bus_reset_stuck')) as locked`.execute(this.db)).rows[0]?.locked!==!0)return 0;try{let G=await this.db.updateTable("event_deliveries").set({status:"pending"}).where("status","=","processing").executeTakeFirst();return Number(G.numUpdatedRows??0)}finally{await B1`SELECT pg_advisory_unlock(hashtext('event_bus_reset_stuck'))`.execute(this.db)}}async getEvent(X,Y){let G=await this.db.selectFrom("events").selectAll().where("id","=",X).where("organization_id","=",Y).executeTakeFirst();if(!G)return null;return{id:G.id,organizationId:G.organization_id,type:G.type,source:G.source,specversion:G.specversion,subject:G.subject,time:G.time,datacontenttype:G.datacontenttype,dataschema:G.dataschema,data:G.data?JSON.parse(G.data):null,cron:G.cron,status:G.status,attempts:G.attempts,lastError:G.last_error,nextRetryAt:G.next_retry_at,createdAt:G.created_at,updatedAt:G.updated_at}}async findActiveCronEvent(X,Y,G,Q){let J=await this.db.selectFrom("events").selectAll().where("organization_id","=",X).where("type","=",Y).where("source","=",G).where("cron","=",Q).where("status","in",["pending","processing","delivered"]).orderBy("created_at","desc").executeTakeFirst();if(!J)return null;return{id:J.id,organizationId:J.organization_id,type:J.type,source:J.source,specversion:J.specversion,subject:J.subject,time:J.time,datacontenttype:J.datacontenttype,dataschema:J.dataschema,data:J.data?JSON.parse(J.data):null,cron:J.cron,status:J.status,attempts:J.attempts,lastError:J.last_error,nextRetryAt:J.next_retry_at,createdAt:J.created_at,updatedAt:J.updated_at}}async findOrphanedCronEvents(){return(await this.db.selectFrom("events").selectAll().where("cron","is not",null).where("status","=","delivered").where((Y)=>Y.not(Y.exists(Y.selectFrom("event_deliveries").select("id").whereRef("event_deliveries.event_id","=","events.id").where("event_deliveries.status","in",["pending","processing"])))).execute()).map((Y)=>({id:Y.id,organizationId:Y.organization_id,type:Y.type,source:Y.source,specversion:Y.specversion,subject:Y.subject,time:Y.time,datacontenttype:Y.datacontenttype,dataschema:Y.dataschema,data:Y.data?JSON.parse(Y.data):null,cron:Y.cron,status:Y.status,attempts:Y.attempts,lastError:Y.last_error,nextRetryAt:Y.next_retry_at,createdAt:Y.created_at,updatedAt:Y.updated_at}))}async cancelEvent(X,Y,G){let Q=await this.db.updateTable("events").set({status:"failed",last_error:"Cancelled by publisher",updated_at:new Date().toISOString()}).where("id","=",X).where("organization_id","=",Y).where("source","=",G).where("status","in",["pending","processing"]).executeTakeFirst();if((Q.numUpdatedRows??0n)>0n)await this.db.updateTable("event_deliveries").set({status:"failed",last_error:"Event cancelled by publisher"}).where("event_id","=",X).where("status","in",["pending","processing"]).execute();return{success:(Q.numUpdatedRows??0n)>0n}}async scheduleRetryWithoutAttemptIncrement(X,Y){if(X.length===0)return;let G=new Date(Date.now()+Y).toISOString();await this.db.updateTable("event_deliveries").set({status:"pending",next_retry_at:G}).where("id","in",X).execute()}async ackDelivery(X,Y,G){if(!await this.db.selectFrom("events").select(["id"]).where("id","=",X).where("organization_id","=",Y).executeTakeFirst())return{success:!1};let W=((await this.db.updateTable("event_deliveries").set({status:"delivered",delivered_at:new Date().toISOString()}).where("event_id","=",X).where("status","in",["pending","processing"]).where((Z)=>Z.exists(Z.selectFrom("event_subscriptions").select("id").whereRef("event_subscriptions.id","=","event_deliveries.subscription_id").where("event_subscriptions.connection_id","=",G).where("event_subscriptions.organization_id","=",Y))).executeTakeFirst()).numUpdatedRows??0n)>0n;if(W)await this.updateEventStatus(X);return{success:W}}async syncSubscriptions(X){let{organizationId:Y,connectionId:G,subscriptions:Q}=X,J=(P,q)=>{return`${P}::${q??""}`},W=await this.listSubscriptions(Y,G),Z=new Map;for(let P of W)Z.set(J(P.eventType,P.publisher),P);let $=new Map;for(let P of Q)$.set(J(P.eventType,P.publisher),P);let K=new Date().toISOString(),H=[],U=[],B=[],N=0;for(let[P,q]of $){let j=Z.get(P);if(!j)H.push({id:crypto.randomUUID(),organization_id:Y,connection_id:G,event_type:q.eventType,publisher:q.publisher??null,filter:q.filter??null,enabled:!0,created_at:K,updated_at:K});else{let M=j.filter??null,I=q.filter??null;if(M!==I)U.push({id:j.id,filter:I});else N++}}for(let[P,q]of Z)if(!$.has(P))B.push(q.id);if(H.length>0)await this.db.insertInto("event_subscriptions").values(H).execute();if(U.length>0)await Promise.all(U.map((P)=>this.db.updateTable("event_subscriptions").set({filter:P.filter,updated_at:K}).where("id","=",P.id).execute()));if(B.length>0)await this.db.deleteFrom("event_subscriptions").where("id","in",B).execute();let z=H.length,O=U.length,D=B.length,E=await this.listSubscriptions(Y,G);return{created:z,updated:O,deleted:D,unchanged:N,subscriptions:E}}}function YW8(X){return new XW8(X)}var GW8=w(()=>{B6()});class QW8{listeners=new Map;totalCount=0;strategy=null;started=!1;async start(X){if(this.started){if(!X)return;await this.stop()}this.strategy=X,await this.strategy.start((Y,G)=>this.localEmit(Y,G)),this.started=!0}async stop(){if(!this.started||!this.strategy)return;await this.strategy.stop(),this.started=!1}add(X){if(this.totalCount>=500)return console.warn("[SSEHub] Total connection limit reached (500)"),null;let Y=this.listeners.get(X.organizationId);if(!Y)Y=new Map,this.listeners.set(X.organizationId,Y);if(Y.size>=50)return console.warn(`[SSEHub] Per-org connection limit reached for ${X.organizationId} (50)`),null;return Y.set(X.id,X),this.totalCount++,X.id}remove(X,Y){let G=this.listeners.get(X);if(!G)return;if(G.delete(Y)){if(this.totalCount--,G.size===0)this.listeners.delete(X)}}emit(X,Y){if(this.strategy)this.strategy.broadcast(X,Y);else this.localEmit(X,Y)}countForOrg(X){return this.listeners.get(X)?.size??0}get count(){return this.totalCount}localEmit(X,Y){let G=this.listeners.get(X);if(!G||G.size===0)return;for(let Q of G.values()){if(Q.typePatterns&&!U$7(Y.type,Q.typePatterns))continue;try{Q.push(Y)}catch{this.remove(X,Q.id)}}}}function U$7(X,Y){for(let G of Y){if(G===X)return!0;if(G.endsWith(".*")){let Q=G.slice(0,-1);if(X.startsWith(Q))return!0}}return!1}function JW8(X){return{id:X.id,type:X.type,source:X.source,subject:X.subject,data:X.data?B$7(X.data):void 0,time:X.time}}function B$7(X){if(typeof X==="string")try{return JSON.parse(X)}catch{return X}return X}var zK;var Mi1=w(()=>{zK=new QW8});function ZW8(X){if(typeof X==="object"&&X!==null){let Q=X,J=Q.status??Q.code;if(typeof J==="number"&&N$7.has(J))return!0}let Y=X instanceof Error?X.message:typeof X==="string"?X:"";if(!Y)return!1;let G=Y.toLowerCase();if(/\b401\b/.test(G))return!0;return z$7.some((Q)=>G.includes(Q))}function WW8(X){let Y=X instanceof Error?X.message:typeof X==="string"?X:"";if(!Y)return!1;let G=Y.toLowerCase();return O$7.some((Q)=>G.includes(Q))}var N$7,z$7,O$7,LW1;var vx0=w(()=>{N$7=new Set([401]),z$7=["unauthorized","invalid_token","invalid api key","api key required","api-key required"],O$7=["tool on_events not found","tool not found"];LW1=class LW1 extends Error{constructor(X){super(X);this.name="PermanentDeliveryError"}}});var Ri1;var _x0=w(()=>{Ri1={pollIntervalMs:5000,batchSize:100,maxAttempts:20,retryDelayMs:1000,maxDelayMs:3600000}});function D$7(X){return X.endsWith("_self")}function w$7(X){return X.slice(0,-5)}function $W8(){return async(X,Y)=>{try{if(D$7(X)){let Z=w$7(X),$=await GB.create(),K={organizationId:Z,connectionId:X,publish:async(B,N,z,O)=>{await $.eventBus.publish(Z,X,{type:B,subject:N,data:z,deliverAt:O?.deliverAt})},createMCPProxy:async(B)=>{let N={...$,getOrCreateClient:Co()},z=await sM0(B,N);return{callTool:async(O,D,E)=>{let P=await z.callTool(O,D,E);return{content:P.content,structuredContent:P.structuredContent,isError:P.isError}},close:()=>z.close()}}},H=Y.filter((B)=>B.type==="registry.monitor.scheduled");if(H.length>0){let{parseMonitorConfig:B}=await Promise.resolve().then(() => (aH(),bn6)),N=await K.createMCPProxy(X);try{for(let z of H){let O=z.data&&typeof z.data==="object"?z.data:{},D=O.config&&typeof O.config==="object"?O.config:{},E=B(D);await N.callTool({name:"REGISTRY_MONITOR_RUN_START",arguments:{config:E}})}}finally{await N.close()}if(H.length===Y.length)return{success:!0}}if(await eo4(Y,K))return{success:!0}}let G=await GB.create(),Q=await sM0(X,G),W=await Tj0.forClient(CJ1(Q)).ON_EVENTS({events:Y});return{success:W.success,error:W.error,retryAfter:W.retryAfter,results:W.results}}catch(G){let Q=G instanceof Error?G.message:String(G);if(console.error(`[EventBus] Failed to notify connection ${X}:`,Q),ZW8(G)||WW8(G))throw new LW1(Q);return{success:!1,error:Q}}}}var KW8=w(()=>{xZ1();pt();dR1();LQ1();gR1();vx0()});function HW8(X){return{specversion:"1.0",id:X.id,source:X.source,type:X.type,time:X.time,subject:X.subject??void 0,datacontenttype:X.datacontenttype,dataschema:X.dataschema??void 0,data:X.data??void 0}}function L$7(X){let Y=new Map;for(let Q of X){let J=Q.subscription.connectionId,W=Y.get(J);if(W){if(W.deliveryIds.push(Q.delivery.id),!W.seenEventIds.has(Q.event.id))W.seenEventIds.add(Q.event.id),W.events.push(HW8(Q.event))}else Y.set(J,{connectionId:Q.subscription.connectionId,deliveryIds:[Q.delivery.id],events:[HW8(Q.event)],seenEventIds:new Set([Q.event.id])})}let G=new Map;for(let[Q,J]of Y)G.set(Q,{connectionId:J.connectionId,deliveryIds:J.deliveryIds,events:J.events});return G}class fx0{storage;notifySubscriber;running=!1;processing=!1;pendingNotify=!1;config;eventTriggerEngine;constructor(X,Y,G){this.storage=X;this.notifySubscriber=G??$W8(),this.config={...Ri1,...Y}}setEventTriggerEngine(X){this.eventTriggerEngine=X}async start(){if(this.running)return;await this.storage.resetStuckDeliveries();let X=await this.storage.findOrphanedCronEvents();for(let Y of X)await this.scheduleNextCronDelivery(Y);this.running=!0}stop(){this.running=!1}isRunning(){return this.running}async processNow(){if(!this.running)return;if(this.processing){this.pendingNotify=!0;return}this.processing=!0;try{do this.pendingNotify=!1,await this.processEvents();while(this.pendingNotify)}catch(X){console.error("[EventBus] Error processing events:",X)}finally{this.processing=!1}}async processEvents(){let X=await this.storage.claimPendingDeliveries(this.config.batchSize);if(X.length===0)return;let Y=L$7(X),G=await Promise.allSettled(Array.from(Y.entries()).map(async([W,Z])=>{let $=new Set;try{let H=await this.notifySubscriber(Z.connectionId,Z.events);if(H.results&&Object.keys(H.results).length>0)await this.processPerEventResults(Z,H);else if(H.success)await this.storage.markDeliveriesDelivered(Z.deliveryIds);else if(H.retryAfter&&H.retryAfter>0)await this.storage.scheduleRetryWithoutAttemptIncrement(Z.deliveryIds,H.retryAfter);else await this.storage.markDeliveriesFailed(Z.deliveryIds,H.error||"Subscriber returned success=false",this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}catch(H){if(H instanceof LW1){await this.storage.markDeliveriesPermanentlyFailed(Z.deliveryIds,H.message);for(let U of Z.events)$.add(U.id)}else{let U=H instanceof Error?H.message:String(H);console.error(`[EventBus] Failed to notify subscription ${W}:`,U),await this.storage.markDeliveriesFailed(Z.deliveryIds,U,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}let K=new Set;for(let H of X)if(Z.deliveryIds.includes(H.delivery.id))K.add(H.event.id);return{eventIds:K,permanentlyFailed:$}})),Q=new Set,J=new Set;for(let W of G)if(W.status==="fulfilled"){for(let Z of W.value.eventIds)Q.add(Z);for(let Z of W.value.permanentlyFailed)J.add(Z)}for(let W of Q)try{await this.storage.updateEventStatus(W);let Z=X.find(($)=>$.event.id===W)?.event;if(Z?.cron&&!J.has(W))await this.scheduleNextCronDelivery(Z)}catch(Z){console.error(`[EventBus] Failed to update event status ${W}:`,Z)}if(this.eventTriggerEngine){let W=new Set,Z=[];for(let $ of X){if($.delivery.attempts>0)continue;if(!W.has($.event.id))W.add($.event.id),Z.push({source:$.event.source,type:$.event.type,data:$.event.data,organizationId:$.event.organizationId})}if(Z.length>0)this.eventTriggerEngine.notifyEvents(Z)}}async processPerEventResults(X,Y){let G=[],Q=new Map,J=[],W=new Map;for(let Z=0;Z<X.events.length;Z++){let $=X.events?.[Z];if(!$)continue;let K=X.deliveryIds?.[Z];if(!K)continue;W.set($.id,K)}for(let Z of X.events){let $=W.get(Z.id);if(!$)continue;let K=Y.results?.[Z.id];if(K)if(K.success)G.push($);else if(K.retryAfter&&K.retryAfter>0){let H=Q.get(K.retryAfter)||[];H.push($),Q.set(K.retryAfter,H)}else J.push({deliveryId:$,error:K.error||"Event processing failed"});else if(Y.success)G.push($);else if(Y.retryAfter&&Y.retryAfter>0){let H=Q.get(Y.retryAfter)||[];H.push($),Q.set(Y.retryAfter,H)}else J.push({deliveryId:$,error:Y.error||"Batch processing failed"})}if(G.length>0)await this.storage.markDeliveriesDelivered(G);for(let[Z,$]of Q)await this.storage.scheduleRetryWithoutAttemptIncrement($,Z);if(J.length>0){let Z=new Map;for(let{deliveryId:$,error:K}of J){let H=Z.get(K)||[];H.push($),Z.set(K,H)}for(let[$,K]of Z)await this.storage.markDeliveriesFailed(K,$,this.config.maxAttempts,this.config.retryDelayMs,this.config.maxDelayMs)}}async scheduleNextCronDelivery(X){if(!X.cron)return;try{let G=new LL(X.cron,{timezone:"UTC"}).nextRun();if(!G)return;let Q=G.toISOString(),J=await this.storage.getMatchingSubscriptions(X);if(J.length===0)return;await this.storage.createDeliveries(X.id,J.map((W)=>W.id),Q)}catch(Y){console.error(`[EventBus] Failed to schedule next cron delivery for event ${X.id}:`,Y)}}}var FW8=w(()=>{Q31();vx0();_x0();KW8()});class bx0{storage;worker;notifyStrategy;running=!1;constructor(X){this.storage=X.storage,this.notifyStrategy=X.notifyStrategy,this.worker=new fx0(this.storage,X.config)}setEventTriggerEngine(X){this.worker.setEventTriggerEngine(X)}async publish(X,Y,G){if(G.deliverAt&&G.cron)throw Error("Cannot set both deliverAt and cron. Use one or the other.");let Q;if(G.cron){try{let U=new LL(G.cron,{timezone:"UTC"}).nextRun();if(!U)throw Error("Cron expression does not produce a next run time");Q=U.toISOString()}catch(H){throw Error(`Invalid cron expression: ${H instanceof Error?H.message:String(H)}`)}let K=await this.storage.findActiveCronEvent(X,G.type,Y,G.cron);if(K)return K}let J=crypto.randomUUID(),W=new Date().toISOString(),Z=await this.storage.publishEvent({id:J,organizationId:X,type:G.type,source:Y,subject:G.subject,time:W,data:G.data,cron:G.cron});zK.emit(X,JW8(Z));let $=await this.storage.getMatchingSubscriptions(Z);if($.length>0){let K=G.deliverAt??Q;await this.storage.createDeliveries(J,$.map((U)=>U.id),K);let H=K!=null&&new Date(K).getTime()<=Date.now();if(this.notifyStrategy&&(!K||H))await this.notifyStrategy.notify(J).catch((U)=>{console.warn("[EventBus] Notify failed (non-critical):",U)})}return Z}async subscribe(X,Y){return this.storage.subscribe({id:crypto.randomUUID(),organizationId:X,connectionId:Y.connectionId,publisher:Y.publisher,eventType:Y.eventType,filter:Y.filter})}async unsubscribe(X,Y){return this.storage.unsubscribe(Y,X)}async listSubscriptions(X,Y){return this.storage.listSubscriptions(X,Y)}async getSubscription(X,Y){return this.storage.getSubscription(Y,X)}async getEvent(X,Y){return this.storage.getEvent(Y,X)}async cancelEvent(X,Y,G){return this.storage.cancelEvent(Y,X,G)}async ackEvent(X,Y,G){return this.storage.ackDelivery(Y,X,G)}async syncSubscriptions(X,Y){return this.storage.syncSubscriptions({organizationId:X,...Y})}async start(){if(this.running)return;if(this.running=!0,await this.worker.start(),this.notifyStrategy)await this.notifyStrategy.start(()=>{this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing after notify:",X)})});await this.worker.processNow().catch((X)=>{console.error("[EventBus] Error processing pending events on startup:",X)})}async stop(){if(!this.running)return;if(this.running=!1,this.worker.stop(),this.notifyStrategy)try{await this.notifyStrategy.stop()}catch(X){console.error("[EventBus] Error stopping notify strategy:",X)}}isRunning(){return this.running}}var UW8=w(()=>{Q31();Mi1();FW8()});class yx0{options;sub=null;onNotify=null;encoder=new TextEncoder;constructor(X){this.options=X}async start(X){if(this.sub)return;if(X)this.onNotify=X;if(!this.onNotify)return;let Y=this.options.getConnection();if(!Y)return;this.sub=Y.subscribe("mesh.events.notify"),(async()=>{for await(let G of this.sub)this.onNotify?.()})().catch((G)=>{console.error("[NatsNotify] Subscription error:",G)})}async stop(){this.sub?.unsubscribe(),this.sub=null,this.onNotify=null}async notify(X){try{let Y=this.options.getConnection();if(!Y)return;Y.publish("mesh.events.notify",this.encoder.encode(X))}catch(Y){console.warn("[NatsNotify] Publish failed (non-critical):",Y)}}}class xx0{options;sub=null;localEmit=null;originId=crypto.randomUUID();encoder=new TextEncoder;constructor(X){this.options=X}async start(X){if(X)this.localEmit=X;if(this.sub)return;if(!this.localEmit)return;let Y=this.options.getConnection();if(!Y)return;this.sub=Y.subscribe("mesh.sse.broadcast");let G=new TextDecoder;(async()=>{for await(let Q of this.sub)try{let J=JSON.parse(G.decode(Q.data));if(typeof J?.originId!=="string"||typeof J?.organizationId!=="string"||typeof J?.event?.id!=="string"||typeof J?.event?.type!=="string")continue;if(J.originId===this.originId)continue;this.localEmit?.(J.organizationId,J.event)}catch{}})().catch((Q)=>{console.error("[NatsSSEBroadcast] Subscription error:",Q)})}broadcast(X,Y){this.localEmit?.(X,Y);let G={originId:this.originId,organizationId:X,event:Y};try{let Q=this.options.getConnection();if(!Q)return;Q.publish("mesh.sse.broadcast",this.encoder.encode(JSON.stringify(G)))}catch(Q){console.warn("[NatsSSEBroadcast] Publish failed (non-critical):",Q)}}async stop(){this.sub?.unsubscribe(),this.sub=null,this.localEmit=null}}function BW8(...X){return{async start(Y){await Promise.all(X.map((G)=>G.start(Y)))},async stop(){await Promise.all(X.map((Y)=>Y.stop().catch((G)=>{console.error("[NotifyStrategy] Error stopping strategy:",G)})))},async notify(Y){await Promise.all(X.map((G)=>G.notify(Y).catch((Q)=>{console.warn("[NotifyStrategy] Notify failed (non-critical):",Q)})))}}}class hx0{intervalMs;timer=null;onNotify=null;constructor(X){this.intervalMs=X}async start(X){if(this.timer)return;this.onNotify=X,this.scheduleNext()}async stop(){if(this.timer)clearTimeout(this.timer),this.timer=null;this.onNotify=null}async notify(X){if(this.onNotify)this.onNotify()}scheduleNext(){this.timer=setTimeout(()=>{if(this.onNotify)this.onNotify();if(this.timer)this.scheduleNext()},this.intervalMs)}}async function NW8(X,Y,G=5){for(let Q=1;Q<=G;Q++)try{await Y();return}catch(J){if(Q===G){console.error(`${X} Deferred start failed:`,J);return}let W=Math.min(1000*2**(Q-1),1e4);console.warn(`${X} Start attempt ${Q}/${G} failed, retrying in ${W}ms`),await new Promise((Z)=>setTimeout(Z,W))}}function zW8(X,Y,G){let Q=YW8(X.db),J=G?.pollIntervalMs??Ri1.pollIntervalMs,W=new yx0({getConnection:()=>Y.getConnection()}),Z=BW8(new hx0(J),W),$=new xx0({getConnection:()=>Y.getConnection()});return zK.start($).catch((K)=>{console.error("[SSEHub] Failed to start broadcast strategy:",K)}),Y.onReady(()=>{NW8("[NatsNotify]",()=>W.start()),NW8("[NatsSSEBroadcast]",()=>$.start())}),new bx0({storage:Q,config:G,notifyStrategy:Z})}var gx0=w(()=>{GW8();UW8();_x0();Mi1();Mi1()});var OW8=()=>{};var ux0=()=>{};var DW8=()=>{};var E$7,V9Q;var wW8=w(()=>{OW8();ux0();JA();DW8();E$7={br:".br",zstd:".zst",gzip:".gz"},V9Q=Object.keys(E$7)});var LW8=w(()=>{wW8()});var EW8=()=>{};var PW8=w(()=>{EW8()});var qW8=()=>{};var AW8=w(()=>{YI0()});var lx0=w(()=>{ZA();AW8()});var mx0="x-hono-disable-ssg",c9Q;var dx0=w(()=>{lx0();c9Q=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[mx0]:"true"}})}catch{return null}})()});var TW8=w(()=>{yV1()});var cx0=w(()=>{TW8()});var IW8=w(()=>{PW8();qW8();ux0();dx0();cx0();lx0()});var VW8=w(()=>{dx0();cx0();IW8()});var j7Q;var jW8=w(()=>{VW8();({write:j7Q}=Bun)});var A$7=class{#X;constructor(X){this.#X=X,this.raw=X.raw,this.url=X.url?new URL(X.url):null,this.protocol=X.protocol??null}send(X,Y){this.#X.send(X,Y??{})}raw;binaryType="arraybuffer";get readyState(){return this.#X.readyState}url;protocol;close(X,Y){this.#X.close(X,Y)}},MW8=(X)=>{return(...Y)=>{if(typeof Y[0]==="function"){let[G,Q]=Y;return async function(W,Z){let $=await G(W),K=await X(W,$,Q);if(K)return K;await Z()}}else{let[G,Q,J]=Y;return(async()=>{let W=await X(G,Q,J);if(!W)throw Error("Failed to upgrade WebSocket");return W})()}}};var RW8=()=>{};var EW1=(X)=>("server"in X.env)?X.env.server:X.env;var Si1=()=>{};var T$7;var SW8=w(()=>{RW8();Si1();T$7=MW8((X,Y)=>{let G=EW1(X);if(!G)throw TypeError("env has to include the 2nd argument of fetch.");if(G.upgrade(X.req.raw,{data:{events:Y,url:new URL(X.req.url),protocol:X.req.url}}))return new Response(null);return})});var ix0=(X)=>{let Y=EW1(X);if(!Y)throw TypeError("env has to include the 2nd argument of fetch.");if(typeof Y.requestIP!=="function")throw TypeError("server.requestIP is not a function.");let G=Y.requestIP(X.req.raw);if(!G)return{remote:{}};return{remote:{address:G.address,addressType:G.family==="IPv6"||G.family==="IPv4"?G.family:void 0,port:G.port}}};var kW8=w(()=>{Si1()});var CW8=w(()=>{LW8();jW8();SW8();kW8();Si1()});var vW8;var _W8=w(()=>{vW8={google:{name:"Google",icon:"https://assets.decocache.com/webdraw/eb7480aa-a68b-4ce4-98ff-36aa121762a7/google.svg"},github:{name:"GitHub",icon:"https://assets.decocache.com/decocms/e02ce92e-6684-41a6-acfc-432977eb4878/github.png"},microsoft:{name:"Microsoft",icon:"https://assets.decocache.com/mcp/aa6f6e1a-6526-4bca-99cc-82e2ec38b0e4/microsoft.png"}}});var Ci1={};T0(Ci1,{waitForSeed:()=>k$7,seedLocalMode:()=>M$7,markSeedComplete:()=>S$7,isLocalMode:()=>om,getLocalAdminUser:()=>px0,getLocalAdminPassword:()=>ki1});import{userInfo as I$7}from"os";async function ki1(){return u4().betterAuthSecret||"local-mode-default"}function fW8(){try{return I$7().username||"local"}catch{return"local"}}function V$7(X){return X.charAt(0).toUpperCase()+X.slice(1)}async function j$7(){let X=a7(),Y=await X.db.selectFrom("user").select(X.db.fn.countAll().as("count")).executeTakeFirst();return Number(Y?.count??0)===0}async function M$7(){if(!await j$7())return!1;let Y=fW8(),G=`${Y}@localhost.mesh`,Q=V$7(Y),J=await ki1(),W=await kY.api.signUpEmail({body:{email:G,password:J,name:Q}});if(!W?.user?.id)throw Error("Failed to create local admin user");let Z=W.user.id,$=a7();await $.db.updateTable("user").set({role:"admin"}).where("id","=",Z).execute();let K=`${Y}-local`.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),H=`${Q} Local`;return await $.db.updateTable("organization").set({name:H,slug:K}).where("id","in",(U)=>U.selectFrom("member").select("organizationId").where("userId","=",Z)).execute(),!0}async function px0(){let X=a7(),Y=`${fW8()}@localhost.mesh`;return X.db.selectFrom("user").where("email","=",Y).selectAll().executeTakeFirst()}function om(){return u4().localMode}function S$7(){bW8()}function k$7(){return R$7}var bW8,R$7;var es=w(()=>{ZU();l9();aR();R$7=new Promise((X)=>{if(bW8=X,!om())X()})});function yW8(){let X=Object.keys(r5.socialProviders??{}),Y=X.length>0,G=X.map((J)=>({name:J,icon:vW8[J].icon})),Q=u4().localMode;return{emailAndPassword:{enabled:r5.emailAndPassword?.enabled??!1},magicLink:{enabled:r5.magicLinkConfig?.enabled??!1},emailOtp:{enabled:r5.emailOtpConfig?.enabled??!1},resetPassword:{enabled:ji1},socialProviders:{enabled:Y,providers:G},sso:r5.ssoConfig?{enabled:!0,providerId:r5.ssoConfig.providerId}:{enabled:!1},stdioEnabled:Q,localMode:om()}}var PW1,xW8;var nx0=w(()=>{iX();CW8();CX();l9();aR();ZU();ZC0();hM0();_W8();es();PW1=new A6;PW1.post("/local-session",async(X)=>{if(!om())return X.json({success:!1,error:"Local mode is not active"},403);let Y;try{Y=ix0(X).remote.address}catch{}if(!(Y==="127.0.0.1"||Y==="::1"||Y==="::ffff:127.0.0.1"))return X.json({success:!1,error:"Forbidden"},403);try{let{waitForSeed:Q}=await Promise.resolve().then(() => (es(),Ci1));await Q();let{auth:J}=await Promise.resolve().then(() => (aR(),s38)),W=await px0();if(!W)return X.json({success:!1,error:"Local admin user not found"},500);let Z=await ki1();return await J.api.signInEmail({body:{email:W.email,password:Z},asResponse:!0})}catch(Q){return console.error("Failed to create local session:",Q),X.json({success:!1,error:Q instanceof Error?Q.message:"Failed to create local session"},500)}});PW1.get("/domain-lookup",async(X)=>{let Y=await kY.api.getSession({headers:X.req.raw.headers});if(!Y?.user)return X.json({success:!1,error:"Authentication required"},401);if(!Y.user.emailVerified)return X.json({found:!1});let G=Y.user.email?.split("@")[1]?.toLowerCase();if(!G||$T.has(G))return X.json({found:!1});try{let J=await new mw(a7().db).getByDomain(G);if(!J)return X.json({found:!1});let W=await a7().db.selectFrom("organization").select(["name","slug"]).where("id","=",J.organizationId).executeTakeFirst();return X.json({found:!0,autoJoinEnabled:J.autoJoinEnabled,organization:W?{name:W.name,slug:W.slug}:null})}catch(Q){return console.error("[Auth] Domain lookup failed:",Q),X.json({success:!1,error:"Domain lookup failed"},500)}});PW1.post("/domain-join",async(X)=>{let Y=await kY.api.getSession({headers:X.req.raw.headers});if(!Y?.user)return X.json({success:!1,error:"Authentication required"},401);if(!Y.user.emailVerified)return X.json({success:!1,error:"Email must be verified to join"},403);let G=Y.user.email?.split("@")[1]?.toLowerCase();if(!G||$T.has(G))return X.json({success:!1,error:"Generic email domains cannot auto-join"},403);try{let J=await new mw(a7().db).getByDomain(G);if(!J||!J.autoJoinEnabled)return X.json({success:!1,error:"Auto-join is not available for this domain"},403);let W=await a7().db.selectFrom("organization").select(["id","slug"]).where("id","=",J.organizationId).executeTakeFirst();if(!W)return X.json({success:!1,error:"Organization not found"},404);try{await kY.api.addMember({body:{userId:Y.user.id,role:"user",organizationId:W.id}})}catch(Z){if(!(Z instanceof Error?Z.message.toLowerCase():"").includes("already a member"))return console.error("[Auth] Domain join addMember failed:",Z),X.json({success:!1,error:"Failed to join organization"},500)}return M6.capture({distinctId:Y.user.id,event:"organization_domain_joined",groups:{organization:W.id},properties:{organization_id:W.id,organization_slug:W.slug,email_domain:G}}),X.json({success:!0,slug:W.slug})}catch(Q){return M6.captureException(Q,Y.user.id),console.error("[Auth] Domain join failed:",Q),X.json({success:!1,error:"Failed to join organization"},500)}});PW1.post("/domain-setup",async(X)=>{let Y=await kY.api.getSession({headers:X.req.raw.headers});if(!Y?.user)return X.json({success:!1,error:"Authentication required"},401);if(!Y.user.emailVerified)return X.json({success:!1,error:"Email must be verified"},403);let G=Y.user.email?.split("@")[1]?.toLowerCase();if(!G||$T.has(G))return X.json({success:!1,error:"Corporate email required"},403);try{let Q=a7().db,J=new mw(Q),W=await J.getByDomain(G);if(W){let N=await Q.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.slug"]).where("member.userId","=",Y.user.id).where("member.organizationId","=",W.organizationId).executeTakeFirst();if(N)return X.json({success:!0,slug:N.slug,alreadyExists:!0});return X.json({success:!1,error:"This domain is already claimed. Ask an admin for an invitation."},403)}let Z=G.split(".")[0]??G,$=Z.charAt(0).toUpperCase()+Z.slice(1),K=Z.toLowerCase().replace(/[^a-z0-9-]/g,""),H=null;for(let z=0;z<3;z++){let O=z===0?"":`-${Math.random().toString(36).slice(2,6)}`,D=z===0?$:`${$}${O}`,E=`${K}${O}`;try{H=await kY.api.createOrganization({body:{name:D,slug:E,userId:Y.user.id}});break}catch(P){if(!(P instanceof Error&&("body"in P)&&P.body?.code==="ORGANIZATION_ALREADY_EXISTS")||z===2)throw P}}if(!H?.id)throw Error("Failed to create organization");let U=H.id;try{await J.setDomain(U,G,!0)}catch(N){if(N instanceof Error&&N.message.includes("already claimed")){try{await kY.api.deleteOrganization({headers:X.req.raw.headers,body:{organizationId:U}})}catch{console.error("[Auth] Failed to clean up orphaned org after domain race:",U)}return X.json({success:!1,error:"This domain was just claimed by another user. Please refresh and try again."},409)}throw N}let B=!1;try{let N=u4().firecrawlApiKey;if(N){let z=await dS1(G,N,$);if(z){let O=new kJ1(a7().db),D=await O.create(U,z);await O.setDefault(D.id,U),B=!0;let E=z.favicon??z.logo??null,P={};if(z.name!==$)P.name=z.name;if(E)P.logo=E;if(Object.keys(P).length>0)await kY.api.updateOrganization({headers:X.req.raw.headers,body:{organizationId:U,data:P}})}}}catch(N){console.error("[Auth] Brand extraction failed (non-fatal):",N)}return M6.identify({distinctId:Y.user.id,properties:{email:Y.user.email,$set:{email:Y.user.email},$set_once:{first_organization_created_at:new Date().toISOString()}}}),M6.groupIdentify({groupType:"organization",groupKey:U,properties:{name:H.slug??K,slug:H.slug??K,email_domain:G,brand_extracted:B,created_at:new Date().toISOString()}}),M6.capture({distinctId:Y.user.id,event:"organization_created",groups:{organization:U},properties:{organization_id:U,organization_slug:H.slug??K,email_domain:G,brand_extracted:B}}),X.json({success:!0,slug:H.slug??K,brandExtracted:B})}catch(Q){return M6.captureException(Q,Y.user?.id),console.error("[Auth] Domain setup failed:",Q),X.json({success:!1,error:"Failed to set up organization"},500)}});xW8=PW1});function C$7(X){X.get("/status",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!await ax0(G,G.auth.user.id,Q))return Y.json({error:"Not a member of this organization"},403);let W=await G.storage.orgSsoConfig.getByOrgId(Q);if(!W||!W.enforced)return Y.json({ssoRequired:!1});let Z=await G.storage.orgSsoSessions.isValid(G.auth.user.id,Q);return Y.json({ssoRequired:!0,authenticated:Z,issuer:W.issuer,domain:W.domain})}),X.get("/authorize",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!await ax0(G,G.auth.user.id,Q))return Y.json({error:"Not a member of this organization"},403);let W=await G.storage.orgSsoConfig.getByOrgId(Q);if(!W)return Y.json({error:"SSO not configured for this organization"},404);let Z=await tx0(W.issuer,W.discoveryEndpoint),$=v$7(),K=await _$7($),H=crypto.randomUUID(),U=JSON.stringify({state:H,codeVerifier:$,orgId:Q,userId:G.auth.user.id});KI0(Y,"org_sso_state",U,{httpOnly:!0,secure:!0,sameSite:"Lax",path:"/api/org-sso/callback",maxAge:600});let B=new URLSearchParams({response_type:"code",client_id:W.clientId,redirect_uri:`${G.baseUrl}/api/org-sso/callback`,scope:W.scopes.join(" "),state:H,code_challenge:K,code_challenge_method:"S256"}),N=`${Z.authorization_endpoint}?${B.toString()}`;return Y.redirect(N)}),X.get("/callback",async(Y)=>{let G=Y.get("meshContext"),Q=Y.req.query("code"),J=Y.req.query("state"),W=Y.req.query("error");if(W)return Y.redirect(`/?sso_error=${encodeURIComponent(W)}`);if(!Q||!J)return Y.redirect("/?sso_error=missing_code_or_state");let Z=cV1(Y,"org_sso_state");if(!Z)return Y.redirect("/?sso_error=state_expired");KI0(Y,"org_sso_state","",{httpOnly:!0,secure:!0,sameSite:"Lax",path:"/api/org-sso/callback",maxAge:0});let $;try{$=JSON.parse(Z)}catch{return Y.redirect("/?sso_error=invalid_state")}if($.state!==J)return Y.redirect("/?sso_error=state_mismatch");if(!G.auth.user||G.auth.user.id!==$.userId)return Y.redirect("/?sso_error=session_expired");let K=await G.storage.orgSsoConfig.getByOrgId($.orgId);if(!K)return Y.redirect("/?sso_error=sso_not_configured");let H=await tx0(K.issuer,K.discoveryEndpoint),U=await fetch(H.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Q,redirect_uri:`${G.baseUrl}/api/org-sso/callback`,client_id:K.clientId,client_secret:K.clientSecret,code_verifier:$.codeVerifier})});if(!U.ok)return console.error("[org-sso] Token exchange failed:",await U.text()),Y.redirect("/?sso_error=token_exchange_failed");let B=await U.json();if(!B.id_token)return Y.redirect("/?sso_error=no_id_token");try{let O=lI(new URL(H.jwks_uri)),{payload:D}=await f7(B.id_token,O,{issuer:K.issuer,audience:K.clientId}),E=D.email?.toLowerCase(),P=G.auth.user.email?.toLowerCase();if(!E||E!==P)return console.error(`[org-sso] Email mismatch: token=${E}, user=${P}`),Y.redirect("/?sso_error=email_mismatch")}catch(O){return console.error("[org-sso] ID token verification failed:",O),Y.redirect("/?sso_error=token_verification_failed")}await G.storage.orgSsoSessions.upsert(G.auth.user.id,$.orgId);let N=await ax0(G,G.auth.user.id,$.orgId),z=N?.orgSlug?`/${N.orgSlug}`:"/";return Y.redirect(z)}),X.get("/config",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!f$7(G))return Y.json({error:"Admin role required"},403);let J=await G.storage.orgSsoConfig.getByOrgId(Q);if(!J)return Y.json({configured:!1});return Y.json({configured:!0,config:G.storage.orgSsoConfig.toPublic(J)})}),X.post("/config",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!rx0(G))return Y.json({error:"Owner role required"},403);let J=await Y.req.json();if(!J.issuer||!J.clientId||!J.domain)return Y.json({error:"issuer, clientId, and domain are required"},400);let W=await G.storage.orgSsoConfig.getByOrgId(Q);if(!W&&!J.clientSecret)return Y.json({error:"clientSecret is required for initial SSO setup"},400);let Z=J.clientSecret||W?.clientSecret||"";try{await tx0(J.issuer,J.discoveryEndpoint)}catch(K){return Y.json({error:"Failed to reach OIDC discovery endpoint",details:K instanceof Error?K.message:String(K)},400)}let $=await G.storage.orgSsoConfig.upsert(Q,{issuer:J.issuer,clientId:J.clientId,clientSecret:Z,discoveryEndpoint:J.discoveryEndpoint,scopes:J.scopes,domain:J.domain,enforced:J.enforced});return Y.json({success:!0,config:G.storage.orgSsoConfig.toPublic($)})}),X.post("/config/enforce",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!rx0(G))return Y.json({error:"Owner role required"},403);let J=await Y.req.json();if(!await G.storage.orgSsoConfig.getByOrgId(Q))return Y.json({error:"SSO must be configured before enforcing"},400);return await G.storage.orgSsoConfig.setEnforced(Q,J.enforced),Y.json({success:!0,enforced:J.enforced})}),X.delete("/config",async(Y)=>{let G=Y.get("meshContext");if(!G.auth.user)return Y.json({error:"Authentication required"},401);let Q=G.organization?.id;if(!Q)return Y.json({error:"Organization context required"},400);if(!rx0(G))return Y.json({error:"Owner role required"},403);return await G.storage.orgSsoConfig.delete(Q),Y.json({success:!0})})}function vi1(X){let Y;try{Y=new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}let G=u4().localMode;if(Y.protocol!=="https:"&&!(G&&Y.protocol==="http:"))throw Error(`OIDC URL must use HTTPS: ${X}`);let Q=Y.hostname,J=[/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^0\./,/^\[::1\]$/,/^\[fd/,/^\[fe80:/,/^localhost$/i],W=/^127\.|^\[::1\]$|^localhost$/i.test(Q);if(G&&W)return;for(let Z of J)if(Z.test(Q))throw Error(`OIDC URL must not point to a private network address: ${Q}`)}async function tx0(X,Y){let G=Y||X,Q=hW8.get(G);if(Q&&Q.expiresAt>Date.now())return Q.doc;let J=Y||`${X.replace(/\/$/,"")}/.well-known/openid-configuration`;vi1(J);let W=await fetch(J);if(!W.ok)throw Error(`OIDC discovery failed: ${W.status} ${W.statusText}`);let Z=await W.json();if(!Z.authorization_endpoint||!Z.token_endpoint||!Z.jwks_uri)throw Error("OIDC discovery document missing required endpoints");return vi1(Z.authorization_endpoint),vi1(Z.token_endpoint),vi1(Z.jwks_uri),hW8.set(G,{doc:Z,expiresAt:Date.now()+3600000}),Z}function v$7(){let X=new Uint8Array(32);return crypto.getRandomValues(X),btoa(String.fromCharCode(...X)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _$7(X){let G=new TextEncoder().encode(X),Q=await crypto.subtle.digest("SHA-256",G);return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ax0(X,Y,G){return await X.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.slug as orgSlug","member.role"]).where("member.userId","=",Y).where("member.organizationId","=",G).executeTakeFirst()??null}function f$7(X){let Y=X.auth.user?.role;if(!Y)return!1;return ko.includes(Y)}function rx0(X){return X.auth.user?.role==="owner"}var _i1=()=>{let X=new A6;return C$7(X),X},hW8;var ox0=w(()=>{iX();HI0();RJ();l9();vJ1();hW8=new Map});function gW8(X){let Y=X.filter((Q)=>Q.role==="system"),G=X.find((Q)=>Q.role!=="system");return{systemMessages:Y,requestMessage:G}}function b$7(X){let Y=!1,G=X.map((Q)=>{if(Q.role!=="assistant")return Q;if(!Q.parts.some((W)=>("state"in W)&&W.state==="approval-requested"))return Q;return Y=!0,{...Q,parts:Q.parts.map((W)=>{if(!("state"in W)||W.state!=="approval-requested"||!("approval"in W)||!W.approval)return W;return{...W,state:"output-denied",approval:{...W.approval,approved:!1,reason:"User sent a new message without approving this tool call."}}})}});return Y?G:X}function y$7(X){let[Y,G]=X.reduce((Q,J)=>{if(J.role==="system")Q[0].push(J);else Q[1].push(J);return Q},[[],[]]);return{systemMessages:Y,messages:G}}async function x$7(X,Y){return await X.loadHistory(Y)}function h$7(X,Y){let G=X.filter((W)=>W.parts&&W.parts.length>0);if(!Y)return G;let Q=G.findIndex((W)=>W.id===Y.id);return Q>=0?[...G.slice(0,Q),Y]:[...G,Y]}async function uW8(X,Y,G,Q){let J=await x$7(X,Q),W=h$7(J,Y);return[...G,...W]}async function lW8(X,Y){let G=X.filter((U)=>U.role!=="assistant"||U.parts&&U.parts.length>0),Q=await j31({messages:G}),J=b$7(Q),W=await V31(J,{tools:Y.tools,ignoreIncompleteToolCalls:!0}),{systemMessages:Z,messages:$}=y$7(W),H=d_0({messages:$,reasoning:"all",emptyMessages:"remove",toolCalls:"none"}).map((U)=>{if(U.role!=="assistant")return U;let B=Array.isArray(U.content)?U.content.filter((N)=>N.type!=="reasoning"&&N.type!=="thinking"&&N.type!=="redacted-reasoning").map((N)=>{let z=N;if("providerOptions"in z||"providerMetadata"in z){let{providerOptions:O,providerMetadata:D,...E}=z;if(z.type==="tool-call"){let P=D?.google,q=O?.google;return{...E,...P?{providerMetadata:{google:P}}:{},...q?{providerOptions:{google:q}}:{}}}return E}return N}):U.content;return{...U,content:Array.isArray(B)&&B.length===0?[{type:"text",text:""}]:B,providerOptions:void 0,providerMetadata:void 0}});return{systemMessages:Z,messages:H,originalMessages:Q}}var sx0=w(()=>{xX()});function OK(X){return`mesh-storage://${X}`}function sm(X){if(!X.startsWith("mesh-storage://"))return null;return X.slice(15)}function ex0(){return/mesh-storage:\/\/([^\s"'<>[\]]+)/g}function g$7(X,Y,G){return`${X}/api/${Y}/files/${G}`}function l$7(X){return X.type==="file"&&"mediaType"in X&&typeof X.mediaType==="string"&&u$7.has(X.mediaType)}function mW8(X){let Y=X.match(/^data:([^;]+);base64,(.+)$/s);if(!Y)return null;let[,G,Q]=Y;try{let J=atob(Q),W=new Uint8Array(J.length);for(let Z=0;Z<J.length;Z++)W[Z]=J.charCodeAt(Z);return{mimeType:G,bytes:W}}catch{return null}}function dW8(X){return{"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","application/pdf":"pdf","text/plain":"txt","text/html":"html","application/json":"json"}[X]??"bin"}async function cW8(X,Y,G,Q){if(!Q.objectStorage)return null;try{return await Q.objectStorage.put(Y,X,{contentType:G}),Y}catch(J){return console.error("[file-materializer] Failed to upload file:",J),null}}async function em(X,Y){if(!Y.objectStorage)return null;try{return await Y.objectStorage.presignedGetUrl(X,m$7)}catch(G){return console.error("[file-materializer] Failed to generate presigned URL:",G),null}}async function iW8(X,Y){if(!Y.organization)return X;let G=Y.organization.slug;if(!G)return X;let Q=X.findLastIndex((O)=>O.role==="user");if(Q===-1)return X;let J=X[Q],W=J.parts.filter((O)=>O.type==="file"&&("url"in O)&&typeof O.url==="string"&&O.url.startsWith("data:"));if(W.length===0)return X;let $=(await Promise.all(W.map(async(O)=>{if(O.type!=="file"||!("url"in O)||typeof O.url!=="string")return null;let D=mW8(O.url);if(!D)return null;let E=dW8(D.mimeType),P=`chat-uploads/${crypto.randomUUID()}.${E}`,q=await cW8(D.bytes,P,D.mimeType,Y);if(!q)return null;let j="filename"in O&&typeof O.filename==="string"?O.filename:P;return{dataUrl:O.url,meshStorageUrl:OK(q),redirectUrl:g$7(Y.baseUrl,G,q),filename:j}}))).filter((O)=>O!==null);if($.length===0)return X;let H=`[Uploaded files \u2014 use these URLs when calling tools]
|
|
7149
7149
|
${$.map((O)=>`- ${O.filename}: ${O.meshStorageUrl}`).join(`
|
|
7150
7150
|
`)}`,U=new Map($.map((O)=>[O.dataUrl,O.meshStorageUrl])),B=J.parts.map((O)=>{if(O.type!=="file"||!("url"in O)||typeof O.url!=="string")return O;let D=U.get(O.url);if(!D)return O;return{...O,url:D}}),N=B.findIndex((O)=>O.type==="text"),z;if(N!==-1)z=B.map((O,D)=>{if(D!==N||O.type!=="text")return O;return{...O,text:`${H}
|
|
7151
7151
|
|
|
@@ -7179,7 +7179,7 @@ Preview:
|
|
|
7179
7179
|
${E}`}}return{contents:[{uri:J,mimeType:N.contentType||"text/markdown",text:z}]}}catch(N){return{result:`Failed to read resource: ${N instanceof Error?N.message:String(N)}`}}}let $=(await Y.readResource({uri:J})).contents;if(!$||$.length===0)return{result:"Resource returned no content."};let K=$.map((B)=>{if("text"in B&&B.text!==void 0)return{uri:B.uri,mimeType:B.mimeType,text:B.text};if("blob"in B&&B.blob!==void 0)return{uri:B.uri,mimeType:B.mimeType,blob:`[binary data, ${B.blob.length} bytes base64]`};return{uri:B.uri,mimeType:B.mimeType}}),H=JSON.stringify(K,null,2),U=nW(H);if(U>XO){let B=`resource_${Date.now()}`;G.set(B,H);let N=LZ(H);return{result:`Resource content too large (${U} tokens). Use read_tool_output with tool_call_id "${B}" to extract specific data.
|
|
7180
7180
|
|
|
7181
7181
|
Preview:
|
|
7182
|
-
${N}`}}return{contents:K}}})}var K$8=w(()=>{xX();K0();CL()});function MW1(X,Y){let G;try{G=typeof X==="string"?X:JSON.stringify(X,null,2)}catch{G=String(X)}let Q=nW(G);if(Q>XO){let J=`vm_${Date.now()}`;Y.set(J,G);let W=LZ(G);return{truncated:!0,message:`Output too large (${Q} tokens). Use read_tool_output with tool_call_id "${J}" to extract specific data.`,preview:W}}return X}var H$8=w(()=>{CL()});function T$8(){return"Execute a shell command in the VM's project directory. Working directory is the project root. Timeout default 30s, max 2min.\n\nPre-installed skills live at `/mnt/skills/public/<name>/SKILL.md`. Run `ls /mnt/skills/public/` for the index and `cat /mnt/skills/public/<name>/SKILL.md` before using one. Skills cover common file operations: pptx (PowerPoint), docx (Word), xlsx (Excel), pdf, file-reading (router).\n\nTo bring chat attachments / presigned URLs into the sandbox FS use `copy_to_sandbox` (NOT bash + curl). To deliver a file you produced back to the user as a download chip, use `share_with_user`."}var F$8,U$8,B$8,N$8,z$8,O$8,D$8,w$8,L$8,E$8="Write content to a file in the VM's project directory. Creates parent directories if needed. Overwrites existing files entirely.",P$8="Perform exact string replacement in a file in the VM. old_string must be unique in the file unless replace_all is true.",q$8="Search file contents in the VM using ripgrep. Supports regex patterns, file type filtering via glob, and context lines.",A$8="Find files by name pattern in the VM's project directory. Uses ripgrep for gitignore-aware matching. Returns relative file paths.",I$8,V$8="Upload a file from the sandbox FS back to the user's chat as a download chip on this turn. Use this for artifacts the user should be able to save (CSV reports, generated decks, zipped builds, etc). The file lands under the current thread's outputs prefix; the UI surfaces it automatically when the turn finishes.",vL;var j$8=w(()=>{K0();F$8=F.object({path:F.string().describe("File path. Relative paths resolve against the project root (e.g. 'src/index.ts'); absolute paths are accepted for files outside the project (e.g. '/home/sandbox/deck.thumbnail.jpg')."),offset:F.number().optional().describe("Starting line number for text files (1-based, default 1)"),limit:F.number().optional().describe("Max lines to return for text files (default 2000)")}),U$8=F.object({path:F.string().describe("File path relative to project root"),content:F.string().describe("The full file content to write")}),B$8=F.object({path:F.string().describe("File path relative to project root"),old_string:F.string().describe("The exact text to find and replace"),new_string:F.string().describe("The replacement text (must differ from old_string)"),replace_all:F.boolean().optional().describe("Replace all occurrences (default false)")}),N$8=F.object({pattern:F.string().describe("Regex pattern to search for"),path:F.string().optional().describe("Directory or file to search in (default: project root)"),glob:F.string().optional().describe("Glob pattern to filter files (e.g. '*.ts', '*.{js,jsx}')"),context:F.number().optional().describe("Lines of context around matches"),ignore_case:F.boolean().optional().describe("Case-insensitive search"),output_mode:F.enum(["content","files","count"]).optional().describe("Output mode (default: 'files')"),limit:F.number().optional().describe("Max result lines (default 250)")}),z$8=F.object({pattern:F.string().describe("Glob pattern to match files (e.g. '**/*.ts', 'src/**/*.test.tsx')"),path:F.string().optional().describe("Directory to search in (default: project root)")}),O$8=F.object({command:F.string().describe("The bash command to execute"),timeout:F.number().optional().describe("Timeout in milliseconds (default 30000, max 120000)")}),D$8=F.object({url:F.string().describe("Org-scoped storage reference. Accepts a mesh-storage:// URI from chat (e.g. mesh-storage://chat-uploads/abc.pdf) or a bare key (e.g. chat-uploads/abc.pdf). Arbitrary http(s):// URLs are NOT "+"accepted \u2014 for public URLs use the bash tool with curl."),target:F.string().describe("Destination path on the sandbox FS (relative to project root). Parent directories are created as needed.")}),w$8=F.object({source:F.string().describe("Path to a file on the sandbox FS to share back to the user. Must be a single file (not a directory)."),name:F.string().optional().describe("Filename to surface in the chat UI (default: basename of source). Cannot contain slashes.")}),L$8="Read a file. For text files, returns content with line numbers (use offset and limit for large files). For images (jpeg, png, gif, webp), the image "+"is injected into the next turn as a vision input \u2014 do NOT describe what "+"you 'expect' to see, just call read and look at the next message. Other binary formats are not supported; use a format-specific skill (e.g. pptx-extract for .pptx).";I$8="Copy a chat-attached or org-storage file into the sandbox filesystem at `target`. Use this BEFORE running format-specific skills (pptx-extract, pdf, docx, ...) on user-uploaded files. Accepts "+"mesh-storage:// URIs and bare org-storage keys only \u2014 for arbitrary "+"public URLs use bash + curl. Bytes stream directly from S3 to the sandbox; they do not pass through the model.",vL={read:!1,write:!0,edit:!0,grep:!1,glob:!1,bash:!0,copy_to_sandbox:!1,share_with_user:!1}});import ZK7 from"path";async function WK7(X,Y){if(X.startsWith("https://")||X.startsWith("http://"))throw Error("copy_to_sandbox does not accept arbitrary URLs \u2014 pass a "+"mesh-storage:// URI or a bare org storage key. For public URLs, use the bash tool (curl).");let G=X.startsWith(M$8)?X.slice(M$8.length):X;if(!G||G.startsWith("/")||G.includes(".."))throw Error(`Invalid source: ${X}`);let Q=Y.objectStorage;if(!Q)throw Error("Object storage is not configured for this org");return Q.presignedGetUrl(G)}function $K7(X){let Y=X.trim();if(!Y)return null;if(Y.includes("/")||Y.includes("\\"))return null;if(Y==="."||Y===".."||Y.includes(".."))return null;if(Y.length>255)return null;return Y}function KK7(X,Y,G){let Q=G.split("/").map(encodeURIComponent).join("/");return`${X}/api/${encodeURIComponent(Y)}/files/${Q}`}async function HK7(X,Y,G,Q,J="POST"){let W;try{let K={method:J,headers:new Headers({"content-type":"application/json"}),body:null};if(J!=="GET"&&Q!==null)K.body=Buffer.from(JSON.stringify(Q),"utf-8").toString("base64");W=await X.proxyDaemonRequest(Y,G,K)}catch{throw Error("The sandbox is not running. Ask the user to start it by clicking the server button (left side of the header bar).")}let Z=await W.text(),$;try{$=JSON.parse(Z)}catch{console.error("[vm-tools] Failed to parse JSON response runner=%s path=%s status=%d rawText=%s",X.kind,G,W.status,Z.slice(0,2000));let K=W.status>=500?" (server error)":W.status===0?" (no response)":"";throw Error(`Daemon ${G} returned invalid JSON (HTTP ${W.status}${K}): ${Z.slice(0,800)}`)}if(!W.ok)throw console.error("[vm-tools] Non-OK response runner=%s path=%s status=%d body=%s",X.kind,G,W.status,Z.slice(0,2000)),Error($.error??`Daemon ${G} failed (${W.status})`);return $}function R$8(X){let{runner:Y,ensureHandle:G,toolOutputMap:Q,needsApproval:J,pendingImages:W,ctx:Z,threadId:$}=X,K=(q)=>q?J:!1,H=async(q,j,M="POST")=>{let I=await G();return HK7(Y,I,q,j,M)},U=J8({needsApproval:K(vL.read),description:L$8,inputSchema:n1(F$8),execute:async(q)=>{let j=await H("/_decopilot_vm/read",q);if(j.kind==="image")return W.push({url:`data:${j.mediaType};base64,${j.base64}`,mediaType:j.mediaType,label:`[Image at ${q.path}]`}),{kind:"image",path:q.path,mediaType:j.mediaType,size:j.size,message:"Image attached below."};return MW1(j,Q)}}),B=J8({needsApproval:K(vL.write),description:E$8,inputSchema:n1(U$8),execute:async(q)=>H("/_decopilot_vm/write",q)}),N=J8({needsApproval:K(vL.edit),description:P$8,inputSchema:n1(B$8),execute:async(q)=>H("/_decopilot_vm/edit",q)}),z=J8({needsApproval:K(vL.grep),description:q$8,inputSchema:n1(N$8),execute:async(q)=>{let j=await H("/_decopilot_vm/grep",q);return MW1(j,Q)}}),O=J8({needsApproval:K(vL.glob),description:A$8,inputSchema:n1(z$8),execute:async(q)=>{let j=await H("/_decopilot_vm/glob",q);return MW1(j,Q)}}),D=J8({needsApproval:K(vL.bash),description:T$8(),inputSchema:n1(O$8),execute:async(q)=>{let j=await H("/_decopilot_vm/bash",q);return MW1(j,Q)}}),E=J8({needsApproval:K(vL.copy_to_sandbox),description:I$8,inputSchema:n1(D$8),execute:async(q)=>{let j=await WK7(q.url,Z);return await H("/_decopilot_vm/write_from_url",{url:j,path:q.target})}}),P=J8({needsApproval:K(vL.share_with_user),description:V$8,inputSchema:n1(w$8),execute:async(q)=>{let j=Z.organization?.id,M=Z.objectStorage;if(!j||!M)throw Error("Object storage is not configured for this org");let I=$K7(q.name??ZK7.basename(q.source));if(!I)throw Error(`Invalid filename: ${q.name??q.source}`);let R=`model-outputs/${$}/${I}`,C=await M.presignedPutUrl(R);return await H("/_decopilot_vm/upload_to_url",{path:q.source,url:C}),{key:R,filename:I,downloadUrl:KK7(Z.baseUrl,j,R)}}});return{read:U,write:B,edit:N,grep:z,glob:O,bash:D,copy_to_sandbox:E,share_with_user:P}}var M$8="mesh-storage://";var S$8=w(()=>{xX();H$8();j$8()});function zK7(X){let Y=[NK7];if(X?.trim())Y.push(X);return Y}function k$8(X,Y,G){let{provider:Q,organization:J,models:W,needsApproval:Z}=Y;return J8({description:UK7,inputSchema:n1(FK7),needsApproval:Z,execute:async function*({prompt:$,agent_id:K},{abortSignal:H,toolCallId:U}){let B=performance.now(),N=await G.storage.virtualMcps.findById(K,J.id);if(!N||N.organization_id!==J.id)throw Error("Agent not found");if(N.status!=="active")throw Error("Agent is not active");let z=await nR(N,G,"passthrough"),{tools:O}=await yi1(z,new Map,X,"auto",{disableOutputTruncation:!0}),D=Object.fromEntries(Object.entries(O).filter(([I])=>!GC6.includes(I))),E=z.getInstructions(),P=zK7(E),q=vF0(),j=pz({model:mi1(Q,W.thinking),system:P.map((I)=>({role:"system",content:I})),prompt:$,tools:D,abortSignal:H,stopWhen:cz(YC6),maxOutputTokens:W.thinking.limits?.maxOutputTokens??uR1,onStepFinish:({usage:I,providerMetadata:R})=>{q=_F0(q,{...I,providerMetadata:R})},onAbort:()=>{console.error(`[subtask:${K}] Aborted`),z.close().catch(()=>{})},onError:(I)=>{console.error(`[subtask:${K}] Error`,I)}});for await(let I of u_0({stream:j.toUIMessageStream()}))yield I;let M=performance.now()-B;X.write({type:"data-tool-metadata",id:U,data:{annotations:BK7,latencyMs:M}}),X.write({type:"data-tool-subtask-metadata",id:U,data:{usage:q,agent:K,models:W}})},toModelOutput:({output:$})=>{return{type:"text",value:$?.parts?.findLast((H)=>("type"in H)&&H.type==="text"&&("text"in H))?.text??"Subtask completed (no output)."}}})}var FK7,UK7,BK7,NK7=`You are a focused subtask agent delegated a specific task by a parent agent. You are NOT the parent agent.
|
|
7182
|
+
${N}`}}return{contents:K}}})}var K$8=w(()=>{xX();K0();CL()});function MW1(X,Y){let G;try{G=typeof X==="string"?X:JSON.stringify(X,null,2)}catch{G=String(X)}let Q=nW(G);if(Q>XO){let J=`vm_${Date.now()}`;Y.set(J,G);let W=LZ(G);return{truncated:!0,message:`Output too large (${Q} tokens). Use read_tool_output with tool_call_id "${J}" to extract specific data.`,preview:W}}return X}var H$8=w(()=>{CL()});function T$8(){return"Execute a shell command in the VM's project directory. Working directory is the project root. Timeout default 30s, max 2min.\n\nPre-installed skills live at `/mnt/skills/public/<name>/SKILL.md`. Run `ls /mnt/skills/public/` for the index and `cat /mnt/skills/public/<name>/SKILL.md` before using one. Skills cover common file operations: pptx (PowerPoint), docx (Word), xlsx (Excel), pdf, file-reading (router).\n\nTo bring chat attachments / presigned URLs into the sandbox FS use `copy_to_sandbox` (NOT bash + curl). To deliver a file you produced back to the user as a download chip, use `share_with_user`."}var F$8,U$8,B$8,N$8,z$8,O$8,D$8,w$8,L$8,E$8="Write content to a file in the VM's project directory. Creates parent directories if needed. Overwrites existing files entirely.",P$8="Perform exact string replacement in a file in the VM. old_string must be unique in the file unless replace_all is true.",q$8="Search file contents in the VM using ripgrep. Supports regex patterns, file type filtering via glob, and context lines.",A$8="Find files by name pattern in the VM's project directory. Uses ripgrep for gitignore-aware matching. Returns relative file paths.",I$8,V$8="Upload a file from the sandbox FS back to the user's chat as a download chip on this turn. Use this for artifacts the user should be able to save (CSV reports, generated decks, zipped builds, etc). The file lands under the current thread's outputs prefix; the UI surfaces it automatically when the turn finishes.",vL;var j$8=w(()=>{K0();F$8=F.object({path:F.string().describe("File path. Relative paths resolve against the project root (e.g. 'src/index.ts'); absolute paths are accepted for files outside the project (e.g. '/home/sandbox/deck.thumbnail.jpg')."),offset:F.number().optional().describe("Starting line number for text files (1-based, default 1)"),limit:F.number().optional().describe("Max lines to return for text files (default 2000)")}),U$8=F.object({path:F.string().describe("File path relative to project root"),content:F.string().describe("The full file content to write")}),B$8=F.object({path:F.string().describe("File path relative to project root"),old_string:F.string().describe("The exact text to find and replace"),new_string:F.string().describe("The replacement text (must differ from old_string)"),replace_all:F.boolean().optional().describe("Replace all occurrences (default false)")}),N$8=F.object({pattern:F.string().describe("Regex pattern to search for"),path:F.string().optional().describe("Directory or file to search in (default: project root)"),glob:F.string().optional().describe("Glob pattern to filter files (e.g. '*.ts', '*.{js,jsx}')"),context:F.number().optional().describe("Lines of context around matches"),ignore_case:F.boolean().optional().describe("Case-insensitive search"),output_mode:F.enum(["content","files","count"]).optional().describe("Output mode (default: 'files')"),limit:F.number().optional().describe("Max result lines (default 250)")}),z$8=F.object({pattern:F.string().describe("Glob pattern to match files (e.g. '**/*.ts', 'src/**/*.test.tsx')"),path:F.string().optional().describe("Directory to search in (default: project root)")}),O$8=F.object({command:F.string().describe("The bash command to execute"),timeout:F.number().optional().describe("Timeout in milliseconds (default 30000, max 120000)")}),D$8=F.object({url:F.string().describe("Org-scoped storage reference. Accepts a mesh-storage:// URI from chat (e.g. mesh-storage://chat-uploads/abc.pdf) or a bare key (e.g. chat-uploads/abc.pdf). Arbitrary http(s):// URLs are NOT "+"accepted \u2014 for public URLs use the bash tool with curl."),target:F.string().describe("Destination path on the sandbox FS (relative to project root). Parent directories are created as needed.")}),w$8=F.object({source:F.string().describe("Path to a file on the sandbox FS to share back to the user. Must be a single file (not a directory)."),name:F.string().optional().describe("Filename to surface in the chat UI (default: basename of source). Cannot contain slashes.")}),L$8="Read a file. For text files, returns content with line numbers (use offset and limit for large files). For images (jpeg, png, gif, webp), the image "+"is injected into the next turn as a vision input \u2014 do NOT describe what "+"you 'expect' to see, just call read and look at the next message. Other binary formats are not supported; use a format-specific skill (e.g. pptx-extract for .pptx).";I$8="Copy a chat-attached or org-storage file into the sandbox filesystem at `target`. Use this BEFORE running format-specific skills (pptx-extract, pdf, docx, ...) on user-uploaded files. Accepts "+"mesh-storage:// URIs and bare org-storage keys only \u2014 for arbitrary "+"public URLs use bash + curl. Bytes stream directly from S3 to the sandbox; they do not pass through the model.",vL={read:!1,write:!0,edit:!0,grep:!1,glob:!1,bash:!0,copy_to_sandbox:!1,share_with_user:!1}});import ZK7 from"path";async function WK7(X,Y){if(X.startsWith("https://")||X.startsWith("http://"))throw Error("copy_to_sandbox does not accept arbitrary URLs \u2014 pass a "+"mesh-storage:// URI or a bare org storage key. For public URLs, use the bash tool (curl).");let G=X.startsWith(M$8)?X.slice(M$8.length):X;if(!G||G.startsWith("/")||G.includes(".."))throw Error(`Invalid source: ${X}`);let Q=Y.objectStorage;if(!Q)throw Error("Object storage is not configured for this org");return Q.presignedGetUrl(G)}function $K7(X){let Y=X.trim();if(!Y)return null;if(Y.includes("/")||Y.includes("\\"))return null;if(Y==="."||Y===".."||Y.includes(".."))return null;if(Y.length>255)return null;return Y}function KK7(X,Y,G){let Q=G.split("/").map(encodeURIComponent).join("/");return`${X}/api/${encodeURIComponent(Y)}/files/${Q}`}async function HK7(X,Y,G,Q,J="POST"){let W;try{let K={method:J,headers:new Headers({"content-type":"application/json"}),body:null};if(J!=="GET"&&Q!==null)K.body=Buffer.from(JSON.stringify(Q),"utf-8").toString("base64");W=await X.proxyDaemonRequest(Y,G,K)}catch{throw Error("The sandbox is not running. Ask the user to start it by clicking the server button (left side of the header bar).")}let Z=await W.text(),$;try{$=JSON.parse(Z)}catch{console.error("[vm-tools] Failed to parse JSON response runner=%s path=%s status=%d rawText=%s",X.kind,G,W.status,Z.slice(0,2000));let K=W.status>=500?" (server error)":W.status===0?" (no response)":"";throw Error(`Daemon ${G} returned invalid JSON (HTTP ${W.status}${K}): ${Z.slice(0,800)}`)}if(!W.ok)throw console.error("[vm-tools] Non-OK response runner=%s path=%s status=%d body=%s",X.kind,G,W.status,Z.slice(0,2000)),Error($.error??`Daemon ${G} failed (${W.status})`);return $}function R$8(X){let{runner:Y,ensureHandle:G,toolOutputMap:Q,needsApproval:J,pendingImages:W,ctx:Z,threadId:$}=X,K=(q)=>q?J:!1,H=async(q,j,M="POST")=>{let I=await G();return HK7(Y,I,q,j,M)},U=J8({needsApproval:K(vL.read),description:L$8,inputSchema:n1(F$8),execute:async(q)=>{let j=await H("/_decopilot_vm/read",q);if(j.kind==="image")return W.push({url:`data:${j.mediaType};base64,${j.base64}`,mediaType:j.mediaType,label:`[Image at ${q.path}]`}),{kind:"image",path:q.path,mediaType:j.mediaType,size:j.size,message:"Image attached below."};return MW1(j,Q)}}),B=J8({needsApproval:K(vL.write),description:E$8,inputSchema:n1(U$8),execute:async(q)=>H("/_decopilot_vm/write",q)}),N=J8({needsApproval:K(vL.edit),description:P$8,inputSchema:n1(B$8),execute:async(q)=>H("/_decopilot_vm/edit",q)}),z=J8({needsApproval:K(vL.grep),description:q$8,inputSchema:n1(N$8),execute:async(q)=>{let j=await H("/_decopilot_vm/grep",q);return MW1(j,Q)}}),O=J8({needsApproval:K(vL.glob),description:A$8,inputSchema:n1(z$8),execute:async(q)=>{let j=await H("/_decopilot_vm/glob",q);return MW1(j,Q)}}),D=J8({needsApproval:K(vL.bash),description:T$8(),inputSchema:n1(O$8),execute:async(q)=>{let j=await H("/_decopilot_vm/bash",q);return MW1(j,Q)}}),E=J8({needsApproval:K(vL.copy_to_sandbox),description:I$8,inputSchema:n1(D$8),execute:async(q)=>{let j=await WK7(q.url,Z);return await H("/_decopilot_vm/write_from_url",{url:j,path:q.target})}}),P=J8({needsApproval:K(vL.share_with_user),description:V$8,inputSchema:n1(w$8),execute:async(q)=>{let j=Z.organization?.slug,M=Z.objectStorage;if(!j||!M)throw Error("Object storage is not configured for this org");let I=$K7(q.name??ZK7.basename(q.source));if(!I)throw Error(`Invalid filename: ${q.name??q.source}`);let R=`model-outputs/${$}/${I}`,C=await M.presignedPutUrl(R);return await H("/_decopilot_vm/upload_to_url",{path:q.source,url:C}),{key:R,filename:I,downloadUrl:KK7(Z.baseUrl,j,R)}}});return{read:U,write:B,edit:N,grep:z,glob:O,bash:D,copy_to_sandbox:E,share_with_user:P}}var M$8="mesh-storage://";var S$8=w(()=>{xX();H$8();j$8()});function zK7(X){let Y=[NK7];if(X?.trim())Y.push(X);return Y}function k$8(X,Y,G){let{provider:Q,organization:J,models:W,needsApproval:Z}=Y;return J8({description:UK7,inputSchema:n1(FK7),needsApproval:Z,execute:async function*({prompt:$,agent_id:K},{abortSignal:H,toolCallId:U}){let B=performance.now(),N=await G.storage.virtualMcps.findById(K,J.id);if(!N||N.organization_id!==J.id)throw Error("Agent not found");if(N.status!=="active")throw Error("Agent is not active");let z=await nR(N,G,"passthrough"),{tools:O}=await yi1(z,new Map,X,"auto",{disableOutputTruncation:!0}),D=Object.fromEntries(Object.entries(O).filter(([I])=>!GC6.includes(I))),E=z.getInstructions(),P=zK7(E),q=vF0(),j=pz({model:mi1(Q,W.thinking),system:P.map((I)=>({role:"system",content:I})),prompt:$,tools:D,abortSignal:H,stopWhen:cz(YC6),maxOutputTokens:W.thinking.limits?.maxOutputTokens??uR1,onStepFinish:({usage:I,providerMetadata:R})=>{q=_F0(q,{...I,providerMetadata:R})},onAbort:()=>{console.error(`[subtask:${K}] Aborted`),z.close().catch(()=>{})},onError:(I)=>{console.error(`[subtask:${K}] Error`,I)}});for await(let I of u_0({stream:j.toUIMessageStream()}))yield I;let M=performance.now()-B;X.write({type:"data-tool-metadata",id:U,data:{annotations:BK7,latencyMs:M}}),X.write({type:"data-tool-subtask-metadata",id:U,data:{usage:q,agent:K,models:W}})},toModelOutput:({output:$})=>{return{type:"text",value:$?.parts?.findLast((H)=>("type"in H)&&H.type==="text"&&("text"in H))?.text??"Subtask completed (no output)."}}})}var FK7,UK7,BK7,NK7=`You are a focused subtask agent delegated a specific task by a parent agent. You are NOT the parent agent.
|
|
7183
7183
|
|
|
7184
7184
|
## Rules (non-negotiable)
|
|
7185
7185
|
|
|
@@ -7281,7 +7281,7 @@ ${$.map(([H,{name:U,totalCount:B,preview:N}])=>{let z=B-N.length,O=N.join(", ")+
|
|
|
7281
7281
|
<available-prompts>
|
|
7282
7282
|
${Y.map((Q)=>{let J=`${Q.name}|${Q.description??""}`;if(Q.arguments&&Q.arguments.length>0){let W=Q.arguments.map((Z)=>Z.required?`${Z.name} (required)`:Z.name).join(", ");J+=`|args: ${W}`}return J}).join(`
|
|
7283
7283
|
`)}
|
|
7284
|
-
</available-prompts>`}async function ii1(X){let Y=X.stream.getReader();while(!0){let{done:G}=await Y.read();if(G)break}}var ci1,cK7=5;var RW1=w(()=>{CX();cZ1();X$8();Y$8();q7();xX();K0();t$8();r$8();vR();sx0();qW1();TW1();s$8();GK8();J31();ZK8();VS1();vS1();lw();T$();di1();ez();ci1=X1(x0(),1)});async function WK8(X,Y,G,Q){let{storage:J,streamBuffer:W,sseHub:Z}=Q,K=(await J.get(X,Y))?.virtual_mcp_id??void 0;await J.update(X,Y,{status:G,run_owner_pod:null,run_config:null,run_started_at:null}),W.purge(X),Z.emit(Y,Dj(X,G,K)),Z.emit(Y,_71(X,G))}async function tK7(X,Y){let{storage:G,streamBuffer:Q,sseHub:J}=Y;switch(X.type){case"RUN_STARTED":{if(!await G.claimRunStart(X.taskId,X.orgId,{status:"in_progress",run_owner_pod:X.podId??null,run_config:X.runConfig??null,run_started_at:X.podId?new Date().toISOString():null},X.podId??null))throw new pi1(X.taskId);let Z=await G.get(X.taskId,X.orgId);J.emit(X.orgId,Dj(X.taskId,"in_progress",Z?.virtual_mcp_id??void 0));return}case"RUN_RESUMED":{await G.update(X.taskId,X.orgId,{run_owner_pod:X.podId,run_started_at:new Date().toISOString()});let W=await G.get(X.taskId,X.orgId);J.emit(X.orgId,Dj(X.taskId,"in_progress",W?.virtual_mcp_id??void 0));return}case"STEP_COMPLETED":J.emit(X.orgId,Pq1(X.taskId,X.stepCount));return;case"RUN_COMPLETED":await WK8(X.taskId,X.orgId,"completed",Y);return;case"RUN_REQUIRES_ACTION":await WK8(X.taskId,X.orgId,"requires_action",Y);return;case"RUN_FAILED":{if(X.reason==="ghost"){if(!await G.forceFailIfInProgress(X.taskId,X.orgId))return;await G.update(X.taskId,X.orgId,{run_owner_pod:null,run_config:null,run_started_at:null})}else await G.update(X.taskId,X.orgId,{status:"failed",run_owner_pod:null,run_config:null,run_started_at:null});Q.purge(X.taskId);let W=await G.get(X.taskId,X.orgId);J.emit(X.orgId,Dj(X.taskId,"failed",W?.virtual_mcp_id??void 0)),J.emit(X.orgId,_71(X.taskId,"failed"));return}case"PREVIOUS_RUN_ABORTED":return}}async function $K8(X,Y){for(let{event:G}of X)await tK7(G,Y)}var pi1;var Hh0=w(()=>{q7();pi1=class pi1 extends Error{constructor(X){super(`Failed to claim run for thread ${X} \u2014 already running on another pod`);this.name="RunClaimError"}}});async function KK8(X){let Y=fi1(X),G=await X.req.json(),Q=sW8.safeParse(G);if(!Q.success)throw new E5(400,{message:Q.error.message});let{messages:J,...W}=Q.data,Z=J,{systemMessages:$,requestMessage:K}=gW8(Z);return{organization:Y,systemMessages:$,requestMessage:K,...W}}async function HK8(X,Y){let G=await X.storage.aiProviderKeys.list({organizationId:Y});if(G.length===0)throw new E5(400,{message:"No AI provider credentials configured for this organization"});let Q=G[0],J=await X.aiProviders.listModels(Q.id,Y);if(J.length===0)throw new E5(400,{message:"No models available from the configured AI provider"});let W=J[0];return{credentialId:Q.id,thinking:{id:W.modelId,title:W.title}}}function Fh0(X){let{cancelBroadcast:Y,streamBuffer:G,runRegistry:Q,threadStorage:J}=X,W=new A6;return W.get("/:org/decopilot/allowed-models",async(Z)=>{try{let $=Z.get("meshContext"),K=fi1(Z),H=$.auth.user?.role,U=await QB($.db,K.id,H);return Z.json(Ih6(U))}catch($){if(console.error("[decopilot:allowed-models] Error",$),$ instanceof E5)return Z.json({error:$.message},$.status);return Z.json({error:$ instanceof Error?$.message:"Internal error"},500)}}),W.post("/:org/decopilot/stream",async(Z)=>{try{let $=Z.get("meshContext"),{organization:K,models:H,agent:U,systemMessages:B,requestMessage:N,temperature:z,memory:O,thread_id:D,branch:E,toolApprovalLevel:P,mode:q}=await KK8(Z),j=$.auth?.user?.id;if(!j)throw new E5(401,{message:"User ID is required"});let M=H??await HK8($,K.id),I=await QB($.db,K.id,$.auth.user?.role);if(I!==void 0&&!UT(I,M.credentialId,M.thinking.id))throw new E5(403,{message:"Model not allowed for your role"});let R=O?.windowSize??CR,C=D??O?.thread_id,_=await _L({messages:[...B,N],models:M,agent:U,temperature:z,toolApprovalLevel:P,mode:q,organizationId:K.id,userId:j,taskId:C,windowSize:R,branch:E??null},$,{runRegistry:Q,streamBuffer:G,cancelBroadcast:Y});return M6.capture({distinctId:j,event:"chat_message_started",groups:{organization:K.id},properties:{organization_id:K.id,agent_id:U,mode:q,thread_id:C,credential_id:M.credentialId}}),wT({stream:_.stream,consumeSseStream:iz})}catch($){if(console.error("[decopilot:stream] Error",$),$ instanceof E5)return Z.json({error:$.message},$.status);if($ instanceof Error&&$.name==="AbortError")return console.warn("[decopilot:stream] Aborted",{error:$.message}),Z.json({error:"Request aborted"},400);return M6.captureException($),console.error("[decopilot:stream] Failed",{error:$ instanceof Error?$.message:JSON.stringify($),stack:$ instanceof Error?$.stack:void 0}),Z.json({error:$ instanceof Error?$.message:JSON.stringify($)},500)}}),W.post("/:org/decopilot/runtime/stream",async(Z)=>{try{let $=Z.get("meshContext"),{organization:K,models:H,agent:U,systemMessages:B,requestMessage:N,temperature:z,memory:O,thread_id:D,branch:E,toolApprovalLevel:P,mode:q}=await KK8(Z),j=$.auth?.user?.id;if(!j)throw new E5(401,{message:"User ID is required"});let M=H??await HK8($,K.id),I=await QB($.db,K.id,$.auth.user?.role);if(I!==void 0&&!UT(I,M.credentialId,M.thinking.id))throw new E5(403,{message:"Model not allowed for your role"});let R=O?.windowSize??CR,C=D??O?.thread_id,_=await _L({messages:[...B,N],models:M,agent:U,temperature:z,toolApprovalLevel:P,mode:q,organizationId:K.id,userId:j,taskId:C,windowSize:R,branch:E??null},$,{runRegistry:Q,streamBuffer:G,cancelBroadcast:Y});return wT({stream:_.stream,consumeSseStream:iz})}catch($){if(console.error("[decopilot:stream] Error",$),$ instanceof pi1)return Z.json({error:$.message},409);if($ instanceof E5)return Z.json({error:$.message},$.status);if($ instanceof Error&&$.name==="AbortError")return console.warn("[decopilot:stream] Aborted",{error:$.message}),Z.json({error:"Request aborted"},400);return console.error("[decopilot:stream] Failed",{error:$ instanceof Error?$.message:JSON.stringify($),stack:$ instanceof Error?$.stack:void 0}),Z.json({error:$ instanceof Error?$.message:JSON.stringify($)},500)}}),W.post("/:org/decopilot/cancel/:threadId",async(Z)=>{let{taskId:$,thread:K,organization:H}=await rW8(Z);if((await Q.execute({type:"CANCEL",taskId:$})).some((B)=>B.event.type==="RUN_FAILED"))return Z.json({cancelled:!0});if(Y.broadcast($),K.status==="in_progress")console.warn("[decopilot:cancel] Ghost run detected, force-failing",{taskId:$}),Q.execute({type:"FORCE_FAIL",taskId:$,reason:"ghost",orgId:H.id}).catch((B)=>{console.error("[decopilot:cancel] Failed to force-fail ghost thread",{taskId:$,err:B})});return Z.json({cancelled:!0,async:!0},202)}),W.get("/:org/decopilot/attach/:threadId",async(Z)=>{try{let{taskId:$,thread:K,organization:H}=await Zh0(Z);if(Q.isRunning($)){let P=await G.createReplayStream($);if(!P)return Z.body(null,204);let q=I31({execute:async({writer:j})=>{let M=P.getReader();try{while(!0){let{done:I,value:R}=await M.read();if(I)break;j.write(R)}}finally{M.releaseLock()}}});return wT({stream:q,consumeSseStream:iz})}let U=Z.get("meshContext"),B=U.auth?.user?.id;if(K.status!=="in_progress")return Z.body(null,204);if(K.created_by!==B)return Z.body(null,204);if(!K.run_config)return await J.forceFailIfInProgress($,H.id),Z.body(null,204);let N=xi1.safeParse(K.run_config);if(!N.success)return await J.forceFailIfInProgress($,H.id),Z.body(null,204);let z=N.data,O=await QB(U.db,H.id,U.auth.user?.role);if(O!==void 0&&!UT(O,z.models.credentialId,z.models.thinking.id))throw new E5(403,{message:"Model not allowed for your role"});if(!await J.claimOrphanedRun($,H.id,Xd()))return Z.body(null,204);let E=await _L({messages:[],models:hi1(z.models),agent:z.agent,temperature:z.temperature,toolApprovalLevel:z.toolApprovalLevel,mode:z.mode,organizationId:H.id,userId:B,taskId:$,windowSize:z.windowSize,isResume:!0},U,{runRegistry:Q,streamBuffer:G,cancelBroadcast:Y});return wT({stream:E.stream,consumeSseStream:iz})}catch($){if($ instanceof E5)throw $;return console.error("[decopilot:attach] Error",$),Z.body(null,500)}}),W}var FK8=w(()=>{CX();xX();iX();gw();vR();sx0();TW1();J31();Wh0();eW8();RW1();Hh0();di1()});var UK8=w(()=>{FK8()});var ni1=()=>{let X=new A6;return X.post("/connections/:connectionId/oauth-token",async(Y)=>{let G=Y.get("meshContext"),Q=Y.req.param("connectionId");if(!(G.auth.user?.id??G.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);let W=G.organization?.id;if(!W)return Y.json({error:"Organization context required"},403);let Z=await G.storage.connections.findById(Q,W);if(!Z)return Y.json({error:"Connection not found"},404);let $=await Y.req.json();if(!$.accessToken)return Y.json({error:"accessToken is required"},400);if($.tokenEndpoint){let z;try{z=new URL($.tokenEndpoint)}catch{return Y.json({error:"tokenEndpoint must be a valid URL"},400)}if(z.protocol!=="http:"&&z.protocol!=="https:")return Y.json({error:"tokenEndpoint must be an http(s) URL"},400)}let K=$.expiresIn?new Date(Date.now()+$.expiresIn*1000):null,H=$.tokenEndpoint??null;if(H?.includes("/oauth-proxy/")&&Z.connection_url)try{let z=await yS1(Z.connection_url);if(z)try{let O=new URL(z);if(O.protocol==="http:"||O.protocol==="https:")H=z}catch{}}catch{}let U=new V3(G.db,G.vault),B={connectionId:Q,accessToken:$.accessToken,refreshToken:$.refreshToken??null,scope:$.scope??null,expiresAt:K,clientId:$.clientId??null,clientSecret:$.clientSecret??null,tokenEndpoint:H},N=await U.upsert(B);return Y.json({success:!0,expiresAt:N.expiresAt})}),X.delete("/connections/:connectionId/oauth-token",async(Y)=>{let G=Y.get("meshContext"),Q=Y.req.param("connectionId");if(!(G.auth.user?.id??G.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);let W=G.organization?.id;if(!W)return Y.json({error:"Organization context required"},403);if(!await G.storage.connections.findById(Q,W))return Y.json({error:"Connection not found"},404);return await new V3(G.db,G.vault).delete(Q),Y.json({success:!0})}),X.get("/connections/:connectionId/oauth-token/status",async(Y)=>{let G=Y.get("meshContext"),Q=Y.req.param("connectionId");if(!(G.auth.user?.id??G.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);let W=G.organization?.id;if(!W)return Y.json({error:"Organization context required"},403);if(!await G.storage.connections.findById(Q,W))return Y.json({error:"Connection not found"},404);let $=new V3(G.db,G.vault),K=await $.get(Q);if(!K)return Y.json({hasToken:!1,isExpired:!0,canRefresh:!1});let H=$.isExpired(K),U=!!K.refreshToken&&!!K.tokenEndpoint;return Y.json({hasToken:!0,isExpired:H,canRefresh:U,expiresAt:K.expiresAt})}),X};var Uh0=w(()=>{iX();Bk0();pR()});var eY=async(X,Y)=>{await Y();let Q=(X.req.matchedRoutes??[]).find((W)=>W.method!=="ALL"&&!W.path.endsWith("*"));if(!Q||Q.path.startsWith("/api/:org/"))return;let J=X.get("meshContext");console.log("deprecated route",{route:X.req.routePath,method:X.req.method,org:J?.organization?.slug,user:J?.auth?.user?.id,ua:X.req.header("user-agent")})};var Qe=async(X,Y)=>{let G=X.req.param("org");if(!G)return X.json({error:"org slug missing in path"},400);let Q=X.get("meshContext");if(!Q?.db)return X.json({error:"meshContext not initialized"},500);let J=Q.db,W=await J.selectFrom("organization").select(["id","slug","name"]).where("slug","=",G).executeTakeFirst();if(!W)return X.json({error:`organization "${G}" not found`},404);let Z=Q.auth?.user?.id,$;if(Z){let K=await J.selectFrom("member").select(["role"]).where("userId","=",Z).where("organizationId","=",W.id).executeTakeFirst();if(!K)return X.json({error:"forbidden: not a member of organization"},403);$=K.role}if(Q.organization={id:W.id,slug:W.slug,name:W.name,role:$},Q.access.setOrganizationId(W.id),Q.access.setRole($),Q.storage.threads.setOrganizationId(W.id),!Q.objectStorage){let K=Qr();Q.objectStorage=K?fS1(K,W.id):new yZ1(W.id,Q.baseUrl)}return await Y()};var Bh0=w(()=>{Zk0();kV1()});async function fL(X,Y,G){let Q=await fetch(`${X}/rest/v1/${G}`,{headers:{apikey:Y,Authorization:`Bearer ${Y}`,Accept:"application/json"}});if(!Q.ok){let J=await Q.text().catch(()=>Q.statusText);throw console.error(`[deco-sites] Supabase error (${Q.status}): ${J}`),Error(`External service error (${Q.status})`)}return Q.json()}async function Je(X,Y,G,Q){let J=await fetch(`${X}/rest/v1/${G}`,{method:"POST",headers:{apikey:Y,Authorization:`Bearer ${Y}`,"Content-Type":"application/json",Accept:"application/json",Prefer:"return=representation"},body:JSON.stringify(Q)});if(!J.ok){let Z=await J.text().catch(()=>J.statusText);throw console.error(`[deco-sites] Supabase POST error (${J.status}): ${Z}`),Error(`External service error (${J.status})`)}let W=await J.json();if(!W[0])throw Error("Supabase POST returned no rows");return W[0]}function Nh0(){let X=u4(),Y=X.decoSupabaseUrl,G=X.decoSupabaseServiceKey;if(!Y||!G)return null;return{supabaseUrl:Y,serviceKey:G}}async function zh0(X,Y,G){return(await fL(X,Y,`profiles?email=eq.${encodeURIComponent(G)}&select=user_id`))[0]?.user_id??null}async function BK8(X,Y,G){let Q=await fL(X,Y,`api_key?user_id=eq.${encodeURIComponent(G)}&select=id&limit=1`);if(Q[0]?.id)return Q[0].id;return(await Je(X,Y,"api_key",{user_id:G})).id}function oK7(X){return`${aK7}${X}@${rK7}`}async function sK7(X,Y,G){return(await fL(X,Y,`sites?name=eq.${encodeURIComponent(G)}&select=team&limit=1`))[0]?.team??null}async function eK7(X,Y,G){let Q=await fetch(`${X}/auth/v1/admin/users`,{method:"POST",headers:{apikey:Y,Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({email:G,email_confirm:!0,app_metadata:{mesh_service_account:!0}})});if(!Q.ok){let W=await Q.text().catch(()=>Q.statusText);throw console.error(`[deco-sites] Auth admin create user error (${Q.status}): ${W}`),Error(`Failed to create auth user (${Q.status})`)}return(await Q.json()).id}async function XH7(X,Y,G){let Q=oK7(G),J=await fL(X,Y,`profiles?email=eq.${encodeURIComponent(Q)}&select=user_id&limit=1`);if(J[0]?.user_id){let K=J[0].user_id;if(!(await fL(X,Y,`members?user_id=eq.${encodeURIComponent(K)}&team_id=eq.${G}&select=id&limit=1`))[0]?.id){let U=await Je(X,Y,"members",{user_id:K,team_id:G,admin:!0});await Je(X,Y,"member_roles",{member_id:U.id,role_id:1})}return BK8(X,Y,K)}let W=await eK7(X,Y,Q);if(!(await fL(X,Y,`profiles?user_id=eq.${encodeURIComponent(W)}&select=user_id&limit=1`))[0])await Je(X,Y,"profiles",{user_id:W,email:Q,name:`Mesh Service Account (team ${G})`});let $=await Je(X,Y,"members",{user_id:W,team_id:G,admin:!0});return await Je(X,Y,"member_roles",{member_id:$.id,role_id:1}),BK8(X,Y,W)}async function YH7(X){try{let Y=await fetch(`https://${X}/favicon.ico`,{signal:AbortSignal.timeout(5000)});if(!Y.ok)return null;let G=Y.headers.get("content-type")??"image/x-icon",Q=await Y.arrayBuffer();if(Q.byteLength===0)return null;let J=Buffer.from(Q).toString("base64");return`data:${G};base64,${J}`}catch{return null}}var aK7="deco-team-",rK7="deco.cx",zK8=async(X,Y)=>{if(!X.get("meshContext").auth.user?.id)return X.json({error:"Unauthorized"},401);return Y()},NK8="https://sites-admin-mcp.decocache.com/api/mcp",OK8=()=>{let X=new A6;return X.use("*",zK8),X.get("/profile",async(Y)=>{let Q=Y.get("meshContext").auth.user?.email;if(!Q)return Y.json({error:"Unauthorized"},401);let J=Nh0();if(!J)return Y.json({isDecoUser:!1});try{let W=await zh0(J.supabaseUrl,J.serviceKey,Q);return Y.json({isDecoUser:W!==null})}catch{return Y.json({isDecoUser:!1})}}),X},ti1=()=>{let X=new A6;return X.use("*",zK8),X.get("/",async(Y)=>{let Q=Y.get("meshContext").auth.user?.email;if(!Q)return Y.json({error:"Unauthorized"},401);let J=Nh0();if(!J)return Y.json({sites:[]});let{supabaseUrl:W,serviceKey:Z}=J;try{let $=await zh0(W,Z,Q);if(!$)return Y.json({sites:[]});let H=(await fL(W,Z,`members?user_id=eq.${encodeURIComponent($)}&deleted_at=is.null&select=team_id`)).map((B)=>B.team_id).filter((B)=>Number.isInteger(B));if(H.length===0)return Y.json({sites:[]});let U=await fL(W,Z,`sites?team=in.(${H.join(",")})&select=name,domains,thumb_url&order=id`);return Y.json({sites:U})}catch($){return console.error("[deco-sites] GET error:",$),Y.json({error:"Failed to fetch sites"},502)}}),X.post("/connection",async(Y)=>{let G=Y.get("meshContext"),Q=G.auth.user?.email,J=H6(G);if(!Q||!J)return Y.json({error:"Unauthorized"},401);let W;try{W=await Y.req.json()}catch{return Y.json({error:"Invalid request body"},400)}let{siteName:Z,orgId:$}=W;if(!Z||!$)return Y.json({error:"siteName and orgId are required"},400);let K=m7("conn");if(!/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(Z))return Y.json({error:"Invalid siteName"},400);if(!await G.db.selectFrom("member").select("member.id").where("member.userId","=",J).where("member.organizationId","=",$).executeTakeFirst())return Y.json({error:"Forbidden"},403);let U=Nh0();if(!U)return Y.json({error:"Deco integration is not configured"},503);let{supabaseUrl:B,serviceKey:N}=U;try{let z=await zh0(B,N,Q);if(!z)return Y.json({error:"No deco.cx account found for this user"},404);let O=await sK7(B,N,Z);if(!O)return Y.json({error:"Site not found or has no team"},404);if(!(await fL(B,N,`members?user_id=eq.${encodeURIComponent(z)}&team_id=eq.${O}&deleted_at=is.null&select=id&limit=1`))[0])return Y.json({error:"You are not a member of this site's team"},403);let E=await XH7(B,N,O),P=await UA({id:`pending-${K}`,title:`deco.cx \u2014 ${Z}`,connection_type:"HTTP",connection_url:NK8,connection_token:E}).catch(()=>null),q=P?.tools?.length?P.tools:null,j=P?.scopes?.length?P.scopes:null,M=await YH7(`${Z}.deco.site`),I=await G.storage.connections.create({id:K,organization_id:$,created_by:J,title:`deco.cx \u2014 ${Z}`,description:`Admin MCP for deco.cx site: ${Z}`,connection_type:"HTTP",connection_url:NK8,connection_token:E,connection_headers:null,oauth_config:null,configuration_state:{SITE_NAME:Z},metadata:{source:"deco.cx-import"},icon:null,app_name:"deco.cx",app_id:null,tools:q,configuration_scopes:j});return Y.json({connId:I.id,icon:M})}catch(z){return console.error("[deco-sites] POST /connection error:",z),Y.json({error:"Failed to create connection"},500)}}),X};var Oh0=w(()=>{iX();kH();bG1();l9()});import{createHmac as GH7}from"crypto";import{mkdir as QH7,writeFile as JH7}from"fs/promises";import{dirname as ZH7,join as LK8}from"path";function $H7(X){let Y=X.replace(/[^a-zA-Z0-9_-]/g,"_");return LK8(WH7,Y)}function KH7(X){return X.replace(/^\/+/,"").replace(/\.\./g,"")}function DK8(X,Y){let G=$H7(X),Q=KH7(Y);return LK8(G,Q)}function wK8(X,Y,G,Q,J){let W=u4().encryptionKey||"dev-secret",Z=`${X}:${Y}:${G}:${Q}`,$=GH7("sha256",W).update(Z).digest("hex");return J===$}function Dh0(X){let Y=X.split(".").pop()?.toLowerCase()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",bmp:"image/bmp",pdf:"application/pdf",json:"application/json",xml:"application/xml",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",md:"text/markdown",js:"application/javascript",mjs:"application/javascript",ts:"application/typescript",mp4:"video/mp4",webm:"video/webm",avi:"video/x-msvideo",mov:"video/quicktime",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf"}[Y]||"application/octet-stream"}var WH7="./data/assets",ai1=(X)=>{let Y=new A6,G=X.orgFromPath?"/*":"/:orgId/*";return Y.get(G,async(Q)=>{let J=X.orgFromPath?Q.get("meshContext")?.organization?.id:Q.req.param("orgId");if(!J)return Q.json({error:"Missing organization context"},500);let W=X.orgFromPath?`/api/${Q.req.param("org")??""}/dev-assets/`:`/api/dev-assets/${J}/`,Z=Q.req.path.replace(W,"");if(!Z)return Q.json({error:"Missing key"},400);let $=Q.req.query("expires"),K=Q.req.query("signature"),H=Q.req.query("method");if(!$||!K||H!=="GET")return Q.json({error:"Invalid or missing signature parameters"},400);let U=parseInt($,10);if(!Number.isFinite(U))return Q.json({error:"Invalid expires parameter"},400);let B=Math.floor(Date.now()/1000);if(U<B)return Q.json({error:"URL has expired"},403);if(!wK8(J,Z,U,"GET",K))return Q.json({error:"Invalid signature"},403);let N=DK8(J,Z);try{let z=Bun.file(N);if(!await z.exists())return Q.json({error:"File not found"},404);let D=Dh0(Z);return new Response(z.stream(),{headers:{"Content-Type":D,"Content-Length":z.size.toString(),"Cache-Control":"private, max-age=3600"}})}catch(z){return console.error("Error serving file:",z),Q.json({error:"Failed to read file"},500)}}),Y.put(G,async(Q)=>{let J=X.orgFromPath?Q.get("meshContext")?.organization?.id:Q.req.param("orgId");if(!J)return Q.json({error:"Missing organization context"},500);let W=X.orgFromPath?`/api/${Q.req.param("org")??""}/dev-assets/`:`/api/dev-assets/${J}/`,Z=Q.req.path.replace(W,"");if(!Z)return Q.json({error:"Missing key"},400);let $=Q.req.query("expires"),K=Q.req.query("signature"),H=Q.req.query("method");if(!$||!K||H!=="PUT")return Q.json({error:"Invalid or missing signature parameters"},400);let U=parseInt($,10);if(!Number.isFinite(U))return Q.json({error:"Invalid expires parameter"},400);let B=Math.floor(Date.now()/1000);if(U<B)return Q.json({error:"URL has expired"},403);if(!wK8(J,Z,U,"PUT",K))return Q.json({error:"Invalid signature"},403);let N=DK8(J,Z),z=ZH7(N);try{await QH7(z,{recursive:!0});let O=await Q.req.arrayBuffer();return await JH7(N,Buffer.from(O)),Q.json({success:!0,key:Z})}catch(O){return console.error("Error saving file:",O),Q.json({error:"Failed to save file"},500)}}),Y};var ri1=w(()=>{iX();l9()});var EK8="Payload Too Large",PK8,oi1=(X)=>{let Y=X.onError||(()=>{let Q=new Response(EK8,{status:413});throw new E5(413,{res:Q})}),G=X.maxSize;return async function(J,W){if(!J.req.raw.body)return W();let Z=J.req.raw.headers.has("transfer-encoding"),$=J.req.raw.headers.has("content-length");if($&&!Z)return parseInt(J.req.raw.headers.get("content-length")||"0",10)>G?Y(J):W();let K=0,H=J.req.raw.body.getReader(),B={body:new ReadableStream({async start(N){try{for(;;){let{done:z,value:O}=await H.read();if(z)break;if(K+=O.length,K>G){N.error(new PK8(EK8));break}N.enqueue(O)}}finally{N.close()}}}),duplex:"half"};if(J.req.raw=new Request(J.req.raw,B),await W(),J.error instanceof PK8)J.res=await Y(J)}};var wh0=w(()=>{gw();PK8=class extends Error{constructor(X){super(X);this.name="BodyLimitError"}}});function si1(X){let Y=new A6;return Y.get("/kv/:key",async(G)=>{let J=G.get("meshContext").organization?.id;if(!J)return G.json({error:"Organization required"},400);let W=G.req.param("key"),Z=await X.kvStorage.get(J,W);if(Z===null)return G.json({error:"Not found"},404);return G.json({key:W,value:Z})}),Y.put("/kv/:key",oi1({maxSize:HH7,onError:(G)=>G.json({error:"Payload too large"},413)}),async(G)=>{let J=G.get("meshContext").organization?.id;if(!J)return G.json({error:"Organization required"},400);let W=G.req.param("key"),Z;try{Z=await G.req.json()}catch{return G.json({error:"Invalid JSON body"},400)}return await X.kvStorage.set(J,W,Z),G.json({ok:!0})}),Y.delete("/kv/:key",async(G)=>{let J=G.get("meshContext").organization?.id;if(!J)return G.json({error:"Organization required"},400);let W=G.req.param("key");return await X.kvStorage.delete(J,W),G.json({ok:!0})}),Y}var HH7=1048576;var Lh0=w(()=>{iX();wh0()});var ei1=()=>{let X=new A6;return X.all("/",async(Y)=>{let G=await $s(Y.get("meshContext")),Q=new iH({enableJsonResponse:Y.req.raw.headers.get("Accept")?.includes("application/json")??!1});return await G.connect(Q),Q.handleRequest(Y.req.raw)}),X};var Eh0=w(()=>{iX();Ws();Js()});var Xp1=()=>{let X=new A6;return X.get("/threads/:threadId/outputs",async(Y)=>{let G=Y.get("meshContext");if(!G.auth?.user?.id)throw new E5(401,{message:"Unauthorized"});let J=G.organization?.id;if(!J)throw new E5(400,{message:"Organization required"});let W=Y.req.param("threadId");if(!W||!/^[A-Za-z0-9_-]+$/.test(W))throw new E5(400,{message:"Invalid thread ID"});if(!await G.storage.threads.get(W))throw new E5(404,{message:"Thread not found"});let $=G.objectStorage;if(!$)return Y.json({objects:[]});let K=await $.list({prefix:`model-outputs/${W}/`,maxKeys:200});return Y.json({objects:K.objects.map((H)=>{let U=H.key.split("/").pop()??H.key,B=H.key.split("/").map(encodeURIComponent).join("/");return{key:H.key,filename:U,size:H.size,uploadedAt:H.lastModified?.toISOString(),downloadUrl:`${G.baseUrl}/api/${encodeURIComponent(J)}/files/${B}`}})})}),X};var Ph0=w(()=>{iX();gw()});function Yp1(X){let Y=new A6;return Y.post("/trigger-callback",oi1({maxSize:UH7,onError:(G)=>G.json({error:"Payload too large"},413)}),async(G)=>{let Q=G.req.header("authorization");if(!Q?.startsWith("Bearer "))return G.json({error:"Missing or invalid Authorization header"},401);let J=Q.slice(7),W=await X.tokenStorage.validateToken(J);if(!W)return G.json({error:"Invalid callback token"},401);let Z=FH7.safeParse(await G.req.json().catch(()=>null));if(!Z.success)return G.json({error:"Invalid body",details:Z.error.issues},400);let{type:$,data:K}=Z.data;return X.eventTriggerEngine.notifyEvents([{source:W.connectionId,type:$,data:K??{},organizationId:W.organizationId}]),G.json({ok:!0,type:$},202)}),Y}var FH7,UH7=1048576;var qh0=w(()=>{iX();wh0();K0();FH7=F.object({type:F.string().min(1),data:F.record(F.string(),F.unknown()).optional()})});var Ah0=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(X,Y){this.writable=X,this.writer=X.getWriter(),this.encoder=new TextEncoder;let G=Y.getReader();this.abortSubscribers.push(async()=>{await G.cancel()}),this.responseReadable=new ReadableStream({async pull(Q){let{done:J,value:W}=await G.read();J?Q.close():Q.enqueue(W)},cancel:()=>{this.abort()}})}async write(X){try{if(typeof X==="string")X=this.encoder.encode(X);await this.writer.write(X)}catch{}return this}async writeln(X){return await this.write(X+`
|
|
7284
|
+
</available-prompts>`}async function ii1(X){let Y=X.stream.getReader();while(!0){let{done:G}=await Y.read();if(G)break}}var ci1,cK7=5;var RW1=w(()=>{CX();cZ1();X$8();Y$8();q7();xX();K0();t$8();r$8();vR();sx0();qW1();TW1();s$8();GK8();J31();ZK8();VS1();vS1();lw();T$();di1();ez();ci1=X1(x0(),1)});async function WK8(X,Y,G,Q){let{storage:J,streamBuffer:W,sseHub:Z}=Q,K=(await J.get(X,Y))?.virtual_mcp_id??void 0;await J.update(X,Y,{status:G,run_owner_pod:null,run_config:null,run_started_at:null}),W.purge(X),Z.emit(Y,Dj(X,G,K)),Z.emit(Y,_71(X,G))}async function tK7(X,Y){let{storage:G,streamBuffer:Q,sseHub:J}=Y;switch(X.type){case"RUN_STARTED":{if(!await G.claimRunStart(X.taskId,X.orgId,{status:"in_progress",run_owner_pod:X.podId??null,run_config:X.runConfig??null,run_started_at:X.podId?new Date().toISOString():null},X.podId??null))throw new pi1(X.taskId);let Z=await G.get(X.taskId,X.orgId);J.emit(X.orgId,Dj(X.taskId,"in_progress",Z?.virtual_mcp_id??void 0));return}case"RUN_RESUMED":{await G.update(X.taskId,X.orgId,{run_owner_pod:X.podId,run_started_at:new Date().toISOString()});let W=await G.get(X.taskId,X.orgId);J.emit(X.orgId,Dj(X.taskId,"in_progress",W?.virtual_mcp_id??void 0));return}case"STEP_COMPLETED":J.emit(X.orgId,Pq1(X.taskId,X.stepCount));return;case"RUN_COMPLETED":await WK8(X.taskId,X.orgId,"completed",Y);return;case"RUN_REQUIRES_ACTION":await WK8(X.taskId,X.orgId,"requires_action",Y);return;case"RUN_FAILED":{if(X.reason==="ghost"){if(!await G.forceFailIfInProgress(X.taskId,X.orgId))return;await G.update(X.taskId,X.orgId,{run_owner_pod:null,run_config:null,run_started_at:null})}else await G.update(X.taskId,X.orgId,{status:"failed",run_owner_pod:null,run_config:null,run_started_at:null});Q.purge(X.taskId);let W=await G.get(X.taskId,X.orgId);J.emit(X.orgId,Dj(X.taskId,"failed",W?.virtual_mcp_id??void 0)),J.emit(X.orgId,_71(X.taskId,"failed"));return}case"PREVIOUS_RUN_ABORTED":return}}async function $K8(X,Y){for(let{event:G}of X)await tK7(G,Y)}var pi1;var Hh0=w(()=>{q7();pi1=class pi1 extends Error{constructor(X){super(`Failed to claim run for thread ${X} \u2014 already running on another pod`);this.name="RunClaimError"}}});async function KK8(X){let Y=fi1(X),G=await X.req.json(),Q=sW8.safeParse(G);if(!Q.success)throw new E5(400,{message:Q.error.message});let{messages:J,...W}=Q.data,Z=J,{systemMessages:$,requestMessage:K}=gW8(Z);return{organization:Y,systemMessages:$,requestMessage:K,...W}}async function HK8(X,Y){let G=await X.storage.aiProviderKeys.list({organizationId:Y});if(G.length===0)throw new E5(400,{message:"No AI provider credentials configured for this organization"});let Q=G[0],J=await X.aiProviders.listModels(Q.id,Y);if(J.length===0)throw new E5(400,{message:"No models available from the configured AI provider"});let W=J[0];return{credentialId:Q.id,thinking:{id:W.modelId,title:W.title}}}function Fh0(X){let{cancelBroadcast:Y,streamBuffer:G,runRegistry:Q,threadStorage:J}=X,W=new A6;return W.get("/:org/decopilot/allowed-models",async(Z)=>{try{let $=Z.get("meshContext"),K=fi1(Z),H=$.auth.user?.role,U=await QB($.db,K.id,H);return Z.json(Ih6(U))}catch($){if(console.error("[decopilot:allowed-models] Error",$),$ instanceof E5)return Z.json({error:$.message},$.status);return Z.json({error:$ instanceof Error?$.message:"Internal error"},500)}}),W.post("/:org/decopilot/stream",async(Z)=>{try{let $=Z.get("meshContext"),{organization:K,models:H,agent:U,systemMessages:B,requestMessage:N,temperature:z,memory:O,thread_id:D,branch:E,toolApprovalLevel:P,mode:q}=await KK8(Z),j=$.auth?.user?.id;if(!j)throw new E5(401,{message:"User ID is required"});let M=H??await HK8($,K.id),I=await QB($.db,K.id,$.auth.user?.role);if(I!==void 0&&!UT(I,M.credentialId,M.thinking.id))throw new E5(403,{message:"Model not allowed for your role"});let R=O?.windowSize??CR,C=D??O?.thread_id,_=await _L({messages:[...B,N],models:M,agent:U,temperature:z,toolApprovalLevel:P,mode:q,organizationId:K.id,userId:j,taskId:C,windowSize:R,branch:E??null},$,{runRegistry:Q,streamBuffer:G,cancelBroadcast:Y});return M6.capture({distinctId:j,event:"chat_message_started",groups:{organization:K.id},properties:{organization_id:K.id,agent_id:U,mode:q,thread_id:C,credential_id:M.credentialId}}),wT({stream:_.stream,consumeSseStream:iz})}catch($){if(console.error("[decopilot:stream] Error",$),$ instanceof E5)return Z.json({error:$.message},$.status);if($ instanceof Error&&$.name==="AbortError")return console.warn("[decopilot:stream] Aborted",{error:$.message}),Z.json({error:"Request aborted"},400);return M6.captureException($),console.error("[decopilot:stream] Failed",{error:$ instanceof Error?$.message:JSON.stringify($),stack:$ instanceof Error?$.stack:void 0}),Z.json({error:$ instanceof Error?$.message:JSON.stringify($)},500)}}),W.post("/:org/decopilot/runtime/stream",async(Z)=>{try{let $=Z.get("meshContext"),{organization:K,models:H,agent:U,systemMessages:B,requestMessage:N,temperature:z,memory:O,thread_id:D,branch:E,toolApprovalLevel:P,mode:q}=await KK8(Z),j=$.auth?.user?.id;if(!j)throw new E5(401,{message:"User ID is required"});let M=H??await HK8($,K.id),I=await QB($.db,K.id,$.auth.user?.role);if(I!==void 0&&!UT(I,M.credentialId,M.thinking.id))throw new E5(403,{message:"Model not allowed for your role"});let R=O?.windowSize??CR,C=D??O?.thread_id,_=await _L({messages:[...B,N],models:M,agent:U,temperature:z,toolApprovalLevel:P,mode:q,organizationId:K.id,userId:j,taskId:C,windowSize:R,branch:E??null},$,{runRegistry:Q,streamBuffer:G,cancelBroadcast:Y});return wT({stream:_.stream,consumeSseStream:iz})}catch($){if(console.error("[decopilot:stream] Error",$),$ instanceof pi1)return Z.json({error:$.message},409);if($ instanceof E5)return Z.json({error:$.message},$.status);if($ instanceof Error&&$.name==="AbortError")return console.warn("[decopilot:stream] Aborted",{error:$.message}),Z.json({error:"Request aborted"},400);return console.error("[decopilot:stream] Failed",{error:$ instanceof Error?$.message:JSON.stringify($),stack:$ instanceof Error?$.stack:void 0}),Z.json({error:$ instanceof Error?$.message:JSON.stringify($)},500)}}),W.post("/:org/decopilot/cancel/:threadId",async(Z)=>{let{taskId:$,thread:K,organization:H}=await rW8(Z);if((await Q.execute({type:"CANCEL",taskId:$})).some((B)=>B.event.type==="RUN_FAILED"))return Z.json({cancelled:!0});if(Y.broadcast($),K.status==="in_progress")console.warn("[decopilot:cancel] Ghost run detected, force-failing",{taskId:$}),Q.execute({type:"FORCE_FAIL",taskId:$,reason:"ghost",orgId:H.id}).catch((B)=>{console.error("[decopilot:cancel] Failed to force-fail ghost thread",{taskId:$,err:B})});return Z.json({cancelled:!0,async:!0},202)}),W.get("/:org/decopilot/attach/:threadId",async(Z)=>{try{let{taskId:$,thread:K,organization:H}=await Zh0(Z);if(Q.isRunning($)){let P=await G.createReplayStream($);if(!P)return Z.body(null,204);let q=I31({execute:async({writer:j})=>{let M=P.getReader();try{while(!0){let{done:I,value:R}=await M.read();if(I)break;j.write(R)}}finally{M.releaseLock()}}});return wT({stream:q,consumeSseStream:iz})}let U=Z.get("meshContext"),B=U.auth?.user?.id;if(K.status!=="in_progress")return Z.body(null,204);if(K.created_by!==B)return Z.body(null,204);if(!K.run_config)return await J.forceFailIfInProgress($,H.id),Z.body(null,204);let N=xi1.safeParse(K.run_config);if(!N.success)return await J.forceFailIfInProgress($,H.id),Z.body(null,204);let z=N.data,O=await QB(U.db,H.id,U.auth.user?.role);if(O!==void 0&&!UT(O,z.models.credentialId,z.models.thinking.id))throw new E5(403,{message:"Model not allowed for your role"});if(!await J.claimOrphanedRun($,H.id,Xd()))return Z.body(null,204);let E=await _L({messages:[],models:hi1(z.models),agent:z.agent,temperature:z.temperature,toolApprovalLevel:z.toolApprovalLevel,mode:z.mode,organizationId:H.id,userId:B,taskId:$,windowSize:z.windowSize,isResume:!0},U,{runRegistry:Q,streamBuffer:G,cancelBroadcast:Y});return wT({stream:E.stream,consumeSseStream:iz})}catch($){if($ instanceof E5)throw $;return console.error("[decopilot:attach] Error",$),Z.body(null,500)}}),W}var FK8=w(()=>{CX();xX();iX();gw();vR();sx0();TW1();J31();Wh0();eW8();RW1();Hh0();di1()});var UK8=w(()=>{FK8()});var ni1=()=>{let X=new A6;return X.post("/connections/:connectionId/oauth-token",async(Y)=>{let G=Y.get("meshContext"),Q=Y.req.param("connectionId");if(!(G.auth.user?.id??G.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);let W=G.organization?.id;if(!W)return Y.json({error:"Organization context required"},403);let Z=await G.storage.connections.findById(Q,W);if(!Z)return Y.json({error:"Connection not found"},404);let $=await Y.req.json();if(!$.accessToken)return Y.json({error:"accessToken is required"},400);if($.tokenEndpoint){let z;try{z=new URL($.tokenEndpoint)}catch{return Y.json({error:"tokenEndpoint must be a valid URL"},400)}if(z.protocol!=="http:"&&z.protocol!=="https:")return Y.json({error:"tokenEndpoint must be an http(s) URL"},400)}let K=$.expiresIn?new Date(Date.now()+$.expiresIn*1000):null,H=$.tokenEndpoint??null;if(H?.includes("/oauth-proxy/")&&Z.connection_url)try{let z=await yS1(Z.connection_url);if(z)try{let O=new URL(z);if(O.protocol==="http:"||O.protocol==="https:")H=z}catch{}}catch{}let U=new V3(G.db,G.vault),B={connectionId:Q,accessToken:$.accessToken,refreshToken:$.refreshToken??null,scope:$.scope??null,expiresAt:K,clientId:$.clientId??null,clientSecret:$.clientSecret??null,tokenEndpoint:H},N=await U.upsert(B);return Y.json({success:!0,expiresAt:N.expiresAt})}),X.delete("/connections/:connectionId/oauth-token",async(Y)=>{let G=Y.get("meshContext"),Q=Y.req.param("connectionId");if(!(G.auth.user?.id??G.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);let W=G.organization?.id;if(!W)return Y.json({error:"Organization context required"},403);if(!await G.storage.connections.findById(Q,W))return Y.json({error:"Connection not found"},404);return await new V3(G.db,G.vault).delete(Q),Y.json({success:!0})}),X.get("/connections/:connectionId/oauth-token/status",async(Y)=>{let G=Y.get("meshContext"),Q=Y.req.param("connectionId");if(!(G.auth.user?.id??G.auth.apiKey?.userId??null))return Y.json({error:"Unauthorized"},401);let W=G.organization?.id;if(!W)return Y.json({error:"Organization context required"},403);if(!await G.storage.connections.findById(Q,W))return Y.json({error:"Connection not found"},404);let $=new V3(G.db,G.vault),K=await $.get(Q);if(!K)return Y.json({hasToken:!1,isExpired:!0,canRefresh:!1});let H=$.isExpired(K),U=!!K.refreshToken&&!!K.tokenEndpoint;return Y.json({hasToken:!0,isExpired:H,canRefresh:U,expiresAt:K.expiresAt})}),X};var Uh0=w(()=>{iX();Bk0();pR()});var eY=async(X,Y)=>{await Y();let Q=(X.req.matchedRoutes??[]).find((W)=>W.method!=="ALL"&&!W.path.endsWith("*"));if(!Q||Q.path.startsWith("/api/:org/"))return;let J=X.get("meshContext");console.log("deprecated route",{route:X.req.routePath,method:X.req.method,org:J?.organization?.slug,user:J?.auth?.user?.id,ua:X.req.header("user-agent")})};var Qe=async(X,Y)=>{let G=X.req.param("org");if(!G)return X.json({error:"org slug missing in path"},400);let Q=X.get("meshContext");if(!Q?.db)return X.json({error:"meshContext not initialized"},500);let J=Q.db,W=await J.selectFrom("organization").select(["id","slug","name"]).where("slug","=",G).executeTakeFirst();if(!W)return X.json({error:`organization "${G}" not found`},404);let Z=Q.auth?.user?.id,$;if(Z){let K=await J.selectFrom("member").select(["role"]).where("userId","=",Z).where("organizationId","=",W.id).executeTakeFirst();if(!K)return X.json({error:"forbidden: not a member of organization"},403);$=K.role}if(Q.organization={id:W.id,slug:W.slug,name:W.name,role:$},Q.access.setOrganizationId(W.id),Q.access.setRole($),Q.storage.threads.setOrganizationId(W.id),!Q.objectStorage){let K=Qr();Q.objectStorage=K?fS1(K,W.id):new yZ1(W.id,Q.baseUrl)}return await Y()};var Bh0=w(()=>{Zk0();kV1()});async function fL(X,Y,G){let Q=await fetch(`${X}/rest/v1/${G}`,{headers:{apikey:Y,Authorization:`Bearer ${Y}`,Accept:"application/json"}});if(!Q.ok){let J=await Q.text().catch(()=>Q.statusText);throw console.error(`[deco-sites] Supabase error (${Q.status}): ${J}`),Error(`External service error (${Q.status})`)}return Q.json()}async function Je(X,Y,G,Q){let J=await fetch(`${X}/rest/v1/${G}`,{method:"POST",headers:{apikey:Y,Authorization:`Bearer ${Y}`,"Content-Type":"application/json",Accept:"application/json",Prefer:"return=representation"},body:JSON.stringify(Q)});if(!J.ok){let Z=await J.text().catch(()=>J.statusText);throw console.error(`[deco-sites] Supabase POST error (${J.status}): ${Z}`),Error(`External service error (${J.status})`)}let W=await J.json();if(!W[0])throw Error("Supabase POST returned no rows");return W[0]}function Nh0(){let X=u4(),Y=X.decoSupabaseUrl,G=X.decoSupabaseServiceKey;if(!Y||!G)return null;return{supabaseUrl:Y,serviceKey:G}}async function zh0(X,Y,G){return(await fL(X,Y,`profiles?email=eq.${encodeURIComponent(G)}&select=user_id`))[0]?.user_id??null}async function BK8(X,Y,G){let Q=await fL(X,Y,`api_key?user_id=eq.${encodeURIComponent(G)}&select=id&limit=1`);if(Q[0]?.id)return Q[0].id;return(await Je(X,Y,"api_key",{user_id:G})).id}function oK7(X){return`${aK7}${X}@${rK7}`}async function sK7(X,Y,G){return(await fL(X,Y,`sites?name=eq.${encodeURIComponent(G)}&select=team&limit=1`))[0]?.team??null}async function eK7(X,Y,G){let Q=await fetch(`${X}/auth/v1/admin/users`,{method:"POST",headers:{apikey:Y,Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({email:G,email_confirm:!0,app_metadata:{mesh_service_account:!0}})});if(!Q.ok){let W=await Q.text().catch(()=>Q.statusText);throw console.error(`[deco-sites] Auth admin create user error (${Q.status}): ${W}`),Error(`Failed to create auth user (${Q.status})`)}return(await Q.json()).id}async function XH7(X,Y,G){let Q=oK7(G),J=await fL(X,Y,`profiles?email=eq.${encodeURIComponent(Q)}&select=user_id&limit=1`);if(J[0]?.user_id){let K=J[0].user_id;if(!(await fL(X,Y,`members?user_id=eq.${encodeURIComponent(K)}&team_id=eq.${G}&select=id&limit=1`))[0]?.id){let U=await Je(X,Y,"members",{user_id:K,team_id:G,admin:!0});await Je(X,Y,"member_roles",{member_id:U.id,role_id:1})}return BK8(X,Y,K)}let W=await eK7(X,Y,Q);if(!(await fL(X,Y,`profiles?user_id=eq.${encodeURIComponent(W)}&select=user_id&limit=1`))[0])await Je(X,Y,"profiles",{user_id:W,email:Q,name:`Mesh Service Account (team ${G})`});let $=await Je(X,Y,"members",{user_id:W,team_id:G,admin:!0});return await Je(X,Y,"member_roles",{member_id:$.id,role_id:1}),BK8(X,Y,W)}async function YH7(X){try{let Y=await fetch(`https://${X}/favicon.ico`,{signal:AbortSignal.timeout(5000)});if(!Y.ok)return null;let G=Y.headers.get("content-type")??"image/x-icon",Q=await Y.arrayBuffer();if(Q.byteLength===0)return null;let J=Buffer.from(Q).toString("base64");return`data:${G};base64,${J}`}catch{return null}}var aK7="deco-team-",rK7="deco.cx",zK8=async(X,Y)=>{if(!X.get("meshContext").auth.user?.id)return X.json({error:"Unauthorized"},401);return Y()},NK8="https://sites-admin-mcp.decocache.com/api/mcp",OK8=()=>{let X=new A6;return X.use("*",zK8),X.get("/profile",async(Y)=>{let Q=Y.get("meshContext").auth.user?.email;if(!Q)return Y.json({error:"Unauthorized"},401);let J=Nh0();if(!J)return Y.json({isDecoUser:!1});try{let W=await zh0(J.supabaseUrl,J.serviceKey,Q);return Y.json({isDecoUser:W!==null})}catch{return Y.json({isDecoUser:!1})}}),X},ti1=()=>{let X=new A6;return X.use("*",zK8),X.get("/",async(Y)=>{let Q=Y.get("meshContext").auth.user?.email;if(!Q)return Y.json({error:"Unauthorized"},401);let J=Nh0();if(!J)return Y.json({sites:[]});let{supabaseUrl:W,serviceKey:Z}=J;try{let $=await zh0(W,Z,Q);if(!$)return Y.json({sites:[]});let H=(await fL(W,Z,`members?user_id=eq.${encodeURIComponent($)}&deleted_at=is.null&select=team_id`)).map((B)=>B.team_id).filter((B)=>Number.isInteger(B));if(H.length===0)return Y.json({sites:[]});let U=await fL(W,Z,`sites?team=in.(${H.join(",")})&select=name,domains,thumb_url&order=id`);return Y.json({sites:U})}catch($){return console.error("[deco-sites] GET error:",$),Y.json({error:"Failed to fetch sites"},502)}}),X.post("/connection",async(Y)=>{let G=Y.get("meshContext"),Q=G.auth.user?.email,J=H6(G);if(!Q||!J)return Y.json({error:"Unauthorized"},401);let W;try{W=await Y.req.json()}catch{return Y.json({error:"Invalid request body"},400)}let{siteName:Z,orgId:$}=W;if(!Z||!$)return Y.json({error:"siteName and orgId are required"},400);let K=m7("conn");if(!/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(Z))return Y.json({error:"Invalid siteName"},400);if(!await G.db.selectFrom("member").select("member.id").where("member.userId","=",J).where("member.organizationId","=",$).executeTakeFirst())return Y.json({error:"Forbidden"},403);let U=Nh0();if(!U)return Y.json({error:"Deco integration is not configured"},503);let{supabaseUrl:B,serviceKey:N}=U;try{let z=await zh0(B,N,Q);if(!z)return Y.json({error:"No deco.cx account found for this user"},404);let O=await sK7(B,N,Z);if(!O)return Y.json({error:"Site not found or has no team"},404);if(!(await fL(B,N,`members?user_id=eq.${encodeURIComponent(z)}&team_id=eq.${O}&deleted_at=is.null&select=id&limit=1`))[0])return Y.json({error:"You are not a member of this site's team"},403);let E=await XH7(B,N,O),P=await UA({id:`pending-${K}`,title:`deco.cx \u2014 ${Z}`,connection_type:"HTTP",connection_url:NK8,connection_token:E}).catch(()=>null),q=P?.tools?.length?P.tools:null,j=P?.scopes?.length?P.scopes:null,M=await YH7(`${Z}.deco.site`),I=await G.storage.connections.create({id:K,organization_id:$,created_by:J,title:`deco.cx \u2014 ${Z}`,description:`Admin MCP for deco.cx site: ${Z}`,connection_type:"HTTP",connection_url:NK8,connection_token:E,connection_headers:null,oauth_config:null,configuration_state:{SITE_NAME:Z},metadata:{source:"deco.cx-import"},icon:null,app_name:"deco.cx",app_id:null,tools:q,configuration_scopes:j});return Y.json({connId:I.id,icon:M})}catch(z){return console.error("[deco-sites] POST /connection error:",z),Y.json({error:"Failed to create connection"},500)}}),X};var Oh0=w(()=>{iX();kH();bG1();l9()});import{createHmac as GH7}from"crypto";import{mkdir as QH7,writeFile as JH7}from"fs/promises";import{dirname as ZH7,join as LK8}from"path";function $H7(X){let Y=X.replace(/[^a-zA-Z0-9_-]/g,"_");return LK8(WH7,Y)}function KH7(X){return X.replace(/^\/+/,"").replace(/\.\./g,"")}function DK8(X,Y){let G=$H7(X),Q=KH7(Y);return LK8(G,Q)}function wK8(X,Y,G,Q,J){let W=u4().encryptionKey||"dev-secret",Z=`${X}:${Y}:${G}:${Q}`,$=GH7("sha256",W).update(Z).digest("hex");return J===$}function Dh0(X){let Y=X.split(".").pop()?.toLowerCase()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",ico:"image/x-icon",bmp:"image/bmp",pdf:"application/pdf",json:"application/json",xml:"application/xml",txt:"text/plain",html:"text/html",htm:"text/html",css:"text/css",csv:"text/csv",md:"text/markdown",js:"application/javascript",mjs:"application/javascript",ts:"application/typescript",mp4:"video/mp4",webm:"video/webm",avi:"video/x-msvideo",mov:"video/quicktime",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",zip:"application/zip",gz:"application/gzip",tar:"application/x-tar",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf"}[Y]||"application/octet-stream"}var WH7="./data/assets",ai1=(X)=>{let Y=new A6,G=X.orgFromPath?"/*":"/:orgId/*";return Y.get(G,async(Q)=>{let J=X.orgFromPath?Q.get("meshContext")?.organization?.id:Q.req.param("orgId");if(!J)return Q.json({error:"Missing organization context"},500);let W=X.orgFromPath?`/api/${Q.req.param("org")??""}/dev-assets/`:`/api/dev-assets/${J}/`,Z=Q.req.path.replace(W,"");if(!Z)return Q.json({error:"Missing key"},400);let $=Q.req.query("expires"),K=Q.req.query("signature"),H=Q.req.query("method");if(!$||!K||H!=="GET")return Q.json({error:"Invalid or missing signature parameters"},400);let U=parseInt($,10);if(!Number.isFinite(U))return Q.json({error:"Invalid expires parameter"},400);let B=Math.floor(Date.now()/1000);if(U<B)return Q.json({error:"URL has expired"},403);if(!wK8(J,Z,U,"GET",K))return Q.json({error:"Invalid signature"},403);let N=DK8(J,Z);try{let z=Bun.file(N);if(!await z.exists())return Q.json({error:"File not found"},404);let D=Dh0(Z);return new Response(z.stream(),{headers:{"Content-Type":D,"Content-Length":z.size.toString(),"Cache-Control":"private, max-age=3600"}})}catch(z){return console.error("Error serving file:",z),Q.json({error:"Failed to read file"},500)}}),Y.put(G,async(Q)=>{let J=X.orgFromPath?Q.get("meshContext")?.organization?.id:Q.req.param("orgId");if(!J)return Q.json({error:"Missing organization context"},500);let W=X.orgFromPath?`/api/${Q.req.param("org")??""}/dev-assets/`:`/api/dev-assets/${J}/`,Z=Q.req.path.replace(W,"");if(!Z)return Q.json({error:"Missing key"},400);let $=Q.req.query("expires"),K=Q.req.query("signature"),H=Q.req.query("method");if(!$||!K||H!=="PUT")return Q.json({error:"Invalid or missing signature parameters"},400);let U=parseInt($,10);if(!Number.isFinite(U))return Q.json({error:"Invalid expires parameter"},400);let B=Math.floor(Date.now()/1000);if(U<B)return Q.json({error:"URL has expired"},403);if(!wK8(J,Z,U,"PUT",K))return Q.json({error:"Invalid signature"},403);let N=DK8(J,Z),z=ZH7(N);try{await QH7(z,{recursive:!0});let O=await Q.req.arrayBuffer();return await JH7(N,Buffer.from(O)),Q.json({success:!0,key:Z})}catch(O){return console.error("Error saving file:",O),Q.json({error:"Failed to save file"},500)}}),Y};var ri1=w(()=>{iX();l9()});var EK8="Payload Too Large",PK8,oi1=(X)=>{let Y=X.onError||(()=>{let Q=new Response(EK8,{status:413});throw new E5(413,{res:Q})}),G=X.maxSize;return async function(J,W){if(!J.req.raw.body)return W();let Z=J.req.raw.headers.has("transfer-encoding"),$=J.req.raw.headers.has("content-length");if($&&!Z)return parseInt(J.req.raw.headers.get("content-length")||"0",10)>G?Y(J):W();let K=0,H=J.req.raw.body.getReader(),B={body:new ReadableStream({async start(N){try{for(;;){let{done:z,value:O}=await H.read();if(z)break;if(K+=O.length,K>G){N.error(new PK8(EK8));break}N.enqueue(O)}}finally{N.close()}}}),duplex:"half"};if(J.req.raw=new Request(J.req.raw,B),await W(),J.error instanceof PK8)J.res=await Y(J)}};var wh0=w(()=>{gw();PK8=class extends Error{constructor(X){super(X);this.name="BodyLimitError"}}});function si1(X){let Y=new A6;return Y.get("/kv/:key",async(G)=>{let J=G.get("meshContext").organization?.id;if(!J)return G.json({error:"Organization required"},400);let W=G.req.param("key"),Z=await X.kvStorage.get(J,W);if(Z===null)return G.json({error:"Not found"},404);return G.json({key:W,value:Z})}),Y.put("/kv/:key",oi1({maxSize:HH7,onError:(G)=>G.json({error:"Payload too large"},413)}),async(G)=>{let J=G.get("meshContext").organization?.id;if(!J)return G.json({error:"Organization required"},400);let W=G.req.param("key"),Z;try{Z=await G.req.json()}catch{return G.json({error:"Invalid JSON body"},400)}return await X.kvStorage.set(J,W,Z),G.json({ok:!0})}),Y.delete("/kv/:key",async(G)=>{let J=G.get("meshContext").organization?.id;if(!J)return G.json({error:"Organization required"},400);let W=G.req.param("key");return await X.kvStorage.delete(J,W),G.json({ok:!0})}),Y}var HH7=1048576;var Lh0=w(()=>{iX();wh0()});var ei1=()=>{let X=new A6;return X.all("/",async(Y)=>{let G=await $s(Y.get("meshContext")),Q=new iH({enableJsonResponse:Y.req.raw.headers.get("Accept")?.includes("application/json")??!1});return await G.connect(Q),Q.handleRequest(Y.req.raw)}),X};var Eh0=w(()=>{iX();Ws();Js()});var Xp1=()=>{let X=new A6;return X.get("/threads/:threadId/outputs",async(Y)=>{let G=Y.get("meshContext");if(!G.auth?.user?.id)throw new E5(401,{message:"Unauthorized"});let J=G.organization?.slug;if(!J)throw new E5(400,{message:"Organization required"});let W=Y.req.param("threadId");if(!W||!/^[A-Za-z0-9_-]+$/.test(W))throw new E5(400,{message:"Invalid thread ID"});if(!await G.storage.threads.get(W))throw new E5(404,{message:"Thread not found"});let $=G.objectStorage;if(!$)return Y.json({objects:[]});let K=await $.list({prefix:`model-outputs/${W}/`,maxKeys:200});return Y.json({objects:K.objects.map((H)=>{let U=H.key.split("/").pop()??H.key,B=H.key.split("/").map(encodeURIComponent).join("/");return{key:H.key,filename:U,size:H.size,uploadedAt:H.lastModified?.toISOString(),downloadUrl:`${G.baseUrl}/api/${encodeURIComponent(J)}/files/${B}`}})})}),X};var Ph0=w(()=>{iX();gw()});function Yp1(X){let Y=new A6;return Y.post("/trigger-callback",oi1({maxSize:UH7,onError:(G)=>G.json({error:"Payload too large"},413)}),async(G)=>{let Q=G.req.header("authorization");if(!Q?.startsWith("Bearer "))return G.json({error:"Missing or invalid Authorization header"},401);let J=Q.slice(7),W=await X.tokenStorage.validateToken(J);if(!W)return G.json({error:"Invalid callback token"},401);let Z=FH7.safeParse(await G.req.json().catch(()=>null));if(!Z.success)return G.json({error:"Invalid body",details:Z.error.issues},400);let{type:$,data:K}=Z.data;return X.eventTriggerEngine.notifyEvents([{source:W.connectionId,type:$,data:K??{},organizationId:W.organizationId}]),G.json({ok:!0,type:$},202)}),Y}var FH7,UH7=1048576;var qh0=w(()=>{iX();wh0();K0();FH7=F.object({type:F.string().min(1),data:F.record(F.string(),F.unknown()).optional()})});var Ah0=class{writer;encoder;writable;abortSubscribers=[];responseReadable;aborted=!1;closed=!1;constructor(X,Y){this.writable=X,this.writer=X.getWriter(),this.encoder=new TextEncoder;let G=Y.getReader();this.abortSubscribers.push(async()=>{await G.cancel()}),this.responseReadable=new ReadableStream({async pull(Q){let{done:J,value:W}=await G.read();J?Q.close():Q.enqueue(W)},cancel:()=>{this.abort()}})}async write(X){try{if(typeof X==="string")X=this.encoder.encode(X);await this.writer.write(X)}catch{}return this}async writeln(X){return await this.write(X+`
|
|
7285
7285
|
`),this}sleep(X){return new Promise((Y)=>setTimeout(Y,X))}async close(){try{await this.writer.close()}catch{}this.closed=!0}async pipe(X){this.writer.releaseLock(),await X.pipeTo(this.writable,{preventClose:!0}),this.writer=this.writable.getWriter()}onAbort(X){this.abortSubscribers.push(X)}abort(){if(!this.aborted)this.aborted=!0,this.abortSubscribers.forEach((X)=>X())}};var Th0=()=>{};var Gp1=()=>{let X=typeof Bun<"u"?Bun.version:void 0;if(X===void 0)return!1;let Y=X.startsWith("1.1")||X.startsWith("1.0")||X.startsWith("0.");return Gp1=()=>Y,Y};var Ih0=()=>{};var qK8=w(()=>{Th0();Ih0()});var AK8,BH7=async(X,Y,G)=>{try{await Y(X)}catch(Q){if(Q instanceof Error&&G)await G(Q,X),await X.writeSSE({event:"error",data:Q.message});else console.error(Q)}finally{X.close()}},NH7,gT=(X,Y,G)=>{let{readable:Q,writable:J}=new TransformStream,W=new AK8(J,Q);if(Gp1())X.req.raw.signal.addEventListener("abort",()=>{if(!W.closed)W.abort()});return NH7.set(W.responseReadable,X),X.header("Transfer-Encoding","chunked"),X.header("Content-Type","text/event-stream"),X.header("Cache-Control","no-cache"),X.header("Connection","keep-alive"),BH7(W,Y,G),X.newResponse(W.responseReadable)};var TK8=w(()=>{yV1();Th0();Ih0();AK8=class extends Ah0{constructor(X,Y){super(X,Y)}async writeSSE(X){let G=(await JG1(X.data,bV1.Stringify,!1,{})).split(/\r\n|\r|\n/).map((J)=>{return`data: ${J}`}).join(`
|
|
7286
7286
|
`);for(let J of["event","id","retry"])if(X[J]&&/[\r\n]/.test(X[J]))throw Error(`${J} must not contain "\\r" or "\\n"`);let Q=[X.event&&`event: ${X.event}`,G,X.id&&`id: ${X.id}`,X.retry&&`retry: ${X.retry}`].filter(Boolean).join(`
|
|
7287
7287
|
`)+`
|