decocms 4.240.0 → 4.241.1
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-Cg3fHuBn.js → AlertCircle-DM41S5Z5.js} +1 -1
- package/dist/client/assets/{AreaChart-Dahh-4-C.js → AreaChart-CeS7wdSU.js} +1 -1
- package/dist/client/assets/{ArrowLeft-CKDBuIH0.js → ArrowLeft-_2CMEHl-.js} +1 -1
- package/dist/client/assets/{ArrowUp-CNSXQcbu.js → ArrowUp-BakohXbr.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-CiPprS4P.js → ArrowUpRight-CTpe7RIn.js} +1 -1
- package/dist/client/assets/{Check-BajQzgjU.js → Check-D1jXHJCh.js} +1 -1
- package/dist/client/assets/{CheckCircle-jMq_LGKl.js → CheckCircle-AYtQ59q6.js} +1 -1
- package/dist/client/assets/{ChevronDown-B1SP4Q2f.js → ChevronDown-CQzgTDWg.js} +1 -1
- package/dist/client/assets/{ChevronRight-DYzmp5S1.js → ChevronRight-zOukHN5J.js} +1 -1
- package/dist/client/assets/{ChevronUp-CmjfaMFY.js → ChevronUp-CxLYLOrv.js} +1 -1
- package/dist/client/assets/{Copy01-1rF1hHQA.js → Copy01-C1bOkt0L.js} +1 -1
- package/dist/client/assets/{CreditCard01-ClLSYbqv.js → CreditCard01-CRr1X6M_.js} +1 -1
- package/dist/client/assets/{DotsVertical-wRY0m847.js → DotsVertical-P-X5Mufl.js} +1 -1
- package/dist/client/assets/Download01-BzRrEOnM.js +1 -0
- package/dist/client/assets/{Eye-BX-sf9wy.js → Eye-C0KTKKJF.js} +1 -1
- package/dist/client/assets/{FilterLines-ClJ_YJto.js → FilterLines-CfXZWnlF.js} +1 -1
- package/dist/client/assets/Globe01-Cou3ky_5.js +1 -0
- package/dist/client/assets/{Globe04-Bqrij7bv.js → Globe04-BAURDfvu.js} +1 -1
- package/dist/client/assets/{HardDrive-DJgL_JOo.js → HardDrive-Cd282Mai.js} +1 -1
- package/dist/client/assets/{Key01-WmVZ8QXt.js → Key01-mbqRH6mK.js} +1 -1
- package/dist/client/assets/{LayoutLeft-Cxosu4Vt.js → LayoutLeft-DC6WJh9Y.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BjhdSnR3.js → LinkExternal01-DhYqUjKN.js} +1 -1
- package/dist/client/assets/{LockUnlocked01-BSzBmosQ.js → LockUnlocked01-EXLocz58.js} +1 -1
- package/dist/client/assets/{LogOut01-M0Karp0_.js → LogOut01-C0GCrbOu.js} +1 -1
- package/dist/client/assets/{Monitor01-D8Oqtnh3.js → Monitor01-D1Ywzeig.js} +1 -1
- package/dist/client/assets/{Palette-BU4Si7Wh.js → Palette-DBmNDW91.js} +1 -1
- package/dist/client/assets/{Play-XYqRlm8a.js → Play-BvFv415E.js} +1 -1
- package/dist/client/assets/{Plus-Beu31VvD.js → Plus-183giWYf.js} +1 -1
- package/dist/client/assets/{SearchLg-ctNZwaUj.js → SearchLg-B7BxifEX.js} +1 -1
- package/dist/client/assets/{SearchMd-CrfRVVNu.js → SearchMd-CM8BurdL.js} +1 -1
- package/dist/client/assets/{Settings02-DjCcM4YH.js → Settings02-CDCqmH2y.js} +1 -1
- package/dist/client/assets/{Share07-_nwKmR9H.js → Share07-4wiqviev.js} +1 -1
- package/dist/client/assets/{Shield01-w6inEe2u.js → Shield01-BpVwYc8W.js} +1 -1
- package/dist/client/assets/{Stars01-C_iarf2U.js → Stars01-BNF996_E.js} +1 -1
- package/dist/client/assets/{Stars02-CzGdY2r0.js → Stars02-DK8tfpbc.js} +1 -1
- package/dist/client/assets/{Sun-BuLGisqZ.js → Sun-GtaTfxOx.js} +1 -1
- package/dist/client/assets/{SwitchHorizontal01-Ai8WkF2C.js → SwitchHorizontal01-SB503joS.js} +1 -1
- package/dist/client/assets/{Tool01-CmewmN8z.js → Tool01-D0IxVPmR.js} +1 -1
- package/dist/client/assets/{Tool02-CIq5KPgH.js → Tool02-Dw-UoNMF.js} +1 -1
- package/dist/client/assets/{Trash01-_QtQD9Y8.js → Trash01-xAMG4igT.js} +1 -1
- package/dist/client/assets/{TrendUp01-DFsn-nmD.js → TrendUp01-CyDskMTc.js} +1 -1
- package/dist/client/assets/{Upload01-C7JN7_i1.js → Upload01-CXYdms2a.js} +1 -1
- package/dist/client/assets/{User01-Dv8gliJ8.js → User01-BuGMrYkY.js} +1 -1
- package/dist/client/assets/{Users01-BNRCLVLR.js → Users01-B4ufXHfS.js} +1 -1
- package/dist/client/assets/{Users03-Ps3JKhNc.js → Users03-C8lJ4QPE.js} +1 -1
- package/dist/client/assets/{X-Bc21exsC.js → X-CFtahbse.js} +1 -1
- package/dist/client/assets/{XCircle-D3PkxCJR.js → XCircle-CjCSqvRp.js} +1 -1
- package/dist/client/assets/{XClose-C-dp2TW3.js → XClose-hFhPw2cX.js} +1 -1
- package/dist/client/assets/{YAxis-D06Q-cZ8.js → YAxis-BVXr0BmV.js} +1 -1
- package/dist/client/assets/{Zap-xSjXNKoR.js → Zap-DSqgHmL9.js} +1 -1
- package/dist/client/assets/{ZapSquare-DdmGlJDv.js → ZapSquare-OwtsgqsS.js} +1 -1
- package/dist/client/assets/{access-gate-DT76HnbT.js → access-gate-fjV0y2jb.js} +1 -1
- package/dist/client/assets/agent-icon-JCSxz6gi.js +1 -0
- package/dist/client/assets/agents-list-DaGM2H7k.js +1 -0
- package/dist/client/assets/ai-providers-DHcZaksx.js +1 -0
- package/dist/client/assets/{alert-dialog-C5aixBa-.js → alert-dialog-BaeQkFB7.js} +1 -1
- package/dist/client/assets/{alert-B5SrlnQS.js → alert-v-t6mrgX.js} +1 -1
- package/dist/client/assets/{api-keys-Cfkis4BG.js → api-keys-CkkVYEIe.js} +1 -1
- package/dist/client/assets/app-editor-Emo1wnmS.js +1 -0
- package/dist/client/assets/{auth-DSeANwkS.js → auth-M5FlCsXs.js} +1 -1
- package/dist/client/assets/{auth-catchall-DH3MdMMP.js → auth-catchall-OfwbBs9h.js} +1 -1
- package/dist/client/assets/{auth-entry-ovq7tYcR.js → auth-entry-DUucydDK.js} +1 -1
- package/dist/client/assets/{auth-split-layout-QkUaJV5m.js → auth-split-layout-DYzg1Qc8.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-BjwtT0ab.js → authenticate-and-persist-oauth-DoSR4iKF.js} +1 -1
- package/dist/client/assets/{automation-list-row-CFqmtzgR.js → automation-list-row-Ba1IUTNo.js} +1 -1
- package/dist/client/assets/{automation-runs-ZYVEpsZX.js → automation-runs-BbcZJUyD.js} +16 -16
- package/dist/client/assets/automations-OOI7bWx-.js +1 -0
- package/dist/client/assets/{avatar-BGP-avp4.js → avatar-6w4t2nGf.js} +1 -1
- package/dist/client/assets/{badge-D0q0tCmx.js → badge-t-2thrpZ.js} +1 -1
- package/dist/client/assets/{billing-Cx1PkhRS.js → billing-Bzj9k8ua.js} +1 -1
- package/dist/client/assets/{block-document-DlfPvomd.js → block-document-BRRPfXBO.js} +1 -1
- package/dist/client/assets/{buckets-Bn1jTc51.js → buckets-DTAYBoD2.js} +1 -1
- package/dist/client/assets/bulk-category-panel-BJEYlps2.js +1 -0
- package/dist/client/assets/{capability-load-error-CKdQNufy.js → capability-load-error-C0ztJ_Ig.js} +1 -1
- package/dist/client/assets/{card-B6s-X_7q.js → card-CZLDmlyM.js} +1 -1
- package/dist/client/assets/cards-CxicMSJC.js +9 -0
- package/dist/client/assets/category-editor-DLPuKHh-.js +1 -0
- package/dist/client/assets/{chart-B7nZ8pjs.js → chart-CAto47lg.js} +1 -1
- package/dist/client/assets/{chat-context-CkD6Rm1l.js → chat-context-CVRXzKpr.js} +1 -1
- package/dist/client/assets/{checkbox-SU4x7etH.js → checkbox-CvQFDXhk.js} +1 -1
- package/dist/client/assets/{cli-auth-success-DbLb2lL3.js → cli-auth-success-CsuxPjv_.js} +1 -1
- package/dist/client/assets/collection-detail-BfyX0et5.js +1 -0
- package/dist/client/assets/{collection-display-button-o0ZpnDLT.js → collection-display-button-CeJFFjyk.js} +1 -1
- package/dist/client/assets/{collection-search-B9FHnrlK.js → collection-search-B-SPD0Km.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-CHuYWW3f.js → collection-table-wrapper-C0hCnz6-.js} +1 -1
- package/dist/client/assets/{collection-tabs-CTztoi_L.js → collection-tabs-C-XFHKK4.js} +1 -1
- package/dist/client/assets/{command-9SJIiMMJ.js → command-C0az0b8t.js} +1 -1
- package/dist/client/assets/commerce-onboarding-Bj8hKn97.js +1 -0
- package/dist/client/assets/{connect-D3SR0gqF.js → connect-CxV3qWBq.js} +1 -1
- package/dist/client/assets/{connection-CcZxGNbF.js → connection-X8aleug0.js} +1 -1
- package/dist/client/assets/{connection-card-CSTEPEAl.js → connection-card-BAXxPPFo.js} +1 -1
- package/dist/client/assets/connection-detail-7KM4tc3e.js +1 -0
- package/dist/client/assets/{connection-form-helpers-CAWuRDfe.js → connection-form-helpers-DA7t7XXZ.js} +1 -1
- package/dist/client/assets/connections-NHAu-l0D.js +1 -0
- package/dist/client/assets/{decopilot-sse-pool-DPwEBX2U.js → decopilot-sse-pool-DIk3pxOB.js} +1 -1
- package/dist/client/assets/{dialog-CRQLMTBJ.js → dialog-DV18W6Yx.js} +1 -1
- package/dist/client/assets/{domain-settings-Bpc-HBB5.js → domain-settings-Degjs_Ra.js} +1 -1
- package/dist/client/assets/{drawer-DYhKMhrd.js → drawer-YXQaX_y_.js} +1 -1
- package/dist/client/assets/{dropdown-menu-0pSlZu2s.js → dropdown-menu-Bz4edgHd.js} +1 -1
- package/dist/client/assets/{empty-state-CTZGG5L9.js → empty-state-DAwc227L.js} +1 -1
- package/dist/client/assets/{extract-connection-data-D2Rvpp_3.js → extract-connection-data-BOM-VC2a.js} +1 -1
- package/dist/client/assets/file-explorer-DgaCxj63.js +2 -0
- package/dist/client/assets/{file-type-icon-BStuf1sH.js → file-type-icon-BiDvFSRa.js} +1 -1
- package/dist/client/assets/{form-CAuMNyGV.js → form-B9M2sKi3.js} +1 -1
- package/dist/client/assets/general-CIC9nSes.js +1 -0
- package/dist/client/assets/{github-repo-picker-CpkkHZIF.js → github-repo-picker-CYAs_tSm.js} +1 -1
- package/dist/client/assets/{hooks-Dconqo8e.js → hooks-Dhj1Xj9t.js} +1 -1
- package/dist/client/assets/{index-CU49llDJ.js → index-5w9oF367.js} +2 -2
- package/dist/client/assets/{index-DkG1WKnv.js → index-BIngEGJF.js} +1 -1
- package/dist/client/assets/{index-DinNtldY.js → index-BrXlWoMq.js} +1 -1
- package/dist/client/assets/{index-CzE82-fO.js → index-C6ebGaw_.js} +1 -1
- package/dist/client/assets/{index-SQAL2Po3.js → index-CCAGgYK0.js} +1 -1
- package/dist/client/assets/{index-CWW_VhWW.js → index-CbHqDGBA.js} +36 -36
- package/dist/client/assets/{index-DALKCDkR.js → index-CtW1djEc.js} +1 -1
- package/dist/client/assets/{index-CvbvPSw1.js → index-H2VxcyQH.js} +1 -1
- package/dist/client/assets/index-PRPKuR9Q.js +1 -0
- package/dist/client/assets/{index-Ckn2SAtv.js → index-rP33bQlN.js} +12 -12
- package/dist/client/assets/{index-redirect-DZqCPWrl.js → index-redirect-DwkhDSou.js} +1 -1
- package/dist/client/assets/{infra-billing-X97xqG8z.js → infra-billing-DUmrumkB.js} +1 -1
- package/dist/client/assets/{input-033UIAd3.js → input-BkCJTDrP.js} +1 -1
- package/dist/client/assets/{integration-icon-CW3TfCPl.js → integration-icon-q-JlSkbf.js} +1 -1
- package/dist/client/assets/{invite-member-dialog-DSuSH2Bn.js → invite-member-dialog-C-5Nd4zW.js} +1 -1
- package/dist/client/assets/{label-BlznzMhv.js → label-DQKQ8lEd.js} +1 -1
- package/dist/client/assets/{layout-B-zy_djv.js → layout-X8EQrkUX.js} +1 -1
- package/dist/client/assets/{login-D7Ayb_mN.js → login-DcHBdKPJ.js} +1 -1
- package/dist/client/assets/{mcp-oauth-DVQQO3hY.js → mcp-oauth-B5CECs49.js} +1 -1
- package/dist/client/assets/{members-BREd8-zu.js → members-CfPp8RcB.js} +1 -1
- package/dist/client/assets/{monaco-editor-7mkphsHS.js → monaco-editor-CHK_WTN1.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-CCLMpVuV.js → monitoring-stats-row-CVEWE4Fd.js} +1 -1
- package/dist/client/assets/{multi-select-BRyr0E5T.js → multi-select-BUKy42et.js} +1 -1
- package/dist/client/assets/{oauth-callback-kzl5SlVO.js → oauth-callback-BDPrRF-o.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-DqhbuYc1.js → oauth-callback-ai-provider-DLXIVnfM.js} +1 -1
- package/dist/client/assets/{onboarding-BofSB4PB.js → onboarding-TVyuaga-.js} +1 -1
- package/dist/client/assets/{org-layout-BWXXOPjv.js → org-layout-fQ1dxK8S.js} +1 -1
- package/dist/client/assets/{organization-choice-BvVEAsXL.js → organization-choice-CiaOuZu3.js} +1 -1
- package/dist/client/assets/{orgs-CZ7w4IkX.js → orgs-ar044Xjk.js} +1 -1
- package/dist/client/assets/{page-seo-form-C4DmOsVu.js → page-seo-form-VfWsE88H.js} +1 -1
- package/dist/client/assets/{popover-BjnUzD6X.js → popover-BFqFQf4f.js} +1 -1
- package/dist/client/assets/post-editor-DSjVWBl5.js +1 -0
- package/dist/client/assets/{primitives-2hE7GOVH.js → primitives-C0bsPQWu.js} +1 -1
- package/dist/client/assets/{profile-Cp0MQE5c.js → profile-DUsq9NF5.js} +1 -1
- package/dist/client/assets/project-app-view-DAA6fQeU.js +1 -0
- package/dist/client/assets/record-editor-S54mYWvP.js +1 -0
- package/dist/client/assets/redirect-editor-OoYwc6vQ.js +1 -0
- package/dist/client/assets/registry-DC4p8qDH.js +2 -0
- package/dist/client/assets/{registry-layout-DJKdYnZG.js → registry-layout-0D8i2a-K.js} +3 -3
- package/dist/client/assets/{reports-yJiJoqyv.js → reports-CuKybDwh.js} +1 -1
- package/dist/client/assets/{require-capability-Fzrnw44H.js → require-capability-BxGw2L90.js} +1 -1
- package/dist/client/assets/{required-auth-layout-CKO-W8hh.js → required-auth-layout-BIBsXtMo.js} +1 -1
- package/dist/client/assets/{reset-password-3zlCasG5.js → reset-password-DjY9EA4m.js} +1 -1
- package/dist/client/assets/roles-Bmd9cdRT.js +1 -0
- package/dist/client/assets/{search-input-BWqunmRq.js → search-input-CdEt0Dpt.js} +1 -1
- package/dist/client/assets/{secrets-C-c-qjgQ.js → secrets-CT9FyUhf.js} +1 -1
- package/dist/client/assets/{sections-editor-XJGfoB4V.js → sections-editor-DTGUO4Z6.js} +2 -2
- package/dist/client/assets/{select-CJxHvEHm.js → select-CA9WZQjc.js} +1 -1
- package/dist/client/assets/select-model-8Tx2fyM5.js +4 -0
- package/dist/client/assets/{self-tool-result-BxC3b6xs.js → self-tool-result-Dd3iJBUw.js} +1 -1
- package/dist/client/assets/seo-editor-DCZL7FmV.js +1 -0
- package/dist/client/assets/{settings-layout-Gjf7WBFi.js → settings-layout-CITrZViJ.js} +1 -1
- package/dist/client/assets/{settings-section-3mgQUekG.js → settings-section-U_d9SZ5z.js} +1 -1
- package/dist/client/assets/{settings-subnav-ByjVZ9_c.js → settings-subnav-CU4zvN8b.js} +1 -1
- package/dist/client/assets/{shell-controls-DkVuUh-D.js → shell-controls-OYFwRgxx.js} +1 -1
- package/dist/client/assets/{shell-layout-B48CP4qv.js → shell-layout-DZNAvGub.js} +1 -1
- package/dist/client/assets/{sidebar-DoSaJzfh.js → sidebar-CbAXZRty.js} +1 -1
- package/dist/client/assets/{skeleton-DESj-M-E.js → skeleton-Baz5nFrz.js} +1 -1
- package/dist/client/assets/{spinner-BUSgQvV9.js → spinner-DxScZBKB.js} +1 -1
- package/dist/client/assets/{sso-Al9ETsbg.js → sso-6nyhXisL.js} +1 -1
- package/dist/client/assets/{store-9WOeRNsD.js → store-C2pKj8sd.js} +1 -1
- package/dist/client/assets/store-registry-CSkrVbdj.js +2 -0
- package/dist/client/assets/{studio-tools-B9Ct3_YC.js → studio-tools-VUr_6R55.js} +1 -1
- package/dist/client/assets/{switch-DBix4dGe.js → switch-gXErSebn.js} +1 -1
- package/dist/client/assets/synced-repos-CBjsmnWh.js +1 -0
- package/dist/client/assets/tab-id-CcDWY6Z5.js +1 -0
- package/dist/client/assets/{table-B2oaMHDO.js → table-BomvPzw1.js} +1 -1
- package/dist/client/assets/{tabs-IZkuMTkN.js → tabs-ByC6UswV.js} +1 -1
- package/dist/client/assets/tasks-CuhWDed7.js +1 -0
- package/dist/client/assets/{textarea-D8uJ17IC.js → textarea-Cmbx33e9.js} +1 -1
- package/dist/client/assets/{toggle-group-CY8Vk8gH.js → toggle-group-D4zn64EK.js} +1 -1
- package/dist/client/assets/{toolbar-B1fZNVFp.js → toolbar-Db9EKJVj.js} +1 -1
- package/dist/client/assets/{tooltip-BLoH72H_.js → tooltip-CjWdSuMr.js} +1 -1
- package/dist/client/assets/{track-DJo1DwOE.js → track-Bb2qAfNZ.js} +1 -1
- package/dist/client/assets/{types-DeLO2iP6.js → types-BOZwIefN.js} +1 -1
- package/dist/client/assets/{use-ai-providers-DFB4FltD.js → use-ai-providers-k4pjcS3t.js} +1 -1
- package/dist/client/assets/{use-api-keys-D23iLtT8.js → use-api-keys-Cw-Cv09b.js} +1 -1
- package/dist/client/assets/{use-automations-DSxQRe0A.js → use-automations-CV8c2KIQ.js} +1 -1
- package/dist/client/assets/{use-autosave-DQimJC28.js → use-autosave-HbmpHR38.js} +1 -1
- package/dist/client/assets/{use-capability-BS9lZAmO.js → use-capability-BxvzMTBW.js} +1 -1
- package/dist/client/assets/{use-clock-tick-CDVao7cr.js → use-clock-tick-bYeZWlWy.js} +1 -1
- package/dist/client/assets/{use-commerce-diagnostic-C75dfvGU.js → use-commerce-diagnostic-DZ8-RWdI.js} +1 -1
- package/dist/client/assets/{use-connection-CtbwqEgR.js → use-connection-CYuunbtf.js} +1 -1
- package/dist/client/assets/{use-copy-BQc_zaTa.js → use-copy-CD6Jpi9s.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-C9Bsz2lP.js → use-create-virtual-mcp-ALSzfOtx.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-76bcg_cg.js → use-debounced-autosave-CuQc51JO.js} +1 -1
- package/dist/client/assets/{use-debounced-value-gZF3WfW1.js → use-debounced-value-9IZFnJOd.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-BN4-nZxC.js → use-decopilot-events-CnEWes5G.js} +1 -1
- package/dist/client/assets/{use-delete-connection-M3bsidfz.js → use-delete-connection-NUz645Q2.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-CH7xJf3e.js → use-deployment-admin-Cy9b9FZ0.js} +1 -1
- package/dist/client/assets/{use-file-configs-Dx7xwSzN.js → use-file-configs-S1p6BPLy.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-BYVKlMFT.js → use-infinite-scroll-2P9IYhHm.js} +1 -1
- package/dist/client/assets/{use-join-requests-UvImlwy9.js → use-join-requests-D0I_MKin.js} +1 -1
- package/dist/client/assets/{use-mcp-client-fJDYDlU9.js → use-mcp-client-BE_e-uEm.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-CWf9IZJb.js → use-mcp-tools-C_DeYZLk.js} +1 -1
- package/dist/client/assets/{use-members-2MwYNAyl.js → use-members-BlkVgAkC.js} +1 -1
- package/dist/client/assets/{use-mobile-C_wE74fy.js → use-mobile-CcypTxrj.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-FbpYb5Qu.js → use-navigate-to-agent-DXBflHYS.js} +1 -1
- package/dist/client/assets/{use-open-billing-url-SAk7c31b.js → use-open-billing-url-Bz2NF5sP.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-Dsqqo9TA.js → use-org-auth-client-DDrK6a1L.js} +1 -1
- package/dist/client/assets/{use-org-repo-syncs-rIsglk2d.js → use-org-repo-syncs-VOmFIF6x.js} +1 -1
- package/dist/client/assets/{use-org-sso-CwtFlYvS.js → use-org-sso-ZlmQXdwK.js} +1 -1
- package/dist/client/assets/{use-organization-roles-DcEcqFQc.js → use-organization-roles-BR-sb5ep.js} +1 -1
- package/dist/client/assets/{use-organization-settings-51Vgj4aH.js → use-organization-settings-CigEU-nL.js} +1 -1
- package/dist/client/assets/{use-registry-connections-Cr2-nQsF.js → use-registry-connections-DpPGnRab.js} +1 -1
- package/dist/client/assets/{use-secrets-D8qcP46x.js → use-secrets-DziYD0M6.js} +1 -1
- package/dist/client/assets/{use-section-preview-base-9Ic0FJS_.js → use-section-preview-base-09B4aWt-.js} +1 -1
- package/dist/client/assets/{use-settings-tabs-BJvLsXvA.js → use-settings-tabs-BGK4ZoR5.js} +1 -1
- package/dist/client/assets/{use-status-sounds-bXYnEckM.js → use-status-sounds-kD8SM-pB.js} +1 -1
- package/dist/client/assets/{use-tags-DtlP3bNr.js → use-tags-CUJjaXC6.js} +1 -1
- package/dist/client/assets/{use-view-mode-PlD_tVP0.js → use-view-mode-Bln07e-3.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-BX9f53BJ.js → use-virtual-mcp-DhY25Szl.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-sIgcqV0U.js +1 -0
- package/dist/client/assets/{useRouterState-ZW2MxINW.js → useRouterState-B7wg4Z59.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-xXNO1vN3.js +1 -0
- package/dist/client/assets/{users-CNeiktS7.js → users-BW9rR2JN.js} +1 -1
- package/dist/client/assets/variant-calendar-D77dQCtJ.js +1 -0
- package/dist/client/assets/{view-mode-toggle-CU01TMfv.js → view-mode-toggle-hhxSebBr.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/client/install.sh +443 -45
- package/dist/server/cli.js +3 -3
- package/dist/server/server.js +3 -3
- package/package.json +1 -1
- package/dist/client/assets/Globe01-D_2HJX-I.js +0 -1
- package/dist/client/assets/agent-icon-CRyupzh3.js +0 -1
- package/dist/client/assets/agents-list-cVl-UZFI.js +0 -1
- package/dist/client/assets/ai-providers-D9tdPwkm.js +0 -1
- package/dist/client/assets/app-editor-BqpUNh9_.js +0 -1
- package/dist/client/assets/automations-Dk6ZV6Eb.js +0 -1
- package/dist/client/assets/bulk-category-panel-DMni3s7V.js +0 -1
- package/dist/client/assets/cards-D3ylftrl.js +0 -9
- package/dist/client/assets/category-editor-BFcnjGRo.js +0 -1
- package/dist/client/assets/collection-detail-BxSstYra.js +0 -1
- package/dist/client/assets/commerce-onboarding-BhswfRNb.js +0 -1
- package/dist/client/assets/connection-detail-ZgJQ7OvZ.js +0 -1
- package/dist/client/assets/connections-ZotNV6n8.js +0 -1
- package/dist/client/assets/file-explorer-BLHd0BVU.js +0 -2
- package/dist/client/assets/general-CD1AT3tQ.js +0 -1
- package/dist/client/assets/index-DiJ_A5BP.js +0 -1
- package/dist/client/assets/post-editor-GruQqpeL.js +0 -1
- package/dist/client/assets/project-app-view-dQmr9egb.js +0 -1
- package/dist/client/assets/record-editor-CuQ7aMF4.js +0 -1
- package/dist/client/assets/redirect-editor-BtP9Suy0.js +0 -1
- package/dist/client/assets/registry-DvcPDCWO.js +0 -2
- package/dist/client/assets/roles-CGQqEhv-.js +0 -1
- package/dist/client/assets/select-model-Bwc94yCX.js +0 -4
- package/dist/client/assets/seo-editor-CnXY0_68.js +0 -1
- package/dist/client/assets/store-registry-Dh0rL2Qs.js +0 -2
- package/dist/client/assets/synced-repos-BbnsPm_Q.js +0 -1
- package/dist/client/assets/tab-id-BkooGyuQ.js +0 -1
- package/dist/client/assets/tasks-TdSCx-Ct.js +0 -1
- package/dist/client/assets/useInfiniteQuery-QYDYXkJa.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CbXYLrJc.js +0 -1
- package/dist/client/assets/variant-calendar-1ktwOI__.js +0 -1
package/dist/server/server.js
CHANGED
|
@@ -1046,8 +1046,8 @@ ${X}
|
|
|
1046
1046
|
Pass the connectionId of the repo to load.`}async function pQ$($){let{ctx:Z,orgId:X,virtualMcpId:Q,userId:Y,threadId:G,writer:J,rebindFs:W}=$;if(!IG(Q))return null;let K=await FJ4(Z,X);if(K.length===0)return null;let H=new Map(K.map((F)=>[F.connectionId,F]));return b$({description:UJ4(K),inputSchema:Z0(dQ$.object({connectionId:dQ$.string().describe("connectionId of the imported repository to load (see the list in this tool's description).")})),execute:async({connectionId:F})=>{let N=H.get(F);if(!N)return{success:!1,error:`No imported repository found for connectionId "${F}". Available: ${K.map((C)=>C.connectionId).join(", ")||"none"}.`};let U=VF(G,N.connectionId),O={url:`https://github.com/${N.owner}/${N.repo}`,owner:N.owner,name:N.repo,installationId:N.installationId,connectionId:N.connectionId},B=await Z.storage.threads.get(G);await Z.storage.threads.update(G,{metadata:{...B?.metadata??{},githubRepo:O},branch:U,updated_by:Y});let{kind:D}=await oX(Z,{userId:Y,branch:U,virtualMcpMetadata:null}),L=await Qy({virtualMcpId:Q,branch:U,sandboxProviderKind:D},Z),E=ei(B5(B?.metadata),Y,U,D,L);J.write({type:"data-open-preview",id:G,data:{previewUrl:L.previewUrl??null,branch:U,githubRepo:O,sandboxMap:E,sandboxProviderKind:D}});let j=await Yy(Z,{virtualMcpId:Q,branch:U,userId:Y,threadId:G}),z=Date.now()+mQ$,A="",P=!1,M=0,q=null;while(Date.now()<z){let C=await j.onBash("if git -C /app/repo rev-parse HEAD >/dev/null 2>&1; then echo __CLONED__; fi; ls -A /app/repo 2>/dev/null").then((f)=>({ok:!0,stdout:f.stdout})).catch(()=>({ok:!1,stdout:""}));if(!C.ok){if(++M>=HJ4)break;await q$(iQ$);continue}M=0;let l=NJ4(C.stdout);if(l.cloned&&l.listing===q){P=!0,A=l.listing;break}q=l.cloned?l.listing:null,await q$(iQ$)}let k=!1;if(P&&W)try{await W(U),k=!0}catch(C){console.warn("[load_repo] live fs rebind failed",C)}return{success:!0,repo:`${N.owner}/${N.repo}`,previewUrl:L.previewUrl??null,cloned:P,files:A,message:!P?`Loaded ${N.owner}/${N.repo} and opened the Preview, but the clone did not finish within ${Math.round(mQ$/1000)}s. It may still be in progress \u2014 your file tools will use it next message.`:k?`Loaded ${N.owner}/${N.repo} and opened the Preview. The repo is cloned and its dev server is booting. Your file tools (read/write/edit/bash/grep/glob) now operate on it \u2014 you can use it right away.`:`Loaded ${N.owner}/${N.repo} and opened the Preview. The repo is cloned and its dev server is booting. Your file tools operate on it from your next message.`}}})}var mQ$=120000,iQ$=1500,HJ4=5;var bO0=w(()=>{u4();_4();JB();AQ();U8();dX();fp();S3();fO0()});import{AsyncLocalStorage as OJ4}from"async_hooks";function xO0(){let $=yS.getStore();if(!$)throw Error("This tool is only available on a task run's MCP endpoint (/api/<org>/mcp/task-run/<threadId>).");return $}function tQ$($){return G90.some((X)=>ki($,X))?BJ4:nQ$}var yS,nQ$,BJ4;var Jy=w(()=>{L9();yS=new OJ4;nQ$=["TASK_ADD_REPO","TASK_BOARD_ITEM_LIST","TASK_BOARD_ITEM_UPDATE","TASK_BOARD_ITEM_PRS_GET","TASK_BOARD_ITEM_PR_LINK","TASK_BOARD_ACTIVITY_LIST","TASK_BOARD_COMMENT_LIST","TASK_BOARD_COMMENT_CREATE","TASK_BOARD_COMMENT_UPDATE"],BJ4=[...nQ$,"TASK_BOARD_REVIEW_DECISION"]});import{z as mG}from"zod";async function jJ4($,Z,X,Q,Y){return F9(async()=>{let G=KK(await qO0($,Z),X,Q,Y);if(!G)throw Error("sandbox record not written yet");return G},{maxAttempts:DJ4,minTimeout:LJ4,maxTimeout:EJ4,jitter:0}).catch(()=>null)}async function aQ$($,Z,X,Q){let Y=await $.proxyDaemonRequest(Z,"/_sandbox/bash",{method:"POST",headers:new Headers({"content-type":"application/json","x-thread-id":X}),body:JSON.stringify({command:Q})});if(!Y.ok)throw Error(`sandbox bash failed (${Y.status} ${Y.statusText})`);let G=await Y.json();return{stdout:G.stdout??"",exitCode:G.exitCode??0}}function PJ4($){let Z=$.split(`
|
|
1047
1047
|
`).map((X)=>X.trim()).filter((X)=>X&&X!==".git"&&X!=="__CLONED__");return{cloned:Z.length>0,listing:Z.join(`
|
|
1048
1048
|
`)}}async function TJ4($,Z){let{items:X}=await $.storage.connections.list(Z,{slug:"mcp-github"});return Gy(X)}var wJ4=3300000,DJ4=4,LJ4=250,EJ4=2000,oQ$=180000,rQ$=1500,zJ4=5,AJ4,Yp0;var sQ$=w(()=>{_0();bO0();_O0();JB();gx();dX();S3();u4();Jy();AJ4=['token=$(git remote get-url origin | sed -n "s|.*x-access-token:\\([^@]*\\)@.*|\\1|p")','[ -n "$token" ] || exit 0','mkdir -p "${HOME:-/root}/.config/gh"',"umask 077",'printf "github.com:\\n oauth_token: %s\\n git_protocol: https\\n" "$token" > "${HOME:-/root}/.config/gh/hosts.yml"'].join(`
|
|
1049
|
-
`);Yp0=c({name:"TASK_ADD_REPO",description:"Clone one of this organization's repositories into your working directory. "+"Your working directory is EMPTY until you call this \u2014 do not look for "+"files, and do not run git, before it returns. Call it once, with the repository the task is about; it waits for the checkout and returns the repository root listing, so you can start reading files immediately after. `git` and `gh` are authenticated once it returns. Call TASK_ADD_REPO with no arguments to list the repositories available.",annotations:{title:"Add Repository",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:mG.object({connectionId:mG.string().optional().describe("connectionId of the repository to clone. Omit to list the available repositories.")}),outputSchema:mG.object({success:mG.boolean(),repositories:mG.array(mG.object({connectionId:mG.string(),repo:mG.string()})).optional(),repo:mG.string().optional(),cloned:mG.boolean().optional(),files:mG.string().optional(),message:mG.string()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=J1(Z);if(!Q)throw Error("User ID required");let{threadId:Y}=xO0(),G=await TJ4(Z,X.id),J=$.connectionId?G.find((q)=>q.connectionId===$.connectionId):void 0;if(!J){let q=G.map((k)=>({connectionId:k.connectionId,repo:`${k.owner}/${k.repo}`}));return{success:!1,repositories:q,message:$.connectionId?`No imported repository for connectionId "${$.connectionId}". Pick one of the repositories listed.`:q.length===0?"This organization has no repositories imported, so none can be cloned.":"Pick a repository and call TASK_ADD_REPO again with its connectionId."}}let W=await Z.storage.threads.get(Y);if(!W)throw Error(`Thread not found: ${Y}`);let K=await IO0(Z,{threadId:Y}),H=await CF(Z,K,Q),{provider:F,kind:N}=await oX(Z,{userId:H,branch:K,virtualMcpMetadata:null}),U=await jJ4(Z,Y,H,K,N);if(!U)throw Error(`No sandbox is registered for this run (thread ${Y}), so there is nowhere to clone into.`);await iO({ctx:Z,connectionId:J.connectionId,organizationId:X.id,forceRefresh:!0,onLegacyMintError:(q)=>console.error("[TASK_ADD_REPO] legacy repo-scoped mint failed",{connectionId:J.connectionId,error:q.message})});let{cloneUrl:O,gitUserName:B,gitUserEmail:D}=await pO(J.connectionId,J.owner,J.repo,Z.db,Z.vault,{bufferMs:wJ4});await Z.storage.threads.update(Y,{metadata:{...W.metadata??{},githubRepo:{url:`https://github.com/${J.owner}/${J.repo}`,owner:J.owner,name:J.repo,installationId:J.installationId,connectionId:J.connectionId}},updated_by:Q});let L=CO0({branch:K,derivedRef:SF(K),recordedHeadRef:null,sticky:!1}),E=await F.proxyDaemonRequest(U.sandboxHandle,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({git:{repository:{cloneUrl:O,branch:L,repoName:`${J.owner}/${J.repo}`},identity:{userName:B,userEmail:D}}})});if(!E.ok)throw Error(`the sandbox rejected the repository (${E.status} ${E.statusText})`);await F.proxyDaemonRequest(U.sandboxHandle,"/_sandbox/setup/clone",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:"{}"}).catch((q)=>{console.warn("[TASK_ADD_REPO] explicit clone kick failed",q)});let j=Date.now()+oQ$,z=!1,A="",P=0,M=null;while(Date.now()<j){let q=await aQ$(F,U.sandboxHandle,Y,"if git rev-parse HEAD >/dev/null 2>&1; then echo __CLONED__; fi; ls -A 2>/dev/null").catch(()=>null);if(!q){if(++P>=zJ4)break;await q$(rQ$);continue}P=0;let k=PJ4(q.stdout);if(k.cloned&&k.listing===M){z=!0,A=k.listing;break}M=k.cloned?k.listing:null,await q$(rQ$)}if(z)await aQ$(F,U.sandboxHandle,Y,AJ4).catch((q)=>console.warn("[TASK_ADD_REPO] gh auth setup failed",q));return{success:z,repo:`${J.owner}/${J.repo}`,cloned:z,files:A,message:z?`${J.owner}/${J.repo} is checked out at your working directory on branch ${L}. \`git\` and \`gh\` are authenticated. Start working.`:`The clone of ${J.owner}/${J.repo} did not finish within ${Math.round(oQ$/1000)}s. It may still be in progress \u2014 check your working directory before calling this again.`}}})});import{z as e1}from"zod";var C3,gS,RJ4,IJ4,eQ$,Wy,qJ4,MJ4,$Y$;var _3=w(()=>{L9();C3=e1.enum(["triage","todo","in_progress","in_review","done","archived"]),gS=e1.enum(["none","low","medium","high","urgent"]),RJ4=e1.object({threadId:e1.string(),virtualMcpId:e1.string().nullable(),status:e1.enum(["in_progress","requires_action","failed","completed","expired"]).nullable(),title:e1.string().nullable(),lastMessage:e1.string().nullable(),hasPreview:e1.boolean(),failureKind:e1.string().nullable(),hasMessages:e1.boolean(),costUsd:e1.number().nullable(),createdAt:e1.string()}),IJ4=e1.object({id:e1.string(),name:e1.string(),color:e1.string().nullable().describe('Hex color, e.g. "#3b82f6"'),createdBy:e1.string(),createdAt:e1.string().datetime()}),eQ$=e1.object({url:e1.string(),number:e1.number(),repoOwner:e1.string(),repoName:e1.string(),createdAt:e1.string(),title:e1.string().nullable(),body:e1.string().nullable(),state:e1.enum(["open","closed"]).nullable(),draft:e1.boolean().nullable(),merged:e1.boolean().nullable(),mergeable:e1.boolean().nullable(),checksStatus:e1.enum(["pending","passing","failing"]).nullable(),checks:e1.array(e1.object({name:e1.string(),status:e1.string(),conclusion:e1.string().nullable(),detailsUrl:e1.string().nullable(),summary:e1.string().nullable()})),previewUrl:e1.string().nullable()}),Wy=e1.object({id:e1.string(),organizationId:e1.string(),title:e1.string(),description:e1.string().nullable(),status:C3,priority:gS,assigneeId:e1.string().nullable(),assignedBy:e1.string().nullable(),repo:e1.string().nullable(),dueDate:e1.string().datetime().nullable(),sortOrder:e1.number(),threads:e1.array(RJ4),tags:e1.array(IJ4),createdBy:e1.string(),createdAt:e1.string().datetime(),updatedBy:e1.string(),updatedAt:e1.string().datetime()}),qJ4=["created","status_changed","assignee_changed","priority_changed","due_date_changed","title_changed","description_changed","tags_changed","review_requested","review_approved","review_changes_requested","merge_conflict_resolution","merge_failed"],MJ4=e1.enum(qJ4),$Y$=e1.object({id:e1.string(),taskBoardItemId:e1.string(),action:MJ4,actorId:e1.string().nullable(),data:e1.record(e1.string(),e1.unknown()),occurredAt:e1.string().datetime()})});async function yO0($,Z,X){if(X===n8)return;let{members:Q}=await $.boundAuth.organization.listMembers({organizationId:Z,filterField:"userId",filterValue:X});if(!Q.some((Y)=>Y.userId===X))throw Error("assigneeId is not a member of the organization")}var Gp0=w(()=>{_3()});function QY$($){let Z={};for(let[X,Q]of Object.entries($)){if(X.startsWith(kJ4))continue;Z[X]=Q}return Z}function gO0($){return{taskBoardItemId:$.id,...MQ($)&&{[ZY$]:XY$}}}function VJ4($){return $?.[ZY$]===XY$}function SJ4($){if(/[:\s]/.test($))throw Error("organization id unsuitable for the subsidy key scheme");return`subsidy:${$}`}async function CJ4($,Z){let X=b0();try{let Q=await $.storage.subsidizedGatewayKeys.get(Z);if(Q)return Q;let Y=$.auth?.user?.id;if(Y&&X.aiGatewayEnabled&&X.studioProvisionSecretKey&&DO.provisionKey){let G=await TW(Y,$.auth?.user?.email),J=await DO.provisionKey(G,SJ4(Z));return await $.storage.subsidizedGatewayKeys.put(Z,J),J}}catch(Q){console.error("[subsidized-runs] subsidy key unavailable \u2014 run stays on the org's key:",Q)}return}async function YY$($,Z,X){if(!b0().taskQuotaEnforced)return;if(!VJ4(X))return;let Q=X?.taskBoardItemId;if(!Q)return;let Y=await $.storage.taskBoard.getById(Q,Z);if(!Y||!MQ(Y))return;if(!await ma1($,Q))return;return await CJ4($,Z)}function GY$($,Z){if(!Z)return $;if($.providerId!=="deco")return $;return{...$,apiKey:Z}}var kJ4="srv.",ZY$="srv.billing",XY$="subscription";var bp=w(()=>{Y50();OU();T$();L3()});function uO0($){let Z=$?.runClass;return Z&&Z in Jp0?Jp0[Z]:Jp0.interactive}var Jp0,hO0="runClass";var xp=w(()=>{Jp0={interactive:10,reviewer:20,retry:30,new_task:40}});async function Wp0($,Z,X){let Q;try{return await Promise.race([$.aiProviders.listModels(Z,X),new Promise((G,J)=>{Q=setTimeout(()=>J(Error("listModels timeout")),_J4)})])}finally{if(Q)clearTimeout(Q)}}function vJ4($,Z){switch($){case"fast":return Z.chat.fast;case"smart":return Z.chat.smart;case"thinking":return Z.chat.thinking;case"image":return Z.image;case"web_search":return Z.webSearch;case"deep_research":return Z.deepResearch}}function Kp0($,Z,X){let Q=$.find((Y)=>Y.modelId===Z);return{title:Q?.title??X??Z,providerId:Q?.providerId,capabilities:Q?.capabilities,limits:Q?.limits??null}}async function e7($,Z,X){let Q=$.organization?.id;if(!Q)throw Error("resolveTier called without an organization");let G=(await $.storage.organizationSettings.get(Q))?.simple_mode?.tiers?.[Z]??null,J=$.auth?.user?.id,W=kO.safeParse(Z),K=X?.applyUserPrefs&&W.success&&J?(await $.storage.userModelPreferences.get(J,Q))?.tiers?.[W.data]??null:null,H=(await $.storage.aiProviderKeys.list({organizationId:Q})).filter((B)=>kD(B.providerId));for(let B of[K,G])if(B&&H.some((D)=>D.id===B.keyId)){let D=await Wp0($,B.keyId,Q).catch(()=>[]);return{credentialId:B.keyId,modelId:B.modelId,modelMeta:Kp0(D,B.modelId,B.title)}}if(H.length===0)throw new Ky(Z);let F={};await Promise.all(H.map(async(B)=>{F[B.id]=await Wp0($,B.id,Q).catch(()=>[])}));let N=H.map((B)=>({id:B.id,providerId:B.providerId,label:B.label,presetId:B.presetId,createdBy:B.createdBy,createdAt:B.createdAt})),U=ax1(N,F),O=vJ4(Z,U);if(!O)throw new Ky(Z);return{credentialId:O.keyId,modelId:O.modelId,modelMeta:Kp0(F[O.keyId]??[],O.modelId,O.title)}}async function JY$($,Z,X){let Q=$.organization?.id;if(!Q)throw Error("resolveSpecificModel called without an organization");let Y=await $.storage.aiProviderKeys.findById(Z,Q).catch((J)=>{if(J instanceof Error&&J.message==="Provider key not found")throw new yp(`AI provider credential "${Z}" was not found`,{cause:J});throw J});if(!kD(Y.providerId))throw new yp(`AI provider credential "${Z}" uses native-only provider "${Y.providerId}" and cannot run a hosted model`);let G=await Wp0($,Z,Q).catch(()=>[]);return{credentialId:Z,modelId:X,modelMeta:Kp0(G,X)}}async function iG($,Z){try{return await e7($,Z)}catch(X){if(X instanceof Ky)return null;return console.warn(`[resolveTier] tier "${Z}" resolution failed:`,X),null}}var Ky,yp,_J4=5000;var NB=w(()=>{RQ();U8();Ky=class Ky extends Error{tier;constructor($){super(`No model available for tier "${$}". Connect a provider or configure the tier in organization settings.`);this.tier=$;this.name="TierUnavailableError"}};yp=class yp extends Error{constructor($,Z){super($,Z);this.name="SpecificModelCredentialUnavailableError"}}});function WY$($){return $ instanceof wK||typeof $==="object"&&$!==null&&$.permanent===!0}var wK;var Hp0=w(()=>{wK=class wK extends Error{permanent=!0;code;constructor($,Z){super(Z);this.name="PermanentRunError",this.code=$}}});import{z as gp}from"zod/v4";import{z as I}from"zod/v4";import{z as K1}from"zod/v4";import{z as WZ}from"zod/v4";import{z as nG}from"zod/v4";import{z as T9}from"zod/v4";import{z as R9}from"zod/v4";import{z as j6}from"zod/v4";import{z as z6}from"zod/v4";import{z as v3}from"zod/v4";import{z as s1}from"zod/v4";import{z as f1}from"zod/v4";import{z as hS}from"zod/v4";import{z as Op0}from"zod/v4";import{z as Bp0}from"zod/v4";import{z as hp}from"zod/v4";import{z as pG}from"zod/v4";import{z as F7}from"zod/v4";import{z as S6}from"zod/v4";import{z as DK}from"zod/v4";import{z as LK}from"zod/v4";import{z as EK}from"zod/v4";import{z as uS}from"zod/v4";function hJ4($){var Z;let X=$==null?void 0:$.anthropic;return(Z=X==null?void 0:X.cacheControl)!=null?Z:X==null?void 0:X.cache_control}async function U34({tools:$,toolChoice:Z,disableParallelToolUse:X,cacheControlValidator:Q,supportsStructuredOutput:Y,supportsStrictTools:G,defaultEagerInputStreaming:J=!1}){var W,K;$=($==null?void 0:$.length)?$:void 0;let H=[],F=new Set,N=Q||new wp0;if($==null)return{tools:void 0,toolChoice:void 0,toolWarnings:H,betas:F};let U=[];for(let B of $)switch(B.type){case"function":{let D=N.getCacheControl(B.providerOptions,{type:"tool definition",canCache:!0}),L=(W=B.providerOptions)==null?void 0:W.anthropic,E=(K=L==null?void 0:L.eagerInputStreaming)!=null?K:J,j=L==null?void 0:L.deferLoading,z=L==null?void 0:L.allowedCallers;if(!G&&B.strict!=null)H.push({type:"unsupported",feature:"strict",details:`Tool '${B.name}' has strict: ${B.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`});if(U.push({name:B.name,description:B.description,input_schema:B.inputSchema,cache_control:D,...E?{eager_input_streaming:!0}:{},...G===!0&&B.strict!=null?{strict:B.strict}:{},...j!=null?{defer_loading:j}:{},...z!=null?{allowed_callers:z}:{},...B.inputExamples!=null?{input_examples:B.inputExamples.map((A)=>A.input)}:{}}),Y===!0)F.add("structured-outputs-2025-11-13");if(B.inputExamples!=null||z!=null)F.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(B.id){case"anthropic.code_execution_20250522":{F.add("code-execution-2025-05-22"),U.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{F.add("code-execution-2025-08-25"),U.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{U.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"computer",type:"computer_20250124",display_width_px:B.args.displayWidthPx,display_height_px:B.args.displayHeightPx,display_number:B.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{F.add("computer-use-2025-11-24"),U.push({name:"computer",type:"computer_20251124",display_width_px:B.args.displayWidthPx,display_height_px:B.args.displayHeightPx,display_number:B.args.displayNumber,enable_zoom:B.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"computer",type:"computer_20241022",display_width_px:B.args.displayWidthPx,display_height_px:B.args.displayHeightPx,display_number:B.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{F.add("computer-use-2025-01-24"),U.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let D=await g$({value:B.args,schema:mJ4});U.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:D.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{F.add("context-management-2025-06-27"),U.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{F.add("web-fetch-2025-09-10");let D=await g$({value:B.args,schema:K34});U.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,citations:D.citations,max_content_tokens:D.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{F.add("code-execution-web-tools-2026-02-09");let D=await g$({value:B.args,schema:Q34});U.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,citations:D.citations,max_content_tokens:D.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let D=await g$({value:B.args,schema:eJ4});U.push({type:"web_search_20250305",name:"web_search",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,user_location:D.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{F.add("code-execution-web-tools-2026-02-09");let D=await g$({value:B.args,schema:tJ4});U.push({type:"web_search_20260209",name:"web_search",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,user_location:D.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{U.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{U.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}case"anthropic.advisor_20260301":{F.add("advisor-tool-2026-03-01");let D=await g$({value:B.args,schema:uJ4});U.push({type:"advisor_20260301",name:"advisor",model:D.model,...D.maxUses!==void 0&&{max_uses:D.maxUses},...D.caching!==void 0&&{caching:D.caching}});break}default:{H.push({type:"unsupported",feature:`provider-defined tool ${B.id}`});break}}break}default:{H.push({type:"unsupported",feature:`tool ${B}`});break}}if(Z==null)return{tools:U,toolChoice:X?{type:"auto",disable_parallel_tool_use:X}:void 0,toolWarnings:H,betas:F};let O=Z.type;switch(O){case"auto":return{tools:U,toolChoice:{type:"auto",disable_parallel_tool_use:X},toolWarnings:H,betas:F};case"required":return{tools:U,toolChoice:{type:"any",disable_parallel_tool_use:X},toolWarnings:H,betas:F};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:H,betas:F};case"tool":return{tools:U,toolChoice:{type:"tool",name:Z.toolName,disable_parallel_tool_use:X},toolWarnings:H,betas:F};default:throw new V4({functionality:`tool choice type: ${O}`})}}function UY$({usage:$,rawUsage:Z}){var X,Q,Y;let G=(X=$.cache_creation_input_tokens)!=null?X:0,J=(Q=$.cache_read_input_tokens)!=null?Q:0,W,K,H=(Y=$.iterations)==null?void 0:Y.some((F)=>F.type==="fallback_message");if($.iterations&&$.iterations.length>0&&!H){let F=$.iterations.filter((N)=>N.type==="compaction"||N.type==="message");if(F.length>0){let N=F.reduce((U,O)=>({input:U.input+O.input_tokens,output:U.output+O.output_tokens}),{input:0,output:0});W=N.input,K=N.output}else W=$.input_tokens,K=$.output_tokens}else W=$.input_tokens,K=$.output_tokens;return{inputTokens:{total:W+G+J,noCache:W,cacheRead:J,cacheWrite:G},outputTokens:{total:K,text:void 0,reasoning:void 0},raw:Z!=null?Z:$}}function I34($){if(typeof $==="string")return new TextDecoder().decode(E9($));if($ instanceof Uint8Array)return new TextDecoder().decode($);if($ instanceof URL)throw new V4({functionality:"URL-based text documents are not supported for citations"});throw new V4({functionality:`unsupported data type for text documents: ${typeof $}`})}function Fp0($){return $ instanceof URL||q34($)}function q34($){return typeof $==="string"&&/^https?:\/\//i.test($)}function Np0($){return $ instanceof URL?$.toString():$}async function OY$($){if(typeof $==="string"){let Z=await vZ({text:$});if(Z.success&&typeof Z.value==="object"&&Z.value!==null)return Z.value;return{errorCode:"unavailable"}}if(typeof $==="object"&&$!==null)return $;return{}}async function M34({prompt:$,sendReasoning:Z,warnings:X,cacheControlValidator:Q,toolNameMapping:Y}){var G,J,W,K,H,F,N,U,O,B,D,L,E,j,z,A,P,M,q,k,C;let l=new Set,f=k34($),x=Q||new wp0,n=void 0,u=[];async function a(B0){var e,o;let P0=await t8({provider:"anthropic",providerOptions:B0,schema:HY$});return(o=(e=P0==null?void 0:P0.citations)==null?void 0:e.enabled)!=null?o:!1}async function O0(B0){let e=await t8({provider:"anthropic",providerOptions:B0,schema:HY$});return{title:e==null?void 0:e.title,context:e==null?void 0:e.context}}for(let B0=0;B0<f.length;B0++){let e=f[B0],o=B0===f.length-1,P0=e.type;switch(P0){case"system":{let Y0=e.messages.map(({content:j0,providerOptions:x0})=>({type:"text",text:j0,cache_control:x.getCacheControl(x0,{type:"system message",canCache:!0})}));if(n==null)n=Y0;else u.push({role:"system",content:Y0}),l.add("mid-conversation-system-2026-04-07");break}case"user":{let Y0=[];for(let j0 of e.messages){let{role:x0,content:V0}=j0;switch(x0){case"user":{for(let u0=0;u0<V0.length;u0++){let Q0=V0[u0],w0=u0===V0.length-1,L0=(G=x.getCacheControl(Q0.providerOptions,{type:"user message part",canCache:!0}))!=null?G:w0?x.getCacheControl(j0.providerOptions,{type:"user message",canCache:!0}):void 0;switch(Q0.type){case"text":{Y0.push({type:"text",text:Q0.text,cache_control:L0});break}case"file":{if(Q0.mediaType.startsWith("image/"))Y0.push({type:"image",source:Fp0(Q0.data)?{type:"url",url:Np0(Q0.data)}:{type:"base64",media_type:Q0.mediaType==="image/*"?"image/jpeg":Q0.mediaType,data:YZ(Q0.data)},cache_control:L0});else if(Q0.mediaType==="application/pdf"){l.add("pdfs-2024-09-25");let I0=await a(Q0.providerOptions),$0=await O0(Q0.providerOptions);Y0.push({type:"document",source:Fp0(Q0.data)?{type:"url",url:Np0(Q0.data)}:{type:"base64",media_type:"application/pdf",data:YZ(Q0.data)},title:(J=$0.title)!=null?J:Q0.filename,...$0.context&&{context:$0.context},...I0&&{citations:{enabled:!0}},cache_control:L0})}else if(Q0.mediaType==="text/plain"){let I0=await a(Q0.providerOptions),$0=await O0(Q0.providerOptions);Y0.push({type:"document",source:Fp0(Q0.data)?{type:"url",url:Np0(Q0.data)}:{type:"text",media_type:"text/plain",data:I34(Q0.data)},title:(W=$0.title)!=null?W:Q0.filename,...$0.context&&{context:$0.context},...I0&&{citations:{enabled:!0}},cache_control:L0})}else throw new V4({functionality:`media type: ${Q0.mediaType}`});break}}}break}case"tool":{for(let u0=0;u0<V0.length;u0++){let Q0=V0[u0];if(Q0.type==="tool-approval-response")continue;let w0=Q0.output,L0="providerOptions"in w0?w0.providerOptions:w0.type==="content"?(K=w0.value.find((R0)=>R0.providerOptions!=null))==null?void 0:K.providerOptions:void 0,I0=u0===V0.length-1,$0=(F=(H=x.getCacheControl(Q0.providerOptions,{type:"tool result part",canCache:!0}))!=null?H:x.getCacheControl(L0,{type:"tool result output",canCache:!0}))!=null?F:I0?x.getCacheControl(j0.providerOptions,{type:"tool result message",canCache:!0}):void 0,X0;switch(w0.type){case"content":X0=w0.value.map((R0)=>{var G0;switch(R0.type){case"text":return{type:"text",text:R0.text};case"image-data":return{type:"image",source:{type:"base64",media_type:R0.mediaType,data:R0.data}};case"image-url":return{type:"image",source:{type:"url",url:R0.url}};case"file-url":return{type:"document",source:{type:"url",url:R0.url}};case"file-data":{if(R0.mediaType==="application/pdf")return l.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:R0.mediaType,data:R0.data}};X.push({type:"other",message:`unsupported tool content part type: ${R0.type} with media type: ${R0.mediaType}`});return}case"custom":{let N0=(G0=R0.providerOptions)==null?void 0:G0.anthropic;if((N0==null?void 0:N0.type)==="tool-reference")return{type:"tool_reference",tool_name:N0.toolName};X.push({type:"other",message:"unsupported custom tool content part"});return}default:{X.push({type:"other",message:`unsupported tool content part type: ${R0.type}`});return}}}).filter(mL);break;case"text":case"error-text":X0=w0.value;break;case"execution-denied":X0=(N=w0.reason)!=null?N:"Tool execution denied.";break;case"json":case"error-json":default:X0=JSON.stringify(w0.value);break}Y0.push({type:"tool_result",tool_use_id:Q0.toolCallId,content:X0,is_error:w0.type==="error-text"||w0.type==="error-json"?!0:void 0,cache_control:$0})}break}default:throw Error(`Unsupported role: ${x0}`)}}u.push({role:"user",content:Y0});break}case"assistant":{let Y0=[],j0=new Set;for(let x0=0;x0<e.messages.length;x0++){let V0=e.messages[x0],u0=x0===e.messages.length-1,{content:Q0}=V0;for(let w0=0;w0<Q0.length;w0++){let L0=Q0[w0],I0=w0===Q0.length-1,$0=(U=x.getCacheControl(L0.providerOptions,{type:"assistant message part",canCache:!0}))!=null?U:I0?x.getCacheControl(V0.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(L0.type){case"text":{let X0=(O=L0.providerOptions)==null?void 0:O.anthropic;if((X0==null?void 0:X0.type)==="compaction")Y0.push({type:"compaction",content:L0.text,cache_control:$0});else Y0.push({type:"text",text:o&&u0&&I0?L0.text.trim():L0.text,cache_control:$0});break}case"reasoning":{if(Z){let X0=await t8({provider:"anthropic",providerOptions:L0.providerOptions,schema:gJ4});if(X0!=null)if(X0.signature!=null)x.getCacheControl(L0.providerOptions,{type:"thinking block",canCache:!1}),Y0.push({type:"thinking",thinking:L0.text,signature:X0.signature});else if(X0.redactedData!=null)x.getCacheControl(L0.providerOptions,{type:"redacted thinking block",canCache:!1}),Y0.push({type:"redacted_thinking",data:X0.redactedData});else X.push({type:"other",message:"unsupported reasoning metadata"});else X.push({type:"other",message:"unsupported reasoning metadata"})}else X.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(L0.providerExecuted){let G0=Y.toProviderToolName(L0.toolName);if(((D=(B=L0.providerOptions)==null?void 0:B.anthropic)==null?void 0:D.type)==="mcp-tool-use"){j0.add(L0.toolCallId);let E1=(E=(L=L0.providerOptions)==null?void 0:L.anthropic)==null?void 0:E.serverName;if(E1==null||typeof E1!=="string"){X.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}Y0.push({type:"mcp_tool_use",id:L0.toolCallId,name:L0.toolName,input:L0.input,server_name:E1,cache_control:$0})}else if(G0==="code_execution"&&L0.input!=null&&typeof L0.input==="object"&&"type"in L0.input&&typeof L0.input.type==="string"&&(L0.input.type==="bash_code_execution"||L0.input.type==="text_editor_code_execution"))Y0.push({type:"server_tool_use",id:L0.toolCallId,name:L0.input.type,input:L0.input,cache_control:$0});else if(G0==="code_execution"&&L0.input!=null&&typeof L0.input==="object"&&"type"in L0.input&&L0.input.type==="programmatic-tool-call"){let{type:E1,...n0}=L0.input;Y0.push({type:"server_tool_use",id:L0.toolCallId,name:"code_execution",input:n0,cache_control:$0})}else if(G0==="code_execution"||G0==="web_fetch"||G0==="web_search")Y0.push({type:"server_tool_use",id:L0.toolCallId,name:G0,input:L0.input,cache_control:$0});else if(G0==="tool_search_tool_regex"||G0==="tool_search_tool_bm25")Y0.push({type:"server_tool_use",id:L0.toolCallId,name:G0,input:L0.input,cache_control:$0});else if(G0==="advisor")Y0.push({type:"server_tool_use",id:L0.toolCallId,name:"advisor",input:{},cache_control:$0});else X.push({type:"other",message:`provider executed tool call for tool ${L0.toolName} is not supported`});break}let X0=(j=L0.providerOptions)==null?void 0:j.anthropic,R0=(X0==null?void 0:X0.caller)?(X0.caller.type==="code_execution_20250825"||X0.caller.type==="code_execution_20260120")&&X0.caller.toolId?{type:X0.caller.type,tool_id:X0.caller.toolId}:X0.caller.type==="direct"?{type:"direct"}:void 0:void 0;Y0.push({type:"tool_use",id:L0.toolCallId,name:L0.toolName,input:L0.input,...R0&&{caller:R0},cache_control:$0});break}case"tool-result":{let X0=Y.toProviderToolName(L0.toolName);if(j0.has(L0.toolCallId)){let R0=L0.output;if(R0.type!=="json"&&R0.type!=="error-json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}Y0.push({type:"mcp_tool_result",tool_use_id:L0.toolCallId,is_error:R0.type==="error-json",content:R0.value,cache_control:$0})}else if(X0==="code_execution"){let R0=L0.output;if(R0.type==="error-text"||R0.type==="error-json"){let G0={};try{if(typeof R0.value==="string")G0=JSON.parse(R0.value);else if(typeof R0.value==="object"&&R0.value!==null)G0=R0.value}catch(N0){}if(G0.type==="code_execution_tool_result_error")Y0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(z=G0.errorCode)!=null?z:"unknown"},cache_control:$0});else Y0.push({type:"bash_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:$0,content:{type:"bash_code_execution_tool_result_error",error_code:(A=G0.errorCode)!=null?A:"unknown"}});break}if(R0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}if(R0.value==null||typeof R0.value!=="object"||!("type"in R0.value)||typeof R0.value.type!=="string"){X.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${L0.toolName}`});break}if(R0.value.type==="code_execution_result"){let G0=await g$({value:R0.value,schema:AY$});Y0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:G0.type,stdout:G0.stdout,stderr:G0.stderr,return_code:G0.return_code,content:(P=G0.content)!=null?P:[]},cache_control:$0})}else if(R0.value.type==="encrypted_code_execution_result"){let G0=await g$({value:R0.value,schema:RY$});if(G0.type==="encrypted_code_execution_result")Y0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:G0.type,encrypted_stdout:G0.encrypted_stdout,stderr:G0.stderr,return_code:G0.return_code,content:(M=G0.content)!=null?M:[]},cache_control:$0})}else{let G0=await g$({value:R0.value,schema:TY$});if(G0.type==="code_execution_result")Y0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:G0.type,stdout:G0.stdout,stderr:G0.stderr,return_code:G0.return_code,content:(q=G0.content)!=null?q:[]},cache_control:$0});else if(G0.type==="bash_code_execution_result"||G0.type==="bash_code_execution_tool_result_error")Y0.push({type:"bash_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:$0,content:G0});else Y0.push({type:"text_editor_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:$0,content:G0})}break}if(X0==="web_fetch"){let R0=L0.output;if(R0.type==="error-json"){Y0.push({type:"web_fetch_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(k=(await OY$(R0.value)).errorCode)!=null?k:"unavailable"},cache_control:$0});break}if(R0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}let G0=await g$({value:R0.value,schema:PY$});Y0.push({type:"web_fetch_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_fetch_result",url:G0.url,retrieved_at:G0.retrievedAt,content:{type:"document",title:G0.content.title,citations:G0.content.citations,source:{type:G0.content.source.type,media_type:G0.content.source.mediaType,data:G0.content.source.data}}},cache_control:$0});break}if(X0==="web_search"){let R0=L0.output;if(R0.type==="error-json"){Y0.push({type:"web_search_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_search_tool_result_error",error_code:(C=(await OY$(R0.value)).errorCode)!=null?C:"unavailable"},cache_control:$0});break}if(R0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}let G0=await g$({value:R0.value,schema:zY$});Y0.push({type:"web_search_tool_result",tool_use_id:L0.toolCallId,content:G0.map((N0)=>({url:N0.url,title:N0.title,page_age:N0.pageAge,encrypted_content:N0.encryptedContent,type:N0.type})),cache_control:$0});break}if(X0==="tool_search_tool_regex"||X0==="tool_search_tool_bm25"){let R0=L0.output;if(R0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}let N0=(await g$({value:R0.value,schema:IY$})).map((E1)=>({type:"tool_reference",tool_name:E1.toolName}));Y0.push({type:"tool_search_tool_result",tool_use_id:L0.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:N0},cache_control:$0});break}if(X0==="advisor"){let R0=L0.output;if(R0.type!=="json"&&R0.type!=="error-json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}let G0=await g$({value:R0.value,schema:jY$});if(G0.type==="advisor_result")Y0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_result",text:G0.text},cache_control:$0});else if(G0.type==="advisor_redacted_result")Y0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:G0.encryptedContent},cache_control:$0});else Y0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_tool_result_error",error_code:G0.errorCode},cache_control:$0});break}X.push({type:"other",message:`provider executed tool result for tool ${L0.toolName} is not supported`});break}}}}u.push({role:"assistant",content:Y0});break}default:throw Error(`content type: ${P0}`)}}return{prompt:{system:n,messages:u},betas:l}}function k34($){let Z=[],X=void 0;for(let Q of $){let{role:Y}=Q;switch(Y){case"system":{if((X==null?void 0:X.type)!=="system")X={type:"system",messages:[]},Z.push(X);X.messages.push(Q);break}case"assistant":{if((X==null?void 0:X.type)!=="assistant")X={type:"assistant",messages:[]},Z.push(X);X.messages.push(Q);break}case"user":{if((X==null?void 0:X.type)!=="user")X={type:"user",messages:[]},Z.push(X);X.messages.push(Q);break}case"tool":{if((X==null?void 0:X.type)!=="user")X={type:"user",messages:[]},Z.push(X);X.messages.push(Q);break}default:throw Error(`Unsupported role: ${Y}`)}}return Z}function Up0({finishReason:$,isJsonResponseFromTool:Z}){switch($){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return Z?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}function S34($){return MY$($)}function UB($){if(typeof $==="boolean"||!f34($))return $;return MY$($)}function MY$($){let Z={},X=$;if($.$ref!=null)return{$ref:$.$ref};if($.$schema!=null)Z.$schema=$.$schema;if($.$id!=null)Z.$id=$.$id;if($.title!=null)Z.title=$.title;if($.description!=null)Z.description=$.description;if($.default!==void 0)Z.default=$.default;if($.const!==void 0)Z.const=$.const;if($.enum!=null)Z.enum=$.enum;if($.type!=null)Z.type=$.type;if($.anyOf!=null)Z.anyOf=$.anyOf.map(UB);else if($.oneOf!=null)Z.anyOf=$.oneOf.map(UB);if($.allOf!=null)Z.allOf=$.allOf.map(UB);if($.definitions!=null)Z.definitions=Object.fromEntries(Object.entries($.definitions).map(([Y,G])=>[Y,UB(G)]));if(X.$defs!=null){let Y=Z;Y.$defs=Object.fromEntries(Object.entries(X.$defs).map(([G,J])=>[G,UB(J)]))}if($.type==="object"||$.properties!=null){if($.properties!=null)Z.properties=Object.fromEntries(Object.entries($.properties).map(([Y,G])=>[Y,UB(G)]));if(Z.additionalProperties=!1,$.required!=null)Z.required=$.required}if($.items!=null)Z.items=Array.isArray($.items)?$.items.map(UB):UB($.items);if(typeof $.format==="string"&&qY$.has($.format))Z.format=$.format;let Q=C34($);if(Q!=null)Z.description=Z.description==null?Q:`${Z.description}
|
|
1050
|
-
${Q}`;return Z}function C34($){let Z=V34.flatMap((X)=>{let Q=$[X];if(Q==null||Q===!1)return[];return`${_34(X)}: ${v34(Q)}`});if(typeof $.format==="string"&&!qY$.has($.format))Z.push(`format: ${$.format}`);return Z.length===0?void 0:`${Z.join("; ")}.`}function _34($){return $.replace(/[A-Z]/g,(Z)=>` ${Z.toLowerCase()}`)}function v34($){if(typeof $==="string")return $;return JSON.stringify($)}function f34($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function BY$($,Z,X){var Q;if($.type==="web_search_result_location")return{type:"source",sourceType:"url",id:X(),url:$.url,title:$.title,providerMetadata:{anthropic:{citedText:$.cited_text,encryptedIndex:$.encrypted_index}}};if($.type!=="page_location"&&$.type!=="char_location")return;let Y=Z[$.document_index];if(!Y)return;return{type:"source",sourceType:"document",id:X(),mediaType:Y.mediaType,title:(Q=$.document_title)!=null?Q:Y.title,filename:Y.filename,providerMetadata:{anthropic:$.type==="page_location"?{citedText:$.cited_text,startPageNumber:$.start_page_number,endPageNumber:$.end_page_number}:{citedText:$.cited_text,startCharIndex:$.start_char_index,endCharIndex:$.end_char_index}}}}function x34($){if($.includes("claude-opus-4-8")||$.includes("claude-opus-4-7")||$.includes("claude-fable-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,isKnownModel:!0};else if($.includes("claude-sonnet-4-6")||$.includes("claude-opus-4-6"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-sonnet-4-5")||$.includes("claude-opus-4-5")||$.includes("claude-haiku-4-5"))return{maxOutputTokens:64000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-opus-4-1"))return{maxOutputTokens:32000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-sonnet-4-"))return{maxOutputTokens:64000,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-opus-4-"))return{maxOutputTokens:32000,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-3-haiku"))return{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else return{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!1}}function wY$($){if(!$)return!1;let Z=!1,X=!1;for(let Q of $){if("type"in Q&&(Q.type==="web_fetch_20260209"||Q.type==="web_search_20260209")){Z=!0;continue}if(Q.name==="code_execution"){X=!0;break}}return Z&&!X}function DY$($){return $?{appliedEdits:$.applied_edits.map((Z)=>{switch(Z.type){case"clear_tool_uses_20250919":return{type:Z.type,clearedToolUses:Z.cleared_tool_uses,clearedInputTokens:Z.cleared_input_tokens};case"clear_thinking_20251015":return{type:Z.type,clearedThinkingTurns:Z.cleared_thinking_turns,clearedInputTokens:Z.cleared_input_tokens};case"compact_20260112":return{type:Z.type}}}).filter((Z)=>Z!==void 0)}:null}function LY$($){if($==null)return;return{type:$.type,...$.category!=null?{category:$.category}:{},...$.explanation!=null?{explanation:$.explanation}:{},...$.recommended_model!=null?{recommendedModel:$.recommended_model}:{}}}function up($={}){var Z,X;let Q=(Z=xO(XK({settingValue:$.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?Z:"https://api.anthropic.com/v1",Y=(X=$.name)!=null?X:"anthropic.messages";if($.apiKey&&$.authToken)throw new vO({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let G=()=>{let K=$.authToken?{Authorization:`Bearer ${$.authToken}`}:{"x-api-key":Mx({apiKey:$.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return p4({"anthropic-version":"2023-06-01",...K,...$.headers},`ai-sdk/anthropic/${fJ4}`)},J=(K)=>{var H;return new b34(K,{provider:Y,baseURL:Q,headers:G,fetch:$.fetch,generateId:(H=$.generateId)!=null?H:f8,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},W=function(K){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return J(K)};return W.specificationVersion="v3",W.languageModel=J,W.chat=J,W.messages=J,W.embeddingModel=(K)=>{throw new y5({modelId:K,modelType:"embeddingModel"})},W.textEmbeddingModel=W.embeddingModel,W.imageModel=(K)=>{throw new y5({modelId:K,modelType:"imageModel"})},W.tools=GW4,W}var fJ4="3.0.85",bJ4,KY$,EY$,xJ4,yJ4,gJ4,HY$,FY$,NY$=4,wp0=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl($,Z){let X=hJ4($);if(!X)return;if(!Z.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${Z.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>NY$){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${NY$} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return X}getWarnings(){return this.warnings}},uJ4,jY$,cJ4,lJ4,dJ4=($)=>{return lJ4($)},mJ4,iJ4,pJ4,nJ4=($={})=>{return pJ4($)},tJ4,oJ4,rJ4,aJ4,sJ4=($={})=>{return aJ4($)},eJ4,zY$,$34,Z34,X34=($={})=>{return Z34($)},Q34,Y34,G34,J34,W34=($={})=>{return J34($)},K34,PY$,H34,F34,N34=($={})=>{return F34($)},AY$,O34,B34,w34=($={})=>{return B34($)},TY$,D34,L34,E34=($={})=>{return L34($)},RY$,j34,z34,P34=($={})=>{return z34($)},IY$,A34,T34,R34=($={})=>{return T34($)},qY$,V34,b34=class{constructor($,Z){this.specificationVersion="v3";var X;this.modelId=$,this.config=Z,this.generateId=(X=Z.generateId)!=null?X:f8}supportsUrl($){return $.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let $=this.config.provider,Z=$.indexOf(".");return Z===-1?$:$.substring(0,Z)}get supportedUrls(){var $,Z,X;return(X=(Z=($=this.config).supportedUrls)==null?void 0:Z.call($))!=null?X:{}}async getArgs({userSuppliedBetas:$,prompt:Z,maxOutputTokens:X,temperature:Q,topP:Y,topK:G,frequencyPenalty:J,presencePenalty:W,stopSequences:K,responseFormat:H,seed:F,tools:N,toolChoice:U,providerOptions:O,stream:B}){var D,L,E,j,z,A,P,M,q,k;let C=[];if(J!=null)C.push({type:"unsupported",feature:"frequencyPenalty"});if(W!=null)C.push({type:"unsupported",feature:"presencePenalty"});if(F!=null)C.push({type:"unsupported",feature:"seed"});if(Q!=null&&Q>1)C.push({type:"unsupported",feature:"temperature",details:`${Q} exceeds anthropic maximum of 1.0. clamped to 1.0`}),Q=1;else if(Q!=null&&Q<0)C.push({type:"unsupported",feature:"temperature",details:`${Q} is below anthropic minimum of 0. clamped to 0`}),Q=0;if((H==null?void 0:H.type)==="json"){if(H.schema==null)C.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."})}let l=this.providerOptionsName,f=await t8({provider:"anthropic",providerOptions:O,schema:FY$}),x=l!=="anthropic"?await t8({provider:l,providerOptions:O,schema:FY$}):null,n=x!=null,u=Object.assign({},f!=null?f:{},x!=null?x:{}),{maxOutputTokens:a,supportsStructuredOutput:O0,rejectsSamplingParameters:B0,isKnownModel:e}=x34(this.modelId);if(B0){if(Q!=null)C.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),Q=void 0;if(G!=null)C.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),G=void 0;if(Y!=null)C.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),Y=void 0}let o=e||this.modelId.startsWith("claude-"),P0=((D=this.config.supportsNativeStructuredOutput)!=null?D:!0)&&O0,Y0=((L=this.config.supportsStrictTools)!=null?L:!0)&&O0,j0=(E=u==null?void 0:u.structuredOutputMode)!=null?E:"auto",x0=j0==="outputFormat"||j0==="auto"&&P0,V0=(H==null?void 0:H.type)==="json"&&H.schema!=null&&!x0?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:H.schema}:void 0,u0=u==null?void 0:u.contextManagement,Q0=new wp0,w0=N90({tools:N,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25","anthropic.advisor_20260301":"advisor"}}),{prompt:L0,betas:I0}=await M34({prompt:Z,sendReasoning:(j=u==null?void 0:u.sendReasoning)!=null?j:!0,warnings:C,cacheControlValidator:Q0,toolNameMapping:w0}),$0=(z=u==null?void 0:u.thinking)==null?void 0:z.type,X0=$0==="enabled"||$0==="adaptive",R0=$0==="enabled"?(A=u==null?void 0:u.thinking)==null?void 0:A.budgetTokens:void 0,G0=$0==="adaptive"?(P=u==null?void 0:u.thinking)==null?void 0:P.display:void 0,N0=X!=null?X:a,E1={model:this.modelId,max_tokens:N0,temperature:Q,top_k:G,top_p:Y,stop_sequences:K,...X0&&{thinking:{type:$0,...R0!=null&&{budget_tokens:R0},...G0!=null&&{display:G0}}},...((u==null?void 0:u.effort)||(u==null?void 0:u.taskBudget)||x0&&(H==null?void 0:H.type)==="json"&&H.schema!=null)&&{output_config:{...(u==null?void 0:u.effort)&&{effort:u.effort},...(u==null?void 0:u.taskBudget)&&{task_budget:{type:u.taskBudget.type,total:u.taskBudget.total,...u.taskBudget.remaining!=null&&{remaining:u.taskBudget.remaining}}},...x0&&(H==null?void 0:H.type)==="json"&&H.schema!=null&&{format:{type:"json_schema",schema:S34(H.schema)}}}},...(u==null?void 0:u.speed)&&{speed:u.speed},...(u==null?void 0:u.inferenceGeo)&&{inference_geo:u.inferenceGeo},...(u==null?void 0:u.fallbacks)&&u.fallbacks.length>0&&{fallbacks:u.fallbacks},...(u==null?void 0:u.cacheControl)&&{cache_control:u.cacheControl},...((M=u==null?void 0:u.metadata)==null?void 0:M.userId)!=null&&{metadata:{user_id:u.metadata.userId}},...(u==null?void 0:u.mcpServers)&&u.mcpServers.length>0&&{mcp_servers:u.mcpServers.map((k0)=>({type:k0.type,name:k0.name,url:k0.url,authorization_token:k0.authorizationToken,tool_configuration:k0.toolConfiguration?{allowed_tools:k0.toolConfiguration.allowedTools,enabled:k0.toolConfiguration.enabled}:void 0}))},...(u==null?void 0:u.container)&&{container:u.container.skills&&u.container.skills.length>0?{id:u.container.id,skills:u.container.skills.map((k0)=>({type:k0.type,skill_id:k0.skillId,version:k0.version}))}:u.container.id},system:L0.system,messages:L0.messages,...u0&&{context_management:{edits:u0.edits.map((k0)=>{let g1=k0.type;switch(g1){case"clear_tool_uses_20250919":return{type:k0.type,...k0.trigger!==void 0&&{trigger:k0.trigger},...k0.keep!==void 0&&{keep:k0.keep},...k0.clearAtLeast!==void 0&&{clear_at_least:k0.clearAtLeast},...k0.clearToolInputs!==void 0&&{clear_tool_inputs:k0.clearToolInputs},...k0.excludeTools!==void 0&&{exclude_tools:k0.excludeTools}};case"clear_thinking_20251015":return{type:k0.type,...k0.keep!==void 0&&{keep:k0.keep}};case"compact_20260112":return{type:k0.type,...k0.trigger!==void 0&&{trigger:k0.trigger},...k0.pauseAfterCompaction!==void 0&&{pause_after_compaction:k0.pauseAfterCompaction},...k0.instructions!==void 0&&{instructions:k0.instructions}};default:C.push({type:"other",message:`Unknown context management strategy: ${g1}`});return}}).filter((k0)=>k0!==void 0)}}};if(X0){if($0==="enabled"&&R0==null)C.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),E1.thinking={type:"enabled",budget_tokens:1024},R0=1024;if(E1.temperature!=null)E1.temperature=void 0,C.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(G!=null)E1.top_k=void 0,C.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(Y!=null)E1.top_p=void 0,C.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});E1.max_tokens=N0+(R0!=null?R0:0)}else if(o&&Y!=null&&Q!=null)C.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),E1.top_p=void 0;if(e&&E1.max_tokens>a){if(X!=null)C.push({type:"unsupported",feature:"maxOutputTokens",details:`${E1.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${a} max output tokens. The max output tokens have been limited to ${a}.`});E1.max_tokens=a}if((u==null?void 0:u.mcpServers)&&u.mcpServers.length>0)I0.add("mcp-client-2025-04-04");if(u0){if(I0.add("context-management-2025-06-27"),u0.edits.some((k0)=>k0.type==="compact_20260112"))I0.add("compact-2026-01-12")}if((u==null?void 0:u.container)&&u.container.skills&&u.container.skills.length>0){if(I0.add("code-execution-2025-08-25"),I0.add("skills-2025-10-02"),I0.add("files-api-2025-04-14"),!(N==null?void 0:N.some((k0)=>k0.type==="provider"&&(k0.id==="anthropic.code_execution_20250825"||k0.id==="anthropic.code_execution_20260120"))))C.push({type:"other",message:"code execution tool is required when using skills"})}if(u==null?void 0:u.taskBudget)I0.add("task-budgets-2026-03-13");if((u==null?void 0:u.speed)==="fast")I0.add("fast-mode-2026-02-01");if((u==null?void 0:u.fallbacks)&&u.fallbacks.length>0)I0.add("server-side-fallback-2026-06-01");let n0=B&&((q=u==null?void 0:u.toolStreaming)!=null?q:!0),{tools:y0,toolChoice:i,toolWarnings:S0,betas:X1}=await U34(V0!=null?{tools:[...N!=null?N:[],V0],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:Q0,supportsStructuredOutput:!1,supportsStrictTools:Y0,defaultEagerInputStreaming:n0}:{tools:N!=null?N:[],toolChoice:U,disableParallelToolUse:u==null?void 0:u.disableParallelToolUse,cacheControlValidator:Q0,supportsStructuredOutput:P0,supportsStrictTools:Y0,defaultEagerInputStreaming:n0}),A1=Q0.getWarnings();return{args:{...E1,tools:y0,tool_choice:i,stream:B===!0?!0:void 0},warnings:[...C,...S0,...A1],betas:new Set([...I0,...X1,...$,...(k=u==null?void 0:u.anthropicBeta)!=null?k:[]]),usesJsonResponseTool:V0!=null,toolNameMapping:w0,providerOptionsName:l,usedCustomProviderKey:n}}async getHeaders({betas:$,headers:Z}){return t$(await v$(this.config.headers),Z,$.size>0?{"anthropic-beta":Array.from($).join(",")}:{})}async getBetasFromHeaders($){var Z,X;let Y=(Z=(await v$(this.config.headers))["anthropic-beta"])!=null?Z:"",G=(X=$==null?void 0:$["anthropic-beta"])!=null?X:"";return new Set([...Y.toLowerCase().split(","),...G.toLowerCase().split(",")].map((J)=>J.trim()).filter((J)=>J!==""))}buildRequestUrl($){var Z,X,Q;return(Q=(X=(Z=this.config).buildRequestUrl)==null?void 0:X.call(Z,this.config.baseURL,$))!=null?Q:`${this.config.baseURL}/messages`}transformRequestBody($,Z){var X,Q,Y;return(Y=(Q=(X=this.config).transformRequestBody)==null?void 0:Q.call(X,$,Z))!=null?Y:$}extractCitationDocuments($){let Z=(X)=>{var Q,Y;if(X.type!=="file")return!1;if(X.mediaType!=="application/pdf"&&X.mediaType!=="text/plain")return!1;let G=(Q=X.providerOptions)==null?void 0:Q.anthropic,J=G==null?void 0:G.citations;return(Y=J==null?void 0:J.enabled)!=null?Y:!1};return $.filter((X)=>X.role==="user").flatMap((X)=>X.content).filter(Z).map((X)=>{var Q;let Y=X;return{title:(Q=Y.filename)!=null?Q:"Untitled Document",filename:Y.filename,mediaType:Y.mediaType}})}async doGenerate($){var Z,X,Q,Y,G,J,W;let{args:K,warnings:H,betas:F,usesJsonResponseTool:N,toolNameMapping:U,providerOptionsName:O,usedCustomProviderKey:B}=await this.getArgs({...$,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders($.headers)}),D=[...this.extractCitationDocuments($.prompt)],L=wY$(K.tools),{responseHeaders:E,value:j,rawValue:z}=await K8({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:F,headers:$.headers}),body:this.transformRequestBody(K,F),failedResponseHandler:KY$,successfulResponseHandler:e$(xJ4),abortSignal:$.abortSignal,fetch:this.config.fetch}),A=[],P={},M={},q=!1;for(let k of j.content)switch(k.type){case"text":{if(!N){if(A.push({type:"text",text:k.text}),k.citations)for(let C of k.citations){let l=BY$(C,D,this.generateId);if(l)A.push(l)}}break}case"thinking":{A.push({type:"reasoning",text:k.thinking,providerMetadata:{anthropic:{signature:k.signature}}});break}case"redacted_thinking":{A.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:k.data}}});break}case"compaction":{A.push({type:"text",text:k.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(N&&k.name==="json")q=!0,A.push({type:"text",text:JSON.stringify(k.input)});else{let l=k.caller,f=l?{type:l.type,toolId:"tool_id"in l?l.tool_id:void 0}:void 0;A.push({type:"tool-call",toolCallId:k.id,toolName:k.name,input:JSON.stringify(k.input),...f&&{providerMetadata:{anthropic:{caller:f}}}})}break}case"server_tool_use":{if(k.name==="text_editor_code_execution"||k.name==="bash_code_execution")A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName("code_execution"),input:JSON.stringify({type:k.name,...k.input}),providerExecuted:!0,...L?{dynamic:!0}:{}});else if(k.name==="web_search"||k.name==="code_execution"||k.name==="web_fetch"){let C=k.name==="code_execution"&&k.input!=null&&typeof k.input==="object"&&"code"in k.input&&!("type"in k.input)?{type:"programmatic-tool-call",...k.input}:k.input;A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName(k.name),input:JSON.stringify(C),providerExecuted:!0,...L&&k.name==="code_execution"?{dynamic:!0}:{}})}else if(k.name==="tool_search_tool_regex"||k.name==="tool_search_tool_bm25")M[k.id]=k.name,A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName(k.name),input:JSON.stringify(k.input),providerExecuted:!0});else if(k.name==="advisor")A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName("advisor"),input:JSON.stringify(k.input),providerExecuted:!0});break}case"mcp_tool_use":{P[k.id]={type:"tool-call",toolCallId:k.id,toolName:k.name,input:JSON.stringify(k.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:k.server_name}}},A.push(P[k.id]);break}case"mcp_tool_result":{A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:P[k.tool_use_id].toolName,isError:k.is_error,result:k.content,dynamic:!0,providerMetadata:P[k.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{if(k.content.type==="web_fetch_result")D.push({title:(Z=k.content.content.title)!=null?Z:k.content.url,mediaType:k.content.content.source.media_type}),A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:k.content.url,retrievedAt:k.content.retrieved_at,content:{type:k.content.content.type,title:k.content.content.title,citations:k.content.content.citations,source:{type:k.content.content.source.type,mediaType:k.content.content.source.media_type,data:k.content.content.source.data}}}});else if(k.content.type==="web_fetch_tool_result_error")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:k.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(k.content)){A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_search"),result:k.content.map((C)=>{var l;return{url:C.url,title:C.title,pageAge:(l=C.page_age)!=null?l:null,encryptedContent:C.encrypted_content,type:C.type}})});for(let C of k.content)A.push({type:"source",sourceType:"url",id:this.generateId(),url:C.url,title:C.title,providerMetadata:{anthropic:{pageAge:(X=C.page_age)!=null?X:null}}})}else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:k.content.error_code}});break}case"code_execution_tool_result":{if(k.content.type==="code_execution_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:{type:k.content.type,stdout:k.content.stdout,stderr:k.content.stderr,return_code:k.content.return_code,content:(Q=k.content.content)!=null?Q:[]}});else if(k.content.type==="encrypted_code_execution_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:{type:k.content.type,encrypted_stdout:k.content.encrypted_stdout,stderr:k.content.stderr,return_code:k.content.return_code,content:(Y=k.content.content)!=null?Y:[]}});else if(k.content.type==="code_execution_tool_result_error")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:k.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:k.content});break}case"tool_search_tool_result":{let C=M[k.tool_use_id];if(C==null){let l=U.toCustomToolName("tool_search_tool_bm25"),f=U.toCustomToolName("tool_search_tool_regex");if(l!=="tool_search_tool_bm25")C="tool_search_tool_bm25";else if(f!=="tool_search_tool_regex")C="tool_search_tool_regex";else C="tool_search_tool_regex"}if(k.content.type==="tool_search_tool_search_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName(C),result:k.content.tool_references.map((l)=>({type:l.type,toolName:l.tool_name}))});else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName(C),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:k.content.error_code}});break}case"advisor_tool_result":{let C=U.toCustomToolName("advisor");if(k.content.type==="advisor_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:C,result:{type:"advisor_result",text:k.content.text}});else if(k.content.type==="advisor_redacted_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:C,result:{type:"advisor_redacted_result",encryptedContent:k.content.encrypted_content}});else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:C,isError:!0,result:{type:"advisor_tool_result_error",errorCode:k.content.error_code}});break}case"fallback":break}return{content:A,finishReason:{unified:Up0({finishReason:j.stop_reason,isJsonResponseFromTool:q}),raw:(G=j.stop_reason)!=null?G:void 0},usage:UY$({usage:j.usage}),request:{body:K},response:{id:(J=j.id)!=null?J:void 0,modelId:(W=j.model)!=null?W:void 0,headers:E,body:z},warnings:H,providerMetadata:(()=>{var k,C,l,f,x;let n=LY$(j.stop_details),u={usage:j.usage,cacheCreationInputTokens:(k=j.usage.cache_creation_input_tokens)!=null?k:null,stopSequence:(C=j.stop_sequence)!=null?C:null,...n!=null?{stopDetails:n}:{},iterations:j.usage.iterations?j.usage.iterations.map((O0)=>({type:O0.type,...O0.model!=null?{model:O0.model}:{},inputTokens:O0.input_tokens,outputTokens:O0.output_tokens,...O0.cache_creation_input_tokens?{cacheCreationInputTokens:O0.cache_creation_input_tokens}:{},...O0.cache_read_input_tokens?{cacheReadInputTokens:O0.cache_read_input_tokens}:{}})):null,container:j.container?{expiresAt:j.container.expires_at,id:j.container.id,skills:(f=(l=j.container.skills)==null?void 0:l.map((O0)=>({type:O0.type,skillId:O0.skill_id,version:O0.version})))!=null?f:null}:null,contextManagement:(x=DY$(j.context_management))!=null?x:null},a={anthropic:u};if(B&&O!=="anthropic")a[O]=u;return a})()}}async doStream($){var Z,X;let{args:Q,warnings:Y,betas:G,usesJsonResponseTool:J,toolNameMapping:W,providerOptionsName:K,usedCustomProviderKey:H}=await this.getArgs({...$,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders($.headers)}),F=[...this.extractCitationDocuments($.prompt)],N=wY$(Q.tools),U=this.buildRequestUrl(!0),{responseHeaders:O,value:B}=await K8({url:U,headers:await this.getHeaders({betas:G,headers:$.headers}),body:this.transformRequestBody(Q,G),failedResponseHandler:KY$,successfulResponseHandler:t7(yJ4),abortSignal:$.abortSignal,fetch:this.config.fetch}),D={unified:"other",raw:void 0},L={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},E={},j={},z={},A=null,P=void 0,M=null,q=null,k=void 0,C=null,l=!1,f=void 0,x=this.generateId,n=B.pipeThrough(new TransformStream({start(B0){B0.enqueue({type:"stream-start",warnings:Y})},transform(B0,e){var o,P0,Y0,j0,x0,V0,u0,Q0,w0,L0,I0,$0,X0,R0;if($.includeRawChunks)e.enqueue({type:"raw",rawValue:B0.rawValue});if(!B0.success){e.enqueue({type:"error",error:B0.error});return}let G0=B0.value;switch(G0.type){case"ping":return;case"content_block_start":{let N0=G0.content_block,E1=N0.type;if(E1==="fallback")return;switch(f=E1,E1){case"text":{if(J)return;E[G0.index]={type:"text"},e.enqueue({type:"text-start",id:String(G0.index)});return}case"thinking":{E[G0.index]={type:"reasoning"},e.enqueue({type:"reasoning-start",id:String(G0.index)});return}case"redacted_thinking":{E[G0.index]={type:"reasoning"},e.enqueue({type:"reasoning-start",id:String(G0.index),providerMetadata:{anthropic:{redactedData:N0.data}}});return}case"compaction":{E[G0.index]={type:"text"},e.enqueue({type:"text-start",id:String(G0.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(J&&N0.name==="json")l=!0,E[G0.index]={type:"text"},e.enqueue({type:"text-start",id:String(G0.index)});else{let y0=N0.caller,i=y0?{type:y0.type,toolId:"tool_id"in y0?y0.tool_id:void 0}:void 0,X1=N0.input&&Object.keys(N0.input).length>0?JSON.stringify(N0.input):"";E[G0.index]={type:"tool-call",toolCallId:N0.id,toolName:N0.name,input:X1,firstDelta:X1.length===0,...i&&{caller:i}},e.enqueue({type:"tool-input-start",id:N0.id,toolName:N0.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(N0.name)){let n0=N0.name==="text_editor_code_execution"||N0.name==="bash_code_execution"?"code_execution":N0.name,y0=W.toCustomToolName(n0),i=N0.input!=null&&typeof N0.input==="object"&&Object.keys(N0.input).length>0?JSON.stringify(N0.input):"";E[G0.index]={type:"tool-call",toolCallId:N0.id,toolName:y0,input:i,providerExecuted:!0,...N&&n0==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:n0},e.enqueue({type:"tool-input-start",id:N0.id,toolName:y0,providerExecuted:!0,...N&&n0==="code_execution"?{dynamic:!0}:{}})}else if(N0.name==="tool_search_tool_regex"||N0.name==="tool_search_tool_bm25"){z[N0.id]=N0.name;let n0=W.toCustomToolName(N0.name);E[G0.index]={type:"tool-call",toolCallId:N0.id,toolName:n0,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:N0.name},e.enqueue({type:"tool-input-start",id:N0.id,toolName:n0,providerExecuted:!0})}else if(N0.name==="advisor"){let n0=W.toCustomToolName("advisor");E[G0.index]={type:"tool-call",toolCallId:N0.id,toolName:n0,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:N0.name},e.enqueue({type:"tool-input-start",id:N0.id,toolName:n0,providerExecuted:!0})}return}case"web_fetch_tool_result":{if(N0.content.type==="web_fetch_result")F.push({title:(o=N0.content.content.title)!=null?o:N0.content.url,mediaType:N0.content.content.source.media_type}),e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:N0.content.url,retrievedAt:N0.content.retrieved_at,content:{type:N0.content.content.type,title:N0.content.content.title,citations:N0.content.content.citations,source:{type:N0.content.content.source.type,mediaType:N0.content.content.source.media_type,data:N0.content.content.source.data}}}});else if(N0.content.type==="web_fetch_tool_result_error")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:N0.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(N0.content)){e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("web_search"),result:N0.content.map((n0)=>{var y0;return{url:n0.url,title:n0.title,pageAge:(y0=n0.page_age)!=null?y0:null,encryptedContent:n0.encrypted_content,type:n0.type}})});for(let n0 of N0.content)e.enqueue({type:"source",sourceType:"url",id:x(),url:n0.url,title:n0.title,providerMetadata:{anthropic:{pageAge:(P0=n0.page_age)!=null?P0:null}}})}else e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:N0.content.error_code}});return}case"code_execution_tool_result":{if(N0.content.type==="code_execution_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("code_execution"),result:{type:N0.content.type,stdout:N0.content.stdout,stderr:N0.content.stderr,return_code:N0.content.return_code,content:(Y0=N0.content.content)!=null?Y0:[]}});else if(N0.content.type==="encrypted_code_execution_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("code_execution"),result:{type:N0.content.type,encrypted_stdout:N0.content.encrypted_stdout,stderr:N0.content.stderr,return_code:N0.content.return_code,content:(j0=N0.content.content)!=null?j0:[]}});else if(N0.content.type==="code_execution_tool_result_error")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:N0.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("code_execution"),result:N0.content});return}case"tool_search_tool_result":{let n0=z[N0.tool_use_id];if(n0==null){let y0=W.toCustomToolName("tool_search_tool_bm25"),i=W.toCustomToolName("tool_search_tool_regex");if(y0!=="tool_search_tool_bm25")n0="tool_search_tool_bm25";else if(i!=="tool_search_tool_regex")n0="tool_search_tool_regex";else n0="tool_search_tool_regex"}if(N0.content.type==="tool_search_tool_search_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName(n0),result:N0.content.tool_references.map((y0)=>({type:y0.type,toolName:y0.tool_name}))});else e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName(n0),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:N0.content.error_code}});return}case"advisor_tool_result":{let n0=W.toCustomToolName("advisor");if(N0.content.type==="advisor_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:n0,result:{type:"advisor_result",text:N0.content.text}});else if(N0.content.type==="advisor_redacted_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:n0,result:{type:"advisor_redacted_result",encryptedContent:N0.content.encrypted_content}});else e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:n0,isError:!0,result:{type:"advisor_tool_result_error",errorCode:N0.content.error_code}});return}case"mcp_tool_use":{j[N0.id]={type:"tool-call",toolCallId:N0.id,toolName:N0.name,input:JSON.stringify(N0.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:N0.server_name}}},e.enqueue(j[N0.id]);return}case"mcp_tool_result":{e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:j[N0.tool_use_id].toolName,isError:N0.is_error,result:N0.content,dynamic:!0,providerMetadata:j[N0.tool_use_id].providerMetadata});return}default:throw Error(`Unsupported content block type: ${E1}`)}}case"content_block_stop":{if(E[G0.index]!=null){let N0=E[G0.index];switch(N0.type){case"text":{e.enqueue({type:"text-end",id:String(G0.index)});break}case"reasoning":{e.enqueue({type:"reasoning-end",id:String(G0.index)});break}case"tool-call":if(!(J&&N0.toolName==="json")){e.enqueue({type:"tool-input-end",id:N0.toolCallId});let n0=N0.input===""?"{}":N0.input;if(N0.providerToolName==="code_execution")try{let y0=JSON.parse(n0);if(y0!=null&&typeof y0==="object"&&"code"in y0&&!("type"in y0))n0=JSON.stringify({type:"programmatic-tool-call",...y0})}catch(y0){}e.enqueue({type:"tool-call",toolCallId:N0.toolCallId,toolName:N0.toolName,input:n0,providerExecuted:N0.providerExecuted,...N&&N0.providerToolName==="code_execution"?{dynamic:!0}:{},...N0.caller&&{providerMetadata:{anthropic:{caller:N0.caller}}}})}break}delete E[G0.index]}f=void 0;return}case"content_block_delta":{let N0=G0.delta.type;switch(N0){case"text_delta":{if(J)return;e.enqueue({type:"text-delta",id:String(G0.index),delta:G0.delta.text});return}case"thinking_delta":{e.enqueue({type:"reasoning-delta",id:String(G0.index),delta:G0.delta.thinking});return}case"signature_delta":{if(f==="thinking")e.enqueue({type:"reasoning-delta",id:String(G0.index),delta:"",providerMetadata:{anthropic:{signature:G0.delta.signature}}});return}case"compaction_delta":{if(G0.delta.content!=null)e.enqueue({type:"text-delta",id:String(G0.index),delta:G0.delta.content});return}case"input_json_delta":{let E1=E[G0.index],n0=G0.delta.partial_json;if(n0.length===0)return;if(l){if((E1==null?void 0:E1.type)!=="text")return;e.enqueue({type:"text-delta",id:String(G0.index),delta:n0})}else{if((E1==null?void 0:E1.type)!=="tool-call")return;if(E1.firstDelta&&E1.providerToolName==="code_execution")n0=`{"type": "programmatic-tool-call",${n0.substring(1)}`;e.enqueue({type:"tool-input-delta",id:E1.toolCallId,delta:n0}),E1.input+=n0,E1.firstDelta=!1}return}case"citations_delta":{let E1=G0.delta.citation,n0=BY$(E1,F,x);if(n0)e.enqueue(n0);return}default:throw Error(`Unsupported delta type: ${N0}`)}}case"message_start":{if(L.input_tokens=G0.message.usage.input_tokens,L.cache_read_input_tokens=(x0=G0.message.usage.cache_read_input_tokens)!=null?x0:0,L.cache_creation_input_tokens=(V0=G0.message.usage.cache_creation_input_tokens)!=null?V0:0,P={...G0.message.usage},M=(u0=G0.message.usage.cache_creation_input_tokens)!=null?u0:null,G0.message.container!=null)C={expiresAt:G0.message.container.expires_at,id:G0.message.container.id,skills:null};if(G0.message.stop_reason!=null)D={unified:Up0({finishReason:G0.message.stop_reason,isJsonResponseFromTool:l}),raw:G0.message.stop_reason};if(e.enqueue({type:"response-metadata",id:(Q0=G0.message.id)!=null?Q0:void 0,modelId:(w0=G0.message.model)!=null?w0:void 0}),G0.message.content!=null)for(let N0=0;N0<G0.message.content.length;N0++){let E1=G0.message.content[N0];if(E1.type==="tool_use"){let n0=E1.caller,y0=n0?{type:n0.type,toolId:"tool_id"in n0?n0.tool_id:void 0}:void 0;e.enqueue({type:"tool-input-start",id:E1.id,toolName:E1.name});let i=JSON.stringify((L0=E1.input)!=null?L0:{});e.enqueue({type:"tool-input-delta",id:E1.id,delta:i}),e.enqueue({type:"tool-input-end",id:E1.id}),e.enqueue({type:"tool-call",toolCallId:E1.id,toolName:E1.name,input:i,...y0&&{providerMetadata:{anthropic:{caller:y0}}}})}}return}case"message_delta":{if(G0.usage.input_tokens!=null&&L.input_tokens!==G0.usage.input_tokens)L.input_tokens=G0.usage.input_tokens;if(L.output_tokens=G0.usage.output_tokens,G0.usage.cache_read_input_tokens!=null)L.cache_read_input_tokens=G0.usage.cache_read_input_tokens;if(G0.usage.cache_creation_input_tokens!=null)L.cache_creation_input_tokens=G0.usage.cache_creation_input_tokens,M=G0.usage.cache_creation_input_tokens;if(G0.usage.iterations!=null)L.iterations=G0.usage.iterations;if(D={unified:Up0({finishReason:G0.delta.stop_reason,isJsonResponseFromTool:l}),raw:(I0=G0.delta.stop_reason)!=null?I0:void 0},q=($0=G0.delta.stop_sequence)!=null?$0:null,k=LY$(G0.delta.stop_details),C=G0.delta.container!=null?{expiresAt:G0.delta.container.expires_at,id:G0.delta.container.id,skills:(R0=(X0=G0.delta.container.skills)==null?void 0:X0.map((N0)=>({type:N0.type,skillId:N0.skill_id,version:N0.version})))!=null?R0:null}:null,G0.context_management)A=DY$(G0.context_management);P={...P,...G0.usage};return}case"message_stop":{let N0={usage:P!=null?P:null,cacheCreationInputTokens:M,stopSequence:q,...k!=null?{stopDetails:k}:{},iterations:L.iterations?L.iterations.map((n0)=>({type:n0.type,...n0.model!=null?{model:n0.model}:{},inputTokens:n0.input_tokens,outputTokens:n0.output_tokens,...n0.cache_creation_input_tokens?{cacheCreationInputTokens:n0.cache_creation_input_tokens}:{},...n0.cache_read_input_tokens?{cacheReadInputTokens:n0.cache_read_input_tokens}:{}})):null,container:C,contextManagement:A},E1={anthropic:N0};if(H&&K!=="anthropic")E1[K]=N0;e.enqueue({type:"finish",finishReason:D,usage:UY$({usage:L,rawUsage:P}),providerMetadata:E1});return}case"error":{e.enqueue({type:"error",error:G0.error});return}default:throw Error(`Unsupported chunk type: ${G0}`)}}})),[u,a]=n.tee(),O0=u.getReader();try{await O0.read();let B0=await O0.read();if(((Z=B0.value)==null?void 0:Z.type)==="raw")B0=await O0.read();if(((X=B0.value)==null?void 0:X.type)==="error"){let e=B0.value.error;throw new Z4({message:e.message,url:U,requestBodyValues:Q,statusCode:e.type==="overloaded_error"?529:500,responseHeaders:O,responseBody:JSON.stringify(e),isRetryable:e.type==="overloaded_error"})}}finally{O0.cancel().catch(()=>{}),O0.releaseLock()}return{stream:a,request:{body:Q},response:{headers:O}}}},y34,g34,h34,u34,c34,l34,d34,m34,i34,p34,n34,t34,o34,r34,a34,s34,e34,$W4,ZW4,XW4,QW4,YW4=($={})=>{return QW4($)},GW4,TE9;var Dp0=w(()=>{r1();g0();r1();g0();g0();g0();r1();g0();g0();g0();g0();g0();g0();g0();r1();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();bJ4=U0(()=>Z0(gp.object({type:gp.literal("error"),error:gp.object({type:gp.string(),message:gp.string()})}))),KY$=q5({errorSchema:bJ4,errorToMessage:($)=>$.error.message}),EY$=I.object({type:I.string(),category:I.string().nullish(),explanation:I.string().nullish(),recommended_model:I.string().nullish()}),xJ4=U0(()=>Z0(I.object({type:I.literal("message"),id:I.string().nullish(),model:I.string().nullish(),content:I.array(I.discriminatedUnion("type",[I.object({type:I.literal("text"),text:I.string(),citations:I.array(I.discriminatedUnion("type",[I.object({type:I.literal("web_search_result_location"),cited_text:I.string(),url:I.string(),title:I.string(),encrypted_index:I.string()}),I.object({type:I.literal("page_location"),cited_text:I.string(),document_index:I.number(),document_title:I.string().nullable(),start_page_number:I.number(),end_page_number:I.number()}),I.object({type:I.literal("char_location"),cited_text:I.string(),document_index:I.number(),document_title:I.string().nullable(),start_char_index:I.number(),end_char_index:I.number()})])).optional()}),I.object({type:I.literal("thinking"),thinking:I.string(),signature:I.string()}),I.object({type:I.literal("redacted_thinking"),data:I.string()}),I.object({type:I.literal("compaction"),content:I.string()}),I.object({type:I.literal("tool_use"),id:I.string(),name:I.string(),input:I.unknown(),caller:I.union([I.object({type:I.literal("code_execution_20250825"),tool_id:I.string()}),I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()}),I.object({type:I.literal("server_tool_use"),id:I.string(),name:I.string(),input:I.record(I.string(),I.unknown()).nullish(),caller:I.union([I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()}),I.object({type:I.literal("mcp_tool_use"),id:I.string(),name:I.string(),input:I.unknown(),server_name:I.string()}),I.object({type:I.literal("mcp_tool_result"),tool_use_id:I.string(),is_error:I.boolean(),content:I.array(I.union([I.string(),I.object({type:I.literal("text"),text:I.string()})]))}),I.object({type:I.literal("web_fetch_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("web_fetch_result"),url:I.string(),retrieved_at:I.string(),content:I.object({type:I.literal("document"),title:I.string().nullable(),citations:I.object({enabled:I.boolean()}).optional(),source:I.union([I.object({type:I.literal("base64"),media_type:I.literal("application/pdf"),data:I.string()}),I.object({type:I.literal("text"),media_type:I.literal("text/plain"),data:I.string()})])})}),I.object({type:I.literal("web_fetch_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("web_search_tool_result"),tool_use_id:I.string(),content:I.union([I.array(I.object({type:I.literal("web_search_result"),url:I.string(),title:I.string(),encrypted_content:I.string(),page_age:I.string().nullish()})),I.object({type:I.literal("web_search_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("code_execution_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("code_execution_result"),stdout:I.string(),stderr:I.string(),return_code:I.number(),content:I.array(I.object({type:I.literal("code_execution_output"),file_id:I.string()})).optional().default([])}),I.object({type:I.literal("encrypted_code_execution_result"),encrypted_stdout:I.string(),stderr:I.string(),return_code:I.number(),content:I.array(I.object({type:I.literal("code_execution_output"),file_id:I.string()})).optional().default([])}),I.object({type:I.literal("code_execution_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("bash_code_execution_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("bash_code_execution_result"),content:I.array(I.object({type:I.literal("bash_code_execution_output"),file_id:I.string()})),stdout:I.string(),stderr:I.string(),return_code:I.number()}),I.object({type:I.literal("bash_code_execution_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("text_editor_code_execution_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("text_editor_code_execution_tool_result_error"),error_code:I.string()}),I.object({type:I.literal("text_editor_code_execution_view_result"),content:I.string(),file_type:I.string(),num_lines:I.number().nullable(),start_line:I.number().nullable(),total_lines:I.number().nullable()}),I.object({type:I.literal("text_editor_code_execution_create_result"),is_file_update:I.boolean()}),I.object({type:I.literal("text_editor_code_execution_str_replace_result"),lines:I.array(I.string()).nullable(),new_lines:I.number().nullable(),new_start:I.number().nullable(),old_lines:I.number().nullable(),old_start:I.number().nullable()})])}),I.object({type:I.literal("tool_search_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("tool_search_tool_search_result"),tool_references:I.array(I.object({type:I.literal("tool_reference"),tool_name:I.string()}))}),I.object({type:I.literal("tool_search_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("advisor_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("advisor_result"),text:I.string()}),I.object({type:I.literal("advisor_redacted_result"),encrypted_content:I.string()}),I.object({type:I.literal("advisor_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("fallback")})])),stop_reason:I.string().nullish(),stop_sequence:I.string().nullish(),stop_details:EY$.nullish(),usage:I.looseObject({input_tokens:I.number(),output_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish(),iterations:I.array(I.object({type:I.union([I.literal("compaction"),I.literal("message"),I.literal("advisor_message"),I.literal("fallback_message")]),model:I.string().nullish(),input_tokens:I.number(),output_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish()})).nullish()}),container:I.object({expires_at:I.string(),id:I.string(),skills:I.array(I.object({type:I.union([I.literal("anthropic"),I.literal("custom")]),skill_id:I.string(),version:I.string()})).nullish()}).nullish(),context_management:I.object({applied_edits:I.array(I.union([I.object({type:I.literal("clear_tool_uses_20250919"),cleared_tool_uses:I.number(),cleared_input_tokens:I.number()}),I.object({type:I.literal("clear_thinking_20251015"),cleared_thinking_turns:I.number(),cleared_input_tokens:I.number()}),I.object({type:I.literal("compact_20260112")})]))}).nullish()}))),yJ4=U0(()=>Z0(I.discriminatedUnion("type",[I.object({type:I.literal("message_start"),message:I.object({id:I.string().nullish(),model:I.string().nullish(),role:I.string().nullish(),usage:I.looseObject({input_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish()}),content:I.array(I.discriminatedUnion("type",[I.object({type:I.literal("tool_use"),id:I.string(),name:I.string(),input:I.unknown(),caller:I.union([I.object({type:I.literal("code_execution_20250825"),tool_id:I.string()}),I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()})])).nullish(),stop_reason:I.string().nullish(),container:I.object({expires_at:I.string(),id:I.string()}).nullish()})}),I.object({type:I.literal("content_block_start"),index:I.number(),content_block:I.discriminatedUnion("type",[I.object({type:I.literal("text"),text:I.string()}),I.object({type:I.literal("thinking"),thinking:I.string()}),I.object({type:I.literal("tool_use"),id:I.string(),name:I.string(),input:I.record(I.string(),I.unknown()).optional(),caller:I.union([I.object({type:I.literal("code_execution_20250825"),tool_id:I.string()}),I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()}),I.object({type:I.literal("redacted_thinking"),data:I.string()}),I.object({type:I.literal("compaction"),content:I.string().nullish()}),I.object({type:I.literal("server_tool_use"),id:I.string(),name:I.string(),input:I.record(I.string(),I.unknown()).nullish(),caller:I.union([I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()}),I.object({type:I.literal("mcp_tool_use"),id:I.string(),name:I.string(),input:I.unknown(),server_name:I.string()}),I.object({type:I.literal("mcp_tool_result"),tool_use_id:I.string(),is_error:I.boolean(),content:I.array(I.union([I.string(),I.object({type:I.literal("text"),text:I.string()})]))}),I.object({type:I.literal("web_fetch_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("web_fetch_result"),url:I.string(),retrieved_at:I.string(),content:I.object({type:I.literal("document"),title:I.string().nullable(),citations:I.object({enabled:I.boolean()}).optional(),source:I.union([I.object({type:I.literal("base64"),media_type:I.literal("application/pdf"),data:I.string()}),I.object({type:I.literal("text"),media_type:I.literal("text/plain"),data:I.string()})])})}),I.object({type:I.literal("web_fetch_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("web_search_tool_result"),tool_use_id:I.string(),content:I.union([I.array(I.object({type:I.literal("web_search_result"),url:I.string(),title:I.string(),encrypted_content:I.string(),page_age:I.string().nullish()})),I.object({type:I.literal("web_search_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("code_execution_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("code_execution_result"),stdout:I.string(),stderr:I.string(),return_code:I.number(),content:I.array(I.object({type:I.literal("code_execution_output"),file_id:I.string()})).optional().default([])}),I.object({type:I.literal("encrypted_code_execution_result"),encrypted_stdout:I.string(),stderr:I.string(),return_code:I.number(),content:I.array(I.object({type:I.literal("code_execution_output"),file_id:I.string()})).optional().default([])}),I.object({type:I.literal("code_execution_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("bash_code_execution_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("bash_code_execution_result"),content:I.array(I.object({type:I.literal("bash_code_execution_output"),file_id:I.string()})),stdout:I.string(),stderr:I.string(),return_code:I.number()}),I.object({type:I.literal("bash_code_execution_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("text_editor_code_execution_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("text_editor_code_execution_tool_result_error"),error_code:I.string()}),I.object({type:I.literal("text_editor_code_execution_view_result"),content:I.string(),file_type:I.string(),num_lines:I.number().nullable(),start_line:I.number().nullable(),total_lines:I.number().nullable()}),I.object({type:I.literal("text_editor_code_execution_create_result"),is_file_update:I.boolean()}),I.object({type:I.literal("text_editor_code_execution_str_replace_result"),lines:I.array(I.string()).nullable(),new_lines:I.number().nullable(),new_start:I.number().nullable(),old_lines:I.number().nullable(),old_start:I.number().nullable()})])}),I.object({type:I.literal("tool_search_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("tool_search_tool_search_result"),tool_references:I.array(I.object({type:I.literal("tool_reference"),tool_name:I.string()}))}),I.object({type:I.literal("tool_search_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("advisor_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("advisor_result"),text:I.string()}),I.object({type:I.literal("advisor_redacted_result"),encrypted_content:I.string()}),I.object({type:I.literal("advisor_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("fallback")})])}),I.object({type:I.literal("content_block_delta"),index:I.number(),delta:I.discriminatedUnion("type",[I.object({type:I.literal("input_json_delta"),partial_json:I.string()}),I.object({type:I.literal("text_delta"),text:I.string()}),I.object({type:I.literal("thinking_delta"),thinking:I.string()}),I.object({type:I.literal("signature_delta"),signature:I.string()}),I.object({type:I.literal("compaction_delta"),content:I.string().nullish()}),I.object({type:I.literal("citations_delta"),citation:I.discriminatedUnion("type",[I.object({type:I.literal("web_search_result_location"),cited_text:I.string(),url:I.string(),title:I.string(),encrypted_index:I.string()}),I.object({type:I.literal("page_location"),cited_text:I.string(),document_index:I.number(),document_title:I.string().nullable(),start_page_number:I.number(),end_page_number:I.number()}),I.object({type:I.literal("char_location"),cited_text:I.string(),document_index:I.number(),document_title:I.string().nullable(),start_char_index:I.number(),end_char_index:I.number()})])})])}),I.object({type:I.literal("content_block_stop"),index:I.number()}),I.object({type:I.literal("error"),error:I.object({type:I.string(),message:I.string()})}),I.object({type:I.literal("message_delta"),delta:I.object({stop_reason:I.string().nullish(),stop_sequence:I.string().nullish(),stop_details:EY$.nullish(),container:I.object({expires_at:I.string(),id:I.string(),skills:I.array(I.object({type:I.union([I.literal("anthropic"),I.literal("custom")]),skill_id:I.string(),version:I.string()})).nullish()}).nullish()}),usage:I.looseObject({input_tokens:I.number().nullish(),output_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish(),iterations:I.array(I.object({type:I.union([I.literal("compaction"),I.literal("message"),I.literal("advisor_message"),I.literal("fallback_message")]),model:I.string().nullish(),input_tokens:I.number(),output_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish()})).nullish()}),context_management:I.object({applied_edits:I.array(I.union([I.object({type:I.literal("clear_tool_uses_20250919"),cleared_tool_uses:I.number(),cleared_input_tokens:I.number()}),I.object({type:I.literal("clear_thinking_20251015"),cleared_thinking_turns:I.number(),cleared_input_tokens:I.number()}),I.object({type:I.literal("compact_20260112")})]))}).nullish()}),I.object({type:I.literal("message_stop")}),I.object({type:I.literal("ping")})]))),gJ4=U0(()=>Z0(I.object({signature:I.string().optional(),redactedData:I.string().optional()}))),HY$=K1.object({citations:K1.object({enabled:K1.boolean()}).optional(),title:K1.string().optional(),context:K1.string().optional()}),FY$=K1.object({sendReasoning:K1.boolean().optional(),structuredOutputMode:K1.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:K1.discriminatedUnion("type",[K1.object({type:K1.literal("adaptive"),display:K1.enum(["omitted","summarized"]).optional()}),K1.object({type:K1.literal("enabled"),budgetTokens:K1.number().optional()}),K1.object({type:K1.literal("disabled")})]).optional(),disableParallelToolUse:K1.boolean().optional(),cacheControl:K1.object({type:K1.literal("ephemeral"),ttl:K1.union([K1.literal("5m"),K1.literal("1h")]).optional()}).optional(),metadata:K1.object({userId:K1.string().optional()}).optional(),mcpServers:K1.array(K1.object({type:K1.literal("url"),name:K1.string(),url:K1.string(),authorizationToken:K1.string().nullish(),toolConfiguration:K1.object({enabled:K1.boolean().nullish(),allowedTools:K1.array(K1.string()).nullish()}).nullish()})).optional(),container:K1.object({id:K1.string().optional(),skills:K1.array(K1.object({type:K1.union([K1.literal("anthropic"),K1.literal("custom")]),skillId:K1.string(),version:K1.string().optional()})).optional()}).optional(),toolStreaming:K1.boolean().optional(),effort:K1.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:K1.object({type:K1.literal("tokens"),total:K1.number().int().min(20000),remaining:K1.number().int().min(0).optional()}).optional(),speed:K1.enum(["fast","standard"]).optional(),inferenceGeo:K1.enum(["us","global"]).optional(),fallbacks:K1.array(K1.object({model:K1.string(),max_tokens:K1.number().int().optional(),thinking:K1.record(K1.string(),K1.unknown()).optional(),output_config:K1.record(K1.string(),K1.unknown()).optional(),speed:K1.enum(["fast","standard"]).optional()})).optional(),anthropicBeta:K1.array(K1.string()).optional(),contextManagement:K1.object({edits:K1.array(K1.discriminatedUnion("type",[K1.object({type:K1.literal("clear_tool_uses_20250919"),trigger:K1.discriminatedUnion("type",[K1.object({type:K1.literal("input_tokens"),value:K1.number()}),K1.object({type:K1.literal("tool_uses"),value:K1.number()})]).optional(),keep:K1.object({type:K1.literal("tool_uses"),value:K1.number()}).optional(),clearAtLeast:K1.object({type:K1.literal("input_tokens"),value:K1.number()}).optional(),clearToolInputs:K1.boolean().optional(),excludeTools:K1.array(K1.string()).optional()}),K1.object({type:K1.literal("clear_thinking_20251015"),keep:K1.union([K1.literal("all"),K1.object({type:K1.literal("thinking_turns"),value:K1.number()})]).optional()}),K1.object({type:K1.literal("compact_20260112"),trigger:K1.object({type:K1.literal("input_tokens"),value:K1.number()}).optional(),pauseAfterCompaction:K1.boolean().optional(),instructions:K1.string().optional()})]))}).optional()});uJ4=U0(()=>Z0(WZ.object({model:WZ.string(),maxUses:WZ.number().optional(),caching:WZ.object({type:WZ.literal("ephemeral"),ttl:WZ.union([WZ.literal("5m"),WZ.literal("1h")])}).optional()}))),jY$=U0(()=>Z0(WZ.discriminatedUnion("type",[WZ.object({type:WZ.literal("advisor_result"),text:WZ.string()}),WZ.object({type:WZ.literal("advisor_redacted_result"),encryptedContent:WZ.string()}),WZ.object({type:WZ.literal("advisor_tool_result_error"),errorCode:WZ.string()})]))),cJ4=U0(()=>Z0(WZ.object({}).strict())),lJ4=o$({id:"anthropic.advisor_20260301",inputSchema:cJ4,outputSchema:jY$,supportsDeferredResults:!0}),mJ4=U0(()=>Z0(nG.object({maxCharacters:nG.number().optional()}))),iJ4=U0(()=>Z0(nG.object({command:nG.enum(["view","create","str_replace","insert"]),path:nG.string(),file_text:nG.string().optional(),insert_line:nG.number().int().optional(),new_str:nG.string().optional(),insert_text:nG.string().optional(),old_str:nG.string().optional(),view_range:nG.array(nG.number().int()).optional()}))),pJ4=S4({id:"anthropic.text_editor_20250728",inputSchema:iJ4}),tJ4=U0(()=>Z0(T9.object({maxUses:T9.number().optional(),allowedDomains:T9.array(T9.string()).optional(),blockedDomains:T9.array(T9.string()).optional(),userLocation:T9.object({type:T9.literal("approximate"),city:T9.string().optional(),region:T9.string().optional(),country:T9.string().optional(),timezone:T9.string().optional()}).optional()}))),oJ4=U0(()=>Z0(T9.array(T9.object({url:T9.string(),title:T9.string().nullable(),pageAge:T9.string().nullable(),encryptedContent:T9.string(),type:T9.literal("web_search_result")})))),rJ4=U0(()=>Z0(T9.object({query:T9.string()}))),aJ4=o$({id:"anthropic.web_search_20260209",inputSchema:rJ4,outputSchema:oJ4,supportsDeferredResults:!0}),eJ4=U0(()=>Z0(R9.object({maxUses:R9.number().optional(),allowedDomains:R9.array(R9.string()).optional(),blockedDomains:R9.array(R9.string()).optional(),userLocation:R9.object({type:R9.literal("approximate"),city:R9.string().optional(),region:R9.string().optional(),country:R9.string().optional(),timezone:R9.string().optional()}).optional()}))),zY$=U0(()=>Z0(R9.array(R9.object({url:R9.string(),title:R9.string().nullable(),pageAge:R9.string().nullable(),encryptedContent:R9.string(),type:R9.literal("web_search_result")})))),$34=U0(()=>Z0(R9.object({query:R9.string()}))),Z34=o$({id:"anthropic.web_search_20250305",inputSchema:$34,outputSchema:zY$,supportsDeferredResults:!0}),Q34=U0(()=>Z0(j6.object({maxUses:j6.number().optional(),allowedDomains:j6.array(j6.string()).optional(),blockedDomains:j6.array(j6.string()).optional(),citations:j6.object({enabled:j6.boolean()}).optional(),maxContentTokens:j6.number().optional()}))),Y34=U0(()=>Z0(j6.object({type:j6.literal("web_fetch_result"),url:j6.string(),content:j6.object({type:j6.literal("document"),title:j6.string().nullable(),citations:j6.object({enabled:j6.boolean()}).optional(),source:j6.union([j6.object({type:j6.literal("base64"),mediaType:j6.literal("application/pdf"),data:j6.string()}),j6.object({type:j6.literal("text"),mediaType:j6.literal("text/plain"),data:j6.string()})])}),retrievedAt:j6.string().nullable()}))),G34=U0(()=>Z0(j6.object({url:j6.string()}))),J34=o$({id:"anthropic.web_fetch_20260209",inputSchema:G34,outputSchema:Y34,supportsDeferredResults:!0}),K34=U0(()=>Z0(z6.object({maxUses:z6.number().optional(),allowedDomains:z6.array(z6.string()).optional(),blockedDomains:z6.array(z6.string()).optional(),citations:z6.object({enabled:z6.boolean()}).optional(),maxContentTokens:z6.number().optional()}))),PY$=U0(()=>Z0(z6.object({type:z6.literal("web_fetch_result"),url:z6.string(),content:z6.object({type:z6.literal("document"),title:z6.string().nullable(),citations:z6.object({enabled:z6.boolean()}).optional(),source:z6.union([z6.object({type:z6.literal("base64"),mediaType:z6.literal("application/pdf"),data:z6.string()}),z6.object({type:z6.literal("text"),mediaType:z6.literal("text/plain"),data:z6.string()})])}),retrievedAt:z6.string().nullable()}))),H34=U0(()=>Z0(z6.object({url:z6.string()}))),F34=o$({id:"anthropic.web_fetch_20250910",inputSchema:H34,outputSchema:PY$,supportsDeferredResults:!0});AY$=U0(()=>Z0(v3.object({type:v3.literal("code_execution_result"),stdout:v3.string(),stderr:v3.string(),return_code:v3.number(),content:v3.array(v3.object({type:v3.literal("code_execution_output"),file_id:v3.string()})).optional().default([])}))),O34=U0(()=>Z0(v3.object({code:v3.string()}))),B34=o$({id:"anthropic.code_execution_20250522",inputSchema:O34,outputSchema:AY$}),TY$=U0(()=>Z0(s1.discriminatedUnion("type",[s1.object({type:s1.literal("code_execution_result"),stdout:s1.string(),stderr:s1.string(),return_code:s1.number(),content:s1.array(s1.object({type:s1.literal("code_execution_output"),file_id:s1.string()})).optional().default([])}),s1.object({type:s1.literal("bash_code_execution_result"),content:s1.array(s1.object({type:s1.literal("bash_code_execution_output"),file_id:s1.string()})),stdout:s1.string(),stderr:s1.string(),return_code:s1.number()}),s1.object({type:s1.literal("bash_code_execution_tool_result_error"),error_code:s1.string()}),s1.object({type:s1.literal("text_editor_code_execution_tool_result_error"),error_code:s1.string()}),s1.object({type:s1.literal("text_editor_code_execution_view_result"),content:s1.string(),file_type:s1.string(),num_lines:s1.number().nullable(),start_line:s1.number().nullable(),total_lines:s1.number().nullable()}),s1.object({type:s1.literal("text_editor_code_execution_create_result"),is_file_update:s1.boolean()}),s1.object({type:s1.literal("text_editor_code_execution_str_replace_result"),lines:s1.array(s1.string()).nullable(),new_lines:s1.number().nullable(),new_start:s1.number().nullable(),old_lines:s1.number().nullable(),old_start:s1.number().nullable()})]))),D34=U0(()=>Z0(s1.discriminatedUnion("type",[s1.object({type:s1.literal("programmatic-tool-call"),code:s1.string()}),s1.object({type:s1.literal("bash_code_execution"),command:s1.string()}),s1.discriminatedUnion("command",[s1.object({type:s1.literal("text_editor_code_execution"),command:s1.literal("view"),path:s1.string()}),s1.object({type:s1.literal("text_editor_code_execution"),command:s1.literal("create"),path:s1.string(),file_text:s1.string().nullish()}),s1.object({type:s1.literal("text_editor_code_execution"),command:s1.literal("str_replace"),path:s1.string(),old_str:s1.string(),new_str:s1.string()})])]))),L34=o$({id:"anthropic.code_execution_20250825",inputSchema:D34,outputSchema:TY$,supportsDeferredResults:!0}),RY$=U0(()=>Z0(f1.discriminatedUnion("type",[f1.object({type:f1.literal("code_execution_result"),stdout:f1.string(),stderr:f1.string(),return_code:f1.number(),content:f1.array(f1.object({type:f1.literal("code_execution_output"),file_id:f1.string()})).optional().default([])}),f1.object({type:f1.literal("encrypted_code_execution_result"),encrypted_stdout:f1.string(),stderr:f1.string(),return_code:f1.number(),content:f1.array(f1.object({type:f1.literal("code_execution_output"),file_id:f1.string()})).optional().default([])}),f1.object({type:f1.literal("bash_code_execution_result"),content:f1.array(f1.object({type:f1.literal("bash_code_execution_output"),file_id:f1.string()})),stdout:f1.string(),stderr:f1.string(),return_code:f1.number()}),f1.object({type:f1.literal("bash_code_execution_tool_result_error"),error_code:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution_tool_result_error"),error_code:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution_view_result"),content:f1.string(),file_type:f1.string(),num_lines:f1.number().nullable(),start_line:f1.number().nullable(),total_lines:f1.number().nullable()}),f1.object({type:f1.literal("text_editor_code_execution_create_result"),is_file_update:f1.boolean()}),f1.object({type:f1.literal("text_editor_code_execution_str_replace_result"),lines:f1.array(f1.string()).nullable(),new_lines:f1.number().nullable(),new_start:f1.number().nullable(),old_lines:f1.number().nullable(),old_start:f1.number().nullable()})]))),j34=U0(()=>Z0(f1.discriminatedUnion("type",[f1.object({type:f1.literal("programmatic-tool-call"),code:f1.string()}),f1.object({type:f1.literal("bash_code_execution"),command:f1.string()}),f1.discriminatedUnion("command",[f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("view"),path:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("create"),path:f1.string(),file_text:f1.string().nullish()}),f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("str_replace"),path:f1.string(),old_str:f1.string(),new_str:f1.string()})])]))),z34=o$({id:"anthropic.code_execution_20260120",inputSchema:j34,outputSchema:RY$,supportsDeferredResults:!0}),IY$=U0(()=>Z0(hS.array(hS.object({type:hS.literal("tool_reference"),toolName:hS.string()})))),A34=U0(()=>Z0(hS.object({pattern:hS.string(),limit:hS.number().optional()}))),T34=o$({id:"anthropic.tool_search_regex_20251119",inputSchema:A34,outputSchema:IY$,supportsDeferredResults:!0});qY$=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),V34=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];y34=U0(()=>Z0(Op0.object({command:Op0.string(),restart:Op0.boolean().optional()}))),g34=S4({id:"anthropic.bash_20241022",inputSchema:y34}),h34=U0(()=>Z0(Bp0.object({command:Bp0.string(),restart:Bp0.boolean().optional()}))),u34=S4({id:"anthropic.bash_20250124",inputSchema:h34}),c34=U0(()=>Z0(hp.object({action:hp.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:hp.array(hp.number().int()).optional(),text:hp.string().optional()}))),l34=S4({id:"anthropic.computer_20241022",inputSchema:c34}),d34=U0(()=>Z0(pG.object({action:pG.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:pG.tuple([pG.number().int(),pG.number().int()]).optional(),duration:pG.number().optional(),scroll_amount:pG.number().optional(),scroll_direction:pG.enum(["up","down","left","right"]).optional(),start_coordinate:pG.tuple([pG.number().int(),pG.number().int()]).optional(),text:pG.string().optional()}))),m34=S4({id:"anthropic.computer_20250124",inputSchema:d34}),i34=U0(()=>Z0(F7.object({action:F7.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:F7.tuple([F7.number().int(),F7.number().int()]).optional(),duration:F7.number().optional(),region:F7.tuple([F7.number().int(),F7.number().int(),F7.number().int(),F7.number().int()]).optional(),scroll_amount:F7.number().optional(),scroll_direction:F7.enum(["up","down","left","right"]).optional(),start_coordinate:F7.tuple([F7.number().int(),F7.number().int()]).optional(),text:F7.string().optional()}))),p34=S4({id:"anthropic.computer_20251124",inputSchema:i34}),n34=U0(()=>Z0(S6.discriminatedUnion("command",[S6.object({command:S6.literal("view"),path:S6.string(),view_range:S6.tuple([S6.number(),S6.number()]).optional()}),S6.object({command:S6.literal("create"),path:S6.string(),file_text:S6.string()}),S6.object({command:S6.literal("str_replace"),path:S6.string(),old_str:S6.string(),new_str:S6.string()}),S6.object({command:S6.literal("insert"),path:S6.string(),insert_line:S6.number(),insert_text:S6.string()}),S6.object({command:S6.literal("delete"),path:S6.string()}),S6.object({command:S6.literal("rename"),old_path:S6.string(),new_path:S6.string()})]))),t34=S4({id:"anthropic.memory_20250818",inputSchema:n34}),o34=U0(()=>Z0(DK.object({command:DK.enum(["view","create","str_replace","insert","undo_edit"]),path:DK.string(),file_text:DK.string().optional(),insert_line:DK.number().int().optional(),new_str:DK.string().optional(),insert_text:DK.string().optional(),old_str:DK.string().optional(),view_range:DK.array(DK.number().int()).optional()}))),r34=S4({id:"anthropic.text_editor_20241022",inputSchema:o34}),a34=U0(()=>Z0(LK.object({command:LK.enum(["view","create","str_replace","insert","undo_edit"]),path:LK.string(),file_text:LK.string().optional(),insert_line:LK.number().int().optional(),new_str:LK.string().optional(),insert_text:LK.string().optional(),old_str:LK.string().optional(),view_range:LK.array(LK.number().int()).optional()}))),s34=S4({id:"anthropic.text_editor_20250124",inputSchema:a34}),e34=U0(()=>Z0(EK.object({command:EK.enum(["view","create","str_replace","insert"]),path:EK.string(),file_text:EK.string().optional(),insert_line:EK.number().int().optional(),new_str:EK.string().optional(),insert_text:EK.string().optional(),old_str:EK.string().optional(),view_range:EK.array(EK.number().int()).optional()}))),$W4=S4({id:"anthropic.text_editor_20250429",inputSchema:e34}),ZW4=U0(()=>Z0(uS.array(uS.object({type:uS.literal("tool_reference"),toolName:uS.string()})))),XW4=U0(()=>Z0(uS.object({query:uS.string(),limit:uS.number().optional()}))),QW4=o$({id:"anthropic.tool_search_bm25_20251119",inputSchema:XW4,outputSchema:ZW4,supportsDeferredResults:!0}),GW4={advisor_20260301:dJ4,bash_20241022:g34,bash_20250124:u34,codeExecution_20250522:w34,codeExecution_20250825:E34,codeExecution_20260120:P34,computer_20241022:l34,computer_20250124:m34,computer_20251124:p34,memory_20250818:t34,textEditor_20241022:r34,textEditor_20250124:s34,textEditor_20250429:$W4,textEditor_20250728:nJ4,webFetch_20250910:N34,webFetch_20260209:W34,webSearch_20250305:X34,webSearch_20260209:sJ4,toolSearchRegex_20251119:R34,toolSearchBm25_20251119:YW4};TE9=up()});import{z as vF}from"zod/v4";import{z as cp}from"zod/v4";import{z as $X}from"zod/v4";import{z as h0}from"zod/v4";import{z as W6}from"zod/v4";import{z as Hy}from"zod/v4";import{z as CW4}from"zod/v4";import{z as lp}from"zod/v4";import{z as xW4}from"zod/v4";import{z as cS}from"zod/v4";import{z as uW4}from"zod/v4";import{z as Lp0}from"zod/v4";import{z as lS}from"zod/v4";import{z as Z9}from"zod/v4";import{z as F0}from"zod/v4";import{z as m1}from"zod/v4";function kY$($){var Z,X,Q,Y;if($==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let G=(Z=$.promptTokenCount)!=null?Z:0,J=(X=$.candidatesTokenCount)!=null?X:0,W=(Q=$.cachedContentTokenCount)!=null?Q:0,K=(Y=$.thoughtsTokenCount)!=null?Y:0;return{inputTokens:{total:G,noCache:G-W,cacheRead:W,cacheWrite:void 0},outputTokens:{total:J+K,text:J,reasoning:K},raw:$}}function f3($,Z=!0){if($==null)return;if(OW4($)){if(Z)return;if(typeof $==="object"&&$.description)return{type:"object",description:$.description};return{type:"object"}}if(typeof $==="boolean")return{type:"boolean",properties:{}};let{type:X,description:Q,required:Y,properties:G,items:J,allOf:W,anyOf:K,oneOf:H,format:F,const:N,minLength:U,enum:O}=$,B={};if(Q)B.description=Q;if(Y)B.required=Y;if(F)B.format=F;if(N!==void 0)B.enum=[N];if(X)if(Array.isArray(X)){let D=X.includes("null"),L=X.filter((E)=>E!=="null");if(L.length===0)B.type="null";else if(B.anyOf=L.map((E)=>({type:E})),D)B.nullable=!0}else B.type=X;if(O!==void 0)B.enum=O;if(G!=null)B.properties=Object.entries(G).reduce((D,[L,E])=>{return D[L]=f3(E,!1),D},{});if(J)B.items=Array.isArray(J)?J.map((D)=>f3(D,!1)):f3(J,!1);if(W)B.allOf=W.map((D)=>f3(D,!1));if(K)if(K.some((D)=>typeof D==="object"&&(D==null?void 0:D.type)==="null")){let D=K.filter((L)=>!(typeof L==="object"&&(L==null?void 0:L.type)==="null"));if(D.length===1){let L=f3(D[0],!1);if(typeof L==="object")B.nullable=!0,Object.assign(B,L)}else B.anyOf=D.map((L)=>f3(L,!1)),B.nullable=!0}else B.anyOf=K.map((D)=>f3(D,!1));if(H)B.oneOf=H.map((D)=>f3(D,!1));if(U!==void 0)B.minLength=U;return B}function OW4($){return $!=null&&typeof $==="object"&&$.type==="object"&&($.properties==null||Object.keys($.properties).length===0)&&!$.additionalProperties}function VY$($,Z){let X=[Z,"google","googleVertex","vertex"].filter((Q,Y,G)=>{return G.indexOf(Q)===Y});for(let Q of X){let Y=$==null?void 0:$[Q];if(Y!=null)return Y}}function DW4($){let Z=wW4.exec($);if(Z==null)return;return{mediaType:Z[1],data:Z[2]}}function LW4($){let Z=DW4($);if(Z==null)return;return{inlineData:{mimeType:Z.mediaType,data:Z.data}}}function EW4($,Z,X,Q){let Y=[],G=[];for(let J of X)switch(J.type){case"text":{G.push(J.text);break}case"image-data":case"file-data":{Y.push({inlineData:{mimeType:J.mediaType,data:J.data}});break}case"image-url":case"file-url":{let W=LW4(J.url);if(W!=null)Y.push(W);else G.push(JSON.stringify(J));break}default:{G.push(JSON.stringify(J));break}}$.push({functionResponse:{...Q!=null?{id:Q}:{},name:Z,response:{name:Z,content:G.length>0?G.join(`
|
|
1049
|
+
`);Yp0=c({name:"TASK_ADD_REPO",description:"Clone one of this organization's repositories into your working directory. "+"Your working directory is EMPTY until you call this \u2014 do not look for "+"files, and do not run git, before it returns. Call it once, with the repository the task is about; it waits for the checkout and returns the repository root listing, so you can start reading files immediately after. `git` and `gh` are authenticated once it returns. Call TASK_ADD_REPO with no arguments to list the repositories available.",annotations:{title:"Add Repository",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},inputSchema:mG.object({connectionId:mG.string().optional().describe("connectionId of the repository to clone. Omit to list the available repositories.")}),outputSchema:mG.object({success:mG.boolean(),repositories:mG.array(mG.object({connectionId:mG.string(),repo:mG.string()})).optional(),repo:mG.string().optional(),cloned:mG.boolean().optional(),files:mG.string().optional(),message:mG.string()}),handler:async($,Z)=>{r(Z),await Z.access.check();let X=t(Z),Q=J1(Z);if(!Q)throw Error("User ID required");let{threadId:Y}=xO0(),G=await TJ4(Z,X.id),J=$.connectionId?G.find((q)=>q.connectionId===$.connectionId):void 0;if(!J){let q=G.map((k)=>({connectionId:k.connectionId,repo:`${k.owner}/${k.repo}`}));return{success:!1,repositories:q,message:$.connectionId?`No imported repository for connectionId "${$.connectionId}". Pick one of the repositories listed.`:q.length===0?"This organization has no repositories imported, so none can be cloned.":"Pick a repository and call TASK_ADD_REPO again with its connectionId."}}let W=await Z.storage.threads.get(Y);if(!W)throw Error(`Thread not found: ${Y}`);let K=await IO0(Z,{threadId:Y}),H=await CF(Z,K,Q),{provider:F,kind:N}=await oX(Z,{userId:H,branch:K,virtualMcpMetadata:null}),U=await jJ4(Z,Y,H,K,N);if(!U)throw Error(`No sandbox is registered for this run (thread ${Y}), so there is nowhere to clone into.`);await iO({ctx:Z,connectionId:J.connectionId,organizationId:X.id,forceRefresh:!0,onLegacyMintError:(q)=>console.error("[TASK_ADD_REPO] legacy repo-scoped mint failed",{connectionId:J.connectionId,error:q.message})});let{cloneUrl:O,gitUserName:B,gitUserEmail:D}=await pO(J.connectionId,J.owner,J.repo,Z.db,Z.vault,{bufferMs:wJ4});await Z.storage.threads.update(Y,{metadata:{...W.metadata??{},githubRepo:{url:`https://github.com/${J.owner}/${J.repo}`,owner:J.owner,name:J.repo,installationId:J.installationId,connectionId:J.connectionId}},updated_by:Q});let L=CO0({branch:K,derivedRef:SF(K),recordedHeadRef:null,sticky:!1}),E=await F.proxyDaemonRequest(U.sandboxHandle,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({git:{repository:{cloneUrl:O,branch:L,repoName:`${J.owner}/${J.repo}`},identity:{userName:B,userEmail:D}}})});if(!E.ok)throw Error(`the sandbox rejected the repository (${E.status} ${E.statusText})`);await F.proxyDaemonRequest(U.sandboxHandle,"/_sandbox/setup/clone",{method:"POST",headers:new Headers({"content-type":"application/json"}),body:"{}"}).catch((q)=>{console.warn("[TASK_ADD_REPO] explicit clone kick failed",q)});let j=Date.now()+oQ$,z=!1,A="",P=0,M=null;while(Date.now()<j){let q=await aQ$(F,U.sandboxHandle,Y,"if git rev-parse HEAD >/dev/null 2>&1; then echo __CLONED__; fi; ls -A 2>/dev/null").catch(()=>null);if(!q){if(++P>=zJ4)break;await q$(rQ$);continue}P=0;let k=PJ4(q.stdout);if(k.cloned&&k.listing===M){z=!0,A=k.listing;break}M=k.cloned?k.listing:null,await q$(rQ$)}if(z)await aQ$(F,U.sandboxHandle,Y,AJ4).catch((q)=>console.warn("[TASK_ADD_REPO] gh auth setup failed",q));return{success:z,repo:`${J.owner}/${J.repo}`,cloned:z,files:A,message:z?`${J.owner}/${J.repo} is checked out at your working directory on branch ${L}. \`git\` and \`gh\` are authenticated. Start working.`:`The clone of ${J.owner}/${J.repo} did not finish within ${Math.round(oQ$/1000)}s. It may still be in progress \u2014 check your working directory before calling this again.`}}})});import{z as s1}from"zod";var C3,gS,RJ4,IJ4,eQ$,Wy,qJ4,MJ4,$Y$;var _3=w(()=>{L9();C3=s1.enum(["triage","todo","in_progress","in_review","done","archived"]),gS=s1.enum(["none","low","medium","high","urgent"]),RJ4=s1.object({threadId:s1.string(),virtualMcpId:s1.string().nullable(),status:s1.enum(["in_progress","requires_action","failed","completed","expired"]).nullable(),title:s1.string().nullable(),lastMessage:s1.string().nullable(),hasPreview:s1.boolean(),failureKind:s1.string().nullable(),hasMessages:s1.boolean(),costUsd:s1.number().nullable(),createdAt:s1.string()}),IJ4=s1.object({id:s1.string(),name:s1.string(),color:s1.string().nullable().describe('Hex color, e.g. "#3b82f6"'),createdBy:s1.string(),createdAt:s1.string().datetime()}),eQ$=s1.object({url:s1.string(),number:s1.number(),repoOwner:s1.string(),repoName:s1.string(),createdAt:s1.string(),title:s1.string().nullable(),body:s1.string().nullable(),state:s1.enum(["open","closed"]).nullable(),draft:s1.boolean().nullable(),merged:s1.boolean().nullable(),mergeable:s1.boolean().nullable(),checksStatus:s1.enum(["pending","passing","failing"]).nullable(),checks:s1.array(s1.object({name:s1.string(),status:s1.string(),conclusion:s1.string().nullable(),detailsUrl:s1.string().nullable(),summary:s1.string().nullable()})),previewUrl:s1.string().nullable()}),Wy=s1.object({id:s1.string(),organizationId:s1.string(),title:s1.string(),description:s1.string().nullable(),status:C3,priority:gS,assigneeId:s1.string().nullable(),assignedBy:s1.string().nullable(),repo:s1.string().nullable(),dueDate:s1.string().datetime().nullable(),sortOrder:s1.number(),retryAttempts:s1.number(),threads:s1.array(RJ4),tags:s1.array(IJ4),createdBy:s1.string(),createdAt:s1.string().datetime(),updatedBy:s1.string(),updatedAt:s1.string().datetime()}),qJ4=["created","status_changed","assignee_changed","priority_changed","due_date_changed","title_changed","description_changed","tags_changed","review_requested","review_approved","review_changes_requested","merge_conflict_resolution","merge_failed"],MJ4=s1.enum(qJ4),$Y$=s1.object({id:s1.string(),taskBoardItemId:s1.string(),action:MJ4,actorId:s1.string().nullable(),data:s1.record(s1.string(),s1.unknown()),occurredAt:s1.string().datetime()})});async function yO0($,Z,X){if(X===n8)return;let{members:Q}=await $.boundAuth.organization.listMembers({organizationId:Z,filterField:"userId",filterValue:X});if(!Q.some((Y)=>Y.userId===X))throw Error("assigneeId is not a member of the organization")}var Gp0=w(()=>{_3()});function QY$($){let Z={};for(let[X,Q]of Object.entries($)){if(X.startsWith(kJ4))continue;Z[X]=Q}return Z}function gO0($){return{taskBoardItemId:$.id,...MQ($)&&{[ZY$]:XY$}}}function VJ4($){return $?.[ZY$]===XY$}function SJ4($){if(/[:\s]/.test($))throw Error("organization id unsuitable for the subsidy key scheme");return`subsidy:${$}`}async function CJ4($,Z){let X=b0();try{let Q=await $.storage.subsidizedGatewayKeys.get(Z);if(Q)return Q;let Y=$.auth?.user?.id;if(Y&&X.aiGatewayEnabled&&X.studioProvisionSecretKey&&DO.provisionKey){let G=await TW(Y,$.auth?.user?.email),J=await DO.provisionKey(G,SJ4(Z));return await $.storage.subsidizedGatewayKeys.put(Z,J),J}}catch(Q){console.error("[subsidized-runs] subsidy key unavailable \u2014 run stays on the org's key:",Q)}return}async function YY$($,Z,X){if(!b0().taskQuotaEnforced)return;if(!VJ4(X))return;let Q=X?.taskBoardItemId;if(!Q)return;let Y=await $.storage.taskBoard.getById(Q,Z);if(!Y||!MQ(Y))return;if(!await ma1($,Q))return;return await CJ4($,Z)}function GY$($,Z){if(!Z)return $;if($.providerId!=="deco")return $;return{...$,apiKey:Z}}var kJ4="srv.",ZY$="srv.billing",XY$="subscription";var bp=w(()=>{Y50();OU();T$();L3()});function uO0($){let Z=$?.runClass;return Z&&Z in Jp0?Jp0[Z]:Jp0.interactive}var Jp0,hO0="runClass";var xp=w(()=>{Jp0={interactive:10,reviewer:20,retry:30,new_task:40}});async function Wp0($,Z,X){let Q;try{return await Promise.race([$.aiProviders.listModels(Z,X),new Promise((G,J)=>{Q=setTimeout(()=>J(Error("listModels timeout")),_J4)})])}finally{if(Q)clearTimeout(Q)}}function vJ4($,Z){switch($){case"fast":return Z.chat.fast;case"smart":return Z.chat.smart;case"thinking":return Z.chat.thinking;case"image":return Z.image;case"web_search":return Z.webSearch;case"deep_research":return Z.deepResearch}}function Kp0($,Z,X){let Q=$.find((Y)=>Y.modelId===Z);return{title:Q?.title??X??Z,providerId:Q?.providerId,capabilities:Q?.capabilities,limits:Q?.limits??null}}async function e7($,Z,X){let Q=$.organization?.id;if(!Q)throw Error("resolveTier called without an organization");let G=(await $.storage.organizationSettings.get(Q))?.simple_mode?.tiers?.[Z]??null,J=$.auth?.user?.id,W=kO.safeParse(Z),K=X?.applyUserPrefs&&W.success&&J?(await $.storage.userModelPreferences.get(J,Q))?.tiers?.[W.data]??null:null,H=(await $.storage.aiProviderKeys.list({organizationId:Q})).filter((B)=>kD(B.providerId));for(let B of[K,G])if(B&&H.some((D)=>D.id===B.keyId)){let D=await Wp0($,B.keyId,Q).catch(()=>[]);return{credentialId:B.keyId,modelId:B.modelId,modelMeta:Kp0(D,B.modelId,B.title)}}if(H.length===0)throw new Ky(Z);let F={};await Promise.all(H.map(async(B)=>{F[B.id]=await Wp0($,B.id,Q).catch(()=>[])}));let N=H.map((B)=>({id:B.id,providerId:B.providerId,label:B.label,presetId:B.presetId,createdBy:B.createdBy,createdAt:B.createdAt})),U=ax1(N,F),O=vJ4(Z,U);if(!O)throw new Ky(Z);return{credentialId:O.keyId,modelId:O.modelId,modelMeta:Kp0(F[O.keyId]??[],O.modelId,O.title)}}async function JY$($,Z,X){let Q=$.organization?.id;if(!Q)throw Error("resolveSpecificModel called without an organization");let Y=await $.storage.aiProviderKeys.findById(Z,Q).catch((J)=>{if(J instanceof Error&&J.message==="Provider key not found")throw new yp(`AI provider credential "${Z}" was not found`,{cause:J});throw J});if(!kD(Y.providerId))throw new yp(`AI provider credential "${Z}" uses native-only provider "${Y.providerId}" and cannot run a hosted model`);let G=await Wp0($,Z,Q).catch(()=>[]);return{credentialId:Z,modelId:X,modelMeta:Kp0(G,X)}}async function iG($,Z){try{return await e7($,Z)}catch(X){if(X instanceof Ky)return null;return console.warn(`[resolveTier] tier "${Z}" resolution failed:`,X),null}}var Ky,yp,_J4=5000;var NB=w(()=>{RQ();U8();Ky=class Ky extends Error{tier;constructor($){super(`No model available for tier "${$}". Connect a provider or configure the tier in organization settings.`);this.tier=$;this.name="TierUnavailableError"}};yp=class yp extends Error{constructor($,Z){super($,Z);this.name="SpecificModelCredentialUnavailableError"}}});function WY$($){return $ instanceof wK||typeof $==="object"&&$!==null&&$.permanent===!0}var wK;var Hp0=w(()=>{wK=class wK extends Error{permanent=!0;code;constructor($,Z){super(Z);this.name="PermanentRunError",this.code=$}}});import{z as gp}from"zod/v4";import{z as I}from"zod/v4";import{z as K1}from"zod/v4";import{z as WZ}from"zod/v4";import{z as nG}from"zod/v4";import{z as T9}from"zod/v4";import{z as R9}from"zod/v4";import{z as j6}from"zod/v4";import{z as z6}from"zod/v4";import{z as v3}from"zod/v4";import{z as e1}from"zod/v4";import{z as f1}from"zod/v4";import{z as hS}from"zod/v4";import{z as Op0}from"zod/v4";import{z as Bp0}from"zod/v4";import{z as hp}from"zod/v4";import{z as pG}from"zod/v4";import{z as F7}from"zod/v4";import{z as S6}from"zod/v4";import{z as DK}from"zod/v4";import{z as LK}from"zod/v4";import{z as EK}from"zod/v4";import{z as uS}from"zod/v4";function hJ4($){var Z;let X=$==null?void 0:$.anthropic;return(Z=X==null?void 0:X.cacheControl)!=null?Z:X==null?void 0:X.cache_control}async function U34({tools:$,toolChoice:Z,disableParallelToolUse:X,cacheControlValidator:Q,supportsStructuredOutput:Y,supportsStrictTools:G,defaultEagerInputStreaming:J=!1}){var W,K;$=($==null?void 0:$.length)?$:void 0;let H=[],F=new Set,N=Q||new wp0;if($==null)return{tools:void 0,toolChoice:void 0,toolWarnings:H,betas:F};let U=[];for(let B of $)switch(B.type){case"function":{let D=N.getCacheControl(B.providerOptions,{type:"tool definition",canCache:!0}),L=(W=B.providerOptions)==null?void 0:W.anthropic,E=(K=L==null?void 0:L.eagerInputStreaming)!=null?K:J,j=L==null?void 0:L.deferLoading,z=L==null?void 0:L.allowedCallers;if(!G&&B.strict!=null)H.push({type:"unsupported",feature:"strict",details:`Tool '${B.name}' has strict: ${B.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`});if(U.push({name:B.name,description:B.description,input_schema:B.inputSchema,cache_control:D,...E?{eager_input_streaming:!0}:{},...G===!0&&B.strict!=null?{strict:B.strict}:{},...j!=null?{defer_loading:j}:{},...z!=null?{allowed_callers:z}:{},...B.inputExamples!=null?{input_examples:B.inputExamples.map((A)=>A.input)}:{}}),Y===!0)F.add("structured-outputs-2025-11-13");if(B.inputExamples!=null||z!=null)F.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(B.id){case"anthropic.code_execution_20250522":{F.add("code-execution-2025-05-22"),U.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{F.add("code-execution-2025-08-25"),U.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{U.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"computer",type:"computer_20250124",display_width_px:B.args.displayWidthPx,display_height_px:B.args.displayHeightPx,display_number:B.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{F.add("computer-use-2025-11-24"),U.push({name:"computer",type:"computer_20251124",display_width_px:B.args.displayWidthPx,display_height_px:B.args.displayHeightPx,display_number:B.args.displayNumber,enable_zoom:B.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"computer",type:"computer_20241022",display_width_px:B.args.displayWidthPx,display_height_px:B.args.displayHeightPx,display_number:B.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{F.add("computer-use-2025-01-24"),U.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let D=await g$({value:B.args,schema:mJ4});U.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:D.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{F.add("computer-use-2025-01-24"),U.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{F.add("computer-use-2024-10-22"),U.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{F.add("context-management-2025-06-27"),U.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{F.add("web-fetch-2025-09-10");let D=await g$({value:B.args,schema:K34});U.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,citations:D.citations,max_content_tokens:D.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{F.add("code-execution-web-tools-2026-02-09");let D=await g$({value:B.args,schema:Q34});U.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,citations:D.citations,max_content_tokens:D.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let D=await g$({value:B.args,schema:eJ4});U.push({type:"web_search_20250305",name:"web_search",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,user_location:D.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{F.add("code-execution-web-tools-2026-02-09");let D=await g$({value:B.args,schema:tJ4});U.push({type:"web_search_20260209",name:"web_search",max_uses:D.maxUses,allowed_domains:D.allowedDomains,blocked_domains:D.blockedDomains,user_location:D.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{U.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{U.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}case"anthropic.advisor_20260301":{F.add("advisor-tool-2026-03-01");let D=await g$({value:B.args,schema:uJ4});U.push({type:"advisor_20260301",name:"advisor",model:D.model,...D.maxUses!==void 0&&{max_uses:D.maxUses},...D.caching!==void 0&&{caching:D.caching}});break}default:{H.push({type:"unsupported",feature:`provider-defined tool ${B.id}`});break}}break}default:{H.push({type:"unsupported",feature:`tool ${B}`});break}}if(Z==null)return{tools:U,toolChoice:X?{type:"auto",disable_parallel_tool_use:X}:void 0,toolWarnings:H,betas:F};let O=Z.type;switch(O){case"auto":return{tools:U,toolChoice:{type:"auto",disable_parallel_tool_use:X},toolWarnings:H,betas:F};case"required":return{tools:U,toolChoice:{type:"any",disable_parallel_tool_use:X},toolWarnings:H,betas:F};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:H,betas:F};case"tool":return{tools:U,toolChoice:{type:"tool",name:Z.toolName,disable_parallel_tool_use:X},toolWarnings:H,betas:F};default:throw new V4({functionality:`tool choice type: ${O}`})}}function UY$({usage:$,rawUsage:Z}){var X,Q,Y;let G=(X=$.cache_creation_input_tokens)!=null?X:0,J=(Q=$.cache_read_input_tokens)!=null?Q:0,W,K,H=(Y=$.iterations)==null?void 0:Y.some((F)=>F.type==="fallback_message");if($.iterations&&$.iterations.length>0&&!H){let F=$.iterations.filter((N)=>N.type==="compaction"||N.type==="message");if(F.length>0){let N=F.reduce((U,O)=>({input:U.input+O.input_tokens,output:U.output+O.output_tokens}),{input:0,output:0});W=N.input,K=N.output}else W=$.input_tokens,K=$.output_tokens}else W=$.input_tokens,K=$.output_tokens;return{inputTokens:{total:W+G+J,noCache:W,cacheRead:J,cacheWrite:G},outputTokens:{total:K,text:void 0,reasoning:void 0},raw:Z!=null?Z:$}}function I34($){if(typeof $==="string")return new TextDecoder().decode(E9($));if($ instanceof Uint8Array)return new TextDecoder().decode($);if($ instanceof URL)throw new V4({functionality:"URL-based text documents are not supported for citations"});throw new V4({functionality:`unsupported data type for text documents: ${typeof $}`})}function Fp0($){return $ instanceof URL||q34($)}function q34($){return typeof $==="string"&&/^https?:\/\//i.test($)}function Np0($){return $ instanceof URL?$.toString():$}async function OY$($){if(typeof $==="string"){let Z=await vZ({text:$});if(Z.success&&typeof Z.value==="object"&&Z.value!==null)return Z.value;return{errorCode:"unavailable"}}if(typeof $==="object"&&$!==null)return $;return{}}async function M34({prompt:$,sendReasoning:Z,warnings:X,cacheControlValidator:Q,toolNameMapping:Y}){var G,J,W,K,H,F,N,U,O,B,D,L,E,j,z,A,P,M,q,k,C;let l=new Set,f=k34($),x=Q||new wp0,n=void 0,u=[];async function a(B0){var e,o;let P0=await t8({provider:"anthropic",providerOptions:B0,schema:HY$});return(o=(e=P0==null?void 0:P0.citations)==null?void 0:e.enabled)!=null?o:!1}async function O0(B0){let e=await t8({provider:"anthropic",providerOptions:B0,schema:HY$});return{title:e==null?void 0:e.title,context:e==null?void 0:e.context}}for(let B0=0;B0<f.length;B0++){let e=f[B0],o=B0===f.length-1,P0=e.type;switch(P0){case"system":{let Y0=e.messages.map(({content:j0,providerOptions:x0})=>({type:"text",text:j0,cache_control:x.getCacheControl(x0,{type:"system message",canCache:!0})}));if(n==null)n=Y0;else u.push({role:"system",content:Y0}),l.add("mid-conversation-system-2026-04-07");break}case"user":{let Y0=[];for(let j0 of e.messages){let{role:x0,content:V0}=j0;switch(x0){case"user":{for(let u0=0;u0<V0.length;u0++){let Q0=V0[u0],w0=u0===V0.length-1,L0=(G=x.getCacheControl(Q0.providerOptions,{type:"user message part",canCache:!0}))!=null?G:w0?x.getCacheControl(j0.providerOptions,{type:"user message",canCache:!0}):void 0;switch(Q0.type){case"text":{Y0.push({type:"text",text:Q0.text,cache_control:L0});break}case"file":{if(Q0.mediaType.startsWith("image/"))Y0.push({type:"image",source:Fp0(Q0.data)?{type:"url",url:Np0(Q0.data)}:{type:"base64",media_type:Q0.mediaType==="image/*"?"image/jpeg":Q0.mediaType,data:YZ(Q0.data)},cache_control:L0});else if(Q0.mediaType==="application/pdf"){l.add("pdfs-2024-09-25");let I0=await a(Q0.providerOptions),$0=await O0(Q0.providerOptions);Y0.push({type:"document",source:Fp0(Q0.data)?{type:"url",url:Np0(Q0.data)}:{type:"base64",media_type:"application/pdf",data:YZ(Q0.data)},title:(J=$0.title)!=null?J:Q0.filename,...$0.context&&{context:$0.context},...I0&&{citations:{enabled:!0}},cache_control:L0})}else if(Q0.mediaType==="text/plain"){let I0=await a(Q0.providerOptions),$0=await O0(Q0.providerOptions);Y0.push({type:"document",source:Fp0(Q0.data)?{type:"url",url:Np0(Q0.data)}:{type:"text",media_type:"text/plain",data:I34(Q0.data)},title:(W=$0.title)!=null?W:Q0.filename,...$0.context&&{context:$0.context},...I0&&{citations:{enabled:!0}},cache_control:L0})}else throw new V4({functionality:`media type: ${Q0.mediaType}`});break}}}break}case"tool":{for(let u0=0;u0<V0.length;u0++){let Q0=V0[u0];if(Q0.type==="tool-approval-response")continue;let w0=Q0.output,L0="providerOptions"in w0?w0.providerOptions:w0.type==="content"?(K=w0.value.find((R0)=>R0.providerOptions!=null))==null?void 0:K.providerOptions:void 0,I0=u0===V0.length-1,$0=(F=(H=x.getCacheControl(Q0.providerOptions,{type:"tool result part",canCache:!0}))!=null?H:x.getCacheControl(L0,{type:"tool result output",canCache:!0}))!=null?F:I0?x.getCacheControl(j0.providerOptions,{type:"tool result message",canCache:!0}):void 0,X0;switch(w0.type){case"content":X0=w0.value.map((R0)=>{var G0;switch(R0.type){case"text":return{type:"text",text:R0.text};case"image-data":return{type:"image",source:{type:"base64",media_type:R0.mediaType,data:R0.data}};case"image-url":return{type:"image",source:{type:"url",url:R0.url}};case"file-url":return{type:"document",source:{type:"url",url:R0.url}};case"file-data":{if(R0.mediaType==="application/pdf")return l.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:R0.mediaType,data:R0.data}};X.push({type:"other",message:`unsupported tool content part type: ${R0.type} with media type: ${R0.mediaType}`});return}case"custom":{let N0=(G0=R0.providerOptions)==null?void 0:G0.anthropic;if((N0==null?void 0:N0.type)==="tool-reference")return{type:"tool_reference",tool_name:N0.toolName};X.push({type:"other",message:"unsupported custom tool content part"});return}default:{X.push({type:"other",message:`unsupported tool content part type: ${R0.type}`});return}}}).filter(mL);break;case"text":case"error-text":X0=w0.value;break;case"execution-denied":X0=(N=w0.reason)!=null?N:"Tool execution denied.";break;case"json":case"error-json":default:X0=JSON.stringify(w0.value);break}Y0.push({type:"tool_result",tool_use_id:Q0.toolCallId,content:X0,is_error:w0.type==="error-text"||w0.type==="error-json"?!0:void 0,cache_control:$0})}break}default:throw Error(`Unsupported role: ${x0}`)}}u.push({role:"user",content:Y0});break}case"assistant":{let Y0=[],j0=new Set;for(let x0=0;x0<e.messages.length;x0++){let V0=e.messages[x0],u0=x0===e.messages.length-1,{content:Q0}=V0;for(let w0=0;w0<Q0.length;w0++){let L0=Q0[w0],I0=w0===Q0.length-1,$0=(U=x.getCacheControl(L0.providerOptions,{type:"assistant message part",canCache:!0}))!=null?U:I0?x.getCacheControl(V0.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(L0.type){case"text":{let X0=(O=L0.providerOptions)==null?void 0:O.anthropic;if((X0==null?void 0:X0.type)==="compaction")Y0.push({type:"compaction",content:L0.text,cache_control:$0});else Y0.push({type:"text",text:o&&u0&&I0?L0.text.trim():L0.text,cache_control:$0});break}case"reasoning":{if(Z){let X0=await t8({provider:"anthropic",providerOptions:L0.providerOptions,schema:gJ4});if(X0!=null)if(X0.signature!=null)x.getCacheControl(L0.providerOptions,{type:"thinking block",canCache:!1}),Y0.push({type:"thinking",thinking:L0.text,signature:X0.signature});else if(X0.redactedData!=null)x.getCacheControl(L0.providerOptions,{type:"redacted thinking block",canCache:!1}),Y0.push({type:"redacted_thinking",data:X0.redactedData});else X.push({type:"other",message:"unsupported reasoning metadata"});else X.push({type:"other",message:"unsupported reasoning metadata"})}else X.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(L0.providerExecuted){let G0=Y.toProviderToolName(L0.toolName);if(((D=(B=L0.providerOptions)==null?void 0:B.anthropic)==null?void 0:D.type)==="mcp-tool-use"){j0.add(L0.toolCallId);let E1=(E=(L=L0.providerOptions)==null?void 0:L.anthropic)==null?void 0:E.serverName;if(E1==null||typeof E1!=="string"){X.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}Y0.push({type:"mcp_tool_use",id:L0.toolCallId,name:L0.toolName,input:L0.input,server_name:E1,cache_control:$0})}else if(G0==="code_execution"&&L0.input!=null&&typeof L0.input==="object"&&"type"in L0.input&&typeof L0.input.type==="string"&&(L0.input.type==="bash_code_execution"||L0.input.type==="text_editor_code_execution"))Y0.push({type:"server_tool_use",id:L0.toolCallId,name:L0.input.type,input:L0.input,cache_control:$0});else if(G0==="code_execution"&&L0.input!=null&&typeof L0.input==="object"&&"type"in L0.input&&L0.input.type==="programmatic-tool-call"){let{type:E1,...n0}=L0.input;Y0.push({type:"server_tool_use",id:L0.toolCallId,name:"code_execution",input:n0,cache_control:$0})}else if(G0==="code_execution"||G0==="web_fetch"||G0==="web_search")Y0.push({type:"server_tool_use",id:L0.toolCallId,name:G0,input:L0.input,cache_control:$0});else if(G0==="tool_search_tool_regex"||G0==="tool_search_tool_bm25")Y0.push({type:"server_tool_use",id:L0.toolCallId,name:G0,input:L0.input,cache_control:$0});else if(G0==="advisor")Y0.push({type:"server_tool_use",id:L0.toolCallId,name:"advisor",input:{},cache_control:$0});else X.push({type:"other",message:`provider executed tool call for tool ${L0.toolName} is not supported`});break}let X0=(j=L0.providerOptions)==null?void 0:j.anthropic,R0=(X0==null?void 0:X0.caller)?(X0.caller.type==="code_execution_20250825"||X0.caller.type==="code_execution_20260120")&&X0.caller.toolId?{type:X0.caller.type,tool_id:X0.caller.toolId}:X0.caller.type==="direct"?{type:"direct"}:void 0:void 0;Y0.push({type:"tool_use",id:L0.toolCallId,name:L0.toolName,input:L0.input,...R0&&{caller:R0},cache_control:$0});break}case"tool-result":{let X0=Y.toProviderToolName(L0.toolName);if(j0.has(L0.toolCallId)){let R0=L0.output;if(R0.type!=="json"&&R0.type!=="error-json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}Y0.push({type:"mcp_tool_result",tool_use_id:L0.toolCallId,is_error:R0.type==="error-json",content:R0.value,cache_control:$0})}else if(X0==="code_execution"){let R0=L0.output;if(R0.type==="error-text"||R0.type==="error-json"){let G0={};try{if(typeof R0.value==="string")G0=JSON.parse(R0.value);else if(typeof R0.value==="object"&&R0.value!==null)G0=R0.value}catch(N0){}if(G0.type==="code_execution_tool_result_error")Y0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(z=G0.errorCode)!=null?z:"unknown"},cache_control:$0});else Y0.push({type:"bash_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:$0,content:{type:"bash_code_execution_tool_result_error",error_code:(A=G0.errorCode)!=null?A:"unknown"}});break}if(R0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}if(R0.value==null||typeof R0.value!=="object"||!("type"in R0.value)||typeof R0.value.type!=="string"){X.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${L0.toolName}`});break}if(R0.value.type==="code_execution_result"){let G0=await g$({value:R0.value,schema:AY$});Y0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:G0.type,stdout:G0.stdout,stderr:G0.stderr,return_code:G0.return_code,content:(P=G0.content)!=null?P:[]},cache_control:$0})}else if(R0.value.type==="encrypted_code_execution_result"){let G0=await g$({value:R0.value,schema:RY$});if(G0.type==="encrypted_code_execution_result")Y0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:G0.type,encrypted_stdout:G0.encrypted_stdout,stderr:G0.stderr,return_code:G0.return_code,content:(M=G0.content)!=null?M:[]},cache_control:$0})}else{let G0=await g$({value:R0.value,schema:TY$});if(G0.type==="code_execution_result")Y0.push({type:"code_execution_tool_result",tool_use_id:L0.toolCallId,content:{type:G0.type,stdout:G0.stdout,stderr:G0.stderr,return_code:G0.return_code,content:(q=G0.content)!=null?q:[]},cache_control:$0});else if(G0.type==="bash_code_execution_result"||G0.type==="bash_code_execution_tool_result_error")Y0.push({type:"bash_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:$0,content:G0});else Y0.push({type:"text_editor_code_execution_tool_result",tool_use_id:L0.toolCallId,cache_control:$0,content:G0})}break}if(X0==="web_fetch"){let R0=L0.output;if(R0.type==="error-json"){Y0.push({type:"web_fetch_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(k=(await OY$(R0.value)).errorCode)!=null?k:"unavailable"},cache_control:$0});break}if(R0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}let G0=await g$({value:R0.value,schema:PY$});Y0.push({type:"web_fetch_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_fetch_result",url:G0.url,retrieved_at:G0.retrievedAt,content:{type:"document",title:G0.content.title,citations:G0.content.citations,source:{type:G0.content.source.type,media_type:G0.content.source.mediaType,data:G0.content.source.data}}},cache_control:$0});break}if(X0==="web_search"){let R0=L0.output;if(R0.type==="error-json"){Y0.push({type:"web_search_tool_result",tool_use_id:L0.toolCallId,content:{type:"web_search_tool_result_error",error_code:(C=(await OY$(R0.value)).errorCode)!=null?C:"unavailable"},cache_control:$0});break}if(R0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}let G0=await g$({value:R0.value,schema:zY$});Y0.push({type:"web_search_tool_result",tool_use_id:L0.toolCallId,content:G0.map((N0)=>({url:N0.url,title:N0.title,page_age:N0.pageAge,encrypted_content:N0.encryptedContent,type:N0.type})),cache_control:$0});break}if(X0==="tool_search_tool_regex"||X0==="tool_search_tool_bm25"){let R0=L0.output;if(R0.type!=="json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}let N0=(await g$({value:R0.value,schema:IY$})).map((E1)=>({type:"tool_reference",tool_name:E1.toolName}));Y0.push({type:"tool_search_tool_result",tool_use_id:L0.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:N0},cache_control:$0});break}if(X0==="advisor"){let R0=L0.output;if(R0.type!=="json"&&R0.type!=="error-json"){X.push({type:"other",message:`provider executed tool result output type ${R0.type} for tool ${L0.toolName} is not supported`});break}let G0=await g$({value:R0.value,schema:jY$});if(G0.type==="advisor_result")Y0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_result",text:G0.text},cache_control:$0});else if(G0.type==="advisor_redacted_result")Y0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_redacted_result",encrypted_content:G0.encryptedContent},cache_control:$0});else Y0.push({type:"advisor_tool_result",tool_use_id:L0.toolCallId,content:{type:"advisor_tool_result_error",error_code:G0.errorCode},cache_control:$0});break}X.push({type:"other",message:`provider executed tool result for tool ${L0.toolName} is not supported`});break}}}}u.push({role:"assistant",content:Y0});break}default:throw Error(`content type: ${P0}`)}}return{prompt:{system:n,messages:u},betas:l}}function k34($){let Z=[],X=void 0;for(let Q of $){let{role:Y}=Q;switch(Y){case"system":{if((X==null?void 0:X.type)!=="system")X={type:"system",messages:[]},Z.push(X);X.messages.push(Q);break}case"assistant":{if((X==null?void 0:X.type)!=="assistant")X={type:"assistant",messages:[]},Z.push(X);X.messages.push(Q);break}case"user":{if((X==null?void 0:X.type)!=="user")X={type:"user",messages:[]},Z.push(X);X.messages.push(Q);break}case"tool":{if((X==null?void 0:X.type)!=="user")X={type:"user",messages:[]},Z.push(X);X.messages.push(Q);break}default:throw Error(`Unsupported role: ${Y}`)}}return Z}function Up0({finishReason:$,isJsonResponseFromTool:Z}){switch($){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return Z?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}function S34($){return MY$($)}function UB($){if(typeof $==="boolean"||!f34($))return $;return MY$($)}function MY$($){let Z={},X=$;if($.$ref!=null)return{$ref:$.$ref};if($.$schema!=null)Z.$schema=$.$schema;if($.$id!=null)Z.$id=$.$id;if($.title!=null)Z.title=$.title;if($.description!=null)Z.description=$.description;if($.default!==void 0)Z.default=$.default;if($.const!==void 0)Z.const=$.const;if($.enum!=null)Z.enum=$.enum;if($.type!=null)Z.type=$.type;if($.anyOf!=null)Z.anyOf=$.anyOf.map(UB);else if($.oneOf!=null)Z.anyOf=$.oneOf.map(UB);if($.allOf!=null)Z.allOf=$.allOf.map(UB);if($.definitions!=null)Z.definitions=Object.fromEntries(Object.entries($.definitions).map(([Y,G])=>[Y,UB(G)]));if(X.$defs!=null){let Y=Z;Y.$defs=Object.fromEntries(Object.entries(X.$defs).map(([G,J])=>[G,UB(J)]))}if($.type==="object"||$.properties!=null){if($.properties!=null)Z.properties=Object.fromEntries(Object.entries($.properties).map(([Y,G])=>[Y,UB(G)]));if(Z.additionalProperties=!1,$.required!=null)Z.required=$.required}if($.items!=null)Z.items=Array.isArray($.items)?$.items.map(UB):UB($.items);if(typeof $.format==="string"&&qY$.has($.format))Z.format=$.format;let Q=C34($);if(Q!=null)Z.description=Z.description==null?Q:`${Z.description}
|
|
1050
|
+
${Q}`;return Z}function C34($){let Z=V34.flatMap((X)=>{let Q=$[X];if(Q==null||Q===!1)return[];return`${_34(X)}: ${v34(Q)}`});if(typeof $.format==="string"&&!qY$.has($.format))Z.push(`format: ${$.format}`);return Z.length===0?void 0:`${Z.join("; ")}.`}function _34($){return $.replace(/[A-Z]/g,(Z)=>` ${Z.toLowerCase()}`)}function v34($){if(typeof $==="string")return $;return JSON.stringify($)}function f34($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function BY$($,Z,X){var Q;if($.type==="web_search_result_location")return{type:"source",sourceType:"url",id:X(),url:$.url,title:$.title,providerMetadata:{anthropic:{citedText:$.cited_text,encryptedIndex:$.encrypted_index}}};if($.type!=="page_location"&&$.type!=="char_location")return;let Y=Z[$.document_index];if(!Y)return;return{type:"source",sourceType:"document",id:X(),mediaType:Y.mediaType,title:(Q=$.document_title)!=null?Q:Y.title,filename:Y.filename,providerMetadata:{anthropic:$.type==="page_location"?{citedText:$.cited_text,startPageNumber:$.start_page_number,endPageNumber:$.end_page_number}:{citedText:$.cited_text,startCharIndex:$.start_char_index,endCharIndex:$.end_char_index}}}}function x34($){if($.includes("claude-opus-4-8")||$.includes("claude-opus-4-7")||$.includes("claude-fable-5"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,rejectsSamplingParameters:!0,isKnownModel:!0};else if($.includes("claude-sonnet-4-6")||$.includes("claude-opus-4-6"))return{maxOutputTokens:128000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-sonnet-4-5")||$.includes("claude-opus-4-5")||$.includes("claude-haiku-4-5"))return{maxOutputTokens:64000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-opus-4-1"))return{maxOutputTokens:32000,supportsStructuredOutput:!0,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-sonnet-4-"))return{maxOutputTokens:64000,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-opus-4-"))return{maxOutputTokens:32000,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else if($.includes("claude-3-haiku"))return{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!0};else return{maxOutputTokens:4096,supportsStructuredOutput:!1,rejectsSamplingParameters:!1,isKnownModel:!1}}function wY$($){if(!$)return!1;let Z=!1,X=!1;for(let Q of $){if("type"in Q&&(Q.type==="web_fetch_20260209"||Q.type==="web_search_20260209")){Z=!0;continue}if(Q.name==="code_execution"){X=!0;break}}return Z&&!X}function DY$($){return $?{appliedEdits:$.applied_edits.map((Z)=>{switch(Z.type){case"clear_tool_uses_20250919":return{type:Z.type,clearedToolUses:Z.cleared_tool_uses,clearedInputTokens:Z.cleared_input_tokens};case"clear_thinking_20251015":return{type:Z.type,clearedThinkingTurns:Z.cleared_thinking_turns,clearedInputTokens:Z.cleared_input_tokens};case"compact_20260112":return{type:Z.type}}}).filter((Z)=>Z!==void 0)}:null}function LY$($){if($==null)return;return{type:$.type,...$.category!=null?{category:$.category}:{},...$.explanation!=null?{explanation:$.explanation}:{},...$.recommended_model!=null?{recommendedModel:$.recommended_model}:{}}}function up($={}){var Z,X;let Q=(Z=xO(XK({settingValue:$.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?Z:"https://api.anthropic.com/v1",Y=(X=$.name)!=null?X:"anthropic.messages";if($.apiKey&&$.authToken)throw new vO({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let G=()=>{let K=$.authToken?{Authorization:`Bearer ${$.authToken}`}:{"x-api-key":Mx({apiKey:$.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return p4({"anthropic-version":"2023-06-01",...K,...$.headers},`ai-sdk/anthropic/${fJ4}`)},J=(K)=>{var H;return new b34(K,{provider:Y,baseURL:Q,headers:G,fetch:$.fetch,generateId:(H=$.generateId)!=null?H:f8,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},W=function(K){if(new.target)throw Error("The Anthropic model function cannot be called with the new keyword.");return J(K)};return W.specificationVersion="v3",W.languageModel=J,W.chat=J,W.messages=J,W.embeddingModel=(K)=>{throw new y5({modelId:K,modelType:"embeddingModel"})},W.textEmbeddingModel=W.embeddingModel,W.imageModel=(K)=>{throw new y5({modelId:K,modelType:"imageModel"})},W.tools=GW4,W}var fJ4="3.0.85",bJ4,KY$,EY$,xJ4,yJ4,gJ4,HY$,FY$,NY$=4,wp0=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl($,Z){let X=hJ4($);if(!X)return;if(!Z.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${Z.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>NY$){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${NY$} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return X}getWarnings(){return this.warnings}},uJ4,jY$,cJ4,lJ4,dJ4=($)=>{return lJ4($)},mJ4,iJ4,pJ4,nJ4=($={})=>{return pJ4($)},tJ4,oJ4,rJ4,aJ4,sJ4=($={})=>{return aJ4($)},eJ4,zY$,$34,Z34,X34=($={})=>{return Z34($)},Q34,Y34,G34,J34,W34=($={})=>{return J34($)},K34,PY$,H34,F34,N34=($={})=>{return F34($)},AY$,O34,B34,w34=($={})=>{return B34($)},TY$,D34,L34,E34=($={})=>{return L34($)},RY$,j34,z34,P34=($={})=>{return z34($)},IY$,A34,T34,R34=($={})=>{return T34($)},qY$,V34,b34=class{constructor($,Z){this.specificationVersion="v3";var X;this.modelId=$,this.config=Z,this.generateId=(X=Z.generateId)!=null?X:f8}supportsUrl($){return $.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let $=this.config.provider,Z=$.indexOf(".");return Z===-1?$:$.substring(0,Z)}get supportedUrls(){var $,Z,X;return(X=(Z=($=this.config).supportedUrls)==null?void 0:Z.call($))!=null?X:{}}async getArgs({userSuppliedBetas:$,prompt:Z,maxOutputTokens:X,temperature:Q,topP:Y,topK:G,frequencyPenalty:J,presencePenalty:W,stopSequences:K,responseFormat:H,seed:F,tools:N,toolChoice:U,providerOptions:O,stream:B}){var D,L,E,j,z,A,P,M,q,k;let C=[];if(J!=null)C.push({type:"unsupported",feature:"frequencyPenalty"});if(W!=null)C.push({type:"unsupported",feature:"presencePenalty"});if(F!=null)C.push({type:"unsupported",feature:"seed"});if(Q!=null&&Q>1)C.push({type:"unsupported",feature:"temperature",details:`${Q} exceeds anthropic maximum of 1.0. clamped to 1.0`}),Q=1;else if(Q!=null&&Q<0)C.push({type:"unsupported",feature:"temperature",details:`${Q} is below anthropic minimum of 0. clamped to 0`}),Q=0;if((H==null?void 0:H.type)==="json"){if(H.schema==null)C.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."})}let l=this.providerOptionsName,f=await t8({provider:"anthropic",providerOptions:O,schema:FY$}),x=l!=="anthropic"?await t8({provider:l,providerOptions:O,schema:FY$}):null,n=x!=null,u=Object.assign({},f!=null?f:{},x!=null?x:{}),{maxOutputTokens:a,supportsStructuredOutput:O0,rejectsSamplingParameters:B0,isKnownModel:e}=x34(this.modelId);if(B0){if(Q!=null)C.push({type:"unsupported",feature:"temperature",details:`temperature is not supported by ${this.modelId} and will be ignored`}),Q=void 0;if(G!=null)C.push({type:"unsupported",feature:"topK",details:`topK is not supported by ${this.modelId} and will be ignored`}),G=void 0;if(Y!=null)C.push({type:"unsupported",feature:"topP",details:`topP is not supported by ${this.modelId} and will be ignored`}),Y=void 0}let o=e||this.modelId.startsWith("claude-"),P0=((D=this.config.supportsNativeStructuredOutput)!=null?D:!0)&&O0,Y0=((L=this.config.supportsStrictTools)!=null?L:!0)&&O0,j0=(E=u==null?void 0:u.structuredOutputMode)!=null?E:"auto",x0=j0==="outputFormat"||j0==="auto"&&P0,V0=(H==null?void 0:H.type)==="json"&&H.schema!=null&&!x0?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:H.schema}:void 0,u0=u==null?void 0:u.contextManagement,Q0=new wp0,w0=N90({tools:N,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25","anthropic.advisor_20260301":"advisor"}}),{prompt:L0,betas:I0}=await M34({prompt:Z,sendReasoning:(j=u==null?void 0:u.sendReasoning)!=null?j:!0,warnings:C,cacheControlValidator:Q0,toolNameMapping:w0}),$0=(z=u==null?void 0:u.thinking)==null?void 0:z.type,X0=$0==="enabled"||$0==="adaptive",R0=$0==="enabled"?(A=u==null?void 0:u.thinking)==null?void 0:A.budgetTokens:void 0,G0=$0==="adaptive"?(P=u==null?void 0:u.thinking)==null?void 0:P.display:void 0,N0=X!=null?X:a,E1={model:this.modelId,max_tokens:N0,temperature:Q,top_k:G,top_p:Y,stop_sequences:K,...X0&&{thinking:{type:$0,...R0!=null&&{budget_tokens:R0},...G0!=null&&{display:G0}}},...((u==null?void 0:u.effort)||(u==null?void 0:u.taskBudget)||x0&&(H==null?void 0:H.type)==="json"&&H.schema!=null)&&{output_config:{...(u==null?void 0:u.effort)&&{effort:u.effort},...(u==null?void 0:u.taskBudget)&&{task_budget:{type:u.taskBudget.type,total:u.taskBudget.total,...u.taskBudget.remaining!=null&&{remaining:u.taskBudget.remaining}}},...x0&&(H==null?void 0:H.type)==="json"&&H.schema!=null&&{format:{type:"json_schema",schema:S34(H.schema)}}}},...(u==null?void 0:u.speed)&&{speed:u.speed},...(u==null?void 0:u.inferenceGeo)&&{inference_geo:u.inferenceGeo},...(u==null?void 0:u.fallbacks)&&u.fallbacks.length>0&&{fallbacks:u.fallbacks},...(u==null?void 0:u.cacheControl)&&{cache_control:u.cacheControl},...((M=u==null?void 0:u.metadata)==null?void 0:M.userId)!=null&&{metadata:{user_id:u.metadata.userId}},...(u==null?void 0:u.mcpServers)&&u.mcpServers.length>0&&{mcp_servers:u.mcpServers.map((k0)=>({type:k0.type,name:k0.name,url:k0.url,authorization_token:k0.authorizationToken,tool_configuration:k0.toolConfiguration?{allowed_tools:k0.toolConfiguration.allowedTools,enabled:k0.toolConfiguration.enabled}:void 0}))},...(u==null?void 0:u.container)&&{container:u.container.skills&&u.container.skills.length>0?{id:u.container.id,skills:u.container.skills.map((k0)=>({type:k0.type,skill_id:k0.skillId,version:k0.version}))}:u.container.id},system:L0.system,messages:L0.messages,...u0&&{context_management:{edits:u0.edits.map((k0)=>{let g1=k0.type;switch(g1){case"clear_tool_uses_20250919":return{type:k0.type,...k0.trigger!==void 0&&{trigger:k0.trigger},...k0.keep!==void 0&&{keep:k0.keep},...k0.clearAtLeast!==void 0&&{clear_at_least:k0.clearAtLeast},...k0.clearToolInputs!==void 0&&{clear_tool_inputs:k0.clearToolInputs},...k0.excludeTools!==void 0&&{exclude_tools:k0.excludeTools}};case"clear_thinking_20251015":return{type:k0.type,...k0.keep!==void 0&&{keep:k0.keep}};case"compact_20260112":return{type:k0.type,...k0.trigger!==void 0&&{trigger:k0.trigger},...k0.pauseAfterCompaction!==void 0&&{pause_after_compaction:k0.pauseAfterCompaction},...k0.instructions!==void 0&&{instructions:k0.instructions}};default:C.push({type:"other",message:`Unknown context management strategy: ${g1}`});return}}).filter((k0)=>k0!==void 0)}}};if(X0){if($0==="enabled"&&R0==null)C.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),E1.thinking={type:"enabled",budget_tokens:1024},R0=1024;if(E1.temperature!=null)E1.temperature=void 0,C.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"});if(G!=null)E1.top_k=void 0,C.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"});if(Y!=null)E1.top_p=void 0,C.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"});E1.max_tokens=N0+(R0!=null?R0:0)}else if(o&&Y!=null&&Q!=null)C.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),E1.top_p=void 0;if(e&&E1.max_tokens>a){if(X!=null)C.push({type:"unsupported",feature:"maxOutputTokens",details:`${E1.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${a} max output tokens. The max output tokens have been limited to ${a}.`});E1.max_tokens=a}if((u==null?void 0:u.mcpServers)&&u.mcpServers.length>0)I0.add("mcp-client-2025-04-04");if(u0){if(I0.add("context-management-2025-06-27"),u0.edits.some((k0)=>k0.type==="compact_20260112"))I0.add("compact-2026-01-12")}if((u==null?void 0:u.container)&&u.container.skills&&u.container.skills.length>0){if(I0.add("code-execution-2025-08-25"),I0.add("skills-2025-10-02"),I0.add("files-api-2025-04-14"),!(N==null?void 0:N.some((k0)=>k0.type==="provider"&&(k0.id==="anthropic.code_execution_20250825"||k0.id==="anthropic.code_execution_20260120"))))C.push({type:"other",message:"code execution tool is required when using skills"})}if(u==null?void 0:u.taskBudget)I0.add("task-budgets-2026-03-13");if((u==null?void 0:u.speed)==="fast")I0.add("fast-mode-2026-02-01");if((u==null?void 0:u.fallbacks)&&u.fallbacks.length>0)I0.add("server-side-fallback-2026-06-01");let n0=B&&((q=u==null?void 0:u.toolStreaming)!=null?q:!0),{tools:y0,toolChoice:i,toolWarnings:S0,betas:X1}=await U34(V0!=null?{tools:[...N!=null?N:[],V0],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:Q0,supportsStructuredOutput:!1,supportsStrictTools:Y0,defaultEagerInputStreaming:n0}:{tools:N!=null?N:[],toolChoice:U,disableParallelToolUse:u==null?void 0:u.disableParallelToolUse,cacheControlValidator:Q0,supportsStructuredOutput:P0,supportsStrictTools:Y0,defaultEagerInputStreaming:n0}),A1=Q0.getWarnings();return{args:{...E1,tools:y0,tool_choice:i,stream:B===!0?!0:void 0},warnings:[...C,...S0,...A1],betas:new Set([...I0,...X1,...$,...(k=u==null?void 0:u.anthropicBeta)!=null?k:[]]),usesJsonResponseTool:V0!=null,toolNameMapping:w0,providerOptionsName:l,usedCustomProviderKey:n}}async getHeaders({betas:$,headers:Z}){return t$(await v$(this.config.headers),Z,$.size>0?{"anthropic-beta":Array.from($).join(",")}:{})}async getBetasFromHeaders($){var Z,X;let Y=(Z=(await v$(this.config.headers))["anthropic-beta"])!=null?Z:"",G=(X=$==null?void 0:$["anthropic-beta"])!=null?X:"";return new Set([...Y.toLowerCase().split(","),...G.toLowerCase().split(",")].map((J)=>J.trim()).filter((J)=>J!==""))}buildRequestUrl($){var Z,X,Q;return(Q=(X=(Z=this.config).buildRequestUrl)==null?void 0:X.call(Z,this.config.baseURL,$))!=null?Q:`${this.config.baseURL}/messages`}transformRequestBody($,Z){var X,Q,Y;return(Y=(Q=(X=this.config).transformRequestBody)==null?void 0:Q.call(X,$,Z))!=null?Y:$}extractCitationDocuments($){let Z=(X)=>{var Q,Y;if(X.type!=="file")return!1;if(X.mediaType!=="application/pdf"&&X.mediaType!=="text/plain")return!1;let G=(Q=X.providerOptions)==null?void 0:Q.anthropic,J=G==null?void 0:G.citations;return(Y=J==null?void 0:J.enabled)!=null?Y:!1};return $.filter((X)=>X.role==="user").flatMap((X)=>X.content).filter(Z).map((X)=>{var Q;let Y=X;return{title:(Q=Y.filename)!=null?Q:"Untitled Document",filename:Y.filename,mediaType:Y.mediaType}})}async doGenerate($){var Z,X,Q,Y,G,J,W;let{args:K,warnings:H,betas:F,usesJsonResponseTool:N,toolNameMapping:U,providerOptionsName:O,usedCustomProviderKey:B}=await this.getArgs({...$,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders($.headers)}),D=[...this.extractCitationDocuments($.prompt)],L=wY$(K.tools),{responseHeaders:E,value:j,rawValue:z}=await K8({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:F,headers:$.headers}),body:this.transformRequestBody(K,F),failedResponseHandler:KY$,successfulResponseHandler:e$(xJ4),abortSignal:$.abortSignal,fetch:this.config.fetch}),A=[],P={},M={},q=!1;for(let k of j.content)switch(k.type){case"text":{if(!N){if(A.push({type:"text",text:k.text}),k.citations)for(let C of k.citations){let l=BY$(C,D,this.generateId);if(l)A.push(l)}}break}case"thinking":{A.push({type:"reasoning",text:k.thinking,providerMetadata:{anthropic:{signature:k.signature}}});break}case"redacted_thinking":{A.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:k.data}}});break}case"compaction":{A.push({type:"text",text:k.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(N&&k.name==="json")q=!0,A.push({type:"text",text:JSON.stringify(k.input)});else{let l=k.caller,f=l?{type:l.type,toolId:"tool_id"in l?l.tool_id:void 0}:void 0;A.push({type:"tool-call",toolCallId:k.id,toolName:k.name,input:JSON.stringify(k.input),...f&&{providerMetadata:{anthropic:{caller:f}}}})}break}case"server_tool_use":{if(k.name==="text_editor_code_execution"||k.name==="bash_code_execution")A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName("code_execution"),input:JSON.stringify({type:k.name,...k.input}),providerExecuted:!0,...L?{dynamic:!0}:{}});else if(k.name==="web_search"||k.name==="code_execution"||k.name==="web_fetch"){let C=k.name==="code_execution"&&k.input!=null&&typeof k.input==="object"&&"code"in k.input&&!("type"in k.input)?{type:"programmatic-tool-call",...k.input}:k.input;A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName(k.name),input:JSON.stringify(C),providerExecuted:!0,...L&&k.name==="code_execution"?{dynamic:!0}:{}})}else if(k.name==="tool_search_tool_regex"||k.name==="tool_search_tool_bm25")M[k.id]=k.name,A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName(k.name),input:JSON.stringify(k.input),providerExecuted:!0});else if(k.name==="advisor")A.push({type:"tool-call",toolCallId:k.id,toolName:U.toCustomToolName("advisor"),input:JSON.stringify(k.input),providerExecuted:!0});break}case"mcp_tool_use":{P[k.id]={type:"tool-call",toolCallId:k.id,toolName:k.name,input:JSON.stringify(k.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:k.server_name}}},A.push(P[k.id]);break}case"mcp_tool_result":{A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:P[k.tool_use_id].toolName,isError:k.is_error,result:k.content,dynamic:!0,providerMetadata:P[k.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{if(k.content.type==="web_fetch_result")D.push({title:(Z=k.content.content.title)!=null?Z:k.content.url,mediaType:k.content.content.source.media_type}),A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:k.content.url,retrievedAt:k.content.retrieved_at,content:{type:k.content.content.type,title:k.content.content.title,citations:k.content.content.citations,source:{type:k.content.content.source.type,mediaType:k.content.content.source.media_type,data:k.content.content.source.data}}}});else if(k.content.type==="web_fetch_tool_result_error")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:k.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(k.content)){A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_search"),result:k.content.map((C)=>{var l;return{url:C.url,title:C.title,pageAge:(l=C.page_age)!=null?l:null,encryptedContent:C.encrypted_content,type:C.type}})});for(let C of k.content)A.push({type:"source",sourceType:"url",id:this.generateId(),url:C.url,title:C.title,providerMetadata:{anthropic:{pageAge:(X=C.page_age)!=null?X:null}}})}else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:k.content.error_code}});break}case"code_execution_tool_result":{if(k.content.type==="code_execution_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:{type:k.content.type,stdout:k.content.stdout,stderr:k.content.stderr,return_code:k.content.return_code,content:(Q=k.content.content)!=null?Q:[]}});else if(k.content.type==="encrypted_code_execution_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:{type:k.content.type,encrypted_stdout:k.content.encrypted_stdout,stderr:k.content.stderr,return_code:k.content.return_code,content:(Y=k.content.content)!=null?Y:[]}});else if(k.content.type==="code_execution_tool_result_error")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:k.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName("code_execution"),result:k.content});break}case"tool_search_tool_result":{let C=M[k.tool_use_id];if(C==null){let l=U.toCustomToolName("tool_search_tool_bm25"),f=U.toCustomToolName("tool_search_tool_regex");if(l!=="tool_search_tool_bm25")C="tool_search_tool_bm25";else if(f!=="tool_search_tool_regex")C="tool_search_tool_regex";else C="tool_search_tool_regex"}if(k.content.type==="tool_search_tool_search_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName(C),result:k.content.tool_references.map((l)=>({type:l.type,toolName:l.tool_name}))});else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:U.toCustomToolName(C),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:k.content.error_code}});break}case"advisor_tool_result":{let C=U.toCustomToolName("advisor");if(k.content.type==="advisor_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:C,result:{type:"advisor_result",text:k.content.text}});else if(k.content.type==="advisor_redacted_result")A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:C,result:{type:"advisor_redacted_result",encryptedContent:k.content.encrypted_content}});else A.push({type:"tool-result",toolCallId:k.tool_use_id,toolName:C,isError:!0,result:{type:"advisor_tool_result_error",errorCode:k.content.error_code}});break}case"fallback":break}return{content:A,finishReason:{unified:Up0({finishReason:j.stop_reason,isJsonResponseFromTool:q}),raw:(G=j.stop_reason)!=null?G:void 0},usage:UY$({usage:j.usage}),request:{body:K},response:{id:(J=j.id)!=null?J:void 0,modelId:(W=j.model)!=null?W:void 0,headers:E,body:z},warnings:H,providerMetadata:(()=>{var k,C,l,f,x;let n=LY$(j.stop_details),u={usage:j.usage,cacheCreationInputTokens:(k=j.usage.cache_creation_input_tokens)!=null?k:null,stopSequence:(C=j.stop_sequence)!=null?C:null,...n!=null?{stopDetails:n}:{},iterations:j.usage.iterations?j.usage.iterations.map((O0)=>({type:O0.type,...O0.model!=null?{model:O0.model}:{},inputTokens:O0.input_tokens,outputTokens:O0.output_tokens,...O0.cache_creation_input_tokens?{cacheCreationInputTokens:O0.cache_creation_input_tokens}:{},...O0.cache_read_input_tokens?{cacheReadInputTokens:O0.cache_read_input_tokens}:{}})):null,container:j.container?{expiresAt:j.container.expires_at,id:j.container.id,skills:(f=(l=j.container.skills)==null?void 0:l.map((O0)=>({type:O0.type,skillId:O0.skill_id,version:O0.version})))!=null?f:null}:null,contextManagement:(x=DY$(j.context_management))!=null?x:null},a={anthropic:u};if(B&&O!=="anthropic")a[O]=u;return a})()}}async doStream($){var Z,X;let{args:Q,warnings:Y,betas:G,usesJsonResponseTool:J,toolNameMapping:W,providerOptionsName:K,usedCustomProviderKey:H}=await this.getArgs({...$,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders($.headers)}),F=[...this.extractCitationDocuments($.prompt)],N=wY$(Q.tools),U=this.buildRequestUrl(!0),{responseHeaders:O,value:B}=await K8({url:U,headers:await this.getHeaders({betas:G,headers:$.headers}),body:this.transformRequestBody(Q,G),failedResponseHandler:KY$,successfulResponseHandler:t7(yJ4),abortSignal:$.abortSignal,fetch:this.config.fetch}),D={unified:"other",raw:void 0},L={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},E={},j={},z={},A=null,P=void 0,M=null,q=null,k=void 0,C=null,l=!1,f=void 0,x=this.generateId,n=B.pipeThrough(new TransformStream({start(B0){B0.enqueue({type:"stream-start",warnings:Y})},transform(B0,e){var o,P0,Y0,j0,x0,V0,u0,Q0,w0,L0,I0,$0,X0,R0;if($.includeRawChunks)e.enqueue({type:"raw",rawValue:B0.rawValue});if(!B0.success){e.enqueue({type:"error",error:B0.error});return}let G0=B0.value;switch(G0.type){case"ping":return;case"content_block_start":{let N0=G0.content_block,E1=N0.type;if(E1==="fallback")return;switch(f=E1,E1){case"text":{if(J)return;E[G0.index]={type:"text"},e.enqueue({type:"text-start",id:String(G0.index)});return}case"thinking":{E[G0.index]={type:"reasoning"},e.enqueue({type:"reasoning-start",id:String(G0.index)});return}case"redacted_thinking":{E[G0.index]={type:"reasoning"},e.enqueue({type:"reasoning-start",id:String(G0.index),providerMetadata:{anthropic:{redactedData:N0.data}}});return}case"compaction":{E[G0.index]={type:"text"},e.enqueue({type:"text-start",id:String(G0.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(J&&N0.name==="json")l=!0,E[G0.index]={type:"text"},e.enqueue({type:"text-start",id:String(G0.index)});else{let y0=N0.caller,i=y0?{type:y0.type,toolId:"tool_id"in y0?y0.tool_id:void 0}:void 0,X1=N0.input&&Object.keys(N0.input).length>0?JSON.stringify(N0.input):"";E[G0.index]={type:"tool-call",toolCallId:N0.id,toolName:N0.name,input:X1,firstDelta:X1.length===0,...i&&{caller:i}},e.enqueue({type:"tool-input-start",id:N0.id,toolName:N0.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(N0.name)){let n0=N0.name==="text_editor_code_execution"||N0.name==="bash_code_execution"?"code_execution":N0.name,y0=W.toCustomToolName(n0),i=N0.input!=null&&typeof N0.input==="object"&&Object.keys(N0.input).length>0?JSON.stringify(N0.input):"";E[G0.index]={type:"tool-call",toolCallId:N0.id,toolName:y0,input:i,providerExecuted:!0,...N&&n0==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:n0},e.enqueue({type:"tool-input-start",id:N0.id,toolName:y0,providerExecuted:!0,...N&&n0==="code_execution"?{dynamic:!0}:{}})}else if(N0.name==="tool_search_tool_regex"||N0.name==="tool_search_tool_bm25"){z[N0.id]=N0.name;let n0=W.toCustomToolName(N0.name);E[G0.index]={type:"tool-call",toolCallId:N0.id,toolName:n0,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:N0.name},e.enqueue({type:"tool-input-start",id:N0.id,toolName:n0,providerExecuted:!0})}else if(N0.name==="advisor"){let n0=W.toCustomToolName("advisor");E[G0.index]={type:"tool-call",toolCallId:N0.id,toolName:n0,input:"{}",providerExecuted:!0,firstDelta:!0,providerToolName:N0.name},e.enqueue({type:"tool-input-start",id:N0.id,toolName:n0,providerExecuted:!0})}return}case"web_fetch_tool_result":{if(N0.content.type==="web_fetch_result")F.push({title:(o=N0.content.content.title)!=null?o:N0.content.url,mediaType:N0.content.content.source.media_type}),e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:N0.content.url,retrievedAt:N0.content.retrieved_at,content:{type:N0.content.content.type,title:N0.content.content.title,citations:N0.content.content.citations,source:{type:N0.content.content.source.type,mediaType:N0.content.content.source.media_type,data:N0.content.content.source.data}}}});else if(N0.content.type==="web_fetch_tool_result_error")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:N0.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(N0.content)){e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("web_search"),result:N0.content.map((n0)=>{var y0;return{url:n0.url,title:n0.title,pageAge:(y0=n0.page_age)!=null?y0:null,encryptedContent:n0.encrypted_content,type:n0.type}})});for(let n0 of N0.content)e.enqueue({type:"source",sourceType:"url",id:x(),url:n0.url,title:n0.title,providerMetadata:{anthropic:{pageAge:(P0=n0.page_age)!=null?P0:null}}})}else e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:N0.content.error_code}});return}case"code_execution_tool_result":{if(N0.content.type==="code_execution_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("code_execution"),result:{type:N0.content.type,stdout:N0.content.stdout,stderr:N0.content.stderr,return_code:N0.content.return_code,content:(Y0=N0.content.content)!=null?Y0:[]}});else if(N0.content.type==="encrypted_code_execution_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("code_execution"),result:{type:N0.content.type,encrypted_stdout:N0.content.encrypted_stdout,stderr:N0.content.stderr,return_code:N0.content.return_code,content:(j0=N0.content.content)!=null?j0:[]}});else if(N0.content.type==="code_execution_tool_result_error")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:N0.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName("code_execution"),result:N0.content});return}case"tool_search_tool_result":{let n0=z[N0.tool_use_id];if(n0==null){let y0=W.toCustomToolName("tool_search_tool_bm25"),i=W.toCustomToolName("tool_search_tool_regex");if(y0!=="tool_search_tool_bm25")n0="tool_search_tool_bm25";else if(i!=="tool_search_tool_regex")n0="tool_search_tool_regex";else n0="tool_search_tool_regex"}if(N0.content.type==="tool_search_tool_search_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName(n0),result:N0.content.tool_references.map((y0)=>({type:y0.type,toolName:y0.tool_name}))});else e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:W.toCustomToolName(n0),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:N0.content.error_code}});return}case"advisor_tool_result":{let n0=W.toCustomToolName("advisor");if(N0.content.type==="advisor_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:n0,result:{type:"advisor_result",text:N0.content.text}});else if(N0.content.type==="advisor_redacted_result")e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:n0,result:{type:"advisor_redacted_result",encryptedContent:N0.content.encrypted_content}});else e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:n0,isError:!0,result:{type:"advisor_tool_result_error",errorCode:N0.content.error_code}});return}case"mcp_tool_use":{j[N0.id]={type:"tool-call",toolCallId:N0.id,toolName:N0.name,input:JSON.stringify(N0.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:N0.server_name}}},e.enqueue(j[N0.id]);return}case"mcp_tool_result":{e.enqueue({type:"tool-result",toolCallId:N0.tool_use_id,toolName:j[N0.tool_use_id].toolName,isError:N0.is_error,result:N0.content,dynamic:!0,providerMetadata:j[N0.tool_use_id].providerMetadata});return}default:throw Error(`Unsupported content block type: ${E1}`)}}case"content_block_stop":{if(E[G0.index]!=null){let N0=E[G0.index];switch(N0.type){case"text":{e.enqueue({type:"text-end",id:String(G0.index)});break}case"reasoning":{e.enqueue({type:"reasoning-end",id:String(G0.index)});break}case"tool-call":if(!(J&&N0.toolName==="json")){e.enqueue({type:"tool-input-end",id:N0.toolCallId});let n0=N0.input===""?"{}":N0.input;if(N0.providerToolName==="code_execution")try{let y0=JSON.parse(n0);if(y0!=null&&typeof y0==="object"&&"code"in y0&&!("type"in y0))n0=JSON.stringify({type:"programmatic-tool-call",...y0})}catch(y0){}e.enqueue({type:"tool-call",toolCallId:N0.toolCallId,toolName:N0.toolName,input:n0,providerExecuted:N0.providerExecuted,...N&&N0.providerToolName==="code_execution"?{dynamic:!0}:{},...N0.caller&&{providerMetadata:{anthropic:{caller:N0.caller}}}})}break}delete E[G0.index]}f=void 0;return}case"content_block_delta":{let N0=G0.delta.type;switch(N0){case"text_delta":{if(J)return;e.enqueue({type:"text-delta",id:String(G0.index),delta:G0.delta.text});return}case"thinking_delta":{e.enqueue({type:"reasoning-delta",id:String(G0.index),delta:G0.delta.thinking});return}case"signature_delta":{if(f==="thinking")e.enqueue({type:"reasoning-delta",id:String(G0.index),delta:"",providerMetadata:{anthropic:{signature:G0.delta.signature}}});return}case"compaction_delta":{if(G0.delta.content!=null)e.enqueue({type:"text-delta",id:String(G0.index),delta:G0.delta.content});return}case"input_json_delta":{let E1=E[G0.index],n0=G0.delta.partial_json;if(n0.length===0)return;if(l){if((E1==null?void 0:E1.type)!=="text")return;e.enqueue({type:"text-delta",id:String(G0.index),delta:n0})}else{if((E1==null?void 0:E1.type)!=="tool-call")return;if(E1.firstDelta&&E1.providerToolName==="code_execution")n0=`{"type": "programmatic-tool-call",${n0.substring(1)}`;e.enqueue({type:"tool-input-delta",id:E1.toolCallId,delta:n0}),E1.input+=n0,E1.firstDelta=!1}return}case"citations_delta":{let E1=G0.delta.citation,n0=BY$(E1,F,x);if(n0)e.enqueue(n0);return}default:throw Error(`Unsupported delta type: ${N0}`)}}case"message_start":{if(L.input_tokens=G0.message.usage.input_tokens,L.cache_read_input_tokens=(x0=G0.message.usage.cache_read_input_tokens)!=null?x0:0,L.cache_creation_input_tokens=(V0=G0.message.usage.cache_creation_input_tokens)!=null?V0:0,P={...G0.message.usage},M=(u0=G0.message.usage.cache_creation_input_tokens)!=null?u0:null,G0.message.container!=null)C={expiresAt:G0.message.container.expires_at,id:G0.message.container.id,skills:null};if(G0.message.stop_reason!=null)D={unified:Up0({finishReason:G0.message.stop_reason,isJsonResponseFromTool:l}),raw:G0.message.stop_reason};if(e.enqueue({type:"response-metadata",id:(Q0=G0.message.id)!=null?Q0:void 0,modelId:(w0=G0.message.model)!=null?w0:void 0}),G0.message.content!=null)for(let N0=0;N0<G0.message.content.length;N0++){let E1=G0.message.content[N0];if(E1.type==="tool_use"){let n0=E1.caller,y0=n0?{type:n0.type,toolId:"tool_id"in n0?n0.tool_id:void 0}:void 0;e.enqueue({type:"tool-input-start",id:E1.id,toolName:E1.name});let i=JSON.stringify((L0=E1.input)!=null?L0:{});e.enqueue({type:"tool-input-delta",id:E1.id,delta:i}),e.enqueue({type:"tool-input-end",id:E1.id}),e.enqueue({type:"tool-call",toolCallId:E1.id,toolName:E1.name,input:i,...y0&&{providerMetadata:{anthropic:{caller:y0}}}})}}return}case"message_delta":{if(G0.usage.input_tokens!=null&&L.input_tokens!==G0.usage.input_tokens)L.input_tokens=G0.usage.input_tokens;if(L.output_tokens=G0.usage.output_tokens,G0.usage.cache_read_input_tokens!=null)L.cache_read_input_tokens=G0.usage.cache_read_input_tokens;if(G0.usage.cache_creation_input_tokens!=null)L.cache_creation_input_tokens=G0.usage.cache_creation_input_tokens,M=G0.usage.cache_creation_input_tokens;if(G0.usage.iterations!=null)L.iterations=G0.usage.iterations;if(D={unified:Up0({finishReason:G0.delta.stop_reason,isJsonResponseFromTool:l}),raw:(I0=G0.delta.stop_reason)!=null?I0:void 0},q=($0=G0.delta.stop_sequence)!=null?$0:null,k=LY$(G0.delta.stop_details),C=G0.delta.container!=null?{expiresAt:G0.delta.container.expires_at,id:G0.delta.container.id,skills:(R0=(X0=G0.delta.container.skills)==null?void 0:X0.map((N0)=>({type:N0.type,skillId:N0.skill_id,version:N0.version})))!=null?R0:null}:null,G0.context_management)A=DY$(G0.context_management);P={...P,...G0.usage};return}case"message_stop":{let N0={usage:P!=null?P:null,cacheCreationInputTokens:M,stopSequence:q,...k!=null?{stopDetails:k}:{},iterations:L.iterations?L.iterations.map((n0)=>({type:n0.type,...n0.model!=null?{model:n0.model}:{},inputTokens:n0.input_tokens,outputTokens:n0.output_tokens,...n0.cache_creation_input_tokens?{cacheCreationInputTokens:n0.cache_creation_input_tokens}:{},...n0.cache_read_input_tokens?{cacheReadInputTokens:n0.cache_read_input_tokens}:{}})):null,container:C,contextManagement:A},E1={anthropic:N0};if(H&&K!=="anthropic")E1[K]=N0;e.enqueue({type:"finish",finishReason:D,usage:UY$({usage:L,rawUsage:P}),providerMetadata:E1});return}case"error":{e.enqueue({type:"error",error:G0.error});return}default:throw Error(`Unsupported chunk type: ${G0}`)}}})),[u,a]=n.tee(),O0=u.getReader();try{await O0.read();let B0=await O0.read();if(((Z=B0.value)==null?void 0:Z.type)==="raw")B0=await O0.read();if(((X=B0.value)==null?void 0:X.type)==="error"){let e=B0.value.error;throw new Z4({message:e.message,url:U,requestBodyValues:Q,statusCode:e.type==="overloaded_error"?529:500,responseHeaders:O,responseBody:JSON.stringify(e),isRetryable:e.type==="overloaded_error"})}}finally{O0.cancel().catch(()=>{}),O0.releaseLock()}return{stream:a,request:{body:Q},response:{headers:O}}}},y34,g34,h34,u34,c34,l34,d34,m34,i34,p34,n34,t34,o34,r34,a34,s34,e34,$W4,ZW4,XW4,QW4,YW4=($={})=>{return QW4($)},GW4,TE9;var Dp0=w(()=>{r1();g0();r1();g0();g0();g0();r1();g0();g0();g0();g0();g0();g0();g0();r1();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();g0();bJ4=U0(()=>Z0(gp.object({type:gp.literal("error"),error:gp.object({type:gp.string(),message:gp.string()})}))),KY$=q5({errorSchema:bJ4,errorToMessage:($)=>$.error.message}),EY$=I.object({type:I.string(),category:I.string().nullish(),explanation:I.string().nullish(),recommended_model:I.string().nullish()}),xJ4=U0(()=>Z0(I.object({type:I.literal("message"),id:I.string().nullish(),model:I.string().nullish(),content:I.array(I.discriminatedUnion("type",[I.object({type:I.literal("text"),text:I.string(),citations:I.array(I.discriminatedUnion("type",[I.object({type:I.literal("web_search_result_location"),cited_text:I.string(),url:I.string(),title:I.string(),encrypted_index:I.string()}),I.object({type:I.literal("page_location"),cited_text:I.string(),document_index:I.number(),document_title:I.string().nullable(),start_page_number:I.number(),end_page_number:I.number()}),I.object({type:I.literal("char_location"),cited_text:I.string(),document_index:I.number(),document_title:I.string().nullable(),start_char_index:I.number(),end_char_index:I.number()})])).optional()}),I.object({type:I.literal("thinking"),thinking:I.string(),signature:I.string()}),I.object({type:I.literal("redacted_thinking"),data:I.string()}),I.object({type:I.literal("compaction"),content:I.string()}),I.object({type:I.literal("tool_use"),id:I.string(),name:I.string(),input:I.unknown(),caller:I.union([I.object({type:I.literal("code_execution_20250825"),tool_id:I.string()}),I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()}),I.object({type:I.literal("server_tool_use"),id:I.string(),name:I.string(),input:I.record(I.string(),I.unknown()).nullish(),caller:I.union([I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()}),I.object({type:I.literal("mcp_tool_use"),id:I.string(),name:I.string(),input:I.unknown(),server_name:I.string()}),I.object({type:I.literal("mcp_tool_result"),tool_use_id:I.string(),is_error:I.boolean(),content:I.array(I.union([I.string(),I.object({type:I.literal("text"),text:I.string()})]))}),I.object({type:I.literal("web_fetch_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("web_fetch_result"),url:I.string(),retrieved_at:I.string(),content:I.object({type:I.literal("document"),title:I.string().nullable(),citations:I.object({enabled:I.boolean()}).optional(),source:I.union([I.object({type:I.literal("base64"),media_type:I.literal("application/pdf"),data:I.string()}),I.object({type:I.literal("text"),media_type:I.literal("text/plain"),data:I.string()})])})}),I.object({type:I.literal("web_fetch_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("web_search_tool_result"),tool_use_id:I.string(),content:I.union([I.array(I.object({type:I.literal("web_search_result"),url:I.string(),title:I.string(),encrypted_content:I.string(),page_age:I.string().nullish()})),I.object({type:I.literal("web_search_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("code_execution_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("code_execution_result"),stdout:I.string(),stderr:I.string(),return_code:I.number(),content:I.array(I.object({type:I.literal("code_execution_output"),file_id:I.string()})).optional().default([])}),I.object({type:I.literal("encrypted_code_execution_result"),encrypted_stdout:I.string(),stderr:I.string(),return_code:I.number(),content:I.array(I.object({type:I.literal("code_execution_output"),file_id:I.string()})).optional().default([])}),I.object({type:I.literal("code_execution_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("bash_code_execution_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("bash_code_execution_result"),content:I.array(I.object({type:I.literal("bash_code_execution_output"),file_id:I.string()})),stdout:I.string(),stderr:I.string(),return_code:I.number()}),I.object({type:I.literal("bash_code_execution_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("text_editor_code_execution_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("text_editor_code_execution_tool_result_error"),error_code:I.string()}),I.object({type:I.literal("text_editor_code_execution_view_result"),content:I.string(),file_type:I.string(),num_lines:I.number().nullable(),start_line:I.number().nullable(),total_lines:I.number().nullable()}),I.object({type:I.literal("text_editor_code_execution_create_result"),is_file_update:I.boolean()}),I.object({type:I.literal("text_editor_code_execution_str_replace_result"),lines:I.array(I.string()).nullable(),new_lines:I.number().nullable(),new_start:I.number().nullable(),old_lines:I.number().nullable(),old_start:I.number().nullable()})])}),I.object({type:I.literal("tool_search_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("tool_search_tool_search_result"),tool_references:I.array(I.object({type:I.literal("tool_reference"),tool_name:I.string()}))}),I.object({type:I.literal("tool_search_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("advisor_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("advisor_result"),text:I.string()}),I.object({type:I.literal("advisor_redacted_result"),encrypted_content:I.string()}),I.object({type:I.literal("advisor_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("fallback")})])),stop_reason:I.string().nullish(),stop_sequence:I.string().nullish(),stop_details:EY$.nullish(),usage:I.looseObject({input_tokens:I.number(),output_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish(),iterations:I.array(I.object({type:I.union([I.literal("compaction"),I.literal("message"),I.literal("advisor_message"),I.literal("fallback_message")]),model:I.string().nullish(),input_tokens:I.number(),output_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish()})).nullish()}),container:I.object({expires_at:I.string(),id:I.string(),skills:I.array(I.object({type:I.union([I.literal("anthropic"),I.literal("custom")]),skill_id:I.string(),version:I.string()})).nullish()}).nullish(),context_management:I.object({applied_edits:I.array(I.union([I.object({type:I.literal("clear_tool_uses_20250919"),cleared_tool_uses:I.number(),cleared_input_tokens:I.number()}),I.object({type:I.literal("clear_thinking_20251015"),cleared_thinking_turns:I.number(),cleared_input_tokens:I.number()}),I.object({type:I.literal("compact_20260112")})]))}).nullish()}))),yJ4=U0(()=>Z0(I.discriminatedUnion("type",[I.object({type:I.literal("message_start"),message:I.object({id:I.string().nullish(),model:I.string().nullish(),role:I.string().nullish(),usage:I.looseObject({input_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish()}),content:I.array(I.discriminatedUnion("type",[I.object({type:I.literal("tool_use"),id:I.string(),name:I.string(),input:I.unknown(),caller:I.union([I.object({type:I.literal("code_execution_20250825"),tool_id:I.string()}),I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()})])).nullish(),stop_reason:I.string().nullish(),container:I.object({expires_at:I.string(),id:I.string()}).nullish()})}),I.object({type:I.literal("content_block_start"),index:I.number(),content_block:I.discriminatedUnion("type",[I.object({type:I.literal("text"),text:I.string()}),I.object({type:I.literal("thinking"),thinking:I.string()}),I.object({type:I.literal("tool_use"),id:I.string(),name:I.string(),input:I.record(I.string(),I.unknown()).optional(),caller:I.union([I.object({type:I.literal("code_execution_20250825"),tool_id:I.string()}),I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()}),I.object({type:I.literal("redacted_thinking"),data:I.string()}),I.object({type:I.literal("compaction"),content:I.string().nullish()}),I.object({type:I.literal("server_tool_use"),id:I.string(),name:I.string(),input:I.record(I.string(),I.unknown()).nullish(),caller:I.union([I.object({type:I.literal("code_execution_20260120"),tool_id:I.string()}),I.object({type:I.literal("direct")})]).optional()}),I.object({type:I.literal("mcp_tool_use"),id:I.string(),name:I.string(),input:I.unknown(),server_name:I.string()}),I.object({type:I.literal("mcp_tool_result"),tool_use_id:I.string(),is_error:I.boolean(),content:I.array(I.union([I.string(),I.object({type:I.literal("text"),text:I.string()})]))}),I.object({type:I.literal("web_fetch_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("web_fetch_result"),url:I.string(),retrieved_at:I.string(),content:I.object({type:I.literal("document"),title:I.string().nullable(),citations:I.object({enabled:I.boolean()}).optional(),source:I.union([I.object({type:I.literal("base64"),media_type:I.literal("application/pdf"),data:I.string()}),I.object({type:I.literal("text"),media_type:I.literal("text/plain"),data:I.string()})])})}),I.object({type:I.literal("web_fetch_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("web_search_tool_result"),tool_use_id:I.string(),content:I.union([I.array(I.object({type:I.literal("web_search_result"),url:I.string(),title:I.string(),encrypted_content:I.string(),page_age:I.string().nullish()})),I.object({type:I.literal("web_search_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("code_execution_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("code_execution_result"),stdout:I.string(),stderr:I.string(),return_code:I.number(),content:I.array(I.object({type:I.literal("code_execution_output"),file_id:I.string()})).optional().default([])}),I.object({type:I.literal("encrypted_code_execution_result"),encrypted_stdout:I.string(),stderr:I.string(),return_code:I.number(),content:I.array(I.object({type:I.literal("code_execution_output"),file_id:I.string()})).optional().default([])}),I.object({type:I.literal("code_execution_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("bash_code_execution_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("bash_code_execution_result"),content:I.array(I.object({type:I.literal("bash_code_execution_output"),file_id:I.string()})),stdout:I.string(),stderr:I.string(),return_code:I.number()}),I.object({type:I.literal("bash_code_execution_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("text_editor_code_execution_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("text_editor_code_execution_tool_result_error"),error_code:I.string()}),I.object({type:I.literal("text_editor_code_execution_view_result"),content:I.string(),file_type:I.string(),num_lines:I.number().nullable(),start_line:I.number().nullable(),total_lines:I.number().nullable()}),I.object({type:I.literal("text_editor_code_execution_create_result"),is_file_update:I.boolean()}),I.object({type:I.literal("text_editor_code_execution_str_replace_result"),lines:I.array(I.string()).nullable(),new_lines:I.number().nullable(),new_start:I.number().nullable(),old_lines:I.number().nullable(),old_start:I.number().nullable()})])}),I.object({type:I.literal("tool_search_tool_result"),tool_use_id:I.string(),content:I.union([I.object({type:I.literal("tool_search_tool_search_result"),tool_references:I.array(I.object({type:I.literal("tool_reference"),tool_name:I.string()}))}),I.object({type:I.literal("tool_search_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("advisor_tool_result"),tool_use_id:I.string(),content:I.discriminatedUnion("type",[I.object({type:I.literal("advisor_result"),text:I.string()}),I.object({type:I.literal("advisor_redacted_result"),encrypted_content:I.string()}),I.object({type:I.literal("advisor_tool_result_error"),error_code:I.string()})])}),I.object({type:I.literal("fallback")})])}),I.object({type:I.literal("content_block_delta"),index:I.number(),delta:I.discriminatedUnion("type",[I.object({type:I.literal("input_json_delta"),partial_json:I.string()}),I.object({type:I.literal("text_delta"),text:I.string()}),I.object({type:I.literal("thinking_delta"),thinking:I.string()}),I.object({type:I.literal("signature_delta"),signature:I.string()}),I.object({type:I.literal("compaction_delta"),content:I.string().nullish()}),I.object({type:I.literal("citations_delta"),citation:I.discriminatedUnion("type",[I.object({type:I.literal("web_search_result_location"),cited_text:I.string(),url:I.string(),title:I.string(),encrypted_index:I.string()}),I.object({type:I.literal("page_location"),cited_text:I.string(),document_index:I.number(),document_title:I.string().nullable(),start_page_number:I.number(),end_page_number:I.number()}),I.object({type:I.literal("char_location"),cited_text:I.string(),document_index:I.number(),document_title:I.string().nullable(),start_char_index:I.number(),end_char_index:I.number()})])})])}),I.object({type:I.literal("content_block_stop"),index:I.number()}),I.object({type:I.literal("error"),error:I.object({type:I.string(),message:I.string()})}),I.object({type:I.literal("message_delta"),delta:I.object({stop_reason:I.string().nullish(),stop_sequence:I.string().nullish(),stop_details:EY$.nullish(),container:I.object({expires_at:I.string(),id:I.string(),skills:I.array(I.object({type:I.union([I.literal("anthropic"),I.literal("custom")]),skill_id:I.string(),version:I.string()})).nullish()}).nullish()}),usage:I.looseObject({input_tokens:I.number().nullish(),output_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish(),iterations:I.array(I.object({type:I.union([I.literal("compaction"),I.literal("message"),I.literal("advisor_message"),I.literal("fallback_message")]),model:I.string().nullish(),input_tokens:I.number(),output_tokens:I.number(),cache_creation_input_tokens:I.number().nullish(),cache_read_input_tokens:I.number().nullish()})).nullish()}),context_management:I.object({applied_edits:I.array(I.union([I.object({type:I.literal("clear_tool_uses_20250919"),cleared_tool_uses:I.number(),cleared_input_tokens:I.number()}),I.object({type:I.literal("clear_thinking_20251015"),cleared_thinking_turns:I.number(),cleared_input_tokens:I.number()}),I.object({type:I.literal("compact_20260112")})]))}).nullish()}),I.object({type:I.literal("message_stop")}),I.object({type:I.literal("ping")})]))),gJ4=U0(()=>Z0(I.object({signature:I.string().optional(),redactedData:I.string().optional()}))),HY$=K1.object({citations:K1.object({enabled:K1.boolean()}).optional(),title:K1.string().optional(),context:K1.string().optional()}),FY$=K1.object({sendReasoning:K1.boolean().optional(),structuredOutputMode:K1.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:K1.discriminatedUnion("type",[K1.object({type:K1.literal("adaptive"),display:K1.enum(["omitted","summarized"]).optional()}),K1.object({type:K1.literal("enabled"),budgetTokens:K1.number().optional()}),K1.object({type:K1.literal("disabled")})]).optional(),disableParallelToolUse:K1.boolean().optional(),cacheControl:K1.object({type:K1.literal("ephemeral"),ttl:K1.union([K1.literal("5m"),K1.literal("1h")]).optional()}).optional(),metadata:K1.object({userId:K1.string().optional()}).optional(),mcpServers:K1.array(K1.object({type:K1.literal("url"),name:K1.string(),url:K1.string(),authorizationToken:K1.string().nullish(),toolConfiguration:K1.object({enabled:K1.boolean().nullish(),allowedTools:K1.array(K1.string()).nullish()}).nullish()})).optional(),container:K1.object({id:K1.string().optional(),skills:K1.array(K1.object({type:K1.union([K1.literal("anthropic"),K1.literal("custom")]),skillId:K1.string(),version:K1.string().optional()})).optional()}).optional(),toolStreaming:K1.boolean().optional(),effort:K1.enum(["low","medium","high","xhigh","max"]).optional(),taskBudget:K1.object({type:K1.literal("tokens"),total:K1.number().int().min(20000),remaining:K1.number().int().min(0).optional()}).optional(),speed:K1.enum(["fast","standard"]).optional(),inferenceGeo:K1.enum(["us","global"]).optional(),fallbacks:K1.array(K1.object({model:K1.string(),max_tokens:K1.number().int().optional(),thinking:K1.record(K1.string(),K1.unknown()).optional(),output_config:K1.record(K1.string(),K1.unknown()).optional(),speed:K1.enum(["fast","standard"]).optional()})).optional(),anthropicBeta:K1.array(K1.string()).optional(),contextManagement:K1.object({edits:K1.array(K1.discriminatedUnion("type",[K1.object({type:K1.literal("clear_tool_uses_20250919"),trigger:K1.discriminatedUnion("type",[K1.object({type:K1.literal("input_tokens"),value:K1.number()}),K1.object({type:K1.literal("tool_uses"),value:K1.number()})]).optional(),keep:K1.object({type:K1.literal("tool_uses"),value:K1.number()}).optional(),clearAtLeast:K1.object({type:K1.literal("input_tokens"),value:K1.number()}).optional(),clearToolInputs:K1.boolean().optional(),excludeTools:K1.array(K1.string()).optional()}),K1.object({type:K1.literal("clear_thinking_20251015"),keep:K1.union([K1.literal("all"),K1.object({type:K1.literal("thinking_turns"),value:K1.number()})]).optional()}),K1.object({type:K1.literal("compact_20260112"),trigger:K1.object({type:K1.literal("input_tokens"),value:K1.number()}).optional(),pauseAfterCompaction:K1.boolean().optional(),instructions:K1.string().optional()})]))}).optional()});uJ4=U0(()=>Z0(WZ.object({model:WZ.string(),maxUses:WZ.number().optional(),caching:WZ.object({type:WZ.literal("ephemeral"),ttl:WZ.union([WZ.literal("5m"),WZ.literal("1h")])}).optional()}))),jY$=U0(()=>Z0(WZ.discriminatedUnion("type",[WZ.object({type:WZ.literal("advisor_result"),text:WZ.string()}),WZ.object({type:WZ.literal("advisor_redacted_result"),encryptedContent:WZ.string()}),WZ.object({type:WZ.literal("advisor_tool_result_error"),errorCode:WZ.string()})]))),cJ4=U0(()=>Z0(WZ.object({}).strict())),lJ4=o$({id:"anthropic.advisor_20260301",inputSchema:cJ4,outputSchema:jY$,supportsDeferredResults:!0}),mJ4=U0(()=>Z0(nG.object({maxCharacters:nG.number().optional()}))),iJ4=U0(()=>Z0(nG.object({command:nG.enum(["view","create","str_replace","insert"]),path:nG.string(),file_text:nG.string().optional(),insert_line:nG.number().int().optional(),new_str:nG.string().optional(),insert_text:nG.string().optional(),old_str:nG.string().optional(),view_range:nG.array(nG.number().int()).optional()}))),pJ4=S4({id:"anthropic.text_editor_20250728",inputSchema:iJ4}),tJ4=U0(()=>Z0(T9.object({maxUses:T9.number().optional(),allowedDomains:T9.array(T9.string()).optional(),blockedDomains:T9.array(T9.string()).optional(),userLocation:T9.object({type:T9.literal("approximate"),city:T9.string().optional(),region:T9.string().optional(),country:T9.string().optional(),timezone:T9.string().optional()}).optional()}))),oJ4=U0(()=>Z0(T9.array(T9.object({url:T9.string(),title:T9.string().nullable(),pageAge:T9.string().nullable(),encryptedContent:T9.string(),type:T9.literal("web_search_result")})))),rJ4=U0(()=>Z0(T9.object({query:T9.string()}))),aJ4=o$({id:"anthropic.web_search_20260209",inputSchema:rJ4,outputSchema:oJ4,supportsDeferredResults:!0}),eJ4=U0(()=>Z0(R9.object({maxUses:R9.number().optional(),allowedDomains:R9.array(R9.string()).optional(),blockedDomains:R9.array(R9.string()).optional(),userLocation:R9.object({type:R9.literal("approximate"),city:R9.string().optional(),region:R9.string().optional(),country:R9.string().optional(),timezone:R9.string().optional()}).optional()}))),zY$=U0(()=>Z0(R9.array(R9.object({url:R9.string(),title:R9.string().nullable(),pageAge:R9.string().nullable(),encryptedContent:R9.string(),type:R9.literal("web_search_result")})))),$34=U0(()=>Z0(R9.object({query:R9.string()}))),Z34=o$({id:"anthropic.web_search_20250305",inputSchema:$34,outputSchema:zY$,supportsDeferredResults:!0}),Q34=U0(()=>Z0(j6.object({maxUses:j6.number().optional(),allowedDomains:j6.array(j6.string()).optional(),blockedDomains:j6.array(j6.string()).optional(),citations:j6.object({enabled:j6.boolean()}).optional(),maxContentTokens:j6.number().optional()}))),Y34=U0(()=>Z0(j6.object({type:j6.literal("web_fetch_result"),url:j6.string(),content:j6.object({type:j6.literal("document"),title:j6.string().nullable(),citations:j6.object({enabled:j6.boolean()}).optional(),source:j6.union([j6.object({type:j6.literal("base64"),mediaType:j6.literal("application/pdf"),data:j6.string()}),j6.object({type:j6.literal("text"),mediaType:j6.literal("text/plain"),data:j6.string()})])}),retrievedAt:j6.string().nullable()}))),G34=U0(()=>Z0(j6.object({url:j6.string()}))),J34=o$({id:"anthropic.web_fetch_20260209",inputSchema:G34,outputSchema:Y34,supportsDeferredResults:!0}),K34=U0(()=>Z0(z6.object({maxUses:z6.number().optional(),allowedDomains:z6.array(z6.string()).optional(),blockedDomains:z6.array(z6.string()).optional(),citations:z6.object({enabled:z6.boolean()}).optional(),maxContentTokens:z6.number().optional()}))),PY$=U0(()=>Z0(z6.object({type:z6.literal("web_fetch_result"),url:z6.string(),content:z6.object({type:z6.literal("document"),title:z6.string().nullable(),citations:z6.object({enabled:z6.boolean()}).optional(),source:z6.union([z6.object({type:z6.literal("base64"),mediaType:z6.literal("application/pdf"),data:z6.string()}),z6.object({type:z6.literal("text"),mediaType:z6.literal("text/plain"),data:z6.string()})])}),retrievedAt:z6.string().nullable()}))),H34=U0(()=>Z0(z6.object({url:z6.string()}))),F34=o$({id:"anthropic.web_fetch_20250910",inputSchema:H34,outputSchema:PY$,supportsDeferredResults:!0});AY$=U0(()=>Z0(v3.object({type:v3.literal("code_execution_result"),stdout:v3.string(),stderr:v3.string(),return_code:v3.number(),content:v3.array(v3.object({type:v3.literal("code_execution_output"),file_id:v3.string()})).optional().default([])}))),O34=U0(()=>Z0(v3.object({code:v3.string()}))),B34=o$({id:"anthropic.code_execution_20250522",inputSchema:O34,outputSchema:AY$}),TY$=U0(()=>Z0(e1.discriminatedUnion("type",[e1.object({type:e1.literal("code_execution_result"),stdout:e1.string(),stderr:e1.string(),return_code:e1.number(),content:e1.array(e1.object({type:e1.literal("code_execution_output"),file_id:e1.string()})).optional().default([])}),e1.object({type:e1.literal("bash_code_execution_result"),content:e1.array(e1.object({type:e1.literal("bash_code_execution_output"),file_id:e1.string()})),stdout:e1.string(),stderr:e1.string(),return_code:e1.number()}),e1.object({type:e1.literal("bash_code_execution_tool_result_error"),error_code:e1.string()}),e1.object({type:e1.literal("text_editor_code_execution_tool_result_error"),error_code:e1.string()}),e1.object({type:e1.literal("text_editor_code_execution_view_result"),content:e1.string(),file_type:e1.string(),num_lines:e1.number().nullable(),start_line:e1.number().nullable(),total_lines:e1.number().nullable()}),e1.object({type:e1.literal("text_editor_code_execution_create_result"),is_file_update:e1.boolean()}),e1.object({type:e1.literal("text_editor_code_execution_str_replace_result"),lines:e1.array(e1.string()).nullable(),new_lines:e1.number().nullable(),new_start:e1.number().nullable(),old_lines:e1.number().nullable(),old_start:e1.number().nullable()})]))),D34=U0(()=>Z0(e1.discriminatedUnion("type",[e1.object({type:e1.literal("programmatic-tool-call"),code:e1.string()}),e1.object({type:e1.literal("bash_code_execution"),command:e1.string()}),e1.discriminatedUnion("command",[e1.object({type:e1.literal("text_editor_code_execution"),command:e1.literal("view"),path:e1.string()}),e1.object({type:e1.literal("text_editor_code_execution"),command:e1.literal("create"),path:e1.string(),file_text:e1.string().nullish()}),e1.object({type:e1.literal("text_editor_code_execution"),command:e1.literal("str_replace"),path:e1.string(),old_str:e1.string(),new_str:e1.string()})])]))),L34=o$({id:"anthropic.code_execution_20250825",inputSchema:D34,outputSchema:TY$,supportsDeferredResults:!0}),RY$=U0(()=>Z0(f1.discriminatedUnion("type",[f1.object({type:f1.literal("code_execution_result"),stdout:f1.string(),stderr:f1.string(),return_code:f1.number(),content:f1.array(f1.object({type:f1.literal("code_execution_output"),file_id:f1.string()})).optional().default([])}),f1.object({type:f1.literal("encrypted_code_execution_result"),encrypted_stdout:f1.string(),stderr:f1.string(),return_code:f1.number(),content:f1.array(f1.object({type:f1.literal("code_execution_output"),file_id:f1.string()})).optional().default([])}),f1.object({type:f1.literal("bash_code_execution_result"),content:f1.array(f1.object({type:f1.literal("bash_code_execution_output"),file_id:f1.string()})),stdout:f1.string(),stderr:f1.string(),return_code:f1.number()}),f1.object({type:f1.literal("bash_code_execution_tool_result_error"),error_code:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution_tool_result_error"),error_code:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution_view_result"),content:f1.string(),file_type:f1.string(),num_lines:f1.number().nullable(),start_line:f1.number().nullable(),total_lines:f1.number().nullable()}),f1.object({type:f1.literal("text_editor_code_execution_create_result"),is_file_update:f1.boolean()}),f1.object({type:f1.literal("text_editor_code_execution_str_replace_result"),lines:f1.array(f1.string()).nullable(),new_lines:f1.number().nullable(),new_start:f1.number().nullable(),old_lines:f1.number().nullable(),old_start:f1.number().nullable()})]))),j34=U0(()=>Z0(f1.discriminatedUnion("type",[f1.object({type:f1.literal("programmatic-tool-call"),code:f1.string()}),f1.object({type:f1.literal("bash_code_execution"),command:f1.string()}),f1.discriminatedUnion("command",[f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("view"),path:f1.string()}),f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("create"),path:f1.string(),file_text:f1.string().nullish()}),f1.object({type:f1.literal("text_editor_code_execution"),command:f1.literal("str_replace"),path:f1.string(),old_str:f1.string(),new_str:f1.string()})])]))),z34=o$({id:"anthropic.code_execution_20260120",inputSchema:j34,outputSchema:RY$,supportsDeferredResults:!0}),IY$=U0(()=>Z0(hS.array(hS.object({type:hS.literal("tool_reference"),toolName:hS.string()})))),A34=U0(()=>Z0(hS.object({pattern:hS.string(),limit:hS.number().optional()}))),T34=o$({id:"anthropic.tool_search_regex_20251119",inputSchema:A34,outputSchema:IY$,supportsDeferredResults:!0});qY$=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),V34=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","minItems","maxItems","uniqueItems","minProperties","maxProperties","not"];y34=U0(()=>Z0(Op0.object({command:Op0.string(),restart:Op0.boolean().optional()}))),g34=S4({id:"anthropic.bash_20241022",inputSchema:y34}),h34=U0(()=>Z0(Bp0.object({command:Bp0.string(),restart:Bp0.boolean().optional()}))),u34=S4({id:"anthropic.bash_20250124",inputSchema:h34}),c34=U0(()=>Z0(hp.object({action:hp.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:hp.array(hp.number().int()).optional(),text:hp.string().optional()}))),l34=S4({id:"anthropic.computer_20241022",inputSchema:c34}),d34=U0(()=>Z0(pG.object({action:pG.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:pG.tuple([pG.number().int(),pG.number().int()]).optional(),duration:pG.number().optional(),scroll_amount:pG.number().optional(),scroll_direction:pG.enum(["up","down","left","right"]).optional(),start_coordinate:pG.tuple([pG.number().int(),pG.number().int()]).optional(),text:pG.string().optional()}))),m34=S4({id:"anthropic.computer_20250124",inputSchema:d34}),i34=U0(()=>Z0(F7.object({action:F7.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:F7.tuple([F7.number().int(),F7.number().int()]).optional(),duration:F7.number().optional(),region:F7.tuple([F7.number().int(),F7.number().int(),F7.number().int(),F7.number().int()]).optional(),scroll_amount:F7.number().optional(),scroll_direction:F7.enum(["up","down","left","right"]).optional(),start_coordinate:F7.tuple([F7.number().int(),F7.number().int()]).optional(),text:F7.string().optional()}))),p34=S4({id:"anthropic.computer_20251124",inputSchema:i34}),n34=U0(()=>Z0(S6.discriminatedUnion("command",[S6.object({command:S6.literal("view"),path:S6.string(),view_range:S6.tuple([S6.number(),S6.number()]).optional()}),S6.object({command:S6.literal("create"),path:S6.string(),file_text:S6.string()}),S6.object({command:S6.literal("str_replace"),path:S6.string(),old_str:S6.string(),new_str:S6.string()}),S6.object({command:S6.literal("insert"),path:S6.string(),insert_line:S6.number(),insert_text:S6.string()}),S6.object({command:S6.literal("delete"),path:S6.string()}),S6.object({command:S6.literal("rename"),old_path:S6.string(),new_path:S6.string()})]))),t34=S4({id:"anthropic.memory_20250818",inputSchema:n34}),o34=U0(()=>Z0(DK.object({command:DK.enum(["view","create","str_replace","insert","undo_edit"]),path:DK.string(),file_text:DK.string().optional(),insert_line:DK.number().int().optional(),new_str:DK.string().optional(),insert_text:DK.string().optional(),old_str:DK.string().optional(),view_range:DK.array(DK.number().int()).optional()}))),r34=S4({id:"anthropic.text_editor_20241022",inputSchema:o34}),a34=U0(()=>Z0(LK.object({command:LK.enum(["view","create","str_replace","insert","undo_edit"]),path:LK.string(),file_text:LK.string().optional(),insert_line:LK.number().int().optional(),new_str:LK.string().optional(),insert_text:LK.string().optional(),old_str:LK.string().optional(),view_range:LK.array(LK.number().int()).optional()}))),s34=S4({id:"anthropic.text_editor_20250124",inputSchema:a34}),e34=U0(()=>Z0(EK.object({command:EK.enum(["view","create","str_replace","insert"]),path:EK.string(),file_text:EK.string().optional(),insert_line:EK.number().int().optional(),new_str:EK.string().optional(),insert_text:EK.string().optional(),old_str:EK.string().optional(),view_range:EK.array(EK.number().int()).optional()}))),$W4=S4({id:"anthropic.text_editor_20250429",inputSchema:e34}),ZW4=U0(()=>Z0(uS.array(uS.object({type:uS.literal("tool_reference"),toolName:uS.string()})))),XW4=U0(()=>Z0(uS.object({query:uS.string(),limit:uS.number().optional()}))),QW4=o$({id:"anthropic.tool_search_bm25_20251119",inputSchema:XW4,outputSchema:ZW4,supportsDeferredResults:!0}),GW4={advisor_20260301:dJ4,bash_20241022:g34,bash_20250124:u34,codeExecution_20250522:w34,codeExecution_20250825:E34,codeExecution_20260120:P34,computer_20241022:l34,computer_20250124:m34,computer_20251124:p34,memory_20250818:t34,textEditor_20241022:r34,textEditor_20250124:s34,textEditor_20250429:$W4,textEditor_20250728:nJ4,webFetch_20250910:N34,webFetch_20260209:W34,webSearch_20250305:X34,webSearch_20260209:sJ4,toolSearchRegex_20251119:R34,toolSearchBm25_20251119:YW4};TE9=up()});import{z as vF}from"zod/v4";import{z as cp}from"zod/v4";import{z as $X}from"zod/v4";import{z as h0}from"zod/v4";import{z as W6}from"zod/v4";import{z as Hy}from"zod/v4";import{z as CW4}from"zod/v4";import{z as lp}from"zod/v4";import{z as xW4}from"zod/v4";import{z as cS}from"zod/v4";import{z as uW4}from"zod/v4";import{z as Lp0}from"zod/v4";import{z as lS}from"zod/v4";import{z as Z9}from"zod/v4";import{z as F0}from"zod/v4";import{z as m1}from"zod/v4";function kY$($){var Z,X,Q,Y;if($==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let G=(Z=$.promptTokenCount)!=null?Z:0,J=(X=$.candidatesTokenCount)!=null?X:0,W=(Q=$.cachedContentTokenCount)!=null?Q:0,K=(Y=$.thoughtsTokenCount)!=null?Y:0;return{inputTokens:{total:G,noCache:G-W,cacheRead:W,cacheWrite:void 0},outputTokens:{total:J+K,text:J,reasoning:K},raw:$}}function f3($,Z=!0){if($==null)return;if(OW4($)){if(Z)return;if(typeof $==="object"&&$.description)return{type:"object",description:$.description};return{type:"object"}}if(typeof $==="boolean")return{type:"boolean",properties:{}};let{type:X,description:Q,required:Y,properties:G,items:J,allOf:W,anyOf:K,oneOf:H,format:F,const:N,minLength:U,enum:O}=$,B={};if(Q)B.description=Q;if(Y)B.required=Y;if(F)B.format=F;if(N!==void 0)B.enum=[N];if(X)if(Array.isArray(X)){let D=X.includes("null"),L=X.filter((E)=>E!=="null");if(L.length===0)B.type="null";else if(B.anyOf=L.map((E)=>({type:E})),D)B.nullable=!0}else B.type=X;if(O!==void 0)B.enum=O;if(G!=null)B.properties=Object.entries(G).reduce((D,[L,E])=>{return D[L]=f3(E,!1),D},{});if(J)B.items=Array.isArray(J)?J.map((D)=>f3(D,!1)):f3(J,!1);if(W)B.allOf=W.map((D)=>f3(D,!1));if(K)if(K.some((D)=>typeof D==="object"&&(D==null?void 0:D.type)==="null")){let D=K.filter((L)=>!(typeof L==="object"&&(L==null?void 0:L.type)==="null"));if(D.length===1){let L=f3(D[0],!1);if(typeof L==="object")B.nullable=!0,Object.assign(B,L)}else B.anyOf=D.map((L)=>f3(L,!1)),B.nullable=!0}else B.anyOf=K.map((D)=>f3(D,!1));if(H)B.oneOf=H.map((D)=>f3(D,!1));if(U!==void 0)B.minLength=U;return B}function OW4($){return $!=null&&typeof $==="object"&&$.type==="object"&&($.properties==null||Object.keys($.properties).length===0)&&!$.additionalProperties}function VY$($,Z){let X=[Z,"google","googleVertex","vertex"].filter((Q,Y,G)=>{return G.indexOf(Q)===Y});for(let Q of X){let Y=$==null?void 0:$[Q];if(Y!=null)return Y}}function DW4($){let Z=wW4.exec($);if(Z==null)return;return{mediaType:Z[1],data:Z[2]}}function LW4($){let Z=DW4($);if(Z==null)return;return{inlineData:{mimeType:Z.mediaType,data:Z.data}}}function EW4($,Z,X,Q){let Y=[],G=[];for(let J of X)switch(J.type){case"text":{G.push(J.text);break}case"image-data":case"file-data":{Y.push({inlineData:{mimeType:J.mediaType,data:J.data}});break}case"image-url":case"file-url":{let W=LW4(J.url);if(W!=null)Y.push(W);else G.push(JSON.stringify(J));break}default:{G.push(JSON.stringify(J));break}}$.push({functionResponse:{...Q!=null?{id:Q}:{},name:Z,response:{name:Z,content:G.length>0?G.join(`
|
|
1051
1051
|
`):"Tool executed successfully."},...Y.length>0?{parts:Y}:{}}})}function jW4($,Z,X,Q){for(let Y of X)switch(Y.type){case"text":$.push({functionResponse:{...Q!=null?{id:Q}:{},name:Z,response:{name:Z,content:Y.text}}});break;case"image-data":$.push({inlineData:{mimeType:String(Y.mediaType),data:String(Y.data)}},{text:"Tool executed successfully and returned this image as a response"});break;default:$.push({text:JSON.stringify(Y)});break}}function zW4($,Z){var X,Q,Y,G,J;let W=[],K=[],H=!0,F=(X=Z==null?void 0:Z.isGemmaModel)!=null?X:!1,N=(Q=Z==null?void 0:Z.isGemini3Model)!=null?Q:!1,U=(Y=Z==null?void 0:Z.providerOptionsName)!=null?Y:"google",O=(G=Z==null?void 0:Z.supportsFunctionResponseParts)!=null?G:!0,B=Z==null?void 0:Z.onWarning,D=!1,L=[],E=(j)=>{return L.push(j),D=!0,BW4};for(let{role:j,content:z}of $)switch(j){case"system":{if(!H)throw new V4({functionality:"system messages are only supported at the beginning of the conversation"});W.push({text:z});break}case"user":{H=!1;let A=[];for(let P of z)switch(P.type){case"text":{A.push({text:P.text});break}case"file":{let M=P.mediaType==="image/*"?"image/jpeg":P.mediaType;A.push(P.data instanceof URL?{fileData:{mimeType:M,fileUri:P.data.toString()}}:{inlineData:{mimeType:M,data:YZ(P.data)}});break}}K.push({role:"user",parts:A});break}case"assistant":{H=!1,K.push({role:"model",parts:z.map((A)=>{let P=VY$(A.providerOptions,U),M=(P==null?void 0:P.thoughtSignature)!=null?String(P.thoughtSignature):void 0;switch(A.type){case"text":return A.text.length===0?void 0:{text:A.text,thoughtSignature:M};case"reasoning":return A.text.length===0?void 0:{text:A.text,thought:!0,thoughtSignature:M};case"file":{if(A.data instanceof URL)throw new V4({functionality:"File data URLs in assistant messages are not supported"});return{inlineData:{mimeType:A.mediaType,data:YZ(A.data)},...(P==null?void 0:P.thought)===!0?{thought:!0}:{},thoughtSignature:M}}case"tool-call":{let q=(P==null?void 0:P.serverToolCallId)!=null?String(P.serverToolCallId):void 0,k=(P==null?void 0:P.serverToolType)!=null?String(P.serverToolType):void 0,C=M!=null?M:N?E(A.toolName):void 0;if(q&&k)return{toolCall:{toolType:k,args:typeof A.input==="string"?JSON.parse(A.input):A.input,id:q},thoughtSignature:C};return{functionCall:{...A.toolCallId!=null?{id:A.toolCallId}:{},name:A.toolName,args:A.input},thoughtSignature:C}}case"tool-result":{let q=(P==null?void 0:P.serverToolCallId)!=null?String(P.serverToolCallId):void 0,k=(P==null?void 0:P.serverToolType)!=null?String(P.serverToolType):void 0;if(q&&k)return{toolResponse:{toolType:k,response:A.output.type==="json"?A.output.value:{},id:q},thoughtSignature:M};return}}}).filter((A)=>A!==void 0)});break}case"tool":{H=!1;let A=[];for(let P of z){if(P.type==="tool-approval-response")continue;let M=VY$(P.providerOptions,U),q=(M==null?void 0:M.serverToolCallId)!=null?String(M.serverToolCallId):void 0,k=(M==null?void 0:M.serverToolType)!=null?String(M.serverToolType):void 0;if(q&&k){let l=(M==null?void 0:M.thoughtSignature)!=null?String(M.thoughtSignature):void 0;if(K.length>0){let f=K[K.length-1];if(f.role==="model"){f.parts.push({toolResponse:{toolType:k,response:P.output.type==="json"?P.output.value:{},id:q},thoughtSignature:l});continue}}}let C=P.output;if(C.type==="content")if(O)EW4(A,P.toolName,C.value,P.toolCallId);else jW4(A,P.toolName,C.value,P.toolCallId);else A.push({functionResponse:{...P.toolCallId!=null?{id:P.toolCallId}:{},name:P.toolName,response:{name:P.toolName,content:C.type==="execution-denied"?(J=C.reason)!=null?J:"Tool execution denied.":C.value}}})}K.push({role:"user",parts:A});break}}if(F&&W.length>0&&K.length>0&&K[0].role==="user"){let j=W.map((z)=>z.text).join(`
|
|
1052
1052
|
|
|
1053
1053
|
`);K[0].parts.unshift({text:j+`
|
|
@@ -2783,7 +2783,7 @@ Respond with the structured verdict and a short reason.`,wy$;var Ly$=w(()=>{_4()
|
|
|
2783
2783
|
${G.join(`
|
|
2784
2784
|
`)}`:Y}function dY6($){let Z=new Set;for(let X of $)for(let Q of X.split(`
|
|
2785
2785
|
`)){let Y=Q.trim();if(/^Co-authored-by:\s/i.test(Y))Z.add(Y)}return[...Z]}var xY6=200,yY6=12,gY6=300,N91=3;var U91=w(()=>{R_();_P0()});function iY6($){if(!$||$.includes(".."))return!1;return mY6.test($)}function Xg$($){let Z=typeof $.__resolveType==="string"?$.__resolveType:null;if(!Z||!iY6(Z))return null;let{__resolveType:X,...Q}=$;return{resolveType:Z,payload:Q}}function Qg$($,Z){return`${$.replace(/\/+$/,"")}/deco/invoke/${Z}`}var mY6;var Yg$=w(()=>{mY6=/^[\w./@-]+$/});function O91($){let Z;try{Z=new URL($)}catch{return null}if(!Z.hostname.endsWith(".localhost"))return null;let X=Z.host;return Z.hostname="127.0.0.1",{url:Z.toString(),hostHeader:X}}function sr($,Z){let X=$?.githubRepo;if(!X?.owner||!X?.name)return null;if(!X.connectionId)return X;if(!Z.includes(X.connectionId))return null;return X}async function Gg$($,Z,X,Q){if(!Q.connectionId)throw new q_("Push requires a connected GitHub account. Connect mcp-github for this project and restart the sandbox.");let Y=$.organization?.id;if(!Y)throw new q_(fZ);await iO({ctx:$,connectionId:Q.connectionId,organizationId:Y,forceRefresh:!0,onLegacyMintError:(F)=>{let N=F instanceof Error?F.message:fZ;throw new q_(N)}});let{cloneUrl:G,gitUserName:J,gitUserEmail:W}=await pO(Q.connectionId,Q.owner,Q.name,$.db,$.vault).catch((F)=>{let{code:N,message:U}=t8$(F instanceof Error?F.message:String(F));throw N?new q_(U):F}),K=ch($),H=await Z.proxyDaemonRequest(X,"/_sandbox/config",{method:"PUT",headers:new Headers({"content-type":"application/json"}),body:JSON.stringify({git:{repository:{cloneUrl:G},identity:{userName:J,userEmail:W}},...K?{operator:K}:{}})});if(!H.ok){let F=await FB(H,pY6).catch(()=>H.statusText);throw Error(`Failed to refresh sandbox git credentials (${H.status}): ${F}`)}}var pY6=10485760,q_;var B91=w(()=>{R3();PP0();vp();vd0();gx();q_=class q_ extends Error{constructor($){super($);this.name="GitPushAuthError"}}});function tY6($){let Z=$.startsWith("thread:")?$.slice(7):$;if(!Z||Z.length>255||Z.includes("..")||Z.startsWith("/")||Z.endsWith("/")||Z.endsWith(".lock")||!nY6.test(Z))throw Error(`Invalid branch name: ${$}`)}function M_($){return AbortSignal.any([$.req.raw.signal,AbortSignal.timeout(rY6)])}function aY6($,Z,X){let Q=B5($)[Z]?.[X];return!!Q&&Object.keys(AY(Q)).length>0}function k_($){let{runner:Z}=$.get("vmClaim");if(!Z)return $.json({error:"No sandbox runner configured"},503);return Z}async function ph($){let{virtualMcpMetadata:Z,connectionIds:X}=$.get("vmClaim"),Q=$.var.studioContext,Y=sr(Z,X);if(!Y)throw new Q6(404,"AUTH","repo","Project has no GitHub repository");let G=t(Q);return AP0(Q,G.id,Y)}function w91($,Z){if(Z instanceof Q6){let Q=Z.status===404?404:Z.status===409||Z.status===422?409:502;return $.json({error:Z.message},Q,m5)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},502,m5)}async function Kg$($){try{let Z=await ph($),X=await vP0(Z,$.get("vmClaim").branch);return $.json(X,200,m5)}catch(Z){return w91($,Z)}}function er($,Z){let Q=(xP0.get($)??Promise.resolve()).catch(()=>{}).then(Z),Y=Q.catch(()=>{});return xP0.set($,Y),Y.finally(()=>{if(xP0.get($)===Y)xP0.delete($)}),Q}async function dZ($,Z,X){if($.get("vmClaim").fastPreview)return $.json({error:"sandbox not found: Fast Preview projects are sandbox-less"},404,m5);let Q=k_($);if(Q instanceof Response)return Q;let{claimName:Y,userId:G,projectRef:J}=$.get("vmClaim"),W=X?.method??"POST",K=null,H=new Headers;if(X?.jsonBody!==void 0)K=X.jsonBody,H.set("content-type","application/json");else if(X?.forwardJsonBody)K=await $.req.text(),H.set("content-type","application/json");let F=X?.signal,N={method:W,headers:H,body:K,...F?{signal:F}:{}},U=async()=>{let O=await Q.proxyDaemonRequest(Y,Z,N);if(X?.map404to410&&O.status===404){try{await O.body?.cancel()}catch{}if(await Q.adoptLiveClaim?.({userId:G,projectRef:J},Y))O=await Q.proxyDaemonRequest(Y,Z,N);if(O.status===404){try{await O.body?.cancel()}catch{}return new Response(JSON.stringify({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."}),{status:410,headers:{"content-type":"application/json",...m5}})}}let B=await O.text(),D=X?.redactRepoDirUnlessDesktop&&Q.kind!=="user-desktop"?eY6(B):B,L=O.headers.get("content-type")??"application/json";return new Response(D,{status:O.status,headers:{"content-type":L,...m5}})};try{if(F){let O=U();return O.catch(()=>{}),await Promise.race([O,new Promise((D,L)=>{if(F.aborted)return L(F.reason);F.addEventListener("abort",()=>L(F.reason),{once:!0})})])}return await U()}catch(O){let B=O instanceof Error?O.message:String(O);return $.json({error:`Daemon unreachable: ${B}`},502)}}function eY6($){try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&"repoDir"in Z)return JSON.stringify({...Z,repoDir:null})}catch{}return $}async function yP0($,Z,X,Q="GET",Y){let G=await $.proxyDaemonRequest(Z,X,{method:Q,headers:new Headers,body:null});if(G.status===404&&Y){try{await G.body?.cancel()}catch{}if(await $.adoptLiveClaim?.(Y,Z))G=await $.proxyDaemonRequest(Z,X,{method:Q,headers:new Headers,body:null})}if(G.status===404){try{await G.body?.cancel()}catch{}throw Error("SANDBOX_GONE")}let J=await G.text();if(!G.ok){let W=`Daemon error (${G.status})`;try{W=JSON.parse(J).error??W}catch{}throw Error(W)}return JSON.parse(J)}function $G6($){return Hg$.includes($)}var nY6,Jg$=524288,oY6=65536,rY6=1e4,Wg$=2000,sY6,xP0,m5,Hg$,Fg$=()=>{let $=new U1;$.use("/:virtualMcpId/:branch/*",sY6),$.post("/:virtualMcpId/:branch/write",(X)=>dZ(X,"/_sandbox/write",{forwardJsonBody:!0,signal:M_(X)})),$.post("/:virtualMcpId/:branch/unlink",(X)=>dZ(X,"/_sandbox/unlink",{forwardJsonBody:!0,signal:M_(X)})),$.post("/:virtualMcpId/:branch/mkdir",(X)=>dZ(X,"/_sandbox/mkdir",{forwardJsonBody:!0,signal:M_(X)})),$.post("/:virtualMcpId/:branch/rename",(X)=>dZ(X,"/_sandbox/rename",{forwardJsonBody:!0,signal:M_(X)})),$.post("/:virtualMcpId/:branch/read",(X)=>dZ(X,"/_sandbox/read",{forwardJsonBody:!0,signal:M_(X)})),$.post("/:virtualMcpId/:branch/glob",(X)=>dZ(X,"/_sandbox/glob",{forwardJsonBody:!0,signal:M_(X)})),$.post("/:virtualMcpId/:branch/grep",(X)=>dZ(X,"/_sandbox/grep",{forwardJsonBody:!0,signal:M_(X)})),$.post("/:virtualMcpId/:branch/exec/:script",async(X)=>{let Q=X.req.param("script");if(!Q)return X.json({error:"missing script name"},400);return dZ(X,`/_sandbox/exec/${encodeURIComponent(Q)}`)}),$.post("/:virtualMcpId/:branch/exec/:script/kill",async(X)=>{let Q=X.req.param("script");if(!Q)return X.json({error:"missing script name"},400);return dZ(X,`/_sandbox/exec/${encodeURIComponent(Q)}/kill`)}),$.get("/:virtualMcpId/:branch/config",(X)=>dZ(X,"/_sandbox/config",{method:"GET",map404to410:!0,redactRepoDirUnlessDesktop:!0})),$.put("/:virtualMcpId/:branch/config",(X)=>dZ(X,"/_sandbox/config",{method:"PUT",forwardJsonBody:!0,map404to410:!0})),$.post("/:virtualMcpId/:branch/setup/:step",async(X)=>{let Q=X.req.param("step");if(!Q||!$G6(Q))return X.json({error:`step must be one of: ${Hg$.join(", ")}`},400);if(Q==="start"){let Y=X.get("vmClaim");if(Y.runner){let G=t(X.var.studioContext),J=Xy(Y.virtualMcpMetadata);try{await kO0({ctx:X.var.studioContext,runner:Y.runner,handle:Y.claimName,orgId:G.id,userId:Y.callerUserId,entries:J})}catch(W){let K=W instanceof Error?W.message:String(W);return X.json({error:`Failed to push env to daemon: ${K}`},502)}}}return dZ(X,`/_sandbox/setup/${Q}`,{signal:X.req.raw.signal,map404to410:!0})}),$.get("/:virtualMcpId/:branch/events",(X)=>{let Q=X.get("vmClaim");if(!Q.runner)return PN(X,async(Y)=>{await Y.writeSSE({event:"phase",data:JSON.stringify({kind:"failed",reason:"unknown",message:"No sandbox runner configured on this studio instance."})})});return Hy$(X,{ctx:X.var.studioContext,claimName:Q.claimName,runner:Q.runner,virtualMcpId:Q.virtualMcpId,branch:Q.branch,userId:Q.userId,projectRef:Q.projectRef,virtualMcpMetadata:Q.virtualMcpMetadata})}),$.get("/:virtualMcpId/:branch/git/status",(X)=>{if(X.get("vmClaim").fastPreview)return Kg$(X);return Z(X)});let Z=(X)=>dZ(X,"/_sandbox/git/status",{method:"GET",map404to410:!0,signal:AbortSignal.any([X.req.raw.signal,AbortSignal.timeout(Wg$)])});return $.post("/:virtualMcpId/:branch/git/status",(X)=>{if(X.get("vmClaim").fastPreview)return Kg$(X);return dZ(X,"/_sandbox/git/status",{map404to410:!0,signal:AbortSignal.any([X.req.raw.signal,AbortSignal.timeout(Wg$)])})}),$.post("/:virtualMcpId/:branch/git/diff",async(X)=>{let Q=X.get("vmClaim");if(Q.fastPreview)try{let Y=await X.req.json().catch(()=>({})),G=await ph(X),J=await fP0(G,Q.branch,Y.base);return X.json(J,200,m5)}catch(Y){return w91(X,Y)}return dZ(X,"/_sandbox/git/diff",{forwardJsonBody:!0,map404to410:!0})}),$.post("/:virtualMcpId/:branch/git/publish",async(X)=>{if(X.get("vmClaim").fastPreview)return X.json({ok:!0},200,m5);let Q=k_(X);if(Q instanceof Response)return Q;let{claimName:Y,virtualMcpMetadata:G,connectionIds:J}=X.get("vmClaim"),W=X.var.studioContext;return er(Y,async()=>{try{await t51(W,Q,Y);let K=sr(G,J);if(K)await Gg$(W,Q,Y,K)}catch(K){if(K instanceof q_)return X.json({error:K.message},403,m5);let H=K instanceof Error?K.message:String(K);return X.json({error:H},502,m5)}return dZ(X,"/_sandbox/git/publish",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/discard",async(X)=>{let Q=X.get("vmClaim");if(Q.fastPreview)return er(Q.claimName,async()=>{let Y=await X.req.json().catch(()=>({})),G=Array.isArray(Y.filepaths)?Y.filepaths.filter((J)=>typeof J==="string"):[];if(G.length===0)return X.json({error:"filepaths is required"},400,m5);try{let J=await ph(X);return await Zg$(J,Q.branch,G),X.json({ok:!0},200,m5)}catch(J){let W=J instanceof Q6&&J.status===409?409:502,K=J instanceof Error?J.message:String(J);return X.json({error:K},W,m5)}});return er(Q.claimName,()=>dZ(X,"/_sandbox/git/discard",{forwardJsonBody:!0,map404to410:!0}))}),$.post("/:virtualMcpId/:branch/git/rebase",async(X)=>{let Q=X.get("vmClaim");if(Q.fastPreview)return er(Q.claimName,async()=>{try{let W=await X.req.json().catch(()=>({})),K=await ph(X),H=W.base??await K.getDefaultBranch();return await bP0(K,Q.branch,H),X.json({ok:!0},200,m5)}catch(W){return w91(X,W)}});let Y=k_(X);if(Y instanceof Response)return Y;let{claimName:G}=X.get("vmClaim"),J=X.var.studioContext;return er(G,async()=>{try{await t51(J,Y,G)}catch(W){let K=W instanceof Error?W.message:String(W);return X.json({error:K},502,m5)}return dZ(X,"/_sandbox/git/rebase",{forwardJsonBody:!0,map404to410:!0})})}),$.post("/:virtualMcpId/:branch/git/suggest-commit",q9({maxSize:Jg$,onError:(X)=>X.json({error:"Payload too large"},413,m5)}),async(X)=>{let Q=X.get("vmClaim"),Y=null;if(!Q.fastPreview){let H=k_(X);if(H instanceof Response)return H;Y=H}let{claimName:G,userId:J,projectRef:W}=Q,K=X.var.studioContext;try{let H=await X.req.json().catch(()=>({})),F=H.status,N=H.diff,U=N!=null&&typeof N.diffs==="object"&&N.diffs!==null,[O,B]=a51(F)&&U?[F,N]:Y?await Promise.all([yP0(Y,G,"/_sandbox/git/status","GET",{userId:J,projectRef:W}),yP0(Y,G,"/_sandbox/git/diff","GET",{userId:J,projectRef:W})]):await(async()=>{let L=await ph(X);return Promise.all([vP0(L,Q.branch),fP0(L,Q.branch)])})(),D=await By$(K,O,B);return X.json(D,200,m5)}catch(H){let F=H instanceof Error?H.message:String(H);if(F==="SANDBOX_GONE")return X.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,m5);return X.json({error:F},502,m5)}}),$.post("/:virtualMcpId/:branch/git/judge-review",q9({maxSize:Jg$,onError:(X)=>X.json({error:"Payload too large"},413,m5)}),async(X)=>{let Q=X.get("vmClaim"),Y=null;if(!Q.fastPreview){let H=k_(X);if(H instanceof Response)return H;Y=H}let{claimName:G,userId:J,projectRef:W}=Q,K=X.var.studioContext;try{let H=await X.req.json().catch(()=>({})),F=H.status,N=H.diff,U=N!=null&&typeof N.diffs==="object"&&N.diffs!==null,[O,B]=a51(F)&&U?[F,N]:Y?await Promise.all([yP0(Y,G,"/_sandbox/git/status","GET",{userId:J,projectRef:W}),yP0(Y,G,"/_sandbox/git/diff","GET",{userId:J,projectRef:W})]):await(async()=>{let L=await ph(X);return Promise.all([vP0(L,Q.branch),fP0(L,Q.branch)])})(),D=await Dy$(K,O,B,typeof H.language==="string"?H.language:void 0);return X.json(D,200,m5)}catch(H){let F=H instanceof Error?H.message:String(H);if(F==="SANDBOX_GONE")return X.json({error:"Sandbox handle is gone. The sandbox needs to be re-provisioned."},410,m5);return X.json({error:F},502,m5)}}),$.get("/:virtualMcpId/:branch/preview-fetch",async(X)=>{let Q=k_(X);if(Q instanceof Response)return Q;let{claimName:Y}=X.get("vmClaim"),G=X.req.query("path");if(!G||!G.startsWith("/")||G.startsWith("//")||G.includes("..")||G.includes("\\"))return X.json({error:"Path not allowed"},403);let J;try{J=await Q.getPreviewUrl(Y)}catch{return X.json({error:"Preview not available"},502)}if(!J)return X.json({error:"Preview not available"},502);let W=J.replace(/\/+$/,""),K=O91(`${W}${G}`),H;try{H=await fetch(K?.url??`${W}${G}`,{...K?{headers:{host:K.hostHeader}}:{}})}catch{return X.json({error:"Preview unreachable"},502)}let F;try{F=await H.text()}catch{return X.json({error:"Preview unreachable"},502)}return new Response(F,{status:H.status,headers:{"content-type":H.headers.get("content-type")??"application/json"}})}),$.post("/:virtualMcpId/:branch/preview-invoke",q9({maxSize:oY6,onError:(X)=>X.json({error:"Payload too large"},413)}),async(X)=>{let Q=k_(X);if(Q instanceof Response)return Q;let{claimName:Y}=X.get("vmClaim"),G;try{G=await Q.getPreviewUrl(Y)}catch{return X.json({error:"Preview not available"},502)}if(!G)return X.json({error:"Preview not available"},502);let J;try{J=await X.req.json()}catch{return X.json({error:"Invalid JSON body"},400)}if(!J||typeof J!=="object"||Array.isArray(J))return X.json({error:"Invalid JSON body"},400);let W=Xg$(J);if(!W)return X.json({error:"Invalid or missing __resolveType"},400);let K=Qg$(G,W.resolveType),H=O91(K),F;try{F=await fetch(H?.url??K,{method:"POST",headers:{"content-type":"application/json",...H?{host:H.hostHeader}:{}},body:JSON.stringify(W.payload),signal:AbortSignal.timeout(30000)})}catch{return X.json({error:"Preview unreachable"},502)}let N;try{N=await F.text()}catch{return X.json({error:"Preview unreachable"},502)}return new Response(N,{status:F.status,headers:{"content-type":F.headers.get("content-type")??"application/json"}})}),$};var Ng$=w(()=>{P8();UN();uh();n51();PF();Wy$();S3();dX();U8();kB0();JB();Ky$();Fy$();Zp0();Cp();$91();Ly$();Q91();R_();U91();Yg$();B91();nY6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;sY6=zP0(async($,Z)=>{let X=$.var.studioContext;try{r(X)}catch{return $.json({error:"Unauthorized"},401)}let Q=J1(X);if(!Q)return $.json({error:"Unauthorized"},401);let Y;try{Y=t(X)}catch{return $.json({error:"Organization scope required"},403)}let G=$.req.param("virtualMcpId"),J=$.req.param("branch");if(!G||!J)return $.json({error:"virtualMcpId and branch are required"},400);try{tY6(J)}catch(O){let B=O instanceof Error?O.message:String(O);return $.json({error:B},400)}let W=await X.storage.virtualMcps.findById(G);if(!W||W.organization_id!==Y.id)return $.json({error:"Virtual MCP not found"},404);let K=ai({orgId:Y.id,virtualMcpId:G,branch:J}),H=await CF(X,J,Q),F=Jy$({userId:H,projectRef:K}),N=W.metadata??null;if(FW$(N).fastPreviewCapability&&!aY6(N,H,J))return $.set("vmClaim",{claimName:F,callerUserId:Q,runner:null,virtualMcpId:G,branch:J,userId:H,projectRef:K,virtualMcpMetadata:N,connectionIds:W.connections?.map((O)=>O.connection_id)??[],fastPreview:!0}),Z();let U;try{U=(await oX(X,{userId:H,branch:J,virtualMcpMetadata:N})).provider}catch{U=null}if(!U)return $.json({error:"No sandbox runner found"},404);return $.set("vmClaim",{claimName:F,callerUserId:Q,runner:U,virtualMcpId:G,branch:J,userId:H,projectRef:K,virtualMcpMetadata:N,connectionIds:W.connections?.map((O)=>O.connection_id)??[]}),Z()});xP0=new Map;m5={"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache"};Hg$=["clone","install","start"]});function Ug$($,Z,X){let Q=D91.get($);if(!Q)Q={pending:null,running:!1},D91.set($,Q);if(!Q.pending)Q.pending={set:new Map,del:new Set,deps:Z,resolvers:[],rejecters:[]};let Y=Q.pending;Y.deps=Z;for(let[J,W]of Object.entries(X.set??{}))Y.set.set(J,W),Y.del.delete(J);for(let J of X.delete??[])Y.del.add(J),Y.set.delete(J);let G=new Promise((J,W)=>{Y.resolvers.push(J),Y.rejecters.push(W)});if(!Q.running)XG6($,Q);return G}async function XG6($,Z){Z.running=!0;try{while(Z.pending){let X=Z.pending;Z.pending=null;try{let Q=await QG6(X);for(let Y of X.resolvers)Y(Q)}catch(Q){for(let Y of X.rejecters)Y(Q)}}}finally{if(Z.running=!1,!Z.pending)D91.delete($)}}async function QG6($){let{client:Z,branch:X,packagePath:Q}=$.deps;for(let Y=0;;Y++){let G=await ar(Z,X),J=await Z.getCommitTreeSha(G),W=await Z.getTreeRecursive(J),K=H91(W,Q),H=[],F=new Map(K.map((B)=>[B.path,{stem:B.stem,sha:B.sha}]));for(let[B,D]of $.set){let L=F91(K,B),E=`${JSON.stringify(D,null,2)}
|
|
2786
|
-
`,j=await Z.createBlob(E);await ey$(Z.owner,Z.repo,j,E);let z=L[0]??`${CP0(Q)}/${Y91(B)}.json`;H.push({path:z,mode:"100644",type:"blob",sha:j});let A=z.slice(z.lastIndexOf("/")+1,-5);F.set(z,{stem:A,sha:j,content:E});for(let P of L.slice(1))H.push({path:P,mode:"100644",type:"blob",sha:null}),F.delete(P)}for(let B of $.del)for(let D of F91(K,B))H.push({path:D,mode:"100644",type:"blob",sha:null}),F.delete(D);if(H.length===0)return G;let N=Q?`${Q}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(W.some((B)=>B.type==="blob"&&B.path===N)){let B=await Promise.all([...F.values()].map(async(j)=>({stem:j.stem,content:j.content??await Z.getBlobText(j.sha)}))),{decofile:D,skipped:L}=nr(B);if(L.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:`${Z.owner}/${Z.repo}`,branch:X,packagePath:Q,blocks:L.map((j)=>j.key)});let E=await Z.createBlob(D);H.push({path:N,mode:"100644",type:"blob",sha:E})}let U=await Z.createTree(J,H),O=await Z.createCommit({message:YG6($),treeSha:U,parentShas:[G]});try{return await Z.updateRef(X,O),O}catch(B){if(!(B instanceof Q6&&B.status===422)||Y>=ZG6-1)throw B;await q$(pZ(2000,200,Y,2,0.5))}}}function YG6($){let Z=(Y)=>{let G=Y.slice(0,3).join(", ");return Y.length>3?`${G} (+${Y.length-3} more)`:G},X=[];if($.set.size>0)X.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)X.push(`delete ${Z([...$.del])}`);let Q=`chore(decofile): ${X.join("; ")}`;return Rd0(Q,$.deps.coAuthor)}var ZG6=3,D91;var Og$=w(()=>{zO0();RP0();u4();R_();_P0();D91=new Map});import{createHmac as Bg$,randomBytes as GG6,timingSafeEqual as JG6}from"crypto";function wg$(){if(gP0)return gP0;let $;try{let Z=b0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return gP0=$?Buffer.from($):GG6(32),gP0}function L91($){let Z=$.nowMs??Date.now(),X={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+WG6)/1000)},Q=Buffer.from(JSON.stringify(X)).toString("base64url"),Y=Bg$("sha256",wg$()).update(Q).digest("base64url");return`${Q}.${Y}`}function Dg$($,Z){let X=$.indexOf(".");if(X<0)return!1;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(Bg$("sha256",wg$()).update(Q).digest("base64url"));if(Y.length!==G.length||!JG6(Y,G))return!1;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return!1}let W=Math.floor((Z.nowMs??Date.now())/1000);return J.o===Z.organizationId&&J.m===Z.virtualMcpId&&J.b===Z.branch&&typeof J.e==="number"&&J.e>=W}var WG6=21600000,gP0=null;var Lg$=w(()=>{T$()});import{z as nh}from"zod";function HG6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&KG6.test($)}function jg$($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function hP0($){let Z=$.get("decofileScope");return AP0($.var.studioContext,Z.organizationId,Z.githubRepo)}function uP0($,Z){if(Z instanceof Q6){let Q=Z.status===404?404:Z.status===409?409:Z.status===422?409:502;return $.json({error:Z.message},Q)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},500)}function zg$(){let $=new U1;return $.use("/:virtualMcpId/:branch",Eg$),$.use("/:virtualMcpId/:branch/*",Eg$),$.get("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await hP0(Z),Y=await $g$(Q,X.branch,X.packagePath,{createBranchIfMissing:!!X.userId}),G={ETag:`"${Y.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${Y.sha}"`)return Z.body(null,304,G);if(!X.userId)return Z.body(Y.decofile,200,{...G,"content-type":"application/json"});let J=L91({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.body(`{"version":${JSON.stringify(Y.sha)},"token":${JSON.stringify(J)},"apiHost":${JSON.stringify(jg$(Z))},"decofile":${Y.decofile}}`,200,{...G,"content-type":"application/json"})}catch(Q){return uP0(Z,Q)}}),$.patch("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope"),Q=Z.var.studioContext,Y=FG6.safeParse(await Z.req.json().catch(()=>null));if(!Y.success)return Z.json({error:"Invalid body",details:Y.error.issues},400);let G=Y.data;for(let J of[...Object.keys(G.set??{}),...G.delete??[]])try{TP0(J)}catch(W){let K=W instanceof Error?W.message:String(W);return Z.json({error:K},400)}for(let[J,W]of Object.entries(G.set??{}))if(typeof W!=="object"||W===null||Array.isArray(W))return Z.json({error:`Block "${J}" must be a JSON object`},400);try{let J=await hP0(Z),W=await Ug$(`${X.organizationId}/${X.virtualMcpId}/${X.branch}`,{client:J,branch:X.branch,packagePath:X.packagePath,coAuthor:ch(Q)},G),K=L91({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.json({version:W,token:K,apiHost:jg$(Z)})}catch(J){return uP0(Z,J)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await hP0(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({error:"Branch is already the default branch"},400);let G=`chore(decofile): publish ${X.branch}`;try{let J;try{J=await Q.mergeBranch(Y,X.branch,G)}catch(W){if(!(W instanceof Q6&&W.status===409))throw W;await bP0(Q,X.branch,Y),J=await Q.mergeBranch(Y,X.branch,G)}return J?Z.json({result:"merged",sha:J}):Z.json({result:"up-to-date"})}catch(J){if(J instanceof Q6&&J.status===409)return Z.json({error:"merge-conflict"},409);if(J instanceof Q6&&J.status===405){let K=await Q.findOpenPullRequest(Y,X.branch)??await Q.createPullRequest({base:Y,head:X.branch,title:`Publish ${X.branch}`});return Z.json({result:"pull-request",number:K.number,url:K.html_url})}throw J}}catch(Q){return uP0(Z,Q)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await hP0(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});try{let{aheadBy:G,behindBy:J}=await Q.compare(Y,X.branch);return Z.json({baseBranch:Y,aheadBy:G,behindBy:J})}catch(G){if(G instanceof Q6&&G.status===404)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});throw G}}catch(Q){return uP0(Z,Q)}}),$}var KG6,FG6,Eg$;var Pg$=w(()=>{RP0();P8();n51();PP0();B91();Q91();Og$();Lg$();U91();R_();_P0();KG6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;FG6=nh.object({set:nh.record(nh.string(),nh.unknown()).optional(),delete:nh.array(nh.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}),Eg$=zP0(async($,Z)=>{let X=$.var.studioContext,Q=X.organization;if(!Q)return $.json({error:"Organization scope required"},500);let Y=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!Y||!G)return $.json({error:"virtualMcpId and branch are required"},400);if(!HG6(G))return $.json({error:`Invalid branch name: ${G}`},400);let J=X.auth?.user?.id??null;if(!J){let O=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!O||!Dg$(O,{organizationId:Q.id,virtualMcpId:Y,branch:G}))return $.json({error:"Unauthorized"},401)}let W=await X.storage.virtualMcps.findById(Y);if(!W||W.organization_id!==Q.id)return $.json({error:"Virtual MCP not found"},404);let K=W.metadata??null;if(!MB0(K)||K?.fastPreview!==!0)return $.json({error:"Fast Preview is not enabled for this project"},404);let F=W.connections?.map((O)=>O.connection_id)??[],N=sr(K,F);if(!N)return $.json({error:"Project has no GitHub repository"},404);let U=K?.runtime;return $.set("decofileScope",{organizationId:Q.id,virtualMcpId:Y,branch:G,packagePath:U?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:N,userId:J}),Z()})});var Ag$=($)=>{let Z=new U1;if(Z.use("*",D_),Z.route("/",yz0()),Z.route("/",nv$()),Z.route("/",nx$()),Z.route("/",mx$()),Z.route("/",LP0()),Z.route("/tools",$y$()),Z.route("/",ax$()),Z.route("/",qx$({kvStorage:$.kvStorage})),Z.route("/",Rx$()),Z.route("/fs",yx$({getConnection:$.getNatsConnection})),Z.route("/sandbox",Fg$()),Z.route("/decofile",zg$()),Z.route("/",cx$()),Z.route("/deco-sites",hz0()),Z.route("/sso",Cz0()),Z.route("/",EP0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",hv$()),$.mountDevAssets)Z.route("/dev-assets",uz0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",PC$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",hx$()),Z.route("/mcp",iw0()),Z.route("/mcp/self",DP0()),Z.route("/mcp",tw0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var Tg$=w(()=>{P8();w61();uv$();j61();cz0();jr();O61();Ix$();Mx$();gx$();Vn();G61();ow0();u51();ux$();lx$();ix$();tx$();sx$();l51();Zy$();d51();pw0();Ng$();Pg$()});function NG6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var UG6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},Rg$=()=>{let $=new U1;return $.use("*",UG6),$.get("/",async(Z)=>{let X=b0(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await lZ(Q,Y,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:NG6(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var Ig$=w(()=>{P8();T$();hj0()});import{z as M1}from"zod";function ZH($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function AG6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let X=$.substring(0,Z),Q=$.substring(Z+1);if(!X||!Q)return null;return{credentialId:X,modelId:Q}}function TG6($,Z,X){try{return JSON.parse($)}catch{throw new kg$(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function RG6($){let Z={};for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Q of X.tool_calls)Z[Q.id]=Q.function.name;return $.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};return{type:"image",image:Y.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((Y)=>({type:"tool-call",toolCallId:Y.id,toolName:Y.function.name,input:TG6(Y.function.arguments,Y.id,Y.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let Q=Z[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:Q,output:{type:"text",value:X.content}}]}}})}function IG6($){let Z=$.map((X)=>{let Q=X.function.parameters?yY(X.function.parameters):yY({type:"object",properties:{}});return[X.function.name,b$({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function qG6($){if(!$)return;return{openai:{response_format:$}}}function MG6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function qg$($,Z,X,Q,Y,G){let J={model:$,messages:Z,tools:X,temperature:Q.temperature,maxTokens:Q.max_tokens,topP:Q.top_p,frequencyPenalty:Q.frequency_penalty,presencePenalty:Q.presence_penalty,stopSequences:Q.stop?Array.isArray(Q.stop)?Q.stop:[Q.stop]:void 0,abortSignal:G};return Y?{...J,providerOptions:Y}:J}function Mg$($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var OG6=256,BG6,wG6,DG6,LG6,EG6,jG6,zG6,PG6,kg$,Vg$,Sg$;var Cg$=w(()=>{_4();P8();uh();$N();BG6=M1.object({type:M1.literal("function"),function:M1.object({name:M1.string(),description:M1.string().optional(),parameters:M1.record(M1.string(),M1.unknown()).optional()})}),wG6=M1.object({id:M1.string(),type:M1.literal("function"),function:M1.object({name:M1.string(),arguments:M1.string()})}),DG6=M1.discriminatedUnion("role",[M1.object({role:M1.literal("system"),content:M1.string(),name:M1.string().optional()}),M1.object({role:M1.literal("user"),content:M1.union([M1.string(),M1.array(M1.union([M1.object({type:M1.literal("text"),text:M1.string()}),M1.object({type:M1.literal("image_url"),image_url:M1.object({url:M1.string(),detail:M1.string().optional()})})]))]),name:M1.string().optional()}),M1.object({role:M1.literal("assistant"),content:M1.string().nullable().optional(),name:M1.string().optional(),tool_calls:M1.array(wG6).optional()}),M1.object({role:M1.literal("tool"),content:M1.string(),tool_call_id:M1.string()})]),LG6=M1.object({type:M1.literal("text")}),EG6=M1.object({type:M1.literal("json_object")}),jG6=M1.object({type:M1.literal("json_schema"),json_schema:M1.object({name:M1.string(),description:M1.string().optional(),schema:M1.record(M1.string(),M1.unknown()),strict:M1.boolean().optional()})}),zG6=M1.union([LG6,EG6,jG6]),PG6=M1.object({model:M1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:M1.array(DG6),stream:M1.boolean().optional().default(!1),temperature:M1.number().min(0).max(2).optional(),max_tokens:M1.number().positive().optional(),top_p:M1.number().min(0).max(1).optional(),frequency_penalty:M1.number().min(-2).max(2).optional(),presence_penalty:M1.number().min(-2).max(2).optional(),stop:M1.union([M1.string(),M1.array(M1.string())]).optional(),tools:M1.array(BG6).optional(),tool_choice:M1.union([M1.literal("auto"),M1.literal("none"),M1.literal("required"),M1.object({type:M1.literal("function"),function:M1.object({name:M1.string()})})]).optional(),response_format:zG6.optional(),user:M1.string().optional()});kg$=class kg$ extends Error{constructor($){super($);this.name="MessageConversionError"}};Vg$=new U1;Vg$.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(ZH("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(ZH("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==X)return $.json(ZH("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=PG6.safeParse(Q);if(!Y.success){let L=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(ZH(`Invalid request: ${L.message}`,"invalid_request_error",L.path.length>0?L.path.join("."):null),400)}let G=Y.data,J=AG6(G.model);if(!J)return $.json(ZH("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:W}=J,{modelId:K}=J;if(!W){let E=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((j)=>kD(j.providerId));if(!E)return $.json(ZH("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);W=E.id}let H;try{H=await Z.aiProviders.activate(W,Z.organization.id)}catch{return $.json(ZH(`AI provider credential not found or inaccessible: ${W}`,"invalid_request_error","model"),404)}let F=H.aiSdk.languageModel(K),N=RG6(G.messages),U=G.tools?IG6(G.tools):void 0,O=qG6(G.response_format),B=MG6(),D=Math.floor(Date.now()/1000);if(G.stream)return PN($,async(L)=>{let E=qg$(F,N,U,G,O,$.req.raw.signal);try{let j=dO(E),z=!1,A=0,P="",M=async()=>{if(P.length===0)return;let q=P;P="",await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{content:q},finish_reason:null}]})})};for await(let q of j.fullStream){if(!z&&(q.type==="text-delta"||q.type==="tool-call"))await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(q.type==="text-delta"){if(P+=q.text,P.length>=OG6)await M()}else if(q.type==="tool-call"){await M();let k=A++;await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:k,id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.input)}}]},finish_reason:null}]})})}else if(q.type==="finish")await M(),await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{},finish_reason:Mg$(q.finishReason)}],usage:q.totalUsage?{prompt_tokens:q.totalUsage.inputTokens??0,completion_tokens:q.totalUsage.outputTokens??0,total_tokens:q.totalUsage.totalTokens??0}:void 0})})}await M(),await L.writeSSE({data:"[DONE]"})}catch(j){let z=j;console.error("[openai-compat:stream] Error:",z.message),await L.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let L=qg$(F,N,U,G,O,$.req.raw.signal),E=await cO(L),j={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)j.tool_calls=E.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),j.content=null;return $.json({id:B,object:"chat.completion",created:D,model:G.model,choices:[{index:0,message:j,finish_reason:Mg$(E.finishReason)}],usage:{prompt_tokens:E.usage?.inputTokens??0,completion_tokens:E.usage?.outputTokens??0,total_tokens:E.usage?.totalTokens??0}})}}catch(Q){let Y=Q;if(Y.name==="AbortError")return $.json(ZH("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(ZH(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(ZH(Y.message,"server_error"),500)}});Sg$=Vg$});var vg$;var _g$=w(()=>{vg$={name:"decocms",version:"4.240.0",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^2.9.1","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^3.0.10","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@nats-io/jwt":"0.0.10-5","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});function SG6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??VG6}}var fg$,VG6="https://ph.studio.decocms.com",bg$;var xg$=w(()=>{P8();Yh0();XC();_9();T$();$61();_g$();fg$=new U1;fg$.get("/",($)=>{let Z={version:vg$.version,theme:Od1(),...EL().logo&&{logo:EL().logo},...AK()&&{internalUrl:dV1()},...b0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!b0().firecrawlApiKey,auth:Yv$(),posthog:SG6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:!AK()&&b0().sandboxProviderKind==="agent-sandbox"}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});bg$=fg$});function th($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function E91($){return(th($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function gg$($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(th($))}&sz=${Z}`}function yg$($,Z){let X=$.trim();if(X.length<=Z)return X;let Q=X.slice(0,Z-1),Y=Q.lastIndexOf(" ");return`${(Y>Z*0.6?Q.slice(0,Y):Q).trimEnd()}\u2026`}function hg$($){let{brand:Z,domain:X,score:Q,verdict:Y}=$,G=typeof Q==="number"?`${Z} commerce report \u2014 ${Math.round(Q)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=`See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,W=Y?.trim()?yg$(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):yg$(`How does ${X} really perform? ${J}`,200);return{title:G,description:W}}import{z as l0}from"zod";var V_,CG6,_G6,vG6,fG6,ug$;var cg$=w(()=>{V_=l0.enum(["good","bad","neutral"]),CG6=l0.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},l0.object({kind:l0.enum(["text","number","sparkline","badge","score"]).catch("text"),value:l0.coerce.string().optional(),tone:V_.optional(),muted:l0.boolean().optional(),delta:l0.coerce.string().optional(),deltaDir:l0.enum(["up","down","neutral"]).optional(),points:l0.array(l0.coerce.number()).optional(),label:l0.coerce.string().optional()}).transform(($)=>{if($.kind==="badge"&&$.label==null)$.label=$.value??"";if($.kind==="score"){let Z=Number($.value);if(Number.isNaN(Z))return{...$,kind:"text"}}return $})),_G6=l0.preprocess(($)=>{let Z=$;if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Array.isArray(Z.cells))Z=Z.cells;if(Array.isArray(Z)&&Z.length===1&&Array.isArray(Z[0]))Z=Z[0];if(Array.isArray(Z))return Z;if(Z&&typeof Z==="object")return Object.values(Z);return Z},l0.array(CG6)),vG6={key:l0.coerce.string(),title:l0.coerce.string(),eyebrow:l0.coerce.string().optional(),headline:l0.coerce.string(),annotation:l0.coerce.string().optional(),methodology:l0.coerce.string().optional(),sources:l0.array(l0.object({name:l0.coerce.string(),logoUrl:l0.coerce.string()})).optional()},fG6=l0.discriminatedUnion("template",[l0.object({template:l0.literal("cover"),score:l0.object({value:l0.coerce.number(),max:l0.coerce.number().optional(),grade:l0.coerce.string().optional(),label:l0.coerce.string().optional()}).optional(),brandImage:l0.coerce.string().optional(),screenshot:l0.coerce.string().optional(),mobileScreenshot:l0.coerce.string().optional()}),l0.object({template:l0.literal("cta"),ctaUrl:l0.coerce.string().optional(),ctaLabel:l0.coerce.string().optional(),bullets:l0.array(l0.coerce.string()).optional()}),l0.object({template:l0.literal("series"),points:l0.array(l0.coerce.number()).min(2),xLabels:l0.array(l0.coerce.string()).min(1),unit:l0.coerce.string().optional(),callout:l0.object({index:l0.coerce.number(),value:l0.coerce.string(),tone:V_.optional()})}),l0.object({template:l0.literal("threshold"),value:l0.coerce.string().default(""),metricLabel:l0.coerce.string().optional(),ratio:l0.coerce.number(),thresholdRatio:l0.coerce.number().optional(),thresholdLabel:l0.coerce.string().default(""),tone:V_.optional()}),l0.object({template:l0.literal("stats"),stats:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),tone:V_.optional()})).min(1)}),l0.object({template:l0.literal("bars"),items:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),ratio:l0.coerce.number(),tone:V_.optional()})).min(1)}),l0.object({template:l0.literal("gauges"),gauges:l0.array(l0.object({label:l0.coerce.string(),value:l0.coerce.string(),status:l0.enum(["good","warn","bad"]).catch("warn"),caption:l0.coerce.string().optional(),ratio:l0.coerce.number().optional()})).min(1)}),l0.object({template:l0.literal("checklist"),checks:l0.array(l0.object({label:l0.coerce.string(),status:l0.enum(["pass","fail","warn"]).catch("fail"),value:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("table"),columns:l0.array(l0.object({label:l0.coerce.string(),align:l0.enum(["left","right"]).optional()})).min(1),rows:l0.array(_G6).min(1),highlightRow:l0.coerce.number().optional()}),l0.object({template:l0.literal("products"),products:l0.array(l0.object({name:l0.coerce.string(),price:l0.coerce.string().optional(),image:l0.coerce.string().optional(),url:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("list"),entries:l0.array(l0.object({label:l0.coerce.string(),severity:l0.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:l0.coerce.number().optional()}),l0.object({template:l0.literal("keywords"),volumeLabel:l0.coerce.string().optional(),keywords:l0.array(l0.object({term:l0.coerce.string(),volume:l0.coerce.string(),position:l0.coerce.number().catch(0)})).min(1)}),l0.object({template:l0.literal("competitor"),metricLabel:l0.coerce.string().optional(),competitors:l0.array(l0.object({name:l0.coerce.string(),value:l0.coerce.string(),tone:V_.optional(),isYou:l0.boolean().optional()})).min(1)}),l0.object({template:l0.literal("scorecard"),rivalLabel:l0.coerce.string().optional(),dimensions:l0.array(l0.object({label:l0.coerce.string(),you:l0.coerce.string(),rival:l0.coerce.string().optional(),rivalName:l0.coerce.string().optional(),tone:V_.optional()})).min(1)})]),ug$=l0.object({...vG6,template:fG6})});function cP0($){let Z=[],X=[...$.sections].sort((Y,G)=>Y.position-G.position).map((Y)=>{let G=ug$.safeParse(Y.props);if(G.success)return G.data;let J=G.error.issues[0];return Z.push({section_type:Y.section_type,position:Y.position,reason:J?`${J.path.join(".")||"(root)"}: ${J.message}`:"contract violation"}),null}).filter((Y)=>Y!==null),Q=X.filter((Y)=>Y.template.template!=="cover"&&Y.template.template!=="cta").map((Y)=>({key:Y.key,title:Y.title}));return{deck:{meta:{...$.meta,scores:$.summary?.scores,scannedAt:$.scanned_at,toc:Q},slides:X},drops:Z}}var j91=w(()=>{cg$()});import{join as lg$}from"path";async function xG6($){try{let Z=await fetch(`${tW({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(bG6)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=cP0(X);if(!Q.slides.length)return null;let Y=Q.slides.find((W)=>W.template.template==="cover"),G=Y?.template,J=G&&G.template==="cover"?G:void 0;return{brand:Q.meta.brand?.trim()||E91($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function GG($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}function yG6($,Z){let X=th($),Q=Z?.brand?.trim()||E91(X),Y=gg$(X,128),J=`${(b0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:W,description:K}=hg$({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),H=`${J}/og.png`,F=`${Q} commerce report by decocms`;return[`<title>${GG(W)}</title>`,`<meta name="description" content="${GG(K)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${GG(W)}" />`,`<meta property="og:description" content="${GG(K)}" />`,`<meta property="og:url" content="${GG(J)}" />`,`<meta property="og:image" content="${GG(H)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${GG(F)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${GG(W)}" />`,`<meta name="twitter:description" content="${GG(K)}" />`,`<meta name="twitter:image" content="${GG(H)}" />`,`<meta name="twitter:image:alt" content="${GG(F)}" />`,`<link rel="canonical" href="${GG(J)}" />`,`<link rel="icon" href="${GG(Y)}" sizes="any" />`].join(`
|
|
2786
|
+
`,j=await Z.createBlob(E);await ey$(Z.owner,Z.repo,j,E);let z=L[0]??`${CP0(Q)}/${Y91(B)}.json`;H.push({path:z,mode:"100644",type:"blob",sha:j});let A=z.slice(z.lastIndexOf("/")+1,-5);F.set(z,{stem:A,sha:j,content:E});for(let P of L.slice(1))H.push({path:P,mode:"100644",type:"blob",sha:null}),F.delete(P)}for(let B of $.del)for(let D of F91(K,B))H.push({path:D,mode:"100644",type:"blob",sha:null}),F.delete(D);if(H.length===0)return G;let N=Q?`${Q}/.deco/blocks.gen.json`:".deco/blocks.gen.json";if(W.some((B)=>B.type==="blob"&&B.path===N)){let B=await Promise.all([...F.values()].map(async(j)=>({stem:j.stem,content:j.content??await Z.getBlobText(j.sha)}))),{decofile:D,skipped:L}=nr(B);if(L.length>0)console.warn("decofile gen: dropped blocks that were not valid JSON",{repo:`${Z.owner}/${Z.repo}`,branch:X,packagePath:Q,blocks:L.map((j)=>j.key)});let E=await Z.createBlob(D);H.push({path:N,mode:"100644",type:"blob",sha:E})}let U=await Z.createTree(J,H),O=await Z.createCommit({message:YG6($),treeSha:U,parentShas:[G]});try{return await Z.updateRef(X,O),O}catch(B){if(!(B instanceof Q6&&B.status===422)||Y>=ZG6-1)throw B;await q$(pZ(2000,200,Y,2,0.5))}}}function YG6($){let Z=(Y)=>{let G=Y.slice(0,3).join(", ");return Y.length>3?`${G} (+${Y.length-3} more)`:G},X=[];if($.set.size>0)X.push(`update ${Z([...$.set.keys()])}`);if($.del.size>0)X.push(`delete ${Z([...$.del])}`);let Q=`chore(decofile): ${X.join("; ")}`;return Rd0(Q,$.deps.coAuthor)}var ZG6=3,D91;var Og$=w(()=>{zO0();RP0();u4();R_();_P0();D91=new Map});import{createHmac as Bg$,randomBytes as GG6,timingSafeEqual as JG6}from"crypto";function wg$(){if(gP0)return gP0;let $;try{let Z=b0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return gP0=$?Buffer.from($):GG6(32),gP0}function L91($){let Z=$.nowMs??Date.now(),X={o:$.organizationId,m:$.virtualMcpId,b:$.branch,e:Math.floor((Z+WG6)/1000)},Q=Buffer.from(JSON.stringify(X)).toString("base64url"),Y=Bg$("sha256",wg$()).update(Q).digest("base64url");return`${Q}.${Y}`}function Dg$($,Z){let X=$.indexOf(".");if(X<0)return!1;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from(Bg$("sha256",wg$()).update(Q).digest("base64url"));if(Y.length!==G.length||!JG6(Y,G))return!1;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return!1}let W=Math.floor((Z.nowMs??Date.now())/1000);return J.o===Z.organizationId&&J.m===Z.virtualMcpId&&J.b===Z.branch&&typeof J.e==="number"&&J.e>=W}var WG6=21600000,gP0=null;var Lg$=w(()=>{T$()});import{z as nh}from"zod";function HG6($){return $.length>0&&$.length<=255&&!$.includes("..")&&!$.endsWith("/")&&!$.endsWith(".lock")&&KG6.test($)}function jg$($){return $.req.header("x-forwarded-host")??new URL($.req.url).host}async function hP0($){let Z=$.get("decofileScope");return AP0($.var.studioContext,Z.organizationId,Z.githubRepo)}function uP0($,Z){if(Z instanceof Q6){let Q=Z.status===404?404:Z.status===409?409:Z.status===422?409:502;return $.json({error:Z.message},Q)}let X=Z instanceof Error?Z.message:String(Z);return $.json({error:X},500)}function zg$(){let $=new U1;return $.use("/:virtualMcpId/:branch",Eg$),$.use("/:virtualMcpId/:branch/*",Eg$),$.get("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await hP0(Z),Y=await $g$(Q,X.branch,X.packagePath,{createBranchIfMissing:!!X.userId}),G={ETag:`"${Y.sha}"`,"Cache-Control":"no-store","Access-Control-Allow-Origin":"*"};if(Z.req.header("if-none-match")===`"${Y.sha}"`)return Z.body(null,304,G);if(!X.userId)return Z.body(Y.decofile,200,{...G,"content-type":"application/json"});let J=L91({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.body(`{"version":${JSON.stringify(Y.sha)},"token":${JSON.stringify(J)},"apiHost":${JSON.stringify(jg$(Z))},"decofile":${Y.decofile}}`,200,{...G,"content-type":"application/json"})}catch(Q){return uP0(Z,Q)}}),$.patch("/:virtualMcpId/:branch",async(Z)=>{let X=Z.get("decofileScope"),Q=Z.var.studioContext,Y=FG6.safeParse(await Z.req.json().catch(()=>null));if(!Y.success)return Z.json({error:"Invalid body",details:Y.error.issues},400);let G=Y.data;for(let J of[...Object.keys(G.set??{}),...G.delete??[]])try{TP0(J)}catch(W){let K=W instanceof Error?W.message:String(W);return Z.json({error:K},400)}for(let[J,W]of Object.entries(G.set??{}))if(typeof W!=="object"||W===null||Array.isArray(W))return Z.json({error:`Block "${J}" must be a JSON object`},400);try{let J=await hP0(Z),W=await Ug$(`${X.organizationId}/${X.virtualMcpId}/${X.branch}`,{client:J,branch:X.branch,packagePath:X.packagePath,coAuthor:ch(Q)},G),K=L91({organizationId:X.organizationId,virtualMcpId:X.virtualMcpId,branch:X.branch});return Z.json({version:W,token:K,apiHost:jg$(Z)})}catch(J){return uP0(Z,J)}}),$.post("/:virtualMcpId/:branch/publish",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await hP0(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({error:"Branch is already the default branch"},400);let G=`chore(decofile): publish ${X.branch}`;try{let J;try{J=await Q.mergeBranch(Y,X.branch,G)}catch(W){if(!(W instanceof Q6&&W.status===409))throw W;await bP0(Q,X.branch,Y),J=await Q.mergeBranch(Y,X.branch,G)}return J?Z.json({result:"merged",sha:J}):Z.json({result:"up-to-date"})}catch(J){if(J instanceof Q6&&J.status===409)return Z.json({error:"merge-conflict"},409);if(J instanceof Q6&&J.status===405){let K=await Q.findOpenPullRequest(Y,X.branch)??await Q.createPullRequest({base:Y,head:X.branch,title:`Publish ${X.branch}`});return Z.json({result:"pull-request",number:K.number,url:K.html_url})}throw J}}catch(Q){return uP0(Z,Q)}}),$.get("/:virtualMcpId/:branch/status",async(Z)=>{let X=Z.get("decofileScope");try{let Q=await hP0(Z),Y=await Q.getDefaultBranch();if(Y===X.branch)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});try{let{aheadBy:G,behindBy:J}=await Q.compare(Y,X.branch);return Z.json({baseBranch:Y,aheadBy:G,behindBy:J})}catch(G){if(G instanceof Q6&&G.status===404)return Z.json({baseBranch:Y,aheadBy:0,behindBy:0});throw G}}catch(Q){return uP0(Z,Q)}}),$}var KG6,FG6,Eg$;var Pg$=w(()=>{RP0();P8();n51();PP0();B91();Q91();Og$();Lg$();U91();R_();_P0();KG6=/^[a-zA-Z0-9][a-zA-Z0-9/._-]*$/;FG6=nh.object({set:nh.record(nh.string(),nh.unknown()).optional(),delete:nh.array(nh.string()).optional()}).refine(($)=>Object.keys($.set??{}).length>0||($.delete?.length??0)>0,{message:"Patch must set or delete at least one block"}),Eg$=zP0(async($,Z)=>{let X=$.var.studioContext,Q=X.organization;if(!Q)return $.json({error:"Organization scope required"},500);let Y=$.req.param("virtualMcpId"),G=$.req.param("branch");if(!Y||!G)return $.json({error:"virtualMcpId and branch are required"},400);if(!HG6(G))return $.json({error:`Invalid branch name: ${G}`},400);let J=X.auth?.user?.id??null;if(!J){let O=$.req.query("token");if(!($.req.method==="GET"&&!$.req.path.match(/\/(publish|status)$/)))return $.json({error:"Unauthorized"},401);if(!O||!Dg$(O,{organizationId:Q.id,virtualMcpId:Y,branch:G}))return $.json({error:"Unauthorized"},401)}let W=await X.storage.virtualMcps.findById(Y);if(!W||W.organization_id!==Q.id)return $.json({error:"Virtual MCP not found"},404);let K=W.metadata??null;if(!MB0(K)||K?.fastPreview!==!0)return $.json({error:"Fast Preview is not enabled for this project"},404);let F=W.connections?.map((O)=>O.connection_id)??[],N=sr(K,F);if(!N)return $.json({error:"Project has no GitHub repository"},404);let U=K?.runtime;return $.set("decofileScope",{organizationId:Q.id,virtualMcpId:Y,branch:G,packagePath:U?.path?.replace(/^\/+|\/+$/g,"")||null,githubRepo:N,userId:J}),Z()})});var Ag$=($)=>{let Z=new U1;if(Z.use("*",D_),Z.route("/",yz0()),Z.route("/",nv$()),Z.route("/",nx$()),Z.route("/",mx$()),Z.route("/",LP0()),Z.route("/tools",$y$()),Z.route("/",ax$()),Z.route("/",qx$({kvStorage:$.kvStorage})),Z.route("/",Rx$()),Z.route("/fs",yx$({getConnection:$.getNatsConnection})),Z.route("/sandbox",Fg$()),Z.route("/decofile",zg$()),Z.route("/",cx$()),Z.route("/deco-sites",hz0()),Z.route("/sso",Cz0()),Z.route("/",EP0({tokenStorage:$.tokenStorage,automationEventDispatcher:$.automationEventDispatcher})),Z.route("/webhooks",hv$()),$.mountDevAssets)Z.route("/dev-assets",uz0({orgFromPath:!0}));return Z.use("/mcp/:connectionId?",$.mcpAuth),Z.use("/mcp/:connectionId/ui-resource",$.mcpAuth),Z.use("/mcp/gateway/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/virtual-mcp/:virtualMcpId?",$.mcpAuth),Z.use("/mcp/self",$.mcpAuth),Z.use("/mcp/task-run/:threadId",$.mcpAuth),Z.route("/",PC$()),Z.get("/mcp/:gateway?/:connectionId/.well-known/oauth-protected-resource/*",$.betterAuthProtectedResourceHandler),Z.get("/mcp/.well-known/oauth-protected-resource",$.betterAuthProtectedResourceHandler),Z.route("/mcp/task-run",hx$()),Z.route("/mcp",iw0()),Z.route("/mcp/self",DP0()),Z.route("/mcp",tw0()),Z.all("/oauth-proxy/:connectionId/*",$.oauthProxyHandler),Z.get("/watch",$.watchHandler),Z};var Tg$=w(()=>{P8();w61();uv$();j61();cz0();jr();O61();Ix$();Mx$();gx$();Vn();G61();ow0();u51();ux$();lx$();ix$();tx$();sx$();l51();Zy$();d51();pw0();Ng$();Pg$()});function NG6($){return $.filter((Z)=>Z.vendors?.alias).map((Z)=>({name:Z.name,title:Z.title,description:Z.description,logo:Z.logo,category:Z.category,vendor:{alias:Z.vendors.alias,url:Z.vendors.url}}))}var UG6=async($,Z)=>{if(!$.get("studioContext").auth.user?.id)return $.json({error:"Unauthorized"},401);return Z()},Rg$=()=>{let $=new U1;return $.use("*",UG6),$.get("/",async(Z)=>{let X=b0(),Q=X.decoSupabaseUrl,Y=X.decoSupabaseServiceKey;if(!Q||!Y)return Z.json({apps:[]});try{let G=await lZ(Q,Y,"apps?select=name,title,description,logo,category,vendors(alias,url)");return Z.json({apps:NG6(G)})}catch(G){return console.error("[deco-apps] GET error:",G),Z.json({error:"Failed to fetch apps"},502)}}),$};var Ig$=w(()=>{P8();T$();hj0()});import{z as M1}from"zod";function ZH($,Z="invalid_request_error",X=null,Q=null){return{error:{message:$,type:Z,param:X,code:Q}}}function AG6($){if(!$)return null;let Z=$.indexOf(":");if(Z===-1)return{credentialId:null,modelId:$};let X=$.substring(0,Z),Q=$.substring(Z+1);if(!X||!Q)return null;return{credentialId:X,modelId:Q}}function TG6($,Z,X){try{return JSON.parse($)}catch{throw new kg$(`Invalid JSON in tool call arguments for function '${X}' (tool_call_id: ${Z}): ${$}`)}}function RG6($){let Z={};for(let X of $)if(X.role==="assistant"&&X.tool_calls)for(let Q of X.tool_calls)Z[Q.id]=Q.function.name;return $.map((X)=>{switch(X.role){case"system":return{role:"system",content:X.content};case"user":if(typeof X.content==="string")return{role:"user",content:X.content};return{role:"user",content:X.content.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};return{type:"image",image:Y.image_url.url}})};case"assistant":if(X.tool_calls&&X.tool_calls.length>0)return{role:"assistant",content:X.tool_calls.map((Y)=>({type:"tool-call",toolCallId:Y.id,toolName:Y.function.name,input:TG6(Y.function.arguments,Y.id,Y.function.name)}))};return{role:"assistant",content:X.content??""};case"tool":let Q=Z[X.tool_call_id]??"unknown";return{role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:Q,output:{type:"text",value:X.content}}]}}})}function IG6($){let Z=$.map((X)=>{let Q=X.function.parameters?yY(X.function.parameters):yY({type:"object",properties:{}});return[X.function.name,b$({description:X.function.description,inputSchema:Q})]});return Object.fromEntries(Z)}function qG6($){if(!$)return;return{openai:{response_format:$}}}function MG6(){return`chatcmpl-${crypto.randomUUID().replace(/-/g,"").substring(0,29)}`}function qg$($,Z,X,Q,Y,G){let J={model:$,messages:Z,tools:X,temperature:Q.temperature,maxTokens:Q.max_tokens,topP:Q.top_p,frequencyPenalty:Q.frequency_penalty,presencePenalty:Q.presence_penalty,stopSequences:Q.stop?Array.isArray(Q.stop)?Q.stop:[Q.stop]:void 0,abortSignal:G};return Y?{...J,providerOptions:Y}:J}function Mg$($){if($==="tool-calls")return"tool_calls";if($==="length")return"length";return"stop"}var OG6=256,BG6,wG6,DG6,LG6,EG6,jG6,zG6,PG6,kg$,Vg$,Sg$;var Cg$=w(()=>{_4();P8();uh();$N();BG6=M1.object({type:M1.literal("function"),function:M1.object({name:M1.string(),description:M1.string().optional(),parameters:M1.record(M1.string(),M1.unknown()).optional()})}),wG6=M1.object({id:M1.string(),type:M1.literal("function"),function:M1.object({name:M1.string(),arguments:M1.string()})}),DG6=M1.discriminatedUnion("role",[M1.object({role:M1.literal("system"),content:M1.string(),name:M1.string().optional()}),M1.object({role:M1.literal("user"),content:M1.union([M1.string(),M1.array(M1.union([M1.object({type:M1.literal("text"),text:M1.string()}),M1.object({type:M1.literal("image_url"),image_url:M1.object({url:M1.string(),detail:M1.string().optional()})})]))]),name:M1.string().optional()}),M1.object({role:M1.literal("assistant"),content:M1.string().nullable().optional(),name:M1.string().optional(),tool_calls:M1.array(wG6).optional()}),M1.object({role:M1.literal("tool"),content:M1.string(),tool_call_id:M1.string()})]),LG6=M1.object({type:M1.literal("text")}),EG6=M1.object({type:M1.literal("json_object")}),jG6=M1.object({type:M1.literal("json_schema"),json_schema:M1.object({name:M1.string(),description:M1.string().optional(),schema:M1.record(M1.string(),M1.unknown()),strict:M1.boolean().optional()})}),zG6=M1.union([LG6,EG6,jG6]),PG6=M1.object({model:M1.string().describe("Format: 'model_id' or 'credential_id:model_id'"),messages:M1.array(DG6),stream:M1.boolean().optional().default(!1),temperature:M1.number().min(0).max(2).optional(),max_tokens:M1.number().positive().optional(),top_p:M1.number().min(0).max(1).optional(),frequency_penalty:M1.number().min(-2).max(2).optional(),presence_penalty:M1.number().min(-2).max(2).optional(),stop:M1.union([M1.string(),M1.array(M1.string())]).optional(),tools:M1.array(BG6).optional(),tool_choice:M1.union([M1.literal("auto"),M1.literal("none"),M1.literal("required"),M1.object({type:M1.literal("function"),function:M1.object({name:M1.string()})})]).optional(),response_format:zG6.optional(),user:M1.string().optional()});kg$=class kg$ extends Error{constructor($){super($);this.name="MessageConversionError"}};Vg$=new U1;Vg$.post("/:org/v1/chat/completions",async($)=>{let Z=$.get("studioContext"),X=$.req.param("org");try{if(!Z.auth.apiKey?.id)return $.json(ZH("API key authentication required. Provide a valid API key via Authorization header.","authentication_error"),401);if(!Z.organization)return $.json(ZH("Organization context is required. Ensure your API key has organization metadata.","invalid_request_error","organization"),400);if((Z.organization.slug??Z.organization.id)!==X)return $.json(ZH("Organization mismatch. The API key's organization does not match the requested organization.","invalid_request_error","organization"),403);let Q=await $.req.json(),Y=PG6.safeParse(Q);if(!Y.success){let L=Y.error.issues[0]??{message:"Invalid request",path:[]};return $.json(ZH(`Invalid request: ${L.message}`,"invalid_request_error",L.path.length>0?L.path.join("."):null),400)}let G=Y.data,J=AG6(G.model);if(!J)return $.json(ZH("Invalid model format. Expected 'model_id' or 'credential_id:model_id' (e.g., 'claude-sonnet-4-6' or 'key_abc123:claude-sonnet-4-6')","invalid_request_error","model"),400);let{credentialId:W}=J,{modelId:K}=J;if(!W){let E=(await Z.storage.aiProviderKeys.list({organizationId:Z.organization.id})).find((j)=>kD(j.providerId));if(!E)return $.json(ZH("No AI provider credentials configured for this organization. Add a credential in settings or specify one explicitly via 'credential_id:model_id'.","invalid_request_error","model"),400);W=E.id}let H;try{H=await Z.aiProviders.activate(W,Z.organization.id)}catch{return $.json(ZH(`AI provider credential not found or inaccessible: ${W}`,"invalid_request_error","model"),404)}let F=H.aiSdk.languageModel(K),N=RG6(G.messages),U=G.tools?IG6(G.tools):void 0,O=qG6(G.response_format),B=MG6(),D=Math.floor(Date.now()/1000);if(G.stream)return PN($,async(L)=>{let E=qg$(F,N,U,G,O,$.req.raw.signal);try{let j=dO(E),z=!1,A=0,P="",M=async()=>{if(P.length===0)return;let q=P;P="",await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{content:q},finish_reason:null}]})})};for await(let q of j.fullStream){if(!z&&(q.type==="text-delta"||q.type==="tool-call"))await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{role:"assistant",content:""},finish_reason:null}]})}),z=!0;if(q.type==="text-delta"){if(P+=q.text,P.length>=OG6)await M()}else if(q.type==="tool-call"){await M();let k=A++;await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{tool_calls:[{index:k,id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.input)}}]},finish_reason:null}]})})}else if(q.type==="finish")await M(),await L.writeSSE({data:JSON.stringify({id:B,object:"chat.completion.chunk",created:D,model:G.model,choices:[{index:0,delta:{},finish_reason:Mg$(q.finishReason)}],usage:q.totalUsage?{prompt_tokens:q.totalUsage.inputTokens??0,completion_tokens:q.totalUsage.outputTokens??0,total_tokens:q.totalUsage.totalTokens??0}:void 0})})}await M(),await L.writeSSE({data:"[DONE]"})}catch(j){let z=j;console.error("[openai-compat:stream] Error:",z.message),await L.writeSSE({data:JSON.stringify({error:{message:z.message,type:"server_error"}})})}});else{let L=qg$(F,N,U,G,O,$.req.raw.signal),E=await cO(L),j={role:"assistant",content:E.text||null};if(E.toolCalls&&E.toolCalls.length>0)j.tool_calls=E.toolCalls.map((z)=>({id:z.toolCallId,type:"function",function:{name:z.toolName,arguments:JSON.stringify("input"in z?z.input:{})}})),j.content=null;return $.json({id:B,object:"chat.completion",created:D,model:G.model,choices:[{index:0,message:j,finish_reason:Mg$(E.finishReason)}],usage:{prompt_tokens:E.usage?.inputTokens??0,completion_tokens:E.usage?.outputTokens??0,total_tokens:E.usage?.totalTokens??0}})}}catch(Q){let Y=Q;if(Y.name==="AbortError")return $.json(ZH("Request aborted","invalid_request_error"),400);if(Y.name==="MessageConversionError")return $.json(ZH(Y.message,"invalid_request_error","messages"),400);return console.error("[openai-compat] Error:",Y.message,Y.stack),$.json(ZH(Y.message,"server_error"),500)}});Sg$=Vg$});var vg$;var _g$=w(()=>{vg$={name:"decocms",version:"4.241.1",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^2.9.1","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^3.0.10","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@nats-io/jwt":"0.0.10-5","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^6.0.208","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});function SG6(){let $=process.env.POSTHOG_KEY;if(!$)return null;return{key:$,host:process.env.POSTHOG_HOST??VG6}}var fg$,VG6="https://ph.studio.decocms.com",bg$;var xg$=w(()=>{P8();Yh0();XC();_9();T$();$61();_g$();fg$=new U1;fg$.get("/",($)=>{let Z={version:vg$.version,theme:Od1(),...EL().logo&&{logo:EL().logo},...AK()&&{internalUrl:dV1()},...b0().enableDecoImport&&{enableDecoImport:!0},brandExtractEnabled:!!b0().firecrawlApiKey,auth:Yv$(),posthog:SG6(),googleMapsApiKey:process.env.GOOGLE_MAPS_API_KEY?.trim()||null,runtime:{agentSandbox:!AK()&&b0().sandboxProviderKind==="agent-sandbox"}};return $.header("Cache-Control","no-store"),$.json({success:!0,config:Z})});bg$=fg$});function th($){let Z=($??"").trim().toLowerCase();return Z=Z.replace(/^https?:\/\//,""),Z=Z.replace(/^www\./,""),Z=Z.split(/[/?#]/)[0]??"",Z.replace(/\/+$/,"")}function E91($){return(th($).split(".")[0]||$).replace(/[-_]/g," ").split(" ").filter(Boolean).map((X)=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")}function gg$($,Z=64){return`https://www.google.com/s2/favicons?domain=${encodeURIComponent(th($))}&sz=${Z}`}function yg$($,Z){let X=$.trim();if(X.length<=Z)return X;let Q=X.slice(0,Z-1),Y=Q.lastIndexOf(" ");return`${(Y>Z*0.6?Q.slice(0,Y):Q).trimEnd()}\u2026`}function hg$($){let{brand:Z,domain:X,score:Q,verdict:Y}=$,G=typeof Q==="number"?`${Z} commerce report \u2014 ${Math.round(Q)}/100 \xB7 decocms`:`${Z} commerce report \xB7 decocms`,J=`See the full ${Z} scorecard \u2014 SEO, performance, conversion & AEO signals scored by decocms.`,W=Y?.trim()?yg$(`${Y.trim().replace(/\s+/g," ")} \u2014 ${J}`,200):yg$(`How does ${X} really perform? ${J}`,200);return{title:G,description:W}}import{z as l0}from"zod";var V_,CG6,_G6,vG6,fG6,ug$;var cg$=w(()=>{V_=l0.enum(["good","bad","neutral"]),CG6=l0.preprocess(($)=>{if(Array.isArray($))return{kind:"text",value:$.find((X)=>X!==null&&typeof X!=="object")??""};return $!==null&&typeof $==="object"?$:{kind:"text",value:$}},l0.object({kind:l0.enum(["text","number","sparkline","badge","score"]).catch("text"),value:l0.coerce.string().optional(),tone:V_.optional(),muted:l0.boolean().optional(),delta:l0.coerce.string().optional(),deltaDir:l0.enum(["up","down","neutral"]).optional(),points:l0.array(l0.coerce.number()).optional(),label:l0.coerce.string().optional()}).transform(($)=>{if($.kind==="badge"&&$.label==null)$.label=$.value??"";if($.kind==="score"){let Z=Number($.value);if(Number.isNaN(Z))return{...$,kind:"text"}}return $})),_G6=l0.preprocess(($)=>{let Z=$;if(Z&&typeof Z==="object"&&!Array.isArray(Z)&&Array.isArray(Z.cells))Z=Z.cells;if(Array.isArray(Z)&&Z.length===1&&Array.isArray(Z[0]))Z=Z[0];if(Array.isArray(Z))return Z;if(Z&&typeof Z==="object")return Object.values(Z);return Z},l0.array(CG6)),vG6={key:l0.coerce.string(),title:l0.coerce.string(),eyebrow:l0.coerce.string().optional(),headline:l0.coerce.string(),annotation:l0.coerce.string().optional(),methodology:l0.coerce.string().optional(),sources:l0.array(l0.object({name:l0.coerce.string(),logoUrl:l0.coerce.string()})).optional()},fG6=l0.discriminatedUnion("template",[l0.object({template:l0.literal("cover"),score:l0.object({value:l0.coerce.number(),max:l0.coerce.number().optional(),grade:l0.coerce.string().optional(),label:l0.coerce.string().optional()}).optional(),brandImage:l0.coerce.string().optional(),screenshot:l0.coerce.string().optional(),mobileScreenshot:l0.coerce.string().optional()}),l0.object({template:l0.literal("cta"),ctaUrl:l0.coerce.string().optional(),ctaLabel:l0.coerce.string().optional(),bullets:l0.array(l0.coerce.string()).optional()}),l0.object({template:l0.literal("series"),points:l0.array(l0.coerce.number()).min(2),xLabels:l0.array(l0.coerce.string()).min(1),unit:l0.coerce.string().optional(),callout:l0.object({index:l0.coerce.number(),value:l0.coerce.string(),tone:V_.optional()})}),l0.object({template:l0.literal("threshold"),value:l0.coerce.string().default(""),metricLabel:l0.coerce.string().optional(),ratio:l0.coerce.number(),thresholdRatio:l0.coerce.number().optional(),thresholdLabel:l0.coerce.string().default(""),tone:V_.optional()}),l0.object({template:l0.literal("stats"),stats:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),tone:V_.optional()})).min(1)}),l0.object({template:l0.literal("bars"),items:l0.array(l0.object({value:l0.coerce.string(),label:l0.coerce.string(),ratio:l0.coerce.number(),tone:V_.optional()})).min(1)}),l0.object({template:l0.literal("gauges"),gauges:l0.array(l0.object({label:l0.coerce.string(),value:l0.coerce.string(),status:l0.enum(["good","warn","bad"]).catch("warn"),caption:l0.coerce.string().optional(),ratio:l0.coerce.number().optional()})).min(1)}),l0.object({template:l0.literal("checklist"),checks:l0.array(l0.object({label:l0.coerce.string(),status:l0.enum(["pass","fail","warn"]).catch("fail"),value:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("table"),columns:l0.array(l0.object({label:l0.coerce.string(),align:l0.enum(["left","right"]).optional()})).min(1),rows:l0.array(_G6).min(1),highlightRow:l0.coerce.number().optional()}),l0.object({template:l0.literal("products"),products:l0.array(l0.object({name:l0.coerce.string(),price:l0.coerce.string().optional(),image:l0.coerce.string().optional(),url:l0.coerce.string().optional()})).min(1)}),l0.object({template:l0.literal("list"),entries:l0.array(l0.object({label:l0.coerce.string(),severity:l0.enum(["error","warning","notice"]).catch("notice")})).min(1),moreCount:l0.coerce.number().optional()}),l0.object({template:l0.literal("keywords"),volumeLabel:l0.coerce.string().optional(),keywords:l0.array(l0.object({term:l0.coerce.string(),volume:l0.coerce.string(),position:l0.coerce.number().catch(0)})).min(1)}),l0.object({template:l0.literal("competitor"),metricLabel:l0.coerce.string().optional(),competitors:l0.array(l0.object({name:l0.coerce.string(),value:l0.coerce.string(),tone:V_.optional(),isYou:l0.boolean().optional()})).min(1)}),l0.object({template:l0.literal("scorecard"),rivalLabel:l0.coerce.string().optional(),dimensions:l0.array(l0.object({label:l0.coerce.string(),you:l0.coerce.string(),rival:l0.coerce.string().optional(),rivalName:l0.coerce.string().optional(),tone:V_.optional()})).min(1)})]),ug$=l0.object({...vG6,template:fG6})});function cP0($){let Z=[],X=[...$.sections].sort((Y,G)=>Y.position-G.position).map((Y)=>{let G=ug$.safeParse(Y.props);if(G.success)return G.data;let J=G.error.issues[0];return Z.push({section_type:Y.section_type,position:Y.position,reason:J?`${J.path.join(".")||"(root)"}: ${J.message}`:"contract violation"}),null}).filter((Y)=>Y!==null),Q=X.filter((Y)=>Y.template.template!=="cover"&&Y.template.template!=="cta").map((Y)=>({key:Y.key,title:Y.title}));return{deck:{meta:{...$.meta,scores:$.summary?.scores,scannedAt:$.scanned_at,toc:Q},slides:X},drops:Z}}var j91=w(()=>{cg$()});import{join as lg$}from"path";async function xG6($){try{let Z=await fetch(`${tW({})}/api/v2/public/diagnostics/${encodeURIComponent($)}`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(bG6)});if(!Z.ok)return null;let X=await Z.json(),{deck:Q}=cP0(X);if(!Q.slides.length)return null;let Y=Q.slides.find((W)=>W.template.template==="cover"),G=Y?.template,J=G&&G.template==="cover"?G:void 0;return{brand:Q.meta.brand?.trim()||E91($),score:Q.meta.scores?.cover??J?.score?.value,verdict:Y?.annotation?.trim()||Y?.headline?.trim()||void 0}}catch{return null}}function GG($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}function yG6($,Z){let X=th($),Q=Z?.brand?.trim()||E91(X),Y=gg$(X,128),J=`${(b0().baseUrl??"https://studio.decocms.com").replace(/\/+$/,"")}/report/${encodeURIComponent(X)}`,{title:W,description:K}=hg$({brand:Q,domain:X,score:Z?.score,verdict:Z?.verdict}),H=`${J}/og.png`,F=`${Q} commerce report by decocms`;return[`<title>${GG(W)}</title>`,`<meta name="description" content="${GG(K)}" />`,'<meta name="robots" content="noindex, follow" />','<meta property="og:type" content="website" />','<meta property="og:site_name" content="decocms" />',`<meta property="og:title" content="${GG(W)}" />`,`<meta property="og:description" content="${GG(K)}" />`,`<meta property="og:url" content="${GG(J)}" />`,`<meta property="og:image" content="${GG(H)}" />`,'<meta property="og:image:width" content="1200" />','<meta property="og:image:height" content="630" />',`<meta property="og:image:alt" content="${GG(F)}" />`,'<meta name="twitter:card" content="summary_large_image" />',`<meta name="twitter:title" content="${GG(W)}" />`,`<meta name="twitter:description" content="${GG(K)}" />`,`<meta name="twitter:image" content="${GG(H)}" />`,`<meta name="twitter:image:alt" content="${GG(F)}" />`,`<link rel="canonical" href="${GG(J)}" />`,`<link rel="icon" href="${GG(Y)}" sizes="any" />`].join(`
|
|
2787
2787
|
`)}function gG6($,Z){return $.replace(/<title>[\s\S]*?<\/title>\s*/i,"").replace(/<meta\s+name="(?:description|twitter:[^"]*)"[^>]*>\s*/gi,"").replace(/<meta\s+property="og:[^"]*"[^>]*>\s*/gi,"").replace(/<link\s+rel="icon"[^>]*>\s*/gi,"").replace("</head>",` ${Z}
|
|
2788
2788
|
</head>`)}function dg$($){let Z=new U1;return Z.get("/:domain/og.png",async(X)=>{let Q=th(X.req.param("domain")),Y=async()=>{let G=$?Bun.file(lg$($,"report-og-fallback.png")):null;if(!G||!await G.exists())return X.notFound();return X.body(new Uint8Array(await G.arrayBuffer()),200,{"Content-Type":"image/png","Cache-Control":"public, max-age=0, s-maxage=3600"})};try{let G=await fetch(`${tW({})}/api/v2/public/diagnostics/${encodeURIComponent(Q)}/og.png`,{signal:AbortSignal.timeout(hG6)}),J=G.headers.get("content-type")??"";if(!G.ok||!J.startsWith("image/")||!G.body)return Y();return X.body(G.body,200,{"Content-Type":J,"Cache-Control":"public, max-age=0, s-maxage=604800"})}catch{return Y()}}),Z.get("/:domain",async(X)=>{let Q=X.req.param("domain"),Y=$?lg$($,"index.html"):null,G=Y?Bun.file(Y):null;if(!G||!await G.exists())return X.notFound();let J=await G.text();try{let W=await xG6(th(Q)),K=yG6(Q,W);return X.html(gG6(J,K),200,{"Cache-Control":"public, max-age=0, s-maxage=300"})}catch{return X.html(J)}}),Z}var bG6=2500,hG6=1e4;var mg$=w(()=>{P8();j91();_L();T$()});function $a($,Z){return fetch(`${tW({})}${$}`,Z)}async function uG6($,Z,X){let Q=new URLSearchParams;if(Z)Q.set("pw",Z);if(X)Q.set("lang",X);let Y=Q.toString()?`?${Q.toString()}`:"",G=await $a(`/api/v2/public/diagnostics/${encodeURIComponent($)}${Y}`,{headers:{Accept:"application/json"}});if(G.status===404)return{status:"not_found",deck:null,scanned_at:null,drops:[]};if(!G.ok)throw Error(`report read HTTP ${G.status}`);let J=await G.json(),{deck:W,drops:K}=cP0(J);return{status:W.slides.length?"ready":"empty",deck:W,scanned_at:J.scanned_at,drops:K}}var cG6,TN,ig$=async($,Z)=>{if(!$.get("reportUser"))return $.json({error:"Authentication required"},401);await Z();return},pg$;var ng$=w(()=>{P8();vY();_L();j91();cG6=new Set(["complete","errored","terminated","unknown"]),TN=new U1;TN.use("*",async($,Z)=>{let X=await H8.api.getSession({headers:$.req.raw.headers});$.set("reportUser",X?.user?.id?{email:X.user.email}:void 0),await Z(),$.header("Cache-Control","private, no-store"),$.header("Vary","Cookie");return});TN.use("/link-token/*",ig$);TN.use("/suggest",ig$);TN.get("/site/:domain",async($)=>{let Z=$.req.param("domain").trim();if(!Z)return $.json({error:"domain is required"},400);let X=$.get("reportUser"),Q=$.req.query("key")?.trim()||void 0,Y=$.req.query("lang")?.trim()||void 0;try{let G=await uG6(Z,Q,Y);if($.header("Cache-Control","private, no-store"),X||!G.deck)return $.json(G);return $.json({...G,deck:{...G.deck,slides:G.deck.slides.slice(0,1)},truncated:G.status==="ready"})}catch{return $.json({error:"report read failed"},502)}});TN.post("/run",async($)=>{let Z=$.get("reportUser"),X;try{X=await $.req.json()}catch{return $.json({error:"invalid JSON"},400)}let Q=typeof X.domain==="string"?X.domain.trim():"";if(!Q)return $.json({error:"domain is required"},400);let Y=Z?.email,G=typeof X.distinctId==="string"&&X.distinctId.trim()&&X.distinctId.length<=200?X.distinctId.trim():void 0;try{let J=await $a("/api/v2/diagnostics/run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${CL({})}`},body:JSON.stringify({url:Q,...Y?{email:Y}:{},distinct_id:G})});if(!J.ok)return $.json({error:`run HTTP ${J.status}`},502);let W=await J.json(),K=W.blocked?{state:"blocked"}:W.status==="fresh"?{state:"fresh"}:W.mode==="sync"?{state:"sync"}:{state:"running",id:W.id??null};return $.json(K)}catch{return $.json({error:"run failed"},502)}});TN.get("/status",async($)=>{let Z=$.req.query("id");if(!Z)return $.json({error:"id is required"},400);try{let X=await $a(`/api/v2/diagnostics/status?id=${encodeURIComponent(Z)}`,{headers:{Authorization:`Bearer ${CL({})}`}});if(!X.ok)return $.json({error:`status HTTP ${X.status}`},502);let Y=(await X.json()).status??"unknown",G={done:cG6.has(Y),status:Y};return $.json(G)}catch{return $.json({error:"status failed"},502)}});TN.get("/link-token/:id",async($)=>{let Z=$.req.param("id");try{let X=await $a(`/api/v2/public/link-tokens/${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(X.status===404)return $.json(null);if(!X.ok)return $.json({error:`link token HTTP ${X.status}`},502);return $.json(await X.json())}catch{return $.json({error:"link token resolve failed"},502)}});TN.get("/suggest",async($)=>{let Z=($.req.query("q")??"").trim().slice(0,64);if(Z.length<2)return $.json({suggestions:[]});try{let X=await $a(`/api/v2/public/suggest?q=${encodeURIComponent(Z)}`,{headers:{Accept:"application/json"}});if(!X.ok)return $.json({suggestions:[]});let Q=await X.json();return $.json({suggestions:Array.isArray(Q.suggestions)?Q.suggestions:[]})}catch{return $.json({suggestions:[]})}});pg$=TN});import{createHmac as lG6,timingSafeEqual as dG6}from"crypto";function og$($,Z,X,Q=Date.now()){if(!Z||!X)return!1;let Y,G=[];for(let H of Z.split(",")){let F=H.indexOf("=");if(F<=0)continue;let N=H.slice(0,F).trim(),U=H.slice(F+1).trim();if(N==="t")Y=U;else if(N==="v1")G.push(U)}if(!Y||G.length===0)return!1;let J=Number(Y);if(!Number.isFinite(J)||Math.abs(Q/1000-J)>mG6)return!1;let W=lG6("sha256",X).update(`${Y}.${$}`).digest("hex"),K=Buffer.from(W,"hex");return G.some((H)=>{let F=Buffer.from(H,"hex");return K.length===F.length&&dG6(K,F)})}function rg$($){let Z;try{Z=JSON.parse($)}catch{return null}let X=zJ(Z),Q=zJ(zJ(X?.data)?.object);if(!X||typeof X.type!=="string"||!Q)return null;return{id:XH(X.id),type:X.type,created:typeof X.created==="number"?X.created:void 0,livemode:typeof X.livemode==="boolean"?X.livemode:void 0,data:{object:Q}}}function ag$($){switch($){case"active":case"trialing":return"active";case"past_due":return"past_due";default:return"canceled"}}function XH($){return typeof $==="string"?$:void 0}function zJ($){return typeof $==="object"&&$!==null?$:void 0}function lP0($){return typeof $==="number"?new Date($*1000):null}function A91($){return XH($)??XH(zJ($)?.id)}function iG6($){return A91($.subscription)??XH(zJ(zJ($.parent)?.subscription_details)?.subscription)}function pG6($){let Z=lP0($.current_period_end);if(Z)return Z;let X=zJ($.items)?.data;if(!Array.isArray(X))return null;let Q=0;for(let Y of X){let G=zJ(Y)?.current_period_end;if(typeof G==="number"&&G>Q)Q=G}return Q>0?new Date(Q*1000):null}function z91($,Z){let X=lP0($.created);return!!X&&!!Z.lastStripeEventAt&&X<Z.lastStripeEventAt}function P91($,Z){let X=lP0($.created);if(!X)return;return Z.lastStripeEventAt&&Z.lastStripeEventAt>X?void 0:X}async function nG6($,Z){let X=Z.data.object;switch(Z.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":{let Q=XH(zJ(X.metadata)?.orgId);if(!Q)return{handled:!1,reason:"no orgId"};if(XH(zJ(X.metadata)?.kind)==="topup"){if(X.mode!=="payment")return{handled:!1,reason:"topup with wrong mode"};if(XH(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let J=XH(X.id);if(!J)return console.error("stripe webhook: topup session without id",{eventId:Z.id,organizationId:Q}),{handled:!1,reason:"topup session without id"};let W=Number(zJ(X.metadata)?.creditCents);if(!Number.isInteger(W)||W<=0)return console.error("stripe webhook: paid topup with bad metadata \u2014 credit NOT applied",{eventId:Z.id,organizationId:Q,creditCents:zJ(X.metadata)?.creditCents}),{handled:!1,reason:"bad topup metadata"};return{handled:!0,organizationId:Q,topUp:{creditCents:W,referenceId:`stripe-topup:${J}`}}}if(X.mode!=="subscription")return{handled:!1,reason:"not a subscription checkout"};if(XH(X.payment_status)!=="paid")return{handled:!1,reason:"payment not confirmed"};let Y=await $.getBilling(Q);if(!Y)return{handled:!1,reason:"unknown org"};let G=A91(X.subscription);if(Y.stripeSubscriptionId&&G&&Y.stripeSubscriptionId!==G)return console.error("stripe webhook: refused checkout rebind",{organizationId:Q,eventId:Z.id}),{handled:!1,reason:"org already bound to another subscription",orphanSubscriptionId:G};if(z91(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Q,{stripeCustomerId:A91(X.customer),stripeSubscriptionId:G,status:"active",lastStripeEventAt:P91(Z,Y)}),{handled:!0,organizationId:Q}}case"customer.subscription.updated":case"customer.subscription.deleted":{let Q=XH(X.id);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};let G=Z.type==="customer.subscription.deleted";if(!G&&z91(Z,Y))return{handled:!1,reason:"stale event"};let J=G?"canceled":ag$(X.status);return await $.updateStripeState(Y.organizationId,{status:J,currentPeriodEnd:pG6(X),...G&&{stripeSubscriptionId:null},lastStripeEventAt:P91(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}case"invoice.paid":{let Q=iG6(X);if(!Q)return{handled:!1,reason:"no sub id"};let Y=await $.getBillingByStripeSubscriptionId(Q);if(!Y)return{handled:!1,reason:"unknown subscription"};if(z91(Z,Y))return{handled:!1,reason:"stale event"};return await $.updateStripeState(Y.organizationId,{status:"active",currentPeriodEnd:lP0(X.period_end),lastStripeEventAt:P91(Z,Y)}),{handled:!0,organizationId:Y.organizationId}}default:return{handled:!1,reason:`unhandled event ${Z.type}`}}}function tG6($,Z){if(!Z.handled||$.livemode===!1)return null;let X=$.data.object;if(Z.topUp)return{name:"credits_topup_succeeded",organizationId:Z.organizationId,properties:{credit_cents:Z.topUp.creditCents}};switch($.type){case"checkout.session.completed":case"checkout.session.async_payment_succeeded":return{name:"subscription_started",organizationId:Z.organizationId,properties:{}};case"customer.subscription.deleted":return{name:"subscription_canceled",organizationId:Z.organizationId,properties:{}};case"customer.subscription.updated":return{name:"subscription_updated",organizationId:Z.organizationId,properties:{status:ag$(X.status),...typeof X.cancel_at_period_end==="boolean"?{cancel_at_period_end:X.cancel_at_period_end}:{}}};case"invoice.paid":if(X.billing_reason==="subscription_create")return null;return{name:"subscription_renewed",organizationId:Z.organizationId,properties:{}};default:return null}}function tg$($,Z){let X=tG6($,Z);if(!X)return;MY({event:X.name,organizationId:X.organizationId,...$.id?{uuid:Pi1(`stripe:${$.id}:${X.name}`)}:{},...$.created?{timestamp:new Date($.created*1000)}:{},properties:X.properties})}async function sg$($){let Z=new mW(p8().db),X=await nG6(Z,$);if(!(X.handled&&X.topUp))tg$($,X);if(X.handled&&X.topUp)await sB$({organizationId:X.organizationId,amountCents:X.topUp.creditCents,referenceId:X.topUp.referenceId}),tg$($,X);if(!X.handled&&X.orphanSubscriptionId)try{await fa1(X.orphanSubscriptionId),console.error("stripe webhook: canceled orphan subscription",{subscriptionId:X.orphanSubscriptionId,eventId:$.id})}catch(Q){if(!(Q instanceof fY&&(Q.status===400||Q.status===404)))throw Q}return X}var mG6=300;var eg$=w(()=>{fG();M4();X60();cL();fs0()});var oG6=1048576,T91;var $h$=w(()=>{P8();UN();T$();eg$();T91=new U1;T91.post("/webhook",q9({maxSize:oG6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=b0().stripeWebhookSecret;if(!Z)return $.json({error:"stripe billing not configured"},503);let X=await $.req.text();if(!og$(X,$.req.header("stripe-signature"),Z))return $.json({error:"invalid signature"},400);let Y=rg$(X);if(!Y)return $.json({error:"invalid payload"},400);let G=await sg$(Y);return console.log("stripe webhook",{eventId:Y.id,type:Y.type,livemode:Y.livemode,...G}),$.json({received:!0})})});import{timingSafeEqual as rG6}from"crypto";function sG6($,Z,X){if(!Z?.startsWith("sha256="))return!1;let Q=new Bun.CryptoHasher("sha256",X).update($).digest("hex"),Y=Z.slice(7);if(Y.length!==Q.length)return!1;return rG6(Buffer.from(Y),Buffer.from(Q))}var aG6=5242880,R91;var Zh$=w(()=>{P8();UN();kp();R91=new U1;R91.post("/webhook",q9({maxSize:aG6,onError:($)=>$.json({error:"payload too large"},413)}),async($)=>{let Z=process.env.GITHUB_WEBHOOK_SECRET;if(!Z)return $.json({error:"github webhook not configured"},503);let X=await $.req.text();if(!sG6(X,$.req.header("x-hub-signature-256"),Z))return $.json({error:"invalid signature"},400);if($.req.header("x-github-event")!=="push")return $.json({ok:!0,ignored:"event"});let Q;try{Q=JSON.parse(X)}catch{return $.json({error:"invalid payload"},400)}let Y=Q.ref,G=Q.repository?.full_name;if(!Y||!G)return $.json({ok:!0,ignored:"shape"});let W=(await oi0())?.markTenantPoolsDirty(G,Y)??[];return $.json({ok:!0,pools:W})})});function Xh$($,Z){if(Z.startsWith("text/html")||Z.startsWith("image/svg"))$.set("Content-Security-Policy","sandbox allow-scripts allow-modals allow-same-origin")}var Qh$,eG6,$J6,Yh$;var Gh$=w(()=>{P8();W3();Ey();wx();Qh$=new U1,eG6=["range","if-none-match","if-modified-since"],$J6=["content-type","content-length","content-range","accept-ranges","etag","last-modified"];Qh$.get("/:org/files/*",async($)=>{let Z=$.get("studioContext"),X=Z.organization?.id;if(!Z.auth?.user?.id){if(Ah($))return $.redirect(`/login?next=${encodeURIComponent($.req.path)}`,302);throw new $$(401,{message:"Authentication required"})}if(!X)throw new $$(401,{message:"Organization context required"});let Q=$.req.path.replace(/^.*\/files\//,"");if(!Q)throw new $$(400,{message:"Missing file key"});let Y=await Yn(Q,Z);if(!Y)throw new $$(503,{message:"Object storage not configured"});if(Y.startsWith("data:")&&U3()){let K=Y.match(/^data:([^;]+);base64,(.+)$/s);if(!K)throw new $$(500,{message:"Invalid data URL from storage"});let[,H,F]=K,N=Buffer.from(F,"base64"),U=new Headers({"Content-Type":H,"Cache-Control":"private, max-age=86400"});return Xh$(U,H),new Response(N,{status:200,headers:U})}let G=new Headers;for(let K of eG6){let H=$.req.header(K);if(H)G.set(K,H)}let J=await fetch(Y,{headers:G});if(J.status===403||J.status===404)throw new $$(404,{message:"File not found"});if(!J.ok&&J.status!==304&&J.status!==416)throw console.error(`[files] upstream storage error ${J.status} for key:`,Q),new $$(502,{message:"Upstream storage error"});let W=new Headers;for(let K of $J6){let H=J.headers.get(K);if(H)W.set(K,H)}return W.set("Cache-Control","private, max-age=86400"),Xh$(W,W.get("content-type")??""),new Response(J.body,{status:J.status,headers:W})});Yh$=Qh$});var Za=_((S_)=>{var ZJ6=S_&&S_.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),XJ6=S_&&S_.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))ZJ6(Z,$,X)};Object.defineProperty(S_,"__esModule",{value:!0});XJ6(FY(),S_)});var Kh$=_((Jh$)=>{Object.defineProperty(Jh$,"__esModule",{value:!0});Jh$.version=void 0;Jh$.version="3.4.0"});var Nh$=_((QH)=>{var QJ6=QH&&QH.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(QH,"__esModule",{value:!0});QH.NodeTransport=QH.VERSION=void 0;QH.nodeResolveHost=HJ6;var t6=Za(),YJ6=z0("net"),I91=z0("tls"),GJ6=z0("path"),Hh$=z0("fs"),JJ6=QJ6(z0("dns")),WJ6=Kh$();QH.VERSION=WJ6.version;var KJ6="nats.js";class Fh${socket;version;lang;yields=[];signal=(0,t6.deferred)();closedNotification=(0,t6.deferred)();options;connected=!1;tlsName="";done=!1;closeError;constructor(){this.lang=KJ6,this.version=QH.VERSION}async connect($,Z){this.tlsName=$.tlsName,this.options=Z;let{tls:X}=this.options,{handshakeFirst:Q}=X||{};try{if(Q===!0)this.socket=await this.tlsFirst($);else this.socket=await this.dial($);if(this.done)this.socket?.destroy();let Y=await this.peekInfo();(0,t6.checkOptions)(Y,Z);let{tls_required:G,tls_available:J}=Y,W=J===!0&&Z.tls!==null;if(!Q&&(G||W))this.socket=await this.startTLS();if(this.done)this.socket?.destroy();if(G&&this.socket.encrypted!==!0)throw t6.errors.InvalidArgumentError.format("tls","is not available on this server");return this.connected=!0,this.setupHandlers(),this.signal.resolve(),Promise.resolve()}catch(Y){let G=Y;if(!G)G=new t6.errors.ConnectionError("error connecting - node provided an undefined error");let{code:J}=G,W=J==="ECONNREFUSED"?new t6.errors.ConnectionError("connection refused",{cause:G}):G;throw this.socket?.destroy(),W}}dial($){let Z=(0,t6.deferred)(),X,Q=(0,YJ6.createConnection)($.port,$.hostname,()=>{Z.resolve(Q),Q.removeAllListeners()});return Q.on("error",(Y)=>{X=Y}),Q.on("close",()=>{Q.removeAllListeners(),Z.reject(X)}),Q.setNoDelay(!0),Z}get isClosed(){return this.done}close($){return this._closed($,!1)}peekInfo(){let $=(0,t6.deferred)(),Z;return this.socket.on("data",(X)=>{this.yields.push(X);let Q=t6.DataBuffer.concat(...this.yields),Y=(0,t6.extractProtocolMessage)(Q);if(Y!=="")try{let G=t6.INFO.exec(Y);if(!G)throw Error("unexpected response from server");let J=JSON.parse(G[1]);$.resolve(J)}catch(G){$.reject(G)}finally{this.socket.removeAllListeners()}}),this.socket.on("error",(X)=>{Z=X}),this.socket.on("close",()=>{this.socket.removeAllListeners(),$.reject(Z)}),$}loadFile($){if(!$)return Promise.resolve();let Z=(0,t6.deferred)();try{if($=(0,GJ6.resolve)($),!(0,Hh$.existsSync)($))Z.reject(Error(`${$} doesn't exist`));(0,Hh$.readFile)($,(X,Q)=>{if(X)return Z.reject(X);Z.resolve(Q)})}catch(X){Z.reject(X)}return Z}async loadClientCerts(){let $={},{certFile:Z,cert:X,caFile:Q,ca:Y,keyFile:G,key:J}=this.options.tls;try{if(Z){let W=await this.loadFile(Z);if(W)$.cert=W}else if(X)$.cert=X;if(G){let W=await this.loadFile(G);if(W)$.key=W}else if(J)$.key=J;if(Q){let W=await this.loadFile(Q);if(W)$.ca=[W]}else if(Y)$.ca=Y;return Promise.resolve($)}catch(W){return Promise.reject(W)}}async tlsFirst($){let Z,X={servername:this.tlsName,rejectUnauthorized:!0};if(this.socket)X.socket=this.socket;if(typeof this.options.tls==="object")try{let Y=await this.loadClientCerts()||{};X=(0,t6.extend)(X,this.options.tls,Y)}catch(Y){return Promise.reject(new t6.errors.ConnectionError(Y.message,{cause:Y}))}let Q=(0,t6.deferred)();try{let Y=(0,I91.connect)($.port,$.hostname,X,()=>{Y.removeAllListeners(),Q.resolve(Y)});Y.on("error",(G)=>{Z=G}),Y.on("secureConnect",()=>{if(X.rejectUnauthorized===!1)return;if(!Y.authorized)throw Y.authorizationError}),Y.on("close",()=>{Q.reject(Z),Y.removeAllListeners()}),Y.setNoDelay(!0)}catch(Y){Q.reject(new t6.errors.ConnectionError(Y.message,{cause:Y}))}return Q}async startTLS(){let $,Z={socket:this.socket,servername:this.tlsName,rejectUnauthorized:!0};if(typeof this.options.tls==="object")try{let Q=await this.loadClientCerts()||{};Z=(0,t6.extend)(Z,this.options.tls,Q)}catch(Q){return Promise.reject(new t6.errors.ConnectionError(Q.message,{cause:Q}))}let X=(0,t6.deferred)();try{let Q=(0,I91.connect)(Z,()=>{Q.removeAllListeners(),X.resolve(Q)});Q.on("error",(Y)=>{$=Y}),Q.on("secureConnect",()=>{if(Z.rejectUnauthorized===!1)return;if(!Q.authorized)throw Q.authorizationError}),Q.on("close",()=>{X.reject($),Q.removeAllListeners()})}catch(Q){X.reject(new t6.errors.ConnectionError(Q.message,{cause:Q}))}return X}setupHandlers(){let $;this.socket.on("data",(Z)=>{return this.yields.push(Z),this.signal.resolve()}),this.socket.on("error",(Z)=>{$=Z}),this.socket.on("end",()=>{if(this.socket?.destroyed)return;this.socket?.write(new Uint8Array(0),()=>{this.socket?.end()})}),this.socket.on("close",()=>{this._closed($,!1)})}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.yields.length===0)await this.signal;let $=this.yields;this.yields=[];for(let Z=0;Z<$.length;Z++){if(this.options.debug)console.info(`> ${(0,t6.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,t6.deferred)()}}discard(){if(this.done=!0,this.socket)try{this.socket.removeAllListeners(),this.socket.destroy()}catch{}}disconnect(){this._closed(void 0,!0).then().catch()}isEncrypted(){return this.socket instanceof I91.TLSSocket}_send($){if(this.isClosed||this.socket===void 0)return Promise.resolve();if(this.options.debug)console.info(`< ${(0,t6.render)($)}`);let Z=(0,t6.deferred)();try{this.socket.write($,(X)=>{if(X){if(this.options.debug)console.error(`!!! ${(0,t6.render)($)}: ${X}`);return Z.reject(X)}return Z.resolve()})}catch(X){if(this.options.debug)console.error(`!!! ${(0,t6.render)($)}: ${X}`);Z.reject(X)}return Z}send($){this._send($).catch((X)=>{})}async _closed($,Z=!0){if(!this.connected)return;if(this.done){this.socket?.destroy();return}if(this.closeError=$,!$&&this.socket&&Z)try{await this._send(new TextEncoder().encode(""))}catch(X){if(this.options.debug)console.log("transport close terminated with an error",X)}try{if(this.socket)this.socket.removeAllListeners(),this.socket?.destroy(),this.socket=void 0}catch(X){console.log(X)}this.done=!0,this.closedNotification.resolve(this.closeError)}closed(){return this.closedNotification}}QH.NodeTransport=Fh$;function HJ6($){let Z=(0,t6.deferred)();return JJ6.default.lookup($,{all:!0},(X,Q)=>{if(X){Z.reject(X);return}let Y=[];for(let G of Q)Y.push(G.address);if(Y.length===0)Y.push($);Z.resolve(Y)}),Z}});var Dh$=_((wh$)=>{Object.defineProperty(wh$,"__esModule",{value:!0});wh$.connect=FJ6;var Uh$=Nh$(),Oh$=Za(),Bh$=Za();function FJ6($={}){if((0,Bh$.hasWsProtocol)($))return Promise.reject(Bh$.errors.InvalidArgumentError.format("servers","node client doesn't support websockets, use the 'wsconnect' function instead"));return(0,Oh$.setTransportFactory)({factory:()=>{return new Uh$.NodeTransport},dnsResolveFn:Uh$.nodeResolveHost}),Oh$.NatsConnectionImpl.connect($)}});var Lh$=_((RN)=>{var UJ6=RN&&RN.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),OJ6=RN&&RN.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))UJ6(Z,$,X)};Object.defineProperty(RN,"__esModule",{value:!0});RN.connect=void 0;var BJ6=Dh$();Object.defineProperty(RN,"connect",{enumerable:!0,get:function(){return BJ6.connect}});OJ6(Za(),RN)});function Ph$($){let Z=$?.connectFn??EJ6,X=null,Q=null,Y=!1,G=!1,J=!1,W=[];function K(){return X!==null&&!X.isClosed()&&!X.isDraining()&&!J}function H(){console.log(`[NatsProvider] fireReady: ${W.length} callbacks`);for(let U of W)try{U()}catch{}}function F(U){(async()=>{for await(let O of U.status())if(O.type==="disconnect")console.log("[NatsProvider] Disconnected"),J=!0;else if(O.type==="reconnect")console.log("[NatsProvider] Reconnected, re-firing ready callbacks"),J=!1,Q=null,H()})().catch(()=>{})}async function N(U,O){let B=0;while(!G)try{X=await Z({servers:U,timeout:LJ6,reconnect:!0,maxReconnectAttempts:-1,...O?{authenticator:O}:{}}),console.log(`[NatsProvider] Connected to ${X.getServer()} after ${B} attempt(s)`),Q=null,J=!1,F(X),H();return}catch{B++;let D=pZ(DJ6,wJ6,B-1,2,0.5);await q$(D)}}return{init(U,O){if(Y)return;Y=!0,G=!1;let B=O?.creds?Eh$.credsAuthenticator(new TextEncoder().encode(O.creds)):void 0;N(U,B).catch(()=>{})},isConnected(){return K()},getConnection(){return K()?X:null},getJetStream(){if(!K())return null;if(!Q)Q=zh$.jetstream(X);return Q},onReady(U){if(W.push(U),K())try{U()}catch{}},async drain(){if(G=!0,Y=!1,Q=null,J=!1,X){let U=X;X=null,await U.drain().catch(()=>{})}}}}function EJ6($){return jh$.connect($)}var Eh$,jh$,zh$,wJ6=100,DJ6=3000,LJ6=3000;var Ah$=w(()=>{u4();Eh$=V(ju(),1),jh$=V(Lh$(),1),zh$=V(fw(),1)});function q91($,Z){return`${$}.${Z}`}class M91{cache;constructor($){this.cache=Hh({ttlMs:$?.ttlMs??jJ6,maxSize:$?.maxSize??zJ6})}async get($,Z){return this.cache.get(q91($,Z))??null}async set($,Z,X){this.cache.set(q91($,Z),X)}async invalidate($,Z){this.cache.delete(q91($,Z))}teardown(){this.cache.clear()}}var jJ6=600000,zJ6=5000;var Th$=()=>{};function dP0($,Z){return`${$}:${Z}`}function k91($){let Z=Hh({ttlMs:$?.ttlMs??PJ6,maxSize:$?.maxSize??AJ6}),X=$?.getConnection,Q=crypto.randomUUID(),Y=new TextEncoder,G=new TextDecoder,J=null;function W(K,H){let F=X?.();if(!F)return;try{F.publish(Rh$,Y.encode(JSON.stringify({organizationId:K,keyId:H,originId:Q})))}catch(N){console.warn("[ProviderKeyCache] Publish failed (non-critical):",N)}}return{get(K,H){return Z.get(dP0(K,H))},set(K,H,F){Z.set(dP0(K,H),F)},invalidate(K,H){Z.delete(dP0(K,H)),W(K,H)},start(){if(J)return;let K=X?.();if(!K)return;J=K.subscribe(Rh$),(async()=>{for await(let H of J)try{let F=JSON.parse(G.decode(H.data));if(F.originId===Q)continue;Z.delete(dP0(F.organizationId,F.keyId))}catch{}})().catch(console.error)},teardown(){J?.unsubscribe(),J=null,Z.clear()}}}var Rh$="studio.ai-provider-keys.invalidate",PJ6=30000,AJ6=5000;var Ih$=()=>{};class V91{options;subscriptions=[];onCancel=null;encoder=new TextEncoder;originId=crypto.randomUUID();seenMessageIds=new Set;constructor($){this.options=$}async start($){if($)this.onCancel=$;if(this.subscriptions.length>0)return;if(!this.onCancel)return;let Z=this.options.getConnection();if(!Z)return;let X=new TextDecoder;this.subscriptions=qh$.map((Q)=>Z.subscribe(Q));for(let Q of this.subscriptions)(async()=>{for await(let Y of Q)try{let G=JSON.parse(X.decode(Y.data));if(G.originId===this.originId)continue;if(G.messageId&&this.hasSeen(G.messageId))continue;this.onCancel?.(G.taskId)}catch{}})().catch(console.error)}broadcast($){if(/[.*>\s]/.test($)){console.warn("[NatsCancelBroadcast] Invalid threadId, skipping broadcast");return}this.onCancel?.($);try{let Z=this.options.getConnection();if(!Z)return;let X=this.encoder.encode(JSON.stringify({taskId:$,originId:this.originId,messageId:crypto.randomUUID()}));for(let Q of qh$)Z.publish(Q,X)}catch(Z){console.warn("[NatsCancelBroadcast] Publish failed (non-critical):",Z)}}publishControlFrame($,Z){}async stop(){for(let $ of this.subscriptions)$.unsubscribe();this.subscriptions=[],this.seenMessageIds.clear(),this.onCancel=null}hasSeen($){if(this.seenMessageIds.has($))return!0;if(this.seenMessageIds.add($),this.seenMessageIds.size>1000){let Z=this.seenMessageIds.values().next().value;if(Z)this.seenMessageIds.delete(Z)}return!1}}var qh$;var Mh$=w(()=>{qh$=["studio.decopilot.cancel","mesh.decopilot.cancel"]});var kh$=($)=>{let Z;return()=>Z??=$()},S91,C91;var Vh$=w(()=>{b6();S91=kh$(()=>S$.createHistogram("decopilot.stream.encode_ms",{description:"Per-chunk JSON.stringify+encode time for decopilot stream",unit:"ms"})),C91=kh$(()=>S$.createCounter("decopilot.stream.published_chunks",{description:"Logical decopilot stream chunks published to JetStream",unit:"{chunks}"}))});function VJ6(){return{name:lF,subjects:[`${Fw0}.>`],storage:GW.StorageType.File,max_age:IJ6,max_bytes:MJ6,max_msgs_per_subject:kJ6,discard:GW.DiscardPolicy.Old,retention:GW.RetentionPolicy.Limits,duplicate_window:qJ6,num_replicas:1}}class _h${chunks=0;encodeMs=0;maxMs=0;bytes=0;windowStart=performance.now();constructor(){setInterval(()=>this.flush(),1e4).unref?.()}record($,Z){if(this.chunks++,this.encodeMs+=$,$>this.maxMs)this.maxMs=$;this.bytes+=Z}flush(){let $=performance.now(),Z=$-this.windowStart;if(this.chunks>0&&Z>0)console.warn(JSON.stringify({msg:"stream-encode-trace",windowMs:Math.round(Z),chunks:this.chunks,encodeMs:Math.round(this.encodeMs),pctOfLoop:+(this.encodeMs/Z*100).toFixed(1),maxChunkMs:+this.maxMs.toFixed(2),mbEncoded:+(this.bytes/1048576).toFixed(2)}));this.chunks=0,this.encodeMs=0,this.maxMs=0,this.bytes=0,this.windowStart=$}}function Sh$($){let Z=Ch$.headers();for(let[X,Q]of Object.entries($))Z.set(X,Q);return Z}function vJ6($,Z){let X=0;return{publish(Q,Y,G,J){Q.publish(Y,G,J?{headers:J}:void 0).catch((W)=>{if(X++,RJ6().add(1,{"org.id":Z??"unknown"}),X===1||X%100===0)console.warn(`[Decopilot] JetStream publish failed for thread ${$} (${X} total):`,W)})},get errorCount(){return X}}}function fJ6($){if(!($ instanceof Error))return!1;if($.name==="TimeoutError")return!0;return/timeout|no responders|503/i.test($.message)}class _91{options;js=null;jsm=null;constructor($){this.options=$}async init(){let $=this.options.getConnection();if(!$){console.log("[Decopilot] StreamBuffer.init skipped: NATS not connected yet");return}let Z=VJ6(),X=await F9(async()=>{let Q=this.options.getJetStreamManager?await this.options.getJetStreamManager():await GW.jetstreamManager($);try{await Q.streams.info(lF),await Q.streams.update(lF,Z)}catch(Y){if(Y instanceof Error&&Y.message.includes("stream not found"))await Q.streams.add(Z);else if(Y instanceof Error&&/can ?not change.*storage|storage type/i.test(Y.message))await Q.streams.delete(lF),await Q.streams.add(Z);else throw Y}return Q},{maxAttempts:5,minTimeout:250,maxTimeout:4000,jitter:0.5,isRetriable:fJ6});this.js=this.options.getJetStream(),this.jsm=X,console.log(`[Decopilot] StreamBuffer.init ${this.js?"ready":"degraded (js=null)"}`)}pump($,Z,X,Q){let Y=this.js;if(!Y)return console.warn(`[Decopilot] pump: JetStream client unavailable for thread ${Z}; chunks NOT published to NATS`),Promise.resolve();let G=vJ6(Z,Q),J=!1,W=()=>{if(J)return;J=!0;let H=SH$(Z);Y.publish(H.subject,H.data).catch(()=>{})};X.addEventListener("abort",W,{once:!0});let K=(H)=>{let F=performance.now(),N=Ct0(H,{runId:Z}),U=performance.now()-F;if(S91().record(U),C91().add(1,{"org.id":Q??"unknown"}),_J6?.record(U,N.reduce((O,B)=>O+B.data.length,0)),N.length===0){console.warn(`[Decopilot] dropping oversized stream chunk for thread ${Z}`);return}for(let O of N)G.publish(Y,O.subject,O.data,O.headers?Sh$(O.headers):void 0)};return(async()=>{let H=$.getReader(),F=0,N=0,U;try{while(!0){let{done:O,value:B}=await H.read();if(O)break;if(K(B),N++,++F>=64)F=0,await new Promise((D)=>setImmediate(D))}}catch(O){U=O,console.warn(`[Decopilot] stream pump error for thread ${Z}:`,O?.message??O)}finally{if(H.releaseLock(),W(),CJ6)console.warn(JSON.stringify({msg:"decopilot-stream-diag",event:"pump-done",taskId:Z,publishedChunks:N,publishErrors:G.errorCount}))}if(U!==void 0)throw U})()}async publishRawChunk($,Z,X){let Q=this.js;if(!Q)return!1;let Y=performance.now(),G=Ct0(Z,{runId:$,dedup:X});if(S91().record(performance.now()-Y),C91().add(1),G.length===0)return console.warn(`[Decopilot] dropping oversized raw chunk for thread ${$} (> MAX_CHUNKED_BYTES)`),!0;for(let J of G)await Q.publish(J.subject,J.data,{...J.headers?{headers:Sh$(J.headers)}:{},...J.msgId?{msgID:J.msgId}:{}});return!0}async publishDone($,Z,X){let Q=this.js;if(!Q)return!1;let Y=VH$({runId:$,fenceToken:Z,finalSeq:X});return await Q.publish(Y.subject,Y.data,{msgID:Y.msgId}),!0}async createTailStream($,Z,X){let Q=this.js;if(!Q)return console.warn(`[Decopilot] createTailStream: JetStream client unavailable for thread ${$}; no live tail`),null;let Y=X?.deliverPolicy==="new"?GW.DeliverPolicy.New:GW.DeliverPolicy.All,G=X?.closeOnDone??!1,J=IB($),W;try{W=await(await Q.consumers.get(lF,{filter_subjects:J,deliver_policy:Y})).consume()}catch(D){return console.warn("[Decopilot] JetStream tail unavailable (non-critical):",D?.message??D),null}let F=ww0({messages:async function*(){try{for await(let D of W)yield{subject:D.subject,data:D.data,headers:D.headers}}finally{W.stop()}}(),onCancel:()=>W.stop()}).pipeThrough(Nw0()).pipeThrough(Uw0()).getReader(),N=!1,U=()=>{if(N)return;N=!0;try{F.releaseLock()}catch{}},O=!1,B=()=>{if(O)return;O=!0,W.stop(),F.cancel().catch(()=>{}),U()};return Z?.addEventListener("abort",B,{once:!0}),new ReadableStream({async pull(D){for(;;){let{done:L,value:E}=await F.read();if(L){B(),D.close();return}let j=E;if(j.kind==="done"){if(G){B(),D.close();return}continue}D.enqueue(j.chunk);return}},cancel(){B()}})}purge($){if(!this.jsm)return;this.jsm.streams.purge(lF,{filter:IB($)}).catch(()=>{})}teardown(){this.js=null,this.jsm=null}}var GW,Ch$,TJ6=($)=>{let Z;return()=>Z??=$()},RJ6,IJ6=86400000000000,qJ6=120000000000,MJ6=4294967296,kJ6=500000,SJ6,CJ6,_J6;var vh$=w(()=>{u4();_t0();Dw0();Ow0();b6();Vh$();GW=V(fw(),1),Ch$=V(ju(),1),RJ6=TJ6(()=>S$.createCounter("decopilot.stream.publish_errors",{description:"Number of JetStream publish failures for decopilot stream chunks",unit:"{errors}"}));SJ6=process.env.STREAM_ENCODE_TRACE==="1",CJ6=process.env.DECOPILOT_STREAM_TRACE==="1";_J6=SJ6?new _h$:null});function mP0($,Z,X,Q){if(!Q)return!1;return $.emit(Z,MW(X,Q.status,{title:Q.title??void 0,virtualMcpId:Q.virtual_mcp_id??void 0,createdBy:Q.created_by??void 0,triggerId:Q.trigger_id??null,branch:Q.branch??null,harnessId:Q.harness_id??void 0,createdAt:Q.created_at,updatedAt:Q.updated_at})),!0}var fh$=w(()=>{U8()});class v91{storage;options;timer=null;constructor($,Z={}){this.storage=$;this.options=Z}start(){if(this.timer)return;let $=this.options.intervalMs??300000;this.timer=setInterval(()=>{this.runOnce()},$)}async runOnce(){let $=this.options.staleAfterMs??3600000;try{let Z=await this.storage.sweepAbandoned($);if(Z>0)console.log(`[async-research-sweeper] marked ${Z} stale jobs as abandoned`);return Z}catch(Z){return console.error("[async-research-sweeper] sweep failed",Z),0}}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}function cJ6($){return $ instanceof p7}function lJ6($,Z){return Z-$>=hJ6}class f91{taskBoard;contextFactory;billing;options;timer=null;running=!1;cursor=null;constructor($,Z,X,Q={}){this.taskBoard=$;this.contextFactory=Z;this.billing=X;this.options=Q}start(){if(this.timer)return;let $=this.options.intervalMs??bJ6;this.timer=setInterval(()=>{this.runOnce()},$),this.timer.unref()}async runOnce(){if(this.running)return 0;this.running=!0;let $=0;try{let Z=this.options.batchSize??yJ6,X=this.options.itemIntervalMs??xJ6,Q=new Date(Date.now()-X),Y=await this.taskBoard.listItemsPendingReview(Z,this.cursor,Q),G=Y.at(-1);this.cursor=Y.length===Z&&G?{updatedAt:G.updatedAt,id:G.id}:null;for(let{id:J,organizationId:W}of Y)try{if(await this.reconcileItem(J,W,Q))$++}catch(K){console.error(`[task-board-review-sweeper] ${J} failed`,K)}await this.reapNeverStartedThreads(Z),$+=await this.dispatchDueRetries(Z),await this.reactToUnhandledFailures(Z)}catch(Z){console.error("[task-board-review-sweeper] sweep failed",Z)}finally{this.running=!1}return $}async reapNeverStartedThreads($){try{let Z=await this.taskBoard.failNeverStartedLinkedThreads($,new Date(Date.now()-Tn0),Bo0);for(let X of Z)console.warn(`[task-board-review-sweeper] failed never-started thread ${X.threadId} on ${X.itemId}`)}catch(Z){console.error("[task-board-review-sweeper] reaping failed",Z)}}async reactToUnhandledFailures($){let Z=await this.taskBoard.listItemsStuckAfterFailure($,new Date(Date.now()-uJ6));for(let{id:X,organizationId:Q,threadId:Y}of Z)try{console.warn(`[task-board-review-sweeper] reacting to an unhandled failure on ${X}`),await $t0(this.taskBoard,Y,Q),await Zt0(this.taskBoard,this.billing,Y,Q)}catch(G){console.error(`[task-board-review-sweeper] unhandled-failure reaction for ${X} failed`,G)}}async dispatchDueRetries($){let Z=0,X=await this.taskBoard.listItemsDueForRetry($,new Date);for(let{id:Q,organizationId:Y,attempts:G}of X)try{if(!await this.taskBoard.claimDueRetry(Q,Y,new Date))continue;let J=await this.taskBoard.getById(Q,Y);if(!J||J.status!=="in_progress"||J.assigneeId!==n8)continue;let W=await this.contextFactory(Y,J.assignedBy??J.createdBy);if(!W)continue;await dF(W,J,{runClass:"retry"}),Z++,console.warn(`[task-board-review-sweeper] re-dispatched ${Q} after a failure (attempt ${G})`)}catch(J){if(console.error(`[task-board-review-sweeper] retry dispatch for ${Q} failed`,J),cJ6(J)){await this.returnToTodo(Q,Y,J instanceof Error?J.message:String(J));continue}await this.taskBoard.scheduleRunRetry(Q,Y,G,new Date(Date.now()+gJ6)).catch((W)=>console.error(`[task-board-review-sweeper] re-arming ${Q} failed`,W))}return Z}async returnToTodo($,Z,X){try{let Q=await this.taskBoard.getById($,Z);if(!Q||Q.status!=="in_progress")return;let Y=await this.taskBoard.returnToTodoAfterFailure($,Z,Q.updatedBy);if(!Y)return;await this.taskBoard.recordActivity({taskBoardItemId:$,action:"status_changed",actorId:null,data:{from:"in_progress",to:"todo",reason:X}}).catch(()=>{}),A8(Z,Y)}catch(Q){console.error(`[task-board-review-sweeper] returning ${$} to todo failed`,Q)}}async handOffReviewWithoutPr($,Z){let X=await this.taskBoard.listActivity(Z.id,Z.organizationId);if(!lJ6(wF(X),Date.now()))return;await IK($,Z,"no pull request is linked to this task \u2014 there is nothing for a "+"reviewer to review")}async reconcileItem($,Z,X){if(!await this.taskBoard.claimSweep($,Z,X))return!1;let Q=await this.taskBoard.getById($,Z);if(!Q)return!1;if(Q.status!=="in_review")return!1;let Y=Q.assigneeId===n8,G=await this.taskBoard.listPrs($,Z),J=await this.contextFactory(Z,Q.assignedBy??Q.createdBy);if(!J)return!1;if(G.length===0){if(Y)await this.handOffReviewWithoutPr(J,Q);return!1}if(await lF$(J,Q))return!0;if(!Y)return!1;let W=await Promise.all(G.map(async(K)=>({...K,...await _y(Z,K)})));if(W.every((K)=>K.state===null))console.warn(`[task-board-review-sweeper] ${$}: no live PR state from GitHub (${W.length} PR(s)) \u2014 proceeding on unknown`);if(!Fo0(W))return!1;return await Aw0(J,Q,{previewMatchesHead:No0(W)}),!0}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null}}var bJ6=60000,xJ6=300000,yJ6=50,gJ6=60000,hJ6=900000,uJ6=120000;var bh$=w(()=>{L9();Xo0();hF();Rn();Y9();L3();wo0();MK();En()});import{readdir as dJ6,rm as iP0}from"fs/promises";import{join as pP0}from"path";async function nP0($){let Z=new Date;Z.setUTCDate(Z.getUTCDate()-mJ6),Z.setUTCHours(0,0,0,0);let X=0;try{let Q=await C_($);for(let Y of Q)if(/^\d{4}$/.test(Y))X+=await xh$($,Y,Z);else if(!Y.startsWith(".")){let G=pP0($,Y),J=await C_(G);for(let K of J){if(!/^\d{4}$/.test(K))continue;X+=await xh$(G,K,Z)}if((await C_(G)).length===0)await iP0(G,{recursive:!0,force:!0})}}catch(Q){console.warn("monitoring retention cleanup failed:",Q)}return X}async function xh$($,Z,X){let Q=0,Y=pP0($,Z),G=await C_(Y);for(let W of G){if(!/^\d{2}$/.test(W))continue;let K=pP0(Y,W),H=await C_(K);for(let N of H){if(!/^\d{2}$/.test(N))continue;let U=new Date(`${Z}-${W}-${N}T00:00:00Z`);if(isNaN(U.getTime()))continue;if(U<X){let O=pP0(K,N);await iP0(O,{recursive:!0,force:!0}),Q++}}if((await C_(K)).length===0)await iP0(K,{recursive:!0,force:!0})}if((await C_(Y)).length===0)await iP0(Y,{recursive:!0,force:!0});return Q}async function C_($){try{return(await dJ6($)).filter((X)=>!X.startsWith("."))}catch{return[]}}var mJ6=30;var b91=()=>{};import{DBOS as x91,SchedulerMode as iJ6}from"@dbos-inc/dbos-sdk";async function nJ6(){let $=[IJ(),__(),WH()],Z=0;for(let X of $)try{Z+=await nP0(X)}catch(Q){console.error("[monitoring-retention] cleanup failed:",Q)}return console.log(`[monitoring-retention] deleted ${Z} day-dir(s) across ${$.length} signal dir(s)`),{deleted:Z,dirs:$.length}}async function tJ6($,Z){await x91.runStep(()=>nJ6(),{name:"monitoringRetention"})}function gh$(){if(yh$)return;yh$=!0;let $=x91.registerWorkflow(tJ6,{name:"monitoringRetentionWorkflow"});x91.registerScheduled($,{name:"monitoringRetentionWorkflow",crontab:pJ6,mode:iJ6.ExactlyOncePerIntervalWhenActive})}var pJ6="23 4 * * *",yh$=!1;var hh$=w(()=>{JY();b91()});function uh$($){return async(Z,X)=>{let Q=await $.db.selectFrom("member").innerJoin("organization","organization.id","member.organizationId").select(["member.role","organization.id as orgId","organization.slug as orgSlug","organization.name as orgName"]).where("member.userId","=",X).where("member.organizationId","=",Z).executeTakeFirst();if(!Q)return console.warn(`[automationContextFactory] User ${X} not found in org ${Z} \u2014 returning null`),null;let Y=await sG.create();Y.auth.user={id:X,role:Q.role},Y.organization={id:Q.orgId,slug:Q.orgSlug,name:Q.orgName};let G=await x41($.db,Z,Q.role);return Y.boundAuth=b41({auth:Y.authInstance,headers:new Headers,role:Q.role,permissions:G,userId:X}),Y.access=new BL(X,void 0,Y.boundAuth,Q.role,"self"),zB(Y,{id:Q.orgId,slug:Q.orgSlug}),Y}}var ch$=w(()=>{wL();QC()});function oJ6(){return{services:[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}],migrationsStatus:"pending",serverUrl:null,logs:[]}}function aJ6(){for(let $ of rJ6)$()}function lh$($){let Z=[...y91.logs,$];y91={...y91,logs:Z.length>500?Z.slice(-500):Z},aJ6()}function g91(){return sJ6}var y91,rJ6,sJ6=!1;var h91=w(()=>{y91=oJ6(),rJ6=new Set});import{EventEmitter as eJ6}from"events";var u91;var dh$=w(()=>{h91();u91=new eJ6;u91.on("request",($)=>{lh$($)})});function mh$(){return async($,Z)=>{let X=Date.now(),Q=$.req.method,Y=$.req.path;if(Y==="/api/auth/get-session"||Y.includes("favicon")){await Z();return}let G="",J=!1;if(Y.startsWith("/mcp")&&Q==="POST"){J=!0;try{if($.req.header("Content-Type")?.includes("application/json")){let U=await $.req.raw.clone().json();if(U.method==="tools/call"&&U.params?.name){let O=oh(U.params.name),B=U.params.arguments||{},D=Object.keys(B).map((E)=>oh(E)),L=D.length>0?D.slice(0,3).join(",")+(D.length>3?"\u2026":""):"";G=`${Y5.tool}${O}${Y5.dim}(${L})${Y5.reset}`}else if(U.method)G=`${Y5.dim}${oh(U.method)}${Y5.reset}`}}catch{}}let W=oh(Y);if(Y.startsWith("/mcp/conn_")){let F=Y.split("/")[2]??"";W=`/mcp/${Y5.mcp}${oh(F.slice(0,12))}\u2026${Y5.reset}`}else if(Y==="/mcp")W=`${Y5.mcp}/mcp${Y5.reset}`;else if(Y==="/mcp/registry")W=`${Y5.mcp}/mcp/registry${Y5.reset}`;let K=Z36(Q),H=J?"\u25C0":"\u2190";if(!g91())console.log(`${Y5.dim}${H}${Y5.reset} ${K}${Q}${Y5.reset} ${W}${G?` ${G}`:""}`);try{await Z()}finally{let F=Date.now()-X,N=$.res.status,U=$36(N),O=F<1000?`${F}ms`:`${(F/1000).toFixed(1)}s`,B=J?"\u25B6":"\u2192";if(!g91())console.log(`${Y5.dim}${B}${Y5.reset} ${K}${Q}${Y5.reset} ${W}${G?` ${G}`:""} ${U}${N}${Y5.reset} ${Y5.duration}${O}${Y5.reset}`);u91.emit("request",{method:Q,path:oh(Y),status:N,duration:F,timestamp:new Date})}}}var Y5,$36=($)=>{if($>=500)return Y5.serverError;if($>=400)return Y5.clientError;if($>=300)return Y5.redirect;return Y5.ok},Z36=($)=>{return Y5[$]||Y5.reset},oh=($)=>{return $.replace(/\r/g,"").replace(/\n/g,"").replace(/\x1b\[[0-9;]*m/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"")};var ih$=w(()=>{h91();dh$();Y5={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",GET:"\x1B[36m",POST:"\x1B[33m",PUT:"\x1B[35m",DELETE:"\x1B[31m",ok:"\x1B[32m",redirect:"\x1B[36m",clientError:"\x1B[33m",serverError:"\x1B[31m",mcp:"\x1B[35m",tool:"\x1B[96m",duration:"\x1B[90m"}});import{createHmac as oh$}from"crypto";import{mkdir as X36,readdir as Q36,rm as ph$,stat as rh$}from"fs/promises";import{join as l91,relative as Y36}from"path";import{z as z$}from"zod";function sh$($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return l91(G36,Z)}function eh$($){return $.replace(/^\/+/,"").replace(/\.\./g,"")}function c91($,Z){let X=sh$($),Q=eh$(Z);return l91(X,Q)}function J36($,Z,X,Q){let Y=b0().encryptionKey||"dev-secret",G=`${$}:${Z}:${X}:${Q}`;return oh$("sha256",Y).update(G).digest("hex")}function th$($,Z,X,Q,Y){let G=Math.floor(Date.now()/1000)+Q,J=J36(Z,X,G,Y),W=new URL(`/api/dev-assets/${Z}/${eh$(X)}`,$);return W.searchParams.set("expires",G.toString()),W.searchParams.set("signature",J),W.searchParams.set("method",Y),W.toString()}function $u$($,Z,X){let Q=`${$}:${Z.getTime()}:${X}`;return`"${oh$("md5","etag").update(Q).digest("hex")}"`}async function Zu$($,Z,X,Q,Y){try{let G=await Q36($,{withFileTypes:!0});for(let J of G){let W=l91($,J.name),H=Y36(Z,W).replace(/\\/g,"/");if(X&&!H.startsWith(X))continue;if(J.isDirectory())if(Q){let F=H+"/";if(!X||F.startsWith(X)){if(!(X?H.slice(X.length):H).includes("/"))Y.commonPrefixes.add(F)}}else await Zu$(W,Z,X,Q,Y);else if(J.isFile()){if(Q&&X){let F=H.slice(X.length);if(F.includes(Q)){let N=F.indexOf(Q),U=X+F.slice(0,N+1);Y.commonPrefixes.add(U);continue}}try{let F=await rh$(W);Y.objects.push({key:H,size:F.size,lastModified:F.mtime.toISOString(),etag:$u$(W,F.mtime,F.size)})}catch{}}}}catch{}}function Xu$($,Z){let Q=t($).id;return[{name:"LIST_OBJECTS",description:"List objects in the local assets directory with pagination support",inputSchema:z$.object({prefix:z$.string().optional(),maxKeys:z$.number().optional().default(1000),continuationToken:z$.string().optional(),delimiter:z$.string().optional()}),outputSchema:z$.object({objects:z$.array(z$.object({key:z$.string(),size:z$.number(),lastModified:z$.string(),etag:z$.string()})),nextContinuationToken:z$.string().optional(),isTruncated:z$.boolean(),commonPrefixes:z$.array(z$.string()).optional()}),handler:async(Y)=>{let G=Y,J=G.prefix||"",W=G.maxKeys??1000,K=G.delimiter,H=G.continuationToken,F=sh$(Q);await X36(F,{recursive:!0});let N={objects:[],commonPrefixes:new Set};await Zu$(F,F,J,K,N),N.objects.sort((L,E)=>L.key.localeCompare(E.key));let U=0;if(H){if(U=N.objects.findIndex((L)=>L.key>H),U===-1)U=N.objects.length}let O=N.objects.slice(U,U+W),B=U+W<N.objects.length,D=B?O[O.length-1]?.key:void 0;return{objects:O,isTruncated:B,nextContinuationToken:D,commonPrefixes:Array.from(N.commonPrefixes).sort()}}},{name:"GET_OBJECT_METADATA",description:"Get metadata for a file in the local assets directory",inputSchema:z$.object({key:z$.string()}),outputSchema:z$.object({contentType:z$.string().optional(),contentLength:z$.number(),lastModified:z$.string(),etag:z$.string(),metadata:z$.record(z$.string(),z$.string()).optional()}),handler:async(Y)=>{let G=Y,J=c91(Q,G.key),W=await rh$(J);return{contentType:P61(G.key),contentLength:W.size,lastModified:W.mtime.toISOString(),etag:$u$(J,W.mtime,W.size)}}},{name:"GET_PRESIGNED_URL",description:"Generate a presigned URL for downloading a file from local storage",inputSchema:z$.object({key:z$.string(),expiresIn:z$.number().optional()}),outputSchema:z$.object({url:z$.string(),expiresIn:z$.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??nh$;return{url:th$(Z,Q,G.key,J,"GET"),expiresIn:J}}},{name:"PUT_PRESIGNED_URL",description:"Generate a presigned URL for uploading a file to local storage",inputSchema:z$.object({key:z$.string(),expiresIn:z$.number().optional(),contentType:z$.string().optional()}),outputSchema:z$.object({url:z$.string(),expiresIn:z$.number()}),handler:async(Y)=>{let G=Y,J=G.expiresIn??nh$;return{url:th$(Z,Q,G.key,J,"PUT"),expiresIn:J}}},{name:"DELETE_OBJECT",description:"Delete a single file from local storage",inputSchema:z$.object({key:z$.string()}),outputSchema:z$.object({success:z$.boolean(),key:z$.string()}),handler:async(Y)=>{let G=Y,J=c91(Q,G.key);try{return await ph$(J),{success:!0,key:G.key}}catch{return{success:!1,key:G.key}}}},{name:"DELETE_OBJECTS",description:"Delete multiple files from local storage",inputSchema:z$.object({keys:z$.array(z$.string()).max(1000)}),outputSchema:z$.object({deleted:z$.array(z$.string()),errors:z$.array(z$.object({key:z$.string(),message:z$.string()}))}),handler:async(Y)=>{let G=Y,J=[],W=[];return await Promise.all(G.keys.map(async(K)=>{let H=c91(Q,K);try{await ph$(H),J.push(K)}catch(F){W.push({key:K,message:F instanceof Error?F.message:"Unknown error"})}})),{deleted:J,errors:W}}}]}async function d91($,Z,X){let Q=Xu$(Z,X),Y=new fW({name:"dev-assets-mcp",version:"1.0.0"},{capabilities:{tools:{}},jsonSchemaValidator:H5});for(let J of Q){let W="shape"in J.inputSchema?J.inputSchema.shape:z$.object({}).shape,K=J.outputSchema&&"shape"in J.outputSchema?J.outputSchema.shape:z$.object({}).shape;Y.registerTool(J.name,{description:J.description??"",inputSchema:W,outputSchema:K,annotations:J.annotations,_meta:J._meta},async(H)=>{try{let F=await J.handler(H);return{content:[{type:"text",text:JSON.stringify(F)}],structuredContent:F}}catch(F){return{content:[{type:"text",text:`Error: ${F.message}`}],isError:!0}}})}let G=new sX({enableJsonResponse:$.headers.get("Accept")?.includes("application/json")??!1});return await Y.connect(G),GJ(Y,G,$,"mcp:dev-assets")}async function Qu$($,Z,X,Q){let G=Xu$(X,Q).find((J)=>J.name===$);if(!G)return{content:[{type:"text",text:`Tool not found: ${$}`}],isError:!0};try{let J=await G.handler(Z);return{content:[{type:"text",text:JSON.stringify(J)}]}}catch(J){return{content:[{type:"text",text:J instanceof Error?J.message:String(J)}],isError:!0}}}var G36="./data/assets",nh$=3600,ah$,Yu$;var Gu$=w(()=>{T$();gy();P8();ll();BC();CX();cz0();ah$=new U1;ah$.all("/",async($)=>{let Z=$.get("studioContext"),X=new URL($.req.url),Q=`${X.protocol}//${X.host}`;return d91($.req.raw,Z,Q)});Yu$=ah$});var Ju$={};Y4(Ju$,{mountDevRoutes:()=>W36});function W36($,Z){$.all("/mcp/:connectionId{.*_dev-assets$}",Z,async(Q)=>{let Y=Q.get("studioContext"),G=new URL(Q.req.url),J=`${G.protocol}//${G.host}`;return d91(Q.req.raw,Y,J)}),$.all("/mcp/:connectionId{.*_dev-assets$}/call-tool/:toolName",Z,async(Q)=>{let Y=Q.get("studioContext"),G=new URL(Q.req.url),J=`${G.protocol}//${G.host}`,W=Q.req.param("toolName");if(!W)return Q.json({error:"Missing tool name"},400);let K=await Q.req.json(),H=await Qu$(W,K,Y,J);if(H.isError)return Q.json(H.content,500);return Q.json(H.content)}),$.use("/mcp/dev-assets",Z),$.route("/mcp/dev-assets",Yu$);let X=new U1;X.use("*",QW({mountPath:"/api/dev-assets"})),X.route("/",uz0({orgFromPath:!1})),$.route("/api/dev-assets",X)}var Wu$=w(()=>{P8();B61();cz0();Gu$()});import{sql as K36}from"kysely";import{randomUUID as Ku$}from"crypto";import{z as H36}from"zod";async function N36($){let Z=new Date().toISOString(),X=Ku$(),Q=l4.SELF($.organizationId),Y="registry.publish_request.created",G={requestId:$.request.id,requestedId:$.request.requested_id,title:$.request.title,status:$.request.status,createdAt:$.request.created_at,requester:{name:$.request.requester_name,email:$.request.requester_email}};await $.db.insertInto("events").values({id:X,organization_id:$.organizationId,type:"registry.publish_request.created",source:Q,specversion:"1.0",subject:$.request.id,time:Z,datacontenttype:"application/json",dataschema:null,data:JSON.stringify(G),cron:null,status:"pending",attempts:0,last_error:null,next_retry_at:null,created_at:Z,updated_at:Z}).execute();let J=await $.db.selectFrom("event_subscriptions").select(["id"]).where("organization_id","=",$.organizationId).where("enabled","=",1).where("event_type","=","registry.publish_request.created").where((W)=>W.or([W("publisher","is",null),W("publisher","=",Q)])).execute();if(J.length>0)await $.db.insertInto("event_deliveries").values(J.map((W)=>({id:Ku$(),event_id:X,subscription_id:W.id,status:"pending",attempts:0,last_error:null,delivered_at:null,next_retry_at:null,created_at:Z}))).execute();try{await K36`SELECT
|
|
2789
2789
|
pg_notify('studio_events', ${X}),
|