decocms 4.402.1 → 4.403.0
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-DcHwjWsq.js → AlertCircle-BxsvjprR.js} +1 -1
- package/dist/client/assets/{AreaChart-BPY6McAI.js → AreaChart-BXuWJn9c.js} +1 -1
- package/dist/client/assets/{ArrowLeft-Bkin1mI_.js → ArrowLeft-C98PG333.js} +1 -1
- package/dist/client/assets/{ArrowRight-5pCNMYve.js → ArrowRight-CK7-YvUr.js} +1 -1
- package/dist/client/assets/{ArrowUp-BBAz-eci.js → ArrowUp-DPWXMpl2.js} +1 -1
- package/dist/client/assets/{CartesianChart-Jh2jk1q9.js → CartesianChart-DD9gGd-G.js} +1 -1
- package/dist/client/assets/{Check-D8Zqb1HC.js → Check-Blxq8j59.js} +1 -1
- package/dist/client/assets/{CheckCircle-CF8WeHYg.js → CheckCircle-DS--6hmh.js} +1 -1
- package/dist/client/assets/{ChevronUp-CGDgj0bm.js → ChevronUp-CRNjHjTK.js} +1 -1
- package/dist/client/assets/{Copy01-C9mP-VM4.js → Copy01-DmLSY0Qf.js} +1 -1
- package/dist/client/assets/{CreditCard01-DQsr79v7.js → CreditCard01-C6GC8NM-.js} +1 -1
- package/dist/client/assets/{DotsVertical-DpAeUNyz.js → DotsVertical-B2eyM1bc.js} +1 -1
- package/dist/client/assets/{ErrorBarContext-CwmIk3tm.js → ErrorBarContext-CYai77oS.js} +1 -1
- package/dist/client/assets/{Eye-DpBHj09D.js → Eye-DDS_VF-Y.js} +1 -1
- package/dist/client/assets/{Globe04-vwBxz8j-.js → Globe04-95dd8QSP.js} +1 -1
- package/dist/client/assets/{Image01-CWl1q5TL.js → Image01-C1vTsGg9.js} +1 -1
- package/dist/client/assets/{Key01-BdZlsNHY.js → Key01-CfEGZMt9.js} +1 -1
- package/dist/client/assets/{LayoutLeft-BCyzo03m.js → LayoutLeft-xPkXxcb6.js} +1 -1
- package/dist/client/assets/{Line-D3dMYTRZ.js → Line-C67AfCyw.js} +1 -1
- package/dist/client/assets/{Link01-DL0Bhiy8.js → Link01-CvcI1eLv.js} +1 -1
- package/dist/client/assets/{LinkExternal01-Bzm59G9x.js → LinkExternal01-DH3oN4WK.js} +1 -1
- package/dist/client/assets/{Monitor01-BWry3mi8.js → Monitor01-B9ABYuV_.js} +1 -1
- package/dist/client/assets/{Palette-QMR4FKys.js → Palette-DJJWQUTk.js} +1 -1
- package/dist/client/assets/{Plus-BUY7Ud4X.js → Plus-GxHWJNZK.js} +1 -1
- package/dist/client/assets/{SearchMd-BZrJSLPd.js → SearchMd-QgF27GDM.js} +1 -1
- package/dist/client/assets/{Sector-DDD99rSB.js → Sector-BNV9jqXa.js} +1 -1
- package/dist/client/assets/{Share07-lQLk_Wuy.js → Share07-DV5DThxW.js} +1 -1
- package/dist/client/assets/{Sun-BVJsSwmV.js → Sun-C3em9BZW.js} +1 -1
- package/dist/client/assets/{Tool01-eWiBwjAj.js → Tool01-BCsmpwCz.js} +1 -1
- package/dist/client/assets/{Trash01-CytDsT4G.js → Trash01-BgJo-uHb.js} +1 -1
- package/dist/client/assets/{Upload01-CDaZdY6S.js → Upload01-BNcthBU9.js} +1 -1
- package/dist/client/assets/{User01-Co__-w2M.js → User01-DvYjRkyx.js} +1 -1
- package/dist/client/assets/{UserSquare-DWwkQbY_.js → UserSquare-DKTJMzlh.js} +1 -1
- package/dist/client/assets/{Users01-DAz3tepP.js → Users01-DqJ21DOW.js} +1 -1
- package/dist/client/assets/{X-DAJc3BKO.js → X-tomqNIg1.js} +1 -1
- package/dist/client/assets/{XClose-BNaGgCB0.js → XClose-DKTON5RG.js} +1 -1
- package/dist/client/assets/{Zap-Cku-mkoY.js → Zap-DMCGUdZC.js} +1 -1
- package/dist/client/assets/{ZoomOut-DdkoWs_x.js → ZoomOut-CvfOKBlv.js} +1 -1
- package/dist/client/assets/{access-gate-BhuVj9y1.js → access-gate-DsBjN_k-.js} +1 -1
- package/dist/client/assets/{add-connection-dialog-Df12oKBz.js → add-connection-dialog-DGaBiFHb.js} +1 -1
- package/dist/client/assets/{agent-analytics-DbTHKQ1k.js → agent-analytics-n1UGPVtK.js} +1 -1
- package/dist/client/assets/agent-app-ucQZeOf-.js +1 -0
- package/dist/client/assets/{agent-assets-CK7eio8D.js → agent-assets-DRURWRvp.js} +1 -1
- package/dist/client/assets/{agent-automation-CuAepk_l.js → agent-automation-DBbEhZPF.js} +1 -1
- package/dist/client/assets/{agent-automations-Bj04SxRa.js → agent-automations-B8ZFE67t.js} +1 -1
- package/dist/client/assets/{agent-connect-sources-BCyCM1tV.js → agent-connect-sources-Dj71XW9T.js} +1 -1
- package/dist/client/assets/agent-deck-96Di6sOJ.js +1 -0
- package/dist/client/assets/{agent-e2e-C-5GcU_j.js → agent-e2e-DfXNlhc3.js} +1 -1
- package/dist/client/assets/{agent-experiments-C8LQkh0S.js → agent-experiments-BJWBqxLp.js} +1 -1
- package/dist/client/assets/{agent-file-iVhCT82h.js → agent-file-BBipxVNI.js} +1 -1
- package/dist/client/assets/{agent-git-3yyAe1K7.js → agent-git-Z2sLlW-j.js} +1 -1
- package/dist/client/assets/{agent-hosting-DDQwutKA.js → agent-hosting-D8WZlGjj.js} +1 -1
- package/dist/client/assets/{agent-icon-BvX9_a8p.js → agent-icon-CP9iXRWW.js} +1 -1
- package/dist/client/assets/agent-library-file-BlvILtIR.js +1 -0
- package/dist/client/assets/{agent-monitor-Cb-4CMIV.js → agent-monitor-CnK_AfrL.js} +1 -1
- package/dist/client/assets/{agent-overview-DGYqyfwa.js → agent-overview-8y0eYIH6.js} +1 -1
- package/dist/client/assets/agent-settings-CeWV6MPi.js +1 -0
- package/dist/client/assets/{agent-site-editor-DZsDoL4C.js → agent-site-editor-CQcbIrSJ.js} +1 -1
- package/dist/client/assets/agent-site-editor-code-orvWD6S7.js +2 -0
- package/dist/client/assets/{agent-site-editor-content-DTjzis44.js → agent-site-editor-content-BlZJF4Kt.js} +3 -3
- package/dist/client/assets/{agent-site-editor-preview-CjO8bl2l.js → agent-site-editor-preview-B2myVBRe.js} +3 -3
- package/dist/client/assets/agent-view-BhpD7HoJ.js +1 -0
- package/dist/client/assets/{agent-view-guard-DKeKGOgB.js → agent-view-guard-CR5g29BH.js} +1 -1
- package/dist/client/assets/{agents-list-VW3RCSuu.js → agents-list-Bn6kIacr.js} +1 -1
- package/dist/client/assets/{ai-providers-DmdvF_P2.js → ai-providers-DIo8QsY4.js} +1 -1
- package/dist/client/assets/{alert-dialog-BUIr72GF.js → alert-dialog-B5hf3Zq6.js} +1 -1
- package/dist/client/assets/{alert-BWOy_aTe.js → alert-xdPy5Dnu.js} +1 -1
- package/dist/client/assets/{analytics-sections-CtJSDTKq.js → analytics-sections-MCA0egKf.js} +1 -1
- package/dist/client/assets/api-keys-BB-GxSyT.js +1 -0
- package/dist/client/assets/{api-keys-BkC5Tf1A.js → api-keys-k6o9_ZVL.js} +1 -1
- package/dist/client/assets/app-editor-BYBxWW6P.js +1 -0
- package/dist/client/assets/{asset-utils-CCxUxZJl.js → asset-utils-DHewT25o.js} +1 -1
- package/dist/client/assets/{auth-catchall-Bc-Nu92V.js → auth-catchall-DrFinUIn.js} +1 -1
- package/dist/client/assets/{auth-entry-BwKPXJEb.js → auth-entry-Ceu5j70S.js} +1 -1
- package/dist/client/assets/{auth-D8auDfWe.js → auth-pb03Kzig.js} +1 -1
- package/dist/client/assets/{auth-split-layout-34Nf6GFY.js → auth-split-layout-Bt9Pa3Bg.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-xX05HUt0.js → authenticate-and-persist-oauth-ByuGS_gG.js} +1 -1
- package/dist/client/assets/{automation-list-row-BjKSRD_8.js → automation-list-row-CH-bg8ai.js} +1 -1
- package/dist/client/assets/{automation-runs-DYTaC7v8.js → automation-runs-C1MhxQwE.js} +1 -1
- package/dist/client/assets/{automations-Dh1bOrz6.js → automations-D4d9Yr8A.js} +1 -1
- package/dist/client/assets/{autosend-CAruNR-r.js → autosend-DxvfLrdl.js} +1 -1
- package/dist/client/assets/{avatar-DpIdIzyq.js → avatar-D9bHXtJ-.js} +1 -1
- package/dist/client/assets/{badge-Cz4FrB04.js → badge-DXHGQv94.js} +1 -1
- package/dist/client/assets/{block-document-DBd3EXVE.js → block-document-Cjfk5S2Y.js} +1 -1
- package/dist/client/assets/{blocks-preview-workspace-context-CagHfewh.js → blocks-preview-workspace-context-D339Nq0O.js} +1 -1
- package/dist/client/assets/{buckets-pLKwt15L.js → buckets-8xQyeFnA.js} +1 -1
- package/dist/client/assets/{build-improve-prompt-doc-DktDRS2O.js → build-improve-prompt-doc-D2Ll2Rce.js} +1 -1
- package/dist/client/assets/{calendar-D1XYfb8U.js → calendar-Wk2YDk5Q.js} +1 -1
- package/dist/client/assets/{capability-load-error-C7vdFk9B.js → capability-load-error-QLFmZqWG.js} +1 -1
- package/dist/client/assets/{cards-DwAzndr5.js → cards-c3aviZef.js} +1 -1
- package/dist/client/assets/{category-editor-ogyqgis9.js → category-editor-zXprfyEx.js} +1 -1
- package/dist/client/assets/{chart-PWKZfojU.js → chart-DKqJHT22.js} +1 -1
- package/dist/client/assets/{chat-context-lntumHEL.js → chat-context-zkHg9OWQ.js} +1 -1
- package/dist/client/assets/{chat-draft-vzCx0JHx.js → chat-draft-DSG5ngj7.js} +1 -1
- package/dist/client/assets/{checkbox-CjzMziEV.js → checkbox-K4FR-PUT.js} +1 -1
- package/dist/client/assets/{choose-editor-Dau4YBRD.js → choose-editor-BXV7Je4x.js} +1 -1
- package/dist/client/assets/{claim-phase-copy-CKjixjui.js → claim-phase-copy-pJF6tq00.js} +1 -1
- package/dist/client/assets/{cli-auth-success-DYzdHJrD.js → cli-auth-success-Cl8P0ld7.js} +1 -1
- package/dist/client/assets/{client-icons-DsW6C1D5.js → client-icons-Q4X702lN.js} +1 -1
- package/dist/client/assets/{collapsible-C1N5Vk5A.js → collapsible-C198MfkN.js} +1 -1
- package/dist/client/assets/{collection-detail-CpyWy-pY.js → collection-detail-j8tNEP48.js} +1 -1
- package/dist/client/assets/{collection-display-button-DDhY9dMS.js → collection-display-button-HO4jLV8w.js} +1 -1
- package/dist/client/assets/{collection-search-hFSvTg9q.js → collection-search-DIxBrmSt.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-CoSdC7p-.js → collection-table-wrapper-Be87XQmm.js} +1 -1
- package/dist/client/assets/{collection-tabs-CB5jU9UN.js → collection-tabs-BAPv5IF9.js} +1 -1
- package/dist/client/assets/{combobox-D6DckToA.js → combobox-BVFjv7zx.js} +1 -1
- package/dist/client/assets/{command-M2XMNX_S.js → command-CfliK-Cc.js} +1 -1
- package/dist/client/assets/{companion-mcps-section-B9h24TwK.js → companion-mcps-section-BbAoBFxb.js} +1 -1
- package/dist/client/assets/{connect-kPokwQd1.js → connect-BA0xuDG1.js} +1 -1
- package/dist/client/assets/{connect-layout-BLRcrSQ6.js → connect-layout-BdvXARBl.js} +1 -1
- package/dist/client/assets/{connection-card-B_Iux5tH.js → connection-card-DvPe_M7v.js} +1 -1
- package/dist/client/assets/{connection-detail-X7jG3k4W.js → connection-detail-DwqbKjaA.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-Diud5YKf.js → connection-form-helpers-DplEqD9m.js} +1 -1
- package/dist/client/assets/{connection-DNxakCqK.js → connection-vEOaKzQz.js} +1 -1
- package/dist/client/assets/{connections-CdmbRwtQ.js → connections-DP3rfITi.js} +1 -1
- package/dist/client/assets/{context-D_-nNlkt.js → context-BN_AZdQK.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-Dvo8jU8X.js → create-organization-dialog-CIJFPZj1.js} +1 -1
- package/dist/client/assets/{decofile-api-CRY_R36f.js → decofile-api-W5b1cAOf.js} +1 -1
- package/dist/client/assets/{decopilot-B9r80dff.js → decopilot-TYyHvkDT.js} +1 -1
- package/dist/client/assets/{dialog-DZbrQs4a.js → dialog-D_eZEQVv.js} +1 -1
- package/dist/client/assets/{discover-N-k9SPj2.js → discover-B9q6xfGX.js} +1 -1
- package/dist/client/assets/{domain-settings-DaO7iyKF.js → domain-settings-DNUorrft.js} +1 -1
- package/dist/client/assets/{download-app-dialog-Cc26MdhV.js → download-app-dialog-Cg2Fsige.js} +1 -1
- package/dist/client/assets/{drawer-B5y-1Csa.js → drawer-BbjSV6aw.js} +1 -1
- package/dist/client/assets/{editor-BYzs-ptR.js → editor-z3_N_jkd.js} +1 -1
- package/dist/client/assets/{empty-state-sf1-Jq0W.js → empty-state-CDIBHplc.js} +1 -1
- package/dist/client/assets/{empty-state-ypVDBd57.js → empty-state-DdD7u29c.js} +1 -1
- package/dist/client/assets/{extract-connection-data-DjI_aoBC.js → extract-connection-data-IvHnTVAw.js} +1 -1
- package/dist/client/assets/{feature-gate-DcRjQ5be.js → feature-gate-BWDpzS9z.js} +1 -1
- package/dist/client/assets/{feature-paywall-BJyKoG94.js → feature-paywall-BMHKK3Z9.js} +1 -1
- package/dist/client/assets/{file-explorer-4Pc4NHzH.js → file-explorer-D27HdHX3.js} +1 -1
- package/dist/client/assets/{file-preview-BEbWQaxd.js → file-preview-8F3P6Bl5.js} +1 -1
- package/dist/client/assets/{file-share-button-c3pbTUkm.js → file-share-button-DyElnx8z.js} +1 -1
- package/dist/client/assets/{file-type-icon-M-h3H6gl.js → file-type-icon-ClDaqk3f.js} +1 -1
- package/dist/client/assets/{folder-icon-u0aPfhqN.js → folder-icon-D04YRFhU.js} +1 -1
- package/dist/client/assets/{form-BW5sQRmk.js → form-C7tLG-xD.js} +1 -1
- package/dist/client/assets/{gateway-client-Iyhaszzo.js → gateway-client-BS6ihzBm.js} +1 -1
- package/dist/client/assets/{general-BvHqxpPY.js → general-B2rNnykE.js} +1 -1
- package/dist/client/assets/{github-icon-BDxNO7KC.js → github-icon-CfU12Xim.js} +1 -1
- package/dist/client/assets/{home-5wJZqSWV.js → home-i2aU9Ufv.js} +1 -1
- package/dist/client/assets/{hooks-DWWfCdjK.js → hooks-BdWJM6ej.js} +1 -1
- package/dist/client/assets/{icon-button-CtJzFHej.js → icon-button-DAJ4484y.js} +1 -1
- package/dist/client/assets/{index-By68j_mZ.js → index-3i5Lrx2p.js} +1 -1
- package/dist/client/assets/{index-ziWxoYuo.js → index-B_jqJjWZ.js} +39 -39
- package/dist/client/assets/{index-BTBWEo6K.js → index-CFR2L-q4.js} +1 -1
- package/dist/client/assets/{index-CS_gB0YL.js → index-CS_ks7u-.js} +1 -1
- package/dist/client/assets/{index-fHAcll79.js → index-Cc2tAO7N.js} +1 -1
- package/dist/client/assets/{index-BICcivlc.js → index-Chkg10uz.js} +1 -1
- package/dist/client/assets/{index-B_nJnclR.js → index-D6rGE1Dy.js} +1 -1
- package/dist/client/assets/{index-6cM3T3JU.js → index-DBxyNE8f.js} +1 -1
- package/dist/client/assets/{index-sefeb9SI.js → index-DZwO8JK7.js} +1 -1
- package/dist/client/assets/{index-CC84NaKX.js → index-DnYPqGbF.js} +1 -1
- package/dist/client/assets/{index-DMC1gEI3.js → index-DwgW_YLd.js} +1 -1
- package/dist/client/assets/{index-BO05OYcW.js → index-E9kwMDzy.js} +1 -1
- package/dist/client/assets/{index--em0zeg6.js → index-Hk82ozwG.js} +1 -1
- package/dist/client/assets/{index-9mA_jLNn.js → index-_sXoF1Et.js} +1 -1
- package/dist/client/assets/{index-redirect-Bup6rHGm.js → index-redirect-B6SWpWIS.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-C0scbCv9.js → infiniteQueryObserver-DSiFdm1_.js} +1 -1
- package/dist/client/assets/{infra-billing-DZvKZXmT.js → infra-billing-4kvUQS8R.js} +1 -1
- package/dist/client/assets/{input-CXPy1lnR.js → input-CPX_K4na.js} +1 -1
- package/dist/client/assets/{input-CztG7UMa.js → input-CUqzZQqX.js} +1 -1
- package/dist/client/assets/{input-CJpGQ1Th.js → input-D3d-YnPi.js} +1 -1
- package/dist/client/assets/{integration-icon-BzvUNmRE.js → integration-icon-DG8pRbj-.js} +1 -1
- package/dist/client/assets/{label-_3WYFdo5.js → label-B42WVwom.js} +1 -1
- package/dist/client/assets/{last-preview-page-CHWyRhbr.js → last-preview-page-VDeNxgNa.js} +1 -1
- package/dist/client/assets/{layout-DYIHs9kD.js → layout-Cg9QXreU.js} +1 -1
- package/dist/client/assets/{legacy-agents-deep-DBTnH6bL.js → legacy-agents-deep-BQwnmlAz.js} +1 -1
- package/dist/client/assets/{legacy-main-redirect-BsYq-xiI.js → legacy-main-redirect-DPq1EZZB.js} +1 -1
- package/dist/client/assets/{library-Do40Vk3o.js → library-C5v9Lai5.js} +1 -1
- package/dist/client/assets/{login-Btr57Seb.js → login-CQeYUvND.js} +1 -1
- package/dist/client/assets/{markdown-BA0WefIr.js → markdown-7es2nAha.js} +1 -1
- package/dist/client/assets/{mcp-app-renderer-BMekd9hK.js → mcp-app-renderer-DhZPltbk.js} +1 -1
- package/dist/client/assets/{mcp-oauth-9MW-5Yis.js → mcp-oauth-Ckxkgwom.js} +1 -1
- package/dist/client/assets/{members-C1yb5hTi.js → members-BwpS2FJg.js} +1 -1
- package/dist/client/assets/{message-templates-BreVPcoU.js → message-templates-B94eek_d.js} +1 -1
- package/dist/client/assets/{mini-report-page-C4fct7wn.js → mini-report-page-CsRp8RBX.js} +1 -1
- package/dist/client/assets/{mock-board-BtM1Rw_K.js → mock-board-CDJcm5pO.js} +3 -3
- package/dist/client/assets/{monaco-editor-Rppk41ht.js → monaco-editor-CVsFBD0x.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-Cc7ItOSd.js → monitoring-stats-row-ByyxXINL.js} +1 -1
- package/dist/client/assets/{multi-select-3KqHCA4E.js → multi-select-Dz5xTYyG.js} +1 -1
- package/dist/client/assets/{mustache-_Bjx0slz.js → mustache-CP6S3NLE.js} +1 -1
- package/dist/client/assets/{oauth-callback-Bcy-6PY_.js → oauth-callback-Doz3uO24.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-ly_LHSFd.js → oauth-callback-ai-provider-BNo5jLbk.js} +1 -1
- package/dist/client/assets/{onboarding-CbAB8H9h.js → onboarding-CFbudetK.js} +1 -1
- package/dist/client/assets/{optimistic-project-sidebar-views-BEr3crxf.js → optimistic-project-sidebar-views-BZFYBphr.js} +1 -1
- package/dist/client/assets/{org-file-open-context--mCB_iQy.js → org-file-open-context-BUYeSnyZ.js} +1 -1
- package/dist/client/assets/{organization-choice-BsW0tsr0.js → organization-choice-D785n-oL.js} +1 -1
- package/dist/client/assets/{orgs-DqNq_SYU.js → orgs-BYiTsfBK.js} +1 -1
- package/dist/client/assets/{page-seo-form-DojL7wpr.js → page-seo-form-DLdbZSvc.js} +1 -1
- package/dist/client/assets/{pair-B8zmeOHa.js → pair-Cntzz70t.js} +1 -1
- package/dist/client/assets/{plan-ladder-B4Yh8okh.js → plan-ladder-CgZjoFq0.js} +1 -1
- package/dist/client/assets/{popover-Bk7hW0ey.js → popover-D7TbzVGm.js} +1 -1
- package/dist/client/assets/{post-calendar-BV1eHaK8.js → post-calendar-C1z8ltmP.js} +1 -1
- package/dist/client/assets/{post-editor-BT9uGcZD.js → post-editor-C_EE2ywm.js} +1 -1
- package/dist/client/assets/{preview-content-QoDE1rCY.js → preview-content-BHvFZwTL.js} +1 -1
- package/dist/client/assets/{preview-dialog-C9P8-JXO.js → preview-dialog-LK5goGiO.js} +1 -1
- package/dist/client/assets/{profile-io3wVtBH.js → profile-C8Ekz_R3.js} +1 -1
- package/dist/client/assets/{project-app-view-uS1Oyo_z.js → project-app-view-w895ELfV.js} +1 -1
- package/dist/client/assets/{project-feed-BOlh1fkU.js → project-feed-BIeMuQsl.js} +1 -1
- package/dist/client/assets/{project-icon-Dqsi312T.js → project-icon-KCkwxFCZ.js} +1 -1
- package/dist/client/assets/project-reports-Cl2HONmy.js +1 -0
- package/dist/client/assets/project-tasks-BIMrLh_c.js +1 -0
- package/dist/client/assets/{prompts-BG-MPyn-.js → prompts-ndmFBjqL.js} +1 -1
- package/dist/client/assets/record-editor-DjlSkTMR.js +1 -0
- package/dist/client/assets/{redirect-editor-JipDfipG.js → redirect-editor-CguLDdkl.js} +1 -1
- package/dist/client/assets/reports-D5LirKe3.js +1 -0
- package/dist/client/assets/{reports-DKfv6F8w.js → reports-DlVcHkUD.js} +1 -1
- package/dist/client/assets/{reports-onboarding-Cy3jqQvd.js → reports-onboarding-Ds5SahYM.js} +1 -1
- package/dist/client/assets/{reports-tab-o_wsXSh7.js → reports-tab-DC6c1sVj.js} +2 -2
- package/dist/client/assets/{repositories-CSGkwVyT.js → repositories-CUfjI4El.js} +1 -1
- package/dist/client/assets/{repository-import-picker-CQVzq3BU.js → repository-import-picker-OZgXFfxq.js} +1 -1
- package/dist/client/assets/{repository-picker-BdMF9zgM.js → repository-picker-Cuj06eQZ.js} +1 -1
- package/dist/client/assets/{require-capability-DEtYkpLS.js → require-capability-naAuPznp.js} +1 -1
- package/dist/client/assets/{required-auth-layout-CAKi6iDw.js → required-auth-layout-BuQC1B0R.js} +1 -1
- package/dist/client/assets/{reset-password-CjXeqPrv.js → reset-password-C-TuQEuk.js} +1 -1
- package/dist/client/assets/{resizable-Dwlj_5ft.js → resizable-BSTHeCGD.js} +1 -1
- package/dist/client/assets/{review-settings-BUpwP2dx.js → review-settings-DPAP3K_X.js} +1 -1
- package/dist/client/assets/{rich-text-link-control-DNvgXQgl.js → rich-text-link-control-DSqyN-4h.js} +1 -1
- package/dist/client/assets/{roles-BTKe5RPi.js → roles-p5A3Dtl6.js} +1 -1
- package/dist/client/assets/{route-DAYL9p8i.js → route-CKMOQ40u.js} +1 -1
- package/dist/client/assets/{route-CW79snE6.js → route-CpKC5KjI.js} +1 -1
- package/dist/client/assets/{route-CJkw61Zc.js → route-DBh4p0P2.js} +1 -1
- package/dist/client/assets/{route-page-header-BX_04V6X.js → route-page-header-DqB3P7Mp.js} +1 -1
- package/dist/client/assets/{runnable-block-editor-BqGS6HoQ.js → runnable-block-editor-CgZ8SmOe.js} +1 -1
- package/dist/client/assets/{sandbox-lifecycle-context-CMg8X78k.js → sandbox-lifecycle-context-D9wQaDsx.js} +1 -1
- package/dist/client/assets/schema-B6bqanRf.js +1 -0
- package/dist/client/assets/{scroll-area-WP6xUrg2.js → scroll-area-bbynZh9-.js} +1 -1
- package/dist/client/assets/{search-input-CzMI7SbY.js → search-input-Btpivanp.js} +1 -1
- package/dist/client/assets/{search-toggle-_SwtmigM.js → search-toggle-CPZhZrMT.js} +1 -1
- package/dist/client/assets/{secret-picker-B7LbtI2k.js → secret-picker-AWBv6wFY.js} +1 -1
- package/dist/client/assets/{secrets-B5P1IBT4.js → secrets-Dj_h5xgB.js} +1 -1
- package/dist/client/assets/{sections-editor-DIx6r2h9.js → sections-editor-DHlfw38F.js} +1 -1
- package/dist/client/assets/{select-8KXSGRLl.js → select-jSjoqSVI.js} +1 -1
- package/dist/client/assets/{select-model-Bo57k2gC.js → select-model-xbu3VazG.js} +1 -1
- package/dist/client/assets/{seo-editor-BCM5fWif.js → seo-editor-cQIPvPvE.js} +1 -1
- package/dist/client/assets/{separator-BW4l_JXy.js → separator-CzwHfLvM.js} +1 -1
- package/dist/client/assets/{settings-tab-CvDc9lSQ.js → settings-tab-CeOX7aTs.js} +1 -1
- package/dist/client/assets/{sheet-BoIBD2fU.js → sheet-D_ZIeH1i.js} +1 -1
- package/dist/client/assets/{shell-layout-C4Rn0yyM.js → shell-layout-5RFwQBw2.js} +1 -1
- package/dist/client/assets/{skill-preview-CQYYDECQ.js → skill-preview-CNoU4Qye.js} +1 -1
- package/dist/client/assets/{skills-ByEvh5tv.js → skills-BJkniNrS.js} +1 -1
- package/dist/client/assets/{sso-CmLvBErH.js → sso-B9hnmDuf.js} +1 -1
- package/dist/client/assets/{suggestion-tuFcyOKm.js → suggestion-U-2vYvOO.js} +1 -1
- package/dist/client/assets/{switch-DPTro45D.js → switch-CxeV46Qg.js} +1 -1
- package/dist/client/assets/{synced-repos-B4c-CrQ7.js → synced-repos-21EGZfBM.js} +1 -1
- package/dist/client/assets/{table-C7ZZ1Gh3.js → table-C-Py-wTW.js} +1 -1
- package/dist/client/assets/{tabs-CI-qOCoA.js → tabs-C3x66yHR.js} +1 -1
- package/dist/client/assets/{task-board-DPuIO3lj.js → task-board-DfS5a_U6.js} +1 -1
- package/dist/client/assets/{task-route-B502sFo7.js → task-route-D4Lm7oMd.js} +1 -1
- package/dist/client/assets/{task-status-CY7tmQAt.js → task-status-BVsZxsbL.js} +1 -1
- package/dist/client/assets/{taskboard-analytics-wJrWcpXu.js → taskboard-analytics-BPvIiWmk.js} +1 -1
- package/dist/client/assets/tasks-DcFwVI3V.js +1 -0
- package/dist/client/assets/{tasks-DdJpYlFL.js → tasks-DiyaPFMr.js} +1 -1
- package/dist/client/assets/{textarea-BncilA97.js → textarea-BWwZU_t6.js} +1 -1
- package/dist/client/assets/{thread-analytics-ApATKMqj.js → thread-analytics-DUYI7gXn.js} +1 -1
- package/dist/client/assets/{thread-button-DJeTkAyH.js → thread-button-C_OQPTk1.js} +1 -1
- package/dist/client/assets/{thread-intent-BNnANQO5.js → thread-intent-E5sYh_tC.js} +1 -1
- package/dist/client/assets/{thread-route-CBWg87G3.js → thread-route-BDTLcWS1.js} +1 -1
- package/dist/client/assets/{thread-route-M4rTxHUV.js → thread-route-BZ26YLl1.js} +1 -1
- package/dist/client/assets/{thread-sheet-body-CFRV6F8c.js → thread-sheet-body-CsPcwFou.js} +1 -1
- package/dist/client/assets/{toggle-group-DnlZm5ed.js → toggle-group-Br61F69t.js} +1 -1
- package/dist/client/assets/{toolbar-icon-button-D8Zp_HQd.js → toolbar-icon-button-DAWIeeny.js} +1 -1
- package/dist/client/assets/{tooltip-OlmP4Xne.js → tooltip-MGIMGAoz.js} +1 -1
- package/dist/client/assets/{track-B0Nkp-gO.js → track-DRMUb5wX.js} +1 -1
- package/dist/client/assets/{types-DXypKwsh.js → types-BobDzo_S.js} +1 -1
- package/dist/client/assets/{usage-stats-CAm8ll0C.js → usage-stats-CtwYJCDG.js} +1 -1
- package/dist/client/assets/{use-ai-providers-Lvr_1665.js → use-ai-providers-D3QOmX-C.js} +1 -1
- package/dist/client/assets/{use-automations-81CjRTlN.js → use-automations-cNW48WkH.js} +1 -1
- package/dist/client/assets/{use-autosave-t6s5wMUE.js → use-autosave-VCuxTv0J.js} +1 -1
- package/dist/client/assets/{use-connect-companion-BxZZw6OD.js → use-connect-companion-BuSwVwXM.js} +1 -1
- package/dist/client/assets/{use-connection-DXReahBl.js → use-connection-BhRHLAsr.js} +1 -1
- package/dist/client/assets/{use-copy-DZfoedG5.js → use-copy-BF-mjGgx.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-D3lKBA1-.js → use-create-virtual-mcp-DwVcqONE.js} +1 -1
- package/dist/client/assets/{use-date-fns-locale-B6lsja9n.js → use-date-fns-locale-DCvnbugy.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-D2HFk0bO.js → use-debounced-autosave-jBJVBJsX.js} +1 -1
- package/dist/client/assets/{use-debounced-value-C7-JMyFp.js → use-debounced-value-I_7zwW8J.js} +1 -1
- package/dist/client/assets/{use-deco-credits-hhJiNpZB.js → use-deco-credits-Doeu9LgP.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-zVeGPrg4.js → use-decopilot-events-BnXMCuEf.js} +1 -1
- package/dist/client/assets/{use-delete-connection-B5GiyA_y.js → use-delete-connection-CvMWFyh1.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-Bw0ESsNA.js → use-deployment-admin-BetxU96z.js} +1 -1
- package/dist/client/assets/{use-entitlements-DdLeP5e8.js → use-entitlements-CObs1qD4.js} +1 -1
- package/dist/client/assets/{use-fast-preview-draft-url-DmGf6kPM.js → use-fast-preview-draft-url--bVRoyz9.js} +1 -1
- package/dist/client/assets/{use-file-configs-DtnzXs8S.js → use-file-configs-DigsDSAK.js} +1 -1
- package/dist/client/assets/{use-in-settings-Dvk70b-r.js → use-in-settings-kPZjTMQr.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-OBKDpZd2.js → use-infinite-scroll-R-FVBBxh.js} +1 -1
- package/dist/client/assets/{use-join-requests-BR_Ts9mr.js → use-join-requests-BUHZc4Mq.js} +1 -1
- package/dist/client/assets/{use-main-panel-tabs-D7hvsAEq.js → use-main-panel-tabs-DQnZor4-.js} +1 -1
- package/dist/client/assets/{use-mcp-auth-status-B6yMK8tP.js → use-mcp-auth-status-ermcBJaV.js} +1 -1
- package/dist/client/assets/{use-mcp-client-D0GxBaDo.js → use-mcp-client-BdNrVAJP.js} +1 -1
- package/dist/client/assets/{use-mcp-prompts-CYjViP6k.js → use-mcp-prompts-1Ewo80b8.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-_g4NAjrq.js → use-mcp-tools-Cu0xFgEP.js} +1 -1
- package/dist/client/assets/{use-members-Ct_DkclC.js → use-members-hbcweNuZ.js} +1 -1
- package/dist/client/assets/{use-mobile-DL0BBun-.js → use-mobile-beNLxD1C.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-C0Wb0lHC.js → use-navigate-to-agent-C6DjZGwr.js} +1 -1
- package/dist/client/assets/{use-open-billing-url-5Jl47ZN-.js → use-open-billing-url-y3R__MyB.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-BhlcNBON.js → use-org-auth-client-Cn5VVAMk.js} +1 -1
- package/dist/client/assets/{use-org-fs-BZxhCLBv.js → use-org-fs-iJQRZ_Y8.js} +1 -1
- package/dist/client/assets/{use-org-sso-B67vSzPL.js → use-org-sso-DUkP7wB6.js} +1 -1
- package/dist/client/assets/{use-organization-roles-DvWLvtJo.js → use-organization-roles-B_L60GhE.js} +1 -1
- package/dist/client/assets/{use-organization-settings-Cj191Ewd.js → use-organization-settings-DkOGSUvX.js} +1 -1
- package/dist/client/assets/{use-panel-navigate-CxM_dPDF.js → use-panel-navigate-rE0Chr-2.js} +1 -1
- package/dist/client/assets/{use-project-native-view-presence-Dpkg39tr.js → use-project-native-view-presence-1YdimLRn.js} +1 -1
- package/dist/client/assets/{use-project-scope-CmwWylK9.js → use-project-scope-P0x76zE6.js} +1 -1
- package/dist/client/assets/{use-releases-C64Gw739.js → use-releases-B1QdX0n3.js} +1 -1
- package/dist/client/assets/{use-reports-diagnostic-BlZh8B-b.js → use-reports-diagnostic-rG5xwYUZ.js} +1 -1
- package/dist/client/assets/{use-route-default-main-4PMl5Y8H.js → use-route-default-main-D9XS7l59.js} +1 -1
- package/dist/client/assets/{use-secrets-DCi_KkhE.js → use-secrets-omlZfkaj.js} +1 -1
- package/dist/client/assets/{use-section-preview-base-0PubG-2k.js → use-section-preview-base-D8Bv__bX.js} +1 -1
- package/dist/client/assets/{use-session-runtime-BQHvzOwo.js → use-session-runtime-DdWkBfbN.js} +1 -1
- package/dist/client/assets/{use-tags-NI2eu5Cz.js → use-tags-CTTUJ_N1.js} +1 -1
- package/dist/client/assets/{use-task-board-analytics-Xdiuqy_o.js → use-task-board-analytics-CnU57ib7.js} +1 -1
- package/dist/client/assets/{use-task-metadata-CCc0stnS.js → use-task-metadata-DDYUL_Qx.js} +1 -1
- package/dist/client/assets/{use-thread-analytics-CYxmK_WD.js → use-thread-analytics-Dr_m25eO.js} +1 -1
- package/dist/client/assets/{use-thread-outputs-Bv992dBv.js → use-thread-outputs-DM_M_g6a.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-D6_hi4NV.js → use-virtual-mcp-DfNb-iFO.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-U5kS7Aw3.js +1 -0
- package/dist/client/assets/{useQueries-Dh-P597K.js → useQueries-o0vNhPOA.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-BGK64Vi3.js +1 -0
- package/dist/client/assets/{users-D2bWKe0T.js → users-DoJNHPyq.js} +1 -1
- package/dist/client/assets/{utils-Drhm0YFn.js → utils-YiROKHsB.js} +1 -1
- package/dist/client/assets/{variant-calendar-aRH9J9TF.js → variant-calendar-h0YzSol5.js} +1 -1
- package/dist/client/assets/{variant-matcher-override-D83fZJgn.js → variant-matcher-override-Dw_V_0pd.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-CyBHOQ0X.js → view-mode-toggle-BzLcGe3J.js} +1 -1
- package/dist/client/assets/{virtual-mcp-BcxcIP1Z.js → virtual-mcp-VXYym_wm.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +791 -738
- package/dist/server/migrate.js +288 -235
- package/dist/server/server.js +8 -8
- package/package.json +1 -1
- package/dist/client/assets/agent-app-Sr-2nirf.js +0 -1
- package/dist/client/assets/agent-deck-D-UCGYQX.js +0 -1
- package/dist/client/assets/agent-library-file-Cvi8jKHC.js +0 -1
- package/dist/client/assets/agent-settings-CTbjU_Gy.js +0 -1
- package/dist/client/assets/agent-site-editor-code-DR-g4J4J.js +0 -2
- package/dist/client/assets/agent-view-B6BDTAiP.js +0 -1
- package/dist/client/assets/api-keys-CvoR7Xp2.js +0 -1
- package/dist/client/assets/app-editor-BxSmqsZG.js +0 -1
- package/dist/client/assets/project-reports-DDobh4a3.js +0 -1
- package/dist/client/assets/project-tasks-DQbSKuzy.js +0 -1
- package/dist/client/assets/record-editor-BEfIzmJ1.js +0 -1
- package/dist/client/assets/reports-DypWpAd4.js +0 -1
- package/dist/client/assets/schema-DVTBToxW.js +0 -1
- package/dist/client/assets/tasks-BCglhWH3.js +0 -1
- package/dist/client/assets/useInfiniteQuery-BGHP6rbt.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-D4hZ-82Z.js +0 -1
package/dist/server/server.js
CHANGED
|
@@ -76,7 +76,7 @@ Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.ht
|
|
|
76
76
|
However, a future version may change this behavior to prefer the ENV static credentials.
|
|
77
77
|
Please ensure that your environment only sets either the AWS_PROFILE or the
|
|
78
78
|
AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
|
|
79
|
-
`),Hx1=!0}throw new EZ0.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.",{logger:$.logger,tryNextLink:!0})}return $.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"),ex0($)()},async(Z)=>{$.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");let{ssoStartUrl:Q,ssoAccountId:Y,ssoRegion:X,ssoRoleName:J,ssoSession:G}=$;if(!Q&&!Y&&!X&&!J&&!G)throw new EZ0.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).",{logger:$.logger});let{fromSSO:W}=await Promise.resolve().then(() => (Fy0(),Hy0));return W($)(Z)},async(Z)=>{$.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");let{fromIni:Q}=await Promise.resolve().then(() => (Kx1(),Wx1));return Q($)(Z)},async(Z)=>{$.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");let{fromProcess:Q}=await Promise.resolve().then(() => (Ng0(),Ug0));return Q($)(Z)},async(Z)=>{$.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");let{fromTokenFile:Q}=await Promise.resolve().then(() => (jg0(),wg0));return Q($)(Z)},async()=>{return $.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"),(await MV1($))()},async()=>{throw new EZ0.CredentialsProviderError("Could not load credentials from any providers",{tryNextLink:!1,logger:$.logger})}],Nh8),Nh8=($)=>$?.expiration!==void 0&&$.expiration.getTime()-Date.now()<300000;var Nx1=D(()=>{$f0();IV1();EZ0=C(b5(),1),Fx1=C(rY(),1)});var Bx1=D(()=>{Nx1()});var Ox1=()=>{};var hg,Bh8="AWS_S3_USE_ARN_REGION",Oh8="s3_use_arn_region",Dx1;var Lx1=D(()=>{hg=C(xp(),1),Dx1={environmentVariableSelector:($)=>hg.booleanSelector($,Bh8,hg.SelectorType.ENV),configFileSelector:($)=>hg.booleanSelector($,Oh8,hg.SelectorType.CONFIG),default:void 0}});var wx1=()=>{};var jx1=()=>{};var Ex1=D(()=>{Ox1();Lx1();jx1();wx1()});class ug{bytes;constructor($){if(this.bytes=$,$.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber($){if($>9223372036854776000||$<-9223372036854776000)throw Error(`${$} is too large (or, if negative, too small) to represent as an Int64`);let Z=new Uint8Array(8);for(let Q=7,Y=Math.abs(Math.round($));Q>-1&&Y>0;Q--,Y/=256)Z[Q]=Y;if($<0)zx1(Z);return new ug(Z)}valueOf(){let $=this.bytes.slice(0),Z=$[0]&128;if(Z)zx1($);return parseInt(Px1.toHex($),16)*(Z?-1:1)}toString(){return String(this.valueOf())}}function zx1($){for(let Z=0;Z<8;Z++)$[Z]^=255;for(let Z=7;Z>-1;Z--)if($[Z]++,$[Z]!==0)break}var Px1;var zg0=D(()=>{Px1=C(Fp(),1)});class Pg0{toUtf8;fromUtf8;constructor($,Z){this.toUtf8=$,this.fromUtf8=Z}format($){let Z=[];for(let X of Object.keys($)){let J=this.fromUtf8(X);Z.push(Uint8Array.from([J.byteLength]),J,this.formatHeaderValue($[X]))}let Q=new Uint8Array(Z.reduce((X,J)=>X+J.byteLength,0)),Y=0;for(let X of Z)Q.set(X,Y),Y+=X.byteLength;return Q}formatHeaderValue($){switch($.type){case"boolean":return Uint8Array.from([$.value?0:1]);case"byte":return Uint8Array.from([2,$.value]);case"short":let Z=new DataView(new ArrayBuffer(3));return Z.setUint8(0,3),Z.setInt16(1,$.value,!1),new Uint8Array(Z.buffer);case"integer":let Q=new DataView(new ArrayBuffer(5));return Q.setUint8(0,4),Q.setInt32(1,$.value,!1),new Uint8Array(Q.buffer);case"long":let Y=new Uint8Array(9);return Y[0]=5,Y.set($.value.bytes,1),Y;case"binary":let X=new DataView(new ArrayBuffer(3+$.value.byteLength));X.setUint8(0,6),X.setUint16(1,$.value.byteLength,!1);let J=new Uint8Array(X.buffer);return J.set($.value,3),J;case"string":let G=this.fromUtf8($.value),W=new DataView(new ArrayBuffer(3+G.byteLength));W.setUint8(0,7),W.setUint16(1,G.byteLength,!1);let K=new Uint8Array(W.buffer);return K.set(G,3),K;case"timestamp":let H=new Uint8Array(9);return H[0]=8,H.set(ug.fromNumber($.value.valueOf()).bytes,1),H;case"uuid":if(!Th8.test($.value))throw Error(`Invalid UUID received: ${$.value}`);let F=new Uint8Array(17);return F[0]=9,F.set(TD.fromHex($.value.replace(/\-/g,"")),1),F}}parse($){let Z={},Q=0;while(Q<$.byteLength){let Y=$.getUint8(Q++),X=this.toUtf8(new Uint8Array($.buffer,$.byteOffset+Q,Y));switch(Q+=Y,$.getUint8(Q++)){case 0:Z[X]={type:Tx1,value:!0};break;case 1:Z[X]={type:Tx1,value:!1};break;case 2:Z[X]={type:Dh8,value:$.getInt8(Q++)};break;case 3:Z[X]={type:Lh8,value:$.getInt16(Q,!1)},Q+=2;break;case 4:Z[X]={type:wh8,value:$.getInt32(Q,!1)},Q+=4;break;case 5:Z[X]={type:jh8,value:new ug(new Uint8Array($.buffer,$.byteOffset+Q,8))},Q+=8;break;case 6:let J=$.getUint16(Q,!1);Q+=2,Z[X]={type:Eh8,value:new Uint8Array($.buffer,$.byteOffset+Q,J)},Q+=J;break;case 7:let G=$.getUint16(Q,!1);Q+=2,Z[X]={type:zh8,value:this.toUtf8(new Uint8Array($.buffer,$.byteOffset+Q,G))},Q+=G;break;case 8:Z[X]={type:Ph8,value:new Date(new ug(new Uint8Array($.buffer,$.byteOffset+Q,8)).valueOf())},Q+=8;break;case 9:let W=new Uint8Array($.buffer,$.byteOffset+Q,16);Q+=16,Z[X]={type:Ah8,value:`${TD.toHex(W.subarray(0,4))}-${TD.toHex(W.subarray(4,6))}-${TD.toHex(W.subarray(6,8))}-${TD.toHex(W.subarray(8,10))}-${TD.toHex(W.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return Z}}var TD,Ax1,Tx1="boolean",Dh8="byte",Lh8="short",wh8="integer",jh8="long",Eh8="binary",zh8="string",Ph8="timestamp",Ah8="uuid",Th8;var Ag0=D(()=>{zg0();TD=C(Fp(),1);(function($){$[$.boolTrue=0]="boolTrue",$[$.boolFalse=1]="boolFalse",$[$.byte=2]="byte",$[$.short=3]="short",$[$.integer=4]="integer",$[$.long=5]="long",$[$.byteArray=6]="byteArray",$[$.string=7]="string",$[$.timestamp=8]="timestamp",$[$.uuid=9]="uuid"})(Ax1||(Ax1={}));Th8=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/});function Mx1({byteLength:$,byteOffset:Z,buffer:Q}){if($<Rh8)throw Error("Provided message too short to accommodate event stream message overhead");let Y=new DataView(Q,Z,$),X=Y.getUint32(0,!1);if($!==X)throw Error("Reported message length does not match received message length");let J=Y.getUint32(qx1,!1),G=Y.getUint32(RD,!1),W=Y.getUint32($-qz,!1),K=new Rx1.Crc32().update(new Uint8Array(Q,Z,RD));if(G!==K.digest())throw Error(`The prelude checksum specified in the message (${G}) does not match the calculated CRC32 checksum (${K.digest()})`);if(K.update(new Uint8Array(Q,Z+RD,$-(RD+qz))),W!==K.digest())throw Error(`The message checksum (${K.digest()}) did not match the expected value of ${W}`);return{headers:new DataView(Q,Z+RD+qz,J),body:new Uint8Array(Q,Z+RD+qz+J,X-J-(RD+qz+qz))}}var Rx1,qx1=4,RD,qz=4,Rh8;var Ix1=D(()=>{Rx1=C(iE(),1),RD=qx1*2,Rh8=RD+qz*2});class Tg0{headerMarshaller;messageBuffer;isEndOfStream;constructor($,Z){this.headerMarshaller=new Pg0($,Z),this.messageBuffer=[],this.isEndOfStream=!1}feed($){this.messageBuffer.push(this.decode($))}endOfStream(){this.isEndOfStream=!0}getMessage(){let $=this.messageBuffer.pop(),Z=this.isEndOfStream;return{getMessage(){return $},isEndOfStream(){return Z}}}getAvailableMessages(){let $=this.messageBuffer;this.messageBuffer=[];let Z=this.isEndOfStream;return{getMessages(){return $},isEndOfStream(){return Z}}}encode({headers:$,body:Z}){let Q=this.headerMarshaller.format($),Y=Q.byteLength+Z.byteLength+16,X=new Uint8Array(Y),J=new DataView(X.buffer,X.byteOffset,X.byteLength),G=new Vx1.Crc32;return J.setUint32(0,Y,!1),J.setUint32(4,Q.byteLength,!1),J.setUint32(8,G.update(X.subarray(0,8)).digest(),!1),X.set(Q,12),X.set(Z,Q.byteLength+12),J.setUint32(Y-4,G.update(X.subarray(8,Y-4)).digest(),!1),X}decode($){let{headers:Z,body:Q}=Mx1($);return{headers:this.headerMarshaller.parse(Z),body:Q}}formatHeaders($){return this.headerMarshaller.format($)}}var Vx1;var kx1=D(()=>{Ag0();Ix1();Vx1=C(iE(),1)});var Sx1=()=>{};var Rg0;var Cx1=D(()=>{Rg0=class Rg0{options;constructor($){this.options=$}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let $ of this.options.inputStream)yield this.options.decoder.decode($)}}});var qg0;var _x1=D(()=>{qg0=class qg0{options;constructor($){this.options=$}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let $ of this.options.messageStream)yield this.options.encoder.encode($);if(this.options.includeEndFrame)yield new Uint8Array(0)}}});var Mg0;var vx1=D(()=>{Mg0=class Mg0{options;constructor($){this.options=$}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let $ of this.options.messageStream){let Z=await this.options.deserializer($);if(Z===void 0)continue;yield Z}}}});var Ig0;var bx1=D(()=>{Ig0=class Ig0{options;constructor($){this.options=$}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let $ of this.options.inputStream)yield this.options.serializer($)}}});var xx1=D(()=>{kx1();Ag0();zg0();Sx1();Cx1();_x1();vx1();bx1()});function fx1($){let Z=0,Q=0,Y=null,X=null,J=(W)=>{if(typeof W!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+W);Z=W,Q=4,Y=new Uint8Array(W),new DataView(Y.buffer).setUint32(0,W,!1)},G=async function*(){let W=$[Symbol.asyncIterator]();while(!0){let{value:K,done:H}=await W.next();if(H){if(!Z)return;else if(Z===Q)yield Y;else throw Error("Truncated event message received.");return}let F=K.length,U=0;while(U<F){if(!Y){let B=F-U;if(!X)X=new Uint8Array(4);let O=Math.min(4-Q,B);if(X.set(K.slice(U,U+O),Q),Q+=O,U+=O,Q<4)break;J(new DataView(X.buffer).getUint32(0,!1)),X=null}let N=Math.min(Z-Q,F-U);if(Y.set(K.slice(U,U+N),Q),Q+=N,U+=N,Z&&Z===Q)yield Y,Y=null,Z=0,Q=0}}};return{[Symbol.asyncIterator]:G}}function yx1($,Z){return async function(Q){let{value:Y}=Q.headers[":message-type"];if(Y==="error"){let X=Error(Q.headers[":error-message"].value||"UnknownError");throw X.name=Q.headers[":error-code"].value,X}else if(Y==="exception"){let X=Q.headers[":exception-type"].value,J={[X]:Q},G=await $(J);if(G.$unknown){let W=Error(Z(Q.body));throw W.name=X,W}throw G[X]}else if(Y==="event"){let X={[Q.headers[":event-type"].value]:Q},J=await $(X);if(J.$unknown)return;return J}else throw Error(`Unrecognizable event type: ${Q.headers[":event-type"].value}`)}}class Vg0{eventStreamCodec;utfEncoder;constructor({utf8Encoder:$,utf8Decoder:Z}){this.eventStreamCodec=new Tg0($,Z),this.utfEncoder=$}deserialize($,Z){let Q=fx1($);return new Mg0({messageStream:new Rg0({inputStream:Q,decoder:this.eventStreamCodec}),deserializer:yx1(Z,this.utfEncoder)})}serialize($,Z){return new qg0({messageStream:new Ig0({inputStream:$,serializer:Z}),encoder:this.eventStreamCodec,includeEndFrame:!0})}}var gx1=D(()=>{xx1()});var hx1=()=>{};var ux1=D(()=>{gx1();hx1()});async function*lx1($){let Z=!1,Q=!1,Y=[];$.on("error",(X)=>{if(!Z)Z=!0;if(X)throw X}),$.on("data",(X)=>{Y.push(X)}),$.on("end",()=>{Z=!0});while(!Q){let X=await new Promise((J)=>setTimeout(()=>J(Y.shift()),0));if(X)yield X;Q=Z&&Y.length===0}}import{Readable as qh8}from"stream";class kg0{universalMarshaller;constructor({utf8Encoder:$,utf8Decoder:Z}){this.universalMarshaller=new Vg0({utf8Decoder:Z,utf8Encoder:$})}deserialize($,Z){let Q=typeof $[Symbol.asyncIterator]==="function"?$:lx1($);return this.universalMarshaller.deserialize(Q,Z)}serialize($,Z){return qh8.from(this.universalMarshaller.serialize($,Z))}}var Sg0=D(()=>{ux1()});var cx1=($)=>new kg0($);var mx1=D(()=>{Sg0()});var dx1=D(()=>{Sg0();mx1()});import{Writable as Mh8}from"stream";var ix1,Cg0;var px1=D(()=>{ix1=C(GQ(),1);Cg0=class Cg0 extends Mh8{hash;constructor($,Z){super(Z);this.hash=$}_write($,Z,Q){try{this.hash.update(ix1.toUint8Array($))}catch(Y){return Q(Y)}Q()}}});var nx1=()=>{};var tx1=($,Z)=>{if(Z.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let Q=new $,Y=new Cg0(Q);return Z.pipe(Y),new Promise((X,J)=>{Z.on("error",(G)=>{Y.end(),J(G)}),Y.on("error",J),Y.on("finish",()=>{Q.digest().then(X).catch(J)})})};var ox1=D(()=>{px1()});var rx1=D(()=>{nx1();ox1()});var zZ0,sx1,ax1,ex1,$f1,PZ0,AZ0,TZ0,Zf1=($)=>{return{apiVersion:"2006-03-01",base64Decoder:$?.base64Decoder??PZ0.fromBase64,base64Encoder:$?.base64Encoder??PZ0.toBase64,disableHostPrefix:$?.disableHostPrefix??!1,endpointProvider:$?.endpointProvider??$90,extensions:$?.extensions??[],getAwsChunkedEncodingStream:$?.getAwsChunkedEncodingStream??AZ0.getAwsChunkedEncodingStream,httpAuthSchemeProvider:$?.httpAuthSchemeProvider??Xq1,httpAuthSchemes:$?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(Z)=>Z.getIdentityProvider("aws.auth#sigv4"),signer:new zZ0.AwsSdkSigV4Signer},{schemeId:"aws.auth#sigv4a",identityProvider:(Z)=>Z.getIdentityProvider("aws.auth#sigv4a"),signer:new zZ0.AwsSdkSigV4ASigner}],logger:$?.logger??new ex1.NoOpLogger,protocol:$?.protocol??sx1.S3RestXmlProtocol,protocolSettings:$?.protocolSettings??{defaultNamespace:"com.amazonaws.s3",errorTypeRegistries:Fq1,xmlNamespace:"http://s3.amazonaws.com/doc/2006-03-01/",version:"2006-03-01",serviceTarget:"AmazonS3"},sdkStreamMixin:$?.sdkStreamMixin??AZ0.sdkStreamMixin,serviceId:$?.serviceId??"S3",signerConstructor:$?.signerConstructor??ax1.SignatureV4MultiRegion,signingEscapePath:$?.signingEscapePath??!1,urlParser:$?.urlParser??$f1.parseUrl,useArnRegion:$?.useArnRegion??void 0,utf8Decoder:$?.utf8Decoder??TZ0.fromUtf8,utf8Encoder:$?.utf8Encoder??TZ0.toUtf8}};var Qf1=D(()=>{ux0();hx0();J1();zZ0=C(oQ(),1),sx1=C($$(),1),ax1=C(Eg(),1),ex1=C(i0(),1),$f1=C(vH(),1),PZ0=C(uX(),1),AZ0=C(py(),1),TZ0=C(GQ(),1)});var Yf1,qZ0,Xf1,MZ0,qD,RZ0,IZ0,WG,VZ0,kZ0,Jf1,Gf1,Wf1,Kf1=($)=>{kZ0.emitWarningIfUnsupportedVersion(process.version);let Z=Gf1.resolveDefaultsModeConfig($),Q=()=>Z().then(kZ0.loadConfigsForDefaultMode),Y=Zf1($);Yf1.emitWarningIfUnsupportedVersion(process.version);let X={profile:$?.profile,logger:Y.logger};return{...Y,...$,runtime:"node",defaultsMode:Z,authSchemePreference:$?.authSchemePreference??WG.loadConfig(qZ0.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,X),bodyLengthChecker:$?.bodyLengthChecker??Jf1.calculateBodyLength,credentialDefaultProvider:$?.credentialDefaultProvider??Ux1,defaultUserAgentProvider:$?.defaultUserAgentProvider??MZ0.createDefaultUserAgentProvider({serviceId:Y.serviceId,clientVersion:uI1.version}),disableS3ExpressSessionAuth:$?.disableS3ExpressSessionAuth??WG.loadConfig(Xf1.NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS,X),eventStreamSerdeProvider:$?.eventStreamSerdeProvider??cx1,maxAttempts:$?.maxAttempts??WG.loadConfig(IZ0.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,$),md5:$?.md5??RZ0.Hash.bind(null,"md5"),region:$?.region??WG.loadConfig(qD.NODE_REGION_CONFIG_OPTIONS,{...qD.NODE_REGION_CONFIG_FILE_OPTIONS,...X}),requestChecksumCalculation:$?.requestChecksumCalculation??WG.loadConfig(oL1,X),requestHandler:VZ0.NodeHttpHandler.create($?.requestHandler??Q),responseChecksumValidation:$?.responseChecksumValidation??WG.loadConfig(sL1,X),retryMode:$?.retryMode??WG.loadConfig({...IZ0.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await Q()).retryMode||Wf1.DEFAULT_RETRY_MODE},$),sha1:$?.sha1??RZ0.Hash.bind(null,"sha1"),sha256:$?.sha256??RZ0.Hash.bind(null,"sha256"),sigv4aSigningRegionSet:$?.sigv4aSigningRegionSet??WG.loadConfig(qZ0.NODE_SIGV4A_CONFIG_OPTIONS,X),streamCollector:$?.streamCollector??VZ0.streamCollector,streamHasher:$?.streamHasher??tx1,useArnRegion:$?.useArnRegion??WG.loadConfig(Dx1,X),useDualstackEndpoint:$?.useDualstackEndpoint??WG.loadConfig(qD.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,X),useFipsEndpoint:$?.useFipsEndpoint??WG.loadConfig(qD.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,X),userAgentAppId:$?.userAgentAppId??WG.loadConfig(MZ0.NODE_APP_ID_CONFIG_OPTIONS,X)}};var Hf1=D(()=>{hI1();Bx1();Ex1();A6();dx1();rx1();Qf1();Yf1=C(X9(),1),qZ0=C(oQ(),1),Xf1=C($$(),1),MZ0=C(Mg(),1),qD=C(mX(),1),RZ0=C(Ig(),1),IZ0=C(oW(),1),WG=C(tW(),1),VZ0=C(QD(),1),kZ0=C(i0(),1),Jf1=C(Vg(),1),Gf1=C(kg(),1),Wf1=C(WN(),1)});var Ff1=($)=>{let{httpAuthSchemes:Z,httpAuthSchemeProvider:Q,credentials:Y}=$;return{setHttpAuthScheme(X){let J=Z.findIndex((G)=>G.schemeId===X.schemeId);if(J===-1)Z.push(X);else Z.splice(J,1,X)},httpAuthSchemes(){return Z},setHttpAuthSchemeProvider(X){Q=X},httpAuthSchemeProvider(){return Q},setCredentials(X){Y=X},credentials(){return Y}}},Uf1=($)=>{return{httpAuthSchemes:$.httpAuthSchemes(),httpAuthSchemeProvider:$.httpAuthSchemeProvider(),credentials:$.credentials()}};var SZ0,CZ0,_Z0,Nf1=($,Z)=>{let Q=Object.assign(SZ0.getAwsRegionExtensionConfiguration($),_Z0.getDefaultExtensionConfiguration($),CZ0.getHttpHandlerExtensionConfiguration($),Ff1($));return Z.forEach((Y)=>Y.configure(Q)),Object.assign($,SZ0.resolveAwsRegionExtensionConfiguration(Q),_Z0.resolveDefaultRuntimeConfig(Q),CZ0.resolveHttpHandlerRuntimeConfig(Q),Uf1(Q))};var Bf1=D(()=>{SZ0=C(Kz(),1),CZ0=C(v5(),1),_Z0=C(i0(),1)});var vZ0,Of1,Df1,gH,bZ0,Lf1,lg,wf1,jf1,Ef1,xZ0,zf1,eY;var Mz=D(()=>{nL1();A6();a21();ux0();E90();W1();Hf1();Bf1();vZ0=C(ay(),1),Of1=C(ey(),1),Df1=C($g(),1),gH=C($$(),1),bZ0=C(Qz(),1),Lf1=C(mX(),1),lg=C(X7(),1),wf1=C(pQ(),1),jf1=C(Dg(),1),Ef1=C(Y1(),1),xZ0=C(oW(),1),zf1=C(i0(),1);eY=class eY extends zf1.Client{config;constructor(...[$]){let Z=Kf1($||{});super(Z);this.initConfig=Z;let Q=Gq1(Z),Y=bZ0.resolveUserAgentConfig(Q),X=Rz1(Y),J=xZ0.resolveRetryConfig(X),G=Lf1.resolveRegionConfig(J),W=vZ0.resolveHostHeaderConfig(G),K=Ef1.resolveEndpointConfig(W),H=s21(K),F=Jq1(H),U=gH.resolveS3Config(F,{session:[()=>this,np]}),N=Nf1(U,$?.extensions||[]);this.config=N,this.middlewareStack.use(wf1.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(bZ0.getUserAgentPlugin(this.config)),this.middlewareStack.use(xZ0.getRetryPlugin(this.config)),this.middlewareStack.use(jf1.getContentLengthPlugin(this.config)),this.middlewareStack.use(vZ0.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Of1.getLoggerPlugin(this.config)),this.middlewareStack.use(Df1.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(lg.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:Zq1,identityProviderConfigProvider:async(B)=>new lg.DefaultIdentityProviderConfig({"aws.auth#sigv4":B.credentials,"aws.auth#sigv4a":B.credentials})})),this.middlewareStack.use(lg.getHttpSigningPlugin(this.config)),this.middlewareStack.use(gH.getValidateBucketNamePlugin(this.config)),this.middlewareStack.use(pL1(this.config)),this.middlewareStack.use(gH.getRegionRedirectMiddlewarePlugin(this.config)),this.middlewareStack.use(gH.getS3ExpressPlugin(this.config)),this.middlewareStack.use(gH.getS3ExpressHttpSigningPlugin(this.config))}destroy(){super.destroy()}}});var Pf1,Af1,Tf1,On;var _g0=D(()=>{W1();J1();Pf1=C($$(),1),Af1=C(Y1(),1),Tf1=C(i0(),1);On=class On extends Tf1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[Af1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Pf1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","AbortMultipartUpload",{}).n("S3Client","AbortMultipartUploadCommand").sc(yq1).build(){}});function Ih8($){return(Z)=>async(Q)=>{let Y={...Q.input},X=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}];for(let J of X){let G=Y[J.target];if(G){let W;if(typeof G==="string")if(kh8(G,$))W=$.base64Decoder(G);else W=$.utf8Decoder(G),Y[J.target]=$.base64Encoder(W);else W=ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):new Uint8Array(G),Y[J.target]=$.base64Encoder(W);let K=new $.md5;K.update(W),Y[J.hash]=$.base64Encoder(await K.digest())}}return Z({...Q,input:Y})}}function kh8($,Z){if(!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))return!1;try{return Z.base64Decoder($).length===32}catch{return!1}}var Vh8,r9=($)=>({applyToStack:(Z)=>{Z.add(Ih8($),Vh8)}});var R3=D(()=>{Vh8={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0}});var Rf1,qf1,Mf1,Dn;var vg0=D(()=>{R3();W1();J1();Rf1=C($$(),1),qf1=C(Y1(),1),Mf1=C(i0(),1);Dn=class Dn extends Mf1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[qf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Rf1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","CompleteMultipartUpload",{}).n("S3Client","CompleteMultipartUploadCommand").sc(gq1).build(){}});var If1,Vf1,kf1,bg0;var xg0=D(()=>{R3();W1();J1();If1=C($$(),1),Vf1=C(Y1(),1),kf1=C(i0(),1);bg0=class bg0 extends kf1.Command.classBuilder().ep({...B0,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"},CopySource:{type:"contextParams",name:"CopySource"}}).m(function($,Z,Q,Y){return[Vf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),If1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","CopyObject",{}).n("S3Client","CopyObjectCommand").sc(hq1).build(){}});function Sh8($){return(Z)=>async(Q)=>{let{CreateBucketConfiguration:Y}=Q.input,X=await $.region();if(!Y?.LocationConstraint&&!Y?.Location){if(X!=="us-east-1")Q.input.CreateBucketConfiguration=Q.input.CreateBucketConfiguration??{},Q.input.CreateBucketConfiguration.LocationConstraint=X}return Z(Q)}}var Ch8,Sf1=($)=>({applyToStack:(Z)=>{Z.add(Sh8($),Ch8)}});var Cf1=D(()=>{Ch8={step:"initialize",tags:["LOCATION_CONSTRAINT","CREATE_BUCKET_CONFIGURATION"],name:"locationConstraintMiddleware",override:!0}});var _f1,vf1,bf1,fg0;var yg0=D(()=>{Cf1();W1();J1();_f1=C($$(),1),vf1=C(Y1(),1),bf1=C(i0(),1);fg0=class fg0 extends bf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},DisableAccessPoints:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[vf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),_f1.getThrow200ExceptionsPlugin(Q),Sf1(Q)]}).s("AmazonS3","CreateBucket",{}).n("S3Client","CreateBucketCommand").sc(uq1).build(){}});var xf1,ff1,gg0;var hg0=D(()=>{A6();W1();J1();xf1=C(Y1(),1),ff1=C(i0(),1);gg0=class gg0 extends ff1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[xf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","CreateBucketMetadataConfiguration",{}).n("S3Client","CreateBucketMetadataConfigurationCommand").sc(lq1).build(){}});var yf1,gf1,ug0;var lg0=D(()=>{A6();W1();J1();yf1=C(Y1(),1),gf1=C(i0(),1);ug0=class ug0 extends gf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[yf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","CreateBucketMetadataTableConfiguration",{}).n("S3Client","CreateBucketMetadataTableConfigurationCommand").sc(cq1).build(){}});var hf1,uf1,lf1,Ln;var cg0=D(()=>{R3();W1();J1();hf1=C($$(),1),uf1=C(Y1(),1),lf1=C(i0(),1);Ln=class Ln extends lf1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[uf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),hf1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","CreateMultipartUpload",{}).n("S3Client","CreateMultipartUploadCommand").sc(mq1).build(){}});var cf1,mf1,mg0;var dg0=D(()=>{W1();J1();cf1=C(Y1(),1),mf1=C(i0(),1);mg0=class mg0 extends mf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[cf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketAnalyticsConfiguration",{}).n("S3Client","DeleteBucketAnalyticsConfigurationCommand").sc(pq1).build(){}});var df1,if1,ig0;var pg0=D(()=>{W1();J1();df1=C(Y1(),1),if1=C(i0(),1);ig0=class ig0 extends if1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[df1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucket",{}).n("S3Client","DeleteBucketCommand").sc(iq1).build(){}});var pf1,nf1,ng0;var tg0=D(()=>{W1();J1();pf1=C(Y1(),1),nf1=C(i0(),1);ng0=class ng0 extends nf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[pf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketCors",{}).n("S3Client","DeleteBucketCorsCommand").sc(nq1).build(){}});var tf1,of1,og0;var rg0=D(()=>{W1();J1();tf1=C(Y1(),1),of1=C(i0(),1);og0=class og0 extends of1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[tf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketEncryption",{}).n("S3Client","DeleteBucketEncryptionCommand").sc(tq1).build(){}});var rf1,sf1,sg0;var ag0=D(()=>{W1();J1();rf1=C(Y1(),1),sf1=C(i0(),1);sg0=class sg0 extends sf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[rf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketIntelligentTieringConfiguration",{}).n("S3Client","DeleteBucketIntelligentTieringConfigurationCommand").sc(oq1).build(){}});var af1,ef1,eg0;var $h0=D(()=>{W1();J1();af1=C(Y1(),1),ef1=C(i0(),1);eg0=class eg0 extends ef1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[af1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketInventoryConfiguration",{}).n("S3Client","DeleteBucketInventoryConfigurationCommand").sc(rq1).build(){}});var $y1,Zy1,Zh0;var Qh0=D(()=>{W1();J1();$y1=C(Y1(),1),Zy1=C(i0(),1);Zh0=class Zh0 extends Zy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[$y1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketLifecycle",{}).n("S3Client","DeleteBucketLifecycleCommand").sc(sq1).build(){}});var Qy1,Yy1,Yh0;var Xh0=D(()=>{W1();J1();Qy1=C(Y1(),1),Yy1=C(i0(),1);Yh0=class Yh0 extends Yy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Qy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetadataConfiguration",{}).n("S3Client","DeleteBucketMetadataConfigurationCommand").sc(aq1).build(){}});var Xy1,Jy1,Jh0;var Gh0=D(()=>{W1();J1();Xy1=C(Y1(),1),Jy1=C(i0(),1);Jh0=class Jh0 extends Jy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Xy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetadataTableConfiguration",{}).n("S3Client","DeleteBucketMetadataTableConfigurationCommand").sc(eq1).build(){}});var Gy1,Wy1,Wh0;var Kh0=D(()=>{W1();J1();Gy1=C(Y1(),1),Wy1=C(i0(),1);Wh0=class Wh0 extends Wy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Gy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetricsConfiguration",{}).n("S3Client","DeleteBucketMetricsConfigurationCommand").sc($M1).build(){}});var Ky1,Hy1,Hh0;var Fh0=D(()=>{W1();J1();Ky1=C(Y1(),1),Hy1=C(i0(),1);Hh0=class Hh0 extends Hy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ky1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketOwnershipControls",{}).n("S3Client","DeleteBucketOwnershipControlsCommand").sc(ZM1).build(){}});var Fy1,Uy1,Uh0;var Nh0=D(()=>{W1();J1();Fy1=C(Y1(),1),Uy1=C(i0(),1);Uh0=class Uh0 extends Uy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Fy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketPolicy",{}).n("S3Client","DeleteBucketPolicyCommand").sc(QM1).build(){}});var Ny1,By1,Bh0;var Oh0=D(()=>{W1();J1();Ny1=C(Y1(),1),By1=C(i0(),1);Bh0=class Bh0 extends By1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ny1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketReplication",{}).n("S3Client","DeleteBucketReplicationCommand").sc(YM1).build(){}});var Oy1,Dy1,Dh0;var Lh0=D(()=>{W1();J1();Oy1=C(Y1(),1),Dy1=C(i0(),1);Dh0=class Dh0 extends Dy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Oy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketTagging",{}).n("S3Client","DeleteBucketTaggingCommand").sc(XM1).build(){}});var Ly1,wy1,wh0;var jh0=D(()=>{W1();J1();Ly1=C(Y1(),1),wy1=C(i0(),1);wh0=class wh0 extends wy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ly1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketWebsite",{}).n("S3Client","DeleteBucketWebsiteCommand").sc(JM1).build(){}});var jy1,Ey1,zy1,Iz;var Eh0=D(()=>{W1();J1();jy1=C($$(),1),Ey1=C(Y1(),1),zy1=C(i0(),1);Iz=class Iz extends zy1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[Ey1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),jy1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").sc(GM1).build(){}});var Py1,Ay1,Ty1,zh0;var Ph0=D(()=>{A6();W1();J1();Py1=C($$(),1),Ay1=C(Y1(),1),Ty1=C(i0(),1);zh0=class zh0 extends Ty1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ay1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),Py1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","DeleteObjects",{}).n("S3Client","DeleteObjectsCommand").sc(WM1).build(){}});var Ry1,qy1,My1,Ah0;var Th0=D(()=>{W1();J1();Ry1=C($$(),1),qy1=C(Y1(),1),My1=C(i0(),1);Ah0=class Ah0 extends My1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[qy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Ry1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","DeleteObjectTagging",{}).n("S3Client","DeleteObjectTaggingCommand").sc(KM1).build(){}});var Iy1,Vy1,Rh0;var qh0=D(()=>{W1();J1();Iy1=C(Y1(),1),Vy1=C(i0(),1);Rh0=class Rh0 extends Vy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Iy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeletePublicAccessBlock",{}).n("S3Client","DeletePublicAccessBlockCommand").sc(HM1).build(){}});var ky1,Sy1,Cy1,Mh0;var Ih0=D(()=>{W1();J1();ky1=C($$(),1),Sy1=C(Y1(),1),Cy1=C(i0(),1);Mh0=class Mh0 extends Cy1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Sy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ky1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketAbac",{}).n("S3Client","GetBucketAbacCommand").sc(FM1).build(){}});var _y1,vy1,by1,Vh0;var kh0=D(()=>{W1();J1();_y1=C($$(),1),vy1=C(Y1(),1),by1=C(i0(),1);Vh0=class Vh0 extends by1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[vy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),_y1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketAccelerateConfiguration",{}).n("S3Client","GetBucketAccelerateConfigurationCommand").sc(UM1).build(){}});var xy1,fy1,yy1,Sh0;var Ch0=D(()=>{W1();J1();xy1=C($$(),1),fy1=C(Y1(),1),yy1=C(i0(),1);Sh0=class Sh0 extends yy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[fy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),xy1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketAcl",{}).n("S3Client","GetBucketAclCommand").sc(NM1).build(){}});var gy1,hy1,uy1,_h0;var vh0=D(()=>{W1();J1();gy1=C($$(),1),hy1=C(Y1(),1),uy1=C(i0(),1);_h0=class _h0 extends uy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[hy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),gy1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketAnalyticsConfiguration",{}).n("S3Client","GetBucketAnalyticsConfigurationCommand").sc(BM1).build(){}});var ly1,cy1,my1,bh0;var xh0=D(()=>{W1();J1();ly1=C($$(),1),cy1=C(Y1(),1),my1=C(i0(),1);bh0=class bh0 extends my1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[cy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ly1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketCors",{}).n("S3Client","GetBucketCorsCommand").sc(OM1).build(){}});var dy1,iy1,py1,fh0;var yh0=D(()=>{W1();J1();dy1=C($$(),1),iy1=C(Y1(),1),py1=C(i0(),1);fh0=class fh0 extends py1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[iy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),dy1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketEncryption",{}).n("S3Client","GetBucketEncryptionCommand").sc(DM1).build(){}});var ny1,ty1,oy1,gh0;var hh0=D(()=>{W1();J1();ny1=C($$(),1),ty1=C(Y1(),1),oy1=C(i0(),1);gh0=class gh0 extends oy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[ty1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ny1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketIntelligentTieringConfiguration",{}).n("S3Client","GetBucketIntelligentTieringConfigurationCommand").sc(LM1).build(){}});var ry1,sy1,ay1,uh0;var lh0=D(()=>{W1();J1();ry1=C($$(),1),sy1=C(Y1(),1),ay1=C(i0(),1);uh0=class uh0 extends ay1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[sy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ry1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketInventoryConfiguration",{}).n("S3Client","GetBucketInventoryConfigurationCommand").sc(wM1).build(){}});var ey1,$g1,Zg1,ch0;var mh0=D(()=>{W1();J1();ey1=C($$(),1),$g1=C(Y1(),1),Zg1=C(i0(),1);ch0=class ch0 extends Zg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[$g1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ey1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketLifecycleConfiguration",{}).n("S3Client","GetBucketLifecycleConfigurationCommand").sc(jM1).build(){}});var Qg1,Yg1,Xg1,dh0;var ih0=D(()=>{W1();J1();Qg1=C($$(),1),Yg1=C(Y1(),1),Xg1=C(i0(),1);dh0=class dh0 extends Xg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Yg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Qg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketLocation",{}).n("S3Client","GetBucketLocationCommand").sc(EM1).build(){}});var Jg1,Gg1,Wg1,ph0;var nh0=D(()=>{W1();J1();Jg1=C($$(),1),Gg1=C(Y1(),1),Wg1=C(i0(),1);ph0=class ph0 extends Wg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Gg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Jg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketLogging",{}).n("S3Client","GetBucketLoggingCommand").sc(zM1).build(){}});var Kg1,Hg1,Fg1,th0;var oh0=D(()=>{W1();J1();Kg1=C($$(),1),Hg1=C(Y1(),1),Fg1=C(i0(),1);th0=class th0 extends Fg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Hg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Kg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketMetadataConfiguration",{}).n("S3Client","GetBucketMetadataConfigurationCommand").sc(PM1).build(){}});var Ug1,Ng1,Bg1,rh0;var sh0=D(()=>{W1();J1();Ug1=C($$(),1),Ng1=C(Y1(),1),Bg1=C(i0(),1);rh0=class rh0 extends Bg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ng1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Ug1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketMetadataTableConfiguration",{}).n("S3Client","GetBucketMetadataTableConfigurationCommand").sc(AM1).build(){}});var Og1,Dg1,Lg1,ah0;var eh0=D(()=>{W1();J1();Og1=C($$(),1),Dg1=C(Y1(),1),Lg1=C(i0(),1);ah0=class ah0 extends Lg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Dg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Og1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketMetricsConfiguration",{}).n("S3Client","GetBucketMetricsConfigurationCommand").sc(TM1).build(){}});var wg1,jg1,Eg1,$u0;var Zu0=D(()=>{W1();J1();wg1=C($$(),1),jg1=C(Y1(),1),Eg1=C(i0(),1);$u0=class $u0 extends Eg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[jg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),wg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketNotificationConfiguration",{}).n("S3Client","GetBucketNotificationConfigurationCommand").sc(RM1).build(){}});var zg1,Pg1,Ag1,Qu0;var Yu0=D(()=>{W1();J1();zg1=C($$(),1),Pg1=C(Y1(),1),Ag1=C(i0(),1);Qu0=class Qu0 extends Ag1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Pg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),zg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketOwnershipControls",{}).n("S3Client","GetBucketOwnershipControlsCommand").sc(qM1).build(){}});var Tg1,Rg1,Xu0;var Ju0=D(()=>{W1();J1();Tg1=C(Y1(),1),Rg1=C(i0(),1);Xu0=class Xu0 extends Rg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Tg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","GetBucketPolicy",{}).n("S3Client","GetBucketPolicyCommand").sc(MM1).build(){}});var qg1,Mg1,Ig1,Gu0;var Wu0=D(()=>{W1();J1();qg1=C($$(),1),Mg1=C(Y1(),1),Ig1=C(i0(),1);Gu0=class Gu0 extends Ig1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Mg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),qg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketPolicyStatus",{}).n("S3Client","GetBucketPolicyStatusCommand").sc(IM1).build(){}});var Vg1,kg1,Sg1,Ku0;var Hu0=D(()=>{W1();J1();Vg1=C($$(),1),kg1=C(Y1(),1),Sg1=C(i0(),1);Ku0=class Ku0 extends Sg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[kg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Vg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketReplication",{}).n("S3Client","GetBucketReplicationCommand").sc(VM1).build(){}});var Cg1,_g1,vg1,Fu0;var Uu0=D(()=>{W1();J1();Cg1=C($$(),1),_g1=C(Y1(),1),vg1=C(i0(),1);Fu0=class Fu0 extends vg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[_g1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Cg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketRequestPayment",{}).n("S3Client","GetBucketRequestPaymentCommand").sc(kM1).build(){}});var bg1,xg1,fg1,Nu0;var Bu0=D(()=>{W1();J1();bg1=C($$(),1),xg1=C(Y1(),1),fg1=C(i0(),1);Nu0=class Nu0 extends fg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[xg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),bg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketTagging",{}).n("S3Client","GetBucketTaggingCommand").sc(SM1).build(){}});var yg1,gg1,hg1,Ou0;var Du0=D(()=>{W1();J1();yg1=C($$(),1),gg1=C(Y1(),1),hg1=C(i0(),1);Ou0=class Ou0 extends hg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[gg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),yg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketVersioning",{}).n("S3Client","GetBucketVersioningCommand").sc(CM1).build(){}});var ug1,lg1,cg1,Lu0;var wu0=D(()=>{W1();J1();ug1=C($$(),1),lg1=C(Y1(),1),cg1=C(i0(),1);Lu0=class Lu0 extends cg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[lg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ug1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketWebsite",{}).n("S3Client","GetBucketWebsiteCommand").sc(_M1).build(){}});var mg1,dg1,ig1,ju0;var Eu0=D(()=>{W1();J1();mg1=C($$(),1),dg1=C(Y1(),1),ig1=C(i0(),1);ju0=class ju0 extends ig1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[dg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),mg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectAcl",{}).n("S3Client","GetObjectAclCommand").sc(bM1).build(){}});var pg1,ng1,tg1,zu0;var Pu0=D(()=>{R3();W1();J1();pg1=C($$(),1),ng1=C(Y1(),1),tg1=C(i0(),1);zu0=class zu0 extends tg1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[ng1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),pg1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","GetObjectAttributes",{}).n("S3Client","GetObjectAttributesCommand").sc(xM1).build(){}});var og1,rg1,sg1,MD;var Au0=D(()=>{A6();R3();W1();J1();og1=C($$(),1),rg1=C(Y1(),1),sg1=C(i0(),1);MD=class MD extends sg1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[rg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC64NVME","CRC32","CRC32C","SHA256","SHA1","SHA512","MD5","XXHASH64","XXHASH3","XXHASH128"]}),r9(Q),og1.getS3ExpiresMiddlewarePlugin(Q)]}).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").sc(vM1).build(){}});var ag1,eg1,$h1,Tu0;var Ru0=D(()=>{W1();J1();ag1=C($$(),1),eg1=C(Y1(),1),$h1=C(i0(),1);Tu0=class Tu0 extends $h1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[eg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ag1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectLegalHold",{}).n("S3Client","GetObjectLegalHoldCommand").sc(fM1).build(){}});var Zh1,Qh1,Yh1,qu0;var Mu0=D(()=>{W1();J1();Zh1=C($$(),1),Qh1=C(Y1(),1),Yh1=C(i0(),1);qu0=class qu0 extends Yh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Qh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Zh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectLockConfiguration",{}).n("S3Client","GetObjectLockConfigurationCommand").sc(yM1).build(){}});var Xh1,Jh1,Gh1,Iu0;var Vu0=D(()=>{W1();J1();Xh1=C($$(),1),Jh1=C(Y1(),1),Gh1=C(i0(),1);Iu0=class Iu0 extends Gh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Jh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Xh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectRetention",{}).n("S3Client","GetObjectRetentionCommand").sc(gM1).build(){}});var Wh1,Kh1,Hh1,ku0;var Su0=D(()=>{W1();J1();Wh1=C($$(),1),Kh1=C(Y1(),1),Hh1=C(i0(),1);ku0=class ku0 extends Hh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Kh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Wh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectTagging",{}).n("S3Client","GetObjectTaggingCommand").sc(hM1).build(){}});var Fh1,Uh1,Cu0;var _u0=D(()=>{W1();J1();Fh1=C(Y1(),1),Uh1=C(i0(),1);Cu0=class Cu0 extends Uh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Fh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","GetObjectTorrent",{}).n("S3Client","GetObjectTorrentCommand").sc(uM1).build(){}});var Nh1,Bh1,Oh1,vu0;var bu0=D(()=>{W1();J1();Nh1=C($$(),1),Bh1=C(Y1(),1),Oh1=C(i0(),1);vu0=class vu0 extends Oh1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Bh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Nh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetPublicAccessBlock",{}).n("S3Client","GetPublicAccessBlockCommand").sc(lM1).build(){}});var Dh1,Lh1,wh1,Vz;var wn=D(()=>{W1();J1();Dh1=C($$(),1),Lh1=C(Y1(),1),wh1=C(i0(),1);Vz=class Vz extends wh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Lh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Dh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","HeadBucket",{}).n("S3Client","HeadBucketCommand").sc(cM1).build(){}});var fZ0,jh1,Eh1,hH;var jn=D(()=>{R3();W1();J1();fZ0=C($$(),1),jh1=C(Y1(),1),Eh1=C(i0(),1);hH=class hH extends Eh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[jh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),fZ0.getThrow200ExceptionsPlugin(Q),r9(Q),fZ0.getS3ExpiresMiddlewarePlugin(Q)]}).s("AmazonS3","HeadObject",{}).n("S3Client","HeadObjectCommand").sc(mM1).build(){}});var zh1,Ph1,Ah1,xu0;var fu0=D(()=>{W1();J1();zh1=C($$(),1),Ph1=C(Y1(),1),Ah1=C(i0(),1);xu0=class xu0 extends Ah1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ph1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),zh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBucketAnalyticsConfigurations",{}).n("S3Client","ListBucketAnalyticsConfigurationsCommand").sc(dM1).build(){}});var Th1,Rh1,qh1,yu0;var gu0=D(()=>{W1();J1();Th1=C($$(),1),Rh1=C(Y1(),1),qh1=C(i0(),1);yu0=class yu0 extends qh1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Rh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Th1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBucketIntelligentTieringConfigurations",{}).n("S3Client","ListBucketIntelligentTieringConfigurationsCommand").sc(iM1).build(){}});var Mh1,Ih1,Vh1,hu0;var uu0=D(()=>{W1();J1();Mh1=C($$(),1),Ih1=C(Y1(),1),Vh1=C(i0(),1);hu0=class hu0 extends Vh1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ih1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Mh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBucketInventoryConfigurations",{}).n("S3Client","ListBucketInventoryConfigurationsCommand").sc(pM1).build(){}});var kh1,Sh1,Ch1,lu0;var cu0=D(()=>{W1();J1();kh1=C($$(),1),Sh1=C(Y1(),1),Ch1=C(i0(),1);lu0=class lu0 extends Ch1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Sh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),kh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBucketMetricsConfigurations",{}).n("S3Client","ListBucketMetricsConfigurationsCommand").sc(nM1).build(){}});var _h1,vh1,bh1,En;var yZ0=D(()=>{W1();J1();_h1=C($$(),1),vh1=C(Y1(),1),bh1=C(i0(),1);En=class En extends bh1.Command.classBuilder().ep(B0).m(function($,Z,Q,Y){return[vh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),_h1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBuckets",{}).n("S3Client","ListBucketsCommand").sc(tM1).build(){}});var xh1,fh1,yh1,zn;var gZ0=D(()=>{W1();J1();xh1=C($$(),1),fh1=C(Y1(),1),yh1=C(i0(),1);zn=class zn extends yh1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0}}).m(function($,Z,Q,Y){return[fh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),xh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListDirectoryBuckets",{}).n("S3Client","ListDirectoryBucketsCommand").sc(oM1).build(){}});var gh1,hh1,uh1,mu0;var du0=D(()=>{W1();J1();gh1=C($$(),1),hh1=C(Y1(),1),uh1=C(i0(),1);mu0=class mu0 extends uh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function($,Z,Q,Y){return[hh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),gh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListMultipartUploads",{}).n("S3Client","ListMultipartUploadsCommand").sc(rM1).build(){}});var lh1,ch1,mh1,iu0;var pu0=D(()=>{W1();J1();lh1=C($$(),1),ch1=C(Y1(),1),mh1=C(i0(),1);iu0=class iu0 extends mh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function($,Z,Q,Y){return[ch1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),lh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListObjects",{}).n("S3Client","ListObjectsCommand").sc(sM1).build(){}});var dh1,ih1,ph1,uH;var hZ0=D(()=>{W1();J1();dh1=C($$(),1),ih1=C(Y1(),1),ph1=C(i0(),1);uH=class uH extends ph1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function($,Z,Q,Y){return[ih1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),dh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").sc(aM1).build(){}});var nh1,th1,oh1,nu0;var tu0=D(()=>{W1();J1();nh1=C($$(),1),th1=C(Y1(),1),oh1=C(i0(),1);nu0=class nu0 extends oh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function($,Z,Q,Y){return[th1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),nh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListObjectVersions",{}).n("S3Client","ListObjectVersionsCommand").sc(eM1).build(){}});var rh1,sh1,ah1,Pn;var uZ0=D(()=>{R3();W1();J1();rh1=C($$(),1),sh1=C(Y1(),1),ah1=C(i0(),1);Pn=class Pn extends ah1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[sh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),rh1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","ListParts",{}).n("S3Client","ListPartsCommand").sc($I1).build(){}});var eh1,$u1,ou0;var ru0=D(()=>{A6();W1();J1();eh1=C(Y1(),1),$u1=C(i0(),1);ou0=class ou0 extends $u1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[eh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]}).s("AmazonS3","PutBucketAbac",{}).n("S3Client","PutBucketAbacCommand").sc(ZI1).build(){}});var Zu1,Qu1,su0;var au0=D(()=>{A6();W1();J1();Zu1=C(Y1(),1),Qu1=C(i0(),1);su0=class su0 extends Qu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Zu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]}).s("AmazonS3","PutBucketAccelerateConfiguration",{}).n("S3Client","PutBucketAccelerateConfigurationCommand").sc(QI1).build(){}});var Yu1,Xu1,eu0;var $l0=D(()=>{A6();W1();J1();Yu1=C(Y1(),1),Xu1=C(i0(),1);eu0=class eu0 extends Xu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Yu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketAcl",{}).n("S3Client","PutBucketAclCommand").sc(YI1).build(){}});var Ju1,Gu1,Zl0;var Ql0=D(()=>{W1();J1();Ju1=C(Y1(),1),Gu1=C(i0(),1);Zl0=class Zl0 extends Gu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ju1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketAnalyticsConfiguration",{}).n("S3Client","PutBucketAnalyticsConfigurationCommand").sc(XI1).build(){}});var Wu1,Ku1,Yl0;var Xl0=D(()=>{A6();W1();J1();Wu1=C(Y1(),1),Ku1=C(i0(),1);Yl0=class Yl0 extends Ku1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Wu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketCors",{}).n("S3Client","PutBucketCorsCommand").sc(JI1).build(){}});var Hu1,Fu1,Jl0;var Gl0=D(()=>{A6();W1();J1();Hu1=C(Y1(),1),Fu1=C(i0(),1);Jl0=class Jl0 extends Fu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Hu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketEncryption",{}).n("S3Client","PutBucketEncryptionCommand").sc(GI1).build(){}});var Uu1,Nu1,Wl0;var Kl0=D(()=>{W1();J1();Uu1=C(Y1(),1),Nu1=C(i0(),1);Wl0=class Wl0 extends Nu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Uu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketIntelligentTieringConfiguration",{}).n("S3Client","PutBucketIntelligentTieringConfigurationCommand").sc(WI1).build(){}});var Bu1,Ou1,Hl0;var Fl0=D(()=>{W1();J1();Bu1=C(Y1(),1),Ou1=C(i0(),1);Hl0=class Hl0 extends Ou1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Bu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketInventoryConfiguration",{}).n("S3Client","PutBucketInventoryConfigurationCommand").sc(KI1).build(){}});var Du1,Lu1,wu1,Ul0;var Nl0=D(()=>{A6();W1();J1();Du1=C($$(),1),Lu1=C(Y1(),1),wu1=C(i0(),1);Ul0=class Ul0 extends wu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Lu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),Du1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutBucketLifecycleConfiguration",{}).n("S3Client","PutBucketLifecycleConfigurationCommand").sc(HI1).build(){}});var ju1,Eu1,Bl0;var Ol0=D(()=>{A6();W1();J1();ju1=C(Y1(),1),Eu1=C(i0(),1);Bl0=class Bl0 extends Eu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[ju1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketLogging",{}).n("S3Client","PutBucketLoggingCommand").sc(FI1).build(){}});var zu1,Pu1,Dl0;var Ll0=D(()=>{W1();J1();zu1=C(Y1(),1),Pu1=C(i0(),1);Dl0=class Dl0 extends Pu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[zu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketMetricsConfiguration",{}).n("S3Client","PutBucketMetricsConfigurationCommand").sc(UI1).build(){}});var Au1,Tu1,wl0;var jl0=D(()=>{W1();J1();Au1=C(Y1(),1),Tu1=C(i0(),1);wl0=class wl0 extends Tu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Au1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketNotificationConfiguration",{}).n("S3Client","PutBucketNotificationConfigurationCommand").sc(NI1).build(){}});var Ru1,qu1,El0;var zl0=D(()=>{A6();W1();J1();Ru1=C(Y1(),1),qu1=C(i0(),1);El0=class El0 extends qu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ru1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketOwnershipControls",{}).n("S3Client","PutBucketOwnershipControlsCommand").sc(BI1).build(){}});var Mu1,Iu1,Pl0;var Al0=D(()=>{A6();W1();J1();Mu1=C(Y1(),1),Iu1=C(i0(),1);Pl0=class Pl0 extends Iu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Mu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketPolicy",{}).n("S3Client","PutBucketPolicyCommand").sc(OI1).build(){}});var Vu1,ku1,Tl0;var Rl0=D(()=>{A6();W1();J1();Vu1=C(Y1(),1),ku1=C(i0(),1);Tl0=class Tl0 extends ku1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Vu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketReplication",{}).n("S3Client","PutBucketReplicationCommand").sc(DI1).build(){}});var Su1,Cu1,ql0;var Ml0=D(()=>{A6();W1();J1();Su1=C(Y1(),1),Cu1=C(i0(),1);ql0=class ql0 extends Cu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Su1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketRequestPayment",{}).n("S3Client","PutBucketRequestPaymentCommand").sc(LI1).build(){}});var _u1,vu1,Il0;var Vl0=D(()=>{A6();W1();J1();_u1=C(Y1(),1),vu1=C(i0(),1);Il0=class Il0 extends vu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[_u1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketTagging",{}).n("S3Client","PutBucketTaggingCommand").sc(wI1).build(){}});var bu1,xu1,kl0;var Sl0=D(()=>{A6();W1();J1();bu1=C(Y1(),1),xu1=C(i0(),1);kl0=class kl0 extends xu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[bu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketVersioning",{}).n("S3Client","PutBucketVersioningCommand").sc(jI1).build(){}});var fu1,yu1,Cl0;var _l0=D(()=>{A6();W1();J1();fu1=C(Y1(),1),yu1=C(i0(),1);Cl0=class Cl0 extends yu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[fu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketWebsite",{}).n("S3Client","PutBucketWebsiteCommand").sc(EI1).build(){}});var gu1,hu1,uu1,vl0;var bl0=D(()=>{A6();W1();J1();gu1=C($$(),1),hu1=C(Y1(),1),uu1=C(i0(),1);vl0=class vl0 extends uu1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[hu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),gu1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectAcl",{}).n("S3Client","PutObjectAclCommand").sc(PI1).build(){}});var lZ0,lu1,cu1,CN;var xl0=D(()=>{A6();R3();W1();J1();lZ0=C($$(),1),lu1=C(Y1(),1),cu1=C(i0(),1);CN=class CN extends cu1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[lu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),lZ0.getCheckContentLengthHeaderPlugin(Q),lZ0.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").sc(zI1).build(){}});var mu1,du1,iu1,fl0;var yl0=D(()=>{A6();W1();J1();mu1=C($$(),1),du1=C(Y1(),1),iu1=C(i0(),1);fl0=class fl0 extends iu1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[du1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),mu1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectLegalHold",{}).n("S3Client","PutObjectLegalHoldCommand").sc(AI1).build(){}});var pu1,nu1,tu1,gl0;var hl0=D(()=>{A6();W1();J1();pu1=C($$(),1),nu1=C(Y1(),1),tu1=C(i0(),1);gl0=class gl0 extends tu1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[nu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),pu1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectLockConfiguration",{}).n("S3Client","PutObjectLockConfigurationCommand").sc(TI1).build(){}});var ou1,ru1,su1,ul0;var ll0=D(()=>{A6();W1();J1();ou1=C($$(),1),ru1=C(Y1(),1),su1=C(i0(),1);ul0=class ul0 extends su1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[ru1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),ou1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectRetention",{}).n("S3Client","PutObjectRetentionCommand").sc(RI1).build(){}});var au1,eu1,$l1,An;var cl0=D(()=>{A6();W1();J1();au1=C($$(),1),eu1=C(Y1(),1),$l1=C(i0(),1);An=class An extends $l1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[eu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),au1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectTagging",{}).n("S3Client","PutObjectTaggingCommand").sc(qI1).build(){}});var Zl1,Ql1,ml0;var dl0=D(()=>{A6();W1();J1();Zl1=C(Y1(),1),Ql1=C(i0(),1);ml0=class ml0 extends Ql1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Zl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutPublicAccessBlock",{}).n("S3Client","PutPublicAccessBlockCommand").sc(MI1).build(){}});var Yl1,Xl1,Jl1,il0;var pl0=D(()=>{W1();J1();Yl1=C($$(),1),Xl1=C(Y1(),1),Jl1=C(i0(),1);il0=class il0 extends Jl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[Xl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Yl1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","RenameObject",{}).n("S3Client","RenameObjectCommand").sc(II1).build(){}});var Gl1,Wl1,Kl1,nl0;var tl0=D(()=>{A6();W1();J1();Gl1=C($$(),1),Wl1=C(Y1(),1),Kl1=C(i0(),1);nl0=class nl0 extends Kl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Wl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),Gl1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","RestoreObject",{}).n("S3Client","RestoreObjectCommand").sc(VI1).build(){}});var Hl1,Fl1,ol0;var rl0=D(()=>{R3();W1();J1();Hl1=C(Y1(),1),Fl1=C(i0(),1);ol0=class ol0 extends Fl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Hl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),r9(Q)]}).s("AmazonS3","SelectObjectContent",{eventStream:{output:!0}}).n("S3Client","SelectObjectContentCommand").sc(kI1).build(){}});var Ul1,Nl1,sl0;var al0=D(()=>{A6();W1();J1();Ul1=C(Y1(),1),Nl1=C(i0(),1);sl0=class sl0 extends Nl1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ul1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","UpdateBucketMetadataInventoryTableConfiguration",{}).n("S3Client","UpdateBucketMetadataInventoryTableConfigurationCommand").sc(SI1).build(){}});var Bl1,Ol1,el0;var $c0=D(()=>{A6();W1();J1();Bl1=C(Y1(),1),Ol1=C(i0(),1);el0=class el0 extends Ol1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Bl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","UpdateBucketMetadataJournalTableConfiguration",{}).n("S3Client","UpdateBucketMetadataJournalTableConfigurationCommand").sc(CI1).build(){}});var Dl1,Ll1,wl1,Zc0;var Qc0=D(()=>{A6();W1();J1();Dl1=C($$(),1),Ll1=C(Y1(),1),wl1=C(i0(),1);Zc0=class Zc0 extends wl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ll1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),Dl1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","UpdateObjectEncryption",{}).n("S3Client","UpdateObjectEncryptionCommand").sc(_I1).build(){}});var jl1,El1,zl1,Tn;var Yc0=D(()=>{A6();R3();W1();J1();jl1=C($$(),1),El1=C(Y1(),1),zl1=C(i0(),1);Tn=class Tn extends zl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[El1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),jl1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","UploadPart",{}).n("S3Client","UploadPartCommand").sc(vI1).build(){}});var Pl1,Al1,Tl1,Xc0;var Jc0=D(()=>{R3();W1();J1();Pl1=C($$(),1),Al1=C(Y1(),1),Tl1=C(i0(),1);Xc0=class Xc0 extends Tl1.Command.classBuilder().ep({...B0,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Al1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Pl1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","UploadPartCopy",{}).n("S3Client","UploadPartCopyCommand").sc(bI1).build(){}});var Rl1,ql1,Gc0;var Wc0=D(()=>{W1();J1();Rl1=C(Y1(),1),ql1=C(i0(),1);Gc0=class Gc0 extends ql1.Command.classBuilder().ep({...B0,UseObjectLambdaEndpoint:{type:"staticContextParams",value:!0}}).m(function($,Z,Q,Y){return[Rl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","WriteGetObjectResponse",{}).n("S3Client","WriteGetObjectResponseCommand").sc(xI1).build(){}});var Ml1,Il1;var Kc0=D(()=>{yZ0();Mz();Ml1=C(X7(),1),Il1=Ml1.createPaginator(eY,En,"ContinuationToken","ContinuationToken","MaxBuckets")});var Vl1,kl1;var Hc0=D(()=>{gZ0();Mz();Vl1=C(X7(),1),kl1=Vl1.createPaginator(eY,zn,"ContinuationToken","ContinuationToken","MaxDirectoryBuckets")});var Sl1,Cl1;var Fc0=D(()=>{hZ0();Mz();Sl1=C(X7(),1),Cl1=Sl1.createPaginator(eY,uH,"ContinuationToken","NextContinuationToken","MaxKeys")});var _l1,vl1;var Uc0=D(()=>{uZ0();Mz();_l1=C(X7(),1),vl1=_l1.createPaginator(eY,Pn,"PartNumberMarker","NextPartNumberMarker","MaxParts")});var cg=()=>{let $=new WeakSet;return(Z,Q)=>{if(typeof Q==="object"&&Q!==null){if($.has(Q))return"[Circular]";$.add(Q)}return Q}};var bl1=($)=>{return new Promise((Z)=>setTimeout(Z,$*1000))};var xl1,J9,ID=($)=>{if($.state===J9.ABORTED){let Z=Error(`${JSON.stringify({...$,reason:"Request was aborted"},cg())}`);throw Z.name="AbortError",Z}else if($.state===J9.TIMEOUT){let Z=Error(`${JSON.stringify({...$,reason:"Waiter has timed out"},cg())}`);throw Z.name="TimeoutError",Z}else if($.state!==J9.SUCCESS)throw Error(`${JSON.stringify($,cg())}`);return $};var cZ0=D(()=>{xl1={minDelay:2,maxDelay:120};(function($){$.ABORTED="ABORTED",$.FAILURE="FAILURE",$.SUCCESS="SUCCESS",$.RETRY="RETRY",$.TIMEOUT="TIMEOUT"})(J9||(J9={}))});var fl1=async({minDelay:$,maxDelay:Z,maxWaitTime:Q,abortController:Y,client:X,abortSignal:J},G,W)=>{let K={},[H,F]=[$*1000,Z*1000],U=0,N=Date.now()+Q*1000,B=Date.now()+60000,O=!1;while(!0){if(U>0){let j=bh8(H,F,U,N);if(Y?.signal?.aborted||J?.aborted)return K["AbortController signal aborted."]|=0,K["AbortController signal aborted."]+=1,{state:J9.ABORTED,observedResponses:K};if(Date.now()+j>N)return{state:J9.TIMEOUT,observedResponses:K};await bl1(j/1000)}let{state:L,reason:w}=await W(X,G);if(w){let j=vh8(w);K[j]|=0,K[j]+=1}if(L!==J9.RETRY)return{state:L,reason:w,final:w,observedResponses:K};if(U+=1,!O&&Date.now()>=B)_h8(K,X),O=!0}},_h8=($={},Z)=>{let Q=Object.keys($),Y=0,X=0;for(let W of Q){let K=$[W]|0;if(Y=Math.max(K,Y),W.startsWith("403:"))X+=K}let J=Z?.config?.logger,G=typeof J?.warn==="function"&&!J.constructor?.name?.includes?.("NoOpLogger")?J:console;if(X>=3||Q[Q.length-1].startsWith("403:"))G.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},vh8=($)=>{let Z=$?.$response?.statusCode??$?.$metadata?.httpStatusCode;if($?.$responseBodyText)return`${Z?Z+": ":""}Deserialization error for body: ${$.$responseBodyText}`;if(Z){if($?.$response||$?.message)return`${Z??"Unknown"}: ${$?.message}`;return`${Z}: OK`}return String($?.message??JSON.stringify($,cg())??"Unknown")},bh8=($,Z,Q,Y)=>{let X=Math.log(Z/$)/Math.log(2)+1;if(Q>X)return Z;let J=$*2**(Q-1),G=Math.min(J,Z),W=xh8($,G);if(Date.now()+W>Y){let K=Y-Date.now();return Math.max(0,K-500)}return W},xh8=($,Z)=>$+Math.random()*(Z-$);var yl1=D(()=>{cZ0()});var gl1=($)=>{if($.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if($.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if($.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if($.maxWaitTime<=$.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${$.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${$.minDelay}] for this waiter`);else if($.maxDelay<$.minDelay)throw Error(`WaiterConfiguration.maxDelay [${$.maxDelay}] must be greater than WaiterConfiguration.minDelay [${$.minDelay}] for this waiter`)};var hl1=()=>{};var ul1=($)=>{let Z,Q=new Promise((Y)=>{if(Z=()=>Y({state:J9.ABORTED}),typeof $.addEventListener==="function")$.addEventListener("abort",Z);else $.onabort=Z});return{clearListener(){if(typeof $.removeEventListener==="function")$.removeEventListener("abort",Z)},aborted:Q}},VD=async($,Z,Q)=>{let Y={...xl1,...$};gl1(Y);let X=[fl1(Y,Z,Q)],J=[];if($.abortSignal){let{aborted:G,clearListener:W}=ul1($.abortSignal);J.push(W),X.push(G)}if($.abortController?.signal){let{aborted:G,clearListener:W}=ul1($.abortController.signal);J.push(W),X.push(G)}return Promise.race(X).then((G)=>{for(let W of J)W();return G})};var ll1=D(()=>{yl1();hl1();cZ0()});var Rn=D(()=>{ll1();cZ0()});var fh8=async($,Z)=>{let Q;try{return Q=await $.send(new Vz(Z)),{state:J9.SUCCESS,reason:Q}}catch(Y){if(Q=Y,Y.name==="NotFound")return{state:J9.RETRY,reason:Q}}return{state:J9.RETRY,reason:Q}},cl1=async($,Z)=>{let Y=await VD({...{minDelay:5,maxDelay:120},...$},Z,fh8);return ID(Y)};var Nc0=D(()=>{Rn();wn()});var yh8=async($,Z)=>{let Q;try{Q=await $.send(new Vz(Z))}catch(Y){if(Q=Y,Y.name==="NotFound")return{state:J9.SUCCESS,reason:Q}}return{state:J9.RETRY,reason:Q}},ml1=async($,Z)=>{let Y=await VD({...{minDelay:5,maxDelay:120},...$},Z,yh8);return ID(Y)};var Bc0=D(()=>{Rn();wn()});var gh8=async($,Z)=>{let Q;try{return Q=await $.send(new hH(Z)),{state:J9.SUCCESS,reason:Q}}catch(Y){if(Q=Y,Y.name==="NotFound")return{state:J9.RETRY,reason:Q}}return{state:J9.RETRY,reason:Q}},dl1=async($,Z)=>{let Y=await VD({...{minDelay:5,maxDelay:120},...$},Z,gh8);return ID(Y)};var Oc0=D(()=>{Rn();jn()});var hh8=async($,Z)=>{let Q;try{Q=await $.send(new hH(Z))}catch(Y){if(Q=Y,Y.name==="NotFound")return{state:J9.SUCCESS,reason:Q}}return{state:J9.RETRY,reason:Q}},il1=async($,Z)=>{let Y=await VD({...{minDelay:5,maxDelay:120},...$},Z,hh8);return ID(Y)};var Dc0=D(()=>{Rn();jn()});var pl1,uh8,lh8,ch8,nl1;var tl1=D(()=>{_g0();vg0();xg0();yg0();hg0();lg0();cg0();E90();dg0();pg0();tg0();rg0();ag0();$h0();Qh0();Xh0();Gh0();Kh0();Fh0();Nh0();Oh0();Lh0();jh0();Eh0();Ph0();Th0();qh0();Ih0();kh0();Ch0();vh0();xh0();yh0();hh0();lh0();mh0();ih0();nh0();oh0();sh0();eh0();Zu0();Yu0();Ju0();Wu0();Hu0();Uu0();Bu0();Du0();wu0();Eu0();Pu0();Au0();Ru0();Mu0();Vu0();Su0();_u0();bu0();wn();jn();fu0();gu0();uu0();cu0();yZ0();gZ0();du0();pu0();hZ0();tu0();uZ0();ru0();au0();$l0();Ql0();Xl0();Gl0();Kl0();Fl0();Nl0();Ol0();Ll0();jl0();zl0();Al0();Rl0();Ml0();Vl0();Sl0();_l0();bl0();xl0();yl0();hl0();ll0();cl0();dl0();pl0();tl0();rl0();al0();$c0();Qc0();Yc0();Jc0();Wc0();Kc0();Hc0();Fc0();Uc0();Mz();Nc0();Bc0();Oc0();Dc0();pl1=C(i0(),1),uh8={AbortMultipartUploadCommand:On,CompleteMultipartUploadCommand:Dn,CopyObjectCommand:bg0,CreateBucketCommand:fg0,CreateBucketMetadataConfigurationCommand:gg0,CreateBucketMetadataTableConfigurationCommand:ug0,CreateMultipartUploadCommand:Ln,CreateSessionCommand:np,DeleteBucketCommand:ig0,DeleteBucketAnalyticsConfigurationCommand:mg0,DeleteBucketCorsCommand:ng0,DeleteBucketEncryptionCommand:og0,DeleteBucketIntelligentTieringConfigurationCommand:sg0,DeleteBucketInventoryConfigurationCommand:eg0,DeleteBucketLifecycleCommand:Zh0,DeleteBucketMetadataConfigurationCommand:Yh0,DeleteBucketMetadataTableConfigurationCommand:Jh0,DeleteBucketMetricsConfigurationCommand:Wh0,DeleteBucketOwnershipControlsCommand:Hh0,DeleteBucketPolicyCommand:Uh0,DeleteBucketReplicationCommand:Bh0,DeleteBucketTaggingCommand:Dh0,DeleteBucketWebsiteCommand:wh0,DeleteObjectCommand:Iz,DeleteObjectsCommand:zh0,DeleteObjectTaggingCommand:Ah0,DeletePublicAccessBlockCommand:Rh0,GetBucketAbacCommand:Mh0,GetBucketAccelerateConfigurationCommand:Vh0,GetBucketAclCommand:Sh0,GetBucketAnalyticsConfigurationCommand:_h0,GetBucketCorsCommand:bh0,GetBucketEncryptionCommand:fh0,GetBucketIntelligentTieringConfigurationCommand:gh0,GetBucketInventoryConfigurationCommand:uh0,GetBucketLifecycleConfigurationCommand:ch0,GetBucketLocationCommand:dh0,GetBucketLoggingCommand:ph0,GetBucketMetadataConfigurationCommand:th0,GetBucketMetadataTableConfigurationCommand:rh0,GetBucketMetricsConfigurationCommand:ah0,GetBucketNotificationConfigurationCommand:$u0,GetBucketOwnershipControlsCommand:Qu0,GetBucketPolicyCommand:Xu0,GetBucketPolicyStatusCommand:Gu0,GetBucketReplicationCommand:Ku0,GetBucketRequestPaymentCommand:Fu0,GetBucketTaggingCommand:Nu0,GetBucketVersioningCommand:Ou0,GetBucketWebsiteCommand:Lu0,GetObjectCommand:MD,GetObjectAclCommand:ju0,GetObjectAttributesCommand:zu0,GetObjectLegalHoldCommand:Tu0,GetObjectLockConfigurationCommand:qu0,GetObjectRetentionCommand:Iu0,GetObjectTaggingCommand:ku0,GetObjectTorrentCommand:Cu0,GetPublicAccessBlockCommand:vu0,HeadBucketCommand:Vz,HeadObjectCommand:hH,ListBucketAnalyticsConfigurationsCommand:xu0,ListBucketIntelligentTieringConfigurationsCommand:yu0,ListBucketInventoryConfigurationsCommand:hu0,ListBucketMetricsConfigurationsCommand:lu0,ListBucketsCommand:En,ListDirectoryBucketsCommand:zn,ListMultipartUploadsCommand:mu0,ListObjectsCommand:iu0,ListObjectsV2Command:uH,ListObjectVersionsCommand:nu0,ListPartsCommand:Pn,PutBucketAbacCommand:ou0,PutBucketAccelerateConfigurationCommand:su0,PutBucketAclCommand:eu0,PutBucketAnalyticsConfigurationCommand:Zl0,PutBucketCorsCommand:Yl0,PutBucketEncryptionCommand:Jl0,PutBucketIntelligentTieringConfigurationCommand:Wl0,PutBucketInventoryConfigurationCommand:Hl0,PutBucketLifecycleConfigurationCommand:Ul0,PutBucketLoggingCommand:Bl0,PutBucketMetricsConfigurationCommand:Dl0,PutBucketNotificationConfigurationCommand:wl0,PutBucketOwnershipControlsCommand:El0,PutBucketPolicyCommand:Pl0,PutBucketReplicationCommand:Tl0,PutBucketRequestPaymentCommand:ql0,PutBucketTaggingCommand:Il0,PutBucketVersioningCommand:kl0,PutBucketWebsiteCommand:Cl0,PutObjectCommand:CN,PutObjectAclCommand:vl0,PutObjectLegalHoldCommand:fl0,PutObjectLockConfigurationCommand:gl0,PutObjectRetentionCommand:ul0,PutObjectTaggingCommand:An,PutPublicAccessBlockCommand:ml0,RenameObjectCommand:il0,RestoreObjectCommand:nl0,SelectObjectContentCommand:ol0,UpdateBucketMetadataInventoryTableConfigurationCommand:sl0,UpdateBucketMetadataJournalTableConfigurationCommand:el0,UpdateObjectEncryptionCommand:Zc0,UploadPartCommand:Tn,UploadPartCopyCommand:Xc0,WriteGetObjectResponseCommand:Gc0},lh8={paginateListBuckets:Il1,paginateListDirectoryBuckets:kl1,paginateListObjectsV2:Cl1,paginateListParts:vl1},ch8={waitUntilBucketExists:cl1,waitUntilBucketNotExists:ml1,waitUntilObjectExists:dl1,waitUntilObjectNotExists:il1};nl1=class nl1 extends eY{};pl1.createAggregatedClient(uh8,nl1,{paginators:lh8,waiters:ch8})});var ol1=D(()=>{_g0();vg0();xg0();yg0();hg0();lg0();cg0();E90();dg0();pg0();tg0();rg0();ag0();$h0();Qh0();Xh0();Gh0();Kh0();Fh0();Nh0();Oh0();Lh0();jh0();Eh0();Th0();Ph0();qh0();Ih0();kh0();Ch0();vh0();xh0();yh0();hh0();lh0();mh0();ih0();nh0();oh0();sh0();eh0();Zu0();Yu0();Ju0();Wu0();Hu0();Uu0();Bu0();Du0();wu0();Eu0();Pu0();Au0();Ru0();Mu0();Vu0();Su0();_u0();bu0();wn();jn();fu0();gu0();uu0();cu0();yZ0();gZ0();du0();tu0();pu0();hZ0();uZ0();ru0();au0();$l0();Ql0();Xl0();Gl0();Kl0();Fl0();Nl0();Ol0();Ll0();jl0();zl0();Al0();Rl0();Ml0();Vl0();Sl0();_l0();bl0();xl0();yl0();hl0();ll0();cl0();dl0();pl0();tl0();rl0();al0();$c0();Qc0();Yc0();Jc0();Wc0()});var rl1=()=>{};var sl1=D(()=>{rl1();Kc0();Hc0();Fc0();Uc0()});var al1=D(()=>{Nc0();Bc0();Oc0();Dc0()});var el1;var $c1=D(()=>{el1={CRC32:"CRC32",CRC32C:"CRC32C",CRC64NVME:"CRC64NVME",MD5:"MD5",SHA1:"SHA1",SHA256:"SHA256",SHA512:"SHA512",XXHASH128:"XXHASH128",XXHASH3:"XXHASH3",XXHASH64:"XXHASH64"}});var Zc1=()=>{};var Qc1=()=>{};var mZ0=D(()=>{Mz();tl1();ol1();J1();sl1();al1();$c1();cx0();Zc1();Qc1()});function Xc1($){let{port:Z,query:Q}=$,{protocol:Y,path:X,hostname:J}=$;if(Y&&Y.slice(-1)!==":")Y+=":";if(Z)J+=`:${Z}`;if(X&&X.charAt(0)!=="/")X=`/${X}`;let G=Q?Yc1.buildQueryString(Q):"";if(G&&G[0]!=="?")G=`?${G}`;let W="";if($.username!=null||$.password!=null){let H=$.username??"",F=$.password??"";W=`${H}:${F}@`}let K="";if($.fragment)K=`#${$.fragment}`;return`${Y}//${W}${J}${X}${G}${K}`}var Yc1;var Jc1=D(()=>{Yc1=C(R60(),1)});var Gc1="UNSIGNED-PAYLOAD",Wc1="X-Amz-Content-Sha256";class dZ0{signer;constructor($){let Z={service:$.signingName||$.service||"s3",uriEscapePath:$.uriEscapePath||!1,applyChecksum:$.applyChecksum||!1,...$};this.signer=new Kc1.SignatureV4MultiRegion(Z)}presign($,{unsignableHeaders:Z=new Set,hoistableHeaders:Q=new Set,unhoistableHeaders:Y=new Set,...X}={}){return this.prepareRequest($,{unsignableHeaders:Z,unhoistableHeaders:Y,hoistableHeaders:Q}),this.signer.presign($,{expiresIn:900,unsignableHeaders:Z,unhoistableHeaders:Y,...X})}presignWithCredentials($,Z,{unsignableHeaders:Q=new Set,hoistableHeaders:Y=new Set,unhoistableHeaders:X=new Set,...J}={}){return this.prepareRequest($,{unsignableHeaders:Q,unhoistableHeaders:X,hoistableHeaders:Y}),this.signer.presignWithCredentials($,Z,{expiresIn:900,unsignableHeaders:Q,unhoistableHeaders:X,...J})}prepareRequest($,{unsignableHeaders:Z=new Set,unhoistableHeaders:Q=new Set,hoistableHeaders:Y=new Set}={}){Z.add("content-type"),Object.keys($.headers).map((W)=>W.toLowerCase()).filter((W)=>W.startsWith("x-amz-server-side-encryption")).forEach((W)=>{if(!Y.has(W))Q.add(W)}),$.headers[Wc1]=Gc1;let X=$.headers.host,J=$.port,G=`${$.hostname}${$.port!=null?":"+J:""}`;if(!X||X===$.hostname&&$.port!=null)$.headers.host=G}}var Kc1;var Lc0=D(()=>{Kc1=C(Eg(),1)});var Hc1,Fc1,iZ0=async($,Z,Q={})=>{let Y,X;if(typeof $.config.endpointProvider==="function"){let N=(await Hc1.getEndpointFromInstructions(Z.input,Z.constructor,$.config)).properties?.authSchemes?.[0];if(N?.name==="sigv4a")X=N?.signingRegionSet?.join(",");else X=N?.signingRegion;Y=new dZ0({...$.config,signingName:N?.signingName,region:async()=>X})}else Y=new dZ0($.config);let J=(U,N)=>async(B)=>{let{request:O}=B;if(!Fc1.HttpRequest.isInstance(O))throw Error("Request to be presigned is not an valid HTTP request.");delete O.headers["amz-sdk-invocation-id"],delete O.headers["amz-sdk-request"],delete O.headers["x-amz-user-agent"];let L,w={...Q,signingRegion:Q.signingRegion??N.signing_region??X,signingService:Q.signingService??N.signing_service};if(N.s3ExpressIdentity)L=await Y.presignWithCredentials(O,N.s3ExpressIdentity,w);else L=await Y.presign(O,w);return{response:{},output:{$metadata:{httpStatusCode:200},presigned:L}}},G="presignInterceptMiddleware",W=$.middlewareStack.clone();W.addRelativeTo(J,{name:G,relation:"before",toMiddleware:"awsAuthMiddleware",override:!0});let K=Z.resolveMiddleware(W,$.config,{}),{output:H}=await K({input:Z.input}),{presigned:F}=H;return Xc1(F)};var Uc1=D(()=>{Jc1();Lc0();Hc1=C(Y1(),1),Fc1=C(v5(),1)});var Nc1=D(()=>{Uc1();Lc0()});import{extname as mh8}from"path";function q3($){let Z;try{Z=decodeURIComponent($)}catch{Z=$}let Y=Z.replace(/\0/g,"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"/").split("/"),X=[];for(let J of Y)if(J==="..")X.pop();else if(J!=="."&&J!=="")X.push(J);return X.join("/")}function kD($,Z){let Q=q3(Z);if(!Q)throw Error("Key is empty after sanitization");return`${$}/${Q}`}function Bc1($,Z){if(!Z)return`${$}/`;let Q=q3(Z);return`${$}/${Q}${Q.endsWith("/")?"":"/"}`}function mg($,Z,Q){let Y=Q.split("/").map(encodeURIComponent).join("/");return`${$}/api/${encodeURIComponent(Z)}/files/${Y}`}function wc0($,Z){let Q=`${$}/`;if(Z.startsWith(Q))return Z.slice(Q.length);return Z}function v7($){let Z=mh8($).toLowerCase();return dh8[Z]??"application/octet-stream"}function pZ0($){let Z=$.split(";")[0].trim();if(ih8.has(Z))return!0;if(Z.startsWith("text/"))return!0;return!1}var dh8,ih8;var YK=D(()=>{dh8={".json":"application/json",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".ts":"text/typescript",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".pdf":"application/pdf",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".wasm":"application/wasm",".yaml":"application/yaml",".yml":"application/yaml",".toml":"application/toml"};ih8=new Set(["application/json","text/html","text/css","application/javascript","text/typescript","text/plain","text/markdown","text/csv","application/xml","image/svg+xml","application/yaml","application/toml"])});class jc0{client;bucket;constructor($){this.bucket=$.bucket,this.client=new eY({endpoint:$.endpoint,region:$.region,credentials:{accessKeyId:$.accessKeyId,secretAccessKey:$.secretAccessKey},forcePathStyle:$.forcePathStyle})}async getBytesOrPresign($,Z,Q){let Y=kD($,Z),X=await this.client.send(new hH({Bucket:this.bucket,Key:Y})),J=X.ContentLength??0,G=X.ContentType??v7(Z);if(J>Q.presignWhenLargerThan){let F=await iZ0(this.client,new MD({Bucket:this.bucket,Key:Y}),{expiresIn:Q.presignExpiresIn??3600});return{error:"FILE_TOO_LARGE",size:J,maxInlineSize:Q.presignWhenLargerThan,presignedUrl:F,contentType:G}}let K=await(await this.client.send(new MD({Bucket:this.bucket,Key:Y}))).Body.transformToByteArray(),H=pZ0(G);return{content:H?new TextDecoder().decode(K):Buffer.from(K).toString("base64"),contentType:G,encoding:H?"utf-8":"base64",size:J,lastModified:X.LastModified,etag:X.ETag}}async getBytes($,Z){let Q=kD($,Z);return(await this.client.send(new MD({Bucket:this.bucket,Key:Q}))).Body.transformToByteArray()}async put($,Z,Q,Y){let X=kD($,Z),J=Y?.contentType??v7(Z);return{etag:(await this.client.send(new CN({Bucket:this.bucket,Key:X,Body:typeof Q==="string"?Buffer.from(Q,"utf-8"):Q,ContentType:J}))).ETag,key:Z}}async list($,Z){let Q=Bc1($,Z?.prefix),Y=await this.client.send(new uH({Bucket:this.bucket,Prefix:Q,MaxKeys:Z?.maxKeys??1000,ContinuationToken:Z?.continuationToken,Delimiter:Z?.delimiter})),X=Y.CommonPrefixes?.map((J)=>wc0($,J.Prefix??"")).filter(Boolean);return{objects:(Y.Contents??[]).map((J)=>({key:wc0($,J.Key??""),size:J.Size??0,lastModified:J.LastModified,etag:J.ETag})),isTruncated:Y.IsTruncated??!1,nextContinuationToken:Y.NextContinuationToken,commonPrefixes:X&&X.length>0?X:void 0}}async delete($,Z){let Q=kD($,Z);await this.client.send(new Iz({Bucket:this.bucket,Key:Q}))}async head($,Z){let Q=kD($,Z),Y=await this.client.send(new hH({Bucket:this.bucket,Key:Q}));return{contentType:Y.ContentType??v7(Z),size:Y.ContentLength??0,lastModified:Y.LastModified,etag:Y.ETag,metadata:Y.Metadata&&Object.keys(Y.Metadata).length>0?Y.Metadata:void 0}}async presignedGetUrl($,Z,Q=3600,Y){let X=kD($,Z);return iZ0(this.client,new MD({Bucket:this.bucket,Key:X}),{expiresIn:Q})}async presignedPutUrl($,Z,Q=3600,Y){let X=kD($,Z);return iZ0(this.client,new CN({Bucket:this.bucket,Key:X,ContentType:Y}),{expiresIn:Q})}}var Oc1=D(()=>{mZ0();Nc1();YK()});function ph8(){let $=E0();return!!($.s3Endpoint&&$.s3Bucket&&$.s3AccessKeyId&&$.s3SecretAccessKey)}function $X(){if(qn!==void 0)return qn;if(!ph8())return qn=null,null;let $=E0();return qn=new jc0({endpoint:$.s3Endpoint,bucket:$.s3Bucket,region:$.s3Region,accessKeyId:$.s3AccessKeyId,secretAccessKey:$.s3SecretAccessKey,forcePathStyle:$.s3ForcePathStyle}),qn}var qn;var SD=D(()=>{F$();Oc1()});function KG($,Z){return{getBytesOrPresign:(Q,Y)=>$.getBytesOrPresign(Z,Q,Y),getBytes:(Q)=>$.getBytes(Z,Q),put:(Q,Y,X)=>$.put(Z,Q,Y,X),list:(Q)=>$.list(Z,Q),delete:(Q)=>$.delete(Z,Q),head:(Q)=>$.head(Z,Q),presignedGetUrl:(Q,Y,X)=>$.presignedGetUrl(Z,Q,Y,X),presignedPutUrl:(Q,Y,X)=>$.presignedPutUrl(Z,Q,Y,X)}}import{mkdir as nh8,readdir as th8,readFile as Ec0,stat as nZ0,unlink as oh8,writeFile as rh8}from"fs/promises";import{createHmac as sh8}from"crypto";import{dirname as ah8,join as Mn}from"path";function zc0($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return Mn(eh8,Z)}function dg($,Z){return Mn(zc0($),q3(Z))}class M3{orgId;baseUrl;constructor($,Z){this.orgId=$;this.baseUrl=Z}async getBytesOrPresign($,Z){let Q=dg(this.orgId,$),Y=await nZ0(Q),X=v7($);if(Y.size>Z.presignWhenLargerThan)return{error:"FILE_TOO_LARGE",size:Y.size,maxInlineSize:Z.presignWhenLargerThan,presignedUrl:await this.presignedGetUrl($),contentType:X};let J=await Ec0(Q),G=pZ0(X);return{content:G?new TextDecoder().decode(J):Buffer.from(J).toString("base64"),contentType:X,encoding:G?"utf-8":"base64",size:Y.size,lastModified:Y.mtime}}async getBytes($){let Z=await Ec0(dg(this.orgId,$));return new Uint8Array(Z)}async put($,Z,Q){let Y=dg(this.orgId,$);return await nh8(ah8(Y),{recursive:!0}),await rh8(Y,typeof Z==="string"?Buffer.from(Z,"utf-8"):Z),{key:$}}async list($){let Z=$?.prefix?Mn(zc0(this.orgId),q3($.prefix)):zc0(this.orgId),Q;try{Q=await th8(Z,{withFileTypes:!0})}catch{return{objects:[],isTruncated:!1}}let Y=$?.maxKeys??1000,X=$?.prefix,J=Q.filter((W)=>W.isFile());if($?.delimiter){let W=[],K=Q.filter((O)=>O.isDirectory());for(let O of K){let L=X?`${X}/${O.name}/`:`${O.name}/`;W.push(L)}W.sort();let H=Y,F=W.slice(0,H);H-=F.length;let U=J.slice(0,H),N=W.length+J.length;return{objects:await Promise.all(U.map(async(O)=>{let L=await nZ0(Mn(Z,O.name));return{key:X?`${X}/${O.name}`:O.name,size:L.size,lastModified:L.mtime}})),isTruncated:N>Y,commonPrefixes:F.length>0?F:void 0}}return{objects:await Promise.all(J.slice(0,Y).map(async(W)=>{let K=await nZ0(Mn(Z,W.name));return{key:X?`${X}/${W.name}`:W.name,size:K.size,lastModified:K.mtime}})),isTruncated:J.length>Y}}async delete($){await oh8(dg(this.orgId,$))}async head($){let Z=await nZ0(dg(this.orgId,$));return{contentType:v7($),size:Z.size,lastModified:Z.mtime}}async presignedGetUrl($,Z,Q){if(Q?.requireFetchable)throw Error("object storage returned a not fetchable (data:) URL; configure real S3/R2/MinIO for large-payload offload");let Y=dg(this.orgId,$),X=await Ec0(Y),J=v7($),G=Buffer.from(X).toString("base64");return`data:${J};base64,${G}`}async presignedPutUrl($,Z=3600){if(!this.baseUrl)throw Error("baseUrl required for presigned PUT URLs in dev mode");let Q=q3($),Y=Math.floor(Date.now()/1000)+Z,X=E0().encryptionKey||"dev-secret",J=`${this.orgId}:${Q}:${Y}:PUT`,G=sh8("sha256",X).update(J).digest("hex"),W=new URL(`/api/dev-assets/${this.orgId}/${Q}`,this.baseUrl);return W.searchParams.set("expires",Y.toString()),W.searchParams.set("signature",G),W.searchParams.set("method","PUT"),W.toString()}}var eh8="./data/assets";var ig=D(()=>{YK();F$()});function lH($){return $u8.test($)&&$!=="."&&$!==".."}function G7($){if(!lH($))throw Error(`Invalid org-fs volume name: ${JSON.stringify($)}`)}function b7($){return q3($)}function pg($){let Z=$.lastIndexOf("/");return Z===-1?"":$.slice(0,Z)}function CD($){let Z=pg($);if(Z==="")return[];let Q=Z.split("/"),Y=[],X="";for(let J of Q)X=X===""?J:`${X}/${J}`,Y.push(X);return Y}function cH($,Z){return`${Dc1}/${$}/${Z}`}function tZ0($){return`${Dc1}/${$}/`}var $u8,Dc1="_fs";var kz=D(()=>{YK();$u8=/^[A-Za-z0-9_.-]{1,128}$/});import{createHmac as Pc0,randomBytes as Ac0,scrypt as Zu8,timingSafeEqual as Lc1}from"crypto";import{promisify as Qu8}from"util";async function jc1($){let Z=Ac0(16),Q=await wc1($,Z,Yu8);return`scrypt$${Z.toString("hex")}$${Q.toString("hex")}`}async function Ec1($,Z){let Q=Z.split("$");if(Q.length!==3||Q[0]!=="scrypt")return!1;let Y=Buffer.from(Q[1],"hex"),X=Buffer.from(Q[2],"hex");if(Y.length===0||X.length===0)return!1;let J;try{J=await wc1($,Y,X.length)}catch{return!1}return X.length===J.length&&Lc1(X,J)}function zc1(){return Ac0(16).toString("hex")}function Pc1(){if(oZ0)return oZ0;let $;try{let Z=E0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return oZ0=$?Buffer.from($):Ac0(32),oZ0}function Ac1($){let Z=Buffer.from(JSON.stringify($)).toString("base64url"),Q=Pc0("sha256",Pc1()).update(Z).digest("base64url");return`${Z}.${Q}`}function Tc1($,Z){let Q=$.indexOf(".");if(Q<0)return null;let Y=$.slice(0,Q),X=Buffer.from($.slice(Q+1)),J=Buffer.from(Pc0("sha256",Pc1()).update(Y).digest("base64url"));if(X.length!==J.length||!Lc1(X,J))return null;let G;try{G=JSON.parse(Buffer.from(Y,"base64url").toString())}catch{return null}if(G.o!==Z.org||G.v!==Z.volume||G.s!==Z.secret||typeof G.e!=="number"||G.e<Z.nowSec)return null;return{govPath:G.p}}function Tc0($,Z,Q){return`fsu_${Pc0("sha256","fsunlock-name").update(`${$}:${Z}:${Q}`).digest("hex").slice(0,16)}`}var Yu8=64,wc1,oZ0=null;var Rc0=D(()=>{F$();wc1=Qu8(Zu8)});import{createHash as Xu8}from"crypto";function Hu8($){if(typeof $!=="object"||$===null)return!1;let Z=$;return Z.name==="NoSuchKey"||Z.Code==="NoSuchKey"||Z.code==="ENOENT"||Z.$metadata?.httpStatusCode===404}function Rc1($){return Xu8("sha256").update($).digest("hex")}class I3{storage;manifest;organizationId;maxFileBytes;volumeQuotaBytes;constructor($,Z,Q,Y={}){this.storage=$;this.manifest=Z;this.organizationId=Q;this.maxFileBytes=Y.maxFileBytes??Wu8,this.volumeQuotaBytes=Y.volumeQuotaBytes??Ku8}async usage($){return G7($),this.manifest.usage(this.organizationId,$)}async stat($,Z){return G7($),this.manifest.get(this.organizationId,$,b7(Z))}async listVolumeFiles($){return G7($),this.manifest.listVolumeFiles(this.organizationId,$)}async listDir($,Z){return G7($),this.manifest.listDir(this.organizationId,$,b7(Z))}async read($,Z){let Q=await this.requireFile($,Z);try{return await this.storage.getBytes(cH($,Q.path))}catch(Y){if(Hu8(Y))throw new ZX(`No such file: ${Q.path}`);throw Y}}async setShareMode($,Z,Q,Y){G7($);let X=b7(Z),J=await this.manifest.get(this.organizationId,$,X);if(!J)throw new ZX(`No such path: ${X}`);let G=null,W=null;if(Q==="password"){if(!Y.password)throw new HG("A password is required to set password mode");G=await jc1(Y.password),W=zc1()}let K=await this.manifest.setShareMode({organizationId:this.organizationId,volume:$,path:J.path,readPublic:Q!=="private",passwordHash:G,shareSecret:W,actor:Y.actor});if(!K)throw new ZX(`No such path: ${J.path}`);return K}async setReadPublic($,Z,Q,Y){return this.setShareMode($,Z,Q?"public":"private",{actor:Y.actor})}async resolveReadAccess($,Z){G7($);let Q=b7(Z),Y=await this.manifest.get(this.organizationId,$,Q);if(!Y||Y.kind!=="file")return{access:"private"};let X=await this.manifest.resolveGoverningShare({organizationId:this.organizationId,volume:$,candidatePaths:[Q,...CD(Q)]});if(!X)return{access:"private"};if(!X.passwordHash)return{access:"public"};return{access:"password",govPath:X.path,secret:X.secret??"",passwordHash:X.passwordHash}}async isPubliclyReadable($,Z){G7($);let Q=b7(Z),Y=await this.manifest.get(this.organizationId,$,Q);if(!Y||Y.kind!=="file")return!1;if(Y.readPublic)return!0;return this.manifest.hasPublicAncestorDir(this.organizationId,$,CD(Q))}async inheritsPublic($,Z){return G7($),this.manifest.hasPublicAncestorDir(this.organizationId,$,CD(b7(Z)))}async childrenInheritPublic($,Z){G7($);let Q=b7(Z);if(Q==="")return!1;return this.manifest.hasPublicAncestorDir(this.organizationId,$,[...CD(Q),Q])}async recentWithEffectivePublic($){return this.withEffectivePublic(await this.recent($))}async searchWithEffectivePublic($,Z,Q,Y){return this.withEffectivePublic(await this.manifest.searchFiles({organizationId:this.organizationId,query:$,limit:Z,volumes:Q,pathPrefix:Y?b7(Y):void 0}))}async withEffectivePublic($){let Z=new Map;for(let Y of $){let X=Z.get(Y.volume);if(!X)X=new Set,Z.set(Y.volume,X);for(let J of CD(Y.path))X.add(J)}let Q=new Map;return await Promise.all([...Z].map(async([Y,X])=>{let J=await this.manifest.publicDirPaths({organizationId:this.organizationId,volume:Y,paths:[...X]});Q.set(Y,new Set(J))})),$.map((Y)=>{let X=Q.get(Y.volume),J=!!X&&CD(Y.path).some((G)=>X.has(G));return{...Y,effectivePublic:Y.readPublic||J}})}async presignRead($,Z,Q){let Y=await this.requireFile($,Z);return this.storage.presignedGetUrl(cH($,Y.path),Q)}async write($,Z,Q,Y){G7($);let X=b7(Z);if(X==="")throw new HG("Cannot write to the volume root");let J=typeof Q==="string"?new TextEncoder().encode(Q):Q;if(J.byteLength>this.maxFileBytes)throw new Sz(`File exceeds the ${this.maxFileBytes}-byte per-file limit`);let[G,W]=await Promise.all([Y.skipVolumeQuota?Promise.resolve(null):this.manifest.usage(this.organizationId,$),this.manifest.get(this.organizationId,$,X)]);if(W?.kind==="dir")throw new HG(`Cannot write a file at ${X}: a directory exists there`);if(G){let K=W?.kind==="file"?W.size:0;if(G.bytes-K+J.byteLength>this.volumeQuotaBytes)throw new Sz(`Write would exceed the volume quota of ${this.volumeQuotaBytes} bytes`)}await this.ensureDirs($,X,Y.actor),await this.storage.put(cH($,X),J,{contentType:Y.contentType??v7(X)});try{return await g8(()=>this.manifest.putFile({organizationId:this.organizationId,volume:$,path:X,parent:pg(X),contentHash:Rc1(J),size:J.byteLength,actor:Y.actor,threadId:Y.threadId??null}))}catch(K){throw console.error("org-fs manifest write lost after object put",{organizationId:this.organizationId,volume:$,path:X,size:J.byteLength,error:K instanceof Error?K.message:String(K)}),K}}async mkdir($,Z,Q){G7($);let Y=b7(Z);if(Y==="")return;if((await this.manifest.get(this.organizationId,$,Y))?.kind==="file")throw new HG(`Cannot create a directory at ${Y}: a file exists there`);await this.ensureDirs($,Y,Q.actor),await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Y,parent:pg(Y),actor:Q.actor})}async delete($,Z,Q){G7($);let Y=b7(Z);if(Y==="")throw new HG("Cannot delete the volume root");let X=await this.manifest.get(this.organizationId,$,Y);if(!X)return;if(X.kind==="dir"){let J=await this.manifest.listSubtreeFiles(this.organizationId,$,Y);await Promise.all(J.map((G)=>this.storage.delete(cH($,G.path)))),await this.manifest.tombstoneSubtree(this.organizationId,$,Y,Q.actor);return}await this.storage.delete(cH($,Y)),await this.manifest.tombstone(this.organizationId,$,Y,Q.actor)}async move($,Z,Q,Y){G7($);let X=b7(Z),J=b7(Q);if(X===""||J==="")throw new HG("Cannot move the volume root");if(J===X||J.startsWith(`${X}/`))throw new HG(`Cannot move ${X} onto itself or into its own subtree`);let G=await this.manifest.get(this.organizationId,$,X);if(!G)throw new ZX(`No such path: ${X}`);if(G.kind==="file"){let H=await this.storage.getBytes(cH($,X));await this.write($,J,H,{...Y,skipVolumeQuota:!0}),await this.delete($,X,Y);return}let[W,K]=await Promise.all([this.manifest.listSubtreeFiles(this.organizationId,$,X),this.manifest.listSubtreeDirs(this.organizationId,$,X)]);await this.mkdir($,J,Y);for(let H of W){let F=H.path.slice(X.length+1),U=await this.storage.getBytes(cH($,H.path));await this.write($,`${J}/${F}`,U,{...Y,skipVolumeQuota:!0})}for(let H of K){let F=H.path.slice(X.length+1);await this.mkdir($,`${J}/${F}`,Y)}await this.delete($,X,Y)}async filesExist($,Z){G7($);let Q=await this.manifest.liveFilePaths({organizationId:this.organizationId,volume:$,paths:Z.map((Y)=>b7(Y))});return new Set(Q)}async recent($){return this.manifest.recentFiles({organizationId:this.organizationId,limit:$})}async changes($,Z,Q=Ju8){G7($);let Y=Z||"0";if(!/^\d+$/.test(Y))throw new HG(`Invalid cursor: ${Z}`);let X=await this.manifest.changesSince({organizationId:this.organizationId,volume:$,sinceSeq:Y,limit:Q}),J=X.at(-1);return{entries:X,cursor:J?J.seq:Z||"0",hasMore:X.length>=Q}}async latestSeq($){return G7($),this.manifest.latestSeq({organizationId:this.organizationId,volume:$})}async backfillFromStorage($,Z){G7($);let Q=tZ0($),Y,X=0;do{let J=await this.storage.list({prefix:Q,maxKeys:Gu8,continuationToken:Y});for(let G of J.objects){let W=G.key.slice(Q.length);if(W==="")continue;await this.ensureDirs($,W,Z.actor);let K=await this.storage.getBytes(G.key);await this.manifest.putFile({organizationId:this.organizationId,volume:$,path:W,parent:pg(W),contentHash:Rc1(K),size:K.byteLength,actor:Z.actor}),X++}Y=J.isTruncated?J.nextContinuationToken:void 0}while(Y);return X}async requireFile($,Z){G7($);let Q=b7(Z),Y=await this.manifest.get(this.organizationId,$,Q);if(!Y||Y.kind!=="file")throw new ZX(`No such file: ${Q}`);return Y}async ensureDirs($,Z,Q){for(let Y of CD(Z))await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Y,parent:pg(Y),actor:Q})}}var Ju8=500,Gu8=1000,Wu8=524288000,Ku8=10737418240,Sz,HG,ZX;var _N=D(()=>{D8();YK();kz();Rc0();Sz=class Sz extends Error{constructor($){super($);this.name="OrgFsQuotaError"}};HG=class HG extends Error{constructor($){super($);this.name="OrgFsValidationError"}};ZX=class ZX extends Error{constructor($){super($);this.name="OrgFsNotFoundError"}}});import{z as vN}from"zod";function mH($){return $.startsWith(qc1)}function _D($){return`${qc1}${$}`}function Ou8($){let Z=new Map(Nu8.map((Q)=>[Q.set,Q]));if($)try{for(let Q of Bu8.parse(JSON.parse($)))Z.set(Q.set,Q)}catch(Q){console.warn("[org-fs] invalid ORGFS_PUBLIC_SETS \u2014 using built-in defaults only",Q)}return[...Z.values()]}function V3(){return Ou8(E0().orgFsPublicSetsJson)}function Vn($){let Z=$X(),Q=Z?KG(Z,In):new M3(In,$.baseUrl);return new I3(Q,$.storage.orgFsEntries,In)}var In="org_orgfs_public_skills",qc1="public-",Fu8,Uu8,Nu8,Bu8;var Cz=D(()=>{F$();SD();ig();_N();Fu8=vN.object({from:vN.string(),to:vN.string().optional()}),Uu8=vN.object({set:vN.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/),repo:vN.string().regex(/^[\w.-]+\/[\w.-]+$/),ref:vN.string().min(1),paths:vN.array(Fu8).min(1)}),Nu8=[{set:"core",repo:"decocms/studio",ref:"main",paths:[{from:"packages/sandbox/image/skills"}]},{set:"storefront",repo:"decocms/storefront-skills",ref:"main",paths:[{from:".claude-seo/skills"},{from:".claude-performance/skills"},{from:".claude-deco/skills"}]}],Bu8=vN.array(Uu8).refine(($)=>new Set($.map((Z)=>Z.set)).size===$.length,{message:"duplicate set names"})});function bN($){if(typeof $==="string")return $.length>0?[$]:[];if(Array.isArray($))return $.flatMap(bN);if($!==null&&typeof $==="object")return Object.values($).flatMap(bN);return[]}var y0;var w5=D(()=>{y0=class y0 extends Error{provider;status;retryAfterMs;constructor($){super($.message,{cause:$.cause});this.name="GitProviderError",this.provider=$.provider,this.status=$.status,this.retryAfterMs=$.retryAfterMs??null}get isRateLimited(){return this.status===429||this.retryAfterMs!==null}get isAuthFailure(){return this.status===401||this.status===403}}});import{sql as _z}from"kysely";function qc0($){if($===null)return null;return $ instanceof Date?$.toISOString():String($)}function XK($){return{organizationId:$.organization_id,volume:$.volume,path:$.path,parent:$.parent,kind:$.kind,contentHash:$.content_hash,size:Number($.size),seq:String($.seq),deletedAt:qc0($.deleted_at),createdBy:$.created_by,createdAt:qc0($.created_at)??"",updatedBy:$.updated_by,updatedAt:qc0($.updated_at)??"",threadId:$.thread_id,readPublic:$.read_public,shareMode:!$.read_public?"private":$.share_password_hash?"password":"public"}}class Sn{db;constructor($){this.db=$}async putFile($){let Z=new Date,Q=$.threadId??null,Y=await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z,thread_id:Q}).onConflict((X)=>X.columns(["organization_id","volume","path"]).doUpdateSet({kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:rZ0,read_public:_z`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`,thread_id:_z`coalesce(cast(${Q} as text), org_fs_entry.thread_id)`})).returning(JK).executeTakeFirstOrThrow();return XK(Y)}async putDir($){let Z=new Date;await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"dir",content_hash:null,size:0,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z}).onConflict((Q)=>Q.columns(["organization_id","volume","path"]).where("org_fs_entry.deleted_at","is not",null).doUpdateSet({kind:"dir",content_hash:null,size:0,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:rZ0,read_public:_z`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`})).execute()}async get($,Z,Q){let Y=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("path","=",Q).where("deleted_at","is",null).select(JK).executeTakeFirst();return Y?XK(Y):null}async listDir($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("parent","=",Q).where("deleted_at","is",null).select(JK).orderBy("path","asc").execute()).map((X)=>XK(X))}async listVolumeDirs($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).select(JK).execute()).map((Y)=>XK(Y))}async listVolumeFiles($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select(JK).execute()).map((Y)=>XK(Y))}async listSubtreeFiles($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).where("path","like",`${kn(Q)}/%`).select(JK).execute()).map((X)=>XK(X))}async listSubtreeDirs($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).where("path","like",`${kn(Q)}/%`).select(JK).execute()).map((X)=>XK(X))}async tombstone($,Z,Q,Y){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Y,updated_at:new Date,seq:rZ0}).where("organization_id","=",$).where("volume","=",Z).where("path","=",Q).where("deleted_at","is",null).execute()}async tombstoneSubtree($,Z,Q,Y){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Y,updated_at:new Date,seq:rZ0}).where("organization_id","=",$).where("volume","=",Z).where("deleted_at","is",null).where((X)=>X.or([X("path","=",Q),X("path","like",`${kn(Q)}/%`)])).execute()}async setShareMode($){let Z=new Date,Q=await this.db.updateTable("org_fs_entry").set({read_public:$.readPublic,share_password_hash:$.passwordHash,share_secret:$.shareSecret,updated_by:$.actor,updated_at:Z}).where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("path","=",$.path).where("deleted_at","is",null).returning(JK).executeTakeFirst();return Q?XK(Q):null}async resolveGoverningShare($){if($.candidatePaths.length===0)return null;let Z=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.candidatePaths).select(["path","share_password_hash","share_secret"]).execute();if(Z.length===0)return null;Z.sort((Y,X)=>X.path.length-Y.path.length);let Q=Z[0];return{path:Q.path,passwordHash:Q.share_password_hash,secret:Q.share_secret}}async hasPublicAncestorDir($,Z,Q){if(Q.length===0)return!1;return!!await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",Q).select("path").limit(1).executeTakeFirst()}async publicDirPaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.paths).select("path").execute()).map((Q)=>Q.path)}async usage($,Z){let Q=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select((Y)=>[Y.fn.countAll().as("files"),Y.fn.coalesce(Y.fn.sum("size"),_z`0`).as("bytes")]).executeTakeFirst();return{files:Number(Q?.files??0),bytes:Number(Q?.bytes??0)}}async liveFilePaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","file").where("deleted_at","is",null).where("path","in",$.paths).select(["path"]).execute()).map((Q)=>Q.path)}async recentFiles($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).select(JK).orderBy("seq","desc").limit($.limit).execute()).map((Q)=>XK(Q))}async searchFiles($){if($.volumes&&$.volumes.length===0)return[];let Z=kn($.query),Q=this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).where("path","ilike",`%${Z}%`);if($.volumes)Q=Q.where("volume","in",$.volumes);if($.pathPrefix)Q=Q.where("path","like",`${kn($.pathPrefix)}/%`);return(await Q.select(JK).orderBy("seq","desc").limit($.limit).execute()).map((X)=>XK(X))}async changesSince($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("seq",">",_z`cast(${$.sinceSeq} as bigint)`).select(JK).orderBy("seq","asc").limit($.limit).execute()).map((Q)=>XK(Q))}async latestSeq($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).select(_z`max(seq)`.as("seq")).executeTakeFirst())?.seq??"0"}}function kn($){return $.replace(/[\\%_]/g,"\\$&")}var JK,rZ0;var Mc0=D(()=>{JK=["organization_id","volume","path","parent","kind","content_hash","size","seq","deleted_at","created_by","created_at","updated_by","updated_at","thread_id","read_public","share_password_hash"],rZ0=_z`nextval('org_fs_entry_seq')`});import{createHash as Du8}from"crypto";import{gunzipSync as Lu8}from"zlib";function Vc0($,Z,Q){let Y=Z,X=Z+Q;while(Y<X&&$[Y]!==0)Y++;return new TextDecoder().decode($.subarray(Z,Y))}function ju8($,Z,Q){let Y=Vc0($,Z,Q).trim();return Y===""?0:Number.parseInt(Y,8)}function Eu8($){let Z=new Map,Q=0,Y=null,X=null;while(Q+512<=$.length){let J=$.subarray(Q,Q+512);if(Q+=512,J.every((N)=>N===0))break;let G=Vc0(J,0,100),W=Vc0(J,345,155);if(W)G=`${W}/${G}`;let K=ju8(J,124,12),H=String.fromCharCode(J[156]??0),F=$.subarray(Q,Q+K);if(Q+=Math.ceil(K/512)*512,H==="L"){let N=new TextDecoder().decode(F),B=N.indexOf("\x00");Y=B===-1?N:N.slice(0,B);continue}if(H==="x"){let N=new TextDecoder().decode(F);X=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(N)?.[1]??null;continue}if(H==="g")continue;let U=X??Y??G;if(Y=null,X=null,H==="0"||H==="\x00"||H==="")Z.set(U,new Uint8Array(F))}return Z}function zu8($,Z,Q){let Y=encodeURIComponent(Z);if(!Q)return{url:`https://codeload.github.com/${$}/tar.gz/${Y}`,headers:{}};return{url:`https://api.github.com/repos/${$}/tarball/${Y}`,headers:{Authorization:`Bearer ${Q}`,Accept:"application/vnd.github+json"}}}function Mc1($,Z){if($.length>ng)throw Error(`tarball for ${Z} exceeds ${ng} bytes`);let Q=Eu8(new Uint8Array(Lu8($,{maxOutputLength:wu8}))),Y=new Map;for(let[X,J]of Q){let G=X.indexOf("/");if(G===-1)continue;let W=X.slice(G+1);if(W)Y.set(W,J)}return Y}function Ic1($,Z,Q){if($>Z)throw Error(`tarball for ${Q} exceeds ${Z} bytes`)}async function Pu8($,Z){let Q=[],Y=0,X=$.getReader();try{while(!0){let{done:W,value:K}=await X.read();if(W)break;Y+=K.length,Ic1(Y,ng,Z),Q.push(K)}}finally{await X.cancel().catch(()=>{}),X.releaseLock()}let J=new Uint8Array(Y),G=0;for(let W of Q)J.set(W,G),G+=W.length;return J}function Vc1($){if($ instanceof kc0)return $.status>=500||$.status===429;if($ instanceof y0)return $.status===0||$.status>=500||$.status===429;if($ instanceof Error&&/declares .* bytes|exceeds .* bytes/.test($.message))return!1;return!0}async function Au8($,Z,Q){let{url:Y,headers:X}=zu8($,Z,Q),J=`${$}@${Z}`,G=async()=>{let W=await fetch(Y,{headers:X,signal:AbortSignal.timeout(60000)});if(!W.ok)throw await W.body?.cancel().catch(()=>{}),new kc0(W.status,`tarball fetch failed for ${J}: HTTP ${W.status}`);let K=Number(W.headers.get("content-length")??0);if(K>ng)throw Error(`tarball for ${J} declares ${K} bytes (cap ${ng})`);let H=new Uint8Array(await W.arrayBuffer());return Ic1(H.length,ng,J),H};try{let W=await g8(G,{maxAttempts:3,minTimeout:500,maxTimeout:4000,jitter:0.5,isRetriable:Vc1});return Mc1(W,J)}catch(W){if(W instanceof i5)throw W.cause instanceof Error?W.cause:W;throw W}}async function Tu8($,Z){if(!Z.tarball)return Au8($.repo,$.ref,Z.authToken);let Q=Z.tarball,Y=`${$.repo}@${$.ref}`,X;try{X=await g8(()=>Q(),{maxAttempts:3,minTimeout:500,maxTimeout:4000,jitter:0.5,isRetriable:Vc1})}catch(J){throw J instanceof i5&&J.cause instanceof Error?J.cause:J}if(!X)throw Error(`tarball not found for ${Y}`);return Mc1(await Pu8(X,Y),Y)}function Ru8($,Z){let Q=new Map;for(let{from:Y,to:X}of Z){let J=Y===""?"":`${Y.replace(/\/+$/,"")}/`;for(let[G,W]of $){if(!G.startsWith(J))continue;let K=G.slice(J.length);if(!K)continue;let H=b7(X?`${X}/${K}`:K);if(H)Q.set(H,W)}}return Q}function qu8($,Z){let Q=new Set;for(let J of $){let G=J.split("/");for(let W=1;W<G.length;W++)Q.add(G.slice(0,W).join("/"))}let Y=[...Z].filter((J)=>!Q.has(J)).sort((J,G)=>J.length-G.length),X=[];for(let J of Y)if(!X.some((G)=>J.startsWith(`${G}/`)))X.push(J);return X}function Mu8($){return Du8("sha256").update($).digest("hex")}function Iu8($){return $.manifestHash===$.hash&&$.storedPaths.has($.path)}async function Vu8($,Z){let Q=tZ0(Z),Y=new Set,X;do{let J=await $.list({prefix:Q,continuationToken:X});for(let G of J.objects)Y.add(G.key.slice(Q.length));X=J.nextContinuationToken}while(X);return Y}async function Sc0($,Z){let{orgId:Q,volume:Y,source:X}=Z,J=$X(),G=J?KG(J,Q):new M3(Q,Z.baseUrl),W=new Sn($),K=new I3(G,W,Q),H=Ru8(await Tu8(X,Z),X.paths),F=new Map((await W.listVolumeFiles(Q,Y)).map((w)=>[w.path,w.contentHash]));if(H.size===0&&F.size>0)throw Error(`volume "${Y}" resolved 0 files from ${X.repo}@${X.ref} `+`(check paths config) \u2014 refusing to delete the ${F.size} existing files`);let U=0;for(let w of F.keys()){if(H.has(w))continue;await K.delete(Y,w,{actor:Ic0}),U++}let N=await W.listVolumeDirs(Q,Y);for(let w of qu8(H.keys(),N.map((j)=>j.path)))await K.delete(Y,w,{actor:Ic0});let B=0,O=0,L=await Vu8(G,Y);for(let[w,j]of H){if(Iu8({hash:Mu8(j),manifestHash:F.get(w),storedPaths:L,path:w})){O++;continue}await K.write(Y,w,j,{actor:Ic0,contentType:v7(w),skipVolumeQuota:Z.skipVolumeQuota}),B++}return{written:B,deleted:U,unchanged:O}}async function ku8($,Z,Q){let Y=await Sc0($,{orgId:In,baseUrl:Q.baseUrl,volume:_D(Z.set),source:Z,skipVolumeQuota:!0});return{set:Z.set,...Y}}async function Cc0($,Z,Q){try{return await ku8($,Z,Q)}catch(Y){return{set:Z.set,error:Y instanceof Error?Y.message:String(Y)}}}async function kc1($,Z){let Q=[];for(let Y of V3())Q.push(await Cc0($,Y,Z));return Q}var Ic0="system:skill-set-sync",ng=209715200,wu8=1073741824,kc0;var sZ0=D(()=>{D8();w5();Mc0();ig();SD();YK();_N();kz();Cz();kc0=class kc0 extends Error{status;constructor($,Z){super(Z);this.status=$;this.name="TarballHttpError"}}});import{DBOS as aZ0,SchedulerMode as Su8}from"@dbos-inc/dbos-sdk";function Sc1($){_c0=$}function _u8(){if(!_c0)throw Error("[org-fs] public-sets sync runtime not initialized \u2014 setPublicSetsSyncRuntime() must run before the workflow fires");return _c0}async function vu8($,Z){for(let Q of V3()){let Y=await aZ0.runStep(()=>{let X=_u8();return Cc0(X.db,Q,{baseUrl:X.baseUrl})},{name:`syncPublicSet:${Q.set}`});if("error"in Y)console.warn(`[org-fs] public set "${Y.set}" sync failed: ${Y.error}`);else if(Y.written||Y.deleted)console.log(`[org-fs] public set "${Y.set}" synced: +${Y.written} -${Y.deleted} (=${Y.unchanged})`)}}function Cc1(){if(Cn)return;Cn=aZ0.registerWorkflow(vu8,{name:"publicSetsSyncWorkflow"}),aZ0.registerScheduled(Cn,{name:"publicSetsSyncWorkflow",crontab:Cu8,mode:Su8.ExactlyOncePerIntervalWhenActive})}async function _c1(){if(V3().length===0||!Cn)return;let $=new Date,Z=`public-sets-sync-boot:${$.toISOString().slice(0,13)}`;await aZ0.startWorkflow(Cn,{workflowID:Z})($,$)}var Cu8="4-59/10 * * * *",_c0=null,Cn=null;var vc1=D(()=>{Cz();sZ0()});import{jwtVerify as bu8,SignJWT as bc1}from"jose";import{randomBytes as xu8}from"crypto";function xc1(){if(_n)return _n;let $=E0(),Z=$.studioJwtSecret??$.betterAuthSecret;if(Z)_n=new TextEncoder().encode(Z);else console.warn("STUDIO_JWT_SECRET not set - generating random secret (not persistent)"),_n=new Uint8Array(xu8(32));return _n}async function fc1($,Z="5m"){let Q=xc1();return await new bc1($).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Z).sign(Q)}async function vc0($){try{let Z=xc1(),{payload:Q}=await bu8($,Z);return Q}catch{return}}async function NQ($,Z,Q=3600){let Y=E0(),X=Y.plansEnabled?Y.studioJwtSecret:Y.studioJwtSecret??Y.betterAuthSecret;if(!X)throw Error(Y.plansEnabled?"STUDIO_JWT_SECRET (or MESH_JWT_SECRET) is required to mint gateway JWTs when STUDIO_PLANS_ENABLED is set \u2014 BETTER_AUTH_SECRET is deliberately not a fallback, see resolve-config":"A deterministic JWT secret is required to mint gateway JWTs \u2014 set STUDIO_JWT_SECRET or BETTER_AUTH_SECRET");let J=new TextEncoder().encode(X);return await new bc1({iss:"mesh",sub:$,...Z&&{email:Z}}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+Q).sign(J)}var _n=null;var GK=D(()=>{F$()});import{createCipheriv as fu8,createDecipheriv as yu8,createHash as gu8,randomBytes as yc1}from"crypto";class FG{key;constructor($){if(Buffer.from($,"base64").length===uc1)this.key=Buffer.from($,"base64");else this.key=gu8("sha256").update($).digest()}async encrypt($){let Z=yc1(vn),Q=fu8(gc1,this.key,Z),Y=Q.update($,"utf8");Y=Buffer.concat([Y,Q.final()]);let X=Q.getAuthTag();return Buffer.concat([Z,X,Y]).toString("base64")}async decrypt($){let Z=Buffer.from($,"base64"),Q=Z.subarray(0,vn),Y=Z.subarray(vn,vn+hc1),X=Z.subarray(vn+hc1),J=yu8(gc1,this.key,Q);J.setAuthTag(Y);let G=J.update(X);return G=Buffer.concat([G,J.final()]),G.toString("utf8")}static generateKey(){return yc1(uc1).toString("base64")}}var gc1="aes-256-gcm",vn=16,hc1=16,uc1=32;var vz=()=>{};function s9(){let $=E0();if($.baseUrl)return $.baseUrl;return`http://localhost:${$.port??3000}`}function lc1(){return`http://localhost:${E0().port??3000}`}function x5(){return E0().publicUrl??s9()}var E9=D(()=>{F$()});import*as f from"zod/v4";function Ym1($){if($.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${$.params.ref.type}`)}function Xm1($){if($.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${$.params.ref.type}`)}var vD="2025-11-25",cc1="2025-03-26",bD,xD="io.modelcontextprotocol/related-task",$70="2.0",W7,mc1,dc1,dW5,hu8,uu8,bc0,UG,bn,ic1=($)=>bn.safeParse($).success,BQ,k3,S3,OQ,Z70,pc1,dH=($)=>pc1.safeParse($).success,nc1,tc1=($)=>nc1.safeParse($).success,xc0,WK=($)=>xc0.safeParse($).success,_1,fc0,og=($)=>fc0.safeParse($).success,NG,iW5,xN,lu8,Q70,cu8,xn,tg,oc1,mu8,du8,iu8,pu8,nu8,tu8,Y70,yc0=($)=>Y70.safeParse($).success,ou8,gc0,X70,rc1=($)=>X70.safeParse($).success,J70,ru8,su8,G70,au8,fn,yn,eu8,gn,fN,$l8,hn,W70,K70,H70,pW5,F70,U70,N70,sc1,ac1,ec1,hc0,$m1,un,rg,Zm1,Zl8,fD,uc0,yD,lc0,cc0,Ql8,sg,mc0,dc0,Yl8,Xl8,Jl8,Gl8,Wl8,Kl8,Hl8,Fl8,gD,ic0,Ul8,ag,pc0,nc0,tc0,Nl8,Bl8,Ol8,oc0,Dl8,rc0,sc0,Ll8,wl8,B70,eg,ln,iH,nW5,jl8,hD,ac0,Qm1,cn,El8,ec0,zl8,Pl8,Al8,Tl8,Rl8,ql8,Ml8,eZ0,Il8,Vl8,$m0,bz,mn,kl8,Sl8,Cl8,_l8,vl8,bl8,xl8,fl8,yl8,gl8,hl8,ul8,ll8,cl8,ml8,Zm0,dl8,il8,uD,pl8,nl8,tl8,O70,Qm0,ol8,rl8,Ym0,sl8,tW5,oW5,rW5,sW5,aW5,eW5,M1,Jm1;var a9=D(()=>{bD=[vD,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],W7=f.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),mc1=f.union([f.string(),f.number().int()]),dc1=f.string(),dW5=f.looseObject({ttl:f.number().optional(),pollInterval:f.number().optional()}),hu8=f.object({ttl:f.number().optional()}),uu8=f.object({taskId:f.string()}),bc0=f.looseObject({progressToken:mc1.optional(),[xD]:uu8.optional()}),UG=f.object({_meta:bc0.optional()}),bn=UG.extend({task:hu8.optional()}),BQ=f.object({method:f.string(),params:UG.loose().optional()}),k3=f.object({_meta:bc0.optional()}),S3=f.object({method:f.string(),params:k3.loose().optional()}),OQ=f.looseObject({_meta:bc0.optional()}),Z70=f.union([f.string(),f.number().int()]),pc1=f.object({jsonrpc:f.literal($70),id:Z70,...BQ.shape}).strict(),nc1=f.object({jsonrpc:f.literal($70),...S3.shape}).strict(),xc0=f.object({jsonrpc:f.literal($70),id:Z70,result:OQ}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(_1||(_1={}));fc0=f.object({jsonrpc:f.literal($70),id:Z70.optional(),error:f.object({code:f.number().int(),message:f.string(),data:f.unknown().optional()})}).strict(),NG=f.union([pc1,nc1,xc0,fc0]),iW5=f.union([xc0,fc0]),xN=OQ.strict(),lu8=k3.extend({requestId:Z70.optional(),reason:f.string().optional()}),Q70=S3.extend({method:f.literal("notifications/cancelled"),params:lu8}),cu8=f.object({src:f.string(),mimeType:f.string().optional(),sizes:f.array(f.string()).optional(),theme:f.enum(["light","dark"]).optional()}),xn=f.object({icons:f.array(cu8).optional()}),tg=f.object({name:f.string(),title:f.string().optional()}),oc1=tg.extend({...tg.shape,...xn.shape,version:f.string(),websiteUrl:f.string().optional(),description:f.string().optional()}),mu8=f.intersection(f.object({applyDefaults:f.boolean().optional()}),f.record(f.string(),f.unknown())),du8=f.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},f.intersection(f.object({form:mu8.optional(),url:W7.optional()}),f.record(f.string(),f.unknown()).optional())),iu8=f.looseObject({list:W7.optional(),cancel:W7.optional(),requests:f.looseObject({sampling:f.looseObject({createMessage:W7.optional()}).optional(),elicitation:f.looseObject({create:W7.optional()}).optional()}).optional()}),pu8=f.looseObject({list:W7.optional(),cancel:W7.optional(),requests:f.looseObject({tools:f.looseObject({call:W7.optional()}).optional()}).optional()}),nu8=f.object({experimental:f.record(f.string(),W7).optional(),sampling:f.object({context:W7.optional(),tools:W7.optional()}).optional(),elicitation:du8.optional(),roots:f.object({listChanged:f.boolean().optional()}).optional(),tasks:iu8.optional(),extensions:f.record(f.string(),W7).optional()}),tu8=UG.extend({protocolVersion:f.string(),capabilities:nu8,clientInfo:oc1}),Y70=BQ.extend({method:f.literal("initialize"),params:tu8}),ou8=f.object({experimental:f.record(f.string(),W7).optional(),logging:W7.optional(),completions:W7.optional(),prompts:f.object({listChanged:f.boolean().optional()}).optional(),resources:f.object({subscribe:f.boolean().optional(),listChanged:f.boolean().optional()}).optional(),tools:f.object({listChanged:f.boolean().optional()}).optional(),tasks:pu8.optional(),extensions:f.record(f.string(),W7).optional()}),gc0=OQ.extend({protocolVersion:f.string(),capabilities:ou8,serverInfo:oc1,instructions:f.string().optional()}),X70=S3.extend({method:f.literal("notifications/initialized"),params:k3.optional()}),J70=BQ.extend({method:f.literal("ping"),params:UG.optional()}),ru8=f.object({progress:f.number(),total:f.optional(f.number()),message:f.optional(f.string())}),su8=f.object({...k3.shape,...ru8.shape,progressToken:mc1}),G70=S3.extend({method:f.literal("notifications/progress"),params:su8}),au8=UG.extend({cursor:dc1.optional()}),fn=BQ.extend({params:au8.optional()}),yn=OQ.extend({nextCursor:dc1.optional()}),eu8=f.enum(["working","input_required","completed","failed","cancelled"]),gn=f.object({taskId:f.string(),status:eu8,ttl:f.union([f.number(),f.null()]),createdAt:f.string(),lastUpdatedAt:f.string(),pollInterval:f.optional(f.number()),statusMessage:f.optional(f.string())}),fN=OQ.extend({task:gn}),$l8=k3.merge(gn),hn=S3.extend({method:f.literal("notifications/tasks/status"),params:$l8}),W70=BQ.extend({method:f.literal("tasks/get"),params:UG.extend({taskId:f.string()})}),K70=OQ.merge(gn),H70=BQ.extend({method:f.literal("tasks/result"),params:UG.extend({taskId:f.string()})}),pW5=OQ.loose(),F70=fn.extend({method:f.literal("tasks/list")}),U70=yn.extend({tasks:f.array(gn)}),N70=BQ.extend({method:f.literal("tasks/cancel"),params:UG.extend({taskId:f.string()})}),sc1=OQ.merge(gn),ac1=f.object({uri:f.string(),mimeType:f.optional(f.string()),_meta:f.record(f.string(),f.unknown()).optional()}),ec1=ac1.extend({text:f.string()}),hc0=f.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),$m1=ac1.extend({blob:hc0}),un=f.enum(["user","assistant"]),rg=f.object({audience:f.array(un).optional(),priority:f.number().min(0).max(1).optional(),lastModified:f.iso.datetime({offset:!0}).optional()}),Zm1=f.object({...tg.shape,...xn.shape,uri:f.string(),description:f.optional(f.string()),mimeType:f.optional(f.string()),size:f.optional(f.number()),annotations:rg.optional(),_meta:f.optional(f.looseObject({}))}),Zl8=f.object({...tg.shape,...xn.shape,uriTemplate:f.string(),description:f.optional(f.string()),mimeType:f.optional(f.string()),annotations:rg.optional(),_meta:f.optional(f.looseObject({}))}),fD=fn.extend({method:f.literal("resources/list")}),uc0=yn.extend({resources:f.array(Zm1)}),yD=fn.extend({method:f.literal("resources/templates/list")}),lc0=yn.extend({resourceTemplates:f.array(Zl8)}),cc0=UG.extend({uri:f.string()}),Ql8=cc0,sg=BQ.extend({method:f.literal("resources/read"),params:Ql8}),mc0=OQ.extend({contents:f.array(f.union([ec1,$m1]))}),dc0=S3.extend({method:f.literal("notifications/resources/list_changed"),params:k3.optional()}),Yl8=cc0,Xl8=BQ.extend({method:f.literal("resources/subscribe"),params:Yl8}),Jl8=cc0,Gl8=BQ.extend({method:f.literal("resources/unsubscribe"),params:Jl8}),Wl8=k3.extend({uri:f.string()}),Kl8=S3.extend({method:f.literal("notifications/resources/updated"),params:Wl8}),Hl8=f.object({name:f.string(),description:f.optional(f.string()),required:f.optional(f.boolean())}),Fl8=f.object({...tg.shape,...xn.shape,description:f.optional(f.string()),arguments:f.optional(f.array(Hl8)),_meta:f.optional(f.looseObject({}))}),gD=fn.extend({method:f.literal("prompts/list")}),ic0=yn.extend({prompts:f.array(Fl8)}),Ul8=UG.extend({name:f.string(),arguments:f.record(f.string(),f.string()).optional()}),ag=BQ.extend({method:f.literal("prompts/get"),params:Ul8}),pc0=f.object({type:f.literal("text"),text:f.string(),annotations:rg.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),nc0=f.object({type:f.literal("image"),data:hc0,mimeType:f.string(),annotations:rg.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),tc0=f.object({type:f.literal("audio"),data:hc0,mimeType:f.string(),annotations:rg.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),Nl8=f.object({type:f.literal("tool_use"),name:f.string(),id:f.string(),input:f.record(f.string(),f.unknown()),_meta:f.record(f.string(),f.unknown()).optional()}),Bl8=f.object({type:f.literal("resource"),resource:f.union([ec1,$m1]),annotations:rg.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),Ol8=Zm1.extend({type:f.literal("resource_link")}),oc0=f.union([pc0,nc0,tc0,Ol8,Bl8]),Dl8=f.object({role:un,content:oc0}),rc0=OQ.extend({description:f.string().optional(),messages:f.array(Dl8)}),sc0=S3.extend({method:f.literal("notifications/prompts/list_changed"),params:k3.optional()}),Ll8=f.object({title:f.string().optional(),readOnlyHint:f.boolean().optional(),destructiveHint:f.boolean().optional(),idempotentHint:f.boolean().optional(),openWorldHint:f.boolean().optional()}),wl8=f.object({taskSupport:f.enum(["required","optional","forbidden"]).optional()}),B70=f.object({...tg.shape,...xn.shape,description:f.string().optional(),inputSchema:f.object({type:f.literal("object"),properties:f.record(f.string(),W7).optional(),required:f.array(f.string()).optional()}).catchall(f.unknown()),outputSchema:f.object({type:f.literal("object"),properties:f.record(f.string(),W7).optional(),required:f.array(f.string()).optional()}).catchall(f.unknown()).optional(),annotations:Ll8.optional(),execution:wl8.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),eg=fn.extend({method:f.literal("tools/list")}),ln=yn.extend({tools:f.array(B70)}),iH=OQ.extend({content:f.array(oc0).default([]),structuredContent:f.record(f.string(),f.unknown()).optional(),isError:f.boolean().optional()}),nW5=iH.or(OQ.extend({toolResult:f.unknown()})),jl8=bn.extend({name:f.string(),arguments:f.record(f.string(),f.unknown()).optional()}),hD=BQ.extend({method:f.literal("tools/call"),params:jl8}),ac0=S3.extend({method:f.literal("notifications/tools/list_changed"),params:k3.optional()}),Qm1=f.object({autoRefresh:f.boolean().default(!0),debounceMs:f.number().int().nonnegative().default(300)}),cn=f.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),El8=UG.extend({level:cn}),ec0=BQ.extend({method:f.literal("logging/setLevel"),params:El8}),zl8=k3.extend({level:cn,logger:f.string().optional(),data:f.unknown()}),Pl8=S3.extend({method:f.literal("notifications/message"),params:zl8}),Al8=f.object({name:f.string().optional()}),Tl8=f.object({hints:f.array(Al8).optional(),costPriority:f.number().min(0).max(1).optional(),speedPriority:f.number().min(0).max(1).optional(),intelligencePriority:f.number().min(0).max(1).optional()}),Rl8=f.object({mode:f.enum(["auto","required","none"]).optional()}),ql8=f.object({type:f.literal("tool_result"),toolUseId:f.string().describe("The unique identifier for the corresponding tool call."),content:f.array(oc0).default([]),structuredContent:f.object({}).loose().optional(),isError:f.boolean().optional(),_meta:f.record(f.string(),f.unknown()).optional()}),Ml8=f.discriminatedUnion("type",[pc0,nc0,tc0]),eZ0=f.discriminatedUnion("type",[pc0,nc0,tc0,Nl8,ql8]),Il8=f.object({role:un,content:f.union([eZ0,f.array(eZ0)]),_meta:f.record(f.string(),f.unknown()).optional()}),Vl8=bn.extend({messages:f.array(Il8),modelPreferences:Tl8.optional(),systemPrompt:f.string().optional(),includeContext:f.enum(["none","thisServer","allServers"]).optional(),temperature:f.number().optional(),maxTokens:f.number().int(),stopSequences:f.array(f.string()).optional(),metadata:W7.optional(),tools:f.array(B70).optional(),toolChoice:Rl8.optional()}),$m0=BQ.extend({method:f.literal("sampling/createMessage"),params:Vl8}),bz=OQ.extend({model:f.string(),stopReason:f.optional(f.enum(["endTurn","stopSequence","maxTokens"]).or(f.string())),role:un,content:Ml8}),mn=OQ.extend({model:f.string(),stopReason:f.optional(f.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(f.string())),role:un,content:f.union([eZ0,f.array(eZ0)])}),kl8=f.object({type:f.literal("boolean"),title:f.string().optional(),description:f.string().optional(),default:f.boolean().optional()}),Sl8=f.object({type:f.literal("string"),title:f.string().optional(),description:f.string().optional(),minLength:f.number().optional(),maxLength:f.number().optional(),format:f.enum(["email","uri","date","date-time"]).optional(),default:f.string().optional()}),Cl8=f.object({type:f.enum(["number","integer"]),title:f.string().optional(),description:f.string().optional(),minimum:f.number().optional(),maximum:f.number().optional(),default:f.number().optional()}),_l8=f.object({type:f.literal("string"),title:f.string().optional(),description:f.string().optional(),enum:f.array(f.string()),default:f.string().optional()}),vl8=f.object({type:f.literal("string"),title:f.string().optional(),description:f.string().optional(),oneOf:f.array(f.object({const:f.string(),title:f.string()})),default:f.string().optional()}),bl8=f.object({type:f.literal("string"),title:f.string().optional(),description:f.string().optional(),enum:f.array(f.string()),enumNames:f.array(f.string()).optional(),default:f.string().optional()}),xl8=f.union([_l8,vl8]),fl8=f.object({type:f.literal("array"),title:f.string().optional(),description:f.string().optional(),minItems:f.number().optional(),maxItems:f.number().optional(),items:f.object({type:f.literal("string"),enum:f.array(f.string())}),default:f.array(f.string()).optional()}),yl8=f.object({type:f.literal("array"),title:f.string().optional(),description:f.string().optional(),minItems:f.number().optional(),maxItems:f.number().optional(),items:f.object({anyOf:f.array(f.object({const:f.string(),title:f.string()}))}),default:f.array(f.string()).optional()}),gl8=f.union([fl8,yl8]),hl8=f.union([bl8,xl8,gl8]),ul8=f.union([hl8,kl8,Sl8,Cl8]),ll8=bn.extend({mode:f.literal("form").optional(),message:f.string(),requestedSchema:f.object({type:f.literal("object"),properties:f.record(f.string(),ul8),required:f.array(f.string()).optional()})}),cl8=bn.extend({mode:f.literal("url"),message:f.string(),elicitationId:f.string(),url:f.string().url()}),ml8=f.union([ll8,cl8]),Zm0=BQ.extend({method:f.literal("elicitation/create"),params:ml8}),dl8=k3.extend({elicitationId:f.string()}),il8=S3.extend({method:f.literal("notifications/elicitation/complete"),params:dl8}),uD=OQ.extend({action:f.enum(["accept","decline","cancel"]),content:f.preprocess(($)=>$===null?void 0:$,f.record(f.string(),f.union([f.string(),f.number(),f.boolean(),f.array(f.string())])).optional())}),pl8=f.object({type:f.literal("ref/resource"),uri:f.string()}),nl8=f.object({type:f.literal("ref/prompt"),name:f.string()}),tl8=UG.extend({ref:f.union([nl8,pl8]),argument:f.object({name:f.string(),value:f.string()}),context:f.object({arguments:f.record(f.string(),f.string()).optional()}).optional()}),O70=BQ.extend({method:f.literal("completion/complete"),params:tl8});Qm0=OQ.extend({completion:f.looseObject({values:f.array(f.string()).max(100),total:f.optional(f.number().int()),hasMore:f.optional(f.boolean())})}),ol8=f.object({uri:f.string().startsWith("file://"),name:f.string().optional(),_meta:f.record(f.string(),f.unknown()).optional()}),rl8=BQ.extend({method:f.literal("roots/list"),params:UG.optional()}),Ym0=OQ.extend({roots:f.array(ol8)}),sl8=S3.extend({method:f.literal("notifications/roots/list_changed"),params:k3.optional()}),tW5=f.union([J70,Y70,O70,ec0,ag,gD,fD,yD,sg,Xl8,Gl8,hD,eg,W70,H70,F70,N70]),oW5=f.union([Q70,G70,X70,sl8,hn]),rW5=f.union([xN,bz,mn,uD,Ym0,K70,U70,fN]),sW5=f.union([J70,$m0,Zm0,rl8,W70,H70,F70,N70]),aW5=f.union([Q70,G70,Pl8,Kl8,dc0,ac0,sc0,hn,il8]),eW5=f.union([xN,gc0,Qm0,rc0,ic0,uc0,lc0,mc0,iH,ln,K70,U70,fN]);M1=class M1 extends Error{constructor($,Z,Q){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,Z,Q){if($===_1.UrlElicitationRequired&&Q){let Y=Q;if(Y.elicitations)return new Jm1(Y.elicitations,Z)}return new M1($,Z,Q)}};Jm1=class Jm1 extends M1{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(_1.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});import{z as o$}from"zod";function Km1($){return o$.record(o$.string(),o$.unknown()).nullable().refine((Z)=>Z===null||JSON.stringify(Z).length<=Wm1,{message:`${$} must serialize to at most ${Wm1} bytes`})}function pH($){return $!==null&&$!==void 0&&"command"in $}function $h($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function Zh($){return`virtual://${$}`}var Hm1,Gm1,al8,el8,$c8,Wm1=262144,eQ,D70,L70;var Fm1=D(()=>{a9();Hm1=o$.object({authorizationEndpoint:o$.string().url(),tokenEndpoint:o$.string().url(),introspectionEndpoint:o$.string().url().optional(),clientId:o$.string(),clientSecret:o$.string().optional(),scopes:o$.array(o$.string()),grantType:o$.enum(["authorization_code","client_credentials"])}),Gm1=o$.object({type:o$.literal("object"),properties:o$.record(o$.string(),o$.unknown()).optional(),required:o$.array(o$.string()).optional()}).catchall(o$.unknown()),al8=B70.extend({inputSchema:Gm1,outputSchema:Gm1.optional()}),el8=o$.object({headers:o$.record(o$.string(),o$.string()).optional()}),$c8=o$.object({command:o$.string().describe("Command to run (e.g., 'npx', 'node')"),args:o$.array(o$.string()).optional().describe("Command arguments"),cwd:o$.string().optional().describe("Working directory"),envVars:o$.record(o$.string(),o$.string()).optional().describe("Environment variables (encrypted in storage)")});eQ=o$.object({id:o$.string().describe("Unique identifier for the connection"),title:o$.string().describe("Human-readable name for the connection"),created_at:o$.string().describe("When the connection was created"),updated_at:o$.string().describe("When the connection was last updated"),created_by:o$.string().describe("User ID who created the connection"),updated_by:o$.string().optional().describe("User ID who last updated the connection"),organization_id:o$.string().describe("Organization ID this connection belongs to"),description:o$.string().nullable().describe("Description of the connection"),icon:o$.string().nullable().describe("Icon URL for the connection"),app_name:o$.string().nullable().describe("Associated app name"),app_id:o$.string().nullable().describe("Associated app ID"),slug:o$.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:o$.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:o$.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:o$.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:o$.union([$c8,el8]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:Hm1.nullable().describe("OAuth configuration"),configuration_state:Km1("configuration_state").describe("Configuration state (decrypted)"),configuration_scopes:o$.array(o$.string()).nullable().optional().describe("Configuration scopes"),metadata:Km1("metadata").describe("Additional metadata (includes repository info)"),tools:o$.array(al8).nullable().describe("Discovered tools from MCP"),bindings:o$.array(o$.string()).nullable().describe("Detected bindings"),status:o$.enum(["active","inactive","error"]).describe("Current status")}),D70=eQ.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}).extend({icon:o$.string().nullish()}),L70=eQ.partial()});import{z as S0}from"zod";function Gm0($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let Q=$?.homeTile;return Q?[Q]:[]}function yN($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,Q={};for(let[Y,X]of Object.entries(Z)){if(!X||typeof X!=="object")continue;if(Y!=="agent-sandbox"&&Y!=="local-api")continue;try{Q[Y]=Wm0.parse(X)}catch{}}return Q}function Km0($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[Q,Y]of Object.entries($)){if(!Y||typeof Y!=="object"||Array.isArray(Y))continue;let X={};for(let[J,G]of Object.entries(Y)){let W=yN(G);if(Object.keys(W).length>0)X[J]=W}if(Object.keys(X).length>0)Z[Q]=X}return Z}var Bm1,Xm0=500,Om1=200,Zc8=200,Qc8=20,Yc8=50,Xc8=100,Jc8=20,Gc8=100,Dm1=50,Wc8=100,Kc8=8192,Lm1,Hc8,wm1,Jm0,Fc8,Uc8,jm1,Um1,Nc8,w70,Nm1,Bc8,Oc8,Dc8,Lc8,wc8,Wm0,Em1,jc8,Ec8,zc8,Pc8,Ac8,Tc8,Rc8,zm1,qc8,Hm0,$Y,Fm0,j70,E70;var Pm1=D(()=>{Bm1=S0.object({connection_id:S0.string().describe("Connection ID"),selected_tools:S0.array(S0.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:S0.array(S0.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:S0.array(S0.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),Lm1=Bm1.extend({selected_tools:S0.array(S0.string()).max(Xm0).nullable().optional().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:S0.array(S0.string()).max(Xm0).nullable().optional().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:S0.array(S0.string()).max(Xm0).nullable().optional().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),Hc8=S0.object({connectionId:S0.string(),toolName:S0.string(),label:S0.string(),icon:S0.string().nullable().optional()}),wm1=S0.object({id:S0.string().describe("Stable id; used as React key and ?tab= value"),title:S0.string().describe("Tab label"),icon:S0.string().optional().describe("Optional lucide icon name"),view:S0.object({type:S0.literal("ext-app"),appId:S0.string(),args:S0.record(S0.string(),S0.unknown()).optional()})}),Jm0=S0.enum(["overview","reports","board","site-editor","assets","hosting","e2e","analytics","cdn","automations","experiments"]),Fc8=S0.enum(["on","off"]),Uc8=S0.enum(["on","off","manual","auto"]),jm1=S0.object({defaultMainView:S0.object({type:S0.string(),id:S0.string().optional(),toolName:S0.string().optional()}).nullable().optional(),chatDefaultOpen:S0.boolean().nullable().optional(),cmsDefaultOpen:S0.boolean().nullable().optional(),cms:Uc8.nullable().optional().describe("How this agent offers content editing. Absent means on; the retired `manual` / `auto` read as on too."),sidebarViews:S0.array(Jm0).max(10).nullable().optional().describe("Deprecated layout-scoped sidebar selections. Read only as a fallback when metadata.sidebarViews is absent."),tabs:S0.array(wm1).max(Jc8).optional()}),Um1=S0.object({tileId:S0.string().optional(),connectionId:S0.string().optional().describe("Connection that owns the resource \u2014 the host opens a direct MCP client to this connection so the iframe can call tools by their bare names."),resourceUri:S0.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),toolName:S0.string().optional().describe("Tool name \u2014 identifies which tool's inputSchema to display when editing tile props."),toolInput:S0.record(S0.string(),S0.unknown()).optional().describe("User-configured input props passed to MCPAppRenderer when rendering the tile."),minHeight:S0.number().int().positive().optional(),maxHeight:S0.number().int().positive().optional()}),Nc8=S0.object({banner:S0.string().nullable().optional(),bannerColor:S0.string().nullable().optional(),icon:S0.string().nullable().optional(),themeColor:S0.string().nullable().optional(),pinnedViews:S0.array(Hc8).max(Xc8).nullable().optional(),layout:jm1.nullable().optional(),homeTile:Um1.nullable().optional(),homeTiles:S0.array(Um1).max(Qc8).nullable().optional(),homePrompts:S0.array(S0.string()).max(Yc8).nullable().optional()});w70=/^[A-Za-z_][A-Za-z0-9_]*$/,Nm1=S0.string().min(1).regex(w70,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),Bc8=S0.discriminatedUnion("kind",[S0.object({key:Nm1,kind:S0.literal("literal"),value:S0.string().max(Kc8)}),S0.object({key:Nm1,kind:S0.literal("secret"),secretId:S0.string().min(1)})]),Oc8=S0.object({selected:S0.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:S0.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:S0.string().nullable().optional().describe("Optional path (relative to repo root) to the directory containing package.json. Null/absent means repo root. Forwarded as `application.packageManager.path` to the daemon config."),env:S0.array(Bc8).max(Wc8).nullable().optional().describe("Env vars injected on every SANDBOX_START. Literal entries inline their value; secret entries store a secretId that Studio resolves via the credential vault before posting /_sandbox/config.")}),Dc8=S0.object({url:S0.string().describe("GitHub repository URL"),owner:S0.string().describe("Repository owner"),name:S0.string().describe("Repository name"),installationId:S0.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:S0.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials."),repositoryId:S0.string().optional().describe("First-class repository (REPOSITORY_LINK) backing this binding. When set, credentials come from the repository's git provider account rather than connectionId.")}),Lc8=S0.enum(["agent-sandbox","local-api"]),wc8={sandboxHandle:S0.string().describe("Provider-specific handle"),previewUrl:S0.string().nullable().describe("URL where the sandbox's iframe-proxied UI is served, or null when the sandbox has no dev server (blank / tool sandboxes)."),sandboxApiUrl:S0.string().nullable().optional().describe("Direct sandbox API URL for runtimes that expose one. Equal to previewUrl for local-api; null/absent for AgentSandbox, which routes control traffic through hosted Studio."),createdAt:S0.number().optional().describe("Epoch ms the entry was first written by SANDBOX_START. Used by the booting overlay to show a stable elapsed timer that survives browser reloads. Optional for backward compatibility with entries written before this field existed."),startedWith:S0.object({packageManager:S0.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:S0.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:S0.string().nullable().optional().describe("metadata.runtime.path at the time of SANDBOX_START")}).optional().describe("Snapshot of metadata.runtime fields (selected/port/path) used at SANDBOX_START. The Preview tab compares the live metadata.runtime against this to decide if a restart is required to apply changes.")},Wm0=S0.object(wc8);Em1=S0.record(S0.string().describe("userId"),S0.record(S0.string().describe("branch"),S0.partialRecord(Lc8,Wm0)));jc8=S0.object({id:S0.string().describe("Stable identifier for this knowledge file"),name:S0.string().describe("File name shown in the UI"),kind:S0.enum(["file","skill"]).optional().describe("'file' (a single document) or 'skill' (a Claude Code skill folder containing SKILL.md). Defaults to 'file'."),volume:S0.string().describe("Org filesystem (Library) volume the file lives in"),path:S0.string().describe("Path within the volume"),url:S0.string().describe("Same-origin URL to read the file (display/download)"),contentType:S0.string().nullable().optional().describe("MIME type, used to decide whether to inline the content"),size:S0.number().nullable().optional().describe("File size in bytes"),addedAt:S0.string().describe("ISO timestamp when the file was attached")}),Ec8=S0.array(jc8).max(Gc8).nullable().optional().describe("Files attached to the agent as reference knowledge. Surfaced in the system prompt: small text documents are inlined, others are listed as retrievable references."),zc8=S0.enum(["smart","code-review","open"]),Pc8=zc8.nullable().optional().describe("Controls when this code agent's changes may be published directly vs. requiring PR review. 'smart' (default) uses AI to judge per change; 'code-review' requires review for any code; 'open' allows direct publish always."),Ac8=S0.boolean().nullable().optional().describe("Enable Fast Preview (sandbox-less): render the draft instantly on the preview server's own page via a ?__draft pointer, with reads/writes served by the decofile API against GitHub. Requires previewServerUrl (or legacy productionUrl) to be set to take effect."),Tc8=S0.boolean().nullable().optional().describe("EXPERIMENTAL: with Fast Preview on, refresh content edits via an in-place /live/previews render (no commit, no reload) instead of a commit + re-navigation. Deco-runtime preview targets only. Requires fastPreview."),Rc8=S0.string().nullable().optional().describe("Preview server URL \u2014 the deployment the CMS preview renders against (often the live site, e.g. https://acme.com). Painted in the preview iframe, and the render target for Fast Preview drafts. Supersedes the legacy productionUrl key."),zm1=S0.object({branch:S0.string().describe("Git branch backing this release"),name:S0.string().describe('User-facing name, e.g. "Black Friday 2026"'),color:S0.string().describe("Dot color token shown in the version switcher"),createdBy:S0.string().optional().describe("User ID who created the release"),createdAt:S0.string().optional().describe("ISO 8601 creation timestamp")}),qc8=S0.array(zm1).max(Dm1).nullable().optional().describe("Curated list of named, branch-backed releases shown in the version switcher. The base branch ('No ar') is derived, not stored here."),Hm0={instructions:S0.string().nullable().optional().describe("Instructions also used as system prompt"),subAgents:S0.array(S0.string()).max(Zc8).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:S0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:Nc8.nullable().optional().describe("UI customization settings"),sidebarViews:S0.array(Jm0).max(10).nullable().optional().describe("Project views selected for the sidebar. Interpret as an exact list when sidebarViewsVersion is 1; unversioned values use legacy native-only semantics. Runtime presence gates still apply."),sidebarViewsVersion:S0.literal(1).optional().describe("Version 1 marks metadata.sidebarViews as an exact list that can disable legacy default rows."),githubRepo:Dc8.nullable().optional().describe("Linked GitHub repository"),runtime:Oc8.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),knowledge:Ec8,siteSlug:S0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:Pc8,previewServerUrl:Rc8,productionUrl:S0.string().nullable().optional().describe("Legacy key for previewServerUrl \u2014 still read as a fallback. New writes use previewServerUrl."),fieldDescriptionTooltips:S0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title."),fastPreview:Ac8,releases:qc8,fastPreviewInPlace:Tc8},$Y=S0.object({id:S0.string().describe("Unique identifier"),title:S0.string().describe("Human-readable name"),description:S0.string().nullable().describe("Description"),icon:S0.string().nullable().describe("Icon URL"),created_at:S0.string().describe("Creation timestamp"),updated_at:S0.string().describe("Last update timestamp"),created_by:S0.string().describe("User ID who created this item"),updated_by:S0.string().optional().describe("User ID who last updated this item"),organization_id:S0.string().describe("Organization ID this item belongs to"),status:S0.enum(["active","inactive"]).describe("Current status"),pinned:S0.boolean().describe("Whether this space is pinned to the sidebar"),metadata:S0.object(Hm0).extend({instructions:S0.string().nullable().describe("Instructions also used as system prompt"),sandboxMap:Em1.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }")}).loose().describe("Metadata"),connections:S0.array(Bm1).describe("Connections with their selected tools, resources, and prompts")}),Fm0=S0.object({title:S0.string().min(1).max(120).describe("Short label shown on the chip"),description:S0.string().max(280).optional().describe("One-line subtitle shown under the title"),text:S0.string().min(1).max(4000).describe("The message sent to the agent when the prompt is clicked")}),j70=S0.object({title:S0.string().min(1).max(255).describe("Name for the virtual MCP"),description:S0.string().max(500).nullable().optional().describe("Optional description"),icon:S0.string().nullish().describe("Optional icon URL"),status:S0.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:S0.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:S0.object(Hm0).loose().superRefine(($,Z)=>{if("sandboxMap"in $)Z.addIssue({code:"custom",path:["sandboxMap"],message:"sandboxMap is managed by the sandbox lifecycle"})}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:S0.array(Lm1).max(Om1).describe("Connections to include/exclude (can be empty for exclusion mode)"),prompts:S0.array(Fm0).max(20).optional().describe("Optional kickstart prompts to seed on the agent. Each becomes a clickable conversation starter (icebreaker) on the agent. Author them from the agent's role and the tools it will have so they're coherent and immediately useful.")}),E70=S0.object({title:S0.string().min(1).max(255).optional().describe("New name"),description:S0.string().max(500).nullable().optional().describe("New description (null to clear)"),icon:S0.string().nullish().describe("New icon URL"),status:S0.enum(["active","inactive"]).optional().describe("New status"),pinned:S0.boolean().optional().describe("Pin/unpin from sidebar"),metadata:S0.object(Hm0).loose().superRefine(($,Z)=>{if("sandboxMap"in $)Z.addIssue({code:"custom",path:["sandboxMap"],message:"sandboxMap is managed by the sandbox lifecycle"})}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:S0.array(Lm1).max(Om1).optional().describe("New connections (replaces existing)"),prompts:S0.array(Fm0).max(20).optional().describe("Replace the agent's kickstart prompts with this full set. Omit to leave them unchanged; pass an empty array to remove all. Each becomes a clickable conversation starter (icebreaker).")})});function xz($){return Mc8.has($)}var wZ,Mc8,z70;var Am1=D(()=>{wZ=["deco","anthropic","openrouter","llmapi","google","openai-compatible"],Mc8=new Set(wZ);z70=[...wZ,"claude-code","codex"]});function Um0($,Z){return{id:crypto.randomUUID(),type:dn.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function P70($,Z){return{id:crypto.randomUUID(),type:dn.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function nH($,Z,Q){return{id:crypto.randomUUID(),type:dn.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...Q?.messageId!==void 0&&{message_id:Q.messageId},...Q?.virtualMcpId!==void 0&&{virtual_mcp_id:Q.virtualMcpId},...Q?.createdBy!==void 0&&{created_by:Q.createdBy},...Q?.triggerId!==void 0&&{trigger_id:Q.triggerId},...Q?.title!==void 0&&{title:Q.title},...Q?.branch!==void 0&&{branch:Q.branch},...Q?.harnessId!==void 0&&{harness_id:Q.harnessId},...Q?.createdAt!==void 0&&{created_at:Q.createdAt},...Q?.updatedAt!==void 0&&{updated_at:Q.updatedAt},...Q?.metadata!==void 0&&{metadata:Q.metadata}},time:new Date().toISOString()}}var Tm1,Ic8,dn,Vc8;var Rm1=D(()=>{Tm1=["in_progress","requires_action","failed","completed"],Ic8=[...Tm1,"expired"],dn={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},Vc8=Object.values(dn)});var A70=D(()=>{Fm1();Pm1();Am1();Rm1()});var tH=D(()=>{A70()});import{lookup as kc8}from"dns/promises";function pn($,Z){if($===10)return!0;if($===172&&Z!==void 0&&Z>=16&&Z<=31)return!0;if($===192&&Z===168)return!0;if($===127)return!0;if($===169&&Z===254)return!0;if($===0)return!0;if($===100&&Z!==void 0&&Z>=64&&Z<=127)return!0;return!1}function Nm0($){let Z=Number.parseInt($.padStart(4,"0"),16);return[Z>>8,Z&255]}function qm1($){let Z=$.split(":").filter((Q)=>Q.length>0);if($.startsWith("2002:")&&Z.length>=2){let[Q,Y]=Nm0(Z[1]);if(pn(Q,Y))return!0}if($.startsWith("64:ff9b::")&&Z.length>=4){let[Q,Y]=Nm0(Z[Z.length-2]);if(pn(Q,Y))return!0}if($.startsWith("::")&&Z.length===2){let[Q,Y]=Nm0(Z[0]);if(pn(Q,Y))return!0}return!1}function T70($){try{let Q=new URL($).hostname.toLowerCase();if(Q==="localhost"||Q==="0.0.0.0"||Q.endsWith(".local")||Q.endsWith(".internal")||Q.endsWith(".localhost"))return!0;let Y=Q.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(Y){let[,X,J]=Y.map(Number);if(pn(X,J))return!0}if(Q.startsWith("[")&&Q.endsWith("]")){let X=Q.slice(1,-1).toLowerCase();if(X==="::1"||X==="::")return!0;if(X.startsWith("::ffff:"))return!0;if(X.startsWith("fc")||X.startsWith("fd"))return!0;if(X.startsWith("fe80"))return!0;if(X.startsWith("100:"))return!0;if(X.startsWith("::1"))return!0;if(qm1(X))return!0}return!1}catch{return!0}}function Sc8($){let Z=$.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(Z){let[,Y,X]=Z.map(Number);return pn(Y,X)}let Q=$.toLowerCase();if(Q==="::1"||Q==="::")return!0;if(Q.startsWith("::ffff:"))return!0;if(Q.startsWith("fc")||Q.startsWith("fd"))return!0;if(Q.startsWith("fe80"))return!0;if(Q.startsWith("100:"))return!0;return qm1(Q)}async function Cc8($,Z=async(Q)=>(await kc8(Q,{all:!0})).map((Y)=>Y.address)){try{let Q=await Z($);return Q.length===0||Q.some(Sc8)}catch{return!0}}async function fz($){if(T70($))return"URLs targeting private networks are not allowed";let Q=new URL($).hostname;if(/^\d+\.\d+\.\d+\.\d+$/.test(Q)||Q.startsWith("[")&&Q.endsWith("]"))return null;try{return await _c8(Cc8(Q),5000,"DNS resolution timeout")?"URLs targeting private networks are not allowed":null}catch{return"URLs targeting private networks are not allowed"}}function _c8($,Z,Q){let Y,X=new Promise((J,G)=>{Y=setTimeout(()=>G(Error(Q)),Z)});return Promise.race([$,X]).finally(()=>clearTimeout(Y))}function yz($=fetch){return async(Z,Q)=>{let Y=await $(Z,{...Q,redirect:"manual"});if(Y.status>=300&&Y.status<400)throw Error("Refusing to follow a redirect from the remote server");return Y}}var nn=()=>{};var Mm1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as Im1}from"crypto";function bc8($){if(!gz||gz.length<$)gz=Buffer.allocUnsafe($*vc8),Im1.getRandomValues(gz),Qh=0;else if(Qh+$>gz.length)Im1.getRandomValues(gz),Qh=0;Qh+=$}function R70($=21){bc8($|=0);let Z="";for(let Q=Qh-$;Q<Qh;Q++)Z+=Mm1[gz[Q]&63];return Z}var vc8=128,gz,Qh;var Bm0=()=>{};function a8($){return`${$}_${R70()}`}var ZY=D(()=>{Bm0()});function km1($,Z){return{id:y4.SELF(Z),title:"Deco CMS",description:"The MCP for the CMS API",connection_type:"HTTP",connection_url:`${$}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}function Sm1($,Z){return{id:y4.DEV_ASSETS(Z),title:"Local Files",description:"Local file storage for development. Files are stored in /data/assets/.",connection_type:"HTTP",connection_url:`${$}/mcp/dev-assets`,icon:"https://api.iconify.design/lucide:folder.svg?color=%23888",app_name:"@deco/dev-assets-mcp",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isFixed:!0,devOnly:!0,type:"dev-assets"}}}function C3($){return{is(Z){if(!Z)return null;if(!Z.startsWith($))return null;return Z.slice($.length)||null},get(Z){return`${$}${Z}`}}}function Cm1($){return{id:$.id,organization_id:$.organizationId,title:$.title,description:$.description,icon:$.icon,status:"active",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),created_by:"system",updated_by:void 0,metadata:{instructions:$.instructions??null,...$.ui?{ui:$.ui}:{}},pinned:!1,connections:[]}}function Dm0($){return Cm1({id:uz($),organizationId:$,title:"Super Agent",description:"Default agent that aggregates all organization connections",icon:xc8,ui:{layout:{defaultMainView:{type:"overview"},chatDefaultOpen:!0}}})}function fm1($){return Cm1({id:yc8($),organizationId:$,title:"Brand context setup",description:"Guided onboarding agent that extracts brand context from a website URL.",icon:"https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",instructions:gc8})}function hm1($,Z,Q="https://reports.decocms.com/api/v2/mcp"){return{id:y4.REPORTS($),title:"Store Report",description:"Your store's report and diagnostics",connection_type:"HTTP",connection_url:Q,icon:"https://github.com/decocms.png",app_name:"commerce-discovery",app_id:null,connection_token:Z,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!1,type:"commerce-discovery"}}}function um1($,Z=y4.REPORTS($)){return{title:"Report Agent",description:"Ask anything about your store's report",icon:"https://github.com/decocms.png",status:"active",pinned:!0,metadata:{type:"commerce-discovery",isDefault:!1,ui:{pinnedViews:[{connectionId:Z,toolName:"get_my_diagnostic",label:"Report",icon:"https://github.com/decocms.png"}],layout:{defaultMainView:{type:"ext-apps",id:Z,toolName:"get_my_diagnostic"},chatDefaultOpen:!0}}},connections:[{connection_id:Z,selected_tools:null,selected_resources:null,selected_prompts:null}]}}function lm1($){if(!$)return!1;return Object.values(hz).some((Z)=>Z.is($)!==null)}function cm1($){let Z=Dm0($);return{...Z,id:Z.id,connection_type:"VIRTUAL",connection_url:`virtual://${Z.id}`,app_name:"decopilot",app_id:"decopilot",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"decopilot"},tools:[],bindings:[]}}var y4,Vm1="https://reports.decocms.com/api/v2/mcp",q70="get_my_diagnostic",_m1,DQ,uz,vm1,bm1,Om0,xc8="https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",fc8="#6366f1",MK5,xm1,M70,yc8,gc8,ym1,IK5,VK5,gm1,kK5,Yh,hz,_3,Lm0,SK5;var mm1=D(()=>{y4={SELF:($)=>`${$}_self`,REGISTRY:($)=>`${$}_registry`,COMMUNITY_REGISTRY:($)=>`${$}_community-registry`,DEV_ASSETS:($)=>`${$}_dev-assets`,SITE_DIAGNOSTICS:($)=>`site-diagnostics_${$}`,REPORTS:($)=>`${$}_commerce-discovery`};_m1=C3("decopilot_"),DQ=_m1.is,uz=_m1.get,vm1=C3("dev_"),bm1=vm1.get,Om0=vm1.is,MK5=`https://api.iconify.design/lucide:file-search.svg?color=${encodeURIComponent(fc8)}`;xm1=C3("brand-context-setup_"),M70=xm1.is,yc8=xm1.get,gc8=`
|
|
79
|
+
`),Hx1=!0}throw new EZ0.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.",{logger:$.logger,tryNextLink:!0})}return $.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"),ex0($)()},async(Z)=>{$.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");let{ssoStartUrl:Q,ssoAccountId:Y,ssoRegion:X,ssoRoleName:J,ssoSession:G}=$;if(!Q&&!Y&&!X&&!J&&!G)throw new EZ0.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).",{logger:$.logger});let{fromSSO:W}=await Promise.resolve().then(() => (Fy0(),Hy0));return W($)(Z)},async(Z)=>{$.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");let{fromIni:Q}=await Promise.resolve().then(() => (Kx1(),Wx1));return Q($)(Z)},async(Z)=>{$.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");let{fromProcess:Q}=await Promise.resolve().then(() => (Ng0(),Ug0));return Q($)(Z)},async(Z)=>{$.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");let{fromTokenFile:Q}=await Promise.resolve().then(() => (jg0(),wg0));return Q($)(Z)},async()=>{return $.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"),(await MV1($))()},async()=>{throw new EZ0.CredentialsProviderError("Could not load credentials from any providers",{tryNextLink:!1,logger:$.logger})}],Nh8),Nh8=($)=>$?.expiration!==void 0&&$.expiration.getTime()-Date.now()<300000;var Nx1=D(()=>{$f0();IV1();EZ0=C(b5(),1),Fx1=C(rY(),1)});var Bx1=D(()=>{Nx1()});var Ox1=()=>{};var hg,Bh8="AWS_S3_USE_ARN_REGION",Oh8="s3_use_arn_region",Dx1;var Lx1=D(()=>{hg=C(xp(),1),Dx1={environmentVariableSelector:($)=>hg.booleanSelector($,Bh8,hg.SelectorType.ENV),configFileSelector:($)=>hg.booleanSelector($,Oh8,hg.SelectorType.CONFIG),default:void 0}});var wx1=()=>{};var jx1=()=>{};var Ex1=D(()=>{Ox1();Lx1();jx1();wx1()});class ug{bytes;constructor($){if(this.bytes=$,$.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber($){if($>9223372036854776000||$<-9223372036854776000)throw Error(`${$} is too large (or, if negative, too small) to represent as an Int64`);let Z=new Uint8Array(8);for(let Q=7,Y=Math.abs(Math.round($));Q>-1&&Y>0;Q--,Y/=256)Z[Q]=Y;if($<0)zx1(Z);return new ug(Z)}valueOf(){let $=this.bytes.slice(0),Z=$[0]&128;if(Z)zx1($);return parseInt(Px1.toHex($),16)*(Z?-1:1)}toString(){return String(this.valueOf())}}function zx1($){for(let Z=0;Z<8;Z++)$[Z]^=255;for(let Z=7;Z>-1;Z--)if($[Z]++,$[Z]!==0)break}var Px1;var zg0=D(()=>{Px1=C(Fp(),1)});class Pg0{toUtf8;fromUtf8;constructor($,Z){this.toUtf8=$,this.fromUtf8=Z}format($){let Z=[];for(let X of Object.keys($)){let J=this.fromUtf8(X);Z.push(Uint8Array.from([J.byteLength]),J,this.formatHeaderValue($[X]))}let Q=new Uint8Array(Z.reduce((X,J)=>X+J.byteLength,0)),Y=0;for(let X of Z)Q.set(X,Y),Y+=X.byteLength;return Q}formatHeaderValue($){switch($.type){case"boolean":return Uint8Array.from([$.value?0:1]);case"byte":return Uint8Array.from([2,$.value]);case"short":let Z=new DataView(new ArrayBuffer(3));return Z.setUint8(0,3),Z.setInt16(1,$.value,!1),new Uint8Array(Z.buffer);case"integer":let Q=new DataView(new ArrayBuffer(5));return Q.setUint8(0,4),Q.setInt32(1,$.value,!1),new Uint8Array(Q.buffer);case"long":let Y=new Uint8Array(9);return Y[0]=5,Y.set($.value.bytes,1),Y;case"binary":let X=new DataView(new ArrayBuffer(3+$.value.byteLength));X.setUint8(0,6),X.setUint16(1,$.value.byteLength,!1);let J=new Uint8Array(X.buffer);return J.set($.value,3),J;case"string":let G=this.fromUtf8($.value),W=new DataView(new ArrayBuffer(3+G.byteLength));W.setUint8(0,7),W.setUint16(1,G.byteLength,!1);let K=new Uint8Array(W.buffer);return K.set(G,3),K;case"timestamp":let H=new Uint8Array(9);return H[0]=8,H.set(ug.fromNumber($.value.valueOf()).bytes,1),H;case"uuid":if(!Th8.test($.value))throw Error(`Invalid UUID received: ${$.value}`);let F=new Uint8Array(17);return F[0]=9,F.set(TD.fromHex($.value.replace(/\-/g,"")),1),F}}parse($){let Z={},Q=0;while(Q<$.byteLength){let Y=$.getUint8(Q++),X=this.toUtf8(new Uint8Array($.buffer,$.byteOffset+Q,Y));switch(Q+=Y,$.getUint8(Q++)){case 0:Z[X]={type:Tx1,value:!0};break;case 1:Z[X]={type:Tx1,value:!1};break;case 2:Z[X]={type:Dh8,value:$.getInt8(Q++)};break;case 3:Z[X]={type:Lh8,value:$.getInt16(Q,!1)},Q+=2;break;case 4:Z[X]={type:wh8,value:$.getInt32(Q,!1)},Q+=4;break;case 5:Z[X]={type:jh8,value:new ug(new Uint8Array($.buffer,$.byteOffset+Q,8))},Q+=8;break;case 6:let J=$.getUint16(Q,!1);Q+=2,Z[X]={type:Eh8,value:new Uint8Array($.buffer,$.byteOffset+Q,J)},Q+=J;break;case 7:let G=$.getUint16(Q,!1);Q+=2,Z[X]={type:zh8,value:this.toUtf8(new Uint8Array($.buffer,$.byteOffset+Q,G))},Q+=G;break;case 8:Z[X]={type:Ph8,value:new Date(new ug(new Uint8Array($.buffer,$.byteOffset+Q,8)).valueOf())},Q+=8;break;case 9:let W=new Uint8Array($.buffer,$.byteOffset+Q,16);Q+=16,Z[X]={type:Ah8,value:`${TD.toHex(W.subarray(0,4))}-${TD.toHex(W.subarray(4,6))}-${TD.toHex(W.subarray(6,8))}-${TD.toHex(W.subarray(8,10))}-${TD.toHex(W.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return Z}}var TD,Ax1,Tx1="boolean",Dh8="byte",Lh8="short",wh8="integer",jh8="long",Eh8="binary",zh8="string",Ph8="timestamp",Ah8="uuid",Th8;var Ag0=D(()=>{zg0();TD=C(Fp(),1);(function($){$[$.boolTrue=0]="boolTrue",$[$.boolFalse=1]="boolFalse",$[$.byte=2]="byte",$[$.short=3]="short",$[$.integer=4]="integer",$[$.long=5]="long",$[$.byteArray=6]="byteArray",$[$.string=7]="string",$[$.timestamp=8]="timestamp",$[$.uuid=9]="uuid"})(Ax1||(Ax1={}));Th8=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/});function Mx1({byteLength:$,byteOffset:Z,buffer:Q}){if($<Rh8)throw Error("Provided message too short to accommodate event stream message overhead");let Y=new DataView(Q,Z,$),X=Y.getUint32(0,!1);if($!==X)throw Error("Reported message length does not match received message length");let J=Y.getUint32(qx1,!1),G=Y.getUint32(RD,!1),W=Y.getUint32($-qz,!1),K=new Rx1.Crc32().update(new Uint8Array(Q,Z,RD));if(G!==K.digest())throw Error(`The prelude checksum specified in the message (${G}) does not match the calculated CRC32 checksum (${K.digest()})`);if(K.update(new Uint8Array(Q,Z+RD,$-(RD+qz))),W!==K.digest())throw Error(`The message checksum (${K.digest()}) did not match the expected value of ${W}`);return{headers:new DataView(Q,Z+RD+qz,J),body:new Uint8Array(Q,Z+RD+qz+J,X-J-(RD+qz+qz))}}var Rx1,qx1=4,RD,qz=4,Rh8;var Ix1=D(()=>{Rx1=C(iE(),1),RD=qx1*2,Rh8=RD+qz*2});class Tg0{headerMarshaller;messageBuffer;isEndOfStream;constructor($,Z){this.headerMarshaller=new Pg0($,Z),this.messageBuffer=[],this.isEndOfStream=!1}feed($){this.messageBuffer.push(this.decode($))}endOfStream(){this.isEndOfStream=!0}getMessage(){let $=this.messageBuffer.pop(),Z=this.isEndOfStream;return{getMessage(){return $},isEndOfStream(){return Z}}}getAvailableMessages(){let $=this.messageBuffer;this.messageBuffer=[];let Z=this.isEndOfStream;return{getMessages(){return $},isEndOfStream(){return Z}}}encode({headers:$,body:Z}){let Q=this.headerMarshaller.format($),Y=Q.byteLength+Z.byteLength+16,X=new Uint8Array(Y),J=new DataView(X.buffer,X.byteOffset,X.byteLength),G=new Vx1.Crc32;return J.setUint32(0,Y,!1),J.setUint32(4,Q.byteLength,!1),J.setUint32(8,G.update(X.subarray(0,8)).digest(),!1),X.set(Q,12),X.set(Z,Q.byteLength+12),J.setUint32(Y-4,G.update(X.subarray(8,Y-4)).digest(),!1),X}decode($){let{headers:Z,body:Q}=Mx1($);return{headers:this.headerMarshaller.parse(Z),body:Q}}formatHeaders($){return this.headerMarshaller.format($)}}var Vx1;var kx1=D(()=>{Ag0();Ix1();Vx1=C(iE(),1)});var Sx1=()=>{};var Rg0;var Cx1=D(()=>{Rg0=class Rg0{options;constructor($){this.options=$}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let $ of this.options.inputStream)yield this.options.decoder.decode($)}}});var qg0;var _x1=D(()=>{qg0=class qg0{options;constructor($){this.options=$}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let $ of this.options.messageStream)yield this.options.encoder.encode($);if(this.options.includeEndFrame)yield new Uint8Array(0)}}});var Mg0;var vx1=D(()=>{Mg0=class Mg0{options;constructor($){this.options=$}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let $ of this.options.messageStream){let Z=await this.options.deserializer($);if(Z===void 0)continue;yield Z}}}});var Ig0;var bx1=D(()=>{Ig0=class Ig0{options;constructor($){this.options=$}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let $ of this.options.inputStream)yield this.options.serializer($)}}});var xx1=D(()=>{kx1();Ag0();zg0();Sx1();Cx1();_x1();vx1();bx1()});function fx1($){let Z=0,Q=0,Y=null,X=null,J=(W)=>{if(typeof W!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+W);Z=W,Q=4,Y=new Uint8Array(W),new DataView(Y.buffer).setUint32(0,W,!1)},G=async function*(){let W=$[Symbol.asyncIterator]();while(!0){let{value:K,done:H}=await W.next();if(H){if(!Z)return;else if(Z===Q)yield Y;else throw Error("Truncated event message received.");return}let F=K.length,U=0;while(U<F){if(!Y){let B=F-U;if(!X)X=new Uint8Array(4);let O=Math.min(4-Q,B);if(X.set(K.slice(U,U+O),Q),Q+=O,U+=O,Q<4)break;J(new DataView(X.buffer).getUint32(0,!1)),X=null}let N=Math.min(Z-Q,F-U);if(Y.set(K.slice(U,U+N),Q),Q+=N,U+=N,Z&&Z===Q)yield Y,Y=null,Z=0,Q=0}}};return{[Symbol.asyncIterator]:G}}function yx1($,Z){return async function(Q){let{value:Y}=Q.headers[":message-type"];if(Y==="error"){let X=Error(Q.headers[":error-message"].value||"UnknownError");throw X.name=Q.headers[":error-code"].value,X}else if(Y==="exception"){let X=Q.headers[":exception-type"].value,J={[X]:Q},G=await $(J);if(G.$unknown){let W=Error(Z(Q.body));throw W.name=X,W}throw G[X]}else if(Y==="event"){let X={[Q.headers[":event-type"].value]:Q},J=await $(X);if(J.$unknown)return;return J}else throw Error(`Unrecognizable event type: ${Q.headers[":event-type"].value}`)}}class Vg0{eventStreamCodec;utfEncoder;constructor({utf8Encoder:$,utf8Decoder:Z}){this.eventStreamCodec=new Tg0($,Z),this.utfEncoder=$}deserialize($,Z){let Q=fx1($);return new Mg0({messageStream:new Rg0({inputStream:Q,decoder:this.eventStreamCodec}),deserializer:yx1(Z,this.utfEncoder)})}serialize($,Z){return new qg0({messageStream:new Ig0({inputStream:$,serializer:Z}),encoder:this.eventStreamCodec,includeEndFrame:!0})}}var gx1=D(()=>{xx1()});var hx1=()=>{};var ux1=D(()=>{gx1();hx1()});async function*lx1($){let Z=!1,Q=!1,Y=[];$.on("error",(X)=>{if(!Z)Z=!0;if(X)throw X}),$.on("data",(X)=>{Y.push(X)}),$.on("end",()=>{Z=!0});while(!Q){let X=await new Promise((J)=>setTimeout(()=>J(Y.shift()),0));if(X)yield X;Q=Z&&Y.length===0}}import{Readable as qh8}from"stream";class kg0{universalMarshaller;constructor({utf8Encoder:$,utf8Decoder:Z}){this.universalMarshaller=new Vg0({utf8Decoder:Z,utf8Encoder:$})}deserialize($,Z){let Q=typeof $[Symbol.asyncIterator]==="function"?$:lx1($);return this.universalMarshaller.deserialize(Q,Z)}serialize($,Z){return qh8.from(this.universalMarshaller.serialize($,Z))}}var Sg0=D(()=>{ux1()});var cx1=($)=>new kg0($);var mx1=D(()=>{Sg0()});var dx1=D(()=>{Sg0();mx1()});import{Writable as Mh8}from"stream";var ix1,Cg0;var px1=D(()=>{ix1=C(GQ(),1);Cg0=class Cg0 extends Mh8{hash;constructor($,Z){super(Z);this.hash=$}_write($,Z,Q){try{this.hash.update(ix1.toUint8Array($))}catch(Y){return Q(Y)}Q()}}});var nx1=()=>{};var tx1=($,Z)=>{if(Z.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let Q=new $,Y=new Cg0(Q);return Z.pipe(Y),new Promise((X,J)=>{Z.on("error",(G)=>{Y.end(),J(G)}),Y.on("error",J),Y.on("finish",()=>{Q.digest().then(X).catch(J)})})};var ox1=D(()=>{px1()});var rx1=D(()=>{nx1();ox1()});var zZ0,sx1,ax1,ex1,$f1,PZ0,AZ0,TZ0,Zf1=($)=>{return{apiVersion:"2006-03-01",base64Decoder:$?.base64Decoder??PZ0.fromBase64,base64Encoder:$?.base64Encoder??PZ0.toBase64,disableHostPrefix:$?.disableHostPrefix??!1,endpointProvider:$?.endpointProvider??$90,extensions:$?.extensions??[],getAwsChunkedEncodingStream:$?.getAwsChunkedEncodingStream??AZ0.getAwsChunkedEncodingStream,httpAuthSchemeProvider:$?.httpAuthSchemeProvider??Xq1,httpAuthSchemes:$?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(Z)=>Z.getIdentityProvider("aws.auth#sigv4"),signer:new zZ0.AwsSdkSigV4Signer},{schemeId:"aws.auth#sigv4a",identityProvider:(Z)=>Z.getIdentityProvider("aws.auth#sigv4a"),signer:new zZ0.AwsSdkSigV4ASigner}],logger:$?.logger??new ex1.NoOpLogger,protocol:$?.protocol??sx1.S3RestXmlProtocol,protocolSettings:$?.protocolSettings??{defaultNamespace:"com.amazonaws.s3",errorTypeRegistries:Fq1,xmlNamespace:"http://s3.amazonaws.com/doc/2006-03-01/",version:"2006-03-01",serviceTarget:"AmazonS3"},sdkStreamMixin:$?.sdkStreamMixin??AZ0.sdkStreamMixin,serviceId:$?.serviceId??"S3",signerConstructor:$?.signerConstructor??ax1.SignatureV4MultiRegion,signingEscapePath:$?.signingEscapePath??!1,urlParser:$?.urlParser??$f1.parseUrl,useArnRegion:$?.useArnRegion??void 0,utf8Decoder:$?.utf8Decoder??TZ0.fromUtf8,utf8Encoder:$?.utf8Encoder??TZ0.toUtf8}};var Qf1=D(()=>{ux0();hx0();J1();zZ0=C(oQ(),1),sx1=C($$(),1),ax1=C(Eg(),1),ex1=C(i0(),1),$f1=C(vH(),1),PZ0=C(uX(),1),AZ0=C(py(),1),TZ0=C(GQ(),1)});var Yf1,qZ0,Xf1,MZ0,qD,RZ0,IZ0,WG,VZ0,kZ0,Jf1,Gf1,Wf1,Kf1=($)=>{kZ0.emitWarningIfUnsupportedVersion(process.version);let Z=Gf1.resolveDefaultsModeConfig($),Q=()=>Z().then(kZ0.loadConfigsForDefaultMode),Y=Zf1($);Yf1.emitWarningIfUnsupportedVersion(process.version);let X={profile:$?.profile,logger:Y.logger};return{...Y,...$,runtime:"node",defaultsMode:Z,authSchemePreference:$?.authSchemePreference??WG.loadConfig(qZ0.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,X),bodyLengthChecker:$?.bodyLengthChecker??Jf1.calculateBodyLength,credentialDefaultProvider:$?.credentialDefaultProvider??Ux1,defaultUserAgentProvider:$?.defaultUserAgentProvider??MZ0.createDefaultUserAgentProvider({serviceId:Y.serviceId,clientVersion:uI1.version}),disableS3ExpressSessionAuth:$?.disableS3ExpressSessionAuth??WG.loadConfig(Xf1.NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS,X),eventStreamSerdeProvider:$?.eventStreamSerdeProvider??cx1,maxAttempts:$?.maxAttempts??WG.loadConfig(IZ0.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,$),md5:$?.md5??RZ0.Hash.bind(null,"md5"),region:$?.region??WG.loadConfig(qD.NODE_REGION_CONFIG_OPTIONS,{...qD.NODE_REGION_CONFIG_FILE_OPTIONS,...X}),requestChecksumCalculation:$?.requestChecksumCalculation??WG.loadConfig(oL1,X),requestHandler:VZ0.NodeHttpHandler.create($?.requestHandler??Q),responseChecksumValidation:$?.responseChecksumValidation??WG.loadConfig(sL1,X),retryMode:$?.retryMode??WG.loadConfig({...IZ0.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await Q()).retryMode||Wf1.DEFAULT_RETRY_MODE},$),sha1:$?.sha1??RZ0.Hash.bind(null,"sha1"),sha256:$?.sha256??RZ0.Hash.bind(null,"sha256"),sigv4aSigningRegionSet:$?.sigv4aSigningRegionSet??WG.loadConfig(qZ0.NODE_SIGV4A_CONFIG_OPTIONS,X),streamCollector:$?.streamCollector??VZ0.streamCollector,streamHasher:$?.streamHasher??tx1,useArnRegion:$?.useArnRegion??WG.loadConfig(Dx1,X),useDualstackEndpoint:$?.useDualstackEndpoint??WG.loadConfig(qD.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,X),useFipsEndpoint:$?.useFipsEndpoint??WG.loadConfig(qD.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,X),userAgentAppId:$?.userAgentAppId??WG.loadConfig(MZ0.NODE_APP_ID_CONFIG_OPTIONS,X)}};var Hf1=D(()=>{hI1();Bx1();Ex1();A6();dx1();rx1();Qf1();Yf1=C(X9(),1),qZ0=C(oQ(),1),Xf1=C($$(),1),MZ0=C(Mg(),1),qD=C(mX(),1),RZ0=C(Ig(),1),IZ0=C(oW(),1),WG=C(tW(),1),VZ0=C(QD(),1),kZ0=C(i0(),1),Jf1=C(Vg(),1),Gf1=C(kg(),1),Wf1=C(WN(),1)});var Ff1=($)=>{let{httpAuthSchemes:Z,httpAuthSchemeProvider:Q,credentials:Y}=$;return{setHttpAuthScheme(X){let J=Z.findIndex((G)=>G.schemeId===X.schemeId);if(J===-1)Z.push(X);else Z.splice(J,1,X)},httpAuthSchemes(){return Z},setHttpAuthSchemeProvider(X){Q=X},httpAuthSchemeProvider(){return Q},setCredentials(X){Y=X},credentials(){return Y}}},Uf1=($)=>{return{httpAuthSchemes:$.httpAuthSchemes(),httpAuthSchemeProvider:$.httpAuthSchemeProvider(),credentials:$.credentials()}};var SZ0,CZ0,_Z0,Nf1=($,Z)=>{let Q=Object.assign(SZ0.getAwsRegionExtensionConfiguration($),_Z0.getDefaultExtensionConfiguration($),CZ0.getHttpHandlerExtensionConfiguration($),Ff1($));return Z.forEach((Y)=>Y.configure(Q)),Object.assign($,SZ0.resolveAwsRegionExtensionConfiguration(Q),_Z0.resolveDefaultRuntimeConfig(Q),CZ0.resolveHttpHandlerRuntimeConfig(Q),Uf1(Q))};var Bf1=D(()=>{SZ0=C(Kz(),1),CZ0=C(v5(),1),_Z0=C(i0(),1)});var vZ0,Of1,Df1,gH,bZ0,Lf1,lg,wf1,jf1,Ef1,xZ0,zf1,eY;var Mz=D(()=>{nL1();A6();a21();ux0();E90();W1();Hf1();Bf1();vZ0=C(ay(),1),Of1=C(ey(),1),Df1=C($g(),1),gH=C($$(),1),bZ0=C(Qz(),1),Lf1=C(mX(),1),lg=C(X7(),1),wf1=C(pQ(),1),jf1=C(Dg(),1),Ef1=C(Y1(),1),xZ0=C(oW(),1),zf1=C(i0(),1);eY=class eY extends zf1.Client{config;constructor(...[$]){let Z=Kf1($||{});super(Z);this.initConfig=Z;let Q=Gq1(Z),Y=bZ0.resolveUserAgentConfig(Q),X=Rz1(Y),J=xZ0.resolveRetryConfig(X),G=Lf1.resolveRegionConfig(J),W=vZ0.resolveHostHeaderConfig(G),K=Ef1.resolveEndpointConfig(W),H=s21(K),F=Jq1(H),U=gH.resolveS3Config(F,{session:[()=>this,np]}),N=Nf1(U,$?.extensions||[]);this.config=N,this.middlewareStack.use(wf1.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(bZ0.getUserAgentPlugin(this.config)),this.middlewareStack.use(xZ0.getRetryPlugin(this.config)),this.middlewareStack.use(jf1.getContentLengthPlugin(this.config)),this.middlewareStack.use(vZ0.getHostHeaderPlugin(this.config)),this.middlewareStack.use(Of1.getLoggerPlugin(this.config)),this.middlewareStack.use(Df1.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(lg.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:Zq1,identityProviderConfigProvider:async(B)=>new lg.DefaultIdentityProviderConfig({"aws.auth#sigv4":B.credentials,"aws.auth#sigv4a":B.credentials})})),this.middlewareStack.use(lg.getHttpSigningPlugin(this.config)),this.middlewareStack.use(gH.getValidateBucketNamePlugin(this.config)),this.middlewareStack.use(pL1(this.config)),this.middlewareStack.use(gH.getRegionRedirectMiddlewarePlugin(this.config)),this.middlewareStack.use(gH.getS3ExpressPlugin(this.config)),this.middlewareStack.use(gH.getS3ExpressHttpSigningPlugin(this.config))}destroy(){super.destroy()}}});var Pf1,Af1,Tf1,On;var _g0=D(()=>{W1();J1();Pf1=C($$(),1),Af1=C(Y1(),1),Tf1=C(i0(),1);On=class On extends Tf1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[Af1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Pf1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","AbortMultipartUpload",{}).n("S3Client","AbortMultipartUploadCommand").sc(yq1).build(){}});function Ih8($){return(Z)=>async(Q)=>{let Y={...Q.input},X=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}];for(let J of X){let G=Y[J.target];if(G){let W;if(typeof G==="string")if(kh8(G,$))W=$.base64Decoder(G);else W=$.utf8Decoder(G),Y[J.target]=$.base64Encoder(W);else W=ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):new Uint8Array(G),Y[J.target]=$.base64Encoder(W);let K=new $.md5;K.update(W),Y[J.hash]=$.base64Encoder(await K.digest())}}return Z({...Q,input:Y})}}function kh8($,Z){if(!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test($))return!1;try{return Z.base64Decoder($).length===32}catch{return!1}}var Vh8,r9=($)=>({applyToStack:(Z)=>{Z.add(Ih8($),Vh8)}});var R3=D(()=>{Vh8={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0}});var Rf1,qf1,Mf1,Dn;var vg0=D(()=>{R3();W1();J1();Rf1=C($$(),1),qf1=C(Y1(),1),Mf1=C(i0(),1);Dn=class Dn extends Mf1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[qf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Rf1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","CompleteMultipartUpload",{}).n("S3Client","CompleteMultipartUploadCommand").sc(gq1).build(){}});var If1,Vf1,kf1,bg0;var xg0=D(()=>{R3();W1();J1();If1=C($$(),1),Vf1=C(Y1(),1),kf1=C(i0(),1);bg0=class bg0 extends kf1.Command.classBuilder().ep({...B0,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"},CopySource:{type:"contextParams",name:"CopySource"}}).m(function($,Z,Q,Y){return[Vf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),If1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","CopyObject",{}).n("S3Client","CopyObjectCommand").sc(hq1).build(){}});function Sh8($){return(Z)=>async(Q)=>{let{CreateBucketConfiguration:Y}=Q.input,X=await $.region();if(!Y?.LocationConstraint&&!Y?.Location){if(X!=="us-east-1")Q.input.CreateBucketConfiguration=Q.input.CreateBucketConfiguration??{},Q.input.CreateBucketConfiguration.LocationConstraint=X}return Z(Q)}}var Ch8,Sf1=($)=>({applyToStack:(Z)=>{Z.add(Sh8($),Ch8)}});var Cf1=D(()=>{Ch8={step:"initialize",tags:["LOCATION_CONSTRAINT","CREATE_BUCKET_CONFIGURATION"],name:"locationConstraintMiddleware",override:!0}});var _f1,vf1,bf1,fg0;var yg0=D(()=>{Cf1();W1();J1();_f1=C($$(),1),vf1=C(Y1(),1),bf1=C(i0(),1);fg0=class fg0 extends bf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},DisableAccessPoints:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[vf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),_f1.getThrow200ExceptionsPlugin(Q),Sf1(Q)]}).s("AmazonS3","CreateBucket",{}).n("S3Client","CreateBucketCommand").sc(uq1).build(){}});var xf1,ff1,gg0;var hg0=D(()=>{A6();W1();J1();xf1=C(Y1(),1),ff1=C(i0(),1);gg0=class gg0 extends ff1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[xf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","CreateBucketMetadataConfiguration",{}).n("S3Client","CreateBucketMetadataConfigurationCommand").sc(lq1).build(){}});var yf1,gf1,ug0;var lg0=D(()=>{A6();W1();J1();yf1=C(Y1(),1),gf1=C(i0(),1);ug0=class ug0 extends gf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[yf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","CreateBucketMetadataTableConfiguration",{}).n("S3Client","CreateBucketMetadataTableConfigurationCommand").sc(cq1).build(){}});var hf1,uf1,lf1,Ln;var cg0=D(()=>{R3();W1();J1();hf1=C($$(),1),uf1=C(Y1(),1),lf1=C(i0(),1);Ln=class Ln extends lf1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[uf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),hf1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","CreateMultipartUpload",{}).n("S3Client","CreateMultipartUploadCommand").sc(mq1).build(){}});var cf1,mf1,mg0;var dg0=D(()=>{W1();J1();cf1=C(Y1(),1),mf1=C(i0(),1);mg0=class mg0 extends mf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[cf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketAnalyticsConfiguration",{}).n("S3Client","DeleteBucketAnalyticsConfigurationCommand").sc(pq1).build(){}});var df1,if1,ig0;var pg0=D(()=>{W1();J1();df1=C(Y1(),1),if1=C(i0(),1);ig0=class ig0 extends if1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[df1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucket",{}).n("S3Client","DeleteBucketCommand").sc(iq1).build(){}});var pf1,nf1,ng0;var tg0=D(()=>{W1();J1();pf1=C(Y1(),1),nf1=C(i0(),1);ng0=class ng0 extends nf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[pf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketCors",{}).n("S3Client","DeleteBucketCorsCommand").sc(nq1).build(){}});var tf1,of1,og0;var rg0=D(()=>{W1();J1();tf1=C(Y1(),1),of1=C(i0(),1);og0=class og0 extends of1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[tf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketEncryption",{}).n("S3Client","DeleteBucketEncryptionCommand").sc(tq1).build(){}});var rf1,sf1,sg0;var ag0=D(()=>{W1();J1();rf1=C(Y1(),1),sf1=C(i0(),1);sg0=class sg0 extends sf1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[rf1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketIntelligentTieringConfiguration",{}).n("S3Client","DeleteBucketIntelligentTieringConfigurationCommand").sc(oq1).build(){}});var af1,ef1,eg0;var $h0=D(()=>{W1();J1();af1=C(Y1(),1),ef1=C(i0(),1);eg0=class eg0 extends ef1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[af1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketInventoryConfiguration",{}).n("S3Client","DeleteBucketInventoryConfigurationCommand").sc(rq1).build(){}});var $y1,Zy1,Zh0;var Qh0=D(()=>{W1();J1();$y1=C(Y1(),1),Zy1=C(i0(),1);Zh0=class Zh0 extends Zy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[$y1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketLifecycle",{}).n("S3Client","DeleteBucketLifecycleCommand").sc(sq1).build(){}});var Qy1,Yy1,Yh0;var Xh0=D(()=>{W1();J1();Qy1=C(Y1(),1),Yy1=C(i0(),1);Yh0=class Yh0 extends Yy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Qy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetadataConfiguration",{}).n("S3Client","DeleteBucketMetadataConfigurationCommand").sc(aq1).build(){}});var Xy1,Jy1,Jh0;var Gh0=D(()=>{W1();J1();Xy1=C(Y1(),1),Jy1=C(i0(),1);Jh0=class Jh0 extends Jy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Xy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetadataTableConfiguration",{}).n("S3Client","DeleteBucketMetadataTableConfigurationCommand").sc(eq1).build(){}});var Gy1,Wy1,Wh0;var Kh0=D(()=>{W1();J1();Gy1=C(Y1(),1),Wy1=C(i0(),1);Wh0=class Wh0 extends Wy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Gy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketMetricsConfiguration",{}).n("S3Client","DeleteBucketMetricsConfigurationCommand").sc($M1).build(){}});var Ky1,Hy1,Hh0;var Fh0=D(()=>{W1();J1();Ky1=C(Y1(),1),Hy1=C(i0(),1);Hh0=class Hh0 extends Hy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ky1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketOwnershipControls",{}).n("S3Client","DeleteBucketOwnershipControlsCommand").sc(ZM1).build(){}});var Fy1,Uy1,Uh0;var Nh0=D(()=>{W1();J1();Fy1=C(Y1(),1),Uy1=C(i0(),1);Uh0=class Uh0 extends Uy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Fy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketPolicy",{}).n("S3Client","DeleteBucketPolicyCommand").sc(QM1).build(){}});var Ny1,By1,Bh0;var Oh0=D(()=>{W1();J1();Ny1=C(Y1(),1),By1=C(i0(),1);Bh0=class Bh0 extends By1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ny1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketReplication",{}).n("S3Client","DeleteBucketReplicationCommand").sc(YM1).build(){}});var Oy1,Dy1,Dh0;var Lh0=D(()=>{W1();J1();Oy1=C(Y1(),1),Dy1=C(i0(),1);Dh0=class Dh0 extends Dy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Oy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketTagging",{}).n("S3Client","DeleteBucketTaggingCommand").sc(XM1).build(){}});var Ly1,wy1,wh0;var jh0=D(()=>{W1();J1();Ly1=C(Y1(),1),wy1=C(i0(),1);wh0=class wh0 extends wy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ly1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeleteBucketWebsite",{}).n("S3Client","DeleteBucketWebsiteCommand").sc(JM1).build(){}});var jy1,Ey1,zy1,Iz;var Eh0=D(()=>{W1();J1();jy1=C($$(),1),Ey1=C(Y1(),1),zy1=C(i0(),1);Iz=class Iz extends zy1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[Ey1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),jy1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").sc(GM1).build(){}});var Py1,Ay1,Ty1,zh0;var Ph0=D(()=>{A6();W1();J1();Py1=C($$(),1),Ay1=C(Y1(),1),Ty1=C(i0(),1);zh0=class zh0 extends Ty1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ay1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),Py1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","DeleteObjects",{}).n("S3Client","DeleteObjectsCommand").sc(WM1).build(){}});var Ry1,qy1,My1,Ah0;var Th0=D(()=>{W1();J1();Ry1=C($$(),1),qy1=C(Y1(),1),My1=C(i0(),1);Ah0=class Ah0 extends My1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[qy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Ry1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","DeleteObjectTagging",{}).n("S3Client","DeleteObjectTaggingCommand").sc(KM1).build(){}});var Iy1,Vy1,Rh0;var qh0=D(()=>{W1();J1();Iy1=C(Y1(),1),Vy1=C(i0(),1);Rh0=class Rh0 extends Vy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Iy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","DeletePublicAccessBlock",{}).n("S3Client","DeletePublicAccessBlockCommand").sc(HM1).build(){}});var ky1,Sy1,Cy1,Mh0;var Ih0=D(()=>{W1();J1();ky1=C($$(),1),Sy1=C(Y1(),1),Cy1=C(i0(),1);Mh0=class Mh0 extends Cy1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Sy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ky1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketAbac",{}).n("S3Client","GetBucketAbacCommand").sc(FM1).build(){}});var _y1,vy1,by1,Vh0;var kh0=D(()=>{W1();J1();_y1=C($$(),1),vy1=C(Y1(),1),by1=C(i0(),1);Vh0=class Vh0 extends by1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[vy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),_y1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketAccelerateConfiguration",{}).n("S3Client","GetBucketAccelerateConfigurationCommand").sc(UM1).build(){}});var xy1,fy1,yy1,Sh0;var Ch0=D(()=>{W1();J1();xy1=C($$(),1),fy1=C(Y1(),1),yy1=C(i0(),1);Sh0=class Sh0 extends yy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[fy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),xy1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketAcl",{}).n("S3Client","GetBucketAclCommand").sc(NM1).build(){}});var gy1,hy1,uy1,_h0;var vh0=D(()=>{W1();J1();gy1=C($$(),1),hy1=C(Y1(),1),uy1=C(i0(),1);_h0=class _h0 extends uy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[hy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),gy1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketAnalyticsConfiguration",{}).n("S3Client","GetBucketAnalyticsConfigurationCommand").sc(BM1).build(){}});var ly1,cy1,my1,bh0;var xh0=D(()=>{W1();J1();ly1=C($$(),1),cy1=C(Y1(),1),my1=C(i0(),1);bh0=class bh0 extends my1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[cy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ly1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketCors",{}).n("S3Client","GetBucketCorsCommand").sc(OM1).build(){}});var dy1,iy1,py1,fh0;var yh0=D(()=>{W1();J1();dy1=C($$(),1),iy1=C(Y1(),1),py1=C(i0(),1);fh0=class fh0 extends py1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[iy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),dy1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketEncryption",{}).n("S3Client","GetBucketEncryptionCommand").sc(DM1).build(){}});var ny1,ty1,oy1,gh0;var hh0=D(()=>{W1();J1();ny1=C($$(),1),ty1=C(Y1(),1),oy1=C(i0(),1);gh0=class gh0 extends oy1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[ty1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ny1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketIntelligentTieringConfiguration",{}).n("S3Client","GetBucketIntelligentTieringConfigurationCommand").sc(LM1).build(){}});var ry1,sy1,ay1,uh0;var lh0=D(()=>{W1();J1();ry1=C($$(),1),sy1=C(Y1(),1),ay1=C(i0(),1);uh0=class uh0 extends ay1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[sy1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ry1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketInventoryConfiguration",{}).n("S3Client","GetBucketInventoryConfigurationCommand").sc(wM1).build(){}});var ey1,$g1,Zg1,ch0;var mh0=D(()=>{W1();J1();ey1=C($$(),1),$g1=C(Y1(),1),Zg1=C(i0(),1);ch0=class ch0 extends Zg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[$g1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ey1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketLifecycleConfiguration",{}).n("S3Client","GetBucketLifecycleConfigurationCommand").sc(jM1).build(){}});var Qg1,Yg1,Xg1,dh0;var ih0=D(()=>{W1();J1();Qg1=C($$(),1),Yg1=C(Y1(),1),Xg1=C(i0(),1);dh0=class dh0 extends Xg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Yg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Qg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketLocation",{}).n("S3Client","GetBucketLocationCommand").sc(EM1).build(){}});var Jg1,Gg1,Wg1,ph0;var nh0=D(()=>{W1();J1();Jg1=C($$(),1),Gg1=C(Y1(),1),Wg1=C(i0(),1);ph0=class ph0 extends Wg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Gg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Jg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketLogging",{}).n("S3Client","GetBucketLoggingCommand").sc(zM1).build(){}});var Kg1,Hg1,Fg1,th0;var oh0=D(()=>{W1();J1();Kg1=C($$(),1),Hg1=C(Y1(),1),Fg1=C(i0(),1);th0=class th0 extends Fg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Hg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Kg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketMetadataConfiguration",{}).n("S3Client","GetBucketMetadataConfigurationCommand").sc(PM1).build(){}});var Ug1,Ng1,Bg1,rh0;var sh0=D(()=>{W1();J1();Ug1=C($$(),1),Ng1=C(Y1(),1),Bg1=C(i0(),1);rh0=class rh0 extends Bg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ng1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Ug1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketMetadataTableConfiguration",{}).n("S3Client","GetBucketMetadataTableConfigurationCommand").sc(AM1).build(){}});var Og1,Dg1,Lg1,ah0;var eh0=D(()=>{W1();J1();Og1=C($$(),1),Dg1=C(Y1(),1),Lg1=C(i0(),1);ah0=class ah0 extends Lg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Dg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Og1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketMetricsConfiguration",{}).n("S3Client","GetBucketMetricsConfigurationCommand").sc(TM1).build(){}});var wg1,jg1,Eg1,$u0;var Zu0=D(()=>{W1();J1();wg1=C($$(),1),jg1=C(Y1(),1),Eg1=C(i0(),1);$u0=class $u0 extends Eg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[jg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),wg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketNotificationConfiguration",{}).n("S3Client","GetBucketNotificationConfigurationCommand").sc(RM1).build(){}});var zg1,Pg1,Ag1,Qu0;var Yu0=D(()=>{W1();J1();zg1=C($$(),1),Pg1=C(Y1(),1),Ag1=C(i0(),1);Qu0=class Qu0 extends Ag1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Pg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),zg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketOwnershipControls",{}).n("S3Client","GetBucketOwnershipControlsCommand").sc(qM1).build(){}});var Tg1,Rg1,Xu0;var Ju0=D(()=>{W1();J1();Tg1=C(Y1(),1),Rg1=C(i0(),1);Xu0=class Xu0 extends Rg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Tg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","GetBucketPolicy",{}).n("S3Client","GetBucketPolicyCommand").sc(MM1).build(){}});var qg1,Mg1,Ig1,Gu0;var Wu0=D(()=>{W1();J1();qg1=C($$(),1),Mg1=C(Y1(),1),Ig1=C(i0(),1);Gu0=class Gu0 extends Ig1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Mg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),qg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketPolicyStatus",{}).n("S3Client","GetBucketPolicyStatusCommand").sc(IM1).build(){}});var Vg1,kg1,Sg1,Ku0;var Hu0=D(()=>{W1();J1();Vg1=C($$(),1),kg1=C(Y1(),1),Sg1=C(i0(),1);Ku0=class Ku0 extends Sg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[kg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Vg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketReplication",{}).n("S3Client","GetBucketReplicationCommand").sc(VM1).build(){}});var Cg1,_g1,vg1,Fu0;var Uu0=D(()=>{W1();J1();Cg1=C($$(),1),_g1=C(Y1(),1),vg1=C(i0(),1);Fu0=class Fu0 extends vg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[_g1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Cg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketRequestPayment",{}).n("S3Client","GetBucketRequestPaymentCommand").sc(kM1).build(){}});var bg1,xg1,fg1,Nu0;var Bu0=D(()=>{W1();J1();bg1=C($$(),1),xg1=C(Y1(),1),fg1=C(i0(),1);Nu0=class Nu0 extends fg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[xg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),bg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketTagging",{}).n("S3Client","GetBucketTaggingCommand").sc(SM1).build(){}});var yg1,gg1,hg1,Ou0;var Du0=D(()=>{W1();J1();yg1=C($$(),1),gg1=C(Y1(),1),hg1=C(i0(),1);Ou0=class Ou0 extends hg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[gg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),yg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketVersioning",{}).n("S3Client","GetBucketVersioningCommand").sc(CM1).build(){}});var ug1,lg1,cg1,Lu0;var wu0=D(()=>{W1();J1();ug1=C($$(),1),lg1=C(Y1(),1),cg1=C(i0(),1);Lu0=class Lu0 extends cg1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[lg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ug1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetBucketWebsite",{}).n("S3Client","GetBucketWebsiteCommand").sc(_M1).build(){}});var mg1,dg1,ig1,ju0;var Eu0=D(()=>{W1();J1();mg1=C($$(),1),dg1=C(Y1(),1),ig1=C(i0(),1);ju0=class ju0 extends ig1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[dg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),mg1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectAcl",{}).n("S3Client","GetObjectAclCommand").sc(bM1).build(){}});var pg1,ng1,tg1,zu0;var Pu0=D(()=>{R3();W1();J1();pg1=C($$(),1),ng1=C(Y1(),1),tg1=C(i0(),1);zu0=class zu0 extends tg1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[ng1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),pg1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","GetObjectAttributes",{}).n("S3Client","GetObjectAttributesCommand").sc(xM1).build(){}});var og1,rg1,sg1,MD;var Au0=D(()=>{A6();R3();W1();J1();og1=C($$(),1),rg1=C(Y1(),1),sg1=C(i0(),1);MD=class MD extends sg1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[rg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC64NVME","CRC32","CRC32C","SHA256","SHA1","SHA512","MD5","XXHASH64","XXHASH3","XXHASH128"]}),r9(Q),og1.getS3ExpiresMiddlewarePlugin(Q)]}).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").sc(vM1).build(){}});var ag1,eg1,$h1,Tu0;var Ru0=D(()=>{W1();J1();ag1=C($$(),1),eg1=C(Y1(),1),$h1=C(i0(),1);Tu0=class Tu0 extends $h1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[eg1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),ag1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectLegalHold",{}).n("S3Client","GetObjectLegalHoldCommand").sc(fM1).build(){}});var Zh1,Qh1,Yh1,qu0;var Mu0=D(()=>{W1();J1();Zh1=C($$(),1),Qh1=C(Y1(),1),Yh1=C(i0(),1);qu0=class qu0 extends Yh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Qh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Zh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectLockConfiguration",{}).n("S3Client","GetObjectLockConfigurationCommand").sc(yM1).build(){}});var Xh1,Jh1,Gh1,Iu0;var Vu0=D(()=>{W1();J1();Xh1=C($$(),1),Jh1=C(Y1(),1),Gh1=C(i0(),1);Iu0=class Iu0 extends Gh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Jh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Xh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectRetention",{}).n("S3Client","GetObjectRetentionCommand").sc(gM1).build(){}});var Wh1,Kh1,Hh1,ku0;var Su0=D(()=>{W1();J1();Wh1=C($$(),1),Kh1=C(Y1(),1),Hh1=C(i0(),1);ku0=class ku0 extends Hh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Kh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Wh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetObjectTagging",{}).n("S3Client","GetObjectTaggingCommand").sc(hM1).build(){}});var Fh1,Uh1,Cu0;var _u0=D(()=>{W1();J1();Fh1=C(Y1(),1),Uh1=C(i0(),1);Cu0=class Cu0 extends Uh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Fh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","GetObjectTorrent",{}).n("S3Client","GetObjectTorrentCommand").sc(uM1).build(){}});var Nh1,Bh1,Oh1,vu0;var bu0=D(()=>{W1();J1();Nh1=C($$(),1),Bh1=C(Y1(),1),Oh1=C(i0(),1);vu0=class vu0 extends Oh1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Bh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Nh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","GetPublicAccessBlock",{}).n("S3Client","GetPublicAccessBlockCommand").sc(lM1).build(){}});var Dh1,Lh1,wh1,Vz;var wn=D(()=>{W1();J1();Dh1=C($$(),1),Lh1=C(Y1(),1),wh1=C(i0(),1);Vz=class Vz extends wh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Lh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Dh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","HeadBucket",{}).n("S3Client","HeadBucketCommand").sc(cM1).build(){}});var fZ0,jh1,Eh1,hH;var jn=D(()=>{R3();W1();J1();fZ0=C($$(),1),jh1=C(Y1(),1),Eh1=C(i0(),1);hH=class hH extends Eh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[jh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),fZ0.getThrow200ExceptionsPlugin(Q),r9(Q),fZ0.getS3ExpiresMiddlewarePlugin(Q)]}).s("AmazonS3","HeadObject",{}).n("S3Client","HeadObjectCommand").sc(mM1).build(){}});var zh1,Ph1,Ah1,xu0;var fu0=D(()=>{W1();J1();zh1=C($$(),1),Ph1=C(Y1(),1),Ah1=C(i0(),1);xu0=class xu0 extends Ah1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ph1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),zh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBucketAnalyticsConfigurations",{}).n("S3Client","ListBucketAnalyticsConfigurationsCommand").sc(dM1).build(){}});var Th1,Rh1,qh1,yu0;var gu0=D(()=>{W1();J1();Th1=C($$(),1),Rh1=C(Y1(),1),qh1=C(i0(),1);yu0=class yu0 extends qh1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Rh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Th1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBucketIntelligentTieringConfigurations",{}).n("S3Client","ListBucketIntelligentTieringConfigurationsCommand").sc(iM1).build(){}});var Mh1,Ih1,Vh1,hu0;var uu0=D(()=>{W1();J1();Mh1=C($$(),1),Ih1=C(Y1(),1),Vh1=C(i0(),1);hu0=class hu0 extends Vh1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ih1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Mh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBucketInventoryConfigurations",{}).n("S3Client","ListBucketInventoryConfigurationsCommand").sc(pM1).build(){}});var kh1,Sh1,Ch1,lu0;var cu0=D(()=>{W1();J1();kh1=C($$(),1),Sh1=C(Y1(),1),Ch1=C(i0(),1);lu0=class lu0 extends Ch1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Sh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),kh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBucketMetricsConfigurations",{}).n("S3Client","ListBucketMetricsConfigurationsCommand").sc(nM1).build(){}});var _h1,vh1,bh1,En;var yZ0=D(()=>{W1();J1();_h1=C($$(),1),vh1=C(Y1(),1),bh1=C(i0(),1);En=class En extends bh1.Command.classBuilder().ep(B0).m(function($,Z,Q,Y){return[vh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),_h1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListBuckets",{}).n("S3Client","ListBucketsCommand").sc(tM1).build(){}});var xh1,fh1,yh1,zn;var gZ0=D(()=>{W1();J1();xh1=C($$(),1),fh1=C(Y1(),1),yh1=C(i0(),1);zn=class zn extends yh1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0}}).m(function($,Z,Q,Y){return[fh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),xh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListDirectoryBuckets",{}).n("S3Client","ListDirectoryBucketsCommand").sc(oM1).build(){}});var gh1,hh1,uh1,mu0;var du0=D(()=>{W1();J1();gh1=C($$(),1),hh1=C(Y1(),1),uh1=C(i0(),1);mu0=class mu0 extends uh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function($,Z,Q,Y){return[hh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),gh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListMultipartUploads",{}).n("S3Client","ListMultipartUploadsCommand").sc(rM1).build(){}});var lh1,ch1,mh1,iu0;var pu0=D(()=>{W1();J1();lh1=C($$(),1),ch1=C(Y1(),1),mh1=C(i0(),1);iu0=class iu0 extends mh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function($,Z,Q,Y){return[ch1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),lh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListObjects",{}).n("S3Client","ListObjectsCommand").sc(sM1).build(){}});var dh1,ih1,ph1,uH;var hZ0=D(()=>{W1();J1();dh1=C($$(),1),ih1=C(Y1(),1),ph1=C(i0(),1);uH=class uH extends ph1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function($,Z,Q,Y){return[ih1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),dh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").sc(aM1).build(){}});var nh1,th1,oh1,nu0;var tu0=D(()=>{W1();J1();nh1=C($$(),1),th1=C(Y1(),1),oh1=C(i0(),1);nu0=class nu0 extends oh1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function($,Z,Q,Y){return[th1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),nh1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","ListObjectVersions",{}).n("S3Client","ListObjectVersionsCommand").sc(eM1).build(){}});var rh1,sh1,ah1,Pn;var uZ0=D(()=>{R3();W1();J1();rh1=C($$(),1),sh1=C(Y1(),1),ah1=C(i0(),1);Pn=class Pn extends ah1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[sh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),rh1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","ListParts",{}).n("S3Client","ListPartsCommand").sc($I1).build(){}});var eh1,$u1,ou0;var ru0=D(()=>{A6();W1();J1();eh1=C(Y1(),1),$u1=C(i0(),1);ou0=class ou0 extends $u1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[eh1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]}).s("AmazonS3","PutBucketAbac",{}).n("S3Client","PutBucketAbacCommand").sc(ZI1).build(){}});var Zu1,Qu1,su0;var au0=D(()=>{A6();W1();J1();Zu1=C(Y1(),1),Qu1=C(i0(),1);su0=class su0 extends Qu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Zu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]}).s("AmazonS3","PutBucketAccelerateConfiguration",{}).n("S3Client","PutBucketAccelerateConfigurationCommand").sc(QI1).build(){}});var Yu1,Xu1,eu0;var $l0=D(()=>{A6();W1();J1();Yu1=C(Y1(),1),Xu1=C(i0(),1);eu0=class eu0 extends Xu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Yu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketAcl",{}).n("S3Client","PutBucketAclCommand").sc(YI1).build(){}});var Ju1,Gu1,Zl0;var Ql0=D(()=>{W1();J1();Ju1=C(Y1(),1),Gu1=C(i0(),1);Zl0=class Zl0 extends Gu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ju1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketAnalyticsConfiguration",{}).n("S3Client","PutBucketAnalyticsConfigurationCommand").sc(XI1).build(){}});var Wu1,Ku1,Yl0;var Xl0=D(()=>{A6();W1();J1();Wu1=C(Y1(),1),Ku1=C(i0(),1);Yl0=class Yl0 extends Ku1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Wu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketCors",{}).n("S3Client","PutBucketCorsCommand").sc(JI1).build(){}});var Hu1,Fu1,Jl0;var Gl0=D(()=>{A6();W1();J1();Hu1=C(Y1(),1),Fu1=C(i0(),1);Jl0=class Jl0 extends Fu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Hu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketEncryption",{}).n("S3Client","PutBucketEncryptionCommand").sc(GI1).build(){}});var Uu1,Nu1,Wl0;var Kl0=D(()=>{W1();J1();Uu1=C(Y1(),1),Nu1=C(i0(),1);Wl0=class Wl0 extends Nu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Uu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketIntelligentTieringConfiguration",{}).n("S3Client","PutBucketIntelligentTieringConfigurationCommand").sc(WI1).build(){}});var Bu1,Ou1,Hl0;var Fl0=D(()=>{W1();J1();Bu1=C(Y1(),1),Ou1=C(i0(),1);Hl0=class Hl0 extends Ou1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Bu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketInventoryConfiguration",{}).n("S3Client","PutBucketInventoryConfigurationCommand").sc(KI1).build(){}});var Du1,Lu1,wu1,Ul0;var Nl0=D(()=>{A6();W1();J1();Du1=C($$(),1),Lu1=C(Y1(),1),wu1=C(i0(),1);Ul0=class Ul0 extends wu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Lu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),Du1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutBucketLifecycleConfiguration",{}).n("S3Client","PutBucketLifecycleConfigurationCommand").sc(HI1).build(){}});var ju1,Eu1,Bl0;var Ol0=D(()=>{A6();W1();J1();ju1=C(Y1(),1),Eu1=C(i0(),1);Bl0=class Bl0 extends Eu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[ju1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketLogging",{}).n("S3Client","PutBucketLoggingCommand").sc(FI1).build(){}});var zu1,Pu1,Dl0;var Ll0=D(()=>{W1();J1();zu1=C(Y1(),1),Pu1=C(i0(),1);Dl0=class Dl0 extends Pu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[zu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketMetricsConfiguration",{}).n("S3Client","PutBucketMetricsConfigurationCommand").sc(UI1).build(){}});var Au1,Tu1,wl0;var jl0=D(()=>{W1();J1();Au1=C(Y1(),1),Tu1=C(i0(),1);wl0=class wl0 extends Tu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Au1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","PutBucketNotificationConfiguration",{}).n("S3Client","PutBucketNotificationConfigurationCommand").sc(NI1).build(){}});var Ru1,qu1,El0;var zl0=D(()=>{A6();W1();J1();Ru1=C(Y1(),1),qu1=C(i0(),1);El0=class El0 extends qu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ru1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketOwnershipControls",{}).n("S3Client","PutBucketOwnershipControlsCommand").sc(BI1).build(){}});var Mu1,Iu1,Pl0;var Al0=D(()=>{A6();W1();J1();Mu1=C(Y1(),1),Iu1=C(i0(),1);Pl0=class Pl0 extends Iu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Mu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketPolicy",{}).n("S3Client","PutBucketPolicyCommand").sc(OI1).build(){}});var Vu1,ku1,Tl0;var Rl0=D(()=>{A6();W1();J1();Vu1=C(Y1(),1),ku1=C(i0(),1);Tl0=class Tl0 extends ku1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Vu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketReplication",{}).n("S3Client","PutBucketReplicationCommand").sc(DI1).build(){}});var Su1,Cu1,ql0;var Ml0=D(()=>{A6();W1();J1();Su1=C(Y1(),1),Cu1=C(i0(),1);ql0=class ql0 extends Cu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Su1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketRequestPayment",{}).n("S3Client","PutBucketRequestPaymentCommand").sc(LI1).build(){}});var _u1,vu1,Il0;var Vl0=D(()=>{A6();W1();J1();_u1=C(Y1(),1),vu1=C(i0(),1);Il0=class Il0 extends vu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[_u1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketTagging",{}).n("S3Client","PutBucketTaggingCommand").sc(wI1).build(){}});var bu1,xu1,kl0;var Sl0=D(()=>{A6();W1();J1();bu1=C(Y1(),1),xu1=C(i0(),1);kl0=class kl0 extends xu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[bu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketVersioning",{}).n("S3Client","PutBucketVersioningCommand").sc(jI1).build(){}});var fu1,yu1,Cl0;var _l0=D(()=>{A6();W1();J1();fu1=C(Y1(),1),yu1=C(i0(),1);Cl0=class Cl0 extends yu1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[fu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutBucketWebsite",{}).n("S3Client","PutBucketWebsiteCommand").sc(EI1).build(){}});var gu1,hu1,uu1,vl0;var bl0=D(()=>{A6();W1();J1();gu1=C($$(),1),hu1=C(Y1(),1),uu1=C(i0(),1);vl0=class vl0 extends uu1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[hu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),gu1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectAcl",{}).n("S3Client","PutObjectAclCommand").sc(PI1).build(){}});var lZ0,lu1,cu1,CN;var xl0=D(()=>{A6();R3();W1();J1();lZ0=C($$(),1),lu1=C(Y1(),1),cu1=C(i0(),1);CN=class CN extends cu1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[lu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),lZ0.getCheckContentLengthHeaderPlugin(Q),lZ0.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").sc(zI1).build(){}});var mu1,du1,iu1,fl0;var yl0=D(()=>{A6();W1();J1();mu1=C($$(),1),du1=C(Y1(),1),iu1=C(i0(),1);fl0=class fl0 extends iu1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[du1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),mu1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectLegalHold",{}).n("S3Client","PutObjectLegalHoldCommand").sc(AI1).build(){}});var pu1,nu1,tu1,gl0;var hl0=D(()=>{A6();W1();J1();pu1=C($$(),1),nu1=C(Y1(),1),tu1=C(i0(),1);gl0=class gl0 extends tu1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[nu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),pu1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectLockConfiguration",{}).n("S3Client","PutObjectLockConfigurationCommand").sc(TI1).build(){}});var ou1,ru1,su1,ul0;var ll0=D(()=>{A6();W1();J1();ou1=C($$(),1),ru1=C(Y1(),1),su1=C(i0(),1);ul0=class ul0 extends su1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[ru1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),ou1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectRetention",{}).n("S3Client","PutObjectRetentionCommand").sc(RI1).build(){}});var au1,eu1,$l1,An;var cl0=D(()=>{A6();W1();J1();au1=C($$(),1),eu1=C(Y1(),1),$l1=C(i0(),1);An=class An extends $l1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[eu1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),au1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","PutObjectTagging",{}).n("S3Client","PutObjectTaggingCommand").sc(qI1).build(){}});var Zl1,Ql1,ml0;var dl0=D(()=>{A6();W1();J1();Zl1=C(Y1(),1),Ql1=C(i0(),1);ml0=class ml0 extends Ql1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Zl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","PutPublicAccessBlock",{}).n("S3Client","PutPublicAccessBlockCommand").sc(MI1).build(){}});var Yl1,Xl1,Jl1,il0;var pl0=D(()=>{W1();J1();Yl1=C($$(),1),Xl1=C(Y1(),1),Jl1=C(i0(),1);il0=class il0 extends Jl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[Xl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Yl1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","RenameObject",{}).n("S3Client","RenameObjectCommand").sc(II1).build(){}});var Gl1,Wl1,Kl1,nl0;var tl0=D(()=>{A6();W1();J1();Gl1=C($$(),1),Wl1=C(Y1(),1),Kl1=C(i0(),1);nl0=class nl0 extends Kl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Wl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),Gl1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","RestoreObject",{}).n("S3Client","RestoreObjectCommand").sc(VI1).build(){}});var Hl1,Fl1,ol0;var rl0=D(()=>{R3();W1();J1();Hl1=C(Y1(),1),Fl1=C(i0(),1);ol0=class ol0 extends Fl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Hl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),r9(Q)]}).s("AmazonS3","SelectObjectContent",{eventStream:{output:!0}}).n("S3Client","SelectObjectContentCommand").sc(kI1).build(){}});var Ul1,Nl1,sl0;var al0=D(()=>{A6();W1();J1();Ul1=C(Y1(),1),Nl1=C(i0(),1);sl0=class sl0 extends Nl1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ul1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","UpdateBucketMetadataInventoryTableConfiguration",{}).n("S3Client","UpdateBucketMetadataInventoryTableConfigurationCommand").sc(SI1).build(){}});var Bl1,Ol1,el0;var $c0=D(()=>{A6();W1();J1();Bl1=C(Y1(),1),Ol1=C(i0(),1);el0=class el0 extends Ol1.Command.classBuilder().ep({...B0,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Bl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]}).s("AmazonS3","UpdateBucketMetadataJournalTableConfiguration",{}).n("S3Client","UpdateBucketMetadataJournalTableConfigurationCommand").sc(CI1).build(){}});var Dl1,Ll1,wl1,Zc0;var Qc0=D(()=>{A6();W1();J1();Dl1=C($$(),1),Ll1=C(Y1(),1),wl1=C(i0(),1);Zc0=class Zc0 extends wl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Ll1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),Dl1.getThrow200ExceptionsPlugin(Q)]}).s("AmazonS3","UpdateObjectEncryption",{}).n("S3Client","UpdateObjectEncryptionCommand").sc(_I1).build(){}});var jl1,El1,zl1,Tn;var Yc0=D(()=>{A6();R3();W1();J1();jl1=C($$(),1),El1=C(Y1(),1),zl1=C(i0(),1);Tn=class Tn extends zl1.Command.classBuilder().ep({...B0,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function($,Z,Q,Y){return[El1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),y$(Q,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),jl1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","UploadPart",{}).n("S3Client","UploadPartCommand").sc(vI1).build(){}});var Pl1,Al1,Tl1,Xc0;var Jc0=D(()=>{R3();W1();J1();Pl1=C($$(),1),Al1=C(Y1(),1),Tl1=C(i0(),1);Xc0=class Xc0 extends Tl1.Command.classBuilder().ep({...B0,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function($,Z,Q,Y){return[Al1.getEndpointPlugin(Q,$.getEndpointParameterInstructions()),Pl1.getThrow200ExceptionsPlugin(Q),r9(Q)]}).s("AmazonS3","UploadPartCopy",{}).n("S3Client","UploadPartCopyCommand").sc(bI1).build(){}});var Rl1,ql1,Gc0;var Wc0=D(()=>{W1();J1();Rl1=C(Y1(),1),ql1=C(i0(),1);Gc0=class Gc0 extends ql1.Command.classBuilder().ep({...B0,UseObjectLambdaEndpoint:{type:"staticContextParams",value:!0}}).m(function($,Z,Q,Y){return[Rl1.getEndpointPlugin(Q,$.getEndpointParameterInstructions())]}).s("AmazonS3","WriteGetObjectResponse",{}).n("S3Client","WriteGetObjectResponseCommand").sc(xI1).build(){}});var Ml1,Il1;var Kc0=D(()=>{yZ0();Mz();Ml1=C(X7(),1),Il1=Ml1.createPaginator(eY,En,"ContinuationToken","ContinuationToken","MaxBuckets")});var Vl1,kl1;var Hc0=D(()=>{gZ0();Mz();Vl1=C(X7(),1),kl1=Vl1.createPaginator(eY,zn,"ContinuationToken","ContinuationToken","MaxDirectoryBuckets")});var Sl1,Cl1;var Fc0=D(()=>{hZ0();Mz();Sl1=C(X7(),1),Cl1=Sl1.createPaginator(eY,uH,"ContinuationToken","NextContinuationToken","MaxKeys")});var _l1,vl1;var Uc0=D(()=>{uZ0();Mz();_l1=C(X7(),1),vl1=_l1.createPaginator(eY,Pn,"PartNumberMarker","NextPartNumberMarker","MaxParts")});var cg=()=>{let $=new WeakSet;return(Z,Q)=>{if(typeof Q==="object"&&Q!==null){if($.has(Q))return"[Circular]";$.add(Q)}return Q}};var bl1=($)=>{return new Promise((Z)=>setTimeout(Z,$*1000))};var xl1,J9,ID=($)=>{if($.state===J9.ABORTED){let Z=Error(`${JSON.stringify({...$,reason:"Request was aborted"},cg())}`);throw Z.name="AbortError",Z}else if($.state===J9.TIMEOUT){let Z=Error(`${JSON.stringify({...$,reason:"Waiter has timed out"},cg())}`);throw Z.name="TimeoutError",Z}else if($.state!==J9.SUCCESS)throw Error(`${JSON.stringify($,cg())}`);return $};var cZ0=D(()=>{xl1={minDelay:2,maxDelay:120};(function($){$.ABORTED="ABORTED",$.FAILURE="FAILURE",$.SUCCESS="SUCCESS",$.RETRY="RETRY",$.TIMEOUT="TIMEOUT"})(J9||(J9={}))});var fl1=async({minDelay:$,maxDelay:Z,maxWaitTime:Q,abortController:Y,client:X,abortSignal:J},G,W)=>{let K={},[H,F]=[$*1000,Z*1000],U=0,N=Date.now()+Q*1000,B=Date.now()+60000,O=!1;while(!0){if(U>0){let j=bh8(H,F,U,N);if(Y?.signal?.aborted||J?.aborted)return K["AbortController signal aborted."]|=0,K["AbortController signal aborted."]+=1,{state:J9.ABORTED,observedResponses:K};if(Date.now()+j>N)return{state:J9.TIMEOUT,observedResponses:K};await bl1(j/1000)}let{state:L,reason:w}=await W(X,G);if(w){let j=vh8(w);K[j]|=0,K[j]+=1}if(L!==J9.RETRY)return{state:L,reason:w,final:w,observedResponses:K};if(U+=1,!O&&Date.now()>=B)_h8(K,X),O=!0}},_h8=($={},Z)=>{let Q=Object.keys($),Y=0,X=0;for(let W of Q){let K=$[W]|0;if(Y=Math.max(K,Y),W.startsWith("403:"))X+=K}let J=Z?.config?.logger,G=typeof J?.warn==="function"&&!J.constructor?.name?.includes?.("NoOpLogger")?J:console;if(X>=3||Q[Q.length-1].startsWith("403:"))G.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},vh8=($)=>{let Z=$?.$response?.statusCode??$?.$metadata?.httpStatusCode;if($?.$responseBodyText)return`${Z?Z+": ":""}Deserialization error for body: ${$.$responseBodyText}`;if(Z){if($?.$response||$?.message)return`${Z??"Unknown"}: ${$?.message}`;return`${Z}: OK`}return String($?.message??JSON.stringify($,cg())??"Unknown")},bh8=($,Z,Q,Y)=>{let X=Math.log(Z/$)/Math.log(2)+1;if(Q>X)return Z;let J=$*2**(Q-1),G=Math.min(J,Z),W=xh8($,G);if(Date.now()+W>Y){let K=Y-Date.now();return Math.max(0,K-500)}return W},xh8=($,Z)=>$+Math.random()*(Z-$);var yl1=D(()=>{cZ0()});var gl1=($)=>{if($.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if($.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if($.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if($.maxWaitTime<=$.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${$.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${$.minDelay}] for this waiter`);else if($.maxDelay<$.minDelay)throw Error(`WaiterConfiguration.maxDelay [${$.maxDelay}] must be greater than WaiterConfiguration.minDelay [${$.minDelay}] for this waiter`)};var hl1=()=>{};var ul1=($)=>{let Z,Q=new Promise((Y)=>{if(Z=()=>Y({state:J9.ABORTED}),typeof $.addEventListener==="function")$.addEventListener("abort",Z);else $.onabort=Z});return{clearListener(){if(typeof $.removeEventListener==="function")$.removeEventListener("abort",Z)},aborted:Q}},VD=async($,Z,Q)=>{let Y={...xl1,...$};gl1(Y);let X=[fl1(Y,Z,Q)],J=[];if($.abortSignal){let{aborted:G,clearListener:W}=ul1($.abortSignal);J.push(W),X.push(G)}if($.abortController?.signal){let{aborted:G,clearListener:W}=ul1($.abortController.signal);J.push(W),X.push(G)}return Promise.race(X).then((G)=>{for(let W of J)W();return G})};var ll1=D(()=>{yl1();hl1();cZ0()});var Rn=D(()=>{ll1();cZ0()});var fh8=async($,Z)=>{let Q;try{return Q=await $.send(new Vz(Z)),{state:J9.SUCCESS,reason:Q}}catch(Y){if(Q=Y,Y.name==="NotFound")return{state:J9.RETRY,reason:Q}}return{state:J9.RETRY,reason:Q}},cl1=async($,Z)=>{let Y=await VD({...{minDelay:5,maxDelay:120},...$},Z,fh8);return ID(Y)};var Nc0=D(()=>{Rn();wn()});var yh8=async($,Z)=>{let Q;try{Q=await $.send(new Vz(Z))}catch(Y){if(Q=Y,Y.name==="NotFound")return{state:J9.SUCCESS,reason:Q}}return{state:J9.RETRY,reason:Q}},ml1=async($,Z)=>{let Y=await VD({...{minDelay:5,maxDelay:120},...$},Z,yh8);return ID(Y)};var Bc0=D(()=>{Rn();wn()});var gh8=async($,Z)=>{let Q;try{return Q=await $.send(new hH(Z)),{state:J9.SUCCESS,reason:Q}}catch(Y){if(Q=Y,Y.name==="NotFound")return{state:J9.RETRY,reason:Q}}return{state:J9.RETRY,reason:Q}},dl1=async($,Z)=>{let Y=await VD({...{minDelay:5,maxDelay:120},...$},Z,gh8);return ID(Y)};var Oc0=D(()=>{Rn();jn()});var hh8=async($,Z)=>{let Q;try{Q=await $.send(new hH(Z))}catch(Y){if(Q=Y,Y.name==="NotFound")return{state:J9.SUCCESS,reason:Q}}return{state:J9.RETRY,reason:Q}},il1=async($,Z)=>{let Y=await VD({...{minDelay:5,maxDelay:120},...$},Z,hh8);return ID(Y)};var Dc0=D(()=>{Rn();jn()});var pl1,uh8,lh8,ch8,nl1;var tl1=D(()=>{_g0();vg0();xg0();yg0();hg0();lg0();cg0();E90();dg0();pg0();tg0();rg0();ag0();$h0();Qh0();Xh0();Gh0();Kh0();Fh0();Nh0();Oh0();Lh0();jh0();Eh0();Ph0();Th0();qh0();Ih0();kh0();Ch0();vh0();xh0();yh0();hh0();lh0();mh0();ih0();nh0();oh0();sh0();eh0();Zu0();Yu0();Ju0();Wu0();Hu0();Uu0();Bu0();Du0();wu0();Eu0();Pu0();Au0();Ru0();Mu0();Vu0();Su0();_u0();bu0();wn();jn();fu0();gu0();uu0();cu0();yZ0();gZ0();du0();pu0();hZ0();tu0();uZ0();ru0();au0();$l0();Ql0();Xl0();Gl0();Kl0();Fl0();Nl0();Ol0();Ll0();jl0();zl0();Al0();Rl0();Ml0();Vl0();Sl0();_l0();bl0();xl0();yl0();hl0();ll0();cl0();dl0();pl0();tl0();rl0();al0();$c0();Qc0();Yc0();Jc0();Wc0();Kc0();Hc0();Fc0();Uc0();Mz();Nc0();Bc0();Oc0();Dc0();pl1=C(i0(),1),uh8={AbortMultipartUploadCommand:On,CompleteMultipartUploadCommand:Dn,CopyObjectCommand:bg0,CreateBucketCommand:fg0,CreateBucketMetadataConfigurationCommand:gg0,CreateBucketMetadataTableConfigurationCommand:ug0,CreateMultipartUploadCommand:Ln,CreateSessionCommand:np,DeleteBucketCommand:ig0,DeleteBucketAnalyticsConfigurationCommand:mg0,DeleteBucketCorsCommand:ng0,DeleteBucketEncryptionCommand:og0,DeleteBucketIntelligentTieringConfigurationCommand:sg0,DeleteBucketInventoryConfigurationCommand:eg0,DeleteBucketLifecycleCommand:Zh0,DeleteBucketMetadataConfigurationCommand:Yh0,DeleteBucketMetadataTableConfigurationCommand:Jh0,DeleteBucketMetricsConfigurationCommand:Wh0,DeleteBucketOwnershipControlsCommand:Hh0,DeleteBucketPolicyCommand:Uh0,DeleteBucketReplicationCommand:Bh0,DeleteBucketTaggingCommand:Dh0,DeleteBucketWebsiteCommand:wh0,DeleteObjectCommand:Iz,DeleteObjectsCommand:zh0,DeleteObjectTaggingCommand:Ah0,DeletePublicAccessBlockCommand:Rh0,GetBucketAbacCommand:Mh0,GetBucketAccelerateConfigurationCommand:Vh0,GetBucketAclCommand:Sh0,GetBucketAnalyticsConfigurationCommand:_h0,GetBucketCorsCommand:bh0,GetBucketEncryptionCommand:fh0,GetBucketIntelligentTieringConfigurationCommand:gh0,GetBucketInventoryConfigurationCommand:uh0,GetBucketLifecycleConfigurationCommand:ch0,GetBucketLocationCommand:dh0,GetBucketLoggingCommand:ph0,GetBucketMetadataConfigurationCommand:th0,GetBucketMetadataTableConfigurationCommand:rh0,GetBucketMetricsConfigurationCommand:ah0,GetBucketNotificationConfigurationCommand:$u0,GetBucketOwnershipControlsCommand:Qu0,GetBucketPolicyCommand:Xu0,GetBucketPolicyStatusCommand:Gu0,GetBucketReplicationCommand:Ku0,GetBucketRequestPaymentCommand:Fu0,GetBucketTaggingCommand:Nu0,GetBucketVersioningCommand:Ou0,GetBucketWebsiteCommand:Lu0,GetObjectCommand:MD,GetObjectAclCommand:ju0,GetObjectAttributesCommand:zu0,GetObjectLegalHoldCommand:Tu0,GetObjectLockConfigurationCommand:qu0,GetObjectRetentionCommand:Iu0,GetObjectTaggingCommand:ku0,GetObjectTorrentCommand:Cu0,GetPublicAccessBlockCommand:vu0,HeadBucketCommand:Vz,HeadObjectCommand:hH,ListBucketAnalyticsConfigurationsCommand:xu0,ListBucketIntelligentTieringConfigurationsCommand:yu0,ListBucketInventoryConfigurationsCommand:hu0,ListBucketMetricsConfigurationsCommand:lu0,ListBucketsCommand:En,ListDirectoryBucketsCommand:zn,ListMultipartUploadsCommand:mu0,ListObjectsCommand:iu0,ListObjectsV2Command:uH,ListObjectVersionsCommand:nu0,ListPartsCommand:Pn,PutBucketAbacCommand:ou0,PutBucketAccelerateConfigurationCommand:su0,PutBucketAclCommand:eu0,PutBucketAnalyticsConfigurationCommand:Zl0,PutBucketCorsCommand:Yl0,PutBucketEncryptionCommand:Jl0,PutBucketIntelligentTieringConfigurationCommand:Wl0,PutBucketInventoryConfigurationCommand:Hl0,PutBucketLifecycleConfigurationCommand:Ul0,PutBucketLoggingCommand:Bl0,PutBucketMetricsConfigurationCommand:Dl0,PutBucketNotificationConfigurationCommand:wl0,PutBucketOwnershipControlsCommand:El0,PutBucketPolicyCommand:Pl0,PutBucketReplicationCommand:Tl0,PutBucketRequestPaymentCommand:ql0,PutBucketTaggingCommand:Il0,PutBucketVersioningCommand:kl0,PutBucketWebsiteCommand:Cl0,PutObjectCommand:CN,PutObjectAclCommand:vl0,PutObjectLegalHoldCommand:fl0,PutObjectLockConfigurationCommand:gl0,PutObjectRetentionCommand:ul0,PutObjectTaggingCommand:An,PutPublicAccessBlockCommand:ml0,RenameObjectCommand:il0,RestoreObjectCommand:nl0,SelectObjectContentCommand:ol0,UpdateBucketMetadataInventoryTableConfigurationCommand:sl0,UpdateBucketMetadataJournalTableConfigurationCommand:el0,UpdateObjectEncryptionCommand:Zc0,UploadPartCommand:Tn,UploadPartCopyCommand:Xc0,WriteGetObjectResponseCommand:Gc0},lh8={paginateListBuckets:Il1,paginateListDirectoryBuckets:kl1,paginateListObjectsV2:Cl1,paginateListParts:vl1},ch8={waitUntilBucketExists:cl1,waitUntilBucketNotExists:ml1,waitUntilObjectExists:dl1,waitUntilObjectNotExists:il1};nl1=class nl1 extends eY{};pl1.createAggregatedClient(uh8,nl1,{paginators:lh8,waiters:ch8})});var ol1=D(()=>{_g0();vg0();xg0();yg0();hg0();lg0();cg0();E90();dg0();pg0();tg0();rg0();ag0();$h0();Qh0();Xh0();Gh0();Kh0();Fh0();Nh0();Oh0();Lh0();jh0();Eh0();Th0();Ph0();qh0();Ih0();kh0();Ch0();vh0();xh0();yh0();hh0();lh0();mh0();ih0();nh0();oh0();sh0();eh0();Zu0();Yu0();Ju0();Wu0();Hu0();Uu0();Bu0();Du0();wu0();Eu0();Pu0();Au0();Ru0();Mu0();Vu0();Su0();_u0();bu0();wn();jn();fu0();gu0();uu0();cu0();yZ0();gZ0();du0();tu0();pu0();hZ0();uZ0();ru0();au0();$l0();Ql0();Xl0();Gl0();Kl0();Fl0();Nl0();Ol0();Ll0();jl0();zl0();Al0();Rl0();Ml0();Vl0();Sl0();_l0();bl0();xl0();yl0();hl0();ll0();cl0();dl0();pl0();tl0();rl0();al0();$c0();Qc0();Yc0();Jc0();Wc0()});var rl1=()=>{};var sl1=D(()=>{rl1();Kc0();Hc0();Fc0();Uc0()});var al1=D(()=>{Nc0();Bc0();Oc0();Dc0()});var el1;var $c1=D(()=>{el1={CRC32:"CRC32",CRC32C:"CRC32C",CRC64NVME:"CRC64NVME",MD5:"MD5",SHA1:"SHA1",SHA256:"SHA256",SHA512:"SHA512",XXHASH128:"XXHASH128",XXHASH3:"XXHASH3",XXHASH64:"XXHASH64"}});var Zc1=()=>{};var Qc1=()=>{};var mZ0=D(()=>{Mz();tl1();ol1();J1();sl1();al1();$c1();cx0();Zc1();Qc1()});function Xc1($){let{port:Z,query:Q}=$,{protocol:Y,path:X,hostname:J}=$;if(Y&&Y.slice(-1)!==":")Y+=":";if(Z)J+=`:${Z}`;if(X&&X.charAt(0)!=="/")X=`/${X}`;let G=Q?Yc1.buildQueryString(Q):"";if(G&&G[0]!=="?")G=`?${G}`;let W="";if($.username!=null||$.password!=null){let H=$.username??"",F=$.password??"";W=`${H}:${F}@`}let K="";if($.fragment)K=`#${$.fragment}`;return`${Y}//${W}${J}${X}${G}${K}`}var Yc1;var Jc1=D(()=>{Yc1=C(R60(),1)});var Gc1="UNSIGNED-PAYLOAD",Wc1="X-Amz-Content-Sha256";class dZ0{signer;constructor($){let Z={service:$.signingName||$.service||"s3",uriEscapePath:$.uriEscapePath||!1,applyChecksum:$.applyChecksum||!1,...$};this.signer=new Kc1.SignatureV4MultiRegion(Z)}presign($,{unsignableHeaders:Z=new Set,hoistableHeaders:Q=new Set,unhoistableHeaders:Y=new Set,...X}={}){return this.prepareRequest($,{unsignableHeaders:Z,unhoistableHeaders:Y,hoistableHeaders:Q}),this.signer.presign($,{expiresIn:900,unsignableHeaders:Z,unhoistableHeaders:Y,...X})}presignWithCredentials($,Z,{unsignableHeaders:Q=new Set,hoistableHeaders:Y=new Set,unhoistableHeaders:X=new Set,...J}={}){return this.prepareRequest($,{unsignableHeaders:Q,unhoistableHeaders:X,hoistableHeaders:Y}),this.signer.presignWithCredentials($,Z,{expiresIn:900,unsignableHeaders:Q,unhoistableHeaders:X,...J})}prepareRequest($,{unsignableHeaders:Z=new Set,unhoistableHeaders:Q=new Set,hoistableHeaders:Y=new Set}={}){Z.add("content-type"),Object.keys($.headers).map((W)=>W.toLowerCase()).filter((W)=>W.startsWith("x-amz-server-side-encryption")).forEach((W)=>{if(!Y.has(W))Q.add(W)}),$.headers[Wc1]=Gc1;let X=$.headers.host,J=$.port,G=`${$.hostname}${$.port!=null?":"+J:""}`;if(!X||X===$.hostname&&$.port!=null)$.headers.host=G}}var Kc1;var Lc0=D(()=>{Kc1=C(Eg(),1)});var Hc1,Fc1,iZ0=async($,Z,Q={})=>{let Y,X;if(typeof $.config.endpointProvider==="function"){let N=(await Hc1.getEndpointFromInstructions(Z.input,Z.constructor,$.config)).properties?.authSchemes?.[0];if(N?.name==="sigv4a")X=N?.signingRegionSet?.join(",");else X=N?.signingRegion;Y=new dZ0({...$.config,signingName:N?.signingName,region:async()=>X})}else Y=new dZ0($.config);let J=(U,N)=>async(B)=>{let{request:O}=B;if(!Fc1.HttpRequest.isInstance(O))throw Error("Request to be presigned is not an valid HTTP request.");delete O.headers["amz-sdk-invocation-id"],delete O.headers["amz-sdk-request"],delete O.headers["x-amz-user-agent"];let L,w={...Q,signingRegion:Q.signingRegion??N.signing_region??X,signingService:Q.signingService??N.signing_service};if(N.s3ExpressIdentity)L=await Y.presignWithCredentials(O,N.s3ExpressIdentity,w);else L=await Y.presign(O,w);return{response:{},output:{$metadata:{httpStatusCode:200},presigned:L}}},G="presignInterceptMiddleware",W=$.middlewareStack.clone();W.addRelativeTo(J,{name:G,relation:"before",toMiddleware:"awsAuthMiddleware",override:!0});let K=Z.resolveMiddleware(W,$.config,{}),{output:H}=await K({input:Z.input}),{presigned:F}=H;return Xc1(F)};var Uc1=D(()=>{Jc1();Lc0();Hc1=C(Y1(),1),Fc1=C(v5(),1)});var Nc1=D(()=>{Uc1();Lc0()});import{extname as mh8}from"path";function q3($){let Z;try{Z=decodeURIComponent($)}catch{Z=$}let Y=Z.replace(/\0/g,"").replace(/[\x00-\x1f\x7f]/g,"").replace(/\\/g,"/").split("/"),X=[];for(let J of Y)if(J==="..")X.pop();else if(J!=="."&&J!=="")X.push(J);return X.join("/")}function kD($,Z){let Q=q3(Z);if(!Q)throw Error("Key is empty after sanitization");return`${$}/${Q}`}function Bc1($,Z){if(!Z)return`${$}/`;let Q=q3(Z);return`${$}/${Q}${Q.endsWith("/")?"":"/"}`}function mg($,Z,Q){let Y=Q.split("/").map(encodeURIComponent).join("/");return`${$}/api/${encodeURIComponent(Z)}/files/${Y}`}function wc0($,Z){let Q=`${$}/`;if(Z.startsWith(Q))return Z.slice(Q.length);return Z}function v7($){let Z=mh8($).toLowerCase();return dh8[Z]??"application/octet-stream"}function pZ0($){let Z=$.split(";")[0].trim();if(ih8.has(Z))return!0;if(Z.startsWith("text/"))return!0;return!1}var dh8,ih8;var YK=D(()=>{dh8={".json":"application/json",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"application/javascript",".mjs":"application/javascript",".ts":"text/typescript",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".xml":"application/xml",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".pdf":"application/pdf",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".wasm":"application/wasm",".yaml":"application/yaml",".yml":"application/yaml",".toml":"application/toml"};ih8=new Set(["application/json","text/html","text/css","application/javascript","text/typescript","text/plain","text/markdown","text/csv","application/xml","image/svg+xml","application/yaml","application/toml"])});class jc0{client;bucket;constructor($){this.bucket=$.bucket,this.client=new eY({endpoint:$.endpoint,region:$.region,credentials:{accessKeyId:$.accessKeyId,secretAccessKey:$.secretAccessKey},forcePathStyle:$.forcePathStyle})}async getBytesOrPresign($,Z,Q){let Y=kD($,Z),X=await this.client.send(new hH({Bucket:this.bucket,Key:Y})),J=X.ContentLength??0,G=X.ContentType??v7(Z);if(J>Q.presignWhenLargerThan){let F=await iZ0(this.client,new MD({Bucket:this.bucket,Key:Y}),{expiresIn:Q.presignExpiresIn??3600});return{error:"FILE_TOO_LARGE",size:J,maxInlineSize:Q.presignWhenLargerThan,presignedUrl:F,contentType:G}}let K=await(await this.client.send(new MD({Bucket:this.bucket,Key:Y}))).Body.transformToByteArray(),H=pZ0(G);return{content:H?new TextDecoder().decode(K):Buffer.from(K).toString("base64"),contentType:G,encoding:H?"utf-8":"base64",size:J,lastModified:X.LastModified,etag:X.ETag}}async getBytes($,Z){let Q=kD($,Z);return(await this.client.send(new MD({Bucket:this.bucket,Key:Q}))).Body.transformToByteArray()}async put($,Z,Q,Y){let X=kD($,Z),J=Y?.contentType??v7(Z);return{etag:(await this.client.send(new CN({Bucket:this.bucket,Key:X,Body:typeof Q==="string"?Buffer.from(Q,"utf-8"):Q,ContentType:J}))).ETag,key:Z}}async list($,Z){let Q=Bc1($,Z?.prefix),Y=await this.client.send(new uH({Bucket:this.bucket,Prefix:Q,MaxKeys:Z?.maxKeys??1000,ContinuationToken:Z?.continuationToken,Delimiter:Z?.delimiter})),X=Y.CommonPrefixes?.map((J)=>wc0($,J.Prefix??"")).filter(Boolean);return{objects:(Y.Contents??[]).map((J)=>({key:wc0($,J.Key??""),size:J.Size??0,lastModified:J.LastModified,etag:J.ETag})),isTruncated:Y.IsTruncated??!1,nextContinuationToken:Y.NextContinuationToken,commonPrefixes:X&&X.length>0?X:void 0}}async delete($,Z){let Q=kD($,Z);await this.client.send(new Iz({Bucket:this.bucket,Key:Q}))}async head($,Z){let Q=kD($,Z),Y=await this.client.send(new hH({Bucket:this.bucket,Key:Q}));return{contentType:Y.ContentType??v7(Z),size:Y.ContentLength??0,lastModified:Y.LastModified,etag:Y.ETag,metadata:Y.Metadata&&Object.keys(Y.Metadata).length>0?Y.Metadata:void 0}}async presignedGetUrl($,Z,Q=3600,Y){let X=kD($,Z);return iZ0(this.client,new MD({Bucket:this.bucket,Key:X}),{expiresIn:Q})}async presignedPutUrl($,Z,Q=3600,Y){let X=kD($,Z);return iZ0(this.client,new CN({Bucket:this.bucket,Key:X,ContentType:Y}),{expiresIn:Q})}}var Oc1=D(()=>{mZ0();Nc1();YK()});function ph8(){let $=E0();return!!($.s3Endpoint&&$.s3Bucket&&$.s3AccessKeyId&&$.s3SecretAccessKey)}function $X(){if(qn!==void 0)return qn;if(!ph8())return qn=null,null;let $=E0();return qn=new jc0({endpoint:$.s3Endpoint,bucket:$.s3Bucket,region:$.s3Region,accessKeyId:$.s3AccessKeyId,secretAccessKey:$.s3SecretAccessKey,forcePathStyle:$.s3ForcePathStyle}),qn}var qn;var SD=D(()=>{F$();Oc1()});function KG($,Z){return{getBytesOrPresign:(Q,Y)=>$.getBytesOrPresign(Z,Q,Y),getBytes:(Q)=>$.getBytes(Z,Q),put:(Q,Y,X)=>$.put(Z,Q,Y,X),list:(Q)=>$.list(Z,Q),delete:(Q)=>$.delete(Z,Q),head:(Q)=>$.head(Z,Q),presignedGetUrl:(Q,Y,X)=>$.presignedGetUrl(Z,Q,Y,X),presignedPutUrl:(Q,Y,X)=>$.presignedPutUrl(Z,Q,Y,X)}}import{mkdir as nh8,readdir as th8,readFile as Ec0,stat as nZ0,unlink as oh8,writeFile as rh8}from"fs/promises";import{createHmac as sh8}from"crypto";import{dirname as ah8,join as Mn}from"path";function zc0($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return Mn(eh8,Z)}function dg($,Z){return Mn(zc0($),q3(Z))}class M3{orgId;baseUrl;constructor($,Z){this.orgId=$;this.baseUrl=Z}async getBytesOrPresign($,Z){let Q=dg(this.orgId,$),Y=await nZ0(Q),X=v7($);if(Y.size>Z.presignWhenLargerThan)return{error:"FILE_TOO_LARGE",size:Y.size,maxInlineSize:Z.presignWhenLargerThan,presignedUrl:await this.presignedGetUrl($),contentType:X};let J=await Ec0(Q),G=pZ0(X);return{content:G?new TextDecoder().decode(J):Buffer.from(J).toString("base64"),contentType:X,encoding:G?"utf-8":"base64",size:Y.size,lastModified:Y.mtime}}async getBytes($){let Z=await Ec0(dg(this.orgId,$));return new Uint8Array(Z)}async put($,Z,Q){let Y=dg(this.orgId,$);return await nh8(ah8(Y),{recursive:!0}),await rh8(Y,typeof Z==="string"?Buffer.from(Z,"utf-8"):Z),{key:$}}async list($){let Z=$?.prefix?Mn(zc0(this.orgId),q3($.prefix)):zc0(this.orgId),Q;try{Q=await th8(Z,{withFileTypes:!0})}catch{return{objects:[],isTruncated:!1}}let Y=$?.maxKeys??1000,X=$?.prefix,J=Q.filter((W)=>W.isFile());if($?.delimiter){let W=[],K=Q.filter((O)=>O.isDirectory());for(let O of K){let L=X?`${X}/${O.name}/`:`${O.name}/`;W.push(L)}W.sort();let H=Y,F=W.slice(0,H);H-=F.length;let U=J.slice(0,H),N=W.length+J.length;return{objects:await Promise.all(U.map(async(O)=>{let L=await nZ0(Mn(Z,O.name));return{key:X?`${X}/${O.name}`:O.name,size:L.size,lastModified:L.mtime}})),isTruncated:N>Y,commonPrefixes:F.length>0?F:void 0}}return{objects:await Promise.all(J.slice(0,Y).map(async(W)=>{let K=await nZ0(Mn(Z,W.name));return{key:X?`${X}/${W.name}`:W.name,size:K.size,lastModified:K.mtime}})),isTruncated:J.length>Y}}async delete($){await oh8(dg(this.orgId,$))}async head($){let Z=await nZ0(dg(this.orgId,$));return{contentType:v7($),size:Z.size,lastModified:Z.mtime}}async presignedGetUrl($,Z,Q){if(Q?.requireFetchable)throw Error("object storage returned a not fetchable (data:) URL; configure real S3/R2/MinIO for large-payload offload");let Y=dg(this.orgId,$),X=await Ec0(Y),J=v7($),G=Buffer.from(X).toString("base64");return`data:${J};base64,${G}`}async presignedPutUrl($,Z=3600){if(!this.baseUrl)throw Error("baseUrl required for presigned PUT URLs in dev mode");let Q=q3($),Y=Math.floor(Date.now()/1000)+Z,X=E0().encryptionKey||"dev-secret",J=`${this.orgId}:${Q}:${Y}:PUT`,G=sh8("sha256",X).update(J).digest("hex"),W=new URL(`/api/dev-assets/${this.orgId}/${Q}`,this.baseUrl);return W.searchParams.set("expires",Y.toString()),W.searchParams.set("signature",G),W.searchParams.set("method","PUT"),W.toString()}}var eh8="./data/assets";var ig=D(()=>{YK();F$()});function lH($){return $u8.test($)&&$!=="."&&$!==".."}function G7($){if(!lH($))throw Error(`Invalid org-fs volume name: ${JSON.stringify($)}`)}function b7($){return q3($)}function pg($){let Z=$.lastIndexOf("/");return Z===-1?"":$.slice(0,Z)}function CD($){let Z=pg($);if(Z==="")return[];let Q=Z.split("/"),Y=[],X="";for(let J of Q)X=X===""?J:`${X}/${J}`,Y.push(X);return Y}function cH($,Z){return`${Dc1}/${$}/${Z}`}function tZ0($){return`${Dc1}/${$}/`}var $u8,Dc1="_fs";var kz=D(()=>{YK();$u8=/^[A-Za-z0-9_.-]{1,128}$/});import{createHmac as Pc0,randomBytes as Ac0,scrypt as Zu8,timingSafeEqual as Lc1}from"crypto";import{promisify as Qu8}from"util";async function jc1($){let Z=Ac0(16),Q=await wc1($,Z,Yu8);return`scrypt$${Z.toString("hex")}$${Q.toString("hex")}`}async function Ec1($,Z){let Q=Z.split("$");if(Q.length!==3||Q[0]!=="scrypt")return!1;let Y=Buffer.from(Q[1],"hex"),X=Buffer.from(Q[2],"hex");if(Y.length===0||X.length===0)return!1;let J;try{J=await wc1($,Y,X.length)}catch{return!1}return X.length===J.length&&Lc1(X,J)}function zc1(){return Ac0(16).toString("hex")}function Pc1(){if(oZ0)return oZ0;let $;try{let Z=E0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return oZ0=$?Buffer.from($):Ac0(32),oZ0}function Ac1($){let Z=Buffer.from(JSON.stringify($)).toString("base64url"),Q=Pc0("sha256",Pc1()).update(Z).digest("base64url");return`${Z}.${Q}`}function Tc1($,Z){let Q=$.indexOf(".");if(Q<0)return null;let Y=$.slice(0,Q),X=Buffer.from($.slice(Q+1)),J=Buffer.from(Pc0("sha256",Pc1()).update(Y).digest("base64url"));if(X.length!==J.length||!Lc1(X,J))return null;let G;try{G=JSON.parse(Buffer.from(Y,"base64url").toString())}catch{return null}if(G.o!==Z.org||G.v!==Z.volume||G.s!==Z.secret||typeof G.e!=="number"||G.e<Z.nowSec)return null;return{govPath:G.p}}function Tc0($,Z,Q){return`fsu_${Pc0("sha256","fsunlock-name").update(`${$}:${Z}:${Q}`).digest("hex").slice(0,16)}`}var Yu8=64,wc1,oZ0=null;var Rc0=D(()=>{F$();wc1=Qu8(Zu8)});import{createHash as Xu8}from"crypto";function Hu8($){if(typeof $!=="object"||$===null)return!1;let Z=$;return Z.name==="NoSuchKey"||Z.Code==="NoSuchKey"||Z.code==="ENOENT"||Z.$metadata?.httpStatusCode===404}function Rc1($){return Xu8("sha256").update($).digest("hex")}class I3{storage;manifest;organizationId;maxFileBytes;volumeQuotaBytes;constructor($,Z,Q,Y={}){this.storage=$;this.manifest=Z;this.organizationId=Q;this.maxFileBytes=Y.maxFileBytes??Wu8,this.volumeQuotaBytes=Y.volumeQuotaBytes??Ku8}async usage($){return G7($),this.manifest.usage(this.organizationId,$)}async stat($,Z){return G7($),this.manifest.get(this.organizationId,$,b7(Z))}async listVolumeFiles($){return G7($),this.manifest.listVolumeFiles(this.organizationId,$)}async listDir($,Z){return G7($),this.manifest.listDir(this.organizationId,$,b7(Z))}async read($,Z){let Q=await this.requireFile($,Z);try{return await this.storage.getBytes(cH($,Q.path))}catch(Y){if(Hu8(Y))throw new ZX(`No such file: ${Q.path}`);throw Y}}async setShareMode($,Z,Q,Y){G7($);let X=b7(Z),J=await this.manifest.get(this.organizationId,$,X);if(!J)throw new ZX(`No such path: ${X}`);let G=null,W=null;if(Q==="password"){if(!Y.password)throw new HG("A password is required to set password mode");G=await jc1(Y.password),W=zc1()}let K=await this.manifest.setShareMode({organizationId:this.organizationId,volume:$,path:J.path,readPublic:Q!=="private",passwordHash:G,shareSecret:W,actor:Y.actor});if(!K)throw new ZX(`No such path: ${J.path}`);return K}async setReadPublic($,Z,Q,Y){return this.setShareMode($,Z,Q?"public":"private",{actor:Y.actor})}async resolveReadAccess($,Z){G7($);let Q=b7(Z),Y=await this.manifest.get(this.organizationId,$,Q);if(!Y||Y.kind!=="file")return{access:"private"};let X=await this.manifest.resolveGoverningShare({organizationId:this.organizationId,volume:$,candidatePaths:[Q,...CD(Q)]});if(!X)return{access:"private"};if(!X.passwordHash)return{access:"public"};return{access:"password",govPath:X.path,secret:X.secret??"",passwordHash:X.passwordHash}}async isPubliclyReadable($,Z){G7($);let Q=b7(Z),Y=await this.manifest.get(this.organizationId,$,Q);if(!Y||Y.kind!=="file")return!1;if(Y.readPublic)return!0;return this.manifest.hasPublicAncestorDir(this.organizationId,$,CD(Q))}async inheritsPublic($,Z){return G7($),this.manifest.hasPublicAncestorDir(this.organizationId,$,CD(b7(Z)))}async childrenInheritPublic($,Z){G7($);let Q=b7(Z);if(Q==="")return!1;return this.manifest.hasPublicAncestorDir(this.organizationId,$,[...CD(Q),Q])}async recentWithEffectivePublic($){return this.withEffectivePublic(await this.recent($))}async searchWithEffectivePublic($,Z,Q,Y){return this.withEffectivePublic(await this.manifest.searchFiles({organizationId:this.organizationId,query:$,limit:Z,volumes:Q,pathPrefix:Y?b7(Y):void 0}))}async withEffectivePublic($){let Z=new Map;for(let Y of $){let X=Z.get(Y.volume);if(!X)X=new Set,Z.set(Y.volume,X);for(let J of CD(Y.path))X.add(J)}let Q=new Map;return await Promise.all([...Z].map(async([Y,X])=>{let J=await this.manifest.publicDirPaths({organizationId:this.organizationId,volume:Y,paths:[...X]});Q.set(Y,new Set(J))})),$.map((Y)=>{let X=Q.get(Y.volume),J=!!X&&CD(Y.path).some((G)=>X.has(G));return{...Y,effectivePublic:Y.readPublic||J}})}async presignRead($,Z,Q){let Y=await this.requireFile($,Z);return this.storage.presignedGetUrl(cH($,Y.path),Q)}async write($,Z,Q,Y){G7($);let X=b7(Z);if(X==="")throw new HG("Cannot write to the volume root");let J=typeof Q==="string"?new TextEncoder().encode(Q):Q;if(J.byteLength>this.maxFileBytes)throw new Sz(`File exceeds the ${this.maxFileBytes}-byte per-file limit`);let[G,W]=await Promise.all([Y.skipVolumeQuota?Promise.resolve(null):this.manifest.usage(this.organizationId,$),this.manifest.get(this.organizationId,$,X)]);if(W?.kind==="dir")throw new HG(`Cannot write a file at ${X}: a directory exists there`);if(G){let K=W?.kind==="file"?W.size:0;if(G.bytes-K+J.byteLength>this.volumeQuotaBytes)throw new Sz(`Write would exceed the volume quota of ${this.volumeQuotaBytes} bytes`)}await this.ensureDirs($,X,Y.actor),await this.storage.put(cH($,X),J,{contentType:Y.contentType??v7(X)});try{return await g8(()=>this.manifest.putFile({organizationId:this.organizationId,volume:$,path:X,parent:pg(X),contentHash:Rc1(J),size:J.byteLength,actor:Y.actor,threadId:Y.threadId??null}))}catch(K){throw console.error("org-fs manifest write lost after object put",{organizationId:this.organizationId,volume:$,path:X,size:J.byteLength,error:K instanceof Error?K.message:String(K)}),K}}async mkdir($,Z,Q){G7($);let Y=b7(Z);if(Y==="")return;if((await this.manifest.get(this.organizationId,$,Y))?.kind==="file")throw new HG(`Cannot create a directory at ${Y}: a file exists there`);await this.ensureDirs($,Y,Q.actor),await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Y,parent:pg(Y),actor:Q.actor})}async delete($,Z,Q){G7($);let Y=b7(Z);if(Y==="")throw new HG("Cannot delete the volume root");let X=await this.manifest.get(this.organizationId,$,Y);if(!X)return;if(X.kind==="dir"){let J=await this.manifest.listSubtreeFiles(this.organizationId,$,Y);await Promise.all(J.map((G)=>this.storage.delete(cH($,G.path)))),await this.manifest.tombstoneSubtree(this.organizationId,$,Y,Q.actor);return}await this.storage.delete(cH($,Y)),await this.manifest.tombstone(this.organizationId,$,Y,Q.actor)}async move($,Z,Q,Y){G7($);let X=b7(Z),J=b7(Q);if(X===""||J==="")throw new HG("Cannot move the volume root");if(J===X||J.startsWith(`${X}/`))throw new HG(`Cannot move ${X} onto itself or into its own subtree`);let G=await this.manifest.get(this.organizationId,$,X);if(!G)throw new ZX(`No such path: ${X}`);if(G.kind==="file"){let H=await this.storage.getBytes(cH($,X));await this.write($,J,H,{...Y,skipVolumeQuota:!0}),await this.delete($,X,Y);return}let[W,K]=await Promise.all([this.manifest.listSubtreeFiles(this.organizationId,$,X),this.manifest.listSubtreeDirs(this.organizationId,$,X)]);await this.mkdir($,J,Y);for(let H of W){let F=H.path.slice(X.length+1),U=await this.storage.getBytes(cH($,H.path));await this.write($,`${J}/${F}`,U,{...Y,skipVolumeQuota:!0})}for(let H of K){let F=H.path.slice(X.length+1);await this.mkdir($,`${J}/${F}`,Y)}await this.delete($,X,Y)}async filesExist($,Z){G7($);let Q=await this.manifest.liveFilePaths({organizationId:this.organizationId,volume:$,paths:Z.map((Y)=>b7(Y))});return new Set(Q)}async recent($){return this.manifest.recentFiles({organizationId:this.organizationId,limit:$})}async changes($,Z,Q=Ju8){G7($);let Y=Z||"0";if(!/^\d+$/.test(Y))throw new HG(`Invalid cursor: ${Z}`);let X=await this.manifest.changesSince({organizationId:this.organizationId,volume:$,sinceSeq:Y,limit:Q}),J=X.at(-1);return{entries:X,cursor:J?J.seq:Z||"0",hasMore:X.length>=Q}}async latestSeq($){return G7($),this.manifest.latestSeq({organizationId:this.organizationId,volume:$})}async backfillFromStorage($,Z){G7($);let Q=tZ0($),Y,X=0;do{let J=await this.storage.list({prefix:Q,maxKeys:Gu8,continuationToken:Y});for(let G of J.objects){let W=G.key.slice(Q.length);if(W==="")continue;await this.ensureDirs($,W,Z.actor);let K=await this.storage.getBytes(G.key);await this.manifest.putFile({organizationId:this.organizationId,volume:$,path:W,parent:pg(W),contentHash:Rc1(K),size:K.byteLength,actor:Z.actor}),X++}Y=J.isTruncated?J.nextContinuationToken:void 0}while(Y);return X}async requireFile($,Z){G7($);let Q=b7(Z),Y=await this.manifest.get(this.organizationId,$,Q);if(!Y||Y.kind!=="file")throw new ZX(`No such file: ${Q}`);return Y}async ensureDirs($,Z,Q){for(let Y of CD(Z))await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Y,parent:pg(Y),actor:Q})}}var Ju8=500,Gu8=1000,Wu8=524288000,Ku8=10737418240,Sz,HG,ZX;var _N=D(()=>{D8();YK();kz();Rc0();Sz=class Sz extends Error{constructor($){super($);this.name="OrgFsQuotaError"}};HG=class HG extends Error{constructor($){super($);this.name="OrgFsValidationError"}};ZX=class ZX extends Error{constructor($){super($);this.name="OrgFsNotFoundError"}}});import{z as vN}from"zod";function mH($){return $.startsWith(qc1)}function _D($){return`${qc1}${$}`}function Ou8($){let Z=new Map(Nu8.map((Q)=>[Q.set,Q]));if($)try{for(let Q of Bu8.parse(JSON.parse($)))Z.set(Q.set,Q)}catch(Q){console.warn("[org-fs] invalid ORGFS_PUBLIC_SETS \u2014 using built-in defaults only",Q)}return[...Z.values()]}function V3(){return Ou8(E0().orgFsPublicSetsJson)}function Vn($){let Z=$X(),Q=Z?KG(Z,In):new M3(In,$.baseUrl);return new I3(Q,$.storage.orgFsEntries,In)}var In="org_orgfs_public_skills",qc1="public-",Fu8,Uu8,Nu8,Bu8;var Cz=D(()=>{F$();SD();ig();_N();Fu8=vN.object({from:vN.string(),to:vN.string().optional()}),Uu8=vN.object({set:vN.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/),repo:vN.string().regex(/^[\w.-]+\/[\w.-]+$/),ref:vN.string().min(1),paths:vN.array(Fu8).min(1)}),Nu8=[{set:"core",repo:"decocms/studio",ref:"main",paths:[{from:"packages/sandbox/image/skills"}]},{set:"storefront",repo:"decocms/storefront-skills",ref:"main",paths:[{from:".claude-seo/skills"},{from:".claude-performance/skills"},{from:".claude-deco/skills"}]}],Bu8=vN.array(Uu8).refine(($)=>new Set($.map((Z)=>Z.set)).size===$.length,{message:"duplicate set names"})});function bN($){if(typeof $==="string")return $.length>0?[$]:[];if(Array.isArray($))return $.flatMap(bN);if($!==null&&typeof $==="object")return Object.values($).flatMap(bN);return[]}var y0;var w5=D(()=>{y0=class y0 extends Error{provider;status;retryAfterMs;constructor($){super($.message,{cause:$.cause});this.name="GitProviderError",this.provider=$.provider,this.status=$.status,this.retryAfterMs=$.retryAfterMs??null}get isRateLimited(){return this.status===429||this.retryAfterMs!==null}get isAuthFailure(){return this.status===401||this.status===403}}});import{sql as _z}from"kysely";function qc0($){if($===null)return null;return $ instanceof Date?$.toISOString():String($)}function XK($){return{organizationId:$.organization_id,volume:$.volume,path:$.path,parent:$.parent,kind:$.kind,contentHash:$.content_hash,size:Number($.size),seq:String($.seq),deletedAt:qc0($.deleted_at),createdBy:$.created_by,createdAt:qc0($.created_at)??"",updatedBy:$.updated_by,updatedAt:qc0($.updated_at)??"",threadId:$.thread_id,readPublic:$.read_public,shareMode:!$.read_public?"private":$.share_password_hash?"password":"public"}}class Sn{db;constructor($){this.db=$}async putFile($){let Z=new Date,Q=$.threadId??null,Y=await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z,thread_id:Q}).onConflict((X)=>X.columns(["organization_id","volume","path"]).doUpdateSet({kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:rZ0,read_public:_z`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`,thread_id:_z`coalesce(cast(${Q} as text), org_fs_entry.thread_id)`})).returning(JK).executeTakeFirstOrThrow();return XK(Y)}async putDir($){let Z=new Date;await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"dir",content_hash:null,size:0,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z}).onConflict((Q)=>Q.columns(["organization_id","volume","path"]).where("org_fs_entry.deleted_at","is not",null).doUpdateSet({kind:"dir",content_hash:null,size:0,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:rZ0,read_public:_z`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`})).execute()}async get($,Z,Q){let Y=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("path","=",Q).where("deleted_at","is",null).select(JK).executeTakeFirst();return Y?XK(Y):null}async listDir($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("parent","=",Q).where("deleted_at","is",null).select(JK).orderBy("path","asc").execute()).map((X)=>XK(X))}async listVolumeDirs($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).select(JK).execute()).map((Y)=>XK(Y))}async listVolumeFiles($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select(JK).execute()).map((Y)=>XK(Y))}async listSubtreeFiles($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).where("path","like",`${kn(Q)}/%`).select(JK).execute()).map((X)=>XK(X))}async listSubtreeDirs($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).where("path","like",`${kn(Q)}/%`).select(JK).execute()).map((X)=>XK(X))}async tombstone($,Z,Q,Y){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Y,updated_at:new Date,seq:rZ0}).where("organization_id","=",$).where("volume","=",Z).where("path","=",Q).where("deleted_at","is",null).execute()}async tombstoneSubtree($,Z,Q,Y){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Y,updated_at:new Date,seq:rZ0}).where("organization_id","=",$).where("volume","=",Z).where("deleted_at","is",null).where((X)=>X.or([X("path","=",Q),X("path","like",`${kn(Q)}/%`)])).execute()}async setShareMode($){let Z=new Date,Q=await this.db.updateTable("org_fs_entry").set({read_public:$.readPublic,share_password_hash:$.passwordHash,share_secret:$.shareSecret,updated_by:$.actor,updated_at:Z}).where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("path","=",$.path).where("deleted_at","is",null).returning(JK).executeTakeFirst();return Q?XK(Q):null}async resolveGoverningShare($){if($.candidatePaths.length===0)return null;let Z=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.candidatePaths).select(["path","share_password_hash","share_secret"]).execute();if(Z.length===0)return null;Z.sort((Y,X)=>X.path.length-Y.path.length);let Q=Z[0];return{path:Q.path,passwordHash:Q.share_password_hash,secret:Q.share_secret}}async hasPublicAncestorDir($,Z,Q){if(Q.length===0)return!1;return!!await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",Q).select("path").limit(1).executeTakeFirst()}async publicDirPaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.paths).select("path").execute()).map((Q)=>Q.path)}async usage($,Z){let Q=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select((Y)=>[Y.fn.countAll().as("files"),Y.fn.coalesce(Y.fn.sum("size"),_z`0`).as("bytes")]).executeTakeFirst();return{files:Number(Q?.files??0),bytes:Number(Q?.bytes??0)}}async liveFilePaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","file").where("deleted_at","is",null).where("path","in",$.paths).select(["path"]).execute()).map((Q)=>Q.path)}async recentFiles($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).select(JK).orderBy("seq","desc").limit($.limit).execute()).map((Q)=>XK(Q))}async searchFiles($){if($.volumes&&$.volumes.length===0)return[];let Z=kn($.query),Q=this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).where("path","ilike",`%${Z}%`);if($.volumes)Q=Q.where("volume","in",$.volumes);if($.pathPrefix)Q=Q.where("path","like",`${kn($.pathPrefix)}/%`);return(await Q.select(JK).orderBy("seq","desc").limit($.limit).execute()).map((X)=>XK(X))}async changesSince($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("seq",">",_z`cast(${$.sinceSeq} as bigint)`).select(JK).orderBy("seq","asc").limit($.limit).execute()).map((Q)=>XK(Q))}async latestSeq($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).select(_z`max(seq)`.as("seq")).executeTakeFirst())?.seq??"0"}}function kn($){return $.replace(/[\\%_]/g,"\\$&")}var JK,rZ0;var Mc0=D(()=>{JK=["organization_id","volume","path","parent","kind","content_hash","size","seq","deleted_at","created_by","created_at","updated_by","updated_at","thread_id","read_public","share_password_hash"],rZ0=_z`nextval('org_fs_entry_seq')`});import{createHash as Du8}from"crypto";import{gunzipSync as Lu8}from"zlib";function Vc0($,Z,Q){let Y=Z,X=Z+Q;while(Y<X&&$[Y]!==0)Y++;return new TextDecoder().decode($.subarray(Z,Y))}function ju8($,Z,Q){let Y=Vc0($,Z,Q).trim();return Y===""?0:Number.parseInt(Y,8)}function Eu8($){let Z=new Map,Q=0,Y=null,X=null;while(Q+512<=$.length){let J=$.subarray(Q,Q+512);if(Q+=512,J.every((N)=>N===0))break;let G=Vc0(J,0,100),W=Vc0(J,345,155);if(W)G=`${W}/${G}`;let K=ju8(J,124,12),H=String.fromCharCode(J[156]??0),F=$.subarray(Q,Q+K);if(Q+=Math.ceil(K/512)*512,H==="L"){let N=new TextDecoder().decode(F),B=N.indexOf("\x00");Y=B===-1?N:N.slice(0,B);continue}if(H==="x"){let N=new TextDecoder().decode(F);X=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(N)?.[1]??null;continue}if(H==="g")continue;let U=X??Y??G;if(Y=null,X=null,H==="0"||H==="\x00"||H==="")Z.set(U,new Uint8Array(F))}return Z}function zu8($,Z,Q){let Y=encodeURIComponent(Z);if(!Q)return{url:`https://codeload.github.com/${$}/tar.gz/${Y}`,headers:{}};return{url:`https://api.github.com/repos/${$}/tarball/${Y}`,headers:{Authorization:`Bearer ${Q}`,Accept:"application/vnd.github+json"}}}function Mc1($,Z){if($.length>ng)throw Error(`tarball for ${Z} exceeds ${ng} bytes`);let Q=Eu8(new Uint8Array(Lu8($,{maxOutputLength:wu8}))),Y=new Map;for(let[X,J]of Q){let G=X.indexOf("/");if(G===-1)continue;let W=X.slice(G+1);if(W)Y.set(W,J)}return Y}function Ic1($,Z,Q){if($>Z)throw Error(`tarball for ${Q} exceeds ${Z} bytes`)}async function Pu8($,Z){let Q=[],Y=0,X=$.getReader();try{while(!0){let{done:W,value:K}=await X.read();if(W)break;Y+=K.length,Ic1(Y,ng,Z),Q.push(K)}}finally{await X.cancel().catch(()=>{}),X.releaseLock()}let J=new Uint8Array(Y),G=0;for(let W of Q)J.set(W,G),G+=W.length;return J}function Vc1($){if($ instanceof kc0)return $.status>=500||$.status===429;if($ instanceof y0)return $.status===0||$.status>=500||$.status===429;if($ instanceof Error&&/declares .* bytes|exceeds .* bytes/.test($.message))return!1;return!0}async function Au8($,Z,Q){let{url:Y,headers:X}=zu8($,Z,Q),J=`${$}@${Z}`,G=async()=>{let W=await fetch(Y,{headers:X,signal:AbortSignal.timeout(60000)});if(!W.ok)throw await W.body?.cancel().catch(()=>{}),new kc0(W.status,`tarball fetch failed for ${J}: HTTP ${W.status}`);let K=Number(W.headers.get("content-length")??0);if(K>ng)throw Error(`tarball for ${J} declares ${K} bytes (cap ${ng})`);let H=new Uint8Array(await W.arrayBuffer());return Ic1(H.length,ng,J),H};try{let W=await g8(G,{maxAttempts:3,minTimeout:500,maxTimeout:4000,jitter:0.5,isRetriable:Vc1});return Mc1(W,J)}catch(W){if(W instanceof i5)throw W.cause instanceof Error?W.cause:W;throw W}}async function Tu8($,Z){if(!Z.tarball)return Au8($.repo,$.ref,Z.authToken);let Q=Z.tarball,Y=`${$.repo}@${$.ref}`,X;try{X=await g8(()=>Q(),{maxAttempts:3,minTimeout:500,maxTimeout:4000,jitter:0.5,isRetriable:Vc1})}catch(J){throw J instanceof i5&&J.cause instanceof Error?J.cause:J}if(!X)throw Error(`tarball not found for ${Y}`);return Mc1(await Pu8(X,Y),Y)}function Ru8($,Z){let Q=new Map;for(let{from:Y,to:X}of Z){let J=Y===""?"":`${Y.replace(/\/+$/,"")}/`;for(let[G,W]of $){if(!G.startsWith(J))continue;let K=G.slice(J.length);if(!K)continue;let H=b7(X?`${X}/${K}`:K);if(H)Q.set(H,W)}}return Q}function qu8($,Z){let Q=new Set;for(let J of $){let G=J.split("/");for(let W=1;W<G.length;W++)Q.add(G.slice(0,W).join("/"))}let Y=[...Z].filter((J)=>!Q.has(J)).sort((J,G)=>J.length-G.length),X=[];for(let J of Y)if(!X.some((G)=>J.startsWith(`${G}/`)))X.push(J);return X}function Mu8($){return Du8("sha256").update($).digest("hex")}function Iu8($){return $.manifestHash===$.hash&&$.storedPaths.has($.path)}async function Vu8($,Z){let Q=tZ0(Z),Y=new Set,X;do{let J=await $.list({prefix:Q,continuationToken:X});for(let G of J.objects)Y.add(G.key.slice(Q.length));X=J.nextContinuationToken}while(X);return Y}async function Sc0($,Z){let{orgId:Q,volume:Y,source:X}=Z,J=$X(),G=J?KG(J,Q):new M3(Q,Z.baseUrl),W=new Sn($),K=new I3(G,W,Q),H=Ru8(await Tu8(X,Z),X.paths),F=new Map((await W.listVolumeFiles(Q,Y)).map((w)=>[w.path,w.contentHash]));if(H.size===0&&F.size>0)throw Error(`volume "${Y}" resolved 0 files from ${X.repo}@${X.ref} `+`(check paths config) \u2014 refusing to delete the ${F.size} existing files`);let U=0;for(let w of F.keys()){if(H.has(w))continue;await K.delete(Y,w,{actor:Ic0}),U++}let N=await W.listVolumeDirs(Q,Y);for(let w of qu8(H.keys(),N.map((j)=>j.path)))await K.delete(Y,w,{actor:Ic0});let B=0,O=0,L=await Vu8(G,Y);for(let[w,j]of H){if(Iu8({hash:Mu8(j),manifestHash:F.get(w),storedPaths:L,path:w})){O++;continue}await K.write(Y,w,j,{actor:Ic0,contentType:v7(w),skipVolumeQuota:Z.skipVolumeQuota}),B++}return{written:B,deleted:U,unchanged:O}}async function ku8($,Z,Q){let Y=await Sc0($,{orgId:In,baseUrl:Q.baseUrl,volume:_D(Z.set),source:Z,skipVolumeQuota:!0});return{set:Z.set,...Y}}async function Cc0($,Z,Q){try{return await ku8($,Z,Q)}catch(Y){return{set:Z.set,error:Y instanceof Error?Y.message:String(Y)}}}async function kc1($,Z){let Q=[];for(let Y of V3())Q.push(await Cc0($,Y,Z));return Q}var Ic0="system:skill-set-sync",ng=209715200,wu8=1073741824,kc0;var sZ0=D(()=>{D8();w5();Mc0();ig();SD();YK();_N();kz();Cz();kc0=class kc0 extends Error{status;constructor($,Z){super(Z);this.status=$;this.name="TarballHttpError"}}});import{DBOS as aZ0,SchedulerMode as Su8}from"@dbos-inc/dbos-sdk";function Sc1($){_c0=$}function _u8(){if(!_c0)throw Error("[org-fs] public-sets sync runtime not initialized \u2014 setPublicSetsSyncRuntime() must run before the workflow fires");return _c0}async function vu8($,Z){for(let Q of V3()){let Y=await aZ0.runStep(()=>{let X=_u8();return Cc0(X.db,Q,{baseUrl:X.baseUrl})},{name:`syncPublicSet:${Q.set}`});if("error"in Y)console.warn(`[org-fs] public set "${Y.set}" sync failed: ${Y.error}`);else if(Y.written||Y.deleted)console.log(`[org-fs] public set "${Y.set}" synced: +${Y.written} -${Y.deleted} (=${Y.unchanged})`)}}function Cc1(){if(Cn)return;Cn=aZ0.registerWorkflow(vu8,{name:"publicSetsSyncWorkflow"}),aZ0.registerScheduled(Cn,{name:"publicSetsSyncWorkflow",crontab:Cu8,mode:Su8.ExactlyOncePerIntervalWhenActive})}async function _c1(){if(V3().length===0||!Cn)return;let $=new Date,Z=`public-sets-sync-boot:${$.toISOString().slice(0,13)}`;await aZ0.startWorkflow(Cn,{workflowID:Z})($,$)}var Cu8="4-59/10 * * * *",_c0=null,Cn=null;var vc1=D(()=>{Cz();sZ0()});import{jwtVerify as bu8,SignJWT as bc1}from"jose";import{randomBytes as xu8}from"crypto";function xc1(){if(_n)return _n;let $=E0(),Z=$.studioJwtSecret??$.betterAuthSecret;if(Z)_n=new TextEncoder().encode(Z);else console.warn("STUDIO_JWT_SECRET not set - generating random secret (not persistent)"),_n=new Uint8Array(xu8(32));return _n}async function fc1($,Z="5m"){let Q=xc1();return await new bc1($).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Z).sign(Q)}async function vc0($){try{let Z=xc1(),{payload:Q}=await bu8($,Z);return Q}catch{return}}async function NQ($,Z,Q=3600){let Y=E0(),X=Y.plansEnabled?Y.studioJwtSecret:Y.studioJwtSecret??Y.betterAuthSecret;if(!X)throw Error(Y.plansEnabled?"STUDIO_JWT_SECRET (or MESH_JWT_SECRET) is required to mint gateway JWTs when STUDIO_PLANS_ENABLED is set \u2014 BETTER_AUTH_SECRET is deliberately not a fallback, see resolve-config":"A deterministic JWT secret is required to mint gateway JWTs \u2014 set STUDIO_JWT_SECRET or BETTER_AUTH_SECRET");let J=new TextEncoder().encode(X);return await new bc1({iss:"mesh",sub:$,...Z&&{email:Z}}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+Q).sign(J)}var _n=null;var GK=D(()=>{F$()});import{createCipheriv as fu8,createDecipheriv as yu8,createHash as gu8,randomBytes as yc1}from"crypto";class FG{key;constructor($){if(Buffer.from($,"base64").length===uc1)this.key=Buffer.from($,"base64");else this.key=gu8("sha256").update($).digest()}async encrypt($){let Z=yc1(vn),Q=fu8(gc1,this.key,Z),Y=Q.update($,"utf8");Y=Buffer.concat([Y,Q.final()]);let X=Q.getAuthTag();return Buffer.concat([Z,X,Y]).toString("base64")}async decrypt($){let Z=Buffer.from($,"base64"),Q=Z.subarray(0,vn),Y=Z.subarray(vn,vn+hc1),X=Z.subarray(vn+hc1),J=yu8(gc1,this.key,Q);J.setAuthTag(Y);let G=J.update(X);return G=Buffer.concat([G,J.final()]),G.toString("utf8")}static generateKey(){return yc1(uc1).toString("base64")}}var gc1="aes-256-gcm",vn=16,hc1=16,uc1=32;var vz=()=>{};function s9(){let $=E0();if($.baseUrl)return $.baseUrl;return`http://localhost:${$.port??3000}`}function lc1(){return`http://localhost:${E0().port??3000}`}function x5(){return E0().publicUrl??s9()}var E9=D(()=>{F$()});import*as f from"zod/v4";function Ym1($){if($.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${$.params.ref.type}`)}function Xm1($){if($.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${$.params.ref.type}`)}var vD="2025-11-25",cc1="2025-03-26",bD,xD="io.modelcontextprotocol/related-task",$70="2.0",W7,mc1,dc1,dW5,hu8,uu8,bc0,UG,bn,ic1=($)=>bn.safeParse($).success,BQ,k3,S3,OQ,Z70,pc1,dH=($)=>pc1.safeParse($).success,nc1,tc1=($)=>nc1.safeParse($).success,xc0,WK=($)=>xc0.safeParse($).success,_1,fc0,og=($)=>fc0.safeParse($).success,NG,iW5,xN,lu8,Q70,cu8,xn,tg,oc1,mu8,du8,iu8,pu8,nu8,tu8,Y70,yc0=($)=>Y70.safeParse($).success,ou8,gc0,X70,rc1=($)=>X70.safeParse($).success,J70,ru8,su8,G70,au8,fn,yn,eu8,gn,fN,$l8,hn,W70,K70,H70,pW5,F70,U70,N70,sc1,ac1,ec1,hc0,$m1,un,rg,Zm1,Zl8,fD,uc0,yD,lc0,cc0,Ql8,sg,mc0,dc0,Yl8,Xl8,Jl8,Gl8,Wl8,Kl8,Hl8,Fl8,gD,ic0,Ul8,ag,pc0,nc0,tc0,Nl8,Bl8,Ol8,oc0,Dl8,rc0,sc0,Ll8,wl8,B70,eg,ln,iH,nW5,jl8,hD,ac0,Qm1,cn,El8,ec0,zl8,Pl8,Al8,Tl8,Rl8,ql8,Ml8,eZ0,Il8,Vl8,$m0,bz,mn,kl8,Sl8,Cl8,_l8,vl8,bl8,xl8,fl8,yl8,gl8,hl8,ul8,ll8,cl8,ml8,Zm0,dl8,il8,uD,pl8,nl8,tl8,O70,Qm0,ol8,rl8,Ym0,sl8,tW5,oW5,rW5,sW5,aW5,eW5,M1,Jm1;var a9=D(()=>{bD=[vD,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],W7=f.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),mc1=f.union([f.string(),f.number().int()]),dc1=f.string(),dW5=f.looseObject({ttl:f.number().optional(),pollInterval:f.number().optional()}),hu8=f.object({ttl:f.number().optional()}),uu8=f.object({taskId:f.string()}),bc0=f.looseObject({progressToken:mc1.optional(),[xD]:uu8.optional()}),UG=f.object({_meta:bc0.optional()}),bn=UG.extend({task:hu8.optional()}),BQ=f.object({method:f.string(),params:UG.loose().optional()}),k3=f.object({_meta:bc0.optional()}),S3=f.object({method:f.string(),params:k3.loose().optional()}),OQ=f.looseObject({_meta:bc0.optional()}),Z70=f.union([f.string(),f.number().int()]),pc1=f.object({jsonrpc:f.literal($70),id:Z70,...BQ.shape}).strict(),nc1=f.object({jsonrpc:f.literal($70),...S3.shape}).strict(),xc0=f.object({jsonrpc:f.literal($70),id:Z70,result:OQ}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(_1||(_1={}));fc0=f.object({jsonrpc:f.literal($70),id:Z70.optional(),error:f.object({code:f.number().int(),message:f.string(),data:f.unknown().optional()})}).strict(),NG=f.union([pc1,nc1,xc0,fc0]),iW5=f.union([xc0,fc0]),xN=OQ.strict(),lu8=k3.extend({requestId:Z70.optional(),reason:f.string().optional()}),Q70=S3.extend({method:f.literal("notifications/cancelled"),params:lu8}),cu8=f.object({src:f.string(),mimeType:f.string().optional(),sizes:f.array(f.string()).optional(),theme:f.enum(["light","dark"]).optional()}),xn=f.object({icons:f.array(cu8).optional()}),tg=f.object({name:f.string(),title:f.string().optional()}),oc1=tg.extend({...tg.shape,...xn.shape,version:f.string(),websiteUrl:f.string().optional(),description:f.string().optional()}),mu8=f.intersection(f.object({applyDefaults:f.boolean().optional()}),f.record(f.string(),f.unknown())),du8=f.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},f.intersection(f.object({form:mu8.optional(),url:W7.optional()}),f.record(f.string(),f.unknown()).optional())),iu8=f.looseObject({list:W7.optional(),cancel:W7.optional(),requests:f.looseObject({sampling:f.looseObject({createMessage:W7.optional()}).optional(),elicitation:f.looseObject({create:W7.optional()}).optional()}).optional()}),pu8=f.looseObject({list:W7.optional(),cancel:W7.optional(),requests:f.looseObject({tools:f.looseObject({call:W7.optional()}).optional()}).optional()}),nu8=f.object({experimental:f.record(f.string(),W7).optional(),sampling:f.object({context:W7.optional(),tools:W7.optional()}).optional(),elicitation:du8.optional(),roots:f.object({listChanged:f.boolean().optional()}).optional(),tasks:iu8.optional(),extensions:f.record(f.string(),W7).optional()}),tu8=UG.extend({protocolVersion:f.string(),capabilities:nu8,clientInfo:oc1}),Y70=BQ.extend({method:f.literal("initialize"),params:tu8}),ou8=f.object({experimental:f.record(f.string(),W7).optional(),logging:W7.optional(),completions:W7.optional(),prompts:f.object({listChanged:f.boolean().optional()}).optional(),resources:f.object({subscribe:f.boolean().optional(),listChanged:f.boolean().optional()}).optional(),tools:f.object({listChanged:f.boolean().optional()}).optional(),tasks:pu8.optional(),extensions:f.record(f.string(),W7).optional()}),gc0=OQ.extend({protocolVersion:f.string(),capabilities:ou8,serverInfo:oc1,instructions:f.string().optional()}),X70=S3.extend({method:f.literal("notifications/initialized"),params:k3.optional()}),J70=BQ.extend({method:f.literal("ping"),params:UG.optional()}),ru8=f.object({progress:f.number(),total:f.optional(f.number()),message:f.optional(f.string())}),su8=f.object({...k3.shape,...ru8.shape,progressToken:mc1}),G70=S3.extend({method:f.literal("notifications/progress"),params:su8}),au8=UG.extend({cursor:dc1.optional()}),fn=BQ.extend({params:au8.optional()}),yn=OQ.extend({nextCursor:dc1.optional()}),eu8=f.enum(["working","input_required","completed","failed","cancelled"]),gn=f.object({taskId:f.string(),status:eu8,ttl:f.union([f.number(),f.null()]),createdAt:f.string(),lastUpdatedAt:f.string(),pollInterval:f.optional(f.number()),statusMessage:f.optional(f.string())}),fN=OQ.extend({task:gn}),$l8=k3.merge(gn),hn=S3.extend({method:f.literal("notifications/tasks/status"),params:$l8}),W70=BQ.extend({method:f.literal("tasks/get"),params:UG.extend({taskId:f.string()})}),K70=OQ.merge(gn),H70=BQ.extend({method:f.literal("tasks/result"),params:UG.extend({taskId:f.string()})}),pW5=OQ.loose(),F70=fn.extend({method:f.literal("tasks/list")}),U70=yn.extend({tasks:f.array(gn)}),N70=BQ.extend({method:f.literal("tasks/cancel"),params:UG.extend({taskId:f.string()})}),sc1=OQ.merge(gn),ac1=f.object({uri:f.string(),mimeType:f.optional(f.string()),_meta:f.record(f.string(),f.unknown()).optional()}),ec1=ac1.extend({text:f.string()}),hc0=f.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),$m1=ac1.extend({blob:hc0}),un=f.enum(["user","assistant"]),rg=f.object({audience:f.array(un).optional(),priority:f.number().min(0).max(1).optional(),lastModified:f.iso.datetime({offset:!0}).optional()}),Zm1=f.object({...tg.shape,...xn.shape,uri:f.string(),description:f.optional(f.string()),mimeType:f.optional(f.string()),size:f.optional(f.number()),annotations:rg.optional(),_meta:f.optional(f.looseObject({}))}),Zl8=f.object({...tg.shape,...xn.shape,uriTemplate:f.string(),description:f.optional(f.string()),mimeType:f.optional(f.string()),annotations:rg.optional(),_meta:f.optional(f.looseObject({}))}),fD=fn.extend({method:f.literal("resources/list")}),uc0=yn.extend({resources:f.array(Zm1)}),yD=fn.extend({method:f.literal("resources/templates/list")}),lc0=yn.extend({resourceTemplates:f.array(Zl8)}),cc0=UG.extend({uri:f.string()}),Ql8=cc0,sg=BQ.extend({method:f.literal("resources/read"),params:Ql8}),mc0=OQ.extend({contents:f.array(f.union([ec1,$m1]))}),dc0=S3.extend({method:f.literal("notifications/resources/list_changed"),params:k3.optional()}),Yl8=cc0,Xl8=BQ.extend({method:f.literal("resources/subscribe"),params:Yl8}),Jl8=cc0,Gl8=BQ.extend({method:f.literal("resources/unsubscribe"),params:Jl8}),Wl8=k3.extend({uri:f.string()}),Kl8=S3.extend({method:f.literal("notifications/resources/updated"),params:Wl8}),Hl8=f.object({name:f.string(),description:f.optional(f.string()),required:f.optional(f.boolean())}),Fl8=f.object({...tg.shape,...xn.shape,description:f.optional(f.string()),arguments:f.optional(f.array(Hl8)),_meta:f.optional(f.looseObject({}))}),gD=fn.extend({method:f.literal("prompts/list")}),ic0=yn.extend({prompts:f.array(Fl8)}),Ul8=UG.extend({name:f.string(),arguments:f.record(f.string(),f.string()).optional()}),ag=BQ.extend({method:f.literal("prompts/get"),params:Ul8}),pc0=f.object({type:f.literal("text"),text:f.string(),annotations:rg.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),nc0=f.object({type:f.literal("image"),data:hc0,mimeType:f.string(),annotations:rg.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),tc0=f.object({type:f.literal("audio"),data:hc0,mimeType:f.string(),annotations:rg.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),Nl8=f.object({type:f.literal("tool_use"),name:f.string(),id:f.string(),input:f.record(f.string(),f.unknown()),_meta:f.record(f.string(),f.unknown()).optional()}),Bl8=f.object({type:f.literal("resource"),resource:f.union([ec1,$m1]),annotations:rg.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),Ol8=Zm1.extend({type:f.literal("resource_link")}),oc0=f.union([pc0,nc0,tc0,Ol8,Bl8]),Dl8=f.object({role:un,content:oc0}),rc0=OQ.extend({description:f.string().optional(),messages:f.array(Dl8)}),sc0=S3.extend({method:f.literal("notifications/prompts/list_changed"),params:k3.optional()}),Ll8=f.object({title:f.string().optional(),readOnlyHint:f.boolean().optional(),destructiveHint:f.boolean().optional(),idempotentHint:f.boolean().optional(),openWorldHint:f.boolean().optional()}),wl8=f.object({taskSupport:f.enum(["required","optional","forbidden"]).optional()}),B70=f.object({...tg.shape,...xn.shape,description:f.string().optional(),inputSchema:f.object({type:f.literal("object"),properties:f.record(f.string(),W7).optional(),required:f.array(f.string()).optional()}).catchall(f.unknown()),outputSchema:f.object({type:f.literal("object"),properties:f.record(f.string(),W7).optional(),required:f.array(f.string()).optional()}).catchall(f.unknown()).optional(),annotations:Ll8.optional(),execution:wl8.optional(),_meta:f.record(f.string(),f.unknown()).optional()}),eg=fn.extend({method:f.literal("tools/list")}),ln=yn.extend({tools:f.array(B70)}),iH=OQ.extend({content:f.array(oc0).default([]),structuredContent:f.record(f.string(),f.unknown()).optional(),isError:f.boolean().optional()}),nW5=iH.or(OQ.extend({toolResult:f.unknown()})),jl8=bn.extend({name:f.string(),arguments:f.record(f.string(),f.unknown()).optional()}),hD=BQ.extend({method:f.literal("tools/call"),params:jl8}),ac0=S3.extend({method:f.literal("notifications/tools/list_changed"),params:k3.optional()}),Qm1=f.object({autoRefresh:f.boolean().default(!0),debounceMs:f.number().int().nonnegative().default(300)}),cn=f.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),El8=UG.extend({level:cn}),ec0=BQ.extend({method:f.literal("logging/setLevel"),params:El8}),zl8=k3.extend({level:cn,logger:f.string().optional(),data:f.unknown()}),Pl8=S3.extend({method:f.literal("notifications/message"),params:zl8}),Al8=f.object({name:f.string().optional()}),Tl8=f.object({hints:f.array(Al8).optional(),costPriority:f.number().min(0).max(1).optional(),speedPriority:f.number().min(0).max(1).optional(),intelligencePriority:f.number().min(0).max(1).optional()}),Rl8=f.object({mode:f.enum(["auto","required","none"]).optional()}),ql8=f.object({type:f.literal("tool_result"),toolUseId:f.string().describe("The unique identifier for the corresponding tool call."),content:f.array(oc0).default([]),structuredContent:f.object({}).loose().optional(),isError:f.boolean().optional(),_meta:f.record(f.string(),f.unknown()).optional()}),Ml8=f.discriminatedUnion("type",[pc0,nc0,tc0]),eZ0=f.discriminatedUnion("type",[pc0,nc0,tc0,Nl8,ql8]),Il8=f.object({role:un,content:f.union([eZ0,f.array(eZ0)]),_meta:f.record(f.string(),f.unknown()).optional()}),Vl8=bn.extend({messages:f.array(Il8),modelPreferences:Tl8.optional(),systemPrompt:f.string().optional(),includeContext:f.enum(["none","thisServer","allServers"]).optional(),temperature:f.number().optional(),maxTokens:f.number().int(),stopSequences:f.array(f.string()).optional(),metadata:W7.optional(),tools:f.array(B70).optional(),toolChoice:Rl8.optional()}),$m0=BQ.extend({method:f.literal("sampling/createMessage"),params:Vl8}),bz=OQ.extend({model:f.string(),stopReason:f.optional(f.enum(["endTurn","stopSequence","maxTokens"]).or(f.string())),role:un,content:Ml8}),mn=OQ.extend({model:f.string(),stopReason:f.optional(f.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(f.string())),role:un,content:f.union([eZ0,f.array(eZ0)])}),kl8=f.object({type:f.literal("boolean"),title:f.string().optional(),description:f.string().optional(),default:f.boolean().optional()}),Sl8=f.object({type:f.literal("string"),title:f.string().optional(),description:f.string().optional(),minLength:f.number().optional(),maxLength:f.number().optional(),format:f.enum(["email","uri","date","date-time"]).optional(),default:f.string().optional()}),Cl8=f.object({type:f.enum(["number","integer"]),title:f.string().optional(),description:f.string().optional(),minimum:f.number().optional(),maximum:f.number().optional(),default:f.number().optional()}),_l8=f.object({type:f.literal("string"),title:f.string().optional(),description:f.string().optional(),enum:f.array(f.string()),default:f.string().optional()}),vl8=f.object({type:f.literal("string"),title:f.string().optional(),description:f.string().optional(),oneOf:f.array(f.object({const:f.string(),title:f.string()})),default:f.string().optional()}),bl8=f.object({type:f.literal("string"),title:f.string().optional(),description:f.string().optional(),enum:f.array(f.string()),enumNames:f.array(f.string()).optional(),default:f.string().optional()}),xl8=f.union([_l8,vl8]),fl8=f.object({type:f.literal("array"),title:f.string().optional(),description:f.string().optional(),minItems:f.number().optional(),maxItems:f.number().optional(),items:f.object({type:f.literal("string"),enum:f.array(f.string())}),default:f.array(f.string()).optional()}),yl8=f.object({type:f.literal("array"),title:f.string().optional(),description:f.string().optional(),minItems:f.number().optional(),maxItems:f.number().optional(),items:f.object({anyOf:f.array(f.object({const:f.string(),title:f.string()}))}),default:f.array(f.string()).optional()}),gl8=f.union([fl8,yl8]),hl8=f.union([bl8,xl8,gl8]),ul8=f.union([hl8,kl8,Sl8,Cl8]),ll8=bn.extend({mode:f.literal("form").optional(),message:f.string(),requestedSchema:f.object({type:f.literal("object"),properties:f.record(f.string(),ul8),required:f.array(f.string()).optional()})}),cl8=bn.extend({mode:f.literal("url"),message:f.string(),elicitationId:f.string(),url:f.string().url()}),ml8=f.union([ll8,cl8]),Zm0=BQ.extend({method:f.literal("elicitation/create"),params:ml8}),dl8=k3.extend({elicitationId:f.string()}),il8=S3.extend({method:f.literal("notifications/elicitation/complete"),params:dl8}),uD=OQ.extend({action:f.enum(["accept","decline","cancel"]),content:f.preprocess(($)=>$===null?void 0:$,f.record(f.string(),f.union([f.string(),f.number(),f.boolean(),f.array(f.string())])).optional())}),pl8=f.object({type:f.literal("ref/resource"),uri:f.string()}),nl8=f.object({type:f.literal("ref/prompt"),name:f.string()}),tl8=UG.extend({ref:f.union([nl8,pl8]),argument:f.object({name:f.string(),value:f.string()}),context:f.object({arguments:f.record(f.string(),f.string()).optional()}).optional()}),O70=BQ.extend({method:f.literal("completion/complete"),params:tl8});Qm0=OQ.extend({completion:f.looseObject({values:f.array(f.string()).max(100),total:f.optional(f.number().int()),hasMore:f.optional(f.boolean())})}),ol8=f.object({uri:f.string().startsWith("file://"),name:f.string().optional(),_meta:f.record(f.string(),f.unknown()).optional()}),rl8=BQ.extend({method:f.literal("roots/list"),params:UG.optional()}),Ym0=OQ.extend({roots:f.array(ol8)}),sl8=S3.extend({method:f.literal("notifications/roots/list_changed"),params:k3.optional()}),tW5=f.union([J70,Y70,O70,ec0,ag,gD,fD,yD,sg,Xl8,Gl8,hD,eg,W70,H70,F70,N70]),oW5=f.union([Q70,G70,X70,sl8,hn]),rW5=f.union([xN,bz,mn,uD,Ym0,K70,U70,fN]),sW5=f.union([J70,$m0,Zm0,rl8,W70,H70,F70,N70]),aW5=f.union([Q70,G70,Pl8,Kl8,dc0,ac0,sc0,hn,il8]),eW5=f.union([xN,gc0,Qm0,rc0,ic0,uc0,lc0,mc0,iH,ln,K70,U70,fN]);M1=class M1 extends Error{constructor($,Z,Q){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,Z,Q){if($===_1.UrlElicitationRequired&&Q){let Y=Q;if(Y.elicitations)return new Jm1(Y.elicitations,Z)}return new M1($,Z,Q)}};Jm1=class Jm1 extends M1{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(_1.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});import{z as o$}from"zod";function Km1($){return o$.record(o$.string(),o$.unknown()).nullable().refine((Z)=>Z===null||JSON.stringify(Z).length<=Wm1,{message:`${$} must serialize to at most ${Wm1} bytes`})}function pH($){return $!==null&&$!==void 0&&"command"in $}function $h($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function Zh($){return`virtual://${$}`}var Hm1,Gm1,al8,el8,$c8,Wm1=262144,eQ,D70,L70;var Fm1=D(()=>{a9();Hm1=o$.object({authorizationEndpoint:o$.string().url(),tokenEndpoint:o$.string().url(),introspectionEndpoint:o$.string().url().optional(),clientId:o$.string(),clientSecret:o$.string().optional(),scopes:o$.array(o$.string()),grantType:o$.enum(["authorization_code","client_credentials"])}),Gm1=o$.object({type:o$.literal("object"),properties:o$.record(o$.string(),o$.unknown()).optional(),required:o$.array(o$.string()).optional()}).catchall(o$.unknown()),al8=B70.extend({inputSchema:Gm1,outputSchema:Gm1.optional()}),el8=o$.object({headers:o$.record(o$.string(),o$.string()).optional()}),$c8=o$.object({command:o$.string().describe("Command to run (e.g., 'npx', 'node')"),args:o$.array(o$.string()).optional().describe("Command arguments"),cwd:o$.string().optional().describe("Working directory"),envVars:o$.record(o$.string(),o$.string()).optional().describe("Environment variables (encrypted in storage)")});eQ=o$.object({id:o$.string().describe("Unique identifier for the connection"),title:o$.string().describe("Human-readable name for the connection"),created_at:o$.string().describe("When the connection was created"),updated_at:o$.string().describe("When the connection was last updated"),created_by:o$.string().describe("User ID who created the connection"),updated_by:o$.string().optional().describe("User ID who last updated the connection"),organization_id:o$.string().describe("Organization ID this connection belongs to"),description:o$.string().nullable().describe("Description of the connection"),icon:o$.string().nullable().describe("Icon URL for the connection"),app_name:o$.string().nullable().describe("Associated app name"),app_id:o$.string().nullable().describe("Associated app ID"),slug:o$.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:o$.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:o$.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:o$.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:o$.union([$c8,el8]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:Hm1.nullable().describe("OAuth configuration"),configuration_state:Km1("configuration_state").describe("Configuration state (decrypted)"),configuration_scopes:o$.array(o$.string()).nullable().optional().describe("Configuration scopes"),metadata:Km1("metadata").describe("Additional metadata (includes repository info)"),tools:o$.array(al8).nullable().describe("Discovered tools from MCP"),bindings:o$.array(o$.string()).nullable().describe("Detected bindings"),status:o$.enum(["active","inactive","error"]).describe("Current status")}),D70=eQ.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}).extend({icon:o$.string().nullish()}),L70=eQ.partial()});import{z as S0}from"zod";function Gm0($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let Q=$?.homeTile;return Q?[Q]:[]}function yN($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,Q={};for(let[Y,X]of Object.entries(Z)){if(!X||typeof X!=="object")continue;if(Y!=="agent-sandbox"&&Y!=="local-api")continue;try{Q[Y]=Wm0.parse(X)}catch{}}return Q}function Km0($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[Q,Y]of Object.entries($)){if(!Y||typeof Y!=="object"||Array.isArray(Y))continue;let X={};for(let[J,G]of Object.entries(Y)){let W=yN(G);if(Object.keys(W).length>0)X[J]=W}if(Object.keys(X).length>0)Z[Q]=X}return Z}var Bm1,Xm0=500,Om1=200,Zc8=200,Qc8=20,Yc8=50,Xc8=100,Jc8=20,Gc8=100,Dm1=50,Wc8=100,Kc8=8192,Lm1,Hc8,wm1,Jm0,Fc8,Uc8,jm1,Um1,Nc8,w70,Nm1,Bc8,Oc8,Dc8,Lc8,wc8,Wm0,Em1,jc8,Ec8,zc8,Pc8,Ac8,Tc8,Rc8,zm1,qc8,Hm0,$Y,Fm0,j70,E70;var Pm1=D(()=>{Bm1=S0.object({connection_id:S0.string().describe("Connection ID"),selected_tools:S0.array(S0.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:S0.array(S0.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:S0.array(S0.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),Lm1=Bm1.extend({selected_tools:S0.array(S0.string()).max(Xm0).nullable().optional().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:S0.array(S0.string()).max(Xm0).nullable().optional().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:S0.array(S0.string()).max(Xm0).nullable().optional().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),Hc8=S0.object({connectionId:S0.string(),toolName:S0.string(),label:S0.string(),icon:S0.string().nullable().optional()}),wm1=S0.object({id:S0.string().describe("Stable id; used as React key and ?tab= value"),title:S0.string().describe("Tab label"),icon:S0.string().optional().describe("Optional lucide icon name"),view:S0.object({type:S0.literal("ext-app"),appId:S0.string(),args:S0.record(S0.string(),S0.unknown()).optional()})}),Jm0=S0.enum(["overview","reports","board","site-editor","assets","hosting","e2e","analytics","cdn","automations","experiments"]),Fc8=S0.enum(["on","off"]),Uc8=S0.enum(["on","off","manual","auto"]),jm1=S0.object({defaultMainView:S0.object({type:S0.string(),id:S0.string().optional(),toolName:S0.string().optional()}).nullable().optional(),chatDefaultOpen:S0.boolean().nullable().optional(),cmsDefaultOpen:S0.boolean().nullable().optional(),cms:Uc8.nullable().optional().describe("How this agent offers content editing. Absent means on; the retired `manual` / `auto` read as on too."),sidebarViews:S0.array(Jm0).max(10).nullable().optional().describe("Deprecated layout-scoped sidebar selections. Read only as a fallback when metadata.sidebarViews is absent."),tabs:S0.array(wm1).max(Jc8).optional()}),Um1=S0.object({tileId:S0.string().optional(),connectionId:S0.string().optional().describe("Connection that owns the resource \u2014 the host opens a direct MCP client to this connection so the iframe can call tools by their bare names."),resourceUri:S0.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),toolName:S0.string().optional().describe("Tool name \u2014 identifies which tool's inputSchema to display when editing tile props."),toolInput:S0.record(S0.string(),S0.unknown()).optional().describe("User-configured input props passed to MCPAppRenderer when rendering the tile."),minHeight:S0.number().int().positive().optional(),maxHeight:S0.number().int().positive().optional()}),Nc8=S0.object({banner:S0.string().nullable().optional(),bannerColor:S0.string().nullable().optional(),icon:S0.string().nullable().optional(),themeColor:S0.string().nullable().optional(),pinnedViews:S0.array(Hc8).max(Xc8).nullable().optional(),layout:jm1.nullable().optional(),homeTile:Um1.nullable().optional(),homeTiles:S0.array(Um1).max(Qc8).nullable().optional(),homePrompts:S0.array(S0.string()).max(Yc8).nullable().optional()});w70=/^[A-Za-z_][A-Za-z0-9_]*$/,Nm1=S0.string().min(1).regex(w70,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),Bc8=S0.discriminatedUnion("kind",[S0.object({key:Nm1,kind:S0.literal("literal"),value:S0.string().max(Kc8)}),S0.object({key:Nm1,kind:S0.literal("secret"),secretId:S0.string().min(1)})]),Oc8=S0.object({selected:S0.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:S0.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:S0.string().nullable().optional().describe("Optional path (relative to repo root) to the directory containing package.json. Null/absent means repo root. Forwarded as `application.packageManager.path` to the daemon config."),env:S0.array(Bc8).max(Wc8).nullable().optional().describe("Env vars injected on every SANDBOX_START. Literal entries inline their value; secret entries store a secretId that Studio resolves via the credential vault before posting /_sandbox/config.")}),Dc8=S0.object({url:S0.string().describe("GitHub repository URL"),owner:S0.string().describe("Repository owner"),name:S0.string().describe("Repository name"),installationId:S0.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:S0.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials."),repositoryId:S0.string().optional().describe("First-class repository (REPOSITORY_LINK) backing this binding. When set, credentials come from the repository's git provider account rather than connectionId.")}),Lc8=S0.enum(["agent-sandbox","local-api"]),wc8={sandboxHandle:S0.string().describe("Provider-specific handle"),previewUrl:S0.string().nullable().describe("URL where the sandbox's iframe-proxied UI is served, or null when the sandbox has no dev server (blank / tool sandboxes)."),sandboxApiUrl:S0.string().nullable().optional().describe("Direct sandbox API URL for runtimes that expose one. Equal to previewUrl for local-api; null/absent for AgentSandbox, which routes control traffic through hosted Studio."),createdAt:S0.number().optional().describe("Epoch ms the entry was first written by SANDBOX_START. Used by the booting overlay to show a stable elapsed timer that survives browser reloads. Optional for backward compatibility with entries written before this field existed."),startedWith:S0.object({packageManager:S0.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:S0.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:S0.string().nullable().optional().describe("metadata.runtime.path at the time of SANDBOX_START")}).optional().describe("Snapshot of metadata.runtime fields (selected/port/path) used at SANDBOX_START. The Preview tab compares the live metadata.runtime against this to decide if a restart is required to apply changes.")},Wm0=S0.object(wc8);Em1=S0.record(S0.string().describe("userId"),S0.record(S0.string().describe("branch"),S0.partialRecord(Lc8,Wm0)));jc8=S0.object({id:S0.string().describe("Stable identifier for this knowledge file"),name:S0.string().describe("File name shown in the UI"),kind:S0.enum(["file","skill"]).optional().describe("'file' (a single document) or 'skill' (a Claude Code skill folder containing SKILL.md). Defaults to 'file'."),volume:S0.string().describe("Org filesystem (Library) volume the file lives in"),path:S0.string().describe("Path within the volume"),url:S0.string().describe("Same-origin URL to read the file (display/download)"),contentType:S0.string().nullable().optional().describe("MIME type, used to decide whether to inline the content"),size:S0.number().nullable().optional().describe("File size in bytes"),addedAt:S0.string().describe("ISO timestamp when the file was attached")}),Ec8=S0.array(jc8).max(Gc8).nullable().optional().describe("Files attached to the agent as reference knowledge. Surfaced in the system prompt: small text documents are inlined, others are listed as retrievable references."),zc8=S0.enum(["smart","code-review","open"]),Pc8=zc8.nullable().optional().describe("Controls when this code agent's changes may be published directly vs. requiring PR review. 'smart' (default) uses AI to judge per change; 'code-review' requires review for any code; 'open' allows direct publish always."),Ac8=S0.boolean().nullable().optional().describe("Enable Fast Preview (sandbox-less): render the draft instantly on the preview server's own page via a ?__draft pointer, with reads/writes served by the decofile API against GitHub. Requires previewServerUrl (or legacy productionUrl) to be set to take effect."),Tc8=S0.boolean().nullable().optional().describe("EXPERIMENTAL: with Fast Preview on, refresh content edits via an in-place /live/previews render (no commit, no reload) instead of a commit + re-navigation. Deco-runtime preview targets only. Requires fastPreview."),Rc8=S0.string().nullable().optional().describe("Preview server URL \u2014 the deployment the CMS preview renders against (often the live site, e.g. https://acme.com). Painted in the preview iframe, and the render target for Fast Preview drafts. Supersedes the legacy productionUrl key."),zm1=S0.object({branch:S0.string().describe("Git branch backing this release"),name:S0.string().describe('User-facing name, e.g. "Black Friday 2026"'),color:S0.string().describe("Dot color token shown in the version switcher"),createdBy:S0.string().optional().describe("User ID who created the release"),createdAt:S0.string().optional().describe("ISO 8601 creation timestamp")}),qc8=S0.array(zm1).max(Dm1).nullable().optional().describe("Curated list of named, branch-backed releases shown in the version switcher. The base branch ('No ar') is derived, not stored here."),Hm0={instructions:S0.string().nullable().optional().describe("Instructions also used as system prompt"),subAgents:S0.array(S0.string()).max(Zc8).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:S0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:Nc8.nullable().optional().describe("UI customization settings"),sidebarViews:S0.array(Jm0).max(10).nullable().optional().describe("Project views selected for the sidebar. Interpret as an exact list when sidebarViewsVersion is 1; unversioned values use legacy native-only semantics. Runtime presence gates still apply."),sidebarViewsVersion:S0.literal(1).optional().describe("Version 1 marks metadata.sidebarViews as an exact list that can disable legacy default rows."),githubRepo:Dc8.nullable().optional().describe("Linked GitHub repository"),runtime:Oc8.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),knowledge:Ec8,siteSlug:S0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:Pc8,previewServerUrl:Rc8,productionUrl:S0.string().nullable().optional().describe("Legacy key for previewServerUrl \u2014 still read as a fallback. New writes use previewServerUrl."),fieldDescriptionTooltips:S0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title."),fastPreview:Ac8,releases:qc8,fastPreviewInPlace:Tc8},$Y=S0.object({id:S0.string().describe("Unique identifier"),title:S0.string().describe("Human-readable name"),description:S0.string().nullable().describe("Description"),icon:S0.string().nullable().describe("Icon URL"),created_at:S0.string().describe("Creation timestamp"),updated_at:S0.string().describe("Last update timestamp"),created_by:S0.string().describe("User ID who created this item"),updated_by:S0.string().optional().describe("User ID who last updated this item"),organization_id:S0.string().describe("Organization ID this item belongs to"),status:S0.enum(["active","inactive"]).describe("Current status"),pinned:S0.boolean().describe("Whether this space is pinned to the sidebar"),metadata:S0.object(Hm0).extend({instructions:S0.string().nullable().describe("Instructions also used as system prompt"),sandboxMap:Em1.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }")}).loose().describe("Metadata"),connections:S0.array(Bm1).describe("Connections with their selected tools, resources, and prompts")}),Fm0=S0.object({title:S0.string().min(1).max(120).describe("Short label shown on the chip"),description:S0.string().max(280).optional().describe("One-line subtitle shown under the title"),text:S0.string().min(1).max(4000).describe("The message sent to the agent when the prompt is clicked")}),j70=S0.object({title:S0.string().min(1).max(255).describe("Name for the virtual MCP"),description:S0.string().max(500).nullable().optional().describe("Optional description"),icon:S0.string().nullish().describe("Optional icon URL"),status:S0.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:S0.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:S0.object(Hm0).loose().superRefine(($,Z)=>{if("sandboxMap"in $)Z.addIssue({code:"custom",path:["sandboxMap"],message:"sandboxMap is managed by the sandbox lifecycle"})}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:S0.array(Lm1).max(Om1).describe("Connections to include/exclude (can be empty for exclusion mode)"),prompts:S0.array(Fm0).max(20).optional().describe("Optional kickstart prompts to seed on the agent. Each becomes a clickable conversation starter (icebreaker) on the agent. Author them from the agent's role and the tools it will have so they're coherent and immediately useful.")}),E70=S0.object({title:S0.string().min(1).max(255).optional().describe("New name"),description:S0.string().max(500).nullable().optional().describe("New description (null to clear)"),icon:S0.string().nullish().describe("New icon URL"),status:S0.enum(["active","inactive"]).optional().describe("New status"),pinned:S0.boolean().optional().describe("Pin/unpin from sidebar"),metadata:S0.object(Hm0).loose().superRefine(($,Z)=>{if("sandboxMap"in $)Z.addIssue({code:"custom",path:["sandboxMap"],message:"sandboxMap is managed by the sandbox lifecycle"})}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:S0.array(Lm1).max(Om1).optional().describe("New connections (replaces existing)"),prompts:S0.array(Fm0).max(20).optional().describe("Replace the agent's kickstart prompts with this full set. Omit to leave them unchanged; pass an empty array to remove all. Each becomes a clickable conversation starter (icebreaker).")})});function xz($){return Mc8.has($)}var wZ,Mc8,z70;var Am1=D(()=>{wZ=["deco","anthropic","openrouter","llmapi","google","openai-compatible"],Mc8=new Set(wZ);z70=[...wZ,"claude-code","codex"]});function Um0($,Z){return{id:crypto.randomUUID(),type:dn.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function P70($,Z){return{id:crypto.randomUUID(),type:dn.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function nH($,Z,Q){return{id:crypto.randomUUID(),type:dn.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...Q?.messageId!==void 0&&{message_id:Q.messageId},...Q?.virtualMcpId!==void 0&&{virtual_mcp_id:Q.virtualMcpId},...Q?.createdBy!==void 0&&{created_by:Q.createdBy},...Q?.triggerId!==void 0&&{trigger_id:Q.triggerId},...Q?.title!==void 0&&{title:Q.title},...Q?.branch!==void 0&&{branch:Q.branch},...Q?.harnessId!==void 0&&{harness_id:Q.harnessId},...Q?.createdAt!==void 0&&{created_at:Q.createdAt},...Q?.updatedAt!==void 0&&{updated_at:Q.updatedAt},...Q?.metadata!==void 0&&{metadata:Q.metadata}},time:new Date().toISOString()}}var Tm1,Ic8,dn,Vc8;var Rm1=D(()=>{Tm1=["in_progress","requires_action","failed","completed"],Ic8=[...Tm1,"expired"],dn={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},Vc8=Object.values(dn)});var A70=D(()=>{Fm1();Pm1();Am1();Rm1()});var tH=D(()=>{A70()});import{lookup as kc8}from"dns/promises";function pn($,Z){if($===10)return!0;if($===172&&Z!==void 0&&Z>=16&&Z<=31)return!0;if($===192&&Z===168)return!0;if($===127)return!0;if($===169&&Z===254)return!0;if($===0)return!0;if($===100&&Z!==void 0&&Z>=64&&Z<=127)return!0;return!1}function Nm0($){let Z=Number.parseInt($.padStart(4,"0"),16);return[Z>>8,Z&255]}function qm1($){let Z=$.split(":").filter((Q)=>Q.length>0);if($.startsWith("2002:")&&Z.length>=2){let[Q,Y]=Nm0(Z[1]);if(pn(Q,Y))return!0}if($.startsWith("64:ff9b::")&&Z.length>=4){let[Q,Y]=Nm0(Z[Z.length-2]);if(pn(Q,Y))return!0}if($.startsWith("::")&&Z.length===2){let[Q,Y]=Nm0(Z[0]);if(pn(Q,Y))return!0}return!1}function T70($){try{let Q=new URL($).hostname.toLowerCase();if(Q==="localhost"||Q==="0.0.0.0"||Q.endsWith(".local")||Q.endsWith(".internal")||Q.endsWith(".localhost"))return!0;let Y=Q.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(Y){let[,X,J]=Y.map(Number);if(pn(X,J))return!0}if(Q.startsWith("[")&&Q.endsWith("]")){let X=Q.slice(1,-1).toLowerCase();if(X==="::1"||X==="::")return!0;if(X.startsWith("::ffff:"))return!0;if(X.startsWith("fc")||X.startsWith("fd"))return!0;if(X.startsWith("fe80"))return!0;if(X.startsWith("100:"))return!0;if(X.startsWith("::1"))return!0;if(qm1(X))return!0}return!1}catch{return!0}}function Sc8($){let Z=$.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(Z){let[,Y,X]=Z.map(Number);return pn(Y,X)}let Q=$.toLowerCase();if(Q==="::1"||Q==="::")return!0;if(Q.startsWith("::ffff:"))return!0;if(Q.startsWith("fc")||Q.startsWith("fd"))return!0;if(Q.startsWith("fe80"))return!0;if(Q.startsWith("100:"))return!0;return qm1(Q)}async function Cc8($,Z=async(Q)=>(await kc8(Q,{all:!0})).map((Y)=>Y.address)){try{let Q=await Z($);return Q.length===0||Q.some(Sc8)}catch{return!0}}async function fz($){if(T70($))return"URLs targeting private networks are not allowed";let Q=new URL($).hostname;if(/^\d+\.\d+\.\d+\.\d+$/.test(Q)||Q.startsWith("[")&&Q.endsWith("]"))return null;try{return await _c8(Cc8(Q),5000,"DNS resolution timeout")?"URLs targeting private networks are not allowed":null}catch{return"URLs targeting private networks are not allowed"}}function _c8($,Z,Q){let Y,X=new Promise((J,G)=>{Y=setTimeout(()=>G(Error(Q)),Z)});return Promise.race([$,X]).finally(()=>clearTimeout(Y))}function yz($=fetch){return async(Z,Q)=>{let Y=await $(Z,{...Q,redirect:"manual"});if(Y.status>=300&&Y.status<400)throw Error("Refusing to follow a redirect from the remote server");return Y}}var nn=()=>{};var Mm1="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as Im1}from"crypto";function bc8($){if(!gz||gz.length<$)gz=Buffer.allocUnsafe($*vc8),Im1.getRandomValues(gz),Qh=0;else if(Qh+$>gz.length)Im1.getRandomValues(gz),Qh=0;Qh+=$}function R70($=21){bc8($|=0);let Z="";for(let Q=Qh-$;Q<Qh;Q++)Z+=Mm1[gz[Q]&63];return Z}var vc8=128,gz,Qh;var Bm0=()=>{};function a8($){return`${$}_${R70()}`}var ZY=D(()=>{Bm0()});function km1($,Z){return{id:y4.SELF(Z),title:"Deco CMS",description:"The MCP for the CMS API",connection_type:"HTTP",connection_url:`${$}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}function Sm1($,Z){return{id:y4.DEV_ASSETS(Z),title:"Local Files",description:"Local file storage for development. Files are stored in /data/assets/.",connection_type:"HTTP",connection_url:`${$}/mcp/dev-assets`,icon:"https://api.iconify.design/lucide:folder.svg?color=%23888",app_name:"@deco/dev-assets-mcp",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isFixed:!0,devOnly:!0,type:"dev-assets"}}}function C3($){return{is(Z){if(!Z)return null;if(!Z.startsWith($))return null;return Z.slice($.length)||null},get(Z){return`${$}${Z}`}}}function Cm1($){return{id:$.id,organization_id:$.organizationId,title:$.title,description:$.description,icon:$.icon,status:"active",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),created_by:"system",updated_by:void 0,metadata:{instructions:$.instructions??null,...$.ui?{ui:$.ui}:{}},pinned:!1,connections:[]}}function Dm0($){return Cm1({id:uz($),organizationId:$,title:"Super Agent",description:"Default agent that aggregates all organization connections",icon:xc8,ui:{layout:{defaultMainView:{type:"overview"},chatDefaultOpen:!0}}})}function fm1($){return Cm1({id:yc8($),organizationId:$,title:"Brand context setup",description:"Guided onboarding agent that extracts brand context from a website URL.",icon:"https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",instructions:gc8})}function hm1($,Z,Q="https://reports.decocms.com/api/v2/mcp"){return{id:y4.REPORTS($),title:"Deco Score",description:"Your store's Deco Score",connection_type:"HTTP",connection_url:Q,icon:"https://github.com/decocms.png",app_name:"commerce-discovery",app_id:null,connection_token:Z,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!1,type:"commerce-discovery"}}}function um1($,Z=y4.REPORTS($)){return{title:"Deco Score Agent",description:"Ask anything about your store's Deco Score",icon:"https://github.com/decocms.png",status:"active",pinned:!0,metadata:{type:"commerce-discovery",isDefault:!1,ui:{pinnedViews:[{connectionId:Z,toolName:"get_my_diagnostic",label:"Deco Score",icon:"https://github.com/decocms.png"}],layout:{defaultMainView:{type:"ext-apps",id:Z,toolName:"get_my_diagnostic"},chatDefaultOpen:!0}}},connections:[{connection_id:Z,selected_tools:null,selected_resources:null,selected_prompts:null}]}}function lm1($){if(!$)return!1;return Object.values(hz).some((Z)=>Z.is($)!==null)}function cm1($){let Z=Dm0($);return{...Z,id:Z.id,connection_type:"VIRTUAL",connection_url:`virtual://${Z.id}`,app_name:"decopilot",app_id:"decopilot",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"decopilot"},tools:[],bindings:[]}}var y4,Vm1="https://reports.decocms.com/api/v2/mcp",q70="get_my_diagnostic",_m1,DQ,uz,vm1,bm1,Om0,xc8="https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",fc8="#6366f1",MK5,xm1,M70,yc8,gc8,ym1,IK5,VK5,gm1,kK5,Yh,hz,_3,Lm0,SK5;var mm1=D(()=>{y4={SELF:($)=>`${$}_self`,REGISTRY:($)=>`${$}_registry`,COMMUNITY_REGISTRY:($)=>`${$}_community-registry`,DEV_ASSETS:($)=>`${$}_dev-assets`,SITE_DIAGNOSTICS:($)=>`site-diagnostics_${$}`,REPORTS:($)=>`${$}_commerce-discovery`};_m1=C3("decopilot_"),DQ=_m1.is,uz=_m1.get,vm1=C3("dev_"),bm1=vm1.get,Om0=vm1.is,MK5=`https://api.iconify.design/lucide:file-search.svg?color=${encodeURIComponent(fc8)}`;xm1=C3("brand-context-setup_"),M70=xm1.is,yc8=xm1.get,gc8=`
|
|
80
80
|
You are running the brand-context onboarding for the user's organization. Your only job in this thread is to set up the organization's brand context:
|
|
81
81
|
|
|
82
82
|
1. If the user hasn't already given you a website URL, ask for it in one short message. Accept whatever URL they give \u2014 don't quibble about format.
|
|
@@ -443,7 +443,7 @@ ${X}`}return $}});var EQ0=b((KP)=>{var so8=KP&&KP.__createBinding||(Object.creat
|
|
|
443
443
|
${Y("properties")} AS properties
|
|
444
444
|
FROM _flat
|
|
445
445
|
WHERE ${Y("type")} IN ('tool_call', 'llm_call')
|
|
446
|
-
)`}function Na8($){if(!$?.startDate&&!$?.endDate)return null;let Z="make_date(CAST(year AS INT), CAST(month AS INT), CAST(day AS INT))",Q=(X,J)=>new Date(X.getTime()+J*86400000).toISOString().slice(0,10),Y=[];if($.startDate)Y.push(`${Z} >= DATE '${Q($.startDate,-1)}'`);if($.endDate)Y.push(`${Z} <= DATE '${Q($.endDate,1)}'`);return Y.join(" AND ")}function Go1($){if(/[';]/.test($.bucket)||/[';]/.test($.prefix))throw Error("Invalid monitoring GCS bucket/prefix");let Z=$.prefix.replace(/^\/+|\/+$/g,""),Q=Z?`s3://${$.bucket}/${Z}`:`s3://${$.bucket}`,X=$.range?.startDate||$.range?.endDate?`${Q}/year=*/**/*`:`${Q}/**/*`;return Ua8(X,{range:$.range})}var Ha8="studio_monitoring_logs",Fa8="studio.monitoring.";var Wo1=D(()=>{D3()});import{sql as Ba8}from"kysely";function Xu($){if(!$)return null;return typeof $==="string"?JSON.parse($):$}function Ju($){return $?JSON.stringify($):null}function Ko1($){return{organizationId:$.organizationId,sidebar_items:Xu($.sidebar_items),coding_agent_mcp_excluded:Xu($.coding_agent_mcp_excluded),simple_mode:Xu($.simple_mode),default_home_agents:Xu($.default_home_agents),flags:Xu($.flags),submodule_credentials:Xu($.submodule_credentials),createdAt:$.createdAt,updatedAt:$.updatedAt}}class NP{db;constructor($){this.db=$}async get($){let Z=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",$).executeTakeFirst();return Z?Ko1(Z):null}async upsert($,Z){let Q=new Date().toISOString(),Y={sidebar_items:Ju(Z?.sidebar_items),coding_agent_mcp_excluded:Ju(Z?.coding_agent_mcp_excluded),simple_mode:Ju(Z?.simple_mode),default_home_agents:Ju(Z?.default_home_agents),flags:Ju(Z?.flags),submodule_credentials:Ju(Z?.submodule_credentials)},X=await this.db.insertInto("organization_settings").values({organizationId:$,...Y,createdAt:Q,updatedAt:Q}).onConflict((J)=>J.column("organizationId").doUpdateSet({sidebar_items:Y.sidebar_items??void 0,coding_agent_mcp_excluded:Y.coding_agent_mcp_excluded??void 0,simple_mode:Y.simple_mode??void 0,default_home_agents:Y.default_home_agents??void 0,flags:Y.flags?Ba8`coalesce("organization_settings"."flags", '{}'::jsonb) || ${Y.flags}::jsonb`:void 0,submodule_credentials:Y.submodule_credentials??void 0,updatedAt:Q})).returningAll().executeTakeFirstOrThrow();return Ko1(X)}}var Oi0=()=>{};class Di0{db;constructor($){this.db=$}async get($,Z){let Q=await this.db.selectFrom("user_model_preferences").select("tiers").where("user_id","=",$).where("organization_id","=",Z).executeTakeFirst();if(!Q)return null;return{tiers:(typeof Q.tiers==="string"?JSON.parse(Q.tiers):Q.tiers)??{}}}async upsert($,Z,Q){let Y=new Date().toISOString(),X=JSON.stringify(Q.tiers??{});return await this.db.insertInto("user_model_preferences").values({user_id:$,organization_id:Z,tiers:X,created_at:Y,updated_at:Y}).onConflict((J)=>J.columns(["user_id","organization_id"]).doUpdateSet({tiers:X,updated_at:Y})).execute(),{tiers:Q.tiers??{}}}}function Wu($){return typeof $==="string"?$:$.toISOString()}function Uo($){return{id:$.id,organization_id:$.organization_id,name:$.name,active:!!$.active,created_by:$.created_by,messages:$.messages,models:$.models,tools:$.tools??null,temperature:$.temperature,max_agent_steps:$.max_agent_steps??null,virtual_mcp_id:$.virtual_mcp_id,created_at:Wu($.created_at),updated_at:Wu($.updated_at)}}function Gu($){return{id:$.id,automation_id:$.automation_id,type:$.type,cron_expression:$.cron_expression,connection_id:$.connection_id,event_type:$.event_type,params:$.params,last_run_at:$.last_run_at?Wu($.last_run_at):null,next_run_at:$.next_run_at?Wu($.next_run_at):null,api_key_id:$.api_key_id??null,created_at:Wu($.created_at)}}function Fo1($){return Uo({id:$.a_id,organization_id:$.a_organization_id,name:$.a_name,active:$.a_active,created_by:$.a_created_by,messages:$.a_messages,models:$.a_models,tools:$.a_tools,temperature:$.a_temperature,max_agent_steps:$.a_max_agent_steps,virtual_mcp_id:$.a_virtual_mcp_id,created_at:$.a_created_at,updated_at:$.a_updated_at})}class Uo1{db;constructor($){this.db=$}async create($){let Z=new Date().toISOString(),Y={id:crypto.randomUUID(),organization_id:$.organization_id,name:$.name,active:$.active??!0,created_by:$.created_by,messages:$.messages,models:$.models,tools:$.tools??null,temperature:$.temperature??0.5,max_agent_steps:$.max_agent_steps??null,virtual_mcp_id:$.virtual_mcp_id,created_at:Z,updated_at:Z},X=await this.db.insertInto("automations").values(Y).returningAll().executeTakeFirstOrThrow();return Uo(X)}async findById($,Z){let Q=await this.db.selectFrom("automations").selectAll().where("id","=",$).where("organization_id","=",Z).executeTakeFirst();return Q?Uo(Q):null}async list($){return(await this.db.selectFrom("automations").selectAll().where("organization_id","=",$).orderBy("created_at","desc").execute()).map(Uo)}async listWithTriggerCounts($,Z){let Q=this.db.selectFrom("automations as a").leftJoin("automation_triggers as t","t.automation_id","a.id").select(["a.id","a.organization_id","a.name","a.active","a.created_by","a.messages","a.models","a.tools","a.temperature","a.max_agent_steps","a.virtual_mcp_id","a.created_at","a.updated_at"]).select((X)=>X.fn.count("t.id").as("trigger_count")).select((X)=>X.fn.min("t.next_run_at").as("nearest_next_run_at")).where("a.organization_id","=",$);if(Z)Q=Q.where("a.virtual_mcp_id","=",Z);return(await Q.groupBy(["a.id","a.organization_id","a.name","a.active","a.created_by","a.messages","a.models","a.tools","a.temperature","a.max_agent_steps","a.virtual_mcp_id","a.created_at","a.updated_at"]).orderBy("a.created_at","desc").execute()).map((X)=>({...Uo(X),trigger_count:Number(X.trigger_count),nearest_next_run_at:X.nearest_next_run_at?Wu(X.nearest_next_run_at):null}))}async update($,Z,Q){let X={updated_at:new Date().toISOString()};if(Q.name!==void 0)X.name=Q.name;if(Q.active!==void 0)X.active=Q.active;if(Q.messages!==void 0)X.messages=Q.messages;if(Q.models!==void 0)X.models=Q.models;if(Q.tools!==void 0)X.tools=Q.tools;if(Q.temperature!==void 0)X.temperature=Q.temperature;if(Q.max_agent_steps!==void 0)X.max_agent_steps=Q.max_agent_steps;await this.db.updateTable("automations").set(X).where("id","=",$).where("organization_id","=",Z).execute();let J=await this.findById($,Z);if(!J)throw Error("Automation not found after update");return J}async delete($,Z){return{success:((await this.db.deleteFrom("automations").where("id","=",$).where("organization_id","=",Z).executeTakeFirst()).numDeletedRows??0n)>0n}}async addTrigger($){let Z=new Date().toISOString(),Y={id:crypto.randomUUID(),automation_id:$.automation_id,type:$.type,cron_expression:$.cron_expression??null,connection_id:$.connection_id??null,event_type:$.event_type??null,params:$.params??null,last_run_at:null,next_run_at:$.next_run_at??null,api_key_id:$.api_key_id??null,created_at:Z},X=await this.db.insertInto("automation_triggers").values(Y).returningAll().executeTakeFirstOrThrow();return Gu(X)}async removeTrigger($,Z){return{success:((await this.db.deleteFrom("automation_triggers").where("id","=",$).where("automation_id","=",Z).executeTakeFirst()).numDeletedRows??0n)>0n}}async listTriggers($){return(await this.db.selectFrom("automation_triggers").selectAll().where("automation_id","=",$).orderBy("created_at","asc").execute()).map(Gu)}async listTriggersForAutomations($){if($.length===0)return[];return(await this.db.selectFrom("automation_triggers").selectAll().where("automation_id","in",$).orderBy("created_at","asc").execute()).map(Gu)}async findTriggerById($){let Z=await this.db.selectFrom("automation_triggers").selectAll().where("id","=",$).executeTakeFirst();return Z?Gu(Z):null}async setTriggerApiKeyId($,Z){await this.db.updateTable("automation_triggers").set({api_key_id:Z}).where("id","=",$).execute()}async findActiveEventTriggers($,Z,Q){return(await this.db.selectFrom("automation_triggers as t").innerJoin("automations as a","a.id","t.automation_id").select(["t.id","t.automation_id","t.type","t.cron_expression","t.connection_id","t.event_type","t.params","t.last_run_at","t.api_key_id","t.created_at",...Ho1]).where("t.type","=","event").where("t.connection_id","=",$).where("t.event_type","=",Z).where("a.organization_id","=",Q).where("a.active","=",!0).execute()).map((X)=>({...Gu(X),automation:Fo1(X)}))}async listActiveByEventTriggerConnectionId($){return await this.db.selectFrom("automation_triggers as t").innerJoin("automations as a","a.id","t.automation_id").select(["a.id","a.name"]).where("t.type","=","event").where("t.connection_id","=",$).where("a.active","=",!0).distinct().execute()}async findAllCronTriggers(){return(await this.db.selectFrom("automation_triggers as t").innerJoin("automations as a","a.id","t.automation_id").select(["t.id","t.automation_id","t.type","t.cron_expression","t.connection_id","t.event_type","t.params","t.last_run_at","t.api_key_id","t.created_at",...Ho1]).where("t.type","=","cron").execute()).map((Z)=>({...Gu(Z),automation:Fo1(Z)}))}async updateNextRunAt($,Z){await this.db.updateTable("automation_triggers").set({next_run_at:Z}).where("id","=",$).execute()}async createAutomationRunThread($,Z){let Q=a8("thrd"),Y=new Date().toISOString();return await this.db.insertInto("threads").values({id:Q,organization_id:$.organization_id,title:`Automation: ${$.name}`,description:null,status:"in_progress",trigger_id:Z,virtual_mcp_id:$.virtual_mcp_id,harness_id:"decopilot",metadata:JSON.stringify({runtime:"sandbox"}),hidden:!1,message_storage_version:2,created_at:Y,updated_at:Y,created_by:$.created_by,updated_by:null}).execute(),Q}async markRunFailed($,Z,Q){await this.db.updateTable("threads").set({status:"failed",updated_at:new Date().toISOString(),...Z!=null?{failure_reason:Z}:{},...Q!=null?{failure_kind:Q}:{}}).where("id","=",$).where("status","=","in_progress").execute()}async markRunCompleted($){await this.db.updateTable("threads").set({status:"completed",updated_at:new Date().toISOString()}).where("id","=",$).where("status","=","in_progress").execute()}async updateTriggerLastRunAt($,Z){await this.db.updateTable("automation_triggers").set({last_run_at:Z}).where("id","=",$).execute()}async deactivateAutomation($){await this.db.updateTable("automations").set({active:!1,updated_at:new Date().toISOString()}).where("id","=",$).where("active","=",!0).execute()}async getRunStats($,Z,Q){let Y=this.db.selectFrom("threads as th").innerJoin("automation_triggers as t","t.id","th.trigger_id").select("th.status").select((G)=>G.fn.count("th.id").as("count")).where("t.automation_id","=",$).where("th.organization_id","=",Z).where("th.hidden","=",!1).groupBy("th.status");if(Q?.startDate)Y=Y.where("th.created_at",">=",Q.startDate);if(Q?.endDate)Y=Y.where("th.created_at","<=",Q.endDate);let X=await Y.execute(),J={total:0,completed:0,failed:0,inProgress:0};for(let G of X){let W=Number(G.count);if(J.total+=W,G.status==="completed")J.completed+=W;else if(G.status==="failed")J.failed+=W;else if(G.status==="in_progress")J.inProgress+=W}return J}async listRunThreadIds($,Z,Q){let Y=this.db.selectFrom("threads as th").innerJoin("automation_triggers as t","t.id","th.trigger_id").select("th.id").where("t.automation_id","=",$).where("th.organization_id","=",Z).where("th.hidden","=",!1).orderBy("th.created_at","desc").limit(Q?.limit??500);if(Q?.startDate)Y=Y.where("th.created_at",">=",Q.startDate);if(Q?.endDate)Y=Y.where("th.created_at","<=",Q.endDate);return(await Y.execute()).map((J)=>J.id)}}function _Q0($){return new Uo1($)}var Ho1;var Li0=D(()=>{ZY();Ho1=["a.id as a_id","a.organization_id as a_organization_id","a.name as a_name","a.active as a_active","a.created_by as a_created_by","a.messages as a_messages","a.models as a_models","a.tools as a_tools","a.temperature as a_temperature","a.max_agent_steps as a_max_agent_steps","a.virtual_mcp_id as a_virtual_mcp_id","a.created_at as a_created_at","a.updated_at as a_updated_at"]});import{createHash as Oa8,randomBytes as Da8}from"crypto";function No1($){return Oa8("sha256").update($).digest("hex")}function La8(){return Da8(32).toString("hex")}class No{db;constructor($){this.db=$}async generateTokenPair(){let $=La8(),Z=await No1($);return{plaintext:$,hash:Z}}async persistTokenHash($,Z,Q){let Y=crypto.randomUUID();await this.db.insertInto("trigger_callback_tokens").values({id:Y,organization_id:$,connection_id:Z,token_hash:Q,created_at:new Date().toISOString()}).onConflict((X)=>X.columns(["connection_id","organization_id"]).doUpdateSet({id:Y,token_hash:Q})).execute()}async createOrRotateToken($,Z){let{plaintext:Q,hash:Y}=await this.generateTokenPair();return await this.persistTokenHash($,Z,Y),Q}async validateToken($){let Z=await No1($),Q=await this.db.selectFrom("trigger_callback_tokens").select(["organization_id","connection_id"]).where("token_hash","=",Z).executeTakeFirst();if(!Q)return null;return{organizationId:Q.organization_id,connectionId:Q.connection_id}}async deleteByConnection($,Z){await this.db.deleteFrom("trigger_callback_tokens").where("connection_id","=",$).where("organization_id","=",Z).execute()}}var wi0=()=>{};function vQ0($){if(!$)return null;try{return JSON.parse($)}catch{return null}}function wa8($){if(!$)return null;if(!Array.isArray($)&&typeof $==="object"){let Z=$;if(Object.keys(Z).some((Y)=>bQ0.has(Y))){let Y={};for(let X of bQ0)if(typeof Z[X]==="string")Y[X]=Z[X];return Y}let Q={};for(let[Y,X]of Object.entries(Z))if(typeof X==="string"&&bQ0.has(Y.toLowerCase()))Q[Y.toLowerCase()]=X;return Object.keys(Q).length>0?Q:null}if(Array.isArray($)){let Z={};for(let Q of $){let Y=Q,X=Y.label?.toLowerCase?.(),J=Y.value;if(X&&J&&bQ0.has(X))Z[X]=J}return Object.keys(Z).length>0?Z:null}return null}function Ea8($){if(!$)return null;if(!Array.isArray($)&&typeof $==="object"){let Z=$;if(typeof Z.heading==="string"||typeof Z.body==="string"||typeof Z.code==="string")return{heading:typeof Z.heading==="string"?Z.heading:void 0,body:typeof Z.body==="string"?Z.body:void 0,code:typeof Z.code==="string"?Z.code:void 0};return null}if(Array.isArray($)){let Z={},Q=[];for(let Y of $){let X=Y,J=X.name??X.family??void 0,G=X.role?.toLowerCase?.()??"";if(!J)continue;let W=ja8[G];if(W&&!Z[W])Z[W]=J;else Q.push(J)}if(!Z.body&&Q[0])Z.body=Q[0];return Object.keys(Z).length>0?Z:null}return null}function ji0($){return{id:$.id,organizationId:$.organization_id,name:$.name,domain:$.domain,overview:$.overview,logo:$.logo,favicon:$.favicon,ogImage:$.og_image,fonts:Ea8(vQ0($.fonts)),colors:wa8(vQ0($.colors)),images:vQ0($.images),metadata:vQ0($.metadata),archivedAt:$.archived_at,isDefault:$.is_default,createdAt:$.created_at,updatedAt:$.updated_at}}class Bo{db;constructor($){this.db=$}async get($,Z){let Q=await this.db.selectFrom("brand_context").selectAll().where("id","=",$).where("organization_id","=",Z).executeTakeFirst();if(!Q)return null;return ji0(Q)}async list($,Z){let Q=this.db.selectFrom("brand_context").selectAll().where("organization_id","=",$);if(!Z?.includeArchived)Q=Q.where("archived_at","is",null);return(await Q.orderBy("created_at","asc").execute()).map(ji0)}async create($,Z){let Q=crypto.randomUUID(),Y=new Date().toISOString();return await this.db.insertInto("brand_context").values({id:Q,organization_id:$,name:Z.name,domain:Z.domain,overview:Z.overview,logo:Z.logo,favicon:Z.favicon,og_image:Z.ogImage,fonts:Z.fonts?JSON.stringify(Z.fonts):null,colors:Z.colors?JSON.stringify(Z.colors):null,images:Z.images?JSON.stringify(Z.images):null,metadata:Z.metadata?JSON.stringify(Z.metadata):null,archived_at:null,is_default:!1,created_at:Y,updated_at:Y}).execute(),await this.get(Q,$)}async update($,Z,Q){let X={updated_at:new Date().toISOString()};if(Q.name!==void 0)X.name=Q.name;if(Q.domain!==void 0)X.domain=Q.domain;if(Q.overview!==void 0)X.overview=Q.overview;if(Q.logo!==void 0)X.logo=Q.logo;if(Q.favicon!==void 0)X.favicon=Q.favicon;if(Q.ogImage!==void 0)X.og_image=Q.ogImage;if(Q.fonts!==void 0)X.fonts=Q.fonts?JSON.stringify(Q.fonts):null;if(Q.colors!==void 0)X.colors=Q.colors?JSON.stringify(Q.colors):null;if(Q.images!==void 0)X.images=Q.images?JSON.stringify(Q.images):null;if(Q.metadata!==void 0)X.metadata=Q.metadata?JSON.stringify(Q.metadata):null;if(Q.archivedAt!==void 0)X.archived_at=Q.archivedAt??null;if(Q.isDefault!==void 0)X.is_default=Q.isDefault;await this.db.updateTable("brand_context").set(X).where("id","=",$).where("organization_id","=",Z).execute();let J=await this.get($,Z);if(!J)throw Error("Brand context not found");return J}async getDefault($){let Z=await this.db.selectFrom("brand_context").selectAll().where("organization_id","=",$).where("is_default","=",!0).where("archived_at","is",null).executeTakeFirst();if(!Z)return null;return ji0(Z)}async setDefault($,Z){await this.db.transaction().execute(async(Y)=>{await Y.updateTable("brand_context").set({is_default:!1}).where("organization_id","=",Z).where("is_default","=",!0).execute(),await Y.updateTable("brand_context").set({is_default:!0,updated_at:new Date().toISOString()}).where("id","=",$).where("organization_id","=",Z).execute()});let Q=await this.get($,Z);if(!Q)throw Error("Brand context not found");return Q}async delete($,Z){await this.db.deleteFrom("brand_context").where("id","=",$).where("organization_id","=",Z).execute()}}var bQ0,ja8;var Ei0=D(()=>{bQ0=new Set(["primary","secondary","accent","background","foreground"]);ja8={heading:"heading",headings:"heading",head:"heading",title:"heading",body:"body",primary:"body",text:"body",code:"code",monospace:"code",mono:"code"}});function xQ0($){return{id:$.id,organizationId:$.organization_id,domain:$.domain,joinMode:$.join_mode,verificationStatus:$.verification_status==="verified"?"verified":"pending",verificationMethod:$.verification_method??null,verificationToken:$.verification_token,verifiedAt:$.verified_at,createdAt:$.created_at,updatedAt:$.updated_at}}class OG{db;constructor($){this.db=$}async getAllByDomain($){return(await this.db.selectFrom("organization_domains").selectAll().where("domain","=",$.toLowerCase()).execute()).map(xQ0)}async listByOrganizationId($){return(await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",$).orderBy("created_at","asc").execute()).map(xQ0)}async getById($){let Z=await this.db.selectFrom("organization_domains").selectAll().where("id","=",$).executeTakeFirst();return Z?xQ0(Z):null}async getByOrgAndDomain($,Z){let Q=await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",$).where("domain","=",Z.toLowerCase()).executeTakeFirst();return Q?xQ0(Q):null}async add($,Z,Q={}){let Y=Z.toLowerCase(),X=await this.getByOrgAndDomain($,Y);if(X)return X;let J=new Date().toISOString(),G=crypto.randomUUID(),W=Q.verificationStatus??"pending";try{await this.db.insertInto("organization_domains").values({id:G,organization_id:$,domain:Y,join_mode:Q.joinMode??"off",verification_status:W,verification_method:Q.verificationMethod??null,verification_token:Q.verificationToken??null,verified_at:W==="verified"?J:null,created_at:J,updated_at:J}).execute()}catch(H){if(H.code==="23505"){let F=await this.getByOrgAndDomain($,Y);if(F)return F}throw H}let K=await this.getById(G);if(!K)throw Error("Failed to add domain");return K}async updateJoinMode($,Z){await this.db.updateTable("organization_domains").set({join_mode:Z,updated_at:new Date().toISOString()}).where("id","=",$).execute();let Q=await this.getById($);if(!Q)throw Error("Domain not found");return Q}async markVerified($,Z){let Q=new Date().toISOString();await this.db.updateTable("organization_domains").set({verification_status:"verified",verification_method:Z,verification_token:null,verified_at:Q,updated_at:Q}).where("id","=",$).execute();let Y=await this.getById($);if(!Y)throw Error("Domain not found");return Y}async removeById($){await this.db.deleteFrom("organization_domains").where("id","=",$).execute()}}function zi0($){return{id:$.id,organizationId:$.organization_id,userId:$.user_id,status:$.status,decidedBy:$.decided_by,decidedAt:$.decided_at,createdAt:$.created_at,updatedAt:$.updated_at}}class Ku{db;constructor($){this.db=$}async create($,Z){let Q=await this.getPending($,Z);if(Q)return Q;let Y=new Date().toISOString(),X=crypto.randomUUID();try{await this.db.insertInto("organization_join_requests").values({id:X,organization_id:$,user_id:Z,status:"pending",decided_by:null,decided_at:null,created_at:Y,updated_at:Y}).execute()}catch(G){if(G.code==="23505"){let W=await this.getPending($,Z);if(W)return W}throw G}let J=await this.getById(X);if(!J)throw Error("Failed to create join request");return J}async getById($){let Z=await this.db.selectFrom("organization_join_requests").selectAll().where("id","=",$).executeTakeFirst();return Z?zi0(Z):null}async getPending($,Z){let Q=await this.db.selectFrom("organization_join_requests").selectAll().where("organization_id","=",$).where("user_id","=",Z).where("status","=","pending").executeTakeFirst();return Q?zi0(Q):null}async listPendingWithUser($){return(await this.db.selectFrom("organization_join_requests as r").innerJoin("user","user.id","r.user_id").select(["r.id as id","r.organization_id as organization_id","r.user_id as user_id","r.status as status","r.decided_by as decided_by","r.decided_at as decided_at","r.created_at as created_at","r.updated_at as updated_at","user.name as user_name","user.email as user_email","user.image as user_image"]).where("r.organization_id","=",$).where("r.status","=","pending").orderBy("r.created_at","asc").execute()).map((Q)=>({...zi0(Q),user:{id:Q.user_id,name:Q.user_name,email:Q.user_email,image:Q.user_image}}))}async decide($,Z,Q){let Y=new Date().toISOString();if((await this.db.updateTable("organization_join_requests").set({status:Z,decided_by:Q,decided_at:Y,updated_at:Y}).where("id","=",$).where("status","=","pending").executeTakeFirst()).numUpdatedRows===0n)return null;return this.getById($)}}class Oo{db;constructor($){this.db=$}async get($,Z){let Q=await this.db.selectFrom("kv").select("value").where("organization_id","=",$).where("key","=",Z).executeTakeFirst();if(!Q)return null;return Q.value}async set($,Z,Q){await this.db.insertInto("kv").values({organization_id:$,key:Z,value:JSON.stringify(Q),updated_at:new Date().toISOString()}).onConflict((Y)=>Y.columns(["organization_id","key"]).doUpdateSet({value:JSON.stringify(Q),updated_at:new Date().toISOString()})).execute()}async delete($,Z){await this.db.deleteFrom("kv").where("organization_id","=",$).where("key","=",Z).execute()}}function za8($){if(!$||!Array.isArray($.interests))return null;return{interests:$.interests}}class Pi0{kv;constructor($){this.kv=$}async getForAgent($,Z,Q){let Y=await this.kv.get($,Bo1(Z,Q));return za8(Y)}async setForAgent($,Z,Q,Y){await this.kv.set($,Bo1(Z,Q),Y)}}var Oo1="interests:",Bo1=($,Z)=>`interests:${$}:${Z}`;class Ai0{db;vault;constructor($,Z){this.db=$;this.vault=Z}async getByOrgId($){let Z=await this.db.selectFrom("org_sso_config").selectAll().where("organization_id","=",$).executeTakeFirst();if(!Z)return null;return this.toRuntime(Z)}async getByDomain($){let Z=await this.db.selectFrom("org_sso_config").selectAll().where("domain","=",$.toLowerCase()).executeTakeFirst();if(!Z)return null;return this.toRuntime(Z)}async upsert($,Z){let Q=new Date().toISOString(),Y=crypto.randomUUID(),X=await this.vault.encrypt(Z.clientSecret),J=JSON.stringify(Z.scopes??["openid","email","profile"]),G=Z.enforced===void 0?void 0:Z.enforced?1:0;await this.db.insertInto("org_sso_config").values({id:Y,organization_id:$,issuer:Z.issuer,client_id:Z.clientId,client_secret:X,discovery_endpoint:Z.discoveryEndpoint??null,scopes:J,domain:Z.domain.toLowerCase(),enforced:G??0,created_at:Q,updated_at:Q}).onConflict((K)=>K.column("organization_id").doUpdateSet({issuer:Z.issuer,client_id:Z.clientId,client_secret:X,discovery_endpoint:Z.discoveryEndpoint??null,scopes:J,domain:Z.domain.toLowerCase(),...G!==void 0?{enforced:G}:{},updated_at:Q})).execute();let W=await this.getByOrgId($);if(!W)throw Error("Failed to upsert org SSO config");return W}async setEnforced($,Z){await this.db.updateTable("org_sso_config").set({enforced:Z?1:0,updated_at:new Date().toISOString()}).where("organization_id","=",$).execute()}async delete($){await this.db.deleteFrom("org_sso_config").where("organization_id","=",$).execute()}toPublic($){let{clientSecret:Z,...Q}=$;return Q}async toRuntime($){let Z=await this.vault.decrypt($.client_secret),Q=typeof $.scopes==="string"?JSON.parse($.scopes):$.scopes;return{id:$.id,organizationId:$.organization_id,issuer:$.issuer,clientId:$.client_id,clientSecret:Z,discoveryEndpoint:$.discovery_endpoint,scopes:Q,domain:$.domain,enforced:$.enforced===1,createdAt:$.created_at,updatedAt:$.updated_at}}}class Ti0{db;constructor($){this.db=$}async get($,Z){let Q=await this.db.selectFrom("org_sso_sessions").selectAll().where("user_id","=",$).where("organization_id","=",Z).executeTakeFirst();if(!Q)return null;return{id:Q.id,userId:Q.user_id,organizationId:Q.organization_id,authenticatedAt:Q.authenticated_at,expiresAt:Q.expires_at,createdAt:Q.created_at}}async isValid($,Z){let Q=await this.get($,Z);if(!Q)return!1;return new Date(Q.expiresAt)>new Date}async upsert($,Z){let Q=new Date,Y=new Date(Q.getTime()+86400000),X=crypto.randomUUID();await this.db.insertInto("org_sso_sessions").values({id:X,user_id:$,organization_id:Z,authenticated_at:Q.toISOString(),expires_at:Y.toISOString(),created_at:Q.toISOString()}).onConflict((G)=>G.columns(["user_id","organization_id"]).doUpdateSet({authenticated_at:Q.toISOString(),expires_at:Y.toISOString()})).execute();let J=await this.get($,Z);if(!J)throw Error("Failed to upsert SSO session");return J}async deleteExpired(){await this.db.deleteFrom("org_sso_sessions").where("expires_at","<",new Date().toISOString()).execute()}}class Do{db;constructor($){this.db=$}async listOrgTags($){return(await this.db.selectFrom("organization_tags").selectAll().where("organization_id","=",$).orderBy("name","asc").execute()).map((Q)=>this.tagFromDbRow(Q))}async getTag($){let Z=await this.db.selectFrom("organization_tags").selectAll().where("id","=",$).executeTakeFirst();return Z?this.tagFromDbRow(Z):null}async getTagsByIds($){if($.length===0)return[];return(await this.db.selectFrom("organization_tags").selectAll().where("id","in",$).execute()).map((Q)=>this.tagFromDbRow(Q))}async getTagByName($,Z){let Q=await this.db.selectFrom("organization_tags").selectAll().where("organization_id","=",$).where("name","=",Z).executeTakeFirst();return Q?this.tagFromDbRow(Q):null}async createTag($,Z,Q){let Y=a8("tag"),X=new Date().toISOString();await this.db.insertInto("organization_tags").values({id:Y,organization_id:$,name:Z,color:Q??null,created_at:X}).onConflict((G)=>G.columns(["organization_id","name"]).doNothing()).execute();let J=await this.getTagByName($,Z);if(!J)throw Error(`Failed to create or retrieve tag: ${Z}`);return J}async deleteTag($){await this.db.deleteFrom("organization_tags").where("id","=",$).execute()}async getMemberTags($){return(await this.db.selectFrom("member_tags").innerJoin("organization_tags","organization_tags.id","member_tags.tag_id").select(["organization_tags.id","organization_tags.organization_id","organization_tags.name","organization_tags.color","organization_tags.created_at"]).where("member_tags.member_id","=",$).orderBy("organization_tags.name","asc").execute()).map((Q)=>this.tagFromDbRow(Q))}async setMemberTags($,Z){await this.db.transaction().execute(async(Q)=>{if(await Q.deleteFrom("member_tags").where("member_id","=",$).execute(),Z.length>0){let Y=new Date().toISOString();await Q.insertInto("member_tags").values(Z.map((X)=>({id:a8("mtag"),member_id:$,tag_id:X,created_at:Y}))).execute()}})}async addMemberTag($,Z){let Q=new Date().toISOString();await this.db.insertInto("member_tags").values({id:a8("mtag"),member_id:$,tag_id:Z,created_at:Q}).onConflict((Y)=>Y.columns(["member_id","tag_id"]).doNothing()).execute()}async removeMemberTag($,Z){await this.db.deleteFrom("member_tags").where("member_id","=",$).where("tag_id","=",Z).execute()}async verifyMemberOrg($,Z){return await this.db.selectFrom("member").select("id").where("id","=",$).where("organizationId","=",Z).executeTakeFirst()!==void 0}async getUserTagsInOrg($,Z){return(await this.db.selectFrom("member").innerJoin("member_tags","member_tags.member_id","member.id").innerJoin("organization_tags","organization_tags.id","member_tags.tag_id").select(["organization_tags.id","organization_tags.organization_id","organization_tags.name","organization_tags.color","organization_tags.created_at"]).where("member.userId","=",$).where("member.organizationId","=",Z).orderBy("organization_tags.name","asc").execute()).map((Y)=>this.tagFromDbRow(Y))}async getMembersWithTags($){let Z=await this.db.selectFrom("member").leftJoin("member_tags","member_tags.member_id","member.id").leftJoin("organization_tags","organization_tags.id","member_tags.tag_id").select(["member.id as memberId","organization_tags.name as tagName"]).where("member.organizationId","=",$).execute(),Q=new Map;for(let Y of Z){if(!Q.has(Y.memberId))Q.set(Y.memberId,[]);if(Y.tagName)Q.get(Y.memberId).push(Y.tagName)}return Q}tagFromDbRow($){return{id:$.id,organizationId:$.organization_id,name:$.name,color:$.color??null,createdAt:$.created_at}}}var Ri0=D(()=>{ZY()});class qi0{db;constructor($){this.db=$}async listBySite($,Z){return(await this.db.selectFrom("experiments").selectAll().where("organization_id","=",$).where("site","=",Z).orderBy("created_at","desc").execute()).map((Y)=>this.fromRow(Y))}async getByKey($,Z,Q){let Y=await this.db.selectFrom("experiments").selectAll().where("organization_id","=",$).where("site","=",Z).where("key","=",Q).executeTakeFirst();return Y?this.fromRow(Y):null}async create($){let Z=a8("exp"),Q=new Date().toISOString();await this.db.insertInto("experiments").values({id:Z,organization_id:$.organizationId,site:$.site,key:$.key,name:$.name,status:"draft",goals:JSON.stringify($.goals??[]),variants:JSON.stringify($.variants??[]),created_by:$.createdBy,created_at:Q,updated_at:Q}).execute();let Y=await this.getByKey($.organizationId,$.site,$.key);if(!Y)throw Error("failed to create experiment");return Y}async update($,Z,Q,Y){let X=await this.getByKey($,Z,Q);if(!X)return null;let J=new Date().toISOString(),G={updated_at:J};if(Y.name!==void 0)G.name=Y.name;if(Y.goals!==void 0)G.goals=JSON.stringify(Y.goals);if(Y.variants!==void 0)G.variants=JSON.stringify(Y.variants);if(Y.status!==void 0){if(G.status=Y.status,Y.status==="running"&&!X.startedAt)G.started_at=J;if(Y.status==="ended"&&!X.endedAt)G.ended_at=J}return await this.db.updateTable("experiments").set(G).where("organization_id","=",$).where("site","=",Z).where("key","=",Q).execute(),this.getByKey($,Z,Q)}async delete($,Z,Q){return((await this.db.deleteFrom("experiments").where("organization_id","=",$).where("site","=",Z).where("key","=",Q).executeTakeFirst()).numDeletedRows??0n)>0n}fromRow($){let Z=(Q)=>new Date(Q).toISOString();return{id:$.id,organizationId:$.organization_id,site:$.site,key:$.key,name:$.name,status:["running","paused","ended"].includes($.status)?$.status:"draft",goals:$.goals??[],variants:$.variants??[],startedAt:$.started_at?Z($.started_at):null,endedAt:$.ended_at?Z($.ended_at):null,createdBy:$.created_by,createdAt:Z($.created_at),updatedAt:Z($.updated_at)}}}var Do1=D(()=>{ZY()});import{sql as Pa8}from"kysely";function Mi0($){return{organizationId:$.organization_id,status:$.status,stripeCustomerId:$.stripe_customer_id,stripeSubscriptionId:$.stripe_subscription_id,currentPeriodEnd:$.current_period_end,lastStripeEventAt:$.last_stripe_event_at,freeTaskExecutions:$.free_task_executions,monthlyTaskExecutions:$.monthly_task_executions}}class DG{db;constructor($){this.db=$}async getBilling($){let Z=await this.db.selectFrom("organization_billing").selectAll().where("organization_id","=",$).executeTakeFirst();return Z?Mi0(Z):null}async ensureBilling($){let Z=await this.getBilling($);if(Z)return Z;try{await this.db.insertInto("organization_billing").values({organization_id:$}).onConflict((Q)=>Q.column("organization_id").doNothing()).execute()}catch{return null}return await this.getBilling($)}async getBillingByStripeSubscriptionId($){let Z=await this.db.selectFrom("organization_billing").selectAll().where("stripe_subscription_id","=",$).executeTakeFirst();return Z?Mi0(Z):null}async listSubscriptionsPastPeriodEnd($,Z){return(await this.db.selectFrom("organization_billing").selectAll().where("stripe_subscription_id","is not",null).where("status","<>","canceled").where("current_period_end","is not",null).where("current_period_end","<",$).orderBy("current_period_end","asc").limit(Z).execute()).map(Mi0)}async bindSubscription($,Z){return((await this.db.updateTable("organization_billing").set({stripe_subscription_id:Z.stripeSubscriptionId,...Z.stripeCustomerId!==void 0&&{stripe_customer_id:Z.stripeCustomerId},...Z.status!==void 0&&{status:Z.status},...Z.lastStripeEventAt!==void 0&&{last_stripe_event_at:Z.lastStripeEventAt},updated_at:new Date}).where("organization_id","=",$).where((Y)=>Y.or([Y("stripe_subscription_id","is",null),Y("stripe_subscription_id","=",Z.stripeSubscriptionId)])).executeTakeFirst()).numUpdatedRows??0n)>0n}async updateStripeState($,Z){return((await this.db.updateTable("organization_billing").set({...Z.stripeCustomerId!==void 0&&{stripe_customer_id:Z.stripeCustomerId},...Z.stripeSubscriptionId!==void 0&&{stripe_subscription_id:Z.stripeSubscriptionId},...Z.status!==void 0&&{status:Z.status},...Z.currentPeriodEnd!==void 0&&{current_period_end:Z.currentPeriodEnd},...Z.lastStripeEventAt!==void 0&&{last_stripe_event_at:Z.lastStripeEventAt},updated_at:new Date}).where("organization_id","=",$).executeTakeFirst()).numUpdatedRows??0n)>0n}async taskClaim($){let Z=await this.db.selectFrom("task_quota_claims").select(["run_count","state"]).where("task_board_item_id","=",$).executeTakeFirst();return Z?{runCount:Z.run_count,state:Z.state}:null}static liveClaimCount($,Z,Q){return $.selectFrom("task_quota_claims").select((Y)=>Y.fn.countAll().as("count")).where("organization_id","=",Z).where("period_key","=",Q).where("state","<>","released").executeTakeFirst().then((Y)=>Number(Y?.count??0))}async countTaskClaims($,Z){return await DG.liveClaimCount(this.db,$,Z)}async claimTaskUnderLimit($,Z,Q,Y,X){return await this.db.transaction().execute(async(J)=>{await J.insertInto("organization_billing").values({organization_id:$}).onConflict((K)=>K.column("organization_id").doNothing()).execute(),await J.selectFrom("organization_billing").select("organization_id").where("organization_id","=",$).forUpdate().executeTakeFirstOrThrow();let G=await J.selectFrom("task_quota_claims").select(["run_count","state"]).where("task_board_item_id","=",Z).executeTakeFirst();if(G&&G.run_count>=X)return"runs_exhausted";let W=()=>DG.liveClaimCount(J,$,Q);if(G&&G.state!=="released")return await J.updateTable("task_quota_claims").set({run_count:G.run_count+1}).where("task_board_item_id","=",Z).execute(),"rerun";if(await W()>=Y)return"exhausted";if(G)return await J.updateTable("task_quota_claims").set({state:"held",period_key:Q,run_count:G.run_count+1}).where("task_board_item_id","=",Z).execute(),"claimed";return await J.insertInto("task_quota_claims").values({task_board_item_id:Z,organization_id:$,period_key:Q,state:"held"}).execute(),"claimed"})}async releaseTaskClaim($,Z){return((await this.db.updateTable("task_quota_claims").set({state:"released"}).where("organization_id","=",$).where("task_board_item_id","=",Z).where("state","=","held").executeTakeFirst()).numUpdatedRows??0n)>0n}async rollbackTaskClaim($,Z,{releaseSlot:Q}){await this.db.updateTable("task_quota_claims").set(()=>({...Q?{state:"released"}:{},run_count:Pa8`greatest(run_count - 1, 0)`})).where("organization_id","=",$).where("task_board_item_id","=",Z).where("state","=","held").execute()}}var Lo=()=>{};class Ii0{db;constructor($){this.db=$}async findById($,Z){let Q=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",$).where((Y)=>Y.exists(Y.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",$).where("m2.userId","=",Z))).executeTakeFirst();if(!Q)return null;return{id:Q.id,name:Q.name,email:Q.email,role:"",createdAt:Q.createdAt,updatedAt:Q.updatedAt,image:Q.image??void 0}}}function YF($){let Z=$?.["mcp.studio"];if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z;let Q=$?.["mcp.mesh"];if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q;return}function wo1(){let $={};for(let Z of fQ0){if(Z.id==="basic-usage")continue;$[Z.id]=!0}return $}function ki0($){let Z=(J)=>{let G=$[J];return Array.isArray(G)?G:[]},Q=Z("*").includes("*")||Z("self").includes("*"),Y=new Set;if(!Q)for(let J of Object.values($)){if(!Array.isArray(J))continue;for(let G of J)Y.add(G)}let X={};for(let J of fQ0){if(J.id==="basic-usage")continue;X[J.id]=Q||J.tools.every((G)=>Y.has(G))}return X}function BP(){let $={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],Tags:[],Experiments:[],"AI Providers":[],Secrets:[],"File Configs":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],Git:[],VM:[],Search:[],"Task Board":[],Jira:[],Blog:[]};for(let Z of Vi0)$[Z.category].push(Z);return $}var Vi0,fQ0,Lo1,Aa8,yQ0;var Hu=D(()=>{Vi0=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"BRAND_CONTEXT_LIST",description:"List brand contexts",category:"Organizations"},{name:"BRAND_CONTEXT_GET",description:"View brand context",category:"Organizations"},{name:"BRAND_CONTEXT_CREATE",description:"Create brand context",category:"Organizations"},{name:"BRAND_CONTEXT_UPDATE",description:"Update brand context",category:"Organizations"},{name:"BRAND_CONTEXT_DELETE",description:"Delete brand context",category:"Organizations",dangerous:!0},{name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context from website",category:"Organizations"},{name:"BLOG_BRAND_EXTRACT",description:"Infer editorial brand context (tone, dos and don'ts) from a site",category:"Blog"},{name:"BLOG_PILLAR_SUGGEST",description:"Propose content pillars from a brand's editorial context",category:"Blog"},{name:"BLOG_THEME_SUGGEST",description:"Propose blog post ideas from a brand's editorial context",category:"Blog"},{name:"BLOG_FORMAT_SUGGEST",description:"Name the post formats a blog writes in",category:"Blog"},{name:"BLOG_POST_DRAFT",description:"Write a blog post from a theme and a format",category:"Blog"},{name:"BLOG_LINK_SUGGEST",description:"Propose internal links from a post to the site's other posts",category:"Blog"},{name:"BRAND_GET",description:"Get brand (binding)",category:"Organizations"},{name:"BRAND_LIST",description:"List brands (binding)",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_LIST",description:"List organization domain claims",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_ADD",description:"Claim an email domain for the organization",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_UPDATE",description:"Set a domain's join mode",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_VERIFY",description:"Verify a domain via DNS TXT record",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_REMOVE",description:"Remove an organization domain claim",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_JOIN_REQUEST_LIST",description:"List pending requests to join the organization",category:"Organizations"},{name:"ORGANIZATION_JOIN_REQUEST_APPROVE",description:"Approve a request to join the organization",category:"Organizations"},{name:"ORGANIZATION_JOIN_REQUEST_DENY",description:"Deny a request to join the organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"ORGANIZATION_BILLING_CHECKOUT_START",description:"Start the org subscription checkout",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_BILLING_PORTAL",description:"Open the Stripe billing portal",category:"Organizations"},{name:"ORGANIZATION_BILLING_PLAN_PRICES",description:"Read each plan's monthly price from Stripe",category:"Organizations"},{name:"ORGANIZATION_TASK_QUOTA_GET",description:"Get the org's auto-task quota usage",category:"Organizations"},{name:"INFRA_BILLING_SITES_LIST",description:"List the legacy deco.cx sites the org owns",category:"Organizations"},{name:"INFRA_BILLING_GET",description:"Get infra usage, plan and invoices for an owned site",category:"Organizations"},{name:"INFRA_BILLING_PORTAL",description:"Open the Stripe billing portal for an owned site",category:"Organizations"},{name:"ORGANIZATION_HAS_SITE",description:"Whether this organization owns at least one legacy deco.cx site",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"REPORTS_SETUP",description:"Set up Reports",category:"Connections"},{name:"REPORTS_RUN",description:"Run Reports",category:"Connections"},{name:"REPORTS_BIND",description:"Bind Reports data source",category:"Connections"},{name:"REPORTS_CONNECTION_STATUS",description:"Read Reports connection status",category:"Connections"},{name:"REPORTS_SET_REPOSITORY",description:"Set the Reports repository",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_HEATMAP",description:"View tool-call volume by agent and tool",category:"Monitoring"},{name:"MONITORING_LOG_GET",description:"View monitoring log details",category:"Monitoring"},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"MONITORING_THREAD_USAGE",description:"View per-thread token usage and cost",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"USER_MODEL_PREFERENCES_GET",description:"Get the calling user's chat tier \u2192 model overrides",category:"Users"},{name:"USER_MODEL_PREFERENCES_UPDATE",description:"Set the calling user's chat tier \u2192 model overrides",category:"Users"},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"},{name:"TAGS_LIST",description:"List organization tags",category:"Tags"},{name:"TAGS_CREATE",description:"Create organization tag",category:"Tags"},{name:"TAGS_DELETE",description:"Delete organization tag",category:"Tags",dangerous:!0},{name:"EXPERIMENT_LIST",description:"List a site's A/B experiments",category:"Experiments"},{name:"EXPERIMENT_GET",description:"Get one A/B experiment",category:"Experiments"},{name:"EXPERIMENT_CREATE",description:"Create an A/B experiment",category:"Experiments"},{name:"EXPERIMENT_UPDATE",description:"Update an A/B experiment",category:"Experiments"},{name:"EXPERIMENT_DELETE",description:"Delete an A/B experiment",category:"Experiments",dangerous:!0},{name:"EXPERIMENT_RESULTS",description:"A/B results for one experiment",category:"Experiments"},{name:"MEMBER_TAGS_GET",description:"Get member tags",category:"Tags"},{name:"MEMBER_TAGS_SET",description:"Set member tags",category:"Tags"},{name:"AUTOMATION_CREATE",description:"Create automation",category:"Automations"},{name:"AUTOMATION_GET",description:"View automation details",category:"Automations"},{name:"AUTOMATION_LIST",description:"List automations",category:"Automations"},{name:"AUTOMATION_UPDATE",description:"Update automation",category:"Automations"},{name:"AUTOMATION_DELETE",description:"Delete automation",category:"Automations",dangerous:!0},{name:"AUTOMATION_TRIGGER_ADD",description:"Add trigger to automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_REMOVE",description:"Remove trigger from automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_ROTATE_TOKEN",description:"Rotate the secret token for a webhook automation trigger",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"AUTOMATION_RUN_STATS",description:"View aggregated run counts and token/cost for an automation",category:"Automations"},{name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update virtual MCP pinned sidebar views",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_LAST_USED_LIST",description:"Get last-used info for one or more virtual MCPs",category:"Virtual MCPs"},{name:"AI_PROVIDERS_LIST",description:"List available AI providers",category:"AI Providers"},{name:"AI_PROVIDERS_LIST_MODELS",description:"List AI provider models",category:"AI Providers"},{name:"AI_PROVIDERS_ACTIVE",description:"List active AI providers",category:"AI Providers"},{name:"AI_PROVIDER_KEY_CREATE",description:"Store AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_KEY_LIST",description:"List AI provider API keys",category:"AI Providers"},{name:"AI_PROVIDER_KEY_DELETE",description:"Delete AI provider API key",category:"AI Providers",dangerous:!0},{name:"AI_PROVIDER_KEY_UPDATE",description:"Update AI provider API key label or credential",category:"AI Providers"},{name:"AI_PROVIDER_KEY_PREVIEW",description:"Get masked preview of AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_URL",description:"Get OAuth URL for provider",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_EXCHANGE",description:"Exchange OAuth code for API key",category:"AI Providers"},{name:"AI_PROVIDER_PROVISION_KEY",description:"Auto-provision API key for a provider",category:"AI Providers"},{name:"AI_PROVIDER_TOPUP_URL",description:"Get checkout URL to top up provider credits",category:"AI Providers"},{name:"CLAUDE_SUBSCRIPTION_CONNECT",description:"Link your own Claude subscription with a setup token",category:"AI Providers"},{name:"CLAUDE_SUBSCRIPTION_STATUS",description:"Whether your Claude subscription is linked, and since when",category:"AI Providers"},{name:"CLAUDE_SUBSCRIPTION_DISCONNECT",description:"Unlink your Claude subscription",category:"AI Providers"},{name:"AI_PROVIDER_CREDITS",description:"Get current credit balance for a provider",category:"AI Providers"},{name:"AI_PLAN_ENTITLEMENTS",description:"Get the org's plan, feature flags and AI usage bar",category:"AI Providers"},{name:"AI_PLAN_LIST",description:"List the plans an organization can move to",category:"AI Providers"},{name:"AI_PLAN_SET",description:"Change the organization's plan",category:"AI Providers"},{name:"SECRET_CREATE",description:"Create a secret in the credential vault",category:"Secrets"},{name:"SECRET_LIST",description:"List secrets visible to the caller (no values returned)",category:"Secrets"},{name:"FILE_CONFIG_CREATE",description:"Create an S3-compatible bucket configuration for the org",category:"File Configs"},{name:"FILE_CONFIG_LIST",description:"List S3 bucket configurations for the org (no creds returned)",category:"File Configs"},{name:"ORG_FS_PUBLIC_SETS_SYNC",description:"Re-sync the shared public skill-set volumes from their GitHub sources",category:"File Configs"},{name:"ORG_REPO_SYNC_CREATE",description:"Keep a GitHub repository mirrored into a new org-fs volume",category:"File Configs"},{name:"ORG_REPO_SYNC_LIST",description:"List the org's synced repositories and their sync status",category:"File Configs"},{name:"ORG_REPO_SYNC_UPDATE",description:"Update a synced repository's ref, paths, or enabled flag",category:"File Configs"},{name:"ORG_REPO_SYNC_DELETE",description:"Stop syncing a repository (already-synced files are kept)",category:"File Configs"},{name:"ORG_REPO_SYNC_RUN",description:"Sync a repository into its volume right now",category:"File Configs"},{name:"JIRA_INTEGRATION_GET",description:"Get the org's Jira integration config",category:"Jira"},{name:"JIRA_INTEGRATION_UPSERT",description:"Connect or update the org's Jira integration",category:"Jira"},{name:"JIRA_INTEGRATION_DELETE",description:"Disconnect Jira (already-synced cards are kept)",category:"Jira"},{name:"JIRA_BOARDS_LIST",description:"List Jira boards visible to the connected credentials",category:"Jira"},{name:"JIRA_BOARD_COLUMNS_LIST",description:"List a Jira board's columns and statuses for the mapping",category:"Jira"},{name:"JIRA_AUTOMATION_LIST",description:"List which Jira statuses start an agent run",category:"Jira"},{name:"JIRA_AUTOMATION_UPSERT",description:"Run the agent on issues entering a Jira status",category:"Jira"},{name:"JIRA_AUTOMATION_DELETE",description:"Stop running the agent on issues entering a Jira status",category:"Jira"},{name:"JIRA_RUN_START",description:"Run the agent on Jira issues now, to try a rule out",category:"Jira"},{name:"JIRA_ISSUE_GET",description:"Read a Jira issue on the board from a run",category:"Jira"},{name:"JIRA_COMMENT_ADD",description:"Comment on a Jira issue on the board from a run",category:"Jira"},{name:"JIRA_ISSUE_TRANSITION",description:"Move a Jira issue on the board to another status",category:"Jira"},{name:"JIRA_ATTACHMENT_DOWNLOAD",description:"Get a short-lived download URL for an attachment of a Jira issue",category:"Jira"},{name:"JIRA_REMOTE_LINK_ADD",description:"Link a pull request or deploy preview on a Jira issue",category:"Jira"},{name:"JIRA_ISSUE_CREATE",description:"Create a Jira issue on the board from a run",category:"Jira"},{name:"JIRA_ISSUE_SEARCH",description:"Search the Jira board's issues with JQL from a run",category:"Jira"},{name:"FILE_CONFIG_UPDATE",description:"Update an S3 bucket configuration, optionally rotating credentials",category:"File Configs"},{name:"FILE_CONFIG_DELETE",description:"Delete an S3 bucket configuration",category:"File Configs"},{name:"FILE_OBJECTS_LIST",description:"List existing objects in a configured bucket",category:"File Configs"},{name:"FILE_OBJECT_DELETE",description:"Delete an object from a configured bucket",category:"File Configs"},{name:"LIST_OBJECTS",description:"List objects in storage",category:"Object Storage"},{name:"GET_OBJECT_METADATA",description:"Get object metadata",category:"Object Storage"},{name:"GET_PRESIGNED_URL",description:"Generate download URL",category:"Object Storage"},{name:"PUT_PRESIGNED_URL",description:"Generate upload URL",category:"Object Storage"},{name:"DELETE_OBJECT",description:"Delete object",category:"Object Storage",dangerous:!0},{name:"DELETE_OBJECTS",description:"Delete multiple objects",category:"Object Storage",dangerous:!0},{name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry apps",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_GET",description:"Get registry app details",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"List registry app versions",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get registry app filters",category:"Registry"},{name:"REGISTRY_ITEM_LIST",description:"List Deco registry items",category:"Registry"},{name:"REGISTRY_ITEM_SEARCH",description:"Search registry items",category:"Registry"},{name:"REGISTRY_ITEM_GET",description:"Get registry item details",category:"Registry"},{name:"REGISTRY_ITEM_VERSIONS",description:"List registry item versions",category:"Registry"},{name:"REGISTRY_ITEM_FILTERS",description:"Get registry item filters",category:"Registry"},{name:"SANDBOX_START",description:"Start a sandbox VM with dev server preview",category:"VM"},{name:"SANDBOX_DELETE",description:"Stop and delete a sandbox VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"},{name:"GIT_PROVIDER_CAPABILITIES",description:"Which git providers this deployment can connect, with their connect URLs",category:"Git"},{name:"GIT_ACCOUNT_LIST",description:"List the git provider accounts connected to the organization",category:"Git"},{name:"GIT_ACCOUNT_CONNECT_TOKEN",description:"Connect a git provider account with an access token",category:"Git"},{name:"GIT_ACCOUNT_DELETE",description:"Disconnect a git provider account",category:"Git"},{name:"REPOSITORY_LIST",description:"List the repositories linked to the organization",category:"Git"},{name:"REPOSITORY_SEARCH",description:"Search the repositories an account can reach on its provider",category:"Git"},{name:"REPOSITORY_LINK",description:"Link a repository to the organization",category:"Git"},{name:"REPOSITORY_SEARCH_BRANCHES",description:"Search a repository's branches by name substring, on either provider",category:"Git"},{name:"CHANGE_REQUEST_STATE",description:"Read a branch's change request with its CI runs, review state and comments",category:"Git"},{name:"CHANGE_REQUEST_LAST_MERGED",description:"Read the most recently merged change request into a base branch",category:"Git"},{name:"CHANGE_REQUEST_LIST_OPEN",description:"List a repository's open change requests",category:"Git"},{name:"CHANGE_REQUEST_CHECK_LOG",description:"Read one CI run's report for a change request",category:"Git"},{name:"CHANGE_REQUEST_OPEN",description:"Propose a branch onto another, reusing the branch's existing change request",category:"Git"},{name:"CHANGE_REQUEST_MERGE",description:"Land a change request, reporting why it could not merge",category:"Git"},{name:"REPOSITORY_UPDATE",description:"Change a linked repository's settings, such as its sandbox image",category:"Git"},{name:"REPOSITORY_DELETE",description:"Unlink a repository from the organization",category:"Git"},{name:"GLOBAL_SEARCH",description:"Search across organization resources (currently threads). Returns a typed union of matches.",category:"Search"},{name:"TASK_BOARD_ITEM_CREATE",description:"Create task board item",category:"Task Board"},{name:"TASK_BOARD_ITEM_LIST",description:"List task board items",category:"Task Board"},{name:"TASK_BOARD_ITEM_UPDATE",description:"Update task board item",category:"Task Board"},{name:"TASK_BOARD_ITEM_DELETE",description:"Delete task board item",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_AUTOMATION_LIST",description:"List what the board runs when a card lands in each column",category:"Task Board"},{name:"TASK_BOARD_AUTOMATION_UPSERT",description:"Run the agent on cards landing in a board column",category:"Task Board"},{name:"TASK_BOARD_AUTOMATION_DELETE",description:"Stop running the agent on cards landing in a board column",category:"Task Board"},{name:"TASK_BOARD_PROMPT_LIST",description:"List the instructions appended to the system prompt of the board's runs",category:"Task Board"},{name:"TASK_BOARD_PROMPT_UPSERT",description:"Set the instructions appended to the system prompt of the board's runs",category:"Task Board"},{name:"TASK_BOARD_PROMPT_DELETE",description:"Clear a board system prompt",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_ITEM_PRS_GET",description:"Get a task board item's linked pull requests with live state",category:"Task Board"},{name:"TASK_BOARD_PREVIEW_PROBE",description:"Check whether a pull request's deploy preview URL is currently reachable",category:"Task Board"},{name:"TASK_BOARD_ITEM_RERUN",description:"Re-run a task with the Super Agent, failing any run still holding it open",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_RUN_REVIEWER",description:"Run the Reviewer on a task even when the organization has automated review turned off",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_RESOLVE_CONFLICT",description:"Hand a task's conflicting pull request back to the Super Agent to resolve the merge conflict",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_REVIEW_DECISION",description:"Record a reviewer's decision (approve or request changes) for a task under review",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_PROMOTE_TO_PRODUCTION",description:"Merge a reviewed task's pull request and move the task to Done",category:"Task Board",dangerous:!0},{name:"NOTIFICATION_LIST",description:"List your unread notifications in this organization",category:"Task Board"},{name:"NOTIFICATION_MARK_READ",description:"Mark your notifications read",category:"Task Board"},{name:"NOTIFICATION_SUBSCRIPTION_SET",description:"Follow or unfollow a task board item",category:"Task Board"},{name:"NOTIFICATION_SUBSCRIPTION_LIST",description:"List the users following a task board item",category:"Task Board"},{name:"TASK_BOARD_ACTIVITY_LIST",description:"List a task board item's change history",category:"Task Board"},{name:"TASK_BOARD_COMMENT_LIST",description:"List a task board item's comment threads",category:"Task Board"},{name:"TASK_BOARD_COMMENT_CREATE",description:"Post a comment or a reply on a task board item",category:"Task Board"},{name:"TASK_BOARD_COMMENT_UPDATE",description:"Edit a comment, or resolve/unresolve a comment thread",category:"Task Board"},{name:"TASK_BOARD_COMMENT_DELETE",description:"Delete a comment (a thread root takes its replies)",category:"Task Board"},{name:"TASK_BOARD_DISMISSED_LIST",description:"List diagnostic findings dismissed by deleting their task board cards",category:"Task Board"},{name:"TASK_BOARD_DISMISSED_RESTORE",description:"Un-dismiss diagnostic findings so the next report import pushes them again",category:"Task Board"},{name:"TASK_BOARD_ADMIN_ORG_LIST",description:"Whether the caller may read every org's task board, and the orgs that have board items",category:"Task Board"},{name:"TASK_BOARD_DELIVERY",description:"Task board throughput and flow \u2014 completions, PR rate, lead vs cycle time, dwell by lane",category:"Task Board"},{name:"TASK_BOARD_STUCK",description:"Task board work that is stuck right now, and WIP by age",category:"Task Board"},{name:"TASK_BOARD_COST",description:"Task board spend \u2014 total, per task, per shipped PR, and the coverage % behind those figures",category:"Task Board"},{name:"TASK_BOARD_QUALITY",description:"Task board quality \u2014 first-pass yield, rework, autonomy, abandonment, retry burn",category:"Task Board"},{name:"TASK_BOARD_ERRORS",description:"Task board run failures \u2014 counts, kinds, live error feed, error signatures, superseded runs",category:"Task Board"},{name:"TASK_BOARD_TENANTS",description:"Per-tenant task board scorecard and queue wait",category:"Task Board"},{name:"THREAD_ANALYTICS_ORG_LIST",description:"Whether the caller may read every org's threads, and the orgs that have any",category:"Threads"},{name:"THREAD_ANALYTICS_LIVE",description:"Recently active threads across orgs with status, owner and spend (admin orgs)",category:"Threads"},{name:"THREAD_ANALYTICS_USAGE",description:"Token and USD usage by org, user, agent and kind; top spenders (admin orgs)",category:"Threads"},{name:"THREAD_ANALYTICS_ERRORS",description:"Failed threads, error feed and error signatures across orgs (admin orgs)",category:"Threads"},{name:"TASK_ADD_REPO",description:"Clone an organization repository into the sandbox of the task run calling it",category:"Task Board"}],fQ0=[{id:"basic-usage",label:"Basic Usage",description:"Tools all org members can access by default",section:"Basic Usage",tools:["COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","CONNECTION_TEST","COLLECTION_VIRTUAL_MCP_LIST","COLLECTION_VIRTUAL_MCP_GET","VIRTUAL_MCP_LAST_USED_LIST","AUTOMATION_GET","AUTOMATION_LIST","AUTOMATION_RUN_STATS","AI_PROVIDERS_LIST","AI_PROVIDERS_LIST_MODELS","AI_PROVIDERS_ACTIVE","AI_PROVIDER_KEY_LIST","AI_PROVIDER_CREDITS","AI_PLAN_ENTITLEMENTS","AI_PLAN_LIST","ORGANIZATION_BILLING_PLAN_PRICES","AI_PROVIDER_TOPUP_URL","LIST_OBJECTS","GET_OBJECT_METADATA","GET_PRESIGNED_URL","PUT_PRESIGNED_URL","FILE_OBJECTS_LIST","ORG_REPO_SYNC_LIST","SANDBOX_START","SANDBOX_DELETE","REPOSITORY_SEARCH_BRANCHES","GIT_PROVIDER_CAPABILITIES","GIT_ACCOUNT_LIST","REPOSITORY_LIST","REPOSITORY_SEARCH","CHANGE_REQUEST_STATE","CHANGE_REQUEST_LAST_MERGED","CHANGE_REQUEST_LIST_OPEN","CHANGE_REQUEST_CHECK_LOG","GLOBAL_SEARCH","ORGANIZATION_SETTINGS_GET","USER_GET","BRAND_CONTEXT_LIST","ORGANIZATION_HAS_SITE","COLLECTION_THREADS_CREATE","COLLECTION_THREADS_LIST","COLLECTION_THREADS_GET","COLLECTION_THREADS_UPDATE","COLLECTION_THREADS_DELETE","COLLECTION_THREAD_MESSAGES_LIST","TASK_BOARD_ITEM_CREATE","TASK_BOARD_ITEM_LIST","TASK_BOARD_ITEM_UPDATE","TASK_BOARD_ITEM_DELETE","TASK_BOARD_AUTOMATION_LIST","TASK_BOARD_AUTOMATION_UPSERT","TASK_BOARD_AUTOMATION_DELETE","TASK_BOARD_PROMPT_LIST","TASK_BOARD_PROMPT_UPSERT","TASK_BOARD_PROMPT_DELETE","TASK_BOARD_ITEM_PRS_GET","TASK_BOARD_PREVIEW_PROBE","TASK_BOARD_ITEM_RERUN","TASK_BOARD_RUN_REVIEWER","TASK_BOARD_REVIEW_DECISION","TASK_BOARD_PROMOTE_TO_PRODUCTION","TASK_BOARD_ACTIVITY_LIST","TASK_BOARD_COMMENT_LIST","TASK_BOARD_COMMENT_CREATE","TASK_BOARD_COMMENT_UPDATE","TASK_BOARD_COMMENT_DELETE","TASK_BOARD_DISMISSED_LIST","TASK_BOARD_DISMISSED_RESTORE","TASK_BOARD_ADMIN_ORG_LIST","TASK_BOARD_DELIVERY","TASK_BOARD_STUCK","TASK_BOARD_COST","TASK_BOARD_QUALITY","TASK_BOARD_ERRORS","TASK_BOARD_TENANTS","THREAD_ANALYTICS_ORG_LIST","THREAD_ANALYTICS_LIVE","THREAD_ANALYTICS_USAGE","THREAD_ANALYTICS_ERRORS","NOTIFICATION_LIST","NOTIFICATION_MARK_READ","NOTIFICATION_SUBSCRIPTION_SET","NOTIFICATION_SUBSCRIPTION_LIST"]},{id:"org:manage",label:"Manage organization",description:"Edit organization settings, brand context, and domain configuration",section:"Organization",tools:["ORGANIZATION_GET","ORGANIZATION_LIST","ORGANIZATION_UPDATE","ORGANIZATION_SETTINGS_GET","ORGANIZATION_SETTINGS_UPDATE","BRAND_CONTEXT_LIST","BRAND_CONTEXT_GET","BRAND_CONTEXT_CREATE","BRAND_CONTEXT_UPDATE","BRAND_CONTEXT_DELETE","BRAND_CONTEXT_EXTRACT","BRAND_GET","BRAND_LIST","ORGANIZATION_DOMAIN_LIST","ORGANIZATION_DOMAIN_ADD","ORGANIZATION_DOMAIN_UPDATE","ORGANIZATION_DOMAIN_VERIFY","ORGANIZATION_DOMAIN_REMOVE","JIRA_INTEGRATION_GET","JIRA_INTEGRATION_UPSERT","JIRA_INTEGRATION_DELETE","JIRA_BOARDS_LIST","JIRA_BOARD_COLUMNS_LIST","JIRA_AUTOMATION_LIST","JIRA_AUTOMATION_UPSERT","JIRA_AUTOMATION_DELETE","JIRA_RUN_START"]},{id:"members:manage",label:"Manage members",description:"Invite members, remove them, and change their roles",section:"Organization",tools:["ORGANIZATION_MEMBER_LIST","ORGANIZATION_MEMBER_ADD","ORGANIZATION_MEMBER_REMOVE","ORGANIZATION_MEMBER_UPDATE_ROLE","ORGANIZATION_BILLING_CHECKOUT_START","ORGANIZATION_BILLING_PORTAL","ORGANIZATION_TASK_QUOTA_GET","INFRA_BILLING_SITES_LIST","INFRA_BILLING_GET","INFRA_BILLING_PORTAL","ORGANIZATION_JOIN_REQUEST_LIST","ORGANIZATION_JOIN_REQUEST_APPROVE","ORGANIZATION_JOIN_REQUEST_DENY"],dangerous:!0},{id:"connections:manage",label:"Manage connections",description:"Create, update, and delete connections",section:"Connections & Agents",tools:["COLLECTION_CONNECTIONS_CREATE","COLLECTION_CONNECTIONS_UPDATE","COLLECTION_CONNECTIONS_DELETE","REPORTS_SETUP","REPORTS_RUN","REPORTS_BIND","REPORTS_CONNECTION_STATUS","REPORTS_SET_REPOSITORY"],dangerous:!0},{id:"agents:manage",label:"Manage agents",description:"Create, configure, and delete agents",section:"Connections & Agents",tools:["COLLECTION_VIRTUAL_MCP_CREATE","COLLECTION_VIRTUAL_MCP_UPDATE","COLLECTION_VIRTUAL_MCP_DELETE","VIRTUAL_MCP_PINNED_VIEWS_UPDATE"],dangerous:!0},{id:"automations:manage",label:"Manage automations",description:"Create, update, run, and delete automations",section:"Automations",tools:["AUTOMATION_CREATE","AUTOMATION_UPDATE","AUTOMATION_DELETE","AUTOMATION_TRIGGER_ADD","AUTOMATION_TRIGGER_REMOVE","AUTOMATION_TRIGGER_ROTATE_TOKEN","AUTOMATION_RUN"],dangerous:!0},{id:"monitoring:view",label:"View monitoring",description:"Access logs and usage statistics",section:"Monitoring",tools:["MONITORING_HEATMAP","MONITORING_LOG_GET","MONITORING_LOGS_LIST","MONITORING_STATS","MONITORING_THREAD_USAGE"]},{id:"secrets:manage",label:"Manage secrets",description:"Create and list secrets stored in the credential vault",section:"Organization",tools:["SECRET_CREATE","SECRET_LIST"]},{id:"file-configs:manage",label:"Manage file configs",description:"Create, list, update and delete S3 bucket configurations and synced GitHub repositories",section:"Organization",tools:["FILE_CONFIG_CREATE","FILE_CONFIG_LIST","FILE_CONFIG_UPDATE","FILE_CONFIG_DELETE","FILE_OBJECTS_LIST","FILE_OBJECT_DELETE","ORG_REPO_SYNC_CREATE","ORG_REPO_SYNC_LIST","ORG_REPO_SYNC_UPDATE","ORG_REPO_SYNC_DELETE","ORG_REPO_SYNC_RUN"]},{id:"ai-providers:manage",label:"Manage AI providers",description:"Add or remove API keys and provision provider credentials",section:"AI Providers",tools:["AI_PROVIDER_KEY_CREATE","AI_PROVIDER_KEY_LIST","AI_PROVIDER_KEY_DELETE","AI_PROVIDER_KEY_UPDATE","AI_PROVIDER_KEY_PREVIEW","AI_PROVIDER_OAUTH_URL","AI_PROVIDER_OAUTH_EXCHANGE","AI_PROVIDER_PROVISION_KEY","AI_PROVIDER_TOPUP_URL","AI_PROVIDER_CREDITS","AI_PLAN_ENTITLEMENTS","AI_PLAN_LIST","AI_PLAN_SET","CLAUDE_SUBSCRIPTION_CONNECT","CLAUDE_SUBSCRIPTION_STATUS","CLAUDE_SUBSCRIPTION_DISCONNECT"]},{id:"tags:manage",label:"Manage tags",description:"Create, assign, and delete organization tags",section:"Organization",tools:["TAGS_LIST","TAGS_CREATE","TAGS_DELETE","MEMBER_TAGS_GET","MEMBER_TAGS_SET"]},{id:"experiments:manage",label:"Manage experiments",description:"Create, update, and delete A/B experiments, and view results",section:"Experiments",tools:["EXPERIMENT_LIST","EXPERIMENT_GET","EXPERIMENT_CREATE","EXPERIMENT_UPDATE","EXPERIMENT_DELETE","EXPERIMENT_RESULTS"],dangerous:!0},{id:"registry:manage",label:"Browse registry",description:"Browse the Deco MCP catalog",section:"Store & Registry",tools:["COLLECTION_REGISTRY_APP_LIST","COLLECTION_REGISTRY_APP_GET","COLLECTION_REGISTRY_APP_VERSIONS","COLLECTION_REGISTRY_APP_FILTERS","REGISTRY_ITEM_LIST","REGISTRY_ITEM_SEARCH","REGISTRY_ITEM_GET","REGISTRY_ITEM_VERSIONS","REGISTRY_ITEM_FILTERS"]},{id:"api-keys:manage",label:"Manage API keys",description:"Create, update, and revoke API keys",section:"Developer",tools:["API_KEY_CREATE","API_KEY_LIST","API_KEY_UPDATE","API_KEY_DELETE"]},{id:"storage:delete",label:"Delete from storage",description:"Permanently delete files from object storage",section:"Developer",tools:["DELETE_OBJECT","DELETE_OBJECTS"],dangerous:!0},{id:"connections:sql",label:"Run SQL queries",description:"Execute raw SQL against connected databases",section:"Developer",tools:["DATABASES_RUN_SQL"],dangerous:!0}],Lo1=new Set([...fQ0.find(($)=>$.id==="basic-usage")?.tools??[],"ORG_FS_READ","ORG_FS_WRITE"]),Aa8=["agents:manage","connections:manage"],yQ0=new Set(fQ0.filter(($)=>Aa8.includes($.id)).flatMap(($)=>$.tools))});function EZ($){if(!$)return!1;return $.split(",").some((Q)=>wo.includes(Q))}function gQ0($,Z){let Q=Array.isArray(Z)?Z:[Z];if(Q.length===0)return!1;let Y=$?$.split(","):[];if(Y.includes("owner"))return!0;if(Y.includes("admin"))return Q.every((X)=>X!=="owner");return!1}var Fu,wo;var GY=D(()=>{Fu=["owner","admin","user"],wo=["owner","admin"]});class OP{userId;toolName;boundAuth;role;connectionId;getToolMeta;organizationId;trustPublicPrefix;_granted=!1;constructor($,Z,Q,Y,X="self",J,G,W=!0){this.userId=$;this.toolName=Z;this.boundAuth=Q;this.role=Y;this.connectionId=X;this.getToolMeta=J;this.organizationId=G;this.trustPublicPrefix=W}setToolName($){this.toolName=$}setOrganizationId($){this.organizationId=$}getOrganizationId(){return this.organizationId}setRole($){this.role=$}getRole(){return this.role}grant(){this._granted=!0}async check(...$){if(this._granted)return;if(this.trustPublicPrefix&&(this.toolName?.startsWith("STUDIO_PUBLIC_")||this.toolName?.startsWith("MESH_PUBLIC_"))){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new LL("Authentication required. Please provide a valid OAuth token or API key.")}let Z=$.length>0?$:this.toolName?[this.toolName]:[];if(Z.length===0)throw new y7("No resources specified for access check");for(let Q of Z)if(await this.checkResource(Q)){this.grant();return}throw new y7(`Access denied to: ${Z.join(", ")}`)}async checkResource($){if(!this.userId&&!this.boundAuth)return!1;return this.boundAuth?.isApiKeyPrincipal?this.checkApiKeyAccess($):this.checkMemberAccess($)}async checkApiKeyAccess($){if(!this.boundAuth)return!1;return this.boundAuth.hasPermission({[this.connectionId]:[$]})}async checkMemberAccess($){if(this.userId&&this.role&&Lo1.has($))return!0;if(EZ(this.role))return!0;if(!this.boundAuth)return!1;return this.boundAuth.hasPermission({[this.connectionId]:[$]},{organizationId:this.organizationId,role:this.role})}async isToolPublic(){if(this.trustPublicPrefix&&(this.toolName?.startsWith("STUDIO_PUBLIC_")||this.toolName?.startsWith("MESH_PUBLIC_")))return!0;if(!this.getToolMeta)return!1;try{let $=await this.getToolMeta();if(!$)return!1;let Q=YF($)?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}var LL,y7;var BK=D(()=>{Hu();GY();LL=class LL extends Error{constructor($){super($);this.name="UnauthorizedError"}};y7=class y7 extends Error{constructor($){super($);this.name="ForbiddenError"}}});function jo1($){let Z={};for(let Q of Object.keys($))Z[Q]=["*"];return Z}function P9($){let Z=$?.metadata;if(!Z)return!1;try{return(typeof Z==="string"?JSON.parse(Z):Z).archived===!0}catch{return!1}}var hQ0="Organization is archived";function cQ0($,Z){return $.get(uQ0[Z])??$.get(lQ0[Z])}function Si0($,Z,Q){$[uQ0[Z]]=Q,$[lQ0[Z]]=Q}var uQ0,lQ0;var Ci0=D(()=>{uQ0={token:"x-studio-token",client:"x-studio-client",properties:"x-studio-properties",runMetadata:"x-studio-run-metadata"},lQ0={token:"x-mesh-token",client:"x-mesh-client",properties:"x-mesh-properties",runMetadata:"x-mesh-run-metadata"}});import*as Eo1 from"zod/v3";import*as DP from"zod/v4-mini";function nX($){return!!$._zod}function LP($){let Z=Object.values($);if(Z.length===0)return DP.object({});let Q=Z.every(nX),Y=Z.every((X)=>!nX(X));if(Q)return DP.object($);if(Y)return Eo1.object($);throw Error("Mixed Zod versions detected in object shape.")}function YX($,Z){if(nX($))return DP.safeParse($,Z);return $.safeParse(Z)}async function mQ0($,Z){if(nX($))return await DP.safeParseAsync($,Z);return await $.safeParseAsync(Z)}function XF($){if(!$)return;let Z;if(nX($))Z=$._zod?.def?.shape;else Z=$.shape;if(!Z)return;if(typeof Z==="function")try{return Z()}catch{return}return Z}function Uu($){if(!$)return;if(typeof $==="object"){let Z=$,Q=$;if(!Z._def&&!Q._zod){let Y=Object.values($);if(Y.length>0&&Y.every((X)=>typeof X==="object"&&X!==null&&(X._def!==void 0||X._zod!==void 0||typeof X.parse==="function")))return LP($)}}if(nX($)){let Q=$._zod?.def;if(Q&&(Q.type==="object"||Q.shape!==void 0))return $}else if($.shape!==void 0)return $;return}function dQ0($){if($&&typeof $==="object"){if("message"in $&&typeof $.message==="string")return $.message;if("issues"in $&&Array.isArray($.issues)&&$.issues.length>0){let Z=$.issues[0];if(Z&&typeof Z==="object"&&"message"in Z)return String(Z.message)}try{return JSON.stringify($)}catch{return String($)}}return String($)}function zo1($){return $.description}function Po1($){if(nX($))return $._zod?.def?.type==="optional";let Z=$;if(typeof $.isOptional==="function")return $.isOptional();return Z._def?.typeName==="ZodOptional"}function iQ0($){if(nX($)){let J=$._zod?.def;if(J){if(J.value!==void 0)return J.value;if(Array.isArray(J.values)&&J.values.length>0)return J.values[0]}}let Q=$._def;if(Q){if(Q.value!==void 0)return Q.value;if(Array.isArray(Q.values)&&Q.values.length>0)return Q.values[0]}let Y=$.value;if(Y!==void 0)return Y;return}var Nu=()=>{};function wL($){return $==="completed"||$==="failed"||$==="cancelled"}var To1,Ao1,Ro1=($)=>typeof $==="string"?{...Ao1,name:$}:{...Ao1,...$};var pQ0=D(()=>{To1=Symbol("Let zodToJsonSchema decide on which parser to use"),Ao1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"}});var qo1=($)=>{let Z=Ro1($),Q=Z.name!==void 0?[...Z.basePath,Z.definitionPath,Z.name]:Z.basePath;return{...Z,flags:{hasReferencedOpenAiAnyType:!1},currentPath:Q,propertyPath:void 0,seen:new Map(Object.entries(Z.definitions).map(([Y,X])=>[X._def,{def:X._def,path:[...Z.basePath,Z.definitionPath,Y],jsonSchema:void 0}]))}};var _i0=D(()=>{pQ0()});function vi0($,Z,Q,Y){if(!Y?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[Z]:Q}}function $6($,Z,Q,Y,X){$[Z]=Q,vi0($,Z,Y,X)}var nQ0=($,Z)=>{let Q=0;for(;Q<$.length&&Q<Z.length;Q++)if($[Q]!==Z[Q])break;return[($.length-Q).toString(),...Z.slice(Q)].join("/")};function A9($){if($.target!=="openAi")return{};let Z=[...$.basePath,$.definitionPath,$.openAiAnyTypeName];return $.flags.hasReferencedOpenAiAnyType=!0,{$ref:$.$refStrategy==="relative"?nQ0(Z,$.currentPath):Z.join("/")}}var g3=()=>{};import{ZodFirstPartyTypeKind as Ta8}from"zod/v3";function Mo1($,Z){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==Ta8.ZodAny)Q.items=L8($.type._def,{...Z,currentPath:[...Z.currentPath,"items"]});if($.minLength)$6(Q,"minItems",$.minLength.value,$.minLength.message,Z);if($.maxLength)$6(Q,"maxItems",$.maxLength.value,$.maxLength.message,Z);if($.exactLength)$6(Q,"minItems",$.exactLength.value,$.exactLength.message,Z),$6(Q,"maxItems",$.exactLength.value,$.exactLength.message,Z);return Q}var bi0=D(()=>{lZ()});function Io1($,Z){let Q={type:"integer",format:"int64"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"min":if(Z.target==="jsonSchema7")if(Y.inclusive)$6(Q,"minimum",Y.value,Y.message,Z);else $6(Q,"exclusiveMinimum",Y.value,Y.message,Z);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;$6(Q,"minimum",Y.value,Y.message,Z)}break;case"max":if(Z.target==="jsonSchema7")if(Y.inclusive)$6(Q,"maximum",Y.value,Y.message,Z);else $6(Q,"exclusiveMaximum",Y.value,Y.message,Z);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;$6(Q,"maximum",Y.value,Y.message,Z)}break;case"multipleOf":$6(Q,"multipleOf",Y.value,Y.message,Z);break}return Q}var xi0=()=>{};function Vo1(){return{type:"boolean"}}function tQ0($,Z){return L8($.type._def,Z)}var oQ0=D(()=>{lZ()});var ko1=($,Z)=>{return L8($.innerType._def,Z)};var fi0=D(()=>{lZ()});function yi0($,Z,Q){let Y=Q??Z.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((X,J)=>yi0($,Z,X))};switch(Y){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ra8($,Z)}}var Ra8=($,Z)=>{let Q={type:"integer",format:"unix-time"};if(Z.target==="openApi3")return Q;for(let Y of $.checks)switch(Y.kind){case"min":$6(Q,"minimum",Y.value,Y.message,Z);break;case"max":$6(Q,"maximum",Y.value,Y.message,Z);break}return Q};var gi0=()=>{};function So1($,Z){return{...L8($.innerType._def,Z),default:$.defaultValue()}}var hi0=D(()=>{lZ()});function Co1($,Z){return Z.effectStrategy==="input"?L8($.schema._def,Z):A9(Z)}var ui0=D(()=>{lZ();g3()});function _o1($){return{type:"string",enum:Array.from($.values)}}function vo1($,Z){let Q=[L8($.left._def,{...Z,currentPath:[...Z.currentPath,"allOf","0"]}),L8($.right._def,{...Z,currentPath:[...Z.currentPath,"allOf","1"]})].filter((J)=>!!J),Y=Z.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,X=[];return Q.forEach((J)=>{if(qa8(J)){if(X.push(...J.allOf),J.unevaluatedProperties===void 0)Y=void 0}else{let G=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...K}=J;G=K}else Y=void 0;X.push(G)}}),X.length?{allOf:X,...Y}:void 0}var qa8=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};var li0=D(()=>{lZ()});function bo1($,Z){let Q=typeof $.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray($.value)?"array":"object"};if(Z.target==="openApi3")return{type:Q==="bigint"?"integer":Q,enum:[$.value]};return{type:Q==="bigint"?"integer":Q,const:$.value}}function rQ0($,Z){let Q={type:"string"};if($.checks)for(let Y of $.checks)switch(Y.kind){case"min":$6(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,Y.value):Y.value,Y.message,Z);break;case"max":$6(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,Y.value):Y.value,Y.message,Z);break;case"email":switch(Z.emailStrategy){case"format:email":DK(Q,"email",Y.message,Z);break;case"format:idn-email":DK(Q,"idn-email",Y.message,Z);break;case"pattern:zod":XX(Q,OK.email,Y.message,Z);break}break;case"url":DK(Q,"uri",Y.message,Z);break;case"uuid":DK(Q,"uuid",Y.message,Z);break;case"regex":XX(Q,Y.regex,Y.message,Z);break;case"cuid":XX(Q,OK.cuid,Y.message,Z);break;case"cuid2":XX(Q,OK.cuid2,Y.message,Z);break;case"startsWith":XX(Q,RegExp(`^${mi0(Y.value,Z)}`),Y.message,Z);break;case"endsWith":XX(Q,RegExp(`${mi0(Y.value,Z)}$`),Y.message,Z);break;case"datetime":DK(Q,"date-time",Y.message,Z);break;case"date":DK(Q,"date",Y.message,Z);break;case"time":DK(Q,"time",Y.message,Z);break;case"duration":DK(Q,"duration",Y.message,Z);break;case"length":$6(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,Y.value):Y.value,Y.message,Z),$6(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,Y.value):Y.value,Y.message,Z);break;case"includes":{XX(Q,RegExp(mi0(Y.value,Z)),Y.message,Z);break}case"ip":{if(Y.version!=="v6")DK(Q,"ipv4",Y.message,Z);if(Y.version!=="v4")DK(Q,"ipv6",Y.message,Z);break}case"base64url":XX(Q,OK.base64url,Y.message,Z);break;case"jwt":XX(Q,OK.jwt,Y.message,Z);break;case"cidr":{if(Y.version!=="v6")XX(Q,OK.ipv4Cidr,Y.message,Z);if(Y.version!=="v4")XX(Q,OK.ipv6Cidr,Y.message,Z);break}case"emoji":XX(Q,OK.emoji(),Y.message,Z);break;case"ulid":{XX(Q,OK.ulid,Y.message,Z);break}case"base64":{switch(Z.base64Strategy){case"format:binary":{DK(Q,"binary",Y.message,Z);break}case"contentEncoding:base64":{$6(Q,"contentEncoding","base64",Y.message,Z);break}case"pattern:zod":{XX(Q,OK.base64,Y.message,Z);break}}break}case"nanoid":XX(Q,OK.nanoid,Y.message,Z);case"toLowerCase":case"toUpperCase":case"trim":break;default:((X)=>{})(Y)}return Q}function mi0($,Z){return Z.patternStrategy==="escape"?Ia8($):$}function Ia8($){let Z="";for(let Q=0;Q<$.length;Q++){if(!Ma8.has($[Q]))Z+="\\";Z+=$[Q]}return Z}function DK($,Z,Q,Y){if($.format||$.anyOf?.some((X)=>X.format)){if(!$.anyOf)$.anyOf=[];if($.format){if($.anyOf.push({format:$.format,...$.errorMessage&&Y.errorMessages&&{errorMessage:{format:$.errorMessage.format}}}),delete $.format,$.errorMessage){if(delete $.errorMessage.format,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.anyOf.push({format:Z,...Q&&Y.errorMessages&&{errorMessage:{format:Q}}})}else $6($,"format",Z,Q,Y)}function XX($,Z,Q,Y){if($.pattern||$.allOf?.some((X)=>X.pattern)){if(!$.allOf)$.allOf=[];if($.pattern){if($.allOf.push({pattern:$.pattern,...$.errorMessage&&Y.errorMessages&&{errorMessage:{pattern:$.errorMessage.pattern}}}),delete $.pattern,$.errorMessage){if(delete $.errorMessage.pattern,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.allOf.push({pattern:xo1(Z,Y),...Q&&Y.errorMessages&&{errorMessage:{pattern:Q}}})}else $6($,"pattern",xo1(Z,Y),Q,Y)}function xo1($,Z){if(!Z.applyRegexFlags||!$.flags)return $.source;let Q={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},Y=Q.i?$.source.toLowerCase():$.source,X="",J=!1,G=!1,W=!1;for(let K=0;K<Y.length;K++){if(J){X+=Y[K],J=!1;continue}if(Q.i){if(G){if(Y[K].match(/[a-z]/)){if(W)X+=Y[K],X+=`${Y[K-2]}-${Y[K]}`.toUpperCase(),W=!1;else if(Y[K+1]==="-"&&Y[K+2]?.match(/[a-z]/))X+=Y[K],W=!0;else X+=`${Y[K]}${Y[K].toUpperCase()}`;continue}}else if(Y[K].match(/[a-z]/)){X+=`[${Y[K]}${Y[K].toUpperCase()}]`;continue}}if(Q.m){if(Y[K]==="^"){X+=`(^|(?<=[\r
|
|
446
|
+
)`}function Na8($){if(!$?.startDate&&!$?.endDate)return null;let Z="make_date(CAST(year AS INT), CAST(month AS INT), CAST(day AS INT))",Q=(X,J)=>new Date(X.getTime()+J*86400000).toISOString().slice(0,10),Y=[];if($.startDate)Y.push(`${Z} >= DATE '${Q($.startDate,-1)}'`);if($.endDate)Y.push(`${Z} <= DATE '${Q($.endDate,1)}'`);return Y.join(" AND ")}function Go1($){if(/[';]/.test($.bucket)||/[';]/.test($.prefix))throw Error("Invalid monitoring GCS bucket/prefix");let Z=$.prefix.replace(/^\/+|\/+$/g,""),Q=Z?`s3://${$.bucket}/${Z}`:`s3://${$.bucket}`,X=$.range?.startDate||$.range?.endDate?`${Q}/year=*/**/*`:`${Q}/**/*`;return Ua8(X,{range:$.range})}var Ha8="studio_monitoring_logs",Fa8="studio.monitoring.";var Wo1=D(()=>{D3()});import{sql as Ba8}from"kysely";function Xu($){if(!$)return null;return typeof $==="string"?JSON.parse($):$}function Ju($){return $?JSON.stringify($):null}function Ko1($){return{organizationId:$.organizationId,sidebar_items:Xu($.sidebar_items),coding_agent_mcp_excluded:Xu($.coding_agent_mcp_excluded),simple_mode:Xu($.simple_mode),default_home_agents:Xu($.default_home_agents),flags:Xu($.flags),submodule_credentials:Xu($.submodule_credentials),createdAt:$.createdAt,updatedAt:$.updatedAt}}class NP{db;constructor($){this.db=$}async get($){let Z=await this.db.selectFrom("organization_settings").selectAll().where("organizationId","=",$).executeTakeFirst();return Z?Ko1(Z):null}async upsert($,Z){let Q=new Date().toISOString(),Y={sidebar_items:Ju(Z?.sidebar_items),coding_agent_mcp_excluded:Ju(Z?.coding_agent_mcp_excluded),simple_mode:Ju(Z?.simple_mode),default_home_agents:Ju(Z?.default_home_agents),flags:Ju(Z?.flags),submodule_credentials:Ju(Z?.submodule_credentials)},X=await this.db.insertInto("organization_settings").values({organizationId:$,...Y,createdAt:Q,updatedAt:Q}).onConflict((J)=>J.column("organizationId").doUpdateSet({sidebar_items:Y.sidebar_items??void 0,coding_agent_mcp_excluded:Y.coding_agent_mcp_excluded??void 0,simple_mode:Y.simple_mode??void 0,default_home_agents:Y.default_home_agents??void 0,flags:Y.flags?Ba8`coalesce("organization_settings"."flags", '{}'::jsonb) || ${Y.flags}::jsonb`:void 0,submodule_credentials:Y.submodule_credentials??void 0,updatedAt:Q})).returningAll().executeTakeFirstOrThrow();return Ko1(X)}}var Oi0=()=>{};class Di0{db;constructor($){this.db=$}async get($,Z){let Q=await this.db.selectFrom("user_model_preferences").select("tiers").where("user_id","=",$).where("organization_id","=",Z).executeTakeFirst();if(!Q)return null;return{tiers:(typeof Q.tiers==="string"?JSON.parse(Q.tiers):Q.tiers)??{}}}async upsert($,Z,Q){let Y=new Date().toISOString(),X=JSON.stringify(Q.tiers??{});return await this.db.insertInto("user_model_preferences").values({user_id:$,organization_id:Z,tiers:X,created_at:Y,updated_at:Y}).onConflict((J)=>J.columns(["user_id","organization_id"]).doUpdateSet({tiers:X,updated_at:Y})).execute(),{tiers:Q.tiers??{}}}}function Wu($){return typeof $==="string"?$:$.toISOString()}function Uo($){return{id:$.id,organization_id:$.organization_id,name:$.name,active:!!$.active,created_by:$.created_by,messages:$.messages,models:$.models,tools:$.tools??null,temperature:$.temperature,max_agent_steps:$.max_agent_steps??null,virtual_mcp_id:$.virtual_mcp_id,created_at:Wu($.created_at),updated_at:Wu($.updated_at)}}function Gu($){return{id:$.id,automation_id:$.automation_id,type:$.type,cron_expression:$.cron_expression,connection_id:$.connection_id,event_type:$.event_type,params:$.params,last_run_at:$.last_run_at?Wu($.last_run_at):null,next_run_at:$.next_run_at?Wu($.next_run_at):null,api_key_id:$.api_key_id??null,created_at:Wu($.created_at)}}function Fo1($){return Uo({id:$.a_id,organization_id:$.a_organization_id,name:$.a_name,active:$.a_active,created_by:$.a_created_by,messages:$.a_messages,models:$.a_models,tools:$.a_tools,temperature:$.a_temperature,max_agent_steps:$.a_max_agent_steps,virtual_mcp_id:$.a_virtual_mcp_id,created_at:$.a_created_at,updated_at:$.a_updated_at})}class Uo1{db;constructor($){this.db=$}async create($){let Z=new Date().toISOString(),Y={id:crypto.randomUUID(),organization_id:$.organization_id,name:$.name,active:$.active??!0,created_by:$.created_by,messages:$.messages,models:$.models,tools:$.tools??null,temperature:$.temperature??0.5,max_agent_steps:$.max_agent_steps??null,virtual_mcp_id:$.virtual_mcp_id,created_at:Z,updated_at:Z},X=await this.db.insertInto("automations").values(Y).returningAll().executeTakeFirstOrThrow();return Uo(X)}async findById($,Z){let Q=await this.db.selectFrom("automations").selectAll().where("id","=",$).where("organization_id","=",Z).executeTakeFirst();return Q?Uo(Q):null}async list($){return(await this.db.selectFrom("automations").selectAll().where("organization_id","=",$).orderBy("created_at","desc").execute()).map(Uo)}async listWithTriggerCounts($,Z){let Q=this.db.selectFrom("automations as a").leftJoin("automation_triggers as t","t.automation_id","a.id").select(["a.id","a.organization_id","a.name","a.active","a.created_by","a.messages","a.models","a.tools","a.temperature","a.max_agent_steps","a.virtual_mcp_id","a.created_at","a.updated_at"]).select((X)=>X.fn.count("t.id").as("trigger_count")).select((X)=>X.fn.min("t.next_run_at").as("nearest_next_run_at")).where("a.organization_id","=",$);if(Z)Q=Q.where("a.virtual_mcp_id","=",Z);return(await Q.groupBy(["a.id","a.organization_id","a.name","a.active","a.created_by","a.messages","a.models","a.tools","a.temperature","a.max_agent_steps","a.virtual_mcp_id","a.created_at","a.updated_at"]).orderBy("a.created_at","desc").execute()).map((X)=>({...Uo(X),trigger_count:Number(X.trigger_count),nearest_next_run_at:X.nearest_next_run_at?Wu(X.nearest_next_run_at):null}))}async update($,Z,Q){let X={updated_at:new Date().toISOString()};if(Q.name!==void 0)X.name=Q.name;if(Q.active!==void 0)X.active=Q.active;if(Q.messages!==void 0)X.messages=Q.messages;if(Q.models!==void 0)X.models=Q.models;if(Q.tools!==void 0)X.tools=Q.tools;if(Q.temperature!==void 0)X.temperature=Q.temperature;if(Q.max_agent_steps!==void 0)X.max_agent_steps=Q.max_agent_steps;await this.db.updateTable("automations").set(X).where("id","=",$).where("organization_id","=",Z).execute();let J=await this.findById($,Z);if(!J)throw Error("Automation not found after update");return J}async delete($,Z){return{success:((await this.db.deleteFrom("automations").where("id","=",$).where("organization_id","=",Z).executeTakeFirst()).numDeletedRows??0n)>0n}}async addTrigger($){let Z=new Date().toISOString(),Y={id:crypto.randomUUID(),automation_id:$.automation_id,type:$.type,cron_expression:$.cron_expression??null,connection_id:$.connection_id??null,event_type:$.event_type??null,params:$.params??null,last_run_at:null,next_run_at:$.next_run_at??null,api_key_id:$.api_key_id??null,created_at:Z},X=await this.db.insertInto("automation_triggers").values(Y).returningAll().executeTakeFirstOrThrow();return Gu(X)}async removeTrigger($,Z){return{success:((await this.db.deleteFrom("automation_triggers").where("id","=",$).where("automation_id","=",Z).executeTakeFirst()).numDeletedRows??0n)>0n}}async listTriggers($){return(await this.db.selectFrom("automation_triggers").selectAll().where("automation_id","=",$).orderBy("created_at","asc").execute()).map(Gu)}async listTriggersForAutomations($){if($.length===0)return[];return(await this.db.selectFrom("automation_triggers").selectAll().where("automation_id","in",$).orderBy("created_at","asc").execute()).map(Gu)}async findTriggerById($){let Z=await this.db.selectFrom("automation_triggers").selectAll().where("id","=",$).executeTakeFirst();return Z?Gu(Z):null}async setTriggerApiKeyId($,Z){await this.db.updateTable("automation_triggers").set({api_key_id:Z}).where("id","=",$).execute()}async findActiveEventTriggers($,Z,Q){return(await this.db.selectFrom("automation_triggers as t").innerJoin("automations as a","a.id","t.automation_id").select(["t.id","t.automation_id","t.type","t.cron_expression","t.connection_id","t.event_type","t.params","t.last_run_at","t.api_key_id","t.created_at",...Ho1]).where("t.type","=","event").where("t.connection_id","=",$).where("t.event_type","=",Z).where("a.organization_id","=",Q).where("a.active","=",!0).execute()).map((X)=>({...Gu(X),automation:Fo1(X)}))}async listActiveByEventTriggerConnectionId($){return await this.db.selectFrom("automation_triggers as t").innerJoin("automations as a","a.id","t.automation_id").select(["a.id","a.name"]).where("t.type","=","event").where("t.connection_id","=",$).where("a.active","=",!0).distinct().execute()}async findAllCronTriggers(){return(await this.db.selectFrom("automation_triggers as t").innerJoin("automations as a","a.id","t.automation_id").select(["t.id","t.automation_id","t.type","t.cron_expression","t.connection_id","t.event_type","t.params","t.last_run_at","t.api_key_id","t.created_at",...Ho1]).where("t.type","=","cron").execute()).map((Z)=>({...Gu(Z),automation:Fo1(Z)}))}async updateNextRunAt($,Z){await this.db.updateTable("automation_triggers").set({next_run_at:Z}).where("id","=",$).execute()}async createAutomationRunThread($,Z){let Q=a8("thrd"),Y=new Date().toISOString();return await this.db.insertInto("threads").values({id:Q,organization_id:$.organization_id,title:`Automation: ${$.name}`,description:null,status:"in_progress",trigger_id:Z,virtual_mcp_id:$.virtual_mcp_id,harness_id:"decopilot",metadata:JSON.stringify({runtime:"sandbox"}),hidden:!1,message_storage_version:2,created_at:Y,updated_at:Y,created_by:$.created_by,updated_by:null}).execute(),Q}async markRunFailed($,Z,Q){await this.db.updateTable("threads").set({status:"failed",updated_at:new Date().toISOString(),...Z!=null?{failure_reason:Z}:{},...Q!=null?{failure_kind:Q}:{}}).where("id","=",$).where("status","=","in_progress").execute()}async markRunCompleted($){await this.db.updateTable("threads").set({status:"completed",updated_at:new Date().toISOString()}).where("id","=",$).where("status","=","in_progress").execute()}async updateTriggerLastRunAt($,Z){await this.db.updateTable("automation_triggers").set({last_run_at:Z}).where("id","=",$).execute()}async deactivateAutomation($){await this.db.updateTable("automations").set({active:!1,updated_at:new Date().toISOString()}).where("id","=",$).where("active","=",!0).execute()}async getRunStats($,Z,Q){let Y=this.db.selectFrom("threads as th").innerJoin("automation_triggers as t","t.id","th.trigger_id").select("th.status").select((G)=>G.fn.count("th.id").as("count")).where("t.automation_id","=",$).where("th.organization_id","=",Z).where("th.hidden","=",!1).groupBy("th.status");if(Q?.startDate)Y=Y.where("th.created_at",">=",Q.startDate);if(Q?.endDate)Y=Y.where("th.created_at","<=",Q.endDate);let X=await Y.execute(),J={total:0,completed:0,failed:0,inProgress:0};for(let G of X){let W=Number(G.count);if(J.total+=W,G.status==="completed")J.completed+=W;else if(G.status==="failed")J.failed+=W;else if(G.status==="in_progress")J.inProgress+=W}return J}async listRunThreadIds($,Z,Q){let Y=this.db.selectFrom("threads as th").innerJoin("automation_triggers as t","t.id","th.trigger_id").select("th.id").where("t.automation_id","=",$).where("th.organization_id","=",Z).where("th.hidden","=",!1).orderBy("th.created_at","desc").limit(Q?.limit??500);if(Q?.startDate)Y=Y.where("th.created_at",">=",Q.startDate);if(Q?.endDate)Y=Y.where("th.created_at","<=",Q.endDate);return(await Y.execute()).map((J)=>J.id)}}function _Q0($){return new Uo1($)}var Ho1;var Li0=D(()=>{ZY();Ho1=["a.id as a_id","a.organization_id as a_organization_id","a.name as a_name","a.active as a_active","a.created_by as a_created_by","a.messages as a_messages","a.models as a_models","a.tools as a_tools","a.temperature as a_temperature","a.max_agent_steps as a_max_agent_steps","a.virtual_mcp_id as a_virtual_mcp_id","a.created_at as a_created_at","a.updated_at as a_updated_at"]});import{createHash as Oa8,randomBytes as Da8}from"crypto";function No1($){return Oa8("sha256").update($).digest("hex")}function La8(){return Da8(32).toString("hex")}class No{db;constructor($){this.db=$}async generateTokenPair(){let $=La8(),Z=await No1($);return{plaintext:$,hash:Z}}async persistTokenHash($,Z,Q){let Y=crypto.randomUUID();await this.db.insertInto("trigger_callback_tokens").values({id:Y,organization_id:$,connection_id:Z,token_hash:Q,created_at:new Date().toISOString()}).onConflict((X)=>X.columns(["connection_id","organization_id"]).doUpdateSet({id:Y,token_hash:Q})).execute()}async createOrRotateToken($,Z){let{plaintext:Q,hash:Y}=await this.generateTokenPair();return await this.persistTokenHash($,Z,Y),Q}async validateToken($){let Z=await No1($),Q=await this.db.selectFrom("trigger_callback_tokens").select(["organization_id","connection_id"]).where("token_hash","=",Z).executeTakeFirst();if(!Q)return null;return{organizationId:Q.organization_id,connectionId:Q.connection_id}}async deleteByConnection($,Z){await this.db.deleteFrom("trigger_callback_tokens").where("connection_id","=",$).where("organization_id","=",Z).execute()}}var wi0=()=>{};function vQ0($){if(!$)return null;try{return JSON.parse($)}catch{return null}}function wa8($){if(!$)return null;if(!Array.isArray($)&&typeof $==="object"){let Z=$;if(Object.keys(Z).some((Y)=>bQ0.has(Y))){let Y={};for(let X of bQ0)if(typeof Z[X]==="string")Y[X]=Z[X];return Y}let Q={};for(let[Y,X]of Object.entries(Z))if(typeof X==="string"&&bQ0.has(Y.toLowerCase()))Q[Y.toLowerCase()]=X;return Object.keys(Q).length>0?Q:null}if(Array.isArray($)){let Z={};for(let Q of $){let Y=Q,X=Y.label?.toLowerCase?.(),J=Y.value;if(X&&J&&bQ0.has(X))Z[X]=J}return Object.keys(Z).length>0?Z:null}return null}function Ea8($){if(!$)return null;if(!Array.isArray($)&&typeof $==="object"){let Z=$;if(typeof Z.heading==="string"||typeof Z.body==="string"||typeof Z.code==="string")return{heading:typeof Z.heading==="string"?Z.heading:void 0,body:typeof Z.body==="string"?Z.body:void 0,code:typeof Z.code==="string"?Z.code:void 0};return null}if(Array.isArray($)){let Z={},Q=[];for(let Y of $){let X=Y,J=X.name??X.family??void 0,G=X.role?.toLowerCase?.()??"";if(!J)continue;let W=ja8[G];if(W&&!Z[W])Z[W]=J;else Q.push(J)}if(!Z.body&&Q[0])Z.body=Q[0];return Object.keys(Z).length>0?Z:null}return null}function ji0($){return{id:$.id,organizationId:$.organization_id,name:$.name,domain:$.domain,overview:$.overview,logo:$.logo,favicon:$.favicon,ogImage:$.og_image,fonts:Ea8(vQ0($.fonts)),colors:wa8(vQ0($.colors)),images:vQ0($.images),metadata:vQ0($.metadata),archivedAt:$.archived_at,isDefault:$.is_default,createdAt:$.created_at,updatedAt:$.updated_at}}class Bo{db;constructor($){this.db=$}async get($,Z){let Q=await this.db.selectFrom("brand_context").selectAll().where("id","=",$).where("organization_id","=",Z).executeTakeFirst();if(!Q)return null;return ji0(Q)}async list($,Z){let Q=this.db.selectFrom("brand_context").selectAll().where("organization_id","=",$);if(!Z?.includeArchived)Q=Q.where("archived_at","is",null);return(await Q.orderBy("created_at","asc").execute()).map(ji0)}async create($,Z){let Q=crypto.randomUUID(),Y=new Date().toISOString();return await this.db.insertInto("brand_context").values({id:Q,organization_id:$,name:Z.name,domain:Z.domain,overview:Z.overview,logo:Z.logo,favicon:Z.favicon,og_image:Z.ogImage,fonts:Z.fonts?JSON.stringify(Z.fonts):null,colors:Z.colors?JSON.stringify(Z.colors):null,images:Z.images?JSON.stringify(Z.images):null,metadata:Z.metadata?JSON.stringify(Z.metadata):null,archived_at:null,is_default:!1,created_at:Y,updated_at:Y}).execute(),await this.get(Q,$)}async update($,Z,Q){let X={updated_at:new Date().toISOString()};if(Q.name!==void 0)X.name=Q.name;if(Q.domain!==void 0)X.domain=Q.domain;if(Q.overview!==void 0)X.overview=Q.overview;if(Q.logo!==void 0)X.logo=Q.logo;if(Q.favicon!==void 0)X.favicon=Q.favicon;if(Q.ogImage!==void 0)X.og_image=Q.ogImage;if(Q.fonts!==void 0)X.fonts=Q.fonts?JSON.stringify(Q.fonts):null;if(Q.colors!==void 0)X.colors=Q.colors?JSON.stringify(Q.colors):null;if(Q.images!==void 0)X.images=Q.images?JSON.stringify(Q.images):null;if(Q.metadata!==void 0)X.metadata=Q.metadata?JSON.stringify(Q.metadata):null;if(Q.archivedAt!==void 0)X.archived_at=Q.archivedAt??null;if(Q.isDefault!==void 0)X.is_default=Q.isDefault;await this.db.updateTable("brand_context").set(X).where("id","=",$).where("organization_id","=",Z).execute();let J=await this.get($,Z);if(!J)throw Error("Brand context not found");return J}async getDefault($){let Z=await this.db.selectFrom("brand_context").selectAll().where("organization_id","=",$).where("is_default","=",!0).where("archived_at","is",null).executeTakeFirst();if(!Z)return null;return ji0(Z)}async setDefault($,Z){await this.db.transaction().execute(async(Y)=>{await Y.updateTable("brand_context").set({is_default:!1}).where("organization_id","=",Z).where("is_default","=",!0).execute(),await Y.updateTable("brand_context").set({is_default:!0,updated_at:new Date().toISOString()}).where("id","=",$).where("organization_id","=",Z).execute()});let Q=await this.get($,Z);if(!Q)throw Error("Brand context not found");return Q}async delete($,Z){await this.db.deleteFrom("brand_context").where("id","=",$).where("organization_id","=",Z).execute()}}var bQ0,ja8;var Ei0=D(()=>{bQ0=new Set(["primary","secondary","accent","background","foreground"]);ja8={heading:"heading",headings:"heading",head:"heading",title:"heading",body:"body",primary:"body",text:"body",code:"code",monospace:"code",mono:"code"}});function xQ0($){return{id:$.id,organizationId:$.organization_id,domain:$.domain,joinMode:$.join_mode,verificationStatus:$.verification_status==="verified"?"verified":"pending",verificationMethod:$.verification_method??null,verificationToken:$.verification_token,verifiedAt:$.verified_at,createdAt:$.created_at,updatedAt:$.updated_at}}class OG{db;constructor($){this.db=$}async getAllByDomain($){return(await this.db.selectFrom("organization_domains").selectAll().where("domain","=",$.toLowerCase()).execute()).map(xQ0)}async listByOrganizationId($){return(await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",$).orderBy("created_at","asc").execute()).map(xQ0)}async getById($){let Z=await this.db.selectFrom("organization_domains").selectAll().where("id","=",$).executeTakeFirst();return Z?xQ0(Z):null}async getByOrgAndDomain($,Z){let Q=await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",$).where("domain","=",Z.toLowerCase()).executeTakeFirst();return Q?xQ0(Q):null}async add($,Z,Q={}){let Y=Z.toLowerCase(),X=await this.getByOrgAndDomain($,Y);if(X)return X;let J=new Date().toISOString(),G=crypto.randomUUID(),W=Q.verificationStatus??"pending";try{await this.db.insertInto("organization_domains").values({id:G,organization_id:$,domain:Y,join_mode:Q.joinMode??"off",verification_status:W,verification_method:Q.verificationMethod??null,verification_token:Q.verificationToken??null,verified_at:W==="verified"?J:null,created_at:J,updated_at:J}).execute()}catch(H){if(H.code==="23505"){let F=await this.getByOrgAndDomain($,Y);if(F)return F}throw H}let K=await this.getById(G);if(!K)throw Error("Failed to add domain");return K}async updateJoinMode($,Z){await this.db.updateTable("organization_domains").set({join_mode:Z,updated_at:new Date().toISOString()}).where("id","=",$).execute();let Q=await this.getById($);if(!Q)throw Error("Domain not found");return Q}async markVerified($,Z){let Q=new Date().toISOString();await this.db.updateTable("organization_domains").set({verification_status:"verified",verification_method:Z,verification_token:null,verified_at:Q,updated_at:Q}).where("id","=",$).execute();let Y=await this.getById($);if(!Y)throw Error("Domain not found");return Y}async removeById($){await this.db.deleteFrom("organization_domains").where("id","=",$).execute()}}function zi0($){return{id:$.id,organizationId:$.organization_id,userId:$.user_id,status:$.status,decidedBy:$.decided_by,decidedAt:$.decided_at,createdAt:$.created_at,updatedAt:$.updated_at}}class Ku{db;constructor($){this.db=$}async create($,Z){let Q=await this.getPending($,Z);if(Q)return Q;let Y=new Date().toISOString(),X=crypto.randomUUID();try{await this.db.insertInto("organization_join_requests").values({id:X,organization_id:$,user_id:Z,status:"pending",decided_by:null,decided_at:null,created_at:Y,updated_at:Y}).execute()}catch(G){if(G.code==="23505"){let W=await this.getPending($,Z);if(W)return W}throw G}let J=await this.getById(X);if(!J)throw Error("Failed to create join request");return J}async getById($){let Z=await this.db.selectFrom("organization_join_requests").selectAll().where("id","=",$).executeTakeFirst();return Z?zi0(Z):null}async getPending($,Z){let Q=await this.db.selectFrom("organization_join_requests").selectAll().where("organization_id","=",$).where("user_id","=",Z).where("status","=","pending").executeTakeFirst();return Q?zi0(Q):null}async listPendingWithUser($){return(await this.db.selectFrom("organization_join_requests as r").innerJoin("user","user.id","r.user_id").select(["r.id as id","r.organization_id as organization_id","r.user_id as user_id","r.status as status","r.decided_by as decided_by","r.decided_at as decided_at","r.created_at as created_at","r.updated_at as updated_at","user.name as user_name","user.email as user_email","user.image as user_image"]).where("r.organization_id","=",$).where("r.status","=","pending").orderBy("r.created_at","asc").execute()).map((Q)=>({...zi0(Q),user:{id:Q.user_id,name:Q.user_name,email:Q.user_email,image:Q.user_image}}))}async decide($,Z,Q){let Y=new Date().toISOString();if((await this.db.updateTable("organization_join_requests").set({status:Z,decided_by:Q,decided_at:Y,updated_at:Y}).where("id","=",$).where("status","=","pending").executeTakeFirst()).numUpdatedRows===0n)return null;return this.getById($)}}class Oo{db;constructor($){this.db=$}async get($,Z){let Q=await this.db.selectFrom("kv").select("value").where("organization_id","=",$).where("key","=",Z).executeTakeFirst();if(!Q)return null;return Q.value}async set($,Z,Q){await this.db.insertInto("kv").values({organization_id:$,key:Z,value:JSON.stringify(Q),updated_at:new Date().toISOString()}).onConflict((Y)=>Y.columns(["organization_id","key"]).doUpdateSet({value:JSON.stringify(Q),updated_at:new Date().toISOString()})).execute()}async delete($,Z){await this.db.deleteFrom("kv").where("organization_id","=",$).where("key","=",Z).execute()}}function za8($){if(!$||!Array.isArray($.interests))return null;return{interests:$.interests}}class Pi0{kv;constructor($){this.kv=$}async getForAgent($,Z,Q){let Y=await this.kv.get($,Bo1(Z,Q));return za8(Y)}async setForAgent($,Z,Q,Y){await this.kv.set($,Bo1(Z,Q),Y)}}var Oo1="interests:",Bo1=($,Z)=>`interests:${$}:${Z}`;class Ai0{db;vault;constructor($,Z){this.db=$;this.vault=Z}async getByOrgId($){let Z=await this.db.selectFrom("org_sso_config").selectAll().where("organization_id","=",$).executeTakeFirst();if(!Z)return null;return this.toRuntime(Z)}async getByDomain($){let Z=await this.db.selectFrom("org_sso_config").selectAll().where("domain","=",$.toLowerCase()).executeTakeFirst();if(!Z)return null;return this.toRuntime(Z)}async upsert($,Z){let Q=new Date().toISOString(),Y=crypto.randomUUID(),X=await this.vault.encrypt(Z.clientSecret),J=JSON.stringify(Z.scopes??["openid","email","profile"]),G=Z.enforced===void 0?void 0:Z.enforced?1:0;await this.db.insertInto("org_sso_config").values({id:Y,organization_id:$,issuer:Z.issuer,client_id:Z.clientId,client_secret:X,discovery_endpoint:Z.discoveryEndpoint??null,scopes:J,domain:Z.domain.toLowerCase(),enforced:G??0,created_at:Q,updated_at:Q}).onConflict((K)=>K.column("organization_id").doUpdateSet({issuer:Z.issuer,client_id:Z.clientId,client_secret:X,discovery_endpoint:Z.discoveryEndpoint??null,scopes:J,domain:Z.domain.toLowerCase(),...G!==void 0?{enforced:G}:{},updated_at:Q})).execute();let W=await this.getByOrgId($);if(!W)throw Error("Failed to upsert org SSO config");return W}async setEnforced($,Z){await this.db.updateTable("org_sso_config").set({enforced:Z?1:0,updated_at:new Date().toISOString()}).where("organization_id","=",$).execute()}async delete($){await this.db.deleteFrom("org_sso_config").where("organization_id","=",$).execute()}toPublic($){let{clientSecret:Z,...Q}=$;return Q}async toRuntime($){let Z=await this.vault.decrypt($.client_secret),Q=typeof $.scopes==="string"?JSON.parse($.scopes):$.scopes;return{id:$.id,organizationId:$.organization_id,issuer:$.issuer,clientId:$.client_id,clientSecret:Z,discoveryEndpoint:$.discovery_endpoint,scopes:Q,domain:$.domain,enforced:$.enforced===1,createdAt:$.created_at,updatedAt:$.updated_at}}}class Ti0{db;constructor($){this.db=$}async get($,Z){let Q=await this.db.selectFrom("org_sso_sessions").selectAll().where("user_id","=",$).where("organization_id","=",Z).executeTakeFirst();if(!Q)return null;return{id:Q.id,userId:Q.user_id,organizationId:Q.organization_id,authenticatedAt:Q.authenticated_at,expiresAt:Q.expires_at,createdAt:Q.created_at}}async isValid($,Z){let Q=await this.get($,Z);if(!Q)return!1;return new Date(Q.expiresAt)>new Date}async upsert($,Z){let Q=new Date,Y=new Date(Q.getTime()+86400000),X=crypto.randomUUID();await this.db.insertInto("org_sso_sessions").values({id:X,user_id:$,organization_id:Z,authenticated_at:Q.toISOString(),expires_at:Y.toISOString(),created_at:Q.toISOString()}).onConflict((G)=>G.columns(["user_id","organization_id"]).doUpdateSet({authenticated_at:Q.toISOString(),expires_at:Y.toISOString()})).execute();let J=await this.get($,Z);if(!J)throw Error("Failed to upsert SSO session");return J}async deleteExpired(){await this.db.deleteFrom("org_sso_sessions").where("expires_at","<",new Date().toISOString()).execute()}}class Do{db;constructor($){this.db=$}async listOrgTags($){return(await this.db.selectFrom("organization_tags").selectAll().where("organization_id","=",$).orderBy("name","asc").execute()).map((Q)=>this.tagFromDbRow(Q))}async getTag($){let Z=await this.db.selectFrom("organization_tags").selectAll().where("id","=",$).executeTakeFirst();return Z?this.tagFromDbRow(Z):null}async getTagsByIds($){if($.length===0)return[];return(await this.db.selectFrom("organization_tags").selectAll().where("id","in",$).execute()).map((Q)=>this.tagFromDbRow(Q))}async getTagByName($,Z){let Q=await this.db.selectFrom("organization_tags").selectAll().where("organization_id","=",$).where("name","=",Z).executeTakeFirst();return Q?this.tagFromDbRow(Q):null}async createTag($,Z,Q){let Y=a8("tag"),X=new Date().toISOString();await this.db.insertInto("organization_tags").values({id:Y,organization_id:$,name:Z,color:Q??null,created_at:X}).onConflict((G)=>G.columns(["organization_id","name"]).doNothing()).execute();let J=await this.getTagByName($,Z);if(!J)throw Error(`Failed to create or retrieve tag: ${Z}`);return J}async deleteTag($){await this.db.deleteFrom("organization_tags").where("id","=",$).execute()}async getMemberTags($){return(await this.db.selectFrom("member_tags").innerJoin("organization_tags","organization_tags.id","member_tags.tag_id").select(["organization_tags.id","organization_tags.organization_id","organization_tags.name","organization_tags.color","organization_tags.created_at"]).where("member_tags.member_id","=",$).orderBy("organization_tags.name","asc").execute()).map((Q)=>this.tagFromDbRow(Q))}async setMemberTags($,Z){await this.db.transaction().execute(async(Q)=>{if(await Q.deleteFrom("member_tags").where("member_id","=",$).execute(),Z.length>0){let Y=new Date().toISOString();await Q.insertInto("member_tags").values(Z.map((X)=>({id:a8("mtag"),member_id:$,tag_id:X,created_at:Y}))).execute()}})}async addMemberTag($,Z){let Q=new Date().toISOString();await this.db.insertInto("member_tags").values({id:a8("mtag"),member_id:$,tag_id:Z,created_at:Q}).onConflict((Y)=>Y.columns(["member_id","tag_id"]).doNothing()).execute()}async removeMemberTag($,Z){await this.db.deleteFrom("member_tags").where("member_id","=",$).where("tag_id","=",Z).execute()}async verifyMemberOrg($,Z){return await this.db.selectFrom("member").select("id").where("id","=",$).where("organizationId","=",Z).executeTakeFirst()!==void 0}async getUserTagsInOrg($,Z){return(await this.db.selectFrom("member").innerJoin("member_tags","member_tags.member_id","member.id").innerJoin("organization_tags","organization_tags.id","member_tags.tag_id").select(["organization_tags.id","organization_tags.organization_id","organization_tags.name","organization_tags.color","organization_tags.created_at"]).where("member.userId","=",$).where("member.organizationId","=",Z).orderBy("organization_tags.name","asc").execute()).map((Y)=>this.tagFromDbRow(Y))}async getMembersWithTags($){let Z=await this.db.selectFrom("member").leftJoin("member_tags","member_tags.member_id","member.id").leftJoin("organization_tags","organization_tags.id","member_tags.tag_id").select(["member.id as memberId","organization_tags.name as tagName"]).where("member.organizationId","=",$).execute(),Q=new Map;for(let Y of Z){if(!Q.has(Y.memberId))Q.set(Y.memberId,[]);if(Y.tagName)Q.get(Y.memberId).push(Y.tagName)}return Q}tagFromDbRow($){return{id:$.id,organizationId:$.organization_id,name:$.name,color:$.color??null,createdAt:$.created_at}}}var Ri0=D(()=>{ZY()});class qi0{db;constructor($){this.db=$}async listBySite($,Z){return(await this.db.selectFrom("experiments").selectAll().where("organization_id","=",$).where("site","=",Z).orderBy("created_at","desc").execute()).map((Y)=>this.fromRow(Y))}async getByKey($,Z,Q){let Y=await this.db.selectFrom("experiments").selectAll().where("organization_id","=",$).where("site","=",Z).where("key","=",Q).executeTakeFirst();return Y?this.fromRow(Y):null}async create($){let Z=a8("exp"),Q=new Date().toISOString();await this.db.insertInto("experiments").values({id:Z,organization_id:$.organizationId,site:$.site,key:$.key,name:$.name,status:"draft",goals:JSON.stringify($.goals??[]),variants:JSON.stringify($.variants??[]),created_by:$.createdBy,created_at:Q,updated_at:Q}).execute();let Y=await this.getByKey($.organizationId,$.site,$.key);if(!Y)throw Error("failed to create experiment");return Y}async update($,Z,Q,Y){let X=await this.getByKey($,Z,Q);if(!X)return null;let J=new Date().toISOString(),G={updated_at:J};if(Y.name!==void 0)G.name=Y.name;if(Y.goals!==void 0)G.goals=JSON.stringify(Y.goals);if(Y.variants!==void 0)G.variants=JSON.stringify(Y.variants);if(Y.status!==void 0){if(G.status=Y.status,Y.status==="running"&&!X.startedAt)G.started_at=J;if(Y.status==="ended"&&!X.endedAt)G.ended_at=J}return await this.db.updateTable("experiments").set(G).where("organization_id","=",$).where("site","=",Z).where("key","=",Q).execute(),this.getByKey($,Z,Q)}async delete($,Z,Q){return((await this.db.deleteFrom("experiments").where("organization_id","=",$).where("site","=",Z).where("key","=",Q).executeTakeFirst()).numDeletedRows??0n)>0n}fromRow($){let Z=(Q)=>new Date(Q).toISOString();return{id:$.id,organizationId:$.organization_id,site:$.site,key:$.key,name:$.name,status:["running","paused","ended"].includes($.status)?$.status:"draft",goals:$.goals??[],variants:$.variants??[],startedAt:$.started_at?Z($.started_at):null,endedAt:$.ended_at?Z($.ended_at):null,createdBy:$.created_by,createdAt:Z($.created_at),updatedAt:Z($.updated_at)}}}var Do1=D(()=>{ZY()});import{sql as Pa8}from"kysely";function Mi0($){return{organizationId:$.organization_id,status:$.status,stripeCustomerId:$.stripe_customer_id,stripeSubscriptionId:$.stripe_subscription_id,currentPeriodEnd:$.current_period_end,lastStripeEventAt:$.last_stripe_event_at,freeTaskExecutions:$.free_task_executions,monthlyTaskExecutions:$.monthly_task_executions}}class DG{db;constructor($){this.db=$}async getBilling($){let Z=await this.db.selectFrom("organization_billing").selectAll().where("organization_id","=",$).executeTakeFirst();return Z?Mi0(Z):null}async ensureBilling($){let Z=await this.getBilling($);if(Z)return Z;try{await this.db.insertInto("organization_billing").values({organization_id:$}).onConflict((Q)=>Q.column("organization_id").doNothing()).execute()}catch{return null}return await this.getBilling($)}async getBillingByStripeSubscriptionId($){let Z=await this.db.selectFrom("organization_billing").selectAll().where("stripe_subscription_id","=",$).executeTakeFirst();return Z?Mi0(Z):null}async listSubscriptionsPastPeriodEnd($,Z){return(await this.db.selectFrom("organization_billing").selectAll().where("stripe_subscription_id","is not",null).where("status","<>","canceled").where("current_period_end","is not",null).where("current_period_end","<",$).orderBy("current_period_end","asc").limit(Z).execute()).map(Mi0)}async bindSubscription($,Z){return((await this.db.updateTable("organization_billing").set({stripe_subscription_id:Z.stripeSubscriptionId,...Z.stripeCustomerId!==void 0&&{stripe_customer_id:Z.stripeCustomerId},...Z.status!==void 0&&{status:Z.status},...Z.lastStripeEventAt!==void 0&&{last_stripe_event_at:Z.lastStripeEventAt},updated_at:new Date}).where("organization_id","=",$).where((Y)=>Y.or([Y("stripe_subscription_id","is",null),Y("stripe_subscription_id","=",Z.stripeSubscriptionId)])).executeTakeFirst()).numUpdatedRows??0n)>0n}async updateStripeState($,Z){return((await this.db.updateTable("organization_billing").set({...Z.stripeCustomerId!==void 0&&{stripe_customer_id:Z.stripeCustomerId},...Z.stripeSubscriptionId!==void 0&&{stripe_subscription_id:Z.stripeSubscriptionId},...Z.status!==void 0&&{status:Z.status},...Z.currentPeriodEnd!==void 0&&{current_period_end:Z.currentPeriodEnd},...Z.lastStripeEventAt!==void 0&&{last_stripe_event_at:Z.lastStripeEventAt},updated_at:new Date}).where("organization_id","=",$).executeTakeFirst()).numUpdatedRows??0n)>0n}async taskClaim($){let Z=await this.db.selectFrom("task_quota_claims").select(["run_count","state"]).where("task_board_item_id","=",$).executeTakeFirst();return Z?{runCount:Z.run_count,state:Z.state}:null}static liveClaimCount($,Z,Q){return $.selectFrom("task_quota_claims").select((Y)=>Y.fn.countAll().as("count")).where("organization_id","=",Z).where("period_key","=",Q).where("state","<>","released").executeTakeFirst().then((Y)=>Number(Y?.count??0))}async countTaskClaims($,Z){return await DG.liveClaimCount(this.db,$,Z)}async claimTaskUnderLimit($,Z,Q,Y,X){return await this.db.transaction().execute(async(J)=>{await J.insertInto("organization_billing").values({organization_id:$}).onConflict((K)=>K.column("organization_id").doNothing()).execute(),await J.selectFrom("organization_billing").select("organization_id").where("organization_id","=",$).forUpdate().executeTakeFirstOrThrow();let G=await J.selectFrom("task_quota_claims").select(["run_count","state"]).where("task_board_item_id","=",Z).executeTakeFirst();if(G&&G.run_count>=X)return"runs_exhausted";let W=()=>DG.liveClaimCount(J,$,Q);if(G&&G.state!=="released")return await J.updateTable("task_quota_claims").set({run_count:G.run_count+1}).where("task_board_item_id","=",Z).execute(),"rerun";if(await W()>=Y)return"exhausted";if(G)return await J.updateTable("task_quota_claims").set({state:"held",period_key:Q,run_count:G.run_count+1}).where("task_board_item_id","=",Z).execute(),"claimed";return await J.insertInto("task_quota_claims").values({task_board_item_id:Z,organization_id:$,period_key:Q,state:"held"}).execute(),"claimed"})}async releaseTaskClaim($,Z){return((await this.db.updateTable("task_quota_claims").set({state:"released"}).where("organization_id","=",$).where("task_board_item_id","=",Z).where("state","=","held").executeTakeFirst()).numUpdatedRows??0n)>0n}async rollbackTaskClaim($,Z,{releaseSlot:Q}){await this.db.updateTable("task_quota_claims").set(()=>({...Q?{state:"released"}:{},run_count:Pa8`greatest(run_count - 1, 0)`})).where("organization_id","=",$).where("task_board_item_id","=",Z).where("state","=","held").execute()}}var Lo=()=>{};class Ii0{db;constructor($){this.db=$}async findById($,Z){let Q=await this.db.selectFrom("user").select(["user.id","user.name","user.email","user.image","user.createdAt","user.updatedAt"]).where("user.id","=",$).where((Y)=>Y.exists(Y.selectFrom("member as m1").innerJoin("member as m2","m1.organizationId","m2.organizationId").select("m1.id").where("m1.userId","=",$).where("m2.userId","=",Z))).executeTakeFirst();if(!Q)return null;return{id:Q.id,name:Q.name,email:Q.email,role:"",createdAt:Q.createdAt,updatedAt:Q.updatedAt,image:Q.image??void 0}}}function YF($){let Z=$?.["mcp.studio"];if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z;let Q=$?.["mcp.mesh"];if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q;return}function wo1(){let $={};for(let Z of fQ0){if(Z.id==="basic-usage")continue;$[Z.id]=!0}return $}function ki0($){let Z=(J)=>{let G=$[J];return Array.isArray(G)?G:[]},Q=Z("*").includes("*")||Z("self").includes("*"),Y=new Set;if(!Q)for(let J of Object.values($)){if(!Array.isArray(J))continue;for(let G of J)Y.add(G)}let X={};for(let J of fQ0){if(J.id==="basic-usage")continue;X[J.id]=Q||J.tools.every((G)=>Y.has(G))}return X}function BP(){let $={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],Tags:[],Experiments:[],"AI Providers":[],Secrets:[],"File Configs":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],Git:[],VM:[],Search:[],"Task Board":[],Jira:[],Blog:[]};for(let Z of Vi0)$[Z.category].push(Z);return $}var Vi0,fQ0,Lo1,Aa8,yQ0;var Hu=D(()=>{Vi0=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"BRAND_CONTEXT_LIST",description:"List brand contexts",category:"Organizations"},{name:"BRAND_CONTEXT_GET",description:"View brand context",category:"Organizations"},{name:"BRAND_CONTEXT_CREATE",description:"Create brand context",category:"Organizations"},{name:"BRAND_CONTEXT_UPDATE",description:"Update brand context",category:"Organizations"},{name:"BRAND_CONTEXT_DELETE",description:"Delete brand context",category:"Organizations",dangerous:!0},{name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context from website",category:"Organizations"},{name:"BLOG_BRAND_EXTRACT",description:"Infer editorial brand context (tone, dos and don'ts) from a site",category:"Blog"},{name:"BLOG_PILLAR_SUGGEST",description:"Propose content pillars from a brand's editorial context",category:"Blog"},{name:"BLOG_THEME_SUGGEST",description:"Propose blog post ideas from a brand's editorial context",category:"Blog"},{name:"BLOG_FORMAT_SUGGEST",description:"Name the post formats a blog writes in",category:"Blog"},{name:"BLOG_POST_DRAFT",description:"Write a blog post from a theme and a format",category:"Blog"},{name:"BLOG_LINK_SUGGEST",description:"Propose internal links from a post to the site's other posts",category:"Blog"},{name:"BRAND_GET",description:"Get brand (binding)",category:"Organizations"},{name:"BRAND_LIST",description:"List brands (binding)",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_LIST",description:"List organization domain claims",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_ADD",description:"Claim an email domain for the organization",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_UPDATE",description:"Set a domain's join mode",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_VERIFY",description:"Verify a domain via DNS TXT record",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_REMOVE",description:"Remove an organization domain claim",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_JOIN_REQUEST_LIST",description:"List pending requests to join the organization",category:"Organizations"},{name:"ORGANIZATION_JOIN_REQUEST_APPROVE",description:"Approve a request to join the organization",category:"Organizations"},{name:"ORGANIZATION_JOIN_REQUEST_DENY",description:"Deny a request to join the organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"ORGANIZATION_BILLING_CHECKOUT_START",description:"Start the org subscription checkout",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_BILLING_PORTAL",description:"Open the Stripe billing portal",category:"Organizations"},{name:"ORGANIZATION_BILLING_PLAN_PRICES",description:"Read each plan's monthly price from Stripe",category:"Organizations"},{name:"ORGANIZATION_TASK_QUOTA_GET",description:"Get the org's auto-task quota usage",category:"Organizations"},{name:"INFRA_BILLING_SITES_LIST",description:"List the legacy deco.cx sites the org owns",category:"Organizations"},{name:"INFRA_BILLING_GET",description:"Get infra usage, plan and invoices for an owned site",category:"Organizations"},{name:"INFRA_BILLING_PORTAL",description:"Open the Stripe billing portal for an owned site",category:"Organizations"},{name:"ORGANIZATION_HAS_SITE",description:"Whether this organization owns at least one legacy deco.cx site",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"REPORTS_SETUP",description:"Set up Deco Score",category:"Connections"},{name:"REPORTS_RUN",description:"Run Deco Score",category:"Connections"},{name:"REPORTS_BIND",description:"Bind Deco Score data source",category:"Connections"},{name:"REPORTS_CONNECTION_STATUS",description:"Read Deco Score connection status",category:"Connections"},{name:"REPORTS_SET_REPOSITORY",description:"Set the Deco Score repository",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_HEATMAP",description:"View tool-call volume by agent and tool",category:"Monitoring"},{name:"MONITORING_LOG_GET",description:"View monitoring log details",category:"Monitoring"},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"MONITORING_THREAD_USAGE",description:"View per-thread token usage and cost",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"USER_MODEL_PREFERENCES_GET",description:"Get the calling user's chat tier \u2192 model overrides",category:"Users"},{name:"USER_MODEL_PREFERENCES_UPDATE",description:"Set the calling user's chat tier \u2192 model overrides",category:"Users"},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"},{name:"TAGS_LIST",description:"List organization tags",category:"Tags"},{name:"TAGS_CREATE",description:"Create organization tag",category:"Tags"},{name:"TAGS_DELETE",description:"Delete organization tag",category:"Tags",dangerous:!0},{name:"EXPERIMENT_LIST",description:"List a site's A/B experiments",category:"Experiments"},{name:"EXPERIMENT_GET",description:"Get one A/B experiment",category:"Experiments"},{name:"EXPERIMENT_CREATE",description:"Create an A/B experiment",category:"Experiments"},{name:"EXPERIMENT_UPDATE",description:"Update an A/B experiment",category:"Experiments"},{name:"EXPERIMENT_DELETE",description:"Delete an A/B experiment",category:"Experiments",dangerous:!0},{name:"EXPERIMENT_RESULTS",description:"A/B results for one experiment",category:"Experiments"},{name:"MEMBER_TAGS_GET",description:"Get member tags",category:"Tags"},{name:"MEMBER_TAGS_SET",description:"Set member tags",category:"Tags"},{name:"AUTOMATION_CREATE",description:"Create automation",category:"Automations"},{name:"AUTOMATION_GET",description:"View automation details",category:"Automations"},{name:"AUTOMATION_LIST",description:"List automations",category:"Automations"},{name:"AUTOMATION_UPDATE",description:"Update automation",category:"Automations"},{name:"AUTOMATION_DELETE",description:"Delete automation",category:"Automations",dangerous:!0},{name:"AUTOMATION_TRIGGER_ADD",description:"Add trigger to automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_REMOVE",description:"Remove trigger from automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_ROTATE_TOKEN",description:"Rotate the secret token for a webhook automation trigger",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"AUTOMATION_RUN_STATS",description:"View aggregated run counts and token/cost for an automation",category:"Automations"},{name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update virtual MCP pinned sidebar views",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_LAST_USED_LIST",description:"Get last-used info for one or more virtual MCPs",category:"Virtual MCPs"},{name:"AI_PROVIDERS_LIST",description:"List available AI providers",category:"AI Providers"},{name:"AI_PROVIDERS_LIST_MODELS",description:"List AI provider models",category:"AI Providers"},{name:"AI_PROVIDERS_ACTIVE",description:"List active AI providers",category:"AI Providers"},{name:"AI_PROVIDER_KEY_CREATE",description:"Store AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_KEY_LIST",description:"List AI provider API keys",category:"AI Providers"},{name:"AI_PROVIDER_KEY_DELETE",description:"Delete AI provider API key",category:"AI Providers",dangerous:!0},{name:"AI_PROVIDER_KEY_UPDATE",description:"Update AI provider API key label or credential",category:"AI Providers"},{name:"AI_PROVIDER_KEY_PREVIEW",description:"Get masked preview of AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_URL",description:"Get OAuth URL for provider",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_EXCHANGE",description:"Exchange OAuth code for API key",category:"AI Providers"},{name:"AI_PROVIDER_PROVISION_KEY",description:"Auto-provision API key for a provider",category:"AI Providers"},{name:"AI_PROVIDER_TOPUP_URL",description:"Get checkout URL to top up provider credits",category:"AI Providers"},{name:"CLAUDE_SUBSCRIPTION_CONNECT",description:"Link your own Claude subscription with a setup token",category:"AI Providers"},{name:"CLAUDE_SUBSCRIPTION_STATUS",description:"Whether your Claude subscription is linked, and since when",category:"AI Providers"},{name:"CLAUDE_SUBSCRIPTION_DISCONNECT",description:"Unlink your Claude subscription",category:"AI Providers"},{name:"AI_PROVIDER_CREDITS",description:"Get current credit balance for a provider",category:"AI Providers"},{name:"AI_PLAN_ENTITLEMENTS",description:"Get the org's plan, feature flags and AI usage bar",category:"AI Providers"},{name:"AI_PLAN_LIST",description:"List the plans an organization can move to",category:"AI Providers"},{name:"AI_PLAN_SET",description:"Change the organization's plan",category:"AI Providers"},{name:"SECRET_CREATE",description:"Create a secret in the credential vault",category:"Secrets"},{name:"SECRET_LIST",description:"List secrets visible to the caller (no values returned)",category:"Secrets"},{name:"FILE_CONFIG_CREATE",description:"Create an S3-compatible bucket configuration for the org",category:"File Configs"},{name:"FILE_CONFIG_LIST",description:"List S3 bucket configurations for the org (no creds returned)",category:"File Configs"},{name:"ORG_FS_PUBLIC_SETS_SYNC",description:"Re-sync the shared public skill-set volumes from their GitHub sources",category:"File Configs"},{name:"ORG_REPO_SYNC_CREATE",description:"Keep a GitHub repository mirrored into a new org-fs volume",category:"File Configs"},{name:"ORG_REPO_SYNC_LIST",description:"List the org's synced repositories and their sync status",category:"File Configs"},{name:"ORG_REPO_SYNC_UPDATE",description:"Update a synced repository's ref, paths, or enabled flag",category:"File Configs"},{name:"ORG_REPO_SYNC_DELETE",description:"Stop syncing a repository (already-synced files are kept)",category:"File Configs"},{name:"ORG_REPO_SYNC_RUN",description:"Sync a repository into its volume right now",category:"File Configs"},{name:"JIRA_INTEGRATION_GET",description:"Get the org's Jira integration config",category:"Jira"},{name:"JIRA_INTEGRATION_UPSERT",description:"Connect or update the org's Jira integration",category:"Jira"},{name:"JIRA_INTEGRATION_DELETE",description:"Disconnect Jira (already-synced cards are kept)",category:"Jira"},{name:"JIRA_BOARDS_LIST",description:"List Jira boards visible to the connected credentials",category:"Jira"},{name:"JIRA_BOARD_COLUMNS_LIST",description:"List a Jira board's columns and statuses for the mapping",category:"Jira"},{name:"JIRA_AUTOMATION_LIST",description:"List which Jira statuses start an agent run",category:"Jira"},{name:"JIRA_AUTOMATION_UPSERT",description:"Run the agent on issues entering a Jira status",category:"Jira"},{name:"JIRA_AUTOMATION_DELETE",description:"Stop running the agent on issues entering a Jira status",category:"Jira"},{name:"JIRA_RUN_START",description:"Run the agent on Jira issues now, to try a rule out",category:"Jira"},{name:"JIRA_ISSUE_GET",description:"Read a Jira issue on the board from a run",category:"Jira"},{name:"JIRA_COMMENT_ADD",description:"Comment on a Jira issue on the board from a run",category:"Jira"},{name:"JIRA_ISSUE_TRANSITION",description:"Move a Jira issue on the board to another status",category:"Jira"},{name:"JIRA_ATTACHMENT_DOWNLOAD",description:"Get a short-lived download URL for an attachment of a Jira issue",category:"Jira"},{name:"JIRA_REMOTE_LINK_ADD",description:"Link a pull request or deploy preview on a Jira issue",category:"Jira"},{name:"JIRA_ISSUE_CREATE",description:"Create a Jira issue on the board from a run",category:"Jira"},{name:"JIRA_ISSUE_SEARCH",description:"Search the Jira board's issues with JQL from a run",category:"Jira"},{name:"FILE_CONFIG_UPDATE",description:"Update an S3 bucket configuration, optionally rotating credentials",category:"File Configs"},{name:"FILE_CONFIG_DELETE",description:"Delete an S3 bucket configuration",category:"File Configs"},{name:"FILE_OBJECTS_LIST",description:"List existing objects in a configured bucket",category:"File Configs"},{name:"FILE_OBJECT_DELETE",description:"Delete an object from a configured bucket",category:"File Configs"},{name:"LIST_OBJECTS",description:"List objects in storage",category:"Object Storage"},{name:"GET_OBJECT_METADATA",description:"Get object metadata",category:"Object Storage"},{name:"GET_PRESIGNED_URL",description:"Generate download URL",category:"Object Storage"},{name:"PUT_PRESIGNED_URL",description:"Generate upload URL",category:"Object Storage"},{name:"DELETE_OBJECT",description:"Delete object",category:"Object Storage",dangerous:!0},{name:"DELETE_OBJECTS",description:"Delete multiple objects",category:"Object Storage",dangerous:!0},{name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry apps",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_GET",description:"Get registry app details",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"List registry app versions",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get registry app filters",category:"Registry"},{name:"REGISTRY_ITEM_LIST",description:"List Deco registry items",category:"Registry"},{name:"REGISTRY_ITEM_SEARCH",description:"Search registry items",category:"Registry"},{name:"REGISTRY_ITEM_GET",description:"Get registry item details",category:"Registry"},{name:"REGISTRY_ITEM_VERSIONS",description:"List registry item versions",category:"Registry"},{name:"REGISTRY_ITEM_FILTERS",description:"Get registry item filters",category:"Registry"},{name:"SANDBOX_START",description:"Start a sandbox VM with dev server preview",category:"VM"},{name:"SANDBOX_DELETE",description:"Stop and delete a sandbox VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"},{name:"GIT_PROVIDER_CAPABILITIES",description:"Which git providers this deployment can connect, with their connect URLs",category:"Git"},{name:"GIT_ACCOUNT_LIST",description:"List the git provider accounts connected to the organization",category:"Git"},{name:"GIT_ACCOUNT_CONNECT_TOKEN",description:"Connect a git provider account with an access token",category:"Git"},{name:"GIT_ACCOUNT_DELETE",description:"Disconnect a git provider account",category:"Git"},{name:"REPOSITORY_LIST",description:"List the repositories linked to the organization",category:"Git"},{name:"REPOSITORY_SEARCH",description:"Search the repositories an account can reach on its provider",category:"Git"},{name:"REPOSITORY_LINK",description:"Link a repository to the organization",category:"Git"},{name:"REPOSITORY_SEARCH_BRANCHES",description:"Search a repository's branches by name substring, on either provider",category:"Git"},{name:"CHANGE_REQUEST_STATE",description:"Read a branch's change request with its CI runs, review state and comments",category:"Git"},{name:"CHANGE_REQUEST_LAST_MERGED",description:"Read the most recently merged change request into a base branch",category:"Git"},{name:"CHANGE_REQUEST_LIST_OPEN",description:"List a repository's open change requests",category:"Git"},{name:"CHANGE_REQUEST_CHECK_LOG",description:"Read one CI run's report for a change request",category:"Git"},{name:"CHANGE_REQUEST_OPEN",description:"Propose a branch onto another, reusing the branch's existing change request",category:"Git"},{name:"CHANGE_REQUEST_MERGE",description:"Land a change request, reporting why it could not merge",category:"Git"},{name:"REPOSITORY_UPDATE",description:"Change a linked repository's settings, such as its sandbox image",category:"Git"},{name:"REPOSITORY_DELETE",description:"Unlink a repository from the organization",category:"Git"},{name:"GLOBAL_SEARCH",description:"Search across organization resources (currently threads). Returns a typed union of matches.",category:"Search"},{name:"TASK_BOARD_ITEM_CREATE",description:"Create task board item",category:"Task Board"},{name:"TASK_BOARD_ITEM_LIST",description:"List task board items",category:"Task Board"},{name:"TASK_BOARD_ITEM_UPDATE",description:"Update task board item",category:"Task Board"},{name:"TASK_BOARD_ITEM_DELETE",description:"Delete task board item",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_AUTOMATION_LIST",description:"List what the board runs when a card lands in each column",category:"Task Board"},{name:"TASK_BOARD_AUTOMATION_UPSERT",description:"Run the agent on cards landing in a board column",category:"Task Board"},{name:"TASK_BOARD_AUTOMATION_DELETE",description:"Stop running the agent on cards landing in a board column",category:"Task Board"},{name:"TASK_BOARD_PROMPT_LIST",description:"List the instructions appended to the system prompt of the board's runs",category:"Task Board"},{name:"TASK_BOARD_PROMPT_UPSERT",description:"Set the instructions appended to the system prompt of the board's runs",category:"Task Board"},{name:"TASK_BOARD_PROMPT_DELETE",description:"Clear a board system prompt",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_ITEM_PRS_GET",description:"Get a task board item's linked pull requests with live state",category:"Task Board"},{name:"TASK_BOARD_PREVIEW_PROBE",description:"Check whether a pull request's deploy preview URL is currently reachable",category:"Task Board"},{name:"TASK_BOARD_ITEM_RERUN",description:"Re-run a task with the Super Agent, failing any run still holding it open",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_RUN_REVIEWER",description:"Run the Reviewer on a task even when the organization has automated review turned off",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_RESOLVE_CONFLICT",description:"Hand a task's conflicting pull request back to the Super Agent to resolve the merge conflict",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_REVIEW_DECISION",description:"Record a reviewer's decision (approve or request changes) for a task under review",category:"Task Board",dangerous:!0},{name:"TASK_BOARD_PROMOTE_TO_PRODUCTION",description:"Merge a reviewed task's pull request and move the task to Done",category:"Task Board",dangerous:!0},{name:"NOTIFICATION_LIST",description:"List your unread notifications in this organization",category:"Task Board"},{name:"NOTIFICATION_MARK_READ",description:"Mark your notifications read",category:"Task Board"},{name:"NOTIFICATION_SUBSCRIPTION_SET",description:"Follow or unfollow a task board item",category:"Task Board"},{name:"NOTIFICATION_SUBSCRIPTION_LIST",description:"List the users following a task board item",category:"Task Board"},{name:"TASK_BOARD_ACTIVITY_LIST",description:"List a task board item's change history",category:"Task Board"},{name:"TASK_BOARD_COMMENT_LIST",description:"List a task board item's comment threads",category:"Task Board"},{name:"TASK_BOARD_COMMENT_CREATE",description:"Post a comment or a reply on a task board item",category:"Task Board"},{name:"TASK_BOARD_COMMENT_UPDATE",description:"Edit a comment, or resolve/unresolve a comment thread",category:"Task Board"},{name:"TASK_BOARD_COMMENT_DELETE",description:"Delete a comment (a thread root takes its replies)",category:"Task Board"},{name:"TASK_BOARD_DISMISSED_LIST",description:"List Deco Score findings dismissed by deleting their task board cards",category:"Task Board"},{name:"TASK_BOARD_DISMISSED_RESTORE",description:"Un-dismiss Deco Score findings so the next Deco Score import pushes them again",category:"Task Board"},{name:"TASK_BOARD_ADMIN_ORG_LIST",description:"Whether the caller may read every org's task board, and the orgs that have board items",category:"Task Board"},{name:"TASK_BOARD_DELIVERY",description:"Task board throughput and flow \u2014 completions, PR rate, lead vs cycle time, dwell by lane",category:"Task Board"},{name:"TASK_BOARD_STUCK",description:"Task board work that is stuck right now, and WIP by age",category:"Task Board"},{name:"TASK_BOARD_COST",description:"Task board spend \u2014 total, per task, per shipped PR, and the coverage % behind those figures",category:"Task Board"},{name:"TASK_BOARD_QUALITY",description:"Task board quality \u2014 first-pass yield, rework, autonomy, abandonment, retry burn",category:"Task Board"},{name:"TASK_BOARD_ERRORS",description:"Task board run failures \u2014 counts, kinds, live error feed, error signatures, superseded runs",category:"Task Board"},{name:"TASK_BOARD_TENANTS",description:"Per-tenant task board scorecard and queue wait",category:"Task Board"},{name:"THREAD_ANALYTICS_ORG_LIST",description:"Whether the caller may read every org's threads, and the orgs that have any",category:"Threads"},{name:"THREAD_ANALYTICS_LIVE",description:"Recently active threads across orgs with status, owner and spend (admin orgs)",category:"Threads"},{name:"THREAD_ANALYTICS_USAGE",description:"Token and USD usage by org, user, agent and kind; top spenders (admin orgs)",category:"Threads"},{name:"THREAD_ANALYTICS_ERRORS",description:"Failed threads, error feed and error signatures across orgs (admin orgs)",category:"Threads"},{name:"TASK_ADD_REPO",description:"Clone an organization repository into the sandbox of the task run calling it",category:"Task Board"}],fQ0=[{id:"basic-usage",label:"Basic Usage",description:"Tools all org members can access by default",section:"Basic Usage",tools:["COLLECTION_CONNECTIONS_LIST","COLLECTION_CONNECTIONS_GET","CONNECTION_TEST","COLLECTION_VIRTUAL_MCP_LIST","COLLECTION_VIRTUAL_MCP_GET","VIRTUAL_MCP_LAST_USED_LIST","AUTOMATION_GET","AUTOMATION_LIST","AUTOMATION_RUN_STATS","AI_PROVIDERS_LIST","AI_PROVIDERS_LIST_MODELS","AI_PROVIDERS_ACTIVE","AI_PROVIDER_KEY_LIST","AI_PROVIDER_CREDITS","AI_PLAN_ENTITLEMENTS","AI_PLAN_LIST","ORGANIZATION_BILLING_PLAN_PRICES","AI_PROVIDER_TOPUP_URL","LIST_OBJECTS","GET_OBJECT_METADATA","GET_PRESIGNED_URL","PUT_PRESIGNED_URL","FILE_OBJECTS_LIST","ORG_REPO_SYNC_LIST","SANDBOX_START","SANDBOX_DELETE","REPOSITORY_SEARCH_BRANCHES","GIT_PROVIDER_CAPABILITIES","GIT_ACCOUNT_LIST","REPOSITORY_LIST","REPOSITORY_SEARCH","CHANGE_REQUEST_STATE","CHANGE_REQUEST_LAST_MERGED","CHANGE_REQUEST_LIST_OPEN","CHANGE_REQUEST_CHECK_LOG","GLOBAL_SEARCH","ORGANIZATION_SETTINGS_GET","USER_GET","BRAND_CONTEXT_LIST","ORGANIZATION_HAS_SITE","COLLECTION_THREADS_CREATE","COLLECTION_THREADS_LIST","COLLECTION_THREADS_GET","COLLECTION_THREADS_UPDATE","COLLECTION_THREADS_DELETE","COLLECTION_THREAD_MESSAGES_LIST","TASK_BOARD_ITEM_CREATE","TASK_BOARD_ITEM_LIST","TASK_BOARD_ITEM_UPDATE","TASK_BOARD_ITEM_DELETE","TASK_BOARD_AUTOMATION_LIST","TASK_BOARD_AUTOMATION_UPSERT","TASK_BOARD_AUTOMATION_DELETE","TASK_BOARD_PROMPT_LIST","TASK_BOARD_PROMPT_UPSERT","TASK_BOARD_PROMPT_DELETE","TASK_BOARD_ITEM_PRS_GET","TASK_BOARD_PREVIEW_PROBE","TASK_BOARD_ITEM_RERUN","TASK_BOARD_RUN_REVIEWER","TASK_BOARD_REVIEW_DECISION","TASK_BOARD_PROMOTE_TO_PRODUCTION","TASK_BOARD_ACTIVITY_LIST","TASK_BOARD_COMMENT_LIST","TASK_BOARD_COMMENT_CREATE","TASK_BOARD_COMMENT_UPDATE","TASK_BOARD_COMMENT_DELETE","TASK_BOARD_DISMISSED_LIST","TASK_BOARD_DISMISSED_RESTORE","TASK_BOARD_ADMIN_ORG_LIST","TASK_BOARD_DELIVERY","TASK_BOARD_STUCK","TASK_BOARD_COST","TASK_BOARD_QUALITY","TASK_BOARD_ERRORS","TASK_BOARD_TENANTS","THREAD_ANALYTICS_ORG_LIST","THREAD_ANALYTICS_LIVE","THREAD_ANALYTICS_USAGE","THREAD_ANALYTICS_ERRORS","NOTIFICATION_LIST","NOTIFICATION_MARK_READ","NOTIFICATION_SUBSCRIPTION_SET","NOTIFICATION_SUBSCRIPTION_LIST"]},{id:"org:manage",label:"Manage organization",description:"Edit organization settings, brand context, and domain configuration",section:"Organization",tools:["ORGANIZATION_GET","ORGANIZATION_LIST","ORGANIZATION_UPDATE","ORGANIZATION_SETTINGS_GET","ORGANIZATION_SETTINGS_UPDATE","BRAND_CONTEXT_LIST","BRAND_CONTEXT_GET","BRAND_CONTEXT_CREATE","BRAND_CONTEXT_UPDATE","BRAND_CONTEXT_DELETE","BRAND_CONTEXT_EXTRACT","BRAND_GET","BRAND_LIST","ORGANIZATION_DOMAIN_LIST","ORGANIZATION_DOMAIN_ADD","ORGANIZATION_DOMAIN_UPDATE","ORGANIZATION_DOMAIN_VERIFY","ORGANIZATION_DOMAIN_REMOVE","JIRA_INTEGRATION_GET","JIRA_INTEGRATION_UPSERT","JIRA_INTEGRATION_DELETE","JIRA_BOARDS_LIST","JIRA_BOARD_COLUMNS_LIST","JIRA_AUTOMATION_LIST","JIRA_AUTOMATION_UPSERT","JIRA_AUTOMATION_DELETE","JIRA_RUN_START"]},{id:"members:manage",label:"Manage members",description:"Invite members, remove them, and change their roles",section:"Organization",tools:["ORGANIZATION_MEMBER_LIST","ORGANIZATION_MEMBER_ADD","ORGANIZATION_MEMBER_REMOVE","ORGANIZATION_MEMBER_UPDATE_ROLE","ORGANIZATION_BILLING_CHECKOUT_START","ORGANIZATION_BILLING_PORTAL","ORGANIZATION_TASK_QUOTA_GET","INFRA_BILLING_SITES_LIST","INFRA_BILLING_GET","INFRA_BILLING_PORTAL","ORGANIZATION_JOIN_REQUEST_LIST","ORGANIZATION_JOIN_REQUEST_APPROVE","ORGANIZATION_JOIN_REQUEST_DENY"],dangerous:!0},{id:"connections:manage",label:"Manage connections",description:"Create, update, and delete connections",section:"Connections & Agents",tools:["COLLECTION_CONNECTIONS_CREATE","COLLECTION_CONNECTIONS_UPDATE","COLLECTION_CONNECTIONS_DELETE","REPORTS_SETUP","REPORTS_RUN","REPORTS_BIND","REPORTS_CONNECTION_STATUS","REPORTS_SET_REPOSITORY"],dangerous:!0},{id:"agents:manage",label:"Manage agents",description:"Create, configure, and delete agents",section:"Connections & Agents",tools:["COLLECTION_VIRTUAL_MCP_CREATE","COLLECTION_VIRTUAL_MCP_UPDATE","COLLECTION_VIRTUAL_MCP_DELETE","VIRTUAL_MCP_PINNED_VIEWS_UPDATE"],dangerous:!0},{id:"automations:manage",label:"Manage automations",description:"Create, update, run, and delete automations",section:"Automations",tools:["AUTOMATION_CREATE","AUTOMATION_UPDATE","AUTOMATION_DELETE","AUTOMATION_TRIGGER_ADD","AUTOMATION_TRIGGER_REMOVE","AUTOMATION_TRIGGER_ROTATE_TOKEN","AUTOMATION_RUN"],dangerous:!0},{id:"monitoring:view",label:"View monitoring",description:"Access logs and usage statistics",section:"Monitoring",tools:["MONITORING_HEATMAP","MONITORING_LOG_GET","MONITORING_LOGS_LIST","MONITORING_STATS","MONITORING_THREAD_USAGE"]},{id:"secrets:manage",label:"Manage secrets",description:"Create and list secrets stored in the credential vault",section:"Organization",tools:["SECRET_CREATE","SECRET_LIST"]},{id:"file-configs:manage",label:"Manage file configs",description:"Create, list, update and delete S3 bucket configurations and synced GitHub repositories",section:"Organization",tools:["FILE_CONFIG_CREATE","FILE_CONFIG_LIST","FILE_CONFIG_UPDATE","FILE_CONFIG_DELETE","FILE_OBJECTS_LIST","FILE_OBJECT_DELETE","ORG_REPO_SYNC_CREATE","ORG_REPO_SYNC_LIST","ORG_REPO_SYNC_UPDATE","ORG_REPO_SYNC_DELETE","ORG_REPO_SYNC_RUN"]},{id:"ai-providers:manage",label:"Manage AI providers",description:"Add or remove API keys and provision provider credentials",section:"AI Providers",tools:["AI_PROVIDER_KEY_CREATE","AI_PROVIDER_KEY_LIST","AI_PROVIDER_KEY_DELETE","AI_PROVIDER_KEY_UPDATE","AI_PROVIDER_KEY_PREVIEW","AI_PROVIDER_OAUTH_URL","AI_PROVIDER_OAUTH_EXCHANGE","AI_PROVIDER_PROVISION_KEY","AI_PROVIDER_TOPUP_URL","AI_PROVIDER_CREDITS","AI_PLAN_ENTITLEMENTS","AI_PLAN_LIST","AI_PLAN_SET","CLAUDE_SUBSCRIPTION_CONNECT","CLAUDE_SUBSCRIPTION_STATUS","CLAUDE_SUBSCRIPTION_DISCONNECT"]},{id:"tags:manage",label:"Manage tags",description:"Create, assign, and delete organization tags",section:"Organization",tools:["TAGS_LIST","TAGS_CREATE","TAGS_DELETE","MEMBER_TAGS_GET","MEMBER_TAGS_SET"]},{id:"experiments:manage",label:"Manage experiments",description:"Create, update, and delete A/B experiments, and view results",section:"Experiments",tools:["EXPERIMENT_LIST","EXPERIMENT_GET","EXPERIMENT_CREATE","EXPERIMENT_UPDATE","EXPERIMENT_DELETE","EXPERIMENT_RESULTS"],dangerous:!0},{id:"registry:manage",label:"Browse registry",description:"Browse the Deco MCP catalog",section:"Store & Registry",tools:["COLLECTION_REGISTRY_APP_LIST","COLLECTION_REGISTRY_APP_GET","COLLECTION_REGISTRY_APP_VERSIONS","COLLECTION_REGISTRY_APP_FILTERS","REGISTRY_ITEM_LIST","REGISTRY_ITEM_SEARCH","REGISTRY_ITEM_GET","REGISTRY_ITEM_VERSIONS","REGISTRY_ITEM_FILTERS"]},{id:"api-keys:manage",label:"Manage API keys",description:"Create, update, and revoke API keys",section:"Developer",tools:["API_KEY_CREATE","API_KEY_LIST","API_KEY_UPDATE","API_KEY_DELETE"]},{id:"storage:delete",label:"Delete from storage",description:"Permanently delete files from object storage",section:"Developer",tools:["DELETE_OBJECT","DELETE_OBJECTS"],dangerous:!0},{id:"connections:sql",label:"Run SQL queries",description:"Execute raw SQL against connected databases",section:"Developer",tools:["DATABASES_RUN_SQL"],dangerous:!0}],Lo1=new Set([...fQ0.find(($)=>$.id==="basic-usage")?.tools??[],"ORG_FS_READ","ORG_FS_WRITE"]),Aa8=["agents:manage","connections:manage"],yQ0=new Set(fQ0.filter(($)=>Aa8.includes($.id)).flatMap(($)=>$.tools))});function EZ($){if(!$)return!1;return $.split(",").some((Q)=>wo.includes(Q))}function gQ0($,Z){let Q=Array.isArray(Z)?Z:[Z];if(Q.length===0)return!1;let Y=$?$.split(","):[];if(Y.includes("owner"))return!0;if(Y.includes("admin"))return Q.every((X)=>X!=="owner");return!1}var Fu,wo;var GY=D(()=>{Fu=["owner","admin","user"],wo=["owner","admin"]});class OP{userId;toolName;boundAuth;role;connectionId;getToolMeta;organizationId;trustPublicPrefix;_granted=!1;constructor($,Z,Q,Y,X="self",J,G,W=!0){this.userId=$;this.toolName=Z;this.boundAuth=Q;this.role=Y;this.connectionId=X;this.getToolMeta=J;this.organizationId=G;this.trustPublicPrefix=W}setToolName($){this.toolName=$}setOrganizationId($){this.organizationId=$}getOrganizationId(){return this.organizationId}setRole($){this.role=$}getRole(){return this.role}grant(){this._granted=!0}async check(...$){if(this._granted)return;if(this.trustPublicPrefix&&(this.toolName?.startsWith("STUDIO_PUBLIC_")||this.toolName?.startsWith("MESH_PUBLIC_"))){this.grant();return}if(!this.userId&&!this.boundAuth){if(this.getToolMeta&&await this.isToolPublic()){this.grant();return}throw new LL("Authentication required. Please provide a valid OAuth token or API key.")}let Z=$.length>0?$:this.toolName?[this.toolName]:[];if(Z.length===0)throw new y7("No resources specified for access check");for(let Q of Z)if(await this.checkResource(Q)){this.grant();return}throw new y7(`Access denied to: ${Z.join(", ")}`)}async checkResource($){if(!this.userId&&!this.boundAuth)return!1;return this.boundAuth?.isApiKeyPrincipal?this.checkApiKeyAccess($):this.checkMemberAccess($)}async checkApiKeyAccess($){if(!this.boundAuth)return!1;return this.boundAuth.hasPermission({[this.connectionId]:[$]})}async checkMemberAccess($){if(this.userId&&this.role&&Lo1.has($))return!0;if(EZ(this.role))return!0;if(!this.boundAuth)return!1;return this.boundAuth.hasPermission({[this.connectionId]:[$]},{organizationId:this.organizationId,role:this.role})}async isToolPublic(){if(this.trustPublicPrefix&&(this.toolName?.startsWith("STUDIO_PUBLIC_")||this.toolName?.startsWith("MESH_PUBLIC_")))return!0;if(!this.getToolMeta)return!1;try{let $=await this.getToolMeta();if(!$)return!1;let Q=YF($)?.public_tool;return Q===!0||Q==="true"}catch{return!1}}granted(){return this._granted}}var LL,y7;var BK=D(()=>{Hu();GY();LL=class LL extends Error{constructor($){super($);this.name="UnauthorizedError"}};y7=class y7 extends Error{constructor($){super($);this.name="ForbiddenError"}}});function jo1($){let Z={};for(let Q of Object.keys($))Z[Q]=["*"];return Z}function P9($){let Z=$?.metadata;if(!Z)return!1;try{return(typeof Z==="string"?JSON.parse(Z):Z).archived===!0}catch{return!1}}var hQ0="Organization is archived";function cQ0($,Z){return $.get(uQ0[Z])??$.get(lQ0[Z])}function Si0($,Z,Q){$[uQ0[Z]]=Q,$[lQ0[Z]]=Q}var uQ0,lQ0;var Ci0=D(()=>{uQ0={token:"x-studio-token",client:"x-studio-client",properties:"x-studio-properties",runMetadata:"x-studio-run-metadata"},lQ0={token:"x-mesh-token",client:"x-mesh-client",properties:"x-mesh-properties",runMetadata:"x-mesh-run-metadata"}});import*as Eo1 from"zod/v3";import*as DP from"zod/v4-mini";function nX($){return!!$._zod}function LP($){let Z=Object.values($);if(Z.length===0)return DP.object({});let Q=Z.every(nX),Y=Z.every((X)=>!nX(X));if(Q)return DP.object($);if(Y)return Eo1.object($);throw Error("Mixed Zod versions detected in object shape.")}function YX($,Z){if(nX($))return DP.safeParse($,Z);return $.safeParse(Z)}async function mQ0($,Z){if(nX($))return await DP.safeParseAsync($,Z);return await $.safeParseAsync(Z)}function XF($){if(!$)return;let Z;if(nX($))Z=$._zod?.def?.shape;else Z=$.shape;if(!Z)return;if(typeof Z==="function")try{return Z()}catch{return}return Z}function Uu($){if(!$)return;if(typeof $==="object"){let Z=$,Q=$;if(!Z._def&&!Q._zod){let Y=Object.values($);if(Y.length>0&&Y.every((X)=>typeof X==="object"&&X!==null&&(X._def!==void 0||X._zod!==void 0||typeof X.parse==="function")))return LP($)}}if(nX($)){let Q=$._zod?.def;if(Q&&(Q.type==="object"||Q.shape!==void 0))return $}else if($.shape!==void 0)return $;return}function dQ0($){if($&&typeof $==="object"){if("message"in $&&typeof $.message==="string")return $.message;if("issues"in $&&Array.isArray($.issues)&&$.issues.length>0){let Z=$.issues[0];if(Z&&typeof Z==="object"&&"message"in Z)return String(Z.message)}try{return JSON.stringify($)}catch{return String($)}}return String($)}function zo1($){return $.description}function Po1($){if(nX($))return $._zod?.def?.type==="optional";let Z=$;if(typeof $.isOptional==="function")return $.isOptional();return Z._def?.typeName==="ZodOptional"}function iQ0($){if(nX($)){let J=$._zod?.def;if(J){if(J.value!==void 0)return J.value;if(Array.isArray(J.values)&&J.values.length>0)return J.values[0]}}let Q=$._def;if(Q){if(Q.value!==void 0)return Q.value;if(Array.isArray(Q.values)&&Q.values.length>0)return Q.values[0]}let Y=$.value;if(Y!==void 0)return Y;return}var Nu=()=>{};function wL($){return $==="completed"||$==="failed"||$==="cancelled"}var To1,Ao1,Ro1=($)=>typeof $==="string"?{...Ao1,name:$}:{...Ao1,...$};var pQ0=D(()=>{To1=Symbol("Let zodToJsonSchema decide on which parser to use"),Ao1={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"}});var qo1=($)=>{let Z=Ro1($),Q=Z.name!==void 0?[...Z.basePath,Z.definitionPath,Z.name]:Z.basePath;return{...Z,flags:{hasReferencedOpenAiAnyType:!1},currentPath:Q,propertyPath:void 0,seen:new Map(Object.entries(Z.definitions).map(([Y,X])=>[X._def,{def:X._def,path:[...Z.basePath,Z.definitionPath,Y],jsonSchema:void 0}]))}};var _i0=D(()=>{pQ0()});function vi0($,Z,Q,Y){if(!Y?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[Z]:Q}}function $6($,Z,Q,Y,X){$[Z]=Q,vi0($,Z,Y,X)}var nQ0=($,Z)=>{let Q=0;for(;Q<$.length&&Q<Z.length;Q++)if($[Q]!==Z[Q])break;return[($.length-Q).toString(),...Z.slice(Q)].join("/")};function A9($){if($.target!=="openAi")return{};let Z=[...$.basePath,$.definitionPath,$.openAiAnyTypeName];return $.flags.hasReferencedOpenAiAnyType=!0,{$ref:$.$refStrategy==="relative"?nQ0(Z,$.currentPath):Z.join("/")}}var g3=()=>{};import{ZodFirstPartyTypeKind as Ta8}from"zod/v3";function Mo1($,Z){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==Ta8.ZodAny)Q.items=L8($.type._def,{...Z,currentPath:[...Z.currentPath,"items"]});if($.minLength)$6(Q,"minItems",$.minLength.value,$.minLength.message,Z);if($.maxLength)$6(Q,"maxItems",$.maxLength.value,$.maxLength.message,Z);if($.exactLength)$6(Q,"minItems",$.exactLength.value,$.exactLength.message,Z),$6(Q,"maxItems",$.exactLength.value,$.exactLength.message,Z);return Q}var bi0=D(()=>{lZ()});function Io1($,Z){let Q={type:"integer",format:"int64"};if(!$.checks)return Q;for(let Y of $.checks)switch(Y.kind){case"min":if(Z.target==="jsonSchema7")if(Y.inclusive)$6(Q,"minimum",Y.value,Y.message,Z);else $6(Q,"exclusiveMinimum",Y.value,Y.message,Z);else{if(!Y.inclusive)Q.exclusiveMinimum=!0;$6(Q,"minimum",Y.value,Y.message,Z)}break;case"max":if(Z.target==="jsonSchema7")if(Y.inclusive)$6(Q,"maximum",Y.value,Y.message,Z);else $6(Q,"exclusiveMaximum",Y.value,Y.message,Z);else{if(!Y.inclusive)Q.exclusiveMaximum=!0;$6(Q,"maximum",Y.value,Y.message,Z)}break;case"multipleOf":$6(Q,"multipleOf",Y.value,Y.message,Z);break}return Q}var xi0=()=>{};function Vo1(){return{type:"boolean"}}function tQ0($,Z){return L8($.type._def,Z)}var oQ0=D(()=>{lZ()});var ko1=($,Z)=>{return L8($.innerType._def,Z)};var fi0=D(()=>{lZ()});function yi0($,Z,Q){let Y=Q??Z.dateStrategy;if(Array.isArray(Y))return{anyOf:Y.map((X,J)=>yi0($,Z,X))};switch(Y){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Ra8($,Z)}}var Ra8=($,Z)=>{let Q={type:"integer",format:"unix-time"};if(Z.target==="openApi3")return Q;for(let Y of $.checks)switch(Y.kind){case"min":$6(Q,"minimum",Y.value,Y.message,Z);break;case"max":$6(Q,"maximum",Y.value,Y.message,Z);break}return Q};var gi0=()=>{};function So1($,Z){return{...L8($.innerType._def,Z),default:$.defaultValue()}}var hi0=D(()=>{lZ()});function Co1($,Z){return Z.effectStrategy==="input"?L8($.schema._def,Z):A9(Z)}var ui0=D(()=>{lZ();g3()});function _o1($){return{type:"string",enum:Array.from($.values)}}function vo1($,Z){let Q=[L8($.left._def,{...Z,currentPath:[...Z.currentPath,"allOf","0"]}),L8($.right._def,{...Z,currentPath:[...Z.currentPath,"allOf","1"]})].filter((J)=>!!J),Y=Z.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,X=[];return Q.forEach((J)=>{if(qa8(J)){if(X.push(...J.allOf),J.unevaluatedProperties===void 0)Y=void 0}else{let G=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...K}=J;G=K}else Y=void 0;X.push(G)}}),X.length?{allOf:X,...Y}:void 0}var qa8=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};var li0=D(()=>{lZ()});function bo1($,Z){let Q=typeof $.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray($.value)?"array":"object"};if(Z.target==="openApi3")return{type:Q==="bigint"?"integer":Q,enum:[$.value]};return{type:Q==="bigint"?"integer":Q,const:$.value}}function rQ0($,Z){let Q={type:"string"};if($.checks)for(let Y of $.checks)switch(Y.kind){case"min":$6(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,Y.value):Y.value,Y.message,Z);break;case"max":$6(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,Y.value):Y.value,Y.message,Z);break;case"email":switch(Z.emailStrategy){case"format:email":DK(Q,"email",Y.message,Z);break;case"format:idn-email":DK(Q,"idn-email",Y.message,Z);break;case"pattern:zod":XX(Q,OK.email,Y.message,Z);break}break;case"url":DK(Q,"uri",Y.message,Z);break;case"uuid":DK(Q,"uuid",Y.message,Z);break;case"regex":XX(Q,Y.regex,Y.message,Z);break;case"cuid":XX(Q,OK.cuid,Y.message,Z);break;case"cuid2":XX(Q,OK.cuid2,Y.message,Z);break;case"startsWith":XX(Q,RegExp(`^${mi0(Y.value,Z)}`),Y.message,Z);break;case"endsWith":XX(Q,RegExp(`${mi0(Y.value,Z)}$`),Y.message,Z);break;case"datetime":DK(Q,"date-time",Y.message,Z);break;case"date":DK(Q,"date",Y.message,Z);break;case"time":DK(Q,"time",Y.message,Z);break;case"duration":DK(Q,"duration",Y.message,Z);break;case"length":$6(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,Y.value):Y.value,Y.message,Z),$6(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,Y.value):Y.value,Y.message,Z);break;case"includes":{XX(Q,RegExp(mi0(Y.value,Z)),Y.message,Z);break}case"ip":{if(Y.version!=="v6")DK(Q,"ipv4",Y.message,Z);if(Y.version!=="v4")DK(Q,"ipv6",Y.message,Z);break}case"base64url":XX(Q,OK.base64url,Y.message,Z);break;case"jwt":XX(Q,OK.jwt,Y.message,Z);break;case"cidr":{if(Y.version!=="v6")XX(Q,OK.ipv4Cidr,Y.message,Z);if(Y.version!=="v4")XX(Q,OK.ipv6Cidr,Y.message,Z);break}case"emoji":XX(Q,OK.emoji(),Y.message,Z);break;case"ulid":{XX(Q,OK.ulid,Y.message,Z);break}case"base64":{switch(Z.base64Strategy){case"format:binary":{DK(Q,"binary",Y.message,Z);break}case"contentEncoding:base64":{$6(Q,"contentEncoding","base64",Y.message,Z);break}case"pattern:zod":{XX(Q,OK.base64,Y.message,Z);break}}break}case"nanoid":XX(Q,OK.nanoid,Y.message,Z);case"toLowerCase":case"toUpperCase":case"trim":break;default:((X)=>{})(Y)}return Q}function mi0($,Z){return Z.patternStrategy==="escape"?Ia8($):$}function Ia8($){let Z="";for(let Q=0;Q<$.length;Q++){if(!Ma8.has($[Q]))Z+="\\";Z+=$[Q]}return Z}function DK($,Z,Q,Y){if($.format||$.anyOf?.some((X)=>X.format)){if(!$.anyOf)$.anyOf=[];if($.format){if($.anyOf.push({format:$.format,...$.errorMessage&&Y.errorMessages&&{errorMessage:{format:$.errorMessage.format}}}),delete $.format,$.errorMessage){if(delete $.errorMessage.format,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.anyOf.push({format:Z,...Q&&Y.errorMessages&&{errorMessage:{format:Q}}})}else $6($,"format",Z,Q,Y)}function XX($,Z,Q,Y){if($.pattern||$.allOf?.some((X)=>X.pattern)){if(!$.allOf)$.allOf=[];if($.pattern){if($.allOf.push({pattern:$.pattern,...$.errorMessage&&Y.errorMessages&&{errorMessage:{pattern:$.errorMessage.pattern}}}),delete $.pattern,$.errorMessage){if(delete $.errorMessage.pattern,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.allOf.push({pattern:xo1(Z,Y),...Q&&Y.errorMessages&&{errorMessage:{pattern:Q}}})}else $6($,"pattern",xo1(Z,Y),Q,Y)}function xo1($,Z){if(!Z.applyRegexFlags||!$.flags)return $.source;let Q={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},Y=Q.i?$.source.toLowerCase():$.source,X="",J=!1,G=!1,W=!1;for(let K=0;K<Y.length;K++){if(J){X+=Y[K],J=!1;continue}if(Q.i){if(G){if(Y[K].match(/[a-z]/)){if(W)X+=Y[K],X+=`${Y[K-2]}-${Y[K]}`.toUpperCase(),W=!1;else if(Y[K+1]==="-"&&Y[K+2]?.match(/[a-z]/))X+=Y[K],W=!0;else X+=`${Y[K]}${Y[K].toUpperCase()}`;continue}}else if(Y[K].match(/[a-z]/)){X+=`[${Y[K]}${Y[K].toUpperCase()}]`;continue}}if(Q.m){if(Y[K]==="^"){X+=`(^|(?<=[\r
|
|
447
447
|
]))`;continue}else if(Y[K]==="$"){X+=`($|(?=[\r
|
|
448
448
|
]))`;continue}}if(Q.s&&Y[K]==="."){X+=G?`${Y[K]}\r
|
|
449
449
|
`:`[${Y[K]}\r
|
|
@@ -1006,13 +1006,13 @@ ${G}
|
|
|
1006
1006
|
${Z}:`]}}function DG$($){switch($){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}function QL4($){return!("error"in $)&&$.choices.some((Z)=>Z.text.length>0)}function Sa0($){let Z=encodeURIComponent($);return Z==="."?"%252E":Z===".."?"%252E%252E":Z}function UL4($){return FL4.some((Z)=>$.startsWith(Z))}function NL4($){var Z;return(Z=HL4[$])!=null?Z:$.startsWith("gpt-image-")?10:1}function EG$($,Z,Q){if($==null)return{};let Y={};if($.image_tokens!=null){let X=Math.floor($.image_tokens/Q),J=$.image_tokens-X*(Q-1);Y.imageTokens=Z===Q-1?J:X}if($.text_tokens!=null){let X=Math.floor($.text_tokens/Q),J=$.text_tokens-X*(Q-1);Y.textTokens=Z===Q-1?J:X}return Y}async function LL4($,Z){if(!$)return;if($.type==="url")return hr($.url,{abortSignal:Z});let Q=$.data instanceof Uint8Array?$.data:_9($.data);return new Blob([Q],{type:$.mediaType})}function la0($){var Z,Q,Y,X,J,G;if($==null)return EF();let{input_tokens:W,output_tokens:K}=$,H=(Q=(Z=$.input_tokens_details)==null?void 0:Z.cached_tokens)!=null?Q:0,F=(X=(Y=$.input_tokens_details)==null?void 0:Y.cache_write_tokens)!=null?X:void 0,U=(G=(J=$.output_tokens_details)==null?void 0:J.reasoning_tokens)!=null?G:0;return{inputTokens:{total:W,noCache:W-H-(F!=null?F:0),cacheRead:H,cacheWrite:F},outputTokens:{total:K,text:K-U,reasoning:U},raw:$}}function Z30({finishReason:$,hasFunctionCall:Z}){switch($){case void 0:case null:return Z?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return Z?"tool-calls":"other"}}function Ow4($){if(typeof $.type!=="string"||!Nw4.has($.type))return!1;if($.type!=="response.output_item.added"&&$.type!=="response.output_item.done")return!0;if(!u7($.item)||typeof $.item.type!=="string")return!0;return Bw4.has($.item.type)}function Lw4($){if($.provider==null)throw Error("OpenAI model is missing provider after workflow deserialization.");return{...$,provider:$.provider,url:typeof $.url==="function"?$.url:({path:Z})=>{if($.baseURL==null)throw Error("OpenAI model is missing baseURL after workflow deserialization.");return`${$.baseURL}${Z}`},headers:typeof $.headers==="function"?$.headers:$.headers==null?void 0:()=>$.headers}}function ta0({providerOptions:$,providerOptionsName:Z}){var Q;let Y=(Q=$==null?void 0:$[Z])==null?void 0:Q.parallelToolCall;if(!i3(Y)||typeof Y.itemId!=="string"||typeof Y.toolCallId!=="string"||typeof Y.toolName!=="string"||typeof Y.input!=="string"||typeof Y.index!=="number"||!Number.isInteger(Y.index)||typeof Y.count!=="number"||!Number.isInteger(Y.count)||Y.index<0||Y.count<=Y.index)return;return Y}function oa0({toolName:$,tools:Z}){return $===PG$&&!Z.some((Q)=>Q.name===PG$)}async function TG$({toolCall:$,tools:Z,providerOptionsName:Q,itemId:Y}){if(!oa0({toolName:$.toolName,tools:Z}))return;let X=await P5({text:$.input});if(!X.success||!i3(X.value))return;let J=X.value.tool_uses;if(!Array.isArray(J)||J.length===0)return;let G=new Set(Z.map((K)=>K.name)),W=[];for(let[K,H]of J.entries()){if(!i3(H))return;let{recipient_name:F,parameters:U}=H;if(typeof F!=="string"||!F.startsWith(AG$)||!i3(U))return;let N=F.slice(AG$.length);if(N.length===0||!G.has(N))return;W.push({type:"tool-call",toolCallId:`${$.toolCallId}_${K}`,toolName:N,input:JSON.stringify(U),providerMetadata:{[Q]:{parallelToolCall:{itemId:Y,toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,index:K,count:J.length}}}})}return W}function ww4($){return JSON.stringify($===void 0?{}:$)}function RG$($){return $==null?void 0:$.type==="program"?{type:"program",caller_id:$.callerId}:$}async function qG$({output:$,toolName:Z,outputSchemaToolNames:Q,promptCacheBreakpoint:Y,providerOptionsName:X,warnings:J}){var G;let W=Q==null?void 0:Q.has(Z),K=(H)=>Y==null?H:[{type:"input_text",text:H,prompt_cache_breakpoint:Y}];switch($.type){case"text":case"error-text":return K(W?JSON.stringify($.value):$.value);case"execution-denied":{let H=(G=$.reason)!=null?G:"Tool call execution denied.";return K(W?JSON.stringify(H):H)}case"json":case"error-json":return K(JSON.stringify($.value));case"content":return $.value.map((H)=>{var F,U,N;let B=Dw(H.providerOptions,X);switch(H.type){case"text":return{type:"input_text",text:H.text,...B!=null&&{prompt_cache_breakpoint:B}};case"file":{let O=PQ(H.mediaType),L=(U=(F=H.providerOptions)==null?void 0:F[X])==null?void 0:U.imageDetail;if(H.data.type==="reference"){let w=AQ({reference:H.data.reference,provider:X});if(O==="image")return{type:"input_image",file_id:w,detail:L,...B!=null&&{prompt_cache_breakpoint:B}};return{type:"input_file",file_id:w,...B!=null&&{prompt_cache_breakpoint:B}}}if(H.data.type==="data"){let w=v9({part:H});if(O==="image")return{type:"input_image",image_url:`data:${w};base64,${X4(H.data.data)}`,detail:L,...B!=null&&{prompt_cache_breakpoint:B}};return{type:"input_file",filename:(N=H.filename)!=null?N:"data",file_data:`data:${w};base64,${X4(H.data.data)}`,...B!=null&&{prompt_cache_breakpoint:B}}}if(H.data.type==="url"){if(O==="image")return{type:"input_image",image_url:H.data.url.toString(),detail:L,...B!=null&&{prompt_cache_breakpoint:B}};return{type:"input_file",file_url:H.data.url.toString(),...B!=null&&{prompt_cache_breakpoint:B}}}J.push({type:"other",message:`unsupported tool content part type: ${H.type} with data type: ${H.data.type}`});return}default:{J.push({type:"other",message:`unsupported tool content part type: ${H.type}`});return}}}).filter(tL)}}function ra0($,Z){return $.itemId===Z.itemId&&$.toolCallId===Z.toolCallId&&$.toolName===Z.toolName&&$.input===Z.input&&$.count===Z.count}function jw4({prompt:$,providerOptionsName:Z}){let Q=new Map;for(let X of $){if(X.role!=="tool")continue;for(let J of X.content){if(J.type!=="tool-result")continue;let G=ta0({providerOptions:J.providerOptions,providerOptionsName:Z});if(G==null)continue;let W=Q.get(G.toolCallId);if(W==null){Q.set(G.toolCallId,{metadata:G,results:new Map([[G.index,J]]),invalid:!1});continue}if(!ra0(W.metadata,G)||W.results.has(G.index)){W.invalid=!0;continue}W.results.set(G.index,J)}}let Y=new Map;for(let[X,J]of Q){if(J.invalid||J.results.size!==J.metadata.count)continue;let G=Array.from({length:J.metadata.count},(W,K)=>J.results.get(K));if(G.every(tL))Y.set(X,{metadata:J.metadata,results:G})}return Y}function Dw($,Z){var Q;return(Q=$==null?void 0:$[Z])==null?void 0:Q.promptCacheBreakpoint}function va0({output:$,toolResultProviderOptions:Z,providerOptionsName:Q}){var Y;return $.type==="content"?void 0:(Y=Dw($.providerOptions,Q))!=null?Y:Dw(Z,Q)}function MG$($,Z){if(!Z)return!1;return Z.some((Q)=>$.startsWith(Q))}async function Ew4({prompt:$,toolNameMapping:Z,systemMessageMode:Q,providerOptionsName:Y,explicitMessageItemType:X=!1,fileIdPrefixes:J,passThroughUnsupportedFiles:G=!1,store:W,hasConversation:K=!1,hasPreviousResponseId:H=!1,hasLocalShellTool:F=!1,hasShellTool:U=!1,hasApplyPatchTool:N=!1,hasComputerTool:B=!1,toolSearchToolName:O,customProviderToolNames:L,outputSchemaToolNames:w}){var j,E,z,T,P,A,q,x,_,V,y,g,l,n,p,F0,V0,G0,H0,X0,Z0,Y0,o,J0,c0,k0,j1,d0,L0,j0,a0,P1,K1,v0,l0,Q0,w0,e,i,m0,I0,t0;let f0=[],I1=[],H8=new Set,B8=new Set,m4=K||H?jw4({prompt:$,providerOptionsName:Y}):new Map,Q8=new Set,D5=new Set;for(let{role:x8,content:m6,providerOptions:O9}of $)switch(x8){case"system":{switch(Q){case"system":{let o0=Dw(O9,Y);f0.push({...X&&{type:"message"},role:"system",content:o0==null?m6:[{type:"input_text",text:m6,prompt_cache_breakpoint:o0}]});break}case"developer":{let o0=Dw(O9,Y);f0.push({...X&&{type:"message"},role:"developer",content:o0==null?m6:[{type:"input_text",text:m6,prompt_cache_breakpoint:o0}]});break}case"remove":{I1.push({type:"other",message:"system messages are removed for this model"});break}default:throw Error(`Unsupported system message mode: ${Q}`)}break}case"user":{f0.push({...X&&{type:"message"},role:"user",content:m6.map((o0,D1)=>{var x$,h1,Y$,_8,r6;switch(o0.type){case"text":{let G4=Dw(o0.providerOptions,Y);return{type:"input_text",text:o0.text,...G4!=null&&{prompt_cache_breakpoint:G4}}}case"file":{let G4=Dw(o0.providerOptions,Y);switch(o0.data.type){case"reference":{let a1=AQ({reference:o0.data.reference,provider:Y});if(PQ(o0.mediaType)==="image")return{type:"input_image",file_id:a1,detail:(h1=(x$=o0.providerOptions)==null?void 0:x$[Y])==null?void 0:h1.imageDetail,...G4!=null&&{prompt_cache_breakpoint:G4}};return{type:"input_file",file_id:a1,...G4!=null&&{prompt_cache_breakpoint:G4}}}case"text":throw new t1({functionality:"text file parts"});case"url":case"data":if(PQ(o0.mediaType)==="image")return{type:"input_image",...o0.data.type==="url"?{image_url:o0.data.url.toString()}:typeof o0.data.data==="string"&&MG$(o0.data.data,J)?{file_id:o0.data.data}:{image_url:`data:${v9({part:o0})};base64,${X4(o0.data.data)}`},detail:(_8=(Y$=o0.providerOptions)==null?void 0:Y$[Y])==null?void 0:_8.imageDetail,...G4!=null&&{prompt_cache_breakpoint:G4}};else{if(o0.data.type==="url")return{type:"input_file",file_url:o0.data.url.toString(),...G4!=null&&{prompt_cache_breakpoint:G4}};let T8=v9({part:o0});if(T8!=="application/pdf"&&!G)throw new t1({functionality:`file part media type ${T8}`});return{type:"input_file",...typeof o0.data.data==="string"&&MG$(o0.data.data,J)?{file_id:o0.data.data}:{filename:(r6=o0.filename)!=null?r6:T8==="application/pdf"?`part-${D1}.pdf`:`part-${D1}`,file_data:`data:${T8};base64,${X4(o0.data.data)}`},...G4!=null&&{prompt_cache_breakpoint:G4}}}}}}})});break}case"assistant":{let o0={};for(let D1 of m6)switch(D1.type){case"text":{let x$=(j=D1.providerOptions)==null?void 0:j[Y],h1=x$==null?void 0:x$.itemId,Y$=x$==null?void 0:x$.phase;if(K&&h1!=null)break;if(W&&h1!=null){f0.push({type:"item_reference",id:h1});break}f0.push({...X&&{type:"message"},role:"assistant",content:D1.text,...Y$!=null&&{phase:Y$}});break}case"tool-call":{let x$=ta0({providerOptions:D1.providerOptions,providerOptionsName:Y}),h1=x$==null?void 0:m4.get(x$.toolCallId);if(x$!=null&&h1!=null&&ra0(h1.metadata,x$)){if(!Q8.has(h1.metadata.toolCallId)){if(Q8.add(h1.metadata.toolCallId),!K)f0.push({type:"function_call",call_id:h1.metadata.toolCallId,name:h1.metadata.toolName,arguments:h1.metadata.input})}break}let Y$=(A=(z=(E=D1.providerOptions)==null?void 0:E[Y])==null?void 0:z.itemId)!=null?A:(P=(T=D1.providerMetadata)==null?void 0:T[Y])==null?void 0:P.itemId,_8=(y=(x=(q=D1.providerOptions)==null?void 0:q[Y])==null?void 0:x.namespace)!=null?y:(V=(_=D1.providerMetadata)==null?void 0:_[Y])==null?void 0:V.namespace,r6=(F0=(l=(g=D1.providerOptions)==null?void 0:g[Y])==null?void 0:l.async)!=null?F0:(p=(n=D1.providerMetadata)==null?void 0:n[Y])==null?void 0:p.async,G4=(G0=(V0=D1.providerOptions)==null?void 0:V0[Y])==null?void 0:G0.caller;if((G4==null?void 0:G4.type)==="program")B8.add(D1.toolCallId);if(K&&Y$!=null)break;let a1=Z.toProviderToolName(D1.toolName);if(D1.toolName===O){if(W&&Y$!=null){f0.push({type:"item_reference",id:Y$});break}let n$=typeof D1.input==="string"?await br({text:D1.input,schema:ga0}):await $8({value:D1.input,schema:ga0}),W$=n$.call_id!=null?"client":"server";f0.push({type:"tool_search_call",id:Y$!=null?Y$:D1.toolCallId,execution:W$,call_id:(H0=n$.call_id)!=null?H0:null,status:"completed",arguments:n$.arguments});break}if(a1==="programmatic_tool_calling"){if(W&&Y$!=null){f0.push({type:"item_reference",id:Y$});break}let n$=await $8({value:D1.input,schema:Z3$});f0.push({type:"program",id:Y$!=null?Y$:D1.toolCallId,call_id:D1.toolCallId,code:n$.code,fingerprint:n$.fingerprint});break}if(D1.providerExecuted){if(W&&Y$!=null)f0.push({type:"item_reference",id:Y$});if(W||!U||a1!=="shell")break}let T8=F&&a1==="local_shell"||U&&a1==="shell"||N&&a1==="apply_patch"||B&&a1==="computer"||((X0=L==null?void 0:L.has(a1))!=null?X0:!1);if(H&&W&&Y$!=null&&T8)break;if(W&&Y$!=null&&T8){f0.push({type:"item_reference",id:Y$});break}if(F&&a1==="local_shell"){let n$=await $8({value:D1.input,schema:aG$});f0.push({type:"local_shell_call",call_id:D1.toolCallId,id:Y$,action:{type:"exec",command:n$.action.command,timeout_ms:n$.action.timeoutMs,user:n$.action.user,working_directory:n$.action.workingDirectory,env:n$.action.env}});break}if(U&&a1==="shell"){let n$=await $8({value:D1.input,schema:$3$});f0.push({type:"shell_call",call_id:D1.toolCallId,id:Y$,status:"completed",action:{commands:n$.action.commands,timeout_ms:n$.action.timeoutMs,max_output_length:n$.action.maxOutputLength}});break}if(N&&a1==="apply_patch"){let n$=await $8({value:D1.input,schema:iG$});f0.push({type:"apply_patch_call",call_id:n$.callId,id:Y$,status:"completed",operation:n$.operation});break}if(B&&a1==="computer"){let n$=await $8({value:D1.input,schema:tG$});f0.push({type:"computer_call",call_id:D1.toolCallId,id:Y$,status:n$.status,actions:n$.actions.map((W$)=>{switch(W$.type){case"click":case"double_click":case"move":return{...W$,keys:W$.keys};case"drag":return{...W$,keys:W$.keys};case"scroll":return{type:"scroll",x:W$.x,y:W$.y,scroll_x:W$.scrollX,scroll_y:W$.scrollY,keys:W$.keys};default:return W$}}),pending_safety_checks:n$.pendingSafetyChecks.map((W$)=>({id:W$.id,code:W$.code,message:W$.message}))});break}if(L==null?void 0:L.has(a1)){f0.push({type:"custom_tool_call",call_id:D1.toolCallId,name:a1,input:typeof D1.input==="string"?D1.input:JSON.stringify(D1.input),...r6!=null&&{async:r6},id:Y$});break}f0.push({type:"function_call",call_id:D1.toolCallId,name:a1,arguments:ww4(D1.input),...r6!=null&&{async:r6},..._8!=null&&{namespace:_8},...G4!=null&&{caller:RG$(G4)}});break}case"tool-result":{if(D1.output.type==="execution-denied"||D1.output.type==="json"&&typeof D1.output.value==="object"&&D1.output.value!=null&&"type"in D1.output.value&&D1.output.value.type==="execution-denied")break;if(K)break;let x$=Z.toProviderToolName(D1.toolName);if(D1.toolName===O){let h1=(k0=(c0=(Y0=(Z0=D1.providerOptions)==null?void 0:Z0[Y])==null?void 0:Y0.itemId)!=null?c0:(J0=(o=D1.providerMetadata)==null?void 0:o[Y])==null?void 0:J0.itemId)!=null?k0:D1.toolCallId;if(W)f0.push({type:"item_reference",id:h1});else if(D1.output.type==="json"){let Y$=await $8({value:D1.output.value,schema:ha0});f0.push({type:"tool_search_output",id:h1,execution:"server",call_id:null,status:"completed",tools:Y$.tools})}break}if(x$==="programmatic_tool_calling"){let h1=(P1=(a0=(d0=(j1=D1.providerOptions)==null?void 0:j1[Y])==null?void 0:d0.itemId)!=null?a0:(j0=(L0=D1.providerMetadata)==null?void 0:L0[Y])==null?void 0:j0.itemId)!=null?P1:D1.toolCallId;if(W)f0.push({type:"item_reference",id:h1});else if(D1.output.type==="json"){let Y$=await $8({value:D1.output.value,schema:Q3$});f0.push({type:"program_output",id:h1,call_id:D1.toolCallId,result:Y$.result,status:Y$.status})}break}if(U&&x$==="shell"){if(D1.output.type==="json"){let h1=await $8({value:D1.output.value,schema:ya0});f0.push({type:"shell_call_output",call_id:D1.toolCallId,output:h1.output.map((Y$)=>({stdout:Y$.stdout,stderr:Y$.stderr,outcome:Y$.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:Y$.outcome.exitCode}}))})}break}if(W){let h1=(l0=(v0=(K1=D1.providerOptions)==null?void 0:K1[Y])==null?void 0:v0.itemId)!=null?l0:D1.toolCallId;f0.push({type:"item_reference",id:h1})}else I1.push({type:"other",message:`Results for OpenAI tool ${D1.toolName} are not sent to the API when store is false`});break}case"reasoning":{let x$=await I$({provider:Y,providerOptions:D1.providerOptions,schema:zw4}),h1=x$==null?void 0:x$.itemId;if((K||H)&&h1!=null)break;if(h1!=null){let Y$=o0[h1];if(W){if(Y$===void 0)f0.push({type:"item_reference",id:h1}),o0[h1]={type:"reasoning",id:h1,summary:[]}}else{let _8=[];if(D1.text.length>0)_8.push({type:"summary_text",text:D1.text});else if(Y$!==void 0)I1.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(D1)}.`});if(Y$===void 0)o0[h1]={type:"reasoning",id:h1,encrypted_content:x$==null?void 0:x$.reasoningEncryptedContent,summary:_8},f0.push(o0[h1]);else if(Y$.summary.push(..._8),(x$==null?void 0:x$.reasoningEncryptedContent)!=null)Y$.encrypted_content=x$.reasoningEncryptedContent}}else{let Y$=x$==null?void 0:x$.reasoningEncryptedContent;if(Y$!=null){let _8=[];if(D1.text.length>0)_8.push({type:"summary_text",text:D1.text});f0.push({type:"reasoning",encrypted_content:Y$,summary:_8})}else I1.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(D1)}.`})}break}case"custom":{if(D1.kind==="openai.compaction"){let x$=(Q0=D1.providerOptions)==null?void 0:Q0[Y],h1=x$==null?void 0:x$.itemId;if(K&&h1!=null)break;if(W&&h1!=null){f0.push({type:"item_reference",id:h1});break}let Y$=x$==null?void 0:x$.encryptedContent;if(h1!=null)f0.push({type:"compaction",id:h1,encrypted_content:Y$})}break}}break}case"tool":{for(let o0 of m6){if(o0.type==="tool-approval-response"){let a1=o0;if(H8.has(a1.approvalId))continue;if(H8.add(a1.approvalId),W&&!K&&!H)f0.push({type:"item_reference",id:a1.approvalId});f0.push({type:"mcp_approval_response",approval_request_id:a1.approvalId,approve:a1.approved});continue}let D1=ta0({providerOptions:o0.providerOptions,providerOptionsName:Y}),x$=D1==null?void 0:m4.get(D1.toolCallId);if(D1!=null&&x$!=null&&ra0(x$.metadata,D1)){if(!D5.has(x$.metadata.toolCallId)){D5.add(x$.metadata.toolCallId);let a1=await Promise.all(x$.results.map(async(W$)=>{let Q9=va0({output:W$.output,toolResultProviderOptions:W$.providerOptions,providerOptionsName:Y});return{output:await qG$({output:W$.output,toolName:W$.toolName,outputSchemaToolNames:w,providerOptionsName:Y,warnings:I1}),promptCacheBreakpoint:Q9}})),T8=a1.map(({output:W$})=>typeof W$==="string"?W$:JSON.stringify(W$)),n$=a1.some(({promptCacheBreakpoint:W$})=>W$!=null);f0.push({type:"function_call_output",call_id:x$.metadata.toolCallId,output:n$?T8.map((W$,Q9)=>({type:"input_text",text:Q9===0?W$:`
|
|
1007
1007
|
${W$}`,...a1[Q9].promptCacheBreakpoint!=null&&{prompt_cache_breakpoint:a1[Q9].promptCacheBreakpoint}})):T8.join(`
|
|
1008
1008
|
`)})}continue}let h1=o0.output;if(h1.type==="execution-denied"){if((e=(w0=h1.providerOptions)==null?void 0:w0.openai)==null?void 0:e.approvalId)continue}let Y$=Z.toProviderToolName(o0.toolName);if(o0.toolName===O&&h1.type==="json"){let a1=await $8({value:h1.value,schema:ha0});f0.push({type:"tool_search_output",execution:"client",call_id:o0.toolCallId,status:"completed",tools:a1.tools});continue}if(F&&Y$==="local_shell"&&h1.type==="json"){let a1=await $8({value:h1.value,schema:eG$});f0.push({type:"local_shell_call_output",call_id:o0.toolCallId,output:a1.output});continue}if(U&&Y$==="shell"&&h1.type==="json"){let a1=await $8({value:h1.value,schema:ya0});f0.push({type:"shell_call_output",call_id:o0.toolCallId,output:a1.output.map((T8)=>({stdout:T8.stdout,stderr:T8.stderr,outcome:T8.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:T8.outcome.exitCode}}))});continue}if(N&&o0.toolName==="apply_patch"&&h1.type==="json"){let a1=await $8({value:h1.value,schema:pG$});f0.push({type:"apply_patch_call_output",call_id:o0.toolCallId,status:a1.status,output:a1.output});continue}if(B&&Y$==="computer"&&h1.type==="json"){let a1=await $8({value:h1.value,schema:oG$});f0.push({type:"computer_call_output",call_id:o0.toolCallId,output:{type:"computer_screenshot",image_url:a1.output.imageUrl,file_id:a1.output.fileId,detail:a1.output.detail},acknowledged_safety_checks:(i=a1.acknowledgedSafetyChecks)==null?void 0:i.map((T8)=>({id:T8.id,code:T8.code,message:T8.message}))});continue}if(L==null?void 0:L.has(Y$)){let a1=va0({output:h1,toolResultProviderOptions:o0.providerOptions,providerOptionsName:Y}),T8=(W$)=>a1==null?W$:[{type:"input_text",text:W$,prompt_cache_breakpoint:a1}],n$;switch(h1.type){case"text":case"error-text":n$=T8(h1.value);break;case"execution-denied":n$=T8((m0=h1.reason)!=null?m0:"Tool call execution denied.");break;case"json":case"error-json":n$=T8(JSON.stringify(h1.value));break;case"content":n$=h1.value.map((W$)=>{var Q9,ZQ,OZ;let $0=Dw(W$.providerOptions,Y);switch(W$.type){case"text":return{type:"input_text",text:W$.text,...$0!=null&&{prompt_cache_breakpoint:$0}};case"file":{let M0=PQ(W$.mediaType),R1=(ZQ=(Q9=W$.providerOptions)==null?void 0:Q9[Y])==null?void 0:ZQ.imageDetail;if(W$.data.type==="data"){let f8=v9({part:W$});if(M0==="image")return{type:"input_image",image_url:`data:${f8};base64,${X4(W$.data.data)}`,detail:R1,...$0!=null&&{prompt_cache_breakpoint:$0}};return{type:"input_file",filename:(OZ=W$.filename)!=null?OZ:"data",file_data:`data:${f8};base64,${X4(W$.data.data)}`,...$0!=null&&{prompt_cache_breakpoint:$0}}}if(W$.data.type==="url"){if(M0==="image")return{type:"input_image",image_url:W$.data.url.toString(),detail:R1,...$0!=null&&{prompt_cache_breakpoint:$0}};return{type:"input_file",file_url:W$.data.url.toString(),...$0!=null&&{prompt_cache_breakpoint:$0}}}I1.push({type:"other",message:`unsupported custom tool content part type: ${W$.type} with data type: ${W$.data.type}`});return}default:I1.push({type:"other",message:`unsupported custom tool content part type: ${W$.type}`});return}}).filter(tL);break;default:n$=""}f0.push({type:"custom_tool_call_output",call_id:o0.toolCallId,output:n$});continue}let _8=(t0=(I0=o0.providerOptions)==null?void 0:I0[Y])==null?void 0:t0.caller;if(h1.type==="execution-denied"&&((_8==null?void 0:_8.type)==="program"||B8.has(o0.toolCallId)))throw new t1({functionality:"execution-denied results for programmatic tool calls"});let r6=await qG$({output:h1,toolName:o0.toolName,outputSchemaToolNames:w,promptCacheBreakpoint:va0({output:h1,toolResultProviderOptions:o0.providerOptions,providerOptionsName:Y}),providerOptionsName:Y,warnings:I1}),G4=RG$(_8);f0.push({type:"function_call_output",call_id:o0.toolCallId,output:r6,...G4!=null&&{caller:G4}})}break}default:throw Error(`Unsupported role: ${x8}`)}if(!W&&f0.some((x8)=>("type"in x8)&&x8.type==="reasoning"&&x8.encrypted_content==null))I1.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),f0=f0.filter((x8)=>!("type"in x8)||x8.type!=="reasoning"||x8.encrypted_content!=null);return{input:f0,warnings:I1}}async function Aw4({tools:$,toolChoice:Z,allowedTools:Q,toolNameMapping:Y,customProviderToolNames:X,outputSchemaToolNames:J,supportsAsyncToolCalling:G=!0}){var W,K,H,F;$=($==null?void 0:$.length)?$:void 0;let U=[];if($==null)return{tools:void 0,toolChoice:void 0,toolWarnings:U};let N=[],B=new Map,O=X!=null?X:new Set,L=new Map,w=new Map,j=(z,T,P)=>{if(L.set(z,T),P==null||P===z)return;let A=w.get(P);if(A==null)w.set(P,T);else if(A!=="ambiguous"&&!Tw4(A,T))w.set(P,"ambiguous")};for(let z of $)switch(z.type){case"function":{let T=(W=z.providerOptions)==null?void 0:W.openai;if((T==null?void 0:T.outputSchema)!=null)J==null||J.add(z.name);let P=qw4({tool:z,options:T,toolWarnings:U,async:kG$({value:T==null?void 0:T.async,supportsAsyncToolCalling:G,toolName:z.name,toolWarnings:U})}),A=T==null?void 0:T.namespace;if(A==null)N.push(P);else{let q=B.get(A.name);if(q==null)q={type:"namespace",name:A.name,description:A.description,tools:[]},B.set(A.name,q),N.push(q);else if(q.description!==A.description)throw new t1({functionality:`conflicting descriptions for OpenAI tool namespace "${A.name}"`});q.tools.push(P)}j(z.name,A!=null?{supported:!1,reason:"tools inside an OpenAI tool namespace are not visible to tool_choice.allowed_tools"}:(T==null?void 0:T.deferLoading)===!0?{supported:!1,reason:"deferred tools are not visible to tool_choice.allowed_tools"}:{supported:!0,entry:{type:"function",name:z.name}},void 0);break}case"provider":{let T=N.length;switch(z.id){case"openai.file_search":{let P=await $8({value:z.args,schema:CL4});N.push({type:"file_search",vector_store_ids:P.vectorStoreIds,max_num_results:P.maxNumResults,ranking_options:P.ranking?{ranker:P.ranking.ranker,score_threshold:P.ranking.scoreThreshold}:void 0,filters:P.filters});break}case"openai.local_shell":{N.push({type:"local_shell"});break}case"openai.shell":{let P=await $8({value:z.args,schema:lL4});N.push({type:"shell",...P.environment&&{environment:Mw4(P.environment)}});break}case"openai.apply_patch":{N.push({type:"apply_patch"});break}case"openai.computer":{N.push({type:"computer"});break}case"openai.web_search_preview":{let P=await $8({value:z.args,schema:sL4});N.push({type:"web_search_preview",search_context_size:P.searchContextSize,user_location:P.userLocation});break}case"openai.web_search":{let P=await $8({value:z.args,schema:pL4});N.push({type:"web_search",filters:P.filters!=null?{allowed_domains:P.filters.allowedDomains,blocked_domains:P.filters.blockedDomains}:void 0,external_web_access:P.externalWebAccess,search_context_size:P.searchContextSize,user_location:P.userLocation});break}case"openai.code_interpreter":{let P=await $8({value:z.args,schema:PL4});N.push({type:"code_interpreter",container:P.container==null?{type:"auto",file_ids:void 0}:typeof P.container==="string"?P.container:{type:"auto",file_ids:P.container.fileIds}});break}case"openai.image_generation":{let P=await $8({value:z.args,schema:bL4});N.push({type:"image_generation",action:P.action,background:P.background,input_fidelity:P.inputFidelity,input_image_mask:P.inputImageMask?{file_id:P.inputImageMask.fileId,image_url:P.inputImageMask.imageUrl}:void 0,model:P.model,moderation:P.moderation,partial_images:P.partialImages,quality:P.quality,output_compression:P.outputCompression,output_format:P.outputFormat,size:P.size});break}case"openai.mcp":{let P=await $8({value:z.args,schema:Zw4}),A=(_)=>({tool_names:_.toolNames}),q=P.requireApproval,x=q==null?void 0:typeof q==="string"?q:q.never!=null?{never:A(q.never)}:void 0;N.push({type:"mcp",server_label:P.serverLabel,allowed_tools:Array.isArray(P.allowedTools)?P.allowedTools:P.allowedTools?{read_only:P.allowedTools.readOnly,tool_names:P.allowedTools.toolNames}:void 0,authorization:P.authorization,connector_id:P.connectorId,headers:P.headers,require_approval:x!=null?x:"never",server_description:P.serverDescription,server_url:P.serverUrl});break}case"openai.custom":{let P=await $8({value:z.args,schema:IL4});N.push({type:"custom",name:z.name,description:P.description,...kG$({value:P.async,supportsAsyncToolCalling:G,toolName:z.name,toolWarnings:U})!=null?{async:P.async}:{},format:P.format}),O.add(z.name);break}case"openai.programmatic_tool_calling":{N.push({type:"programmatic_tool_calling"});break}case"openai.tool_search":{let P=await $8({value:z.args,schema:mL4});N.push({type:"tool_search",...P.execution!=null?{execution:P.execution}:{},...P.description!=null?{description:P.description}:{},...P.parameters!=null?{parameters:P.parameters}:{}});break}}if(N.length>T){let P=N[T];j(z.name,Rw4(P),Y==null?void 0:Y.toProviderToolName(z.name))}break}default:U.push({type:"unsupported",feature:`function tool ${z}`});break}if(Q!=null){let z=[],T=[];for(let P of Q.toolNames){let A=L.get(P),q=A!=null?A:w.get(P);if(A!=null&&w.has(P))U.push({type:"unsupported",feature:`allowedTools entry "${P}"`,details:"this name is both a tool name and the provider tool name of another tool in this request; the tool with this name is allowed"});if(q==="ambiguous"){U.push({type:"unsupported",feature:`allowedTools entry "${P}"`,details:"several tools in this request share this provider tool name; use the tool name from the tools for this request instead"}),T.push(P);continue}if(q==null){U.push({type:"unsupported",feature:`allowedTools entry "${P}"`,details:"the tool is not part of the tools for this request and is sent as a function tool"}),z.push({type:"function",name:(K=Y==null?void 0:Y.toProviderToolName(P))!=null?K:P});continue}if(!q.supported){U.push({type:"unsupported",feature:`allowedTools entry "${P}"`,details:`${q.reason}; the tool is removed from the allowed tools`}),T.push(P);continue}z.push(q.entry)}if(z.length===0)throw new t1({functionality:`allowedTools with only tools that cannot be allow-listed (${T.join(", ")})`});return{tools:N,toolChoice:{type:"allowed_tools",mode:(H=Q.mode)!=null?H:"auto",tools:z},toolWarnings:U}}if(Z==null)return{tools:N,toolChoice:void 0,toolWarnings:U};let E=Z.type;switch(E){case"auto":case"none":case"required":return{tools:N,toolChoice:E,toolWarnings:U};case"tool":{let z=(F=Y==null?void 0:Y.toProviderToolName(Z.toolName))!=null?F:Z.toolName;return{tools:N,toolChoice:z==="code_interpreter"||z==="file_search"||z==="image_generation"||z==="web_search_preview"||z==="web_search"||z==="mcp"||z==="apply_patch"||z==="computer"||z==="programmatic_tool_calling"?{type:z}:O.has(z)?{type:"custom",name:z}:{type:"function",name:z},toolWarnings:U}}default:throw new t1({functionality:`tool choice type: ${E}`})}}function VG$($){switch($.type){case"mcp":return`mcp:${$.server_label}`;case"function":case"custom":return`${$.type}:${$.name}`;default:return $.type}}function Tw4($,Z){if($.supported&&Z.supported)return VG$($.entry)===VG$(Z.entry);if(!$.supported&&!Z.supported)return $.reason===Z.reason;return!1}function Rw4($){switch($.type){case"custom":return{supported:!0,entry:{type:"custom",name:$.name}};case"mcp":return{supported:!0,entry:{type:"mcp",server_label:$.server_label}};case"file_search":case"web_search":case"web_search_preview":case"image_generation":case"code_interpreter":case"computer":case"apply_patch":case"shell":case"local_shell":case"programmatic_tool_calling":return{supported:!0,entry:{type:$.type}};default:return{supported:!1,reason:`OpenAI does not support ${$.type} tools in tool_choice.allowed_tools`}}}function qw4({tool:$,options:Z,toolWarnings:Q,async:Y}){var X;let J=Z==null?void 0:Z.deferLoading,G=Fa($.inputSchema),W=(Z==null?void 0:Z.outputSchema)!=null?Fa(Z.outputSchema):void 0;return Q.push(...G.warnings,...(X=W==null?void 0:W.warnings)!=null?X:[]),{type:"function",name:$.name,description:$.description,parameters:G.schema,...Y!=null?{async:Y}:{},...$.strict!=null?{strict:$.strict}:{},...J!=null?{defer_loading:J}:{},...(Z==null?void 0:Z.allowedCallers)!=null?{allowed_callers:Z.allowedCallers}:{},...(Z==null?void 0:Z.outputSchema)!=null?{output_schema:W==null?void 0:W.schema}:{}}}function kG$({value:$,supportsAsyncToolCalling:Z,toolName:Q,toolWarnings:Y}){if($!==!0||Z)return $;Y.push({type:"unsupported",feature:`async tool calling for "${Q}"`,details:"Async tool calling is only supported by GPT-6 and later models."});return}function Mw4($){if($.type==="containerReference")return{type:"container_reference",container_id:$.containerId};if($.type==="containerAuto"){let Q=$;return{type:"container_auto",file_ids:Q.fileIds,memory_limit:Q.memoryLimit,network_policy:Q.networkPolicy==null?void 0:Q.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:Q.networkPolicy.allowedDomains,domain_secrets:Q.networkPolicy.domainSecrets},skills:Iw4(Q.skills)}}return{type:"local",skills:$.skills}}function Iw4($){return $==null?void 0:$.map((Z)=>{var Q,Y;return Z.type==="skillReference"?{type:"skill_reference",skill_id:AQ({reference:(Q=Z.providerReference)!=null?Q:{},provider:"openai"}),version:(Y=Z.version)!=null?Y:"latest"}:{type:"inline",name:Z.name,description:Z.description,source:{type:"base64",media_type:Z.source.mediaType,data:Z.source.data}}})}function SG$($){var Z,Q;let Y={};for(let X of $){if(X.role!=="assistant")continue;for(let J of X.content){if(J.type!=="tool-call")continue;let G=(Q=(Z=J.providerOptions)==null?void 0:Z.openai)==null?void 0:Q.approvalRequestId;if(G!=null)Y[G]=J.toolCallId}}return Y}function Vw4($){switch($.type){case"click":return{type:"click",button:$.button,x:$.x,y:$.y,...$.keys!=null&&{keys:$.keys}};case"double_click":return{type:"double_click",x:$.x,y:$.y,...$.keys!=null&&{keys:$.keys}};case"drag":return{type:"drag",path:$.path,...$.keys!=null&&{keys:$.keys}};case"keypress":return $;case"move":return{type:"move",x:$.x,y:$.y,...$.keys!=null&&{keys:$.keys}};case"screenshot":return $;case"scroll":return{type:"scroll",x:$.x,y:$.y,scrollX:$.scroll_x,scrollY:$.scroll_y,...$.keys!=null&&{keys:$.keys}};case"type":return $;case"wait":return $}}function CG$({action:$,actions:Z,pending_safety_checks:Q,status:Y}){var X;return{actions:(Z!=null?Z:$!=null?[$]:[]).map(Vw4),pendingSafetyChecks:(X=Q==null?void 0:Q.map((J)=>({id:J.id,...J.code!=null&&{code:J.code},...J.message!=null&&{message:J.message}})))!=null?X:[],status:Y}}function kw4($){return $.type==="response.output_text.delta"}function Sw4($){let Z=_w4($);return Z!=null&&Array.isArray(Z.choices)&&typeof Z.type!=="string"}function Cw4({value:$,cause:Z,url:Q,requestBodyValues:Y,responseHeaders:X}){return new W8({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:Q,requestBodyValues:Y,responseHeaders:X,responseBody:JSON.stringify($),cause:Z,data:$,isRetryable:!1})}function _w4($){return typeof $==="object"&&$!=null?$:void 0}function vw4($){return $.type==="response.output_item.done"}function bw4($){return $.type==="response.completed"||$.type==="response.incomplete"}function _G$($){return $.type==="response.failed"}function xw4($){return $.type==="response.created"}function fw4($){return $.type==="response.function_call_arguments.delta"}function yw4($){return $.type==="response.custom_tool_call_input.delta"}function gw4($){return $.type==="response.image_generation_call.partial_image"}function hw4($){return $.type==="response.code_interpreter_call_code.delta"}function uw4($){return $.type==="response.code_interpreter_call_code.done"}function lw4($){return $.type==="response.apply_patch_call_operation_diff.delta"}function cw4($){return $.type==="response.apply_patch_call_operation_diff.done"}function vG$($){return $.type==="response.output_item.added"}function mw4($){return $.type==="response.output_text.annotation.added"}function bG$($){return $.type==="error"}function dw4($){return $.type==="response.in_progress"}function iw4($){return!($.type==="response.created"||$.type==="response.in_progress"||$.type==="response.failed"||$.type==="error"||$.type==="unknown_chunk")}function sa0($){var Z;if($==null)return{};switch($.type){case"search":return{action:{type:"search",query:(Z=$.query)!=null?Z:void 0,...$.queries!=null&&{queries:$.queries}},...$.sources!=null&&{sources:$.sources}};case"open_page":return{action:{type:"openPage",url:$.url}};case"find_in_page":return{action:{type:"findInPage",url:$.url,pattern:$.pattern}}}}function DA($){return JSON.stringify($).slice(1,-1)}function nw4($){for(let Z of $){let Q=Z.type;if(Q!=="text")throw new t1({functionality:`batch request type: ${Q}`,message:`The OpenAI Batch API does not support batch requests with type "${Q}".`})}}function sw4($){var Z;let Q=(Z=$[0])==null?void 0:Z.modelId;for(let Y of $)if(Y.modelId!==Q)throw new b8({argument:"requests",message:`The OpenAI Batch API requires all requests in a batch to use the same model. Found "${Q}" and "${Y.modelId}".`})}function eG0($){var Z,Q,Y;let X=ew4($.status),J=(Q=(Z=$.errors)==null?void 0:Z.data)==null?void 0:Q[0],G=$j4($.request_counts),W=aa0($.created_at),K=aa0($.expires_at);return{status:X,rawStatus:$.status,...G!=null?{requestCounts:G}:{},...J!=null?{error:{message:(Y=J.message)!=null?Y:"OpenAI batch failed.",...J.code!=null?{code:J.code}:{}}}:{},...W!=null?{createdAt:W}:{},...K!=null?{expiresAt:K}:{}}}function ew4($){switch($){case"completed":return"completed";case"failed":case"expired":case"cancelled":return"failed";case"validating":case"in_progress":case"finalizing":case"cancelling":default:return"pending"}}function $j4($){let Z=$==null?void 0:$.total,Q=$==null?void 0:$.completed,Y=$==null?void 0:$.failed;return oL({total:Z,pending:Z!=null&&Q!=null&&Y!=null?Z-Q-Y:void 0,completed:Q,failed:Y})}function aa0($){if($==null||!Number.isFinite($))return;let Z=new Date($*1000);return Number.isNaN(Z.getTime())?void 0:Z.toISOString()}async function Zj4({body:$,statusCode:Z}){var Q;let Y=await u4({value:$,schema:Y30});if(!Y.success)return{message:`OpenAI batch request failed with status code ${Z}.`,statusCode:Z};return{message:Y.value.error.message,type:(Q=Y.value.error.type)!=null?Q:void 0,code:Y.value.error.code!=null?String(Y.value.error.code):void 0,statusCode:Z}}async function Qj4($){var Z,Q,Y,X,J,G,W,K;let H=await u4({value:$,schema:Y3$});if(!H.success)return{success:!1,error:{message:"OpenAI returned an invalid Responses batch result.",code:"invalid_response"}};let F=H.value;if(F.error!=null)return{success:!1,error:{message:F.error.message,type:F.error.type,code:F.error.code}};if(F.output==null){let L=(Z=F.incomplete_details)==null?void 0:Z.reason;return{success:!1,error:{message:L!=null?`OpenAI Responses returned no output (${L}).`:"OpenAI Responses returned no output.",code:"invalid_response"}}}let U=[],N=[],B=!1;for(let L of F.output)switch(L.type){case"reasoning":{let w=L.summary.length>0?L.summary:[{type:"summary_text",text:""}];for(let j of w)U.push({type:"reasoning",text:j.text,providerMetadata:{openai:{itemId:L.id,reasoningEncryptedContent:(Q=L.encrypted_content)!=null?Q:null}}});break}case"message":{for(let w of L.content)if(U.push({type:"text",text:w.text}),w.logprobs!=null)N.push(w.logprobs);break}case"function_call":B=!0,U.push({type:"tool-call",toolCallId:L.call_id,toolName:L.name,input:L.arguments,providerMetadata:{openai:{itemId:L.id,...L.namespace!=null&&{namespace:L.namespace},...L.caller!=null&&{caller:L.caller.type==="program"?{type:"program",callerId:L.caller.caller_id}:L.caller}}}});break;case"custom_tool_call":B=!0,U.push({type:"tool-call",toolCallId:L.call_id,toolName:L.name,input:JSON.stringify(L.input),providerMetadata:{openai:{itemId:L.id}}});break;case"web_search_call":U.push({type:"tool-call",toolCallId:L.id,toolName:"web_search",input:"{}",providerExecuted:!0,dynamic:!0}),U.push({type:"tool-result",toolCallId:L.id,toolName:"web_search",result:sa0(L.action),dynamic:!0});break;case"file_search_call":U.push({type:"tool-call",toolCallId:L.id,toolName:"file_search",input:"{}",providerExecuted:!0,dynamic:!0}),U.push({type:"tool-result",toolCallId:L.id,toolName:"file_search",result:{queries:L.queries,results:(X=(Y=L.results)==null?void 0:Y.map((w)=>({attributes:w.attributes,fileId:w.file_id,filename:w.filename,score:w.score,text:w.text})))!=null?X:null},dynamic:!0});break;case"code_interpreter_call":U.push({type:"tool-call",toolCallId:L.id,toolName:"code_interpreter",input:JSON.stringify({code:L.code,containerId:L.container_id}),providerExecuted:!0,dynamic:!0}),U.push({type:"tool-result",toolCallId:L.id,toolName:"code_interpreter",result:{outputs:L.outputs},dynamic:!0});break;default:return{success:!1,error:{message:`OpenAI returned an unsupported "${L.type}" output item in an AI SDK text batch.`,code:"unsupported_content"}}}let O={openai:{responseId:F.id,...N.length>0?{logprobs:N}:{},...typeof F.service_tier==="string"?{serviceTier:F.service_tier}:{},...((J=F.reasoning)==null?void 0:J.context)!=null?{reasoningContext:F.reasoning.context}:{}}};return{success:!0,result:{content:U,finishReason:{unified:Z30({finishReason:(G=F.incomplete_details)==null?void 0:G.reason,hasFunctionCall:B}),raw:(K=(W=F.incomplete_details)==null?void 0:W.reason)!=null?K:void 0},usage:la0(F.usage),response:{id:F.id,timestamp:F.created_at!=null?new Date(F.created_at*1000):void 0,modelId:F.model},providerMetadata:O,warnings:[]}}}function ea0($,Z,Q="websocket"){var Y,X,J,G,W,K;for(let N of Object.keys($))if(!["instructions","voice","inputAudioFormat","outputAudioFormat","providerOptions"].includes(N))throw new t1({functionality:`OpenAI Live session setting: ${N}`});if($W.object({delegation:$W.object({type:$W.literal("responses")})}).safeParse((Y=$.providerOptions)==null?void 0:Y.openai).success)throw new t1({functionality:"OpenAI Live Responses delegation; only client delegation is supported"});let H=Xj4.parse((J=(X=$.providerOptions)==null?void 0:X.openai)!=null?J:{});if(H.client!==void 0&&Q!=="webrtc")throw new t1({functionality:"OpenAI Live client permissions outside WebRTC startup"});if(H.voice!=null&&$.voice!=null)throw new b8({argument:"voice",message:"Choose either voice or providerOptions.openai.voice."});if(Q==="webrtc"&&($.inputAudioFormat!==void 0||$.outputAudioFormat!==void 0))throw new t1({functionality:"Fixed audio formats for OpenAI Live WebRTC; audio is negotiated through SDP"});let F=$.inputAudioFormat==null?void 0:yG$.parse($.inputAudioFormat),U=$.outputAudioFormat==null?void 0:yG$.parse($.outputAudioFormat);if(F!=null&&U!=null&&(F.type!==U.type||F.rate!==U.rate))throw new b8({argument:"outputAudioFormat",message:"OpenAI Live requires the same input and output audio format."});return{model:Z,...$.instructions!==void 0?{instructions:$.instructions}:{},audio:{...Q==="websocket"?{format:(G=F!=null?F:U)!=null?G:{type:"audio/pcm",rate:24000}}:{},output:{voice:(K=(W=H.voice)!=null?W:$.voice)!=null?K:"marin"}},...H.delegation!==void 0?{delegation:H.delegation}:{},...H.client!==void 0?{client:{data_channel:{...H.client.dataChannel.allowedClientEvents!==void 0?{allowed_client_events:H.client.dataChannel.allowedClientEvents}:{},...H.client.dataChannel.allowedServerEvents!==void 0?{allowed_server_events:H.client.dataChannel.allowedServerEvents==="all"?"all":H.client.dataChannel.allowedServerEvents.map((N)=>({type:N.type,...N.responseEvent!==void 0?{response_event:N.responseEvent}:{}}))}:{}}}}:{},...H.input!==void 0?{input:H.input}:{},...H.store!==void 0?{store:H.store}:{}}}function Kj4(){return($)=>H3$($)}function H3$($){return[Hj4($)]}function Hj4($){var Z,Q,Y,X,J,G,W,K,H,F;let U=Wj4.safeParse($);if(U.success&&!Gj4.has(U.data.type))return{type:"custom",rawType:U.data.type,raw:$};let N=K3$.safeParse($);if(!N.success)return{type:"error",code:"invalid_server_event",message:"Invalid OpenAI Live server event.",raw:$};let B=N.data;if("start_ms"in B&&B.end_ms<B.start_ms)return{type:"error",code:"invalid_server_event",message:"Invalid OpenAI Live event time interval.",raw:$};switch(B.type){case"session.started":return{type:"session-started",sessionId:B.session.id,delegationMode:((Z=B.session.delegation)==null?void 0:Z.type)==="responses"?"provider":"client",raw:$};case"session.closed":return{type:"session-closed",sessionId:(Q=B.session)==null?void 0:Q.id,usage:B.usage,reason:B.reason,raw:$};case"session.usage.updated":return{type:"session-usage",usage:B.usage,contextWindowUsageRatio:(Y=B.context_window)==null?void 0:Y.usage_ratio,raw:$};case"session.output_audio.delta":return{type:"audio-chunk",delta:B.delta,raw:$};case"session.input_transcript.delta":case"session.output_transcript.delta":return{type:"transcript-fragment",speaker:B.type==="session.input_transcript.delta"?"user":"assistant",delta:B.delta,startMs:B.start_ms,endMs:B.end_ms,raw:$};case"session.delegation.created":return{type:"delegation-created",delegationId:B.delegation.id,target:B.delegation.target==="responses"?"provider":(X=B.delegation.target)!=null?X:void 0,offsetMs:(J=B.offset_ms)!=null?J:void 0,...B.delegation.response_id!=null?{responseId:B.delegation.response_id}:{},raw:$};case"error":return{type:"error",message:B.error.message,code:(G=B.error.code)!=null?G:void 0,clientEventId:(W=B.error.client_event_id)!=null?W:void 0,raw:$};case"session.updated":return{type:"command-acknowledged",command:"session.update",clientEventId:(K=B.client_event_id)!=null?K:void 0,raw:$};case"session.input_audio.muted":case"session.input_audio.unmuted":return{type:"command-acknowledged",command:B.type.slice(0,-1),clientEventId:(H=B.client_event_id)!=null?H:void 0,raw:$};case"session.instructions.appended":case"session.thinking.appended":case"session.commentary.appended":return{type:"command-acknowledged",command:B.type.slice(0,-2),clientEventId:(F=B.client_event_id)!=null?F:void 0,raw:$}}}function Fj4($,Z){var Q,Y,X;let J="eventId"in $&&$.eventId!==void 0?{event_id:$.eventId}:{};switch($.type){case"session-start":return{type:"session.start",session:ea0($.config,Z),...J};case"session-update":throw new t1({functionality:"OpenAI Live session-update; startup settings are immutable; use context-append or input-audio-mute/input-audio-unmute"});case"session-close":return{type:"session.close",...J};case"input-audio-append":return{type:"session.input_audio.append",audio:$.audio,...J};case"input-audio-mute":return{type:"session.input_audio.mute",...J};case"input-audio-unmute":return{type:"session.input_audio.unmute",...J};case"context-append":{let G=v$.object({content:v$.string(),delegationId:v$.string().min(1).nullable()}).parse($);return{type:`session.${(X=v$.strictObject({channel:v$.enum(["instructions","thinking","commentary"]).optional()}).parse((Y=(Q=$.providerOptions)==null?void 0:Q.openai)!=null?Y:{}).channel)!=null?X:"thinking"}.append`,content:G.content,delegation_id:G.delegationId,...J}}default:throw new t1({functionality:`OpenAI Live command: ${$.type}; use continuous audio and context-append instead of voice-turn commands`})}}function Nj4($){var Z,Q,Y,X,J,G,W,K,H,F,U,N,B,O,L,w,j,E,z,T,P;let A=$,q=A.type;switch(q){case"session.created":return{type:"session-created",sessionId:(Z=A.session)==null?void 0:Z.id,raw:$};case"session.updated":return{type:"session-updated",raw:$};case"input_audio_buffer.speech_started":return{type:"speech-started",itemId:A.item_id,raw:$};case"input_audio_buffer.speech_stopped":return{type:"speech-stopped",itemId:A.item_id,raw:$};case"input_audio_buffer.committed":return{type:"audio-committed",itemId:A.item_id,previousItemId:A.previous_item_id,raw:$};case"conversation.item.added":return{type:"conversation-item-added",itemId:(Y=(Q=A.item)==null?void 0:Q.id)!=null?Y:A.item_id,item:A.item,raw:$};case"conversation.item.input_audio_transcription.completed":return{type:"input-transcription-completed",itemId:A.item_id,transcript:(X=A.transcript)!=null?X:"",raw:$};case"response.created":return{type:"response-created",responseId:(G=(J=A.response)==null?void 0:J.id)!=null?G:A.response_id,raw:$};case"response.done":return{type:"response-done",responseId:(K=(W=A.response)==null?void 0:W.id)!=null?K:A.response_id,status:(F=(H=A.response)==null?void 0:H.status)!=null?F:"completed",raw:$};case"response.output_item.added":return{type:"output-item-added",responseId:A.response_id,itemId:(N=(U=A.item)==null?void 0:U.id)!=null?N:A.item_id,raw:$};case"response.output_item.done":return{type:"output-item-done",responseId:A.response_id,itemId:(O=(B=A.item)==null?void 0:B.id)!=null?O:A.item_id,raw:$};case"response.content_part.added":return{type:"content-part-added",responseId:A.response_id,itemId:A.item_id,raw:$};case"response.content_part.done":return{type:"content-part-done",responseId:A.response_id,itemId:A.item_id,raw:$};case"response.output_audio.delta":return{type:"audio-delta",responseId:A.response_id,itemId:A.item_id,delta:A.delta,raw:$};case"response.output_audio.done":return{type:"audio-done",responseId:A.response_id,itemId:A.item_id,raw:$};case"response.output_audio_transcript.delta":return{type:"audio-transcript-delta",responseId:A.response_id,itemId:A.item_id,delta:A.delta,raw:$};case"response.output_audio_transcript.done":return{type:"audio-transcript-done",responseId:A.response_id,itemId:A.item_id,transcript:A.transcript,raw:$};case"response.output_text.delta":return{type:"text-delta",responseId:A.response_id,itemId:A.item_id,delta:A.delta,raw:$};case"response.output_text.done":return{type:"text-done",responseId:A.response_id,itemId:A.item_id,text:A.text,raw:$};case"response.function_call_arguments.delta":return{type:"function-call-arguments-delta",responseId:A.response_id,itemId:A.item_id,callId:A.call_id,delta:A.delta,raw:$};case"response.function_call_arguments.done":return{type:"function-call-arguments-done",responseId:A.response_id,itemId:A.item_id,callId:A.call_id,name:A.name,arguments:A.arguments,raw:$};case"error":return{type:"error",message:(j=(w=(L=A.error)==null?void 0:L.message)!=null?w:A.message)!=null?j:"Unknown error",code:(z=(E=A.error)==null?void 0:E.code)!=null?z:A.code,clientEventId:(P=(T=A.error)==null?void 0:T.event_id)!=null?P:void 0,raw:$};default:return{type:"custom",rawType:q,raw:$}}}function Bj4($,Z){switch($.type){case"session-update":return{type:"session.update",session:Ze0($.config,Z),...$.eventId!=null?{event_id:$.eventId}:{}};case"input-audio-append":return{type:"input_audio_buffer.append",audio:$.audio,...$.eventId!=null?{event_id:$.eventId}:{}};case"input-audio-commit":return{type:"input_audio_buffer.commit"};case"input-audio-clear":return{type:"input_audio_buffer.clear"};case"conversation-item-create":{let Q=$.item;switch(Q.type){case"text-message":return{type:"conversation.item.create",item:{type:"message",role:Q.role,content:[{type:"input_text",text:Q.text}]}};case"audio-message":return{type:"conversation.item.create",item:{type:"message",role:Q.role,content:[{type:"input_audio",audio:Q.audio}]}};case"function-call-output":return{type:"conversation.item.create",item:{type:"function_call_output",call_id:Q.callId,output:Q.output}}}break}case"conversation-item-truncate":return{type:"conversation.item.truncate",item_id:$.itemId,content_index:$.contentIndex,audio_end_ms:$.audioEndMs};case"response-create":return{type:"response.create",...$.options!=null?{response:{...$.options.modalities!=null?{output_modalities:$.options.modalities}:{},...$.options.instructions!=null?{instructions:$.options.instructions}:{},...$.options.metadata!=null?{metadata:$.options.metadata}:{}}}:{}};case"response-cancel":return{type:"response.cancel"}}}function Ze0($,Z){var Q;let Y={type:"realtime",model:Z};if($.instructions!=null)Y.instructions=$.instructions;if($.outputModalities!=null)Y.output_modalities=$.outputModalities;let X={};if($.inputAudioFormat!=null||$.inputAudioTranscription!=null||$.turnDetection!=null){let J={};if($.inputAudioFormat!=null)J.format={type:$.inputAudioFormat.type,...$.inputAudioFormat.rate!=null?{rate:$.inputAudioFormat.rate}:{}};if($.turnDetection!=null)if($.turnDetection.type==="disabled")J.turn_detection=null;else{let G={type:$.turnDetection.type==="server-vad"?"server_vad":"semantic_vad"};if($.turnDetection.threshold!=null)G.threshold=$.turnDetection.threshold;if($.turnDetection.silenceDurationMs!=null)G.silence_duration_ms=$.turnDetection.silenceDurationMs;if($.turnDetection.prefixPaddingMs!=null)G.prefix_padding_ms=$.turnDetection.prefixPaddingMs;J.turn_detection=G}if($.inputAudioTranscription!=null)J.transcription={model:(Q=$.inputAudioTranscription.model)!=null?Q:"gpt-realtime-whisper",...$.inputAudioTranscription.language!=null?{language:$.inputAudioTranscription.language}:{},...$.inputAudioTranscription.prompt!=null?{prompt:$.inputAudioTranscription.prompt}:{}};X.input=J}if($.outputAudioFormat!=null||$.voice!=null){let J={};if($.outputAudioFormat!=null)J.format={type:$.outputAudioFormat.type,...$.outputAudioFormat.rate!=null?{rate:$.outputAudioFormat.rate}:{}};if($.voice!=null)J.voice=$.voice;X.output=J}if(Object.keys(X).length>0)Y.audio=X;if($.tools!=null&&$.tools.length>0)Y.tools=$.tools.map((J)=>({type:J.type,name:J.name,description:J.description,parameters:J.parameters})),Y.tool_choice="auto";if($.providerOptions!=null)Object.assign(Y,$.providerOptions);return Y}function Lj4($,{api:Z}={}){if(Z!==void 0){if(Z!=="live"&&Z!=="realtime")throw new b8({argument:"api",message:'OpenAI realtime api must be "live" or "realtime".'});return Z}return Dj4.some((Q)=>Q===$)?"live":"realtime"}function wj4($){let Z=(Q,Y)=>{let X=Lj4(Q,Y),J={...$,provider:`${$.provider}.${X}`};return X==="live"?new uG$(Q,J):new Oj4(Q,J)};return Object.assign(Z,{getToken:async(Q)=>{let Y=Z(Q.model,Q);if(Y instanceof uG$)throw new t1({functionality:"Short-lived OpenAI credentials for the Live API. Use server WebSocket setup via getServerWebSocketConfig() with a server-side API key instead."});let X=await Y.doCreateClientSecret({sessionConfig:Q.sessionConfig,expiresAfterSeconds:Q.expiresAfterSeconds});return{token:X.token,url:X.url,expiresAt:X.expiresAt}}})}function cG$($){return $==="gpt-realtime-whisper"||$.startsWith("gpt-realtime-whisper-")}function Aj4({webSocket:$,url:Z,headers:Q,sessionUpdate:Y,language:X,warnings:J,audio:G,abortSignal:W,includeRawChunks:K}){let H=!1,F=()=>{};return new ReadableStream({start:(U)=>{let N=Rj4(Q),B,O;F=(E)=>{if(B!=null)B.cancel().catch(()=>{});else G.cancel().catch(()=>{});O==null||O.close(E)};let L=(E)=>{if(H)return;H=!0,F(),U.error(E)},w=(E,z)=>{if(H)return;if(H=!0,z!=null)U.enqueue({type:"transcript-final",id:z,text:E});U.enqueue({type:"finish",text:E,segments:[],language:X}),U.close(),F(1000)},j=async(E)=>{B=G.getReader();try{while(!0){let{done:z,value:T}=await B.read();if(z||H)break;E.send(JSON.stringify({type:"input_audio_buffer.append",audio:X4(T)})),await DF(E)}}finally{B.releaseLock(),B=void 0}if(!H)E.send(JSON.stringify({type:"input_audio_buffer.commit"}))};O=LF({url:Z,protocols:N.protocols,headers:N.headers,webSocket:$,abortSignal:W,onAbort:L,onProcessingError:L,onOpen:(E)=>{U.enqueue({type:"stream-start",warnings:J}),E.send(JSON.stringify(Y)),j(E).catch(L)},onMessageText:async(E)=>{var z,T,P,A;let q=await P5({text:E});if(!q.success)return;let x=q.value;if(K)U.enqueue({type:"raw",rawValue:x});switch(x.type){case"conversation.item.input_audio_transcription.delta":{U.enqueue({type:"transcript-delta",id:x.item_id,delta:(z=x.delta)!=null?z:""});break}case"conversation.item.input_audio_transcription.completed":{w((T=x.transcript)!=null?T:"",x.item_id);break}case"error":{L(Error((A=(P=x.error)==null?void 0:P.message)!=null?A:"OpenAI realtime error"));break}}},onSocketError:()=>{L(Error("OpenAI realtime transcription error"))},onClose:()=>{if(H)return;H=!0,F(),U.close()}})},cancel:()=>{if(H)return;H=!0,F()}})}function Tj4({modelId:$,inputAudioFormat:Z,providerOptions:Q}){var Y,X;return{type:"session.update",session:{type:"transcription",audio:{input:{format:{type:Z.type,...Z.rate!=null?{rate:Z.rate}:{}},transcription:{model:$,...(Q==null?void 0:Q.language)!=null?{language:Q.language}:{},...((Y=Q==null?void 0:Q.streaming)==null?void 0:Y.delay)!=null?{delay:Q.streaming.delay}:{}},turn_detection:null}},...((X=Q==null?void 0:Q.streaming)==null?void 0:X.include)!=null?{include:Q.streaming.include}:{}}}}function Rj4($){var Z;let Q;for(let[X,J]of Object.entries($))if(X.toLowerCase()==="authorization"&&J!=null)Q=J;let Y=(Z=Q==null?void 0:Q.match(/^bearer\s+(.+)$/i))==null?void 0:Z[1];if(Y==null)return{protocols:["realtime"],headers:$};return{protocols:["realtime",`openai-insecure-api-key.${Y}`],headers:Object.fromEntries(Object.entries($).filter(([X])=>X.toLowerCase()!=="authorization"))}}function Vj4({webSocket:$,url:Z,headers:Q,sessionUpdate:Y,warnings:X,audio:J,abortSignal:G,includeRawChunks:W}){let K=!1,H=()=>{};return new ReadableStream({start:(F)=>{let U=Cj4(Q),N,B,O="",L="";H=(z)=>{if(N!=null)N.cancel().catch(()=>{});else J.cancel().catch(()=>{});B==null||B.close(z)};let w=(z)=>{if(K)return;K=!0,H(),F.error(z)},j=()=>{if(K)return;if(K=!0,O!=="")F.enqueue({type:"source-transcript-final",text:O});if(L!=="")F.enqueue({type:"output-text-final",text:L});F.enqueue({type:"finish",sourceText:O,outputText:L,usage:void 0}),F.close(),H(1000)},E=async(z)=>{N=J.getReader();try{while(!0){let{done:T,value:P}=await N.read();if(T||K)break;z.send(JSON.stringify({type:"session.input_audio_buffer.append",audio:X4(P)})),await DF(z)}}finally{N.releaseLock(),N=void 0}if(!K)z.send(JSON.stringify({type:"session.close"}))};B=LF({url:Z,protocols:U.protocols,headers:U.headers,webSocket:$,abortSignal:G,onAbort:w,onProcessingError:w,onOpen:(z)=>{F.enqueue({type:"stream-start",warnings:X}),z.send(JSON.stringify(Y)),E(z).catch(w)},onMessageText:async(z)=>{var T,P,A,q,x,_;if(K)return;let V=await P5({text:z});if(!V.success)return;let y=V.value;if(W)F.enqueue({type:"raw",rawValue:y});switch(y.type){case"session.output_audio.delta":{if(y.delta)F.enqueue({type:"audio",audio:y.delta});break}case"session.output_transcript.delta":{L+=(T=y.delta)!=null?T:"",F.enqueue({type:"output-text-delta",delta:(P=y.delta)!=null?P:""});break}case"session.input_transcript.delta":{O+=(A=y.delta)!=null?A:"",F.enqueue({type:"source-transcript-delta",delta:(q=y.delta)!=null?q:""});break}case"session.closed":{j();break}case"error":{F.enqueue({type:"error",error:Error((_=(x=y.error)==null?void 0:x.message)!=null?_:"OpenAI realtime error")});break}}},onSocketError:()=>{w(Error("OpenAI realtime translation error"))},onClose:({code:z,reason:T})=>{if(K)return;w(Error(`OpenAI realtime translation WebSocket closed unexpectedly before finishing (code ${z!=null?z:"unknown"}${T?`, reason: ${T}`:""}).`))}})},cancel:()=>{if(K)return;K=!0,H()}})}function kj4({targetLanguage:$}){return{type:"session.update",session:{audio:{input:{transcription:{model:"gpt-realtime-whisper"},noise_reduction:null},output:{language:$}}}}}function Sj4($){if($.type!=="audio/pcm"||$.rate!=null&&$.rate!==24000)throw new b8({argument:"inputAudioFormat",message:"The OpenAI Realtime translation API only supports 24kHz 16-bit PCM input audio."})}function Cj4($){var Z;let Q;for(let[X,J]of Object.entries($))if(X.toLowerCase()==="authorization"&&J!=null)Q=J;let Y=(Z=Q==null?void 0:Q.match(/^bearer\s+(.+)$/i))==null?void 0:Z[1];if(Y==null)return{protocols:["realtime"],headers:$};return{protocols:["realtime",`openai-insecure-api-key.${Y}`],headers:Object.fromEntries(Object.entries($).filter(([X])=>X.toLowerCase()!=="authorization"))}}function wA($={}){var Z,Q;let Y=(Z=sL(gJ0(PF({settingValue:$.baseURL,environmentVariableName:"OPENAI_BASE_URL"}))))!=null?Z:"https://api.openai.com/v1",X=(Q=$.name)!=null?Q:"openai",J=()=>r5({Authorization:`Bearer ${Wl({apiKey:$.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":$.organization,"OpenAI-Project":$.project,...$.headers},`ai-sdk/openai/${bj4}`),G=(z)=>new rD4(z,{provider:`${X}.chat`,url:({path:T})=>`${Y}${T}`,headers:J,fetch:$.fetch}),W=(z)=>new ZL4(z,{provider:`${X}.completion`,url:({path:T})=>`${Y}${T}`,headers:J,fetch:$.fetch}),K=(z)=>new JL4(z,{provider:`${X}.embedding`,url:({path:T})=>`${Y}${T}`,headers:J,fetch:$.fetch}),H=(z)=>new DL4(z,{provider:`${X}.image`,url:({path:T})=>`${Y}${T}`,headers:J,fetch:$.fetch}),F=(z)=>new Pj4(z,{provider:`${X}.transcription`,url:({path:T})=>`${Y}${T}`,headers:J,fetch:$.fetch,webSocket:$.webSocket}),U=(z)=>new Ij4(z,{provider:`${X}.speech-translation`,url:({path:T})=>`${Y}${T}`,headers:J,fetch:$.fetch,webSocket:$.webSocket}),N=(z)=>new Ej4(z,{provider:`${X}.speech`,url:({path:T})=>`${Y}${T}`,headers:J,fetch:$.fetch}),B=()=>new KL4({provider:`${X}.files`,baseURL:Y,headers:J,fetch:$.fetch}),O=()=>new vj4({provider:`${X}.skills`,url:({path:z})=>`${Y}${z}`,headers:J,fetch:$.fetch}),L=(z)=>{if(new.target)throw Error("The OpenAI model function cannot be called with the new keyword.");return w(z)},w=(z)=>{return new G3$(z,{provider:`${X}.responses`,baseURL:Y,url:({path:T})=>`${Y}${T}`,headers:J,fetch:$.fetch,fileIdPrefixes:["file-"]})},j=()=>new rw4({provider:`${X}.batch`,config:{provider:`${X}.responses`,baseURL:Y,url:({path:z})=>`${Y}${z}`,headers:J,fetch:$.fetch,fileIdPrefixes:["file-"]}}),E=function(z){return L(z)};return E.specificationVersion="v4",E.languageModel=L,E.chat=G,E.completion=W,E.responses=w,E.evaluationModel=(z)=>new Fl({model:w(z),provider:`${X}.evaluation`}),E.embedding=K,E.embeddingModel=K,E.textEmbedding=K,E.textEmbeddingModel=K,E.image=H,E.imageModel=H,E.transcription=F,E.transcriptionModel=F,E.translation=U,E.speechTranslationModel=U,E.speech=N,E.speechModel=N,E.files=B,E.skills=O,E.experimental_batch=j,E.experimental_realtime=wj4({provider:X,baseURL:Y,headers:J,fetch:$.fetch}),E.tools=Kw4,E}var Y30,R9,pD4,nD4,tD4,rD4,eD4,$L4,LG$,ZL4,YL4,XL4,wG$,JL4,$30,GL4,WL4,KL4=class{constructor($){this.config=$,this.specificationVersion="v4"}get provider(){return this.config.provider}getFileId($){let Z=$.openai;if(Z==null||Z.trim()==="")throw new b8({argument:"file",message:"file reference is missing an 'openai' file id."});return Z}getHeaders($){return T1(this.config.headers(),$)}async uploadFile({data:$,mediaType:Z,filename:Q,abortSignal:Y,headers:X,providerOptions:J}){var G,W,K;let H;try{H=await I$({provider:"openai",providerOptions:J,schema:WL4})}catch(O){if($.type==="stream")await $.stream.cancel(O).catch(()=>{});throw O}let F=(G=H==null?void 0:H.purpose)!=null?G:"assistants",U=this.getHeaders(X),N=`${this.config.baseURL}/files`,B;if($.type==="stream"){let O=[{type:"field",name:"purpose",value:F}];if((H==null?void 0:H.expiresAfter)!=null)O.push({type:"field",name:"expires_after[anchor]",value:"created_at"},{type:"field",name:"expires_after[seconds]",value:String(H.expiresAfter)});O.push({type:"file",name:"file",filename:Q,mediaType:Z,content:$.stream}),{value:B}=await h7$({url:N,headers:U,parts:O,failedResponseHandler:R9,successfulResponseHandler:E1($30),abortSignal:Y,fetch:this.config.fetch})}else{let O=jF($),L=new Blob([O],{type:Z}),w=new FormData;if(Q!=null)w.append("file",L,Q);else w.append("file",L);if(w.append("purpose",F),(H==null?void 0:H.expiresAfter)!=null)w.append("expires_after[anchor]","created_at"),w.append("expires_after[seconds]",String(H.expiresAfter));({value:B}=await p3({url:N,headers:U,formData:w,failedResponseHandler:R9,successfulResponseHandler:E1($30),abortSignal:Y,fetch:this.config.fetch}))}return{warnings:[],providerReference:{openai:B.id},...((W=B.filename)!=null?W:Q)?{filename:(K=B.filename)!=null?K:Q}:{},...Z!=null?{mediaType:Z}:{},...B.bytes!=null?{byteSize:B.bytes}:{},...B.created_at!=null?{createdAt:new Date(B.created_at*1000)}:{},...B.expires_at!=null?{expiresAt:new Date(B.expires_at*1000)}:{},providerMetadata:{openai:this.toFileMetadata(B)}}}async getFileMetadata({file:$,abortSignal:Z,headers:Q}){let Y=this.getFileId($),{value:X}=await S6({url:`${this.config.baseURL}/files/${Sa0(Y)}`,headers:this.getHeaders(Q),failedResponseHandler:R9,successfulResponseHandler:E1($30),abortSignal:Z,fetch:this.config.fetch,validateUrl:!1});return{warnings:[],providerReference:{openai:X.id},...X.filename!=null?{filename:X.filename}:{},...X.bytes!=null?{byteSize:X.bytes}:{},...X.created_at!=null?{createdAt:new Date(X.created_at*1000)}:{},...X.expires_at!=null?{expiresAt:new Date(X.expires_at*1000)}:{},providerMetadata:{openai:this.toFileMetadata(X)}}}async downloadFile({file:$,abortSignal:Z,headers:Q}){var Y;let X=this.getFileId($),{value:J,responseHeaders:G}=await S6({url:`${this.config.baseURL}/files/${Sa0(X)}/content`,headers:this.getHeaders(Q),failedResponseHandler:R9,successfulResponseHandler:i7$(),abortSignal:Z,fetch:this.config.fetch,validateUrl:!1}),W=(Y=G==null?void 0:G["content-type"])==null?void 0:Y.split(";")[0].trim();return{warnings:[],content:J,...W?{mediaType:W}:{}}}async deleteFile({file:$,abortSignal:Z,headers:Q}){let Y=this.getFileId($),{value:X}=await A7$({url:`${this.config.baseURL}/files/${Sa0(Y)}`,headers:this.getHeaders(Q),failedResponseHandler:R9,successfulResponseHandler:E1(GL4),abortSignal:Z,fetch:this.config.fetch});return{warnings:[],providerReference:{openai:X.id},deleted:X.deleted}}toFileMetadata($){return{...$.filename!=null?{filename:$.filename}:{},...$.purpose!=null?{purpose:$.purpose}:{},...$.bytes!=null?{bytes:$.bytes}:{},...$.created_at!=null?{createdAt:$.created_at}:{},...$.status!=null?{status:$.status}:{},...$.expires_at!=null?{expiresAt:$.expires_at}:{}}}},jG$,HL4,FL4,Ye0,ph5,BL4,OL4,DL4,iG$,pG$,oh5,wL4,jL4,EL4,zL4,PL4,AL4,TL4=($={})=>{return AL4($)},nG$,RL4,tG$,oG$,qL4,ML4=($={})=>qL4($),IL4,VL4,kL4,SL4=($)=>kL4($),rG$,sG$,CL4,_L4,vL4,bL4,xL4,fL4,yL4,gL4=($={})=>{return yL4($)},aG$,eG$,hL4,$3$,ya0,uL4,lL4,cL4,mL4,ga0,ha0,dL4,iL4=($={})=>dL4($),pL4,nL4,tL4,oL4,rL4=($={})=>oL4($),sL4,aL4,eL4,$w4,ua0,Zw4,Qw4,Yw4,Xw4,Jw4=($)=>Xw4($),Z3$,Q3$,Gw4,Ww4=()=>dP(Gw4({}),{type:"provider",prepareProviderOptions:($)=>{var Z;let Q=$==null?void 0:$.openai;return{...$,openai:{...Q,allowedCallers:[...new Set([...(Z=Q==null?void 0:Q.allowedCallers)!=null?Z:[],"programmatic"])]}}}}),Kw4,dl,Ca0,ca0,Hw4,zG$,ma0,da0,ia0,pa0,na0,Fw4,Uw4,Nw4,Bw4,Dw4,Y3$,PG$="parallel",AG$="functions.",zw4,X3$=20,Pw4,xu5,IG$,J3$,G3$,xG$="/v1/responses",pw4=172800,fG$,W3$=()=>y6.object({id:y6.string(),status:y6.string(),output_file_id:y6.string().nullish(),error_file_id:y6.string().nullish(),created_at:y6.number().nullish(),expires_at:y6.number().nullish(),request_counts:y6.object({total:y6.number().nullish(),completed:y6.number().nullish(),failed:y6.number().nullish()}).nullish(),errors:y6.object({data:y6.array(y6.object({code:y6.string().nullish(),message:y6.string().nullish()})).nullish()}).nullish()}),ba0,tw4,ow4,rw4=class{constructor($){this.options=$,this.specificationVersion="v4",this.supportedUrls=J3$,this.provider=$.provider}async doStartBatch($){var Z,Q,Y,X,J,G;nw4($.requests),sw4($.requests);let W=[],K=$.webhookUrl==null?[]:[{warning:{type:"unsupported",feature:"webhookUrl",details:"The OpenAI Batch API does not support per-batch webhook URLs."}}],H=await this.parseBatchProviderOptions($.providerOptions),F=(Z=H==null?void 0:H.inputFileExpiresAfter)!=null?Z:pw4;for(let j of $.requests){let E=await this.prepareRequest(j);W.push(JSON.stringify({custom_id:j.id,method:"POST",url:xG$,body:E.body}),`
|
|
1009
|
-
`);for(let z of E.warnings)K.push({requestId:j.id,warning:z});for(let z of(Q=j.options.tools)!=null?Q:[])if(z.type==="provider"&&!aw4.has(z.id))K.push({requestId:j.id,warning:{type:"unsupported",feature:`batch result conversion for tool "${z.name}"`,details:"OpenAI may return output for this tool that AI SDK text batches cannot currently convert."}})}let U="batch.jsonl",N=new Blob(W,{type:"application/jsonl"});W.length=0;let B=new FormData;B.append("file",N,U),B.append("purpose","batch"),B.append("expires_after[anchor]","created_at"),B.append("expires_after[seconds]",String(F));let{value:O}=await Kl({url:this.getUrl("/files"),headers:T1((X=(Y=this.options.config).headers)==null?void 0:X.call(Y),$.headers),body:{content:B,values:{purpose:"batch","expires_after[anchor]":"created_at","expires_after[seconds]":String(F),file:{name:U,type:N.type,size:N.size}}},failedResponseHandler:R9,successfulResponseHandler:E1($30),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),{value:L}=await o1({url:this.getUrl("/batches"),headers:T1((G=(J=this.options.config).headers)==null?void 0:G.call(J),$.headers),body:{input_file_id:O.id,endpoint:xG$,completion_window:"24h"},failedResponseHandler:R9,successfulResponseHandler:E1(ba0),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),w=aa0(O.expires_at);return{batchId:L.id,...eG0(L),providerMetadata:{openai:{inputFileId:O.id,...w!=null?{inputFileExpiresAt:w}:{}}},warnings:K}}async parseBatchProviderOptions($){let Z=this.options.config.provider.includes("azure")?"azure":"openai",Q=await I$({provider:Z,providerOptions:$,schema:fG$});if(Q==null&&Z!=="openai")Q=await I$({provider:"openai",providerOptions:$,schema:fG$});return Q}async doGetBatchStatus($){let Z=await this.retrieveBatch($);return eG0(Z)}async doCancelBatch($){var Z,Q;return await o1({url:this.getUrl(`/batches/${encodeURIComponent($.batchId)}/cancel`),headers:T1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),body:{},failedResponseHandler:R9,successfulResponseHandler:E1(ba0),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),{}}async doListBatches($){var Z,Q;let Y=new URL(this.getUrl("/batches"));if($.limit!=null)Y.searchParams.set("limit",String($.limit));if($.cursor!=null)Y.searchParams.set("after",$.cursor);let{value:X}=await S6({url:Y.toString(),headers:T1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),failedResponseHandler:R9,successfulResponseHandler:E1(ow4),abortSignal:$.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return{batches:X.data.map((J)=>({batchId:J.id,...eG0(J)})),...X.has_more&&X.last_id!=null?{nextCursor:X.last_id}:{}}}async doGetBatchResults($){let Z=await this.retrieveBatch($),Q=eG0(Z);if(Q.status==="pending")throw new b8({argument:"batchId",message:`OpenAI batch "${$.batchId}" is not complete.`});let Y=[Z.output_file_id,Z.error_file_id].filter((J)=>J!=null);if(Q.status==="completed"&&Y.length===0)throw new W9({data:Z,message:`OpenAI batch "${$.batchId}" completed without batch output.`});let X=this.iterateBatchResults({fileIds:Y,options:$});return wF(X)}async retrieveBatch($){var Z,Q;let{value:Y}=await S6({url:this.getUrl(`/batches/${encodeURIComponent($.batchId)}`),headers:T1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),failedResponseHandler:R9,successfulResponseHandler:E1(ba0),abortSignal:$.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return Y}async*iterateBatchResults({fileIds:$,options:Z}){var Q,Y;for(let X of $){let{value:J}=await S6({url:this.getUrl(`/files/${encodeURIComponent(X)}/content`),headers:T1((Y=(Q=this.options.config).headers)==null?void 0:Y.call(Q),Z.headers),failedResponseHandler:R9,successfulResponseHandler:rL(tw4),abortSignal:Z.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});for await(let G of J)yield await this.convertResultLine(G)}}async convertResultLine($){if($.error!=null){let Q={message:$.error.message,code:$.error.code};if($.error.code==="batch_cancelled")return{type:"text",id:$.custom_id,status:"cancelled",error:Q};if($.error.code==="batch_expired")return{type:"text",id:$.custom_id,status:"expired",error:Q};return{type:"text",id:$.custom_id,status:"failed",error:Q}}if($.response==null)return{type:"text",id:$.custom_id,status:"failed",error:{message:"OpenAI returned a batch result without a response or error.",code:"invalid_batch_result"}};if($.response.status_code<200||$.response.status_code>=300)return{type:"text",id:$.custom_id,status:"failed",error:await Zj4({body:$.response.body,statusCode:$.response.status_code})};let Z=await Qj4($.response.body);if(!Z.success)return{type:"text",id:$.custom_id,status:"failed",error:Z.error};return{type:"text",id:$.custom_id,status:"succeeded",result:Z.result}}async prepareRequest($){let{args:Z,warnings:Q}=await G3$.prepareRequest({modelId:$.modelId,config:this.options.config,options:$.options});return{body:Z,warnings:Q}}getUrl($){return this.options.config.url({path:$,modelId:""})}},aw4,Yj4,Xj4,yG$,$e0,Jj4,gG$,hG$,Q30,xa0,K3$,Gj4,Wj4,Uj4,uG$=class{constructor($,Z){this.modelId=$,this.config=Z,this.specificationVersion="v4",this.capabilities={conversation:"continuous",transports:["websocket","webrtc"],connections:["server-websocket","webrtc"],startup:"session-start",finalization:"session-close"}}get provider(){return this.config.provider}getWebRTCConfig(){return{dataChannelLabel:"oai-events"}}getServerWebSocketConfig(){let $=new URL(`${this.config.baseURL}/live/sessions`);$.protocol=$.protocol==="http:"?"ws:":"wss:";let Z={};for(let[Q,Y]of Object.entries(this.config.headers()))if(Y!==void 0)Z[Q]=Y;return{url:$.toString(),headers:Z}}async doCreateWebRTCSession({sdp:$,sessionConfig:Z={},abortSignal:Q}){let Y=ea0(Z,this.modelId,"webrtc"),{value:X}=await o1({url:`${this.config.baseURL}/live/sessions`,headers:this.config.headers(),body:{session:Y,transport:{type:"webrtc",sdp:LA.string().min(1).parse($)}},failedResponseHandler:R9,successfulResponseHandler:E1(Uj4),abortSignal:Q,fetch:this.config.fetch});return{sessionId:X.session.id,sdp:X.transport.sdp}}parseServerEvent($){return H3$($)}createServerEventParser(){return Kj4()}serializeClientEvent($){return Fj4($,this.modelId)}buildSessionConfig($){return ea0($,this.modelId)}},Oj4=class{constructor($,Z){this.specificationVersion="v4",this.modelId=$,this.provider=Z.provider,this.config=Z}async doCreateClientSecret($){var Z;let Q=(Z=this.config.fetch)!=null?Z:fetch,Y=`${this.config.baseURL}/realtime/client_secrets`,X=$.sessionConfig!=null?Ze0($.sessionConfig,this.modelId):{type:"realtime",model:this.modelId},J=await Q(Y,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify({session:X,...$.expiresAfterSeconds!=null?{expires_after:{anchor:"created_at",seconds:$.expiresAfterSeconds}}:{}})});if(!J.ok){let W=await J.text();throw Error(`OpenAI realtime client secret request failed: ${J.status} ${W}`)}let G=await J.json();return{token:G.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:G.expires_at}}getWebSocketConfig($){return{url:$.url,protocols:["realtime",`openai-insecure-api-key.${$.token}`]}}parseServerEvent($){return Nj4($)}serializeClientEvent($){return Bj4($,this.modelId)}buildSessionConfig($){return Ze0($,this.modelId)}},Dj4,jj4,Ej4,zj4,lG$,mG$,Pj4,Mj4,Ij4,_j4,Kl5,vj4=class{constructor($){this.config=$,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadSkill($){let Z=[];if($.displayTitle!=null)Z.push({type:"unsupported",feature:"displayTitle"});let Q=new FormData;for(let X of $.files){let J=jF(X.data);Q.append("files[]",new Blob([J]),X.path)}let{value:Y}=await p3({url:this.config.url({path:"/skills"}),headers:T1(this.config.headers()),formData:Q,failedResponseHandler:R9,successfulResponseHandler:E1(_j4),fetch:this.config.fetch});return{providerReference:{openai:Y.id},...Y.name!=null?{name:Y.name}:{},...Y.description!=null?{description:Y.description}:{},...Y.latest_version!=null?{latestVersion:Y.latest_version}:{},providerMetadata:{openai:{...Y.default_version!=null?{defaultVersion:Y.default_version}:{},...Y.created_at!=null?{createdAt:Y.created_at}:{},...Y.updated_at!=null?{updatedAt:Y.updated_at}:{}}},warnings:Z}}},bj4="4.0.71",Hl5;var X30=D(()=>{z0();lJ0();O1();z0();z0();O1();z0();z0();O1();z0();z0();z0();z0();O1();O1();z0();z0();O1();z0();z0();z0();O1();z0();z0();z0();O1();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();O1();z0();z0();z0();O1();z0();O1();z0();O1();z0();z0();O1();z0();O1();z0();O1();O1();z0();z0();O1();z0();z0();z0();O1();z0();z0();z0();z0();Y30=Ow.object({error:Ow.object({message:Ow.string(),type:Ow.string().nullish(),param:Ow.any().nullish(),code:Ow.union([Ow.string(),Ow.number()]).nullish()})}),R9=V4({errorSchema:Y30,errorToMessage:($)=>$.error.message});pD4=W0(()=>r(z1.object({id:z1.string().nullish(),created:z1.number().nullish(),model:z1.string().nullish(),choices:z1.array(z1.object({message:z1.object({role:z1.literal("assistant").nullish(),content:z1.string().nullish(),tool_calls:z1.array(z1.object({id:z1.string().nullish(),type:z1.literal("function"),function:z1.object({name:z1.string(),arguments:z1.string()})})).nullish(),annotations:z1.array(z1.object({type:z1.literal("url_citation"),url_citation:z1.object({start_index:z1.number(),end_index:z1.number(),url:z1.string(),title:z1.string()})})).nullish()}),index:z1.number(),logprobs:z1.object({content:z1.array(z1.object({token:z1.string(),logprob:z1.number(),top_logprobs:z1.array(z1.object({token:z1.string(),logprob:z1.number()}))})).nullish()}).nullish(),finish_reason:z1.string().nullish()})),usage:z1.object({prompt_tokens:z1.number().nullish(),completion_tokens:z1.number().nullish(),total_tokens:z1.number().nullish(),prompt_tokens_details:z1.object({cached_tokens:z1.number().nullish(),cache_write_tokens:z1.number().nullish()}).nullish(),completion_tokens_details:z1.object({reasoning_tokens:z1.number().nullish(),accepted_prediction_tokens:z1.number().nullish(),rejected_prediction_tokens:z1.number().nullish()}).nullish()}).nullish()}))),nD4=W0(()=>r(z1.union([z1.object({id:z1.string().nullish(),created:z1.number().nullish(),model:z1.string().nullish(),choices:z1.array(z1.object({delta:z1.object({role:z1.enum(["assistant"]).nullish(),content:z1.string().nullish(),tool_calls:z1.array(z1.object({index:z1.number(),id:z1.string().nullish(),type:z1.literal("function").nullish(),function:z1.object({name:z1.string().nullish(),arguments:z1.string().nullish()})})).nullish(),annotations:z1.array(z1.object({type:z1.literal("url_citation"),url_citation:z1.object({start_index:z1.number(),end_index:z1.number(),url:z1.string(),title:z1.string()})})).nullish()}).nullish(),logprobs:z1.object({content:z1.array(z1.object({token:z1.string(),logprob:z1.number(),top_logprobs:z1.array(z1.object({token:z1.string(),logprob:z1.number()}))})).nullish()}).nullish(),finish_reason:z1.string().nullish(),index:z1.number()})),usage:z1.object({prompt_tokens:z1.number().nullish(),completion_tokens:z1.number().nullish(),total_tokens:z1.number().nullish(),prompt_tokens_details:z1.object({cached_tokens:z1.number().nullish(),cache_write_tokens:z1.number().nullish()}).nullish(),completion_tokens_details:z1.object({reasoning_tokens:z1.number().nullish(),accepted_prediction_tokens:z1.number().nullish(),rejected_prediction_tokens:z1.number().nullish()}).nullish()}).nullish()}),Y30]))),tD4=W0(()=>r(K5.object({logitBias:K5.record(K5.coerce.number(),K5.number()).optional(),logprobs:K5.union([K5.boolean(),K5.number()]).optional(),parallelToolCalls:K5.boolean().optional(),user:K5.string().optional(),reasoningEffort:K5.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:K5.number().optional(),store:K5.boolean().optional(),metadata:K5.record(K5.string().max(64),K5.string().max(512)).optional(),prediction:K5.record(K5.string(),K5.any()).optional(),serviceTier:K5.enum(["auto","flex","priority","fast","ultrafast","default"]).optional(),strictJsonSchema:K5.boolean().optional(),textVerbosity:K5.enum(["low","medium","high"]).optional(),promptCacheKey:K5.string().optional(),promptCacheOptions:K5.object({mode:K5.enum(["implicit","explicit"]).optional(),ttl:K5.literal("30m").optional()}).optional(),promptCacheRetention:K5.enum(["in_memory","24h"]).optional(),safetyIdentifier:K5.string().optional(),systemMessageMode:K5.enum(["system","developer","remove"]).optional(),forceReasoning:K5.boolean().optional()})));rD4=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Z,this.config=Q}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({prompt:Z,maxOutputTokens:Q,temperature:Y,topP:X,topK:J,frequencyPenalty:G,presencePenalty:W,stopSequences:K,responseFormat:H,seed:F,tools:U,toolChoice:N,reasoning:B,providerOptions:O}){var L,w,j,E,z,T;let P=[],A=(L=await I$({provider:"openai",providerOptions:O,schema:tD4}))!=null?L:{},q=dG$(this.modelId),x=(w=A.reasoningEffort)!=null?w:XB(B)?B:void 0;if(x!=null&&q.supportedReasoningEfforts!=null&&!q.supportedReasoningEfforts.includes(x))P.push({type:"unsupported",feature:"reasoningEffort",details:`${this.modelId} only supports the following reasoning efforts: ${q.supportedReasoningEfforts.join(", ")}`}),x=void 0;let _=(j=A.forceReasoning)!=null?j:q.isReasoningModel;if(J!=null)P.push({type:"unsupported",feature:"topK"});let{messages:V,warnings:y}=iD4({prompt:Z,systemMessageMode:(E=A.systemMessageMode)!=null?E:_?"developer":q.systemMessageMode});P.push(...y);let g=(z=A.strictJsonSchema)!=null?z:!0,l=(H==null?void 0:H.type)==="json"&&H.schema!=null?Fa(H.schema):void 0;if(l!=null)P.push(...l.warnings);let n={model:this.modelId,logit_bias:A.logitBias,logprobs:A.logprobs===!0||typeof A.logprobs==="number"?!0:void 0,top_logprobs:typeof A.logprobs==="number"?A.logprobs:typeof A.logprobs==="boolean"?A.logprobs?0:void 0:void 0,user:A.user,parallel_tool_calls:A.parallelToolCalls,max_tokens:Q,temperature:Y,top_p:X,frequency_penalty:G,presence_penalty:W,response_format:(H==null?void 0:H.type)==="json"?l!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:g,name:(T=H.name)!=null?T:"response",description:H.description}}:{type:"json_object"}:void 0,stop:K,seed:F,verbosity:A.textVerbosity,max_completion_tokens:A.maxCompletionTokens,store:A.store,metadata:A.metadata,prediction:A.prediction,reasoning_effort:x,service_tier:A.serviceTier,prompt_cache_key:A.promptCacheKey,prompt_cache_options:A.promptCacheOptions,prompt_cache_retention:A.promptCacheRetention,safety_identifier:A.safetyIdentifier,messages:V};if(q.supportedReasoningEfforts!=null&&n.prompt_cache_retention!=null)n.prompt_cache_retention=void 0,P.push({type:"unsupported",feature:"promptCacheRetention",details:"promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"});if(_){if(x!=="none"||!q.supportsNonReasoningParameters){if(n.temperature!=null)n.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(n.top_p!=null)n.top_p=void 0,P.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(n.logprobs!=null)n.logprobs=void 0,P.push({type:"other",message:"logprobs is not supported for reasoning models"})}if(n.frequency_penalty!=null)n.frequency_penalty=void 0,P.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"});if(n.presence_penalty!=null)n.presence_penalty=void 0,P.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"});if(n.logit_bias!=null)n.logit_bias=void 0,P.push({type:"other",message:"logitBias is not supported for reasoning models"});if(n.top_logprobs!=null)n.top_logprobs=void 0,P.push({type:"other",message:"topLogprobs is not supported for reasoning models"});if(n.max_tokens!=null){if(n.max_completion_tokens==null)n.max_completion_tokens=n.max_tokens;n.max_tokens=void 0}}else if(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview")){if(n.temperature!=null)n.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})}if(A.serviceTier==="flex"&&!q.supportsFlexProcessing)P.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),n.service_tier=void 0;if((A.serviceTier==="priority"||A.serviceTier==="fast")&&!q.supportsPriorityProcessing)P.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),n.service_tier=void 0;let{tools:p,toolChoice:F0,toolWarnings:V0}=oD4({tools:U,toolChoice:N});return{args:{...n,tools:p,tool_choice:F0},warnings:[...P,...V0]}}async doGenerate(Z){var Q,Y,X,J,G,W,K;let{args:H,warnings:F}=await this.getArgs(Z),{responseHeaders:U,value:N,rawValue:B}=await o1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:H,failedResponseHandler:R9,successfulResponseHandler:E1(pD4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),O=N.choices[0];if(O==null)throw new W9({data:B,message:"Response did not contain any choices."});let L=[],w=O.message.content;if(w!=null&&w.length>0)L.push({type:"text",text:w});for(let z of(X=O.message.tool_calls)!=null?X:[])L.push({type:"tool-call",toolCallId:z.id||o8(),toolName:z.function.name,input:z.function.arguments});for(let z of(J=O.message.annotations)!=null?J:[])L.push({type:"source",sourceType:"url",id:o8(),url:z.url_citation.url,title:z.url_citation.title});let j=(G=N.usage)==null?void 0:G.completion_tokens_details,E={openai:{}};if((j==null?void 0:j.accepted_prediction_tokens)!=null)E.openai.acceptedPredictionTokens=j==null?void 0:j.accepted_prediction_tokens;if((j==null?void 0:j.rejected_prediction_tokens)!=null)E.openai.rejectedPredictionTokens=j==null?void 0:j.rejected_prediction_tokens;if(((W=O.logprobs)==null?void 0:W.content)!=null)E.openai.logprobs=O.logprobs.content;return{content:L,finishReason:{unified:BG$(O.finish_reason),raw:(K=O.finish_reason)!=null?K:void 0},usage:NG$(N.usage),request:{body:H},response:{...Ia0(N),headers:U,body:B},warnings:F,providerMetadata:E}}async doStream(Z){var Q,Y;let{args:X,warnings:J}=await this.getArgs(Z),G={...X,stream:!0,stream_options:{include_usage:!0}},W=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:K,value:H}=await o1({url:W,headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:G,failedResponseHandler:R9,successfulResponseHandler:UY(nD4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=await Qe0({stream:H,getError:(E)=>("error"in E)?E.error:void 0,isOutputChunk:sD4,url:W,requestBodyValues:G,responseHeaders:K}),U,N={unified:"other",raw:void 0},B=void 0,O=!1,L=!1,w={openai:{}};return{stream:F.pipeThrough(new TransformStream({start(E){U=new t7$(E,{generateId:o8,typeValidation:"if-present"}),E.enqueue({type:"stream-start",warnings:J})},transform(E,z){var T,P,A,q,x,_;if(Z.includeRawChunks)z.enqueue({type:"raw",rawValue:E.rawValue});if(!E.success){N={unified:"error",raw:void 0},z.enqueue({type:"error",error:E.error});return}let V=E.value;if("error"in V){N={unified:"error",raw:void 0},z.enqueue({type:"error",error:(T=Ha(V.error))!=null?T:V.error});return}if(!O){let l=Ia0(V);if(Object.values(l).some(Boolean))O=!0,z.enqueue({type:"response-metadata",...Ia0(V)})}if(V.usage!=null){if(B=V.usage,((P=V.usage.completion_tokens_details)==null?void 0:P.accepted_prediction_tokens)!=null)w.openai.acceptedPredictionTokens=(A=V.usage.completion_tokens_details)==null?void 0:A.accepted_prediction_tokens;if(((q=V.usage.completion_tokens_details)==null?void 0:q.rejected_prediction_tokens)!=null)w.openai.rejectedPredictionTokens=(x=V.usage.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens}let y=V.choices[0];if((y==null?void 0:y.finish_reason)!=null)N={unified:BG$(y.finish_reason),raw:y.finish_reason};if(((_=y==null?void 0:y.logprobs)==null?void 0:_.content)!=null)w.openai.logprobs=y.logprobs.content;if((y==null?void 0:y.delta)==null)return;let g=y.delta;if(g.content!=null){if(!L)z.enqueue({type:"text-start",id:"0"}),L=!0;z.enqueue({type:"text-delta",id:"0",delta:g.content})}if(g.tool_calls!=null)for(let l of g.tool_calls)U.processDelta(l);if(g.annotations!=null)for(let l of g.annotations)z.enqueue({type:"source",sourceType:"url",id:o8(),url:l.url_citation.url,title:l.url_citation.title})},flush(E){if(L)E.enqueue({type:"text-end",id:"0"});U.flush(),E.enqueue({type:"finish",finishReason:N,usage:NG$(B),...w!=null?{providerMetadata:w}:{}})}})),request:{body:G},response:{headers:K}}}};eD4=W0(()=>r(u8.object({id:u8.string().nullish(),created:u8.number().nullish(),model:u8.string().nullish(),choices:u8.array(u8.object({text:u8.string(),finish_reason:u8.string(),logprobs:u8.object({tokens:u8.array(u8.string()),token_logprobs:u8.array(u8.number()),top_logprobs:u8.array(u8.record(u8.string(),u8.number())).nullish()}).nullish()})),usage:u8.object({prompt_tokens:u8.number(),completion_tokens:u8.number(),total_tokens:u8.number()}).nullish()}))),$L4=W0(()=>r(u8.union([u8.object({id:u8.string().nullish(),created:u8.number().nullish(),model:u8.string().nullish(),choices:u8.array(u8.object({text:u8.string(),finish_reason:u8.string().nullish(),index:u8.number(),logprobs:u8.object({tokens:u8.array(u8.string()),token_logprobs:u8.array(u8.number()),top_logprobs:u8.array(u8.record(u8.string(),u8.number())).nullish()}).nullish()})),usage:u8.object({prompt_tokens:u8.number(),completion_tokens:u8.number(),total_tokens:u8.number()}).nullish()}),Y30]))),LG$=W0(()=>r(fF.object({echo:fF.boolean().optional(),logitBias:fF.record(fF.string(),fF.number()).optional(),suffix:fF.string().optional(),user:fF.string().optional(),logprobs:fF.union([fF.boolean(),fF.number()]).optional()}))),ZL4=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls={},this.modelId=Z,this.config=Q}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({prompt:Z,maxOutputTokens:Q,temperature:Y,topP:X,topK:J,frequencyPenalty:G,presencePenalty:W,stopSequences:K,responseFormat:H,tools:F,toolChoice:U,seed:N,providerOptions:B}){let O=[],L={...await I$({provider:"openai",providerOptions:B,schema:LG$}),...await I$({provider:this.providerOptionsName,providerOptions:B,schema:LG$})};if(J!=null)O.push({type:"unsupported",feature:"topK"});if(F==null?void 0:F.length)O.push({type:"unsupported",feature:"tools"});if(U!=null)O.push({type:"unsupported",feature:"toolChoice"});if(H!=null&&H.type!=="text")O.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});let{prompt:w,stopSequences:j}=aD4({prompt:Z}),E=[...j!=null?j:[],...K!=null?K:[]];return{args:{model:this.modelId,echo:L.echo,logit_bias:L.logitBias,logprobs:(L==null?void 0:L.logprobs)===!0?0:(L==null?void 0:L.logprobs)===!1?void 0:L==null?void 0:L.logprobs,suffix:L.suffix,user:L.user,max_tokens:Q,temperature:Y,top_p:X,frequency_penalty:G,presence_penalty:W,seed:N,prompt:w,stop:E.length>0?E:void 0},warnings:O}}async doGenerate(Z){var Q,Y,X;let{args:J,warnings:G}=await this.getArgs(Z),{responseHeaders:W,value:K,rawValue:H}=await o1({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:J,failedResponseHandler:R9,successfulResponseHandler:E1(eD4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=K.choices[0],U={openai:{}};if(F.logprobs!=null)U.openai.logprobs=F.logprobs;return{content:[{type:"text",text:F.text}],usage:OG$(K.usage),finishReason:{unified:DG$(F.finish_reason),raw:(X=F.finish_reason)!=null?X:void 0},request:{body:J},response:{...xr(K),headers:W,body:H},providerMetadata:U,warnings:G}}async doStream(Z){var Q,Y;let{args:X,warnings:J}=await this.getArgs(Z),G={...X,stream:!0,stream_options:{include_usage:!0}},W=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:K,value:H}=await o1({url:W,headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:G,failedResponseHandler:R9,successfulResponseHandler:UY($L4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=await Qe0({stream:H,getError:(w)=>("error"in w)?w.error:void 0,isOutputChunk:QL4,url:W,requestBodyValues:G,responseHeaders:K}),U={unified:"other",raw:void 0},N={openai:{}},B=void 0,O=!0;return{stream:F.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:J})},transform(w,j){var E;if(Z.includeRawChunks)j.enqueue({type:"raw",rawValue:w.rawValue});if(!w.success){U={unified:"error",raw:void 0},j.enqueue({type:"error",error:w.error});return}let z=w.value;if("error"in z){U={unified:"error",raw:void 0},j.enqueue({type:"error",error:(E=Ha(z.error))!=null?E:z.error});return}if(O)O=!1,j.enqueue({type:"response-metadata",...xr(z)}),j.enqueue({type:"text-start",id:"0"});if(z.usage!=null)B=z.usage;let T=z.choices[0];if((T==null?void 0:T.finish_reason)!=null)U={unified:DG$(T.finish_reason),raw:T.finish_reason};if((T==null?void 0:T.logprobs)!=null)N.openai.logprobs=T.logprobs;if((T==null?void 0:T.text)!=null&&T.text.length>0)j.enqueue({type:"text-delta",id:"0",delta:T.text})},flush(w){if(!O)w.enqueue({type:"text-end",id:"0"});w.enqueue({type:"finish",finishReason:U,providerMetadata:N,usage:OG$(B)})}})),request:{body:G},response:{headers:K}}}};YL4=W0(()=>r(Va0.object({dimensions:Va0.number().optional(),user:Va0.string().optional()}))),XL4=W0(()=>r(OA.object({data:OA.array(OA.object({embedding:OA.array(OA.number())})),usage:OA.object({prompt_tokens:OA.number()}).nullish()}))),JL4=class ${constructor(Z,Q){this.specificationVersion="v4",this.maxEmbeddingsPerCall=2048,this[wG$]=300000,this.supportsParallelCalls=!0,this.modelId=Z,this.config=Q}static[(wG$=C7$,Q4)](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async doEmbed({values:Z,headers:Q,abortSignal:Y,providerOptions:X}){var J,G,W;if(Z.length>this.maxEmbeddingsPerCall)throw new MJ0({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Z});let K=(J=await I$({provider:"openai",providerOptions:X,schema:YL4}))!=null?J:{},{responseHeaders:H,value:F,rawValue:U}=await o1({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:T1((W=(G=this.config).headers)==null?void 0:W.call(G),Q),body:{model:this.modelId,input:Z,encoding_format:"float",dimensions:K.dimensions,user:K.user},failedResponseHandler:R9,successfulResponseHandler:E1(XL4),abortSignal:Y,fetch:this.config.fetch});return{warnings:[],embeddings:F.data.map((N)=>N.embedding),usage:F.usage?{tokens:F.usage.prompt_tokens}:void 0,response:{headers:H,body:U}}}},$30=W0(()=>r(_G.object({id:_G.string(),object:_G.string().nullish(),bytes:_G.number().nullish(),created_at:_G.number().nullish(),filename:_G.string().nullish(),purpose:_G.string().nullish(),status:_G.string().nullish(),expires_at:_G.number().nullish()}))),GL4=W0(()=>r(_G.object({id:_G.string(),object:_G.string().nullish(),deleted:_G.boolean()}))),WL4=W0(()=>r(ka0.object({purpose:ka0.string().optional(),expiresAfter:ka0.number().optional()})));jG$=W0(()=>r(MQ.object({created:MQ.number().nullish(),data:MQ.array(MQ.object({b64_json:MQ.string(),revised_prompt:MQ.string().nullish()})),background:MQ.string().nullish(),output_format:MQ.string().nullish(),size:MQ.string().nullish(),quality:MQ.string().nullish(),usage:MQ.object({input_tokens:MQ.number().nullish(),output_tokens:MQ.number().nullish(),total_tokens:MQ.number().nullish(),input_tokens_details:MQ.object({image_tokens:MQ.number().nullish(),text_tokens:MQ.number().nullish()}).nullish()}).nullish()}))),HL4={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"gpt-image-2.5-flare":10,"gpt-image-2.5-flare-2026-09-08":10,"gpt-image-2.5-sunburst":10,"gpt-image-2.5-sunburst-2026-09-08":10,"chatgpt-image-latest":10},FL4=["chatgpt-image-","gpt-image-"];Ye0=LB.object({quality:LB.enum(["standard","hd","low","medium","high","xhigh","max","auto"]).optional(),background:LB.enum(["transparent","opaque","auto"]).optional(),outputFormat:LB.enum(["png","jpeg","webp"]).optional(),outputCompression:LB.number().int().min(0).max(100).optional(),user:LB.string().optional()}),ph5=W0(()=>r(Ye0)),BL4=W0(()=>r(Ye0.extend({style:LB.enum(["vivid","natural"]).optional(),moderation:LB.enum(["auto","low"]).optional()}))),OL4=W0(()=>r(Ye0.extend({inputFidelity:LB.enum(["high","low"]).optional()}))),DL4=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get maxImagesPerCall(){return NL4(this.modelId)}get provider(){return this.config.provider}async doGenerate({prompt:Z,files:Q,mask:Y,n:X,size:J,aspectRatio:G,seed:W,providerOptions:K,headers:H,abortSignal:F}){var U,N,B,O,L,w,j,E,z,T,P,A,q,x,_;let V=[];if(G!=null)V.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."});if(W!=null)V.push({type:"unsupported",feature:"seed"});let y=(B=(N=(U=this.config._internal)==null?void 0:U.currentDate)==null?void 0:N.call(U))!=null?B:new Date;if(Q!=null){let p=(O=await I$({provider:"openai",providerOptions:K,schema:OL4}))!=null?O:{},{value:F0,responseHeaders:V0}=await p3({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:T1((w=(L=this.config).headers)==null?void 0:w.call(L),H),formData:z7$({model:this.modelId,prompt:Z,image:await Promise.all(Q.map((G0)=>G0.type==="file"?new Blob([G0.data instanceof Uint8Array?new Blob([G0.data],{type:G0.mediaType}):new Blob([_9(G0.data)],{type:G0.mediaType})],{type:G0.mediaType}):hr(G0.url,{abortSignal:F}))),mask:Y!=null?await LL4(Y,F):void 0,n:X,size:J,quality:p.quality,background:p.background,output_format:p.outputFormat,output_compression:p.outputCompression,input_fidelity:p.inputFidelity,user:p.user}),failedResponseHandler:R9,successfulResponseHandler:E1(jG$),abortSignal:F,fetch:this.config.fetch});return{images:F0.data.map((G0)=>G0.b64_json),warnings:V,usage:F0.usage!=null?{inputTokens:(j=F0.usage.input_tokens)!=null?j:void 0,outputTokens:(E=F0.usage.output_tokens)!=null?E:void 0,totalTokens:(z=F0.usage.total_tokens)!=null?z:void 0}:void 0,response:{timestamp:y,modelId:this.modelId,headers:V0},providerMetadata:{openai:{images:F0.data.map((G0,H0)=>{var X0,Z0,Y0,o,J0,c0;return{...G0.revised_prompt?{revisedPrompt:G0.revised_prompt}:{},created:(X0=F0.created)!=null?X0:void 0,size:(Z0=F0.size)!=null?Z0:void 0,quality:(Y0=F0.quality)!=null?Y0:void 0,background:(o=F0.background)!=null?o:void 0,outputFormat:(J0=F0.output_format)!=null?J0:void 0,...EG$((c0=F0.usage)==null?void 0:c0.input_tokens_details,H0,F0.data.length)}})}}}}let g=(T=await I$({provider:"openai",providerOptions:K,schema:BL4}))!=null?T:{},{value:l,responseHeaders:n}=await o1({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:T1((A=(P=this.config).headers)==null?void 0:A.call(P),H),body:{model:this.modelId,prompt:Z,n:X,size:J,quality:g.quality,style:g.style,background:g.background,moderation:g.moderation,output_format:g.outputFormat,output_compression:g.outputCompression,user:g.user,...!UL4(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:R9,successfulResponseHandler:E1(jG$),abortSignal:F,fetch:this.config.fetch});return{images:l.data.map((p)=>p.b64_json),warnings:V,usage:l.usage!=null?{inputTokens:(q=l.usage.input_tokens)!=null?q:void 0,outputTokens:(x=l.usage.output_tokens)!=null?x:void 0,totalTokens:(_=l.usage.total_tokens)!=null?_:void 0}:void 0,response:{timestamp:y,modelId:this.modelId,headers:n},providerMetadata:{openai:{images:l.data.map((p,F0)=>{var V0,G0,H0,X0,Z0,Y0;return{...p.revised_prompt?{revisedPrompt:p.revised_prompt}:{},created:(V0=l.created)!=null?V0:void 0,size:(G0=l.size)!=null?G0:void 0,quality:(H0=l.quality)!=null?H0:void 0,background:(X0=l.background)!=null?X0:void 0,outputFormat:(Z0=l.output_format)!=null?Z0:void 0,...EG$((Y0=l.usage)==null?void 0:Y0.input_tokens_details,F0,l.data.length)}})}}}}};iG$=W0(()=>r(m7.object({callId:m7.string(),operation:m7.discriminatedUnion("type",[m7.object({type:m7.literal("create_file"),path:m7.string(),diff:m7.string()}),m7.object({type:m7.literal("delete_file"),path:m7.string()}),m7.object({type:m7.literal("update_file"),path:m7.string(),diff:m7.string()})])}))),pG$=W0(()=>r(m7.object({status:m7.enum(["completed","failed"]),output:m7.string().optional()}))),oh5=W0(()=>r(m7.object({}))),wL4=TF({id:"openai.apply_patch",inputSchema:iG$,outputSchema:pG$}),jL4=wL4,EL4=W0(()=>r(d7.object({code:d7.string().nullish(),containerId:d7.string()}))),zL4=W0(()=>r(d7.object({outputs:d7.array(d7.discriminatedUnion("type",[d7.object({type:d7.literal("logs"),logs:d7.string()}),d7.object({type:d7.literal("image"),url:d7.string()})])).nullish()}))),PL4=W0(()=>r(d7.object({container:d7.union([d7.string(),d7.object({fileIds:d7.array(d7.string()).optional()})]).optional()}))),AL4=g$({id:"openai.code_interpreter",inputSchema:EL4,outputSchema:zL4}),nG$=J$.object({id:J$.string(),code:J$.string().optional(),message:J$.string().optional()}),RL4=J$.discriminatedUnion("type",[J$.object({type:J$.literal("click"),button:J$.enum(["left","right","wheel","back","forward"]),x:J$.number(),y:J$.number(),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("double_click"),x:J$.number(),y:J$.number(),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("drag"),path:J$.array(J$.object({x:J$.number(),y:J$.number()})),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("keypress"),keys:J$.array(J$.string())}),J$.object({type:J$.literal("move"),x:J$.number(),y:J$.number(),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("screenshot")}),J$.object({type:J$.literal("scroll"),x:J$.number(),y:J$.number(),scrollX:J$.number(),scrollY:J$.number(),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("type"),text:J$.string()}),J$.object({type:J$.literal("wait")})]),tG$=W0(()=>r(J$.object({actions:J$.array(RL4),pendingSafetyChecks:J$.array(nG$),status:J$.enum(["in_progress","completed","incomplete"])}))),oG$=W0(()=>r(J$.object({output:J$.union([J$.object({type:J$.literal("computer_screenshot"),imageUrl:J$.string(),fileId:J$.string().optional(),detail:J$.enum(["auto","low","high","original"]).optional()}),J$.object({type:J$.literal("computer_screenshot"),fileId:J$.string(),imageUrl:J$.string().optional(),detail:J$.enum(["auto","low","high","original"]).optional()})]),acknowledgedSafetyChecks:J$.array(nG$).optional()}))),qL4=TF({id:"openai.computer",inputSchema:tG$,outputSchema:oG$}),IL4=W0(()=>r(gK.object({description:gK.string().optional(),async:gK.boolean().optional(),format:gK.union([gK.object({type:gK.literal("grammar"),syntax:gK.enum(["regex","lark"]),definition:gK.string()}),gK.object({type:gK.literal("text")})]).optional()}))),VL4=W0(()=>r(gK.string())),kL4=$Z({id:"openai.custom",inputSchema:VL4}),rG$=X6.object({key:X6.string(),type:X6.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:X6.union([X6.string(),X6.number(),X6.boolean(),X6.array(X6.string())])}),sG$=X6.object({type:X6.enum(["and","or"]),filters:X6.array(X6.union([rG$,X6.lazy(()=>sG$)]))}),CL4=W0(()=>r(X6.object({vectorStoreIds:X6.array(X6.string()),maxNumResults:X6.number().optional(),ranking:X6.object({ranker:X6.string().optional(),scoreThreshold:X6.number().optional()}).optional(),filters:X6.union([rG$,sG$]).optional()}))),_L4=W0(()=>r(X6.object({queries:X6.array(X6.string()),results:X6.array(X6.object({attributes:X6.record(X6.string(),X6.unknown()),fileId:X6.string(),filename:X6.string(),score:X6.number(),text:X6.string()})).nullable()}))),vL4=g$({id:"openai.file_search",inputSchema:X6.object({}),outputSchema:_L4}),bL4=W0(()=>r(w7.object({action:w7.enum(["generate","edit","auto"]).optional(),background:w7.enum(["auto","opaque","transparent"]).optional(),inputFidelity:w7.enum(["low","high"]).optional(),inputImageMask:w7.object({fileId:w7.string().optional(),imageUrl:w7.string().optional()}).optional(),model:w7.string().optional(),moderation:w7.enum(["auto","low"]).optional(),outputCompression:w7.number().int().min(0).max(100).optional(),outputFormat:w7.enum(["png","jpeg","webp"]).optional(),partialImages:w7.number().int().min(0).max(3).optional(),quality:w7.enum(["auto","low","medium","high","xhigh","max"]).optional(),size:w7.union([w7.enum(["1024x1024","1024x1536","1536x1024","auto"]),w7.string().regex(/^\d+x\d+$/)]).optional()}).strict())),xL4=W0(()=>r(w7.object({}))),fL4=W0(()=>r(w7.object({result:w7.string()}))),yL4=g$({id:"openai.image_generation",inputSchema:xL4,outputSchema:fL4}),aG$=W0(()=>r(CG.object({action:CG.object({type:CG.literal("exec"),command:CG.array(CG.string()),timeoutMs:CG.number().optional(),user:CG.string().optional(),workingDirectory:CG.string().optional(),env:CG.record(CG.string(),CG.string()).optional()})}))),eG$=W0(()=>r(CG.object({output:CG.string()}))),hL4=TF({id:"openai.local_shell",inputSchema:aG$,outputSchema:eG$}),$3$=W0(()=>r(k$.object({action:k$.object({commands:k$.array(k$.string()),timeoutMs:k$.number().optional(),maxOutputLength:k$.number().optional()})}))),ya0=W0(()=>r(k$.object({output:k$.array(k$.object({stdout:k$.string(),stderr:k$.string(),outcome:k$.discriminatedUnion("type",[k$.object({type:k$.literal("timeout")}),k$.object({type:k$.literal("exit"),exitCode:k$.number()})])}))}))),uL4=k$.array(k$.discriminatedUnion("type",[k$.object({type:k$.literal("skillReference"),providerReference:k$.record(k$.string(),k$.string()),version:k$.string().optional()}),k$.object({type:k$.literal("inline"),name:k$.string(),description:k$.string(),source:k$.object({type:k$.literal("base64"),mediaType:k$.literal("application/zip"),data:k$.string()})})])).optional(),lL4=W0(()=>r(k$.object({environment:k$.union([k$.object({type:k$.literal("containerAuto"),fileIds:k$.array(k$.string()).optional(),memoryLimit:k$.enum(["1g","4g","16g","64g"]).optional(),networkPolicy:k$.discriminatedUnion("type",[k$.object({type:k$.literal("disabled")}),k$.object({type:k$.literal("allowlist"),allowedDomains:k$.array(k$.string()),domainSecrets:k$.array(k$.object({domain:k$.string(),name:k$.string(),value:k$.string()})).optional()})]).optional(),skills:uL4}),k$.object({type:k$.literal("containerReference"),containerId:k$.string()}),k$.object({type:k$.literal("local").optional(),skills:k$.array(k$.object({name:k$.string(),description:k$.string(),path:k$.string()})).optional()})]).optional()}))),cL4=TF({id:"openai.shell",inputSchema:$3$,outputSchema:ya0}),mL4=W0(()=>r(NJ.object({execution:NJ.enum(["server","client"]).optional(),description:NJ.string().optional(),parameters:NJ.record(NJ.string(),NJ.unknown()).optional()}))),ga0=W0(()=>r(NJ.object({arguments:NJ.unknown().optional(),call_id:NJ.string().nullish()}))),ha0=W0(()=>r(NJ.object({tools:NJ.array(NJ.record(NJ.string(),NJ.unknown()))}))),dL4=TF({id:"openai.tool_search",inputSchema:ga0,outputSchema:ha0}),pL4=W0(()=>r(l4.object({externalWebAccess:l4.boolean().optional(),filters:l4.object({allowedDomains:l4.array(l4.string()).optional(),blockedDomains:l4.array(l4.string()).optional()}).optional(),searchContextSize:l4.enum(["low","medium","high"]).optional(),userLocation:l4.object({type:l4.literal("approximate"),country:l4.string().optional(),city:l4.string().optional(),region:l4.string().optional(),timezone:l4.string().optional()}).optional()}))),nL4=W0(()=>r(l4.object({}))),tL4=W0(()=>r(l4.object({action:l4.discriminatedUnion("type",[l4.object({type:l4.literal("search"),query:l4.string().optional(),queries:l4.array(l4.string()).optional()}),l4.object({type:l4.literal("openPage"),url:l4.string().nullish()}),l4.object({type:l4.literal("findInPage"),url:l4.string().nullish(),pattern:l4.string().nullish()})]).optional(),sources:l4.array(l4.discriminatedUnion("type",[l4.object({type:l4.literal("url"),url:l4.string()}),l4.object({type:l4.literal("api"),name:l4.string()})])).optional()}))),oL4=g$({id:"openai.web_search",inputSchema:nL4,outputSchema:tL4}),sL4=W0(()=>r(MZ.object({searchContextSize:MZ.enum(["low","medium","high"]).optional(),userLocation:MZ.object({type:MZ.literal("approximate"),country:MZ.string().optional(),city:MZ.string().optional(),region:MZ.string().optional(),timezone:MZ.string().optional()}).optional()}))),aL4=W0(()=>r(MZ.object({}))),eL4=W0(()=>r(MZ.object({action:MZ.discriminatedUnion("type",[MZ.object({type:MZ.literal("search"),query:MZ.string().optional()}),MZ.object({type:MZ.literal("openPage"),url:MZ.string().nullish()}),MZ.object({type:MZ.literal("findInPage"),url:MZ.string().nullish(),pattern:MZ.string().nullish()})]).optional()}))),$w4=g$({id:"openai.web_search_preview",inputSchema:aL4,outputSchema:eL4}),ua0=D4.lazy(()=>D4.union([D4.string(),D4.number(),D4.boolean(),D4.null(),D4.array(ua0),D4.record(D4.string(),ua0)])),Zw4=W0(()=>r(D4.object({serverLabel:D4.string(),allowedTools:D4.union([D4.array(D4.string()),D4.object({readOnly:D4.boolean().optional(),toolNames:D4.array(D4.string()).optional()})]).optional(),authorization:D4.string().optional(),connectorId:D4.string().optional(),headers:D4.record(D4.string(),D4.string()).optional(),requireApproval:D4.union([D4.enum(["always","never"]),D4.object({never:D4.object({toolNames:D4.array(D4.string()).optional()}).optional()})]).optional(),serverDescription:D4.string().optional(),serverUrl:D4.string().optional()}).refine(($)=>$.serverUrl!=null||$.connectorId!=null,"One of serverUrl or connectorId must be provided."))),Qw4=W0(()=>r(D4.object({}))),Yw4=W0(()=>r(D4.object({type:D4.literal("call"),serverLabel:D4.string(),name:D4.string(),arguments:D4.string(),output:D4.string().nullish(),error:D4.union([D4.string(),ua0]).optional()}))),Xw4=g$({id:"openai.mcp",inputSchema:Qw4,outputSchema:Yw4}),Z3$=W0(()=>r(ml.object({code:ml.string(),fingerprint:ml.string()}))),Q3$=W0(()=>r(ml.object({result:ml.string(),status:ml.enum(["completed","incomplete"])}))),Gw4=g$({id:"openai.programmatic_tool_calling",inputSchema:Z3$,outputSchema:Q3$,supportsDeferredResults:!0}),Kw4={applyPatch:jL4,customTool:SL4,codeInterpreter:TL4,computer:ML4,fileSearch:vL4,imageGeneration:gL4,localShell:hL4,shell:cL4,webSearchPreview:$w4,webSearch:rL4,mcp:Jw4,programmaticToolCalling:Ww4,toolSearch:iL4};dl=R.lazy(()=>R.union([R.string(),R.number(),R.boolean(),R.null(),R.array(dl),R.record(R.string(),dl.optional())])),Ca0=R.record(R.string(),dl.optional()),ca0=R.intersection(Ca0,R.object({input_tokens:R.number(),input_tokens_details:R.intersection(Ca0,R.object({cached_tokens:R.number().nullish(),cache_write_tokens:R.number().nullish(),orchestration_input_tokens:R.number().nullish(),orchestration_input_cached_tokens:R.number().nullish()})).nullish(),output_tokens:R.number(),output_tokens_details:R.intersection(Ca0,R.object({reasoning_tokens:R.number().nullish(),orchestration_output_tokens:R.number().nullish()})).nullish(),total_tokens:R.number().optional()})),Hw4=R.object({id:R.string(),code:R.string().nullish(),message:R.string().nullish()}),zG$=R.discriminatedUnion("type",[R.object({type:R.literal("click"),button:R.enum(["left","right","wheel","back","forward"]),x:R.number(),y:R.number(),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("double_click"),x:R.number(),y:R.number(),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("drag"),path:R.array(R.object({x:R.number(),y:R.number()})),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("keypress"),keys:R.array(R.string())}),R.object({type:R.literal("move"),x:R.number(),y:R.number(),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("screenshot")}),R.object({type:R.literal("scroll"),x:R.number(),y:R.number(),scroll_x:R.number(),scroll_y:R.number(),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("type"),text:R.string()}),R.object({type:R.literal("wait")})]),ma0=R.object({type:R.literal("computer_call"),id:R.string(),call_id:R.string().nullish(),status:R.enum(["in_progress","completed","incomplete"]),action:zG$.nullish(),actions:R.array(zG$).nullish(),pending_safety_checks:R.array(Hw4).nullish()}),da0=R.discriminatedUnion("type",[R.object({type:R.literal("direct")}),R.object({type:R.literal("program"),caller_id:R.string()})]),ia0=R.object({type:R.literal("program"),id:R.string(),call_id:R.string(),code:R.string(),fingerprint:R.string()}),pa0=R.object({type:R.literal("program_output"),id:R.string(),call_id:R.string(),result:R.string(),status:R.enum(["completed","incomplete"])}),na0=R.object({type:R.literal("local_shell_call"),id:R.string(),call_id:R.string(),action:R.object({type:R.literal("exec"),command:R.array(R.string()),timeout_ms:R.number().optional(),user:R.string().optional(),working_directory:R.string().optional(),env:R.record(R.string(),R.string()).optional()})}),Fw4=R.object({type:R.literal("error"),sequence_number:R.number(),error:R.object({type:R.string(),code:R.string(),message:R.string(),param:R.string().nullish()})}),Uw4=R.object({type:R.literal("error"),sequence_number:R.number(),code:R.string().nullish(),message:R.string(),param:R.string().nullish()}),Nw4=new Set(["error","response.apply_patch_call_operation_diff.delta","response.apply_patch_call_operation_diff.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.completed","response.created","response.custom_tool_call_input.delta","response.failed","response.function_call_arguments.delta","response.function_call_arguments.done","response.image_generation_call.partial_image","response.in_progress","response.incomplete","response.output_item.added","response.output_item.done","response.output_text.annotation.added","response.output_text.delta","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta"]),Bw4=new Set(["apply_patch_call","code_interpreter_call","compaction","computer_call","custom_tool_call","file_search_call","function_call","image_generation_call","local_shell_call","mcp_approval_request","mcp_call","mcp_list_tools","message","program","program_output","reasoning","shell_call","shell_call_output","tool_search_call","tool_search_output","web_search_call"]);Dw4=W0(()=>r(R.union([R.object({type:R.literal("response.output_text.delta"),item_id:R.string(),output_index:R.number().nullish(),delta:R.string(),logprobs:R.array(R.object({token:R.string(),logprob:R.number(),top_logprobs:R.array(R.object({token:R.string(),logprob:R.number()}))})).nullish()}),R.object({type:R.enum(["response.completed","response.incomplete"]),response:R.object({incomplete_details:R.object({reason:R.string()}).nullish(),usage:ca0.nullish(),reasoning:R.object({context:R.string().nullish()}).nullish(),service_tier:R.string().nullish()})}),R.object({type:R.literal("response.failed"),sequence_number:R.number(),response:R.object({error:R.object({code:R.string().nullish(),message:R.string()}).nullish(),incomplete_details:R.object({reason:R.string()}).nullish(),usage:ca0.nullish(),reasoning:R.object({context:R.string().nullish()}).nullish(),service_tier:R.string().nullish()})}),R.object({type:R.literal("response.created"),response:R.object({id:R.string(),created_at:R.number(),model:R.string(),service_tier:R.string().nullish()})}),R.object({type:R.literal("response.in_progress"),response:R.object({id:R.string(),created_at:R.number(),model:R.string(),service_tier:R.string().nullish()})}),R.object({type:R.literal("response.output_item.added"),output_index:R.number(),item:R.discriminatedUnion("type",[R.object({type:R.literal("message"),id:R.string(),phase:R.enum(["commentary","final_answer"]).nullish()}),R.object({type:R.literal("reasoning"),id:R.string(),encrypted_content:R.string().nullish()}),R.object({type:R.literal("function_call"),id:R.string(),call_id:R.string(),name:R.string(),arguments:R.string(),async:R.boolean().nullish(),namespace:R.string().nullish(),caller:da0.nullish()}),ia0,pa0,R.object({type:R.literal("web_search_call"),id:R.string(),status:R.string()}),ma0,R.object({type:R.literal("file_search_call"),id:R.string()}),na0,R.object({type:R.literal("image_generation_call"),id:R.string()}),R.object({type:R.literal("code_interpreter_call"),id:R.string(),container_id:R.string(),code:R.string().nullable(),outputs:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("logs"),logs:R.string()}),R.object({type:R.literal("image"),url:R.string()})])).nullable(),status:R.string()}),R.object({type:R.literal("mcp_call"),id:R.string(),status:R.string(),approval_request_id:R.string().nullish()}),R.object({type:R.literal("mcp_list_tools"),id:R.string()}),R.object({type:R.literal("mcp_approval_request"),id:R.string()}),R.object({type:R.literal("apply_patch_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed"]),operation:R.discriminatedUnion("type",[R.object({type:R.literal("create_file"),path:R.string(),diff:R.string()}),R.object({type:R.literal("delete_file"),path:R.string()}),R.object({type:R.literal("update_file"),path:R.string(),diff:R.string()})])}),R.object({type:R.literal("custom_tool_call"),id:R.string(),call_id:R.string(),name:R.string(),input:R.string(),async:R.boolean().nullish()}),R.object({type:R.literal("shell_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),action:R.object({commands:R.array(R.string())})}),R.object({type:R.literal("compaction"),id:R.string(),encrypted_content:R.string().nullish()}),R.object({type:R.literal("shell_call_output"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),output:R.array(R.object({stdout:R.string(),stderr:R.string(),outcome:R.discriminatedUnion("type",[R.object({type:R.literal("timeout")}),R.object({type:R.literal("exit"),exit_code:R.number()})])}))}),R.object({type:R.literal("tool_search_call"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),arguments:R.unknown()}),R.object({type:R.literal("tool_search_output"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),tools:R.array(R.record(R.string(),dl.optional()))})])}),R.object({type:R.literal("response.output_item.done"),output_index:R.number(),item:R.discriminatedUnion("type",[R.object({type:R.literal("message"),id:R.string(),phase:R.enum(["commentary","final_answer"]).nullish()}),R.object({type:R.literal("reasoning"),id:R.string(),encrypted_content:R.string().nullish()}),R.object({type:R.literal("function_call"),id:R.string(),call_id:R.string(),name:R.string(),arguments:R.string(),async:R.boolean().nullish(),status:R.enum(["in_progress","completed","incomplete"]),namespace:R.string().nullish(),caller:da0.nullish()}),ia0,pa0,R.object({type:R.literal("custom_tool_call"),id:R.string(),call_id:R.string(),name:R.string(),input:R.string(),async:R.boolean().nullish(),status:R.literal("completed")}),R.object({type:R.literal("code_interpreter_call"),id:R.string(),code:R.string().nullable(),container_id:R.string(),outputs:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("logs"),logs:R.string()}),R.object({type:R.literal("image"),url:R.string()})])).nullable()}),R.object({type:R.literal("image_generation_call"),id:R.string(),result:R.string()}),R.object({type:R.literal("web_search_call"),id:R.string(),status:R.string(),action:R.discriminatedUnion("type",[R.object({type:R.literal("search"),query:R.string().nullish(),queries:R.array(R.string()).nullish(),sources:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("url"),url:R.string()}),R.object({type:R.literal("api"),name:R.string()})])).nullish()}),R.object({type:R.literal("open_page"),url:R.string().nullish()}),R.object({type:R.literal("find_in_page"),url:R.string().nullish(),pattern:R.string().nullish()})]).nullish()}),R.object({type:R.literal("file_search_call"),id:R.string(),queries:R.array(R.string()),results:R.array(R.object({attributes:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])),file_id:R.string(),filename:R.string(),score:R.number(),text:R.string()})).nullish()}),na0,ma0,R.object({type:R.literal("mcp_call"),id:R.string(),status:R.string(),arguments:R.string(),name:R.string(),server_label:R.string(),output:R.string().nullish(),error:R.union([R.string(),R.object({type:R.string().optional(),code:R.union([R.number(),R.string()]).optional(),message:R.string().optional()}).loose()]).nullish(),approval_request_id:R.string().nullish()}),R.object({type:R.literal("mcp_list_tools"),id:R.string(),server_label:R.string(),tools:R.array(R.object({name:R.string(),description:R.string().optional(),input_schema:R.any(),annotations:R.record(R.string(),R.unknown()).optional()})),error:R.union([R.string(),R.object({type:R.string().optional(),code:R.union([R.number(),R.string()]).optional(),message:R.string().optional()}).loose()]).optional()}),R.object({type:R.literal("mcp_approval_request"),id:R.string(),server_label:R.string(),name:R.string(),arguments:R.string(),approval_request_id:R.string().optional()}),R.object({type:R.literal("apply_patch_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed"]),operation:R.discriminatedUnion("type",[R.object({type:R.literal("create_file"),path:R.string(),diff:R.string()}),R.object({type:R.literal("delete_file"),path:R.string()}),R.object({type:R.literal("update_file"),path:R.string(),diff:R.string()})])}),R.object({type:R.literal("shell_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),action:R.object({commands:R.array(R.string())})}),R.object({type:R.literal("compaction"),id:R.string(),encrypted_content:R.string()}),R.object({type:R.literal("shell_call_output"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),output:R.array(R.object({stdout:R.string(),stderr:R.string(),outcome:R.discriminatedUnion("type",[R.object({type:R.literal("timeout")}),R.object({type:R.literal("exit"),exit_code:R.number()})])}))}),R.object({type:R.literal("tool_search_call"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),arguments:R.unknown()}),R.object({type:R.literal("tool_search_output"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),tools:R.array(R.record(R.string(),dl.optional()))})])}),R.object({type:R.literal("response.function_call_arguments.delta"),item_id:R.string(),output_index:R.number(),delta:R.string()}),R.object({type:R.literal("response.function_call_arguments.done"),item_id:R.string(),output_index:R.number(),arguments:R.string()}),R.object({type:R.literal("response.custom_tool_call_input.delta"),item_id:R.string(),output_index:R.number(),delta:R.string()}),R.object({type:R.literal("response.image_generation_call.partial_image"),item_id:R.string(),output_index:R.number(),partial_image_b64:R.string()}),R.object({type:R.literal("response.code_interpreter_call_code.delta"),item_id:R.string(),output_index:R.number(),delta:R.string()}),R.object({type:R.literal("response.code_interpreter_call_code.done"),item_id:R.string(),output_index:R.number(),code:R.string()}),R.object({type:R.literal("response.output_text.annotation.added"),annotation:R.discriminatedUnion("type",[R.object({type:R.literal("url_citation"),start_index:R.number(),end_index:R.number(),url:R.string(),title:R.string()}),R.object({type:R.literal("file_citation"),file_id:R.string(),filename:R.string(),index:R.number()}),R.object({type:R.literal("container_file_citation"),container_id:R.string(),file_id:R.string(),filename:R.string(),start_index:R.number(),end_index:R.number()}),R.object({type:R.literal("file_path"),file_id:R.string(),index:R.number()})])}),R.object({type:R.literal("response.reasoning_summary_part.added"),item_id:R.string(),output_index:R.number().nullish(),summary_index:R.number()}),R.object({type:R.literal("response.reasoning_summary_text.delta"),item_id:R.string(),output_index:R.number().nullish(),summary_index:R.number(),delta:R.string()}),R.object({type:R.literal("response.reasoning_summary_part.done"),item_id:R.string(),output_index:R.number().nullish(),summary_index:R.number()}),R.object({type:R.literal("response.apply_patch_call_operation_diff.delta"),item_id:R.string(),output_index:R.number(),delta:R.string(),obfuscation:R.string().nullish()}),R.object({type:R.literal("response.apply_patch_call_operation_diff.done"),item_id:R.string(),output_index:R.number(),diff:R.string()}),Fw4,Uw4,R.object({type:R.string()}).loose().refine(($)=>!Ow4($),{message:"Known response chunk failed schema validation"}).transform(($)=>({type:"unknown_chunk",message:$.type}))]))),Y3$=W0(()=>r(R.object({id:R.string().optional(),created_at:R.number().optional(),error:R.object({message:R.string(),type:R.string(),param:R.string().nullish(),code:R.string()}).nullish(),model:R.string().optional(),output:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("message"),role:R.literal("assistant"),id:R.string(),phase:R.enum(["commentary","final_answer"]).nullish(),content:R.array(R.object({type:R.literal("output_text"),text:R.string(),logprobs:R.array(R.object({token:R.string(),logprob:R.number(),top_logprobs:R.array(R.object({token:R.string(),logprob:R.number()}))})).nullish(),annotations:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("url_citation"),start_index:R.number(),end_index:R.number(),url:R.string(),title:R.string()}),R.object({type:R.literal("file_citation"),file_id:R.string(),filename:R.string(),index:R.number()}),R.object({type:R.literal("container_file_citation"),container_id:R.string(),file_id:R.string(),filename:R.string(),start_index:R.number(),end_index:R.number()}),R.object({type:R.literal("file_path"),file_id:R.string(),index:R.number()})]))}))}),R.object({type:R.literal("web_search_call"),id:R.string(),status:R.string(),action:R.discriminatedUnion("type",[R.object({type:R.literal("search"),query:R.string().nullish(),queries:R.array(R.string()).nullish(),sources:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("url"),url:R.string()}),R.object({type:R.literal("api"),name:R.string()})])).nullish()}),R.object({type:R.literal("open_page"),url:R.string().nullish()}),R.object({type:R.literal("find_in_page"),url:R.string().nullish(),pattern:R.string().nullish()})]).nullish()}),R.object({type:R.literal("file_search_call"),id:R.string(),queries:R.array(R.string()),results:R.array(R.object({attributes:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])),file_id:R.string(),filename:R.string(),score:R.number(),text:R.string()})).nullish()}),R.object({type:R.literal("code_interpreter_call"),id:R.string(),code:R.string().nullable(),container_id:R.string(),outputs:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("logs"),logs:R.string()}),R.object({type:R.literal("image"),url:R.string()})])).nullable()}),R.object({type:R.literal("image_generation_call"),id:R.string(),result:R.string()}),na0,R.object({type:R.literal("function_call"),call_id:R.string(),name:R.string(),arguments:R.string(),id:R.string(),async:R.boolean().nullish(),namespace:R.string().nullish(),caller:da0.nullish()}),ia0,pa0,R.object({type:R.literal("custom_tool_call"),call_id:R.string(),name:R.string(),input:R.string(),id:R.string(),async:R.boolean().nullish()}),ma0,R.object({type:R.literal("reasoning"),id:R.string(),encrypted_content:R.string().nullish(),summary:R.array(R.object({type:R.literal("summary_text"),text:R.string()}))}),R.object({type:R.literal("mcp_call"),id:R.string(),status:R.string(),arguments:R.string(),name:R.string(),server_label:R.string(),output:R.string().nullish(),error:R.union([R.string(),R.object({type:R.string().optional(),code:R.union([R.number(),R.string()]).optional(),message:R.string().optional()}).loose()]).nullish(),approval_request_id:R.string().nullish()}),R.object({type:R.literal("mcp_list_tools"),id:R.string(),server_label:R.string(),tools:R.array(R.object({name:R.string(),description:R.string().optional(),input_schema:R.any(),annotations:R.record(R.string(),R.unknown()).optional()})),error:R.union([R.string(),R.object({type:R.string().optional(),code:R.union([R.number(),R.string()]).optional(),message:R.string().optional()}).loose()]).optional()}),R.object({type:R.literal("mcp_approval_request"),id:R.string(),server_label:R.string(),name:R.string(),arguments:R.string(),approval_request_id:R.string().optional()}),R.object({type:R.literal("apply_patch_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed"]),operation:R.discriminatedUnion("type",[R.object({type:R.literal("create_file"),path:R.string(),diff:R.string()}),R.object({type:R.literal("delete_file"),path:R.string()}),R.object({type:R.literal("update_file"),path:R.string(),diff:R.string()})])}),R.object({type:R.literal("shell_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),action:R.object({commands:R.array(R.string())})}),R.object({type:R.literal("compaction"),id:R.string(),encrypted_content:R.string()}),R.object({type:R.literal("shell_call_output"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),output:R.array(R.object({stdout:R.string(),stderr:R.string(),outcome:R.discriminatedUnion("type",[R.object({type:R.literal("timeout")}),R.object({type:R.literal("exit"),exit_code:R.number()})])}))}),R.object({type:R.literal("tool_search_call"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),arguments:R.unknown()}),R.object({type:R.literal("tool_search_output"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),tools:R.array(R.record(R.string(),dl.optional()))})])).optional(),service_tier:R.string().nullish(),reasoning:R.object({context:R.string().nullish()}).nullish(),incomplete_details:R.object({reason:R.string()}).nullish(),usage:ca0.nullish()})));zw4=_a0.object({itemId:_a0.string().nullish(),reasoningEncryptedContent:_a0.string().nullish()}),Pw4=["o1","o1-2024-12-17","o3","o3-2025-04-16","o3-mini","o3-mini-2025-01-31","o4-mini","o4-mini-2025-04-16","gpt-5","gpt-5-2025-08-07","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06","gpt-5.1","gpt-5.1-chat-latest","gpt-5.1-codex-mini","gpt-5.1-codex","gpt-5.1-codex-max","gpt-5.2","gpt-5.2-chat-latest","gpt-5.2-pro","gpt-5.2-codex","gpt-5.3-chat-latest","gpt-5.3-codex","gpt-5.4","gpt-5.4-2026-03-05","gpt-5.4-mini","gpt-5.4-mini-2026-03-17","gpt-5.4-nano","gpt-5.4-nano-2026-03-17","gpt-5.4-pro","gpt-5.4-pro-2026-03-05","gpt-5.5","gpt-5.5-2026-04-23","gpt-5.6","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra"],xu5=["gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-3.5-turbo-0125","gpt-3.5-turbo","gpt-3.5-turbo-1106","gpt-5-chat-latest",...Pw4],IG$=W0(()=>r(r8.object({conversation:r8.string().nullish(),include:r8.array(r8.enum(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),includeWebSearchSources:r8.boolean().optional(),instructions:r8.string().nullish(),logprobs:r8.union([r8.boolean(),r8.number().min(1).max(X3$)]).optional(),maxToolCalls:r8.number().nullish(),metadata:r8.any().nullish(),parallelToolCalls:r8.boolean().nullish(),previousResponseId:r8.string().nullish(),promptCacheKey:r8.string().nullish(),promptCacheOptions:r8.object({mode:r8.enum(["implicit","explicit"]).optional(),ttl:r8.literal("30m").optional()}).optional(),promptCacheRetention:r8.enum(["in_memory","24h"]).nullish(),reasoningEffort:r8.string().nullish(),reasoningEffortUpdate:r8.enum(["low","medium","high","xhigh","max"]).optional(),reasoningMode:r8.enum(["standard","pro"]).optional(),reasoningContext:r8.enum(["auto","current_turn","all_turns"]).optional(),reasoningSummary:r8.string().nullish(),safetyIdentifier:r8.string().nullish(),serviceTier:r8.enum(["auto","flex","priority","fast","ultrafast","default"]).nullish(),store:r8.boolean().nullish(),passThroughUnsupportedFiles:r8.boolean().optional(),strictJsonSchema:r8.boolean().nullish(),textVerbosity:r8.enum(["low","medium","high"]).nullish(),truncation:r8.enum(["auto","disabled"]).nullish(),user:r8.string().nullish(),systemMessageMode:r8.enum(["system","developer","remove"]).optional(),forceReasoning:r8.boolean().optional(),contextManagement:r8.array(r8.object({type:r8.literal("compaction"),compactThreshold:r8.number()})).nullish(),compactionTrigger:r8.boolean().optional(),allowedTools:r8.object({toolNames:r8.array(r8.string()).min(1),mode:r8.enum(["auto","required"]).optional()}).optional()})));J3$={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},G3$=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls=J3$,this.modelId=Z,this.config=Q}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Lw4(Z.config))}get provider(){return this.config.provider}static async prepareRequest({modelId:Z,config:Q,options:{maxOutputTokens:Y,temperature:X,stopSequences:J,topP:G,topK:W,presencePenalty:K,frequencyPenalty:H,seed:F,prompt:U,reasoning:N,providerOptions:B,tools:O,toolChoice:L,responseFormat:w}}){var j,E,z,T,P,A,q,x,_,V,y,g,l,n;let p=[],F0=dG$(Z);if(W!=null)p.push({type:"unsupported",feature:"topK"});if(F!=null)p.push({type:"unsupported",feature:"seed"});if(K!=null)p.push({type:"unsupported",feature:"presencePenalty"});if(H!=null)p.push({type:"unsupported",feature:"frequencyPenalty"});if(J!=null)p.push({type:"unsupported",feature:"stopSequences"});let V0=Q.provider.includes("azure")?"azure":"openai",G0=await I$({provider:V0,providerOptions:B,schema:IG$});if(G0==null&&V0!=="openai")G0=await I$({provider:"openai",providerOptions:B,schema:IG$});let H0=(j=G0==null?void 0:G0.reasoningEffort)!=null?j:XB(N)?N:void 0;if(H0!=null&&F0.supportedReasoningEfforts!=null&&!F0.supportedReasoningEfforts.includes(H0))p.push({type:"unsupported",feature:"reasoningEffort",details:`${Z} only supports the following reasoning efforts: ${F0.supportedReasoningEfforts.join(", ")}`}),H0=void 0;let X0=(G0==null?void 0:G0.reasoningSummary)!==void 0?G0.reasoningSummary:H0!=null&&H0!=="none"?"detailed":void 0,Z0=(E=G0==null?void 0:G0.forceReasoning)!=null?E:F0.isReasoningModel;if((G0==null?void 0:G0.conversation)&&(G0==null?void 0:G0.previousResponseId))p.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});let Y0=Jl({tools:O,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.computer":"computer","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search","openai.programmatic_tool_calling":"programmatic_tool_calling"}}),o=new Set,J0=new Set,{tools:c0,toolChoice:k0,toolWarnings:j1}=await Aw4({tools:O,toolChoice:L,allowedTools:(z=G0==null?void 0:G0.allowedTools)!=null?z:void 0,toolNameMapping:Y0,customProviderToolNames:o,outputSchemaToolNames:J0,supportsAsyncToolCalling:F0.supportsAsyncToolCalling}),{input:d0,warnings:L0}=await Ew4({prompt:U,toolNameMapping:Y0,systemMessageMode:(T=G0==null?void 0:G0.systemMessageMode)!=null?T:Z0?"developer":F0.systemMessageMode,providerOptionsName:V0,explicitMessageItemType:Q.explicitMessageItemType,fileIdPrefixes:Q.fileIdPrefixes,passThroughUnsupportedFiles:(P=G0==null?void 0:G0.passThroughUnsupportedFiles)!=null?P:!1,store:(A=G0==null?void 0:G0.store)!=null?A:!0,hasConversation:(G0==null?void 0:G0.conversation)!=null,hasPreviousResponseId:(G0==null?void 0:G0.previousResponseId)!=null,hasLocalShellTool:w0("openai.local_shell"),hasShellTool:w0("openai.shell"),hasApplyPatchTool:w0("openai.apply_patch"),hasComputerTool:w0("openai.computer"),toolSearchToolName:Q0("openai.tool_search"),customProviderToolNames:o.size>0?o:void 0,outputSchemaToolNames:J0.size>0?J0:void 0});p.push(...L0);let j0=G0==null?void 0:G0.reasoningEffortUpdate,a0=j0==null||F0.supportsConfigurationUpdate&&(G0==null?void 0:G0.reasoningMode)!=="pro"&&(G0==null?void 0:G0.contextManagement)==null&&(G0==null?void 0:G0.truncation)!=="auto";if(j0!=null&&!a0)p.push({type:"unsupported",feature:"reasoningEffortUpdate",details:!F0.supportsConfigurationUpdate?"reasoningEffortUpdate is only supported by GPT-6 and later models":"reasoningEffortUpdate requires standard reasoning mode without automatic compaction or automatic truncation"});else if(j0!=null)d0.unshift({type:"configuration_update",reasoning:{effort:j0}});if(G0==null?void 0:G0.compactionTrigger)d0.push({type:"compaction_trigger"});let P1=(q=G0==null?void 0:G0.strictJsonSchema)!=null?q:!0,K1=(w==null?void 0:w.type)==="json"&&w.schema!=null?Fa(w.schema):void 0;if(K1!=null)p.push(...K1.warnings);let v0=G0==null?void 0:G0.include;function l0(I1){if(v0==null)v0=[I1];else if(!v0.includes(I1))v0=[...v0,I1]}function Q0(I1){var H8;return(H8=O==null?void 0:O.find((B8)=>B8.type==="provider"&&B8.id===I1))==null?void 0:H8.name}function w0(I1){return Q0(I1)!=null}let e=typeof(G0==null?void 0:G0.logprobs)==="number"?G0==null?void 0:G0.logprobs:(G0==null?void 0:G0.logprobs)===!0?X3$:void 0;if(e)l0("message.output_text.logprobs");let i=(x=O==null?void 0:O.find((I1)=>I1.type==="provider"&&(I1.id==="openai.web_search"||I1.id==="openai.web_search_preview")))==null?void 0:x.name;if(i&&Q.supportsWebSearchSourcesInclude!==!1&&(G0==null?void 0:G0.includeWebSearchSources)!==!1)l0("web_search_call.action.sources");if(w0("openai.code_interpreter"))l0("code_interpreter_call.outputs");let m0=G0==null?void 0:G0.store;if(m0===!1&&Z0)l0("reasoning.encrypted_content");let I0={model:Z,input:d0,temperature:X,top_p:G,max_output_tokens:Y,...((w==null?void 0:w.type)==="json"||(G0==null?void 0:G0.textVerbosity))&&{text:{...(w==null?void 0:w.type)==="json"&&{format:K1!=null?{type:"json_schema",strict:P1,name:(_=w.name)!=null?_:"response",description:w.description,schema:K1.schema}:{type:"json_object"}},...(G0==null?void 0:G0.textVerbosity)&&{verbosity:G0.textVerbosity}}},conversation:G0==null?void 0:G0.conversation,max_tool_calls:G0==null?void 0:G0.maxToolCalls,metadata:G0==null?void 0:G0.metadata,parallel_tool_calls:G0==null?void 0:G0.parallelToolCalls,previous_response_id:G0==null?void 0:G0.previousResponseId,store:m0,user:G0==null?void 0:G0.user,instructions:G0==null?void 0:G0.instructions,service_tier:G0==null?void 0:G0.serviceTier,include:v0,prompt_cache_key:G0==null?void 0:G0.promptCacheKey,prompt_cache_options:G0==null?void 0:G0.promptCacheOptions,prompt_cache_retention:G0==null?void 0:G0.promptCacheRetention,safety_identifier:G0==null?void 0:G0.safetyIdentifier,top_logprobs:e,truncation:G0==null?void 0:G0.truncation,...(G0==null?void 0:G0.contextManagement)&&{context_management:G0.contextManagement.map((I1)=>({type:I1.type,compact_threshold:I1.compactThreshold}))},...Z0&&(H0!=null||X0!=null||(G0==null?void 0:G0.reasoningMode)!=null||(G0==null?void 0:G0.reasoningContext)!=null)&&{reasoning:{...H0!=null&&{effort:H0},...X0!=null&&{summary:X0},...(G0==null?void 0:G0.reasoningMode)!=null&&{mode:G0.reasoningMode},...(G0==null?void 0:G0.reasoningContext)!=null&&{context:G0.reasoningContext}}}};if(F0.supportsConfigurationUpdate&&I0.prompt_cache_retention!=null)I0.prompt_cache_retention=void 0,p.push({type:"unsupported",feature:"promptCacheRetention",details:"promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"});if(Z0){if(!(H0==="none"&&F0.supportsNonReasoningParameters)){if(I0.temperature!=null)I0.temperature=void 0,p.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(I0.top_p!=null)I0.top_p=void 0,p.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(F0.supportedReasoningEfforts!=null&&(I0.top_logprobs!=null||((V=I0.include)==null?void 0:V.includes("message.output_text.logprobs")))){I0.top_logprobs=void 0;let I1=(y=I0.include)==null?void 0:y.filter((H8)=>H8!=="message.output_text.logprobs");I0.include=I1!=null&&I1.length>0?I1:void 0,p.push({type:"unsupported",feature:"logprobs",details:"logprobs is not supported for reasoning models"})}}}else{if((G0==null?void 0:G0.reasoningEffort)!=null)p.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"});if((G0==null?void 0:G0.reasoningSummary)!=null)p.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"});if((G0==null?void 0:G0.reasoningMode)!=null)p.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"});if((G0==null?void 0:G0.reasoningContext)!=null)p.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})}if((G0==null?void 0:G0.serviceTier)==="flex"&&!F0.supportsFlexProcessing)p.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete I0.service_tier;if(((G0==null?void 0:G0.serviceTier)==="priority"||(G0==null?void 0:G0.serviceTier)==="fast")&&!F0.supportsPriorityProcessing)p.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete I0.service_tier;let t0=(n=(l=(g=O==null?void 0:O.find((I1)=>I1.type==="provider"&&I1.id==="openai.shell"))==null?void 0:g.args)==null?void 0:l.environment)==null?void 0:n.type,f0=t0==="containerAuto"||t0==="containerReference";return{webSearchToolName:i,args:{...I0,tools:c0,tool_choice:k0},warnings:[...p,...j1],store:m0,toolNameMapping:Y0,providerOptionsName:V0,isShellProviderExecuted:f0}}getArgs(Z){return $.prepareRequest({modelId:this.modelId,config:this.config,options:Z})}async doGenerate(Z){var Q,Y,X,J,G,W,K,H,F,U,N,B,O,L,w,j,E,z,T,P,A,q,x,_,V,y,g,l,n,p,F0,V0,G0,H0;let{args:X0,warnings:Z0,webSearchToolName:Y0,toolNameMapping:o,providerOptionsName:J0,isShellProviderExecuted:c0}=await this.getArgs(Z),k0=this.config.url({path:"/responses",modelId:this.modelId}),j1=SG$(Z.prompt),{responseHeaders:d0,value:L0,rawValue:j0}=await o1({url:k0,headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:X0,failedResponseHandler:R9,successfulResponseHandler:E1(Y3$),abortSignal:Z.abortSignal,fetch:this.config.fetch});if(L0.error)throw new W8({message:L0.error.message,url:k0,requestBodyValues:X0,statusCode:400,responseHeaders:d0,responseBody:j0,isRetryable:!1});if(L0.output==null){let e=(X=L0.incomplete_details)==null?void 0:X.reason;throw new W8({message:e?`Responses API returned no output (${e})`:"Responses API returned no output",url:k0,requestBodyValues:X0,statusCode:500,responseHeaders:d0,responseBody:j0,isRetryable:!1})}let a0=[],P1=[],K1=(G=(J=Z.tools)==null?void 0:J.filter((e)=>e.type==="function"))!=null?G:[],v0=!1,l0=[];for(let e of L0.output)switch(e.type){case"reasoning":{if(e.summary.length===0)e.summary.push({type:"summary_text",text:""});for(let i of e.summary)a0.push({type:"reasoning",text:i.text,providerMetadata:{[J0]:{itemId:e.id,reasoningEncryptedContent:(W=e.encrypted_content)!=null?W:null}}});break}case"image_generation_call":{a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName("image_generation"),result:{result:e.result}});break}case"tool_search_call":{let i=(K=e.call_id)!=null?K:e.id,m0=e.execution==="server";if(m0)l0.push(i);a0.push({type:"tool-call",toolCallId:i,toolName:o.toCustomToolName("tool_search"),input:JSON.stringify({arguments:e.arguments,call_id:e.call_id}),...m0?{providerExecuted:!0}:{},providerMetadata:{[J0]:{itemId:e.id}}});break}case"tool_search_output":{let i=(F=(H=e.call_id)!=null?H:l0.shift())!=null?F:e.id;a0.push({type:"tool-result",toolCallId:i,toolName:o.toCustomToolName("tool_search"),result:{tools:e.tools},providerMetadata:{[J0]:{itemId:e.id}}});break}case"local_shell_call":{a0.push({type:"tool-call",toolCallId:e.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:e.action}),providerMetadata:{[J0]:{itemId:e.id}}});break}case"shell_call":{a0.push({type:"tool-call",toolCallId:e.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:e.action.commands}}),...c0&&{providerExecuted:!0},providerMetadata:{[J0]:{itemId:e.id}}});break}case"shell_call_output":{a0.push({type:"tool-result",toolCallId:e.call_id,toolName:o.toCustomToolName("shell"),result:{output:e.output.map((i)=>({stdout:i.stdout,stderr:i.stderr,outcome:i.outcome.type==="exit"?{type:"exit",exitCode:i.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(let i of e.content){if(((N=(U=Z.providerOptions)==null?void 0:U[J0])==null?void 0:N.logprobs)&&i.logprobs)P1.push(i.logprobs);let m0={itemId:e.id,...e.phase!=null&&{phase:e.phase},...i.annotations.length>0&&{annotations:i.annotations}};a0.push({type:"text",text:i.text,providerMetadata:{[J0]:m0}});for(let I0 of i.annotations)if(I0.type==="url_citation")a0.push({type:"source",sourceType:"url",id:(L=(O=(B=this.config).generateId)==null?void 0:O.call(B))!=null?L:o8(),url:I0.url,title:I0.title});else if(I0.type==="file_citation")a0.push({type:"source",sourceType:"document",id:(E=(j=(w=this.config).generateId)==null?void 0:j.call(w))!=null?E:o8(),mediaType:"text/plain",title:I0.filename,filename:I0.filename,providerMetadata:{[J0]:{type:I0.type,fileId:I0.file_id,index:I0.index}}});else if(I0.type==="container_file_citation")a0.push({type:"source",sourceType:"document",id:(P=(T=(z=this.config).generateId)==null?void 0:T.call(z))!=null?P:o8(),mediaType:"text/plain",title:I0.filename,filename:I0.filename,providerMetadata:{[J0]:{type:I0.type,fileId:I0.file_id,containerId:I0.container_id}}});else if(I0.type==="file_path")a0.push({type:"source",sourceType:"document",id:(x=(q=(A=this.config).generateId)==null?void 0:q.call(A))!=null?x:o8(),mediaType:"application/octet-stream",title:I0.file_id,filename:I0.file_id,providerMetadata:{[J0]:{type:I0.type,fileId:I0.file_id,index:I0.index}}})}break}case"function_call":{v0=!0;let i=await TG$({toolCall:{toolCallId:e.call_id,toolName:e.name,input:e.arguments},tools:K1,providerOptionsName:J0,itemId:e.id});if(i!=null){a0.push(...i);break}a0.push({type:"tool-call",toolCallId:e.call_id,toolName:e.name,input:e.arguments,providerMetadata:{[J0]:{itemId:e.id,...e.async!=null&&{async:e.async},...e.namespace!=null&&{namespace:e.namespace},...e.caller!=null&&{caller:e.caller.type==="program"?{type:"program",callerId:e.caller.caller_id}:e.caller}}}});break}case"program":{a0.push({type:"tool-call",toolCallId:e.call_id,toolName:o.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:e.code,fingerprint:e.fingerprint}),providerExecuted:!0,providerMetadata:{[J0]:{itemId:e.id}}});break}case"program_output":{a0.push({type:"tool-result",toolCallId:e.call_id,toolName:o.toCustomToolName("programmatic_tool_calling"),result:{result:e.result,status:e.status},providerMetadata:{[J0]:{itemId:e.id}}});break}case"custom_tool_call":{v0=!0;let i=o.toCustomToolName(e.name);a0.push({type:"tool-call",toolCallId:e.call_id,toolName:i,input:JSON.stringify(e.input),providerMetadata:{[J0]:{itemId:e.id,...e.async!=null&&{async:e.async}}}});break}case"web_search_call":{a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName(Y0!=null?Y0:"web_search"),input:JSON.stringify({}),providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName(Y0!=null?Y0:"web_search"),result:sa0(e.action)});break}case"mcp_call":{let i=e.approval_request_id!=null?(_=j1[e.approval_request_id])!=null?_:e.id:e.id,m0=`mcp.${e.name}`;a0.push({type:"tool-call",toolCallId:i,toolName:m0,input:e.arguments,providerExecuted:!0,dynamic:!0}),a0.push({type:"tool-result",toolCallId:i,toolName:m0,result:{type:"call",serverLabel:e.server_label,name:e.name,arguments:e.arguments,...e.output!=null?{output:e.output}:{},...e.error!=null?{error:e.error}:{}},providerMetadata:{[J0]:{itemId:e.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{let i=(V=e.approval_request_id)!=null?V:e.id,m0=(l=(g=(y=this.config).generateId)==null?void 0:g.call(y))!=null?l:o8(),I0=`mcp.${e.name}`;a0.push({type:"tool-call",toolCallId:m0,toolName:I0,input:e.arguments,providerExecuted:!0,dynamic:!0}),a0.push({type:"tool-approval-request",approvalId:i,toolCallId:m0});break}case"computer_call":{if(e.call_id==null){a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:e.status}});break}v0=!0;let i=o.toCustomToolName("computer");a0.push({type:"tool-call",toolCallId:e.call_id,toolName:i,input:JSON.stringify(CG$(e)),providerMetadata:{[J0]:{itemId:e.id}}});break}case"file_search_call":{a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName("file_search"),result:{queries:e.queries,results:(p=(n=e.results)==null?void 0:n.map((i)=>({attributes:i.attributes,fileId:i.file_id,filename:i.filename,score:i.score,text:i.text})))!=null?p:null}});break}case"code_interpreter_call":{a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:e.code,containerId:e.container_id}),providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:e.outputs}});break}case"apply_patch_call":{v0=!0,a0.push({type:"tool-call",toolCallId:e.call_id,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:e.call_id,operation:e.operation}),providerMetadata:{[J0]:{itemId:e.id}}});break}case"compaction":{a0.push({type:"custom",kind:"openai.compaction",providerMetadata:{[J0]:{type:"compaction",itemId:e.id,encryptedContent:e.encrypted_content}}});break}}let Q0={[J0]:{responseId:L0.id,...P1.length>0?{logprobs:P1}:{},...typeof L0.service_tier==="string"?{serviceTier:L0.service_tier}:{},...((F0=L0.reasoning)==null?void 0:F0.context)!=null?{reasoningContext:L0.reasoning.context}:{}}},w0=L0.usage;return{content:a0,finishReason:{unified:Z30({finishReason:(V0=L0.incomplete_details)==null?void 0:V0.reason,hasFunctionCall:v0}),raw:(H0=(G0=L0.incomplete_details)==null?void 0:G0.reason)!=null?H0:void 0},usage:la0(w0),request:{body:X0},response:{id:L0.id,timestamp:new Date(L0.created_at*1000),modelId:L0.model,headers:d0,body:j0},providerMetadata:Q0,warnings:Z0}}async doStream(Z){var Q,Y,X,J;let{args:G,warnings:W,webSearchToolName:K,toolNameMapping:H,store:F,providerOptionsName:U,isShellProviderExecuted:N}=await this.getArgs(Z),B=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:O,value:L}=await o1({url:B,headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:{...G,stream:!0},failedResponseHandler:R9,successfulResponseHandler:UY(Dw4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),w=await Qe0({stream:L,getError:(Z0)=>bG$(Z0)||_G$(Z0)&&Z0.response.error!=null?Z0:void 0,isOutputChunk:iw4,isAcceptedChunk:dw4,url:B,requestBodyValues:G,responseHeaders:O}),j=this,E=SG$(Z.prompt),z=(J=(X=Z.tools)==null?void 0:X.filter((Z0)=>Z0.type==="function"))!=null?J:[],T=new Map,P={unified:"other",raw:void 0},A=void 0,q=[],x=null,_={},V=[],y,g=!1,l={},n={},p=({itemId:Z0,outputIndex:Y0})=>{var o;return Y0==null?Z0:(o=n[Y0])!=null?o:Z0},F0,V0,G0=[],H0=!1;return{stream:w.pipeThrough(new TransformStream({start(Z0){Z0.enqueue({type:"stream-start",warnings:W})},transform(Z0,Y0){var o,J0,c0,k0,j1,d0,L0,j0,a0,P1,K1,v0,l0,Q0,w0,e,i,m0,I0,t0,f0,I1,H8,B8,m4,Q8,D5,x8,m6,O9,o0,D1,x$,h1,Y$,_8,r6,G4,a1,T8,n$,W$,Q9,ZQ,OZ;if(Z.includeRawChunks)Y0.enqueue({type:"raw",rawValue:Z0.rawValue});if(!Z0.success){let M0=Sw4(Z0.rawValue)?Cw4({value:Z0.rawValue,cause:Z0.error,url:B,requestBodyValues:G,responseHeaders:O}):Z0.error;H0=!0,P={unified:"error",raw:void 0},Y0.enqueue({type:"error",error:M0});return}let $0=Z0.value;if(vG$($0)){if($0.item.type==="function_call"){let M0=oa0({toolName:$0.item.name,tools:z});if(_[$0.output_index]={toolName:$0.item.name,toolCallId:$0.item.call_id,suppressInputStreaming:M0,bufferedInputDeltas:M0?[]:void 0,async:$0.item.async},!M0)Y0.enqueue({type:"tool-input-start",id:$0.item.call_id,toolName:$0.item.name})}else if($0.item.type==="custom_tool_call"){let M0=H.toCustomToolName($0.item.name);_[$0.output_index]={toolName:M0,toolCallId:$0.item.call_id,async:$0.item.async},Y0.enqueue({type:"tool-input-start",id:$0.item.call_id,toolName:M0})}else if($0.item.type==="web_search_call")_[$0.output_index]={toolName:H.toCustomToolName(K!=null?K:"web_search"),toolCallId:$0.item.id},Y0.enqueue({type:"tool-input-start",id:$0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),providerExecuted:!0}),Y0.enqueue({type:"tool-input-end",id:$0.item.id}),Y0.enqueue({type:"tool-call",toolCallId:$0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($0.item.type==="computer_call"){let M0=(o=$0.item.call_id)!=null?o:$0.item.id;_[$0.output_index]={toolName:H.toCustomToolName("computer"),toolCallId:M0},Y0.enqueue({type:"tool-input-start",id:M0,toolName:H.toCustomToolName("computer")})}else if($0.item.type==="code_interpreter_call")_[$0.output_index]={toolName:H.toCustomToolName("code_interpreter"),toolCallId:$0.item.id,codeInterpreter:{containerId:$0.item.container_id}},Y0.enqueue({type:"tool-input-start",id:$0.item.id,toolName:H.toCustomToolName("code_interpreter"),providerExecuted:!0}),Y0.enqueue({type:"tool-input-delta",id:$0.item.id,delta:`{"containerId":"${$0.item.container_id}","code":"`});else if($0.item.type==="file_search_call")Y0.enqueue({type:"tool-call",toolCallId:$0.item.id,toolName:H.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($0.item.type==="image_generation_call")Y0.enqueue({type:"tool-call",toolCallId:$0.item.id,toolName:H.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if($0.item.type==="tool_search_call"){let M0=$0.item.id,R1=H.toCustomToolName("tool_search"),f8=$0.item.execution==="server";if(_[$0.output_index]={toolName:R1,toolCallId:M0,toolSearchExecution:(J0=$0.item.execution)!=null?J0:"server"},f8)Y0.enqueue({type:"tool-input-start",id:M0,toolName:R1,providerExecuted:!0})}else if($0.item.type==="tool_search_output");else if($0.item.type==="mcp_call"||$0.item.type==="mcp_list_tools"||$0.item.type==="mcp_approval_request");else if($0.item.type==="apply_patch_call"){let{call_id:M0,operation:R1}=$0.item;if(_[$0.output_index]={toolName:H.toCustomToolName("apply_patch"),toolCallId:M0,applyPatch:{hasDiff:R1.type==="delete_file",endEmitted:R1.type==="delete_file"}},Y0.enqueue({type:"tool-input-start",id:M0,toolName:H.toCustomToolName("apply_patch")}),R1.type==="delete_file"){let f8=JSON.stringify({callId:M0,operation:R1});Y0.enqueue({type:"tool-input-delta",id:M0,delta:f8}),Y0.enqueue({type:"tool-input-end",id:M0})}else Y0.enqueue({type:"tool-input-delta",id:M0,delta:`{"callId":"${DA(M0)}","operation":{"type":"${DA(R1.type)}","path":"${DA(R1.path)}","diff":"`})}else if($0.item.type==="shell_call")_[$0.output_index]={toolName:H.toCustomToolName("shell"),toolCallId:$0.item.call_id};else if($0.item.type==="shell_call_output");else if($0.item.type==="message")n[$0.output_index]=$0.item.id,V.splice(0,V.length),y=(c0=$0.item.phase)!=null?c0:void 0,Y0.enqueue({type:"text-start",id:$0.item.id,providerMetadata:{[U]:{itemId:$0.item.id,...$0.item.phase!=null&&{phase:$0.item.phase}}}});else if(vG$($0)&&$0.item.type==="reasoning")n[$0.output_index]=$0.item.id,l[$0.item.id]={encryptedContent:$0.item.encrypted_content,summaryParts:{0:"active"}},Y0.enqueue({type:"reasoning-start",id:`${$0.item.id}:0`,providerMetadata:{[U]:{itemId:$0.item.id,reasoningEncryptedContent:(k0=$0.item.encrypted_content)!=null?k0:null}}})}else if(vw4($0)){if($0.item.type==="message"){let M0=p({itemId:$0.item.id,outputIndex:$0.output_index}),R1=(j1=$0.item.phase)!=null?j1:y;y=void 0,Y0.enqueue({type:"text-end",id:M0,providerMetadata:{[U]:{itemId:M0,...R1!=null&&{phase:R1},...V.length>0&&{annotations:V}}}}),n[$0.output_index]=void 0}else if($0.item.type==="function_call"){let M0=$0.item,R1=_[$0.output_index];_[$0.output_index]=void 0,g=!0;let f8=(d0=R1==null?void 0:R1.suppressInputStreaming)!=null?d0:oa0({toolName:M0.name,tools:z}),v=()=>{var c;if(f8){Y0.enqueue({type:"tool-input-start",id:M0.call_id,toolName:M0.name});let m=(c=R1==null?void 0:R1.bufferedInputDeltas)!=null?c:[];if(m.length>0)for(let M of m)Y0.enqueue({type:"tool-input-delta",id:M0.call_id,delta:M});else if(M0.arguments.length>0)Y0.enqueue({type:"tool-input-delta",id:M0.call_id,delta:M0.arguments})}Y0.enqueue({type:"tool-input-end",id:M0.call_id,...M0.namespace!=null&&{providerMetadata:{[U]:{namespace:M0.namespace}}}}),Y0.enqueue({type:"tool-call",toolCallId:M0.call_id,toolName:M0.name,input:M0.arguments,providerMetadata:{[U]:{itemId:M0.id,...M0.async!=null?{async:M0.async}:(R1==null?void 0:R1.async)!=null?{async:R1.async}:{},...M0.namespace!=null&&{namespace:M0.namespace},...M0.caller!=null&&{caller:M0.caller.type==="program"?{type:"program",callerId:M0.caller.caller_id}:M0.caller}}}})};if(!f8){v();return}return TG$({toolCall:{toolCallId:M0.call_id,toolName:M0.name,input:M0.arguments},tools:z,providerOptionsName:U,itemId:M0.id}).then((c)=>{if(c==null){v();return}for(let m of c)Y0.enqueue({type:"tool-input-start",id:m.toolCallId,toolName:m.toolName}),Y0.enqueue({type:"tool-input-delta",id:m.toolCallId,delta:m.input}),Y0.enqueue({type:"tool-input-end",id:m.toolCallId}),Y0.enqueue(m)})}else if($0.item.type==="program")Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:$0.item.code,fingerprint:$0.item.fingerprint}),providerExecuted:!0,providerMetadata:{[U]:{itemId:$0.item.id}}});else if($0.item.type==="program_output")Y0.enqueue({type:"tool-result",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("programmatic_tool_calling"),result:{result:$0.item.result,status:$0.item.status},providerMetadata:{[U]:{itemId:$0.item.id}}});else if($0.item.type==="custom_tool_call"){let M0=_[$0.output_index];_[$0.output_index]=void 0,g=!0;let R1=H.toCustomToolName($0.item.name);Y0.enqueue({type:"tool-input-end",id:$0.item.call_id}),Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:R1,input:JSON.stringify($0.item.input),providerMetadata:{[U]:{itemId:$0.item.id,...$0.item.async!=null?{async:$0.item.async}:(M0==null?void 0:M0.async)!=null?{async:M0.async}:{}}}})}else if($0.item.type==="web_search_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),result:sa0($0.item.action)});else if($0.item.type==="computer_call"){if(_[$0.output_index]=void 0,$0.item.call_id==null){Y0.enqueue({type:"tool-input-end",id:$0.item.id}),Y0.enqueue({type:"tool-call",toolCallId:$0.item.id,toolName:H.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$0.item.status}});return}g=!0;let M0=H.toCustomToolName("computer"),R1=JSON.stringify(CG$($0.item));Y0.enqueue({type:"tool-input-delta",id:$0.item.call_id,delta:R1}),Y0.enqueue({type:"tool-input-end",id:$0.item.call_id}),Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:M0,input:R1,providerMetadata:{[U]:{itemId:$0.item.id}}})}else if($0.item.type==="file_search_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName("file_search"),result:{queries:$0.item.queries,results:(j0=(L0=$0.item.results)==null?void 0:L0.map((M0)=>({attributes:M0.attributes,fileId:M0.file_id,filename:M0.filename,score:M0.score,text:M0.text})))!=null?j0:null}});else if($0.item.type==="code_interpreter_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName("code_interpreter"),result:{outputs:$0.item.outputs}});else if($0.item.type==="image_generation_call")Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName("image_generation"),result:{result:$0.item.result}});else if($0.item.type==="tool_search_call"){let M0=_[$0.output_index],R1=$0.item.execution==="server";if(M0!=null){let f8=R1?M0.toolCallId:(a0=$0.item.call_id)!=null?a0:$0.item.id;if(R1)G0.push(f8);else Y0.enqueue({type:"tool-input-start",id:f8,toolName:M0.toolName});Y0.enqueue({type:"tool-input-end",id:f8}),Y0.enqueue({type:"tool-call",toolCallId:f8,toolName:M0.toolName,input:JSON.stringify({arguments:$0.item.arguments,call_id:R1?null:f8}),...R1?{providerExecuted:!0}:{},providerMetadata:{[U]:{itemId:$0.item.id}}})}_[$0.output_index]=void 0}else if($0.item.type==="tool_search_output"){let M0=(K1=(P1=$0.item.call_id)!=null?P1:G0.shift())!=null?K1:$0.item.id;Y0.enqueue({type:"tool-result",toolCallId:M0,toolName:H.toCustomToolName("tool_search"),result:{tools:$0.item.tools},providerMetadata:{[U]:{itemId:$0.item.id}}})}else if($0.item.type==="mcp_call"){_[$0.output_index]=void 0;let M0=(v0=$0.item.approval_request_id)!=null?v0:void 0,R1=M0!=null?(Q0=(l0=T.get(M0))!=null?l0:E[M0])!=null?Q0:$0.item.id:$0.item.id,f8=`mcp.${$0.item.name}`;Y0.enqueue({type:"tool-call",toolCallId:R1,toolName:f8,input:$0.item.arguments,providerExecuted:!0,dynamic:!0}),Y0.enqueue({type:"tool-result",toolCallId:R1,toolName:f8,result:{type:"call",serverLabel:$0.item.server_label,name:$0.item.name,arguments:$0.item.arguments,...$0.item.output!=null?{output:$0.item.output}:{},...$0.item.error!=null?{error:$0.item.error}:{}},providerMetadata:{[U]:{itemId:$0.item.id}}})}else if($0.item.type==="mcp_list_tools")_[$0.output_index]=void 0;else if($0.item.type==="apply_patch_call"){let M0=_[$0.output_index];if((M0==null?void 0:M0.applyPatch)&&!M0.applyPatch.endEmitted&&$0.item.operation.type!=="delete_file"){if(!M0.applyPatch.hasDiff)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:DA($0.item.operation.diff)});Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:'"}}'}),Y0.enqueue({type:"tool-input-end",id:M0.toolCallId}),M0.applyPatch.endEmitted=!0}if(M0&&$0.item.status==="completed")g=!0,Y0.enqueue({type:"tool-call",toolCallId:M0.toolCallId,toolName:H.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$0.item.call_id,operation:$0.item.operation}),providerMetadata:{[U]:{itemId:$0.item.id}}});_[$0.output_index]=void 0}else if($0.item.type==="mcp_approval_request"){_[$0.output_index]=void 0;let M0=(i=(e=(w0=j.config).generateId)==null?void 0:e.call(w0))!=null?i:o8(),R1=(m0=$0.item.approval_request_id)!=null?m0:$0.item.id;T.set(R1,M0);let f8=`mcp.${$0.item.name}`;Y0.enqueue({type:"tool-call",toolCallId:M0,toolName:f8,input:$0.item.arguments,providerExecuted:!0,dynamic:!0}),Y0.enqueue({type:"tool-approval-request",approvalId:R1,toolCallId:M0})}else if($0.item.type==="local_shell_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:$0.item.action.command,timeoutMs:$0.item.action.timeout_ms,user:$0.item.action.user,workingDirectory:$0.item.action.working_directory,env:$0.item.action.env}}),providerMetadata:{[U]:{itemId:$0.item.id}}});else if($0.item.type==="shell_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$0.item.action.commands}}),...N&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:$0.item.id}}});else if($0.item.type==="shell_call_output")Y0.enqueue({type:"tool-result",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("shell"),result:{output:$0.item.output.map((M0)=>({stdout:M0.stdout,stderr:M0.stderr,outcome:M0.outcome.type==="exit"?{type:"exit",exitCode:M0.outcome.exit_code}:{type:"timeout"}}))}});else if($0.item.type==="reasoning"){let M0=p({itemId:$0.item.id,outputIndex:$0.output_index}),R1=l[M0];if(R1!=null){let f8=Object.entries(R1.summaryParts).filter(([v,c])=>c==="active"||c==="can-conclude").map(([v])=>v);for(let v of f8)Y0.enqueue({type:"reasoning-end",id:`${M0}:${v}`,providerMetadata:{[U]:{itemId:M0,reasoningEncryptedContent:(I0=$0.item.encrypted_content)!=null?I0:null}}});delete l[M0]}n[$0.output_index]=void 0}else if($0.item.type==="compaction")Y0.enqueue({type:"custom",kind:"openai.compaction",providerMetadata:{[U]:{type:"compaction",itemId:$0.item.id,encryptedContent:$0.item.encrypted_content}}})}else if(fw4($0)){let M0=_[$0.output_index];if(M0!=null)if(M0.suppressInputStreaming)(t0=M0.bufferedInputDeltas)==null||t0.push($0.delta);else Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:$0.delta})}else if(yw4($0)){let M0=_[$0.output_index];if(M0!=null)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:$0.delta})}else if(lw4($0)){let M0=_[$0.output_index];if(M0==null?void 0:M0.applyPatch)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:DA($0.delta)}),M0.applyPatch.hasDiff=!0}else if(cw4($0)){let M0=_[$0.output_index];if((M0==null?void 0:M0.applyPatch)&&!M0.applyPatch.endEmitted){if(!M0.applyPatch.hasDiff)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:DA($0.diff)}),M0.applyPatch.hasDiff=!0;Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:'"}}'}),Y0.enqueue({type:"tool-input-end",id:M0.toolCallId}),M0.applyPatch.endEmitted=!0}}else if(gw4($0))Y0.enqueue({type:"tool-result",toolCallId:$0.item_id,toolName:H.toCustomToolName("image_generation"),result:{result:$0.partial_image_b64},preliminary:!0});else if(hw4($0)){let M0=_[$0.output_index];if(M0!=null)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:DA($0.delta)})}else if(uw4($0)){let M0=_[$0.output_index];if(M0!=null)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:'"}'}),Y0.enqueue({type:"tool-input-end",id:M0.toolCallId}),Y0.enqueue({type:"tool-call",toolCallId:M0.toolCallId,toolName:H.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$0.code,containerId:M0.codeInterpreter.containerId}),providerExecuted:!0})}else if(xw4($0))x=$0.response.id,Y0.enqueue({type:"response-metadata",id:$0.response.id,timestamp:new Date($0.response.created_at*1000),modelId:$0.response.model});else if(kw4($0)){let M0=p({itemId:$0.item_id,outputIndex:$0.output_index});if(Y0.enqueue({type:"text-delta",id:M0,delta:$0.delta}),((I1=(f0=Z.providerOptions)==null?void 0:f0[U])==null?void 0:I1.logprobs)&&$0.logprobs)q.push($0.logprobs)}else if($0.type==="response.reasoning_summary_part.added"){let M0=p({itemId:$0.item_id,outputIndex:$0.output_index});if($0.summary_index>0){let R1=l[M0];if(R1!=null){R1.summaryParts[$0.summary_index]="active";for(let f8 of Object.keys(R1.summaryParts))if(R1.summaryParts[f8]==="can-conclude")Y0.enqueue({type:"reasoning-end",id:`${M0}:${f8}`,providerMetadata:{[U]:{itemId:M0}}}),R1.summaryParts[f8]="concluded";Y0.enqueue({type:"reasoning-start",id:`${M0}:${$0.summary_index}`,providerMetadata:{[U]:{itemId:M0,reasoningEncryptedContent:(H8=R1.encryptedContent)!=null?H8:null}}})}}}else if($0.type==="response.reasoning_summary_text.delta"){let M0=p({itemId:$0.item_id,outputIndex:$0.output_index});Y0.enqueue({type:"reasoning-delta",id:`${M0}:${$0.summary_index}`,delta:$0.delta,providerMetadata:{[U]:{itemId:M0}}})}else if($0.type==="response.reasoning_summary_part.done"){let M0=p({itemId:$0.item_id,outputIndex:$0.output_index}),R1=l[M0];if(R1!=null)if(F)Y0.enqueue({type:"reasoning-end",id:`${M0}:${$0.summary_index}`,providerMetadata:{[U]:{itemId:M0}}}),R1.summaryParts[$0.summary_index]="concluded";else R1.summaryParts[$0.summary_index]="can-conclude"}else if(bw4($0)){if(!H0)P={unified:Z30({finishReason:(B8=$0.response.incomplete_details)==null?void 0:B8.reason,hasFunctionCall:g}),raw:(Q8=(m4=$0.response.incomplete_details)==null?void 0:m4.reason)!=null?Q8:void 0};if(A=(D5=$0.response.usage)!=null?D5:void 0,typeof $0.response.service_tier==="string")F0=$0.response.service_tier;if(((x8=$0.response.reasoning)==null?void 0:x8.context)!=null)V0=$0.response.reasoning.context}else if(_G$($0)){let M0=(m6=$0.response.incomplete_details)==null?void 0:m6.reason;if(P={unified:M0?Z30({finishReason:M0,hasFunctionCall:g}):"error",raw:M0!=null?M0:"error"},A=(O9=$0.response.usage)!=null?O9:void 0,((o0=$0.response.reasoning)==null?void 0:o0.context)!=null)V0=$0.response.reasoning.context;if(!H0&&$0.response.error!=null){H0=!0;let R1={type:"response.failed",sequence_number:$0.sequence_number,response:{error:$0.response.error,incomplete_details:$0.response.incomplete_details,service_tier:$0.response.service_tier}};Y0.enqueue({type:"error",error:(D1=Ha(R1))!=null?D1:R1})}}else if(mw4($0)){if(V.push($0.annotation),$0.annotation.type==="url_citation")Y0.enqueue({type:"source",sourceType:"url",id:(Y$=(h1=(x$=j.config).generateId)==null?void 0:h1.call(x$))!=null?Y$:o8(),url:$0.annotation.url,title:$0.annotation.title});else if($0.annotation.type==="file_citation")Y0.enqueue({type:"source",sourceType:"document",id:(G4=(r6=(_8=j.config).generateId)==null?void 0:r6.call(_8))!=null?G4:o8(),mediaType:"text/plain",title:$0.annotation.filename,filename:$0.annotation.filename,providerMetadata:{[U]:{type:$0.annotation.type,fileId:$0.annotation.file_id,index:$0.annotation.index}}});else if($0.annotation.type==="container_file_citation")Y0.enqueue({type:"source",sourceType:"document",id:(n$=(T8=(a1=j.config).generateId)==null?void 0:T8.call(a1))!=null?n$:o8(),mediaType:"text/plain",title:$0.annotation.filename,filename:$0.annotation.filename,providerMetadata:{[U]:{type:$0.annotation.type,fileId:$0.annotation.file_id,containerId:$0.annotation.container_id}}});else if($0.annotation.type==="file_path")Y0.enqueue({type:"source",sourceType:"document",id:(ZQ=(Q9=(W$=j.config).generateId)==null?void 0:Q9.call(W$))!=null?ZQ:o8(),mediaType:"application/octet-stream",title:$0.annotation.file_id,filename:$0.annotation.file_id,providerMetadata:{[U]:{type:$0.annotation.type,fileId:$0.annotation.file_id,index:$0.annotation.index}}})}else if(bG$($0))H0=!0,P={unified:"error",raw:"error"},Y0.enqueue({type:"error",error:(OZ=Ha($0))!=null?OZ:$0})},flush(Z0){var Y0;for(let J0 of Object.values(_)){if(!(J0==null?void 0:J0.suppressInputStreaming))continue;Z0.enqueue({type:"tool-input-start",id:J0.toolCallId,toolName:J0.toolName});for(let c0 of(Y0=J0.bufferedInputDeltas)!=null?Y0:[])Z0.enqueue({type:"tool-input-delta",id:J0.toolCallId,delta:c0})}let o={[U]:{responseId:x,...q.length>0?{logprobs:q}:{},...F0!==void 0?{serviceTier:F0}:{},...V0!==void 0?{reasoningContext:V0}:{}}};Z0.enqueue({type:"finish",finishReason:P,usage:la0(A),providerMetadata:o})}})),request:{body:G},response:{headers:O}}}};fG$=W0(()=>r(y6.object({inputFileExpiresAfter:y6.number().int().min(3600).max(2592000).optional()})));ba0=W0(()=>r(W3$())),tw4=W0(()=>r(y6.object({custom_id:y6.string(),response:y6.object({status_code:y6.number(),request_id:y6.string().nullish(),body:y6.unknown()}).nullish(),error:y6.object({code:y6.string(),message:y6.string()}).nullish()}))),ow4=W0(()=>r(y6.object({data:y6.array(W3$()),has_more:y6.boolean(),last_id:y6.string().nullish()})));aw4=new Set(["openai.code_interpreter","openai.custom","openai.file_search","openai.web_search","openai.web_search_preview"]);Yj4=D6.strictObject({type:D6.string(),responseEvent:D6.string().optional()}).refine(($)=>$.type==="response.event"===($.responseEvent!==void 0),"responseEvent is required for response.event and forbidden for other event types."),Xj4=D6.strictObject({client:D6.strictObject({dataChannel:D6.strictObject({allowedClientEvents:D6.union([D6.literal("all"),D6.array(D6.string())]).optional(),allowedServerEvents:D6.union([D6.literal("all"),D6.array(Yj4)]).optional()})}).optional(),delegation:D6.strictObject({type:D6.literal("client")}).nullable().optional(),input:D6.array(D6.discriminatedUnion("role",[D6.strictObject({type:D6.literal("message"),role:D6.enum(["developer","user"]),content:D6.tuple([D6.strictObject({type:D6.literal("input_text"),text:D6.string()})])}),D6.strictObject({type:D6.literal("message"),role:D6.literal("assistant"),content:D6.tuple([D6.strictObject({type:D6.enum(["text","output_text"]),text:D6.string()})])})])).max(128).optional(),store:D6.boolean().optional(),voice:D6.strictObject({id:D6.string().min(1)}).optional()}),yG$=$W.union([$W.strictObject({type:$W.literal("audio/pcm"),rate:$W.union([$W.literal(16000),$W.literal(24000)])}),$W.strictObject({type:$W.enum(["audio/pcma","audio/pcmu"]),rate:$W.literal(8000)})]);$e0=v$.object({id:v$.string().min(1)}),Jj4=$e0.extend({delegation:v$.object({type:v$.enum(["client","responses"])}).nullish()}),gG$=v$.object({seconds:v$.number().nonnegative()}),hG$={delta:v$.string(),start_ms:v$.number().nonnegative(),end_ms:v$.number().nonnegative()},Q30={client_event_id:v$.string().nullish()},xa0={...Q30,start_ms:v$.number().nonnegative(),end_ms:v$.number().nonnegative()},K3$=v$.discriminatedUnion("type",[v$.object({type:v$.literal("session.started"),session:Jj4}),v$.object({type:v$.literal("session.closed"),session:$e0.nullish(),usage:gG$,reason:v$.string()}),v$.object({type:v$.literal("session.usage.updated"),usage:gG$,context_window:v$.object({usage_ratio:v$.number().min(0).max(1)}).nullish()}),v$.object({type:v$.literal("session.output_audio.delta"),delta:v$.string()}),v$.object({type:v$.literal("session.input_transcript.delta"),...hG$}),v$.object({type:v$.literal("session.output_transcript.delta"),...hG$}),v$.object({type:v$.literal("session.delegation.created"),offset_ms:v$.number().nonnegative().nullish(),delegation:v$.object({id:v$.string().min(1),target:v$.enum(["client","responses"]).nullish(),response_id:v$.string().min(1).nullish()})}),v$.object({type:v$.literal("session.updated"),session:$e0,...Q30}),v$.object({type:v$.literal("session.input_audio.muted"),...Q30}),v$.object({type:v$.literal("session.input_audio.unmuted"),...Q30}),v$.object({type:v$.literal("session.instructions.appended"),...xa0}),v$.object({type:v$.literal("session.thinking.appended"),...xa0}),v$.object({type:v$.literal("session.commentary.appended"),...xa0}),v$.object({type:v$.literal("error"),error:v$.object({message:v$.string(),code:v$.string().nullish(),client_event_id:v$.string().nullish()})})]),Gj4=new Set(K3$.options.map(($)=>$.shape.type.value)),Wj4=v$.object({type:v$.string()});Uj4=LA.object({session:LA.object({id:LA.string().min(1)}),transport:LA.object({type:LA.literal("webrtc"),sdp:LA.string().min(1)})});Dj4=["gpt-live-1"];jj4=W0(()=>r(fa0.object({instructions:fa0.string().nullish(),speed:fa0.number().min(0.25).max(4).default(1).nullish()}))),Ej4=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({text:Z,voice:Q="alloy",outputFormat:Y="mp3",speed:X,instructions:J,language:G,providerOptions:W}){let K=[],H=await I$({provider:"openai",providerOptions:W,schema:jj4}),F={model:this.modelId,input:Z,voice:Q,response_format:"mp3",speed:X,instructions:J};if(Y)if(["mp3","opus","aac","flac","wav","pcm"].includes(Y))F.response_format=Y;else K.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${Y}. Using mp3 instead.`});if(H){let U={};for(let N in U){let B=U[N];if(B!==void 0)F[N]=B}}if(G)K.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${G}" was ignored.`});return{requestBody:F,warnings:K}}async doGenerate(Z){var Q,Y,X,J,G;let W=(X=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?X:new Date,{requestBody:K,warnings:H}=await this.getArgs(Z),{value:F,responseHeaders:U,rawValue:N}=await o1({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:T1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),body:K,failedResponseHandler:R9,successfulResponseHandler:d7$(),abortSignal:Z.abortSignal,fetch:this.config.fetch});return{audio:F,warnings:H,request:{body:JSON.stringify(K)},response:{timestamp:W,modelId:this.modelId,headers:U,body:N}}}},zj4=W0(()=>r(n6.object({text:n6.string(),language:n6.string().nullish(),duration:n6.number().nullish(),words:n6.array(n6.object({word:n6.string(),start:n6.number(),end:n6.number()})).nullish(),segments:n6.array(n6.union([n6.object({id:n6.number(),seek:n6.number(),start:n6.number(),end:n6.number(),text:n6.string(),tokens:n6.array(n6.number()),temperature:n6.number(),avg_logprob:n6.number(),compression_ratio:n6.number(),no_speech_prob:n6.number()}),n6.object({type:n6.literal("transcript.text.segment"),id:n6.string(),start:n6.number(),end:n6.number(),text:n6.string(),speaker:n6.string()})])).nullish()}))),lG$=W0(()=>r(dZ.object({include:dZ.array(dZ.string()).optional(),language:dZ.string().optional(),prompt:dZ.string().optional(),temperature:dZ.number().min(0).max(1).default(0).optional(),timestampGranularities:dZ.array(dZ.enum(["word","segment"])).default(["segment"]).optional(),responseFormat:dZ.enum(["json","verbose_json","diarized_json"]).optional(),chunkingStrategy:dZ.union([dZ.literal("auto"),dZ.object({type:dZ.literal("server_vad"),threshold:dZ.number().min(0).max(1).optional(),prefixPaddingMs:dZ.number().int().min(0).optional(),silenceDurationMs:dZ.number().int().min(0).optional()})]).optional(),streaming:dZ.object({delay:dZ.enum(["minimal","low","medium","high","xhigh"]).optional(),include:dZ.array(dZ.string()).optional()}).optional()})));mG$={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Pj4=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({audio:Z,mediaType:Q,providerOptions:Y}){var X,J;let G=[],W=await I$({provider:"openai",providerOptions:Y,schema:lG$}),K=new FormData,H=Z instanceof Uint8Array?new Blob([Z]):new Blob([_9(Z)]);K.append("model",this.modelId);let F=b7$(Q);if(K.append("file",new File([H],"audio",{type:Q}),`audio.${F}`),this.modelId==="whisper-1")K.append("response_format","verbose_json");let U=this.modelId==="gpt-4o-transcribe-diarize",N=(X=W==null?void 0:W.chunkingStrategy)!=null?X:U?"auto":void 0;if(W){let B=["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId),O={include:W.include,language:W.language,prompt:W.prompt,...this.modelId!=="whisper-1"&&{response_format:(J=W.responseFormat)!=null?J:U?"diarized_json":B?"json":"verbose_json"},temperature:W.temperature,timestamp_granularities:W.timestampGranularities};for(let[L,w]of Object.entries(O))if(w!=null)if(Array.isArray(w))for(let j of w)K.append(`${L}[]`,String(j));else K.append(L,String(w))}else if(U)K.append("response_format","diarized_json");if(N!=null)K.append("chunking_strategy",typeof N==="string"?N:JSON.stringify({type:N.type,...N.threshold!=null&&{threshold:N.threshold},...N.prefixPaddingMs!=null&&{prefix_padding_ms:N.prefixPaddingMs},...N.silenceDurationMs!=null&&{silence_duration_ms:N.silenceDurationMs}}));return{formData:K,warnings:G}}async doGenerate(Z){var Q,Y,X,J,G,W,K,H,F,U,N;if(cG$(this.modelId))throw new t1({functionality:`non-streaming transcription with ${this.modelId}`});let B=(X=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?X:new Date,{formData:O,warnings:L}=await this.getArgs(Z),{value:w,responseHeaders:j,rawValue:E}=await p3({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:T1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),formData:O,failedResponseHandler:R9,successfulResponseHandler:E1(zj4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),z=w.language!=null&&w.language in mG$?mG$[w.language]:void 0,T=(W=w.segments)==null?void 0:W.flatMap((P)=>("speaker"in P)?[{text:P.text,startSecond:P.start,endSecond:P.end,speaker:P.speaker}]:[]);return{text:w.text,segments:(U=(F=(K=w.segments)==null?void 0:K.map((P)=>({text:P.text,startSecond:P.start,endSecond:P.end})))!=null?F:(H=w.words)==null?void 0:H.map((P)=>({text:P.word,startSecond:P.start,endSecond:P.end})))!=null?U:[],language:z,durationInSeconds:(N=w.duration)!=null?N:void 0,warnings:L,response:{timestamp:B,modelId:this.modelId,headers:j,body:E},...T!=null&&T.length>0&&{providerMetadata:{openai:{segments:T}}}}}async doStream(Z){var Q,Y,X,J,G,W,K;if(!cG$(this.modelId))throw new t1({functionality:`streaming transcription with ${this.modelId}`});let H=(X=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?X:new Date,F=await I$({provider:"openai",providerOptions:Z.providerOptions,schema:lG$}),U=[],N=(G=(J=Z.providerOptions)==null?void 0:J.openai)!=null?G:{};for(let L of["include","prompt","temperature","timestampGranularities"])if(N[L]!=null)U.push({type:"unsupported",feature:`providerOptions.openai.${L}`,details:`OpenAI streaming transcription does not support ${L}.`});let B=T1((K=(W=this.config).headers)==null?void 0:K.call(W),Z.headers),O=Tj4({modelId:this.modelId,inputAudioFormat:Z.inputAudioFormat,providerOptions:F});return{request:{body:O},response:{timestamp:H,modelId:this.modelId},stream:Aj4({webSocket:this.config.webSocket,url:kJ0(this.config.url({path:"/realtime?intent=transcription",modelId:this.modelId})),headers:B,sessionUpdate:O,language:F==null?void 0:F.language,warnings:U,audio:Z.audio,abortSignal:Z.abortSignal,includeRawChunks:Z.includeRawChunks})}}};Mj4=W0(()=>r(qj4.object({}))),Ij4=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async doStream(Z){var Q,Y,X,J,G;if(Z.targetLanguage==null)throw new b8({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let W=(X=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?X:new Date;await I$({provider:"openai",providerOptions:Z.providerOptions,schema:Mj4});let K=[];if(Sj4(Z.inputAudioFormat),Z.sourceLanguage!=null)K.push({type:"unsupported",feature:"sourceLanguage",details:"The OpenAI Realtime translation API auto-detects the source language and does not accept a source language."});if(Z.outputAudioFormat!=null)K.push({type:"unsupported",feature:"outputAudioFormat",details:"The OpenAI Realtime translation API always outputs 24kHz 16-bit PCM audio and does not accept an output audio format."});let H=T1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),F=kj4({targetLanguage:Z.targetLanguage});return{request:{body:F},response:{timestamp:W,modelId:this.modelId},stream:Vj4({webSocket:this.config.webSocket,url:kJ0(this.config.url({path:`/realtime/translations?model=${encodeURIComponent(this.modelId)}`,modelId:this.modelId})),headers:H,sessionUpdate:F,warnings:K,audio:Z.audio,abortSignal:Z.abortSignal,includeRawChunks:Z.includeRawChunks})}}};_j4=W0(()=>r(vG.object({id:vG.string(),name:vG.string().nullish(),description:vG.string().nullish(),default_version:vG.string().nullish(),latest_version:vG.string().nullish(),created_at:vG.number(),updated_at:vG.number().nullish()}))),Kl5=W0(()=>r(vG.object({id:vG.string(),version:vG.string().nullish(),name:vG.string().nullish(),description:vG.string().nullish()})));Hl5=wA()});function fj4($){return UF("LLMAPI listModels",`${F3$}/models`,{headers:$?{Authorization:`Bearer ${$}`}:{},signal:AbortSignal.timeout(15000)})}var F3$="https://api.llmapi.ai/v1",xj4="https://llmapi.ai/wp-content/uploads/2026/01/Frame-2085662993.png",U3$;var N3$=D(()=>{X30();hP();U3$={info:{id:"llmapi",name:"LLMAPI",description:"One API key, 400+ models across every provider",logo:xj4},supportedMethods:["api-key"],create($){let Z=wA({apiKey:$||"not-needed",baseURL:F3$,name:"llmapi"}),Q=Object.assign((...Y)=>Z.chat(...Y),Z,{languageModel:Z.chat});return{info:this.info,aiSdk:Q,async listModels(){let Y=await fj4($);if(!Y.ok)await FY("LLMAPI listModels",Y);let{data:X}=await GJ0("LLMAPI listModels",Y);return X.map((J)=>{let G=J.architecture??{},W=!!J.reasoning_levels?.length||!!J.providers?.some((K)=>K.reasoning);return{providerId:"llmapi",modelId:J.id,title:J.name||J.id,description:J.description??null,logo:null,capabilities:WJ0(G.input_modalities??[],G.output_modalities??[],J.supported_parameters,W?["reasoning"]:[]),limits:{contextWindow:J.context_length??0,maxOutputTokens:null},costs:{input:Number(J.pricing?.prompt)||0,output:Number(J.pricing?.completion)||0}}})}}}}});function yj4($,Z){return UF("OpenAI-compatible listModels",`${$}/models`,{headers:Z,signal:AbortSignal.timeout(15000)})}function gj4($){let Z=JSON.parse($);if(!Z.baseUrl||typeof Z.baseUrl!=="string")throw Error("Invalid OpenAI-compatible credential: missing baseUrl field");let Q=Z.baseUrl.replace(/\/+$/,"");if(!Q.endsWith("/v1"))Q+="/v1";return{baseUrl:Q,apiKey:Z.apiKey??""}}var hj4="https://assets.decocache.com/decocms/d138aa7e-5b8c-4821-9e64-6aff40df2cdc/ChatGPT_logo.svg",B3$;var O3$=D(()=>{X30();hP();B3$={info:{id:"openai-compatible",name:"OpenAI Compatible",description:"Custom OpenAI-compatible endpoint",logo:hj4},supportedMethods:["api-key"],create($){let{baseUrl:Z,apiKey:Q}=gj4($),Y=wA({baseURL:Z,apiKey:Q||"not-needed",name:"openai-compatible"}),X=Object.assign((...J)=>Y.chat(...J),Y,{languageModel:Y.chat});return{info:this.info,aiSdk:X,async listModels(){let J={};if(Q)J.Authorization=`Bearer ${Q}`;let G=await yj4(Z,J);if(!G.ok)await FY("OpenAI-compatible listModels",G);let W=await G.text(),K;try{K=JSON.parse(W)}catch{throw Error(`OpenAI-compatible listModels returned malformed JSON: ${W.slice(0,200)}`)}return K.data.map((H)=>({providerId:"openai-compatible",modelId:H.id,title:H.id,description:H.owned_by?`Owned by ${H.owned_by}`:null,logo:null,capabilities:[],limits:null,costs:null}))}}}}});function q9(){return{...E0().aiGatewayEnabled&&{deco:cL},anthropic:KJ$,google:KG$,openrouter:KJ0,llmapi:U3$,"openai-compatible":B3$}}var ZW=D(()=>{HJ$();HG$();N3$();O3$();Po0();su();F$()});function cj4($,Z,Q){EJ0($,Z,Q)}function mj4($,Z,Q){zJ0($,Z,Q)}function Je0($){Ua.delete($)}async function Ge0($,Z){if(!E0().plansEnabled)return null;if(!E0().aiGatewayEnabled)return null;let Q=Ua.get(Z);if(Q&&Date.now()-Q.at<L3$)return Q.value;let Y=Xe0.get(Z);if(Y)return Y;let X=dj4($,Z,Q).finally(()=>{Xe0.delete(Z)});return Xe0.set(Z,X),X}async function dj4($,Z,Q){let Y=q9().deco;if(!Y?.getEntitlements)return null;let X=$.auth.user?.id??$.auth.apiKey?.userId;if(!X)return D3$(Z,Q);try{let J=await NQ(X),{features:G,usage:W,modelPins:K,credits:H}=await Y.getEntitlements(J,Z);if(!G||typeof G!=="object")throw new uP(502);let F={features:G,modelPins:K,usageState:W?.state??null,creditsUsd:H?.remainingUsd??null};return cj4(Ua,Z,F),mj4(Ua,lj4,L3$),F}catch(J){let G=J instanceof uP&&J.isDefinitive,W=J instanceof uP&&J.isDormant,K={organizationId:Z,servedStale:!!Q,status:J instanceof uP?J.status:null,error:J instanceof Error?J.message:String(J)};if(W);else if(G)console.error("[Plans] entitlements REFUSED by the gateway \u2014 gates fail OPEN for every org until this is fixed (check STUDIO_JWT_SECRET and STUDIO_PROVISION_SECRET_KEY against the gateway's MESH_JWT_SECRET and STUDIO_PROVISION_KEY)",K);else console.warn("[Plans] entitlements lookup failed (gateway unreachable) \u2014 gates fail OPEN",K);return D3$(Z,Q)}}function D3$($,Z){if(Z&&Date.now()-Z.at>=uj4)return Ua.delete($),null;return Z?.value??null}async function QW($,Z,Q){let Y=await Ge0($,Z);return w3$(Y?.features??null,Q)}function w3$($,Z){if(!$)return!0;return $[Z]===!0}function ij4($,Z){if($!=="exhausted")return!1;return!(Z!==null&&Z>0)}async function hK($,Z,Q){let Y=await Ge0($,Z);if(!ij4(Y?.usageState??null,Y?.creditsUsd??null))return;throw new J30(`${Q} is paused: this organization has used its monthly AI allowance`)}async function j3$($,Z,Q){let Y=await Ge0($,Z);if(!Y)return null;if(w3$(Y.features,"model_choice"))return null;return Y.modelPins?.[Q]??null}var yF,L3$=60000,uj4=600000,Ua,lj4=1e4,Xe0,J30;var gF=D(()=>{BK();ZW();su();GK();F$();yF=class yF extends y7{feature;code="feature_not_in_plan";constructor($,Z){super($);this.feature=Z;this.name="FeatureNotInPlanError"}};Ua=new Map;Xe0=new Map;J30=class J30 extends y7{code="ai_budget_exhausted";constructor($){super($);this.name="AiBudgetExhaustedError"}}});function E3$($){let{ctx:Z,toolName:Q,organizationId:Y,durationMs:X,isError:J}=$,G={"tool.name":Q,"organization.id":Y,status:J?"error":"success"};Z.meter.createHistogram("studio_tool.execution.duration",{description:"Duration of in-process Studio tool executions in milliseconds",unit:"ms"}).record(X,G),Z.meter.createCounter("studio_tool.execution.count",{description:"Number of in-process Studio tool executions"}).add(1,G)}import{SpanStatusCode as z3$}from"@opentelemetry/api";function d($){return{...$,execute:async(Z,Q)=>{let Y=performance.now(),X=!1;return await Q.timings.measure(`tool.${$.name}`,async()=>Q.tracer.startActiveSpan(`tool.${$.name}`,{attributes:{"tool.name":$.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(J)=>{try{Q.toolName=$.name,Q.access.setToolName?.($.name);let G=Q.organization?.id;if(G&&!o9$($.name)&&await AJ0(Q.db,G))throw new Cr(`This organization is blocked: ${$.name} is unavailable until the block is resolved`);if(($.requiresFeature||$.requiresAiBudget)&&!G)console.warn(`[Plans] ${$.name} declares a plan gate but no organization is in scope \u2014 running UNGATED`);if($.requiresFeature&&G&&!await QW(Q,G,$.requiresFeature))throw new yF(`${$.name} needs the ${$.requiresFeature} feature, which this organization's plan does not include`,$.requiresFeature);if($.requiresAiBudget&&G)await hK(Q,G,$.name);let W=await $.handler(Z,Q);return J.setStatus({code:z3$.OK}),W}catch(G){throw X=!0,J.setStatus({code:z3$.ERROR,message:G.message}),J.recordException(G),G}finally{E3$({ctx:Q,toolName:$.name,organizationId:Q.organization?.id??"system",durationMs:performance.now()-Y,isError:X}),J.end()}}))}}}var C0=D(()=>{mP();gF()});function K0($){if(!$.organization)throw Error("This operation requires organization scope");return $.organization}function p0($){return $.auth.user?.id??$.auth.apiKey?.userId}function jA($){return!!($.auth.user||$.auth.apiKey)}function a($){if(!jA($))throw Error("Authentication required")}import{z as J4}from"zod";var A3$,P3$=1000,pj4=500,T3$,R3$,q3$,M3$,I3$,V3$,k3$,S3$,C3$,_3$;var il=D(()=>{A3$=J4.record(J4.string(),J4.array(J4.string())),T3$=J4.record(J4.string(),J4.array(J4.string()).max(pj4)).refine(($)=>Object.keys($).length<=P3$,{message:`Permissions cannot grant more than ${P3$} resources`}),R3$=J4.object({id:J4.string().describe("Unique identifier for the API key"),name:J4.string().describe("Human-readable name for the API key"),userId:J4.string().describe("ID of the user who owns this API key"),permissions:A3$.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:J4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:J4.string().datetime().describe("When the API key was created (ISO 8601)")}),q3$=J4.object({name:J4.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:T3$.describe(`Permissions to grant (REQUIRED \u2014 there is no implicit default). Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["ORGANIZATION_GET"]) or ["*"] for all. Example: { "self": ["ORGANIZATION_GET", "COLLECTION_CONNECTIONS_LIST"] }. The key is authorized solely by this allowlist; the creator's role does not widen it.`),expiresIn:J4.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:J4.record(J4.string(),J4.unknown()).optional().describe("Additional metadata to store with the API key")}),M3$=J4.object({id:J4.string().describe("Unique identifier for the API key"),name:J4.string().describe("Human-readable name for the API key"),key:J4.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:A3$.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:J4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:J4.string().datetime().describe("When the API key was created (ISO 8601)")}),I3$=J4.object({}),V3$=J4.object({items:J4.array(R3$).describe("List of API keys (without key values)")}),k3$=J4.object({keyId:J4.string().describe("ID of the API key to update"),name:J4.string().min(1).max(64).optional().describe("New name for the API key"),permissions:T3$.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:J4.record(J4.string(),J4.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),S3$=J4.object({item:R3$.describe("The updated API key (without key value)")}),C3$=J4.object({keyId:J4.string().describe("ID of the API key to delete")}),_3$=J4.object({success:J4.boolean().describe("Whether the deletion was successful"),keyId:J4.string().describe("ID of the deleted API key")})});var We0;var v3$=D(()=>{U6();C0();il();We0=d({name:"API_KEY_CREATE",description:"Create an API key with scoped permissions. The key value is returned only once \u2014 store it immediately.",annotations:{title:"Create API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q3$,outputSchema:M3$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=await Z.boundAuth.apiKey.create({name:$.name,permissions:$.permissions,expiresIn:$.expiresIn,metadata:{...$.metadata,organization:Z.organization}}),Y=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,X=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,J=p0(Z);if(J)v1.capture({distinctId:J,event:"api_key_created",...Z.organization?.id?{groups:{organization:Z.organization.id}}:{},properties:{key_id:Q.id,key_name:Q.name??$.name,organization_id:Z.organization?.id,has_expiry:!!Y}});return{id:Q.id,name:Q.name??$.name,key:Q.key,permissions:Q.permissions??{},expiresAt:Y,createdAt:X}}})});var Ke0;var b3$=D(()=>{U6();C0();il();Ke0=d({name:"API_KEY_DELETE",description:"Delete and instantly revoke an API key. Cannot be undone.",annotations:{title:"Delete API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:C3$,outputSchema:_3$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=p0(Z);if(!Q)throw Error("User ID required to delete API key");let X=(await Z.boundAuth.apiKey.list())?.find((K)=>K.id===$.keyId);if(!X)throw Error("API key not found");let G=X.metadata?.organization?.id,W=Z.organization?.id;if(G!==W)throw Error("Cannot delete API key from another organization");if(await Z.boundAuth.apiKey.delete($.keyId),W)v1.capture({distinctId:Q,event:"api_key_deleted",groups:{organization:W},properties:{key_id:$.keyId,organization_id:W}});return{success:!0,keyId:$.keyId}}})});var He0;var x3$=D(()=>{C0();il();He0=d({name:"API_KEY_LIST",description:"List API keys for the current user in the current organization. Returns metadata only \u2014 key values are never shown after creation.",annotations:{title:"List API Keys",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:I3$,outputSchema:V3$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=await Z.boundAuth.apiKey.list(),Y=Z.organization?.id;return{items:(Q??[]).filter((J)=>{return J.metadata?.organization?.id===Y}).map((J)=>({id:J.id,name:J.name??"Unnamed Key",userId:J.userId,permissions:J.permissions??{},expiresAt:J.expiresAt?J.expiresAt instanceof Date?J.expiresAt.toISOString():J.expiresAt:null,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}))}}})});var Fe0;var f3$=D(()=>{C0();il();Fe0=d({name:"API_KEY_UPDATE",description:"Update an API key's name, permissions, or metadata. The key value cannot be changed or retrieved.",annotations:{title:"Update API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:k3$,outputSchema:S3$,handler:async($,Z)=>{if(a(Z),await Z.access.check(),!p0(Z))throw Error("User ID required to update API key");let X=(await Z.boundAuth.apiKey.list())?.find((H)=>H.id===$.keyId);if(!X)throw Error(`API key not found: ${$.keyId}`);let G=X.metadata?.organization?.id,W=Z.organization?.id;if(G!==W)throw Error("Cannot update API key from another organization");let K=await Z.boundAuth.apiKey.update({keyId:$.keyId,name:$.name,permissions:$.permissions,metadata:{...$.metadata,organization:Z.organization}});if(!K)throw Error(`Failed to update API key: ${$.keyId}`);return{item:{id:K.id,name:K.name??$.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var y3$=D(()=>{v3$();b3$();x3$();f3$();il()});function Lw($){let Z=$.trim();if(!Z)return{ok:!1,error:"Enter a website URL."};let Q=tj4.test(Z),Y=oj4.test(Z),X=rj4.test(Z);if(Q&&!Y&&!X)return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let J=Y?Z:`https://${Z}`,G;try{G=new URL(J)}catch{return{ok:!1,error:"Enter a valid website URL."}}if(G.protocol!=="http:"&&G.protocol!=="https:")return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let W=G.hostname.split(".");if(W.length<2||W.some((K)=>!K||!sj4.test(K)))return{ok:!1,error:"Enter a valid website URL."};return G.protocol="https:",{ok:!0,value:G.origin}}var tj4,oj4,rj4,sj4;var Na=D(()=>{tj4=/^[a-zA-Z][a-zA-Z\d+.-]*:/,oj4=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//,rj4=/^[^\s/:?#]+\.[^\s/:?#]+:\d+(?:[/?#]|$)/,sj4=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i});import{z as BJ}from"zod";function G30($){return{repository_id:$.repositoryId,provider:$.provider,host:$.host,path:$.path,default_branch:$.defaultBranch??null,web_url:$.webUrl??null}}function g3$($){let Z=aj4.safeParse($);if(!Z.success)return null;return{repositoryId:Z.data.repository_id,provider:Z.data.provider,host:Z.data.host,path:Z.data.path,defaultBranch:Z.data.default_branch??null,webUrl:Z.data.web_url??null}}function W30($){return $.provider==="github"&&$.host.toLowerCase()==="github.com"?$.path:null}var Ue0,aj4;var K30=D(()=>{Ue0=BJ.object({repositoryId:BJ.string().min(1),provider:BJ.enum(["github","gitlab","bitbucket"]),host:BJ.string().min(1),path:BJ.string().min(1),defaultBranch:BJ.string().nullable().optional(),webUrl:BJ.string().nullable().optional()}),aj4=BJ.object({repository_id:BJ.string().min(1),provider:BJ.enum(["github","gitlab","bitbucket"]),host:BJ.string().min(1),path:BJ.string().min(1),default_branch:BJ.string().nullable().optional(),web_url:BJ.string().nullable().optional()})});import{z as wX}from"zod";function uK($){if($.baseUrl)return $.baseUrl.replace(/\/+$/,"");return(($.settings??E0()).reportsInternalApiUrl??ej4).replace(/\/+$/,"")}function u3$($={}){return`${uK($)}/api/v2/mcp`}function EA($){let Z=$.apiKey??($.settings??E0()).reportsInternalApiKey;if(!Z)throw Error("REPORTS_INTERNAL_API_KEY (or the legacy COMMERCE_DISCOVERY_INTERNAL_API_KEY) is required to set up reports.");return Z}function F30($){return new URL($).hostname}function ZE4($){return $==="ownership_unverified"||$==="already_claimed_by_other_org"}function QE4($,Z={}){switch($){case"ownership_unverified":{let Q=Z.email?`O e-mail ${Z.email}`:"Este e-mail",Y=Z.domain?` ${Z.domain}`:" este site";return`${Q} n\xE3o tem permiss\xE3o para reivindicar${Y}. Use um e-mail do dom\xEDnio do site ou pe\xE7a ao suporte para autorizar seu dom\xEDnio.`}case"already_claimed_by_other_org":return"Este site j\xE1 pertence a outra organiza\xE7\xE3o. Fale com o suporte para transferir o acesso.";case"unknown":return"N\xE3o foi poss\xEDvel configurar o Reports. Tente novamente ou fale com o suporte.";default:return $}}async function YE4($){let Z=await Ba($);return ZE4(Z?.error)?Z.error:"unknown"}async function Ba($){let Z=await $.text().catch(()=>"");if(!Z)return;try{return JSON.parse(Z)}catch{return}}async function U30($){let Z=`Reports auth failed with status ${$.status}.`,Q=await $.text().catch(()=>"");if(!Q)return Z;try{let Y=JSON.parse(Q),X=typeof Y.error==="string"?Y.error:typeof Y.message==="string"?Y.message:null;return X?`Reports auth failed: ${X}.`:Z}catch{return Z}}async function c3$($,Z={}){let Q=uK(Z),Y=EA(Z),X=Z.fetchImpl??fetch,J=F30($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/upgrade`,W=await X(G,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.orgName?{name:$.orgName}:{},...$.email?{email:$.email}:{},...$.reportUrl?{report_url:$.reportUrl}:{}}),signal:AbortSignal.timeout(H30)});if(!W.ok){let H=await YE4(W);throw new l3$(H,{email:$.email,domain:J})}let K=$E4.safeParse(await Ba(W));if(!K.success)throw Error("Reports auth response did not include a token.");return{authorizationToken:K.data.token}}async function m3$($,Z={}){let Q=uK(Z),Y=EA(Z),X=Z.fetchImpl??fetch,J=F30($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/bindings`,W=await X(G,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,provider:$.provider,resource_id:$.resourceId}),signal:AbortSignal.timeout(H30)});if(W.status===409)return{ok:!1,reason:"resource_already_bound",detail:"Este recurso j\xE1 est\xE1 vinculado a outra loja. Se ele \xE9 seu, fale com o suporte para revis\xE3o manual."};if(W.status===422){let H=h3$.safeParse(await Ba(W));return{ok:!1,reason:H.success?H.data.reason??"verification_failed":"verification_failed",detail:(H.success?H.data.detail:void 0)??"N\xE3o foi poss\xEDvel verificar o acesso a este recurso."}}if(!W.ok)throw Error(await U30(W));let K=h3$.safeParse(await Ba(W));if(!K.success||!K.data.binding)throw Error("Reports bind response did not include a binding.");return{ok:!0,resourceId:K.data.binding.resource_id,evidence:K.data.binding.evidence}}async function d3$($,Z={}){let Q=uK(Z),Y=EA(Z),X=Z.fetchImpl??fetch,J=F30($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/run`,W=await X(G,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.repository?{repository:G30($.repository)}:{},...$.githubRepo?{github_repo:$.githubRepo}:{}}),signal:AbortSignal.timeout(H30)});if(W.status===409)return{triggered:!1,reason:"not_upgraded"};if(!W.ok)throw Error(await U30(W));return{triggered:!0}}async function XE4($,Z,Q){try{return await g8(async()=>{let Y=await $(Z,{method:"GET",headers:{Authorization:`Bearer ${Q}`},signal:AbortSignal.timeout(H30)});if(Y.status>=500||Y.status===429)throw new Ne0(await U30(Y));return Y},{maxAttempts:3,minTimeout:200,maxTimeout:2000,multiplier:2,jitter:1,isRetriable:(Y)=>Y instanceof Ne0})}catch(Y){if(Y instanceof i5&&Y.cause instanceof Error)throw Y.cause;throw Y}}async function i3$($,Z={}){let Q=uK(Z),Y=EA(Z),X=Z.fetchImpl??fetch,J=F30($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/connections/status?org_id=${encodeURIComponent($.orgId)}`,W=await XE4(X,G,Y);if(W.status===404||W.status===409)return{providers:{},claimed:!1};if(!W.ok)throw Error(await U30(W));let K=JE4.safeParse(await Ba(W));return{providers:K.success?K.data.providers:{},claimed:!0}}var ej4,H30=15000,$E4,h3$,l3$,Ne0,JE4;var ww=D(()=>{e8();D8();K30();F$();ej4=new URL(Vm1).origin,$E4=wX.object({token:wX.string().min(1)}),h3$=wX.object({binding:wX.object({resource_id:wX.string(),evidence:wX.string()}).optional(),reason:wX.string().optional(),detail:wX.string().optional()});l3$=class l3$ extends Error{code;constructor($,Z={}){super(QE4($,Z));this.name="ReportsClaimError",this.code=$}};Ne0=class Ne0 extends Error{};JE4=wX.object({providers:wX.record(wX.string(),wX.object({connected:wX.boolean(),via:wX.enum(["oauth","sa"]).nullable(),resource:wX.string().nullable()}))})});import{z as bG}from"zod";var GE4,WE4,Be0;var p3$=D(()=>{Na();C0();ww();GE4=bG.object({siteUrl:bG.string().min(1).describe("Website URL of the store being bound."),provider:bG.enum(["ga4","gsc"]).describe("Which Google source to bind: ga4 (Analytics) or gsc (Search Console)."),resourceId:bG.string().min(1).describe("The resource id the client typed: GA4 numeric property id, or GSC site (sc-domain:example.com or https://example.com/).")}),WE4=bG.discriminatedUnion("ok",[bG.object({ok:bG.literal(!0),resourceId:bG.string(),evidence:bG.string()}),bG.object({ok:bG.literal(!1),reason:bG.string(),detail:bG.string()})]),Be0=d({name:"REPORTS_BIND",description:"Bind a GA4 property or GSC site to the org's store via the shared service account (consent-free lane). The client grants deco-reader@\u2026 access to the resource and provides its id; Reports verifies the resource belongs to this domain before persisting. Returns ok:false with an actionable pt-BR detail when verification fails or the resource is already bound elsewhere.",annotations:{title:"Bind Reports Data Source",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:GE4,outputSchema:WE4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check("REPORTS_BIND","COMMERCE_DISCOVERY_BIND");let Y=Lw($.siteUrl);if(!Y.ok)throw Error(Y.error);return m3$({siteUrl:Y.value,orgId:Q.id,provider:$.provider,resourceId:$.resourceId.trim()})}})});import{z as hF}from"zod";var KE4,HE4,Oe0;var n3$=D(()=>{Na();C0();ww();KE4=hF.object({siteUrl:hF.string().min(1).describe("Website URL of the store to inspect.")}),HE4=hF.object({providers:hF.record(hF.string(),hF.object({connected:hF.boolean(),via:hF.enum(["oauth","sa"]).nullable(),resource:hF.string().nullable()})),claimed:hF.boolean().describe("False when the site isn't claimed/upgraded for this org \u2014 providers is then empty because the status is unreadable, NOT because nothing is connected. The UI must warn instead of rendering existing bindings as disconnected.")}),Oe0=d({name:"REPORTS_CONNECTION_STATUS",description:"Read per-provider connection status (ga4/gsc/vtex) for the org's store \u2014 { connected, via: oauth|sa, resource }. The single source of truth for whether a data source is connected, unifying the OAuth (Studio vault) and shared-SA binding lanes. Read-only.",annotations:{title:"Reports Connection Status",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:KE4,outputSchema:HE4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check("REPORTS_CONNECTION_STATUS","COMMERCE_DISCOVERY_CONNECTION_STATUS");let Y=Lw($.siteUrl);if(!Y.ok)throw Error(Y.error);return i3$({siteUrl:Y.value,orgId:Q.id})}})});import{z as jw}from"zod";function BE4($){let Z=NE4.safeParse($),Q=Z.success?Z.data:void 0,Y=(Q?g3$(Q.repository):void 0)??void 0,X=Q&&typeof Q.github_repo==="string"&&Q.github_repo.length>0?Q.github_repo:void 0;return{repository:Y??void 0,githubRepo:(Y?W30(Y):X)??void 0}}var FE4,UE4,NE4,De0;var t3$=D(()=>{e8();K30();Na();C0();ww();FE4=jw.object({siteUrl:jw.string().min(1).describe("Website URL to run the diagnostic for.")}),UE4=jw.object({triggered:jw.boolean(),reason:jw.string().optional()}),NE4=jw.object({repository:jw.unknown().optional(),github_repo:jw.string().optional()}).passthrough().nullable().optional();De0=d({name:"REPORTS_RUN",description:"Trigger the Reports diagnostic run for the current organization's store. Call once the data sources (GA4/GSC/VTEX) are connected \u2014 this run resolves credentials and produces the enriched report.",annotations:{title:"Run Reports",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:FE4,outputSchema:UE4,requiresFeature:"diagnostic_enriched",requiresAiBudget:!0,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check("REPORTS_RUN","COMMERCE_DISCOVERY_RUN");let Y=Lw($.siteUrl);if(!Y.ok)throw Error(Y.error);let X=y4.REPORTS(Q.id),J=await Z.storage.connections.findById(X,Q.id),{repository:G,githubRepo:W}=BE4(J?.configuration_state);return d3$({siteUrl:Y.value,orgId:Q.id,repository:G,githubRepo:W})}})});import{z as H5}from"zod";var OE4,Oa,DE4,LE4,wE4,jE4,o3$,r3$,Da,N30;var s3$=D(()=>{OE4=["github","gitlab","bitbucket"],Oa=H5.enum(OE4),DE4=["github_app","oauth","token","github_cli"],LE4=H5.enum(DE4),wE4=["active","revoked"],jE4=H5.enum(wE4),o3$=H5.object({provider:Oa,host:H5.string().min(1).describe("Provider host, e.g. github.com"),path:H5.string().min(1).describe("Full namespace path, e.g. owner/name or group/sub/project")}),r3$=H5.object({id:H5.string(),organizationId:H5.string(),type:Oa,host:H5.string(),authKind:LE4,externalAccountId:H5.string().describe("Provider-side account identity: installation id (GitHub App), user/group id (GitLab) or user/workspace uuid (Bitbucket)."),login:H5.string().describe("Display login of the account/namespace"),avatarUrl:H5.string().nullable(),installationId:H5.number().nullable().describe("GitHub App installation id; null for other auth kinds."),status:jE4,createdAt:H5.string(),updatedAt:H5.string()}),Da=H5.string().regex(/^[a-z][a-z0-9-]{0,31}$/,"lowercase letters, digits and dashes only"),N30=H5.object({id:H5.string(),organizationId:H5.string(),accountId:H5.string().nullable().describe("Credential-holding account; null for anonymous public clones."),provider:Oa,host:H5.string(),path:H5.string(),externalId:H5.string().nullable().describe("Provider repository/project id, when known."),defaultBranch:H5.string().nullable(),webUrl:H5.string(),visibility:H5.enum(["public","private","internal"]).nullable(),sandboxImage:Da.describe("Sandbox image this repository's sandboxes boot from."),createdAt:H5.string(),updatedAt:H5.string()})});function PE4($){let Z=$.toLowerCase();if(Z==="github.com"||Z==="www.github.com")return"github";if(Z==="gitlab.com"||Z==="www.gitlab.com")return"gitlab";if(Z==="bitbucket.org"||Z==="www.bitbucket.org")return"bitbucket";if(/(^|[.-])gitlab([.-]|$)/.test(Z))return"gitlab";return null}function a3$($){let Z=$.toLowerCase();return Z.startsWith("www.")?Z.slice(4):Z}function lK($,Z){let Q=$.trim();if(!Q)return null;let Y,X,J=/^(?:[\w.-]+@)?([\w.-]+(?::\d+)?):(?!\/\/)(.+)$/.exec(Q);if(J&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(Q))Y=J[1],X=J[2];else if(/^[a-z][a-z0-9+.-]*:\/\//i.test(Q)){let F;try{F=new URL(Q)}catch{return null}if(!/^(https?|ssh|git)(\+ssh)?:$/.test(F.protocol))return null;Y=F.host,X=F.pathname}else if(Z?.provider)Y=Z.host??B30[Z.provider],X=Q;else return null;Y=a3$(Y);let G=Z?.provider??PE4(Y);if(!G)return null;let W=X.split("/").map((F)=>F.trim()).filter(Boolean),K=W.indexOf("-");if(K>=0)W=W.slice(0,K);if(zE4.has(G))W=W.slice(0,2);if(W.length<2)return null;let H=W[W.length-1];if(W[W.length-1]=H.replace(/\.git$/i,""),W.some((F)=>F.length===0||F==="."||F===".."))return null;return{provider:G,host:Y,path:W.join("/")}}function cK($){return`${$.host.toLowerCase()}/${$.path.toLowerCase()}`}function Le0($){let Z=$.path.split("/");return Z[Z.length-1]??$.path}function AE4($){let Z=$.path.lastIndexOf("/");return Z<0?"":$.path.slice(0,Z)}function h5($){return{owner:AE4($),name:Le0($)}}function OJ($){return`https://${$.host}/${$.path}`}function we0($,Z){let Q=`${$.host}/${$.path}.git`;if(!Z)return`https://${Q}`;return`https://${EE4[$.provider]}:${encodeURIComponent(Z)}@${Q}`}function wB($,Z){let Q=a3$(Z);switch($){case"github":return Q==="github.com"?"https://api.github.com":`https://${Q}/api/v3`;case"gitlab":return`https://${Q}/api/v4`;case"bitbucket":return"https://api.bitbucket.org/2.0"}}function jB($,Z){return{provider:"github",host:B30.github,path:`${$}/${Z}`}}var B30,EE4,zE4;var je0=D(()=>{B30={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"},EE4={github:"x-access-token",gitlab:"oauth2",bitbucket:"x-token-auth"},zE4=new Set(["github","bitbucket"])});function YW($,Z){return`${OJ($)}/${TE4[$.provider]}/${Z}`}function qE4($){let Z=$.toLowerCase();return RE4[Z]??Z}function ZW$($,Z){let Q=Number($[3]);if(!Number.isSafeInteger(Q)||Q<=0)return null;let Y=qE4($[1]),X=$[2],J=Z?decodeURIComponent(X):X;if(/^\d+$/.test(J))return null;let G=lK(`https://${Y}/${J}`);if(!G)return null;return{repo:G,number:Q,url:YW(G,Q)}}function QW$($){let Z=$.trim();if(!Z)return null;for(let{re:Q,api:Y}of $W$){let X=Q.exec(Z),J=X?ZW$(X,Y===!0):null;if(J)return J}return null}function Ee0($){let Z=$.length>e3$?$.slice(0,e3$):$;for(let{re:Q,api:Y}of $W$){let X=Q.exec(Z),J=X?ZW$(X,Y===!0):null;if(J)return J}return null}var TE4,$W$,RE4,e3$=200000;var ze0=D(()=>{je0();TE4={github:"pull",gitlab:"-/merge_requests",bitbucket:"pull-requests"};$W$=[{re:/https?:\/\/([^/\s"']+)\/([^\s"']+?)\/-\/merge_requests\/(\d+)/},{re:/https?:\/\/([^/\s"']+)\/([^/\s"']+\/[^/\s"']+)\/pull\/(\d+)/},{re:/https?:\/\/([^/\s"']+)\/([^/\s"']+\/[^/\s"']+)\/pull-requests\/(\d+)/},{re:/https?:\/\/([^/\s"']+)\/repos\/([^/\s"']+\/[^/\s"']+)\/pulls\/(\d+)/,api:!0},{re:/https?:\/\/([^/\s"']+)\/api\/v4\/projects\/([^/\s"']+)\/merge_requests\/(\d+)/,api:!0},{re:/https?:\/\/([^/\s"']+)\/2\.0\/repositories\/([^/\s"']+\/[^/\s"']+)\/pullrequests\/(\d+)/,api:!0}],RE4={"api.github.com":"github.com","api.bitbucket.org":"bitbucket.org"}});function YW$($){return Pe0[$]}function Ae0($,Z){return Pe0[$].checkoutCommand.replace("{number}",String(Z))}function XW$($,Z){let{abbreviation:Q,numberSigil:Y}=Pe0[$];return`${Q} ${Y}${Z}`}var Pe0;var JW$=D(()=>{Pe0={github:{name:"GitHub",cli:"gh",changeRequest:"pull request",abbreviation:"PR",createCommand:"gh pr create",checkoutCommand:"gh pr checkout {number}",numberSigil:"#"},gitlab:{name:"GitLab",cli:"glab",changeRequest:"merge request",abbreviation:"MR",createCommand:"glab mr create",checkoutCommand:"glab mr checkout {number}",numberSigil:"!"},bitbucket:{name:"Bitbucket",cli:null,changeRequest:"pull request",abbreviation:"PR",createCommand:`curl -fsS -X POST -H "Authorization: Bearer $BITBUCKET_TOKEN" -H "Content-Type: application/json" https://api.bitbucket.org/2.0/repositories/<workspace>/<repo>/pullrequests -d '{"title":"<title>","source":{"branch":{"name":"<branch>"}},"destination":{"branch":{"name":"<base>"}}}'`,checkoutCommand:"git fetch origin <source branch> && git checkout <source branch>",numberSigil:"#"}}});var T6=D(()=>{s3$();je0();ze0();JW$()});async function La($,Z,Q){let Y=new AbortController,X,J=new Promise((W,K)=>{X=setTimeout(()=>{Y.abort(),K(new GW$($.id,Q))},Q)}),G=(async()=>{let W=await xG($,Z,!0);try{return(await W.listTools(void 0,{timeout:Q,signal:Y.signal})).tools}finally{await W.close().catch(()=>{})}})();G.catch(()=>{});try{return await Promise.race([G,J])}finally{if(X)clearTimeout(X)}}var GW$;var WW$=D(()=>{wa();GW$=class GW$ extends Error{constructor($,Z){super(`listTools timed out after ${Z}ms for connection ${$}`);this.name="ListToolsTimeoutError"}}});var Te0=b((KW$)=>{Object.defineProperty(KW$,"__esModule",{value:!0});KW$.kvPrefix=KW$.KvWatchInclude=void 0;KW$.KvWatchInclude={LastValue:"",AllHistory:"history",UpdatesOnly:"updates"};KW$.kvPrefix="KV_"});var zW$=b((jW$)=>{Object.defineProperty(jW$,"__esModule",{value:!0});jW$.KvStatusImpl=jW$.Bucket=jW$.Kvm=jW$.kvOperationHdr=void 0;jW$.Base64KeyCodec=IE4;jW$.NoopKvCodecs=Re0;jW$.defaultBucketOpts=UW$;jW$.validateKey=NW$;jW$.validateSearchKey=BW$;jW$.hasWildcards=OW$;jW$.validateBucket=O30;var f9=$G(),s5=B60(),x9=Te0();function IE4(){let $=(Z,Q)=>{let Y=[];for(let X of Z.split("."))switch(X){case">":case"*":Y.push(X);break;default:Y.push(Q(X));break}return Y.join(".")};return{encode(Z){return $(Z,btoa)},decode(Z){return $(Z,atob)}}}function Re0(){return{key:{encode($){return $},decode($){return $}},value:{encode($){return typeof $==="string"?new TextEncoder().encode($):$},decode($){return $}}}}function UW$(){return{replicas:1,history:1,timeout:2000,max_bytes:-1,maxValueSize:-1,codec:Re0(),storage:s5.StorageType.File}}jW$.kvOperationHdr="KV-Operation";var FW$="$KV",VE4=/^[-/=.\w]+$/,kE4=/^[-/=.>*\w]+$/,SE4=/^[-\w]+$/;function NW$($){if($.startsWith(".")||$.endsWith(".")||!VE4.test($))throw Error(`invalid key: ${$}`)}function BW$($){if($.startsWith(".")||$.endsWith(".")||$.includes("..")||!kE4.test($))throw Error(`invalid key: ${$}`)}function OW$($){if($.startsWith(".")||$.endsWith("."))throw Error(`invalid key: ${$}`);let Z=$.split("."),Q=!1;for(let Y=0;Y<Z.length;Y++)switch(Z[Y]){case"*":Q=!0;break;case">":if(Y!==Z.length-1)throw Error(`invalid key: ${$}`);Q=!0;break;default:}return Q}function O30($){if(!SE4.test($))throw Error(`invalid bucket name: ${$}`)}class DW${js;constructor($){this.js=(0,s5.toJetStreamClient)($)}create($,Z={}){return this.#$($,Z)}open($,Z={}){return Z.bindOnly=!0,this.#$($,Z)}#$($,Z={}){let{ok:Q,min:Y}=this.js.nc.features.get(f9.Feature.JS_KV);if(!Q)return Promise.reject(Error(`kv is only supported on servers ${Y} or better`));if(Z.bindOnly)return pl.bind(this.js,$,Z);return pl.create(this.js,$,Z)}list(){let $=(Q)=>{let X=Q.streams.filter((G)=>{return G.config.name.startsWith(x9.kvPrefix)});X.forEach((G)=>{G.config.sealed=G.config.sealed||!1,G.config.deny_delete=G.config.deny_delete||!1,G.config.deny_purge=G.config.deny_purge||!1,G.config.allow_rollup_hdrs=G.config.allow_rollup_hdrs||!1});let J="";if(X.length)J=this.js.nc.info?.cluster??"";return X.map((G)=>{return new D30(G,J)})},Z=`${this.js.prefix}.STREAM.LIST`;return new s5.ListerImpl(Z,$,this.js)}}jW$.Kvm=DW$;class pl{js;jsm;stream;bucket;direct;codec;prefix;editPrefix;useJsPrefix;_prefixLen;constructor($,Z,Q){O30($),this.js=Z,this.jsm=Q,this.bucket=$,this.prefix=FW$,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create($,Z,Q={}){O30(Z);let Y=await $.jetstreamManager(),X=new pl(Z,$,Y);return await X.init(Q),X}static async bind($,Z,Q={}){let Y=$.getOptions()?.checkAPI||Q.bindOnly===!1,X=await $.jetstreamManager(Y),J={config:{allow_direct:Q.allow_direct}};O30(Z);let G=new pl(Z,$,X);return J.config.name=Q.streamName??G.bucketName(),Object.assign(G,J),G.stream=J.config.name,G.codec=Q.codec||Re0(),G.direct=J.config.allow_direct??!1,G.initializePrefixes(J),G}async init($={}){let Z=Object.assign(UW$(),$);this.codec=Z.codec;let Q={};if(this.stream=Q.name=$.streamName??this.bucketName(),Q.retention=s5.RetentionPolicy.Limits,Q.max_msgs_per_subject=Z.history,Z.max_bytes)Q.max_bytes=Z.max_bytes;if(Q.max_msg_size=Z.maxValueSize,Q.storage=Z.storage,$.placement)Q.placement=$.placement;if($.republish)Q.republish=$.republish;if($.description)Q.description=$.description;if($.markerTTL)Q.allow_msg_ttl=!0,Q.subject_delete_marker_ttl=(0,f9.nanos)(Z.markerTTL);if($.mirror){let H=Object.assign({},$.mirror);if(!H.name.startsWith(x9.kvPrefix))H.name=`${x9.kvPrefix}${H.name}`;Q.mirror=H,Q.mirror_direct=!0}else if($.sources){let H=$.sources.map((F)=>{let U=Object.assign({},F),N=U.name.startsWith(x9.kvPrefix)?U.name.substring(x9.kvPrefix.length):U.name;if(!U.name.startsWith(x9.kvPrefix))U.name=`${x9.kvPrefix}${U.name}`;if(!F.external&&N!==this.bucket)U.subject_transforms=[{src:`$KV.${N}.>`,dest:`$KV.${this.bucket}.>`}];return U});Q.sources=H,Q.subjects=[this.subjectForBucket()]}else Q.subjects=[this.subjectForBucket()];if($.metadata)Q.metadata=$.metadata;if(typeof $.compression==="boolean")Q.compression=$.compression?s5.StoreCompression.S2:s5.StoreCompression.None;let Y=this.js.nc,X=Y.getServerVersion(),J=X?(0,f9.compare)(X,(0,f9.parseSemVer)("2.7.2"))>=0:!1;Q.discard=J?s5.DiscardPolicy.New:s5.DiscardPolicy.Old;let{ok:G,min:W}=Y.features.get(f9.Feature.JS_ALLOW_DIRECT);if(!G&&$.allow_direct===!0){let H=X?`${X.major}.${X.minor}.${X.micro}`:"unknown";return Promise.reject(Error(`allow_direct is not available on server version ${H} - requires ${W}`))}if($.allow_direct=typeof $.allow_direct==="boolean"?$.allow_direct:G,Q.allow_direct=$.allow_direct,this.direct=Q.allow_direct,Q.num_replicas=Z.replicas,Z.ttl)Q.max_age=(0,f9.nanos)(Z.ttl);Q.allow_rollup_hdrs=!0;let K;try{if(K=await this.jsm.streams.info(Q.name),!K.config.allow_direct&&this.direct===!0)this.direct=!1}catch(H){if(H.message==="stream not found")K=await this.jsm.streams.add(Q);else throw H}this.initializePrefixes(K)}initializePrefixes($){this._prefixLen=0,this.prefix=`$KV.${this.bucket}`,this.useJsPrefix=this.js.apiPrefix!=="$JS.API";let{mirror:Z}=$.config;if(Z){let Q=Z.name;if(Q.startsWith(x9.kvPrefix))Q=Q.substring(x9.kvPrefix.length);if(Z.external&&Z.external.api!==""){let Y=Z.name.substring(x9.kvPrefix.length);this.useJsPrefix=!1,this.prefix=`$KV.${Y}`,this.editPrefix=`${Z.external.api}.$KV.${Q}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${x9.kvPrefix}${this.bucket}`}subjectForBucket(){return`${this.prefix}.${this.bucket}.>`}subjectForKey($,Z=!1){let Q=[];if(Z){if(this.useJsPrefix)Q.push(this.js.apiPrefix);if(this.editPrefix!=="")Q.push(this.editPrefix);else Q.push(this.prefix)}else if(this.prefix)Q.push(this.prefix);return Q.push($),Q.join(".")}fullKeyName($){if(this.prefix!=="")return`${this.prefix}.${$}`;return`${FW$}.${this.bucket}.${$}`}get prefixLen(){if(this._prefixLen===0)this._prefixLen=this.prefix.length+1;return this._prefixLen}encodeKey($){let Z=[];for(let Q of $.split("."))switch(Q){case">":case"*":Z.push(Q);break;default:Z.push(this.codec.key.encode(Q));break}return Z.join(".")}decodeKey($){let Z=[];for(let Q of $.split("."))switch(Q){case">":case"*":Z.push(Q);break;default:Z.push(this.codec.key.decode(Q));break}return Z.join(".")}validateKey=NW$;validateSearchKey=BW$;hasWildcards=OW$;close(){return Promise.resolve()}dataLen($,Z){let Q=Z?Z.get(s5.JsHeaders.MessageSizeHdr)||"":"";if(Q!=="")return parseInt(Q,10);return $.length}smToEntry($){return new LW$(this.bucket,this.prefixLen,$,this.codec)}jmToWatchEntry($,Z){return new wW$(this.bucket,this.prefixLen,$,Z,this.codec)}async create($,Z,Q){let Y;try{let J={previousSeq:0},G=await this._put($,Z,J,Q);return Promise.resolve(G)}catch(J){if(Y=J,J instanceof s5.JetStreamApiError){let G=J;if(G.code!==s5.JetStreamApiCodes.StreamWrongLastSequence&&G.code!==s5.JetStreamApiCodes.StreamWrongLastSequenceUnknown)return Promise.reject(J)}}let X=0;try{let J=await this.get($);if(J?.operation==="DEL"||J?.operation==="PURGE")return X=J!==null?J.revision:0,this._put($,Z,{previousSeq:X},Q);else return Promise.reject(Y)}catch(J){return Promise.reject(J)}}update($,Z,Q,Y){if(Q<=0)throw Error("version must be greater than 0");return this.put($,Z,{previousSeq:Q,timeout:Y})}async _put($,Z,Q={},Y){let X=this.encodeKey($);this.validateKey(X),Z=this.codec.value.encode(Z);let J={timeout:Q?.timeout};if(Q.previousSeq!==void 0){let G=(0,f9.headers)();J.headers=G,G.set(s5.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Q.previousSeq}`)}if(Y)(J.headers||(0,f9.headers)()).set(s5.PubHeaders.MessageTTL,Y);try{return(await this.js.publish(this.subjectForKey(X,!0),Z,J)).seq}catch(G){return Promise.reject(G)}}put($,Z,Q={}){return this._put($,Z,Q)}async get($,Z){let Q=this.encodeKey($);this.validateKey(Q);let Y={last_by_subj:this.subjectForKey(Q)};if(Z&&Z.revision>0)Y={seq:Z.revision};let X=null;try{if(this.direct)X=await this.jsm.direct.getMessage(this.bucketName(),Y);else X=await this.jsm.streams.getMessage(this.bucketName(),Y);if(X===null)return null;let J=this.smToEntry(X);if(J.rawKey!==Q)return null;return J}catch(J){throw J}}purge($,Z){return this._deleteOrPurge($,"PURGE",Z)}delete($,Z){return this._deleteOrPurge($,"DEL",Z)}async purgeDeletes($=1800000){let Z=[],Q=await this.history({key:">"});await(async()=>{for await(let G of Q)if(G.operation==="DEL"||G.operation==="PURGE")Z.push(G)})().then(),Q.stop();let Y=Date.now()-$,X=Z.map((G)=>{let W=this.subjectForKey(G.key);if(G.created.getTime()>=Y)return this.jsm.streams.purge(this.stream,{filter:W,keep:1});else return this.jsm.streams.purge(this.stream,{filter:W,keep:0})}),J=await Promise.all(X);return J.unshift({success:!0,purged:0}),J.reduce((G,W)=>{return G.purged+=W.purged,G})}async _deleteOrPurge($,Z,Q){if(!this.hasWildcards($))return this._doDeleteOrPurge($,Z,Q);let Y=await this.keys($),X=[];for await(let J of Y)if(X.push(this._doDeleteOrPurge(J,Z)),X.length===100)await Promise.all(X),X.length=0;if(X.length>0)await Promise.all(X)}async _doDeleteOrPurge($,Z,Q){let Y=this.encodeKey($);this.validateKey(Y);let X=(0,f9.headers)();if(X.set(jW$.kvOperationHdr,Z),Z==="PURGE"){let J=Q;if(X.set(s5.JsHeaders.RollupHdr,s5.JsHeaders.RollupValueSubject),typeof J?.ttl==="string"&&J.ttl!=="")X.set(s5.PubHeaders.MessageTTL,`${J.ttl}`)}if(Q?.previousSeq)X.set(s5.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Q.previousSeq}`);await this.js.publish(this.subjectForKey(Y,!0),f9.Empty,{headers:X})}_buildCC($,Z,Q={}){let X=(!Array.isArray($)?[$]:$).map((W)=>{let K=this.encodeKey(W);return this.validateSearchKey(W),this.fullKeyName(K)}),J=s5.DeliverPolicy.LastPerSubject;if(Z===x9.KvWatchInclude.AllHistory)J=s5.DeliverPolicy.All;if(Z===x9.KvWatchInclude.UpdatesOnly)J=s5.DeliverPolicy.New;let G=void 0;if(X.length===1)G=X[0],X=void 0;return Object.assign({deliver_policy:J,ack_policy:s5.AckPolicy.None,filter_subjects:X,filter_subject:G,flow_control:!0,idle_heartbeat:(0,f9.nanos)(5000)},Q)}remove($){return this.purge($)}async history($={}){let Z=$.key??">",Q={};Q.headers_only=$.headers_only||!1;let Y=new f9.QueuedIteratorImpl,X=()=>{Y.stop()},J=this._buildCC(Z,x9.KvWatchInclude.AllHistory,Q),G=await this.js.consumers.getPushConsumer(this.stream,J);if(Y._data=G,(await G.info(!0)).num_pending===0)return Y.push(X),Y;let K=await G.consume({callback:(H)=>{let F=this.jmToWatchEntry(H,!1);if(Y.push(F),Y.received++,H.info.pending===0)Y.push(X)}});return K.closed().then(()=>{Y.push(X)}),(async()=>{for await(let H of K.status())switch(H.type){case"heartbeat":Y.push(()=>{Y.stop()});break}})().then(),Y.iterClosed.then(()=>{K.stop()}),Y}canSetWatcherName(){let $=this.js.nc,{ok:Z}=$.features.get(f9.Feature.JS_NEW_CONSUMER_CREATE_API);return Z}async watch($={}){let Z=$.key??">",Q=new f9.QueuedIteratorImpl,Y={};Y.headers_only=$.headers_only||!1;let X=x9.KvWatchInclude.LastValue;if($.include===x9.KvWatchInclude.AllHistory)X=x9.KvWatchInclude.AllHistory;else if($.include===x9.KvWatchInclude.UpdatesOnly)X=x9.KvWatchInclude.UpdatesOnly;let J=$.ignoreDeletes===!0,G=this._buildCC(Z,X,Y);if(G.name=`KV_WATCHER_${f9.nuid.next()}`,$.resumeFromRevision&&$.resumeFromRevision>0)G.deliver_policy=s5.DeliverPolicy.StartSequence,G.opt_start_seq=$.resumeFromRevision;let W=await this.js.consumers.getPushConsumer(this.stream,G),H=(await W.info(!0)).num_pending,F=X===x9.KvWatchInclude.UpdatesOnly||H===0;Q._data=W;let U=0,N=await W.consume({callback:(B)=>{if(!F)U++,F=U>=H;let O=this.jmToWatchEntry(B,F);if(J&&O.operation==="DEL")return;Q.push(O),Q.received++}});return Q.iterClosed.then(()=>{N.stop()}),N.closed().then(()=>{Q.push(()=>{Q.stop()})}),Q}async keys($=">"){let Z=new f9.QueuedIteratorImpl,Q=this._buildCC($,x9.KvWatchInclude.LastValue,{headers_only:!0}),Y=await this.js.consumers.getPushConsumer(this.stream,Q);if((await Y.info()).num_pending===0)return Z.stop(),Z;Z._data=Y;let J=await Y.consume({callback:(G)=>{let W=G.headers?.get(jW$.kvOperationHdr);if(W!=="DEL"&&W!=="PURGE"){let K=this.decodeKey(G.subject.substring(this.prefixLen));Z.push(K)}if(G.info.pending===0)J.stop()}});return(async()=>{for await(let G of J.status())switch(G.type){case"heartbeat":Z.push(()=>{Z.stop()});break}})().then(),J.closed().then(()=>{Z.push(()=>{Z.stop()})}),Z.iterClosed.then(()=>{J.stop()}),Z}purgeBucket($){return this.jsm.streams.purge(this.bucketName(),$)}destroy(){return this.jsm.streams.delete(this.bucketName())}async status(){let Z=this.js.nc.info?.cluster??"",Q=this.bucketName(),Y=await this.jsm.streams.info(Q);return new D30(Y,Z)}}jW$.Bucket=pl;class D30{si;cluster;constructor($,Z=""){this.si=$,this.cluster=Z}get bucket(){return this.si.config.name.startsWith(x9.kvPrefix)?this.si.config.name.substring(x9.kvPrefix.length):this.si.config.name}get values(){return this.si.state.messages}get history(){return this.si.config.max_msgs_per_subject}get ttl(){return(0,f9.millis)(this.si.config.max_age)}get markerTTL(){if(typeof this.si.config.subject_delete_marker_ttl==="number")return(0,f9.millis)(this.si.config.subject_delete_marker_ttl);return 0}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){return this.si.config.placement?.cluster??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){if(this.si.config.compression)return this.si.config.compression!==s5.StoreCompression.None;return!1}}jW$.KvStatusImpl=D30;class LW${bucket;sm;prefixLen;codec;constructor($,Z,Q,Y){this.bucket=$,this.prefixLen=Z,this.sm=Q,this.codec=Y}get rawKey(){return this.sm.subject.substring(this.prefixLen)}get key(){return this.codec.key.decode(this.rawKey)}get value(){return this.codec.value.decode(this.sm.data)}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){if(this.sm.header?.has("Nats-Marker-Reason")){if(this.sm.header?.get("Nats-Marker-Reason")==="MaxAge")return"PURGE"}return this.sm.header?.get(jW$.kvOperationHdr)||"PUT"}get length(){let $=this.sm.header.get(s5.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}json($){return JSON.parse(f9.TD.decode(this.value),$)}string(){return f9.TD.decode(this.value)}}class wW${bucket;sm;prefixLen;update;codec;constructor($,Z,Q,Y,X){this.bucket=$,this.prefixLen=Z,this.sm=Q,this.update=Y,this.codec=X}get rawKey(){return this.sm.subject.substring(this.prefixLen)}get key(){return this.codec.key.decode(this.rawKey)}get value(){return this.codec.value.decode(this.sm.data)}get created(){return new Date((0,f9.millis)(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){if(this.sm.headers?.has("Nats-Marker-Reason")){if(this.sm.headers?.get("Nats-Marker-Reason")==="MaxAge")return"PURGE"}return this.sm.headers?.get(jW$.kvOperationHdr)||"PUT"}get delta(){return this.sm.info.pending}get length(){let $=this.sm.headers?.get(s5.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}get isUpdate(){return this.update}json($){return JSON.parse(f9.TD.decode(this.value),$)}string(){return f9.TD.decode(this.value)}}});var qe0=b((mK)=>{Object.defineProperty(mK,"__esModule",{value:!0});mK.validateKey=mK.validateBucket=mK.NoopKvCodecs=mK.Kvm=mK.defaultBucketOpts=mK.Bucket=mK.Base64KeyCodec=mK.KvWatchInclude=mK.kvPrefix=void 0;var PW$=Te0();Object.defineProperty(mK,"kvPrefix",{enumerable:!0,get:function(){return PW$.kvPrefix}});Object.defineProperty(mK,"KvWatchInclude",{enumerable:!0,get:function(){return PW$.KvWatchInclude}});var zA=zW$();Object.defineProperty(mK,"Base64KeyCodec",{enumerable:!0,get:function(){return zA.Base64KeyCodec}});Object.defineProperty(mK,"Bucket",{enumerable:!0,get:function(){return zA.Bucket}});Object.defineProperty(mK,"defaultBucketOpts",{enumerable:!0,get:function(){return zA.defaultBucketOpts}});Object.defineProperty(mK,"Kvm",{enumerable:!0,get:function(){return zA.Kvm}});Object.defineProperty(mK,"NoopKvCodecs",{enumerable:!0,get:function(){return zA.NoopKvCodecs}});Object.defineProperty(mK,"validateBucket",{enumerable:!0,get:function(){return zA.validateBucket}});Object.defineProperty(mK,"validateKey",{enumerable:!0,get:function(){return zA.validateKey}})});var za=b((Ew)=>{Object.defineProperty(Ew,"__esModule",{value:!0});Ew.NoopKvCodecs=Ew.Kvm=Ew.defaultBucketOpts=Ew.Bucket=Ew.Base64KeyCodec=Ew.KvWatchInclude=void 0;var lE4=qe0();Object.defineProperty(Ew,"KvWatchInclude",{enumerable:!0,get:function(){return lE4.KvWatchInclude}});var Ea=qe0();Object.defineProperty(Ew,"Base64KeyCodec",{enumerable:!0,get:function(){return Ea.Base64KeyCodec}});Object.defineProperty(Ew,"Bucket",{enumerable:!0,get:function(){return Ea.Bucket}});Object.defineProperty(Ew,"defaultBucketOpts",{enumerable:!0,get:function(){return Ea.defaultBucketOpts}});Object.defineProperty(Ew,"Kvm",{enumerable:!0,get:function(){return Ea.Kvm}});Object.defineProperty(Ew,"NoopKvCodecs",{enumerable:!0,get:function(){return Ea.NoopKvCodecs}})});function zw(){let $=new TextEncoder,Z=new TextDecoder;return{encode:(Q)=>$.encode(JSON.stringify(Q)),decode:(Q)=>JSON.parse(Z.decode(Q))}}class Me0{options;kv=null;codec=zw();constructor($){this.options=$}async init(){let $=this.options.getJetStream();if(!$)return;this.kv=await new TW$.Kvm($).create(mE4,{storage:AW$.StorageType.Memory})}async get($,Z){if(!this.kv)return null;try{let Q=await this.kv.get(`${$}.${Z}`);if(!Q?.value?.length)return null;if(Q.operation==="DEL"||Q.operation==="PURGE")return null;return this.codec.decode(Q.value)}catch{return null}}async set($,Z,Q){if(!this.kv)return;try{await this.kv.put(`${$}.${Z}`,this.codec.encode(Q))}catch{}}async invalidate($){if(!this.kv)return;await Promise.all(["tools","resources","prompts"].map(async(Q)=>{try{await this.kv.delete(`${Q}.${$}`)}catch{}}))}teardown(){this.kv=null}}function dE4($,Z,Q){if(Q<=0)return!0;if($===void 0)return!0;return Z-$>=Q}function RW$($){let Z=["tools","resources","prompts"];for(let Q of Z){let Y=`${Q}:${$}`;w30.delete(Y),Aa.delete(Y)}}function L30($){return $ instanceof M1&&$.code===_1.MethodNotFound}function iE4($){return $ instanceof M1&&$.code===-32000&&/connection closed/i.test($.message)}async function Aw($,Z,Q,Y,X,J=0){if(!Y)try{return await Q()}catch(H){if(L30(H))return[];return Pa.add(1,{type:$,outcome:"error",stage:"no_cache"}),null}let G=`${$}:${Z}`,W=await Y.get($,Z);if(W===null)try{let H=await Q();return Y.set($,Z,H).catch(()=>{}),w30.set(G,Date.now()),Pa.add(1,{type:$,outcome:"miss",stage:"miss"}),H}catch(H){if(L30(H))return Y.set($,Z,[]).catch(()=>{}),[];return Pa.add(1,{type:$,outcome:"error",stage:"miss"}),null}if(Pa.add(1,{type:$,outcome:"hit",stage:"hit"}),dE4(w30.get(G),Date.now(),J)&&!Aa.has(G)){Aa.add(G),w30.set(G,Date.now());let H=Q().then((F)=>Y.set($,Z,F)).catch((F)=>{if(L30(F)||iE4(F)){if(L30(F))Y.set($,Z,[]).catch(()=>{});return}Pa.add(1,{type:$,outcome:"error",stage:"revalidation"})}).finally(()=>Aa.delete(G));X?.(H)}return W}function Ie0($){qW$=$}function GZ(){return qW$}var AW$,TW$,Pa,mE4="DECOCMS_MCP_LISTS",Aa,w30,Pw=30000,qW$=null;var DJ=D(()=>{a9();C6();AW$=C(GN(),1),TW$=C(za(),1),Pa=z$.createCounter("mcp_list_cache.fetches",{description:"MCP list cache fetch outcomes (hit, miss, error)",unit:"{fetches}"});Aa=new Set;z$.createObservableGauge("mcp_list_cache.pending_revalidations",{description:"In-flight background MCP list revalidations on this pod",unit:"{revalidations}"}).addCallback(($)=>$.observe(Aa.size));w30=new Map});function j30($){return(Z)=>{if(Z instanceof M1&&Z.code===_1.MethodNotFound)return $;throw Z}}var MW$=D(()=>{a9()});function E30($,Z,Q){let Y=Tw($,Z,Q,GZ()??void 0),X=TP(Y,{name:"studio-mcp-server",version:"1.0.0"},{capabilities:pE4,toolCallTimeoutMs:Jh});X.server.setRequestHandler(fD,async()=>{return await Y.listResources().catch(j30({resources:[]}))}),X.server.setRequestHandler(yD,async()=>{return await Y.listResourceTemplates().catch(j30({resourceTemplates:[]}))}),X.server.setRequestHandler(gD,async()=>{return await Y.listPrompts().catch(j30({prompts:[]}))});let J=X.close.bind(X);return X.close=async()=>{await J(),await Y.close().catch(()=>{})},X}var pE4;var IW$=D(()=>{aX();a9();Ta();DJ();MW$();pE4={tools:{},resources:{},prompts:{}}});var nl=D(()=>{wa();WW$();IW$()});async function tl($,Z,Q){await(await xG(Z,$,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:Q.state,scopes:Q.scopes,firstRun:Q.firstRun,...Q.vault?{vault:Q.vault}:{}}})}var z30=D(()=>{nl()});import{z as Ve0}from"zod";function oE4($){let{owner:Z,name:Q}=h5({path:$.path});return{owner:Z,name:Q,url:$.webUrl??`https://${$.host}/${$.path}`,repositoryId:$.repositoryId}}function rE4($,Z){if(!Z)return $;return $.filter((Q)=>Q.connection_id!==Z)}function sE4($,Z){let{repository:Q,github_repo:Y,...X}=$,J=Z?W30(Z):null;return{...X,...Z?{repository:G30(Z)}:{},...J?{github_repo:J}:{}}}async function aE4($,Z,Q){let Y=y4.REPORTS(Z),X=await $.storage.connections.findById(Y,Z);if(!X)throw Error("Reports is not set up for this organization yet");let J=sE4(X.configuration_state??{},Q);await $.storage.connections.update(Y,{configuration_state:J});try{await tl($,{...X,configuration_state:J},{state:J,scopes:X.configuration_scopes??[],firstRun:!1})}catch(G){console.error("[reports] ON_MCP_CONFIGURATION after repository change failed",G)}}async function eE4($,Z,Q,Y){let X=Yh(Z),J=await $.storage.virtualMcps.findById(X,Z);if(!J)return;let G=J.metadata??{},W=G.githubRepo,{githubRepo:K,...H}=G;await $.storage.virtualMcps.update(X,Q,{metadata:{...H,...Y?{githubRepo:oE4(Y)}:{}},connections:rE4(J.connections??[],W?.connectionId??null)})}var nE4,tE4,ke0;var VW$=D(()=>{e8();T6();K30();C0();z30();nE4=Ve0.object({repositoryId:Ve0.string().min(1).nullable().describe("Studio repository id to diagnose, or null to unlink the current one.")}),tE4=Ve0.object({repository:Ue0.nullable()});ke0=d({name:"REPORTS_SET_REPOSITORY",description:"Point the organization's Reports diagnostic at one of its linked repositories, or unlink the current one. Works for GitHub, GitLab and Bitbucket.",annotations:{title:"Set Reports Repository",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:nE4,outputSchema:tE4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=p0(Z);if(!Y)throw Error("User ID required to set the diagnostic's repository");let X=null;if($.repositoryId){let J=await Z.storage.repositories.get($.repositoryId,Q.id);if(!J)throw Error(`Repository ${$.repositoryId} is not linked to this organization`);let G={repositoryId:J.id,provider:J.provider,host:J.host,path:J.path,defaultBranch:J.defaultBranch,webUrl:J.webUrl},W=Ue0.safeParse(G);if(!W.success)throw Error(`Repository ${$.repositoryId} has invalid configuration (missing or empty host/path)`);X=W.data}return await aE4(Z,Q.id,X),await eE4(Z,Q.id,Y,X),{repository:X}}})});function Rw($,Z){let Q=`/${encodeURIComponent($)}/settings`;return Z?`${Q}/${Z}`:Q}function P30($,Z){let Q=`/${encodeURIComponent($)}/agents`,Y=Z.panel?`${Q}/${Z.panel}`:Q,X=new URLSearchParams({virtualmcpid:Z.projectId,...Z.search??{}});return`${Y}?${X.toString()}`}var qw=D(()=>{A70()});import{z as uF}from"zod";async function Yz4($,Z,Q,Y){let X=await $.storage.connections.findById(Z,Q);if(X)return X;throw Y}async function Xz4($,Z,Q,Y){let X=await $.storage.virtualMcps.findById(Z,Q);if(X)return X;throw Y}var Se0,$z4=3600000,Zz4,Qz4,Ce0;var kW$=D(()=>{e8();Na();C0();tH();qw();ww();Se0=q70,Zz4=uF.object({siteUrl:uF.string().min(1).describe("Website URL to configure.")}),Qz4=uF.object({connection:eQ,virtualMcp:$Y,reportApp:uF.object({connectionId:uF.string(),virtualMcpId:uF.string(),toolName:uF.literal(Se0)}),created:uF.object({connection:uF.boolean(),virtualMcp:uF.boolean()})});Ce0=d({name:"REPORTS_SETUP",description:"Create or return the Reports connection and virtual MCP for the current organization.",annotations:{title:"Set Up Reports",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Zz4,outputSchema:Qz4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check("COLLECTION_CONNECTIONS_CREATE");let Y=p0(Z);if(!Y)throw Error("User ID required to set up Reports");let X=Lw($.siteUrl);if(!X.ok)throw Error(X.error);let J=y4.REPORTS(Q.id),G=Yh(Q.id),W={email:Z.auth.user?.email,reportUrl:`${Z.baseUrl}${P30(Q.slug??Q.id,{projectId:G,panel:"app",search:{connection:J,tool:Se0}})}`},K=await Z.storage.connections.findById(J,Q.id),H={connection:!1,virtualMcp:!1},F=await c3$({siteUrl:X.value,orgId:Q.id,orgName:Q.name,...W}),U=u3$();if(K)console.log("[reports] syncing connection to claimed site",{orgId:Q.id,siteUrl:X.value,connectionId:J}),K=await Z.storage.connections.update(K.id,{connection_url:U,connection_token:F.authorizationToken,metadata:{...K.metadata??{},siteUrl:X.value}});else{console.log("[reports] creating connection",{orgId:Q.id,siteUrl:X.value,connectionId:J});try{let L=hm1(Q.id,F.authorizationToken,U);K=await Z.storage.connections.create({...L,metadata:{...L.metadata??{},siteUrl:X.value},organization_id:Q.id,created_by:Y}),H.connection=!0}catch(L){K=await Yz4(Z,J,Q.id,L)}}let N=await Z.storage.virtualMcps.findById(G,Q.id);if(!N){console.log("[reports] creating virtual MCP",{orgId:Q.id,siteUrl:X.value,connectionId:K.id,virtualMcpId:G});try{N=await Z.storage.virtualMcps.create(Q.id,Y,um1(Q.id,K.id),{id:G}),H.virtualMcp=!0}catch(L){N=await Xz4(Z,G,Q.id,L)}}if(!N.pinned)N=await Z.storage.virtualMcps.update(N.id,Y,{pinned:!0});let B=await Z.db.selectFrom("organization").select(["createdAt"]).where("id","=",Q.id).executeTakeFirst();if((B?Date.now()-new Date(B.createdAt).getTime():Number.POSITIVE_INFINITY)<$z4){let w=(await Z.storage.organizationSettings.get(Q.id))?.flags,j={};if(w?.reports_only==null)j.reports_only=!0;if(Object.keys(j).length>0)await Z.storage.organizationSettings.upsert(Q.id,{flags:j})}return{connection:K,virtualMcp:N,reportApp:{connectionId:K.id,virtualMcpId:N.id,toolName:Se0},created:H}}})});var SW$=D(()=>{p3$();n3$();t3$();VW$();kW$()});function Ra($,Z,Q){if(Z.some((Y)=>Y!=="*"&&Y.startsWith("SELF::"))&&$.SELF===void 0)$.SELF={value:`${Q}_self`}}function qa($,Z){let Q=new Map;for(let Y of Z){if(Y==="*")continue;let[X,J]=NX0(Y);if(!Gz4.has(J))continue;let G=Qr(X,$);if(typeof G!=="object"||G===null||!("value"in G))continue;let W=G.value;if(typeof W!=="string")continue;Q.set(`${W}:${J}`,{targetConnectionId:W,scope:J})}return[...Q.values()]}async function Ma($,Z,Q,Y){for(let G of Z){if(G==="*")continue;let[W]=NX0(G),K=Qr(W,$);if(K===void 0||K===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let X=T1$($,Z),J=`${Q}_self`;for(let G of X){if(G===J)continue;let W=await Y.storage.connections.findById(G);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${G}`);try{await Y.access.check(G)}catch(K){throw Error(`Access denied to referenced connection: ${G}. ${K.message}`)}}}var Gz4;var _e0=D(()=>{en0();b70();Gz4=new Set([_70,v70])});import{z as CW$}from"zod";var Wz4,Kz4,ve0;var _W$=D(()=>{U6();C0();F$();DJ();z30();_e0();UJ0();tH();Wz4=CW$.object({data:D70.describe("Data for the new connection (id is auto-generated if not provided)")}),Kz4=CW$.object({item:eQ.describe("The created connection entity")}),ve0=d({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection. Auto-fetches and caches the server's tool list.",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Wz4,outputSchema:Kz4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=p0(Z);if(!Y)throw Error("User ID required to create connection");let X={...$.data,organization_id:Q.id,created_by:Y};if(X.id){if((await Z.storage.connections.findById(X.id))?.organization_id===Q.id)throw Error("Connection already exists in organization");if(await Z.storage.connections.findBySanitizedId(X.id))throw Error("Connection id conflicts with an existing connection's isolated database schema")}if(X.connection_type==="VIRTUAL"){let U=$h(X.connection_url);if(!U)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let N=await Z.storage.virtualMcps.findById(U);if(!N)throw Error(`Virtual MCP not found: ${U}`);if(N.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");X.connection_url=Zh(U)}if(X.connection_type==="STDIO"&&!E0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let J=await $l({id:`pending-${Date.now()}`,title:X.title,connection_type:X.connection_type,connection_url:X.connection_url,connection_token:X.connection_token,connection_headers:X.connection_headers}).catch(()=>null),G=J?.tools?.length?J.tools:null,W=J?.scopes?.length?J.scopes:X.configuration_scopes??null,K=X.configuration_state??null;if(K&&W?.length)Ra(K,W,Q.id),await Ma(K,W,Q.id,Z);let H=await Z.storage.connections.createNew({...X,tools:null,configuration_state:K,configuration_scopes:W}),F=K&&W?.length?qa(K,W):[];if(F.length>0){let U;try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:H.id,createdBy:Y,grants:F});let{plaintextToken:N,record:B}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:Q.id,subjectConnectionId:H.id});U=B.id,await tl(Z,H,{state:K,scopes:W,firstRun:!0,vault:{baseUrl:Z.baseUrl,org:Q.slug??Q.id,subjectConnectionId:H.id,token:N}})}catch(N){if(U)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:H.id,tokenId:U});throw await Z.storage.connections.delete(H.id),N}}if(G)GZ()?.set("tools",H.id,G).catch(()=>{});return v1.capture({distinctId:Y,event:"connection_created",groups:{organization:Q.id},properties:{connection_id:H.id,connection_type:H.connection_type,app_name:H.app_name??null,organization_id:Q.id,tools_count:G?.length??0}}),{item:H}}})});import{z as XW}from"zod/v4";import{z as vW$}from"zod/v4";import{z as A30}from"zod/v4";import{z as lF}from"zod/v4";import{z as Nz4}from"zod/v4";import{z as PA}from"zod/v4";import{z as cF}from"zod/v4";import{z as i7}from"zod/v4";import{z as bW$}from"zod/v4";import{z as q30}from"zod/v4";import{z as xz4}from"zod/v4";import{z as xW$}from"zod/v4";import{z as T30}from"zod/v4";import{z as dz4}from"zod/v4";function Ia($,Z){if($===Z)return!0;if($==null||Z==null)return $===Z;if(typeof $!==typeof Z)return!1;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;return $.every((Q,Y)=>Ia(Q,Z[Y]))}if(typeof $==="object"&&typeof Z==="object"){let Q=Object.keys($),Y=Object.keys(Z);if(Q.length!==Y.length)return!1;return Q.every((X)=>Y.includes(X)&&Ia($[X],Z[X]))}return!1}function _z4(){return($)=>{if(!Array.isArray($))return!0;let Z=[];return $.every((Q)=>{if(Z.some((X)=>Ia(Q,X)))return!1;return Z.push(Q),!0})}}function R30($,Z){return $.safeParse(Z).success}function IQ($){if(typeof $==="boolean")return $?XW.any():XW.never();let Z={};for(let X of tz4)X.apply(Z,$);let Q=[];if(Z.string!==!1)Q.push(Z.string||XW.string());if(Z.number!==!1)Q.push(Z.number||XW.number());if(Z.boolean!==!1)Q.push(Z.boolean||XW.boolean());if(Z.null!==!1)Q.push(Z.null||XW.null());if(Z.array!==!1)Q.push(Z.array||XW.array(XW.any()));if(Z.tuple!==!1&&Z.tuple!==void 0)Q.push(Z.tuple);if(Z.object!==!1)if(Z.object)Q.push(Z.object);else{let X=XW.custom((J)=>{return typeof J==="object"&&J!==null&&!Array.isArray(J)},"Must be an object, not an array");Q.push(X)}if(Z.file!==!1&&Z.file!==void 0)Q.push(Z.file);let Y;if(Q.length===0)Y=XW.never();else if(Q.length===1)Y=Q[0];else if(!Object.keys($).some((J)=>J!=="$schema"&&J!=="title"&&J!=="description"))Y=XW.any();else Y=XW.union(Q);for(let X of oz4)Y=X.apply(Y,$);return Y}var Hz4=class{apply($,Z){if(!Z.type)return;let Q=Array.isArray(Z.type)?Z.type:[Z.type],Y=new Set(Q);if(!Y.has("string"))$.string=!1;if(!Y.has("number")&&!Y.has("integer"))$.number=!1;if(!Y.has("boolean"))$.boolean=!1;if(!Y.has("null"))$.null=!1;if(!Y.has("array"))$.array=!1;if(!Y.has("object"))$.object=!1;if(Y.has("integer")&&$.number!==!1){let X=$.number||vW$.number();if(X instanceof vW$.ZodNumber)$.number=X.int()}}},Fz4=class{apply($,Z){if(Z.const===void 0)return;let Q=Z.const;if($.string=!1,$.number=!1,$.boolean=!1,$.null=!1,$.array=!1,$.object=!1,typeof Q==="string")$.string=A30.literal(Q);else if(typeof Q==="number")$.number=A30.literal(Q);else if(typeof Q==="boolean")$.boolean=A30.literal(Q);else if(Q===null)$.null=A30.null();else if(Array.isArray(Q))$.array=void 0;else if(typeof Q==="object")$.object=void 0}},Uz4=class{apply($,Z){if(!Z.enum)return;if(Z.enum.length===0){if(!Z.type)$.string=!1,$.number=!1,$.boolean=!1,$.null=!1,$.array=!1,$.object=!1;return}let Q={string:Z.enum.filter((Y)=>typeof Y==="string"),number:Z.enum.filter((Y)=>typeof Y==="number"),boolean:Z.enum.filter((Y)=>typeof Y==="boolean"),null:Z.enum.filter((Y)=>Y===null),array:Z.enum.filter((Y)=>Array.isArray(Y)),object:Z.enum.filter((Y)=>typeof Y==="object"&&Y!==null&&!Array.isArray(Y))};$.string=this.createTypeSchema(Q.string,"string"),$.number=this.createTypeSchema(Q.number,"number"),$.boolean=this.createTypeSchema(Q.boolean,"boolean"),$.null=Q.null.length>0?lF.null():!1,$.array=Q.array.length>0?void 0:!1,$.object=Q.object.length>0?void 0:!1}createTypeSchema($,Z){if($.length===0)return!1;if($.length===1)return lF.literal($[0]);if(Z==="string")return lF.enum($);if(Z==="number"){let[Q,Y,...X]=$;return lF.union([lF.literal(Q),lF.literal(Y),...X.map((J)=>lF.literal(J))])}if(Z==="boolean")return lF.union([lF.literal(!0),lF.literal(!1)]);return!1}},Bz4=class{apply($,Z){let Q=Z;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let Y=Nz4.file();if(Q.minLength!==void 0)Y=Y.min(Q.minLength);if(Q.maxLength!==void 0)Y=Y.max(Q.maxLength);if(Q.contentMediaType!==void 0)Y=Y.mime(Q.contentMediaType);$.file=Y,$.string=!1}}},Oz4=class{apply($,Z){let Q=Z;if(Z.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if($.string===void 0)$.string=PA.string()}}},Dz4=class{apply($,Z){let Q=Z;if(Q.minLength===void 0)return;if($.string!==!1){let Y=$.string||PA.string();if(Y instanceof PA.ZodString)$.string=Y.refine((X)=>{return Array.from(X).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},Lz4=class{apply($,Z){let Q=Z;if(Q.maxLength===void 0)return;if($.string!==!1){let Y=$.string||PA.string();if(Y instanceof PA.ZodString)$.string=Y.refine((X)=>{return Array.from(X).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},wz4=class{apply($,Z){let Q=Z;if(!Q.pattern)return;if($.string!==!1){let Y=$.string||PA.string();if(Y instanceof PA.ZodString){let X=new RegExp(Q.pattern);$.string=Y.regex(X)}}}},jz4=class{apply($,Z){let Q=Z;if(Q.minimum===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)$.number=Y.min(Q.minimum)}}},Ez4=class{apply($,Z){let Q=Z;if(Q.maximum===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)$.number=Y.max(Q.maximum)}}},zz4=class{apply($,Z){let Q=Z;if(Q.exclusiveMinimum===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)if(typeof Q.exclusiveMinimum==="number")$.number=Y.gt(Q.exclusiveMinimum);else $.number=!1}}},Pz4=class{apply($,Z){let Q=Z;if(Q.exclusiveMaximum===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)if(typeof Q.exclusiveMaximum==="number")$.number=Y.lt(Q.exclusiveMaximum);else $.number=!1}}},Az4=class{apply($,Z){let Q=Z;if(Q.multipleOf===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)$.number=Y.refine((X)=>{if(Q.multipleOf===0)return!1;let J=X/Q.multipleOf,G=Math.round(J),W=Math.min(Math.abs(X)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(J-G)<=W/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Tz4=class{apply($,Z){let Q=Z;if(Z.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if($.array===void 0)$.array=i7.array(i7.any())}}},Rz4=class{apply($,Z){let Q=Z;if(Q.minItems===void 0)return;if($.array!==!1)$.array=($.array||i7.array(i7.any())).min(Q.minItems)}},qz4=class{apply($,Z){let Q=Z;if(Q.maxItems===void 0)return;if($.array!==!1)$.array=($.array||i7.array(i7.any())).max(Q.maxItems)}},Mz4=class{apply($,Z){let Q=Z;if($.array===!1)return;if(Array.isArray(Q.items))$.array=$.array||i7.array(i7.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let Y=IQ(Q.items),X=i7.array(Y);if($.array&&$.array instanceof i7.ZodArray){let J=$.array._def;if(J.checks)J.checks.forEach((G)=>{if(G._zod&&G._zod.def){let W=G._zod.def;if(W.check==="min_length"&&W.minimum!==void 0)X=X.min(W.minimum);else if(W.check==="max_length"&&W.maximum!==void 0)X=X.max(W.maximum)}})}$.array=X}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)$.array=i7.array(i7.any()).max(0);else $.array=$.array||i7.array(i7.any());else if(typeof Q.items==="boolean"&&Q.items===!0)$.array=$.array||i7.array(i7.any());else if(Q.prefixItems)$.array=$.array||i7.array(i7.any())}},Iz4=class{apply($,Z){if(Z.type!=="array")return;let Q=Z;if(!Array.isArray(Q.items))return;if($.array===!1)return;let Y=Q.items.map((J)=>IQ(J)),X;if(Y.length===0)X=bW$.tuple([]);else X=bW$.tuple(Y);if(Q.minItems!==void 0&&Q.minItems>Y.length)X=!1;if(Q.maxItems!==void 0&&Q.maxItems<Y.length)X=!1;$.tuple=X,$.array=!1}},Vz4=class{apply($,Z){let Q=Z;if($.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)$.object=$.object||q30.object({}).passthrough()}},kz4=class{apply($,Z){let Q=Z;if(Z.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if($.object===void 0)$.object=q30.object({}).passthrough()}}},Sz4=class{apply($,Z){let Q=Z;if(Q.maxProperties===void 0)return;if($.object!==!1){let Y=$.object||q30.object({}).passthrough();$.object=Y.refine((X)=>Object.keys(X).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},Cz4=class{apply($,Z){let Q=Z;if(Q.minProperties===void 0)return;if($.object!==!1){let Y=$.object||q30.object({}).passthrough();$.object=Y.refine((X)=>Object.keys(X).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},vz4=class{apply($,Z){if(!Z.not)return $;let Q=IQ(Z.not);return $.refine((Y)=>!R30(Q,Y),{message:"Value must not match the 'not' schema"})}},bz4=class{apply($,Z){if(Z.uniqueItems!==!0)return $;return $.refine(_z4(),{message:"Array items must be unique"})}},fz4=class{apply($,Z){if(!Z.allOf||Z.allOf.length===0)return $;return Z.allOf.map((Y)=>IQ(Y)).reduce((Y,X)=>xz4.intersection(Y,X),$)}},yz4=class{apply($,Z){if(!Z.anyOf||Z.anyOf.length===0)return $;let Q=Z.anyOf.length===1?IQ(Z.anyOf[0]):xW$.union([IQ(Z.anyOf[0]),IQ(Z.anyOf[1]),...Z.anyOf.slice(2).map((Y)=>IQ(Y))]);return xW$.intersection($,Q)}},gz4=class{apply($,Z){if(!Z.oneOf||Z.oneOf.length===0)return $;let Q=Z.oneOf.map((Y)=>IQ(Y));return $.refine((Y)=>{let X=0;for(let J of Q)if(J.safeParse(Y).success){if(X++,X>1)return!1}return X===1},{message:"Value must match exactly one of the oneOf schemas"})}},hz4=class{apply($,Z){let Q=Z;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let X=Q.prefixItems.map((J)=>IQ(J));return $.refine((J)=>{if(!Array.isArray(J))return!0;for(let G=0;G<Math.min(J.length,X.length);G++)if(!R30(X[G],J[G]))return!1;if(J.length>X.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let G=IQ(Q.items);for(let W=X.length;W<J.length;W++)if(!R30(G,J[W]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return $}},uz4=class{apply($,Z){let Q=Z;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return $;if($ instanceof T30.ZodObject||$ instanceof T30.ZodRecord){let Y={};if(Q.properties){for(let[X,J]of Object.entries(Q.properties))if(J!==void 0)Y[X]=IQ(J)}if(Q.required&&Array.isArray(Q.required)){let X=new Set(Q.required);for(let J of Object.keys(Y))if(!X.has(J))Y[J]=Y[J].optional()}else for(let X of Object.keys(Y))Y[X]=Y[X].optional();if(Q.additionalProperties===!1)return T30.object(Y);else return T30.object(Y).passthrough()}return $.refine((Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;if(Q.properties){for(let[X,J]of Object.entries(Q.properties))if(J!==void 0){if(Object.getOwnPropertyDescriptor(Y,X)!==void 0){if(!IQ(J).safeParse(Y[X]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let X of Q.required)if(Object.getOwnPropertyDescriptor(Y,X)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let X=new Set(Object.keys(Q.properties));for(let J in Y)if(!X.has(J))return!1}return!0},{message:"Object constraints validation failed"})}},lz4=class{apply($,Z){if(!Z.enum||Z.enum.length===0)return $;let Q=Z.enum.filter((Y)=>Array.isArray(Y)||typeof Y==="object"&&Y!==null);if(Q.length===0)return $;return $.refine((Y)=>{if(typeof Y!=="object"||Y===null)return!0;return Q.some((X)=>Ia(Y,X))},{message:"Value must match one of the enum values"})}},cz4=class{apply($,Z){if(Z.const===void 0)return $;let Q=Z.const;if(typeof Q!=="object"||Q===null)return $;return $.refine((Y)=>Ia(Y,Q),{message:"Value must equal the const value"})}},mz4=class{apply($,Z){if(Z.description)$=$.describe(Z.description);return $}},iz4=class{apply($,Z){var Q;let Y=Z;if(!((Q=Y.required)==null?void 0:Q.includes("__proto__"))||Z.type!==void 0)return $;return dz4.any().refine((X)=>this.validateRequired(X,Y.required),{message:"Missing required properties"})}validateRequired($,Z){if(typeof $!=="object"||$===null||Array.isArray($))return!0;return Z.every((Q)=>Object.prototype.hasOwnProperty.call($,Q))}},pz4=class{apply($,Z){var Q;let Y=Z;if(Y.contains===void 0)return $;let X=IQ(Y.contains),J=(Q=Y.minContains)!=null?Q:1,G=Y.maxContains;return $.refine((W)=>{if(!Array.isArray(W))return!0;let K=0;for(let H of W)if(R30(X,H))K++;if(K<J)return!1;if(G!==void 0&&K>G)return!1;return!0},{message:"Array must contain required items matching the schema"})}},nz4=class{apply($,Z){let{default:Q}=Z;if(Q===void 0)return $;if(!$.safeParse(Q).success)return $;return $.default(Q)}},tz4,oz4;var fW$=D(()=>{tz4=[new Fz4,new Uz4,new Hz4,new Bz4,new Oz4,new Tz4,new kz4,new Dz4,new Lz4,new wz4,new jz4,new Ez4,new zz4,new Pz4,new Az4,new Iz4,new Rz4,new qz4,new Mz4,new Sz4,new Cz4,new Vz4],oz4=[new iz4,new lz4,new cz4,new fz4,new yz4,new gz4,new hz4,new uz4,new pz4,new vz4,new bz4,new nz4,new mz4]});class be0{constructor($){this._url=$}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise(($,Z)=>{this._socket=new WebSocket(this._url,rz4),this._socket.onerror=(Q)=>{let Y="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);Z(Y),this.onerror?.(Y)},this._socket.onopen=()=>{$()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let Y;try{Y=NG.parse(JSON.parse(Q.data))}catch(X){this.onerror?.(X);return}this.onmessage?.(Y)}})}async close(){this._socket?.close()}send($){return new Promise((Z,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify($)),Z()})}}var rz4="mcp";var yW$=D(()=>{a9()});function sz4($){let Z=$;if(!Z||typeof Z!=="object"||!("method"in Z))return null;switch(Z.method){case"initialize":{let Q=Z?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Z.jsonrpc??"2.0",id:Z.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var xe0;var gW$=D(()=>{Zr();xe0=class xe0 extends SL{constructor($,Z){super($,Z)}send($,Z){let Q=sz4($);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send($,Z)}}});var hW$,uW$=async($,Z,Q)=>{let Y=az4($.connection,Z,Q);if(!Y)throw Error("Unknown MCP connection type");let X=new hW$({name:$?.name??"MCP Client",version:"1.0.0"});return await X.connect(Y),{client:X}},az4=($,Z,Q)=>{if($.type==="Websocket")return new be0(new URL($.url));if($.type!=="SSE"&&$.type!=="HTTP")return null;let X={...$.token?{authorization:`Bearer ${$.token}`}:{},...Q??{},..."headers"in $?$.headers||{}:{}};if($.type==="SSE"){let J={requestInit:{headers:X,signal:Z}};if($.token)J.eventSourceInit={fetch:(G,W)=>{return fetch(G,{...W,headers:{...X,Accept:"text/event-stream"},signal:Z})}};return new MP(new URL($.url),J)}return new xe0(new URL($.url),{requestInit:{headers:X,signal:Z,credentials:"include"}})};var lW$=D(()=>{tN();UX0();yW$();a9();aX();gW$();hW$=class hW$ extends g7{constructor($,Z){super($,{jsonSchemaValidator:PZ,...Z})}async listTools($,Z){return await this.request({method:"tools/list",params:$},ln,Z)}}});function $P4($,Z){if(AA.set($,Z),AA.size>ez4){let Q=AA.keys().next().value;if(Q!==void 0)AA.delete(Q)}}function dW$($){let Z=(Q)=>{if("connection"in $)return uW$({connection:$.connection},void 0,Q);return $.client};return new Proxy({},{get(Q,Y){if(Y==="toJSON")return null;if(typeof Y!=="string")throw Error("Name must be a string");if(Y==="listTools")return W;async function X(K,H=Y){let F=$?.debugId?.(),U=F?{"x-trace-debug-id":F}:void 0,{client:N}=await Z(U),{structuredContent:B,isError:O,content:L}=await N.callTool({name:String(H),arguments:K});if(O){let j=L?.[0]?.text,E=typeof j==="string"?cW$(j):null,z=E?.code&&typeof $?.getErrorByStatusCode==="function"?$.getErrorByStatusCode(E.code,E.message,E.traceId):null;if(z)throw z;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(B??L)}`)}if(B!==void 0)return B;let w=L?.[0]?.text;return typeof w==="string"?cW$(w):void 0}async function J(){let{client:K}=await Z(),{tools:H}=await K.listTools();return H}async function G(){if(!("connection"in $))return J();let K=$.connection,H=JSON.stringify(K);try{if(!AA.has(H))$P4(H,J());return await AA.get(H)}catch(F){console.error("Failed to list tools",F),AA.delete(H);return}}async function W(){return(await G()??[]).map((H)=>mW$(H,X))}return X.asTool=async()=>{let H=(await G()??[]).find((F)=>F.name===Y);if(!H)throw Error(`Tool ${Y} not found`);return mW$(H,X)},X}})}var cW$=($)=>{try{return JSON.parse($)}catch{return $}},ez4=500,AA,mW$=($,Z)=>{return{...$,id:$.name,inputSchema:$.inputSchema?IQ($.inputSchema):void 0,outputSchema:$.outputSchema?IQ($.outputSchema):void 0,execute:(Q)=>{return Z(Q.context,$.name)}}};var iW$=D(()=>{fW$();lW$();AA=new Map});function Va($){return dW$($)}var di5;var pW$=D(()=>{iW$();di5=new Proxy({},{get($,Z){if(Z==="toJSON")return null;if(Z==="forConnection")return(Q)=>Va({connection:Q});if(Z==="forClient")return(Q)=>Va({client:Q});return globalThis[Z]}})});function M30($){return{isImplementedBy:(Z)=>{for(let Q of $){let Y=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,X=Z.find((J)=>Y.test(J.name));if(!X&&Q.opt)continue;if(!X)return!1}return!0}}}var EB=($)=>{return{...M30($),forClient:(Z)=>{return Va({client:Z})},forConnection:(Z)=>{return Va({connection:Z})}}};var ol=D(()=>{pW$()});import{z as y9}from"zod";var nW$,tW$,oW$,rW$,sW$,ZP4;var aW$=D(()=>{ol();nW$=y9.object({specversion:y9.literal("1.0").describe("CloudEvents specification version"),id:y9.string().describe("Unique identifier for this event (UUID recommended)"),source:y9.string().describe("Connection ID of the event publisher"),type:y9.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:y9.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:y9.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:y9.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:y9.string().url().optional().describe("URI to the schema for the data attribute"),data:y9.unknown().optional().describe("Event payload (any JSON value)")}),tW$=y9.object({events:y9.array(nW$).min(1).describe("Batch of CloudEvents to process")}),oW$=y9.object({success:y9.boolean().optional().describe("Whether this event was processed successfully"),error:y9.string().optional().describe("Error message for this event"),retryAfter:y9.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),rW$=y9.object({success:y9.boolean().optional().describe("Batch success - applies to events not in results"),error:y9.string().optional().describe("Batch error message - applies to events not in results"),processedCount:y9.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:y9.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:y9.record(y9.string(),oW$).optional().describe("Per-event results keyed by event ID")}),sW$=[{name:"ON_EVENTS",inputSchema:tW$,outputSchema:rW$}],ZP4=EB(sW$)});import{z as g9}from"zod";var eW$,$K$,ZK$,QK$,YK$,XK$,I30,fe0;var ye0=D(()=>{ol();eW$=g9.object({type:g9.literal("string"),enum:g9.array(g9.string()).optional(),description:g9.string().optional()}),$K$=g9.object({type:g9.string(),description:g9.string(),paramsSchema:g9.record(g9.string(),eW$)}),ZK$=g9.object({}),QK$=g9.object({triggers:g9.array($K$)}),YK$=g9.object({type:g9.string(),params:g9.record(g9.string(),g9.string()),enabled:g9.boolean(),callbackUrl:g9.url().optional(),callbackToken:g9.string().min(1).optional()}),XK$=g9.object({success:g9.boolean()}),I30=[{name:"TRIGGER_LIST",inputSchema:ZK$,outputSchema:QK$},{name:"TRIGGER_CONFIGURE",inputSchema:YK$,outputSchema:XK$}],fe0=EB(I30)});import{z as Z8}from"zod";var QP4,YP4,XP4,JP4,GP4,WP4,KP4,HP4,FP4,UP4,NP4,BP4,TA;var ka=D(()=>{QP4=Z8.object({prefix:Z8.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:Z8.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:Z8.string().optional().describe("Token for pagination from previous response"),delimiter:Z8.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),YP4=Z8.object({objects:Z8.array(Z8.object({key:Z8.string().describe("Object key/path"),size:Z8.number().describe("Object size in bytes"),lastModified:Z8.string().describe("Last modified timestamp"),etag:Z8.string().describe("Entity tag for the object")})),nextContinuationToken:Z8.string().optional().describe("Token for fetching next page of results"),isTruncated:Z8.boolean().describe("Whether there are more results available"),commonPrefixes:Z8.array(Z8.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),XP4=Z8.object({key:Z8.string().describe("Object key/path to get metadata for")}),JP4=Z8.object({contentType:Z8.string().optional().describe("MIME type of the object"),contentLength:Z8.number().describe("Size of the object in bytes"),lastModified:Z8.string().describe("Last modified timestamp"),etag:Z8.string().describe("Entity tag for the object"),metadata:Z8.record(Z8.string(),Z8.string()).optional().describe("Custom metadata key-value pairs")}),GP4=Z8.object({key:Z8.string().describe("Object key/path to generate URL for"),expiresIn:Z8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),WP4=Z8.object({url:Z8.string().describe("Presigned URL for downloading the object"),expiresIn:Z8.number().describe("Expiration time in seconds that was used")}),KP4=Z8.object({key:Z8.string().describe("Object key/path for the upload"),expiresIn:Z8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:Z8.string().optional().describe("MIME type for the object being uploaded")}),HP4=Z8.object({url:Z8.string().describe("Presigned URL for uploading the object"),expiresIn:Z8.number().describe("Expiration time in seconds that was used")}),FP4=Z8.object({key:Z8.string().describe("Object key/path to delete")}),UP4=Z8.object({success:Z8.boolean().describe("Whether the deletion was successful"),key:Z8.string().describe("The key that was deleted")}),NP4=Z8.object({keys:Z8.array(Z8.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),BP4=Z8.object({deleted:Z8.array(Z8.string()).describe("Array of successfully deleted keys"),errors:Z8.array(Z8.object({key:Z8.string(),message:Z8.string()})).describe("Array of errors for failed deletions")}),TA=[{name:"LIST_OBJECTS",inputSchema:QP4,outputSchema:YP4},{name:"GET_OBJECT_METADATA",inputSchema:XP4,outputSchema:JP4},{name:"GET_PRESIGNED_URL",inputSchema:GP4,outputSchema:WP4},{name:"PUT_PRESIGNED_URL",inputSchema:KP4,outputSchema:HP4},{name:"DELETE_OBJECT",inputSchema:FP4,outputSchema:UP4},{name:"DELETE_OBJECTS",inputSchema:NP4,outputSchema:BP4}]});import{z as F5}from"zod";var JK$,GK$,WK$,Sa,V30,k30,S30,C30,OP4;var ge0=D(()=>{ol();JK$=F5.object({primary:F5.string().optional().describe("Primary brand color (hex)"),secondary:F5.string().optional().describe("Secondary brand color (hex)"),accent:F5.string().optional().describe("Accent / highlight color (hex)"),background:F5.string().optional().describe("Background color (hex)"),foreground:F5.string().optional().describe("Foreground / text color (hex)")}),GK$=F5.object({heading:F5.string().optional().describe("Font family for headings"),body:F5.string().optional().describe("Font family for body text"),code:F5.string().optional().describe("Font family for code / monospace")}),WK$=F5.object({logo:F5.string().optional().describe("Logo URL"),favicon:F5.string().optional().describe("Favicon URL"),ogImage:F5.string().optional().describe("Open Graph image URL")}),Sa=F5.object({id:F5.string(),name:F5.string().describe("Brand / company name"),domain:F5.string().optional().describe("Company domain (e.g. example.com)"),colors:JK$.optional().describe("Semantic color palette"),fonts:GK$.optional().describe("Font families by role"),assets:WK$.optional().describe("Visual identity assets"),overview:F5.string().optional().describe("Company overview / description"),tagline:F5.string().optional().describe("Brand tagline"),tone:F5.string().optional().describe("Tone of voice description"),metadata:F5.record(F5.string(),F5.unknown()).optional().describe("Extra design tokens and metadata")}),V30=F5.object({id:F5.string().optional().describe("Brand ID. Omit to get the default brand.")}),k30=F5.object({}),S30=F5.object({items:F5.array(Sa)}),C30=[{name:"BRAND_GET",inputSchema:V30,outputSchema:Sa},{name:"BRAND_LIST",inputSchema:k30,outputSchema:S30,opt:!0}],OP4=EB(C30)});var KK$=D(()=>{ol();aW$();ye0();ka();ge0()});import{z as s8}from"zod";function rl($){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return new RegExp(`^${Q}$`,"i")}function zB($){return s8.object({items:s8.array($).describe("Array of collection items"),totalCount:s8.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:s8.boolean().optional().describe("Whether there are more items available")})}function _a($){return s8.object({item:$.nullable().describe("The retrieved item, or null if not found")})}function wP4($){return s8.object({data:$.partial().describe("Data for the new entity (id may be auto-generated)")})}function jP4($){return s8.object({item:$.describe("The created entity with generated id")})}function EP4($){return s8.object({id:s8.string().describe("ID of the entity to update"),data:$.partial().describe("Partial entity data to update")})}function zP4($){return s8.object({item:$.describe("The updated entity")})}function ba($){return s8.object({item:$.describe("The deleted entity")})}function v30($,Z,Q){let Y=$.toUpperCase(),X=Q?.readOnly??!1,J=[{name:`COLLECTION_${Y}_LIST`,inputSchema:dK,outputSchema:zB(Z)},{name:`COLLECTION_${Y}_GET`,inputSchema:Ca,outputSchema:_a(Z)}];if(!X)J.push({name:`COLLECTION_${Y}_CREATE`,inputSchema:wP4(Z),outputSchema:jP4(Z),opt:!0},{name:`COLLECTION_${Y}_UPDATE`,inputSchema:EP4(Z),outputSchema:zP4(Z),opt:!0},{name:`COLLECTION_${Y}_DELETE`,inputSchema:va,outputSchema:ba(Z),opt:!0});return J}var _30,DP4,HK$,LP4,dK,Ca,va;var LJ=D(()=>{_30=s8.object({id:s8.string().describe("Unique identifier for the entity"),title:s8.string().describe("Human-readable title for the entity"),description:s8.string().nullish().describe("Description of the entity"),created_at:s8.string().datetime(),updated_at:s8.string().datetime(),created_by:s8.string().optional(),updated_by:s8.string().optional()}),DP4=s8.object({field:s8.array(s8.string()),operator:s8.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:s8.unknown()}),HK$=s8.lazy(()=>s8.union([DP4,s8.object({operator:s8.enum(["and","or","not"]),conditions:s8.array(HK$)})]));LP4=s8.object({field:s8.array(s8.string()),direction:s8.enum(["asc","desc"]),nulls:s8.enum(["first","last"]).optional()}),dK=s8.object({where:HK$.optional().describe("Filter expression"),orderBy:s8.array(LP4).optional().describe("Sort expressions"),limit:s8.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:s8.number().int().min(0).optional().describe("Number of items to skip")});Ca=s8.object({id:s8.string().describe("ID of the entity to retrieve")});va=s8.object({id:s8.string().describe("ID of the entity to delete")})});import{z as sl}from"zod";var PP4,AP4,FK$;var UK$=D(()=>{LJ();PP4=_30.extend({avatar:sl.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:sl.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:sl.string().describe("Virtual MCP ID to use for this assistant"),model:sl.object({id:sl.string().describe("Model ID"),connectionId:sl.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),AP4=v30("assistant",PP4),FK$=[...AP4]});import{z as O0}from"zod";var xa,PB,BK$,TP4,RP4,OK$,qP4,MP4,IP4,VP4,kP4,SP4,DK$,CP4,_P4,vP4,bP4,xP4,fP4,yP4,gP4,hP4,uP4,Pp5,lP4,Ap5,NK$,cP4,mP4,b30,Tp5;var LK$=D(()=>{ol();LJ();xa=O0.lazy(()=>O0.union([O0.null(),O0.string(),O0.number(),O0.boolean(),O0.record(O0.string(),xa),O0.array(xa)])),PB=O0.record(O0.string(),O0.record(O0.string(),xa)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),BK$=O0.object({type:O0.literal("text"),text:O0.string().describe("The text content"),providerOptions:PB}),TP4=O0.object({type:O0.literal("text"),text:O0.string().describe("The text content"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),RP4=O0.string().describe("File data as URL string"),OK$=O0.object({type:O0.literal("file"),filename:O0.string().optional().describe("Optional filename of the file"),data:RP4,mediaType:O0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:PB}),qP4=O0.object({type:O0.literal("file"),mediaType:O0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:O0.string().describe("Generated file data as base64 encoded string")}),MP4=O0.object({type:O0.literal("reasoning"),text:O0.string().describe("The reasoning text"),providerOptions:PB}),IP4=O0.object({type:O0.literal("reasoning"),text:O0.string().describe("The reasoning text"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),VP4=O0.object({type:O0.literal("tool-call"),toolCallId:O0.string().describe("ID of the tool call, used to match with tool result"),toolName:O0.string().describe("Name of the tool being called"),input:O0.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:O0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:PB}),kP4=O0.object({type:O0.literal("tool-call"),toolCallId:O0.string().describe("ID of the tool call"),toolName:O0.string().describe("Name of the tool being called"),input:O0.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:O0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),SP4=O0.union([O0.object({type:O0.literal("text"),value:O0.string()}),O0.object({type:O0.literal("json"),value:xa}),O0.object({type:O0.literal("error-text"),value:O0.string()}),O0.object({type:O0.literal("error-json"),value:xa}),O0.object({type:O0.literal("content"),value:O0.array(O0.union([O0.object({type:O0.literal("text"),text:O0.string().describe("Text content")}),O0.object({type:O0.literal("media"),data:O0.string().describe("Base-64 encoded media data"),mediaType:O0.string().describe("IANA media type")})]))}),O0.object({type:O0.literal("execution-denied"),reason:O0.string().optional()}),O0.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),DK$=O0.object({type:O0.literal("tool-result"),toolCallId:O0.string().describe("ID of the tool call that this result is associated with"),toolName:O0.string().describe("Name of the tool that generated this result"),output:SP4.describe("Result of the tool call"),result:O0.unknown().describe("Unknown result of the tool call"),providerOptions:PB}),CP4=O0.object({type:O0.literal("tool-result"),toolCallId:O0.string().describe("ID of the tool call that this result is associated with"),toolName:O0.string().describe("Name of the tool that generated this result"),result:O0.any().describe("Result of the tool call (JSON-serializable)"),isError:O0.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:O0.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),_P4=O0.union([O0.object({type:O0.literal("source"),sourceType:O0.literal("url"),id:O0.string().describe("The ID of the source"),url:O0.string().describe("The URL of the source"),title:O0.string().optional().describe("The title of the source"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),O0.object({type:O0.literal("source"),sourceType:O0.literal("document"),id:O0.string().describe("The ID of the source"),mediaType:O0.string().describe("IANA media type of the document (e.g., application/pdf)"),title:O0.string().describe("The title of the document"),filename:O0.string().optional().describe("Optional filename of the document"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")})]),vP4=O0.object({role:O0.literal("system"),content:O0.string().describe("System message content"),providerOptions:PB}),bP4=O0.object({role:O0.literal("user"),content:O0.array(O0.union([BK$,OK$])).describe("User message content parts (text or file)"),providerOptions:PB}),xP4=O0.object({role:O0.literal("assistant"),content:O0.array(O0.union([BK$,OK$,MP4,VP4,DK$])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:PB}),fP4=O0.object({role:O0.literal("tool"),content:O0.array(DK$).describe("Tool message content (tool results)"),providerOptions:PB}),yP4=O0.union([vP4,bP4,xP4,fP4]),gP4=O0.array(yP4).describe("A list of messages forming the prompt"),hP4=O0.object({prompt:gP4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:O0.number().optional().describe("Maximum number of tokens to generate"),temperature:O0.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:O0.number().optional().describe("Nucleus sampling parameter"),topK:O0.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:O0.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:O0.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:O0.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:O0.array(O0.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:O0.union([O0.object({type:O0.literal("text")}),O0.object({type:O0.literal("json"),schema:O0.any().optional().describe("JSON schema that the generated output should conform to"),name:O0.string().optional().describe("Name of output that should be generated"),description:O0.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:O0.array(O0.any()).optional().describe("The tools that are available for the model"),toolChoice:O0.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:O0.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:O0.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:O0.any().optional().describe("Additional provider-specific options")}),uP4=O0.object({content:O0.array(O0.union([TP4,qP4,IP4,kP4,CP4,_P4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:O0.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:O0.looseObject({inputTokens:O0.number().optional(),outputTokens:O0.number().optional(),totalTokens:O0.number().optional(),reasoningTokens:O0.number().optional()}).describe("Usage information for the language model call"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata"),request:O0.object({body:O0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:O0.object({id:O0.string().optional().describe("ID for the generated response"),timestamp:O0.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:O0.string().optional().describe("The ID of the response model that was used"),headers:O0.record(O0.string(),O0.string()).optional().describe("Response headers"),body:O0.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:O0.array(O0.any()).describe("Warnings for the call, e.g. unsupported settings")}),Pp5=O0.object({stream:O0.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:O0.object({body:O0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:O0.object({headers:O0.record(O0.string(),O0.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),lP4=O0.object({supportedUrls:O0.record(O0.string(),O0.array(O0.string())).describe("Supported URL patterns by media type for the provider")}),Ap5=O0.object({modelId:O0.string().describe("The ID of the model"),logo:O0.string().nullable(),description:O0.string().nullable(),capabilities:O0.array(O0.string()),limits:O0.object({contextWindow:O0.number(),maxOutputTokens:O0.number()}).nullable(),costs:O0.object({input:O0.number(),output:O0.number()}).nullable(),provider:O0.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),NK$=O0.object({modelId:O0.string().describe("The ID of the model"),callOptions:hP4}),cP4=_30.extend({logo:O0.string().nullable(),description:O0.string().nullable(),capabilities:O0.array(O0.string()),limits:O0.object({contextWindow:O0.number(),maxOutputTokens:O0.number()}).nullable(),costs:O0.object({input:O0.number(),output:O0.number()}).nullable(),provider:O0.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),mP4=v30("llm",cP4,{readOnly:!0}),b30=[{name:"LLM_METADATA",inputSchema:O0.object({modelId:O0.string().describe("The ID of the model")}),outputSchema:lP4},{name:"LLM_DO_STREAM",inputSchema:NK$},{name:"LLM_DO_GENERATE",inputSchema:NK$,outputSchema:uP4},...mP4],Tp5=EB(b30)});import{z as RA}from"zod";var dP4,wK$;var jK$=D(()=>{dP4=RA.object({scopes:RA.array(RA.string()).describe("List of scopes available"),stateSchema:RA.record(RA.string(),RA.unknown()).describe("JSON Schema (draft-07) defining the state structure")}),wK$=[{name:"MCP_CONFIGURATION",inputSchema:RA.object({}),outputSchema:dP4}]});import{z as h9}from"zod";var iP4,pP4,EK$;var zK$=D(()=>{iP4=h9.object({}).strict(),pP4=h9.object({billing:h9.object({mode:h9.enum(["prepaid","postpaid"]),limitPeriod:h9.enum(["daily","weekly","monthly"]).nullable()}),limit:h9.object({total:h9.number().nullable(),remaining:h9.number().nullable(),reset:h9.string().nullable()}),usage:h9.object({total:h9.number(),daily:h9.number(),weekly:h9.number(),monthly:h9.number()}),alert:h9.object({enabled:h9.boolean(),threshold_usd:h9.number(),email:h9.string().nullable()}),connectionId:h9.string()}),EK$=[{name:"GATEWAY_USAGE",inputSchema:iP4,outputSchema:pP4},{name:"GATEWAY_SET_LIMIT",inputSchema:h9.object({}),outputSchema:h9.object({}),opt:!0},{name:"GATEWAY_SET_ALERT",inputSchema:h9.object({}),outputSchema:h9.object({}),opt:!0}]});import{z as PK$}from"zod";function JW(){return $X()===null}function x30($,Z){return $===y4.DEV_ASSETS(Z)}function f30($,Z){let Q=Sm1(Z,$),Y=new Date().toISOString();return{id:Q.id??y4.DEV_ASSETS($),title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:Q.app_name??null,app_id:Q.app_id??null,organization_id:$,created_by:"system",created_at:Y,updated_at:Y,connection_type:Q.connection_type,connection_url:Q.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata??null,tools:nP4,bindings:["OBJECT_STORAGE"],status:"active"}}var nP4;var al=D(()=>{SD();ka();e8();nP4=TA.map(($)=>({name:$.name,description:`${$.name} operation for local file storage`,inputSchema:PK$.toJSONSchema($.inputSchema),outputSchema:PK$.toJSONSchema($.outputSchema)}))});function AK$($,Z){return $||Z===0}function TK$($,Z,Q,Y,X){let J=Z?X+1:X,G=$.slice(0,Q),W=Y+Q<J;return{items:G,totalCount:J,hasMore:W}}function RK$($,Z,Q){if(!Q)return{sqlOffset:$,sqlLimit:Z};if($===0)return{sqlOffset:0,sqlLimit:Math.max(Z-1,0)};return{sqlOffset:$-1,sqlLimit:Z}}function tP4($,Z){if(Z.length===0)return;let[Q,...Y]=Z,X=Q==="slug"?lD($):$[Q];for(let J of Y){if(X===null||typeof X!=="object")return;X=X[J]}return X}function oP4($,Z,Q){if($===void 0)return!0;switch(Z){case"eq":return Q===null?$===null:$===Q;case"gt":return $>Q;case"gte":return $>=Q;case"lt":return $<Q;case"lte":return $<=Q;case"in":return Array.isArray(Q)&&Q.includes($);case"like":return typeof $==="string"&&rl(String(Q)).test($);case"contains":return String($).toLowerCase().includes(String(Q).toLowerCase());default:return!0}}function fa($,Z){if(!Z)return!0;if("conditions"in Z){let{operator:Y,conditions:X}=Z;if(X.length===0)return!0;switch(Y){case"and":return X.every((J)=>fa($,J));case"or":return X.some((J)=>fa($,J));case"not":return!X.every((J)=>fa($,J));default:return!0}}let Q=tP4($,Z.field);return oP4(Q,Z.operator,Z.value)}var qK$=D(()=>{k70();LJ()});import{z as Mw}from"zod";var rP4=8,sP4,aP4,eP4,$A4,qA;var he0=D(()=>{KK$();UK$();LJ();LK$();jK$();ka();zK$();e8();C0();E9();DJ();nl();al();tH();k70();qK$();sP4=[{name:/^(COLLECTION_REGISTRY_APP_LIST|REGISTRY_ITEM_LIST)$/,inputSchema:Mw.object({})}],aP4={LLM:b30,LLMS:b30,ASSISTANTS:FK$,MCP:wK$,OBJECT_STORAGE:TA,AI_GATEWAY_BILLING:EK$,TRIGGER:I30,REGISTRY:sP4,BRAND:C30},eP4=dK.extend({binding:Mw.union([Mw.array(Mw.object({}).passthrough()),Mw.object({}).passthrough(),Mw.string()]).optional(),include_virtual:Mw.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false."),slug:Mw.string().optional().describe("Filter by connection slug. Matches against app_name, or a slug derived from connection_url or title.")}),$A4=zB(eQ),qA=d({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:eP4,outputSchema:$A4,handler:async($,Z)=>{await Z.access.check();let Q=K0(Z),Y=$.binding?typeof $.binding==="string"?(()=>{let j=aP4[$.binding.toUpperCase()];if(!j)throw Error(`Unknown binding: ${$.binding}`);return j})():$.binding:void 0,X=Y?M30(Y):void 0,J=!!X,G=$.limit??100,W=$.offset??0,K=s9(),H=y4.DEV_ASSETS(Q.id),F=f30(Q.id,K),U=(!$.slug||lD(F)===$.slug)&&fa(F,$.where),N=JW()&&!J&&U,{sqlOffset:B,sqlLimit:O}=RK$(W,G,N),{items:L,totalCount:w}=await Z.storage.connections.list(Q.id,{includeVirtual:$.include_virtual??!1,slug:$.slug,where:$.where,orderBy:$.orderBy,limit:J?void 0:O,offset:J?void 0:B});if(X){let j=GZ(),E=y4.SELF(Q.id);await Zl(L,rP4,async(z)=>{if(z.tools!==null)return;let T=z.id===E?async()=>{let{listManagementTools:A}=await Promise.resolve().then(() => (Iw(),y30));return A(Z)}:()=>La(z,Z,Gh),P=await Aw("tools",z.id,T,j,(A)=>Z.pendingRevalidations.push(A),Pw);if(P!==null)z.tools=P})}if(JW()&&AK$(J,W)&&U&&!L.some((j)=>j.id===H))L.unshift(F);if(J){let j=(await Promise.all(L.map(async(P)=>{if(!P.tools||P.tools.length===0)return null;return X.isImplementedBy(P.tools.map((q)=>({name:q.name,inputSchema:q.inputSchema,outputSchema:q.outputSchema})))?P:null}))).filter((P)=>P!==null),E=j.length,z=j.slice(W,W+G),T=W+G<E;return{items:z,totalCount:E,hasMore:T}}return TK$(L,N,G,W,w)}})});var ZA4,MA;var ue0=D(()=>{LJ();e8();C0();E9();DJ();nl();al();tH();ZA4=_a(eQ),MA=d({name:"COLLECTION_CONNECTIONS_GET",description:"Get a connection's configuration, tools list, and status by ID.",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:["app"]}},inputSchema:Ca,outputSchema:ZA4,handler:async($,Z)=>{let Q=K0(Z);if(await Z.access.check(),JW()&&x30($.id,Q.id))return{item:f30(Q.id,s9())};let Y=await Z.storage.connections.findById($.id);if(!Y||Y.organization_id!==Q.id)return{item:null};if(Y.tools===null){let X=y4.SELF(Q.id),J=Y.id===X?async()=>{let{listManagementTools:W}=await Promise.resolve().then(() => (Iw(),y30));return W(Z)}:()=>La(Y,Z,Gh),G=await Aw("tools",Y.id,J,GZ(),(W)=>Z.pendingRevalidations.push(W),Pw);if(G!==null)Y.tools=G}return{item:Y}}})});class F9{db;vault;constructor($,Z){this.db=$;this.vault=Z}async get($){let Z=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",$).executeTakeFirst();if(!Z)return null;return QA4(this.vault,Z)}async upsert($){let Z=new Date().toISOString(),Q=await this.vault.encrypt($.accessToken),Y=$.refreshToken?await this.vault.encrypt($.refreshToken):null,X=$.clientSecret?await this.vault.encrypt($.clientSecret):null,J=$.expiresAt?.toISOString()??null,G=await this.db.insertInto("downstream_tokens").values({id:a8("dtok"),connectionId:$.connectionId,accessToken:Q,refreshToken:Y,scope:$.scope,expiresAt:J,clientId:$.clientId,clientSecret:X,tokenEndpoint:$.tokenEndpoint,createdAt:Z,updatedAt:Z}).onConflict((W)=>W.column("connectionId").doUpdateSet({accessToken:Q,refreshToken:Y,scope:$.scope,expiresAt:J,clientId:$.clientId,clientSecret:X,tokenEndpoint:$.tokenEndpoint,updatedAt:Z})).returning(["id","createdAt"]).executeTakeFirstOrThrow();return{id:G.id,connectionId:$.connectionId,accessToken:$.accessToken,refreshToken:$.refreshToken,scope:$.scope,expiresAt:$.expiresAt,createdAt:G.createdAt,updatedAt:Z,clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpoint:$.tokenEndpoint}}async delete($){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",$).execute()}isExpired($,Z=0){if(!$.expiresAt)return!1;let Y=($.expiresAt instanceof Date?$.expiresAt:new Date($.expiresAt)).getTime();if(Number.isNaN(Y))return!0;return Y-Z<Date.now()}}async function QA4($,Z){try{let Q=await $.decrypt(Z.accessToken),Y=Z.refreshToken?await $.decrypt(Z.refreshToken):null,X=Z.clientSecret?await $.decrypt(Z.clientSecret):null;return{id:Z.id,connectionId:Z.connectionId,accessToken:Q,refreshToken:Y,scope:Z.scope,expiresAt:Z.expiresAt,createdAt:Z.createdAt,updatedAt:Z.updatedAt,clientId:Z.clientId,clientSecret:X,tokenEndpoint:Z.tokenEndpoint}}catch(Q){return console.warn("[DownstreamToken] failed to decrypt token row",{connectionId:Z.connectionId,message:Q instanceof Error?Q.message:String(Q)}),null}}var iK=D(()=>{ZY()});function el(...$){if(GA4)console.log("[mcp-read-cache]",...$)}function WA4($){return $.kind==="org"?"org":`u:${$.userId}`}function le0($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(le0).join(",")}]`;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${le0($[Q])}`).join(",")}}`}class u30{config;maxEntries;now;maxTotalBytes;store=new Map;revalidating=new Set;totalBytes=0;constructor($=YA4,Z=XA4,Q=()=>Date.now(),Y=JA4){this.config=$;this.maxEntries=Z;this.now=Q;this.maxTotalBytes=Y}stats(){return{entries:this.store.size,bytes:this.totalBytes}}deleteKey($){let Z=this.store.get($);if(Z)this.store.delete($),this.totalBytes-=Z.bytes}key($,Z,Q,Y){return`${Z}:${WA4(Q)}:${$}:${le0(Y)}`}storeSet($,Z,Q,Y){let X;try{X=JSON.stringify(Z).length}catch{el("SKIP non-serializable",$);return}if(X>Y){el("SKIP oversize",$,`${X}b > cap ${Y}b`);return}this.deleteKey($);while(this.store.size>0&&(this.store.size>=this.maxEntries||this.totalBytes+X>this.maxTotalBytes)){let J=this.store.keys().next().value;if(J===void 0)break;this.deleteKey(J)}this.store.set($,{value:Z,storedAt:Q,bytes:X}),this.totalBytes+=X}async fetch($){let{type:Z,connectionId:Q,scope:Y,params:X,fetchLive:J,shouldCache:G,onRevalidation:W}=$,K=this.config[Z],H=this.key(Z,Q,Y,X),F=this.now(),U=this.store.get(H),N=U?F-U.storedAt:1/0;if(!U||N>K.maxStaleMs){g30.add(1,{type:Z,outcome:"miss"}),el(U?"EXPIRED":"MISS",H);let B=await J();if(G?.(B)??!0)this.storeSet(H,B,this.now(),K.maxValueBytes);else el("NOT-CACHED (shouldCache=false)",H);return B}if(this.store.delete(H),this.store.set(H,U),N>K.revalidateAfterMs&&!this.revalidating.has(H)){g30.add(1,{type:Z,outcome:"stale"}),el("STALE \u2192 serve + revalidate",H,`age=${N}ms`),this.revalidating.add(H);let B=J().then((O)=>{if(G?.(O)??!0)this.storeSet(H,O,this.now(),K.maxValueBytes)}).catch(()=>{g30.add(1,{type:Z,outcome:"error"})}).finally(()=>this.revalidating.delete(H));W?.(B)}else g30.add(1,{type:Z,outcome:"hit"}),el("HIT",H,`age=${N}ms`);return U.value}invalidate($){let Z=`${$}:`;for(let Q of[...this.store.keys()])if(Q.startsWith(Z))this.deleteKey(Q)}}function me0(){return E0().mcpCacheEnabled}function l30(){return me0()?ce0:null}var g30,h30=1024,MK$,YA4,XA4=2000,JA4,GA4,ce0;var ya=D(()=>{C6();F$();g30=z$.createCounter("mcp_read_cache.fetches",{description:"MCP read cache outcomes (hit, stale, miss, error)",unit:"{fetches}"}),MK$=h30*h30,YA4={"tools/call":{revalidateAfterMs:30000,maxStaleMs:300000,maxValueBytes:512*h30},"resources/read":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:4*MK$},"prompts/get":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:512*h30}},JA4=256*MK$,GA4=typeof process<"u"&&!!process.env?.MCP_CACHE_DEBUG;ce0=new u30;z$.createObservableGauge("mcp_read_cache.entries",{description:"Current entry count in the per-pod MCP read cache",unit:"{entries}"}).addCallback(($)=>$.observe(ce0.stats().entries));z$.createObservableGauge("mcp_read_cache.bytes",{description:"Approximate total bytes held in the per-pod MCP read cache",unit:"By"}).addCallback(($)=>$.observe(ce0.stats().bytes))});function SK$(){if(IK$)return;IK$=!0;try{VK$=z$.createCounter("virtual_mcp.aggregate_cache.lookups",{description:"Virtual MCP aggregate tool-list cache lookups by outcome (hit, miss, expired)",unit:"{lookups}"}),kK$=z$.createCounter("virtual_mcp.aggregate_cache.evictions",{description:"Virtual MCP aggregate tool-list cache entries dropped, by reason (capacity, invalidated, failed)",unit:"{entries}"}),z$.createObservableGauge("virtual_mcp.aggregate_cache.entries",{description:"Live entries in this pod's Virtual MCP aggregate tool-list cache",unit:"{entries}"}).addCallback(($)=>$.observe(GW.size))}catch($){console.error("[aggregate-cache] failed to register metrics:",$)}}function de0($){SK$(),VK$?.add(1,{outcome:$})}function ie0($,Z=1){if(Z<=0)return;SK$(),kK$?.add(Z,{reason:$})}function CK$($){return[$.virtualMcpId??"",$.userId??"",$.superUser?"su":"",[...$.connectionIds].sort().join(",")].join("|")}function _K$($){let Z=GW.get($);if(!Z)return de0("miss"),null;if(Date.now()-Z.at>=KA4)return GW.delete($),de0("expired"),null;return de0("hit"),Z.value}function vK$($,Z,Q){let Y=Q.catch((J)=>{if(GW.get($)?.value===Y)GW.delete($),ie0("failed");throw J});GW.delete($),GW.set($,{at:Date.now(),deps:Z,value:Y});let X=0;while(GW.size>HA4){let J=GW.keys().next();if(J.done)break;GW.delete(J.value),X++}return ie0("capacity",X),Y}function bK$($){let Z=0;for(let[Q,Y]of GW)if(Y.deps.includes($))GW.delete(Q),Z++;ie0("invalidated",Z)}var KA4=30000,HA4=500,GW,VK$=null,kK$=null,IK$=!1;var pe0=D(()=>{C6();GW=new Map});function yK$($){l30()?.invalidate($),RW$($),bK$($)}function $c($){yK$($);let Z=ne0?.();if(!Z)return;try{Z.publish(xK$,FA4.encode(JSON.stringify({connectionId:$,originId:fK$})))}catch(Q){console.warn("[McpCacheInvalidation] publish failed (non-critical):",Q)}}function gK$($){if(ne0=$,ga)return;let Z=$();if(!Z)return;ga=Z.subscribe(xK$),(async()=>{for await(let Q of ga)try{let Y=JSON.parse(UA4.decode(Q.data));if(Y.originId===fK$)continue;yK$(Y.connectionId)}catch{}})().catch(console.error)}function hK$(){ga?.unsubscribe(),ga=null,ne0=void 0}var xK$="studio.mcp-cache.invalidate",fK$,FA4,UA4,ne0,ga=null;var ha=D(()=>{ya();DJ();pe0();fK$=crypto.randomUUID(),FA4=new TextEncoder,UA4=new TextDecoder});import{z as te0}from"zod";function BA4($){let Z={...$};for(let Q of NA4)delete Z[Q];return Z}function OA4($,Z){return $.connection_url!==void 0?$.connection_url:Z}function wA4($,Z){return $.length===Z.length&&$.every((Q,Y)=>Q===Z[Y])}var NA4,DA4,LA4,oe0;var uK$=D(()=>{z30();iK();C0();F$();DJ();ha();_e0();UJ0();tH();NA4=["id","organization_id","created_by","created_at"];DA4=te0.object({id:te0.string().describe("ID of the connection to update"),data:L70.describe("Partial connection data to update")}),LA4=te0.object({item:eQ.describe("The updated connection entity")});oe0=d({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update a connection's configuration. Re-fetches tools from the server on URL change.",annotations:{title:"Update Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:DA4,outputSchema:LA4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=p0(Z);if(!Y)throw Error("User ID required to update connection");let{id:X}=$,J=BA4($.data),G=J.configuration_state!==void 0||J.configuration_scopes!==void 0,W=await Z.storage.connections.findById(X);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let K=J.connection_type??W.connection_type,H=OA4(J,W.connection_url);if(K==="VIRTUAL"){let y=$h(H);if(!y)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let g=await Z.storage.virtualMcps.findById(y);if(!g)throw Error(`Virtual MCP not found: ${y}`);if(g.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=Zh(y)}let F=J.configuration_state??W.configuration_state??{},U=J.configuration_scopes??W.configuration_scopes??[];if(G){if(J.configuration_state!==void 0)F=J.configuration_state??{};else if(F===null||F===void 0)F={};if(J.configuration_scopes!==void 0)U=J.configuration_scopes??[];if(U.length>0){let y=F;Ra(y,U,Q.id),await Ma(y,U,Q.id,Z)}}if(K==="STDIO"&&!E0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let N=J.connection_token??W.connection_token;if(!N)try{let g=await new F9(Z.db,Z.vault).get(X);if(g?.accessToken)N=g.accessToken}catch{}let B=await $l({id:W.id,title:J.title??W.title,connection_type:K,connection_url:H,connection_token:N,connection_headers:J.connection_headers??W.connection_headers}).catch(()=>null),O=B?.tools?.length?B.tools:null,L=!1;if(J.configuration_scopes===void 0&&B?.scopes?.length)L=!wA4(U,B.scopes),U=B.scopes;if(Ra(F,U,Q.id),L&&U.length>0)await Ma(F,U,Q.id,Z);let w=G||L,j=w?qa(F,U):[],E=w?qa(W.configuration_state??{},W.configuration_scopes??[]):[],z=W.configuration_state,T=z==null||Object.keys(z).length===0,P,A,q=async()=>{try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:X,createdBy:Y,grants:E})}catch(y){console.error("Failed to restore credential grants after credential vault mutation failed",y)}},x={...J,connection_url:H,tools:null,configuration_state:F,configuration_scopes:U,updated_by:Y},_={...W,...x};if(w)try{if(await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:X,createdBy:Y,grants:j}),j.length>0){if(!await Z.storage.connectionCredentialVault.findActiveWorkloadToken({organizationId:Q.id,subjectConnectionId:X})){let{plaintextToken:g,record:l}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:Q.id,subjectConnectionId:X});A=l.id,P={baseUrl:Z.baseUrl,org:Q.slug??Q.id,subjectConnectionId:X,token:g}}}}catch(y){if(A)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:X,tokenId:A});throw await q(),y}if(w&&F&&U)try{await tl(Z,_,{state:F,scopes:U,firstRun:T,...P?{vault:P}:{}})}catch(y){if(console.error("Failed to invoke ON_MCP_CONFIGURATION callback",y),A)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:X,tokenId:A});if(j.length>0)throw await q(),y}let V;try{V=await Z.storage.connections.update(X,x)}catch(y){if(w){if(A)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:X,tokenId:A});await q()}throw y}if(O)GZ()?.set("tools",X,O).catch(()=>{});return $c(X),{item:V}}})});import{z as jA4}from"zod";var EA4,re0;var lK$=D(()=>{LJ();U6();C0();DJ();ha();WW();al();tH();EA4=va.extend({force:jA4.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),re0=d({name:"COLLECTION_CONNECTIONS_DELETE",description:"Permanently delete a connection. Set force=true to auto-remove from referencing Virtual MCPs.",annotations:{title:"Delete Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:EA4,outputSchema:ba(eQ),handler:async($,Z)=>{a(Z);let Q=K0(Z);if(await Z.access.check(),JW()&&x30($.id,Q.id))throw Error("This connection is a fixed system connection and cannot be deleted");let Y=await Z.storage.connections.findById($.id);if(!Y)throw Error(`Connection not found: ${$.id}`);if(Y.organization_id!==Q.id)throw Error("Connection not found in organization");if(Y.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");let J=await Z.storage.virtualMcps.listByConnectionId(Q.id,$.id);if(J.length>0)if($.force)await Z.storage.virtualMcps.removeConnectionReferences($.id);else throw Error(JSON.stringify({code:"CONNECTION_IN_USE",agentNames:J.map((K)=>K.title)}));let G=await Z.storage.automations.listActiveByEventTriggerConnectionId($.id);if(G.length>0)if($.force)await Promise.all(G.map((K)=>Z.storage.automations.deactivateAutomation(K.id)));else throw Error(JSON.stringify({code:"CONNECTION_IN_USE_BY_AUTOMATION",automationNames:G.map((K)=>K.name)}));await Z.storage.connections.delete($.id),cK$($.id),await Z.storage.triggerCallbackTokens.deleteByConnection($.id,Q.id),GZ()?.invalidate($.id).catch(()=>{}),$c($.id);let W=p0(Z);if(W)v1.capture({distinctId:W,event:"connection_deleted",groups:{organization:Q.id},properties:{connection_id:Y.id,connection_type:Y.connection_type,app_name:Y.app_name??null,organization_id:Q.id,forced:$.force??!1}});return{item:Y}}})});import{z as Zc}from"zod";var se0;var mK$=D(()=>{C0();se0=d({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:Zc.object({id:Zc.string()}),outputSchema:Zc.object({id:Zc.string(),healthy:Zc.boolean(),latencyMs:Zc.number()}),handler:async($,Z)=>{let Q=K0(Z);await Z.access.check();let Y=await Z.storage.connections.findById($.id);if(!Y||Y.organization_id!==Q.id)throw Error("Connection not found");let X=await Z.storage.connections.testConnection($.id);return{id:$.id,...X}}})});var dK$=D(()=>{_W$();he0();ue0();uK$();lK$();mK$()});import{sql as L6}from"kysely";import{z as mF}from"zod";function iK$($){if($===null||$===void 0)return"NULL";if(typeof $==="number")return String($);if(typeof $==="boolean")return $?"TRUE":"FALSE";if(typeof $==="string")return`'${$.replace(/'/g,"''")}'`;if($ instanceof Date)return`'${$.toISOString()}'`;return`'${JSON.stringify($).replace(/'/g,"''")}'`}function AA4($,Z){let Q="",Y=0,X=!1,J=!1,G=!1,W=null;for(let K=0;K<$.length;K++){let H=$[K];if(!X&&!J&&W===null){if($.startsWith("--",K)){let F=$.indexOf(`
|
|
1009
|
+
`);for(let z of E.warnings)K.push({requestId:j.id,warning:z});for(let z of(Q=j.options.tools)!=null?Q:[])if(z.type==="provider"&&!aw4.has(z.id))K.push({requestId:j.id,warning:{type:"unsupported",feature:`batch result conversion for tool "${z.name}"`,details:"OpenAI may return output for this tool that AI SDK text batches cannot currently convert."}})}let U="batch.jsonl",N=new Blob(W,{type:"application/jsonl"});W.length=0;let B=new FormData;B.append("file",N,U),B.append("purpose","batch"),B.append("expires_after[anchor]","created_at"),B.append("expires_after[seconds]",String(F));let{value:O}=await Kl({url:this.getUrl("/files"),headers:T1((X=(Y=this.options.config).headers)==null?void 0:X.call(Y),$.headers),body:{content:B,values:{purpose:"batch","expires_after[anchor]":"created_at","expires_after[seconds]":String(F),file:{name:U,type:N.type,size:N.size}}},failedResponseHandler:R9,successfulResponseHandler:E1($30),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),{value:L}=await o1({url:this.getUrl("/batches"),headers:T1((G=(J=this.options.config).headers)==null?void 0:G.call(J),$.headers),body:{input_file_id:O.id,endpoint:xG$,completion_window:"24h"},failedResponseHandler:R9,successfulResponseHandler:E1(ba0),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),w=aa0(O.expires_at);return{batchId:L.id,...eG0(L),providerMetadata:{openai:{inputFileId:O.id,...w!=null?{inputFileExpiresAt:w}:{}}},warnings:K}}async parseBatchProviderOptions($){let Z=this.options.config.provider.includes("azure")?"azure":"openai",Q=await I$({provider:Z,providerOptions:$,schema:fG$});if(Q==null&&Z!=="openai")Q=await I$({provider:"openai",providerOptions:$,schema:fG$});return Q}async doGetBatchStatus($){let Z=await this.retrieveBatch($);return eG0(Z)}async doCancelBatch($){var Z,Q;return await o1({url:this.getUrl(`/batches/${encodeURIComponent($.batchId)}/cancel`),headers:T1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),body:{},failedResponseHandler:R9,successfulResponseHandler:E1(ba0),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),{}}async doListBatches($){var Z,Q;let Y=new URL(this.getUrl("/batches"));if($.limit!=null)Y.searchParams.set("limit",String($.limit));if($.cursor!=null)Y.searchParams.set("after",$.cursor);let{value:X}=await S6({url:Y.toString(),headers:T1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),failedResponseHandler:R9,successfulResponseHandler:E1(ow4),abortSignal:$.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return{batches:X.data.map((J)=>({batchId:J.id,...eG0(J)})),...X.has_more&&X.last_id!=null?{nextCursor:X.last_id}:{}}}async doGetBatchResults($){let Z=await this.retrieveBatch($),Q=eG0(Z);if(Q.status==="pending")throw new b8({argument:"batchId",message:`OpenAI batch "${$.batchId}" is not complete.`});let Y=[Z.output_file_id,Z.error_file_id].filter((J)=>J!=null);if(Q.status==="completed"&&Y.length===0)throw new W9({data:Z,message:`OpenAI batch "${$.batchId}" completed without batch output.`});let X=this.iterateBatchResults({fileIds:Y,options:$});return wF(X)}async retrieveBatch($){var Z,Q;let{value:Y}=await S6({url:this.getUrl(`/batches/${encodeURIComponent($.batchId)}`),headers:T1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),failedResponseHandler:R9,successfulResponseHandler:E1(ba0),abortSignal:$.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return Y}async*iterateBatchResults({fileIds:$,options:Z}){var Q,Y;for(let X of $){let{value:J}=await S6({url:this.getUrl(`/files/${encodeURIComponent(X)}/content`),headers:T1((Y=(Q=this.options.config).headers)==null?void 0:Y.call(Q),Z.headers),failedResponseHandler:R9,successfulResponseHandler:rL(tw4),abortSignal:Z.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});for await(let G of J)yield await this.convertResultLine(G)}}async convertResultLine($){if($.error!=null){let Q={message:$.error.message,code:$.error.code};if($.error.code==="batch_cancelled")return{type:"text",id:$.custom_id,status:"cancelled",error:Q};if($.error.code==="batch_expired")return{type:"text",id:$.custom_id,status:"expired",error:Q};return{type:"text",id:$.custom_id,status:"failed",error:Q}}if($.response==null)return{type:"text",id:$.custom_id,status:"failed",error:{message:"OpenAI returned a batch result without a response or error.",code:"invalid_batch_result"}};if($.response.status_code<200||$.response.status_code>=300)return{type:"text",id:$.custom_id,status:"failed",error:await Zj4({body:$.response.body,statusCode:$.response.status_code})};let Z=await Qj4($.response.body);if(!Z.success)return{type:"text",id:$.custom_id,status:"failed",error:Z.error};return{type:"text",id:$.custom_id,status:"succeeded",result:Z.result}}async prepareRequest($){let{args:Z,warnings:Q}=await G3$.prepareRequest({modelId:$.modelId,config:this.options.config,options:$.options});return{body:Z,warnings:Q}}getUrl($){return this.options.config.url({path:$,modelId:""})}},aw4,Yj4,Xj4,yG$,$e0,Jj4,gG$,hG$,Q30,xa0,K3$,Gj4,Wj4,Uj4,uG$=class{constructor($,Z){this.modelId=$,this.config=Z,this.specificationVersion="v4",this.capabilities={conversation:"continuous",transports:["websocket","webrtc"],connections:["server-websocket","webrtc"],startup:"session-start",finalization:"session-close"}}get provider(){return this.config.provider}getWebRTCConfig(){return{dataChannelLabel:"oai-events"}}getServerWebSocketConfig(){let $=new URL(`${this.config.baseURL}/live/sessions`);$.protocol=$.protocol==="http:"?"ws:":"wss:";let Z={};for(let[Q,Y]of Object.entries(this.config.headers()))if(Y!==void 0)Z[Q]=Y;return{url:$.toString(),headers:Z}}async doCreateWebRTCSession({sdp:$,sessionConfig:Z={},abortSignal:Q}){let Y=ea0(Z,this.modelId,"webrtc"),{value:X}=await o1({url:`${this.config.baseURL}/live/sessions`,headers:this.config.headers(),body:{session:Y,transport:{type:"webrtc",sdp:LA.string().min(1).parse($)}},failedResponseHandler:R9,successfulResponseHandler:E1(Uj4),abortSignal:Q,fetch:this.config.fetch});return{sessionId:X.session.id,sdp:X.transport.sdp}}parseServerEvent($){return H3$($)}createServerEventParser(){return Kj4()}serializeClientEvent($){return Fj4($,this.modelId)}buildSessionConfig($){return ea0($,this.modelId)}},Oj4=class{constructor($,Z){this.specificationVersion="v4",this.modelId=$,this.provider=Z.provider,this.config=Z}async doCreateClientSecret($){var Z;let Q=(Z=this.config.fetch)!=null?Z:fetch,Y=`${this.config.baseURL}/realtime/client_secrets`,X=$.sessionConfig!=null?Ze0($.sessionConfig,this.modelId):{type:"realtime",model:this.modelId},J=await Q(Y,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify({session:X,...$.expiresAfterSeconds!=null?{expires_after:{anchor:"created_at",seconds:$.expiresAfterSeconds}}:{}})});if(!J.ok){let W=await J.text();throw Error(`OpenAI realtime client secret request failed: ${J.status} ${W}`)}let G=await J.json();return{token:G.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:G.expires_at}}getWebSocketConfig($){return{url:$.url,protocols:["realtime",`openai-insecure-api-key.${$.token}`]}}parseServerEvent($){return Nj4($)}serializeClientEvent($){return Bj4($,this.modelId)}buildSessionConfig($){return Ze0($,this.modelId)}},Dj4,jj4,Ej4,zj4,lG$,mG$,Pj4,Mj4,Ij4,_j4,Kl5,vj4=class{constructor($){this.config=$,this.specificationVersion="v4"}get provider(){return this.config.provider}async uploadSkill($){let Z=[];if($.displayTitle!=null)Z.push({type:"unsupported",feature:"displayTitle"});let Q=new FormData;for(let X of $.files){let J=jF(X.data);Q.append("files[]",new Blob([J]),X.path)}let{value:Y}=await p3({url:this.config.url({path:"/skills"}),headers:T1(this.config.headers()),formData:Q,failedResponseHandler:R9,successfulResponseHandler:E1(_j4),fetch:this.config.fetch});return{providerReference:{openai:Y.id},...Y.name!=null?{name:Y.name}:{},...Y.description!=null?{description:Y.description}:{},...Y.latest_version!=null?{latestVersion:Y.latest_version}:{},providerMetadata:{openai:{...Y.default_version!=null?{defaultVersion:Y.default_version}:{},...Y.created_at!=null?{createdAt:Y.created_at}:{},...Y.updated_at!=null?{updatedAt:Y.updated_at}:{}}},warnings:Z}}},bj4="4.0.71",Hl5;var X30=D(()=>{z0();lJ0();O1();z0();z0();O1();z0();z0();O1();z0();z0();z0();z0();O1();O1();z0();z0();O1();z0();z0();z0();O1();z0();z0();z0();O1();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();z0();O1();z0();z0();z0();O1();z0();O1();z0();O1();z0();z0();O1();z0();O1();z0();O1();O1();z0();z0();O1();z0();z0();z0();O1();z0();z0();z0();z0();Y30=Ow.object({error:Ow.object({message:Ow.string(),type:Ow.string().nullish(),param:Ow.any().nullish(),code:Ow.union([Ow.string(),Ow.number()]).nullish()})}),R9=V4({errorSchema:Y30,errorToMessage:($)=>$.error.message});pD4=W0(()=>r(z1.object({id:z1.string().nullish(),created:z1.number().nullish(),model:z1.string().nullish(),choices:z1.array(z1.object({message:z1.object({role:z1.literal("assistant").nullish(),content:z1.string().nullish(),tool_calls:z1.array(z1.object({id:z1.string().nullish(),type:z1.literal("function"),function:z1.object({name:z1.string(),arguments:z1.string()})})).nullish(),annotations:z1.array(z1.object({type:z1.literal("url_citation"),url_citation:z1.object({start_index:z1.number(),end_index:z1.number(),url:z1.string(),title:z1.string()})})).nullish()}),index:z1.number(),logprobs:z1.object({content:z1.array(z1.object({token:z1.string(),logprob:z1.number(),top_logprobs:z1.array(z1.object({token:z1.string(),logprob:z1.number()}))})).nullish()}).nullish(),finish_reason:z1.string().nullish()})),usage:z1.object({prompt_tokens:z1.number().nullish(),completion_tokens:z1.number().nullish(),total_tokens:z1.number().nullish(),prompt_tokens_details:z1.object({cached_tokens:z1.number().nullish(),cache_write_tokens:z1.number().nullish()}).nullish(),completion_tokens_details:z1.object({reasoning_tokens:z1.number().nullish(),accepted_prediction_tokens:z1.number().nullish(),rejected_prediction_tokens:z1.number().nullish()}).nullish()}).nullish()}))),nD4=W0(()=>r(z1.union([z1.object({id:z1.string().nullish(),created:z1.number().nullish(),model:z1.string().nullish(),choices:z1.array(z1.object({delta:z1.object({role:z1.enum(["assistant"]).nullish(),content:z1.string().nullish(),tool_calls:z1.array(z1.object({index:z1.number(),id:z1.string().nullish(),type:z1.literal("function").nullish(),function:z1.object({name:z1.string().nullish(),arguments:z1.string().nullish()})})).nullish(),annotations:z1.array(z1.object({type:z1.literal("url_citation"),url_citation:z1.object({start_index:z1.number(),end_index:z1.number(),url:z1.string(),title:z1.string()})})).nullish()}).nullish(),logprobs:z1.object({content:z1.array(z1.object({token:z1.string(),logprob:z1.number(),top_logprobs:z1.array(z1.object({token:z1.string(),logprob:z1.number()}))})).nullish()}).nullish(),finish_reason:z1.string().nullish(),index:z1.number()})),usage:z1.object({prompt_tokens:z1.number().nullish(),completion_tokens:z1.number().nullish(),total_tokens:z1.number().nullish(),prompt_tokens_details:z1.object({cached_tokens:z1.number().nullish(),cache_write_tokens:z1.number().nullish()}).nullish(),completion_tokens_details:z1.object({reasoning_tokens:z1.number().nullish(),accepted_prediction_tokens:z1.number().nullish(),rejected_prediction_tokens:z1.number().nullish()}).nullish()}).nullish()}),Y30]))),tD4=W0(()=>r(K5.object({logitBias:K5.record(K5.coerce.number(),K5.number()).optional(),logprobs:K5.union([K5.boolean(),K5.number()]).optional(),parallelToolCalls:K5.boolean().optional(),user:K5.string().optional(),reasoningEffort:K5.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:K5.number().optional(),store:K5.boolean().optional(),metadata:K5.record(K5.string().max(64),K5.string().max(512)).optional(),prediction:K5.record(K5.string(),K5.any()).optional(),serviceTier:K5.enum(["auto","flex","priority","fast","ultrafast","default"]).optional(),strictJsonSchema:K5.boolean().optional(),textVerbosity:K5.enum(["low","medium","high"]).optional(),promptCacheKey:K5.string().optional(),promptCacheOptions:K5.object({mode:K5.enum(["implicit","explicit"]).optional(),ttl:K5.literal("30m").optional()}).optional(),promptCacheRetention:K5.enum(["in_memory","24h"]).optional(),safetyIdentifier:K5.string().optional(),systemMessageMode:K5.enum(["system","developer","remove"]).optional(),forceReasoning:K5.boolean().optional()})));rD4=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Z,this.config=Q}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({prompt:Z,maxOutputTokens:Q,temperature:Y,topP:X,topK:J,frequencyPenalty:G,presencePenalty:W,stopSequences:K,responseFormat:H,seed:F,tools:U,toolChoice:N,reasoning:B,providerOptions:O}){var L,w,j,E,z,T;let P=[],A=(L=await I$({provider:"openai",providerOptions:O,schema:tD4}))!=null?L:{},q=dG$(this.modelId),x=(w=A.reasoningEffort)!=null?w:XB(B)?B:void 0;if(x!=null&&q.supportedReasoningEfforts!=null&&!q.supportedReasoningEfforts.includes(x))P.push({type:"unsupported",feature:"reasoningEffort",details:`${this.modelId} only supports the following reasoning efforts: ${q.supportedReasoningEfforts.join(", ")}`}),x=void 0;let _=(j=A.forceReasoning)!=null?j:q.isReasoningModel;if(J!=null)P.push({type:"unsupported",feature:"topK"});let{messages:V,warnings:y}=iD4({prompt:Z,systemMessageMode:(E=A.systemMessageMode)!=null?E:_?"developer":q.systemMessageMode});P.push(...y);let g=(z=A.strictJsonSchema)!=null?z:!0,l=(H==null?void 0:H.type)==="json"&&H.schema!=null?Fa(H.schema):void 0;if(l!=null)P.push(...l.warnings);let n={model:this.modelId,logit_bias:A.logitBias,logprobs:A.logprobs===!0||typeof A.logprobs==="number"?!0:void 0,top_logprobs:typeof A.logprobs==="number"?A.logprobs:typeof A.logprobs==="boolean"?A.logprobs?0:void 0:void 0,user:A.user,parallel_tool_calls:A.parallelToolCalls,max_tokens:Q,temperature:Y,top_p:X,frequency_penalty:G,presence_penalty:W,response_format:(H==null?void 0:H.type)==="json"?l!=null?{type:"json_schema",json_schema:{schema:l.schema,strict:g,name:(T=H.name)!=null?T:"response",description:H.description}}:{type:"json_object"}:void 0,stop:K,seed:F,verbosity:A.textVerbosity,max_completion_tokens:A.maxCompletionTokens,store:A.store,metadata:A.metadata,prediction:A.prediction,reasoning_effort:x,service_tier:A.serviceTier,prompt_cache_key:A.promptCacheKey,prompt_cache_options:A.promptCacheOptions,prompt_cache_retention:A.promptCacheRetention,safety_identifier:A.safetyIdentifier,messages:V};if(q.supportedReasoningEfforts!=null&&n.prompt_cache_retention!=null)n.prompt_cache_retention=void 0,P.push({type:"unsupported",feature:"promptCacheRetention",details:"promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"});if(_){if(x!=="none"||!q.supportsNonReasoningParameters){if(n.temperature!=null)n.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(n.top_p!=null)n.top_p=void 0,P.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(n.logprobs!=null)n.logprobs=void 0,P.push({type:"other",message:"logprobs is not supported for reasoning models"})}if(n.frequency_penalty!=null)n.frequency_penalty=void 0,P.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"});if(n.presence_penalty!=null)n.presence_penalty=void 0,P.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"});if(n.logit_bias!=null)n.logit_bias=void 0,P.push({type:"other",message:"logitBias is not supported for reasoning models"});if(n.top_logprobs!=null)n.top_logprobs=void 0,P.push({type:"other",message:"topLogprobs is not supported for reasoning models"});if(n.max_tokens!=null){if(n.max_completion_tokens==null)n.max_completion_tokens=n.max_tokens;n.max_tokens=void 0}}else if(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview")){if(n.temperature!=null)n.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})}if(A.serviceTier==="flex"&&!q.supportsFlexProcessing)P.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),n.service_tier=void 0;if((A.serviceTier==="priority"||A.serviceTier==="fast")&&!q.supportsPriorityProcessing)P.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),n.service_tier=void 0;let{tools:p,toolChoice:F0,toolWarnings:V0}=oD4({tools:U,toolChoice:N});return{args:{...n,tools:p,tool_choice:F0},warnings:[...P,...V0]}}async doGenerate(Z){var Q,Y,X,J,G,W,K;let{args:H,warnings:F}=await this.getArgs(Z),{responseHeaders:U,value:N,rawValue:B}=await o1({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:H,failedResponseHandler:R9,successfulResponseHandler:E1(pD4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),O=N.choices[0];if(O==null)throw new W9({data:B,message:"Response did not contain any choices."});let L=[],w=O.message.content;if(w!=null&&w.length>0)L.push({type:"text",text:w});for(let z of(X=O.message.tool_calls)!=null?X:[])L.push({type:"tool-call",toolCallId:z.id||o8(),toolName:z.function.name,input:z.function.arguments});for(let z of(J=O.message.annotations)!=null?J:[])L.push({type:"source",sourceType:"url",id:o8(),url:z.url_citation.url,title:z.url_citation.title});let j=(G=N.usage)==null?void 0:G.completion_tokens_details,E={openai:{}};if((j==null?void 0:j.accepted_prediction_tokens)!=null)E.openai.acceptedPredictionTokens=j==null?void 0:j.accepted_prediction_tokens;if((j==null?void 0:j.rejected_prediction_tokens)!=null)E.openai.rejectedPredictionTokens=j==null?void 0:j.rejected_prediction_tokens;if(((W=O.logprobs)==null?void 0:W.content)!=null)E.openai.logprobs=O.logprobs.content;return{content:L,finishReason:{unified:BG$(O.finish_reason),raw:(K=O.finish_reason)!=null?K:void 0},usage:NG$(N.usage),request:{body:H},response:{...Ia0(N),headers:U,body:B},warnings:F,providerMetadata:E}}async doStream(Z){var Q,Y;let{args:X,warnings:J}=await this.getArgs(Z),G={...X,stream:!0,stream_options:{include_usage:!0}},W=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:K,value:H}=await o1({url:W,headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:G,failedResponseHandler:R9,successfulResponseHandler:UY(nD4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=await Qe0({stream:H,getError:(E)=>("error"in E)?E.error:void 0,isOutputChunk:sD4,url:W,requestBodyValues:G,responseHeaders:K}),U,N={unified:"other",raw:void 0},B=void 0,O=!1,L=!1,w={openai:{}};return{stream:F.pipeThrough(new TransformStream({start(E){U=new t7$(E,{generateId:o8,typeValidation:"if-present"}),E.enqueue({type:"stream-start",warnings:J})},transform(E,z){var T,P,A,q,x,_;if(Z.includeRawChunks)z.enqueue({type:"raw",rawValue:E.rawValue});if(!E.success){N={unified:"error",raw:void 0},z.enqueue({type:"error",error:E.error});return}let V=E.value;if("error"in V){N={unified:"error",raw:void 0},z.enqueue({type:"error",error:(T=Ha(V.error))!=null?T:V.error});return}if(!O){let l=Ia0(V);if(Object.values(l).some(Boolean))O=!0,z.enqueue({type:"response-metadata",...Ia0(V)})}if(V.usage!=null){if(B=V.usage,((P=V.usage.completion_tokens_details)==null?void 0:P.accepted_prediction_tokens)!=null)w.openai.acceptedPredictionTokens=(A=V.usage.completion_tokens_details)==null?void 0:A.accepted_prediction_tokens;if(((q=V.usage.completion_tokens_details)==null?void 0:q.rejected_prediction_tokens)!=null)w.openai.rejectedPredictionTokens=(x=V.usage.completion_tokens_details)==null?void 0:x.rejected_prediction_tokens}let y=V.choices[0];if((y==null?void 0:y.finish_reason)!=null)N={unified:BG$(y.finish_reason),raw:y.finish_reason};if(((_=y==null?void 0:y.logprobs)==null?void 0:_.content)!=null)w.openai.logprobs=y.logprobs.content;if((y==null?void 0:y.delta)==null)return;let g=y.delta;if(g.content!=null){if(!L)z.enqueue({type:"text-start",id:"0"}),L=!0;z.enqueue({type:"text-delta",id:"0",delta:g.content})}if(g.tool_calls!=null)for(let l of g.tool_calls)U.processDelta(l);if(g.annotations!=null)for(let l of g.annotations)z.enqueue({type:"source",sourceType:"url",id:o8(),url:l.url_citation.url,title:l.url_citation.title})},flush(E){if(L)E.enqueue({type:"text-end",id:"0"});U.flush(),E.enqueue({type:"finish",finishReason:N,usage:NG$(B),...w!=null?{providerMetadata:w}:{}})}})),request:{body:G},response:{headers:K}}}};eD4=W0(()=>r(u8.object({id:u8.string().nullish(),created:u8.number().nullish(),model:u8.string().nullish(),choices:u8.array(u8.object({text:u8.string(),finish_reason:u8.string(),logprobs:u8.object({tokens:u8.array(u8.string()),token_logprobs:u8.array(u8.number()),top_logprobs:u8.array(u8.record(u8.string(),u8.number())).nullish()}).nullish()})),usage:u8.object({prompt_tokens:u8.number(),completion_tokens:u8.number(),total_tokens:u8.number()}).nullish()}))),$L4=W0(()=>r(u8.union([u8.object({id:u8.string().nullish(),created:u8.number().nullish(),model:u8.string().nullish(),choices:u8.array(u8.object({text:u8.string(),finish_reason:u8.string().nullish(),index:u8.number(),logprobs:u8.object({tokens:u8.array(u8.string()),token_logprobs:u8.array(u8.number()),top_logprobs:u8.array(u8.record(u8.string(),u8.number())).nullish()}).nullish()})),usage:u8.object({prompt_tokens:u8.number(),completion_tokens:u8.number(),total_tokens:u8.number()}).nullish()}),Y30]))),LG$=W0(()=>r(fF.object({echo:fF.boolean().optional(),logitBias:fF.record(fF.string(),fF.number()).optional(),suffix:fF.string().optional(),user:fF.string().optional(),logprobs:fF.union([fF.boolean(),fF.number()]).optional()}))),ZL4=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls={},this.modelId=Z,this.config=Q}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({prompt:Z,maxOutputTokens:Q,temperature:Y,topP:X,topK:J,frequencyPenalty:G,presencePenalty:W,stopSequences:K,responseFormat:H,tools:F,toolChoice:U,seed:N,providerOptions:B}){let O=[],L={...await I$({provider:"openai",providerOptions:B,schema:LG$}),...await I$({provider:this.providerOptionsName,providerOptions:B,schema:LG$})};if(J!=null)O.push({type:"unsupported",feature:"topK"});if(F==null?void 0:F.length)O.push({type:"unsupported",feature:"tools"});if(U!=null)O.push({type:"unsupported",feature:"toolChoice"});if(H!=null&&H.type!=="text")O.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});let{prompt:w,stopSequences:j}=aD4({prompt:Z}),E=[...j!=null?j:[],...K!=null?K:[]];return{args:{model:this.modelId,echo:L.echo,logit_bias:L.logitBias,logprobs:(L==null?void 0:L.logprobs)===!0?0:(L==null?void 0:L.logprobs)===!1?void 0:L==null?void 0:L.logprobs,suffix:L.suffix,user:L.user,max_tokens:Q,temperature:Y,top_p:X,frequency_penalty:G,presence_penalty:W,seed:N,prompt:w,stop:E.length>0?E:void 0},warnings:O}}async doGenerate(Z){var Q,Y,X;let{args:J,warnings:G}=await this.getArgs(Z),{responseHeaders:W,value:K,rawValue:H}=await o1({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:J,failedResponseHandler:R9,successfulResponseHandler:E1(eD4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=K.choices[0],U={openai:{}};if(F.logprobs!=null)U.openai.logprobs=F.logprobs;return{content:[{type:"text",text:F.text}],usage:OG$(K.usage),finishReason:{unified:DG$(F.finish_reason),raw:(X=F.finish_reason)!=null?X:void 0},request:{body:J},response:{...xr(K),headers:W,body:H},providerMetadata:U,warnings:G}}async doStream(Z){var Q,Y;let{args:X,warnings:J}=await this.getArgs(Z),G={...X,stream:!0,stream_options:{include_usage:!0}},W=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:K,value:H}=await o1({url:W,headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:G,failedResponseHandler:R9,successfulResponseHandler:UY($L4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=await Qe0({stream:H,getError:(w)=>("error"in w)?w.error:void 0,isOutputChunk:QL4,url:W,requestBodyValues:G,responseHeaders:K}),U={unified:"other",raw:void 0},N={openai:{}},B=void 0,O=!0;return{stream:F.pipeThrough(new TransformStream({start(w){w.enqueue({type:"stream-start",warnings:J})},transform(w,j){var E;if(Z.includeRawChunks)j.enqueue({type:"raw",rawValue:w.rawValue});if(!w.success){U={unified:"error",raw:void 0},j.enqueue({type:"error",error:w.error});return}let z=w.value;if("error"in z){U={unified:"error",raw:void 0},j.enqueue({type:"error",error:(E=Ha(z.error))!=null?E:z.error});return}if(O)O=!1,j.enqueue({type:"response-metadata",...xr(z)}),j.enqueue({type:"text-start",id:"0"});if(z.usage!=null)B=z.usage;let T=z.choices[0];if((T==null?void 0:T.finish_reason)!=null)U={unified:DG$(T.finish_reason),raw:T.finish_reason};if((T==null?void 0:T.logprobs)!=null)N.openai.logprobs=T.logprobs;if((T==null?void 0:T.text)!=null&&T.text.length>0)j.enqueue({type:"text-delta",id:"0",delta:T.text})},flush(w){if(!O)w.enqueue({type:"text-end",id:"0"});w.enqueue({type:"finish",finishReason:U,providerMetadata:N,usage:OG$(B)})}})),request:{body:G},response:{headers:K}}}};YL4=W0(()=>r(Va0.object({dimensions:Va0.number().optional(),user:Va0.string().optional()}))),XL4=W0(()=>r(OA.object({data:OA.array(OA.object({embedding:OA.array(OA.number())})),usage:OA.object({prompt_tokens:OA.number()}).nullish()}))),JL4=class ${constructor(Z,Q){this.specificationVersion="v4",this.maxEmbeddingsPerCall=2048,this[wG$]=300000,this.supportsParallelCalls=!0,this.modelId=Z,this.config=Q}static[(wG$=C7$,Q4)](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async doEmbed({values:Z,headers:Q,abortSignal:Y,providerOptions:X}){var J,G,W;if(Z.length>this.maxEmbeddingsPerCall)throw new MJ0({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Z});let K=(J=await I$({provider:"openai",providerOptions:X,schema:YL4}))!=null?J:{},{responseHeaders:H,value:F,rawValue:U}=await o1({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:T1((W=(G=this.config).headers)==null?void 0:W.call(G),Q),body:{model:this.modelId,input:Z,encoding_format:"float",dimensions:K.dimensions,user:K.user},failedResponseHandler:R9,successfulResponseHandler:E1(XL4),abortSignal:Y,fetch:this.config.fetch});return{warnings:[],embeddings:F.data.map((N)=>N.embedding),usage:F.usage?{tokens:F.usage.prompt_tokens}:void 0,response:{headers:H,body:U}}}},$30=W0(()=>r(_G.object({id:_G.string(),object:_G.string().nullish(),bytes:_G.number().nullish(),created_at:_G.number().nullish(),filename:_G.string().nullish(),purpose:_G.string().nullish(),status:_G.string().nullish(),expires_at:_G.number().nullish()}))),GL4=W0(()=>r(_G.object({id:_G.string(),object:_G.string().nullish(),deleted:_G.boolean()}))),WL4=W0(()=>r(ka0.object({purpose:ka0.string().optional(),expiresAfter:ka0.number().optional()})));jG$=W0(()=>r(MQ.object({created:MQ.number().nullish(),data:MQ.array(MQ.object({b64_json:MQ.string(),revised_prompt:MQ.string().nullish()})),background:MQ.string().nullish(),output_format:MQ.string().nullish(),size:MQ.string().nullish(),quality:MQ.string().nullish(),usage:MQ.object({input_tokens:MQ.number().nullish(),output_tokens:MQ.number().nullish(),total_tokens:MQ.number().nullish(),input_tokens_details:MQ.object({image_tokens:MQ.number().nullish(),text_tokens:MQ.number().nullish()}).nullish()}).nullish()}))),HL4={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"gpt-image-2.5-flare":10,"gpt-image-2.5-flare-2026-09-08":10,"gpt-image-2.5-sunburst":10,"gpt-image-2.5-sunburst-2026-09-08":10,"chatgpt-image-latest":10},FL4=["chatgpt-image-","gpt-image-"];Ye0=LB.object({quality:LB.enum(["standard","hd","low","medium","high","xhigh","max","auto"]).optional(),background:LB.enum(["transparent","opaque","auto"]).optional(),outputFormat:LB.enum(["png","jpeg","webp"]).optional(),outputCompression:LB.number().int().min(0).max(100).optional(),user:LB.string().optional()}),ph5=W0(()=>r(Ye0)),BL4=W0(()=>r(Ye0.extend({style:LB.enum(["vivid","natural"]).optional(),moderation:LB.enum(["auto","low"]).optional()}))),OL4=W0(()=>r(Ye0.extend({inputFidelity:LB.enum(["high","low"]).optional()}))),DL4=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get maxImagesPerCall(){return NL4(this.modelId)}get provider(){return this.config.provider}async doGenerate({prompt:Z,files:Q,mask:Y,n:X,size:J,aspectRatio:G,seed:W,providerOptions:K,headers:H,abortSignal:F}){var U,N,B,O,L,w,j,E,z,T,P,A,q,x,_;let V=[];if(G!=null)V.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."});if(W!=null)V.push({type:"unsupported",feature:"seed"});let y=(B=(N=(U=this.config._internal)==null?void 0:U.currentDate)==null?void 0:N.call(U))!=null?B:new Date;if(Q!=null){let p=(O=await I$({provider:"openai",providerOptions:K,schema:OL4}))!=null?O:{},{value:F0,responseHeaders:V0}=await p3({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:T1((w=(L=this.config).headers)==null?void 0:w.call(L),H),formData:z7$({model:this.modelId,prompt:Z,image:await Promise.all(Q.map((G0)=>G0.type==="file"?new Blob([G0.data instanceof Uint8Array?new Blob([G0.data],{type:G0.mediaType}):new Blob([_9(G0.data)],{type:G0.mediaType})],{type:G0.mediaType}):hr(G0.url,{abortSignal:F}))),mask:Y!=null?await LL4(Y,F):void 0,n:X,size:J,quality:p.quality,background:p.background,output_format:p.outputFormat,output_compression:p.outputCompression,input_fidelity:p.inputFidelity,user:p.user}),failedResponseHandler:R9,successfulResponseHandler:E1(jG$),abortSignal:F,fetch:this.config.fetch});return{images:F0.data.map((G0)=>G0.b64_json),warnings:V,usage:F0.usage!=null?{inputTokens:(j=F0.usage.input_tokens)!=null?j:void 0,outputTokens:(E=F0.usage.output_tokens)!=null?E:void 0,totalTokens:(z=F0.usage.total_tokens)!=null?z:void 0}:void 0,response:{timestamp:y,modelId:this.modelId,headers:V0},providerMetadata:{openai:{images:F0.data.map((G0,H0)=>{var X0,Z0,Y0,o,J0,c0;return{...G0.revised_prompt?{revisedPrompt:G0.revised_prompt}:{},created:(X0=F0.created)!=null?X0:void 0,size:(Z0=F0.size)!=null?Z0:void 0,quality:(Y0=F0.quality)!=null?Y0:void 0,background:(o=F0.background)!=null?o:void 0,outputFormat:(J0=F0.output_format)!=null?J0:void 0,...EG$((c0=F0.usage)==null?void 0:c0.input_tokens_details,H0,F0.data.length)}})}}}}let g=(T=await I$({provider:"openai",providerOptions:K,schema:BL4}))!=null?T:{},{value:l,responseHeaders:n}=await o1({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:T1((A=(P=this.config).headers)==null?void 0:A.call(P),H),body:{model:this.modelId,prompt:Z,n:X,size:J,quality:g.quality,style:g.style,background:g.background,moderation:g.moderation,output_format:g.outputFormat,output_compression:g.outputCompression,user:g.user,...!UL4(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:R9,successfulResponseHandler:E1(jG$),abortSignal:F,fetch:this.config.fetch});return{images:l.data.map((p)=>p.b64_json),warnings:V,usage:l.usage!=null?{inputTokens:(q=l.usage.input_tokens)!=null?q:void 0,outputTokens:(x=l.usage.output_tokens)!=null?x:void 0,totalTokens:(_=l.usage.total_tokens)!=null?_:void 0}:void 0,response:{timestamp:y,modelId:this.modelId,headers:n},providerMetadata:{openai:{images:l.data.map((p,F0)=>{var V0,G0,H0,X0,Z0,Y0;return{...p.revised_prompt?{revisedPrompt:p.revised_prompt}:{},created:(V0=l.created)!=null?V0:void 0,size:(G0=l.size)!=null?G0:void 0,quality:(H0=l.quality)!=null?H0:void 0,background:(X0=l.background)!=null?X0:void 0,outputFormat:(Z0=l.output_format)!=null?Z0:void 0,...EG$((Y0=l.usage)==null?void 0:Y0.input_tokens_details,F0,l.data.length)}})}}}}};iG$=W0(()=>r(m7.object({callId:m7.string(),operation:m7.discriminatedUnion("type",[m7.object({type:m7.literal("create_file"),path:m7.string(),diff:m7.string()}),m7.object({type:m7.literal("delete_file"),path:m7.string()}),m7.object({type:m7.literal("update_file"),path:m7.string(),diff:m7.string()})])}))),pG$=W0(()=>r(m7.object({status:m7.enum(["completed","failed"]),output:m7.string().optional()}))),oh5=W0(()=>r(m7.object({}))),wL4=TF({id:"openai.apply_patch",inputSchema:iG$,outputSchema:pG$}),jL4=wL4,EL4=W0(()=>r(d7.object({code:d7.string().nullish(),containerId:d7.string()}))),zL4=W0(()=>r(d7.object({outputs:d7.array(d7.discriminatedUnion("type",[d7.object({type:d7.literal("logs"),logs:d7.string()}),d7.object({type:d7.literal("image"),url:d7.string()})])).nullish()}))),PL4=W0(()=>r(d7.object({container:d7.union([d7.string(),d7.object({fileIds:d7.array(d7.string()).optional()})]).optional()}))),AL4=g$({id:"openai.code_interpreter",inputSchema:EL4,outputSchema:zL4}),nG$=J$.object({id:J$.string(),code:J$.string().optional(),message:J$.string().optional()}),RL4=J$.discriminatedUnion("type",[J$.object({type:J$.literal("click"),button:J$.enum(["left","right","wheel","back","forward"]),x:J$.number(),y:J$.number(),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("double_click"),x:J$.number(),y:J$.number(),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("drag"),path:J$.array(J$.object({x:J$.number(),y:J$.number()})),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("keypress"),keys:J$.array(J$.string())}),J$.object({type:J$.literal("move"),x:J$.number(),y:J$.number(),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("screenshot")}),J$.object({type:J$.literal("scroll"),x:J$.number(),y:J$.number(),scrollX:J$.number(),scrollY:J$.number(),keys:J$.array(J$.string()).optional()}),J$.object({type:J$.literal("type"),text:J$.string()}),J$.object({type:J$.literal("wait")})]),tG$=W0(()=>r(J$.object({actions:J$.array(RL4),pendingSafetyChecks:J$.array(nG$),status:J$.enum(["in_progress","completed","incomplete"])}))),oG$=W0(()=>r(J$.object({output:J$.union([J$.object({type:J$.literal("computer_screenshot"),imageUrl:J$.string(),fileId:J$.string().optional(),detail:J$.enum(["auto","low","high","original"]).optional()}),J$.object({type:J$.literal("computer_screenshot"),fileId:J$.string(),imageUrl:J$.string().optional(),detail:J$.enum(["auto","low","high","original"]).optional()})]),acknowledgedSafetyChecks:J$.array(nG$).optional()}))),qL4=TF({id:"openai.computer",inputSchema:tG$,outputSchema:oG$}),IL4=W0(()=>r(gK.object({description:gK.string().optional(),async:gK.boolean().optional(),format:gK.union([gK.object({type:gK.literal("grammar"),syntax:gK.enum(["regex","lark"]),definition:gK.string()}),gK.object({type:gK.literal("text")})]).optional()}))),VL4=W0(()=>r(gK.string())),kL4=$Z({id:"openai.custom",inputSchema:VL4}),rG$=X6.object({key:X6.string(),type:X6.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:X6.union([X6.string(),X6.number(),X6.boolean(),X6.array(X6.string())])}),sG$=X6.object({type:X6.enum(["and","or"]),filters:X6.array(X6.union([rG$,X6.lazy(()=>sG$)]))}),CL4=W0(()=>r(X6.object({vectorStoreIds:X6.array(X6.string()),maxNumResults:X6.number().optional(),ranking:X6.object({ranker:X6.string().optional(),scoreThreshold:X6.number().optional()}).optional(),filters:X6.union([rG$,sG$]).optional()}))),_L4=W0(()=>r(X6.object({queries:X6.array(X6.string()),results:X6.array(X6.object({attributes:X6.record(X6.string(),X6.unknown()),fileId:X6.string(),filename:X6.string(),score:X6.number(),text:X6.string()})).nullable()}))),vL4=g$({id:"openai.file_search",inputSchema:X6.object({}),outputSchema:_L4}),bL4=W0(()=>r(w7.object({action:w7.enum(["generate","edit","auto"]).optional(),background:w7.enum(["auto","opaque","transparent"]).optional(),inputFidelity:w7.enum(["low","high"]).optional(),inputImageMask:w7.object({fileId:w7.string().optional(),imageUrl:w7.string().optional()}).optional(),model:w7.string().optional(),moderation:w7.enum(["auto","low"]).optional(),outputCompression:w7.number().int().min(0).max(100).optional(),outputFormat:w7.enum(["png","jpeg","webp"]).optional(),partialImages:w7.number().int().min(0).max(3).optional(),quality:w7.enum(["auto","low","medium","high","xhigh","max"]).optional(),size:w7.union([w7.enum(["1024x1024","1024x1536","1536x1024","auto"]),w7.string().regex(/^\d+x\d+$/)]).optional()}).strict())),xL4=W0(()=>r(w7.object({}))),fL4=W0(()=>r(w7.object({result:w7.string()}))),yL4=g$({id:"openai.image_generation",inputSchema:xL4,outputSchema:fL4}),aG$=W0(()=>r(CG.object({action:CG.object({type:CG.literal("exec"),command:CG.array(CG.string()),timeoutMs:CG.number().optional(),user:CG.string().optional(),workingDirectory:CG.string().optional(),env:CG.record(CG.string(),CG.string()).optional()})}))),eG$=W0(()=>r(CG.object({output:CG.string()}))),hL4=TF({id:"openai.local_shell",inputSchema:aG$,outputSchema:eG$}),$3$=W0(()=>r(k$.object({action:k$.object({commands:k$.array(k$.string()),timeoutMs:k$.number().optional(),maxOutputLength:k$.number().optional()})}))),ya0=W0(()=>r(k$.object({output:k$.array(k$.object({stdout:k$.string(),stderr:k$.string(),outcome:k$.discriminatedUnion("type",[k$.object({type:k$.literal("timeout")}),k$.object({type:k$.literal("exit"),exitCode:k$.number()})])}))}))),uL4=k$.array(k$.discriminatedUnion("type",[k$.object({type:k$.literal("skillReference"),providerReference:k$.record(k$.string(),k$.string()),version:k$.string().optional()}),k$.object({type:k$.literal("inline"),name:k$.string(),description:k$.string(),source:k$.object({type:k$.literal("base64"),mediaType:k$.literal("application/zip"),data:k$.string()})})])).optional(),lL4=W0(()=>r(k$.object({environment:k$.union([k$.object({type:k$.literal("containerAuto"),fileIds:k$.array(k$.string()).optional(),memoryLimit:k$.enum(["1g","4g","16g","64g"]).optional(),networkPolicy:k$.discriminatedUnion("type",[k$.object({type:k$.literal("disabled")}),k$.object({type:k$.literal("allowlist"),allowedDomains:k$.array(k$.string()),domainSecrets:k$.array(k$.object({domain:k$.string(),name:k$.string(),value:k$.string()})).optional()})]).optional(),skills:uL4}),k$.object({type:k$.literal("containerReference"),containerId:k$.string()}),k$.object({type:k$.literal("local").optional(),skills:k$.array(k$.object({name:k$.string(),description:k$.string(),path:k$.string()})).optional()})]).optional()}))),cL4=TF({id:"openai.shell",inputSchema:$3$,outputSchema:ya0}),mL4=W0(()=>r(NJ.object({execution:NJ.enum(["server","client"]).optional(),description:NJ.string().optional(),parameters:NJ.record(NJ.string(),NJ.unknown()).optional()}))),ga0=W0(()=>r(NJ.object({arguments:NJ.unknown().optional(),call_id:NJ.string().nullish()}))),ha0=W0(()=>r(NJ.object({tools:NJ.array(NJ.record(NJ.string(),NJ.unknown()))}))),dL4=TF({id:"openai.tool_search",inputSchema:ga0,outputSchema:ha0}),pL4=W0(()=>r(l4.object({externalWebAccess:l4.boolean().optional(),filters:l4.object({allowedDomains:l4.array(l4.string()).optional(),blockedDomains:l4.array(l4.string()).optional()}).optional(),searchContextSize:l4.enum(["low","medium","high"]).optional(),userLocation:l4.object({type:l4.literal("approximate"),country:l4.string().optional(),city:l4.string().optional(),region:l4.string().optional(),timezone:l4.string().optional()}).optional()}))),nL4=W0(()=>r(l4.object({}))),tL4=W0(()=>r(l4.object({action:l4.discriminatedUnion("type",[l4.object({type:l4.literal("search"),query:l4.string().optional(),queries:l4.array(l4.string()).optional()}),l4.object({type:l4.literal("openPage"),url:l4.string().nullish()}),l4.object({type:l4.literal("findInPage"),url:l4.string().nullish(),pattern:l4.string().nullish()})]).optional(),sources:l4.array(l4.discriminatedUnion("type",[l4.object({type:l4.literal("url"),url:l4.string()}),l4.object({type:l4.literal("api"),name:l4.string()})])).optional()}))),oL4=g$({id:"openai.web_search",inputSchema:nL4,outputSchema:tL4}),sL4=W0(()=>r(MZ.object({searchContextSize:MZ.enum(["low","medium","high"]).optional(),userLocation:MZ.object({type:MZ.literal("approximate"),country:MZ.string().optional(),city:MZ.string().optional(),region:MZ.string().optional(),timezone:MZ.string().optional()}).optional()}))),aL4=W0(()=>r(MZ.object({}))),eL4=W0(()=>r(MZ.object({action:MZ.discriminatedUnion("type",[MZ.object({type:MZ.literal("search"),query:MZ.string().optional()}),MZ.object({type:MZ.literal("openPage"),url:MZ.string().nullish()}),MZ.object({type:MZ.literal("findInPage"),url:MZ.string().nullish(),pattern:MZ.string().nullish()})]).optional()}))),$w4=g$({id:"openai.web_search_preview",inputSchema:aL4,outputSchema:eL4}),ua0=D4.lazy(()=>D4.union([D4.string(),D4.number(),D4.boolean(),D4.null(),D4.array(ua0),D4.record(D4.string(),ua0)])),Zw4=W0(()=>r(D4.object({serverLabel:D4.string(),allowedTools:D4.union([D4.array(D4.string()),D4.object({readOnly:D4.boolean().optional(),toolNames:D4.array(D4.string()).optional()})]).optional(),authorization:D4.string().optional(),connectorId:D4.string().optional(),headers:D4.record(D4.string(),D4.string()).optional(),requireApproval:D4.union([D4.enum(["always","never"]),D4.object({never:D4.object({toolNames:D4.array(D4.string()).optional()}).optional()})]).optional(),serverDescription:D4.string().optional(),serverUrl:D4.string().optional()}).refine(($)=>$.serverUrl!=null||$.connectorId!=null,"One of serverUrl or connectorId must be provided."))),Qw4=W0(()=>r(D4.object({}))),Yw4=W0(()=>r(D4.object({type:D4.literal("call"),serverLabel:D4.string(),name:D4.string(),arguments:D4.string(),output:D4.string().nullish(),error:D4.union([D4.string(),ua0]).optional()}))),Xw4=g$({id:"openai.mcp",inputSchema:Qw4,outputSchema:Yw4}),Z3$=W0(()=>r(ml.object({code:ml.string(),fingerprint:ml.string()}))),Q3$=W0(()=>r(ml.object({result:ml.string(),status:ml.enum(["completed","incomplete"])}))),Gw4=g$({id:"openai.programmatic_tool_calling",inputSchema:Z3$,outputSchema:Q3$,supportsDeferredResults:!0}),Kw4={applyPatch:jL4,customTool:SL4,codeInterpreter:TL4,computer:ML4,fileSearch:vL4,imageGeneration:gL4,localShell:hL4,shell:cL4,webSearchPreview:$w4,webSearch:rL4,mcp:Jw4,programmaticToolCalling:Ww4,toolSearch:iL4};dl=R.lazy(()=>R.union([R.string(),R.number(),R.boolean(),R.null(),R.array(dl),R.record(R.string(),dl.optional())])),Ca0=R.record(R.string(),dl.optional()),ca0=R.intersection(Ca0,R.object({input_tokens:R.number(),input_tokens_details:R.intersection(Ca0,R.object({cached_tokens:R.number().nullish(),cache_write_tokens:R.number().nullish(),orchestration_input_tokens:R.number().nullish(),orchestration_input_cached_tokens:R.number().nullish()})).nullish(),output_tokens:R.number(),output_tokens_details:R.intersection(Ca0,R.object({reasoning_tokens:R.number().nullish(),orchestration_output_tokens:R.number().nullish()})).nullish(),total_tokens:R.number().optional()})),Hw4=R.object({id:R.string(),code:R.string().nullish(),message:R.string().nullish()}),zG$=R.discriminatedUnion("type",[R.object({type:R.literal("click"),button:R.enum(["left","right","wheel","back","forward"]),x:R.number(),y:R.number(),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("double_click"),x:R.number(),y:R.number(),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("drag"),path:R.array(R.object({x:R.number(),y:R.number()})),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("keypress"),keys:R.array(R.string())}),R.object({type:R.literal("move"),x:R.number(),y:R.number(),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("screenshot")}),R.object({type:R.literal("scroll"),x:R.number(),y:R.number(),scroll_x:R.number(),scroll_y:R.number(),keys:R.array(R.string()).nullish()}),R.object({type:R.literal("type"),text:R.string()}),R.object({type:R.literal("wait")})]),ma0=R.object({type:R.literal("computer_call"),id:R.string(),call_id:R.string().nullish(),status:R.enum(["in_progress","completed","incomplete"]),action:zG$.nullish(),actions:R.array(zG$).nullish(),pending_safety_checks:R.array(Hw4).nullish()}),da0=R.discriminatedUnion("type",[R.object({type:R.literal("direct")}),R.object({type:R.literal("program"),caller_id:R.string()})]),ia0=R.object({type:R.literal("program"),id:R.string(),call_id:R.string(),code:R.string(),fingerprint:R.string()}),pa0=R.object({type:R.literal("program_output"),id:R.string(),call_id:R.string(),result:R.string(),status:R.enum(["completed","incomplete"])}),na0=R.object({type:R.literal("local_shell_call"),id:R.string(),call_id:R.string(),action:R.object({type:R.literal("exec"),command:R.array(R.string()),timeout_ms:R.number().optional(),user:R.string().optional(),working_directory:R.string().optional(),env:R.record(R.string(),R.string()).optional()})}),Fw4=R.object({type:R.literal("error"),sequence_number:R.number(),error:R.object({type:R.string(),code:R.string(),message:R.string(),param:R.string().nullish()})}),Uw4=R.object({type:R.literal("error"),sequence_number:R.number(),code:R.string().nullish(),message:R.string(),param:R.string().nullish()}),Nw4=new Set(["error","response.apply_patch_call_operation_diff.delta","response.apply_patch_call_operation_diff.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.completed","response.created","response.custom_tool_call_input.delta","response.failed","response.function_call_arguments.delta","response.function_call_arguments.done","response.image_generation_call.partial_image","response.in_progress","response.incomplete","response.output_item.added","response.output_item.done","response.output_text.annotation.added","response.output_text.delta","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta"]),Bw4=new Set(["apply_patch_call","code_interpreter_call","compaction","computer_call","custom_tool_call","file_search_call","function_call","image_generation_call","local_shell_call","mcp_approval_request","mcp_call","mcp_list_tools","message","program","program_output","reasoning","shell_call","shell_call_output","tool_search_call","tool_search_output","web_search_call"]);Dw4=W0(()=>r(R.union([R.object({type:R.literal("response.output_text.delta"),item_id:R.string(),output_index:R.number().nullish(),delta:R.string(),logprobs:R.array(R.object({token:R.string(),logprob:R.number(),top_logprobs:R.array(R.object({token:R.string(),logprob:R.number()}))})).nullish()}),R.object({type:R.enum(["response.completed","response.incomplete"]),response:R.object({incomplete_details:R.object({reason:R.string()}).nullish(),usage:ca0.nullish(),reasoning:R.object({context:R.string().nullish()}).nullish(),service_tier:R.string().nullish()})}),R.object({type:R.literal("response.failed"),sequence_number:R.number(),response:R.object({error:R.object({code:R.string().nullish(),message:R.string()}).nullish(),incomplete_details:R.object({reason:R.string()}).nullish(),usage:ca0.nullish(),reasoning:R.object({context:R.string().nullish()}).nullish(),service_tier:R.string().nullish()})}),R.object({type:R.literal("response.created"),response:R.object({id:R.string(),created_at:R.number(),model:R.string(),service_tier:R.string().nullish()})}),R.object({type:R.literal("response.in_progress"),response:R.object({id:R.string(),created_at:R.number(),model:R.string(),service_tier:R.string().nullish()})}),R.object({type:R.literal("response.output_item.added"),output_index:R.number(),item:R.discriminatedUnion("type",[R.object({type:R.literal("message"),id:R.string(),phase:R.enum(["commentary","final_answer"]).nullish()}),R.object({type:R.literal("reasoning"),id:R.string(),encrypted_content:R.string().nullish()}),R.object({type:R.literal("function_call"),id:R.string(),call_id:R.string(),name:R.string(),arguments:R.string(),async:R.boolean().nullish(),namespace:R.string().nullish(),caller:da0.nullish()}),ia0,pa0,R.object({type:R.literal("web_search_call"),id:R.string(),status:R.string()}),ma0,R.object({type:R.literal("file_search_call"),id:R.string()}),na0,R.object({type:R.literal("image_generation_call"),id:R.string()}),R.object({type:R.literal("code_interpreter_call"),id:R.string(),container_id:R.string(),code:R.string().nullable(),outputs:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("logs"),logs:R.string()}),R.object({type:R.literal("image"),url:R.string()})])).nullable(),status:R.string()}),R.object({type:R.literal("mcp_call"),id:R.string(),status:R.string(),approval_request_id:R.string().nullish()}),R.object({type:R.literal("mcp_list_tools"),id:R.string()}),R.object({type:R.literal("mcp_approval_request"),id:R.string()}),R.object({type:R.literal("apply_patch_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed"]),operation:R.discriminatedUnion("type",[R.object({type:R.literal("create_file"),path:R.string(),diff:R.string()}),R.object({type:R.literal("delete_file"),path:R.string()}),R.object({type:R.literal("update_file"),path:R.string(),diff:R.string()})])}),R.object({type:R.literal("custom_tool_call"),id:R.string(),call_id:R.string(),name:R.string(),input:R.string(),async:R.boolean().nullish()}),R.object({type:R.literal("shell_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),action:R.object({commands:R.array(R.string())})}),R.object({type:R.literal("compaction"),id:R.string(),encrypted_content:R.string().nullish()}),R.object({type:R.literal("shell_call_output"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),output:R.array(R.object({stdout:R.string(),stderr:R.string(),outcome:R.discriminatedUnion("type",[R.object({type:R.literal("timeout")}),R.object({type:R.literal("exit"),exit_code:R.number()})])}))}),R.object({type:R.literal("tool_search_call"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),arguments:R.unknown()}),R.object({type:R.literal("tool_search_output"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),tools:R.array(R.record(R.string(),dl.optional()))})])}),R.object({type:R.literal("response.output_item.done"),output_index:R.number(),item:R.discriminatedUnion("type",[R.object({type:R.literal("message"),id:R.string(),phase:R.enum(["commentary","final_answer"]).nullish()}),R.object({type:R.literal("reasoning"),id:R.string(),encrypted_content:R.string().nullish()}),R.object({type:R.literal("function_call"),id:R.string(),call_id:R.string(),name:R.string(),arguments:R.string(),async:R.boolean().nullish(),status:R.enum(["in_progress","completed","incomplete"]),namespace:R.string().nullish(),caller:da0.nullish()}),ia0,pa0,R.object({type:R.literal("custom_tool_call"),id:R.string(),call_id:R.string(),name:R.string(),input:R.string(),async:R.boolean().nullish(),status:R.literal("completed")}),R.object({type:R.literal("code_interpreter_call"),id:R.string(),code:R.string().nullable(),container_id:R.string(),outputs:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("logs"),logs:R.string()}),R.object({type:R.literal("image"),url:R.string()})])).nullable()}),R.object({type:R.literal("image_generation_call"),id:R.string(),result:R.string()}),R.object({type:R.literal("web_search_call"),id:R.string(),status:R.string(),action:R.discriminatedUnion("type",[R.object({type:R.literal("search"),query:R.string().nullish(),queries:R.array(R.string()).nullish(),sources:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("url"),url:R.string()}),R.object({type:R.literal("api"),name:R.string()})])).nullish()}),R.object({type:R.literal("open_page"),url:R.string().nullish()}),R.object({type:R.literal("find_in_page"),url:R.string().nullish(),pattern:R.string().nullish()})]).nullish()}),R.object({type:R.literal("file_search_call"),id:R.string(),queries:R.array(R.string()),results:R.array(R.object({attributes:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])),file_id:R.string(),filename:R.string(),score:R.number(),text:R.string()})).nullish()}),na0,ma0,R.object({type:R.literal("mcp_call"),id:R.string(),status:R.string(),arguments:R.string(),name:R.string(),server_label:R.string(),output:R.string().nullish(),error:R.union([R.string(),R.object({type:R.string().optional(),code:R.union([R.number(),R.string()]).optional(),message:R.string().optional()}).loose()]).nullish(),approval_request_id:R.string().nullish()}),R.object({type:R.literal("mcp_list_tools"),id:R.string(),server_label:R.string(),tools:R.array(R.object({name:R.string(),description:R.string().optional(),input_schema:R.any(),annotations:R.record(R.string(),R.unknown()).optional()})),error:R.union([R.string(),R.object({type:R.string().optional(),code:R.union([R.number(),R.string()]).optional(),message:R.string().optional()}).loose()]).optional()}),R.object({type:R.literal("mcp_approval_request"),id:R.string(),server_label:R.string(),name:R.string(),arguments:R.string(),approval_request_id:R.string().optional()}),R.object({type:R.literal("apply_patch_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed"]),operation:R.discriminatedUnion("type",[R.object({type:R.literal("create_file"),path:R.string(),diff:R.string()}),R.object({type:R.literal("delete_file"),path:R.string()}),R.object({type:R.literal("update_file"),path:R.string(),diff:R.string()})])}),R.object({type:R.literal("shell_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),action:R.object({commands:R.array(R.string())})}),R.object({type:R.literal("compaction"),id:R.string(),encrypted_content:R.string()}),R.object({type:R.literal("shell_call_output"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),output:R.array(R.object({stdout:R.string(),stderr:R.string(),outcome:R.discriminatedUnion("type",[R.object({type:R.literal("timeout")}),R.object({type:R.literal("exit"),exit_code:R.number()})])}))}),R.object({type:R.literal("tool_search_call"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),arguments:R.unknown()}),R.object({type:R.literal("tool_search_output"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),tools:R.array(R.record(R.string(),dl.optional()))})])}),R.object({type:R.literal("response.function_call_arguments.delta"),item_id:R.string(),output_index:R.number(),delta:R.string()}),R.object({type:R.literal("response.function_call_arguments.done"),item_id:R.string(),output_index:R.number(),arguments:R.string()}),R.object({type:R.literal("response.custom_tool_call_input.delta"),item_id:R.string(),output_index:R.number(),delta:R.string()}),R.object({type:R.literal("response.image_generation_call.partial_image"),item_id:R.string(),output_index:R.number(),partial_image_b64:R.string()}),R.object({type:R.literal("response.code_interpreter_call_code.delta"),item_id:R.string(),output_index:R.number(),delta:R.string()}),R.object({type:R.literal("response.code_interpreter_call_code.done"),item_id:R.string(),output_index:R.number(),code:R.string()}),R.object({type:R.literal("response.output_text.annotation.added"),annotation:R.discriminatedUnion("type",[R.object({type:R.literal("url_citation"),start_index:R.number(),end_index:R.number(),url:R.string(),title:R.string()}),R.object({type:R.literal("file_citation"),file_id:R.string(),filename:R.string(),index:R.number()}),R.object({type:R.literal("container_file_citation"),container_id:R.string(),file_id:R.string(),filename:R.string(),start_index:R.number(),end_index:R.number()}),R.object({type:R.literal("file_path"),file_id:R.string(),index:R.number()})])}),R.object({type:R.literal("response.reasoning_summary_part.added"),item_id:R.string(),output_index:R.number().nullish(),summary_index:R.number()}),R.object({type:R.literal("response.reasoning_summary_text.delta"),item_id:R.string(),output_index:R.number().nullish(),summary_index:R.number(),delta:R.string()}),R.object({type:R.literal("response.reasoning_summary_part.done"),item_id:R.string(),output_index:R.number().nullish(),summary_index:R.number()}),R.object({type:R.literal("response.apply_patch_call_operation_diff.delta"),item_id:R.string(),output_index:R.number(),delta:R.string(),obfuscation:R.string().nullish()}),R.object({type:R.literal("response.apply_patch_call_operation_diff.done"),item_id:R.string(),output_index:R.number(),diff:R.string()}),Fw4,Uw4,R.object({type:R.string()}).loose().refine(($)=>!Ow4($),{message:"Known response chunk failed schema validation"}).transform(($)=>({type:"unknown_chunk",message:$.type}))]))),Y3$=W0(()=>r(R.object({id:R.string().optional(),created_at:R.number().optional(),error:R.object({message:R.string(),type:R.string(),param:R.string().nullish(),code:R.string()}).nullish(),model:R.string().optional(),output:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("message"),role:R.literal("assistant"),id:R.string(),phase:R.enum(["commentary","final_answer"]).nullish(),content:R.array(R.object({type:R.literal("output_text"),text:R.string(),logprobs:R.array(R.object({token:R.string(),logprob:R.number(),top_logprobs:R.array(R.object({token:R.string(),logprob:R.number()}))})).nullish(),annotations:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("url_citation"),start_index:R.number(),end_index:R.number(),url:R.string(),title:R.string()}),R.object({type:R.literal("file_citation"),file_id:R.string(),filename:R.string(),index:R.number()}),R.object({type:R.literal("container_file_citation"),container_id:R.string(),file_id:R.string(),filename:R.string(),start_index:R.number(),end_index:R.number()}),R.object({type:R.literal("file_path"),file_id:R.string(),index:R.number()})]))}))}),R.object({type:R.literal("web_search_call"),id:R.string(),status:R.string(),action:R.discriminatedUnion("type",[R.object({type:R.literal("search"),query:R.string().nullish(),queries:R.array(R.string()).nullish(),sources:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("url"),url:R.string()}),R.object({type:R.literal("api"),name:R.string()})])).nullish()}),R.object({type:R.literal("open_page"),url:R.string().nullish()}),R.object({type:R.literal("find_in_page"),url:R.string().nullish(),pattern:R.string().nullish()})]).nullish()}),R.object({type:R.literal("file_search_call"),id:R.string(),queries:R.array(R.string()),results:R.array(R.object({attributes:R.record(R.string(),R.union([R.string(),R.number(),R.boolean()])),file_id:R.string(),filename:R.string(),score:R.number(),text:R.string()})).nullish()}),R.object({type:R.literal("code_interpreter_call"),id:R.string(),code:R.string().nullable(),container_id:R.string(),outputs:R.array(R.discriminatedUnion("type",[R.object({type:R.literal("logs"),logs:R.string()}),R.object({type:R.literal("image"),url:R.string()})])).nullable()}),R.object({type:R.literal("image_generation_call"),id:R.string(),result:R.string()}),na0,R.object({type:R.literal("function_call"),call_id:R.string(),name:R.string(),arguments:R.string(),id:R.string(),async:R.boolean().nullish(),namespace:R.string().nullish(),caller:da0.nullish()}),ia0,pa0,R.object({type:R.literal("custom_tool_call"),call_id:R.string(),name:R.string(),input:R.string(),id:R.string(),async:R.boolean().nullish()}),ma0,R.object({type:R.literal("reasoning"),id:R.string(),encrypted_content:R.string().nullish(),summary:R.array(R.object({type:R.literal("summary_text"),text:R.string()}))}),R.object({type:R.literal("mcp_call"),id:R.string(),status:R.string(),arguments:R.string(),name:R.string(),server_label:R.string(),output:R.string().nullish(),error:R.union([R.string(),R.object({type:R.string().optional(),code:R.union([R.number(),R.string()]).optional(),message:R.string().optional()}).loose()]).nullish(),approval_request_id:R.string().nullish()}),R.object({type:R.literal("mcp_list_tools"),id:R.string(),server_label:R.string(),tools:R.array(R.object({name:R.string(),description:R.string().optional(),input_schema:R.any(),annotations:R.record(R.string(),R.unknown()).optional()})),error:R.union([R.string(),R.object({type:R.string().optional(),code:R.union([R.number(),R.string()]).optional(),message:R.string().optional()}).loose()]).optional()}),R.object({type:R.literal("mcp_approval_request"),id:R.string(),server_label:R.string(),name:R.string(),arguments:R.string(),approval_request_id:R.string().optional()}),R.object({type:R.literal("apply_patch_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed"]),operation:R.discriminatedUnion("type",[R.object({type:R.literal("create_file"),path:R.string(),diff:R.string()}),R.object({type:R.literal("delete_file"),path:R.string()}),R.object({type:R.literal("update_file"),path:R.string(),diff:R.string()})])}),R.object({type:R.literal("shell_call"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),action:R.object({commands:R.array(R.string())})}),R.object({type:R.literal("compaction"),id:R.string(),encrypted_content:R.string()}),R.object({type:R.literal("shell_call_output"),id:R.string(),call_id:R.string(),status:R.enum(["in_progress","completed","incomplete"]),output:R.array(R.object({stdout:R.string(),stderr:R.string(),outcome:R.discriminatedUnion("type",[R.object({type:R.literal("timeout")}),R.object({type:R.literal("exit"),exit_code:R.number()})])}))}),R.object({type:R.literal("tool_search_call"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),arguments:R.unknown()}),R.object({type:R.literal("tool_search_output"),id:R.string(),execution:R.enum(["server","client"]),call_id:R.string().nullable(),status:R.enum(["in_progress","completed","incomplete"]),tools:R.array(R.record(R.string(),dl.optional()))})])).optional(),service_tier:R.string().nullish(),reasoning:R.object({context:R.string().nullish()}).nullish(),incomplete_details:R.object({reason:R.string()}).nullish(),usage:ca0.nullish()})));zw4=_a0.object({itemId:_a0.string().nullish(),reasoningEncryptedContent:_a0.string().nullish()}),Pw4=["o1","o1-2024-12-17","o3","o3-2025-04-16","o3-mini","o3-mini-2025-01-31","o4-mini","o4-mini-2025-04-16","gpt-5","gpt-5-2025-08-07","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06","gpt-5.1","gpt-5.1-chat-latest","gpt-5.1-codex-mini","gpt-5.1-codex","gpt-5.1-codex-max","gpt-5.2","gpt-5.2-chat-latest","gpt-5.2-pro","gpt-5.2-codex","gpt-5.3-chat-latest","gpt-5.3-codex","gpt-5.4","gpt-5.4-2026-03-05","gpt-5.4-mini","gpt-5.4-mini-2026-03-17","gpt-5.4-nano","gpt-5.4-nano-2026-03-17","gpt-5.4-pro","gpt-5.4-pro-2026-03-05","gpt-5.5","gpt-5.5-2026-04-23","gpt-5.6","gpt-5.6-luna","gpt-5.6-sol","gpt-5.6-terra","gpt-6-astra"],xu5=["gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-3.5-turbo-0125","gpt-3.5-turbo","gpt-3.5-turbo-1106","gpt-5-chat-latest",...Pw4],IG$=W0(()=>r(r8.object({conversation:r8.string().nullish(),include:r8.array(r8.enum(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),includeWebSearchSources:r8.boolean().optional(),instructions:r8.string().nullish(),logprobs:r8.union([r8.boolean(),r8.number().min(1).max(X3$)]).optional(),maxToolCalls:r8.number().nullish(),metadata:r8.any().nullish(),parallelToolCalls:r8.boolean().nullish(),previousResponseId:r8.string().nullish(),promptCacheKey:r8.string().nullish(),promptCacheOptions:r8.object({mode:r8.enum(["implicit","explicit"]).optional(),ttl:r8.literal("30m").optional()}).optional(),promptCacheRetention:r8.enum(["in_memory","24h"]).nullish(),reasoningEffort:r8.string().nullish(),reasoningEffortUpdate:r8.enum(["low","medium","high","xhigh","max"]).optional(),reasoningMode:r8.enum(["standard","pro"]).optional(),reasoningContext:r8.enum(["auto","current_turn","all_turns"]).optional(),reasoningSummary:r8.string().nullish(),safetyIdentifier:r8.string().nullish(),serviceTier:r8.enum(["auto","flex","priority","fast","ultrafast","default"]).nullish(),store:r8.boolean().nullish(),passThroughUnsupportedFiles:r8.boolean().optional(),strictJsonSchema:r8.boolean().nullish(),textVerbosity:r8.enum(["low","medium","high"]).nullish(),truncation:r8.enum(["auto","disabled"]).nullish(),user:r8.string().nullish(),systemMessageMode:r8.enum(["system","developer","remove"]).optional(),forceReasoning:r8.boolean().optional(),contextManagement:r8.array(r8.object({type:r8.literal("compaction"),compactThreshold:r8.number()})).nullish(),compactionTrigger:r8.boolean().optional(),allowedTools:r8.object({toolNames:r8.array(r8.string()).min(1),mode:r8.enum(["auto","required"]).optional()}).optional()})));J3$={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},G3$=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls=J3$,this.modelId=Z,this.config=Q}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Lw4(Z.config))}get provider(){return this.config.provider}static async prepareRequest({modelId:Z,config:Q,options:{maxOutputTokens:Y,temperature:X,stopSequences:J,topP:G,topK:W,presencePenalty:K,frequencyPenalty:H,seed:F,prompt:U,reasoning:N,providerOptions:B,tools:O,toolChoice:L,responseFormat:w}}){var j,E,z,T,P,A,q,x,_,V,y,g,l,n;let p=[],F0=dG$(Z);if(W!=null)p.push({type:"unsupported",feature:"topK"});if(F!=null)p.push({type:"unsupported",feature:"seed"});if(K!=null)p.push({type:"unsupported",feature:"presencePenalty"});if(H!=null)p.push({type:"unsupported",feature:"frequencyPenalty"});if(J!=null)p.push({type:"unsupported",feature:"stopSequences"});let V0=Q.provider.includes("azure")?"azure":"openai",G0=await I$({provider:V0,providerOptions:B,schema:IG$});if(G0==null&&V0!=="openai")G0=await I$({provider:"openai",providerOptions:B,schema:IG$});let H0=(j=G0==null?void 0:G0.reasoningEffort)!=null?j:XB(N)?N:void 0;if(H0!=null&&F0.supportedReasoningEfforts!=null&&!F0.supportedReasoningEfforts.includes(H0))p.push({type:"unsupported",feature:"reasoningEffort",details:`${Z} only supports the following reasoning efforts: ${F0.supportedReasoningEfforts.join(", ")}`}),H0=void 0;let X0=(G0==null?void 0:G0.reasoningSummary)!==void 0?G0.reasoningSummary:H0!=null&&H0!=="none"?"detailed":void 0,Z0=(E=G0==null?void 0:G0.forceReasoning)!=null?E:F0.isReasoningModel;if((G0==null?void 0:G0.conversation)&&(G0==null?void 0:G0.previousResponseId))p.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});let Y0=Jl({tools:O,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.computer":"computer","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch","openai.tool_search":"tool_search","openai.programmatic_tool_calling":"programmatic_tool_calling"}}),o=new Set,J0=new Set,{tools:c0,toolChoice:k0,toolWarnings:j1}=await Aw4({tools:O,toolChoice:L,allowedTools:(z=G0==null?void 0:G0.allowedTools)!=null?z:void 0,toolNameMapping:Y0,customProviderToolNames:o,outputSchemaToolNames:J0,supportsAsyncToolCalling:F0.supportsAsyncToolCalling}),{input:d0,warnings:L0}=await Ew4({prompt:U,toolNameMapping:Y0,systemMessageMode:(T=G0==null?void 0:G0.systemMessageMode)!=null?T:Z0?"developer":F0.systemMessageMode,providerOptionsName:V0,explicitMessageItemType:Q.explicitMessageItemType,fileIdPrefixes:Q.fileIdPrefixes,passThroughUnsupportedFiles:(P=G0==null?void 0:G0.passThroughUnsupportedFiles)!=null?P:!1,store:(A=G0==null?void 0:G0.store)!=null?A:!0,hasConversation:(G0==null?void 0:G0.conversation)!=null,hasPreviousResponseId:(G0==null?void 0:G0.previousResponseId)!=null,hasLocalShellTool:w0("openai.local_shell"),hasShellTool:w0("openai.shell"),hasApplyPatchTool:w0("openai.apply_patch"),hasComputerTool:w0("openai.computer"),toolSearchToolName:Q0("openai.tool_search"),customProviderToolNames:o.size>0?o:void 0,outputSchemaToolNames:J0.size>0?J0:void 0});p.push(...L0);let j0=G0==null?void 0:G0.reasoningEffortUpdate,a0=j0==null||F0.supportsConfigurationUpdate&&(G0==null?void 0:G0.reasoningMode)!=="pro"&&(G0==null?void 0:G0.contextManagement)==null&&(G0==null?void 0:G0.truncation)!=="auto";if(j0!=null&&!a0)p.push({type:"unsupported",feature:"reasoningEffortUpdate",details:!F0.supportsConfigurationUpdate?"reasoningEffortUpdate is only supported by GPT-6 and later models":"reasoningEffortUpdate requires standard reasoning mode without automatic compaction or automatic truncation"});else if(j0!=null)d0.unshift({type:"configuration_update",reasoning:{effort:j0}});if(G0==null?void 0:G0.compactionTrigger)d0.push({type:"compaction_trigger"});let P1=(q=G0==null?void 0:G0.strictJsonSchema)!=null?q:!0,K1=(w==null?void 0:w.type)==="json"&&w.schema!=null?Fa(w.schema):void 0;if(K1!=null)p.push(...K1.warnings);let v0=G0==null?void 0:G0.include;function l0(I1){if(v0==null)v0=[I1];else if(!v0.includes(I1))v0=[...v0,I1]}function Q0(I1){var H8;return(H8=O==null?void 0:O.find((B8)=>B8.type==="provider"&&B8.id===I1))==null?void 0:H8.name}function w0(I1){return Q0(I1)!=null}let e=typeof(G0==null?void 0:G0.logprobs)==="number"?G0==null?void 0:G0.logprobs:(G0==null?void 0:G0.logprobs)===!0?X3$:void 0;if(e)l0("message.output_text.logprobs");let i=(x=O==null?void 0:O.find((I1)=>I1.type==="provider"&&(I1.id==="openai.web_search"||I1.id==="openai.web_search_preview")))==null?void 0:x.name;if(i&&Q.supportsWebSearchSourcesInclude!==!1&&(G0==null?void 0:G0.includeWebSearchSources)!==!1)l0("web_search_call.action.sources");if(w0("openai.code_interpreter"))l0("code_interpreter_call.outputs");let m0=G0==null?void 0:G0.store;if(m0===!1&&Z0)l0("reasoning.encrypted_content");let I0={model:Z,input:d0,temperature:X,top_p:G,max_output_tokens:Y,...((w==null?void 0:w.type)==="json"||(G0==null?void 0:G0.textVerbosity))&&{text:{...(w==null?void 0:w.type)==="json"&&{format:K1!=null?{type:"json_schema",strict:P1,name:(_=w.name)!=null?_:"response",description:w.description,schema:K1.schema}:{type:"json_object"}},...(G0==null?void 0:G0.textVerbosity)&&{verbosity:G0.textVerbosity}}},conversation:G0==null?void 0:G0.conversation,max_tool_calls:G0==null?void 0:G0.maxToolCalls,metadata:G0==null?void 0:G0.metadata,parallel_tool_calls:G0==null?void 0:G0.parallelToolCalls,previous_response_id:G0==null?void 0:G0.previousResponseId,store:m0,user:G0==null?void 0:G0.user,instructions:G0==null?void 0:G0.instructions,service_tier:G0==null?void 0:G0.serviceTier,include:v0,prompt_cache_key:G0==null?void 0:G0.promptCacheKey,prompt_cache_options:G0==null?void 0:G0.promptCacheOptions,prompt_cache_retention:G0==null?void 0:G0.promptCacheRetention,safety_identifier:G0==null?void 0:G0.safetyIdentifier,top_logprobs:e,truncation:G0==null?void 0:G0.truncation,...(G0==null?void 0:G0.contextManagement)&&{context_management:G0.contextManagement.map((I1)=>({type:I1.type,compact_threshold:I1.compactThreshold}))},...Z0&&(H0!=null||X0!=null||(G0==null?void 0:G0.reasoningMode)!=null||(G0==null?void 0:G0.reasoningContext)!=null)&&{reasoning:{...H0!=null&&{effort:H0},...X0!=null&&{summary:X0},...(G0==null?void 0:G0.reasoningMode)!=null&&{mode:G0.reasoningMode},...(G0==null?void 0:G0.reasoningContext)!=null&&{context:G0.reasoningContext}}}};if(F0.supportsConfigurationUpdate&&I0.prompt_cache_retention!=null)I0.prompt_cache_retention=void 0,p.push({type:"unsupported",feature:"promptCacheRetention",details:"promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"});if(Z0){if(!(H0==="none"&&F0.supportsNonReasoningParameters)){if(I0.temperature!=null)I0.temperature=void 0,p.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(I0.top_p!=null)I0.top_p=void 0,p.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(F0.supportedReasoningEfforts!=null&&(I0.top_logprobs!=null||((V=I0.include)==null?void 0:V.includes("message.output_text.logprobs")))){I0.top_logprobs=void 0;let I1=(y=I0.include)==null?void 0:y.filter((H8)=>H8!=="message.output_text.logprobs");I0.include=I1!=null&&I1.length>0?I1:void 0,p.push({type:"unsupported",feature:"logprobs",details:"logprobs is not supported for reasoning models"})}}}else{if((G0==null?void 0:G0.reasoningEffort)!=null)p.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"});if((G0==null?void 0:G0.reasoningSummary)!=null)p.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"});if((G0==null?void 0:G0.reasoningMode)!=null)p.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"});if((G0==null?void 0:G0.reasoningContext)!=null)p.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})}if((G0==null?void 0:G0.serviceTier)==="flex"&&!F0.supportsFlexProcessing)p.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete I0.service_tier;if(((G0==null?void 0:G0.serviceTier)==="priority"||(G0==null?void 0:G0.serviceTier)==="fast")&&!F0.supportsPriorityProcessing)p.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete I0.service_tier;let t0=(n=(l=(g=O==null?void 0:O.find((I1)=>I1.type==="provider"&&I1.id==="openai.shell"))==null?void 0:g.args)==null?void 0:l.environment)==null?void 0:n.type,f0=t0==="containerAuto"||t0==="containerReference";return{webSearchToolName:i,args:{...I0,tools:c0,tool_choice:k0},warnings:[...p,...j1],store:m0,toolNameMapping:Y0,providerOptionsName:V0,isShellProviderExecuted:f0}}getArgs(Z){return $.prepareRequest({modelId:this.modelId,config:this.config,options:Z})}async doGenerate(Z){var Q,Y,X,J,G,W,K,H,F,U,N,B,O,L,w,j,E,z,T,P,A,q,x,_,V,y,g,l,n,p,F0,V0,G0,H0;let{args:X0,warnings:Z0,webSearchToolName:Y0,toolNameMapping:o,providerOptionsName:J0,isShellProviderExecuted:c0}=await this.getArgs(Z),k0=this.config.url({path:"/responses",modelId:this.modelId}),j1=SG$(Z.prompt),{responseHeaders:d0,value:L0,rawValue:j0}=await o1({url:k0,headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:X0,failedResponseHandler:R9,successfulResponseHandler:E1(Y3$),abortSignal:Z.abortSignal,fetch:this.config.fetch});if(L0.error)throw new W8({message:L0.error.message,url:k0,requestBodyValues:X0,statusCode:400,responseHeaders:d0,responseBody:j0,isRetryable:!1});if(L0.output==null){let e=(X=L0.incomplete_details)==null?void 0:X.reason;throw new W8({message:e?`Responses API returned no output (${e})`:"Responses API returned no output",url:k0,requestBodyValues:X0,statusCode:500,responseHeaders:d0,responseBody:j0,isRetryable:!1})}let a0=[],P1=[],K1=(G=(J=Z.tools)==null?void 0:J.filter((e)=>e.type==="function"))!=null?G:[],v0=!1,l0=[];for(let e of L0.output)switch(e.type){case"reasoning":{if(e.summary.length===0)e.summary.push({type:"summary_text",text:""});for(let i of e.summary)a0.push({type:"reasoning",text:i.text,providerMetadata:{[J0]:{itemId:e.id,reasoningEncryptedContent:(W=e.encrypted_content)!=null?W:null}}});break}case"image_generation_call":{a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName("image_generation"),result:{result:e.result}});break}case"tool_search_call":{let i=(K=e.call_id)!=null?K:e.id,m0=e.execution==="server";if(m0)l0.push(i);a0.push({type:"tool-call",toolCallId:i,toolName:o.toCustomToolName("tool_search"),input:JSON.stringify({arguments:e.arguments,call_id:e.call_id}),...m0?{providerExecuted:!0}:{},providerMetadata:{[J0]:{itemId:e.id}}});break}case"tool_search_output":{let i=(F=(H=e.call_id)!=null?H:l0.shift())!=null?F:e.id;a0.push({type:"tool-result",toolCallId:i,toolName:o.toCustomToolName("tool_search"),result:{tools:e.tools},providerMetadata:{[J0]:{itemId:e.id}}});break}case"local_shell_call":{a0.push({type:"tool-call",toolCallId:e.call_id,toolName:o.toCustomToolName("local_shell"),input:JSON.stringify({action:e.action}),providerMetadata:{[J0]:{itemId:e.id}}});break}case"shell_call":{a0.push({type:"tool-call",toolCallId:e.call_id,toolName:o.toCustomToolName("shell"),input:JSON.stringify({action:{commands:e.action.commands}}),...c0&&{providerExecuted:!0},providerMetadata:{[J0]:{itemId:e.id}}});break}case"shell_call_output":{a0.push({type:"tool-result",toolCallId:e.call_id,toolName:o.toCustomToolName("shell"),result:{output:e.output.map((i)=>({stdout:i.stdout,stderr:i.stderr,outcome:i.outcome.type==="exit"?{type:"exit",exitCode:i.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(let i of e.content){if(((N=(U=Z.providerOptions)==null?void 0:U[J0])==null?void 0:N.logprobs)&&i.logprobs)P1.push(i.logprobs);let m0={itemId:e.id,...e.phase!=null&&{phase:e.phase},...i.annotations.length>0&&{annotations:i.annotations}};a0.push({type:"text",text:i.text,providerMetadata:{[J0]:m0}});for(let I0 of i.annotations)if(I0.type==="url_citation")a0.push({type:"source",sourceType:"url",id:(L=(O=(B=this.config).generateId)==null?void 0:O.call(B))!=null?L:o8(),url:I0.url,title:I0.title});else if(I0.type==="file_citation")a0.push({type:"source",sourceType:"document",id:(E=(j=(w=this.config).generateId)==null?void 0:j.call(w))!=null?E:o8(),mediaType:"text/plain",title:I0.filename,filename:I0.filename,providerMetadata:{[J0]:{type:I0.type,fileId:I0.file_id,index:I0.index}}});else if(I0.type==="container_file_citation")a0.push({type:"source",sourceType:"document",id:(P=(T=(z=this.config).generateId)==null?void 0:T.call(z))!=null?P:o8(),mediaType:"text/plain",title:I0.filename,filename:I0.filename,providerMetadata:{[J0]:{type:I0.type,fileId:I0.file_id,containerId:I0.container_id}}});else if(I0.type==="file_path")a0.push({type:"source",sourceType:"document",id:(x=(q=(A=this.config).generateId)==null?void 0:q.call(A))!=null?x:o8(),mediaType:"application/octet-stream",title:I0.file_id,filename:I0.file_id,providerMetadata:{[J0]:{type:I0.type,fileId:I0.file_id,index:I0.index}}})}break}case"function_call":{v0=!0;let i=await TG$({toolCall:{toolCallId:e.call_id,toolName:e.name,input:e.arguments},tools:K1,providerOptionsName:J0,itemId:e.id});if(i!=null){a0.push(...i);break}a0.push({type:"tool-call",toolCallId:e.call_id,toolName:e.name,input:e.arguments,providerMetadata:{[J0]:{itemId:e.id,...e.async!=null&&{async:e.async},...e.namespace!=null&&{namespace:e.namespace},...e.caller!=null&&{caller:e.caller.type==="program"?{type:"program",callerId:e.caller.caller_id}:e.caller}}}});break}case"program":{a0.push({type:"tool-call",toolCallId:e.call_id,toolName:o.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:e.code,fingerprint:e.fingerprint}),providerExecuted:!0,providerMetadata:{[J0]:{itemId:e.id}}});break}case"program_output":{a0.push({type:"tool-result",toolCallId:e.call_id,toolName:o.toCustomToolName("programmatic_tool_calling"),result:{result:e.result,status:e.status},providerMetadata:{[J0]:{itemId:e.id}}});break}case"custom_tool_call":{v0=!0;let i=o.toCustomToolName(e.name);a0.push({type:"tool-call",toolCallId:e.call_id,toolName:i,input:JSON.stringify(e.input),providerMetadata:{[J0]:{itemId:e.id,...e.async!=null&&{async:e.async}}}});break}case"web_search_call":{a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName(Y0!=null?Y0:"web_search"),input:JSON.stringify({}),providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName(Y0!=null?Y0:"web_search"),result:sa0(e.action)});break}case"mcp_call":{let i=e.approval_request_id!=null?(_=j1[e.approval_request_id])!=null?_:e.id:e.id,m0=`mcp.${e.name}`;a0.push({type:"tool-call",toolCallId:i,toolName:m0,input:e.arguments,providerExecuted:!0,dynamic:!0}),a0.push({type:"tool-result",toolCallId:i,toolName:m0,result:{type:"call",serverLabel:e.server_label,name:e.name,arguments:e.arguments,...e.output!=null?{output:e.output}:{},...e.error!=null?{error:e.error}:{}},providerMetadata:{[J0]:{itemId:e.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{let i=(V=e.approval_request_id)!=null?V:e.id,m0=(l=(g=(y=this.config).generateId)==null?void 0:g.call(y))!=null?l:o8(),I0=`mcp.${e.name}`;a0.push({type:"tool-call",toolCallId:m0,toolName:I0,input:e.arguments,providerExecuted:!0,dynamic:!0}),a0.push({type:"tool-approval-request",approvalId:i,toolCallId:m0});break}case"computer_call":{if(e.call_id==null){a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:e.status}});break}v0=!0;let i=o.toCustomToolName("computer");a0.push({type:"tool-call",toolCallId:e.call_id,toolName:i,input:JSON.stringify(CG$(e)),providerMetadata:{[J0]:{itemId:e.id}}});break}case"file_search_call":{a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName("file_search"),result:{queries:e.queries,results:(p=(n=e.results)==null?void 0:n.map((i)=>({attributes:i.attributes,fileId:i.file_id,filename:i.filename,score:i.score,text:i.text})))!=null?p:null}});break}case"code_interpreter_call":{a0.push({type:"tool-call",toolCallId:e.id,toolName:o.toCustomToolName("code_interpreter"),input:JSON.stringify({code:e.code,containerId:e.container_id}),providerExecuted:!0}),a0.push({type:"tool-result",toolCallId:e.id,toolName:o.toCustomToolName("code_interpreter"),result:{outputs:e.outputs}});break}case"apply_patch_call":{v0=!0,a0.push({type:"tool-call",toolCallId:e.call_id,toolName:o.toCustomToolName("apply_patch"),input:JSON.stringify({callId:e.call_id,operation:e.operation}),providerMetadata:{[J0]:{itemId:e.id}}});break}case"compaction":{a0.push({type:"custom",kind:"openai.compaction",providerMetadata:{[J0]:{type:"compaction",itemId:e.id,encryptedContent:e.encrypted_content}}});break}}let Q0={[J0]:{responseId:L0.id,...P1.length>0?{logprobs:P1}:{},...typeof L0.service_tier==="string"?{serviceTier:L0.service_tier}:{},...((F0=L0.reasoning)==null?void 0:F0.context)!=null?{reasoningContext:L0.reasoning.context}:{}}},w0=L0.usage;return{content:a0,finishReason:{unified:Z30({finishReason:(V0=L0.incomplete_details)==null?void 0:V0.reason,hasFunctionCall:v0}),raw:(H0=(G0=L0.incomplete_details)==null?void 0:G0.reason)!=null?H0:void 0},usage:la0(w0),request:{body:X0},response:{id:L0.id,timestamp:new Date(L0.created_at*1000),modelId:L0.model,headers:d0,body:j0},providerMetadata:Q0,warnings:Z0}}async doStream(Z){var Q,Y,X,J;let{args:G,warnings:W,webSearchToolName:K,toolNameMapping:H,store:F,providerOptionsName:U,isShellProviderExecuted:N}=await this.getArgs(Z),B=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:O,value:L}=await o1({url:B,headers:T1((Y=(Q=this.config).headers)==null?void 0:Y.call(Q),Z.headers),body:{...G,stream:!0},failedResponseHandler:R9,successfulResponseHandler:UY(Dw4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),w=await Qe0({stream:L,getError:(Z0)=>bG$(Z0)||_G$(Z0)&&Z0.response.error!=null?Z0:void 0,isOutputChunk:iw4,isAcceptedChunk:dw4,url:B,requestBodyValues:G,responseHeaders:O}),j=this,E=SG$(Z.prompt),z=(J=(X=Z.tools)==null?void 0:X.filter((Z0)=>Z0.type==="function"))!=null?J:[],T=new Map,P={unified:"other",raw:void 0},A=void 0,q=[],x=null,_={},V=[],y,g=!1,l={},n={},p=({itemId:Z0,outputIndex:Y0})=>{var o;return Y0==null?Z0:(o=n[Y0])!=null?o:Z0},F0,V0,G0=[],H0=!1;return{stream:w.pipeThrough(new TransformStream({start(Z0){Z0.enqueue({type:"stream-start",warnings:W})},transform(Z0,Y0){var o,J0,c0,k0,j1,d0,L0,j0,a0,P1,K1,v0,l0,Q0,w0,e,i,m0,I0,t0,f0,I1,H8,B8,m4,Q8,D5,x8,m6,O9,o0,D1,x$,h1,Y$,_8,r6,G4,a1,T8,n$,W$,Q9,ZQ,OZ;if(Z.includeRawChunks)Y0.enqueue({type:"raw",rawValue:Z0.rawValue});if(!Z0.success){let M0=Sw4(Z0.rawValue)?Cw4({value:Z0.rawValue,cause:Z0.error,url:B,requestBodyValues:G,responseHeaders:O}):Z0.error;H0=!0,P={unified:"error",raw:void 0},Y0.enqueue({type:"error",error:M0});return}let $0=Z0.value;if(vG$($0)){if($0.item.type==="function_call"){let M0=oa0({toolName:$0.item.name,tools:z});if(_[$0.output_index]={toolName:$0.item.name,toolCallId:$0.item.call_id,suppressInputStreaming:M0,bufferedInputDeltas:M0?[]:void 0,async:$0.item.async},!M0)Y0.enqueue({type:"tool-input-start",id:$0.item.call_id,toolName:$0.item.name})}else if($0.item.type==="custom_tool_call"){let M0=H.toCustomToolName($0.item.name);_[$0.output_index]={toolName:M0,toolCallId:$0.item.call_id,async:$0.item.async},Y0.enqueue({type:"tool-input-start",id:$0.item.call_id,toolName:M0})}else if($0.item.type==="web_search_call")_[$0.output_index]={toolName:H.toCustomToolName(K!=null?K:"web_search"),toolCallId:$0.item.id},Y0.enqueue({type:"tool-input-start",id:$0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),providerExecuted:!0}),Y0.enqueue({type:"tool-input-end",id:$0.item.id}),Y0.enqueue({type:"tool-call",toolCallId:$0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if($0.item.type==="computer_call"){let M0=(o=$0.item.call_id)!=null?o:$0.item.id;_[$0.output_index]={toolName:H.toCustomToolName("computer"),toolCallId:M0},Y0.enqueue({type:"tool-input-start",id:M0,toolName:H.toCustomToolName("computer")})}else if($0.item.type==="code_interpreter_call")_[$0.output_index]={toolName:H.toCustomToolName("code_interpreter"),toolCallId:$0.item.id,codeInterpreter:{containerId:$0.item.container_id}},Y0.enqueue({type:"tool-input-start",id:$0.item.id,toolName:H.toCustomToolName("code_interpreter"),providerExecuted:!0}),Y0.enqueue({type:"tool-input-delta",id:$0.item.id,delta:`{"containerId":"${$0.item.container_id}","code":"`});else if($0.item.type==="file_search_call")Y0.enqueue({type:"tool-call",toolCallId:$0.item.id,toolName:H.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if($0.item.type==="image_generation_call")Y0.enqueue({type:"tool-call",toolCallId:$0.item.id,toolName:H.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if($0.item.type==="tool_search_call"){let M0=$0.item.id,R1=H.toCustomToolName("tool_search"),f8=$0.item.execution==="server";if(_[$0.output_index]={toolName:R1,toolCallId:M0,toolSearchExecution:(J0=$0.item.execution)!=null?J0:"server"},f8)Y0.enqueue({type:"tool-input-start",id:M0,toolName:R1,providerExecuted:!0})}else if($0.item.type==="tool_search_output");else if($0.item.type==="mcp_call"||$0.item.type==="mcp_list_tools"||$0.item.type==="mcp_approval_request");else if($0.item.type==="apply_patch_call"){let{call_id:M0,operation:R1}=$0.item;if(_[$0.output_index]={toolName:H.toCustomToolName("apply_patch"),toolCallId:M0,applyPatch:{hasDiff:R1.type==="delete_file",endEmitted:R1.type==="delete_file"}},Y0.enqueue({type:"tool-input-start",id:M0,toolName:H.toCustomToolName("apply_patch")}),R1.type==="delete_file"){let f8=JSON.stringify({callId:M0,operation:R1});Y0.enqueue({type:"tool-input-delta",id:M0,delta:f8}),Y0.enqueue({type:"tool-input-end",id:M0})}else Y0.enqueue({type:"tool-input-delta",id:M0,delta:`{"callId":"${DA(M0)}","operation":{"type":"${DA(R1.type)}","path":"${DA(R1.path)}","diff":"`})}else if($0.item.type==="shell_call")_[$0.output_index]={toolName:H.toCustomToolName("shell"),toolCallId:$0.item.call_id};else if($0.item.type==="shell_call_output");else if($0.item.type==="message")n[$0.output_index]=$0.item.id,V.splice(0,V.length),y=(c0=$0.item.phase)!=null?c0:void 0,Y0.enqueue({type:"text-start",id:$0.item.id,providerMetadata:{[U]:{itemId:$0.item.id,...$0.item.phase!=null&&{phase:$0.item.phase}}}});else if(vG$($0)&&$0.item.type==="reasoning")n[$0.output_index]=$0.item.id,l[$0.item.id]={encryptedContent:$0.item.encrypted_content,summaryParts:{0:"active"}},Y0.enqueue({type:"reasoning-start",id:`${$0.item.id}:0`,providerMetadata:{[U]:{itemId:$0.item.id,reasoningEncryptedContent:(k0=$0.item.encrypted_content)!=null?k0:null}}})}else if(vw4($0)){if($0.item.type==="message"){let M0=p({itemId:$0.item.id,outputIndex:$0.output_index}),R1=(j1=$0.item.phase)!=null?j1:y;y=void 0,Y0.enqueue({type:"text-end",id:M0,providerMetadata:{[U]:{itemId:M0,...R1!=null&&{phase:R1},...V.length>0&&{annotations:V}}}}),n[$0.output_index]=void 0}else if($0.item.type==="function_call"){let M0=$0.item,R1=_[$0.output_index];_[$0.output_index]=void 0,g=!0;let f8=(d0=R1==null?void 0:R1.suppressInputStreaming)!=null?d0:oa0({toolName:M0.name,tools:z}),v=()=>{var c;if(f8){Y0.enqueue({type:"tool-input-start",id:M0.call_id,toolName:M0.name});let m=(c=R1==null?void 0:R1.bufferedInputDeltas)!=null?c:[];if(m.length>0)for(let M of m)Y0.enqueue({type:"tool-input-delta",id:M0.call_id,delta:M});else if(M0.arguments.length>0)Y0.enqueue({type:"tool-input-delta",id:M0.call_id,delta:M0.arguments})}Y0.enqueue({type:"tool-input-end",id:M0.call_id,...M0.namespace!=null&&{providerMetadata:{[U]:{namespace:M0.namespace}}}}),Y0.enqueue({type:"tool-call",toolCallId:M0.call_id,toolName:M0.name,input:M0.arguments,providerMetadata:{[U]:{itemId:M0.id,...M0.async!=null?{async:M0.async}:(R1==null?void 0:R1.async)!=null?{async:R1.async}:{},...M0.namespace!=null&&{namespace:M0.namespace},...M0.caller!=null&&{caller:M0.caller.type==="program"?{type:"program",callerId:M0.caller.caller_id}:M0.caller}}}})};if(!f8){v();return}return TG$({toolCall:{toolCallId:M0.call_id,toolName:M0.name,input:M0.arguments},tools:z,providerOptionsName:U,itemId:M0.id}).then((c)=>{if(c==null){v();return}for(let m of c)Y0.enqueue({type:"tool-input-start",id:m.toolCallId,toolName:m.toolName}),Y0.enqueue({type:"tool-input-delta",id:m.toolCallId,delta:m.input}),Y0.enqueue({type:"tool-input-end",id:m.toolCallId}),Y0.enqueue(m)})}else if($0.item.type==="program")Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:$0.item.code,fingerprint:$0.item.fingerprint}),providerExecuted:!0,providerMetadata:{[U]:{itemId:$0.item.id}}});else if($0.item.type==="program_output")Y0.enqueue({type:"tool-result",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("programmatic_tool_calling"),result:{result:$0.item.result,status:$0.item.status},providerMetadata:{[U]:{itemId:$0.item.id}}});else if($0.item.type==="custom_tool_call"){let M0=_[$0.output_index];_[$0.output_index]=void 0,g=!0;let R1=H.toCustomToolName($0.item.name);Y0.enqueue({type:"tool-input-end",id:$0.item.call_id}),Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:R1,input:JSON.stringify($0.item.input),providerMetadata:{[U]:{itemId:$0.item.id,...$0.item.async!=null?{async:$0.item.async}:(M0==null?void 0:M0.async)!=null?{async:M0.async}:{}}}})}else if($0.item.type==="web_search_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),result:sa0($0.item.action)});else if($0.item.type==="computer_call"){if(_[$0.output_index]=void 0,$0.item.call_id==null){Y0.enqueue({type:"tool-input-end",id:$0.item.id}),Y0.enqueue({type:"tool-call",toolCallId:$0.item.id,toolName:H.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:$0.item.status}});return}g=!0;let M0=H.toCustomToolName("computer"),R1=JSON.stringify(CG$($0.item));Y0.enqueue({type:"tool-input-delta",id:$0.item.call_id,delta:R1}),Y0.enqueue({type:"tool-input-end",id:$0.item.call_id}),Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:M0,input:R1,providerMetadata:{[U]:{itemId:$0.item.id}}})}else if($0.item.type==="file_search_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName("file_search"),result:{queries:$0.item.queries,results:(j0=(L0=$0.item.results)==null?void 0:L0.map((M0)=>({attributes:M0.attributes,fileId:M0.file_id,filename:M0.filename,score:M0.score,text:M0.text})))!=null?j0:null}});else if($0.item.type==="code_interpreter_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName("code_interpreter"),result:{outputs:$0.item.outputs}});else if($0.item.type==="image_generation_call")Y0.enqueue({type:"tool-result",toolCallId:$0.item.id,toolName:H.toCustomToolName("image_generation"),result:{result:$0.item.result}});else if($0.item.type==="tool_search_call"){let M0=_[$0.output_index],R1=$0.item.execution==="server";if(M0!=null){let f8=R1?M0.toolCallId:(a0=$0.item.call_id)!=null?a0:$0.item.id;if(R1)G0.push(f8);else Y0.enqueue({type:"tool-input-start",id:f8,toolName:M0.toolName});Y0.enqueue({type:"tool-input-end",id:f8}),Y0.enqueue({type:"tool-call",toolCallId:f8,toolName:M0.toolName,input:JSON.stringify({arguments:$0.item.arguments,call_id:R1?null:f8}),...R1?{providerExecuted:!0}:{},providerMetadata:{[U]:{itemId:$0.item.id}}})}_[$0.output_index]=void 0}else if($0.item.type==="tool_search_output"){let M0=(K1=(P1=$0.item.call_id)!=null?P1:G0.shift())!=null?K1:$0.item.id;Y0.enqueue({type:"tool-result",toolCallId:M0,toolName:H.toCustomToolName("tool_search"),result:{tools:$0.item.tools},providerMetadata:{[U]:{itemId:$0.item.id}}})}else if($0.item.type==="mcp_call"){_[$0.output_index]=void 0;let M0=(v0=$0.item.approval_request_id)!=null?v0:void 0,R1=M0!=null?(Q0=(l0=T.get(M0))!=null?l0:E[M0])!=null?Q0:$0.item.id:$0.item.id,f8=`mcp.${$0.item.name}`;Y0.enqueue({type:"tool-call",toolCallId:R1,toolName:f8,input:$0.item.arguments,providerExecuted:!0,dynamic:!0}),Y0.enqueue({type:"tool-result",toolCallId:R1,toolName:f8,result:{type:"call",serverLabel:$0.item.server_label,name:$0.item.name,arguments:$0.item.arguments,...$0.item.output!=null?{output:$0.item.output}:{},...$0.item.error!=null?{error:$0.item.error}:{}},providerMetadata:{[U]:{itemId:$0.item.id}}})}else if($0.item.type==="mcp_list_tools")_[$0.output_index]=void 0;else if($0.item.type==="apply_patch_call"){let M0=_[$0.output_index];if((M0==null?void 0:M0.applyPatch)&&!M0.applyPatch.endEmitted&&$0.item.operation.type!=="delete_file"){if(!M0.applyPatch.hasDiff)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:DA($0.item.operation.diff)});Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:'"}}'}),Y0.enqueue({type:"tool-input-end",id:M0.toolCallId}),M0.applyPatch.endEmitted=!0}if(M0&&$0.item.status==="completed")g=!0,Y0.enqueue({type:"tool-call",toolCallId:M0.toolCallId,toolName:H.toCustomToolName("apply_patch"),input:JSON.stringify({callId:$0.item.call_id,operation:$0.item.operation}),providerMetadata:{[U]:{itemId:$0.item.id}}});_[$0.output_index]=void 0}else if($0.item.type==="mcp_approval_request"){_[$0.output_index]=void 0;let M0=(i=(e=(w0=j.config).generateId)==null?void 0:e.call(w0))!=null?i:o8(),R1=(m0=$0.item.approval_request_id)!=null?m0:$0.item.id;T.set(R1,M0);let f8=`mcp.${$0.item.name}`;Y0.enqueue({type:"tool-call",toolCallId:M0,toolName:f8,input:$0.item.arguments,providerExecuted:!0,dynamic:!0}),Y0.enqueue({type:"tool-approval-request",approvalId:R1,toolCallId:M0})}else if($0.item.type==="local_shell_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:$0.item.action.command,timeoutMs:$0.item.action.timeout_ms,user:$0.item.action.user,workingDirectory:$0.item.action.working_directory,env:$0.item.action.env}}),providerMetadata:{[U]:{itemId:$0.item.id}}});else if($0.item.type==="shell_call")_[$0.output_index]=void 0,Y0.enqueue({type:"tool-call",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("shell"),input:JSON.stringify({action:{commands:$0.item.action.commands}}),...N&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:$0.item.id}}});else if($0.item.type==="shell_call_output")Y0.enqueue({type:"tool-result",toolCallId:$0.item.call_id,toolName:H.toCustomToolName("shell"),result:{output:$0.item.output.map((M0)=>({stdout:M0.stdout,stderr:M0.stderr,outcome:M0.outcome.type==="exit"?{type:"exit",exitCode:M0.outcome.exit_code}:{type:"timeout"}}))}});else if($0.item.type==="reasoning"){let M0=p({itemId:$0.item.id,outputIndex:$0.output_index}),R1=l[M0];if(R1!=null){let f8=Object.entries(R1.summaryParts).filter(([v,c])=>c==="active"||c==="can-conclude").map(([v])=>v);for(let v of f8)Y0.enqueue({type:"reasoning-end",id:`${M0}:${v}`,providerMetadata:{[U]:{itemId:M0,reasoningEncryptedContent:(I0=$0.item.encrypted_content)!=null?I0:null}}});delete l[M0]}n[$0.output_index]=void 0}else if($0.item.type==="compaction")Y0.enqueue({type:"custom",kind:"openai.compaction",providerMetadata:{[U]:{type:"compaction",itemId:$0.item.id,encryptedContent:$0.item.encrypted_content}}})}else if(fw4($0)){let M0=_[$0.output_index];if(M0!=null)if(M0.suppressInputStreaming)(t0=M0.bufferedInputDeltas)==null||t0.push($0.delta);else Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:$0.delta})}else if(yw4($0)){let M0=_[$0.output_index];if(M0!=null)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:$0.delta})}else if(lw4($0)){let M0=_[$0.output_index];if(M0==null?void 0:M0.applyPatch)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:DA($0.delta)}),M0.applyPatch.hasDiff=!0}else if(cw4($0)){let M0=_[$0.output_index];if((M0==null?void 0:M0.applyPatch)&&!M0.applyPatch.endEmitted){if(!M0.applyPatch.hasDiff)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:DA($0.diff)}),M0.applyPatch.hasDiff=!0;Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:'"}}'}),Y0.enqueue({type:"tool-input-end",id:M0.toolCallId}),M0.applyPatch.endEmitted=!0}}else if(gw4($0))Y0.enqueue({type:"tool-result",toolCallId:$0.item_id,toolName:H.toCustomToolName("image_generation"),result:{result:$0.partial_image_b64},preliminary:!0});else if(hw4($0)){let M0=_[$0.output_index];if(M0!=null)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:DA($0.delta)})}else if(uw4($0)){let M0=_[$0.output_index];if(M0!=null)Y0.enqueue({type:"tool-input-delta",id:M0.toolCallId,delta:'"}'}),Y0.enqueue({type:"tool-input-end",id:M0.toolCallId}),Y0.enqueue({type:"tool-call",toolCallId:M0.toolCallId,toolName:H.toCustomToolName("code_interpreter"),input:JSON.stringify({code:$0.code,containerId:M0.codeInterpreter.containerId}),providerExecuted:!0})}else if(xw4($0))x=$0.response.id,Y0.enqueue({type:"response-metadata",id:$0.response.id,timestamp:new Date($0.response.created_at*1000),modelId:$0.response.model});else if(kw4($0)){let M0=p({itemId:$0.item_id,outputIndex:$0.output_index});if(Y0.enqueue({type:"text-delta",id:M0,delta:$0.delta}),((I1=(f0=Z.providerOptions)==null?void 0:f0[U])==null?void 0:I1.logprobs)&&$0.logprobs)q.push($0.logprobs)}else if($0.type==="response.reasoning_summary_part.added"){let M0=p({itemId:$0.item_id,outputIndex:$0.output_index});if($0.summary_index>0){let R1=l[M0];if(R1!=null){R1.summaryParts[$0.summary_index]="active";for(let f8 of Object.keys(R1.summaryParts))if(R1.summaryParts[f8]==="can-conclude")Y0.enqueue({type:"reasoning-end",id:`${M0}:${f8}`,providerMetadata:{[U]:{itemId:M0}}}),R1.summaryParts[f8]="concluded";Y0.enqueue({type:"reasoning-start",id:`${M0}:${$0.summary_index}`,providerMetadata:{[U]:{itemId:M0,reasoningEncryptedContent:(H8=R1.encryptedContent)!=null?H8:null}}})}}}else if($0.type==="response.reasoning_summary_text.delta"){let M0=p({itemId:$0.item_id,outputIndex:$0.output_index});Y0.enqueue({type:"reasoning-delta",id:`${M0}:${$0.summary_index}`,delta:$0.delta,providerMetadata:{[U]:{itemId:M0}}})}else if($0.type==="response.reasoning_summary_part.done"){let M0=p({itemId:$0.item_id,outputIndex:$0.output_index}),R1=l[M0];if(R1!=null)if(F)Y0.enqueue({type:"reasoning-end",id:`${M0}:${$0.summary_index}`,providerMetadata:{[U]:{itemId:M0}}}),R1.summaryParts[$0.summary_index]="concluded";else R1.summaryParts[$0.summary_index]="can-conclude"}else if(bw4($0)){if(!H0)P={unified:Z30({finishReason:(B8=$0.response.incomplete_details)==null?void 0:B8.reason,hasFunctionCall:g}),raw:(Q8=(m4=$0.response.incomplete_details)==null?void 0:m4.reason)!=null?Q8:void 0};if(A=(D5=$0.response.usage)!=null?D5:void 0,typeof $0.response.service_tier==="string")F0=$0.response.service_tier;if(((x8=$0.response.reasoning)==null?void 0:x8.context)!=null)V0=$0.response.reasoning.context}else if(_G$($0)){let M0=(m6=$0.response.incomplete_details)==null?void 0:m6.reason;if(P={unified:M0?Z30({finishReason:M0,hasFunctionCall:g}):"error",raw:M0!=null?M0:"error"},A=(O9=$0.response.usage)!=null?O9:void 0,((o0=$0.response.reasoning)==null?void 0:o0.context)!=null)V0=$0.response.reasoning.context;if(!H0&&$0.response.error!=null){H0=!0;let R1={type:"response.failed",sequence_number:$0.sequence_number,response:{error:$0.response.error,incomplete_details:$0.response.incomplete_details,service_tier:$0.response.service_tier}};Y0.enqueue({type:"error",error:(D1=Ha(R1))!=null?D1:R1})}}else if(mw4($0)){if(V.push($0.annotation),$0.annotation.type==="url_citation")Y0.enqueue({type:"source",sourceType:"url",id:(Y$=(h1=(x$=j.config).generateId)==null?void 0:h1.call(x$))!=null?Y$:o8(),url:$0.annotation.url,title:$0.annotation.title});else if($0.annotation.type==="file_citation")Y0.enqueue({type:"source",sourceType:"document",id:(G4=(r6=(_8=j.config).generateId)==null?void 0:r6.call(_8))!=null?G4:o8(),mediaType:"text/plain",title:$0.annotation.filename,filename:$0.annotation.filename,providerMetadata:{[U]:{type:$0.annotation.type,fileId:$0.annotation.file_id,index:$0.annotation.index}}});else if($0.annotation.type==="container_file_citation")Y0.enqueue({type:"source",sourceType:"document",id:(n$=(T8=(a1=j.config).generateId)==null?void 0:T8.call(a1))!=null?n$:o8(),mediaType:"text/plain",title:$0.annotation.filename,filename:$0.annotation.filename,providerMetadata:{[U]:{type:$0.annotation.type,fileId:$0.annotation.file_id,containerId:$0.annotation.container_id}}});else if($0.annotation.type==="file_path")Y0.enqueue({type:"source",sourceType:"document",id:(ZQ=(Q9=(W$=j.config).generateId)==null?void 0:Q9.call(W$))!=null?ZQ:o8(),mediaType:"application/octet-stream",title:$0.annotation.file_id,filename:$0.annotation.file_id,providerMetadata:{[U]:{type:$0.annotation.type,fileId:$0.annotation.file_id,index:$0.annotation.index}}})}else if(bG$($0))H0=!0,P={unified:"error",raw:"error"},Y0.enqueue({type:"error",error:(OZ=Ha($0))!=null?OZ:$0})},flush(Z0){var Y0;for(let J0 of Object.values(_)){if(!(J0==null?void 0:J0.suppressInputStreaming))continue;Z0.enqueue({type:"tool-input-start",id:J0.toolCallId,toolName:J0.toolName});for(let c0 of(Y0=J0.bufferedInputDeltas)!=null?Y0:[])Z0.enqueue({type:"tool-input-delta",id:J0.toolCallId,delta:c0})}let o={[U]:{responseId:x,...q.length>0?{logprobs:q}:{},...F0!==void 0?{serviceTier:F0}:{},...V0!==void 0?{reasoningContext:V0}:{}}};Z0.enqueue({type:"finish",finishReason:P,usage:la0(A),providerMetadata:o})}})),request:{body:G},response:{headers:O}}}};fG$=W0(()=>r(y6.object({inputFileExpiresAfter:y6.number().int().min(3600).max(2592000).optional()})));ba0=W0(()=>r(W3$())),tw4=W0(()=>r(y6.object({custom_id:y6.string(),response:y6.object({status_code:y6.number(),request_id:y6.string().nullish(),body:y6.unknown()}).nullish(),error:y6.object({code:y6.string(),message:y6.string()}).nullish()}))),ow4=W0(()=>r(y6.object({data:y6.array(W3$()),has_more:y6.boolean(),last_id:y6.string().nullish()})));aw4=new Set(["openai.code_interpreter","openai.custom","openai.file_search","openai.web_search","openai.web_search_preview"]);Yj4=D6.strictObject({type:D6.string(),responseEvent:D6.string().optional()}).refine(($)=>$.type==="response.event"===($.responseEvent!==void 0),"responseEvent is required for response.event and forbidden for other event types."),Xj4=D6.strictObject({client:D6.strictObject({dataChannel:D6.strictObject({allowedClientEvents:D6.union([D6.literal("all"),D6.array(D6.string())]).optional(),allowedServerEvents:D6.union([D6.literal("all"),D6.array(Yj4)]).optional()})}).optional(),delegation:D6.strictObject({type:D6.literal("client")}).nullable().optional(),input:D6.array(D6.discriminatedUnion("role",[D6.strictObject({type:D6.literal("message"),role:D6.enum(["developer","user"]),content:D6.tuple([D6.strictObject({type:D6.literal("input_text"),text:D6.string()})])}),D6.strictObject({type:D6.literal("message"),role:D6.literal("assistant"),content:D6.tuple([D6.strictObject({type:D6.enum(["text","output_text"]),text:D6.string()})])})])).max(128).optional(),store:D6.boolean().optional(),voice:D6.strictObject({id:D6.string().min(1)}).optional()}),yG$=$W.union([$W.strictObject({type:$W.literal("audio/pcm"),rate:$W.union([$W.literal(16000),$W.literal(24000)])}),$W.strictObject({type:$W.enum(["audio/pcma","audio/pcmu"]),rate:$W.literal(8000)})]);$e0=v$.object({id:v$.string().min(1)}),Jj4=$e0.extend({delegation:v$.object({type:v$.enum(["client","responses"])}).nullish()}),gG$=v$.object({seconds:v$.number().nonnegative()}),hG$={delta:v$.string(),start_ms:v$.number().nonnegative(),end_ms:v$.number().nonnegative()},Q30={client_event_id:v$.string().nullish()},xa0={...Q30,start_ms:v$.number().nonnegative(),end_ms:v$.number().nonnegative()},K3$=v$.discriminatedUnion("type",[v$.object({type:v$.literal("session.started"),session:Jj4}),v$.object({type:v$.literal("session.closed"),session:$e0.nullish(),usage:gG$,reason:v$.string()}),v$.object({type:v$.literal("session.usage.updated"),usage:gG$,context_window:v$.object({usage_ratio:v$.number().min(0).max(1)}).nullish()}),v$.object({type:v$.literal("session.output_audio.delta"),delta:v$.string()}),v$.object({type:v$.literal("session.input_transcript.delta"),...hG$}),v$.object({type:v$.literal("session.output_transcript.delta"),...hG$}),v$.object({type:v$.literal("session.delegation.created"),offset_ms:v$.number().nonnegative().nullish(),delegation:v$.object({id:v$.string().min(1),target:v$.enum(["client","responses"]).nullish(),response_id:v$.string().min(1).nullish()})}),v$.object({type:v$.literal("session.updated"),session:$e0,...Q30}),v$.object({type:v$.literal("session.input_audio.muted"),...Q30}),v$.object({type:v$.literal("session.input_audio.unmuted"),...Q30}),v$.object({type:v$.literal("session.instructions.appended"),...xa0}),v$.object({type:v$.literal("session.thinking.appended"),...xa0}),v$.object({type:v$.literal("session.commentary.appended"),...xa0}),v$.object({type:v$.literal("error"),error:v$.object({message:v$.string(),code:v$.string().nullish(),client_event_id:v$.string().nullish()})})]),Gj4=new Set(K3$.options.map(($)=>$.shape.type.value)),Wj4=v$.object({type:v$.string()});Uj4=LA.object({session:LA.object({id:LA.string().min(1)}),transport:LA.object({type:LA.literal("webrtc"),sdp:LA.string().min(1)})});Dj4=["gpt-live-1"];jj4=W0(()=>r(fa0.object({instructions:fa0.string().nullish(),speed:fa0.number().min(0.25).max(4).default(1).nullish()}))),Ej4=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({text:Z,voice:Q="alloy",outputFormat:Y="mp3",speed:X,instructions:J,language:G,providerOptions:W}){let K=[],H=await I$({provider:"openai",providerOptions:W,schema:jj4}),F={model:this.modelId,input:Z,voice:Q,response_format:"mp3",speed:X,instructions:J};if(Y)if(["mp3","opus","aac","flac","wav","pcm"].includes(Y))F.response_format=Y;else K.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${Y}. Using mp3 instead.`});if(H){let U={};for(let N in U){let B=U[N];if(B!==void 0)F[N]=B}}if(G)K.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${G}" was ignored.`});return{requestBody:F,warnings:K}}async doGenerate(Z){var Q,Y,X,J,G;let W=(X=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?X:new Date,{requestBody:K,warnings:H}=await this.getArgs(Z),{value:F,responseHeaders:U,rawValue:N}=await o1({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:T1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),body:K,failedResponseHandler:R9,successfulResponseHandler:d7$(),abortSignal:Z.abortSignal,fetch:this.config.fetch});return{audio:F,warnings:H,request:{body:JSON.stringify(K)},response:{timestamp:W,modelId:this.modelId,headers:U,body:N}}}},zj4=W0(()=>r(n6.object({text:n6.string(),language:n6.string().nullish(),duration:n6.number().nullish(),words:n6.array(n6.object({word:n6.string(),start:n6.number(),end:n6.number()})).nullish(),segments:n6.array(n6.union([n6.object({id:n6.number(),seek:n6.number(),start:n6.number(),end:n6.number(),text:n6.string(),tokens:n6.array(n6.number()),temperature:n6.number(),avg_logprob:n6.number(),compression_ratio:n6.number(),no_speech_prob:n6.number()}),n6.object({type:n6.literal("transcript.text.segment"),id:n6.string(),start:n6.number(),end:n6.number(),text:n6.string(),speaker:n6.string()})])).nullish()}))),lG$=W0(()=>r(dZ.object({include:dZ.array(dZ.string()).optional(),language:dZ.string().optional(),prompt:dZ.string().optional(),temperature:dZ.number().min(0).max(1).default(0).optional(),timestampGranularities:dZ.array(dZ.enum(["word","segment"])).default(["segment"]).optional(),responseFormat:dZ.enum(["json","verbose_json","diarized_json"]).optional(),chunkingStrategy:dZ.union([dZ.literal("auto"),dZ.object({type:dZ.literal("server_vad"),threshold:dZ.number().min(0).max(1).optional(),prefixPaddingMs:dZ.number().int().min(0).optional(),silenceDurationMs:dZ.number().int().min(0).optional()})]).optional(),streaming:dZ.object({delay:dZ.enum(["minimal","low","medium","high","xhigh"]).optional(),include:dZ.array(dZ.string()).optional()}).optional()})));mG$={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},Pj4=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({audio:Z,mediaType:Q,providerOptions:Y}){var X,J;let G=[],W=await I$({provider:"openai",providerOptions:Y,schema:lG$}),K=new FormData,H=Z instanceof Uint8Array?new Blob([Z]):new Blob([_9(Z)]);K.append("model",this.modelId);let F=b7$(Q);if(K.append("file",new File([H],"audio",{type:Q}),`audio.${F}`),this.modelId==="whisper-1")K.append("response_format","verbose_json");let U=this.modelId==="gpt-4o-transcribe-diarize",N=(X=W==null?void 0:W.chunkingStrategy)!=null?X:U?"auto":void 0;if(W){let B=["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId),O={include:W.include,language:W.language,prompt:W.prompt,...this.modelId!=="whisper-1"&&{response_format:(J=W.responseFormat)!=null?J:U?"diarized_json":B?"json":"verbose_json"},temperature:W.temperature,timestamp_granularities:W.timestampGranularities};for(let[L,w]of Object.entries(O))if(w!=null)if(Array.isArray(w))for(let j of w)K.append(`${L}[]`,String(j));else K.append(L,String(w))}else if(U)K.append("response_format","diarized_json");if(N!=null)K.append("chunking_strategy",typeof N==="string"?N:JSON.stringify({type:N.type,...N.threshold!=null&&{threshold:N.threshold},...N.prefixPaddingMs!=null&&{prefix_padding_ms:N.prefixPaddingMs},...N.silenceDurationMs!=null&&{silence_duration_ms:N.silenceDurationMs}}));return{formData:K,warnings:G}}async doGenerate(Z){var Q,Y,X,J,G,W,K,H,F,U,N;if(cG$(this.modelId))throw new t1({functionality:`non-streaming transcription with ${this.modelId}`});let B=(X=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?X:new Date,{formData:O,warnings:L}=await this.getArgs(Z),{value:w,responseHeaders:j,rawValue:E}=await p3({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:T1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),formData:O,failedResponseHandler:R9,successfulResponseHandler:E1(zj4),abortSignal:Z.abortSignal,fetch:this.config.fetch}),z=w.language!=null&&w.language in mG$?mG$[w.language]:void 0,T=(W=w.segments)==null?void 0:W.flatMap((P)=>("speaker"in P)?[{text:P.text,startSecond:P.start,endSecond:P.end,speaker:P.speaker}]:[]);return{text:w.text,segments:(U=(F=(K=w.segments)==null?void 0:K.map((P)=>({text:P.text,startSecond:P.start,endSecond:P.end})))!=null?F:(H=w.words)==null?void 0:H.map((P)=>({text:P.word,startSecond:P.start,endSecond:P.end})))!=null?U:[],language:z,durationInSeconds:(N=w.duration)!=null?N:void 0,warnings:L,response:{timestamp:B,modelId:this.modelId,headers:j,body:E},...T!=null&&T.length>0&&{providerMetadata:{openai:{segments:T}}}}}async doStream(Z){var Q,Y,X,J,G,W,K;if(!cG$(this.modelId))throw new t1({functionality:`streaming transcription with ${this.modelId}`});let H=(X=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?X:new Date,F=await I$({provider:"openai",providerOptions:Z.providerOptions,schema:lG$}),U=[],N=(G=(J=Z.providerOptions)==null?void 0:J.openai)!=null?G:{};for(let L of["include","prompt","temperature","timestampGranularities"])if(N[L]!=null)U.push({type:"unsupported",feature:`providerOptions.openai.${L}`,details:`OpenAI streaming transcription does not support ${L}.`});let B=T1((K=(W=this.config).headers)==null?void 0:K.call(W),Z.headers),O=Tj4({modelId:this.modelId,inputAudioFormat:Z.inputAudioFormat,providerOptions:F});return{request:{body:O},response:{timestamp:H,modelId:this.modelId},stream:Aj4({webSocket:this.config.webSocket,url:kJ0(this.config.url({path:"/realtime?intent=transcription",modelId:this.modelId})),headers:B,sessionUpdate:O,language:F==null?void 0:F.language,warnings:U,audio:Z.audio,abortSignal:Z.abortSignal,includeRawChunks:Z.includeRawChunks})}}};Mj4=W0(()=>r(qj4.object({}))),Ij4=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[Q4](Z){return k4({modelId:Z.modelId,config:Z.config})}static[Y4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async doStream(Z){var Q,Y,X,J,G;if(Z.targetLanguage==null)throw new b8({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let W=(X=(Y=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:Y.call(Q))!=null?X:new Date;await I$({provider:"openai",providerOptions:Z.providerOptions,schema:Mj4});let K=[];if(Sj4(Z.inputAudioFormat),Z.sourceLanguage!=null)K.push({type:"unsupported",feature:"sourceLanguage",details:"The OpenAI Realtime translation API auto-detects the source language and does not accept a source language."});if(Z.outputAudioFormat!=null)K.push({type:"unsupported",feature:"outputAudioFormat",details:"The OpenAI Realtime translation API always outputs 24kHz 16-bit PCM audio and does not accept an output audio format."});let H=T1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),F=kj4({targetLanguage:Z.targetLanguage});return{request:{body:F},response:{timestamp:W,modelId:this.modelId},stream:Vj4({webSocket:this.config.webSocket,url:kJ0(this.config.url({path:`/realtime/translations?model=${encodeURIComponent(this.modelId)}`,modelId:this.modelId})),headers:H,sessionUpdate:F,warnings:K,audio:Z.audio,abortSignal:Z.abortSignal,includeRawChunks:Z.includeRawChunks})}}};_j4=W0(()=>r(vG.object({id:vG.string(),name:vG.string().nullish(),description:vG.string().nullish(),default_version:vG.string().nullish(),latest_version:vG.string().nullish(),created_at:vG.number(),updated_at:vG.number().nullish()}))),Kl5=W0(()=>r(vG.object({id:vG.string(),version:vG.string().nullish(),name:vG.string().nullish(),description:vG.string().nullish()})));Hl5=wA()});function fj4($){return UF("LLMAPI listModels",`${F3$}/models`,{headers:$?{Authorization:`Bearer ${$}`}:{},signal:AbortSignal.timeout(15000)})}var F3$="https://api.llmapi.ai/v1",xj4="https://llmapi.ai/wp-content/uploads/2026/01/Frame-2085662993.png",U3$;var N3$=D(()=>{X30();hP();U3$={info:{id:"llmapi",name:"LLMAPI",description:"One API key, 400+ models across every provider",logo:xj4},supportedMethods:["api-key"],create($){let Z=wA({apiKey:$||"not-needed",baseURL:F3$,name:"llmapi"}),Q=Object.assign((...Y)=>Z.chat(...Y),Z,{languageModel:Z.chat});return{info:this.info,aiSdk:Q,async listModels(){let Y=await fj4($);if(!Y.ok)await FY("LLMAPI listModels",Y);let{data:X}=await GJ0("LLMAPI listModels",Y);return X.map((J)=>{let G=J.architecture??{},W=!!J.reasoning_levels?.length||!!J.providers?.some((K)=>K.reasoning);return{providerId:"llmapi",modelId:J.id,title:J.name||J.id,description:J.description??null,logo:null,capabilities:WJ0(G.input_modalities??[],G.output_modalities??[],J.supported_parameters,W?["reasoning"]:[]),limits:{contextWindow:J.context_length??0,maxOutputTokens:null},costs:{input:Number(J.pricing?.prompt)||0,output:Number(J.pricing?.completion)||0}}})}}}}});function yj4($,Z){return UF("OpenAI-compatible listModels",`${$}/models`,{headers:Z,signal:AbortSignal.timeout(15000)})}function gj4($){let Z=JSON.parse($);if(!Z.baseUrl||typeof Z.baseUrl!=="string")throw Error("Invalid OpenAI-compatible credential: missing baseUrl field");let Q=Z.baseUrl.replace(/\/+$/,"");if(!Q.endsWith("/v1"))Q+="/v1";return{baseUrl:Q,apiKey:Z.apiKey??""}}var hj4="https://assets.decocache.com/decocms/d138aa7e-5b8c-4821-9e64-6aff40df2cdc/ChatGPT_logo.svg",B3$;var O3$=D(()=>{X30();hP();B3$={info:{id:"openai-compatible",name:"OpenAI Compatible",description:"Custom OpenAI-compatible endpoint",logo:hj4},supportedMethods:["api-key"],create($){let{baseUrl:Z,apiKey:Q}=gj4($),Y=wA({baseURL:Z,apiKey:Q||"not-needed",name:"openai-compatible"}),X=Object.assign((...J)=>Y.chat(...J),Y,{languageModel:Y.chat});return{info:this.info,aiSdk:X,async listModels(){let J={};if(Q)J.Authorization=`Bearer ${Q}`;let G=await yj4(Z,J);if(!G.ok)await FY("OpenAI-compatible listModels",G);let W=await G.text(),K;try{K=JSON.parse(W)}catch{throw Error(`OpenAI-compatible listModels returned malformed JSON: ${W.slice(0,200)}`)}return K.data.map((H)=>({providerId:"openai-compatible",modelId:H.id,title:H.id,description:H.owned_by?`Owned by ${H.owned_by}`:null,logo:null,capabilities:[],limits:null,costs:null}))}}}}});function q9(){return{...E0().aiGatewayEnabled&&{deco:cL},anthropic:KJ$,google:KG$,openrouter:KJ0,llmapi:U3$,"openai-compatible":B3$}}var ZW=D(()=>{HJ$();HG$();N3$();O3$();Po0();su();F$()});function cj4($,Z,Q){EJ0($,Z,Q)}function mj4($,Z,Q){zJ0($,Z,Q)}function Je0($){Ua.delete($)}async function Ge0($,Z){if(!E0().plansEnabled)return null;if(!E0().aiGatewayEnabled)return null;let Q=Ua.get(Z);if(Q&&Date.now()-Q.at<L3$)return Q.value;let Y=Xe0.get(Z);if(Y)return Y;let X=dj4($,Z,Q).finally(()=>{Xe0.delete(Z)});return Xe0.set(Z,X),X}async function dj4($,Z,Q){let Y=q9().deco;if(!Y?.getEntitlements)return null;let X=$.auth.user?.id??$.auth.apiKey?.userId;if(!X)return D3$(Z,Q);try{let J=await NQ(X),{features:G,usage:W,modelPins:K,credits:H}=await Y.getEntitlements(J,Z);if(!G||typeof G!=="object")throw new uP(502);let F={features:G,modelPins:K,usageState:W?.state??null,creditsUsd:H?.remainingUsd??null};return cj4(Ua,Z,F),mj4(Ua,lj4,L3$),F}catch(J){let G=J instanceof uP&&J.isDefinitive,W=J instanceof uP&&J.isDormant,K={organizationId:Z,servedStale:!!Q,status:J instanceof uP?J.status:null,error:J instanceof Error?J.message:String(J)};if(W);else if(G)console.error("[Plans] entitlements REFUSED by the gateway \u2014 gates fail OPEN for every org until this is fixed (check STUDIO_JWT_SECRET and STUDIO_PROVISION_SECRET_KEY against the gateway's MESH_JWT_SECRET and STUDIO_PROVISION_KEY)",K);else console.warn("[Plans] entitlements lookup failed (gateway unreachable) \u2014 gates fail OPEN",K);return D3$(Z,Q)}}function D3$($,Z){if(Z&&Date.now()-Z.at>=uj4)return Ua.delete($),null;return Z?.value??null}async function QW($,Z,Q){let Y=await Ge0($,Z);return w3$(Y?.features??null,Q)}function w3$($,Z){if(!$)return!0;return $[Z]===!0}function ij4($,Z){if($!=="exhausted")return!1;return!(Z!==null&&Z>0)}async function hK($,Z,Q){let Y=await Ge0($,Z);if(!ij4(Y?.usageState??null,Y?.creditsUsd??null))return;throw new J30(`${Q} is paused: this organization has used its monthly AI allowance`)}async function j3$($,Z,Q){let Y=await Ge0($,Z);if(!Y)return null;if(w3$(Y.features,"model_choice"))return null;return Y.modelPins?.[Q]??null}var yF,L3$=60000,uj4=600000,Ua,lj4=1e4,Xe0,J30;var gF=D(()=>{BK();ZW();su();GK();F$();yF=class yF extends y7{feature;code="feature_not_in_plan";constructor($,Z){super($);this.feature=Z;this.name="FeatureNotInPlanError"}};Ua=new Map;Xe0=new Map;J30=class J30 extends y7{code="ai_budget_exhausted";constructor($){super($);this.name="AiBudgetExhaustedError"}}});function E3$($){let{ctx:Z,toolName:Q,organizationId:Y,durationMs:X,isError:J}=$,G={"tool.name":Q,"organization.id":Y,status:J?"error":"success"};Z.meter.createHistogram("studio_tool.execution.duration",{description:"Duration of in-process Studio tool executions in milliseconds",unit:"ms"}).record(X,G),Z.meter.createCounter("studio_tool.execution.count",{description:"Number of in-process Studio tool executions"}).add(1,G)}import{SpanStatusCode as z3$}from"@opentelemetry/api";function d($){return{...$,execute:async(Z,Q)=>{let Y=performance.now(),X=!1;return await Q.timings.measure(`tool.${$.name}`,async()=>Q.tracer.startActiveSpan(`tool.${$.name}`,{attributes:{"tool.name":$.name,"organization.id":Q.organization?.id??"system","user.id":Q.auth.user?.id??Q.auth.apiKey?.userId??"anonymous"}},async(J)=>{try{Q.toolName=$.name,Q.access.setToolName?.($.name);let G=Q.organization?.id;if(G&&!o9$($.name)&&await AJ0(Q.db,G))throw new Cr(`This organization is blocked: ${$.name} is unavailable until the block is resolved`);if(($.requiresFeature||$.requiresAiBudget)&&!G)console.warn(`[Plans] ${$.name} declares a plan gate but no organization is in scope \u2014 running UNGATED`);if($.requiresFeature&&G&&!await QW(Q,G,$.requiresFeature))throw new yF(`${$.name} needs the ${$.requiresFeature} feature, which this organization's plan does not include`,$.requiresFeature);if($.requiresAiBudget&&G)await hK(Q,G,$.name);let W=await $.handler(Z,Q);return J.setStatus({code:z3$.OK}),W}catch(G){throw X=!0,J.setStatus({code:z3$.ERROR,message:G.message}),J.recordException(G),G}finally{E3$({ctx:Q,toolName:$.name,organizationId:Q.organization?.id??"system",durationMs:performance.now()-Y,isError:X}),J.end()}}))}}}var C0=D(()=>{mP();gF()});function K0($){if(!$.organization)throw Error("This operation requires organization scope");return $.organization}function p0($){return $.auth.user?.id??$.auth.apiKey?.userId}function jA($){return!!($.auth.user||$.auth.apiKey)}function a($){if(!jA($))throw Error("Authentication required")}import{z as J4}from"zod";var A3$,P3$=1000,pj4=500,T3$,R3$,q3$,M3$,I3$,V3$,k3$,S3$,C3$,_3$;var il=D(()=>{A3$=J4.record(J4.string(),J4.array(J4.string())),T3$=J4.record(J4.string(),J4.array(J4.string()).max(pj4)).refine(($)=>Object.keys($).length<=P3$,{message:`Permissions cannot grant more than ${P3$} resources`}),R3$=J4.object({id:J4.string().describe("Unique identifier for the API key"),name:J4.string().describe("Human-readable name for the API key"),userId:J4.string().describe("ID of the user who owns this API key"),permissions:A3$.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Example: { "self": ["API_KEY_CREATE"], "conn_abc123": ["SEND_MESSAGE"] }'),expiresAt:J4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:J4.string().datetime().describe("When the API key was created (ISO 8601)")}),q3$=J4.object({name:J4.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:T3$.describe(`Permissions to grant (REQUIRED \u2014 there is no implicit default). Format: { resource: [actions] }. Resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names (e.g., ["ORGANIZATION_GET"]) or ["*"] for all. Example: { "self": ["ORGANIZATION_GET", "COLLECTION_CONNECTIONS_LIST"] }. The key is authorized solely by this allowlist; the creator's role does not widen it.`),expiresIn:J4.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:J4.record(J4.string(),J4.unknown()).optional().describe("Additional metadata to store with the API key")}),M3$=J4.object({id:J4.string().describe("Unique identifier for the API key"),name:J4.string().describe("Human-readable name for the API key"),key:J4.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:A3$.describe('Permissions granted to this API key. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools'),expiresAt:J4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:J4.string().datetime().describe("When the API key was created (ISO 8601)")}),I3$=J4.object({}),V3$=J4.object({items:J4.array(R3$).describe("List of API keys (without key values)")}),k3$=J4.object({keyId:J4.string().describe("ID of the API key to update"),name:J4.string().min(1).max(64).optional().describe("New name for the API key"),permissions:T3$.optional().describe('New permissions. Format: { resource: [actions] } where resource is "self" for management tools or "conn_<UUID>" for connection-specific tools. Actions are tool names or "*" for all. Example: { "self": ["API_KEY_CREATE"] }. Replaces existing permissions.'),metadata:J4.record(J4.string(),J4.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),S3$=J4.object({item:R3$.describe("The updated API key (without key value)")}),C3$=J4.object({keyId:J4.string().describe("ID of the API key to delete")}),_3$=J4.object({success:J4.boolean().describe("Whether the deletion was successful"),keyId:J4.string().describe("ID of the deleted API key")})});var We0;var v3$=D(()=>{U6();C0();il();We0=d({name:"API_KEY_CREATE",description:"Create an API key with scoped permissions. The key value is returned only once \u2014 store it immediately.",annotations:{title:"Create API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:q3$,outputSchema:M3$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=await Z.boundAuth.apiKey.create({name:$.name,permissions:$.permissions,expiresIn:$.expiresIn,metadata:{...$.metadata,organization:Z.organization}}),Y=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,X=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,J=p0(Z);if(J)v1.capture({distinctId:J,event:"api_key_created",...Z.organization?.id?{groups:{organization:Z.organization.id}}:{},properties:{key_id:Q.id,key_name:Q.name??$.name,organization_id:Z.organization?.id,has_expiry:!!Y}});return{id:Q.id,name:Q.name??$.name,key:Q.key,permissions:Q.permissions??{},expiresAt:Y,createdAt:X}}})});var Ke0;var b3$=D(()=>{U6();C0();il();Ke0=d({name:"API_KEY_DELETE",description:"Delete and instantly revoke an API key. Cannot be undone.",annotations:{title:"Delete API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:C3$,outputSchema:_3$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=p0(Z);if(!Q)throw Error("User ID required to delete API key");let X=(await Z.boundAuth.apiKey.list())?.find((K)=>K.id===$.keyId);if(!X)throw Error("API key not found");let G=X.metadata?.organization?.id,W=Z.organization?.id;if(G!==W)throw Error("Cannot delete API key from another organization");if(await Z.boundAuth.apiKey.delete($.keyId),W)v1.capture({distinctId:Q,event:"api_key_deleted",groups:{organization:W},properties:{key_id:$.keyId,organization_id:W}});return{success:!0,keyId:$.keyId}}})});var He0;var x3$=D(()=>{C0();il();He0=d({name:"API_KEY_LIST",description:"List API keys for the current user in the current organization. Returns metadata only \u2014 key values are never shown after creation.",annotations:{title:"List API Keys",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:I3$,outputSchema:V3$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=await Z.boundAuth.apiKey.list(),Y=Z.organization?.id;return{items:(Q??[]).filter((J)=>{return J.metadata?.organization?.id===Y}).map((J)=>({id:J.id,name:J.name??"Unnamed Key",userId:J.userId,permissions:J.permissions??{},expiresAt:J.expiresAt?J.expiresAt instanceof Date?J.expiresAt.toISOString():J.expiresAt:null,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}))}}})});var Fe0;var f3$=D(()=>{C0();il();Fe0=d({name:"API_KEY_UPDATE",description:"Update an API key's name, permissions, or metadata. The key value cannot be changed or retrieved.",annotations:{title:"Update API Key",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:k3$,outputSchema:S3$,handler:async($,Z)=>{if(a(Z),await Z.access.check(),!p0(Z))throw Error("User ID required to update API key");let X=(await Z.boundAuth.apiKey.list())?.find((H)=>H.id===$.keyId);if(!X)throw Error(`API key not found: ${$.keyId}`);let G=X.metadata?.organization?.id,W=Z.organization?.id;if(G!==W)throw Error("Cannot update API key from another organization");let K=await Z.boundAuth.apiKey.update({keyId:$.keyId,name:$.name,permissions:$.permissions,metadata:{...$.metadata,organization:Z.organization}});if(!K)throw Error(`Failed to update API key: ${$.keyId}`);return{item:{id:K.id,name:K.name??$.name??"Unnamed Key",userId:K.userId,permissions:K.permissions??{},expiresAt:K.expiresAt?K.expiresAt instanceof Date?K.expiresAt.toISOString():K.expiresAt:null,createdAt:K.createdAt instanceof Date?K.createdAt.toISOString():K.createdAt}}}})});var y3$=D(()=>{v3$();b3$();x3$();f3$();il()});function Lw($){let Z=$.trim();if(!Z)return{ok:!1,error:"Enter a website URL."};let Q=tj4.test(Z),Y=oj4.test(Z),X=rj4.test(Z);if(Q&&!Y&&!X)return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let J=Y?Z:`https://${Z}`,G;try{G=new URL(J)}catch{return{ok:!1,error:"Enter a valid website URL."}}if(G.protocol!=="http:"&&G.protocol!=="https:")return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let W=G.hostname.split(".");if(W.length<2||W.some((K)=>!K||!sj4.test(K)))return{ok:!1,error:"Enter a valid website URL."};return G.protocol="https:",{ok:!0,value:G.origin}}var tj4,oj4,rj4,sj4;var Na=D(()=>{tj4=/^[a-zA-Z][a-zA-Z\d+.-]*:/,oj4=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//,rj4=/^[^\s/:?#]+\.[^\s/:?#]+:\d+(?:[/?#]|$)/,sj4=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i});import{z as BJ}from"zod";function G30($){return{repository_id:$.repositoryId,provider:$.provider,host:$.host,path:$.path,default_branch:$.defaultBranch??null,web_url:$.webUrl??null}}function g3$($){let Z=aj4.safeParse($);if(!Z.success)return null;return{repositoryId:Z.data.repository_id,provider:Z.data.provider,host:Z.data.host,path:Z.data.path,defaultBranch:Z.data.default_branch??null,webUrl:Z.data.web_url??null}}function W30($){return $.provider==="github"&&$.host.toLowerCase()==="github.com"?$.path:null}var Ue0,aj4;var K30=D(()=>{Ue0=BJ.object({repositoryId:BJ.string().min(1),provider:BJ.enum(["github","gitlab","bitbucket"]),host:BJ.string().min(1),path:BJ.string().min(1),defaultBranch:BJ.string().nullable().optional(),webUrl:BJ.string().nullable().optional()}),aj4=BJ.object({repository_id:BJ.string().min(1),provider:BJ.enum(["github","gitlab","bitbucket"]),host:BJ.string().min(1),path:BJ.string().min(1),default_branch:BJ.string().nullable().optional(),web_url:BJ.string().nullable().optional()})});import{z as wX}from"zod";function uK($){if($.baseUrl)return $.baseUrl.replace(/\/+$/,"");return(($.settings??E0()).reportsInternalApiUrl??ej4).replace(/\/+$/,"")}function u3$($={}){return`${uK($)}/api/v2/mcp`}function EA($){let Z=$.apiKey??($.settings??E0()).reportsInternalApiKey;if(!Z)throw Error("REPORTS_INTERNAL_API_KEY (or the legacy COMMERCE_DISCOVERY_INTERNAL_API_KEY) is required to set up reports.");return Z}function F30($){return new URL($).hostname}function ZE4($){return $==="ownership_unverified"||$==="already_claimed_by_other_org"}function QE4($,Z={}){switch($){case"ownership_unverified":{let Q=Z.email?`O e-mail ${Z.email}`:"Este e-mail",Y=Z.domain?` ${Z.domain}`:" este site";return`${Q} n\xE3o tem permiss\xE3o para reivindicar${Y}. Use um e-mail do dom\xEDnio do site ou pe\xE7a ao suporte para autorizar seu dom\xEDnio.`}case"already_claimed_by_other_org":return"Este site j\xE1 pertence a outra organiza\xE7\xE3o. Fale com o suporte para transferir o acesso.";case"unknown":return"N\xE3o foi poss\xEDvel configurar o Reports. Tente novamente ou fale com o suporte.";default:return $}}async function YE4($){let Z=await Ba($);return ZE4(Z?.error)?Z.error:"unknown"}async function Ba($){let Z=await $.text().catch(()=>"");if(!Z)return;try{return JSON.parse(Z)}catch{return}}async function U30($){let Z=`Reports auth failed with status ${$.status}.`,Q=await $.text().catch(()=>"");if(!Q)return Z;try{let Y=JSON.parse(Q),X=typeof Y.error==="string"?Y.error:typeof Y.message==="string"?Y.message:null;return X?`Reports auth failed: ${X}.`:Z}catch{return Z}}async function c3$($,Z={}){let Q=uK(Z),Y=EA(Z),X=Z.fetchImpl??fetch,J=F30($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/upgrade`,W=await X(G,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.orgName?{name:$.orgName}:{},...$.email?{email:$.email}:{},...$.reportUrl?{report_url:$.reportUrl}:{}}),signal:AbortSignal.timeout(H30)});if(!W.ok){let H=await YE4(W);throw new l3$(H,{email:$.email,domain:J})}let K=$E4.safeParse(await Ba(W));if(!K.success)throw Error("Reports auth response did not include a token.");return{authorizationToken:K.data.token}}async function m3$($,Z={}){let Q=uK(Z),Y=EA(Z),X=Z.fetchImpl??fetch,J=F30($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/bindings`,W=await X(G,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,provider:$.provider,resource_id:$.resourceId}),signal:AbortSignal.timeout(H30)});if(W.status===409)return{ok:!1,reason:"resource_already_bound",detail:"Este recurso j\xE1 est\xE1 vinculado a outra loja. Se ele \xE9 seu, fale com o suporte para revis\xE3o manual."};if(W.status===422){let H=h3$.safeParse(await Ba(W));return{ok:!1,reason:H.success?H.data.reason??"verification_failed":"verification_failed",detail:(H.success?H.data.detail:void 0)??"N\xE3o foi poss\xEDvel verificar o acesso a este recurso."}}if(!W.ok)throw Error(await U30(W));let K=h3$.safeParse(await Ba(W));if(!K.success||!K.data.binding)throw Error("Reports bind response did not include a binding.");return{ok:!0,resourceId:K.data.binding.resource_id,evidence:K.data.binding.evidence}}async function d3$($,Z={}){let Q=uK(Z),Y=EA(Z),X=Z.fetchImpl??fetch,J=F30($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/run`,W=await X(G,{method:"POST",headers:{Authorization:`Bearer ${Y}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.repository?{repository:G30($.repository)}:{},...$.githubRepo?{github_repo:$.githubRepo}:{}}),signal:AbortSignal.timeout(H30)});if(W.status===409)return{triggered:!1,reason:"not_upgraded"};if(!W.ok)throw Error(await U30(W));return{triggered:!0}}async function XE4($,Z,Q){try{return await g8(async()=>{let Y=await $(Z,{method:"GET",headers:{Authorization:`Bearer ${Q}`},signal:AbortSignal.timeout(H30)});if(Y.status>=500||Y.status===429)throw new Ne0(await U30(Y));return Y},{maxAttempts:3,minTimeout:200,maxTimeout:2000,multiplier:2,jitter:1,isRetriable:(Y)=>Y instanceof Ne0})}catch(Y){if(Y instanceof i5&&Y.cause instanceof Error)throw Y.cause;throw Y}}async function i3$($,Z={}){let Q=uK(Z),Y=EA(Z),X=Z.fetchImpl??fetch,J=F30($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/connections/status?org_id=${encodeURIComponent($.orgId)}`,W=await XE4(X,G,Y);if(W.status===404||W.status===409)return{providers:{},claimed:!1};if(!W.ok)throw Error(await U30(W));let K=JE4.safeParse(await Ba(W));return{providers:K.success?K.data.providers:{},claimed:!0}}var ej4,H30=15000,$E4,h3$,l3$,Ne0,JE4;var ww=D(()=>{e8();D8();K30();F$();ej4=new URL(Vm1).origin,$E4=wX.object({token:wX.string().min(1)}),h3$=wX.object({binding:wX.object({resource_id:wX.string(),evidence:wX.string()}).optional(),reason:wX.string().optional(),detail:wX.string().optional()});l3$=class l3$ extends Error{code;constructor($,Z={}){super(QE4($,Z));this.name="ReportsClaimError",this.code=$}};Ne0=class Ne0 extends Error{};JE4=wX.object({providers:wX.record(wX.string(),wX.object({connected:wX.boolean(),via:wX.enum(["oauth","sa"]).nullable(),resource:wX.string().nullable()}))})});import{z as bG}from"zod";var GE4,WE4,Be0;var p3$=D(()=>{Na();C0();ww();GE4=bG.object({siteUrl:bG.string().min(1).describe("Website URL of the store being bound."),provider:bG.enum(["ga4","gsc"]).describe("Which Google source to bind: ga4 (Analytics) or gsc (Search Console)."),resourceId:bG.string().min(1).describe("The resource id the client typed: GA4 numeric property id, or GSC site (sc-domain:example.com or https://example.com/).")}),WE4=bG.discriminatedUnion("ok",[bG.object({ok:bG.literal(!0),resourceId:bG.string(),evidence:bG.string()}),bG.object({ok:bG.literal(!1),reason:bG.string(),detail:bG.string()})]),Be0=d({name:"REPORTS_BIND",description:"Bind a GA4 property or GSC site to the org's store via the shared service account (consent-free lane). The client grants deco-reader@\u2026 access to the resource and provides its id; Deco Score verifies the resource belongs to this domain before persisting. Returns ok:false with an actionable pt-BR detail when verification fails or the resource is already bound elsewhere.",annotations:{title:"Bind Deco Score Data Source",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:GE4,outputSchema:WE4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check("REPORTS_BIND","COMMERCE_DISCOVERY_BIND");let Y=Lw($.siteUrl);if(!Y.ok)throw Error(Y.error);return m3$({siteUrl:Y.value,orgId:Q.id,provider:$.provider,resourceId:$.resourceId.trim()})}})});import{z as hF}from"zod";var KE4,HE4,Oe0;var n3$=D(()=>{Na();C0();ww();KE4=hF.object({siteUrl:hF.string().min(1).describe("Website URL of the store to inspect.")}),HE4=hF.object({providers:hF.record(hF.string(),hF.object({connected:hF.boolean(),via:hF.enum(["oauth","sa"]).nullable(),resource:hF.string().nullable()})),claimed:hF.boolean().describe("False when the site isn't claimed/upgraded for this org \u2014 providers is then empty because the status is unreadable, NOT because nothing is connected. The UI must warn instead of rendering existing bindings as disconnected.")}),Oe0=d({name:"REPORTS_CONNECTION_STATUS",description:"Read per-provider connection status (ga4/gsc/vtex) for the org's store \u2014 { connected, via: oauth|sa, resource }. The single source of truth for whether a data source is connected, unifying the OAuth (Studio vault) and shared-SA binding lanes. Read-only.",annotations:{title:"Deco Score Connection Status",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:KE4,outputSchema:HE4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check("REPORTS_CONNECTION_STATUS","COMMERCE_DISCOVERY_CONNECTION_STATUS");let Y=Lw($.siteUrl);if(!Y.ok)throw Error(Y.error);return i3$({siteUrl:Y.value,orgId:Q.id})}})});import{z as jw}from"zod";function BE4($){let Z=NE4.safeParse($),Q=Z.success?Z.data:void 0,Y=(Q?g3$(Q.repository):void 0)??void 0,X=Q&&typeof Q.github_repo==="string"&&Q.github_repo.length>0?Q.github_repo:void 0;return{repository:Y??void 0,githubRepo:(Y?W30(Y):X)??void 0}}var FE4,UE4,NE4,De0;var t3$=D(()=>{e8();K30();Na();C0();ww();FE4=jw.object({siteUrl:jw.string().min(1).describe("Website URL to run the diagnostic for.")}),UE4=jw.object({triggered:jw.boolean(),reason:jw.string().optional()}),NE4=jw.object({repository:jw.unknown().optional(),github_repo:jw.string().optional()}).passthrough().nullable().optional();De0=d({name:"REPORTS_RUN",description:"Trigger the Deco Score run for the current organization's store. Call once the data sources (GA4/GSC/VTEX) are connected \u2014 this run resolves credentials and produces the enriched Deco Score.",annotations:{title:"Run Deco Score",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:FE4,outputSchema:UE4,requiresFeature:"diagnostic_enriched",requiresAiBudget:!0,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check("REPORTS_RUN","COMMERCE_DISCOVERY_RUN");let Y=Lw($.siteUrl);if(!Y.ok)throw Error(Y.error);let X=y4.REPORTS(Q.id),J=await Z.storage.connections.findById(X,Q.id),{repository:G,githubRepo:W}=BE4(J?.configuration_state);return d3$({siteUrl:Y.value,orgId:Q.id,repository:G,githubRepo:W})}})});import{z as H5}from"zod";var OE4,Oa,DE4,LE4,wE4,jE4,o3$,r3$,Da,N30;var s3$=D(()=>{OE4=["github","gitlab","bitbucket"],Oa=H5.enum(OE4),DE4=["github_app","oauth","token","github_cli"],LE4=H5.enum(DE4),wE4=["active","revoked"],jE4=H5.enum(wE4),o3$=H5.object({provider:Oa,host:H5.string().min(1).describe("Provider host, e.g. github.com"),path:H5.string().min(1).describe("Full namespace path, e.g. owner/name or group/sub/project")}),r3$=H5.object({id:H5.string(),organizationId:H5.string(),type:Oa,host:H5.string(),authKind:LE4,externalAccountId:H5.string().describe("Provider-side account identity: installation id (GitHub App), user/group id (GitLab) or user/workspace uuid (Bitbucket)."),login:H5.string().describe("Display login of the account/namespace"),avatarUrl:H5.string().nullable(),installationId:H5.number().nullable().describe("GitHub App installation id; null for other auth kinds."),status:jE4,createdAt:H5.string(),updatedAt:H5.string()}),Da=H5.string().regex(/^[a-z][a-z0-9-]{0,31}$/,"lowercase letters, digits and dashes only"),N30=H5.object({id:H5.string(),organizationId:H5.string(),accountId:H5.string().nullable().describe("Credential-holding account; null for anonymous public clones."),provider:Oa,host:H5.string(),path:H5.string(),externalId:H5.string().nullable().describe("Provider repository/project id, when known."),defaultBranch:H5.string().nullable(),webUrl:H5.string(),visibility:H5.enum(["public","private","internal"]).nullable(),sandboxImage:Da.describe("Sandbox image this repository's sandboxes boot from."),createdAt:H5.string(),updatedAt:H5.string()})});function PE4($){let Z=$.toLowerCase();if(Z==="github.com"||Z==="www.github.com")return"github";if(Z==="gitlab.com"||Z==="www.gitlab.com")return"gitlab";if(Z==="bitbucket.org"||Z==="www.bitbucket.org")return"bitbucket";if(/(^|[.-])gitlab([.-]|$)/.test(Z))return"gitlab";return null}function a3$($){let Z=$.toLowerCase();return Z.startsWith("www.")?Z.slice(4):Z}function lK($,Z){let Q=$.trim();if(!Q)return null;let Y,X,J=/^(?:[\w.-]+@)?([\w.-]+(?::\d+)?):(?!\/\/)(.+)$/.exec(Q);if(J&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(Q))Y=J[1],X=J[2];else if(/^[a-z][a-z0-9+.-]*:\/\//i.test(Q)){let F;try{F=new URL(Q)}catch{return null}if(!/^(https?|ssh|git)(\+ssh)?:$/.test(F.protocol))return null;Y=F.host,X=F.pathname}else if(Z?.provider)Y=Z.host??B30[Z.provider],X=Q;else return null;Y=a3$(Y);let G=Z?.provider??PE4(Y);if(!G)return null;let W=X.split("/").map((F)=>F.trim()).filter(Boolean),K=W.indexOf("-");if(K>=0)W=W.slice(0,K);if(zE4.has(G))W=W.slice(0,2);if(W.length<2)return null;let H=W[W.length-1];if(W[W.length-1]=H.replace(/\.git$/i,""),W.some((F)=>F.length===0||F==="."||F===".."))return null;return{provider:G,host:Y,path:W.join("/")}}function cK($){return`${$.host.toLowerCase()}/${$.path.toLowerCase()}`}function Le0($){let Z=$.path.split("/");return Z[Z.length-1]??$.path}function AE4($){let Z=$.path.lastIndexOf("/");return Z<0?"":$.path.slice(0,Z)}function h5($){return{owner:AE4($),name:Le0($)}}function OJ($){return`https://${$.host}/${$.path}`}function we0($,Z){let Q=`${$.host}/${$.path}.git`;if(!Z)return`https://${Q}`;return`https://${EE4[$.provider]}:${encodeURIComponent(Z)}@${Q}`}function wB($,Z){let Q=a3$(Z);switch($){case"github":return Q==="github.com"?"https://api.github.com":`https://${Q}/api/v3`;case"gitlab":return`https://${Q}/api/v4`;case"bitbucket":return"https://api.bitbucket.org/2.0"}}function jB($,Z){return{provider:"github",host:B30.github,path:`${$}/${Z}`}}var B30,EE4,zE4;var je0=D(()=>{B30={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"},EE4={github:"x-access-token",gitlab:"oauth2",bitbucket:"x-token-auth"},zE4=new Set(["github","bitbucket"])});function YW($,Z){return`${OJ($)}/${TE4[$.provider]}/${Z}`}function qE4($){let Z=$.toLowerCase();return RE4[Z]??Z}function ZW$($,Z){let Q=Number($[3]);if(!Number.isSafeInteger(Q)||Q<=0)return null;let Y=qE4($[1]),X=$[2],J=Z?decodeURIComponent(X):X;if(/^\d+$/.test(J))return null;let G=lK(`https://${Y}/${J}`);if(!G)return null;return{repo:G,number:Q,url:YW(G,Q)}}function QW$($){let Z=$.trim();if(!Z)return null;for(let{re:Q,api:Y}of $W$){let X=Q.exec(Z),J=X?ZW$(X,Y===!0):null;if(J)return J}return null}function Ee0($){let Z=$.length>e3$?$.slice(0,e3$):$;for(let{re:Q,api:Y}of $W$){let X=Q.exec(Z),J=X?ZW$(X,Y===!0):null;if(J)return J}return null}var TE4,$W$,RE4,e3$=200000;var ze0=D(()=>{je0();TE4={github:"pull",gitlab:"-/merge_requests",bitbucket:"pull-requests"};$W$=[{re:/https?:\/\/([^/\s"']+)\/([^\s"']+?)\/-\/merge_requests\/(\d+)/},{re:/https?:\/\/([^/\s"']+)\/([^/\s"']+\/[^/\s"']+)\/pull\/(\d+)/},{re:/https?:\/\/([^/\s"']+)\/([^/\s"']+\/[^/\s"']+)\/pull-requests\/(\d+)/},{re:/https?:\/\/([^/\s"']+)\/repos\/([^/\s"']+\/[^/\s"']+)\/pulls\/(\d+)/,api:!0},{re:/https?:\/\/([^/\s"']+)\/api\/v4\/projects\/([^/\s"']+)\/merge_requests\/(\d+)/,api:!0},{re:/https?:\/\/([^/\s"']+)\/2\.0\/repositories\/([^/\s"']+\/[^/\s"']+)\/pullrequests\/(\d+)/,api:!0}],RE4={"api.github.com":"github.com","api.bitbucket.org":"bitbucket.org"}});function YW$($){return Pe0[$]}function Ae0($,Z){return Pe0[$].checkoutCommand.replace("{number}",String(Z))}function XW$($,Z){let{abbreviation:Q,numberSigil:Y}=Pe0[$];return`${Q} ${Y}${Z}`}var Pe0;var JW$=D(()=>{Pe0={github:{name:"GitHub",cli:"gh",changeRequest:"pull request",abbreviation:"PR",createCommand:"gh pr create",checkoutCommand:"gh pr checkout {number}",numberSigil:"#"},gitlab:{name:"GitLab",cli:"glab",changeRequest:"merge request",abbreviation:"MR",createCommand:"glab mr create",checkoutCommand:"glab mr checkout {number}",numberSigil:"!"},bitbucket:{name:"Bitbucket",cli:null,changeRequest:"pull request",abbreviation:"PR",createCommand:`curl -fsS -X POST -H "Authorization: Bearer $BITBUCKET_TOKEN" -H "Content-Type: application/json" https://api.bitbucket.org/2.0/repositories/<workspace>/<repo>/pullrequests -d '{"title":"<title>","source":{"branch":{"name":"<branch>"}},"destination":{"branch":{"name":"<base>"}}}'`,checkoutCommand:"git fetch origin <source branch> && git checkout <source branch>",numberSigil:"#"}}});var T6=D(()=>{s3$();je0();ze0();JW$()});async function La($,Z,Q){let Y=new AbortController,X,J=new Promise((W,K)=>{X=setTimeout(()=>{Y.abort(),K(new GW$($.id,Q))},Q)}),G=(async()=>{let W=await xG($,Z,!0);try{return(await W.listTools(void 0,{timeout:Q,signal:Y.signal})).tools}finally{await W.close().catch(()=>{})}})();G.catch(()=>{});try{return await Promise.race([G,J])}finally{if(X)clearTimeout(X)}}var GW$;var WW$=D(()=>{wa();GW$=class GW$ extends Error{constructor($,Z){super(`listTools timed out after ${Z}ms for connection ${$}`);this.name="ListToolsTimeoutError"}}});var Te0=b((KW$)=>{Object.defineProperty(KW$,"__esModule",{value:!0});KW$.kvPrefix=KW$.KvWatchInclude=void 0;KW$.KvWatchInclude={LastValue:"",AllHistory:"history",UpdatesOnly:"updates"};KW$.kvPrefix="KV_"});var zW$=b((jW$)=>{Object.defineProperty(jW$,"__esModule",{value:!0});jW$.KvStatusImpl=jW$.Bucket=jW$.Kvm=jW$.kvOperationHdr=void 0;jW$.Base64KeyCodec=IE4;jW$.NoopKvCodecs=Re0;jW$.defaultBucketOpts=UW$;jW$.validateKey=NW$;jW$.validateSearchKey=BW$;jW$.hasWildcards=OW$;jW$.validateBucket=O30;var f9=$G(),s5=B60(),x9=Te0();function IE4(){let $=(Z,Q)=>{let Y=[];for(let X of Z.split("."))switch(X){case">":case"*":Y.push(X);break;default:Y.push(Q(X));break}return Y.join(".")};return{encode(Z){return $(Z,btoa)},decode(Z){return $(Z,atob)}}}function Re0(){return{key:{encode($){return $},decode($){return $}},value:{encode($){return typeof $==="string"?new TextEncoder().encode($):$},decode($){return $}}}}function UW$(){return{replicas:1,history:1,timeout:2000,max_bytes:-1,maxValueSize:-1,codec:Re0(),storage:s5.StorageType.File}}jW$.kvOperationHdr="KV-Operation";var FW$="$KV",VE4=/^[-/=.\w]+$/,kE4=/^[-/=.>*\w]+$/,SE4=/^[-\w]+$/;function NW$($){if($.startsWith(".")||$.endsWith(".")||!VE4.test($))throw Error(`invalid key: ${$}`)}function BW$($){if($.startsWith(".")||$.endsWith(".")||$.includes("..")||!kE4.test($))throw Error(`invalid key: ${$}`)}function OW$($){if($.startsWith(".")||$.endsWith("."))throw Error(`invalid key: ${$}`);let Z=$.split("."),Q=!1;for(let Y=0;Y<Z.length;Y++)switch(Z[Y]){case"*":Q=!0;break;case">":if(Y!==Z.length-1)throw Error(`invalid key: ${$}`);Q=!0;break;default:}return Q}function O30($){if(!SE4.test($))throw Error(`invalid bucket name: ${$}`)}class DW${js;constructor($){this.js=(0,s5.toJetStreamClient)($)}create($,Z={}){return this.#$($,Z)}open($,Z={}){return Z.bindOnly=!0,this.#$($,Z)}#$($,Z={}){let{ok:Q,min:Y}=this.js.nc.features.get(f9.Feature.JS_KV);if(!Q)return Promise.reject(Error(`kv is only supported on servers ${Y} or better`));if(Z.bindOnly)return pl.bind(this.js,$,Z);return pl.create(this.js,$,Z)}list(){let $=(Q)=>{let X=Q.streams.filter((G)=>{return G.config.name.startsWith(x9.kvPrefix)});X.forEach((G)=>{G.config.sealed=G.config.sealed||!1,G.config.deny_delete=G.config.deny_delete||!1,G.config.deny_purge=G.config.deny_purge||!1,G.config.allow_rollup_hdrs=G.config.allow_rollup_hdrs||!1});let J="";if(X.length)J=this.js.nc.info?.cluster??"";return X.map((G)=>{return new D30(G,J)})},Z=`${this.js.prefix}.STREAM.LIST`;return new s5.ListerImpl(Z,$,this.js)}}jW$.Kvm=DW$;class pl{js;jsm;stream;bucket;direct;codec;prefix;editPrefix;useJsPrefix;_prefixLen;constructor($,Z,Q){O30($),this.js=Z,this.jsm=Q,this.bucket=$,this.prefix=FW$,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create($,Z,Q={}){O30(Z);let Y=await $.jetstreamManager(),X=new pl(Z,$,Y);return await X.init(Q),X}static async bind($,Z,Q={}){let Y=$.getOptions()?.checkAPI||Q.bindOnly===!1,X=await $.jetstreamManager(Y),J={config:{allow_direct:Q.allow_direct}};O30(Z);let G=new pl(Z,$,X);return J.config.name=Q.streamName??G.bucketName(),Object.assign(G,J),G.stream=J.config.name,G.codec=Q.codec||Re0(),G.direct=J.config.allow_direct??!1,G.initializePrefixes(J),G}async init($={}){let Z=Object.assign(UW$(),$);this.codec=Z.codec;let Q={};if(this.stream=Q.name=$.streamName??this.bucketName(),Q.retention=s5.RetentionPolicy.Limits,Q.max_msgs_per_subject=Z.history,Z.max_bytes)Q.max_bytes=Z.max_bytes;if(Q.max_msg_size=Z.maxValueSize,Q.storage=Z.storage,$.placement)Q.placement=$.placement;if($.republish)Q.republish=$.republish;if($.description)Q.description=$.description;if($.markerTTL)Q.allow_msg_ttl=!0,Q.subject_delete_marker_ttl=(0,f9.nanos)(Z.markerTTL);if($.mirror){let H=Object.assign({},$.mirror);if(!H.name.startsWith(x9.kvPrefix))H.name=`${x9.kvPrefix}${H.name}`;Q.mirror=H,Q.mirror_direct=!0}else if($.sources){let H=$.sources.map((F)=>{let U=Object.assign({},F),N=U.name.startsWith(x9.kvPrefix)?U.name.substring(x9.kvPrefix.length):U.name;if(!U.name.startsWith(x9.kvPrefix))U.name=`${x9.kvPrefix}${U.name}`;if(!F.external&&N!==this.bucket)U.subject_transforms=[{src:`$KV.${N}.>`,dest:`$KV.${this.bucket}.>`}];return U});Q.sources=H,Q.subjects=[this.subjectForBucket()]}else Q.subjects=[this.subjectForBucket()];if($.metadata)Q.metadata=$.metadata;if(typeof $.compression==="boolean")Q.compression=$.compression?s5.StoreCompression.S2:s5.StoreCompression.None;let Y=this.js.nc,X=Y.getServerVersion(),J=X?(0,f9.compare)(X,(0,f9.parseSemVer)("2.7.2"))>=0:!1;Q.discard=J?s5.DiscardPolicy.New:s5.DiscardPolicy.Old;let{ok:G,min:W}=Y.features.get(f9.Feature.JS_ALLOW_DIRECT);if(!G&&$.allow_direct===!0){let H=X?`${X.major}.${X.minor}.${X.micro}`:"unknown";return Promise.reject(Error(`allow_direct is not available on server version ${H} - requires ${W}`))}if($.allow_direct=typeof $.allow_direct==="boolean"?$.allow_direct:G,Q.allow_direct=$.allow_direct,this.direct=Q.allow_direct,Q.num_replicas=Z.replicas,Z.ttl)Q.max_age=(0,f9.nanos)(Z.ttl);Q.allow_rollup_hdrs=!0;let K;try{if(K=await this.jsm.streams.info(Q.name),!K.config.allow_direct&&this.direct===!0)this.direct=!1}catch(H){if(H.message==="stream not found")K=await this.jsm.streams.add(Q);else throw H}this.initializePrefixes(K)}initializePrefixes($){this._prefixLen=0,this.prefix=`$KV.${this.bucket}`,this.useJsPrefix=this.js.apiPrefix!=="$JS.API";let{mirror:Z}=$.config;if(Z){let Q=Z.name;if(Q.startsWith(x9.kvPrefix))Q=Q.substring(x9.kvPrefix.length);if(Z.external&&Z.external.api!==""){let Y=Z.name.substring(x9.kvPrefix.length);this.useJsPrefix=!1,this.prefix=`$KV.${Y}`,this.editPrefix=`${Z.external.api}.$KV.${Q}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${x9.kvPrefix}${this.bucket}`}subjectForBucket(){return`${this.prefix}.${this.bucket}.>`}subjectForKey($,Z=!1){let Q=[];if(Z){if(this.useJsPrefix)Q.push(this.js.apiPrefix);if(this.editPrefix!=="")Q.push(this.editPrefix);else Q.push(this.prefix)}else if(this.prefix)Q.push(this.prefix);return Q.push($),Q.join(".")}fullKeyName($){if(this.prefix!=="")return`${this.prefix}.${$}`;return`${FW$}.${this.bucket}.${$}`}get prefixLen(){if(this._prefixLen===0)this._prefixLen=this.prefix.length+1;return this._prefixLen}encodeKey($){let Z=[];for(let Q of $.split("."))switch(Q){case">":case"*":Z.push(Q);break;default:Z.push(this.codec.key.encode(Q));break}return Z.join(".")}decodeKey($){let Z=[];for(let Q of $.split("."))switch(Q){case">":case"*":Z.push(Q);break;default:Z.push(this.codec.key.decode(Q));break}return Z.join(".")}validateKey=NW$;validateSearchKey=BW$;hasWildcards=OW$;close(){return Promise.resolve()}dataLen($,Z){let Q=Z?Z.get(s5.JsHeaders.MessageSizeHdr)||"":"";if(Q!=="")return parseInt(Q,10);return $.length}smToEntry($){return new LW$(this.bucket,this.prefixLen,$,this.codec)}jmToWatchEntry($,Z){return new wW$(this.bucket,this.prefixLen,$,Z,this.codec)}async create($,Z,Q){let Y;try{let J={previousSeq:0},G=await this._put($,Z,J,Q);return Promise.resolve(G)}catch(J){if(Y=J,J instanceof s5.JetStreamApiError){let G=J;if(G.code!==s5.JetStreamApiCodes.StreamWrongLastSequence&&G.code!==s5.JetStreamApiCodes.StreamWrongLastSequenceUnknown)return Promise.reject(J)}}let X=0;try{let J=await this.get($);if(J?.operation==="DEL"||J?.operation==="PURGE")return X=J!==null?J.revision:0,this._put($,Z,{previousSeq:X},Q);else return Promise.reject(Y)}catch(J){return Promise.reject(J)}}update($,Z,Q,Y){if(Q<=0)throw Error("version must be greater than 0");return this.put($,Z,{previousSeq:Q,timeout:Y})}async _put($,Z,Q={},Y){let X=this.encodeKey($);this.validateKey(X),Z=this.codec.value.encode(Z);let J={timeout:Q?.timeout};if(Q.previousSeq!==void 0){let G=(0,f9.headers)();J.headers=G,G.set(s5.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Q.previousSeq}`)}if(Y)(J.headers||(0,f9.headers)()).set(s5.PubHeaders.MessageTTL,Y);try{return(await this.js.publish(this.subjectForKey(X,!0),Z,J)).seq}catch(G){return Promise.reject(G)}}put($,Z,Q={}){return this._put($,Z,Q)}async get($,Z){let Q=this.encodeKey($);this.validateKey(Q);let Y={last_by_subj:this.subjectForKey(Q)};if(Z&&Z.revision>0)Y={seq:Z.revision};let X=null;try{if(this.direct)X=await this.jsm.direct.getMessage(this.bucketName(),Y);else X=await this.jsm.streams.getMessage(this.bucketName(),Y);if(X===null)return null;let J=this.smToEntry(X);if(J.rawKey!==Q)return null;return J}catch(J){throw J}}purge($,Z){return this._deleteOrPurge($,"PURGE",Z)}delete($,Z){return this._deleteOrPurge($,"DEL",Z)}async purgeDeletes($=1800000){let Z=[],Q=await this.history({key:">"});await(async()=>{for await(let G of Q)if(G.operation==="DEL"||G.operation==="PURGE")Z.push(G)})().then(),Q.stop();let Y=Date.now()-$,X=Z.map((G)=>{let W=this.subjectForKey(G.key);if(G.created.getTime()>=Y)return this.jsm.streams.purge(this.stream,{filter:W,keep:1});else return this.jsm.streams.purge(this.stream,{filter:W,keep:0})}),J=await Promise.all(X);return J.unshift({success:!0,purged:0}),J.reduce((G,W)=>{return G.purged+=W.purged,G})}async _deleteOrPurge($,Z,Q){if(!this.hasWildcards($))return this._doDeleteOrPurge($,Z,Q);let Y=await this.keys($),X=[];for await(let J of Y)if(X.push(this._doDeleteOrPurge(J,Z)),X.length===100)await Promise.all(X),X.length=0;if(X.length>0)await Promise.all(X)}async _doDeleteOrPurge($,Z,Q){let Y=this.encodeKey($);this.validateKey(Y);let X=(0,f9.headers)();if(X.set(jW$.kvOperationHdr,Z),Z==="PURGE"){let J=Q;if(X.set(s5.JsHeaders.RollupHdr,s5.JsHeaders.RollupValueSubject),typeof J?.ttl==="string"&&J.ttl!=="")X.set(s5.PubHeaders.MessageTTL,`${J.ttl}`)}if(Q?.previousSeq)X.set(s5.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Q.previousSeq}`);await this.js.publish(this.subjectForKey(Y,!0),f9.Empty,{headers:X})}_buildCC($,Z,Q={}){let X=(!Array.isArray($)?[$]:$).map((W)=>{let K=this.encodeKey(W);return this.validateSearchKey(W),this.fullKeyName(K)}),J=s5.DeliverPolicy.LastPerSubject;if(Z===x9.KvWatchInclude.AllHistory)J=s5.DeliverPolicy.All;if(Z===x9.KvWatchInclude.UpdatesOnly)J=s5.DeliverPolicy.New;let G=void 0;if(X.length===1)G=X[0],X=void 0;return Object.assign({deliver_policy:J,ack_policy:s5.AckPolicy.None,filter_subjects:X,filter_subject:G,flow_control:!0,idle_heartbeat:(0,f9.nanos)(5000)},Q)}remove($){return this.purge($)}async history($={}){let Z=$.key??">",Q={};Q.headers_only=$.headers_only||!1;let Y=new f9.QueuedIteratorImpl,X=()=>{Y.stop()},J=this._buildCC(Z,x9.KvWatchInclude.AllHistory,Q),G=await this.js.consumers.getPushConsumer(this.stream,J);if(Y._data=G,(await G.info(!0)).num_pending===0)return Y.push(X),Y;let K=await G.consume({callback:(H)=>{let F=this.jmToWatchEntry(H,!1);if(Y.push(F),Y.received++,H.info.pending===0)Y.push(X)}});return K.closed().then(()=>{Y.push(X)}),(async()=>{for await(let H of K.status())switch(H.type){case"heartbeat":Y.push(()=>{Y.stop()});break}})().then(),Y.iterClosed.then(()=>{K.stop()}),Y}canSetWatcherName(){let $=this.js.nc,{ok:Z}=$.features.get(f9.Feature.JS_NEW_CONSUMER_CREATE_API);return Z}async watch($={}){let Z=$.key??">",Q=new f9.QueuedIteratorImpl,Y={};Y.headers_only=$.headers_only||!1;let X=x9.KvWatchInclude.LastValue;if($.include===x9.KvWatchInclude.AllHistory)X=x9.KvWatchInclude.AllHistory;else if($.include===x9.KvWatchInclude.UpdatesOnly)X=x9.KvWatchInclude.UpdatesOnly;let J=$.ignoreDeletes===!0,G=this._buildCC(Z,X,Y);if(G.name=`KV_WATCHER_${f9.nuid.next()}`,$.resumeFromRevision&&$.resumeFromRevision>0)G.deliver_policy=s5.DeliverPolicy.StartSequence,G.opt_start_seq=$.resumeFromRevision;let W=await this.js.consumers.getPushConsumer(this.stream,G),H=(await W.info(!0)).num_pending,F=X===x9.KvWatchInclude.UpdatesOnly||H===0;Q._data=W;let U=0,N=await W.consume({callback:(B)=>{if(!F)U++,F=U>=H;let O=this.jmToWatchEntry(B,F);if(J&&O.operation==="DEL")return;Q.push(O),Q.received++}});return Q.iterClosed.then(()=>{N.stop()}),N.closed().then(()=>{Q.push(()=>{Q.stop()})}),Q}async keys($=">"){let Z=new f9.QueuedIteratorImpl,Q=this._buildCC($,x9.KvWatchInclude.LastValue,{headers_only:!0}),Y=await this.js.consumers.getPushConsumer(this.stream,Q);if((await Y.info()).num_pending===0)return Z.stop(),Z;Z._data=Y;let J=await Y.consume({callback:(G)=>{let W=G.headers?.get(jW$.kvOperationHdr);if(W!=="DEL"&&W!=="PURGE"){let K=this.decodeKey(G.subject.substring(this.prefixLen));Z.push(K)}if(G.info.pending===0)J.stop()}});return(async()=>{for await(let G of J.status())switch(G.type){case"heartbeat":Z.push(()=>{Z.stop()});break}})().then(),J.closed().then(()=>{Z.push(()=>{Z.stop()})}),Z.iterClosed.then(()=>{J.stop()}),Z}purgeBucket($){return this.jsm.streams.purge(this.bucketName(),$)}destroy(){return this.jsm.streams.delete(this.bucketName())}async status(){let Z=this.js.nc.info?.cluster??"",Q=this.bucketName(),Y=await this.jsm.streams.info(Q);return new D30(Y,Z)}}jW$.Bucket=pl;class D30{si;cluster;constructor($,Z=""){this.si=$,this.cluster=Z}get bucket(){return this.si.config.name.startsWith(x9.kvPrefix)?this.si.config.name.substring(x9.kvPrefix.length):this.si.config.name}get values(){return this.si.state.messages}get history(){return this.si.config.max_msgs_per_subject}get ttl(){return(0,f9.millis)(this.si.config.max_age)}get markerTTL(){if(typeof this.si.config.subject_delete_marker_ttl==="number")return(0,f9.millis)(this.si.config.subject_delete_marker_ttl);return 0}get bucket_location(){return this.cluster}get backingStore(){return this.si.config.storage}get storage(){return this.si.config.storage}get replicas(){return this.si.config.num_replicas}get description(){return this.si.config.description??""}get maxBucketSize(){return this.si.config.max_bytes}get maxValueSize(){return this.si.config.max_msg_size}get max_bytes(){return this.si.config.max_bytes}get placement(){return this.si.config.placement||{cluster:"",tags:[]}}get placementCluster(){return this.si.config.placement?.cluster??""}get republish(){return this.si.config.republish??{src:"",dest:""}}get streamInfo(){return this.si}get size(){return this.si.state.bytes}get metadata(){return this.si.config.metadata??{}}get compression(){if(this.si.config.compression)return this.si.config.compression!==s5.StoreCompression.None;return!1}}jW$.KvStatusImpl=D30;class LW${bucket;sm;prefixLen;codec;constructor($,Z,Q,Y){this.bucket=$,this.prefixLen=Z,this.sm=Q,this.codec=Y}get rawKey(){return this.sm.subject.substring(this.prefixLen)}get key(){return this.codec.key.decode(this.rawKey)}get value(){return this.codec.value.decode(this.sm.data)}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){if(this.sm.header?.has("Nats-Marker-Reason")){if(this.sm.header?.get("Nats-Marker-Reason")==="MaxAge")return"PURGE"}return this.sm.header?.get(jW$.kvOperationHdr)||"PUT"}get length(){let $=this.sm.header.get(s5.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}json($){return JSON.parse(f9.TD.decode(this.value),$)}string(){return f9.TD.decode(this.value)}}class wW${bucket;sm;prefixLen;update;codec;constructor($,Z,Q,Y,X){this.bucket=$,this.prefixLen=Z,this.sm=Q,this.update=Y,this.codec=X}get rawKey(){return this.sm.subject.substring(this.prefixLen)}get key(){return this.codec.key.decode(this.rawKey)}get value(){return this.codec.value.decode(this.sm.data)}get created(){return new Date((0,f9.millis)(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){if(this.sm.headers?.has("Nats-Marker-Reason")){if(this.sm.headers?.get("Nats-Marker-Reason")==="MaxAge")return"PURGE"}return this.sm.headers?.get(jW$.kvOperationHdr)||"PUT"}get delta(){return this.sm.info.pending}get length(){let $=this.sm.headers?.get(s5.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}get isUpdate(){return this.update}json($){return JSON.parse(f9.TD.decode(this.value),$)}string(){return f9.TD.decode(this.value)}}});var qe0=b((mK)=>{Object.defineProperty(mK,"__esModule",{value:!0});mK.validateKey=mK.validateBucket=mK.NoopKvCodecs=mK.Kvm=mK.defaultBucketOpts=mK.Bucket=mK.Base64KeyCodec=mK.KvWatchInclude=mK.kvPrefix=void 0;var PW$=Te0();Object.defineProperty(mK,"kvPrefix",{enumerable:!0,get:function(){return PW$.kvPrefix}});Object.defineProperty(mK,"KvWatchInclude",{enumerable:!0,get:function(){return PW$.KvWatchInclude}});var zA=zW$();Object.defineProperty(mK,"Base64KeyCodec",{enumerable:!0,get:function(){return zA.Base64KeyCodec}});Object.defineProperty(mK,"Bucket",{enumerable:!0,get:function(){return zA.Bucket}});Object.defineProperty(mK,"defaultBucketOpts",{enumerable:!0,get:function(){return zA.defaultBucketOpts}});Object.defineProperty(mK,"Kvm",{enumerable:!0,get:function(){return zA.Kvm}});Object.defineProperty(mK,"NoopKvCodecs",{enumerable:!0,get:function(){return zA.NoopKvCodecs}});Object.defineProperty(mK,"validateBucket",{enumerable:!0,get:function(){return zA.validateBucket}});Object.defineProperty(mK,"validateKey",{enumerable:!0,get:function(){return zA.validateKey}})});var za=b((Ew)=>{Object.defineProperty(Ew,"__esModule",{value:!0});Ew.NoopKvCodecs=Ew.Kvm=Ew.defaultBucketOpts=Ew.Bucket=Ew.Base64KeyCodec=Ew.KvWatchInclude=void 0;var lE4=qe0();Object.defineProperty(Ew,"KvWatchInclude",{enumerable:!0,get:function(){return lE4.KvWatchInclude}});var Ea=qe0();Object.defineProperty(Ew,"Base64KeyCodec",{enumerable:!0,get:function(){return Ea.Base64KeyCodec}});Object.defineProperty(Ew,"Bucket",{enumerable:!0,get:function(){return Ea.Bucket}});Object.defineProperty(Ew,"defaultBucketOpts",{enumerable:!0,get:function(){return Ea.defaultBucketOpts}});Object.defineProperty(Ew,"Kvm",{enumerable:!0,get:function(){return Ea.Kvm}});Object.defineProperty(Ew,"NoopKvCodecs",{enumerable:!0,get:function(){return Ea.NoopKvCodecs}})});function zw(){let $=new TextEncoder,Z=new TextDecoder;return{encode:(Q)=>$.encode(JSON.stringify(Q)),decode:(Q)=>JSON.parse(Z.decode(Q))}}class Me0{options;kv=null;codec=zw();constructor($){this.options=$}async init(){let $=this.options.getJetStream();if(!$)return;this.kv=await new TW$.Kvm($).create(mE4,{storage:AW$.StorageType.Memory})}async get($,Z){if(!this.kv)return null;try{let Q=await this.kv.get(`${$}.${Z}`);if(!Q?.value?.length)return null;if(Q.operation==="DEL"||Q.operation==="PURGE")return null;return this.codec.decode(Q.value)}catch{return null}}async set($,Z,Q){if(!this.kv)return;try{await this.kv.put(`${$}.${Z}`,this.codec.encode(Q))}catch{}}async invalidate($){if(!this.kv)return;await Promise.all(["tools","resources","prompts"].map(async(Q)=>{try{await this.kv.delete(`${Q}.${$}`)}catch{}}))}teardown(){this.kv=null}}function dE4($,Z,Q){if(Q<=0)return!0;if($===void 0)return!0;return Z-$>=Q}function RW$($){let Z=["tools","resources","prompts"];for(let Q of Z){let Y=`${Q}:${$}`;w30.delete(Y),Aa.delete(Y)}}function L30($){return $ instanceof M1&&$.code===_1.MethodNotFound}function iE4($){return $ instanceof M1&&$.code===-32000&&/connection closed/i.test($.message)}async function Aw($,Z,Q,Y,X,J=0){if(!Y)try{return await Q()}catch(H){if(L30(H))return[];return Pa.add(1,{type:$,outcome:"error",stage:"no_cache"}),null}let G=`${$}:${Z}`,W=await Y.get($,Z);if(W===null)try{let H=await Q();return Y.set($,Z,H).catch(()=>{}),w30.set(G,Date.now()),Pa.add(1,{type:$,outcome:"miss",stage:"miss"}),H}catch(H){if(L30(H))return Y.set($,Z,[]).catch(()=>{}),[];return Pa.add(1,{type:$,outcome:"error",stage:"miss"}),null}if(Pa.add(1,{type:$,outcome:"hit",stage:"hit"}),dE4(w30.get(G),Date.now(),J)&&!Aa.has(G)){Aa.add(G),w30.set(G,Date.now());let H=Q().then((F)=>Y.set($,Z,F)).catch((F)=>{if(L30(F)||iE4(F)){if(L30(F))Y.set($,Z,[]).catch(()=>{});return}Pa.add(1,{type:$,outcome:"error",stage:"revalidation"})}).finally(()=>Aa.delete(G));X?.(H)}return W}function Ie0($){qW$=$}function GZ(){return qW$}var AW$,TW$,Pa,mE4="DECOCMS_MCP_LISTS",Aa,w30,Pw=30000,qW$=null;var DJ=D(()=>{a9();C6();AW$=C(GN(),1),TW$=C(za(),1),Pa=z$.createCounter("mcp_list_cache.fetches",{description:"MCP list cache fetch outcomes (hit, miss, error)",unit:"{fetches}"});Aa=new Set;z$.createObservableGauge("mcp_list_cache.pending_revalidations",{description:"In-flight background MCP list revalidations on this pod",unit:"{revalidations}"}).addCallback(($)=>$.observe(Aa.size));w30=new Map});function j30($){return(Z)=>{if(Z instanceof M1&&Z.code===_1.MethodNotFound)return $;throw Z}}var MW$=D(()=>{a9()});function E30($,Z,Q){let Y=Tw($,Z,Q,GZ()??void 0),X=TP(Y,{name:"studio-mcp-server",version:"1.0.0"},{capabilities:pE4,toolCallTimeoutMs:Jh});X.server.setRequestHandler(fD,async()=>{return await Y.listResources().catch(j30({resources:[]}))}),X.server.setRequestHandler(yD,async()=>{return await Y.listResourceTemplates().catch(j30({resourceTemplates:[]}))}),X.server.setRequestHandler(gD,async()=>{return await Y.listPrompts().catch(j30({prompts:[]}))});let J=X.close.bind(X);return X.close=async()=>{await J(),await Y.close().catch(()=>{})},X}var pE4;var IW$=D(()=>{aX();a9();Ta();DJ();MW$();pE4={tools:{},resources:{},prompts:{}}});var nl=D(()=>{wa();WW$();IW$()});async function tl($,Z,Q){await(await xG(Z,$,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:Q.state,scopes:Q.scopes,firstRun:Q.firstRun,...Q.vault?{vault:Q.vault}:{}}})}var z30=D(()=>{nl()});import{z as Ve0}from"zod";function oE4($){let{owner:Z,name:Q}=h5({path:$.path});return{owner:Z,name:Q,url:$.webUrl??`https://${$.host}/${$.path}`,repositoryId:$.repositoryId}}function rE4($,Z){if(!Z)return $;return $.filter((Q)=>Q.connection_id!==Z)}function sE4($,Z){let{repository:Q,github_repo:Y,...X}=$,J=Z?W30(Z):null;return{...X,...Z?{repository:G30(Z)}:{},...J?{github_repo:J}:{}}}async function aE4($,Z,Q){let Y=y4.REPORTS(Z),X=await $.storage.connections.findById(Y,Z);if(!X)throw Error("Reports is not set up for this organization yet");let J=sE4(X.configuration_state??{},Q);await $.storage.connections.update(Y,{configuration_state:J});try{await tl($,{...X,configuration_state:J},{state:J,scopes:X.configuration_scopes??[],firstRun:!1})}catch(G){console.error("[reports] ON_MCP_CONFIGURATION after repository change failed",G)}}async function eE4($,Z,Q,Y){let X=Yh(Z),J=await $.storage.virtualMcps.findById(X,Z);if(!J)return;let G=J.metadata??{},W=G.githubRepo,{githubRepo:K,...H}=G;await $.storage.virtualMcps.update(X,Q,{metadata:{...H,...Y?{githubRepo:oE4(Y)}:{}},connections:rE4(J.connections??[],W?.connectionId??null)})}var nE4,tE4,ke0;var VW$=D(()=>{e8();T6();K30();C0();z30();nE4=Ve0.object({repositoryId:Ve0.string().min(1).nullable().describe("Studio repository id to diagnose, or null to unlink the current one.")}),tE4=Ve0.object({repository:Ue0.nullable()});ke0=d({name:"REPORTS_SET_REPOSITORY",description:"Point the organization's Deco Score at one of its linked repositories, or unlink the current one. Works for GitHub, GitLab and Bitbucket.",annotations:{title:"Set Deco Score Repository",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:nE4,outputSchema:tE4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=p0(Z);if(!Y)throw Error("User ID required to set the diagnostic's repository");let X=null;if($.repositoryId){let J=await Z.storage.repositories.get($.repositoryId,Q.id);if(!J)throw Error(`Repository ${$.repositoryId} is not linked to this organization`);let G={repositoryId:J.id,provider:J.provider,host:J.host,path:J.path,defaultBranch:J.defaultBranch,webUrl:J.webUrl},W=Ue0.safeParse(G);if(!W.success)throw Error(`Repository ${$.repositoryId} has invalid configuration (missing or empty host/path)`);X=W.data}return await aE4(Z,Q.id,X),await eE4(Z,Q.id,Y,X),{repository:X}}})});function Rw($,Z){let Q=`/${encodeURIComponent($)}/settings`;return Z?`${Q}/${Z}`:Q}function P30($,Z){let Q=`/${encodeURIComponent($)}/agents`,Y=Z.panel?`${Q}/${Z.panel}`:Q,X=new URLSearchParams({virtualmcpid:Z.projectId,...Z.search??{}});return`${Y}?${X.toString()}`}var qw=D(()=>{A70()});import{z as uF}from"zod";async function Yz4($,Z,Q,Y){let X=await $.storage.connections.findById(Z,Q);if(X)return X;throw Y}async function Xz4($,Z,Q,Y){let X=await $.storage.virtualMcps.findById(Z,Q);if(X)return X;throw Y}var Se0,$z4=3600000,Zz4,Qz4,Ce0;var kW$=D(()=>{e8();Na();C0();tH();qw();ww();Se0=q70,Zz4=uF.object({siteUrl:uF.string().min(1).describe("Website URL to configure.")}),Qz4=uF.object({connection:eQ,virtualMcp:$Y,reportApp:uF.object({connectionId:uF.string(),virtualMcpId:uF.string(),toolName:uF.literal(Se0)}),created:uF.object({connection:uF.boolean(),virtualMcp:uF.boolean()})});Ce0=d({name:"REPORTS_SETUP",description:"Create or return the Deco Score connection and virtual MCP for the current organization.",annotations:{title:"Set Up Deco Score",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Zz4,outputSchema:Qz4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check("COLLECTION_CONNECTIONS_CREATE");let Y=p0(Z);if(!Y)throw Error("User ID required to set up Reports");let X=Lw($.siteUrl);if(!X.ok)throw Error(X.error);let J=y4.REPORTS(Q.id),G=Yh(Q.id),W={email:Z.auth.user?.email,reportUrl:`${Z.baseUrl}${P30(Q.slug??Q.id,{projectId:G,panel:"app",search:{connection:J,tool:Se0}})}`},K=await Z.storage.connections.findById(J,Q.id),H={connection:!1,virtualMcp:!1},F=await c3$({siteUrl:X.value,orgId:Q.id,orgName:Q.name,...W}),U=u3$();if(K)console.log("[reports] syncing connection to claimed site",{orgId:Q.id,siteUrl:X.value,connectionId:J}),K=await Z.storage.connections.update(K.id,{connection_url:U,connection_token:F.authorizationToken,metadata:{...K.metadata??{},siteUrl:X.value}});else{console.log("[reports] creating connection",{orgId:Q.id,siteUrl:X.value,connectionId:J});try{let L=hm1(Q.id,F.authorizationToken,U);K=await Z.storage.connections.create({...L,metadata:{...L.metadata??{},siteUrl:X.value},organization_id:Q.id,created_by:Y}),H.connection=!0}catch(L){K=await Yz4(Z,J,Q.id,L)}}let N=await Z.storage.virtualMcps.findById(G,Q.id);if(!N){console.log("[reports] creating virtual MCP",{orgId:Q.id,siteUrl:X.value,connectionId:K.id,virtualMcpId:G});try{N=await Z.storage.virtualMcps.create(Q.id,Y,um1(Q.id,K.id),{id:G}),H.virtualMcp=!0}catch(L){N=await Xz4(Z,G,Q.id,L)}}if(!N.pinned)N=await Z.storage.virtualMcps.update(N.id,Y,{pinned:!0});let B=await Z.db.selectFrom("organization").select(["createdAt"]).where("id","=",Q.id).executeTakeFirst();if((B?Date.now()-new Date(B.createdAt).getTime():Number.POSITIVE_INFINITY)<$z4){let w=(await Z.storage.organizationSettings.get(Q.id))?.flags,j={};if(w?.reports_only==null)j.reports_only=!0;if(Object.keys(j).length>0)await Z.storage.organizationSettings.upsert(Q.id,{flags:j})}return{connection:K,virtualMcp:N,reportApp:{connectionId:K.id,virtualMcpId:N.id,toolName:Se0},created:H}}})});var SW$=D(()=>{p3$();n3$();t3$();VW$();kW$()});function Ra($,Z,Q){if(Z.some((Y)=>Y!=="*"&&Y.startsWith("SELF::"))&&$.SELF===void 0)$.SELF={value:`${Q}_self`}}function qa($,Z){let Q=new Map;for(let Y of Z){if(Y==="*")continue;let[X,J]=NX0(Y);if(!Gz4.has(J))continue;let G=Qr(X,$);if(typeof G!=="object"||G===null||!("value"in G))continue;let W=G.value;if(typeof W!=="string")continue;Q.set(`${W}:${J}`,{targetConnectionId:W,scope:J})}return[...Q.values()]}async function Ma($,Z,Q,Y){for(let G of Z){if(G==="*")continue;let[W]=NX0(G),K=Qr(W,$);if(K===void 0||K===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let X=T1$($,Z),J=`${Q}_self`;for(let G of X){if(G===J)continue;let W=await Y.storage.connections.findById(G);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${G}`);try{await Y.access.check(G)}catch(K){throw Error(`Access denied to referenced connection: ${G}. ${K.message}`)}}}var Gz4;var _e0=D(()=>{en0();b70();Gz4=new Set([_70,v70])});import{z as CW$}from"zod";var Wz4,Kz4,ve0;var _W$=D(()=>{U6();C0();F$();DJ();z30();_e0();UJ0();tH();Wz4=CW$.object({data:D70.describe("Data for the new connection (id is auto-generated if not provided)")}),Kz4=CW$.object({item:eQ.describe("The created connection entity")}),ve0=d({name:"COLLECTION_CONNECTIONS_CREATE",description:"Create a new MCP connection. Auto-fetches and caches the server's tool list.",annotations:{title:"Create Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Wz4,outputSchema:Kz4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=p0(Z);if(!Y)throw Error("User ID required to create connection");let X={...$.data,organization_id:Q.id,created_by:Y};if(X.id){if((await Z.storage.connections.findById(X.id))?.organization_id===Q.id)throw Error("Connection already exists in organization");if(await Z.storage.connections.findBySanitizedId(X.id))throw Error("Connection id conflicts with an existing connection's isolated database schema")}if(X.connection_type==="VIRTUAL"){let U=$h(X.connection_url);if(!U)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let N=await Z.storage.virtualMcps.findById(U);if(!N)throw Error(`Virtual MCP not found: ${U}`);if(N.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");X.connection_url=Zh(U)}if(X.connection_type==="STDIO"&&!E0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let J=await $l({id:`pending-${Date.now()}`,title:X.title,connection_type:X.connection_type,connection_url:X.connection_url,connection_token:X.connection_token,connection_headers:X.connection_headers}).catch(()=>null),G=J?.tools?.length?J.tools:null,W=J?.scopes?.length?J.scopes:X.configuration_scopes??null,K=X.configuration_state??null;if(K&&W?.length)Ra(K,W,Q.id),await Ma(K,W,Q.id,Z);let H=await Z.storage.connections.createNew({...X,tools:null,configuration_state:K,configuration_scopes:W}),F=K&&W?.length?qa(K,W):[];if(F.length>0){let U;try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:H.id,createdBy:Y,grants:F});let{plaintextToken:N,record:B}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:Q.id,subjectConnectionId:H.id});U=B.id,await tl(Z,H,{state:K,scopes:W,firstRun:!0,vault:{baseUrl:Z.baseUrl,org:Q.slug??Q.id,subjectConnectionId:H.id,token:N}})}catch(N){if(U)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:H.id,tokenId:U});throw await Z.storage.connections.delete(H.id),N}}if(G)GZ()?.set("tools",H.id,G).catch(()=>{});return v1.capture({distinctId:Y,event:"connection_created",groups:{organization:Q.id},properties:{connection_id:H.id,connection_type:H.connection_type,app_name:H.app_name??null,organization_id:Q.id,tools_count:G?.length??0}}),{item:H}}})});import{z as XW}from"zod/v4";import{z as vW$}from"zod/v4";import{z as A30}from"zod/v4";import{z as lF}from"zod/v4";import{z as Nz4}from"zod/v4";import{z as PA}from"zod/v4";import{z as cF}from"zod/v4";import{z as i7}from"zod/v4";import{z as bW$}from"zod/v4";import{z as q30}from"zod/v4";import{z as xz4}from"zod/v4";import{z as xW$}from"zod/v4";import{z as T30}from"zod/v4";import{z as dz4}from"zod/v4";function Ia($,Z){if($===Z)return!0;if($==null||Z==null)return $===Z;if(typeof $!==typeof Z)return!1;if(Array.isArray($)&&Array.isArray(Z)){if($.length!==Z.length)return!1;return $.every((Q,Y)=>Ia(Q,Z[Y]))}if(typeof $==="object"&&typeof Z==="object"){let Q=Object.keys($),Y=Object.keys(Z);if(Q.length!==Y.length)return!1;return Q.every((X)=>Y.includes(X)&&Ia($[X],Z[X]))}return!1}function _z4(){return($)=>{if(!Array.isArray($))return!0;let Z=[];return $.every((Q)=>{if(Z.some((X)=>Ia(Q,X)))return!1;return Z.push(Q),!0})}}function R30($,Z){return $.safeParse(Z).success}function IQ($){if(typeof $==="boolean")return $?XW.any():XW.never();let Z={};for(let X of tz4)X.apply(Z,$);let Q=[];if(Z.string!==!1)Q.push(Z.string||XW.string());if(Z.number!==!1)Q.push(Z.number||XW.number());if(Z.boolean!==!1)Q.push(Z.boolean||XW.boolean());if(Z.null!==!1)Q.push(Z.null||XW.null());if(Z.array!==!1)Q.push(Z.array||XW.array(XW.any()));if(Z.tuple!==!1&&Z.tuple!==void 0)Q.push(Z.tuple);if(Z.object!==!1)if(Z.object)Q.push(Z.object);else{let X=XW.custom((J)=>{return typeof J==="object"&&J!==null&&!Array.isArray(J)},"Must be an object, not an array");Q.push(X)}if(Z.file!==!1&&Z.file!==void 0)Q.push(Z.file);let Y;if(Q.length===0)Y=XW.never();else if(Q.length===1)Y=Q[0];else if(!Object.keys($).some((J)=>J!=="$schema"&&J!=="title"&&J!=="description"))Y=XW.any();else Y=XW.union(Q);for(let X of oz4)Y=X.apply(Y,$);return Y}var Hz4=class{apply($,Z){if(!Z.type)return;let Q=Array.isArray(Z.type)?Z.type:[Z.type],Y=new Set(Q);if(!Y.has("string"))$.string=!1;if(!Y.has("number")&&!Y.has("integer"))$.number=!1;if(!Y.has("boolean"))$.boolean=!1;if(!Y.has("null"))$.null=!1;if(!Y.has("array"))$.array=!1;if(!Y.has("object"))$.object=!1;if(Y.has("integer")&&$.number!==!1){let X=$.number||vW$.number();if(X instanceof vW$.ZodNumber)$.number=X.int()}}},Fz4=class{apply($,Z){if(Z.const===void 0)return;let Q=Z.const;if($.string=!1,$.number=!1,$.boolean=!1,$.null=!1,$.array=!1,$.object=!1,typeof Q==="string")$.string=A30.literal(Q);else if(typeof Q==="number")$.number=A30.literal(Q);else if(typeof Q==="boolean")$.boolean=A30.literal(Q);else if(Q===null)$.null=A30.null();else if(Array.isArray(Q))$.array=void 0;else if(typeof Q==="object")$.object=void 0}},Uz4=class{apply($,Z){if(!Z.enum)return;if(Z.enum.length===0){if(!Z.type)$.string=!1,$.number=!1,$.boolean=!1,$.null=!1,$.array=!1,$.object=!1;return}let Q={string:Z.enum.filter((Y)=>typeof Y==="string"),number:Z.enum.filter((Y)=>typeof Y==="number"),boolean:Z.enum.filter((Y)=>typeof Y==="boolean"),null:Z.enum.filter((Y)=>Y===null),array:Z.enum.filter((Y)=>Array.isArray(Y)),object:Z.enum.filter((Y)=>typeof Y==="object"&&Y!==null&&!Array.isArray(Y))};$.string=this.createTypeSchema(Q.string,"string"),$.number=this.createTypeSchema(Q.number,"number"),$.boolean=this.createTypeSchema(Q.boolean,"boolean"),$.null=Q.null.length>0?lF.null():!1,$.array=Q.array.length>0?void 0:!1,$.object=Q.object.length>0?void 0:!1}createTypeSchema($,Z){if($.length===0)return!1;if($.length===1)return lF.literal($[0]);if(Z==="string")return lF.enum($);if(Z==="number"){let[Q,Y,...X]=$;return lF.union([lF.literal(Q),lF.literal(Y),...X.map((J)=>lF.literal(J))])}if(Z==="boolean")return lF.union([lF.literal(!0),lF.literal(!1)]);return!1}},Bz4=class{apply($,Z){let Q=Z;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let Y=Nz4.file();if(Q.minLength!==void 0)Y=Y.min(Q.minLength);if(Q.maxLength!==void 0)Y=Y.max(Q.maxLength);if(Q.contentMediaType!==void 0)Y=Y.mime(Q.contentMediaType);$.file=Y,$.string=!1}}},Oz4=class{apply($,Z){let Q=Z;if(Z.type===void 0&&(Q.minLength!==void 0||Q.maxLength!==void 0||Q.pattern!==void 0)){if($.string===void 0)$.string=PA.string()}}},Dz4=class{apply($,Z){let Q=Z;if(Q.minLength===void 0)return;if($.string!==!1){let Y=$.string||PA.string();if(Y instanceof PA.ZodString)$.string=Y.refine((X)=>{return Array.from(X).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},Lz4=class{apply($,Z){let Q=Z;if(Q.maxLength===void 0)return;if($.string!==!1){let Y=$.string||PA.string();if(Y instanceof PA.ZodString)$.string=Y.refine((X)=>{return Array.from(X).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},wz4=class{apply($,Z){let Q=Z;if(!Q.pattern)return;if($.string!==!1){let Y=$.string||PA.string();if(Y instanceof PA.ZodString){let X=new RegExp(Q.pattern);$.string=Y.regex(X)}}}},jz4=class{apply($,Z){let Q=Z;if(Q.minimum===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)$.number=Y.min(Q.minimum)}}},Ez4=class{apply($,Z){let Q=Z;if(Q.maximum===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)$.number=Y.max(Q.maximum)}}},zz4=class{apply($,Z){let Q=Z;if(Q.exclusiveMinimum===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)if(typeof Q.exclusiveMinimum==="number")$.number=Y.gt(Q.exclusiveMinimum);else $.number=!1}}},Pz4=class{apply($,Z){let Q=Z;if(Q.exclusiveMaximum===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)if(typeof Q.exclusiveMaximum==="number")$.number=Y.lt(Q.exclusiveMaximum);else $.number=!1}}},Az4=class{apply($,Z){let Q=Z;if(Q.multipleOf===void 0)return;if($.number!==!1){let Y=$.number||cF.number();if(Y instanceof cF.ZodNumber)$.number=Y.refine((X)=>{if(Q.multipleOf===0)return!1;let J=X/Q.multipleOf,G=Math.round(J),W=Math.min(Math.abs(X)*Number.EPSILON*10,Math.abs(Q.multipleOf)*Number.EPSILON*10);return Math.abs(J-G)<=W/Math.abs(Q.multipleOf)},{message:`Must be a multiple of ${Q.multipleOf}`})}}},Tz4=class{apply($,Z){let Q=Z;if(Z.type===void 0&&(Q.minItems!==void 0||Q.maxItems!==void 0||Q.items!==void 0||Q.prefixItems!==void 0)){if($.array===void 0)$.array=i7.array(i7.any())}}},Rz4=class{apply($,Z){let Q=Z;if(Q.minItems===void 0)return;if($.array!==!1)$.array=($.array||i7.array(i7.any())).min(Q.minItems)}},qz4=class{apply($,Z){let Q=Z;if(Q.maxItems===void 0)return;if($.array!==!1)$.array=($.array||i7.array(i7.any())).max(Q.maxItems)}},Mz4=class{apply($,Z){let Q=Z;if($.array===!1)return;if(Array.isArray(Q.items))$.array=$.array||i7.array(i7.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let Y=IQ(Q.items),X=i7.array(Y);if($.array&&$.array instanceof i7.ZodArray){let J=$.array._def;if(J.checks)J.checks.forEach((G)=>{if(G._zod&&G._zod.def){let W=G._zod.def;if(W.check==="min_length"&&W.minimum!==void 0)X=X.min(W.minimum);else if(W.check==="max_length"&&W.maximum!==void 0)X=X.max(W.maximum)}})}$.array=X}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)$.array=i7.array(i7.any()).max(0);else $.array=$.array||i7.array(i7.any());else if(typeof Q.items==="boolean"&&Q.items===!0)$.array=$.array||i7.array(i7.any());else if(Q.prefixItems)$.array=$.array||i7.array(i7.any())}},Iz4=class{apply($,Z){if(Z.type!=="array")return;let Q=Z;if(!Array.isArray(Q.items))return;if($.array===!1)return;let Y=Q.items.map((J)=>IQ(J)),X;if(Y.length===0)X=bW$.tuple([]);else X=bW$.tuple(Y);if(Q.minItems!==void 0&&Q.minItems>Y.length)X=!1;if(Q.maxItems!==void 0&&Q.maxItems<Y.length)X=!1;$.tuple=X,$.array=!1}},Vz4=class{apply($,Z){let Q=Z;if($.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)$.object=$.object||q30.object({}).passthrough()}},kz4=class{apply($,Z){let Q=Z;if(Z.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if($.object===void 0)$.object=q30.object({}).passthrough()}}},Sz4=class{apply($,Z){let Q=Z;if(Q.maxProperties===void 0)return;if($.object!==!1){let Y=$.object||q30.object({}).passthrough();$.object=Y.refine((X)=>Object.keys(X).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},Cz4=class{apply($,Z){let Q=Z;if(Q.minProperties===void 0)return;if($.object!==!1){let Y=$.object||q30.object({}).passthrough();$.object=Y.refine((X)=>Object.keys(X).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},vz4=class{apply($,Z){if(!Z.not)return $;let Q=IQ(Z.not);return $.refine((Y)=>!R30(Q,Y),{message:"Value must not match the 'not' schema"})}},bz4=class{apply($,Z){if(Z.uniqueItems!==!0)return $;return $.refine(_z4(),{message:"Array items must be unique"})}},fz4=class{apply($,Z){if(!Z.allOf||Z.allOf.length===0)return $;return Z.allOf.map((Y)=>IQ(Y)).reduce((Y,X)=>xz4.intersection(Y,X),$)}},yz4=class{apply($,Z){if(!Z.anyOf||Z.anyOf.length===0)return $;let Q=Z.anyOf.length===1?IQ(Z.anyOf[0]):xW$.union([IQ(Z.anyOf[0]),IQ(Z.anyOf[1]),...Z.anyOf.slice(2).map((Y)=>IQ(Y))]);return xW$.intersection($,Q)}},gz4=class{apply($,Z){if(!Z.oneOf||Z.oneOf.length===0)return $;let Q=Z.oneOf.map((Y)=>IQ(Y));return $.refine((Y)=>{let X=0;for(let J of Q)if(J.safeParse(Y).success){if(X++,X>1)return!1}return X===1},{message:"Value must match exactly one of the oneOf schemas"})}},hz4=class{apply($,Z){let Q=Z;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let X=Q.prefixItems.map((J)=>IQ(J));return $.refine((J)=>{if(!Array.isArray(J))return!0;for(let G=0;G<Math.min(J.length,X.length);G++)if(!R30(X[G],J[G]))return!1;if(J.length>X.length){if(typeof Q.items==="boolean"&&Q.items===!1)return!1;else if(Q.items&&typeof Q.items==="object"&&!Array.isArray(Q.items)){let G=IQ(Q.items);for(let W=X.length;W<J.length;W++)if(!R30(G,J[W]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return $}},uz4=class{apply($,Z){let Q=Z;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return $;if($ instanceof T30.ZodObject||$ instanceof T30.ZodRecord){let Y={};if(Q.properties){for(let[X,J]of Object.entries(Q.properties))if(J!==void 0)Y[X]=IQ(J)}if(Q.required&&Array.isArray(Q.required)){let X=new Set(Q.required);for(let J of Object.keys(Y))if(!X.has(J))Y[J]=Y[J].optional()}else for(let X of Object.keys(Y))Y[X]=Y[X].optional();if(Q.additionalProperties===!1)return T30.object(Y);else return T30.object(Y).passthrough()}return $.refine((Y)=>{if(typeof Y!=="object"||Y===null||Array.isArray(Y))return!0;if(Q.properties){for(let[X,J]of Object.entries(Q.properties))if(J!==void 0){if(Object.getOwnPropertyDescriptor(Y,X)!==void 0){if(!IQ(J).safeParse(Y[X]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let X of Q.required)if(Object.getOwnPropertyDescriptor(Y,X)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let X=new Set(Object.keys(Q.properties));for(let J in Y)if(!X.has(J))return!1}return!0},{message:"Object constraints validation failed"})}},lz4=class{apply($,Z){if(!Z.enum||Z.enum.length===0)return $;let Q=Z.enum.filter((Y)=>Array.isArray(Y)||typeof Y==="object"&&Y!==null);if(Q.length===0)return $;return $.refine((Y)=>{if(typeof Y!=="object"||Y===null)return!0;return Q.some((X)=>Ia(Y,X))},{message:"Value must match one of the enum values"})}},cz4=class{apply($,Z){if(Z.const===void 0)return $;let Q=Z.const;if(typeof Q!=="object"||Q===null)return $;return $.refine((Y)=>Ia(Y,Q),{message:"Value must equal the const value"})}},mz4=class{apply($,Z){if(Z.description)$=$.describe(Z.description);return $}},iz4=class{apply($,Z){var Q;let Y=Z;if(!((Q=Y.required)==null?void 0:Q.includes("__proto__"))||Z.type!==void 0)return $;return dz4.any().refine((X)=>this.validateRequired(X,Y.required),{message:"Missing required properties"})}validateRequired($,Z){if(typeof $!=="object"||$===null||Array.isArray($))return!0;return Z.every((Q)=>Object.prototype.hasOwnProperty.call($,Q))}},pz4=class{apply($,Z){var Q;let Y=Z;if(Y.contains===void 0)return $;let X=IQ(Y.contains),J=(Q=Y.minContains)!=null?Q:1,G=Y.maxContains;return $.refine((W)=>{if(!Array.isArray(W))return!0;let K=0;for(let H of W)if(R30(X,H))K++;if(K<J)return!1;if(G!==void 0&&K>G)return!1;return!0},{message:"Array must contain required items matching the schema"})}},nz4=class{apply($,Z){let{default:Q}=Z;if(Q===void 0)return $;if(!$.safeParse(Q).success)return $;return $.default(Q)}},tz4,oz4;var fW$=D(()=>{tz4=[new Fz4,new Uz4,new Hz4,new Bz4,new Oz4,new Tz4,new kz4,new Dz4,new Lz4,new wz4,new jz4,new Ez4,new zz4,new Pz4,new Az4,new Iz4,new Rz4,new qz4,new Mz4,new Sz4,new Cz4,new Vz4],oz4=[new iz4,new lz4,new cz4,new fz4,new yz4,new gz4,new hz4,new uz4,new pz4,new vz4,new bz4,new nz4,new mz4]});class be0{constructor($){this._url=$}start(){if(this._socket)throw Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise(($,Z)=>{this._socket=new WebSocket(this._url,rz4),this._socket.onerror=(Q)=>{let Y="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);Z(Y),this.onerror?.(Y)},this._socket.onopen=()=>{$()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let Y;try{Y=NG.parse(JSON.parse(Q.data))}catch(X){this.onerror?.(X);return}this.onmessage?.(Y)}})}async close(){this._socket?.close()}send($){return new Promise((Z,Q)=>{if(!this._socket){Q(Error("Not connected"));return}this._socket?.send(JSON.stringify($)),Z()})}}var rz4="mcp";var yW$=D(()=>{a9()});function sz4($){let Z=$;if(!Z||typeof Z!=="object"||!("method"in Z))return null;switch(Z.method){case"initialize":{let Q=Z?.params?.protocolVersion;if(!Q)return null;return{type:"emit",message:{result:{protocolVersion:Q,capabilities:{tools:{}},serverInfo:{name:"deco-chat-server",version:"1.0.0"}},jsonrpc:Z.jsonrpc??"2.0",id:Z.id}}}case"notifications/roots/list_changed":case"notifications/initialized":case"notifications/cancelled":case"notifications/progress":return{type:"suppress"};default:return null}}var xe0;var gW$=D(()=>{Zr();xe0=class xe0 extends SL{constructor($,Z){super($,Z)}send($,Z){let Q=sz4($);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send($,Z)}}});var hW$,uW$=async($,Z,Q)=>{let Y=az4($.connection,Z,Q);if(!Y)throw Error("Unknown MCP connection type");let X=new hW$({name:$?.name??"MCP Client",version:"1.0.0"});return await X.connect(Y),{client:X}},az4=($,Z,Q)=>{if($.type==="Websocket")return new be0(new URL($.url));if($.type!=="SSE"&&$.type!=="HTTP")return null;let X={...$.token?{authorization:`Bearer ${$.token}`}:{},...Q??{},..."headers"in $?$.headers||{}:{}};if($.type==="SSE"){let J={requestInit:{headers:X,signal:Z}};if($.token)J.eventSourceInit={fetch:(G,W)=>{return fetch(G,{...W,headers:{...X,Accept:"text/event-stream"},signal:Z})}};return new MP(new URL($.url),J)}return new xe0(new URL($.url),{requestInit:{headers:X,signal:Z,credentials:"include"}})};var lW$=D(()=>{tN();UX0();yW$();a9();aX();gW$();hW$=class hW$ extends g7{constructor($,Z){super($,{jsonSchemaValidator:PZ,...Z})}async listTools($,Z){return await this.request({method:"tools/list",params:$},ln,Z)}}});function $P4($,Z){if(AA.set($,Z),AA.size>ez4){let Q=AA.keys().next().value;if(Q!==void 0)AA.delete(Q)}}function dW$($){let Z=(Q)=>{if("connection"in $)return uW$({connection:$.connection},void 0,Q);return $.client};return new Proxy({},{get(Q,Y){if(Y==="toJSON")return null;if(typeof Y!=="string")throw Error("Name must be a string");if(Y==="listTools")return W;async function X(K,H=Y){let F=$?.debugId?.(),U=F?{"x-trace-debug-id":F}:void 0,{client:N}=await Z(U),{structuredContent:B,isError:O,content:L}=await N.callTool({name:String(H),arguments:K});if(O){let j=L?.[0]?.text,E=typeof j==="string"?cW$(j):null,z=E?.code&&typeof $?.getErrorByStatusCode==="function"?$.getErrorByStatusCode(E.code,E.message,E.traceId):null;if(z)throw z;throw Error(`Tool ${String(H)} returned an error: ${JSON.stringify(B??L)}`)}if(B!==void 0)return B;let w=L?.[0]?.text;return typeof w==="string"?cW$(w):void 0}async function J(){let{client:K}=await Z(),{tools:H}=await K.listTools();return H}async function G(){if(!("connection"in $))return J();let K=$.connection,H=JSON.stringify(K);try{if(!AA.has(H))$P4(H,J());return await AA.get(H)}catch(F){console.error("Failed to list tools",F),AA.delete(H);return}}async function W(){return(await G()??[]).map((H)=>mW$(H,X))}return X.asTool=async()=>{let H=(await G()??[]).find((F)=>F.name===Y);if(!H)throw Error(`Tool ${Y} not found`);return mW$(H,X)},X}})}var cW$=($)=>{try{return JSON.parse($)}catch{return $}},ez4=500,AA,mW$=($,Z)=>{return{...$,id:$.name,inputSchema:$.inputSchema?IQ($.inputSchema):void 0,outputSchema:$.outputSchema?IQ($.outputSchema):void 0,execute:(Q)=>{return Z(Q.context,$.name)}}};var iW$=D(()=>{fW$();lW$();AA=new Map});function Va($){return dW$($)}var di5;var pW$=D(()=>{iW$();di5=new Proxy({},{get($,Z){if(Z==="toJSON")return null;if(Z==="forConnection")return(Q)=>Va({connection:Q});if(Z==="forClient")return(Q)=>Va({client:Q});return globalThis[Z]}})});function M30($){return{isImplementedBy:(Z)=>{for(let Q of $){let Y=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,X=Z.find((J)=>Y.test(J.name));if(!X&&Q.opt)continue;if(!X)return!1}return!0}}}var EB=($)=>{return{...M30($),forClient:(Z)=>{return Va({client:Z})},forConnection:(Z)=>{return Va({connection:Z})}}};var ol=D(()=>{pW$()});import{z as y9}from"zod";var nW$,tW$,oW$,rW$,sW$,ZP4;var aW$=D(()=>{ol();nW$=y9.object({specversion:y9.literal("1.0").describe("CloudEvents specification version"),id:y9.string().describe("Unique identifier for this event (UUID recommended)"),source:y9.string().describe("Connection ID of the event publisher"),type:y9.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:y9.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:y9.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:y9.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:y9.string().url().optional().describe("URI to the schema for the data attribute"),data:y9.unknown().optional().describe("Event payload (any JSON value)")}),tW$=y9.object({events:y9.array(nW$).min(1).describe("Batch of CloudEvents to process")}),oW$=y9.object({success:y9.boolean().optional().describe("Whether this event was processed successfully"),error:y9.string().optional().describe("Error message for this event"),retryAfter:y9.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),rW$=y9.object({success:y9.boolean().optional().describe("Batch success - applies to events not in results"),error:y9.string().optional().describe("Batch error message - applies to events not in results"),processedCount:y9.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:y9.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:y9.record(y9.string(),oW$).optional().describe("Per-event results keyed by event ID")}),sW$=[{name:"ON_EVENTS",inputSchema:tW$,outputSchema:rW$}],ZP4=EB(sW$)});import{z as g9}from"zod";var eW$,$K$,ZK$,QK$,YK$,XK$,I30,fe0;var ye0=D(()=>{ol();eW$=g9.object({type:g9.literal("string"),enum:g9.array(g9.string()).optional(),description:g9.string().optional()}),$K$=g9.object({type:g9.string(),description:g9.string(),paramsSchema:g9.record(g9.string(),eW$)}),ZK$=g9.object({}),QK$=g9.object({triggers:g9.array($K$)}),YK$=g9.object({type:g9.string(),params:g9.record(g9.string(),g9.string()),enabled:g9.boolean(),callbackUrl:g9.url().optional(),callbackToken:g9.string().min(1).optional()}),XK$=g9.object({success:g9.boolean()}),I30=[{name:"TRIGGER_LIST",inputSchema:ZK$,outputSchema:QK$},{name:"TRIGGER_CONFIGURE",inputSchema:YK$,outputSchema:XK$}],fe0=EB(I30)});import{z as Z8}from"zod";var QP4,YP4,XP4,JP4,GP4,WP4,KP4,HP4,FP4,UP4,NP4,BP4,TA;var ka=D(()=>{QP4=Z8.object({prefix:Z8.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:Z8.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:Z8.string().optional().describe("Token for pagination from previous response"),delimiter:Z8.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),YP4=Z8.object({objects:Z8.array(Z8.object({key:Z8.string().describe("Object key/path"),size:Z8.number().describe("Object size in bytes"),lastModified:Z8.string().describe("Last modified timestamp"),etag:Z8.string().describe("Entity tag for the object")})),nextContinuationToken:Z8.string().optional().describe("Token for fetching next page of results"),isTruncated:Z8.boolean().describe("Whether there are more results available"),commonPrefixes:Z8.array(Z8.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),XP4=Z8.object({key:Z8.string().describe("Object key/path to get metadata for")}),JP4=Z8.object({contentType:Z8.string().optional().describe("MIME type of the object"),contentLength:Z8.number().describe("Size of the object in bytes"),lastModified:Z8.string().describe("Last modified timestamp"),etag:Z8.string().describe("Entity tag for the object"),metadata:Z8.record(Z8.string(),Z8.string()).optional().describe("Custom metadata key-value pairs")}),GP4=Z8.object({key:Z8.string().describe("Object key/path to generate URL for"),expiresIn:Z8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),WP4=Z8.object({url:Z8.string().describe("Presigned URL for downloading the object"),expiresIn:Z8.number().describe("Expiration time in seconds that was used")}),KP4=Z8.object({key:Z8.string().describe("Object key/path for the upload"),expiresIn:Z8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:Z8.string().optional().describe("MIME type for the object being uploaded")}),HP4=Z8.object({url:Z8.string().describe("Presigned URL for uploading the object"),expiresIn:Z8.number().describe("Expiration time in seconds that was used")}),FP4=Z8.object({key:Z8.string().describe("Object key/path to delete")}),UP4=Z8.object({success:Z8.boolean().describe("Whether the deletion was successful"),key:Z8.string().describe("The key that was deleted")}),NP4=Z8.object({keys:Z8.array(Z8.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),BP4=Z8.object({deleted:Z8.array(Z8.string()).describe("Array of successfully deleted keys"),errors:Z8.array(Z8.object({key:Z8.string(),message:Z8.string()})).describe("Array of errors for failed deletions")}),TA=[{name:"LIST_OBJECTS",inputSchema:QP4,outputSchema:YP4},{name:"GET_OBJECT_METADATA",inputSchema:XP4,outputSchema:JP4},{name:"GET_PRESIGNED_URL",inputSchema:GP4,outputSchema:WP4},{name:"PUT_PRESIGNED_URL",inputSchema:KP4,outputSchema:HP4},{name:"DELETE_OBJECT",inputSchema:FP4,outputSchema:UP4},{name:"DELETE_OBJECTS",inputSchema:NP4,outputSchema:BP4}]});import{z as F5}from"zod";var JK$,GK$,WK$,Sa,V30,k30,S30,C30,OP4;var ge0=D(()=>{ol();JK$=F5.object({primary:F5.string().optional().describe("Primary brand color (hex)"),secondary:F5.string().optional().describe("Secondary brand color (hex)"),accent:F5.string().optional().describe("Accent / highlight color (hex)"),background:F5.string().optional().describe("Background color (hex)"),foreground:F5.string().optional().describe("Foreground / text color (hex)")}),GK$=F5.object({heading:F5.string().optional().describe("Font family for headings"),body:F5.string().optional().describe("Font family for body text"),code:F5.string().optional().describe("Font family for code / monospace")}),WK$=F5.object({logo:F5.string().optional().describe("Logo URL"),favicon:F5.string().optional().describe("Favicon URL"),ogImage:F5.string().optional().describe("Open Graph image URL")}),Sa=F5.object({id:F5.string(),name:F5.string().describe("Brand / company name"),domain:F5.string().optional().describe("Company domain (e.g. example.com)"),colors:JK$.optional().describe("Semantic color palette"),fonts:GK$.optional().describe("Font families by role"),assets:WK$.optional().describe("Visual identity assets"),overview:F5.string().optional().describe("Company overview / description"),tagline:F5.string().optional().describe("Brand tagline"),tone:F5.string().optional().describe("Tone of voice description"),metadata:F5.record(F5.string(),F5.unknown()).optional().describe("Extra design tokens and metadata")}),V30=F5.object({id:F5.string().optional().describe("Brand ID. Omit to get the default brand.")}),k30=F5.object({}),S30=F5.object({items:F5.array(Sa)}),C30=[{name:"BRAND_GET",inputSchema:V30,outputSchema:Sa},{name:"BRAND_LIST",inputSchema:k30,outputSchema:S30,opt:!0}],OP4=EB(C30)});var KK$=D(()=>{ol();aW$();ye0();ka();ge0()});import{z as s8}from"zod";function rl($){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return new RegExp(`^${Q}$`,"i")}function zB($){return s8.object({items:s8.array($).describe("Array of collection items"),totalCount:s8.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:s8.boolean().optional().describe("Whether there are more items available")})}function _a($){return s8.object({item:$.nullable().describe("The retrieved item, or null if not found")})}function wP4($){return s8.object({data:$.partial().describe("Data for the new entity (id may be auto-generated)")})}function jP4($){return s8.object({item:$.describe("The created entity with generated id")})}function EP4($){return s8.object({id:s8.string().describe("ID of the entity to update"),data:$.partial().describe("Partial entity data to update")})}function zP4($){return s8.object({item:$.describe("The updated entity")})}function ba($){return s8.object({item:$.describe("The deleted entity")})}function v30($,Z,Q){let Y=$.toUpperCase(),X=Q?.readOnly??!1,J=[{name:`COLLECTION_${Y}_LIST`,inputSchema:dK,outputSchema:zB(Z)},{name:`COLLECTION_${Y}_GET`,inputSchema:Ca,outputSchema:_a(Z)}];if(!X)J.push({name:`COLLECTION_${Y}_CREATE`,inputSchema:wP4(Z),outputSchema:jP4(Z),opt:!0},{name:`COLLECTION_${Y}_UPDATE`,inputSchema:EP4(Z),outputSchema:zP4(Z),opt:!0},{name:`COLLECTION_${Y}_DELETE`,inputSchema:va,outputSchema:ba(Z),opt:!0});return J}var _30,DP4,HK$,LP4,dK,Ca,va;var LJ=D(()=>{_30=s8.object({id:s8.string().describe("Unique identifier for the entity"),title:s8.string().describe("Human-readable title for the entity"),description:s8.string().nullish().describe("Description of the entity"),created_at:s8.string().datetime(),updated_at:s8.string().datetime(),created_by:s8.string().optional(),updated_by:s8.string().optional()}),DP4=s8.object({field:s8.array(s8.string()),operator:s8.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:s8.unknown()}),HK$=s8.lazy(()=>s8.union([DP4,s8.object({operator:s8.enum(["and","or","not"]),conditions:s8.array(HK$)})]));LP4=s8.object({field:s8.array(s8.string()),direction:s8.enum(["asc","desc"]),nulls:s8.enum(["first","last"]).optional()}),dK=s8.object({where:HK$.optional().describe("Filter expression"),orderBy:s8.array(LP4).optional().describe("Sort expressions"),limit:s8.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:s8.number().int().min(0).optional().describe("Number of items to skip")});Ca=s8.object({id:s8.string().describe("ID of the entity to retrieve")});va=s8.object({id:s8.string().describe("ID of the entity to delete")})});import{z as sl}from"zod";var PP4,AP4,FK$;var UK$=D(()=>{LJ();PP4=_30.extend({avatar:sl.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:sl.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:sl.string().describe("Virtual MCP ID to use for this assistant"),model:sl.object({id:sl.string().describe("Model ID"),connectionId:sl.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),AP4=v30("assistant",PP4),FK$=[...AP4]});import{z as O0}from"zod";var xa,PB,BK$,TP4,RP4,OK$,qP4,MP4,IP4,VP4,kP4,SP4,DK$,CP4,_P4,vP4,bP4,xP4,fP4,yP4,gP4,hP4,uP4,Pp5,lP4,Ap5,NK$,cP4,mP4,b30,Tp5;var LK$=D(()=>{ol();LJ();xa=O0.lazy(()=>O0.union([O0.null(),O0.string(),O0.number(),O0.boolean(),O0.record(O0.string(),xa),O0.array(xa)])),PB=O0.record(O0.string(),O0.record(O0.string(),xa)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),BK$=O0.object({type:O0.literal("text"),text:O0.string().describe("The text content"),providerOptions:PB}),TP4=O0.object({type:O0.literal("text"),text:O0.string().describe("The text content"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),RP4=O0.string().describe("File data as URL string"),OK$=O0.object({type:O0.literal("file"),filename:O0.string().optional().describe("Optional filename of the file"),data:RP4,mediaType:O0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:PB}),qP4=O0.object({type:O0.literal("file"),mediaType:O0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:O0.string().describe("Generated file data as base64 encoded string")}),MP4=O0.object({type:O0.literal("reasoning"),text:O0.string().describe("The reasoning text"),providerOptions:PB}),IP4=O0.object({type:O0.literal("reasoning"),text:O0.string().describe("The reasoning text"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),VP4=O0.object({type:O0.literal("tool-call"),toolCallId:O0.string().describe("ID of the tool call, used to match with tool result"),toolName:O0.string().describe("Name of the tool being called"),input:O0.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:O0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:PB}),kP4=O0.object({type:O0.literal("tool-call"),toolCallId:O0.string().describe("ID of the tool call"),toolName:O0.string().describe("Name of the tool being called"),input:O0.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:O0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),SP4=O0.union([O0.object({type:O0.literal("text"),value:O0.string()}),O0.object({type:O0.literal("json"),value:xa}),O0.object({type:O0.literal("error-text"),value:O0.string()}),O0.object({type:O0.literal("error-json"),value:xa}),O0.object({type:O0.literal("content"),value:O0.array(O0.union([O0.object({type:O0.literal("text"),text:O0.string().describe("Text content")}),O0.object({type:O0.literal("media"),data:O0.string().describe("Base-64 encoded media data"),mediaType:O0.string().describe("IANA media type")})]))}),O0.object({type:O0.literal("execution-denied"),reason:O0.string().optional()}),O0.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),DK$=O0.object({type:O0.literal("tool-result"),toolCallId:O0.string().describe("ID of the tool call that this result is associated with"),toolName:O0.string().describe("Name of the tool that generated this result"),output:SP4.describe("Result of the tool call"),result:O0.unknown().describe("Unknown result of the tool call"),providerOptions:PB}),CP4=O0.object({type:O0.literal("tool-result"),toolCallId:O0.string().describe("ID of the tool call that this result is associated with"),toolName:O0.string().describe("Name of the tool that generated this result"),result:O0.any().describe("Result of the tool call (JSON-serializable)"),isError:O0.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:O0.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),_P4=O0.union([O0.object({type:O0.literal("source"),sourceType:O0.literal("url"),id:O0.string().describe("The ID of the source"),url:O0.string().describe("The URL of the source"),title:O0.string().optional().describe("The title of the source"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")}),O0.object({type:O0.literal("source"),sourceType:O0.literal("document"),id:O0.string().describe("The ID of the source"),mediaType:O0.string().describe("IANA media type of the document (e.g., application/pdf)"),title:O0.string().describe("The title of the document"),filename:O0.string().optional().describe("Optional filename of the document"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata")})]),vP4=O0.object({role:O0.literal("system"),content:O0.string().describe("System message content"),providerOptions:PB}),bP4=O0.object({role:O0.literal("user"),content:O0.array(O0.union([BK$,OK$])).describe("User message content parts (text or file)"),providerOptions:PB}),xP4=O0.object({role:O0.literal("assistant"),content:O0.array(O0.union([BK$,OK$,MP4,VP4,DK$])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:PB}),fP4=O0.object({role:O0.literal("tool"),content:O0.array(DK$).describe("Tool message content (tool results)"),providerOptions:PB}),yP4=O0.union([vP4,bP4,xP4,fP4]),gP4=O0.array(yP4).describe("A list of messages forming the prompt"),hP4=O0.object({prompt:gP4.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:O0.number().optional().describe("Maximum number of tokens to generate"),temperature:O0.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:O0.number().optional().describe("Nucleus sampling parameter"),topK:O0.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:O0.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:O0.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:O0.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:O0.array(O0.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:O0.union([O0.object({type:O0.literal("text")}),O0.object({type:O0.literal("json"),schema:O0.any().optional().describe("JSON schema that the generated output should conform to"),name:O0.string().optional().describe("Name of output that should be generated"),description:O0.string().optional().describe("Description of the output that should be generated")})]).optional().describe("Response format. The output can either be text or JSON. Default is text"),tools:O0.array(O0.any()).optional().describe("The tools that are available for the model"),toolChoice:O0.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:O0.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:O0.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:O0.any().optional().describe("Additional provider-specific options")}),uP4=O0.object({content:O0.array(O0.union([TP4,qP4,IP4,kP4,CP4,_P4])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:O0.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:O0.looseObject({inputTokens:O0.number().optional(),outputTokens:O0.number().optional(),totalTokens:O0.number().optional(),reasoningTokens:O0.number().optional()}).describe("Usage information for the language model call"),providerMetadata:O0.any().optional().describe("Additional provider-specific metadata"),request:O0.object({body:O0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:O0.object({id:O0.string().optional().describe("ID for the generated response"),timestamp:O0.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:O0.string().optional().describe("The ID of the response model that was used"),headers:O0.record(O0.string(),O0.string()).optional().describe("Response headers"),body:O0.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:O0.array(O0.any()).describe("Warnings for the call, e.g. unsupported settings")}),Pp5=O0.object({stream:O0.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:O0.object({body:O0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:O0.object({headers:O0.record(O0.string(),O0.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),lP4=O0.object({supportedUrls:O0.record(O0.string(),O0.array(O0.string())).describe("Supported URL patterns by media type for the provider")}),Ap5=O0.object({modelId:O0.string().describe("The ID of the model"),logo:O0.string().nullable(),description:O0.string().nullable(),capabilities:O0.array(O0.string()),limits:O0.object({contextWindow:O0.number(),maxOutputTokens:O0.number()}).nullable(),costs:O0.object({input:O0.number(),output:O0.number()}).nullable(),provider:O0.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),NK$=O0.object({modelId:O0.string().describe("The ID of the model"),callOptions:hP4}),cP4=_30.extend({logo:O0.string().nullable(),description:O0.string().nullable(),capabilities:O0.array(O0.string()),limits:O0.object({contextWindow:O0.number(),maxOutputTokens:O0.number()}).nullable(),costs:O0.object({input:O0.number(),output:O0.number()}).nullable(),provider:O0.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),mP4=v30("llm",cP4,{readOnly:!0}),b30=[{name:"LLM_METADATA",inputSchema:O0.object({modelId:O0.string().describe("The ID of the model")}),outputSchema:lP4},{name:"LLM_DO_STREAM",inputSchema:NK$},{name:"LLM_DO_GENERATE",inputSchema:NK$,outputSchema:uP4},...mP4],Tp5=EB(b30)});import{z as RA}from"zod";var dP4,wK$;var jK$=D(()=>{dP4=RA.object({scopes:RA.array(RA.string()).describe("List of scopes available"),stateSchema:RA.record(RA.string(),RA.unknown()).describe("JSON Schema (draft-07) defining the state structure")}),wK$=[{name:"MCP_CONFIGURATION",inputSchema:RA.object({}),outputSchema:dP4}]});import{z as h9}from"zod";var iP4,pP4,EK$;var zK$=D(()=>{iP4=h9.object({}).strict(),pP4=h9.object({billing:h9.object({mode:h9.enum(["prepaid","postpaid"]),limitPeriod:h9.enum(["daily","weekly","monthly"]).nullable()}),limit:h9.object({total:h9.number().nullable(),remaining:h9.number().nullable(),reset:h9.string().nullable()}),usage:h9.object({total:h9.number(),daily:h9.number(),weekly:h9.number(),monthly:h9.number()}),alert:h9.object({enabled:h9.boolean(),threshold_usd:h9.number(),email:h9.string().nullable()}),connectionId:h9.string()}),EK$=[{name:"GATEWAY_USAGE",inputSchema:iP4,outputSchema:pP4},{name:"GATEWAY_SET_LIMIT",inputSchema:h9.object({}),outputSchema:h9.object({}),opt:!0},{name:"GATEWAY_SET_ALERT",inputSchema:h9.object({}),outputSchema:h9.object({}),opt:!0}]});import{z as PK$}from"zod";function JW(){return $X()===null}function x30($,Z){return $===y4.DEV_ASSETS(Z)}function f30($,Z){let Q=Sm1(Z,$),Y=new Date().toISOString();return{id:Q.id??y4.DEV_ASSETS($),title:Q.title,description:Q.description??null,icon:Q.icon??null,app_name:Q.app_name??null,app_id:Q.app_id??null,organization_id:$,created_by:"system",created_at:Y,updated_at:Y,connection_type:Q.connection_type,connection_url:Q.connection_url??null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:Q.metadata??null,tools:nP4,bindings:["OBJECT_STORAGE"],status:"active"}}var nP4;var al=D(()=>{SD();ka();e8();nP4=TA.map(($)=>({name:$.name,description:`${$.name} operation for local file storage`,inputSchema:PK$.toJSONSchema($.inputSchema),outputSchema:PK$.toJSONSchema($.outputSchema)}))});function AK$($,Z){return $||Z===0}function TK$($,Z,Q,Y,X){let J=Z?X+1:X,G=$.slice(0,Q),W=Y+Q<J;return{items:G,totalCount:J,hasMore:W}}function RK$($,Z,Q){if(!Q)return{sqlOffset:$,sqlLimit:Z};if($===0)return{sqlOffset:0,sqlLimit:Math.max(Z-1,0)};return{sqlOffset:$-1,sqlLimit:Z}}function tP4($,Z){if(Z.length===0)return;let[Q,...Y]=Z,X=Q==="slug"?lD($):$[Q];for(let J of Y){if(X===null||typeof X!=="object")return;X=X[J]}return X}function oP4($,Z,Q){if($===void 0)return!0;switch(Z){case"eq":return Q===null?$===null:$===Q;case"gt":return $>Q;case"gte":return $>=Q;case"lt":return $<Q;case"lte":return $<=Q;case"in":return Array.isArray(Q)&&Q.includes($);case"like":return typeof $==="string"&&rl(String(Q)).test($);case"contains":return String($).toLowerCase().includes(String(Q).toLowerCase());default:return!0}}function fa($,Z){if(!Z)return!0;if("conditions"in Z){let{operator:Y,conditions:X}=Z;if(X.length===0)return!0;switch(Y){case"and":return X.every((J)=>fa($,J));case"or":return X.some((J)=>fa($,J));case"not":return!X.every((J)=>fa($,J));default:return!0}}let Q=tP4($,Z.field);return oP4(Q,Z.operator,Z.value)}var qK$=D(()=>{k70();LJ()});import{z as Mw}from"zod";var rP4=8,sP4,aP4,eP4,$A4,qA;var he0=D(()=>{KK$();UK$();LJ();LK$();jK$();ka();zK$();e8();C0();E9();DJ();nl();al();tH();k70();qK$();sP4=[{name:/^(COLLECTION_REGISTRY_APP_LIST|REGISTRY_ITEM_LIST)$/,inputSchema:Mw.object({})}],aP4={LLM:b30,LLMS:b30,ASSISTANTS:FK$,MCP:wK$,OBJECT_STORAGE:TA,AI_GATEWAY_BILLING:EK$,TRIGGER:I30,REGISTRY:sP4,BRAND:C30},eP4=dK.extend({binding:Mw.union([Mw.array(Mw.object({}).passthrough()),Mw.object({}).passthrough(),Mw.string()]).optional(),include_virtual:Mw.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false."),slug:Mw.string().optional().describe("Filter by connection slug. Matches against app_name, or a slug derived from connection_url or title.")}),$A4=zB(eQ),qA=d({name:"COLLECTION_CONNECTIONS_LIST",description:"List all connections in the organization with filtering, sorting, and pagination",annotations:{title:"List Connections",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:eP4,outputSchema:$A4,handler:async($,Z)=>{await Z.access.check();let Q=K0(Z),Y=$.binding?typeof $.binding==="string"?(()=>{let j=aP4[$.binding.toUpperCase()];if(!j)throw Error(`Unknown binding: ${$.binding}`);return j})():$.binding:void 0,X=Y?M30(Y):void 0,J=!!X,G=$.limit??100,W=$.offset??0,K=s9(),H=y4.DEV_ASSETS(Q.id),F=f30(Q.id,K),U=(!$.slug||lD(F)===$.slug)&&fa(F,$.where),N=JW()&&!J&&U,{sqlOffset:B,sqlLimit:O}=RK$(W,G,N),{items:L,totalCount:w}=await Z.storage.connections.list(Q.id,{includeVirtual:$.include_virtual??!1,slug:$.slug,where:$.where,orderBy:$.orderBy,limit:J?void 0:O,offset:J?void 0:B});if(X){let j=GZ(),E=y4.SELF(Q.id);await Zl(L,rP4,async(z)=>{if(z.tools!==null)return;let T=z.id===E?async()=>{let{listManagementTools:A}=await Promise.resolve().then(() => (Iw(),y30));return A(Z)}:()=>La(z,Z,Gh),P=await Aw("tools",z.id,T,j,(A)=>Z.pendingRevalidations.push(A),Pw);if(P!==null)z.tools=P})}if(JW()&&AK$(J,W)&&U&&!L.some((j)=>j.id===H))L.unshift(F);if(J){let j=(await Promise.all(L.map(async(P)=>{if(!P.tools||P.tools.length===0)return null;return X.isImplementedBy(P.tools.map((q)=>({name:q.name,inputSchema:q.inputSchema,outputSchema:q.outputSchema})))?P:null}))).filter((P)=>P!==null),E=j.length,z=j.slice(W,W+G),T=W+G<E;return{items:z,totalCount:E,hasMore:T}}return TK$(L,N,G,W,w)}})});var ZA4,MA;var ue0=D(()=>{LJ();e8();C0();E9();DJ();nl();al();tH();ZA4=_a(eQ),MA=d({name:"COLLECTION_CONNECTIONS_GET",description:"Get a connection's configuration, tools list, and status by ID.",annotations:{title:"Get Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:["app"]}},inputSchema:Ca,outputSchema:ZA4,handler:async($,Z)=>{let Q=K0(Z);if(await Z.access.check(),JW()&&x30($.id,Q.id))return{item:f30(Q.id,s9())};let Y=await Z.storage.connections.findById($.id);if(!Y||Y.organization_id!==Q.id)return{item:null};if(Y.tools===null){let X=y4.SELF(Q.id),J=Y.id===X?async()=>{let{listManagementTools:W}=await Promise.resolve().then(() => (Iw(),y30));return W(Z)}:()=>La(Y,Z,Gh),G=await Aw("tools",Y.id,J,GZ(),(W)=>Z.pendingRevalidations.push(W),Pw);if(G!==null)Y.tools=G}return{item:Y}}})});class F9{db;vault;constructor($,Z){this.db=$;this.vault=Z}async get($){let Z=await this.db.selectFrom("downstream_tokens").selectAll().where("connectionId","=",$).executeTakeFirst();if(!Z)return null;return QA4(this.vault,Z)}async upsert($){let Z=new Date().toISOString(),Q=await this.vault.encrypt($.accessToken),Y=$.refreshToken?await this.vault.encrypt($.refreshToken):null,X=$.clientSecret?await this.vault.encrypt($.clientSecret):null,J=$.expiresAt?.toISOString()??null,G=await this.db.insertInto("downstream_tokens").values({id:a8("dtok"),connectionId:$.connectionId,accessToken:Q,refreshToken:Y,scope:$.scope,expiresAt:J,clientId:$.clientId,clientSecret:X,tokenEndpoint:$.tokenEndpoint,createdAt:Z,updatedAt:Z}).onConflict((W)=>W.column("connectionId").doUpdateSet({accessToken:Q,refreshToken:Y,scope:$.scope,expiresAt:J,clientId:$.clientId,clientSecret:X,tokenEndpoint:$.tokenEndpoint,updatedAt:Z})).returning(["id","createdAt"]).executeTakeFirstOrThrow();return{id:G.id,connectionId:$.connectionId,accessToken:$.accessToken,refreshToken:$.refreshToken,scope:$.scope,expiresAt:$.expiresAt,createdAt:G.createdAt,updatedAt:Z,clientId:$.clientId,clientSecret:$.clientSecret,tokenEndpoint:$.tokenEndpoint}}async delete($){await this.db.deleteFrom("downstream_tokens").where("connectionId","=",$).execute()}isExpired($,Z=0){if(!$.expiresAt)return!1;let Y=($.expiresAt instanceof Date?$.expiresAt:new Date($.expiresAt)).getTime();if(Number.isNaN(Y))return!0;return Y-Z<Date.now()}}async function QA4($,Z){try{let Q=await $.decrypt(Z.accessToken),Y=Z.refreshToken?await $.decrypt(Z.refreshToken):null,X=Z.clientSecret?await $.decrypt(Z.clientSecret):null;return{id:Z.id,connectionId:Z.connectionId,accessToken:Q,refreshToken:Y,scope:Z.scope,expiresAt:Z.expiresAt,createdAt:Z.createdAt,updatedAt:Z.updatedAt,clientId:Z.clientId,clientSecret:X,tokenEndpoint:Z.tokenEndpoint}}catch(Q){return console.warn("[DownstreamToken] failed to decrypt token row",{connectionId:Z.connectionId,message:Q instanceof Error?Q.message:String(Q)}),null}}var iK=D(()=>{ZY()});function el(...$){if(GA4)console.log("[mcp-read-cache]",...$)}function WA4($){return $.kind==="org"?"org":`u:${$.userId}`}function le0($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(le0).join(",")}]`;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${le0($[Q])}`).join(",")}}`}class u30{config;maxEntries;now;maxTotalBytes;store=new Map;revalidating=new Set;totalBytes=0;constructor($=YA4,Z=XA4,Q=()=>Date.now(),Y=JA4){this.config=$;this.maxEntries=Z;this.now=Q;this.maxTotalBytes=Y}stats(){return{entries:this.store.size,bytes:this.totalBytes}}deleteKey($){let Z=this.store.get($);if(Z)this.store.delete($),this.totalBytes-=Z.bytes}key($,Z,Q,Y){return`${Z}:${WA4(Q)}:${$}:${le0(Y)}`}storeSet($,Z,Q,Y){let X;try{X=JSON.stringify(Z).length}catch{el("SKIP non-serializable",$);return}if(X>Y){el("SKIP oversize",$,`${X}b > cap ${Y}b`);return}this.deleteKey($);while(this.store.size>0&&(this.store.size>=this.maxEntries||this.totalBytes+X>this.maxTotalBytes)){let J=this.store.keys().next().value;if(J===void 0)break;this.deleteKey(J)}this.store.set($,{value:Z,storedAt:Q,bytes:X}),this.totalBytes+=X}async fetch($){let{type:Z,connectionId:Q,scope:Y,params:X,fetchLive:J,shouldCache:G,onRevalidation:W}=$,K=this.config[Z],H=this.key(Z,Q,Y,X),F=this.now(),U=this.store.get(H),N=U?F-U.storedAt:1/0;if(!U||N>K.maxStaleMs){g30.add(1,{type:Z,outcome:"miss"}),el(U?"EXPIRED":"MISS",H);let B=await J();if(G?.(B)??!0)this.storeSet(H,B,this.now(),K.maxValueBytes);else el("NOT-CACHED (shouldCache=false)",H);return B}if(this.store.delete(H),this.store.set(H,U),N>K.revalidateAfterMs&&!this.revalidating.has(H)){g30.add(1,{type:Z,outcome:"stale"}),el("STALE \u2192 serve + revalidate",H,`age=${N}ms`),this.revalidating.add(H);let B=J().then((O)=>{if(G?.(O)??!0)this.storeSet(H,O,this.now(),K.maxValueBytes)}).catch(()=>{g30.add(1,{type:Z,outcome:"error"})}).finally(()=>this.revalidating.delete(H));W?.(B)}else g30.add(1,{type:Z,outcome:"hit"}),el("HIT",H,`age=${N}ms`);return U.value}invalidate($){let Z=`${$}:`;for(let Q of[...this.store.keys()])if(Q.startsWith(Z))this.deleteKey(Q)}}function me0(){return E0().mcpCacheEnabled}function l30(){return me0()?ce0:null}var g30,h30=1024,MK$,YA4,XA4=2000,JA4,GA4,ce0;var ya=D(()=>{C6();F$();g30=z$.createCounter("mcp_read_cache.fetches",{description:"MCP read cache outcomes (hit, stale, miss, error)",unit:"{fetches}"}),MK$=h30*h30,YA4={"tools/call":{revalidateAfterMs:30000,maxStaleMs:300000,maxValueBytes:512*h30},"resources/read":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:4*MK$},"prompts/get":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:512*h30}},JA4=256*MK$,GA4=typeof process<"u"&&!!process.env?.MCP_CACHE_DEBUG;ce0=new u30;z$.createObservableGauge("mcp_read_cache.entries",{description:"Current entry count in the per-pod MCP read cache",unit:"{entries}"}).addCallback(($)=>$.observe(ce0.stats().entries));z$.createObservableGauge("mcp_read_cache.bytes",{description:"Approximate total bytes held in the per-pod MCP read cache",unit:"By"}).addCallback(($)=>$.observe(ce0.stats().bytes))});function SK$(){if(IK$)return;IK$=!0;try{VK$=z$.createCounter("virtual_mcp.aggregate_cache.lookups",{description:"Virtual MCP aggregate tool-list cache lookups by outcome (hit, miss, expired)",unit:"{lookups}"}),kK$=z$.createCounter("virtual_mcp.aggregate_cache.evictions",{description:"Virtual MCP aggregate tool-list cache entries dropped, by reason (capacity, invalidated, failed)",unit:"{entries}"}),z$.createObservableGauge("virtual_mcp.aggregate_cache.entries",{description:"Live entries in this pod's Virtual MCP aggregate tool-list cache",unit:"{entries}"}).addCallback(($)=>$.observe(GW.size))}catch($){console.error("[aggregate-cache] failed to register metrics:",$)}}function de0($){SK$(),VK$?.add(1,{outcome:$})}function ie0($,Z=1){if(Z<=0)return;SK$(),kK$?.add(Z,{reason:$})}function CK$($){return[$.virtualMcpId??"",$.userId??"",$.superUser?"su":"",[...$.connectionIds].sort().join(",")].join("|")}function _K$($){let Z=GW.get($);if(!Z)return de0("miss"),null;if(Date.now()-Z.at>=KA4)return GW.delete($),de0("expired"),null;return de0("hit"),Z.value}function vK$($,Z,Q){let Y=Q.catch((J)=>{if(GW.get($)?.value===Y)GW.delete($),ie0("failed");throw J});GW.delete($),GW.set($,{at:Date.now(),deps:Z,value:Y});let X=0;while(GW.size>HA4){let J=GW.keys().next();if(J.done)break;GW.delete(J.value),X++}return ie0("capacity",X),Y}function bK$($){let Z=0;for(let[Q,Y]of GW)if(Y.deps.includes($))GW.delete(Q),Z++;ie0("invalidated",Z)}var KA4=30000,HA4=500,GW,VK$=null,kK$=null,IK$=!1;var pe0=D(()=>{C6();GW=new Map});function yK$($){l30()?.invalidate($),RW$($),bK$($)}function $c($){yK$($);let Z=ne0?.();if(!Z)return;try{Z.publish(xK$,FA4.encode(JSON.stringify({connectionId:$,originId:fK$})))}catch(Q){console.warn("[McpCacheInvalidation] publish failed (non-critical):",Q)}}function gK$($){if(ne0=$,ga)return;let Z=$();if(!Z)return;ga=Z.subscribe(xK$),(async()=>{for await(let Q of ga)try{let Y=JSON.parse(UA4.decode(Q.data));if(Y.originId===fK$)continue;yK$(Y.connectionId)}catch{}})().catch(console.error)}function hK$(){ga?.unsubscribe(),ga=null,ne0=void 0}var xK$="studio.mcp-cache.invalidate",fK$,FA4,UA4,ne0,ga=null;var ha=D(()=>{ya();DJ();pe0();fK$=crypto.randomUUID(),FA4=new TextEncoder,UA4=new TextDecoder});import{z as te0}from"zod";function BA4($){let Z={...$};for(let Q of NA4)delete Z[Q];return Z}function OA4($,Z){return $.connection_url!==void 0?$.connection_url:Z}function wA4($,Z){return $.length===Z.length&&$.every((Q,Y)=>Q===Z[Y])}var NA4,DA4,LA4,oe0;var uK$=D(()=>{z30();iK();C0();F$();DJ();ha();_e0();UJ0();tH();NA4=["id","organization_id","created_by","created_at"];DA4=te0.object({id:te0.string().describe("ID of the connection to update"),data:L70.describe("Partial connection data to update")}),LA4=te0.object({item:eQ.describe("The updated connection entity")});oe0=d({name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update a connection's configuration. Re-fetches tools from the server on URL change.",annotations:{title:"Update Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:DA4,outputSchema:LA4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=p0(Z);if(!Y)throw Error("User ID required to update connection");let{id:X}=$,J=BA4($.data),G=J.configuration_state!==void 0||J.configuration_scopes!==void 0,W=await Z.storage.connections.findById(X);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let K=J.connection_type??W.connection_type,H=OA4(J,W.connection_url);if(K==="VIRTUAL"){let y=$h(H);if(!y)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let g=await Z.storage.virtualMcps.findById(y);if(!g)throw Error(`Virtual MCP not found: ${y}`);if(g.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=Zh(y)}let F=J.configuration_state??W.configuration_state??{},U=J.configuration_scopes??W.configuration_scopes??[];if(G){if(J.configuration_state!==void 0)F=J.configuration_state??{};else if(F===null||F===void 0)F={};if(J.configuration_scopes!==void 0)U=J.configuration_scopes??[];if(U.length>0){let y=F;Ra(y,U,Q.id),await Ma(y,U,Q.id,Z)}}if(K==="STDIO"&&!E0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let N=J.connection_token??W.connection_token;if(!N)try{let g=await new F9(Z.db,Z.vault).get(X);if(g?.accessToken)N=g.accessToken}catch{}let B=await $l({id:W.id,title:J.title??W.title,connection_type:K,connection_url:H,connection_token:N,connection_headers:J.connection_headers??W.connection_headers}).catch(()=>null),O=B?.tools?.length?B.tools:null,L=!1;if(J.configuration_scopes===void 0&&B?.scopes?.length)L=!wA4(U,B.scopes),U=B.scopes;if(Ra(F,U,Q.id),L&&U.length>0)await Ma(F,U,Q.id,Z);let w=G||L,j=w?qa(F,U):[],E=w?qa(W.configuration_state??{},W.configuration_scopes??[]):[],z=W.configuration_state,T=z==null||Object.keys(z).length===0,P,A,q=async()=>{try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:X,createdBy:Y,grants:E})}catch(y){console.error("Failed to restore credential grants after credential vault mutation failed",y)}},x={...J,connection_url:H,tools:null,configuration_state:F,configuration_scopes:U,updated_by:Y},_={...W,...x};if(w)try{if(await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:X,createdBy:Y,grants:j}),j.length>0){if(!await Z.storage.connectionCredentialVault.findActiveWorkloadToken({organizationId:Q.id,subjectConnectionId:X})){let{plaintextToken:g,record:l}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:Q.id,subjectConnectionId:X});A=l.id,P={baseUrl:Z.baseUrl,org:Q.slug??Q.id,subjectConnectionId:X,token:g}}}}catch(y){if(A)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:X,tokenId:A});throw await q(),y}if(w&&F&&U)try{await tl(Z,_,{state:F,scopes:U,firstRun:T,...P?{vault:P}:{}})}catch(y){if(console.error("Failed to invoke ON_MCP_CONFIGURATION callback",y),A)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:X,tokenId:A});if(j.length>0)throw await q(),y}let V;try{V=await Z.storage.connections.update(X,x)}catch(y){if(w){if(A)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:X,tokenId:A});await q()}throw y}if(O)GZ()?.set("tools",X,O).catch(()=>{});return $c(X),{item:V}}})});import{z as jA4}from"zod";var EA4,re0;var lK$=D(()=>{LJ();U6();C0();DJ();ha();WW();al();tH();EA4=va.extend({force:jA4.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),re0=d({name:"COLLECTION_CONNECTIONS_DELETE",description:"Permanently delete a connection. Set force=true to auto-remove from referencing Virtual MCPs.",annotations:{title:"Delete Connection",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:EA4,outputSchema:ba(eQ),handler:async($,Z)=>{a(Z);let Q=K0(Z);if(await Z.access.check(),JW()&&x30($.id,Q.id))throw Error("This connection is a fixed system connection and cannot be deleted");let Y=await Z.storage.connections.findById($.id);if(!Y)throw Error(`Connection not found: ${$.id}`);if(Y.organization_id!==Q.id)throw Error("Connection not found in organization");if(Y.metadata?.isFixed===!0)throw Error("This connection is a fixed system connection and cannot be deleted");let J=await Z.storage.virtualMcps.listByConnectionId(Q.id,$.id);if(J.length>0)if($.force)await Z.storage.virtualMcps.removeConnectionReferences($.id);else throw Error(JSON.stringify({code:"CONNECTION_IN_USE",agentNames:J.map((K)=>K.title)}));let G=await Z.storage.automations.listActiveByEventTriggerConnectionId($.id);if(G.length>0)if($.force)await Promise.all(G.map((K)=>Z.storage.automations.deactivateAutomation(K.id)));else throw Error(JSON.stringify({code:"CONNECTION_IN_USE_BY_AUTOMATION",automationNames:G.map((K)=>K.name)}));await Z.storage.connections.delete($.id),cK$($.id),await Z.storage.triggerCallbackTokens.deleteByConnection($.id,Q.id),GZ()?.invalidate($.id).catch(()=>{}),$c($.id);let W=p0(Z);if(W)v1.capture({distinctId:W,event:"connection_deleted",groups:{organization:Q.id},properties:{connection_id:Y.id,connection_type:Y.connection_type,app_name:Y.app_name??null,organization_id:Q.id,forced:$.force??!1}});return{item:Y}}})});import{z as Zc}from"zod";var se0;var mK$=D(()=>{C0();se0=d({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:Zc.object({id:Zc.string()}),outputSchema:Zc.object({id:Zc.string(),healthy:Zc.boolean(),latencyMs:Zc.number()}),handler:async($,Z)=>{let Q=K0(Z);await Z.access.check();let Y=await Z.storage.connections.findById($.id);if(!Y||Y.organization_id!==Q.id)throw Error("Connection not found");let X=await Z.storage.connections.testConnection($.id);return{id:$.id,...X}}})});var dK$=D(()=>{_W$();he0();ue0();uK$();lK$();mK$()});import{sql as L6}from"kysely";import{z as mF}from"zod";function iK$($){if($===null||$===void 0)return"NULL";if(typeof $==="number")return String($);if(typeof $==="boolean")return $?"TRUE":"FALSE";if(typeof $==="string")return`'${$.replace(/'/g,"''")}'`;if($ instanceof Date)return`'${$.toISOString()}'`;return`'${JSON.stringify($).replace(/'/g,"''")}'`}function AA4($,Z){let Q="",Y=0,X=!1,J=!1,G=!1,W=null;for(let K=0;K<$.length;K++){let H=$[K];if(!X&&!J&&W===null){if($.startsWith("--",K)){let F=$.indexOf(`
|
|
1010
1010
|
`,K),U=F===-1?$.slice(K):$.slice(K,F);Q+=U,K+=U.length-1;continue}if($.startsWith("/*",K)){let F=1,U=K+2;while(F>0&&U<$.length)if($.startsWith("/*",U))F++,U+=2;else if($.startsWith("*/",U))F--,U+=2;else U++;let N=$.slice(K,U);Q+=N,K+=N.length-1;continue}}if(W!==null){let F=`$${W}$`;if($.startsWith(F,K))Q+=F,K+=F.length-1,W=null;else Q+=H;continue}if(X&&G&&H==="\\"&&K+1<$.length){Q+=H+$[K+1],K+=1;continue}if(!J&&H==="'"){if(!X){let F=$[K-1],U=$[K-2]??"";G=(F==="e"||F==="E")&&!/[A-Za-z0-9_]/.test(U)}X=!X,Q+=H;continue}if(!X&&H==='"'){J=!J,Q+=H;continue}if(!X&&!J&&H==="$"){let F=/^\$(\d+)/.exec($.slice(K)),U=F?Number(F[1])-1:-1;if(F&&U>=0&&U<Z.length){Q+=iK$(Z[U]),K+=F[0].length-1;continue}let N=/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec($.slice(K));if(N){W=N[1]??"",Q+=N[0],K+=N[0].length-1;continue}}else if(!X&&!J&&H==="?"&&Y<Z.length){Q+=iK$(Z[Y]),Y++;continue}Q+=H}return Q}function pK$($){return $.replace(/-/g,"_")}function RA4($){return`app_${pK$($)}`}function qA4($){return`app_role_${pK$($)}`}function MA4($){if($ instanceof Error){let Z=$.message.toLowerCase(),Q=$.code;return Q==="3F000"||Q==="42704"||Q==="22023"||Z.includes("schema")&&Z.includes("does not exist")||Z.includes("role")&&Z.includes("does not exist")}return!1}async function IA4($,Z,Q){if(await L6`CREATE SCHEMA IF NOT EXISTS ${L6.id(Z)}`.execute($),!(await L6`
|
|
1011
1011
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
|
|
1012
1012
|
`.execute($)).rows[0]?.exists)await L6`CREATE ROLE ${L6.id(Q)} NOLOGIN`.execute($);await L6`GRANT ${L6.id(Q)} TO CURRENT_USER`.execute($),await L6`GRANT USAGE, CREATE ON SCHEMA ${L6.id(Z)} TO ${L6.id(Q)}`.execute($),await L6`GRANT ALL ON ALL TABLES IN SCHEMA ${L6.id(Z)} TO ${L6.id(Q)}`.execute($),await L6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${L6.id(Z)} TO ${L6.id(Q)}`.execute($),await L6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${L6.id(Z)} GRANT ALL ON TABLES TO ${L6.id(Q)}`.execute($),await L6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${L6.id(Z)} GRANT ALL ON SEQUENCES TO ${L6.id(Q)}`.execute($),await L6`REVOKE ALL ON SCHEMA public FROM ${L6.id(Q)}`.execute($)}async function VA4($,Z,Q,Y){try{return await $.transaction().execute(async(X)=>{return await L6`SET LOCAL ROLE ${L6.id(Q)}`.execute(X),await L6`SET LOCAL search_path TO ${L6.id(Z)}`.execute(X),await L6.raw(Y).execute(X)})}catch(X){if(MA4(X))return await IA4($,Z,Q),await $.transaction().execute(async(J)=>{return await L6`SET LOCAL ROLE ${L6.id(Q)}`.execute(J),await L6`SET LOCAL search_path TO ${L6.id(Z)}`.execute(J),await L6.raw(Y).execute(J)});throw X}}var PA4,TA4,nK$;var tK$=D(()=>{C0();PA4=mF.object({results:mF.array(mF.unknown()).optional(),success:mF.boolean().optional()});TA4=mF.object({sql:mF.string().describe("The SQL query to run"),params:mF.array(mF.unknown()).describe("The parameters to pass to the SQL query").optional()});nK$=d({name:"DATABASES_RUN_SQL",description:"Run a SQL query in a connection-scoped isolated schema. Supports SELECT, DDL, and DML.",annotations:{title:"Run SQL Query",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:TA4,outputSchema:mF.object({result:mF.array(PA4)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=AA4($.sql,$.params||[]);if(!Z.connectionId)throw Error("Connection context required for database access");console.warn("DATABASES_RUN_SQL invoked",{"tool.deprecation_probe":"DATABASES_RUN_SQL","connection.id":Z.connectionId,"organization.id":Z.organization?.id??null,"user.id":Z.auth.user?.id??null});let Y=RA4(Z.connectionId),X=qA4(Z.connectionId);return{result:[{results:(await VA4(Z.db,Y,X,Q)).rows,success:!0}]}}})});function c30($){let Z=$.access.getRole();if(!EZ(Z))throw new y7("Only organization owners and admins can change org-wide pin status")}var ae0=D(()=>{GY();BK()});async function m30($,Z,Q){let Y=[...new Set(Q)],X=await Promise.all(Y.map((G)=>$.storage.connections.findById(G,Z))),J=Y.filter((G,W)=>!X[W]);if(J.length>0)throw Error(`Connection not found: ${J.join(", ")}`)}function AB($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function d30($){let Z=2166136261;for(let Q=0;Q<$.length;Q++)Z=Math.imul(Z^$.charCodeAt(Q),16777619);return`a${(Z>>>0).toString(36).padStart(6,"0").slice(-6)}`}function i30($){if($&&typeof $==="object"&&"gatewayClientId"in $&&typeof $.gatewayClientId==="string")return $.gatewayClientId;return}function p30($,Z){if(!Z)return $;let Q=`${d30(Z)}_`;return $.startsWith(Q)?$.slice(Q.length):$}function SA4($){return $.split(/[-_]/).map((Z)=>Z?Z.charAt(0).toUpperCase()+Z.slice(1):Z).join(" ")}function CA4($,Z,Q){let Y,X=new Promise((J,G)=>{Y=setTimeout(()=>G(Error(Q)),Z)});return Promise.race([$,X]).finally(()=>clearTimeout(Y))}var IA;var oK$=D(()=>{tN();IA=class IA extends g7{static MAX_PAGES_PER_CLIENT=1000;static DEFAULT_LIST_TIMEOUT_MS=30000;clients;slugToKey=new Map;resolvedClients=new Map;toolsCache=null;resourcesCache=null;resourceTemplatesCache=null;promptsCache=null;resourceRouteMap=new Map;listTimeoutMs;constructor($,Z){super(Z?.clientInfo??{name:"gateway-client",version:"1.0.0"},{capabilities:Z?.capabilities});this.clients=$,this.listTimeoutMs=Z?.listTimeoutMs??IA.DEFAULT_LIST_TIMEOUT_MS;for(let Q of Object.keys($)){let Y=d30(Q);if(this.slugToKey.has(Y))throw Error(`GatewayClient: duplicate namespace code "${Y}" from keys "${this.slugToKey.get(Y)}" and "${Q}"`);this.slugToKey.set(Y,Q)}}namespace($,Z){return`${d30($)}_${Z}`}async resolveNamespacedTarget($,Z,Q){let Y=$.indexOf("_");if(Y!==-1){let X=$.slice(0,Y),J=this.slugToKey.get(X);if(J)return[J,$.slice(Y+1)]}for(let X of await Q()){let J=i30(X._meta);if(!J)continue;if(p30(X.name,J)===$)return[J,$]}if(Y===-1)throw Error(`GatewayClient: could not resolve ${Z} "${$}" \u2014 no namespace prefix and not found in any client`);throw Error(`GatewayClient: unknown namespace "${$.slice(0,Y)}" in "${$}" and not found by original name in any client`)}resolveToolTarget($){return this.resolveNamespacedTarget($,"tool",async()=>(await this.listTools()).tools)}resolvePromptTarget($){return this.resolveNamespacedTarget($,"prompt",async()=>(await this.listPrompts()).prompts)}resolveClient($){let Z=this.resolvedClients.get($);if(Z)return Z;let Q=this.clients[$];if(!Q)return Promise.reject(Error(`GatewayClient: unknown client key "${$}"`));let Y=Q.client,X;try{X=typeof Y==="function"?Promise.resolve(Y()):Promise.resolve(Y)}catch(G){return Promise.reject(G)}let J=X.catch((G)=>{throw this.resolvedClients.delete($),G});return this.resolvedClients.set($,J),J}getResolvedClient($){return this.resolveClient($)}async listFromClient($,Z,Q){try{return await CA4((async()=>{let Y=await this.resolveClient($);return await Z(Y)})(),this.listTimeoutMs,`timed out after ${this.listTimeoutMs}ms`)}catch(Y){return console.warn(`GatewayClient: skipping ${Q} from client "${$}" \u2014 ${Y?.message??Y}`),[]}}listFromAllClients($,Z){return Promise.all(Object.entries(this.clients).map(async([Q,Y])=>[Q,Y,await this.listFromClient(Q,(X)=>$(X,Q),Z)]))}async paginate($,Z,Q){let Y=[],X,J=0;do{let G=await Q(X);Y.push(...G.items),X=G.nextCursor,J++}while(X&&J<IA.MAX_PAGES_PER_CLIENT);if(X)console.warn(`GatewayClient: client "${$}" exceeded ${IA.MAX_PAGES_PER_CLIENT} pages listing ${Z} \u2014 truncating`);return Y}fetchAllTools($,Z){return this.paginate(Z,"tools",async(Q)=>{let Y=await $.listTools(Q?{cursor:Q}:void 0);return{items:Y.tools,nextCursor:Y.nextCursor}})}fetchAllResources($,Z){return this.paginate(Z,"resources",async(Q)=>{let Y=await $.listResources(Q?{cursor:Q}:void 0);return{items:Y.resources,nextCursor:Y.nextCursor}})}fetchAllResourceTemplates($,Z){return this.paginate(Z,"resource templates",async(Q)=>{let Y=await $.listResourceTemplates(Q?{cursor:Q}:void 0);return{items:Y.resourceTemplates,nextCursor:Y.nextCursor}})}fetchAllPrompts($,Z){return this.paginate(Z,"prompts",async(Q)=>{let Y=await $.listPrompts(Q?{cursor:Q}:void 0);return{items:Y.prompts,nextCursor:Y.nextCursor}})}listTools($,Z){if(!this.toolsCache)this.toolsCache=this.aggregateTools();return this.toolsCache}async aggregateTools(){let $=[],Z=await this.listFromAllClients((Q,Y)=>this.fetchAllTools(Q,Y),"tools");for(let[Q,Y,X]of Z){let J=Y.tools,G=J?new Set(J):null;for(let W of X){if(G&&!G.has(W.name))continue;$.push({...W,name:this.namespace(Q,W.name),_meta:{...W._meta??{},gatewayClientId:Q}})}}return{tools:$}}listResources($,Z){if(!this.resourcesCache)this.resourcesCache=this.aggregateResources();return this.resourcesCache}async aggregateResources(){let $=new Set,Z=[],Q=new Map,Y=await this.listFromAllClients((X,J)=>this.fetchAllResources(X,J),"resources");for(let[X,J,G]of Y){let W=J.resources,K=W?new Set(W):null;for(let H of G){if(K&&!K.has(H.uri)&&!(H.name&&K.has(H.name)))continue;if($.has(H.uri)){console.warn(`GatewayClient: duplicate resource "${H.uri}" from client "${X}" \u2014 skipping`);continue}$.add(H.uri),Q.set(H.uri,X),Z.push({...H,_meta:{...H._meta??{},gatewayClientId:X}})}}return this.resourceRouteMap=Q,{resources:Z}}listResourceTemplates($,Z){if(!this.resourceTemplatesCache)this.resourceTemplatesCache=this.aggregateResourceTemplates();return this.resourceTemplatesCache}async aggregateResourceTemplates(){let $=new Set,Z=[],Q=await this.listFromAllClients((Y,X)=>this.fetchAllResourceTemplates(Y,X),"resource templates");for(let[Y,X,J]of Q)for(let G of J){if($.has(G.uriTemplate)){console.warn(`GatewayClient: duplicate resource template "${G.uriTemplate}" from client "${Y}" \u2014 skipping`);continue}$.add(G.uriTemplate),Z.push({...G,_meta:{...G._meta??{},gatewayClientId:Y}})}return{resourceTemplates:Z}}listPrompts($,Z){if(!this.promptsCache)this.promptsCache=this.aggregatePrompts();return this.promptsCache}async aggregatePrompts(){let $=[],Z=await this.listFromAllClients((Q,Y)=>this.fetchAllPrompts(Q,Y),"prompts");for(let[Q,Y,X]of Z){let J=Y.prompts,G=J?new Set(J):null;for(let W of X){if(G&&!G.has(W.name))continue;$.push({...W,name:this.namespace(Q,W.name),title:W.title??SA4(W.name),_meta:{...W._meta??{},gatewayClientId:Q}})}}return{prompts:$}}async callTool($,Z,Q){let[Y,X]=await this.resolveToolTarget($.name);return(await this.resolveClient(Y)).callTool({...$,name:X},Z,Q)}async readResource($,Z){let Q=await this.resolveResourceRoute($.uri);return(await this.resolveClient(Q)).readResource($)}async getPrompt($,Z){let[Q,Y]=await this.resolvePromptTarget($.name);return(await this.resolveClient(Q)).getPrompt({...$,name:Y})}async resolveResourceRoute($){let Z=this.resourceRouteMap.get($);if(Z)return Z;if(this.resourcesCache=null,await this.listResources(),Z=this.resourceRouteMap.get($),Z)return Z;throw Error(`GatewayClient: resource "${$}" not found in any upstream client`)}getServerCapabilities(){return{tools:{},resources:{},prompts:{}}}getInstructions(){return}refresh(){this.toolsCache=null,this.resourcesCache=null,this.resourceTemplatesCache=null,this.promptsCache=null}async close(){let $=[...this.resolvedClients.values()].map((Z)=>Z.then((Q)=>Q.close()).catch(()=>{}));await Promise.allSettled($),await super.close()}}});var n30=D(()=>{oK$()});function $01($){return AB($)}function vA4($,Z){let Q=AB(Z)||"prompt";return`${String($).padStart(_A4,"0")}-${Q}`}async function Z01($,Z,Q){try{await $.delete(t30,$01(Z),{actor:Q})}catch(Y){console.error("[agent-prompts] failed to delete prompts",{agentId:Z,err:Y})}}async function o30($,Z,Q,Y){let X=$01(Z);await Z01($,Z,Q),await Promise.all(Y.slice(0,ee0).map(async(J,G)=>{let W=vA4(G,J.title),K={name:W,title:J.title,description:J.description,text:J.text};try{await $.write(t30,`${X}/${W}.json`,JSON.stringify(K),{actor:Q,contentType:"application/json"})}catch(H){console.error("[agent-prompts] failed to seed prompt",{agentId:Z,name:W,err:H})}}))}async function rK$($,Z){let Q=$01(Z),Y;try{Y=await $.listDir(t30,Q)}catch{return[]}let X=Y.filter((G)=>G.kind==="file"&&G.path.endsWith(".json")).slice(0,ee0),J=[];for(let G of X)try{let W=await $.read(t30,G.path),K=JSON.parse(new TextDecoder().decode(W));if(K&&typeof K.name==="string"&&typeof K.title==="string"&&typeof K.text==="string")J.push(K)}catch{}return J}var t30="agent-prompts",ee0=20,_A4;var ua=D(()=>{n30();_A4=String(ee0-1).length});function Qc($){if(!$)return $;let Z={...$};return delete Z.sandboxMap,Z}import{z as eK$}from"zod";function bA4(){let $=sK$[Math.floor(Math.random()*sK$.length)];return`icon://${aK$[Math.floor(Math.random()*aK$.length)]}?color=${$}`}var sK$,aK$,xA4,fA4,VA;var Q01=D(()=>{C0();qw();ae0();ua();sK$=["red","orange","amber","yellow","lime","green","emerald","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],aK$=["Star01","Zap","Heart","Globe01","Compass03","Lightbulb02","Rocket01","Flag01","BookOpen01","Shield01","Key01","Diamond01","Cube01","Target04","Award01","Briefcase01","Coffee","Feather","Hexagon01","Layers3_01","Map01","Palette","Package","Terminal"];xA4=eK$.object({data:j70.describe("Data for the new virtual MCP")}),fA4=eK$.object({item:$Y.describe("The created virtual MCP entity")}),VA=d({name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create a Virtual MCP (agent) that aggregates tools from multiple connections into one endpoint. Pass `prompts` to seed the agent with kickstart prompts (conversation starters shown as icebreakers). Author them from the agent's role/instructions and the descriptions of the tools it will have, so the starters are coherent and immediately useful.",annotations:{title:"Create Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:xA4,outputSchema:fA4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=p0(Z);if(!Y)throw Error("User ID required to create virtual MCP");if($.data.pinned===!0)c30(Z);let{prompts:X,metadata:J,...G}=$.data,W=Qc(J);if(G.connections.length>0)await m30(Z,Q.id,G.connections.map((F)=>F.connection_id));let K={...G,metadata:W,icon:G.icon??bA4()},H=await Z.storage.virtualMcps.create(Q.id,Y,K);if(X?.length&&Z.orgFs&&H.id)await o30(Z.orgFs,H.id,Y,X);return{item:H}}})});function Y01($){if(!$)return null;let Z=$.projects;return Array.isArray(Z)?Z:null}function dF($,Z){if($===null)return!0;if($.includes("*"))return!0;return $.includes(Z)}async function iF($){if($.auth.apiKey)return null;let Z=$.organization?.id;if(!Z)return null;let Q=$.access.getRole()??$.organization?.role??$.auth.user?.role;if(!Q||EZ(Q))return null;if($.auth.permissions&&$.auth.permissionsOrganizationId===Z)return Y01($.auth.permissions);let Y=await kA($.db,Z,Q);return Y01(Y)}var Yc=D(()=>{GY();pF()});function Vw($){return typeof $==="string"||typeof $==="number"}function X01($,Z){let Q=Z.split("."),Y=$;for(let X of Q){if(Y==null||typeof Y!=="object")return;Y=Y[X]}return Y}function yA4($,Z){return $.connections.some((Q)=>Q.connection_id===Z)}function r30($,Z){if("conditions"in Z){let{operator:W,conditions:K}=Z;if(K.length===0)return!0;switch(W){case"and":return K.every((H)=>r30($,H));case"or":return K.some((H)=>r30($,H));case"not":return!K.every((H)=>r30($,H));default:return!0}}let{field:Q,operator:Y,value:X}=Z,J=Q.join(".");if(J==="connection_id"){if(Y!=="eq"||typeof X!=="string")return!1;return yA4($,X)}let G=X01($,J);switch(Y){case"eq":return G===X;case"gt":return Vw(G)&&Vw(X)&&G>X;case"gte":return Vw(G)&&Vw(X)&&G>=X;case"lt":return Vw(G)&&Vw(X)&&G<X;case"lte":return Vw(G)&&Vw(X)&&G<=X;case"in":return Array.isArray(X)&&X.includes(G);case"like":if(typeof G!=="string"||typeof X!=="string")return!1;if(X.length>100)return!1;return rl(X).test(G);case"contains":if(typeof G!=="string"||typeof X!=="string")return!1;return G.toLowerCase().includes(X.toLowerCase());default:return!0}}function gA4($,Z){return[...$].sort((Q,Y)=>{for(let X of Z){let J=X.field.join("."),G=X01(Q,J),W=X01(Y,J),K=0;if(G==null&&W==null)continue;if(G==null)K=X.nulls==="first"?-1:1;else if(W==null)K=X.nulls==="first"?1:-1;else if(typeof G==="string"&&typeof W==="string")K=G.localeCompare(W);else if(typeof G==="number"&&typeof W==="number")K=G-W;else K=String(G).localeCompare(String(W));if(K!==0)return X.direction==="desc"?-K:K}return 0})}var hA4,uA4,SA;var J01=D(()=>{LJ();C0();Yc();qw();hA4=dK,uA4=zB($Y),SA=d({name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List all MCP virtual MCPs in the organization",annotations:{title:"List Virtual MCPs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:hA4,outputSchema:uA4,handler:async($,Z)=>{await Z.access.check();let Q=K0(Z),Y=$.where&&!("conditions"in $.where)&&$.where.field.join(".")==="connection_id"&&$.where.operator==="eq"&&typeof $.where.value==="string"?$.where.value:void 0,X=$.where&&!("conditions"in $.where)&&$.where.field.join(".")==="pinned"&&$.where.operator==="eq"&&typeof $.where.value==="boolean"?$.where.value:void 0,G=Y?await Z.storage.virtualMcps.listByConnectionId(Q.id,Y):await Z.storage.virtualMcps.list(Q.id,X!==void 0?{pinnedOnly:X}:void 0);if($.where)G=G.filter((B)=>r30(B,$.where));let W=await iF(Z);if(W!==null)G=G.filter((B)=>dF(W,B.id));if($.orderBy&&$.orderBy.length>0)G=gA4(G,$.orderBy);let K=G.length,H=$.offset??0,F=$.limit??100,U=G.slice(H,H+F),N=H+F<K;return{items:U,totalCount:K,hasMore:N}}})});import{z as G01}from"zod";var lA4,cA4,CA;var W01=D(()=>{C0();Yc();qw();lA4=G01.object({id:G01.string().describe("ID of the virtual MCP to retrieve")}),cA4=G01.object({item:$Y.nullable().describe("The retrieved virtual MCP, or null if not found")}),CA=d({name:"COLLECTION_VIRTUAL_MCP_GET",description:"Get a Virtual MCP's configuration, connections, and virtual tools by ID.",annotations:{title:"Get Virtual MCP",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:lA4,outputSchema:cA4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=await Z.storage.virtualMcps.findById($.id);if(Y&&Y.organization_id!==Q.id)return{item:null};if(!Y)return{item:null};let X=await iF(Z);if(!dF(X,Y.id))return{item:null};return{item:Y}}})});function WZ($){return K01.test($)}function la($){let Z=(Q)=>typeof Q==="string"?Q.trim().toLowerCase():"";return Z($?.metadata?.siteSlug)||Z($?.title)||null}function $H$($){let Z=typeof $?.metadata?.analyticsSiteSlug==="string"?$.metadata.analyticsSiteSlug.trim().toLowerCase():"";if(Z&&WZ(Z))return Z;return la($)}var K01;var fG=D(()=>{K01=/^[a-z0-9][a-z0-9-]{0,59}$/});function ZH$($){let{nextTitle:Z,currentTitle:Q,currentSiteSlug:Y}=$;if(Y?.trim())return null;if(Z===void 0||Z===Q)return null;let X=Q?.trim().toLowerCase()??"";return WZ(X)?X:null}var QH$=D(()=>{fG()});import{z as H01}from"zod";var mA4,dA4,_A;var F01=D(()=>{C0();Yc();ua();qw();ae0();QH$();mA4=H01.object({id:H01.string().describe("ID of the virtual MCP to update"),data:E70.describe("Partial virtual MCP data to update")}),dA4=H01.object({item:$Y.describe("The updated virtual MCP entity")}),_A=d({name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update a Virtual MCP's name, slug, connection list, or kickstart prompts. Pass `prompts` to replace the agent's conversation starters (full set; empty array clears them).",annotations:{title:"Update Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:mA4,outputSchema:dA4,handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let Y=p0(Z);if(!Y)throw Error("User ID required to update virtual MCP");let X=await Z.storage.virtualMcps.findById($.id);if(!X)throw Error(`Virtual MCP not found: ${$.id}`);if(X.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${$.id}`);let J=await iF(Z);if(!dF(J,X.id))throw Error(`Virtual MCP not found: ${$.id}`);let{prompts:G,metadata:W,...K}=$.data,H=Qc(W);if(H&&X.metadata)H={...X.metadata,...H};else if(H===null&&X.metadata?.sandboxMap)H={sandboxMap:X.metadata.sandboxMap};let F={...K,...W!==void 0?{metadata:H}:{}},U=ZH$({nextTitle:F.title,currentTitle:X.title,currentSiteSlug:X.metadata?.siteSlug});if(U)F.metadata={...X.metadata,...F.metadata,siteSlug:U};if(F.pinned!==void 0&&F.pinned!==X.pinned)c30(Z);if(F.connections?.length)await m30(Z,Q.id,F.connections.map((B)=>B.connection_id));let N=await Z.storage.virtualMcps.update($.id,Y,F);if(G!==void 0&&Z.orgFs)await o30(Z.orgFs,$.id,Y,G);return{item:N}}})});function N01($){if(!$)return!1;let Z=ca.join("|");return new RegExp(`permission\\s+"?(?:${Z})"?\\s+is not allowed`,"i").test($)||/permissions exceed what the github app/i.test($)}function YH$($){let Z={...$};for(let Q of ca)Z[Q]="read";return Z}async function XH$($,Z){let Q={...Z};for(;;){let Y=await $(Q);if(!Y.isError)return{result:Y,grantedPermissions:Q};let X=Y.content?.find((K)=>K.type==="text")?.text,J=ca.find((K)=>(K in Q));if(!J||!N01(X))return{result:Y,grantedPermissions:Q};let{[J]:G,...W}=Q;Q=W}}function iA4($){if(!$||typeof $!=="object"||Array.isArray($))return s30;let Z=$;if(Object.values(Z).some((Q)=>typeof Q!=="string"))return s30;return Z}function pA4($){if(typeof $!=="number"||!Number.isFinite($)||!Number.isInteger($)||$<=0)return;return $}function u9($){let Z=$.metadata?.repoScope;if(!Z||typeof Z.installationId!=="number"||!Number.isFinite(Z.installationId)||!Number.isInteger(Z.installationId)||Z.installationId<=0||typeof Z.owner!=="string"||typeof Z.repo!=="string"||Z.owner.length===0||Z.repo.length===0)return null;let Q=pA4(Z.repositoryId);return{sourceConnectionId:typeof Z.sourceConnectionId==="string"?Z.sourceConnectionId:void 0,installationId:Z.installationId,repositoryId:Q,owner:Z.owner,repo:Z.repo,permissions:iA4(Z.permissions),grantProvider:Z.grantProvider==="github-mcp"?"github-mcp":void 0}}function kw($){return $.metadata?.orgShared===!0}function JH$($){let Z=new Set,Q=[];for(let Y of $??[]){if(Y.status!=="active")continue;let X=u9(Y);if(X===null)continue;let J=U01(X.owner,X.repo);if(Z.has(J))continue;Z.add(J),Q.push(`${X.owner}/${X.repo}`)}return Q}function a30($,Z,Q){let Y=U01(Z,Q),X=($??[]).filter((J)=>{if(J.status&&J.status!=="active")return!1;let G=u9(J);return G!==null&&U01(G.owner,G.repo)===Y});return X.find(kw)??X[0]??null}var s30,ca,U01=($,Z)=>`${$}/${Z}`.toLowerCase();var wJ=D(()=>{s30={contents:"write",metadata:"read",pull_requests:"write",issues:"write",checks:"read",deployments:"read"},ca=["deployments","checks"]});function GH$($){return DQ($)!==null||M70($)!==null}var WH$=D(()=>{e8()});import{z as B01}from"zod";var nA4,tA4,vA;var O01=D(()=>{wJ();iK();C0();Yc();ua();qw();WH$();nA4=B01.object({id:B01.string().describe("ID of the virtual MCP to delete")}),tA4=B01.object({item:$Y.describe("The deleted virtual MCP entity")}),vA=d({name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Permanently delete a Virtual MCP and its virtual tools.",annotations:{title:"Delete Virtual MCP",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:nA4,outputSchema:tA4,handler:async($,Z)=>{a(Z);let Q=K0(Z);if(await Z.access.check(),GH$($.id))throw Error(`Virtual MCP not found: ${$.id}`);let Y=await Z.storage.virtualMcps.findById($.id);if(!Y)throw Error(`Virtual MCP not found: ${$.id}`);if(Y.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${$.id}`);let X=await iF(Z);if(!dF(X,Y.id))throw Error(`Virtual MCP not found: ${$.id}`);if(await Z.storage.virtualMcps.delete($.id),Z.orgFs)await Z01(Z.orgFs,$.id,p0(Z)??"system");let J=Y.metadata?.githubRepo?.connectionId;if(J)try{let G=await Z.storage.connections.findById(J,Q.id),W=G&&(kw(G)||(await Z.storage.virtualMcps.listByConnectionId(Q.id,J)).length>0||await Z.storage.connections.isReferencedByThread(J));if(G&&u9(G)&&!W){let H=await new F9(Z.db,Z.vault).get(J);if(H?.accessToken)try{await fetch("https://api.github.com/installation/token",{method:"DELETE",headers:{Authorization:`Bearer ${H.accessToken}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"},signal:AbortSignal.timeout(5000)})}catch{}await Z.storage.connections.delete(J)}}catch(G){console.error("[VIRTUAL_MCP_DELETE] failed to tear down repo-scoped connection",{childConnectionId:J,error:G.message})}return{item:Y}}})});function KH$($,Z){let Q=$!==null&&typeof $==="object"&&!Array.isArray($)?$:null;if(Z===void 0)return Q;return{...Q??{},...Z}}import{z as jX}from"zod";var oA4,bA;var D01=D(()=>{C0();Yc();qw();oA4=jX.object({connectionId:jX.string(),toolName:jX.string(),label:jX.string(),icon:jX.string().nullable().optional()}),bA=d({name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update the pinned sidebar views for a virtual MCP. Replaces all current pins.",annotations:{title:"Update Pinned Views",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:jX.object({virtualMcpId:jX.string().describe("Virtual MCP ID"),pinnedViews:jX.array(oA4).describe("Pinned views to set for the virtual MCP sidebar"),layout:jX.object({defaultMainView:jX.object({type:jX.string(),id:jX.string().optional(),toolName:jX.string().optional()}).nullable().optional(),chatDefaultOpen:jX.boolean().nullable().optional()}).optional()}),outputSchema:jX.object({item:$Y.nullable()}),handler:async($,Z)=>{a(Z);let Q=K0(Z);await Z.access.check();let{virtualMcpId:Y,pinnedViews:X,layout:J}=$,G=p0(Z),W=await Z.storage.virtualMcps.findById(Y);if(!W)throw Error(`Virtual MCP not found: ${Y}`);if(W.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${Y}`);let K=await iF(Z);if(!dF(K,W.id))throw Error(`Virtual MCP not found: ${Y}`);let H=W.metadata?.ui??{},F={...H,pinnedViews:X.length>0?X:null,layout:KH$(H.layout,J)};return{item:await Z.storage.virtualMcps.update(Y,G??"system",{metadata:{...W.metadata,ui:F}})}}})});import{z as TB}from"zod";var rA4,sA4,L01;var HH$=D(()=>{C0();rA4=TB.object({ids:TB.array(TB.string()).max(1000).describe("Virtual MCP ids to look up")}),sA4=TB.object({items:TB.array(TB.object({id:TB.string(),last_used_at:TB.string().optional(),last_used_by:TB.string().optional()}))}),L01=d({name:"VIRTUAL_MCP_LAST_USED_LIST",description:"Get last-used info (timestamp + user) for one or more virtual MCPs, derived from the most recent thread per agent.",annotations:{title:"List Virtual MCP Last Used",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:rA4,outputSchema:sA4,handler:async($,Z)=>{a(Z),K0(Z),await Z.access.check();let Q=await Z.storage.threads.findLastUsedByVirtualMcpIds($.ids);return{items:$.ids.map((Y)=>({id:Y,last_used_at:Q.get(Y)?.last_used_at,last_used_by:Q.get(Y)?.last_used_by}))}}})});var FH$=D(()=>{Q01();J01();W01();F01();O01();D01();HH$()});import{z as jY}from"zod";var w01;var UH$=D(()=>{C6();C0();w01=d({name:"MONITORING_HEATMAP",description:"Get tool-call volume broken down by agent and tool name, for spotting heavily-used tools per agent.",annotations:{title:"Get Tool-Call Heatmap",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:jY.object({startDate:jY.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:jY.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),virtualMcpIds:jY.array(jY.string()).max(100).optional().describe("Filter by specific agent (Virtual MCP) IDs"),excludeConnectionIds:jY.array(jY.string()).max(100).optional().describe("Exclude tool calls from these connection IDs"),limit:jY.number().int().min(1).max(1000).optional().describe("Max number of (agent, tool) cells to return")}),outputSchema:jY.object({cells:jY.array(jY.object({virtualMcpId:jY.string().nullable(),toolName:jY.string(),calls:jY.number(),errors:jY.number(),outputSize:jY.number().describe("Sum of tool-output character length \u2014 a proxy for context weight, not LLM token count")}))}),handler:async($,Z)=>{let Q=K0(Z);return await Z.access.check(),await fX(),Z.storage.monitoring.queryToolCallHeatmap({organizationId:Q.id,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,filters:{virtualMcpIds:$.virtualMcpIds,excludeConnectionIds:$.excludeConnectionIds},limit:$.limit})}})});import{z as U9}from"zod";var j01;var NH$=D(()=>{C6();C0();j01=d({name:"MONITORING_LOG_GET",description:"Get a single monitoring log by ID with full input and output data.",annotations:{title:"Get Monitoring Log",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:U9.object({id:U9.string().describe("Log ID to fetch")}),outputSchema:U9.object({log:U9.object({id:U9.string().optional(),organizationId:U9.string(),connectionId:U9.string(),toolName:U9.string(),input:U9.record(U9.string(),U9.unknown()),output:U9.record(U9.string(),U9.unknown()),isError:U9.boolean(),errorMessage:U9.string().nullish(),durationMs:U9.number(),timestamp:U9.string(),userId:U9.string().nullish(),requestId:U9.string(),userAgent:U9.string().nullish(),virtualMcpId:U9.string().nullish(),properties:U9.record(U9.string(),U9.string()).nullish()}).nullable().describe("The monitoring log, or null if not found")}),handler:async($,Z)=>{await Z.access.check(),await fX();let Q=K0(Z),Y=await Z.storage.monitoring.getById(Q.id,$.id);if(!Y)return{log:null};return{log:{...Y,timestamp:Y.timestamp instanceof Date?Y.timestamp.toISOString():Y.timestamp}}}})});import{z as m8}from"zod";var eA4,E01;var BH$=D(()=>{C6();C0();eA4=m8.object({id:m8.string().optional().describe("Unique log identifier"),organizationId:m8.string().describe("Organization ID"),connectionId:m8.string().describe("Connection ID"),toolName:m8.string().describe("Name of the tool that was called"),isError:m8.boolean().describe("Whether the call resulted in an error"),errorMessage:m8.string().nullish().describe("Error message if applicable"),durationMs:m8.number().describe("Call duration in milliseconds"),timestamp:m8.string().describe("ISO 8601 timestamp of the call"),userId:m8.string().nullish().describe("User who triggered the call"),requestId:m8.string().describe("Unique request identifier"),userAgent:m8.string().nullish().describe("Client identifier (x-studio-client header)"),virtualMcpId:m8.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:m8.record(m8.string(),m8.string()).nullish().describe("Custom key-value metadata attached to the log")}),E01=d({name:"MONITORING_LOGS_LIST",description:"List monitoring logs for tool calls with filtering and pagination.",annotations:{title:"List Monitoring Logs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:m8.object({connectionId:m8.string().optional().describe("Filter by connection ID"),excludeConnectionIds:m8.array(m8.string()).optional().describe("Exclude logs from these connection IDs (e.g. system connections)"),virtualMcpId:m8.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:m8.string().optional().describe("Filter by tool name"),isError:m8.boolean().optional().describe("Filter by error status"),startDate:m8.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:m8.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:m8.number().default(20).describe("Maximum number of results"),offset:m8.number().default(0).describe("Offset for pagination"),properties:m8.record(m8.string(),m8.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:m8.array(m8.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:m8.record(m8.string(),m8.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)"),propertyInValues:m8.record(m8.string(),m8.string()).optional().describe("Filter by exact match within comma-separated values (e.g., user_tags in 'Engineering')")}),outputSchema:m8.object({logs:m8.array(eA4).describe("Array of monitoring logs"),total:m8.number().describe("Total number of logs matching filters"),offset:m8.number().describe("Current offset for pagination"),limit:m8.number().describe("Current limit for pagination")}),handler:async($,Z)=>{await Z.access.check(),await fX();let Q=K0(Z),X=$.properties||$.propertyKeys||$.propertyPatterns||$.propertyInValues?{properties:$.properties,propertyKeys:$.propertyKeys,propertyPatterns:$.propertyPatterns,propertyInValues:$.propertyInValues}:void 0,J={organizationId:Q.id,connectionId:$.connectionId,excludeConnectionIds:$.excludeConnectionIds,virtualMcpId:$.virtualMcpId,toolName:$.toolName,isError:$.isError,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,limit:$.limit,offset:$.offset,propertyFilters:X},G=await Z.storage.monitoring.query(J);return{logs:G.logs.map(({input:W,output:K,...H})=>({...H,timestamp:H.timestamp instanceof Date?H.timestamp.toISOString():H.timestamp})),total:G.total,offset:$.offset,limit:$.limit}}})});import{z as V$}from"zod";var z01;var OH$=D(()=>{C6();C0();z01=d({name:"MONITORING_STATS",description:"Get aggregated statistics (counts, latency, error rates) for tool call monitoring.",annotations:{title:"Get Monitoring Stats",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:V$.object({startDate:V$.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:V$.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),interval:V$.string().regex(/^\d+[mhd]$/).optional().describe("Bucket interval for timeseries data (e.g. 1m, 5m, 2h, 1d). When provided, returns timeseries array."),connectionIds:V$.array(V$.string()).max(100).optional().describe("Filter by specific connection IDs (max 100)"),excludeConnectionIds:V$.array(V$.string()).max(100).optional().describe("Exclude specific connection IDs (max 100)"),toolNames:V$.array(V$.string()).max(100).optional().describe("Filter by specific tool names (max 100)"),status:V$.enum(["success","error"]).optional().describe("Filter metrics by execution status"),topN:V$.number().int().min(1).max(20).optional().describe("When provided with interval, also return top tools and their timeseries"),userIds:V$.array(V$.string()).max(100).optional().describe("Filter LLM usage by user IDs (only applied when llmUsage is true)"),llmUsage:V$.boolean().optional().describe("Aggregate LLM-call usage (tokens + USD cost) from raw log rows for the given connection. Returns token/cost totals and timeseries. Requires interval.")}),outputSchema:V$.object({totalCalls:V$.number().describe("Total number of tool calls"),errorRate:V$.number().optional().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:V$.number().describe("Average call duration in milliseconds"),errorRatePercent:V$.string().optional().describe("Error rate as a percentage string"),totalErrors:V$.number().optional().describe("Total number of errors"),p50DurationMs:V$.number().optional().describe("50th percentile duration in milliseconds"),p95DurationMs:V$.number().optional().describe("95th percentile duration in milliseconds"),connectionBreakdown:V$.array(V$.object({connectionId:V$.string(),calls:V$.number(),errors:V$.number(),errorRate:V$.number(),avgDurationMs:V$.number()})).optional().describe("Per-connection metric breakdown"),totalInputTokens:V$.number().optional().describe("Total input tokens (LLM usage mode)"),totalOutputTokens:V$.number().optional().describe("Total output tokens (LLM usage mode)"),totalTokens:V$.number().optional().describe("Total tokens (LLM usage mode)"),totalCostUsd:V$.number().optional().describe("Total USD cost (LLM usage mode; only non-zero for providers that report cost)"),topTools:V$.array(V$.object({toolName:V$.string(),connectionId:V$.string().nullable(),calls:V$.number(),inputTokens:V$.number().optional(),outputTokens:V$.number().optional(),costUsd:V$.number().optional()})).optional().describe("Top tools ranked by calls"),topToolsTimeseries:V$.array(V$.object({timestamp:V$.string(),toolName:V$.string(),calls:V$.number(),errors:V$.number(),avg:V$.number(),p95:V$.number()})).optional().describe("Per-tool metric timeseries for the top tools"),timeseries:V$.array(V$.object({timestamp:V$.string(),calls:V$.number(),errors:V$.number(),errorRate:V$.number(),avg:V$.number(),p50:V$.number(),p95:V$.number(),inputTokens:V$.number().optional(),outputTokens:V$.number().optional(),totalTokens:V$.number().optional(),costUsd:V$.number().optional()})).optional().describe("Timeseries data points bucketed by interval")}),handler:async($,Z)=>{let Q=K0(Z);if(await Z.access.check(),await fX(),$.interval&&$.llmUsage)return Z.storage.monitoring.queryLlmUsageStats({organizationId:Q.id,interval:$.interval,connectionId:$.connectionIds?.[0]??"decopilot",startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,userIds:$.userIds,topN:$.topN});if($.interval){let X=await Z.storage.monitoring.queryMetricTimeseries({organizationId:Q.id,interval:$.interval,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,filters:{connectionIds:$.connectionIds,excludeConnectionIds:$.excludeConnectionIds,toolNames:$.toolNames,status:$.status}});if(!$.topN)return X;let J=await Z.storage.monitoring.queryMetricTopToolsTimeseries({organizationId:Q.id,interval:$.interval,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0,topN:$.topN,filters:{connectionIds:$.connectionIds,excludeConnectionIds:$.excludeConnectionIds,toolNames:$.toolNames,status:$.status}});return{...X,topTools:J.topTools,topToolsTimeseries:J.timeseries}}let Y=await Z.storage.monitoring.getStats({organizationId:Q.id,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0});return{...Y,errorRatePercent:(Y.errorRate*100).toFixed(2)}}})});import{z as EX}from"zod";var P01;var DH$=D(()=>{C6();C0();P01=d({name:"MONITORING_THREAD_USAGE",description:"Aggregate LLM token usage and USD cost per thread for the given thread IDs.",annotations:{title:"Get Thread Usage",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:EX.object({threadIds:EX.array(EX.string()).min(1).max(500).describe("Thread IDs to aggregate usage for (max 500)"),connectionId:EX.string().optional().describe("LLM connection ID (defaults to 'decopilot')"),startDate:EX.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:EX.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:EX.object({items:EX.array(EX.object({threadId:EX.string(),calls:EX.number(),inputTokens:EX.number(),outputTokens:EX.number(),totalTokens:EX.number(),costUsd:EX.number()}))}),handler:async($,Z)=>{let Q=K0(Z);return await Z.access.check(),await fX(),{items:await Z.storage.monitoring.queryThreadUsage({organizationId:Q.id,connectionId:$.connectionId??"decopilot",threadIds:$.threadIds,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0})}}})});var LH$=D(()=>{UH$();NH$();BH$();OH$();DH$()});function e30($){return typeof $==="string"&&Z24.has($.trim().toLowerCase())}var Z24;var A01=D(()=>{Z24=new Set([".well-known","_admin","_users","api","auth","choose-editor","cli","commerce-onboarding","dbos-queue-depth","health","hosted-run-pending","login","mcp","metrics","oauth","oauth-proxy","onboarding","org","report","reports-onboarding","reset-password"])});import{z as yG}from"zod";var T01;var wH$=D(()=>{C0();A01();T01=d({name:"ORGANIZATION_CREATE",description:"Create a new organization. The caller becomes the owner automatically.",annotations:{title:"Create Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:yG.object({slug:yG.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens").refine(($)=>!e30($),"Slug is reserved by Studio"),name:yG.string().min(1).max(255),description:yG.string().max(500).optional()}),outputSchema:yG.object({id:yG.string(),name:yG.string(),slug:yG.string(),logo:yG.string().nullable().optional(),metadata:yG.any().optional(),createdAt:yG.string().datetime().describe("ISO 8601 timestamp"),members:yG.array(yG.any()).optional()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=p0(Z);if(!Q)throw Error("User ID required to create organization");let Y=await Z.boundAuth.organization.create({name:$.name,slug:$.slug,metadata:$.description?{description:$.description}:void 0,userId:Q});if(!Y)throw Error("Failed to create organization");return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt}}})});import{z as nF}from"zod";var R01;var jH$=D(()=>{C0();R01=d({name:"ORGANIZATION_LIST",description:"List organizations the current user belongs to.",annotations:{title:"List Organizations",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},_meta:{ui:{visibility:"app"}},inputSchema:nF.object({}),outputSchema:nF.object({organizations:nF.array(nF.object({id:nF.string(),name:nF.string(),slug:nF.string(),logo:nF.string().nullable().optional(),metadata:nF.any().optional(),createdAt:nF.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{if(a(Z),await Z.access.check(),!p0(Z))throw Error("User ID required to list organizations");return{organizations:(await Z.boundAuth.organization.list()).map((Y)=>({...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt}))}}})});import{z as KW}from"zod";var q01;var EH$=D(()=>{C0();q01=d({name:"ORGANIZATION_GET",description:"Get an organization's details, members, and settings by slug or ID.",annotations:{title:"Get Organization",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:KW.object({}),outputSchema:KW.object({id:KW.string(),name:KW.string(),slug:KW.string(),logo:KW.string().nullable().optional(),metadata:KW.any().optional(),createdAt:KW.string().datetime().describe("ISO 8601 timestamp"),members:KW.array(KW.any()).optional(),invitations:KW.array(KW.any()).optional()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.boundAuth.organization.get(Q);if(!Y)throw Error("No active organization found");let X=new Date,J=Y.invitations?.filter((G)=>new Date(G.expiresAt)>X);return{...Y,invitations:J,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt}}})});import{z as pK}from"zod";var M01;var zH$=D(()=>{C0();M01=d({name:"ORGANIZATION_UPDATE",description:"Update an organization's name or description.",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:pK.object({id:pK.string(),name:pK.string().min(1).max(255).optional(),description:pK.string().max(500).optional()}),outputSchema:pK.object({id:pK.string(),name:pK.string(),slug:pK.string(),logo:pK.string().nullable().optional(),metadata:pK.any().optional(),createdAt:pK.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{if(a(Z),await Z.access.check(),$.id!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Q={};if($.name)Q.name=$.name;if($.description!==void 0){let X=await Z.boundAuth.organization.get($.id);Q.metadata={...X?.metadata,description:$.description}}let Y=await Z.boundAuth.organization.update({organizationId:$.id,data:Q});if(!Y)throw Error("Failed to update organization");return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt}}})});import{sql as Q24}from"kysely";import{z as ma}from"zod";var I01;var PH$=D(()=>{C0();I01=d({name:"ORGANIZATION_DELETE",description:"Archive an organization (soft delete).",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:ma.object({id:ma.string()}),outputSchema:ma.object({success:ma.boolean(),id:ma.string()}),handler:async($,Z)=>{if(a(Z),await Z.access.check(),$.id!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Y=(await Z.boundAuth.organization.get($.id))?.metadata??{};if(Y.archived===!0)return{success:!0,id:$.id};return await Z.boundAuth.organization.update({organizationId:$.id,data:{metadata:{...Y,archived:!0,archivedAt:new Date().toISOString()}}}),await Q24`
|
|
1013
1013
|
update session set "activeOrganizationId" = null
|
|
1014
1014
|
where "activeOrganizationId" = ${$.id}
|
|
1015
|
-
`.execute(Z.db),{success:!0,id:$.id}}})});import{z as U$}from"zod";function VQ($,Z){let Q=$?.[Z];return X24.has(Z)?Q!==!1:Q===!0}function RH$($){let Z=$?.auto_resolve_conflicts;return typeof Z==="boolean"?Z:$?.auto_merge===!0}var qB=500,da,RB,AH$,Sw,ia,pa,TH$=50,Y24,na,ta,xA,X24,$W0=262144,J24=50,gG=500,G24=5000,Cw;var IZ=D(()=>{da=U$.object({title:U$.string().max(qB),url:U$.string().max(qB),icon:U$.string().max(qB)}),RB=U$.object({keyId:U$.string().max(qB),modelId:U$.string().max(qB),title:U$.string().max(qB).optional()}).nullable(),AH$=U$.enum(["fast","smart","thinking","image","web_search","deep_research"]),Sw=U$.enum(["fast","smart","thinking"]),ia=U$.object({tiers:U$.object({fast:RB,smart:RB,thinking:RB,image:RB,web_search:RB,deep_research:RB})}),pa=U$.object({tiers:U$.object({fast:RB.optional(),smart:RB.optional(),thinking:RB.optional()})}),Y24=/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/,na=U$.object({host:U$.string().min(1).max(qB).regex(Y24).describe("Git host, e.g. 'github.com' (bare hostname, no scheme)."),secretId:U$.string().min(1).max(qB).describe("Vault secret id holding the PAT used to authenticate this host.")}),ta=U$.object({ids:U$.array(U$.string().max(qB)).describe("Ordered list of custom virtual MCP agent ids to show on the home view.")}),xA=U$.object({home_task_intake_enabled:U$.boolean().optional().describe("Show Task mode on the Home composer and allow reports to start tasks."),demo_mode:U$.boolean().optional().describe("Curated demo org: the commerce connect modal proceeds without a configured required data source."),reports_only:U$.boolean().optional().describe("Curated commerce (reports) look: hides agent navigation, the home Customize button, and the Settings/Automations tabs. Defaulted on for orgs created by commerce onboarding."),reviewer_enabled:U$.boolean().optional().describe("Run the Reviewer on a task's pull request once it's In Review \u2014 it reviews the code with the repo's stack-appropriate skills, fixes what it finds on the PR's own branch, then exercises the change on the deploy preview and approves or hands the card to a human."),qa_agent_enabled:U$.boolean().optional().describe("Deprecated: see reviewer_enabled."),code_reviewer_enabled:U$.boolean().optional().describe("Deprecated: see reviewer_enabled."),auto_merge:U$.boolean().optional().describe("When the Reviewer approves a task's pull request, merge it automatically instead of leaving the merge to a human."),auto_resolve_conflicts:U$.boolean().optional().describe("When an approved pull request can't be merged because it conflicts with its base branch, hand it back to the Super Agent to resolve the conflict (check out the branch, merge the base, push). Unset, it follows `auto_merge`; set it explicitly to run one without the other."),cheap_reviewer_model:U$.boolean().optional().describe("Run the Reviewer on a cheaper model than the Super Agent that wrote the code. On by default \u2014 turning it off trades cost for some review depth."),coding_agent_org_mcps:U$.boolean().optional().describe("Give a coding-agent run (the claude-code harness in a sandbox) every MCP connection in the org as its own MCP server, on top of the narrow task-run surface it always gets. Off by default: each connection is one more server the agent connects to at session start, and all of their tools land in its context."),coding_agents_claude_code:U$.boolean().optional().describe("Run chats on a Code Agent (an agent imported from a GitHub repo) with the claude-code harness inside its sandbox, instead of hosted Decopilot. Off by default: it changes the runtime of every such chat, and claude-code flushes whole turns rather than streaming tokens."),auto_assign_report_tasks_to_super_agent:U$.boolean().optional().describe("When a report import creates a task board item without an assignee, delegate it to the Super Agent automatically instead of leaving it unassigned."),hosting_enabled:U$.boolean().optional().describe("Per-site Hosting tab (deployments, domains, deploy outcomes). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org. `HOSTING_CONTROL_PLANE_GA` opens it (and its peers) to every org at once."),deco_analytics_enabled:U$.boolean().optional().describe("Per-site Deco Analytics tab (traffic, realtime, usage & limits). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org. `HOSTING_CONTROL_PLANE_GA` opens it (and its peers) to every org at once."),e2e_enabled:U$.boolean().optional().describe("Per-site E2E tab (end-to-end test runs). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org. `HOSTING_CONTROL_PLANE_GA` opens it (and its peers) to every org at once."),experiments_enabled:U$.boolean().optional().describe("Per-site Experiments tab (A/B tests + variant results). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org."),monitor_enabled:U$.boolean().optional().describe("Per-site Monitor tab (CDN Performance + Audience from the stats-lake warehouse). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org. Its own deployment-wide switch `MONITOR_GA` opens it to every org at once (independent of the control-plane trio)."),delivery_lanes_enabled:U$.boolean().optional().describe("Board lanes for shipping: Approved, Merged and Post-deploy Validation sit between In Review and Done, and a merged pull request lands on Merged instead of Done. For teams whose release process continues after the merge. Off by default \u2014 with it off the board and the state machine behave exactly as if the lanes did not exist."),cms_auto_fresh_branch:U$.boolean().optional().describe("When a user opens the CMS on a branch whose last commit is older than the staleness window (2 days), move the session to a freshly minted branch cut from the default branch. The stale branch is left intact on GitHub. Off by default.")}),X24=new Set(["reviewer_enabled","cheap_reviewer_model"]);Cw=U$.object({id:U$.string().describe("Brand context ID"),name:U$.string().max(gG).describe("Company name"),domain:U$.string().max(gG).describe("Company domain (e.g. example.com)"),overview:U$.string().max(G24).describe("Company overview / description"),logo:U$.string().max(gG).nullable().optional().describe("Logo URL"),favicon:U$.string().max(gG).nullable().optional().describe("Favicon URL"),ogImage:U$.string().max(gG).nullable().optional().describe("OG image URL"),fonts:U$.object({heading:U$.string().max(gG).optional().describe("Font family for headings"),body:U$.string().max(gG).optional().describe("Font family for body text"),code:U$.string().max(gG).optional().describe("Font family for code / monospace")}).nullable().optional().describe("Font families by semantic role"),colors:U$.object({primary:U$.string().max(gG).optional().describe("Primary brand color (hex)"),secondary:U$.string().max(gG).optional().describe("Secondary brand color (hex)"),accent:U$.string().max(gG).optional().describe("Accent / highlight color (hex)"),background:U$.string().max(gG).optional().describe("Background color (hex)"),foreground:U$.string().max(gG).optional().describe("Foreground / text color (hex)")}).nullable().optional().describe("Semantic color palette"),images:U$.array(U$.record(U$.string(),U$.unknown())).max(J24).nullable().optional().refine(($)=>$===null||$===void 0||JSON.stringify($).length<=$W0,{message:`images must serialize to at most ${$W0} bytes`}).describe("Brand images"),metadata:U$.record(U$.string(),U$.unknown()).nullable().optional().refine(($)=>$===null||$===void 0||JSON.stringify($).length<=$W0,{message:`metadata must serialize to at most ${$W0} bytes`}).describe("Extra design tokens (typography, components, spacing, layout, tone, etc.)"),archivedAt:U$.string().nullable().optional().describe("Archive timestamp (null to unarchive)"),isDefault:U$.boolean().optional().describe("Whether this is the default brand for the organization")})});import{z as MB}from"zod";var V01;var qH$=D(()=>{C0();IZ();V01=d({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings including sidebar configuration, store registry settings, simple model mode, and default home agents.",annotations:{title:"Get Organization Settings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:MB.object({}),outputSchema:MB.object({organizationId:MB.string(),sidebar_items:MB.array(da).nullable().optional(),coding_agent_mcp_excluded:MB.array(MB.string()).nullable().optional(),simple_mode:ia.nullable().optional(),default_home_agents:ta.nullable().optional(),flags:xA.nullable().optional(),submodule_credentials:MB.array(na).nullable().optional(),createdAt:MB.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:MB.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.organizationSettings.get(Q);if(!Y)return{organizationId:Q};return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}})});import{z as k01}from"zod";var S01;var MH$=D(()=>{C0();S01=d({name:"ORGANIZATION_HAS_SITE",description:"Whether this organization owns at least one legacy deco.cx site. Boolean only \u2014 does not expose site slugs.",annotations:{title:"Has Owned Site",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:k01.object({}),outputSchema:k01.object({hasSite:k01.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return{hasSite:(await Z.storage.orgSites.listByOrg(Q.id)).length>0}}})});import{z as EY}from"zod";var W24=50,K24=100,H24=500,IH$=500,C01;var VH$=D(()=>{C0();IZ();C01=d({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings such as sidebar configuration, simple model mode, and default home agents.",annotations:{title:"Update Organization Settings",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:EY.object({organizationId:EY.string().min(1,"organizationId is required"),sidebar_items:EY.array(da).max(W24).optional(),coding_agent_mcp_excluded:EY.array(EY.string().max(IH$)).max(H24).optional().describe("Connection ids a coding-agent run must not mount, even with `coding_agent_org_mcps` on. Replaces the stored list; pass [] to clear it."),simple_mode:ia.optional(),default_home_agents:ta.extend({ids:EY.array(EY.string().max(IH$)).max(K24)}).optional(),flags:xA.strict().optional().describe("Org boolean toggles. Shallow-merged into the stored flags: keys you pass win (explicit false persists), omitted keys keep their value."),submodule_credentials:EY.array(na).max(TH$).refine(($)=>new Set($.map((Z)=>Z.host)).size===$.length,"Each git credential host must be unique.").optional().describe("Per-host PATs (as vault secret ids) every sandbox in the org installs in its git config. Replaces the stored list; pass [] to clear it.")}),outputSchema:EY.object({organizationId:EY.string(),sidebar_items:EY.array(da).nullable().optional(),coding_agent_mcp_excluded:EY.array(EY.string()).nullable().optional(),simple_mode:ia.nullable().optional(),default_home_agents:ta.nullable().optional(),flags:xA.nullable().optional(),submodule_credentials:EY.array(na).nullable().optional(),createdAt:EY.string().datetime().describe("ISO 8601 timestamp"),updatedAt:EY.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{if(a(Z),await Z.access.check(),K0(Z).id!==$.organizationId)throw Error("Cannot update settings for a different organization");let Y=await Z.storage.organizationSettings.upsert($.organizationId,{sidebar_items:$.sidebar_items,coding_agent_mcp_excluded:$.coding_agent_mcp_excluded,simple_mode:$.simple_mode,default_home_agents:$.default_home_agents,flags:$.flags,submodule_credentials:$.submodule_credentials});return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}})});import{z as nK}from"zod";var kH$,_01,v01;var SH$=D(()=>{C0();IZ();kH$=Cw.extend({organizationId:nK.string(),archivedAt:nK.string().nullable().optional().describe("ISO 8601 timestamp"),createdAt:nK.string().describe("ISO 8601 timestamp"),updatedAt:nK.string().describe("ISO 8601 timestamp")}),_01=d({name:"BRAND_CONTEXT_LIST",description:"List all brand contexts (company profiles) for the current organization.",annotations:{title:"List Brand Contexts",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:nK.object({includeArchived:nK.boolean().optional().describe("Include archived brands in the list")}),outputSchema:nK.object({items:nK.array(kH$)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return{items:(await Z.storage.brandContext.list(Q,{includeArchived:$.includeArchived})).map((X)=>({...X,archivedAt:X.archivedAt instanceof Date?X.archivedAt.toISOString():X.archivedAt,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}))}}}),v01=d({name:"BRAND_CONTEXT_GET",description:"Get a specific brand context by ID.",annotations:{title:"Get Brand Context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:nK.object({id:nK.string().describe("Brand context ID")}),outputSchema:kH$.extend({organizationId:nK.string()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.brandContext.get($.id,Q);if(!Y)throw Error("Brand context not found");return{...Y,archivedAt:Y.archivedAt instanceof Date?Y.archivedAt.toISOString():Y.archivedAt,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}})});import{z as fA}from"zod";var CH$,b01,x01,f01;var _H$=D(()=>{C0();IZ();CH$=Cw.extend({organizationId:fA.string(),createdAt:fA.string().describe("ISO 8601 timestamp"),updatedAt:fA.string().describe("ISO 8601 timestamp")}),b01=d({name:"BRAND_CONTEXT_CREATE",description:"Create a new brand context (company profile) for the current organization.",annotations:{title:"Create Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:Cw.omit({id:!0}),outputSchema:CH$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.brandContext.create(Q,{name:$.name,domain:$.domain,overview:$.overview,logo:$.logo??null,favicon:$.favicon??null,ogImage:$.ogImage??null,fonts:$.fonts??null,colors:$.colors??null,images:$.images??null,metadata:$.metadata??null});return{...Y,archivedAt:Y.archivedAt instanceof Date?Y.archivedAt.toISOString():Y.archivedAt,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}}),x01=d({name:"BRAND_CONTEXT_UPDATE",description:"Update an existing brand context by ID.",annotations:{title:"Update Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Cw.partial().required({id:!0}),outputSchema:CH$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(!await Z.storage.brandContext.get($.id,Q))throw Error("Brand context not found");let{id:X,...J}=$;if(J.isDefault===!0)await Z.storage.brandContext.setDefault(X,Q);let G=await Z.storage.brandContext.update(X,Q,{name:J.name,domain:J.domain,overview:J.overview,logo:J.logo!==void 0?J.logo??null:void 0,favicon:J.favicon!==void 0?J.favicon??null:void 0,ogImage:J.ogImage!==void 0?J.ogImage??null:void 0,fonts:J.fonts!==void 0?J.fonts??null:void 0,colors:J.colors!==void 0?J.colors??null:void 0,images:J.images!==void 0?J.images??null:void 0,metadata:J.metadata!==void 0?J.metadata??null:void 0,archivedAt:J.archivedAt!==void 0?J.archivedAt??null:void 0,isDefault:J.isDefault===!1?!1:void 0});return{...G,archivedAt:G.archivedAt instanceof Date?G.archivedAt.toISOString():G.archivedAt,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}),f01=d({name:"BRAND_CONTEXT_DELETE",description:"Archive a brand context by ID (soft delete).",annotations:{title:"Archive Brand Context",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:fA.object({id:fA.string().describe("Brand context ID")}),outputSchema:fA.object({success:fA.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(!await Z.storage.brandContext.get($.id,Q))throw Error("Brand context not found");return await Z.storage.brandContext.update($.id,Q,{archivedAt:new Date().toISOString(),isDefault:!1}),{success:!0}}})});async function ZW0($,Z,Q){let Y=$.trim();if(!Y.startsWith("http"))Y=`https://${Y}`;let X=await fetch("https://api.firecrawl.dev/v1/scrape",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify({url:Y,formats:["branding"]})});if(!X.ok){let N=await X.text().catch(()=>"");throw Error(`Firecrawl API error: ${X.status} ${N.slice(0,200)}`)}let J=await X.json();if(!J.success||!J.data?.branding)return null;let G=J.data.branding,W=J.data.metadata??{},K=N24(G,W);return{name:W.title?.split(/[|\u2013\u2014]|\s+-\s+/).map((N)=>N.trim()).filter(Boolean)?.slice().sort((N,B)=>N.length-B.length)[0]??W.ogSiteName??Q??$,domain:$,overview:W.description??"",logo:K.logo,favicon:K.favicon,ogImage:K.ogImage,fonts:K.fonts,colors:K.colors,images:null,metadata:Object.keys(K.metadata).length>0?K.metadata:null}}function N24($,Z){let Q=$.images??{},Y=$.colors??{},X={};for(let[F,U]of Object.entries(Y))if(typeof U==="string"&&U&&F24.has(F))X[F]=U;let J={},W=($.typography??{}).fontFamilies??{};for(let[F,U]of Object.entries(W))if(typeof U==="string"&&U){let N=U24[F.toLowerCase()];if(N&&!J[N])J[N]=U}let K=$.fonts;if(Array.isArray(K))for(let F of K){let U=F.family;if(typeof U==="string"&&U&&!J.body)J.body=U}let H={};for(let F of["typography","components","spacing","layout","animations","icons","tone","personality","colorScheme"])if($[F]!==void 0)H[F]=$[F];return{logo:Q.logo??null,favicon:Q.favicon??null,ogImage:Q.ogImage??Z.ogImage??null,fonts:Object.keys(J).length>0?J:null,colors:Object.keys(X).length>0?X:null,metadata:H}}var F24,U24;var y01=D(()=>{F24=new Set(["primary","secondary","accent","background","foreground"]),U24={heading:"heading",headings:"heading",head:"heading",title:"heading",body:"body",primary:"body",text:"body",code:"code",monospace:"code",mono:"code"}});import{z as QW0}from"zod";var B24,g01;var vH$=D(()=>{C0();y01();IZ();B24=Cw.pick({id:!0,name:!0,domain:!0,overview:!0,logo:!0,favicon:!0,ogImage:!0,fonts:!0,colors:!0}).extend({success:QW0.boolean()}),g01=d({name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context (colors, fonts, logos) from a website URL using Firecrawl.",annotations:{title:"Extract Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:QW0.object({domain:QW0.string().describe("Website domain to extract brand from"),brandId:QW0.string().optional().describe("Existing brand context ID to update (creates new if omitted)")}),outputSchema:B24,modelSummary:($)=>$.success?`Brand saved (id=${$.id}, name=${$.name}, domain=${$.domain}). The UI rendered the logo, colors, fonts, and overview.`:"Brand extraction failed.",handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=Z.firecrawlApiKey;if(!Y)throw Error("FIRECRAWL_API_KEY is not configured. Set the environment variable to enable brand extraction.");let X=await ZW0($.domain,Y,$.domain);if(!X)throw Error("Firecrawl did not return branding data for this URL");let J={name:X.name,domain:X.domain,overview:X.overview,logo:X.logo,favicon:X.favicon,ogImage:X.ogImage,fonts:X.fonts,colors:X.colors,images:X.images,metadata:X.metadata},G=$.brandId?await(async()=>{if(!await Z.storage.brandContext.get($.brandId,Q))throw Error("Brand context not found");return Z.storage.brandContext.update($.brandId,Q,J)})():await Z.storage.brandContext.create(Q,J);return{id:G.id,name:G.name,domain:G.domain,overview:G.overview,logo:G.logo,favicon:G.favicon,ogImage:G.ogImage,fonts:G.fonts,colors:G.colors,success:!0}}})});function bH$($){let Z=$.metadata??{};return{id:$.id,name:$.name,domain:$.domain||void 0,colors:$.colors??void 0,fonts:$.fonts??void 0,assets:$.logo||$.favicon||$.ogImage?{logo:$.logo??void 0,favicon:$.favicon??void 0,ogImage:$.ogImage??void 0}:void 0,overview:$.overview||void 0,tagline:typeof Z.tagline==="string"?Z.tagline:void 0,tone:typeof Z.tone==="string"?Z.tone:void 0,metadata:(()=>{let Q=Object.fromEntries(Object.entries(Z).filter(([Y])=>Y!=="tagline"&&Y!=="tone"));return Object.keys(Q).length>0?Q:void 0})()}}var h01,u01;var xH$=D(()=>{ge0();C0();h01=d({name:"BRAND_GET",description:"Get a brand context by ID. Omit the ID to get the default brand for the organization.",annotations:{title:"Get Brand",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:V30,outputSchema:Sa,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=$.id?await Z.storage.brandContext.get($.id,Q):await Z.storage.brandContext.getDefault(Q);if(!Y)throw Error($.id?"Brand not found":"No default brand configured");return bH$(Y)}}),u01=d({name:"BRAND_LIST",description:"List all active brands for the current organization.",annotations:{title:"List Brands",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:k30,outputSchema:S30,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return{items:(await Z.storage.brandContext.list(Q)).map(bH$)}}})});import{resolveTxt as O24}from"dns/promises";function l01($){return`${D24}.${$.toLowerCase()}`}function fH$(){return`deco-verify-${crypto.randomUUID().replace(/-/g,"")}`}async function yH$($,Z,Q=O24){if(!Z)return!1;try{return(await Q(l01($))).some((X)=>X.join("").trim()===Z)}catch{return!1}}var D24="_deco-verify";var gH$=()=>{};import{z as M9}from"zod";function _w($){let Z=$.verificationStatus==="pending"&&Boolean($.verificationToken);return{id:$.id,domain:$.domain,joinMode:$.joinMode,verificationStatus:$.verificationStatus,verificationMethod:$.verificationMethod,verifiedAt:$.verifiedAt?new Date($.verifiedAt).toISOString():null,recordName:Z?l01($.domain):null,recordValue:Z?$.verificationToken:null}}function w24($){let Z=$.toLowerCase().trim();if(!L24.test(Z))throw Error(`Invalid domain format: "${Z}". Must be a valid domain like "acme.com"`);if(tK.has(Z))throw Error(`Cannot claim generic email domain "${Z}". Only corporate domains are allowed.`);return Z}var L24,c01,YW0,m01,d01,i01,p01,n01;var hH$=D(()=>{hG();gH$();C0();L24=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/,c01=M9.enum(["off","auto","request"]),YW0=M9.object({id:M9.string(),domain:M9.string(),joinMode:c01,verificationStatus:M9.enum(["pending","verified"]),verificationMethod:M9.enum(["email","dns"]).nullable(),verifiedAt:M9.string().nullable(),recordName:M9.string().nullable(),recordValue:M9.string().nullable()});m01=d({name:"ORGANIZATION_DOMAIN_LIST",description:"List the email domains claimed by an organization.",annotations:{title:"List Organization Domains",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:M9.object({}),outputSchema:M9.object({domains:M9.array(YW0)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return{domains:(await Z.storage.organizationDomains.listByOrganizationId(Q.id)).map(_w)}}}),d01=d({name:"ORGANIZATION_DOMAIN_ADD",description:"Claim an email domain for an organization. If the caller's verified email matches the domain it is trusted immediately; otherwise it requires DNS verification.",annotations:{title:"Add Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:M9.object({domain:M9.string().min(1).max(255).describe("Domain to claim, e.g. acme.com"),joinMode:c01.optional().describe("Initial join mode (only applied when the domain is trusted immediately via email match).")}),outputSchema:YW0,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=w24($.domain),J=Z.auth.user?.email?.split("@")[1]?.toLowerCase(),G=Boolean(Z.auth.user?.emailVerified)&&J===Y,W=await Z.storage.organizationDomains.getByOrgAndDomain(Q.id,Y);if(W){if(W.verificationStatus!=="verified"&&G){let H=await Z.storage.organizationDomains.markVerified(W.id,"email");return _w(H)}return _w(W)}let K=G?await Z.storage.organizationDomains.add(Q.id,Y,{joinMode:$.joinMode??"off",verificationStatus:"verified",verificationMethod:"email"}):await Z.storage.organizationDomains.add(Q.id,Y,{joinMode:"off",verificationStatus:"pending",verificationToken:fH$()});return _w(K)}}),i01=d({name:"ORGANIZATION_DOMAIN_UPDATE",description:"Set the join mode for a claimed domain. Discoverable modes (auto/request) require the domain to be verified.",annotations:{title:"Update Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:M9.object({id:M9.string(),joinMode:c01}),outputSchema:YW0,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationDomains.getById($.id);if(!Y||Y.organizationId!==Q.id)throw Error("Domain not found");if($.joinMode!=="off"&&Y.verificationStatus!=="verified")throw Error("Verify the domain before enabling auto-join or requests.");let X=await Z.storage.organizationDomains.updateJoinMode($.id,$.joinMode);return _w(X)}}),p01=d({name:"ORGANIZATION_DOMAIN_VERIFY",description:"Check the DNS TXT record for a pending domain and mark it verified if present.",annotations:{title:"Verify Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:M9.object({id:M9.string()}),outputSchema:M9.object({verified:M9.boolean(),domain:YW0}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationDomains.getById($.id);if(!Y||Y.organizationId!==Q.id)throw Error("Domain not found");if(Y.verificationStatus==="verified")return{verified:!0,domain:_w(Y)};if(!Y.verificationToken)throw Error("Domain has no pending DNS verification.");if(!await yH$(Y.domain,Y.verificationToken))return{verified:!1,domain:_w(Y)};let J=await Z.storage.organizationDomains.markVerified($.id,"dns");return{verified:!0,domain:_w(J)}}}),n01=d({name:"ORGANIZATION_DOMAIN_REMOVE",description:"Remove a claimed domain from an organization.",annotations:{title:"Remove Organization Domain",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:M9.object({id:M9.string()}),outputSchema:M9.object({success:M9.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationDomains.getById($.id);if(!Y||Y.organizationId!==Q.id)throw Error("Domain not found");return await Z.storage.organizationDomains.removeById($.id),{success:!0}}})});function vw($){return($ instanceof Error?$.message.toLowerCase():"").includes("already a member")}import{z as VZ}from"zod";var j24,t01,o01,r01;var uH$=D(()=>{C0();U6();j24=VZ.object({id:VZ.string(),userId:VZ.string(),status:VZ.enum(["pending","approved","denied"]),createdAt:VZ.string(),user:VZ.object({id:VZ.string(),name:VZ.string(),email:VZ.string(),image:VZ.string().nullable()}).nullable()}),t01=d({name:"ORGANIZATION_JOIN_REQUEST_LIST",description:"List pending requests to join the organization.",annotations:{title:"List Join Requests",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:VZ.object({}),outputSchema:VZ.object({requests:VZ.array(j24)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return{requests:(await Z.storage.organizationJoinRequests.listPendingWithUser(Q.id)).map((X)=>({id:X.id,userId:X.userId,status:X.status,createdAt:new Date(X.createdAt).toISOString(),user:X.user}))}}}),o01=d({name:"ORGANIZATION_JOIN_REQUEST_APPROVE",description:"Approve a pending join request, adding the user as a member.",annotations:{title:"Approve Join Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:VZ.object({requestId:VZ.string()}),outputSchema:VZ.object({success:VZ.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationJoinRequests.getById($.requestId);if(!Y||Y.organizationId!==Q.id)throw Error("Join request not found");if(Y.status!=="pending")throw Error("Join request has already been decided");let X=p0(Z);if(!await Z.storage.organizationJoinRequests.decide(Y.id,"approved",X??Y.userId))return{success:!0};try{await Z.boundAuth.organization.addMember({organizationId:Q.id,userId:Y.userId,role:["user"]})}catch(G){if(!vw(G))throw G}if(X)v1.capture({distinctId:X,event:"organization_join_request_approved",groups:{organization:Q.id},properties:{organization_id:Q.id,user_id:Y.userId}});return{success:!0}}}),r01=d({name:"ORGANIZATION_JOIN_REQUEST_DENY",description:"Deny a pending join request.",annotations:{title:"Deny Join Request",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:VZ.object({requestId:VZ.string()}),outputSchema:VZ.object({success:VZ.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationJoinRequests.getById($.requestId);if(!Y||Y.organizationId!==Q.id)throw Error("Join request not found");if(Y.status!=="pending")throw Error("Join request has already been decided");let X=p0(Z);if(await Z.storage.organizationJoinRequests.decide(Y.id,"denied",X??Y.userId)&&X)v1.capture({distinctId:X,event:"organization_join_request_denied",groups:{organization:Q.id},properties:{organization_id:Q.id,user_id:Y.userId}});return{success:!0}}})});import{z as jJ}from"zod";var s01;var lH$=D(()=>{U6();C0();GY();s01=d({name:"ORGANIZATION_MEMBER_ADD",description:"Invite a member to the organization by email with an assigned role.",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:jJ.object({organizationId:jJ.string().optional(),userId:jJ.string(),role:jJ.array(jJ.string())}),outputSchema:jJ.object({id:jJ.string(),organizationId:jJ.string(),userId:jJ.string(),role:jJ.union([jJ.string(),jJ.array(jJ.string())]),createdAt:jJ.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=$.organizationId||Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(Q!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Y=await Z.db.selectFrom("member").select(["role"]).where("userId","=",p0(Z)??"").where("organizationId","=",Q).executeTakeFirst();if(!gQ0(Y?.role,$.role))throw Error(`Insufficient privileges to assign role "${$.role.join(",")}"`);let X=await Z.boundAuth.organization.addMember({organizationId:Q,userId:$.userId,role:$.role});if(!X)throw Error("Failed to add member");let J=p0(Z);if(J)v1.capture({distinctId:J,event:"organization_member_added",groups:{organization:Q},properties:{organization_id:Q,added_user_id:$.userId,role:$.role}});return{...X,role:X.role,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});import{z as Xc}from"zod";var a01;var cH$=D(()=>{U6();C0();a01=d({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from the organization. Revokes all their access immediately.",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Xc.object({organizationId:Xc.string().optional(),memberIdOrEmail:Xc.string()}),outputSchema:Xc.object({success:Xc.boolean(),memberIdOrEmail:Xc.string()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=$.organizationId||Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(Q!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Y=await Z.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:$.memberIdOrEmail});Z.invalidateMemberRole?.(Y.member.userId,Q);let X=p0(Z);if(X)v1.capture({distinctId:X,event:"organization_member_removed",groups:{organization:Q},properties:{organization_id:Q,member_id_or_email:$.memberIdOrEmail}});return{success:!0,memberIdOrEmail:$.memberIdOrEmail}}})});import{z as zY}from"zod";var e01;var mH$=D(()=>{C0();e01=d({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in the organization with their roles.",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:zY.object({limit:zY.number().int().min(1).max(1000).optional(),offset:zY.number().int().min(0).optional()}),outputSchema:zY.object({members:zY.array(zY.object({id:zY.string(),organizationId:zY.string(),userId:zY.string(),role:zY.string(),createdAt:zY.string().datetime().describe("ISO 8601 timestamp"),user:zY.object({id:zY.string(),name:zY.string(),email:zY.string(),image:zY.string().optional()}).optional()}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return{members:((await Z.boundAuth.organization.listMembers({organizationId:Q,limit:$.limit,offset:$.offset}))?.members??[]).map((J)=>({...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}))}}})});import{z as p7}from"zod";var $11;var dH$=D(()=>{U6();C0();GY();$11=d({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Change a member's role (e.g., admin, member) within the organization.",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:p7.object({organizationId:p7.string().optional(),memberId:p7.string(),role:p7.array(p7.string())}),outputSchema:p7.object({id:p7.string(),organizationId:p7.string(),userId:p7.string(),role:p7.union([p7.string(),p7.array(p7.string())]),createdAt:p7.string().datetime().describe("ISO 8601 timestamp"),user:p7.object({email:p7.string(),name:p7.string(),image:p7.string().optional()})}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=$.organizationId||Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(Q!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Y=await Z.db.selectFrom("member").select(["role"]).where("userId","=",p0(Z)??"").where("organizationId","=",Q).executeTakeFirst();if(!gQ0(Y?.role,$.role))throw Error(`Insufficient privileges to assign role "${$.role.join(",")}"`);if(!$.role.includes("owner")){if((await Z.db.selectFrom("member").select(["role"]).where("id","=",$.memberId).where("organizationId","=",Q).executeTakeFirst())?.role.split(",").includes("owner")){if((await Z.db.selectFrom("member").select(["role"]).where("organizationId","=",Q).execute()).filter((H)=>H.role.split(",").includes("owner")).length<=1)throw Error("Cannot remove the organization's last owner. Assign another owner first.")}}let X=await Z.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:$.memberId,role:$.role});if(!X)throw Error("Failed to update member role");Z.invalidateMemberRole?.(X.userId,Q);let J=p0(Z);if(J)v1.capture({distinctId:J,event:"organization_member_role_updated",groups:{organization:Q},properties:{organization_id:Q,member_id:$.memberId,target_user_id:X.userId,new_role:Array.isArray($.role)?$.role.join(","):$.role}});return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});async function iH$(){if(oa&&Date.now()-oa.fetchedAt<600000)return oa.rate;try{let Z=await(await fetch("https://economia.awesomeapi.com.br/json/last/USD-BRL",{signal:AbortSignal.timeout(5000)})).json(),Q=parseFloat(Z.USDBRL?.bid??"");if(Number.isNaN(Q)||Q<=0)throw Error("Invalid rate");return oa={rate:Q,fetchedAt:Date.now()},Q}catch{return oa?.rate??5.5}}function pH$($,Z,Q){if(Z==="brl")return Math.round($/Q);return $}var oa=null;function Z11($,Z="",Q=new URLSearchParams){for(let[Y,X]of Object.entries($)){if(X===void 0||X===null)continue;let J=Z?`${Z}[${Y}]`:Y;if(Array.isArray(X))X.forEach((G,W)=>{if(typeof G==="object"&&G!==null)Z11(G,`${J}[${W}]`,Q);else Q.append(`${J}[${W}]`,String(G))});else if(typeof X==="object")Z11(X,J,Q);else Q.append(J,String(X))}return Q}async function IB($,Z){let Q=E0().stripeSecretKey;if(!Q)throw new kZ(503,"billing is not configured");let Y=Z?.params?Z11(Z.params).toString():void 0,X=await fetch(`${E24}${$}`,{method:Z?.method??(Y?"POST":"GET"),headers:{Authorization:`Bearer ${Q}`,...Y&&{"Content-Type":"application/x-www-form-urlencoded"},...Z?.idempotencyKey&&{"Idempotency-Key":Z.idempotencyKey}},body:Y,signal:AbortSignal.timeout(z24)}),J=await X.json().catch(()=>({}));if(!X.ok){let G=J.error?.message??`HTTP ${X.status}`;throw new kZ(X.status,G)}return J}function nH$($){return{billing_address_collection:"required",custom_fields:[{key:P24,label:{type:"custom",custom:"CPF / CNPJ"},type:"text",optional:!1,text:{minimum_length:A24,maximum_length:T24}}],...$&&{customer_update:{address:"auto",name:"auto"}}}}function tH$($){return Boolean((E0().stripePlanPriceIds??{})[$])}function Q11($){let Z=E0().stripePlanPriceIds??{};return Object.entries(Z).find(([,Q])=>Q===$)?.[0]}function R24($){return["checkout",$.organizationId,$.planId??"flat",$.lastStripeEventAt?.getTime()??0].join(":")}async function oH$($){let Z=E0(),Q=$.planId?Q11($.planId):Z.stripeOrgPriceId;if(!Q)throw new kZ(503,$.planId?`plan '${$.planId}' has no Stripe price configured`:"billing is not configured");let Y=await IB("/checkout/sessions",{idempotencyKey:R24({organizationId:$.organizationId,...$.planId?{planId:$.planId}:{},...$.lastStripeEventAt!==void 0&&{lastStripeEventAt:$.lastStripeEventAt}}),params:{mode:"subscription",...nH$(null),line_items:[{price:Q,quantity:1}],success_url:$.successUrl,cancel_url:$.cancelUrl,metadata:{orgId:$.organizationId,...$.planId?{planId:$.planId}:{}},subscription_data:{billing_cycle_anchor_config:{day_of_month:1,hour:0,minute:0,second:0},metadata:{orgId:$.organizationId,...$.planId?{planId:$.planId}:{}}}}});if(!Y.url)throw new kZ(500,"checkout session lacks url");return{url:Y.url}}function q24($,Z){return Math.round($*(1+Z/100))}function I24($){let Z=Math.floor(($.nowMs??Date.now())/M24);return["topup",$.organizationId,$.currency,$.amountCents,Z].join(":")}async function rH$($){let Z=q24($.amountCents,$.feePercent),Q=pH$($.amountCents,$.currency,await iH$()),Y=E0().stripeTopupProductId,X={kind:"topup",orgId:$.organizationId,creditCents:Q},J=$.currency==="brl"?`Studio AI credits (R$ ${($.amountCents/100).toFixed(2)})`:`Studio AI credits ($${($.amountCents/100).toFixed(2)})`,G=await IB("/checkout/sessions",{idempotencyKey:I24({organizationId:$.organizationId,amountCents:$.amountCents,currency:$.currency}),params:{mode:"payment",...$.customerId&&{customer:$.customerId},...nH$($.customerId),line_items:[{quantity:1,price_data:{currency:$.currency,unit_amount:Z,...Y?{product:Y}:{product_data:{name:J}}}}],success_url:$.successUrl,cancel_url:$.cancelUrl,metadata:X,payment_intent_data:{metadata:X}}});if(!G.url)throw new kZ(500,"checkout session lacks url");return{url:G.url}}async function XW0($){let Z=await IB("/billing_portal/sessions",{params:{customer:$.customerId,return_url:$.returnUrl}});if(!Z.url)throw new kZ(500,"portal session lacks url");return{url:Z.url}}async function sH$($){let Z=await IB("/billing_portal/sessions",{params:{customer:$.customerId,return_url:$.returnUrl,...E0().stripePortalConfigurationId&&{configuration:E0().stripePortalConfigurationId},flow_data:{type:"subscription_update_confirm",subscription_update_confirm:{subscription:$.subscriptionId,items:[{id:$.subscriptionItemId,price:$.priceId}]},after_completion:{type:"redirect",redirect:{return_url:$.returnUrl}}}}});if(!Z.url)throw new kZ(500,"portal session lacks url");return{url:Z.url}}async function aH$($){return IB(`/prices/${encodeURIComponent($)}`)}async function bw($){return IB(`/subscriptions/${encodeURIComponent($)}`)}async function eH$($){await IB(`/subscriptions/${encodeURIComponent($)}`,{method:"DELETE"})}async function $F$($){let Z=await IB(`/invoices?subscription=${encodeURIComponent($)}&status=paid&limit=100`),Q=V24($,Z.data??[]);for(let Y of Q)await IB("/refunds",{params:{payment_intent:Y.paymentIntent,reason:"duplicate"},idempotencyKey:Y.idempotencyKey});return{refundedCents:Q.reduce((Y,X)=>Y+X.amountCents,0)}}function V24($,Z){let Q=[];for(let Y of Z){let X=Y.amount_paid??0;if(X<=0)continue;let J=typeof Y.payment_intent==="string"?Y.payment_intent:Y.payment_intent?.id;if(!J)continue;Q.push({paymentIntent:J,amountCents:X,idempotencyKey:`orphan-refund:${$}:${Y.id??J}`})}return Q}var E24="https://api.stripe.com/v1",kZ,z24=15000,P24="taxid",A24=11,T24=18,M24=120000;var VB=D(()=>{F$();kZ=class kZ extends Error{status;constructor($,Z){super(`Stripe API ${$}: ${Z}`);this.status=$;this.name="StripeApiError"}}});import{z as JW0}from"zod";async function k24($){if(!$.planId)throw Error("This organization already has an active subscription.");let Z=Q11($.planId);if(!Z)throw new kZ(503,`plan '${$.planId}' has no Stripe price configured`);let Q=await bw($.subscriptionId),Y=(Q.items?.data??[]).filter((G)=>G.price?.id?tH$(G.price.id):!1),X=Y[0];if(Y.length>1)throw Error("This organization's subscription has more than one plan line \u2014 change it in Stripe, not here.");if(!X?.id)throw new kZ(500,"subscription has no plan line to move to another price");if(X.price?.id===Z)throw Error("This organization is already on that plan.");let{url:J}=await sH$({customerId:Q.customer,subscriptionId:$.subscriptionId,subscriptionItemId:X.id,priceId:Z,returnUrl:$.returnUrl});return J}var Y11;var ZF$=D(()=>{VB();E9();C0();U6();Y11=d({name:"ORGANIZATION_BILLING_CHECKOUT_START",description:"Start the organization's subscription: creates a Stripe Checkout session and returns its URL.",annotations:{title:"Start Billing Checkout",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},inputSchema:JW0.object({planId:JW0.string().optional()}),outputSchema:JW0.object({url:JW0.string()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id,Y=Z.organization?.slug;if(!Q||!Y)throw Error("Organization context required");let X=await Z.storage.organizationBilling.getBilling(Q),J=`${x5()}${Rw(Y,"members")}`;if(X?.status==="active"&&X.stripeSubscriptionId){let W=await k24({subscriptionId:X.stripeSubscriptionId,planId:$.planId,returnUrl:`${J}?checkout=updated`});return QJ({event:"subscription_plan_change_started",organizationId:Q,...$.planId?{properties:{plan_id:$.planId}}:{},...Z.auth?.user?.id?{userId:Z.auth.user.id}:{}}),{url:W}}if(X?.status==="active")throw Error("This organization already has an active subscription.");if(X?.stripeSubscriptionId)throw Error("This organization still has a subscription on file \u2014 settle or cancel it before starting a new checkout.");let{url:G}=await oH$({organizationId:Q,successUrl:`${J}?checkout=success`,cancelUrl:`${J}?checkout=canceled`,...$.planId?{planId:$.planId}:{},lastStripeEventAt:X?.lastStripeEventAt??null});return QJ({event:"subscription_checkout_started",organizationId:Q,...$.planId?{properties:{plan_id:$.planId}}:{},...Z.auth?.user?.id?{userId:Z.auth.user.id}:{}}),{url:G}}})});import{z as xw}from"zod";async function v24(){if(ra&&Date.now()-ra.at<ra.ttlMs)return ra.prices;let $=new Set,Z=Object.entries(E0().stripePlanPriceIds??{}).filter(([,J])=>{if($.has(J))return!1;return $.add(J),!0}),Y=(await Promise.all(Z.map(async([J,G])=>{try{let W=await aH$(J);if(W.unit_amount===null)return null;return{planId:G,amountCents:W.unit_amount,currency:W.currency,interval:W.recurring?.interval??null}}catch(W){return console.warn(`plan price ${J} (${G}) unreadable:`,W instanceof kZ?W.message:W),null}}))).filter((J)=>J!==null),X=Y.length===Z.length;return ra={at:Date.now(),prices:Y,ttlMs:X?C24:_24},Y}var S24,C24=600000,_24=30000,ra=null,X11;var QF$=D(()=>{VB();C0();F$();S24=xw.object({planId:xw.string(),amountCents:xw.number(),currency:xw.string(),interval:xw.string().nullable()});X11=d({name:"ORGANIZATION_BILLING_PLAN_PRICES",description:"The monthly price of each purchasable plan, read from Stripe. Empty when no plan prices are configured.",annotations:{title:"Plan Prices",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:xw.object({}),outputSchema:xw.object({prices:xw.array(S24)}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{prices:await v24()}}})});import{z as J11}from"zod";var G11;var YF$=D(()=>{VB();E9();C0();G11=d({name:"ORGANIZATION_BILLING_PORTAL",description:"Open the organization's Stripe billing portal (manage card, invoices, cancellation). Returns the portal URL.",annotations:{title:"Open Billing Portal",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},inputSchema:J11.object({}),outputSchema:J11.object({url:J11.string()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);if(!Q.slug)throw Error("Organization context required");let Y=await Z.storage.organizationBilling.getBilling(Q.id);if(!Y?.stripeCustomerId)throw Error("This organization has no billing account yet \u2014 subscribe first.");try{return await XW0({customerId:Y.stripeCustomerId,returnUrl:`${x5()}${Rw(Q.slug,"members")}`})}catch(X){if(X instanceof kZ)throw Error(X.message);throw X}}})});function GW0($){return W11[$%W11.length]??b24}function PY($){return $.createdBy==="system"}function f24($){if($?.reviewer_enabled===void 0&&$?.qa_agent_enabled===!1&&$?.code_reviewer_enabled===!1)return!1;return VQ($,"reviewer_enabled")}function kB($){return f24($)?HW:[]}function y24($){return VQ($,"delivery_lanes_enabled")}function oF($){return y24($)?"merged":"done"}function yw($,Z){if(!$)return!1;return[tF[Z],...x24].some((Q)=>$.startsWith(`${Q}:`))}function SB($,Z){if(Z)return new Date(Z).getTime();let Q=0;for(let Y of $){if(Y.action!=="status_changed")continue;if(Y.data?.to!=="in_review")continue;Q=Math.max(Q,new Date(Y.occurredAt).getTime())}return Q}function gw($,Z){let Q=SB($,Z.cycleStartedAt),Y=new Map;for(let X of $){if(X.action!=="review_approved"&&X.action!=="review_changes_requested")continue;if(new Date(X.occurredAt).getTime()<Q)continue;let J=X.data??{};if(J.reviewer!=="reviewer")continue;if(X.action==="review_approved"){if(Z?.verifiedOnly&&J.verified!==!0)continue;Y.set("reviewer","approved")}else Y.set("reviewer","changes_requested")}return Y}function fw($,Z,Q){if(Z.length===0)return!1;let Y=gw($,Q);return Z.every((X)=>Y.get(X)==="approved")}function GF$($,Z,Q){return fw($,Z,Q)&&!fw($,Z,{...Q,verifiedOnly:!0})}function WF$($){let Z=null;for(let Q of $){if(Q.action!=="review_approved"&&Q.action!=="review_changes_requested")continue;let Y=new Date(Q.occurredAt).getTime();if(Z&&Y<Z.at)continue;let X=Q.data?.notes;Z={at:Y,notes:Q.action==="review_changes_requested"&&typeof X==="string"?X:null}}return Z?.notes??null}function NF$($,Z=Date.now()){if($.state!==null&&$.state!=="open")return!1;if($.state===null)return!0;if($.checksStatus==="pending")return!0;if($.previewUrl!==null)return!1;let Q=$.updatedAt?Date.parse($.updatedAt):Number.NaN;return Number.isFinite(Q)&&Z-Q<g24}var j8="super-agent",W11,b24,sa='Your checkout is SHALLOW (`git clone --depth 1`), so it has no merge base and `git diff main...HEAD` (three dots) fails with "fatal: main...HEAD: no merge base". To see a branch diff, either use the two-dot form against the fetched remote ref (`git fetch origin <base> && git diff origin/<base> HEAD`), or deepen first with `git fetch --deepen=100`. Same for `git log main..HEAD` and anything else that needs shared history.',XF$,K11="chore",HW,tF,x24,aa="NO VISUAL SURFACE",oK,T$,JF$,WW0,KF$="task-board.item.updated",HF$="task-board.item.deleted",FF$="task-board.item.prs.updated",UF$=4000,g24=600000;var C4=D(()=>{IZ();W11=["#9ca3af","#ef4444","#f97316","#f59e0b","#22c55e","#3b82f6","#a855f7","#ec4899"],b24=W11[0];XF$="Read the diff with `gh pr diff <number>`. It comes from the API, so it needs no fetch, no merge base, and is unaffected by the shallow checkout. "+"Read it ONCE \u2014 `gh pr diff <number> --name-only` first if you need to size "+"it, then pull the hunks you need per FILE. Do NOT re-run the diff sliced by directory: each slice re-reads bytes you already have into every remaining turn's context, and it is the largest avoidable cost in a review.",HW=["reviewer"],tF={reviewer:"Reviewer"},x24=["QA Agent","Code Reviewer"];oK=["triage","todo","in_progress","in_review","approved","merged","post_deploy_validation","done","archived"],T$={intake:"triage",queue:"todo",progress:"in_progress",review:"in_review",archive:"archived"},JF$=oK.map(($,Z)=>({key:$,title:$,position:Z})),WW0=["approved","merged","post_deploy_validation"]});function H11($){return $==="trial"?"trial":"subscription"}function ea($,Z,Q,Y={}){QJ({event:Z,organizationId:Q.organizationId,...$.auth?.user?.id?{userId:$.auth.user.id}:{},properties:{task_id:Q.id,...Y}})}function F11($){return $?.status==="active"||$?.status==="past_due"}function KW0($,Z){if(F11($))return{periodKey:$?.currentPeriodEnd?`sub:${$.currentPeriodEnd.toISOString()}`:"sub:pending",limit:$?.monthlyTaskExecutions??Z.monthlyTaskExecutions,exhaustedReason:"monthly_exhausted"};return{periodKey:"trial",limit:$?.freeTaskExecutions??Z.freeTaskExecutions,exhaustedReason:"trial_exhausted"}}function $e(){let $=E0();return{enforced:$.taskQuotaEnforced,freeTaskExecutions:$.freeTaskExecutions,monthlyTaskExecutions:$.monthlyTaskExecutions,maxRunsPerTask:$.maxRunsPerTask}}function hw(){return{...$e(),maxRunsPerTask:Number.POSITIVE_INFINITY}}async function Jc($,Z,Q=$e()){if(!Q.enforced||!PY(Z))return;let Y=await $.storage.organizationBilling.taskClaim(Z.id);if(Y&&Y.runCount>=Q.maxRunsPerTask)throw ea($,"task_quota_blocked",Z,{phase:"precheck",reason:"runs_exhausted"}),new zX("runs_exhausted");if(Y&&Y.state!=="released")return;let X=await $.storage.organizationBilling.getBilling(Z.organizationId),J=KW0(X,Q);if(await $.storage.organizationBilling.countTaskClaims(Z.organizationId,J.periodKey)>=J.limit)throw ea($,"task_quota_blocked",Z,{phase:"precheck",reason:J.exhaustedReason,billing_mode:H11(J.periodKey),limit:J.limit}),new zX(J.exhaustedReason)}async function BF$($,Z,Q=$e()){if(!Q.enforced||!PY(Z))return"skipped";let Y=await $.storage.organizationBilling.getBilling(Z.organizationId),X=KW0(Y,Q),J=await $.storage.organizationBilling.claimTaskUnderLimit(Z.organizationId,Z.id,X.periodKey,X.limit,Q.maxRunsPerTask);if(J==="exhausted")throw ea($,"task_quota_blocked",Z,{phase:"claim",reason:X.exhaustedReason,billing_mode:H11(X.periodKey),limit:X.limit}),new zX(X.exhaustedReason);if(J==="runs_exhausted")throw ea($,"task_quota_blocked",Z,{phase:"claim",reason:"runs_exhausted"}),new zX("runs_exhausted");if(J==="claimed")ea($,"task_quota_claimed",Z,{billing_mode:H11(X.periodKey),period_key:X.periodKey,limit:X.limit});return J}async function OF$($,Z,Q,Y){if(Y==="skipped")return;await $.rollbackTaskClaim(Z,Q,{releaseSlot:Y==="claimed"}).catch((X)=>console.error("[task-quota] rollback failed (stays charged)",X))}async function DF$($,Z){let Q=await $.storage.organizationBilling.taskClaim(Z);return!!Q&&Q.state!=="released"}async function LF$($,Z,Q){if(await $.releaseTaskClaim(Z,Q).catch((X)=>{return console.error("[task-quota] refund failed (stays charged)",X),!1}))QJ({event:"task_quota_refunded",organizationId:Z,properties:{task_id:Q}})}var h24="[SUBSCRIPTION_REQUIRED]",u24,zX;var FW=D(()=>{C4();U6();F$();u24={trial_exhausted:"this organization used its free task executions \u2014 subscribe to keep running tasks",monthly_exhausted:"this organization used its monthly task executions \u2014 more become available next billing cycle",runs_exhausted:"this task reached its execution limit \u2014 create a new task to keep going"};zX=class zX extends Error{reason;constructor($){super(`${h24} ${u24[$]}`);this.reason=$;this.name="TaskQuotaError"}}});import{z as CB}from"zod";var U11;var wF$=D(()=>{C0();FW();U11=d({name:"ORGANIZATION_TASK_QUOTA_GET",description:"Get the organization's auto-task quota: how many runs are used in the current period, the limit, and the subscription's billing status.",annotations:{title:"Get Task Quota",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:CB.object({}),outputSchema:CB.object({enforced:CB.boolean(),billingStatus:CB.string(),subscribed:CB.boolean(),hasBillingAccount:CB.boolean(),used:CB.number(),limit:CB.number(),currentPeriodEnd:CB.string().datetime().nullable()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=$e(),X=await Z.storage.organizationBilling.getBilling(Q.id),J=KW0(X,Y),G=await Z.storage.organizationBilling.countTaskClaims(Q.id,J.periodKey);return{enforced:Y.enforced,billingStatus:X?.status??"none",subscribed:F11(X),hasBillingAccount:!!X?.stripeCustomerId,used:G,limit:J.limit,currentPeriodEnd:X?.currentPeriodEnd?.toISOString()??null}}})});var jF$=D(()=>{wH$();jH$();EH$();zH$();PH$();qH$();MH$();VH$();SH$();_H$();vH$();xH$();hH$();uH$();lH$();cH$();mH$();dH$();ZF$();QF$();YF$();wF$()});function UW($){let Z=$?.status;return typeof Z==="number"?Z:null}function EF$($){let Z=$;if(Z?.isRateLimited!==!0)return;return typeof Z.retryAfterMs==="number"?Z.retryAfterMs:null}async function EJ($,Z){let Q=await $.getBranch(Z);if(Q)return Q.sha;throw new y0({provider:$.repo.provider,status:404,message:`Branch ${Z} does not exist in ${$.repo.path}`})}var t6;var Ze=D(()=>{w5();t6=class t6 extends Error{constructor($,Z){super($,Z);this.name="RepoWriteConflict"}}});function Gc($){if($.length===0)return null;let Z=!1;for(let Q of $){if(Q.state!=="completed"){Z=!0;continue}if(Q.conclusion&&c24.has(Q.conclusion))return"failing"}return Z?"pending":"passing"}var c24,yA;var Qe=D(()=>{c24=new Set(["failure","cancelled","timed_out","action_required"]);yA=class yA extends Error{existing;constructor($,Z){super($);this.name="ChangeRequestExists",this.existing=Z}}});function Wc($){return m24.test($.trim())}function SZ($,Z,Q){if($===void 0||!Number.isFinite($)||$<=0)return Math.min(Z,Q);return Math.min(Math.floor($),Q)}async function Kc($,Z){let Q=$.headers.get("content-length"),Y=Q===null?Number.NaN:Number(Q),X=Number.isFinite(Y)&&Y>=0?Y:null,J=$.body;if(!J)return{content:"",size:X??0,truncated:!1};let G=J.getReader(),W=[],K=0,H=!1;try{for(;;){let{done:U,value:N}=await G.read();if(U)break;if(!N)continue;let B=Z-K;if(N.byteLength>=B){W.push(N.subarray(0,B)),K+=B,H=N.byteLength>B||!(await G.read()).done;break}W.push(N),K+=N.byteLength}}finally{await G.cancel().catch(()=>{})}return{content:new TextDecoder().decode(d24(W,K)),size:X??K,truncated:H||X!==null&&X>K}}function d24($,Z){let Q=new Uint8Array(Z),Y=0;for(let X of $)Q.set(X,Y),Y+=X.byteLength;return Q}function uG($){return $.split("/").map(encodeURIComponent).join("/")}function N11($){let Z=Number($);return Number.isInteger(Z)&&Z>1?Z:1}var uw=400,_B=2000,lw=60000,vB=200000,cw=50,mw=50,rK=100,m24;var Hc=D(()=>{m24=/\[bot\]$|[-_.]bot$|^bot[-_.]|^(dependabot|renovate)$/i});var rF;var B11=D(()=>{rF={name:"Deco Bot",email:"114028756+decobot@users.noreply.github.com"}});import{sql as i24}from"kysely";function zF$($){return $ instanceof Date?$.toISOString():String($)}function Ye($){let Z=$.installation_id===null||$.installation_id===void 0?null:Number($.installation_id);return{id:$.id,organizationId:$.organization_id,type:$.type,host:$.host,authKind:$.auth_kind,externalAccountId:$.external_account_id,login:$.login,avatarUrl:$.avatar_url,installationId:Number.isFinite(Z)?Z:null,status:$.status,installationAuthorizedBy:$.installation_authorized_by??null,installationRepositoryIds:$.installation_repository_ids??null,credentialConnectionId:$.credential_connection_id,connectedBy:$.connected_by_name?{name:$.connected_by_name}:null,createdAt:zF$($.created_at),updatedAt:zF$($.updated_at)}}class gA{db;constructor($){this.db=$}async upsert($){let Z=new Date,Q=await this.db.insertInto("git_provider_accounts").values({organization_id:$.organizationId,type:$.type,host:$.host.toLowerCase(),auth_kind:$.authKind,external_account_id:$.externalAccountId,login:$.login,avatar_url:$.avatarUrl??null,installation_id:$.installationId??null,installation_authorized_by:$.installationAuthorizedBy??null,installation_repository_ids:$.installationRepositoryIds?JSON.stringify($.installationRepositoryIds):null,credential_connection_id:null,status:"active",created_by:$.createdBy??null}).onConflict((Y)=>Y.columns(["organization_id","host","external_account_id"]).doUpdateSet({type:$.type,auth_kind:$.authKind,login:$.login,avatar_url:$.avatarUrl??null,installation_id:$.installationId??null,installation_authorized_by:$.installationAuthorizedBy??null,installation_repository_ids:$.installationRepositoryIds?JSON.stringify($.installationRepositoryIds):null,credential_connection_id:null,status:"active",updated_at:i24`GREATEST(${Z}, git_provider_accounts.updated_at + interval '1 millisecond')`})).returningAll().executeTakeFirstOrThrow();return Ye(Q)}async get($,Z){let Q=await this.db.selectFrom("git_provider_accounts").selectAll().where("id","=",$).where("organization_id","=",Z).executeTakeFirst();return Q?Ye(Q):null}async getUnscoped($){let Z=await this.db.selectFrom("git_provider_accounts").selectAll().where("id","=",$).executeTakeFirst();return Z?Ye(Z):null}async listByOrg($){return(await this.db.selectFrom("git_provider_accounts").leftJoin("user as connector","connector.id","git_provider_accounts.created_by").selectAll("git_provider_accounts").select("connector.name as connected_by_name").where("git_provider_accounts.organization_id","=",$).orderBy("git_provider_accounts.created_at","asc").execute()).map(Ye)}async findByExternalId($){let Z=await this.db.selectFrom("git_provider_accounts").selectAll().where("organization_id","=",$.organizationId).where("host","=",$.host.toLowerCase()).where("external_account_id","=",$.externalAccountId).executeTakeFirst();return Z?Ye(Z):null}async setStatus($,Z,Q){await this.db.updateTable("git_provider_accounts").set({status:Q,updated_at:new Date}).where("id","=",$).where("organization_id","=",Z).execute()}async delete($,Z){return(await this.db.deleteFrom("git_provider_accounts").where("id","=",$).where("organization_id","=",Z).executeTakeFirst()).numDeletedRows>0n}}var HW0=()=>{};class Xe{db;vault;constructor($,Z){this.db=$;this.vault=Z}async get($){let Z=await this.db.selectFrom("git_provider_account_credentials").selectAll().where("account_id","=",$).executeTakeFirst();if(!Z)return null;return p24(this.vault,Z)}async upsert($){let Z=new Date,Q=await this.vault.encrypt($.accessToken),Y=$.refreshToken?await this.vault.encrypt($.refreshToken):null,X=$.clientSecret?await this.vault.encrypt($.clientSecret):null;await this.db.insertInto("git_provider_account_credentials").values({account_id:$.connectionId,access_token:Q,refresh_token:Y,scope:$.scope,expires_at:$.expiresAt,client_id:$.clientId,client_secret:X,token_endpoint:$.tokenEndpoint}).onConflict((J)=>J.column("account_id").doUpdateSet({access_token:Q,refresh_token:Y,scope:$.scope,expires_at:$.expiresAt,client_id:$.clientId,client_secret:X,token_endpoint:$.tokenEndpoint,updated_at:Z})).execute()}async delete($){await this.db.deleteFrom("git_provider_account_credentials").where("account_id","=",$).execute()}isExpired($,Z=0){if(!$.expiresAt)return!1;let Y=($.expiresAt instanceof Date?$.expiresAt:new Date($.expiresAt)).getTime();if(Number.isNaN(Y))return!0;return Y-Z<Date.now()}}async function p24($,Z){try{let Q=await $.decrypt(Z.access_token),Y=Z.refresh_token?await $.decrypt(Z.refresh_token):null,X=Z.client_secret?await $.decrypt(Z.client_secret):null;return{id:Z.account_id,connectionId:Z.account_id,accessToken:Q,refreshToken:Y,scope:Z.scope,expiresAt:Z.expires_at,createdAt:Z.created_at,updatedAt:Z.updated_at,clientId:Z.client_id,clientSecret:X,tokenEndpoint:Z.token_endpoint}}catch(Q){return console.warn("[GitProviderAccountCredential] failed to decrypt credential row",{accountId:Z.account_id,message:Q instanceof Error?Q.message:String(Q)}),null}}import{sql as n24}from"kysely";function PF$($){return $ instanceof Date?$.toISOString():String($)}function hA($){return{id:$.id,organizationId:$.organization_id,accountId:$.account_id,provider:$.provider,host:$.host,path:$.path,externalId:$.external_id,defaultBranch:$.default_branch,webUrl:$.web_url,visibility:$.visibility,sandboxImage:Da.catch("default").parse($.sandbox_image),legacyConnectionId:$.legacy_connection_id,createdAt:PF$($.created_at),updatedAt:PF$($.updated_at)}}function bB($){return{provider:$.provider,host:$.host,path:$.path}}class Je{db;constructor($){this.db=$}async upsert($){let Z=$.ref.host.toLowerCase(),Q=await this.findByRef($.organizationId,$.ref);if(Q){let X=await this.db.updateTable("repositories").set({path:$.ref.path,provider:$.ref.provider,web_url:OJ({...$.ref,host:Z}),...$.accountId!==void 0?{account_id:$.accountId}:{},...$.externalId!==void 0?{external_id:$.externalId}:{},...$.defaultBranch!==void 0?{default_branch:$.defaultBranch}:{},...$.visibility!==void 0?{visibility:$.visibility}:{},...$.sandboxImage!==void 0?{sandbox_image:$.sandboxImage}:{},...$.legacyConnectionId!==void 0?{legacy_connection_id:$.legacyConnectionId}:{},updated_at:new Date}).where("id","=",Q.id).where("organization_id","=",$.organizationId).returningAll().executeTakeFirstOrThrow();return hA(X)}let Y=await this.db.insertInto("repositories").values({organization_id:$.organizationId,account_id:$.accountId??null,provider:$.ref.provider,host:Z,path:$.ref.path,external_id:$.externalId??null,default_branch:$.defaultBranch??null,web_url:OJ({...$.ref,host:Z}),visibility:$.visibility??null,sandbox_image:$.sandboxImage??null,legacy_connection_id:$.legacyConnectionId??null,created_by:$.createdBy??null}).returningAll().executeTakeFirstOrThrow();return hA(Y)}async get($,Z){let Q=await this.db.selectFrom("repositories").selectAll().where("id","=",$).where("organization_id","=",Z).executeTakeFirst();return Q?hA(Q):null}async getUnscoped($){let Z=await this.db.selectFrom("repositories").selectAll().where("id","=",$).executeTakeFirst();return Z?hA(Z):null}async findByRef($,Z){let Q=await this.db.selectFrom("repositories").selectAll().where("organization_id","=",$).where("host","=",Z.host.toLowerCase()).where(n24`lower(path)`,"=",Z.path.toLowerCase()).executeTakeFirst();return Q?hA(Q):null}async listByOrg($,Z){let Q=this.db.selectFrom("repositories").selectAll().where("organization_id","=",$);if(Z?.accountId)Q=Q.where("account_id","=",Z.accountId);return(await Q.orderBy("path","asc").execute()).map(hA)}async setSandboxImage($,Z,Q){let Y=await this.db.updateTable("repositories").set({sandbox_image:Q,updated_at:new Date}).where("id","=",$).where("organization_id","=",Z).returningAll().executeTakeFirst();return Y?hA(Y):null}async delete($,Z){try{return(await this.db.deleteFrom("repositories").where("id","=",$).where("organization_id","=",Z).executeTakeFirst()).numDeletedRows>0n}catch(Q){if(Q instanceof Error&&"constraint"in Q&&Q.constraint==="org_repo_sync_source_present")throw Error("Remove this repository's sync configurations before unlinking it");throw Q}}}var Fc=D(()=>{T6()});function TF$($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function t24($,Z){let{owner:Q}=h5(Z),Y=TF$(Z.host),X=new RegExp(`(?:https?://(?:[^@\\s/]*@)?${Y}/|git@${Y}:)${TF$(Q)}/([A-Za-z0-9._-]+)`,"gi");return[...$.matchAll(X)].flatMap((J)=>J[1]?.replace(/\.git$/i,"")||[])}async function RF$($,Z){let{owner:Q,name:Y}=h5(Z),X=new Set,J=[Z.path];while(J.length>0&&X.size<AF$){let G=J.shift();if(!G)break;let W=await $(G,"pubspec.yaml").catch(()=>null);if(!W)continue;for(let K of t24(W,Z)){if(K===Y||X.has(K))continue;if(X.size>=AF$)break;X.add(K),J.push(`${Q}/${K}`)}}return[...X]}var AF$=20;var qF$=D(()=>{T6()});function IF$($){return Bun.hash($).toString(36)}function o24($){for(let[Z,Q]of dw)if(Q.expiresAt<=$)dw.delete(Z);while(dw.size>=512){let Z=dw.keys().next();if(Z.done)break;dw.delete(Z.value)}}function D11($,Z,Q,Y=Date.now()){o24(Y),dw.set(IF$($),{owner:Z,expiresAt:Q})}function Uc($,Z=Date.now()){let Q=IF$($),Y=dw.get(Q);if(!Y)return"unknown";if(Y.expiresAt<=Z)return dw.delete(Q),"unknown";return Y.owner}var MF$="app",O11="user",dw;var Nc=D(()=>{dw=new Map});function iw($=process.env){let Z=$.GITHUB_APP_ID?.trim(),Q=$.GITHUB_APP_PRIVATE_KEY?.trim(),Y=$.GITHUB_APP_CLIENT_ID?.trim(),X=$.GITHUB_APP_CLIENT_SECRET?.trim(),J=$.GITHUB_APP_SLUG?.trim();if(!Z||!Q||!Y||!X||!J)return null;return{appId:Z,privateKeyPem:Q.replace(/\\n/g,`
|
|
1015
|
+
`.execute(Z.db),{success:!0,id:$.id}}})});import{z as U$}from"zod";function VQ($,Z){let Q=$?.[Z];return X24.has(Z)?Q!==!1:Q===!0}function RH$($){let Z=$?.auto_resolve_conflicts;return typeof Z==="boolean"?Z:$?.auto_merge===!0}var qB=500,da,RB,AH$,Sw,ia,pa,TH$=50,Y24,na,ta,xA,X24,$W0=262144,J24=50,gG=500,G24=5000,Cw;var IZ=D(()=>{da=U$.object({title:U$.string().max(qB),url:U$.string().max(qB),icon:U$.string().max(qB)}),RB=U$.object({keyId:U$.string().max(qB),modelId:U$.string().max(qB),title:U$.string().max(qB).optional()}).nullable(),AH$=U$.enum(["fast","smart","thinking","image","web_search","deep_research"]),Sw=U$.enum(["fast","smart","thinking"]),ia=U$.object({tiers:U$.object({fast:RB,smart:RB,thinking:RB,image:RB,web_search:RB,deep_research:RB})}),pa=U$.object({tiers:U$.object({fast:RB.optional(),smart:RB.optional(),thinking:RB.optional()})}),Y24=/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/,na=U$.object({host:U$.string().min(1).max(qB).regex(Y24).describe("Git host, e.g. 'github.com' (bare hostname, no scheme)."),secretId:U$.string().min(1).max(qB).describe("Vault secret id holding the PAT used to authenticate this host.")}),ta=U$.object({ids:U$.array(U$.string().max(qB)).describe("Ordered list of custom virtual MCP agent ids to show on the home view.")}),xA=U$.object({home_task_intake_enabled:U$.boolean().optional().describe("Show Task mode on the Home composer and allow reports to start tasks."),demo_mode:U$.boolean().optional().describe("Curated demo org: the commerce connect modal proceeds without a configured required data source."),reports_only:U$.boolean().optional().describe("Curated Deco Score look: hides agent navigation, the home Customize button, and the Settings/Automations tabs. Defaulted on for orgs created by commerce onboarding."),reviewer_enabled:U$.boolean().optional().describe("Run the Reviewer on a task's pull request once it's In Review \u2014 it reviews the code with the repo's stack-appropriate skills, fixes what it finds on the PR's own branch, then exercises the change on the deploy preview and approves or hands the card to a human."),qa_agent_enabled:U$.boolean().optional().describe("Deprecated: see reviewer_enabled."),code_reviewer_enabled:U$.boolean().optional().describe("Deprecated: see reviewer_enabled."),auto_merge:U$.boolean().optional().describe("When the Reviewer approves a task's pull request, merge it automatically instead of leaving the merge to a human."),auto_resolve_conflicts:U$.boolean().optional().describe("When an approved pull request can't be merged because it conflicts with its base branch, hand it back to the Super Agent to resolve the conflict (check out the branch, merge the base, push). Unset, it follows `auto_merge`; set it explicitly to run one without the other."),cheap_reviewer_model:U$.boolean().optional().describe("Run the Reviewer on a cheaper model than the Super Agent that wrote the code. On by default \u2014 turning it off trades cost for some review depth."),coding_agent_org_mcps:U$.boolean().optional().describe("Give a coding-agent run (the claude-code harness in a sandbox) every MCP connection in the org as its own MCP server, on top of the narrow task-run surface it always gets. Off by default: each connection is one more server the agent connects to at session start, and all of their tools land in its context."),coding_agents_claude_code:U$.boolean().optional().describe("Run chats on a Code Agent (an agent imported from a GitHub repo) with the claude-code harness inside its sandbox, instead of hosted Decopilot. Off by default: it changes the runtime of every such chat, and claude-code flushes whole turns rather than streaming tokens."),auto_assign_report_tasks_to_super_agent:U$.boolean().optional().describe("When a Deco Score import creates a task board item without an assignee, delegate it to the Super Agent automatically instead of leaving it unassigned."),hosting_enabled:U$.boolean().optional().describe("Per-site Hosting tab (deployments, domains, deploy outcomes). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org. `HOSTING_CONTROL_PLANE_GA` opens it (and its peers) to every org at once."),deco_analytics_enabled:U$.boolean().optional().describe("Per-site Deco Analytics tab (traffic, realtime, usage & limits). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org. `HOSTING_CONTROL_PLANE_GA` opens it (and its peers) to every org at once."),e2e_enabled:U$.boolean().optional().describe("Per-site E2E tab (end-to-end test runs). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org. `HOSTING_CONTROL_PLANE_GA` opens it (and its peers) to every org at once."),experiments_enabled:U$.boolean().optional().describe("Per-site Experiments tab (A/B tests + variant results). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org."),monitor_enabled:U$.boolean().optional().describe("Per-site Monitor tab (CDN Performance + Audience from the stats-lake warehouse). Off by default. deco.cx staff and local dev always see it; this flag is the per-client lever to open it to one external org. Its own deployment-wide switch `MONITOR_GA` opens it to every org at once (independent of the control-plane trio)."),delivery_lanes_enabled:U$.boolean().optional().describe("Board lanes for shipping: Approved, Merged and Post-deploy Validation sit between In Review and Done, and a merged pull request lands on Merged instead of Done. For teams whose release process continues after the merge. Off by default \u2014 with it off the board and the state machine behave exactly as if the lanes did not exist."),cms_auto_fresh_branch:U$.boolean().optional().describe("When a user opens the CMS on a branch whose last commit is older than the staleness window (2 days), move the session to a freshly minted branch cut from the default branch. The stale branch is left intact on GitHub. Off by default.")}),X24=new Set(["reviewer_enabled","cheap_reviewer_model"]);Cw=U$.object({id:U$.string().describe("Brand context ID"),name:U$.string().max(gG).describe("Company name"),domain:U$.string().max(gG).describe("Company domain (e.g. example.com)"),overview:U$.string().max(G24).describe("Company overview / description"),logo:U$.string().max(gG).nullable().optional().describe("Logo URL"),favicon:U$.string().max(gG).nullable().optional().describe("Favicon URL"),ogImage:U$.string().max(gG).nullable().optional().describe("OG image URL"),fonts:U$.object({heading:U$.string().max(gG).optional().describe("Font family for headings"),body:U$.string().max(gG).optional().describe("Font family for body text"),code:U$.string().max(gG).optional().describe("Font family for code / monospace")}).nullable().optional().describe("Font families by semantic role"),colors:U$.object({primary:U$.string().max(gG).optional().describe("Primary brand color (hex)"),secondary:U$.string().max(gG).optional().describe("Secondary brand color (hex)"),accent:U$.string().max(gG).optional().describe("Accent / highlight color (hex)"),background:U$.string().max(gG).optional().describe("Background color (hex)"),foreground:U$.string().max(gG).optional().describe("Foreground / text color (hex)")}).nullable().optional().describe("Semantic color palette"),images:U$.array(U$.record(U$.string(),U$.unknown())).max(J24).nullable().optional().refine(($)=>$===null||$===void 0||JSON.stringify($).length<=$W0,{message:`images must serialize to at most ${$W0} bytes`}).describe("Brand images"),metadata:U$.record(U$.string(),U$.unknown()).nullable().optional().refine(($)=>$===null||$===void 0||JSON.stringify($).length<=$W0,{message:`metadata must serialize to at most ${$W0} bytes`}).describe("Extra design tokens (typography, components, spacing, layout, tone, etc.)"),archivedAt:U$.string().nullable().optional().describe("Archive timestamp (null to unarchive)"),isDefault:U$.boolean().optional().describe("Whether this is the default brand for the organization")})});import{z as MB}from"zod";var V01;var qH$=D(()=>{C0();IZ();V01=d({name:"ORGANIZATION_SETTINGS_GET",description:"Get organization-level settings including sidebar configuration, store registry settings, simple model mode, and default home agents.",annotations:{title:"Get Organization Settings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:MB.object({}),outputSchema:MB.object({organizationId:MB.string(),sidebar_items:MB.array(da).nullable().optional(),coding_agent_mcp_excluded:MB.array(MB.string()).nullable().optional(),simple_mode:ia.nullable().optional(),default_home_agents:ta.nullable().optional(),flags:xA.nullable().optional(),submodule_credentials:MB.array(na).nullable().optional(),createdAt:MB.string().datetime().optional().describe("ISO 8601 timestamp"),updatedAt:MB.string().datetime().optional().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.organizationSettings.get(Q);if(!Y)return{organizationId:Q};return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}})});import{z as k01}from"zod";var S01;var MH$=D(()=>{C0();S01=d({name:"ORGANIZATION_HAS_SITE",description:"Whether this organization owns at least one legacy deco.cx site. Boolean only \u2014 does not expose site slugs.",annotations:{title:"Has Owned Site",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:k01.object({}),outputSchema:k01.object({hasSite:k01.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return{hasSite:(await Z.storage.orgSites.listByOrg(Q.id)).length>0}}})});import{z as EY}from"zod";var W24=50,K24=100,H24=500,IH$=500,C01;var VH$=D(()=>{C0();IZ();C01=d({name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization-level settings such as sidebar configuration, simple model mode, and default home agents.",annotations:{title:"Update Organization Settings",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:EY.object({organizationId:EY.string().min(1,"organizationId is required"),sidebar_items:EY.array(da).max(W24).optional(),coding_agent_mcp_excluded:EY.array(EY.string().max(IH$)).max(H24).optional().describe("Connection ids a coding-agent run must not mount, even with `coding_agent_org_mcps` on. Replaces the stored list; pass [] to clear it."),simple_mode:ia.optional(),default_home_agents:ta.extend({ids:EY.array(EY.string().max(IH$)).max(K24)}).optional(),flags:xA.strict().optional().describe("Org boolean toggles. Shallow-merged into the stored flags: keys you pass win (explicit false persists), omitted keys keep their value."),submodule_credentials:EY.array(na).max(TH$).refine(($)=>new Set($.map((Z)=>Z.host)).size===$.length,"Each git credential host must be unique.").optional().describe("Per-host PATs (as vault secret ids) every sandbox in the org installs in its git config. Replaces the stored list; pass [] to clear it.")}),outputSchema:EY.object({organizationId:EY.string(),sidebar_items:EY.array(da).nullable().optional(),coding_agent_mcp_excluded:EY.array(EY.string()).nullable().optional(),simple_mode:ia.nullable().optional(),default_home_agents:ta.nullable().optional(),flags:xA.nullable().optional(),submodule_credentials:EY.array(na).nullable().optional(),createdAt:EY.string().datetime().describe("ISO 8601 timestamp"),updatedAt:EY.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{if(a(Z),await Z.access.check(),K0(Z).id!==$.organizationId)throw Error("Cannot update settings for a different organization");let Y=await Z.storage.organizationSettings.upsert($.organizationId,{sidebar_items:$.sidebar_items,coding_agent_mcp_excluded:$.coding_agent_mcp_excluded,simple_mode:$.simple_mode,default_home_agents:$.default_home_agents,flags:$.flags,submodule_credentials:$.submodule_credentials});return{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}})});import{z as nK}from"zod";var kH$,_01,v01;var SH$=D(()=>{C0();IZ();kH$=Cw.extend({organizationId:nK.string(),archivedAt:nK.string().nullable().optional().describe("ISO 8601 timestamp"),createdAt:nK.string().describe("ISO 8601 timestamp"),updatedAt:nK.string().describe("ISO 8601 timestamp")}),_01=d({name:"BRAND_CONTEXT_LIST",description:"List all brand contexts (company profiles) for the current organization.",annotations:{title:"List Brand Contexts",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:nK.object({includeArchived:nK.boolean().optional().describe("Include archived brands in the list")}),outputSchema:nK.object({items:nK.array(kH$)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return{items:(await Z.storage.brandContext.list(Q,{includeArchived:$.includeArchived})).map((X)=>({...X,archivedAt:X.archivedAt instanceof Date?X.archivedAt.toISOString():X.archivedAt,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt,updatedAt:X.updatedAt instanceof Date?X.updatedAt.toISOString():X.updatedAt}))}}}),v01=d({name:"BRAND_CONTEXT_GET",description:"Get a specific brand context by ID.",annotations:{title:"Get Brand Context",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:nK.object({id:nK.string().describe("Brand context ID")}),outputSchema:kH$.extend({organizationId:nK.string()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.brandContext.get($.id,Q);if(!Y)throw Error("Brand context not found");return{...Y,archivedAt:Y.archivedAt instanceof Date?Y.archivedAt.toISOString():Y.archivedAt,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}})});import{z as fA}from"zod";var CH$,b01,x01,f01;var _H$=D(()=>{C0();IZ();CH$=Cw.extend({organizationId:fA.string(),createdAt:fA.string().describe("ISO 8601 timestamp"),updatedAt:fA.string().describe("ISO 8601 timestamp")}),b01=d({name:"BRAND_CONTEXT_CREATE",description:"Create a new brand context (company profile) for the current organization.",annotations:{title:"Create Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:Cw.omit({id:!0}),outputSchema:CH$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.brandContext.create(Q,{name:$.name,domain:$.domain,overview:$.overview,logo:$.logo??null,favicon:$.favicon??null,ogImage:$.ogImage??null,fonts:$.fonts??null,colors:$.colors??null,images:$.images??null,metadata:$.metadata??null});return{...Y,archivedAt:Y.archivedAt instanceof Date?Y.archivedAt.toISOString():Y.archivedAt,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():Y.createdAt,updatedAt:Y.updatedAt instanceof Date?Y.updatedAt.toISOString():Y.updatedAt}}}),x01=d({name:"BRAND_CONTEXT_UPDATE",description:"Update an existing brand context by ID.",annotations:{title:"Update Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Cw.partial().required({id:!0}),outputSchema:CH$,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(!await Z.storage.brandContext.get($.id,Q))throw Error("Brand context not found");let{id:X,...J}=$;if(J.isDefault===!0)await Z.storage.brandContext.setDefault(X,Q);let G=await Z.storage.brandContext.update(X,Q,{name:J.name,domain:J.domain,overview:J.overview,logo:J.logo!==void 0?J.logo??null:void 0,favicon:J.favicon!==void 0?J.favicon??null:void 0,ogImage:J.ogImage!==void 0?J.ogImage??null:void 0,fonts:J.fonts!==void 0?J.fonts??null:void 0,colors:J.colors!==void 0?J.colors??null:void 0,images:J.images!==void 0?J.images??null:void 0,metadata:J.metadata!==void 0?J.metadata??null:void 0,archivedAt:J.archivedAt!==void 0?J.archivedAt??null:void 0,isDefault:J.isDefault===!1?!1:void 0});return{...G,archivedAt:G.archivedAt instanceof Date?G.archivedAt.toISOString():G.archivedAt,createdAt:G.createdAt instanceof Date?G.createdAt.toISOString():G.createdAt,updatedAt:G.updatedAt instanceof Date?G.updatedAt.toISOString():G.updatedAt}}}),f01=d({name:"BRAND_CONTEXT_DELETE",description:"Archive a brand context by ID (soft delete).",annotations:{title:"Archive Brand Context",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:fA.object({id:fA.string().describe("Brand context ID")}),outputSchema:fA.object({success:fA.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(!await Z.storage.brandContext.get($.id,Q))throw Error("Brand context not found");return await Z.storage.brandContext.update($.id,Q,{archivedAt:new Date().toISOString(),isDefault:!1}),{success:!0}}})});async function ZW0($,Z,Q){let Y=$.trim();if(!Y.startsWith("http"))Y=`https://${Y}`;let X=await fetch("https://api.firecrawl.dev/v1/scrape",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Z}`},body:JSON.stringify({url:Y,formats:["branding"]})});if(!X.ok){let N=await X.text().catch(()=>"");throw Error(`Firecrawl API error: ${X.status} ${N.slice(0,200)}`)}let J=await X.json();if(!J.success||!J.data?.branding)return null;let G=J.data.branding,W=J.data.metadata??{},K=N24(G,W);return{name:W.title?.split(/[|\u2013\u2014]|\s+-\s+/).map((N)=>N.trim()).filter(Boolean)?.slice().sort((N,B)=>N.length-B.length)[0]??W.ogSiteName??Q??$,domain:$,overview:W.description??"",logo:K.logo,favicon:K.favicon,ogImage:K.ogImage,fonts:K.fonts,colors:K.colors,images:null,metadata:Object.keys(K.metadata).length>0?K.metadata:null}}function N24($,Z){let Q=$.images??{},Y=$.colors??{},X={};for(let[F,U]of Object.entries(Y))if(typeof U==="string"&&U&&F24.has(F))X[F]=U;let J={},W=($.typography??{}).fontFamilies??{};for(let[F,U]of Object.entries(W))if(typeof U==="string"&&U){let N=U24[F.toLowerCase()];if(N&&!J[N])J[N]=U}let K=$.fonts;if(Array.isArray(K))for(let F of K){let U=F.family;if(typeof U==="string"&&U&&!J.body)J.body=U}let H={};for(let F of["typography","components","spacing","layout","animations","icons","tone","personality","colorScheme"])if($[F]!==void 0)H[F]=$[F];return{logo:Q.logo??null,favicon:Q.favicon??null,ogImage:Q.ogImage??Z.ogImage??null,fonts:Object.keys(J).length>0?J:null,colors:Object.keys(X).length>0?X:null,metadata:H}}var F24,U24;var y01=D(()=>{F24=new Set(["primary","secondary","accent","background","foreground"]),U24={heading:"heading",headings:"heading",head:"heading",title:"heading",body:"body",primary:"body",text:"body",code:"code",monospace:"code",mono:"code"}});import{z as QW0}from"zod";var B24,g01;var vH$=D(()=>{C0();y01();IZ();B24=Cw.pick({id:!0,name:!0,domain:!0,overview:!0,logo:!0,favicon:!0,ogImage:!0,fonts:!0,colors:!0}).extend({success:QW0.boolean()}),g01=d({name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context (colors, fonts, logos) from a website URL using Firecrawl.",annotations:{title:"Extract Brand Context",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:QW0.object({domain:QW0.string().describe("Website domain to extract brand from"),brandId:QW0.string().optional().describe("Existing brand context ID to update (creates new if omitted)")}),outputSchema:B24,modelSummary:($)=>$.success?`Brand saved (id=${$.id}, name=${$.name}, domain=${$.domain}). The UI rendered the logo, colors, fonts, and overview.`:"Brand extraction failed.",handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=Z.firecrawlApiKey;if(!Y)throw Error("FIRECRAWL_API_KEY is not configured. Set the environment variable to enable brand extraction.");let X=await ZW0($.domain,Y,$.domain);if(!X)throw Error("Firecrawl did not return branding data for this URL");let J={name:X.name,domain:X.domain,overview:X.overview,logo:X.logo,favicon:X.favicon,ogImage:X.ogImage,fonts:X.fonts,colors:X.colors,images:X.images,metadata:X.metadata},G=$.brandId?await(async()=>{if(!await Z.storage.brandContext.get($.brandId,Q))throw Error("Brand context not found");return Z.storage.brandContext.update($.brandId,Q,J)})():await Z.storage.brandContext.create(Q,J);return{id:G.id,name:G.name,domain:G.domain,overview:G.overview,logo:G.logo,favicon:G.favicon,ogImage:G.ogImage,fonts:G.fonts,colors:G.colors,success:!0}}})});function bH$($){let Z=$.metadata??{};return{id:$.id,name:$.name,domain:$.domain||void 0,colors:$.colors??void 0,fonts:$.fonts??void 0,assets:$.logo||$.favicon||$.ogImage?{logo:$.logo??void 0,favicon:$.favicon??void 0,ogImage:$.ogImage??void 0}:void 0,overview:$.overview||void 0,tagline:typeof Z.tagline==="string"?Z.tagline:void 0,tone:typeof Z.tone==="string"?Z.tone:void 0,metadata:(()=>{let Q=Object.fromEntries(Object.entries(Z).filter(([Y])=>Y!=="tagline"&&Y!=="tone"));return Object.keys(Q).length>0?Q:void 0})()}}var h01,u01;var xH$=D(()=>{ge0();C0();h01=d({name:"BRAND_GET",description:"Get a brand context by ID. Omit the ID to get the default brand for the organization.",annotations:{title:"Get Brand",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:V30,outputSchema:Sa,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=$.id?await Z.storage.brandContext.get($.id,Q):await Z.storage.brandContext.getDefault(Q);if(!Y)throw Error($.id?"Brand not found":"No default brand configured");return bH$(Y)}}),u01=d({name:"BRAND_LIST",description:"List all active brands for the current organization.",annotations:{title:"List Brands",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:k30,outputSchema:S30,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return{items:(await Z.storage.brandContext.list(Q)).map(bH$)}}})});import{resolveTxt as O24}from"dns/promises";function l01($){return`${D24}.${$.toLowerCase()}`}function fH$(){return`deco-verify-${crypto.randomUUID().replace(/-/g,"")}`}async function yH$($,Z,Q=O24){if(!Z)return!1;try{return(await Q(l01($))).some((X)=>X.join("").trim()===Z)}catch{return!1}}var D24="_deco-verify";var gH$=()=>{};import{z as M9}from"zod";function _w($){let Z=$.verificationStatus==="pending"&&Boolean($.verificationToken);return{id:$.id,domain:$.domain,joinMode:$.joinMode,verificationStatus:$.verificationStatus,verificationMethod:$.verificationMethod,verifiedAt:$.verifiedAt?new Date($.verifiedAt).toISOString():null,recordName:Z?l01($.domain):null,recordValue:Z?$.verificationToken:null}}function w24($){let Z=$.toLowerCase().trim();if(!L24.test(Z))throw Error(`Invalid domain format: "${Z}". Must be a valid domain like "acme.com"`);if(tK.has(Z))throw Error(`Cannot claim generic email domain "${Z}". Only corporate domains are allowed.`);return Z}var L24,c01,YW0,m01,d01,i01,p01,n01;var hH$=D(()=>{hG();gH$();C0();L24=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/,c01=M9.enum(["off","auto","request"]),YW0=M9.object({id:M9.string(),domain:M9.string(),joinMode:c01,verificationStatus:M9.enum(["pending","verified"]),verificationMethod:M9.enum(["email","dns"]).nullable(),verifiedAt:M9.string().nullable(),recordName:M9.string().nullable(),recordValue:M9.string().nullable()});m01=d({name:"ORGANIZATION_DOMAIN_LIST",description:"List the email domains claimed by an organization.",annotations:{title:"List Organization Domains",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:M9.object({}),outputSchema:M9.object({domains:M9.array(YW0)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return{domains:(await Z.storage.organizationDomains.listByOrganizationId(Q.id)).map(_w)}}}),d01=d({name:"ORGANIZATION_DOMAIN_ADD",description:"Claim an email domain for an organization. If the caller's verified email matches the domain it is trusted immediately; otherwise it requires DNS verification.",annotations:{title:"Add Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:M9.object({domain:M9.string().min(1).max(255).describe("Domain to claim, e.g. acme.com"),joinMode:c01.optional().describe("Initial join mode (only applied when the domain is trusted immediately via email match).")}),outputSchema:YW0,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=w24($.domain),J=Z.auth.user?.email?.split("@")[1]?.toLowerCase(),G=Boolean(Z.auth.user?.emailVerified)&&J===Y,W=await Z.storage.organizationDomains.getByOrgAndDomain(Q.id,Y);if(W){if(W.verificationStatus!=="verified"&&G){let H=await Z.storage.organizationDomains.markVerified(W.id,"email");return _w(H)}return _w(W)}let K=G?await Z.storage.organizationDomains.add(Q.id,Y,{joinMode:$.joinMode??"off",verificationStatus:"verified",verificationMethod:"email"}):await Z.storage.organizationDomains.add(Q.id,Y,{joinMode:"off",verificationStatus:"pending",verificationToken:fH$()});return _w(K)}}),i01=d({name:"ORGANIZATION_DOMAIN_UPDATE",description:"Set the join mode for a claimed domain. Discoverable modes (auto/request) require the domain to be verified.",annotations:{title:"Update Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:M9.object({id:M9.string(),joinMode:c01}),outputSchema:YW0,handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationDomains.getById($.id);if(!Y||Y.organizationId!==Q.id)throw Error("Domain not found");if($.joinMode!=="off"&&Y.verificationStatus!=="verified")throw Error("Verify the domain before enabling auto-join or requests.");let X=await Z.storage.organizationDomains.updateJoinMode($.id,$.joinMode);return _w(X)}}),p01=d({name:"ORGANIZATION_DOMAIN_VERIFY",description:"Check the DNS TXT record for a pending domain and mark it verified if present.",annotations:{title:"Verify Organization Domain",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:M9.object({id:M9.string()}),outputSchema:M9.object({verified:M9.boolean(),domain:YW0}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationDomains.getById($.id);if(!Y||Y.organizationId!==Q.id)throw Error("Domain not found");if(Y.verificationStatus==="verified")return{verified:!0,domain:_w(Y)};if(!Y.verificationToken)throw Error("Domain has no pending DNS verification.");if(!await yH$(Y.domain,Y.verificationToken))return{verified:!1,domain:_w(Y)};let J=await Z.storage.organizationDomains.markVerified($.id,"dns");return{verified:!0,domain:_w(J)}}}),n01=d({name:"ORGANIZATION_DOMAIN_REMOVE",description:"Remove a claimed domain from an organization.",annotations:{title:"Remove Organization Domain",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:M9.object({id:M9.string()}),outputSchema:M9.object({success:M9.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationDomains.getById($.id);if(!Y||Y.organizationId!==Q.id)throw Error("Domain not found");return await Z.storage.organizationDomains.removeById($.id),{success:!0}}})});function vw($){return($ instanceof Error?$.message.toLowerCase():"").includes("already a member")}import{z as VZ}from"zod";var j24,t01,o01,r01;var uH$=D(()=>{C0();U6();j24=VZ.object({id:VZ.string(),userId:VZ.string(),status:VZ.enum(["pending","approved","denied"]),createdAt:VZ.string(),user:VZ.object({id:VZ.string(),name:VZ.string(),email:VZ.string(),image:VZ.string().nullable()}).nullable()}),t01=d({name:"ORGANIZATION_JOIN_REQUEST_LIST",description:"List pending requests to join the organization.",annotations:{title:"List Join Requests",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:VZ.object({}),outputSchema:VZ.object({requests:VZ.array(j24)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return{requests:(await Z.storage.organizationJoinRequests.listPendingWithUser(Q.id)).map((X)=>({id:X.id,userId:X.userId,status:X.status,createdAt:new Date(X.createdAt).toISOString(),user:X.user}))}}}),o01=d({name:"ORGANIZATION_JOIN_REQUEST_APPROVE",description:"Approve a pending join request, adding the user as a member.",annotations:{title:"Approve Join Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:VZ.object({requestId:VZ.string()}),outputSchema:VZ.object({success:VZ.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationJoinRequests.getById($.requestId);if(!Y||Y.organizationId!==Q.id)throw Error("Join request not found");if(Y.status!=="pending")throw Error("Join request has already been decided");let X=p0(Z);if(!await Z.storage.organizationJoinRequests.decide(Y.id,"approved",X??Y.userId))return{success:!0};try{await Z.boundAuth.organization.addMember({organizationId:Q.id,userId:Y.userId,role:["user"]})}catch(G){if(!vw(G))throw G}if(X)v1.capture({distinctId:X,event:"organization_join_request_approved",groups:{organization:Q.id},properties:{organization_id:Q.id,user_id:Y.userId}});return{success:!0}}}),r01=d({name:"ORGANIZATION_JOIN_REQUEST_DENY",description:"Deny a pending join request.",annotations:{title:"Deny Join Request",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:VZ.object({requestId:VZ.string()}),outputSchema:VZ.object({success:VZ.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.organizationJoinRequests.getById($.requestId);if(!Y||Y.organizationId!==Q.id)throw Error("Join request not found");if(Y.status!=="pending")throw Error("Join request has already been decided");let X=p0(Z);if(await Z.storage.organizationJoinRequests.decide(Y.id,"denied",X??Y.userId)&&X)v1.capture({distinctId:X,event:"organization_join_request_denied",groups:{organization:Q.id},properties:{organization_id:Q.id,user_id:Y.userId}});return{success:!0}}})});import{z as jJ}from"zod";var s01;var lH$=D(()=>{U6();C0();GY();s01=d({name:"ORGANIZATION_MEMBER_ADD",description:"Invite a member to the organization by email with an assigned role.",annotations:{title:"Add Organization Member",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:jJ.object({organizationId:jJ.string().optional(),userId:jJ.string(),role:jJ.array(jJ.string())}),outputSchema:jJ.object({id:jJ.string(),organizationId:jJ.string(),userId:jJ.string(),role:jJ.union([jJ.string(),jJ.array(jJ.string())]),createdAt:jJ.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=$.organizationId||Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(Q!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Y=await Z.db.selectFrom("member").select(["role"]).where("userId","=",p0(Z)??"").where("organizationId","=",Q).executeTakeFirst();if(!gQ0(Y?.role,$.role))throw Error(`Insufficient privileges to assign role "${$.role.join(",")}"`);let X=await Z.boundAuth.organization.addMember({organizationId:Q,userId:$.userId,role:$.role});if(!X)throw Error("Failed to add member");let J=p0(Z);if(J)v1.capture({distinctId:J,event:"organization_member_added",groups:{organization:Q},properties:{organization_id:Q,added_user_id:$.userId,role:$.role}});return{...X,role:X.role,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});import{z as Xc}from"zod";var a01;var cH$=D(()=>{U6();C0();a01=d({name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove a member from the organization. Revokes all their access immediately.",annotations:{title:"Remove Organization Member",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Xc.object({organizationId:Xc.string().optional(),memberIdOrEmail:Xc.string()}),outputSchema:Xc.object({success:Xc.boolean(),memberIdOrEmail:Xc.string()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=$.organizationId||Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(Q!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Y=await Z.boundAuth.organization.removeMember({organizationId:Q,memberIdOrEmail:$.memberIdOrEmail});Z.invalidateMemberRole?.(Y.member.userId,Q);let X=p0(Z);if(X)v1.capture({distinctId:X,event:"organization_member_removed",groups:{organization:Q},properties:{organization_id:Q,member_id_or_email:$.memberIdOrEmail}});return{success:!0,memberIdOrEmail:$.memberIdOrEmail}}})});import{z as zY}from"zod";var e01;var mH$=D(()=>{C0();e01=d({name:"ORGANIZATION_MEMBER_LIST",description:"List all members in the organization with their roles.",annotations:{title:"List Organization Members",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:zY.object({limit:zY.number().int().min(1).max(1000).optional(),offset:zY.number().int().min(0).optional()}),outputSchema:zY.object({members:zY.array(zY.object({id:zY.string(),organizationId:zY.string(),userId:zY.string(),role:zY.string(),createdAt:zY.string().datetime().describe("ISO 8601 timestamp"),user:zY.object({id:zY.string(),name:zY.string(),email:zY.string(),image:zY.string().optional()}).optional()}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return{members:((await Z.boundAuth.organization.listMembers({organizationId:Q,limit:$.limit,offset:$.offset}))?.members??[]).map((J)=>({...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():J.createdAt}))}}})});import{z as p7}from"zod";var $11;var dH$=D(()=>{U6();C0();GY();$11=d({name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Change a member's role (e.g., admin, member) within the organization.",annotations:{title:"Update Member Role",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:p7.object({organizationId:p7.string().optional(),memberId:p7.string(),role:p7.array(p7.string())}),outputSchema:p7.object({id:p7.string(),organizationId:p7.string(),userId:p7.string(),role:p7.union([p7.string(),p7.array(p7.string())]),createdAt:p7.string().datetime().describe("ISO 8601 timestamp"),user:p7.object({email:p7.string(),name:p7.string(),image:p7.string().optional()})}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=$.organizationId||Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(Q!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let Y=await Z.db.selectFrom("member").select(["role"]).where("userId","=",p0(Z)??"").where("organizationId","=",Q).executeTakeFirst();if(!gQ0(Y?.role,$.role))throw Error(`Insufficient privileges to assign role "${$.role.join(",")}"`);if(!$.role.includes("owner")){if((await Z.db.selectFrom("member").select(["role"]).where("id","=",$.memberId).where("organizationId","=",Q).executeTakeFirst())?.role.split(",").includes("owner")){if((await Z.db.selectFrom("member").select(["role"]).where("organizationId","=",Q).execute()).filter((H)=>H.role.split(",").includes("owner")).length<=1)throw Error("Cannot remove the organization's last owner. Assign another owner first.")}}let X=await Z.boundAuth.organization.updateMemberRole({organizationId:Q,memberId:$.memberId,role:$.role});if(!X)throw Error("Failed to update member role");Z.invalidateMemberRole?.(X.userId,Q);let J=p0(Z);if(J)v1.capture({distinctId:J,event:"organization_member_role_updated",groups:{organization:Q},properties:{organization_id:Q,member_id:$.memberId,target_user_id:X.userId,new_role:Array.isArray($.role)?$.role.join(","):$.role}});return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});async function iH$(){if(oa&&Date.now()-oa.fetchedAt<600000)return oa.rate;try{let Z=await(await fetch("https://economia.awesomeapi.com.br/json/last/USD-BRL",{signal:AbortSignal.timeout(5000)})).json(),Q=parseFloat(Z.USDBRL?.bid??"");if(Number.isNaN(Q)||Q<=0)throw Error("Invalid rate");return oa={rate:Q,fetchedAt:Date.now()},Q}catch{return oa?.rate??5.5}}function pH$($,Z,Q){if(Z==="brl")return Math.round($/Q);return $}var oa=null;function Z11($,Z="",Q=new URLSearchParams){for(let[Y,X]of Object.entries($)){if(X===void 0||X===null)continue;let J=Z?`${Z}[${Y}]`:Y;if(Array.isArray(X))X.forEach((G,W)=>{if(typeof G==="object"&&G!==null)Z11(G,`${J}[${W}]`,Q);else Q.append(`${J}[${W}]`,String(G))});else if(typeof X==="object")Z11(X,J,Q);else Q.append(J,String(X))}return Q}async function IB($,Z){let Q=E0().stripeSecretKey;if(!Q)throw new kZ(503,"billing is not configured");let Y=Z?.params?Z11(Z.params).toString():void 0,X=await fetch(`${E24}${$}`,{method:Z?.method??(Y?"POST":"GET"),headers:{Authorization:`Bearer ${Q}`,...Y&&{"Content-Type":"application/x-www-form-urlencoded"},...Z?.idempotencyKey&&{"Idempotency-Key":Z.idempotencyKey}},body:Y,signal:AbortSignal.timeout(z24)}),J=await X.json().catch(()=>({}));if(!X.ok){let G=J.error?.message??`HTTP ${X.status}`;throw new kZ(X.status,G)}return J}function nH$($){return{billing_address_collection:"required",custom_fields:[{key:P24,label:{type:"custom",custom:"CPF / CNPJ"},type:"text",optional:!1,text:{minimum_length:A24,maximum_length:T24}}],...$&&{customer_update:{address:"auto",name:"auto"}}}}function tH$($){return Boolean((E0().stripePlanPriceIds??{})[$])}function Q11($){let Z=E0().stripePlanPriceIds??{};return Object.entries(Z).find(([,Q])=>Q===$)?.[0]}function R24($){return["checkout",$.organizationId,$.planId??"flat",$.lastStripeEventAt?.getTime()??0].join(":")}async function oH$($){let Z=E0(),Q=$.planId?Q11($.planId):Z.stripeOrgPriceId;if(!Q)throw new kZ(503,$.planId?`plan '${$.planId}' has no Stripe price configured`:"billing is not configured");let Y=await IB("/checkout/sessions",{idempotencyKey:R24({organizationId:$.organizationId,...$.planId?{planId:$.planId}:{},...$.lastStripeEventAt!==void 0&&{lastStripeEventAt:$.lastStripeEventAt}}),params:{mode:"subscription",...nH$(null),line_items:[{price:Q,quantity:1}],success_url:$.successUrl,cancel_url:$.cancelUrl,metadata:{orgId:$.organizationId,...$.planId?{planId:$.planId}:{}},subscription_data:{billing_cycle_anchor_config:{day_of_month:1,hour:0,minute:0,second:0},metadata:{orgId:$.organizationId,...$.planId?{planId:$.planId}:{}}}}});if(!Y.url)throw new kZ(500,"checkout session lacks url");return{url:Y.url}}function q24($,Z){return Math.round($*(1+Z/100))}function I24($){let Z=Math.floor(($.nowMs??Date.now())/M24);return["topup",$.organizationId,$.currency,$.amountCents,Z].join(":")}async function rH$($){let Z=q24($.amountCents,$.feePercent),Q=pH$($.amountCents,$.currency,await iH$()),Y=E0().stripeTopupProductId,X={kind:"topup",orgId:$.organizationId,creditCents:Q},J=$.currency==="brl"?`Studio AI credits (R$ ${($.amountCents/100).toFixed(2)})`:`Studio AI credits ($${($.amountCents/100).toFixed(2)})`,G=await IB("/checkout/sessions",{idempotencyKey:I24({organizationId:$.organizationId,amountCents:$.amountCents,currency:$.currency}),params:{mode:"payment",...$.customerId&&{customer:$.customerId},...nH$($.customerId),line_items:[{quantity:1,price_data:{currency:$.currency,unit_amount:Z,...Y?{product:Y}:{product_data:{name:J}}}}],success_url:$.successUrl,cancel_url:$.cancelUrl,metadata:X,payment_intent_data:{metadata:X}}});if(!G.url)throw new kZ(500,"checkout session lacks url");return{url:G.url}}async function XW0($){let Z=await IB("/billing_portal/sessions",{params:{customer:$.customerId,return_url:$.returnUrl}});if(!Z.url)throw new kZ(500,"portal session lacks url");return{url:Z.url}}async function sH$($){let Z=await IB("/billing_portal/sessions",{params:{customer:$.customerId,return_url:$.returnUrl,...E0().stripePortalConfigurationId&&{configuration:E0().stripePortalConfigurationId},flow_data:{type:"subscription_update_confirm",subscription_update_confirm:{subscription:$.subscriptionId,items:[{id:$.subscriptionItemId,price:$.priceId}]},after_completion:{type:"redirect",redirect:{return_url:$.returnUrl}}}}});if(!Z.url)throw new kZ(500,"portal session lacks url");return{url:Z.url}}async function aH$($){return IB(`/prices/${encodeURIComponent($)}`)}async function bw($){return IB(`/subscriptions/${encodeURIComponent($)}`)}async function eH$($){await IB(`/subscriptions/${encodeURIComponent($)}`,{method:"DELETE"})}async function $F$($){let Z=await IB(`/invoices?subscription=${encodeURIComponent($)}&status=paid&limit=100`),Q=V24($,Z.data??[]);for(let Y of Q)await IB("/refunds",{params:{payment_intent:Y.paymentIntent,reason:"duplicate"},idempotencyKey:Y.idempotencyKey});return{refundedCents:Q.reduce((Y,X)=>Y+X.amountCents,0)}}function V24($,Z){let Q=[];for(let Y of Z){let X=Y.amount_paid??0;if(X<=0)continue;let J=typeof Y.payment_intent==="string"?Y.payment_intent:Y.payment_intent?.id;if(!J)continue;Q.push({paymentIntent:J,amountCents:X,idempotencyKey:`orphan-refund:${$}:${Y.id??J}`})}return Q}var E24="https://api.stripe.com/v1",kZ,z24=15000,P24="taxid",A24=11,T24=18,M24=120000;var VB=D(()=>{F$();kZ=class kZ extends Error{status;constructor($,Z){super(`Stripe API ${$}: ${Z}`);this.status=$;this.name="StripeApiError"}}});import{z as JW0}from"zod";async function k24($){if(!$.planId)throw Error("This organization already has an active subscription.");let Z=Q11($.planId);if(!Z)throw new kZ(503,`plan '${$.planId}' has no Stripe price configured`);let Q=await bw($.subscriptionId),Y=(Q.items?.data??[]).filter((G)=>G.price?.id?tH$(G.price.id):!1),X=Y[0];if(Y.length>1)throw Error("This organization's subscription has more than one plan line \u2014 change it in Stripe, not here.");if(!X?.id)throw new kZ(500,"subscription has no plan line to move to another price");if(X.price?.id===Z)throw Error("This organization is already on that plan.");let{url:J}=await sH$({customerId:Q.customer,subscriptionId:$.subscriptionId,subscriptionItemId:X.id,priceId:Z,returnUrl:$.returnUrl});return J}var Y11;var ZF$=D(()=>{VB();E9();C0();U6();Y11=d({name:"ORGANIZATION_BILLING_CHECKOUT_START",description:"Start the organization's subscription: creates a Stripe Checkout session and returns its URL.",annotations:{title:"Start Billing Checkout",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},inputSchema:JW0.object({planId:JW0.string().optional()}),outputSchema:JW0.object({url:JW0.string()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id,Y=Z.organization?.slug;if(!Q||!Y)throw Error("Organization context required");let X=await Z.storage.organizationBilling.getBilling(Q),J=`${x5()}${Rw(Y,"members")}`;if(X?.status==="active"&&X.stripeSubscriptionId){let W=await k24({subscriptionId:X.stripeSubscriptionId,planId:$.planId,returnUrl:`${J}?checkout=updated`});return QJ({event:"subscription_plan_change_started",organizationId:Q,...$.planId?{properties:{plan_id:$.planId}}:{},...Z.auth?.user?.id?{userId:Z.auth.user.id}:{}}),{url:W}}if(X?.status==="active")throw Error("This organization already has an active subscription.");if(X?.stripeSubscriptionId)throw Error("This organization still has a subscription on file \u2014 settle or cancel it before starting a new checkout.");let{url:G}=await oH$({organizationId:Q,successUrl:`${J}?checkout=success`,cancelUrl:`${J}?checkout=canceled`,...$.planId?{planId:$.planId}:{},lastStripeEventAt:X?.lastStripeEventAt??null});return QJ({event:"subscription_checkout_started",organizationId:Q,...$.planId?{properties:{plan_id:$.planId}}:{},...Z.auth?.user?.id?{userId:Z.auth.user.id}:{}}),{url:G}}})});import{z as xw}from"zod";async function v24(){if(ra&&Date.now()-ra.at<ra.ttlMs)return ra.prices;let $=new Set,Z=Object.entries(E0().stripePlanPriceIds??{}).filter(([,J])=>{if($.has(J))return!1;return $.add(J),!0}),Y=(await Promise.all(Z.map(async([J,G])=>{try{let W=await aH$(J);if(W.unit_amount===null)return null;return{planId:G,amountCents:W.unit_amount,currency:W.currency,interval:W.recurring?.interval??null}}catch(W){return console.warn(`plan price ${J} (${G}) unreadable:`,W instanceof kZ?W.message:W),null}}))).filter((J)=>J!==null),X=Y.length===Z.length;return ra={at:Date.now(),prices:Y,ttlMs:X?C24:_24},Y}var S24,C24=600000,_24=30000,ra=null,X11;var QF$=D(()=>{VB();C0();F$();S24=xw.object({planId:xw.string(),amountCents:xw.number(),currency:xw.string(),interval:xw.string().nullable()});X11=d({name:"ORGANIZATION_BILLING_PLAN_PRICES",description:"The monthly price of each purchasable plan, read from Stripe. Empty when no plan prices are configured.",annotations:{title:"Plan Prices",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:xw.object({}),outputSchema:xw.object({prices:xw.array(S24)}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{prices:await v24()}}})});import{z as J11}from"zod";var G11;var YF$=D(()=>{VB();E9();C0();G11=d({name:"ORGANIZATION_BILLING_PORTAL",description:"Open the organization's Stripe billing portal (manage card, invoices, cancellation). Returns the portal URL.",annotations:{title:"Open Billing Portal",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},inputSchema:J11.object({}),outputSchema:J11.object({url:J11.string()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);if(!Q.slug)throw Error("Organization context required");let Y=await Z.storage.organizationBilling.getBilling(Q.id);if(!Y?.stripeCustomerId)throw Error("This organization has no billing account yet \u2014 subscribe first.");try{return await XW0({customerId:Y.stripeCustomerId,returnUrl:`${x5()}${Rw(Q.slug,"members")}`})}catch(X){if(X instanceof kZ)throw Error(X.message);throw X}}})});function GW0($){return W11[$%W11.length]??b24}function PY($){return $.createdBy==="system"}function f24($){if($?.reviewer_enabled===void 0&&$?.qa_agent_enabled===!1&&$?.code_reviewer_enabled===!1)return!1;return VQ($,"reviewer_enabled")}function kB($){return f24($)?HW:[]}function y24($){return VQ($,"delivery_lanes_enabled")}function oF($){return y24($)?"merged":"done"}function yw($,Z){if(!$)return!1;return[tF[Z],...x24].some((Q)=>$.startsWith(`${Q}:`))}function SB($,Z){if(Z)return new Date(Z).getTime();let Q=0;for(let Y of $){if(Y.action!=="status_changed")continue;if(Y.data?.to!=="in_review")continue;Q=Math.max(Q,new Date(Y.occurredAt).getTime())}return Q}function gw($,Z){let Q=SB($,Z.cycleStartedAt),Y=new Map;for(let X of $){if(X.action!=="review_approved"&&X.action!=="review_changes_requested")continue;if(new Date(X.occurredAt).getTime()<Q)continue;let J=X.data??{};if(J.reviewer!=="reviewer")continue;if(X.action==="review_approved"){if(Z?.verifiedOnly&&J.verified!==!0)continue;Y.set("reviewer","approved")}else Y.set("reviewer","changes_requested")}return Y}function fw($,Z,Q){if(Z.length===0)return!1;let Y=gw($,Q);return Z.every((X)=>Y.get(X)==="approved")}function GF$($,Z,Q){return fw($,Z,Q)&&!fw($,Z,{...Q,verifiedOnly:!0})}function WF$($){let Z=null;for(let Q of $){if(Q.action!=="review_approved"&&Q.action!=="review_changes_requested")continue;let Y=new Date(Q.occurredAt).getTime();if(Z&&Y<Z.at)continue;let X=Q.data?.notes;Z={at:Y,notes:Q.action==="review_changes_requested"&&typeof X==="string"?X:null}}return Z?.notes??null}function NF$($,Z=Date.now()){if($.state!==null&&$.state!=="open")return!1;if($.state===null)return!0;if($.checksStatus==="pending")return!0;if($.previewUrl!==null)return!1;let Q=$.updatedAt?Date.parse($.updatedAt):Number.NaN;return Number.isFinite(Q)&&Z-Q<g24}var j8="super-agent",W11,b24,sa='Your checkout is SHALLOW (`git clone --depth 1`), so it has no merge base and `git diff main...HEAD` (three dots) fails with "fatal: main...HEAD: no merge base". To see a branch diff, either use the two-dot form against the fetched remote ref (`git fetch origin <base> && git diff origin/<base> HEAD`), or deepen first with `git fetch --deepen=100`. Same for `git log main..HEAD` and anything else that needs shared history.',XF$,K11="chore",HW,tF,x24,aa="NO VISUAL SURFACE",oK,T$,JF$,WW0,KF$="task-board.item.updated",HF$="task-board.item.deleted",FF$="task-board.item.prs.updated",UF$=4000,g24=600000;var C4=D(()=>{IZ();W11=["#9ca3af","#ef4444","#f97316","#f59e0b","#22c55e","#3b82f6","#a855f7","#ec4899"],b24=W11[0];XF$="Read the diff with `gh pr diff <number>`. It comes from the API, so it needs no fetch, no merge base, and is unaffected by the shallow checkout. "+"Read it ONCE \u2014 `gh pr diff <number> --name-only` first if you need to size "+"it, then pull the hunks you need per FILE. Do NOT re-run the diff sliced by directory: each slice re-reads bytes you already have into every remaining turn's context, and it is the largest avoidable cost in a review.",HW=["reviewer"],tF={reviewer:"Reviewer"},x24=["QA Agent","Code Reviewer"];oK=["triage","todo","in_progress","in_review","approved","merged","post_deploy_validation","done","archived"],T$={intake:"triage",queue:"todo",progress:"in_progress",review:"in_review",archive:"archived"},JF$=oK.map(($,Z)=>({key:$,title:$,position:Z})),WW0=["approved","merged","post_deploy_validation"]});function H11($){return $==="trial"?"trial":"subscription"}function ea($,Z,Q,Y={}){QJ({event:Z,organizationId:Q.organizationId,...$.auth?.user?.id?{userId:$.auth.user.id}:{},properties:{task_id:Q.id,...Y}})}function F11($){return $?.status==="active"||$?.status==="past_due"}function KW0($,Z){if(F11($))return{periodKey:$?.currentPeriodEnd?`sub:${$.currentPeriodEnd.toISOString()}`:"sub:pending",limit:$?.monthlyTaskExecutions??Z.monthlyTaskExecutions,exhaustedReason:"monthly_exhausted"};return{periodKey:"trial",limit:$?.freeTaskExecutions??Z.freeTaskExecutions,exhaustedReason:"trial_exhausted"}}function $e(){let $=E0();return{enforced:$.taskQuotaEnforced,freeTaskExecutions:$.freeTaskExecutions,monthlyTaskExecutions:$.monthlyTaskExecutions,maxRunsPerTask:$.maxRunsPerTask}}function hw(){return{...$e(),maxRunsPerTask:Number.POSITIVE_INFINITY}}async function Jc($,Z,Q=$e()){if(!Q.enforced||!PY(Z))return;let Y=await $.storage.organizationBilling.taskClaim(Z.id);if(Y&&Y.runCount>=Q.maxRunsPerTask)throw ea($,"task_quota_blocked",Z,{phase:"precheck",reason:"runs_exhausted"}),new zX("runs_exhausted");if(Y&&Y.state!=="released")return;let X=await $.storage.organizationBilling.getBilling(Z.organizationId),J=KW0(X,Q);if(await $.storage.organizationBilling.countTaskClaims(Z.organizationId,J.periodKey)>=J.limit)throw ea($,"task_quota_blocked",Z,{phase:"precheck",reason:J.exhaustedReason,billing_mode:H11(J.periodKey),limit:J.limit}),new zX(J.exhaustedReason)}async function BF$($,Z,Q=$e()){if(!Q.enforced||!PY(Z))return"skipped";let Y=await $.storage.organizationBilling.getBilling(Z.organizationId),X=KW0(Y,Q),J=await $.storage.organizationBilling.claimTaskUnderLimit(Z.organizationId,Z.id,X.periodKey,X.limit,Q.maxRunsPerTask);if(J==="exhausted")throw ea($,"task_quota_blocked",Z,{phase:"claim",reason:X.exhaustedReason,billing_mode:H11(X.periodKey),limit:X.limit}),new zX(X.exhaustedReason);if(J==="runs_exhausted")throw ea($,"task_quota_blocked",Z,{phase:"claim",reason:"runs_exhausted"}),new zX("runs_exhausted");if(J==="claimed")ea($,"task_quota_claimed",Z,{billing_mode:H11(X.periodKey),period_key:X.periodKey,limit:X.limit});return J}async function OF$($,Z,Q,Y){if(Y==="skipped")return;await $.rollbackTaskClaim(Z,Q,{releaseSlot:Y==="claimed"}).catch((X)=>console.error("[task-quota] rollback failed (stays charged)",X))}async function DF$($,Z){let Q=await $.storage.organizationBilling.taskClaim(Z);return!!Q&&Q.state!=="released"}async function LF$($,Z,Q){if(await $.releaseTaskClaim(Z,Q).catch((X)=>{return console.error("[task-quota] refund failed (stays charged)",X),!1}))QJ({event:"task_quota_refunded",organizationId:Z,properties:{task_id:Q}})}var h24="[SUBSCRIPTION_REQUIRED]",u24,zX;var FW=D(()=>{C4();U6();F$();u24={trial_exhausted:"this organization used its free task executions \u2014 subscribe to keep running tasks",monthly_exhausted:"this organization used its monthly task executions \u2014 more become available next billing cycle",runs_exhausted:"this task reached its execution limit \u2014 create a new task to keep going"};zX=class zX extends Error{reason;constructor($){super(`${h24} ${u24[$]}`);this.reason=$;this.name="TaskQuotaError"}}});import{z as CB}from"zod";var U11;var wF$=D(()=>{C0();FW();U11=d({name:"ORGANIZATION_TASK_QUOTA_GET",description:"Get the organization's auto-task quota: how many runs are used in the current period, the limit, and the subscription's billing status.",annotations:{title:"Get Task Quota",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:CB.object({}),outputSchema:CB.object({enforced:CB.boolean(),billingStatus:CB.string(),subscribed:CB.boolean(),hasBillingAccount:CB.boolean(),used:CB.number(),limit:CB.number(),currentPeriodEnd:CB.string().datetime().nullable()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=$e(),X=await Z.storage.organizationBilling.getBilling(Q.id),J=KW0(X,Y),G=await Z.storage.organizationBilling.countTaskClaims(Q.id,J.periodKey);return{enforced:Y.enforced,billingStatus:X?.status??"none",subscribed:F11(X),hasBillingAccount:!!X?.stripeCustomerId,used:G,limit:J.limit,currentPeriodEnd:X?.currentPeriodEnd?.toISOString()??null}}})});var jF$=D(()=>{wH$();jH$();EH$();zH$();PH$();qH$();MH$();VH$();SH$();_H$();vH$();xH$();hH$();uH$();lH$();cH$();mH$();dH$();ZF$();QF$();YF$();wF$()});function UW($){let Z=$?.status;return typeof Z==="number"?Z:null}function EF$($){let Z=$;if(Z?.isRateLimited!==!0)return;return typeof Z.retryAfterMs==="number"?Z.retryAfterMs:null}async function EJ($,Z){let Q=await $.getBranch(Z);if(Q)return Q.sha;throw new y0({provider:$.repo.provider,status:404,message:`Branch ${Z} does not exist in ${$.repo.path}`})}var t6;var Ze=D(()=>{w5();t6=class t6 extends Error{constructor($,Z){super($,Z);this.name="RepoWriteConflict"}}});function Gc($){if($.length===0)return null;let Z=!1;for(let Q of $){if(Q.state!=="completed"){Z=!0;continue}if(Q.conclusion&&c24.has(Q.conclusion))return"failing"}return Z?"pending":"passing"}var c24,yA;var Qe=D(()=>{c24=new Set(["failure","cancelled","timed_out","action_required"]);yA=class yA extends Error{existing;constructor($,Z){super($);this.name="ChangeRequestExists",this.existing=Z}}});function Wc($){return m24.test($.trim())}function SZ($,Z,Q){if($===void 0||!Number.isFinite($)||$<=0)return Math.min(Z,Q);return Math.min(Math.floor($),Q)}async function Kc($,Z){let Q=$.headers.get("content-length"),Y=Q===null?Number.NaN:Number(Q),X=Number.isFinite(Y)&&Y>=0?Y:null,J=$.body;if(!J)return{content:"",size:X??0,truncated:!1};let G=J.getReader(),W=[],K=0,H=!1;try{for(;;){let{done:U,value:N}=await G.read();if(U)break;if(!N)continue;let B=Z-K;if(N.byteLength>=B){W.push(N.subarray(0,B)),K+=B,H=N.byteLength>B||!(await G.read()).done;break}W.push(N),K+=N.byteLength}}finally{await G.cancel().catch(()=>{})}return{content:new TextDecoder().decode(d24(W,K)),size:X??K,truncated:H||X!==null&&X>K}}function d24($,Z){let Q=new Uint8Array(Z),Y=0;for(let X of $)Q.set(X,Y),Y+=X.byteLength;return Q}function uG($){return $.split("/").map(encodeURIComponent).join("/")}function N11($){let Z=Number($);return Number.isInteger(Z)&&Z>1?Z:1}var uw=400,_B=2000,lw=60000,vB=200000,cw=50,mw=50,rK=100,m24;var Hc=D(()=>{m24=/\[bot\]$|[-_.]bot$|^bot[-_.]|^(dependabot|renovate)$/i});var rF;var B11=D(()=>{rF={name:"Deco Bot",email:"114028756+decobot@users.noreply.github.com"}});import{sql as i24}from"kysely";function zF$($){return $ instanceof Date?$.toISOString():String($)}function Ye($){let Z=$.installation_id===null||$.installation_id===void 0?null:Number($.installation_id);return{id:$.id,organizationId:$.organization_id,type:$.type,host:$.host,authKind:$.auth_kind,externalAccountId:$.external_account_id,login:$.login,avatarUrl:$.avatar_url,installationId:Number.isFinite(Z)?Z:null,status:$.status,installationAuthorizedBy:$.installation_authorized_by??null,installationRepositoryIds:$.installation_repository_ids??null,credentialConnectionId:$.credential_connection_id,connectedBy:$.connected_by_name?{name:$.connected_by_name}:null,createdAt:zF$($.created_at),updatedAt:zF$($.updated_at)}}class gA{db;constructor($){this.db=$}async upsert($){let Z=new Date,Q=await this.db.insertInto("git_provider_accounts").values({organization_id:$.organizationId,type:$.type,host:$.host.toLowerCase(),auth_kind:$.authKind,external_account_id:$.externalAccountId,login:$.login,avatar_url:$.avatarUrl??null,installation_id:$.installationId??null,installation_authorized_by:$.installationAuthorizedBy??null,installation_repository_ids:$.installationRepositoryIds?JSON.stringify($.installationRepositoryIds):null,credential_connection_id:null,status:"active",created_by:$.createdBy??null}).onConflict((Y)=>Y.columns(["organization_id","host","external_account_id"]).doUpdateSet({type:$.type,auth_kind:$.authKind,login:$.login,avatar_url:$.avatarUrl??null,installation_id:$.installationId??null,installation_authorized_by:$.installationAuthorizedBy??null,installation_repository_ids:$.installationRepositoryIds?JSON.stringify($.installationRepositoryIds):null,credential_connection_id:null,status:"active",updated_at:i24`GREATEST(${Z}, git_provider_accounts.updated_at + interval '1 millisecond')`})).returningAll().executeTakeFirstOrThrow();return Ye(Q)}async get($,Z){let Q=await this.db.selectFrom("git_provider_accounts").selectAll().where("id","=",$).where("organization_id","=",Z).executeTakeFirst();return Q?Ye(Q):null}async getUnscoped($){let Z=await this.db.selectFrom("git_provider_accounts").selectAll().where("id","=",$).executeTakeFirst();return Z?Ye(Z):null}async listByOrg($){return(await this.db.selectFrom("git_provider_accounts").leftJoin("user as connector","connector.id","git_provider_accounts.created_by").selectAll("git_provider_accounts").select("connector.name as connected_by_name").where("git_provider_accounts.organization_id","=",$).orderBy("git_provider_accounts.created_at","asc").execute()).map(Ye)}async findByExternalId($){let Z=await this.db.selectFrom("git_provider_accounts").selectAll().where("organization_id","=",$.organizationId).where("host","=",$.host.toLowerCase()).where("external_account_id","=",$.externalAccountId).executeTakeFirst();return Z?Ye(Z):null}async setStatus($,Z,Q){await this.db.updateTable("git_provider_accounts").set({status:Q,updated_at:new Date}).where("id","=",$).where("organization_id","=",Z).execute()}async delete($,Z){return(await this.db.deleteFrom("git_provider_accounts").where("id","=",$).where("organization_id","=",Z).executeTakeFirst()).numDeletedRows>0n}}var HW0=()=>{};class Xe{db;vault;constructor($,Z){this.db=$;this.vault=Z}async get($){let Z=await this.db.selectFrom("git_provider_account_credentials").selectAll().where("account_id","=",$).executeTakeFirst();if(!Z)return null;return p24(this.vault,Z)}async upsert($){let Z=new Date,Q=await this.vault.encrypt($.accessToken),Y=$.refreshToken?await this.vault.encrypt($.refreshToken):null,X=$.clientSecret?await this.vault.encrypt($.clientSecret):null;await this.db.insertInto("git_provider_account_credentials").values({account_id:$.connectionId,access_token:Q,refresh_token:Y,scope:$.scope,expires_at:$.expiresAt,client_id:$.clientId,client_secret:X,token_endpoint:$.tokenEndpoint}).onConflict((J)=>J.column("account_id").doUpdateSet({access_token:Q,refresh_token:Y,scope:$.scope,expires_at:$.expiresAt,client_id:$.clientId,client_secret:X,token_endpoint:$.tokenEndpoint,updated_at:Z})).execute()}async delete($){await this.db.deleteFrom("git_provider_account_credentials").where("account_id","=",$).execute()}isExpired($,Z=0){if(!$.expiresAt)return!1;let Y=($.expiresAt instanceof Date?$.expiresAt:new Date($.expiresAt)).getTime();if(Number.isNaN(Y))return!0;return Y-Z<Date.now()}}async function p24($,Z){try{let Q=await $.decrypt(Z.access_token),Y=Z.refresh_token?await $.decrypt(Z.refresh_token):null,X=Z.client_secret?await $.decrypt(Z.client_secret):null;return{id:Z.account_id,connectionId:Z.account_id,accessToken:Q,refreshToken:Y,scope:Z.scope,expiresAt:Z.expires_at,createdAt:Z.created_at,updatedAt:Z.updated_at,clientId:Z.client_id,clientSecret:X,tokenEndpoint:Z.token_endpoint}}catch(Q){return console.warn("[GitProviderAccountCredential] failed to decrypt credential row",{accountId:Z.account_id,message:Q instanceof Error?Q.message:String(Q)}),null}}import{sql as n24}from"kysely";function PF$($){return $ instanceof Date?$.toISOString():String($)}function hA($){return{id:$.id,organizationId:$.organization_id,accountId:$.account_id,provider:$.provider,host:$.host,path:$.path,externalId:$.external_id,defaultBranch:$.default_branch,webUrl:$.web_url,visibility:$.visibility,sandboxImage:Da.catch("default").parse($.sandbox_image),legacyConnectionId:$.legacy_connection_id,createdAt:PF$($.created_at),updatedAt:PF$($.updated_at)}}function bB($){return{provider:$.provider,host:$.host,path:$.path}}class Je{db;constructor($){this.db=$}async upsert($){let Z=$.ref.host.toLowerCase(),Q=await this.findByRef($.organizationId,$.ref);if(Q){let X=await this.db.updateTable("repositories").set({path:$.ref.path,provider:$.ref.provider,web_url:OJ({...$.ref,host:Z}),...$.accountId!==void 0?{account_id:$.accountId}:{},...$.externalId!==void 0?{external_id:$.externalId}:{},...$.defaultBranch!==void 0?{default_branch:$.defaultBranch}:{},...$.visibility!==void 0?{visibility:$.visibility}:{},...$.sandboxImage!==void 0?{sandbox_image:$.sandboxImage}:{},...$.legacyConnectionId!==void 0?{legacy_connection_id:$.legacyConnectionId}:{},updated_at:new Date}).where("id","=",Q.id).where("organization_id","=",$.organizationId).returningAll().executeTakeFirstOrThrow();return hA(X)}let Y=await this.db.insertInto("repositories").values({organization_id:$.organizationId,account_id:$.accountId??null,provider:$.ref.provider,host:Z,path:$.ref.path,external_id:$.externalId??null,default_branch:$.defaultBranch??null,web_url:OJ({...$.ref,host:Z}),visibility:$.visibility??null,sandbox_image:$.sandboxImage??null,legacy_connection_id:$.legacyConnectionId??null,created_by:$.createdBy??null}).returningAll().executeTakeFirstOrThrow();return hA(Y)}async get($,Z){let Q=await this.db.selectFrom("repositories").selectAll().where("id","=",$).where("organization_id","=",Z).executeTakeFirst();return Q?hA(Q):null}async getUnscoped($){let Z=await this.db.selectFrom("repositories").selectAll().where("id","=",$).executeTakeFirst();return Z?hA(Z):null}async findByRef($,Z){let Q=await this.db.selectFrom("repositories").selectAll().where("organization_id","=",$).where("host","=",Z.host.toLowerCase()).where(n24`lower(path)`,"=",Z.path.toLowerCase()).executeTakeFirst();return Q?hA(Q):null}async listByOrg($,Z){let Q=this.db.selectFrom("repositories").selectAll().where("organization_id","=",$);if(Z?.accountId)Q=Q.where("account_id","=",Z.accountId);return(await Q.orderBy("path","asc").execute()).map(hA)}async setSandboxImage($,Z,Q){let Y=await this.db.updateTable("repositories").set({sandbox_image:Q,updated_at:new Date}).where("id","=",$).where("organization_id","=",Z).returningAll().executeTakeFirst();return Y?hA(Y):null}async delete($,Z){try{return(await this.db.deleteFrom("repositories").where("id","=",$).where("organization_id","=",Z).executeTakeFirst()).numDeletedRows>0n}catch(Q){if(Q instanceof Error&&"constraint"in Q&&Q.constraint==="org_repo_sync_source_present")throw Error("Remove this repository's sync configurations before unlinking it");throw Q}}}var Fc=D(()=>{T6()});function TF$($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function t24($,Z){let{owner:Q}=h5(Z),Y=TF$(Z.host),X=new RegExp(`(?:https?://(?:[^@\\s/]*@)?${Y}/|git@${Y}:)${TF$(Q)}/([A-Za-z0-9._-]+)`,"gi");return[...$.matchAll(X)].flatMap((J)=>J[1]?.replace(/\.git$/i,"")||[])}async function RF$($,Z){let{owner:Q,name:Y}=h5(Z),X=new Set,J=[Z.path];while(J.length>0&&X.size<AF$){let G=J.shift();if(!G)break;let W=await $(G,"pubspec.yaml").catch(()=>null);if(!W)continue;for(let K of t24(W,Z)){if(K===Y||X.has(K))continue;if(X.size>=AF$)break;X.add(K),J.push(`${Q}/${K}`)}}return[...X]}var AF$=20;var qF$=D(()=>{T6()});function IF$($){return Bun.hash($).toString(36)}function o24($){for(let[Z,Q]of dw)if(Q.expiresAt<=$)dw.delete(Z);while(dw.size>=512){let Z=dw.keys().next();if(Z.done)break;dw.delete(Z.value)}}function D11($,Z,Q,Y=Date.now()){o24(Y),dw.set(IF$($),{owner:Z,expiresAt:Q})}function Uc($,Z=Date.now()){let Q=IF$($),Y=dw.get(Q);if(!Y)return"unknown";if(Y.expiresAt<=Z)return dw.delete(Q),"unknown";return Y.owner}var MF$="app",O11="user",dw;var Nc=D(()=>{dw=new Map});function iw($=process.env){let Z=$.GITHUB_APP_ID?.trim(),Q=$.GITHUB_APP_PRIVATE_KEY?.trim(),Y=$.GITHUB_APP_CLIENT_ID?.trim(),X=$.GITHUB_APP_CLIENT_SECRET?.trim(),J=$.GITHUB_APP_SLUG?.trim();if(!Z||!Q||!Y||!X||!J)return null;return{appId:Z,privateKeyPem:Q.replace(/\\n/g,`
|
|
1016
1016
|
`),clientId:Y,clientSecret:X,slug:J}}function uA($,Z){let Q=$.get(Z);if(Q===null)return null;let Y=Number(Q);return Number.isFinite(Y)?Y:null}function r24($){return{limit:uA($,"x-ratelimit-limit"),remaining:uA($,"x-ratelimit-remaining"),reset:uA($,"x-ratelimit-reset"),used:uA($,"x-ratelimit-used"),resource:$.get("x-ratelimit-resource")}}function pw($){if($.status===429)return!0;if($.status!==403)return!1;if($.headers.get("retry-after")!==null)return!0;return uA($.headers,"x-ratelimit-remaining")===0}function nw($,Z=Date.now()){let Q=uA($,"retry-after");if(Q!==null)return Math.max(0,Q*1000);let Y=uA($,"x-ratelimit-reset");if(Y!==null)return Math.max(0,Y*1000-Z);return null}function tw($,Z){let Q=r24($),Y=Q.resource??"unknown",X={installation:Z.installation,resource:Y},J={...X,lane:Z.lane,operation:Z.operation};if(SF$??=z$.createCounter("github_api_calls",{description:"Calls to the GitHub API, by transport and operation",unit:"{calls}"}),SF$.add(1,J),Q.remaining!==null)VF$??=z$.createGauge("github_rate_limit_remaining",{description:"Requests (REST) or points (GraphQL) left in the window",unit:"{requests}"}),VF$.record(Q.remaining,X);if(Q.used!==null)kF$??=z$.createGauge("github_rate_limit_used",{description:"Requests (REST) or points (GraphQL) spent in the window",unit:"{requests}"}),kF$.record(Q.used,X);return Q}function ow($){CF$??=z$.createCounter("github_rate_limited",{description:"GitHub responses refused for rate-limit reasons",unit:"{responses}"}),CF$.add(1,$)}var VF$=null,kF$=null,SF$=null,CF$=null;var Ge=D(()=>{C6()});function NW($){return process.env.GITHUB_API_BASE_URL??wB("github",$)}async function CZ($,Z){let Q={Authorization:`Bearer ${Z.token}`,Accept:Z.accept??a24,"X-GitHub-Api-Version":s24};if(Z.body!==void 0)Q["Content-Type"]="application/json";let Y;try{Y=await fetch($,{method:Z.method??"GET",headers:Q,body:Z.body===void 0?void 0:JSON.stringify(Z.body),signal:AbortSignal.timeout(Z.timeoutMs??L11)})}catch(J){throw new y0({provider:"github",status:0,message:`GitHub ${Z.operation} failed: ${J instanceof Error?J.message:String(J)}`,cause:J})}let X=Uc(Z.token);if(tw(Y.headers,{lane:"rest",operation:Z.operation,installation:X}),pw(Y)){await Y.body?.cancel().catch(()=>{});let J=Y.headers.get("retry-after")!==null?"secondary":"primary";ow({lane:"rest",operation:Z.operation,installation:X,kind:J});let G=nw(Y.headers);throw new y0({provider:"github",status:Y.status,retryAfterMs:G,message:`GitHub ${J} rate limit reached${G===null?"":`; retry in ${Math.ceil(G/1000)}s`}`})}return Y}function w11($){try{let Z=JSON.parse($);if(Z!==null&&typeof Z==="object"&&"message"in Z&&typeof Z.message==="string"&&Z.message.length>0)return Z.message}catch{}return $.slice(0,300)}function j11($,Z,Q){let Y=w11(Z);return new y0({provider:"github",status:$,message:`GitHub ${Q} failed: ${$}${Y?` ${Y}`:""}`})}async function _Z($,Z){let Q=await $.text().catch(()=>"");return j11($.status,Q,Z)}async function kQ($,Z){let Q=await $.text();try{return JSON.parse(Q)}catch(Y){throw new y0({provider:"github",status:$.status,message:`GitHub ${Z} returned invalid JSON: ${Q.slice(0,300)}`,cause:Y})}}var s24="2022-11-28",a24="application/vnd.github+json",L11=15000;var rw=D(()=>{T6();Ge();Nc();w5()});function YT4($){return $==="public"||$==="private"||$==="internal"}function vF$($,Z){let Q="public";if($.private)Q="private";else if($.visibility&&YT4($.visibility))Q=$.visibility;return{ref:{provider:"github",host:Z,path:$.full_name},externalId:String($.id),defaultBranch:$.default_branch??null,webUrl:$.html_url,visibility:Q,description:$.description??null,updatedAt:$.pushed_at??$.updated_at??null}}function E11($,Z){let Q=Z?.trim().toLowerCase();if(!Q)return!0;return $.toLowerCase().includes(Q)}function XT4($){return{name:$.name||$.login,email:$.email||`${$.login}@users.noreply.github.com`}}function JT4($){return $.split("/").filter(Boolean).map(encodeURIComponent).join("/")}function GT4($,Z){let{owner:Q,name:Y}=h5($),X=`/repos/${encodeURIComponent(Q)}/${encodeURIComponent(Y)}/tarball`;return Z?`${X}/${encodeURIComponent(Z)}`:X}class lA{kind="github";host;apiBaseUrl;options;grantedIds=new Map;constructor($){this.options=$,this.host=$.host.toLowerCase(),this.apiBaseUrl=NW($.host)}async tokenForRepo($,Z={}){let Q=this.options;if("appAuth"in Q){let Y=Q.repositoryIds??null,X=Z.alsoRepositories??[],J=await Q.appAuth.installationToken(Q.installationId,{...Y?{repositoryIds:[await this.grantedRepositoryId($,Y),...await this.grantedSiblingIds($,X,Y)]}:{repositories:[Le0($),...X]},permissions:s30,bufferMs:Z.bufferMs,forceRefresh:Z.forceRefresh});return{token:J.token,kind:"installation",expiresAt:J.expiresAt}}return this.sourceToken(Q.tokenSource,Z)}async accountToken($={}){let Z=this.options;if("appAuth"in Z){let Q=await Z.appAuth.installationToken(Z.installationId,{...Z.repositoryIds?{repositoryIds:Z.repositoryIds}:{},permissions:e24,bufferMs:$.bufferMs,forceRefresh:$.forceRefresh});return{token:Q.token,kind:"installation",expiresAt:Q.expiresAt}}return this.sourceToken(Z.tokenSource,$)}async grantedRepositoryId($,Z){let Q=$.path.toLowerCase(),Y=this.grantedIds.get(Q);if(Y!==void 0)return Y;let X=Number((await this.getRepo($))?.externalId);if(!Number.isSafeInteger(X)||!Z.includes(X))throw new y0({provider:"github",status:403,message:`${$.path} is outside what this GitHub account authorized for Studio. Ask someone who administers it to connect it.`});return this.grantedIds.set(Q,X),X}async grantedSiblingIds($,Z,Q){let{owner:Y}=h5($),X=[];for(let J of Z){let G=await this.getRepo({...$,path:`${Y}/${J}`}).catch(()=>null),W=Number(G?.externalId);if(Number.isSafeInteger(W)&&Q.includes(W))X.push(W)}return X}async sourceToken($,Z){let Q=await $.get(Z);if(!Q)throw new y0({provider:"github",status:401,message:`No usable GitHub token for ${this.host}; reconnect the account`});return Q}async getRepo($){let{owner:Q,name:Y}=h5($),X=await this.request(`/repos/${encodeURIComponent(Q)}/${encodeURIComponent(Y)}`,{operation:"get_repo"});if(X.status===404)return await X.body?.cancel().catch(()=>{}),null;if(!X.ok)throw await _Z(X,"get_repo");return vF$(await kQ(X,"get_repo"),this.host)}async listRepos($={}){let Z=Math.max(1,Math.floor($.page??1)),Q=Math.min(ZT4,Math.max(1,Math.floor($.perPage??$T4))),Y=`per_page=${Q}&page=${Z}`,X;if("appAuth"in this.options){let G=await this.request(`/installation/repositories?${Y}`,{operation:"list_installation_repositories"});if(!G.ok)throw await _Z(G,"list_installation_repositories");let W=await kQ(G,"list_installation_repositories");X=Array.isArray(W.repositories)?W.repositories:[]}else{let G=await this.request(`/user/repos?affiliation=owner,collaborator,organization_member&sort=pushed&${Y}`,{operation:"list_user_repositories"});if(!G.ok)throw await _Z(G,"list_user_repositories");let W=await kQ(G,"list_user_repositories");X=Array.isArray(W)?W:[]}return{repositories:X.filter((J)=>E11(J.full_name,$.query)).map((J)=>vF$(J,this.host)),hasMore:X.length===Q}}async readFile($,Z,Q){let{owner:X,name:J}=h5($),G=Q?`?ref=${encodeURIComponent(Q)}`:"",W=await this.request(`/repos/${encodeURIComponent(X)}/${encodeURIComponent(J)}/contents/${JT4(Z)}${G}`,{operation:"read_file",accept:QT4});if(W.status===404)return await W.body?.cancel().catch(()=>{}),null;if(!W.ok)throw await _Z(W,"read_file");return W.text()}async archiveTarball($,Z){let Y=`${this.apiBaseUrl}${GT4($,Z)}`,X=await this.tokenForRepo($),J=await CZ(Y,{operation:"archive_tarball",token:X.token,timeoutMs:_F$});if(J.status===401){await J.body?.cancel().catch(()=>{});let G=await this.tokenForRepo($,{forceRefresh:!0});J=await CZ(Y,{operation:"archive_tarball",token:G.token,timeoutMs:_F$})}if(J.status===404)return await J.body?.cancel().catch(()=>{}),null;if(!J.ok)throw await _Z(J,"archive_tarball");return J.body}async identity(){if("appAuth"in this.options)return null;let $="get_user",Z=await this.request("/user",{operation:$});if(!Z.ok)throw await _Z(Z,$);return XT4(await kQ(Z,$))}async request($,Z){let Q=`${this.apiBaseUrl}${$}`,Y=await this.accountToken(),X=await CZ(Q,{...Z,token:Y.token});if(X.status!==401)return X;await X.body?.cancel().catch(()=>{});let J=await this.accountToken({forceRefresh:!0});return CZ(Q,{...Z,token:J.token})}}var e24,$T4=30,ZT4=100,QT4="application/vnd.github.raw+json",_F$=60000;var FW0=D(()=>{T6();wJ();w5();rw();e24={metadata:"read",contents:"read"}});import{z as sw}from"zod";function UW0($){return $.repositories.filter((Z)=>Z.permissions?.admin===!0).map((Z)=>({id:Z.id,name:Z.full_name}))}function NW0($){if($.total_count===void 0)return-1;return Math.max(0,Math.ceil($.total_count/cA)-1)}function xF$($){return NW0($)===0&&UW0($).length===0}function fF$($,Z,Q){let Y=$.filter((J)=>E11(J.name,Q)),X=(Z-1)*cA;return{repositories:Y.slice(X,X+cA),hasMore:Y.length>X+cA}}function yF$($,Z){let Q=new Set($.map((Y)=>Y.id));return Z.every((Y)=>Q.has(Y))}function gF$($,Z,Q){if(Z!==null){let J=new Set(Z);return $.filter((G)=>J.has(G.id)).map((G)=>G.id)}let Y=new Set(Q.flatMap((J)=>J.externalId?[J.externalId]:[])),X=new Set(Q.filter((J)=>!J.externalId).map((J)=>J.path.toLowerCase()));return $.filter((J)=>Y.has(String(J.id))||X.has(J.name.toLowerCase())).map((J)=>J.id)}class z11{ttlMs;entries=new Map;constructor($){this.ttlMs=$}installations($){return this.live($)?.installations}repositories($,Z){return this.live($)?.repositories.get(Z)}rememberInstallations($,Z){this.entry($).installations=Z}rememberRepositories($,Z,Q){this.entry($).repositories.set(Z,Q)}forget($){this.entries.delete($)}live($){let Z=this.entries.get($);if(!Z)return;if(Z.expiresAt<=Date.now()){this.entries.delete($);return}return Z}entry($){let Z=Date.now();for(let[Y,X]of this.entries)if(X.expiresAt<=Z)this.entries.delete(Y);let Q=this.entries.get($);if(!Q)Q={expiresAt:Z+this.ttlMs,repositories:new Map},this.entries.set($,Q);return Q}}var cA=100,bF$;var P11=D(()=>{FW0();bF$=sw.object({total_count:sw.number().int().nonnegative().optional(),repositories:sw.array(sw.object({id:sw.number().int().positive().safe(),full_name:sw.string().min(1),permissions:sw.object({admin:sw.boolean().optional()}).optional()}))})});import{createPrivateKey as lF$,sign as WT4}from"crypto";import{z as hF$}from"zod";function A11($){return Buffer.from($).toString("base64url")}function BT4($){let Z=A11(JSON.stringify({alg:"RS256",typ:"JWT"})),Q=A11(JSON.stringify({iat:$.nowSeconds-HT4,exp:$.nowSeconds+R11,iss:$.appId})),Y=`${Z}.${Q}`,X=WT4("RSA-SHA256",Buffer.from(Y),lF$($.privateKeyPem));return`${Y}.${A11(X)}`}function OT4($){let Z=ca.find((X)=>(X in $));if(!Z)return null;let{[Z]:Q,...Y}=$;return Y}function DT4($){let{repositories:Z,repositoryIds:Q}=$;if(Z&&Q)return"A GitHub installation token is scoped by repository name or by id, never both";let Y=Z?.length??Q?.length;if(Y!==void 0&&(Y===0||Y>BW0))return`A GitHub installation token covers 1 to ${BW0} repositories, not ${Y}`;if(Q?.some((X)=>!Number.isSafeInteger(X)||X<=0))return"A GitHub repository id must be a positive integer";return null}function LT4($,Z){let Q=(Z.repositories??[]).map((J)=>J.toLowerCase()).sort(),Y=Object.entries(Z.permissions??{}).map(([J,G])=>`${J}=${G}`).sort(),X=Z.repositoryIds?`ids:${[...Z.repositoryIds].sort((J,G)=>J-G).join(",")}`:"all";return`${$}|${Q.join(",")}|${X}|${Y.join(",")}`}function wT4($,Z){for(let[Q,Y]of $)if(Y.expiresAt.getTime()<=Z)$.delete(Q)}function uF$($){let Z=$.account;if(typeof $.id!=="number"||!Z||typeof Z.id!=="number"||typeof Z.login!=="string")return null;return{installationId:$.id,externalAccountId:String(Z.id),login:Z.login,avatarUrl:typeof Z.avatar_url==="string"?Z.avatar_url:null,accountType:typeof Z.type==="string"?Z.type:"User",htmlUrl:typeof $.html_url==="string"?$.html_url:null}}function jT4($){if(!$||typeof $!=="object"||Array.isArray($))return null;let Z={};for(let[Q,Y]of Object.entries($))if(typeof Y==="string")Z[Q]=Y;return Z}class cF${appId;privateKeyPem;apiBaseUrl;jwt=null;cache=new Map;inFlight=new Map;flowAccess=new z11(NT4);constructor($,Z){this.appId=$.appId,this.privateKeyPem=$.privateKeyPem,this.apiBaseUrl=(Z?.apiBaseUrl??KT4).replace(/\/+$/,"")}appJwt(){let $=Math.floor(Date.now()/1000);if(this.jwt&&this.jwt.exp-$>FT4)return this.jwt.value;let Z=BT4({appId:this.appId,privateKeyPem:this.privateKeyPem,nowSeconds:$});return this.jwt={value:Z,exp:$+R11},D11(Z,MF$,($+R11)*1000),Z}installationToken($,Z={}){let Q=DT4(Z);if(Q)return Promise.reject(new y0({provider:"github",status:403,message:Q}));let Y=LT4($,Z),X=Z.bufferMs??UT4;if(!Z.forceRefresh){let W=this.cache.get(Y);if(W&&W.expiresAt.getTime()-Date.now()>X)return Promise.resolve(W)}let J=this.inFlight.get(Y);if(J)return J;let G=this.mint($,Z).then((W)=>{return this.cache.set(Y,W),D11(W.token,String($),W.expiresAt.getTime()),wT4(this.cache,Date.now()),W}).finally(()=>{this.inFlight.delete(Y)});return this.inFlight.set(Y,G),G}async mint($,Z){let Y=`${this.apiBaseUrl}/app/installations/${$}/access_tokens`,X=Z.repositories&&Z.repositories.length>0?Z.repositories:void 0,J=Z.permissions?{...Z.permissions}:void 0;for(;;){let G=await CZ(Y,{method:"POST",token:this.appJwt(),body:{...X&&{repositories:X},...Z.repositoryIds&&{repository_ids:Z.repositoryIds},...J&&{permissions:J}},operation:"installation_access_token"});if(G.ok){let W=await kQ(G,"installation_access_token");if(typeof W.token!=="string"||W.token.length===0||typeof W.expires_at!=="string"||W.expires_at.length===0)throw new y0({provider:"github",status:G.status,message:"GitHub installation_access_token returned no token"});let K=new Date(W.expires_at);if(isNaN(K.getTime()))throw new y0({provider:"github",status:G.status,message:"GitHub installation_access_token returned invalid token expiration"});return{token:W.token,expiresAt:K,permissions:jT4(W.permissions)??J??{}}}if(G.status===422&&J){let W=await G.text().catch(()=>""),K=OT4(J);if(K&&N01(w11(W))){J=K;continue}throw j11(G.status,W,"installation_access_token")}throw await _Z(G,"installation_access_token")}}async getInstallation($){let Q=await CZ(`${this.apiBaseUrl}/app/installations/${$}`,{token:this.appJwt(),operation:"get_installation"});if(Q.status===404)return null;if(!Q.ok)throw await _Z(Q,"get_installation");let Y=uF$(await kQ(Q,"get_installation"));if(!Y)throw new y0({provider:"github",status:Q.status,message:"GitHub get_installation returned an installation without a user or organization account"});return Y}async connectingUserId($){let Z=hF$.object({id:hF$.number().int().positive().safe()}).parse(await this.userGet("/user",$,"get_connecting_user"));return String(Z.id)}async listConnectableInstallations($,Z){this.flowAccess.forget($);let Q=await this.listUserInstallations(Z);return this.flowAccess.rememberInstallations($,Q),(await $7(Q,4,async(X)=>{let J=await this.repositoryPage(Z,X.installationId,1);if(NW0(J)===0)this.flowAccess.rememberRepositories($,X.installationId,UW0(J));return xF$(J)?null:X})).filter((X)=>X!==null)}async connectableInstallation($,Z,Q,Y={}){let X=Y.fresh?void 0:this.flowAccess.installations($);if(!X)X=await this.listUserInstallations(Z),this.flowAccess.rememberInstallations($,X);return X.find((J)=>J.installationId===Q)??null}async delegableRepositories($,Z,Q,Y={}){if(!Y.fresh){let K=this.flowAccess.repositories($,Q);if(K)return K}let X=await this.repositoryPage(Z,Q,1),J=[X],G=NW0(X);if(G>0)J.push(...await $7(Array.from({length:G},(K,H)=>H+2),4,(K)=>this.repositoryPage(Z,Q,K)));else if(G<0)for(let K=2;J[J.length-1].repositories.length===cA;K++)J.push(await this.repositoryPage(Z,Q,K));let W=J.flatMap(UW0);return this.flowAccess.rememberRepositories($,Q,W),W}forgetFlow($){this.flowAccess.forget($)}async repositoryPage($,Z,Q){return bF$.parse(await this.userGet(`/user/installations/${Z}/repositories?per_page=${cA}&page=${Q}`,$,"list_connecting_user_repositories"))}async userGet($,Z,Q){let Y=await CZ(`${this.apiBaseUrl}${$}`,{token:Z,operation:Q});if(!Y.ok)throw await _Z(Y,Q);return kQ(Y,Q)}async listUserInstallations($){let Y=[];for(let X=1;;X++){let J=await CZ(`${this.apiBaseUrl}/user/installations?per_page=100&page=${X}`,{token:$,operation:"list_user_installations"});if(!J.ok)throw await _Z(J,"list_user_installations");let G=await kQ(J,"list_user_installations"),W=Array.isArray(G.installations)?G.installations:[];for(let K of W){let H=uF$(K);if(H)Y.push(H)}if(W.length<100)return Y}}}function sK(){if(T11===void 0){let $=iw();T11=$&&ET4($)?new cF$($,{apiBaseUrl:NW("github.com")}):null}return T11}function ET4($){try{return lF$($.privateKeyPem),!0}catch(Z){return console.error("[git-providers] GITHUB_APP_PRIVATE_KEY is not a usable private key \u2014 "+"the GitHub App stays disabled and orgs keep their existing connections. Check that newlines survived the secret store.",Z),!1}}function mF$(){let $=iw()!==null&&sK()!==null;return{configured:$,hosts:$?[zT4]:[]}}var KT4="https://api.github.com",HT4=60,R11=540,FT4=60,UT4=300000,NT4=600000,BW0=500,T11,zT4="github.com";var OW0=D(()=>{D8();wJ();Nc();w5();P11();rw()});import{execFile as PT4}from"child_process";import{promisify as AT4}from"util";import{z as DW0}from"zod";function mA(){return E0().localMode}function We($){return new y0({provider:"github",status:403,message:$})}async function dF$($){if(!mA())throw We("GitHub CLI connections are only available in local mode.");let Z={...process.env,GH_PROMPT_DISABLED:"1"};delete Z.GH_TOKEN,delete Z.GITHUB_TOKEN,delete Z.GH_DEBUG,delete Z.DEBUG;try{let{stdout:Q}=await TT4("gh",["auth","token","--hostname",q11,...$?["--user",$]:[]],{env:Z,timeout:1e4,maxBuffer:16384}),Y=Q.trim();if(!Y||/\s/.test(Y))throw Error("Invalid CLI token");return Y}catch{throw We("Could not read your GitHub CLI login. Install gh and run gh auth login --hostname github.com, then connect again.")}}async function iF$($){try{let Z=await CZ(`${NW(q11)}/user`,{token:$,operation:"cli_current_user"});if(!Z.ok)throw Error("GitHub rejected the CLI token");return RT4.parse(await Z.json())}catch{throw We("Could not verify your GitHub CLI account. Run gh auth login --hostname github.com and connect again.")}}async function pF$(){let $=await iF$(await dF$());return{externalAccountId:`cli:user:${$.id}`,login:$.login,avatarUrl:$.avatar_url??null}}function nF$($){return{kind:"token",async get(){if($.host!==q11)throw We("Unsupported GitHub CLI host.");let Z=await dF$($.login);if(`cli:user:${(await iF$(Z)).id}`!==$.externalAccountId)throw We("Your GitHub CLI account changed. Connect it again.");return{token:Z,kind:"token",expiresAt:null}}}}var TT4,q11="github.com",RT4;var LW0=D(()=>{F$();w5();rw();TT4=AT4(PT4),RT4=DW0.object({id:DW0.number().int().positive().safe(),login:DW0.string().min(1),avatar_url:DW0.string().url().nullable().optional()})});function Bc($){return wB("gitlab",$)}function MT4($){try{let Z=JSON.parse($);if(Z!==null&&typeof Z==="object"){let Q=Z,Y=[...bN(Q.message),...bN(Q.error),...bN(Q.error_description)];if(Y.length>0)return Y.join("; ")}}catch{}return $.slice(0,300)}async function lG($){let Z=await $.text().catch(()=>""),Q=Z?MT4(Z):$.statusText;return new y0({provider:"gitlab",status:$.status,message:`GitLab API ${$.status}: ${Q}`,retryAfterMs:$.status===429?tF$($.headers):null})}async function Ke($,Z){let Q=await $.text();try{return JSON.parse(Q)}catch(Y){throw new y0({provider:"gitlab",status:$.status,message:`GitLab ${Z} returned invalid JSON: ${Q.slice(0,300)}`,cause:Y})}}async function sF($,Z,Q={}){let Y={Authorization:`Bearer ${Z}`,Accept:Q.accept??"application/json"};if(Q.body!==void 0)Y["Content-Type"]="application/json";try{return await fetch($,{method:Q.method??"GET",headers:Y,body:Q.body===void 0?void 0:JSON.stringify(Q.body),signal:AbortSignal.timeout(Q.timeoutMs??qT4)})}catch(X){throw new y0({provider:"gitlab",status:0,message:`GitLab request failed: ${X instanceof Error?X.message:String(X)}`,cause:X})}}var qT4=15000;var He=D(()=>{T6();w5();aw()});import{z as AY}from"zod";function xB($){return encodeURIComponent($)}function Fe($){return encodeURIComponent($.replace(/^\/+/,""))}function ST4($,Z){let Q=`/projects/${xB($.path)}/repository/archive.tar.gz`;return Z?`${Q}?sha=${encodeURIComponent(Z)}`:Q}function tF$($,Z=Date.now()){let Q=$.get("retry-after");if(Q!==null){let X=Number(Q);if(Number.isFinite(X))return Math.max(0,X*1000);let J=Date.parse(Q);if(Number.isFinite(J))return Math.max(0,J-Z)}let Y=$.get("ratelimit-reset");if(Y!==null){let X=Number(Y);if(Number.isFinite(X))return Math.max(0,X*1000-Z)}return null}function oF$($,Z){let Q=CT4.parse($),Y={provider:"gitlab",host:Z,path:Q.path_with_namespace};return{ref:Y,externalId:String(Q.id),defaultBranch:Q.default_branch??null,webUrl:Q.web_url??OJ(Y),visibility:Q.visibility,description:Q.description??null,updatedAt:Q.last_activity_at??null}}async function _T4($,Z,Q={}){let Y=await sF($,Z,Q);if(Y.status===404)return await Y.body?.cancel().catch(()=>{}),null;if(!Y.ok)throw await lG(Y);return Y}async function vT4($,Z){let Q=await _T4(`${wB("gitlab",$)}/user`,Z);if(!Q)throw new y0({provider:"gitlab",status:404,message:"GitLab did not recognise the authenticated user"});return rF$.parse(await Ke(Q,"get_user"))}async function wW0($,Z){let Q=await vT4($,Z);return{externalAccountId:String(Q.id),login:Q.username,avatarUrl:Q.avatar_url??null}}class Ue{kind="gitlab";host;apiBase;tokenSource;constructor($){this.host=$.host,this.apiBase=wB("gitlab",$.host),this.tokenSource=$.tokenSource}async tokenForRepo($,Z){return this.accountToken(Z)}async accountToken($){let Z=await this.tokenSource.get($);if(!Z)throw new y0({provider:"gitlab",status:401,message:"GitLab account is not authenticated"});return Z}async getRepo($){let Z=await this.get(`/projects/${xB($.path)}`);if(!Z)return null;return oF$(await Ke(Z,"get_repo"),this.host)}async listRepos($={}){let Z=new URLSearchParams({membership:"true",simple:"true",order_by:"id",sort:"desc",per_page:String(Math.min(kT4,Math.max(1,$.perPage??VT4))),page:String(Math.max(1,$.page??1))}),Q=$.query?.trim();if(Q)Z.set("search",Q);let Y=await this.get(`/projects?${Z}`);if(!Y)return{repositories:[],hasMore:!1};let X=await Ke(Y,"list_repos");if(!Array.isArray(X))throw new y0({provider:"gitlab",status:502,message:"GitLab /projects returned a non-array payload"});return{repositories:X.map((J)=>oF$(J,this.host)),hasMore:X.length===Number(Z.get("per_page"))}}async readFile($,Z,Q){let Y=Q;if(!Y){let J=await this.getRepo($);if(!J?.defaultBranch)return null;Y=J.defaultBranch}let X=await this.get(`/projects/${xB($.path)}/repository/files/${Fe(Z)}/raw?ref=${encodeURIComponent(Y)}`,{accept:"text/plain, */*"});if(!X)return null;return X.text()}async archiveTarball($,Z){let Q=await this.authedFetch(`${this.apiBase}${ST4($,Z)}`,{accept:"application/octet-stream, */*",timeoutMs:IT4});if(Q.status===404)return await Q.body?.cancel().catch(()=>{}),null;if(!Q.ok)throw await lG(Q);return Q.body}async identity(){let $=await this.authedFetch(`${this.apiBase}/user`);if(!$.ok)throw await lG($);let Z=rF$.parse(await Ke($,"identity"));return{name:Z.name||Z.username,email:Z.commit_email||Z.public_email||Z.email||`${Z.username}@users.noreply.${this.host}`}}async get($,Z){let Q=await this.authedFetch(`${this.apiBase}${$}`,Z);if(Q.status===404)return await Q.body?.cancel().catch(()=>{}),null;if(!Q.ok)throw await lG(Q);return Q}async authedFetch($,Z={}){let Q=await this.accountToken(),Y=await sF($,Q.token,Z);if(Y.status!==401)return Y;await Y.body?.cancel().catch(()=>{});let X=await this.accountToken({forceRefresh:!0});return sF($,X.token,Z)}}var IT4=60000,VT4=30,kT4=100,CT4,rF$;var aw=D(()=>{T6();w5();He();CT4=AY.object({id:AY.number(),path_with_namespace:AY.string().min(1),default_branch:AY.string().nullish(),web_url:AY.string().nullish(),visibility:AY.enum(["public","private","internal"]),description:AY.string().nullish(),last_activity_at:AY.string().nullish()});rF$=AY.object({id:AY.number(),username:AY.string().min(1),name:AY.string().nullish(),avatar_url:AY.string().nullish(),email:AY.string().nullish(),public_email:AY.string().nullish(),commit_email:AY.string().nullish()})});function jW0($=process.env){let Z=$.BITBUCKET_OAUTH_CLIENT_ID?.trim(),Q=$.BITBUCKET_OAUTH_CLIENT_SECRET?.trim();if(!Z||!Q)return null;return{host:fB,clientId:Z,clientSecret:Q}}function sF$(){let $=jW0();return{configured:$!==null,hosts:$?[$.host]:[]}}var fB;var Oc=D(()=>{T6();fB=B30.bitbucket});function Ne($){if($.toLowerCase()===fB)return;throw new y0({provider:"bitbucket",status:400,message:`${$} is not Bitbucket Cloud. Only bitbucket.org is supported; Bitbucket Data Center has a different API.`})}function xT4($,Z=Date.now()){let Q=$.get("retry-after");if(Q===null)return null;let Y=Number(Q);if(Number.isFinite(Y))return Math.max(0,Y*1000);let X=Date.parse(Q);return Number.isFinite(X)?Math.max(0,X-Z):null}function fT4($){try{let Z=JSON.parse($);if(Z!==null&&typeof Z==="object"){let Q=Z,Y=[...bN(Q.error),...bN(Q.error_description)];if(Y.length>0)return Y.join("; ")}}catch{}return $.slice(0,300)}async function PX($){let Z=await $.text().catch(()=>""),Q=Z?fT4(Z):$.statusText;return new y0({provider:"bitbucket",status:$.status,message:`Bitbucket API ${$.status}: ${Q}`,retryAfterMs:$.status===429?xT4($.headers):null})}async function dA($,Z){let Q=await $.text();try{return JSON.parse(Q)}catch(Y){throw new y0({provider:"bitbucket",status:$.status,message:`Bitbucket ${Z} returned invalid JSON: ${Q.slice(0,300)}`,cause:Y})}}async function TY($,Z,Q={}){let Y={Authorization:Q.basicAuth?`Basic ${Buffer.from(`x-token-auth:${Z}`).toString("base64")}`:`Bearer ${Z}`,Accept:Q.accept??"application/json"},X=Q.body instanceof FormData;if(Q.body!==void 0&&!X)Y["Content-Type"]="application/json";try{return await fetch($,{method:Q.method??"GET",headers:Y,body:Q.body===void 0?void 0:X?Q.body:JSON.stringify(Q.body),signal:AbortSignal.timeout(Q.timeoutMs??bT4)})}catch(J){throw new y0({provider:"bitbucket",status:0,message:`Bitbucket request failed: ${J instanceof Error?J.message:String(J)}`,cause:J})}}function aF$($){if(!$.next)return null;try{let Z=new URL($.next).searchParams.get("page"),Q=Number(Z);return Z!==null&&Number.isInteger(Q)&&Q>0?Q:null}catch{return null}}function cG($){return`"${$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}var bT4=15000,n7;var Be=D(()=>{T6();w5();Oc();n7=wB("bitbucket",fB)});import{z as vZ}from"zod";function V11($){let{owner:Z,name:Q}=h5({path:$});if(!Z||!Q||Z.includes("/"))throw new y0({provider:"bitbucket",status:400,message:`${$} is not a Bitbucket repository path (expected workspace/repo_slug)`});return{workspace:Z,slug:Q}}function ew($){let{workspace:Z,slug:Q}=V11($.path);return`/repositories/${encodeURIComponent(Z)}/${encodeURIComponent(Q)}`}function hT4($,Z){return`${OJ($)}/get/${encodeURIComponent(Z)}.tar.gz`}function eF$($,Z){let Q=uT4.parse($),Y={provider:"bitbucket",host:Z,path:Q.full_name};return{ref:Y,externalId:Q.uuid,defaultBranch:Q.mainbranch?.name??null,webUrl:Q.links?.html?.href??OJ(Y),visibility:Q.is_private?"private":"public",description:Q.description??null,updatedAt:Q.updated_on??null}}async function EW0($,Z,Q){Ne($);let Y=Q?.trim().toLowerCase();if(Y){let G=await I11(`${n7}/workspaces/${encodeURIComponent(Y)}`,Z);if(G.ok)return $U$(G.json);throw G.failure}let X=await I11(`${n7}/user`,Z);if(X.ok){let G=QU$.parse(X.json);return{externalAccountId:G.uuid,login:G.nickname,avatarUrl:G.links?.avatar?.href??null}}let J=await I11(`${n7}/user/workspaces?pagelen=1`,Z);if(J.ok){let G=J.json.values?.[0];if(G?.workspace!==void 0)return $U$(G.workspace)}throw J.ok?new y0({provider:"bitbucket",status:401,message:"Bitbucket did not recognise this token. An access token cannot name itself \u2014 say which workspace it belongs to and connect it again."}):J.failure}function $U$($){let Z=lT4.parse($);return{externalAccountId:Z.uuid,login:Z.slug,avatarUrl:Z.links?.avatar?.href??null}}async function I11($,Z){let Q=await TY($,Z);if(!Q.ok)return{ok:!1,failure:await PX(Q)};return{ok:!0,json:await dA(Q,"principal")}}class Oe{kind="bitbucket";host;tokenSource;workspace;constructor($){Ne($.host),this.host=fB,this.tokenSource=$.tokenSource,this.workspace=$.workspace?.trim().toLowerCase()||null}async tokenForRepo($,Z){return this.accountToken(Z)}async accountToken($){let Z=await this.tokenSource.get($);if(!Z)throw new y0({provider:"bitbucket",status:401,message:"Bitbucket account is not authenticated"});return Z}async getRepo($){let Z=await this.get(ew($));if(!Z)return null;return eF$(await dA(Z,"get_repo"),this.host)}async listRepos($={}){let Z=Math.min(M11,Math.max(1,$.perPage??gT4)),Q=new URLSearchParams({role:"member",sort:"-updated_on",pagelen:String(Z),page:String(Math.max(1,$.page??1))}),Y=$.query?.trim();if(Y)Q.set("q",`name ~ ${cG(Y)}`);let X=await this.workspaceSlugs(),J=await Promise.all(X.map(async(K)=>{let H=await this.get(`/repositories/${encodeURIComponent(K)}?${Q}`);if(!H)return{values:[],next:null};let F=await dA(H,"list_repos");if(!Array.isArray(F.values))throw new y0({provider:"bitbucket",status:502,message:`Bitbucket /repositories/${K} returned no values array`});return F})),G=J.flatMap((K)=>K.values??[]).map((K)=>eF$(K,this.host)).sort((K,H)=>(H.updatedAt??"").localeCompare(K.updatedAt??"")),W=X.length<=1;return{repositories:W?G:G.slice(0,Z),hasMore:J.some((K)=>!!K.next)||!W&&G.length>Z}}async workspaceSlugs(){if(this.workspace)return[this.workspace];let $=await this.get(`/user/workspaces?pagelen=${M11}`);if(!$)return[];return((await dA($,"list_workspaces")).values??[]).flatMap((Q)=>typeof Q.workspace?.slug==="string"?[Q.workspace.slug]:[])}async readFile($,Z,Q){let Y=Q;if(!Y){let J=await this.getRepo($);if(!J?.defaultBranch)return null;Y=J.defaultBranch}let X=await this.get(`${ew($)}/src/${encodeURIComponent(Y)}/${Dc(Z)}`,{accept:"text/plain, */*"});if(!X)return null;return X.text()}async archiveTarball($,Z){let Q=Z;if(!Q){let G=await this.getRepo($);if(!G?.defaultBranch)return null;Q=G.defaultBranch}let Y=hT4($,Q),X={accept:"application/octet-stream, */*",timeoutMs:yT4},J=await this.authedFetch(Y,X);if(J.status===401||J.status===403){await J.body?.cancel().catch(()=>{});let{token:G}=await this.accountToken();J=await TY(Y,G,{...X,basicAuth:!0})}if(J.status===404)return await J.body?.cancel().catch(()=>{}),null;if(!J.ok)throw await PX(J);return J.body}async identity(){let $=await this.authedFetch(`${n7}/user`);if($.status===401||$.status===403)return await $.body?.cancel().catch(()=>{}),null;if(!$.ok)throw await PX($);let Z=QU$.parse(await dA($,"identity"));return{name:Z.display_name||Z.nickname,email:await this.primaryEmail()??`${Z.nickname}@users.noreply.${this.host}`}}async primaryEmail(){let $=await this.authedFetch(`${n7}/user/emails?pagelen=${M11}`);if(!$.ok)return await $.body?.cancel().catch(()=>{}),null;let Q=(await dA($,"user_emails").catch(()=>null))?.values??[],Y=Q.find((X)=>X.is_primary===!0&&X.is_confirmed!==!1)??Q.find((X)=>X.is_confirmed!==!1);return typeof Y?.email==="string"&&Y.email?Y.email:null}async get($,Z){let Q=await this.authedFetch(`${n7}${$}`,Z);if(Q.status===404)return await Q.body?.cancel().catch(()=>{}),null;if(!Q.ok)throw await PX(Q);return Q}async authedFetch($,Z={}){let Q=await this.accountToken(),Y=await TY($,Q.token,Z);if(Y.status!==401)return Y;await Y.body?.cancel().catch(()=>{});let X=await this.accountToken({forceRefresh:!0});return TY($,X.token,Z)}}function Dc($){return $.replace(/^\/+/,"").split("/").map((Z)=>encodeURIComponent(Z)).join("/")}var yT4=60000,gT4=30,M11=100,uT4,ZU$,QU$,lT4;var iA=D(()=>{T6();w5();Oc();Be();uT4=vZ.object({uuid:vZ.string().min(1),full_name:vZ.string().min(1),is_private:vZ.boolean(),description:vZ.string().nullish(),mainbranch:vZ.object({name:vZ.string().nullish()}).nullish(),links:vZ.object({html:vZ.object({href:vZ.string()}).nullish()}).nullish(),updated_on:vZ.string().nullish()});ZU$=vZ.object({avatar:vZ.object({href:vZ.string().nullish()}).nullish()}).nullish(),QU$=vZ.object({uuid:vZ.string().min(1),nickname:vZ.string().min(1),display_name:vZ.string().nullish(),links:ZU$}),lT4=vZ.object({uuid:vZ.string().min(1),slug:vZ.string().min(1),links:ZU$})});function k11($,Z,Q){return{kind:Q,async get(Y){let X=Y?.forceRefresh?await $.get(Z):null,J=await mG({connectionId:Z,tokenStorage:$,bufferMs:Y?.bufferMs,force:Y?.forceRefresh===!0&&X!==null&&$j(X)});if(!J.accessToken)return null;return{token:J.accessToken,kind:Q,expiresAt:null}}}}function zW0($){return $==="token"?"token":"oauth"}function De($){return S11($)===null}function S11($){if($.status!=="active")return"revoked";if($.authKind==="github_cli")return $.type==="github"&&$.host==="github.com"&&mA()?null:"provider_unavailable";if($.type==="github"&&$.authKind==="github_app"){if(sK()===null)return"provider_unavailable";if($.installationId===null)return"installation_missing";if(!$.installationAuthorizedBy)return"authorization_required";if($.installationRepositoryIds?.length===0)return"no_repositories"}return null}function yB($,Z){if(Z.status!=="active")throw new y0({provider:Z.type,status:403,message:"This git account was revoked. Reconnect it before accessing repositories."});if(Z.authKind==="github_app"&&(!Z.installationAuthorizedBy||Z.installationRepositoryIds?.length===0))throw new y0({provider:Z.type,status:403,message:"Reconnect this git account. A GitHub installation must be authorized by its account owner or by someone who administers repositories in it."});let Q=new Xe($.db,$.vault);switch(Z.type){case"github":{if(Z.authKind==="github_cli")return new lA({host:Z.host,tokenSource:nF$(Z)});if(Z.authKind==="github_app"){let Y=sK();if(!Y)throw new y0({provider:"github",status:503,message:"GitHub App credentials are not configured on this deployment"});if(Z.installationId===null)throw new y0({provider:"github",status:403,message:"This GitHub account has no installation linked. Reconnect it to select repositories."});return new lA({host:Z.host,installationId:Z.installationId,repositoryIds:Z.installationRepositoryIds,appAuth:Y})}return new lA({host:Z.host,tokenSource:k11(Q,Z.id,zW0(Z.authKind))})}case"gitlab":return new Ue({host:Z.host,tokenSource:k11(Q,Z.id,zW0(Z.authKind))});case"bitbucket":return new Oe({workspace:Z.authKind==="token"?Z.login:null,host:Z.host,tokenSource:k11(Q,Z.id,zW0(Z.authKind))})}}function YU$($){if($.authKind==="github_app")return"installation";if($.authKind==="github_cli")return"token";return zW0($.authKind)}function Le($,Z,Q="installation"){return{ref:$,tokenSource:{kind:Q,get:()=>Promise.resolve({token:Z,kind:Q,expiresAt:null})}}}async function PW0($,Z){let Q=bB(Z);if(!Z.accountId)throw new y0({provider:Z.provider,status:401,message:`${Z.path} is linked without an account; link it again to read and write it`});let Y=await XU$($,Z,Z.accountId),X=yB($,Y),J=YU$(Y);return{ref:Q,tokenSource:{kind:J,get:(G)=>X.tokenForRepo(Q,G)}}}async function aF($,Z,Q){let Y=bB(Z);if(!Z.accountId)return cT4(Y);let X=await XU$($,Z,Z.accountId),J=yB($,X),W=YU$(X)==="installation"?await RF$((F,U)=>J.readFile({...Y,path:F},U),Y):[],K=await J.tokenForRepo(Y,{...Q,alsoRepositories:W}),H=K.kind==="installation"?null:await J.identity().catch(()=>null);return{cloneUrl:we0(Y,K.token),gitUserName:H?.name??rF.name,gitUserEmail:H?.email??rF.email}}function cT4($){return{cloneUrl:we0($),gitUserName:rF.name,gitUserEmail:rF.email}}async function XU$($,Z,Q){let Y=await new gA($.db).getUnscoped(Q);if(!Y||Y.organizationId!==Z.organizationId)throw new y0({provider:Z.provider,status:404,message:`The account backing ${Z.path} no longer exists. Link the repository again.`});return Y}async function AW0($,Z,Q){let Y=Q.repositoryId?await $.repositories.get(Q.repositoryId,Z):Q.ref?await $.repositories.findByRef(Z,Q.ref):null,X=Y?bB(Y):Q.ref??null;if(!X)return null;return{ref:X,repository:Y,servable:Y?await gB($,Y):!1}}async function gB($,Z){if(!Z.accountId)return!1;let Q=await $.gitProviderAccounts.getUnscoped(Z.accountId);return Q!==null&&De(Q)}var TW0=D(()=>{T6();WW();B11();HW0();Fc();qF$();OW0();FW0();LW0();aw();iA();w5()});async function mT4($,Z){let Q=$.organization?.id;if(!Q)throw Error(j7);if(!Z.sourceConnectionId)throw Error(j7);let Y=await $.storage.connections.findById(Z.sourceConnectionId,Q);if(!Y)throw Error(j7);let{clientFromConnection:X}=await Promise.resolve().then(() => (wa(),KU$)),J=await X(Y,$,!0);try{let{result:G}=await XH$((H)=>J.callTool({name:"MINT_REPO_TOKEN",arguments:{installationId:Z.installationId,owner:Z.owner,repo:Z.repo,permissions:H}}),YH$(Z.permissions)),W=G.structuredContent?.token;if(G.isError||!W)throw Error(j7);let K=G.structuredContent?.expiresAt;return{accessToken:W,expiresAt:K?new Date(K):null}}finally{await J.close().catch(()=>{})}}function dT4($,Z){return($?.getTime()??0)>Z?$:new Date(Z+WU$)}async function iT4($,Z,Q,Y){let X=Date.now(),J=await mT4($,Q),G=dT4(J.expiresAt,X);try{await Y.upsert({connectionId:Z,accessToken:J.accessToken,refreshToken:null,scope:null,expiresAt:G,clientId:null,clientSecret:null,tokenEndpoint:null})}catch(W){console.warn("[GithubMint] failed to persist minted token",{connectionId:Z,message:W instanceof Error?W.message:String(W)})}return J.accessToken}async function we($,Z,Q){let Y=u9(Z);if(!Y)throw Error("Connection is not repo-scoped");if(!Y.sourceConnectionId)throw Error(j7);let X=new F9($.db,$.vault),J=await X.get(Z.id);if(!Q?.forceRefresh&&J&&!X.isExpired(J,Ee))return J.accessToken;let G=C11.get(Z.id);if(G)return G;let W=iT4($,Z.id,Y,X).finally(()=>{C11.delete(Z.id)});return C11.set(Z.id,W),W}function JU$($){return $.slug==="mcp-github"}async function GU$($,Z,Q){if(u9(Z)?.sourceConnectionId)return we($,Z,Q);return(await mG({connectionId:Z.id,connectionUrl:Z.connection_url,tokenStorage:new F9($.db,$.vault),force:Q?.forceRefresh})).accessToken}var C11;var je=D(()=>{WW();wJ();iK();C11=new Map});function pT4(){return process.env.GITHUB_GRAPHQL_URL??"https://api.github.com/graphql"}function tT4($){return $>=500&&$<600}function oT4($){return $ instanceof i5?$.cause:$}function rT4($,Z){try{return JSON.parse($)}catch(Q){throw Error(`GitHub GraphQL ${Z} returned invalid JSON: ${$.slice(0,300)}`,{cause:Q})}}function sT4($,Z){let Q=$.errors?.[0]?.message;if(Q)throw Error(`GitHub GraphQL ${Z} failed: ${Q}`);if($.data==null)throw Error(`GitHub GraphQL ${Z} returned no data`);return $.data}async function Lc($){let Z=await $.getToken();if(!Z)throw Error($.missingTokenMessage);let Q=(W)=>fetch(pT4(),{method:"POST",headers:{Authorization:`Bearer ${W}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({query:$.query,variables:$.variables}),signal:AbortSignal.timeout(nT4)}),Y=async(W)=>{try{return await g8(async()=>{let K=await Q(W);if(tT4(K.status)){let H=K.status;throw await K.body?.cancel().catch(()=>{}),Error(`GitHub GraphQL transient error: ${H}`)}return K},{maxAttempts:3,minTimeout:300,maxTimeout:3000,jitter:1})}catch(K){throw oT4(K)}},X=await Y(Z),J=Z;if(X.status===401){try{await X.body?.cancel()}catch{}let W=await $.getToken(!0);if(!W)throw Error($.missingTokenMessage);if(X=await Y(W),J=W,X.status===401)throw Error($.missingTokenMessage)}let G=Uc(J);if(tw(X.headers,{lane:"graphql",operation:$.operation,installation:G}),pw(X)){let W=X.headers.get("retry-after")!==null?"secondary":"primary";ow({lane:"graphql",operation:$.operation,installation:G,kind:W});let K=nw(X.headers);throw await X.body?.cancel().catch(()=>{}),new y0({provider:"github",status:X.status,retryAfterMs:K,message:`GitHub ${W} rate limit reached${K===null?"":`; retry in ${Math.ceil(K/1000)}s`}`})}if(!X.ok)throw await X.body?.cancel().catch(()=>{}),new y0({provider:"github",status:X.status,message:`GitHub GraphQL ${$.label} failed: ${X.status}`});return sT4(rT4(await X.text(),$.label),$.label)}var nT4=15000;var RW0=D(()=>{D8();w5();Ge();Nc()});function $R4($){if(!$)return null;if($.state!=="open")return!1;if(typeof $.mergeable==="boolean")return!$.mergeable;let Z=$.mergeable_state;if(typeof Z!=="string"||Z===""||Z==="unknown")return null;return Z==="dirty"}function ZR4($){if($==="clean")return"passing";if($==="unstable")return"failing";return null}function _11($){let Z=$.merged===!0||typeof $.merged_at==="string";return{number:$.number??0,url:$.html_url??"",title:$.title??"",body:$.body??"",state:Z?"merged":$.state==="closed"?"closed":"open",draft:$.draft===!0,mergedAt:$.merged_at??null,updatedAt:$.updated_at??null,base:$.base?.ref??"main",head:$.head?.ref??"",headSha:$.head?.sha??"",headRepoPath:$.head?.repo?.full_name??null,author:$.user?.login??"",conflicting:$R4($),checks:ZR4($.mergeable_state),changedFiles:typeof $.changed_files==="number"?$.changed_files:null}}function QR4($){if($==="IN_PROGRESS")return"running";if($==="COMPLETED")return"completed";return"queued"}function YR4($){switch($){case"SUCCESS":return"success";case"FAILURE":case"STARTUP_FAILURE":return"failure";case"NEUTRAL":case"STALE":return"neutral";case"CANCELLED":return"cancelled";case"SKIPPED":return"skipped";case"TIMED_OUT":return"timed_out";case"ACTION_REQUIRED":return"action_required";default:return null}}function WR4($){let Z=$.state;return{id:null,name:$.context??"",state:Z==="PENDING"||Z==="EXPECTED"?"running":"completed",conclusion:Z==="SUCCESS"?"success":Z==="FAILURE"||Z==="ERROR"?"failure":Z==="PENDING"||Z==="EXPECTED"?null:"neutral",url:$.targetUrl??null,durationMs:null,summary:$.description??null}}function KR4($){let Z=$.commits?.nodes?.[0]?.commit?.statusCheckRollup?.contexts?.nodes??[],Q=[];for(let Y of Z){if(!Y)continue;if(Y.__typename==="StatusContext"){Q.push(WR4(Y));continue}if(Y.__typename!=="CheckRun")continue;let{startedAt:X,completedAt:J}=Y;Q.push({id:Y.databaseId==null?null:String(Y.databaseId),name:Y.name??"",state:QR4(Y.status),conclusion:YR4(Y.conclusion),url:Y.detailsUrl??null,durationMs:X&&J?new Date(J).getTime()-new Date(X).getTime():null,summary:Y.summary??null})}return Q}function HR4($,Z){let Q=($.reviewThreads?.nodes??[]).filter((K)=>K?.isResolved===!1).length,Y=$.reviewDecision,X=Y==="REVIEW_REQUIRED"||Y==="CHANGES_REQUESTED",J=KR4($),G=$.number??0,W=$.merged===!0;return{number:G,url:$.url??YW(Z,G),title:$.title??"",body:$.body??"",state:W?"merged":$.state==="OPEN"?"open":"closed",draft:$.isDraft===!0,mergedAt:$.mergedAt??null,updatedAt:$.updatedAt??null,base:$.baseRefName??"main",head:$.headRefName??"",headSha:$.headRefOid??"",headRepoPath:$.headRepository?.nameWithOwner??null,author:$.author?.login??"",conflicting:$.state!=="OPEN"?!1:$.mergeable==="CONFLICTING"?!0:$.mergeable==="MERGEABLE"?!1:null,checks:Gc(J),changedFiles:$.changedFiles??null,checkRuns:J,comments:($.comments?.nodes??[]).flatMap((K)=>K?[{id:String(K.databaseId??0),author:K.author?.login??"",body:K.body??"",createdAt:K.createdAt??"",updatedAt:K.updatedAt??K.createdAt??"",url:K.url??""}]:[]),unresolvedConversations:Q,reviewBlocked:X}}function FR4($){let Z=null,Q=-1/0;for(let Y of $??[]){if(!Y?.mergedAt)continue;let X=Date.parse(Y.mergedAt);if(Number.isNaN(X)||X<=Q)continue;Z=Y,Q=X}return Z}function HU$($){return/not allowed on this repository/i.test($)}class v11{repo;tokenSource;apiBaseUrl;owner;name;constructor($){this.repo=$.repo,this.tokenSource=$.tokenSource,this.apiBaseUrl=NW($.repo.host);let{owner:Z,name:Q}=h5($.repo);this.owner=Z,this.name=Q}async token($){return(await this.tokenSource.get($?{forceRefresh:!0}:void 0))?.token??null}async requireToken(){let $=await this.token();if($)return $;throw new y0({provider:"github",status:401,message:`No usable GitHub token for ${this.repo.path}; reconnect the account`})}get base(){return`${this.apiBaseUrl}/repos/${this.owner}/${this.name}`}async rest($,Z){let Q=await CZ(`${this.base}${$}`,{method:Z.method,body:Z.body,token:await this.requireToken(),operation:Z.operation});if(Q.status===404)return await Q.body?.cancel().catch(()=>{}),null;if(!Q.ok)throw await _Z(Q,Z.operation);if(Q.status===204)return null;return kQ(Q,Z.operation)}graphql($){return Lc({getToken:(Z)=>this.token(Z),missingTokenMessage:`No usable GitHub token for ${this.repo.path}; reconnect the account`,...$})}async read($){let Z=await this.rest(`/pulls/${$}`,{operation:"change_request_read"});return Z?_11(Z):null}async readForBranch($){return await this.readDetailed({branch:$})}async readDetailed($){let Z="number"in $,Y=(await this.graphql({query:Z?JR4:XR4,variables:Z?{owner:this.owner,repo:this.name,number:$.number}:{owner:this.owner,repo:this.name,branch:$.branch},label:`change request for ${this.repo.path}`,operation:"change_request_detail"})).repository;if(!Y)throw new y0({provider:"github",status:404,message:`${this.repo.path} is not accessible with this credential`});let X=Z?Y.pullRequest:Y.pullRequests?.nodes?.[0];return X?HR4(X,this.repo):null}async listOpen($){return(await this.rest(`/pulls?state=open&sort=updated&direction=desc&per_page=${Math.min($,100)}`,{operation:"change_request_list"})??[]).map(_11)}async lastMergedInto($){let Z=await this.graphql({query:GR4,variables:{owner:this.owner,repo:this.name,base:$},label:`last merged into ${$} on ${this.repo.path}`,operation:"change_request_last_merged"});if(!Z.repository)throw new y0({provider:"github",status:404,message:`${this.repo.path} is not accessible with this credential`});let Q=FR4(Z.repository.pullRequests?.nodes);if(!Q)return null;let Y=Q.number??0;return{number:Y,url:Q.url??YW(this.repo,Y),title:Q.title??"",body:Q.body??"",state:"merged",draft:!1,mergedAt:Q.mergedAt??null,updatedAt:Q.mergedAt??null,base:Q.baseRefName??$,head:Q.headRefName??"",headSha:Q.headRefOid??"",headRepoPath:null,author:Q.author?.login??"",conflicting:!1,checks:null,changedFiles:null}}async open($){let Z=await CZ(`${this.base}/pulls`,{method:"POST",token:await this.requireToken(),operation:"change_request_open",body:{title:$.title,body:$.body||void 0,head:$.head,base:$.base}});if(Z.ok)return _11(await kQ(Z,"change_request_open"));let Q=await _Z(Z,"change_request_open");if(/already exists|pull request already/i.test(Q.message))throw new yA(Q.message,await this.readForBranch($.head).catch(()=>null));throw Q}async describe($,Z){await this.rest(`/pulls/${$}`,{method:"PATCH",body:{body:Z},operation:"change_request_describe"})}async merge($,Z={}){let Q=aT4[Z.strategy??"any"],Y="";for(let X of Q){let J=await this.attemptMerge($,X,Z);if(J.merged)return J;if(J.reason==="blocked"&&HU$(J.detail)){Y=J.detail;continue}return J}return{merged:!1,reason:"blocked",detail:Y}}async attemptMerge($,Z,Q){let Y;try{Y=await CZ(`${this.base}/pulls/${$}/merge`,{method:"PUT",token:await this.requireToken(),operation:"change_request_merge",body:{merge_method:Z,...Q.commitTitle?{commit_title:Q.commitTitle}:{},...Q.commitMessage?{commit_message:Q.commitMessage}:{}}})}catch(G){return{merged:!1,...UR4(G)}}if(Y.ok)return await Y.body?.cancel().catch(()=>{}),{merged:!0};let X=await _Z(Y,"change_request_merge");if(Y.status===404)return{merged:!1,reason:"not_found",detail:X.message};if(HU$(X.message))return{merged:!1,reason:"blocked",detail:X.message};return{merged:!1,reason:await this.read($).then((G)=>G?.conflicting??null).catch(()=>null)===!0?"conflict":"blocked",detail:X.message}}async readCheckLog($){let Z=await this.rest(`/check-runs/${encodeURIComponent($)}`,{operation:"change_request_check_log"});return Z?.output?.summary??Z?.output?.text??null}async readDeployedUrl($){let Z=await this.rest(`/deployments?sha=${encodeURIComponent($)}&per_page=${eT4}`,{operation:"change_request_deployments"});for(let Q of Z??[]){if(typeof Q.id!=="number")continue;let X=(await this.rest(`/deployments/${Q.id}/statuses?per_page=10`,{operation:"change_request_deployment_statuses"})??[]).find((J)=>J.state==="success"&&typeof J.environment_url==="string"&&J.environment_url.length>0);if(X?.environment_url)return X.environment_url}return null}}function UR4($){let Z=$ instanceof Error?$.message:String($);if($ instanceof y0&&$.isRateLimited)return{reason:"rate_limited",detail:Z};return{reason:"error",detail:Z}}var aT4,eT4=3,FU$=`
|
|
1017
1017
|
fragment CrDetail on PullRequest {
|
|
1018
1018
|
number
|
|
@@ -1598,7 +1598,7 @@ Studio renders those as real images in the comment.`,`- End the run by calling \
|
|
|
1598
1598
|
`+"If you cannot exercise the change at all \u2014 every path you tried failed \u2014 "+`do NOT approve: request changes stating which paths you tried, what is blocking and what is needed to unblock. An unexercised change is not a pass.
|
|
1599
1599
|
`+"4. RECORD the whole pass as a task comment BEFORE the decision \u2014 a "+"durable record, separate from the short decision summary, and REQUIRED: a verdict with no comment is an incomplete run and you will be asked for one. Structure it: what you read and the concrete issues with file/line references, WHICH of them you fixed (with the commits), the acceptance criteria / scenarios you exercised with a pass/fail on each, a "+"before\u2192after pointer to the screenshots, the exact URL(s) and viewport, "+`and anything you did not review or could not verify and why.
|
|
1600
1600
|
That comment must ALWAYS carry the visual change: embed the before/after screenshots in it whenever the change has any visual surface. If it has none, write the exact words \`${aa}\` in the comment and `+"name why (backend-only, config, test-only) \u2014 that literal is what a "+"machine check looks for, so no paraphrase of it counts, and silence about screenshots is not an acceptable answer either way.\n5. DECIDE. Approve once the pull request is in the state you would approve. Only `request_changes` for something you genuinely cannot settle here (a product decision, a missing credential, an approach that needs "+"rethinking) \u2014 that hands the card to a human, it does not start another "+"agent round. NEVER end your run without having called `TASK_BOARD_REVIEW_DECISION`: a run that stops to wait on a background task, or that runs low on room, must decide on what it knows first. An unrecorded verdict strands the card and is the one failure this run cannot leave behind."}});function zt4($,Z){return $.status===T$.review&&$.assigneeId===j8&&Z===!0}function R91($){return $.filter((Q)=>Q.action==="merge_conflict_resolution").length>=LV$}async function _j($,Z,Q,Y){if(!zt4(Q,Y.conflict))return!1;let J=(await $.storage.organizationSettings.get(Z))?.flags??{};if(!RH$(J))return!1;let G=kB(J),W=await $.storage.taskBoard.listActivity(Q.id,Z);if(!fw(W,G,{cycleStartedAt:Q.reviewCycleStartedAt,verifiedOnly:!0}))return!1;if(R91(W))return console.warn(`[task-board] conflict auto-resolve cap (${LV$}) reached on task ${Q.id} \u2014 leaving the PR for a human`),!1;let K=Y.pr,H=await $.storage.taskBoard.claimConflictResolution(Q.id,Z,Q.updatedBy);if(!H)return!1;E8(Z,H);try{await HH($,H,{pr:{number:K.number,url:K.url},resolveConflict:!0})}catch(F){throw await wV$($,H,F).catch(()=>!1),await $.storage.taskBoard.update(H.id,Z,{status:T$.review},"system").then((U)=>E8(Z,U)).catch((U)=>console.error("[task-board] conflict-resolution status revert failed",U)),F}return await o6($,{taskBoardItemId:Q.id,action:"merge_conflict_resolution",actorId:null,data:{prNumber:K.number}}),!0}var LV$=3;var zm=D(()=>{C4();IZ();_Y();V9();wU()});import{DBOS as I91}from"@dbos-inc/dbos-sdk";function EV$($){q91=$}async function Rt4($,Z){if(!q91)throw Error("[task-board-github-read] runtime not initialized \u2014 setTaskBoardGithubReadRuntime() must run before the workflow fires");let Q=await PW(q91.db,$);if(!Q)return M91;return await PV$(Q,$,Z)}async function qt4($,Z){return await I91.runStep(()=>Rt4($,Z),{name:"readPrState"})}function zV$(){if(DT0)return;DT0=I91.registerWorkflow(qt4,{name:"taskBoardGithubReadWorkflow"})}async function Pm($,Z){if(!DT0)return M91;try{return await(await I91.startWorkflow(DT0,{queueName:ME,timeoutMS:Tt4})($,Z)).getResult()}catch(Q){return console.error("[task-board-github-read] throttled PR read failed",Q),M91}}var Pt4=20,At4=4,Tt4=60000,jV$,q91=null,M91,DT0=null;var Q10=D(()=>{ox();z7();jV$={concurrency:At4,rateLimit:{limitPerPeriod:Pt4,periodSec:60}};M91={state:null,merged:null,checksStatus:null,conflict:null}});import{createHash as Mt4}from"crypto";class ax{config;options;now;kv=null;codec=zw();revalidating=new Set;fallback;placeholderFallback=new Map;static MAX_PLACEHOLDER_FALLBACK_ENTRIES=1000;constructor($,Z,Q=()=>Date.now()){this.config=$;this.options=Z;this.now=Q;let Y={revalidateAfterMs:$.revalidateAfterMs,maxStaleMs:$.maxStaleMs,maxValueBytes:AV$};this.fallback=new u30({"tools/call":Y,"resources/read":Y,"prompts/get":Y})}async init($){if($){this.kv=$;return}let Z=this.options.getJetStream();if(!Z)return;this.kv=await new RV$.Kvm(Z).create(this.config.bucket,{storage:TV$.StorageType.Memory,ttl:this.config.maxStaleMs,maxValueSize:AV$})}storageKey($,Z){let Q=Mt4("sha256").update(Z).digest("hex").slice(0,32);return`${$}.${Q}`}async fetch($){let{namespace:Z,key:Q,fetchLive:Y,onRevalidation:X}=$,{cache:J,maxStaleMs:G,revalidateAfterMs:W}=this.config;if(!this.kv)return this.fallback.fetch({type:"tools/call",connectionId:Z,scope:{kind:"org"},params:{key:Q},fetchLive:Y,onRevalidation:X});let K=this.storageKey(Z,Q),H=$.fresh?null:await this.read(K),F=H?this.now()-H.storedAt:Number.POSITIVE_INFINITY;if(!H||F>G){JO.add(1,{cache:J,outcome:"miss"});let U=await Y();return await this.write(K,U,J),U}if(F>W&&!this.revalidating.has(K))JO.add(1,{cache:J,outcome:"stale"}),this.revalidating.add(K),X(Y().then((U)=>this.write(K,U,J)).catch(()=>{JO.add(1,{cache:J,outcome:"error"})}).finally(()=>this.revalidating.delete(K)));else JO.add(1,{cache:J,outcome:"hit"});return H.value}async fetchOrPlaceholder($){let{namespace:Z,key:Q,fetchLive:Y,placeholder:X}=$,{cache:J,maxStaleMs:G}=this.config,W=this.storageKey(Z,Q),K=await this.read(W),H=K?this.now()-K.storedAt:Number.POSITIVE_INFINITY,F=K!=null&&H<=G,U=K&&$.revalidateAfterMs?$.revalidateAfterMs(K.value):this.config.revalidateAfterMs;if(F&&H<=U)return JO.add(1,{cache:J,outcome:"hit"}),{value:K.value,live:!0};if(JO.add(1,{cache:J,outcome:F?"stale":"placeholder"}),!this.revalidating.has(W))this.revalidating.add(W),Y().then((N)=>this.write(W,N,J)).catch(()=>{JO.add(1,{cache:J,outcome:"error"})}).finally(()=>this.revalidating.delete(W));return F?{value:K.value,live:!0}:{value:X,live:!1}}async refresh($){let Z=await $.fetchLive();return await this.write(this.storageKey($.namespace,$.key),Z,this.config.cache),JO.add(1,{cache:this.config.cache,outcome:"refresh"}),Z}async read($){if(!this.kv)return this.placeholderFallback.get($)??null;try{let Z=await this.kv?.get($);if(!Z?.value?.length)return null;if(Z.operation==="DEL"||Z.operation==="PURGE")return null;return this.codec.decode(Z.value)}catch{return null}}async write($,Z,Q){if(!this.kv){if(this.placeholderFallback.size>=ax.MAX_PLACEHOLDER_FALLBACK_ENTRIES){let Y=this.placeholderFallback.keys().next().value;if(Y!==void 0)this.placeholderFallback.delete(Y)}this.placeholderFallback.set($,{storedAt:this.now(),value:Z});return}try{await this.kv?.put($,this.codec.encode({storedAt:this.now(),value:Z}))}catch{JO.add(1,{cache:Q,outcome:"store_rejected"})}}async invalidate($){if(this.fallback.invalidate($),!this.kv)return;try{let Z=await this.kv.keys(`${$}.*`);for await(let Q of Z)await this.kv.delete(Q).catch(()=>{})}catch{}}teardown(){this.kv=null}}function k91($){qV$=$?.reads??null,MV$=$?.cards??null}function S91(){return qV$??It4}function LT0(){return MV$??Vt4}var TV$,RV$,JO,AV$=524288,V91,Y10,qV$=null,MV$=null,It4,Vt4;var C91=D(()=>{ya();C6();TV$=C(GN(),1),RV$=C(za(),1),JO=z$.createCounter("pr_read_cache.fetches",{description:"Task board PR cache outcomes (hit, stale, miss, placeholder, refresh, error, store_rejected)",unit:"{fetches}"}),V91={bucket:"DECOCMS_PR_READS",revalidateAfterMs:55000,maxStaleMs:1800000,cache:"reads"},Y10={bucket:"DECOCMS_PR_CARDS",revalidateAfterMs:30000,maxStaleMs:86400000,cache:"cards"};It4=new ax(V91,{getJetStream:()=>null}),Vt4=new ax(Y10,{getJetStream:()=>null})});import{z as wT0}from"zod";function kt4($){if($ instanceof y0&&$.isRateLimited)return!0;let Q=($ instanceof Error?$.message:String($)).replace(/https?:\/\/\S+/gi," ");return/too many requests|rate limit|\b429\b/i.test(Q)}function IV$($){return S91().invalidate($)}function aG($){return LT0().invalidate($)}async function X10($,Z,Q,Y,X=!1){try{return await S91().fetch({namespace:$,key:Z,fresh:X,fetchLive:()=>g8(Y,{maxAttempts:3,minTimeout:300,maxTimeout:3000,jitter:1,isRetriable:(G)=>!kt4(G)}),onRevalidation:()=>{}})??null}catch(J){let G=J instanceof i5?J.cause:J;return console.error(`[task-board] ${Z} failed for ${Q}:`,G),null}}function _91($,Z,Q){return Ec($,Z,a00(Q)).catch((Y)=>{return console.error(`[task-board] no client for ${Am(Q)}:`,Y),null})}function ex($){let Z;try{Z=new URL($).hostname.toLowerCase()}catch{return!1}return Z==="deco.site"||Z.endsWith(".decocdn.com")||Z.endsWith(".deco-cx.workers.dev")||Z.endsWith(".deco.site")||Z.endsWith(".vercel.app")||Z.endsWith(".vtex.app")}function _t4($){for(let Q of $){let Y=/^Workers Builds:\s*([a-z0-9][a-z0-9-]*)\s*$/i.exec(Q.name)?.[1],X=Q.summary?/Version ID:\s*([0-9a-f]{8})/i.exec(Q.summary)?.[1]:null;if(!Y||!X)continue;let J=`https://${X}-${Y}.${Ct4}.workers.dev`;if(ex(J))return J}let Z=(Q)=>Q.conclusion==="success";for(let Q of[...$.filter(Z),...$.filter((Y)=>!Z(Y))]){let Y=(Q.url&&ex(Q.url)?Q.url:null)??VV$(Q.summary);if(Y)return Y}return null}function VV$($){if(typeof $!=="string")return null;return($.match(/https?:\/\/[^\s"'<>)\]]+/g)??[]).find(ex)??null}function vt4($){let Z=(Y)=>Date.parse(Y.updatedAt??"")||Date.parse(Y.createdAt??""),Q=$.map((Y,X)=>({c:Y,index:X})).sort((Y,X)=>{let J=Z(Y.c),G=Z(X.c);if(Number.isNaN(J)||Number.isNaN(G))return Y.index-X.index;return G-J}).map(({c:Y})=>Y);for(let Y of Q){let X=Y.body;if(!X)continue;let J=X.match(/href=['"]([^'"]+)['"][^>]*>\s*Branch Preview/i);if(J?.[1]&&ex(J[1]))return J[1];let G=VV$(X);if(G)return G}return null}function bt4($){return typeof $==="string"&&/^[0-9a-fA-F]{7,40}$/.test($)?$:null}function v91($){if($==="merged")return{state:"closed",merged:!0};return{state:$,merged:!1}}async function xt4($,Z,Q,Y){let X=(J)=>J.state==="completed"&&J.conclusion!==null&&J.conclusion!=="success"&&J.conclusion!=="skipped"&&J.conclusion!=="neutral";return await Promise.all(Y.map(async(J)=>({name:J.name,status:J.state,conclusion:J.conclusion,detailsUrl:J.url,summary:J.summary??(X(J)&&J.id!==null?await X10(Z,`check-log:${J.id}`,`${Am(Q)} check ${J.id}`,()=>$.readCheckLog(J.id)):null)})))}async function ft4($,Z,Q,Y=!1){let X=await _91($,Z,Q);if(!X)return jT0;let J=J10(Q),G=await X10(J,`detail:${Q.number}`,Am(Q),()=>X.readDetailed({number:Q.number}),Y);if(!G)return jT0;let{state:W,merged:K}=v91(G.state);if(W!=="open")return{...jT0,title:G.title,body:G.body,updatedAt:G.updatedAt,state:W,draft:G.draft,merged:K};let F=_t4(G.checkRuns)??vt4(G.comments);if(!F){let U=bt4(G.headSha),N=U?await X10(J,`deployed:${U}`,`${Am(Q)} (deployment preview)`,()=>X.readDeployedUrl(U)):null;F=N&&ex(N)?N:null}return{title:G.title,body:G.body,updatedAt:G.updatedAt,state:W,draft:G.draft,merged:K,mergeable:G.conflicting===null?null:!G.conflicting,checksStatus:G.checks,checks:await xt4(X,J,Q,G.checkRuns),previewUrl:F}}async function ET0($,Z,Q,Y){let X=await _91($,Z,Q);if(!X)return null;return X10(J10(Q),`read:${Q.number}`,`${Am(Q)} (${Y})`,()=>X.read(Q.number))}async function kV$($,Z,Q){let Y=await _91($,Z,Q);if(!Y)return null;return(await X10(J10(Q),`detail:${Q.number}`,Am(Q),()=>Y.readDetailed({number:Q.number})))?.checks??null}async function zT0($,Z,Q){return(await ET0($,Z,Q,"conflict"))?.conflicting??null}async function GT0($,Z,Q){let Y=await ET0($,Z,Q,"landing");if(!Y)return{state:null,merged:null};return v91(Y.state)}async function PV$($,Z,Q){let Y=await ET0($,Z,Q,"candidate");if(!Y)return{state:null,merged:null,checksStatus:null,conflict:null};return{...v91(Y.state),checksStatus:Y.checks,conflict:Y.conflicting}}async function SV$($,Z,Q){let Y=await ET0($,Z,Q,"head ref");if(!Y||Y.state!=="open")return null;return Y.head.length>0?Y.head:null}function x91($){return CV$($).every((Z)=>Z.checksStatus!=="failing"&&Z.checksStatus!=="pending")}function yt4($){let Z=$.findIndex((Q)=>Q!=="closed");return Z===-1?0:Z}async function $f($,Z,Q){if(Q.length<=1)return Q[0];let Y=[];for(let X of Q){let{state:J}=await Pm(Z,X);if(Y.push(J),J!=="closed")break}return Q[yt4(Y)]}function _V$($,Z,Q,Y=!1){return Promise.all(Q.map(async(X)=>{let J=await ft4($,Z,X,Y);return{url:X.url,number:X.number,repoOwner:X.repoOwner,repoName:X.repoName,createdAt:X.createdAt,...J}}))}async function vV$($,Z,Q){try{let Y=await $.storage.taskBoard.listPrs(Q,Z);if(Y.length===0)return null;let X=await LT0().refresh({namespace:Z,key:Q,fetchLive:()=>_V$($,Z,Y,!0)});return bV$(Z,Q,X),X}catch(Y){return console.error(`[task-board] pr card refresh failed for ${Q}:`,Y),null}}var Am=($)=>`${$.repoOwner}/${$.repoName}#${$.number}`,J10=($)=>cK(a00($).repo),St4=0,Ct4="deco-cx",jT0,b91=($)=>CV$($).length>0,CV$=($)=>$.filter((Z)=>Z.state!=="closed"&&Z.merged!==!0),gt4,G10;var z7=D(()=>{C0();iZ();C4();T6();D8();IJ();jm();_Y();tx();WH();V9();OT0();zm();Q10();C91();YT0();jT0={title:null,body:null,updatedAt:null,state:null,draft:null,merged:null,mergeable:null,checksStatus:null,checks:[],previewUrl:null};gt4=d({name:"TASK_BOARD_ITEM_PRS_GET",description:"Get the change requests (GitHub and Bitbucket pull requests, GitLab merge requests) linked to a task board item, each enriched with live state (title, open/closed, draft, merged) fetched from its provider.",annotations:{title:"Get Task Board Item Pull Requests",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:wT0.object({taskBoardItemId:wT0.string()}),outputSchema:wT0.object({prs:wT0.array(mE$)}),handler:async({taskBoardItemId:$},Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.taskBoard.getById($,Q),X=await Z.storage.taskBoard.listPrs($,Q),J=()=>_V$(Z,Q,X),{value:G,live:W}=await LT0().fetchOrPlaceholder({namespace:Q,key:$,fetchLive:J,revalidateAfterMs:(F)=>F.some((U)=>NF$(U))?St4:Y10.revalidateAfterMs,placeholder:X.map((F)=>({url:F.url,number:F.number,repoOwner:F.repoOwner,repoName:F.repoName,createdAt:F.createdAt,...jT0}))});if(!W)return{prs:G};let K=T$.review,H=G.find((F)=>F.state==="open"&&!F.merged);if(Y&&VX(Y)&&Y.assigneeId===j8&&b91(G))await Em(Z,Y,{previewMatchesHead:x91(G)}).catch((F)=>{console.error("[task-board] reviewer auto-handoff failed",F)});if(Y&&Y.status===K&&Y.assigneeId===j8&&H&&H.mergeable===!1)await _j(Z,Q,Y,{pr:{number:H.number,url:H.url},conflict:!0}).catch((F)=>{console.error("[task-board] conflict auto-resolve failed",F)});if(rx(G))try{let F=await Z.storage.organizationSettings.get(Q),U=oF(F?.flags);if(Y&&HV$(Y.status,U)&&!await Z.storage.taskBoard.hasHumanRejectedDone($,Q)){let N=await Z.storage.taskBoard.update($,Q,{status:U},Y.updatedBy);await o6(Z,{taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:Y.status,to:U}}),E8(Q,N)}}catch(F){console.error("[task-board] merged-PR reconcile failed",F)}return{prs:G}}}),G10=wm(gt4)});function fV$($){if(xV$.has($.kind??""))return 0;return mt4($)?lt4:ct4}function mt4($){let Z=$.kind??"";if(xV$.has(Z))return!1;if(ht4.has(Z))return!0;let Q=$.errorText??"";if(!Q)return!1;if(Q.includes(vA0))return!0;let Y=Q.replace(/https?:\/\/\S+/gi," ");return ut4.some((X)=>X.test(Y))}var ht4,xV$,ut4,lt4=3,ct4=1;var yV$=D(()=>{y20();ht4=new Set(["stall","liveness","projection","abandoned"]),xV$=new Set(["cancelled",...d00]),ut4=[/sandbox did not become ready/i,/sandbox (?:provisioning|claim) failed/i,/mcp is unusable/i,/harness_crashed: unexpected eof/i,/too many clients already|timeout exceeded when trying to connect/i,/\b(?:429|503)\b|too many requests|service unavailable/i]});function PT0($,Z,Q,Y){QJ({event:$,organizationId:Z,properties:{task_id:Q.id,reports_task:PY(Q),...Y}})}function E8($,Z){e5.emit($,{id:crypto.randomUUID(),type:KF$,source:"task-board",subject:Z.id,data:Z,time:new Date().toISOString()})}function bV$($,Z,Q){e5.emit($,{id:crypto.randomUUID(),type:FF$,source:"task-board",subject:Z,data:{id:Z,prs:Q},time:new Date().toISOString()})}function gV$($,Z){e5.emit($,{id:crypto.randomUUID(),type:HF$,source:"task-board",subject:Z,data:{id:Z},time:new Date().toISOString()})}function dt4($,Z){return $?[$]:Z}async function f91($,Z,Q){let Y=$.metadata?.runMetadata?.taskBoardItemId,X=!Y&&Q?await $.storage.taskBoard.linkedTaskIds(Q,Z):[];return dt4(Y,X)}async function y91($,Z,Q){return $.storage.taskBoard.boardManagedIds(await f91($,Z,Q),Z)}async function hV$($,Z,Q){let Y=$.organization?.id;if(!Y)return;try{let X=T$[Z];for(let J of await y91($,Y,Q)){let G=await $.storage.taskBoard.getById(J,Y);if(!G)continue;if(G.status===X||!KT0(G.status,X))continue;let W=await $.storage.taskBoard.update(J,Y,{status:X},$.auth?.user?.id??G.updatedBy);if(await $.storage.taskBoard.recordActivity({taskBoardItemId:J,action:"status_changed",actorId:null,data:{from:G.status,to:X}}).catch((K)=>console.error("[task-board] activity log write failed",K)),E8(Y,W),Z==="progress")PT0("task_run_started",Y,W,{from:G.status})}}catch(X){console.error("[task-board] run transition failed",X)}}async function AT0($,Z){let Q=$.organization?.id;if(!Q)return;try{for(let Y of await y91($,Q,Z)){let X=await $.storage.taskBoard.openReviewCycleIfInProgress(Y,Q);if(!X)continue;E8(Q,X),PT0("task_run_completed",Q,X,{from:"in_progress",via:"pr_open"})}}catch(Y){console.error("[task-board] review-cycle open failed",Y)}}async function TT0($,Z,Q,Y){let X=$.organization?.id;if(!X)return;try{let J=Sj(Z);if(!J)return;let G=await y91($,X,Y);for(let W of G)await $.storage.taskBoard.linkPr({taskBoardItemId:W,organizationId:X,url:J.url,prNumber:J.number,repo:J.repo,connectionId:Q??null});if(G.length>0)await aG(X)}catch(J){console.error("[task-board] PR capture failed",J)}}async function Tm($,Z,Q,Y){try{let X=await $.advanceLinkedTasksToReviewOnThreadFinish(Z,Q);for(let J of X)E8(Q,J),PT0("task_run_completed",Q,J,{from:"in_progress",via:"thread_finish"});for(let J of X)await $.clearRunRetry(J.id,Q).catch(()=>{})}catch(X){console.error("[task-board] thread-finish transition failed",X)}await g91($,Z,Q),await h91($,Y,Z,Q)}function uV$($){return(sx($.status)??-1)>=WT0.in_review||Boolean($.reviewCycleStartedAt)}async function g91($,Z,Q){try{let Y=await $.failedRunInfo(Z,Q);if(!Y)return;let X=fV$(Y);for(let J of await $.linkedTaskIds(Z,Q)){let G=await $.getById(J,Q);if(!G)continue;if(G.source)continue;if(uV$(G))await $.relabelDeliveredFailure(Z,Q,nt4).catch(()=>{});if(G.status!==T$.progress)continue;if(G.reviewCycleStartedAt)continue;if(G.threads.some((H)=>H.hasMessages&&H.status==="in_progress"))continue;let W=G.retryAttempts;if(W<X){let H=QQ(pt4,it4,W,2,0.5);if(!await $.scheduleRunRetry(J,Q,W+1,new Date(Date.now()+H)))continue;await $.recordActivity({taskBoardItemId:J,action:"status_changed",actorId:null,data:{from:T$.progress,to:T$.progress,retry:W+1,of:X,reason:Y.errorText??Y.kind}}).catch(()=>{});continue}let K=await $.returnToTodoAfterFailure(J,Q,G.updatedBy);if(!K)continue;await $.recordActivity({taskBoardItemId:J,action:"status_changed",actorId:null,data:{from:T$.progress,to:T$.queue,reason:Y.errorText??Y.kind,retriesSpent:W}}).catch(()=>{}),E8(Q,K),PT0("task_run_failed",Q,G,{reason:Y.kind??"error",retries_spent:W})}}catch(Y){console.error("[task-board] failed-run reaction failed",Y)}}async function h91($,Z,Q,Y){try{for(let X of await $.linkedTaskIds(Q,Y)){let J=await $.getById(X,Y);if(!J)continue;if(J.source)continue;if(uV$(J))continue;if(J.threads.some((W)=>W.hasMessages&&(W.status===null||!s00.has(W.status))))continue;if((await $.listPrs(X,Y)).length>0)continue;await LF$(Z,Y,X)}}catch(X){console.error("[task-board] quota refund pass failed",X)}}async function u91($,Z){if(Z.status!==T$.progress||!VX(Z))return;try{let Q=await $.storage.taskBoard.update(Z.id,Z.organizationId,{status:T$.review},Z.updatedBy);await $.storage.taskBoard.recordActivity({taskBoardItemId:Z.id,action:"status_changed",actorId:null,data:{from:Z.status,to:T$.review}}).catch(()=>{}),E8(Z.organizationId,Q),await XV$($,Q)}catch(Q){console.error(`[task-board] parking ${Z.id} for review failed`,Q)}}async function KH($,Z,Q){let Y=Z.organizationId;if(Z.assigneeId!==j8)return!1;try{await u91($,Z).catch((J)=>console.warn(`[task-board] parking ${Z.id} before hand-off failed`,J));let X=await $.storage.taskBoard.unassignSuperAgent(Z.id,Y,Z.updatedBy);if(!X)return!1;return await o6($,{taskBoardItemId:Z.id,action:"assignee_changed",actorId:null,data:{from:Z.assigneeId,to:null,reason:Q}}),console.warn(`[task-board] ${Z.id} handed to a human: ${Q}`),E8(Y,X),!0}catch(X){return console.error(`[task-board] handing ${Z.id} to a human failed`,X),!1}}async function wV$($,Z,Q){if(!(Q instanceof zX))return!1;if(Q.reason!=="runs_exhausted")return!1;return await KH($,Z,"per-task run limit reached \u2014 the Super Agent can no longer re-dispatch "+"itself on this task. Re-run it manually to continue."),!0}async function lV$($,Z){let Q=$.organization?.id;if(!Q)return;try{let Y=await $.storage.taskBoard.reopenLinkedTasksOnThreadRun(Z,Q);for(let X of Y)E8(Q,X)}catch(Y){console.error("[task-board] thread-run reopen failed",Y)}}function cV$($){return $.includes("create_pull_request")||$.includes("createPullRequest")||$.includes("create_merge_request")||$.includes("createMergeRequest")}function mV$($){if(tt4.test($))return!0;return ot4.test($)&&rt4.test($)}var it4=30000,pt4=120000,nt4="Run ended after it had already delivered \u2014 the task moved on without it",tt4,ot4,rt4;var V9=D(()=>{FW();U6();YO();tx();JV$();z7();yV$();D8();o00();C4();_Y();WH();tt4=/\b(?:gh\s+pr|glab\s+mr)\s+create\b/,ot4=/\/(?:repos\/[^\s"']+\/pulls|projects\/[^\s"']+\/merge_requests|repositories\/[^\s"']+\/pullrequests)\b/,rt4=/(?:-X|--request)\s+POST/});function st4($){if($.status==="completed")return"advance";if($.status==="failed"&&$.messageStorageVersion===2&&($.harnessId==="decopilot"||$.harnessId==="claude-code"))return"nudge";return"none"}function at4($){return["This task is still In Progress on the board and your last run ended without finishing it.","","Look at what you already did (`git log`, `git status`, and the messages above), then either:","- finish the remaining work (and open the PR, if it needed code changes),","- or, if it's actually done, say so in one line \u2014 the board moves the card for you,",$==="decopilot"?"- or, if you're blocked on something only a human knows, call the `user_ask` tool.":"- or, if you're blocked on something only a human knows, say what you need and stop.","","Don't start over and don't redo work you already committed or pushed. You are on the same branch as before \u2014 push to it and update your existing pull request rather than opening a second one."].join(`
|
|
1601
|
-
`)}async function et4($,Z,Q){await Nm($,Z,Q,{messageId:`stall-nudge-${Z.id}-${Q.id}`,prompt:at4(Q.harness_id),workflowID:`stall-nudge:${Z.id}:${Q.id}`})}async function $o4($,Z){let Q=await $.storage.threads.get(Z);if(!Q)return{action:"none",thread:null};return{action:st4({status:Q.status,messageStorageVersion:Q.message_storage_version,harnessId:Q.harness_id}),thread:Q}}function Zo4($,Z=Date.now()){if($.status!=="in_progress")return!1;if($.run_started_at)return!1;return m00($,Z)}async function Qo4($,Z){let Q=[];for(let Y of Z.threads){if(Y.status!=="in_progress")continue;let X=await $.storage.threads.get(Y.threadId);if(!X||!Zo4(X))continue;if(await $.storage.threads.markRunFailed(Y.threadId,l91,"abandoned"))Q.push(Y.threadId),console.warn(`[task-board] failed never-started thread ${Y.threadId} on ${Z.id}`)}return Q}async function dV$($,Z){let Q=$.organization?.id;if(!Q)return;for(let Y of Z){if(Y.status==="in_progress")try{if((await Qo4($,Y)).length>0)continue}catch(G){console.error(`[task-board] reaping threads for ${Y.id} failed`,G)}let X;try{X=Y.repo!=null&&(await $.storage.taskBoard.listPrs(Y.id,Q)).length>0}catch(G){console.error(`[task-board] listPrs for ${Y.id} failed`,G);continue}if(!N91(Y,X))continue;let J=Y.threads.find((G)=>G.hasMessages);if(!J)continue;try{let{action:G,thread:W}=await $o4($,J.threadId);if(G==="none"||!W)continue;if(G==="advance")await Tm($.storage.taskBoard,J.threadId,Q,$.storage.organizationBilling);else await et4($,Y,W)}catch(G){console.error(`[task-board] stall recovery failed for ${Y.id}`,G)}}}var l91="Run never started \u2014 no pod picked it up before the idle window elapsed";var c91=D(()=>{o20();YO();V9()});import{z as jU}from"zod";var Yo4,Xo4,W10;var m91=D(()=>{C4();C0();wJ();IJ();c91();YT0();Yo4=jU.object({key:jU.string(),title:jU.string(),position:jU.number()}),Xo4=d({name:"TASK_BOARD_ITEM_LIST",description:"List all task board items for the organization, plus the `owner/name` repos this organization has imported (the valid values for a task's `repo` field).",annotations:{title:"List Task Board Items",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:jU.object({}),outputSchema:jU.object({items:jU.array(cc),repos:jU.array(jU.string()),columns:jU.array(Yo4)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let[Y,{items:X},J]=await Promise.all([Z.storage.taskBoard.list(Q),Z.storage.connections.list(Q,{slug:"mcp-github"}),Z.storage.repositories.listByOrg(Q)]),G=[...new Set([...J.map((W)=>W.path),...JH$(X)])];return dV$(Z,Y),{items:Y,repos:G,columns:JF$}}}),W10=wm(Xo4)});async function iV$($,Z,Q){if(Z.assigneeId)return Z;let Y=Z.organizationId,X=await $.storage.columnAutomations.get(Y,Z.status);if(!X)return Z;let J=await $.storage.taskBoard.claimUnassignedForSuperAgent(Z.id,Y,Q.assignedBy,Q.actor,Z.status);if(!J)return Z;await $.storage.taskBoard.recordActivity({taskBoardItemId:Z.id,action:"assignee_changed",actorId:null,data:{from:null,to:j8}});try{await vj($,J,{instruction:X.prompt??void 0})}catch(G){return console.warn(`[task-board] column rule on ${Z.status} rejected for ${Z.id}, un-delegating:`,G instanceof Error?G.message:G),await $.storage.taskBoard.unassignSuperAgent(Z.id,Y,Q.actor)??await $.storage.taskBoard.getById(Z.id,Y)??J}return J}var pV$=D(()=>{C4();wU()});function nV$($){if($===void 0)return;let Z=[];for(let Q of $){let Y=Q.trim().replace(/[\t\r\n]/g,"").replace(/\\/g,"/");if(!Y.startsWith("/")||Y.startsWith("//"))continue;if(!Z.includes(Y))Z.push(Y);if(Z.length===20)break}return Z}import{z as kX}from"zod";function Wo4($){return Go4.some((Z)=>$[Z]!==void 0)}function Ko4($,Z){let Q=[];for(let{field:J,action:G}of Jo4){if(Z[J]===$[J])continue;Q.push({action:G,data:{from:$[J],to:Z[J]}})}if(Z.description!==$.description)Q.push({action:"description_changed"});let Y=new Set($.tags.map((J)=>J.id));if(Z.tags.length!==$.tags.length||Z.tags.some((J)=>!Y.has(J.id)))Q.push({action:"tags_changed",data:{from:$.tags,to:Z.tags}});return Q}function Ho4($,Z){if($!==j8)return!1;if(!Z)return!1;return Z.assigneeId!==j8?!0:Z.status===T$.queue}function Uo4($,Z,Q){let Y=$!==void 0&&Fo4.has($),X=Z!==void 0&&VX(Z);return Q&&Y&&X}function d91($,Z){return $!==void 0&&D91($)&&!Z}var Jo4,Go4,Fo4,K10;var RT0=D(()=>{C4();C0();IZ();IJ();WH();b41();wU();_Y();tB();V9();pV$();tx();z7();FW();Jo4=[{field:"status",action:"status_changed"},{field:"assigneeId",action:"assignee_changed"},{field:"priority",action:"priority_changed"},{field:"type",action:"type_changed"},{field:"dueDate",action:"due_date_changed"},{field:"title",action:"title_changed"}],Go4=["title","description","status","priority","type","assigneeId","repo","dueDate","sortOrder","previewRoutes","tagIds"];Fo4=new Set(["approved","merged","post_deploy_validation","done","archived"]);K10=d({name:"TASK_BOARD_ITEM_UPDATE",description:"Update a task board item's fields (title, description, status, priority, assignee), and/or link a chat thread to it.",annotations:{title:"Update Task Board Item",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:kX.object({id:kX.string(),title:kX.string().min(1).max(uc).optional(),description:kX.string().max(hc).nullable().optional(),status:oB.optional(),priority:kx.optional(),type:Q00.optional(),assigneeId:kX.string().nullable().optional(),repo:kX.string().max(MA0).nullable().optional(),dueDate:kX.string().datetime().nullable().optional(),sortOrder:kX.number().optional(),previewRoutes:kX.array(kX.string().max(500)).max(20).optional().describe("Paths this task's work created or edited, e.g. "+'["/cliente-vip", "/cliente-vip/faq"]. Paths only \u2014 no host: the '+"card joins each onto the pull request's deploy-preview origin so a reviewer can open the pages directly. Replaces the previous set; pass [] to clear."),tagIds:kX.array(kX.string()).max(1000).optional(),linkThreadId:kX.string().optional(),prUrl:kX.string().nullable().optional().describe("GitHub pull request URL to link to this task, e.g. https://github.com/owner/repo/pull/123. Pass it after opening a PR for an existing card; linking one is what starts its review.")}),outputSchema:kX.object({item:cc}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=$.prUrl?Sj($.prUrl):null;if($.prUrl&&!Y)throw Error(`Not a change request URL: ${$.prUrl} (expected https://github.com/<owner>/<repo>/pull/<number>, https://gitlab.com/<namespace>/<project>/-/merge_requests/<iid> or https://bitbucket.org/<workspace>/<repo>/pull-requests/<id>)`);if($.assigneeId)await IA0(Z,Q,$.assigneeId);if($.linkThreadId){if(!await Z.storage.taskBoard.getById($.id,Q))throw Error(`Task board item not found: ${$.id}`);if(!await Z.storage.threads.get($.linkThreadId))throw Error(`Thread not found: ${$.linkThreadId}`);await Z.storage.taskBoard.linkThread($.id,$.linkThreadId,Q)}let X=Wo4($),J=X?await Z.storage.taskBoard.getById($.id,Q):null;if(X&&!J)throw Error(`Task board item not found: ${$.id}`);if($.status!==void 0&&D91($.status)){let N=await Z.storage.organizationSettings.get(Q);if(d91($.status,VQ(N?.flags,"delivery_lanes_enabled")))throw Error("Delivery lanes are not enabled for this organization \u2014 enable "+"them in Settings before moving a task to Approved, Merged, or Post-deploy Validation.")}let G=nG.getStore()!==void 0;if(Uo4($.status,J??void 0,G))throw Error("This task is under review \u2014 a run can't move it to Done or Archived. "+"Leave it for the reviewer; only a person, or TASK_BOARD_REVIEW_DECISION on a reviewer's own run, closes out a task under review.");let W=$.assigneeId!==void 0&&$.assigneeId!==(J?.assigneeId??null),K=Ho4($.assigneeId,J),F=(K?T$.queue:void 0)??$.status;if(J&&PY(J)){if($.title!==void 0||$.description!==void 0||$.priority!==void 0)throw Error("This task was generated from your report and can't be edited \u2014 create your own task instead.");if(K)await Jc(Z,J,hw())}if($.tagIds!==void 0){let N=await Z.storage.tags.listOrgTags(Q),B=new Set(N.map((O)=>O.id));for(let O of $.tagIds)if(!B.has(O))throw Error(`Tag not found: ${O}`);await Z.storage.taskBoard.setItemTags($.id,$.tagIds,p0(Z))}let U;if(X)U=await Z.storage.taskBoard.update($.id,Q,{title:$.title,description:$.description,status:F,priority:$.priority,type:$.type,assigneeId:$.assigneeId,assignedBy:W?$.assigneeId?p0(Z):null:void 0,repo:$.repo,dueDate:$.dueDate,sortOrder:$.sortOrder,previewRoutes:nV$($.previewRoutes)},p0(Z));else{let N=await Z.storage.taskBoard.getById($.id,Q);if(!N)throw Error(`Task board item not found: ${$.id}`);U=N}if(Y)await Z.storage.taskBoard.linkPr({taskBoardItemId:U.id,organizationId:Q,url:Y.url,prNumber:Y.number,repo:Y.repo,connectionId:null}),await aG(Q).catch((N)=>{console.error("[task-board] PR card cache invalidation failed",N)});if(J){let N=p0(Z),B=Ko4(J,U);if(B.length>0)await GV$(Z,B.map((O)=>({taskBoardItemId:U.id,actorId:N,...O,alsoSubscribe:O.action==="assignee_changed"&&U.assigneeId!==j8?[U.assigneeId]:void 0})))}if(J&&U.description!==J.description)await Z.storage.notifications.notifyMentions({taskBoardItemId:U.id,organizationId:Q,actorId:p0(Z),body:U.description??"",previousBody:J.description});if(X||$.linkThreadId||Y)E8(Q,U);if(K)return await vj(Z,U,{userInitiated:!0}),{item:U};if($.status!==void 0&&J!==null&&J.status!==U.status)U=await iV$(Z,U,{assignedBy:p0(Z),actor:p0(Z)});return{item:U}}})});import{z as qT0}from"zod";var H10;var i91=D(()=>{C0();V9();H10=d({name:"TASK_BOARD_ITEM_DELETE",description:"Delete a task board item. A reports-pushed task also dismisses its finding, so the next diagnostic import won't re-create the card.",annotations:{title:"Delete Task Board Item",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:qT0.object({id:qT0.string()}),outputSchema:qT0.object({success:qT0.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(!await Z.storage.taskBoard.delete($.id,Q,p0(Z)??"system"))throw Error(`Task board item not found: ${$.id}`);return gV$(Q,$.id),{success:!0}}})});import{z as z8}from"zod";async function p91($,Z,Q){let Y=K0(Z),X={query:{orgIds:[Y.id]},org:Y.slug??Y.id},J=$.to??new Date().toISOString(),W={from:$.from??new Date(Date.parse(J)-No4).toISOString(),to:J},K=$.org;if(!K||K===Y.slug||K===Y.id)return{query:{...W,...X.query},org:X.org};let H=DU(Y.id)&&await LU(Z);if(K==="all"){if(!H)return{query:{...W,...X.query},org:X.org};return XO({action:"analytics_read",actorUserId:Z.auth?.user?.id,actorOrgId:Y.id,targetOrgId:"all",tool:Q}),{query:{...W,orgIds:null},org:"all"}}if(!H)throw Error("Not allowed to read another organization's task board analytics");let F=await Z.storage.taskBoardAnalytics.resolveOrgRef(K);if(!F)throw Error(`Organization not found: ${K}`);return XO({action:"analytics_read",actorUserId:Z.auth?.user?.id,actorOrgId:Y.id,targetOrgId:F.id,tool:Q}),{query:{...W,orgIds:[F.id]},org:F.slug||F.id}}function Eo4($){let Z=$.sections.filter((Y)=>Y.kind==="stat").flatMap((Y)=>Y.values).map((Y)=>`${Y.label}: ${Y.value??"\u2014"}${Y.unit?` ${Y.unit}`:""}`).join(", "),Q=$.sections.filter((Y)=>Y.kind==="table").map((Y)=>`${Y.title} (${Y.rows.length} rows)`).join(", ");return[`${$.org}, ${$.range.from}..${$.range.to}`,Z,Q].filter(Boolean).join(" \u2014 ")}function GO($,Z,Q,Y){return d({name:$,description:Q,annotations:{title:Z,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Bo4,outputSchema:jo4,modelSummary:Eo4,handler:async(X,J)=>{a(J),await J.access.check();let{query:G,org:W}=await p91(X,J,$);return{range:{from:G.from,to:G.to},org:W,sections:await Y(J,G)}}})}var No4=2592000000,Bo4,Oo4,Do4,Lo4,wo4,jo4,F10,U10,N10,B10,O10,D10,L10;var MT0=D(()=>{C0();Lm();Bo4=z8.object({org:z8.string().optional().describe('Org slug or id to report on. Omit for the current org. "all" is the cross-tenant aggregate (admin orgs only).'),from:z8.string().datetime({offset:!0}).optional().describe("ISO start of the range. Defaults to 30 days ago."),to:z8.string().datetime({offset:!0}).optional().describe("ISO end of the range. Defaults to now.")}).refine(($)=>!$.from||!$.to||Date.parse($.from)<=Date.parse($.to),{message:"`from` must not be after `to`",path:["from"]}),Oo4=z8.object({kind:z8.literal("stat"),title:z8.string(),values:z8.array(z8.object({label:z8.string(),value:z8.number().nullable(),unit:z8.string().optional()}))}),Do4=z8.object({kind:z8.literal("series"),title:z8.string(),unit:z8.string().optional(),points:z8.array(z8.record(z8.string(),z8.union([z8.number(),z8.string(),z8.null()])))}),Lo4=z8.object({kind:z8.literal("table"),title:z8.string(),columns:z8.array(z8.string()),rows:z8.array(z8.array(z8.union([z8.string(),z8.number(),z8.null()])))}),wo4=z8.discriminatedUnion("kind",[Oo4,Do4,Lo4]),jo4=z8.object({range:z8.object({from:z8.string(),to:z8.string()}),org:z8.string(),sections:z8.array(wo4)});F10=GO("TASK_BOARD_DELIVERY","Task Board Delivery","Task board throughput and flow: tasks completed, how many shipped a PR, lead vs cycle time, completions per day by board, time in review, and dwell by lane.",($,Z)=>$.storage.taskBoardAnalytics.delivery(Z)),U10=GO("TASK_BOARD_STUCK","Task Board Stuck Work","What is stuck on the task board right now: open lane visits oldest first, and work in progress bucketed by age. Deliberately not time-filtered.",($,Z)=>$.storage.taskBoardAnalytics.stuck(Z)),N10=GO("TASK_BOARD_COST","Task Board Cost","Task board spend: total USD, cost per completed task and per shipped PR, spend burned on abandoned work, spend per day, cost by tenant, and the coverage % that says how much of it was actually priced.",($,Z)=>$.storage.taskBoardAnalytics.cost(Z)),B10=GO("TASK_BOARD_QUALITY","Task Board Quality","Task board quality: first-pass yield, rework rate, autonomy (finished without a human), abandonment, rework over time, and retry burn.",($,Z)=>$.storage.taskBoardAnalytics.quality(Z)),O10=GO("TASK_BOARD_ERRORS","Task Board Errors","Task board run failures: failed runs, quota-blocked runs, failures per day, failure kinds, a live error feed, error signatures, and superseded runs.",($,Z)=>$.storage.taskBoardAnalytics.errors(Z)),D10=GO("TASK_BOARD_TENANTS","Task Board Tenants",'Per-tenant task board scorecard and queue wait. Pass org: "all" for the cross-tenant view (admin orgs only).',($,Z)=>$.storage.taskBoardAnalytics.tenants(Z)),L10=d({name:"TASK_BOARD_ADMIN_ORG_LIST",description:"Whether the caller may read every org's task board, and if so the orgs that have board items. Non-admins get an empty list.",annotations:{title:"List Task Board Admin Orgs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:z8.object({}),outputSchema:z8.object({isTaskBoardAdmin:z8.boolean(),orgs:z8.array(z8.object({id:z8.string(),slug:z8.string(),name:z8.string()}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);if(!DU(Q.id)||!await LU(Z))return{isTaskBoardAdmin:!1,orgs:[]};return{isTaskBoardAdmin:!0,orgs:await Z.storage.taskBoardAnalytics.orgsWithBoardItems()}}})});function tV$($,Z){let Q=({output:X,toolCallId:J})=>j20(X,J,Z)??{type:"json",value:X},Y=(X)=>c$({description:X.description,inputSchema:r(X.inputSchema),execute:(J)=>X.execute(J,$),toModelOutput:Q});return{TASK_BOARD_ITEM_LIST:Y(W10),TASK_BOARD_ITEM_CREATE:Y(w10),TASK_BOARD_ITEM_UPDATE:Y(K10),TASK_BOARD_ITEM_DELETE:Y(H10),TASK_BOARD_ITEM_PRS_GET:Y(G10),TASK_BOARD_ADMIN_ORG_LIST:Y(L10),TASK_BOARD_DELIVERY:Y(F10),TASK_BOARD_STUCK:Y(U10),TASK_BOARD_COST:Y(N10),TASK_BOARD_QUALITY:Y(B10),TASK_BOARD_ERRORS:Y(O10),TASK_BOARD_TENANTS:Y(D10)}}var oV$=D(()=>{v4();UU();n91();m91();RT0();i91();z7();MT0()});import{z as j10}from"zod";var zo4,Po4,Ao4,rV$;var sV$=D(()=>{v4();IJ();zo4=j10.object({title:j10.string().min(1).max(uc).describe("The task as one imperative line (\u226410 words), e.g. 'Add dark mode to the settings page'."),summary:j10.string().min(1).max(hc).describe("Two or three sentences the user can check at a glance: what would be built and why. "+"Written for the user, not for the board \u2014 the real description is written later.")}),Po4=j10.object({accepted:j10.boolean().describe("True when the user agreed to turn this into a task.")}),Ao4="Offer to turn what the user just said into a task on the board. Call this as soon as a "+"message reads like a new piece of work \u2014 a feature they want, a bug they hit, something "+`they wish the product did \u2014 rather than answering it as a question.
|
|
1601
|
+
`)}async function et4($,Z,Q){await Nm($,Z,Q,{messageId:`stall-nudge-${Z.id}-${Q.id}`,prompt:at4(Q.harness_id),workflowID:`stall-nudge:${Z.id}:${Q.id}`})}async function $o4($,Z){let Q=await $.storage.threads.get(Z);if(!Q)return{action:"none",thread:null};return{action:st4({status:Q.status,messageStorageVersion:Q.message_storage_version,harnessId:Q.harness_id}),thread:Q}}function Zo4($,Z=Date.now()){if($.status!=="in_progress")return!1;if($.run_started_at)return!1;return m00($,Z)}async function Qo4($,Z){let Q=[];for(let Y of Z.threads){if(Y.status!=="in_progress")continue;let X=await $.storage.threads.get(Y.threadId);if(!X||!Zo4(X))continue;if(await $.storage.threads.markRunFailed(Y.threadId,l91,"abandoned"))Q.push(Y.threadId),console.warn(`[task-board] failed never-started thread ${Y.threadId} on ${Z.id}`)}return Q}async function dV$($,Z){let Q=$.organization?.id;if(!Q)return;for(let Y of Z){if(Y.status==="in_progress")try{if((await Qo4($,Y)).length>0)continue}catch(G){console.error(`[task-board] reaping threads for ${Y.id} failed`,G)}let X;try{X=Y.repo!=null&&(await $.storage.taskBoard.listPrs(Y.id,Q)).length>0}catch(G){console.error(`[task-board] listPrs for ${Y.id} failed`,G);continue}if(!N91(Y,X))continue;let J=Y.threads.find((G)=>G.hasMessages);if(!J)continue;try{let{action:G,thread:W}=await $o4($,J.threadId);if(G==="none"||!W)continue;if(G==="advance")await Tm($.storage.taskBoard,J.threadId,Q,$.storage.organizationBilling);else await et4($,Y,W)}catch(G){console.error(`[task-board] stall recovery failed for ${Y.id}`,G)}}}var l91="Run never started \u2014 no pod picked it up before the idle window elapsed";var c91=D(()=>{o20();YO();V9()});import{z as jU}from"zod";var Yo4,Xo4,W10;var m91=D(()=>{C4();C0();wJ();IJ();c91();YT0();Yo4=jU.object({key:jU.string(),title:jU.string(),position:jU.number()}),Xo4=d({name:"TASK_BOARD_ITEM_LIST",description:"List all task board items for the organization, plus the `owner/name` repos this organization has imported (the valid values for a task's `repo` field).",annotations:{title:"List Task Board Items",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:jU.object({}),outputSchema:jU.object({items:jU.array(cc),repos:jU.array(jU.string()),columns:jU.array(Yo4)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let[Y,{items:X},J]=await Promise.all([Z.storage.taskBoard.list(Q),Z.storage.connections.list(Q,{slug:"mcp-github"}),Z.storage.repositories.listByOrg(Q)]),G=[...new Set([...J.map((W)=>W.path),...JH$(X)])];return dV$(Z,Y),{items:Y,repos:G,columns:JF$}}}),W10=wm(Xo4)});async function iV$($,Z,Q){if(Z.assigneeId)return Z;let Y=Z.organizationId,X=await $.storage.columnAutomations.get(Y,Z.status);if(!X)return Z;let J=await $.storage.taskBoard.claimUnassignedForSuperAgent(Z.id,Y,Q.assignedBy,Q.actor,Z.status);if(!J)return Z;await $.storage.taskBoard.recordActivity({taskBoardItemId:Z.id,action:"assignee_changed",actorId:null,data:{from:null,to:j8}});try{await vj($,J,{instruction:X.prompt??void 0})}catch(G){return console.warn(`[task-board] column rule on ${Z.status} rejected for ${Z.id}, un-delegating:`,G instanceof Error?G.message:G),await $.storage.taskBoard.unassignSuperAgent(Z.id,Y,Q.actor)??await $.storage.taskBoard.getById(Z.id,Y)??J}return J}var pV$=D(()=>{C4();wU()});function nV$($){if($===void 0)return;let Z=[];for(let Q of $){let Y=Q.trim().replace(/[\t\r\n]/g,"").replace(/\\/g,"/");if(!Y.startsWith("/")||Y.startsWith("//"))continue;if(!Z.includes(Y))Z.push(Y);if(Z.length===20)break}return Z}import{z as kX}from"zod";function Wo4($){return Go4.some((Z)=>$[Z]!==void 0)}function Ko4($,Z){let Q=[];for(let{field:J,action:G}of Jo4){if(Z[J]===$[J])continue;Q.push({action:G,data:{from:$[J],to:Z[J]}})}if(Z.description!==$.description)Q.push({action:"description_changed"});let Y=new Set($.tags.map((J)=>J.id));if(Z.tags.length!==$.tags.length||Z.tags.some((J)=>!Y.has(J.id)))Q.push({action:"tags_changed",data:{from:$.tags,to:Z.tags}});return Q}function Ho4($,Z){if($!==j8)return!1;if(!Z)return!1;return Z.assigneeId!==j8?!0:Z.status===T$.queue}function Uo4($,Z,Q){let Y=$!==void 0&&Fo4.has($),X=Z!==void 0&&VX(Z);return Q&&Y&&X}function d91($,Z){return $!==void 0&&D91($)&&!Z}var Jo4,Go4,Fo4,K10;var RT0=D(()=>{C4();C0();IZ();IJ();WH();b41();wU();_Y();tB();V9();pV$();tx();z7();FW();Jo4=[{field:"status",action:"status_changed"},{field:"assigneeId",action:"assignee_changed"},{field:"priority",action:"priority_changed"},{field:"type",action:"type_changed"},{field:"dueDate",action:"due_date_changed"},{field:"title",action:"title_changed"}],Go4=["title","description","status","priority","type","assigneeId","repo","dueDate","sortOrder","previewRoutes","tagIds"];Fo4=new Set(["approved","merged","post_deploy_validation","done","archived"]);K10=d({name:"TASK_BOARD_ITEM_UPDATE",description:"Update a task board item's fields (title, description, status, priority, assignee), and/or link a chat thread to it.",annotations:{title:"Update Task Board Item",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:kX.object({id:kX.string(),title:kX.string().min(1).max(uc).optional(),description:kX.string().max(hc).nullable().optional(),status:oB.optional(),priority:kx.optional(),type:Q00.optional(),assigneeId:kX.string().nullable().optional(),repo:kX.string().max(MA0).nullable().optional(),dueDate:kX.string().datetime().nullable().optional(),sortOrder:kX.number().optional(),previewRoutes:kX.array(kX.string().max(500)).max(20).optional().describe("Paths this task's work created or edited, e.g. "+'["/cliente-vip", "/cliente-vip/faq"]. Paths only \u2014 no host: the '+"card joins each onto the pull request's deploy-preview origin so a reviewer can open the pages directly. Replaces the previous set; pass [] to clear."),tagIds:kX.array(kX.string()).max(1000).optional(),linkThreadId:kX.string().optional(),prUrl:kX.string().nullable().optional().describe("GitHub pull request URL to link to this task, e.g. https://github.com/owner/repo/pull/123. Pass it after opening a PR for an existing card; linking one is what starts its review.")}),outputSchema:kX.object({item:cc}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=$.prUrl?Sj($.prUrl):null;if($.prUrl&&!Y)throw Error(`Not a change request URL: ${$.prUrl} (expected https://github.com/<owner>/<repo>/pull/<number>, https://gitlab.com/<namespace>/<project>/-/merge_requests/<iid> or https://bitbucket.org/<workspace>/<repo>/pull-requests/<id>)`);if($.assigneeId)await IA0(Z,Q,$.assigneeId);if($.linkThreadId){if(!await Z.storage.taskBoard.getById($.id,Q))throw Error(`Task board item not found: ${$.id}`);if(!await Z.storage.threads.get($.linkThreadId))throw Error(`Thread not found: ${$.linkThreadId}`);await Z.storage.taskBoard.linkThread($.id,$.linkThreadId,Q)}let X=Wo4($),J=X?await Z.storage.taskBoard.getById($.id,Q):null;if(X&&!J)throw Error(`Task board item not found: ${$.id}`);if($.status!==void 0&&D91($.status)){let N=await Z.storage.organizationSettings.get(Q);if(d91($.status,VQ(N?.flags,"delivery_lanes_enabled")))throw Error("Delivery lanes are not enabled for this organization \u2014 enable "+"them in Settings before moving a task to Approved, Merged, or Post-deploy Validation.")}let G=nG.getStore()!==void 0;if(Uo4($.status,J??void 0,G))throw Error("This task is under review \u2014 a run can't move it to Done or Archived. "+"Leave it for the reviewer; only a person, or TASK_BOARD_REVIEW_DECISION on a reviewer's own run, closes out a task under review.");let W=$.assigneeId!==void 0&&$.assigneeId!==(J?.assigneeId??null),K=Ho4($.assigneeId,J),F=(K?T$.queue:void 0)??$.status;if(J&&PY(J)){if($.title!==void 0||$.description!==void 0||$.priority!==void 0)throw Error("This task was generated from your report and can't be edited \u2014 create your own task instead.");if(K)await Jc(Z,J,hw())}if($.tagIds!==void 0){let N=await Z.storage.tags.listOrgTags(Q),B=new Set(N.map((O)=>O.id));for(let O of $.tagIds)if(!B.has(O))throw Error(`Tag not found: ${O}`);await Z.storage.taskBoard.setItemTags($.id,$.tagIds,p0(Z))}let U;if(X)U=await Z.storage.taskBoard.update($.id,Q,{title:$.title,description:$.description,status:F,priority:$.priority,type:$.type,assigneeId:$.assigneeId,assignedBy:W?$.assigneeId?p0(Z):null:void 0,repo:$.repo,dueDate:$.dueDate,sortOrder:$.sortOrder,previewRoutes:nV$($.previewRoutes)},p0(Z));else{let N=await Z.storage.taskBoard.getById($.id,Q);if(!N)throw Error(`Task board item not found: ${$.id}`);U=N}if(Y)await Z.storage.taskBoard.linkPr({taskBoardItemId:U.id,organizationId:Q,url:Y.url,prNumber:Y.number,repo:Y.repo,connectionId:null}),await aG(Q).catch((N)=>{console.error("[task-board] PR card cache invalidation failed",N)});if(J){let N=p0(Z),B=Ko4(J,U);if(B.length>0)await GV$(Z,B.map((O)=>({taskBoardItemId:U.id,actorId:N,...O,alsoSubscribe:O.action==="assignee_changed"&&U.assigneeId!==j8?[U.assigneeId]:void 0})))}if(J&&U.description!==J.description)await Z.storage.notifications.notifyMentions({taskBoardItemId:U.id,organizationId:Q,actorId:p0(Z),body:U.description??"",previousBody:J.description});if(X||$.linkThreadId||Y)E8(Q,U);if(K)return await vj(Z,U,{userInitiated:!0}),{item:U};if($.status!==void 0&&J!==null&&J.status!==U.status)U=await iV$(Z,U,{assignedBy:p0(Z),actor:p0(Z)});return{item:U}}})});import{z as qT0}from"zod";var H10;var i91=D(()=>{C0();V9();H10=d({name:"TASK_BOARD_ITEM_DELETE",description:"Delete a task board item. A Deco Score task also dismisses its finding, so the next Deco Score import won't re-create the card.",annotations:{title:"Delete Task Board Item",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:qT0.object({id:qT0.string()}),outputSchema:qT0.object({success:qT0.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(!await Z.storage.taskBoard.delete($.id,Q,p0(Z)??"system"))throw Error(`Task board item not found: ${$.id}`);return gV$(Q,$.id),{success:!0}}})});import{z as z8}from"zod";async function p91($,Z,Q){let Y=K0(Z),X={query:{orgIds:[Y.id]},org:Y.slug??Y.id},J=$.to??new Date().toISOString(),W={from:$.from??new Date(Date.parse(J)-No4).toISOString(),to:J},K=$.org;if(!K||K===Y.slug||K===Y.id)return{query:{...W,...X.query},org:X.org};let H=DU(Y.id)&&await LU(Z);if(K==="all"){if(!H)return{query:{...W,...X.query},org:X.org};return XO({action:"analytics_read",actorUserId:Z.auth?.user?.id,actorOrgId:Y.id,targetOrgId:"all",tool:Q}),{query:{...W,orgIds:null},org:"all"}}if(!H)throw Error("Not allowed to read another organization's task board analytics");let F=await Z.storage.taskBoardAnalytics.resolveOrgRef(K);if(!F)throw Error(`Organization not found: ${K}`);return XO({action:"analytics_read",actorUserId:Z.auth?.user?.id,actorOrgId:Y.id,targetOrgId:F.id,tool:Q}),{query:{...W,orgIds:[F.id]},org:F.slug||F.id}}function Eo4($){let Z=$.sections.filter((Y)=>Y.kind==="stat").flatMap((Y)=>Y.values).map((Y)=>`${Y.label}: ${Y.value??"\u2014"}${Y.unit?` ${Y.unit}`:""}`).join(", "),Q=$.sections.filter((Y)=>Y.kind==="table").map((Y)=>`${Y.title} (${Y.rows.length} rows)`).join(", ");return[`${$.org}, ${$.range.from}..${$.range.to}`,Z,Q].filter(Boolean).join(" \u2014 ")}function GO($,Z,Q,Y){return d({name:$,description:Q,annotations:{title:Z,readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:Bo4,outputSchema:jo4,modelSummary:Eo4,handler:async(X,J)=>{a(J),await J.access.check();let{query:G,org:W}=await p91(X,J,$);return{range:{from:G.from,to:G.to},org:W,sections:await Y(J,G)}}})}var No4=2592000000,Bo4,Oo4,Do4,Lo4,wo4,jo4,F10,U10,N10,B10,O10,D10,L10;var MT0=D(()=>{C0();Lm();Bo4=z8.object({org:z8.string().optional().describe('Org slug or id to report on. Omit for the current org. "all" is the cross-tenant aggregate (admin orgs only).'),from:z8.string().datetime({offset:!0}).optional().describe("ISO start of the range. Defaults to 30 days ago."),to:z8.string().datetime({offset:!0}).optional().describe("ISO end of the range. Defaults to now.")}).refine(($)=>!$.from||!$.to||Date.parse($.from)<=Date.parse($.to),{message:"`from` must not be after `to`",path:["from"]}),Oo4=z8.object({kind:z8.literal("stat"),title:z8.string(),values:z8.array(z8.object({label:z8.string(),value:z8.number().nullable(),unit:z8.string().optional()}))}),Do4=z8.object({kind:z8.literal("series"),title:z8.string(),unit:z8.string().optional(),points:z8.array(z8.record(z8.string(),z8.union([z8.number(),z8.string(),z8.null()])))}),Lo4=z8.object({kind:z8.literal("table"),title:z8.string(),columns:z8.array(z8.string()),rows:z8.array(z8.array(z8.union([z8.string(),z8.number(),z8.null()])))}),wo4=z8.discriminatedUnion("kind",[Oo4,Do4,Lo4]),jo4=z8.object({range:z8.object({from:z8.string(),to:z8.string()}),org:z8.string(),sections:z8.array(wo4)});F10=GO("TASK_BOARD_DELIVERY","Task Board Delivery","Task board throughput and flow: tasks completed, how many shipped a PR, lead vs cycle time, completions per day by board, time in review, and dwell by lane.",($,Z)=>$.storage.taskBoardAnalytics.delivery(Z)),U10=GO("TASK_BOARD_STUCK","Task Board Stuck Work","What is stuck on the task board right now: open lane visits oldest first, and work in progress bucketed by age. Deliberately not time-filtered.",($,Z)=>$.storage.taskBoardAnalytics.stuck(Z)),N10=GO("TASK_BOARD_COST","Task Board Cost","Task board spend: total USD, cost per completed task and per shipped PR, spend burned on abandoned work, spend per day, cost by tenant, and the coverage % that says how much of it was actually priced.",($,Z)=>$.storage.taskBoardAnalytics.cost(Z)),B10=GO("TASK_BOARD_QUALITY","Task Board Quality","Task board quality: first-pass yield, rework rate, autonomy (finished without a human), abandonment, rework over time, and retry burn.",($,Z)=>$.storage.taskBoardAnalytics.quality(Z)),O10=GO("TASK_BOARD_ERRORS","Task Board Errors","Task board run failures: failed runs, quota-blocked runs, failures per day, failure kinds, a live error feed, error signatures, and superseded runs.",($,Z)=>$.storage.taskBoardAnalytics.errors(Z)),D10=GO("TASK_BOARD_TENANTS","Task Board Tenants",'Per-tenant task board scorecard and queue wait. Pass org: "all" for the cross-tenant view (admin orgs only).',($,Z)=>$.storage.taskBoardAnalytics.tenants(Z)),L10=d({name:"TASK_BOARD_ADMIN_ORG_LIST",description:"Whether the caller may read every org's task board, and if so the orgs that have board items. Non-admins get an empty list.",annotations:{title:"List Task Board Admin Orgs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:z8.object({}),outputSchema:z8.object({isTaskBoardAdmin:z8.boolean(),orgs:z8.array(z8.object({id:z8.string(),slug:z8.string(),name:z8.string()}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);if(!DU(Q.id)||!await LU(Z))return{isTaskBoardAdmin:!1,orgs:[]};return{isTaskBoardAdmin:!0,orgs:await Z.storage.taskBoardAnalytics.orgsWithBoardItems()}}})});function tV$($,Z){let Q=({output:X,toolCallId:J})=>j20(X,J,Z)??{type:"json",value:X},Y=(X)=>c$({description:X.description,inputSchema:r(X.inputSchema),execute:(J)=>X.execute(J,$),toModelOutput:Q});return{TASK_BOARD_ITEM_LIST:Y(W10),TASK_BOARD_ITEM_CREATE:Y(w10),TASK_BOARD_ITEM_UPDATE:Y(K10),TASK_BOARD_ITEM_DELETE:Y(H10),TASK_BOARD_ITEM_PRS_GET:Y(G10),TASK_BOARD_ADMIN_ORG_LIST:Y(L10),TASK_BOARD_DELIVERY:Y(F10),TASK_BOARD_STUCK:Y(U10),TASK_BOARD_COST:Y(N10),TASK_BOARD_QUALITY:Y(B10),TASK_BOARD_ERRORS:Y(O10),TASK_BOARD_TENANTS:Y(D10)}}var oV$=D(()=>{v4();UU();n91();m91();RT0();i91();z7();MT0()});import{z as j10}from"zod";var zo4,Po4,Ao4,rV$;var sV$=D(()=>{v4();IJ();zo4=j10.object({title:j10.string().min(1).max(uc).describe("The task as one imperative line (\u226410 words), e.g. 'Add dark mode to the settings page'."),summary:j10.string().min(1).max(hc).describe("Two or three sentences the user can check at a glance: what would be built and why. "+"Written for the user, not for the board \u2014 the real description is written later.")}),Po4=j10.object({accepted:j10.boolean().describe("True when the user agreed to turn this into a task.")}),Ao4="Offer to turn what the user just said into a task on the board. Call this as soon as a "+"message reads like a new piece of work \u2014 a feature they want, a bug they hit, something "+`they wish the product did \u2014 rather than answering it as a question.
|
|
1602
1602
|
|
|
1603
1603
|
`+`Guidelines:
|
|
1604
1604
|
- One call per distinct piece of work. Don't offer for work already on the board, and don't re-offer something the user just declined.
|
|
@@ -1711,7 +1711,7 @@ Respond with ONLY a JSON object of this shape, and nothing else:
|
|
|
1711
1711
|
{"matches": [{"draft": number, "duplicateOf": string | null, "confidence": "high" | "medium" | "low", "reason": string}]}`;var $71=D(()=>{v4();$_$();VY();C4();ua4=new Set(["a","an","and","the","to","of","in","on","for","with","is","it","be","as","at","by","or","from","that","this","when","n\xE3o","nao","de","da","do","das","dos","em","no","na","um","uma","para","pra","com","que","e","o","os","as"]);ca4=FH.object({duplicateOf:FH.string().nullable().describe("Id of the existing card that already tracks the drafted work, or null when no card does."),confidence:FH.enum(["high","medium","low"]).describe("`high` only when the two clearly ask for the same change. Related or overlapping work is `medium` at most."),reason:FH.string().describe("One sentence explaining the match, or the absence of one.")});ra4=FH.object({matches:FH.array(FH.object({draft:FH.number().int().describe("The draft's index, as listed."),duplicateOf:FH.string().nullable().describe("Id of the existing card that already tracks this draft, or null."),confidence:FH.enum(["high","medium","low"]).describe("`high` only when the two clearly ask for the same change. Related or overlapping work is `medium` at most."),reason:FH.string().describe("One sentence explaining the match.")})).describe("One entry per draft that has a plausible duplicate. Drafts with no candidate may be omitted.")})});import{z as _J}from"zod";async function $e4($,Z){let{organizationId:Q,existing:Y,reason:X,draft:J,pr:G}=Z,W=p0($);if(G)await $.storage.taskBoard.linkPr({taskBoardItemId:Y.id,organizationId:Q,url:G.url,prNumber:G.number,repo:G.repo,connectionId:null}),await aG(Q).catch((H)=>{console.error("[task-board] PR card cache invalidation failed",H)});await o6($,{taskBoardItemId:Y.id,action:"duplicate_reported",actorId:W,data:{title:J.title,reason:X}}),await $.storage.notifications.setSubscribed(W,Y.id,!0).catch((H)=>{console.error("[task-board] duplicate filer subscription failed",H)});let K=await $.storage.taskBoard.getById(Y.id,Q)??Y;if(G)E8(Q,K);return{item:K,deduplicated:!0,duplicateCheck:"matched",duplicateReason:X}}var w10;var n91=D(()=>{C4();C0();IZ();IJ();b41();wU();_Y();V9();tx();$71();z7();RT0();w10=d({name:"TASK_BOARD_ITEM_CREATE",description:"Create a new task board item for the organization.",annotations:{title:"Create Task Board Item",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:_J.object({title:_J.string().min(1).max(uc),description:_J.string().max(hc).nullable().optional(),status:oB.optional(),priority:kx.optional(),type:Q00.optional(),assigneeId:_J.string().nullable().optional(),repo:_J.string().max(MA0).nullable().optional(),dueDate:_J.string().datetime().nullable().optional(),tagIds:_J.array(_J.string()).max(1000).optional(),prUrl:_J.string().nullable().optional().describe("GitHub pull request URL to link to the new task, e.g. https://github.com/owner/repo/pull/123. Pass it right after you open a PR so the card lands on the board with its PR already attached for review."),onDuplicate:_J.enum(["create","return_existing"]).optional().describe("What to do when an open card already tracks this work. `return_existing` asks a model to compare the draft against the board's open cards and, on a confident match, returns that card instead of creating one (`deduplicated: true` in the output; a `prUrl` is linked to it). Default `create` skips the check. Use "+"`return_existing` when filing on someone's behalf \u2014 reports, "+"chat requests \u2014 where the same ask arrives more than once.")}),outputSchema:_J.object({item:cc,deduplicated:_J.boolean(),duplicateCheck:_J.enum(["off","matched","no_match","skipped"]),duplicateReason:_J.string().nullable()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=$.prUrl?Sj($.prUrl):null;if($.prUrl&&!Y)throw Error(`Not a change request URL: ${$.prUrl} (expected https://github.com/<owner>/<repo>/pull/<number>, https://gitlab.com/<namespace>/<project>/-/merge_requests/<iid> or https://bitbucket.org/<workspace>/<repo>/pull-requests/<id>)`);if($.status!==void 0){let H=await Z.storage.organizationSettings.get(Q);if(d91($.status,VQ(H?.flags,"delivery_lanes_enabled")))throw Error("Delivery lanes are not enabled for this organization \u2014 enable "+"them in Settings before creating a task in Approved, Merged, or Post-deploy Validation.")}if($.assigneeId)await IA0(Z,Q,$.assigneeId);let J=$.assigneeId===j8?T$.queue:$.status??T$.intake;if($.tagIds?.length){let H=await Z.storage.tags.listOrgTags(Q),F=new Set(H.map((U)=>U.id));for(let U of $.tagIds)if(!F.has(U))throw Error(`Tag not found: ${U}`)}let G=null;if($.onDuplicate==="return_existing"){if(G=await N_$(Z,Q,{title:$.title,description:$.description,repo:$.repo}).catch((H)=>{return console.error("[task-board] duplicate check failed",H),{status:"skipped",reason:H instanceof Error?H.message:String(H)}}),G.status==="matched")return $e4(Z,{organizationId:Q,existing:G.item,reason:G.reason,draft:$,pr:Y})}let W=await Z.storage.taskBoard.create({organizationId:Q,title:$.title,description:$.description??null,status:J,priority:$.priority,type:$.type,assigneeId:$.assigneeId??null,assignedBy:$.assigneeId?p0(Z):null,repo:$.repo??null,dueDate:$.dueDate??null,by:p0(Z)});if($.tagIds?.length)await Z.storage.taskBoard.setItemTags(W.id,$.tagIds,p0(Z)),W=await Z.storage.taskBoard.getById(W.id,Q);if(Y)await Z.storage.taskBoard.linkPr({taskBoardItemId:W.id,organizationId:Q,url:Y.url,prNumber:Y.number,repo:Y.repo,connectionId:null}),await aG(Q).catch((H)=>{console.error("[task-board] PR card cache invalidation failed",H)});await o6(Z,{taskBoardItemId:W.id,action:"created",actorId:p0(Z),alsoSubscribe:[p0(Z),W.assigneeId===j8?null:W.assigneeId]}),await Z.storage.notifications.notifyMentions({taskBoardItemId:W.id,organizationId:Q,actorId:p0(Z),body:W.description??""}),E8(Q,W),await vj(Z,W);let K=G?.status??"off";return{item:W,deduplicated:!1,duplicateCheck:K,duplicateReason:G?.status==="skipped"?G.reason:null}}})});import{z as vJ}from"zod";var B_$,Z71,Q71,Y71;var O_$=D(()=>{C0();C4();IJ();B_$=vJ.object({columnKey:vJ.string(),prompt:vJ.string().nullable()}),Z71=d({name:"TASK_BOARD_AUTOMATION_LIST",description:"List what the board runs when a card lands in each of its columns. A "+"column with no rule is uneventful \u2014 nothing runs there.",inputSchema:vJ.object({}),outputSchema:vJ.object({automations:vJ.array(B_$)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return{automations:await Z.storage.columnAutomations.listByOrg(Q)}}}),Q71=d({name:"TASK_BOARD_AUTOMATION_UPSERT",description:"Run the agent on every card that lands in a column. Replaces the rule already on that column, if any. Omit `prompt` to use the agent's own instruction; give one to say what it should do there instead. The card's title and description are always included, so the prompt is the instruction, not the whole message.",inputSchema:vJ.object({columnKey:vJ.string().min(1).describe("A column of this board \u2014 see TASK_BOARD_ITEM_LIST."),prompt:vJ.string().max(lc).nullable().optional().describe("What to do with a card landing here; null for the default.")}),outputSchema:vJ.object({automation:B_$}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");if(!oK.some((X)=>X===$.columnKey))throw Error(`This board has no column "${$.columnKey}" \u2014 it has ${oK.join(", ")}`);let Y=$.prompt?.trim()?$.prompt.trim():null;return{automation:await Z.storage.columnAutomations.upsert(Q,$.columnKey,Y)}}}),Y71=d({name:"TASK_BOARD_AUTOMATION_DELETE",description:"Stop running the agent on cards landing in a column. Removing the rule IS the off switch, so a column cannot be configured-but-disabled.",inputSchema:vJ.object({columnKey:vJ.string().min(1)}),outputSchema:vJ.object({removed:vJ.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");return{removed:await Z.storage.columnAutomations.remove(Q,$.columnKey)}}})});import{z as bJ}from"zod";function X71($){let Z=$.organization?.id;if(!Z)throw Error("Organization ID required (no active organization in context)");return Z}var D_$,J71,G71,W71;var L_$=D(()=>{C0();C4();C4();D_$=bJ.object({columnKey:bJ.string().nullable().describe("null for the org-wide prompt; a column key to scope it."),prompt:bJ.string()});J71=d({name:"TASK_BOARD_PROMPT_LIST",description:"List the instructions appended to the system prompt of every agent run started from a card on this board. The org-wide prompt comes first; a prompt with a columnKey applies only to cards in that column.",inputSchema:bJ.object({}),outputSchema:bJ.object({prompts:bJ.array(D_$)}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{prompts:await Z.storage.taskBoardPrompts.listByOrg(X71(Z))}}}),G71=d({name:"TASK_BOARD_PROMPT_UPSERT",description:"Set the instructions appended to the system prompt of agent runs started "+"from this board's cards \u2014 house rules for the work (conventions, tools "+"to prefer, what never to touch), not what to do with one card. Replaces whatever was on that scope. Omit columnKey for the whole board.",annotations:{readOnlyHint:!1,idempotentHint:!0},inputSchema:bJ.object({columnKey:bJ.string().min(1).nullable().optional().describe("A column of this board (see TASK_BOARD_ITEM_LIST) to scope the prompt to. Omit or null for every card on the board."),prompt:bJ.string().min(1).max(UF$)}),outputSchema:bJ.object({prompt:D_$}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=X71(Z),Y=$.columnKey??null;if(Y!==null){if(!oK.some((X)=>X===Y))throw Error(`This board has no column "${Y}" \u2014 it has ${oK.join(", ")}`)}return{prompt:await Z.storage.taskBoardPrompts.upsert(Q,Y,$.prompt.trim())}}}),W71=d({name:"TASK_BOARD_PROMPT_DELETE",description:"Clear a board prompt. Deleting IS the off switch, so a prompt cannot be set-but-inactive. Omit columnKey to clear the org-wide one.",annotations:{readOnlyHint:!1,idempotentHint:!0},inputSchema:bJ.object({columnKey:bJ.string().min(1).nullable().optional()}),outputSchema:bJ.object({removed:bJ.boolean()}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{removed:await Z.storage.taskBoardPrompts.remove(X71(Z),$.columnKey??null)}}})});import{z as I10}from"zod";var Ze4=8000,K71;var w_$=D(()=>{C0();z7();K71=d({name:"TASK_BOARD_PREVIEW_PROBE",description:"Check whether a PR's deploy preview URL is currently reachable, so the UI can enable or block its 'Open preview' button.",annotations:{title:"Probe Deploy Preview",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:I10.object({url:I10.string().url()}),outputSchema:I10.object({available:I10.boolean(),status:I10.number().nullable()}),handler:async({url:$},Z)=>{if(a(Z),await Z.access.check(),!ex($))return{available:!1,status:null};try{let Q=await fetch($,{method:"GET",redirect:"manual",signal:AbortSignal.timeout(Ze4)});return await Q.body?.cancel().catch(()=>{}),{available:Q.status<400,status:Q.status}}catch{return{available:!1,status:null}}}})});function E_$($){j_$=$}function WR0($){j_$?.broadcast($)}var j_$=null;import{DBOS as KR0}from"@dbos-inc/dbos-sdk";function Qe4($,Z){let Q=`thread-run:${Z}:`;if(!$.workflowID.startsWith(Q))return null;let Y=$.input?.[0],X=Y?.request;return{workflowId:$.workflowID,messageId:X?.messageId??$.workflowID.slice(Q.length),status:$.status==="PENDING"?"running":"queued",enqueuedAt:$.createdAt,...Y?.source!==void 0?{source:Y.source}:{}}}async function H71($){return(await KR0.listWorkflows({workflow_id_prefix:`thread-run:${$}:`,status:["PENDING","ENQUEUED"],loadInput:!0,loadOutput:!1})).map((Q)=>Qe4(Q,$)).filter((Q)=>Q!==null).sort((Q,Y)=>Q.enqueuedAt-Y.enqueuedAt)}async function z_$($,Z){if(!Z.startsWith(`thread-run:${$}:`))return!1;return await KR0.cancelWorkflows([Z]),!0}async function bm($){let Z=await KR0.listWorkflows({workflow_id_prefix:`thread-run:${$}:`,status:["PENDING"],loadInput:!1,loadOutput:!1});if(Z.length===0)return;await KR0.cancelWorkflows(Z.map((Q)=>Q.workflowID))}var HR0=()=>{};function Xe4($,Z={}){if($==="failing")return!0;if($==="pending")return!Z.allowPendingChecks;return!1}async function Je4($,Z,Q,Y,X){if(Ye4.has(Y))return;let G=(await $.storage.taskBoard.listActivity(Q,Z).catch(()=>[])).at(-1);if(G?.action==="merge_failed"&&G.data?.reason===Y)return;await o6($,{taskBoardItemId:Q,action:"merge_failed",actorId:null,data:{reason:Y,...X?{detail:X}:{}}})}async function V10($,Z,Q,Y={}){let X=async(N,B)=>{return await Je4($,Z,Q,N,B),{merged:!1,reason:N,...B?{detail:B}:{}}},J=await $.storage.taskBoard.listPrs(Q,Z),G=await $f($,Z,J);if(!G)return console.warn(`[task-board] merge skipped \u2014 no linked PR on ${Q}`),X("no_pr");let W=await kV$($,Z,G);if(Xe4(W,Y))return console.warn(`[task-board] merge blocked \u2014 checks ${W} on PR #${G.number}`),X(W==="failing"?"checks_failing":"checks_pending");let K=a00(G),H=K.repo.path,F=await Ec($,Z,K).catch((N)=>{return console.error(`[task-board] merge blocked \u2014 ${H}:`,N),null});if(!F)return console.warn(`[task-board] merge blocked \u2014 no credential for ${H} (#${G.number})`),X("no_connection",H);let U=await F.merge(G.number);if(U.merged)return await Promise.all([IV$(J10(G)),aG(Z)]),{merged:!0};if(U.reason==="rate_limited")console.warn(`[task-board] merge rate-limited on #${G.number} \u2014 sweep retries`);else console.error(`[task-board] merge refused (${U.reason}) on ${H}#${G.number}:`,U.detail);return X(Ge4(U),U.detail.slice(0,500))}function Ge4($){switch($.reason){case"conflict":return"conflict";case"rate_limited":return"rate_limited";case"not_found":return"no_pr";case"blocked":return"refused";default:return"error"}}async function k10($,Z,Q){let Y=await $.storage.organizationSettings.get(Z),X=kB(Y?.flags),J=await $.storage.taskBoard.listActivity(Q,Z),G=await $.storage.taskBoard.getById(Q,Z);return fw(J,X,{cycleStartedAt:G?.reviewCycleStartedAt??null,verifiedOnly:!0})}async function We4($,Z){let Q=await $.storage.organizationSettings.get(Z.organizationId),Y=kB(Q?.flags),X=await $.storage.taskBoard.listActivity(Z.id,Z.organizationId);if(!GF$(X,Y,{cycleStartedAt:Z.reviewCycleStartedAt}))return;await KH($,Z,"every reviewer approved, but an approval could not be verified \u2014 "+"auto-merge is blocked and no reviewer can be re-dispatched this cycle")}function F71($){if($===null||$.merged)return null;return $.reason==="conflict"?!0:null}async function Ke4($,Z,Q){let Y=F71(Q);if(Y!==!0)return;let X=Z.organizationId,J=await $.storage.taskBoard.listPrs(Z.id,X),G=await $f($,X,J);if(!G)return;await _j($,X,Z,{pr:{number:G.number,url:G.url},conflict:Y}).catch((W)=>{console.error("[task-board] sweep conflict auto-resolve failed",W)})}async function P_$($,Z){let Q=Z.organizationId;if(!VX(Z))return!1;let Y=await $.storage.organizationSettings.get(Q);if(Y?.flags?.auto_merge!==!0)return!1;if(await $.storage.taskBoard.hasHumanRejectedDone(Z.id,Q))return!1;if(!await k10($,Q,Z.id))return await We4($,Z),!1;let X=await V10($,Q,Z.id);if(!X.merged)return await Ke4($,Z,X),!1;let J=oF(Y?.flags),G=await $.storage.taskBoard.update(Z.id,Q,{status:J},Z.updatedBy);return await o6($,{taskBoardItemId:Z.id,action:"status_changed",actorId:null,data:{from:Z.status,to:J}}),E8(Q,G),!0}var Ye4;var S10=D(()=>{iZ();C4();_Y();zm();tx();z7();WH();V9();Ye4=new Set(["checks_pending"])});import{z as xm}from"zod";function Fe4($){return $.threads.filter((Z)=>Z.status!==null&&!s00.has(Z.status)).map((Z)=>Z.threadId)}async function Ue4($,Z,Q){let Y=(J)=>(G)=>console.error("[task-board] rerun takeover step failed",{threadId:Z,step:J,err:G});await $.storage.threads.setCancelRequested(Z,Q).catch(Y("cancel-flag")),await Sm(Z).catch(Y("background-jobs")),await bm(Z).catch(Y("gate-head"));let X=await $.storage.threads.getRunFence(Z).catch(()=>null);if(X)await Kf(Z,X).catch(Y("hosted-harness"));WR0(Z)}function Ne4($,Z){return $===!0&&R91(Z)}async function Be4($,Z,Q){let Y=Z.organizationId,X=await $.storage.taskBoard.listPrs(Z.id,Y).catch(()=>[]),J=await $f($,Y,X).catch(()=>{return});if(!J)return!1;let G=await zT0($,Y,J).catch(()=>null);return Ne4(G,Q)}function De4($,Z,Q){let Y=SB($,Q),X=0;for(let J of $){if(J.action!=="review_approved")continue;let G=new Date(J.occurredAt).getTime();if(G>=Y)X=Math.max(X,G)}return Z-X>=Oe4}async function Le4($,Z){if(!VX(Z))return;if((await $.storage.organizationSettings.get(Z.organizationId))?.flags?.auto_merge!==!0)return;if(!await k10($,Z.organizationId,Z.id))return;let X=await $.storage.taskBoard.listActivity(Z.id,Z.organizationId).catch(()=>[]);if(De4(X,Date.now(),Z.reviewCycleStartedAt))return;if(await Be4($,Z,X))return;throw Error("Every reviewer approved this task and its merge is retrying \u2014 re-running "+"would throw that away and start a new review cycle. Wait for the merge, or use the ship button if the PR needs a nudge.")}async function FR0($,Z){let Q=[];for(let Y of Fe4(Z)){if(!await $.storage.threads.failIfNotTerminal(Y,He4,"superseded"))continue;Q.push(Y),await Ue4($,Y,Z.organizationId)}return Q}var He4="Superseded by a manual re-run of this task",Oe4=900000,U71;var N71=D(()=>{C0();C4();YO();WH();QO();HR0();Cm();_Y();V9();wU();S10();z7();zm();FW();U71=d({name:"TASK_BOARD_ITEM_RERUN",description:"Re-run a task board item with the Super Agent, whatever lane it is in. Use this to retry a task that stalled, finished without doing the job, or is already assigned to the Super Agent (in which case re-assigning it does nothing). Fails any run still holding the task open, moves it to In Progress, and queues a fresh run.",annotations:{title:"Re-run Task",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:xm.object({id:xm.string().describe("The task board item to re-run.")}),outputSchema:xm.object({status:xm.string().describe("The task's lane after the re-run was queued."),supersededThreadIds:xm.array(xm.string()).describe("Runs that were failed to make room for this one.")}),handler:async({id:$},Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.taskBoard.getById($,Q);if(!Y)throw Error(`Task board item not found: ${$}`);if(Y.assigneeId!==j8)throw Error("Only a task assigned to the Super Agent can be re-run. Assign it to "+"the Super Agent instead \u2014 that queues a run by itself.");await Le4(Z,Y),await Jc(Z,Y,hw());let X=await FR0(Z,Y);await Z.storage.taskBoard.closeReviewCycle($,Q);let J=T$.progress,G=J?await Z.storage.taskBoard.update($,Q,{status:J},p0(Z)):Y;return await o6(Z,{taskBoardItemId:$,action:"status_changed",actorId:p0(Z),data:{from:Y.status,to:"in_progress",reason:"rerun"}}),E8(Q,G),await HH(Z,G,{userInitiated:!0}),{status:G.status,supersededThreadIds:X}}})});import{z as UR0}from"zod";var B71;var A_$=D(()=>{C0();C4();OT0();B71=d({name:"TASK_BOARD_RUN_REVIEWER",description:"Run the Reviewer on a task board item even when the organization has automated review turned off. Use this for a task whose Super Agent run finished and whose pull request nobody reviewed. Does nothing if a reviewer is already working this review cycle.",annotations:{title:"Run Reviewer",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0},inputSchema:UR0.object({id:UR0.string().describe("The task board item to review.")}),outputSchema:UR0.object({queued:UR0.boolean().describe("False when a reviewer already holds this review cycle, so nothing was dispatched.")}),handler:async({id:$},Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.taskBoard.getById($,Q);if(!Y)throw Error(`Task board item not found: ${$}`);if((await Z.storage.taskBoard.listPrs($,Q)).length===0)throw Error("This task has no pull request to review yet. Wait for the Super Agent to open one.");if(z91(Y,Date.now()))throw Error("The Super Agent is still working this task \u2014 wait for its run to "+"finish before asking for a review.");return{queued:(await Em(Z,Y,{kinds:HW})).length>0}}})});import{z as C10}from"zod";var O71;var T_$=D(()=>{C4();C0();FW();_Y();V9();wU();z7();O71=d({name:"TASK_BOARD_RESOLVE_CONFLICT",description:"Hand a task's pull request back to the Super Agent to resolve a merge conflict with its base branch. Use when a reviewed PR can't be shipped because it conflicts. Bounces the task to In Progress and queues a run that checks out the existing PR's branch, merges the base, resolves the conflicts, and pushes to the same PR.",annotations:{title:"Resolve Merge Conflict",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:C10.object({id:C10.string().describe("The task board item whose PR conflicts."),prNumber:C10.number().describe("The conflicting pull request's number, linked to this task.")}),outputSchema:C10.object({status:C10.string().describe("The task's lane after the resolution run was queued.")}),handler:async({id:$,prNumber:Z},Q)=>{a(Q),await Q.access.check();let Y=Q.organization?.id;if(!Y)throw Error("Organization ID required (no active organization in context)");let X=await Q.storage.taskBoard.getById($,Y);if(!X)throw Error(`Task board item not found: ${$}`);let G=(await Q.storage.taskBoard.listPrs($,Y)).find((H)=>H.number===Z);if(!G)throw Error(`Pull request #${Z} is not linked to this task.`);if(await zT0(Q,Y,G).catch(()=>null)!==!0)throw Error("This pull request no longer has a merge conflict \u2014 refresh and try again.");if(await Jc(Q,X,hw()),T$.review===null||T$.progress===null)throw Error("This board has no column meaning 'under review' or 'in progress', so there is nowhere to move the card while the conflict is resolved. Set those roles on the board's columns first.");let K=await Q.storage.taskBoard.claimConflictResolution($,Y,p0(Q));if(!K)throw Error("Couldn't start conflict resolution \u2014 the task may have moved, been "+"reassigned, or already be resolving. Refresh and try again.");E8(Y,K);try{await HH(Q,K,{pr:{number:G.number,url:G.url},resolveConflict:!0,runClass:"retry",userInitiated:!0})}catch(H){throw await Q.storage.taskBoard.update(K.id,Y,{status:T$.review},"system").then((F)=>E8(Y,F)).catch((F)=>console.error("[task-board] resolve-conflict status revert failed",F)),H}return await o6(Q,{taskBoardItemId:$,action:"merge_conflict_resolution",actorId:null,data:{prNumber:G.number}}),{status:K.status}}})});function je4($,Z){let Q=$.filter((Y)=>Y.threadId===Z&&Y.body.trim().length>=we4);if(Q.length===0)return"missing";return Q.some((Y)=>R_$(Y.body))?null:"no_screenshots"}function R_$($){return $.includes("![")||$.includes(aa)}function Ee4($){return R_$($)?null:"no_screenshots"}function ze4($,Z,Q){let Y=Z==="approve"?"approved":"requested changes";return`**${tF[$]}** ${Y}:
|
|
1712
1712
|
|
|
1713
1713
|
${Q.trim()}`}function Pe4($){return[`Your ${tF[$]} comment carries no screenshots and does not declare the change free of any visual surface. One of the two is required \u2014 a pass on a visual change nobody can SEE is not a pass.`,"","Do exactly ONE thing in this run and then stop:","- Post a comment with `TASK_BOARD_COMMENT_CREATE` carrying the before/after screenshots you captured, embedded as markdown images referencing their `org/output/...` path, each pair in a two-column table.","- If the change genuinely has none, or you could not capture it (no deploy preview, the page would not render), write the exact words `"+aa+"` in the comment instead, followed by one sentence naming why. That literal is what the check looks for \u2014 no paraphrase and no translation of it counts.","- Do NOT re-run the review, do NOT call `TASK_BOARD_REVIEW_DECISION` again (your verdict is already recorded), and do NOT change any code.","- If you have already posted such a comment, do nothing and say so."].join(`
|
|
1714
|
-
`)}async function q_$($,Z,Q,Y,X){let J=await $.storage.taskBoard.listComments(Z.id,Z.organizationId),G=je4(J,Y);if(!G)return;if(G==="missing"){let K=ze4(Q,X.decision,X.notes);if(await $.storage.taskBoard.createComment({taskBoardItemId:Z.id,organizationId:Z.organizationId,authorId:j8,threadId:Y,body:K}),console.warn(`[task-board] ${Q} reviewer on ${Z.id} recorded no comment \u2014 `+"mirrored its verdict notes"),G=Ee4(K),!G)return}let W=await $.storage.threads.get(Y);if(!W||W.message_storage_version!==2)return;console.warn(`[task-board] reviewer on ${Z.id} showed no visual evidence \u2014 `+"asking for it"),await Nm($,Z,W,{messageId:`review-comment-${Y}`,prompt:Pe4(Q),workflowID:`review-comment:${Y}`,runClass:"reviewer"})}var we4=80;var M_$=D(()=>{C4();o20()});import{z as yj}from"zod";function Te4($,Z,Q){return $!==null&&$.reviewer===Z&&$.cycleAt.getTime()===Q}function Re4($,Z,Q){return gw($,{cycleStartedAt:Q}).get(Z)==="changes_requested"}var Ae4=50000,D71;var I_$=D(()=>{C0();C4();IJ();_Y();V9();S10();z7();E91();zm();FW();M_$();tB();D71=d({name:"TASK_BOARD_REVIEW_DECISION",description:"Record a reviewer's decision for a task under review. `approve` marks the pull request approved by that reviewer (and, once EVERY enabled reviewer has approved, merges it when the org enabled auto-merge, advancing the task to Done); `request_changes` records your notes and hands the task to "+"a human \u2014 review is single-pass, so it is not sent back to the Super Agent.",annotations:{title:"Review Decision",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:yj.object({taskBoardItemId:yj.string(),reviewer:yj.enum(["reviewer","qa","code_review"]).describe("Which reviewer you are \u2014 pass `reviewer`."),reviewToken:yj.string().optional().describe("The reviewToken from your prompt \u2014 proves you are this reviewer. "+"Pass it through exactly; an approval without a valid token is recorded but does NOT count toward an automatic merge."),decision:yj.enum(["approve","request_changes"]),notes:yj.string().min(1).max(Ae4).describe("For approve: a short summary of what you verified. For request_changes: specific, actionable feedback the Super Agent must address.")}),outputSchema:yj.object({status:oB,merged:yj.boolean().describe("True when this approval completed the review and merged the PR.")}),handler:async({taskBoardItemId:$,reviewer:Z,reviewToken:Q,decision:Y,notes:X},J)=>{a(J),await J.access.check();let W=J.organization?.id;if(!W)throw Error("Organization ID required (no active organization in context)");let K=await J.storage.taskBoard.getById($,W);if(!K)throw Error(`Task board item not found: ${$}`);let H=Q?SB(K.reviewCycleStartedAt?[]:await J.storage.taskBoard.listActivity($,W),K.reviewCycleStartedAt):0,F=!!Q&&(BV$(Q,$,Z,new Date(H))||Te4(await J.storage.taskBoard.resolveReviewClaimByToken($,Q),Z,H)),U=nG.getStore()?.threadId;if(U)await q_$(J,K,"reviewer",U,{decision:Y,notes:X}).catch((T)=>console.error("[task-board] reviewer comment record failed",T));if(Y==="request_changes"){let T=await J.storage.taskBoard.listActivity($,W);if(Re4(T,"reviewer",K.reviewCycleStartedAt))return{status:K.status,merged:!1};return await o6(J,{taskBoardItemId:$,action:"review_changes_requested",actorId:null,data:{reviewer:"reviewer",notes:X,verified:F}}),await KH(J,K,`${tF.reviewer} requested changes \u2014 review is single-pass`),{status:(await J.storage.taskBoard.getById($,W)??K).status,merged:!1}}if(await o6(J,{taskBoardItemId:$,action:"review_approved",actorId:null,data:{reviewer:"reviewer",notes:X,verified:F}}),await u91(J,K),!await k10(J,W,$)){let T=await J.storage.taskBoard.getById($,W)??K;return E8(W,T),{status:T.status,merged:!1}}let B=await J.storage.organizationSettings.get(W),O=B?.flags?.auto_merge===!0,L=await J.storage.taskBoard.hasHumanRejectedDone($,W),w=O&&!L,j=w?await V10(J,W,$):null;if(j?.merged===!0){let T=oF(B?.flags),P=await J.storage.taskBoard.getById($,W)??K,A=await J.storage.taskBoard.update($,W,{status:T},K.updatedBy);return await o6(J,{taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:P.status,to:T}}),E8(W,A),{status:A.status,merged:!0}}let z=await J.storage.taskBoard.getById($,W)??K;if(w){let T=await J.storage.taskBoard.listPrs($,W),P=await $f(J,W,T);if(P?await _j(J,W,z,{pr:{number:P.number,url:P.url},conflict:F71(j)}).catch((q)=>{if(q instanceof zX)throw q;return console.error("[task-board] conflict auto-resolve failed",q),!1}):!1)return{status:(await J.storage.taskBoard.getById($,W)??z).status,merged:!1}}return E8(W,z),{status:z.status,merged:!1}}})});import{z as NR0}from"zod";function qe4($,Z,Q,Y){if(!FV$.has($))return!1;return Q.length===0||fw(Z,Q,{cycleStartedAt:Y})}var L71;var V_$=D(()=>{C0();C4();IJ();WH();_Y();V9();S10();L71=d({name:"TASK_BOARD_PROMOTE_TO_PRODUCTION",description:"Ship a reviewed task: merge its open pull request and move the task to Merged (or Done, on a board without the delivery lanes). Used by the board's 'Ship to production' button after the enabled reviewers approved, when auto-merge is off (a human does the final merge).",annotations:{title:"Ship to Production",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:NR0.object({taskBoardItemId:NR0.string()}),outputSchema:NR0.object({status:oB,merged:NR0.boolean().describe("True when the PR was merged.")}),handler:async({taskBoardItemId:$},Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.taskBoard.getById($,Q);if(!Y)throw Error(`Task board item not found: ${$}`);let X=await Z.storage.organizationSettings.get(Q),J=kB(X?.flags),G=await Z.storage.taskBoard.listActivity($,Q);if(!qe4(Y.status,G,J,Y.reviewCycleStartedAt))throw Error("Task is not ready to ship: it must be In Review or Approved with every enabled reviewer approved");if(!(await V10(Z,Q,$,{allowPendingChecks:!0})).merged){let F=await Z.storage.taskBoard.getById($,Q)??Y;return E8(Q,F),{status:Y.status,merged:!1}}let K=oF(X?.flags),H=await Z.storage.taskBoard.update($,Q,{status:K},Y.updatedBy);if(Y.status!==K)await o6(Z,{taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:Y.status,to:K}});return E8(Q,H),{status:H.status,merged:!0}}})});import{z as AW}from"zod";function k_$($){if(!$)throw Error("Organization ID required (no active organization in context)");return $}var Me4,w71,j71;var S_$=D(()=>{C0();Me4=AW.object({externalKey:AW.string(),dismissedBy:AW.string(),dismissedAt:AW.string()});w71=d({name:"TASK_BOARD_DISMISSED_LIST",description:"List the diagnostic findings this organization has dismissed by deleting their task board cards. The import skips these until they're restored.",annotations:{title:"List Dismissed Findings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:AW.object({}),outputSchema:AW.object({findings:AW.array(Me4)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=k_$(Z.organization?.id);return{findings:await Z.storage.taskBoard.listDismissedFindings(Q)}}}),j71=d({name:"TASK_BOARD_DISMISSED_RESTORE",description:"Un-dismiss diagnostic findings, returning their cards to the board. Omit externalKeys to restore every dismissed finding.",annotations:{title:"Restore Dismissed Findings",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:AW.object({externalKeys:AW.array(AW.string()).max(1000).optional()}),outputSchema:AW.object({restored:AW.number()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=k_$(Z.organization?.id);return{restored:await Z.storage.taskBoard.restoreDismissedFindings(Q,$.externalKeys)}}})});import{z as q5}from"zod";function BR0($){let Z=$.organization?.id;if(!Z)throw Error("Organization ID required (no active organization in context)");return Z}function Ve4($,Z,Q){return $.replace(Ie4,(Y,X,J,G)=>{let W=encodeURIComponent(`${Z}/${J}`);return`${X}/api/${encodeURIComponent(Q)}/fs/outputs/read?path=${W}${G}`})}var C_$=50000,E71,z71,Ie4,P71,A71,T71;var __$=D(()=>{C0();C4();tB();E71=q5.object({id:q5.string(),taskBoardItemId:q5.string(),parentId:q5.string().nullable(),authorId:q5.string(),threadId:q5.string().nullable().optional(),body:q5.string(),resolved:q5.boolean(),createdAt:q5.string(),updatedAt:q5.string()});z71=d({name:"TASK_BOARD_COMMENT_LIST",description:"List a task board item's comments (flat, oldest first; replies carry parentId).",annotations:{title:"List Task Comments",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q5.object({taskBoardItemId:q5.string()}),outputSchema:q5.object({comments:q5.array(E71)}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{comments:await Z.storage.taskBoard.listComments($.taskBoardItemId,BR0(Z))}}}),Ie4=/(!\[[^\]]*\]\()org\/output\/([^)\s]+)(\))/g;P71=d({name:"TASK_BOARD_COMMENT_CREATE",description:"Post a comment on a task board item, or a reply to one.",annotations:{title:"Create Task Comment",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:q5.object({taskBoardItemId:q5.string(),body:q5.string().trim().min(1).max(C_$),parentId:q5.string().nullish()}),outputSchema:q5.object({comment:E71}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=BR0(Z),Y=nG.getStore(),X=Z.organization?.slug,J=Y?.threadId&&X?Ve4($.body,Y.threadId,X):$.body,G=await Z.storage.taskBoard.createComment({taskBoardItemId:$.taskBoardItemId,organizationId:Q,parentId:$.parentId??null,authorId:Y?j8:p0(Z),threadId:Y?.threadId??null,body:J});if(!G)throw Error("Task board item not found");return await Z.storage.notifications.notify({taskBoardItemId:G.taskBoardItemId,type:"commented",actorId:Y?null:p0(Z),alsoSubscribe:Y?[]:[p0(Z)]}),await Z.storage.notifications.notifyMentions({taskBoardItemId:G.taskBoardItemId,organizationId:Q,actorId:Y?null:p0(Z),body:G.body}),{comment:G}}}),A71=d({name:"TASK_BOARD_COMMENT_UPDATE",description:"Edit your own comment's body, or resolve/unresolve a comment thread (root only, any org member may toggle it).",annotations:{title:"Update Task Comment",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q5.object({id:q5.string(),body:q5.string().trim().min(1).max(C_$).optional(),resolved:q5.boolean().optional()}),outputSchema:q5.object({comment:E71}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=BR0(Z),Y=$.body!==void 0?await Z.storage.taskBoard.getComment($.id,Q):null,X=await Z.storage.taskBoard.updateComment({id:$.id,organizationId:Q,callerId:p0(Z),body:$.body,resolved:$.resolved});if(!X)throw Error("Comment not found, or you can only edit your own comments");if($.body!==void 0&&X.body!==Y?.body)await Z.storage.notifications.notifyMentions({taskBoardItemId:X.taskBoardItemId,organizationId:Q,actorId:p0(Z),body:X.body,previousBody:Y?.body??null});return{comment:X}}}),T71=d({name:"TASK_BOARD_COMMENT_DELETE",description:"Delete your own comment. Deleting a thread root deletes its replies too.",annotations:{title:"Delete Task Comment",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q5.object({id:q5.string()}),outputSchema:q5.object({success:q5.boolean()}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{success:await Z.storage.taskBoard.deleteComment($.id,BR0(Z),p0(Z))}}})});var v_$=D(()=>{cE$();n91();m91();RT0();i91();O_$();L_$();z7();w_$();N71();A_$();T_$();I_$();V_$();_Y();S_$();__$();MT0()});function _10($){let Z=$.organization?.id;if(!Z)throw Error("Organization ID required (no active organization in context)");return Z}async function R71($,Z){let Q=_10($);if(!await $.storage.taskBoard.getById(Z,Q))throw Error("Task board item not found");return Q}import{z as vY}from"zod";var Se4,b_$;var x_$=D(()=>{C0();s20();Se4=vY.object({id:vY.string(),taskBoardItemId:vY.string(),type:vY.enum(r20),taskTitle:vY.string(),taskKeySeq:vY.number().nullable(),actorName:vY.string().nullable(),actorImage:vY.string().nullable(),createdAt:vY.string()}),b_$=d({name:"NOTIFICATION_LIST",description:"List the current user's unread notifications in the current organization, newest first.",annotations:{title:"List Notifications",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:vY.object({cursor:vY.string().optional(),limit:vY.number().int().positive().max(50).optional()}),outputSchema:vY.object({notifications:vY.array(Se4),unreadCount:vY.number(),nextCursor:vY.string().nullable()}),handler:async($,Z)=>{a(Z),await Z.access.check();let{notifications:Q,unreadCount:Y,nextCursor:X}=await Z.storage.notifications.listUnread(p0(Z),_10(Z),{cursor:$.cursor,limit:$.limit});return{notifications:Q.map((J)=>({id:J.id,taskBoardItemId:J.taskBoardItemId,type:J.type,taskTitle:J.data.taskTitle,taskKeySeq:J.data.taskKeySeq,actorName:J.data.actorName,actorImage:J.data.actorImage,createdAt:J.createdAt})),unreadCount:Y,nextCursor:X}}})});import{z as v10}from"zod";var f_$;var y_$=D(()=>{C0();f_$=d({name:"NOTIFICATION_MARK_READ",description:"Mark notifications read. Omit `ids` to mark all of the current user's unread ones in this organization.",annotations:{title:"Mark Notifications Read",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:v10.object({ids:v10.array(v10.string()).max(1000).optional()}),outputSchema:v10.object({marked:v10.number()}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{marked:await Z.storage.notifications.markRead(p0(Z),_10(Z),$.ids)}}})});import{z as zU}from"zod";var g_$,h_$;var u_$=D(()=>{C0();g_$=d({name:"NOTIFICATION_SUBSCRIPTION_SET",description:"Follow or unfollow a task board item.",annotations:{title:"Set Notification Subscription",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:zU.object({taskBoardItemId:zU.string(),subscribed:zU.boolean()}),outputSchema:zU.object({subscribed:zU.boolean()}),handler:async($,Z)=>{return a(Z),await Z.access.check(),await R71(Z,$.taskBoardItemId),await Z.storage.notifications.setSubscribed(p0(Z),$.taskBoardItemId,$.subscribed),{subscribed:$.subscribed}}}),h_$=d({name:"NOTIFICATION_SUBSCRIPTION_LIST",description:"List the user ids following a task board item.",annotations:{title:"List Notification Subscribers",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:zU.object({taskBoardItemId:zU.string()}),outputSchema:zU.object({userIds:zU.array(zU.string())}),handler:async($,Z)=>{return a(Z),await Z.access.check(),await R71(Z,$.taskBoardItemId),{userIds:await Z.storage.notifications.listSubscribers($.taskBoardItemId)}}})});var l_$=D(()=>{x_$();y_$();u_$()});import{z as KO}from"zod";var q71;var c_$=D(()=>{C0();q71=d({name:"TAGS_LIST",description:"List all tags available in the organization.",annotations:{title:"List Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:KO.object({}),outputSchema:KO.object({tags:KO.array(KO.object({id:KO.string(),organizationId:KO.string(),name:KO.string(),color:KO.string().nullable(),createdAt:KO.string().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return{tags:(await Z.storage.tags.listOrgTags(Q.id)).map((X)=>({...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():String(X.createdAt)}))}}})});import{z as PU}from"zod";var M71;var m_$=D(()=>{C0();M71=d({name:"TAGS_CREATE",description:"Create a new tag, usable on organization members and task board items.",annotations:{title:"Create Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:PU.object({name:PU.string().min(1).max(50).describe("Tag name"),color:PU.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional().describe('Hex color the tag renders its dot with, e.g. "#3b82f6"')}),outputSchema:PU.object({tag:PU.object({id:PU.string(),organizationId:PU.string(),name:PU.string(),color:PU.string().nullable(),createdAt:PU.string().describe("ISO 8601 timestamp")})}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.tags.createTag(Q.id,$.name,$.color);return{tag:{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():String(Y.createdAt)}}}})});import{z as OR0}from"zod";var I71;var d_$=D(()=>{C0();I71=d({name:"TAGS_DELETE",description:"Delete a tag and automatically remove it from all assigned members.",annotations:{title:"Delete Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:OR0.object({tagId:OR0.string().describe("Tag ID to delete")}),outputSchema:OR0.object({success:OR0.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.tags.getTag($.tagId);if(!Y)throw Error("Tag not found");if(Y.organizationId!==Q.id)throw Error("Tag does not belong to this organization");return await Z.storage.tags.deleteTag($.tagId),{success:!0}}})});import{z as AU}from"zod";var V71;var i_$=D(()=>{C0();V71=d({name:"MEMBER_TAGS_GET",description:"Get all tags currently assigned to a specific member.",annotations:{title:"Get Member Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:AU.object({memberId:AU.string().describe("Member ID")}),outputSchema:AU.object({tags:AU.array(AU.object({id:AU.string(),organizationId:AU.string(),name:AU.string(),color:AU.string().nullable(),createdAt:AU.string().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);if(!await Z.storage.tags.verifyMemberOrg($.memberId,Q.id))throw Error(`Member not found in this organization: ${$.memberId}`);return{tags:(await Z.storage.tags.getMemberTags($.memberId)).map((J)=>({...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}))}}})});import{z as TW}from"zod";var k71;var p_$=D(()=>{C0();k71=d({name:"MEMBER_TAGS_SET",description:"Replace all tags on a member with the given set. Pass empty array to clear.",annotations:{title:"Set Member Tags",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:TW.object({memberId:TW.string().describe("Member ID"),tagIds:TW.array(TW.string()).max(1000).describe("Array of tag IDs to assign")}),outputSchema:TW.object({success:TW.boolean(),tags:TW.array(TW.object({id:TW.string(),organizationId:TW.string(),name:TW.string(),createdAt:TW.string().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);if(!await Z.storage.tags.verifyMemberOrg($.memberId,Q.id))throw Error(`Member not found in this organization: ${$.memberId}`);let X=await Z.storage.tags.getTagsByIds($.tagIds),J=new Map(X.map((W)=>[W.id,W]));for(let W of $.tagIds){let K=J.get(W);if(!K)throw Error(`Tag not found: ${W}`);if(K.organizationId!==Q.id)throw Error(`Tag does not belong to this organization: ${W}`)}return await Z.storage.tags.setMemberTags($.memberId,$.tagIds),{success:!0,tags:(await Z.storage.tags.getMemberTags($.memberId)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():String(W.createdAt)}))}}})});var n_$=D(()=>{c_$();m_$();d_$();i_$();p_$()});import{z as HZ}from"zod";var t_$,gj,DR0;var b10=D(()=>{t_$=HZ.object({id:HZ.string().min(1).describe("Arm id, e.g. `control` or `variant-b`."),weight:HZ.number().int().min(0).max(100),role:HZ.enum(["control","treatment"]).nullable().optional()}),gj=HZ.object({id:HZ.string(),organizationId:HZ.string(),site:HZ.string(),key:HZ.string(),name:HZ.string(),status:HZ.enum(["draft","running","paused","ended"]),goals:HZ.array(HZ.string()),variants:HZ.array(t_$),startedAt:HZ.string().nullable(),endedAt:HZ.string().nullable(),createdBy:HZ.string(),createdAt:HZ.string(),updatedAt:HZ.string()}),DR0=HZ.array(t_$).min(1).superRefine(($,Z)=>{let Q=$.reduce((Y,X)=>Y+X.weight,0);if(Q!==100)Z.addIssue({code:HZ.ZodIssueCode.custom,message:`variant weights must sum to 100 (got ${Q})`});if(new Set($.map((Y)=>Y.id)).size!==$.length)Z.addIssue({code:HZ.ZodIssueCode.custom,message:"variant ids must be unique"})})});async function o_$($,Z,Q){let X=(await $.storage.virtualMcps.list(Z)).find((J)=>la(J)===Q);if(!X)throw Error("Site not found in organization");return X}async function TU($,Z,Q){await o_$($,Z,Q)}async function r_$($,Z,Q){let Y=await o_$($,Z,Q),X=$H$(Y)??Q;if(X===Q)return Q;return await $.storage.orgSites.isOwnedBy(X,Z)?X:Q}var Ff=D(()=>{fG()});import{z as LR0}from"zod";var S71;var s_$=D(()=>{C0();b10();Ff();S71=d({name:"EXPERIMENT_LIST",description:"List the A/B experiments configured for a site.",annotations:{title:"List Experiments",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:LR0.object({site:LR0.string().min(1).describe("Site slug the experiments belong to.")}),outputSchema:LR0.object({experiments:LR0.array(gj)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return await TU(Z,Q.id,$.site),{experiments:await Z.storage.experiments.listBySite(Q.id,$.site)}}})});import{z as wR0}from"zod";var C71;var a_$=D(()=>{C0();b10();Ff();C71=d({name:"EXPERIMENT_GET",description:"Get one experiment by site + key. Null when it does not exist.",annotations:{title:"Get Experiment",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:wR0.object({site:wR0.string().min(1),key:wR0.string().min(1)}),outputSchema:wR0.object({experiment:gj.nullable()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return await TU(Z,Q.id,$.site),{experiment:await Z.storage.experiments.getByKey(Q.id,$.site,$.key)}}})});import{z as Uf}from"zod";var _71;var e_$=D(()=>{C0();b10();Ff();_71=d({name:"EXPERIMENT_CREATE",description:"Create a draft A/B experiment for a site. `key` must be unique for the site; weights must sum to 100. Does not publish \u2014 it stores the definition; wiring the traffic-split block into the decofile is a separate step.",annotations:{title:"Create Experiment",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:Uf.object({site:Uf.string().min(1),key:Uf.string().trim().min(1).max(120).describe("The random matcher block's name (e.g. `Cross Sell Bag`) \u2014 the deco runtime records the split as `event:props:<that name>`, so results only populate when the key equals it."),name:Uf.string().min(1),goals:Uf.array(Uf.string()).optional(),variants:DR0.optional()}),outputSchema:Uf.object({experiment:gj}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);await TU(Z,Q.id,$.site);let Y=Z.auth.user.id;if(await Z.storage.experiments.getByKey(Q.id,$.site,$.key))throw Error(`An experiment "${$.key}" already exists on ${$.site}.`);return{experiment:await Z.storage.experiments.create({organizationId:Q.id,site:$.site,key:$.key,name:$.name,goals:$.goals,variants:$.variants,createdBy:Y})}}})});import{z as hj}from"zod";var v71;var $v$=D(()=>{C0();b10();Ff();v71=d({name:"EXPERIMENT_UPDATE",description:"Update an experiment's definition (name, status, goals, variants). Errors when the (site, key) is unknown. When `variants` is present it replaces the full set (weights must sum to 100).",annotations:{title:"Update Experiment",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:hj.object({site:hj.string().min(1),key:hj.string().min(1),name:hj.string().min(1).optional(),status:hj.enum(["draft","running","paused","ended"]).optional(),goals:hj.array(hj.string()).optional(),variants:DR0.optional()}),outputSchema:hj.object({experiment:gj}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);await TU(Z,Q.id,$.site);let Y=await Z.storage.experiments.update(Q.id,$.site,$.key,{name:$.name,status:$.status,goals:$.goals,variants:$.variants});if(!Y)throw Error(`No experiment "${$.key}" on ${$.site}.`);return{experiment:Y}}})});import{z as Nf}from"zod";var b71;var Zv$=D(()=>{C0();Ff();b71=d({name:"EXPERIMENT_DELETE",description:"Delete an experiment (metadata) by site + key. Returns whether a row existed.",annotations:{title:"Delete Experiment",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Nf.object({site:Nf.string().min(1),key:Nf.string().min(1)}),outputSchema:Nf.object({site:Nf.string(),key:Nf.string(),deleted:Nf.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);await TU(Z,Q.id,$.site);let Y=await Z.storage.experiments.delete(Q.id,$.site,$.key);return{site:$.site,key:$.key,deleted:Y}}})});function HO(){let $=E0();return!!($.clickhouseAnalyticsUrl&&$.clickhouseAnalyticsPassword)}async function be4(){if(!jR0){let $=E0();jR0=Promise.resolve().then(() => C(Ni0(),1)).then(({createClient:Z})=>Z({url:$.clickhouseAnalyticsUrl,username:$.clickhouseAnalyticsUsername,password:$.clickhouseAnalyticsPassword,request_timeout:ve4})).catch((Z)=>{throw jR0=null,Z})}return jR0}async function tZ($,Z){if(!HO())return[];return(await(await be4()).query({query:$,query_params:Z,format:"JSONEachRow"})).json()}var jR0=null,ve4=20000;var ER0=D(()=>{F$()});function ye4($){if($.some((Q)=>Q.status==="rejected"))return console.warn("[deco-legacy] a OneDollarStats host query failed"),null;let Z=new Map;for(let Q of $){if(Q.status!=="fulfilled")continue;for(let Y of Q.value){let X=Y.dimensions[0]?.split(" ")[0];if(!X)continue;Z.set(X,(Z.get(X)??0)+(Y.metrics[0]??0))}}return Z}async function Yv$($,Z,Q){let Y=E0().oneDollarStatsApiKey,X=[...new Set($)];if(!Y||X.length===0)return null;let J=async(W)=>{let K=await fetch(`${xe4}/plausible`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":Y,Accept:"application/json"},body:JSON.stringify({site_id:W,date_range:[Z,Q],metrics:["pageviews"],dimensions:["time:day"],pagination:{limit:1e4,offset:0}}),signal:AbortSignal.timeout(fe4)});if(!K.ok)throw Error(`OneDollarStats ${K.status}`);return(await K.json()).results??[]},G=[];for(let W=0;W<X.length;W+=Qv$)G.push(...await Promise.allSettled(X.slice(W,W+Qv$).map(J)));return ye4(G)}function fm($){if($.endsWith(".deco.site")||$.startsWith("www."))return $;return`www.${$}`}var xe4="https://deco.lilstts.com",fe4=1e4,Qv$=6;var zR0=D(()=>{F$()});function ge4($,Z=0,Q=1){let Y=($-Z)/(Q*Math.SQRT2),X=1/(1+0.3275911*Math.abs(Y)),J=1-((((1.061405429*X-1.453152027)*X+1.421413741)*X-0.284496736)*X+0.254829592)*X*Math.exp(-Y*Y);return 0.5*(1+(Y>=0?J:-J))}function x10($){return $.successes/$.total}function Xv$($){let Z=x10($);return Math.sqrt(Z*(1-Z)/$.total)}function Jv$($,Z){let Q=-(x10(Z)-x10($))/Math.sqrt(Xv$($)**2+Xv$(Z)**2),Y=1-ge4(Q,0,1);return Number.isFinite(Y)?Y:0}function Gv$($,Z,Q=0.03){if($.total<1000||$.successes===0)return null;let Y=Z.total/$.total,X=x10($),J=Math.max(X*(1+Q),x10(Z)),G=(X+Y*J)/(Y+1),W=1.644853*Math.sqrt((Y+1)*G*(1-G))+0.8416*Math.sqrt(Y*X*(1-X)+J*(1-J)),K=J-X,H=(W/K)**2/Y,F=1+Math.sqrt(1+2*(Y+1)/(H*Y*Math.abs(X-J))),U=H*F**2/4;return Math.ceil(U)*(1+Y)}async function ce4($,Z,Q){let Y=await tZ(`SELECT host
|
|
1714
|
+
`)}async function q_$($,Z,Q,Y,X){let J=await $.storage.taskBoard.listComments(Z.id,Z.organizationId),G=je4(J,Y);if(!G)return;if(G==="missing"){let K=ze4(Q,X.decision,X.notes);if(await $.storage.taskBoard.createComment({taskBoardItemId:Z.id,organizationId:Z.organizationId,authorId:j8,threadId:Y,body:K}),console.warn(`[task-board] ${Q} reviewer on ${Z.id} recorded no comment \u2014 `+"mirrored its verdict notes"),G=Ee4(K),!G)return}let W=await $.storage.threads.get(Y);if(!W||W.message_storage_version!==2)return;console.warn(`[task-board] reviewer on ${Z.id} showed no visual evidence \u2014 `+"asking for it"),await Nm($,Z,W,{messageId:`review-comment-${Y}`,prompt:Pe4(Q),workflowID:`review-comment:${Y}`,runClass:"reviewer"})}var we4=80;var M_$=D(()=>{C4();o20()});import{z as yj}from"zod";function Te4($,Z,Q){return $!==null&&$.reviewer===Z&&$.cycleAt.getTime()===Q}function Re4($,Z,Q){return gw($,{cycleStartedAt:Q}).get(Z)==="changes_requested"}var Ae4=50000,D71;var I_$=D(()=>{C0();C4();IJ();_Y();V9();S10();z7();E91();zm();FW();M_$();tB();D71=d({name:"TASK_BOARD_REVIEW_DECISION",description:"Record a reviewer's decision for a task under review. `approve` marks the pull request approved by that reviewer (and, once EVERY enabled reviewer has approved, merges it when the org enabled auto-merge, advancing the task to Done); `request_changes` records your notes and hands the task to "+"a human \u2014 review is single-pass, so it is not sent back to the Super Agent.",annotations:{title:"Review Decision",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:yj.object({taskBoardItemId:yj.string(),reviewer:yj.enum(["reviewer","qa","code_review"]).describe("Which reviewer you are \u2014 pass `reviewer`."),reviewToken:yj.string().optional().describe("The reviewToken from your prompt \u2014 proves you are this reviewer. "+"Pass it through exactly; an approval without a valid token is recorded but does NOT count toward an automatic merge."),decision:yj.enum(["approve","request_changes"]),notes:yj.string().min(1).max(Ae4).describe("For approve: a short summary of what you verified. For request_changes: specific, actionable feedback the Super Agent must address.")}),outputSchema:yj.object({status:oB,merged:yj.boolean().describe("True when this approval completed the review and merged the PR.")}),handler:async({taskBoardItemId:$,reviewer:Z,reviewToken:Q,decision:Y,notes:X},J)=>{a(J),await J.access.check();let W=J.organization?.id;if(!W)throw Error("Organization ID required (no active organization in context)");let K=await J.storage.taskBoard.getById($,W);if(!K)throw Error(`Task board item not found: ${$}`);let H=Q?SB(K.reviewCycleStartedAt?[]:await J.storage.taskBoard.listActivity($,W),K.reviewCycleStartedAt):0,F=!!Q&&(BV$(Q,$,Z,new Date(H))||Te4(await J.storage.taskBoard.resolveReviewClaimByToken($,Q),Z,H)),U=nG.getStore()?.threadId;if(U)await q_$(J,K,"reviewer",U,{decision:Y,notes:X}).catch((T)=>console.error("[task-board] reviewer comment record failed",T));if(Y==="request_changes"){let T=await J.storage.taskBoard.listActivity($,W);if(Re4(T,"reviewer",K.reviewCycleStartedAt))return{status:K.status,merged:!1};return await o6(J,{taskBoardItemId:$,action:"review_changes_requested",actorId:null,data:{reviewer:"reviewer",notes:X,verified:F}}),await KH(J,K,`${tF.reviewer} requested changes \u2014 review is single-pass`),{status:(await J.storage.taskBoard.getById($,W)??K).status,merged:!1}}if(await o6(J,{taskBoardItemId:$,action:"review_approved",actorId:null,data:{reviewer:"reviewer",notes:X,verified:F}}),await u91(J,K),!await k10(J,W,$)){let T=await J.storage.taskBoard.getById($,W)??K;return E8(W,T),{status:T.status,merged:!1}}let B=await J.storage.organizationSettings.get(W),O=B?.flags?.auto_merge===!0,L=await J.storage.taskBoard.hasHumanRejectedDone($,W),w=O&&!L,j=w?await V10(J,W,$):null;if(j?.merged===!0){let T=oF(B?.flags),P=await J.storage.taskBoard.getById($,W)??K,A=await J.storage.taskBoard.update($,W,{status:T},K.updatedBy);return await o6(J,{taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:P.status,to:T}}),E8(W,A),{status:A.status,merged:!0}}let z=await J.storage.taskBoard.getById($,W)??K;if(w){let T=await J.storage.taskBoard.listPrs($,W),P=await $f(J,W,T);if(P?await _j(J,W,z,{pr:{number:P.number,url:P.url},conflict:F71(j)}).catch((q)=>{if(q instanceof zX)throw q;return console.error("[task-board] conflict auto-resolve failed",q),!1}):!1)return{status:(await J.storage.taskBoard.getById($,W)??z).status,merged:!1}}return E8(W,z),{status:z.status,merged:!1}}})});import{z as NR0}from"zod";function qe4($,Z,Q,Y){if(!FV$.has($))return!1;return Q.length===0||fw(Z,Q,{cycleStartedAt:Y})}var L71;var V_$=D(()=>{C0();C4();IJ();WH();_Y();V9();S10();L71=d({name:"TASK_BOARD_PROMOTE_TO_PRODUCTION",description:"Ship a reviewed task: merge its open pull request and move the task to Merged (or Done, on a board without the delivery lanes). Used by the board's 'Ship to production' button after the enabled reviewers approved, when auto-merge is off (a human does the final merge).",annotations:{title:"Ship to Production",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},inputSchema:NR0.object({taskBoardItemId:NR0.string()}),outputSchema:NR0.object({status:oB,merged:NR0.boolean().describe("True when the PR was merged.")}),handler:async({taskBoardItemId:$},Z)=>{a(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let Y=await Z.storage.taskBoard.getById($,Q);if(!Y)throw Error(`Task board item not found: ${$}`);let X=await Z.storage.organizationSettings.get(Q),J=kB(X?.flags),G=await Z.storage.taskBoard.listActivity($,Q);if(!qe4(Y.status,G,J,Y.reviewCycleStartedAt))throw Error("Task is not ready to ship: it must be In Review or Approved with every enabled reviewer approved");if(!(await V10(Z,Q,$,{allowPendingChecks:!0})).merged){let F=await Z.storage.taskBoard.getById($,Q)??Y;return E8(Q,F),{status:Y.status,merged:!1}}let K=oF(X?.flags),H=await Z.storage.taskBoard.update($,Q,{status:K},Y.updatedBy);if(Y.status!==K)await o6(Z,{taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:Y.status,to:K}});return E8(Q,H),{status:H.status,merged:!0}}})});import{z as AW}from"zod";function k_$($){if(!$)throw Error("Organization ID required (no active organization in context)");return $}var Me4,w71,j71;var S_$=D(()=>{C0();Me4=AW.object({externalKey:AW.string(),dismissedBy:AW.string(),dismissedAt:AW.string()});w71=d({name:"TASK_BOARD_DISMISSED_LIST",description:"List the Deco Score findings this organization has dismissed by deleting their task board cards. The import skips these until they're restored.",annotations:{title:"List Dismissed Findings",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:AW.object({}),outputSchema:AW.object({findings:AW.array(Me4)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=k_$(Z.organization?.id);return{findings:await Z.storage.taskBoard.listDismissedFindings(Q)}}}),j71=d({name:"TASK_BOARD_DISMISSED_RESTORE",description:"Un-dismiss Deco Score findings, returning their cards to the board. Omit externalKeys to restore every dismissed finding.",annotations:{title:"Restore Dismissed Findings",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:AW.object({externalKeys:AW.array(AW.string()).max(1000).optional()}),outputSchema:AW.object({restored:AW.number()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=k_$(Z.organization?.id);return{restored:await Z.storage.taskBoard.restoreDismissedFindings(Q,$.externalKeys)}}})});import{z as q5}from"zod";function BR0($){let Z=$.organization?.id;if(!Z)throw Error("Organization ID required (no active organization in context)");return Z}function Ve4($,Z,Q){return $.replace(Ie4,(Y,X,J,G)=>{let W=encodeURIComponent(`${Z}/${J}`);return`${X}/api/${encodeURIComponent(Q)}/fs/outputs/read?path=${W}${G}`})}var C_$=50000,E71,z71,Ie4,P71,A71,T71;var __$=D(()=>{C0();C4();tB();E71=q5.object({id:q5.string(),taskBoardItemId:q5.string(),parentId:q5.string().nullable(),authorId:q5.string(),threadId:q5.string().nullable().optional(),body:q5.string(),resolved:q5.boolean(),createdAt:q5.string(),updatedAt:q5.string()});z71=d({name:"TASK_BOARD_COMMENT_LIST",description:"List a task board item's comments (flat, oldest first; replies carry parentId).",annotations:{title:"List Task Comments",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q5.object({taskBoardItemId:q5.string()}),outputSchema:q5.object({comments:q5.array(E71)}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{comments:await Z.storage.taskBoard.listComments($.taskBoardItemId,BR0(Z))}}}),Ie4=/(!\[[^\]]*\]\()org\/output\/([^)\s]+)(\))/g;P71=d({name:"TASK_BOARD_COMMENT_CREATE",description:"Post a comment on a task board item, or a reply to one.",annotations:{title:"Create Task Comment",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:q5.object({taskBoardItemId:q5.string(),body:q5.string().trim().min(1).max(C_$),parentId:q5.string().nullish()}),outputSchema:q5.object({comment:E71}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=BR0(Z),Y=nG.getStore(),X=Z.organization?.slug,J=Y?.threadId&&X?Ve4($.body,Y.threadId,X):$.body,G=await Z.storage.taskBoard.createComment({taskBoardItemId:$.taskBoardItemId,organizationId:Q,parentId:$.parentId??null,authorId:Y?j8:p0(Z),threadId:Y?.threadId??null,body:J});if(!G)throw Error("Task board item not found");return await Z.storage.notifications.notify({taskBoardItemId:G.taskBoardItemId,type:"commented",actorId:Y?null:p0(Z),alsoSubscribe:Y?[]:[p0(Z)]}),await Z.storage.notifications.notifyMentions({taskBoardItemId:G.taskBoardItemId,organizationId:Q,actorId:Y?null:p0(Z),body:G.body}),{comment:G}}}),A71=d({name:"TASK_BOARD_COMMENT_UPDATE",description:"Edit your own comment's body, or resolve/unresolve a comment thread (root only, any org member may toggle it).",annotations:{title:"Update Task Comment",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:q5.object({id:q5.string(),body:q5.string().trim().min(1).max(C_$).optional(),resolved:q5.boolean().optional()}),outputSchema:q5.object({comment:E71}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=BR0(Z),Y=$.body!==void 0?await Z.storage.taskBoard.getComment($.id,Q):null,X=await Z.storage.taskBoard.updateComment({id:$.id,organizationId:Q,callerId:p0(Z),body:$.body,resolved:$.resolved});if(!X)throw Error("Comment not found, or you can only edit your own comments");if($.body!==void 0&&X.body!==Y?.body)await Z.storage.notifications.notifyMentions({taskBoardItemId:X.taskBoardItemId,organizationId:Q,actorId:p0(Z),body:X.body,previousBody:Y?.body??null});return{comment:X}}}),T71=d({name:"TASK_BOARD_COMMENT_DELETE",description:"Delete your own comment. Deleting a thread root deletes its replies too.",annotations:{title:"Delete Task Comment",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:q5.object({id:q5.string()}),outputSchema:q5.object({success:q5.boolean()}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{success:await Z.storage.taskBoard.deleteComment($.id,BR0(Z),p0(Z))}}})});var v_$=D(()=>{cE$();n91();m91();RT0();i91();O_$();L_$();z7();w_$();N71();A_$();T_$();I_$();V_$();_Y();S_$();__$();MT0()});function _10($){let Z=$.organization?.id;if(!Z)throw Error("Organization ID required (no active organization in context)");return Z}async function R71($,Z){let Q=_10($);if(!await $.storage.taskBoard.getById(Z,Q))throw Error("Task board item not found");return Q}import{z as vY}from"zod";var Se4,b_$;var x_$=D(()=>{C0();s20();Se4=vY.object({id:vY.string(),taskBoardItemId:vY.string(),type:vY.enum(r20),taskTitle:vY.string(),taskKeySeq:vY.number().nullable(),actorName:vY.string().nullable(),actorImage:vY.string().nullable(),createdAt:vY.string()}),b_$=d({name:"NOTIFICATION_LIST",description:"List the current user's unread notifications in the current organization, newest first.",annotations:{title:"List Notifications",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:vY.object({cursor:vY.string().optional(),limit:vY.number().int().positive().max(50).optional()}),outputSchema:vY.object({notifications:vY.array(Se4),unreadCount:vY.number(),nextCursor:vY.string().nullable()}),handler:async($,Z)=>{a(Z),await Z.access.check();let{notifications:Q,unreadCount:Y,nextCursor:X}=await Z.storage.notifications.listUnread(p0(Z),_10(Z),{cursor:$.cursor,limit:$.limit});return{notifications:Q.map((J)=>({id:J.id,taskBoardItemId:J.taskBoardItemId,type:J.type,taskTitle:J.data.taskTitle,taskKeySeq:J.data.taskKeySeq,actorName:J.data.actorName,actorImage:J.data.actorImage,createdAt:J.createdAt})),unreadCount:Y,nextCursor:X}}})});import{z as v10}from"zod";var f_$;var y_$=D(()=>{C0();f_$=d({name:"NOTIFICATION_MARK_READ",description:"Mark notifications read. Omit `ids` to mark all of the current user's unread ones in this organization.",annotations:{title:"Mark Notifications Read",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:v10.object({ids:v10.array(v10.string()).max(1000).optional()}),outputSchema:v10.object({marked:v10.number()}),handler:async($,Z)=>{return a(Z),await Z.access.check(),{marked:await Z.storage.notifications.markRead(p0(Z),_10(Z),$.ids)}}})});import{z as zU}from"zod";var g_$,h_$;var u_$=D(()=>{C0();g_$=d({name:"NOTIFICATION_SUBSCRIPTION_SET",description:"Follow or unfollow a task board item.",annotations:{title:"Set Notification Subscription",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:zU.object({taskBoardItemId:zU.string(),subscribed:zU.boolean()}),outputSchema:zU.object({subscribed:zU.boolean()}),handler:async($,Z)=>{return a(Z),await Z.access.check(),await R71(Z,$.taskBoardItemId),await Z.storage.notifications.setSubscribed(p0(Z),$.taskBoardItemId,$.subscribed),{subscribed:$.subscribed}}}),h_$=d({name:"NOTIFICATION_SUBSCRIPTION_LIST",description:"List the user ids following a task board item.",annotations:{title:"List Notification Subscribers",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:zU.object({taskBoardItemId:zU.string()}),outputSchema:zU.object({userIds:zU.array(zU.string())}),handler:async($,Z)=>{return a(Z),await Z.access.check(),await R71(Z,$.taskBoardItemId),{userIds:await Z.storage.notifications.listSubscribers($.taskBoardItemId)}}})});var l_$=D(()=>{x_$();y_$();u_$()});import{z as KO}from"zod";var q71;var c_$=D(()=>{C0();q71=d({name:"TAGS_LIST",description:"List all tags available in the organization.",annotations:{title:"List Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:KO.object({}),outputSchema:KO.object({tags:KO.array(KO.object({id:KO.string(),organizationId:KO.string(),name:KO.string(),color:KO.string().nullable(),createdAt:KO.string().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return{tags:(await Z.storage.tags.listOrgTags(Q.id)).map((X)=>({...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():String(X.createdAt)}))}}})});import{z as PU}from"zod";var M71;var m_$=D(()=>{C0();M71=d({name:"TAGS_CREATE",description:"Create a new tag, usable on organization members and task board items.",annotations:{title:"Create Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:PU.object({name:PU.string().min(1).max(50).describe("Tag name"),color:PU.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional().describe('Hex color the tag renders its dot with, e.g. "#3b82f6"')}),outputSchema:PU.object({tag:PU.object({id:PU.string(),organizationId:PU.string(),name:PU.string(),color:PU.string().nullable(),createdAt:PU.string().describe("ISO 8601 timestamp")})}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.tags.createTag(Q.id,$.name,$.color);return{tag:{...Y,createdAt:Y.createdAt instanceof Date?Y.createdAt.toISOString():String(Y.createdAt)}}}})});import{z as OR0}from"zod";var I71;var d_$=D(()=>{C0();I71=d({name:"TAGS_DELETE",description:"Delete a tag and automatically remove it from all assigned members.",annotations:{title:"Delete Tag",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:OR0.object({tagId:OR0.string().describe("Tag ID to delete")}),outputSchema:OR0.object({success:OR0.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z),Y=await Z.storage.tags.getTag($.tagId);if(!Y)throw Error("Tag not found");if(Y.organizationId!==Q.id)throw Error("Tag does not belong to this organization");return await Z.storage.tags.deleteTag($.tagId),{success:!0}}})});import{z as AU}from"zod";var V71;var i_$=D(()=>{C0();V71=d({name:"MEMBER_TAGS_GET",description:"Get all tags currently assigned to a specific member.",annotations:{title:"Get Member Tags",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:AU.object({memberId:AU.string().describe("Member ID")}),outputSchema:AU.object({tags:AU.array(AU.object({id:AU.string(),organizationId:AU.string(),name:AU.string(),color:AU.string().nullable(),createdAt:AU.string().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);if(!await Z.storage.tags.verifyMemberOrg($.memberId,Q.id))throw Error(`Member not found in this organization: ${$.memberId}`);return{tags:(await Z.storage.tags.getMemberTags($.memberId)).map((J)=>({...J,createdAt:J.createdAt instanceof Date?J.createdAt.toISOString():String(J.createdAt)}))}}})});import{z as TW}from"zod";var k71;var p_$=D(()=>{C0();k71=d({name:"MEMBER_TAGS_SET",description:"Replace all tags on a member with the given set. Pass empty array to clear.",annotations:{title:"Set Member Tags",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:TW.object({memberId:TW.string().describe("Member ID"),tagIds:TW.array(TW.string()).max(1000).describe("Array of tag IDs to assign")}),outputSchema:TW.object({success:TW.boolean(),tags:TW.array(TW.object({id:TW.string(),organizationId:TW.string(),name:TW.string(),createdAt:TW.string().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);if(!await Z.storage.tags.verifyMemberOrg($.memberId,Q.id))throw Error(`Member not found in this organization: ${$.memberId}`);let X=await Z.storage.tags.getTagsByIds($.tagIds),J=new Map(X.map((W)=>[W.id,W]));for(let W of $.tagIds){let K=J.get(W);if(!K)throw Error(`Tag not found: ${W}`);if(K.organizationId!==Q.id)throw Error(`Tag does not belong to this organization: ${W}`)}return await Z.storage.tags.setMemberTags($.memberId,$.tagIds),{success:!0,tags:(await Z.storage.tags.getMemberTags($.memberId)).map((W)=>({...W,createdAt:W.createdAt instanceof Date?W.createdAt.toISOString():String(W.createdAt)}))}}})});var n_$=D(()=>{c_$();m_$();d_$();i_$();p_$()});import{z as HZ}from"zod";var t_$,gj,DR0;var b10=D(()=>{t_$=HZ.object({id:HZ.string().min(1).describe("Arm id, e.g. `control` or `variant-b`."),weight:HZ.number().int().min(0).max(100),role:HZ.enum(["control","treatment"]).nullable().optional()}),gj=HZ.object({id:HZ.string(),organizationId:HZ.string(),site:HZ.string(),key:HZ.string(),name:HZ.string(),status:HZ.enum(["draft","running","paused","ended"]),goals:HZ.array(HZ.string()),variants:HZ.array(t_$),startedAt:HZ.string().nullable(),endedAt:HZ.string().nullable(),createdBy:HZ.string(),createdAt:HZ.string(),updatedAt:HZ.string()}),DR0=HZ.array(t_$).min(1).superRefine(($,Z)=>{let Q=$.reduce((Y,X)=>Y+X.weight,0);if(Q!==100)Z.addIssue({code:HZ.ZodIssueCode.custom,message:`variant weights must sum to 100 (got ${Q})`});if(new Set($.map((Y)=>Y.id)).size!==$.length)Z.addIssue({code:HZ.ZodIssueCode.custom,message:"variant ids must be unique"})})});async function o_$($,Z,Q){let X=(await $.storage.virtualMcps.list(Z)).find((J)=>la(J)===Q);if(!X)throw Error("Site not found in organization");return X}async function TU($,Z,Q){await o_$($,Z,Q)}async function r_$($,Z,Q){let Y=await o_$($,Z,Q),X=$H$(Y)??Q;if(X===Q)return Q;return await $.storage.orgSites.isOwnedBy(X,Z)?X:Q}var Ff=D(()=>{fG()});import{z as LR0}from"zod";var S71;var s_$=D(()=>{C0();b10();Ff();S71=d({name:"EXPERIMENT_LIST",description:"List the A/B experiments configured for a site.",annotations:{title:"List Experiments",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:LR0.object({site:LR0.string().min(1).describe("Site slug the experiments belong to.")}),outputSchema:LR0.object({experiments:LR0.array(gj)}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return await TU(Z,Q.id,$.site),{experiments:await Z.storage.experiments.listBySite(Q.id,$.site)}}})});import{z as wR0}from"zod";var C71;var a_$=D(()=>{C0();b10();Ff();C71=d({name:"EXPERIMENT_GET",description:"Get one experiment by site + key. Null when it does not exist.",annotations:{title:"Get Experiment",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},inputSchema:wR0.object({site:wR0.string().min(1),key:wR0.string().min(1)}),outputSchema:wR0.object({experiment:gj.nullable()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);return await TU(Z,Q.id,$.site),{experiment:await Z.storage.experiments.getByKey(Q.id,$.site,$.key)}}})});import{z as Uf}from"zod";var _71;var e_$=D(()=>{C0();b10();Ff();_71=d({name:"EXPERIMENT_CREATE",description:"Create a draft A/B experiment for a site. `key` must be unique for the site; weights must sum to 100. Does not publish \u2014 it stores the definition; wiring the traffic-split block into the decofile is a separate step.",annotations:{title:"Create Experiment",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:Uf.object({site:Uf.string().min(1),key:Uf.string().trim().min(1).max(120).describe("The random matcher block's name (e.g. `Cross Sell Bag`) \u2014 the deco runtime records the split as `event:props:<that name>`, so results only populate when the key equals it."),name:Uf.string().min(1),goals:Uf.array(Uf.string()).optional(),variants:DR0.optional()}),outputSchema:Uf.object({experiment:gj}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);await TU(Z,Q.id,$.site);let Y=Z.auth.user.id;if(await Z.storage.experiments.getByKey(Q.id,$.site,$.key))throw Error(`An experiment "${$.key}" already exists on ${$.site}.`);return{experiment:await Z.storage.experiments.create({organizationId:Q.id,site:$.site,key:$.key,name:$.name,goals:$.goals,variants:$.variants,createdBy:Y})}}})});import{z as hj}from"zod";var v71;var $v$=D(()=>{C0();b10();Ff();v71=d({name:"EXPERIMENT_UPDATE",description:"Update an experiment's definition (name, status, goals, variants). Errors when the (site, key) is unknown. When `variants` is present it replaces the full set (weights must sum to 100).",annotations:{title:"Update Experiment",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},inputSchema:hj.object({site:hj.string().min(1),key:hj.string().min(1),name:hj.string().min(1).optional(),status:hj.enum(["draft","running","paused","ended"]).optional(),goals:hj.array(hj.string()).optional(),variants:DR0.optional()}),outputSchema:hj.object({experiment:gj}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);await TU(Z,Q.id,$.site);let Y=await Z.storage.experiments.update(Q.id,$.site,$.key,{name:$.name,status:$.status,goals:$.goals,variants:$.variants});if(!Y)throw Error(`No experiment "${$.key}" on ${$.site}.`);return{experiment:Y}}})});import{z as Nf}from"zod";var b71;var Zv$=D(()=>{C0();Ff();b71=d({name:"EXPERIMENT_DELETE",description:"Delete an experiment (metadata) by site + key. Returns whether a row existed.",annotations:{title:"Delete Experiment",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},inputSchema:Nf.object({site:Nf.string().min(1),key:Nf.string().min(1)}),outputSchema:Nf.object({site:Nf.string(),key:Nf.string(),deleted:Nf.boolean()}),handler:async($,Z)=>{a(Z),await Z.access.check();let Q=K0(Z);await TU(Z,Q.id,$.site);let Y=await Z.storage.experiments.delete(Q.id,$.site,$.key);return{site:$.site,key:$.key,deleted:Y}}})});function HO(){let $=E0();return!!($.clickhouseAnalyticsUrl&&$.clickhouseAnalyticsPassword)}async function be4(){if(!jR0){let $=E0();jR0=Promise.resolve().then(() => C(Ni0(),1)).then(({createClient:Z})=>Z({url:$.clickhouseAnalyticsUrl,username:$.clickhouseAnalyticsUsername,password:$.clickhouseAnalyticsPassword,request_timeout:ve4})).catch((Z)=>{throw jR0=null,Z})}return jR0}async function tZ($,Z){if(!HO())return[];return(await(await be4()).query({query:$,query_params:Z,format:"JSONEachRow"})).json()}var jR0=null,ve4=20000;var ER0=D(()=>{F$()});function ye4($){if($.some((Q)=>Q.status==="rejected"))return console.warn("[deco-legacy] a OneDollarStats host query failed"),null;let Z=new Map;for(let Q of $){if(Q.status!=="fulfilled")continue;for(let Y of Q.value){let X=Y.dimensions[0]?.split(" ")[0];if(!X)continue;Z.set(X,(Z.get(X)??0)+(Y.metrics[0]??0))}}return Z}async function Yv$($,Z,Q){let Y=E0().oneDollarStatsApiKey,X=[...new Set($)];if(!Y||X.length===0)return null;let J=async(W)=>{let K=await fetch(`${xe4}/plausible`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":Y,Accept:"application/json"},body:JSON.stringify({site_id:W,date_range:[Z,Q],metrics:["pageviews"],dimensions:["time:day"],pagination:{limit:1e4,offset:0}}),signal:AbortSignal.timeout(fe4)});if(!K.ok)throw Error(`OneDollarStats ${K.status}`);return(await K.json()).results??[]},G=[];for(let W=0;W<X.length;W+=Qv$)G.push(...await Promise.allSettled(X.slice(W,W+Qv$).map(J)));return ye4(G)}function fm($){if($.endsWith(".deco.site")||$.startsWith("www."))return $;return`www.${$}`}var xe4="https://deco.lilstts.com",fe4=1e4,Qv$=6;var zR0=D(()=>{F$()});function ge4($,Z=0,Q=1){let Y=($-Z)/(Q*Math.SQRT2),X=1/(1+0.3275911*Math.abs(Y)),J=1-((((1.061405429*X-1.453152027)*X+1.421413741)*X-0.284496736)*X+0.254829592)*X*Math.exp(-Y*Y);return 0.5*(1+(Y>=0?J:-J))}function x10($){return $.successes/$.total}function Xv$($){let Z=x10($);return Math.sqrt(Z*(1-Z)/$.total)}function Jv$($,Z){let Q=-(x10(Z)-x10($))/Math.sqrt(Xv$($)**2+Xv$(Z)**2),Y=1-ge4(Q,0,1);return Number.isFinite(Y)?Y:0}function Gv$($,Z,Q=0.03){if($.total<1000||$.successes===0)return null;let Y=Z.total/$.total,X=x10($),J=Math.max(X*(1+Q),x10(Z)),G=(X+Y*J)/(Y+1),W=1.644853*Math.sqrt((Y+1)*G*(1-G))+0.8416*Math.sqrt(Y*X*(1-X)+J*(1-J)),K=J-X,H=(W/K)**2/Y,F=1+Math.sqrt(1+2*(Y+1)/(H*Y*Math.abs(X-J))),U=H*F**2/4;return Math.ceil(U)*(1+Y)}async function ce4($,Z,Q){let Y=await tZ(`SELECT host
|
|
1715
1715
|
FROM default.fact_usage_daily_view
|
|
1716
1716
|
WHERE ${le4}
|
|
1717
1717
|
AND date >= {since:Date} AND date <= {until:Date}
|
|
@@ -3703,7 +3703,7 @@ Respond with ONLY a JSON object of this shape, and nothing else:
|
|
|
3703
3703
|
${J.join(`
|
|
3704
3704
|
`)}`:X}function bh6($){let Z=new Set;for(let Q of $)for(let Y of Q.split(`
|
|
3705
3705
|
`)){let X=Y.trim();if(/^Co-authored-by:\s/i.test(X))Z.add(X)}return[...Z]}var _48=200,Rh6=12,Mh6,Vh6=300,mk0=3;var QU1=D(()=>{iZ();D8();ck0();Mh6={aheadBy:0,behindBy:0,files:[]}});function fh6($){if(!$||$.includes(".."))return!1;return xh6.test($)}function b48($){return yh6.includes($)}function YU1($){let Z=typeof $.__resolveType==="string"?$.__resolveType:null;if(!Z||!fh6(Z))return null;let{__resolveType:Q,...Y}=$;return{resolveType:Z,payload:Y}}function XU1($,Z){return`${$.replace(/\/+$/,"")}/deco/invoke/${Z}`}var xh6,yh6;var x48=D(()=>{xh6=/^[\w./@-]+$/;yh6=["vtex/loaders/intelligentSearch/productList.ts","vtex/loaders/categories/tree.ts"]});function Z40($,Z){let Q=$?.githubRepo;if(!Q?.owner||!Q?.name)return null;if(!Q.connectionId)return Q;if(!Z.includes(Q.connectionId))return null;return Q}async function y48($,Z,Q,Y){let X=$.organization?.id;if(!X)throw new zE(j7);let J=await Zj($.storage,X,Y);if(J&&await gB($.storage,J)){let F=await aF($,J,{forceRefresh:!0}).catch((U)=>{throw new zE(U instanceof Error?U.message:j7)});await f48($,Z,Q,F);return}let G=Y.connectionId??J?.legacyConnectionId;if(!G)throw new zE("Push requires a connected git account. Connect the repository's provider for this project and restart the sandbox.");await Pc({ctx:$,connectionId:G,organizationId:X,forceRefresh:!0,onLegacyMintError:(F)=>{let U=F instanceof Error?F.message:j7;throw new zE(U)}});let{cloneUrl:W,gitUserName:K,gitUserEmail:H}=await eF(G,Y.owner,Y.name,$.db,$.vault).catch((F)=>{let{code:U,message:N}=aU$(F instanceof Error?F.message:String(F));throw U?new zE(N):F});await f48($,Z,Q,{cloneUrl:W,gitUserName:K,gitUserEmail:H})}async function f48($,Z,Q,Y){let{cloneUrl:X,gitUserName:J,gitUserEmail:G}=Y,W=wi($),K=await Z.proxyDaemonRequest(Q,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({git:{repository:{cloneUrl:X},identity:{userName:J,userEmail:G}},...W?{operator:W}:{}})});if(!K.ok){let H=await Rj(K,gh6).catch(()=>K.statusText);throw Error(`Failed to refresh sandbox git credentials (${K.status}): ${H}`)}}var gh6=10485760,zE;var JU1=D(()=>{WW();vk0();_00();gW0();qe();iZ();zE=class zE extends Error{constructor($){super($);this.name="GitPushAuthError"}}});function uh6($){let Z=$.startsWith("thread:")?$.slice(7):$;if(!Z||Z.length>255||Z.includes("..")||Z.startsWith("/")||Z.endsWith("/")||Z.endsWith(".lock")||!hh6.test(Z))throw Error(`Invalid branch name: ${$}`)}function Fy($){return AbortSignal.any([$.req.raw.signal,AbortSignal.timeout(lh6)])}async function mh6($,Z){let Q=$.var.studioContext,Y=WU(Z.branch),X=$.req.query("thread")??Y,J=X&&X===Y?Z.branchThread:X?await Q.storage.threads.get(X).catch(()=>null):null,G=J?.virtual_mcp_id===Z.virtualMcpId?J:null,W=fx(G?.metadata?.runtime);if(W)return W;let K=M20(Z.virtualMcpMetadata),H=K==="cms"?await fF1(Q,{claimName:Z.claimName}):"alive",F=K==="cms"&&H!=="alive"?"cms":"sandbox",U=!!G&&(H==="gone"||H==="alive"&&K==="cms");if(U&&G)v00(Q,G.id,F);if(K==="cms")console.log("sandbox proxy: no runtime stamp",{route:$.req.path,method:$.req.method,reason:G?"unstamped":"threadless",liveness:H,resolved:F,stamped:U});return F}async function dh6($){let Z=$.get("vmClaim");if(Z.runner)return Z.runner;try{return await IX($.var.studioContext)}catch{return null}}function Uy($){let{runner:Z}=$.get("vmClaim");if(!Z)return $.json({error:"No sandbox runner configured"},503);return Z}async function Ai($){let{virtualMcpMetadata:Z,connectionIds:Q}=$.get("vmClaim"),Y=$.var.studioContext,X=Z40(Z,Q);if(!X)throw new y0({provider:"github",status:404,message:"Project has no GitHub repository"});let J=K0(Y);return jc(Y,J.id,X)}function WU1($,Z){let Q=Z instanceof Error?Z.message:String(Z),Y=EF$(Z);if(Y!==void 0)return $.json({error:Q},429,{...$9,...Y===null?{}:{"Retry-After":String(Math.ceil(Y/1000))}});if(Z instanceof t6)return $.json({error:Q},409,$9);let X=UW(Z);if(X!==null){let J=X===404?404:X===409||X===422?409:502;return $.json({error:Q},J,$9)}return $.json({error:Q},502,$9)}async function GU1($,Z,Q){let Y;try{Y=await fetch(Z,Q)}catch{return $.json({error:"Preview unreachable"},502)}let X;try{X=await Y.text()}catch{return $.json({error:"Preview unreachable"},502)}return new Response(X,{status:Y.status,headers:{"content-type":Y.headers.get("content-type")??"application/json"}})}async function l48($){try{let Z=await Ai($),Q=await dk0(Z,$.get("vmClaim").branch);return $.json(Q,200,$9)}catch(Z){return WU1($,Z)}}function Q40($,Z){let Y=(nk0.get($)??Promise.resolve()).catch(()=>{}).then(Z),X=Y.catch(()=>{});return nk0.set($,X),X.finally(()=>{if(nk0.get($)===X)nk0.delete($)}),Y}async function $Q($,Z,Q){if(!Q?.runner&&$.get("vmClaim").runtime==="cms")return $.json({error:"sandbox not found: this session is sandbox-less"},404,$9);let Y=Q?.runner??Uy($);if(Y instanceof Response)return Y;let{claimName:X,userId:J,projectRef:G}=$.get("vmClaim"),W=Q?.method??"POST",K=null,H=new Headers;if(Q?.jsonBody!==void 0)K=Q.jsonBody,H.set("content-type","application/json");else if(Q?.forwardJsonBody)K=await $.req.text(),H.set("content-type","application/json");let F=Q?.signal,U={method:W,headers:H,body:K,...F?{signal:F}:{}},N=async()=>{let B=await Y.proxyDaemonRequest(X,Z,U);if(Q?.map404to410&&B.status===404){try{await B.body?.cancel()}catch{}if(await Y.adoptLiveClaim({userId:J,projectRef:G},X))B=await Y.proxyDaemonRequest(X,Z,U);if(B.status===404){try{await B.body?.cancel()}catch{}return new Response(JSON.stringify({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."}),{status:410,headers:{"content-type":"application/json",...$9}})}}let O=await B.text(),L=Q?.redactRepoDir?ih6(O):O,w=B.headers.get("content-type")??"application/json";return new Response(L,{status:B.status,headers:{"content-type":w,...$9}})};try{if(F){let B=N();return B.catch(()=>{}),await Promise.race([B,new Promise((L,w)=>{if(F.aborted)return w(F.reason);F.addEventListener("abort",()=>w(F.reason),{once:!0})})])}return await N()}catch(B){let O=B instanceof Error?B.message:String(B);return $.json({error:`Daemon unreachable: ${O}`},502)}}function ih6($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&"repoDir"in Z)return JSON.stringify({...Z,repoDir:null})}catch{}return $}async function tk0($,Z,Q,Y="GET",X){let J=await $.proxyDaemonRequest(Z,Q,{method:Y,headers:new Headers,body:null});if(J.status===404&&X){try{await J.body?.cancel()}catch{}if(await $.adoptLiveClaim(X,Z))J=await $.proxyDaemonRequest(Z,Q,{method:Y,headers:new Headers,body:null})}if(J.status===404){try{await J.body?.cancel()}catch{}throw Error("SANDBOX_GONE")}let G=await J.text();if(!J.ok){let W=`Daemon error (${J.status})`;try{W=JSON.parse(G).error??W}catch{}throw Error(W)}return JSON.parse(G)}function ph6($){return c48.includes($)}var hh6,g48=524288,h48=65536,lh6=1e4,u48=2000,ch6,nk0,$9,c48,m48=()=>{let $=new Q1;$.use("/:virtualMcpId/:branch/*",ch6),$.post("/:virtualMcpId/:branch/write",(Q)=>$Q(Q,"/_sandbox/write",{forwardJsonBody:!0,signal:Fy(Q)})),$.post("/:virtualMcpId/:branch/unlink",(Q)=>$Q(Q,"/_sandbox/unlink",{forwardJsonBody:!0,signal:Fy(Q)})),$.post("/:virtualMcpId/:branch/mkdir",(Q)=>$Q(Q,"/_sandbox/mkdir",{forwardJsonBody:!0,signal:Fy(Q)})),$.post("/:virtualMcpId/:branch/rename",(Q)=>$Q(Q,"/_sandbox/rename",{forwardJsonBody:!0,signal:Fy(Q)})),$.post("/:virtualMcpId/:branch/read",(Q)=>$Q(Q,"/_sandbox/read",{forwardJsonBody:!0,signal:Fy(Q)})),$.post("/:virtualMcpId/:branch/glob",(Q)=>$Q(Q,"/_sandbox/glob",{forwardJsonBody:!0,signal:Fy(Q)})),$.post("/:virtualMcpId/:branch/grep",(Q)=>$Q(Q,"/_sandbox/grep",{forwardJsonBody:!0,signal:Fy(Q)})),$.post("/:virtualMcpId/:branch/exec/:script",async(Q)=>{let Y=Q.req.param("script");if(!Y)return Q.json({error:"missing script name"},400);return $Q(Q,`/_sandbox/exec/${encodeURIComponent(Y)}`)}),$.post("/:virtualMcpId/:branch/exec/:script/kill",async(Q)=>{let Y=Q.req.param("script");if(!Y)return Q.json({error:"missing script name"},400);return $Q(Q,`/_sandbox/exec/${encodeURIComponent(Y)}/kill`)}),$.get("/:virtualMcpId/:branch/config",(Q)=>$Q(Q,"/_sandbox/config",{method:"GET",map404to410:!0,redactRepoDir:!0})),$.put("/:virtualMcpId/:branch/config",(Q)=>$Q(Q,"/_sandbox/config",{method:"PUT",forwardJsonBody:!0,map404to410:!0})),$.post("/:virtualMcpId/:branch/setup/:step",async(Q)=>{let Y=Q.req.param("step");if(!Y||!ph6(Y))return Q.json({error:`step must be one of: ${c48.join(", ")}`},400);let X=Q.get("vmClaim"),J=await fF1(Q.var.studioContext,{claimName:X.claimName})==="gone"?null:await dh6(Q);if(!J)return Q.json({error:"sandbox not found: nothing is running at this ref"},404,$9);if(Y==="start"){let G=K0(Q.var.studioContext),W=Zm(X.virtualMcpMetadata);try{await A20({ctx:Q.var.studioContext,runner:J,handle:X.claimName,orgId:G.id,userId:X.callerUserId,entries:W})}catch(K){let H=K instanceof Error?K.message:String(K);return Q.json({error:`Failed to push env to daemon: ${H}`},502)}}return $Q(Q,`/_sandbox/setup/${Y}`,{signal:Q.req.raw.signal,map404to410:!0,runner:J})}),$.get("/:virtualMcpId/:branch/events",(Q)=>{let Y=Q.get("vmClaim");if(!Y.runner)return bO(Q,async(X)=>{await X.writeSSE({event:"phase",data:JSON.stringify({kind:"failed",reason:"unknown",message:"No sandbox runner configured on this studio instance."})})});return u88(Q,{ctx:Q.var.studioContext,claimName:Y.claimName,runner:Y.runner,virtualMcpId:Y.virtualMcpId,branch:Y.branch,userId:Y.userId,projectRef:Y.projectRef,virtualMcpMetadata:Y.virtualMcpMetadata})}),$.get("/:virtualMcpId/:branch/git/status",(Q)=>{if(Q.get("vmClaim").runtime==="cms")return l48(Q);return Z(Q)});let Z=(Q)=>$Q(Q,"/_sandbox/git/status",{method:"GET",map404to410:!0,signal:AbortSignal.any([Q.req.raw.signal,AbortSignal.timeout(u48)])});return $.post("/:virtualMcpId/:branch/git/status",(Q)=>{if(Q.get("vmClaim").runtime==="cms")return l48(Q);return $Q(Q,"/_sandbox/git/status",{map404to410:!0,signal:AbortSignal.any([Q.req.raw.signal,AbortSignal.timeout(u48)])})}),$.post("/:virtualMcpId/:branch/git/diff",async(Q)=>{let Y=Q.get("vmClaim");if(Y.runtime==="cms")try{let X=await Q.req.json().catch(()=>({})),J=await Ai(Q),G=await ik0(J,Y.branch,X.base);return Q.json(G,200,$9)}catch(X){return WU1(Q,X)}return $Q(Q,"/_sandbox/git/diff",{forwardJsonBody:!0,map404to410:!0})}),$.post("/:virtualMcpId/:branch/git/publish",async(Q)=>{if(Q.get("vmClaim").runtime==="cms")return Q.json({ok:!0},200,$9);let Y=Uy(Q);if(Y instanceof Response)return Y;let{claimName:X,virtualMcpMetadata:J,connectionIds:G}=Q.get("vmClaim"),W=Q.var.studioContext;return Q40(X,async()=>{try{await yF1(W,Y,X);let K=Z40(J,G);if(K)await y48(W,Y,X,K)}catch(K){if(K instanceof zE)return Q.json({error:K.message},403,$9);let H=K instanceof Error?K.message:String(K);return Q.json({error:H},502,$9)}return $Q(Q,"/_sandbox/git/publish",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/discard",async(Q)=>{let Y=Q.get("vmClaim");if(Y.runtime==="cms")return Q40(Y.claimName,async()=>{let X=await Q.req.json().catch(()=>({})),J=Array.isArray(X.filepaths)?X.filepaths.filter((G)=>typeof G==="string"):[];if(J.length===0)return Q.json({error:"filepaths is required"},400,$9);try{let G=await Ai(Q);return await v48(G,Y.branch,J),Q.json({ok:!0},200,$9)}catch(G){let W=UW(G)===409||G instanceof t6?409:502,K=G instanceof Error?G.message:String(G);return Q.json({error:K},W,$9)}});return Q40(Y.claimName,()=>$Q(Q,"/_sandbox/git/discard",{forwardJsonBody:!0,map404to410:!0}))}),$.post("/:virtualMcpId/:branch/git/rebase",async(Q)=>{let Y=Q.get("vmClaim");if(Y.runtime==="cms")return Q40(Y.claimName,async()=>{try{let W=await Q.req.json().catch(()=>({})),K=await Ai(Q),H=W.base??await K.getDefaultBranch();return await pk0(K,Y.branch,H),Q.json({ok:!0},200,$9)}catch(W){return WU1(Q,W)}});let X=Uy(Q);if(X instanceof Response)return X;let{claimName:J}=Q.get("vmClaim"),G=Q.var.studioContext;return Q40(J,async()=>{try{await yF1(G,X,J)}catch(W){let K=W instanceof Error?W.message:String(W);return Q.json({error:K},502,$9)}return $Q(Q,"/_sandbox/git/rebase",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/suggest-commit",I5({maxSize:g48,onError:(Q)=>Q.json({error:"Payload too large"},413,$9)}),async(Q)=>{let Y=Q.get("vmClaim"),X=null;if(Y.runtime!=="cms"){let H=Uy(Q);if(H instanceof Response)return H;X=H}let{claimName:J,userId:G,projectRef:W}=Y,K=Q.var.studioContext;try{let H=await Q.req.json().catch(()=>({})),F=H.status,U=H.diff,N=U!=null&&typeof U.diffs==="object"&&U.diffs!==null,[B,O]=uF1(F)&&N?[F,U]:X?await Promise.all([tk0(X,J,"/_sandbox/git/status","GET",{userId:G,projectRef:W}),tk0(X,J,"/_sandbox/git/diff","GET",{userId:G,projectRef:W})]):await(async()=>{let w=await Ai(Q);return Promise.all([dk0(w,Y.branch),ik0(w,Y.branch)])})();await hK(K,K0(K).id,"suggesting a commit message");let L=await i88(K,B,O);return Q.json(L,200,$9)}catch(H){let F=H instanceof Error?H.message:String(H);if(F==="SANDBOX_GONE")return Q.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,$9);return Q.json({error:F},502,$9)}}),$.post("/:virtualMcpId/:branch/git/judge-review",I5({maxSize:g48,onError:(Q)=>Q.json({error:"Payload too large"},413,$9)}),async(Q)=>{let Y=Q.get("vmClaim"),X=null;if(Y.runtime!=="cms"){let H=Uy(Q);if(H instanceof Response)return H;X=H}let{claimName:J,userId:G,projectRef:W}=Y,K=Q.var.studioContext;try{let H=await Q.req.json().catch(()=>({})),F=H.status,U=H.diff,N=U!=null&&typeof U.diffs==="object"&&U.diffs!==null,[B,O]=uF1(F)&&N?[F,U]:X?await Promise.all([tk0(X,J,"/_sandbox/git/status","GET",{userId:G,projectRef:W}),tk0(X,J,"/_sandbox/git/diff","GET",{userId:G,projectRef:W})]):await(async()=>{let w=await Ai(Q);return Promise.all([dk0(w,Y.branch),ik0(w,Y.branch)])})();await hK(K,K0(K).id,"judging whether a change needs review");let L=await n88(K,B,O,typeof H.language==="string"?H.language:void 0);return Q.json(L,200,$9)}catch(H){let F=H instanceof Error?H.message:String(H);if(F==="SANDBOX_GONE")return Q.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,$9);return Q.json({error:F},502,$9)}}),$.get("/:virtualMcpId/:branch/preview-fetch",async(Q)=>{let Y=Uy(Q);if(Y instanceof Response)return Y;let{claimName:X}=Q.get("vmClaim"),J=Q.req.query("path");if(!J||!J.startsWith("/")||J.startsWith("//")||J.includes("..")||J.includes("\\"))return Q.json({error:"Path not allowed"},403);let G;try{G=await Y.getPreviewUrl(X)}catch{return Q.json({error:"Preview not available"},502)}if(!G)return Q.json({error:"Preview not available"},502);let W=G.replace(/\/+$/,"");return GU1(Q,`${W}${J}`)}),$.post("/:virtualMcpId/:branch/preview-invoke",I5({maxSize:h48,onError:(Q)=>Q.json({error:"Payload too large"},413)}),async(Q)=>{let Y=Uy(Q);if(Y instanceof Response)return Y;let{claimName:X}=Q.get("vmClaim"),J;try{J=await Y.getPreviewUrl(X)}catch{return Q.json({error:"Preview not available"},502)}if(!J)return Q.json({error:"Preview not available"},502);let G;try{G=await Q.req.json()}catch{return Q.json({error:"Invalid JSON body"},400)}if(!G||typeof G!=="object"||Array.isArray(G))return Q.json({error:"Invalid JSON body"},400);let W=YU1(G);if(!W)return Q.json({error:"Invalid or missing __resolveType"},400);let K=XU1(J,W.resolveType);return GU1(Q,K,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(W.payload),signal:AbortSignal.timeout(30000)})}),$.post("/:virtualMcpId/:branch/catalog-invoke",I5({maxSize:h48,onError:(Q)=>Q.json({error:"Payload too large"},413)}),async(Q)=>{let{runner:Y,claimName:X,virtualMcpMetadata:J}=Q.get("vmClaim"),G;try{G=Y?await Y.getPreviewUrl(X):Qm(J)}catch{return Q.json({error:"Preview not available"},502)}if(!G)return Q.json({error:"Preview not available"},502);let W;try{W=await Q.req.json()}catch{return Q.json({error:"Invalid JSON body"},400)}if(!W||typeof W!=="object"||Array.isArray(W))return Q.json({error:"Invalid JSON body"},400);let K=YU1(W);if(!K)return Q.json({error:"Invalid or missing __resolveType"},400);if(!b48(K.resolveType))return Q.json({error:"resolveType not allowed"},403);let H=XU1(G,K.resolveType);return GU1(Q,H,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(K.payload),signal:AbortSignal.timeout(30000)})}),$};var d48=D(()=>{G8();fW();Li();xF1();k00();y88();jW();Ym();g88();QH();gF();h88();l88();Q51();C00();mF1();t88();iZ();w5();QU1();x48();q20();JU1();hh6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;ch6=_k0(async($,Z)=>{let Q=$.var.studioContext;try{a(Q)}catch{return $.json({error:"Unauthorized"},401)}let Y=p0(Q);if(!Y)return $.json({error:"Unauthorized"},401);let X;try{X=K0(Q)}catch{return $.json({error:"Organization scope required"},403)}let J=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!J||!G)return $.json({error:"virtualMcpId and branch are required"},400);try{uh6(G)}catch(L){let w=L instanceof Error?L.message:String(L);return $.json({error:w},400)}let W=await Q.storage.virtualMcps.findById(J);if(!W||W.organization_id!==X.id)return $.json({error:"Virtual MCP not found"},404);let K=re({orgId:X.id,virtualMcpId:J,branch:G}),H=await V41(Q,G),F=k41(H,Y),U=f88({userId:F,projectRef:K}),N=W.metadata??null,B=await mh6($,{claimName:U,branch:G,virtualMcpId:J,sandboxUserId:F,virtualMcpMetadata:N,branchThread:H});if(B==="cms")return $.set("vmClaim",{claimName:U,callerUserId:Y,runner:null,virtualMcpId:J,branch:G,userId:F,projectRef:K,virtualMcpMetadata:N,connectionIds:W.connections?.map((L)=>L.connection_id)??[],runtime:B}),Z();let O;try{O=await IX(Q)}catch{O=null}if(!O)return $.json({error:"No sandbox runner found"},404);return $.set("vmClaim",{claimName:U,callerUserId:Y,runner:O,virtualMcpId:J,branch:G,userId:F,projectRef:K,virtualMcpMetadata:N,connectionIds:W.connections?.map((L)=>L.connection_id)??[],runtime:B}),Z()});nk0=new Map;$9={"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache"};c48=["clone","install","start"]});function i48($,Z,Q){let Y=KU1.get($);if(!Y)Y={pending:null,running:!1},KU1.set($,Y);if(!Y.pending)Y.pending={set:new Map,del:new Set,deps:Z,resolvers:[],rejecters:[]};let X=Y.pending;X.deps=Z;for(let[G,W]of Object.entries(Q.set??{}))X.set.set(G,W),X.del.delete(G);for(let G of Q.delete??[])X.del.add(G),X.set.delete(G);let J=new Promise((G,W)=>{X.resolvers.push(G),X.rejecters.push(W)});if(!Y.running)th6($,Y);return J}async function th6($,Z){Z.running=!0;try{while(Z.pending){let Q=Z.pending;Z.pending=null;try{let Y=await oh6(Q);for(let X of Q.resolvers)X(Y)}catch(Y){for(let X of Q.rejecters)X(Y)}}}finally{if(Z.running=!1,!Z.pending)KU1.delete($)}}async function oh6($){let{client:Z,branch:Q,packagePath:Y}=$.deps,X=new Map;for(let J=0;;J++){let G=await Pi(Z,Q),W=await Z.listDecofileEntries(G,Y),K=eF1(W,Y),H=[],F=new Map(K.map((N)=>[N.path,{stem:N.stem,sha:N.sha}]));for(let[N,B]of $.set){let O=$U1(K,N),L=`${JSON.stringify(B,null,2)}
|
|
3706
|
-
`;await V48(Z.repo,L);let w=O[0]??`${lk0(Y)}/${pF1(N)}.json`;H.push({path:w,content:L});let j=w.slice(w.lastIndexOf("/")+1,-5);F.set(w,{stem:j,content:L});for(let E of O.slice(1))H.push({path:E,deleted:!0}),F.delete(E)}for(let N of $.del)for(let B of $U1(K,N))H.push({path:B,deleted:!0}),F.delete(B);if(H.length===0)return G;let U=Y?`${Y}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(W.some((N)=>N.type==="blob"&&N.path===U)){let N=await k48(Z,F.values(),X),{decofile:B,skipped:O}=t80(N);if(O.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:cK(Z.repo),branch:Q,packagePath:Y,blocks:O.map((L)=>L.key)});H.push({path:U,content:B})}try{let{sha:N}=await Z.commitFiles({branch:Q,message:rh6($),expectedHead:G,changes:H});return N}catch(N){if(!(N instanceof t6)||J>=nh6-1)throw N;await i$(QQ(2000,200,J,2,0.5))}}}function rh6($){let Z=(X)=>{let J=X.slice(0,3).join(", ");return X.length>3?`${J} (+${X.length-3} more)`:J},Q=[];if($.set.size>0)Q.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)Q.push(`delete ${Z([...$.del])}`);let Y=`chore(decofile): ${Q.join("; ")}`;return s81(Y,$.deps.coAuthor)}var nh6=3,KU1;var p48=D(()=>{FA0();xk0();T6();D8();iZ();ck0();KU1=new Map});import{createHmac as n48,randomBytes as sh6,timingSafeEqual as ah6}from"crypto";function t48(){if(ok0)return ok0;let $;try{let Z=E0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return ok0=$?Buffer.from($):sh6(32),ok0}function HU1($){let Z=$.nowMs??Date.now(),Q={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+eh6)/1000)},Y=Buffer.from(JSON.stringify(Q)).toString("base64url"),X=n48("sha256",t48()).update(Y).digest("base64url");return`${Y}.${X}`}function o48($,Z){let Q=$.indexOf(".");if(Q<0)return!1;let Y=$.slice(0,Q),X=Buffer.from($.slice(Q+1)),J=Buffer.from(n48("sha256",t48()).update(Y).digest("base64url"));if(X.length!==J.length||!ah6(X,J))return!1;let G;try{G=JSON.parse(Buffer.from(Y,"base64url").toString())}catch{return!1}let W=Math.floor((Z.nowMs??Date.now())/1000);return G.o===Z.organizationId&&G.m===Z.virtualMcpId&&G.b===Z.branch&&typeof G.e==="number"&&G.e>=W}var eh6=21600000,ok0=null;var r48=D(()=>{F$()});function rk0($){return $&&typeof $==="object"&&!Array.isArray($)?$:null}function $u6($){for(let[Z,Q]of Object.entries($)){if(!Z.startsWith("collections/blog/posts/"))continue;let Y=rk0(Q)?.__resolveType;if(typeof Y==="string"&&Y)return Y}return"blog/loaders/Blogpost.ts"}function s48($){let Z;try{Z=rk0(JSON.parse($))}catch{return $}if(!Z)return $;let Q=$u6(Z),Y={...Z},X=0;for(let[J,G]of Object.entries(Z)){if(!J.startsWith("blog-manager/posts/"))continue;let W=rk0(G),K=W&&rk0(W.post);if(!K)continue;if(K.status==="archived")continue;if(typeof K.slug!=="string"||!K.slug)continue;let F=`collections/blog/posts/${J.slice(19)}`;if(Object.hasOwn(Y,F))continue;Y[F]={name:F,__resolveType:Q,["post"]:{...K,status:"published"}},X++}return X>0?JSON.stringify(Y):$}import{z as Ti}from"zod";function Qu6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&Zu6.test($)}function Q68($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function Y40($){let Z=$.get("decofileScope");return jc($.var.studioContext,Z.organizationId,Z.githubRepo)}function X40($,Z){let Q=Z instanceof Error?Z.message:String(Z);if(Z instanceof t6)return $.json({error:Q},409);let Y=UW(Z);if(Y!==null){let X=Y===404?404:Y===409||Y===422?409:502;return $.json({error:Q},X)}return $.json({error:Q},500)}function Y68(){let $=new Q1;return $.use("/:virtualMcpId/:branch",Z68),$.use("/:virtualMcpId/:branch/*",Z68),$.get("/:virtualMcpId/:branch",async(Z)=>{let Q=Z.get("decofileScope");try{let Y=await Y40(Z),X=await S48(Y,Q.branch,Q.packagePath,{createBranchIfMissing:!!Q.userId}),J={ETag:`"${X.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${X.sha}"`)return Z.body(null,304,J);if(!Q.userId)return Z.body(s48(X.decofile),200,{...J,"content-type":"application/json"});let G=HU1({organizationId:Q.organizationId,virtualMcpId:Q.virtualMcpId,branch:Q.branch});return Z.body(`{"version":${JSON.stringify(X.sha)},"token":${JSON.stringify(G)},"apiHost":${JSON.stringify(Q68(Z))},"decofile":${X.decofile}}`,200,{...J,"content-type":"application/json"})}catch(Y){return X40(Z,Y)}}),$.get("/:virtualMcpId/:branch/meta",async(Z)=>{let Q=Z.get("decofileScope"),Y=Q.packagePath?`${Q.packagePath}/.deco/meta.gen.json`:".deco/meta.gen.json";try{let X=await Y40(Z),J=await X.readFileAtRef(Q.branch,Y);if(J===null){let G=await X.getDefaultBranch();if(G!==Q.branch)J=await X.readFileAtRef(G,Y)}if(J===null)return Z.json({error:"meta.gen.json not committed"},404);return Z.body(J,200,{"content-type":"application/json","Cache-Control":"no-store","Access-Control-Allow-Origin":"*"})}catch(X){return X40(Z,X)}}),$.patch("/:virtualMcpId/:branch",Xu6,async(Z)=>{let Q=Z.get("decofileScope"),Y=Z.var.studioContext,X=Ju6.safeParse(await Z.req.json().catch(()=>null));if(!X.success)return Z.json({error:"Invalid body",details:X.error.issues},400);let J;try{J=o80(X.data)}catch(G){if(G instanceof r80)return Z.json({error:G.message},400);throw G}for(let G of[...Object.keys(J.set??{}),...J.delete??[]])try{bk0(G)}catch(W){let K=W instanceof Error?W.message:String(W);return Z.json({error:K},400)}for(let[G,W]of Object.entries(J.set??{})){if(typeof W!=="object"||W===null||Array.isArray(W))return Z.json({error:`Block "${G}" must be a JSON object`},400);if(iF1(G))return Z.json({error:`Block key "${G}" collides with a framework resolver module and cannot be written`},400)}try{let G=await Y40(Z),W=await i48(`${Q.organizationId}/${Q.virtualMcpId}/${Q.branch}`,{client:G,branch:Q.branch,packagePath:Q.packagePath,coAuthor:wi(Y)},J),K=HU1({organizationId:Q.organizationId,virtualMcpId:Q.virtualMcpId,branch:Q.branch});return Z.json({version:W,token:K,apiHost:Q68(Z)})}catch(G){return X40(Z,G)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let Q=Z.get("decofileScope");try{let Y=await Y40(Z),X=await Y.getDefaultBranch();if(X===Q.branch)return Z.json({error:"Branch is already the default branch"},400);let J=`chore(decofile): publish ${Q.branch}`;try{let G;try{G=await Y.mergeBranches(X,Q.branch,J)}catch(W){if(UW(W)!==409)throw W;await pk0(Y,Q.branch,X),G=await Y.mergeBranches(X,Q.branch,J)}return G?Z.json({result:"merged",sha:G}):Z.json({result:"up-to-date"})}catch(G){if(UW(G)===409)return Z.json({error:"merge-conflict"},409);if(UW(G)===405){let K=await Y.findOpenChangeRequest(X,Q.branch)??await Y.createChangeRequest({base:X,head:Q.branch,title:`Publish ${Q.branch}`});return Z.json({result:"pull-request",number:K.number,url:K.url})}throw G}}catch(Y){return X40(Z,Y)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let Q=Z.get("decofileScope");try{let Y=await Y40(Z),X=await Y.getDefaultBranch();if(X===Q.branch)return Z.json({baseBranch:X,aheadBy:0,behindBy:0,lastCommitAt:null});try{let[{aheadBy:J,behindBy:G},W]=await Promise.all([Y.compare(X,Q.branch),Y.getBranch(Q.branch)]);return Z.json({baseBranch:X,aheadBy:J,behindBy:G,lastCommitAt:W?.committedAt??null})}catch(J){if(UW(J)===404)return Z.json({baseBranch:X,aheadBy:0,behindBy:0,lastCommitAt:null});throw J}}catch(Y){return X40(Z,Y)}}),$}var Zu6,a48=500,e48=1048576,$68=1024,Yu6=8388608,Xu6,Ju6,Z68;var X68=D(()=>{q20();xk0();G8();fW();xF1();vk0();JU1();iZ();p48();r48();QU1();ck0();gF();Zu6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;Xu6=I5({maxSize:Yu6,onError:($)=>$.json({error:"Payload too large"},413)}),Ju6=Ti.object({set:Ti.record(Ti.string(),Ti.unknown()).optional(),delete:Ti.array(Ti.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}).refine(($)=>Object.keys($.set??{}).length+($.delete?.length??0)<=a48,{message:`Patch cannot touch more than ${a48} blocks`}).refine(($)=>Object.values($.set??{}).every((Z)=>JSON.stringify(Z).length<=e48),{message:`Each block must be at most ${e48} bytes`}).refine(($)=>[...Object.keys($.set??{}),...$.delete??[]].every((Z)=>Z.length<=$68),{message:`Each block key must be at most ${$68} characters`}),Z68=_k0(async($,Z)=>{let Q=$.var.studioContext,Y=Q.organization;if(!Y)return $.json({error:"Organization scope required"},500);let X=$.req.param("virtualMcpId"),J=$.req.param("branch");if(!X||!J)return $.json({error:"virtualMcpId and branch are required"},400);if(!Qu6(J))return $.json({error:`Invalid branch name: ${J}`},400);let G=Q.auth?.user?.id??null;if(!G){let B=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!B||!o48(B,{organizationId:Y.id,virtualMcpId:X,branch:J}))return $.json({error:"Unauthorized"},401)}if(!await QW(Q,Y.id,"cms"))return $.json({error:"This organization's plan does not include the CMS",code:"feature_not_in_plan"},403);let W=await Q.storage.virtualMcps.findById(X);if(!W||W.organization_id!==Y.id)return $.json({error:"Virtual MCP not found"},404);let K=W.metadata??null;if(!Qm(K))return $.json({error:"Project has no preview server configured"},404);let F=W.connections?.map((B)=>B.connection_id)??[],U=Z40(K,F);if(!U)return $.json({error:"Project has no GitHub repository"},404);let N=K?.runtime;return $.set("decofileScope",{organizationId:Y.id,virtualMcpId:X,branch:J,packagePath:N?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:U,userId:G}),Z()})});var J68=($)=>{let Z=new Q1;if(Z.use("*",td),Z.use("*",_e$),Z.route("/",lV0()),Z.route("/",O08()),Z.route("/",$08()),Z.route("/",T88()),Z.route("/",D88()),Z.route("/",P88()),Z.route("/",w88()),Z.route("/",kk0()),Z.route("/tools",S88()),Z.route("/",I88()),Z.route("/",n$8({kvStorage:$.kvStorage})),Z.route("/",i$8()),Z.route("/fs",G88({getConnection:$.getNatsConnection})),Z.route("/sandbox",m48()),Z.route("/decofile",Y68()),Z.route("/",N88()),Z.route("/",K88()),Z.route("/deco-sites",mV0()),Z.route("/hosting",me$()),Z.route("/monitor",re$()),Z.route("/sso",fV0()),Z.route("/",Sk0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",ge$()),$.mountDevAssets)Z.route("/dev-assets",nV0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",gr$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",F88()),Z.route("/mcp",vR0()),Z.route("/mcp/self",qk0()),Z.route("/mcp",fR0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var G68=D(()=>{G8();ve$();RV0();he$();QH1();de$();se$();tV0();af();sK1();WH1();p$8();t$8();W88();H88();u10();iK1();yR0();MF1();U88();B88();L88();j88();kF1();R88();V88();SF1();C88();CF1();bR0();d48();X68()});function Gu6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var Wu6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},W68=()=>{let $=new Q1;return $.use("*",Wu6),$.get("/",async(Z)=>{let Q=E0(),Y=Q.decoSupabaseUrl,X=Q.decoSupabaseServiceKey;if(!Y||!X)return Z.json({apps:[]});try{let J=await lJ(Y,X,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:Gu6(J)})}catch(J){return console.error("[deco-apps] GET error:",J),Z.json({error:"Failed to fetch apps"},502)}}),$};var K68=D(()=>{G8();F$();kI0()});import{z as b1}from"zod";function iU($,Z="invalid_request_error",Q=null,Y=null){return{error:{message:$,type:Z,param:Q,code:Y}}}function wu6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let Q=$.substring(0,Z),Y=$.substring(Z+1);if(!Q||!Y)return null;return{credentialId:Q,modelId:Y}}function ju6($,Z,Q){try{return JSON.parse($)}catch{throw new U68(`Invalid JSON in tool call arguments for function '${Q}' (tool_call_id: ${Z}): ${$}`)}}function Eu6($){let Z={};for(let Q of $)if(Q.role==="assistant"&&Q.tool_calls)for(let Y of Q.tool_calls)Z[Y.id]=Y.function.name;return $.map((Q)=>{switch(Q.role){case"system":return{role:"system",content:Q.content};case"user":if(typeof Q.content==="string")return{role:"user",content:Q.content};return{role:"user",content:Q.content.map((X)=>{if(X.type==="text")return{type:"text",text:X.text};return{type:"image",image:X.image_url.url}})};case"assistant":if(Q.tool_calls&&Q.tool_calls.length>0)return{role:"assistant",content:Q.tool_calls.map((X)=>({type:"tool-call",toolCallId:X.id,toolName:X.function.name,input:ju6(X.function.arguments,X.id,X.function.name)}))};return{role:"assistant",content:Q.content??""};case"tool":let Y=Z[Q.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:Q.tool_call_id,toolName:Y,output:{type:"text",value:Q.content}}]}}})}function zu6($){let Z=$.map((Q)=>{let Y=Q.function.parameters?AF(Q.function.parameters):AF({type:"object",properties:{}});return[Q.function.name,c$({description:Q.function.description,inputSchema:Y})]});return Object.fromEntries(Z)}function Pu6($){if(!$)return;return{openai:{response_format:$}}}function Au6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function H68($,Z,Q,Y,X,J){let G={model:$,instructions:Z.filter((W)=>W.role==="system"),messages:Z.filter((W)=>W.role!=="system"),tools:Q,temperature:Y.temperature,maxOutputTokens:Y.max_tokens,topP:Y.top_p,frequencyPenalty:Y.frequency_penalty,presencePenalty:Y.presence_penalty,stopSequences:Y.stop?Array.isArray(Y.stop)?Y.stop:[Y.stop]:void 0,abortSignal:J};return X?{...G,providerOptions:X}:G}function F68($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var Ku6=256,Hu6,Fu6,Uu6,Nu6,Bu6,Ou6,Du6,Lu6,U68,N68,B68;var O68=D(()=>{v4();G8();Li();NH();Hu6=b1.object({type:b1.literal("function"),function:b1.object({name:b1.string(),description:b1.string().optional(),parameters:b1.record(b1.string(),b1.unknown()).optional()})}),Fu6=b1.object({id:b1.string(),type:b1.literal("function"),function:b1.object({name:b1.string(),arguments:b1.string()})}),Uu6=b1.discriminatedUnion("role",[b1.object({role:b1.literal("system"),content:b1.string(),name:b1.string().optional()}),b1.object({role:b1.literal("user"),content:b1.union([b1.string(),b1.array(b1.union([b1.object({type:b1.literal("text"),text:b1.string()}),b1.object({type:b1.literal("image_url"),image_url:b1.object({url:b1.string(),detail:b1.string().optional()})})]))]),name:b1.string().optional()}),b1.object({role:b1.literal("assistant"),content:b1.string().nullable().optional(),name:b1.string().optional(),tool_calls:b1.array(Fu6).optional()}),b1.object({role:b1.literal("tool"),content:b1.string(),tool_call_id:b1.string()})]),Nu6=b1.object({type:b1.literal("text")}),Bu6=b1.object({type:b1.literal("json_object")}),Ou6=b1.object({type:b1.literal("json_schema"),json_schema:b1.object({name:b1.string(),description:b1.string().optional(),schema:b1.record(b1.string(),b1.unknown()),strict:b1.boolean().optional()})}),Du6=b1.union([Nu6,Bu6,Ou6]),Lu6=b1.object({model:b1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:b1.array(Uu6),stream:b1.boolean().optional().default(!1),temperature:b1.number().min(0).max(2).optional(),max_tokens:b1.number().positive().optional(),top_p:b1.number().min(0).max(1).optional(),frequency_penalty:b1.number().min(-2).max(2).optional(),presence_penalty:b1.number().min(-2).max(2).optional(),stop:b1.union([b1.string(),b1.array(b1.string())]).optional(),tools:b1.array(Hu6).optional(),tool_choice:b1.union([b1.literal("auto"),b1.literal("none"),b1.literal("required"),b1.object({type:b1.literal("function"),function:b1.object({name:b1.string()})})]).optional(),response_format:Du6.optional(),user:b1.string().optional()});U68=class U68 extends Error{constructor($){super($);this.name="MessageConversionError"}};N68=new Q1;N68.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),Q=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(iU("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(iU("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==Q)return $.json(iU("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Y=await $.req.json(),X=Lu6.safeParse(Y);if(!X.success){let w=X.error.issues[0]??{message:"Invalid request",path:[]};return $.json(iU(`Invalid request: ${w.message}`,"invalid_request_error",w.path.length>0?w.path.join("."):null),400)}let J=X.data,G=wu6(J.model);if(!G)return $.json(iU("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:W}=G,{modelId:K}=G;if(!W){let j=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((E)=>xz(E.providerId));if(!j)return $.json(iU("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);W=j.id}let H;try{H=await Z.aiProviders.activate(W,Z.organization.id)}catch{return $.json(iU(`AI provider credential not found or inaccessible: ${W}`,"invalid_request_error","model"),404)}let F=H.aiSdk.languageModel(K),U=Eu6(J.messages),N=J.tools?zu6(J.tools):void 0,B=Pu6(J.response_format),O=Au6(),L=Math.floor(Date.now()/1000);if(J.stream)return bO($,async(w)=>{let j=H68(F,U,N,J,B,$.req.raw.signal);try{let E=$m(j),z=!1,T=0,P="",A=async()=>{if(P.length===0)return;let q=P;P="",await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:J.model,choices:[{index:0,delta:{content:q},finish_reason:null}]})})};for await(let q of E.stream){if(!z&&(q.type==="text-delta"||q.type==="tool-call"))await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:J.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(q.type==="text-delta"){if(P+=q.text,P.length>=Ku6)await A()}else if(q.type==="tool-call"){await A();let x=T++;await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:J.model,choices:[{index:0,delta:{tool_calls:[{index:x,id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.input)}}]},finish_reason:null}]})})}else if(q.type==="finish")await A(),await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:J.model,choices:[{index:0,delta:{},finish_reason:F68(q.finishReason)}],usage:q.totalUsage?{prompt_tokens:q.totalUsage.inputTokens??0,completion_tokens:q.totalUsage.outputTokens??0,total_tokens:q.totalUsage.totalTokens??0}:void 0})})}await A(),await w.writeSSE({data:"[DONE]"})}catch(E){let z=E;console.error("[openai-compat:stream] Error:",z.message),await w.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let w=H68(F,U,N,J,B,$.req.raw.signal),j=await FU(w),E={role:"assistant",content:j.text||null};if(j.toolCalls&&j.toolCalls.length>0)E.tool_calls=j.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),E.content=null;return $.json({id:O,object:"chat.completion",created:L,model:J.model,choices:[{index:0,message:E,finish_reason:F68(j.finishReason)}],usage:{prompt_tokens:j.usage?.inputTokens??0,completion_tokens:j.usage?.outputTokens??0,total_tokens:j.usage?.totalTokens??0}})}}catch(Y){let X=Y;if(X.name==="AbortError")return $.json(iU("Request aborted","invalid_request_error"),400);if(X.name==="MessageConversionError")return $.json(iU(X.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",X.message,X.stack),$.json(iU(X.message,"server_error"),500)}});B68=N68});function Tu6($){if(typeof $!=="object"||$===null)return!1;let Q=$.githubRepo?.url;return typeof Q==="string"&&Q.length>0}function D68(){let $=new Q1;return $.use("*",async(Z,Q)=>{await Q(),Z.header("Cache-Control","private, no-store"),Z.header("Vary","Cookie")}),$.get("/",async(Z)=>{let Q=Z.get("studioContext"),Y=p0(Q);if(!Y)return Z.json({error:"Authentication required"},401);let J=(Z.req.query("site")??"").trim().toLowerCase();if(!WZ(J))return Z.json({error:"Invalid site slug"},400);let G=await Q.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.id as id","organization.slug as slug","organization.name as name","organization.metadata as metadata"]).where("member.userId","=",Y).execute(),W=[];for(let H of G){if(!H.slug||P9(H))continue;let F=await Q.storage.virtualMcps.list(H.id);for(let U of F){if(la(U)!==J)continue;if(!Tu6(U.metadata))continue;W.push({orgSlug:H.slug,orgName:H.name??H.slug,project:{id:U.id,title:U.title,icon:U.icon??null}})}}let K={matches:W};return Z.json(K)}),$}var L68=D(()=>{G8();fG()});var j68;var w68=D(()=>{j68={name:"decocms",version:"4.402.1",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^4.0.58","@ai-sdk/google":"^4.0.76","@ai-sdk/openai":"^4.0.71","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^3.1.0","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^4.0.17","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^7.0.107","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});function Mu6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??qu6}}var E68,qu6="https://ph.studio.decocms.com",z68;var P68=D(()=>{G8();Fr();Zf();E9();F$();CK1();w68();E68=new Q1;E68.get("/",($)=>{let Z={version:j68.version,theme:H$$(),...RK().logo&&{logo:RK().logo},...WO()&&{internalUrl:lc1()},...E0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!E0().firecrawlApiKey,hostingEnabled:!!E0().controlplaneRestUrl&&!!E0().controlplaneServiceToken,hostingControlPlaneGa:E0().hostingControlPlaneGa,monitorEnabled:!!E0().clickhouseAnalyticsUrl&&!!E0().clickhouseAnalyticsPassword,monitorGa:E0().monitorGa,plansEnabled:E0().plansEnabled,auth:Va$(),posthog:Mu6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:pO()}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});z68=E68});function Ny($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function FU1($){return(Ny($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((Q)=>Q.charAt(0).toUpperCase()+Q.slice(1)).join(" ")}function A68($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(Ny($))}&sz=${Z}`}function Iu6($,Z){let Q=$.trim();if(Q.length<=Z)return Q;let Y=Q.slice(0,Z-1),X=Y.lastIndexOf(" ");return`${(X>Z*0.6?Y.slice(0,X):Y).trimEnd()}\u2026`}function T68($){let{brand:Z,domain:Q,score:Y}=$,X=typeof Y==="number"?`${Z} commerce report \u2014 ${Math.round(Y)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=Iu6(`How does ${Q} really perform? See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,200);return{title:X,description:J}}import{z as L$}from"zod";var Vu6,R68;var q68=D(()=>{Vu6=L$.object({check_id:L$.string(),title:L$.string(),description:L$.string().optional(),impact:L$.string().optional(),why:L$.string().optional(),category:L$.string(),severity:L$.string(),value_band:L$.string().optional(),value_driver:L$.string().optional(),controllability:L$.string().optional(),pages:L$.array(L$.string()),tasks:L$.array(L$.string()),evidence:L$.string(),sample_scope:L$.string().optional(),sources:L$.array(L$.string())}),R68=L$.object({domain:L$.string(),brand:L$.string(),favicon:L$.string().optional(),scanned_at:L$.string().nullable(),lang:L$.string(),score:L$.number().nullable(),band:L$.string().nullable(),totals:L$.object({measured:L$.number(),registry_total:L$.number(),passed:L$.number(),failed:L$.number(),blocked:L$.number()}),buckets:L$.array(L$.object({id:L$.enum(["critical","important","worth"]),label:L$.string(),items:L$.array(Vu6)})),passing:L$.object({count:L$.number(),items:L$.array(L$.object({check_id:L$.string(),title:L$.string()}))}),not_measured:L$.object({count:L$.number(),groups:L$.array(L$.object({reason:L$.string(),label:L$.string(),count:L$.number(),checks:L$.array(L$.string())}))}),categories:L$.array(L$.object({key:L$.string(),label:L$.string(),score:L$.number().nullable(),band:L$.string().nullable(),pass:L$.number(),fail:L$.number()})),screenshots:L$.array(L$.object({url:L$.string(),page_type:L$.string().optional(),viewport:L$.enum(["desktop","mobile"]),image_url:L$.string()}))})});function M68($,Z,Q){let Y=Q?`?${new URLSearchParams({lang:Q}).toString()}`:"";return`${uK({})}/api/v2/public/diagnostics/${encodeURIComponent($)}/onepager${Z}${Y}`}async function sk0($,Z={}){let Q=await fetch(M68($,"",Z.lang),{headers:{Accept:"application/json"},signal:Z.signal});if(Q.status===404)return null;if(!Q.ok)throw Error(`onepager read HTTP ${Q.status}`);return R68.parse(await Q.json())}async function I68($,Z={}){let Q=await fetch(M68($,".md",Z.lang),{headers:{Accept:"text/markdown"},signal:Z.signal});if(Q.status===404)return null;if(!Q.ok)throw Error(`onepager markdown HTTP ${Q.status}`);return Q.text()}var UU1=D(()=>{q68();ww()});import{join as V68}from"path";async function Su6($){try{let Z=await sk0($,{signal:AbortSignal.timeout(ku6)});if(!Z?.scanned_at)return null;return{brand:Z.brand.trim()||FU1($),...Z.score!==null?{score:Z.score}:{}}}catch{return null}}function iJ($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}function Cu6($,Z){let Q=Ny($),Y=Z?.brand?.trim()||FU1(Q),X=A68(Q,128),G=`${(E0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(Q)}`,{title:W,description:K}=T68({brand:Y,domain:Q,score:Z?.score}),H=`${G}/og.png`,F=`${Y} commerce report by decocms`;return[`<title>${iJ(W)}</title>`,`<meta name="description" content="${iJ(K)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${iJ(W)}" />`,`<meta property="og:description" content="${iJ(K)}" />`,`<meta property="og:url" content="${iJ(G)}" />`,`<meta property="og:image" content="${iJ(H)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${iJ(F)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${iJ(W)}" />`,`<meta name="twitter:description" content="${iJ(K)}" />`,`<meta name="twitter:image" content="${iJ(H)}" />`,`<meta name="twitter:image:alt" content="${iJ(F)}" />`,`<link rel="canonical" href="${iJ(G)}" />`,`<link rel="alternate" type="text/markdown" href="${iJ(G)}.md" />`,`<link rel="icon" href="${iJ(X)}" sizes="any" />`].join(`
|
|
3706
|
+
`;await V48(Z.repo,L);let w=O[0]??`${lk0(Y)}/${pF1(N)}.json`;H.push({path:w,content:L});let j=w.slice(w.lastIndexOf("/")+1,-5);F.set(w,{stem:j,content:L});for(let E of O.slice(1))H.push({path:E,deleted:!0}),F.delete(E)}for(let N of $.del)for(let B of $U1(K,N))H.push({path:B,deleted:!0}),F.delete(B);if(H.length===0)return G;let U=Y?`${Y}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(W.some((N)=>N.type==="blob"&&N.path===U)){let N=await k48(Z,F.values(),X),{decofile:B,skipped:O}=t80(N);if(O.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:cK(Z.repo),branch:Q,packagePath:Y,blocks:O.map((L)=>L.key)});H.push({path:U,content:B})}try{let{sha:N}=await Z.commitFiles({branch:Q,message:rh6($),expectedHead:G,changes:H});return N}catch(N){if(!(N instanceof t6)||J>=nh6-1)throw N;await i$(QQ(2000,200,J,2,0.5))}}}function rh6($){let Z=(X)=>{let J=X.slice(0,3).join(", ");return X.length>3?`${J} (+${X.length-3} more)`:J},Q=[];if($.set.size>0)Q.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)Q.push(`delete ${Z([...$.del])}`);let Y=`chore(decofile): ${Q.join("; ")}`;return s81(Y,$.deps.coAuthor)}var nh6=3,KU1;var p48=D(()=>{FA0();xk0();T6();D8();iZ();ck0();KU1=new Map});import{createHmac as n48,randomBytes as sh6,timingSafeEqual as ah6}from"crypto";function t48(){if(ok0)return ok0;let $;try{let Z=E0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return ok0=$?Buffer.from($):sh6(32),ok0}function HU1($){let Z=$.nowMs??Date.now(),Q={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+eh6)/1000)},Y=Buffer.from(JSON.stringify(Q)).toString("base64url"),X=n48("sha256",t48()).update(Y).digest("base64url");return`${Y}.${X}`}function o48($,Z){let Q=$.indexOf(".");if(Q<0)return!1;let Y=$.slice(0,Q),X=Buffer.from($.slice(Q+1)),J=Buffer.from(n48("sha256",t48()).update(Y).digest("base64url"));if(X.length!==J.length||!ah6(X,J))return!1;let G;try{G=JSON.parse(Buffer.from(Y,"base64url").toString())}catch{return!1}let W=Math.floor((Z.nowMs??Date.now())/1000);return G.o===Z.organizationId&&G.m===Z.virtualMcpId&&G.b===Z.branch&&typeof G.e==="number"&&G.e>=W}var eh6=21600000,ok0=null;var r48=D(()=>{F$()});function rk0($){return $&&typeof $==="object"&&!Array.isArray($)?$:null}function $u6($){for(let[Z,Q]of Object.entries($)){if(!Z.startsWith("collections/blog/posts/"))continue;let Y=rk0(Q)?.__resolveType;if(typeof Y==="string"&&Y)return Y}return"blog/loaders/Blogpost.ts"}function s48($){let Z;try{Z=rk0(JSON.parse($))}catch{return $}if(!Z)return $;let Q=$u6(Z),Y={...Z},X=0;for(let[J,G]of Object.entries(Z)){if(!J.startsWith("blog-manager/posts/"))continue;let W=rk0(G),K=W&&rk0(W.post);if(!K)continue;if(K.status==="archived")continue;if(typeof K.slug!=="string"||!K.slug)continue;let F=`collections/blog/posts/${J.slice(19)}`;if(Object.hasOwn(Y,F))continue;Y[F]={name:F,__resolveType:Q,["post"]:{...K,status:"published"}},X++}return X>0?JSON.stringify(Y):$}import{z as Ti}from"zod";function Qu6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&Zu6.test($)}function Q68($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function Y40($){let Z=$.get("decofileScope");return jc($.var.studioContext,Z.organizationId,Z.githubRepo)}function X40($,Z){let Q=Z instanceof Error?Z.message:String(Z);if(Z instanceof t6)return $.json({error:Q},409);let Y=UW(Z);if(Y!==null){let X=Y===404?404:Y===409||Y===422?409:502;return $.json({error:Q},X)}return $.json({error:Q},500)}function Y68(){let $=new Q1;return $.use("/:virtualMcpId/:branch",Z68),$.use("/:virtualMcpId/:branch/*",Z68),$.get("/:virtualMcpId/:branch",async(Z)=>{let Q=Z.get("decofileScope");try{let Y=await Y40(Z),X=await S48(Y,Q.branch,Q.packagePath,{createBranchIfMissing:!!Q.userId}),J={ETag:`"${X.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${X.sha}"`)return Z.body(null,304,J);if(!Q.userId)return Z.body(s48(X.decofile),200,{...J,"content-type":"application/json"});let G=HU1({organizationId:Q.organizationId,virtualMcpId:Q.virtualMcpId,branch:Q.branch});return Z.body(`{"version":${JSON.stringify(X.sha)},"token":${JSON.stringify(G)},"apiHost":${JSON.stringify(Q68(Z))},"decofile":${X.decofile}}`,200,{...J,"content-type":"application/json"})}catch(Y){return X40(Z,Y)}}),$.get("/:virtualMcpId/:branch/meta",async(Z)=>{let Q=Z.get("decofileScope"),Y=Q.packagePath?`${Q.packagePath}/.deco/meta.gen.json`:".deco/meta.gen.json";try{let X=await Y40(Z),J=await X.readFileAtRef(Q.branch,Y);if(J===null){let G=await X.getDefaultBranch();if(G!==Q.branch)J=await X.readFileAtRef(G,Y)}if(J===null)return Z.json({error:"meta.gen.json not committed"},404);return Z.body(J,200,{"content-type":"application/json","Cache-Control":"no-store","Access-Control-Allow-Origin":"*"})}catch(X){return X40(Z,X)}}),$.patch("/:virtualMcpId/:branch",Xu6,async(Z)=>{let Q=Z.get("decofileScope"),Y=Z.var.studioContext,X=Ju6.safeParse(await Z.req.json().catch(()=>null));if(!X.success)return Z.json({error:"Invalid body",details:X.error.issues},400);let J;try{J=o80(X.data)}catch(G){if(G instanceof r80)return Z.json({error:G.message},400);throw G}for(let G of[...Object.keys(J.set??{}),...J.delete??[]])try{bk0(G)}catch(W){let K=W instanceof Error?W.message:String(W);return Z.json({error:K},400)}for(let[G,W]of Object.entries(J.set??{})){if(typeof W!=="object"||W===null||Array.isArray(W))return Z.json({error:`Block "${G}" must be a JSON object`},400);if(iF1(G))return Z.json({error:`Block key "${G}" collides with a framework resolver module and cannot be written`},400)}try{let G=await Y40(Z),W=await i48(`${Q.organizationId}/${Q.virtualMcpId}/${Q.branch}`,{client:G,branch:Q.branch,packagePath:Q.packagePath,coAuthor:wi(Y)},J),K=HU1({organizationId:Q.organizationId,virtualMcpId:Q.virtualMcpId,branch:Q.branch});return Z.json({version:W,token:K,apiHost:Q68(Z)})}catch(G){return X40(Z,G)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let Q=Z.get("decofileScope");try{let Y=await Y40(Z),X=await Y.getDefaultBranch();if(X===Q.branch)return Z.json({error:"Branch is already the default branch"},400);let J=`chore(decofile): publish ${Q.branch}`;try{let G;try{G=await Y.mergeBranches(X,Q.branch,J)}catch(W){if(UW(W)!==409)throw W;await pk0(Y,Q.branch,X),G=await Y.mergeBranches(X,Q.branch,J)}return G?Z.json({result:"merged",sha:G}):Z.json({result:"up-to-date"})}catch(G){if(UW(G)===409)return Z.json({error:"merge-conflict"},409);if(UW(G)===405){let K=await Y.findOpenChangeRequest(X,Q.branch)??await Y.createChangeRequest({base:X,head:Q.branch,title:`Publish ${Q.branch}`});return Z.json({result:"pull-request",number:K.number,url:K.url})}throw G}}catch(Y){return X40(Z,Y)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let Q=Z.get("decofileScope");try{let Y=await Y40(Z),X=await Y.getDefaultBranch();if(X===Q.branch)return Z.json({baseBranch:X,aheadBy:0,behindBy:0,lastCommitAt:null});try{let[{aheadBy:J,behindBy:G},W]=await Promise.all([Y.compare(X,Q.branch),Y.getBranch(Q.branch)]);return Z.json({baseBranch:X,aheadBy:J,behindBy:G,lastCommitAt:W?.committedAt??null})}catch(J){if(UW(J)===404)return Z.json({baseBranch:X,aheadBy:0,behindBy:0,lastCommitAt:null});throw J}}catch(Y){return X40(Z,Y)}}),$}var Zu6,a48=500,e48=1048576,$68=1024,Yu6=8388608,Xu6,Ju6,Z68;var X68=D(()=>{q20();xk0();G8();fW();xF1();vk0();JU1();iZ();p48();r48();QU1();ck0();gF();Zu6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;Xu6=I5({maxSize:Yu6,onError:($)=>$.json({error:"Payload too large"},413)}),Ju6=Ti.object({set:Ti.record(Ti.string(),Ti.unknown()).optional(),delete:Ti.array(Ti.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}).refine(($)=>Object.keys($.set??{}).length+($.delete?.length??0)<=a48,{message:`Patch cannot touch more than ${a48} blocks`}).refine(($)=>Object.values($.set??{}).every((Z)=>JSON.stringify(Z).length<=e48),{message:`Each block must be at most ${e48} bytes`}).refine(($)=>[...Object.keys($.set??{}),...$.delete??[]].every((Z)=>Z.length<=$68),{message:`Each block key must be at most ${$68} characters`}),Z68=_k0(async($,Z)=>{let Q=$.var.studioContext,Y=Q.organization;if(!Y)return $.json({error:"Organization scope required"},500);let X=$.req.param("virtualMcpId"),J=$.req.param("branch");if(!X||!J)return $.json({error:"virtualMcpId and branch are required"},400);if(!Qu6(J))return $.json({error:`Invalid branch name: ${J}`},400);let G=Q.auth?.user?.id??null;if(!G){let B=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!B||!o48(B,{organizationId:Y.id,virtualMcpId:X,branch:J}))return $.json({error:"Unauthorized"},401)}if(!await QW(Q,Y.id,"cms"))return $.json({error:"This organization's plan does not include the CMS",code:"feature_not_in_plan"},403);let W=await Q.storage.virtualMcps.findById(X);if(!W||W.organization_id!==Y.id)return $.json({error:"Virtual MCP not found"},404);let K=W.metadata??null;if(!Qm(K))return $.json({error:"Project has no preview server configured"},404);let F=W.connections?.map((B)=>B.connection_id)??[],U=Z40(K,F);if(!U)return $.json({error:"Project has no GitHub repository"},404);let N=K?.runtime;return $.set("decofileScope",{organizationId:Y.id,virtualMcpId:X,branch:J,packagePath:N?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:U,userId:G}),Z()})});var J68=($)=>{let Z=new Q1;if(Z.use("*",td),Z.use("*",_e$),Z.route("/",lV0()),Z.route("/",O08()),Z.route("/",$08()),Z.route("/",T88()),Z.route("/",D88()),Z.route("/",P88()),Z.route("/",w88()),Z.route("/",kk0()),Z.route("/tools",S88()),Z.route("/",I88()),Z.route("/",n$8({kvStorage:$.kvStorage})),Z.route("/",i$8()),Z.route("/fs",G88({getConnection:$.getNatsConnection})),Z.route("/sandbox",m48()),Z.route("/decofile",Y68()),Z.route("/",N88()),Z.route("/",K88()),Z.route("/deco-sites",mV0()),Z.route("/hosting",me$()),Z.route("/monitor",re$()),Z.route("/sso",fV0()),Z.route("/",Sk0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",ge$()),$.mountDevAssets)Z.route("/dev-assets",nV0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",gr$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",F88()),Z.route("/mcp",vR0()),Z.route("/mcp/self",qk0()),Z.route("/mcp",fR0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var G68=D(()=>{G8();ve$();RV0();he$();QH1();de$();se$();tV0();af();sK1();WH1();p$8();t$8();W88();H88();u10();iK1();yR0();MF1();U88();B88();L88();j88();kF1();R88();V88();SF1();C88();CF1();bR0();d48();X68()});function Gu6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var Wu6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},W68=()=>{let $=new Q1;return $.use("*",Wu6),$.get("/",async(Z)=>{let Q=E0(),Y=Q.decoSupabaseUrl,X=Q.decoSupabaseServiceKey;if(!Y||!X)return Z.json({apps:[]});try{let J=await lJ(Y,X,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:Gu6(J)})}catch(J){return console.error("[deco-apps] GET error:",J),Z.json({error:"Failed to fetch apps"},502)}}),$};var K68=D(()=>{G8();F$();kI0()});import{z as b1}from"zod";function iU($,Z="invalid_request_error",Q=null,Y=null){return{error:{message:$,type:Z,param:Q,code:Y}}}function wu6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let Q=$.substring(0,Z),Y=$.substring(Z+1);if(!Q||!Y)return null;return{credentialId:Q,modelId:Y}}function ju6($,Z,Q){try{return JSON.parse($)}catch{throw new U68(`Invalid JSON in tool call arguments for function '${Q}' (tool_call_id: ${Z}): ${$}`)}}function Eu6($){let Z={};for(let Q of $)if(Q.role==="assistant"&&Q.tool_calls)for(let Y of Q.tool_calls)Z[Y.id]=Y.function.name;return $.map((Q)=>{switch(Q.role){case"system":return{role:"system",content:Q.content};case"user":if(typeof Q.content==="string")return{role:"user",content:Q.content};return{role:"user",content:Q.content.map((X)=>{if(X.type==="text")return{type:"text",text:X.text};return{type:"image",image:X.image_url.url}})};case"assistant":if(Q.tool_calls&&Q.tool_calls.length>0)return{role:"assistant",content:Q.tool_calls.map((X)=>({type:"tool-call",toolCallId:X.id,toolName:X.function.name,input:ju6(X.function.arguments,X.id,X.function.name)}))};return{role:"assistant",content:Q.content??""};case"tool":let Y=Z[Q.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:Q.tool_call_id,toolName:Y,output:{type:"text",value:Q.content}}]}}})}function zu6($){let Z=$.map((Q)=>{let Y=Q.function.parameters?AF(Q.function.parameters):AF({type:"object",properties:{}});return[Q.function.name,c$({description:Q.function.description,inputSchema:Y})]});return Object.fromEntries(Z)}function Pu6($){if(!$)return;return{openai:{response_format:$}}}function Au6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function H68($,Z,Q,Y,X,J){let G={model:$,instructions:Z.filter((W)=>W.role==="system"),messages:Z.filter((W)=>W.role!=="system"),tools:Q,temperature:Y.temperature,maxOutputTokens:Y.max_tokens,topP:Y.top_p,frequencyPenalty:Y.frequency_penalty,presencePenalty:Y.presence_penalty,stopSequences:Y.stop?Array.isArray(Y.stop)?Y.stop:[Y.stop]:void 0,abortSignal:J};return X?{...G,providerOptions:X}:G}function F68($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var Ku6=256,Hu6,Fu6,Uu6,Nu6,Bu6,Ou6,Du6,Lu6,U68,N68,B68;var O68=D(()=>{v4();G8();Li();NH();Hu6=b1.object({type:b1.literal("function"),function:b1.object({name:b1.string(),description:b1.string().optional(),parameters:b1.record(b1.string(),b1.unknown()).optional()})}),Fu6=b1.object({id:b1.string(),type:b1.literal("function"),function:b1.object({name:b1.string(),arguments:b1.string()})}),Uu6=b1.discriminatedUnion("role",[b1.object({role:b1.literal("system"),content:b1.string(),name:b1.string().optional()}),b1.object({role:b1.literal("user"),content:b1.union([b1.string(),b1.array(b1.union([b1.object({type:b1.literal("text"),text:b1.string()}),b1.object({type:b1.literal("image_url"),image_url:b1.object({url:b1.string(),detail:b1.string().optional()})})]))]),name:b1.string().optional()}),b1.object({role:b1.literal("assistant"),content:b1.string().nullable().optional(),name:b1.string().optional(),tool_calls:b1.array(Fu6).optional()}),b1.object({role:b1.literal("tool"),content:b1.string(),tool_call_id:b1.string()})]),Nu6=b1.object({type:b1.literal("text")}),Bu6=b1.object({type:b1.literal("json_object")}),Ou6=b1.object({type:b1.literal("json_schema"),json_schema:b1.object({name:b1.string(),description:b1.string().optional(),schema:b1.record(b1.string(),b1.unknown()),strict:b1.boolean().optional()})}),Du6=b1.union([Nu6,Bu6,Ou6]),Lu6=b1.object({model:b1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:b1.array(Uu6),stream:b1.boolean().optional().default(!1),temperature:b1.number().min(0).max(2).optional(),max_tokens:b1.number().positive().optional(),top_p:b1.number().min(0).max(1).optional(),frequency_penalty:b1.number().min(-2).max(2).optional(),presence_penalty:b1.number().min(-2).max(2).optional(),stop:b1.union([b1.string(),b1.array(b1.string())]).optional(),tools:b1.array(Hu6).optional(),tool_choice:b1.union([b1.literal("auto"),b1.literal("none"),b1.literal("required"),b1.object({type:b1.literal("function"),function:b1.object({name:b1.string()})})]).optional(),response_format:Du6.optional(),user:b1.string().optional()});U68=class U68 extends Error{constructor($){super($);this.name="MessageConversionError"}};N68=new Q1;N68.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),Q=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(iU("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(iU("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==Q)return $.json(iU("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Y=await $.req.json(),X=Lu6.safeParse(Y);if(!X.success){let w=X.error.issues[0]??{message:"Invalid request",path:[]};return $.json(iU(`Invalid request: ${w.message}`,"invalid_request_error",w.path.length>0?w.path.join("."):null),400)}let J=X.data,G=wu6(J.model);if(!G)return $.json(iU("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:W}=G,{modelId:K}=G;if(!W){let j=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((E)=>xz(E.providerId));if(!j)return $.json(iU("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);W=j.id}let H;try{H=await Z.aiProviders.activate(W,Z.organization.id)}catch{return $.json(iU(`AI provider credential not found or inaccessible: ${W}`,"invalid_request_error","model"),404)}let F=H.aiSdk.languageModel(K),U=Eu6(J.messages),N=J.tools?zu6(J.tools):void 0,B=Pu6(J.response_format),O=Au6(),L=Math.floor(Date.now()/1000);if(J.stream)return bO($,async(w)=>{let j=H68(F,U,N,J,B,$.req.raw.signal);try{let E=$m(j),z=!1,T=0,P="",A=async()=>{if(P.length===0)return;let q=P;P="",await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:J.model,choices:[{index:0,delta:{content:q},finish_reason:null}]})})};for await(let q of E.stream){if(!z&&(q.type==="text-delta"||q.type==="tool-call"))await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:J.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(q.type==="text-delta"){if(P+=q.text,P.length>=Ku6)await A()}else if(q.type==="tool-call"){await A();let x=T++;await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:J.model,choices:[{index:0,delta:{tool_calls:[{index:x,id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.input)}}]},finish_reason:null}]})})}else if(q.type==="finish")await A(),await w.writeSSE({data:JSON.stringify({id:O,object:"chat.completion.chunk",created:L,model:J.model,choices:[{index:0,delta:{},finish_reason:F68(q.finishReason)}],usage:q.totalUsage?{prompt_tokens:q.totalUsage.inputTokens??0,completion_tokens:q.totalUsage.outputTokens??0,total_tokens:q.totalUsage.totalTokens??0}:void 0})})}await A(),await w.writeSSE({data:"[DONE]"})}catch(E){let z=E;console.error("[openai-compat:stream] Error:",z.message),await w.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let w=H68(F,U,N,J,B,$.req.raw.signal),j=await FU(w),E={role:"assistant",content:j.text||null};if(j.toolCalls&&j.toolCalls.length>0)E.tool_calls=j.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),E.content=null;return $.json({id:O,object:"chat.completion",created:L,model:J.model,choices:[{index:0,message:E,finish_reason:F68(j.finishReason)}],usage:{prompt_tokens:j.usage?.inputTokens??0,completion_tokens:j.usage?.outputTokens??0,total_tokens:j.usage?.totalTokens??0}})}}catch(Y){let X=Y;if(X.name==="AbortError")return $.json(iU("Request aborted","invalid_request_error"),400);if(X.name==="MessageConversionError")return $.json(iU(X.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",X.message,X.stack),$.json(iU(X.message,"server_error"),500)}});B68=N68});function Tu6($){if(typeof $!=="object"||$===null)return!1;let Q=$.githubRepo?.url;return typeof Q==="string"&&Q.length>0}function D68(){let $=new Q1;return $.use("*",async(Z,Q)=>{await Q(),Z.header("Cache-Control","private, no-store"),Z.header("Vary","Cookie")}),$.get("/",async(Z)=>{let Q=Z.get("studioContext"),Y=p0(Q);if(!Y)return Z.json({error:"Authentication required"},401);let J=(Z.req.query("site")??"").trim().toLowerCase();if(!WZ(J))return Z.json({error:"Invalid site slug"},400);let G=await Q.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["organization.id as id","organization.slug as slug","organization.name as name","organization.metadata as metadata"]).where("member.userId","=",Y).execute(),W=[];for(let H of G){if(!H.slug||P9(H))continue;let F=await Q.storage.virtualMcps.list(H.id);for(let U of F){if(la(U)!==J)continue;if(!Tu6(U.metadata))continue;W.push({orgSlug:H.slug,orgName:H.name??H.slug,project:{id:U.id,title:U.title,icon:U.icon??null}})}}let K={matches:W};return Z.json(K)}),$}var L68=D(()=>{G8();fG()});var j68;var w68=D(()=>{j68={name:"decocms",version:"4.403.0",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^4.0.58","@ai-sdk/google":"^4.0.76","@ai-sdk/openai":"^4.0.71","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^3.1.0","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^4.0.17","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^7.0.107","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});function Mu6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??qu6}}var E68,qu6="https://ph.studio.decocms.com",z68;var P68=D(()=>{G8();Fr();Zf();E9();F$();CK1();w68();E68=new Q1;E68.get("/",($)=>{let Z={version:j68.version,theme:H$$(),...RK().logo&&{logo:RK().logo},...WO()&&{internalUrl:lc1()},...E0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!E0().firecrawlApiKey,hostingEnabled:!!E0().controlplaneRestUrl&&!!E0().controlplaneServiceToken,hostingControlPlaneGa:E0().hostingControlPlaneGa,monitorEnabled:!!E0().clickhouseAnalyticsUrl&&!!E0().clickhouseAnalyticsPassword,monitorGa:E0().monitorGa,plansEnabled:E0().plansEnabled,auth:Va$(),posthog:Mu6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:pO()}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});z68=E68});function Ny($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function FU1($){return(Ny($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((Q)=>Q.charAt(0).toUpperCase()+Q.slice(1)).join(" ")}function A68($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(Ny($))}&sz=${Z}`}function Iu6($,Z){let Q=$.trim();if(Q.length<=Z)return Q;let Y=Q.slice(0,Z-1),X=Y.lastIndexOf(" ");return`${(X>Z*0.6?Y.slice(0,X):Y).trimEnd()}\u2026`}function T68($){let{brand:Z,domain:Q,score:Y}=$,X=typeof Y==="number"?`${Z} Deco Score \u2014 ${Math.round(Y)}/100 \xB7 decocms`:`${Z} Deco Score \xB7 decocms`,J=Iu6(`How does ${Q} really perform? See the full ${Z} Deco Score \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,200);return{title:X,description:J}}import{z as L$}from"zod";var Vu6,R68;var q68=D(()=>{Vu6=L$.object({check_id:L$.string(),title:L$.string(),description:L$.string().optional(),impact:L$.string().optional(),why:L$.string().optional(),category:L$.string(),severity:L$.string(),value_band:L$.string().optional(),value_driver:L$.string().optional(),controllability:L$.string().optional(),pages:L$.array(L$.string()),tasks:L$.array(L$.string()),evidence:L$.string(),sample_scope:L$.string().optional(),sources:L$.array(L$.string())}),R68=L$.object({domain:L$.string(),brand:L$.string(),favicon:L$.string().optional(),scanned_at:L$.string().nullable(),lang:L$.string(),score:L$.number().nullable(),band:L$.string().nullable(),totals:L$.object({measured:L$.number(),registry_total:L$.number(),passed:L$.number(),failed:L$.number(),blocked:L$.number()}),buckets:L$.array(L$.object({id:L$.enum(["critical","important","worth"]),label:L$.string(),items:L$.array(Vu6)})),passing:L$.object({count:L$.number(),items:L$.array(L$.object({check_id:L$.string(),title:L$.string()}))}),not_measured:L$.object({count:L$.number(),groups:L$.array(L$.object({reason:L$.string(),label:L$.string(),count:L$.number(),checks:L$.array(L$.string())}))}),categories:L$.array(L$.object({key:L$.string(),label:L$.string(),score:L$.number().nullable(),band:L$.string().nullable(),pass:L$.number(),fail:L$.number()})),screenshots:L$.array(L$.object({url:L$.string(),page_type:L$.string().optional(),viewport:L$.enum(["desktop","mobile"]),image_url:L$.string()}))})});function M68($,Z,Q){let Y=Q?`?${new URLSearchParams({lang:Q}).toString()}`:"";return`${uK({})}/api/v2/public/diagnostics/${encodeURIComponent($)}/onepager${Z}${Y}`}async function sk0($,Z={}){let Q=await fetch(M68($,"",Z.lang),{headers:{Accept:"application/json"},signal:Z.signal});if(Q.status===404)return null;if(!Q.ok)throw Error(`onepager read HTTP ${Q.status}`);return R68.parse(await Q.json())}async function I68($,Z={}){let Q=await fetch(M68($,".md",Z.lang),{headers:{Accept:"text/markdown"},signal:Z.signal});if(Q.status===404)return null;if(!Q.ok)throw Error(`onepager markdown HTTP ${Q.status}`);return Q.text()}var UU1=D(()=>{q68();ww()});import{join as V68}from"path";async function Su6($){try{let Z=await sk0($,{signal:AbortSignal.timeout(ku6)});if(!Z?.scanned_at)return null;return{brand:Z.brand.trim()||FU1($),...Z.score!==null?{score:Z.score}:{}}}catch{return null}}function iJ($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}function Cu6($,Z){let Q=Ny($),Y=Z?.brand?.trim()||FU1(Q),X=A68(Q,128),G=`${(E0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(Q)}`,{title:W,description:K}=T68({brand:Y,domain:Q,score:Z?.score}),H=`${G}/og.png`,F=`${Y} Deco Score by decocms`;return[`<title>${iJ(W)}</title>`,`<meta name="description" content="${iJ(K)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${iJ(W)}" />`,`<meta property="og:description" content="${iJ(K)}" />`,`<meta property="og:url" content="${iJ(G)}" />`,`<meta property="og:image" content="${iJ(H)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${iJ(F)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${iJ(W)}" />`,`<meta name="twitter:description" content="${iJ(K)}" />`,`<meta name="twitter:image" content="${iJ(H)}" />`,`<meta name="twitter:image:alt" content="${iJ(F)}" />`,`<link rel="canonical" href="${iJ(G)}" />`,`<link rel="alternate" type="text/markdown" href="${iJ(G)}.md" />`,`<link rel="icon" href="${iJ(X)}" sizes="any" />`].join(`
|
|
3707
3707
|
`)}function _u6($,Z){return $.replace(/<title>[\s\S]*?<\/title>\s*/i,"").replace(/<meta\s+name="(?:description|twitter:[^"]*)"[^>]*>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*>\s*/gi,"").replace(/<link\s+rel="icon"[^>]*>\s*/gi,"").replace("</head>",` ${Z}
|
|
3708
|
-
</head>`)}function k68($){let Z=new Q1;return Z.get("/:domain/og.png",async(Q)=>{let Y=Ny(Q.req.param("domain")),X=async()=>{let J=$?Bun.file(V68($,"report-og-fallback.png")):null;if(!J||!await J.exists())return Q.notFound();return Q.body(new Uint8Array(await J.arrayBuffer()),200,{"Content-Type":"image/png","Cache-Control":"public, max-age=0, s-maxage=3600"})};try{let J=await fetch(`${uK({})}/api/v2/public/diagnostics/${encodeURIComponent(Y)}/og.png`,{signal:AbortSignal.timeout(vu6)}),G=J.headers.get("content-type")??"";if(!J.ok||!G.startsWith("image/")||!J.body)return X();return Q.body(J.body,200,{"Content-Type":G,"Cache-Control":"public, max-age=0, s-maxage=604800"})}catch{return X()}}),Z.get("/:file{.+\\.md}",async(Q)=>{let Y=Ny(Q.req.param("file").replace(/\.md$/,""));try{let X=await I68(Y,{lang:Q.req.query("lang")?.trim()||void 0,signal:AbortSignal.timeout(bu6)});if(X===null)return Q.text("Report not found",404);return Q.body(X,200,{"Content-Type":"text/markdown; charset=utf-8","Cache-Control":"public, max-age=600, stale-while-revalidate=3600","Access-Control-Allow-Origin":"*"})}catch{return Q.text("Report unavailable",502)}}),Z.get("/:domain",async(Q)=>{let Y=Q.req.param("domain"),X=$?V68($,"index.html"):null,J=X?Bun.file(X):null;if(!J||!await J.exists())return Q.notFound();let G=await J.text();try{let W=await Su6(Ny(Y)),K=Cu6(Y,W);return Q.html(_u6(G,K),200,{"Cache-Control":"public, max-age=0, s-maxage=300"})}catch{return Q.html(G)}}),Z}var ku6=2500,vu6=1e4,bu6=1e4;var S68=D(()=>{G8();ww();UU1();F$()});function ak0($,Z){return fetch(`${uK({})}${$}`,Z)}async function xu6($,Z){let Q=await sk0($,{lang:Z});if(!Q)return{status:"not_found",report:null};return Q.scanned_at?{status:"ready",report:Q}:{status:"empty",report:null}}function yu6($){let Z=typeof $==="object"&&$!==null?$:{},Q=typeof Z.domain==="string"?Z.domain.trim():"",Y=typeof Z.distinctId==="string"&&Z.distinctId.trim()&&Z.distinctId.length<=200?Z.distinctId.trim():void 0;return{domain:Q,distinctId:Y}}var fu6,fO,C68=async($,Z)=>{if(!$.get("reportUser"))return $.json({error:"Authentication required"},401);await Z();return},_68;var v68=D(()=>{G8();hG();ww();UU1();fu6=new Set(["complete","errored","terminated","unknown"]);fO=new Q1;fO.use("*",async($,Z)=>{let Q=await C8.api.getSession({headers:$.req.raw.headers});$.set("reportUser",Q?.user?.id?{email:Q.user.email}:void 0),await Z(),$.header("Cache-Control","private, no-store"),$.header("Vary","Cookie");return});fO.use("/link-token/*",C68);fO.use("/suggest",C68);fO.get("/site/:domain",async($)=>{let Z=$.req.param("domain").trim();if(!Z)return $.json({error:"domain is required"},400);let Q=$.req.query("lang")?.trim()||void 0;try{return $.json(await xu6(Z,Q))}catch{return $.json({error:"report read failed"},502)}});fO.post("/run",async($)=>{let Z=$.get("reportUser"),Q;try{Q=await $.req.json()}catch{return $.json({error:"invalid JSON"},400)}let{domain:Y,distinctId:X}=yu6(Q);if(!Y)return $.json({error:"domain is required"},400);let J=Z?.email;try{let G=await ak0("/api/v2/diagnostics/run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${EA({})}`},body:JSON.stringify({url:Y,...J?{email:J}:{},distinct_id:X})});if(!G.ok)return $.json({error:`run HTTP ${G.status}`},502);let W=await G.json(),K=W.blocked?{state:"blocked"}:W.status==="fresh"?{state:"fresh"}:W.mode==="sync"?{state:"sync"}:{state:"running",id:W.id??null};return $.json(K)}catch{return $.json({error:"run failed"},502)}});fO.get("/status",async($)=>{let Z=$.req.query("id");if(!Z)return $.json({error:"id is required"},400);try{let Q=await ak0(`/api/v2/diagnostics/status?id=${encodeURIComponent(Z)}`,{headers:{Authorization:`Bearer ${EA({})}`}});if(!Q.ok)return $.json({error:`status HTTP ${Q.status}`},502);let X=(await Q.json()).status??"unknown",J={done:fu6.has(X),status:X};return $.json(J)}catch{return $.json({error:"status failed"},502)}});fO.get("/link-token/:id",async($)=>{let Z=$.req.param("id");try{let Q=await ak0(`/api/v2/public/link-tokens/${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(Q.status===404)return $.json(null);if(!Q.ok)return $.json({error:`link token HTTP ${Q.status}`},502);return $.json(await Q.json())}catch{return $.json({error:"link token resolve failed"},502)}});fO.get("/suggest",async($)=>{let Z=($.req.query("q")??"").trim().slice(0,64);if(Z.length<2)return $.json({suggestions:[]});try{let Q=await ak0(`/api/v2/public/suggest?q=${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(!Q.ok)return $.json({suggestions:[]});let Y=await Q.json();return $.json({suggestions:Array.isArray(Y.suggestions)?Y.suggestions:[]})}catch{return $.json({suggestions:[]})}});_68=fO});var gu6=1048576,NU1;var b68=D(()=>{G8();fW();F$();LK1();NU1=new Q1;NU1.post("/webhook",I5({maxSize:gu6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=E0().stripeWebhookSecret;if(!Z)return $.json({error:"stripe billing not configured"},503);let Q=await $.req.text();if(!ls$(Q,$.req.header("stripe-signature"),Z))return $.json({error:"invalid signature"},400);let X=cs$(Q);if(!X)return $.json({error:"invalid payload"},400);let J=await ms$(X);return console.log("stripe webhook",{eventId:X.id,type:X.type,livemode:X.livemode,...J}),$.json({received:!0})})});import{timingSafeEqual as hu6}from"crypto";function cu6($,Z,Q){if(!Z?.startsWith("sha256="))return!1;let Y=new Bun.CryptoHasher("sha256",Q).update($).digest("hex"),X=Z.slice(7);if(X.length!==Y.length)return!1;return hu6(Buffer.from(X),Buffer.from(Y))}function mu6($,Z){let Q=Z,Y=Q?.repository?.name,X=Q?.repository?.owner?.login;if(typeof Y!=="string"||typeof X!=="string")return[];let J=[];if($==="check_suite"){if(Q.action!=="completed")return[];let G=Q.check_suite?.pull_requests;for(let W of Array.isArray(G)?G:[]){let K=W?.number;if(typeof K==="number")J.push(K)}}else if($==="issue_comment"&&Q.issue?.pull_request){let G=Q.issue.number;if(typeof G==="number")J.push(G)}return[...new Set(J)].map((G)=>({repoOwner:X,repoName:Y,number:G}))}function x68($){let Z=new Q1;return Z.post("/webhook",I5({maxSize:uu6,onError:(Q)=>Q.json({error:"payload too large"},413)}),async(Q)=>{let Y=process.env.GITHUB_WEBHOOK_SECRET;if(!Y)return Q.json({error:"github webhook not configured"},503);let X=await Q.req.text();if(!cu6(X,Q.req.header("x-hub-signature-256"),Y))return Q.json({error:"invalid signature"},400);let J=Q.req.header("x-github-event");if(J!=="push"&&!lu6.has(J??""))return Q.json({ok:!0,ignored:"event"});let G;try{G=JSON.parse(X)}catch{return Q.json({error:"invalid payload"},400)}if(J==="push"){let H=G.ref,F=G.repository?.full_name;if(!H||!F)return Q.json({ok:!0,ignored:"shape"});let N=(await T41())?.markTenantPoolsDirty(F,H)??[];return Q.json({ok:!0,pools:N})}let W=mu6(J??"",G);if(W.length===0)return Q.json({ok:!0,ignored:"no-pr"});let K=await du6($,W);return Q.json({ok:!0,refreshed:K})}),Z}async function du6($,Z){let Q=0;for(let Y of Z){let X=$.taskBoard(),J;try{J=await X.findPrLinks(Y)}catch(G){console.error("[github-webhook] pr link lookup failed:",G);continue}for(let G of J)try{let W=await X.getById(G.taskBoardItemId,G.organizationId),K=W?await $.contextFactory()(G.organizationId,W.assignedBy??W.createdBy):null;if(!K)continue;if(await vV$(K,G.organizationId,G.taskBoardItemId)!==null)Q++}catch(W){console.error(`[github-webhook] pr card refresh failed for ${G.taskBoardItemId}:`,W)}}return Q}var uu6=5242880,lu6;var f68=D(()=>{G8();fW();QH();z7();lu6=new Set(["check_suite","issue_comment"])});function y68($){let Z=new RO($.db,new FG($.encryptionKey)),Q=new Q1;return Q.get("/attachments/:token",async(Y)=>{let X=tM$(Y.req.param("token"));if(!X)return Y.json({error:"Invalid or expired link"},404);let J=await Z.getByOrg(X.organizationId);if(!J)return Y.json({error:"Jira is not connected"},404);let W=await new _Q(J.siteUrl,J.email,J.apiToken).downloadAttachment(X.attachmentId);if(!W.ok||!W.body)return Y.json({error:"Jira refused the download"},502);let K=new Headers;for(let H of["content-type","content-length","content-disposition"]){let F=W.headers.get(H);if(F)K.set(H,F)}return K.set("cache-control","no-store"),new Response(W.body,{status:200,headers:K})}),Q}var g68=D(()=>{G8();vz();V51();Vj()});function h68($){let Z=new RO($.db,new FG($.encryptionKey));async function Q(X,J){let G=Ln$(J);if(!G)return;let W=await Z.getByWebhookSecret(X);if(!W?.enabled)return;let K=await PW($.db,W.organizationId);if(!K)return;if(await _I0(K,W,G)==="started")console.log(`[jira-webhook] started a run for ${G.issueKey} entering "${G.toStatus}"`)}let Y=new Q1;return Y.post("/webhook/:secret",I5({maxSize:iu6}),async(X)=>{let J=X.req.param("secret");if(!await Z.getByWebhookSecret(J))return X.json({error:"Unknown webhook"},404);let W;try{W=await X.req.json()}catch{return X.json({error:"Body must be JSON"},400)}return Q(J,W).catch((K)=>{console.error("[jira-webhook] trigger failed",K)}),X.body(null,202)}),Y}var iu6=1048576;var u68=D(()=>{G8();fW();vz();vI0();ox()});import{DBOS as ek0,SchedulerMode as pu6}from"@dbos-inc/dbos-sdk";function c68($){OU1=$}function m68(){if(!OU1)throw Error("[jira-trigger] runtime not initialized \u2014 setJiraTriggerSweepRuntime() must run before the workflow fires");return OU1}function d68(){let $=m68();return new RO($.db,new FG($.encryptionKey))}async function ou6($,Z){try{let Q=await d68().getById($);if(!Q?.enabled||!Q.boardId)return{integrationId:$,started:0};let Y=await PW(m68().db,Q.organizationId);if(!Y)return{integrationId:$,started:0};if((await Y.storage.jiraIntegrations.listAutomations(Q.organizationId)).length===0)return{integrationId:$,started:0};let J=new _Q(Q.siteUrl,Q.email,Q.apiToken),W=`(${await J.getBoardScopeJql(Q.boardId)}) AND status CHANGED AFTER "-${l68}m"`,K=0,H;for(let F=0;F<tu6;F++){let U=await J.searchIssues({jql:W,nextPageToken:H,expandChangelog:!0});for(let N of U.issues){let B=wn$(N,N.changelog?.histories??[],Z);for(let O of B)if(await _I0(Y,Q,O)==="started")K++}if(H=U.nextPageToken??void 0,!H)break}return{integrationId:$,started:K}}catch(Q){return{integrationId:$,started:0,error:Q instanceof Error?Q.message:String(Q)}}}async function ru6($,Z){let Q=new Date($.getTime()-l68*60000),Y=await ek0.runStep(()=>d68().listEnabledIds(),{name:"loadJiraIntegrations"});if(Y.length===0)return;let X=await Promise.all(Y.map((J)=>ek0.runStep(()=>ou6(J,Q),{name:`sweepJira:${J}`})));for(let J of X)if(J.error)console.warn(`[jira-trigger] integration ${J.integrationId} failed: ${J.error}`);else if(J.started>0)console.log(`[jira-trigger] integration ${J.integrationId} started ${J.started} run(s) the webhook missed`)}function i68(){if(BU1)return;BU1=ek0.registerWorkflow(ru6,{name:"jiraTriggerSweepWorkflow"}),ek0.registerScheduled(BU1,{name:"jiraTriggerSweepWorkflow",crontab:nu6,mode:pu6.ExactlyOncePerIntervalWhenActive})}var nu6="7-59/10 * * * *",l68=35,tu6=5,OU1=null,BU1=null;var p68=D(()=>{vz();ox();Vj();vI0()});function n68($,Z){if(Z.startsWith("text/html")||Z.startsWith("image/svg"))$.set("Content-Security-Policy","sandbox allow-scripts allow-modals allow-same-origin")}var t68,su6,au6,o68;var r68=D(()=>{G8();TK();Rm();al();t68=new Q1,su6=["range","if-none-match","if-modified-since"],au6=["content-type","content-length","content-range","accept-ranges","etag","last-modified"];t68.get("/:org/files/*",async($)=>{let Z=$.get("studioContext"),Q=Z.organization?.id;if(!Z.auth?.user?.id){if(nd($))return $.redirect(`/login?next=${encodeURIComponent($.req.path)}`,302);throw new A$(401,{message:"Authentication required"})}if(!Q)throw new A$(401,{message:"Organization context required"});let Y=$.req.path.replace(/^.*\/files\//,"");if(!Y)throw new A$(400,{message:"Missing file key"});let X=await E10(Y,Z);if(!X)throw new A$(503,{message:"Object storage not configured"});if(X.startsWith("data:")&&JW()){let K=X.match(/^data:([^;]+);base64,(.+)$/s);if(!K)throw new A$(500,{message:"Invalid data URL from storage"});let[,H,F]=K,U=Buffer.from(F,"base64"),N=new Headers({"Content-Type":H,"Cache-Control":"private, max-age=86400"});return n68(N,H),new Response(U,{status:200,headers:N})}let J=new Headers;for(let K of su6){let H=$.req.header(K);if(H)J.set(K,H)}let G=await fetch(X,{headers:J});if(G.status===403||G.status===404)throw new A$(404,{message:"File not found"});if(!G.ok&&G.status!==304&&G.status!==416)throw console.error(`[files] upstream storage error ${G.status} for key:`,Y),new A$(502,{message:"Upstream storage error"});let W=new Headers;for(let K of au6){let H=G.headers.get(K);if(H)W.set(K,H)}return W.set("Cache-Control","private, max-age=86400"),n68(W,W.get("content-type")??""),new Response(G.body,{status:G.status,headers:W})});o68=t68});var J40=b((By)=>{var eu6=By&&By.__createBinding||(Object.create?function($,Z,Q,Y){if(Y===void 0)Y=Q;var X=Object.getOwnPropertyDescriptor(Z,Q);if(!X||("get"in X?!Z.__esModule:X.writable||X.configurable))X={enumerable:!0,get:function(){return Z[Q]}};Object.defineProperty($,Y,X)}:function($,Z,Q,Y){if(Y===void 0)Y=Q;$[Y]=Z[Q]}),$l6=By&&By.__exportStar||function($,Z){for(var Q in $)if(Q!=="default"&&!Object.prototype.hasOwnProperty.call(Z,Q))eu6(Z,$,Q)};Object.defineProperty(By,"__esModule",{value:!0});$l6($G(),By)});var e68=b((s68)=>{Object.defineProperty(s68,"__esModule",{value:!0});s68.version=void 0;s68.version="3.4.0"});var Q58=b((pU)=>{var Zl6=pU&&pU.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(pU,"__esModule",{value:!0});pU.NodeTransport=pU.VERSION=void 0;pU.nodeResolveHost=Wl6;var m5=J40(),Ql6=q0("net"),DU1=q0("tls"),Yl6=q0("path"),$58=q0("fs"),Xl6=Zl6(q0("dns")),Jl6=e68();pU.VERSION=Jl6.version;var Gl6="nats.js";class Z58{socket;version;lang;yields=[];signal=(0,m5.deferred)();closedNotification=(0,m5.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=Gl6,this.version=pU.VERSION}async connect($,Z){this.tlsName=$.tlsName,this.options=Z;let{tls:Q}=this.options,{handshakeFirst:Y}=Q||{};try{if(Y===!0)this.socket=await this.tlsFirst($);else this.socket=await this.dial($);if(this.done)this.socket?.destroy();let X=await this.peekInfo();(0,m5.checkOptions)(X,Z);let{tls_required:J,tls_available:G}=X,W=G===!0&&Z.tls!==null;if(!Y&&(J||W))this.socket=await this.startTLS();if(this.done)this.socket?.destroy();if(J&&this.socket.encrypted!==!0)throw m5.errors.InvalidArgumentError.format("tls","is not available on this server");return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(X){let J=X;if(!J)J=new m5.errors.ConnectionError("error connecting - node provided an undefined error");let{code:G}=J,W=G==="ECONNREFUSED"?new m5.errors.ConnectionError("connection refused",{cause:J}):J;throw this.socket?.destroy(),W}}dial($){let Z=(0,m5.deferred)(),Q,Y=(0,Ql6.createConnection)($.port,$.hostname,()=>{Z.resolve(Y),Y.removeAllListeners()});return Y.on("error",(X)=>{Q=X}),Y.on("close",()=>{Y.removeAllListeners(),Z.reject(Q)}),Y.setNoDelay(!0),Z}get isClosed(){return this.done}close($){return this._closed($,!1)}peekInfo(){let $=(0,m5.deferred)(),Z;return this.socket.on("data",(Q)=>{this.yields.push(Q);let Y=m5.DataBuffer.concat(...this.yields),X=(0,m5.extractProtocolMessage)(Y);if(X!=="")try{let J=m5.INFO.exec(X);if(!J)throw Error("unexpected response from server");let G=JSON.parse(J[1]);$.resolve(G)}catch(J){$.reject(J)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(Q)=>{Z=Q}),this.socket.on("close",()=>{this.socket.removeAllListeners(),$.reject(Z)}),$}loadFile($){if(!$)return Promise.resolve();let Z=(0,m5.deferred)();try{if($=(0,Yl6.resolve)($),!(0,$58.existsSync)($))Z.reject(Error(`${$} doesn't exist`));(0,$58.readFile)($,(Q,Y)=>{if(Q)return Z.reject(Q);Z.resolve(Y)})}catch(Q){Z.reject(Q)}return Z}async loadClientCerts(){let $={},{certFile:Z,cert:Q,caFile:Y,ca:X,keyFile:J,key:G}=this.options.tls;try{if(Z){let W=await this.loadFile(Z);if(W)$.cert=W}else if(Q)$.cert=Q;if(J){let W=await this.loadFile(J);if(W)$.key=W}else if(G)$.key=G;if(Y){let W=await this.loadFile(Y);if(W)$.ca=[W]}else if(X)$.ca=X;return Promise.resolve($)}catch(W){return Promise.reject(W)}}async tlsFirst($){let Z,Q={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)Q.socket=this.socket;if(typeof this.options.tls==="object")try{let X=await this.loadClientCerts()||{};Q=(0,m5.extend)(Q,this.options.tls,X)}catch(X){return Promise.reject(new m5.errors.ConnectionError(X.message,{cause:X}))}let Y=(0,m5.deferred)();try{let X=(0,DU1.connect)($.port,$.hostname,Q,()=>{X.removeAllListeners(),Y.resolve(X)});X.on("error",(J)=>{Z=J}),X.on("secureConnect",()=>{if(Q.rejectUnauthorized===!1)return;if(!X.authorized)throw X.authorizationError}),X.on("close",()=>{Y.reject(Z),X.removeAllListeners()}),X.setNoDelay(!0)}catch(X){Y.reject(new m5.errors.ConnectionError(X.message,{cause:X}))}return Y}async startTLS(){let $,Z={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let Y=await this.loadClientCerts()||{};Z=(0,m5.extend)(Z,this.options.tls,Y)}catch(Y){return Promise.reject(new m5.errors.ConnectionError(Y.message,{cause:Y}))}let Q=(0,m5.deferred)();try{let Y=(0,DU1.connect)(Z,()=>{Y.removeAllListeners(),Q.resolve(Y)});Y.on("error",(X)=>{$=X}),Y.on("secureConnect",()=>{if(Z.rejectUnauthorized===!1)return;if(!Y.authorized)throw Y.authorizationError}),Y.on("close",()=>{Q.reject($),Y.removeAllListeners()})}catch(Y){Q.reject(new m5.errors.ConnectionError(Y.message,{cause:Y}))}return Q}setupHandlers(){let $;this.socket.on("data",(Z)=>{return this.yields.push(Z),this.signal.resolve()}),this.socket.on("error",(Z)=>{$=Z}),this.socket.on("end",()=>{if(this.socket?.destroyed)return;this.socket?.write(new Uint8Array(0),()=>{this.socket?.end()})}),this.socket.on("close",()=>{this._closed($,!1)})}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.yields.length===0)await this.signal;let $=this.yields;this.yields=[];for(let Z=0;Z<$.length;Z++){if(this.options.debug)console.info(`> ${(0,m5.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,m5.deferred)()}}discard(){if(this.done=!0,this.socket)try{this.socket.removeAllListeners(),this.socket.destroy()}catch{}}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof DU1.TLSSocket}_send($){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,m5.render)($)}`);let Z=(0,m5.deferred)();try{this.socket.write($,(Q)=>{if(Q){if(this.options.debug)console.error(`!!! ${(0,m5.render)($)}: ${Q}`);return Z.reject(Q)}return Z.resolve()})}catch(Q){if(this.options.debug)console.error(`!!! ${(0,m5.render)($)}: ${Q}`);Z.reject(Q)}return Z}send($){this._send($).catch((Q)=>{})}async _closed($,Z=!0){if(!this.connected)return;if(this.done){this.socket?.destroy();return}if(this.closeError=$,!$&&this.socket&&Z)try{await this._send(new TextEncoder().encode(""))}catch(Q){if(this.options.debug)console.log("transport close terminated with an error",Q)}try{if(this.socket)this.socket.removeAllListeners(),this.socket?.destroy(),this.socket=void 0}catch(Q){console.log(Q)}this.done=!0,this.closedNotification.resolve(this.closeError)}closed(){return this.closedNotification}}pU.NodeTransport=Z58;function Wl6($){let Z=(0,m5.deferred)();return Xl6.default.lookup($,{all:!0},(Q,Y)=>{if(Q){Z.reject(Q);return}let X=[];for(let J of Y)X.push(J.address);if(X.length===0)X.push($);Z.resolve(X)}),Z}});var W58=b((G58)=>{Object.defineProperty(G58,"__esModule",{value:!0});G58.connect=Kl6;var Y58=Q58(),X58=J40(),J58=J40();function Kl6($={}){if((0,J58.hasWsProtocol)($))return Promise.reject(J58.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,X58.setTransportFactory)({factory:()=>{return new Y58.NodeTransport},dnsResolveFn:Y58.nodeResolveHost}),X58.NatsConnectionImpl.connect($)}});var K58=b((yO)=>{var Fl6=yO&&yO.__createBinding||(Object.create?function($,Z,Q,Y){if(Y===void 0)Y=Q;var X=Object.getOwnPropertyDescriptor(Z,Q);if(!X||("get"in X?!Z.__esModule:X.writable||X.configurable))X={enumerable:!0,get:function(){return Z[Q]}};Object.defineProperty($,Y,X)}:function($,Z,Q,Y){if(Y===void 0)Y=Q;$[Y]=Z[Q]}),Ul6=yO&&yO.__exportStar||function($,Z){for(var Q in $)if(Q!=="default"&&!Object.prototype.hasOwnProperty.call(Z,Q))Fl6(Z,$,Q)};Object.defineProperty(yO,"__esModule",{value:!0});yO.connect=void 0;var Nl6=W58();Object.defineProperty(yO,"connect",{enumerable:!0,get:function(){return Nl6.connect}});Ul6(J40(),yO)});function N58($){let Z=$?.connectFn??Ll6,Q=null,Y=null,X=!1,J=!1,G=!1,W=[];function K(){return Q!==null&&!Q.isClosed()&&!Q.isDraining()&&!G}function H(){console.log(`[NatsProvider] fireReady: ${W.length} callbacks`);for(let N of W)try{N()}catch{}}function F(N){(async()=>{for await(let B of N.status())if(B.type==="disconnect")console.log("[NatsProvider] Disconnected"),G=!0;else if(B.type==="reconnect")console.log("[NatsProvider] Reconnected, re-firing ready callbacks"),G=!1,Y=null,H()})().catch(()=>{})}async function U(N,B){let O=0;while(!J)try{Q=await Z({servers:N,timeout:Dl6,reconnect:!0,maxReconnectAttempts:-1,...B?{authenticator:B}:{}}),console.log(`[NatsProvider] Connected to ${Q.getServer()} after ${O} attempt(s)`),Y=null,G=!1,F(Q),H();return}catch{O++;let L=QQ(Ol6,Bl6,O-1,2,0.5);await i$(L)}}return{init(N,B){if(X)return;X=!0,J=!1;let O=B?.creds?H58.credsAuthenticator(new TextEncoder().encode(B.creds)):void 0;U(N,O).catch(()=>{})},isConnected(){return K()},getConnection(){return K()?Q:null},getJetStream(){if(!K())return null;if(!Y)Y=U58.jetstream(Q);return Y},onReady(N){if(W.push(N),K())try{N()}catch{}},async drain(){if(J=!0,X=!1,Y=null,G=!1,Q){let N=Q;Q=null,await N.drain().catch(()=>{})}}}}function Ll6($){return F58.connect($)}var H58,F58,U58,Bl6=100,Ol6=3000,Dl6=3000;var B58=D(()=>{D8();H58=C(ei(),1),F58=C(K58(),1),U58=C(GN(),1)});function $S0($){let Z=$?.ttlMs??60000,Q=$?.maxSize??1e4,Y=$?.updateRecencyOnGet??!1,X=new Map;function J(){if(X.size<=Q)return;let G=Date.now();for(let[W,K]of X)if(K.expiresAt<=G)X.delete(W);while(X.size>Q){let W=X.keys().next().value;if(W===void 0)break;X.delete(W)}}return{get(G){let W=X.get(G);if(!W)return;if(W.expiresAt<=Date.now()){X.delete(G);return}if(Y)X.delete(G),X.set(G,W);return W.value},set(G,W){X.delete(G),X.set(G,{value:W,expiresAt:Date.now()+Z}),J()},delete(G){X.delete(G)},clear(){X.clear()},size(){return X.size}}}function ZS0($,Z){return`${$}.${Z}`}class LU1{cache;constructor($){this.cache=$S0({ttlMs:$?.ttlMs??wl6,maxSize:$?.maxSize??jl6})}async get($,Z){return this.cache.get(ZS0($,Z))??null}async set($,Z,Q){this.cache.set(ZS0($,Z),Q)}async invalidate($,Z){this.cache.delete(ZS0($,Z)),this.cache.delete(ZS0($,`${Z}:decisions`))}teardown(){this.cache.clear()}}var wl6=600000,jl6=5000;var O58=()=>{};function QS0($,Z){return`${$}:${Z}`}function wU1($){let Z=$S0({ttlMs:$?.ttlMs??El6,maxSize:$?.maxSize??zl6}),Q=$?.getConnection,Y=crypto.randomUUID(),X=new TextEncoder,J=new TextDecoder,G=null;function W(K,H){let F=Q?.();if(!F)return;try{F.publish(D58,X.encode(JSON.stringify({organizationId:K,keyId:H,originId:Y})))}catch(U){console.warn("[ProviderKeyCache] Publish failed (non-critical):",U)}}return{get(K,H){return Z.get(QS0(K,H))},set(K,H,F){Z.set(QS0(K,H),F)},invalidate(K,H){Z.delete(QS0(K,H)),W(K,H)},start(){if(G)return;let K=Q?.();if(!K)return;G=K.subscribe(D58),(async()=>{for await(let H of G)try{let F=JSON.parse(J.decode(H.data));if(F.originId===Y)continue;Z.delete(QS0(F.organizationId,F.keyId))}catch{}})().catch(console.error)},teardown(){G?.unsubscribe(),G=null,Z.clear()}}}var D58="studio.ai-provider-keys.invalidate",El6=30000,zl6=5000;var L58=()=>{};class jU1{options;subscription=null;onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();constructor($){this.options=$}async start($){if($)this.onCancel=$;if(this.subscription)return;if(!this.onCancel)return;let Z=this.options.getConnection();if(!Z)return;let Q=new TextDecoder,Y=Z.subscribe("studio.decopilot.cancel");this.subscription=Y,(async()=>{for await(let X of Y)try{let J=JSON.parse(Q.decode(X.data));if(J.originId===this.originId)continue;this.onCancel?.(J.taskId)}catch{}})().catch(console.error)}broadcast($){if(/[.*>\s]/.test($)){console.warn("[NatsCancelBroadcast] Invalid threadId, skipping broadcast");return}this.onCancel?.($);try{let Z=this.options.getConnection();if(!Z)return;let Q=this.encoder.encode(JSON.stringify({taskId:$,originId:this.originId}));Z.publish("studio.decopilot.cancel",Q)}catch(Z){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",Z)}}async stop(){this.subscription?.unsubscribe(),this.subscription=null,this.onCancel=null}}var w58=($)=>{let Z;return()=>Z??=$()},EU1,zU1;var j58=D(()=>{C6();EU1=w58(()=>z$.createHistogram("decopilot.stream.encode_ms",{description:"Per-chunk JSON.stringify+encode time for decopilot stream",unit:"ms"})),zU1=w58(()=>z$.createCounter("decopilot.stream.published_chunks",{description:"Logical decopilot stream chunks published to JetStream",unit:"{chunks}"}))});function Il6($=P58){return{name:EU,subjects:[`${_Z1}.>`],storage:MH.StorageType.File,max_age:Tl6,max_bytes:ql6,max_msgs_per_subject:Ml6,discard:MH.DiscardPolicy.Old,retention:MH.RetentionPolicy.Limits,duplicate_window:Rl6,num_replicas:$}}class A58{chunks=0;encodeMs=0;maxMs=0;bytes=0;windowStart=performance.now();constructor(){setInterval(()=>this.flush(),1e4).unref?.()}record($,Z){if(this.chunks++,this.encodeMs+=$,$>this.maxMs)this.maxMs=$;this.bytes+=Z}flush(){let $=performance.now(),Z=$-this.windowStart;if(this.chunks>0&&Z>0)console.warn(JSON.stringify({msg:"stream-encode-trace",windowMs:Math.round(Z),chunks:this.chunks,encodeMs:Math.round(this.encodeMs),pctOfLoop:+(this.encodeMs/Z*100).toFixed(1),maxChunkMs:+this.maxMs.toFixed(2),mbEncoded:+(this.bytes/1048576).toFixed(2)}));this.chunks=0,this.encodeMs=0,this.maxMs=0,this.bytes=0,this.windowStart=$}}function E58($){let Z=z58.headers();for(let[Q,Y]of Object.entries($))Z.set(Q,Y);return Z}function Cl6($,Z){let Q=0;return{publish(Y,X,J,G){Y.publish(X,J,G?{headers:G}:void 0).catch((W)=>{if(Q++,Al6().add(1,{"org.id":Z??"unknown"}),Q===1||Q%100===0)console.warn(`[Decopilot] JetStream publish failed for thread ${$} (${Q} total):`,W)})},get errorCount(){return Q}}}function _l6($,Z){return $.info?.cluster?Z:1}function vl6($){if(!($ instanceof Error))return!1;if(/non-clustered/i.test($.message))return!0;return/replicas?\b/i.test($.message)&&/not supported|can ?not|exceed|insufficient|greater than/i.test($.message)}class PU1{options;js=null;jsm=null;constructor($){this.options=$}async init(){let $=this.options.getConnection();if(!$){console.log("[Decopilot] StreamBuffer.init skipped: NATS not connected yet");return}let Z=async(Y,X)=>{let J=Il6(X);try{await Y.streams.info(EU),await Y.streams.update(EU,J)}catch(G){if(G instanceof Error&&G.message.includes("stream not found"))await Y.streams.add(J),await Y.streams.update(EU,J);else if(G instanceof Error&&/can ?not change.*storage|storage type/i.test(G.message))await Y.streams.delete(EU),await Y.streams.add(J);else throw G}},Q=await g8(async()=>{let Y=this.options.getJetStreamManager?await this.options.getJetStreamManager():await MH.jetstreamManager($),X=_l6($,P58);try{await Z(Y,X)}catch(J){if(X<=1||!vl6(J))throw J;console.warn(`[Decopilot] StreamBuffer: NATS rejected num_replicas=${X} (${J.message}); falling back to an unreplicated stream`),await Z(Y,1)}return Y},{maxAttempts:5,minTimeout:250,maxTimeout:4000,jitter:0.5,isRetriable:vm});this.js=this.options.getJetStream(),this.jsm=Q,console.log(`[Decopilot] StreamBuffer.init ${this.js?"ready":"degraded (js=null)"}`)}pump($,Z,Q,Y){let X=this.js;if(!X)return console.warn(`[Decopilot] pump: JetStream client unavailable for thread ${Z}; chunks NOT published to NATS`),Promise.resolve();let J=Cl6(Z,Y),G=!1,W=()=>{if(G)return;G=!0;let H=wC$(Z);X.publish(H.subject,H.data).catch(()=>{})};Q.addEventListener("abort",W,{once:!0});let K=(H)=>{let F=performance.now(),U=bZ1(H,{runId:Z}),N=performance.now()-F;EU1().record(N),zU1().add(1,{"org.id":Y??"unknown"}),Sl6?.record(N,U.reduce((B,O)=>B+O.data.length,0));for(let B of U)J.publish(X,B.subject,B.data,B.headers?E58(B.headers):void 0)};return(async()=>{let H=$.getReader(),F=0,U=0,N;try{while(!0){let{done:B,value:O}=await H.read();if(B)break;if(K(O),U++,++F>=64)F=0,await new Promise((L)=>setImmediate(L))}}catch(B){N=B,console.warn(`[Decopilot] stream pump error for thread ${Z}:`,B?.message??B)}finally{if(H.releaseLock(),W(),kl6)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"pump-done",taskId:Z,publishedChunks:U,publishErrors:J.errorCount}))}if(N!==void 0)throw N})()}async publishSerialized($,Z){try{return await g8(()=>$.publish(Z.subject,Z.data,{...Z.headers?{headers:E58(Z.headers)}:{},...Z.msgId?{msgID:Z.msgId}:{}}),{maxAttempts:6,minTimeout:250,maxTimeout:5000,jitter:0.5,isRetriable:vm}),!0}catch(Q){return console.error(`[Decopilot] publish failed after retries subject=${Z.subject}`,Q),!1}}async publishRawChunk($,Z,Q){let Y=this.js;if(!Y)return!1;let X=performance.now(),J=bZ1(Z,{runId:$,dedup:Q});EU1().record(performance.now()-X),zU1().add(1);for(let G of J)if(!await this.publishSerialized(Y,G))return!1;return!0}async publishDone($,Z,Q){let Y=this.js;if(!Y)return!1;let X=LC$({runId:$,fenceToken:Z,finalSeq:Q});return await this.publishSerialized(Y,X)}async createTailStream($,Z,Q){let Y=this.js;if(!Y)return console.warn(`[Decopilot] createTailStream: JetStream client unavailable for thread ${$}; no live tail`),null;let X=Q?.deliverPolicy==="new"?MH.DeliverPolicy.New:MH.DeliverPolicy.All,J=Q?.closeOnDone??!1,G=fj($),W;try{W=await g8(async()=>{return(await Y.consumers.get(EU,{filter_subjects:G,deliver_policy:X})).consume()},{maxAttempts:6,minTimeout:250,maxTimeout:5000,jitter:0.5,isRetriable:vm})}catch(L){return console.warn("[Decopilot] JetStream tail unavailable (non-critical):",L?.message??L),null}let F=QR0({messages:async function*(){try{for await(let L of W)yield{subject:L.subject,data:L.data,headers:L.headers}}finally{W.stop()}}(),onCancel:()=>W.stop()}).pipeThrough(aT0()).pipeThrough(eT0()).getReader(),U=!1,N=()=>{if(U)return;U=!0;try{F.releaseLock()}catch{}},B=!1,O=()=>{if(B)return;B=!0,W.stop(),F.cancel().catch(()=>{}),N()};return Z?.addEventListener("abort",O,{once:!0}),new ReadableStream({async pull(L){for(;;){let{done:w,value:j}=await F.read();if(w){O(),L.close();return}let E=j;if(E.kind==="done"){if(J){O(),L.close();return}continue}L.enqueue(E.chunk);return}},cancel(){O()}})}purge($){if(!this.jsm)return;this.jsm.streams.purge(EU,{filter:fj($)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null}}var MH,z58,Pl6=($)=>{let Z;return()=>Z??=$()},Al6,Tl6=86400000000000,Rl6=120000000000,ql6=4294967296,P58,Ml6=500000,Vl6,kl6,Sl6;var T58=D(()=>{D8();xZ1();YR0();$R0();C6();j58();MH=C(GN(),1),z58=C(ei(),1),Al6=Pl6(()=>z$.createCounter("decopilot.stream.publish_errors",{description:"Number of JetStream publish failures for decopilot stream chunks",unit:"{errors}"})),P58=Math.max(1,Number(process.env.DECOPILOT_STREAM_REPLICAS??3)||3);Vl6=process.env.STREAM_ENCODE_TRACE==="1",kl6=process.env.DECOPILOT_STREAM_TRACE==="1";Sl6=Vl6?new A58:null});function YS0($,Z,Q,Y){if(!Y)return!1;return $.emit(Z,nH(Q,Y.status,{title:Y.title??void 0,virtualMcpId:Y.virtual_mcp_id??void 0,createdBy:Y.created_by??void 0,triggerId:Y.trigger_id??null,branch:Y.branch??null,harnessId:Y.harness_id??void 0,createdAt:Y.created_at,updatedAt:Y.updated_at})),!0}var R58=D(()=>{e8()});class AU1{storage;options;timer=null;constructor($,Z={}){this.storage=$;this.options=Z}start(){if(this.timer)return;let $=this.options.intervalMs??300000;this.timer=setInterval(()=>{this.runOnce()},$)}async runOnce(){let $=this.options.staleAfterMs??3600000;try{let Z=await this.storage.sweepAbandoned($);if(Z>0)console.log(`[async-research-sweeper] marked ${Z} stale jobs as abandoned`);return Z}catch(Z){return console.error("[async-research-sweeper] sweep failed",Z),0}}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}function bl6($,Z){let Q=$.startsWith("thread:")?YH($):$;return[...new Set([Z,Q].filter((Y)=>!!Y))]}async function TU1($,Z){let Q=Z.organizationId;try{let Y=await $.storage.taskBoard.linkedThreadIds(Z.id,Q);for(let X of Y){let J=await KU($,X);if(!J?.owner||!J?.name)continue;let G=await $.storage.threads.get(X),W=await gc($,{threadId:X,runBranch:G?.branch}),K=bl6(W,await AA0($,X)),H=await Pe($,Q,s11(J)).catch(()=>null);if(!H){console.warn(`[task-board] no credential for ${J.owner}/${J.name} \u2014 `+`cannot look up ${Z.id}'s change request by branch`);continue}for(let F of K){let U=await H.readForBranch(F).catch(()=>null);if(!U)continue;return await $.storage.taskBoard.linkPr({taskBoardItemId:Z.id,organizationId:Q,url:U.url,prNumber:U.number,repo:H.repo}),await $.storage.taskBoard.openReviewCycleIfInProgress(Z.id,Q),await aG(Q).catch(()=>{}),console.log(`[task-board] ${Z.id}: linked ${U.url} found on branch ${F}`),!0}}}catch(Y){console.error("[task-board] PR lookup by branch failed",Y)}return!1}var q58=D(()=>{iZ();jW();z7()});async function M58($,Z,Q){let Y=Z.organizationId;if(!VX(Z))return!1;if(!rx(Q))return!1;if(await $.storage.taskBoard.hasHumanRejectedDone(Z.id,Y))return!1;let X=await $.storage.organizationSettings.get(Y),J=oF(X?.flags),G=await $.storage.taskBoard.update(Z.id,Y,{status:J},Z.updatedBy);return await o6($,{taskBoardItemId:Z.id,action:"status_changed",actorId:null,data:{from:Z.status,to:J,reason:"pr_merged"}}),E8(Y,G),console.log(`[task-board-review-sweeper] ${Z.id}: linked PR already merged \u2014 moved to ${J}`),!0}var I58=D(()=>{C4();_Y();jm();WH();V9()});function ll6($){return $ instanceof zX}function V58($,Z){return Z-$>=hl6}class RU1{taskBoard;contextFactory;billing;options;timer=null;running=!1;cursor=null;constructor($,Z,Q,Y={}){this.taskBoard=$;this.contextFactory=Z;this.billing=Q;this.options=Y}start(){if(this.timer)return;let $=this.options.intervalMs??xl6;this.timer=setInterval(()=>{this.runOnce()},$),this.timer.unref()}async runOnce(){if(this.running)return 0;this.running=!0;let $=0;try{let Z=this.options.batchSize??yl6,Q=this.options.itemIntervalMs??fl6,Y=new Date(Date.now()-Q),X=await this.taskBoard.listItemsPendingReview(Z,this.cursor,Y),J=X.at(-1);this.cursor=X.length===Z&&J?{updatedAt:J.updatedAt,id:J.id}:null;for(let{id:G,organizationId:W}of X)try{if(await this.reconcileItem(G,W,Y))$++}catch(K){console.error(`[task-board-review-sweeper] ${G} failed`,K)}await this.reapNeverStartedThreads(Z),$+=await this.dispatchDueRetries(Z),await this.reactToUnhandledFailures(Z),$+=await this.settleFinishedRunsWithoutPr(Z,Y)}catch(Z){console.error("[task-board-review-sweeper] sweep failed",Z)}finally{this.running=!1}return $}async reapNeverStartedThreads($){try{let Z=await this.taskBoard.failNeverStartedLinkedThreads($,new Date(Date.now()-A51),l91);for(let Q of Z)console.warn(`[task-board-review-sweeper] failed never-started thread ${Q.threadId} on ${Q.itemId}`)}catch(Z){console.error("[task-board-review-sweeper] reaping failed",Z)}}async reactToUnhandledFailures($){let Z=await this.taskBoard.listItemsStuckAfterFailure($,new Date(Date.now()-ul6));for(let{id:Q,organizationId:Y,threadId:X}of Z)try{console.warn(`[task-board-review-sweeper] reacting to an unhandled failure on ${Q}`),await g91(this.taskBoard,X,Y),await h91(this.taskBoard,this.billing,X,Y)}catch(J){console.error(`[task-board-review-sweeper] unhandled-failure reaction for ${Q} failed`,J)}}async settleFinishedRunsWithoutPr($,Z){let Q=0,Y=await this.taskBoard.listItemsFinishedWithoutPr($,Z);for(let{id:X,organizationId:J,finishedAt:G}of Y)try{if(!await this.taskBoard.claimSweep(X,J,Z))continue;let W=await this.taskBoard.getById(X,J);if(!W||W.status!==T$.progress||VX(W)||W.assigneeId!==j8)continue;let K=await this.contextFactory(J,W.assignedBy??W.createdBy);if(!K)continue;if(await TU1(K,W)){if(await this.taskBoard.clearSweepBudget(X,J),await this.reconcileItem(X,J,Z))Q++;continue}if(!V58(G.getTime(),Date.now()))continue;let H="the run finished without opening a pull request \u2014 there is "+"nothing for a reviewer to review",F=await this.taskBoard.advanceToReviewIfInProgress(X,J,W.updatedBy);if(!F)continue;await this.taskBoard.recordActivity({taskBoardItemId:X,action:"status_changed",actorId:null,data:{from:T$.progress,to:T$.review,reason:H}}).catch(()=>{}),E8(J,F),await KH(K,F,H)}catch(W){console.error(`[task-board-review-sweeper] settling finished run on ${X} failed`,W)}return Q}async dispatchDueRetries($){let Z=0,Q=await this.taskBoard.listItemsDueForRetry($,new Date);for(let{id:Y,organizationId:X,attempts:J}of Q)try{if(!await this.taskBoard.claimDueRetry(Y,X,new Date))continue;let G=await this.taskBoard.getById(Y,X);if(!G||G.status!==T$.progress||G.assigneeId!==j8)continue;let W=await this.contextFactory(X,G.assignedBy??G.createdBy);if(!W)continue;await HH(W,G,{runClass:"retry"}),Z++,console.warn(`[task-board-review-sweeper] re-dispatched ${Y} after a failure (attempt ${J})`)}catch(G){if(console.error(`[task-board-review-sweeper] retry dispatch for ${Y} failed`,G),ll6(G)){await this.returnToTodo(Y,X,G instanceof Error?G.message:String(G));continue}await this.taskBoard.scheduleRunRetry(Y,X,J,new Date(Date.now()+gl6)).catch((W)=>console.error(`[task-board-review-sweeper] re-arming ${Y} failed`,W))}return Z}async returnToTodo($,Z,Q){try{let Y=await this.taskBoard.getById($,Z);if(!Y||Y.status!==T$.progress)return;let X=await this.taskBoard.returnToTodoAfterFailure($,Z,Y.updatedBy);if(!X)return;await this.taskBoard.recordActivity({taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:"in_progress",to:"todo",reason:Q}}).catch(()=>{}),E8(Z,X)}catch(Y){console.error(`[task-board-review-sweeper] returning ${$} to todo failed`,Y)}}async handOffReviewWithoutPr($,Z){let Q=await this.taskBoard.listActivity(Z.id,Z.organizationId);if(!V58(SB(Q,Z.reviewCycleStartedAt),Date.now()))return;await KH($,Z,"no pull request is linked to this task \u2014 there is nothing for a "+"reviewer to review")}async reconcileItem($,Z,Q){if(!await this.taskBoard.claimSweep($,Z,Q))return!1;let Y=await this.taskBoard.getById($,Z);if(!Y)return!1;if(!VX(Y))return!1;let X=Y.assigneeId===j8,J=await this.taskBoard.listPrs($,Z),G=await this.contextFactory(Z,Y.assignedBy??Y.createdBy);if(!G)return!1;if(J.length===0){if(await TU1(G,Y))J=await this.taskBoard.listPrs($,Z);if(J.length===0){if(X)await this.handOffReviewWithoutPr(G,Y);return!1}}let W=await Promise.all(J.map(async(K)=>({...K,...await Pm(Z,K)})));if(W.every((K)=>K.state===null))console.warn(`[task-board-review-sweeper] ${$}: no live PR state from GitHub (${W.length} PR(s)) \u2014 proceeding on unknown`);if(await M58(G,Y,W))return!0;if(await P_$(G,Y))return!0;if(await this.resolveConflictFromSweep(G,Y,W))return!0;if(!X)return!1;if(!b91(W))return!1;return await Em(G,Y,{previewMatchesHead:x91(W)}),!0}async resolveConflictFromSweep($,Z,Q){let Y=Q.find((X)=>X.state!=="closed"&&X.conflict===!0);if(!Y)return!1;return await _j($,Z.organizationId,Z,{pr:{number:Y.number,url:Y.url},conflict:!0}).catch((X)=>{return console.error("[task-board-review-sweeper] conflict resolve failed",X),!1})}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}var xl6=60000,fl6=300000,yl6=50,gl6=60000,hl6=900000,ul6=120000;var k58=D(()=>{C4();OT0();q58();wU();S10();WH();I58();V9();FW();c91();z7();Q10();zm()});import{readdir as cl6,rm as XS0}from"fs/promises";import{join as JS0}from"path";async function GS0($){let Z=new Date;Z.setUTCDate(Z.getUTCDate()-ml6),Z.setUTCHours(0,0,0,0);let Q=0;try{let Y=await Oy($);for(let X of Y)if(/^\d{4}$/.test(X))Q+=await S58($,X,Z);else if(!X.startsWith(".")){let J=JS0($,X),G=await Oy(J);for(let K of G){if(!/^\d{4}$/.test(K))continue;Q+=await S58(J,K,Z)}if((await Oy(J)).length===0)await XS0(J,{recursive:!0,force:!0})}}catch(Y){console.warn("monitoring retention cleanup failed:",Y)}return Q}async function S58($,Z,Q){let Y=0,X=JS0($,Z),J=await Oy(X);for(let W of J){if(!/^\d{2}$/.test(W))continue;let K=JS0(X,W),H=await Oy(K);for(let U of H){if(!/^\d{2}$/.test(U))continue;let N=new Date(`${Z}-${W}-${U}T00:00:00Z`);if(isNaN(N.getTime()))continue;if(N<Q){let B=JS0(K,U);await XS0(B,{recursive:!0,force:!0}),Y++}}if((await Oy(K)).length===0)await XS0(K,{recursive:!0,force:!0})}if((await Oy(X)).length===0)await XS0(X,{recursive:!0,force:!0});return Y}async function Oy($){try{return(await cl6($)).filter((Q)=>!Q.startsWith("."))}catch{return[]}}var ml6=30;var qU1=()=>{};import{DBOS as MU1,SchedulerMode as dl6}from"@dbos-inc/dbos-sdk";async function pl6(){let $=[uW(),Ty(),eU()],Z=0;for(let Q of $)try{Z+=await GS0(Q)}catch(Y){console.error("[monitoring-retention] cleanup failed:",Y)}return console.log(`[monitoring-retention] deleted ${Z} day-dir(s) across ${$.length} signal dir(s)`),{deleted:Z,dirs:$.length}}async function nl6($,Z){await MU1.runStep(()=>pl6(),{name:"monitoringRetention"})}function _58(){if(C58)return;C58=!0;let $=MU1.registerWorkflow(nl6,{name:"monitoringRetentionWorkflow"});MU1.registerScheduled($,{name:"monitoringRetentionWorkflow",crontab:il6,mode:dl6.ExactlyOncePerIntervalWhenActive})}var il6="23 4 * * *",C58=!1;var v58=D(()=>{D3();qU1()});function b58($){return async(Z,Q)=>{let Y=await $.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Q).where("member.organizationId","=",Z).executeTakeFirst();if(!Y)return console.warn(`[automationContextFactory] User ${Q} not found in org ${Z} \u2014 returning null`),null;let X=await vQ.create();X.auth.user={id:Q,role:Y.role},X.organization={id:Y.orgId,slug:Y.orgSlug,name:Y.orgName};let J=await kA($.db,Z,Y.role);return X.boundAuth=KK1({auth:X.authInstance,headers:new Headers,role:Y.role,permissions:J,userId:Q}),X.access=new OP(Q,void 0,X.boundAuth,Y.role,"self"),Cj(X,{id:Y.orgId,slug:Y.orgSlug}),X}}var x58=D(()=>{BK();pF()});function tl6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function ol6(){return{services:tl6(),migrationsStatus:"pending",serverUrl:null,logs:[]}}function sl6(){for(let $ of rl6)$()}function f58($){let Z=[...IU1.logs,$];IU1={...IU1,logs:Z.length>500?Z.slice(-500):Z},sl6()}function VU1(){return al6}var IU1,rl6,al6=!1;var kU1=D(()=>{IU1=ol6(),rl6=new Set});import{EventEmitter as el6}from"events";var SU1;var y58=D(()=>{kU1();SU1=new el6;SU1.on("request",($)=>{f58($)})});function g58(){return async($,Z)=>{let Q=Date.now(),Y=$.req.method,X=$.req.path;if(X==="/api/auth/get-session"||X.includes("favicon")){await Z();return}let J="",G=!1;if(X.startsWith("/mcp")&&Y==="POST"){G=!0;try{if($.req.header("Content-Type")?.includes("application/json")){let N=await $.req.raw.clone().json();if(N.method==="tools/call"&&N.params?.name){let B=Ri(N.params.name),O=N.params.arguments||{},L=Object.keys(O).map((j)=>Ri(j)),w=L.length>0?L.slice(0,3).join(",")+(L.length>3?"\u2026":""):"";J=`${Z9.tool}${B}${Z9.dim}(${w})${Z9.reset}`}else if(N.method)J=`${Z9.dim}${Ri(N.method)}${Z9.reset}`}}catch{}}let W=Ri(X);if(X.startsWith("/mcp/conn_")){let F=X.split("/")[2]??"";W=`/mcp/${Z9.mcp}${Ri(F.slice(0,12))}\u2026${Z9.reset}`}else if(X==="/mcp")W=`${Z9.mcp}/mcp${Z9.reset}`;else if(X==="/mcp/registry")W=`${Z9.mcp}/mcp/registry${Z9.reset}`;let K=Zc6(Y),H=G?"\u25C0":"\u2190";if(!VU1())console.log(`${Z9.dim}${H}${Z9.reset} ${K}${Y}${Z9.reset} ${W}${J?` ${J}`:""}`);try{await Z()}finally{let F=Date.now()-Q,U=$.res.status,N=$c6(U),B=F<1000?`${F}ms`:`${(F/1000).toFixed(1)}s`,O=G?"\u25B6":"\u2192";if(!VU1())console.log(`${Z9.dim}${O}${Z9.reset} ${K}${Y}${Z9.reset} ${W}${J?` ${J}`:""} ${N}${U}${Z9.reset} ${Z9.duration}${B}${Z9.reset}`);SU1.emit("request",{method:Y,path:Ri(X),status:U,duration:F,timestamp:new Date})}}}var Z9,$c6=($)=>{if($>=500)return Z9.serverError;if($>=400)return Z9.clientError;if($>=300)return Z9.redirect;return Z9.ok},Zc6=($)=>{return Z9[$]||Z9.reset},Ri=($)=>{return $.replace(/\r/g,"").replace(/\n/g,"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"")};var h58=D(()=>{kU1();y58();Z9={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",GET:"\x1B[36m",POST:"\x1B[33m",PUT:"\x1B[35m",DELETE:"\x1B[31m",ok:"\x1B[32m",redirect:"\x1B[36m",clientError:"\x1B[33m",serverError:"\x1B[31m",mcp:"\x1B[35m",tool:"\x1B[96m",duration:"\x1B[90m"}});import{createHmac as m58}from"crypto";import{mkdir as Qc6,readdir as Yc6,rm as u58,stat as d58}from"fs/promises";import{join as _U1,relative as Xc6}from"path";import{z as s$}from"zod";function p58($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return _U1(Jc6,Z)}function n58($){return $.replace(/^\/+/,"").replace(/\.\./g,"")}function CU1($,Z){let Q=p58($),Y=n58(Z);return _U1(Q,Y)}function Gc6($,Z,Q,Y){let X=E0().encryptionKey||"dev-secret",J=`${$}:${Z}:${Q}:${Y}`;return m58("sha256",X).update(J).digest("hex")}function c58($,Z,Q,Y,X){let J=Math.floor(Date.now()/1000)+Y,G=Gc6(Z,Q,J,X),W=new URL(`/api/dev-assets/${Z}/${n58(Q)}`,$);return W.searchParams.set("expires",J.toString()),W.searchParams.set("signature",G),W.searchParams.set("method",X),W.toString()}function t58($,Z,Q){let Y=`${$}:${Z.getTime()}:${Q}`;return`"${m58("md5","etag").update(Y).digest("hex")}"`}async function o58($,Z,Q,Y,X){try{let J=await Yc6($,{withFileTypes:!0});for(let G of J){let W=_U1($,G.name),H=Xc6(Z,W).replace(/\\/g,"/");if(Q&&!H.startsWith(Q))continue;if(G.isDirectory())if(Y){let F=H+"/";if(!Q||F.startsWith(Q)){if(!(Q?H.slice(Q.length):H).includes("/"))X.commonPrefixes.add(F)}}else await o58(W,Z,Q,Y,X);else if(G.isFile()){if(Y&&Q){let F=H.slice(Q.length);if(F.includes(Y)){let U=F.indexOf(Y),N=Q+F.slice(0,U+1);X.commonPrefixes.add(N);continue}}try{let F=await d58(W);X.objects.push({key:H,size:F.size,lastModified:F.mtime.toISOString(),etag:t58(W,F.mtime,F.size)})}catch{}}}}catch{}}function r58($,Z){let Y=K0($).id;return[{name:"LIST_OBJECTS",description:"List objects in the local assets directory with pagination support",inputSchema:s$.object({prefix:s$.string().optional(),maxKeys:s$.number().optional().default(1000),continuationToken:s$.string().optional(),delimiter:s$.string().optional()}),outputSchema:s$.object({objects:s$.array(s$.object({key:s$.string(),size:s$.number(),lastModified:s$.string(),etag:s$.string()})),nextContinuationToken:s$.string().optional(),isTruncated:s$.boolean(),commonPrefixes:s$.array(s$.string()).optional()}),handler:async(X)=>{let J=X,G=J.prefix||"",W=J.maxKeys??1000,K=J.delimiter,H=J.continuationToken,F=p58(Y);await Qc6(F,{recursive:!0});let U={objects:[],commonPrefixes:new Set};await o58(F,F,G,K,U),U.objects.sort((w,j)=>w.key.localeCompare(j.key));let N=0;if(H){if(N=U.objects.findIndex((w)=>w.key>H),N===-1)N=U.objects.length}let B=U.objects.slice(N,N+W),O=N+W<U.objects.length,L=O?B[B.length-1]?.key:void 0;return{objects:B,isTruncated:O,nextContinuationToken:L,commonPrefixes:Array.from(U.commonPrefixes).sort()}}},{name:"GET_OBJECT_METADATA",description:"Get metadata for a file in the local assets directory",inputSchema:s$.object({key:s$.string()}),outputSchema:s$.object({contentType:s$.string().optional(),contentLength:s$.number(),lastModified:s$.string(),etag:s$.string(),metadata:s$.record(s$.string(),s$.string()).optional()}),handler:async(X)=>{let J=X,G=CU1(Y,J.key),W=await d58(G);return{contentType:JH1(J.key),contentLength:W.size,lastModified:W.mtime.toISOString(),etag:t58(G,W.mtime,W.size)}}},{name:"GET_PRESIGNED_URL",description:"Generate a presigned URL for downloading a file from local storage",inputSchema:s$.object({key:s$.string(),expiresIn:s$.number().optional()}),outputSchema:s$.object({url:s$.string(),expiresIn:s$.number()}),handler:async(X)=>{let J=X,G=zO(J.expiresIn,l58);return{url:c58(Z,Y,J.key,G,"GET"),expiresIn:G}}},{name:"PUT_PRESIGNED_URL",description:"Generate a presigned URL for uploading a file to local storage",inputSchema:s$.object({key:s$.string(),expiresIn:s$.number().optional(),contentType:s$.string().optional()}),outputSchema:s$.object({url:s$.string(),expiresIn:s$.number()}),handler:async(X)=>{let J=X,G=zO(J.expiresIn,l58);return{url:c58(Z,Y,J.key,G,"PUT"),expiresIn:G}}},{name:"DELETE_OBJECT",description:"Delete a single file from local storage",inputSchema:s$.object({key:s$.string()}),outputSchema:s$.object({success:s$.boolean(),key:s$.string()}),handler:async(X)=>{let J=X,G=CU1(Y,J.key);try{return await u58(G),{success:!0,key:J.key}}catch{return{success:!1,key:J.key}}}},{name:"DELETE_OBJECTS",description:"Delete multiple files from local storage",inputSchema:s$.object({keys:s$.array(s$.string()).max(1000)}),outputSchema:s$.object({deleted:s$.array(s$.string()),errors:s$.array(s$.object({key:s$.string(),message:s$.string()}))}),handler:async(X)=>{let J=X,G=[],W=[];return await Promise.all(J.keys.map(async(K)=>{let H=CU1(Y,K);try{await u58(H),G.push(K)}catch(F){W.push({key:K,message:F instanceof Error?F.message:"Unknown error"})}})),{deleted:G,errors:W}}}]}async function vU1($,Z,Q){let Y=r58(Z,Q),X=new ML({name:"dev-assets-mcp",version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:PZ});for(let G of Y){let W="shape"in G.inputSchema?G.inputSchema.shape:s$.object({}).shape,K=G.outputSchema&&"shape"in G.outputSchema?G.outputSchema.shape:s$.object({}).shape;X.registerTool(G.name,{description:G.description??"",inputSchema:W,outputSchema:K,annotations:G.annotations,_meta:G._meta},async(H)=>{try{let F=await G.handler(H);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}})}let J=new Y3({enableJsonResponse:$.headers.get("Accept")?.includes("application/json")??!1});return await X.connect(J),MW(X,J,$,"mcp:dev-assets")}async function s58($,Z,Q,Y){let J=r58(Q,Y).find((G)=>G.name===$);if(!J)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};try{let G=await J.handler(Z);return{content:[{type:"text",text:JSON.stringify(G)}]}}catch(G){return{content:[{type:"text",text:G instanceof Error?G.message:String(G)}],isError:!0}}}var Jc6="./data/assets",l58=3600,i58,a58;var e58=D(()=>{F$();um();G8();mY0();hm();aX();PO();tV0();i58=new Q1;i58.all("/",async($)=>{let Z=$.get("studioContext"),Q=new URL($.req.url),Y=`${Q.protocol}//${Q.host}`;return vU1($.req.raw,Z,Y)});a58=i58});var $98={};M6($98,{mountDevRoutes:()=>Wc6});function Wc6($,Z){$.all("/mcp/:connectionId{.*_dev-assets$}",Z,async(Y)=>{let X=Y.get("studioContext"),J=new URL(Y.req.url),G=`${J.protocol}//${J.host}`;return vU1(Y.req.raw,X,G)}),$.all("/mcp/:connectionId{.*_dev-assets$}/call-tool/:toolName",Z,async(Y)=>{let X=Y.get("studioContext"),J=new URL(Y.req.url),G=`${J.protocol}//${J.host}`,W=Y.req.param("toolName");if(!W)return Y.json({error:"Missing tool name"},400);let K=await Y.req.json(),H=await s58(W,K,X,G);if(H.isError)return Y.json(H.content,500);return Y.json(H.content)}),$.use("/mcp/dev-assets",Z),$.route("/mcp/dev-assets",a58);let Q=new Q1;Q.use("*",RH({mountPath:"/api/dev-assets"})),Q.route("/",nV0({orgFromPath:!1})),$.route("/api/dev-assets",Q)}var Z98=D(()=>{G8();aK1();tV0();e58()});var U98={};M6(U98,{watchHandler:()=>F98,resolveCorsOrigin:()=>K98,isSsoExemptPath:()=>G98,isAllowedOAuthRedirectUri:()=>H98,createApp:()=>wc6});import{readFileSync as Kc6}from"fs";import{PrometheusSerializer as Hc6}from"@opentelemetry/exporter-prometheus";import{DBOS as gO}from"@dbos-inc/dbos-sdk";import{oAuthDiscoveryMetadata as Nc6,oAuthProtectedResourceMetadata as Bc6}from"better-auth/plugins";async function Fc6($){let Z=$.connect(),Q;try{Q=await Promise.race([Z,Y98(Q98)])}catch{return Z.then((Y)=>Y.release(!0)).catch(()=>{}),!1}try{return await Promise.race([Q.query("SELECT 1"),Y98(Q98)]),Q.release(),!0}catch{return Q.release(!0),!1}}function Y98($){return new Promise((Z,Q)=>setTimeout(()=>Q(Error("pg health-check timeout")),$))}function G98($){return $.startsWith("/api/org-sso/")||/^\/api\/[^/]+\/sso\//.test($)||$.startsWith("/api/auth/")||$.startsWith("/api/tools/management")||$.startsWith("/oauth-proxy/")||/^\/api\/[^/]+\/oauth-proxy\//.test($)||$.startsWith(`${vV0}/`)||$.startsWith(`${IV0}/`)}function W98($){return $==="local.studio.decocms.com"}function K98($,{baseUrl:Z,requestOrigin:Q}){let Y;try{Y=new URL($).hostname}catch{return null}if(Y==="localhost"||Y==="127.0.0.1")return $;if(W98(Y))return $;let X=Z??Q;try{if(new URL(X).origin===$)return $}catch{}return null}function H98($,Z){return $.origin===new URL(Z).origin||$.hostname==="localhost"||W98($.hostname)}async function wc6($={}){let Z=$.database??P8(),Q=!1;e5.stop().catch((Q0)=>{console.error("[SSEHub] Error stopping previous broadcast (HMR cleanup):",Q0)});let Y,X,J,G,W=new LU1,K,H,F,U=null;if($.disableNats)K=wU1(),Y={get:async()=>null,set:async()=>{},invalidate:async()=>{},teardown:()=>{}},X=null,J=null,G=new h10,H={start:async()=>{},broadcast:()=>{},stop:async()=>{}},F={init:async()=>{},pump:(Q0)=>{return(async()=>{let w0=Q0.getReader();try{while(!0){let{done:e}=await w0.read();if(e)break}}catch{}finally{w0.releaseLock()}})()},publishRawChunk:async()=>!1,publishDone:async()=>!1,createTailStream:async()=>null,purge:()=>{},teardown:()=>{}};else{U=N58();let Q0=E0().natsCredsPath,w0;if(Q0)try{w0=Kc6(Q0,"utf8")}catch(f0){console.error(`[app] failed to read NATS_CREDS at ${Q0}; connecting anonymously`,f0)}U.init(E0().natsUrls,w0?{creds:w0}:void 0);let e=me0()?new Me0({getJetStream:()=>U.getJetStream()}):null;e?.init().catch(()=>{}),Y=e;let i=new g41({getJetStream:()=>U.getJetStream()});i.init().catch(()=>{}),X=i;let m0=new ax(V91,{getJetStream:()=>U.getJetStream()}),I0=new ax(Y10,{getJetStream:()=>U.getJetStream()});m0.init().catch(()=>{}),I0.init().catch(()=>{}),J={reads:m0,cards:I0};let t0=new LQ1({getJetStream:()=>U.getJetStream()});t0.init().catch(()=>{}),G=t0,K=wU1({getConnection:()=>U.getConnection()}),H=new jU1({getConnection:()=>U.getConnection()}),F=new PU1({getConnection:()=>U.getConnection(),getJetStream:()=>U.getJetStream()}),Ha$(U),U.onReady(()=>{e?.init().catch((f0)=>{console.error("[McpListCache] Deferred init failed:",f0)}),i.init().catch((f0)=>{console.error("[SkillCatalogCache] Deferred init failed:",f0)}),m0.init().catch((f0)=>{console.error("[PrReadCache] Deferred init failed:",f0)}),I0.init().catch((f0)=>{console.error("[PrCardCache] Deferred init failed:",f0)}),t0.init().catch((f0)=>{console.error("[ConnectionCircuitStore] Deferred init failed:",f0)}),K.start(),gK$(()=>U.getConnection()),F.init().catch((f0)=>{console.warn("[Decopilot] StreamBuffer init failed (late-join disabled):",f0)})})}if(PE)await PE();Ie0(Y),u41(X),k91(J),wQ1(G);let B={storage:new Hh(Z.db),sseHub:e5,onThreadFinished:async(Q0,w0)=>Tm(new sG(Z.db),Q0,w0,new DG(Z.db))},O=new lZ1(B),L=new J80(Z.db),w=new AU1(L);w.start(),E_$(H),H.start((Q0)=>{lT0(Q0),O.execute({type:"CANCEL",taskId:Q0}).catch((w0)=>{console.error("[Decopilot] CancelBroadcast execute failed:",w0)})}).catch((Q0)=>{console.error("[Decopilot] CancelBroadcast start failed:",Q0)}),U?.onReady(()=>{H.start().catch((Q0)=>{console.error("[CancelBroadcast] Deferred start failed:",Q0)})});let j=()=>U?.getConnection()??null;tK1(j),U?.onReady(()=>tK1(j)),oQ1(j),U?.onReady(()=>oQ1(j)),F.init().catch((Q0)=>{console.warn("[Decopilot] StreamBuffer init failed, attach/late-join disabled:",Q0)}),PE=async()=>{await O.stopAll(),O.dispose(),w.dispose(),H.stop().catch(()=>{}),qe$(),F.teardown(),Y?.teardown(),X?.teardown(),J?.reads.teardown(),J?.cards.teardown(),W.teardown(),K.teardown(),hK$(),G.teardown(),Ie0(null),u41(null),k91(null),wQ1(null)};let E=new Q1;if(E.use("*",BQ1({enabled:(Q0)=>pd(Q0,"debug")==="1"})),E.use("*",VS0),E.use("/*",Xa$({origin:(Q0,w0)=>K98(Q0,{baseUrl:E0().baseUrl,requestOrigin:new URL(w0.req.url).origin}),credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"],exposeHeaders:["WWW-Authenticate"]})),E.use("*",async(Q0,w0)=>{if(await w0(),Q0.req.path.includes("/files/"))return;if(Q0.req.path.includes("/fs/")&&Q0.req.path.endsWith("/read"))return;Q0.header("X-Frame-Options","DENY"),Q0.header("Content-Security-Policy","frame-ancestors 'none'")}),!E0().noTui)E.use("*",g58());E.use("*",async(Q0,w0)=>{if(await w0(),bi(Q0.req.path))return;if(Q0.res.status>=500){let i=await Q0.res.clone().text();console.error(`[5xx Response] ${Q0.req.method} ${Q0.req.path} - ${Q0.res.status}:`,i)}}),E.get(mY.HEALTH,(Q0)=>{if(Q)return Q0.json({status:"shutting_down"},503);return Q0.json({status:"ok"})}),E.get(mY.HEALTH_LIVE,(Q0)=>{return Q0.json({status:"ok"})}),E.get(mY.HEALTH_READY,async(Q0)=>{if(Q)return Q0.json({status:"shutting_down"},503);let w0={};if(w0.postgres={status:await Fc6(Z.pool)?"up":"down"},U)w0.nats=U.isConnected()?{status:"up"}:{status:"down"};else w0.nats={status:"down"};let e=w0.postgres.status==="up",i=e?200:503;return Q0.json({status:e?"ready":"not_ready",services:w0},i)}),E.get(mY.METRICS,async(Q0)=>{try{let w0=await _S0.collect(),e=Uc6.serialize(w0.resourceMetrics);return Q0.text(e,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch(w0){return console.error("Failed to collect metrics:",w0),Q0.text("# Error collecting metrics",500)}});let z=1800000;E.get(`${mY.DBOS_QUEUE_DEPTH_PREFIX}:queueName`,async(Q0)=>{let w0=Q0.req.param("queueName");if(!Oc6.has(w0))return Q0.json({error:`Unknown queue: ${w0}`},404);let[e,i]=await Promise.all([gO.listQueuedWorkflows({queueName:w0,status:"ENQUEUED",loadInput:!1,loadOutput:!1}),gO.listQueuedWorkflows({queueName:w0,status:"PENDING",loadInput:!1,loadOutput:!1,dequeuedAfter:new Date(Date.now()-z).toISOString()})]);return Q0.json({queue_length:e.length,in_flight:i.length})}),E.route("/api/config",z68),E.route("/api/_reports",_68),E.route("/api/_stripe",NU1),E.route("/api/_github",x68({taskBoard:()=>n,contextFactory:()=>g})),E.route("/api/_git",$i);let T={db:Z.db,encryptionKey:E0().encryptionKey};E.route("/api/_jira",h68(T)),E.route("/api/_jira",y68(T)),E.route("/report",k68($.clientDir)),E.route("/api/auth/custom",ka$),E.route("/api/auth/desktop",va$),E.all("/api/auth/admin/*",Ue$),E.all("/api/auth/*",async(Q0)=>{return await C8.handler(Q0.req.raw)});let P=yr$();P.use("/.well-known/oauth-protected-resource/mcp/:connectionId",j80),P.use("/mcp/:connectionId/.well-known/oauth-protected-resource",j80),E.route("/",P),E.get("/.well-known/oauth-protected-resource/api/:org/mcp/:connectionId",Z80),E.route("/",cr$()),E.use("/oauth-proxy/:connectionId/*",j80),E.all("/oauth-proxy/:connectionId/*",X98);let A=async(Q0)=>{let e=await Dc6()(Q0.req.raw),i=await e.json();return Response.json(i,e)};E.use("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",j80),E.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",A);let q=async(Q0)=>{let e=await Lc6()(Q0.req.raw),i=await e.json();return Response.json(i,e)};E.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",q);let x=Ga$({ttlMs:120000}),_=await Cs$({db:Z.db,auth:C8,encryption:{key:E0().encryptionKey},observability:{tracer:nO,meter:z$},modelListCache:W,providerKeyCache:K,memberRoleCache:x});vQ.set(_),Sc1({db:Z.db,baseUrl:x5()}),_s$({db:Z.db}),fs$({db:Z.db}),ds$({db:Z.db}),c68({db:Z.db,encryptionKey:E0().encryptionKey}),rI$({db:Z.db}),rs$({db:Z.db}),EV$({db:Z.db});let V=_Q0(Z.db),y=new No(Z.db),g=b58({db:Z.db});HQ1({storage:V,studioContextFactory:g}),sZ1({systemDatabaseUrl:nt0(E0().databaseUrl,E0().databasePgSsl),studioContextFactory:g,deps:{runRegistry:O,cancelBroadcast:H,streamBuffer:F,sseHub:e5}}),dZ1({dispatchRunFn:HC$,studioContextFactory:g,deps:{runRegistry:O,cancelBroadcast:H,streamBuffer:F,sseHub:e5}});let l=new Hh(Z.db),n=new sG(Z.db),p=new DG(Z.db),F0=new RU1(n,g,p);if(E0().taskBoardReviewSweeperEnabled){F0.start();let Q0=PE;PE=async()=>{await Q0?.(),F0.dispose()}}SC$({getJetStream:()=>U?.getJetStream()??null,getJetStreamManager:async()=>{let Q0=U?.getConnection();return Q0?await J98.jetstreamManager(Q0):null},messageParts:l.messageParts(),resolveRun:async(Q0)=>{let w0=await Z.db.selectFrom("threads").select(["organization_id","created_by","message_storage_version","status","run_fence_token","title"]).where("id","=",Q0).executeTakeFirst();return w0?{orgId:w0.organization_id,createdBy:w0.created_by,version:w0.message_storage_version??1,status:w0.status,runFenceToken:w0.run_fence_token,title:w0.title??null}:null},completeRunIfNotCompleted:async(Q0,w0)=>{let e=await l.completeRunIfNotCompleted(Q0,w0);if(YS0(e5,w0,Q0,e),e)await Tm(n,Q0,w0,p);return e},markRunRequiresAction:async(Q0,w0)=>{let e=await l.requiresActionIfInProgress(Q0,w0);return YS0(e5,w0,Q0,e),e},markRunFailed:async(Q0,w0,e,i)=>{let m0=await l.markRunFailed(Q0,w0,e,i);if(YS0(e5,w0,Q0,m0),m0)await Tm(n,Q0,w0,p);return m0},clearSynthesizedError:async(Q0,w0)=>{await l.messageParts().replaceMessageParts(Q0,xj(Q0,w0),[])},persistTitle:(Q0,w0,e)=>l.update(Q0,w0,{title:e}),onTitleUpdated:async({runId:Q0,orgId:w0,title:e})=>{let i=await l.get(Q0,w0).catch(()=>null);e5.emit(w0,nH(Q0,i?.status??"in_progress",{title:e,virtualMcpId:i?.virtual_mcp_id??void 0,createdBy:i?.created_by,triggerId:i?.trigger_id,branch:i?.branch??null,harnessId:i?.harness_id??void 0,createdAt:i?.created_at,updatedAt:i?.updated_at}))},bumpProgress:async({runId:Q0,orgId:w0})=>{await l.bumpProgress(Q0,w0)},recordCompleted:async({runId:Q0,orgId:w0,distinctId:e,usage:i})=>{v1.capture({distinctId:e,event:"chat_message_completed",groups:{organization:w0},properties:{organization_id:w0,thread_id:Q0,transport:"projector",input_tokens:i.inputTokens,output_tokens:i.outputTokens,total_tokens:i.totalTokens}})},recordFailed:async({runId:Q0,orgId:w0,distinctId:e,reason:i,kind:m0})=>{v1.capture({distinctId:e,event:"chat_message_failed",groups:{organization:w0},properties:{organization_id:w0,thread_id:Q0,transport:"projector",error_category:m0,error_message:i}})},purgeRun:async(Q0)=>{F.purge(Q0)}}),xS$({studioContextFactory:g,systemDatabaseUrl:nt0(E0().databaseUrl,E0().databasePgSsl),streamBuffer:F}),_58(),Cc1(),bs$(),gs$(),ps$(),i68(),ZV$(),as$(),zV$();let V0=async(Q0,w0,e)=>{let i=await V.findById(Q0,w0);if(!i)throw Error("Automation not found");return NQ1({automationId:i.id,organizationId:i.organization_id,triggerId:null})},G0=new ad(V,({automation:Q0,trigger:w0,contextMessages:e,idempotencyKey:i})=>g10({automationId:Q0.id,organizationId:Q0.organization_id,triggerId:w0.id,contextMessages:e},{idempotencyKey:i})),H0=[uW(),Ty(),eU()];for(let Q0 of H0)GS0(Q0).then(()=>{}).catch((w0)=>console.error("[monitoring] Retention cleanup failed:",w0));let X0=()=>C8.api.deleteAllExpiredApiKeys().catch((Q0)=>console.error("[auth] Expired API key cleanup failed:",Q0));X0(),setInterval(X0,86400000).unref(),E.use("*",async(Q0,w0)=>{if(MS0(Q0.req.path))return w0();let e={measure:async(m0,I0)=>{qW(Q0,m0);try{return await I0()}finally{X3(Q0,m0)}}},i=await vQ.create(Q0.req.raw,{timings:e});i.automationRunner=V0,Q0.set("studioContext",i);try{await w0()}finally{let m0=i.pendingRevalidations;if(m0.length>0)Promise.race([Promise.allSettled(m0),i$(30000)]).catch((t0)=>console.error("[studio] revalidation cleanup error:",t0))}}),E.use("/api/:org/decopilot/*",td),E.use("/api/:org/v1/*",td),E.use("/api/:org/files/*",td),E.use("*",async(Q0,w0)=>{if(G98(Q0.req.path))return w0();let e=Q0.get("studioContext");if(!e?.organization?.id||!e?.auth?.user?.id)return w0();if(!(await e.storage.orgSsoConfig.getByOrgId(e.organization.id))?.enforced)return w0();if(!await e.storage.orgSsoSessions.isValid(e.auth.user.id,e.organization.id))return Q0.json({error:"SSO authentication required for this organization"},403);return w0()});let Z0=new Q1;Z0.use("*",RH({mountPath:"/api/org-sso"})),Z0.route("/",fV0()),E.route("/api/org-sso",Z0),E.get("/api/tools/management",(Q0)=>{return Q0.json({tools:Vi0,grouped:BP()})}),E.use("/mcp/*",async(Q0,w0)=>{qW(Q0,"mcp");try{return await w0()}finally{X3(Q0,"mcp")}});let Y0=async(Q0,w0)=>{let e=Q0.var.studioContext;if(!e.auth.user?.id&&!e.auth.apiKey?.id){let i=new URL(Q0.req.url),m0=Q0.req.header("x-forwarded-proto")?.split(",")[0]?.trim(),I0=m0?`${m0}://${i.host}`:i.origin;return Q0.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${I0}${i.pathname}/.well-known/oauth-protected-resource"`}})}return await w0()};if(E.use("/mcp/:connectionId?",Y0),E.use("/mcp/gateway/:virtualMcpId?",Y0),E.use("/mcp/virtual-mcp/:virtualMcpId?",Y0),E.use("/mcp/self",Y0),JW()){let{mountDevRoutes:Q0}=(Z98(),OS0($98));Q0(E,Y0)}let o=new Q1;o.use("*",RH({mountPath:"/mcp"})),o.route("/",vR0()),E.route("/mcp",o);let J0=new Q1;J0.use("*",RH({mountPath:"/mcp/self"})),J0.route("/",qk0()),E.route("/mcp/self",J0);let c0=new Q1;c0.use("*",RH({mountPath:"/mcp"})),c0.route("/",fR0()),E.route("/mcp",c0),E.use("/api/:org/models/*",async(Q0,w0)=>{qW(Q0,"llm_models");try{return await w0()}finally{X3(Q0,"llm_models")}});let k0=Ie$({cancelBroadcast:H,streamBuffer:F,runRegistry:O});E.route("/api",k0),E.route("/api",o68);let j1=new Q1;j1.use("*",RH({mountPath:"/api"})),j1.route("/",kk0()),E.route("/api",j1),E.route("/api",B68);let d0=new Q1;d0.use("*",RH({mountPath:"/api"})),d0.route("/",Sk0({tokenStorage:y,automationEventDispatcher:G0})),E.route("/api",d0);let L0=new Oo(Z.db),j0=new Q1;j0.use("*",RH({mountPath:"/api"})),j0.route("/",lV0()),E.route("/api",j0),E.route("/api/deco-sites",le$()),E.route("/api/deco-apps",W68());let a0=new Q1;a0.use("*",RH({mountPath:"/api/deco-sites"})),a0.route("/",mV0()),E.route("/api/deco-sites",a0),E.route(vV0,Ne$()),E.route(E88,A88()),E.route("/api/_editor-resolve",D68()),E.route(xa$,fa$()),E.route(IV0,pa$());let P1=J68({kvStorage:L0,runRegistry:O,streamBuffer:F,sseHub:e5,cancelBroadcast:H,tokenStorage:y,automationEventDispatcher:G0,mountDevAssets:JW(),mcpAuth:Y0,oauthProxyHandler:X98,watchHandler:F98,betterAuthProtectedResourceHandler:A,getNatsConnection:()=>U?.getConnection()??null});return E.route("/api/:org",P1),E.notFound((Q0)=>{return Q0.json({error:"Not Found",path:Q0.req.path},404)}),E.onError(Se$),Object.assign(E,{markShuttingDown:()=>{Q=!0},shutdown:async()=>{if(console.log("[shutdown] Stopping workers..."),await Promise.allSettled([e5.stop(),PE?Promise.resolve(PE()).finally(()=>{PE=null}):Promise.resolve()]),U)await U.drain().catch((Q0)=>console.error("[shutdown] NATS drain error:",Q0));console.log("[shutdown] Flushing telemetry..."),await fX().catch((Q0)=>console.error("[shutdown] Telemetry flush error:",Q0)),console.log("[shutdown] Closing database..."),await q4$(Z).catch((Q0)=>console.error("[shutdown] Database close error:",Q0)),console.log("[shutdown] Cleanup complete.")},initDbos:async()=>{await gO.registerQueue(O3,{partitionQueue:!0,concurrency:GQ1,minPollingIntervalMs:WQ1}),await gO.registerQueue(B3,{partitionQueue:!0,concurrency:oZ1,priorityEnabled:!0}),await gO.registerQueue(sU,{workerConcurrency:E0().decopilotMaxConcurrentHostedRuns,priorityEnabled:!0}),await gO.registerQueue(aU,{workerConcurrency:E0().sandboxMaxConcurrentHostedRuns,priorityEnabled:!0}),await gO.registerQueue(iO,{partitionQueue:!0,concurrency:bS$}),await gO.registerQueue(ME,jV$),await eK1(V),await Promise.allSettled(["automations-gate","automations-global","jira-push"].map((Q0)=>gO.deleteQueue(Q0))),await KQ1(Z.pool),p9$().catch((Q0)=>{console.error("[studio-pack-backfill] failed:",Q0)}),_c1().catch((Q0)=>{console.error("[org-fs] public-sets boot sync kick failed:",Q0)})}})}var J98,Q98=5000,PE=null,X98=async($)=>{let Z=$.req.param("connectionId");if(!Z)return $.json({error:"Missing connectionId"},400);let Q=$.req.path.split("/").filter(Boolean),Y=Q[Q.length-1],X=$.get("studioContext");if(!X)X=await vQ.create($.req.raw),$.set("studioContext",X);let J=$.req.param("org")?X.organization?.id:void 0,G=await X.storage.connections.findById(Z,J);if(!G?.connection_url)return $.json({error:"Connection not found"},404);if(Y==="register"&&G.oauth_config?.clientId){let y=await $.req.json().catch(()=>({}));return $.json({...typeof y==="object"&&y!==null?y:{},client_id:G.oauth_config.clientId,...G.oauth_config.clientSecret?{client_secret:G.oauth_config.clientSecret}:{},client_secret_expires_at:0})}let W=await cd(G.connection_url),K,H=new URL(G.connection_url),U=(typeof G.metadata?.oauthResource==="string"&&G.metadata.oauthResource.length>0?G.metadata.oauthResource:void 0)??G.connection_url;if(W.ok)K=(await W.json()).authorization_servers?.[0];if(!K)K=H.origin;let N=await Q80(K);if(!N.ok)return $.json({error:"Failed to get auth server metadata"},502);let B=await N.json(),O;if(Y==="authorize")O=B.authorization_endpoint;else if(Y==="token")O=B.token_endpoint;else if(Y==="register")O=B.registration_endpoint;if(!O)return $.json({error:`Unknown OAuth endpoint: ${Y}`},404);let L=lr$(O);if(L)return L;let w=new URL(O),j=new URL($.req.url);if(w.search=j.search,Y==="authorize"){let y=w.searchParams.get("redirect_uri");if(y){let g=E0().baseUrl??j.origin;try{if(!H98(new URL(y),g))return $.json({error:"invalid_request",error_description:"redirect_uri is not allowed"},400)}catch{return $.json({error:"invalid_request",error_description:"redirect_uri is malformed"},400)}w.searchParams.set("redirect_uri",y)}if(w.searchParams.has("resource"))w.searchParams.set("resource",U);if($a$(G.connection_url))w.searchParams.set("auto_personal","true"),w.searchParams.set("force_new","true");return $.redirect(w.toString(),302)}let E={Accept:$.req.header("Accept")||"application/json"},z=$.req.header("Content-Type");if(z)E["Content-Type"]=z;let T=$.req.header("Authorization");if(T)E.Authorization=T;let P,A=null,q=null;if($.req.method!=="GET"&&$.req.method!=="HEAD")if(Y==="token"&&z?.includes("application/x-www-form-urlencoded")){if(T?.toLowerCase().startsWith("basic "))try{let p=atob(T.slice(6).trim()),F0=p.indexOf(":");if(F0!==-1){let V0=decodeURIComponent(p.slice(0,F0)),G0=decodeURIComponent(p.slice(F0+1));A=V0||null,q=G0||null}}catch{}let y=await $.req.formData();if(y.has("resource"))y.set("resource",U);let g=y.get("client_id"),l=y.get("client_secret");if(typeof g==="string"&&g)A=g;if(typeof l==="string"&&l)q=l;let n=new URLSearchParams;for(let[p,F0]of y.entries())n.append(p,F0.toString());P=n.toString()}else if(Y==="register"&&z?.toLowerCase().includes("application/json")){let y=await X.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",G.organization_id).executeTakeFirst(),g=await $.req.text(),l={};try{l=g?JSON.parse(g):{}}catch{P=g}let n=typeof l==="object"&&l!==null&&!Array.isArray(l);if(P===void 0&&!n)P=g;if(P===void 0){let p=l,F0=p.metadata&&typeof p.metadata==="object"?p.metadata:{};p.metadata={...F0,organization_id:G.organization_id,...y?.slug?{organization_slug:y.slug}:{},...y?.name?{organization_name:y.name}:{}},P=JSON.stringify(p),E["Content-Type"]="application/json"}}else P=$.req.raw.body??void 0;let x=await fetch(w.toString(),{method:$.req.method,headers:E,body:P,duplex:"half",redirect:"manual"}),_=new Headers,V=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[y,g]of x.headers.entries())if(!V.includes(y.toLowerCase()))_.set(y,g);if(Y==="token"&&x.ok){let y=await x.text();try{let g=JSON.parse(y);if(typeof g.access_token==="string"&&g.access_token){let l=typeof g.expires_in==="number"?new Date(Date.now()+g.expires_in*1000):null,n=null;try{n=await md(G.connection_url)??O}catch{n=O}let p={connectionId:Z,accessToken:g.access_token,refreshToken:typeof g.refresh_token==="string"?g.refresh_token:null,scope:typeof g.scope==="string"?g.scope:null,expiresAt:l,clientId:A,clientSecret:q,tokenEndpoint:n};await new F9(X.db,X.vault).upsert(p)}}catch(g){console.error("[oauth-proxy] failed to persist downstream token:",g)}return new Response(y,{status:x.status,statusText:x.statusText,headers:_})}return new Response(x.body,{status:x.status,statusText:x.statusText,headers:_})},F98=async($)=>{let Z=$.var.studioContext,Q=Z.auth.user?.id??Z.auth.apiKey?.userId;if(!Q)return $.json({error:"Unauthorized"},401);let Y=Z.organization?.id;if(!Y)return $.json({error:"organization id missing"},400);let X=$.req.query("types"),J=X?X.split(",").map((H)=>H.trim()).filter(Boolean):null,G=$.req.query("scope")==="all";if(G&&(!DU(Y)||!await LU(Z)))return $.json({error:"forbidden"},403);let W=G?a20:Y;if(G)XO({action:"watch_all_orgs",actorUserId:Q,actorOrgId:Y,targetOrgId:"all"});let K=crypto.randomUUID();return bO($,async(H)=>{if(await H.writeSSE({event:"connected",data:JSON.stringify({listenerId:K,organizationId:Y,typePatterns:J,connectedAt:new Date().toISOString()})}),!e5.add({id:K,organizationId:W,typePatterns:J?.length?J:null,push:(N,B)=>{H.writeSSE({id:N.id,event:N.type,data:JSON.stringify(G?{...N,organizationId:B}:N)}).catch(()=>{e5.remove(W,K)})}})){await H.writeSSE({event:"error",data:JSON.stringify({error:"Too many connections",message:"SSE connection limit reached. Try again later."})});return}let U=setInterval(()=>{H.writeSSE({event:"keepalive",data:""}).catch(()=>{clearInterval(U),e5.remove(W,K)})},30000);await new Promise((N)=>{H.onAbort(()=>{clearInterval(U),e5.remove(W,K),N()})})})},Uc6,Oc6,Dc6=()=>Bc6(C8),Lc6=()=>Nc6(C8);var N98=D(()=>{D8();F$();vc1();xs$();hs$();ns$();d10();U91();es$();Q10();E9();al();e8();G8();AV0();Ja$();OQ1();hG();pF();RK1();m3();C6();U6();CK1();ba$();ya$();na$();yK1();Be$();iK1();Ve$();sK1();iK();GV0();aK1();Ce$();RV0();G68();QH1();K68();bR0();u10();O68();yR0();CF1();L68();kF1();P68();S68();v68();b68();f68();g68();u68();p68();WH1();r68();SF1();MF1();P40();B58();DJ();xA0();C91();ya();ha();EQ1();O58();L58();oK1();T58();cZ1();R58();on();Lo();YO();V9();iW1();k58();v58();LJ0();qU1();D3();$H1();QO();hZ1();LJ0();sT0();Li0();wi0();x58();Hu();h58();Li();RK1();Lm();Cm();cT0();J98=C(GN(),1);Uc6=new Hc6,Oc6=new Set([O3,B3,sU,aU,iO,ME])});var L98={};M6(L98,{resolveClientDir:()=>Rc6,resolveAssetPathWithTraversalCheck:()=>D98,isPathWithinDirectory:()=>O98,createAssetHandler:()=>qc6});import{resolve as G40,dirname as jc6,join as Ec6,extname as zc6,basename as Pc6,sep as B98}from"path";function Ac6($,Z){if($===Z||Pc6($)==="index.html")return{"Cache-Control":"no-cache"};if($.includes(`${B98}assets${B98}`))return{"Cache-Control":"public, max-age=31536000, immutable"};return{}}function O98($,Z){let Q=G40(Z),Y=G40($);return Y===Q||Y.startsWith(Q+"/")}function D98({requestPath:$,clientDir:Z}){let Q=$.startsWith("/")?$.slice(1):$,Y=G40(Z,Q);if(!O98(Y,Z))return null;return Y}function Rc6($,Z="../client"){let Q=new URL($),Y=jc6(Q.pathname);return G40(Y,Z)}function qc6($={}){let{env:Z="production",clientDir:Q=Tc6,isServerPath:Y=()=>!1}=$;if(Z==="development")return async function(J){return null};return async function(J){if(J.method!=="GET")return null;let G=new URL(J.url),W;try{W=decodeURIComponent(G.pathname)}catch{return null}if(Y(W))return null;let K=D98({requestPath:W,clientDir:Q});if(!K)return null;let H=Ec6(K,"index.html"),F=G40(Q,"index.html"),U=J.headers.get("accept"),B=U?.includes("text/html")||U?.includes("*/*")&&["",".html"].includes(zc6(K))?[H,F]:[];for(let O of[K,...B])try{let L=Bun.file(O);if(await L.exists())return new Response(L,{headers:Ac6(O,F)})}catch{}if(W.includes("/assets/"))return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});return null}}var Tc6="./dist/client";var w98=()=>{};var j98={};M6(j98,{tryUpgradePreviewWs:()=>_c6,tryHandlePreviewHttp:()=>Cc6,previewWebSocketHandler:()=>vc6,parsePreviewBaseDomain:()=>Sc6,isPreviewWsData:()=>WS0,extractHandleFromHost:()=>bU1});function Vc6($){if($.method!=="GET")return!1;return($.headers.get("accept")??"").includes("text/html")}function kc6(){return new Response(Ic6,{status:503,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","retry-after":"1","access-control-allow-origin":"*"}})}function Sc6($){if(!$||$.trim()==="")return null;let Z=$.includes("{handle}")?$.replace("{handle}","__handle__"):$,Q;try{Q=new URL(Z)}catch{return null}let Y=Q.hostname;if($.includes("{handle}")){let X=Y.indexOf(".");if(X<=0||X===Y.length-1)return null;return Y.slice(X+1)}return Y}function bU1($,Z){if(!$||!Z)return null;let Q=$.indexOf(":"),Y=(Q>=0?$.slice(0,Q):$).toLowerCase(),J=`.${Z.toLowerCase().replace(/^\.+|\.+$/g,"")}`;if(!Y.endsWith(J))return null;let G=Y.slice(0,Y.length-J.length);if(!G||G.includes("."))return null;return G}async function Cc6($,Z){let Q=bU1($.headers.get("host"),Z.baseDomain);if(!Q)return null;let Y=await Z.getRunner();if(!Y)return K40(503,"preview proxy not configured");let X=await Y.proxyPreviewRequest(Q,$);if(X.headers.get(Ix)&&Vc6($))return kc6();return X.headers.delete(Ix),X}function K40($,Z){return new Response(JSON.stringify({error:Z}),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function WS0($){return typeof $==="object"&&$!==null&&$.kind==="preview"}async function _c6($,Z,Q){if(($.headers.get("upgrade")??"").toLowerCase()!=="websocket")return null;let Y=bU1($.headers.get("host"),Q.baseDomain);if(!Y)return null;let X=await Q.getRunner();if(!X)return K40(503,"preview proxy not configured");let J=await X.resolvePreviewUpstreamUrl(Y);if(!J)return K40(404,"sandbox not found");let G=new URL($.url);if(G.pathname.startsWith("/_sandbox"))return K40(404,"not found");let W=`${J.replace(/^http/,"ws")}${G.pathname}${G.search}`,K=$.headers.get("sec-websocket-protocol"),H=K?K.split(",").map((N)=>N.trim()).filter(Boolean):[],F={kind:"preview",upstreamUrl:W,upstreamProtocols:H,pending:[],upstream:null,closed:!1};if(!Z.upgrade($,{data:F}))return K40(426,"upgrade failed");return}function W40($,Z,Q,Y){if(Z.closed)return;Z.closed=!0;try{$.close(Q,Y)}catch{}try{Z.upstream?.close()}catch{}}var Mc6=256,Ic6='<!DOCTYPE html><html><head><meta charset="utf-8"><title>Connecting\u2026</title><style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#fafafa;color:#555}div{text-align:center;max-width:420px;padding:24px}h3{margin:0 0 8px}p{margin:0;font-size:14px;color:#999;line-height:1.5}</style></head><body><div><h3>Connecting to sandbox\u2026</h3><p>Waiting for the sandbox to come online. This page refreshes automatically.</p></div><script>setTimeout(function(){window.location.reload()},1500)</script></body></html>',vc6;var E98=D(()=>{j41();vc6={open($){let Z=$.data;if(!WS0(Z))return;let Q;try{Q=Z.upstreamProtocols.length>0?new WebSocket(Z.upstreamUrl,Z.upstreamProtocols):new WebSocket(Z.upstreamUrl)}catch(Y){console.warn(`[preview-ws] failed to dial upstream ${Z.upstreamUrl}: ${Y instanceof Error?Y.message:String(Y)}`),W40($,Z,1011,"upstream connect failed");return}Q.binaryType="arraybuffer",Z.upstream=Q,Q.addEventListener("open",()=>{while(Z.pending.length>0){let Y=Z.pending.shift();if(Y!==void 0)Q.send(Y)}}),Q.addEventListener("message",(Y)=>{if(Z.closed)return;$.send(Y.data)}),Q.addEventListener("close",(Y)=>{W40($,Z,Y.code||1000,Y.reason||"")}),Q.addEventListener("error",()=>{W40($,Z,1011,"upstream error")})},message($,Z){let Q=$.data;if(!WS0(Q))return;let Y=Q.upstream;if(Y&&Y.readyState===WebSocket.OPEN){Y.send(Z);return}if(Q.pending.length>=Mc6){W40($,Q,1011,"preview ws backlog overflow");return}Q.pending.push(Z)},close($){let Z=$.data;if(!WS0(Z))return;W40($,Z,1000,"")}}});var T98={};M6(T98,{printBanner:()=>xc6,bannerLines:()=>A98,BANNER_LINES:()=>z98,BANNER_GRADIENT:()=>P98});function bc6($){let Z=Number.parseInt($.slice(1),16);return[Z>>16&255,Z>>8&255,Z&255]}function A98($){let Z=z98.map((Q,Y)=>{let[X,J,G]=bc6(P98[Y]);return`\x1B[38;2;${X};${J};${G}m${Q}\x1B[39m`});if($!==void 0)Z.push(`\x1B[2m v${$}\x1B[22m`);return Z}function xc6($){console.log("");for(let Z of A98($))console.log(Z);console.log("")}var z98,P98;var R98=D(()=>{z98=[" \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 "],P98=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"]});D8();var nU1="13";function tU1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:nU1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}D8();import c98 from"pg";var oU1=8314027461559302n,m98=600000,d98=500;async function rU1($,Z){let{databaseUrl:Q,lockTimeoutMs:Y=m98}=$,X=$.log??((K)=>console.log(K)),J=new c98.Client({connectionString:Q});await J.connect();let G=Date.now(),W=!1;try{while(!W){if(W=(await J.query("SELECT pg_try_advisory_lock($1) AS locked",[oU1.toString()])).rows[0]?.locked===!0,W)break;if(Date.now()-G>=Y)throw Error(`Timed out after ${Y}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await i$(d98)}let K=Date.now()-G;if(K>1000)X(`[dbos] waited ${K}ms for the migration lock; another process migrated first`);return await Z()}finally{if(W)try{await J.query("SELECT pg_advisory_unlock($1)",[oU1.toString()])}catch{}await J.end().catch(()=>{})}}F$();jS0();C6();function cZ8(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function xS0($,Z){for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(Y===void 0)continue;if(Y===Z)return $[Q+1];if(Y.startsWith(`${Z}=`))return Y.slice(Z.length+1)}return}function vN1(){let $=cZ8();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:xS0($,"--cpu-prof-dir")??process.cwd(),name:xS0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(xS0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}gS0();var R40;function cN1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=kE();if(!Q)return;let Y={};try{let{heapStats:X}=await import("bun:jsc"),J=X(),G=Object.entries(J.objectTypeCounts).sort((W,K)=>K[1]-W[1]).slice(0,20);Y={objectCount:J.objectCount,heapSize:J.heapSize,top:Object.fromEntries(G)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:Q.rss,heapUsed:Q.heapUsed,heapTotal:Q.heapTotal,external:Q.external,arrayBuffers:Q.arrayBuffers,...Y}))};return Z().catch(()=>{}),R40=setInterval(()=>void Z().catch(()=>{}),$),R40.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),Y=typeof Q==="string"?Q:JSON.stringify(Q),X=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(X,Y),console.log(JSON.stringify({msg:"heap-snapshot-written",path:X}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(R40)clearInterval(R40)}}import*as iZ8 from"bun:jsc";var{startSamplingProfiler:pZ8,samplingProfilerStackTraces:nZ8}=iZ8;function mN1(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{pZ8()}catch(J){return console.error("[stall-watchdog] failed to start sampling profiler:",J),()=>{}}let Q,Y=performance.now()+Z,X=()=>{let J=performance.now(),G=J-Y;Y=J+Z;let W=[];try{W=nZ8()?.traces??[]}catch{}if(G>$&&W.length>0){let K=new Map;for(let F of W){let U=F.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??F.frames[0];if(!U)continue;let N=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${U.name??"?"} @ ${N}:${U.line??"?"}`;K.set(B,(K.get(B)??0)+1)}let H=[...K.entries()].sort((F,U)=>U[1]-F[1]).slice(0,8).map(([F,U])=>({frame:F,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(G),samplesInWindow:W.length,top:H}))}Q=setTimeout(X,Z),Q.unref?.()};return Q=setTimeout(X,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}function dN1(){vN1();let $=[cN1(),lN1(),mN1()];return()=>{for(let Z of $)Z()}}import{existsSync as mc6}from"fs";var pJ=E0();SN1();var{DBOS:H40,DBOSClient:fc6}=await import("@dbos-inc/dbos-sdk");function uU1($,Z){if(!Z)return $;let Q=new URL($);if(!Q.searchParams.has("sslmode"))Q.searchParams.set("sslmode","verify-full");return Q.toString()}var yc6=[O3,B3,sU,aU,iO,ME],gc6=pJ.dispatchRole==="worker"?yc6:pJ.dispatchRole==="api"?[]:void 0;H40.setConfig(tU1({systemDatabaseUrl:uU1(pJ.databaseUrl,pJ.databasePgSsl),poolSize:pJ.dbosPoolSize,executorID:pJ.podName,listenQueues:gc6}));var{createApp:hc6}=await Promise.resolve().then(() => (N98(),U98)),{isServerPath:uc6}=await Promise.resolve().then(() => (P40(),BN1)),{createAssetHandler:lc6,resolveClientDir:k98}=await Promise.resolve().then(() => (w98(),L98)),cc6=pJ.port,q98=k98(import.meta.url,"../client"),S98=mc6(q98)?q98:k98(import.meta.url,"../dist/client"),dc6=lc6({clientDir:S98,isServerPath:uc6}),ic6={"X-Frame-Options":"DENY","Content-Security-Policy":"frame-ancestors 'none'"};function pc6($){let Z=new Headers($.headers);for(let[Q,Y]of Object.entries(ic6))Z.set(Q,Y);return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}var{parsePreviewBaseDomain:nc6,tryHandlePreviewHttp:tc6,tryUpgradePreviewWs:oc6,previewWebSocketHandler:xU1,isPreviewWsData:fU1}=await Promise.resolve().then(() => (E98(),j98)),{getOrInitSharedRunner:C98}=await Promise.resolve().then(() => (QH(),kE$)),_98=nc6(process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN),M98={baseDomain:_98??"",getRunner:C98};if(process.env.STUDIO_SANDBOX_TENANT_POOLS?.trim())C98().catch(($)=>{console.warn("[lifecycle] eager sandbox provider init for tenant pools failed:",$ instanceof Error?$.message:String($))});var KS0=await hc6({clientDir:S98}),yU1=process.env.DBOS_CONDUCTOR_KEY?.trim(),I98=process.env.DBOS_CONDUCTOR_URL?.trim();await rU1({databaseUrl:uU1(pJ.databaseUrl,pJ.databasePgSsl)},()=>H40.launch({...yU1?{conductorKey:yU1}:{},...yU1&&I98?{conductorURL:I98}:{}}));console.log(`[dbos] application version: ${H40.applicationVersion}`);var gU1=5,hU1=0;await g8(async()=>{hU1++;try{return await KS0.initDbos()}catch($){let Z=hU1>=gU1?"giving up":"retrying";throw console.warn(`[dbos] initDbos attempt ${hU1}/${gU1} failed, ${Z}`,$),$}},{maxAttempts:gU1,minTimeout:1000,maxTimeout:1e4,jitter:0.5});if(!pJ.isCli){let{bannerLines:$}=await Promise.resolve().then(() => (R98(),T98));console.log("");for(let Z of $())console.log(Z)}var rc6=Bun.serve({idleTimeout:0,port:cc6,hostname:"0.0.0.0",fetch:async($,Z)=>{if(_98){let Y=await oc6($,Z,M98);if(Y===void 0)return;if(Y)return Y;let X=await tc6($,M98);if(X)return X}let Q=await dc6($);if(Q)return pc6(Q);return KS0.fetch($,{server:Z})},websocket:{open($){if(fU1($.data))xU1.open($)},message($,Z){if(fU1($.data))xU1.message($,Z)},close($){if(fU1($.data))xU1.close($)}},development:!1}),sc6=dN1();if(pJ.localMode)Promise.resolve().then(() => (Zf(),kT0)).then(async({seedLocalMode:$,markSeedComplete:Z,healLocalJwks:Q})=>{try{let Y=await Q();if(Y>0)console.log(`[local-mode] cleared ${Y} undecryptable JWKS key(s); Better Auth will generate a fresh one`);let X=await $()}catch(Y){console.error("Failed to seed local mode:",Y)}finally{Z()}}).catch(async($)=>{console.error("Failed to load local-mode module:",$);try{let{markSeedComplete:Z}=await Promise.resolve().then(() => (Zf(),kT0));Z()}catch{}});var V98=!1;async function ac6($){let Z;try{Z=await fc6.create({systemDatabaseUrl:uU1(pJ.databaseUrl,pJ.databasePgSsl),systemDatabaseSchemaName:"dbos"});let Q=await Z.listWorkflows({status:"PENDING",queueName:B3,executorId:$,loadInput:!1,loadOutput:!1});if(Q.length===0){console.log(`[shutdown] no in-flight thread-gate gates to hand off (executor ${$})`);return}let Y=Q.map((X)=>X.workflowID);await Z.resumeWorkflows(Y,{queueName:B3}),console.log(`[shutdown] re-enqueued ${Y.length} in-flight thread-gate gate(s) for re-adoption by a live executor (from ${$}):`,Y)}catch(Q){console.error("[shutdown] thread-gate handoff failed:",Q)}finally{await Z?.destroy().catch(()=>{})}}async function HS0($){if(V98)return;V98=!0,console.log(`
|
|
3708
|
+
</head>`)}function k68($){let Z=new Q1;return Z.get("/:domain/og.png",async(Q)=>{let Y=Ny(Q.req.param("domain")),X=async()=>{let J=$?Bun.file(V68($,"report-og-fallback.png")):null;if(!J||!await J.exists())return Q.notFound();return Q.body(new Uint8Array(await J.arrayBuffer()),200,{"Content-Type":"image/png","Cache-Control":"public, max-age=0, s-maxage=3600"})};try{let J=await fetch(`${uK({})}/api/v2/public/diagnostics/${encodeURIComponent(Y)}/og.png`,{signal:AbortSignal.timeout(vu6)}),G=J.headers.get("content-type")??"";if(!J.ok||!G.startsWith("image/")||!J.body)return X();return Q.body(J.body,200,{"Content-Type":G,"Cache-Control":"public, max-age=0, s-maxage=604800"})}catch{return X()}}),Z.get("/:file{.+\\.md}",async(Q)=>{let Y=Ny(Q.req.param("file").replace(/\.md$/,""));try{let X=await I68(Y,{lang:Q.req.query("lang")?.trim()||void 0,signal:AbortSignal.timeout(bu6)});if(X===null)return Q.text("Deco Score not found",404);return Q.body(X,200,{"Content-Type":"text/markdown; charset=utf-8","Cache-Control":"public, max-age=600, stale-while-revalidate=3600","Access-Control-Allow-Origin":"*"})}catch{return Q.text("Deco Score unavailable",502)}}),Z.get("/:domain",async(Q)=>{let Y=Q.req.param("domain"),X=$?V68($,"index.html"):null,J=X?Bun.file(X):null;if(!J||!await J.exists())return Q.notFound();let G=await J.text();try{let W=await Su6(Ny(Y)),K=Cu6(Y,W);return Q.html(_u6(G,K),200,{"Cache-Control":"public, max-age=0, s-maxage=300"})}catch{return Q.html(G)}}),Z}var ku6=2500,vu6=1e4,bu6=1e4;var S68=D(()=>{G8();ww();UU1();F$()});function ak0($,Z){return fetch(`${uK({})}${$}`,Z)}async function xu6($,Z){let Q=await sk0($,{lang:Z});if(!Q)return{status:"not_found",report:null};return Q.scanned_at?{status:"ready",report:Q}:{status:"empty",report:null}}function yu6($){let Z=typeof $==="object"&&$!==null?$:{},Q=typeof Z.domain==="string"?Z.domain.trim():"",Y=typeof Z.distinctId==="string"&&Z.distinctId.trim()&&Z.distinctId.length<=200?Z.distinctId.trim():void 0;return{domain:Q,distinctId:Y}}var fu6,fO,C68=async($,Z)=>{if(!$.get("reportUser"))return $.json({error:"Authentication required"},401);await Z();return},_68;var v68=D(()=>{G8();hG();ww();UU1();fu6=new Set(["complete","errored","terminated","unknown"]);fO=new Q1;fO.use("*",async($,Z)=>{let Q=await C8.api.getSession({headers:$.req.raw.headers});$.set("reportUser",Q?.user?.id?{email:Q.user.email}:void 0),await Z(),$.header("Cache-Control","private, no-store"),$.header("Vary","Cookie");return});fO.use("/link-token/*",C68);fO.use("/suggest",C68);fO.get("/site/:domain",async($)=>{let Z=$.req.param("domain").trim();if(!Z)return $.json({error:"domain is required"},400);let Q=$.req.query("lang")?.trim()||void 0;try{return $.json(await xu6(Z,Q))}catch{return $.json({error:"report read failed"},502)}});fO.post("/run",async($)=>{let Z=$.get("reportUser"),Q;try{Q=await $.req.json()}catch{return $.json({error:"invalid JSON"},400)}let{domain:Y,distinctId:X}=yu6(Q);if(!Y)return $.json({error:"domain is required"},400);let J=Z?.email;try{let G=await ak0("/api/v2/diagnostics/run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${EA({})}`},body:JSON.stringify({url:Y,...J?{email:J}:{},distinct_id:X})});if(!G.ok)return $.json({error:`run HTTP ${G.status}`},502);let W=await G.json(),K=W.blocked?{state:"blocked"}:W.status==="fresh"?{state:"fresh"}:W.mode==="sync"?{state:"sync"}:{state:"running",id:W.id??null};return $.json(K)}catch{return $.json({error:"run failed"},502)}});fO.get("/status",async($)=>{let Z=$.req.query("id");if(!Z)return $.json({error:"id is required"},400);try{let Q=await ak0(`/api/v2/diagnostics/status?id=${encodeURIComponent(Z)}`,{headers:{Authorization:`Bearer ${EA({})}`}});if(!Q.ok)return $.json({error:`status HTTP ${Q.status}`},502);let X=(await Q.json()).status??"unknown",J={done:fu6.has(X),status:X};return $.json(J)}catch{return $.json({error:"status failed"},502)}});fO.get("/link-token/:id",async($)=>{let Z=$.req.param("id");try{let Q=await ak0(`/api/v2/public/link-tokens/${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(Q.status===404)return $.json(null);if(!Q.ok)return $.json({error:`link token HTTP ${Q.status}`},502);return $.json(await Q.json())}catch{return $.json({error:"link token resolve failed"},502)}});fO.get("/suggest",async($)=>{let Z=($.req.query("q")??"").trim().slice(0,64);if(Z.length<2)return $.json({suggestions:[]});try{let Q=await ak0(`/api/v2/public/suggest?q=${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(!Q.ok)return $.json({suggestions:[]});let Y=await Q.json();return $.json({suggestions:Array.isArray(Y.suggestions)?Y.suggestions:[]})}catch{return $.json({suggestions:[]})}});_68=fO});var gu6=1048576,NU1;var b68=D(()=>{G8();fW();F$();LK1();NU1=new Q1;NU1.post("/webhook",I5({maxSize:gu6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=E0().stripeWebhookSecret;if(!Z)return $.json({error:"stripe billing not configured"},503);let Q=await $.req.text();if(!ls$(Q,$.req.header("stripe-signature"),Z))return $.json({error:"invalid signature"},400);let X=cs$(Q);if(!X)return $.json({error:"invalid payload"},400);let J=await ms$(X);return console.log("stripe webhook",{eventId:X.id,type:X.type,livemode:X.livemode,...J}),$.json({received:!0})})});import{timingSafeEqual as hu6}from"crypto";function cu6($,Z,Q){if(!Z?.startsWith("sha256="))return!1;let Y=new Bun.CryptoHasher("sha256",Q).update($).digest("hex"),X=Z.slice(7);if(X.length!==Y.length)return!1;return hu6(Buffer.from(X),Buffer.from(Y))}function mu6($,Z){let Q=Z,Y=Q?.repository?.name,X=Q?.repository?.owner?.login;if(typeof Y!=="string"||typeof X!=="string")return[];let J=[];if($==="check_suite"){if(Q.action!=="completed")return[];let G=Q.check_suite?.pull_requests;for(let W of Array.isArray(G)?G:[]){let K=W?.number;if(typeof K==="number")J.push(K)}}else if($==="issue_comment"&&Q.issue?.pull_request){let G=Q.issue.number;if(typeof G==="number")J.push(G)}return[...new Set(J)].map((G)=>({repoOwner:X,repoName:Y,number:G}))}function x68($){let Z=new Q1;return Z.post("/webhook",I5({maxSize:uu6,onError:(Q)=>Q.json({error:"payload too large"},413)}),async(Q)=>{let Y=process.env.GITHUB_WEBHOOK_SECRET;if(!Y)return Q.json({error:"github webhook not configured"},503);let X=await Q.req.text();if(!cu6(X,Q.req.header("x-hub-signature-256"),Y))return Q.json({error:"invalid signature"},400);let J=Q.req.header("x-github-event");if(J!=="push"&&!lu6.has(J??""))return Q.json({ok:!0,ignored:"event"});let G;try{G=JSON.parse(X)}catch{return Q.json({error:"invalid payload"},400)}if(J==="push"){let H=G.ref,F=G.repository?.full_name;if(!H||!F)return Q.json({ok:!0,ignored:"shape"});let N=(await T41())?.markTenantPoolsDirty(F,H)??[];return Q.json({ok:!0,pools:N})}let W=mu6(J??"",G);if(W.length===0)return Q.json({ok:!0,ignored:"no-pr"});let K=await du6($,W);return Q.json({ok:!0,refreshed:K})}),Z}async function du6($,Z){let Q=0;for(let Y of Z){let X=$.taskBoard(),J;try{J=await X.findPrLinks(Y)}catch(G){console.error("[github-webhook] pr link lookup failed:",G);continue}for(let G of J)try{let W=await X.getById(G.taskBoardItemId,G.organizationId),K=W?await $.contextFactory()(G.organizationId,W.assignedBy??W.createdBy):null;if(!K)continue;if(await vV$(K,G.organizationId,G.taskBoardItemId)!==null)Q++}catch(W){console.error(`[github-webhook] pr card refresh failed for ${G.taskBoardItemId}:`,W)}}return Q}var uu6=5242880,lu6;var f68=D(()=>{G8();fW();QH();z7();lu6=new Set(["check_suite","issue_comment"])});function y68($){let Z=new RO($.db,new FG($.encryptionKey)),Q=new Q1;return Q.get("/attachments/:token",async(Y)=>{let X=tM$(Y.req.param("token"));if(!X)return Y.json({error:"Invalid or expired link"},404);let J=await Z.getByOrg(X.organizationId);if(!J)return Y.json({error:"Jira is not connected"},404);let W=await new _Q(J.siteUrl,J.email,J.apiToken).downloadAttachment(X.attachmentId);if(!W.ok||!W.body)return Y.json({error:"Jira refused the download"},502);let K=new Headers;for(let H of["content-type","content-length","content-disposition"]){let F=W.headers.get(H);if(F)K.set(H,F)}return K.set("cache-control","no-store"),new Response(W.body,{status:200,headers:K})}),Q}var g68=D(()=>{G8();vz();V51();Vj()});function h68($){let Z=new RO($.db,new FG($.encryptionKey));async function Q(X,J){let G=Ln$(J);if(!G)return;let W=await Z.getByWebhookSecret(X);if(!W?.enabled)return;let K=await PW($.db,W.organizationId);if(!K)return;if(await _I0(K,W,G)==="started")console.log(`[jira-webhook] started a run for ${G.issueKey} entering "${G.toStatus}"`)}let Y=new Q1;return Y.post("/webhook/:secret",I5({maxSize:iu6}),async(X)=>{let J=X.req.param("secret");if(!await Z.getByWebhookSecret(J))return X.json({error:"Unknown webhook"},404);let W;try{W=await X.req.json()}catch{return X.json({error:"Body must be JSON"},400)}return Q(J,W).catch((K)=>{console.error("[jira-webhook] trigger failed",K)}),X.body(null,202)}),Y}var iu6=1048576;var u68=D(()=>{G8();fW();vz();vI0();ox()});import{DBOS as ek0,SchedulerMode as pu6}from"@dbos-inc/dbos-sdk";function c68($){OU1=$}function m68(){if(!OU1)throw Error("[jira-trigger] runtime not initialized \u2014 setJiraTriggerSweepRuntime() must run before the workflow fires");return OU1}function d68(){let $=m68();return new RO($.db,new FG($.encryptionKey))}async function ou6($,Z){try{let Q=await d68().getById($);if(!Q?.enabled||!Q.boardId)return{integrationId:$,started:0};let Y=await PW(m68().db,Q.organizationId);if(!Y)return{integrationId:$,started:0};if((await Y.storage.jiraIntegrations.listAutomations(Q.organizationId)).length===0)return{integrationId:$,started:0};let J=new _Q(Q.siteUrl,Q.email,Q.apiToken),W=`(${await J.getBoardScopeJql(Q.boardId)}) AND status CHANGED AFTER "-${l68}m"`,K=0,H;for(let F=0;F<tu6;F++){let U=await J.searchIssues({jql:W,nextPageToken:H,expandChangelog:!0});for(let N of U.issues){let B=wn$(N,N.changelog?.histories??[],Z);for(let O of B)if(await _I0(Y,Q,O)==="started")K++}if(H=U.nextPageToken??void 0,!H)break}return{integrationId:$,started:K}}catch(Q){return{integrationId:$,started:0,error:Q instanceof Error?Q.message:String(Q)}}}async function ru6($,Z){let Q=new Date($.getTime()-l68*60000),Y=await ek0.runStep(()=>d68().listEnabledIds(),{name:"loadJiraIntegrations"});if(Y.length===0)return;let X=await Promise.all(Y.map((J)=>ek0.runStep(()=>ou6(J,Q),{name:`sweepJira:${J}`})));for(let J of X)if(J.error)console.warn(`[jira-trigger] integration ${J.integrationId} failed: ${J.error}`);else if(J.started>0)console.log(`[jira-trigger] integration ${J.integrationId} started ${J.started} run(s) the webhook missed`)}function i68(){if(BU1)return;BU1=ek0.registerWorkflow(ru6,{name:"jiraTriggerSweepWorkflow"}),ek0.registerScheduled(BU1,{name:"jiraTriggerSweepWorkflow",crontab:nu6,mode:pu6.ExactlyOncePerIntervalWhenActive})}var nu6="7-59/10 * * * *",l68=35,tu6=5,OU1=null,BU1=null;var p68=D(()=>{vz();ox();Vj();vI0()});function n68($,Z){if(Z.startsWith("text/html")||Z.startsWith("image/svg"))$.set("Content-Security-Policy","sandbox allow-scripts allow-modals allow-same-origin")}var t68,su6,au6,o68;var r68=D(()=>{G8();TK();Rm();al();t68=new Q1,su6=["range","if-none-match","if-modified-since"],au6=["content-type","content-length","content-range","accept-ranges","etag","last-modified"];t68.get("/:org/files/*",async($)=>{let Z=$.get("studioContext"),Q=Z.organization?.id;if(!Z.auth?.user?.id){if(nd($))return $.redirect(`/login?next=${encodeURIComponent($.req.path)}`,302);throw new A$(401,{message:"Authentication required"})}if(!Q)throw new A$(401,{message:"Organization context required"});let Y=$.req.path.replace(/^.*\/files\//,"");if(!Y)throw new A$(400,{message:"Missing file key"});let X=await E10(Y,Z);if(!X)throw new A$(503,{message:"Object storage not configured"});if(X.startsWith("data:")&&JW()){let K=X.match(/^data:([^;]+);base64,(.+)$/s);if(!K)throw new A$(500,{message:"Invalid data URL from storage"});let[,H,F]=K,U=Buffer.from(F,"base64"),N=new Headers({"Content-Type":H,"Cache-Control":"private, max-age=86400"});return n68(N,H),new Response(U,{status:200,headers:N})}let J=new Headers;for(let K of su6){let H=$.req.header(K);if(H)J.set(K,H)}let G=await fetch(X,{headers:J});if(G.status===403||G.status===404)throw new A$(404,{message:"File not found"});if(!G.ok&&G.status!==304&&G.status!==416)throw console.error(`[files] upstream storage error ${G.status} for key:`,Y),new A$(502,{message:"Upstream storage error"});let W=new Headers;for(let K of au6){let H=G.headers.get(K);if(H)W.set(K,H)}return W.set("Cache-Control","private, max-age=86400"),n68(W,W.get("content-type")??""),new Response(G.body,{status:G.status,headers:W})});o68=t68});var J40=b((By)=>{var eu6=By&&By.__createBinding||(Object.create?function($,Z,Q,Y){if(Y===void 0)Y=Q;var X=Object.getOwnPropertyDescriptor(Z,Q);if(!X||("get"in X?!Z.__esModule:X.writable||X.configurable))X={enumerable:!0,get:function(){return Z[Q]}};Object.defineProperty($,Y,X)}:function($,Z,Q,Y){if(Y===void 0)Y=Q;$[Y]=Z[Q]}),$l6=By&&By.__exportStar||function($,Z){for(var Q in $)if(Q!=="default"&&!Object.prototype.hasOwnProperty.call(Z,Q))eu6(Z,$,Q)};Object.defineProperty(By,"__esModule",{value:!0});$l6($G(),By)});var e68=b((s68)=>{Object.defineProperty(s68,"__esModule",{value:!0});s68.version=void 0;s68.version="3.4.0"});var Q58=b((pU)=>{var Zl6=pU&&pU.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(pU,"__esModule",{value:!0});pU.NodeTransport=pU.VERSION=void 0;pU.nodeResolveHost=Wl6;var m5=J40(),Ql6=q0("net"),DU1=q0("tls"),Yl6=q0("path"),$58=q0("fs"),Xl6=Zl6(q0("dns")),Jl6=e68();pU.VERSION=Jl6.version;var Gl6="nats.js";class Z58{socket;version;lang;yields=[];signal=(0,m5.deferred)();closedNotification=(0,m5.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=Gl6,this.version=pU.VERSION}async connect($,Z){this.tlsName=$.tlsName,this.options=Z;let{tls:Q}=this.options,{handshakeFirst:Y}=Q||{};try{if(Y===!0)this.socket=await this.tlsFirst($);else this.socket=await this.dial($);if(this.done)this.socket?.destroy();let X=await this.peekInfo();(0,m5.checkOptions)(X,Z);let{tls_required:J,tls_available:G}=X,W=G===!0&&Z.tls!==null;if(!Y&&(J||W))this.socket=await this.startTLS();if(this.done)this.socket?.destroy();if(J&&this.socket.encrypted!==!0)throw m5.errors.InvalidArgumentError.format("tls","is not available on this server");return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(X){let J=X;if(!J)J=new m5.errors.ConnectionError("error connecting - node provided an undefined error");let{code:G}=J,W=G==="ECONNREFUSED"?new m5.errors.ConnectionError("connection refused",{cause:J}):J;throw this.socket?.destroy(),W}}dial($){let Z=(0,m5.deferred)(),Q,Y=(0,Ql6.createConnection)($.port,$.hostname,()=>{Z.resolve(Y),Y.removeAllListeners()});return Y.on("error",(X)=>{Q=X}),Y.on("close",()=>{Y.removeAllListeners(),Z.reject(Q)}),Y.setNoDelay(!0),Z}get isClosed(){return this.done}close($){return this._closed($,!1)}peekInfo(){let $=(0,m5.deferred)(),Z;return this.socket.on("data",(Q)=>{this.yields.push(Q);let Y=m5.DataBuffer.concat(...this.yields),X=(0,m5.extractProtocolMessage)(Y);if(X!=="")try{let J=m5.INFO.exec(X);if(!J)throw Error("unexpected response from server");let G=JSON.parse(J[1]);$.resolve(G)}catch(J){$.reject(J)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(Q)=>{Z=Q}),this.socket.on("close",()=>{this.socket.removeAllListeners(),$.reject(Z)}),$}loadFile($){if(!$)return Promise.resolve();let Z=(0,m5.deferred)();try{if($=(0,Yl6.resolve)($),!(0,$58.existsSync)($))Z.reject(Error(`${$} doesn't exist`));(0,$58.readFile)($,(Q,Y)=>{if(Q)return Z.reject(Q);Z.resolve(Y)})}catch(Q){Z.reject(Q)}return Z}async loadClientCerts(){let $={},{certFile:Z,cert:Q,caFile:Y,ca:X,keyFile:J,key:G}=this.options.tls;try{if(Z){let W=await this.loadFile(Z);if(W)$.cert=W}else if(Q)$.cert=Q;if(J){let W=await this.loadFile(J);if(W)$.key=W}else if(G)$.key=G;if(Y){let W=await this.loadFile(Y);if(W)$.ca=[W]}else if(X)$.ca=X;return Promise.resolve($)}catch(W){return Promise.reject(W)}}async tlsFirst($){let Z,Q={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)Q.socket=this.socket;if(typeof this.options.tls==="object")try{let X=await this.loadClientCerts()||{};Q=(0,m5.extend)(Q,this.options.tls,X)}catch(X){return Promise.reject(new m5.errors.ConnectionError(X.message,{cause:X}))}let Y=(0,m5.deferred)();try{let X=(0,DU1.connect)($.port,$.hostname,Q,()=>{X.removeAllListeners(),Y.resolve(X)});X.on("error",(J)=>{Z=J}),X.on("secureConnect",()=>{if(Q.rejectUnauthorized===!1)return;if(!X.authorized)throw X.authorizationError}),X.on("close",()=>{Y.reject(Z),X.removeAllListeners()}),X.setNoDelay(!0)}catch(X){Y.reject(new m5.errors.ConnectionError(X.message,{cause:X}))}return Y}async startTLS(){let $,Z={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let Y=await this.loadClientCerts()||{};Z=(0,m5.extend)(Z,this.options.tls,Y)}catch(Y){return Promise.reject(new m5.errors.ConnectionError(Y.message,{cause:Y}))}let Q=(0,m5.deferred)();try{let Y=(0,DU1.connect)(Z,()=>{Y.removeAllListeners(),Q.resolve(Y)});Y.on("error",(X)=>{$=X}),Y.on("secureConnect",()=>{if(Z.rejectUnauthorized===!1)return;if(!Y.authorized)throw Y.authorizationError}),Y.on("close",()=>{Q.reject($),Y.removeAllListeners()})}catch(Y){Q.reject(new m5.errors.ConnectionError(Y.message,{cause:Y}))}return Q}setupHandlers(){let $;this.socket.on("data",(Z)=>{return this.yields.push(Z),this.signal.resolve()}),this.socket.on("error",(Z)=>{$=Z}),this.socket.on("end",()=>{if(this.socket?.destroyed)return;this.socket?.write(new Uint8Array(0),()=>{this.socket?.end()})}),this.socket.on("close",()=>{this._closed($,!1)})}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.yields.length===0)await this.signal;let $=this.yields;this.yields=[];for(let Z=0;Z<$.length;Z++){if(this.options.debug)console.info(`> ${(0,m5.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,m5.deferred)()}}discard(){if(this.done=!0,this.socket)try{this.socket.removeAllListeners(),this.socket.destroy()}catch{}}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof DU1.TLSSocket}_send($){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,m5.render)($)}`);let Z=(0,m5.deferred)();try{this.socket.write($,(Q)=>{if(Q){if(this.options.debug)console.error(`!!! ${(0,m5.render)($)}: ${Q}`);return Z.reject(Q)}return Z.resolve()})}catch(Q){if(this.options.debug)console.error(`!!! ${(0,m5.render)($)}: ${Q}`);Z.reject(Q)}return Z}send($){this._send($).catch((Q)=>{})}async _closed($,Z=!0){if(!this.connected)return;if(this.done){this.socket?.destroy();return}if(this.closeError=$,!$&&this.socket&&Z)try{await this._send(new TextEncoder().encode(""))}catch(Q){if(this.options.debug)console.log("transport close terminated with an error",Q)}try{if(this.socket)this.socket.removeAllListeners(),this.socket?.destroy(),this.socket=void 0}catch(Q){console.log(Q)}this.done=!0,this.closedNotification.resolve(this.closeError)}closed(){return this.closedNotification}}pU.NodeTransport=Z58;function Wl6($){let Z=(0,m5.deferred)();return Xl6.default.lookup($,{all:!0},(Q,Y)=>{if(Q){Z.reject(Q);return}let X=[];for(let J of Y)X.push(J.address);if(X.length===0)X.push($);Z.resolve(X)}),Z}});var W58=b((G58)=>{Object.defineProperty(G58,"__esModule",{value:!0});G58.connect=Kl6;var Y58=Q58(),X58=J40(),J58=J40();function Kl6($={}){if((0,J58.hasWsProtocol)($))return Promise.reject(J58.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,X58.setTransportFactory)({factory:()=>{return new Y58.NodeTransport},dnsResolveFn:Y58.nodeResolveHost}),X58.NatsConnectionImpl.connect($)}});var K58=b((yO)=>{var Fl6=yO&&yO.__createBinding||(Object.create?function($,Z,Q,Y){if(Y===void 0)Y=Q;var X=Object.getOwnPropertyDescriptor(Z,Q);if(!X||("get"in X?!Z.__esModule:X.writable||X.configurable))X={enumerable:!0,get:function(){return Z[Q]}};Object.defineProperty($,Y,X)}:function($,Z,Q,Y){if(Y===void 0)Y=Q;$[Y]=Z[Q]}),Ul6=yO&&yO.__exportStar||function($,Z){for(var Q in $)if(Q!=="default"&&!Object.prototype.hasOwnProperty.call(Z,Q))Fl6(Z,$,Q)};Object.defineProperty(yO,"__esModule",{value:!0});yO.connect=void 0;var Nl6=W58();Object.defineProperty(yO,"connect",{enumerable:!0,get:function(){return Nl6.connect}});Ul6(J40(),yO)});function N58($){let Z=$?.connectFn??Ll6,Q=null,Y=null,X=!1,J=!1,G=!1,W=[];function K(){return Q!==null&&!Q.isClosed()&&!Q.isDraining()&&!G}function H(){console.log(`[NatsProvider] fireReady: ${W.length} callbacks`);for(let N of W)try{N()}catch{}}function F(N){(async()=>{for await(let B of N.status())if(B.type==="disconnect")console.log("[NatsProvider] Disconnected"),G=!0;else if(B.type==="reconnect")console.log("[NatsProvider] Reconnected, re-firing ready callbacks"),G=!1,Y=null,H()})().catch(()=>{})}async function U(N,B){let O=0;while(!J)try{Q=await Z({servers:N,timeout:Dl6,reconnect:!0,maxReconnectAttempts:-1,...B?{authenticator:B}:{}}),console.log(`[NatsProvider] Connected to ${Q.getServer()} after ${O} attempt(s)`),Y=null,G=!1,F(Q),H();return}catch{O++;let L=QQ(Ol6,Bl6,O-1,2,0.5);await i$(L)}}return{init(N,B){if(X)return;X=!0,J=!1;let O=B?.creds?H58.credsAuthenticator(new TextEncoder().encode(B.creds)):void 0;U(N,O).catch(()=>{})},isConnected(){return K()},getConnection(){return K()?Q:null},getJetStream(){if(!K())return null;if(!Y)Y=U58.jetstream(Q);return Y},onReady(N){if(W.push(N),K())try{N()}catch{}},async drain(){if(J=!0,X=!1,Y=null,G=!1,Q){let N=Q;Q=null,await N.drain().catch(()=>{})}}}}function Ll6($){return F58.connect($)}var H58,F58,U58,Bl6=100,Ol6=3000,Dl6=3000;var B58=D(()=>{D8();H58=C(ei(),1),F58=C(K58(),1),U58=C(GN(),1)});function $S0($){let Z=$?.ttlMs??60000,Q=$?.maxSize??1e4,Y=$?.updateRecencyOnGet??!1,X=new Map;function J(){if(X.size<=Q)return;let G=Date.now();for(let[W,K]of X)if(K.expiresAt<=G)X.delete(W);while(X.size>Q){let W=X.keys().next().value;if(W===void 0)break;X.delete(W)}}return{get(G){let W=X.get(G);if(!W)return;if(W.expiresAt<=Date.now()){X.delete(G);return}if(Y)X.delete(G),X.set(G,W);return W.value},set(G,W){X.delete(G),X.set(G,{value:W,expiresAt:Date.now()+Z}),J()},delete(G){X.delete(G)},clear(){X.clear()},size(){return X.size}}}function ZS0($,Z){return`${$}.${Z}`}class LU1{cache;constructor($){this.cache=$S0({ttlMs:$?.ttlMs??wl6,maxSize:$?.maxSize??jl6})}async get($,Z){return this.cache.get(ZS0($,Z))??null}async set($,Z,Q){this.cache.set(ZS0($,Z),Q)}async invalidate($,Z){this.cache.delete(ZS0($,Z)),this.cache.delete(ZS0($,`${Z}:decisions`))}teardown(){this.cache.clear()}}var wl6=600000,jl6=5000;var O58=()=>{};function QS0($,Z){return`${$}:${Z}`}function wU1($){let Z=$S0({ttlMs:$?.ttlMs??El6,maxSize:$?.maxSize??zl6}),Q=$?.getConnection,Y=crypto.randomUUID(),X=new TextEncoder,J=new TextDecoder,G=null;function W(K,H){let F=Q?.();if(!F)return;try{F.publish(D58,X.encode(JSON.stringify({organizationId:K,keyId:H,originId:Y})))}catch(U){console.warn("[ProviderKeyCache] Publish failed (non-critical):",U)}}return{get(K,H){return Z.get(QS0(K,H))},set(K,H,F){Z.set(QS0(K,H),F)},invalidate(K,H){Z.delete(QS0(K,H)),W(K,H)},start(){if(G)return;let K=Q?.();if(!K)return;G=K.subscribe(D58),(async()=>{for await(let H of G)try{let F=JSON.parse(J.decode(H.data));if(F.originId===Y)continue;Z.delete(QS0(F.organizationId,F.keyId))}catch{}})().catch(console.error)},teardown(){G?.unsubscribe(),G=null,Z.clear()}}}var D58="studio.ai-provider-keys.invalidate",El6=30000,zl6=5000;var L58=()=>{};class jU1{options;subscription=null;onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();constructor($){this.options=$}async start($){if($)this.onCancel=$;if(this.subscription)return;if(!this.onCancel)return;let Z=this.options.getConnection();if(!Z)return;let Q=new TextDecoder,Y=Z.subscribe("studio.decopilot.cancel");this.subscription=Y,(async()=>{for await(let X of Y)try{let J=JSON.parse(Q.decode(X.data));if(J.originId===this.originId)continue;this.onCancel?.(J.taskId)}catch{}})().catch(console.error)}broadcast($){if(/[.*>\s]/.test($)){console.warn("[NatsCancelBroadcast] Invalid threadId, skipping broadcast");return}this.onCancel?.($);try{let Z=this.options.getConnection();if(!Z)return;let Q=this.encoder.encode(JSON.stringify({taskId:$,originId:this.originId}));Z.publish("studio.decopilot.cancel",Q)}catch(Z){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",Z)}}async stop(){this.subscription?.unsubscribe(),this.subscription=null,this.onCancel=null}}var w58=($)=>{let Z;return()=>Z??=$()},EU1,zU1;var j58=D(()=>{C6();EU1=w58(()=>z$.createHistogram("decopilot.stream.encode_ms",{description:"Per-chunk JSON.stringify+encode time for decopilot stream",unit:"ms"})),zU1=w58(()=>z$.createCounter("decopilot.stream.published_chunks",{description:"Logical decopilot stream chunks published to JetStream",unit:"{chunks}"}))});function Il6($=P58){return{name:EU,subjects:[`${_Z1}.>`],storage:MH.StorageType.File,max_age:Tl6,max_bytes:ql6,max_msgs_per_subject:Ml6,discard:MH.DiscardPolicy.Old,retention:MH.RetentionPolicy.Limits,duplicate_window:Rl6,num_replicas:$}}class A58{chunks=0;encodeMs=0;maxMs=0;bytes=0;windowStart=performance.now();constructor(){setInterval(()=>this.flush(),1e4).unref?.()}record($,Z){if(this.chunks++,this.encodeMs+=$,$>this.maxMs)this.maxMs=$;this.bytes+=Z}flush(){let $=performance.now(),Z=$-this.windowStart;if(this.chunks>0&&Z>0)console.warn(JSON.stringify({msg:"stream-encode-trace",windowMs:Math.round(Z),chunks:this.chunks,encodeMs:Math.round(this.encodeMs),pctOfLoop:+(this.encodeMs/Z*100).toFixed(1),maxChunkMs:+this.maxMs.toFixed(2),mbEncoded:+(this.bytes/1048576).toFixed(2)}));this.chunks=0,this.encodeMs=0,this.maxMs=0,this.bytes=0,this.windowStart=$}}function E58($){let Z=z58.headers();for(let[Q,Y]of Object.entries($))Z.set(Q,Y);return Z}function Cl6($,Z){let Q=0;return{publish(Y,X,J,G){Y.publish(X,J,G?{headers:G}:void 0).catch((W)=>{if(Q++,Al6().add(1,{"org.id":Z??"unknown"}),Q===1||Q%100===0)console.warn(`[Decopilot] JetStream publish failed for thread ${$} (${Q} total):`,W)})},get errorCount(){return Q}}}function _l6($,Z){return $.info?.cluster?Z:1}function vl6($){if(!($ instanceof Error))return!1;if(/non-clustered/i.test($.message))return!0;return/replicas?\b/i.test($.message)&&/not supported|can ?not|exceed|insufficient|greater than/i.test($.message)}class PU1{options;js=null;jsm=null;constructor($){this.options=$}async init(){let $=this.options.getConnection();if(!$){console.log("[Decopilot] StreamBuffer.init skipped: NATS not connected yet");return}let Z=async(Y,X)=>{let J=Il6(X);try{await Y.streams.info(EU),await Y.streams.update(EU,J)}catch(G){if(G instanceof Error&&G.message.includes("stream not found"))await Y.streams.add(J),await Y.streams.update(EU,J);else if(G instanceof Error&&/can ?not change.*storage|storage type/i.test(G.message))await Y.streams.delete(EU),await Y.streams.add(J);else throw G}},Q=await g8(async()=>{let Y=this.options.getJetStreamManager?await this.options.getJetStreamManager():await MH.jetstreamManager($),X=_l6($,P58);try{await Z(Y,X)}catch(J){if(X<=1||!vl6(J))throw J;console.warn(`[Decopilot] StreamBuffer: NATS rejected num_replicas=${X} (${J.message}); falling back to an unreplicated stream`),await Z(Y,1)}return Y},{maxAttempts:5,minTimeout:250,maxTimeout:4000,jitter:0.5,isRetriable:vm});this.js=this.options.getJetStream(),this.jsm=Q,console.log(`[Decopilot] StreamBuffer.init ${this.js?"ready":"degraded (js=null)"}`)}pump($,Z,Q,Y){let X=this.js;if(!X)return console.warn(`[Decopilot] pump: JetStream client unavailable for thread ${Z}; chunks NOT published to NATS`),Promise.resolve();let J=Cl6(Z,Y),G=!1,W=()=>{if(G)return;G=!0;let H=wC$(Z);X.publish(H.subject,H.data).catch(()=>{})};Q.addEventListener("abort",W,{once:!0});let K=(H)=>{let F=performance.now(),U=bZ1(H,{runId:Z}),N=performance.now()-F;EU1().record(N),zU1().add(1,{"org.id":Y??"unknown"}),Sl6?.record(N,U.reduce((B,O)=>B+O.data.length,0));for(let B of U)J.publish(X,B.subject,B.data,B.headers?E58(B.headers):void 0)};return(async()=>{let H=$.getReader(),F=0,U=0,N;try{while(!0){let{done:B,value:O}=await H.read();if(B)break;if(K(O),U++,++F>=64)F=0,await new Promise((L)=>setImmediate(L))}}catch(B){N=B,console.warn(`[Decopilot] stream pump error for thread ${Z}:`,B?.message??B)}finally{if(H.releaseLock(),W(),kl6)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"pump-done",taskId:Z,publishedChunks:U,publishErrors:J.errorCount}))}if(N!==void 0)throw N})()}async publishSerialized($,Z){try{return await g8(()=>$.publish(Z.subject,Z.data,{...Z.headers?{headers:E58(Z.headers)}:{},...Z.msgId?{msgID:Z.msgId}:{}}),{maxAttempts:6,minTimeout:250,maxTimeout:5000,jitter:0.5,isRetriable:vm}),!0}catch(Q){return console.error(`[Decopilot] publish failed after retries subject=${Z.subject}`,Q),!1}}async publishRawChunk($,Z,Q){let Y=this.js;if(!Y)return!1;let X=performance.now(),J=bZ1(Z,{runId:$,dedup:Q});EU1().record(performance.now()-X),zU1().add(1);for(let G of J)if(!await this.publishSerialized(Y,G))return!1;return!0}async publishDone($,Z,Q){let Y=this.js;if(!Y)return!1;let X=LC$({runId:$,fenceToken:Z,finalSeq:Q});return await this.publishSerialized(Y,X)}async createTailStream($,Z,Q){let Y=this.js;if(!Y)return console.warn(`[Decopilot] createTailStream: JetStream client unavailable for thread ${$}; no live tail`),null;let X=Q?.deliverPolicy==="new"?MH.DeliverPolicy.New:MH.DeliverPolicy.All,J=Q?.closeOnDone??!1,G=fj($),W;try{W=await g8(async()=>{return(await Y.consumers.get(EU,{filter_subjects:G,deliver_policy:X})).consume()},{maxAttempts:6,minTimeout:250,maxTimeout:5000,jitter:0.5,isRetriable:vm})}catch(L){return console.warn("[Decopilot] JetStream tail unavailable (non-critical):",L?.message??L),null}let F=QR0({messages:async function*(){try{for await(let L of W)yield{subject:L.subject,data:L.data,headers:L.headers}}finally{W.stop()}}(),onCancel:()=>W.stop()}).pipeThrough(aT0()).pipeThrough(eT0()).getReader(),U=!1,N=()=>{if(U)return;U=!0;try{F.releaseLock()}catch{}},B=!1,O=()=>{if(B)return;B=!0,W.stop(),F.cancel().catch(()=>{}),N()};return Z?.addEventListener("abort",O,{once:!0}),new ReadableStream({async pull(L){for(;;){let{done:w,value:j}=await F.read();if(w){O(),L.close();return}let E=j;if(E.kind==="done"){if(J){O(),L.close();return}continue}L.enqueue(E.chunk);return}},cancel(){O()}})}purge($){if(!this.jsm)return;this.jsm.streams.purge(EU,{filter:fj($)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null}}var MH,z58,Pl6=($)=>{let Z;return()=>Z??=$()},Al6,Tl6=86400000000000,Rl6=120000000000,ql6=4294967296,P58,Ml6=500000,Vl6,kl6,Sl6;var T58=D(()=>{D8();xZ1();YR0();$R0();C6();j58();MH=C(GN(),1),z58=C(ei(),1),Al6=Pl6(()=>z$.createCounter("decopilot.stream.publish_errors",{description:"Number of JetStream publish failures for decopilot stream chunks",unit:"{errors}"})),P58=Math.max(1,Number(process.env.DECOPILOT_STREAM_REPLICAS??3)||3);Vl6=process.env.STREAM_ENCODE_TRACE==="1",kl6=process.env.DECOPILOT_STREAM_TRACE==="1";Sl6=Vl6?new A58:null});function YS0($,Z,Q,Y){if(!Y)return!1;return $.emit(Z,nH(Q,Y.status,{title:Y.title??void 0,virtualMcpId:Y.virtual_mcp_id??void 0,createdBy:Y.created_by??void 0,triggerId:Y.trigger_id??null,branch:Y.branch??null,harnessId:Y.harness_id??void 0,createdAt:Y.created_at,updatedAt:Y.updated_at})),!0}var R58=D(()=>{e8()});class AU1{storage;options;timer=null;constructor($,Z={}){this.storage=$;this.options=Z}start(){if(this.timer)return;let $=this.options.intervalMs??300000;this.timer=setInterval(()=>{this.runOnce()},$)}async runOnce(){let $=this.options.staleAfterMs??3600000;try{let Z=await this.storage.sweepAbandoned($);if(Z>0)console.log(`[async-research-sweeper] marked ${Z} stale jobs as abandoned`);return Z}catch(Z){return console.error("[async-research-sweeper] sweep failed",Z),0}}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}function bl6($,Z){let Q=$.startsWith("thread:")?YH($):$;return[...new Set([Z,Q].filter((Y)=>!!Y))]}async function TU1($,Z){let Q=Z.organizationId;try{let Y=await $.storage.taskBoard.linkedThreadIds(Z.id,Q);for(let X of Y){let J=await KU($,X);if(!J?.owner||!J?.name)continue;let G=await $.storage.threads.get(X),W=await gc($,{threadId:X,runBranch:G?.branch}),K=bl6(W,await AA0($,X)),H=await Pe($,Q,s11(J)).catch(()=>null);if(!H){console.warn(`[task-board] no credential for ${J.owner}/${J.name} \u2014 `+`cannot look up ${Z.id}'s change request by branch`);continue}for(let F of K){let U=await H.readForBranch(F).catch(()=>null);if(!U)continue;return await $.storage.taskBoard.linkPr({taskBoardItemId:Z.id,organizationId:Q,url:U.url,prNumber:U.number,repo:H.repo}),await $.storage.taskBoard.openReviewCycleIfInProgress(Z.id,Q),await aG(Q).catch(()=>{}),console.log(`[task-board] ${Z.id}: linked ${U.url} found on branch ${F}`),!0}}}catch(Y){console.error("[task-board] PR lookup by branch failed",Y)}return!1}var q58=D(()=>{iZ();jW();z7()});async function M58($,Z,Q){let Y=Z.organizationId;if(!VX(Z))return!1;if(!rx(Q))return!1;if(await $.storage.taskBoard.hasHumanRejectedDone(Z.id,Y))return!1;let X=await $.storage.organizationSettings.get(Y),J=oF(X?.flags),G=await $.storage.taskBoard.update(Z.id,Y,{status:J},Z.updatedBy);return await o6($,{taskBoardItemId:Z.id,action:"status_changed",actorId:null,data:{from:Z.status,to:J,reason:"pr_merged"}}),E8(Y,G),console.log(`[task-board-review-sweeper] ${Z.id}: linked PR already merged \u2014 moved to ${J}`),!0}var I58=D(()=>{C4();_Y();jm();WH();V9()});function ll6($){return $ instanceof zX}function V58($,Z){return Z-$>=hl6}class RU1{taskBoard;contextFactory;billing;options;timer=null;running=!1;cursor=null;constructor($,Z,Q,Y={}){this.taskBoard=$;this.contextFactory=Z;this.billing=Q;this.options=Y}start(){if(this.timer)return;let $=this.options.intervalMs??xl6;this.timer=setInterval(()=>{this.runOnce()},$),this.timer.unref()}async runOnce(){if(this.running)return 0;this.running=!0;let $=0;try{let Z=this.options.batchSize??yl6,Q=this.options.itemIntervalMs??fl6,Y=new Date(Date.now()-Q),X=await this.taskBoard.listItemsPendingReview(Z,this.cursor,Y),J=X.at(-1);this.cursor=X.length===Z&&J?{updatedAt:J.updatedAt,id:J.id}:null;for(let{id:G,organizationId:W}of X)try{if(await this.reconcileItem(G,W,Y))$++}catch(K){console.error(`[task-board-review-sweeper] ${G} failed`,K)}await this.reapNeverStartedThreads(Z),$+=await this.dispatchDueRetries(Z),await this.reactToUnhandledFailures(Z),$+=await this.settleFinishedRunsWithoutPr(Z,Y)}catch(Z){console.error("[task-board-review-sweeper] sweep failed",Z)}finally{this.running=!1}return $}async reapNeverStartedThreads($){try{let Z=await this.taskBoard.failNeverStartedLinkedThreads($,new Date(Date.now()-A51),l91);for(let Q of Z)console.warn(`[task-board-review-sweeper] failed never-started thread ${Q.threadId} on ${Q.itemId}`)}catch(Z){console.error("[task-board-review-sweeper] reaping failed",Z)}}async reactToUnhandledFailures($){let Z=await this.taskBoard.listItemsStuckAfterFailure($,new Date(Date.now()-ul6));for(let{id:Q,organizationId:Y,threadId:X}of Z)try{console.warn(`[task-board-review-sweeper] reacting to an unhandled failure on ${Q}`),await g91(this.taskBoard,X,Y),await h91(this.taskBoard,this.billing,X,Y)}catch(J){console.error(`[task-board-review-sweeper] unhandled-failure reaction for ${Q} failed`,J)}}async settleFinishedRunsWithoutPr($,Z){let Q=0,Y=await this.taskBoard.listItemsFinishedWithoutPr($,Z);for(let{id:X,organizationId:J,finishedAt:G}of Y)try{if(!await this.taskBoard.claimSweep(X,J,Z))continue;let W=await this.taskBoard.getById(X,J);if(!W||W.status!==T$.progress||VX(W)||W.assigneeId!==j8)continue;let K=await this.contextFactory(J,W.assignedBy??W.createdBy);if(!K)continue;if(await TU1(K,W)){if(await this.taskBoard.clearSweepBudget(X,J),await this.reconcileItem(X,J,Z))Q++;continue}if(!V58(G.getTime(),Date.now()))continue;let H="the run finished without opening a pull request \u2014 there is "+"nothing for a reviewer to review",F=await this.taskBoard.advanceToReviewIfInProgress(X,J,W.updatedBy);if(!F)continue;await this.taskBoard.recordActivity({taskBoardItemId:X,action:"status_changed",actorId:null,data:{from:T$.progress,to:T$.review,reason:H}}).catch(()=>{}),E8(J,F),await KH(K,F,H)}catch(W){console.error(`[task-board-review-sweeper] settling finished run on ${X} failed`,W)}return Q}async dispatchDueRetries($){let Z=0,Q=await this.taskBoard.listItemsDueForRetry($,new Date);for(let{id:Y,organizationId:X,attempts:J}of Q)try{if(!await this.taskBoard.claimDueRetry(Y,X,new Date))continue;let G=await this.taskBoard.getById(Y,X);if(!G||G.status!==T$.progress||G.assigneeId!==j8)continue;let W=await this.contextFactory(X,G.assignedBy??G.createdBy);if(!W)continue;await HH(W,G,{runClass:"retry"}),Z++,console.warn(`[task-board-review-sweeper] re-dispatched ${Y} after a failure (attempt ${J})`)}catch(G){if(console.error(`[task-board-review-sweeper] retry dispatch for ${Y} failed`,G),ll6(G)){await this.returnToTodo(Y,X,G instanceof Error?G.message:String(G));continue}await this.taskBoard.scheduleRunRetry(Y,X,J,new Date(Date.now()+gl6)).catch((W)=>console.error(`[task-board-review-sweeper] re-arming ${Y} failed`,W))}return Z}async returnToTodo($,Z,Q){try{let Y=await this.taskBoard.getById($,Z);if(!Y||Y.status!==T$.progress)return;let X=await this.taskBoard.returnToTodoAfterFailure($,Z,Y.updatedBy);if(!X)return;await this.taskBoard.recordActivity({taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:"in_progress",to:"todo",reason:Q}}).catch(()=>{}),E8(Z,X)}catch(Y){console.error(`[task-board-review-sweeper] returning ${$} to todo failed`,Y)}}async handOffReviewWithoutPr($,Z){let Q=await this.taskBoard.listActivity(Z.id,Z.organizationId);if(!V58(SB(Q,Z.reviewCycleStartedAt),Date.now()))return;await KH($,Z,"no pull request is linked to this task \u2014 there is nothing for a "+"reviewer to review")}async reconcileItem($,Z,Q){if(!await this.taskBoard.claimSweep($,Z,Q))return!1;let Y=await this.taskBoard.getById($,Z);if(!Y)return!1;if(!VX(Y))return!1;let X=Y.assigneeId===j8,J=await this.taskBoard.listPrs($,Z),G=await this.contextFactory(Z,Y.assignedBy??Y.createdBy);if(!G)return!1;if(J.length===0){if(await TU1(G,Y))J=await this.taskBoard.listPrs($,Z);if(J.length===0){if(X)await this.handOffReviewWithoutPr(G,Y);return!1}}let W=await Promise.all(J.map(async(K)=>({...K,...await Pm(Z,K)})));if(W.every((K)=>K.state===null))console.warn(`[task-board-review-sweeper] ${$}: no live PR state from GitHub (${W.length} PR(s)) \u2014 proceeding on unknown`);if(await M58(G,Y,W))return!0;if(await P_$(G,Y))return!0;if(await this.resolveConflictFromSweep(G,Y,W))return!0;if(!X)return!1;if(!b91(W))return!1;return await Em(G,Y,{previewMatchesHead:x91(W)}),!0}async resolveConflictFromSweep($,Z,Q){let Y=Q.find((X)=>X.state!=="closed"&&X.conflict===!0);if(!Y)return!1;return await _j($,Z.organizationId,Z,{pr:{number:Y.number,url:Y.url},conflict:!0}).catch((X)=>{return console.error("[task-board-review-sweeper] conflict resolve failed",X),!1})}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}var xl6=60000,fl6=300000,yl6=50,gl6=60000,hl6=900000,ul6=120000;var k58=D(()=>{C4();OT0();q58();wU();S10();WH();I58();V9();FW();c91();z7();Q10();zm()});import{readdir as cl6,rm as XS0}from"fs/promises";import{join as JS0}from"path";async function GS0($){let Z=new Date;Z.setUTCDate(Z.getUTCDate()-ml6),Z.setUTCHours(0,0,0,0);let Q=0;try{let Y=await Oy($);for(let X of Y)if(/^\d{4}$/.test(X))Q+=await S58($,X,Z);else if(!X.startsWith(".")){let J=JS0($,X),G=await Oy(J);for(let K of G){if(!/^\d{4}$/.test(K))continue;Q+=await S58(J,K,Z)}if((await Oy(J)).length===0)await XS0(J,{recursive:!0,force:!0})}}catch(Y){console.warn("monitoring retention cleanup failed:",Y)}return Q}async function S58($,Z,Q){let Y=0,X=JS0($,Z),J=await Oy(X);for(let W of J){if(!/^\d{2}$/.test(W))continue;let K=JS0(X,W),H=await Oy(K);for(let U of H){if(!/^\d{2}$/.test(U))continue;let N=new Date(`${Z}-${W}-${U}T00:00:00Z`);if(isNaN(N.getTime()))continue;if(N<Q){let B=JS0(K,U);await XS0(B,{recursive:!0,force:!0}),Y++}}if((await Oy(K)).length===0)await XS0(K,{recursive:!0,force:!0})}if((await Oy(X)).length===0)await XS0(X,{recursive:!0,force:!0});return Y}async function Oy($){try{return(await cl6($)).filter((Q)=>!Q.startsWith("."))}catch{return[]}}var ml6=30;var qU1=()=>{};import{DBOS as MU1,SchedulerMode as dl6}from"@dbos-inc/dbos-sdk";async function pl6(){let $=[uW(),Ty(),eU()],Z=0;for(let Q of $)try{Z+=await GS0(Q)}catch(Y){console.error("[monitoring-retention] cleanup failed:",Y)}return console.log(`[monitoring-retention] deleted ${Z} day-dir(s) across ${$.length} signal dir(s)`),{deleted:Z,dirs:$.length}}async function nl6($,Z){await MU1.runStep(()=>pl6(),{name:"monitoringRetention"})}function _58(){if(C58)return;C58=!0;let $=MU1.registerWorkflow(nl6,{name:"monitoringRetentionWorkflow"});MU1.registerScheduled($,{name:"monitoringRetentionWorkflow",crontab:il6,mode:dl6.ExactlyOncePerIntervalWhenActive})}var il6="23 4 * * *",C58=!1;var v58=D(()=>{D3();qU1()});function b58($){return async(Z,Q)=>{let Y=await $.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",Q).where("member.organizationId","=",Z).executeTakeFirst();if(!Y)return console.warn(`[automationContextFactory] User ${Q} not found in org ${Z} \u2014 returning null`),null;let X=await vQ.create();X.auth.user={id:Q,role:Y.role},X.organization={id:Y.orgId,slug:Y.orgSlug,name:Y.orgName};let J=await kA($.db,Z,Y.role);return X.boundAuth=KK1({auth:X.authInstance,headers:new Headers,role:Y.role,permissions:J,userId:Q}),X.access=new OP(Q,void 0,X.boundAuth,Y.role,"self"),Cj(X,{id:Y.orgId,slug:Y.orgSlug}),X}}var x58=D(()=>{BK();pF()});function tl6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function ol6(){return{services:tl6(),migrationsStatus:"pending",serverUrl:null,logs:[]}}function sl6(){for(let $ of rl6)$()}function f58($){let Z=[...IU1.logs,$];IU1={...IU1,logs:Z.length>500?Z.slice(-500):Z},sl6()}function VU1(){return al6}var IU1,rl6,al6=!1;var kU1=D(()=>{IU1=ol6(),rl6=new Set});import{EventEmitter as el6}from"events";var SU1;var y58=D(()=>{kU1();SU1=new el6;SU1.on("request",($)=>{f58($)})});function g58(){return async($,Z)=>{let Q=Date.now(),Y=$.req.method,X=$.req.path;if(X==="/api/auth/get-session"||X.includes("favicon")){await Z();return}let J="",G=!1;if(X.startsWith("/mcp")&&Y==="POST"){G=!0;try{if($.req.header("Content-Type")?.includes("application/json")){let N=await $.req.raw.clone().json();if(N.method==="tools/call"&&N.params?.name){let B=Ri(N.params.name),O=N.params.arguments||{},L=Object.keys(O).map((j)=>Ri(j)),w=L.length>0?L.slice(0,3).join(",")+(L.length>3?"\u2026":""):"";J=`${Z9.tool}${B}${Z9.dim}(${w})${Z9.reset}`}else if(N.method)J=`${Z9.dim}${Ri(N.method)}${Z9.reset}`}}catch{}}let W=Ri(X);if(X.startsWith("/mcp/conn_")){let F=X.split("/")[2]??"";W=`/mcp/${Z9.mcp}${Ri(F.slice(0,12))}\u2026${Z9.reset}`}else if(X==="/mcp")W=`${Z9.mcp}/mcp${Z9.reset}`;else if(X==="/mcp/registry")W=`${Z9.mcp}/mcp/registry${Z9.reset}`;let K=Zc6(Y),H=G?"\u25C0":"\u2190";if(!VU1())console.log(`${Z9.dim}${H}${Z9.reset} ${K}${Y}${Z9.reset} ${W}${J?` ${J}`:""}`);try{await Z()}finally{let F=Date.now()-Q,U=$.res.status,N=$c6(U),B=F<1000?`${F}ms`:`${(F/1000).toFixed(1)}s`,O=G?"\u25B6":"\u2192";if(!VU1())console.log(`${Z9.dim}${O}${Z9.reset} ${K}${Y}${Z9.reset} ${W}${J?` ${J}`:""} ${N}${U}${Z9.reset} ${Z9.duration}${B}${Z9.reset}`);SU1.emit("request",{method:Y,path:Ri(X),status:U,duration:F,timestamp:new Date})}}}var Z9,$c6=($)=>{if($>=500)return Z9.serverError;if($>=400)return Z9.clientError;if($>=300)return Z9.redirect;return Z9.ok},Zc6=($)=>{return Z9[$]||Z9.reset},Ri=($)=>{return $.replace(/\r/g,"").replace(/\n/g,"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"")};var h58=D(()=>{kU1();y58();Z9={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",GET:"\x1B[36m",POST:"\x1B[33m",PUT:"\x1B[35m",DELETE:"\x1B[31m",ok:"\x1B[32m",redirect:"\x1B[36m",clientError:"\x1B[33m",serverError:"\x1B[31m",mcp:"\x1B[35m",tool:"\x1B[96m",duration:"\x1B[90m"}});import{createHmac as m58}from"crypto";import{mkdir as Qc6,readdir as Yc6,rm as u58,stat as d58}from"fs/promises";import{join as _U1,relative as Xc6}from"path";import{z as s$}from"zod";function p58($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return _U1(Jc6,Z)}function n58($){return $.replace(/^\/+/,"").replace(/\.\./g,"")}function CU1($,Z){let Q=p58($),Y=n58(Z);return _U1(Q,Y)}function Gc6($,Z,Q,Y){let X=E0().encryptionKey||"dev-secret",J=`${$}:${Z}:${Q}:${Y}`;return m58("sha256",X).update(J).digest("hex")}function c58($,Z,Q,Y,X){let J=Math.floor(Date.now()/1000)+Y,G=Gc6(Z,Q,J,X),W=new URL(`/api/dev-assets/${Z}/${n58(Q)}`,$);return W.searchParams.set("expires",J.toString()),W.searchParams.set("signature",G),W.searchParams.set("method",X),W.toString()}function t58($,Z,Q){let Y=`${$}:${Z.getTime()}:${Q}`;return`"${m58("md5","etag").update(Y).digest("hex")}"`}async function o58($,Z,Q,Y,X){try{let J=await Yc6($,{withFileTypes:!0});for(let G of J){let W=_U1($,G.name),H=Xc6(Z,W).replace(/\\/g,"/");if(Q&&!H.startsWith(Q))continue;if(G.isDirectory())if(Y){let F=H+"/";if(!Q||F.startsWith(Q)){if(!(Q?H.slice(Q.length):H).includes("/"))X.commonPrefixes.add(F)}}else await o58(W,Z,Q,Y,X);else if(G.isFile()){if(Y&&Q){let F=H.slice(Q.length);if(F.includes(Y)){let U=F.indexOf(Y),N=Q+F.slice(0,U+1);X.commonPrefixes.add(N);continue}}try{let F=await d58(W);X.objects.push({key:H,size:F.size,lastModified:F.mtime.toISOString(),etag:t58(W,F.mtime,F.size)})}catch{}}}}catch{}}function r58($,Z){let Y=K0($).id;return[{name:"LIST_OBJECTS",description:"List objects in the local assets directory with pagination support",inputSchema:s$.object({prefix:s$.string().optional(),maxKeys:s$.number().optional().default(1000),continuationToken:s$.string().optional(),delimiter:s$.string().optional()}),outputSchema:s$.object({objects:s$.array(s$.object({key:s$.string(),size:s$.number(),lastModified:s$.string(),etag:s$.string()})),nextContinuationToken:s$.string().optional(),isTruncated:s$.boolean(),commonPrefixes:s$.array(s$.string()).optional()}),handler:async(X)=>{let J=X,G=J.prefix||"",W=J.maxKeys??1000,K=J.delimiter,H=J.continuationToken,F=p58(Y);await Qc6(F,{recursive:!0});let U={objects:[],commonPrefixes:new Set};await o58(F,F,G,K,U),U.objects.sort((w,j)=>w.key.localeCompare(j.key));let N=0;if(H){if(N=U.objects.findIndex((w)=>w.key>H),N===-1)N=U.objects.length}let B=U.objects.slice(N,N+W),O=N+W<U.objects.length,L=O?B[B.length-1]?.key:void 0;return{objects:B,isTruncated:O,nextContinuationToken:L,commonPrefixes:Array.from(U.commonPrefixes).sort()}}},{name:"GET_OBJECT_METADATA",description:"Get metadata for a file in the local assets directory",inputSchema:s$.object({key:s$.string()}),outputSchema:s$.object({contentType:s$.string().optional(),contentLength:s$.number(),lastModified:s$.string(),etag:s$.string(),metadata:s$.record(s$.string(),s$.string()).optional()}),handler:async(X)=>{let J=X,G=CU1(Y,J.key),W=await d58(G);return{contentType:JH1(J.key),contentLength:W.size,lastModified:W.mtime.toISOString(),etag:t58(G,W.mtime,W.size)}}},{name:"GET_PRESIGNED_URL",description:"Generate a presigned URL for downloading a file from local storage",inputSchema:s$.object({key:s$.string(),expiresIn:s$.number().optional()}),outputSchema:s$.object({url:s$.string(),expiresIn:s$.number()}),handler:async(X)=>{let J=X,G=zO(J.expiresIn,l58);return{url:c58(Z,Y,J.key,G,"GET"),expiresIn:G}}},{name:"PUT_PRESIGNED_URL",description:"Generate a presigned URL for uploading a file to local storage",inputSchema:s$.object({key:s$.string(),expiresIn:s$.number().optional(),contentType:s$.string().optional()}),outputSchema:s$.object({url:s$.string(),expiresIn:s$.number()}),handler:async(X)=>{let J=X,G=zO(J.expiresIn,l58);return{url:c58(Z,Y,J.key,G,"PUT"),expiresIn:G}}},{name:"DELETE_OBJECT",description:"Delete a single file from local storage",inputSchema:s$.object({key:s$.string()}),outputSchema:s$.object({success:s$.boolean(),key:s$.string()}),handler:async(X)=>{let J=X,G=CU1(Y,J.key);try{return await u58(G),{success:!0,key:J.key}}catch{return{success:!1,key:J.key}}}},{name:"DELETE_OBJECTS",description:"Delete multiple files from local storage",inputSchema:s$.object({keys:s$.array(s$.string()).max(1000)}),outputSchema:s$.object({deleted:s$.array(s$.string()),errors:s$.array(s$.object({key:s$.string(),message:s$.string()}))}),handler:async(X)=>{let J=X,G=[],W=[];return await Promise.all(J.keys.map(async(K)=>{let H=CU1(Y,K);try{await u58(H),G.push(K)}catch(F){W.push({key:K,message:F instanceof Error?F.message:"Unknown error"})}})),{deleted:G,errors:W}}}]}async function vU1($,Z,Q){let Y=r58(Z,Q),X=new ML({name:"dev-assets-mcp",version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:PZ});for(let G of Y){let W="shape"in G.inputSchema?G.inputSchema.shape:s$.object({}).shape,K=G.outputSchema&&"shape"in G.outputSchema?G.outputSchema.shape:s$.object({}).shape;X.registerTool(G.name,{description:G.description??"",inputSchema:W,outputSchema:K,annotations:G.annotations,_meta:G._meta},async(H)=>{try{let F=await G.handler(H);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}})}let J=new Y3({enableJsonResponse:$.headers.get("Accept")?.includes("application/json")??!1});return await X.connect(J),MW(X,J,$,"mcp:dev-assets")}async function s58($,Z,Q,Y){let J=r58(Q,Y).find((G)=>G.name===$);if(!J)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};try{let G=await J.handler(Z);return{content:[{type:"text",text:JSON.stringify(G)}]}}catch(G){return{content:[{type:"text",text:G instanceof Error?G.message:String(G)}],isError:!0}}}var Jc6="./data/assets",l58=3600,i58,a58;var e58=D(()=>{F$();um();G8();mY0();hm();aX();PO();tV0();i58=new Q1;i58.all("/",async($)=>{let Z=$.get("studioContext"),Q=new URL($.req.url),Y=`${Q.protocol}//${Q.host}`;return vU1($.req.raw,Z,Y)});a58=i58});var $98={};M6($98,{mountDevRoutes:()=>Wc6});function Wc6($,Z){$.all("/mcp/:connectionId{.*_dev-assets$}",Z,async(Y)=>{let X=Y.get("studioContext"),J=new URL(Y.req.url),G=`${J.protocol}//${J.host}`;return vU1(Y.req.raw,X,G)}),$.all("/mcp/:connectionId{.*_dev-assets$}/call-tool/:toolName",Z,async(Y)=>{let X=Y.get("studioContext"),J=new URL(Y.req.url),G=`${J.protocol}//${J.host}`,W=Y.req.param("toolName");if(!W)return Y.json({error:"Missing tool name"},400);let K=await Y.req.json(),H=await s58(W,K,X,G);if(H.isError)return Y.json(H.content,500);return Y.json(H.content)}),$.use("/mcp/dev-assets",Z),$.route("/mcp/dev-assets",a58);let Q=new Q1;Q.use("*",RH({mountPath:"/api/dev-assets"})),Q.route("/",nV0({orgFromPath:!1})),$.route("/api/dev-assets",Q)}var Z98=D(()=>{G8();aK1();tV0();e58()});var U98={};M6(U98,{watchHandler:()=>F98,resolveCorsOrigin:()=>K98,isSsoExemptPath:()=>G98,isAllowedOAuthRedirectUri:()=>H98,createApp:()=>wc6});import{readFileSync as Kc6}from"fs";import{PrometheusSerializer as Hc6}from"@opentelemetry/exporter-prometheus";import{DBOS as gO}from"@dbos-inc/dbos-sdk";import{oAuthDiscoveryMetadata as Nc6,oAuthProtectedResourceMetadata as Bc6}from"better-auth/plugins";async function Fc6($){let Z=$.connect(),Q;try{Q=await Promise.race([Z,Y98(Q98)])}catch{return Z.then((Y)=>Y.release(!0)).catch(()=>{}),!1}try{return await Promise.race([Q.query("SELECT 1"),Y98(Q98)]),Q.release(),!0}catch{return Q.release(!0),!1}}function Y98($){return new Promise((Z,Q)=>setTimeout(()=>Q(Error("pg health-check timeout")),$))}function G98($){return $.startsWith("/api/org-sso/")||/^\/api\/[^/]+\/sso\//.test($)||$.startsWith("/api/auth/")||$.startsWith("/api/tools/management")||$.startsWith("/oauth-proxy/")||/^\/api\/[^/]+\/oauth-proxy\//.test($)||$.startsWith(`${vV0}/`)||$.startsWith(`${IV0}/`)}function W98($){return $==="local.studio.decocms.com"}function K98($,{baseUrl:Z,requestOrigin:Q}){let Y;try{Y=new URL($).hostname}catch{return null}if(Y==="localhost"||Y==="127.0.0.1")return $;if(W98(Y))return $;let X=Z??Q;try{if(new URL(X).origin===$)return $}catch{}return null}function H98($,Z){return $.origin===new URL(Z).origin||$.hostname==="localhost"||W98($.hostname)}async function wc6($={}){let Z=$.database??P8(),Q=!1;e5.stop().catch((Q0)=>{console.error("[SSEHub] Error stopping previous broadcast (HMR cleanup):",Q0)});let Y,X,J,G,W=new LU1,K,H,F,U=null;if($.disableNats)K=wU1(),Y={get:async()=>null,set:async()=>{},invalidate:async()=>{},teardown:()=>{}},X=null,J=null,G=new h10,H={start:async()=>{},broadcast:()=>{},stop:async()=>{}},F={init:async()=>{},pump:(Q0)=>{return(async()=>{let w0=Q0.getReader();try{while(!0){let{done:e}=await w0.read();if(e)break}}catch{}finally{w0.releaseLock()}})()},publishRawChunk:async()=>!1,publishDone:async()=>!1,createTailStream:async()=>null,purge:()=>{},teardown:()=>{}};else{U=N58();let Q0=E0().natsCredsPath,w0;if(Q0)try{w0=Kc6(Q0,"utf8")}catch(f0){console.error(`[app] failed to read NATS_CREDS at ${Q0}; connecting anonymously`,f0)}U.init(E0().natsUrls,w0?{creds:w0}:void 0);let e=me0()?new Me0({getJetStream:()=>U.getJetStream()}):null;e?.init().catch(()=>{}),Y=e;let i=new g41({getJetStream:()=>U.getJetStream()});i.init().catch(()=>{}),X=i;let m0=new ax(V91,{getJetStream:()=>U.getJetStream()}),I0=new ax(Y10,{getJetStream:()=>U.getJetStream()});m0.init().catch(()=>{}),I0.init().catch(()=>{}),J={reads:m0,cards:I0};let t0=new LQ1({getJetStream:()=>U.getJetStream()});t0.init().catch(()=>{}),G=t0,K=wU1({getConnection:()=>U.getConnection()}),H=new jU1({getConnection:()=>U.getConnection()}),F=new PU1({getConnection:()=>U.getConnection(),getJetStream:()=>U.getJetStream()}),Ha$(U),U.onReady(()=>{e?.init().catch((f0)=>{console.error("[McpListCache] Deferred init failed:",f0)}),i.init().catch((f0)=>{console.error("[SkillCatalogCache] Deferred init failed:",f0)}),m0.init().catch((f0)=>{console.error("[PrReadCache] Deferred init failed:",f0)}),I0.init().catch((f0)=>{console.error("[PrCardCache] Deferred init failed:",f0)}),t0.init().catch((f0)=>{console.error("[ConnectionCircuitStore] Deferred init failed:",f0)}),K.start(),gK$(()=>U.getConnection()),F.init().catch((f0)=>{console.warn("[Decopilot] StreamBuffer init failed (late-join disabled):",f0)})})}if(PE)await PE();Ie0(Y),u41(X),k91(J),wQ1(G);let B={storage:new Hh(Z.db),sseHub:e5,onThreadFinished:async(Q0,w0)=>Tm(new sG(Z.db),Q0,w0,new DG(Z.db))},O=new lZ1(B),L=new J80(Z.db),w=new AU1(L);w.start(),E_$(H),H.start((Q0)=>{lT0(Q0),O.execute({type:"CANCEL",taskId:Q0}).catch((w0)=>{console.error("[Decopilot] CancelBroadcast execute failed:",w0)})}).catch((Q0)=>{console.error("[Decopilot] CancelBroadcast start failed:",Q0)}),U?.onReady(()=>{H.start().catch((Q0)=>{console.error("[CancelBroadcast] Deferred start failed:",Q0)})});let j=()=>U?.getConnection()??null;tK1(j),U?.onReady(()=>tK1(j)),oQ1(j),U?.onReady(()=>oQ1(j)),F.init().catch((Q0)=>{console.warn("[Decopilot] StreamBuffer init failed, attach/late-join disabled:",Q0)}),PE=async()=>{await O.stopAll(),O.dispose(),w.dispose(),H.stop().catch(()=>{}),qe$(),F.teardown(),Y?.teardown(),X?.teardown(),J?.reads.teardown(),J?.cards.teardown(),W.teardown(),K.teardown(),hK$(),G.teardown(),Ie0(null),u41(null),k91(null),wQ1(null)};let E=new Q1;if(E.use("*",BQ1({enabled:(Q0)=>pd(Q0,"debug")==="1"})),E.use("*",VS0),E.use("/*",Xa$({origin:(Q0,w0)=>K98(Q0,{baseUrl:E0().baseUrl,requestOrigin:new URL(w0.req.url).origin}),credentials:!0,allowMethods:["GET","POST","PUT","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","mcp-protocol-version"],exposeHeaders:["WWW-Authenticate"]})),E.use("*",async(Q0,w0)=>{if(await w0(),Q0.req.path.includes("/files/"))return;if(Q0.req.path.includes("/fs/")&&Q0.req.path.endsWith("/read"))return;Q0.header("X-Frame-Options","DENY"),Q0.header("Content-Security-Policy","frame-ancestors 'none'")}),!E0().noTui)E.use("*",g58());E.use("*",async(Q0,w0)=>{if(await w0(),bi(Q0.req.path))return;if(Q0.res.status>=500){let i=await Q0.res.clone().text();console.error(`[5xx Response] ${Q0.req.method} ${Q0.req.path} - ${Q0.res.status}:`,i)}}),E.get(mY.HEALTH,(Q0)=>{if(Q)return Q0.json({status:"shutting_down"},503);return Q0.json({status:"ok"})}),E.get(mY.HEALTH_LIVE,(Q0)=>{return Q0.json({status:"ok"})}),E.get(mY.HEALTH_READY,async(Q0)=>{if(Q)return Q0.json({status:"shutting_down"},503);let w0={};if(w0.postgres={status:await Fc6(Z.pool)?"up":"down"},U)w0.nats=U.isConnected()?{status:"up"}:{status:"down"};else w0.nats={status:"down"};let e=w0.postgres.status==="up",i=e?200:503;return Q0.json({status:e?"ready":"not_ready",services:w0},i)}),E.get(mY.METRICS,async(Q0)=>{try{let w0=await _S0.collect(),e=Uc6.serialize(w0.resourceMetrics);return Q0.text(e,200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"})}catch(w0){return console.error("Failed to collect metrics:",w0),Q0.text("# Error collecting metrics",500)}});let z=1800000;E.get(`${mY.DBOS_QUEUE_DEPTH_PREFIX}:queueName`,async(Q0)=>{let w0=Q0.req.param("queueName");if(!Oc6.has(w0))return Q0.json({error:`Unknown queue: ${w0}`},404);let[e,i]=await Promise.all([gO.listQueuedWorkflows({queueName:w0,status:"ENQUEUED",loadInput:!1,loadOutput:!1}),gO.listQueuedWorkflows({queueName:w0,status:"PENDING",loadInput:!1,loadOutput:!1,dequeuedAfter:new Date(Date.now()-z).toISOString()})]);return Q0.json({queue_length:e.length,in_flight:i.length})}),E.route("/api/config",z68),E.route("/api/_reports",_68),E.route("/api/_stripe",NU1),E.route("/api/_github",x68({taskBoard:()=>n,contextFactory:()=>g})),E.route("/api/_git",$i);let T={db:Z.db,encryptionKey:E0().encryptionKey};E.route("/api/_jira",h68(T)),E.route("/api/_jira",y68(T)),E.route("/report",k68($.clientDir)),E.route("/api/auth/custom",ka$),E.route("/api/auth/desktop",va$),E.all("/api/auth/admin/*",Ue$),E.all("/api/auth/*",async(Q0)=>{return await C8.handler(Q0.req.raw)});let P=yr$();P.use("/.well-known/oauth-protected-resource/mcp/:connectionId",j80),P.use("/mcp/:connectionId/.well-known/oauth-protected-resource",j80),E.route("/",P),E.get("/.well-known/oauth-protected-resource/api/:org/mcp/:connectionId",Z80),E.route("/",cr$()),E.use("/oauth-proxy/:connectionId/*",j80),E.all("/oauth-proxy/:connectionId/*",X98);let A=async(Q0)=>{let e=await Dc6()(Q0.req.raw),i=await e.json();return Response.json(i,e)};E.use("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",j80),E.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",A);let q=async(Q0)=>{let e=await Lc6()(Q0.req.raw),i=await e.json();return Response.json(i,e)};E.get("/.well-known/oauth-authorization-server/*/:gateway?/:connectionId?",q);let x=Ga$({ttlMs:120000}),_=await Cs$({db:Z.db,auth:C8,encryption:{key:E0().encryptionKey},observability:{tracer:nO,meter:z$},modelListCache:W,providerKeyCache:K,memberRoleCache:x});vQ.set(_),Sc1({db:Z.db,baseUrl:x5()}),_s$({db:Z.db}),fs$({db:Z.db}),ds$({db:Z.db}),c68({db:Z.db,encryptionKey:E0().encryptionKey}),rI$({db:Z.db}),rs$({db:Z.db}),EV$({db:Z.db});let V=_Q0(Z.db),y=new No(Z.db),g=b58({db:Z.db});HQ1({storage:V,studioContextFactory:g}),sZ1({systemDatabaseUrl:nt0(E0().databaseUrl,E0().databasePgSsl),studioContextFactory:g,deps:{runRegistry:O,cancelBroadcast:H,streamBuffer:F,sseHub:e5}}),dZ1({dispatchRunFn:HC$,studioContextFactory:g,deps:{runRegistry:O,cancelBroadcast:H,streamBuffer:F,sseHub:e5}});let l=new Hh(Z.db),n=new sG(Z.db),p=new DG(Z.db),F0=new RU1(n,g,p);if(E0().taskBoardReviewSweeperEnabled){F0.start();let Q0=PE;PE=async()=>{await Q0?.(),F0.dispose()}}SC$({getJetStream:()=>U?.getJetStream()??null,getJetStreamManager:async()=>{let Q0=U?.getConnection();return Q0?await J98.jetstreamManager(Q0):null},messageParts:l.messageParts(),resolveRun:async(Q0)=>{let w0=await Z.db.selectFrom("threads").select(["organization_id","created_by","message_storage_version","status","run_fence_token","title"]).where("id","=",Q0).executeTakeFirst();return w0?{orgId:w0.organization_id,createdBy:w0.created_by,version:w0.message_storage_version??1,status:w0.status,runFenceToken:w0.run_fence_token,title:w0.title??null}:null},completeRunIfNotCompleted:async(Q0,w0)=>{let e=await l.completeRunIfNotCompleted(Q0,w0);if(YS0(e5,w0,Q0,e),e)await Tm(n,Q0,w0,p);return e},markRunRequiresAction:async(Q0,w0)=>{let e=await l.requiresActionIfInProgress(Q0,w0);return YS0(e5,w0,Q0,e),e},markRunFailed:async(Q0,w0,e,i)=>{let m0=await l.markRunFailed(Q0,w0,e,i);if(YS0(e5,w0,Q0,m0),m0)await Tm(n,Q0,w0,p);return m0},clearSynthesizedError:async(Q0,w0)=>{await l.messageParts().replaceMessageParts(Q0,xj(Q0,w0),[])},persistTitle:(Q0,w0,e)=>l.update(Q0,w0,{title:e}),onTitleUpdated:async({runId:Q0,orgId:w0,title:e})=>{let i=await l.get(Q0,w0).catch(()=>null);e5.emit(w0,nH(Q0,i?.status??"in_progress",{title:e,virtualMcpId:i?.virtual_mcp_id??void 0,createdBy:i?.created_by,triggerId:i?.trigger_id,branch:i?.branch??null,harnessId:i?.harness_id??void 0,createdAt:i?.created_at,updatedAt:i?.updated_at}))},bumpProgress:async({runId:Q0,orgId:w0})=>{await l.bumpProgress(Q0,w0)},recordCompleted:async({runId:Q0,orgId:w0,distinctId:e,usage:i})=>{v1.capture({distinctId:e,event:"chat_message_completed",groups:{organization:w0},properties:{organization_id:w0,thread_id:Q0,transport:"projector",input_tokens:i.inputTokens,output_tokens:i.outputTokens,total_tokens:i.totalTokens}})},recordFailed:async({runId:Q0,orgId:w0,distinctId:e,reason:i,kind:m0})=>{v1.capture({distinctId:e,event:"chat_message_failed",groups:{organization:w0},properties:{organization_id:w0,thread_id:Q0,transport:"projector",error_category:m0,error_message:i}})},purgeRun:async(Q0)=>{F.purge(Q0)}}),xS$({studioContextFactory:g,systemDatabaseUrl:nt0(E0().databaseUrl,E0().databasePgSsl),streamBuffer:F}),_58(),Cc1(),bs$(),gs$(),ps$(),i68(),ZV$(),as$(),zV$();let V0=async(Q0,w0,e)=>{let i=await V.findById(Q0,w0);if(!i)throw Error("Automation not found");return NQ1({automationId:i.id,organizationId:i.organization_id,triggerId:null})},G0=new ad(V,({automation:Q0,trigger:w0,contextMessages:e,idempotencyKey:i})=>g10({automationId:Q0.id,organizationId:Q0.organization_id,triggerId:w0.id,contextMessages:e},{idempotencyKey:i})),H0=[uW(),Ty(),eU()];for(let Q0 of H0)GS0(Q0).then(()=>{}).catch((w0)=>console.error("[monitoring] Retention cleanup failed:",w0));let X0=()=>C8.api.deleteAllExpiredApiKeys().catch((Q0)=>console.error("[auth] Expired API key cleanup failed:",Q0));X0(),setInterval(X0,86400000).unref(),E.use("*",async(Q0,w0)=>{if(MS0(Q0.req.path))return w0();let e={measure:async(m0,I0)=>{qW(Q0,m0);try{return await I0()}finally{X3(Q0,m0)}}},i=await vQ.create(Q0.req.raw,{timings:e});i.automationRunner=V0,Q0.set("studioContext",i);try{await w0()}finally{let m0=i.pendingRevalidations;if(m0.length>0)Promise.race([Promise.allSettled(m0),i$(30000)]).catch((t0)=>console.error("[studio] revalidation cleanup error:",t0))}}),E.use("/api/:org/decopilot/*",td),E.use("/api/:org/v1/*",td),E.use("/api/:org/files/*",td),E.use("*",async(Q0,w0)=>{if(G98(Q0.req.path))return w0();let e=Q0.get("studioContext");if(!e?.organization?.id||!e?.auth?.user?.id)return w0();if(!(await e.storage.orgSsoConfig.getByOrgId(e.organization.id))?.enforced)return w0();if(!await e.storage.orgSsoSessions.isValid(e.auth.user.id,e.organization.id))return Q0.json({error:"SSO authentication required for this organization"},403);return w0()});let Z0=new Q1;Z0.use("*",RH({mountPath:"/api/org-sso"})),Z0.route("/",fV0()),E.route("/api/org-sso",Z0),E.get("/api/tools/management",(Q0)=>{return Q0.json({tools:Vi0,grouped:BP()})}),E.use("/mcp/*",async(Q0,w0)=>{qW(Q0,"mcp");try{return await w0()}finally{X3(Q0,"mcp")}});let Y0=async(Q0,w0)=>{let e=Q0.var.studioContext;if(!e.auth.user?.id&&!e.auth.apiKey?.id){let i=new URL(Q0.req.url),m0=Q0.req.header("x-forwarded-proto")?.split(",")[0]?.trim(),I0=m0?`${m0}://${i.host}`:i.origin;return Q0.res=new Response(null,{status:401,headers:{"WWW-Authenticate":`Bearer realm="mcp",resource_metadata="${I0}${i.pathname}/.well-known/oauth-protected-resource"`}})}return await w0()};if(E.use("/mcp/:connectionId?",Y0),E.use("/mcp/gateway/:virtualMcpId?",Y0),E.use("/mcp/virtual-mcp/:virtualMcpId?",Y0),E.use("/mcp/self",Y0),JW()){let{mountDevRoutes:Q0}=(Z98(),OS0($98));Q0(E,Y0)}let o=new Q1;o.use("*",RH({mountPath:"/mcp"})),o.route("/",vR0()),E.route("/mcp",o);let J0=new Q1;J0.use("*",RH({mountPath:"/mcp/self"})),J0.route("/",qk0()),E.route("/mcp/self",J0);let c0=new Q1;c0.use("*",RH({mountPath:"/mcp"})),c0.route("/",fR0()),E.route("/mcp",c0),E.use("/api/:org/models/*",async(Q0,w0)=>{qW(Q0,"llm_models");try{return await w0()}finally{X3(Q0,"llm_models")}});let k0=Ie$({cancelBroadcast:H,streamBuffer:F,runRegistry:O});E.route("/api",k0),E.route("/api",o68);let j1=new Q1;j1.use("*",RH({mountPath:"/api"})),j1.route("/",kk0()),E.route("/api",j1),E.route("/api",B68);let d0=new Q1;d0.use("*",RH({mountPath:"/api"})),d0.route("/",Sk0({tokenStorage:y,automationEventDispatcher:G0})),E.route("/api",d0);let L0=new Oo(Z.db),j0=new Q1;j0.use("*",RH({mountPath:"/api"})),j0.route("/",lV0()),E.route("/api",j0),E.route("/api/deco-sites",le$()),E.route("/api/deco-apps",W68());let a0=new Q1;a0.use("*",RH({mountPath:"/api/deco-sites"})),a0.route("/",mV0()),E.route("/api/deco-sites",a0),E.route(vV0,Ne$()),E.route(E88,A88()),E.route("/api/_editor-resolve",D68()),E.route(xa$,fa$()),E.route(IV0,pa$());let P1=J68({kvStorage:L0,runRegistry:O,streamBuffer:F,sseHub:e5,cancelBroadcast:H,tokenStorage:y,automationEventDispatcher:G0,mountDevAssets:JW(),mcpAuth:Y0,oauthProxyHandler:X98,watchHandler:F98,betterAuthProtectedResourceHandler:A,getNatsConnection:()=>U?.getConnection()??null});return E.route("/api/:org",P1),E.notFound((Q0)=>{return Q0.json({error:"Not Found",path:Q0.req.path},404)}),E.onError(Se$),Object.assign(E,{markShuttingDown:()=>{Q=!0},shutdown:async()=>{if(console.log("[shutdown] Stopping workers..."),await Promise.allSettled([e5.stop(),PE?Promise.resolve(PE()).finally(()=>{PE=null}):Promise.resolve()]),U)await U.drain().catch((Q0)=>console.error("[shutdown] NATS drain error:",Q0));console.log("[shutdown] Flushing telemetry..."),await fX().catch((Q0)=>console.error("[shutdown] Telemetry flush error:",Q0)),console.log("[shutdown] Closing database..."),await q4$(Z).catch((Q0)=>console.error("[shutdown] Database close error:",Q0)),console.log("[shutdown] Cleanup complete.")},initDbos:async()=>{await gO.registerQueue(O3,{partitionQueue:!0,concurrency:GQ1,minPollingIntervalMs:WQ1}),await gO.registerQueue(B3,{partitionQueue:!0,concurrency:oZ1,priorityEnabled:!0}),await gO.registerQueue(sU,{workerConcurrency:E0().decopilotMaxConcurrentHostedRuns,priorityEnabled:!0}),await gO.registerQueue(aU,{workerConcurrency:E0().sandboxMaxConcurrentHostedRuns,priorityEnabled:!0}),await gO.registerQueue(iO,{partitionQueue:!0,concurrency:bS$}),await gO.registerQueue(ME,jV$),await eK1(V),await Promise.allSettled(["automations-gate","automations-global","jira-push"].map((Q0)=>gO.deleteQueue(Q0))),await KQ1(Z.pool),p9$().catch((Q0)=>{console.error("[studio-pack-backfill] failed:",Q0)}),_c1().catch((Q0)=>{console.error("[org-fs] public-sets boot sync kick failed:",Q0)})}})}var J98,Q98=5000,PE=null,X98=async($)=>{let Z=$.req.param("connectionId");if(!Z)return $.json({error:"Missing connectionId"},400);let Q=$.req.path.split("/").filter(Boolean),Y=Q[Q.length-1],X=$.get("studioContext");if(!X)X=await vQ.create($.req.raw),$.set("studioContext",X);let J=$.req.param("org")?X.organization?.id:void 0,G=await X.storage.connections.findById(Z,J);if(!G?.connection_url)return $.json({error:"Connection not found"},404);if(Y==="register"&&G.oauth_config?.clientId){let y=await $.req.json().catch(()=>({}));return $.json({...typeof y==="object"&&y!==null?y:{},client_id:G.oauth_config.clientId,...G.oauth_config.clientSecret?{client_secret:G.oauth_config.clientSecret}:{},client_secret_expires_at:0})}let W=await cd(G.connection_url),K,H=new URL(G.connection_url),U=(typeof G.metadata?.oauthResource==="string"&&G.metadata.oauthResource.length>0?G.metadata.oauthResource:void 0)??G.connection_url;if(W.ok)K=(await W.json()).authorization_servers?.[0];if(!K)K=H.origin;let N=await Q80(K);if(!N.ok)return $.json({error:"Failed to get auth server metadata"},502);let B=await N.json(),O;if(Y==="authorize")O=B.authorization_endpoint;else if(Y==="token")O=B.token_endpoint;else if(Y==="register")O=B.registration_endpoint;if(!O)return $.json({error:`Unknown OAuth endpoint: ${Y}`},404);let L=lr$(O);if(L)return L;let w=new URL(O),j=new URL($.req.url);if(w.search=j.search,Y==="authorize"){let y=w.searchParams.get("redirect_uri");if(y){let g=E0().baseUrl??j.origin;try{if(!H98(new URL(y),g))return $.json({error:"invalid_request",error_description:"redirect_uri is not allowed"},400)}catch{return $.json({error:"invalid_request",error_description:"redirect_uri is malformed"},400)}w.searchParams.set("redirect_uri",y)}if(w.searchParams.has("resource"))w.searchParams.set("resource",U);if($a$(G.connection_url))w.searchParams.set("auto_personal","true"),w.searchParams.set("force_new","true");return $.redirect(w.toString(),302)}let E={Accept:$.req.header("Accept")||"application/json"},z=$.req.header("Content-Type");if(z)E["Content-Type"]=z;let T=$.req.header("Authorization");if(T)E.Authorization=T;let P,A=null,q=null;if($.req.method!=="GET"&&$.req.method!=="HEAD")if(Y==="token"&&z?.includes("application/x-www-form-urlencoded")){if(T?.toLowerCase().startsWith("basic "))try{let p=atob(T.slice(6).trim()),F0=p.indexOf(":");if(F0!==-1){let V0=decodeURIComponent(p.slice(0,F0)),G0=decodeURIComponent(p.slice(F0+1));A=V0||null,q=G0||null}}catch{}let y=await $.req.formData();if(y.has("resource"))y.set("resource",U);let g=y.get("client_id"),l=y.get("client_secret");if(typeof g==="string"&&g)A=g;if(typeof l==="string"&&l)q=l;let n=new URLSearchParams;for(let[p,F0]of y.entries())n.append(p,F0.toString());P=n.toString()}else if(Y==="register"&&z?.toLowerCase().includes("application/json")){let y=await X.db.selectFrom("organization").select(["id","slug","name"]).where("id","=",G.organization_id).executeTakeFirst(),g=await $.req.text(),l={};try{l=g?JSON.parse(g):{}}catch{P=g}let n=typeof l==="object"&&l!==null&&!Array.isArray(l);if(P===void 0&&!n)P=g;if(P===void 0){let p=l,F0=p.metadata&&typeof p.metadata==="object"?p.metadata:{};p.metadata={...F0,organization_id:G.organization_id,...y?.slug?{organization_slug:y.slug}:{},...y?.name?{organization_name:y.name}:{}},P=JSON.stringify(p),E["Content-Type"]="application/json"}}else P=$.req.raw.body??void 0;let x=await fetch(w.toString(),{method:$.req.method,headers:E,body:P,duplex:"half",redirect:"manual"}),_=new Headers,V=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];for(let[y,g]of x.headers.entries())if(!V.includes(y.toLowerCase()))_.set(y,g);if(Y==="token"&&x.ok){let y=await x.text();try{let g=JSON.parse(y);if(typeof g.access_token==="string"&&g.access_token){let l=typeof g.expires_in==="number"?new Date(Date.now()+g.expires_in*1000):null,n=null;try{n=await md(G.connection_url)??O}catch{n=O}let p={connectionId:Z,accessToken:g.access_token,refreshToken:typeof g.refresh_token==="string"?g.refresh_token:null,scope:typeof g.scope==="string"?g.scope:null,expiresAt:l,clientId:A,clientSecret:q,tokenEndpoint:n};await new F9(X.db,X.vault).upsert(p)}}catch(g){console.error("[oauth-proxy] failed to persist downstream token:",g)}return new Response(y,{status:x.status,statusText:x.statusText,headers:_})}return new Response(x.body,{status:x.status,statusText:x.statusText,headers:_})},F98=async($)=>{let Z=$.var.studioContext,Q=Z.auth.user?.id??Z.auth.apiKey?.userId;if(!Q)return $.json({error:"Unauthorized"},401);let Y=Z.organization?.id;if(!Y)return $.json({error:"organization id missing"},400);let X=$.req.query("types"),J=X?X.split(",").map((H)=>H.trim()).filter(Boolean):null,G=$.req.query("scope")==="all";if(G&&(!DU(Y)||!await LU(Z)))return $.json({error:"forbidden"},403);let W=G?a20:Y;if(G)XO({action:"watch_all_orgs",actorUserId:Q,actorOrgId:Y,targetOrgId:"all"});let K=crypto.randomUUID();return bO($,async(H)=>{if(await H.writeSSE({event:"connected",data:JSON.stringify({listenerId:K,organizationId:Y,typePatterns:J,connectedAt:new Date().toISOString()})}),!e5.add({id:K,organizationId:W,typePatterns:J?.length?J:null,push:(N,B)=>{H.writeSSE({id:N.id,event:N.type,data:JSON.stringify(G?{...N,organizationId:B}:N)}).catch(()=>{e5.remove(W,K)})}})){await H.writeSSE({event:"error",data:JSON.stringify({error:"Too many connections",message:"SSE connection limit reached. Try again later."})});return}let U=setInterval(()=>{H.writeSSE({event:"keepalive",data:""}).catch(()=>{clearInterval(U),e5.remove(W,K)})},30000);await new Promise((N)=>{H.onAbort(()=>{clearInterval(U),e5.remove(W,K),N()})})})},Uc6,Oc6,Dc6=()=>Bc6(C8),Lc6=()=>Nc6(C8);var N98=D(()=>{D8();F$();vc1();xs$();hs$();ns$();d10();U91();es$();Q10();E9();al();e8();G8();AV0();Ja$();OQ1();hG();pF();RK1();m3();C6();U6();CK1();ba$();ya$();na$();yK1();Be$();iK1();Ve$();sK1();iK();GV0();aK1();Ce$();RV0();G68();QH1();K68();bR0();u10();O68();yR0();CF1();L68();kF1();P68();S68();v68();b68();f68();g68();u68();p68();WH1();r68();SF1();MF1();P40();B58();DJ();xA0();C91();ya();ha();EQ1();O58();L58();oK1();T58();cZ1();R58();on();Lo();YO();V9();iW1();k58();v58();LJ0();qU1();D3();$H1();QO();hZ1();LJ0();sT0();Li0();wi0();x58();Hu();h58();Li();RK1();Lm();Cm();cT0();J98=C(GN(),1);Uc6=new Hc6,Oc6=new Set([O3,B3,sU,aU,iO,ME])});var L98={};M6(L98,{resolveClientDir:()=>Rc6,resolveAssetPathWithTraversalCheck:()=>D98,isPathWithinDirectory:()=>O98,createAssetHandler:()=>qc6});import{resolve as G40,dirname as jc6,join as Ec6,extname as zc6,basename as Pc6,sep as B98}from"path";function Ac6($,Z){if($===Z||Pc6($)==="index.html")return{"Cache-Control":"no-cache"};if($.includes(`${B98}assets${B98}`))return{"Cache-Control":"public, max-age=31536000, immutable"};return{}}function O98($,Z){let Q=G40(Z),Y=G40($);return Y===Q||Y.startsWith(Q+"/")}function D98({requestPath:$,clientDir:Z}){let Q=$.startsWith("/")?$.slice(1):$,Y=G40(Z,Q);if(!O98(Y,Z))return null;return Y}function Rc6($,Z="../client"){let Q=new URL($),Y=jc6(Q.pathname);return G40(Y,Z)}function qc6($={}){let{env:Z="production",clientDir:Q=Tc6,isServerPath:Y=()=>!1}=$;if(Z==="development")return async function(J){return null};return async function(J){if(J.method!=="GET")return null;let G=new URL(J.url),W;try{W=decodeURIComponent(G.pathname)}catch{return null}if(Y(W))return null;let K=D98({requestPath:W,clientDir:Q});if(!K)return null;let H=Ec6(K,"index.html"),F=G40(Q,"index.html"),U=J.headers.get("accept"),B=U?.includes("text/html")||U?.includes("*/*")&&["",".html"].includes(zc6(K))?[H,F]:[];for(let O of[K,...B])try{let L=Bun.file(O);if(await L.exists())return new Response(L,{headers:Ac6(O,F)})}catch{}if(W.includes("/assets/"))return new Response("Not Found",{status:404,headers:{"Cache-Control":"no-store"}});return null}}var Tc6="./dist/client";var w98=()=>{};var j98={};M6(j98,{tryUpgradePreviewWs:()=>_c6,tryHandlePreviewHttp:()=>Cc6,previewWebSocketHandler:()=>vc6,parsePreviewBaseDomain:()=>Sc6,isPreviewWsData:()=>WS0,extractHandleFromHost:()=>bU1});function Vc6($){if($.method!=="GET")return!1;return($.headers.get("accept")??"").includes("text/html")}function kc6(){return new Response(Ic6,{status:503,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","retry-after":"1","access-control-allow-origin":"*"}})}function Sc6($){if(!$||$.trim()==="")return null;let Z=$.includes("{handle}")?$.replace("{handle}","__handle__"):$,Q;try{Q=new URL(Z)}catch{return null}let Y=Q.hostname;if($.includes("{handle}")){let X=Y.indexOf(".");if(X<=0||X===Y.length-1)return null;return Y.slice(X+1)}return Y}function bU1($,Z){if(!$||!Z)return null;let Q=$.indexOf(":"),Y=(Q>=0?$.slice(0,Q):$).toLowerCase(),J=`.${Z.toLowerCase().replace(/^\.+|\.+$/g,"")}`;if(!Y.endsWith(J))return null;let G=Y.slice(0,Y.length-J.length);if(!G||G.includes("."))return null;return G}async function Cc6($,Z){let Q=bU1($.headers.get("host"),Z.baseDomain);if(!Q)return null;let Y=await Z.getRunner();if(!Y)return K40(503,"preview proxy not configured");let X=await Y.proxyPreviewRequest(Q,$);if(X.headers.get(Ix)&&Vc6($))return kc6();return X.headers.delete(Ix),X}function K40($,Z){return new Response(JSON.stringify({error:Z}),{status:$,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function WS0($){return typeof $==="object"&&$!==null&&$.kind==="preview"}async function _c6($,Z,Q){if(($.headers.get("upgrade")??"").toLowerCase()!=="websocket")return null;let Y=bU1($.headers.get("host"),Q.baseDomain);if(!Y)return null;let X=await Q.getRunner();if(!X)return K40(503,"preview proxy not configured");let J=await X.resolvePreviewUpstreamUrl(Y);if(!J)return K40(404,"sandbox not found");let G=new URL($.url);if(G.pathname.startsWith("/_sandbox"))return K40(404,"not found");let W=`${J.replace(/^http/,"ws")}${G.pathname}${G.search}`,K=$.headers.get("sec-websocket-protocol"),H=K?K.split(",").map((N)=>N.trim()).filter(Boolean):[],F={kind:"preview",upstreamUrl:W,upstreamProtocols:H,pending:[],upstream:null,closed:!1};if(!Z.upgrade($,{data:F}))return K40(426,"upgrade failed");return}function W40($,Z,Q,Y){if(Z.closed)return;Z.closed=!0;try{$.close(Q,Y)}catch{}try{Z.upstream?.close()}catch{}}var Mc6=256,Ic6='<!DOCTYPE html><html><head><meta charset="utf-8"><title>Connecting\u2026</title><style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#fafafa;color:#555}div{text-align:center;max-width:420px;padding:24px}h3{margin:0 0 8px}p{margin:0;font-size:14px;color:#999;line-height:1.5}</style></head><body><div><h3>Connecting to sandbox\u2026</h3><p>Waiting for the sandbox to come online. This page refreshes automatically.</p></div><script>setTimeout(function(){window.location.reload()},1500)</script></body></html>',vc6;var E98=D(()=>{j41();vc6={open($){let Z=$.data;if(!WS0(Z))return;let Q;try{Q=Z.upstreamProtocols.length>0?new WebSocket(Z.upstreamUrl,Z.upstreamProtocols):new WebSocket(Z.upstreamUrl)}catch(Y){console.warn(`[preview-ws] failed to dial upstream ${Z.upstreamUrl}: ${Y instanceof Error?Y.message:String(Y)}`),W40($,Z,1011,"upstream connect failed");return}Q.binaryType="arraybuffer",Z.upstream=Q,Q.addEventListener("open",()=>{while(Z.pending.length>0){let Y=Z.pending.shift();if(Y!==void 0)Q.send(Y)}}),Q.addEventListener("message",(Y)=>{if(Z.closed)return;$.send(Y.data)}),Q.addEventListener("close",(Y)=>{W40($,Z,Y.code||1000,Y.reason||"")}),Q.addEventListener("error",()=>{W40($,Z,1011,"upstream error")})},message($,Z){let Q=$.data;if(!WS0(Q))return;let Y=Q.upstream;if(Y&&Y.readyState===WebSocket.OPEN){Y.send(Z);return}if(Q.pending.length>=Mc6){W40($,Q,1011,"preview ws backlog overflow");return}Q.pending.push(Z)},close($){let Z=$.data;if(!WS0(Z))return;W40($,Z,1000,"")}}});var T98={};M6(T98,{printBanner:()=>xc6,bannerLines:()=>A98,BANNER_LINES:()=>z98,BANNER_GRADIENT:()=>P98});function bc6($){let Z=Number.parseInt($.slice(1),16);return[Z>>16&255,Z>>8&255,Z&255]}function A98($){let Z=z98.map((Q,Y)=>{let[X,J,G]=bc6(P98[Y]);return`\x1B[38;2;${X};${J};${G}m${Q}\x1B[39m`});if($!==void 0)Z.push(`\x1B[2m v${$}\x1B[22m`);return Z}function xc6($){console.log("");for(let Z of A98($))console.log(Z);console.log("")}var z98,P98;var R98=D(()=>{z98=[" \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 "],P98=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"]});D8();var nU1="13";function tU1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:nU1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}D8();import c98 from"pg";var oU1=8314027461559302n,m98=600000,d98=500;async function rU1($,Z){let{databaseUrl:Q,lockTimeoutMs:Y=m98}=$,X=$.log??((K)=>console.log(K)),J=new c98.Client({connectionString:Q});await J.connect();let G=Date.now(),W=!1;try{while(!W){if(W=(await J.query("SELECT pg_try_advisory_lock($1) AS locked",[oU1.toString()])).rows[0]?.locked===!0,W)break;if(Date.now()-G>=Y)throw Error(`Timed out after ${Y}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await i$(d98)}let K=Date.now()-G;if(K>1000)X(`[dbos] waited ${K}ms for the migration lock; another process migrated first`);return await Z()}finally{if(W)try{await J.query("SELECT pg_advisory_unlock($1)",[oU1.toString()])}catch{}await J.end().catch(()=>{})}}F$();jS0();C6();function cZ8(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function xS0($,Z){for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(Y===void 0)continue;if(Y===Z)return $[Q+1];if(Y.startsWith(`${Z}=`))return Y.slice(Z.length+1)}return}function vN1(){let $=cZ8();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:xS0($,"--cpu-prof-dir")??process.cwd(),name:xS0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(xS0($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}gS0();var R40;function cN1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=kE();if(!Q)return;let Y={};try{let{heapStats:X}=await import("bun:jsc"),J=X(),G=Object.entries(J.objectTypeCounts).sort((W,K)=>K[1]-W[1]).slice(0,20);Y={objectCount:J.objectCount,heapSize:J.heapSize,top:Object.fromEntries(G)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:Q.rss,heapUsed:Q.heapUsed,heapTotal:Q.heapTotal,external:Q.external,arrayBuffers:Q.arrayBuffers,...Y}))};return Z().catch(()=>{}),R40=setInterval(()=>void Z().catch(()=>{}),$),R40.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),Y=typeof Q==="string"?Q:JSON.stringify(Q),X=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(X,Y),console.log(JSON.stringify({msg:"heap-snapshot-written",path:X}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(R40)clearInterval(R40)}}import*as iZ8 from"bun:jsc";var{startSamplingProfiler:pZ8,samplingProfilerStackTraces:nZ8}=iZ8;function mN1(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{pZ8()}catch(J){return console.error("[stall-watchdog] failed to start sampling profiler:",J),()=>{}}let Q,Y=performance.now()+Z,X=()=>{let J=performance.now(),G=J-Y;Y=J+Z;let W=[];try{W=nZ8()?.traces??[]}catch{}if(G>$&&W.length>0){let K=new Map;for(let F of W){let U=F.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??F.frames[0];if(!U)continue;let N=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${U.name??"?"} @ ${N}:${U.line??"?"}`;K.set(B,(K.get(B)??0)+1)}let H=[...K.entries()].sort((F,U)=>U[1]-F[1]).slice(0,8).map(([F,U])=>({frame:F,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(G),samplesInWindow:W.length,top:H}))}Q=setTimeout(X,Z),Q.unref?.()};return Q=setTimeout(X,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}function dN1(){vN1();let $=[cN1(),lN1(),mN1()];return()=>{for(let Z of $)Z()}}import{existsSync as mc6}from"fs";var pJ=E0();SN1();var{DBOS:H40,DBOSClient:fc6}=await import("@dbos-inc/dbos-sdk");function uU1($,Z){if(!Z)return $;let Q=new URL($);if(!Q.searchParams.has("sslmode"))Q.searchParams.set("sslmode","verify-full");return Q.toString()}var yc6=[O3,B3,sU,aU,iO,ME],gc6=pJ.dispatchRole==="worker"?yc6:pJ.dispatchRole==="api"?[]:void 0;H40.setConfig(tU1({systemDatabaseUrl:uU1(pJ.databaseUrl,pJ.databasePgSsl),poolSize:pJ.dbosPoolSize,executorID:pJ.podName,listenQueues:gc6}));var{createApp:hc6}=await Promise.resolve().then(() => (N98(),U98)),{isServerPath:uc6}=await Promise.resolve().then(() => (P40(),BN1)),{createAssetHandler:lc6,resolveClientDir:k98}=await Promise.resolve().then(() => (w98(),L98)),cc6=pJ.port,q98=k98(import.meta.url,"../client"),S98=mc6(q98)?q98:k98(import.meta.url,"../dist/client"),dc6=lc6({clientDir:S98,isServerPath:uc6}),ic6={"X-Frame-Options":"DENY","Content-Security-Policy":"frame-ancestors 'none'"};function pc6($){let Z=new Headers($.headers);for(let[Q,Y]of Object.entries(ic6))Z.set(Q,Y);return new Response($.body,{status:$.status,statusText:$.statusText,headers:Z})}var{parsePreviewBaseDomain:nc6,tryHandlePreviewHttp:tc6,tryUpgradePreviewWs:oc6,previewWebSocketHandler:xU1,isPreviewWsData:fU1}=await Promise.resolve().then(() => (E98(),j98)),{getOrInitSharedRunner:C98}=await Promise.resolve().then(() => (QH(),kE$)),_98=nc6(process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN),M98={baseDomain:_98??"",getRunner:C98};if(process.env.STUDIO_SANDBOX_TENANT_POOLS?.trim())C98().catch(($)=>{console.warn("[lifecycle] eager sandbox provider init for tenant pools failed:",$ instanceof Error?$.message:String($))});var KS0=await hc6({clientDir:S98}),yU1=process.env.DBOS_CONDUCTOR_KEY?.trim(),I98=process.env.DBOS_CONDUCTOR_URL?.trim();await rU1({databaseUrl:uU1(pJ.databaseUrl,pJ.databasePgSsl)},()=>H40.launch({...yU1?{conductorKey:yU1}:{},...yU1&&I98?{conductorURL:I98}:{}}));console.log(`[dbos] application version: ${H40.applicationVersion}`);var gU1=5,hU1=0;await g8(async()=>{hU1++;try{return await KS0.initDbos()}catch($){let Z=hU1>=gU1?"giving up":"retrying";throw console.warn(`[dbos] initDbos attempt ${hU1}/${gU1} failed, ${Z}`,$),$}},{maxAttempts:gU1,minTimeout:1000,maxTimeout:1e4,jitter:0.5});if(!pJ.isCli){let{bannerLines:$}=await Promise.resolve().then(() => (R98(),T98));console.log("");for(let Z of $())console.log(Z)}var rc6=Bun.serve({idleTimeout:0,port:cc6,hostname:"0.0.0.0",fetch:async($,Z)=>{if(_98){let Y=await oc6($,Z,M98);if(Y===void 0)return;if(Y)return Y;let X=await tc6($,M98);if(X)return X}let Q=await dc6($);if(Q)return pc6(Q);return KS0.fetch($,{server:Z})},websocket:{open($){if(fU1($.data))xU1.open($)},message($,Z){if(fU1($.data))xU1.message($,Z)},close($){if(fU1($.data))xU1.close($)}},development:!1}),sc6=dN1();if(pJ.localMode)Promise.resolve().then(() => (Zf(),kT0)).then(async({seedLocalMode:$,markSeedComplete:Z,healLocalJwks:Q})=>{try{let Y=await Q();if(Y>0)console.log(`[local-mode] cleared ${Y} undecryptable JWKS key(s); Better Auth will generate a fresh one`);let X=await $()}catch(Y){console.error("Failed to seed local mode:",Y)}finally{Z()}}).catch(async($)=>{console.error("Failed to load local-mode module:",$);try{let{markSeedComplete:Z}=await Promise.resolve().then(() => (Zf(),kT0));Z()}catch{}});var V98=!1;async function ac6($){let Z;try{Z=await fc6.create({systemDatabaseUrl:uU1(pJ.databaseUrl,pJ.databasePgSsl),systemDatabaseSchemaName:"dbos"});let Q=await Z.listWorkflows({status:"PENDING",queueName:B3,executorId:$,loadInput:!1,loadOutput:!1});if(Q.length===0){console.log(`[shutdown] no in-flight thread-gate gates to hand off (executor ${$})`);return}let Y=Q.map((X)=>X.workflowID);await Z.resumeWorkflows(Y,{queueName:B3}),console.log(`[shutdown] re-enqueued ${Y.length} in-flight thread-gate gate(s) for re-adoption by a live executor (from ${$}):`,Y)}catch(Q){console.error("[shutdown] thread-gate handoff failed:",Q)}finally{await Z?.destroy().catch(()=>{})}}async function HS0($){if(V98)return;V98=!0,console.log(`
|
|
3709
3709
|
[shutdown] Received ${$}, shutting down gracefully...`);let Z=Number(process.env.SHUTDOWN_GRACE_SECONDS??60)*1000,Q=Math.max(Z-5000,1e4),Y=setTimeout(()=>{console.error(`[shutdown] Timed out after ${Q}ms, forcing exit.`),process.exit(1)},Q);Y.unref?.();let X=0;try{sc6(),KS0.markShuttingDown();let J=aU1(pJ.dispatchRole,Q,process.env.SHUTDOWN_DRAIN_MS);await i$(J),await rc6.stop(!0);let G=H40.executorID;await H40.shutdown(),await ac6(G),await KS0.shutdown()}catch(J){console.error("[shutdown] Error during shutdown:",J),X=1}clearTimeout(Y),process.exit(X)}process.on("SIGTERM",()=>HS0("SIGTERM"));process.on("SIGINT",()=>HS0("SIGINT"));process.on("SIGHUP",()=>HS0("SIGHUP"));process.on("unhandledRejection",($)=>{console.error("[process] Unhandled rejection:",$)});process.on("uncaughtException",($)=>{console.error("[process] Uncaught exception:",$),HS0("uncaughtException")});
|