decocms 4.429.3 → 4.429.5
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-Dz9cBs-m.js → AlertCircle-CXwWyjWL.js} +1 -1
- package/dist/client/assets/{AreaChart-DdSEp1PD.js → AreaChart-CWnwFPGD.js} +1 -1
- package/dist/client/assets/{ArrowLeft-D7Qv40Uj.js → ArrowLeft-DYnQbYxF.js} +1 -1
- package/dist/client/assets/{ArrowRight-yu2EcGiJ.js → ArrowRight-C4e8QGnK.js} +1 -1
- package/dist/client/assets/{ArrowUp-DfDTdHqA.js → ArrowUp-BiYv-XbK.js} +1 -1
- package/dist/client/assets/{CartesianChart-D64U_nuI.js → CartesianChart-BGE8uJq6.js} +1 -1
- package/dist/client/assets/{Check-D0vo_Hz-.js → Check-C8M8v3vI.js} +1 -1
- package/dist/client/assets/{CheckCircle-CumYT0Xg.js → CheckCircle-jESFBkr7.js} +1 -1
- package/dist/client/assets/{ChevronUp-CtEbEkWq.js → ChevronUp-Q2TBgNib.js} +1 -1
- package/dist/client/assets/{Copy01-BpbowiHW.js → Copy01-CaF9W1F_.js} +1 -1
- package/dist/client/assets/{CreditCard01-D2EcwWI8.js → CreditCard01-Czi8bh9o.js} +1 -1
- package/dist/client/assets/{DotsVertical-EXf2w9q0.js → DotsVertical-DyDeVQCx.js} +1 -1
- package/dist/client/assets/{ErrorBarContext-B8upM3yO.js → ErrorBarContext-D4BkOvp5.js} +1 -1
- package/dist/client/assets/{Image01-BdTgRZP1.js → Image01-CsDdVFAJ.js} +1 -1
- package/dist/client/assets/{Key01-B4eK1DBH.js → Key01-D2FR3CbZ.js} +1 -1
- package/dist/client/assets/{Line-KSe8sJzM.js → Line-BfgHJMc3.js} +1 -1
- package/dist/client/assets/{Link01-By2X_oW1.js → Link01-NjQr5iwv.js} +1 -1
- package/dist/client/assets/{LinkExternal01-CBdG7toR.js → LinkExternal01-CR1925bA.js} +1 -1
- package/dist/client/assets/{Monitor01-B7ACM5ru.js → Monitor01-50nhII2F.js} +1 -1
- package/dist/client/assets/{Palette-DE1SiHuh.js → Palette-AyH3xXYO.js} +1 -1
- package/dist/client/assets/{Plus-BkxlBn4y.js → Plus-DP7AHtKt.js} +1 -1
- package/dist/client/assets/{SearchMd-LHNOznc4.js → SearchMd-D_KPqWqZ.js} +1 -1
- package/dist/client/assets/{Sector-BRrxOLYM.js → Sector-BR7_Ijx1.js} +1 -1
- package/dist/client/assets/{ShoppingBag01-DoxUqYra.js → ShoppingBag01-Dq4UD5Hm.js} +1 -1
- package/dist/client/assets/{Sun-DNDTyIac.js → Sun-oSoDHq1v.js} +1 -1
- package/dist/client/assets/{Tool01-CpVGuPOC.js → Tool01-D2y7RTX1.js} +1 -1
- package/dist/client/assets/{Trash01-TOxKcbID.js → Trash01-64yehlfB.js} +1 -1
- package/dist/client/assets/{Upload01-CjVkZP6G.js → Upload01-BvgQ3r-o.js} +1 -1
- package/dist/client/assets/{User01-DLdS4GEa.js → User01-CU3qbr5s.js} +1 -1
- package/dist/client/assets/{UserSquare-CcCul-Ku.js → UserSquare-nGw6lX43.js} +1 -1
- package/dist/client/assets/{Users01-ByxJpuoo.js → Users01-Lf2fvOej.js} +1 -1
- package/dist/client/assets/{X-Bv_7H4P-.js → X-NPE_cXRR.js} +1 -1
- package/dist/client/assets/{XAxis-Cn9tLjnY.js → XAxis-Drv4sXya.js} +1 -1
- package/dist/client/assets/{XClose-pHmDo5-O.js → XClose-CMTvfCel.js} +1 -1
- package/dist/client/assets/{ZoomOut-Ya7GOVCv.js → ZoomOut-xQj4oorm.js} +1 -1
- package/dist/client/assets/{access-gate-BhPkP25z.js → access-gate-DRBSlBtJ.js} +1 -1
- package/dist/client/assets/add-connection-dialog-DHl4H43e.js +1 -0
- package/dist/client/assets/{agent-analytics-DHc3-l-w.js → agent-analytics-RDv7d0ta.js} +1 -1
- package/dist/client/assets/agent-app-BMOs_YKU.js +1 -0
- package/dist/client/assets/{agent-assets-DAEmoFC8.js → agent-assets-QMTortLS.js} +1 -1
- package/dist/client/assets/{agent-automation-Cz1jsKJf.js → agent-automation-kP7qIZSD.js} +1 -1
- package/dist/client/assets/{agent-automations-EvO0qN6w.js → agent-automations-D5AIE6G6.js} +1 -1
- package/dist/client/assets/{agent-connect-sources-9RNHPk2h.js → agent-connect-sources-1UnRN6mW.js} +1 -1
- package/dist/client/assets/agent-deck-9_2F3EG2.js +1 -0
- package/dist/client/assets/{agent-e2e-CXics08q.js → agent-e2e-DEc1NtfK.js} +1 -1
- package/dist/client/assets/{agent-experiments-CkZQ-REV.js → agent-experiments-D33dFCpI.js} +1 -1
- package/dist/client/assets/{agent-file-CLSI2x6K.js → agent-file-DxlwynYZ.js} +1 -1
- package/dist/client/assets/{agent-git-DR3UCmuP.js → agent-git-DVn4DsKt.js} +1 -1
- package/dist/client/assets/{agent-hosting-BWh6v3V_.js → agent-hosting-CgiR8Ql4.js} +1 -1
- package/dist/client/assets/{agent-icon-BTsAxpiE.js → agent-icon-TQUkqPJj.js} +1 -1
- package/dist/client/assets/agent-library-BoJuDeBh.js +1 -0
- package/dist/client/assets/agent-library-file-Dyz9u3bt.js +1 -0
- package/dist/client/assets/{agent-monitor-DFjCcLUm.js → agent-monitor-DgcF05B9.js} +1 -1
- package/dist/client/assets/{agent-overview-uEke4jgZ.js → agent-overview-dLl0w1eM.js} +1 -1
- package/dist/client/assets/agent-settings-MQLrMTV8.js +1 -0
- package/dist/client/assets/{agent-site-editor-Cs2D0Grt.js → agent-site-editor-ITnkleU1.js} +1 -1
- package/dist/client/assets/agent-site-editor-code-D4dXTr1f.js +2 -0
- package/dist/client/assets/{agent-site-editor-content-Db30XnTN.js → agent-site-editor-content-CNFJoRJD.js} +3 -3
- package/dist/client/assets/{agent-site-editor-preview-CjnIUhh-.js → agent-site-editor-preview-CNLkTYYB.js} +3 -3
- package/dist/client/assets/agent-view-CfCVRWZl.js +1 -0
- package/dist/client/assets/{agent-view-guard-xLwNDoFo.js → agent-view-guard-BbHyaShN.js} +1 -1
- package/dist/client/assets/{agents-list-Bk-nP-Hz.js → agents-list-D9hihWFU.js} +1 -1
- package/dist/client/assets/{ai-providers-Q2xHefD1.js → ai-providers-oyOl9W3y.js} +1 -1
- package/dist/client/assets/{alert-ClVmStz3.js → alert-CokNymqA.js} +1 -1
- package/dist/client/assets/{alert-dialog-Ba4KW5Tb.js → alert-dialog-DeJgSFRZ.js} +1 -1
- package/dist/client/assets/{analytics-sections-sz__W2rJ.js → analytics-sections-DDWh8YnS.js} +1 -1
- package/dist/client/assets/{api-keys-WAwxvH4q.js → api-keys-Ch7q_sOP.js} +1 -1
- package/dist/client/assets/api-keys-DLiRLY55.js +1 -0
- package/dist/client/assets/{app-editor-Bzg858Ei.js → app-editor-BhWLpri1.js} +1 -1
- package/dist/client/assets/{asset-utils-Cl-DIW8f.js → asset-utils-BRk3fUR7.js} +1 -1
- package/dist/client/assets/{auth-LIeEUIDR.js → auth-BNR-bSJO.js} +1 -1
- package/dist/client/assets/{auth-catchall-Ch_Ds6Cn.js → auth-catchall-CJ0eRklU.js} +1 -1
- package/dist/client/assets/{auth-entry-vJGoo3g-.js → auth-entry-XcfUUozZ.js} +1 -1
- package/dist/client/assets/{auth-split-layout-CzKiP8ly.js → auth-split-layout-mYNIGFvp.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-8VvMLeY7.js → authenticate-and-persist-oauth-CZrI0wkU.js} +1 -1
- package/dist/client/assets/{automation-list-row-Wm3a5p7E.js → automation-list-row-DfLOPauj.js} +1 -1
- package/dist/client/assets/{automation-runs-CPD7oJx0.js → automation-runs-RuvSYlk2.js} +1 -1
- package/dist/client/assets/{automations-C7HPgN05.js → automations-CQh_fULy.js} +1 -1
- package/dist/client/assets/{autosend-BnYajEPM.js → autosend-h1h21hnM.js} +1 -1
- package/dist/client/assets/{avatar-DUUKBKEq.js → avatar-UFbMnkmr.js} +1 -1
- package/dist/client/assets/{badge-DzpaGRTk.js → badge-DzTxW-Ts.js} +1 -1
- package/dist/client/assets/{block-document-mfhczLQn.js → block-document-hxIwEIoN.js} +3 -3
- package/dist/client/assets/{blocks-preview-workspace-context-BntOatBH.js → blocks-preview-workspace-context-DRl7lMaq.js} +1 -1
- package/dist/client/assets/{buckets-Cv77xDfH.js → buckets-B-CYwdgC.js} +1 -1
- package/dist/client/assets/{build-improve-prompt-doc-BH3yj16d.js → build-improve-prompt-doc-DNmtsTJk.js} +1 -1
- package/dist/client/assets/{calendar-ByzzyV6c.js → calendar-Bx26MiuJ.js} +1 -1
- package/dist/client/assets/{capability-load-error-DdZhOWh1.js → capability-load-error-BWTOxRLG.js} +1 -1
- package/dist/client/assets/{category-editor-CY9yp7vC.js → category-editor-DjdC64aL.js} +1 -1
- package/dist/client/assets/{chart-_tBRgksg.js → chart-BxpZzVsr.js} +1 -1
- package/dist/client/assets/{chat-context-BI1s3T66.js → chat-context-DppIIhzA.js} +1 -1
- package/dist/client/assets/{chat-draft-D0PL2mCh.js → chat-draft-DiJpqitX.js} +1 -1
- package/dist/client/assets/{checkbox-Cpv7L0N6.js → checkbox-BGfnFNv1.js} +1 -1
- package/dist/client/assets/{choose-editor-LNwLyfg_.js → choose-editor-DHwWSJiW.js} +1 -1
- package/dist/client/assets/{claim-phase-copy-EPhExNlM.js → claim-phase-copy-BRgB3yX1.js} +1 -1
- package/dist/client/assets/{cli-auth-success-CBcItsza.js → cli-auth-success-BX3DQOO5.js} +1 -1
- package/dist/client/assets/{client-icons-DC-8hNpP.js → client-icons-CYZ83j__.js} +1 -1
- package/dist/client/assets/{collapsible-pPCznIf4.js → collapsible-C2j127TD.js} +1 -1
- package/dist/client/assets/{collection-detail-D_X4bBB3.js → collection-detail-ehNX3PLY.js} +1 -1
- package/dist/client/assets/{collection-display-button-B5I1d5Uv.js → collection-display-button-CwIm419d.js} +1 -1
- package/dist/client/assets/{collection-search-Be-n29of.js → collection-search-D_azi8Gq.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-D52zfTjc.js → collection-table-wrapper-DMU9yWMT.js} +1 -1
- package/dist/client/assets/{collection-tabs-fftcEeJN.js → collection-tabs-C6N84gCC.js} +1 -1
- package/dist/client/assets/{combobox-B1AZk18o.js → combobox--XWfS5lw.js} +1 -1
- package/dist/client/assets/{command-DQBtHyyq.js → command-D1RoIxg2.js} +1 -1
- package/dist/client/assets/{companion-mcps-section-7Vm6IlF1.js → companion-mcps-section-Cs-LBxQr.js} +1 -1
- package/dist/client/assets/{config-CELJkL0z.js → config-CMMAnMUF.js} +1 -1
- package/dist/client/assets/{connect-CqRFxjYq.js → connect-DVE1Hnuy.js} +1 -1
- package/dist/client/assets/{connect-layout-XKXgqJNp.js → connect-layout--NwWaqYw.js} +1 -1
- package/dist/client/assets/{connection-Cd9kpW2N.js → connection-Ds6vwkGM.js} +1 -1
- package/dist/client/assets/{connection-card-C_b6Kn3i.js → connection-card-BPKFHpho.js} +1 -1
- package/dist/client/assets/{connection-detail-Bi6mvLNo.js → connection-detail-BroJMnyc.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-CRij5u84.js → connection-form-helpers-C4OB4j_3.js} +1 -1
- package/dist/client/assets/{connections-HYiawKCj.js → connections-DG2GlCvy.js} +1 -1
- package/dist/client/assets/{context-BkyYtq6r.js → context-BL1LKuLQ.js} +1 -1
- package/dist/client/assets/{context-menu-B6lNE0Gz.js → context-menu-CBJP1RfU.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-CAvO4TWV.js → create-organization-dialog-BQ0I0t_j.js} +1 -1
- package/dist/client/assets/{daily-pulse-BYmWzKWl.js → daily-pulse-Dpp9pCbq.js} +1 -1
- package/dist/client/assets/{decopilot-Cb-_oMnP.js → decopilot-BRlhj2Gw.js} +1 -1
- package/dist/client/assets/{dialog-CGclnAkN.js → dialog-Mg_Z3ES1.js} +1 -1
- package/dist/client/assets/{discover-De-KJC5j.js → discover-DCHf1gBE.js} +1 -1
- package/dist/client/assets/{domain-settings-DrGUovmZ.js → domain-settings-CmoTC2Mj.js} +1 -1
- package/dist/client/assets/{download-app-dialog-D1557QUF.js → download-app-dialog-B7zcmkcH.js} +1 -1
- package/dist/client/assets/{drawer-BDoe-caH.js → drawer-BIoKJwCW.js} +1 -1
- package/dist/client/assets/{editor-BJgmcO1D.js → editor-JpZ1gWwV.js} +1 -1
- package/dist/client/assets/{empty-state-B18ltfc_.js → empty-state-BayRP7H4.js} +1 -1
- package/dist/client/assets/{empty-state-B34CEwUC.js → empty-state-BmztM-Bo.js} +1 -1
- package/dist/client/assets/{extract-connection-data-CGsWt1C2.js → extract-connection-data-D5wjQBt3.js} +1 -1
- package/dist/client/assets/{feature-gate-DYu08LcP.js → feature-gate-DvQXfI5S.js} +1 -1
- package/dist/client/assets/{feature-paywall-C_x6v-Ey.js → feature-paywall-sc2LtOXc.js} +1 -1
- package/dist/client/assets/{file-explorer-DFkQYLLD.js → file-explorer-CqjD-skS.js} +1 -1
- package/dist/client/assets/{file-preview-oOFgi0tu.js → file-preview-VfWoS2gk.js} +1 -1
- package/dist/client/assets/{file-share-button-zWuRzlor.js → file-share-button-BGOzbmtb.js} +1 -1
- package/dist/client/assets/{file-type-icon-RYJiailm.js → file-type-icon-BhiPdwxi.js} +1 -1
- package/dist/client/assets/flat-project-wkNYEFlO.js +1 -0
- package/dist/client/assets/{folder-icon-Bf8F6949.js → folder-icon-DBIJdeY7.js} +1 -1
- package/dist/client/assets/{form-bcXKqc8N.js → form-BgAERq-t.js} +1 -1
- package/dist/client/assets/{gateway-client-DCdFKKN_.js → gateway-client-CIbTMjGx.js} +1 -1
- package/dist/client/assets/{general-16qHlqcQ.js → general-BBuB4XlH.js} +1 -1
- package/dist/client/assets/{home-D781nRhS.js → home-C96-FMPc.js} +1 -1
- package/dist/client/assets/{icon-button-CIiTk2PX.js → icon-button-CWL5E4Ua.js} +1 -1
- package/dist/client/assets/{index-CvEB1wsJ.js → index-2-Z1VD2F.js} +1 -1
- package/dist/client/assets/{index-Bw3BnaKs.js → index-B0WfPFpv.js} +1 -1
- package/dist/client/assets/{index-D9LnhQDL.js → index-B9dD9jj0.js} +4 -4
- package/dist/client/assets/{index-CrqZGA61.js → index-BZOsa8jC.js} +1 -1
- package/dist/client/assets/{index-59z4bzDc.js → index-Bv71AEH5.js} +1 -1
- package/dist/client/assets/{index-bzuuux9r.js → index-CORXJXSN.js} +1 -1
- package/dist/client/assets/{index-Czf46ykC.js → index-CpszPQp_.js} +1 -1
- package/dist/client/assets/{index-BS2Uqa0H.js → index-DL-sDqTO.js} +1 -1
- package/dist/client/assets/{index-DMU-WXJw.js → index-DR9ob9os.js} +1 -1
- package/dist/client/assets/{index---Q5zO6x.js → index-DWe-6mCD.js} +1 -1
- package/dist/client/assets/{index-DAh-d37k.js → index-ROw_u5-U.js} +1 -1
- package/dist/client/assets/{index-BouVTFfo.js → index-RYaP6qX3.js} +3 -3
- package/dist/client/assets/{index-D9sHyQVv.js → index-r8TBLtcZ.js} +1 -1
- package/dist/client/assets/{index-redirect-DVgM6RRC.js → index-redirect-DN5m0MeF.js} +1 -1
- package/dist/client/assets/{index-DiqXHSnv.js → index-v5QvptSB.js} +1 -1
- package/dist/client/assets/{index-BScbcffF.js → index-vYawqXRD.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-BHgtnfJm.js → infiniteQueryObserver-Ex2lNjjr.js} +1 -1
- package/dist/client/assets/{infra-billing-Ce7lPCaU.js → infra-billing-BvYXN3Z1.js} +1 -1
- package/dist/client/assets/{input-DANvmr7V.js → input-BZloVZ72.js} +3 -3
- package/dist/client/assets/{input-DGRfwNJU.js → input-BmzPGvUi.js} +1 -1
- package/dist/client/assets/{input-D_ZVa75L.js → input-Cndqm_5O.js} +1 -1
- package/dist/client/assets/{integration-icon-COxNT19S.js → integration-icon-C5NBXdpz.js} +1 -1
- package/dist/client/assets/{label-DiLYcWOq.js → label-DpahMcEo.js} +1 -1
- package/dist/client/assets/{last-preview-page-3TpsD5I_.js → last-preview-page-Dfux_ulA.js} +1 -1
- package/dist/client/assets/{layout-DPfFiV1_.js → layout-C6k3EFd1.js} +1 -1
- package/dist/client/assets/{legacy-agents-deep-yBBdl4Te.js → legacy-agents-deep-B_DiKZ0c.js} +1 -1
- package/dist/client/assets/{legacy-main-redirect-DXVMcdr-.js → legacy-main-redirect-BgIGaynA.js} +1 -1
- package/dist/client/assets/library-D6flTj5t.js +1 -0
- package/dist/client/assets/{library-tab-CXCLZRQC.js → library-tab-Bso2C2NG.js} +1 -1
- package/dist/client/assets/{login-C4QrpT-9.js → login-CXuSqosI.js} +1 -1
- package/dist/client/assets/{markdown-CYbDwdl9.js → markdown-D8U5yexH.js} +1 -1
- package/dist/client/assets/{mcp-app-renderer-CqnN_gT7.js → mcp-app-renderer-CWOIFfi6.js} +1 -1
- package/dist/client/assets/{mcp-oauth-Bx2SR9KP.js → mcp-oauth-DCDrWVc0.js} +1 -1
- package/dist/client/assets/{members-BZBvmhnB.js → members-BfRC0ceX.js} +1 -1
- package/dist/client/assets/{message-templates-I2fytmn2.js → message-templates-DgOMle6a.js} +1 -1
- package/dist/client/assets/{mini-report-page-eltvP_76.js → mini-report-page-BIktJNbh.js} +1 -1
- package/dist/client/assets/{mock-board-CgZiTliz.js → mock-board-DjQ6xrU_.js} +1 -1
- package/dist/client/assets/{monaco-editor-FD1izitZ.js → monaco-editor-BRUSLTLk.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-BQCERodS.js → monitoring-stats-row-C4bB2YFf.js} +1 -1
- package/dist/client/assets/{multi-select-BfQySwLK.js → multi-select-6bm7qEEn.js} +1 -1
- package/dist/client/assets/{mustache-Di_1lUk9.js → mustache-CAmcva4T.js} +1 -1
- package/dist/client/assets/new-project-dialog-BejzbVG2.js +1 -0
- package/dist/client/assets/{oauth-callback-DKQfywQG.js → oauth-callback-0bxicPCo.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-BHBlU05u.js → oauth-callback-ai-provider-D4kx59om.js} +1 -1
- package/dist/client/assets/{onboarding-ByVxEqxG.js → onboarding-C7mIZXvc.js} +1 -1
- package/dist/client/assets/{openai-conversation-TGydZ30W.js → openai-conversation-DYPzWsQc.js} +1 -1
- package/dist/client/assets/{optimistic-project-sidebar-views-2cxR9DkL.js → optimistic-project-sidebar-views-DHo7EiTm.js} +1 -1
- package/dist/client/assets/{org-file-open-context-BZYS0LJs.js → org-file-open-context-CSDcMwBD.js} +1 -1
- package/dist/client/assets/{organization-choice-BqUqcpt3.js → organization-choice-BZ-4C5a6.js} +1 -1
- package/dist/client/assets/{orgs-BmaONpkl.js → orgs-DnEd_o3Y.js} +1 -1
- package/dist/client/assets/{page-seo-form-ChmpTY6H.js → page-seo-form-BjAunJ7T.js} +1 -1
- package/dist/client/assets/{pair-DGI5fx0e.js → pair-o8Pcow3m.js} +1 -1
- package/dist/client/assets/{plan-ladder-X8Zj9SaM.js → plan-ladder-COYrpP9N.js} +1 -1
- package/dist/client/assets/{popover-qQDOtUT-.js → popover-D5s3M61L.js} +1 -1
- package/dist/client/assets/{post-calendar-B8almCuR.js → post-calendar-Cl-vAwk3.js} +1 -1
- package/dist/client/assets/post-editor-D2HU9kfD.js +2 -0
- package/dist/client/assets/{preview-content-Dyu5DkV0.js → preview-content-B9bgsNRh.js} +1 -1
- package/dist/client/assets/{preview-dialog-CtBqa24y.js → preview-dialog-CwQ43Y6v.js} +1 -1
- package/dist/client/assets/{profile-L1-N4m6i.js → profile-BB1G47uY.js} +1 -1
- package/dist/client/assets/{project-app-view-ClwBU9Qs.js → project-app-view-DS-jWTJh.js} +1 -1
- package/dist/client/assets/{project-feed-Crh26cH9.js → project-feed-Ceha3l-R.js} +1 -1
- package/dist/client/assets/{project-icon-C4nL4fZk.js → project-icon-CmV-Y1UZ.js} +1 -1
- package/dist/client/assets/project-reports-M4OcQRnq.js +1 -0
- package/dist/client/assets/project-tasks-D2UK5JuX.js +1 -0
- package/dist/client/assets/{projects-BSybKzWl.js → projects-Cv5osXsD.js} +1 -1
- package/dist/client/assets/{projects-empty-state-Bk1XoaJn.js → projects-empty-state-CaTjevnb.js} +1 -1
- package/dist/client/assets/{prompts-5ReZRdb6.js → prompts-BgUtk3zC.js} +1 -1
- package/dist/client/assets/record-editor-C0G9mTGj.js +1 -0
- package/dist/client/assets/{redirect-editor-Bp56flLw.js → redirect-editor-BpclUTIj.js} +1 -1
- package/dist/client/assets/{reports-9unH-pwd.js → reports-CLznlgS5.js} +1 -1
- package/dist/client/assets/reports-cbjIbfxK.js +1 -0
- package/dist/client/assets/{reports-onboarding-Bd3z6EGO.js → reports-onboarding-BHCXUocU.js} +1 -1
- package/dist/client/assets/{reports-tab-CR2TjCBy.js → reports-tab-CoZHZlVb.js} +2 -2
- package/dist/client/assets/{repositories-CflRXNfG.js → repositories-DoauYKeu.js} +1 -1
- package/dist/client/assets/{repository-binding-5QFpfewx.js → repository-binding-DzrKIMc8.js} +1 -1
- package/dist/client/assets/{repository-import-picker-B2sU66dU.js → repository-import-picker-CVP1mN_O.js} +1 -1
- package/dist/client/assets/{repository-picker-Vcv9BzsE.js → repository-picker-BIkrH86Z.js} +1 -1
- package/dist/client/assets/{require-capability-BW3G4Us3.js → require-capability-CEGMzsiO.js} +1 -1
- package/dist/client/assets/{required-auth-layout-CD9nIPTu.js → required-auth-layout-BPzqc-yZ.js} +1 -1
- package/dist/client/assets/{reset-password-D1RRMRVB.js → reset-password-CC9lxhEO.js} +1 -1
- package/dist/client/assets/{resizable-D9vEsnsF.js → resizable-Ck9CN4S9.js} +1 -1
- package/dist/client/assets/{resolve-tab-icon-B5IDCHgC.js → resolve-tab-icon-CgOUF0YA.js} +1 -1
- package/dist/client/assets/{review-settings-BrevH4Wn.js → review-settings-cCLUF68J.js} +1 -1
- package/dist/client/assets/{rich-text-link-control-BzuTiJzL.js → rich-text-link-control-RS2mJIfp.js} +1 -1
- package/dist/client/assets/{roles-DJw04POK.js → roles-DWD7cz1d.js} +1 -1
- package/dist/client/assets/{route-Crbe3P1G.js → route-CjKIfVgB.js} +1 -1
- package/dist/client/assets/{route-oyHhMnH0.js → route-DI4K2hiz.js} +1 -1
- package/dist/client/assets/route-n8gaWLVb.js +1 -0
- package/dist/client/assets/{runnable-block-editor-Dm1ttguK.js → runnable-block-editor-h-xGxUBS.js} +1 -1
- package/dist/client/assets/{sandbox-lifecycle-context-B7U4JGhb.js → sandbox-lifecycle-context-OPdARg4I.js} +1 -1
- package/dist/client/assets/{schema-D-otOqEn.js → schema-BejaMrNT.js} +1 -1
- package/dist/client/assets/{scroll-area-BWPHSxC7.js → scroll-area-DjfgE2jb.js} +1 -1
- package/dist/client/assets/{search-input-CpX3lkQR.js → search-input-DviARBm2.js} +1 -1
- package/dist/client/assets/{search-toggle-HqLOjE33.js → search-toggle-DvOTtKmA.js} +1 -1
- package/dist/client/assets/{secret-picker-C3zHxvuV.js → secret-picker-CuEw2DSI.js} +1 -1
- package/dist/client/assets/{secrets-B2qQxKlO.js → secrets-CoVAIKwE.js} +1 -1
- package/dist/client/assets/{sections-editor-DD2nj5mI.js → sections-editor-CsNiIfgn.js} +1 -1
- package/dist/client/assets/{select-C2txP07f.js → select-Cd1ykg-h.js} +1 -1
- package/dist/client/assets/{select-model-DHlaKKMM.js → select-model-a344Xqu_.js} +1 -1
- package/dist/client/assets/{seo-editor-De017z1l.js → seo-editor-D4_b59uB.js} +1 -1
- package/dist/client/assets/{separator--5K9h2sI.js → separator-Ch977YA1.js} +1 -1
- package/dist/client/assets/{settings-tab-Cl0o9K4e.js → settings-tab-sWmscvB1.js} +1 -1
- package/dist/client/assets/{sheet-B12cZ7x2.js → sheet-lggFYx6M.js} +1 -1
- package/dist/client/assets/shell-layout-Bl8of89A.js +1 -0
- package/dist/client/assets/{skills-8pBxw9bR.js → skills-CzJ783Zp.js} +1 -1
- package/dist/client/assets/{sso-TN5MAp8K.js → sso-DKlO8_Lq.js} +1 -1
- package/dist/client/assets/{suggestion-NZIrFsLR.js → suggestion-K--t6EP5.js} +1 -1
- package/dist/client/assets/{switch-Bwf4p87L.js → switch-BLWgY1pz.js} +1 -1
- package/dist/client/assets/{synced-repos-DLmz0NmT.js → synced-repos-BnWEHPVF.js} +1 -1
- package/dist/client/assets/{tab-icon-glyph-DH47_x1a.js → tab-icon-glyph-C_bZ6WrZ.js} +1 -1
- package/dist/client/assets/{table-lla-0ZP_.js → table-CufJwyXQ.js} +1 -1
- package/dist/client/assets/{tabs-Cqnx8A4d.js → tabs-C1zPDoUI.js} +1 -1
- package/dist/client/assets/{task-board-ECBN5WTV.js → task-board-DlEJAtdm.js} +1 -1
- package/dist/client/assets/{task-route-BDq4YcnG.js → task-route-z_uMrYh2.js} +1 -1
- package/dist/client/assets/{task-status-CnOLwVKV.js → task-status-DrVr4O9O.js} +1 -1
- package/dist/client/assets/{taskboard-analytics-uCDwsGG2.js → taskboard-analytics-BEIixlIh.js} +1 -1
- package/dist/client/assets/{tasks-BX0Q_hE9.js → tasks-CpEABx-G.js} +1 -1
- package/dist/client/assets/tasks-l5i1Y6YC.js +1 -0
- package/dist/client/assets/{textarea-D-mcJV9e.js → textarea-r66bOcCD.js} +1 -1
- package/dist/client/assets/{thread-analytics-DDKoGJv6.js → thread-analytics-BmowQF8I.js} +1 -1
- package/dist/client/assets/{thread-intent-CUdr-H41.js → thread-intent-UQGFcX_y.js} +1 -1
- package/dist/client/assets/{thread-route-BWPYI0ZR.js → thread-route-CVz2UKe8.js} +1 -1
- package/dist/client/assets/{thread-route-Dxs07flR.js → thread-route-CowkfwAl.js} +1 -1
- package/dist/client/assets/{thread-sheet-body-BAKNbMRN.js → thread-sheet-body-CxW1uZ8Z.js} +1 -1
- package/dist/client/assets/{toggle-group-C9SgUNwy.js → toggle-group-BQtHqwCK.js} +1 -1
- package/dist/client/assets/{toolbar-icon-button-DWT7n987.js → toolbar-icon-button-B4QTn-IO.js} +1 -1
- package/dist/client/assets/{tooltip-C-B-WE46.js → tooltip-CM3YyNDC.js} +1 -1
- package/dist/client/assets/{track-D7y9daDt.js → track-BqJ0I7ao.js} +1 -1
- package/dist/client/assets/{types-CJIIzGfz.js → types-DyM6In73.js} +1 -1
- package/dist/client/assets/{usage-stats-H19WpNRU.js → usage-stats-5Vc6zWOp.js} +1 -1
- package/dist/client/assets/{use-ai-providers-DKskI-lk.js → use-ai-providers-C98JaJAU.js} +1 -1
- package/dist/client/assets/{use-automations-Cx0j7Q3N.js → use-automations-CqbCGltu.js} +1 -1
- package/dist/client/assets/{use-autosave-CHQrnT-o.js → use-autosave-tzZy_E8d.js} +1 -1
- package/dist/client/assets/{use-chat-layout-state-BjAQ-jEe.js → use-chat-layout-state-BfZJHnkW.js} +1 -1
- package/dist/client/assets/{use-connect-companion-BqzewW5u.js → use-connect-companion-DfiphJ3V.js} +1 -1
- package/dist/client/assets/{use-connection-DHC7ikhv.js → use-connection-BdSGHKJK.js} +1 -1
- package/dist/client/assets/{use-copy-CdZ1BFua.js → use-copy-CiP5Vy7i.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-CPtrtZAW.js → use-create-virtual-mcp-CoU2LYN8.js} +1 -1
- package/dist/client/assets/{use-date-fns-locale-B7kL8ljG.js → use-date-fns-locale-BQIR67dY.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-CYhKiUyc.js → use-debounced-autosave-6IETzqNZ.js} +1 -1
- package/dist/client/assets/{use-debounced-value-CiGe63CI.js → use-debounced-value-DCYhoWzs.js} +1 -1
- package/dist/client/assets/{use-deco-credits-Cte4t6Hc.js → use-deco-credits-x58AfrXU.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-DRNQZQd4.js → use-decopilot-events-BZQXzmAo.js} +1 -1
- package/dist/client/assets/{use-delete-connection-B7AFWvdy.js → use-delete-connection-CzvLG4mr.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-DLIzcPao.js → use-deployment-admin-BmH0eskZ.js} +1 -1
- package/dist/client/assets/{use-fast-preview-draft-url-xQxrekFA.js → use-fast-preview-draft-url-DFL8djh0.js} +1 -1
- package/dist/client/assets/{use-file-configs-Dgw51am7.js → use-file-configs-DRP3Y7X_.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-C8OfQLMA.js → use-infinite-scroll-BjVQV3DR.js} +1 -1
- package/dist/client/assets/{use-join-requests-nZ3kOzHD.js → use-join-requests-B6dqmlCQ.js} +1 -1
- package/dist/client/assets/{use-main-panel-tabs-DxwYJrDB.js → use-main-panel-tabs-sy9nYCqA.js} +1 -1
- package/dist/client/assets/{use-mcp-auth-status-CcDs9GVg.js → use-mcp-auth-status-Cjd2QrWU.js} +1 -1
- package/dist/client/assets/{use-mcp-client-DwI8A7i_.js → use-mcp-client-CqsHeShn.js} +1 -1
- package/dist/client/assets/{use-mcp-prompts-DldVoJeZ.js → use-mcp-prompts-D2YpCb1K.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-CfhB5gVo.js → use-mcp-tools-CHvaFbLg.js} +1 -1
- package/dist/client/assets/{use-members-C0vxrdj1.js → use-members-BIhBY7mT.js} +1 -1
- package/dist/client/assets/{use-mobile-Bl8tDUow.js → use-mobile-3MM_rw4D.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-BkimVMTW.js → use-navigate-to-agent-PjEm7mol.js} +1 -1
- package/dist/client/assets/use-new-blocks-editor-BAZ5qlTk.js +1 -0
- package/dist/client/assets/{use-open-billing-url-C6UjE84T.js → use-open-billing-url-CVEaCqtR.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-DveZle8A.js → use-org-auth-client-DM3Q5_fm.js} +1 -1
- package/dist/client/assets/{use-org-fs-BgFAHUUb.js → use-org-fs-DazA0BMP.js} +1 -1
- package/dist/client/assets/{use-org-repo-syncs-EVtNPamp.js → use-org-repo-syncs-DGjVBBAK.js} +1 -1
- package/dist/client/assets/{use-org-sso-BliqnW_C.js → use-org-sso-DGy0uwEN.js} +1 -1
- package/dist/client/assets/{use-organization-roles-Bapbgw8R.js → use-organization-roles-Bjw-G0xx.js} +1 -1
- package/dist/client/assets/{use-organization-settings-Cwt51JJ-.js → use-organization-settings-DbPbYeMx.js} +1 -1
- package/dist/client/assets/{use-panel-navigate-Bs3wrk2o.js → use-panel-navigate-DH6_TAsx.js} +1 -1
- package/dist/client/assets/{use-project-scope-B0guFEKE.js → use-project-scope-Bgnjdhs7.js} +1 -1
- package/dist/client/assets/{use-releases-ktnIEIhq.js → use-releases-DQGDjOy5.js} +1 -1
- package/dist/client/assets/{use-reports-diagnostic-D3V-85up.js → use-reports-diagnostic-BASyyQU9.js} +1 -1
- package/dist/client/assets/{use-secrets-BkecMwUf.js → use-secrets-B41nk4LH.js} +1 -1
- package/dist/client/assets/{use-section-preview-base-Cx_Jy896.js → use-section-preview-base-DKahorN-.js} +1 -1
- package/dist/client/assets/{use-session-runtime-DePI4bwj.js → use-session-runtime-CsLaMszW.js} +1 -1
- package/dist/client/assets/{use-tags-oLoiyIWO.js → use-tags-BQ9peM4A.js} +1 -1
- package/dist/client/assets/{use-task-board-analytics-Cb5Wgr40.js → use-task-board-analytics-Co6FjpoI.js} +1 -1
- package/dist/client/assets/{use-task-board-events-Dh62k4Ty.js → use-task-board-events-BsviWCWn.js} +1 -1
- package/dist/client/assets/{use-task-metadata-w1PI2EXQ.js → use-task-metadata-DvgRil5z.js} +1 -1
- package/dist/client/assets/{use-thread-analytics-lgnAQ6CS.js → use-thread-analytics-Bf4bUeLT.js} +1 -1
- package/dist/client/assets/{use-thread-outputs-C-Wf6OBJ.js → use-thread-outputs-CvWfZHjR.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-TQWsreUe.js +1 -0
- package/dist/client/assets/{useQueries-Bp03xGbc.js → useQueries-CIVnwtOu.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-DMyZCSsI.js +1 -0
- package/dist/client/assets/{users-BhXTEA2Q.js → users-2Adoo8D9.js} +1 -1
- package/dist/client/assets/{utils-DLvRHMkE.js → utils-BeoNvR__.js} +1 -1
- package/dist/client/assets/{variant-calendar-dnPy16Uh.js → variant-calendar-C6HvphcB.js} +1 -1
- package/dist/client/assets/{variant-matcher-override-Ck-W94Rw.js → variant-matcher-override-De1zsqbc.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-B0zbI0V1.js → view-mode-toggle-DtqPFP6s.js} +1 -1
- package/dist/client/assets/{virtual-mcp-CXOm_lWW.js → virtual-mcp-Cr9A-Wo0.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +4 -4
- package/dist/server/server.js +4 -4
- package/package.json +1 -1
- package/dist/client/assets/add-connection-dialog-CMIKgpSn.js +0 -1
- package/dist/client/assets/agent-app-DvbjKuoc.js +0 -1
- package/dist/client/assets/agent-deck-BOkkFgcN.js +0 -1
- package/dist/client/assets/agent-library-C1r0MXrh.js +0 -1
- package/dist/client/assets/agent-library-file-D5IDjKQA.js +0 -1
- package/dist/client/assets/agent-settings-AbY4U8u3.js +0 -1
- package/dist/client/assets/agent-site-editor-code-bJU2jCGA.js +0 -2
- package/dist/client/assets/agent-view-DS1snkTk.js +0 -1
- package/dist/client/assets/api-keys-ttV9p_C3.js +0 -1
- package/dist/client/assets/flat-project-5lJIGqGg.js +0 -1
- package/dist/client/assets/library-BetPT5Rc.js +0 -1
- package/dist/client/assets/new-project-dialog-BJabJxXa.js +0 -1
- package/dist/client/assets/post-editor-3AfRGsBD.js +0 -2
- package/dist/client/assets/project-reports--pld6WR0.js +0 -1
- package/dist/client/assets/project-tasks-DOClEfO3.js +0 -1
- package/dist/client/assets/record-editor-Cz6r4s_z.js +0 -1
- package/dist/client/assets/reports-Cs6RnnEs.js +0 -1
- package/dist/client/assets/route-B0zINpnC.js +0 -1
- package/dist/client/assets/shell-layout-jXhY2XCJ.js +0 -1
- package/dist/client/assets/tasks-FILO35tu.js +0 -1
- package/dist/client/assets/use-new-blocks-editor-Bg78S2yh.js +0 -1
- package/dist/client/assets/useInfiniteQuery-CkfME6EV.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-Cb-DHagn.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -2178,7 +2178,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var PZ$=L(()=>{uu()});f
|
|
|
2178
2178
|
`.execute($);if(Number(K.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${G}/${W}, keeping in old table`);continue}}await Bc`
|
|
2179
2179
|
DELETE FROM kysely_migration WHERE name = ${Q}
|
|
2180
2180
|
`.execute($)}}async function KG$($){await HO4($),await FO4($);let Z=new GG$({db:$,provider:{getMigrations:()=>Promise.resolve(i81)}}),{error:Q,results:X}=await Z.migrateToLatest(),Y=0;if(X?.forEach((J)=>{if(J.status==="Success")Y++;else if(J.status==="Error")console.error(`Failed to execute migration "${J.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q;return Y}async function UO4($){let{keepOpen:Z=!1,database:Q,skipBetterAuth:X=!1}=$??{},Y="skipped";if(!X&&!Q)Y=await ns0();let J=Q??Z8(),G=async()=>{if(!Z&&!Q)await xj(J).catch((W)=>{console.warn("Warning: Error closing database:",W)})};try{let W=await KG$(J.db);return await G(),{betterAuth:Y,kysely:W}}catch(W){throw await G(),W}}async function NO4(){let $=Z8(),Z=new GG$({db:$.db,provider:{getMigrations:()=>Promise.resolve(i81)}}),{error:Q,results:X}=await Z.migrateDown();if(X?.forEach((Y)=>{if(Y.status==="Success")console.log(`\u2705 Migration "${Y.migrationName}" rolled back successfully`);else if(Y.status==="Error")console.error(`\u274C Failed to rollback migration "${Y.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}var FG$=L(()=>{JG$();ts0();bQ()});async function KK0($){let Z={...process.env},Q=aQ0($,Z);console.log(A_1(Q.settings.encryptionKey));let X=Q.settings.betterAuthSecret||(Q.settings.localMode?e7$(Q.settings.dataDir):""),{ensureServices:Y}=await Promise.resolve().then(() => (KW0(),WW0)),{outputs:J,services:G}=await Y({home:Q.settings.dataDir,externalDatabaseUrl:Q.externalDatabaseUrl,externalNatsUrl:Q.externalNatsUrl});if(!Q.skipMigrations){let{migrateBetterAuth:K}=await Promise.resolve().then(() => (ts0(),ZQ$));await K(J.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (bQ(),j7$)),{migrateToLatest:F}=await Promise.resolve().then(() => (FG$(),HG$)),U=H(J.databaseUrl);await F({keepOpen:!0,database:U,skipBetterAuth:!0})}let W={...Q.settings,betterAuthSecret:X,databaseUrl:J.databaseUrl,natsUrls:J.natsUrls,...J.s3?{s3Endpoint:J.s3.endpoint,s3Bucket:J.s3.bucket,s3AccessKeyId:J.s3.accessKeyId,s3SecretAccessKey:J.s3.secretAccessKey,s3ForcePathStyle:J.s3.forcePathStyle}:{}};return TZ$(W),{settings:W,services:G.map((K)=>({name:K.name==="PostgreSQL"?"Postgres":K.name,port:K.port})),managedServiceNames:G.filter((K)=>K.owner==="managed").map((K)=>K.name)}}var p81=L(()=>{uu();$Q$();X$()});var LG$={};J0(LG$,{updateService:()=>YT,subscribeCliState:()=>o81,setTuiConsoleIntercepted:()=>HK0,setServerUrl:()=>Rs,setMigrationsDone:()=>As,setDevMode:()=>LO4,resetCliStateForTests:()=>BO4,isTuiConsoleIntercepted:()=>FK0,getCliState:()=>t81,addLogEntry:()=>uj});function UG$(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function NG$(){return{services:UG$(),migrationsStatus:"pending",serverUrl:null,logs:[]}}function BO4(){CJ=NG$()}function Ts(){for(let $ of n81)$()}function t81(){return CJ}function o81($){return n81.add($),()=>n81.delete($)}function YT($){CJ={...CJ,services:CJ.services.map((Z)=>Z.name===$.name?$:Z)},Ts()}function As(){CJ={...CJ,migrationsStatus:"done"},Ts()}function Rs($){CJ={...CJ,serverUrl:$},Ts()}function uj($){let Z=[...CJ.logs,$];CJ={...CJ,logs:Z.length>500?Z.slice(-500):Z},Ts()}function LO4(){CJ={...CJ,services:[...UG$(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},Ts()}function HK0($){BG$=$}function FK0(){return BG$}var CJ,n81,BG$=!1;var JT=L(()=>{CJ=NG$();n81=new Set});import{createServer as DG$}from"net";function DO4($){return new Promise((Z)=>{let Q=DG$();Q.once("error",()=>Z(!1)),Q.listen($,"0.0.0.0",()=>{Q.close(()=>Z(!0))})})}async function qs($){if(await DO4($))return $;let Z=await new Promise((Q,X)=>{let Y=DG$();Y.once("error",X),Y.listen(0,"0.0.0.0",()=>{let J=Y.address(),G=typeof J==="object"&&J?J.port:0;Y.close(()=>Q(G))})});return console.warn(`Port ${$} is in use, using port ${Z} instead.`),Z}var a81=()=>{};var s81={};J0(s81,{startDevServer:()=>jO4,pipeToLogStore:()=>r81});import{join as OO4}from"path";function r81($){let Z=$.getReader(),Q=new TextDecoder,X="";function Y(){let J=X.split(`
|
|
2181
|
-
`);X=J.pop()??"";for(let G of J){let W=Bun.stripANSI(G).replace(/^\[\d+\]\s*/,"").trim();if(!W)continue;uj({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}}(async()=>{try{for(;;){let{done:J,value:G}=await Z.read();if(J)break;X+=Q.decode(G,{stream:!0}),Y()}}catch{}if(X.trim()){let J=Bun.stripANSI(X).replace(/^\[\d+\]\s*/,"").trim();if(J)uj({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:J})}})()}async function jO4($){let{baseUrl:Z,noTui:Q}=$,X=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=X?process.env.PORT:$.vitePort,J=Z||`http://localhost:${Y}`,G=X?await qs(Number(Y)+1):await qs(Number($.port)),{settings:W,services:K,managedServiceNames:H}=await KK0({port:String(G),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let O of K)YT({name:O.name,status:"ready",port:O.port});As();let F=OO4(import.meta.dir,"..","..","..","..",".."),U=Q===!0,N=Bun.spawn(["bun","run","dev:servers"],{cwd:F,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,BASE_URL:J,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.betterAuthSecret?{BETTER_AUTH_SECRET:W.betterAuthSecret}:{},...W.s3Endpoint?{S3_ENDPOINT:W.s3Endpoint,S3_BUCKET:W.s3Bucket??"",S3_ACCESS_KEY_ID:W.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:W.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(W.s3ForcePathStyle)}:{},...W.natsCredsPath?{NATS_CREDS:W.natsCredsPath}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)r81(N.stdout),r81(N.stderr);Rs(J),YT({name:"Vite",status:"ready",port:Number(Y)}),YT({name:"API",status:"ready",port:Number(W.port)});let D=async(O)=>{if(N.kill(O),await N.exited,H.length>0){let{stopServices:j}=await Promise.resolve().then(() => (KW0(),WW0));await j(W.dataDir)}};return process.on("SIGINT",()=>D("SIGINT")),process.on("SIGTERM",()=>D("SIGTERM")),{port:Number(Y),process:N}}var e81=L(()=>{p81();JT();a81()});var UK0;var $41=L(()=>{UK0={name:"decocms",version:"4.429.3",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/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"}}});import{Box as EO4,Text as OG$}from"ink";import{jsx as zO4,jsxs as jG$}from"react/jsx-runtime";function wG$({version:$}){return jG$(EO4,{flexDirection:"column",marginTop:1,children:[SW0.map((Z,Q)=>zO4(OG$,{color:_W0[Q],children:Z},Q)),jG$(OG$,{dimColor:!0,children:[" v",$]})]})}var EG$=L(()=>{Gs()});import{Box as GT,Text as lj}from"ink";import{Spinner as PO4}from"@inkjs/ui";import{jsx as rG,jsxs as Lc}from"react/jsx-runtime";function zG$({status:$}){if($==="pending")return rG(PO4,{label:""});return rG(lj,{color:"green",children:"\u2713"})}function TO4($){return`${$.name}: ${$.port||"...."}`}function PG$({services:$,migrationsStatus:Z,home:Q,serverUrl:X}){return Lc(GT,{flexDirection:"column",paddingBottom:1,children:[rG(wG$,{version:UK0.version}),rG(GT,{marginBottom:1,children:rG(lj,{dimColor:!0,children:"\u2500".repeat(80)})}),rG(GT,{children:Lc(lj,{dimColor:!0,children:["Home: ",Q]})}),Lc(GT,{gap:2,children:[$.map((Y)=>Lc(GT,{gap:1,children:[rG(lj,{children:TO4(Y)}),rG(zG$,{status:Y.status})]},Y.name)),Lc(GT,{gap:1,children:[rG(lj,{children:"Migrations"}),rG(zG$,{status:Z})]})]}),rG(GT,{children:X?Lc(lj,{children:["Open in browser: ",rG(lj,{color:"cyan",children:X})]}):rG(lj,{dimColor:!0,children:"Starting..."})})]})}var TG$=L(()=>{$41();EG$()});import{Box as AO4,Text as Ms}from"ink";import{jsx as Z41,jsxs as Q41}from"react/jsx-runtime";function RO4($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function AG$({logs:$}){return Z41(AO4,{flexDirection:"column",children:$.map((Z,Q)=>{if(Z.rawLine)return Z41(Ms,{dimColor:!0,children:Z.rawLine},Q);let X=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return Q41(Ms,{children:[Q41(Ms,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),Z41(Ms,{color:RO4(Z.status),children:Z.status}),Q41(Ms,{dimColor:!0,children:[" ",X.padStart(8)]})]},Q)})})}var RG$=()=>{};var X41={};J0(X41,{App:()=>IO4});import{Box as qO4}from"ink";import{useSyncExternalStore as MO4}from"react";import{jsx as qG$,jsxs as VO4}from"react/jsx-runtime";function IO4({home:$}){let Z=MO4(o81,t81);return VO4(qO4,{flexDirection:"column",children:[qG$(PG$,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),qG$(AG$,{logs:Z.logs})]})}var Y41=L(()=>{TG$();RG$();JT()});var CW="thread-gate",DL="decopilot-hosted-harness",OL="decopilot-hosted-harness-sandboxed",SW="automations",cj="background-tools",WT="task-board-github-reads";var MG$="13";function IG$($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:MG$,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var VG$=()=>{};import kO4 from"pg";async function CG$($,Z){let{databaseUrl:Q,lockTimeoutMs:X=CO4}=$,Y=$.log??((K)=>console.log(K)),J=new kO4.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",[kG$.toString()])).rows[0]?.locked===!0,W)break;if(Date.now()-G>=X)throw Error(`Timed out after ${X}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await $$(SO4)}let K=Date.now()-G;if(K>1000)Y(`[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)",[kG$.toString()])}catch{}await J.end().catch(()=>{})}}var kG$=8314027461559302n,CO4=600000,SO4=500;var SG$=L(()=>{$8()});function _O4(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function J41($,Z){for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X===void 0)continue;if(X===Z)return $[Q+1];if(X.startsWith(`${Z}=`))return X.slice(Z.length+1)}return}function _G$(){let $=_O4();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:J41($,"--cpu-prof-dir")??process.cwd(),name:J41($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(J41($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function vG$(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=$T();if(!Q)return;let X={};try{let{heapStats:Y}=await import("bun:jsc"),J=Y(),G=Object.entries(J.objectTypeCounts).sort((W,K)=>K[1]-W[1]).slice(0,20);X={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,...X}))};return Z().catch(()=>{}),NK0=setInterval(()=>void Z().catch(()=>{}),$),NK0.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),X=typeof Q==="string"?Q:JSON.stringify(Q),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,X),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(NK0)clearInterval(NK0)}}var NK0;var xG$=()=>{};import*as vO4 from"bun:jsc";function fG$(){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{xO4()}catch(J){return console.error("[stall-watchdog] failed to start sampling profiler:",J),()=>{}}let Q,X=performance.now()+Z,Y=()=>{let J=performance.now(),G=J-X;X=J+Z;let W=[];try{W=fO4()?.traces??[]}catch{}if(G>$&&W.length>0){let K=new Map;for(let F of W){let U=F.frames.find((D)=>D.sourceURL&&!/Unknown Executable/.test(D.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(Y,Z),Q.unref?.()};return Q=setTimeout(Y,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}var xO4,fO4;var bG$=L(()=>{({startSamplingProfiler:xO4,samplingProfilerStackTraces:fO4}=vO4)});function yG$(){_G$();let $=[vG$(),H7$(),fG$()];return()=>{for(let Z of $)Z()}}var gG$=L(()=>{hs0();xG$();bG$()});var KT=b((hG$)=>{Object.defineProperty(hG$,"__esModule",{value:!0});hG$.RepublishHeaders=hG$.DirectMsgHeaders=hG$.JsHeaders=hG$.AdvisoryKind=void 0;hG$.isOrderedPushConsumerOptions=bO4;hG$.isPullConsumer=yO4;hG$.isPushConsumer=gO4;hG$.isBoundPushConsumerOptions=hO4;function bO4($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function yO4($){return $.isPullConsumer()}function gO4($){return $.isPushConsumer()}function hO4($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}hG$.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};hG$.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};hG$.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};hG$.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var sG=b((lG$)=>{Object.defineProperty(lG$,"__esModule",{value:!0});lG$.TD=lG$.TE=lG$.Empty=void 0;lG$.encode=tO4;lG$.decode=oO4;lG$.Empty=new Uint8Array(0);lG$.TE=new TextEncoder;lG$.TD=new TextDecoder;function nO4(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}function tO4(...$){let Z=[];for(let Q=0;Q<$.length;Q++)Z.push(lG$.TE.encode($[Q]));if(Z.length===0)return lG$.Empty;if(Z.length===1)return Z[0];return nO4(...Z)}function oO4($){if(!$||$.length===0)return"";return lG$.TD.decode($)}});var eG=b((dG$)=>{Object.defineProperty(dG$,"__esModule",{value:!0});dG$.errors=dG$.PermissionViolationError=dG$.NoRespondersError=dG$.TimeoutError=dG$.RequestError=dG$.ProtocolError=dG$.ConnectionError=dG$.DrainingConnectionError=dG$.ClosedConnectionError=dG$.AuthorizationError=dG$.UserAuthenticationExpiredError=dG$.InvalidOperationError=dG$.InvalidArgumentError=dG$.InvalidSubjectError=void 0;class W41 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}dG$.InvalidSubjectError=W41;class BK0 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,Q){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((X)=>`'${X}'`),$=$.join(",");else $=`'${$}'`;return new BK0(`${$} ${Z}`,Q)}}dG$.InvalidArgumentError=BK0;class K41 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}dG$.InvalidOperationError=K41;class LK0 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new LK0($);return null}}dG$.UserAuthenticationExpiredError=LK0;class DK0 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],Q=$.toLowerCase();for(let X=0;X<Z.length;X++)if(Q.indexOf(Z[X])!==-1)return new DK0($);return null}}dG$.AuthorizationError=DK0;class H41 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}dG$.ClosedConnectionError=H41;class F41 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}dG$.DrainingConnectionError=F41;class U41 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}dG$.ConnectionError=U41;class N41 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}dG$.ProtocolError=N41;class B41 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof OK0}}dG$.RequestError=B41;class L41 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}dG$.TimeoutError=L41;class OK0 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}dG$.NoRespondersError=OK0;class jK0 extends Error{operation;subject;queue;constructor($,Z,Q,X,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=Q,this.queue=X}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let Q="publish",X="",Y=void 0,J=$.match(/(Publish|Subscription) to "(\S+)"/);if(J){if(Q=J[1].toLowerCase(),X=J[2],Q==="subscription"){let G=$.match(/using queue "(\S+)"/);if(G)Y=G[1]}}return new jK0($,Q,X,Y)}}dG$.PermissionViolationError=jK0;dG$.errors={AuthorizationError:DK0,ClosedConnectionError:H41,ConnectionError:U41,DrainingConnectionError:F41,InvalidArgumentError:BK0,InvalidOperationError:K41,InvalidSubjectError:W41,NoRespondersError:OK0,PermissionViolationError:jK0,ProtocolError:N41,RequestError:B41,TimeoutError:L41,UserAuthenticationExpiredError:LK0}});var DH=b((oG$)=>{Object.defineProperty(oG$,"__esModule",{value:!0});oG$.SimpleMutex=oG$.Perf=void 0;oG$.extend=Nj4;oG$.render=Bj4;oG$.timeout=Lj4;oG$.delay=Dj4;oG$.deadline=Oj4;oG$.deferred=O41;oG$.debugDeferred=jj4;oG$.shuffle=wj4;oG$.collect=Ej4;oG$.jitter=tG$;oG$.backoff=zj4;oG$.nanos=Pj4;oG$.millis=Tj4;oG$.randomToken=qj4;var Uj4=sG(),D41=eG();function Nj4($,...Z){for(let Q=0;Q<Z.length;Q++){let X=Z[Q];Object.keys(X).forEach(function(Y){$[Y]=X[Y]})}return $}function Bj4($){return Uj4.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function Lj4($,Z=!0){let Q=Z?new D41.TimeoutError:null,X,Y,J=new Promise((G,W)=>{X={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(Q===null)W(new D41.TimeoutError);else W(Q)},$)});return Object.assign(J,X)}function Dj4($=0){let Z,Q=new Promise((X)=>{let Y=setTimeout(()=>{X()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),X()}}});return Object.assign(Q,Z)}async function Oj4($,Z=1000){let Q=O41(),X=setTimeout(()=>{Q.reject(new D41.TimeoutError)},Z);try{return await Promise.race([$,Q])}finally{clearTimeout(X)}}function O41(){let $={},Z=new Promise((Q,X)=>{$={resolve:Q,reject:X}});return Object.assign(Z,$)}function jj4(){let $={},Z=new Promise((Q,X)=>{$={resolve:(Y)=>{console.trace("resolve",Y),Q(Y)},reject:(Y)=>{console.trace("reject"),X(Y)}}});return Object.assign(Z,$)}function wj4($){for(let Z=$.length-1;Z>0;Z--){let Q=Math.floor(Math.random()*(Z+1));[$[Z],$[Q]]=[$[Q],$[Z]]}return $}async function Ej4($){let Z=[];for await(let Q of $)Z.push(Q);return Z}class pG${timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,Q){let X=this.timers.get(Z);if(X===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(Q);if(Y===void 0)throw Error(`${Q} is not defined`);this.measures.set($,Y-X)}getEntries(){let $=[];return this.measures.forEach((Z,Q)=>{$.push({name:Q,duration:Z})}),$}}oG$.Perf=pG$;class nG${max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=O41();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}oG$.SimpleMutex=nG$;function tG$($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function zj4($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(Q){return tG$(Q>Z?$[Z]:$[Q])}}}function Pj4($){return $*1e6}function Tj4($){return Math.floor($/1e6)}var Aj4="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",jL=new Uint8Array(62);for(let $=0;$<62;$++)jL[$]=Aj4.charCodeAt($);var Rj4=218340105584896;function qj4(){let $=Math.floor(Math.random()*Rj4),Z=$%62,Q=jL[Z];$=($-Z)/62,Z=$%62;let X=jL[Z];$=($-Z)/62,Z=$%62;let Y=jL[Z];$=($-Z)/62,Z=$%62;let J=jL[Z];$=($-Z)/62,Z=$%62;let G=jL[Z];$=($-Z)/62,Z=$%62;let W=jL[Z];$=($-Z)/62,Z=$%62;let K=jL[Z];$=($-Z)/62;let H=jL[$];return String.fromCharCode(Q,X,Y,J,G,W,K,H)}});var X3$=b((Z3$)=>{Object.defineProperty(Z3$,"__esModule",{value:!0});Z3$.nuid=Z3$.NuidImpl=void 0;var lj4="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",mj=62,EK0=12,eG$=10,rG$=33,cj4=333,sG$=EK0+eG$,w41=new Uint8Array(mj);for(let $=0;$<mj;$++)w41[$]=lj4.charCodeAt($);var wK0=4294967296,$3$=BigInt(mj)**BigInt(eG$),Is=Number($3$/(1n<<32n)),j41=Number($3$%(1n<<32n));function mj4($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function dj4($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else mj4($)}class E41{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(sG$),this.cbuf=new Uint8Array(EK0),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(Is+1)),this.seqLo=Math.floor(Math.random()*wK0);while($++<8&&this.seqHi===Is&&this.seqLo>=j41);if(this.seqHi===Is&&this.seqLo>=j41)this.seqLo=0;this.inc=Math.random()*(cj4-rG$)+rG$|0}setPre(){dj4(this.cbuf);for(let $=0;$<EK0;$++)this.buf[$]=w41[this.cbuf[$]%mj]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let Q=sG$-1;Q>=EK0;Q--){let X=Math.floor($/mj),J=($-X*mj)*wK0+Z,G=Math.floor(J/mj),W=J-G*mj;this.buf[Q]=w41[W],$=X,Z=G}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=wK0)this.seqLo-=wK0,this.seqHi+=1;if(this.seqHi>Is||this.seqHi===Is&&this.seqLo>=j41)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}Z3$.NuidImpl=E41;Z3$.nuid=new E41});var W3$=b((J3$)=>{Object.defineProperty(J3$,"__esModule",{value:!0});J3$.nuid=J3$.Nuid=void 0;var Y3$=X3$();J3$.Nuid=Y3$.NuidImpl;J3$.nuid=Y3$.nuid});var PK0=b((zK0)=>{Object.defineProperty(zK0,"__esModule",{value:!0});zK0.nuid=zK0.Nuid=void 0;var K3$=W3$();Object.defineProperty(zK0,"Nuid",{enumerable:!0,get:function(){return K3$.Nuid}});Object.defineProperty(zK0,"nuid",{enumerable:!0,get:function(){return K3$.nuid}})});var dj=b((H3$)=>{Object.defineProperty(H3$,"__esModule",{value:!0});H3$.DEFAULT_HOST=H3$.DEFAULT_PORT=H3$.Match=void 0;H3$.syncIterator=aj4;H3$.createInbox=rj4;var tj4=PK0(),oj4=eG();H3$.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function aj4($){let Z=$[Symbol.asyncIterator]();return{async next(){let Q=await Z.next();if(Q.done)return Promise.resolve(null);return Promise.resolve(Q.value)}}}function rj4($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw oj4.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${tj4.nuid.next()}`}H3$.DEFAULT_PORT=4222;H3$.DEFAULT_HOST="127.0.0.1"});var Vs=b((B3$)=>{Object.defineProperty(B3$,"__esModule",{value:!0});B3$.DataBuffer=void 0;var U3$=sG();class N3${buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}static fromAscii($){if(!$)$="";return U3$.TE.encode($)}static toAscii($){return U3$.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let Q=0;Q<this.buffers.length;Q++)$.set(this.buffers[Q],Z),Z+=this.buffers[Q].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let Q=this.byteLength;if($===void 0||$>Q)$=Q;let X=Z.subarray(0,$);if(Q>$)this.buffers.push(Z.subarray($));return this.byteLength=Q-$,X}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let Q=0;Q<Z.length;Q++)if(Z[Q]&&Z[Q].length)this.buffers.push(Z[Q]),this.byteLength+=Z[Q].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}B3$.DataBuffer=N3$});var HT=b((O3$)=>{Object.defineProperty(O3$,"__esModule",{value:!0});O3$.LF=O3$.CR=O3$.CRLF=O3$.CR_LF_LEN=O3$.CR_LF=void 0;O3$.setTransportFactory=Jw4;O3$.defaultPort=Gw4;O3$.getUrlParseFn=Ww4;O3$.newTransport=Kw4;O3$.getResolveFn=Hw4;O3$.protoLen=D3$;O3$.extractProtocolMessage=Fw4;var Qw4=sG(),Xw4=dj(),Yw4=Vs(),$3;function Jw4($){$3=$}function Gw4(){return $3!==void 0&&$3.defaultPort!==void 0?$3.defaultPort:Xw4.DEFAULT_PORT}function Ww4(){return $3!==void 0&&$3.urlParseFn?$3.urlParseFn:void 0}function Kw4(){if(!$3||typeof $3.factory!=="function")throw Error("transport fn is not set");return $3.factory()}function Hw4(){return $3!==void 0&&$3.dnsResolveFn?$3.dnsResolveFn:void 0}O3$.CR_LF=`\r
|
|
2181
|
+
`);X=J.pop()??"";for(let G of J){let W=Bun.stripANSI(G).replace(/^\[\d+\]\s*/,"").trim();if(!W)continue;uj({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}}(async()=>{try{for(;;){let{done:J,value:G}=await Z.read();if(J)break;X+=Q.decode(G,{stream:!0}),Y()}}catch{}if(X.trim()){let J=Bun.stripANSI(X).replace(/^\[\d+\]\s*/,"").trim();if(J)uj({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:J})}})()}async function jO4($){let{baseUrl:Z,noTui:Q}=$,X=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=X?process.env.PORT:$.vitePort,J=Z||`http://localhost:${Y}`,G=X?await qs(Number(Y)+1):await qs(Number($.port)),{settings:W,services:K,managedServiceNames:H}=await KK0({port:String(G),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let O of K)YT({name:O.name,status:"ready",port:O.port});As();let F=OO4(import.meta.dir,"..","..","..","..",".."),U=Q===!0,N=Bun.spawn(["bun","run","dev:servers"],{cwd:F,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,BASE_URL:J,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.betterAuthSecret?{BETTER_AUTH_SECRET:W.betterAuthSecret}:{},...W.s3Endpoint?{S3_ENDPOINT:W.s3Endpoint,S3_BUCKET:W.s3Bucket??"",S3_ACCESS_KEY_ID:W.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:W.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(W.s3ForcePathStyle)}:{},...W.natsCredsPath?{NATS_CREDS:W.natsCredsPath}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)r81(N.stdout),r81(N.stderr);Rs(J),YT({name:"Vite",status:"ready",port:Number(Y)}),YT({name:"API",status:"ready",port:Number(W.port)});let D=async(O)=>{if(N.kill(O),await N.exited,H.length>0){let{stopServices:j}=await Promise.resolve().then(() => (KW0(),WW0));await j(W.dataDir)}};return process.on("SIGINT",()=>D("SIGINT")),process.on("SIGTERM",()=>D("SIGTERM")),{port:Number(Y),process:N}}var e81=L(()=>{p81();JT();a81()});var UK0;var $41=L(()=>{UK0={name:"decocms",version:"4.429.5",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","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"}}});import{Box as EO4,Text as OG$}from"ink";import{jsx as zO4,jsxs as jG$}from"react/jsx-runtime";function wG$({version:$}){return jG$(EO4,{flexDirection:"column",marginTop:1,children:[SW0.map((Z,Q)=>zO4(OG$,{color:_W0[Q],children:Z},Q)),jG$(OG$,{dimColor:!0,children:[" v",$]})]})}var EG$=L(()=>{Gs()});import{Box as GT,Text as lj}from"ink";import{Spinner as PO4}from"@inkjs/ui";import{jsx as rG,jsxs as Lc}from"react/jsx-runtime";function zG$({status:$}){if($==="pending")return rG(PO4,{label:""});return rG(lj,{color:"green",children:"\u2713"})}function TO4($){return`${$.name}: ${$.port||"...."}`}function PG$({services:$,migrationsStatus:Z,home:Q,serverUrl:X}){return Lc(GT,{flexDirection:"column",paddingBottom:1,children:[rG(wG$,{version:UK0.version}),rG(GT,{marginBottom:1,children:rG(lj,{dimColor:!0,children:"\u2500".repeat(80)})}),rG(GT,{children:Lc(lj,{dimColor:!0,children:["Home: ",Q]})}),Lc(GT,{gap:2,children:[$.map((Y)=>Lc(GT,{gap:1,children:[rG(lj,{children:TO4(Y)}),rG(zG$,{status:Y.status})]},Y.name)),Lc(GT,{gap:1,children:[rG(lj,{children:"Migrations"}),rG(zG$,{status:Z})]})]}),rG(GT,{children:X?Lc(lj,{children:["Open in browser: ",rG(lj,{color:"cyan",children:X})]}):rG(lj,{dimColor:!0,children:"Starting..."})})]})}var TG$=L(()=>{$41();EG$()});import{Box as AO4,Text as Ms}from"ink";import{jsx as Z41,jsxs as Q41}from"react/jsx-runtime";function RO4($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function AG$({logs:$}){return Z41(AO4,{flexDirection:"column",children:$.map((Z,Q)=>{if(Z.rawLine)return Z41(Ms,{dimColor:!0,children:Z.rawLine},Q);let X=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return Q41(Ms,{children:[Q41(Ms,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),Z41(Ms,{color:RO4(Z.status),children:Z.status}),Q41(Ms,{dimColor:!0,children:[" ",X.padStart(8)]})]},Q)})})}var RG$=()=>{};var X41={};J0(X41,{App:()=>IO4});import{Box as qO4}from"ink";import{useSyncExternalStore as MO4}from"react";import{jsx as qG$,jsxs as VO4}from"react/jsx-runtime";function IO4({home:$}){let Z=MO4(o81,t81);return VO4(qO4,{flexDirection:"column",children:[qG$(PG$,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),qG$(AG$,{logs:Z.logs})]})}var Y41=L(()=>{TG$();RG$();JT()});var CW="thread-gate",DL="decopilot-hosted-harness",OL="decopilot-hosted-harness-sandboxed",SW="automations",cj="background-tools",WT="task-board-github-reads";var MG$="13";function IG$($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:MG$,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var VG$=()=>{};import kO4 from"pg";async function CG$($,Z){let{databaseUrl:Q,lockTimeoutMs:X=CO4}=$,Y=$.log??((K)=>console.log(K)),J=new kO4.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",[kG$.toString()])).rows[0]?.locked===!0,W)break;if(Date.now()-G>=X)throw Error(`Timed out after ${X}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await $$(SO4)}let K=Date.now()-G;if(K>1000)Y(`[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)",[kG$.toString()])}catch{}await J.end().catch(()=>{})}}var kG$=8314027461559302n,CO4=600000,SO4=500;var SG$=L(()=>{$8()});function _O4(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function J41($,Z){for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X===void 0)continue;if(X===Z)return $[Q+1];if(X.startsWith(`${Z}=`))return X.slice(Z.length+1)}return}function _G$(){let $=_O4();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:J41($,"--cpu-prof-dir")??process.cwd(),name:J41($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(J41($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function vG$(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=$T();if(!Q)return;let X={};try{let{heapStats:Y}=await import("bun:jsc"),J=Y(),G=Object.entries(J.objectTypeCounts).sort((W,K)=>K[1]-W[1]).slice(0,20);X={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,...X}))};return Z().catch(()=>{}),NK0=setInterval(()=>void Z().catch(()=>{}),$),NK0.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),X=typeof Q==="string"?Q:JSON.stringify(Q),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,X),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(NK0)clearInterval(NK0)}}var NK0;var xG$=()=>{};import*as vO4 from"bun:jsc";function fG$(){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{xO4()}catch(J){return console.error("[stall-watchdog] failed to start sampling profiler:",J),()=>{}}let Q,X=performance.now()+Z,Y=()=>{let J=performance.now(),G=J-X;X=J+Z;let W=[];try{W=fO4()?.traces??[]}catch{}if(G>$&&W.length>0){let K=new Map;for(let F of W){let U=F.frames.find((D)=>D.sourceURL&&!/Unknown Executable/.test(D.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(Y,Z),Q.unref?.()};return Q=setTimeout(Y,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}var xO4,fO4;var bG$=L(()=>{({startSamplingProfiler:xO4,samplingProfilerStackTraces:fO4}=vO4)});function yG$(){_G$();let $=[vG$(),H7$(),fG$()];return()=>{for(let Z of $)Z()}}var gG$=L(()=>{hs0();xG$();bG$()});var KT=b((hG$)=>{Object.defineProperty(hG$,"__esModule",{value:!0});hG$.RepublishHeaders=hG$.DirectMsgHeaders=hG$.JsHeaders=hG$.AdvisoryKind=void 0;hG$.isOrderedPushConsumerOptions=bO4;hG$.isPullConsumer=yO4;hG$.isPushConsumer=gO4;hG$.isBoundPushConsumerOptions=hO4;function bO4($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function yO4($){return $.isPullConsumer()}function gO4($){return $.isPushConsumer()}function hO4($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}hG$.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};hG$.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};hG$.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};hG$.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var sG=b((lG$)=>{Object.defineProperty(lG$,"__esModule",{value:!0});lG$.TD=lG$.TE=lG$.Empty=void 0;lG$.encode=tO4;lG$.decode=oO4;lG$.Empty=new Uint8Array(0);lG$.TE=new TextEncoder;lG$.TD=new TextDecoder;function nO4(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}function tO4(...$){let Z=[];for(let Q=0;Q<$.length;Q++)Z.push(lG$.TE.encode($[Q]));if(Z.length===0)return lG$.Empty;if(Z.length===1)return Z[0];return nO4(...Z)}function oO4($){if(!$||$.length===0)return"";return lG$.TD.decode($)}});var eG=b((dG$)=>{Object.defineProperty(dG$,"__esModule",{value:!0});dG$.errors=dG$.PermissionViolationError=dG$.NoRespondersError=dG$.TimeoutError=dG$.RequestError=dG$.ProtocolError=dG$.ConnectionError=dG$.DrainingConnectionError=dG$.ClosedConnectionError=dG$.AuthorizationError=dG$.UserAuthenticationExpiredError=dG$.InvalidOperationError=dG$.InvalidArgumentError=dG$.InvalidSubjectError=void 0;class W41 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}dG$.InvalidSubjectError=W41;class BK0 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,Q){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((X)=>`'${X}'`),$=$.join(",");else $=`'${$}'`;return new BK0(`${$} ${Z}`,Q)}}dG$.InvalidArgumentError=BK0;class K41 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}dG$.InvalidOperationError=K41;class LK0 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new LK0($);return null}}dG$.UserAuthenticationExpiredError=LK0;class DK0 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],Q=$.toLowerCase();for(let X=0;X<Z.length;X++)if(Q.indexOf(Z[X])!==-1)return new DK0($);return null}}dG$.AuthorizationError=DK0;class H41 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}dG$.ClosedConnectionError=H41;class F41 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}dG$.DrainingConnectionError=F41;class U41 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}dG$.ConnectionError=U41;class N41 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}dG$.ProtocolError=N41;class B41 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof OK0}}dG$.RequestError=B41;class L41 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}dG$.TimeoutError=L41;class OK0 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}dG$.NoRespondersError=OK0;class jK0 extends Error{operation;subject;queue;constructor($,Z,Q,X,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=Q,this.queue=X}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let Q="publish",X="",Y=void 0,J=$.match(/(Publish|Subscription) to "(\S+)"/);if(J){if(Q=J[1].toLowerCase(),X=J[2],Q==="subscription"){let G=$.match(/using queue "(\S+)"/);if(G)Y=G[1]}}return new jK0($,Q,X,Y)}}dG$.PermissionViolationError=jK0;dG$.errors={AuthorizationError:DK0,ClosedConnectionError:H41,ConnectionError:U41,DrainingConnectionError:F41,InvalidArgumentError:BK0,InvalidOperationError:K41,InvalidSubjectError:W41,NoRespondersError:OK0,PermissionViolationError:jK0,ProtocolError:N41,RequestError:B41,TimeoutError:L41,UserAuthenticationExpiredError:LK0}});var DH=b((oG$)=>{Object.defineProperty(oG$,"__esModule",{value:!0});oG$.SimpleMutex=oG$.Perf=void 0;oG$.extend=Nj4;oG$.render=Bj4;oG$.timeout=Lj4;oG$.delay=Dj4;oG$.deadline=Oj4;oG$.deferred=O41;oG$.debugDeferred=jj4;oG$.shuffle=wj4;oG$.collect=Ej4;oG$.jitter=tG$;oG$.backoff=zj4;oG$.nanos=Pj4;oG$.millis=Tj4;oG$.randomToken=qj4;var Uj4=sG(),D41=eG();function Nj4($,...Z){for(let Q=0;Q<Z.length;Q++){let X=Z[Q];Object.keys(X).forEach(function(Y){$[Y]=X[Y]})}return $}function Bj4($){return Uj4.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function Lj4($,Z=!0){let Q=Z?new D41.TimeoutError:null,X,Y,J=new Promise((G,W)=>{X={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(Q===null)W(new D41.TimeoutError);else W(Q)},$)});return Object.assign(J,X)}function Dj4($=0){let Z,Q=new Promise((X)=>{let Y=setTimeout(()=>{X()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),X()}}});return Object.assign(Q,Z)}async function Oj4($,Z=1000){let Q=O41(),X=setTimeout(()=>{Q.reject(new D41.TimeoutError)},Z);try{return await Promise.race([$,Q])}finally{clearTimeout(X)}}function O41(){let $={},Z=new Promise((Q,X)=>{$={resolve:Q,reject:X}});return Object.assign(Z,$)}function jj4(){let $={},Z=new Promise((Q,X)=>{$={resolve:(Y)=>{console.trace("resolve",Y),Q(Y)},reject:(Y)=>{console.trace("reject"),X(Y)}}});return Object.assign(Z,$)}function wj4($){for(let Z=$.length-1;Z>0;Z--){let Q=Math.floor(Math.random()*(Z+1));[$[Z],$[Q]]=[$[Q],$[Z]]}return $}async function Ej4($){let Z=[];for await(let Q of $)Z.push(Q);return Z}class pG${timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,Q){let X=this.timers.get(Z);if(X===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(Q);if(Y===void 0)throw Error(`${Q} is not defined`);this.measures.set($,Y-X)}getEntries(){let $=[];return this.measures.forEach((Z,Q)=>{$.push({name:Q,duration:Z})}),$}}oG$.Perf=pG$;class nG${max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=O41();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}oG$.SimpleMutex=nG$;function tG$($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function zj4($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(Q){return tG$(Q>Z?$[Z]:$[Q])}}}function Pj4($){return $*1e6}function Tj4($){return Math.floor($/1e6)}var Aj4="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",jL=new Uint8Array(62);for(let $=0;$<62;$++)jL[$]=Aj4.charCodeAt($);var Rj4=218340105584896;function qj4(){let $=Math.floor(Math.random()*Rj4),Z=$%62,Q=jL[Z];$=($-Z)/62,Z=$%62;let X=jL[Z];$=($-Z)/62,Z=$%62;let Y=jL[Z];$=($-Z)/62,Z=$%62;let J=jL[Z];$=($-Z)/62,Z=$%62;let G=jL[Z];$=($-Z)/62,Z=$%62;let W=jL[Z];$=($-Z)/62,Z=$%62;let K=jL[Z];$=($-Z)/62;let H=jL[$];return String.fromCharCode(Q,X,Y,J,G,W,K,H)}});var X3$=b((Z3$)=>{Object.defineProperty(Z3$,"__esModule",{value:!0});Z3$.nuid=Z3$.NuidImpl=void 0;var lj4="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",mj=62,EK0=12,eG$=10,rG$=33,cj4=333,sG$=EK0+eG$,w41=new Uint8Array(mj);for(let $=0;$<mj;$++)w41[$]=lj4.charCodeAt($);var wK0=4294967296,$3$=BigInt(mj)**BigInt(eG$),Is=Number($3$/(1n<<32n)),j41=Number($3$%(1n<<32n));function mj4($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function dj4($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else mj4($)}class E41{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(sG$),this.cbuf=new Uint8Array(EK0),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(Is+1)),this.seqLo=Math.floor(Math.random()*wK0);while($++<8&&this.seqHi===Is&&this.seqLo>=j41);if(this.seqHi===Is&&this.seqLo>=j41)this.seqLo=0;this.inc=Math.random()*(cj4-rG$)+rG$|0}setPre(){dj4(this.cbuf);for(let $=0;$<EK0;$++)this.buf[$]=w41[this.cbuf[$]%mj]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let Q=sG$-1;Q>=EK0;Q--){let X=Math.floor($/mj),J=($-X*mj)*wK0+Z,G=Math.floor(J/mj),W=J-G*mj;this.buf[Q]=w41[W],$=X,Z=G}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=wK0)this.seqLo-=wK0,this.seqHi+=1;if(this.seqHi>Is||this.seqHi===Is&&this.seqLo>=j41)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}Z3$.NuidImpl=E41;Z3$.nuid=new E41});var W3$=b((J3$)=>{Object.defineProperty(J3$,"__esModule",{value:!0});J3$.nuid=J3$.Nuid=void 0;var Y3$=X3$();J3$.Nuid=Y3$.NuidImpl;J3$.nuid=Y3$.nuid});var PK0=b((zK0)=>{Object.defineProperty(zK0,"__esModule",{value:!0});zK0.nuid=zK0.Nuid=void 0;var K3$=W3$();Object.defineProperty(zK0,"Nuid",{enumerable:!0,get:function(){return K3$.Nuid}});Object.defineProperty(zK0,"nuid",{enumerable:!0,get:function(){return K3$.nuid}})});var dj=b((H3$)=>{Object.defineProperty(H3$,"__esModule",{value:!0});H3$.DEFAULT_HOST=H3$.DEFAULT_PORT=H3$.Match=void 0;H3$.syncIterator=aj4;H3$.createInbox=rj4;var tj4=PK0(),oj4=eG();H3$.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function aj4($){let Z=$[Symbol.asyncIterator]();return{async next(){let Q=await Z.next();if(Q.done)return Promise.resolve(null);return Promise.resolve(Q.value)}}}function rj4($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw oj4.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${tj4.nuid.next()}`}H3$.DEFAULT_PORT=4222;H3$.DEFAULT_HOST="127.0.0.1"});var Vs=b((B3$)=>{Object.defineProperty(B3$,"__esModule",{value:!0});B3$.DataBuffer=void 0;var U3$=sG();class N3${buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}static fromAscii($){if(!$)$="";return U3$.TE.encode($)}static toAscii($){return U3$.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let Q=0;Q<this.buffers.length;Q++)$.set(this.buffers[Q],Z),Z+=this.buffers[Q].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let Q=this.byteLength;if($===void 0||$>Q)$=Q;let X=Z.subarray(0,$);if(Q>$)this.buffers.push(Z.subarray($));return this.byteLength=Q-$,X}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let Q=0;Q<Z.length;Q++)if(Z[Q]&&Z[Q].length)this.buffers.push(Z[Q]),this.byteLength+=Z[Q].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}B3$.DataBuffer=N3$});var HT=b((O3$)=>{Object.defineProperty(O3$,"__esModule",{value:!0});O3$.LF=O3$.CR=O3$.CRLF=O3$.CR_LF_LEN=O3$.CR_LF=void 0;O3$.setTransportFactory=Jw4;O3$.defaultPort=Gw4;O3$.getUrlParseFn=Ww4;O3$.newTransport=Kw4;O3$.getResolveFn=Hw4;O3$.protoLen=D3$;O3$.extractProtocolMessage=Fw4;var Qw4=sG(),Xw4=dj(),Yw4=Vs(),$3;function Jw4($){$3=$}function Gw4(){return $3!==void 0&&$3.defaultPort!==void 0?$3.defaultPort:Xw4.DEFAULT_PORT}function Ww4(){return $3!==void 0&&$3.urlParseFn?$3.urlParseFn:void 0}function Kw4(){if(!$3||typeof $3.factory!=="function")throw Error("transport fn is not set");return $3.factory()}function Hw4(){return $3!==void 0&&$3.dnsResolveFn?$3.dnsResolveFn:void 0}O3$.CR_LF=`\r
|
|
2182
2182
|
`;O3$.CR_LF_LEN=O3$.CR_LF.length;O3$.CRLF=Yw4.DataBuffer.fromAscii(O3$.CR_LF);O3$.CR=new Uint8Array(O3$.CRLF)[0];O3$.LF=new Uint8Array(O3$.CRLF)[1];function D3$($){for(let Z=0;Z<$.length;Z++){let Q=Z+1;if($.byteLength>Q&&$[Z]===O3$.CR&&$[Q]===O3$.LF)return Q+1}return 0}function Fw4($){let Z=D3$($);if(Z>0){let X=new Uint8Array($).slice(0,Z);return Qw4.TD.decode(X)}return""}});var R41=b((R3$)=>{Object.defineProperty(R3$,"__esModule",{value:!0});R3$.ipV4=P3$;R3$.isIP=Pw4;R3$.parseIP=T3$;var ks=4,FT=16,TK0=48,z3$=57,w3$=65,Ew4=70,E3$=97,zw4=102,A41=16777215;function P3$($,Z,Q,X){let Y=new Uint8Array(FT);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((G,W)=>{Y[W]=G}),Y[12]=$,Y[13]=Z,Y[14]=Q,Y[15]=X,Y}function Pw4($){return T3$($)!==void 0}function T3$($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return A3$($);case":":return Tw4($)}return}function A3$($){let Z=new Uint8Array(ks);for(let Q=0;Q<ks;Q++){if($.length===0)return;if(Q>0){if($[0]!==".")return;$=$.substring(1)}let{n:X,c:Y,ok:J}=Aw4($);if(!J||X>255)return;$=$.substring(Y),Z[Q]=X}return P3$(Z[0],Z[1],Z[2],Z[3])}function Tw4($){let Z=new Uint8Array(FT),Q=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(Q=0,$=$.substring(2),$.length===0)return Z}let X=0;while(X<FT){let{n:Y,c:J,ok:G}=Rw4($);if(!G||Y>65535)return;if(J<$.length&&$[J]==="."){if(Q<0&&X!=FT-ks)return;if(X+ks>FT)return;let W=A3$($);if(W===void 0)return;Z[X]=W[12],Z[X+1]=W[13],Z[X+2]=W[14],Z[X+3]=W[15],$="",X+=ks;break}if(Z[X]=Y>>8,Z[X+1]=Y,X+=2,$=$.substring(J),$.length===0)break;if($[0]!==":"||$.length==1)return;if($=$.substring(1),$[0]===":"){if(Q>=0)return;if(Q=X,$=$.substring(1),$.length===0)break}}if($.length!==0)return;if(X<FT){if(Q<0)return;let Y=FT-X;for(let J=X-1;J>=Q;J--)Z[J+Y]=Z[J];for(let J=Q+Y-1;J>=Q;J--)Z[J]=0}else if(Q>=0)return;return Z}function Aw4($){let Z=0,Q=0;for(Z=0;Z<$.length&&TK0<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=z3$;Z++)if(Q=Q*10+($.charCodeAt(Z)-TK0),Q>=A41)return{n:A41,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:Q,c:Z,ok:!0}}function Rw4($){let Z=0,Q=0;for(Q=0;Q<$.length;Q++){if(TK0<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=z3$)Z*=16,Z+=$.charCodeAt(Q)-TK0;else if(E3$<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=zw4)Z*=16,Z+=$.charCodeAt(Q)-E3$+10;else if(w3$<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=Ew4)Z*=16,Z+=$.charCodeAt(Q)-w3$+10;else break;if(Z>=A41)return{n:0,c:Q,ok:!1}}if(Q===0)return{n:0,c:Q,ok:!1};return{n:Z,c:Q,ok:!0}}});var C41=b((M3$)=>{Object.defineProperty(M3$,"__esModule",{value:!0});M3$.Servers=M3$.ServerImpl=void 0;M3$.isIPV4OrHostname=q3$;M3$.hostPort=k41;var q41=HT(),M41=DH(),I41=R41(),Vw4=dj(),kw4=eG();function q3$($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function V41($){return!q3$($)}function Cw4($){let Q=$.toUpperCase().indexOf("::FFFF:");if(Q!==-1&&$.indexOf(".")!==-1){let X=$.substring(Q+7);return X=X.replace("[",""),X.replace("]","")}return $}function k41($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=Cw4($),V41($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=V41($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),Q=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):Vw4.DEFAULT_PORT,Y=new URL(`${Q===80?"https":"http"}://${$}`);Y.port=`${Q}`;let J=Y.hostname;if(J.charAt(0)==="[")J=J.substring(1,J.length-1);return{listen:Y.host,hostname:J,port:Q}}class Dc{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let Q=k41($);this.listen=Q.listen,this.hostname=Q.hostname,this.port=Q.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=Z}toString(){return this.listen}async resolve($){if(!$.fn||$.resolve===!1)return[this];let Z=[];if((0,I41.isIP)(this.hostname))return[this];else{let Q=await $.fn(this.hostname);if($.debug)console.log(`resolve ${this.hostname} = ${Q.join(",")}`);for(let X of Q){let Y=this.port===80?"https":"http",J=new URL(`${Y}://${V41(X)?"["+X+"]":X}`);J.port=`${this.port}`;let G=new Dc(J.host,!1);G.tlsName=this.hostname,Z.push(G)}}if($.randomize)(0,M41.shuffle)(Z);return this.resolves=Z,Z}}M3$.ServerImpl=Dc;class AK0{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw kw4.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,q41.getUrlParseFn)(),Q=new Map;for(let Y of this.servers)Q.set(Y.listen,Y);let X=[];for(let Y of $){Y=Z?Z(Y):Y;let{listen:J}=k41(Y),G=Q.get(J);if(G)G.gossiped=!1,X.push(G);else X.push(new Dc(Y))}if(this.randomize)(0,M41.shuffle)(X);if(this.servers=X,this.currentServer===void 0||!X.includes(this.currentServer))this.currentServer=X[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let $=this.getCurrentServer();if(!(0,I41.isIP)($.hostname))this.tlsName=$.hostname,this.servers.forEach((Z)=>{if(Z.gossiped)Z.tlsName=this.tlsName})}getCurrentServer(){return this.currentServer}addServer($,Z=!1){let Q=(0,q41.getUrlParseFn)();$=Q?Q($):$;let X=new Dc($,Z);if((0,I41.isIP)(X.hostname))X.tlsName=this.tlsName;this.servers.push(X)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;let $=this.servers.shift();if($)this.servers.push($),this.currentServer=$;return $}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer($){if($){let Z=this.servers.indexOf($);this.servers.splice(Z,1)}}snapshot(){return AK0.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return AK0.freezeAll([$,...this.servers.slice(0,Z),...this.servers.slice(Z+1)])}static freezeAll($){return $.map((Z)=>Object.freeze({hostname:Z.hostname,port:Z.port,listen:Z.listen,src:Z.src,tlsName:Z.tlsName,reconnects:Z.reconnects,lastConnect:Z.lastConnect,gossiped:Z.gossiped,didConnect:Z.didConnect}))}find($){return this.servers.find((Z)=>Z.listen===$.listen)}setCurrent($){this.currentServer=$}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update($,Z){let Q=[],X=[],Y=(0,q41.getUrlParseFn)(),J=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((W)=>{W=Y?Y(W,Z):W;let K=new Dc(W,!0);J.set(W,K)});let G=[];if(this.servers.forEach((W,K)=>{let H=W.listen;if(W.gossiped&&this.currentServer.listen!==H&&J.get(H)===void 0)G.push(K);J.delete(H)}),G.reverse(),G.forEach((W)=>{let K=this.servers.splice(W,1);X=X.concat(K[0].listen)}),J.forEach((W,K)=>{this.servers.push(W),Q.push(K)}),this.randomize&&Q.length>0){let W=this.currentServer,K=this.servers.filter((H)=>H!==W);(0,M41.shuffle)(K),this.servers=W?[W,...K]:K}return{added:Q,deleted:X}}}M3$.Servers=AK0});var RK0=b((C3$)=>{Object.defineProperty(C3$,"__esModule",{value:!0});C3$.QueuedIteratorImpl=void 0;var S41=DH(),V3$=eG();class k3${inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ctx;_data;err;time;profile;yielding;didBreak;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=(0,S41.deferred)(),this.yields=[],this.iterClosed=(0,S41.deferred)(),this.time=0,this.yielding=!1,this.didBreak=!1,this.profile=!1}[Symbol.asyncIterator](){return this.iterate()}push($){if(this.done)return;if(this.didBreak){if(typeof $==="function"){let Z=$;try{Z()}catch(Q){}}return}if(typeof $==="function")this.pendingFiltered++;this.yields.push($),this.signal.resolve()}async*iterate(){if(this.noIterator)throw new V3$.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new V3$.InvalidOperationError("iterator is already yielding");this.yielding=!0;try{while(!0){if(this.yields.length===0)await this.signal;if(this.err)throw this.err;let $=this.yields;this.inflight=$.length,this.yields=[];for(let Z=0;Z<$.length;Z++){if(typeof $[Z]==="function"){this.pendingFiltered--;let X=$[Z];try{X()}catch(Y){throw Y}if(this.err)throw this.err;continue}this.processed++,this.inflight--;let Q=this.profile?Date.now():0;yield $[Z],this.time=this.profile?Date.now()-Q:0}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,S41.deferred)()}}finally{this.didBreak=!0,this.stop()}}stop($){if(this.done)return;this.err=$,this.done=!0,this.signal.resolve(),this.iterClosed.resolve($)}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}C3$.QueuedIteratorImpl=k3$});var _41=b((x3$)=>{Object.defineProperty(x3$,"__esModule",{value:!0});x3$.MuxSubscription=void 0;var xw4=dj(),_3$=eG();class v3${baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,xw4.createInbox)($)}.`,this.baseInbox}add($){if(!isNaN($.received))$.received=0;this.reqs.set($.token,$)}get($){return this.reqs.get($)}cancel($){this.reqs.delete($.token)}getToken($){let Z=$.subject||"";if(Z.indexOf(this.baseInbox)===0)return Z.substring(this.baseInbox.length);return null}all(){return Array.from(this.reqs.values())}handleError($,Z){if($)return this.all().forEach((Q)=>{Q.resolver(Z,{})}),!0;if(Z.operation==="publish"){let Q=this.all().find((X)=>{return X.requestSubject===Z.subject});if(Q)return Q.resolver(Z,{}),!0}return!1}dispatcher(){return($,Z)=>{let Q=this.getToken(Z);if(Q){let X=this.get(Q);if(X){if($===null)$=Z?.data?.length===0&&Z.headers?.code===503?new _3$.NoRespondersError(X.requestSubject):null;X.resolver($,Z)}}}}close(){let $=new _3$.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}x3$.MuxSubscription=v3$});var v41=b((y3$)=>{Object.defineProperty(y3$,"__esModule",{value:!0});y3$.Heartbeat=void 0;var fw4=DH();class b3${ph;interval;maxOut;timer;pendings;constructor($,Z,Q){this.ph=$,this.interval=Z,this.maxOut=Q,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel($){if(this.timer)clearTimeout(this.timer),this.timer=void 0;if(this._reset(),$)this.ph.disconnect()}_schedule(){this.timer=setTimeout(()=>{if(this.ph.dispatchStatus({type:"ping",pendingPings:this.pendings.length+1}),this.pendings.length===this.maxOut){this.cancel(!0);return}let $=(0,fw4.deferred)();this.ph.flush($).then(()=>{this._reset()}).catch(()=>{this.cancel()}),this.pendings.push($),this._schedule()},this.interval)}_reset(){this.pendings=this.pendings.filter(($)=>{return $.resolve(),!1})}}y3$.Heartbeat=b3$});var b41=b((c3$)=>{Object.defineProperty(c3$,"__esModule",{value:!0});c3$.DenoBuffer=c3$.MAX_SIZE=c3$.AssertionError=void 0;c3$.assert=u3$;c3$.concat=l3$;c3$.append=yw4;c3$.readAll=gw4;c3$.writeAll=hw4;var bw4=sG();class x41 extends Error{constructor($){super($);this.name="AssertionError"}}c3$.AssertionError=x41;function u3$($,Z="Assertion failed."){if(!$)throw new x41(Z)}var h3$=32768;c3$.MAX_SIZE=4294967294;function qK0($,Z,Q=0){let X=Z.byteLength-Q;if($.byteLength>X)$=$.subarray(0,X);return Z.set($,Q),$.byteLength}function l3$($,Z){if($===void 0&&Z===void 0)return new Uint8Array(0);if($===void 0)return Z;if(Z===void 0)return $;let Q=new Uint8Array($.length+Z.length);return Q.set($,0),Q.set(Z,$.length),Q}function yw4($,Z){return l3$($,Uint8Array.of(Z))}class f41{_buf;_off;constructor($){if(this._off=0,$==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array($)}bytes($={copy:!0}){if($.copy===!1)return this._buf.subarray(this._off);return this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate($){if($===0){this.reset();return}if($<0||$>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+$)}reset(){this._reslice(0),this._off=0}_tryGrowByReslice($){let Z=this._buf.byteLength;if($<=this.capacity-Z)return this._reslice(Z+$),Z;return-1}_reslice($){u3$($<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,$)}readByte(){let $=new Uint8Array(1);if(this.read($))return $[0];return null}read($){if(this.empty()){if(this.reset(),$.byteLength===0)return 0;return null}let Z=qK0(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write(bw4.TE.encode($))}write($){let Z=this._grow($.byteLength);return qK0($,this._buf,Z)}_grow($){let Z=this.length;if(Z===0&&this._off!==0)this.reset();let Q=this._tryGrowByReslice($);if(Q>=0)return Q;let X=this.capacity;if($<=Math.floor(X/2)-Z)qK0(this._buf.subarray(this._off),this._buf);else if(X+$>c3$.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*X+$,c3$.MAX_SIZE));qK0(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,c3$.MAX_SIZE)),Z}grow($){if($<0)throw Error("Buffer._grow: negative count");let Z=this._grow($);this._reslice(Z)}readFrom($){let Z=0,Q=new Uint8Array(h3$);while(!0){let X=this.capacity-this.length<h3$,Y=X?Q:new Uint8Array(this._buf.buffer,this.length),J=$.read(Y);if(J===null)return Z;if(X)this.write(Y.subarray(0,J));else this._reslice(this.length+J);Z+=J}}}c3$.DenoBuffer=f41;function gw4($){let Z=new f41;return Z.readFrom($),Z.bytes()}function hw4($,Z){let Q=0;while(Q<Z.length)Q+=$.write(Z.subarray(Q))}});var h41=b((n3$)=>{Object.defineProperty(n3$,"__esModule",{value:!0});n3$.cc=n3$.State=n3$.Parser=n3$.Kind=void 0;n3$.describe=pw4;var y41=b41(),g41=sG();n3$.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function pw4($){let Z,Q="";switch($.kind){case n3$.Kind.MSG:Z="MSG";break;case n3$.Kind.OK:Z="OK";break;case n3$.Kind.ERR:Z="ERR",Q=g41.TD.decode($.data);break;case n3$.Kind.PING:Z="PING";break;case n3$.Kind.PONG:Z="PONG";break;case n3$.Kind.INFO:Z="INFO",Q=g41.TD.decode($.data)}return`${Z}: ${Q}`}function d3$(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var i3$=48,nw4=57,Oc=67108864;class p3${dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=n3$.State.OP_START,this.as=0,this.drop=0,this.hdr=0}parse($){let Z;for(Z=0;Z<$.length;Z++){let Q=$[Z];switch(this.state){case n3$.State.OP_START:switch(Q){case n3$.cc.M:case n3$.cc.m:this.state=n3$.State.OP_M,this.hdr=-1,this.ma=d3$();break;case n3$.cc.H:case n3$.cc.h:this.state=n3$.State.OP_H,this.hdr=0,this.ma=d3$();break;case n3$.cc.P:case n3$.cc.p:this.state=n3$.State.OP_P;break;case n3$.cc.PLUS:this.state=n3$.State.OP_PLUS;break;case n3$.cc.MINUS:this.state=n3$.State.OP_MINUS;break;case n3$.cc.I:case n3$.cc.i:this.state=n3$.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_H:switch(Q){case n3$.cc.M:case n3$.cc.m:this.state=n3$.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_M:switch(Q){case n3$.cc.S:case n3$.cc.s:this.state=n3$.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_MS:switch(Q){case n3$.cc.G:case n3$.cc.g:this.state=n3$.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_MSG:switch(Q){case n3$.cc.SPACE:case n3$.cc.TAB:this.state=n3$.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_MSG_SPC:switch(Q){case n3$.cc.SPACE:case n3$.cc.TAB:continue;default:this.state=n3$.State.MSG_ARG,this.as=Z}break;case n3$.State.MSG_ARG:switch(Q){case n3$.cc.CR:this.drop=1;break;case n3$.cc.NL:{let X=this.argBuf?this.argBuf.bytes():$.subarray(this.as,Z-this.drop);this.processMsgArgs(X),this.drop=0,this.as=Z+1,this.state=n3$.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(Q)}break;case n3$.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let X=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:n3$.Kind.MSG,msg:this.ma,data:X}),this.argBuf=void 0,this.msgBuf=void 0,this.state=n3$.State.MSG_END}else{let X=this.ma.size-this.msgBuf.length,Y=$.length-Z;if(Y<X)X=Y;if(X>0)this.msgBuf.write($.subarray(Z,Z+X)),Z=Z+X-1;else this.msgBuf.writeByte(Q)}else if(Z-this.as>=this.ma.size)this.dispatcher.push({kind:n3$.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=n3$.State.MSG_END;break;case n3$.State.MSG_END:switch(Q){case n3$.cc.NL:this.drop=0,this.as=Z+1,this.state=n3$.State.OP_START;break;default:continue}break;case n3$.State.OP_PLUS:switch(Q){case n3$.cc.O:case n3$.cc.o:this.state=n3$.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_PLUS_O:switch(Q){case n3$.cc.K:case n3$.cc.k:this.state=n3$.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_PLUS_OK:switch(Q){case n3$.cc.NL:this.dispatcher.push({kind:n3$.Kind.OK}),this.drop=0,this.state=n3$.State.OP_START;break}break;case n3$.State.OP_MINUS:switch(Q){case n3$.cc.E:case n3$.cc.e:this.state=n3$.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_MINUS_E:switch(Q){case n3$.cc.R:case n3$.cc.r:this.state=n3$.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_MINUS_ER:switch(Q){case n3$.cc.R:case n3$.cc.r:this.state=n3$.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_MINUS_ERR:switch(Q){case n3$.cc.SPACE:case n3$.cc.TAB:this.state=n3$.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_MINUS_ERR_SPC:switch(Q){case n3$.cc.SPACE:case n3$.cc.TAB:continue;default:this.state=n3$.State.MINUS_ERR_ARG,this.as=Z}break;case n3$.State.MINUS_ERR_ARG:switch(Q){case n3$.cc.CR:this.drop=1;break;case n3$.cc.NL:{let X;if(this.argBuf)X=this.argBuf.bytes(),this.argBuf=void 0;else X=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:n3$.Kind.ERR,data:X}),this.drop=0,this.as=Z+1,this.state=n3$.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(Q))}break;case n3$.State.OP_P:switch(Q){case n3$.cc.I:case n3$.cc.i:this.state=n3$.State.OP_PI;break;case n3$.cc.O:case n3$.cc.o:this.state=n3$.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_PO:switch(Q){case n3$.cc.N:case n3$.cc.n:this.state=n3$.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_PON:switch(Q){case n3$.cc.G:case n3$.cc.g:this.state=n3$.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_PONG:switch(Q){case n3$.cc.NL:this.dispatcher.push({kind:n3$.Kind.PONG}),this.drop=0,this.state=n3$.State.OP_START;break}break;case n3$.State.OP_PI:switch(Q){case n3$.cc.N:case n3$.cc.n:this.state=n3$.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_PIN:switch(Q){case n3$.cc.G:case n3$.cc.g:this.state=n3$.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_PING:switch(Q){case n3$.cc.NL:this.dispatcher.push({kind:n3$.Kind.PING}),this.drop=0,this.state=n3$.State.OP_START;break}break;case n3$.State.OP_I:switch(Q){case n3$.cc.N:case n3$.cc.n:this.state=n3$.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_IN:switch(Q){case n3$.cc.F:case n3$.cc.f:this.state=n3$.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_INF:switch(Q){case n3$.cc.O:case n3$.cc.o:this.state=n3$.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_INFO:switch(Q){case n3$.cc.SPACE:case n3$.cc.TAB:this.state=n3$.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case n3$.State.OP_INFO_SPC:switch(Q){case n3$.cc.SPACE:case n3$.cc.TAB:continue;default:this.state=n3$.State.INFO_ARG,this.as=Z}break;case n3$.State.INFO_ARG:switch(Q){case n3$.cc.CR:this.drop=1;break;case n3$.cc.NL:{let X;if(this.argBuf)X=this.argBuf.bytes(),this.argBuf=void 0;else X=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:n3$.Kind.INFO,data:X}),this.drop=0,this.as=Z+1,this.state=n3$.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(Q)}break;default:throw this.fail($.subarray(Z))}}if((this.state===n3$.State.MSG_ARG||this.state===n3$.State.MINUS_ERR_ARG||this.state===n3$.State.INFO_ARG)&&!this.argBuf)this.argBuf=new y41.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===n3$.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new y41.DenoBuffer($.subarray(this.as))}}cloneMsgArg(){let $=this.ma.subject.length,Z=this.ma.reply?this.ma.reply.length:0,Q=new Uint8Array($+Z);if(Q.set(this.ma.subject),this.ma.reply)Q.set(this.ma.reply,$);if(this.argBuf=new y41.DenoBuffer(Q),this.ma.subject=Q.subarray(0,$),this.ma.reply)this.ma.reply=Q.subarray($)}processMsgArgs($){if(this.hdr>=0)return this.processHeaderMsgArgs($);let Z=[],Q=-1;for(let X=0;X<$.length;X++)switch($[X]){case n3$.cc.SPACE:case n3$.cc.TAB:case n3$.cc.CR:case n3$.cc.NL:if(Q>=0)Z.push($.subarray(Q,X)),Q=-1;break;default:if(Q<0)Q=X}if(Q>=0)Z.push($.subarray(Q));switch(Z.length){case 3:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.size=this.protoParseInt(Z[2],Oc);break;case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.size=this.protoParseInt(Z[3],Oc);break;default:throw this.fail($,"processMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processMsgArgs Bad or Missing Sid Error");if(this.ma.size<0)throw this.fail($,"processMsgArgs Bad or Missing Size Error")}fail($,Z=""){if(!Z)Z=`parse error [${this.state}]`;else Z=`${Z} [${this.state}]`;return Error(`${Z}: ${g41.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],Q=-1;for(let X=0;X<$.length;X++)switch($[X]){case n3$.cc.SPACE:case n3$.cc.TAB:case n3$.cc.CR:case n3$.cc.NL:if(Q>=0)Z.push($.subarray(Q,X)),Q=-1;break;default:if(Q<0)Q=X}if(Q>=0)Z.push($.subarray(Q));switch(Z.length){case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.hdr=this.protoParseInt(Z[2],Oc),this.ma.size=this.protoParseInt(Z[3],Oc);break;case 5:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.hdr=this.protoParseInt(Z[3],Oc),this.ma.size=this.protoParseInt(Z[4],Oc);break;default:throw this.fail($,"processHeaderMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Sid Error");if(this.ma.hdr<0||this.ma.hdr>this.ma.size)throw this.fail($,"processHeaderMsgArgs Bad or Missing Header Size Error");if(this.ma.size<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Size Error")}protoParseInt($,Z){if($.length===0||$.length>15)return-1;let Q=0;for(let X=0;X<$.length;X++){if($[X]<i3$||$[X]>nw4)return-1;Q=Q*10+($[X]-i3$)}return Z!==void 0&&Q>Z?-1:Q}}n3$.Parser=p3$;n3$.State={OP_START:0,OP_PLUS:1,OP_PLUS_O:2,OP_PLUS_OK:3,OP_MINUS:4,OP_MINUS_E:5,OP_MINUS_ER:6,OP_MINUS_ERR:7,OP_MINUS_ERR_SPC:8,MINUS_ERR_ARG:9,OP_M:10,OP_MS:11,OP_MSG:12,OP_MSG_SPC:13,MSG_ARG:14,MSG_PAYLOAD:15,MSG_END:16,OP_H:17,OP_P:18,OP_PI:19,OP_PIN:20,OP_PING:21,OP_PO:22,OP_PON:23,OP_PONG:24,OP_I:25,OP_IN:26,OP_INF:27,OP_INFO:28,OP_INFO_SPC:29,INFO_ARG:30};n3$.cc={CR:13,E:69,e:101,F:70,f:102,G:71,g:103,H:72,h:104,I:73,i:105,K:75,k:107,M:77,m:109,MINUS:45,N:78,n:110,NL:10,O:79,o:111,P:80,p:112,PLUS:43,R:82,r:114,S:83,s:115,SPACE:32,TAB:9}});var VK0=b((o3$)=>{Object.defineProperty(o3$,"__esModule",{value:!0});o3$.MsgHdrsImpl=void 0;o3$.canonicalMIMEHeaderKey=l41;o3$.headers=aw4;var t3$=sG(),OH=dj(),IK0=eG();function l41($){let F=!0,U=Array($.length);for(let N=0;N<$.length;N++){let B=$.charCodeAt(N);if(B===58||B<33||B>126)throw IK0.InvalidArgumentError.format("header",`'${$[N]}' is not a valid character in a header name`);if(F&&97<=B&&B<=122)B-=32;else if(!F&&65<=B&&B<=90)B+=32;U[N]=B,F=B==45}return String.fromCharCode(...U)}function aw4($=0,Z=""){if($===0&&Z!=="")throw IK0.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw IK0.InvalidArgumentError.format("description","is required");return new jc($,Z)}var u41="NATS/1.0";class jc{_code;headers;_description;constructor($=0,Z=""){this._code=$,this._description=Z,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals($){if($&&this.headers.size===$.headers.size&&this._code===$._code){for(let[Z,Q]of this.headers){let X=$.values(Z);if(Q.length!==X.length)return!1;let Y=[...Q].sort(),J=[...X].sort();for(let G=0;G<Y.length;G++)if(Y[G]!==J[G])return!1}return!0}return!1}static decode($){let Z=new jc,X=t3$.TD.decode($).split(`\r
|
|
2183
2183
|
`),Y=X[0];if(Y!==u41){let J=Y.replace(u41,"").trim();if(J.length>0){if(Z._code=parseInt(J,10),isNaN(Z._code))Z._code=0;let G=Z._code.toString();J=J.replace(G,""),Z._description=J.trim()}}if(X.length>=1)X.slice(1).map((J)=>{if(J){let G=J.indexOf(":");if(G>-1){let W=J.slice(0,G),K=J.slice(G+1).trim();Z.append(W,K)}}});return Z}toString(){if(this.headers.size===0&&this._code===0)return"";let $=u41;if(this._code>0&&this._description!=="")$+=` ${this._code} ${this._description}`;for(let[Z,Q]of this.headers)for(let X=0;X<Q.length;X++)$=`${$}\r
|
|
2184
2184
|
${Z}: ${Q[X]}`;return`${$}\r
|
|
@@ -3085,7 +3085,7 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
3085
3085
|
|
|
3086
3086
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
3087
3087
|
`);this.baseURL=J.baseURL,this._baseURLIsExplicit=Y.__baseURLIsExplicit??!!$,this.timeout=J.timeout??x31.DEFAULT_TIMEOUT,this.logger=J.logger??console,this.logLevel=z$0,this.logLevel=NL0(J.logLevel,"ClientOptions.logLevel",P6(this))??NL0(h4("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",P6(this))??z$0,this.fetchOptions=J.fetchOptions,this.maxRetries=J.maxRetries??2,this.fetch=J.fetch??$S$(),G1(this,rL0,QS$,"f"),this.middleware=[...J.middleware??[]];let G=h4("ANTHROPIC_CUSTOM_HEADERS");if(G){let K={};for(let H of G.split(`
|
|
3088
|
-
`)){let F=H.indexOf(":");if(F>=0)K[H.substring(0,F).trim()]=H.substring(F+1).trim()}J.defaultHeaders={...K,...J.defaultHeaders}}let W=Y.__auth;if(delete J.__auth,delete J.__baseURLIsExplicit,this._options=J,this.apiKey=typeof Z==="string"?Z:null,this.authToken=Q,this.webhookKey=X,W){if(this._authState=W,!this._baseURLIsExplicit&&W.baseURL)this.baseURL=W.baseURL}else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let K=J.credentials??null;if(K)this._authState.provider=K,this._authState.tokenCache=this._makeTokenCache(K);else if(J.config!=null){let H=YG1(J.config,this._credentialResolverOptions());this._authState.provider=H.provider,this._authState.tokenCache=this._makeTokenCache(H.provider),this._authState.extraHeaders=H.extraHeaders,this._applyCredentialBaseURL(H.baseURL)}else if(J.profile!=null)this._authState.resolution=this._resolveDefaultCredentials(J.profile);else this._authState.resolution=this._resolveDefaultCredentials()}}_applyCredentialBaseURL($){if(!$)return;let Z=$.replace(/\/+$/,"");if(this._authState.baseURL=Z,!this._baseURLIsExplicit)this.baseURL=Z}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:($)=>{P6(this).debug("credential cache write failed (best-effort)",$)},onSafetyWarning:($)=>{P6(this).warn($)}}}_credentialsFetch(){return WG1(this.fetch,this.middleware,void 0,this)}_makeTokenCache($){return new aJ1($,(Z)=>{P6(this).debug("advisory token refresh failed; serving cached token",Z)})}withOptions($){let Z="credentials"in $||"config"in $||"profile"in $,Q="apiKey"in $||"authToken"in $||Z,X={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...Z?{credentials:void 0,config:void 0,profile:void 0}:{},...$,__auth:Q?void 0:this._authState,__baseURLIsExplicit:"baseURL"in $?!0:this._baseURLIsExplicit};return new this.constructor(X)}async _resolveDefaultCredentials($){try{let Z=await gS$(this._credentialResolverOptions(),$);if(Z)this._authState.provider=Z.provider,this._authState.tokenCache=this._makeTokenCache(Z.provider),this._authState.extraHeaders=Z.extraHeaders,this._applyCredentialBaseURL(Z.baseURL);else if($!=null)throw new A1(`Profile "${$}" could not be resolved (no <config_dir>/configs/${$}.json found).`)}catch(Z){this._authState.error=Z}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){if($.get("x-api-key")||$.get("authorization"))return;if(this._authState.error)throw this._authState.error;if(this._authState.tokenCache||this._authState.resolution)return;if(this.apiKey&&$.get("x-api-key"))return;if(Z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(Z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}_authFlags($){let Z=this._requestAuthFlags.get($);if(!Z)Z={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set($,Z);return Z}async authHeaders($){if(this._authState.resolution)await this._authState.resolution;if(this._authState.error)return;if(this._authState.tokenCache&&this.apiKey==null){let Z=await this._authState.tokenCache.getToken();return this._authFlags($).usedTokenCache=!0,y0([{Authorization:`Bearer ${Z}`}])}return y0([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return y0([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return y0([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return BS$($)}getUserAgent(){return`${this.constructor.name}/JS ${ZK}`}defaultIdempotencyKey(){return`stainless-node-retry-${sd()}`}makeStatusError($,Z,Q,X){return qZ.generate($,Z,Q,X)}buildURL($,Z,Q){let X=!$0(this,v31,"m",jv$).call(this)&&Q||this.baseURL,Y=nC$($)?new URL($):new URL(X+(X.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery(),G=Object.fromEntries(Y.searchParams);if(!hJ1(J)||!hJ1(G))Z={...G,...J,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))Y.search=this.stringifyQuery(Z);return Y.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new A1("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:Q}){if(this._authState.tokenCache&&this.apiKey==null){let X=$.headers instanceof Headers?$.headers:new Headers($.headers);for(let[J,G]of Object.entries(this._authState.extraHeaders))if(!X.has(J))X.set(J,G);if(!X.get("anthropic-beta")?.split(",").map((J)=>J.trim())?.includes(bA))X.append("anthropic-beta",bA);$.headers=X}}backendMiddleware(){return[]}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,Q){return this.request(Promise.resolve(Q).then((X)=>{return{method:$,path:Z,...X}}))}request($,Z=null){return new yA(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Q){let X=await $,Y=X.maxRetries??this.maxRetries;if(Z==null)Z=Y,this._requestAuthFlags.delete(X);await this.prepareOptions(X);let{req:J,url:G,timeout:W}=await this.buildRequest(X,{retryCount:Y-Z}),K="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=Q===void 0?"":`, retryOf: ${Q}`,F=Date.now();if(X.signal?.aborted)throw new cX;let U=new AbortController,N=await this.fetchWithTimeout(G,J,W,U,X,{requestLogID:K,retryOfRequestLogID:Q}).catch(fA),B=Date.now();if(N instanceof globalThis.Error){let j=`retrying, ${Z} attempts remaining`;if(X.signal?.aborted)throw new cX;let w=$K(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):"")),E=this.middleware.length>0||!!X.middleware?.length||this.backendMiddleware().length>0;if(E&&!w&&!iS$(N))throw P6(this).info(`[${K}] middleware error (not retryable)`),P6(this).debug(`[${K}] middleware error (not retryable)`,GN({retryOfRequestLogID:Q,url:G,durationMs:B-F,message:N.message})),N;if(Z)return P6(this).info(`[${K}] connection ${w?"timed out":"failed"} - ${j}`),P6(this).debug(`[${K}] connection ${w?"timed out":"failed"} (${j})`,GN({retryOfRequestLogID:Q,url:G,durationMs:B-F,message:N.message})),this.retryRequest(X,Z,Q??K);if(P6(this).info(`[${K}] connection ${w?"timed out":"failed"} - error; no more retries left`),P6(this).debug(`[${K}] connection ${w?"timed out":"failed"} (error; no more retries left)`,GN({retryOfRequestLogID:Q,url:G,durationMs:B-F,message:N.message})),w)throw new W$0;if(E&&!GG1(N))throw N;throw new eL({cause:N})}let D=[...N.headers.entries()].filter(([j])=>j==="request-id").map(([j,w])=>", "+j+": "+JSON.stringify(w)).join(""),O=`[${K}${H}${D}] ${J.method} ${G} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${B-F}ms`;if(!N.ok){let j=await this.shouldRetry(N,X);if(Z&&j){let T=`retrying, ${Z} attempts remaining`;return await ZS$(N.body),P6(this).info(`${O} - ${T}`),P6(this).debug(`[${K}] response error (${T})`,GN({retryOfRequestLogID:Q,url:N.url,status:N.status,headers:N.headers,durationMs:B-F})),this.retryRequest(X,Z,Q??K,N.headers)}let w=j?"error; no more retries left":"error; not retryable";P6(this).info(`${O} - ${w}`);let E=await N.text().catch((T)=>fA(T).message),z=O$0(E),A=z?void 0:E;throw P6(this).debug(`[${K}] response error (${w})`,GN({retryOfRequestLogID:Q,url:N.url,status:N.status,headers:N.headers,message:A,durationMs:Date.now()-F})),this.makeStatusError(N.status,z,A,N.headers)}return P6(this).info(O),P6(this).debug(`[${K}] response start`,GN({retryOfRequestLogID:Q,url:N.url,status:N.status,headers:N.headers,durationMs:B-F})),{response:N,options:X,controller:U,requestLogID:K,retryOfRequestLogID:Q,startTime:F}}getAPIList($,Z,Q){return this.requestAPIList(Z,Q&&"then"in Q?Q.then((X)=>({method:"get",path:$,...X})):{method:"get",path:$,...Q})}requestAPIList($,Z){let Q=this.makeRequest(Z,null,void 0);return new wL0(this,Q,$)}async fetchWithTimeout($,Z,Q,X,Y,J){let{signal:G,method:W,...K}=Z||{},H=this._makeAbort(X);if(G)G.addEventListener("abort",H,{once:!0});let F=globalThis.ReadableStream&&K.body instanceof globalThis.ReadableStream||typeof K.body==="object"&&K.body!==null&&Symbol.asyncIterator in K.body,U={signal:X.signal,...F?{duplex:"half"}:{},method:"GET",...K};if(W)U.method=W.toUpperCase();let N=this.fetch,B=async(E,z)=>{let A=setTimeout(H,Q);try{return await N.call(void 0,E,z)}finally{clearTimeout(A)}},D=Y===void 0?B:async(E,z={})=>{let A=typeof E==="string"?E:E instanceof URL?E.href:E.url;if(z.headers=z.headers instanceof Headers?z.headers:new Headers(z.headers),await this.prepareRequest(z,{url:A,options:Y}),J)P6(this).debug(`[${J.requestLogID}] sending request`,GN({retryOfRequestLogID:J.retryOfRequestLogID,method:z.method,url:A,options:Y,headers:z.headers}));return B(E,z)},O=Y?.middleware,j=this.backendMiddleware(),w=O?.length||j.length?[...this.middleware,...O??[],...j]:this.middleware;return await WG1(D,w,Y,this)($,U)}async shouldRetry($,Z){let Q=this._authFlags(Z);if($.status===401&&this._authState.tokenCache&&Q.usedTokenCache&&!Q.didRefreshFor401)return Q.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let X=$.headers.get("x-should-retry");if(X==="true")return!0;if(X==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Q,X){let Y,J=X?.get("retry-after-ms");if(J){let W=parseFloat(J);if(!Number.isNaN(W))Y=W}let G=X?.get("retry-after");if(G&&!Y){let W=parseFloat(G);if(!Number.isNaN(W))Y=W*1000;else Y=Date.parse(G)-Date.now()}if(Y===void 0){let W=$.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis(Z,W)}return await $F(Y),this.makeRequest($,Z-1,Q)}calculateDefaultRetryTimeoutMillis($,Z){let Y=Z-$,J=Math.min(0.5*Math.pow(2,Y),8),G=1-Math.random()*0.25;return J*G*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new A1("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let Q={...$},{method:X,path:Y,query:J,defaultBaseURL:G}=Q;if(this._authState.resolution)await this._authState.resolution;if(!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL)this.baseURL=this._authState.baseURL;let W=this.buildURL(Y,J,G);if("timeout"in Q)oC$("timeout",Q.timeout);Q.timeout=Q.timeout??this.timeout;let{bodyHeaders:K,body:H}=this.buildBody({options:Q}),F=await this.buildHeaders({options:$,method:X,bodyHeaders:K,retryCount:Z});return{req:{method:X,headers:F,...Q.signal&&{signal:Q.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...Q.fetchOptions??{}},url:W,timeout:Q.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Q,retryCount:X}){let Y={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Y[this.idempotencyHeader]=$.idempotencyKey}let J=y0([Y,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(X),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...j$0(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Q,$.headers]);return this.validateHeaders(J),J.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Q=y0([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Q.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:XL0($)};else if(typeof $==="object"&&Q.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return $0(this,rL0,"f").call(this,{body:$,headers:Q})}}var v31,x31,rL0,jv$,wv$="\\n\\nHuman:",Ev$="\\n\\nAssistant:",QD;var f31=L(()=>{oJ();eH();QL0();tJ1();M9();$i();zS$();hS$();pS$();$9();BG1();Ov$();OL0();z31();_31();E31();S31();QL0();T6();WN();eH();x31=MZ,rL0=new WeakMap,v31=new WeakSet,jv$=function(){return this.baseURL!=="https://api.anthropic.com"};MZ.Anthropic=x31;MZ.HUMAN_PROMPT=wv$;MZ.AI_PROMPT=Ev$;MZ.DEFAULT_TIMEOUT=600000;MZ.AnthropicError=A1;MZ.APIError=qZ;MZ.APIConnectionError=eL;MZ.APIConnectionTimeoutError=W$0;MZ.APIUserAbortError=cX;MZ.NotFoundError=U$0;MZ.ConflictError=N$0;MZ.RateLimitError=L$0;MZ.BadRequestError=K$0;MZ.AuthenticationError=H$0;MZ.InternalServerError=D$0;MZ.PermissionDeniedError=F$0;MZ.UnprocessableEntityError=B$0;MZ.toFile=EL0;QD=class QD extends MZ{constructor(){super(...arguments);this.completions=new Ai(this),this.messages=new rA(this),this.models=new qi(this),this.beta=new g7(this)}};QD.Completions=Ai;QD.Messages=rA;QD.Models=qi;QD.Beta=g7});var zv$=L(()=>{M9();T$0();eH()});var SG1=L(()=>{f31();BG1();OL0();zv$();f31();$9();M9()});var Pv$;var Tv$=L(()=>{yJ1();SG1();Pv$={info:{id:"anthropic",name:"Anthropic",description:"Anthropic's Claude family of models",logo:"https://assets.decocache.com/decocms/51a209ae-14bc-4b6f-8216-8eb670695bd7/Anthropic-Icon--Streamline-Svg-Logos.svg"},supportedMethods:["api-key"],create($){let Z=G$0({apiKey:$}),Q=new QD({apiKey:$});return{info:this.info,aiSdk:Z,async listModels(){return(await Q.models.list()).data.map((Y)=>({modelId:Y.id,providerId:"anthropic",title:Y.display_name,description:null,logo:null,capabilities:[],limits:null,costs:null}))},async countTokens({messages:X,modelId:Y}){return{count:(await Q.messages.countTokens({messages:X,model:Y})).input_tokens}}}}}});import{z as WD}from"zod/v4";import{z as sA}from"zod/v4";import{z as nX}from"zod/v4";import{z as I8}from"zod/v4";import{z as d0}from"zod/v4";import{z as N6}from"zod/v4";import{z as m86}from"zod/v4";import{z as GD}from"zod/v4";import{z as Mi}from"zod/v4";import{z as vv$}from"zod/v4";import{z as eA}from"zod/v4";import{z as xv$}from"zod/v4";import{z as fv$}from"zod/v4";import{z as bv$}from"zod/v4";import{z as aY}from"zod/v4";import{z as A3}from"zod/v4";import{z as XD}from"zod/v4";import{z as YD}from"zod/v4";import{z as SE}from"zod/v4";import{z as D0}from"zod/v4";import{z as s1}from"zod/v4";import{z as h7}from"zod/v4";import{z as CE}from"zod/v4";import{z as iv$}from"zod/v4";function Vi($){return $.includes("/")?$:`models/${$}`}function Av$($){var Z,Q,X,Y,J;if($==null)return aU();let G=(Z=$.promptTokenCount)!=null?Z:0,W=(Q=$.candidatesTokenCount)!=null?Q:0,K=(X=$.toolUsePromptTokenCount)!=null?X:0,H=(Y=$.cachedContentTokenCount)!=null?Y:0,F=(J=$.thoughtsTokenCount)!=null?J:0,U=G+K;return{inputTokens:{total:U,noCache:U-H,cacheRead:H,cacheWrite:void 0},outputTokens:{total:W+F,text:W,reasoning:F},raw:$}}function O86($){let Z=D86.exec($);if(Z==null)return;return{mediaType:Z[1],data:Z[2]}}function j86($){let Z=O86($);if(Z==null)return;return{inlineData:{mimeType:Z.mediaType,data:Z.data}}}function w86($,Z,Q,X,Y=!0){let J=[],G=[];for(let W of Q)switch(W.type){case"text":{G.push(W.text);break}case"file":{if(W.data.type==="data")J.push({inlineData:{mimeType:r9({part:W}),data:B4(W.data.data)}});else if(W.data.type==="url"){let K=j86(W.data.url.toString());if(K!=null)J.push(K);else G.push(JSON.stringify(W))}else G.push(JSON.stringify(W));break}default:{G.push(JSON.stringify(W));break}}$.push({functionResponse:{...Y&&X!=null?{id:X}:{},name:Z,response:{name:Z,content:G.length>0?G.join(`
|
|
3088
|
+
`)){let F=H.indexOf(":");if(F>=0)K[H.substring(0,F).trim()]=H.substring(F+1).trim()}J.defaultHeaders={...K,...J.defaultHeaders}}let W=Y.__auth;if(delete J.__auth,delete J.__baseURLIsExplicit,this._options=J,this.apiKey=typeof Z==="string"?Z:null,this.authToken=Q,this.webhookKey=X,W){if(this._authState=W,!this._baseURLIsExplicit&&W.baseURL)this.baseURL=W.baseURL}else if(this._authState={provider:null,tokenCache:null,resolution:null,error:null,extraHeaders:{}},this.apiKey==null&&this.authToken==null){let K=J.credentials??null;if(K)this._authState.provider=K,this._authState.tokenCache=this._makeTokenCache(K);else if(J.config!=null){let H=YG1(J.config,this._credentialResolverOptions());this._authState.provider=H.provider,this._authState.tokenCache=this._makeTokenCache(H.provider),this._authState.extraHeaders=H.extraHeaders,this._applyCredentialBaseURL(H.baseURL)}else if(J.profile!=null)this._authState.resolution=this._resolveDefaultCredentials(J.profile);else this._authState.resolution=this._resolveDefaultCredentials()}}_applyCredentialBaseURL($){if(!$)return;let Z=$.replace(/\/+$/,"");if(this._authState.baseURL=Z,!this._baseURLIsExplicit)this.baseURL=Z}_credentialResolverOptions(){return{baseURL:this.baseURL,fetch:this._credentialsFetch(),userAgent:this.getUserAgent(),onCacheWriteError:($)=>{P6(this).debug("credential cache write failed (best-effort)",$)},onSafetyWarning:($)=>{P6(this).warn($)}}}_credentialsFetch(){return WG1(this.fetch,this.middleware,void 0,this)}_makeTokenCache($){return new aJ1($,(Z)=>{P6(this).debug("advisory token refresh failed; serving cached token",Z)})}withOptions($){let Z="credentials"in $||"config"in $||"profile"in $,Q="apiKey"in $||"authToken"in $||Z,X={...this._options,...this._baseURLIsExplicit?{baseURL:this.baseURL}:{},maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,middleware:this.middleware,apiKey:this.apiKey,authToken:this.authToken,webhookKey:this.webhookKey,credentials:this.credentials,...Z?{credentials:void 0,config:void 0,profile:void 0}:{},...$,__auth:Q?void 0:this._authState,__baseURLIsExplicit:"baseURL"in $?!0:this._baseURLIsExplicit};return new this.constructor(X)}async _resolveDefaultCredentials($){try{let Z=await gS$(this._credentialResolverOptions(),$);if(Z)this._authState.provider=Z.provider,this._authState.tokenCache=this._makeTokenCache(Z.provider),this._authState.extraHeaders=Z.extraHeaders,this._applyCredentialBaseURL(Z.baseURL);else if($!=null)throw new A1(`Profile "${$}" could not be resolved (no <config_dir>/configs/${$}.json found).`)}catch(Z){this._authState.error=Z}finally{this._authState.resolution=null}}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){if($.get("x-api-key")||$.get("authorization"))return;if(this._authState.error)throw this._authState.error;if(this._authState.tokenCache||this._authState.resolution)return;if(this.apiKey&&$.get("x-api-key"))return;if(Z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(Z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}_authFlags($){let Z=this._requestAuthFlags.get($);if(!Z)Z={usedTokenCache:!1,didRefreshFor401:!1},this._requestAuthFlags.set($,Z);return Z}async authHeaders($){if(this._authState.resolution)await this._authState.resolution;if(this._authState.error)return;if(this._authState.tokenCache&&this.apiKey==null){let Z=await this._authState.tokenCache.getToken();return this._authFlags($).usedTokenCache=!0,y0([{Authorization:`Bearer ${Z}`}])}return y0([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return y0([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return y0([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return BS$($)}getUserAgent(){return`${this.constructor.name}/JS ${ZK}`}defaultIdempotencyKey(){return`stainless-node-retry-${sd()}`}makeStatusError($,Z,Q,X){return qZ.generate($,Z,Q,X)}buildURL($,Z,Q){let X=!$0(this,v31,"m",jv$).call(this)&&Q||this.baseURL,Y=nC$($)?new URL($):new URL(X+(X.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),J=this.defaultQuery(),G=Object.fromEntries(Y.searchParams);if(!hJ1(J)||!hJ1(G))Z={...G,...J,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))Y.search=this.stringifyQuery(Z);return Y.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new A1("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:Q}){if(this._authState.tokenCache&&this.apiKey==null){let X=$.headers instanceof Headers?$.headers:new Headers($.headers);for(let[J,G]of Object.entries(this._authState.extraHeaders))if(!X.has(J))X.set(J,G);if(!X.get("anthropic-beta")?.split(",").map((J)=>J.trim())?.includes(bA))X.append("anthropic-beta",bA);$.headers=X}}backendMiddleware(){return[]}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,Q){return this.request(Promise.resolve(Q).then((X)=>{return{method:$,path:Z,...X}}))}request($,Z=null){return new yA(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Q){let X=await $,Y=X.maxRetries??this.maxRetries;if(Z==null)Z=Y,this._requestAuthFlags.delete(X);await this.prepareOptions(X);let{req:J,url:G,timeout:W}=await this.buildRequest(X,{retryCount:Y-Z}),K="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=Q===void 0?"":`, retryOf: ${Q}`,F=Date.now();if(X.signal?.aborted)throw new cX;let U=new AbortController,N=await this.fetchWithTimeout(G,J,W,U,X,{requestLogID:K,retryOfRequestLogID:Q}).catch(fA),B=Date.now();if(N instanceof globalThis.Error){let j=`retrying, ${Z} attempts remaining`;if(X.signal?.aborted)throw new cX;let w=$K(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):"")),E=this.middleware.length>0||!!X.middleware?.length||this.backendMiddleware().length>0;if(E&&!w&&!iS$(N))throw P6(this).info(`[${K}] middleware error (not retryable)`),P6(this).debug(`[${K}] middleware error (not retryable)`,GN({retryOfRequestLogID:Q,url:G,durationMs:B-F,message:N.message})),N;if(Z)return P6(this).info(`[${K}] connection ${w?"timed out":"failed"} - ${j}`),P6(this).debug(`[${K}] connection ${w?"timed out":"failed"} (${j})`,GN({retryOfRequestLogID:Q,url:G,durationMs:B-F,message:N.message})),this.retryRequest(X,Z,Q??K);if(P6(this).info(`[${K}] connection ${w?"timed out":"failed"} - error; no more retries left`),P6(this).debug(`[${K}] connection ${w?"timed out":"failed"} (error; no more retries left)`,GN({retryOfRequestLogID:Q,url:G,durationMs:B-F,message:N.message})),w)throw new W$0;if(E&&!GG1(N))throw N;throw new eL({cause:N})}let D=[...N.headers.entries()].filter(([j])=>j==="request-id").map(([j,w])=>", "+j+": "+JSON.stringify(w)).join(""),O=`[${K}${H}${D}] ${J.method} ${G} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${B-F}ms`;if(!N.ok){let j=await this.shouldRetry(N,X);if(Z&&j){let T=`retrying, ${Z} attempts remaining`;return await ZS$(N.body),P6(this).info(`${O} - ${T}`),P6(this).debug(`[${K}] response error (${T})`,GN({retryOfRequestLogID:Q,url:N.url,status:N.status,headers:N.headers,durationMs:B-F})),this.retryRequest(X,Z,Q??K,N.headers)}let w=j?"error; no more retries left":"error; not retryable";P6(this).info(`${O} - ${w}`);let E=await N.text().catch((T)=>fA(T).message),z=O$0(E),A=z?void 0:E;throw P6(this).debug(`[${K}] response error (${w})`,GN({retryOfRequestLogID:Q,url:N.url,status:N.status,headers:N.headers,message:A,durationMs:Date.now()-F})),this.makeStatusError(N.status,z,A,N.headers)}return P6(this).info(O),P6(this).debug(`[${K}] response start`,GN({retryOfRequestLogID:Q,url:N.url,status:N.status,headers:N.headers,durationMs:B-F})),{response:N,options:X,controller:U,requestLogID:K,retryOfRequestLogID:Q,startTime:F}}getAPIList($,Z,Q){return this.requestAPIList(Z,Q&&"then"in Q?Q.then((X)=>({method:"get",path:$,...X})):{method:"get",path:$,...Q})}requestAPIList($,Z){let Q=this.makeRequest(Z,null,void 0);return new wL0(this,Q,$)}async fetchWithTimeout($,Z,Q,X,Y,J){let{signal:G,method:W,...K}=Z||{},H=this._makeAbort(X);if(G)G.addEventListener("abort",H,{once:!0});let F=globalThis.ReadableStream&&K.body instanceof globalThis.ReadableStream||typeof K.body==="object"&&K.body!==null&&Symbol.asyncIterator in K.body,U={signal:X.signal,...F?{duplex:"half"}:{},method:"GET",...K};if(W)U.method=W.toUpperCase();let N=this.fetch,B=async(E,z)=>{let A=setTimeout(H,Q);try{return await N.call(void 0,E,z)}finally{clearTimeout(A)}},D=Y===void 0?B:async(E,z={})=>{let A=typeof E==="string"?E:E instanceof URL?E.href:E.url;if(z.headers=z.headers instanceof Headers?z.headers:new Headers(z.headers),await this.prepareRequest(z,{url:A,options:Y}),J)P6(this).debug(`[${J.requestLogID}] sending request`,GN({retryOfRequestLogID:J.retryOfRequestLogID,method:z.method,url:A,options:Y,headers:z.headers}));return B(E,z)},O=Y?.middleware,j=this.backendMiddleware(),w=O?.length||j.length?[...this.middleware,...O??[],...j]:this.middleware;return await WG1(D,w,Y,this)($,U)}async shouldRetry($,Z){let Q=this._authFlags(Z);if($.status===401&&this._authState.tokenCache&&Q.usedTokenCache&&!Q.didRefreshFor401)return Q.didRefreshFor401=!0,this._authState.tokenCache.invalidate(),!0;let X=$.headers.get("x-should-retry");if(X==="true")return!0;if(X==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Q,X){let Y,J=X?.get("retry-after-ms");if(J){let W=parseFloat(J);if(!Number.isNaN(W))Y=W}let G=X?.get("retry-after");if(G&&!Y){let W=parseFloat(G);if(!Number.isNaN(W))Y=W*1000;else Y=Date.parse(G)-Date.now()}if(Y===void 0){let W=$.maxRetries??this.maxRetries;Y=this.calculateDefaultRetryTimeoutMillis(Z,W)}return await $F(Y),this.makeRequest($,Z-1,Q)}calculateDefaultRetryTimeoutMillis($,Z){let Y=Z-$,J=Math.min(0.5*Math.pow(2,Y),8),G=1-Math.random()*0.25;return J*G*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new A1("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let Q={...$},{method:X,path:Y,query:J,defaultBaseURL:G}=Q;if(this._authState.resolution)await this._authState.resolution;if(!this._baseURLIsExplicit&&this._authState.baseURL&&this.baseURL!==this._authState.baseURL)this.baseURL=this._authState.baseURL;let W=this.buildURL(Y,J,G);if("timeout"in Q)oC$("timeout",Q.timeout);Q.timeout=Q.timeout??this.timeout;let{bodyHeaders:K,body:H}=this.buildBody({options:Q}),F=await this.buildHeaders({options:$,method:X,bodyHeaders:K,retryCount:Z});return{req:{method:X,headers:F,...Q.signal&&{signal:Q.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...Q.fetchOptions??{}},url:W,timeout:Q.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Q,retryCount:X}){let Y={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Y[this.idempotencyHeader]=$.idempotencyKey}let J=y0([Y,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(X),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...j$0(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Q,$.headers]);return this.validateHeaders(J),J.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Q=y0([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Q.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:XL0($)};else if(typeof $==="object"&&Q.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return $0(this,rL0,"f").call(this,{body:$,headers:Q})}}var v31,x31,rL0,jv$,wv$="\\n\\nHuman:",Ev$="\\n\\nAssistant:",QD;var f31=L(()=>{oJ();eH();QL0();tJ1();M9();$i();zS$();hS$();pS$();$9();BG1();Ov$();OL0();z31();_31();E31();S31();QL0();T6();WN();eH();x31=MZ,rL0=new WeakMap,v31=new WeakSet,jv$=function(){return this.baseURL!=="https://api.anthropic.com"};MZ.Anthropic=x31;MZ.HUMAN_PROMPT=wv$;MZ.AI_PROMPT=Ev$;MZ.DEFAULT_TIMEOUT=600000;MZ.AnthropicError=A1;MZ.APIError=qZ;MZ.APIConnectionError=eL;MZ.APIConnectionTimeoutError=W$0;MZ.APIUserAbortError=cX;MZ.NotFoundError=U$0;MZ.ConflictError=N$0;MZ.RateLimitError=L$0;MZ.BadRequestError=K$0;MZ.AuthenticationError=H$0;MZ.InternalServerError=D$0;MZ.PermissionDeniedError=F$0;MZ.UnprocessableEntityError=B$0;MZ.toFile=EL0;QD=class QD extends MZ{constructor(){super(...arguments);this.completions=new Ai(this),this.messages=new rA(this),this.models=new qi(this),this.beta=new g7(this)}};QD.Completions=Ai;QD.Messages=rA;QD.Models=qi;QD.Beta=g7});var zv$=L(()=>{M9();T$0();eH()});var SG1=L(()=>{f31();BG1();OL0();zv$();f31();$9();M9()});var Pv$;var Tv$=L(()=>{yJ1();SG1();Pv$={info:{id:"anthropic",name:"Anthropic",description:"Anthropic's Claude family of models",logo:"https://assets.decocache.com/decocms/51a209ae-14bc-4b6f-8216-8eb670695bd7/Anthropic-Icon--Streamline-Svg-Logos.svg"},supportedMethods:["api-key"],create($){let Z=G$0({apiKey:$}),Q=new QD({apiKey:$});return{info:this.info,aiSdk:Z,async listModels(){let X=[];for await(let Y of Q.models.list())X.push({modelId:Y.id,providerId:"anthropic",title:Y.display_name,description:null,logo:null,capabilities:[],limits:null,costs:null});return X},async countTokens({messages:X,modelId:Y}){return{count:(await Q.messages.countTokens({messages:X,model:Y})).input_tokens}}}}}});import{z as WD}from"zod/v4";import{z as sA}from"zod/v4";import{z as nX}from"zod/v4";import{z as I8}from"zod/v4";import{z as d0}from"zod/v4";import{z as N6}from"zod/v4";import{z as m86}from"zod/v4";import{z as GD}from"zod/v4";import{z as Mi}from"zod/v4";import{z as vv$}from"zod/v4";import{z as eA}from"zod/v4";import{z as xv$}from"zod/v4";import{z as fv$}from"zod/v4";import{z as bv$}from"zod/v4";import{z as aY}from"zod/v4";import{z as A3}from"zod/v4";import{z as XD}from"zod/v4";import{z as YD}from"zod/v4";import{z as SE}from"zod/v4";import{z as D0}from"zod/v4";import{z as s1}from"zod/v4";import{z as h7}from"zod/v4";import{z as CE}from"zod/v4";import{z as iv$}from"zod/v4";function Vi($){return $.includes("/")?$:`models/${$}`}function Av$($){var Z,Q,X,Y,J;if($==null)return aU();let G=(Z=$.promptTokenCount)!=null?Z:0,W=(Q=$.candidatesTokenCount)!=null?Q:0,K=(X=$.toolUsePromptTokenCount)!=null?X:0,H=(Y=$.cachedContentTokenCount)!=null?Y:0,F=(J=$.thoughtsTokenCount)!=null?J:0,U=G+K;return{inputTokens:{total:U,noCache:U-H,cacheRead:H,cacheWrite:void 0},outputTokens:{total:W+F,text:W,reasoning:F},raw:$}}function O86($){let Z=D86.exec($);if(Z==null)return;return{mediaType:Z[1],data:Z[2]}}function j86($){let Z=O86($);if(Z==null)return;return{inlineData:{mimeType:Z.mediaType,data:Z.data}}}function w86($,Z,Q,X,Y=!0){let J=[],G=[];for(let W of Q)switch(W.type){case"text":{G.push(W.text);break}case"file":{if(W.data.type==="data")J.push({inlineData:{mimeType:r9({part:W}),data:B4(W.data.data)}});else if(W.data.type==="url"){let K=j86(W.data.url.toString());if(K!=null)J.push(K);else G.push(JSON.stringify(W))}else G.push(JSON.stringify(W));break}default:{G.push(JSON.stringify(W));break}}$.push({functionResponse:{...Y&&X!=null?{id:X}:{},name:Z,response:{name:Z,content:G.length>0?G.join(`
|
|
3089
3089
|
`):"Tool executed successfully."},...J.length>0?{parts:J}:{}}})}function E86($,Z,Q,X,Y=!0){for(let J of Q)switch(J.type){case"text":$.push({functionResponse:{...Y&&X!=null?{id:X}:{},name:Z,response:{name:Z,content:J.text}}});break;case"file":{if(J.data.type==="data"){let G=aQ(J.mediaType);$.push({inlineData:{mimeType:r9({part:J}),data:B4(J.data.data)}},{text:`Tool executed successfully and returned this ${G==="image"?"image":"file"} as a response`})}else $.push({text:JSON.stringify(J)});break}default:$.push({text:JSON.stringify(J)});break}}function z86($,Z){var Q,X,Y,J,G,W;let K=[],H=[],F=!0,U=(Q=Z==null?void 0:Z.isGemmaModel)!=null?Q:!1,N=(X=Z==null?void 0:Z.isGemini3Model)!=null?X:!1,B=Z==null?void 0:Z.onWarning,D=(Y=Z==null?void 0:Z.providerOptionsNames)!=null?Y:["google"],O=!D.includes("google"),j=(J=Z==null?void 0:Z.supportsFunctionResponseParts)!=null?J:!0,w=(G=Z==null?void 0:Z.includeFunctionCallIds)!=null?G:!0,E=!1,z=[],A=(T)=>{return z.push(T),E=!0,L86},P=(T)=>{var q,f,S,V,u;for(let g of D){let l=(q=T.providerOptions)==null?void 0:q[g];if(l!=null)return l}if(O)return(f=T.providerOptions)==null?void 0:f.google;return(u=(S=T.providerOptions)==null?void 0:S.googleVertex)!=null?u:(V=T.providerOptions)==null?void 0:V.vertex};for(let{role:T,content:q}of $)switch(T){case"system":{if(!F)throw new Z$({functionality:"system messages are only supported at the beginning of the conversation"});K.push({text:q});break}case"user":{F=!1;let f=[];for(let S of q)switch(S.type){case"text":{f.push({text:S.text});break}case"file":{switch(S.data.type){case"url":{f.push({fileData:{mimeType:r9({part:S}),fileUri:S.data.url.toString()}});break}case"reference":{if(O)throw new Z$({functionality:"file parts with provider references"});f.push({fileData:{mimeType:r9({part:S}),fileUri:rQ({reference:S.data.reference,provider:"google"})}});break}case"text":{f.push({inlineData:{mimeType:nJ(S.mediaType)?S.mediaType:"text/plain",data:B4(new TextEncoder().encode(S.data.text))}});break}case"data":{f.push({inlineData:{mimeType:r9({part:S}),data:B4(S.data.data)}});break}}break}}H.push({role:"user",parts:f});break}case"assistant":{F=!1;let f=!1;H.push({role:"model",parts:q.map((S)=>{let V=P(S),u=(V==null?void 0:V.thoughtSignature)!=null?String(V.thoughtSignature):void 0;switch(S.type){case"text":return S.text.length===0?void 0:{text:S.text,thoughtSignature:u};case"reasoning":return S.text.length===0?void 0:{text:S.text,thought:!0,thoughtSignature:u};case"reasoning-file":{switch(S.data.type){case"url":throw new Z$({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:S.mediaType,data:B4(S.data.data)},thought:!0,thoughtSignature:u}}break}case"file":{switch(S.data.type){case"url":throw new Z$({functionality:"File data URLs in assistant messages are not supported"});case"reference":{if(O)throw new Z$({functionality:"file parts with provider references"});return{fileData:{mimeType:S.mediaType,fileUri:rQ({reference:S.data.reference,provider:"google"})},...(V==null?void 0:V.thought)===!0?{thought:!0}:{},thoughtSignature:u}}case"text":return{inlineData:{mimeType:nJ(S.mediaType)?S.mediaType:"text/plain",data:B4(new TextEncoder().encode(S.data.text))},...(V==null?void 0:V.thought)===!0?{thought:!0}:{},thoughtSignature:u};case"data":return{inlineData:{mimeType:S.mediaType,data:B4(S.data.data)},...(V==null?void 0:V.thought)===!0?{thought:!0}:{},thoughtSignature:u}}break}case"tool-call":{let g=(V==null?void 0:V.serverToolCallId)!=null?String(V.serverToolCallId):void 0,l=(V==null?void 0:V.serverToolType)!=null?String(V.serverToolType):void 0,h=g!=null&&l!=null,i=!h&&u==null&&f,H0=u!=null?u:N&&!i?A(S.toolName):void 0;if(!h&&u!=null)f=!0;if(h)return{toolCall:{toolType:l,args:typeof S.input==="string"?tJ(S.input):S.input,id:g},thoughtSignature:H0};return{functionCall:{...w&&S.toolCallId!=null?{id:S.toolCallId}:{},name:S.toolName,args:S.input},thoughtSignature:H0}}case"tool-result":{let g=(V==null?void 0:V.serverToolCallId)!=null?String(V.serverToolCallId):void 0,l=(V==null?void 0:V.serverToolType)!=null?String(V.serverToolType):void 0;if(g&&l)return{toolResponse:{toolType:l,response:S.output.type==="json"?S.output.value:{},id:g},thoughtSignature:u};return}}}).filter((S)=>S!==void 0)});break}case"tool":{F=!1;let f=[];for(let S of q){if(S.type==="tool-approval-response")continue;let V=P(S),u=(V==null?void 0:V.serverToolCallId)!=null?String(V.serverToolCallId):void 0,g=(V==null?void 0:V.serverToolType)!=null?String(V.serverToolType):void 0;if(u&&g){let h=(V==null?void 0:V.thoughtSignature)!=null?String(V.thoughtSignature):void 0;if(H.length>0){let i=H[H.length-1];if(i.role==="model"){i.parts.push({toolResponse:{toolType:g,response:S.output.type==="json"?S.output.value:{},id:u},thoughtSignature:h});continue}}}let l=S.output;if(l.type==="content")if(j)w86(f,S.toolName,l.value,S.toolCallId,w);else E86(f,S.toolName,l.value,S.toolCallId,w);else f.push({functionResponse:{...w&&S.toolCallId!=null?{id:S.toolCallId}:{},name:S.toolName,response:{name:S.toolName,content:l.type==="execution-denied"?(W=l.reason)!=null?W:"Tool call execution denied.":l.value}}})}H.push({role:"user",parts:f});break}}if(U&&K.length>0&&H.length>0&&H[0].role==="user"){let T=K.map((q)=>q.text).join(`
|
|
3090
3090
|
|
|
3091
3091
|
`);H[0].parts.unshift({text:T+`
|
|
@@ -3115,7 +3115,7 @@ ${G}
|
|
|
3115
3115
|
${Z}:`]}}function Vx$($){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 I56($){return!("error"in $)&&$.choices.some((Z)=>Z.text.length>0)}function $W1($){let Z=encodeURIComponent($);return Z==="."?"%252E":Z===".."?"%252E%252E":Z}function b56($){return f56.some((Z)=>$.startsWith(Z))}function y56($){var Z;return(Z=x56[$])!=null?Z:$.startsWith("gpt-image-")?10:1}function _x$($,Z,Q){if($==null)return{};let X={};if($.image_tokens!=null){let Y=Math.floor($.image_tokens/Q),J=$.image_tokens-Y*(Q-1);X.imageTokens=Z===Q-1?J:Y}if($.text_tokens!=null){let Y=Math.floor($.text_tokens/Q),J=$.text_tokens-Y*(Q-1);X.textTokens=Z===Q-1?J:Y}return X}async function l56($,Z){if(!$)return;if($.type==="url")return Q$0($.url,{abortSignal:Z});let Q=$.data instanceof Uint8Array?$.data:a9($.data);return new Blob([Q],{type:$.mediaType})}function UW1($){var Z,Q,X,Y,J,G;if($==null)return aU();let{input_tokens:W,output_tokens:K}=$,H=(Q=(Z=$.input_tokens_details)==null?void 0:Z.cached_tokens)!=null?Q:0,F=(Y=(X=$.input_tokens_details)==null?void 0:X.cache_write_tokens)!=null?Y: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 KD0({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 h96($){if(typeof $.type!=="string"||!y96.has($.type))return!1;if($.type!=="response.output_item.added"&&$.type!=="response.output_item.done")return!0;if(!UQ($.item)||typeof $.item.type!=="string")return!0;return g96.has($.item.type)}function l96($){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 wW1({providerOptions:$,providerOptionsName:Z}){var Q;let X=(Q=$==null?void 0:$[Z])==null?void 0:Q.parallelToolCall;if(!aW(X)||typeof X.itemId!=="string"||typeof X.toolCallId!=="string"||typeof X.toolName!=="string"||typeof X.input!=="string"||typeof X.index!=="number"||!Number.isInteger(X.index)||typeof X.count!=="number"||!Number.isInteger(X.count)||X.index<0||X.count<=X.index)return;return X}function EW1({toolName:$,tools:Z}){return $===xx$&&!Z.some((Q)=>Q.name===xx$)}async function bx$({toolCall:$,tools:Z,providerOptionsName:Q,itemId:X}){if(!EW1({toolName:$.toolName,tools:Z}))return;let Y=await f5({text:$.input});if(!Y.success||!aW(Y.value))return;let J=Y.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(!aW(H))return;let{recipient_name:F,parameters:U}=H;if(typeof F!=="string"||!F.startsWith(fx$)||!aW(U))return;let N=F.slice(fx$.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:X,toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,index:K,count:J.length}}}})}return W}function c96($){return JSON.stringify($===void 0?{}:$)}function yx$($){return $==null?void 0:$.type==="program"?{type:"program",caller_id:$.callerId}:$}async function gx$({output:$,toolName:Z,outputSchemaToolNames:Q,promptCacheBreakpoint:X,providerOptionsName:Y,warnings:J}){var G;let W=Q==null?void 0:Q.has(Z),K=(H)=>X==null?H:[{type:"input_text",text:H,prompt_cache_breakpoint:X}];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=vE(H.providerOptions,Y);switch(H.type){case"text":return{type:"input_text",text:H.text,...B!=null&&{prompt_cache_breakpoint:B}};case"file":{let D=aQ(H.mediaType),O=(U=(F=H.providerOptions)==null?void 0:F[Y])==null?void 0:U.imageDetail;if(H.data.type==="reference"){let j=rQ({reference:H.data.reference,provider:Y});if(D==="image")return{type:"input_image",file_id:j,detail:O,...B!=null&&{prompt_cache_breakpoint:B}};return{type:"input_file",file_id:j,...B!=null&&{prompt_cache_breakpoint:B}}}if(H.data.type==="data"){let j=r9({part:H});if(D==="image")return{type:"input_image",image_url:`data:${j};base64,${B4(H.data.data)}`,detail:O,...B!=null&&{prompt_cache_breakpoint:B}};return{type:"input_file",filename:(N=H.filename)!=null?N:"data",file_data:`data:${j};base64,${B4(H.data.data)}`,...B!=null&&{prompt_cache_breakpoint:B}}}if(H.data.type==="url"){if(D==="image")return{type:"input_image",image_url:H.data.url.toString(),detail:O,...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(NE)}}function zW1($,Z){return $.itemId===Z.itemId&&$.toolCallId===Z.toolCallId&&$.toolName===Z.toolName&&$.input===Z.input&&$.count===Z.count}function m96({prompt:$,providerOptionsName:Z}){let Q=new Map;for(let Y of $){if(Y.role!=="tool")continue;for(let J of Y.content){if(J.type!=="tool-result")continue;let G=wW1({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(!zW1(W.metadata,G)||W.results.has(G.index)){W.invalid=!0;continue}W.results.set(G.index,J)}}let X=new Map;for(let[Y,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(NE))X.set(Y,{metadata:J.metadata,results:G})}return X}function vE($,Z){var Q;return(Q=$==null?void 0:$[Z])==null?void 0:Q.promptCacheBreakpoint}function XW1({output:$,toolResultProviderOptions:Z,providerOptionsName:Q}){var X;return $.type==="content"?void 0:(X=vE($.providerOptions,Q))!=null?X:vE(Z,Q)}function hx$($,Z){if(!Z)return!1;return Z.some((Q)=>$.startsWith(Q))}async function d96({prompt:$,toolNameMapping:Z,systemMessageMode:Q,providerOptionsName:X,explicitMessageItemType:Y=!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:D,customProviderToolNames:O,outputSchemaToolNames:j}){var w,E,z,A,P,T,q,f,S,V,u,g,l,h,i,H0,R0,Y0,N0,n,t,a,s,X0,p0,v0,H1,c0,w0,z0,m0,j1,Y1,f0,i0,n0,$1,G0,Q0,F0,U0,I0;let q0=[],O1=[],g$=new Set,o$=new Set,T8=K||H?m96({prompt:$,providerOptionsName:X}):new Map,B8=new Set,I5=new Set;for(let{role:m8,content:s6,providerOptions:v9}of $)switch(m8){case"system":{switch(Q){case"system":{let r0=vE(v9,X);q0.push({...Y&&{type:"message"},role:"system",content:r0==null?s6:[{type:"input_text",text:s6,prompt_cache_breakpoint:r0}]});break}case"developer":{let r0=vE(v9,X);q0.push({...Y&&{type:"message"},role:"developer",content:r0==null?s6:[{type:"input_text",text:s6,prompt_cache_breakpoint:r0}]});break}case"remove":{O1.push({type:"other",message:"system messages are removed for this model"});break}default:throw Error(`Unsupported system message mode: ${Q}`)}break}case"user":{q0.push({...Y&&{type:"message"},role:"user",content:s6.map((r0,P1)=>{var m$,i1,N$,u8,K5;switch(r0.type){case"text":{let D4=vE(r0.providerOptions,X);return{type:"input_text",text:r0.text,...D4!=null&&{prompt_cache_breakpoint:D4}}}case"file":{let D4=vE(r0.providerOptions,X);switch(r0.data.type){case"reference":{let W$=rQ({reference:r0.data.reference,provider:X});if(aQ(r0.mediaType)==="image")return{type:"input_image",file_id:W$,detail:(i1=(m$=r0.providerOptions)==null?void 0:m$[X])==null?void 0:i1.imageDetail,...D4!=null&&{prompt_cache_breakpoint:D4}};return{type:"input_file",file_id:W$,...D4!=null&&{prompt_cache_breakpoint:D4}}}case"text":throw new Z$({functionality:"text file parts"});case"url":case"data":if(aQ(r0.mediaType)==="image")return{type:"input_image",...r0.data.type==="url"?{image_url:r0.data.url.toString()}:typeof r0.data.data==="string"&&hx$(r0.data.data,J)?{file_id:r0.data.data}:{image_url:`data:${r9({part:r0})};base64,${B4(r0.data.data)}`},detail:(u8=(N$=r0.providerOptions)==null?void 0:N$[X])==null?void 0:u8.imageDetail,...D4!=null&&{prompt_cache_breakpoint:D4}};else{if(r0.data.type==="url")return{type:"input_file",file_url:r0.data.url.toString(),...D4!=null&&{prompt_cache_breakpoint:D4}};let S8=r9({part:r0});if(S8!=="application/pdf"&&!G)throw new Z$({functionality:`file part media type ${S8}`});return{type:"input_file",...typeof r0.data.data==="string"&&hx$(r0.data.data,J)?{file_id:r0.data.data}:{filename:(K5=r0.filename)!=null?K5:S8==="application/pdf"?`part-${P1}.pdf`:`part-${P1}`,file_data:`data:${S8};base64,${B4(r0.data.data)}`},...D4!=null&&{prompt_cache_breakpoint:D4}}}}}}})});break}case"assistant":{let r0={};for(let P1 of s6)switch(P1.type){case"text":{let m$=(w=P1.providerOptions)==null?void 0:w[X],i1=m$==null?void 0:m$.itemId,N$=m$==null?void 0:m$.phase;if(K&&i1!=null)break;if(W&&i1!=null){q0.push({type:"item_reference",id:i1});break}q0.push({...Y&&{type:"message"},role:"assistant",content:P1.text,...N$!=null&&{phase:N$}});break}case"tool-call":{let m$=wW1({providerOptions:P1.providerOptions,providerOptionsName:X}),i1=m$==null?void 0:T8.get(m$.toolCallId);if(m$!=null&&i1!=null&&zW1(i1.metadata,m$)){if(!B8.has(i1.metadata.toolCallId)){if(B8.add(i1.metadata.toolCallId),!K)q0.push({type:"function_call",call_id:i1.metadata.toolCallId,name:i1.metadata.toolName,arguments:i1.metadata.input})}break}let N$=(T=(z=(E=P1.providerOptions)==null?void 0:E[X])==null?void 0:z.itemId)!=null?T:(P=(A=P1.providerMetadata)==null?void 0:A[X])==null?void 0:P.itemId,u8=(u=(f=(q=P1.providerOptions)==null?void 0:q[X])==null?void 0:f.namespace)!=null?u:(V=(S=P1.providerMetadata)==null?void 0:S[X])==null?void 0:V.namespace,K5=(H0=(l=(g=P1.providerOptions)==null?void 0:g[X])==null?void 0:l.async)!=null?H0:(i=(h=P1.providerMetadata)==null?void 0:h[X])==null?void 0:i.async,D4=(Y0=(R0=P1.providerOptions)==null?void 0:R0[X])==null?void 0:Y0.caller;if((D4==null?void 0:D4.type)==="program")o$.add(P1.toolCallId);if(K&&N$!=null)break;let W$=Z.toProviderToolName(P1.toolName);if(P1.toolName===D){if(W&&N$!=null){q0.push({type:"item_reference",id:N$});break}let X8=typeof P1.input==="string"?await r10({text:P1.input,schema:KW1}):await U8({value:P1.input,schema:KW1}),O$=X8.call_id!=null?"client":"server";q0.push({type:"tool_search_call",id:N$!=null?N$:P1.toolCallId,execution:O$,call_id:(N0=X8.call_id)!=null?N0:null,status:"completed",arguments:X8.arguments});break}if(W$==="programmatic_tool_calling"){if(W&&N$!=null){q0.push({type:"item_reference",id:N$});break}let X8=await U8({value:P1.input,schema:Lf$});q0.push({type:"program",id:N$!=null?N$:P1.toolCallId,call_id:P1.toolCallId,code:X8.code,fingerprint:X8.fingerprint});break}if(P1.providerExecuted){if(W&&N$!=null)q0.push({type:"item_reference",id:N$});if(W||!U||W$!=="shell")break}let S8=F&&W$==="local_shell"||U&&W$==="shell"||N&&W$==="apply_patch"||B&&W$==="computer"||((n=O==null?void 0:O.has(W$))!=null?n:!1);if(H&&W&&N$!=null&&S8)break;if(W&&N$!=null&&S8){q0.push({type:"item_reference",id:N$});break}if(F&&W$==="local_shell"){let X8=await U8({value:P1.input,schema:Uf$});q0.push({type:"local_shell_call",call_id:P1.toolCallId,id:N$,action:{type:"exec",command:X8.action.command,timeout_ms:X8.action.timeoutMs,user:X8.action.user,working_directory:X8.action.workingDirectory,env:X8.action.env}});break}if(U&&W$==="shell"){let X8=await U8({value:P1.input,schema:Bf$});q0.push({type:"shell_call",call_id:P1.toolCallId,id:N$,status:"completed",action:{commands:X8.action.commands,timeout_ms:X8.action.timeoutMs,max_output_length:X8.action.maxOutputLength}});break}if(N&&W$==="apply_patch"){let X8=await U8({value:P1.input,schema:Yf$});q0.push({type:"apply_patch_call",call_id:X8.callId,id:N$,status:"completed",operation:X8.operation});break}if(B&&W$==="computer"){let X8=await U8({value:P1.input,schema:Wf$});q0.push({type:"computer_call",call_id:P1.toolCallId,id:N$,status:X8.status,actions:X8.actions.map((O$)=>{switch(O$.type){case"click":case"double_click":case"move":return{...O$,keys:O$.keys};case"drag":return{...O$,keys:O$.keys};case"scroll":return{type:"scroll",x:O$.x,y:O$.y,scroll_x:O$.scrollX,scroll_y:O$.scrollY,keys:O$.keys};default:return O$}}),pending_safety_checks:X8.pendingSafetyChecks.map((O$)=>({id:O$.id,code:O$.code,message:O$.message}))});break}if(O==null?void 0:O.has(W$)){q0.push({type:"custom_tool_call",call_id:P1.toolCallId,name:W$,input:typeof P1.input==="string"?P1.input:JSON.stringify(P1.input),...K5!=null&&{async:K5},id:N$});break}q0.push({type:"function_call",call_id:P1.toolCallId,name:W$,arguments:c96(P1.input),...K5!=null&&{async:K5},...u8!=null&&{namespace:u8},...D4!=null&&{caller:yx$(D4)}});break}case"tool-result":{if(P1.output.type==="execution-denied"||P1.output.type==="json"&&typeof P1.output.value==="object"&&P1.output.value!=null&&"type"in P1.output.value&&P1.output.value.type==="execution-denied")break;if(K)break;let m$=Z.toProviderToolName(P1.toolName);if(P1.toolName===D){let i1=(v0=(p0=(a=(t=P1.providerOptions)==null?void 0:t[X])==null?void 0:a.itemId)!=null?p0:(X0=(s=P1.providerMetadata)==null?void 0:s[X])==null?void 0:X0.itemId)!=null?v0:P1.toolCallId;if(W)q0.push({type:"item_reference",id:i1});else if(P1.output.type==="json"){let N$=await U8({value:P1.output.value,schema:HW1});q0.push({type:"tool_search_output",id:i1,execution:"server",call_id:null,status:"completed",tools:N$.tools})}break}if(m$==="programmatic_tool_calling"){let i1=(j1=(m0=(c0=(H1=P1.providerOptions)==null?void 0:H1[X])==null?void 0:c0.itemId)!=null?m0:(z0=(w0=P1.providerMetadata)==null?void 0:w0[X])==null?void 0:z0.itemId)!=null?j1:P1.toolCallId;if(W)q0.push({type:"item_reference",id:i1});else if(P1.output.type==="json"){let N$=await U8({value:P1.output.value,schema:Df$});q0.push({type:"program_output",id:i1,call_id:P1.toolCallId,result:N$.result,status:N$.status})}break}if(U&&m$==="shell"){if(P1.output.type==="json"){let i1=await U8({value:P1.output.value,schema:WW1});q0.push({type:"shell_call_output",call_id:P1.toolCallId,output:i1.output.map((N$)=>({stdout:N$.stdout,stderr:N$.stderr,outcome:N$.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:N$.outcome.exitCode}}))})}break}if(W){let i1=(i0=(f0=(Y1=P1.providerOptions)==null?void 0:Y1[X])==null?void 0:f0.itemId)!=null?i0:P1.toolCallId;q0.push({type:"item_reference",id:i1})}else O1.push({type:"other",message:`Results for OpenAI tool ${P1.toolName} are not sent to the API when store is false`});break}case"reasoning":{let m$=await x$({provider:X,providerOptions:P1.providerOptions,schema:i96}),i1=m$==null?void 0:m$.itemId;if((K||H)&&i1!=null)break;if(i1!=null){let N$=r0[i1];if(W){if(N$===void 0)q0.push({type:"item_reference",id:i1}),r0[i1]={type:"reasoning",id:i1,summary:[]}}else{let u8=[];if(P1.text.length>0)u8.push({type:"summary_text",text:P1.text});else if(N$!==void 0)O1.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(P1)}.`});if(N$===void 0)r0[i1]={type:"reasoning",id:i1,encrypted_content:m$==null?void 0:m$.reasoningEncryptedContent,summary:u8},q0.push(r0[i1]);else if(N$.summary.push(...u8),(m$==null?void 0:m$.reasoningEncryptedContent)!=null)N$.encrypted_content=m$.reasoningEncryptedContent}}else{let N$=m$==null?void 0:m$.reasoningEncryptedContent;if(N$!=null){let u8=[];if(P1.text.length>0)u8.push({type:"summary_text",text:P1.text});q0.push({type:"reasoning",encrypted_content:N$,summary:u8})}else O1.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(P1)}.`})}break}case"custom":{if(P1.kind==="openai.compaction"){let m$=(n0=P1.providerOptions)==null?void 0:n0[X],i1=m$==null?void 0:m$.itemId;if(K&&i1!=null)break;if(W&&i1!=null){q0.push({type:"item_reference",id:i1});break}let N$=m$==null?void 0:m$.encryptedContent;if(i1!=null)q0.push({type:"compaction",id:i1,encrypted_content:N$})}break}}break}case"tool":{for(let r0 of s6){if(r0.type==="tool-approval-response"){let W$=r0;if(g$.has(W$.approvalId))continue;if(g$.add(W$.approvalId),W&&!K&&!H)q0.push({type:"item_reference",id:W$.approvalId});q0.push({type:"mcp_approval_response",approval_request_id:W$.approvalId,approve:W$.approved});continue}let P1=wW1({providerOptions:r0.providerOptions,providerOptionsName:X}),m$=P1==null?void 0:T8.get(P1.toolCallId);if(P1!=null&&m$!=null&&zW1(m$.metadata,P1)){if(!I5.has(m$.metadata.toolCallId)){I5.add(m$.metadata.toolCallId);let W$=await Promise.all(m$.results.map(async(O$)=>{let O9=XW1({output:O$.output,toolResultProviderOptions:O$.providerOptions,providerOptionsName:X});return{output:await gx$({output:O$.output,toolName:O$.toolName,outputSchemaToolNames:j,providerOptionsName:X,warnings:O1}),promptCacheBreakpoint:O9}})),S8=W$.map(({output:O$})=>typeof O$==="string"?O$:JSON.stringify(O$)),X8=W$.some(({promptCacheBreakpoint:O$})=>O$!=null);q0.push({type:"function_call_output",call_id:m$.metadata.toolCallId,output:X8?S8.map((O$,O9)=>({type:"input_text",text:O9===0?O$:`
|
|
3116
3116
|
${O$}`,...W$[O9].promptCacheBreakpoint!=null&&{prompt_cache_breakpoint:W$[O9].promptCacheBreakpoint}})):S8.join(`
|
|
3117
3117
|
`)})}continue}let i1=r0.output;if(i1.type==="execution-denied"){if((G0=($1=i1.providerOptions)==null?void 0:$1.openai)==null?void 0:G0.approvalId)continue}let N$=Z.toProviderToolName(r0.toolName);if(r0.toolName===D&&i1.type==="json"){let W$=await U8({value:i1.value,schema:HW1});q0.push({type:"tool_search_output",execution:"client",call_id:r0.toolCallId,status:"completed",tools:W$.tools});continue}if(F&&N$==="local_shell"&&i1.type==="json"){let W$=await U8({value:i1.value,schema:Nf$});q0.push({type:"local_shell_call_output",call_id:r0.toolCallId,output:W$.output});continue}if(U&&N$==="shell"&&i1.type==="json"){let W$=await U8({value:i1.value,schema:WW1});q0.push({type:"shell_call_output",call_id:r0.toolCallId,output:W$.output.map((S8)=>({stdout:S8.stdout,stderr:S8.stderr,outcome:S8.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:S8.outcome.exitCode}}))});continue}if(N&&r0.toolName==="apply_patch"&&i1.type==="json"){let W$=await U8({value:i1.value,schema:Jf$});q0.push({type:"apply_patch_call_output",call_id:r0.toolCallId,status:W$.status,output:W$.output});continue}if(B&&N$==="computer"&&i1.type==="json"){let W$=await U8({value:i1.value,schema:Kf$});q0.push({type:"computer_call_output",call_id:r0.toolCallId,output:{type:"computer_screenshot",image_url:W$.output.imageUrl,file_id:W$.output.fileId,detail:W$.output.detail},acknowledged_safety_checks:(Q0=W$.acknowledgedSafetyChecks)==null?void 0:Q0.map((S8)=>({id:S8.id,code:S8.code,message:S8.message}))});continue}if(O==null?void 0:O.has(N$)){let W$=XW1({output:i1,toolResultProviderOptions:r0.providerOptions,providerOptionsName:X}),S8=(O$)=>W$==null?O$:[{type:"input_text",text:O$,prompt_cache_breakpoint:W$}],X8;switch(i1.type){case"text":case"error-text":X8=S8(i1.value);break;case"execution-denied":X8=S8((F0=i1.reason)!=null?F0:"Tool call execution denied.");break;case"json":case"error-json":X8=S8(JSON.stringify(i1.value));break;case"content":X8=i1.value.map((O$)=>{var O9,VQ,gZ;let Z0=vE(O$.providerOptions,X);switch(O$.type){case"text":return{type:"input_text",text:O$.text,...Z0!=null&&{prompt_cache_breakpoint:Z0}};case"file":{let C0=aQ(O$.mediaType),C1=(VQ=(O9=O$.providerOptions)==null?void 0:O9[X])==null?void 0:VQ.imageDetail;if(O$.data.type==="data"){let d8=r9({part:O$});if(C0==="image")return{type:"input_image",image_url:`data:${d8};base64,${B4(O$.data.data)}`,detail:C1,...Z0!=null&&{prompt_cache_breakpoint:Z0}};return{type:"input_file",filename:(gZ=O$.filename)!=null?gZ:"data",file_data:`data:${d8};base64,${B4(O$.data.data)}`,...Z0!=null&&{prompt_cache_breakpoint:Z0}}}if(O$.data.type==="url"){if(C0==="image")return{type:"input_image",image_url:O$.data.url.toString(),detail:C1,...Z0!=null&&{prompt_cache_breakpoint:Z0}};return{type:"input_file",file_url:O$.data.url.toString(),...Z0!=null&&{prompt_cache_breakpoint:Z0}}}O1.push({type:"other",message:`unsupported custom tool content part type: ${O$.type} with data type: ${O$.data.type}`});return}default:O1.push({type:"other",message:`unsupported custom tool content part type: ${O$.type}`});return}}).filter(NE);break;default:X8=""}q0.push({type:"custom_tool_call_output",call_id:r0.toolCallId,output:X8});continue}let u8=(I0=(U0=r0.providerOptions)==null?void 0:U0[X])==null?void 0:I0.caller;if(i1.type==="execution-denied"&&((u8==null?void 0:u8.type)==="program"||o$.has(r0.toolCallId)))throw new Z$({functionality:"execution-denied results for programmatic tool calls"});let K5=await gx$({output:i1,toolName:r0.toolName,outputSchemaToolNames:j,promptCacheBreakpoint:XW1({output:i1,toolResultProviderOptions:r0.providerOptions,providerOptionsName:X}),providerOptionsName:X,warnings:O1}),D4=yx$(u8);q0.push({type:"function_call_output",call_id:r0.toolCallId,output:K5,...D4!=null&&{caller:D4}})}break}default:throw Error(`Unsupported role: ${m8}`)}if(!W&&q0.some((m8)=>("type"in m8)&&m8.type==="reasoning"&&m8.encrypted_content==null))O1.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),q0=q0.filter((m8)=>!("type"in m8)||m8.type!=="reasoning"||m8.encrypted_content!=null);return{input:q0,warnings:O1}}async function n96({tools:$,toolChoice:Z,allowedTools:Q,toolNameMapping:X,customProviderToolNames:Y,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,D=Y!=null?Y:new Set,O=new Map,j=new Map,w=(z,A,P)=>{if(O.set(z,A),P==null||P===z)return;let T=j.get(P);if(T==null)j.set(P,A);else if(T!=="ambiguous"&&!t96(T,A))j.set(P,"ambiguous")};for(let z of $)switch(z.type){case"function":{let A=(W=z.providerOptions)==null?void 0:W.openai;if((A==null?void 0:A.outputSchema)!=null)J==null||J.add(z.name);let P=a96({tool:z,options:A,toolWarnings:U,async:cx$({value:A==null?void 0:A.async,supportsAsyncToolCalling:G,toolName:z.name,toolWarnings:U})}),T=A==null?void 0:A.namespace;if(T==null)N.push(P);else{let q=B.get(T.name);if(q==null)q={type:"namespace",name:T.name,description:T.description,tools:[]},B.set(T.name,q),N.push(q);else if(q.description!==T.description)throw new Z$({functionality:`conflicting descriptions for OpenAI tool namespace "${T.name}"`});q.tools.push(P)}w(z.name,T!=null?{supported:!1,reason:"tools inside an OpenAI tool namespace are not visible to tool_choice.allowed_tools"}:(A==null?void 0:A.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 A=N.length;switch(z.id){case"openai.file_search":{let P=await U8({value:z.args,schema:Q96});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 U8({value:z.args,schema:N96});N.push({type:"shell",...P.environment&&{environment:r96(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 U8({value:z.args,schema:T96});N.push({type:"web_search_preview",search_context_size:P.searchContextSize,user_location:P.userLocation});break}case"openai.web_search":{let P=await U8({value:z.args,schema:j96});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 U8({value:z.args,schema:p56});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 U8({value:z.args,schema:J96});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 U8({value:z.args,schema:M96}),T=(S)=>({tool_names:S.toolNames}),q=P.requireApproval,f=q==null?void 0:typeof q==="string"?q:q.never!=null?{never:T(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:f!=null?f:"never",server_description:P.serverDescription,server_url:P.serverUrl});break}case"openai.custom":{let P=await U8({value:z.args,schema:s56});N.push({type:"custom",name:z.name,description:P.description,...cx$({value:P.async,supportsAsyncToolCalling:G,toolName:z.name,toolWarnings:U})!=null?{async:P.async}:{},format:P.format}),D.add(z.name);break}case"openai.programmatic_tool_calling":{N.push({type:"programmatic_tool_calling"});break}case"openai.tool_search":{let P=await U8({value:z.args,schema:L96});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>A){let P=N[A];w(z.name,o96(P),X==null?void 0:X.toProviderToolName(z.name))}break}default:U.push({type:"unsupported",feature:`function tool ${z}`});break}if(Q!=null){let z=[],A=[];for(let P of Q.toolNames){let T=O.get(P),q=T!=null?T:j.get(P);if(T!=null&&j.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"}),A.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=X==null?void 0:X.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`}),A.push(P);continue}z.push(q.entry)}if(z.length===0)throw new Z$({functionality:`allowedTools with only tools that cannot be allow-listed (${A.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=X==null?void 0:X.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}:D.has(z)?{type:"custom",name:z}:{type:"function",name:z},toolWarnings:U}}default:throw new Z$({functionality:`tool choice type: ${E}`})}}function lx$($){switch($.type){case"mcp":return`mcp:${$.server_label}`;case"function":case"custom":return`${$.type}:${$.name}`;default:return $.type}}function t96($,Z){if($.supported&&Z.supported)return lx$($.entry)===lx$(Z.entry);if(!$.supported&&!Z.supported)return $.reason===Z.reason;return!1}function o96($){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 a96({tool:$,options:Z,toolWarnings:Q,async:X}){var Y;let J=Z==null?void 0:Z.deferLoading,G=I80($.inputSchema),W=(Z==null?void 0:Z.outputSchema)!=null?I80(Z.outputSchema):void 0;return Q.push(...G.warnings,...(Y=W==null?void 0:W.warnings)!=null?Y:[]),{type:"function",name:$.name,description:$.description,parameters:G.schema,...X!=null?{async:X}:{},...$.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 cx$({value:$,supportsAsyncToolCalling:Z,toolName:Q,toolWarnings:X}){if($!==!0||Z)return $;X.push({type:"unsupported",feature:`async tool calling for "${Q}"`,details:"Async tool calling is only supported by GPT-6 and later models."});return}function r96($){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:s96(Q.skills)}}return{type:"local",skills:$.skills}}function s96($){return $==null?void 0:$.map((Z)=>{var Q,X;return Z.type==="skillReference"?{type:"skill_reference",skill_id:rQ({reference:(Q=Z.providerReference)!=null?Q:{},provider:"openai"}),version:(X=Z.version)!=null?X:"latest"}:{type:"inline",name:Z.name,description:Z.description,source:{type:"base64",media_type:Z.source.mediaType,data:Z.source.data}}})}function mx$($){var Z,Q;let X={};for(let Y of $){if(Y.role!=="assistant")continue;for(let J of Y.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)X[G]=J.toolCallId}}return X}function e96($){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 dx$({action:$,actions:Z,pending_safety_checks:Q,status:X}){var Y;return{actions:(Z!=null?Z:$!=null?[$]:[]).map(e96),pendingSafetyChecks:(Y=Q==null?void 0:Q.map((J)=>({id:J.id,...J.code!=null&&{code:J.code},...J.message!=null&&{message:J.message}})))!=null?Y:[],status:X}}function $Z6($){return $.type==="response.output_text.delta"}function ZZ6($){let Z=XZ6($);return Z!=null&&Array.isArray(Z.choices)&&typeof Z.type!=="string"}function QZ6({value:$,cause:Z,url:Q,requestBodyValues:X,responseHeaders:Y}){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:X,responseHeaders:Y,responseBody:JSON.stringify($),cause:Z,data:$,isRetryable:!1})}function XZ6($){return typeof $==="object"&&$!=null?$:void 0}function YZ6($){return $.type==="response.output_item.done"}function JZ6($){return $.type==="response.completed"||$.type==="response.incomplete"}function ix$($){return $.type==="response.failed"}function GZ6($){return $.type==="response.created"}function WZ6($){return $.type==="response.function_call_arguments.delta"}function KZ6($){return $.type==="response.custom_tool_call_input.delta"}function HZ6($){return $.type==="response.image_generation_call.partial_image"}function FZ6($){return $.type==="response.code_interpreter_call_code.delta"}function UZ6($){return $.type==="response.code_interpreter_call_code.done"}function NZ6($){return $.type==="response.apply_patch_call_operation_diff.delta"}function BZ6($){return $.type==="response.apply_patch_call_operation_diff.done"}function px$($){return $.type==="response.output_item.added"}function LZ6($){return $.type==="response.output_text.annotation.added"}function nx$($){return $.type==="error"}function DZ6($){return $.type==="response.in_progress"}function OZ6($){return!($.type==="response.created"||$.type==="response.in_progress"||$.type==="response.failed"||$.type==="error"||$.type==="unknown_chunk")}function PW1($){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 XR($){return JSON.stringify($).slice(1,-1)}function wZ6($){for(let Z of $){let Q=Z.type;if(Q!=="text")throw new Z$({functionality:`batch request type: ${Q}`,message:`The OpenAI Batch API does not support batch requests with type "${Q}".`})}}function TZ6($){var Z;let Q=(Z=$[0])==null?void 0:Z.modelId;for(let X of $)if(X.modelId!==Q)throw new c8({argument:"requests",message:`The OpenAI Batch API requires all requests in a batch to use the same model. Found "${Q}" and "${X.modelId}".`})}function GD0($){var Z,Q,X;let Y=RZ6($.status),J=(Q=(Z=$.errors)==null?void 0:Z.data)==null?void 0:Q[0],G=qZ6($.request_counts),W=TW1($.created_at),K=TW1($.expires_at);return{status:Y,rawStatus:$.status,...G!=null?{requestCounts:G}:{},...J!=null?{error:{message:(X=J.message)!=null?X:"OpenAI batch failed.",...J.code!=null?{code:J.code}:{}}}:{},...W!=null?{createdAt:W}:{},...K!=null?{expiresAt:K}:{}}}function RZ6($){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 qZ6($){let Z=$==null?void 0:$.total,Q=$==null?void 0:$.completed,X=$==null?void 0:$.failed;return BE({total:Z,pending:Z!=null&&Q!=null&&X!=null?Z-Q-X:void 0,completed:Q,failed:X})}function TW1($){if($==null||!Number.isFinite($))return;let Z=new Date($*1000);return Number.isNaN(Z.getTime())?void 0:Z.toISOString()}async function MZ6({body:$,statusCode:Z}){var Q;let X=await t4({value:$,schema:FD0});if(!X.success)return{message:`OpenAI batch request failed with status code ${Z}.`,statusCode:Z};return{message:X.value.error.message,type:(Q=X.value.error.type)!=null?Q:void 0,code:X.value.error.code!=null?String(X.value.error.code):void 0,statusCode:Z}}async function IZ6($){var Z,Q,X,Y,J,G,W,K;let H=await t4({value:$,schema:Of$});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 O=(Z=F.incomplete_details)==null?void 0:Z.reason;return{success:!1,error:{message:O!=null?`OpenAI Responses returned no output (${O}).`:"OpenAI Responses returned no output.",code:"invalid_response"}}}let U=[],N=[],B=!1;for(let O of F.output)switch(O.type){case"reasoning":{let j=O.summary.length>0?O.summary:[{type:"summary_text",text:""}];for(let w of j)U.push({type:"reasoning",text:w.text,providerMetadata:{openai:{itemId:O.id,reasoningEncryptedContent:(Q=O.encrypted_content)!=null?Q:null}}});break}case"message":{for(let j of O.content)if(U.push({type:"text",text:j.text}),j.logprobs!=null)N.push(j.logprobs);break}case"function_call":B=!0,U.push({type:"tool-call",toolCallId:O.call_id,toolName:O.name,input:O.arguments,providerMetadata:{openai:{itemId:O.id,...O.namespace!=null&&{namespace:O.namespace},...O.caller!=null&&{caller:O.caller.type==="program"?{type:"program",callerId:O.caller.caller_id}:O.caller}}}});break;case"custom_tool_call":B=!0,U.push({type:"tool-call",toolCallId:O.call_id,toolName:O.name,input:JSON.stringify(O.input),providerMetadata:{openai:{itemId:O.id}}});break;case"web_search_call":U.push({type:"tool-call",toolCallId:O.id,toolName:"web_search",input:"{}",providerExecuted:!0,dynamic:!0}),U.push({type:"tool-result",toolCallId:O.id,toolName:"web_search",result:PW1(O.action),dynamic:!0});break;case"file_search_call":U.push({type:"tool-call",toolCallId:O.id,toolName:"file_search",input:"{}",providerExecuted:!0,dynamic:!0}),U.push({type:"tool-result",toolCallId:O.id,toolName:"file_search",result:{queries:O.queries,results:(Y=(X=O.results)==null?void 0:X.map((j)=>({attributes:j.attributes,fileId:j.file_id,filename:j.filename,score:j.score,text:j.text})))!=null?Y:null},dynamic:!0});break;case"code_interpreter_call":U.push({type:"tool-call",toolCallId:O.id,toolName:"code_interpreter",input:JSON.stringify({code:O.code,containerId:O.container_id}),providerExecuted:!0,dynamic:!0}),U.push({type:"tool-result",toolCallId:O.id,toolName:"code_interpreter",result:{outputs:O.outputs},dynamic:!0});break;default:return{success:!1,error:{message:`OpenAI returned an unsupported "${O.type}" output item in an AI SDK text batch.`,code:"unsupported_content"}}}let D={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:KD0({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:UW1(F.usage),response:{id:F.id,timestamp:F.created_at!=null?new Date(F.created_at*1000):void 0,modelId:F.model},providerMetadata:D,warnings:[]}}}function AW1($,Z,Q="websocket"){var X,Y,J,G,W,K;for(let N of Object.keys($))if(!["instructions","voice","inputAudioFormat","outputAudioFormat","providerOptions"].includes(N))throw new Z$({functionality:`OpenAI Live session setting: ${N}`});if(JK.object({delegation:JK.object({type:JK.literal("responses")})}).safeParse((X=$.providerOptions)==null?void 0:X.openai).success)throw new Z$({functionality:"OpenAI Live Responses delegation; only client delegation is supported"});let H=kZ6.parse((J=(Y=$.providerOptions)==null?void 0:Y.openai)!=null?J:{});if(H.client!==void 0&&Q!=="webrtc")throw new Z$({functionality:"OpenAI Live client permissions outside WebRTC startup"});if(H.voice!=null&&$.voice!=null)throw new c8({argument:"voice",message:"Choose either voice or providerOptions.openai.voice."});if(Q==="webrtc"&&($.inputAudioFormat!==void 0||$.outputAudioFormat!==void 0))throw new Z$({functionality:"Fixed audio formats for OpenAI Live WebRTC; audio is negotiated through SDP"});let F=$.inputAudioFormat==null?void 0:ax$.parse($.inputAudioFormat),U=$.outputAudioFormat==null?void 0:ax$.parse($.outputAudioFormat);if(F!=null&&U!=null&&(F.type!==U.type||F.rate!==U.rate))throw new c8({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 vZ6(){return($)=>Tf$($)}function Tf$($){return[xZ6($)]}function xZ6($){var Z,Q,X,Y,J,G,W,K,H,F;let U=_Z6.safeParse($);if(U.success&&!SZ6.has(U.data.type))return{type:"custom",rawType:U.data.type,raw:$};let N=Pf$.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:(X=B.context_window)==null?void 0:X.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":(Y=B.delegation.target)!=null?Y: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 fZ6($,Z){var Q,X,Y;let J="eventId"in $&&$.eventId!==void 0?{event_id:$.eventId}:{};switch($.type){case"session-start":return{type:"session.start",session:AW1($.config,Z),...J};case"session-update":throw new Z$({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=l$.object({content:l$.string(),delegationId:l$.string().min(1).nullable()}).parse($);return{type:`session.${(Y=l$.strictObject({channel:l$.enum(["instructions","thinking","commentary"]).optional()}).parse((X=(Q=$.providerOptions)==null?void 0:Q.openai)!=null?X:{}).channel)!=null?Y:"thinking"}.append`,content:G.content,delegation_id:G.delegationId,...J}}default:throw new Z$({functionality:`OpenAI Live command: ${$.type}; use continuous audio and context-append instead of voice-turn commands`})}}function yZ6($){var Z,Q,X,Y,J,G,W,K,H,F,U,N,B,D,O,j,w,E,z,A,P;let T=$,q=T.type;switch(q){case"session.created":return{type:"session-created",sessionId:(Z=T.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:T.item_id,raw:$};case"input_audio_buffer.speech_stopped":return{type:"speech-stopped",itemId:T.item_id,raw:$};case"input_audio_buffer.committed":return{type:"audio-committed",itemId:T.item_id,previousItemId:T.previous_item_id,raw:$};case"conversation.item.added":return{type:"conversation-item-added",itemId:(X=(Q=T.item)==null?void 0:Q.id)!=null?X:T.item_id,item:T.item,raw:$};case"conversation.item.input_audio_transcription.completed":return{type:"input-transcription-completed",itemId:T.item_id,transcript:(Y=T.transcript)!=null?Y:"",raw:$};case"response.created":return{type:"response-created",responseId:(G=(J=T.response)==null?void 0:J.id)!=null?G:T.response_id,raw:$};case"response.done":return{type:"response-done",responseId:(K=(W=T.response)==null?void 0:W.id)!=null?K:T.response_id,status:(F=(H=T.response)==null?void 0:H.status)!=null?F:"completed",raw:$};case"response.output_item.added":return{type:"output-item-added",responseId:T.response_id,itemId:(N=(U=T.item)==null?void 0:U.id)!=null?N:T.item_id,raw:$};case"response.output_item.done":return{type:"output-item-done",responseId:T.response_id,itemId:(D=(B=T.item)==null?void 0:B.id)!=null?D:T.item_id,raw:$};case"response.content_part.added":return{type:"content-part-added",responseId:T.response_id,itemId:T.item_id,raw:$};case"response.content_part.done":return{type:"content-part-done",responseId:T.response_id,itemId:T.item_id,raw:$};case"response.output_audio.delta":return{type:"audio-delta",responseId:T.response_id,itemId:T.item_id,delta:T.delta,raw:$};case"response.output_audio.done":return{type:"audio-done",responseId:T.response_id,itemId:T.item_id,raw:$};case"response.output_audio_transcript.delta":return{type:"audio-transcript-delta",responseId:T.response_id,itemId:T.item_id,delta:T.delta,raw:$};case"response.output_audio_transcript.done":return{type:"audio-transcript-done",responseId:T.response_id,itemId:T.item_id,transcript:T.transcript,raw:$};case"response.output_text.delta":return{type:"text-delta",responseId:T.response_id,itemId:T.item_id,delta:T.delta,raw:$};case"response.output_text.done":return{type:"text-done",responseId:T.response_id,itemId:T.item_id,text:T.text,raw:$};case"response.function_call_arguments.delta":return{type:"function-call-arguments-delta",responseId:T.response_id,itemId:T.item_id,callId:T.call_id,delta:T.delta,raw:$};case"response.function_call_arguments.done":return{type:"function-call-arguments-done",responseId:T.response_id,itemId:T.item_id,callId:T.call_id,name:T.name,arguments:T.arguments,raw:$};case"error":return{type:"error",message:(w=(j=(O=T.error)==null?void 0:O.message)!=null?j:T.message)!=null?w:"Unknown error",code:(z=(E=T.error)==null?void 0:E.code)!=null?z:T.code,clientEventId:(P=(A=T.error)==null?void 0:A.event_id)!=null?P:void 0,raw:$};default:return{type:"custom",rawType:q,raw:$}}}function gZ6($,Z){switch($.type){case"session-update":return{type:"session.update",session:qW1($.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 qW1($,Z){var Q;let X={type:"realtime",model:Z};if($.instructions!=null)X.instructions=$.instructions;if($.outputModalities!=null)X.output_modalities=$.outputModalities;let Y={};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}:{}};Y.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;Y.output=J}if(Object.keys(Y).length>0)X.audio=Y;if($.tools!=null&&$.tools.length>0)X.tools=$.tools.map((J)=>({type:J.type,name:J.name,description:J.description,parameters:J.parameters})),X.tool_choice="auto";if($.providerOptions!=null)Object.assign(X,$.providerOptions);return X}function lZ6($,{api:Z}={}){if(Z!==void 0){if(Z!=="live"&&Z!=="realtime")throw new c8({argument:"api",message:'OpenAI realtime api must be "live" or "realtime".'});return Z}return uZ6.some((Q)=>Q===$)?"live":"realtime"}function cZ6($){let Z=(Q,X)=>{let Y=lZ6(Q,X),J={...$,provider:`${$.provider}.${Y}`};return Y==="live"?new ex$(Q,J):new hZ6(Q,J)};return Object.assign(Z,{getToken:async(Q)=>{let X=Z(Q.model,Q);if(X instanceof ex$)throw new Z$({functionality:"Short-lived OpenAI credentials for the Live API. Use server WebSocket setup via getServerWebSocketConfig() with a server-side API key instead."});let Y=await X.doCreateClientSecret({sessionConfig:Q.sessionConfig,expiresAfterSeconds:Q.expiresAfterSeconds});return{token:Y.token,url:Y.url,expiresAt:Y.expiresAt}}})}function Zf$($){return $==="gpt-realtime-whisper"||$.startsWith("gpt-realtime-whisper-")}function nZ6({webSocket:$,url:Z,headers:Q,sessionUpdate:X,language:Y,warnings:J,audio:G,abortSignal:W,includeRawChunks:K}){let H=!1,F=()=>{};return new ReadableStream({start:(U)=>{let N=oZ6(Q),B,D;F=(E)=>{if(B!=null)B.cancel().catch(()=>{});else G.cancel().catch(()=>{});D==null||D.close(E)};let O=(E)=>{if(H)return;H=!0,F(),U.error(E)},j=(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:Y}),U.close(),F(1000)},w=async(E)=>{B=G.getReader();try{while(!0){let{done:z,value:A}=await B.read();if(z||H)break;E.send(JSON.stringify({type:"input_audio_buffer.append",audio:B4(A)})),await pU(E)}}finally{B.releaseLock(),B=void 0}if(!H)E.send(JSON.stringify({type:"input_audio_buffer.commit"}))};D=nU({url:Z,protocols:N.protocols,headers:N.headers,webSocket:$,abortSignal:W,onAbort:O,onProcessingError:O,onOpen:(E)=>{U.enqueue({type:"stream-start",warnings:J}),E.send(JSON.stringify(X)),w(E).catch(O)},onMessageText:async(E)=>{var z,A,P,T;let q=await f5({text:E});if(!q.success)return;let f=q.value;if(K)U.enqueue({type:"raw",rawValue:f});switch(f.type){case"conversation.item.input_audio_transcription.delta":{U.enqueue({type:"transcript-delta",id:f.item_id,delta:(z=f.delta)!=null?z:""});break}case"conversation.item.input_audio_transcription.completed":{j((A=f.transcript)!=null?A:"",f.item_id);break}case"error":{O(Error((T=(P=f.error)==null?void 0:P.message)!=null?T:"OpenAI realtime error"));break}}},onSocketError:()=>{O(Error("OpenAI realtime transcription error"))},onClose:()=>{if(H)return;H=!0,F(),U.close()}})},cancel:()=>{if(H)return;H=!0,F()}})}function tZ6({modelId:$,inputAudioFormat:Z,providerOptions:Q}){var X,Y;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}:{},...((X=Q==null?void 0:Q.streaming)==null?void 0:X.delay)!=null?{delay:Q.streaming.delay}:{}},turn_detection:null}},...((Y=Q==null?void 0:Q.streaming)==null?void 0:Y.include)!=null?{include:Q.streaming.include}:{}}}}function oZ6($){var Z;let Q;for(let[Y,J]of Object.entries($))if(Y.toLowerCase()==="authorization"&&J!=null)Q=J;let X=(Z=Q==null?void 0:Q.match(/^bearer\s+(.+)$/i))==null?void 0:Z[1];if(X==null)return{protocols:["realtime"],headers:$};return{protocols:["realtime",`openai-insecure-api-key.${X}`],headers:Object.fromEntries(Object.entries($).filter(([Y])=>Y.toLowerCase()!=="authorization"))}}function eZ6({webSocket:$,url:Z,headers:Q,sessionUpdate:X,warnings:Y,audio:J,abortSignal:G,includeRawChunks:W}){let K=!1,H=()=>{};return new ReadableStream({start:(F)=>{let U=Q76(Q),N,B,D="",O="";H=(z)=>{if(N!=null)N.cancel().catch(()=>{});else J.cancel().catch(()=>{});B==null||B.close(z)};let j=(z)=>{if(K)return;K=!0,H(),F.error(z)},w=()=>{if(K)return;if(K=!0,D!=="")F.enqueue({type:"source-transcript-final",text:D});if(O!=="")F.enqueue({type:"output-text-final",text:O});F.enqueue({type:"finish",sourceText:D,outputText:O,usage:void 0}),F.close(),H(1000)},E=async(z)=>{N=J.getReader();try{while(!0){let{done:A,value:P}=await N.read();if(A||K)break;z.send(JSON.stringify({type:"session.input_audio_buffer.append",audio:B4(P)})),await pU(z)}}finally{N.releaseLock(),N=void 0}if(!K)z.send(JSON.stringify({type:"session.close"}))};B=nU({url:Z,protocols:U.protocols,headers:U.headers,webSocket:$,abortSignal:G,onAbort:j,onProcessingError:j,onOpen:(z)=>{F.enqueue({type:"stream-start",warnings:Y}),z.send(JSON.stringify(X)),E(z).catch(j)},onMessageText:async(z)=>{var A,P,T,q,f,S;if(K)return;let V=await f5({text:z});if(!V.success)return;let u=V.value;if(W)F.enqueue({type:"raw",rawValue:u});switch(u.type){case"session.output_audio.delta":{if(u.delta)F.enqueue({type:"audio",audio:u.delta});break}case"session.output_transcript.delta":{O+=(A=u.delta)!=null?A:"",F.enqueue({type:"output-text-delta",delta:(P=u.delta)!=null?P:""});break}case"session.input_transcript.delta":{D+=(T=u.delta)!=null?T:"",F.enqueue({type:"source-transcript-delta",delta:(q=u.delta)!=null?q:""});break}case"session.closed":{w();break}case"error":{F.enqueue({type:"error",error:Error((S=(f=u.error)==null?void 0:f.message)!=null?S:"OpenAI realtime error")});break}}},onSocketError:()=>{j(Error("OpenAI realtime translation error"))},onClose:({code:z,reason:A})=>{if(K)return;j(Error(`OpenAI realtime translation WebSocket closed unexpectedly before finishing (code ${z!=null?z:"unknown"}${A?`, reason: ${A}`:""}).`))}})},cancel:()=>{if(K)return;K=!0,H()}})}function $76({targetLanguage:$}){return{type:"session.update",session:{audio:{input:{transcription:{model:"gpt-realtime-whisper"},noise_reduction:null},output:{language:$}}}}}function Z76($){if($.type!=="audio/pcm"||$.rate!=null&&$.rate!==24000)throw new c8({argument:"inputAudioFormat",message:"The OpenAI Realtime translation API only supports 24kHz 16-bit PCM input audio."})}function Q76($){var Z;let Q;for(let[Y,J]of Object.entries($))if(Y.toLowerCase()==="authorization"&&J!=null)Q=J;let X=(Z=Q==null?void 0:Q.match(/^bearer\s+(.+)$/i))==null?void 0:Z[1];if(X==null)return{protocols:["realtime"],headers:$};return{protocols:["realtime",`openai-insecure-api-key.${X}`],headers:Object.fromEntries(Object.entries($).filter(([Y])=>Y.toLowerCase()!=="authorization"))}}function JR($={}){var Z,Q;let X=(Z=DE(iB0(sU({settingValue:$.baseURL,environmentVariableName:"OPENAI_BASE_URL"}))))!=null?Z:"https://api.openai.com/v1",Y=(Q=$.name)!=null?Q:"openai",J=()=>U9({Authorization:`Bearer ${td({apiKey:$.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":$.organization,"OpenAI-Project":$.project,...$.headers},`ai-sdk/openai/${J76}`),G=(z)=>new P56(z,{provider:`${Y}.chat`,url:({path:A})=>`${X}${A}`,headers:J,fetch:$.fetch}),W=(z)=>new M56(z,{provider:`${Y}.completion`,url:({path:A})=>`${X}${A}`,headers:J,fetch:$.fetch}),K=(z)=>new C56(z,{provider:`${Y}.embedding`,url:({path:A})=>`${X}${A}`,headers:J,fetch:$.fetch}),H=(z)=>new u56(z,{provider:`${Y}.image`,url:({path:A})=>`${X}${A}`,headers:J,fetch:$.fetch}),F=(z)=>new pZ6(z,{provider:`${Y}.transcription`,url:({path:A})=>`${X}${A}`,headers:J,fetch:$.fetch,webSocket:$.webSocket}),U=(z)=>new sZ6(z,{provider:`${Y}.speech-translation`,url:({path:A})=>`${X}${A}`,headers:J,fetch:$.fetch,webSocket:$.webSocket}),N=(z)=>new dZ6(z,{provider:`${Y}.speech`,url:({path:A})=>`${X}${A}`,headers:J,fetch:$.fetch}),B=()=>new v56({provider:`${Y}.files`,baseURL:X,headers:J,fetch:$.fetch}),D=()=>new Y76({provider:`${Y}.skills`,url:({path:z})=>`${X}${z}`,headers:J,fetch:$.fetch}),O=(z)=>{if(new.target)throw Error("The OpenAI model function cannot be called with the new keyword.");return j(z)},j=(z)=>{return new Ef$(z,{provider:`${Y}.responses`,baseURL:X,url:({path:A})=>`${X}${A}`,headers:J,fetch:$.fetch,fileIdPrefixes:["file-"]})},w=()=>new PZ6({provider:`${Y}.batch`,config:{provider:`${Y}.responses`,baseURL:X,url:({path:z})=>`${X}${z}`,headers:J,fetch:$.fetch,fileIdPrefixes:["file-"]}}),E=function(z){return O(z)};return E.specificationVersion="v4",E.languageModel=O,E.chat=G,E.completion=W,E.responses=j,E.evaluationModel=(z)=>new rd({model:j(z),provider:`${Y}.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=D,E.experimental_batch=w,E.experimental_realtime=cZ6({provider:Y,baseURL:X,headers:J,fetch:$.fetch}),E.tools=v96,E}var FD0,m9,j56,w56,E56,P56,R56,q56,kx$,M56,V56,k56,Cx$,C56,WD0,S56,_56,v56=class{constructor($){this.config=$,this.specificationVersion="v4"}get provider(){return this.config.provider}getFileId($){let Z=$.openai;if(Z==null||Z.trim()==="")throw new c8({argument:"file",message:"file reference is missing an 'openai' file id."});return Z}getHeaders($){return k1(this.config.headers(),$)}async uploadFile({data:$,mediaType:Z,filename:Q,abortSignal:X,headers:Y,providerOptions:J}){var G,W,K;let H;try{H=await x$({provider:"openai",providerOptions:J,schema:_56})}catch(D){if($.type==="stream")await $.stream.cancel(D).catch(()=>{});throw D}let F=(G=H==null?void 0:H.purpose)!=null?G:"assistants",U=this.getHeaders(Y),N=`${this.config.baseURL}/files`,B;if($.type==="stream"){let D=[{type:"field",name:"purpose",value:F}];if((H==null?void 0:H.expiresAfter)!=null)D.push({type:"field",name:"expires_after[anchor]",value:"created_at"},{type:"field",name:"expires_after[seconds]",value:String(H.expiresAfter)});D.push({type:"file",name:"file",filename:Q,mediaType:Z,content:$.stream}),{value:B}=await sk$({url:N,headers:U,parts:D,failedResponseHandler:m9,successfulResponseHandler:R1(WD0),abortSignal:X,fetch:this.config.fetch})}else{let D=oU($),O=new Blob([D],{type:Z}),j=new FormData;if(Q!=null)j.append("file",O,Q);else j.append("file",O);if(j.append("purpose",F),(H==null?void 0:H.expiresAfter)!=null)j.append("expires_after[anchor]","created_at"),j.append("expires_after[seconds]",String(H.expiresAfter));({value:B}=await rW({url:N,headers:U,formData:j,failedResponseHandler:m9,successfulResponseHandler:R1(WD0),abortSignal:X,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 X=this.getFileId($),{value:Y}=await h6({url:`${this.config.baseURL}/files/${$W1(X)}`,headers:this.getHeaders(Q),failedResponseHandler:m9,successfulResponseHandler:R1(WD0),abortSignal:Z,fetch:this.config.fetch,validateUrl:!1});return{warnings:[],providerReference:{openai:Y.id},...Y.filename!=null?{filename:Y.filename}:{},...Y.bytes!=null?{byteSize:Y.bytes}:{},...Y.created_at!=null?{createdAt:new Date(Y.created_at*1000)}:{},...Y.expires_at!=null?{expiresAt:new Date(Y.expires_at*1000)}:{},providerMetadata:{openai:this.toFileMetadata(Y)}}}async downloadFile({file:$,abortSignal:Z,headers:Q}){var X;let Y=this.getFileId($),{value:J,responseHeaders:G}=await h6({url:`${this.config.baseURL}/files/${$W1(Y)}/content`,headers:this.getHeaders(Q),failedResponseHandler:m9,successfulResponseHandler:YC$(),abortSignal:Z,fetch:this.config.fetch,validateUrl:!1}),W=(X=G==null?void 0:G["content-type"])==null?void 0:X.split(";")[0].trim();return{warnings:[],content:J,...W?{mediaType:W}:{}}}async deleteFile({file:$,abortSignal:Z,headers:Q}){let X=this.getFileId($),{value:Y}=await fk$({url:`${this.config.baseURL}/files/${$W1(X)}`,headers:this.getHeaders(Q),failedResponseHandler:m9,successfulResponseHandler:R1(S56),abortSignal:Z,fetch:this.config.fetch});return{warnings:[],providerReference:{openai:Y.id},deleted:Y.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}:{}}}},Sx$,x56,f56,IW1,RV9,g56,h56,u56,Yf$,Jf$,IV9,c56,m56,d56,i56,p56,n56,t56=($={})=>{return n56($)},Gf$,o56,Wf$,Kf$,a56,r56=($={})=>a56($),s56,e56,$96,Z96=($)=>$96($),Hf$,Ff$,Q96,X96,Y96,J96,G96,W96,K96,H96=($={})=>{return K96($)},Uf$,Nf$,F96,Bf$,WW1,U96,N96,B96,L96,KW1,HW1,D96,O96=($={})=>D96($),j96,w96,E96,z96,P96=($={})=>z96($),T96,A96,R96,q96,FW1,M96,I96,V96,k96,C96=($)=>k96($),Lf$,Df$,S96,_96=()=>_A(S96({}),{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"])]}}}}),v96,Si,ZW1,NW1,x96,vx$,BW1,LW1,DW1,OW1,jW1,f96,b96,y96,g96,u96,Of$,xx$="parallel",fx$="functions.",i96,jf$=20,p96,Bk9,ux$,wf$,Ef$,tx$="/v1/responses",jZ6=172800,ox$,zf$=()=>i6.object({id:i6.string(),status:i6.string(),output_file_id:i6.string().nullish(),error_file_id:i6.string().nullish(),created_at:i6.number().nullish(),expires_at:i6.number().nullish(),request_counts:i6.object({total:i6.number().nullish(),completed:i6.number().nullish(),failed:i6.number().nullish()}).nullish(),errors:i6.object({data:i6.array(i6.object({code:i6.string().nullish(),message:i6.string().nullish()})).nullish()}).nullish()}),YW1,EZ6,zZ6,PZ6=class{constructor($){this.options=$,this.specificationVersion="v4",this.supportedUrls=wf$,this.provider=$.provider}async doStartBatch($){var Z,Q,X,Y,J,G;wZ6($.requests),TZ6($.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:jZ6;for(let w of $.requests){let E=await this.prepareRequest(w);W.push(JSON.stringify({custom_id:w.id,method:"POST",url:tx$,body:E.body}),`
|
|
3118
|
-
`);for(let z of E.warnings)K.push({requestId:w.id,warning:z});for(let z of(Q=w.options.tools)!=null?Q:[])if(z.type==="provider"&&!AZ6.has(z.id))K.push({requestId:w.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:D}=await od({url:this.getUrl("/files"),headers:k1((Y=(X=this.options.config).headers)==null?void 0:Y.call(X),$.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:m9,successfulResponseHandler:R1(WD0),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),{value:O}=await Q$({url:this.getUrl("/batches"),headers:k1((G=(J=this.options.config).headers)==null?void 0:G.call(J),$.headers),body:{input_file_id:D.id,endpoint:tx$,completion_window:"24h"},failedResponseHandler:m9,successfulResponseHandler:R1(YW1),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),j=TW1(D.expires_at);return{batchId:O.id,...GD0(O),providerMetadata:{openai:{inputFileId:D.id,...j!=null?{inputFileExpiresAt:j}:{}}},warnings:K}}async parseBatchProviderOptions($){let Z=this.options.config.provider.includes("azure")?"azure":"openai",Q=await x$({provider:Z,providerOptions:$,schema:ox$});if(Q==null&&Z!=="openai")Q=await x$({provider:"openai",providerOptions:$,schema:ox$});return Q}async doGetBatchStatus($){let Z=await this.retrieveBatch($);return GD0(Z)}async doCancelBatch($){var Z,Q;return await Q$({url:this.getUrl(`/batches/${encodeURIComponent($.batchId)}/cancel`),headers:k1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),body:{},failedResponseHandler:m9,successfulResponseHandler:R1(YW1),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),{}}async doListBatches($){var Z,Q;let X=new URL(this.getUrl("/batches"));if($.limit!=null)X.searchParams.set("limit",String($.limit));if($.cursor!=null)X.searchParams.set("after",$.cursor);let{value:Y}=await h6({url:X.toString(),headers:k1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),failedResponseHandler:m9,successfulResponseHandler:R1(zZ6),abortSignal:$.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return{batches:Y.data.map((J)=>({batchId:J.id,...GD0(J)})),...Y.has_more&&Y.last_id!=null?{nextCursor:Y.last_id}:{}}}async doGetBatchResults($){let Z=await this.retrieveBatch($),Q=GD0(Z);if(Q.status==="pending")throw new c8({argument:"batchId",message:`OpenAI batch "${$.batchId}" is not complete.`});let X=[Z.output_file_id,Z.error_file_id].filter((J)=>J!=null);if(Q.status==="completed"&&X.length===0)throw new q9({data:Z,message:`OpenAI batch "${$.batchId}" completed without batch output.`});let Y=this.iterateBatchResults({fileIds:X,options:$});return tU(Y)}async retrieveBatch($){var Z,Q;let{value:X}=await h6({url:this.getUrl(`/batches/${encodeURIComponent($.batchId)}`),headers:k1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),failedResponseHandler:m9,successfulResponseHandler:R1(YW1),abortSignal:$.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return X}async*iterateBatchResults({fileIds:$,options:Z}){var Q,X;for(let Y of $){let{value:J}=await h6({url:this.getUrl(`/files/${encodeURIComponent(Y)}/content`),headers:k1((X=(Q=this.options.config).headers)==null?void 0:X.call(Q),Z.headers),failedResponseHandler:m9,successfulResponseHandler:LE(EZ6),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 MZ6({body:$.response.body,statusCode:$.response.status_code})};let Z=await IZ6($.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 Ef$.prepareRequest({modelId:$.modelId,config:this.options.config,options:$.options});return{body:Z,warnings:Q}}getUrl($){return this.options.config.url({path:$,modelId:""})}},AZ6,VZ6,kZ6,ax$,RW1,CZ6,rx$,sx$,HD0,JW1,Pf$,SZ6,_Z6,bZ6,ex$=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,X]of Object.entries(this.config.headers()))if(X!==void 0)Z[Q]=X;return{url:$.toString(),headers:Z}}async doCreateWebRTCSession({sdp:$,sessionConfig:Z={},abortSignal:Q}){let X=AW1(Z,this.modelId,"webrtc"),{value:Y}=await Q$({url:`${this.config.baseURL}/live/sessions`,headers:this.config.headers(),body:{session:X,transport:{type:"webrtc",sdp:YR.string().min(1).parse($)}},failedResponseHandler:m9,successfulResponseHandler:R1(bZ6),abortSignal:Q,fetch:this.config.fetch});return{sessionId:Y.session.id,sdp:Y.transport.sdp}}parseServerEvent($){return Tf$($)}createServerEventParser(){return vZ6()}serializeClientEvent($){return fZ6($,this.modelId)}buildSessionConfig($){return AW1($,this.modelId)}},hZ6=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,X=`${this.config.baseURL}/realtime/client_secrets`,Y=$.sessionConfig!=null?qW1($.sessionConfig,this.modelId):{type:"realtime",model:this.modelId},J=await Q(X,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify({session:Y,...$.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 yZ6($)}serializeClientEvent($){return gZ6($,this.modelId)}buildSessionConfig($){return qW1($,this.modelId)}},uZ6,mZ6,dZ6,iZ6,$f$,Qf$,pZ6,rZ6,sZ6,X76,uk9,Y76=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 Y of $.files){let J=oU(Y.data);Q.append("files[]",new Blob([J]),Y.path)}let{value:X}=await rW({url:this.config.url({path:"/skills"}),headers:k1(this.config.headers()),formData:Q,failedResponseHandler:m9,successfulResponseHandler:R1(X76),fetch:this.config.fetch});return{providerReference:{openai:X.id},...X.name!=null?{name:X.name}:{},...X.description!=null?{description:X.description}:{},...X.latest_version!=null?{latestVersion:X.latest_version}:{},providerMetadata:{openai:{...X.default_version!=null?{defaultVersion:X.default_version}:{},...X.created_at!=null?{createdAt:X.created_at}:{},...X.updated_at!=null?{updatedAt:X.updated_at}:{}}},warnings:Z}}},J76="4.0.71",lk9;var UD0=L(()=>{T0();tB0();z1();T0();T0();z1();T0();T0();z1();T0();T0();T0();T0();z1();z1();T0();T0();z1();T0();T0();T0();z1();T0();T0();T0();z1();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();z1();T0();T0();T0();z1();T0();z1();T0();z1();T0();T0();z1();T0();z1();T0();z1();z1();T0();T0();z1();T0();T0();T0();z1();T0();T0();T0();T0();FD0=_E.object({error:_E.object({message:_E.string(),type:_E.string().nullish(),param:_E.any().nullish(),code:_E.union([_E.string(),_E.number()]).nullish()})}),m9=y4({errorSchema:FD0,errorToMessage:($)=>$.error.message});j56=K0(()=>e(q1.object({id:q1.string().nullish(),created:q1.number().nullish(),model:q1.string().nullish(),choices:q1.array(q1.object({message:q1.object({role:q1.literal("assistant").nullish(),content:q1.string().nullish(),tool_calls:q1.array(q1.object({id:q1.string().nullish(),type:q1.literal("function"),function:q1.object({name:q1.string(),arguments:q1.string()})})).nullish(),annotations:q1.array(q1.object({type:q1.literal("url_citation"),url_citation:q1.object({start_index:q1.number(),end_index:q1.number(),url:q1.string(),title:q1.string()})})).nullish()}),index:q1.number(),logprobs:q1.object({content:q1.array(q1.object({token:q1.string(),logprob:q1.number(),top_logprobs:q1.array(q1.object({token:q1.string(),logprob:q1.number()}))})).nullish()}).nullish(),finish_reason:q1.string().nullish()})),usage:q1.object({prompt_tokens:q1.number().nullish(),completion_tokens:q1.number().nullish(),total_tokens:q1.number().nullish(),prompt_tokens_details:q1.object({cached_tokens:q1.number().nullish(),cache_write_tokens:q1.number().nullish()}).nullish(),completion_tokens_details:q1.object({reasoning_tokens:q1.number().nullish(),accepted_prediction_tokens:q1.number().nullish(),rejected_prediction_tokens:q1.number().nullish()}).nullish()}).nullish()}))),w56=K0(()=>e(q1.union([q1.object({id:q1.string().nullish(),created:q1.number().nullish(),model:q1.string().nullish(),choices:q1.array(q1.object({delta:q1.object({role:q1.enum(["assistant"]).nullish(),content:q1.string().nullish(),tool_calls:q1.array(q1.object({index:q1.number(),id:q1.string().nullish(),type:q1.literal("function").nullish(),function:q1.object({name:q1.string().nullish(),arguments:q1.string().nullish()})})).nullish(),annotations:q1.array(q1.object({type:q1.literal("url_citation"),url_citation:q1.object({start_index:q1.number(),end_index:q1.number(),url:q1.string(),title:q1.string()})})).nullish()}).nullish(),logprobs:q1.object({content:q1.array(q1.object({token:q1.string(),logprob:q1.number(),top_logprobs:q1.array(q1.object({token:q1.string(),logprob:q1.number()}))})).nullish()}).nullish(),finish_reason:q1.string().nullish(),index:q1.number()})),usage:q1.object({prompt_tokens:q1.number().nullish(),completion_tokens:q1.number().nullish(),total_tokens:q1.number().nullish(),prompt_tokens_details:q1.object({cached_tokens:q1.number().nullish(),cache_write_tokens:q1.number().nullish()}).nullish(),completion_tokens_details:q1.object({reasoning_tokens:q1.number().nullish(),accepted_prediction_tokens:q1.number().nullish(),rejected_prediction_tokens:q1.number().nullish()}).nullish()}).nullish()}),FD0]))),E56=K0(()=>e(z5.object({logitBias:z5.record(z5.coerce.number(),z5.number()).optional(),logprobs:z5.union([z5.boolean(),z5.number()]).optional(),parallelToolCalls:z5.boolean().optional(),user:z5.string().optional(),reasoningEffort:z5.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:z5.number().optional(),store:z5.boolean().optional(),metadata:z5.record(z5.string().max(64),z5.string().max(512)).optional(),prediction:z5.record(z5.string(),z5.any()).optional(),serviceTier:z5.enum(["auto","flex","priority","fast","ultrafast","default"]).optional(),strictJsonSchema:z5.boolean().optional(),textVerbosity:z5.enum(["low","medium","high"]).optional(),promptCacheKey:z5.string().optional(),promptCacheOptions:z5.object({mode:z5.enum(["implicit","explicit"]).optional(),ttl:z5.literal("30m").optional()}).optional(),promptCacheRetention:z5.enum(["in_memory","24h"]).optional(),safetyIdentifier:z5.string().optional(),systemMessageMode:z5.enum(["system","developer","remove"]).optional(),forceReasoning:z5.boolean().optional()})));P56=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Z,this.config=Q}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({prompt:Z,maxOutputTokens:Q,temperature:X,topP:Y,topK:J,frequencyPenalty:G,presencePenalty:W,stopSequences:K,responseFormat:H,seed:F,tools:U,toolChoice:N,reasoning:B,providerOptions:D}){var O,j,w,E,z,A;let P=[],T=(O=await x$({provider:"openai",providerOptions:D,schema:E56}))!=null?O:{},q=Xf$(this.modelId),f=(j=T.reasoningEffort)!=null?j:rL(B)?B:void 0;if(f!=null&&q.supportedReasoningEfforts!=null&&!q.supportedReasoningEfforts.includes(f))P.push({type:"unsupported",feature:"reasoningEffort",details:`${this.modelId} only supports the following reasoning efforts: ${q.supportedReasoningEfforts.join(", ")}`}),f=void 0;let S=(w=T.forceReasoning)!=null?w:q.isReasoningModel;if(J!=null)P.push({type:"unsupported",feature:"topK"});let{messages:V,warnings:u}=O56({prompt:Z,systemMessageMode:(E=T.systemMessageMode)!=null?E:S?"developer":q.systemMessageMode});P.push(...u);let g=(z=T.strictJsonSchema)!=null?z:!0,l=(H==null?void 0:H.type)==="json"&&H.schema!=null?I80(H.schema):void 0;if(l!=null)P.push(...l.warnings);let h={model:this.modelId,logit_bias:T.logitBias,logprobs:T.logprobs===!0||typeof T.logprobs==="number"?!0:void 0,top_logprobs:typeof T.logprobs==="number"?T.logprobs:typeof T.logprobs==="boolean"?T.logprobs?0:void 0:void 0,user:T.user,parallel_tool_calls:T.parallelToolCalls,max_tokens:Q,temperature:X,top_p:Y,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:(A=H.name)!=null?A:"response",description:H.description}}:{type:"json_object"}:void 0,stop:K,seed:F,verbosity:T.textVerbosity,max_completion_tokens:T.maxCompletionTokens,store:T.store,metadata:T.metadata,prediction:T.prediction,reasoning_effort:f,service_tier:T.serviceTier,prompt_cache_key:T.promptCacheKey,prompt_cache_options:T.promptCacheOptions,prompt_cache_retention:T.promptCacheRetention,safety_identifier:T.safetyIdentifier,messages:V};if(q.supportedReasoningEfforts!=null&&h.prompt_cache_retention!=null)h.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(S){if(f!=="none"||!q.supportsNonReasoningParameters){if(h.temperature!=null)h.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(h.top_p!=null)h.top_p=void 0,P.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(h.logprobs!=null)h.logprobs=void 0,P.push({type:"other",message:"logprobs is not supported for reasoning models"})}if(h.frequency_penalty!=null)h.frequency_penalty=void 0,P.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"});if(h.presence_penalty!=null)h.presence_penalty=void 0,P.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"});if(h.logit_bias!=null)h.logit_bias=void 0,P.push({type:"other",message:"logitBias is not supported for reasoning models"});if(h.top_logprobs!=null)h.top_logprobs=void 0,P.push({type:"other",message:"topLogprobs is not supported for reasoning models"});if(h.max_tokens!=null){if(h.max_completion_tokens==null)h.max_completion_tokens=h.max_tokens;h.max_tokens=void 0}}else if(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview")){if(h.temperature!=null)h.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})}if(T.serviceTier==="flex"&&!q.supportsFlexProcessing)P.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),h.service_tier=void 0;if((T.serviceTier==="priority"||T.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"}),h.service_tier=void 0;let{tools:i,toolChoice:H0,toolWarnings:R0}=z56({tools:U,toolChoice:N});return{args:{...h,tools:i,tool_choice:H0},warnings:[...P,...R0]}}async doGenerate(Z){var Q,X,Y,J,G,W,K;let{args:H,warnings:F}=await this.getArgs(Z),{responseHeaders:U,value:N,rawValue:B}=await Q$({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:H,failedResponseHandler:m9,successfulResponseHandler:R1(j56),abortSignal:Z.abortSignal,fetch:this.config.fetch}),D=N.choices[0];if(D==null)throw new q9({data:B,message:"Response did not contain any choices."});let O=[],j=D.message.content;if(j!=null&&j.length>0)O.push({type:"text",text:j});for(let z of(Y=D.message.tool_calls)!=null?Y:[])O.push({type:"tool-call",toolCallId:z.id||J4(),toolName:z.function.name,input:z.function.arguments});for(let z of(J=D.message.annotations)!=null?J:[])O.push({type:"source",sourceType:"url",id:J4(),url:z.url_citation.url,title:z.url_citation.title});let w=(G=N.usage)==null?void 0:G.completion_tokens_details,E={openai:{}};if((w==null?void 0:w.accepted_prediction_tokens)!=null)E.openai.acceptedPredictionTokens=w==null?void 0:w.accepted_prediction_tokens;if((w==null?void 0:w.rejected_prediction_tokens)!=null)E.openai.rejectedPredictionTokens=w==null?void 0:w.rejected_prediction_tokens;if(((W=D.logprobs)==null?void 0:W.content)!=null)E.openai.logprobs=D.logprobs.content;return{content:O,finishReason:{unified:Mx$(D.finish_reason),raw:(K=D.finish_reason)!=null?K:void 0},usage:qx$(N.usage),request:{body:H},response:{...r31(N),headers:U,body:B},warnings:F,providerMetadata:E}}async doStream(Z){var Q,X;let{args:Y,warnings:J}=await this.getArgs(Z),G={...Y,stream:!0,stream_options:{include_usage:!0}},W=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:K,value:H}=await Q$({url:W,headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:G,failedResponseHandler:m9,successfulResponseHandler:lX(w56),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=await MW1({stream:H,getError:(E)=>("error"in E)?E.error:void 0,isOutputChunk:T56,url:W,requestBodyValues:G,responseHeaders:K}),U,N={unified:"other",raw:void 0},B=void 0,D=!1,O=!1,j={openai:{}};return{stream:F.pipeThrough(new TransformStream({start(E){U=new WC$(E,{generateId:J4,typeValidation:"if-present"}),E.enqueue({type:"stream-start",warnings:J})},transform(E,z){var A,P,T,q,f,S;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:(A=M80(V.error))!=null?A:V.error});return}if(!D){let l=r31(V);if(Object.values(l).some(Boolean))D=!0,z.enqueue({type:"response-metadata",...r31(V)})}if(V.usage!=null){if(B=V.usage,((P=V.usage.completion_tokens_details)==null?void 0:P.accepted_prediction_tokens)!=null)j.openai.acceptedPredictionTokens=(T=V.usage.completion_tokens_details)==null?void 0:T.accepted_prediction_tokens;if(((q=V.usage.completion_tokens_details)==null?void 0:q.rejected_prediction_tokens)!=null)j.openai.rejectedPredictionTokens=(f=V.usage.completion_tokens_details)==null?void 0:f.rejected_prediction_tokens}let u=V.choices[0];if((u==null?void 0:u.finish_reason)!=null)N={unified:Mx$(u.finish_reason),raw:u.finish_reason};if(((S=u==null?void 0:u.logprobs)==null?void 0:S.content)!=null)j.openai.logprobs=u.logprobs.content;if((u==null?void 0:u.delta)==null)return;let g=u.delta;if(g.content!=null){if(!O)z.enqueue({type:"text-start",id:"0"}),O=!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:J4(),url:l.url_citation.url,title:l.url_citation.title})},flush(E){if(O)E.enqueue({type:"text-end",id:"0"});U.flush(),E.enqueue({type:"finish",finishReason:N,usage:qx$(B),...j!=null?{providerMetadata:j}:{}})}})),request:{body:G},response:{headers:K}}}};R56=K0(()=>e(t8.object({id:t8.string().nullish(),created:t8.number().nullish(),model:t8.string().nullish(),choices:t8.array(t8.object({text:t8.string(),finish_reason:t8.string(),logprobs:t8.object({tokens:t8.array(t8.string()),token_logprobs:t8.array(t8.number()),top_logprobs:t8.array(t8.record(t8.string(),t8.number())).nullish()}).nullish()})),usage:t8.object({prompt_tokens:t8.number(),completion_tokens:t8.number(),total_tokens:t8.number()}).nullish()}))),q56=K0(()=>e(t8.union([t8.object({id:t8.string().nullish(),created:t8.number().nullish(),model:t8.string().nullish(),choices:t8.array(t8.object({text:t8.string(),finish_reason:t8.string().nullish(),index:t8.number(),logprobs:t8.object({tokens:t8.array(t8.string()),token_logprobs:t8.array(t8.number()),top_logprobs:t8.array(t8.record(t8.string(),t8.number())).nullish()}).nullish()})),usage:t8.object({prompt_tokens:t8.number(),completion_tokens:t8.number(),total_tokens:t8.number()}).nullish()}),FD0]))),kx$=K0(()=>e(BN.object({echo:BN.boolean().optional(),logitBias:BN.record(BN.string(),BN.number()).optional(),suffix:BN.string().optional(),user:BN.string().optional(),logprobs:BN.union([BN.boolean(),BN.number()]).optional()}))),M56=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[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({prompt:Z,maxOutputTokens:Q,temperature:X,topP:Y,topK:J,frequencyPenalty:G,presencePenalty:W,stopSequences:K,responseFormat:H,tools:F,toolChoice:U,seed:N,providerOptions:B}){let D=[],O={...await x$({provider:"openai",providerOptions:B,schema:kx$}),...await x$({provider:this.providerOptionsName,providerOptions:B,schema:kx$})};if(J!=null)D.push({type:"unsupported",feature:"topK"});if(F==null?void 0:F.length)D.push({type:"unsupported",feature:"tools"});if(U!=null)D.push({type:"unsupported",feature:"toolChoice"});if(H!=null&&H.type!=="text")D.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});let{prompt:j,stopSequences:w}=A56({prompt:Z}),E=[...w!=null?w:[],...K!=null?K:[]];return{args:{model:this.modelId,echo:O.echo,logit_bias:O.logitBias,logprobs:(O==null?void 0:O.logprobs)===!0?0:(O==null?void 0:O.logprobs)===!1?void 0:O==null?void 0:O.logprobs,suffix:O.suffix,user:O.user,max_tokens:Q,temperature:X,top_p:Y,frequency_penalty:G,presence_penalty:W,seed:N,prompt:j,stop:E.length>0?E:void 0},warnings:D}}async doGenerate(Z){var Q,X,Y;let{args:J,warnings:G}=await this.getArgs(Z),{responseHeaders:W,value:K,rawValue:H}=await Q$({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:J,failedResponseHandler:m9,successfulResponseHandler:R1(R56),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:Ix$(K.usage),finishReason:{unified:Vx$(F.finish_reason),raw:(Y=F.finish_reason)!=null?Y:void 0},request:{body:J},response:{...s10(K),headers:W,body:H},providerMetadata:U,warnings:G}}async doStream(Z){var Q,X;let{args:Y,warnings:J}=await this.getArgs(Z),G={...Y,stream:!0,stream_options:{include_usage:!0}},W=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:K,value:H}=await Q$({url:W,headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:G,failedResponseHandler:m9,successfulResponseHandler:lX(q56),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=await MW1({stream:H,getError:(j)=>("error"in j)?j.error:void 0,isOutputChunk:I56,url:W,requestBodyValues:G,responseHeaders:K}),U={unified:"other",raw:void 0},N={openai:{}},B=void 0,D=!0;return{stream:F.pipeThrough(new TransformStream({start(j){j.enqueue({type:"stream-start",warnings:J})},transform(j,w){var E;if(Z.includeRawChunks)w.enqueue({type:"raw",rawValue:j.rawValue});if(!j.success){U={unified:"error",raw:void 0},w.enqueue({type:"error",error:j.error});return}let z=j.value;if("error"in z){U={unified:"error",raw:void 0},w.enqueue({type:"error",error:(E=M80(z.error))!=null?E:z.error});return}if(D)D=!1,w.enqueue({type:"response-metadata",...s10(z)}),w.enqueue({type:"text-start",id:"0"});if(z.usage!=null)B=z.usage;let A=z.choices[0];if((A==null?void 0:A.finish_reason)!=null)U={unified:Vx$(A.finish_reason),raw:A.finish_reason};if((A==null?void 0:A.logprobs)!=null)N.openai.logprobs=A.logprobs;if((A==null?void 0:A.text)!=null&&A.text.length>0)w.enqueue({type:"text-delta",id:"0",delta:A.text})},flush(j){if(!D)j.enqueue({type:"text-end",id:"0"});j.enqueue({type:"finish",finishReason:U,providerMetadata:N,usage:Ix$(B)})}})),request:{body:G},response:{headers:K}}}};V56=K0(()=>e(s31.object({dimensions:s31.number().optional(),user:s31.string().optional()}))),k56=K0(()=>e(QR.object({data:QR.array(QR.object({embedding:QR.array(QR.number())})),usage:QR.object({prompt_tokens:QR.number()}).nullish()}))),C56=class ${constructor(Z,Q){this.specificationVersion="v4",this.maxEmbeddingsPerCall=2048,this[Cx$]=300000,this.supportsParallelCalls=!0,this.modelId=Z,this.config=Q}static[(Cx$=dk$,U4)](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async doEmbed({values:Z,headers:Q,abortSignal:X,providerOptions:Y}){var J,G,W;if(Z.length>this.maxEmbeddingsPerCall)throw new vB0({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Z});let K=(J=await x$({provider:"openai",providerOptions:Y,schema:V56}))!=null?J:{},{responseHeaders:H,value:F,rawValue:U}=await Q$({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:k1((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:m9,successfulResponseHandler:R1(k56),abortSignal:X,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}}}},WD0=K0(()=>e(q3.object({id:q3.string(),object:q3.string().nullish(),bytes:q3.number().nullish(),created_at:q3.number().nullish(),filename:q3.string().nullish(),purpose:q3.string().nullish(),status:q3.string().nullish(),expires_at:q3.number().nullish()}))),S56=K0(()=>e(q3.object({id:q3.string(),object:q3.string().nullish(),deleted:q3.boolean()}))),_56=K0(()=>e(e31.object({purpose:e31.string().optional(),expiresAfter:e31.number().optional()})));Sx$=K0(()=>e(ZX.object({created:ZX.number().nullish(),data:ZX.array(ZX.object({b64_json:ZX.string(),revised_prompt:ZX.string().nullish()})),background:ZX.string().nullish(),output_format:ZX.string().nullish(),size:ZX.string().nullish(),quality:ZX.string().nullish(),usage:ZX.object({input_tokens:ZX.number().nullish(),output_tokens:ZX.number().nullish(),total_tokens:ZX.number().nullish(),input_tokens_details:ZX.object({image_tokens:ZX.number().nullish(),text_tokens:ZX.number().nullish()}).nullish()}).nullish()}))),x56={"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},f56=["chatgpt-image-","gpt-image-"];IW1=HD.object({quality:HD.enum(["standard","hd","low","medium","high","xhigh","max","auto"]).optional(),background:HD.enum(["transparent","opaque","auto"]).optional(),outputFormat:HD.enum(["png","jpeg","webp"]).optional(),outputCompression:HD.number().int().min(0).max(100).optional(),user:HD.string().optional()}),RV9=K0(()=>e(IW1)),g56=K0(()=>e(IW1.extend({style:HD.enum(["vivid","natural"]).optional(),moderation:HD.enum(["auto","low"]).optional()}))),h56=K0(()=>e(IW1.extend({inputFidelity:HD.enum(["high","low"]).optional()}))),u56=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get maxImagesPerCall(){return y56(this.modelId)}get provider(){return this.config.provider}async doGenerate({prompt:Z,files:Q,mask:X,n:Y,size:J,aspectRatio:G,seed:W,providerOptions:K,headers:H,abortSignal:F}){var U,N,B,D,O,j,w,E,z,A,P,T,q,f,S;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 u=(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 i=(D=await x$({provider:"openai",providerOptions:K,schema:h56}))!=null?D:{},{value:H0,responseHeaders:R0}=await rW({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:k1((j=(O=this.config).headers)==null?void 0:j.call(O),H),formData:vk$({model:this.modelId,prompt:Z,image:await Promise.all(Q.map((Y0)=>Y0.type==="file"?new Blob([Y0.data instanceof Uint8Array?new Blob([Y0.data],{type:Y0.mediaType}):new Blob([a9(Y0.data)],{type:Y0.mediaType})],{type:Y0.mediaType}):Q$0(Y0.url,{abortSignal:F}))),mask:X!=null?await l56(X,F):void 0,n:Y,size:J,quality:i.quality,background:i.background,output_format:i.outputFormat,output_compression:i.outputCompression,input_fidelity:i.inputFidelity,user:i.user}),failedResponseHandler:m9,successfulResponseHandler:R1(Sx$),abortSignal:F,fetch:this.config.fetch});return{images:H0.data.map((Y0)=>Y0.b64_json),warnings:V,usage:H0.usage!=null?{inputTokens:(w=H0.usage.input_tokens)!=null?w:void 0,outputTokens:(E=H0.usage.output_tokens)!=null?E:void 0,totalTokens:(z=H0.usage.total_tokens)!=null?z:void 0}:void 0,response:{timestamp:u,modelId:this.modelId,headers:R0},providerMetadata:{openai:{images:H0.data.map((Y0,N0)=>{var n,t,a,s,X0,p0;return{...Y0.revised_prompt?{revisedPrompt:Y0.revised_prompt}:{},created:(n=H0.created)!=null?n:void 0,size:(t=H0.size)!=null?t:void 0,quality:(a=H0.quality)!=null?a:void 0,background:(s=H0.background)!=null?s:void 0,outputFormat:(X0=H0.output_format)!=null?X0:void 0,..._x$((p0=H0.usage)==null?void 0:p0.input_tokens_details,N0,H0.data.length)}})}}}}let g=(A=await x$({provider:"openai",providerOptions:K,schema:g56}))!=null?A:{},{value:l,responseHeaders:h}=await Q$({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:k1((T=(P=this.config).headers)==null?void 0:T.call(P),H),body:{model:this.modelId,prompt:Z,n:Y,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,...!b56(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:m9,successfulResponseHandler:R1(Sx$),abortSignal:F,fetch:this.config.fetch});return{images:l.data.map((i)=>i.b64_json),warnings:V,usage:l.usage!=null?{inputTokens:(q=l.usage.input_tokens)!=null?q:void 0,outputTokens:(f=l.usage.output_tokens)!=null?f:void 0,totalTokens:(S=l.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:u,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:l.data.map((i,H0)=>{var R0,Y0,N0,n,t,a;return{...i.revised_prompt?{revisedPrompt:i.revised_prompt}:{},created:(R0=l.created)!=null?R0:void 0,size:(Y0=l.size)!=null?Y0:void 0,quality:(N0=l.quality)!=null?N0:void 0,background:(n=l.background)!=null?n:void 0,outputFormat:(t=l.output_format)!=null?t:void 0,..._x$((a=l.usage)==null?void 0:a.input_tokens_details,H0,l.data.length)}})}}}}};Yf$=K0(()=>e(LQ.object({callId:LQ.string(),operation:LQ.discriminatedUnion("type",[LQ.object({type:LQ.literal("create_file"),path:LQ.string(),diff:LQ.string()}),LQ.object({type:LQ.literal("delete_file"),path:LQ.string()}),LQ.object({type:LQ.literal("update_file"),path:LQ.string(),diff:LQ.string()})])}))),Jf$=K0(()=>e(LQ.object({status:LQ.enum(["completed","failed"]),output:LQ.string().optional()}))),IV9=K0(()=>e(LQ.object({}))),c56=$N({id:"openai.apply_patch",inputSchema:Yf$,outputSchema:Jf$}),m56=c56,d56=K0(()=>e(DQ.object({code:DQ.string().nullish(),containerId:DQ.string()}))),i56=K0(()=>e(DQ.object({outputs:DQ.array(DQ.discriminatedUnion("type",[DQ.object({type:DQ.literal("logs"),logs:DQ.string()}),DQ.object({type:DQ.literal("image"),url:DQ.string()})])).nullish()}))),p56=K0(()=>e(DQ.object({container:DQ.union([DQ.string(),DQ.object({fileIds:DQ.array(DQ.string()).optional()})]).optional()}))),n56=p$({id:"openai.code_interpreter",inputSchema:d56,outputSchema:i56}),Gf$=L$.object({id:L$.string(),code:L$.string().optional(),message:L$.string().optional()}),o56=L$.discriminatedUnion("type",[L$.object({type:L$.literal("click"),button:L$.enum(["left","right","wheel","back","forward"]),x:L$.number(),y:L$.number(),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("double_click"),x:L$.number(),y:L$.number(),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("drag"),path:L$.array(L$.object({x:L$.number(),y:L$.number()})),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("keypress"),keys:L$.array(L$.string())}),L$.object({type:L$.literal("move"),x:L$.number(),y:L$.number(),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("screenshot")}),L$.object({type:L$.literal("scroll"),x:L$.number(),y:L$.number(),scrollX:L$.number(),scrollY:L$.number(),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("type"),text:L$.string()}),L$.object({type:L$.literal("wait")})]),Wf$=K0(()=>e(L$.object({actions:L$.array(o56),pendingSafetyChecks:L$.array(Gf$),status:L$.enum(["in_progress","completed","incomplete"])}))),Kf$=K0(()=>e(L$.object({output:L$.union([L$.object({type:L$.literal("computer_screenshot"),imageUrl:L$.string(),fileId:L$.string().optional(),detail:L$.enum(["auto","low","high","original"]).optional()}),L$.object({type:L$.literal("computer_screenshot"),fileId:L$.string(),imageUrl:L$.string().optional(),detail:L$.enum(["auto","low","high","original"]).optional()})]),acknowledgedSafetyChecks:L$.array(Gf$).optional()}))),a56=$N({id:"openai.computer",inputSchema:Wf$,outputSchema:Kf$}),s56=K0(()=>e(XF.object({description:XF.string().optional(),async:XF.boolean().optional(),format:XF.union([XF.object({type:XF.literal("grammar"),syntax:XF.enum(["regex","lark"]),definition:XF.string()}),XF.object({type:XF.literal("text")})]).optional()}))),e56=K0(()=>e(XF.string())),$96=TZ({id:"openai.custom",inputSchema:e56}),Hf$=B6.object({key:B6.string(),type:B6.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:B6.union([B6.string(),B6.number(),B6.boolean(),B6.array(B6.string())])}),Ff$=B6.object({type:B6.enum(["and","or"]),filters:B6.array(B6.union([Hf$,B6.lazy(()=>Ff$)]))}),Q96=K0(()=>e(B6.object({vectorStoreIds:B6.array(B6.string()),maxNumResults:B6.number().optional(),ranking:B6.object({ranker:B6.string().optional(),scoreThreshold:B6.number().optional()}).optional(),filters:B6.union([Hf$,Ff$]).optional()}))),X96=K0(()=>e(B6.object({queries:B6.array(B6.string()),results:B6.array(B6.object({attributes:B6.record(B6.string(),B6.unknown()),fileId:B6.string(),filename:B6.string(),score:B6.number(),text:B6.string()})).nullable()}))),Y96=p$({id:"openai.file_search",inputSchema:B6.object({}),outputSchema:X96}),J96=K0(()=>e(u7.object({action:u7.enum(["generate","edit","auto"]).optional(),background:u7.enum(["auto","opaque","transparent"]).optional(),inputFidelity:u7.enum(["low","high"]).optional(),inputImageMask:u7.object({fileId:u7.string().optional(),imageUrl:u7.string().optional()}).optional(),model:u7.string().optional(),moderation:u7.enum(["auto","low"]).optional(),outputCompression:u7.number().int().min(0).max(100).optional(),outputFormat:u7.enum(["png","jpeg","webp"]).optional(),partialImages:u7.number().int().min(0).max(3).optional(),quality:u7.enum(["auto","low","medium","high","xhigh","max"]).optional(),size:u7.union([u7.enum(["1024x1024","1024x1536","1536x1024","auto"]),u7.string().regex(/^\d+x\d+$/)]).optional()}).strict())),G96=K0(()=>e(u7.object({}))),W96=K0(()=>e(u7.object({result:u7.string()}))),K96=p$({id:"openai.image_generation",inputSchema:G96,outputSchema:W96}),Uf$=K0(()=>e(R3.object({action:R3.object({type:R3.literal("exec"),command:R3.array(R3.string()),timeoutMs:R3.number().optional(),user:R3.string().optional(),workingDirectory:R3.string().optional(),env:R3.record(R3.string(),R3.string()).optional()})}))),Nf$=K0(()=>e(R3.object({output:R3.string()}))),F96=$N({id:"openai.local_shell",inputSchema:Uf$,outputSchema:Nf$}),Bf$=K0(()=>e(b$.object({action:b$.object({commands:b$.array(b$.string()),timeoutMs:b$.number().optional(),maxOutputLength:b$.number().optional()})}))),WW1=K0(()=>e(b$.object({output:b$.array(b$.object({stdout:b$.string(),stderr:b$.string(),outcome:b$.discriminatedUnion("type",[b$.object({type:b$.literal("timeout")}),b$.object({type:b$.literal("exit"),exitCode:b$.number()})])}))}))),U96=b$.array(b$.discriminatedUnion("type",[b$.object({type:b$.literal("skillReference"),providerReference:b$.record(b$.string(),b$.string()),version:b$.string().optional()}),b$.object({type:b$.literal("inline"),name:b$.string(),description:b$.string(),source:b$.object({type:b$.literal("base64"),mediaType:b$.literal("application/zip"),data:b$.string()})})])).optional(),N96=K0(()=>e(b$.object({environment:b$.union([b$.object({type:b$.literal("containerAuto"),fileIds:b$.array(b$.string()).optional(),memoryLimit:b$.enum(["1g","4g","16g","64g"]).optional(),networkPolicy:b$.discriminatedUnion("type",[b$.object({type:b$.literal("disabled")}),b$.object({type:b$.literal("allowlist"),allowedDomains:b$.array(b$.string()),domainSecrets:b$.array(b$.object({domain:b$.string(),name:b$.string(),value:b$.string()})).optional()})]).optional(),skills:U96}),b$.object({type:b$.literal("containerReference"),containerId:b$.string()}),b$.object({type:b$.literal("local").optional(),skills:b$.array(b$.object({name:b$.string(),description:b$.string(),path:b$.string()})).optional()})]).optional()}))),B96=$N({id:"openai.shell",inputSchema:Bf$,outputSchema:WW1}),L96=K0(()=>e(ZG.object({execution:ZG.enum(["server","client"]).optional(),description:ZG.string().optional(),parameters:ZG.record(ZG.string(),ZG.unknown()).optional()}))),KW1=K0(()=>e(ZG.object({arguments:ZG.unknown().optional(),call_id:ZG.string().nullish()}))),HW1=K0(()=>e(ZG.object({tools:ZG.array(ZG.record(ZG.string(),ZG.unknown()))}))),D96=$N({id:"openai.tool_search",inputSchema:KW1,outputSchema:HW1}),j96=K0(()=>e(o4.object({externalWebAccess:o4.boolean().optional(),filters:o4.object({allowedDomains:o4.array(o4.string()).optional(),blockedDomains:o4.array(o4.string()).optional()}).optional(),searchContextSize:o4.enum(["low","medium","high"]).optional(),userLocation:o4.object({type:o4.literal("approximate"),country:o4.string().optional(),city:o4.string().optional(),region:o4.string().optional(),timezone:o4.string().optional()}).optional()}))),w96=K0(()=>e(o4.object({}))),E96=K0(()=>e(o4.object({action:o4.discriminatedUnion("type",[o4.object({type:o4.literal("search"),query:o4.string().optional(),queries:o4.array(o4.string()).optional()}),o4.object({type:o4.literal("openPage"),url:o4.string().nullish()}),o4.object({type:o4.literal("findInPage"),url:o4.string().nullish(),pattern:o4.string().nullish()})]).optional(),sources:o4.array(o4.discriminatedUnion("type",[o4.object({type:o4.literal("url"),url:o4.string()}),o4.object({type:o4.literal("api"),name:o4.string()})])).optional()}))),z96=p$({id:"openai.web_search",inputSchema:w96,outputSchema:E96}),T96=K0(()=>e(aZ.object({searchContextSize:aZ.enum(["low","medium","high"]).optional(),userLocation:aZ.object({type:aZ.literal("approximate"),country:aZ.string().optional(),city:aZ.string().optional(),region:aZ.string().optional(),timezone:aZ.string().optional()}).optional()}))),A96=K0(()=>e(aZ.object({}))),R96=K0(()=>e(aZ.object({action:aZ.discriminatedUnion("type",[aZ.object({type:aZ.literal("search"),query:aZ.string().optional()}),aZ.object({type:aZ.literal("openPage"),url:aZ.string().nullish()}),aZ.object({type:aZ.literal("findInPage"),url:aZ.string().nullish(),pattern:aZ.string().nullish()})]).optional()}))),q96=p$({id:"openai.web_search_preview",inputSchema:A96,outputSchema:R96}),FW1=R4.lazy(()=>R4.union([R4.string(),R4.number(),R4.boolean(),R4.null(),R4.array(FW1),R4.record(R4.string(),FW1)])),M96=K0(()=>e(R4.object({serverLabel:R4.string(),allowedTools:R4.union([R4.array(R4.string()),R4.object({readOnly:R4.boolean().optional(),toolNames:R4.array(R4.string()).optional()})]).optional(),authorization:R4.string().optional(),connectorId:R4.string().optional(),headers:R4.record(R4.string(),R4.string()).optional(),requireApproval:R4.union([R4.enum(["always","never"]),R4.object({never:R4.object({toolNames:R4.array(R4.string()).optional()}).optional()})]).optional(),serverDescription:R4.string().optional(),serverUrl:R4.string().optional()}).refine(($)=>$.serverUrl!=null||$.connectorId!=null,"One of serverUrl or connectorId must be provided."))),I96=K0(()=>e(R4.object({}))),V96=K0(()=>e(R4.object({type:R4.literal("call"),serverLabel:R4.string(),name:R4.string(),arguments:R4.string(),output:R4.string().nullish(),error:R4.union([R4.string(),FW1]).optional()}))),k96=p$({id:"openai.mcp",inputSchema:I96,outputSchema:V96}),Lf$=K0(()=>e(Ci.object({code:Ci.string(),fingerprint:Ci.string()}))),Df$=K0(()=>e(Ci.object({result:Ci.string(),status:Ci.enum(["completed","incomplete"])}))),S96=p$({id:"openai.programmatic_tool_calling",inputSchema:Lf$,outputSchema:Df$,supportsDeferredResults:!0}),v96={applyPatch:m56,customTool:Z96,codeInterpreter:t56,computer:r56,fileSearch:Y96,imageGeneration:H96,localShell:F96,shell:B96,webSearchPreview:q96,webSearch:P96,mcp:C96,programmaticToolCalling:_96,toolSearch:O96};Si=R.lazy(()=>R.union([R.string(),R.number(),R.boolean(),R.null(),R.array(Si),R.record(R.string(),Si.optional())])),ZW1=R.record(R.string(),Si.optional()),NW1=R.intersection(ZW1,R.object({input_tokens:R.number(),input_tokens_details:R.intersection(ZW1,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(ZW1,R.object({reasoning_tokens:R.number().nullish(),orchestration_output_tokens:R.number().nullish()})).nullish(),total_tokens:R.number().optional()})),x96=R.object({id:R.string(),code:R.string().nullish(),message:R.string().nullish()}),vx$=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")})]),BW1=R.object({type:R.literal("computer_call"),id:R.string(),call_id:R.string().nullish(),status:R.enum(["in_progress","completed","incomplete"]),action:vx$.nullish(),actions:R.array(vx$).nullish(),pending_safety_checks:R.array(x96).nullish()}),LW1=R.discriminatedUnion("type",[R.object({type:R.literal("direct")}),R.object({type:R.literal("program"),caller_id:R.string()})]),DW1=R.object({type:R.literal("program"),id:R.string(),call_id:R.string(),code:R.string(),fingerprint:R.string()}),OW1=R.object({type:R.literal("program_output"),id:R.string(),call_id:R.string(),result:R.string(),status:R.enum(["completed","incomplete"])}),jW1=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()})}),f96=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()})}),b96=R.object({type:R.literal("error"),sequence_number:R.number(),code:R.string().nullish(),message:R.string(),param:R.string().nullish()}),y96=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"]),g96=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"]);u96=K0(()=>e(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:NW1.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:NW1.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:LW1.nullish()}),DW1,OW1,R.object({type:R.literal("web_search_call"),id:R.string(),status:R.string()}),BW1,R.object({type:R.literal("file_search_call"),id:R.string()}),jW1,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(),Si.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:LW1.nullish()}),DW1,OW1,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()}),jW1,BW1,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(),Si.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()}),f96,b96,R.object({type:R.string()}).loose().refine(($)=>!h96($),{message:"Known response chunk failed schema validation"}).transform(($)=>({type:"unknown_chunk",message:$.type}))]))),Of$=K0(()=>e(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()}),jW1,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:LW1.nullish()}),DW1,OW1,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()}),BW1,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(),Si.optional()))})])).optional(),service_tier:R.string().nullish(),reasoning:R.object({context:R.string().nullish()}).nullish(),incomplete_details:R.object({reason:R.string()}).nullish(),usage:NW1.nullish()})));i96=QW1.object({itemId:QW1.string().nullish(),reasoningEncryptedContent:QW1.string().nullish()}),p96=["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"],Bk9=["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",...p96],ux$=K0(()=>e(G4.object({conversation:G4.string().nullish(),include:G4.array(G4.enum(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),includeWebSearchSources:G4.boolean().optional(),instructions:G4.string().nullish(),logprobs:G4.union([G4.boolean(),G4.number().min(1).max(jf$)]).optional(),maxToolCalls:G4.number().nullish(),metadata:G4.any().nullish(),parallelToolCalls:G4.boolean().nullish(),previousResponseId:G4.string().nullish(),promptCacheKey:G4.string().nullish(),promptCacheOptions:G4.object({mode:G4.enum(["implicit","explicit"]).optional(),ttl:G4.literal("30m").optional()}).optional(),promptCacheRetention:G4.enum(["in_memory","24h"]).nullish(),reasoningEffort:G4.string().nullish(),reasoningEffortUpdate:G4.enum(["low","medium","high","xhigh","max"]).optional(),reasoningMode:G4.enum(["standard","pro"]).optional(),reasoningContext:G4.enum(["auto","current_turn","all_turns"]).optional(),reasoningSummary:G4.string().nullish(),safetyIdentifier:G4.string().nullish(),serviceTier:G4.enum(["auto","flex","priority","fast","ultrafast","default"]).nullish(),store:G4.boolean().nullish(),passThroughUnsupportedFiles:G4.boolean().optional(),strictJsonSchema:G4.boolean().nullish(),textVerbosity:G4.enum(["low","medium","high"]).nullish(),truncation:G4.enum(["auto","disabled"]).nullish(),user:G4.string().nullish(),systemMessageMode:G4.enum(["system","developer","remove"]).optional(),forceReasoning:G4.boolean().optional(),contextManagement:G4.array(G4.object({type:G4.literal("compaction"),compactThreshold:G4.number()})).nullish(),compactionTrigger:G4.boolean().optional(),allowedTools:G4.object({toolNames:G4.array(G4.string()).min(1),mode:G4.enum(["auto","required"]).optional()}).optional()})));wf$={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},Ef$=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls=wf$,this.modelId=Z,this.config=Q}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,l96(Z.config))}get provider(){return this.config.provider}static async prepareRequest({modelId:Z,config:Q,options:{maxOutputTokens:X,temperature:Y,stopSequences:J,topP:G,topK:W,presencePenalty:K,frequencyPenalty:H,seed:F,prompt:U,reasoning:N,providerOptions:B,tools:D,toolChoice:O,responseFormat:j}}){var w,E,z,A,P,T,q,f,S,V,u,g,l,h;let i=[],H0=Xf$(Z);if(W!=null)i.push({type:"unsupported",feature:"topK"});if(F!=null)i.push({type:"unsupported",feature:"seed"});if(K!=null)i.push({type:"unsupported",feature:"presencePenalty"});if(H!=null)i.push({type:"unsupported",feature:"frequencyPenalty"});if(J!=null)i.push({type:"unsupported",feature:"stopSequences"});let R0=Q.provider.includes("azure")?"azure":"openai",Y0=await x$({provider:R0,providerOptions:B,schema:ux$});if(Y0==null&&R0!=="openai")Y0=await x$({provider:"openai",providerOptions:B,schema:ux$});let N0=(w=Y0==null?void 0:Y0.reasoningEffort)!=null?w:rL(N)?N:void 0;if(N0!=null&&H0.supportedReasoningEfforts!=null&&!H0.supportedReasoningEfforts.includes(N0))i.push({type:"unsupported",feature:"reasoningEffort",details:`${Z} only supports the following reasoning efforts: ${H0.supportedReasoningEfforts.join(", ")}`}),N0=void 0;let n=(Y0==null?void 0:Y0.reasoningSummary)!==void 0?Y0.reasoningSummary:N0!=null&&N0!=="none"?"detailed":void 0,t=(E=Y0==null?void 0:Y0.forceReasoning)!=null?E:H0.isReasoningModel;if((Y0==null?void 0:Y0.conversation)&&(Y0==null?void 0:Y0.previousResponseId))i.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});let a=pd({tools:D,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"}}),s=new Set,X0=new Set,{tools:p0,toolChoice:v0,toolWarnings:H1}=await n96({tools:D,toolChoice:O,allowedTools:(z=Y0==null?void 0:Y0.allowedTools)!=null?z:void 0,toolNameMapping:a,customProviderToolNames:s,outputSchemaToolNames:X0,supportsAsyncToolCalling:H0.supportsAsyncToolCalling}),{input:c0,warnings:w0}=await d96({prompt:U,toolNameMapping:a,systemMessageMode:(A=Y0==null?void 0:Y0.systemMessageMode)!=null?A:t?"developer":H0.systemMessageMode,providerOptionsName:R0,explicitMessageItemType:Q.explicitMessageItemType,fileIdPrefixes:Q.fileIdPrefixes,passThroughUnsupportedFiles:(P=Y0==null?void 0:Y0.passThroughUnsupportedFiles)!=null?P:!1,store:(T=Y0==null?void 0:Y0.store)!=null?T:!0,hasConversation:(Y0==null?void 0:Y0.conversation)!=null,hasPreviousResponseId:(Y0==null?void 0:Y0.previousResponseId)!=null,hasLocalShellTool:$1("openai.local_shell"),hasShellTool:$1("openai.shell"),hasApplyPatchTool:$1("openai.apply_patch"),hasComputerTool:$1("openai.computer"),toolSearchToolName:n0("openai.tool_search"),customProviderToolNames:s.size>0?s:void 0,outputSchemaToolNames:X0.size>0?X0:void 0});i.push(...w0);let z0=Y0==null?void 0:Y0.reasoningEffortUpdate,m0=z0==null||H0.supportsConfigurationUpdate&&(Y0==null?void 0:Y0.reasoningMode)!=="pro"&&(Y0==null?void 0:Y0.contextManagement)==null&&(Y0==null?void 0:Y0.truncation)!=="auto";if(z0!=null&&!m0)i.push({type:"unsupported",feature:"reasoningEffortUpdate",details:!H0.supportsConfigurationUpdate?"reasoningEffortUpdate is only supported by GPT-6 and later models":"reasoningEffortUpdate requires standard reasoning mode without automatic compaction or automatic truncation"});else if(z0!=null)c0.unshift({type:"configuration_update",reasoning:{effort:z0}});if(Y0==null?void 0:Y0.compactionTrigger)c0.push({type:"compaction_trigger"});let j1=(q=Y0==null?void 0:Y0.strictJsonSchema)!=null?q:!0,Y1=(j==null?void 0:j.type)==="json"&&j.schema!=null?I80(j.schema):void 0;if(Y1!=null)i.push(...Y1.warnings);let f0=Y0==null?void 0:Y0.include;function i0(O1){if(f0==null)f0=[O1];else if(!f0.includes(O1))f0=[...f0,O1]}function n0(O1){var g$;return(g$=D==null?void 0:D.find((o$)=>o$.type==="provider"&&o$.id===O1))==null?void 0:g$.name}function $1(O1){return n0(O1)!=null}let G0=typeof(Y0==null?void 0:Y0.logprobs)==="number"?Y0==null?void 0:Y0.logprobs:(Y0==null?void 0:Y0.logprobs)===!0?jf$:void 0;if(G0)i0("message.output_text.logprobs");let Q0=(f=D==null?void 0:D.find((O1)=>O1.type==="provider"&&(O1.id==="openai.web_search"||O1.id==="openai.web_search_preview")))==null?void 0:f.name;if(Q0&&Q.supportsWebSearchSourcesInclude!==!1&&(Y0==null?void 0:Y0.includeWebSearchSources)!==!1)i0("web_search_call.action.sources");if($1("openai.code_interpreter"))i0("code_interpreter_call.outputs");let F0=Y0==null?void 0:Y0.store;if(F0===!1&&t)i0("reasoning.encrypted_content");let U0={model:Z,input:c0,temperature:Y,top_p:G,max_output_tokens:X,...((j==null?void 0:j.type)==="json"||(Y0==null?void 0:Y0.textVerbosity))&&{text:{...(j==null?void 0:j.type)==="json"&&{format:Y1!=null?{type:"json_schema",strict:j1,name:(S=j.name)!=null?S:"response",description:j.description,schema:Y1.schema}:{type:"json_object"}},...(Y0==null?void 0:Y0.textVerbosity)&&{verbosity:Y0.textVerbosity}}},conversation:Y0==null?void 0:Y0.conversation,max_tool_calls:Y0==null?void 0:Y0.maxToolCalls,metadata:Y0==null?void 0:Y0.metadata,parallel_tool_calls:Y0==null?void 0:Y0.parallelToolCalls,previous_response_id:Y0==null?void 0:Y0.previousResponseId,store:F0,user:Y0==null?void 0:Y0.user,instructions:Y0==null?void 0:Y0.instructions,service_tier:Y0==null?void 0:Y0.serviceTier,include:f0,prompt_cache_key:Y0==null?void 0:Y0.promptCacheKey,prompt_cache_options:Y0==null?void 0:Y0.promptCacheOptions,prompt_cache_retention:Y0==null?void 0:Y0.promptCacheRetention,safety_identifier:Y0==null?void 0:Y0.safetyIdentifier,top_logprobs:G0,truncation:Y0==null?void 0:Y0.truncation,...(Y0==null?void 0:Y0.contextManagement)&&{context_management:Y0.contextManagement.map((O1)=>({type:O1.type,compact_threshold:O1.compactThreshold}))},...t&&(N0!=null||n!=null||(Y0==null?void 0:Y0.reasoningMode)!=null||(Y0==null?void 0:Y0.reasoningContext)!=null)&&{reasoning:{...N0!=null&&{effort:N0},...n!=null&&{summary:n},...(Y0==null?void 0:Y0.reasoningMode)!=null&&{mode:Y0.reasoningMode},...(Y0==null?void 0:Y0.reasoningContext)!=null&&{context:Y0.reasoningContext}}}};if(H0.supportsConfigurationUpdate&&U0.prompt_cache_retention!=null)U0.prompt_cache_retention=void 0,i.push({type:"unsupported",feature:"promptCacheRetention",details:"promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"});if(t){if(!(N0==="none"&&H0.supportsNonReasoningParameters)){if(U0.temperature!=null)U0.temperature=void 0,i.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(U0.top_p!=null)U0.top_p=void 0,i.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(H0.supportedReasoningEfforts!=null&&(U0.top_logprobs!=null||((V=U0.include)==null?void 0:V.includes("message.output_text.logprobs")))){U0.top_logprobs=void 0;let O1=(u=U0.include)==null?void 0:u.filter((g$)=>g$!=="message.output_text.logprobs");U0.include=O1!=null&&O1.length>0?O1:void 0,i.push({type:"unsupported",feature:"logprobs",details:"logprobs is not supported for reasoning models"})}}}else{if((Y0==null?void 0:Y0.reasoningEffort)!=null)i.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"});if((Y0==null?void 0:Y0.reasoningSummary)!=null)i.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"});if((Y0==null?void 0:Y0.reasoningMode)!=null)i.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"});if((Y0==null?void 0:Y0.reasoningContext)!=null)i.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})}if((Y0==null?void 0:Y0.serviceTier)==="flex"&&!H0.supportsFlexProcessing)i.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete U0.service_tier;if(((Y0==null?void 0:Y0.serviceTier)==="priority"||(Y0==null?void 0:Y0.serviceTier)==="fast")&&!H0.supportsPriorityProcessing)i.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 U0.service_tier;let I0=(h=(l=(g=D==null?void 0:D.find((O1)=>O1.type==="provider"&&O1.id==="openai.shell"))==null?void 0:g.args)==null?void 0:l.environment)==null?void 0:h.type,q0=I0==="containerAuto"||I0==="containerReference";return{webSearchToolName:Q0,args:{...U0,tools:p0,tool_choice:v0},warnings:[...i,...H1],store:F0,toolNameMapping:a,providerOptionsName:R0,isShellProviderExecuted:q0}}getArgs(Z){return $.prepareRequest({modelId:this.modelId,config:this.config,options:Z})}async doGenerate(Z){var Q,X,Y,J,G,W,K,H,F,U,N,B,D,O,j,w,E,z,A,P,T,q,f,S,V,u,g,l,h,i,H0,R0,Y0,N0;let{args:n,warnings:t,webSearchToolName:a,toolNameMapping:s,providerOptionsName:X0,isShellProviderExecuted:p0}=await this.getArgs(Z),v0=this.config.url({path:"/responses",modelId:this.modelId}),H1=mx$(Z.prompt),{responseHeaders:c0,value:w0,rawValue:z0}=await Q$({url:v0,headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:n,failedResponseHandler:m9,successfulResponseHandler:R1(Of$),abortSignal:Z.abortSignal,fetch:this.config.fetch});if(w0.error)throw new w8({message:w0.error.message,url:v0,requestBodyValues:n,statusCode:400,responseHeaders:c0,responseBody:z0,isRetryable:!1});if(w0.output==null){let G0=(Y=w0.incomplete_details)==null?void 0:Y.reason;throw new w8({message:G0?`Responses API returned no output (${G0})`:"Responses API returned no output",url:v0,requestBodyValues:n,statusCode:500,responseHeaders:c0,responseBody:z0,isRetryable:!1})}let m0=[],j1=[],Y1=(G=(J=Z.tools)==null?void 0:J.filter((G0)=>G0.type==="function"))!=null?G:[],f0=!1,i0=[];for(let G0 of w0.output)switch(G0.type){case"reasoning":{if(G0.summary.length===0)G0.summary.push({type:"summary_text",text:""});for(let Q0 of G0.summary)m0.push({type:"reasoning",text:Q0.text,providerMetadata:{[X0]:{itemId:G0.id,reasoningEncryptedContent:(W=G0.encrypted_content)!=null?W:null}}});break}case"image_generation_call":{m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName("image_generation"),result:{result:G0.result}});break}case"tool_search_call":{let Q0=(K=G0.call_id)!=null?K:G0.id,F0=G0.execution==="server";if(F0)i0.push(Q0);m0.push({type:"tool-call",toolCallId:Q0,toolName:s.toCustomToolName("tool_search"),input:JSON.stringify({arguments:G0.arguments,call_id:G0.call_id}),...F0?{providerExecuted:!0}:{},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"tool_search_output":{let Q0=(F=(H=G0.call_id)!=null?H:i0.shift())!=null?F:G0.id;m0.push({type:"tool-result",toolCallId:Q0,toolName:s.toCustomToolName("tool_search"),result:{tools:G0.tools},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"local_shell_call":{m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:s.toCustomToolName("local_shell"),input:JSON.stringify({action:G0.action}),providerMetadata:{[X0]:{itemId:G0.id}}});break}case"shell_call":{m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:s.toCustomToolName("shell"),input:JSON.stringify({action:{commands:G0.action.commands}}),...p0&&{providerExecuted:!0},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"shell_call_output":{m0.push({type:"tool-result",toolCallId:G0.call_id,toolName:s.toCustomToolName("shell"),result:{output:G0.output.map((Q0)=>({stdout:Q0.stdout,stderr:Q0.stderr,outcome:Q0.outcome.type==="exit"?{type:"exit",exitCode:Q0.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(let Q0 of G0.content){if(((N=(U=Z.providerOptions)==null?void 0:U[X0])==null?void 0:N.logprobs)&&Q0.logprobs)j1.push(Q0.logprobs);let F0={itemId:G0.id,...G0.phase!=null&&{phase:G0.phase},...Q0.annotations.length>0&&{annotations:Q0.annotations}};m0.push({type:"text",text:Q0.text,providerMetadata:{[X0]:F0}});for(let U0 of Q0.annotations)if(U0.type==="url_citation")m0.push({type:"source",sourceType:"url",id:(O=(D=(B=this.config).generateId)==null?void 0:D.call(B))!=null?O:J4(),url:U0.url,title:U0.title});else if(U0.type==="file_citation")m0.push({type:"source",sourceType:"document",id:(E=(w=(j=this.config).generateId)==null?void 0:w.call(j))!=null?E:J4(),mediaType:"text/plain",title:U0.filename,filename:U0.filename,providerMetadata:{[X0]:{type:U0.type,fileId:U0.file_id,index:U0.index}}});else if(U0.type==="container_file_citation")m0.push({type:"source",sourceType:"document",id:(P=(A=(z=this.config).generateId)==null?void 0:A.call(z))!=null?P:J4(),mediaType:"text/plain",title:U0.filename,filename:U0.filename,providerMetadata:{[X0]:{type:U0.type,fileId:U0.file_id,containerId:U0.container_id}}});else if(U0.type==="file_path")m0.push({type:"source",sourceType:"document",id:(f=(q=(T=this.config).generateId)==null?void 0:q.call(T))!=null?f:J4(),mediaType:"application/octet-stream",title:U0.file_id,filename:U0.file_id,providerMetadata:{[X0]:{type:U0.type,fileId:U0.file_id,index:U0.index}}})}break}case"function_call":{f0=!0;let Q0=await bx$({toolCall:{toolCallId:G0.call_id,toolName:G0.name,input:G0.arguments},tools:Y1,providerOptionsName:X0,itemId:G0.id});if(Q0!=null){m0.push(...Q0);break}m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:G0.name,input:G0.arguments,providerMetadata:{[X0]:{itemId:G0.id,...G0.async!=null&&{async:G0.async},...G0.namespace!=null&&{namespace:G0.namespace},...G0.caller!=null&&{caller:G0.caller.type==="program"?{type:"program",callerId:G0.caller.caller_id}:G0.caller}}}});break}case"program":{m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:s.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:G0.code,fingerprint:G0.fingerprint}),providerExecuted:!0,providerMetadata:{[X0]:{itemId:G0.id}}});break}case"program_output":{m0.push({type:"tool-result",toolCallId:G0.call_id,toolName:s.toCustomToolName("programmatic_tool_calling"),result:{result:G0.result,status:G0.status},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"custom_tool_call":{f0=!0;let Q0=s.toCustomToolName(G0.name);m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:Q0,input:JSON.stringify(G0.input),providerMetadata:{[X0]:{itemId:G0.id,...G0.async!=null&&{async:G0.async}}}});break}case"web_search_call":{m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName(a!=null?a:"web_search"),input:JSON.stringify({}),providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName(a!=null?a:"web_search"),result:PW1(G0.action)});break}case"mcp_call":{let Q0=G0.approval_request_id!=null?(S=H1[G0.approval_request_id])!=null?S:G0.id:G0.id,F0=`mcp.${G0.name}`;m0.push({type:"tool-call",toolCallId:Q0,toolName:F0,input:G0.arguments,providerExecuted:!0,dynamic:!0}),m0.push({type:"tool-result",toolCallId:Q0,toolName:F0,result:{type:"call",serverLabel:G0.server_label,name:G0.name,arguments:G0.arguments,...G0.output!=null?{output:G0.output}:{},...G0.error!=null?{error:G0.error}:{}},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{let Q0=(V=G0.approval_request_id)!=null?V:G0.id,F0=(l=(g=(u=this.config).generateId)==null?void 0:g.call(u))!=null?l:J4(),U0=`mcp.${G0.name}`;m0.push({type:"tool-call",toolCallId:F0,toolName:U0,input:G0.arguments,providerExecuted:!0,dynamic:!0}),m0.push({type:"tool-approval-request",approvalId:Q0,toolCallId:F0});break}case"computer_call":{if(G0.call_id==null){m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:G0.status}});break}f0=!0;let Q0=s.toCustomToolName("computer");m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:Q0,input:JSON.stringify(dx$(G0)),providerMetadata:{[X0]:{itemId:G0.id}}});break}case"file_search_call":{m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName("file_search"),result:{queries:G0.queries,results:(i=(h=G0.results)==null?void 0:h.map((Q0)=>({attributes:Q0.attributes,fileId:Q0.file_id,filename:Q0.filename,score:Q0.score,text:Q0.text})))!=null?i:null}});break}case"code_interpreter_call":{m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:G0.code,containerId:G0.container_id}),providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName("code_interpreter"),result:{outputs:G0.outputs}});break}case"apply_patch_call":{f0=!0,m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:s.toCustomToolName("apply_patch"),input:JSON.stringify({callId:G0.call_id,operation:G0.operation}),providerMetadata:{[X0]:{itemId:G0.id}}});break}case"compaction":{m0.push({type:"custom",kind:"openai.compaction",providerMetadata:{[X0]:{type:"compaction",itemId:G0.id,encryptedContent:G0.encrypted_content}}});break}}let n0={[X0]:{responseId:w0.id,...j1.length>0?{logprobs:j1}:{},...typeof w0.service_tier==="string"?{serviceTier:w0.service_tier}:{},...((H0=w0.reasoning)==null?void 0:H0.context)!=null?{reasoningContext:w0.reasoning.context}:{}}},$1=w0.usage;return{content:m0,finishReason:{unified:KD0({finishReason:(R0=w0.incomplete_details)==null?void 0:R0.reason,hasFunctionCall:f0}),raw:(N0=(Y0=w0.incomplete_details)==null?void 0:Y0.reason)!=null?N0:void 0},usage:UW1($1),request:{body:n},response:{id:w0.id,timestamp:new Date(w0.created_at*1000),modelId:w0.model,headers:c0,body:z0},providerMetadata:n0,warnings:t}}async doStream(Z){var Q,X,Y,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:D,value:O}=await Q$({url:B,headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:{...G,stream:!0},failedResponseHandler:m9,successfulResponseHandler:lX(u96),abortSignal:Z.abortSignal,fetch:this.config.fetch}),j=await MW1({stream:O,getError:(t)=>nx$(t)||ix$(t)&&t.response.error!=null?t:void 0,isOutputChunk:OZ6,isAcceptedChunk:DZ6,url:B,requestBodyValues:G,responseHeaders:D}),w=this,E=mx$(Z.prompt),z=(J=(Y=Z.tools)==null?void 0:Y.filter((t)=>t.type==="function"))!=null?J:[],A=new Map,P={unified:"other",raw:void 0},T=void 0,q=[],f=null,S={},V=[],u,g=!1,l={},h={},i=({itemId:t,outputIndex:a})=>{var s;return a==null?t:(s=h[a])!=null?s:t},H0,R0,Y0=[],N0=!1;return{stream:j.pipeThrough(new TransformStream({start(t){t.enqueue({type:"stream-start",warnings:W})},transform(t,a){var s,X0,p0,v0,H1,c0,w0,z0,m0,j1,Y1,f0,i0,n0,$1,G0,Q0,F0,U0,I0,q0,O1,g$,o$,T8,B8,I5,m8,s6,v9,r0,P1,m$,i1,N$,u8,K5,D4,W$,S8,X8,O$,O9,VQ,gZ;if(Z.includeRawChunks)a.enqueue({type:"raw",rawValue:t.rawValue});if(!t.success){let C0=ZZ6(t.rawValue)?QZ6({value:t.rawValue,cause:t.error,url:B,requestBodyValues:G,responseHeaders:D}):t.error;N0=!0,P={unified:"error",raw:void 0},a.enqueue({type:"error",error:C0});return}let Z0=t.value;if(px$(Z0)){if(Z0.item.type==="function_call"){let C0=EW1({toolName:Z0.item.name,tools:z});if(S[Z0.output_index]={toolName:Z0.item.name,toolCallId:Z0.item.call_id,suppressInputStreaming:C0,bufferedInputDeltas:C0?[]:void 0,async:Z0.item.async},!C0)a.enqueue({type:"tool-input-start",id:Z0.item.call_id,toolName:Z0.item.name})}else if(Z0.item.type==="custom_tool_call"){let C0=H.toCustomToolName(Z0.item.name);S[Z0.output_index]={toolName:C0,toolCallId:Z0.item.call_id,async:Z0.item.async},a.enqueue({type:"tool-input-start",id:Z0.item.call_id,toolName:C0})}else if(Z0.item.type==="web_search_call")S[Z0.output_index]={toolName:H.toCustomToolName(K!=null?K:"web_search"),toolCallId:Z0.item.id},a.enqueue({type:"tool-input-start",id:Z0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),providerExecuted:!0}),a.enqueue({type:"tool-input-end",id:Z0.item.id}),a.enqueue({type:"tool-call",toolCallId:Z0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(Z0.item.type==="computer_call"){let C0=(s=Z0.item.call_id)!=null?s:Z0.item.id;S[Z0.output_index]={toolName:H.toCustomToolName("computer"),toolCallId:C0},a.enqueue({type:"tool-input-start",id:C0,toolName:H.toCustomToolName("computer")})}else if(Z0.item.type==="code_interpreter_call")S[Z0.output_index]={toolName:H.toCustomToolName("code_interpreter"),toolCallId:Z0.item.id,codeInterpreter:{containerId:Z0.item.container_id}},a.enqueue({type:"tool-input-start",id:Z0.item.id,toolName:H.toCustomToolName("code_interpreter"),providerExecuted:!0}),a.enqueue({type:"tool-input-delta",id:Z0.item.id,delta:`{"containerId":"${Z0.item.container_id}","code":"`});else if(Z0.item.type==="file_search_call")a.enqueue({type:"tool-call",toolCallId:Z0.item.id,toolName:H.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(Z0.item.type==="image_generation_call")a.enqueue({type:"tool-call",toolCallId:Z0.item.id,toolName:H.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(Z0.item.type==="tool_search_call"){let C0=Z0.item.id,C1=H.toCustomToolName("tool_search"),d8=Z0.item.execution==="server";if(S[Z0.output_index]={toolName:C1,toolCallId:C0,toolSearchExecution:(X0=Z0.item.execution)!=null?X0:"server"},d8)a.enqueue({type:"tool-input-start",id:C0,toolName:C1,providerExecuted:!0})}else if(Z0.item.type==="tool_search_output");else if(Z0.item.type==="mcp_call"||Z0.item.type==="mcp_list_tools"||Z0.item.type==="mcp_approval_request");else if(Z0.item.type==="apply_patch_call"){let{call_id:C0,operation:C1}=Z0.item;if(S[Z0.output_index]={toolName:H.toCustomToolName("apply_patch"),toolCallId:C0,applyPatch:{hasDiff:C1.type==="delete_file",endEmitted:C1.type==="delete_file"}},a.enqueue({type:"tool-input-start",id:C0,toolName:H.toCustomToolName("apply_patch")}),C1.type==="delete_file"){let d8=JSON.stringify({callId:C0,operation:C1});a.enqueue({type:"tool-input-delta",id:C0,delta:d8}),a.enqueue({type:"tool-input-end",id:C0})}else a.enqueue({type:"tool-input-delta",id:C0,delta:`{"callId":"${XR(C0)}","operation":{"type":"${XR(C1.type)}","path":"${XR(C1.path)}","diff":"`})}else if(Z0.item.type==="shell_call")S[Z0.output_index]={toolName:H.toCustomToolName("shell"),toolCallId:Z0.item.call_id};else if(Z0.item.type==="shell_call_output");else if(Z0.item.type==="message")h[Z0.output_index]=Z0.item.id,V.splice(0,V.length),u=(p0=Z0.item.phase)!=null?p0:void 0,a.enqueue({type:"text-start",id:Z0.item.id,providerMetadata:{[U]:{itemId:Z0.item.id,...Z0.item.phase!=null&&{phase:Z0.item.phase}}}});else if(px$(Z0)&&Z0.item.type==="reasoning")h[Z0.output_index]=Z0.item.id,l[Z0.item.id]={encryptedContent:Z0.item.encrypted_content,summaryParts:{0:"active"}},a.enqueue({type:"reasoning-start",id:`${Z0.item.id}:0`,providerMetadata:{[U]:{itemId:Z0.item.id,reasoningEncryptedContent:(v0=Z0.item.encrypted_content)!=null?v0:null}}})}else if(YZ6(Z0)){if(Z0.item.type==="message"){let C0=i({itemId:Z0.item.id,outputIndex:Z0.output_index}),C1=(H1=Z0.item.phase)!=null?H1:u;u=void 0,a.enqueue({type:"text-end",id:C0,providerMetadata:{[U]:{itemId:C0,...C1!=null&&{phase:C1},...V.length>0&&{annotations:V}}}}),h[Z0.output_index]=void 0}else if(Z0.item.type==="function_call"){let C0=Z0.item,C1=S[Z0.output_index];S[Z0.output_index]=void 0,g=!0;let d8=(c0=C1==null?void 0:C1.suppressInputStreaming)!=null?c0:EW1({toolName:C0.name,tools:z}),x=()=>{var d;if(d8){a.enqueue({type:"tool-input-start",id:C0.call_id,toolName:C0.name});let p=(d=C1==null?void 0:C1.bufferedInputDeltas)!=null?d:[];if(p.length>0)for(let M of p)a.enqueue({type:"tool-input-delta",id:C0.call_id,delta:M});else if(C0.arguments.length>0)a.enqueue({type:"tool-input-delta",id:C0.call_id,delta:C0.arguments})}a.enqueue({type:"tool-input-end",id:C0.call_id,...C0.namespace!=null&&{providerMetadata:{[U]:{namespace:C0.namespace}}}}),a.enqueue({type:"tool-call",toolCallId:C0.call_id,toolName:C0.name,input:C0.arguments,providerMetadata:{[U]:{itemId:C0.id,...C0.async!=null?{async:C0.async}:(C1==null?void 0:C1.async)!=null?{async:C1.async}:{},...C0.namespace!=null&&{namespace:C0.namespace},...C0.caller!=null&&{caller:C0.caller.type==="program"?{type:"program",callerId:C0.caller.caller_id}:C0.caller}}}})};if(!d8){x();return}return bx$({toolCall:{toolCallId:C0.call_id,toolName:C0.name,input:C0.arguments},tools:z,providerOptionsName:U,itemId:C0.id}).then((d)=>{if(d==null){x();return}for(let p of d)a.enqueue({type:"tool-input-start",id:p.toolCallId,toolName:p.toolName}),a.enqueue({type:"tool-input-delta",id:p.toolCallId,delta:p.input}),a.enqueue({type:"tool-input-end",id:p.toolCallId}),a.enqueue(p)})}else if(Z0.item.type==="program")a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:Z0.item.code,fingerprint:Z0.item.fingerprint}),providerExecuted:!0,providerMetadata:{[U]:{itemId:Z0.item.id}}});else if(Z0.item.type==="program_output")a.enqueue({type:"tool-result",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("programmatic_tool_calling"),result:{result:Z0.item.result,status:Z0.item.status},providerMetadata:{[U]:{itemId:Z0.item.id}}});else if(Z0.item.type==="custom_tool_call"){let C0=S[Z0.output_index];S[Z0.output_index]=void 0,g=!0;let C1=H.toCustomToolName(Z0.item.name);a.enqueue({type:"tool-input-end",id:Z0.item.call_id}),a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:C1,input:JSON.stringify(Z0.item.input),providerMetadata:{[U]:{itemId:Z0.item.id,...Z0.item.async!=null?{async:Z0.item.async}:(C0==null?void 0:C0.async)!=null?{async:C0.async}:{}}}})}else if(Z0.item.type==="web_search_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),result:PW1(Z0.item.action)});else if(Z0.item.type==="computer_call"){if(S[Z0.output_index]=void 0,Z0.item.call_id==null){a.enqueue({type:"tool-input-end",id:Z0.item.id}),a.enqueue({type:"tool-call",toolCallId:Z0.item.id,toolName:H.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:Z0.item.status}});return}g=!0;let C0=H.toCustomToolName("computer"),C1=JSON.stringify(dx$(Z0.item));a.enqueue({type:"tool-input-delta",id:Z0.item.call_id,delta:C1}),a.enqueue({type:"tool-input-end",id:Z0.item.call_id}),a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:C0,input:C1,providerMetadata:{[U]:{itemId:Z0.item.id}}})}else if(Z0.item.type==="file_search_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName("file_search"),result:{queries:Z0.item.queries,results:(z0=(w0=Z0.item.results)==null?void 0:w0.map((C0)=>({attributes:C0.attributes,fileId:C0.file_id,filename:C0.filename,score:C0.score,text:C0.text})))!=null?z0:null}});else if(Z0.item.type==="code_interpreter_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName("code_interpreter"),result:{outputs:Z0.item.outputs}});else if(Z0.item.type==="image_generation_call")a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName("image_generation"),result:{result:Z0.item.result}});else if(Z0.item.type==="tool_search_call"){let C0=S[Z0.output_index],C1=Z0.item.execution==="server";if(C0!=null){let d8=C1?C0.toolCallId:(m0=Z0.item.call_id)!=null?m0:Z0.item.id;if(C1)Y0.push(d8);else a.enqueue({type:"tool-input-start",id:d8,toolName:C0.toolName});a.enqueue({type:"tool-input-end",id:d8}),a.enqueue({type:"tool-call",toolCallId:d8,toolName:C0.toolName,input:JSON.stringify({arguments:Z0.item.arguments,call_id:C1?null:d8}),...C1?{providerExecuted:!0}:{},providerMetadata:{[U]:{itemId:Z0.item.id}}})}S[Z0.output_index]=void 0}else if(Z0.item.type==="tool_search_output"){let C0=(Y1=(j1=Z0.item.call_id)!=null?j1:Y0.shift())!=null?Y1:Z0.item.id;a.enqueue({type:"tool-result",toolCallId:C0,toolName:H.toCustomToolName("tool_search"),result:{tools:Z0.item.tools},providerMetadata:{[U]:{itemId:Z0.item.id}}})}else if(Z0.item.type==="mcp_call"){S[Z0.output_index]=void 0;let C0=(f0=Z0.item.approval_request_id)!=null?f0:void 0,C1=C0!=null?(n0=(i0=A.get(C0))!=null?i0:E[C0])!=null?n0:Z0.item.id:Z0.item.id,d8=`mcp.${Z0.item.name}`;a.enqueue({type:"tool-call",toolCallId:C1,toolName:d8,input:Z0.item.arguments,providerExecuted:!0,dynamic:!0}),a.enqueue({type:"tool-result",toolCallId:C1,toolName:d8,result:{type:"call",serverLabel:Z0.item.server_label,name:Z0.item.name,arguments:Z0.item.arguments,...Z0.item.output!=null?{output:Z0.item.output}:{},...Z0.item.error!=null?{error:Z0.item.error}:{}},providerMetadata:{[U]:{itemId:Z0.item.id}}})}else if(Z0.item.type==="mcp_list_tools")S[Z0.output_index]=void 0;else if(Z0.item.type==="apply_patch_call"){let C0=S[Z0.output_index];if((C0==null?void 0:C0.applyPatch)&&!C0.applyPatch.endEmitted&&Z0.item.operation.type!=="delete_file"){if(!C0.applyPatch.hasDiff)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:XR(Z0.item.operation.diff)});a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:'"}}'}),a.enqueue({type:"tool-input-end",id:C0.toolCallId}),C0.applyPatch.endEmitted=!0}if(C0&&Z0.item.status==="completed")g=!0,a.enqueue({type:"tool-call",toolCallId:C0.toolCallId,toolName:H.toCustomToolName("apply_patch"),input:JSON.stringify({callId:Z0.item.call_id,operation:Z0.item.operation}),providerMetadata:{[U]:{itemId:Z0.item.id}}});S[Z0.output_index]=void 0}else if(Z0.item.type==="mcp_approval_request"){S[Z0.output_index]=void 0;let C0=(Q0=(G0=($1=w.config).generateId)==null?void 0:G0.call($1))!=null?Q0:J4(),C1=(F0=Z0.item.approval_request_id)!=null?F0:Z0.item.id;A.set(C1,C0);let d8=`mcp.${Z0.item.name}`;a.enqueue({type:"tool-call",toolCallId:C0,toolName:d8,input:Z0.item.arguments,providerExecuted:!0,dynamic:!0}),a.enqueue({type:"tool-approval-request",approvalId:C1,toolCallId:C0})}else if(Z0.item.type==="local_shell_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:Z0.item.action.command,timeoutMs:Z0.item.action.timeout_ms,user:Z0.item.action.user,workingDirectory:Z0.item.action.working_directory,env:Z0.item.action.env}}),providerMetadata:{[U]:{itemId:Z0.item.id}}});else if(Z0.item.type==="shell_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("shell"),input:JSON.stringify({action:{commands:Z0.item.action.commands}}),...N&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:Z0.item.id}}});else if(Z0.item.type==="shell_call_output")a.enqueue({type:"tool-result",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("shell"),result:{output:Z0.item.output.map((C0)=>({stdout:C0.stdout,stderr:C0.stderr,outcome:C0.outcome.type==="exit"?{type:"exit",exitCode:C0.outcome.exit_code}:{type:"timeout"}}))}});else if(Z0.item.type==="reasoning"){let C0=i({itemId:Z0.item.id,outputIndex:Z0.output_index}),C1=l[C0];if(C1!=null){let d8=Object.entries(C1.summaryParts).filter(([x,d])=>d==="active"||d==="can-conclude").map(([x])=>x);for(let x of d8)a.enqueue({type:"reasoning-end",id:`${C0}:${x}`,providerMetadata:{[U]:{itemId:C0,reasoningEncryptedContent:(U0=Z0.item.encrypted_content)!=null?U0:null}}});delete l[C0]}h[Z0.output_index]=void 0}else if(Z0.item.type==="compaction")a.enqueue({type:"custom",kind:"openai.compaction",providerMetadata:{[U]:{type:"compaction",itemId:Z0.item.id,encryptedContent:Z0.item.encrypted_content}}})}else if(WZ6(Z0)){let C0=S[Z0.output_index];if(C0!=null)if(C0.suppressInputStreaming)(I0=C0.bufferedInputDeltas)==null||I0.push(Z0.delta);else a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:Z0.delta})}else if(KZ6(Z0)){let C0=S[Z0.output_index];if(C0!=null)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:Z0.delta})}else if(NZ6(Z0)){let C0=S[Z0.output_index];if(C0==null?void 0:C0.applyPatch)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:XR(Z0.delta)}),C0.applyPatch.hasDiff=!0}else if(BZ6(Z0)){let C0=S[Z0.output_index];if((C0==null?void 0:C0.applyPatch)&&!C0.applyPatch.endEmitted){if(!C0.applyPatch.hasDiff)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:XR(Z0.diff)}),C0.applyPatch.hasDiff=!0;a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:'"}}'}),a.enqueue({type:"tool-input-end",id:C0.toolCallId}),C0.applyPatch.endEmitted=!0}}else if(HZ6(Z0))a.enqueue({type:"tool-result",toolCallId:Z0.item_id,toolName:H.toCustomToolName("image_generation"),result:{result:Z0.partial_image_b64},preliminary:!0});else if(FZ6(Z0)){let C0=S[Z0.output_index];if(C0!=null)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:XR(Z0.delta)})}else if(UZ6(Z0)){let C0=S[Z0.output_index];if(C0!=null)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:'"}'}),a.enqueue({type:"tool-input-end",id:C0.toolCallId}),a.enqueue({type:"tool-call",toolCallId:C0.toolCallId,toolName:H.toCustomToolName("code_interpreter"),input:JSON.stringify({code:Z0.code,containerId:C0.codeInterpreter.containerId}),providerExecuted:!0})}else if(GZ6(Z0))f=Z0.response.id,a.enqueue({type:"response-metadata",id:Z0.response.id,timestamp:new Date(Z0.response.created_at*1000),modelId:Z0.response.model});else if($Z6(Z0)){let C0=i({itemId:Z0.item_id,outputIndex:Z0.output_index});if(a.enqueue({type:"text-delta",id:C0,delta:Z0.delta}),((O1=(q0=Z.providerOptions)==null?void 0:q0[U])==null?void 0:O1.logprobs)&&Z0.logprobs)q.push(Z0.logprobs)}else if(Z0.type==="response.reasoning_summary_part.added"){let C0=i({itemId:Z0.item_id,outputIndex:Z0.output_index});if(Z0.summary_index>0){let C1=l[C0];if(C1!=null){C1.summaryParts[Z0.summary_index]="active";for(let d8 of Object.keys(C1.summaryParts))if(C1.summaryParts[d8]==="can-conclude")a.enqueue({type:"reasoning-end",id:`${C0}:${d8}`,providerMetadata:{[U]:{itemId:C0}}}),C1.summaryParts[d8]="concluded";a.enqueue({type:"reasoning-start",id:`${C0}:${Z0.summary_index}`,providerMetadata:{[U]:{itemId:C0,reasoningEncryptedContent:(g$=C1.encryptedContent)!=null?g$:null}}})}}}else if(Z0.type==="response.reasoning_summary_text.delta"){let C0=i({itemId:Z0.item_id,outputIndex:Z0.output_index});a.enqueue({type:"reasoning-delta",id:`${C0}:${Z0.summary_index}`,delta:Z0.delta,providerMetadata:{[U]:{itemId:C0}}})}else if(Z0.type==="response.reasoning_summary_part.done"){let C0=i({itemId:Z0.item_id,outputIndex:Z0.output_index}),C1=l[C0];if(C1!=null)if(F)a.enqueue({type:"reasoning-end",id:`${C0}:${Z0.summary_index}`,providerMetadata:{[U]:{itemId:C0}}}),C1.summaryParts[Z0.summary_index]="concluded";else C1.summaryParts[Z0.summary_index]="can-conclude"}else if(JZ6(Z0)){if(!N0)P={unified:KD0({finishReason:(o$=Z0.response.incomplete_details)==null?void 0:o$.reason,hasFunctionCall:g}),raw:(B8=(T8=Z0.response.incomplete_details)==null?void 0:T8.reason)!=null?B8:void 0};if(T=(I5=Z0.response.usage)!=null?I5:void 0,typeof Z0.response.service_tier==="string")H0=Z0.response.service_tier;if(((m8=Z0.response.reasoning)==null?void 0:m8.context)!=null)R0=Z0.response.reasoning.context}else if(ix$(Z0)){let C0=(s6=Z0.response.incomplete_details)==null?void 0:s6.reason;if(P={unified:C0?KD0({finishReason:C0,hasFunctionCall:g}):"error",raw:C0!=null?C0:"error"},T=(v9=Z0.response.usage)!=null?v9:void 0,((r0=Z0.response.reasoning)==null?void 0:r0.context)!=null)R0=Z0.response.reasoning.context;if(!N0&&Z0.response.error!=null){N0=!0;let C1={type:"response.failed",sequence_number:Z0.sequence_number,response:{error:Z0.response.error,incomplete_details:Z0.response.incomplete_details,service_tier:Z0.response.service_tier}};a.enqueue({type:"error",error:(P1=M80(C1))!=null?P1:C1})}}else if(LZ6(Z0)){if(V.push(Z0.annotation),Z0.annotation.type==="url_citation")a.enqueue({type:"source",sourceType:"url",id:(N$=(i1=(m$=w.config).generateId)==null?void 0:i1.call(m$))!=null?N$:J4(),url:Z0.annotation.url,title:Z0.annotation.title});else if(Z0.annotation.type==="file_citation")a.enqueue({type:"source",sourceType:"document",id:(D4=(K5=(u8=w.config).generateId)==null?void 0:K5.call(u8))!=null?D4:J4(),mediaType:"text/plain",title:Z0.annotation.filename,filename:Z0.annotation.filename,providerMetadata:{[U]:{type:Z0.annotation.type,fileId:Z0.annotation.file_id,index:Z0.annotation.index}}});else if(Z0.annotation.type==="container_file_citation")a.enqueue({type:"source",sourceType:"document",id:(X8=(S8=(W$=w.config).generateId)==null?void 0:S8.call(W$))!=null?X8:J4(),mediaType:"text/plain",title:Z0.annotation.filename,filename:Z0.annotation.filename,providerMetadata:{[U]:{type:Z0.annotation.type,fileId:Z0.annotation.file_id,containerId:Z0.annotation.container_id}}});else if(Z0.annotation.type==="file_path")a.enqueue({type:"source",sourceType:"document",id:(VQ=(O9=(O$=w.config).generateId)==null?void 0:O9.call(O$))!=null?VQ:J4(),mediaType:"application/octet-stream",title:Z0.annotation.file_id,filename:Z0.annotation.file_id,providerMetadata:{[U]:{type:Z0.annotation.type,fileId:Z0.annotation.file_id,index:Z0.annotation.index}}})}else if(nx$(Z0))N0=!0,P={unified:"error",raw:"error"},a.enqueue({type:"error",error:(gZ=M80(Z0))!=null?gZ:Z0})},flush(t){var a;for(let X0 of Object.values(S)){if(!(X0==null?void 0:X0.suppressInputStreaming))continue;t.enqueue({type:"tool-input-start",id:X0.toolCallId,toolName:X0.toolName});for(let p0 of(a=X0.bufferedInputDeltas)!=null?a:[])t.enqueue({type:"tool-input-delta",id:X0.toolCallId,delta:p0})}let s={[U]:{responseId:f,...q.length>0?{logprobs:q}:{},...H0!==void 0?{serviceTier:H0}:{},...R0!==void 0?{reasoningContext:R0}:{}}};t.enqueue({type:"finish",finishReason:P,usage:UW1(T),providerMetadata:s})}})),request:{body:G},response:{headers:D}}}};ox$=K0(()=>e(i6.object({inputFileExpiresAfter:i6.number().int().min(3600).max(2592000).optional()})));YW1=K0(()=>e(zf$())),EZ6=K0(()=>e(i6.object({custom_id:i6.string(),response:i6.object({status_code:i6.number(),request_id:i6.string().nullish(),body:i6.unknown()}).nullish(),error:i6.object({code:i6.string(),message:i6.string()}).nullish()}))),zZ6=K0(()=>e(i6.object({data:i6.array(zf$()),has_more:i6.boolean(),last_id:i6.string().nullish()})));AZ6=new Set(["openai.code_interpreter","openai.custom","openai.file_search","openai.web_search","openai.web_search_preview"]);VZ6=A6.strictObject({type:A6.string(),responseEvent:A6.string().optional()}).refine(($)=>$.type==="response.event"===($.responseEvent!==void 0),"responseEvent is required for response.event and forbidden for other event types."),kZ6=A6.strictObject({client:A6.strictObject({dataChannel:A6.strictObject({allowedClientEvents:A6.union([A6.literal("all"),A6.array(A6.string())]).optional(),allowedServerEvents:A6.union([A6.literal("all"),A6.array(VZ6)]).optional()})}).optional(),delegation:A6.strictObject({type:A6.literal("client")}).nullable().optional(),input:A6.array(A6.discriminatedUnion("role",[A6.strictObject({type:A6.literal("message"),role:A6.enum(["developer","user"]),content:A6.tuple([A6.strictObject({type:A6.literal("input_text"),text:A6.string()})])}),A6.strictObject({type:A6.literal("message"),role:A6.literal("assistant"),content:A6.tuple([A6.strictObject({type:A6.enum(["text","output_text"]),text:A6.string()})])})])).max(128).optional(),store:A6.boolean().optional(),voice:A6.strictObject({id:A6.string().min(1)}).optional()}),ax$=JK.union([JK.strictObject({type:JK.literal("audio/pcm"),rate:JK.union([JK.literal(16000),JK.literal(24000)])}),JK.strictObject({type:JK.enum(["audio/pcma","audio/pcmu"]),rate:JK.literal(8000)})]);RW1=l$.object({id:l$.string().min(1)}),CZ6=RW1.extend({delegation:l$.object({type:l$.enum(["client","responses"])}).nullish()}),rx$=l$.object({seconds:l$.number().nonnegative()}),sx$={delta:l$.string(),start_ms:l$.number().nonnegative(),end_ms:l$.number().nonnegative()},HD0={client_event_id:l$.string().nullish()},JW1={...HD0,start_ms:l$.number().nonnegative(),end_ms:l$.number().nonnegative()},Pf$=l$.discriminatedUnion("type",[l$.object({type:l$.literal("session.started"),session:CZ6}),l$.object({type:l$.literal("session.closed"),session:RW1.nullish(),usage:rx$,reason:l$.string()}),l$.object({type:l$.literal("session.usage.updated"),usage:rx$,context_window:l$.object({usage_ratio:l$.number().min(0).max(1)}).nullish()}),l$.object({type:l$.literal("session.output_audio.delta"),delta:l$.string()}),l$.object({type:l$.literal("session.input_transcript.delta"),...sx$}),l$.object({type:l$.literal("session.output_transcript.delta"),...sx$}),l$.object({type:l$.literal("session.delegation.created"),offset_ms:l$.number().nonnegative().nullish(),delegation:l$.object({id:l$.string().min(1),target:l$.enum(["client","responses"]).nullish(),response_id:l$.string().min(1).nullish()})}),l$.object({type:l$.literal("session.updated"),session:RW1,...HD0}),l$.object({type:l$.literal("session.input_audio.muted"),...HD0}),l$.object({type:l$.literal("session.input_audio.unmuted"),...HD0}),l$.object({type:l$.literal("session.instructions.appended"),...JW1}),l$.object({type:l$.literal("session.thinking.appended"),...JW1}),l$.object({type:l$.literal("session.commentary.appended"),...JW1}),l$.object({type:l$.literal("error"),error:l$.object({message:l$.string(),code:l$.string().nullish(),client_event_id:l$.string().nullish()})})]),SZ6=new Set(Pf$.options.map(($)=>$.shape.type.value)),_Z6=l$.object({type:l$.string()});bZ6=YR.object({session:YR.object({id:YR.string().min(1)}),transport:YR.object({type:YR.literal("webrtc"),sdp:YR.string().min(1)})});uZ6=["gpt-live-1"];mZ6=K0(()=>e(GW1.object({instructions:GW1.string().nullish(),speed:GW1.number().min(0.25).max(4).default(1).nullish()}))),dZ6=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({text:Z,voice:Q="alloy",outputFormat:X="mp3",speed:Y,instructions:J,language:G,providerOptions:W}){let K=[],H=await x$({provider:"openai",providerOptions:W,schema:mZ6}),F={model:this.modelId,input:Z,voice:Q,response_format:"mp3",speed:Y,instructions:J};if(X)if(["mp3","opus","aac","flac","wav","pcm"].includes(X))F.response_format=X;else K.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${X}. 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,X,Y,J,G;let W=(Y=(X=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:X.call(Q))!=null?Y:new Date,{requestBody:K,warnings:H}=await this.getArgs(Z),{value:F,responseHeaders:U,rawValue:N}=await Q$({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:k1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),body:K,failedResponseHandler:m9,successfulResponseHandler:XC$(),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}}}},iZ6=K0(()=>e(X5.object({text:X5.string(),language:X5.string().nullish(),duration:X5.number().nullish(),words:X5.array(X5.object({word:X5.string(),start:X5.number(),end:X5.number()})).nullish(),segments:X5.array(X5.union([X5.object({id:X5.number(),seek:X5.number(),start:X5.number(),end:X5.number(),text:X5.string(),tokens:X5.array(X5.number()),temperature:X5.number(),avg_logprob:X5.number(),compression_ratio:X5.number(),no_speech_prob:X5.number()}),X5.object({type:X5.literal("transcript.text.segment"),id:X5.string(),start:X5.number(),end:X5.number(),text:X5.string(),speaker:X5.string()})])).nullish()}))),$f$=K0(()=>e(U7.object({include:U7.array(U7.string()).optional(),language:U7.string().optional(),prompt:U7.string().optional(),temperature:U7.number().min(0).max(1).default(0).optional(),timestampGranularities:U7.array(U7.enum(["word","segment"])).default(["segment"]).optional(),responseFormat:U7.enum(["json","verbose_json","diarized_json"]).optional(),chunkingStrategy:U7.union([U7.literal("auto"),U7.object({type:U7.literal("server_vad"),threshold:U7.number().min(0).max(1).optional(),prefixPaddingMs:U7.number().int().min(0).optional(),silenceDurationMs:U7.number().int().min(0).optional()})]).optional(),streaming:U7.object({delay:U7.enum(["minimal","low","medium","high","xhigh"]).optional(),include:U7.array(U7.string()).optional()}).optional()})));Qf$={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"},pZ6=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({audio:Z,mediaType:Q,providerOptions:X}){var Y,J;let G=[],W=await x$({provider:"openai",providerOptions:X,schema:$f$}),K=new FormData,H=Z instanceof Uint8Array?new Blob([Z]):new Blob([a9(Z)]);K.append("model",this.modelId);let F=nk$(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=(Y=W==null?void 0:W.chunkingStrategy)!=null?Y:U?"auto":void 0;if(W){let B=["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId),D={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[O,j]of Object.entries(D))if(j!=null)if(Array.isArray(j))for(let w of j)K.append(`${O}[]`,String(w));else K.append(O,String(j))}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,X,Y,J,G,W,K,H,F,U,N;if(Zf$(this.modelId))throw new Z$({functionality:`non-streaming transcription with ${this.modelId}`});let B=(Y=(X=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:X.call(Q))!=null?Y:new Date,{formData:D,warnings:O}=await this.getArgs(Z),{value:j,responseHeaders:w,rawValue:E}=await rW({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:k1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),formData:D,failedResponseHandler:m9,successfulResponseHandler:R1(iZ6),abortSignal:Z.abortSignal,fetch:this.config.fetch}),z=j.language!=null&&j.language in Qf$?Qf$[j.language]:void 0,A=(W=j.segments)==null?void 0:W.flatMap((P)=>("speaker"in P)?[{text:P.text,startSecond:P.start,endSecond:P.end,speaker:P.speaker}]:[]);return{text:j.text,segments:(U=(F=(K=j.segments)==null?void 0:K.map((P)=>({text:P.text,startSecond:P.start,endSecond:P.end})))!=null?F:(H=j.words)==null?void 0:H.map((P)=>({text:P.word,startSecond:P.start,endSecond:P.end})))!=null?U:[],language:z,durationInSeconds:(N=j.duration)!=null?N:void 0,warnings:O,response:{timestamp:B,modelId:this.modelId,headers:w,body:E},...A!=null&&A.length>0&&{providerMetadata:{openai:{segments:A}}}}}async doStream(Z){var Q,X,Y,J,G,W,K;if(!Zf$(this.modelId))throw new Z$({functionality:`streaming transcription with ${this.modelId}`});let H=(Y=(X=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:X.call(Q))!=null?Y:new Date,F=await x$({provider:"openai",providerOptions:Z.providerOptions,schema:$f$}),U=[],N=(G=(J=Z.providerOptions)==null?void 0:J.openai)!=null?G:{};for(let O of["include","prompt","temperature","timestampGranularities"])if(N[O]!=null)U.push({type:"unsupported",feature:`providerOptions.openai.${O}`,details:`OpenAI streaming transcription does not support ${O}.`});let B=k1((K=(W=this.config).headers)==null?void 0:K.call(W),Z.headers),D=tZ6({modelId:this.modelId,inputAudioFormat:Z.inputAudioFormat,providerOptions:F});return{request:{body:D},response:{timestamp:H,modelId:this.modelId},stream:nZ6({webSocket:this.config.webSocket,url:bB0(this.config.url({path:"/realtime?intent=transcription",modelId:this.modelId})),headers:B,sessionUpdate:D,language:F==null?void 0:F.language,warnings:U,audio:Z.audio,abortSignal:Z.abortSignal,includeRawChunks:Z.includeRawChunks})}}};rZ6=K0(()=>e(aZ6.object({}))),sZ6=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async doStream(Z){var Q,X,Y,J,G;if(Z.targetLanguage==null)throw new c8({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let W=(Y=(X=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:X.call(Q))!=null?Y:new Date;await x$({provider:"openai",providerOptions:Z.providerOptions,schema:rZ6});let K=[];if(Z76(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=k1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),F=$76({targetLanguage:Z.targetLanguage});return{request:{body:F},response:{timestamp:W,modelId:this.modelId},stream:eZ6({webSocket:this.config.webSocket,url:bB0(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})}}};X76=K0(()=>e(M3.object({id:M3.string(),name:M3.string().nullish(),description:M3.string().nullish(),default_version:M3.string().nullish(),latest_version:M3.string().nullish(),created_at:M3.number(),updated_at:M3.number().nullish()}))),uk9=K0(()=>e(M3.object({id:M3.string(),version:M3.string().nullish(),name:M3.string().nullish(),description:M3.string().nullish()})));lk9=JR()});function W76($){return lU("LLMAPI listModels",`${Af$}/models`,{headers:$?{Authorization:`Bearer ${$}`}:{},signal:AbortSignal.timeout(15000)})}var Af$="https://api.llmapi.ai/v1",G76="https://llmapi.ai/wp-content/uploads/2026/01/Frame-2085662993.png",Rf$;var qf$=L(()=>{UD0();IA();Rf$={info:{id:"llmapi",name:"LLMAPI",description:"One API key, 400+ models across every provider",logo:G76},supportedMethods:["api-key"],create($){let Z=JR({apiKey:$||"not-needed",baseURL:Af$,name:"llmapi"}),Q=Object.assign((...X)=>Z.chat(...X),Z,{languageModel:Z.chat});return{info:this.info,aiSdk:Q,async listModels(){let X=await W76($);if(!X.ok)await uX("LLMAPI listModels",X);let{data:Y}=await cU("LLMAPI listModels",X);return Y.filter((J)=>typeof J.id==="string"&&J.id.length>0).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:OB0(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 K76($,Z){return lU("OpenAI-compatible listModels",`${$}/models`,{headers:Z,signal:AbortSignal.timeout(15000)})}function H76($){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 F76="https://assets.decocache.com/decocms/d138aa7e-5b8c-4821-9e64-6aff40df2cdc/ChatGPT_logo.svg",Mf$;var If$=L(()=>{UD0();IA();Mf$={info:{id:"openai-compatible",name:"OpenAI Compatible",description:"Custom OpenAI-compatible endpoint",logo:F76},supportedMethods:["api-key"],create($){let{baseUrl:Z,apiKey:Q}=H76($),X=JR({baseURL:Z,apiKey:Q||"not-needed",name:"openai-compatible"}),Y=Object.assign((...J)=>X.chat(...J),X,{languageModel:X.chat});return{info:this.info,aiSdk:Y,async listModels(){let J={};if(Q)J.Authorization=`Bearer ${Q}`;let G=await K76(Z,J);if(!G.ok)await uX("OpenAI-compatible listModels",G);return(await cU("OpenAI-compatible listModels",G)).data.filter((K)=>typeof K.id==="string"&&K.id.length>0).map((K)=>({providerId:"openai-compatible",modelId:K.id,title:K.id,description:K.owned_by?`Owned by ${K.owned_by}`:null,logo:null,capabilities:[],limits:null,costs:null}))}}}}});function d9(){return{...P0().aiGatewayEnabled&&{deco:GE},anthropic:Pv$,google:Px$,openrouter:jB0,llmapi:Rf$,"openai-compatible":Mf$}}var GK=L(()=>{Tv$();Tx$();qf$();If$();iY1();gd();X$()});function B76($,Z,Q){om($,Z,Q)}function L76($,Z,Q){am($,Z,Q)}function kW1($){V80.delete($)}async function CW1($,Z){if(!P0().plansEnabled)return null;if(!P0().aiGatewayEnabled)return null;let Q=V80.get(Z);if(Q&&Date.now()-Q.at<kf$)return Q.value;let X=VW1.get(Z);if(X)return X;let Y=D76($,Z,Q).finally(()=>{VW1.delete(Z)});return VW1.set(Z,Y),Y}async function D76($,Z,Q){let X=d9().deco;if(!X?.getEntitlements)return null;let Y=$.auth.user?.id??$.auth.apiKey?.userId;if(!Y)return Vf$(Z,Q);try{let J=await lQ(Y),{features:G,usage:W,modelPins:K,credits:H}=await X.getEntitlements(J,Z);if(!G||typeof G!=="object")throw new VA(502);let F={features:G,modelPins:K,usageState:W?.state??null,creditsUsd:H?.remainingUsd??null};return B76(V80,Z,F),L76(V80,N76,kf$),F}catch(J){let G=J instanceof VA&&J.isDefinitive,W=J instanceof VA&&J.isDormant,K={organizationId:Z,servedStale:!!Q,status:J instanceof VA?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 Vf$(Z,Q)}}function Vf$($,Z){if(Z&&Date.now()-Z.at>=U76)return V80.delete($),null;return Z?.value??null}async function QG($,Z,Q){let X=await CW1($,Z);return Cf$(X?.features??null,Q)}function Cf$($,Z){if(!$)return!0;return $[Z]===!0}function O76($,Z){if($!=="exhausted")return!1;return!(Z!==null&&Z>0)}async function I3($,Z,Q){let X=await CW1($,Z);if(!O76(X?.usageState??null,X?.creditsUsd??null))return;throw new ND0(`${Q} is paused: this organization has used its monthly AI allowance`)}async function Sf$($,Z,Q){let X=await CW1($,Z);if(!X)return null;if(Cf$(X.features,"model_choice"))return null;return X.modelPins?.[Q]??null}var LN,kf$=60000,U76=600000,V80,N76=1e4,VW1,ND0;var YF=L(()=>{vH();GK();gd();qH();X$();LN=class LN extends HQ{feature;code="feature_not_in_plan";constructor($,Z){super($);this.feature=Z;this.name="FeatureNotInPlanError"}};V80=new Map;VW1=new Map;ND0=class ND0 extends HQ{code="ai_budget_exhausted";constructor($){super($);this.name="AiBudgetExhaustedError"}}});function _f$($){let{ctx:Z,toolName:Q,organizationId:X,durationMs:Y,isError:J}=$,G={"tool.name":Q,"organization.id":X,status:J?"error":"success"};Z.meter.createHistogram("studio_tool.execution.duration",{description:"Duration of in-process Studio tool executions in milliseconds",unit:"ms"}).record(Y,G),Z.meter.createCounter("studio_tool.execution.count",{description:"Number of in-process Studio tool executions"}).add(1,G)}import{SpanStatusCode as vf$}from"@opentelemetry/api";function m($){return{...$,execute:async(Z,Q)=>{let X=performance.now(),Y=!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&&!KV$($.name)&&await kB0(Q.db,G))throw new t10(`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 QG(Q,G,$.requiresFeature))throw new LN(`${$.name} needs the ${$.requiresFeature} feature, which this organization's plan does not include`,$.requiresFeature);if($.requiresAiBudget&&G)await I3(Q,G,$.name);let W=await $.handler(Z,Q);return J.setStatus({code:vf$.OK}),W}catch(G){throw Y=!0,J.setStatus({code:vf$.ERROR,message:G.message}),J.recordException(G),G}finally{_f$({ctx:Q,toolName:$.name,organizationId:Q.organization?.id??"system",durationMs:performance.now()-X,isError:Y}),J.end()}}))}}}var _0=L(()=>{SA();YF()});function W0($){if(!$.organization)throw Error("This operation requires organization scope");return $.organization}function t0($){return $.auth.user?.id??$.auth.apiKey?.userId}function GR($){return!!($.auth.user||$.auth.apiKey)}function o($){if(!GR($))throw Error("Authentication required")}import{z as L4}from"zod";var ff$,xf$=1000,j76=500,bf$,yf$,gf$,hf$,uf$,lf$,cf$,mf$,df$,if$;var _i=L(()=>{ff$=L4.record(L4.string(),L4.array(L4.string())),bf$=L4.record(L4.string(),L4.array(L4.string()).max(j76)).refine(($)=>Object.keys($).length<=xf$,{message:`Permissions cannot grant more than ${xf$} resources`}),yf$=L4.object({id:L4.string().describe("Unique identifier for the API key"),name:L4.string().describe("Human-readable name for the API key"),userId:L4.string().describe("ID of the user who owns this API key"),permissions:ff$.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:L4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:L4.string().datetime().describe("When the API key was created (ISO 8601)")}),gf$=L4.object({name:L4.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:bf$.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:L4.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:L4.record(L4.string(),L4.unknown()).optional().describe("Additional metadata to store with the API key")}),hf$=L4.object({id:L4.string().describe("Unique identifier for the API key"),name:L4.string().describe("Human-readable name for the API key"),key:L4.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:ff$.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:L4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:L4.string().datetime().describe("When the API key was created (ISO 8601)")}),uf$=L4.object({}),lf$=L4.object({items:L4.array(yf$).describe("List of API keys (without key values)")}),cf$=L4.object({keyId:L4.string().describe("ID of the API key to update"),name:L4.string().min(1).max(64).optional().describe("New name for the API key"),permissions:bf$.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:L4.record(L4.string(),L4.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),mf$=L4.object({item:yf$.describe("The updated API key (without key value)")}),df$=L4.object({keyId:L4.string().describe("ID of the API key to delete")}),if$=L4.object({success:L4.boolean().describe("Whether the deletion was successful"),keyId:L4.string().describe("ID of the deleted API key")})});var SW1;var pf$=L(()=>{F6();_0();_i();SW1=m({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:gf$,outputSchema:hf$,handler:async($,Z)=>{o(Z),await Z.access.check();let Q=await Z.boundAuth.apiKey.create({name:$.name,permissions:$.permissions,expiresIn:$.expiresIn,metadata:{...$.metadata,organization:Z.organization}}),X=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,Y=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,J=t0(Z);if(J)h1.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:!!X}});return{id:Q.id,name:Q.name??$.name,key:Q.key,permissions:Q.permissions??{},expiresAt:X,createdAt:Y}}})});var _W1;var nf$=L(()=>{F6();_0();_i();_W1=m({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:df$,outputSchema:if$,handler:async($,Z)=>{o(Z),await Z.access.check();let Q=t0(Z);if(!Q)throw Error("User ID required to delete API key");let Y=(await Z.boundAuth.apiKey.list())?.find((K)=>K.id===$.keyId);if(!Y)throw Error("API key not found");let G=Y.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)h1.capture({distinctId:Q,event:"api_key_deleted",groups:{organization:W},properties:{key_id:$.keyId,organization_id:W}});return{success:!0,keyId:$.keyId}}})});var vW1;var tf$=L(()=>{_0();_i();vW1=m({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:uf$,outputSchema:lf$,handler:async($,Z)=>{o(Z),await Z.access.check();let Q=await Z.boundAuth.apiKey.list(),X=Z.organization?.id;return{items:(Q??[]).filter((J)=>{return J.metadata?.organization?.id===X}).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 xW1;var of$=L(()=>{_0();_i();xW1=m({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:cf$,outputSchema:mf$,handler:async($,Z)=>{if(o(Z),await Z.access.check(),!t0(Z))throw Error("User ID required to update API key");let Y=(await Z.boundAuth.apiKey.list())?.find((H)=>H.id===$.keyId);if(!Y)throw Error(`API key not found: ${$.keyId}`);let G=Y.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 af$=L(()=>{pf$();nf$();tf$();of$();_i()});function FD($){let Z=$.trim();if(!Z)return{ok:!1,error:"Enter a website URL."};let Q=E76.test(Z),X=z76.test(Z),Y=P76.test(Z);if(Q&&!X&&!Y)return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let J=X?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||!T76.test(K)))return{ok:!1,error:"Enter a valid website URL."};return G.protocol="https:",{ok:!0,value:G.origin}}function fW1($){if(!$)return null;let Z=FD($);return Z.ok?new URL(Z.value).hostname:null}var E76,z76,P76,T76;var vi=L(()=>{E76=/^[a-zA-Z][a-zA-Z\d+.-]*:/,z76=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//,P76=/^[^\s/:?#]+\.[^\s/:?#]+:\d+(?:[/?#]|$)/,T76=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i});import{z as XG}from"zod";function BD0($){return{repository_id:$.repositoryId,provider:$.provider,host:$.host,path:$.path,default_branch:$.defaultBranch??null,web_url:$.webUrl??null}}function rf$($){let Z=A76.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 LD0($){return $.provider==="github"&&$.host.toLowerCase()==="github.com"?$.path:null}var bW1,A76;var DD0=L(()=>{bW1=XG.object({repositoryId:XG.string().min(1),provider:XG.enum(["github","gitlab","bitbucket"]),host:XG.string().min(1),path:XG.string().min(1),defaultBranch:XG.string().nullable().optional(),webUrl:XG.string().nullable().optional()}),A76=XG.object({repository_id:XG.string().min(1),provider:XG.enum(["github","gitlab","bitbucket"]),host:XG.string().min(1),path:XG.string().min(1),default_branch:XG.string().nullable().optional(),web_url:XG.string().nullable().optional()})});import{z as OQ}from"zod";function WK($){if($.baseUrl)return $.baseUrl.replace(/\/+$/,"");return(($.settings??P0()).reportsInternalApiUrl??R76).replace(/\/+$/,"")}function ef$($={}){return`${WK($)}/api/v2/mcp`}function xE($){let Z=$.apiKey??($.settings??P0()).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 k80($){return new URL($).hostname}function M76($){return $==="ownership_unverified"||$==="already_claimed_by_other_org"}function I76($,Z={}){switch($){case"ownership_unverified":{let Q=Z.email?`O e-mail ${Z.email}`:"Este e-mail",X=Z.domain?` ${Z.domain}`:" este site";return`${Q} n\xE3o tem permiss\xE3o para reivindicar${X}. 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 V76($){let Z=await xi($);return M76(Z?.error)?Z.error:"unknown"}async function xi($){let Z=await $.text().catch(()=>"");if(!Z)return;try{return JSON.parse(Z)}catch{return}}async function jD0($){let Z=`Reports auth failed with status ${$.status}.`,Q=await $.text().catch(()=>"");if(!Q)return Z;try{let X=JSON.parse(Q),Y=typeof X.error==="string"?X.error:typeof X.message==="string"?X.message:null;return Y?`Reports auth failed: ${Y}.`:Z}catch{return Z}}async function Zb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/upgrade`,W=await Y(G,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.orgName?{name:$.orgName}:{},...$.email?{email:$.email}:{},...$.reportUrl?{report_url:$.reportUrl}:{}}),signal:AbortSignal.timeout(OD0)});if(!W.ok){let H=await V76(W);throw new $b$(H,{email:$.email,domain:J})}let K=q76.safeParse(await xi(W));if(!K.success)throw Error("Reports auth response did not include a token.");return{authorizationToken:K.data.token}}async function Qb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/bindings`,W=await Y(G,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,provider:$.provider,resource_id:$.resourceId}),signal:AbortSignal.timeout(OD0)});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=sf$.safeParse(await xi(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 jD0(W));let K=sf$.safeParse(await xi(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 Xb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/run`,W=await Y(G,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.repository?{repository:BD0($.repository)}:{},...$.githubRepositoryPath?{github_repo:$.githubRepositoryPath}:{}}),signal:AbortSignal.timeout(OD0)});if(W.status===409)return{triggered:!1,reason:"not_upgraded"};if(!W.ok)throw Error(await jD0(W));return{triggered:!0}}async function Yb$($,Z,Q){try{return await O8(async()=>{let X=await $(Z,{...Q,signal:AbortSignal.timeout(OD0)});if(X.status>=500||X.status===429)throw new yW1(await jD0(X));return X},{maxAttempts:3,minTimeout:200,maxTimeout:2000,multiplier:2,jitter:1,isRetriable:(X)=>X instanceof yW1})}catch(X){if(X instanceof k5&&X.cause instanceof Error)throw X.cause;throw X}}async function Jb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/connections/status?org_id=${encodeURIComponent($.orgId)}`,W=await Yb$(Y,G,{method:"GET",headers:{Authorization:`Bearer ${X}`}});if(W.status===404||W.status===409)return{providers:{},claimed:!1};if(!W.ok)throw Error(await jD0(W));let K=k76.safeParse(await xi(W));return{providers:K.success?K.data.providers:{},claimed:!0}}async function Gb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/unlink`,W=await Yb$(Y,G,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId})});if(!W.ok)throw Error(`Reports unlink failed with status ${W.status}.`);let K=C76.safeParse(await xi(W));if(!K.success)throw Error("Reports unlink response did not say whether it unlinked.");return K.data}var R76,OD0=15000,q76,sf$,$b$,yW1,k76,C76;var UD=L(()=>{r8();$8();DD0();X$();R76=new URL(tF$).origin,q76=OQ.object({token:OQ.string().min(1)}),sf$=OQ.object({binding:OQ.object({resource_id:OQ.string(),evidence:OQ.string()}).optional(),reason:OQ.string().optional(),detail:OQ.string().optional()});$b$=class $b$ extends Error{code;constructor($,Z={}){super(I76($,Z));this.name="ReportsClaimError",this.code=$}};yW1=class yW1 extends Error{};k76=OQ.object({providers:OQ.record(OQ.string(),OQ.object({connected:OQ.boolean(),via:OQ.enum(["oauth","sa"]).nullable(),resource:OQ.string().nullable()}))});C76=OQ.object({unlinked:OQ.boolean(),reason:OQ.string().optional()})});import{z as V3}from"zod";var S76,_76,gW1;var Wb$=L(()=>{vi();_0();UD();S76=V3.object({siteUrl:V3.string().min(1).describe("Website URL of the store being bound."),provider:V3.enum(["ga4","gsc"]).describe("Which Google source to bind: ga4 (Analytics) or gsc (Search Console)."),resourceId:V3.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/).")}),_76=V3.discriminatedUnion("ok",[V3.object({ok:V3.literal(!0),resourceId:V3.string(),evidence:V3.string()}),V3.object({ok:V3.literal(!1),reason:V3.string(),detail:V3.string()})]),gW1=m({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:S76,outputSchema:_76,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check("REPORTS_BIND","COMMERCE_DISCOVERY_BIND");let X=FD($.siteUrl);if(!X.ok)throw Error(X.error);return Qb$({siteUrl:X.value,orgId:Q.id,provider:$.provider,resourceId:$.resourceId.trim()})}})});import{z as DN}from"zod";var v76,x76,hW1;var Kb$=L(()=>{vi();_0();UD();v76=DN.object({siteUrl:DN.string().min(1).describe("Website URL of the store to inspect.")}),x76=DN.object({providers:DN.record(DN.string(),DN.object({connected:DN.boolean(),via:DN.enum(["oauth","sa"]).nullable(),resource:DN.string().nullable()})),claimed:DN.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.")}),hW1=m({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:v76,outputSchema:x76,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check("REPORTS_CONNECTION_STATUS","COMMERCE_DISCOVERY_CONNECTION_STATUS");let X=FD($.siteUrl);if(!X.ok)throw Error(X.error);return Jb$({siteUrl:X.value,orgId:Q.id})}})});import{z as fE}from"zod";function g76($){let Z=y76.safeParse($),Q=Z.success?Z.data:void 0,X=(Q?rf$(Q.repository):void 0)??void 0,Y=Q&&typeof Q.github_repo==="string"&&Q.github_repo.length>0?Q.github_repo:void 0;return{repository:X??void 0,githubRepositoryPath:(X?LD0(X):Y)??void 0}}var f76,b76,y76,uW1;var Hb$=L(()=>{r8();DD0();vi();_0();UD();f76=fE.object({siteUrl:fE.string().min(1).describe("Website URL to run the diagnostic for.")}),b76=fE.object({triggered:fE.boolean(),reason:fE.string().optional()}),y76=fE.object({repository:fE.unknown().optional(),github_repo:fE.string().optional()}).passthrough().nullable().optional();uW1=m({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:f76,outputSchema:b76,requiresFeature:"diagnostic_enriched",requiresAiBudget:!0,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check("REPORTS_RUN","COMMERCE_DISCOVERY_RUN");let X=FD($.siteUrl);if(!X.ok)throw Error(X.error);let Y=K4.REPORTS(Q.id),J=await Z.storage.connections.findById(Y,Q.id),{repository:G,githubRepositoryPath:W}=g76(J?.configuration_state);return Xb$({siteUrl:X.value,orgId:Q.id,repository:G,githubRepositoryPath:W})}})});import{z as P5}from"zod";var h76,C80,u76,l76,c76,m76,Fb$,Ub$,ON,S80;var Nb$=L(()=>{h76=["github","gitlab","bitbucket"],C80=P5.enum(h76),u76=["github_app","oauth","token","github_cli"],l76=P5.enum(u76),c76=["active","revoked"],m76=P5.enum(c76),Fb$=P5.object({provider:C80,host:P5.string().min(1).describe("Provider host, e.g. github.com"),path:P5.string().min(1).describe("Full namespace path, e.g. owner/name or group/sub/project")}),Ub$=P5.object({id:P5.string(),organizationId:P5.string(),type:C80,host:P5.string(),authKind:l76,externalAccountId:P5.string().describe("Provider-side account identity: installation id (GitHub App), user/group id (GitLab) or user/workspace uuid (Bitbucket)."),login:P5.string().describe("Display login of the account/namespace"),avatarUrl:P5.string().nullable(),installationId:P5.number().nullable().describe("GitHub App installation id; null for other auth kinds."),status:m76,createdAt:P5.string(),updatedAt:P5.string()}),ON=P5.string().regex(/^[a-z][a-z0-9-]{0,31}$/,"lowercase letters, digits and dashes only"),S80=P5.object({id:P5.string(),organizationId:P5.string(),accountId:P5.string().nullable().describe("Credential-holding account; null for anonymous public clones."),provider:C80,host:P5.string(),path:P5.string(),externalId:P5.string().nullable().describe("Provider repository/project id, when known."),defaultBranch:P5.string().nullable(),webUrl:P5.string(),visibility:P5.enum(["public","private","internal"]).nullable(),sandboxImage:ON.describe("Sandbox image this repository's sandboxes boot from."),createdAt:P5.string(),updatedAt:P5.string()})});function p76($){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 Bb$($){let Z=$.toLowerCase();return Z.startsWith("www.")?Z.slice(4):Z}function tX($,Z){let Q=$.trim();if(!Q)return null;let X,Y,J=/^(?:[\w.-]+@)?([\w.-]+(?::\d+)?):(?!\/\/)(.+)$/.exec(Q);if(J&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(Q))X=J[1],Y=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;X=F.host,Y=F.pathname}else if(Z?.provider)X=Z.host??wD0[Z.provider],Y=Q;else return null;X=Bb$(X);let G=Z?.provider??p76(X);if(!G)return null;let W=Y.split("/").map((F)=>F.trim()).filter(Boolean),K=W.indexOf("-");if(K>=0)W=W.slice(0,K);if(i76.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:X,path:W.join("/")}}function JF($){return`${$.host.toLowerCase()}/${$.path.toLowerCase()}`}function lW1($){let Z=$.path.split("/");return Z[Z.length-1]??$.path}function n76($){let Z=$.path.lastIndexOf("/");return Z<0?"":$.path.slice(0,Z)}function y5($){return{owner:n76($),name:lW1($)}}function YG($){return`https://${$.host}/${$.path}`}function _80($,Z){let Q=`${$.host}/${$.path}.git`;if(!Z)return`https://${Q}`;return`https://${d76[$.provider]}:${encodeURIComponent(Z)}@${Q}`}function ND($,Z){let Q=Bb$(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 fi($,Z){return{provider:"github",host:wD0.github,path:`${$}/${Z}`}}var wD0,d76,i76;var cW1=L(()=>{wD0={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"},d76={github:"x-access-token",gitlab:"oauth2",bitbucket:"x-token-auth"},i76=new Set(["github","bitbucket"])});function KK($,Z){return`${YG($)}/${t76[$.provider]}/${Z}`}function a76($){let Z=$.toLowerCase();return o76[Z]??Z}function Ob$($,Z,Q){let X=Number($[3]);if(!Number.isSafeInteger(X)||X<=0)return null;let Y=a76($[1]),J=$[2],G=Z?decodeURIComponent(J):J;if(/^\d+$/.test(G))return null;let W=`https://${Y}/${G}`,K=tX(W)??(Q?tX(W,{provider:Q}):null);if(!K)return null;return{repo:K,number:X,url:KK(K,X)}}function ED0($){let Z=$.trim();if(!Z)return null;for(let{re:Q,api:X,provider:Y}of Db$){let J=Q.exec(Z),G=J?Ob$(J,X===!0,Y):null;if(G)return G}return null}function mW1($){let Z=$.length>Lb$?$.slice(0,Lb$):$;for(let{re:Q,api:X,provider:Y}of Db$){let J=Q.exec(Z),G=J?Ob$(J,X===!0,Y):null;if(G)return G}return null}var t76,Db$,o76,Lb$=200000;var dW1=L(()=>{cW1();t76={github:"pull",gitlab:"-/merge_requests",bitbucket:"pull-requests"};Db$=[{re:/https?:\/\/([^/\s"']+)\/([^\s"']+?)\/-\/merge_requests\/(\d+)/,provider:"gitlab"},{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,provider:"gitlab"},{re:/https?:\/\/([^/\s"']+)\/2\.0\/repositories\/([^/\s"']+\/[^/\s"']+)\/pullrequests\/(\d+)/,api:!0}],o76={"api.github.com":"github.com","api.bitbucket.org":"bitbucket.org"}});function jb$($){return iW1[$]}function pW1($,Z){return iW1[$].checkoutCommand.replace("{number}",String(Z))}function wb$($,Z){let{abbreviation:Q,numberSigil:X}=iW1[$];return`${Q} ${X}${Z}`}var iW1;var Eb$=L(()=>{iW1={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 a4=L(()=>{Nb$();cW1();dW1();Eb$()});async function v80($,Z,Q){let X=new AbortController,Y,J=new Promise((W,K)=>{Y=setTimeout(()=>{X.abort(),K(new zb$($.id,Q))},Q)}),G=(async()=>{let W=await k3($,Z,!0);try{return(await W.listTools(void 0,{timeout:Q,signal:X.signal})).tools}finally{await W.close().catch(()=>{})}})();G.catch(()=>{});try{return await Promise.race([G,J])}finally{if(Y)clearTimeout(Y)}}var zb$;var Pb$=L(()=>{x80();zb$=class zb$ extends Error{constructor($,Z){super(`listTools timed out after ${Z}ms for connection ${$}`);this.name="ListToolsTimeoutError"}}});var nW1=b((Tb$)=>{Object.defineProperty(Tb$,"__esModule",{value:!0});Tb$.kvPrefix=Tb$.KvWatchInclude=void 0;Tb$.KvWatchInclude={LastValue:"",AllHistory:"history",UpdatesOnly:"updates"};Tb$.kvPrefix="KV_"});var xb$=b((_b$)=>{Object.defineProperty(_b$,"__esModule",{value:!0});_b$.KvStatusImpl=_b$.Bucket=_b$.Kvm=_b$.kvOperationHdr=void 0;_b$.Base64KeyCodec=s76;_b$.NoopKvCodecs=tW1;_b$.defaultBucketOpts=qb$;_b$.validateKey=Mb$;_b$.validateSearchKey=Ib$;_b$.hasWildcards=Vb$;_b$.validateBucket=zD0;var $Z=Z3(),N9=ZH0(),e9=nW1();function s76(){let $=(Z,Q)=>{let X=[];for(let Y of Z.split("."))switch(Y){case">":case"*":X.push(Y);break;default:X.push(Q(Y));break}return X.join(".")};return{encode(Z){return $(Z,btoa)},decode(Z){return $(Z,atob)}}}function tW1(){return{key:{encode($){return $},decode($){return $}},value:{encode($){return typeof $==="string"?new TextEncoder().encode($):$},decode($){return $}}}}function qb$(){return{replicas:1,history:1,timeout:2000,max_bytes:-1,maxValueSize:-1,codec:tW1(),storage:N9.StorageType.File}}_b$.kvOperationHdr="KV-Operation";var Rb$="$KV",e76=/^[-/=.\w]+$/,$Q6=/^[-/=.>*\w]+$/,ZQ6=/^[-\w]+$/;function Mb$($){if($.startsWith(".")||$.endsWith(".")||!e76.test($))throw Error(`invalid key: ${$}`)}function Ib$($){if($.startsWith(".")||$.endsWith(".")||$.includes("..")||!$Q6.test($))throw Error(`invalid key: ${$}`)}function Vb$($){if($.startsWith(".")||$.endsWith("."))throw Error(`invalid key: ${$}`);let Z=$.split("."),Q=!1;for(let X=0;X<Z.length;X++)switch(Z[X]){case"*":Q=!0;break;case">":if(X!==Z.length-1)throw Error(`invalid key: ${$}`);Q=!0;break;default:}return Q}function zD0($){if(!ZQ6.test($))throw Error(`invalid bucket name: ${$}`)}class kb${js;constructor($){this.js=(0,N9.toJetStreamClient)($)}create($,Z={}){return this.#$($,Z)}open($,Z={}){return Z.bindOnly=!0,this.#$($,Z)}#$($,Z={}){let{ok:Q,min:X}=this.js.nc.features.get($Z.Feature.JS_KV);if(!Q)return Promise.reject(Error(`kv is only supported on servers ${X} or better`));if(Z.bindOnly)return bi.bind(this.js,$,Z);return bi.create(this.js,$,Z)}list(){let $=(Q)=>{let Y=Q.streams.filter((G)=>{return G.config.name.startsWith(e9.kvPrefix)});Y.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(Y.length)J=this.js.nc.info?.cluster??"";return Y.map((G)=>{return new PD0(G,J)})},Z=`${this.js.prefix}.STREAM.LIST`;return new N9.ListerImpl(Z,$,this.js)}}_b$.Kvm=kb$;class bi{js;jsm;stream;bucket;direct;codec;prefix;editPrefix;useJsPrefix;_prefixLen;constructor($,Z,Q){zD0($),this.js=Z,this.jsm=Q,this.bucket=$,this.prefix=Rb$,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create($,Z,Q={}){zD0(Z);let X=await $.jetstreamManager(),Y=new bi(Z,$,X);return await Y.init(Q),Y}static async bind($,Z,Q={}){let X=$.getOptions()?.checkAPI||Q.bindOnly===!1,Y=await $.jetstreamManager(X),J={config:{allow_direct:Q.allow_direct}};zD0(Z);let G=new bi(Z,$,Y);return J.config.name=Q.streamName??G.bucketName(),Object.assign(G,J),G.stream=J.config.name,G.codec=Q.codec||tW1(),G.direct=J.config.allow_direct??!1,G.initializePrefixes(J),G}async init($={}){let Z=Object.assign(qb$(),$);this.codec=Z.codec;let Q={};if(this.stream=Q.name=$.streamName??this.bucketName(),Q.retention=N9.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,$Z.nanos)(Z.markerTTL);if($.mirror){let H=Object.assign({},$.mirror);if(!H.name.startsWith(e9.kvPrefix))H.name=`${e9.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(e9.kvPrefix)?U.name.substring(e9.kvPrefix.length):U.name;if(!U.name.startsWith(e9.kvPrefix))U.name=`${e9.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?N9.StoreCompression.S2:N9.StoreCompression.None;let X=this.js.nc,Y=X.getServerVersion(),J=Y?(0,$Z.compare)(Y,(0,$Z.parseSemVer)("2.7.2"))>=0:!1;Q.discard=J?N9.DiscardPolicy.New:N9.DiscardPolicy.Old;let{ok:G,min:W}=X.features.get($Z.Feature.JS_ALLOW_DIRECT);if(!G&&$.allow_direct===!0){let H=Y?`${Y.major}.${Y.minor}.${Y.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,$Z.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(e9.kvPrefix))Q=Q.substring(e9.kvPrefix.length);if(Z.external&&Z.external.api!==""){let X=Z.name.substring(e9.kvPrefix.length);this.useJsPrefix=!1,this.prefix=`$KV.${X}`,this.editPrefix=`${Z.external.api}.$KV.${Q}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${e9.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`${Rb$}.${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=Mb$;validateSearchKey=Ib$;hasWildcards=Vb$;close(){return Promise.resolve()}dataLen($,Z){let Q=Z?Z.get(N9.JsHeaders.MessageSizeHdr)||"":"";if(Q!=="")return parseInt(Q,10);return $.length}smToEntry($){return new Cb$(this.bucket,this.prefixLen,$,this.codec)}jmToWatchEntry($,Z){return new Sb$(this.bucket,this.prefixLen,$,Z,this.codec)}async create($,Z,Q){let X;try{let J={previousSeq:0},G=await this._put($,Z,J,Q);return Promise.resolve(G)}catch(J){if(X=J,J instanceof N9.JetStreamApiError){let G=J;if(G.code!==N9.JetStreamApiCodes.StreamWrongLastSequence&&G.code!==N9.JetStreamApiCodes.StreamWrongLastSequenceUnknown)return Promise.reject(J)}}let Y=0;try{let J=await this.get($);if(J?.operation==="DEL"||J?.operation==="PURGE")return Y=J!==null?J.revision:0,this._put($,Z,{previousSeq:Y},Q);else return Promise.reject(X)}catch(J){return Promise.reject(J)}}update($,Z,Q,X){if(Q<=0)throw Error("version must be greater than 0");return this.put($,Z,{previousSeq:Q,timeout:X})}async _put($,Z,Q={},X){let Y=this.encodeKey($);this.validateKey(Y),Z=this.codec.value.encode(Z);let J={timeout:Q?.timeout};if(Q.previousSeq!==void 0){let G=(0,$Z.headers)();J.headers=G,G.set(N9.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Q.previousSeq}`)}if(X)(J.headers||(0,$Z.headers)()).set(N9.PubHeaders.MessageTTL,X);try{return(await this.js.publish(this.subjectForKey(Y,!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 X={last_by_subj:this.subjectForKey(Q)};if(Z&&Z.revision>0)X={seq:Z.revision};let Y=null;try{if(this.direct)Y=await this.jsm.direct.getMessage(this.bucketName(),X);else Y=await this.jsm.streams.getMessage(this.bucketName(),X);if(Y===null)return null;let J=this.smToEntry(Y);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 X=Date.now()-$,Y=Z.map((G)=>{let W=this.subjectForKey(G.key);if(G.created.getTime()>=X)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(Y);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 X=await this.keys($),Y=[];for await(let J of X)if(Y.push(this._doDeleteOrPurge(J,Z)),Y.length===100)await Promise.all(Y),Y.length=0;if(Y.length>0)await Promise.all(Y)}async _doDeleteOrPurge($,Z,Q){let X=this.encodeKey($);this.validateKey(X);let Y=(0,$Z.headers)();if(Y.set(_b$.kvOperationHdr,Z),Z==="PURGE"){let J=Q;if(Y.set(N9.JsHeaders.RollupHdr,N9.JsHeaders.RollupValueSubject),typeof J?.ttl==="string"&&J.ttl!=="")Y.set(N9.PubHeaders.MessageTTL,`${J.ttl}`)}if(Q?.previousSeq)Y.set(N9.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Q.previousSeq}`);await this.js.publish(this.subjectForKey(X,!0),$Z.Empty,{headers:Y})}_buildCC($,Z,Q={}){let Y=(!Array.isArray($)?[$]:$).map((W)=>{let K=this.encodeKey(W);return this.validateSearchKey(W),this.fullKeyName(K)}),J=N9.DeliverPolicy.LastPerSubject;if(Z===e9.KvWatchInclude.AllHistory)J=N9.DeliverPolicy.All;if(Z===e9.KvWatchInclude.UpdatesOnly)J=N9.DeliverPolicy.New;let G=void 0;if(Y.length===1)G=Y[0],Y=void 0;return Object.assign({deliver_policy:J,ack_policy:N9.AckPolicy.None,filter_subjects:Y,filter_subject:G,flow_control:!0,idle_heartbeat:(0,$Z.nanos)(5000)},Q)}remove($){return this.purge($)}async history($={}){let Z=$.key??">",Q={};Q.headers_only=$.headers_only||!1;let X=new $Z.QueuedIteratorImpl,Y=()=>{X.stop()},J=this._buildCC(Z,e9.KvWatchInclude.AllHistory,Q),G=await this.js.consumers.getPushConsumer(this.stream,J);if(X._data=G,(await G.info(!0)).num_pending===0)return X.push(Y),X;let K=await G.consume({callback:(H)=>{let F=this.jmToWatchEntry(H,!1);if(X.push(F),X.received++,H.info.pending===0)X.push(Y)}});return K.closed().then(()=>{X.push(Y)}),(async()=>{for await(let H of K.status())switch(H.type){case"heartbeat":X.push(()=>{X.stop()});break}})().then(),X.iterClosed.then(()=>{K.stop()}),X}canSetWatcherName(){let $=this.js.nc,{ok:Z}=$.features.get($Z.Feature.JS_NEW_CONSUMER_CREATE_API);return Z}async watch($={}){let Z=$.key??">",Q=new $Z.QueuedIteratorImpl,X={};X.headers_only=$.headers_only||!1;let Y=e9.KvWatchInclude.LastValue;if($.include===e9.KvWatchInclude.AllHistory)Y=e9.KvWatchInclude.AllHistory;else if($.include===e9.KvWatchInclude.UpdatesOnly)Y=e9.KvWatchInclude.UpdatesOnly;let J=$.ignoreDeletes===!0,G=this._buildCC(Z,Y,X);if(G.name=`KV_WATCHER_${$Z.nuid.next()}`,$.resumeFromRevision&&$.resumeFromRevision>0)G.deliver_policy=N9.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=Y===e9.KvWatchInclude.UpdatesOnly||H===0;Q._data=W;let U=0,N=await W.consume({callback:(B)=>{if(!F)U++,F=U>=H;let D=this.jmToWatchEntry(B,F);if(J&&D.operation==="DEL")return;Q.push(D),Q.received++}});return Q.iterClosed.then(()=>{N.stop()}),N.closed().then(()=>{Q.push(()=>{Q.stop()})}),Q}async keys($=">"){let Z=new $Z.QueuedIteratorImpl,Q=this._buildCC($,e9.KvWatchInclude.LastValue,{headers_only:!0}),X=await this.js.consumers.getPushConsumer(this.stream,Q);if((await X.info()).num_pending===0)return Z.stop(),Z;Z._data=X;let J=await X.consume({callback:(G)=>{let W=G.headers?.get(_b$.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(),X=await this.jsm.streams.info(Q);return new PD0(X,Z)}}_b$.Bucket=bi;class PD0{si;cluster;constructor($,Z=""){this.si=$,this.cluster=Z}get bucket(){return this.si.config.name.startsWith(e9.kvPrefix)?this.si.config.name.substring(e9.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,$Z.millis)(this.si.config.max_age)}get markerTTL(){if(typeof this.si.config.subject_delete_marker_ttl==="number")return(0,$Z.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!==N9.StoreCompression.None;return!1}}_b$.KvStatusImpl=PD0;class Cb${bucket;sm;prefixLen;codec;constructor($,Z,Q,X){this.bucket=$,this.prefixLen=Z,this.sm=Q,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 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(_b$.kvOperationHdr)||"PUT"}get length(){let $=this.sm.header.get(N9.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}json($){return JSON.parse($Z.TD.decode(this.value),$)}string(){return $Z.TD.decode(this.value)}}class Sb${bucket;sm;prefixLen;update;codec;constructor($,Z,Q,X,Y){this.bucket=$,this.prefixLen=Z,this.sm=Q,this.update=X,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 created(){return new Date((0,$Z.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(_b$.kvOperationHdr)||"PUT"}get delta(){return this.sm.info.pending}get length(){let $=this.sm.headers?.get(N9.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}get isUpdate(){return this.update}json($){return JSON.parse($Z.TD.decode(this.value),$)}string(){return $Z.TD.decode(this.value)}}});var oW1=b((GF)=>{Object.defineProperty(GF,"__esModule",{value:!0});GF.validateKey=GF.validateBucket=GF.NoopKvCodecs=GF.Kvm=GF.defaultBucketOpts=GF.Bucket=GF.Base64KeyCodec=GF.KvWatchInclude=GF.kvPrefix=void 0;var fb$=nW1();Object.defineProperty(GF,"kvPrefix",{enumerable:!0,get:function(){return fb$.kvPrefix}});Object.defineProperty(GF,"KvWatchInclude",{enumerable:!0,get:function(){return fb$.KvWatchInclude}});var WR=xb$();Object.defineProperty(GF,"Base64KeyCodec",{enumerable:!0,get:function(){return WR.Base64KeyCodec}});Object.defineProperty(GF,"Bucket",{enumerable:!0,get:function(){return WR.Bucket}});Object.defineProperty(GF,"defaultBucketOpts",{enumerable:!0,get:function(){return WR.defaultBucketOpts}});Object.defineProperty(GF,"Kvm",{enumerable:!0,get:function(){return WR.Kvm}});Object.defineProperty(GF,"NoopKvCodecs",{enumerable:!0,get:function(){return WR.NoopKvCodecs}});Object.defineProperty(GF,"validateBucket",{enumerable:!0,get:function(){return WR.validateBucket}});Object.defineProperty(GF,"validateKey",{enumerable:!0,get:function(){return WR.validateKey}})});var KR=b((bE)=>{Object.defineProperty(bE,"__esModule",{value:!0});bE.NoopKvCodecs=bE.Kvm=bE.defaultBucketOpts=bE.Bucket=bE.Base64KeyCodec=bE.KvWatchInclude=void 0;var NQ6=oW1();Object.defineProperty(bE,"KvWatchInclude",{enumerable:!0,get:function(){return NQ6.KvWatchInclude}});var b80=oW1();Object.defineProperty(bE,"Base64KeyCodec",{enumerable:!0,get:function(){return b80.Base64KeyCodec}});Object.defineProperty(bE,"Bucket",{enumerable:!0,get:function(){return b80.Bucket}});Object.defineProperty(bE,"defaultBucketOpts",{enumerable:!0,get:function(){return b80.defaultBucketOpts}});Object.defineProperty(bE,"Kvm",{enumerable:!0,get:function(){return b80.Kvm}});Object.defineProperty(bE,"NoopKvCodecs",{enumerable:!0,get:function(){return b80.NoopKvCodecs}})});function yE(){let $=new TextEncoder,Z=new TextDecoder;return{encode:(Q)=>$.encode(JSON.stringify(Q)),decode:(Q)=>JSON.parse(Z.decode(Q))}}class aW1{options;kv=null;codec=yE();constructor($){this.options=$}async init(){let $=this.options.getJetStream();if(!$)return;this.kv=await new yb$.Kvm($).create(LQ6,{storage:bb$.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 DQ6($,Z,Q){if(Q<=0)return!0;if($===void 0)return!0;return Z-$>=Q}function gb$($){let Z=["tools","resources","prompts"];for(let Q of Z){let X=`${Q}:${$}`;AD0.delete(X),g80.delete(X)}}function TD0($){return $ instanceof _1&&$.code===g1.MethodNotFound}function OQ6($){return $ instanceof _1&&$.code===-32000&&/connection closed/i.test($.message)}async function hE($,Z,Q,X,Y,J=0){if(!X)try{return await Q()}catch(H){if(TD0(H))return[];return y80.add(1,{type:$,outcome:"error",stage:"no_cache"}),null}let G=`${$}:${Z}`,W=await X.get($,Z);if(W===null)try{let H=await Q();return X.set($,Z,H).catch(()=>{}),AD0.set(G,Date.now()),y80.add(1,{type:$,outcome:"miss",stage:"miss"}),H}catch(H){if(TD0(H))return X.set($,Z,[]).catch(()=>{}),[];return y80.add(1,{type:$,outcome:"error",stage:"miss"}),null}if(y80.add(1,{type:$,outcome:"hit",stage:"hit"}),DQ6(AD0.get(G),Date.now(),J)&&!g80.has(G)){g80.add(G),AD0.set(G,Date.now());let H=Q().then((F)=>X.set($,Z,F)).catch((F)=>{if(TD0(F)||OQ6(F)){if(TD0(F))X.set($,Z,[]).catch(()=>{});return}y80.add(1,{type:$,outcome:"error",stage:"revalidation"})}).finally(()=>g80.delete(G));Y?.(H)}return W}function rW1($){hb$=$}function VZ(){return hb$}var bb$,yb$,y80,LQ6="DECOCMS_MCP_LISTS",g80,AD0,gE=30000,hb$=null;var JG=L(()=>{zZ();f6();bb$=_(TH(),1),yb$=_(KR(),1),y80=Y$.createCounter("mcp_list_cache.fetches",{description:"MCP list cache fetch outcomes (hit, miss, error)",unit:"{fetches}"});g80=new Set;Y$.createObservableGauge("mcp_list_cache.pending_revalidations",{description:"In-flight background MCP list revalidations on this pod",unit:"{revalidations}"}).addCallback(($)=>$.observe(g80.size));AD0=new Map});function RD0($){return(Z)=>{if(Z instanceof _1&&Z.code===g1.MethodNotFound)return $;throw Z}}var ub$=L(()=>{zZ()});function qD0($,Z,Q){let X=uE($,Z,Q,VZ()??void 0),Y=NA(X,{name:"studio-mcp-server",version:"1.0.0"},{capabilities:jQ6,toolCallTimeoutMs:uc});Y.server.setRequestHandler(Zw,async()=>{return await X.listResources().catch(RD0({resources:[]}))}),Y.server.setRequestHandler(Qw,async()=>{return await X.listResourceTemplates().catch(RD0({resourceTemplates:[]}))}),Y.server.setRequestHandler(Xw,async()=>{return await X.listPrompts().catch(RD0({prompts:[]}))});let J=Y.close.bind(Y);return Y.close=async()=>{await J(),await X.close().catch(()=>{})},Y}var jQ6;var lb$=L(()=>{lJ();zZ();h80();JG();ub$();jQ6={tools:{},resources:{},prompts:{}}});var yi=L(()=>{x80();Pb$();lb$()});async function gi($,Z,Q){await(await k3(Z,$,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:Q.state,scopes:Q.scopes,firstRun:Q.firstRun,...Q.vault?{vault:Q.vault}:{}}})}var MD0=L(()=>{yi()});import{z as sW1}from"zod";function zQ6($){let{owner:Z,name:Q}=y5({path:$.path});return{owner:Z,name:Q,url:$.webUrl??`https://${$.host}/${$.path}`,repositoryId:$.repositoryId}}function PQ6($,Z){if(!Z)return $;return $.filter((Q)=>Q.connection_id!==Z)}function TQ6($,Z){let{repository:Q,github_repo:X,...Y}=$,J=Z?LD0(Z):null;return{...Y,...Z?{repository:BD0(Z)}:{},...J?{github_repo:J}:{}}}async function AQ6($,Z,Q){let X=K4.REPORTS(Z),Y=await $.storage.connections.findById(X,Z);if(!Y)throw Error("Reports is not set up for this organization yet");let J=TQ6(Y.configuration_state??{},Q);await $.storage.connections.update(X,{configuration_state:J});try{await gi($,{...Y,configuration_state:J},{state:J,scopes:Y.configuration_scopes??[],firstRun:!1})}catch(G){console.error("[reports] ON_MCP_CONFIGURATION after repository change failed",G)}}async function RQ6($,Z,Q,X){let Y=gc(Z),J=await $.storage.virtualMcps.findById(Y,Z);if(!J)return;let G=J.metadata??{},W=G.repository,{repository:K,...H}=G;await $.storage.virtualMcps.update(Y,Q,{metadata:{...H,...X?{repository:zQ6(X)}:{}},connections:PQ6(J.connections??[],W?.connectionId??null)})}var wQ6,EQ6,eW1;var cb$=L(()=>{r8();a4();DD0();_0();MD0();wQ6=sW1.object({repositoryId:sW1.string().min(1).nullable().describe("Studio repository id to diagnose, or null to unlink the current one.")}),EQ6=sW1.object({repository:bW1.nullable()});eW1=m({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:wQ6,outputSchema:EQ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to set the diagnostic's repository");let Y=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=bW1.safeParse(G);if(!W.success)throw Error(`Repository ${$.repositoryId} has invalid configuration (missing or empty host/path)`);Y=W.data}return await AQ6(Z,Q.id,Y),await RQ6(Z,Q.id,X,Y),{repository:Y}}})});function lE($,Z){let Q=`/${encodeURIComponent($)}/settings`;return Z?`${Q}/${Z}`:Q}function ID0($,Z){let Q=`/${encodeURIComponent($)}/agents`,X=Z.panel?`${Q}/${Z.panel}`:Q,Y=new URLSearchParams({virtualmcpid:Z.projectId,...Z.search??{}});return`${X}?${Y.toString()}`}var cE=L(()=>{_H0()});function mb$($,Z){if(typeof $!=="string")return null;let Q=fW1($);return Q&&Q!==fW1(Z)?$:null}function hi($){Gb$({siteUrl:$.siteUrl,orgId:$.orgId}).then((Z)=>console.log("[reports] released site",{...$,...Z}),(Z)=>console.warn("[reports] could not release site",{...$,error:Z instanceof Error?Z.message:String(Z)}))}var VD0=L(()=>{vi();UD()});import{z as jN}from"zod";async function VQ6($,Z,Q,X){let Y=await $.storage.connections.findById(Z,Q);if(Y)return Y;throw X}async function kQ6($,Z,Q,X){let Y=await $.storage.virtualMcps.findById(Z,Q);if(Y)return Y;throw X}var $K1,qQ6=3600000,MQ6,IQ6,ZK1;var db$=L(()=>{r8();vi();_0();TU();cE();UD();VD0();$K1=xH0,MQ6=jN.object({siteUrl:jN.string().min(1).describe("Website URL to configure.")}),IQ6=jN.object({connection:CX,virtualMcp:kX,reportApp:jN.object({connectionId:jN.string(),virtualMcpId:jN.string(),toolName:jN.literal($K1)}),created:jN.object({connection:jN.boolean(),virtualMcp:jN.boolean()})});ZK1=m({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:MQ6,outputSchema:IQ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check("COLLECTION_CONNECTIONS_CREATE");let X=t0(Z);if(!X)throw Error("User ID required to set up Reports");let Y=FD($.siteUrl);if(!Y.ok)throw Error(Y.error);let J=K4.REPORTS(Q.id),G=gc(Q.id),W={email:Z.auth.user?.email,reportUrl:`${Z.baseUrl}${ID0(Q.slug??Q.id,{projectId:G,panel:"app",search:{connection:J,tool:$K1}})}`},K=await Z.storage.connections.findById(J,Q.id),H={connection:!1,virtualMcp:!1},F=await Zb$({siteUrl:Y.value,orgId:Q.id,orgName:Q.name,...W}),U=ef$();if(K){console.log("[reports] syncing connection to claimed site",{orgId:Q.id,siteUrl:Y.value,connectionId:J});let O=mb$(K.metadata?.siteUrl,Y.value);if(K=await Z.storage.connections.update(K.id,{connection_url:U,connection_token:F.authorizationToken,metadata:{...K.metadata??{},siteUrl:Y.value}}),O)hi({siteUrl:O,orgId:Q.id,cause:"site_changed"})}else{console.log("[reports] creating connection",{orgId:Q.id,siteUrl:Y.value,connectionId:J});try{let O=JU$(Q.id,F.authorizationToken,U);K=await Z.storage.connections.create({...O,metadata:{...O.metadata??{},siteUrl:Y.value},organization_id:Q.id,created_by:X}),H.connection=!0}catch(O){K=await VQ6(Z,J,Q.id,O)}}let N=await Z.storage.virtualMcps.findById(G,Q.id);if(!N){console.log("[reports] creating virtual MCP",{orgId:Q.id,siteUrl:Y.value,connectionId:K.id,virtualMcpId:G});try{N=await Z.storage.virtualMcps.create(Q.id,X,GU$(Q.id,K.id),{id:G}),H.virtualMcp=!0}catch(O){N=await kQ6(Z,G,Q.id,O)}}if(!N.pinned)N=await Z.storage.virtualMcps.update(N.id,X,{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)<qQ6){let j=(await Z.storage.organizationSettings.get(Q.id))?.flags,w={};if(j?.reports_only==null)w.reports_only=!0;if(Object.keys(w).length>0)await Z.storage.organizationSettings.upsert(Q.id,{flags:w})}return{connection:K,virtualMcp:N,reportApp:{connectionId:K.id,virtualMcpId:N.id,toolName:$K1},created:H}}})});var ib$=L(()=>{Wb$();Kb$();Hb$();cb$();db$()});function u80($,Z,Q){if(Z.some((X)=>X!=="*"&&X.startsWith("SELF::"))&&$.SELF===void 0)$.SELF={value:`${Q}_self`}}function l80($,Z){let Q=new Map;for(let X of Z){if(X==="*")continue;let[Y,J]=TN0(X);if(!SQ6.has(J))continue;let G=P10(Y,$);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 c80($,Z,Q,X){for(let G of Z){if(G==="*")continue;let[W]=TN0(G),K=P10(W,$);if(K===void 0||K===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let Y=d2$($,Z),J=`${Q}_self`;for(let G of Y){if(G===J)continue;let W=await X.storage.connections.findById(G);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${G}`);try{await X.access.check(G)}catch(K){throw Error(`Access denied to referenced connection: ${G}. ${K.message}`)}}}var SQ6;var QK1=L(()=>{qX1();mH0();SQ6=new Set([lH0,cH0])});import{z as pb$}from"zod";var _Q6,vQ6,XK1;var nb$=L(()=>{F6();_0();X$();JG();MD0();QK1();zB0();TU();_Q6=pb$.object({data:VH0.describe("Data for the new connection (id is auto-generated if not provided)")}),vQ6=pb$.object({item:CX.describe("The created connection entity")}),XK1=m({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:_Q6,outputSchema:vQ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to create connection");let Y={...$.data,organization_id:Q.id,created_by:X};if(Y.id){if((await Z.storage.connections.findById(Y.id))?.organization_id===Q.id)throw Error("Connection already exists in organization");if(await Z.storage.connections.findBySanitizedId(Y.id))throw Error("Connection id conflicts with an existing connection's isolated database schema")}if(Y.connection_type==="VIRTUAL"){let U=bc(Y.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");Y.connection_url=yc(U)}if(Y.connection_type==="STDIO"&&!P0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let J=await ld({id:`pending-${Date.now()}`,title:Y.title,connection_type:Y.connection_type,connection_url:Y.connection_url,connection_token:Y.connection_token,connection_headers:Y.connection_headers}).catch(()=>null),G=J?.tools?.length?J.tools:null,W=J?.scopes?.length?J.scopes:Y.configuration_scopes??null,K=Y.configuration_state??null;if(K&&W?.length)u80(K,W,Q.id),await c80(K,W,Q.id,Z);let H=await Z.storage.connections.createNew({...Y,tools:null,configuration_state:K,configuration_scopes:W}),F=K&&W?.length?l80(K,W):[];if(F.length>0){let U;try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:H.id,createdBy:X,grants:F});let{plaintextToken:N,record:B}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:Q.id,subjectConnectionId:H.id});U=B.id,await gi(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)VZ()?.set("tools",H.id,G).catch(()=>{});return h1.capture({distinctId:X,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 HK}from"zod/v4";import{z as tb$}from"zod/v4";import{z as kD0}from"zod/v4";import{z as wN}from"zod/v4";import{z as yQ6}from"zod/v4";import{z as HR}from"zod/v4";import{z as EN}from"zod/v4";import{z as jQ}from"zod/v4";import{z as ob$}from"zod/v4";import{z as _D0}from"zod/v4";import{z as GX6}from"zod/v4";import{z as ab$}from"zod/v4";import{z as CD0}from"zod/v4";import{z as DX6}from"zod/v4";function m80($,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,X)=>m80(Q,Z[X]))}if(typeof $==="object"&&typeof Z==="object"){let Q=Object.keys($),X=Object.keys(Z);if(Q.length!==X.length)return!1;return Q.every((Y)=>X.includes(Y)&&m80($[Y],Z[Y]))}return!1}function XX6(){return($)=>{if(!Array.isArray($))return!0;let Z=[];return $.every((Q)=>{if(Z.some((Y)=>m80(Q,Y)))return!1;return Z.push(Q),!0})}}function SD0($,Z){return $.safeParse(Z).success}function QX($){if(typeof $==="boolean")return $?HK.any():HK.never();let Z={};for(let Y of EX6)Y.apply(Z,$);let Q=[];if(Z.string!==!1)Q.push(Z.string||HK.string());if(Z.number!==!1)Q.push(Z.number||HK.number());if(Z.boolean!==!1)Q.push(Z.boolean||HK.boolean());if(Z.null!==!1)Q.push(Z.null||HK.null());if(Z.array!==!1)Q.push(Z.array||HK.array(HK.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 Y=HK.custom((J)=>{return typeof J==="object"&&J!==null&&!Array.isArray(J)},"Must be an object, not an array");Q.push(Y)}if(Z.file!==!1&&Z.file!==void 0)Q.push(Z.file);let X;if(Q.length===0)X=HK.never();else if(Q.length===1)X=Q[0];else if(!Object.keys($).some((J)=>J!=="$schema"&&J!=="title"&&J!=="description"))X=HK.any();else X=HK.union(Q);for(let Y of zX6)X=Y.apply(X,$);return X}var xQ6=class{apply($,Z){if(!Z.type)return;let Q=Array.isArray(Z.type)?Z.type:[Z.type],X=new Set(Q);if(!X.has("string"))$.string=!1;if(!X.has("number")&&!X.has("integer"))$.number=!1;if(!X.has("boolean"))$.boolean=!1;if(!X.has("null"))$.null=!1;if(!X.has("array"))$.array=!1;if(!X.has("object"))$.object=!1;if(X.has("integer")&&$.number!==!1){let Y=$.number||tb$.number();if(Y instanceof tb$.ZodNumber)$.number=Y.int()}}},fQ6=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=kD0.literal(Q);else if(typeof Q==="number")$.number=kD0.literal(Q);else if(typeof Q==="boolean")$.boolean=kD0.literal(Q);else if(Q===null)$.null=kD0.null();else if(Array.isArray(Q))$.array=void 0;else if(typeof Q==="object")$.object=void 0}},bQ6=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((X)=>typeof X==="string"),number:Z.enum.filter((X)=>typeof X==="number"),boolean:Z.enum.filter((X)=>typeof X==="boolean"),null:Z.enum.filter((X)=>X===null),array:Z.enum.filter((X)=>Array.isArray(X)),object:Z.enum.filter((X)=>typeof X==="object"&&X!==null&&!Array.isArray(X))};$.string=this.createTypeSchema(Q.string,"string"),$.number=this.createTypeSchema(Q.number,"number"),$.boolean=this.createTypeSchema(Q.boolean,"boolean"),$.null=Q.null.length>0?wN.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 wN.literal($[0]);if(Z==="string")return wN.enum($);if(Z==="number"){let[Q,X,...Y]=$;return wN.union([wN.literal(Q),wN.literal(X),...Y.map((J)=>wN.literal(J))])}if(Z==="boolean")return wN.union([wN.literal(!0),wN.literal(!1)]);return!1}},gQ6=class{apply($,Z){let Q=Z;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let X=yQ6.file();if(Q.minLength!==void 0)X=X.min(Q.minLength);if(Q.maxLength!==void 0)X=X.max(Q.maxLength);if(Q.contentMediaType!==void 0)X=X.mime(Q.contentMediaType);$.file=X,$.string=!1}}},hQ6=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=HR.string()}}},uQ6=class{apply($,Z){let Q=Z;if(Q.minLength===void 0)return;if($.string!==!1){let X=$.string||HR.string();if(X instanceof HR.ZodString)$.string=X.refine((Y)=>{return Array.from(Y).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},lQ6=class{apply($,Z){let Q=Z;if(Q.maxLength===void 0)return;if($.string!==!1){let X=$.string||HR.string();if(X instanceof HR.ZodString)$.string=X.refine((Y)=>{return Array.from(Y).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},cQ6=class{apply($,Z){let Q=Z;if(!Q.pattern)return;if($.string!==!1){let X=$.string||HR.string();if(X instanceof HR.ZodString){let Y=new RegExp(Q.pattern);$.string=X.regex(Y)}}}},mQ6=class{apply($,Z){let Q=Z;if(Q.minimum===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)$.number=X.min(Q.minimum)}}},dQ6=class{apply($,Z){let Q=Z;if(Q.maximum===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)$.number=X.max(Q.maximum)}}},iQ6=class{apply($,Z){let Q=Z;if(Q.exclusiveMinimum===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)if(typeof Q.exclusiveMinimum==="number")$.number=X.gt(Q.exclusiveMinimum);else $.number=!1}}},pQ6=class{apply($,Z){let Q=Z;if(Q.exclusiveMaximum===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)if(typeof Q.exclusiveMaximum==="number")$.number=X.lt(Q.exclusiveMaximum);else $.number=!1}}},nQ6=class{apply($,Z){let Q=Z;if(Q.multipleOf===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)$.number=X.refine((Y)=>{if(Q.multipleOf===0)return!1;let J=Y/Q.multipleOf,G=Math.round(J),W=Math.min(Math.abs(Y)*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}`})}}},tQ6=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=jQ.array(jQ.any())}}},oQ6=class{apply($,Z){let Q=Z;if(Q.minItems===void 0)return;if($.array!==!1)$.array=($.array||jQ.array(jQ.any())).min(Q.minItems)}},aQ6=class{apply($,Z){let Q=Z;if(Q.maxItems===void 0)return;if($.array!==!1)$.array=($.array||jQ.array(jQ.any())).max(Q.maxItems)}},rQ6=class{apply($,Z){let Q=Z;if($.array===!1)return;if(Array.isArray(Q.items))$.array=$.array||jQ.array(jQ.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let X=QX(Q.items),Y=jQ.array(X);if($.array&&$.array instanceof jQ.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)Y=Y.min(W.minimum);else if(W.check==="max_length"&&W.maximum!==void 0)Y=Y.max(W.maximum)}})}$.array=Y}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)$.array=jQ.array(jQ.any()).max(0);else $.array=$.array||jQ.array(jQ.any());else if(typeof Q.items==="boolean"&&Q.items===!0)$.array=$.array||jQ.array(jQ.any());else if(Q.prefixItems)$.array=$.array||jQ.array(jQ.any())}},sQ6=class{apply($,Z){if(Z.type!=="array")return;let Q=Z;if(!Array.isArray(Q.items))return;if($.array===!1)return;let X=Q.items.map((J)=>QX(J)),Y;if(X.length===0)Y=ob$.tuple([]);else Y=ob$.tuple(X);if(Q.minItems!==void 0&&Q.minItems>X.length)Y=!1;if(Q.maxItems!==void 0&&Q.maxItems<X.length)Y=!1;$.tuple=Y,$.array=!1}},eQ6=class{apply($,Z){let Q=Z;if($.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)$.object=$.object||_D0.object({}).passthrough()}},$X6=class{apply($,Z){let Q=Z;if(Z.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if($.object===void 0)$.object=_D0.object({}).passthrough()}}},ZX6=class{apply($,Z){let Q=Z;if(Q.maxProperties===void 0)return;if($.object!==!1){let X=$.object||_D0.object({}).passthrough();$.object=X.refine((Y)=>Object.keys(Y).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},QX6=class{apply($,Z){let Q=Z;if(Q.minProperties===void 0)return;if($.object!==!1){let X=$.object||_D0.object({}).passthrough();$.object=X.refine((Y)=>Object.keys(Y).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},YX6=class{apply($,Z){if(!Z.not)return $;let Q=QX(Z.not);return $.refine((X)=>!SD0(Q,X),{message:"Value must not match the 'not' schema"})}},JX6=class{apply($,Z){if(Z.uniqueItems!==!0)return $;return $.refine(XX6(),{message:"Array items must be unique"})}},WX6=class{apply($,Z){if(!Z.allOf||Z.allOf.length===0)return $;return Z.allOf.map((X)=>QX(X)).reduce((X,Y)=>GX6.intersection(X,Y),$)}},KX6=class{apply($,Z){if(!Z.anyOf||Z.anyOf.length===0)return $;let Q=Z.anyOf.length===1?QX(Z.anyOf[0]):ab$.union([QX(Z.anyOf[0]),QX(Z.anyOf[1]),...Z.anyOf.slice(2).map((X)=>QX(X))]);return ab$.intersection($,Q)}},HX6=class{apply($,Z){if(!Z.oneOf||Z.oneOf.length===0)return $;let Q=Z.oneOf.map((X)=>QX(X));return $.refine((X)=>{let Y=0;for(let J of Q)if(J.safeParse(X).success){if(Y++,Y>1)return!1}return Y===1},{message:"Value must match exactly one of the oneOf schemas"})}},FX6=class{apply($,Z){let Q=Z;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let Y=Q.prefixItems.map((J)=>QX(J));return $.refine((J)=>{if(!Array.isArray(J))return!0;for(let G=0;G<Math.min(J.length,Y.length);G++)if(!SD0(Y[G],J[G]))return!1;if(J.length>Y.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=QX(Q.items);for(let W=Y.length;W<J.length;W++)if(!SD0(G,J[W]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return $}},UX6=class{apply($,Z){let Q=Z;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return $;if($ instanceof CD0.ZodObject||$ instanceof CD0.ZodRecord){let X={};if(Q.properties){for(let[Y,J]of Object.entries(Q.properties))if(J!==void 0)X[Y]=QX(J)}if(Q.required&&Array.isArray(Q.required)){let Y=new Set(Q.required);for(let J of Object.keys(X))if(!Y.has(J))X[J]=X[J].optional()}else for(let Y of Object.keys(X))X[Y]=X[Y].optional();if(Q.additionalProperties===!1)return CD0.object(X);else return CD0.object(X).passthrough()}return $.refine((X)=>{if(typeof X!=="object"||X===null||Array.isArray(X))return!0;if(Q.properties){for(let[Y,J]of Object.entries(Q.properties))if(J!==void 0){if(Object.getOwnPropertyDescriptor(X,Y)!==void 0){if(!QX(J).safeParse(X[Y]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let Y of Q.required)if(Object.getOwnPropertyDescriptor(X,Y)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let Y=new Set(Object.keys(Q.properties));for(let J in X)if(!Y.has(J))return!1}return!0},{message:"Object constraints validation failed"})}},NX6=class{apply($,Z){if(!Z.enum||Z.enum.length===0)return $;let Q=Z.enum.filter((X)=>Array.isArray(X)||typeof X==="object"&&X!==null);if(Q.length===0)return $;return $.refine((X)=>{if(typeof X!=="object"||X===null)return!0;return Q.some((Y)=>m80(X,Y))},{message:"Value must match one of the enum values"})}},BX6=class{apply($,Z){if(Z.const===void 0)return $;let Q=Z.const;if(typeof Q!=="object"||Q===null)return $;return $.refine((X)=>m80(X,Q),{message:"Value must equal the const value"})}},LX6=class{apply($,Z){if(Z.description)$=$.describe(Z.description);return $}},OX6=class{apply($,Z){var Q;let X=Z;if(!((Q=X.required)==null?void 0:Q.includes("__proto__"))||Z.type!==void 0)return $;return DX6.any().refine((Y)=>this.validateRequired(Y,X.required),{message:"Missing required properties"})}validateRequired($,Z){if(typeof $!=="object"||$===null||Array.isArray($))return!0;return Z.every((Q)=>Object.prototype.hasOwnProperty.call($,Q))}},jX6=class{apply($,Z){var Q;let X=Z;if(X.contains===void 0)return $;let Y=QX(X.contains),J=(Q=X.minContains)!=null?Q:1,G=X.maxContains;return $.refine((W)=>{if(!Array.isArray(W))return!0;let K=0;for(let H of W)if(SD0(Y,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"})}},wX6=class{apply($,Z){let{default:Q}=Z;if(Q===void 0)return $;if(!$.safeParse(Q).success)return $;return $.default(Q)}},EX6,zX6;var rb$=L(()=>{EX6=[new fQ6,new bQ6,new xQ6,new gQ6,new hQ6,new tQ6,new $X6,new uQ6,new lQ6,new cQ6,new mQ6,new dQ6,new iQ6,new pQ6,new nQ6,new sQ6,new oQ6,new aQ6,new rQ6,new ZX6,new QX6,new eQ6],zX6=[new OX6,new NX6,new BX6,new WX6,new KX6,new HX6,new FX6,new UX6,new jX6,new YX6,new JX6,new wX6,new LX6]});class YK1{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,PX6),this._socket.onerror=(Q)=>{let X="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);Z(X),this.onerror?.(X)},this._socket.onopen=()=>{$()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let X;try{X=J3.parse(JSON.parse(Q.data))}catch(Y){this.onerror?.(Y);return}this.onmessage?.(X)}})}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 PX6="mcp";var sb$=L(()=>{zZ()});function TX6($){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 JK1;var eb$=L(()=>{qd();JK1=class JK1 extends yU{constructor($,Z){super($,Z)}send($,Z){let Q=TX6($);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send($,Z)}}});var $y$,Zy$=async($,Z,Q)=>{let X=AX6($.connection,Z,Q);if(!X)throw Error("Unknown MCP connection type");let Y=new $y$({name:$?.name??"MCP Client",version:"1.0.0"});return await Y.connect(X),{client:Y}},AX6=($,Z,Q)=>{if($.type==="Websocket")return new YK1(new URL($.url));if($.type!=="SSE"&&$.type!=="HTTP")return null;let Y={...$.token?{authorization:`Bearer ${$.token}`}:{},...Q??{},..."headers"in $?$.headers||{}:{}};if($.type==="SSE"){let J={requestInit:{headers:Y,signal:Z}};if($.token)J.eventSourceInit={fetch:(G,W)=>{return fetch(G,{...W,headers:{...Y,Accept:"text/event-stream"},signal:Z})}};return new DA(new URL($.url),J)}return new JK1(new URL($.url),{requestInit:{headers:Y,signal:Z,credentials:"include"}})};var Qy$=L(()=>{bU();PN0();sb$();zZ();lJ();eb$();$y$=class $y$ extends K7{constructor($,Z){super($,{jsonSchemaValidator:iZ,...Z})}async listTools($,Z){return await this.request({method:"tools/list",params:$},Ke,Z)}}});function qX6($,Z){if(FR.set($,Z),FR.size>RX6){let Q=FR.keys().next().value;if(Q!==void 0)FR.delete(Q)}}function Jy$($){let Z=(Q)=>{if("connection"in $)return Zy$({connection:$.connection},void 0,Q);return $.client};return new Proxy({},{get(Q,X){if(X==="toJSON")return null;if(typeof X!=="string")throw Error("Name must be a string");if(X==="listTools")return W;async function Y(K,H=X){let F=$?.debugId?.(),U=F?{"x-trace-debug-id":F}:void 0,{client:N}=await Z(U),{structuredContent:B,isError:D,content:O}=await N.callTool({name:String(H),arguments:K});if(D){let w=O?.[0]?.text,E=typeof w==="string"?Xy$(w):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??O)}`)}if(B!==void 0)return B;let j=O?.[0]?.text;return typeof j==="string"?Xy$(j):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(!FR.has(H))qX6(H,J());return await FR.get(H)}catch(F){console.error("Failed to list tools",F),FR.delete(H);return}}async function W(){return(await G()??[]).map((H)=>Yy$(H,Y))}return Y.asTool=async()=>{let H=(await G()??[]).find((F)=>F.name===X);if(!H)throw Error(`Tool ${X} not found`);return Yy$(H,Y)},Y}})}var Xy$=($)=>{try{return JSON.parse($)}catch{return $}},RX6=500,FR,Yy$=($,Z)=>{return{...$,id:$.name,inputSchema:$.inputSchema?QX($.inputSchema):void 0,outputSchema:$.outputSchema?QX($.outputSchema):void 0,execute:(Q)=>{return Z(Q.context,$.name)}}};var Gy$=L(()=>{rb$();Qy$();FR=new Map});function d80($){return Jy$($)}var Mx9;var Wy$=L(()=>{Gy$();Mx9=new Proxy({},{get($,Z){if(Z==="toJSON")return null;if(Z==="forConnection")return(Q)=>d80({connection:Q});if(Z==="forClient")return(Q)=>d80({client:Q});return globalThis[Z]}})});function vD0($){return{isImplementedBy:(Z)=>{for(let Q of $){let X=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,Y=Z.find((J)=>X.test(J.name));if(!Y&&Q.opt)continue;if(!Y)return!1}return!0}}}var BD=($)=>{return{...vD0($),forClient:(Z)=>{return d80({client:Z})},forConnection:(Z)=>{return d80({connection:Z})}}};var ui=L(()=>{Wy$()});import{z as ZZ}from"zod";var Ky$,Hy$,Fy$,Uy$,Ny$,MX6;var By$=L(()=>{ui();Ky$=ZZ.object({specversion:ZZ.literal("1.0").describe("CloudEvents specification version"),id:ZZ.string().describe("Unique identifier for this event (UUID recommended)"),source:ZZ.string().describe("Connection ID of the event publisher"),type:ZZ.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:ZZ.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:ZZ.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:ZZ.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:ZZ.string().url().optional().describe("URI to the schema for the data attribute"),data:ZZ.unknown().optional().describe("Event payload (any JSON value)")}),Hy$=ZZ.object({events:ZZ.array(Ky$).min(1).describe("Batch of CloudEvents to process")}),Fy$=ZZ.object({success:ZZ.boolean().optional().describe("Whether this event was processed successfully"),error:ZZ.string().optional().describe("Error message for this event"),retryAfter:ZZ.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),Uy$=ZZ.object({success:ZZ.boolean().optional().describe("Batch success - applies to events not in results"),error:ZZ.string().optional().describe("Batch error message - applies to events not in results"),processedCount:ZZ.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:ZZ.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:ZZ.record(ZZ.string(),Fy$).optional().describe("Per-event results keyed by event ID")}),Ny$=[{name:"ON_EVENTS",inputSchema:Hy$,outputSchema:Uy$}],MX6=BD(Ny$)});import{z as QZ}from"zod";var Ly$,Dy$,Oy$,jy$,wy$,Ey$,xD0,GK1;var WK1=L(()=>{ui();Ly$=QZ.object({type:QZ.literal("string"),enum:QZ.array(QZ.string()).optional(),description:QZ.string().optional()}),Dy$=QZ.object({type:QZ.string(),description:QZ.string(),paramsSchema:QZ.record(QZ.string(),Ly$)}),Oy$=QZ.object({}),jy$=QZ.object({triggers:QZ.array(Dy$)}),wy$=QZ.object({type:QZ.string(),params:QZ.record(QZ.string(),QZ.string()),enabled:QZ.boolean(),callbackUrl:QZ.url().optional(),callbackToken:QZ.string().min(1).optional()}),Ey$=QZ.object({success:QZ.boolean()}),xD0=[{name:"TRIGGER_LIST",inputSchema:Oy$,outputSchema:jy$},{name:"TRIGGER_CONFIGURE",inputSchema:wy$,outputSchema:Ey$}],GK1=BD(xD0)});import{z as N8}from"zod";var IX6,VX6,kX6,CX6,SX6,_X6,vX6,xX6,fX6,bX6,yX6,gX6,UR;var i80=L(()=>{IX6=N8.object({prefix:N8.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:N8.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:N8.string().optional().describe("Token for pagination from previous response"),delimiter:N8.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),VX6=N8.object({objects:N8.array(N8.object({key:N8.string().describe("Object key/path"),size:N8.number().describe("Object size in bytes"),lastModified:N8.string().describe("Last modified timestamp"),etag:N8.string().describe("Entity tag for the object")})),nextContinuationToken:N8.string().optional().describe("Token for fetching next page of results"),isTruncated:N8.boolean().describe("Whether there are more results available"),commonPrefixes:N8.array(N8.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),kX6=N8.object({key:N8.string().describe("Object key/path to get metadata for")}),CX6=N8.object({contentType:N8.string().optional().describe("MIME type of the object"),contentLength:N8.number().describe("Size of the object in bytes"),lastModified:N8.string().describe("Last modified timestamp"),etag:N8.string().describe("Entity tag for the object"),metadata:N8.record(N8.string(),N8.string()).optional().describe("Custom metadata key-value pairs")}),SX6=N8.object({key:N8.string().describe("Object key/path to generate URL for"),expiresIn:N8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),_X6=N8.object({url:N8.string().describe("Presigned URL for downloading the object"),expiresIn:N8.number().describe("Expiration time in seconds that was used")}),vX6=N8.object({key:N8.string().describe("Object key/path for the upload"),expiresIn:N8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:N8.string().optional().describe("MIME type for the object being uploaded")}),xX6=N8.object({url:N8.string().describe("Presigned URL for uploading the object"),expiresIn:N8.number().describe("Expiration time in seconds that was used")}),fX6=N8.object({key:N8.string().describe("Object key/path to delete")}),bX6=N8.object({success:N8.boolean().describe("Whether the deletion was successful"),key:N8.string().describe("The key that was deleted")}),yX6=N8.object({keys:N8.array(N8.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),gX6=N8.object({deleted:N8.array(N8.string()).describe("Array of successfully deleted keys"),errors:N8.array(N8.object({key:N8.string(),message:N8.string()})).describe("Array of errors for failed deletions")}),UR=[{name:"LIST_OBJECTS",inputSchema:IX6,outputSchema:VX6},{name:"GET_OBJECT_METADATA",inputSchema:kX6,outputSchema:CX6},{name:"GET_PRESIGNED_URL",inputSchema:SX6,outputSchema:_X6},{name:"PUT_PRESIGNED_URL",inputSchema:vX6,outputSchema:xX6},{name:"DELETE_OBJECT",inputSchema:fX6,outputSchema:bX6},{name:"DELETE_OBJECTS",inputSchema:yX6,outputSchema:gX6}]});import{z as T5}from"zod";var zy$,Py$,Ty$,p80,fD0,bD0,yD0,gD0,hX6;var KK1=L(()=>{ui();zy$=T5.object({primary:T5.string().optional().describe("Primary brand color (hex)"),secondary:T5.string().optional().describe("Secondary brand color (hex)"),accent:T5.string().optional().describe("Accent / highlight color (hex)"),background:T5.string().optional().describe("Background color (hex)"),foreground:T5.string().optional().describe("Foreground / text color (hex)")}),Py$=T5.object({heading:T5.string().optional().describe("Font family for headings"),body:T5.string().optional().describe("Font family for body text"),code:T5.string().optional().describe("Font family for code / monospace")}),Ty$=T5.object({logo:T5.string().optional().describe("Logo URL"),favicon:T5.string().optional().describe("Favicon URL"),ogImage:T5.string().optional().describe("Open Graph image URL")}),p80=T5.object({id:T5.string(),name:T5.string().describe("Brand / company name"),domain:T5.string().optional().describe("Company domain (e.g. example.com)"),colors:zy$.optional().describe("Semantic color palette"),fonts:Py$.optional().describe("Font families by role"),assets:Ty$.optional().describe("Visual identity assets"),overview:T5.string().optional().describe("Company overview / description"),tagline:T5.string().optional().describe("Brand tagline"),tone:T5.string().optional().describe("Tone of voice description"),metadata:T5.record(T5.string(),T5.unknown()).optional().describe("Extra design tokens and metadata")}),fD0=T5.object({id:T5.string().optional().describe("Brand ID. Omit to get the default brand.")}),bD0=T5.object({}),yD0=T5.object({items:T5.array(p80)}),gD0=[{name:"BRAND_GET",inputSchema:fD0,outputSchema:p80},{name:"BRAND_LIST",inputSchema:bD0,outputSchema:yD0,opt:!0}],hX6=BD(gD0)});var Ay$=L(()=>{ui();By$();WK1();i80();KK1()});import{z as W4}from"zod";function li($){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return new RegExp(`^${Q}$`,"i")}function LD($){return W4.object({items:W4.array($).describe("Array of collection items"),totalCount:W4.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:W4.boolean().optional().describe("Whether there are more items available")})}function t80($){return W4.object({item:$.nullable().describe("The retrieved item, or null if not found")})}function cX6($){return W4.object({data:$.partial().describe("Data for the new entity (id may be auto-generated)")})}function mX6($){return W4.object({item:$.describe("The created entity with generated id")})}function dX6($){return W4.object({id:W4.string().describe("ID of the entity to update"),data:$.partial().describe("Partial entity data to update")})}function iX6($){return W4.object({item:$.describe("The updated entity")})}function a80($){return W4.object({item:$.describe("The deleted entity")})}function uD0($,Z,Q){let X=$.toUpperCase(),Y=Q?.readOnly??!1,J=[{name:`COLLECTION_${X}_LIST`,inputSchema:WF,outputSchema:LD(Z)},{name:`COLLECTION_${X}_GET`,inputSchema:n80,outputSchema:t80(Z)}];if(!Y)J.push({name:`COLLECTION_${X}_CREATE`,inputSchema:cX6(Z),outputSchema:mX6(Z),opt:!0},{name:`COLLECTION_${X}_UPDATE`,inputSchema:dX6(Z),outputSchema:iX6(Z),opt:!0},{name:`COLLECTION_${X}_DELETE`,inputSchema:o80,outputSchema:a80(Z),opt:!0});return J}var hD0,uX6,Ry$,lX6,WF,n80,o80;var GG=L(()=>{hD0=W4.object({id:W4.string().describe("Unique identifier for the entity"),title:W4.string().describe("Human-readable title for the entity"),description:W4.string().nullish().describe("Description of the entity"),created_at:W4.string().datetime(),updated_at:W4.string().datetime(),created_by:W4.string().optional(),updated_by:W4.string().optional()}),uX6=W4.object({field:W4.array(W4.string()),operator:W4.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:W4.unknown()}),Ry$=W4.lazy(()=>W4.union([uX6,W4.object({operator:W4.enum(["and","or","not"]),conditions:W4.array(Ry$)})]));lX6=W4.object({field:W4.array(W4.string()),direction:W4.enum(["asc","desc"]),nulls:W4.enum(["first","last"]).optional()}),WF=W4.object({where:Ry$.optional().describe("Filter expression"),orderBy:W4.array(lX6).optional().describe("Sort expressions"),limit:W4.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:W4.number().int().min(0).optional().describe("Number of items to skip")});n80=W4.object({id:W4.string().describe("ID of the entity to retrieve")});o80=W4.object({id:W4.string().describe("ID of the entity to delete")})});import{z as ci}from"zod";var pX6,nX6,qy$;var My$=L(()=>{GG();pX6=hD0.extend({avatar:ci.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:ci.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:ci.string().describe("Virtual MCP ID to use for this assistant"),model:ci.object({id:ci.string().describe("Model ID"),connectionId:ci.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),nX6=uD0("assistant",pX6),qy$=[...nX6]});import{z as j0}from"zod";var r80,DD,Vy$,tX6,oX6,ky$,aX6,rX6,sX6,eX6,$Y6,ZY6,Cy$,QY6,XY6,YY6,JY6,GY6,WY6,KY6,HY6,FY6,UY6,Xf9,NY6,Yf9,Iy$,BY6,LY6,lD0,Jf9;var Sy$=L(()=>{ui();GG();r80=j0.lazy(()=>j0.union([j0.null(),j0.string(),j0.number(),j0.boolean(),j0.record(j0.string(),r80),j0.array(r80)])),DD=j0.record(j0.string(),j0.record(j0.string(),r80)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Vy$=j0.object({type:j0.literal("text"),text:j0.string().describe("The text content"),providerOptions:DD}),tX6=j0.object({type:j0.literal("text"),text:j0.string().describe("The text content"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),oX6=j0.string().describe("File data as URL string"),ky$=j0.object({type:j0.literal("file"),filename:j0.string().optional().describe("Optional filename of the file"),data:oX6,mediaType:j0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:DD}),aX6=j0.object({type:j0.literal("file"),mediaType:j0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:j0.string().describe("Generated file data as base64 encoded string")}),rX6=j0.object({type:j0.literal("reasoning"),text:j0.string().describe("The reasoning text"),providerOptions:DD}),sX6=j0.object({type:j0.literal("reasoning"),text:j0.string().describe("The reasoning text"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),eX6=j0.object({type:j0.literal("tool-call"),toolCallId:j0.string().describe("ID of the tool call, used to match with tool result"),toolName:j0.string().describe("Name of the tool being called"),input:j0.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:j0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:DD}),$Y6=j0.object({type:j0.literal("tool-call"),toolCallId:j0.string().describe("ID of the tool call"),toolName:j0.string().describe("Name of the tool being called"),input:j0.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:j0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),ZY6=j0.union([j0.object({type:j0.literal("text"),value:j0.string()}),j0.object({type:j0.literal("json"),value:r80}),j0.object({type:j0.literal("error-text"),value:j0.string()}),j0.object({type:j0.literal("error-json"),value:r80}),j0.object({type:j0.literal("content"),value:j0.array(j0.union([j0.object({type:j0.literal("text"),text:j0.string().describe("Text content")}),j0.object({type:j0.literal("media"),data:j0.string().describe("Base-64 encoded media data"),mediaType:j0.string().describe("IANA media type")})]))}),j0.object({type:j0.literal("execution-denied"),reason:j0.string().optional()}),j0.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Cy$=j0.object({type:j0.literal("tool-result"),toolCallId:j0.string().describe("ID of the tool call that this result is associated with"),toolName:j0.string().describe("Name of the tool that generated this result"),output:ZY6.describe("Result of the tool call"),result:j0.unknown().describe("Unknown result of the tool call"),providerOptions:DD}),QY6=j0.object({type:j0.literal("tool-result"),toolCallId:j0.string().describe("ID of the tool call that this result is associated with"),toolName:j0.string().describe("Name of the tool that generated this result"),result:j0.any().describe("Result of the tool call (JSON-serializable)"),isError:j0.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:j0.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),XY6=j0.union([j0.object({type:j0.literal("source"),sourceType:j0.literal("url"),id:j0.string().describe("The ID of the source"),url:j0.string().describe("The URL of the source"),title:j0.string().optional().describe("The title of the source"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),j0.object({type:j0.literal("source"),sourceType:j0.literal("document"),id:j0.string().describe("The ID of the source"),mediaType:j0.string().describe("IANA media type of the document (e.g., application/pdf)"),title:j0.string().describe("The title of the document"),filename:j0.string().optional().describe("Optional filename of the document"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")})]),YY6=j0.object({role:j0.literal("system"),content:j0.string().describe("System message content"),providerOptions:DD}),JY6=j0.object({role:j0.literal("user"),content:j0.array(j0.union([Vy$,ky$])).describe("User message content parts (text or file)"),providerOptions:DD}),GY6=j0.object({role:j0.literal("assistant"),content:j0.array(j0.union([Vy$,ky$,rX6,eX6,Cy$])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:DD}),WY6=j0.object({role:j0.literal("tool"),content:j0.array(Cy$).describe("Tool message content (tool results)"),providerOptions:DD}),KY6=j0.union([YY6,JY6,GY6,WY6]),HY6=j0.array(KY6).describe("A list of messages forming the prompt"),FY6=j0.object({prompt:HY6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:j0.number().optional().describe("Maximum number of tokens to generate"),temperature:j0.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:j0.number().optional().describe("Nucleus sampling parameter"),topK:j0.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:j0.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:j0.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:j0.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:j0.array(j0.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:j0.union([j0.object({type:j0.literal("text")}),j0.object({type:j0.literal("json"),schema:j0.any().optional().describe("JSON schema that the generated output should conform to"),name:j0.string().optional().describe("Name of output that should be generated"),description:j0.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:j0.array(j0.any()).optional().describe("The tools that are available for the model"),toolChoice:j0.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:j0.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:j0.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:j0.any().optional().describe("Additional provider-specific options")}),UY6=j0.object({content:j0.array(j0.union([tX6,aX6,sX6,$Y6,QY6,XY6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:j0.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:j0.looseObject({inputTokens:j0.number().optional(),outputTokens:j0.number().optional(),totalTokens:j0.number().optional(),reasoningTokens:j0.number().optional()}).describe("Usage information for the language model call"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata"),request:j0.object({body:j0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:j0.object({id:j0.string().optional().describe("ID for the generated response"),timestamp:j0.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:j0.string().optional().describe("The ID of the response model that was used"),headers:j0.record(j0.string(),j0.string()).optional().describe("Response headers"),body:j0.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:j0.array(j0.any()).describe("Warnings for the call, e.g. unsupported settings")}),Xf9=j0.object({stream:j0.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:j0.object({body:j0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:j0.object({headers:j0.record(j0.string(),j0.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),NY6=j0.object({supportedUrls:j0.record(j0.string(),j0.array(j0.string())).describe("Supported URL patterns by media type for the provider")}),Yf9=j0.object({modelId:j0.string().describe("The ID of the model"),logo:j0.string().nullable(),description:j0.string().nullable(),capabilities:j0.array(j0.string()),limits:j0.object({contextWindow:j0.number(),maxOutputTokens:j0.number()}).nullable(),costs:j0.object({input:j0.number(),output:j0.number()}).nullable(),provider:j0.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Iy$=j0.object({modelId:j0.string().describe("The ID of the model"),callOptions:FY6}),BY6=hD0.extend({logo:j0.string().nullable(),description:j0.string().nullable(),capabilities:j0.array(j0.string()),limits:j0.object({contextWindow:j0.number(),maxOutputTokens:j0.number()}).nullable(),costs:j0.object({input:j0.number(),output:j0.number()}).nullable(),provider:j0.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),LY6=uD0("llm",BY6,{readOnly:!0}),lD0=[{name:"LLM_METADATA",inputSchema:j0.object({modelId:j0.string().describe("The ID of the model")}),outputSchema:NY6},{name:"LLM_DO_STREAM",inputSchema:Iy$},{name:"LLM_DO_GENERATE",inputSchema:Iy$,outputSchema:UY6},...LY6],Jf9=BD(lD0)});import{z as NR}from"zod";var DY6,_y$;var vy$=L(()=>{DY6=NR.object({scopes:NR.array(NR.string()).describe("List of scopes available"),stateSchema:NR.record(NR.string(),NR.unknown()).describe("JSON Schema (draft-07) defining the state structure")}),_y$=[{name:"MCP_CONFIGURATION",inputSchema:NR.object({}),outputSchema:DY6}]});import{z as XZ}from"zod";var OY6,jY6,xy$;var fy$=L(()=>{OY6=XZ.object({}).strict(),jY6=XZ.object({billing:XZ.object({mode:XZ.enum(["prepaid","postpaid"]),limitPeriod:XZ.enum(["daily","weekly","monthly"]).nullable()}),limit:XZ.object({total:XZ.number().nullable(),remaining:XZ.number().nullable(),reset:XZ.string().nullable()}),usage:XZ.object({total:XZ.number(),daily:XZ.number(),weekly:XZ.number(),monthly:XZ.number()}),alert:XZ.object({enabled:XZ.boolean(),threshold_usd:XZ.number(),email:XZ.string().nullable()}),connectionId:XZ.string()}),xy$=[{name:"GATEWAY_USAGE",inputSchema:OY6,outputSchema:jY6},{name:"GATEWAY_SET_LIMIT",inputSchema:XZ.object({}),outputSchema:XZ.object({}),opt:!0},{name:"GATEWAY_SET_ALERT",inputSchema:XZ.object({}),outputSchema:XZ.object({}),opt:!0}]});import{z as by$}from"zod";function FK(){return yQ()===null}function cD0($,Z){return $===K4.DEV_ASSETS(Z)}function mD0($,Z){let Q=aF$(Z,$),X=new Date().toISOString();return{id:Q.id??K4.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:X,updated_at:X,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:wY6,bindings:["OBJECT_STORAGE"],status:"active"}}var wY6;var mi=L(()=>{NL();i80();r8();wY6=UR.map(($)=>({name:$.name,description:`${$.name} operation for local file storage`,inputSchema:by$.toJSONSchema($.inputSchema),outputSchema:by$.toJSONSchema($.outputSchema)}))});function yy$($,Z){return $||Z===0}function gy$($,Z,Q,X,Y){let J=Z?Y+1:Y,G=$.slice(0,Q),W=X+Q<J;return{items:G,totalCount:J,hasMore:W}}function hy$($,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 EY6($,Z){if(Z.length===0)return;let[Q,...X]=Z,Y=Q==="slug"?Gw($):$[Q];for(let J of X){if(Y===null||typeof Y!=="object")return;Y=Y[J]}return Y}function zY6($,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"&&li(String(Q)).test($);case"contains":return String($).toLowerCase().includes(String(Q).toLowerCase());default:return!0}}function s80($,Z){if(!Z)return!0;if("conditions"in Z){let{operator:X,conditions:Y}=Z;if(Y.length===0)return!0;switch(X){case"and":return Y.every((J)=>s80($,J));case"or":return Y.some((J)=>s80($,J));case"not":return!Y.every((J)=>s80($,J));default:return!0}}let Q=EY6($,Z.field);return zY6(Q,Z.operator,Z.value)}var uy$=L(()=>{gH0();GG()});import{z as mE}from"zod";var PY6=8,TY6,AY6,RY6,qY6,BR;var HK1=L(()=>{Ay$();My$();GG();Sy$();vy$();i80();fy$();r8();_0();A9();JG();yi();mi();TU();gH0();uy$();TY6=[{name:/^(COLLECTION_REGISTRY_APP_LIST|REGISTRY_ITEM_LIST)$/,inputSchema:mE.object({})}],AY6={LLM:lD0,LLMS:lD0,ASSISTANTS:qy$,MCP:_y$,OBJECT_STORAGE:UR,AI_GATEWAY_BILLING:xy$,TRIGGER:xD0,REGISTRY:TY6,BRAND:gD0},RY6=WF.extend({binding:mE.union([mE.array(mE.object({}).passthrough()),mE.object({}).passthrough(),mE.string()]).optional(),include_virtual:mE.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false."),slug:mE.string().optional().describe("Filter by connection slug. Matches against app_name, or a slug derived from connection_url or title.")}),qY6=LD(CX),BR=m({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:RY6,outputSchema:qY6,handler:async($,Z)=>{await Z.access.check();let Q=W0(Z),X=$.binding?typeof $.binding==="string"?(()=>{let w=AY6[$.binding.toUpperCase()];if(!w)throw Error(`Unknown binding: ${$.binding}`);return w})():$.binding:void 0,Y=X?vD0(X):void 0,J=!!Y,G=$.limit??100,W=$.offset??0,K=g9(),H=K4.DEV_ASSETS(Q.id),F=mD0(Q.id,K),U=(!$.slug||Gw(F)===$.slug)&&s80(F,$.where),N=FK()&&!J&&U,{sqlOffset:B,sqlLimit:D}=hy$(W,G,N),{items:O,totalCount:j}=await Z.storage.connections.list(Q.id,{includeVirtual:$.include_virtual??!1,slug:$.slug,where:$.where,orderBy:$.orderBy,limit:J?void 0:D,offset:J?void 0:B});if(Y){let w=VZ(),E=K4.SELF(Q.id);await cd(O,PY6,async(z)=>{if(z.tools!==null)return;let A=z.id===E?async()=>{let{listManagementTools:T}=await Promise.resolve().then(() => (dE(),dD0));return T(Z)}:()=>v80(z,Z,lc),P=await hE("tools",z.id,A,w,(T)=>Z.pendingRevalidations.push(T),gE);if(P!==null)z.tools=P})}if(FK()&&yy$(J,W)&&U&&!O.some((w)=>w.id===H))O.unshift(F);if(J){let w=(await Promise.all(O.map(async(P)=>{if(!P.tools||P.tools.length===0)return null;return Y.isImplementedBy(P.tools.map((q)=>({name:q.name,inputSchema:q.inputSchema,outputSchema:q.outputSchema})))?P:null}))).filter((P)=>P!==null),E=w.length,z=w.slice(W,W+G),A=W+G<E;return{items:z,totalCount:E,hasMore:A}}return gy$(O,N,G,W,j)}})});var MY6,LR;var FK1=L(()=>{GG();r8();_0();A9();JG();yi();mi();TU();MY6=t80(CX),LR=m({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:n80,outputSchema:MY6,handler:async($,Z)=>{let Q=W0(Z);if(await Z.access.check(),FK()&&cD0($.id,Q.id))return{item:mD0(Q.id,g9())};let X=await Z.storage.connections.findById($.id);if(!X||X.organization_id!==Q.id)return{item:null};if(X.tools===null){let Y=K4.SELF(Q.id),J=X.id===Y?async()=>{let{listManagementTools:W}=await Promise.resolve().then(() => (dE(),dD0));return W(Z)}:()=>v80(X,Z,lc),G=await hE("tools",X.id,J,VZ(),(W)=>Z.pendingRevalidations.push(W),gE);if(G!==null)X.tools=G}return{item:X}}})});class V9{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 IY6(this.vault,Z)}async upsert($){let Z=new Date().toISOString(),Q=await this.vault.encrypt($.accessToken),X=$.refreshToken?await this.vault.encrypt($.refreshToken):null,Y=$.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:X,scope:$.scope,expiresAt:J,clientId:$.clientId,clientSecret:Y,tokenEndpoint:$.tokenEndpoint,createdAt:Z,updatedAt:Z}).onConflict((W)=>W.column("connectionId").doUpdateSet({accessToken:Q,refreshToken:X,scope:$.scope,expiresAt:J,clientId:$.clientId,clientSecret:Y,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 X=($.expiresAt instanceof Date?$.expiresAt:new Date($.expiresAt)).getTime();if(Number.isNaN(X))return!0;return X-Z<Date.now()}}async function IY6($,Z){try{let Q=await $.decrypt(Z.accessToken),X=Z.refreshToken?await $.decrypt(Z.refreshToken):null,Y=Z.clientSecret?await $.decrypt(Z.clientSecret):null;return{id:Z.id,connectionId:Z.connectionId,accessToken:Q,refreshToken:X,scope:Z.scope,expiresAt:Z.expiresAt,createdAt:Z.createdAt,updatedAt:Z.updatedAt,clientId:Z.clientId,clientSecret:Y,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 KF=L(()=>{SX()});function di(...$){if(SY6)console.log("[mcp-read-cache]",...$)}function _Y6($){return $.kind==="org"?"org":`u:${$.userId}`}function UK1($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(UK1).join(",")}]`;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${UK1($[Q])}`).join(",")}}`}class nD0{config;maxEntries;now;maxTotalBytes;store=new Map;revalidating=new Set;totalBytes=0;byConnection=new Map;constructor($=VY6,Z=kY6,Q=()=>Date.now(),X=CY6){this.config=$;this.maxEntries=Z;this.now=Q;this.maxTotalBytes=X}stats(){return{entries:this.store.size,bytes:this.totalBytes}}deleteKey($){let Z=this.store.get($);if(Z){this.store.delete($),this.totalBytes-=Z.bytes;let Q=this.byConnection.get(Z.connectionId);if(Q){if(Q.delete($),Q.size===0)this.byConnection.delete(Z.connectionId)}}}key($,Z,Q,X){return`${Z}:${_Y6(Q)}:${$}:${UK1(X)}`}storeSet($,Z,Q,X,Y){let J;try{J=JSON.stringify(Q).length}catch{di("SKIP non-serializable",$);return}if(J>Y){di("SKIP oversize",$,`${J}b > cap ${Y}b`);return}this.deleteKey($);while(this.store.size>0&&(this.store.size>=this.maxEntries||this.totalBytes+J>this.maxTotalBytes)){let W=this.store.keys().next().value;if(W===void 0)break;this.deleteKey(W)}this.store.set($,{value:Q,storedAt:X,bytes:J,connectionId:Z}),this.totalBytes+=J;let G=this.byConnection.get(Z);if(!G)G=new Set,this.byConnection.set(Z,G);G.add($)}async fetch($){let{type:Z,connectionId:Q,scope:X,params:Y,fetchLive:J,shouldCache:G,onRevalidation:W}=$,K=this.config[Z],H=this.key(Z,Q,X,Y),F=this.now(),U=this.store.get(H),N=U?F-U.storedAt:1/0;if(!U||N>K.maxStaleMs){iD0.add(1,{type:Z,outcome:"miss"}),di(U?"EXPIRED":"MISS",H);let B=await J();if(G?.(B)??!0)this.storeSet(H,Q,B,this.now(),K.maxValueBytes);else di("NOT-CACHED (shouldCache=false)",H);return B}if(this.store.delete(H),this.store.set(H,U),N>K.revalidateAfterMs&&!this.revalidating.has(H)){iD0.add(1,{type:Z,outcome:"stale"}),di("STALE \u2192 serve + revalidate",H,`age=${N}ms`),this.revalidating.add(H);let B=J().then((D)=>{if(G?.(D)??!0)this.storeSet(H,Q,D,this.now(),K.maxValueBytes)}).catch(()=>{iD0.add(1,{type:Z,outcome:"error"})}).finally(()=>this.revalidating.delete(H));W?.(B)}else iD0.add(1,{type:Z,outcome:"hit"}),di("HIT",H,`age=${N}ms`);return U.value}invalidate($){let Z=this.byConnection.get($);if(!Z)return;for(let Q of[...Z])this.deleteKey(Q)}}function BK1(){return P0().mcpCacheEnabled}function tD0(){return BK1()?NK1:null}var iD0,pD0=1024,ly$,VY6,kY6=2000,CY6,SY6,NK1;var e80=L(()=>{f6();X$();iD0=Y$.createCounter("mcp_read_cache.fetches",{description:"MCP read cache outcomes (hit, stale, miss, error)",unit:"{fetches}"}),ly$=pD0*pD0,VY6={"tools/call":{revalidateAfterMs:30000,maxStaleMs:300000,maxValueBytes:512*pD0},"resources/read":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:4*ly$},"prompts/get":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:512*pD0}},CY6=256*ly$,SY6=typeof process<"u"&&!!process.env?.MCP_CACHE_DEBUG;NK1=new nD0;Y$.createObservableGauge("mcp_read_cache.entries",{description:"Current entry count in the per-pod MCP read cache",unit:"{entries}"}).addCallback(($)=>$.observe(NK1.stats().entries));Y$.createObservableGauge("mcp_read_cache.bytes",{description:"Approximate total bytes held in the per-pod MCP read cache",unit:"By"}).addCallback(($)=>$.observe(NK1.stats().bytes))});function iy$(){if(cy$)return;cy$=!0;try{my$=Y$.createCounter("virtual_mcp.aggregate_cache.lookups",{description:"Virtual MCP aggregate tool-list cache lookups by outcome (hit, miss, expired)",unit:"{lookups}"}),dy$=Y$.createCounter("virtual_mcp.aggregate_cache.evictions",{description:"Virtual MCP aggregate tool-list cache entries dropped, by reason (capacity, invalidated, failed)",unit:"{entries}"}),Y$.createObservableGauge("virtual_mcp.aggregate_cache.entries",{description:"Live entries in this pod's Virtual MCP aggregate tool-list cache",unit:"{entries}"}).addCallback(($)=>$.observe(UK.size))}catch($){console.error("[aggregate-cache] failed to register metrics:",$)}}function LK1($){iy$(),my$?.add(1,{outcome:$})}function DK1($,Z=1){if(Z<=0)return;iy$(),dy$?.add(Z,{reason:$})}function py$($){return[$.virtualMcpId??"",$.userId??"",$.superUser?"su":"",[...$.connectionIds].sort().join(",")].join("|")}function ny$($){let Z=UK.get($);if(!Z)return LK1("miss"),null;if(Date.now()-Z.at>=vY6)return UK.delete($),LK1("expired"),null;return LK1("hit"),Z.value}function ty$($,Z,Q){let X=Q.catch((J)=>{if(UK.get($)?.value===X)UK.delete($),DK1("failed");throw J});UK.delete($),UK.set($,{at:Date.now(),deps:Z,value:X});let Y=0;while(UK.size>xY6){let J=UK.keys().next();if(J.done)break;UK.delete(J.value),Y++}return DK1("capacity",Y),X}function oy$($){let Z=0;for(let[Q,X]of UK)if(X.deps.includes($))UK.delete(Q),Z++;DK1("invalidated",Z)}var vY6=30000,xY6=500,UK,my$=null,dy$=null,cy$=!1;var OK1=L(()=>{f6();UK=new Map});function sy$($){tD0()?.invalidate($),gb$($),oy$($)}function ii($){sy$($);let Z=jK1?.();if(!Z)return;try{Z.publish(ay$,fY6.encode(JSON.stringify({connectionId:$,originId:ry$})))}catch(Q){console.warn("[McpCacheInvalidation] publish failed (non-critical):",Q)}}function ey$($){if(jK1=$,$40)return;let Z=$();if(!Z)return;$40=Z.subscribe(ay$),(async()=>{for await(let Q of $40)try{let X=JSON.parse(bY6.decode(Q.data));if(X.originId===ry$)continue;sy$(X.connectionId)}catch{}})().catch(console.error)}function $g$(){$40?.unsubscribe(),$40=null,jK1=void 0}var ay$="studio.mcp-cache.invalidate",ry$,fY6,bY6,jK1,$40=null;var Z40=L(()=>{e80();JG();OK1();ry$=crypto.randomUUID(),fY6=new TextEncoder,bY6=new TextDecoder});import{z as wK1}from"zod";function gY6($){let Z={...$};for(let Q of yY6)delete Z[Q];return Z}function hY6($,Z){return $.connection_url!==void 0?$.connection_url:Z}function cY6($,Z){return $.length===Z.length&&$.every((Q,X)=>Q===Z[X])}var yY6,uY6,lY6,EK1;var Zg$=L(()=>{MD0();KF();_0();X$();JG();Z40();QK1();zB0();TU();yY6=["id","organization_id","created_by","created_at"];uY6=wK1.object({id:wK1.string().describe("ID of the connection to update"),data:kH0.describe("Partial connection data to update")}),lY6=wK1.object({item:CX.describe("The updated connection entity")});EK1=m({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:uY6,outputSchema:lY6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to update connection");let{id:Y}=$,J=gY6($.data),G=J.configuration_state!==void 0||J.configuration_scopes!==void 0,W=await Z.storage.connections.findById(Y);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let K=J.connection_type??W.connection_type,H=hY6(J,W.connection_url);if(K==="VIRTUAL"){let u=bc(H);if(!u)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let g=await Z.storage.virtualMcps.findById(u);if(!g)throw Error(`Virtual MCP not found: ${u}`);if(g.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=yc(u)}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 u=F;u80(u,U,Q.id),await c80(u,U,Q.id,Z)}}if(K==="STDIO"&&!P0().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 V9(Z.db,Z.vault).get(Y);if(g?.accessToken)N=g.accessToken}catch{}let B=await ld({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),D=B?.tools?.length?B.tools:null,O=!1;if(J.configuration_scopes===void 0&&B?.scopes?.length)O=!cY6(U,B.scopes),U=B.scopes;if(u80(F,U,Q.id),O&&U.length>0)await c80(F,U,Q.id,Z);let j=G||O,w=j?l80(F,U):[],E=j?l80(W.configuration_state??{},W.configuration_scopes??[]):[],z=W.configuration_state,A=z==null||Object.keys(z).length===0,P,T,q=async()=>{try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:Y,createdBy:X,grants:E})}catch(u){console.error("Failed to restore credential grants after credential vault mutation failed",u)}},f={...J,connection_url:H,tools:null,configuration_state:F,configuration_scopes:U,updated_by:X},S={...W,...f};if(j)try{if(await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:Y,createdBy:X,grants:w}),w.length>0){if(!await Z.storage.connectionCredentialVault.findActiveWorkloadToken({organizationId:Q.id,subjectConnectionId:Y})){let{plaintextToken:g,record:l}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:Q.id,subjectConnectionId:Y});T=l.id,P={baseUrl:Z.baseUrl,org:Q.slug??Q.id,subjectConnectionId:Y,token:g}}}}catch(u){if(T)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:Y,tokenId:T});throw await q(),u}if(j&&F&&U)try{await gi(Z,S,{state:F,scopes:U,firstRun:A,...P?{vault:P}:{}})}catch(u){if(console.error("Failed to invoke ON_MCP_CONFIGURATION callback",u),T)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:Y,tokenId:T});if(w.length>0)throw await q(),u}let V;try{V=await Z.storage.connections.update(Y,f)}catch(u){if(j){if(T)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:Y,tokenId:T});await q()}throw u}if(D)VZ()?.set("tools",Y,D).catch(()=>{});return ii(Y),{item:V}}})});import{z as mY6}from"zod";var dY6,zK1;var Qg$=L(()=>{GG();r8();F6();VD0();_0();JG();Z40();NK();mi();TU();dY6=o80.extend({force:mY6.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),zK1=m({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:dY6,outputSchema:a80(CX),handler:async($,Z)=>{o(Z);let Q=W0(Z);if(await Z.access.check(),FK()&&cD0($.id,Q.id))throw Error("This connection is a fixed system connection and cannot be deleted");let X=await Z.storage.connections.findById($.id);if(!X)throw Error(`Connection not found: ${$.id}`);if(X.organization_id!==Q.id)throw Error("Connection not found in organization");let Y=X.metadata;if(Y?.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)}));if(await Z.storage.connections.delete($.id),$.id===K4.REPORTS(Q.id)&&typeof Y?.siteUrl==="string")hi({siteUrl:Y.siteUrl,orgId:Q.id,cause:"connection_deleted"});Xg$($.id),await Z.storage.triggerCallbackTokens.deleteByConnection($.id,Q.id),VZ()?.invalidate($.id).catch(()=>{}),ii($.id);let W=t0(Z);if(W)h1.capture({distinctId:W,event:"connection_deleted",groups:{organization:Q.id},properties:{connection_id:X.id,connection_type:X.connection_type,app_name:X.app_name??null,organization_id:Q.id,forced:$.force??!1}});return{item:X}}})});import{z as pi}from"zod";var PK1;var Yg$=L(()=>{_0();PK1=m({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:pi.object({id:pi.string()}),outputSchema:pi.object({id:pi.string(),healthy:pi.boolean(),latencyMs:pi.number()}),handler:async($,Z)=>{let Q=W0(Z);await Z.access.check();let X=await Z.storage.connections.findById($.id);if(!X||X.organization_id!==Q.id)throw Error("Connection not found");let Y=await Z.storage.connections.testConnection($.id);return{id:$.id,...Y}}})});var Jg$=L(()=>{nb$();HK1();FK1();Zg$();Qg$();Yg$()});import{sql as R6}from"kysely";import{z as zN}from"zod";function Gg$($){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 nY6($,Z){let Q="",X=0,Y=!1,J=!1,G=!1,W=null;for(let K=0;K<$.length;K++){let H=$[K];if(!Y&&!J&&W===null){if($.startsWith("--",K)){let F=$.indexOf(`
|
|
3118
|
+
`);for(let z of E.warnings)K.push({requestId:w.id,warning:z});for(let z of(Q=w.options.tools)!=null?Q:[])if(z.type==="provider"&&!AZ6.has(z.id))K.push({requestId:w.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:D}=await od({url:this.getUrl("/files"),headers:k1((Y=(X=this.options.config).headers)==null?void 0:Y.call(X),$.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:m9,successfulResponseHandler:R1(WD0),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),{value:O}=await Q$({url:this.getUrl("/batches"),headers:k1((G=(J=this.options.config).headers)==null?void 0:G.call(J),$.headers),body:{input_file_id:D.id,endpoint:tx$,completion_window:"24h"},failedResponseHandler:m9,successfulResponseHandler:R1(YW1),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),j=TW1(D.expires_at);return{batchId:O.id,...GD0(O),providerMetadata:{openai:{inputFileId:D.id,...j!=null?{inputFileExpiresAt:j}:{}}},warnings:K}}async parseBatchProviderOptions($){let Z=this.options.config.provider.includes("azure")?"azure":"openai",Q=await x$({provider:Z,providerOptions:$,schema:ox$});if(Q==null&&Z!=="openai")Q=await x$({provider:"openai",providerOptions:$,schema:ox$});return Q}async doGetBatchStatus($){let Z=await this.retrieveBatch($);return GD0(Z)}async doCancelBatch($){var Z,Q;return await Q$({url:this.getUrl(`/batches/${encodeURIComponent($.batchId)}/cancel`),headers:k1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),body:{},failedResponseHandler:m9,successfulResponseHandler:R1(YW1),abortSignal:$.abortSignal,fetch:this.options.config.fetch}),{}}async doListBatches($){var Z,Q;let X=new URL(this.getUrl("/batches"));if($.limit!=null)X.searchParams.set("limit",String($.limit));if($.cursor!=null)X.searchParams.set("after",$.cursor);let{value:Y}=await h6({url:X.toString(),headers:k1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),failedResponseHandler:m9,successfulResponseHandler:R1(zZ6),abortSignal:$.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return{batches:Y.data.map((J)=>({batchId:J.id,...GD0(J)})),...Y.has_more&&Y.last_id!=null?{nextCursor:Y.last_id}:{}}}async doGetBatchResults($){let Z=await this.retrieveBatch($),Q=GD0(Z);if(Q.status==="pending")throw new c8({argument:"batchId",message:`OpenAI batch "${$.batchId}" is not complete.`});let X=[Z.output_file_id,Z.error_file_id].filter((J)=>J!=null);if(Q.status==="completed"&&X.length===0)throw new q9({data:Z,message:`OpenAI batch "${$.batchId}" completed without batch output.`});let Y=this.iterateBatchResults({fileIds:X,options:$});return tU(Y)}async retrieveBatch($){var Z,Q;let{value:X}=await h6({url:this.getUrl(`/batches/${encodeURIComponent($.batchId)}`),headers:k1((Q=(Z=this.options.config).headers)==null?void 0:Q.call(Z),$.headers),failedResponseHandler:m9,successfulResponseHandler:R1(YW1),abortSignal:$.abortSignal,fetch:this.options.config.fetch,validateUrl:!1});return X}async*iterateBatchResults({fileIds:$,options:Z}){var Q,X;for(let Y of $){let{value:J}=await h6({url:this.getUrl(`/files/${encodeURIComponent(Y)}/content`),headers:k1((X=(Q=this.options.config).headers)==null?void 0:X.call(Q),Z.headers),failedResponseHandler:m9,successfulResponseHandler:LE(EZ6),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 MZ6({body:$.response.body,statusCode:$.response.status_code})};let Z=await IZ6($.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 Ef$.prepareRequest({modelId:$.modelId,config:this.options.config,options:$.options});return{body:Z,warnings:Q}}getUrl($){return this.options.config.url({path:$,modelId:""})}},AZ6,VZ6,kZ6,ax$,RW1,CZ6,rx$,sx$,HD0,JW1,Pf$,SZ6,_Z6,bZ6,ex$=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,X]of Object.entries(this.config.headers()))if(X!==void 0)Z[Q]=X;return{url:$.toString(),headers:Z}}async doCreateWebRTCSession({sdp:$,sessionConfig:Z={},abortSignal:Q}){let X=AW1(Z,this.modelId,"webrtc"),{value:Y}=await Q$({url:`${this.config.baseURL}/live/sessions`,headers:this.config.headers(),body:{session:X,transport:{type:"webrtc",sdp:YR.string().min(1).parse($)}},failedResponseHandler:m9,successfulResponseHandler:R1(bZ6),abortSignal:Q,fetch:this.config.fetch});return{sessionId:Y.session.id,sdp:Y.transport.sdp}}parseServerEvent($){return Tf$($)}createServerEventParser(){return vZ6()}serializeClientEvent($){return fZ6($,this.modelId)}buildSessionConfig($){return AW1($,this.modelId)}},hZ6=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,X=`${this.config.baseURL}/realtime/client_secrets`,Y=$.sessionConfig!=null?qW1($.sessionConfig,this.modelId):{type:"realtime",model:this.modelId},J=await Q(X,{method:"POST",headers:{...this.config.headers(),"Content-Type":"application/json"},body:JSON.stringify({session:Y,...$.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 yZ6($)}serializeClientEvent($){return gZ6($,this.modelId)}buildSessionConfig($){return qW1($,this.modelId)}},uZ6,mZ6,dZ6,iZ6,$f$,Qf$,pZ6,rZ6,sZ6,X76,uk9,Y76=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 Y of $.files){let J=oU(Y.data);Q.append("files[]",new Blob([J]),Y.path)}let{value:X}=await rW({url:this.config.url({path:"/skills"}),headers:k1(this.config.headers()),formData:Q,failedResponseHandler:m9,successfulResponseHandler:R1(X76),fetch:this.config.fetch});return{providerReference:{openai:X.id},...X.name!=null?{name:X.name}:{},...X.description!=null?{description:X.description}:{},...X.latest_version!=null?{latestVersion:X.latest_version}:{},providerMetadata:{openai:{...X.default_version!=null?{defaultVersion:X.default_version}:{},...X.created_at!=null?{createdAt:X.created_at}:{},...X.updated_at!=null?{updatedAt:X.updated_at}:{}}},warnings:Z}}},J76="4.0.71",lk9;var UD0=L(()=>{T0();tB0();z1();T0();T0();z1();T0();T0();z1();T0();T0();T0();T0();z1();z1();T0();T0();z1();T0();T0();T0();z1();T0();T0();T0();z1();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();T0();z1();T0();T0();T0();z1();T0();z1();T0();z1();T0();T0();z1();T0();z1();T0();z1();z1();T0();T0();z1();T0();T0();T0();z1();T0();T0();T0();T0();FD0=_E.object({error:_E.object({message:_E.string(),type:_E.string().nullish(),param:_E.any().nullish(),code:_E.union([_E.string(),_E.number()]).nullish()})}),m9=y4({errorSchema:FD0,errorToMessage:($)=>$.error.message});j56=K0(()=>e(q1.object({id:q1.string().nullish(),created:q1.number().nullish(),model:q1.string().nullish(),choices:q1.array(q1.object({message:q1.object({role:q1.literal("assistant").nullish(),content:q1.string().nullish(),tool_calls:q1.array(q1.object({id:q1.string().nullish(),type:q1.literal("function"),function:q1.object({name:q1.string(),arguments:q1.string()})})).nullish(),annotations:q1.array(q1.object({type:q1.literal("url_citation"),url_citation:q1.object({start_index:q1.number(),end_index:q1.number(),url:q1.string(),title:q1.string()})})).nullish()}),index:q1.number(),logprobs:q1.object({content:q1.array(q1.object({token:q1.string(),logprob:q1.number(),top_logprobs:q1.array(q1.object({token:q1.string(),logprob:q1.number()}))})).nullish()}).nullish(),finish_reason:q1.string().nullish()})),usage:q1.object({prompt_tokens:q1.number().nullish(),completion_tokens:q1.number().nullish(),total_tokens:q1.number().nullish(),prompt_tokens_details:q1.object({cached_tokens:q1.number().nullish(),cache_write_tokens:q1.number().nullish()}).nullish(),completion_tokens_details:q1.object({reasoning_tokens:q1.number().nullish(),accepted_prediction_tokens:q1.number().nullish(),rejected_prediction_tokens:q1.number().nullish()}).nullish()}).nullish()}))),w56=K0(()=>e(q1.union([q1.object({id:q1.string().nullish(),created:q1.number().nullish(),model:q1.string().nullish(),choices:q1.array(q1.object({delta:q1.object({role:q1.enum(["assistant"]).nullish(),content:q1.string().nullish(),tool_calls:q1.array(q1.object({index:q1.number(),id:q1.string().nullish(),type:q1.literal("function").nullish(),function:q1.object({name:q1.string().nullish(),arguments:q1.string().nullish()})})).nullish(),annotations:q1.array(q1.object({type:q1.literal("url_citation"),url_citation:q1.object({start_index:q1.number(),end_index:q1.number(),url:q1.string(),title:q1.string()})})).nullish()}).nullish(),logprobs:q1.object({content:q1.array(q1.object({token:q1.string(),logprob:q1.number(),top_logprobs:q1.array(q1.object({token:q1.string(),logprob:q1.number()}))})).nullish()}).nullish(),finish_reason:q1.string().nullish(),index:q1.number()})),usage:q1.object({prompt_tokens:q1.number().nullish(),completion_tokens:q1.number().nullish(),total_tokens:q1.number().nullish(),prompt_tokens_details:q1.object({cached_tokens:q1.number().nullish(),cache_write_tokens:q1.number().nullish()}).nullish(),completion_tokens_details:q1.object({reasoning_tokens:q1.number().nullish(),accepted_prediction_tokens:q1.number().nullish(),rejected_prediction_tokens:q1.number().nullish()}).nullish()}).nullish()}),FD0]))),E56=K0(()=>e(z5.object({logitBias:z5.record(z5.coerce.number(),z5.number()).optional(),logprobs:z5.union([z5.boolean(),z5.number()]).optional(),parallelToolCalls:z5.boolean().optional(),user:z5.string().optional(),reasoningEffort:z5.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:z5.number().optional(),store:z5.boolean().optional(),metadata:z5.record(z5.string().max(64),z5.string().max(512)).optional(),prediction:z5.record(z5.string(),z5.any()).optional(),serviceTier:z5.enum(["auto","flex","priority","fast","ultrafast","default"]).optional(),strictJsonSchema:z5.boolean().optional(),textVerbosity:z5.enum(["low","medium","high"]).optional(),promptCacheKey:z5.string().optional(),promptCacheOptions:z5.object({mode:z5.enum(["implicit","explicit"]).optional(),ttl:z5.literal("30m").optional()}).optional(),promptCacheRetention:z5.enum(["in_memory","24h"]).optional(),safetyIdentifier:z5.string().optional(),systemMessageMode:z5.enum(["system","developer","remove"]).optional(),forceReasoning:z5.boolean().optional()})));P56=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=Z,this.config=Q}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({prompt:Z,maxOutputTokens:Q,temperature:X,topP:Y,topK:J,frequencyPenalty:G,presencePenalty:W,stopSequences:K,responseFormat:H,seed:F,tools:U,toolChoice:N,reasoning:B,providerOptions:D}){var O,j,w,E,z,A;let P=[],T=(O=await x$({provider:"openai",providerOptions:D,schema:E56}))!=null?O:{},q=Xf$(this.modelId),f=(j=T.reasoningEffort)!=null?j:rL(B)?B:void 0;if(f!=null&&q.supportedReasoningEfforts!=null&&!q.supportedReasoningEfforts.includes(f))P.push({type:"unsupported",feature:"reasoningEffort",details:`${this.modelId} only supports the following reasoning efforts: ${q.supportedReasoningEfforts.join(", ")}`}),f=void 0;let S=(w=T.forceReasoning)!=null?w:q.isReasoningModel;if(J!=null)P.push({type:"unsupported",feature:"topK"});let{messages:V,warnings:u}=O56({prompt:Z,systemMessageMode:(E=T.systemMessageMode)!=null?E:S?"developer":q.systemMessageMode});P.push(...u);let g=(z=T.strictJsonSchema)!=null?z:!0,l=(H==null?void 0:H.type)==="json"&&H.schema!=null?I80(H.schema):void 0;if(l!=null)P.push(...l.warnings);let h={model:this.modelId,logit_bias:T.logitBias,logprobs:T.logprobs===!0||typeof T.logprobs==="number"?!0:void 0,top_logprobs:typeof T.logprobs==="number"?T.logprobs:typeof T.logprobs==="boolean"?T.logprobs?0:void 0:void 0,user:T.user,parallel_tool_calls:T.parallelToolCalls,max_tokens:Q,temperature:X,top_p:Y,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:(A=H.name)!=null?A:"response",description:H.description}}:{type:"json_object"}:void 0,stop:K,seed:F,verbosity:T.textVerbosity,max_completion_tokens:T.maxCompletionTokens,store:T.store,metadata:T.metadata,prediction:T.prediction,reasoning_effort:f,service_tier:T.serviceTier,prompt_cache_key:T.promptCacheKey,prompt_cache_options:T.promptCacheOptions,prompt_cache_retention:T.promptCacheRetention,safety_identifier:T.safetyIdentifier,messages:V};if(q.supportedReasoningEfforts!=null&&h.prompt_cache_retention!=null)h.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(S){if(f!=="none"||!q.supportsNonReasoningParameters){if(h.temperature!=null)h.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(h.top_p!=null)h.top_p=void 0,P.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(h.logprobs!=null)h.logprobs=void 0,P.push({type:"other",message:"logprobs is not supported for reasoning models"})}if(h.frequency_penalty!=null)h.frequency_penalty=void 0,P.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"});if(h.presence_penalty!=null)h.presence_penalty=void 0,P.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"});if(h.logit_bias!=null)h.logit_bias=void 0,P.push({type:"other",message:"logitBias is not supported for reasoning models"});if(h.top_logprobs!=null)h.top_logprobs=void 0,P.push({type:"other",message:"topLogprobs is not supported for reasoning models"});if(h.max_tokens!=null){if(h.max_completion_tokens==null)h.max_completion_tokens=h.max_tokens;h.max_tokens=void 0}}else if(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview")){if(h.temperature!=null)h.temperature=void 0,P.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})}if(T.serviceTier==="flex"&&!q.supportsFlexProcessing)P.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),h.service_tier=void 0;if((T.serviceTier==="priority"||T.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"}),h.service_tier=void 0;let{tools:i,toolChoice:H0,toolWarnings:R0}=z56({tools:U,toolChoice:N});return{args:{...h,tools:i,tool_choice:H0},warnings:[...P,...R0]}}async doGenerate(Z){var Q,X,Y,J,G,W,K;let{args:H,warnings:F}=await this.getArgs(Z),{responseHeaders:U,value:N,rawValue:B}=await Q$({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:H,failedResponseHandler:m9,successfulResponseHandler:R1(j56),abortSignal:Z.abortSignal,fetch:this.config.fetch}),D=N.choices[0];if(D==null)throw new q9({data:B,message:"Response did not contain any choices."});let O=[],j=D.message.content;if(j!=null&&j.length>0)O.push({type:"text",text:j});for(let z of(Y=D.message.tool_calls)!=null?Y:[])O.push({type:"tool-call",toolCallId:z.id||J4(),toolName:z.function.name,input:z.function.arguments});for(let z of(J=D.message.annotations)!=null?J:[])O.push({type:"source",sourceType:"url",id:J4(),url:z.url_citation.url,title:z.url_citation.title});let w=(G=N.usage)==null?void 0:G.completion_tokens_details,E={openai:{}};if((w==null?void 0:w.accepted_prediction_tokens)!=null)E.openai.acceptedPredictionTokens=w==null?void 0:w.accepted_prediction_tokens;if((w==null?void 0:w.rejected_prediction_tokens)!=null)E.openai.rejectedPredictionTokens=w==null?void 0:w.rejected_prediction_tokens;if(((W=D.logprobs)==null?void 0:W.content)!=null)E.openai.logprobs=D.logprobs.content;return{content:O,finishReason:{unified:Mx$(D.finish_reason),raw:(K=D.finish_reason)!=null?K:void 0},usage:qx$(N.usage),request:{body:H},response:{...r31(N),headers:U,body:B},warnings:F,providerMetadata:E}}async doStream(Z){var Q,X;let{args:Y,warnings:J}=await this.getArgs(Z),G={...Y,stream:!0,stream_options:{include_usage:!0}},W=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:K,value:H}=await Q$({url:W,headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:G,failedResponseHandler:m9,successfulResponseHandler:lX(w56),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=await MW1({stream:H,getError:(E)=>("error"in E)?E.error:void 0,isOutputChunk:T56,url:W,requestBodyValues:G,responseHeaders:K}),U,N={unified:"other",raw:void 0},B=void 0,D=!1,O=!1,j={openai:{}};return{stream:F.pipeThrough(new TransformStream({start(E){U=new WC$(E,{generateId:J4,typeValidation:"if-present"}),E.enqueue({type:"stream-start",warnings:J})},transform(E,z){var A,P,T,q,f,S;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:(A=M80(V.error))!=null?A:V.error});return}if(!D){let l=r31(V);if(Object.values(l).some(Boolean))D=!0,z.enqueue({type:"response-metadata",...r31(V)})}if(V.usage!=null){if(B=V.usage,((P=V.usage.completion_tokens_details)==null?void 0:P.accepted_prediction_tokens)!=null)j.openai.acceptedPredictionTokens=(T=V.usage.completion_tokens_details)==null?void 0:T.accepted_prediction_tokens;if(((q=V.usage.completion_tokens_details)==null?void 0:q.rejected_prediction_tokens)!=null)j.openai.rejectedPredictionTokens=(f=V.usage.completion_tokens_details)==null?void 0:f.rejected_prediction_tokens}let u=V.choices[0];if((u==null?void 0:u.finish_reason)!=null)N={unified:Mx$(u.finish_reason),raw:u.finish_reason};if(((S=u==null?void 0:u.logprobs)==null?void 0:S.content)!=null)j.openai.logprobs=u.logprobs.content;if((u==null?void 0:u.delta)==null)return;let g=u.delta;if(g.content!=null){if(!O)z.enqueue({type:"text-start",id:"0"}),O=!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:J4(),url:l.url_citation.url,title:l.url_citation.title})},flush(E){if(O)E.enqueue({type:"text-end",id:"0"});U.flush(),E.enqueue({type:"finish",finishReason:N,usage:qx$(B),...j!=null?{providerMetadata:j}:{}})}})),request:{body:G},response:{headers:K}}}};R56=K0(()=>e(t8.object({id:t8.string().nullish(),created:t8.number().nullish(),model:t8.string().nullish(),choices:t8.array(t8.object({text:t8.string(),finish_reason:t8.string(),logprobs:t8.object({tokens:t8.array(t8.string()),token_logprobs:t8.array(t8.number()),top_logprobs:t8.array(t8.record(t8.string(),t8.number())).nullish()}).nullish()})),usage:t8.object({prompt_tokens:t8.number(),completion_tokens:t8.number(),total_tokens:t8.number()}).nullish()}))),q56=K0(()=>e(t8.union([t8.object({id:t8.string().nullish(),created:t8.number().nullish(),model:t8.string().nullish(),choices:t8.array(t8.object({text:t8.string(),finish_reason:t8.string().nullish(),index:t8.number(),logprobs:t8.object({tokens:t8.array(t8.string()),token_logprobs:t8.array(t8.number()),top_logprobs:t8.array(t8.record(t8.string(),t8.number())).nullish()}).nullish()})),usage:t8.object({prompt_tokens:t8.number(),completion_tokens:t8.number(),total_tokens:t8.number()}).nullish()}),FD0]))),kx$=K0(()=>e(BN.object({echo:BN.boolean().optional(),logitBias:BN.record(BN.string(),BN.number()).optional(),suffix:BN.string().optional(),user:BN.string().optional(),logprobs:BN.union([BN.boolean(),BN.number()]).optional()}))),M56=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[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({prompt:Z,maxOutputTokens:Q,temperature:X,topP:Y,topK:J,frequencyPenalty:G,presencePenalty:W,stopSequences:K,responseFormat:H,tools:F,toolChoice:U,seed:N,providerOptions:B}){let D=[],O={...await x$({provider:"openai",providerOptions:B,schema:kx$}),...await x$({provider:this.providerOptionsName,providerOptions:B,schema:kx$})};if(J!=null)D.push({type:"unsupported",feature:"topK"});if(F==null?void 0:F.length)D.push({type:"unsupported",feature:"tools"});if(U!=null)D.push({type:"unsupported",feature:"toolChoice"});if(H!=null&&H.type!=="text")D.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});let{prompt:j,stopSequences:w}=A56({prompt:Z}),E=[...w!=null?w:[],...K!=null?K:[]];return{args:{model:this.modelId,echo:O.echo,logit_bias:O.logitBias,logprobs:(O==null?void 0:O.logprobs)===!0?0:(O==null?void 0:O.logprobs)===!1?void 0:O==null?void 0:O.logprobs,suffix:O.suffix,user:O.user,max_tokens:Q,temperature:X,top_p:Y,frequency_penalty:G,presence_penalty:W,seed:N,prompt:j,stop:E.length>0?E:void 0},warnings:D}}async doGenerate(Z){var Q,X,Y;let{args:J,warnings:G}=await this.getArgs(Z),{responseHeaders:W,value:K,rawValue:H}=await Q$({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:J,failedResponseHandler:m9,successfulResponseHandler:R1(R56),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:Ix$(K.usage),finishReason:{unified:Vx$(F.finish_reason),raw:(Y=F.finish_reason)!=null?Y:void 0},request:{body:J},response:{...s10(K),headers:W,body:H},providerMetadata:U,warnings:G}}async doStream(Z){var Q,X;let{args:Y,warnings:J}=await this.getArgs(Z),G={...Y,stream:!0,stream_options:{include_usage:!0}},W=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:K,value:H}=await Q$({url:W,headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:G,failedResponseHandler:m9,successfulResponseHandler:lX(q56),abortSignal:Z.abortSignal,fetch:this.config.fetch}),F=await MW1({stream:H,getError:(j)=>("error"in j)?j.error:void 0,isOutputChunk:I56,url:W,requestBodyValues:G,responseHeaders:K}),U={unified:"other",raw:void 0},N={openai:{}},B=void 0,D=!0;return{stream:F.pipeThrough(new TransformStream({start(j){j.enqueue({type:"stream-start",warnings:J})},transform(j,w){var E;if(Z.includeRawChunks)w.enqueue({type:"raw",rawValue:j.rawValue});if(!j.success){U={unified:"error",raw:void 0},w.enqueue({type:"error",error:j.error});return}let z=j.value;if("error"in z){U={unified:"error",raw:void 0},w.enqueue({type:"error",error:(E=M80(z.error))!=null?E:z.error});return}if(D)D=!1,w.enqueue({type:"response-metadata",...s10(z)}),w.enqueue({type:"text-start",id:"0"});if(z.usage!=null)B=z.usage;let A=z.choices[0];if((A==null?void 0:A.finish_reason)!=null)U={unified:Vx$(A.finish_reason),raw:A.finish_reason};if((A==null?void 0:A.logprobs)!=null)N.openai.logprobs=A.logprobs;if((A==null?void 0:A.text)!=null&&A.text.length>0)w.enqueue({type:"text-delta",id:"0",delta:A.text})},flush(j){if(!D)j.enqueue({type:"text-end",id:"0"});j.enqueue({type:"finish",finishReason:U,providerMetadata:N,usage:Ix$(B)})}})),request:{body:G},response:{headers:K}}}};V56=K0(()=>e(s31.object({dimensions:s31.number().optional(),user:s31.string().optional()}))),k56=K0(()=>e(QR.object({data:QR.array(QR.object({embedding:QR.array(QR.number())})),usage:QR.object({prompt_tokens:QR.number()}).nullish()}))),C56=class ${constructor(Z,Q){this.specificationVersion="v4",this.maxEmbeddingsPerCall=2048,this[Cx$]=300000,this.supportsParallelCalls=!0,this.modelId=Z,this.config=Q}static[(Cx$=dk$,U4)](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async doEmbed({values:Z,headers:Q,abortSignal:X,providerOptions:Y}){var J,G,W;if(Z.length>this.maxEmbeddingsPerCall)throw new vB0({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:Z});let K=(J=await x$({provider:"openai",providerOptions:Y,schema:V56}))!=null?J:{},{responseHeaders:H,value:F,rawValue:U}=await Q$({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:k1((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:m9,successfulResponseHandler:R1(k56),abortSignal:X,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}}}},WD0=K0(()=>e(q3.object({id:q3.string(),object:q3.string().nullish(),bytes:q3.number().nullish(),created_at:q3.number().nullish(),filename:q3.string().nullish(),purpose:q3.string().nullish(),status:q3.string().nullish(),expires_at:q3.number().nullish()}))),S56=K0(()=>e(q3.object({id:q3.string(),object:q3.string().nullish(),deleted:q3.boolean()}))),_56=K0(()=>e(e31.object({purpose:e31.string().optional(),expiresAfter:e31.number().optional()})));Sx$=K0(()=>e(ZX.object({created:ZX.number().nullish(),data:ZX.array(ZX.object({b64_json:ZX.string(),revised_prompt:ZX.string().nullish()})),background:ZX.string().nullish(),output_format:ZX.string().nullish(),size:ZX.string().nullish(),quality:ZX.string().nullish(),usage:ZX.object({input_tokens:ZX.number().nullish(),output_tokens:ZX.number().nullish(),total_tokens:ZX.number().nullish(),input_tokens_details:ZX.object({image_tokens:ZX.number().nullish(),text_tokens:ZX.number().nullish()}).nullish()}).nullish()}))),x56={"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},f56=["chatgpt-image-","gpt-image-"];IW1=HD.object({quality:HD.enum(["standard","hd","low","medium","high","xhigh","max","auto"]).optional(),background:HD.enum(["transparent","opaque","auto"]).optional(),outputFormat:HD.enum(["png","jpeg","webp"]).optional(),outputCompression:HD.number().int().min(0).max(100).optional(),user:HD.string().optional()}),RV9=K0(()=>e(IW1)),g56=K0(()=>e(IW1.extend({style:HD.enum(["vivid","natural"]).optional(),moderation:HD.enum(["auto","low"]).optional()}))),h56=K0(()=>e(IW1.extend({inputFidelity:HD.enum(["high","low"]).optional()}))),u56=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get maxImagesPerCall(){return y56(this.modelId)}get provider(){return this.config.provider}async doGenerate({prompt:Z,files:Q,mask:X,n:Y,size:J,aspectRatio:G,seed:W,providerOptions:K,headers:H,abortSignal:F}){var U,N,B,D,O,j,w,E,z,A,P,T,q,f,S;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 u=(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 i=(D=await x$({provider:"openai",providerOptions:K,schema:h56}))!=null?D:{},{value:H0,responseHeaders:R0}=await rW({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:k1((j=(O=this.config).headers)==null?void 0:j.call(O),H),formData:vk$({model:this.modelId,prompt:Z,image:await Promise.all(Q.map((Y0)=>Y0.type==="file"?new Blob([Y0.data instanceof Uint8Array?new Blob([Y0.data],{type:Y0.mediaType}):new Blob([a9(Y0.data)],{type:Y0.mediaType})],{type:Y0.mediaType}):Q$0(Y0.url,{abortSignal:F}))),mask:X!=null?await l56(X,F):void 0,n:Y,size:J,quality:i.quality,background:i.background,output_format:i.outputFormat,output_compression:i.outputCompression,input_fidelity:i.inputFidelity,user:i.user}),failedResponseHandler:m9,successfulResponseHandler:R1(Sx$),abortSignal:F,fetch:this.config.fetch});return{images:H0.data.map((Y0)=>Y0.b64_json),warnings:V,usage:H0.usage!=null?{inputTokens:(w=H0.usage.input_tokens)!=null?w:void 0,outputTokens:(E=H0.usage.output_tokens)!=null?E:void 0,totalTokens:(z=H0.usage.total_tokens)!=null?z:void 0}:void 0,response:{timestamp:u,modelId:this.modelId,headers:R0},providerMetadata:{openai:{images:H0.data.map((Y0,N0)=>{var n,t,a,s,X0,p0;return{...Y0.revised_prompt?{revisedPrompt:Y0.revised_prompt}:{},created:(n=H0.created)!=null?n:void 0,size:(t=H0.size)!=null?t:void 0,quality:(a=H0.quality)!=null?a:void 0,background:(s=H0.background)!=null?s:void 0,outputFormat:(X0=H0.output_format)!=null?X0:void 0,..._x$((p0=H0.usage)==null?void 0:p0.input_tokens_details,N0,H0.data.length)}})}}}}let g=(A=await x$({provider:"openai",providerOptions:K,schema:g56}))!=null?A:{},{value:l,responseHeaders:h}=await Q$({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:k1((T=(P=this.config).headers)==null?void 0:T.call(P),H),body:{model:this.modelId,prompt:Z,n:Y,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,...!b56(this.modelId)?{response_format:"b64_json"}:{}},failedResponseHandler:m9,successfulResponseHandler:R1(Sx$),abortSignal:F,fetch:this.config.fetch});return{images:l.data.map((i)=>i.b64_json),warnings:V,usage:l.usage!=null?{inputTokens:(q=l.usage.input_tokens)!=null?q:void 0,outputTokens:(f=l.usage.output_tokens)!=null?f:void 0,totalTokens:(S=l.usage.total_tokens)!=null?S:void 0}:void 0,response:{timestamp:u,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:l.data.map((i,H0)=>{var R0,Y0,N0,n,t,a;return{...i.revised_prompt?{revisedPrompt:i.revised_prompt}:{},created:(R0=l.created)!=null?R0:void 0,size:(Y0=l.size)!=null?Y0:void 0,quality:(N0=l.quality)!=null?N0:void 0,background:(n=l.background)!=null?n:void 0,outputFormat:(t=l.output_format)!=null?t:void 0,..._x$((a=l.usage)==null?void 0:a.input_tokens_details,H0,l.data.length)}})}}}}};Yf$=K0(()=>e(LQ.object({callId:LQ.string(),operation:LQ.discriminatedUnion("type",[LQ.object({type:LQ.literal("create_file"),path:LQ.string(),diff:LQ.string()}),LQ.object({type:LQ.literal("delete_file"),path:LQ.string()}),LQ.object({type:LQ.literal("update_file"),path:LQ.string(),diff:LQ.string()})])}))),Jf$=K0(()=>e(LQ.object({status:LQ.enum(["completed","failed"]),output:LQ.string().optional()}))),IV9=K0(()=>e(LQ.object({}))),c56=$N({id:"openai.apply_patch",inputSchema:Yf$,outputSchema:Jf$}),m56=c56,d56=K0(()=>e(DQ.object({code:DQ.string().nullish(),containerId:DQ.string()}))),i56=K0(()=>e(DQ.object({outputs:DQ.array(DQ.discriminatedUnion("type",[DQ.object({type:DQ.literal("logs"),logs:DQ.string()}),DQ.object({type:DQ.literal("image"),url:DQ.string()})])).nullish()}))),p56=K0(()=>e(DQ.object({container:DQ.union([DQ.string(),DQ.object({fileIds:DQ.array(DQ.string()).optional()})]).optional()}))),n56=p$({id:"openai.code_interpreter",inputSchema:d56,outputSchema:i56}),Gf$=L$.object({id:L$.string(),code:L$.string().optional(),message:L$.string().optional()}),o56=L$.discriminatedUnion("type",[L$.object({type:L$.literal("click"),button:L$.enum(["left","right","wheel","back","forward"]),x:L$.number(),y:L$.number(),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("double_click"),x:L$.number(),y:L$.number(),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("drag"),path:L$.array(L$.object({x:L$.number(),y:L$.number()})),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("keypress"),keys:L$.array(L$.string())}),L$.object({type:L$.literal("move"),x:L$.number(),y:L$.number(),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("screenshot")}),L$.object({type:L$.literal("scroll"),x:L$.number(),y:L$.number(),scrollX:L$.number(),scrollY:L$.number(),keys:L$.array(L$.string()).optional()}),L$.object({type:L$.literal("type"),text:L$.string()}),L$.object({type:L$.literal("wait")})]),Wf$=K0(()=>e(L$.object({actions:L$.array(o56),pendingSafetyChecks:L$.array(Gf$),status:L$.enum(["in_progress","completed","incomplete"])}))),Kf$=K0(()=>e(L$.object({output:L$.union([L$.object({type:L$.literal("computer_screenshot"),imageUrl:L$.string(),fileId:L$.string().optional(),detail:L$.enum(["auto","low","high","original"]).optional()}),L$.object({type:L$.literal("computer_screenshot"),fileId:L$.string(),imageUrl:L$.string().optional(),detail:L$.enum(["auto","low","high","original"]).optional()})]),acknowledgedSafetyChecks:L$.array(Gf$).optional()}))),a56=$N({id:"openai.computer",inputSchema:Wf$,outputSchema:Kf$}),s56=K0(()=>e(XF.object({description:XF.string().optional(),async:XF.boolean().optional(),format:XF.union([XF.object({type:XF.literal("grammar"),syntax:XF.enum(["regex","lark"]),definition:XF.string()}),XF.object({type:XF.literal("text")})]).optional()}))),e56=K0(()=>e(XF.string())),$96=TZ({id:"openai.custom",inputSchema:e56}),Hf$=B6.object({key:B6.string(),type:B6.enum(["eq","ne","gt","gte","lt","lte","in","nin"]),value:B6.union([B6.string(),B6.number(),B6.boolean(),B6.array(B6.string())])}),Ff$=B6.object({type:B6.enum(["and","or"]),filters:B6.array(B6.union([Hf$,B6.lazy(()=>Ff$)]))}),Q96=K0(()=>e(B6.object({vectorStoreIds:B6.array(B6.string()),maxNumResults:B6.number().optional(),ranking:B6.object({ranker:B6.string().optional(),scoreThreshold:B6.number().optional()}).optional(),filters:B6.union([Hf$,Ff$]).optional()}))),X96=K0(()=>e(B6.object({queries:B6.array(B6.string()),results:B6.array(B6.object({attributes:B6.record(B6.string(),B6.unknown()),fileId:B6.string(),filename:B6.string(),score:B6.number(),text:B6.string()})).nullable()}))),Y96=p$({id:"openai.file_search",inputSchema:B6.object({}),outputSchema:X96}),J96=K0(()=>e(u7.object({action:u7.enum(["generate","edit","auto"]).optional(),background:u7.enum(["auto","opaque","transparent"]).optional(),inputFidelity:u7.enum(["low","high"]).optional(),inputImageMask:u7.object({fileId:u7.string().optional(),imageUrl:u7.string().optional()}).optional(),model:u7.string().optional(),moderation:u7.enum(["auto","low"]).optional(),outputCompression:u7.number().int().min(0).max(100).optional(),outputFormat:u7.enum(["png","jpeg","webp"]).optional(),partialImages:u7.number().int().min(0).max(3).optional(),quality:u7.enum(["auto","low","medium","high","xhigh","max"]).optional(),size:u7.union([u7.enum(["1024x1024","1024x1536","1536x1024","auto"]),u7.string().regex(/^\d+x\d+$/)]).optional()}).strict())),G96=K0(()=>e(u7.object({}))),W96=K0(()=>e(u7.object({result:u7.string()}))),K96=p$({id:"openai.image_generation",inputSchema:G96,outputSchema:W96}),Uf$=K0(()=>e(R3.object({action:R3.object({type:R3.literal("exec"),command:R3.array(R3.string()),timeoutMs:R3.number().optional(),user:R3.string().optional(),workingDirectory:R3.string().optional(),env:R3.record(R3.string(),R3.string()).optional()})}))),Nf$=K0(()=>e(R3.object({output:R3.string()}))),F96=$N({id:"openai.local_shell",inputSchema:Uf$,outputSchema:Nf$}),Bf$=K0(()=>e(b$.object({action:b$.object({commands:b$.array(b$.string()),timeoutMs:b$.number().optional(),maxOutputLength:b$.number().optional()})}))),WW1=K0(()=>e(b$.object({output:b$.array(b$.object({stdout:b$.string(),stderr:b$.string(),outcome:b$.discriminatedUnion("type",[b$.object({type:b$.literal("timeout")}),b$.object({type:b$.literal("exit"),exitCode:b$.number()})])}))}))),U96=b$.array(b$.discriminatedUnion("type",[b$.object({type:b$.literal("skillReference"),providerReference:b$.record(b$.string(),b$.string()),version:b$.string().optional()}),b$.object({type:b$.literal("inline"),name:b$.string(),description:b$.string(),source:b$.object({type:b$.literal("base64"),mediaType:b$.literal("application/zip"),data:b$.string()})})])).optional(),N96=K0(()=>e(b$.object({environment:b$.union([b$.object({type:b$.literal("containerAuto"),fileIds:b$.array(b$.string()).optional(),memoryLimit:b$.enum(["1g","4g","16g","64g"]).optional(),networkPolicy:b$.discriminatedUnion("type",[b$.object({type:b$.literal("disabled")}),b$.object({type:b$.literal("allowlist"),allowedDomains:b$.array(b$.string()),domainSecrets:b$.array(b$.object({domain:b$.string(),name:b$.string(),value:b$.string()})).optional()})]).optional(),skills:U96}),b$.object({type:b$.literal("containerReference"),containerId:b$.string()}),b$.object({type:b$.literal("local").optional(),skills:b$.array(b$.object({name:b$.string(),description:b$.string(),path:b$.string()})).optional()})]).optional()}))),B96=$N({id:"openai.shell",inputSchema:Bf$,outputSchema:WW1}),L96=K0(()=>e(ZG.object({execution:ZG.enum(["server","client"]).optional(),description:ZG.string().optional(),parameters:ZG.record(ZG.string(),ZG.unknown()).optional()}))),KW1=K0(()=>e(ZG.object({arguments:ZG.unknown().optional(),call_id:ZG.string().nullish()}))),HW1=K0(()=>e(ZG.object({tools:ZG.array(ZG.record(ZG.string(),ZG.unknown()))}))),D96=$N({id:"openai.tool_search",inputSchema:KW1,outputSchema:HW1}),j96=K0(()=>e(o4.object({externalWebAccess:o4.boolean().optional(),filters:o4.object({allowedDomains:o4.array(o4.string()).optional(),blockedDomains:o4.array(o4.string()).optional()}).optional(),searchContextSize:o4.enum(["low","medium","high"]).optional(),userLocation:o4.object({type:o4.literal("approximate"),country:o4.string().optional(),city:o4.string().optional(),region:o4.string().optional(),timezone:o4.string().optional()}).optional()}))),w96=K0(()=>e(o4.object({}))),E96=K0(()=>e(o4.object({action:o4.discriminatedUnion("type",[o4.object({type:o4.literal("search"),query:o4.string().optional(),queries:o4.array(o4.string()).optional()}),o4.object({type:o4.literal("openPage"),url:o4.string().nullish()}),o4.object({type:o4.literal("findInPage"),url:o4.string().nullish(),pattern:o4.string().nullish()})]).optional(),sources:o4.array(o4.discriminatedUnion("type",[o4.object({type:o4.literal("url"),url:o4.string()}),o4.object({type:o4.literal("api"),name:o4.string()})])).optional()}))),z96=p$({id:"openai.web_search",inputSchema:w96,outputSchema:E96}),T96=K0(()=>e(aZ.object({searchContextSize:aZ.enum(["low","medium","high"]).optional(),userLocation:aZ.object({type:aZ.literal("approximate"),country:aZ.string().optional(),city:aZ.string().optional(),region:aZ.string().optional(),timezone:aZ.string().optional()}).optional()}))),A96=K0(()=>e(aZ.object({}))),R96=K0(()=>e(aZ.object({action:aZ.discriminatedUnion("type",[aZ.object({type:aZ.literal("search"),query:aZ.string().optional()}),aZ.object({type:aZ.literal("openPage"),url:aZ.string().nullish()}),aZ.object({type:aZ.literal("findInPage"),url:aZ.string().nullish(),pattern:aZ.string().nullish()})]).optional()}))),q96=p$({id:"openai.web_search_preview",inputSchema:A96,outputSchema:R96}),FW1=R4.lazy(()=>R4.union([R4.string(),R4.number(),R4.boolean(),R4.null(),R4.array(FW1),R4.record(R4.string(),FW1)])),M96=K0(()=>e(R4.object({serverLabel:R4.string(),allowedTools:R4.union([R4.array(R4.string()),R4.object({readOnly:R4.boolean().optional(),toolNames:R4.array(R4.string()).optional()})]).optional(),authorization:R4.string().optional(),connectorId:R4.string().optional(),headers:R4.record(R4.string(),R4.string()).optional(),requireApproval:R4.union([R4.enum(["always","never"]),R4.object({never:R4.object({toolNames:R4.array(R4.string()).optional()}).optional()})]).optional(),serverDescription:R4.string().optional(),serverUrl:R4.string().optional()}).refine(($)=>$.serverUrl!=null||$.connectorId!=null,"One of serverUrl or connectorId must be provided."))),I96=K0(()=>e(R4.object({}))),V96=K0(()=>e(R4.object({type:R4.literal("call"),serverLabel:R4.string(),name:R4.string(),arguments:R4.string(),output:R4.string().nullish(),error:R4.union([R4.string(),FW1]).optional()}))),k96=p$({id:"openai.mcp",inputSchema:I96,outputSchema:V96}),Lf$=K0(()=>e(Ci.object({code:Ci.string(),fingerprint:Ci.string()}))),Df$=K0(()=>e(Ci.object({result:Ci.string(),status:Ci.enum(["completed","incomplete"])}))),S96=p$({id:"openai.programmatic_tool_calling",inputSchema:Lf$,outputSchema:Df$,supportsDeferredResults:!0}),v96={applyPatch:m56,customTool:Z96,codeInterpreter:t56,computer:r56,fileSearch:Y96,imageGeneration:H96,localShell:F96,shell:B96,webSearchPreview:q96,webSearch:P96,mcp:C96,programmaticToolCalling:_96,toolSearch:O96};Si=R.lazy(()=>R.union([R.string(),R.number(),R.boolean(),R.null(),R.array(Si),R.record(R.string(),Si.optional())])),ZW1=R.record(R.string(),Si.optional()),NW1=R.intersection(ZW1,R.object({input_tokens:R.number(),input_tokens_details:R.intersection(ZW1,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(ZW1,R.object({reasoning_tokens:R.number().nullish(),orchestration_output_tokens:R.number().nullish()})).nullish(),total_tokens:R.number().optional()})),x96=R.object({id:R.string(),code:R.string().nullish(),message:R.string().nullish()}),vx$=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")})]),BW1=R.object({type:R.literal("computer_call"),id:R.string(),call_id:R.string().nullish(),status:R.enum(["in_progress","completed","incomplete"]),action:vx$.nullish(),actions:R.array(vx$).nullish(),pending_safety_checks:R.array(x96).nullish()}),LW1=R.discriminatedUnion("type",[R.object({type:R.literal("direct")}),R.object({type:R.literal("program"),caller_id:R.string()})]),DW1=R.object({type:R.literal("program"),id:R.string(),call_id:R.string(),code:R.string(),fingerprint:R.string()}),OW1=R.object({type:R.literal("program_output"),id:R.string(),call_id:R.string(),result:R.string(),status:R.enum(["completed","incomplete"])}),jW1=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()})}),f96=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()})}),b96=R.object({type:R.literal("error"),sequence_number:R.number(),code:R.string().nullish(),message:R.string(),param:R.string().nullish()}),y96=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"]),g96=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"]);u96=K0(()=>e(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:NW1.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:NW1.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:LW1.nullish()}),DW1,OW1,R.object({type:R.literal("web_search_call"),id:R.string(),status:R.string()}),BW1,R.object({type:R.literal("file_search_call"),id:R.string()}),jW1,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(),Si.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:LW1.nullish()}),DW1,OW1,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()}),jW1,BW1,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(),Si.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()}),f96,b96,R.object({type:R.string()}).loose().refine(($)=>!h96($),{message:"Known response chunk failed schema validation"}).transform(($)=>({type:"unknown_chunk",message:$.type}))]))),Of$=K0(()=>e(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()}),jW1,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:LW1.nullish()}),DW1,OW1,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()}),BW1,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(),Si.optional()))})])).optional(),service_tier:R.string().nullish(),reasoning:R.object({context:R.string().nullish()}).nullish(),incomplete_details:R.object({reason:R.string()}).nullish(),usage:NW1.nullish()})));i96=QW1.object({itemId:QW1.string().nullish(),reasoningEncryptedContent:QW1.string().nullish()}),p96=["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"],Bk9=["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",...p96],ux$=K0(()=>e(G4.object({conversation:G4.string().nullish(),include:G4.array(G4.enum(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),includeWebSearchSources:G4.boolean().optional(),instructions:G4.string().nullish(),logprobs:G4.union([G4.boolean(),G4.number().min(1).max(jf$)]).optional(),maxToolCalls:G4.number().nullish(),metadata:G4.any().nullish(),parallelToolCalls:G4.boolean().nullish(),previousResponseId:G4.string().nullish(),promptCacheKey:G4.string().nullish(),promptCacheOptions:G4.object({mode:G4.enum(["implicit","explicit"]).optional(),ttl:G4.literal("30m").optional()}).optional(),promptCacheRetention:G4.enum(["in_memory","24h"]).nullish(),reasoningEffort:G4.string().nullish(),reasoningEffortUpdate:G4.enum(["low","medium","high","xhigh","max"]).optional(),reasoningMode:G4.enum(["standard","pro"]).optional(),reasoningContext:G4.enum(["auto","current_turn","all_turns"]).optional(),reasoningSummary:G4.string().nullish(),safetyIdentifier:G4.string().nullish(),serviceTier:G4.enum(["auto","flex","priority","fast","ultrafast","default"]).nullish(),store:G4.boolean().nullish(),passThroughUnsupportedFiles:G4.boolean().optional(),strictJsonSchema:G4.boolean().nullish(),textVerbosity:G4.enum(["low","medium","high"]).nullish(),truncation:G4.enum(["auto","disabled"]).nullish(),user:G4.string().nullish(),systemMessageMode:G4.enum(["system","developer","remove"]).optional(),forceReasoning:G4.boolean().optional(),contextManagement:G4.array(G4.object({type:G4.literal("compaction"),compactThreshold:G4.number()})).nullish(),compactionTrigger:G4.boolean().optional(),allowedTools:G4.object({toolNames:G4.array(G4.string()).min(1),mode:G4.enum(["auto","required"]).optional()}).optional()})));wf$={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},Ef$=class ${constructor(Z,Q){this.specificationVersion="v4",this.supportedUrls=wf$,this.modelId=Z,this.config=Q}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,l96(Z.config))}get provider(){return this.config.provider}static async prepareRequest({modelId:Z,config:Q,options:{maxOutputTokens:X,temperature:Y,stopSequences:J,topP:G,topK:W,presencePenalty:K,frequencyPenalty:H,seed:F,prompt:U,reasoning:N,providerOptions:B,tools:D,toolChoice:O,responseFormat:j}}){var w,E,z,A,P,T,q,f,S,V,u,g,l,h;let i=[],H0=Xf$(Z);if(W!=null)i.push({type:"unsupported",feature:"topK"});if(F!=null)i.push({type:"unsupported",feature:"seed"});if(K!=null)i.push({type:"unsupported",feature:"presencePenalty"});if(H!=null)i.push({type:"unsupported",feature:"frequencyPenalty"});if(J!=null)i.push({type:"unsupported",feature:"stopSequences"});let R0=Q.provider.includes("azure")?"azure":"openai",Y0=await x$({provider:R0,providerOptions:B,schema:ux$});if(Y0==null&&R0!=="openai")Y0=await x$({provider:"openai",providerOptions:B,schema:ux$});let N0=(w=Y0==null?void 0:Y0.reasoningEffort)!=null?w:rL(N)?N:void 0;if(N0!=null&&H0.supportedReasoningEfforts!=null&&!H0.supportedReasoningEfforts.includes(N0))i.push({type:"unsupported",feature:"reasoningEffort",details:`${Z} only supports the following reasoning efforts: ${H0.supportedReasoningEfforts.join(", ")}`}),N0=void 0;let n=(Y0==null?void 0:Y0.reasoningSummary)!==void 0?Y0.reasoningSummary:N0!=null&&N0!=="none"?"detailed":void 0,t=(E=Y0==null?void 0:Y0.forceReasoning)!=null?E:H0.isReasoningModel;if((Y0==null?void 0:Y0.conversation)&&(Y0==null?void 0:Y0.previousResponseId))i.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});let a=pd({tools:D,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"}}),s=new Set,X0=new Set,{tools:p0,toolChoice:v0,toolWarnings:H1}=await n96({tools:D,toolChoice:O,allowedTools:(z=Y0==null?void 0:Y0.allowedTools)!=null?z:void 0,toolNameMapping:a,customProviderToolNames:s,outputSchemaToolNames:X0,supportsAsyncToolCalling:H0.supportsAsyncToolCalling}),{input:c0,warnings:w0}=await d96({prompt:U,toolNameMapping:a,systemMessageMode:(A=Y0==null?void 0:Y0.systemMessageMode)!=null?A:t?"developer":H0.systemMessageMode,providerOptionsName:R0,explicitMessageItemType:Q.explicitMessageItemType,fileIdPrefixes:Q.fileIdPrefixes,passThroughUnsupportedFiles:(P=Y0==null?void 0:Y0.passThroughUnsupportedFiles)!=null?P:!1,store:(T=Y0==null?void 0:Y0.store)!=null?T:!0,hasConversation:(Y0==null?void 0:Y0.conversation)!=null,hasPreviousResponseId:(Y0==null?void 0:Y0.previousResponseId)!=null,hasLocalShellTool:$1("openai.local_shell"),hasShellTool:$1("openai.shell"),hasApplyPatchTool:$1("openai.apply_patch"),hasComputerTool:$1("openai.computer"),toolSearchToolName:n0("openai.tool_search"),customProviderToolNames:s.size>0?s:void 0,outputSchemaToolNames:X0.size>0?X0:void 0});i.push(...w0);let z0=Y0==null?void 0:Y0.reasoningEffortUpdate,m0=z0==null||H0.supportsConfigurationUpdate&&(Y0==null?void 0:Y0.reasoningMode)!=="pro"&&(Y0==null?void 0:Y0.contextManagement)==null&&(Y0==null?void 0:Y0.truncation)!=="auto";if(z0!=null&&!m0)i.push({type:"unsupported",feature:"reasoningEffortUpdate",details:!H0.supportsConfigurationUpdate?"reasoningEffortUpdate is only supported by GPT-6 and later models":"reasoningEffortUpdate requires standard reasoning mode without automatic compaction or automatic truncation"});else if(z0!=null)c0.unshift({type:"configuration_update",reasoning:{effort:z0}});if(Y0==null?void 0:Y0.compactionTrigger)c0.push({type:"compaction_trigger"});let j1=(q=Y0==null?void 0:Y0.strictJsonSchema)!=null?q:!0,Y1=(j==null?void 0:j.type)==="json"&&j.schema!=null?I80(j.schema):void 0;if(Y1!=null)i.push(...Y1.warnings);let f0=Y0==null?void 0:Y0.include;function i0(O1){if(f0==null)f0=[O1];else if(!f0.includes(O1))f0=[...f0,O1]}function n0(O1){var g$;return(g$=D==null?void 0:D.find((o$)=>o$.type==="provider"&&o$.id===O1))==null?void 0:g$.name}function $1(O1){return n0(O1)!=null}let G0=typeof(Y0==null?void 0:Y0.logprobs)==="number"?Y0==null?void 0:Y0.logprobs:(Y0==null?void 0:Y0.logprobs)===!0?jf$:void 0;if(G0)i0("message.output_text.logprobs");let Q0=(f=D==null?void 0:D.find((O1)=>O1.type==="provider"&&(O1.id==="openai.web_search"||O1.id==="openai.web_search_preview")))==null?void 0:f.name;if(Q0&&Q.supportsWebSearchSourcesInclude!==!1&&(Y0==null?void 0:Y0.includeWebSearchSources)!==!1)i0("web_search_call.action.sources");if($1("openai.code_interpreter"))i0("code_interpreter_call.outputs");let F0=Y0==null?void 0:Y0.store;if(F0===!1&&t)i0("reasoning.encrypted_content");let U0={model:Z,input:c0,temperature:Y,top_p:G,max_output_tokens:X,...((j==null?void 0:j.type)==="json"||(Y0==null?void 0:Y0.textVerbosity))&&{text:{...(j==null?void 0:j.type)==="json"&&{format:Y1!=null?{type:"json_schema",strict:j1,name:(S=j.name)!=null?S:"response",description:j.description,schema:Y1.schema}:{type:"json_object"}},...(Y0==null?void 0:Y0.textVerbosity)&&{verbosity:Y0.textVerbosity}}},conversation:Y0==null?void 0:Y0.conversation,max_tool_calls:Y0==null?void 0:Y0.maxToolCalls,metadata:Y0==null?void 0:Y0.metadata,parallel_tool_calls:Y0==null?void 0:Y0.parallelToolCalls,previous_response_id:Y0==null?void 0:Y0.previousResponseId,store:F0,user:Y0==null?void 0:Y0.user,instructions:Y0==null?void 0:Y0.instructions,service_tier:Y0==null?void 0:Y0.serviceTier,include:f0,prompt_cache_key:Y0==null?void 0:Y0.promptCacheKey,prompt_cache_options:Y0==null?void 0:Y0.promptCacheOptions,prompt_cache_retention:Y0==null?void 0:Y0.promptCacheRetention,safety_identifier:Y0==null?void 0:Y0.safetyIdentifier,top_logprobs:G0,truncation:Y0==null?void 0:Y0.truncation,...(Y0==null?void 0:Y0.contextManagement)&&{context_management:Y0.contextManagement.map((O1)=>({type:O1.type,compact_threshold:O1.compactThreshold}))},...t&&(N0!=null||n!=null||(Y0==null?void 0:Y0.reasoningMode)!=null||(Y0==null?void 0:Y0.reasoningContext)!=null)&&{reasoning:{...N0!=null&&{effort:N0},...n!=null&&{summary:n},...(Y0==null?void 0:Y0.reasoningMode)!=null&&{mode:Y0.reasoningMode},...(Y0==null?void 0:Y0.reasoningContext)!=null&&{context:Y0.reasoningContext}}}};if(H0.supportsConfigurationUpdate&&U0.prompt_cache_retention!=null)U0.prompt_cache_retention=void 0,i.push({type:"unsupported",feature:"promptCacheRetention",details:"promptCacheRetention is not supported by GPT-6 and later models; use promptCacheOptions instead"});if(t){if(!(N0==="none"&&H0.supportsNonReasoningParameters)){if(U0.temperature!=null)U0.temperature=void 0,i.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"});if(U0.top_p!=null)U0.top_p=void 0,i.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"});if(H0.supportedReasoningEfforts!=null&&(U0.top_logprobs!=null||((V=U0.include)==null?void 0:V.includes("message.output_text.logprobs")))){U0.top_logprobs=void 0;let O1=(u=U0.include)==null?void 0:u.filter((g$)=>g$!=="message.output_text.logprobs");U0.include=O1!=null&&O1.length>0?O1:void 0,i.push({type:"unsupported",feature:"logprobs",details:"logprobs is not supported for reasoning models"})}}}else{if((Y0==null?void 0:Y0.reasoningEffort)!=null)i.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"});if((Y0==null?void 0:Y0.reasoningSummary)!=null)i.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"});if((Y0==null?void 0:Y0.reasoningMode)!=null)i.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"});if((Y0==null?void 0:Y0.reasoningContext)!=null)i.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})}if((Y0==null?void 0:Y0.serviceTier)==="flex"&&!H0.supportsFlexProcessing)i.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete U0.service_tier;if(((Y0==null?void 0:Y0.serviceTier)==="priority"||(Y0==null?void 0:Y0.serviceTier)==="fast")&&!H0.supportsPriorityProcessing)i.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 U0.service_tier;let I0=(h=(l=(g=D==null?void 0:D.find((O1)=>O1.type==="provider"&&O1.id==="openai.shell"))==null?void 0:g.args)==null?void 0:l.environment)==null?void 0:h.type,q0=I0==="containerAuto"||I0==="containerReference";return{webSearchToolName:Q0,args:{...U0,tools:p0,tool_choice:v0},warnings:[...i,...H1],store:F0,toolNameMapping:a,providerOptionsName:R0,isShellProviderExecuted:q0}}getArgs(Z){return $.prepareRequest({modelId:this.modelId,config:this.config,options:Z})}async doGenerate(Z){var Q,X,Y,J,G,W,K,H,F,U,N,B,D,O,j,w,E,z,A,P,T,q,f,S,V,u,g,l,h,i,H0,R0,Y0,N0;let{args:n,warnings:t,webSearchToolName:a,toolNameMapping:s,providerOptionsName:X0,isShellProviderExecuted:p0}=await this.getArgs(Z),v0=this.config.url({path:"/responses",modelId:this.modelId}),H1=mx$(Z.prompt),{responseHeaders:c0,value:w0,rawValue:z0}=await Q$({url:v0,headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:n,failedResponseHandler:m9,successfulResponseHandler:R1(Of$),abortSignal:Z.abortSignal,fetch:this.config.fetch});if(w0.error)throw new w8({message:w0.error.message,url:v0,requestBodyValues:n,statusCode:400,responseHeaders:c0,responseBody:z0,isRetryable:!1});if(w0.output==null){let G0=(Y=w0.incomplete_details)==null?void 0:Y.reason;throw new w8({message:G0?`Responses API returned no output (${G0})`:"Responses API returned no output",url:v0,requestBodyValues:n,statusCode:500,responseHeaders:c0,responseBody:z0,isRetryable:!1})}let m0=[],j1=[],Y1=(G=(J=Z.tools)==null?void 0:J.filter((G0)=>G0.type==="function"))!=null?G:[],f0=!1,i0=[];for(let G0 of w0.output)switch(G0.type){case"reasoning":{if(G0.summary.length===0)G0.summary.push({type:"summary_text",text:""});for(let Q0 of G0.summary)m0.push({type:"reasoning",text:Q0.text,providerMetadata:{[X0]:{itemId:G0.id,reasoningEncryptedContent:(W=G0.encrypted_content)!=null?W:null}}});break}case"image_generation_call":{m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName("image_generation"),result:{result:G0.result}});break}case"tool_search_call":{let Q0=(K=G0.call_id)!=null?K:G0.id,F0=G0.execution==="server";if(F0)i0.push(Q0);m0.push({type:"tool-call",toolCallId:Q0,toolName:s.toCustomToolName("tool_search"),input:JSON.stringify({arguments:G0.arguments,call_id:G0.call_id}),...F0?{providerExecuted:!0}:{},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"tool_search_output":{let Q0=(F=(H=G0.call_id)!=null?H:i0.shift())!=null?F:G0.id;m0.push({type:"tool-result",toolCallId:Q0,toolName:s.toCustomToolName("tool_search"),result:{tools:G0.tools},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"local_shell_call":{m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:s.toCustomToolName("local_shell"),input:JSON.stringify({action:G0.action}),providerMetadata:{[X0]:{itemId:G0.id}}});break}case"shell_call":{m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:s.toCustomToolName("shell"),input:JSON.stringify({action:{commands:G0.action.commands}}),...p0&&{providerExecuted:!0},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"shell_call_output":{m0.push({type:"tool-result",toolCallId:G0.call_id,toolName:s.toCustomToolName("shell"),result:{output:G0.output.map((Q0)=>({stdout:Q0.stdout,stderr:Q0.stderr,outcome:Q0.outcome.type==="exit"?{type:"exit",exitCode:Q0.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(let Q0 of G0.content){if(((N=(U=Z.providerOptions)==null?void 0:U[X0])==null?void 0:N.logprobs)&&Q0.logprobs)j1.push(Q0.logprobs);let F0={itemId:G0.id,...G0.phase!=null&&{phase:G0.phase},...Q0.annotations.length>0&&{annotations:Q0.annotations}};m0.push({type:"text",text:Q0.text,providerMetadata:{[X0]:F0}});for(let U0 of Q0.annotations)if(U0.type==="url_citation")m0.push({type:"source",sourceType:"url",id:(O=(D=(B=this.config).generateId)==null?void 0:D.call(B))!=null?O:J4(),url:U0.url,title:U0.title});else if(U0.type==="file_citation")m0.push({type:"source",sourceType:"document",id:(E=(w=(j=this.config).generateId)==null?void 0:w.call(j))!=null?E:J4(),mediaType:"text/plain",title:U0.filename,filename:U0.filename,providerMetadata:{[X0]:{type:U0.type,fileId:U0.file_id,index:U0.index}}});else if(U0.type==="container_file_citation")m0.push({type:"source",sourceType:"document",id:(P=(A=(z=this.config).generateId)==null?void 0:A.call(z))!=null?P:J4(),mediaType:"text/plain",title:U0.filename,filename:U0.filename,providerMetadata:{[X0]:{type:U0.type,fileId:U0.file_id,containerId:U0.container_id}}});else if(U0.type==="file_path")m0.push({type:"source",sourceType:"document",id:(f=(q=(T=this.config).generateId)==null?void 0:q.call(T))!=null?f:J4(),mediaType:"application/octet-stream",title:U0.file_id,filename:U0.file_id,providerMetadata:{[X0]:{type:U0.type,fileId:U0.file_id,index:U0.index}}})}break}case"function_call":{f0=!0;let Q0=await bx$({toolCall:{toolCallId:G0.call_id,toolName:G0.name,input:G0.arguments},tools:Y1,providerOptionsName:X0,itemId:G0.id});if(Q0!=null){m0.push(...Q0);break}m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:G0.name,input:G0.arguments,providerMetadata:{[X0]:{itemId:G0.id,...G0.async!=null&&{async:G0.async},...G0.namespace!=null&&{namespace:G0.namespace},...G0.caller!=null&&{caller:G0.caller.type==="program"?{type:"program",callerId:G0.caller.caller_id}:G0.caller}}}});break}case"program":{m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:s.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:G0.code,fingerprint:G0.fingerprint}),providerExecuted:!0,providerMetadata:{[X0]:{itemId:G0.id}}});break}case"program_output":{m0.push({type:"tool-result",toolCallId:G0.call_id,toolName:s.toCustomToolName("programmatic_tool_calling"),result:{result:G0.result,status:G0.status},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"custom_tool_call":{f0=!0;let Q0=s.toCustomToolName(G0.name);m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:Q0,input:JSON.stringify(G0.input),providerMetadata:{[X0]:{itemId:G0.id,...G0.async!=null&&{async:G0.async}}}});break}case"web_search_call":{m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName(a!=null?a:"web_search"),input:JSON.stringify({}),providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName(a!=null?a:"web_search"),result:PW1(G0.action)});break}case"mcp_call":{let Q0=G0.approval_request_id!=null?(S=H1[G0.approval_request_id])!=null?S:G0.id:G0.id,F0=`mcp.${G0.name}`;m0.push({type:"tool-call",toolCallId:Q0,toolName:F0,input:G0.arguments,providerExecuted:!0,dynamic:!0}),m0.push({type:"tool-result",toolCallId:Q0,toolName:F0,result:{type:"call",serverLabel:G0.server_label,name:G0.name,arguments:G0.arguments,...G0.output!=null?{output:G0.output}:{},...G0.error!=null?{error:G0.error}:{}},providerMetadata:{[X0]:{itemId:G0.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{let Q0=(V=G0.approval_request_id)!=null?V:G0.id,F0=(l=(g=(u=this.config).generateId)==null?void 0:g.call(u))!=null?l:J4(),U0=`mcp.${G0.name}`;m0.push({type:"tool-call",toolCallId:F0,toolName:U0,input:G0.arguments,providerExecuted:!0,dynamic:!0}),m0.push({type:"tool-approval-request",approvalId:Q0,toolCallId:F0});break}case"computer_call":{if(G0.call_id==null){m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:G0.status}});break}f0=!0;let Q0=s.toCustomToolName("computer");m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:Q0,input:JSON.stringify(dx$(G0)),providerMetadata:{[X0]:{itemId:G0.id}}});break}case"file_search_call":{m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName("file_search"),result:{queries:G0.queries,results:(i=(h=G0.results)==null?void 0:h.map((Q0)=>({attributes:Q0.attributes,fileId:Q0.file_id,filename:Q0.filename,score:Q0.score,text:Q0.text})))!=null?i:null}});break}case"code_interpreter_call":{m0.push({type:"tool-call",toolCallId:G0.id,toolName:s.toCustomToolName("code_interpreter"),input:JSON.stringify({code:G0.code,containerId:G0.container_id}),providerExecuted:!0}),m0.push({type:"tool-result",toolCallId:G0.id,toolName:s.toCustomToolName("code_interpreter"),result:{outputs:G0.outputs}});break}case"apply_patch_call":{f0=!0,m0.push({type:"tool-call",toolCallId:G0.call_id,toolName:s.toCustomToolName("apply_patch"),input:JSON.stringify({callId:G0.call_id,operation:G0.operation}),providerMetadata:{[X0]:{itemId:G0.id}}});break}case"compaction":{m0.push({type:"custom",kind:"openai.compaction",providerMetadata:{[X0]:{type:"compaction",itemId:G0.id,encryptedContent:G0.encrypted_content}}});break}}let n0={[X0]:{responseId:w0.id,...j1.length>0?{logprobs:j1}:{},...typeof w0.service_tier==="string"?{serviceTier:w0.service_tier}:{},...((H0=w0.reasoning)==null?void 0:H0.context)!=null?{reasoningContext:w0.reasoning.context}:{}}},$1=w0.usage;return{content:m0,finishReason:{unified:KD0({finishReason:(R0=w0.incomplete_details)==null?void 0:R0.reason,hasFunctionCall:f0}),raw:(N0=(Y0=w0.incomplete_details)==null?void 0:Y0.reason)!=null?N0:void 0},usage:UW1($1),request:{body:n},response:{id:w0.id,timestamp:new Date(w0.created_at*1000),modelId:w0.model,headers:c0,body:z0},providerMetadata:n0,warnings:t}}async doStream(Z){var Q,X,Y,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:D,value:O}=await Q$({url:B,headers:k1((X=(Q=this.config).headers)==null?void 0:X.call(Q),Z.headers),body:{...G,stream:!0},failedResponseHandler:m9,successfulResponseHandler:lX(u96),abortSignal:Z.abortSignal,fetch:this.config.fetch}),j=await MW1({stream:O,getError:(t)=>nx$(t)||ix$(t)&&t.response.error!=null?t:void 0,isOutputChunk:OZ6,isAcceptedChunk:DZ6,url:B,requestBodyValues:G,responseHeaders:D}),w=this,E=mx$(Z.prompt),z=(J=(Y=Z.tools)==null?void 0:Y.filter((t)=>t.type==="function"))!=null?J:[],A=new Map,P={unified:"other",raw:void 0},T=void 0,q=[],f=null,S={},V=[],u,g=!1,l={},h={},i=({itemId:t,outputIndex:a})=>{var s;return a==null?t:(s=h[a])!=null?s:t},H0,R0,Y0=[],N0=!1;return{stream:j.pipeThrough(new TransformStream({start(t){t.enqueue({type:"stream-start",warnings:W})},transform(t,a){var s,X0,p0,v0,H1,c0,w0,z0,m0,j1,Y1,f0,i0,n0,$1,G0,Q0,F0,U0,I0,q0,O1,g$,o$,T8,B8,I5,m8,s6,v9,r0,P1,m$,i1,N$,u8,K5,D4,W$,S8,X8,O$,O9,VQ,gZ;if(Z.includeRawChunks)a.enqueue({type:"raw",rawValue:t.rawValue});if(!t.success){let C0=ZZ6(t.rawValue)?QZ6({value:t.rawValue,cause:t.error,url:B,requestBodyValues:G,responseHeaders:D}):t.error;N0=!0,P={unified:"error",raw:void 0},a.enqueue({type:"error",error:C0});return}let Z0=t.value;if(px$(Z0)){if(Z0.item.type==="function_call"){let C0=EW1({toolName:Z0.item.name,tools:z});if(S[Z0.output_index]={toolName:Z0.item.name,toolCallId:Z0.item.call_id,suppressInputStreaming:C0,bufferedInputDeltas:C0?[]:void 0,async:Z0.item.async},!C0)a.enqueue({type:"tool-input-start",id:Z0.item.call_id,toolName:Z0.item.name})}else if(Z0.item.type==="custom_tool_call"){let C0=H.toCustomToolName(Z0.item.name);S[Z0.output_index]={toolName:C0,toolCallId:Z0.item.call_id,async:Z0.item.async},a.enqueue({type:"tool-input-start",id:Z0.item.call_id,toolName:C0})}else if(Z0.item.type==="web_search_call")S[Z0.output_index]={toolName:H.toCustomToolName(K!=null?K:"web_search"),toolCallId:Z0.item.id},a.enqueue({type:"tool-input-start",id:Z0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),providerExecuted:!0}),a.enqueue({type:"tool-input-end",id:Z0.item.id}),a.enqueue({type:"tool-call",toolCallId:Z0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(Z0.item.type==="computer_call"){let C0=(s=Z0.item.call_id)!=null?s:Z0.item.id;S[Z0.output_index]={toolName:H.toCustomToolName("computer"),toolCallId:C0},a.enqueue({type:"tool-input-start",id:C0,toolName:H.toCustomToolName("computer")})}else if(Z0.item.type==="code_interpreter_call")S[Z0.output_index]={toolName:H.toCustomToolName("code_interpreter"),toolCallId:Z0.item.id,codeInterpreter:{containerId:Z0.item.container_id}},a.enqueue({type:"tool-input-start",id:Z0.item.id,toolName:H.toCustomToolName("code_interpreter"),providerExecuted:!0}),a.enqueue({type:"tool-input-delta",id:Z0.item.id,delta:`{"containerId":"${Z0.item.container_id}","code":"`});else if(Z0.item.type==="file_search_call")a.enqueue({type:"tool-call",toolCallId:Z0.item.id,toolName:H.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(Z0.item.type==="image_generation_call")a.enqueue({type:"tool-call",toolCallId:Z0.item.id,toolName:H.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(Z0.item.type==="tool_search_call"){let C0=Z0.item.id,C1=H.toCustomToolName("tool_search"),d8=Z0.item.execution==="server";if(S[Z0.output_index]={toolName:C1,toolCallId:C0,toolSearchExecution:(X0=Z0.item.execution)!=null?X0:"server"},d8)a.enqueue({type:"tool-input-start",id:C0,toolName:C1,providerExecuted:!0})}else if(Z0.item.type==="tool_search_output");else if(Z0.item.type==="mcp_call"||Z0.item.type==="mcp_list_tools"||Z0.item.type==="mcp_approval_request");else if(Z0.item.type==="apply_patch_call"){let{call_id:C0,operation:C1}=Z0.item;if(S[Z0.output_index]={toolName:H.toCustomToolName("apply_patch"),toolCallId:C0,applyPatch:{hasDiff:C1.type==="delete_file",endEmitted:C1.type==="delete_file"}},a.enqueue({type:"tool-input-start",id:C0,toolName:H.toCustomToolName("apply_patch")}),C1.type==="delete_file"){let d8=JSON.stringify({callId:C0,operation:C1});a.enqueue({type:"tool-input-delta",id:C0,delta:d8}),a.enqueue({type:"tool-input-end",id:C0})}else a.enqueue({type:"tool-input-delta",id:C0,delta:`{"callId":"${XR(C0)}","operation":{"type":"${XR(C1.type)}","path":"${XR(C1.path)}","diff":"`})}else if(Z0.item.type==="shell_call")S[Z0.output_index]={toolName:H.toCustomToolName("shell"),toolCallId:Z0.item.call_id};else if(Z0.item.type==="shell_call_output");else if(Z0.item.type==="message")h[Z0.output_index]=Z0.item.id,V.splice(0,V.length),u=(p0=Z0.item.phase)!=null?p0:void 0,a.enqueue({type:"text-start",id:Z0.item.id,providerMetadata:{[U]:{itemId:Z0.item.id,...Z0.item.phase!=null&&{phase:Z0.item.phase}}}});else if(px$(Z0)&&Z0.item.type==="reasoning")h[Z0.output_index]=Z0.item.id,l[Z0.item.id]={encryptedContent:Z0.item.encrypted_content,summaryParts:{0:"active"}},a.enqueue({type:"reasoning-start",id:`${Z0.item.id}:0`,providerMetadata:{[U]:{itemId:Z0.item.id,reasoningEncryptedContent:(v0=Z0.item.encrypted_content)!=null?v0:null}}})}else if(YZ6(Z0)){if(Z0.item.type==="message"){let C0=i({itemId:Z0.item.id,outputIndex:Z0.output_index}),C1=(H1=Z0.item.phase)!=null?H1:u;u=void 0,a.enqueue({type:"text-end",id:C0,providerMetadata:{[U]:{itemId:C0,...C1!=null&&{phase:C1},...V.length>0&&{annotations:V}}}}),h[Z0.output_index]=void 0}else if(Z0.item.type==="function_call"){let C0=Z0.item,C1=S[Z0.output_index];S[Z0.output_index]=void 0,g=!0;let d8=(c0=C1==null?void 0:C1.suppressInputStreaming)!=null?c0:EW1({toolName:C0.name,tools:z}),x=()=>{var d;if(d8){a.enqueue({type:"tool-input-start",id:C0.call_id,toolName:C0.name});let p=(d=C1==null?void 0:C1.bufferedInputDeltas)!=null?d:[];if(p.length>0)for(let M of p)a.enqueue({type:"tool-input-delta",id:C0.call_id,delta:M});else if(C0.arguments.length>0)a.enqueue({type:"tool-input-delta",id:C0.call_id,delta:C0.arguments})}a.enqueue({type:"tool-input-end",id:C0.call_id,...C0.namespace!=null&&{providerMetadata:{[U]:{namespace:C0.namespace}}}}),a.enqueue({type:"tool-call",toolCallId:C0.call_id,toolName:C0.name,input:C0.arguments,providerMetadata:{[U]:{itemId:C0.id,...C0.async!=null?{async:C0.async}:(C1==null?void 0:C1.async)!=null?{async:C1.async}:{},...C0.namespace!=null&&{namespace:C0.namespace},...C0.caller!=null&&{caller:C0.caller.type==="program"?{type:"program",callerId:C0.caller.caller_id}:C0.caller}}}})};if(!d8){x();return}return bx$({toolCall:{toolCallId:C0.call_id,toolName:C0.name,input:C0.arguments},tools:z,providerOptionsName:U,itemId:C0.id}).then((d)=>{if(d==null){x();return}for(let p of d)a.enqueue({type:"tool-input-start",id:p.toolCallId,toolName:p.toolName}),a.enqueue({type:"tool-input-delta",id:p.toolCallId,delta:p.input}),a.enqueue({type:"tool-input-end",id:p.toolCallId}),a.enqueue(p)})}else if(Z0.item.type==="program")a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("programmatic_tool_calling"),input:JSON.stringify({code:Z0.item.code,fingerprint:Z0.item.fingerprint}),providerExecuted:!0,providerMetadata:{[U]:{itemId:Z0.item.id}}});else if(Z0.item.type==="program_output")a.enqueue({type:"tool-result",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("programmatic_tool_calling"),result:{result:Z0.item.result,status:Z0.item.status},providerMetadata:{[U]:{itemId:Z0.item.id}}});else if(Z0.item.type==="custom_tool_call"){let C0=S[Z0.output_index];S[Z0.output_index]=void 0,g=!0;let C1=H.toCustomToolName(Z0.item.name);a.enqueue({type:"tool-input-end",id:Z0.item.call_id}),a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:C1,input:JSON.stringify(Z0.item.input),providerMetadata:{[U]:{itemId:Z0.item.id,...Z0.item.async!=null?{async:Z0.item.async}:(C0==null?void 0:C0.async)!=null?{async:C0.async}:{}}}})}else if(Z0.item.type==="web_search_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName(K!=null?K:"web_search"),result:PW1(Z0.item.action)});else if(Z0.item.type==="computer_call"){if(S[Z0.output_index]=void 0,Z0.item.call_id==null){a.enqueue({type:"tool-input-end",id:Z0.item.id}),a.enqueue({type:"tool-call",toolCallId:Z0.item.id,toolName:H.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:Z0.item.status}});return}g=!0;let C0=H.toCustomToolName("computer"),C1=JSON.stringify(dx$(Z0.item));a.enqueue({type:"tool-input-delta",id:Z0.item.call_id,delta:C1}),a.enqueue({type:"tool-input-end",id:Z0.item.call_id}),a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:C0,input:C1,providerMetadata:{[U]:{itemId:Z0.item.id}}})}else if(Z0.item.type==="file_search_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName("file_search"),result:{queries:Z0.item.queries,results:(z0=(w0=Z0.item.results)==null?void 0:w0.map((C0)=>({attributes:C0.attributes,fileId:C0.file_id,filename:C0.filename,score:C0.score,text:C0.text})))!=null?z0:null}});else if(Z0.item.type==="code_interpreter_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName("code_interpreter"),result:{outputs:Z0.item.outputs}});else if(Z0.item.type==="image_generation_call")a.enqueue({type:"tool-result",toolCallId:Z0.item.id,toolName:H.toCustomToolName("image_generation"),result:{result:Z0.item.result}});else if(Z0.item.type==="tool_search_call"){let C0=S[Z0.output_index],C1=Z0.item.execution==="server";if(C0!=null){let d8=C1?C0.toolCallId:(m0=Z0.item.call_id)!=null?m0:Z0.item.id;if(C1)Y0.push(d8);else a.enqueue({type:"tool-input-start",id:d8,toolName:C0.toolName});a.enqueue({type:"tool-input-end",id:d8}),a.enqueue({type:"tool-call",toolCallId:d8,toolName:C0.toolName,input:JSON.stringify({arguments:Z0.item.arguments,call_id:C1?null:d8}),...C1?{providerExecuted:!0}:{},providerMetadata:{[U]:{itemId:Z0.item.id}}})}S[Z0.output_index]=void 0}else if(Z0.item.type==="tool_search_output"){let C0=(Y1=(j1=Z0.item.call_id)!=null?j1:Y0.shift())!=null?Y1:Z0.item.id;a.enqueue({type:"tool-result",toolCallId:C0,toolName:H.toCustomToolName("tool_search"),result:{tools:Z0.item.tools},providerMetadata:{[U]:{itemId:Z0.item.id}}})}else if(Z0.item.type==="mcp_call"){S[Z0.output_index]=void 0;let C0=(f0=Z0.item.approval_request_id)!=null?f0:void 0,C1=C0!=null?(n0=(i0=A.get(C0))!=null?i0:E[C0])!=null?n0:Z0.item.id:Z0.item.id,d8=`mcp.${Z0.item.name}`;a.enqueue({type:"tool-call",toolCallId:C1,toolName:d8,input:Z0.item.arguments,providerExecuted:!0,dynamic:!0}),a.enqueue({type:"tool-result",toolCallId:C1,toolName:d8,result:{type:"call",serverLabel:Z0.item.server_label,name:Z0.item.name,arguments:Z0.item.arguments,...Z0.item.output!=null?{output:Z0.item.output}:{},...Z0.item.error!=null?{error:Z0.item.error}:{}},providerMetadata:{[U]:{itemId:Z0.item.id}}})}else if(Z0.item.type==="mcp_list_tools")S[Z0.output_index]=void 0;else if(Z0.item.type==="apply_patch_call"){let C0=S[Z0.output_index];if((C0==null?void 0:C0.applyPatch)&&!C0.applyPatch.endEmitted&&Z0.item.operation.type!=="delete_file"){if(!C0.applyPatch.hasDiff)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:XR(Z0.item.operation.diff)});a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:'"}}'}),a.enqueue({type:"tool-input-end",id:C0.toolCallId}),C0.applyPatch.endEmitted=!0}if(C0&&Z0.item.status==="completed")g=!0,a.enqueue({type:"tool-call",toolCallId:C0.toolCallId,toolName:H.toCustomToolName("apply_patch"),input:JSON.stringify({callId:Z0.item.call_id,operation:Z0.item.operation}),providerMetadata:{[U]:{itemId:Z0.item.id}}});S[Z0.output_index]=void 0}else if(Z0.item.type==="mcp_approval_request"){S[Z0.output_index]=void 0;let C0=(Q0=(G0=($1=w.config).generateId)==null?void 0:G0.call($1))!=null?Q0:J4(),C1=(F0=Z0.item.approval_request_id)!=null?F0:Z0.item.id;A.set(C1,C0);let d8=`mcp.${Z0.item.name}`;a.enqueue({type:"tool-call",toolCallId:C0,toolName:d8,input:Z0.item.arguments,providerExecuted:!0,dynamic:!0}),a.enqueue({type:"tool-approval-request",approvalId:C1,toolCallId:C0})}else if(Z0.item.type==="local_shell_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:Z0.item.action.command,timeoutMs:Z0.item.action.timeout_ms,user:Z0.item.action.user,workingDirectory:Z0.item.action.working_directory,env:Z0.item.action.env}}),providerMetadata:{[U]:{itemId:Z0.item.id}}});else if(Z0.item.type==="shell_call")S[Z0.output_index]=void 0,a.enqueue({type:"tool-call",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("shell"),input:JSON.stringify({action:{commands:Z0.item.action.commands}}),...N&&{providerExecuted:!0},providerMetadata:{[U]:{itemId:Z0.item.id}}});else if(Z0.item.type==="shell_call_output")a.enqueue({type:"tool-result",toolCallId:Z0.item.call_id,toolName:H.toCustomToolName("shell"),result:{output:Z0.item.output.map((C0)=>({stdout:C0.stdout,stderr:C0.stderr,outcome:C0.outcome.type==="exit"?{type:"exit",exitCode:C0.outcome.exit_code}:{type:"timeout"}}))}});else if(Z0.item.type==="reasoning"){let C0=i({itemId:Z0.item.id,outputIndex:Z0.output_index}),C1=l[C0];if(C1!=null){let d8=Object.entries(C1.summaryParts).filter(([x,d])=>d==="active"||d==="can-conclude").map(([x])=>x);for(let x of d8)a.enqueue({type:"reasoning-end",id:`${C0}:${x}`,providerMetadata:{[U]:{itemId:C0,reasoningEncryptedContent:(U0=Z0.item.encrypted_content)!=null?U0:null}}});delete l[C0]}h[Z0.output_index]=void 0}else if(Z0.item.type==="compaction")a.enqueue({type:"custom",kind:"openai.compaction",providerMetadata:{[U]:{type:"compaction",itemId:Z0.item.id,encryptedContent:Z0.item.encrypted_content}}})}else if(WZ6(Z0)){let C0=S[Z0.output_index];if(C0!=null)if(C0.suppressInputStreaming)(I0=C0.bufferedInputDeltas)==null||I0.push(Z0.delta);else a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:Z0.delta})}else if(KZ6(Z0)){let C0=S[Z0.output_index];if(C0!=null)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:Z0.delta})}else if(NZ6(Z0)){let C0=S[Z0.output_index];if(C0==null?void 0:C0.applyPatch)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:XR(Z0.delta)}),C0.applyPatch.hasDiff=!0}else if(BZ6(Z0)){let C0=S[Z0.output_index];if((C0==null?void 0:C0.applyPatch)&&!C0.applyPatch.endEmitted){if(!C0.applyPatch.hasDiff)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:XR(Z0.diff)}),C0.applyPatch.hasDiff=!0;a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:'"}}'}),a.enqueue({type:"tool-input-end",id:C0.toolCallId}),C0.applyPatch.endEmitted=!0}}else if(HZ6(Z0))a.enqueue({type:"tool-result",toolCallId:Z0.item_id,toolName:H.toCustomToolName("image_generation"),result:{result:Z0.partial_image_b64},preliminary:!0});else if(FZ6(Z0)){let C0=S[Z0.output_index];if(C0!=null)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:XR(Z0.delta)})}else if(UZ6(Z0)){let C0=S[Z0.output_index];if(C0!=null)a.enqueue({type:"tool-input-delta",id:C0.toolCallId,delta:'"}'}),a.enqueue({type:"tool-input-end",id:C0.toolCallId}),a.enqueue({type:"tool-call",toolCallId:C0.toolCallId,toolName:H.toCustomToolName("code_interpreter"),input:JSON.stringify({code:Z0.code,containerId:C0.codeInterpreter.containerId}),providerExecuted:!0})}else if(GZ6(Z0))f=Z0.response.id,a.enqueue({type:"response-metadata",id:Z0.response.id,timestamp:new Date(Z0.response.created_at*1000),modelId:Z0.response.model});else if($Z6(Z0)){let C0=i({itemId:Z0.item_id,outputIndex:Z0.output_index});if(a.enqueue({type:"text-delta",id:C0,delta:Z0.delta}),((O1=(q0=Z.providerOptions)==null?void 0:q0[U])==null?void 0:O1.logprobs)&&Z0.logprobs)q.push(Z0.logprobs)}else if(Z0.type==="response.reasoning_summary_part.added"){let C0=i({itemId:Z0.item_id,outputIndex:Z0.output_index});if(Z0.summary_index>0){let C1=l[C0];if(C1!=null){C1.summaryParts[Z0.summary_index]="active";for(let d8 of Object.keys(C1.summaryParts))if(C1.summaryParts[d8]==="can-conclude")a.enqueue({type:"reasoning-end",id:`${C0}:${d8}`,providerMetadata:{[U]:{itemId:C0}}}),C1.summaryParts[d8]="concluded";a.enqueue({type:"reasoning-start",id:`${C0}:${Z0.summary_index}`,providerMetadata:{[U]:{itemId:C0,reasoningEncryptedContent:(g$=C1.encryptedContent)!=null?g$:null}}})}}}else if(Z0.type==="response.reasoning_summary_text.delta"){let C0=i({itemId:Z0.item_id,outputIndex:Z0.output_index});a.enqueue({type:"reasoning-delta",id:`${C0}:${Z0.summary_index}`,delta:Z0.delta,providerMetadata:{[U]:{itemId:C0}}})}else if(Z0.type==="response.reasoning_summary_part.done"){let C0=i({itemId:Z0.item_id,outputIndex:Z0.output_index}),C1=l[C0];if(C1!=null)if(F)a.enqueue({type:"reasoning-end",id:`${C0}:${Z0.summary_index}`,providerMetadata:{[U]:{itemId:C0}}}),C1.summaryParts[Z0.summary_index]="concluded";else C1.summaryParts[Z0.summary_index]="can-conclude"}else if(JZ6(Z0)){if(!N0)P={unified:KD0({finishReason:(o$=Z0.response.incomplete_details)==null?void 0:o$.reason,hasFunctionCall:g}),raw:(B8=(T8=Z0.response.incomplete_details)==null?void 0:T8.reason)!=null?B8:void 0};if(T=(I5=Z0.response.usage)!=null?I5:void 0,typeof Z0.response.service_tier==="string")H0=Z0.response.service_tier;if(((m8=Z0.response.reasoning)==null?void 0:m8.context)!=null)R0=Z0.response.reasoning.context}else if(ix$(Z0)){let C0=(s6=Z0.response.incomplete_details)==null?void 0:s6.reason;if(P={unified:C0?KD0({finishReason:C0,hasFunctionCall:g}):"error",raw:C0!=null?C0:"error"},T=(v9=Z0.response.usage)!=null?v9:void 0,((r0=Z0.response.reasoning)==null?void 0:r0.context)!=null)R0=Z0.response.reasoning.context;if(!N0&&Z0.response.error!=null){N0=!0;let C1={type:"response.failed",sequence_number:Z0.sequence_number,response:{error:Z0.response.error,incomplete_details:Z0.response.incomplete_details,service_tier:Z0.response.service_tier}};a.enqueue({type:"error",error:(P1=M80(C1))!=null?P1:C1})}}else if(LZ6(Z0)){if(V.push(Z0.annotation),Z0.annotation.type==="url_citation")a.enqueue({type:"source",sourceType:"url",id:(N$=(i1=(m$=w.config).generateId)==null?void 0:i1.call(m$))!=null?N$:J4(),url:Z0.annotation.url,title:Z0.annotation.title});else if(Z0.annotation.type==="file_citation")a.enqueue({type:"source",sourceType:"document",id:(D4=(K5=(u8=w.config).generateId)==null?void 0:K5.call(u8))!=null?D4:J4(),mediaType:"text/plain",title:Z0.annotation.filename,filename:Z0.annotation.filename,providerMetadata:{[U]:{type:Z0.annotation.type,fileId:Z0.annotation.file_id,index:Z0.annotation.index}}});else if(Z0.annotation.type==="container_file_citation")a.enqueue({type:"source",sourceType:"document",id:(X8=(S8=(W$=w.config).generateId)==null?void 0:S8.call(W$))!=null?X8:J4(),mediaType:"text/plain",title:Z0.annotation.filename,filename:Z0.annotation.filename,providerMetadata:{[U]:{type:Z0.annotation.type,fileId:Z0.annotation.file_id,containerId:Z0.annotation.container_id}}});else if(Z0.annotation.type==="file_path")a.enqueue({type:"source",sourceType:"document",id:(VQ=(O9=(O$=w.config).generateId)==null?void 0:O9.call(O$))!=null?VQ:J4(),mediaType:"application/octet-stream",title:Z0.annotation.file_id,filename:Z0.annotation.file_id,providerMetadata:{[U]:{type:Z0.annotation.type,fileId:Z0.annotation.file_id,index:Z0.annotation.index}}})}else if(nx$(Z0))N0=!0,P={unified:"error",raw:"error"},a.enqueue({type:"error",error:(gZ=M80(Z0))!=null?gZ:Z0})},flush(t){var a;for(let X0 of Object.values(S)){if(!(X0==null?void 0:X0.suppressInputStreaming))continue;t.enqueue({type:"tool-input-start",id:X0.toolCallId,toolName:X0.toolName});for(let p0 of(a=X0.bufferedInputDeltas)!=null?a:[])t.enqueue({type:"tool-input-delta",id:X0.toolCallId,delta:p0})}let s={[U]:{responseId:f,...q.length>0?{logprobs:q}:{},...H0!==void 0?{serviceTier:H0}:{},...R0!==void 0?{reasoningContext:R0}:{}}};t.enqueue({type:"finish",finishReason:P,usage:UW1(T),providerMetadata:s})}})),request:{body:G},response:{headers:D}}}};ox$=K0(()=>e(i6.object({inputFileExpiresAfter:i6.number().int().min(3600).max(2592000).optional()})));YW1=K0(()=>e(zf$())),EZ6=K0(()=>e(i6.object({custom_id:i6.string(),response:i6.object({status_code:i6.number(),request_id:i6.string().nullish(),body:i6.unknown()}).nullish(),error:i6.object({code:i6.string(),message:i6.string()}).nullish()}))),zZ6=K0(()=>e(i6.object({data:i6.array(zf$()),has_more:i6.boolean(),last_id:i6.string().nullish()})));AZ6=new Set(["openai.code_interpreter","openai.custom","openai.file_search","openai.web_search","openai.web_search_preview"]);VZ6=A6.strictObject({type:A6.string(),responseEvent:A6.string().optional()}).refine(($)=>$.type==="response.event"===($.responseEvent!==void 0),"responseEvent is required for response.event and forbidden for other event types."),kZ6=A6.strictObject({client:A6.strictObject({dataChannel:A6.strictObject({allowedClientEvents:A6.union([A6.literal("all"),A6.array(A6.string())]).optional(),allowedServerEvents:A6.union([A6.literal("all"),A6.array(VZ6)]).optional()})}).optional(),delegation:A6.strictObject({type:A6.literal("client")}).nullable().optional(),input:A6.array(A6.discriminatedUnion("role",[A6.strictObject({type:A6.literal("message"),role:A6.enum(["developer","user"]),content:A6.tuple([A6.strictObject({type:A6.literal("input_text"),text:A6.string()})])}),A6.strictObject({type:A6.literal("message"),role:A6.literal("assistant"),content:A6.tuple([A6.strictObject({type:A6.enum(["text","output_text"]),text:A6.string()})])})])).max(128).optional(),store:A6.boolean().optional(),voice:A6.strictObject({id:A6.string().min(1)}).optional()}),ax$=JK.union([JK.strictObject({type:JK.literal("audio/pcm"),rate:JK.union([JK.literal(16000),JK.literal(24000)])}),JK.strictObject({type:JK.enum(["audio/pcma","audio/pcmu"]),rate:JK.literal(8000)})]);RW1=l$.object({id:l$.string().min(1)}),CZ6=RW1.extend({delegation:l$.object({type:l$.enum(["client","responses"])}).nullish()}),rx$=l$.object({seconds:l$.number().nonnegative()}),sx$={delta:l$.string(),start_ms:l$.number().nonnegative(),end_ms:l$.number().nonnegative()},HD0={client_event_id:l$.string().nullish()},JW1={...HD0,start_ms:l$.number().nonnegative(),end_ms:l$.number().nonnegative()},Pf$=l$.discriminatedUnion("type",[l$.object({type:l$.literal("session.started"),session:CZ6}),l$.object({type:l$.literal("session.closed"),session:RW1.nullish(),usage:rx$,reason:l$.string()}),l$.object({type:l$.literal("session.usage.updated"),usage:rx$,context_window:l$.object({usage_ratio:l$.number().min(0).max(1)}).nullish()}),l$.object({type:l$.literal("session.output_audio.delta"),delta:l$.string()}),l$.object({type:l$.literal("session.input_transcript.delta"),...sx$}),l$.object({type:l$.literal("session.output_transcript.delta"),...sx$}),l$.object({type:l$.literal("session.delegation.created"),offset_ms:l$.number().nonnegative().nullish(),delegation:l$.object({id:l$.string().min(1),target:l$.enum(["client","responses"]).nullish(),response_id:l$.string().min(1).nullish()})}),l$.object({type:l$.literal("session.updated"),session:RW1,...HD0}),l$.object({type:l$.literal("session.input_audio.muted"),...HD0}),l$.object({type:l$.literal("session.input_audio.unmuted"),...HD0}),l$.object({type:l$.literal("session.instructions.appended"),...JW1}),l$.object({type:l$.literal("session.thinking.appended"),...JW1}),l$.object({type:l$.literal("session.commentary.appended"),...JW1}),l$.object({type:l$.literal("error"),error:l$.object({message:l$.string(),code:l$.string().nullish(),client_event_id:l$.string().nullish()})})]),SZ6=new Set(Pf$.options.map(($)=>$.shape.type.value)),_Z6=l$.object({type:l$.string()});bZ6=YR.object({session:YR.object({id:YR.string().min(1)}),transport:YR.object({type:YR.literal("webrtc"),sdp:YR.string().min(1)})});uZ6=["gpt-live-1"];mZ6=K0(()=>e(GW1.object({instructions:GW1.string().nullish(),speed:GW1.number().min(0.25).max(4).default(1).nullish()}))),dZ6=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({text:Z,voice:Q="alloy",outputFormat:X="mp3",speed:Y,instructions:J,language:G,providerOptions:W}){let K=[],H=await x$({provider:"openai",providerOptions:W,schema:mZ6}),F={model:this.modelId,input:Z,voice:Q,response_format:"mp3",speed:Y,instructions:J};if(X)if(["mp3","opus","aac","flac","wav","pcm"].includes(X))F.response_format=X;else K.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${X}. 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,X,Y,J,G;let W=(Y=(X=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:X.call(Q))!=null?Y:new Date,{requestBody:K,warnings:H}=await this.getArgs(Z),{value:F,responseHeaders:U,rawValue:N}=await Q$({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:k1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),body:K,failedResponseHandler:m9,successfulResponseHandler:XC$(),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}}}},iZ6=K0(()=>e(X5.object({text:X5.string(),language:X5.string().nullish(),duration:X5.number().nullish(),words:X5.array(X5.object({word:X5.string(),start:X5.number(),end:X5.number()})).nullish(),segments:X5.array(X5.union([X5.object({id:X5.number(),seek:X5.number(),start:X5.number(),end:X5.number(),text:X5.string(),tokens:X5.array(X5.number()),temperature:X5.number(),avg_logprob:X5.number(),compression_ratio:X5.number(),no_speech_prob:X5.number()}),X5.object({type:X5.literal("transcript.text.segment"),id:X5.string(),start:X5.number(),end:X5.number(),text:X5.string(),speaker:X5.string()})])).nullish()}))),$f$=K0(()=>e(U7.object({include:U7.array(U7.string()).optional(),language:U7.string().optional(),prompt:U7.string().optional(),temperature:U7.number().min(0).max(1).default(0).optional(),timestampGranularities:U7.array(U7.enum(["word","segment"])).default(["segment"]).optional(),responseFormat:U7.enum(["json","verbose_json","diarized_json"]).optional(),chunkingStrategy:U7.union([U7.literal("auto"),U7.object({type:U7.literal("server_vad"),threshold:U7.number().min(0).max(1).optional(),prefixPaddingMs:U7.number().int().min(0).optional(),silenceDurationMs:U7.number().int().min(0).optional()})]).optional(),streaming:U7.object({delay:U7.enum(["minimal","low","medium","high","xhigh"]).optional(),include:U7.array(U7.string()).optional()}).optional()})));Qf$={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"},pZ6=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async getArgs({audio:Z,mediaType:Q,providerOptions:X}){var Y,J;let G=[],W=await x$({provider:"openai",providerOptions:X,schema:$f$}),K=new FormData,H=Z instanceof Uint8Array?new Blob([Z]):new Blob([a9(Z)]);K.append("model",this.modelId);let F=nk$(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=(Y=W==null?void 0:W.chunkingStrategy)!=null?Y:U?"auto":void 0;if(W){let B=["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId),D={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[O,j]of Object.entries(D))if(j!=null)if(Array.isArray(j))for(let w of j)K.append(`${O}[]`,String(w));else K.append(O,String(j))}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,X,Y,J,G,W,K,H,F,U,N;if(Zf$(this.modelId))throw new Z$({functionality:`non-streaming transcription with ${this.modelId}`});let B=(Y=(X=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:X.call(Q))!=null?Y:new Date,{formData:D,warnings:O}=await this.getArgs(Z),{value:j,responseHeaders:w,rawValue:E}=await rW({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:k1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),formData:D,failedResponseHandler:m9,successfulResponseHandler:R1(iZ6),abortSignal:Z.abortSignal,fetch:this.config.fetch}),z=j.language!=null&&j.language in Qf$?Qf$[j.language]:void 0,A=(W=j.segments)==null?void 0:W.flatMap((P)=>("speaker"in P)?[{text:P.text,startSecond:P.start,endSecond:P.end,speaker:P.speaker}]:[]);return{text:j.text,segments:(U=(F=(K=j.segments)==null?void 0:K.map((P)=>({text:P.text,startSecond:P.start,endSecond:P.end})))!=null?F:(H=j.words)==null?void 0:H.map((P)=>({text:P.word,startSecond:P.start,endSecond:P.end})))!=null?U:[],language:z,durationInSeconds:(N=j.duration)!=null?N:void 0,warnings:O,response:{timestamp:B,modelId:this.modelId,headers:w,body:E},...A!=null&&A.length>0&&{providerMetadata:{openai:{segments:A}}}}}async doStream(Z){var Q,X,Y,J,G,W,K;if(!Zf$(this.modelId))throw new Z$({functionality:`streaming transcription with ${this.modelId}`});let H=(Y=(X=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:X.call(Q))!=null?Y:new Date,F=await x$({provider:"openai",providerOptions:Z.providerOptions,schema:$f$}),U=[],N=(G=(J=Z.providerOptions)==null?void 0:J.openai)!=null?G:{};for(let O of["include","prompt","temperature","timestampGranularities"])if(N[O]!=null)U.push({type:"unsupported",feature:`providerOptions.openai.${O}`,details:`OpenAI streaming transcription does not support ${O}.`});let B=k1((K=(W=this.config).headers)==null?void 0:K.call(W),Z.headers),D=tZ6({modelId:this.modelId,inputAudioFormat:Z.inputAudioFormat,providerOptions:F});return{request:{body:D},response:{timestamp:H,modelId:this.modelId},stream:nZ6({webSocket:this.config.webSocket,url:bB0(this.config.url({path:"/realtime?intent=transcription",modelId:this.modelId})),headers:B,sessionUpdate:D,language:F==null?void 0:F.language,warnings:U,audio:Z.audio,abortSignal:Z.abortSignal,includeRawChunks:Z.includeRawChunks})}}};rZ6=K0(()=>e(aZ6.object({}))),sZ6=class ${constructor(Z,Q){this.modelId=Z,this.config=Q,this.specificationVersion="v4"}static[U4](Z){return g4({modelId:Z.modelId,config:Z.config})}static[N4](Z){return new $(Z.modelId,Z.config)}get provider(){return this.config.provider}async doStream(Z){var Q,X,Y,J,G;if(Z.targetLanguage==null)throw new c8({argument:"targetLanguage",message:`targetLanguage is required for translation model '${this.modelId}'.`});let W=(Y=(X=(Q=this.config._internal)==null?void 0:Q.currentDate)==null?void 0:X.call(Q))!=null?Y:new Date;await x$({provider:"openai",providerOptions:Z.providerOptions,schema:rZ6});let K=[];if(Z76(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=k1((G=(J=this.config).headers)==null?void 0:G.call(J),Z.headers),F=$76({targetLanguage:Z.targetLanguage});return{request:{body:F},response:{timestamp:W,modelId:this.modelId},stream:eZ6({webSocket:this.config.webSocket,url:bB0(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})}}};X76=K0(()=>e(M3.object({id:M3.string(),name:M3.string().nullish(),description:M3.string().nullish(),default_version:M3.string().nullish(),latest_version:M3.string().nullish(),created_at:M3.number(),updated_at:M3.number().nullish()}))),uk9=K0(()=>e(M3.object({id:M3.string(),version:M3.string().nullish(),name:M3.string().nullish(),description:M3.string().nullish()})));lk9=JR()});function W76($){return lU("LLMAPI listModels",`${Af$}/models`,{headers:{Authorization:`Bearer ${$||"not-needed"}`},signal:AbortSignal.timeout(15000)})}var Af$="https://api.llmapi.ai/v1",G76="https://llmapi.ai/wp-content/uploads/2026/01/Frame-2085662993.png",Rf$;var qf$=L(()=>{UD0();IA();Rf$={info:{id:"llmapi",name:"LLMAPI",description:"One API key, 400+ models across every provider",logo:G76},supportedMethods:["api-key"],create($){let Z=JR({apiKey:$||"not-needed",baseURL:Af$,name:"llmapi"}),Q=Object.assign((...X)=>Z.chat(...X),Z,{languageModel:Z.chat});return{info:this.info,aiSdk:Q,async listModels(){let X=await W76($);if(!X.ok)await uX("LLMAPI listModels",X);let{data:Y}=await cU("LLMAPI listModels",X);return Y.filter((J)=>typeof J.id==="string"&&J.id.length>0).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:OB0(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 K76($,Z){return lU("OpenAI-compatible listModels",`${$}/models`,{headers:Z,signal:AbortSignal.timeout(15000)})}function H76($){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 F76="https://assets.decocache.com/decocms/d138aa7e-5b8c-4821-9e64-6aff40df2cdc/ChatGPT_logo.svg",Mf$;var If$=L(()=>{UD0();IA();Mf$={info:{id:"openai-compatible",name:"OpenAI Compatible",description:"Custom OpenAI-compatible endpoint",logo:F76},supportedMethods:["api-key"],create($){let{baseUrl:Z,apiKey:Q}=H76($),X=JR({baseURL:Z,apiKey:Q||"not-needed",name:"openai-compatible"}),Y=Object.assign((...J)=>X.chat(...J),X,{languageModel:X.chat});return{info:this.info,aiSdk:Y,async listModels(){let J={};if(Q)J.Authorization=`Bearer ${Q}`;let G=await K76(Z,J);if(!G.ok)await uX("OpenAI-compatible listModels",G);return(await cU("OpenAI-compatible listModels",G)).data.filter((K)=>typeof K.id==="string"&&K.id.length>0).map((K)=>({providerId:"openai-compatible",modelId:K.id,title:K.id,description:K.owned_by?`Owned by ${K.owned_by}`:null,logo:null,capabilities:[],limits:null,costs:null}))}}}}});function d9(){return{...P0().aiGatewayEnabled&&{deco:GE},anthropic:Pv$,google:Px$,openrouter:jB0,llmapi:Rf$,"openai-compatible":Mf$}}var GK=L(()=>{Tv$();Tx$();qf$();If$();iY1();gd();X$()});function B76($,Z,Q){om($,Z,Q)}function L76($,Z,Q){am($,Z,Q)}function kW1($){V80.delete($)}async function CW1($,Z){if(!P0().plansEnabled)return null;if(!P0().aiGatewayEnabled)return null;let Q=V80.get(Z);if(Q&&Date.now()-Q.at<kf$)return Q.value;let X=VW1.get(Z);if(X)return X;let Y=D76($,Z,Q).finally(()=>{VW1.delete(Z)});return VW1.set(Z,Y),Y}async function D76($,Z,Q){let X=d9().deco;if(!X?.getEntitlements)return null;let Y=$.auth.user?.id??$.auth.apiKey?.userId;if(!Y)return Vf$(Z,Q);try{let J=await lQ(Y),{features:G,usage:W,modelPins:K,credits:H}=await X.getEntitlements(J,Z);if(!G||typeof G!=="object")throw new VA(502);let F={features:G,modelPins:K,usageState:W?.state??null,creditsUsd:H?.remainingUsd??null};return B76(V80,Z,F),L76(V80,N76,kf$),F}catch(J){let G=J instanceof VA&&J.isDefinitive,W=J instanceof VA&&J.isDormant,K={organizationId:Z,servedStale:!!Q,status:J instanceof VA?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 Vf$(Z,Q)}}function Vf$($,Z){if(Z&&Date.now()-Z.at>=U76)return V80.delete($),null;return Z?.value??null}async function QG($,Z,Q){let X=await CW1($,Z);return Cf$(X?.features??null,Q)}function Cf$($,Z){if(!$)return!0;return $[Z]===!0}function O76($,Z){if($!=="exhausted")return!1;return!(Z!==null&&Z>0)}async function I3($,Z,Q){let X=await CW1($,Z);if(!O76(X?.usageState??null,X?.creditsUsd??null))return;throw new ND0(`${Q} is paused: this organization has used its monthly AI allowance`)}async function Sf$($,Z,Q){let X=await CW1($,Z);if(!X)return null;if(Cf$(X.features,"model_choice"))return null;return X.modelPins?.[Q]??null}var LN,kf$=60000,U76=600000,V80,N76=1e4,VW1,ND0;var YF=L(()=>{vH();GK();gd();qH();X$();LN=class LN extends HQ{feature;code="feature_not_in_plan";constructor($,Z){super($);this.feature=Z;this.name="FeatureNotInPlanError"}};V80=new Map;VW1=new Map;ND0=class ND0 extends HQ{code="ai_budget_exhausted";constructor($){super($);this.name="AiBudgetExhaustedError"}}});function _f$($){let{ctx:Z,toolName:Q,organizationId:X,durationMs:Y,isError:J}=$,G={"tool.name":Q,"organization.id":X,status:J?"error":"success"};Z.meter.createHistogram("studio_tool.execution.duration",{description:"Duration of in-process Studio tool executions in milliseconds",unit:"ms"}).record(Y,G),Z.meter.createCounter("studio_tool.execution.count",{description:"Number of in-process Studio tool executions"}).add(1,G)}import{SpanStatusCode as vf$}from"@opentelemetry/api";function m($){return{...$,execute:async(Z,Q)=>{let X=performance.now(),Y=!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&&!KV$($.name)&&await kB0(Q.db,G))throw new t10(`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 QG(Q,G,$.requiresFeature))throw new LN(`${$.name} needs the ${$.requiresFeature} feature, which this organization's plan does not include`,$.requiresFeature);if($.requiresAiBudget&&G)await I3(Q,G,$.name);let W=await $.handler(Z,Q);return J.setStatus({code:vf$.OK}),W}catch(G){throw Y=!0,J.setStatus({code:vf$.ERROR,message:G.message}),J.recordException(G),G}finally{_f$({ctx:Q,toolName:$.name,organizationId:Q.organization?.id??"system",durationMs:performance.now()-X,isError:Y}),J.end()}}))}}}var _0=L(()=>{SA();YF()});function W0($){if(!$.organization)throw Error("This operation requires organization scope");return $.organization}function t0($){return $.auth.user?.id??$.auth.apiKey?.userId}function GR($){return!!($.auth.user||$.auth.apiKey)}function o($){if(!GR($))throw Error("Authentication required")}import{z as L4}from"zod";var ff$,xf$=1000,j76=500,bf$,yf$,gf$,hf$,uf$,lf$,cf$,mf$,df$,if$;var _i=L(()=>{ff$=L4.record(L4.string(),L4.array(L4.string())),bf$=L4.record(L4.string(),L4.array(L4.string()).max(j76)).refine(($)=>Object.keys($).length<=xf$,{message:`Permissions cannot grant more than ${xf$} resources`}),yf$=L4.object({id:L4.string().describe("Unique identifier for the API key"),name:L4.string().describe("Human-readable name for the API key"),userId:L4.string().describe("ID of the user who owns this API key"),permissions:ff$.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:L4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:L4.string().datetime().describe("When the API key was created (ISO 8601)")}),gf$=L4.object({name:L4.string().min(1).max(64).describe("Human-readable name for the API key"),permissions:bf$.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:L4.number().positive().optional().describe("Expiration time in seconds. If not provided, key never expires."),metadata:L4.record(L4.string(),L4.unknown()).optional().describe("Additional metadata to store with the API key")}),hf$=L4.object({id:L4.string().describe("Unique identifier for the API key"),name:L4.string().describe("Human-readable name for the API key"),key:L4.string().describe("The actual API key value. STORE THIS SECURELY - it will not be shown again!"),permissions:ff$.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:L4.string().datetime().nullable().optional().describe("Expiration date of the API key (ISO 8601)"),createdAt:L4.string().datetime().describe("When the API key was created (ISO 8601)")}),uf$=L4.object({}),lf$=L4.object({items:L4.array(yf$).describe("List of API keys (without key values)")}),cf$=L4.object({keyId:L4.string().describe("ID of the API key to update"),name:L4.string().min(1).max(64).optional().describe("New name for the API key"),permissions:bf$.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:L4.record(L4.string(),L4.unknown()).optional().describe("New metadata. Replaces existing metadata.")}),mf$=L4.object({item:yf$.describe("The updated API key (without key value)")}),df$=L4.object({keyId:L4.string().describe("ID of the API key to delete")}),if$=L4.object({success:L4.boolean().describe("Whether the deletion was successful"),keyId:L4.string().describe("ID of the deleted API key")})});var SW1;var pf$=L(()=>{F6();_0();_i();SW1=m({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:gf$,outputSchema:hf$,handler:async($,Z)=>{o(Z),await Z.access.check();let Q=await Z.boundAuth.apiKey.create({name:$.name,permissions:$.permissions,expiresIn:$.expiresIn,metadata:{...$.metadata,organization:Z.organization}}),X=Q.expiresAt?Q.expiresAt instanceof Date?Q.expiresAt.toISOString():Q.expiresAt:null,Y=Q.createdAt instanceof Date?Q.createdAt.toISOString():Q.createdAt,J=t0(Z);if(J)h1.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:!!X}});return{id:Q.id,name:Q.name??$.name,key:Q.key,permissions:Q.permissions??{},expiresAt:X,createdAt:Y}}})});var _W1;var nf$=L(()=>{F6();_0();_i();_W1=m({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:df$,outputSchema:if$,handler:async($,Z)=>{o(Z),await Z.access.check();let Q=t0(Z);if(!Q)throw Error("User ID required to delete API key");let Y=(await Z.boundAuth.apiKey.list())?.find((K)=>K.id===$.keyId);if(!Y)throw Error("API key not found");let G=Y.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)h1.capture({distinctId:Q,event:"api_key_deleted",groups:{organization:W},properties:{key_id:$.keyId,organization_id:W}});return{success:!0,keyId:$.keyId}}})});var vW1;var tf$=L(()=>{_0();_i();vW1=m({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:uf$,outputSchema:lf$,handler:async($,Z)=>{o(Z),await Z.access.check();let Q=await Z.boundAuth.apiKey.list(),X=Z.organization?.id;return{items:(Q??[]).filter((J)=>{return J.metadata?.organization?.id===X}).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 xW1;var of$=L(()=>{_0();_i();xW1=m({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:cf$,outputSchema:mf$,handler:async($,Z)=>{if(o(Z),await Z.access.check(),!t0(Z))throw Error("User ID required to update API key");let Y=(await Z.boundAuth.apiKey.list())?.find((H)=>H.id===$.keyId);if(!Y)throw Error(`API key not found: ${$.keyId}`);let G=Y.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 af$=L(()=>{pf$();nf$();tf$();of$();_i()});function FD($){let Z=$.trim();if(!Z)return{ok:!1,error:"Enter a website URL."};let Q=E76.test(Z),X=z76.test(Z),Y=P76.test(Z);if(Q&&!X&&!Y)return{ok:!1,error:"Use an HTTP or HTTPS website URL."};let J=X?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||!T76.test(K)))return{ok:!1,error:"Enter a valid website URL."};return G.protocol="https:",{ok:!0,value:G.origin}}function fW1($){if(!$)return null;let Z=FD($);return Z.ok?new URL(Z.value).hostname:null}var E76,z76,P76,T76;var vi=L(()=>{E76=/^[a-zA-Z][a-zA-Z\d+.-]*:/,z76=/^[a-zA-Z][a-zA-Z\d+.-]*:\/\//,P76=/^[^\s/:?#]+\.[^\s/:?#]+:\d+(?:[/?#]|$)/,T76=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i});import{z as XG}from"zod";function BD0($){return{repository_id:$.repositoryId,provider:$.provider,host:$.host,path:$.path,default_branch:$.defaultBranch??null,web_url:$.webUrl??null}}function rf$($){let Z=A76.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 LD0($){return $.provider==="github"&&$.host.toLowerCase()==="github.com"?$.path:null}var bW1,A76;var DD0=L(()=>{bW1=XG.object({repositoryId:XG.string().min(1),provider:XG.enum(["github","gitlab","bitbucket"]),host:XG.string().min(1),path:XG.string().min(1),defaultBranch:XG.string().nullable().optional(),webUrl:XG.string().nullable().optional()}),A76=XG.object({repository_id:XG.string().min(1),provider:XG.enum(["github","gitlab","bitbucket"]),host:XG.string().min(1),path:XG.string().min(1),default_branch:XG.string().nullable().optional(),web_url:XG.string().nullable().optional()})});import{z as OQ}from"zod";function WK($){if($.baseUrl)return $.baseUrl.replace(/\/+$/,"");return(($.settings??P0()).reportsInternalApiUrl??R76).replace(/\/+$/,"")}function ef$($={}){return`${WK($)}/api/v2/mcp`}function xE($){let Z=$.apiKey??($.settings??P0()).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 k80($){return new URL($).hostname}function M76($){return $==="ownership_unverified"||$==="already_claimed_by_other_org"}function I76($,Z={}){switch($){case"ownership_unverified":{let Q=Z.email?`O e-mail ${Z.email}`:"Este e-mail",X=Z.domain?` ${Z.domain}`:" este site";return`${Q} n\xE3o tem permiss\xE3o para reivindicar${X}. 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 V76($){let Z=await xi($);return M76(Z?.error)?Z.error:"unknown"}async function xi($){let Z=await $.text().catch(()=>"");if(!Z)return;try{return JSON.parse(Z)}catch{return}}async function jD0($){let Z=`Reports auth failed with status ${$.status}.`,Q=await $.text().catch(()=>"");if(!Q)return Z;try{let X=JSON.parse(Q),Y=typeof X.error==="string"?X.error:typeof X.message==="string"?X.message:null;return Y?`Reports auth failed: ${Y}.`:Z}catch{return Z}}async function Zb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/upgrade`,W=await Y(G,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.orgName?{name:$.orgName}:{},...$.email?{email:$.email}:{},...$.reportUrl?{report_url:$.reportUrl}:{}}),signal:AbortSignal.timeout(OD0)});if(!W.ok){let H=await V76(W);throw new $b$(H,{email:$.email,domain:J})}let K=q76.safeParse(await xi(W));if(!K.success)throw Error("Reports auth response did not include a token.");return{authorizationToken:K.data.token}}async function Qb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/bindings`,W=await Y(G,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,provider:$.provider,resource_id:$.resourceId}),signal:AbortSignal.timeout(OD0)});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=sf$.safeParse(await xi(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 jD0(W));let K=sf$.safeParse(await xi(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 Xb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/run`,W=await Y(G,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId,...$.repository?{repository:BD0($.repository)}:{},...$.githubRepositoryPath?{github_repo:$.githubRepositoryPath}:{}}),signal:AbortSignal.timeout(OD0)});if(W.status===409)return{triggered:!1,reason:"not_upgraded"};if(!W.ok)throw Error(await jD0(W));return{triggered:!0}}async function Yb$($,Z,Q){try{return await O8(async()=>{let X=await $(Z,{...Q,signal:AbortSignal.timeout(OD0)});if(X.status>=500||X.status===429)throw new yW1(await jD0(X));return X},{maxAttempts:3,minTimeout:200,maxTimeout:2000,multiplier:2,jitter:1,isRetriable:(X)=>X instanceof yW1})}catch(X){if(X instanceof k5&&X.cause instanceof Error)throw X.cause;throw X}}async function Jb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/connections/status?org_id=${encodeURIComponent($.orgId)}`,W=await Yb$(Y,G,{method:"GET",headers:{Authorization:`Bearer ${X}`}});if(W.status===404||W.status===409)return{providers:{},claimed:!1};if(!W.ok)throw Error(await jD0(W));let K=k76.safeParse(await xi(W));return{providers:K.success?K.data.providers:{},claimed:!0}}async function Gb$($,Z={}){let Q=WK(Z),X=xE(Z),Y=Z.fetchImpl??fetch,J=k80($.siteUrl),G=`${Q}/api/v2/internal/diagnostics/${encodeURIComponent(J)}/unlink`,W=await Yb$(Y,G,{method:"POST",headers:{Authorization:`Bearer ${X}`,"Content-Type":"application/json"},body:JSON.stringify({org_id:$.orgId})});if(!W.ok)throw Error(`Reports unlink failed with status ${W.status}.`);let K=C76.safeParse(await xi(W));if(!K.success)throw Error("Reports unlink response did not say whether it unlinked.");return K.data}var R76,OD0=15000,q76,sf$,$b$,yW1,k76,C76;var UD=L(()=>{r8();$8();DD0();X$();R76=new URL(tF$).origin,q76=OQ.object({token:OQ.string().min(1)}),sf$=OQ.object({binding:OQ.object({resource_id:OQ.string(),evidence:OQ.string()}).optional(),reason:OQ.string().optional(),detail:OQ.string().optional()});$b$=class $b$ extends Error{code;constructor($,Z={}){super(I76($,Z));this.name="ReportsClaimError",this.code=$}};yW1=class yW1 extends Error{};k76=OQ.object({providers:OQ.record(OQ.string(),OQ.object({connected:OQ.boolean(),via:OQ.enum(["oauth","sa"]).nullable(),resource:OQ.string().nullable()}))});C76=OQ.object({unlinked:OQ.boolean(),reason:OQ.string().optional()})});import{z as V3}from"zod";var S76,_76,gW1;var Wb$=L(()=>{vi();_0();UD();S76=V3.object({siteUrl:V3.string().min(1).describe("Website URL of the store being bound."),provider:V3.enum(["ga4","gsc"]).describe("Which Google source to bind: ga4 (Analytics) or gsc (Search Console)."),resourceId:V3.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/).")}),_76=V3.discriminatedUnion("ok",[V3.object({ok:V3.literal(!0),resourceId:V3.string(),evidence:V3.string()}),V3.object({ok:V3.literal(!1),reason:V3.string(),detail:V3.string()})]),gW1=m({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:S76,outputSchema:_76,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check("REPORTS_BIND","COMMERCE_DISCOVERY_BIND");let X=FD($.siteUrl);if(!X.ok)throw Error(X.error);return Qb$({siteUrl:X.value,orgId:Q.id,provider:$.provider,resourceId:$.resourceId.trim()})}})});import{z as DN}from"zod";var v76,x76,hW1;var Kb$=L(()=>{vi();_0();UD();v76=DN.object({siteUrl:DN.string().min(1).describe("Website URL of the store to inspect.")}),x76=DN.object({providers:DN.record(DN.string(),DN.object({connected:DN.boolean(),via:DN.enum(["oauth","sa"]).nullable(),resource:DN.string().nullable()})),claimed:DN.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.")}),hW1=m({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:v76,outputSchema:x76,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check("REPORTS_CONNECTION_STATUS","COMMERCE_DISCOVERY_CONNECTION_STATUS");let X=FD($.siteUrl);if(!X.ok)throw Error(X.error);return Jb$({siteUrl:X.value,orgId:Q.id})}})});import{z as fE}from"zod";function g76($){let Z=y76.safeParse($),Q=Z.success?Z.data:void 0,X=(Q?rf$(Q.repository):void 0)??void 0,Y=Q&&typeof Q.github_repo==="string"&&Q.github_repo.length>0?Q.github_repo:void 0;return{repository:X??void 0,githubRepositoryPath:(X?LD0(X):Y)??void 0}}var f76,b76,y76,uW1;var Hb$=L(()=>{r8();DD0();vi();_0();UD();f76=fE.object({siteUrl:fE.string().min(1).describe("Website URL to run the diagnostic for.")}),b76=fE.object({triggered:fE.boolean(),reason:fE.string().optional()}),y76=fE.object({repository:fE.unknown().optional(),github_repo:fE.string().optional()}).passthrough().nullable().optional();uW1=m({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:f76,outputSchema:b76,requiresFeature:"diagnostic_enriched",requiresAiBudget:!0,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check("REPORTS_RUN","COMMERCE_DISCOVERY_RUN");let X=FD($.siteUrl);if(!X.ok)throw Error(X.error);let Y=K4.REPORTS(Q.id),J=await Z.storage.connections.findById(Y,Q.id),{repository:G,githubRepositoryPath:W}=g76(J?.configuration_state);return Xb$({siteUrl:X.value,orgId:Q.id,repository:G,githubRepositoryPath:W})}})});import{z as P5}from"zod";var h76,C80,u76,l76,c76,m76,Fb$,Ub$,ON,S80;var Nb$=L(()=>{h76=["github","gitlab","bitbucket"],C80=P5.enum(h76),u76=["github_app","oauth","token","github_cli"],l76=P5.enum(u76),c76=["active","revoked"],m76=P5.enum(c76),Fb$=P5.object({provider:C80,host:P5.string().min(1).describe("Provider host, e.g. github.com"),path:P5.string().min(1).describe("Full namespace path, e.g. owner/name or group/sub/project")}),Ub$=P5.object({id:P5.string(),organizationId:P5.string(),type:C80,host:P5.string(),authKind:l76,externalAccountId:P5.string().describe("Provider-side account identity: installation id (GitHub App), user/group id (GitLab) or user/workspace uuid (Bitbucket)."),login:P5.string().describe("Display login of the account/namespace"),avatarUrl:P5.string().nullable(),installationId:P5.number().nullable().describe("GitHub App installation id; null for other auth kinds."),status:m76,createdAt:P5.string(),updatedAt:P5.string()}),ON=P5.string().regex(/^[a-z][a-z0-9-]{0,31}$/,"lowercase letters, digits and dashes only"),S80=P5.object({id:P5.string(),organizationId:P5.string(),accountId:P5.string().nullable().describe("Credential-holding account; null for anonymous public clones."),provider:C80,host:P5.string(),path:P5.string(),externalId:P5.string().nullable().describe("Provider repository/project id, when known."),defaultBranch:P5.string().nullable(),webUrl:P5.string(),visibility:P5.enum(["public","private","internal"]).nullable(),sandboxImage:ON.describe("Sandbox image this repository's sandboxes boot from."),createdAt:P5.string(),updatedAt:P5.string()})});function p76($){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 Bb$($){let Z=$.toLowerCase();return Z.startsWith("www.")?Z.slice(4):Z}function tX($,Z){let Q=$.trim();if(!Q)return null;let X,Y,J=/^(?:[\w.-]+@)?([\w.-]+(?::\d+)?):(?!\/\/)(.+)$/.exec(Q);if(J&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(Q))X=J[1],Y=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;X=F.host,Y=F.pathname}else if(Z?.provider)X=Z.host??wD0[Z.provider],Y=Q;else return null;X=Bb$(X);let G=Z?.provider??p76(X);if(!G)return null;let W=Y.split("/").map((F)=>F.trim()).filter(Boolean),K=W.indexOf("-");if(K>=0)W=W.slice(0,K);if(i76.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:X,path:W.join("/")}}function JF($){return`${$.host.toLowerCase()}/${$.path.toLowerCase()}`}function lW1($){let Z=$.path.split("/");return Z[Z.length-1]??$.path}function n76($){let Z=$.path.lastIndexOf("/");return Z<0?"":$.path.slice(0,Z)}function y5($){return{owner:n76($),name:lW1($)}}function YG($){return`https://${$.host}/${$.path}`}function _80($,Z){let Q=`${$.host}/${$.path}.git`;if(!Z)return`https://${Q}`;return`https://${d76[$.provider]}:${encodeURIComponent(Z)}@${Q}`}function ND($,Z){let Q=Bb$(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 fi($,Z){return{provider:"github",host:wD0.github,path:`${$}/${Z}`}}var wD0,d76,i76;var cW1=L(()=>{wD0={github:"github.com",gitlab:"gitlab.com",bitbucket:"bitbucket.org"},d76={github:"x-access-token",gitlab:"oauth2",bitbucket:"x-token-auth"},i76=new Set(["github","bitbucket"])});function KK($,Z){return`${YG($)}/${t76[$.provider]}/${Z}`}function a76($){let Z=$.toLowerCase();return o76[Z]??Z}function Ob$($,Z,Q){let X=Number($[3]);if(!Number.isSafeInteger(X)||X<=0)return null;let Y=a76($[1]),J=$[2],G=Z?decodeURIComponent(J):J;if(/^\d+$/.test(G))return null;let W=`https://${Y}/${G}`,K=tX(W)??(Q?tX(W,{provider:Q}):null);if(!K)return null;return{repo:K,number:X,url:KK(K,X)}}function ED0($){let Z=$.trim();if(!Z)return null;for(let{re:Q,api:X,provider:Y}of Db$){let J=Q.exec(Z),G=J?Ob$(J,X===!0,Y):null;if(G)return G}return null}function mW1($){let Z=$.length>Lb$?$.slice(0,Lb$):$;for(let{re:Q,api:X,provider:Y}of Db$){let J=Q.exec(Z),G=J?Ob$(J,X===!0,Y):null;if(G)return G}return null}var t76,Db$,o76,Lb$=200000;var dW1=L(()=>{cW1();t76={github:"pull",gitlab:"-/merge_requests",bitbucket:"pull-requests"};Db$=[{re:/https?:\/\/([^/\s"']+)\/([^\s"']+?)\/-\/merge_requests\/(\d+)/,provider:"gitlab"},{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,provider:"gitlab"},{re:/https?:\/\/([^/\s"']+)\/2\.0\/repositories\/([^/\s"']+\/[^/\s"']+)\/pullrequests\/(\d+)/,api:!0}],o76={"api.github.com":"github.com","api.bitbucket.org":"bitbucket.org"}});function jb$($){return iW1[$]}function pW1($,Z){return iW1[$].checkoutCommand.replace("{number}",String(Z))}function wb$($,Z){let{abbreviation:Q,numberSigil:X}=iW1[$];return`${Q} ${X}${Z}`}var iW1;var Eb$=L(()=>{iW1={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 a4=L(()=>{Nb$();cW1();dW1();Eb$()});async function v80($,Z,Q){let X=new AbortController,Y,J=new Promise((W,K)=>{Y=setTimeout(()=>{X.abort(),K(new zb$($.id,Q))},Q)}),G=(async()=>{let W=await k3($,Z,!0);try{return(await W.listTools(void 0,{timeout:Q,signal:X.signal})).tools}finally{await W.close().catch(()=>{})}})();G.catch(()=>{});try{return await Promise.race([G,J])}finally{if(Y)clearTimeout(Y)}}var zb$;var Pb$=L(()=>{x80();zb$=class zb$ extends Error{constructor($,Z){super(`listTools timed out after ${Z}ms for connection ${$}`);this.name="ListToolsTimeoutError"}}});var nW1=b((Tb$)=>{Object.defineProperty(Tb$,"__esModule",{value:!0});Tb$.kvPrefix=Tb$.KvWatchInclude=void 0;Tb$.KvWatchInclude={LastValue:"",AllHistory:"history",UpdatesOnly:"updates"};Tb$.kvPrefix="KV_"});var xb$=b((_b$)=>{Object.defineProperty(_b$,"__esModule",{value:!0});_b$.KvStatusImpl=_b$.Bucket=_b$.Kvm=_b$.kvOperationHdr=void 0;_b$.Base64KeyCodec=s76;_b$.NoopKvCodecs=tW1;_b$.defaultBucketOpts=qb$;_b$.validateKey=Mb$;_b$.validateSearchKey=Ib$;_b$.hasWildcards=Vb$;_b$.validateBucket=zD0;var $Z=Z3(),N9=ZH0(),e9=nW1();function s76(){let $=(Z,Q)=>{let X=[];for(let Y of Z.split("."))switch(Y){case">":case"*":X.push(Y);break;default:X.push(Q(Y));break}return X.join(".")};return{encode(Z){return $(Z,btoa)},decode(Z){return $(Z,atob)}}}function tW1(){return{key:{encode($){return $},decode($){return $}},value:{encode($){return typeof $==="string"?new TextEncoder().encode($):$},decode($){return $}}}}function qb$(){return{replicas:1,history:1,timeout:2000,max_bytes:-1,maxValueSize:-1,codec:tW1(),storage:N9.StorageType.File}}_b$.kvOperationHdr="KV-Operation";var Rb$="$KV",e76=/^[-/=.\w]+$/,$Q6=/^[-/=.>*\w]+$/,ZQ6=/^[-\w]+$/;function Mb$($){if($.startsWith(".")||$.endsWith(".")||!e76.test($))throw Error(`invalid key: ${$}`)}function Ib$($){if($.startsWith(".")||$.endsWith(".")||$.includes("..")||!$Q6.test($))throw Error(`invalid key: ${$}`)}function Vb$($){if($.startsWith(".")||$.endsWith("."))throw Error(`invalid key: ${$}`);let Z=$.split("."),Q=!1;for(let X=0;X<Z.length;X++)switch(Z[X]){case"*":Q=!0;break;case">":if(X!==Z.length-1)throw Error(`invalid key: ${$}`);Q=!0;break;default:}return Q}function zD0($){if(!ZQ6.test($))throw Error(`invalid bucket name: ${$}`)}class kb${js;constructor($){this.js=(0,N9.toJetStreamClient)($)}create($,Z={}){return this.#$($,Z)}open($,Z={}){return Z.bindOnly=!0,this.#$($,Z)}#$($,Z={}){let{ok:Q,min:X}=this.js.nc.features.get($Z.Feature.JS_KV);if(!Q)return Promise.reject(Error(`kv is only supported on servers ${X} or better`));if(Z.bindOnly)return bi.bind(this.js,$,Z);return bi.create(this.js,$,Z)}list(){let $=(Q)=>{let Y=Q.streams.filter((G)=>{return G.config.name.startsWith(e9.kvPrefix)});Y.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(Y.length)J=this.js.nc.info?.cluster??"";return Y.map((G)=>{return new PD0(G,J)})},Z=`${this.js.prefix}.STREAM.LIST`;return new N9.ListerImpl(Z,$,this.js)}}_b$.Kvm=kb$;class bi{js;jsm;stream;bucket;direct;codec;prefix;editPrefix;useJsPrefix;_prefixLen;constructor($,Z,Q){zD0($),this.js=Z,this.jsm=Q,this.bucket=$,this.prefix=Rb$,this.editPrefix="",this.useJsPrefix=!1,this._prefixLen=0}static async create($,Z,Q={}){zD0(Z);let X=await $.jetstreamManager(),Y=new bi(Z,$,X);return await Y.init(Q),Y}static async bind($,Z,Q={}){let X=$.getOptions()?.checkAPI||Q.bindOnly===!1,Y=await $.jetstreamManager(X),J={config:{allow_direct:Q.allow_direct}};zD0(Z);let G=new bi(Z,$,Y);return J.config.name=Q.streamName??G.bucketName(),Object.assign(G,J),G.stream=J.config.name,G.codec=Q.codec||tW1(),G.direct=J.config.allow_direct??!1,G.initializePrefixes(J),G}async init($={}){let Z=Object.assign(qb$(),$);this.codec=Z.codec;let Q={};if(this.stream=Q.name=$.streamName??this.bucketName(),Q.retention=N9.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,$Z.nanos)(Z.markerTTL);if($.mirror){let H=Object.assign({},$.mirror);if(!H.name.startsWith(e9.kvPrefix))H.name=`${e9.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(e9.kvPrefix)?U.name.substring(e9.kvPrefix.length):U.name;if(!U.name.startsWith(e9.kvPrefix))U.name=`${e9.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?N9.StoreCompression.S2:N9.StoreCompression.None;let X=this.js.nc,Y=X.getServerVersion(),J=Y?(0,$Z.compare)(Y,(0,$Z.parseSemVer)("2.7.2"))>=0:!1;Q.discard=J?N9.DiscardPolicy.New:N9.DiscardPolicy.Old;let{ok:G,min:W}=X.features.get($Z.Feature.JS_ALLOW_DIRECT);if(!G&&$.allow_direct===!0){let H=Y?`${Y.major}.${Y.minor}.${Y.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,$Z.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(e9.kvPrefix))Q=Q.substring(e9.kvPrefix.length);if(Z.external&&Z.external.api!==""){let X=Z.name.substring(e9.kvPrefix.length);this.useJsPrefix=!1,this.prefix=`$KV.${X}`,this.editPrefix=`${Z.external.api}.$KV.${Q}`}else this.editPrefix=this.prefix}}bucketName(){return this.stream??`${e9.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`${Rb$}.${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=Mb$;validateSearchKey=Ib$;hasWildcards=Vb$;close(){return Promise.resolve()}dataLen($,Z){let Q=Z?Z.get(N9.JsHeaders.MessageSizeHdr)||"":"";if(Q!=="")return parseInt(Q,10);return $.length}smToEntry($){return new Cb$(this.bucket,this.prefixLen,$,this.codec)}jmToWatchEntry($,Z){return new Sb$(this.bucket,this.prefixLen,$,Z,this.codec)}async create($,Z,Q){let X;try{let J={previousSeq:0},G=await this._put($,Z,J,Q);return Promise.resolve(G)}catch(J){if(X=J,J instanceof N9.JetStreamApiError){let G=J;if(G.code!==N9.JetStreamApiCodes.StreamWrongLastSequence&&G.code!==N9.JetStreamApiCodes.StreamWrongLastSequenceUnknown)return Promise.reject(J)}}let Y=0;try{let J=await this.get($);if(J?.operation==="DEL"||J?.operation==="PURGE")return Y=J!==null?J.revision:0,this._put($,Z,{previousSeq:Y},Q);else return Promise.reject(X)}catch(J){return Promise.reject(J)}}update($,Z,Q,X){if(Q<=0)throw Error("version must be greater than 0");return this.put($,Z,{previousSeq:Q,timeout:X})}async _put($,Z,Q={},X){let Y=this.encodeKey($);this.validateKey(Y),Z=this.codec.value.encode(Z);let J={timeout:Q?.timeout};if(Q.previousSeq!==void 0){let G=(0,$Z.headers)();J.headers=G,G.set(N9.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Q.previousSeq}`)}if(X)(J.headers||(0,$Z.headers)()).set(N9.PubHeaders.MessageTTL,X);try{return(await this.js.publish(this.subjectForKey(Y,!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 X={last_by_subj:this.subjectForKey(Q)};if(Z&&Z.revision>0)X={seq:Z.revision};let Y=null;try{if(this.direct)Y=await this.jsm.direct.getMessage(this.bucketName(),X);else Y=await this.jsm.streams.getMessage(this.bucketName(),X);if(Y===null)return null;let J=this.smToEntry(Y);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 X=Date.now()-$,Y=Z.map((G)=>{let W=this.subjectForKey(G.key);if(G.created.getTime()>=X)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(Y);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 X=await this.keys($),Y=[];for await(let J of X)if(Y.push(this._doDeleteOrPurge(J,Z)),Y.length===100)await Promise.all(Y),Y.length=0;if(Y.length>0)await Promise.all(Y)}async _doDeleteOrPurge($,Z,Q){let X=this.encodeKey($);this.validateKey(X);let Y=(0,$Z.headers)();if(Y.set(_b$.kvOperationHdr,Z),Z==="PURGE"){let J=Q;if(Y.set(N9.JsHeaders.RollupHdr,N9.JsHeaders.RollupValueSubject),typeof J?.ttl==="string"&&J.ttl!=="")Y.set(N9.PubHeaders.MessageTTL,`${J.ttl}`)}if(Q?.previousSeq)Y.set(N9.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Q.previousSeq}`);await this.js.publish(this.subjectForKey(X,!0),$Z.Empty,{headers:Y})}_buildCC($,Z,Q={}){let Y=(!Array.isArray($)?[$]:$).map((W)=>{let K=this.encodeKey(W);return this.validateSearchKey(W),this.fullKeyName(K)}),J=N9.DeliverPolicy.LastPerSubject;if(Z===e9.KvWatchInclude.AllHistory)J=N9.DeliverPolicy.All;if(Z===e9.KvWatchInclude.UpdatesOnly)J=N9.DeliverPolicy.New;let G=void 0;if(Y.length===1)G=Y[0],Y=void 0;return Object.assign({deliver_policy:J,ack_policy:N9.AckPolicy.None,filter_subjects:Y,filter_subject:G,flow_control:!0,idle_heartbeat:(0,$Z.nanos)(5000)},Q)}remove($){return this.purge($)}async history($={}){let Z=$.key??">",Q={};Q.headers_only=$.headers_only||!1;let X=new $Z.QueuedIteratorImpl,Y=()=>{X.stop()},J=this._buildCC(Z,e9.KvWatchInclude.AllHistory,Q),G=await this.js.consumers.getPushConsumer(this.stream,J);if(X._data=G,(await G.info(!0)).num_pending===0)return X.push(Y),X;let K=await G.consume({callback:(H)=>{let F=this.jmToWatchEntry(H,!1);if(X.push(F),X.received++,H.info.pending===0)X.push(Y)}});return K.closed().then(()=>{X.push(Y)}),(async()=>{for await(let H of K.status())switch(H.type){case"heartbeat":X.push(()=>{X.stop()});break}})().then(),X.iterClosed.then(()=>{K.stop()}),X}canSetWatcherName(){let $=this.js.nc,{ok:Z}=$.features.get($Z.Feature.JS_NEW_CONSUMER_CREATE_API);return Z}async watch($={}){let Z=$.key??">",Q=new $Z.QueuedIteratorImpl,X={};X.headers_only=$.headers_only||!1;let Y=e9.KvWatchInclude.LastValue;if($.include===e9.KvWatchInclude.AllHistory)Y=e9.KvWatchInclude.AllHistory;else if($.include===e9.KvWatchInclude.UpdatesOnly)Y=e9.KvWatchInclude.UpdatesOnly;let J=$.ignoreDeletes===!0,G=this._buildCC(Z,Y,X);if(G.name=`KV_WATCHER_${$Z.nuid.next()}`,$.resumeFromRevision&&$.resumeFromRevision>0)G.deliver_policy=N9.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=Y===e9.KvWatchInclude.UpdatesOnly||H===0;Q._data=W;let U=0,N=await W.consume({callback:(B)=>{if(!F)U++,F=U>=H;let D=this.jmToWatchEntry(B,F);if(J&&D.operation==="DEL")return;Q.push(D),Q.received++}});return Q.iterClosed.then(()=>{N.stop()}),N.closed().then(()=>{Q.push(()=>{Q.stop()})}),Q}async keys($=">"){let Z=new $Z.QueuedIteratorImpl,Q=this._buildCC($,e9.KvWatchInclude.LastValue,{headers_only:!0}),X=await this.js.consumers.getPushConsumer(this.stream,Q);if((await X.info()).num_pending===0)return Z.stop(),Z;Z._data=X;let J=await X.consume({callback:(G)=>{let W=G.headers?.get(_b$.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(),X=await this.jsm.streams.info(Q);return new PD0(X,Z)}}_b$.Bucket=bi;class PD0{si;cluster;constructor($,Z=""){this.si=$,this.cluster=Z}get bucket(){return this.si.config.name.startsWith(e9.kvPrefix)?this.si.config.name.substring(e9.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,$Z.millis)(this.si.config.max_age)}get markerTTL(){if(typeof this.si.config.subject_delete_marker_ttl==="number")return(0,$Z.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!==N9.StoreCompression.None;return!1}}_b$.KvStatusImpl=PD0;class Cb${bucket;sm;prefixLen;codec;constructor($,Z,Q,X){this.bucket=$,this.prefixLen=Z,this.sm=Q,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 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(_b$.kvOperationHdr)||"PUT"}get length(){let $=this.sm.header.get(N9.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}json($){return JSON.parse($Z.TD.decode(this.value),$)}string(){return $Z.TD.decode(this.value)}}class Sb${bucket;sm;prefixLen;update;codec;constructor($,Z,Q,X,Y){this.bucket=$,this.prefixLen=Z,this.sm=Q,this.update=X,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 created(){return new Date((0,$Z.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(_b$.kvOperationHdr)||"PUT"}get delta(){return this.sm.info.pending}get length(){let $=this.sm.headers?.get(N9.JsHeaders.MessageSizeHdr)||"";if($!=="")return parseInt($,10);return this.sm.data.length}get isUpdate(){return this.update}json($){return JSON.parse($Z.TD.decode(this.value),$)}string(){return $Z.TD.decode(this.value)}}});var oW1=b((GF)=>{Object.defineProperty(GF,"__esModule",{value:!0});GF.validateKey=GF.validateBucket=GF.NoopKvCodecs=GF.Kvm=GF.defaultBucketOpts=GF.Bucket=GF.Base64KeyCodec=GF.KvWatchInclude=GF.kvPrefix=void 0;var fb$=nW1();Object.defineProperty(GF,"kvPrefix",{enumerable:!0,get:function(){return fb$.kvPrefix}});Object.defineProperty(GF,"KvWatchInclude",{enumerable:!0,get:function(){return fb$.KvWatchInclude}});var WR=xb$();Object.defineProperty(GF,"Base64KeyCodec",{enumerable:!0,get:function(){return WR.Base64KeyCodec}});Object.defineProperty(GF,"Bucket",{enumerable:!0,get:function(){return WR.Bucket}});Object.defineProperty(GF,"defaultBucketOpts",{enumerable:!0,get:function(){return WR.defaultBucketOpts}});Object.defineProperty(GF,"Kvm",{enumerable:!0,get:function(){return WR.Kvm}});Object.defineProperty(GF,"NoopKvCodecs",{enumerable:!0,get:function(){return WR.NoopKvCodecs}});Object.defineProperty(GF,"validateBucket",{enumerable:!0,get:function(){return WR.validateBucket}});Object.defineProperty(GF,"validateKey",{enumerable:!0,get:function(){return WR.validateKey}})});var KR=b((bE)=>{Object.defineProperty(bE,"__esModule",{value:!0});bE.NoopKvCodecs=bE.Kvm=bE.defaultBucketOpts=bE.Bucket=bE.Base64KeyCodec=bE.KvWatchInclude=void 0;var NQ6=oW1();Object.defineProperty(bE,"KvWatchInclude",{enumerable:!0,get:function(){return NQ6.KvWatchInclude}});var b80=oW1();Object.defineProperty(bE,"Base64KeyCodec",{enumerable:!0,get:function(){return b80.Base64KeyCodec}});Object.defineProperty(bE,"Bucket",{enumerable:!0,get:function(){return b80.Bucket}});Object.defineProperty(bE,"defaultBucketOpts",{enumerable:!0,get:function(){return b80.defaultBucketOpts}});Object.defineProperty(bE,"Kvm",{enumerable:!0,get:function(){return b80.Kvm}});Object.defineProperty(bE,"NoopKvCodecs",{enumerable:!0,get:function(){return b80.NoopKvCodecs}})});function yE(){let $=new TextEncoder,Z=new TextDecoder;return{encode:(Q)=>$.encode(JSON.stringify(Q)),decode:(Q)=>JSON.parse(Z.decode(Q))}}class aW1{options;kv=null;codec=yE();constructor($){this.options=$}async init(){let $=this.options.getJetStream();if(!$)return;this.kv=await new yb$.Kvm($).create(LQ6,{storage:bb$.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 DQ6($,Z,Q){if(Q<=0)return!0;if($===void 0)return!0;return Z-$>=Q}function gb$($){let Z=["tools","resources","prompts"];for(let Q of Z){let X=`${Q}:${$}`;AD0.delete(X),g80.delete(X)}}function TD0($){return $ instanceof _1&&$.code===g1.MethodNotFound}function OQ6($){return $ instanceof _1&&$.code===-32000&&/connection closed/i.test($.message)}async function hE($,Z,Q,X,Y,J=0){if(!X)try{return await Q()}catch(H){if(TD0(H))return[];return y80.add(1,{type:$,outcome:"error",stage:"no_cache"}),null}let G=`${$}:${Z}`,W=await X.get($,Z);if(W===null)try{let H=await Q();return X.set($,Z,H).catch(()=>{}),AD0.set(G,Date.now()),y80.add(1,{type:$,outcome:"miss",stage:"miss"}),H}catch(H){if(TD0(H))return X.set($,Z,[]).catch(()=>{}),[];return y80.add(1,{type:$,outcome:"error",stage:"miss"}),null}if(y80.add(1,{type:$,outcome:"hit",stage:"hit"}),DQ6(AD0.get(G),Date.now(),J)&&!g80.has(G)){g80.add(G),AD0.set(G,Date.now());let H=Q().then((F)=>X.set($,Z,F)).catch((F)=>{if(TD0(F)||OQ6(F)){if(TD0(F))X.set($,Z,[]).catch(()=>{});return}y80.add(1,{type:$,outcome:"error",stage:"revalidation"})}).finally(()=>g80.delete(G));Y?.(H)}return W}function rW1($){hb$=$}function VZ(){return hb$}var bb$,yb$,y80,LQ6="DECOCMS_MCP_LISTS",g80,AD0,gE=30000,hb$=null;var JG=L(()=>{zZ();f6();bb$=_(TH(),1),yb$=_(KR(),1),y80=Y$.createCounter("mcp_list_cache.fetches",{description:"MCP list cache fetch outcomes (hit, miss, error)",unit:"{fetches}"});g80=new Set;Y$.createObservableGauge("mcp_list_cache.pending_revalidations",{description:"In-flight background MCP list revalidations on this pod",unit:"{revalidations}"}).addCallback(($)=>$.observe(g80.size));AD0=new Map});function RD0($){return(Z)=>{if(Z instanceof _1&&Z.code===g1.MethodNotFound)return $;throw Z}}var ub$=L(()=>{zZ()});function qD0($,Z,Q){let X=uE($,Z,Q,VZ()??void 0),Y=NA(X,{name:"studio-mcp-server",version:"1.0.0"},{capabilities:jQ6,toolCallTimeoutMs:uc});Y.server.setRequestHandler(Zw,async()=>{return await X.listResources().catch(RD0({resources:[]}))}),Y.server.setRequestHandler(Qw,async()=>{return await X.listResourceTemplates().catch(RD0({resourceTemplates:[]}))}),Y.server.setRequestHandler(Xw,async()=>{return await X.listPrompts().catch(RD0({prompts:[]}))});let J=Y.close.bind(Y);return Y.close=async()=>{await J(),await X.close().catch(()=>{})},Y}var jQ6;var lb$=L(()=>{lJ();zZ();h80();JG();ub$();jQ6={tools:{},resources:{},prompts:{}}});var yi=L(()=>{x80();Pb$();lb$()});async function gi($,Z,Q){await(await k3(Z,$,!1)).callTool({name:"ON_MCP_CONFIGURATION",arguments:{state:Q.state,scopes:Q.scopes,firstRun:Q.firstRun,...Q.vault?{vault:Q.vault}:{}}})}var MD0=L(()=>{yi()});import{z as sW1}from"zod";function zQ6($){let{owner:Z,name:Q}=y5({path:$.path});return{owner:Z,name:Q,url:$.webUrl??`https://${$.host}/${$.path}`,repositoryId:$.repositoryId}}function PQ6($,Z){if(!Z)return $;return $.filter((Q)=>Q.connection_id!==Z)}function TQ6($,Z){let{repository:Q,github_repo:X,...Y}=$,J=Z?LD0(Z):null;return{...Y,...Z?{repository:BD0(Z)}:{},...J?{github_repo:J}:{}}}async function AQ6($,Z,Q){let X=K4.REPORTS(Z),Y=await $.storage.connections.findById(X,Z);if(!Y)throw Error("Reports is not set up for this organization yet");let J=TQ6(Y.configuration_state??{},Q);await $.storage.connections.update(X,{configuration_state:J});try{await gi($,{...Y,configuration_state:J},{state:J,scopes:Y.configuration_scopes??[],firstRun:!1})}catch(G){console.error("[reports] ON_MCP_CONFIGURATION after repository change failed",G)}}async function RQ6($,Z,Q,X){let Y=gc(Z),J=await $.storage.virtualMcps.findById(Y,Z);if(!J)return;let G=J.metadata??{},W=G.repository,{repository:K,...H}=G;await $.storage.virtualMcps.update(Y,Q,{metadata:{...H,...X?{repository:zQ6(X)}:{}},connections:PQ6(J.connections??[],W?.connectionId??null)})}var wQ6,EQ6,eW1;var cb$=L(()=>{r8();a4();DD0();_0();MD0();wQ6=sW1.object({repositoryId:sW1.string().min(1).nullable().describe("Studio repository id to diagnose, or null to unlink the current one.")}),EQ6=sW1.object({repository:bW1.nullable()});eW1=m({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:wQ6,outputSchema:EQ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to set the diagnostic's repository");let Y=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=bW1.safeParse(G);if(!W.success)throw Error(`Repository ${$.repositoryId} has invalid configuration (missing or empty host/path)`);Y=W.data}return await AQ6(Z,Q.id,Y),await RQ6(Z,Q.id,X,Y),{repository:Y}}})});function lE($,Z){let Q=`/${encodeURIComponent($)}/settings`;return Z?`${Q}/${Z}`:Q}function ID0($,Z){let Q=`/${encodeURIComponent($)}/agents`,X=Z.panel?`${Q}/${Z.panel}`:Q,Y=new URLSearchParams({virtualmcpid:Z.projectId,...Z.search??{}});return`${X}?${Y.toString()}`}var cE=L(()=>{_H0()});function mb$($,Z){if(typeof $!=="string")return null;let Q=fW1($);return Q&&Q!==fW1(Z)?$:null}function hi($){Gb$({siteUrl:$.siteUrl,orgId:$.orgId}).then((Z)=>console.log("[reports] released site",{...$,...Z}),(Z)=>console.warn("[reports] could not release site",{...$,error:Z instanceof Error?Z.message:String(Z)}))}var VD0=L(()=>{vi();UD()});import{z as jN}from"zod";async function VQ6($,Z,Q,X){let Y=await $.storage.connections.findById(Z,Q);if(Y)return Y;throw X}async function kQ6($,Z,Q,X){let Y=await $.storage.virtualMcps.findById(Z,Q);if(Y)return Y;throw X}var $K1,qQ6=3600000,MQ6,IQ6,ZK1;var db$=L(()=>{r8();vi();_0();TU();cE();UD();VD0();$K1=xH0,MQ6=jN.object({siteUrl:jN.string().min(1).describe("Website URL to configure.")}),IQ6=jN.object({connection:CX,virtualMcp:kX,reportApp:jN.object({connectionId:jN.string(),virtualMcpId:jN.string(),toolName:jN.literal($K1)}),created:jN.object({connection:jN.boolean(),virtualMcp:jN.boolean()})});ZK1=m({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:MQ6,outputSchema:IQ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check("COLLECTION_CONNECTIONS_CREATE");let X=t0(Z);if(!X)throw Error("User ID required to set up Reports");let Y=FD($.siteUrl);if(!Y.ok)throw Error(Y.error);let J=K4.REPORTS(Q.id),G=gc(Q.id),W={email:Z.auth.user?.email,reportUrl:`${Z.baseUrl}${ID0(Q.slug??Q.id,{projectId:G,panel:"app",search:{connection:J,tool:$K1}})}`},K=await Z.storage.connections.findById(J,Q.id),H={connection:!1,virtualMcp:!1},F=await Zb$({siteUrl:Y.value,orgId:Q.id,orgName:Q.name,...W}),U=ef$();if(K){console.log("[reports] syncing connection to claimed site",{orgId:Q.id,siteUrl:Y.value,connectionId:J});let O=mb$(K.metadata?.siteUrl,Y.value);if(K=await Z.storage.connections.update(K.id,{connection_url:U,connection_token:F.authorizationToken,metadata:{...K.metadata??{},siteUrl:Y.value}}),O)hi({siteUrl:O,orgId:Q.id,cause:"site_changed"})}else{console.log("[reports] creating connection",{orgId:Q.id,siteUrl:Y.value,connectionId:J});try{let O=JU$(Q.id,F.authorizationToken,U);K=await Z.storage.connections.create({...O,metadata:{...O.metadata??{},siteUrl:Y.value},organization_id:Q.id,created_by:X}),H.connection=!0}catch(O){K=await VQ6(Z,J,Q.id,O)}}let N=await Z.storage.virtualMcps.findById(G,Q.id);if(!N){console.log("[reports] creating virtual MCP",{orgId:Q.id,siteUrl:Y.value,connectionId:K.id,virtualMcpId:G});try{N=await Z.storage.virtualMcps.create(Q.id,X,GU$(Q.id,K.id),{id:G}),H.virtualMcp=!0}catch(O){N=await kQ6(Z,G,Q.id,O)}}if(!N.pinned)N=await Z.storage.virtualMcps.update(N.id,X,{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)<qQ6){let j=(await Z.storage.organizationSettings.get(Q.id))?.flags,w={};if(j?.reports_only==null)w.reports_only=!0;if(Object.keys(w).length>0)await Z.storage.organizationSettings.upsert(Q.id,{flags:w})}return{connection:K,virtualMcp:N,reportApp:{connectionId:K.id,virtualMcpId:N.id,toolName:$K1},created:H}}})});var ib$=L(()=>{Wb$();Kb$();Hb$();cb$();db$()});function u80($,Z,Q){if(Z.some((X)=>X!=="*"&&X.startsWith("SELF::"))&&$.SELF===void 0)$.SELF={value:`${Q}_self`}}function l80($,Z){let Q=new Map;for(let X of Z){if(X==="*")continue;let[Y,J]=TN0(X);if(!SQ6.has(J))continue;let G=P10(Y,$);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 c80($,Z,Q,X){for(let G of Z){if(G==="*")continue;let[W]=TN0(G),K=P10(W,$);if(K===void 0||K===null)throw Error(`Scope references key "${W}" but it's not present in state`)}let Y=d2$($,Z),J=`${Q}_self`;for(let G of Y){if(G===J)continue;let W=await X.storage.connections.findById(G);if(!W||W.organization_id!==Q)throw Error(`Referenced connection not found: ${G}`);try{await X.access.check(G)}catch(K){throw Error(`Access denied to referenced connection: ${G}. ${K.message}`)}}}var SQ6;var QK1=L(()=>{qX1();mH0();SQ6=new Set([lH0,cH0])});import{z as pb$}from"zod";var _Q6,vQ6,XK1;var nb$=L(()=>{F6();_0();X$();JG();MD0();QK1();zB0();TU();_Q6=pb$.object({data:VH0.describe("Data for the new connection (id is auto-generated if not provided)")}),vQ6=pb$.object({item:CX.describe("The created connection entity")}),XK1=m({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:_Q6,outputSchema:vQ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to create connection");let Y={...$.data,organization_id:Q.id,created_by:X};if(Y.id){if((await Z.storage.connections.findById(Y.id))?.organization_id===Q.id)throw Error("Connection already exists in organization");if(await Z.storage.connections.findBySanitizedId(Y.id))throw Error("Connection id conflicts with an existing connection's isolated database schema")}if(Y.connection_type==="VIRTUAL"){let U=bc(Y.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");Y.connection_url=yc(U)}if(Y.connection_type==="STDIO"&&!P0().localMode)throw Error("STDIO connections are only available in local mode (--local-mode).");let J=await ld({id:`pending-${Date.now()}`,title:Y.title,connection_type:Y.connection_type,connection_url:Y.connection_url,connection_token:Y.connection_token,connection_headers:Y.connection_headers}).catch(()=>null),G=J?.tools?.length?J.tools:null,W=J?.scopes?.length?J.scopes:Y.configuration_scopes??null,K=Y.configuration_state??null;if(K&&W?.length)u80(K,W,Q.id),await c80(K,W,Q.id,Z);let H=await Z.storage.connections.createNew({...Y,tools:null,configuration_state:K,configuration_scopes:W}),F=K&&W?.length?l80(K,W):[];if(F.length>0){let U;try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:H.id,createdBy:X,grants:F});let{plaintextToken:N,record:B}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:Q.id,subjectConnectionId:H.id});U=B.id,await gi(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)VZ()?.set("tools",H.id,G).catch(()=>{});return h1.capture({distinctId:X,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 HK}from"zod/v4";import{z as tb$}from"zod/v4";import{z as kD0}from"zod/v4";import{z as wN}from"zod/v4";import{z as yQ6}from"zod/v4";import{z as HR}from"zod/v4";import{z as EN}from"zod/v4";import{z as jQ}from"zod/v4";import{z as ob$}from"zod/v4";import{z as _D0}from"zod/v4";import{z as GX6}from"zod/v4";import{z as ab$}from"zod/v4";import{z as CD0}from"zod/v4";import{z as DX6}from"zod/v4";function m80($,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,X)=>m80(Q,Z[X]))}if(typeof $==="object"&&typeof Z==="object"){let Q=Object.keys($),X=Object.keys(Z);if(Q.length!==X.length)return!1;return Q.every((Y)=>X.includes(Y)&&m80($[Y],Z[Y]))}return!1}function XX6(){return($)=>{if(!Array.isArray($))return!0;let Z=[];return $.every((Q)=>{if(Z.some((Y)=>m80(Q,Y)))return!1;return Z.push(Q),!0})}}function SD0($,Z){return $.safeParse(Z).success}function QX($){if(typeof $==="boolean")return $?HK.any():HK.never();let Z={};for(let Y of EX6)Y.apply(Z,$);let Q=[];if(Z.string!==!1)Q.push(Z.string||HK.string());if(Z.number!==!1)Q.push(Z.number||HK.number());if(Z.boolean!==!1)Q.push(Z.boolean||HK.boolean());if(Z.null!==!1)Q.push(Z.null||HK.null());if(Z.array!==!1)Q.push(Z.array||HK.array(HK.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 Y=HK.custom((J)=>{return typeof J==="object"&&J!==null&&!Array.isArray(J)},"Must be an object, not an array");Q.push(Y)}if(Z.file!==!1&&Z.file!==void 0)Q.push(Z.file);let X;if(Q.length===0)X=HK.never();else if(Q.length===1)X=Q[0];else if(!Object.keys($).some((J)=>J!=="$schema"&&J!=="title"&&J!=="description"))X=HK.any();else X=HK.union(Q);for(let Y of zX6)X=Y.apply(X,$);return X}var xQ6=class{apply($,Z){if(!Z.type)return;let Q=Array.isArray(Z.type)?Z.type:[Z.type],X=new Set(Q);if(!X.has("string"))$.string=!1;if(!X.has("number")&&!X.has("integer"))$.number=!1;if(!X.has("boolean"))$.boolean=!1;if(!X.has("null"))$.null=!1;if(!X.has("array"))$.array=!1;if(!X.has("object"))$.object=!1;if(X.has("integer")&&$.number!==!1){let Y=$.number||tb$.number();if(Y instanceof tb$.ZodNumber)$.number=Y.int()}}},fQ6=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=kD0.literal(Q);else if(typeof Q==="number")$.number=kD0.literal(Q);else if(typeof Q==="boolean")$.boolean=kD0.literal(Q);else if(Q===null)$.null=kD0.null();else if(Array.isArray(Q))$.array=void 0;else if(typeof Q==="object")$.object=void 0}},bQ6=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((X)=>typeof X==="string"),number:Z.enum.filter((X)=>typeof X==="number"),boolean:Z.enum.filter((X)=>typeof X==="boolean"),null:Z.enum.filter((X)=>X===null),array:Z.enum.filter((X)=>Array.isArray(X)),object:Z.enum.filter((X)=>typeof X==="object"&&X!==null&&!Array.isArray(X))};$.string=this.createTypeSchema(Q.string,"string"),$.number=this.createTypeSchema(Q.number,"number"),$.boolean=this.createTypeSchema(Q.boolean,"boolean"),$.null=Q.null.length>0?wN.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 wN.literal($[0]);if(Z==="string")return wN.enum($);if(Z==="number"){let[Q,X,...Y]=$;return wN.union([wN.literal(Q),wN.literal(X),...Y.map((J)=>wN.literal(J))])}if(Z==="boolean")return wN.union([wN.literal(!0),wN.literal(!1)]);return!1}},gQ6=class{apply($,Z){let Q=Z;if(Q.type==="string"&&Q.format==="binary"&&Q.contentEncoding==="binary"){let X=yQ6.file();if(Q.minLength!==void 0)X=X.min(Q.minLength);if(Q.maxLength!==void 0)X=X.max(Q.maxLength);if(Q.contentMediaType!==void 0)X=X.mime(Q.contentMediaType);$.file=X,$.string=!1}}},hQ6=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=HR.string()}}},uQ6=class{apply($,Z){let Q=Z;if(Q.minLength===void 0)return;if($.string!==!1){let X=$.string||HR.string();if(X instanceof HR.ZodString)$.string=X.refine((Y)=>{return Array.from(Y).length>=Q.minLength},{message:`String must be at least ${Q.minLength} characters long`})}}},lQ6=class{apply($,Z){let Q=Z;if(Q.maxLength===void 0)return;if($.string!==!1){let X=$.string||HR.string();if(X instanceof HR.ZodString)$.string=X.refine((Y)=>{return Array.from(Y).length<=Q.maxLength},{message:`String must be at most ${Q.maxLength} characters long`})}}},cQ6=class{apply($,Z){let Q=Z;if(!Q.pattern)return;if($.string!==!1){let X=$.string||HR.string();if(X instanceof HR.ZodString){let Y=new RegExp(Q.pattern);$.string=X.regex(Y)}}}},mQ6=class{apply($,Z){let Q=Z;if(Q.minimum===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)$.number=X.min(Q.minimum)}}},dQ6=class{apply($,Z){let Q=Z;if(Q.maximum===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)$.number=X.max(Q.maximum)}}},iQ6=class{apply($,Z){let Q=Z;if(Q.exclusiveMinimum===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)if(typeof Q.exclusiveMinimum==="number")$.number=X.gt(Q.exclusiveMinimum);else $.number=!1}}},pQ6=class{apply($,Z){let Q=Z;if(Q.exclusiveMaximum===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)if(typeof Q.exclusiveMaximum==="number")$.number=X.lt(Q.exclusiveMaximum);else $.number=!1}}},nQ6=class{apply($,Z){let Q=Z;if(Q.multipleOf===void 0)return;if($.number!==!1){let X=$.number||EN.number();if(X instanceof EN.ZodNumber)$.number=X.refine((Y)=>{if(Q.multipleOf===0)return!1;let J=Y/Q.multipleOf,G=Math.round(J),W=Math.min(Math.abs(Y)*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}`})}}},tQ6=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=jQ.array(jQ.any())}}},oQ6=class{apply($,Z){let Q=Z;if(Q.minItems===void 0)return;if($.array!==!1)$.array=($.array||jQ.array(jQ.any())).min(Q.minItems)}},aQ6=class{apply($,Z){let Q=Z;if(Q.maxItems===void 0)return;if($.array!==!1)$.array=($.array||jQ.array(jQ.any())).max(Q.maxItems)}},rQ6=class{apply($,Z){let Q=Z;if($.array===!1)return;if(Array.isArray(Q.items))$.array=$.array||jQ.array(jQ.any());else if(Q.items&&typeof Q.items!=="boolean"&&!Q.prefixItems){let X=QX(Q.items),Y=jQ.array(X);if($.array&&$.array instanceof jQ.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)Y=Y.min(W.minimum);else if(W.check==="max_length"&&W.maximum!==void 0)Y=Y.max(W.maximum)}})}$.array=Y}else if(typeof Q.items==="boolean"&&Q.items===!1)if(!Q.prefixItems)$.array=jQ.array(jQ.any()).max(0);else $.array=$.array||jQ.array(jQ.any());else if(typeof Q.items==="boolean"&&Q.items===!0)$.array=$.array||jQ.array(jQ.any());else if(Q.prefixItems)$.array=$.array||jQ.array(jQ.any())}},sQ6=class{apply($,Z){if(Z.type!=="array")return;let Q=Z;if(!Array.isArray(Q.items))return;if($.array===!1)return;let X=Q.items.map((J)=>QX(J)),Y;if(X.length===0)Y=ob$.tuple([]);else Y=ob$.tuple(X);if(Q.minItems!==void 0&&Q.minItems>X.length)Y=!1;if(Q.maxItems!==void 0&&Q.maxItems<X.length)Y=!1;$.tuple=Y,$.array=!1}},eQ6=class{apply($,Z){let Q=Z;if($.object===!1)return;if(Q.properties||Q.required||Q.additionalProperties!==void 0)$.object=$.object||_D0.object({}).passthrough()}},$X6=class{apply($,Z){let Q=Z;if(Z.type===void 0&&(Q.maxProperties!==void 0||Q.minProperties!==void 0)){if($.object===void 0)$.object=_D0.object({}).passthrough()}}},ZX6=class{apply($,Z){let Q=Z;if(Q.maxProperties===void 0)return;if($.object!==!1){let X=$.object||_D0.object({}).passthrough();$.object=X.refine((Y)=>Object.keys(Y).length<=Q.maxProperties,{message:`Object must have at most ${Q.maxProperties} properties`})}}},QX6=class{apply($,Z){let Q=Z;if(Q.minProperties===void 0)return;if($.object!==!1){let X=$.object||_D0.object({}).passthrough();$.object=X.refine((Y)=>Object.keys(Y).length>=Q.minProperties,{message:`Object must have at least ${Q.minProperties} properties`})}}},YX6=class{apply($,Z){if(!Z.not)return $;let Q=QX(Z.not);return $.refine((X)=>!SD0(Q,X),{message:"Value must not match the 'not' schema"})}},JX6=class{apply($,Z){if(Z.uniqueItems!==!0)return $;return $.refine(XX6(),{message:"Array items must be unique"})}},WX6=class{apply($,Z){if(!Z.allOf||Z.allOf.length===0)return $;return Z.allOf.map((X)=>QX(X)).reduce((X,Y)=>GX6.intersection(X,Y),$)}},KX6=class{apply($,Z){if(!Z.anyOf||Z.anyOf.length===0)return $;let Q=Z.anyOf.length===1?QX(Z.anyOf[0]):ab$.union([QX(Z.anyOf[0]),QX(Z.anyOf[1]),...Z.anyOf.slice(2).map((X)=>QX(X))]);return ab$.intersection($,Q)}},HX6=class{apply($,Z){if(!Z.oneOf||Z.oneOf.length===0)return $;let Q=Z.oneOf.map((X)=>QX(X));return $.refine((X)=>{let Y=0;for(let J of Q)if(J.safeParse(X).success){if(Y++,Y>1)return!1}return Y===1},{message:"Value must match exactly one of the oneOf schemas"})}},FX6=class{apply($,Z){let Q=Z;if(Q.prefixItems&&Array.isArray(Q.prefixItems)){let Y=Q.prefixItems.map((J)=>QX(J));return $.refine((J)=>{if(!Array.isArray(J))return!0;for(let G=0;G<Math.min(J.length,Y.length);G++)if(!SD0(Y[G],J[G]))return!1;if(J.length>Y.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=QX(Q.items);for(let W=Y.length;W<J.length;W++)if(!SD0(G,J[W]))return!1}}return!0},{message:"Array does not match prefixItems schema"})}return $}},UX6=class{apply($,Z){let Q=Z;if(!Q.properties&&!Q.required&&Q.additionalProperties!==!1)return $;if($ instanceof CD0.ZodObject||$ instanceof CD0.ZodRecord){let X={};if(Q.properties){for(let[Y,J]of Object.entries(Q.properties))if(J!==void 0)X[Y]=QX(J)}if(Q.required&&Array.isArray(Q.required)){let Y=new Set(Q.required);for(let J of Object.keys(X))if(!Y.has(J))X[J]=X[J].optional()}else for(let Y of Object.keys(X))X[Y]=X[Y].optional();if(Q.additionalProperties===!1)return CD0.object(X);else return CD0.object(X).passthrough()}return $.refine((X)=>{if(typeof X!=="object"||X===null||Array.isArray(X))return!0;if(Q.properties){for(let[Y,J]of Object.entries(Q.properties))if(J!==void 0){if(Object.getOwnPropertyDescriptor(X,Y)!==void 0){if(!QX(J).safeParse(X[Y]).success)return!1}}}if(Q.required&&Array.isArray(Q.required)){for(let Y of Q.required)if(Object.getOwnPropertyDescriptor(X,Y)===void 0)return!1}if(Q.additionalProperties===!1&&Q.properties){let Y=new Set(Object.keys(Q.properties));for(let J in X)if(!Y.has(J))return!1}return!0},{message:"Object constraints validation failed"})}},NX6=class{apply($,Z){if(!Z.enum||Z.enum.length===0)return $;let Q=Z.enum.filter((X)=>Array.isArray(X)||typeof X==="object"&&X!==null);if(Q.length===0)return $;return $.refine((X)=>{if(typeof X!=="object"||X===null)return!0;return Q.some((Y)=>m80(X,Y))},{message:"Value must match one of the enum values"})}},BX6=class{apply($,Z){if(Z.const===void 0)return $;let Q=Z.const;if(typeof Q!=="object"||Q===null)return $;return $.refine((X)=>m80(X,Q),{message:"Value must equal the const value"})}},LX6=class{apply($,Z){if(Z.description)$=$.describe(Z.description);return $}},OX6=class{apply($,Z){var Q;let X=Z;if(!((Q=X.required)==null?void 0:Q.includes("__proto__"))||Z.type!==void 0)return $;return DX6.any().refine((Y)=>this.validateRequired(Y,X.required),{message:"Missing required properties"})}validateRequired($,Z){if(typeof $!=="object"||$===null||Array.isArray($))return!0;return Z.every((Q)=>Object.prototype.hasOwnProperty.call($,Q))}},jX6=class{apply($,Z){var Q;let X=Z;if(X.contains===void 0)return $;let Y=QX(X.contains),J=(Q=X.minContains)!=null?Q:1,G=X.maxContains;return $.refine((W)=>{if(!Array.isArray(W))return!0;let K=0;for(let H of W)if(SD0(Y,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"})}},wX6=class{apply($,Z){let{default:Q}=Z;if(Q===void 0)return $;if(!$.safeParse(Q).success)return $;return $.default(Q)}},EX6,zX6;var rb$=L(()=>{EX6=[new fQ6,new bQ6,new xQ6,new gQ6,new hQ6,new tQ6,new $X6,new uQ6,new lQ6,new cQ6,new mQ6,new dQ6,new iQ6,new pQ6,new nQ6,new sQ6,new oQ6,new aQ6,new rQ6,new ZX6,new QX6,new eQ6],zX6=[new OX6,new NX6,new BX6,new WX6,new KX6,new HX6,new FX6,new UX6,new jX6,new YX6,new JX6,new wX6,new LX6]});class YK1{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,PX6),this._socket.onerror=(Q)=>{let X="error"in Q?Q.error:Error(`WebSocket error: ${JSON.stringify(Q)}`);Z(X),this.onerror?.(X)},this._socket.onopen=()=>{$()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=(Q)=>{let X;try{X=J3.parse(JSON.parse(Q.data))}catch(Y){this.onerror?.(Y);return}this.onmessage?.(X)}})}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 PX6="mcp";var sb$=L(()=>{zZ()});function TX6($){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 JK1;var eb$=L(()=>{qd();JK1=class JK1 extends yU{constructor($,Z){super($,Z)}send($,Z){let Q=TX6($);if(Q?.type==="emit")return this.onmessage?.(Q.message),Promise.resolve();if(Q?.type==="suppress")return Promise.resolve();return super.send($,Z)}}});var $y$,Zy$=async($,Z,Q)=>{let X=AX6($.connection,Z,Q);if(!X)throw Error("Unknown MCP connection type");let Y=new $y$({name:$?.name??"MCP Client",version:"1.0.0"});return await Y.connect(X),{client:Y}},AX6=($,Z,Q)=>{if($.type==="Websocket")return new YK1(new URL($.url));if($.type!=="SSE"&&$.type!=="HTTP")return null;let Y={...$.token?{authorization:`Bearer ${$.token}`}:{},...Q??{},..."headers"in $?$.headers||{}:{}};if($.type==="SSE"){let J={requestInit:{headers:Y,signal:Z}};if($.token)J.eventSourceInit={fetch:(G,W)=>{return fetch(G,{...W,headers:{...Y,Accept:"text/event-stream"},signal:Z})}};return new DA(new URL($.url),J)}return new JK1(new URL($.url),{requestInit:{headers:Y,signal:Z,credentials:"include"}})};var Qy$=L(()=>{bU();PN0();sb$();zZ();lJ();eb$();$y$=class $y$ extends K7{constructor($,Z){super($,{jsonSchemaValidator:iZ,...Z})}async listTools($,Z){return await this.request({method:"tools/list",params:$},Ke,Z)}}});function qX6($,Z){if(FR.set($,Z),FR.size>RX6){let Q=FR.keys().next().value;if(Q!==void 0)FR.delete(Q)}}function Jy$($){let Z=(Q)=>{if("connection"in $)return Zy$({connection:$.connection},void 0,Q);return $.client};return new Proxy({},{get(Q,X){if(X==="toJSON")return null;if(typeof X!=="string")throw Error("Name must be a string");if(X==="listTools")return W;async function Y(K,H=X){let F=$?.debugId?.(),U=F?{"x-trace-debug-id":F}:void 0,{client:N}=await Z(U),{structuredContent:B,isError:D,content:O}=await N.callTool({name:String(H),arguments:K});if(D){let w=O?.[0]?.text,E=typeof w==="string"?Xy$(w):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??O)}`)}if(B!==void 0)return B;let j=O?.[0]?.text;return typeof j==="string"?Xy$(j):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(!FR.has(H))qX6(H,J());return await FR.get(H)}catch(F){console.error("Failed to list tools",F),FR.delete(H);return}}async function W(){return(await G()??[]).map((H)=>Yy$(H,Y))}return Y.asTool=async()=>{let H=(await G()??[]).find((F)=>F.name===X);if(!H)throw Error(`Tool ${X} not found`);return Yy$(H,Y)},Y}})}var Xy$=($)=>{try{return JSON.parse($)}catch{return $}},RX6=500,FR,Yy$=($,Z)=>{return{...$,id:$.name,inputSchema:$.inputSchema?QX($.inputSchema):void 0,outputSchema:$.outputSchema?QX($.outputSchema):void 0,execute:(Q)=>{return Z(Q.context,$.name)}}};var Gy$=L(()=>{rb$();Qy$();FR=new Map});function d80($){return Jy$($)}var Mx9;var Wy$=L(()=>{Gy$();Mx9=new Proxy({},{get($,Z){if(Z==="toJSON")return null;if(Z==="forConnection")return(Q)=>d80({connection:Q});if(Z==="forClient")return(Q)=>d80({client:Q});return globalThis[Z]}})});function vD0($){return{isImplementedBy:(Z)=>{for(let Q of $){let X=typeof Q.name==="string"?new RegExp(`^${Q.name}$`):Q.name,Y=Z.find((J)=>X.test(J.name));if(!Y&&Q.opt)continue;if(!Y)return!1}return!0}}}var BD=($)=>{return{...vD0($),forClient:(Z)=>{return d80({client:Z})},forConnection:(Z)=>{return d80({connection:Z})}}};var ui=L(()=>{Wy$()});import{z as ZZ}from"zod";var Ky$,Hy$,Fy$,Uy$,Ny$,MX6;var By$=L(()=>{ui();Ky$=ZZ.object({specversion:ZZ.literal("1.0").describe("CloudEvents specification version"),id:ZZ.string().describe("Unique identifier for this event (UUID recommended)"),source:ZZ.string().describe("Connection ID of the event publisher"),type:ZZ.string().describe("Event type (e.g., 'order.created', 'user.signup')"),time:ZZ.string().datetime().optional().describe("Timestamp of when the event occurred (ISO 8601)"),subject:ZZ.string().optional().describe("Subject/resource identifier (e.g., order ID, user ID)"),datacontenttype:ZZ.string().optional().default("application/json").describe("Content type of the data attribute"),dataschema:ZZ.string().url().optional().describe("URI to the schema for the data attribute"),data:ZZ.unknown().optional().describe("Event payload (any JSON value)")}),Hy$=ZZ.object({events:ZZ.array(Ky$).min(1).describe("Batch of CloudEvents to process")}),Fy$=ZZ.object({success:ZZ.boolean().optional().describe("Whether this event was processed successfully"),error:ZZ.string().optional().describe("Error message for this event"),retryAfter:ZZ.number().int().positive().optional().describe("Re-deliver this event after this many ms")}),Uy$=ZZ.object({success:ZZ.boolean().optional().describe("Batch success - applies to events not in results"),error:ZZ.string().optional().describe("Batch error message - applies to events not in results"),processedCount:ZZ.number().int().min(0).optional().describe("Number of events successfully processed"),retryAfter:ZZ.number().int().positive().optional().describe("Batch retryAfter - applies to events not in results"),results:ZZ.record(ZZ.string(),Fy$).optional().describe("Per-event results keyed by event ID")}),Ny$=[{name:"ON_EVENTS",inputSchema:Hy$,outputSchema:Uy$}],MX6=BD(Ny$)});import{z as QZ}from"zod";var Ly$,Dy$,Oy$,jy$,wy$,Ey$,xD0,GK1;var WK1=L(()=>{ui();Ly$=QZ.object({type:QZ.literal("string"),enum:QZ.array(QZ.string()).optional(),description:QZ.string().optional()}),Dy$=QZ.object({type:QZ.string(),description:QZ.string(),paramsSchema:QZ.record(QZ.string(),Ly$)}),Oy$=QZ.object({}),jy$=QZ.object({triggers:QZ.array(Dy$)}),wy$=QZ.object({type:QZ.string(),params:QZ.record(QZ.string(),QZ.string()),enabled:QZ.boolean(),callbackUrl:QZ.url().optional(),callbackToken:QZ.string().min(1).optional()}),Ey$=QZ.object({success:QZ.boolean()}),xD0=[{name:"TRIGGER_LIST",inputSchema:Oy$,outputSchema:jy$},{name:"TRIGGER_CONFIGURE",inputSchema:wy$,outputSchema:Ey$}],GK1=BD(xD0)});import{z as N8}from"zod";var IX6,VX6,kX6,CX6,SX6,_X6,vX6,xX6,fX6,bX6,yX6,gX6,UR;var i80=L(()=>{IX6=N8.object({prefix:N8.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:N8.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:N8.string().optional().describe("Token for pagination from previous response"),delimiter:N8.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),VX6=N8.object({objects:N8.array(N8.object({key:N8.string().describe("Object key/path"),size:N8.number().describe("Object size in bytes"),lastModified:N8.string().describe("Last modified timestamp"),etag:N8.string().describe("Entity tag for the object")})),nextContinuationToken:N8.string().optional().describe("Token for fetching next page of results"),isTruncated:N8.boolean().describe("Whether there are more results available"),commonPrefixes:N8.array(N8.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),kX6=N8.object({key:N8.string().describe("Object key/path to get metadata for")}),CX6=N8.object({contentType:N8.string().optional().describe("MIME type of the object"),contentLength:N8.number().describe("Size of the object in bytes"),lastModified:N8.string().describe("Last modified timestamp"),etag:N8.string().describe("Entity tag for the object"),metadata:N8.record(N8.string(),N8.string()).optional().describe("Custom metadata key-value pairs")}),SX6=N8.object({key:N8.string().describe("Object key/path to generate URL for"),expiresIn:N8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),_X6=N8.object({url:N8.string().describe("Presigned URL for downloading the object"),expiresIn:N8.number().describe("Expiration time in seconds that was used")}),vX6=N8.object({key:N8.string().describe("Object key/path for the upload"),expiresIn:N8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:N8.string().optional().describe("MIME type for the object being uploaded")}),xX6=N8.object({url:N8.string().describe("Presigned URL for uploading the object"),expiresIn:N8.number().describe("Expiration time in seconds that was used")}),fX6=N8.object({key:N8.string().describe("Object key/path to delete")}),bX6=N8.object({success:N8.boolean().describe("Whether the deletion was successful"),key:N8.string().describe("The key that was deleted")}),yX6=N8.object({keys:N8.array(N8.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),gX6=N8.object({deleted:N8.array(N8.string()).describe("Array of successfully deleted keys"),errors:N8.array(N8.object({key:N8.string(),message:N8.string()})).describe("Array of errors for failed deletions")}),UR=[{name:"LIST_OBJECTS",inputSchema:IX6,outputSchema:VX6},{name:"GET_OBJECT_METADATA",inputSchema:kX6,outputSchema:CX6},{name:"GET_PRESIGNED_URL",inputSchema:SX6,outputSchema:_X6},{name:"PUT_PRESIGNED_URL",inputSchema:vX6,outputSchema:xX6},{name:"DELETE_OBJECT",inputSchema:fX6,outputSchema:bX6},{name:"DELETE_OBJECTS",inputSchema:yX6,outputSchema:gX6}]});import{z as T5}from"zod";var zy$,Py$,Ty$,p80,fD0,bD0,yD0,gD0,hX6;var KK1=L(()=>{ui();zy$=T5.object({primary:T5.string().optional().describe("Primary brand color (hex)"),secondary:T5.string().optional().describe("Secondary brand color (hex)"),accent:T5.string().optional().describe("Accent / highlight color (hex)"),background:T5.string().optional().describe("Background color (hex)"),foreground:T5.string().optional().describe("Foreground / text color (hex)")}),Py$=T5.object({heading:T5.string().optional().describe("Font family for headings"),body:T5.string().optional().describe("Font family for body text"),code:T5.string().optional().describe("Font family for code / monospace")}),Ty$=T5.object({logo:T5.string().optional().describe("Logo URL"),favicon:T5.string().optional().describe("Favicon URL"),ogImage:T5.string().optional().describe("Open Graph image URL")}),p80=T5.object({id:T5.string(),name:T5.string().describe("Brand / company name"),domain:T5.string().optional().describe("Company domain (e.g. example.com)"),colors:zy$.optional().describe("Semantic color palette"),fonts:Py$.optional().describe("Font families by role"),assets:Ty$.optional().describe("Visual identity assets"),overview:T5.string().optional().describe("Company overview / description"),tagline:T5.string().optional().describe("Brand tagline"),tone:T5.string().optional().describe("Tone of voice description"),metadata:T5.record(T5.string(),T5.unknown()).optional().describe("Extra design tokens and metadata")}),fD0=T5.object({id:T5.string().optional().describe("Brand ID. Omit to get the default brand.")}),bD0=T5.object({}),yD0=T5.object({items:T5.array(p80)}),gD0=[{name:"BRAND_GET",inputSchema:fD0,outputSchema:p80},{name:"BRAND_LIST",inputSchema:bD0,outputSchema:yD0,opt:!0}],hX6=BD(gD0)});var Ay$=L(()=>{ui();By$();WK1();i80();KK1()});import{z as W4}from"zod";function li($){let Q=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,".");return new RegExp(`^${Q}$`,"i")}function LD($){return W4.object({items:W4.array($).describe("Array of collection items"),totalCount:W4.number().int().min(0).optional().describe("Total number of matching items (if available)"),hasMore:W4.boolean().optional().describe("Whether there are more items available")})}function t80($){return W4.object({item:$.nullable().describe("The retrieved item, or null if not found")})}function cX6($){return W4.object({data:$.partial().describe("Data for the new entity (id may be auto-generated)")})}function mX6($){return W4.object({item:$.describe("The created entity with generated id")})}function dX6($){return W4.object({id:W4.string().describe("ID of the entity to update"),data:$.partial().describe("Partial entity data to update")})}function iX6($){return W4.object({item:$.describe("The updated entity")})}function a80($){return W4.object({item:$.describe("The deleted entity")})}function uD0($,Z,Q){let X=$.toUpperCase(),Y=Q?.readOnly??!1,J=[{name:`COLLECTION_${X}_LIST`,inputSchema:WF,outputSchema:LD(Z)},{name:`COLLECTION_${X}_GET`,inputSchema:n80,outputSchema:t80(Z)}];if(!Y)J.push({name:`COLLECTION_${X}_CREATE`,inputSchema:cX6(Z),outputSchema:mX6(Z),opt:!0},{name:`COLLECTION_${X}_UPDATE`,inputSchema:dX6(Z),outputSchema:iX6(Z),opt:!0},{name:`COLLECTION_${X}_DELETE`,inputSchema:o80,outputSchema:a80(Z),opt:!0});return J}var hD0,uX6,Ry$,lX6,WF,n80,o80;var GG=L(()=>{hD0=W4.object({id:W4.string().describe("Unique identifier for the entity"),title:W4.string().describe("Human-readable title for the entity"),description:W4.string().nullish().describe("Description of the entity"),created_at:W4.string().datetime(),updated_at:W4.string().datetime(),created_by:W4.string().optional(),updated_by:W4.string().optional()}),uX6=W4.object({field:W4.array(W4.string()),operator:W4.enum(["eq","gt","gte","lt","lte","in","like","contains"]),value:W4.unknown()}),Ry$=W4.lazy(()=>W4.union([uX6,W4.object({operator:W4.enum(["and","or","not"]),conditions:W4.array(Ry$)})]));lX6=W4.object({field:W4.array(W4.string()),direction:W4.enum(["asc","desc"]),nulls:W4.enum(["first","last"]).optional()}),WF=W4.object({where:Ry$.optional().describe("Filter expression"),orderBy:W4.array(lX6).optional().describe("Sort expressions"),limit:W4.number().int().min(1).max(1000).optional().describe("Maximum number of items to return"),offset:W4.number().int().min(0).optional().describe("Number of items to skip")});n80=W4.object({id:W4.string().describe("ID of the entity to retrieve")});o80=W4.object({id:W4.string().describe("ID of the entity to delete")})});import{z as ci}from"zod";var pX6,nX6,qy$;var My$=L(()=>{GG();pX6=hD0.extend({avatar:ci.string().describe("URL or data URI to the assistant's avatar image"),system_prompt:ci.string().describe("System prompt that defines the assistant's behavior"),virtual_mcp_id:ci.string().describe("Virtual MCP ID to use for this assistant"),model:ci.object({id:ci.string().describe("Model ID"),connectionId:ci.string().describe("Connection ID that provides the model")}).describe("Selected model reference for this assistant")}),nX6=uD0("assistant",pX6),qy$=[...nX6]});import{z as j0}from"zod";var r80,DD,Vy$,tX6,oX6,ky$,aX6,rX6,sX6,eX6,$Y6,ZY6,Cy$,QY6,XY6,YY6,JY6,GY6,WY6,KY6,HY6,FY6,UY6,Xf9,NY6,Yf9,Iy$,BY6,LY6,lD0,Jf9;var Sy$=L(()=>{ui();GG();r80=j0.lazy(()=>j0.union([j0.null(),j0.string(),j0.number(),j0.boolean(),j0.record(j0.string(),r80),j0.array(r80)])),DD=j0.record(j0.string(),j0.record(j0.string(),r80)).optional().describe("Additional provider-specific options. Outer record keyed by provider name, inner by option key"),Vy$=j0.object({type:j0.literal("text"),text:j0.string().describe("The text content"),providerOptions:DD}),tX6=j0.object({type:j0.literal("text"),text:j0.string().describe("The text content"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),oX6=j0.string().describe("File data as URL string"),ky$=j0.object({type:j0.literal("file"),filename:j0.string().optional().describe("Optional filename of the file"),data:oX6,mediaType:j0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),providerOptions:DD}),aX6=j0.object({type:j0.literal("file"),mediaType:j0.string().describe("IANA media type of the file (e.g., image/png, audio/mp3)"),data:j0.string().describe("Generated file data as base64 encoded string")}),rX6=j0.object({type:j0.literal("reasoning"),text:j0.string().describe("The reasoning text"),providerOptions:DD}),sX6=j0.object({type:j0.literal("reasoning"),text:j0.string().describe("The reasoning text"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),eX6=j0.object({type:j0.literal("tool-call"),toolCallId:j0.string().describe("ID of the tool call, used to match with tool result"),toolName:j0.string().describe("Name of the tool being called"),input:j0.string().describe("Arguments of the tool call (JSON-serializable object matching tool input schema)"),providerExecuted:j0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerOptions:DD}),$Y6=j0.object({type:j0.literal("tool-call"),toolCallId:j0.string().describe("ID of the tool call"),toolName:j0.string().describe("Name of the tool being called"),input:j0.string().describe("Stringified JSON object with the tool call arguments"),providerExecuted:j0.boolean().optional().describe("Whether the tool call will be executed by the provider"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),ZY6=j0.union([j0.object({type:j0.literal("text"),value:j0.string()}),j0.object({type:j0.literal("json"),value:r80}),j0.object({type:j0.literal("error-text"),value:j0.string()}),j0.object({type:j0.literal("error-json"),value:r80}),j0.object({type:j0.literal("content"),value:j0.array(j0.union([j0.object({type:j0.literal("text"),text:j0.string().describe("Text content")}),j0.object({type:j0.literal("media"),data:j0.string().describe("Base-64 encoded media data"),mediaType:j0.string().describe("IANA media type")})]))}),j0.object({type:j0.literal("execution-denied"),reason:j0.string().optional()}),j0.string().describe("Raw or JSON-serialized output (e.g. from AI SDK mapToolResultOutput)")]),Cy$=j0.object({type:j0.literal("tool-result"),toolCallId:j0.string().describe("ID of the tool call that this result is associated with"),toolName:j0.string().describe("Name of the tool that generated this result"),output:ZY6.describe("Result of the tool call"),result:j0.unknown().describe("Unknown result of the tool call"),providerOptions:DD}),QY6=j0.object({type:j0.literal("tool-result"),toolCallId:j0.string().describe("ID of the tool call that this result is associated with"),toolName:j0.string().describe("Name of the tool that generated this result"),result:j0.any().describe("Result of the tool call (JSON-serializable)"),isError:j0.boolean().optional().describe("Whether the result is an error or error message"),providerExecuted:j0.boolean().optional().describe("Whether the tool result was generated by the provider"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),XY6=j0.union([j0.object({type:j0.literal("source"),sourceType:j0.literal("url"),id:j0.string().describe("The ID of the source"),url:j0.string().describe("The URL of the source"),title:j0.string().optional().describe("The title of the source"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")}),j0.object({type:j0.literal("source"),sourceType:j0.literal("document"),id:j0.string().describe("The ID of the source"),mediaType:j0.string().describe("IANA media type of the document (e.g., application/pdf)"),title:j0.string().describe("The title of the document"),filename:j0.string().optional().describe("Optional filename of the document"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata")})]),YY6=j0.object({role:j0.literal("system"),content:j0.string().describe("System message content"),providerOptions:DD}),JY6=j0.object({role:j0.literal("user"),content:j0.array(j0.union([Vy$,ky$])).describe("User message content parts (text or file)"),providerOptions:DD}),GY6=j0.object({role:j0.literal("assistant"),content:j0.array(j0.union([Vy$,ky$,rX6,eX6,Cy$])).describe("Assistant message content parts (text, file, reasoning, tool-call, or tool-result)"),providerOptions:DD}),WY6=j0.object({role:j0.literal("tool"),content:j0.array(Cy$).describe("Tool message content (tool results)"),providerOptions:DD}),KY6=j0.union([YY6,JY6,GY6,WY6]),HY6=j0.array(KY6).describe("A list of messages forming the prompt"),FY6=j0.object({prompt:HY6.describe("A language model prompt is a standardized prompt type (array of messages with roles: system, user, assistant, tool)"),maxOutputTokens:j0.number().optional().describe("Maximum number of tokens to generate"),temperature:j0.number().optional().describe("Temperature setting. The range depends on the provider and model"),topP:j0.number().optional().describe("Nucleus sampling parameter"),topK:j0.number().optional().describe("Only sample from the top K options for each subsequent token. Used to remove long tail low probability responses"),presencePenalty:j0.number().optional().describe("Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt"),frequencyPenalty:j0.number().optional().describe("Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases"),seed:j0.number().optional().describe("The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results"),stopSequences:j0.array(j0.string()).optional().describe("Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated"),responseFormat:j0.union([j0.object({type:j0.literal("text")}),j0.object({type:j0.literal("json"),schema:j0.any().optional().describe("JSON schema that the generated output should conform to"),name:j0.string().optional().describe("Name of output that should be generated"),description:j0.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:j0.array(j0.any()).optional().describe("The tools that are available for the model"),toolChoice:j0.any().optional().describe("Specifies how the tool should be selected. Defaults to 'auto'"),includeRawChunks:j0.boolean().optional().describe("Include raw chunks in the stream. Only applicable for streaming calls"),abortSignal:j0.any().optional().describe("Abort signal for cancelling the operation"),providerOptions:j0.any().optional().describe("Additional provider-specific options")}),UY6=j0.object({content:j0.array(j0.union([tX6,aX6,sX6,$Y6,QY6,XY6])).describe("Ordered content that the model has generated (text, tool-calls, reasoning, files, sources)"),finishReason:j0.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]).describe("Reason why generation stopped"),usage:j0.looseObject({inputTokens:j0.number().optional(),outputTokens:j0.number().optional(),totalTokens:j0.number().optional(),reasoningTokens:j0.number().optional()}).describe("Usage information for the language model call"),providerMetadata:j0.any().optional().describe("Additional provider-specific metadata"),request:j0.object({body:j0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:j0.object({id:j0.string().optional().describe("ID for the generated response"),timestamp:j0.iso.datetime().optional().describe("Timestamp for the start of the generated response"),modelId:j0.string().optional().describe("The ID of the response model that was used"),headers:j0.record(j0.string(),j0.string()).optional().describe("Response headers"),body:j0.any().optional().describe("Response HTTP body")}).optional().describe("Optional response information for telemetry and debugging"),warnings:j0.array(j0.any()).describe("Warnings for the call, e.g. unsupported settings")}),Xf9=j0.object({stream:j0.any().describe("ReadableStream of LanguageModelV2StreamPart"),request:j0.object({body:j0.any().optional().describe("Request HTTP body sent to the provider API")}).optional().describe("Optional request information for telemetry and debugging"),response:j0.object({headers:j0.record(j0.string(),j0.string()).optional().describe("Response headers")}).optional().describe("Optional response data")}),NY6=j0.object({supportedUrls:j0.record(j0.string(),j0.array(j0.string())).describe("Supported URL patterns by media type for the provider")}),Yf9=j0.object({modelId:j0.string().describe("The ID of the model"),logo:j0.string().nullable(),description:j0.string().nullable(),capabilities:j0.array(j0.string()),limits:j0.object({contextWindow:j0.number(),maxOutputTokens:j0.number()}).nullable(),costs:j0.object({input:j0.number(),output:j0.number()}).nullable(),provider:j0.enum(["openai","anthropic","google","x-ai","deepseek","openai-compatible","openrouter"]).nullable()}),Iy$=j0.object({modelId:j0.string().describe("The ID of the model"),callOptions:FY6}),BY6=hD0.extend({logo:j0.string().nullable(),description:j0.string().nullable(),capabilities:j0.array(j0.string()),limits:j0.object({contextWindow:j0.number(),maxOutputTokens:j0.number()}).nullable(),costs:j0.object({input:j0.number(),output:j0.number()}).nullable(),provider:j0.enum(["openai","anthropic","google","xai","deepseek","openai-compatible","openrouter"]).nullable()}),LY6=uD0("llm",BY6,{readOnly:!0}),lD0=[{name:"LLM_METADATA",inputSchema:j0.object({modelId:j0.string().describe("The ID of the model")}),outputSchema:NY6},{name:"LLM_DO_STREAM",inputSchema:Iy$},{name:"LLM_DO_GENERATE",inputSchema:Iy$,outputSchema:UY6},...LY6],Jf9=BD(lD0)});import{z as NR}from"zod";var DY6,_y$;var vy$=L(()=>{DY6=NR.object({scopes:NR.array(NR.string()).describe("List of scopes available"),stateSchema:NR.record(NR.string(),NR.unknown()).describe("JSON Schema (draft-07) defining the state structure")}),_y$=[{name:"MCP_CONFIGURATION",inputSchema:NR.object({}),outputSchema:DY6}]});import{z as XZ}from"zod";var OY6,jY6,xy$;var fy$=L(()=>{OY6=XZ.object({}).strict(),jY6=XZ.object({billing:XZ.object({mode:XZ.enum(["prepaid","postpaid"]),limitPeriod:XZ.enum(["daily","weekly","monthly"]).nullable()}),limit:XZ.object({total:XZ.number().nullable(),remaining:XZ.number().nullable(),reset:XZ.string().nullable()}),usage:XZ.object({total:XZ.number(),daily:XZ.number(),weekly:XZ.number(),monthly:XZ.number()}),alert:XZ.object({enabled:XZ.boolean(),threshold_usd:XZ.number(),email:XZ.string().nullable()}),connectionId:XZ.string()}),xy$=[{name:"GATEWAY_USAGE",inputSchema:OY6,outputSchema:jY6},{name:"GATEWAY_SET_LIMIT",inputSchema:XZ.object({}),outputSchema:XZ.object({}),opt:!0},{name:"GATEWAY_SET_ALERT",inputSchema:XZ.object({}),outputSchema:XZ.object({}),opt:!0}]});import{z as by$}from"zod";function FK(){return yQ()===null}function cD0($,Z){return $===K4.DEV_ASSETS(Z)}function mD0($,Z){let Q=aF$(Z,$),X=new Date().toISOString();return{id:Q.id??K4.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:X,updated_at:X,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:wY6,bindings:["OBJECT_STORAGE"],status:"active"}}var wY6;var mi=L(()=>{NL();i80();r8();wY6=UR.map(($)=>({name:$.name,description:`${$.name} operation for local file storage`,inputSchema:by$.toJSONSchema($.inputSchema),outputSchema:by$.toJSONSchema($.outputSchema)}))});function yy$($,Z){return $||Z===0}function gy$($,Z,Q,X,Y){let J=Z?Y+1:Y,G=$.slice(0,Q),W=X+Q<J;return{items:G,totalCount:J,hasMore:W}}function hy$($,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 EY6($,Z){if(Z.length===0)return;let[Q,...X]=Z,Y=Q==="slug"?Gw($):$[Q];for(let J of X){if(Y===null||typeof Y!=="object")return;Y=Y[J]}return Y}function zY6($,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"&&li(String(Q)).test($);case"contains":return String($).toLowerCase().includes(String(Q).toLowerCase());default:return!0}}function s80($,Z){if(!Z)return!0;if("conditions"in Z){let{operator:X,conditions:Y}=Z;if(Y.length===0)return!0;switch(X){case"and":return Y.every((J)=>s80($,J));case"or":return Y.some((J)=>s80($,J));case"not":return!Y.every((J)=>s80($,J));default:return!0}}let Q=EY6($,Z.field);return zY6(Q,Z.operator,Z.value)}var uy$=L(()=>{gH0();GG()});import{z as mE}from"zod";var PY6=8,TY6,AY6,RY6,qY6,BR;var HK1=L(()=>{Ay$();My$();GG();Sy$();vy$();i80();fy$();r8();_0();A9();JG();yi();mi();TU();gH0();uy$();TY6=[{name:/^(COLLECTION_REGISTRY_APP_LIST|REGISTRY_ITEM_LIST)$/,inputSchema:mE.object({})}],AY6={LLM:lD0,LLMS:lD0,ASSISTANTS:qy$,MCP:_y$,OBJECT_STORAGE:UR,AI_GATEWAY_BILLING:xy$,TRIGGER:xD0,REGISTRY:TY6,BRAND:gD0},RY6=WF.extend({binding:mE.union([mE.array(mE.object({}).passthrough()),mE.object({}).passthrough(),mE.string()]).optional(),include_virtual:mE.boolean().optional().describe("Whether to include VIRTUAL connections in the results. Defaults to false."),slug:mE.string().optional().describe("Filter by connection slug. Matches against app_name, or a slug derived from connection_url or title.")}),qY6=LD(CX),BR=m({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:RY6,outputSchema:qY6,handler:async($,Z)=>{await Z.access.check();let Q=W0(Z),X=$.binding?typeof $.binding==="string"?(()=>{let w=AY6[$.binding.toUpperCase()];if(!w)throw Error(`Unknown binding: ${$.binding}`);return w})():$.binding:void 0,Y=X?vD0(X):void 0,J=!!Y,G=$.limit??100,W=$.offset??0,K=g9(),H=K4.DEV_ASSETS(Q.id),F=mD0(Q.id,K),U=(!$.slug||Gw(F)===$.slug)&&s80(F,$.where),N=FK()&&!J&&U,{sqlOffset:B,sqlLimit:D}=hy$(W,G,N),{items:O,totalCount:j}=await Z.storage.connections.list(Q.id,{includeVirtual:$.include_virtual??!1,slug:$.slug,where:$.where,orderBy:$.orderBy,limit:J?void 0:D,offset:J?void 0:B});if(Y){let w=VZ(),E=K4.SELF(Q.id);await cd(O,PY6,async(z)=>{if(z.tools!==null)return;let A=z.id===E?async()=>{let{listManagementTools:T}=await Promise.resolve().then(() => (dE(),dD0));return T(Z)}:()=>v80(z,Z,lc),P=await hE("tools",z.id,A,w,(T)=>Z.pendingRevalidations.push(T),gE);if(P!==null)z.tools=P})}if(FK()&&yy$(J,W)&&U&&!O.some((w)=>w.id===H))O.unshift(F);if(J){let w=(await Promise.all(O.map(async(P)=>{if(!P.tools||P.tools.length===0)return null;return Y.isImplementedBy(P.tools.map((q)=>({name:q.name,inputSchema:q.inputSchema,outputSchema:q.outputSchema})))?P:null}))).filter((P)=>P!==null),E=w.length,z=w.slice(W,W+G),A=W+G<E;return{items:z,totalCount:E,hasMore:A}}return gy$(O,N,G,W,j)}})});var MY6,LR;var FK1=L(()=>{GG();r8();_0();A9();JG();yi();mi();TU();MY6=t80(CX),LR=m({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:n80,outputSchema:MY6,handler:async($,Z)=>{let Q=W0(Z);if(await Z.access.check(),FK()&&cD0($.id,Q.id))return{item:mD0(Q.id,g9())};let X=await Z.storage.connections.findById($.id);if(!X||X.organization_id!==Q.id)return{item:null};if(X.tools===null){let Y=K4.SELF(Q.id),J=X.id===Y?async()=>{let{listManagementTools:W}=await Promise.resolve().then(() => (dE(),dD0));return W(Z)}:()=>v80(X,Z,lc),G=await hE("tools",X.id,J,VZ(),(W)=>Z.pendingRevalidations.push(W),gE);if(G!==null)X.tools=G}return{item:X}}})});class V9{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 IY6(this.vault,Z)}async upsert($){let Z=new Date().toISOString(),Q=await this.vault.encrypt($.accessToken),X=$.refreshToken?await this.vault.encrypt($.refreshToken):null,Y=$.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:X,scope:$.scope,expiresAt:J,clientId:$.clientId,clientSecret:Y,tokenEndpoint:$.tokenEndpoint,createdAt:Z,updatedAt:Z}).onConflict((W)=>W.column("connectionId").doUpdateSet({accessToken:Q,refreshToken:X,scope:$.scope,expiresAt:J,clientId:$.clientId,clientSecret:Y,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 X=($.expiresAt instanceof Date?$.expiresAt:new Date($.expiresAt)).getTime();if(Number.isNaN(X))return!0;return X-Z<Date.now()}}async function IY6($,Z){try{let Q=await $.decrypt(Z.accessToken),X=Z.refreshToken?await $.decrypt(Z.refreshToken):null,Y=Z.clientSecret?await $.decrypt(Z.clientSecret):null;return{id:Z.id,connectionId:Z.connectionId,accessToken:Q,refreshToken:X,scope:Z.scope,expiresAt:Z.expiresAt,createdAt:Z.createdAt,updatedAt:Z.updatedAt,clientId:Z.clientId,clientSecret:Y,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 KF=L(()=>{SX()});function di(...$){if(SY6)console.log("[mcp-read-cache]",...$)}function _Y6($){return $.kind==="org"?"org":`u:${$.userId}`}function UK1($){if($===null||typeof $!=="object")return JSON.stringify($)??"null";if(Array.isArray($))return`[${$.map(UK1).join(",")}]`;return`{${Object.keys($).sort().map((Q)=>`${JSON.stringify(Q)}:${UK1($[Q])}`).join(",")}}`}class nD0{config;maxEntries;now;maxTotalBytes;store=new Map;revalidating=new Set;totalBytes=0;byConnection=new Map;constructor($=VY6,Z=kY6,Q=()=>Date.now(),X=CY6){this.config=$;this.maxEntries=Z;this.now=Q;this.maxTotalBytes=X}stats(){return{entries:this.store.size,bytes:this.totalBytes}}deleteKey($){let Z=this.store.get($);if(Z){this.store.delete($),this.totalBytes-=Z.bytes;let Q=this.byConnection.get(Z.connectionId);if(Q){if(Q.delete($),Q.size===0)this.byConnection.delete(Z.connectionId)}}}key($,Z,Q,X){return`${Z}:${_Y6(Q)}:${$}:${UK1(X)}`}storeSet($,Z,Q,X,Y){let J;try{J=JSON.stringify(Q).length}catch{di("SKIP non-serializable",$);return}if(J>Y){di("SKIP oversize",$,`${J}b > cap ${Y}b`);return}this.deleteKey($);while(this.store.size>0&&(this.store.size>=this.maxEntries||this.totalBytes+J>this.maxTotalBytes)){let W=this.store.keys().next().value;if(W===void 0)break;this.deleteKey(W)}this.store.set($,{value:Q,storedAt:X,bytes:J,connectionId:Z}),this.totalBytes+=J;let G=this.byConnection.get(Z);if(!G)G=new Set,this.byConnection.set(Z,G);G.add($)}async fetch($){let{type:Z,connectionId:Q,scope:X,params:Y,fetchLive:J,shouldCache:G,onRevalidation:W}=$,K=this.config[Z],H=this.key(Z,Q,X,Y),F=this.now(),U=this.store.get(H),N=U?F-U.storedAt:1/0;if(!U||N>K.maxStaleMs){iD0.add(1,{type:Z,outcome:"miss"}),di(U?"EXPIRED":"MISS",H);let B=await J();if(G?.(B)??!0)this.storeSet(H,Q,B,this.now(),K.maxValueBytes);else di("NOT-CACHED (shouldCache=false)",H);return B}if(this.store.delete(H),this.store.set(H,U),N>K.revalidateAfterMs&&!this.revalidating.has(H)){iD0.add(1,{type:Z,outcome:"stale"}),di("STALE \u2192 serve + revalidate",H,`age=${N}ms`),this.revalidating.add(H);let B=J().then((D)=>{if(G?.(D)??!0)this.storeSet(H,Q,D,this.now(),K.maxValueBytes)}).catch(()=>{iD0.add(1,{type:Z,outcome:"error"})}).finally(()=>this.revalidating.delete(H));W?.(B)}else iD0.add(1,{type:Z,outcome:"hit"}),di("HIT",H,`age=${N}ms`);return U.value}invalidate($){let Z=this.byConnection.get($);if(!Z)return;for(let Q of[...Z])this.deleteKey(Q)}}function BK1(){return P0().mcpCacheEnabled}function tD0(){return BK1()?NK1:null}var iD0,pD0=1024,ly$,VY6,kY6=2000,CY6,SY6,NK1;var e80=L(()=>{f6();X$();iD0=Y$.createCounter("mcp_read_cache.fetches",{description:"MCP read cache outcomes (hit, stale, miss, error)",unit:"{fetches}"}),ly$=pD0*pD0,VY6={"tools/call":{revalidateAfterMs:30000,maxStaleMs:300000,maxValueBytes:512*pD0},"resources/read":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:4*ly$},"prompts/get":{revalidateAfterMs:60000,maxStaleMs:300000,maxValueBytes:512*pD0}},CY6=256*ly$,SY6=typeof process<"u"&&!!process.env?.MCP_CACHE_DEBUG;NK1=new nD0;Y$.createObservableGauge("mcp_read_cache.entries",{description:"Current entry count in the per-pod MCP read cache",unit:"{entries}"}).addCallback(($)=>$.observe(NK1.stats().entries));Y$.createObservableGauge("mcp_read_cache.bytes",{description:"Approximate total bytes held in the per-pod MCP read cache",unit:"By"}).addCallback(($)=>$.observe(NK1.stats().bytes))});function iy$(){if(cy$)return;cy$=!0;try{my$=Y$.createCounter("virtual_mcp.aggregate_cache.lookups",{description:"Virtual MCP aggregate tool-list cache lookups by outcome (hit, miss, expired)",unit:"{lookups}"}),dy$=Y$.createCounter("virtual_mcp.aggregate_cache.evictions",{description:"Virtual MCP aggregate tool-list cache entries dropped, by reason (capacity, invalidated, failed)",unit:"{entries}"}),Y$.createObservableGauge("virtual_mcp.aggregate_cache.entries",{description:"Live entries in this pod's Virtual MCP aggregate tool-list cache",unit:"{entries}"}).addCallback(($)=>$.observe(UK.size))}catch($){console.error("[aggregate-cache] failed to register metrics:",$)}}function LK1($){iy$(),my$?.add(1,{outcome:$})}function DK1($,Z=1){if(Z<=0)return;iy$(),dy$?.add(Z,{reason:$})}function py$($){return[$.virtualMcpId??"",$.userId??"",$.superUser?"su":"",[...$.connectionIds].sort().join(",")].join("|")}function ny$($){let Z=UK.get($);if(!Z)return LK1("miss"),null;if(Date.now()-Z.at>=vY6)return UK.delete($),LK1("expired"),null;return LK1("hit"),Z.value}function ty$($,Z,Q){let X=Q.catch((J)=>{if(UK.get($)?.value===X)UK.delete($),DK1("failed");throw J});UK.delete($),UK.set($,{at:Date.now(),deps:Z,value:X});let Y=0;while(UK.size>xY6){let J=UK.keys().next();if(J.done)break;UK.delete(J.value),Y++}return DK1("capacity",Y),X}function oy$($){let Z=0;for(let[Q,X]of UK)if(X.deps.includes($))UK.delete(Q),Z++;DK1("invalidated",Z)}var vY6=30000,xY6=500,UK,my$=null,dy$=null,cy$=!1;var OK1=L(()=>{f6();UK=new Map});function sy$($){tD0()?.invalidate($),gb$($),oy$($)}function ii($){sy$($);let Z=jK1?.();if(!Z)return;try{Z.publish(ay$,fY6.encode(JSON.stringify({connectionId:$,originId:ry$})))}catch(Q){console.warn("[McpCacheInvalidation] publish failed (non-critical):",Q)}}function ey$($){if(jK1=$,$40)return;let Z=$();if(!Z)return;$40=Z.subscribe(ay$),(async()=>{for await(let Q of $40)try{let X=JSON.parse(bY6.decode(Q.data));if(X.originId===ry$)continue;sy$(X.connectionId)}catch{}})().catch(console.error)}function $g$(){$40?.unsubscribe(),$40=null,jK1=void 0}var ay$="studio.mcp-cache.invalidate",ry$,fY6,bY6,jK1,$40=null;var Z40=L(()=>{e80();JG();OK1();ry$=crypto.randomUUID(),fY6=new TextEncoder,bY6=new TextDecoder});import{z as wK1}from"zod";function gY6($){let Z={...$};for(let Q of yY6)delete Z[Q];return Z}function hY6($,Z){return $.connection_url!==void 0?$.connection_url:Z}function cY6($,Z){return $.length===Z.length&&$.every((Q,X)=>Q===Z[X])}var yY6,uY6,lY6,EK1;var Zg$=L(()=>{MD0();KF();_0();X$();JG();Z40();QK1();zB0();TU();yY6=["id","organization_id","created_by","created_at"];uY6=wK1.object({id:wK1.string().describe("ID of the connection to update"),data:kH0.describe("Partial connection data to update")}),lY6=wK1.object({item:CX.describe("The updated connection entity")});EK1=m({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:uY6,outputSchema:lY6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to update connection");let{id:Y}=$,J=gY6($.data),G=J.configuration_state!==void 0||J.configuration_scopes!==void 0,W=await Z.storage.connections.findById(Y);if(!W||W.organization_id!==Q.id)throw Error("Connection not found in organization");let K=J.connection_type??W.connection_type,H=hY6(J,W.connection_url);if(K==="VIRTUAL"){let u=bc(H);if(!u)throw Error("VIRTUAL connection requires connection_url in format: virtual://$virtual_mcp_id");let g=await Z.storage.virtualMcps.findById(u);if(!g)throw Error(`Virtual MCP not found: ${u}`);if(g.organization_id!==Q.id)throw Error("Virtual MCP does not belong to the current organization");H=yc(u)}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 u=F;u80(u,U,Q.id),await c80(u,U,Q.id,Z)}}if(K==="STDIO"&&!P0().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 V9(Z.db,Z.vault).get(Y);if(g?.accessToken)N=g.accessToken}catch{}let B=await ld({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),D=B?.tools?.length?B.tools:null,O=!1;if(J.configuration_scopes===void 0&&B?.scopes?.length)O=!cY6(U,B.scopes),U=B.scopes;if(u80(F,U,Q.id),O&&U.length>0)await c80(F,U,Q.id,Z);let j=G||O,w=j?l80(F,U):[],E=j?l80(W.configuration_state??{},W.configuration_scopes??[]):[],z=W.configuration_state,A=z==null||Object.keys(z).length===0,P,T,q=async()=>{try{await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:Y,createdBy:X,grants:E})}catch(u){console.error("Failed to restore credential grants after credential vault mutation failed",u)}},f={...J,connection_url:H,tools:null,configuration_state:F,configuration_scopes:U,updated_by:X},S={...W,...f};if(j)try{if(await Z.storage.connectionCredentialVault.replaceGrantsForSubject({organizationId:Q.id,subjectConnectionId:Y,createdBy:X,grants:w}),w.length>0){if(!await Z.storage.connectionCredentialVault.findActiveWorkloadToken({organizationId:Q.id,subjectConnectionId:Y})){let{plaintextToken:g,record:l}=await Z.storage.connectionCredentialVault.createOrRotateWorkloadToken({organizationId:Q.id,subjectConnectionId:Y});T=l.id,P={baseUrl:Z.baseUrl,org:Q.slug??Q.id,subjectConnectionId:Y,token:g}}}}catch(u){if(T)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:Y,tokenId:T});throw await q(),u}if(j&&F&&U)try{await gi(Z,S,{state:F,scopes:U,firstRun:A,...P?{vault:P}:{}})}catch(u){if(console.error("Failed to invoke ON_MCP_CONFIGURATION callback",u),T)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:Y,tokenId:T});if(w.length>0)throw await q(),u}let V;try{V=await Z.storage.connections.update(Y,f)}catch(u){if(j){if(T)await Z.storage.connectionCredentialVault.revokeWorkloadToken({organizationId:Q.id,subjectConnectionId:Y,tokenId:T});await q()}throw u}if(D)VZ()?.set("tools",Y,D).catch(()=>{});return ii(Y),{item:V}}})});import{z as mY6}from"zod";var dY6,zK1;var Qg$=L(()=>{GG();r8();F6();VD0();_0();JG();Z40();NK();mi();TU();dY6=o80.extend({force:mY6.boolean().optional().describe("If true, removes this connection from all agents that reference it before deleting")}),zK1=m({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:dY6,outputSchema:a80(CX),handler:async($,Z)=>{o(Z);let Q=W0(Z);if(await Z.access.check(),FK()&&cD0($.id,Q.id))throw Error("This connection is a fixed system connection and cannot be deleted");let X=await Z.storage.connections.findById($.id);if(!X)throw Error(`Connection not found: ${$.id}`);if(X.organization_id!==Q.id)throw Error("Connection not found in organization");let Y=X.metadata;if(Y?.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)}));if(await Z.storage.connections.delete($.id),$.id===K4.REPORTS(Q.id)&&typeof Y?.siteUrl==="string")hi({siteUrl:Y.siteUrl,orgId:Q.id,cause:"connection_deleted"});Xg$($.id),await Z.storage.triggerCallbackTokens.deleteByConnection($.id,Q.id),VZ()?.invalidate($.id).catch(()=>{}),ii($.id);let W=t0(Z);if(W)h1.capture({distinctId:W,event:"connection_deleted",groups:{organization:Q.id},properties:{connection_id:X.id,connection_type:X.connection_type,app_name:X.app_name??null,organization_id:Q.id,forced:$.force??!1}});return{item:X}}})});import{z as pi}from"zod";var PK1;var Yg$=L(()=>{_0();PK1=m({name:"CONNECTION_TEST",description:"Test connection health and latency",annotations:{title:"Test Connection",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:pi.object({id:pi.string()}),outputSchema:pi.object({id:pi.string(),healthy:pi.boolean(),latencyMs:pi.number()}),handler:async($,Z)=>{let Q=W0(Z);await Z.access.check();let X=await Z.storage.connections.findById($.id);if(!X||X.organization_id!==Q.id)throw Error("Connection not found");let Y=await Z.storage.connections.testConnection($.id);return{id:$.id,...Y}}})});var Jg$=L(()=>{nb$();HK1();FK1();Zg$();Qg$();Yg$()});import{sql as R6}from"kysely";import{z as zN}from"zod";function Gg$($){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 nY6($,Z){let Q="",X=0,Y=!1,J=!1,G=!1,W=null;for(let K=0;K<$.length;K++){let H=$[K];if(!Y&&!J&&W===null){if($.startsWith("--",K)){let F=$.indexOf(`
|
|
3119
3119
|
`,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(Y&&G&&H==="\\"&&K+1<$.length){Q+=H+$[K+1],K+=1;continue}if(!J&&H==="'"){if(!Y){let F=$[K-1],U=$[K-2]??"";G=(F==="e"||F==="E")&&!/[A-Za-z0-9_]/.test(U)}Y=!Y,Q+=H;continue}if(!Y&&H==='"'){J=!J,Q+=H;continue}if(!Y&&!J&&H==="$"){let F=/^\$(\d+)/.exec($.slice(K)),U=F?Number(F[1])-1:-1;if(F&&U>=0&&U<Z.length){Q+=Gg$(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(!Y&&!J&&H==="?"&&X<Z.length){Q+=Gg$(Z[X]),X++;continue}Q+=H}return Q}function Wg$($){return $.replace(/-/g,"_")}function oY6($){return`app_${Wg$($)}`}function aY6($){return`app_role_${Wg$($)}`}function rY6($){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 sY6($,Z,Q){if(await R6`CREATE SCHEMA IF NOT EXISTS ${R6.id(Z)}`.execute($),!(await R6`
|
|
3120
3120
|
SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${Q}) as exists
|
|
3121
3121
|
`.execute($)).rows[0]?.exists)await R6`CREATE ROLE ${R6.id(Q)} NOLOGIN`.execute($);await R6`GRANT ${R6.id(Q)} TO CURRENT_USER`.execute($),await R6`GRANT USAGE, CREATE ON SCHEMA ${R6.id(Z)} TO ${R6.id(Q)}`.execute($),await R6`GRANT ALL ON ALL TABLES IN SCHEMA ${R6.id(Z)} TO ${R6.id(Q)}`.execute($),await R6`GRANT ALL ON ALL SEQUENCES IN SCHEMA ${R6.id(Z)} TO ${R6.id(Q)}`.execute($),await R6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${R6.id(Z)} GRANT ALL ON TABLES TO ${R6.id(Q)}`.execute($),await R6`ALTER DEFAULT PRIVILEGES IN SCHEMA ${R6.id(Z)} GRANT ALL ON SEQUENCES TO ${R6.id(Q)}`.execute($),await R6`REVOKE ALL ON SCHEMA public FROM ${R6.id(Q)}`.execute($)}async function eY6($,Z,Q,X){try{return await $.transaction().execute(async(Y)=>{return await R6`SET LOCAL ROLE ${R6.id(Q)}`.execute(Y),await R6`SET LOCAL search_path TO ${R6.id(Z)}`.execute(Y),await R6.raw(X).execute(Y)})}catch(Y){if(rY6(Y))return await sY6($,Z,Q),await $.transaction().execute(async(J)=>{return await R6`SET LOCAL ROLE ${R6.id(Q)}`.execute(J),await R6`SET LOCAL search_path TO ${R6.id(Z)}`.execute(J),await R6.raw(X).execute(J)});throw Y}}var pY6,tY6,Kg$;var Hg$=L(()=>{_0();pY6=zN.object({results:zN.array(zN.unknown()).optional(),success:zN.boolean().optional()});tY6=zN.object({sql:zN.string().describe("The SQL query to run"),params:zN.array(zN.unknown()).describe("The parameters to pass to the SQL query").optional()});Kg$=m({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:tY6,outputSchema:zN.object({result:zN.array(pY6)}),handler:async($,Z)=>{o(Z),await Z.access.check();let Q=nY6($.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 X=oY6(Z.connectionId),Y=aY6(Z.connectionId);return{result:[{results:(await eY6(Z.db,X,Y,Q)).rows,success:!0}]}}})});function oD0($){let Z=$.access.getRole();if(!mZ(Z))throw new HQ("Only organization owners and admins can change org-wide pin status")}var TK1=L(()=>{fX();vH()});async function aD0($,Z,Q){let X=[...new Set(Q)],Y=await Promise.all(X.map((G)=>$.storage.connections.findById(G,Z))),J=X.filter((G,W)=>!Y[W]);if(J.length>0)throw Error(`Connection not found: ${J.join(", ")}`)}function OD($){return $.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function rD0($){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 sD0($){if($&&typeof $==="object"&&"gatewayClientId"in $&&typeof $.gatewayClientId==="string")return $.gatewayClientId;return}function eD0($,Z){if(!Z)return $;let Q=`${rD0(Z)}_`;return $.startsWith(Q)?$.slice(Q.length):$}function ZJ6($){return $.split(/[-_]/).map((Z)=>Z?Z.charAt(0).toUpperCase()+Z.slice(1):Z).join(" ")}function QJ6($,Z,Q){let X,Y=new Promise((J,G)=>{X=setTimeout(()=>G(Error(Q)),Z)});return Promise.race([$,Y]).finally(()=>clearTimeout(X))}var DR;var Fg$=L(()=>{bU();DR=class DR extends K7{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??DR.DEFAULT_LIST_TIMEOUT_MS;for(let Q of Object.keys($)){let X=rD0(Q);if(this.slugToKey.has(X))throw Error(`GatewayClient: duplicate namespace code "${X}" from keys "${this.slugToKey.get(X)}" and "${Q}"`);this.slugToKey.set(X,Q)}}namespace($,Z){return`${rD0($)}_${Z}`}async resolveNamespacedTarget($,Z,Q){let X=$.indexOf("_");if(X!==-1){let Y=$.slice(0,X),J=this.slugToKey.get(Y);if(J)return[J,$.slice(X+1)]}for(let Y of await Q()){let J=sD0(Y._meta);if(!J)continue;if(eD0(Y.name,J)===$)return[J,$]}if(X===-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,X)}" 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 X=Q.client,Y;try{Y=typeof X==="function"?Promise.resolve(X()):Promise.resolve(X)}catch(G){return Promise.reject(G)}let J=Y.catch((G)=>{throw this.resolvedClients.delete($),G});return this.resolvedClients.set($,J),J}getResolvedClient($){return this.resolveClient($)}async listFromClient($,Z,Q){try{return await QJ6((async()=>{let X=await this.resolveClient($);return await Z(X)})(),this.listTimeoutMs,`timed out after ${this.listTimeoutMs}ms`)}catch(X){return console.warn(`GatewayClient: skipping ${Q} from client "${$}" \u2014 ${X?.message??X}`),[]}}listFromAllClients($,Z){return Promise.all(Object.entries(this.clients).map(async([Q,X])=>[Q,X,await this.listFromClient(Q,(Y)=>$(Y,Q),Z)]))}async paginate($,Z,Q){let X=[],Y,J=0;do{let G=await Q(Y);X.push(...G.items),Y=G.nextCursor,J++}while(Y&&J<DR.MAX_PAGES_PER_CLIENT);if(Y)console.warn(`GatewayClient: client "${$}" exceeded ${DR.MAX_PAGES_PER_CLIENT} pages listing ${Z} \u2014 truncating`);return X}fetchAllTools($,Z){return this.paginate(Z,"tools",async(Q)=>{let X=await $.listTools(Q?{cursor:Q}:void 0);return{items:X.tools,nextCursor:X.nextCursor}})}fetchAllResources($,Z){return this.paginate(Z,"resources",async(Q)=>{let X=await $.listResources(Q?{cursor:Q}:void 0);return{items:X.resources,nextCursor:X.nextCursor}})}fetchAllResourceTemplates($,Z){return this.paginate(Z,"resource templates",async(Q)=>{let X=await $.listResourceTemplates(Q?{cursor:Q}:void 0);return{items:X.resourceTemplates,nextCursor:X.nextCursor}})}fetchAllPrompts($,Z){return this.paginate(Z,"prompts",async(Q)=>{let X=await $.listPrompts(Q?{cursor:Q}:void 0);return{items:X.prompts,nextCursor:X.nextCursor}})}listTools($,Z){if(!this.toolsCache)this.toolsCache=this.aggregateTools();return this.toolsCache}async aggregateTools(){let $=[],Z=await this.listFromAllClients((Q,X)=>this.fetchAllTools(Q,X),"tools");for(let[Q,X,Y]of Z){let J=X.tools,G=J?new Set(J):null;for(let W of Y){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,X=await this.listFromAllClients((Y,J)=>this.fetchAllResources(Y,J),"resources");for(let[Y,J,G]of X){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 "${Y}" \u2014 skipping`);continue}$.add(H.uri),Q.set(H.uri,Y),Z.push({...H,_meta:{...H._meta??{},gatewayClientId:Y}})}}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((X,Y)=>this.fetchAllResourceTemplates(X,Y),"resource templates");for(let[X,Y,J]of Q)for(let G of J){if($.has(G.uriTemplate)){console.warn(`GatewayClient: duplicate resource template "${G.uriTemplate}" from client "${X}" \u2014 skipping`);continue}$.add(G.uriTemplate),Z.push({...G,_meta:{...G._meta??{},gatewayClientId:X}})}return{resourceTemplates:Z}}listPrompts($,Z){if(!this.promptsCache)this.promptsCache=this.aggregatePrompts();return this.promptsCache}async aggregatePrompts(){let $=[],Z=await this.listFromAllClients((Q,X)=>this.fetchAllPrompts(Q,X),"prompts");for(let[Q,X,Y]of Z){let J=X.prompts,G=J?new Set(J):null;for(let W of Y){if(G&&!G.has(W.name))continue;$.push({...W,name:this.namespace(Q,W.name),title:W.title??ZJ6(W.name),_meta:{...W._meta??{},gatewayClientId:Q}})}}return{prompts:$}}async callTool($,Z,Q){let[X,Y]=await this.resolveToolTarget($.name);return(await this.resolveClient(X)).callTool({...$,name:Y},Z,Q)}async readResource($,Z){let Q=await this.resolveResourceRoute($.uri);return(await this.resolveClient(Q)).readResource($)}async getPrompt($,Z){let[Q,X]=await this.resolvePromptTarget($.name);return(await this.resolveClient(Q)).getPrompt({...$,name:X})}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 $O0=L(()=>{Fg$()});function RK1($){return OD($)}function YJ6($,Z){let Q=OD(Z)||"prompt";return`${String($).padStart(XJ6,"0")}-${Q}`}async function qK1($,Z,Q){try{await $.delete(ZO0,RK1(Z),{actor:Q})}catch(X){console.error("[agent-prompts] failed to delete prompts",{agentId:Z,err:X})}}async function QO0($,Z,Q,X){let Y=RK1(Z);await qK1($,Z,Q),await Promise.all(X.slice(0,AK1).map(async(J,G)=>{let W=YJ6(G,J.title),K={name:W,title:J.title,description:J.description,text:J.text};try{await $.write(ZO0,`${Y}/${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 Ug$($,Z){let Q=RK1(Z),X;try{X=await $.listDir(ZO0,Q)}catch{return[]}let Y=X.filter((G)=>G.kind==="file"&&G.path.endsWith(".json")).slice(0,AK1),J=[];for(let G of Y)try{let W=await $.read(ZO0,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 ZO0="agent-prompts",AK1=20,XJ6;var Q40=L(()=>{$O0();XJ6=String(AK1-1).length});function ni($){if(!$)return $;let Z={...$};return delete Z.sandboxMap,Z}import{z as Lg$}from"zod";function JJ6(){let $=Ng$[Math.floor(Math.random()*Ng$.length)];return`icon://${Bg$[Math.floor(Math.random()*Bg$.length)]}?color=${$}`}var Ng$,Bg$,GJ6,WJ6,OR;var MK1=L(()=>{_0();cE();TK1();Q40();Ng$=["red","orange","amber","yellow","lime","green","emerald","cyan","sky","blue","indigo","violet","purple","fuchsia","pink","rose"],Bg$=["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"];GJ6=Lg$.object({data:FH0.describe("Data for the new virtual MCP")}),WJ6=Lg$.object({item:kX.describe("The created virtual MCP entity")}),OR=m({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:GJ6,outputSchema:WJ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to create virtual MCP");if($.data.pinned===!0)oD0(Z);let{prompts:Y,metadata:J,...G}=$.data,W=ni(J);if(G.connections.length>0)await aD0(Z,Q.id,G.connections.map((F)=>F.connection_id));let K={...G,metadata:W,icon:G.icon??JJ6()},H=await Z.storage.virtualMcps.create(Q.id,X,K);if(Y?.length&&Z.orgFs&&H.id)await QO0(Z.orgFs,H.id,X,Y);return{item:H}}})});function IK1($){if(!$)return null;let Z=$.projects;return Array.isArray(Z)?Z:null}function PN($,Z){if($===null)return!0;if($.includes("*"))return!0;return $.includes(Z)}async function TN($){if($.auth.apiKey)return null;let Z=$.organization?.id;if(!Z)return null;let Q=$.access.getRole()??$.organization?.role??$.auth.user?.role;if(!Q||mZ(Q))return null;if($.auth.permissions&&$.auth.permissionsOrganizationId===Z)return IK1($.auth.permissions);let X=await jR($.db,Z,Q);return IK1(X)}var ti=L(()=>{fX();AN()});function iE($){return typeof $==="string"||typeof $==="number"}function VK1($,Z){let Q=Z.split("."),X=$;for(let Y of Q){if(X==null||typeof X!=="object")return;X=X[Y]}return X}function KJ6($,Z){return $.connections.some((Q)=>Q.connection_id===Z)}function XO0($,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)=>XO0($,H));case"or":return K.some((H)=>XO0($,H));case"not":return!K.every((H)=>XO0($,H));default:return!0}}let{field:Q,operator:X,value:Y}=Z,J=Q.join(".");if(J==="connection_id"){if(X!=="eq"||typeof Y!=="string")return!1;return KJ6($,Y)}let G=VK1($,J);switch(X){case"eq":return G===Y;case"gt":return iE(G)&&iE(Y)&&G>Y;case"gte":return iE(G)&&iE(Y)&&G>=Y;case"lt":return iE(G)&&iE(Y)&&G<Y;case"lte":return iE(G)&&iE(Y)&&G<=Y;case"in":return Array.isArray(Y)&&Y.includes(G);case"like":if(typeof G!=="string"||typeof Y!=="string")return!1;if(Y.length>100)return!1;return li(Y).test(G);case"contains":if(typeof G!=="string"||typeof Y!=="string")return!1;return G.toLowerCase().includes(Y.toLowerCase());default:return!0}}function HJ6($,Z){return[...$].sort((Q,X)=>{for(let Y of Z){let J=Y.field.join("."),G=VK1(Q,J),W=VK1(X,J),K=0;if(G==null&&W==null)continue;if(G==null)K=Y.nulls==="first"?-1:1;else if(W==null)K=Y.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 Y.direction==="desc"?-K:K}return 0})}var FJ6,UJ6,wR;var kK1=L(()=>{GG();_0();ti();cE();FJ6=WF,UJ6=LD(kX),wR=m({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:FJ6,outputSchema:UJ6,handler:async($,Z)=>{await Z.access.check();let Q=W0(Z),X=$.where&&!("conditions"in $.where)&&$.where.field.join(".")==="connection_id"&&$.where.operator==="eq"&&typeof $.where.value==="string"?$.where.value:void 0,Y=$.where&&!("conditions"in $.where)&&$.where.field.join(".")==="pinned"&&$.where.operator==="eq"&&typeof $.where.value==="boolean"?$.where.value:void 0,G=X?await Z.storage.virtualMcps.listByConnectionId(Q.id,X):await Z.storage.virtualMcps.list(Q.id,Y!==void 0?{pinnedOnly:Y}:void 0);if($.where)G=G.filter((B)=>XO0(B,$.where));let W=await TN(Z);if(W!==null)G=G.filter((B)=>PN(W,B.id));if($.orderBy&&$.orderBy.length>0)G=HJ6(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 CK1}from"zod";var NJ6,BJ6,ER;var SK1=L(()=>{_0();ti();cE();NJ6=CK1.object({id:CK1.string().describe("ID of the virtual MCP to retrieve")}),BJ6=CK1.object({item:kX.nullable().describe("The retrieved virtual MCP, or null if not found")}),ER=m({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:NJ6,outputSchema:BJ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=await Z.storage.virtualMcps.findById($.id);if(X&&X.organization_id!==Q.id)return{item:null};if(!X)return{item:null};let Y=await TN(Z);if(!PN(Y,X.id))return{item:null};return{item:X}}})});function kZ($){return _K1.test($)}function zR($){let Z=(Q)=>typeof Q==="string"?Q.trim().toLowerCase():"";return Z($?.metadata?.siteSlug)||Z($?.title)||null}function Dg$($){let Z=typeof $?.metadata?.analyticsSiteSlug==="string"?$.metadata.analyticsSiteSlug.trim().toLowerCase():"";if(Z&&kZ(Z))return Z;return zR($)}var _K1;var C3=L(()=>{_K1=/^[a-z0-9][a-z0-9-]{0,59}$/});function Og$($){let{nextTitle:Z,currentTitle:Q,currentSiteSlug:X}=$;if(X?.trim())return null;if(Z===void 0||Z===Q)return null;let Y=Q?.trim().toLowerCase()??"";return kZ(Y)?Y:null}var jg$=L(()=>{C3()});import{z as vK1}from"zod";var LJ6,DJ6,PR;var xK1=L(()=>{_0();ti();Q40();cE();TK1();jg$();LJ6=vK1.object({id:vK1.string().describe("ID of the virtual MCP to update"),data:UH0.describe("Partial virtual MCP data to update")}),DJ6=vK1.object({item:kX.describe("The updated virtual MCP entity")}),PR=m({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:LJ6,outputSchema:DJ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to update virtual MCP");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 J=await TN(Z);if(!PN(J,Y.id))throw Error(`Virtual MCP not found: ${$.id}`);let{prompts:G,metadata:W,...K}=$.data,H=ni(W);if(H&&Y.metadata)H={...Y.metadata,...H};else if(H===null&&Y.metadata?.sandboxMap)H={sandboxMap:Y.metadata.sandboxMap};let F={...K,...W!==void 0?{metadata:H}:{}},U=Og$({nextTitle:F.title,currentTitle:Y.title,currentSiteSlug:Y.metadata?.siteSlug});if(U)F.metadata={...Y.metadata,...F.metadata,siteSlug:U};if(F.pinned!==void 0&&F.pinned!==Y.pinned)oD0(Z);if(F.connections?.length)await aD0(Z,Q.id,F.connections.map((B)=>B.connection_id));let N=await Z.storage.virtualMcps.update($.id,X,F);if(G!==void 0&&Z.orgFs)await QO0(Z.orgFs,$.id,X,G);return{item:N}}})});function bK1($){if(!$)return!1;let Z=X40.join("|");return new RegExp(`permission\\s+"?(?:${Z})"?\\s+is not allowed`,"i").test($)||/permissions exceed what the github app/i.test($)}function wg$($){let Z={...$};for(let Q of X40)Z[Q]="read";return Z}async function Eg$($,Z){let Q={...Z};for(;;){let X=await $(Q);if(!X.isError)return{result:X,grantedPermissions:Q};let Y=X.content?.find((K)=>K.type==="text")?.text,J=X40.find((K)=>(K in Q));if(!J||!bK1(Y))return{result:X,grantedPermissions:Q};let{[J]:G,...W}=Q;Q=W}}function OJ6($){if(!$||typeof $!=="object"||Array.isArray($))return YO0;let Z=$;if(Object.values(Z).some((Q)=>typeof Q!=="string"))return YO0;return Z}function jJ6($){if(typeof $!=="number"||!Number.isFinite($)||!Number.isInteger($)||$<=0)return;return $}function YZ($){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=jJ6(Z.repositoryId);return{sourceConnectionId:typeof Z.sourceConnectionId==="string"?Z.sourceConnectionId:void 0,installationId:Z.installationId,repositoryId:Q,owner:Z.owner,repo:Z.repo,permissions:OJ6(Z.permissions),grantProvider:Z.grantProvider==="github-mcp"?"github-mcp":void 0}}function pE($){return $.metadata?.orgShared===!0}function zg$($){let Z=new Set,Q=[];for(let X of $??[]){if(X.status!=="active")continue;let Y=YZ(X);if(Y===null)continue;let J=fK1(Y.owner,Y.repo);if(Z.has(J))continue;Z.add(J),Q.push(`${Y.owner}/${Y.repo}`)}return Q}function JO0($,Z,Q){let X=fK1(Z,Q),Y=($??[]).filter((J)=>{if(J.status&&J.status!=="active")return!1;let G=YZ(J);return G!==null&&fK1(G.owner,G.repo)===X});return Y.find(pE)??Y[0]??null}var YO0,X40,fK1=($,Z)=>`${$}/${Z}`.toLowerCase();var WG=L(()=>{YO0={contents:"write",metadata:"read",pull_requests:"write",issues:"write",checks:"read",deployments:"read",statuses:"read"},X40=["statuses","deployments","checks"]});function Pg$($){return dQ($)!==null||fH0($)!==null}var Tg$=L(()=>{r8()});import{z as yK1}from"zod";var wJ6,EJ6,TR;var gK1=L(()=>{WG();KF();_0();ti();Q40();cE();Tg$();wJ6=yK1.object({id:yK1.string().describe("ID of the virtual MCP to delete")}),EJ6=yK1.object({item:kX.describe("The deleted virtual MCP entity")}),TR=m({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:wJ6,outputSchema:EJ6,handler:async($,Z)=>{o(Z);let Q=W0(Z);if(await Z.access.check(),Pg$($.id))throw Error(`Virtual MCP not found: ${$.id}`);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 Y=await TN(Z);if(!PN(Y,X.id))throw Error(`Virtual MCP not found: ${$.id}`);if(await Z.storage.virtualMcps.delete($.id),Z.orgFs)await qK1(Z.orgFs,$.id,t0(Z)??"system");let J=X.metadata?.repository?.connectionId;if(J)try{let G=await Z.storage.connections.findById(J,Q.id),W=G&&(pE(G)||(await Z.storage.virtualMcps.listByConnectionId(Q.id,J)).length>0||await Z.storage.connections.isReferencedByThread(J));if(G&&YZ(G)&&!W){let H=await new V9(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:X}}})});function Ag$($,Z){let Q=$!==null&&typeof $==="object"&&!Array.isArray($)?$:null;if(Z===void 0)return Q;return{...Q??{},...Z}}import{z as rY}from"zod";var zJ6,AR;var hK1=L(()=>{_0();ti();cE();zJ6=rY.object({connectionId:rY.string(),toolName:rY.string(),label:rY.string(),icon:rY.string().nullable().optional()}),AR=m({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:rY.object({virtualMcpId:rY.string().describe("Virtual MCP ID"),pinnedViews:rY.array(zJ6).describe("Pinned views to set for the virtual MCP sidebar"),layout:rY.object({defaultMainView:rY.object({type:rY.string(),id:rY.string().optional(),toolName:rY.string().optional()}).nullable().optional(),chatDefaultOpen:rY.boolean().nullable().optional()}).optional()}),outputSchema:rY.object({item:kX.nullable()}),handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let{virtualMcpId:X,pinnedViews:Y,layout:J}=$,G=t0(Z),W=await Z.storage.virtualMcps.findById(X);if(!W)throw Error(`Virtual MCP not found: ${X}`);if(W.organization_id!==Q.id)throw Error(`Virtual MCP not found: ${X}`);let K=await TN(Z);if(!PN(K,W.id))throw Error(`Virtual MCP not found: ${X}`);let H=W.metadata?.ui??{},F={...H,pinnedViews:Y.length>0?Y:null,layout:Ag$(H.layout,J)};return{item:await Z.storage.virtualMcps.update(X,G??"system",{metadata:{...W.metadata,ui:F}})}}})});import{z as jD}from"zod";var PJ6,TJ6,uK1;var Rg$=L(()=>{_0();PJ6=jD.object({ids:jD.array(jD.string()).max(1000).describe("Virtual MCP ids to look up")}),TJ6=jD.object({items:jD.array(jD.object({id:jD.string(),last_used_at:jD.string().optional(),last_used_by:jD.string().optional()}))}),uK1=m({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:PJ6,outputSchema:TJ6,handler:async($,Z)=>{o(Z),W0(Z),await Z.access.check();let Q=await Z.storage.threads.findLastUsedByVirtualMcpIds($.ids);return{items:$.ids.map((X)=>({id:X,last_used_at:Q.get(X)?.last_used_at,last_used_by:Q.get(X)?.last_used_by}))}}})});var qg$=L(()=>{MK1();kK1();SK1();xK1();gK1();hK1();Rg$()});import{z as oX}from"zod";var lK1;var Mg$=L(()=>{f6();_0();lK1=m({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:oX.object({startDate:oX.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:oX.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),virtualMcpIds:oX.array(oX.string()).max(100).optional().describe("Filter by specific agent (Virtual MCP) IDs"),excludeConnectionIds:oX.array(oX.string()).max(100).optional().describe("Exclude tool calls from these connection IDs"),limit:oX.number().int().min(1).max(1000).optional().describe("Max number of (agent, tool) cells to return")}),outputSchema:oX.object({cells:oX.array(oX.object({virtualMcpId:oX.string().nullable(),toolName:oX.string(),calls:oX.number(),errors:oX.number(),outputSize:oX.number().describe("Sum of tool-output character length \u2014 a proxy for context weight, not LLM token count")}))}),handler:async($,Z)=>{let Q=W0(Z);return await Z.access.check(),await kJ(),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 k9}from"zod";var cK1;var Ig$=L(()=>{f6();_0();cK1=m({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:k9.object({id:k9.string().describe("Log ID to fetch")}),outputSchema:k9.object({log:k9.object({id:k9.string().optional(),organizationId:k9.string(),connectionId:k9.string(),toolName:k9.string(),input:k9.record(k9.string(),k9.unknown()),output:k9.record(k9.string(),k9.unknown()),isError:k9.boolean(),errorMessage:k9.string().nullish(),durationMs:k9.number(),timestamp:k9.string(),userId:k9.string().nullish(),requestId:k9.string(),userAgent:k9.string().nullish(),virtualMcpId:k9.string().nullish(),properties:k9.record(k9.string(),k9.string()).nullish()}).nullable().describe("The monitoring log, or null if not found")}),handler:async($,Z)=>{await Z.access.check(),await kJ();let Q=W0(Z),X=await Z.storage.monitoring.getById(Q.id,$.id);if(!X)return{log:null};return{log:{...X,timestamp:X.timestamp instanceof Date?X.timestamp.toISOString():X.timestamp}}}})});import{z as e8}from"zod";var RJ6,mK1;var Vg$=L(()=>{f6();_0();RJ6=e8.object({id:e8.string().optional().describe("Unique log identifier"),organizationId:e8.string().describe("Organization ID"),connectionId:e8.string().describe("Connection ID"),toolName:e8.string().describe("Name of the tool that was called"),isError:e8.boolean().describe("Whether the call resulted in an error"),errorMessage:e8.string().nullish().describe("Error message if applicable"),durationMs:e8.number().describe("Call duration in milliseconds"),timestamp:e8.string().describe("ISO 8601 timestamp of the call"),userId:e8.string().nullish().describe("User who triggered the call"),requestId:e8.string().describe("Unique request identifier"),userAgent:e8.string().nullish().describe("Client identifier (x-studio-client header)"),virtualMcpId:e8.string().nullish().describe("Virtual MCP (Agent) ID if routed through an agent"),properties:e8.record(e8.string(),e8.string()).nullish().describe("Custom key-value metadata attached to the log")}),mK1=m({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:e8.object({connectionId:e8.string().optional().describe("Filter by connection ID"),excludeConnectionIds:e8.array(e8.string()).optional().describe("Exclude logs from these connection IDs (e.g. system connections)"),virtualMcpId:e8.string().optional().describe("Filter by Virtual MCP (Agent) ID"),toolName:e8.string().optional().describe("Filter by tool name"),isError:e8.boolean().optional().describe("Filter by error status"),startDate:e8.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:e8.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),limit:e8.number().default(20).describe("Maximum number of results"),offset:e8.number().default(0).describe("Offset for pagination"),properties:e8.record(e8.string(),e8.string()).optional().describe("Filter by exact property key=value matches"),propertyKeys:e8.array(e8.string()).optional().describe("Filter by logs that have these property keys"),propertyPatterns:e8.record(e8.string(),e8.string()).optional().describe("Filter by property value patterns (SQL LIKE, use % as wildcard)"),propertyInValues:e8.record(e8.string(),e8.string()).optional().describe("Filter by exact match within comma-separated values (e.g., user_tags in 'Engineering')")}),outputSchema:e8.object({logs:e8.array(RJ6).describe("Array of monitoring logs"),total:e8.number().describe("Total number of logs matching filters"),offset:e8.number().describe("Current offset for pagination"),limit:e8.number().describe("Current limit for pagination")}),handler:async($,Z)=>{await Z.access.check(),await kJ();let Q=W0(Z),Y=$.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:Y},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 f$}from"zod";var dK1;var kg$=L(()=>{f6();_0();dK1=m({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:f$.object({startDate:f$.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:f$.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)"),interval:f$.string().regex(/^\d+[mhd]$/).optional().describe("Bucket interval for timeseries data (e.g. 1m, 5m, 2h, 1d). When provided, returns timeseries array."),connectionIds:f$.array(f$.string()).max(100).optional().describe("Filter by specific connection IDs (max 100)"),excludeConnectionIds:f$.array(f$.string()).max(100).optional().describe("Exclude specific connection IDs (max 100)"),toolNames:f$.array(f$.string()).max(100).optional().describe("Filter by specific tool names (max 100)"),status:f$.enum(["success","error"]).optional().describe("Filter metrics by execution status"),topN:f$.number().int().min(1).max(20).optional().describe("When provided with interval, also return top tools and their timeseries"),userIds:f$.array(f$.string()).max(100).optional().describe("Filter LLM usage by user IDs (only applied when llmUsage is true)"),llmUsage:f$.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:f$.object({totalCalls:f$.number().describe("Total number of tool calls"),errorRate:f$.number().optional().describe("Error rate as a decimal (0 to 1)"),avgDurationMs:f$.number().describe("Average call duration in milliseconds"),errorRatePercent:f$.string().optional().describe("Error rate as a percentage string"),totalErrors:f$.number().optional().describe("Total number of errors"),p50DurationMs:f$.number().optional().describe("50th percentile duration in milliseconds"),p95DurationMs:f$.number().optional().describe("95th percentile duration in milliseconds"),connectionBreakdown:f$.array(f$.object({connectionId:f$.string(),calls:f$.number(),errors:f$.number(),errorRate:f$.number(),avgDurationMs:f$.number()})).optional().describe("Per-connection metric breakdown"),totalInputTokens:f$.number().optional().describe("Total input tokens (LLM usage mode)"),totalOutputTokens:f$.number().optional().describe("Total output tokens (LLM usage mode)"),totalTokens:f$.number().optional().describe("Total tokens (LLM usage mode)"),totalCostUsd:f$.number().optional().describe("Total USD cost (LLM usage mode; only non-zero for providers that report cost)"),topTools:f$.array(f$.object({toolName:f$.string(),connectionId:f$.string().nullable(),calls:f$.number(),inputTokens:f$.number().optional(),outputTokens:f$.number().optional(),costUsd:f$.number().optional()})).optional().describe("Top tools ranked by calls"),topToolsTimeseries:f$.array(f$.object({timestamp:f$.string(),toolName:f$.string(),calls:f$.number(),errors:f$.number(),avg:f$.number(),p95:f$.number()})).optional().describe("Per-tool metric timeseries for the top tools"),timeseries:f$.array(f$.object({timestamp:f$.string(),calls:f$.number(),errors:f$.number(),errorRate:f$.number(),avg:f$.number(),p50:f$.number(),p95:f$.number(),inputTokens:f$.number().optional(),outputTokens:f$.number().optional(),totalTokens:f$.number().optional(),costUsd:f$.number().optional()})).optional().describe("Timeseries data points bucketed by interval")}),handler:async($,Z)=>{let Q=W0(Z);if(await Z.access.check(),await kJ(),$.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 Y=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 Y;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{...Y,topTools:J.topTools,topToolsTimeseries:J.timeseries}}let X=await Z.storage.monitoring.getStats({organizationId:Q.id,startDate:$.startDate?new Date($.startDate):void 0,endDate:$.endDate?new Date($.endDate):void 0});return{...X,errorRatePercent:(X.errorRate*100).toFixed(2)}}})});import{z as sY}from"zod";var iK1;var Cg$=L(()=>{f6();_0();iK1=m({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:sY.object({threadIds:sY.array(sY.string()).min(1).max(500).describe("Thread IDs to aggregate usage for (max 500)"),connectionId:sY.string().optional().describe("LLM connection ID (defaults to 'decopilot')"),startDate:sY.string().datetime().optional().describe("Filter by start date (ISO 8601 datetime string)"),endDate:sY.string().datetime().optional().describe("Filter by end date (ISO 8601 datetime string)")}),outputSchema:sY.object({items:sY.array(sY.object({threadId:sY.string(),calls:sY.number(),inputTokens:sY.number(),outputTokens:sY.number(),totalTokens:sY.number(),costUsd:sY.number()}))}),handler:async($,Z)=>{let Q=W0(Z);return await Z.access.check(),await kJ(),{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 Sg$=L(()=>{Mg$();Ig$();Vg$();kg$();Cg$()});function GO0($){return typeof $==="string"&&MJ6.has($.trim().toLowerCase())}var MJ6;var pK1=L(()=>{MJ6=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 S3}from"zod";var nK1;var _g$=L(()=>{_0();pK1();nK1=m({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:S3.object({slug:S3.string().min(1).max(50).regex(/^[a-z0-9-]+$/,"Slug must be lowercase alphanumeric with hyphens").refine(($)=>!GO0($),"Slug is reserved by Studio"),name:S3.string().min(1).max(255),description:S3.string().max(500).optional()}),outputSchema:S3.object({id:S3.string(),name:S3.string(),slug:S3.string(),logo:S3.string().nullable().optional(),metadata:S3.any().optional(),createdAt:S3.string().datetime().describe("ISO 8601 timestamp"),members:S3.array(S3.any()).optional()}),handler:async($,Z)=>{o(Z),await Z.access.check();let Q=t0(Z);if(!Q)throw Error("User ID required to create organization");let X=await Z.boundAuth.organization.create({name:$.name,slug:$.slug,metadata:$.description?{description:$.description}:void 0,userId:Q});if(!X)throw Error("Failed to create organization");return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});import{z as RN}from"zod";var tK1;var vg$=L(()=>{_0();tK1=m({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:RN.object({}),outputSchema:RN.object({organizations:RN.array(RN.object({id:RN.string(),name:RN.string(),slug:RN.string(),logo:RN.string().nullable().optional(),metadata:RN.any().optional(),createdAt:RN.string().datetime().describe("ISO 8601 timestamp")}))}),handler:async($,Z)=>{if(o(Z),await Z.access.check(),!t0(Z))throw Error("User ID required to list organizations");return{organizations:(await Z.boundAuth.organization.list()).map((X)=>({...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}))}}})});import{z as BK}from"zod";var oK1;var xg$=L(()=>{_0();oK1=m({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:BK.object({}),outputSchema:BK.object({id:BK.string(),name:BK.string(),slug:BK.string(),logo:BK.string().nullable().optional(),metadata:BK.any().optional(),createdAt:BK.string().datetime().describe("ISO 8601 timestamp"),members:BK.array(BK.any()).optional(),invitations:BK.array(BK.any()).optional()}),handler:async($,Z)=>{o(Z),await Z.access.check();let Q=Z.organization?.id;if(!Q)throw Error("Organization ID required (no active organization in context)");let X=await Z.boundAuth.organization.get(Q);if(!X)throw Error("No active organization found");let Y=new Date,J=X.invitations?.filter((G)=>new Date(G.expiresAt)>Y);return{...X,invitations:J,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});import{z as HF}from"zod";var aK1;var fg$=L(()=>{_0();aK1=m({name:"ORGANIZATION_UPDATE",description:"Update an organization's name or description.",annotations:{title:"Update Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:HF.object({id:HF.string(),name:HF.string().min(1).max(255).optional(),description:HF.string().max(500).optional()}),outputSchema:HF.object({id:HF.string(),name:HF.string(),slug:HF.string(),logo:HF.string().nullable().optional(),metadata:HF.any().optional(),createdAt:HF.string().datetime().describe("ISO 8601 timestamp")}),handler:async($,Z)=>{if(o(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 Y=await Z.boundAuth.organization.get($.id);Q.metadata={...Y?.metadata,description:$.description}}let X=await Z.boundAuth.organization.update({organizationId:$.id,data:Q});if(!X)throw Error("Failed to update organization");return{...X,createdAt:X.createdAt instanceof Date?X.createdAt.toISOString():X.createdAt}}})});import{sql as IJ6}from"kysely";import{z as Y40}from"zod";var rK1;var bg$=L(()=>{r8();_0();VD0();rK1=m({name:"ORGANIZATION_DELETE",description:"Archive an organization (soft delete).",annotations:{title:"Delete Organization",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Y40.object({id:Y40.string()}),outputSchema:Y40.object({success:Y40.boolean(),id:Y40.string()}),handler:async($,Z)=>{if(o(Z),await Z.access.check(),$.id!==Z.organization?.id)throw Error("Organization ID does not match authenticated organization");let X=(await Z.boundAuth.organization.get($.id))?.metadata??{};if(X.archived===!0)return{success:!0,id:$.id};let Y=await Z.storage.connections.findById(K4.REPORTS($.id),$.id);await Z.boundAuth.organization.update({organizationId:$.id,data:{metadata:{...X,archived:!0,archivedAt:new Date().toISOString()}}}),await IJ6`
|
|
@@ -3869,7 +3869,7 @@ ${Q.trim()}`}function hb6($){return[`Your ${qN[$]} comment carries no screenshot
|
|
|
3869
3869
|
AND date >= {since:Date} AND date <= {until:Date}
|
|
3870
3870
|
GROUP BY host
|
|
3871
3871
|
ORDER BY sum(requests) DESC
|
|
3872
|
-
LIMIT 25`,{slug:$,since:Z,until:Q});return[...new Set(X.map((Y)=>mn(Y.host)).filter(Boolean))]}async function CX8($){let Z=P0().oneDollarStatsApiKey;if(!Z||!XO())return{status:"not_configured"};let{slug:Q,testName:X,since:Y,until:J,goalOnDash:G}=$,W=await Gy6(Q,Y,J);if(W.length===0)return{status:"no_site_data"};let K=`event:props:${X}`,H=[Y,J],F=Array.from(new Set([nv0,...$.goals])),U=async(g,l,h)=>{let i=[];for(let H0=0;H0<W.length;H0+=kX8){let R0=await Promise.all(W.slice(H0,H0+kX8).map(async(Y0)=>{let N0=await fetch(Xy6,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":Z,Accept:"application/json"},body:JSON.stringify({site_id:Y0,metrics:g,date_range:H,...l.length?{dimensions:l}:{},...h.length?{filters:h}:{},pagination:{limit:1e4,offset:0}}),signal:AbortSignal.timeout(Yy6)}).catch(()=>null);if(!N0||!N0.ok)return[];return(await N0.json().catch(()=>null))?.results??[]}));for(let Y0 of R0)i.push(...Y0)}return i},N=async(g,l)=>{let h=g===nv0;return(await U(["visitors"],[K,...h?[]:["event:goal"]],[["is",K,[l]],...h?[]:[["is","event:goal",[g]]]])).reduce((H0,R0)=>H0+(R0.metrics?.[0]??0),0)},B=async(g)=>{let l=G===nv0;return U(["visitors"],["time:day",K,...l?[]:["event:goal"]],[["is",K,[g]],...l?[]:[["is","event:goal",[G]]]])},[D,O,j]=await Promise.all([Promise.all(F.map(async(g)=>{let[l,h]=await Promise.all([N(g,"true"),N(g,"false")]);return{goal:g,variant:l,default:h}})),B("false"),B("true")]),w=D.find((g)=>g.goal===nv0),E={default:w?.default??0,variant:w?.variant??0},z=new Map;for(let g of O){let l=g.dimensions?.[0]?.split(" ")[0]??"";if(!l)continue;let h=z.get(l)??{default:0,variant:0};h.default+=g.metrics?.[0]??0,z.set(l,h)}for(let g of j){let l=g.dimensions?.[0]?.split(" ")[0]??"";if(!l)continue;let h=z.get(l)??{default:0,variant:0};h.variant+=g.metrics?.[0]??0,z.set(l,h)}let A=Array.from(z.entries()).map(([g,l])=>({date:g,...l})).sort((g,l)=>g.date.localeCompare(l.date)),P=O.reduce((g,l)=>g+(l.metrics?.[0]??0),0),T=j.reduce((g,l)=>g+(l.metrics?.[0]??0),0),q={successes:P,total:E.default},f={successes:T,total:E.variant},S=VX8(q,f),V=S==null||Number.isNaN(S)?1000:S,u=IX8(q,f);return{status:"ok",results:{visitors:E,goals:D,timeseries:A,stats:{totalParticipants:E.default+E.variant,sampleSize:V,probabilityVariantBest:u,probabilityDefaultBest:1-u}}}}var Xy6="https://deco.lilstts.com/plausible",Yy6=12000,kX8=6,nv0="visitors",Jy6="site_id IN (SELECT id FROM default.dim_sites WHERE name = {slug:String})";var SX8=L(()=>{X$();iv0();pv0()});import{z as n6}from"zod";function vX8($){return $.toISOString().slice(0,10)}function Wy6(){let $=new Date,Z=new Date($);return Z.setUTCDate(Z.getUTCDate()-29),{since:vX8(Z),until:vX8($)}}var _X8,HE1;var xX8=L(()=>{C3();_0();SX8();Qh();_X8=/^\d{4}-\d{2}-\d{2}$/;HE1=m({name:"EXPERIMENT_RESULTS",description:"A/B results for one experiment: per-goal visitor conversions for each variant, a daily timeseries for the selected goal, and the computed statistics (participants, target sample size, probability each variant is best).",annotations:{title:"Experiment Results",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:n6.object({site:n6.string().min(1).max(60).refine(kZ).describe("Site slug the experiment belongs to."),key:n6.string().min(1).describe("Analytics prop key the variants split on: `event:props:<key>` = 'true'/'false'. In the deco runtime this is the sticky segment matcher block's id (not the multivariate section name), so `key` must equal that matcher id for results to populate."),since:n6.string().regex(_X8).optional().describe("Window start (YYYY-MM-DD)."),until:n6.string().regex(_X8).optional().describe("Window end (YYYY-MM-DD)."),goals:n6.array(n6.string().min(1).max(200)).max(20).default([]).describe("Custom goals to aggregate conversions for."),goalOnDash:n6.string().default("visitors").describe("Goal plotted in the timeseries / used for the statistics.")}),outputSchema:n6.object({available:n6.boolean(),reason:n6.enum(["not_configured","no_site_data"]).nullable(),analyticsSite:n6.string(),results:n6.object({visitors:n6.object({default:n6.number(),variant:n6.number()}),goals:n6.array(n6.object({goal:n6.string(),default:n6.number(),variant:n6.number()})),timeseries:n6.array(n6.object({date:n6.string(),default:n6.number(),variant:n6.number()})),stats:n6.object({totalParticipants:n6.number(),sampleSize:n6.number(),probabilityVariantBest:n6.number(),probabilityDefaultBest:n6.number()})}).nullable()}),handler:async($,Z)=>{o(Z),await Z.access.check();let Q=W0(Z),X=await wX8(Z,Q.id,$.site),Y=$.since&&$.until?{since:$.since,until:$.until}:Wy6(),J=await CX8({slug:X,testName:$.key,since:Y.since,until:Y.until,goals:$.goals,goalOnDash:$.goalOnDash});return J.status==="ok"?{available:!0,reason:null,analyticsSite:X,results:J.results}:{available:!1,reason:J.status,analyticsSite:X,results:null}}})});var fX8=L(()=>{EX8();zX8();PX8();TX8();AX8();xX8()});import{z as bX8}from"zod";function Uy6($,Z){let Q=$?.[Z];if(!Q)return;return Object.entries(Q).filter(([,Y])=>(YX in Y)).sort(([,Y],[,J])=>(J[YX]?.createdAt??0)-(Y[YX]?.createdAt??0))[0]?.[0]}var Hy6,Fy6,FE1;var yX8=L(()=>{F6();_0();Sg();Kn();SX();OG();Hy6=bX8.object({data:H68.describe("Data for the new thread (id is auto-generated if not provided)")}),Fy6=bX8.object({item:tN.describe("The created thread entity")});FE1=m({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread for organizing messages and conversations.",annotations:{title:"Create Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Hy6,outputSchema:Fy6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to create thread");let{data:Y}=$,J=Y.id??a8("thrd"),W=(await G_0(Z.storage.virtualMcps,Y.virtual_mcp_id,Q.id)).metadata,K=W?.repository,H=null;if(K)H=Y.branch??Uy6(W?.sandboxMap,X)??tS0(nS0(Z.auth.user));let F=await Z.storage.threads.create({id:J,organization_id:Q.id,title:Y.title,description:Y.description,virtual_mcp_id:Y.virtual_mcp_id,branch:H,created_by:X,metadata:{runtime:Y.runtime??aS0(W)}});if(F.isNew)h1.capture({distinctId:X,event:"chat_started",groups:{organization:Q.id},properties:{organization_id:Q.id,thread_id:J,has_title:!!$.data.title,created_via:"tool"}});return{item:MK(F)}}})});import{z as UE1}from"zod";var Ny6,By6,NE1;var gX8=L(()=>{F6();_0();Sg();Kn();Ny6=UE1.object({id:UE1.string().describe("ID of the thread to update"),data:F68.describe("Partial thread data to update")}),By6=UE1.object({item:tN.describe("The updated thread entity")}),NE1=m({name:"COLLECTION_THREADS_UPDATE",description:"Update a thread's title, description, or visibility.",annotations:{title:"Update Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Ny6,outputSchema:By6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to update thread");let{id:Y,data:J}=$,G=await Z.storage.threads.get(Y);if(!G)throw Error("Thread not found in organization");let W;if(J.virtual_mcp_id!==void 0)W=await G_0(Z.storage.virtualMcps,J.virtual_mcp_id,Q.id);let K=J.virtual_mcp_id!==void 0?J.virtual_mcp_id:G.virtual_mcp_id;if(J.branch===null&&K){if((W??await Z.storage.virtualMcps.findById(K,Q.id))?.metadata?.repository)throw Error("Cannot set branch=null on a repository-linked thread (vMCP has repository)")}let H={title:J.title,description:J.description,hidden:J.hidden,updated_by:X};if(J.status)H.status=J.status;if(J.metadata!==void 0){let U=ni(J.metadata)??{},N=kg(G.metadata?.runtime),B=kg(U.runtime);if(N&&B&&B!==N)throw Error(`Cannot change a thread's runtime (${N} \u2192 ${B}); it is stamped once at creation. Start a new chat instead.`);let D=G.metadata?.sandboxMap;H.metadata={...U,...N?{runtime:N}:{},...D!==void 0?{sandboxMap:D}:{}}}if(J.branch!==void 0)H.branch=J.branch;if(J.virtual_mcp_id!==void 0)H.virtual_mcp_id=J.virtual_mcp_id;let F=await Z.storage.threads.update(Y,H);if(J.hidden!==void 0&&J.hidden!==G.hidden)h1.capture({distinctId:X,event:J.hidden?"chat_archived":"chat_unarchived",groups:{organization:Q.id},properties:{organization_id:Q.id,thread_id:Y}});return{item:MK(F)}}})});var BE1;var hX8=L(()=>{GG();Sg();F6();_0();aD();fv0();gn();BE1=m({name:"COLLECTION_THREADS_DELETE",description:"Permanently delete a thread and all its messages.",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:o80,outputSchema:a80(tN),handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=await Z.storage.threads.get($.id);if(!X)throw Error(`Thread not found: ${$.id}`);if(X.status==="in_progress"){let J=(W)=>(K)=>console.error("[thread] delete-time run cancel step failed",{threadId:$.id,step:W,err:K});await yn($.id).catch(J("background-jobs")),await ln($.id).catch(J("gate-head"));let G=await Z.storage.threads.getRunFence($.id).catch(()=>null);if(G)await $h($.id,G).catch(J("hosted-harness"));vv0($.id)}await Z.storage.threads.delete($.id);let Y=t0(Z);if(Y)h1.capture({distinctId:Y,event:"chat_deleted",groups:{organization:Q.id},properties:{organization_id:Q.id,thread_id:$.id}});return{item:MK(X)}}})});import{sql as m4}from"kysely";class LE1{db;constructor($){this.db=$}async rows($){return(await $.execute(this.db)).rows}async delivery($){let Z=tv0($.orgIds),[Q]=await this.rows(m4`
|
|
3872
|
+
LIMIT 25`,{slug:$,since:Z,until:Q});return[...new Set(X.map((Y)=>mn(Y.host)).filter(Boolean))]}async function CX8($){let Z=P0().oneDollarStatsApiKey;if(!Z||!XO())return{status:"not_configured"};let{slug:Q,testName:X,since:Y,until:J,goalOnDash:G}=$,W=await Gy6(Q,Y,J);if(W.length===0)return{status:"no_site_data"};let K=`event:props:${X}`,H=[Y,J],F=Array.from(new Set([nv0,...$.goals])),U=async(g,l,h)=>{let i=[];for(let H0=0;H0<W.length;H0+=kX8){let R0=await Promise.all(W.slice(H0,H0+kX8).map(async(Y0)=>{let N0=await fetch(Xy6,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":Z,Accept:"application/json"},body:JSON.stringify({site_id:Y0,metrics:g,date_range:H,...l.length?{dimensions:l}:{},...h.length?{filters:h}:{},pagination:{limit:1e4,offset:0}}),signal:AbortSignal.timeout(Yy6)}).catch(()=>null);if(!N0||!N0.ok)return[];return(await N0.json().catch(()=>null))?.results??[]}));for(let Y0 of R0)i.push(...Y0)}return i},N=async(g,l)=>{let h=g===nv0;return(await U(["visitors"],[K,...h?[]:["event:goal"]],[["is",K,[l]],...h?[]:[["is","event:goal",[g]]]])).reduce((H0,R0)=>H0+(R0.metrics?.[0]??0),0)},B=async(g)=>{let l=G===nv0;return U(["visitors"],["time:day",K,...l?[]:["event:goal"]],[["is",K,[g]],...l?[]:[["is","event:goal",[G]]]])},[D,O,j]=await Promise.all([Promise.all(F.map(async(g)=>{let[l,h]=await Promise.all([N(g,"true"),N(g,"false")]);return{goal:g,variant:l,default:h}})),B("false"),B("true")]),w=D.find((g)=>g.goal===nv0),E={default:w?.default??0,variant:w?.variant??0},z=new Map;for(let g of O){let l=g.dimensions?.[0]?.split(" ")[0]??"";if(!l)continue;let h=z.get(l)??{default:0,variant:0};h.default+=g.metrics?.[0]??0,z.set(l,h)}for(let g of j){let l=g.dimensions?.[0]?.split(" ")[0]??"";if(!l)continue;let h=z.get(l)??{default:0,variant:0};h.variant+=g.metrics?.[0]??0,z.set(l,h)}let A=Array.from(z.entries()).map(([g,l])=>({date:g,...l})).sort((g,l)=>g.date.localeCompare(l.date)),P=O.reduce((g,l)=>g+(l.metrics?.[0]??0),0),T=j.reduce((g,l)=>g+(l.metrics?.[0]??0),0),q={successes:P,total:E.default},f={successes:T,total:E.variant},S=VX8(q,f),V=S==null||Number.isNaN(S)?1000:S,u=IX8(q,f);return{status:"ok",results:{visitors:E,goals:D,timeseries:A,stats:{totalParticipants:E.default+E.variant,sampleSize:V,probabilityVariantBest:u,probabilityDefaultBest:1-u}}}}var Xy6="https://deco.lilstts.com/plausible",Yy6=12000,kX8=6,nv0="visitors",Jy6="site_id IN (SELECT id FROM default.dim_sites WHERE name = {slug:String})";var SX8=L(()=>{X$();iv0();pv0()});import{z as n6}from"zod";function vX8($){return $.toISOString().slice(0,10)}function Wy6(){let $=new Date,Z=new Date($);return Z.setUTCDate(Z.getUTCDate()-29),{since:vX8(Z),until:vX8($)}}var _X8,HE1;var xX8=L(()=>{C3();_0();SX8();Qh();_X8=/^\d{4}-\d{2}-\d{2}$/;HE1=m({name:"EXPERIMENT_RESULTS",description:"A/B results for one experiment: per-goal visitor conversions for each variant, a daily timeseries for the selected goal, and the computed statistics (participants, target sample size, probability each variant is best).",annotations:{title:"Experiment Results",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:n6.object({site:n6.string().min(1).max(60).refine(kZ).describe("Site slug the experiment belongs to."),key:n6.string().min(1).describe("Analytics prop key the variants split on: `event:props:<key>` = 'true'/'false'. In the deco runtime this is the sticky segment matcher block's id (not the multivariate section name), so `key` must equal that matcher id for results to populate."),since:n6.string().regex(_X8).optional().describe("Window start (YYYY-MM-DD)."),until:n6.string().regex(_X8).optional().describe("Window end (YYYY-MM-DD)."),goals:n6.array(n6.string().min(1).max(200)).max(20).default([]).describe("Custom goals to aggregate conversions for."),goalOnDash:n6.string().default("visitors").describe("Goal plotted in the timeseries / used for the statistics.")}).refine(($)=>!$.since||!$.until||$.since<=$.until,{message:"`since` must not be after `until`",path:["since"]}),outputSchema:n6.object({available:n6.boolean(),reason:n6.enum(["not_configured","no_site_data"]).nullable(),analyticsSite:n6.string(),results:n6.object({visitors:n6.object({default:n6.number(),variant:n6.number()}),goals:n6.array(n6.object({goal:n6.string(),default:n6.number(),variant:n6.number()})),timeseries:n6.array(n6.object({date:n6.string(),default:n6.number(),variant:n6.number()})),stats:n6.object({totalParticipants:n6.number(),sampleSize:n6.number(),probabilityVariantBest:n6.number(),probabilityDefaultBest:n6.number()})}).nullable()}),handler:async($,Z)=>{o(Z),await Z.access.check();let Q=W0(Z),X=await wX8(Z,Q.id,$.site),Y=$.since&&$.until?{since:$.since,until:$.until}:Wy6(),J=await CX8({slug:X,testName:$.key,since:Y.since,until:Y.until,goals:$.goals,goalOnDash:$.goalOnDash});return J.status==="ok"?{available:!0,reason:null,analyticsSite:X,results:J.results}:{available:!1,reason:J.status,analyticsSite:X,results:null}}})});var fX8=L(()=>{EX8();zX8();PX8();TX8();AX8();xX8()});import{z as bX8}from"zod";function Uy6($,Z){let Q=$?.[Z];if(!Q)return;return Object.entries(Q).filter(([,Y])=>(YX in Y)).sort(([,Y],[,J])=>(J[YX]?.createdAt??0)-(Y[YX]?.createdAt??0))[0]?.[0]}var Hy6,Fy6,FE1;var yX8=L(()=>{F6();_0();Sg();Kn();SX();OG();Hy6=bX8.object({data:H68.describe("Data for the new thread (id is auto-generated if not provided)")}),Fy6=bX8.object({item:tN.describe("The created thread entity")});FE1=m({name:"COLLECTION_THREADS_CREATE",description:"Create a new thread for organizing messages and conversations.",annotations:{title:"Create Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Hy6,outputSchema:Fy6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to create thread");let{data:Y}=$,J=Y.id??a8("thrd"),W=(await G_0(Z.storage.virtualMcps,Y.virtual_mcp_id,Q.id)).metadata,K=W?.repository,H=null;if(K)H=Y.branch??Uy6(W?.sandboxMap,X)??tS0(nS0(Z.auth.user));let F=await Z.storage.threads.create({id:J,organization_id:Q.id,title:Y.title,description:Y.description,virtual_mcp_id:Y.virtual_mcp_id,branch:H,created_by:X,metadata:{runtime:Y.runtime??aS0(W)}});if(F.isNew)h1.capture({distinctId:X,event:"chat_started",groups:{organization:Q.id},properties:{organization_id:Q.id,thread_id:J,has_title:!!$.data.title,created_via:"tool"}});return{item:MK(F)}}})});import{z as UE1}from"zod";var Ny6,By6,NE1;var gX8=L(()=>{F6();_0();Sg();Kn();Ny6=UE1.object({id:UE1.string().describe("ID of the thread to update"),data:F68.describe("Partial thread data to update")}),By6=UE1.object({item:tN.describe("The updated thread entity")}),NE1=m({name:"COLLECTION_THREADS_UPDATE",description:"Update a thread's title, description, or visibility.",annotations:{title:"Update Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:Ny6,outputSchema:By6,handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=t0(Z);if(!X)throw Error("User ID required to update thread");let{id:Y,data:J}=$,G=await Z.storage.threads.get(Y);if(!G)throw Error("Thread not found in organization");let W;if(J.virtual_mcp_id!==void 0)W=await G_0(Z.storage.virtualMcps,J.virtual_mcp_id,Q.id);let K=J.virtual_mcp_id!==void 0?J.virtual_mcp_id:G.virtual_mcp_id;if(J.branch===null&&K){if((W??await Z.storage.virtualMcps.findById(K,Q.id))?.metadata?.repository)throw Error("Cannot set branch=null on a repository-linked thread (vMCP has repository)")}let H={title:J.title,description:J.description,hidden:J.hidden,updated_by:X};if(J.status)H.status=J.status;if(J.metadata!==void 0){let U=ni(J.metadata)??{},N=kg(G.metadata?.runtime),B=kg(U.runtime);if(N&&B&&B!==N)throw Error(`Cannot change a thread's runtime (${N} \u2192 ${B}); it is stamped once at creation. Start a new chat instead.`);let D=G.metadata?.sandboxMap;H.metadata={...U,...N?{runtime:N}:{},...D!==void 0?{sandboxMap:D}:{}}}if(J.branch!==void 0)H.branch=J.branch;if(J.virtual_mcp_id!==void 0)H.virtual_mcp_id=J.virtual_mcp_id;let F=await Z.storage.threads.update(Y,H);if(J.hidden!==void 0&&J.hidden!==G.hidden)h1.capture({distinctId:X,event:J.hidden?"chat_archived":"chat_unarchived",groups:{organization:Q.id},properties:{organization_id:Q.id,thread_id:Y}});return{item:MK(F)}}})});var BE1;var hX8=L(()=>{GG();Sg();F6();_0();aD();fv0();gn();BE1=m({name:"COLLECTION_THREADS_DELETE",description:"Permanently delete a thread and all its messages.",annotations:{title:"Delete Thread",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},inputSchema:o80,outputSchema:a80(tN),handler:async($,Z)=>{o(Z);let Q=W0(Z);await Z.access.check();let X=await Z.storage.threads.get($.id);if(!X)throw Error(`Thread not found: ${$.id}`);if(X.status==="in_progress"){let J=(W)=>(K)=>console.error("[thread] delete-time run cancel step failed",{threadId:$.id,step:W,err:K});await yn($.id).catch(J("background-jobs")),await ln($.id).catch(J("gate-head"));let G=await Z.storage.threads.getRunFence($.id).catch(()=>null);if(G)await $h($.id,G).catch(J("hosted-harness"));vv0($.id)}await Z.storage.threads.delete($.id);let Y=t0(Z);if(Y)h1.capture({distinctId:Y,event:"chat_deleted",groups:{organization:Q.id},properties:{organization_id:Q.id,thread_id:$.id}});return{item:MK(X)}}})});import{sql as m4}from"kysely";class LE1{db;constructor($){this.db=$}async rows($){return(await $.execute(this.db)).rows}async delivery($){let Z=tv0($.orgIds),[Q]=await this.rows(m4`
|
|
3873
3873
|
with moves as (${Z})
|
|
3874
3874
|
select count(distinct item_id) as completed,
|
|
3875
3875
|
count(distinct item_id) filter (
|