openpond 0.2.44 → 0.2.46
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/RELEASE.md +16 -13
- package/dist/app-server.d.ts +20954 -11829
- package/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-I3NI75P2.js +2 -0
- package/dist/chunks/{app-layer-7SPLENWD.js → app-layer-B3SMVO4B.js} +1 -1
- package/dist/chunks/app-server-runtime-FL2CHQU2.js +2 -0
- package/dist/chunks/apps-OA2VX34V.js +2 -0
- package/dist/chunks/{chunk-PEYA2Q7Q.js → chunk-33AO3P6X.js} +3 -3
- package/dist/chunks/chunk-4UTIEH5H.js +16 -0
- package/dist/chunks/chunk-4VKNBADF.js +2 -0
- package/dist/chunks/{chunk-ANVOHBUV.js → chunk-5OGRWWEH.js} +1 -1
- package/dist/chunks/chunk-5ZZM3TUN.js +24 -0
- package/dist/chunks/chunk-6JBWHR6T.js +5 -0
- package/dist/chunks/{chunk-DXAZUJPA.js → chunk-6SJZXZNA.js} +1 -1
- package/dist/chunks/chunk-6WLJWRMF.js +2 -0
- package/dist/chunks/chunk-BKMGBIBT.js +2 -0
- package/dist/chunks/chunk-BQNK2NMB.js +21 -0
- package/dist/chunks/chunk-BUFQKDAW.js +2 -0
- package/dist/chunks/chunk-D6E7JBBQ.js +19 -0
- package/dist/chunks/chunk-D6MQTNJ3.js +9 -0
- package/dist/chunks/chunk-DNXKIIV7.js +3 -0
- package/dist/chunks/{chunk-OI2N2636.js → chunk-EWS7MXTM.js} +1 -1
- package/dist/chunks/chunk-F2AG46CV.js +2 -0
- package/dist/chunks/{chunk-CR6CDOKS.js → chunk-F5DUN73H.js} +2 -2
- package/dist/chunks/chunk-FKCWOASO.js +49 -0
- package/dist/chunks/chunk-FOEUDMME.js +2678 -0
- package/dist/chunks/chunk-H6W55CQG.js +2 -0
- package/dist/chunks/chunk-HK3WGUKK.js +17 -0
- package/dist/chunks/{chunk-ZEVARU6J.js → chunk-HO5L2FUU.js} +1 -1
- package/dist/chunks/chunk-HP2D3W2B.js +42 -0
- package/dist/chunks/chunk-ICZEOMPO.js +2 -0
- package/dist/chunks/{chunk-X2B4MN6W.js → chunk-IV7F74JJ.js} +1 -1
- package/dist/chunks/chunk-JBHAU7PH.js +2409 -0
- package/dist/chunks/chunk-JO7GRBOG.js +2 -0
- package/dist/chunks/{chunk-KPDWQCF6.js → chunk-KE5RH6JA.js} +1 -1
- package/dist/chunks/chunk-KUKOZJIR.js +2 -0
- package/dist/chunks/chunk-L4BYPZ4U.js +22 -0
- package/dist/chunks/{chunk-2CXJK2M3.js → chunk-LL4QP2IM.js} +1 -1
- package/dist/chunks/{chunk-Z2BYC6TP.js → chunk-LZSY5IM3.js} +1 -1
- package/dist/chunks/chunk-M7PBDRKC.js +2 -0
- package/dist/chunks/{chunk-OJVIH7J6.js → chunk-MCRA6ZGJ.js} +1 -1
- package/dist/chunks/chunk-NPOHW5OU.js +2 -0
- package/dist/chunks/{chunk-KIGN4FI6.js → chunk-OGXSE57Z.js} +1 -1
- package/dist/chunks/{chunk-HZP5U2AA.js → chunk-P653BXMY.js} +1 -1
- package/dist/chunks/{chunk-YF6IDYTS.js → chunk-PGKEDR3S.js} +1 -1
- package/dist/chunks/chunk-PMZH2TKS.js +4 -0
- package/dist/chunks/chunk-TYWBEJOA.js +3 -0
- package/dist/chunks/chunk-USWZ3KUC.js +2 -0
- package/dist/chunks/chunk-UWO34HP6.js +33 -0
- package/dist/chunks/{chunk-Z6ZR5O3J.js → chunk-VW7D3DRM.js} +2 -2
- package/dist/chunks/chunk-W4IL6TWB.js +186 -0
- package/dist/chunks/chunk-WVNN3RB2.js +2 -0
- package/dist/chunks/{chunk-RAWEO7SJ.js → chunk-WWABOVRW.js} +2 -2
- package/dist/chunks/{chunk-B3O2GAQH.js → chunk-XLDW5NN3.js} +1 -1
- package/dist/chunks/chunk-YSYXIJ46.js +8 -0
- package/dist/chunks/{chunk-V62BHD5G.js → chunk-ZC57DX6D.js} +1 -1
- package/dist/chunks/{chunk-W5NQ2DI7.js → chunk-ZJY2L43W.js} +3 -3
- package/dist/chunks/cli-5QR7QNQJ.js +2 -0
- package/dist/chunks/{configuration-command-LDPUCHVH.js → configuration-command-MVZS625X.js} +1 -1
- package/dist/chunks/connected-evidence-7LHUZ2UI.js +2 -0
- package/dist/chunks/{continual-MHMPLLUZ.js → continual-K5JNHNQH.js} +3 -3
- package/dist/chunks/core-commands-J2SJM5I5.js +2 -0
- package/dist/chunks/datasets-KDN2EXHE.js +2 -0
- package/dist/chunks/desktop-test-WIOEKMPR.js +3 -0
- package/dist/chunks/dist-3MTJ7VM6.js +2 -0
- package/dist/chunks/{dist-ELWB75PL.js → dist-JBE7DPFZ.js} +1 -1
- package/dist/chunks/evaluation-coordination-NGYHL7HG.js +2 -0
- package/dist/chunks/experiment-improvements-2M7GRGWS.js +2 -0
- package/dist/chunks/experiments-B6CRZ3GI.js +2 -0
- package/dist/chunks/{extension-JEUZZJ5X.js → extension-RZTMK3ON.js} +1 -1
- package/dist/chunks/{help-4F4QGL4C.js → help-EISFHH2F.js} +1 -1
- package/dist/chunks/hosted-experiment-improvement-6CHH65DX.js +3 -0
- package/dist/chunks/hosted-harness-runtime-PAYMAXH7.js +2 -0
- package/dist/chunks/hosted-profile-candidate-HYEISIAC.js +3 -0
- package/dist/chunks/hosted-profile-compiler-KQREWJA5.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-control-LV6YXOG7.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-inspection-A62UYFEP.js +3 -0
- package/dist/chunks/hosted-profile-evaluation-preparation-OR4OLYEX.js +3 -0
- package/dist/chunks/human-review-J6JGNRBR.js +2 -0
- package/dist/chunks/import-YHSX6SBZ.js +4 -0
- package/dist/chunks/learning-REL6GGNA.js +2 -0
- package/dist/chunks/opchat-CUZUU2WM.js +3 -0
- package/dist/chunks/organizations-VT27V4B2.js +2 -0
- package/dist/chunks/{profile-ESULTWDN.js → profile-N2E5ASHQ.js} +1 -1
- package/dist/chunks/project-agent-XMXOBJSC.js +2 -0
- package/dist/chunks/sandbox-command-NC665ZZ5.js +2 -0
- package/dist/chunks/{sandbox-template-7WHGNVM6.js → sandbox-template-OTP6S3RU.js} +1 -1
- package/dist/chunks/src-TNWF3IC5.js +329 -0
- package/dist/chunks/{src-A3OVZOSV.js → src-WM35IF4W.js} +5 -5
- package/dist/chunks/taskset-COAPMTT3.js +2 -0
- package/dist/chunks/{teams-bot-YMCDLBGT.js → teams-bot-ACWJ7PJP.js} +1 -1
- package/dist/chunks/training-4JUK7YQV.js +2 -0
- package/dist/chunks/{workspaces-ZZ7R5BUL.js → workspaces-WTPFRJMS.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/assets/App-CdDQ-lXE.css +1 -0
- package/dist/web/assets/App-D2f8_mGk.js +235 -0
- package/dist/web/assets/{AppDialog-CV3ddujB.js → AppDialog-CaxeNfsu.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-dhbGOO_K.js → AppTerminalPanel-dtK0ZPer.js} +2 -2
- package/dist/web/assets/{AppsView-Bxa-9BF2.js → AppsView-DwK1UBJP.js} +1 -1
- package/dist/web/assets/BrowserSidebar-Cj9VnkgU.js +1 -0
- package/dist/web/assets/{CartesianChart-BOxN-Su1.js → CartesianChart-Drfk6jTn.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-DTmJvNJx.js → CollaborationTabs-Czh2noeb.js} +1 -1
- package/dist/web/assets/{CommandMenu-DggN2ygj.js → CommandMenu-D-M-xomh.js} +1 -1
- package/dist/web/assets/CommunityView-BrdxUI5Z.js +1 -0
- package/dist/web/assets/ComposerCreateImproveStrip-CJ8nkYJf.js +1 -0
- package/dist/web/assets/GetStartedView-u7Jw7YA1.js +1 -0
- package/dist/web/assets/HostedModelLearningReview-D0a2nwse.js +1 -0
- package/dist/web/assets/HostedModelLearningSettings-CQQGyjxi.js +1 -0
- package/dist/web/assets/LabModelVersionDetailPage-Cxlc4sSC.js +1 -0
- package/dist/web/assets/LabSkillSidebar-BnJkDb0c.js +1 -0
- package/dist/web/assets/LabsRoute-ACN76d2j.css +1 -0
- package/dist/web/assets/LabsRoute-hHwZNbqN.js +99 -0
- package/dist/web/assets/MainChatThread-r_TYiTnW.js +2 -0
- package/dist/web/assets/MainPane-DJcd4tPk.js +19 -0
- package/dist/web/assets/MainPane-DOWsSew1.css +1 -0
- package/dist/web/assets/{MarkdownText-BhzHRq1J.js → MarkdownText-BxPHz4je.js} +1 -1
- package/dist/web/assets/{NativeSkillSidebar-LU-PhEhW.js → NativeSkillSidebar-CCHK6kMG.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-Bi_gpHLG.js → NewExperienceSwitcher-CuKWTDZj.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-B8pWvSkq.js → NewProjectDialog-CS6sw2oD.js} +1 -1
- package/dist/web/assets/OutputsPage-JDM5bfLJ.js +1 -0
- package/dist/web/assets/{ProjectsPage-Ca8_iEWu.js → ProjectsPage-B3zTBHOA.js} +1 -1
- package/dist/web/assets/RightChatPanelStack-L8S3yj1u.js +1 -0
- package/dist/web/assets/{RightSidebarHomePanel-6pygznxX.js → RightSidebarHomePanel-BWJQKFUp.js} +1 -1
- package/dist/web/assets/ScheduledWorkPage-qX12p4B0.js +1 -0
- package/dist/web/assets/SettingsView-0KMs-r2I.js +9 -0
- package/dist/web/assets/SettingsView-CVsuQeCZ.css +1 -0
- package/dist/web/assets/{TeamChatView-BGLCPTen.js → TeamChatView-DakXCNQE.js} +1 -1
- package/dist/web/assets/{TerminalOverlay-DHkS2cVJ.js → TerminalOverlay-DaonK5C0.js} +12 -12
- package/dist/web/assets/{TrainingCreationPanel-Dneamjzh.js → TrainingCreationPanel-CUvSsSwp.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-Cfh59jLZ.js → TrainingDraftPanel-DNivtVwd.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-C9l1KY-O.js → UsageSettingsSection-rbmuoPoE.js} +1 -1
- package/dist/web/assets/WorkSidebarPanel-DrYt9xzv.js +1 -0
- package/dist/web/assets/WorkspaceDiffPanel-CThoTqe4.js +14 -0
- package/dist/web/assets/WorkspaceEnvironmentMenu-DeODKxvW.js +32 -0
- package/dist/web/assets/{WorkspaceGitDialogs-mE3Og6Zo.js → WorkspaceGitDialogs-CBarJYF-.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-DPZ0n0G9.js → WorkspaceMonacoEditor-Hmu5m_sO.js} +3 -3
- package/dist/web/assets/{arrow-up-right-DU2KsZD-.js → arrow-up-right-BV2IHfb9.js} +1 -1
- package/dist/web/assets/chunk-YTGRET2L-PKzEfYnf.js +1 -0
- package/dist/web/assets/{clipboard-g2b4_k81.js → clipboard-DDIvAWKp.js} +1 -1
- package/dist/web/assets/{cloud-upload-P2bDOPsQ.js → cloud-upload-Dv6kFnfC.js} +1 -1
- package/dist/web/assets/{cssMode-CPbPVAUt.js → cssMode-BK0jFqWW.js} +1 -1
- package/dist/web/assets/{folder-open-BmsONNsr.js → folder-open-B9ixJQJX.js} +1 -1
- package/dist/web/assets/{folder-plus-B18NgUxy.js → folder-plus-DqSKvtNB.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-enxGCV_e.js → git-commit-horizontal-C1lQvfxe.js} +1 -1
- package/dist/web/assets/{htmlMode-DiV88uQv.js → htmlMode-CCV301b6.js} +1 -1
- package/dist/web/assets/index-1cMIFBxZ.css +1 -0
- package/dist/web/assets/{index-vfpCN9zy.js → index-DIaKfM8a.js} +2 -2
- package/dist/web/assets/{info-DmuSBIYe.js → info-BEvaynAD.js} +1 -1
- package/dist/web/assets/{jsonMode-BaeOjuKU.js → jsonMode-Co4pyN4F.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-D8To0CQA.js → lspLanguageFeatures-CSU0G5da.js} +1 -1
- package/dist/web/assets/{minimize-2-C2xnEzCe.js → minimize-2-DT8t8wwP.js} +1 -1
- package/dist/web/assets/{monaco.contribution-JW3MxX6k.js → monaco.contribution-CBwGIQY1.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DgTFvG2Q.js → monaco.contribution-Cr0AaHCD.js} +2 -2
- package/dist/web/assets/{monaco.contribution-bytkwn0O.js → monaco.contribution-DSBAb_PC.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DbrACt99.js → monaco.contribution-DUZrs1D-.js} +2 -2
- package/dist/web/assets/{monitor-mtHVW7gU.js → monitor-DGqnfsK9.js} +1 -1
- package/dist/web/assets/play-C1XWyKh6.js +1 -0
- package/dist/web/assets/{python-DAPe0Urm.js → python-Z1foxLdf.js} +1 -1
- package/dist/web/assets/{save-B2eVAjW6.js → save-CX2kF74j.js} +1 -1
- package/dist/web/assets/{square-16bX2k2i.js → square-DMkXeYeV.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-Ce0YhEQg.js → toggleHighContrast-CRMVp779.js} +1 -1
- package/dist/web/assets/{tsMode-CnvMmHz6.js → tsMode-Czu8YAqh.js} +1 -1
- package/dist/web/assets/{upload-COPbAaD-.js → upload-giKOPnl1.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-C-Wjm5HK.js → useLocalAgentSchedules-BHxWmOeC.js} +1 -1
- package/dist/web/assets/{useSessionTurnCache-BfVbncMB.js → useSessionTurnCache-CUYFsu_W.js} +1 -1
- package/dist/web/assets/{wifi-off-C9iLbCC-.js → wifi-off-DbDXaV1N.js} +1 -1
- package/dist/web/assets/{workers-BXh_u8Fr.js → workers-Cno4XklJ.js} +1 -1
- package/dist/web/assets/{yaml-CRSr9x6_.js → yaml-C28t_C6h.js} +1 -1
- package/dist/web/index.html +2 -2
- package/docs/command-reference.md +99 -0
- package/package.json +4 -3
- package/dist/chunks/actions-command-5IEZEP6W.js +0 -2
- package/dist/chunks/app-server-runtime-NQ2BYPGK.js +0 -2
- package/dist/chunks/apps-XQ7PHJTD.js +0 -2
- package/dist/chunks/chunk-36RCXSEJ.js +0 -2
- package/dist/chunks/chunk-3QC2DDQ5.js +0 -2
- package/dist/chunks/chunk-3XDFNA7W.js +0 -2
- package/dist/chunks/chunk-4S4WH65X.js +0 -3
- package/dist/chunks/chunk-4TMC5F2P.js +0 -5
- package/dist/chunks/chunk-65BW2QXY.js +0 -2
- package/dist/chunks/chunk-65QCNUGE.js +0 -659
- package/dist/chunks/chunk-6XF4GI35.js +0 -2
- package/dist/chunks/chunk-ALZRXBEC.js +0 -33
- package/dist/chunks/chunk-ARJUNUH6.js +0 -5
- package/dist/chunks/chunk-CEEZ7Y2J.js +0 -2
- package/dist/chunks/chunk-DZVVGU6K.js +0 -8
- package/dist/chunks/chunk-HY2Q7EDK.js +0 -4
- package/dist/chunks/chunk-IT4AT6LB.js +0 -42
- package/dist/chunks/chunk-KRC2S5QF.js +0 -5
- package/dist/chunks/chunk-L6HCBIAU.js +0 -2
- package/dist/chunks/chunk-LNEOLOK2.js +0 -13
- package/dist/chunks/chunk-MTJNKRXL.js +0 -22
- package/dist/chunks/chunk-NM2GYDPA.js +0 -19
- package/dist/chunks/chunk-OMM4ZO7E.js +0 -2182
- package/dist/chunks/chunk-OQPFFKU6.js +0 -2
- package/dist/chunks/chunk-QID62K65.js +0 -2400
- package/dist/chunks/chunk-YOOPTMQK.js +0 -3
- package/dist/chunks/cli-OJU6NQSA.js +0 -2
- package/dist/chunks/core-commands-UZL5RF2M.js +0 -2
- package/dist/chunks/datasets-42AZHVSV.js +0 -13
- package/dist/chunks/desktop-test-DI76HKS7.js +0 -3
- package/dist/chunks/dist-6YP37XI5.js +0 -2
- package/dist/chunks/experiments-Z3S35BYN.js +0 -2
- package/dist/chunks/hosted-harness-runtime-VZNYNQ6T.js +0 -2
- package/dist/chunks/hosted-profile-compiler-JXLPR7SX.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-control-Q54YXXIM.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-inspection-7WESM3ZH.js +0 -3
- package/dist/chunks/hosted-profile-evaluation-preparation-QP24PYBL.js +0 -3
- package/dist/chunks/opchat-UFWWVJL6.js +0 -3
- package/dist/chunks/organizations-SBBIOF6O.js +0 -2
- package/dist/chunks/project-agent-IBHUQ3JX.js +0 -2
- package/dist/chunks/sandbox-command-PAJAIMWM.js +0 -2
- package/dist/chunks/src-5MJSO3UD.js +0 -326
- package/dist/chunks/taskset-BZYQT65N.js +0 -2
- package/dist/chunks/training-7PST5HZU.js +0 -2
- package/dist/web/assets/App-6AQXN2SM.js +0 -226
- package/dist/web/assets/App-7h_oHCFd.css +0 -1
- package/dist/web/assets/BrowserSidebar-BLwL2FOG.js +0 -1
- package/dist/web/assets/CommunityView-CuDrYOIf.js +0 -1
- package/dist/web/assets/ComposerCreateImproveStrip-BrduENlL.js +0 -1
- package/dist/web/assets/GetStartedView-Db1IEWzv.js +0 -1
- package/dist/web/assets/HostedModelLearningReview-kofNdPAe.js +0 -1
- package/dist/web/assets/HostedModelLearningSettings-6ij3nwWD.js +0 -1
- package/dist/web/assets/LabModelVersionDetailPage-C7Maqcit.js +0 -1
- package/dist/web/assets/LabSkillSidebar-Bz0U-Nmw.js +0 -1
- package/dist/web/assets/LabsRoute-Ch1N-e2S.js +0 -52
- package/dist/web/assets/LabsRoute-Dw6-12kt.css +0 -1
- package/dist/web/assets/MainChatThread-BJbhZOvs.js +0 -2
- package/dist/web/assets/MainPane-Cs2Kng_k.js +0 -19
- package/dist/web/assets/OutputsPage-BkGI0kHp.js +0 -1
- package/dist/web/assets/RightChatPanelStack-DjEdxsq8.js +0 -1
- package/dist/web/assets/ScheduledWorkPage-BSiOxxAH.js +0 -1
- package/dist/web/assets/SettingsView-1XN7KLBl.js +0 -9
- package/dist/web/assets/SettingsView-C7av3zwv.css +0 -1
- package/dist/web/assets/WorkSidebarPanel-CEnO-Txp.js +0 -1
- package/dist/web/assets/WorkspaceDiffPanel-BiuQBflC.js +0 -14
- package/dist/web/assets/WorkspaceEnvironmentMenu-Dr-E0c1j.js +0 -32
- package/dist/web/assets/index-B9VSiz_z.css +0 -1
- package/dist/web/assets/refresh-cw-Dvm_Pq3U.js +0 -1
|
@@ -1,226 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CommandMenu-DggN2ygj.js","assets/index-vfpCN9zy.js","assets/index-B9VSiz_z.css","assets/CommandMenu-Cb3vNGJr.css","assets/SettingsView-1XN7KLBl.js","assets/refresh-cw-Dvm_Pq3U.js","assets/save-B2eVAjW6.js","assets/MarkdownText-BhzHRq1J.js","assets/folder-open-BmsONNsr.js","assets/wifi-off-C9iLbCC-.js","assets/useLocalAgentSchedules-C-Wjm5HK.js","assets/cloud-upload-P2bDOPsQ.js","assets/git-commit-horizontal-enxGCV_e.js","assets/folder-plus-B18NgUxy.js","assets/AppDialog-CV3ddujB.js","assets/WorkspaceDiffPanel-BiuQBflC.js","assets/training-model-data-CKOkpBBL.js","assets/info-DmuSBIYe.js","assets/minimize-2-C2xnEzCe.js","assets/clipboard-g2b4_k81.js","assets/SettingsView-C7av3zwv.css","assets/git-dialogs-C-F47S10.css","assets/NewProjectDialog-B8pWvSkq.js","assets/monitor-mtHVW7gU.js","assets/WorkspaceGitDialogs-mE3Og6Zo.js","assets/upload-COPbAaD-.js","assets/WorkspaceEnvironmentMenu-Dr-E0c1j.js","assets/square-16bX2k2i.js","assets/WorkspaceEnvironmentMenu-DGIFdG3o.css","assets/MainPane-Cs2Kng_k.js","assets/arrow-up-right-DU2KsZD-.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as v,j as k,a as PP,_ as ur}from"./index-vfpCN9zy.js";const Ix=v.createContext(void 0),_x=e=>{const t=v.useContext(Ix);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},AP=({client:e,children:t})=>(v.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),k.jsx(Ix.Provider,{value:e,children:t})),TP={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var EP=class{#e=TP;#t=!1;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};const Zi=new EP;function MP(e){setTimeout(e,0)}const jP=typeof window>"u"||"Deno"in globalThis;function ea(){}function OP(e,t){return typeof e=="function"?e(t):e}function Cx(e){return typeof e=="number"&&e>=0&&e!==1/0}function Rx(e,t){return Math.max(e+(t||0)-Date.now(),0)}function nn(e,t){return typeof e=="function"?e(t):e}function Cb(e,t){const{type:n="all",exact:a,fetchStatus:o,predicate:r,queryKey:s,stale:l}=e;if(s){if(a){if(t.queryHash!==Xh(s,t.options))return!1}else if(!ys(t.queryKey,s))return!1}if(n!=="all"){const m=t.isActive();if(n==="active"&&!m||n==="inactive"&&m)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||o&&o!==t.state.fetchStatus||r&&!r(t))}function Rb(e,t){const{exact:n,status:a,predicate:o,mutationKey:r}=e;if(r){if(!t.options.mutationKey)return!1;if(n){if(Hl(t.options.mutationKey)!==Hl(r))return!1}else if(!ys(t.options.mutationKey,r))return!1}return!(a&&t.state.status!==a||o&&!o(t))}function Xh(e,t){return(t?.queryKeyHashFn||Hl)(e)}function Hl(e){return JSON.stringify(e,(t,n)=>Gf(n)?Object.keys(n).sort().reduce((a,o)=>(a[o]=n[o],a),{}):n)}function ys(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t)){for(let a=0;a<t.length;a++)if(!ys(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!ys(e[a],t[a]))return!1;return!0}return!1}const $P=Object.prototype.hasOwnProperty;function Px(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Pb(e)&&Pb(t);if(!a&&!(Gf(e)&&Gf(t)))return t;const o=(a?e:Object.keys(e)).length,r=a?t:Object.keys(t),s=r.length,l=a?new Array(s):{};let m=0;for(let d=0;d<s;d++){const h=a?d:r[d],g=e[h],y=t[h];if(g===y){l[h]=g,(a?d<o:$P.call(e,h))&&m++;continue}if(g===null||y===null||typeof g!="object"||typeof y!="object"){l[h]=y;continue}const w=Px(g,y,n+1);l[h]=w,w===g&&m++}return o===s&&m===o?e:l}function Ap(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Pb(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Gf(e){if(!Ab(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Ab(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Ab(e){return Object.prototype.toString.call(e)==="[object Object]"}function NP(e){return new Promise(t=>{Zi.setTimeout(t,e)})}function Jf(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Px(e,t):t}function DP(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function LP(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const eg=Symbol();function Ax(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===eg?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Tx(e,t){return typeof e=="function"?e(...t):!!e}function HP(e,t,n){let a=!1,o;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(o??=t(),a||(a=!0,o.aborted?n():o.addEventListener("abort",n,{once:!0})),o)}),e}let UP=()=>jP;const tg=()=>UP();var dc=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},qP=class extends dc{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}};const ng=new qP,zP=MP;function BP(){let e=[],t=0,n=l=>{l()},a=l=>{l()},o=zP;const r=l=>{t?e.push(l):o(()=>{n(l)})},s=()=>{const l=e;e=[],l.length&&o(()=>{a(()=>{l.forEach(m=>{n(m)})})})};return{batch:l=>{let m;t++;try{m=l()}finally{t--,t||s()}return m},batchCalls:l=>(...m)=>{r(()=>{l(...m)})},schedule:r,setNotifyFunction:l=>{n=l},setBatchNotifyFunction:l=>{a=l},setScheduler:l=>{o=l}}}const Mn=BP();var FP=class extends dc{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<"u"&&window.addEventListener){const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",n,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};const Gd=new FP;function VP(e){return Math.min(1e3*2**e,3e4)}function Ex(e){return(e??"online")==="online"?Gd.isOnline():!0}var Zf=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Mx(e){let t=!1,n=0,a,o="pending",r,s;const l=new Promise(($,O)=>{r=$,s=O});l.catch(ea);const m=()=>o!=="pending",d=$=>{if(!m()){const O=new Zf($);P(O),e.onCancel?.(O)}},h=()=>{t=!0},g=()=>{t=!1},y=()=>ng.isFocused()&&(e.networkMode==="always"||Gd.isOnline())&&e.canRun(),w=()=>Ex(e.networkMode)&&e.canRun(),_=$=>{m()||(a?.(),o="resolved",r($))},P=$=>{m()||(a?.(),o="rejected",s($))},M=()=>new Promise($=>{a=O=>{(m()||y())&&$(O)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),C=()=>{if(m())return;let $;const O=n===0?e.initialPromise:void 0;try{$=O??e.fn()}catch(j){$=Promise.reject(j)}Promise.resolve($).then(_).catch(j=>{if(m())return;const x=e.retry??(tg()?0:3),R=e.retryDelay??VP,E=typeof R=="function"?R(n,j):R,H=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,j);if(t||!H){P(j);return}n++,e.onFail?.(n,j),NP(E).then(()=>y()?void 0:M()).then(()=>{t?P(j):C()})})};return{promise:l,status:()=>o,cancel:d,continue:()=>(a?.(),l),cancelRetry:h,continueRetry:g,canStart:w,start:()=>(w()?C():M().then(C),l)}}var jx=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Cx(this.gcTime)&&(this.#e=Zi.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(tg()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Zi.clearTimeout(this.#e),this.#e=void 0)}};function KP(e){return{onFetch:(t,n)=>{const a=t.options,o=t.fetchOptions?.meta?.fetchMore?.direction,r=t.state.data?.pages||[],s=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},m=0;const d=async()=>{let h=!1;const g=_=>{HP(_,()=>t.signal,()=>h=!0)},y=Ax(t.options,t.fetchOptions),w=async(_,P,M)=>{if(h)return Promise.reject(t.signal.reason);if(P==null&&_.pages.length)return Promise.resolve(_);const $=(()=>{const R={client:t.client,queryKey:t.queryKey,pageParam:P,direction:M?"backward":"forward",meta:t.options.meta};return g(R),R})(),O=await y($),{maxPages:j}=t.options,x=M?LP:DP;return{pages:x(_.pages,O,j),pageParams:x(_.pageParams,P,j)}};if(o&&r.length){const _=o==="backward",P=_?Ox:Yf,M={pages:r,pageParams:s};l=await w(M,P(a,M),_)}else{const _=e??r.length;do{const P=m===0?s[0]??a.initialPageParam:Yf(a,l);if(m>0&&P==null)break;l=await w(l,P),m++}while(m<_)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Yf(e,{pages:t,pageParams:n}){const a=t.length-1;return t.length>0?e.getNextPageParam(t[a],t,n[a],n):void 0}function Ox(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function vX(e,t){return t?Yf(e,t)!=null:!1}function bX(e,t){return!t||!e.getPreviousPageParam?!1:Ox(e,t)!=null}var WP=class extends jx{#e;#t;#n;#a;#i;#o;#r;#l;constructor(e){super(),this.#l=!1,this.#r=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#a=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Eb(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#o?.promise}setOptions(e){if(this.options={...this.#r,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Eb(this.options);t.data!==void 0&&(this.setState(Tb(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=Jf(this.state.data,e,this.options);return this.#s({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#s({type:"setState",state:e})}cancel(e){const t=this.#o?.promise;return this.#o?.cancel(e),t?t.then(ea).catch(ea):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>nn(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===eg||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>nn(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Rx(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#o?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#o?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#a.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){const t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#o&&(this.#l||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#o.cancel({revert:!0}):this.#o.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#o?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#o)return this.#o.continueRetry(),this.#o.promise}if(e&&this.setOptions(e),!this.options.queryFn){const m=this.observers.find(d=>d.options.queryFn);m&&this.setOptions(m.options)}const n=new AbortController,a=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(this.#l=!0,n.signal)})},o=()=>{const m=Ax(this.options,t),h=(()=>{const g={client:this.#i,queryKey:this.queryKey,meta:this.meta};return a(g),g})();return this.#l=!1,this.options.persister?this.options.persister(m,h,this):m(h)},s=(()=>{const m={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:o};return a(m),m})();(this.#e==="infinite"?KP(this.options.pages):this.options.behavior)?.onFetch(s,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#s({type:"fetch",meta:s.fetchOptions?.meta});const l=this.#o=Mx({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof Zf&&m.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(m,d)=>{this.#s({type:"failed",failureCount:m,error:d})},onPause:()=>{this.#s({type:"pause"})},onContinue:()=>{this.#s({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0});try{const m=await l.start();if(m===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(m),this.#a.config.onSuccess?.(m,this),this.#a.config.onSettled?.(m,this.state.error,this),m}catch(m){if(m instanceof Zf){if(m.silent)return this.#o.promise;if(m.revert){if(this.state.data===void 0)throw m;return this.state.data}}throw this.#s({type:"error",error:m}),this.#a.config.onError?.(m,this),this.#a.config.onSettled?.(this.state.data,m,this),m}finally{this.#o===l&&(this.#o=void 0),this.scheduleGc()}}#s(e){const t=n=>{switch(e.type){case"failed":return{...n,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...n,fetchStatus:"paused"};case"continue":return{...n,fetchStatus:"fetching"};case"fetch":return{...n,...$x(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Tb(e.data,e.dataUpdatedAt),dataUpdateCount:n.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?a:void 0,a;case"error":const o=e.error;return{...n,error:o,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Mn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function $x(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ex(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Tb(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Eb(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,a=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?a??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var GP=class extends dc{#e;#t=void 0;#n=void 0;#a=void 0;#i;#o;#r;#l;#s;#p;#d;#u;#c;#f=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#r=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Mb(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Qf(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Qf(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#x(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof nn(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#k(),this.#t.setOptions(this.options),t._defaulted&&!Ap(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&jb(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||nn(this.options.enabled,this.#t)!==nn(t.enabled,this.#t)||nn(this.options.staleTime,this.#t)!==nn(t.staleTime,this.#t))&&this.#g();const o=this.#v();a&&(this.#t!==n||nn(this.options.enabled,this.#t)!==nn(t.enabled,this.#t)||o!==this.#c)&&this.#b(o)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Ap(this.getCurrentResult(),n)||(this.#a=n,this.#o=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#a}trackResult(e,t){return new Proxy(e,{get:(n,a)=>(this.trackProp(a),t?.(a),Reflect.get(n,a))})}trackProp(e){this.#f.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);let a=()=>{},o;const r=new Promise(s=>{o=s,a=this.#e.getQueryCache().subscribe(l=>{l.type==="updated"&&l.query.queryHash===n.queryHash&&n.state.data!==void 0&&(a(),s(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{const s=this.createResult(n,t);return o?.(s),s}).finally(()=>{a()}),r])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#k();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(ea)),t}#h(e){return!tg()&&nn(this.options.enabled,this.#t)!==!1&&Cx(e)}#g(){this.#S();const e=nn(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=Rx(this.#a.dataUpdatedAt,e)+1;this.#d=Zi.setTimeout(()=>{this.#a.isStale||this.updateResult()},t)}#v(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#b(e){this.#x(),this.#c=e,!(this.#c===0||!this.#h(this.#c))&&(this.#u=Zi.setInterval(()=>{(this.options.refetchIntervalInBackground||ng.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(Zi.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(Zi.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,o=this.#a,r=this.#i,s=this.#o,l=e!==n?e.state:this.#n,{state:m}=e;let d={...m},h=!1,g;if(t._optimisticResults){const x=this.hasListeners(),R=!x&&Mb(e,t),E=x&&jb(e,n,t,a);(R||E)&&(d={...d,...$x(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:y,errorUpdatedAt:w,status:_}=d;g=d.data;let P=!1;if(t.placeholderData!==void 0&&g===void 0&&_==="pending"){let x;o?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(x=o.data,P=!0):x=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,x!==void 0&&(_="success",g=Jf(o?.data,x,t),h=!0)}if(t.select&&g!==void 0&&!P)if(o&&g===r?.data&&t.select===this.#l)g=this.#s;else try{this.#l=t.select,g=t.select(g),g=Jf(o?.data,g,t),this.#s=g,this.#r=null}catch(x){this.#r=x}else g===void 0&&(this.#r=null);this.#r&&(y=this.#r,g=this.#s,w=Date.now(),_="error",h=!1);const M=d.fetchStatus==="fetching",C=_==="pending",$=_==="error",O=C&&M,j=g!==void 0;return{status:_,fetchStatus:d.fetchStatus,isPending:C,isSuccess:_==="success",isError:$,isInitialLoading:O,isLoading:O,data:g,dataUpdatedAt:d.dataUpdatedAt,error:y,errorUpdatedAt:w,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:d.dataUpdateCount>l.dataUpdateCount||d.errorUpdateCount>l.errorUpdateCount,isFetching:M,isRefetching:M&&!C,isLoadingError:$&&!j,isPaused:d.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:$&&j,isStale:ag(e,t),refetch:this.refetch,isEnabled:nn(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#o=this.options,this.#i.data!==void 0&&(this.#p=this.#t),Ap(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:o}=this.options,r=typeof o=="function"?o():o;if(r==="all"||!r&&!this.#f.size)return!0;const s=new Set(r??this.#f);return this.options.throwOnError&&s.add("error"),Object.keys(this.#a).some(l=>{const m=l;return this.#a[m]!==e[m]&&s.has(m)})})();Mn.batch(()=>{a&&this.listeners.forEach(o=>{o(this.#a)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}#k(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function JP(e,t){return nn(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&nn(t.retryOnMount,e)===!1)}function Mb(e,t){return JP(e,t)||e.state.data!==void 0&&Qf(e,t,t.refetchOnMount)}function Qf(e,t,n){if(nn(t.enabled,e)!==!1&&nn(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&ag(e,t)}return!1}function jb(e,t,n,a){return(e!==t||nn(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&ag(e,n)}function ag(e,t){return nn(t.enabled,e)!==!1&&e.isStaleByTime(nn(t.staleTime,e))}var ZP=class extends jx{#e;#t;#n;#a;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||YP(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#n.remove(this))}continue(){return this.#a?.continue()??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(e){const t=()=>{this.#i({type:"continue"})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},a=this.#a=Mx({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(new Error("No mutationFn found")),onFail:(s,l)=>{this.#i({type:"failed",failureCount:s,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),o=this.state.status==="pending",r=!a.canStart();try{if(o)t();else{this.#i({type:"pending",variables:e,isPaused:r}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);const l=await this.options.onMutate?.(e,n);l!==this.state.context&&this.#i({type:"pending",context:l,variables:e,isPaused:r})}const s=await a.start();return await this.#n.config.onSuccess?.(s,e,this.state.context,this,n),await this.options.onSuccess?.(s,e,this.state.context,n),await this.#n.config.onSettled?.(s,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(s,null,e,this.state.context,n),this.#i({type:"success",data:s}),s}catch(s){try{await this.#n.config.onError?.(s,e,this.state.context,this,n)}catch(l){Promise.reject(l)}try{await this.options.onError?.(s,e,this.state.context,n)}catch(l){Promise.reject(l)}try{await this.#n.config.onSettled?.(void 0,s,this.state.variables,this.state.context,this,n)}catch(l){Promise.reject(l)}try{await this.options.onSettled?.(void 0,s,e,this.state.context,n)}catch(l){Promise.reject(l)}throw this.#i({type:"error",error:s}),s}finally{this.#a===a&&(this.#a=void 0),this.#n.runNext(this)}}#i(e){const t=n=>{switch(e.type){case"failed":return{...n,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...n,isPaused:!0};case"continue":return{...n,isPaused:!1};case"pending":return{...n,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...n,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...n,data:void 0,error:e.error,failureCount:n.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),Mn.batch(()=>{this.#t.forEach(n=>{n.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:"updated",action:e})})}};function YP(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var QP=class extends dc{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){const a=new ZP({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(a),a}add(e){this.#e.add(e);const t=id(e);if(typeof t=="string"){const n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=id(e);if(typeof t=="string"){const n=this.#t.get(t);if(n)if(n.length>1){const a=n.indexOf(e);a!==-1&&n.splice(a,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=id(e);if(typeof t=="string"){const n=this.#t.get(t)?.find(a=>a.state.status==="pending");return!n||n===e}else return!0}runNext(e){const t=id(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Mn.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Rb(t,n))}findAll(e={}){return this.getAll().filter(t=>Rb(e,t))}notify(e){Mn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Mn.batch(()=>Promise.all(e.map(t=>t.continue().catch(ea))))}};function id(e){return e.options.scope?.id}var XP=class extends dc{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,o=t.queryHash??Xh(a,t);let r=this.get(o);return r||(r=new WP({client:e,queryKey:a,queryHash:o,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(r)),r}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Mn.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(n=>Cb(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Cb(e,n)):t}notify(e){Mn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Mn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Mn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},eA=class{#e;#t;#n;#a;#i;#o;#r;#l;constructor(e={}){this.#e=e.queryCache||new XP,this.#t=e.mutationCache||new QP,this.#n=e.defaultOptions||{},this.#a=new Map,this.#i=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#r=ng.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=Gd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#o--,this.#o===0&&(this.#r?.(),this.#r=void 0,this.#l?.(),this.#l=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=this.#e.build(this,t),a=n.state.data;return a===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(nn(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(a))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(e,t,n){const a=this.defaultQueryOptions({queryKey:e}),o=this.#e.get(a.queryHash)?.state.data,r=OP(t,o);if(r!==void 0)return this.#e.build(this,a).setData(r,{...n,manual:!0})}setQueriesData(e,t,n){return Mn.batch(()=>this.#e.findAll(e).map(({queryKey:a})=>[a,this.setQueryData(a,t,n)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;Mn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Mn.batch(()=>{const a=n.findAll(e),o=new Set(a);return a.forEach(r=>{r.reset()}),this.refetchQueries({type:"active",predicate:r=>o.has(r)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Mn.batch(()=>this.#e.findAll(e).map(o=>o.cancel(n)));return Promise.all(a).then(ea).catch(ea)}invalidateQueries(e,t={}){return Mn.batch(()=>(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},a=Mn.batch(()=>this.#e.findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let r=o.fetch(void 0,n);return n.throwOnError||(r=r.catch(ea)),o.state.fetchStatus==="paused"?Promise.resolve():r}));return Promise.all(a).then(ea)}async query(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t),a=n.isStaleByTime(nn(t.staleTime,n))?await n.fetch(t):n.state.data,o=t.select;return o?o(a):a}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=this.#e.build(this,t);return n.isStaleByTime(nn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(ea).catch(ea)}infiniteQuery(e){return e._type="infinite",this.query(e)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(ea).catch(ea)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Gd.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#a.set(Hl(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{ys(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(Hl(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#i.values()],n={};return t.forEach(a=>{ys(e,a.mutationKey)&&Object.assign(n,a.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Xh(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===eg&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};const Nx=v.createContext(!1),tA=()=>v.useContext(Nx);Nx.Provider;function nA(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const aA=v.createContext(nA()),oA=()=>v.useContext(aA),iA=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?Tx(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},rA=e=>{v.useEffect(()=>{e.clearReset()},[e])},sA=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(o&&e.data===void 0||Tx(n,[e.error,a])),lA=e=>{if(e.suspense){const n=o=>o==="static"?o:Math.max(o??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...o)=>n(a(...o)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},cA=(e,t)=>e?.suspense&&t.isPending,dA=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function uA(e,t,n){const a=tA(),o=oA(),r=_x(),s=r.defaultQueryOptions(e),l=r.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,lA(s),iA(s,o,l),rA(o);const[d]=v.useState(()=>new t(r,s)),h=d.getOptimisticResult(s),g=!a&&m;if(v.useSyncExternalStore(v.useCallback(y=>{const w=g?d.subscribe(Mn.batchCalls(y)):ea;return d.updateResult(),w},[d,g]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),v.useEffect(()=>{d.setOptions(s)},[s,d]),cA(s,h))throw dA(s,d,o);if(sA({result:h,errorResetBoundary:o,throwOnError:s.throwOnError,query:l,suspense:s.suspense}))throw h.error;return s.notifyOnChangeProps?h:d.trackResult(h)}function mA(e,t){return uA(e,GP)}function pA(){return new eA({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var Ob;function ge(e,t,n){function a(l,m){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:m,constr:s,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,m);const d=s.prototype,h=Object.keys(d);for(let g=0;g<h.length;g++){const y=h[g];y in l||(l[y]=d[y].bind(l))}}const o=n?.Parent??Object;class r extends o{}Object.defineProperty(r,"name",{value:e});function s(l){var m;const d=n?.Parent?new r:this;a(d,l),(m=d._zod).deferred??(m.deferred=[]);for(const h of d._zod.deferred)h();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class ps extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Dx extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Ob=globalThis).__zod_globalConfig??(Ob.__zod_globalConfig={});const og=globalThis.__zod_globalConfig;function ti(e){return og}function Lx(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,o])=>t.indexOf(+a)===-1).map(([a,o])=>o)}function Xf(e,t){return typeof t=="bigint"?t.toString():t}function Iu(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ig(e){return e==null}function rg(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function fA(e,t){const n=e/t,a=Math.round(n),o=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<o?0:n-a}const $b=Symbol("evaluating");function Ct(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==$b)return a===void 0&&(a=$b,a=n()),a},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function mr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ai(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function Nb(e){return JSON.stringify(e)}function hA(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Hx="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ul(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const gA=Iu(()=>{if(og.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Ss(e){if(Ul(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ul(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function Ux(e){return Ss(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const vA=new Set(["string","number","symbol"]);function xs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ti(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function et(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function bA(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const yA={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function SA(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const r=Ai(e._zod.def,{get shape(){const s={};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&(s[l]=n.shape[l])}return mr(this,"shape",s),s},checks:[]});return Ti(e,r)}function xA(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const r=Ai(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&delete s[l]}return mr(this,"shape",s),s},checks:[]});return Ti(e,r)}function kA(e,t){if(!Ss(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const r=e._zod.def.shape;for(const s in t)if(Object.getOwnPropertyDescriptor(r,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=Ai(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return mr(this,"shape",r),r}});return Ti(e,o)}function wA(e,t){if(!Ss(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ai(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return mr(this,"shape",a),a}});return Ti(e,n)}function IA(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Ai(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return mr(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ti(e,n)}function _A(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const s=Ai(t._zod.def,{get shape(){const l=t._zod.def.shape,m={...l};if(n)for(const d in n){if(!(d in l))throw new Error(`Unrecognized key: "${d}"`);n[d]&&(m[d]=e?new e({type:"optional",innerType:l[d]}):l[d])}else for(const d in l)m[d]=e?new e({type:"optional",innerType:l[d]}):l[d];return mr(this,"shape",m),m},checks:[]});return Ti(t,s)}function CA(e,t,n){const a=Ai(t._zod.def,{get shape(){const o=t._zod.def.shape,r={...o};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(r[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(const s in o)r[s]=new e({type:"nonoptional",innerType:o[s]});return mr(this,"shape",r),r}});return Ti(t,a)}function es(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function RA(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ts(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function rd(e){return typeof e=="string"?e:e?.message}function ni(e,t,n){const a=e.message?e.message:rd(e.inst?._zod.def?.error?.(e))??rd(t?.error?.(e))??rd(n.customError?.(e))??rd(n.localeError?.(e))??"Invalid input",{inst:o,continue:r,input:s,...l}=e;return l.path??(l.path=[]),l.message=a,t?.reportInput&&(l.input=s),l}function sg(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function ql(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const qx=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Xf,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},zx=ge("$ZodError",qx),Bx=ge("$ZodError",qx,{Parent:Error});function PA(e,t=n=>n.message){const n={},a=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):a.push(t(o));return{formErrors:a,fieldErrors:n}}function AA(e,t=n=>n.message){const n={_errors:[]},a=(o,r=[])=>{for(const s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(l=>a({issues:l},[...r,...s.path]));else if(s.code==="invalid_key")a({issues:s.issues},[...r,...s.path]);else if(s.code==="invalid_element")a({issues:s.issues},[...r,...s.path]);else{const l=[...r,...s.path];if(l.length===0)n._errors.push(t(s));else{let m=n,d=0;for(;d<l.length;){const h=l[d];d===l.length-1?(m[h]=m[h]||{_errors:[]},m[h]._errors.push(t(s))):m[h]=m[h]||{_errors:[]},m=m[h],d++}}}};return a(e),n}const lg=e=>(t,n,a,o)=>{const r=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new ps;if(s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>ni(m,r,ti())));throw Hx(l,o?.callee),l}return s.value},cg=e=>async(t,n,a,o)=>{const r=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise&&(s=await s),s.issues.length){const l=new(o?.Err??e)(s.issues.map(m=>ni(m,r,ti())));throw Hx(l,o?.callee),l}return s.value},_u=e=>(t,n,a)=>{const o=a?{...a,async:!1}:{async:!1},r=t._zod.run({value:n,issues:[]},o);if(r instanceof Promise)throw new ps;return r.issues.length?{success:!1,error:new(e??zx)(r.issues.map(s=>ni(s,o,ti())))}:{success:!0,data:r.value}},TA=_u(Bx),Cu=e=>async(t,n,a)=>{const o=a?{...a,async:!0}:{async:!0};let r=t._zod.run({value:n,issues:[]},o);return r instanceof Promise&&(r=await r),r.issues.length?{success:!1,error:new e(r.issues.map(s=>ni(s,o,ti())))}:{success:!0,data:r.value}},EA=Cu(Bx),MA=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return lg(e)(t,n,o)},jA=e=>(t,n,a)=>lg(e)(t,n,a),OA=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return cg(e)(t,n,o)},$A=e=>async(t,n,a)=>cg(e)(t,n,a),NA=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return _u(e)(t,n,o)},DA=e=>(t,n,a)=>_u(e)(t,n,a),LA=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Cu(e)(t,n,o)},HA=e=>async(t,n,a)=>Cu(e)(t,n,a),UA=/^[cC][0-9a-z]{6,}$/,qA=/^[0-9a-z]+$/,zA=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,BA=/^[0-9a-vA-V]{20}$/,FA=/^[A-Za-z0-9]{27}$/,VA=/^[a-zA-Z0-9_-]{21}$/,KA=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,WA=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Db=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,GA=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,JA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ZA(){return new RegExp(JA,"u")}const YA=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,QA=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,XA=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,eT=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,tT=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fx=/^[A-Za-z0-9_-]*$/,nT=/^https?$/,aT=/^\+[1-9]\d{6,14}$/,Vx="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",oT=new RegExp(`^${Vx}$`);function Kx(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function iT(e){return new RegExp(`^${Kx(e)}$`)}function rT(e){const t=Kx({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const a=`${t}(?:${n.join("|")})`;return new RegExp(`^${Vx}T(?:${a})$`)}const sT=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},lT=/^-?\d+$/,Wx=/^-?\d+(?:\.\d+)?$/,cT=/^(?:true|false)$/i,dT=/^null$/i,uT=/^[^A-Z]*$/,mT=/^[^a-z]*$/,ia=ge("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Gx={number:"number",bigint:"bigint",object:"date"},Jx=ge("$ZodCheckLessThan",(e,t)=>{ia.init(e,t);const n=Gx[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,r=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Zx=ge("$ZodCheckGreaterThan",(e,t)=>{ia.init(e,t);const n=Gx[typeof t.value];e._zod.onattach.push(a=>{const o=a._zod.bag,r=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),pT=ge("$ZodCheckMultipleOf",(e,t)=>{ia.init(e,t),e._zod.onattach.push(n=>{var a;(a=n._zod.bag).multipleOf??(a.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):fA(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),fT=ge("$ZodCheckNumberFormat",(e,t)=>{ia.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[o,r]=yA[t.format];e._zod.onattach.push(s=>{const l=s._zod.bag;l.format=t.format,l.minimum=o,l.maximum=r,n&&(l.pattern=lT)}),e._zod.check=s=>{const l=s.value;if(n){if(!Number.isInteger(l)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?s.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort}):s.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,inclusive:!0,continue:!t.abort});return}}l<o&&s.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>r&&s.issues.push({origin:"number",input:l,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),hT=ge("$ZodCheckMaxLength",(e,t)=>{var n;ia.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!ig(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const o=a.value;if(o.length<=t.maximum)return;const s=sg(o);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),gT=ge("$ZodCheckMinLength",(e,t)=>{var n;ia.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!ig(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const o=a.value;if(o.length>=t.minimum)return;const s=sg(o);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),vT=ge("$ZodCheckLengthEquals",(e,t)=>{var n;ia.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!ig(o)&&o.length!==void 0}),e._zod.onattach.push(a=>{const o=a._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=a=>{const o=a.value,r=o.length;if(r===t.length)return;const s=sg(o),l=r>t.length;a.issues.push({origin:s,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),Ru=ge("$ZodCheckStringFormat",(e,t)=>{var n,a;ia.init(e,t),e._zod.onattach.push(o=>{const r=o._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),bT=ge("$ZodCheckRegex",(e,t)=>{Ru.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),yT=ge("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=uT),Ru.init(e,t)}),ST=ge("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=mT),Ru.init(e,t)}),xT=ge("$ZodCheckIncludes",(e,t)=>{ia.init(e,t);const n=xs(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(o=>{const r=o._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(a)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),kT=ge("$ZodCheckStartsWith",(e,t)=>{ia.init(e,t);const n=new RegExp(`^${xs(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=a=>{a.value.startsWith(t.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:a.value,inst:e,continue:!t.abort})}}),wT=ge("$ZodCheckEndsWith",(e,t)=>{ia.init(e,t);const n=new RegExp(`.*${xs(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const o=a._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=a=>{a.value.endsWith(t.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:a.value,inst:e,continue:!t.abort})}}),IT=ge("$ZodCheckOverwrite",(e,t)=>{ia.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class _T{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const a=t.split(`
|
|
3
|
-
`).filter(s=>s),o=Math.min(...a.map(s=>s.length-s.trimStart().length)),r=a.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(const s of r)this.content.push(s)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(r=>` ${r}`)];return new t(...n,o.join(`
|
|
4
|
-
`))}}const CT={major:4,minor:4,patch:3},Jt=ge("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=CT;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const o of a)for(const r of o._zod.onattach)r(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(s,l,m)=>{let d=es(s),h;for(const g of l){if(g._zod.def.when){if(RA(s)||!g._zod.def.when(s))continue}else if(d)continue;const y=s.issues.length,w=g._zod.check(s);if(w instanceof Promise&&m?.async===!1)throw new ps;if(h||w instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await w,s.issues.length!==y&&(d||(d=es(s,y)))});else{if(s.issues.length===y)continue;d||(d=es(s,y))}}return h?h.then(()=>s):s},r=(s,l,m)=>{if(es(s))return s.aborted=!0,s;const d=o(l,a,m);if(d instanceof Promise){if(m.async===!1)throw new ps;return d.then(h=>e._zod.parse(h,m))}return e._zod.parse(d,m)};e._zod.run=(s,l)=>{if(l.skipChecks)return e._zod.parse(s,l);if(l.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...l,skipChecks:!0});return d instanceof Promise?d.then(h=>r(h,s,l)):r(d,s,l)}const m=e._zod.parse(s,l);if(m instanceof Promise){if(l.async===!1)throw new ps;return m.then(d=>o(d,a,l))}return o(m,a,l)}}Ct(e,"~standard",()=>({validate:o=>{try{const r=TA(e,o);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return EA(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),dg=ge("$ZodString",(e,t)=>{Jt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??sT(e._zod.bag),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Qt=ge("$ZodStringFormat",(e,t)=>{Ru.init(e,t),dg.init(e,t)}),RT=ge("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=WA),Qt.init(e,t)}),PT=ge("$ZodUUID",(e,t)=>{if(t.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Db(a))}else t.pattern??(t.pattern=Db());Qt.init(e,t)}),AT=ge("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=GA),Qt.init(e,t)}),TT=ge("$ZodURL",(e,t)=>{Qt.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===nT.source&&!/^https?:\/\//i.test(a)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const o=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),ET=ge("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=ZA()),Qt.init(e,t)}),MT=ge("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=VA),Qt.init(e,t)}),jT=ge("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=UA),Qt.init(e,t)}),OT=ge("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=qA),Qt.init(e,t)}),$T=ge("$ZodULID",(e,t)=>{t.pattern??(t.pattern=zA),Qt.init(e,t)}),NT=ge("$ZodXID",(e,t)=>{t.pattern??(t.pattern=BA),Qt.init(e,t)}),DT=ge("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=FA),Qt.init(e,t)}),LT=ge("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=rT(t)),Qt.init(e,t)}),HT=ge("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=oT),Qt.init(e,t)}),UT=ge("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=iT(t)),Qt.init(e,t)}),qT=ge("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=KA),Qt.init(e,t)}),zT=ge("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=YA),Qt.init(e,t),e._zod.bag.format="ipv4"}),BT=ge("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=QA),Qt.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),FT=ge("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=XA),Qt.init(e,t)}),VT=ge("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=eT),Qt.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[o,r]=a;if(!r)throw new Error;const s=Number(r);if(`${s}`!==r)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Yx(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const KT=ge("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=tT),Qt.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Yx(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function WT(e){if(!Fx.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Yx(n)}const GT=ge("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Fx),Qt.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{WT(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),JT=ge("$ZodE164",(e,t)=>{t.pattern??(t.pattern=aT),Qt.init(e,t)});function ZT(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const o=JSON.parse(atob(a));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const YT=ge("$ZodJWT",(e,t)=>{Qt.init(e,t),e._zod.check=n=>{ZT(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Qx=ge("$ZodNumber",(e,t)=>{Jt.init(e,t),e._zod.pattern=e._zod.bag.pattern??Wx,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const r=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...r?{received:r}:{}}),n}}),QT=ge("$ZodNumberFormat",(e,t)=>{fT.init(e,t),Qx.init(e,t)}),XT=ge("$ZodBoolean",(e,t)=>{Jt.init(e,t),e._zod.pattern=cT,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),eE=ge("$ZodNull",(e,t)=>{Jt.init(e,t),e._zod.pattern=dT,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),tE=ge("$ZodUnknown",(e,t)=>{Jt.init(e,t),e._zod.parse=n=>n}),nE=ge("$ZodNever",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Lb(e,t,n){e.issues.length&&t.issues.push(...ts(n,e.issues)),t.value[n]=e.value}const aE=ge("$ZodArray",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const r=[];for(let s=0;s<o.length;s++){const l=o[s],m=t.element._zod.run({value:l,issues:[]},a);m instanceof Promise?r.push(m.then(d=>Lb(d,n,s))):Lb(m,n,s)}return r.length?Promise.all(r).then(()=>n):n}});function Jd(e,t,n,a,o,r){const s=n in a;if(e.issues.length){if(o&&r&&!s)return;t.issues.push(...ts(n,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function Xx(e){const t=Object.keys(e.shape);for(const a of t)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const n=bA(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function ek(e,t,n,a,o,r){const s=[],l=o.keySet,m=o.catchall._zod,d=m.def.type,h=m.optin==="optional",g=m.optout==="optional";for(const y in t){if(y==="__proto__"||l.has(y))continue;if(d==="never"){s.push(y);continue}const w=m.run({value:t[y],issues:[]},a);w instanceof Promise?e.push(w.then(_=>Jd(_,n,y,t,h,g))):Jd(w,n,y,t,h,g)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:r}),e.length?Promise.all(e).then(()=>n):n}const oE=ge("$ZodObject",(e,t)=>{if(Jt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const m={...l};return Object.defineProperty(t,"shape",{value:m}),m}})}const a=Iu(()=>Xx(t));Ct(e._zod,"propValues",()=>{const l=t.shape,m={};for(const d in l){const h=l[d]._zod;if(h.values){m[d]??(m[d]=new Set);for(const g of h.values)m[d].add(g)}}return m});const o=Ul,r=t.catchall;let s;e._zod.parse=(l,m)=>{s??(s=a.value);const d=l.value;if(!o(d))return l.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),l;l.value={};const h=[],g=s.shape;for(const y of s.keys){const w=g[y],_=w._zod.optin==="optional",P=w._zod.optout==="optional",M=w._zod.run({value:d[y],issues:[]},m);M instanceof Promise?h.push(M.then(C=>Jd(C,l,y,d,_,P))):Jd(M,l,y,d,_,P)}return r?ek(h,d,l,m,a.value,e):h.length?Promise.all(h).then(()=>l):l}}),iE=ge("$ZodObjectJIT",(e,t)=>{oE.init(e,t);const n=e._zod.parse,a=Iu(()=>Xx(t)),o=y=>{const w=new _T(["shape","payload","ctx"]),_=a.value,P=O=>{const j=Nb(O);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};w.write("const input = payload.value;");const M=Object.create(null);let C=0;for(const O of _.keys)M[O]=`key_${C++}`;w.write("const newResult = {};");for(const O of _.keys){const j=M[O],x=Nb(O),R=y[O],E=R?._zod?.optin==="optional",H=R?._zod?.optout==="optional";w.write(`const ${j} = ${P(O)};`),E&&H?w.write(`
|
|
5
|
-
if (${j}.issues.length) {
|
|
6
|
-
if (${x} in input) {
|
|
7
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
8
|
-
...iss,
|
|
9
|
-
path: iss.path ? [${x}, ...iss.path] : [${x}]
|
|
10
|
-
})));
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
if (${j}.value === undefined) {
|
|
15
|
-
if (${x} in input) {
|
|
16
|
-
newResult[${x}] = undefined;
|
|
17
|
-
}
|
|
18
|
-
} else {
|
|
19
|
-
newResult[${x}] = ${j}.value;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
`):E?w.write(`
|
|
23
|
-
if (${j}.issues.length) {
|
|
24
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
25
|
-
...iss,
|
|
26
|
-
path: iss.path ? [${x}, ...iss.path] : [${x}]
|
|
27
|
-
})));
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
if (${j}.value === undefined) {
|
|
31
|
-
if (${x} in input) {
|
|
32
|
-
newResult[${x}] = undefined;
|
|
33
|
-
}
|
|
34
|
-
} else {
|
|
35
|
-
newResult[${x}] = ${j}.value;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
`):w.write(`
|
|
39
|
-
const ${j}_present = ${x} in input;
|
|
40
|
-
if (${j}.issues.length) {
|
|
41
|
-
payload.issues = payload.issues.concat(${j}.issues.map(iss => ({
|
|
42
|
-
...iss,
|
|
43
|
-
path: iss.path ? [${x}, ...iss.path] : [${x}]
|
|
44
|
-
})));
|
|
45
|
-
}
|
|
46
|
-
if (!${j}_present && !${j}.issues.length) {
|
|
47
|
-
payload.issues.push({
|
|
48
|
-
code: "invalid_type",
|
|
49
|
-
expected: "nonoptional",
|
|
50
|
-
input: undefined,
|
|
51
|
-
path: [${x}]
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
if (${j}_present) {
|
|
56
|
-
if (${j}.value === undefined) {
|
|
57
|
-
newResult[${x}] = undefined;
|
|
58
|
-
} else {
|
|
59
|
-
newResult[${x}] = ${j}.value;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
`)}w.write("payload.value = newResult;"),w.write("return payload;");const $=w.compile();return(O,j)=>$(y,O,j)};let r;const s=Ul,l=!og.jitless,d=l&&gA.value,h=t.catchall;let g;e._zod.parse=(y,w)=>{g??(g=a.value);const _=y.value;return s(_)?l&&d&&w?.async===!1&&w.jitless!==!0?(r||(r=o(t.shape)),y=r(y,w),h?ek([],_,y,w,g,e):y):n(y,w):(y.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),y)}});function Hb(e,t,n,a){for(const r of e)if(r.issues.length===0)return t.value=r.value,t;const o=e.filter(r=>!es(r));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(r=>r.issues.map(s=>ni(s,a,ti())))}),t)}const tk=ge("$ZodUnion",(e,t)=>{Jt.init(e,t),Ct(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),Ct(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),Ct(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),Ct(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${a.map(o=>rg(o.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,o)=>{if(n)return n(a,o);let r=!1;const s=[];for(const l of t.options){const m=l._zod.run({value:a.value,issues:[]},o);if(m instanceof Promise)s.push(m),r=!0;else{if(m.issues.length===0)return m;s.push(m)}}return r?Promise.all(s).then(l=>Hb(l,a,e,o)):Hb(s,a,e,o)}}),rE=ge("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,tk.init(e,t);const n=e._zod.parse;Ct(e._zod,"propValues",()=>{const o={};for(const r of t.options){const s=r._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[l,m]of Object.entries(s)){o[l]||(o[l]=new Set);for(const d of m)o[l].add(d)}}return o});const a=Iu(()=>{const o=t.options,r=new Map;for(const s of o){const l=s._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const m of l){if(r.has(m))throw new Error(`Duplicate discriminator value "${String(m)}"`);r.set(m,s)}}return r});e._zod.parse=(o,r)=>{const s=o.value;if(!Ul(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const l=a.value.get(s?.[t.discriminator]);return l?l._zod.run(o,r):t.unionFallback||r.direction==="backward"?n(o,r):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(a.value.keys()),input:s,path:[t.discriminator],inst:e}),o)}}),sE=ge("$ZodIntersection",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value,r=t.left._zod.run({value:o,issues:[]},a),s=t.right._zod.run({value:o,issues:[]},a);return r instanceof Promise||s instanceof Promise?Promise.all([r,s]).then(([m,d])=>Ub(n,m,d)):Ub(n,r,s)}});function eh(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ss(e)&&Ss(t)){const n=Object.keys(t),a=Object.keys(e).filter(r=>n.indexOf(r)!==-1),o={...e,...t};for(const r of a){const s=eh(e[r],t[r]);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};o[r]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let a=0;a<e.length;a++){const o=e[a],r=t[a],s=eh(o,r);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ub(e,t,n){const a=new Map;let o;for(const l of t.issues)if(l.code==="unrecognized_keys"){o??(o=l);for(const m of l.keys)a.has(m)||a.set(m,{}),a.get(m).l=!0}else e.issues.push(l);for(const l of n.issues)if(l.code==="unrecognized_keys")for(const m of l.keys)a.has(m)||a.set(m,{}),a.get(m).r=!0;else e.issues.push(l);const r=[...a].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(r.length&&o&&e.issues.push({...o,keys:r}),es(e))return e;const s=eh(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const lE=ge("$ZodRecord",(e,t)=>{Jt.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Ss(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const r=[],s=t.keyType._zod.values;if(s){n.value={};const l=new Set;for(const d of s)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){l.add(typeof d=="number"?d.toString():d);const h=t.keyType._zod.run({value:d,issues:[]},a);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(h.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(w=>ni(w,a,ti())),input:d,path:[d],inst:e});continue}const g=h.value,y=t.valueType._zod.run({value:o[d],issues:[]},a);y instanceof Promise?r.push(y.then(w=>{w.issues.length&&n.issues.push(...ts(d,w.issues)),n.value[g]=w.value})):(y.issues.length&&n.issues.push(...ts(d,y.issues)),n.value[g]=y.value)}let m;for(const d in o)l.has(d)||(m=m??[],m.push(d));m&&m.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:m})}else{n.value={};for(const l of Reflect.ownKeys(o)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,l))continue;let m=t.keyType._zod.run({value:l,issues:[]},a);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&Wx.test(l)&&m.issues.length){const g=t.keyType._zod.run({value:Number(l),issues:[]},a);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(m=g)}if(m.issues.length){t.mode==="loose"?n.value[l]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map(g=>ni(g,a,ti())),input:l,path:[l],inst:e});continue}const h=t.valueType._zod.run({value:o[l],issues:[]},a);h instanceof Promise?r.push(h.then(g=>{g.issues.length&&n.issues.push(...ts(l,g.issues)),n.value[m.value]=g.value})):(h.issues.length&&n.issues.push(...ts(l,h.issues)),n.value[m.value]=h.value)}}return r.length?Promise.all(r).then(()=>n):n}}),cE=ge("$ZodEnum",(e,t)=>{Jt.init(e,t);const n=Lx(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(o=>vA.has(typeof o)).map(o=>typeof o=="string"?xs(o):o.toString()).join("|")})$`),e._zod.parse=(o,r)=>{const s=o.value;return a.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),dE=ge("$ZodLiteral",(e,t)=>{if(Jt.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(a=>typeof a=="string"?xs(a):a?xs(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,o)=>{const r=a.value;return n.has(r)||a.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),a}}),uE=ge("$ZodTransform",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new Dx(e.constructor.name);const o=t.transform(n.value,n);if(a.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(n.value=s,n.fallback=!0,n));if(o instanceof Promise)throw new ps;return n.value=o,n.fallback=!0,n}});function qb(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const nk=ge("$ZodOptional",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ct(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ct(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${rg(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const o=n.value,r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(s=>qb(s,o)):qb(r,o)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),mE=ge("$ZodExactOptional",(e,t)=>{nk.init(e,t),Ct(e._zod,"values",()=>t.innerType._zod.values),Ct(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),pE=ge("$ZodNullable",(e,t)=>{Jt.init(e,t),Ct(e._zod,"optin",()=>t.innerType._zod.optin),Ct(e._zod,"optout",()=>t.innerType._zod.optout),Ct(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${rg(n.source)}|null)$`):void 0}),Ct(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,a)=>n.value===null?n:t.innerType._zod.run(n,a)}),fE=ge("$ZodDefault",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Ct(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(r=>zb(r,t)):zb(o,t)}});function zb(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const hE=ge("$ZodPrefault",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Ct(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>(a.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,a))}),gE=ge("$ZodNonOptional",(e,t)=>{Jt.init(e,t),Ct(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),e._zod.parse=(n,a)=>{const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(r=>Bb(r,e)):Bb(o,e)}});function Bb(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const vE=ge("$ZodCatch",(e,t)=>{Jt.init(e,t),e._zod.optin="optional",Ct(e._zod,"optout",()=>t.innerType._zod.optout),Ct(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(r=>(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(s=>ni(s,a,ti()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(r=>ni(r,a,ti()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),ak=ge("$ZodPipe",(e,t)=>{Jt.init(e,t),Ct(e._zod,"values",()=>t.in._zod.values),Ct(e._zod,"optin",()=>t.in._zod.optin),Ct(e._zod,"optout",()=>t.out._zod.optout),Ct(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const r=t.out._zod.run(n,a);return r instanceof Promise?r.then(s=>sd(s,t.in,a)):sd(r,t.in,a)}const o=t.in._zod.run(n,a);return o instanceof Promise?o.then(r=>sd(r,t.out,a)):sd(o,t.out,a)}});function sd(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const bE=ge("$ZodPreprocess",(e,t)=>{ak.init(e,t)}),yE=ge("$ZodReadonly",(e,t)=>{Jt.init(e,t),Ct(e._zod,"propValues",()=>t.innerType._zod.propValues),Ct(e._zod,"values",()=>t.innerType._zod.values),Ct(e._zod,"optin",()=>t.innerType?._zod?.optin),Ct(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const o=t.innerType._zod.run(n,a);return o instanceof Promise?o.then(Fb):Fb(o)}});function Fb(e){return e.value=Object.freeze(e.value),e}const SE=ge("$ZodLazy",(e,t)=>{Jt.init(e,t),Ct(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),Ct(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),Ct(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),Ct(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),Ct(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),xE=ge("$ZodCustom",(e,t)=>{ia.init(e,t),Jt.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,o=t.fn(a);if(o instanceof Promise)return o.then(r=>Vb(r,n,a,e));Vb(o,n,a,e)}});function Vb(e,t,n,a){if(!e){const o={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(o.params=a._zod.def.params),t.issues.push(ql(o))}}var Kb;class kE{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const a=n[0];return this._map.set(t,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const a={...this.get(n)??{}};delete a.id;const o={...a,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function wE(){return new kE}(Kb=globalThis).__zod_globalRegistry??(Kb.__zod_globalRegistry=wE());const wl=globalThis.__zod_globalRegistry;function IE(e,t){return new e({type:"string",...et(t)})}function _E(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...et(t)})}function Wb(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...et(t)})}function CE(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...et(t)})}function RE(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...et(t)})}function PE(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...et(t)})}function AE(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...et(t)})}function TE(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...et(t)})}function EE(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...et(t)})}function ME(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...et(t)})}function jE(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...et(t)})}function OE(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...et(t)})}function $E(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...et(t)})}function NE(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...et(t)})}function DE(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...et(t)})}function LE(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...et(t)})}function HE(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...et(t)})}function UE(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...et(t)})}function qE(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...et(t)})}function zE(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...et(t)})}function BE(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...et(t)})}function FE(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...et(t)})}function VE(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...et(t)})}function KE(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...et(t)})}function WE(e,t){return new e({type:"string",format:"date",check:"string_format",...et(t)})}function GE(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...et(t)})}function JE(e,t){return new e({type:"string",format:"duration",check:"string_format",...et(t)})}function ZE(e,t){return new e({type:"number",checks:[],...et(t)})}function yX(e,t){return new e({type:"number",coerce:!0,checks:[],...et(t)})}function YE(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...et(t)})}function QE(e,t){return new e({type:"boolean",...et(t)})}function XE(e,t){return new e({type:"null",...et(t)})}function eM(e){return new e({type:"unknown"})}function tM(e,t){return new e({type:"never",...et(t)})}function Gb(e,t){return new Jx({check:"less_than",...et(t),value:e,inclusive:!1})}function Tp(e,t){return new Jx({check:"less_than",...et(t),value:e,inclusive:!0})}function Jb(e,t){return new Zx({check:"greater_than",...et(t),value:e,inclusive:!1})}function Ep(e,t){return new Zx({check:"greater_than",...et(t),value:e,inclusive:!0})}function Zb(e,t){return new pT({check:"multiple_of",...et(t),value:e})}function ok(e,t){return new hT({check:"max_length",...et(t),maximum:e})}function Zd(e,t){return new gT({check:"min_length",...et(t),minimum:e})}function ik(e,t){return new vT({check:"length_equals",...et(t),length:e})}function nM(e,t){return new bT({check:"string_format",format:"regex",...et(t),pattern:e})}function aM(e){return new yT({check:"string_format",format:"lowercase",...et(e)})}function oM(e){return new ST({check:"string_format",format:"uppercase",...et(e)})}function iM(e,t){return new xT({check:"string_format",format:"includes",...et(t),includes:e})}function rM(e,t){return new kT({check:"string_format",format:"starts_with",...et(t),prefix:e})}function sM(e,t){return new wT({check:"string_format",format:"ends_with",...et(t),suffix:e})}function js(e){return new IT({check:"overwrite",tx:e})}function lM(e){return js(t=>t.normalize(e))}function cM(){return js(e=>e.trim())}function dM(){return js(e=>e.toLowerCase())}function uM(){return js(e=>e.toUpperCase())}function mM(){return js(e=>hA(e))}function pM(e,t,n){return new e({type:"array",element:t,...et(n)})}function fM(e,t,n){const a=et(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function hM(e,t,n){return new e({type:"custom",check:"custom",fn:t,...et(n)})}function gM(e,t){const n=vM(a=>(a.addIssue=o=>{if(typeof o=="string")a.issues.push(ql(o,a.value,n._zod.def));else{const r=o;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),a.issues.push(ql(r))}},e(a.value,a)),t);return n}function vM(e,t){const n=new ia({check:"custom",...et(t)});return n._zod.check=e,n}function rk(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??wl,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function dn(e,t,n={path:[],schemaPath:[]}){var a;const o=e._zod.def,r=t.seen.get(e);if(r)return r.count++,n.schemaPath.includes(e)&&(r.cycle=n.path),r.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const l=e._zod.toJSONSchema?.();if(l)s.schema=l;else{const h={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,h);else{const y=s.schema,w=t.processors[o.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);w(e,t,y,h)}const g=e._zod.parent;g&&(s.ref||(s.ref=g),dn(g,t,h),t.seen.get(g).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&zn(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((a=s.schema).default??(a.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function sk(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=new Map;for(const s of e.seen.entries()){const l=e.metadataRegistry.get(s[0])?.id;if(l){const m=a.get(l);if(m&&m!==s[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(l,s[0])}}const o=s=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(s[0])?.id,y=e.external.uri??(_=>_);if(g)return{ref:y(g)};const w=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=w,{defId:w,ref:`${y("__shared")}#/${l}/${w}`}}if(s[1]===n)return{ref:"#"};const d=`#/${l}/`,h=s[1].schema.id??`__schema${e.counter++}`;return{defId:h,ref:d+h}},r=s=>{if(s[1].schema.$ref)return;const l=s[1],{ref:m,defId:d}=o(s);l.def={...l.schema},d&&(l.defId=d);const h=l.schema;for(const g in h)delete h[g];h.$ref=m};if(e.cycles==="throw")for(const s of e.seen.entries()){const l=s[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
64
|
-
|
|
65
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const s of e.seen.entries()){const l=s[1];if(t===s[0]){r(s);continue}if(e.external){const d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){r(s);continue}}if(e.metadataRegistry.get(s[0])?.id){r(s);continue}if(l.cycle){r(s);continue}if(l.count>1&&e.reused==="ref"){r(s);continue}}}function lk(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const m=e.seen.get(l);if(m.ref===null)return;const d=m.def??m.schema,h={...d},g=m.ref;if(m.ref=null,g){a(g);const w=e.seen.get(g),_=w.schema;if(_.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(_)):Object.assign(d,_),Object.assign(d,h),l._zod.parent===g)for(const M in d)M==="$ref"||M==="allOf"||M in h||delete d[M];if(_.$ref&&w.def)for(const M in d)M==="$ref"||M==="allOf"||M in w.def&&JSON.stringify(d[M])===JSON.stringify(w.def[M])&&delete d[M]}const y=l._zod.parent;if(y&&y!==g){a(y);const w=e.seen.get(y);if(w?.schema.$ref&&(d.$ref=w.schema.$ref,w.def))for(const _ in d)_==="$ref"||_==="allOf"||_ in w.def&&JSON.stringify(d[_])===JSON.stringify(w.def[_])&&delete d[_]}e.override({zodSchema:l,jsonSchema:d,path:m.path??[]})};for(const l of[...e.seen.entries()].reverse())a(l[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const l=e.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(l)}Object.assign(o,n.def??n.schema);const r=e.metadataRegistry.get(t)?.id;r!==void 0&&o.id===r&&delete o.id;const s=e.external?.defs??{};for(const l of e.seen.entries()){const m=l[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,s[m.defId]=m.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{const l=JSON.parse(JSON.stringify(o));return Object.defineProperty(l,"~standard",{value:{...t["~standard"],jsonSchema:{input:Yd(t,"input",e.processors),output:Yd(t,"output",e.processors)}},enumerable:!1,writable:!1}),l}catch{throw new Error("Error converting schema to JSON.")}}function zn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const a=e._zod.def;if(a.type==="transform")return!0;if(a.type==="array")return zn(a.element,n);if(a.type==="set")return zn(a.valueType,n);if(a.type==="lazy")return zn(a.getter(),n);if(a.type==="promise"||a.type==="optional"||a.type==="nonoptional"||a.type==="nullable"||a.type==="readonly"||a.type==="default"||a.type==="prefault")return zn(a.innerType,n);if(a.type==="intersection")return zn(a.left,n)||zn(a.right,n);if(a.type==="record"||a.type==="map")return zn(a.keyType,n)||zn(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:zn(a.in,n)||zn(a.out,n);if(a.type==="object"){for(const o in a.shape)if(zn(a.shape[o],n))return!0;return!1}if(a.type==="union"){for(const o of a.options)if(zn(o,n))return!0;return!1}if(a.type==="tuple"){for(const o of a.items)if(zn(o,n))return!0;return!!(a.rest&&zn(a.rest,n))}return!1}const bM=(e,t={})=>n=>{const a=rk({...n,processors:t});return dn(e,a),sk(a,e),lk(a,e)},Yd=(e,t,n={})=>a=>{const{libraryOptions:o,target:r}=a??{},s=rk({...o??{},target:r,io:t,processors:n});return dn(e,s),sk(s,e),lk(s,e)},yM={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},SM=(e,t,n,a)=>{const o=n;o.type="string";const{minimum:r,maximum:s,format:l,patterns:m,contentEncoding:d}=e._zod.bag;if(typeof r=="number"&&(o.minLength=r),typeof s=="number"&&(o.maxLength=s),l&&(o.format=yM[l]??l,o.format===""&&delete o.format,l==="time"&&delete o.format),d&&(o.contentEncoding=d),m&&m.size>0){const h=[...m];h.length===1?o.pattern=h[0].source:h.length>1&&(o.allOf=[...h.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},xM=(e,t,n,a)=>{const o=n,{minimum:r,maximum:s,format:l,multipleOf:m,exclusiveMaximum:d,exclusiveMinimum:h}=e._zod.bag;typeof l=="string"&&l.includes("int")?o.type="integer":o.type="number";const g=typeof h=="number"&&h>=(r??Number.NEGATIVE_INFINITY),y=typeof d=="number"&&d<=(s??Number.POSITIVE_INFINITY),w=t.target==="draft-04"||t.target==="openapi-3.0";g?w?(o.minimum=h,o.exclusiveMinimum=!0):o.exclusiveMinimum=h:typeof r=="number"&&(o.minimum=r),y?w?(o.maximum=d,o.exclusiveMaximum=!0):o.exclusiveMaximum=d:typeof s=="number"&&(o.maximum=s),typeof m=="number"&&(o.multipleOf=m)},kM=(e,t,n,a)=>{n.type="boolean"},wM=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},IM=(e,t,n,a)=>{n.not={}},_M=(e,t,n,a)=>{},CM=(e,t,n,a)=>{const o=e._zod.def,r=Lx(o.entries);r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),n.enum=r},RM=(e,t,n,a)=>{const o=e._zod.def,r=[];for(const s of o.values)if(s===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");r.push(Number(s))}else r.push(s);if(r.length!==0)if(r.length===1){const s=r[0];n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[s]:n.const=s}else r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),r.every(s=>typeof s=="boolean")&&(n.type="boolean"),r.every(s=>s===null)&&(n.type="null"),n.enum=r},PM=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},AM=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},TM=(e,t,n,a)=>{const o=n,r=e._zod.def,{minimum:s,maximum:l}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof l=="number"&&(o.maxItems=l),o.type="array",o.items=dn(r.element,t,{...a,path:[...a.path,"items"]})},EM=(e,t,n,a)=>{const o=n,r=e._zod.def;o.type="object",o.properties={};const s=r.shape;for(const d in s)o.properties[d]=dn(s[d],t,{...a,path:[...a.path,"properties",d]});const l=new Set(Object.keys(s)),m=new Set([...l].filter(d=>{const h=r.shape[d]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));m.size>0&&(o.required=Array.from(m)),r.catchall?._zod.def.type==="never"?o.additionalProperties=!1:r.catchall?r.catchall&&(o.additionalProperties=dn(r.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},MM=(e,t,n,a)=>{const o=e._zod.def,r=o.inclusive===!1,s=o.options.map((l,m)=>dn(l,t,{...a,path:[...a.path,r?"oneOf":"anyOf",m]}));r?n.oneOf=s:n.anyOf=s},jM=(e,t,n,a)=>{const o=e._zod.def,r=dn(o.left,t,{...a,path:[...a.path,"allOf",0]}),s=dn(o.right,t,{...a,path:[...a.path,"allOf",1]}),l=d=>"allOf"in d&&Object.keys(d).length===1,m=[...l(r)?r.allOf:[r],...l(s)?s.allOf:[s]];n.allOf=m},OM=(e,t,n,a)=>{const o=n,r=e._zod.def;o.type="object";const s=r.keyType,m=s._zod.bag?.patterns;if(r.mode==="loose"&&m&&m.size>0){const h=dn(r.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});o.patternProperties={};for(const g of m)o.patternProperties[g.source]=h}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=dn(r.keyType,t,{...a,path:[...a.path,"propertyNames"]})),o.additionalProperties=dn(r.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const d=s._zod.values;if(d){const h=[...d].filter(g=>typeof g=="string"||typeof g=="number");h.length>0&&(o.required=h)}},$M=(e,t,n,a)=>{const o=e._zod.def,r=dn(o.innerType,t,a),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[r,{type:"null"}]},NM=(e,t,n,a)=>{const o=e._zod.def;dn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType},DM=(e,t,n,a)=>{const o=e._zod.def;dn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},LM=(e,t,n,a)=>{const o=e._zod.def;dn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},HM=(e,t,n,a)=>{const o=e._zod.def;dn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},UM=(e,t,n,a)=>{const o=e._zod.def,r=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?r?o.out:o.in:o.out;dn(s,t,a);const l=t.seen.get(e);l.ref=s},qM=(e,t,n,a)=>{const o=e._zod.def;dn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType,n.readOnly=!0},ck=(e,t,n,a)=>{const o=e._zod.def;dn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType},zM=(e,t,n,a)=>{const o=e._zod.innerType;dn(o,t,a);const r=t.seen.get(e);r.ref=o},BM=ge("ZodISODateTime",(e,t)=>{LT.init(e,t),en.init(e,t)});function wn(e){return KE(BM,e)}const FM=ge("ZodISODate",(e,t)=>{HT.init(e,t),en.init(e,t)});function VM(e){return WE(FM,e)}const KM=ge("ZodISOTime",(e,t)=>{UT.init(e,t),en.init(e,t)});function WM(e){return GE(KM,e)}const GM=ge("ZodISODuration",(e,t)=>{qT.init(e,t),en.init(e,t)});function JM(e){return JE(GM,e)}const dk=(e,t)=>{zx.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>AA(e,n)},flatten:{value:n=>PA(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Xf,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Xf,2)}},isEmpty:{get(){return e.issues.length===0}}})},ZM=ge("ZodError",dk),$a=ge("ZodError",dk,{Parent:Error}),YM=lg($a),QM=cg($a),XM=_u($a),ej=Cu($a),tj=MA($a),nj=jA($a),aj=OA($a),oj=$A($a),ij=NA($a),rj=DA($a),sj=LA($a),lj=HA($a),Yb=new WeakMap;function uc(e,t,n){const a=Object.getPrototypeOf(e);let o=Yb.get(a);if(o||(o=new Set,Yb.set(a,o)),!o.has(t)){o.add(t);for(const r in n){const s=n[r];Object.defineProperty(a,r,{configurable:!0,enumerable:!1,get(){const l=s.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const Zt=ge("ZodType",(e,t)=>(Jt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Yd(e,"input"),output:Yd(e,"output")}}),e.toJSONSchema=bM(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>YM(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>XM(e,n,a),e.parseAsync=async(n,a)=>QM(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>ej(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>tj(e,n,a),e.decode=(n,a)=>nj(e,n,a),e.encodeAsync=async(n,a)=>aj(e,n,a),e.decodeAsync=async(n,a)=>oj(e,n,a),e.safeEncode=(n,a)=>ij(e,n,a),e.safeDecode=(n,a)=>rj(e,n,a),e.safeEncodeAsync=async(n,a)=>sj(e,n,a),e.safeDecodeAsync=async(n,a)=>lj(e,n,a),uc(e,"ZodType",{check(...n){const a=this.def;return this.clone(Ai(a,{checks:[...a.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return Ti(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(Qj(n,a))},superRefine(n,a){return this.check(Xj(n,a))},overwrite(n){return this.check(js(n))},optional(){return ty(this)},exactOptional(){return Hj(this)},nullable(){return ny(this)},nullish(){return ty(ny(this))},nonoptional(n){return Vj(this,n)},array(){return p(this)},or(n){return Tt([this,n])},and(n){return $j(this,n)},transform(n){return ay(this,gk(n))},default(n){return zj(this,n)},prefault(n){return Fj(this,n)},catch(n){return Wj(this,n)},pipe(n){return ay(this,n)},readonly(){return Zj(this)},describe(n){const a=this.clone();return wl.add(a,{description:n}),a},meta(...n){if(n.length===0)return wl.get(this);const a=this.clone();return wl.add(a,n[0]),a},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){return wl.get(e)?.description},configurable:!0}),e)),uk=ge("_ZodString",(e,t)=>{dg.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(a,o,r)=>SM(e,a,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,uc(e,"_ZodString",{regex(...a){return this.check(nM(...a))},includes(...a){return this.check(iM(...a))},startsWith(...a){return this.check(rM(...a))},endsWith(...a){return this.check(sM(...a))},min(...a){return this.check(Zd(...a))},max(...a){return this.check(ok(...a))},length(...a){return this.check(ik(...a))},nonempty(...a){return this.check(Zd(1,...a))},lowercase(a){return this.check(aM(a))},uppercase(a){return this.check(oM(a))},trim(){return this.check(cM())},normalize(...a){return this.check(lM(...a))},toLowerCase(){return this.check(dM())},toUpperCase(){return this.check(uM())},slugify(){return this.check(mM())}})}),cj=ge("ZodString",(e,t)=>{dg.init(e,t),uk.init(e,t),e.email=n=>e.check(_E(dj,n)),e.url=n=>e.check(TE(uj,n)),e.jwt=n=>e.check(VE(Cj,n)),e.emoji=n=>e.check(EE(mj,n)),e.guid=n=>e.check(Wb(Qb,n)),e.uuid=n=>e.check(CE(ld,n)),e.uuidv4=n=>e.check(RE(ld,n)),e.uuidv6=n=>e.check(PE(ld,n)),e.uuidv7=n=>e.check(AE(ld,n)),e.nanoid=n=>e.check(ME(pj,n)),e.guid=n=>e.check(Wb(Qb,n)),e.cuid=n=>e.check(jE(fj,n)),e.cuid2=n=>e.check(OE(hj,n)),e.ulid=n=>e.check($E(gj,n)),e.base64=n=>e.check(zE(wj,n)),e.base64url=n=>e.check(BE(Ij,n)),e.xid=n=>e.check(NE(vj,n)),e.ksuid=n=>e.check(DE(bj,n)),e.ipv4=n=>e.check(LE(yj,n)),e.ipv6=n=>e.check(HE(Sj,n)),e.cidrv4=n=>e.check(UE(xj,n)),e.cidrv6=n=>e.check(qE(kj,n)),e.e164=n=>e.check(FE(_j,n)),e.datetime=n=>e.check(wn(n)),e.date=n=>e.check(VM(n)),e.time=n=>e.check(WM(n)),e.duration=n=>e.check(JM(n))});function i(e){return IE(cj,e)}const en=ge("ZodStringFormat",(e,t)=>{Qt.init(e,t),uk.init(e,t)}),dj=ge("ZodEmail",(e,t)=>{AT.init(e,t),en.init(e,t)}),Qb=ge("ZodGUID",(e,t)=>{RT.init(e,t),en.init(e,t)}),ld=ge("ZodUUID",(e,t)=>{PT.init(e,t),en.init(e,t)}),uj=ge("ZodURL",(e,t)=>{TT.init(e,t),en.init(e,t)}),mj=ge("ZodEmoji",(e,t)=>{ET.init(e,t),en.init(e,t)}),pj=ge("ZodNanoID",(e,t)=>{MT.init(e,t),en.init(e,t)}),fj=ge("ZodCUID",(e,t)=>{jT.init(e,t),en.init(e,t)}),hj=ge("ZodCUID2",(e,t)=>{OT.init(e,t),en.init(e,t)}),gj=ge("ZodULID",(e,t)=>{$T.init(e,t),en.init(e,t)}),vj=ge("ZodXID",(e,t)=>{NT.init(e,t),en.init(e,t)}),bj=ge("ZodKSUID",(e,t)=>{DT.init(e,t),en.init(e,t)}),yj=ge("ZodIPv4",(e,t)=>{zT.init(e,t),en.init(e,t)}),Sj=ge("ZodIPv6",(e,t)=>{BT.init(e,t),en.init(e,t)}),xj=ge("ZodCIDRv4",(e,t)=>{FT.init(e,t),en.init(e,t)}),kj=ge("ZodCIDRv6",(e,t)=>{VT.init(e,t),en.init(e,t)}),wj=ge("ZodBase64",(e,t)=>{KT.init(e,t),en.init(e,t)}),Ij=ge("ZodBase64URL",(e,t)=>{GT.init(e,t),en.init(e,t)}),_j=ge("ZodE164",(e,t)=>{JT.init(e,t),en.init(e,t)}),Cj=ge("ZodJWT",(e,t)=>{YT.init(e,t),en.init(e,t)}),mk=ge("ZodNumber",(e,t)=>{Qx.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(a,o,r)=>xM(e,a,o),uc(e,"ZodNumber",{gt(a,o){return this.check(Jb(a,o))},gte(a,o){return this.check(Ep(a,o))},min(a,o){return this.check(Ep(a,o))},lt(a,o){return this.check(Gb(a,o))},lte(a,o){return this.check(Tp(a,o))},max(a,o){return this.check(Tp(a,o))},int(a){return this.check(Xb(a))},safe(a){return this.check(Xb(a))},positive(a){return this.check(Jb(0,a))},nonnegative(a){return this.check(Ep(0,a))},negative(a){return this.check(Gb(0,a))},nonpositive(a){return this.check(Tp(0,a))},multipleOf(a,o){return this.check(Zb(a,o))},step(a,o){return this.check(Zb(a,o))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function u(e){return ZE(mk,e)}const Rj=ge("ZodNumberFormat",(e,t)=>{QT.init(e,t),mk.init(e,t)});function Xb(e){return YE(Rj,e)}const Pj=ge("ZodBoolean",(e,t)=>{XT.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>kM(e,n,a)});function A(e){return QE(Pj,e)}const Aj=ge("ZodNull",(e,t)=>{eE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>wM(e,n,a)});function mc(e){return XE(Aj,e)}const Tj=ge("ZodUnknown",(e,t)=>{tE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>_M()});function se(){return eM(Tj)}const Ej=ge("ZodNever",(e,t)=>{nE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>IM(e,n,a)});function pk(e){return tM(Ej,e)}const Mj=ge("ZodArray",(e,t)=>{aE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>TM(e,n,a,o),e.element=t.element,uc(e,"ZodArray",{min(n,a){return this.check(Zd(n,a))},nonempty(n){return this.check(Zd(1,n))},max(n,a){return this.check(ok(n,a))},length(n,a){return this.check(ik(n,a))},unwrap(){return this.element}})});function p(e,t){return pM(Mj,e,t)}const fk=ge("ZodObject",(e,t)=>{iE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>EM(e,n,a,o),Ct(e,"shape",()=>t.shape),uc(e,"ZodObject",{keyof(){return b(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:se()})},loose(){return this.clone({...this._zod.def,catchall:se()})},strict(){return this.clone({...this._zod.def,catchall:pk()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return kA(this,n)},safeExtend(n){return wA(this,n)},merge(n){return IA(this,n)},pick(n){return SA(this,n)},omit(n){return xA(this,n)},partial(...n){return _A(vk,this,n[0])},required(...n){return CA(bk,this,n[0])}})});function c(e,t){const n={type:"object",shape:e??{},...et(t)};return new fk(n)}function Mp(e,t){return new fk({type:"object",shape:e,catchall:pk(),...et(t)})}const hk=ge("ZodUnion",(e,t)=>{tk.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>MM(e,n,a,o),e.options=t.options});function Tt(e,t){return new hk({type:"union",options:e,...et(t)})}const jj=ge("ZodDiscriminatedUnion",(e,t)=>{hk.init(e,t),rE.init(e,t)});function vt(e,t,n){return new jj({type:"union",options:t,discriminator:e,...et(n)})}const Oj=ge("ZodIntersection",(e,t)=>{sE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>jM(e,n,a,o)});function $j(e,t){return new Oj({type:"intersection",left:e,right:t})}const ey=ge("ZodRecord",(e,t)=>{lE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>OM(e,n,a,o),e.keyType=t.keyType,e.valueType=t.valueType});function oe(e,t,n){return!t||!t._zod?new ey({type:"record",keyType:i(),valueType:e,...et(t)}):new ey({type:"record",keyType:e,valueType:t,...et(n)})}const th=ge("ZodEnum",(e,t)=>{cE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(a,o,r)=>CM(e,a,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,o)=>{const r={};for(const s of a)if(n.has(s))r[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new th({...t,checks:[],...et(o),entries:r})},e.exclude=(a,o)=>{const r={...t.entries};for(const s of a)if(n.has(s))delete r[s];else throw new Error(`Key ${s} not found in enum`);return new th({...t,checks:[],...et(o),entries:r})}});function b(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new th({type:"enum",entries:n,...et(t)})}const Nj=ge("ZodLiteral",(e,t)=>{dE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>RM(e,n,a),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function S(e,t){return new Nj({type:"literal",values:Array.isArray(e)?e:[e],...et(t)})}const Dj=ge("ZodTransform",(e,t)=>{uE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>AM(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new Dx(e.constructor.name);n.addIssue=r=>{if(typeof r=="string")n.issues.push(ql(r,n.value,t));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),n.issues.push(ql(s))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(r=>(n.value=r,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function gk(e){return new Dj({type:"transform",transform:e})}const vk=ge("ZodOptional",(e,t)=>{nk.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>ck(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function ty(e){return new vk({type:"optional",innerType:e})}const Lj=ge("ZodExactOptional",(e,t)=>{mE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>ck(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function Hj(e){return new Lj({type:"optional",innerType:e})}const Uj=ge("ZodNullable",(e,t)=>{pE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>$M(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function ny(e){return new Uj({type:"nullable",innerType:e})}const qj=ge("ZodDefault",(e,t)=>{fE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>DM(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function zj(e,t){return new qj({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Ux(t)}})}const Bj=ge("ZodPrefault",(e,t)=>{hE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>LM(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function Fj(e,t){return new Bj({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Ux(t)}})}const bk=ge("ZodNonOptional",(e,t)=>{gE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>NM(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function Vj(e,t){return new bk({type:"nonoptional",innerType:e,...et(t)})}const Kj=ge("ZodCatch",(e,t)=>{vE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>HM(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wj(e,t){return new Kj({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const yk=ge("ZodPipe",(e,t)=>{ak.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>UM(e,n,a,o),e.in=t.in,e.out=t.out});function ay(e,t){return new yk({type:"pipe",in:e,out:t})}const Gj=ge("ZodPreprocess",(e,t)=>{yk.init(e,t),bE.init(e,t)}),Jj=ge("ZodReadonly",(e,t)=>{yE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>qM(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function Zj(e){return new Jj({type:"readonly",innerType:e})}const Yj=ge("ZodLazy",(e,t)=>{SE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>zM(e,n,a,o),e.unwrap=()=>e._zod.def.getter()});function Sk(e){return new Yj({type:"lazy",getter:e})}const xk=ge("ZodCustom",(e,t)=>{xE.init(e,t),Zt.init(e,t),e._zod.processJSONSchema=(n,a,o)=>PM(e,n)});function jp(e,t){return fM(xk,(()=>!0),t)}function Qj(e,t={}){return hM(xk,e,t)}function Xj(e,t){return gM(e,t)}function or(e){const t=Sk(()=>Tt([i(e),u(),A(),mc(),p(t),oe(i(),t)]));return t}function eO(e,t){return new Gj({type:"pipe",in:gk(e),out:t})}const Fn={custom:"custom"},tO=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),nO=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function aO(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const o=t.byteLength*8,r=new DataView(a.buffer);r.setUint32(n-8,Math.floor(o/4294967296),!1),r.setUint32(n-4,o>>>0,!1);const s=new Uint32Array(tO),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let C=0;C<16;C+=1)l[C]=r.getUint32(m+C*4,!1);for(let C=16;C<64;C+=1){const $=l[C-15],O=l[C-2],j=uo($,7)^uo($,18)^$>>>3,x=uo(O,17)^uo(O,19)^O>>>10;l[C]=l[C-16]+j+l[C-7]+x>>>0}let d=s[0],h=s[1],g=s[2],y=s[3],w=s[4],_=s[5],P=s[6],M=s[7];for(let C=0;C<64;C+=1){const $=w&_^~w&P,O=d&h^d&g^h&g,j=uo(d,2)^uo(d,13)^uo(d,22),x=uo(w,6)^uo(w,11)^uo(w,25),R=M+x+$+nO[C]+l[C]>>>0,E=j+O>>>0;M=P,P=_,_=w,w=y+R>>>0,y=g,g=h,h=d,d=R+E>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+P>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function uo(e,t){return e>>>t|e<<32-t}const oO=2e3,kk=25e7,T=i().trim().min(1).max(240),F=i().regex(/^[a-f0-9]{64}$/),Ce=i().datetime({offset:!0}),_n=oe(i(),se()).default({}),G=c({id:T,contentHash:F}).strict(),Kt=G.extend({revision:u().int().positive()}).strict(),cn=c({id:T,path:i().trim().min(1).max(oO).refine(sO),contentHash:F,sizeBytes:u().int().nonnegative().max(kk),mediaType:i().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),ha=c({id:T,contentHash:F,mediaType:i().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(kk).nullable().default(null)}).strict(),pc=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function iO(e){return`${JSON.stringify(nh(e),null,2)}
|
|
66
|
-
`}function ug(e){return aO(e)}function _t(e){return ug(iO(e))}function rO(e,t){const{contentHash:n,...a}=e,o=_t(a);if(n!==o)throw new Error(`${t} contentHash is ${n}; expected ${o}.`)}function sO(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function nh(e){return Array.isArray(e)?e.map(nh):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,nh(n)]))}const Pu=c({provider:T,model:T,revision:i().trim().min(1).max(500).nullable().default(null),artifactHash:F.nullable().default(null),tokenizerRevision:i().trim().min(1).max(500).nullable().default(null),chatTemplateHash:F.nullable().default(null)}).strict(),mg=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],pr=b(mg),un=c({providerId:pr,modelId:i().trim().min(1).max(300)}),Au=b(["active","preview","planned","deprecated"]),wk=b(["openpond-account","openpond-managed","codex-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),lO=b(["none","local_secret","env","openpond_account","codex_login","chatgpt_subscription","hosted"]),oy=c({connected:A().default(!1),source:lO.default("none"),redacted:i().nullable().default(null),lastValidatedAt:i().nullable().default(null),lastError:i().nullable().default(null)}),ah=c({hostedOpChat:A().default(!1),localRuntime:A().default(!0),localByok:A().default(!1),hostedByok:A().default(!1)}),cO=b(["hosted","provider","manual","none"]),oh=c({chatCompletions:A().default(!0),streaming:A().default(!0),modelDiscovery:cO.default("none"),toolCalling:A().default(!1),reasoning:A().default(!1),imageInput:A().default(!1),structuredOutput:A().default(!1)}),dO=b(["hosted","provider","curated","manual","cache"]),ih=c({streaming:A().default(!0),toolCalling:A().default(!1),reasoning:A().default(!1),reasoningEfforts:p(b(["off","low","medium","high","xhigh","max"])).default([]),vision:A().default(!1),structuredOutput:A().default(!1)}),uO=c({id:i().trim().min(1).max(300),providerId:pr,displayName:i().trim().min(1).max(300),contextWindow:u().int().positive().nullable().default(null),outputLimit:u().int().positive().nullable().default(null),lifecycleStatus:Au.default("active"),source:dO,capabilities:ih.default(()=>ih.parse({})),raw:oe(i(),se()).optional()}),mO=c({providerId:pr,models:p(uO).default([]),fetchedAt:i().nullable().default(null),lastError:i().nullable().default(null),source:b(["none","hosted","provider","curated","manual"]).default("none")}),pO=c({enabled:A().default(!1),baseUrl:i().trim().min(1).max(2048).nullable().default(null),defaultModel:i().trim().min(1).max(300).nullable().default(null),modelOverrides:p(i().trim().min(1).max(300)).max(500).default([]),updatedAt:i().nullable().default(null)}),fO=c({enabled:A().optional(),baseUrl:i().trim().min(1).max(2048).nullable().optional(),defaultModel:i().trim().min(1).max(300).nullable().optional(),modelOverrides:p(i().trim().min(1).max(300)).max(500).optional()}),hO=c({id:i().trim().min(1).max(300),displayName:i().trim().min(1).max(300),contextWindow:u().int().positive().nullable().optional(),outputLimit:u().int().positive().nullable().optional(),lifecycleStatus:Au.optional(),capabilities:ih.partial().optional()}),gO=c({id:pr,displayName:i().trim().min(1).max(160),lifecycleStatus:Au.default("active"),credentialModes:p(wk).default([]),routing:ah,capabilities:oh,defaultEnabled:A().optional(),defaultBaseUrl:i().trim().min(1).max(2048).nullable().optional(),defaultModel:i().trim().min(1).max(300).nullable().optional(),modelCacheSource:b(["none","hosted","provider","curated","manual"]),models:p(hO).default([])});c({version:S(1).default(1),generatedAt:i().datetime(),providers:p(gO)});const vO=c({id:pr,displayName:i().trim().min(1).max(160),lifecycleStatus:Au.default("active"),credentialModes:p(wk).default([]),routing:ah.default(()=>ah.parse({})),capabilities:oh.default(()=>oh.parse({})),credential:oy.default(()=>oy.parse({})),enabled:A().default(!1),available:A().default(!1),defaultModel:i().trim().min(1).max(300).nullable().default(null),modelIds:p(i().trim().min(1).max(300)).max(1e3).default([]),lastError:i().nullable().default(null)}),iy=c({version:S(1).default(1),providers:oe(i(),pO).default({}),statuses:oe(i(),vO).default({}),modelCaches:oe(i(),mO).default({}),updatedAt:i().nullable().default(null)});c({providers:oe(i(),fO).optional()});c({source:b(["local_secret","env"]).default("local_secret"),value:i().min(1).max(2e4).optional(),envVar:i().trim().min(1).max(160).optional()}).superRefine((e,t)=>{e.source==="env"&&!e.envVar&&t.addIssue({code:"custom",path:["envVar"],message:"envVar is required when provider credential source is env."}),e.source==="local_secret"&&!e.value&&t.addIssue({code:"custom",path:["value"],message:"value is required when provider credential source is local_secret."})});c({source:b(["local_secret","env","chatgpt_subscription"]).optional()});c({modelId:i().trim().min(1).max(300).optional(),baseUrl:i().trim().min(1).max(2048).optional()});c({query:i().trim().max(200).optional(),refresh:A().default(!1),limit:u().int().positive().max(500).default(100)});c({query:i().trim().max(200).optional(),force:A().default(!1)});const bO=["coding","research","review","test","docs","planner","summarizer"];b(bO);const Os=i().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),Ik=b(["none","worktree","copy_on_write"]),_k=b(["read_only","workspace_write","full_tools"]),Ck=b(["disabled","parent_scoped"]),Tu=b(["manual","balanced","proactive"]),yO=b(["queued","running","completed","failed","cancelled","needs_resume"]),Rk=["subagent.started","subagent.reported","subagent.completed","subagent.progress","subagent.failed","subagent.cancelled","subagent.cleanup","subagent.workspace_retained","subagent.workspace_retention_expiring","subagent.archived","subagent.message"];b(Rk);const SO=[{id:"coding",label:"Coding",description:"Make scoped code changes and return patch, diff, and test evidence.",defaultToolPolicy:"full_tools"},{id:"research",label:"Research",description:"Inspect docs, code, web or repo context and return cited findings.",defaultToolPolicy:"full_tools"},{id:"review",label:"Review",description:"Inspect diffs or implementation plans and return ranked findings.",defaultToolPolicy:"full_tools"},{id:"test",label:"Test",description:"Run or design validation in isolation and return command evidence.",defaultToolPolicy:"full_tools"},{id:"docs",label:"Docs",description:"Update or draft project documentation in an isolated target.",defaultToolPolicy:"full_tools"},{id:"planner",label:"Planner",description:"Decompose a goal into child assignments and context packs.",defaultToolPolicy:"full_tools"},{id:"summarizer",label:"Summarizer",description:"Compact transcripts, child results, and goal state for parent context.",defaultToolPolicy:"full_tools"}],pg=c({id:Os,enabled:A().default(!0),modelRef:un.nullable().default(null),isolationMode:Ik.default("none"),maxConcurrentRuns:u().int().min(1).max(16).default(1),toolPolicy:_k.default("read_only"),background:A().default(!0),peerMessages:Ck.default("parent_scoped")}),zl=c({enabled:A().default(!0),workspaceDefaultsVersion:S(1).default(1),toolDefaultsVersion:S(1).default(1),delegationMode:Tu.default("manual"),defaultModelRef:un.nullable().default(null),roles:p(pg).max(64).default(()=>Tk()),maxConcurrentRuns:u().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:u().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:u().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:EO(e.roles)})),Tl=c({kind:b(["session","turn","file","diff","artifact"]),id:i().trim().min(1).max(500),label:i().trim().min(1).max(500)}),xO=c({kind:b(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:u().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:u().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:A().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),kO=b(["orient","edit","validate","report"]),wO=c({command:i().trim().min(1).max(2e3),status:b(["passed","failed","unknown"]).default("unknown"),exitCode:u().int().nullable().default(null),outputSummary:i().trim().max(5e3).nullable().default(null),startedAt:i().nullable().default(null),completedAt:i().nullable().default(null)}),IO=c({phase:kO.default("orient"),inspectedFiles:p(i().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:p(i().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:p(i().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:p(i().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:p(i().trim().min(1).max(1e3)).max(200).default([]),changedFiles:p(i().trim().min(1).max(1e3)).max(500).default([]),patchRefs:p(Tl).max(100).default([]),validationAttempts:p(wO).max(100).default([]),latestMeaningfulActivity:i().trim().max(5e3).nullable().default(null),currentBlocker:i().trim().max(5e3).nullable().default(null),updatedAt:i().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),_O=c({summary:i().trim().max(2e4).default(""),findings:p(i().trim().min(1).max(5e3)).max(200).default([]),artifacts:p(Tl).max(200).default([]),patchRef:Tl.nullable().default(null),diffRef:Tl.nullable().default(null),testsRun:p(i().trim().min(1).max(2e3)).max(100).default([]),blockers:p(i().trim().min(1).max(5e3)).max(100).default([]),confidence:b(["low","medium","high"]).nullable().default(null),followUpNeeded:A().default(!1)}),Pk=c({id:i().trim().min(1).max(200),parentSessionId:i().trim().min(1).max(200),parentTurnId:i().trim().min(1).max(200).nullable().default(null),childSessionId:i().trim().min(1).max(200).nullable().default(null),roleId:Os,objective:i().trim().min(1).max(5e4),modelRef:un.nullable().default(null),isolationMode:Ik.default("none"),toolPolicy:_k.default("read_only"),background:A().default(!0),peerMessages:Ck.default("parent_scoped"),status:yO.default("queued"),progress:IO,evidenceRetention:xO,createdAt:i(),startedAt:i().nullable().default(null),completedAt:i().nullable().default(null),updatedAt:i().nullable().default(null),error:i().nullable().default(null),report:_O.nullable().default(null),metadata:oe(i(),se()).optional().default({})}),Ak=b(["cleanup","archive","cleanup_and_archive"]);c({action:Ak,reason:i().trim().min(1).max(2e3).nullable().default(null)});c({action:Ak,run:Pk,workspaceCleanup:oe(i(),se()).nullable().default(null),sessionArchive:oe(i(),se()).nullable().default(null),nextStep:i()});const CO=b(["question","answer","handoff","artifact","status","blocker"]),RO=b(["normal","interrupt"]),PO=c({inputIds:p(i()).default([]),status:b(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:p(i().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:p(i().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:i().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:i().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:i().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:i().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:i().trim().min(1).max(200).nullable().default(null),wakeParentReason:i().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:p(i().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:p(i().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:p(i().trim().min(1).max(200)).max(200).default([]),reason:i().trim().min(1).max(1e3).nullable().default(null)}),AO=c({id:i().trim().min(1).max(200),fromRunId:i().trim().min(1).max(200),toRunId:i().trim().min(1).max(200).nullable().default(null),toRole:Os.nullable().default(null),kind:CO,priority:RO.optional(),body:i().trim().min(1).max(5e4),refs:p(Tl).max(100).default([]),delivery:PO.optional(),createdAt:i()});function Tk(){return SO.map(e=>pg.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function TO(){return zl.parse({})}function EO(e){const t=Tk(),n=new Map(t.map(o=>[o.id,o])),a=[];for(const o of e??[]){const r=pg.parse(o);n.has(r.id)?n.set(r.id,r):a.push(r)}return[...t.map(o=>n.get(o.id)??o),...a]}const MO=b(["task.inbox","task.input","task.wait","session.started","session.title.updated","turn.started","assistant.delta","assistant.reasoning.delta","tool.started","tool.completed","skill.selected","skill.loaded","skill.load_failed","user_question.asked","user_question.answered","user_question.dismissed","approval.requested","approval.resolved","command.output","workspace_action","workspace_action_result","workspace.diff","create_improve.updated","session.context.updated","session.compaction.started","session.compaction.completed","session.compaction.failed","goal.continuation.started","goal.continuation.skipped","goal.continuation.failed","harness.refiner.queued","harness.refiner.started","harness.refiner.completed","harness.refiner.failed","turn.completed","turn.failed","turn.interrupted","session.closed",...Rk,"diagnostic"]),ry=c({id:i(),sequence:u().int().positive().optional(),sessionId:i().optional(),turnId:i().optional(),name:MO,timestamp:i(),source:b(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:i().optional(),appId:i().nullable().optional(),args:oe(i(),se()).optional(),status:b(["started","completed","failed","pending"]).optional(),output:i().optional(),error:i().optional(),relatedDeploymentId:i().optional(),data:se().optional()}),jO=c({id:i().trim().min(1).max(80),label:i().trim().min(1).max(160),description:i().trim().max(500).nullable().optional().default(null)}),OO=c({id:i().trim().min(1),sessionId:i().trim().min(1),turnId:i().trim().min(1),toolCallId:i().trim().min(1),question:i().trim().min(1).max(2e3),reason:i().trim().max(1e3).nullable().optional().default(null),options:p(jO).max(5).default([]),allowFreeform:A().default(!0),status:b(["pending","answered","dismissed"]),answer:c({optionId:i().trim().min(1).nullable(),text:i().max(4e3)}).nullable(),createdAt:i(),answeredAt:i().nullable()}),$O=c({questionId:i().trim().min(1),action:b(["answer","dismiss"]),optionId:i().trim().min(1).nullable().optional().default(null),text:i().trim().max(4e3).optional().default("")});c({kind:b(["session","project","draft"]),id:i().trim().min(1).max(300)});b(["unknown","idle","running","success","failed"]);b(["none","idle","running","success","failed","unknown"]);function NO(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ln={},cd={},bi={},sy;function fc(){if(sy)return bi;sy=1;function e(s){return typeof s>"u"||s===null}function t(s){return typeof s=="object"&&s!==null}function n(s){return Array.isArray(s)?s:e(s)?[]:[s]}function a(s,l){if(l){const m=Object.keys(l);for(let d=0,h=m.length;d<h;d+=1){const g=m[d];s[g]=l[g]}}return s}function o(s,l){let m="";for(let d=0;d<l;d+=1)m+=s;return m}function r(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return bi.isNothing=e,bi.isObject=t,bi.toArray=n,bi.repeat=o,bi.isNegativeZero=r,bi.extend=a,bi}var Op,ly;function hc(){if(ly)return Op;ly=1;function e(n,a){let o="";const r=n.reason||"(unknown reason)";return n.mark?(n.mark.name&&(o+='in "'+n.mark.name+'" '),o+="("+(n.mark.line+1)+":"+(n.mark.column+1)+")",!a&&n.mark.snippet&&(o+=`
|
|
67
|
-
|
|
68
|
-
`+n.mark.snippet),r+" "+o):r}function t(n,a){Error.call(this),this.name="YAMLException",this.reason=n,this.mark=a,this.message=e(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t.prototype.toString=function(a){return this.name+": "+e(this,a)},Op=t,Op}var $p,cy;function DO(){if(cy)return $p;cy=1;const e=fc();function t(o,r,s,l,m){let d="",h="";const g=Math.floor(m/2)-1;return l-r>g&&(d=" ... ",r=l-g+d.length),s-l>g&&(h=" ...",s=l+g-h.length),{str:d+o.slice(r,s).replace(/\t/g,"→")+h,pos:l-r+d.length}}function n(o,r){return e.repeat(" ",r-o.length)+o}function a(o,r){if(r=Object.create(r||null),!o.buffer)return null;r.maxLength||(r.maxLength=79),typeof r.indent!="number"&&(r.indent=1),typeof r.linesBefore!="number"&&(r.linesBefore=3),typeof r.linesAfter!="number"&&(r.linesAfter=2);const s=/\r?\n|\r|\0/g,l=[0],m=[];let d,h=-1;for(;d=s.exec(o.buffer);)m.push(d.index),l.push(d.index+d[0].length),o.position<=d.index&&h<0&&(h=l.length-2);h<0&&(h=l.length-1);let g="";const y=Math.min(o.line+r.linesAfter,m.length).toString().length,w=r.maxLength-(r.indent+y+3);for(let P=1;P<=r.linesBefore&&!(h-P<0);P++){const M=t(o.buffer,l[h-P],m[h-P],o.position-(l[h]-l[h-P]),w);g=e.repeat(" ",r.indent)+n((o.line-P+1).toString(),y)+" | "+M.str+`
|
|
69
|
-
`+g}const _=t(o.buffer,l[h],m[h],o.position,w);g+=e.repeat(" ",r.indent)+n((o.line+1).toString(),y)+" | "+_.str+`
|
|
70
|
-
`,g+=e.repeat("-",r.indent+y+3+_.pos)+`^
|
|
71
|
-
`;for(let P=1;P<=r.linesAfter&&!(h+P>=m.length);P++){const M=t(o.buffer,l[h+P],m[h+P],o.position-(l[h]-l[h+P]),w);g+=e.repeat(" ",r.indent)+n((o.line+P+1).toString(),y)+" | "+M.str+`
|
|
72
|
-
`}return g.replace(/\n$/,"")}return $p=a,$p}var Np,dy;function Gn(){if(dy)return Np;dy=1;const e=hc(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],n=["scalar","sequence","mapping"];function a(r){const s={};return r!==null&&Object.keys(r).forEach(function(l){r[l].forEach(function(m){s[String(m)]=l})}),s}function o(r,s){if(s=s||{},Object.keys(s).forEach(function(l){if(t.indexOf(l)===-1)throw new e('Unknown option "'+l+'" is met in definition of "'+r+'" YAML type.')}),this.options=s,this.tag=r,this.kind=s.kind||null,this.resolve=s.resolve||function(){return!0},this.construct=s.construct||function(l){return l},this.instanceOf=s.instanceOf||null,this.predicate=s.predicate||null,this.represent=s.represent||null,this.representName=s.representName||null,this.defaultStyle=s.defaultStyle||null,this.multi=s.multi||!1,this.styleAliases=a(s.styleAliases||null),n.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+r+'" YAML type.')}return Np=o,Np}var Dp,uy;function Ek(){if(uy)return Dp;uy=1;const e=hc(),t=Gn();function n(r,s){const l=[];return r[s].forEach(function(m){let d=l.length;l.forEach(function(h,g){h.tag===m.tag&&h.kind===m.kind&&h.multi===m.multi&&(d=g)}),l[d]=m}),l}function a(){const r={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(l){l.multi?(r.multi[l.kind].push(l),r.multi.fallback.push(l)):r[l.kind][l.tag]=r.fallback[l.tag]=l}for(let l=0,m=arguments.length;l<m;l+=1)arguments[l].forEach(s);return r}function o(r){return this.extend(r)}return o.prototype.extend=function(s){let l=[],m=[];if(s instanceof t)m.push(s);else if(Array.isArray(s))m=m.concat(s);else if(s&&(Array.isArray(s.implicit)||Array.isArray(s.explicit)))s.implicit&&(l=l.concat(s.implicit)),s.explicit&&(m=m.concat(s.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");l.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(h.loadKind&&h.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(h.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),m.forEach(function(h){if(!(h instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const d=Object.create(o.prototype);return d.implicit=(this.implicit||[]).concat(l),d.explicit=(this.explicit||[]).concat(m),d.compiledImplicit=n(d,"implicit"),d.compiledExplicit=n(d,"explicit"),d.compiledTypeMap=a(d.compiledImplicit,d.compiledExplicit),d},Dp=o,Dp}var Lp,my;function Mk(){if(my)return Lp;my=1;const e=Gn();return Lp=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),Lp}var Hp,py;function jk(){if(py)return Hp;py=1;const e=Gn();return Hp=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Hp}var Up,fy;function Ok(){if(fy)return Up;fy=1;const e=Gn();return Up=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),Up}var qp,hy;function $k(){if(hy)return qp;hy=1;const e=Ek();return qp=new e({explicit:[Mk(),jk(),Ok()]}),qp}var zp,gy;function Nk(){if(gy)return zp;gy=1;const e=Gn();function t(o){if(o===null)return!0;const r=o.length;return r===1&&o==="~"||r===4&&(o==="null"||o==="Null"||o==="NULL")}function n(){return null}function a(o){return o===null}return zp=new e("tag:yaml.org,2002:null",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"}),zp}var Bp,vy;function Dk(){if(vy)return Bp;vy=1;const e=Gn();function t(o){if(o===null)return!1;const r=o.length;return r===4&&(o==="true"||o==="True"||o==="TRUE")||r===5&&(o==="false"||o==="False"||o==="FALSE")}function n(o){return o==="true"||o==="True"||o==="TRUE"}function a(o){return Object.prototype.toString.call(o)==="[object Boolean]"}return Bp=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:n,predicate:a,represent:{lowercase:function(o){return o?"true":"false"},uppercase:function(o){return o?"TRUE":"FALSE"},camelcase:function(o){return o?"True":"False"}},defaultStyle:"lowercase"}),Bp}var Fp,by;function Lk(){if(by)return Fp;by=1;const e=fc(),t=Gn();function n(d){return d>=48&&d<=57||d>=65&&d<=70||d>=97&&d<=102}function a(d){return d>=48&&d<=55}function o(d){return d>=48&&d<=57}function r(d){if(d===null)return!1;const h=d.length;let g=0,y=!1;if(!h)return!1;let w=d[g];if((w==="-"||w==="+")&&(w=d[++g]),w==="0"){if(g+1===h)return!0;if(w=d[++g],w==="b"){for(g++;g<h;g++){if(w=d[g],w!=="0"&&w!=="1")return!1;y=!0}return y&&isFinite(s(d))}if(w==="x"){for(g++;g<h;g++){if(!n(d.charCodeAt(g)))return!1;y=!0}return y&&isFinite(s(d))}if(w==="o"){for(g++;g<h;g++){if(!a(d.charCodeAt(g)))return!1;y=!0}return y&&isFinite(s(d))}}for(;g<h;g++){if(!o(d.charCodeAt(g)))return!1;y=!0}return y?isFinite(s(d)):!1}function s(d){let h=d,g=1,y=h[0];if((y==="-"||y==="+")&&(y==="-"&&(g=-1),h=h.slice(1),y=h[0]),h==="0")return 0;if(y==="0"){if(h[1]==="b")return g*parseInt(h.slice(2),2);if(h[1]==="x")return g*parseInt(h.slice(2),16);if(h[1]==="o")return g*parseInt(h.slice(2),8)}return g*parseInt(h,10)}function l(d){return s(d)}function m(d){return Object.prototype.toString.call(d)==="[object Number]"&&d%1===0&&!e.isNegativeZero(d)}return Fp=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:r,construct:l,predicate:m,represent:{binary:function(d){return d>=0?"0b"+d.toString(2):"-0b"+d.toString(2).slice(1)},octal:function(d){return d>=0?"0o"+d.toString(8):"-0o"+d.toString(8).slice(1)},decimal:function(d){return d.toString(10)},hexadecimal:function(d){return d>=0?"0x"+d.toString(16).toUpperCase():"-0x"+d.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),Fp}var Vp,yy;function Hk(){if(yy)return Vp;yy=1;const e=fc(),t=Gn(),n=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),a=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function o(d){return d===null||!n.test(d)?!1:isFinite(parseFloat(d,10))?!0:a.test(d)}function r(d){let h=d.toLowerCase();const g=h[0]==="-"?-1:1;return"+-".indexOf(h[0])>=0&&(h=h.slice(1)),h===".inf"?g===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:h===".nan"?NaN:g*parseFloat(h,10)}const s=/^[-+]?[0-9]+e/;function l(d,h){if(isNaN(d))switch(h){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===d)switch(h){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===d)switch(h){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(d))return"-0.0";const g=d.toString(10);return s.test(g)?g.replace("e",".e"):g}function m(d){return Object.prototype.toString.call(d)==="[object Number]"&&(d%1!==0||e.isNegativeZero(d))}return Vp=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:o,construct:r,predicate:m,represent:l,defaultStyle:"lowercase"}),Vp}var Kp,Sy;function Uk(){return Sy||(Sy=1,Kp=$k().extend({implicit:[Nk(),Dk(),Lk(),Hk()]})),Kp}var Wp,xy;function qk(){return xy||(xy=1,Wp=Uk()),Wp}var Gp,ky;function zk(){if(ky)return Gp;ky=1;const e=Gn(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),n=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function a(s){return s===null?!1:t.exec(s)!==null||n.exec(s)!==null}function o(s){let l=0,m=null,d=t.exec(s);if(d===null&&(d=n.exec(s)),d===null)throw new Error("Date resolve error");const h=+d[1],g=+d[2]-1,y=+d[3];if(!d[4])return new Date(Date.UTC(h,g,y));const w=+d[4],_=+d[5],P=+d[6];if(d[7]){for(l=d[7].slice(0,3);l.length<3;)l+="0";l=+l}if(d[9]){const C=+d[10],$=+(d[11]||0);m=(C*60+$)*6e4,d[9]==="-"&&(m=-m)}const M=new Date(Date.UTC(h,g,y,w,_,P,l));return m&&M.setTime(M.getTime()-m),M}function r(s){return s.toISOString()}return Gp=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:o,instanceOf:Date,represent:r}),Gp}var Jp,wy;function Bk(){if(wy)return Jp;wy=1;const e=Gn();function t(n){return n==="<<"||n===null}return Jp=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),Jp}var Zp,Iy;function Fk(){if(Iy)return Zp;Iy=1;const e=Gn(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
73
|
-
\r`;function n(s){if(s===null)return!1;let l=0;const m=s.length,d=t;for(let h=0;h<m;h++){const g=d.indexOf(s.charAt(h));if(!(g>64)){if(g<0)return!1;l+=6}}return l%8===0}function a(s){const l=s.replace(/[\r\n=]/g,""),m=l.length,d=t;let h=0;const g=[];for(let w=0;w<m;w++)w%4===0&&w&&(g.push(h>>16&255),g.push(h>>8&255),g.push(h&255)),h=h<<6|d.indexOf(l.charAt(w));const y=m%4*6;return y===0?(g.push(h>>16&255),g.push(h>>8&255),g.push(h&255)):y===18?(g.push(h>>10&255),g.push(h>>2&255)):y===12&&g.push(h>>4&255),new Uint8Array(g)}function o(s){let l="",m=0;const d=s.length,h=t;for(let y=0;y<d;y++)y%3===0&&y&&(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]),m=(m<<8)+s[y];const g=d%3;return g===0?(l+=h[m>>18&63],l+=h[m>>12&63],l+=h[m>>6&63],l+=h[m&63]):g===2?(l+=h[m>>10&63],l+=h[m>>4&63],l+=h[m<<2&63],l+=h[64]):g===1&&(l+=h[m>>2&63],l+=h[m<<4&63],l+=h[64],l+=h[64]),l}function r(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return Zp=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:r,represent:o}),Zp}var Yp,_y;function Vk(){if(_y)return Yp;_y=1;const e=Gn(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(r){if(r===null)return!0;const s=[],l=r;for(let m=0,d=l.length;m<d;m+=1){const h=l[m];let g=!1;if(n.call(h)!=="[object Object]")return!1;let y;for(y in h)if(t.call(h,y))if(!g)g=!0;else return!1;if(!g)return!1;if(s.indexOf(y)===-1)s.push(y);else return!1}return!0}function o(r){return r!==null?r:[]}return Yp=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:o}),Yp}var Qp,Cy;function Kk(){if(Cy)return Qp;Cy=1;const e=Gn(),t=Object.prototype.toString;function n(o){if(o===null)return!0;const r=o,s=new Array(r.length);for(let l=0,m=r.length;l<m;l+=1){const d=r[l];if(t.call(d)!=="[object Object]")return!1;const h=Object.keys(d);if(h.length!==1)return!1;s[l]=[h[0],d[h[0]]]}return!0}function a(o){if(o===null)return[];const r=o,s=new Array(r.length);for(let l=0,m=r.length;l<m;l+=1){const d=r[l],h=Object.keys(d);s[l]=[h[0],d[h[0]]]}return s}return Qp=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),Qp}var Xp,Ry;function Wk(){if(Ry)return Xp;Ry=1;const e=Gn(),t=Object.prototype.hasOwnProperty;function n(o){if(o===null)return!0;const r=o;for(const s in r)if(t.call(r,s)&&r[s]!==null)return!1;return!0}function a(o){return o!==null?o:{}}return Xp=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Xp}var ef,Py;function fg(){return Py||(Py=1,ef=qk().extend({implicit:[zk(),Bk()],explicit:[Fk(),Vk(),Kk(),Wk()]})),ef}var Ay;function LO(){if(Ay)return cd;Ay=1;const e=fc(),t=hc(),n=DO(),a=fg(),o=Object.prototype.hasOwnProperty,r=1,s=2,l=3,m=4,d=1,h=2,g=3,y=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,w=/[\x85\u2028\u2029]/,_=/[,\[\]{}]/,P=/^(?:!|!!|![0-9A-Za-z-]+!)$/,M=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function C(f){return Object.prototype.toString.call(f)}function $(f){return f===10||f===13}function O(f){return f===9||f===32}function j(f){return f===9||f===32||f===10||f===13}function x(f){return f===44||f===91||f===93||f===123||f===125}function R(f){if(f>=48&&f<=57)return f-48;const U=f|32;return U>=97&&U<=102?U-97+10:-1}function E(f){return f===120?2:f===117?4:f===85?8:0}function H(f){return f>=48&&f<=57?f-48:-1}function B(f){switch(f){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
|
|
74
|
-
`;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"
";case 95:return" ";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function D(f){return f<=65535?String.fromCharCode(f):String.fromCharCode((f-65536>>10)+55296,(f-65536&1023)+56320)}function J(f,U,Y){U==="__proto__"?Object.defineProperty(f,U,{configurable:!0,enumerable:!0,writable:!0,value:Y}):f[U]=Y}const le=new Array(256),ue=new Array(256);for(let f=0;f<256;f++)le[f]=B(f)?1:0,ue[f]=B(f);function je(f,U){this.input=f,this.filename=U.filename||null,this.schema=U.schema||a,this.onWarning=U.onWarning||null,this.legacy=U.legacy||!1,this.json=U.json||!1,this.listener=U.listener||null,this.maxDepth=typeof U.maxDepth=="number"?U.maxDepth:100,this.maxTotalMergeKeys=typeof U.maxTotalMergeKeys=="number"?U.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=f.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function ke(f,U){const Y={name:f.filename,buffer:f.input.slice(0,-1),position:f.position,line:f.line,column:f.position-f.lineStart};return Y.snippet=n(Y),new t(U,Y)}function te(f,U){throw ke(f,U)}function Me(f,U){f.onWarning&&f.onWarning.call(null,ke(f,U))}function ye(f,U,Y){const he=f.anchorMapTransactions;if(he.length!==0){const re=he[he.length-1];o.call(re,U)||(re[U]={existed:o.call(f.anchorMap,U),value:f.anchorMap[U]})}f.anchorMap[U]=Y}function ne(f){f.anchorMapTransactions.push(Object.create(null))}function be(f){const U=f.anchorMapTransactions.pop(),Y=f.anchorMapTransactions;if(Y.length===0)return;const he=Y[Y.length-1],re=Object.keys(U);for(let W=0,I=re.length;W<I;W+=1){const K=re[W];o.call(he,K)||(he[K]=U[K])}}function ae(f){const U=f.anchorMapTransactions.pop(),Y=Object.keys(U);for(let he=Y.length-1;he>=0;he-=1){const re=U[Y[he]];re.existed?f.anchorMap[Y[he]]=re.value:delete f.anchorMap[Y[he]]}}function de(f){return{position:f.position,line:f.line,lineStart:f.lineStart,lineIndent:f.lineIndent,firstTabInLine:f.firstTabInLine,tag:f.tag,anchor:f.anchor,kind:f.kind,result:f.result}}function xe(f,U){f.position=U.position,f.line=U.line,f.lineStart=U.lineStart,f.lineIndent=U.lineIndent,f.firstTabInLine=U.firstTabInLine,f.tag=U.tag,f.anchor=U.anchor,f.kind=U.kind,f.result=U.result}const De={YAML:function(U,Y,he){U.version!==null&&te(U,"duplication of %YAML directive"),he.length!==1&&te(U,"YAML directive accepts exactly one argument");const re=/^([0-9]+)\.([0-9]+)$/.exec(he[0]);re===null&&te(U,"ill-formed argument of the YAML directive");const W=parseInt(re[1],10),I=parseInt(re[2],10);W!==1&&te(U,"unacceptable YAML version of the document"),U.version=he[0],U.checkLineBreaks=I<2,I!==1&&I!==2&&Me(U,"unsupported YAML version of the document")},TAG:function(U,Y,he){let re;he.length!==2&&te(U,"TAG directive accepts exactly two arguments");const W=he[0];re=he[1],P.test(W)||te(U,"ill-formed tag handle (first argument) of the TAG directive"),o.call(U.tagMap,W)&&te(U,'there is a previously declared suffix for "'+W+'" tag handle'),M.test(re)||te(U,"ill-formed tag prefix (second argument) of the TAG directive");try{re=decodeURIComponent(re)}catch{te(U,"tag prefix is malformed: "+re)}U.tagMap[W]=re}};function we(f,U,Y,he){if(U<Y){const re=f.input.slice(U,Y);if(he)for(let W=0,I=re.length;W<I;W+=1){const K=re.charCodeAt(W);K===9||K>=32&&K<=1114111||te(f,"expected valid JSON character")}else y.test(re)&&te(f,"the stream contains non-printable characters");f.result+=re}}function ie(f,U,Y,he){e.isObject(Y)||te(f,"cannot merge mappings; the provided source object is unacceptable");const re=Object.keys(Y);for(let W=0,I=re.length;W<I;W+=1){const K=re[W];f.maxTotalMergeKeys!==-1&&++f.totalMergeKeys>f.maxTotalMergeKeys&&te(f,"merge keys exceeded maxTotalMergeKeys ("+f.maxTotalMergeKeys+")"),o.call(U,K)||(J(U,K,Y[K]),he[K]=!0)}}function Se(f,U,Y,he,re,W,I,K,ee){if(Array.isArray(re)){re=Array.prototype.slice.call(re);for(let Z=0,ce=re.length;Z<ce;Z+=1)Array.isArray(re[Z])&&te(f,"nested arrays are not supported inside keys"),typeof re=="object"&&C(re[Z])==="[object Object]"&&(re[Z]="[object Object]")}if(typeof re=="object"&&C(re)==="[object Object]"&&(re="[object Object]"),re=String(re),U===null&&(U={}),he==="tag:yaml.org,2002:merge")if(Array.isArray(W))for(let Z=0,ce=W.length;Z<ce;Z+=1)ie(f,U,W[Z],Y);else ie(f,U,W,Y);else!f.json&&!o.call(Y,re)&&o.call(U,re)&&(f.line=I||f.line,f.lineStart=K||f.lineStart,f.position=ee||f.position,te(f,"duplicated mapping key")),J(U,re,W),delete Y[re];return U}function Ue(f){const U=f.input.charCodeAt(f.position);U===10?f.position++:U===13?(f.position++,f.input.charCodeAt(f.position)===10&&f.position++):te(f,"a line break is expected"),f.line+=1,f.lineStart=f.position,f.firstTabInLine=-1}function Je(f,U,Y){let he=0,re=f.input.charCodeAt(f.position);for(;re!==0;){for(;O(re);)re===9&&f.firstTabInLine===-1&&(f.firstTabInLine=f.position),re=f.input.charCodeAt(++f.position);if(U&&re===35)do re=f.input.charCodeAt(++f.position);while(re!==10&&re!==13&&re!==0);if($(re))for(Ue(f),re=f.input.charCodeAt(f.position),he++,f.lineIndent=0;re===32;)f.lineIndent++,re=f.input.charCodeAt(++f.position);else break}return Y!==-1&&he!==0&&f.lineIndent<Y&&Me(f,"deficient indentation"),he}function Ke(f){let U=f.position,Y=f.input.charCodeAt(U);return!!((Y===45||Y===46)&&Y===f.input.charCodeAt(U+1)&&Y===f.input.charCodeAt(U+2)&&(U+=3,Y=f.input.charCodeAt(U),Y===0||j(Y)))}function tt(f,U){U===1?f.result+=" ":U>1&&(f.result+=e.repeat(`
|
|
75
|
-
`,U-1))}function ze(f,U,Y){let he,re,W,I,K,ee;const Z=f.kind,ce=f.result;let pe=f.input.charCodeAt(f.position);if(j(pe)||x(pe)||pe===35||pe===38||pe===42||pe===33||pe===124||pe===62||pe===39||pe===34||pe===37||pe===64||pe===96)return!1;if(pe===63||pe===45){const fe=f.input.charCodeAt(f.position+1);if(j(fe)||Y&&x(fe))return!1}for(f.kind="scalar",f.result="",he=re=f.position,W=!1;pe!==0;){if(pe===58){const fe=f.input.charCodeAt(f.position+1);if(j(fe)||Y&&x(fe))break}else if(pe===35){const fe=f.input.charCodeAt(f.position-1);if(j(fe))break}else{if(f.position===f.lineStart&&Ke(f)||Y&&x(pe))break;if($(pe))if(I=f.line,K=f.lineStart,ee=f.lineIndent,Je(f,!1,-1),f.lineIndent>=U){W=!0,pe=f.input.charCodeAt(f.position);continue}else{f.position=re,f.line=I,f.lineStart=K,f.lineIndent=ee;break}}W&&(we(f,he,re,!1),tt(f,f.line-I),he=re=f.position,W=!1),O(pe)||(re=f.position+1),pe=f.input.charCodeAt(++f.position)}return we(f,he,re,!1),f.result?!0:(f.kind=Z,f.result=ce,!1)}function Ge(f,U){let Y,he,re=f.input.charCodeAt(f.position);if(re!==39)return!1;for(f.kind="scalar",f.result="",f.position++,Y=he=f.position;(re=f.input.charCodeAt(f.position))!==0;)if(re===39)if(we(f,Y,f.position,!0),re=f.input.charCodeAt(++f.position),re===39)Y=f.position,f.position++,he=f.position;else return!0;else $(re)?(we(f,Y,he,!0),tt(f,Je(f,!1,U)),Y=he=f.position):f.position===f.lineStart&&Ke(f)?te(f,"unexpected end of the document within a single quoted scalar"):(f.position++,O(re)||(he=f.position));te(f,"unexpected end of the stream within a single quoted scalar")}function qe(f,U){let Y,he,re,W=f.input.charCodeAt(f.position);if(W!==34)return!1;for(f.kind="scalar",f.result="",f.position++,Y=he=f.position;(W=f.input.charCodeAt(f.position))!==0;){if(W===34)return we(f,Y,f.position,!0),f.position++,!0;if(W===92){if(we(f,Y,f.position,!0),W=f.input.charCodeAt(++f.position),$(W))Je(f,!1,U);else if(W<256&&le[W])f.result+=ue[W],f.position++;else if((re=E(W))>0){let I=re,K=0;for(;I>0;I--)W=f.input.charCodeAt(++f.position),(re=R(W))>=0?K=(K<<4)+re:te(f,"expected hexadecimal character");f.result+=D(K),f.position++}else te(f,"unknown escape sequence");Y=he=f.position}else $(W)?(we(f,Y,he,!0),tt(f,Je(f,!1,U)),Y=he=f.position):f.position===f.lineStart&&Ke(f)?te(f,"unexpected end of the document within a double quoted scalar"):(f.position++,O(W)||(he=f.position))}te(f,"unexpected end of the stream within a double quoted scalar")}function L(f,U){let Y=!0,he,re,W;const I=f.tag;let K;const ee=f.anchor;let Z,ce,pe,fe;const Ae=Object.create(null);let _e,Ne,Pe,Xe=f.input.charCodeAt(f.position);if(Xe===91)Z=93,fe=!1,K=[];else if(Xe===123)Z=125,fe=!0,K={};else return!1;for(f.anchor!==null&&ye(f,f.anchor,K),Xe=f.input.charCodeAt(++f.position);Xe!==0;){if(Je(f,!0,U),Xe=f.input.charCodeAt(f.position),Xe===Z)return f.position++,f.tag=I,f.anchor=ee,f.kind=fe?"mapping":"sequence",f.result=K,!0;if(Y?Xe===44&&te(f,"expected the node content, but found ','"):te(f,"missed comma between flow collection entries"),Ne=_e=Pe=null,ce=pe=!1,Xe===63){const st=f.input.charCodeAt(f.position+1);j(st)&&(ce=pe=!0,f.position++,Je(f,!0,U))}he=f.line,re=f.lineStart,W=f.position,at(f,U,r,!1,!0),Ne=f.tag,_e=f.result,Je(f,!0,U),Xe=f.input.charCodeAt(f.position),(pe||f.line===he)&&Xe===58&&(ce=!0,Xe=f.input.charCodeAt(++f.position),Je(f,!0,U),at(f,U,r,!1,!0),Pe=f.result),fe?Se(f,K,Ae,Ne,_e,Pe,he,re,W):ce?K.push(Se(f,null,Ae,Ne,_e,Pe,he,re,W)):K.push(_e),Je(f,!0,U),Xe=f.input.charCodeAt(f.position),Xe===44?(Y=!0,Xe=f.input.charCodeAt(++f.position)):Y=!1}te(f,"unexpected end of the stream within a flow collection")}function N(f,U){let Y,he=d,re=!1,W=!1,I=U,K=0,ee=!1,Z,ce=f.input.charCodeAt(f.position);if(ce===124)Y=!1;else if(ce===62)Y=!0;else return!1;for(f.kind="scalar",f.result="";ce!==0;)if(ce=f.input.charCodeAt(++f.position),ce===43||ce===45)d===he?he=ce===43?g:h:te(f,"repeat of a chomping mode identifier");else if((Z=H(ce))>=0)Z===0?te(f,"bad explicit indentation width of a block scalar; it cannot be less than one"):W?te(f,"repeat of an indentation width identifier"):(I=U+Z-1,W=!0);else break;if(O(ce)){do ce=f.input.charCodeAt(++f.position);while(O(ce));if(ce===35)do ce=f.input.charCodeAt(++f.position);while(!$(ce)&&ce!==0)}for(;ce!==0;){for(Ue(f),f.lineIndent=0,ce=f.input.charCodeAt(f.position);(!W||f.lineIndent<I)&&ce===32;)f.lineIndent++,ce=f.input.charCodeAt(++f.position);if(!W&&f.lineIndent>I&&(I=f.lineIndent),$(ce)){K++;continue}if(!W&&I===0&&te(f,"missing indentation for block scalar"),f.lineIndent<I){he===g?f.result+=e.repeat(`
|
|
76
|
-
`,re?1+K:K):he===d&&re&&(f.result+=`
|
|
77
|
-
`);break}Y?O(ce)?(ee=!0,f.result+=e.repeat(`
|
|
78
|
-
`,re?1+K:K)):ee?(ee=!1,f.result+=e.repeat(`
|
|
79
|
-
`,K+1)):K===0?re&&(f.result+=" "):f.result+=e.repeat(`
|
|
80
|
-
`,K):f.result+=e.repeat(`
|
|
81
|
-
`,re?1+K:K),re=!0,W=!0,K=0;const pe=f.position;for(;!$(ce)&&ce!==0;)ce=f.input.charCodeAt(++f.position);we(f,pe,f.position,!1)}return!0}function q(f,U){const Y=f.tag,he=f.anchor,re=[];let W=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&ye(f,f.anchor,re);let I=f.input.charCodeAt(f.position);for(;I!==0&&(f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,te(f,"tab characters must not be used in indentation")),I===45);){const K=f.input.charCodeAt(f.position+1);if(!j(K))break;if(W=!0,f.position++,Je(f,!0,-1)&&f.lineIndent<=U){re.push(null),I=f.input.charCodeAt(f.position);continue}const ee=f.line;if(at(f,U,l,!1,!0),re.push(f.result),Je(f,!0,-1),I=f.input.charCodeAt(f.position),(f.line===ee||f.lineIndent>U)&&I!==0)te(f,"bad indentation of a sequence entry");else if(f.lineIndent<U)break}return W?(f.tag=Y,f.anchor=he,f.kind="sequence",f.result=re,!0):!1}function X(f,U,Y){let he,re,W,I;const K=f.tag,ee=f.anchor,Z={},ce=Object.create(null);let pe=null,fe=null,Ae=null,_e=!1,Ne=!1;if(f.firstTabInLine!==-1)return!1;f.anchor!==null&&ye(f,f.anchor,Z);let Pe=f.input.charCodeAt(f.position);for(;Pe!==0;){!_e&&f.firstTabInLine!==-1&&(f.position=f.firstTabInLine,te(f,"tab characters must not be used in indentation"));const Xe=f.input.charCodeAt(f.position+1),st=f.line;if((Pe===63||Pe===58)&&j(Xe))Pe===63?(_e&&(Se(f,Z,ce,pe,fe,null,re,W,I),pe=fe=Ae=null),Ne=!0,_e=!0,he=!0):_e?(_e=!1,he=!0):te(f,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),f.position+=1,Pe=Xe;else{if(re=f.line,W=f.lineStart,I=f.position,!at(f,Y,s,!1,!0))break;if(f.line===st){for(Pe=f.input.charCodeAt(f.position);O(Pe);)Pe=f.input.charCodeAt(++f.position);if(Pe===58)Pe=f.input.charCodeAt(++f.position),j(Pe)||te(f,"a whitespace character is expected after the key-value separator within a block mapping"),_e&&(Se(f,Z,ce,pe,fe,null,re,W,I),pe=fe=Ae=null),Ne=!0,_e=!1,he=!1,pe=f.tag,fe=f.result;else if(Ne)te(f,"can not read an implicit mapping pair; a colon is missed");else return f.tag=K,f.anchor=ee,!0}else if(Ne)te(f,"can not read a block mapping entry; a multiline key may not be an implicit key");else return f.tag=K,f.anchor=ee,!0}if((f.line===st||f.lineIndent>U)&&(_e&&(re=f.line,W=f.lineStart,I=f.position),at(f,U,m,!0,he)&&(_e?fe=f.result:Ae=f.result),_e||(Se(f,Z,ce,pe,fe,Ae,re,W,I),pe=fe=Ae=null),Je(f,!0,-1),Pe=f.input.charCodeAt(f.position)),(f.line===st||f.lineIndent>U)&&Pe!==0)te(f,"bad indentation of a mapping entry");else if(f.lineIndent<U)break}return _e&&Se(f,Z,ce,pe,fe,null,re,W,I),Ne&&(f.tag=K,f.anchor=ee,f.kind="mapping",f.result=Z),Ne}function me(f){let U=!1,Y=!1,he,re,W=f.input.charCodeAt(f.position);if(W!==33)return!1;f.tag!==null&&te(f,"duplication of a tag property"),W=f.input.charCodeAt(++f.position),W===60?(U=!0,W=f.input.charCodeAt(++f.position)):W===33?(Y=!0,he="!!",W=f.input.charCodeAt(++f.position)):he="!";let I=f.position;if(U){do W=f.input.charCodeAt(++f.position);while(W!==0&&W!==62);f.position<f.length?(re=f.input.slice(I,f.position),W=f.input.charCodeAt(++f.position)):te(f,"unexpected end of the stream within a verbatim tag")}else{for(;W!==0&&!j(W);)W===33&&(Y?te(f,"tag suffix cannot contain exclamation marks"):(he=f.input.slice(I-1,f.position+1),P.test(he)||te(f,"named tag handle cannot contain such characters"),Y=!0,I=f.position+1)),W=f.input.charCodeAt(++f.position);re=f.input.slice(I,f.position),_.test(re)&&te(f,"tag suffix cannot contain flow indicator characters")}re&&!M.test(re)&&te(f,"tag name cannot contain such characters: "+re);try{re=decodeURIComponent(re)}catch{te(f,"tag name is malformed: "+re)}return U?f.tag=re:o.call(f.tagMap,he)?f.tag=f.tagMap[he]+re:he==="!"?f.tag="!"+re:he==="!!"?f.tag="tag:yaml.org,2002:"+re:te(f,'undeclared tag handle "'+he+'"'),!0}function $e(f){let U=f.input.charCodeAt(f.position);if(U!==38)return!1;f.anchor!==null&&te(f,"duplication of an anchor property"),U=f.input.charCodeAt(++f.position);const Y=f.position;for(;U!==0&&!j(U)&&!x(U);)U=f.input.charCodeAt(++f.position);return f.position===Y&&te(f,"name of an anchor node must contain at least one character"),f.anchor=f.input.slice(Y,f.position),!0}function Le(f){let U=f.input.charCodeAt(f.position);if(U!==42)return!1;U=f.input.charCodeAt(++f.position);const Y=f.position;for(;U!==0&&!j(U)&&!x(U);)U=f.input.charCodeAt(++f.position);f.position===Y&&te(f,"name of an alias node must contain at least one character");const he=f.input.slice(Y,f.position);return o.call(f.anchorMap,he)||te(f,'unidentified alias "'+he+'"'),f.result=f.anchorMap[he],Je(f,!0,-1),!0}function nt(f,U,Y,he){const re=de(f);return ne(f),xe(f,U),f.tag=null,f.anchor=null,f.kind=null,f.result=null,X(f,Y,he)&&f.kind==="mapping"?(be(f),!0):(ae(f),xe(f,re),!1)}function at(f,U,Y,he,re){let W,I,K=1,ee=!1,Z=!1,ce=null,pe,fe,Ae;f.depth>=f.maxDepth&&te(f,"nesting exceeded maxDepth ("+f.maxDepth+")"),f.depth+=1,f.listener!==null&&f.listener("open",f),f.tag=null,f.anchor=null,f.kind=null,f.result=null;const _e=W=I=m===Y||l===Y;if(he&&Je(f,!0,-1)&&(ee=!0,f.lineIndent>U?K=1:f.lineIndent===U?K=0:f.lineIndent<U&&(K=-1)),K===1)for(;;){const Ne=f.input.charCodeAt(f.position),Pe=de(f);if(ee&&(Ne===33&&f.tag!==null||Ne===38&&f.anchor!==null)||!me(f)&&!$e(f))break;ce===null&&(ce=Pe),Je(f,!0,-1)?(ee=!0,I=_e,f.lineIndent>U?K=1:f.lineIndent===U?K=0:f.lineIndent<U&&(K=-1)):I=!1}if(I&&(I=ee||re),K===1||m===Y)if(r===Y||s===Y?fe=U:fe=U+1,Ae=f.position-f.lineStart,K===1)if(I&&(q(f,Ae)||X(f,Ae,fe))||L(f,fe))Z=!0;else{const Ne=f.input.charCodeAt(f.position);ce!==null&&_e&&!I&&Ne!==124&&Ne!==62&&nt(f,ce,ce.position-ce.lineStart,fe)||W&&N(f,fe)||Ge(f,fe)||qe(f,fe)?Z=!0:Le(f)?(Z=!0,(f.tag!==null||f.anchor!==null)&&te(f,"alias node should not have any properties")):ze(f,fe,r===Y)&&(Z=!0,f.tag===null&&(f.tag="?")),f.anchor!==null&&ye(f,f.anchor,f.result)}else K===0&&(Z=I&&q(f,Ae));if(f.tag===null)f.anchor!==null&&ye(f,f.anchor,f.result);else if(f.tag==="?"){f.result!==null&&f.kind!=="scalar"&&te(f,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+f.kind+'"');for(let Ne=0,Pe=f.implicitTypes.length;Ne<Pe;Ne+=1)if(pe=f.implicitTypes[Ne],pe.resolve(f.result)){f.result=pe.construct(f.result),f.tag=pe.tag,f.anchor!==null&&ye(f,f.anchor,f.result);break}}else if(f.tag!=="!"){if(o.call(f.typeMap[f.kind||"fallback"],f.tag))pe=f.typeMap[f.kind||"fallback"][f.tag];else{pe=null;const Ne=f.typeMap.multi[f.kind||"fallback"];for(let Pe=0,Xe=Ne.length;Pe<Xe;Pe+=1)if(f.tag.slice(0,Ne[Pe].tag.length)===Ne[Pe].tag){pe=Ne[Pe];break}}pe||te(f,"unknown tag !<"+f.tag+">"),f.result!==null&&pe.kind!==f.kind&&te(f,"unacceptable node kind for !<"+f.tag+'> tag; it should be "'+pe.kind+'", not "'+f.kind+'"'),pe.resolve(f.result,f.tag)?(f.result=pe.construct(f.result,f.tag),f.anchor!==null&&ye(f,f.anchor,f.result)):te(f,"cannot resolve a node with !<"+f.tag+"> explicit tag")}return f.listener!==null&&f.listener("close",f),f.depth-=1,f.tag!==null||f.anchor!==null||Z}function lt(f){const U=f.position;let Y=!1,he;for(f.version=null,f.checkLineBreaks=f.legacy,f.tagMap=Object.create(null),f.anchorMap=Object.create(null);(he=f.input.charCodeAt(f.position))!==0&&(Je(f,!0,-1),he=f.input.charCodeAt(f.position),!(f.lineIndent>0||he!==37));){Y=!0,he=f.input.charCodeAt(++f.position);let re=f.position;for(;he!==0&&!j(he);)he=f.input.charCodeAt(++f.position);const W=f.input.slice(re,f.position),I=[];for(W.length<1&&te(f,"directive name must not be less than one character in length");he!==0;){for(;O(he);)he=f.input.charCodeAt(++f.position);if(he===35){do he=f.input.charCodeAt(++f.position);while(he!==0&&!$(he));break}if($(he))break;for(re=f.position;he!==0&&!j(he);)he=f.input.charCodeAt(++f.position);I.push(f.input.slice(re,f.position))}he!==0&&Ue(f),o.call(De,W)?De[W](f,W,I):Me(f,'unknown document directive "'+W+'"')}if(Je(f,!0,-1),f.lineIndent===0&&f.input.charCodeAt(f.position)===45&&f.input.charCodeAt(f.position+1)===45&&f.input.charCodeAt(f.position+2)===45?(f.position+=3,Je(f,!0,-1)):Y&&te(f,"directives end mark is expected"),at(f,f.lineIndent-1,m,!1,!0),Je(f,!0,-1),f.checkLineBreaks&&w.test(f.input.slice(U,f.position))&&Me(f,"non-ASCII line breaks are interpreted as content"),f.documents.push(f.result),f.position===f.lineStart&&Ke(f)){f.input.charCodeAt(f.position)===46&&(f.position+=3,Je(f,!0,-1));return}f.position<f.length-1&&te(f,"end of the stream or a document separator is expected")}function pt(f,U){f=String(f),U=U||{},f.length!==0&&(f.charCodeAt(f.length-1)!==10&&f.charCodeAt(f.length-1)!==13&&(f+=`
|
|
82
|
-
`),f.charCodeAt(0)===65279&&(f=f.slice(1)));const Y=new je(f,U),he=f.indexOf("\0");for(he!==-1&&(Y.position=he,te(Y,"null byte is not allowed in input")),Y.input+="\0";Y.input.charCodeAt(Y.position)===32;)Y.lineIndent+=1,Y.position+=1;for(;Y.position<Y.length-1;)lt(Y);return Y.documents}function Oe(f,U,Y){U!==null&&typeof U=="object"&&typeof Y>"u"&&(Y=U,U=null);const he=pt(f,Y);if(typeof U!="function")return he;for(let re=0,W=he.length;re<W;re+=1)U(he[re])}function Ye(f,U){const Y=pt(f,U);if(Y.length!==0){if(Y.length===1)return Y[0];throw new t("expected a single document in the stream, but found more")}}return cd.loadAll=Oe,cd.load=Ye,cd}var tf={},Ty;function HO(){if(Ty)return tf;Ty=1;const e=fc(),t=hc(),n=fg(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,r=65279,s=9,l=10,m=13,d=32,h=33,g=34,y=35,w=37,_=38,P=39,M=42,C=44,$=45,O=58,j=61,x=62,R=63,E=64,H=91,B=93,D=96,J=123,le=124,ue=125,je={};je[0]="\\0",je[7]="\\a",je[8]="\\b",je[9]="\\t",je[10]="\\n",je[11]="\\v",je[12]="\\f",je[13]="\\r",je[27]="\\e",je[34]='\\"',je[92]="\\\\",je[133]="\\N",je[160]="\\_",je[8232]="\\L",je[8233]="\\P";const ke=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],te=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function Me(I,K){if(K===null)return{};const ee={},Z=Object.keys(K);for(let ce=0,pe=Z.length;ce<pe;ce+=1){let fe=Z[ce],Ae=String(K[fe]);fe.slice(0,2)==="!!"&&(fe="tag:yaml.org,2002:"+fe.slice(2));const _e=I.compiledTypeMap.fallback[fe];_e&&o.call(_e.styleAliases,Ae)&&(Ae=_e.styleAliases[Ae]),ee[fe]=Ae}return ee}function ye(I){let K,ee;const Z=I.toString(16).toUpperCase();if(I<=255)K="x",ee=2;else if(I<=65535)K="u",ee=4;else if(I<=4294967295)K="U",ee=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+K+e.repeat("0",ee-Z.length)+Z}const ne=1,be=2;function ae(I){this.schema=I.schema||n,this.indent=Math.max(1,I.indent||2),this.noArrayIndent=I.noArrayIndent||!1,this.skipInvalid=I.skipInvalid||!1,this.flowLevel=e.isNothing(I.flowLevel)?-1:I.flowLevel,this.styleMap=Me(this.schema,I.styles||null),this.sortKeys=I.sortKeys||!1,this.lineWidth=I.lineWidth||80,this.noRefs=I.noRefs||!1,this.noCompatMode=I.noCompatMode||!1,this.condenseFlow=I.condenseFlow||!1,this.quotingType=I.quotingType==='"'?be:ne,this.forceQuotes=I.forceQuotes||!1,this.replacer=typeof I.replacer=="function"?I.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function de(I,K){const ee=e.repeat(" ",K);let Z=0,ce="";const pe=I.length;for(;Z<pe;){let fe;const Ae=I.indexOf(`
|
|
83
|
-
`,Z);Ae===-1?(fe=I.slice(Z),Z=pe):(fe=I.slice(Z,Ae+1),Z=Ae+1),fe.length&&fe!==`
|
|
84
|
-
`&&(ce+=ee),ce+=fe}return ce}function xe(I,K){return`
|
|
85
|
-
`+e.repeat(" ",I.indent*K)}function De(I,K){for(let ee=0,Z=I.implicitTypes.length;ee<Z;ee+=1)if(I.implicitTypes[ee].resolve(K))return!0;return!1}function we(I){return I===d||I===s}function ie(I){return I>=32&&I<=126||I>=161&&I<=55295&&I!==8232&&I!==8233||I>=57344&&I<=65533&&I!==r||I>=65536&&I<=1114111}function Se(I){return ie(I)&&I!==r&&I!==m&&I!==l}function Ue(I,K,ee){const Z=Se(I),ce=Z&&!we(I);return(ee?Z:Z&&I!==C&&I!==H&&I!==B&&I!==J&&I!==ue)&&I!==y&&!(K===O&&!ce)||Se(K)&&!we(K)&&I===y||K===O&&ce}function Je(I){return ie(I)&&I!==r&&!we(I)&&I!==$&&I!==R&&I!==O&&I!==C&&I!==H&&I!==B&&I!==J&&I!==ue&&I!==y&&I!==_&&I!==M&&I!==h&&I!==le&&I!==j&&I!==x&&I!==P&&I!==g&&I!==w&&I!==E&&I!==D}function Ke(I){return!we(I)&&I!==O}function tt(I,K){const ee=I.charCodeAt(K);let Z;return ee>=55296&&ee<=56319&&K+1<I.length&&(Z=I.charCodeAt(K+1),Z>=56320&&Z<=57343)?(ee-55296)*1024+Z-56320+65536:ee}function ze(I){return/^\n* /.test(I)}const Ge=1,qe=2,L=3,N=4,q=5;function X(I,K,ee,Z,ce,pe,fe,Ae){let _e,Ne=0,Pe=null,Xe=!1,st=!1;const rn=Z!==-1;let Et=-1,tn=Je(tt(I,0))&&Ke(tt(I,I.length-1));if(K||fe)for(_e=0;_e<I.length;Ne>=65536?_e+=2:_e++){if(Ne=tt(I,_e),!ie(Ne))return q;tn=tn&&Ue(Ne,Pe,Ae),Pe=Ne}else{for(_e=0;_e<I.length;Ne>=65536?_e+=2:_e++){if(Ne=tt(I,_e),Ne===l)Xe=!0,rn&&(st=st||_e-Et-1>Z&&I[Et+1]!==" ",Et=_e);else if(!ie(Ne))return q;tn=tn&&Ue(Ne,Pe,Ae),Pe=Ne}st=st||rn&&_e-Et-1>Z&&I[Et+1]!==" "}return!Xe&&!st?tn&&!fe&&!ce(I)?Ge:pe===be?q:qe:ee>9&&ze(I)?q:fe?pe===be?q:qe:st?N:L}function me(I,K,ee,Z,ce){I.dump=(function(){if(K.length===0)return I.quotingType===be?'""':"''";if(!I.noCompatMode&&(ke.indexOf(K)!==-1||te.test(K)))return I.quotingType===be?'"'+K+'"':"'"+K+"'";const pe=I.indent*Math.max(1,ee),fe=I.lineWidth===-1?-1:Math.max(Math.min(I.lineWidth,40),I.lineWidth-pe),Ae=Z||I.flowLevel>-1&&ee>=I.flowLevel;function _e(Ne){return De(I,Ne)}switch(X(K,Ae,I.indent,fe,_e,I.quotingType,I.forceQuotes&&!Z,ce)){case Ge:return K;case qe:return"'"+K.replace(/'/g,"''")+"'";case L:return"|"+$e(K,I.indent)+Le(de(K,pe));case N:return">"+$e(K,I.indent)+Le(de(nt(K,fe),pe));case q:return'"'+lt(K)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function $e(I,K){const ee=ze(I)?String(K):"",Z=I[I.length-1]===`
|
|
86
|
-
`,pe=Z&&(I[I.length-2]===`
|
|
87
|
-
`||I===`
|
|
88
|
-
`)?"+":Z?"":"-";return ee+pe+`
|
|
89
|
-
`}function Le(I){return I[I.length-1]===`
|
|
90
|
-
`?I.slice(0,-1):I}function nt(I,K){const ee=/(\n+)([^\n]*)/g;let Z=(function(){let Ae=I.indexOf(`
|
|
91
|
-
`);return Ae=Ae!==-1?Ae:I.length,ee.lastIndex=Ae,at(I.slice(0,Ae),K)})(),ce=I[0]===`
|
|
92
|
-
`||I[0]===" ",pe,fe;for(;fe=ee.exec(I);){const Ae=fe[1],_e=fe[2];pe=_e[0]===" ",Z+=Ae+(!ce&&!pe&&_e!==""?`
|
|
93
|
-
`:"")+at(_e,K),ce=pe}return Z}function at(I,K){if(I===""||I[0]===" ")return I;const ee=/ [^ ]/g;let Z,ce=0,pe,fe=0,Ae=0,_e="";for(;Z=ee.exec(I);)Ae=Z.index,Ae-ce>K&&(pe=fe>ce?fe:Ae,_e+=`
|
|
94
|
-
`+I.slice(ce,pe),ce=pe+1),fe=Ae;return _e+=`
|
|
95
|
-
`,I.length-ce>K&&fe>ce?_e+=I.slice(ce,fe)+`
|
|
96
|
-
`+I.slice(fe+1):_e+=I.slice(ce),_e.slice(1)}function lt(I){let K="",ee=0;for(let Z=0;Z<I.length;ee>=65536?Z+=2:Z++){ee=tt(I,Z);const ce=je[ee];!ce&&ie(ee)?(K+=I[Z],ee>=65536&&(K+=I[Z+1])):K+=ce||ye(ee)}return K}function pt(I,K,ee){let Z="";const ce=I.tag;for(let pe=0,fe=ee.length;pe<fe;pe+=1){let Ae=ee[pe];I.replacer&&(Ae=I.replacer.call(ee,String(pe),Ae)),(Y(I,K,Ae,!1,!1)||typeof Ae>"u"&&Y(I,K,null,!1,!1))&&(Z!==""&&(Z+=","+(I.condenseFlow?"":" ")),Z+=I.dump)}I.tag=ce,I.dump="["+Z+"]"}function Oe(I,K,ee,Z){let ce="";const pe=I.tag;for(let fe=0,Ae=ee.length;fe<Ae;fe+=1){let _e=ee[fe];I.replacer&&(_e=I.replacer.call(ee,String(fe),_e)),(Y(I,K+1,_e,!0,!0,!1,!0)||typeof _e>"u"&&Y(I,K+1,null,!0,!0,!1,!0))&&((!Z||ce!=="")&&(ce+=xe(I,K)),I.dump&&l===I.dump.charCodeAt(0)?ce+="-":ce+="- ",ce+=I.dump)}I.tag=pe,I.dump=ce||"[]"}function Ye(I,K,ee){let Z="";const ce=I.tag,pe=Object.keys(ee);for(let fe=0,Ae=pe.length;fe<Ae;fe+=1){let _e="";Z!==""&&(_e+=", "),I.condenseFlow&&(_e+='"');const Ne=pe[fe];let Pe=ee[Ne];I.replacer&&(Pe=I.replacer.call(ee,Ne,Pe)),Y(I,K,Ne,!1,!1)&&(I.dump.length>1024&&(_e+="? "),_e+=I.dump+(I.condenseFlow?'"':"")+":"+(I.condenseFlow?"":" "),Y(I,K,Pe,!1,!1)&&(_e+=I.dump,Z+=_e))}I.tag=ce,I.dump="{"+Z+"}"}function f(I,K,ee,Z){let ce="";const pe=I.tag,fe=Object.keys(ee);if(I.sortKeys===!0)fe.sort();else if(typeof I.sortKeys=="function")fe.sort(I.sortKeys);else if(I.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Ae=0,_e=fe.length;Ae<_e;Ae+=1){let Ne="";(!Z||ce!=="")&&(Ne+=xe(I,K));const Pe=fe[Ae];let Xe=ee[Pe];if(I.replacer&&(Xe=I.replacer.call(ee,Pe,Xe)),!Y(I,K+1,Pe,!0,!0,!0))continue;const st=I.tag!==null&&I.tag!=="?"||I.dump&&I.dump.length>1024;st&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+="?":Ne+="? "),Ne+=I.dump,st&&(Ne+=xe(I,K)),Y(I,K+1,Xe,!0,st)&&(I.dump&&l===I.dump.charCodeAt(0)?Ne+=":":Ne+=": ",Ne+=I.dump,ce+=Ne)}I.tag=pe,I.dump=ce||"{}"}function U(I,K,ee){const Z=ee?I.explicitTypes:I.implicitTypes;for(let ce=0,pe=Z.length;ce<pe;ce+=1){const fe=Z[ce];if((fe.instanceOf||fe.predicate)&&(!fe.instanceOf||typeof K=="object"&&K instanceof fe.instanceOf)&&(!fe.predicate||fe.predicate(K))){if(ee?fe.multi&&fe.representName?I.tag=fe.representName(K):I.tag=fe.tag:I.tag="?",fe.represent){const Ae=I.styleMap[fe.tag]||fe.defaultStyle;let _e;if(a.call(fe.represent)==="[object Function]")_e=fe.represent(K,Ae);else if(o.call(fe.represent,Ae))_e=fe.represent[Ae](K,Ae);else throw new t("!<"+fe.tag+'> tag resolver accepts not "'+Ae+'" style');I.dump=_e}return!0}}return!1}function Y(I,K,ee,Z,ce,pe,fe){I.tag=null,I.dump=ee,U(I,ee,!1)||U(I,ee,!0);const Ae=a.call(I.dump),_e=Z;Z&&(Z=I.flowLevel<0||I.flowLevel>K);const Ne=Ae==="[object Object]"||Ae==="[object Array]";let Pe,Xe;if(Ne&&(Pe=I.duplicates.indexOf(ee),Xe=Pe!==-1),(I.tag!==null&&I.tag!=="?"||Xe||I.indent!==2&&K>0)&&(ce=!1),Xe&&I.usedDuplicates[Pe])I.dump="*ref_"+Pe;else{if(Ne&&Xe&&!I.usedDuplicates[Pe]&&(I.usedDuplicates[Pe]=!0),Ae==="[object Object]")Z&&Object.keys(I.dump).length!==0?(f(I,K,I.dump,ce),Xe&&(I.dump="&ref_"+Pe+I.dump)):(Ye(I,K,I.dump),Xe&&(I.dump="&ref_"+Pe+" "+I.dump));else if(Ae==="[object Array]")Z&&I.dump.length!==0?(I.noArrayIndent&&!fe&&K>0?Oe(I,K-1,I.dump,ce):Oe(I,K,I.dump,ce),Xe&&(I.dump="&ref_"+Pe+I.dump)):(pt(I,K,I.dump),Xe&&(I.dump="&ref_"+Pe+" "+I.dump));else if(Ae==="[object String]")I.tag!=="?"&&me(I,I.dump,K,pe,_e);else{if(Ae==="[object Undefined]")return!1;if(I.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Ae)}if(I.tag!==null&&I.tag!=="?"){let st=encodeURI(I.tag[0]==="!"?I.tag.slice(1):I.tag).replace(/!/g,"%21");I.tag[0]==="!"?st="!"+st:st.slice(0,18)==="tag:yaml.org,2002:"?st="!!"+st.slice(18):st="!<"+st+">",I.dump=st+" "+I.dump}}return!0}function he(I,K){const ee=[],Z=[];re(I,ee,Z);const ce=Z.length;for(let pe=0;pe<ce;pe+=1)K.duplicates.push(ee[Z[pe]]);K.usedDuplicates=new Array(ce)}function re(I,K,ee){if(I!==null&&typeof I=="object"){const Z=K.indexOf(I);if(Z!==-1)ee.indexOf(Z)===-1&&ee.push(Z);else if(K.push(I),Array.isArray(I))for(let ce=0,pe=I.length;ce<pe;ce+=1)re(I[ce],K,ee);else{const ce=Object.keys(I);for(let pe=0,fe=ce.length;pe<fe;pe+=1)re(I[ce[pe]],K,ee)}}}function W(I,K){K=K||{};const ee=new ae(K);ee.noRefs||he(I,ee);let Z=I;return ee.replacer&&(Z=ee.replacer.call({"":Z},"",Z)),Y(ee,0,Z,!0,!0)?ee.dump+`
|
|
97
|
-
`:""}return tf.dump=W,tf}var Ey;function UO(){if(Ey)return Ln;Ey=1;const e=LO(),t=HO();function n(a,o){return function(){throw new Error("Function yaml."+a+" is removed in js-yaml 4. Use yaml."+o+" instead, which is now safe by default.")}}return Ln.Type=Gn(),Ln.Schema=Ek(),Ln.FAILSAFE_SCHEMA=$k(),Ln.JSON_SCHEMA=Uk(),Ln.CORE_SCHEMA=qk(),Ln.DEFAULT_SCHEMA=fg(),Ln.load=e.load,Ln.loadAll=e.loadAll,Ln.dump=t.dump,Ln.YAMLException=hc(),Ln.types={binary:Fk(),float:Hk(),map:Ok(),null:Nk(),pairs:Kk(),set:Wk(),timestamp:zk(),bool:Dk(),int:Lk(),merge:Bk(),omap:Vk(),seq:jk(),str:Mk()},Ln.safeLoad=n("safeLoad","load"),Ln.safeLoadAll=n("safeLoadAll","loadAll"),Ln.safeDump=n("safeDump","dump"),Ln}var qO=UO();const zO=NO(qO),{Type:SX,Schema:xX,FAILSAFE_SCHEMA:kX,JSON_SCHEMA:wX,CORE_SCHEMA:IX,DEFAULT_SCHEMA:_X,load:CX,loadAll:RX,dump:PX,YAMLException:AX,types:TX,safeLoad:EX,safeLoadAll:MX,safeDump:jX}=zO,hg=3e3,gg=9999,OX="openpond.yaml",BO=["google","github","x"],vg=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),My=p(i().trim().min(1).max(1e3)).max(50),Bl=i().trim().min(1).max(4096).refine(Yk,{message:"path must be a relative workspace path"}),FO=i().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),VO=i().trim().regex(/^sha256:[0-9a-f]{64}$/i),Gk=i().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),KO=c({ref:FO,digest:VO.optional(),registrySecretRef:i().trim().min(1).max(500).optional(),platform:S("linux/amd64").optional(),workspaceRoot:Gk.optional()}).strict(),WO=c({context:Bl.default("."),path:Bl.default("Dockerfile"),target:i().trim().min(1).max(191).optional(),buildArgs:oe(i().max(191),i().max(500)).optional(),registrySecretRefs:p(i().trim().min(1).max(500)).max(10).optional(),platform:S("linux/amd64").optional(),workspaceRoot:Gk.optional()}).strict(),GO=c({base:i().trim().min(1).max(120).optional(),snapshot:i().trim().min(1).max(191).optional(),image:KO.optional(),dockerfile:WO.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:Fn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),Jk=c({cpu:u().positive().max(8).optional(),memoryGb:u().positive().max(32).optional(),diskGb:u().positive().max(100).optional()}).strict(),JO=c({provider:b(BO),scopes:p(i().trim().min(1).max(200)).max(100).default([]),capabilities:p(i().trim().min(1).max(200)).max(100).default([])}).strict(),ZO=c({models:p(i().trim().min(1).max(200)).max(100).default([]),scopes:p(i().trim().min(1).max(200)).max(100).default([])}).strict(),YO=c({opchat:ZO.optional()}).catchall(oe(i(),se())).default({}),QO=c({name:i().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:i().trim().min(1).max(256).optional(),storageGb:u().int().positive().max(100).optional(),deleteOnSandboxDelete:A().optional()}).strict(),XO=c({port:u().int().min(hg).max(gg).refine(e=>!vg.has(e),{message:"preview port is reserved"}),protocol:S("http").default("http"),label:i().trim().min(1).max(80).optional(),access:b(["private","public"]).default("private"),path:i().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),Zk=c({command:i().trim().min(1).max(1e3),cwd:Bl.optional(),timeoutSeconds:u().int().positive().max(86400).optional(),requiresStart:A().default(!1),ports:p(XO).max(20).default([]),artifactPaths:p(Bl).max(100).default([])}).strict(),jy=Zk.extend({name:i().trim().min(1).max(80)}).strict(),e2=c({name:i().trim().min(1).max(80).optional(),service:i().trim().min(1).max(80).optional(),port:u().int().min(hg).max(gg).refine(e=>!vg.has(e),{message:"app MCP port is reserved"}),path:i().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"app MCP path must start with /"}).default("/mcp")}).strict(),t2=c({name:i().trim().min(1).max(80).optional(),port:u().int().min(hg).max(gg).refine(e=>!vg.has(e),{message:"validation probe port is reserved"}),path:i().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"validation probe path must start with /"}).default("/"),expectedStatus:u().int().min(100).max(599).default(200)}).strict(),n2=oe(i(),se()).refine(e=>e.type==="object","input schema must be a JSON schema object"),a2=c({name:i().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:A().default(!1),secret:A().default(!0),description:i().trim().max(500).optional()}).strict(),nf=i().trim().min(1).max(120),o2=c({name:i().trim().min(1).max(120),description:i().trim().max(500).optional(),cron:i().trim().min(1).max(500).optional(),rate:i().trim().min(1).max(500).optional(),once:nf.optional(),scheduleType:b(["rate","cron","once"]).optional(),scheduleExpression:i().trim().min(1).max(500).optional(),timezone:i().trim().min(1).max(100).optional(),enabled:A().default(!0),startAt:nf.optional(),endAt:nf.optional(),maxRuns:u().int().positive().nullable().optional(),runtimePolicy:b(["run_and_stop","run_and_archive","run_and_delete","use_existing_running"]).default("run_and_stop"),action:i().trim().min(1).max(120).optional(),actionName:i().trim().min(1).max(120).optional(),command:i().trim().min(1).max(2e3).optional(),target:c({kind:b(["start","action","service","command"]).optional(),name:i().trim().min(1).max(120).optional(),actionName:i().trim().min(1).max(120).optional(),command:i().trim().min(1).max(2e3).optional(),requiresStart:A().optional()}).strict().optional(),requiresStart:A().optional(),budget:c({maxUsd:i().trim().min(1).max(40).optional()}).strict().optional(),resources:Jk.optional(),quotas:oe(i(),se()).optional(),lifecycle:oe(i(),se()).optional(),retentionPolicy:oe(i(),se()).optional(),env:p(c({name:i().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),value:i().optional(),secretRef:i().optional()}).strict()).max(100).optional(),integrationLeases:p(oe(i(),se())).max(20).optional(),metadata:oe(i(),se()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(l=>typeof l=="string"&&l.trim()).length!==1&&t.addIssue({code:Fn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:Fn.custom,path:["scheduleType"],message:"scheduleType is required with scheduleExpression"});const a=e.command??e.target?.command??null,o=e.target?.name??null,r=e.actionName??e.action??e.target?.actionName??(e.target?.kind==="action"?o:null),s=e.target?.kind??(a?"command":"action");s==="action"&&!r&&t.addIssue({code:Fn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!o&&t.addIssue({code:Fn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:Fn.custom,path:["command"],message:"schedule command target is required"})}),i2=c({schemaVersion:S(1),name:i().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/),version:i().trim().min(1).max(40),useCase:i().trim().min(1).max(80),description:i().trim().min(1).max(500),runtime:GO,resources:Jk.optional(),setup:c({commands:My.default([])}).strict().default({commands:[]}),validation:c({commands:My.min(1),probes:p(t2).max(20).default([])}).strict(),start:Zk,actions:p(jy).max(20).default([]),services:p(jy).max(20).default([]),schedules:p(o2).max(20).default([]),mcp:c({endpoints:p(e2).max(10).default([])}).strict().default({endpoints:[]}),volumes:p(QO).max(5).default([]),integrations:c({requiredLeases:p(JO).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:YO,inputs:c({schema:n2.default({type:"object"}),env:p(a2).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:c({paths:p(Bl).max(100).default([])}).strict().default({paths:[]}),network:c({egress:b(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{s2(e,t),bg(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),l2(e,t),c2(e,t),d2(e,t),u2(e,t)}),r2=c({path:i(),message:i(),code:i()});function $X(e){return[{kind:"start",name:"start",...e.start,artifactPaths:of(e.start,e)},...e.actions.map(t=>({kind:"action",name:t.name,command:t.command,cwd:t.cwd,timeoutSeconds:t.timeoutSeconds,requiresStart:t.requiresStart,ports:t.ports,artifactPaths:of(t,e)})),...e.services.map(t=>({kind:"service",name:t.name,command:t.command,cwd:t.cwd,timeoutSeconds:t.timeoutSeconds,requiresStart:t.requiresStart,ports:t.ports,artifactPaths:of(t,e)}))]}function Yk(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function bg(e,t,n,a){const o=new Set;for(const r of t){if(o.has(r)){e.addIssue({code:Fn.custom,path:[a],message:n});return}o.add(r)}}function s2(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];bg(t,n,"start, action, and service names must be unique","actions")}function l2(e,t){const n=af(e.inputs.schema.properties),a=new Set(e.volumes.map(o=>o.name).filter(o=>!!o));for(const[o,r]of Object.entries(n)){const s=af(r),l=af(s["x-openpond-upload"]??s.xOpenPondUpload),m=typeof l.targetPath=="string"&&l.targetPath.trim()?l.targetPath.trim():typeof l.path=="string"&&l.path.trim()?l.path.trim():"";if(!m)continue;const d=m.replace(/^workspace\//,"").replace(/^\/+/,"").replace(/\/+$/,"");if(!Yk(d)){t.addIssue({code:Fn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const h=d.split("/");h[0]==="volumes"&&(!h[1]||!a.has(h[1]))&&t.addIssue({code:Fn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function c2(e,t){bg(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function d2(e,t){const n=new Map(e.services.map(o=>[o.name,new Set(o.ports.map(r=>r.port))])),a=new Set([...e.start.ports.map(o=>o.port),...e.services.flatMap(o=>o.ports.map(r=>r.port))]);for(const[o,r]of e.mcp.endpoints.entries()){if(r.service){const s=n.get(r.service);if(!s){t.addIssue({code:Fn.custom,path:["mcp","endpoints",o,"service"],message:`app MCP service does not exist: ${r.service}`});continue}s.has(r.port)||t.addIssue({code:Fn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${r.port} is not declared on service ${r.service}`});continue}a.has(r.port)||t.addIssue({code:Fn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${r.port} is not declared on start or services`})}}function u2(e,t){const n=new Set(e.actions.map(o=>o.name)),a=new Set(e.services.map(o=>o.name));for(const[o,r]of e.schedules.entries()){const s=r.command??r.target?.command??null;if(r.target?.kind==="command"||s)continue;const l=r.actionName??r.action??r.target?.actionName??(r.target?.kind==="action"?r.target?.name:null);if(l&&!n.has(l)&&t.addIssue({code:Fn.custom,path:["schedules",o,"action"],message:`schedule action target does not exist: ${l}`}),r.target?.kind==="service"){const m=r.target.name??"";m&&!a.has(m)&&t.addIssue({code:Fn.custom,path:["schedules",o,"target","name"],message:`schedule service target does not exist: ${m}`})}}}function af(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function of(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const m2=c({id:i(),name:i(),description:i().nullable(),scheduleType:i(),scheduleExpression:i(),enabled:A(),rawEnabled:A().optional(),syncStatus:i().nullable(),syncError:i().nullable().optional(),startAt:i().nullable(),endAt:i().nullable(),maxRuns:u().nullable(),executionCount:u().nullable(),lifecycleStatus:i().nullable(),lifecycleReason:i().nullable(),lastExecutionAt:i().nullable().optional(),lastExecutionStatus:i().nullable().optional(),lastRunNowAt:i().nullable().optional(),lastRunNowStatus:i().nullable().optional(),updatedAt:i(),deploymentId:i(),isProduction:A().optional(),payload:se().optional()}).passthrough(),p2=c({total:u().int().nonnegative(),active:u().int().nonnegative(),paused:u().int().nonnegative(),enabled:u().int().nonnegative().optional(),disabled:u().int().nonnegative().optional(),nextRunAt:i().nullable().optional(),lastRunAt:i().nullable().optional(),schedules:p(m2).optional().default([]),truncated:A().optional()}).passthrough(),rf=c({name:i(),kind:b(["start","action","service"]),command:i(),cwd:i().nullable(),timeoutSeconds:u().nullable(),requiresStart:A(),ports:p(c({port:u(),protocol:i(),label:i().nullable(),access:i(),path:i()}).passthrough()).default([]),artifactPaths:p(i()).default([])}).passthrough(),f2=c({schemaVersion:S(1),source:S("openpond.yaml"),manifestName:i(),manifestVersion:i(),manifestUseCase:i(),manifestDescription:i(),manifestPath:i(),manifestHash:i(),inputSchema:oe(i(),se()).default({}),env:p(c({name:i(),required:A(),secret:A(),description:i().nullable()}).passthrough()).default([]),start:rf,actions:p(rf).default([]),services:p(rf).default([]),defaultActionName:i().nullable(),updatedAt:i()}).passthrough(),h2=c({id:i(),name:i(),description:i().nullable(),visibility:i().nullable().optional(),gitOwner:i().nullable().optional(),gitRepo:i().nullable().optional(),gitHost:i().nullable().optional(),defaultBranch:i().nullable().optional(),sandbox:A().optional().default(!1),sandboxActionRegistry:f2.nullable().optional(),sandboxManifestHash:i().nullable().optional(),sandboxManifestPath:i().nullable().optional(),sandboxManifestSyncedAt:i().nullable().optional(),sandboxManifestError:i().nullable().optional(),updatedAt:i().nullable().optional(),latestDeployment:c({id:i().optional(),status:i().optional(),deploymentDomain:i().nullable().optional(),createdAt:i().optional(),isProduction:A().nullable().optional(),gitBranch:i().nullable().optional()}).nullable().optional(),scheduleSummary:p2.nullable().optional()}),g2=c({detected:A(),rootPath:i(),manifestPath:i(),manifestHash:i().nullable().optional().default(null),manifest:oe(i(),se()).nullable().optional().default(null),normalizedManifest:i2.nullable().optional().default(null),valid:A().optional().default(!1),diagnostics:p(r2).optional().default([])}),v2=c({appId:i(),appName:i(),gitOwner:i().nullable(),gitRepo:i().nullable(),gitHost:i().nullable(),defaultBranch:i().nullable(),linkedAt:i()}),Qk=c({teamId:i(),projectId:i(),projectSlug:i().nullable().optional().default(null),projectName:i().nullable().optional().default(null),sourceRepoUrl:i().nullable().optional().default(null),defaultBranch:i().nullable().optional().default(null),lastUploadedCommit:i().nullable().optional().default(null),lastUploadTransport:b(["git_head","snapshot","api_source_upload"]).nullable().optional().default(null),manifestPath:i().nullable().optional().default(null),manifestHash:i().nullable().optional().default(null),syncedAt:i().nullable().optional().default(null),linkedAt:i()}),b2=b(["github_repo","internal_repo","template","manual"]),y2=c({id:i(),teamId:i(),name:i(),slug:i().nullable().optional().default(null),sourceType:b2.optional().default("manual"),sourceLabel:i().nullable().optional().default(null),defaultBranch:i().nullable().optional().default(null),internalRepoPath:i().nullable().optional().default(null),manifestPath:i().nullable().optional().default(null),manifestHash:i().nullable().optional().default(null),syncedAt:i().nullable().optional().default(null),organizationName:i().nullable().optional().default(null),organizationSlug:i().nullable().optional().default(null),createdAt:i().nullable().optional().default(null),updatedAt:i().nullable().optional().default(null)}),S2=c({id:i(),name:i(),path:i(),workspacePath:i(),repoPath:i().nullable(),source:b(["folder","git"]),sourceFolders:p(i().min(1)).min(1).optional(),hiddenFromDefaultSidebar:A().optional(),sandboxTemplate:g2.nullable().optional().default(null),linkedOpenPondApp:v2.nullable().optional().default(null),linkedSandboxProject:Qk.nullable().optional().default(null),preferredSandboxAgentId:i().nullable().optional().default(null),createdAt:i(),updatedAt:i()});c({path:i().trim().min(1).optional(),sourceFolders:p(i().trim().min(1)).min(1).optional(),primaryFolder:i().trim().min(1).optional(),name:i().trim().min(1).max(120).optional(),createNew:A().optional(),baseDirectory:i().trim().min(1).max(4096).optional()}).superRefine((e,t)=>{if(e.createNew){(e.path||e.sourceFolders||e.primaryFolder)&&t.addIssue({code:"custom",message:"A new folder cannot be combined with existing source folders."}),e.name?.trim()||t.addIssue({code:"custom",path:["name"],message:"Project name is required when creating a new project."});return}e.path&&e.sourceFolders&&t.addIssue({code:"custom",message:"Use either path or source folders."}),!e.path?.trim()&&!e.sourceFolders?.length&&t.addIssue({code:"custom",path:["path"],message:"Project path is required."}),e.sourceFolders?.length&&!e.name?.trim()&&t.addIssue({code:"custom",path:["name"],message:"Project name is required."}),e.primaryFolder&&!e.sourceFolders?.length&&t.addIssue({code:"custom",path:["primaryFolder"],message:"Primary folder requires source folders."})});c({linkedSandboxProject:Qk.nullable().optional(),preferredSandboxAgentId:i().nullable().optional(),hiddenFromDefaultSidebar:A().optional()});const x2=["connected_app_search","connected_app_read","connected_app_write"],sf="https://openpond.ai",yg=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Sg={slack:[Gt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Gt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Gt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Gt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Gt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Gt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Gt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Gt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Gt("google.comments.read","Read comments","Read Google file comments.","read",!0),Gt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Gt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Gt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Gt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Gt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Gt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Gt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Gt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Gt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Gt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Gt("x.search.read","Search X","Search public X posts when granted.","read",!0),Gt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Gt("x.post.write","Post","Create approved X posts.","write",!0),Gt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Gt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Gt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},xg={slack:[],microsoft_teams:[],google:[Ht("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Ht("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Ht("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Ht("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Ht("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Ht("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Ht("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Ht("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Ht("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Ht("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Ht("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Ht("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Ht("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Ht("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Ht("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Ht("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Ht("github.pull_request.comment","write","Comment on pull request","Create an explicitly approved pull request comment and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref","body"]}),Ht("github.pull_request.update","write","Update pull request","Apply an explicitly approved pull request metadata update and return readback verification.",["github.pull_request.write"],{requiredKeys:["ref"]})],turnkey:[Ht("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Ht("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Ht("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Ht("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Ht("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Ht("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Ht("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Ht("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Ht("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Ht("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},k2={google:["# Google Connected App","","Use Google only through server-provided connected app tools. Never ask for or infer OAuth tokens.","Before reading or editing, identify the exact Drive file, Doc, Sheet, Slide, or comment thread. If the target is ambiguous, ask a short clarification or search first.","Use only declared Google operation ids: google.drive.search, google.drive.read_file, google.docs.read, google.comments.read, google.docs.update, google.comments.create, google.comments.resolve.","For writes, require explicit user intent, summarize the planned change, and verify the target identity before applying updates.","After a write, read back the changed object or relevant range and report the result with the provider file name or stable reference.","Prefer narrow reads over broad Drive scans. Do not expose private file ids unless the tool result already presents them as stable refs."].join(`
|
|
98
|
-
`),github:["# GitHub Connected App","","Use GitHub only through server-provided connected app tools. Repository, issue, and pull request identity must be grounded before action.","Use only declared GitHub operation ids: github.repo.search, github.issue.search, github.pull_request.search, github.repo.read, github.issue.read, github.pull_request.read, github.issue.create, github.issue.comment, github.issue.update, github.pull_request.comment, github.pull_request.update.","For reads, name the owner/repo and issue or pull request number when available. If several targets match, ask or inspect before proceeding.","For writes, require explicit user intent and avoid destructive repository changes. Create issues only when the user clearly asks to submit or file a new issue. Prefer comments, labels, or metadata updates unless a stronger operation is clearly requested.","Do not claim CI, review, branch, or PR state changed until a tool result confirms it.","Keep local workspace git operations separate from connected GitHub operations unless the user explicitly asks to bridge them."].join(`
|
|
99
|
-
`),turnkey:["# Turnkey Agent Wallet Connected App","","Use Turnkey only through server-provided connected app tools. Never ask for, expose, or infer API keys, P-256 credentials, wallet private keys, or lease material.","Use only declared Turnkey read operation ids: turnkey.wallets.read, turnkey.balances.read, and turnkey.activities.read.","Turnkey connected-app access is read-only. Do not claim that a transaction was created, signed, approved, rejected, or sent.","Use turnkey.wallets.read for the Agent Wallet address and metadata, turnkey.balances.read for supported-network balances, and turnkey.activities.read for recent Turnkey activity.","Report the wallet address and network with balance results, and distinguish an empty balance from a failed provider read."].join(`
|
|
100
|
-
`),x:["# X Connected App","","Use X only through server-provided connected app tools. Distinguish profile, recent search, mention, post, and reply operations.","Use only declared X operation ids: x.profile.read, x.post.read, x.search.posts, x.mentions.search, x.mention.read, x.post.create, x.reply.create.","For x.com, twitter.com, or stable status URLs, first parse the status/post id and read the post with connected_app_read using operation x.post.read and ref set to the original URL, stable ref, or id. Do not open a browser before trying the X connector.","Use x.search.posts for discovery, related public posts, replies, quote-post searches, and conversation scans. It uses X API recent search, so report zero-result searches as zero recent public posts returned by X.","For conversation or reply collection, dedupe by returned post id/ref. Do not repeat the same search call unless the result exposes a usable cursor or next token; if pagination is unavailable, state that coverage is limited to returned recent-search results.","Reads can summarize recent public posts, connected-account profile details, and mentions when the capability is available.","Writes require explicit user intent for the exact post or reply. Do not publish drafts, jokes, endorsements, or replies unless the user clearly approves the content.","Before posting or replying, preserve account identity, quote the proposed content in summary form, and respect provider limits and policy boundaries.","After a write, verify the returned post or reply ref before reporting success."].join(`
|
|
101
|
-
`),microsoft_teams:["# Microsoft Teams Connected App","","Microsoft Teams is currently an ingestion/native binding surface only. Do not expose Teams OAuth reads, replies, file operations, or sandbox leases.","Native Teams setup can bind chats or channels to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Teams actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
|
|
102
|
-
`),slack:["# Slack Connected App","","Slack is currently an ingestion/native binding surface only. Do not expose Slack OAuth reads, replies, file operations, or sandbox leases.","Native Slack setup can bind channels or threads to OpenPond profiles and ingest activity into OpenPond context.","If the user asks for Slack actions beyond ingestion or binding status, explain that the connector is not available yet rather than inventing tool access."].join(`
|
|
103
|
-
`),mcp:["# OpenPond MCP Connected App","","Use OpenPond MCP only through server-provided tool discovery and call paths. Do not invent MCP tools or endpoints.","Treat MCP as team-scoped tooling, not an OAuth connector. Tool availability must come from server-confirmed discovery results.","Before calling an MCP tool, match the requested operation to the tool name, description, input schema, and allowed team context.","For writes or side effects, require explicit user intent and report only confirmed tool results."].join(`
|
|
104
|
-
`)},NX=yg.map(e=>{const t=e1(e),n=k2[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${z2(n)}`,charCount:n.length}});function w2(e){const t=kg(e.provider);if(!t)return{ok:!1,error:`Connected app provider is not supported: ${e.provider}`};if(!t.leasePolicy.leaseable)return{ok:!1,error:`Connected app provider ${e.provider} is not leaseable for cloud connector execution.`};const n=D2(e.operation);if(e.toolName!==n)return{ok:!1,error:`Connected app tool ${e.toolName} does not match ${e.operation} operation.`};const a=e.operation==="write"?"write":"read",o=new Set(t.capabilities.filter(l=>l.access===a&&l.leaseable).map(l=>l.id)),r=e.capabilityIds.filter(l=>!o.has(l));if(r.length>0)return{ok:!1,error:`Connected app capability ${r[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=_2(e);return s.ok?{ok:!0,request:e}:s}function I2(e){const t=Mu(e);return t?xg[t]:[]}function _2(e){const t=A2(e.args),n=I2(e.provider).filter(s=>s.operation===e.operation);if(n.length===0)return{ok:!1,error:`Connected app provider ${e.provider} does not declare ${e.operation} operations.`};if(!t)return e.operation==="write"?{ok:!1,error:`Connected app ${e.provider} write calls require a provider operation id.`}:{ok:!0,request:e};const a=n.find(s=>s.id===t);if(!a)return{ok:!1,error:`Connected app operation ${t} is not allowed for ${e.provider} ${e.operation}.`};const o=e.capabilityIds.filter(s=>!a.capabilityIds.includes(s));if(o.length>0)return{ok:!1,error:`Connected app operation ${a.id} does not allow capability ${o[0]}.`};const r=E2(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const l=r[s];if(l==null||typeof l=="string"&&!l.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const C2=[{id:"slack",providerFamily:"slack",setupSurface:"native_bot",statusSource:"native_binding",label:"Slack",shortLabel:"Slack",kind:"native",category:"Chat",description:"Bind Slack channels or threads for ingestion into OpenPond profiles.",icon:"/connected-apps/slack.svg",installLabel:"Continue to Slack details"},{id:"google",providerFamily:"google",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"Google",shortLabel:"Google",kind:"oauth",category:"Productivity",description:"Docs, Drive files, and comments for sandbox workflows.",icon:"/connected-apps/google.svg",installLabel:"Continue to Google details"},{id:"github",providerFamily:"github",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"GitHub",shortLabel:"GitHub",kind:"oauth",category:"Developer tools",description:"Access repositories, issues, and pull requests.",icon:"/connected-apps/github.svg",installLabel:"Continue to GitHub details"},{id:"x",providerFamily:"x",setupSurface:"oauth_connector",statusSource:"integration_connection",label:"X",shortLabel:"X",kind:"oauth",category:"Productivity",description:"User profile, mentions, and approved reply access.",icon:"/connected-apps/x.svg",installLabel:"Continue to X details"},{id:"turnkey",providerFamily:"turnkey",setupSurface:"wallet_connector",statusSource:"integration_connection",label:"Turnkey Agent Wallet",shortLabel:"Turnkey",kind:"wallet",category:"Wallet",description:"Read your OpenPond Agent Wallet address, balances, and activity through policy-bound Turnkey access.",icon:"/connected-apps/turnkey.svg",installLabel:"Manage OpenPond wallet"},{id:"microsoft_teams",providerFamily:"microsoft_teams",setupSurface:"native_bot",statusSource:"native_binding",label:"Teams",shortLabel:"Teams",kind:"native",category:"Chat",description:"Bind Teams chats or channels for ingestion into OpenPond profiles.",icon:"/connected-apps/microsoft.svg",installLabel:"Continue to Teams details"},{id:"mcp",providerFamily:"mcp",setupSurface:"mcp_endpoint",statusSource:"mcp_endpoint",label:"OpenPond MCP",shortLabel:"MCP",kind:"mcp",category:"Tools",description:"Expose workspace tools through a team-scoped MCP endpoint.",icon:"/connected-apps/openpond-mcp.svg",installLabel:"Open MCP settings"}],Eu=C2,R2=yg.map(e=>{const t=Eu.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:El(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Sg[e],skills:$2(e),tools:N2(e),operations:xg[e],leasePolicy:L2(e)}});function Xk(e){const t=P2(e);return t?Eu.find(n=>n.id===t)??null:null}function kg(e){const t=Mu(e);return t?R2.find(n=>n.id===t)??null:null}function DX(e){const t=Xk(e.appId),n=j2(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",o=new URL(a,n);t?.kind!=="mcp"&&o.searchParams.set("app",t?.deepLinkAppId??e.appId);const r=e.teamId?.trim();return r&&o.searchParams.set("teamId",r),o.toString()}function P2(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Eu.some(n=>n.id===t)?t:null:null}function Mu(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":yg.includes(t)?t:Xk(t)?.providerFamily??null:null}function lf(e={}){const t=H2(e.connections??[]);return Eu.map(n=>{const a=kg(n.providerFamily),o=n.statusSource==="integration_connection"?t.filter(l=>l.provider===n.providerFamily):[],r=o.some(l=>l.status==="active"),s=U2(n,r);return{...n,providerLabel:a.label,setupSurfaceLabel:O2(n.setupSurface),status:s,statusLabel:q2(n,s,o),connections:o,connected:r,capabilities:Oy(n,a.capabilities),capabilityLabels:Oy(n,a.capabilities).map(l=>l.label),leasePolicy:a.leasePolicy}})}function Gt(e,t,n,a,o){return{id:e,label:t,description:n,access:a,leaseable:o}}function Ht(e,t,n,a,o,r){return{id:e,operation:t,label:n,description:a,capabilityIds:o,...r?{input:r}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function A2(e){return T2(e.operation)}function T2(e){return typeof e=="string"&&e.trim()?e.trim():null}function E2(e,t){return t==="write"?M2(e.input)?e.input:{}:e}function M2(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function j2(e){const t=e?.trim();if(!t)return sf;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?sf:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return sf}}function El(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function O2(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function $2(e){return[e1(e)]}function e1(e){return{name:`${e}-connected-app`,description:`Use ${El(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function N2(e){if(e==="mcp")return[];const t=Sg[e],n=xg[e],a=t.filter(s=>s.access==="read").map(s=>s.id),o=t.filter(s=>s.access==="write").map(s=>s.id),r=[];return n.some(s=>s.operation==="search")&&r.push({name:"connected_app_search",description:`Search ${El(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(s=>s.operation==="read")&&r.push({name:"connected_app_read",description:`Read a grounded ${El(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),o.length>0&&n.some(s=>s.operation==="write")&&r.push({name:"connected_app_write",description:`Perform an explicitly approved ${El(e)} write through a server-owned connected app connector.`,capabilityIds:o,write:!0}),r}function D2(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function L2(e){const t=Sg[e].filter(a=>a.leaseable).map(a=>a.id),n=e!=="mcp"&&t.length>0;return{leaseable:n,defaultTtlSeconds:n?e==="turnkey"?300:3600:null,allowedCapabilityIds:t,requiresProxy:n}}function Oy(e,t){return e.setupSurface==="native_bot"?t.filter(n=>n.access==="setup"):e.setupSurface==="mcp_endpoint"?t:t.filter(n=>n.access!=="setup")}function H2(e){return e.flatMap(t=>{const n=Mu(t.provider);return n?[{id:t.id??null,teamId:t.teamId?.trim()||null,provider:n,accountLabel:t.providerAccountName??null,workspaceLabel:t.providerWorkspaceName??null,scopes:Array.isArray(t.scopes)?t.scopes:[],capabilities:Array.isArray(t.capabilities)?t.capabilities:[],status:t.status?.trim().toLowerCase()||"active"}]:[]})}function U2(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function q2(e,t,n){if(t==="connected"){const a=n.filter(o=>o.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function z2(e){let t=5381;for(let n=0;n<e.length;n+=1)t=(t<<5)+t^e.charCodeAt(n);return(t>>>0).toString(36)}const B2=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),F2=b(["search","read","write"]),V2=b(x2);c({provider:B2,operation:F2,toolName:V2,sessionId:i().trim().min(1).max(200),turnId:i().trim().min(1).max(200),toolCallId:i().trim().min(1).max(300),userPrompt:i().max(2e5),connectionIds:p(i().trim().min(1).max(300)).min(1).max(8),capabilityIds:p(i().trim().min(1).max(200)).min(1).max(64),args:oe(i(),se()).default({})}).strict().superRefine((e,t)=>{const n=w2(e);n.ok||t.addIssue({code:Fn.custom,message:n.error})});c({ok:A(),output:i().nullable().optional(),data:se().optional()}).strict();const K2="local_path:";function t1(e){return`${K2}${e.trim()}`}c({appId:i(),source:b(["openpond","github","local_git","local_folder","unknown"]),workspacePath:i(),repoPath:i(),initialized:A(),remoteUrl:i().nullable(),expectedRemoteUrl:i().nullable(),currentBranch:i().nullable(),headCommit:i().nullable().optional().default(null),upstreamBranch:i().nullable().optional().default(null),ahead:u().int().nonnegative().optional().default(0),behind:u().int().nonnegative().optional().default(0),diverged:A().optional().default(!1),linkedSourceHeadCommit:i().nullable().optional().default(null),aheadOfLinkedSource:u().int().nonnegative().optional().default(0),behindLinkedSource:u().int().nonnegative().optional().default(0),divergedFromLinkedSource:A().optional().default(!1),linkedSourceComparisonError:i().nullable().optional().default(null),lastFetchAt:i().nullable().optional().default(null),defaultBranch:i().nullable(),branches:p(i()),dirty:A(),changedFilesCount:u(),untrackedFilesCount:u(),error:i().nullable(),updatedAt:i()});const W2=c({path:i(),status:i(),additions:u(),deletions:u(),patch:i(),content:i().nullable().optional().default(null)}),G2=c({appId:i(),repoPath:i(),initialized:A(),dirty:A(),filesChanged:u(),additions:u(),deletions:u(),repoFiles:p(i()).optional().default([]),files:p(W2),error:i().nullable(),updatedAt:i()});c({branch:i().trim().min(1).max(160)});c({path:i().trim().min(1),content:i()});const $y=c({line:u().int().nonnegative(),character:u().int().nonnegative()}),J2=c({start:$y,end:$y}),Z2=c({path:i(),range:J2,severity:b(["error","warning","info","hint"]),message:i(),source:i().nullable().optional().default(null),code:i().nullable().optional().default(null)}),n1=c({id:i(),root:i(),status:b(["connected","unavailable","error"]),message:i().nullable().optional().default(null)});c({path:i().trim().min(1),content:i().optional(),waitForDiagnostics:A().optional().default(!0)});c({appId:i(),path:i(),diagnostics:p(Z2),servers:p(n1),updatedAt:i()});const Y2=c({operation:b(["hover","definition","references","documentSymbol"]),path:i().trim().min(1),content:i().optional(),line:u().int().nonnegative().optional(),character:u().int().nonnegative().optional()});c({appId:i(),operation:Y2.shape.operation,path:i(),results:se(),servers:p(n1),updatedAt:i()});const Q2=c({pinned:A().optional(),archived:A().optional(),order:u().optional()}),X2=oe(i(),Q2),a1=b(["local","sandbox"]),e$=b(["pinned","saved_for_later"]),o1=c({id:i().min(1),workspaceKind:a1,workspaceId:i().min(1),workspaceName:i().min(1),path:i().min(1),status:e$,order:u().int().nonnegative().nullable().default(null),sourceSessionId:i().min(1).nullable().default(null),available:A().default(!0),createdAt:i().min(1),updatedAt:i().min(1)});c({items:p(o1)});c({workspaceKind:a1,workspaceId:i().trim().min(1),workspaceName:i().trim().min(1),path:i().trim().min(1),status:b(["pinned","saved_for_later","none"]),order:u().int().nonnegative().nullable().optional(),sourceSessionId:i().trim().min(1).nullable().optional()});b(["pin","save_for_later","remove","list"]);function t$(e){let t=e.trim().replaceAll("\\","/");if(t=t.replace(/^(?:workspace|sandbox):file:/,""),t=t.replace(/^\/workspace\/app\//,""),t=t.replace(/^\.\//,""),!t||t.startsWith("/"))throw new Error("File path must be relative to the workspace.");const n=t.split("/").filter(a=>a&&a!==".");if(n.some(a=>a===".."))throw new Error("File path cannot leave the workspace.");if(n.length===0)throw new Error("File path is required.");return n.join("/")}function LX(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(t$(e.path))].join(":")}const n$=c({id:i(),name:i(),type:i(),status:i(),isActive:A().nullable(),price:i().nullable(),currency:i().nullable(),credits:i().nullable()}).passthrough(),a$=c({reachable:A(),authenticated:A().nullable(),apiBase:i(),latencyMs:u(),status:u().nullable(),service:i().nullable(),checkedAt:i(),error:i().nullable()}),o$=c({id:i().nullable(),email:i().nullable(),name:i().nullable(),handle:i().nullable(),image:i().nullable(),timezone:i().nullable(),isAdmin:A().nullable(),isVerified:A().nullable(),dailyAgentAppId:i().nullable(),dailyAgentDeploymentId:i().nullable(),credits:i().nullable()}),i$=c({handle:i(),baseUrl:i().nullable().optional()}),r$=c({state:b(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:i$.nullable(),label:i(),email:i().nullable(),avatarUrl:i().nullable(),environment:i().nullable(),baseUrl:i().nullable(),apiBaseUrl:i().nullable(),chatApiBaseUrl:i().nullable().optional().default(null),creditsLabel:i().nullable(),profile:o$.nullable(),products:p(n$),apiHealth:a$.nullable(),accounts:p(c({handle:i(),baseUrl:i().nullable(),apiBaseUrl:i().nullable().optional().default(null),chatApiBaseUrl:i().nullable().optional(),environment:i().nullable(),isActive:A(),authHealth:b(["signed_out","signed_in","auth_error","unknown"]),displayLabel:i().nullable(),email:i().nullable().optional().default(null),avatarUrl:i().nullable(),apiKeyHint:i().nullable().optional(),apiKeyAccess:c({ownerType:b(["user","team","organization","service"]).nullable(),teamId:i().nullable(),scopes:p(i())}).nullable().optional().default(null)})),error:i().nullable()}),Ny=c({asOf:i().nullable(),refreshing:A(),lastRefreshError:i().nullable(),source:b(["fresh","cache","empty"])}),s$=c({available:A(),binaryPath:i().nullable(),version:i().nullable(),authHealth:b(["unknown","signed_in","signed_out","auth_error"]),account:c({type:i(),email:i().nullable(),planType:i().nullable(),label:i().nullable()}).nullable().default(null),appServer:c({status:b(["idle","starting","ready","error"]),lastError:i().nullable()})}),wg="gpt-5.6-sol",ks="openpond-chat",ir="openpond",Fl=ks,Ig="default",_g="high",ju="ask",$s=pr,Cg=b(["default","auto-review","full-access"]),gc=b(["ask","full-access","disabled"]),Ou=b(["off","low","medium","high","xhigh","max"]),vc=b(["sandbox_app","local_project","sandbox","sandbox_template"]);b(["openpond"]);const l$=b(["provider_usage","provider_tokenizer","model_family","heuristic"]),c$=c({provider:$s,model:i().min(1),usedTokens:u().int().nonnegative(),maxContextTokens:u().int().positive(),usableContextTokens:u().int().positive(),percentFull:u().min(0).max(100),source:l$,updatedAtEventId:i().nullable()}),rh=c({pinned:A().default(!1),projects:A().default(!1),cloudProjects:A().default(!1),chats:A().default(!1),savedForLater:A().default(!0)}),d$=b(["auto","off"]),u$=b(["typescript","python","rust"]),i1=b(["auto","disabled","custom"]),No=c({mode:i1.default("auto"),customCommand:i().trim().max(4096).default("")}),Qd=c({languageServers:d$.default("auto"),diagnosticsWhileEditing:A().default(!0),checkOnSave:A().default(!0),languages:c({typescript:No.optional().default(()=>No.parse({})),python:No.optional().default(()=>No.parse({})),rust:No.optional().default(()=>No.parse({}))}).optional().default(()=>({typescript:No.parse({}),python:No.parse({}),rust:No.parse({})}))}),m$=c({language:u$,label:i(),mode:i1,status:b(["found","missing","disabled","error"]),command:i().nullable(),message:i().nullable()});c({settings:Qd,languages:p(m$),updatedAt:i()});const p$=c({id:i(),root:i(),status:b(["starting","connected","unavailable","error"]),message:i().nullable().optional().default(null),openedDocuments:u().int().nonnegative(),pendingRequests:u().int().nonnegative(),lastUsedAt:i(),stderrTail:i()});c({clients:p(p$),maxClients:u().int().positive(),idleTimeoutMs:u().int().positive(),updatedAt:i()});const sh=c({autoEnabled:A().default(!0),triggerPercent:u().int().min(50).max(95).default(85),summaryModel:b(["same_model"]).default("same_model")}),lh=c({defaultModelRef:un.nullable().default(null),creationMode:b(["defaults","customize"]).default("customize"),autoApproveEvidence:A().default(!1)}),Dy=c({defaultChatProvider:$s.default(ir),defaultChatModel:i().min(1).default(Fl),defaultChatModelRef:un.nullable().optional(),subagents:zl.optional().default(()=>zl.parse({})),codexPermissionMode:Cg.default(Ig),codexReasoningEffort:Ou.default(_g),openPondCommandAccessMode:gc.default(ju),defaultBranchPrefix:i().trim().max(48).default("feat/"),defaultNewProjectDirectory:i().trim().max(4096).default(""),defaultTeamId:i().trim().max(191).nullable().default(null),advancedWorkspaceControls:A().default(!1),steerActiveResponses:A().default(!0),contextCompaction:sh.optional().default(()=>sh.parse({})),training:lh.optional().default(()=>lh.parse({})),sidebarWidth:u().int().min(244).max(560).default(332),diffPanelWidth:u().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:rh.optional().default(()=>rh.parse({})),editor:Qd.optional().default(()=>Qd.parse({}))}),f$="default",r1=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
|
|
105
|
-
Be concise, accurate, and direct.
|
|
106
|
-
Do not use emojis.
|
|
107
|
-
Ask only when missing information would materially change the answer.
|
|
108
|
-
Prioritize practical next steps.`},{id:"pragmatic",name:"Pragmatic",source:"built_in",description:"Direct, practical, and engineering-minded.",content:`You are a pragmatic AI assistant with strong engineering judgment.
|
|
109
|
-
Be direct, concrete, and outcome-focused.
|
|
110
|
-
Do not use emojis.
|
|
111
|
-
Prefer simple working solutions over clever abstractions.
|
|
112
|
-
Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
|
|
113
|
-
Use a warm, conversational tone without filler.
|
|
114
|
-
Do not use emojis.
|
|
115
|
-
Explain decisions clearly and keep the user moving.
|
|
116
|
-
Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
|
|
117
|
-
Use precise, professional language.
|
|
118
|
-
Do not use emojis.
|
|
119
|
-
Structure answers clearly and avoid casual phrasing.
|
|
120
|
-
State uncertainty and assumptions explicitly.`},{id:"technical",name:"Technical",source:"built_in",description:"Precise, detailed, and implementation-focused.",content:`You are a technical AI assistant.
|
|
121
|
-
Prioritize correctness, implementation detail, and edge cases.
|
|
122
|
-
Do not use emojis.
|
|
123
|
-
Use concise explanations, but include necessary specifics.
|
|
124
|
-
Surface risks, constraints, and verification steps.`}],Rg=i().trim().min(1).max(120),h$=c({id:Rg,name:i(),source:b(["built_in","custom"]).default("custom"),description:i(),content:i()}),Ly=c({activeTemplateId:Rg.default(f$),customized:A().default(!1),soul:i(),soulPath:i().nullable(),updatedAt:i().nullable(),templates:p(h$).default(()=>[...r1])}),g$=c({id:i(),host:i(),port:u(),startedAt:i(),storePath:i(),version:i(),runtimeVersion:i()}),Pg=b(["chat","work","development"]);b(["chat","models","console","development"]);const v$="work",Ve=i().trim().min(1).nullable(),Na=oe(i(),se()).default({}),b$=b(["direct_prompt_create","context_backed_create","create_as_agent","workflow_suggestion","local_extend","hosted_create","local_import","direct_prompt_improve","context_backed_improve","hosted_improve","lab_create","lab_improve","training"]),s1=b(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),y$=b(["create","improve","import","promote"]),S$=b(["planning","awaiting_questions","awaiting_plan_approval","paused","applying_source","running_checks","evaluating","awaiting_promotion","opening_pull_request","pull_request_open","reconciling_release","released","rejected","ready","ready_local","pushing_hosted","running_hosted_checks","published_hosted","blocked","failed","cancelled"]),dd=b(["always_require_plan_approval","approval_already_granted"]);b(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const x$=vt("kind",[c({kind:S("local"),sourceAuthority:S("local_profile"),activeProfile:i().trim().min(1).nullable(),repoPath:Ve,sourcePath:Ve,localHead:Ve,confirmationPolicy:dd.default("always_require_plan_approval")}),c({kind:S("hosted"),sourceAuthority:S("hosted_profile"),teamId:Ve,projectId:Ve,activeProfile:i().trim().min(1).nullable(),sourceRef:Ve,baseSha:Ve,confirmationPolicy:dd.default("always_require_plan_approval")}),c({kind:S("promote_local_to_hosted"),sourceAuthority:S("promote_local_to_hosted"),teamId:Ve,projectId:Ve,activeProfile:i().trim().min(1).nullable(),repoPath:Ve,sourcePath:Ve,localHead:Ve,hostedHead:Ve,sourceRef:Ve,confirmationPolicy:dd.default("always_require_plan_approval")}),c({kind:S("managed_artifact"),sourceAuthority:S("managed_artifact"),activeProfile:i().trim().min(1).nullable(),confirmationPolicy:dd.default("always_require_plan_approval")})]),k$=c({id:Ve,kind:b(["user","system","automation"]).default("user"),label:Ve}),w$=c({profileId:i().trim().min(1),conversationId:Ve,originTurnId:Ve,projectId:Ve,targetProject:c({id:Ve,name:Ve,workspacePath:Ve,sourceRef:Ve,baseSha:Ve}).nullable()}),Il=c({messageIds:p(i().trim().min(1)).default([]),conversationExcerpts:p(c({messageId:Ve,role:i().trim().min(1).nullable(),excerpt:i().trim().min(1),reason:i().trim().min(1).nullable()})).default([]),attachments:p(c({id:Ve,name:i().trim().min(1),mediaType:Ve,ref:Ve})).default([]),apps:p(c({id:i().trim().min(1),name:i().trim().min(1),connectionId:Ve,required:A().default(!1)})).default([]),tools:p(c({name:i().trim().min(1),inputSummary:Ve,outputSummary:Ve,artifactRefs:p(i().trim().min(1)).default([]),sideEffects:p(i().trim().min(1)).default([])})).default([]),signalRefs:p(i().trim().min(1)).default([]),evalRefs:p(i().trim().min(1)).default([]),targetRepoAssumptions:p(i().trim().min(1)).default([])}),Kr={id:Ve,displayName:Ve},Ag=vt("kind",[c({kind:S("unselected"),...Kr}),c({kind:S("agent"),...Kr,defaultActionKey:Ve}),c({kind:S("skill"),...Kr,skillName:Ve}),c({kind:S("extension"),...Kr,slot:Ve}),c({kind:S("model"),...Kr,trainingPlanId:Ve,trainingJobId:Ve,artifactId:Ve}),c({kind:S("configuration"),...Kr,key:Ve})]),ch=b(["agent","skill","extension","model","configuration"]),I$=c({schemaVersion:S("openpond.createImprove.evidenceSnapshot.v1"),id:i().trim().min(1),contentHash:i().trim().min(8),consent:c({status:b(["granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Ve,reviewedAt:i().trim().min(1)}),sources:p(c({kind:b(["signal","conversation","direct_correction","manual_intent","artifact"]),id:i().trim().min(1),sourceHash:i().trim().min(8),excerptRef:Ve})).min(1),reviewerIntent:i().trim().min(1),createdAt:i().trim().min(1),metadata:Na}),l1=c({schemaVersion:S("openpond.createImprove.tasksetRef.v1"),id:i().trim().min(1),revision:u().int().positive(),contentHash:i().trim().min(8),evidenceSnapshotIds:p(i().trim().min(1)).min(1),policyBoundary:c({policyVisibleFields:p(i().trim().min(1)).default([]),privilegedFields:p(i().trim().min(1)).default([]),hiddenGraderRefs:p(i().trim().min(1)).default([]),connectedAppScopes:p(i().trim().min(1)).default([])}),targetRecommendation:c({kind:ch,rationale:p(i().trim().min(1)).min(1),confidence:u().min(0).max(1)}),authoringSplitRefs:p(i().trim().min(1)).default([]),privateSplitRefs:p(i().trim().min(1)).default([]),approvedBy:Ve,approvedAt:i().trim().min(1),metadata:Na}),_$=c({kind:b(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:i().trim().min(1),status:b(["declared","required","blocked","satisfied"]).default("declared"),detail:Ve,metadata:Na}),C$=c({mode:b(["chat","direct_action","chat_and_direct_actions"]),label:i().trim().min(1),detail:i().trim().min(1),defaultActionKey:Ve,directActionHint:Ve,artifactPolicy:i().trim().min(1)}),R$=c({schemaVersion:S("openpond.createImprove.plan.v1"),id:i().trim().min(1),runId:i().trim().min(1),status:b(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:i().trim().min(1),summary:i().trim().min(1),capturedContextSummary:i().trim().min(1),defaultChatAction:c({key:Ve,label:Ve,required:A().default(!0)}),sourcePlan:p(c({path:i().trim().min(1),operation:b(["create","update","delete","inspect"]),reason:i().trim().min(1)})).default([]),requirements:p(_$).default([]),checks:p(c({name:i().trim().min(1),command:i().trim().min(1),required:A().default(!0)})).default([]),approvalId:Ve,approvedAt:Ve,editedFromPlanId:Ve,metadata:Na,createdAt:i().trim().min(1),updatedAt:i().trim().min(1)}),P$=c({id:i().trim().min(1),label:i().trim().min(1),value:i().trim().min(1),description:Ve,metadata:Na}),A$=c({value:i().trim().min(1),label:Ve,detail:Ve,answeredAt:i().trim().min(1),metadata:Na}),T$=c({id:i().trim().min(1),kind:b(["single_choice","free_text"]).default("single_choice"),title:i().trim().min(1),prompt:i().trim().min(1),required:A().default(!0),status:b(["pending","answered","skipped"]).default("pending"),options:p(P$).default([]),answer:A$.nullable().default(null),metadata:Na}),E$=c({schemaVersion:S("openpond.createImprove.workflowCapture.v1"),id:i().trim().min(1),runId:i().trim().min(1),command:s1,objective:i().trim().min(1),conversationExcerpts:Il.shape.conversationExcerpts,attachments:Il.shape.attachments,apps:Il.shape.apps,tools:Il.shape.tools,sideEffects:p(i().trim().min(1)).default([]),profileActions:p(i().trim().min(1)).default([]),externalProviders:p(i().trim().min(1)).default([]),environmentVariables:p(i().trim().min(1)).default([]),files:p(i().trim().min(1)).default([]),schedules:p(i().trim().min(1)).default([]),webhooks:p(i().trim().min(1)).default([]),channelTargets:p(i().trim().min(1)).default([]),outputArtifacts:p(i().trim().min(1)).default([]),targetRepoAssumptions:p(i().trim().min(1)).default([]),traceRefs:p(i().trim().min(1)).default([]),metadata:Na,createdAt:i().trim().min(1)}),c1=c({provider:S("github"),number:u().int().positive(),url:i().url(),state:b(["open","merged","closed"]),baseBranch:i().trim().min(1),headBranch:i().trim().min(1),mergeCommit:Ve,openedAt:i().trim().min(1),updatedAt:i().trim().min(1)}),M$=c({baseBranch:i().trim().min(1),baseCommit:i().trim().min(1),branch:i().trim().min(1),headCommit:Ve,remoteName:i().trim().min(1).default("origin"),remoteUrl:Ve,worktreePath:Ve,changedPaths:p(i().trim().min(1)).default([]),diffStat:Ve,pullRequest:c1.nullable().default(null)}),j$=c({id:i().trim().min(1),target:Ag,status:b(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:M$.nullable().default(null),parentCandidateId:Ve.default(null),tasksetRef:l1.nullable().default(null),authoringModelRef:Ve.default(null),allowedPaths:p(i().trim().min(1)).default([]),sourceRefs:p(i().trim().min(1)).default([]),artifactRefs:p(i().trim().min(1)).default([]),checkRefs:p(i().trim().min(1)).default([]),evaluationReceiptRefs:p(i().trim().min(1)).default([]),createdAt:i().trim().min(1),updatedAt:i().trim().min(1),metadata:Na}),O$=c({id:i().trim().min(1),candidateId:Ve,target:Ag,evaluatorKind:b(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:b(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Ve.default(null),sourceBranch:Ve.default(null),tasksetId:Ve.default(null),tasksetHash:Ve.default(null),taskAttemptRefs:p(i().trim().min(1)).default([]),status:b(["pending","passed","failed","blocked"]),publishGate:b(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:c({total:u().int().nonnegative(),passed:u().int().nonnegative(),failed:u().int().nonnegative()}).nullable().default(null),evalRefs:p(i().trim().min(1)).default([]),artifactRefs:p(i().trim().min(1)).default([]),summary:Ve,createdAt:i().trim().min(1),metadata:Na}),$$=c({mode:b(["foreground","background"]).default("background"),pauseAllowed:A().default(!0),cancellationAllowed:A().default(!0)}),N$=c({mode:b(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:u().int().min(1).max(20).default(1),currentAttempt:u().int().min(0).max(20).default(0)}),D$=c({kind:b(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:i().trim().min(1),status:Ve,metadata:Na}),L$=c({status:b(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ve,profileTag:Ve,releaseReceiptRef:Ve,pullRequest:c1.nullable().default(null),updatedAt:Ve}),bc=c({schemaVersion:S("openpond.createImprove.run.v1"),id:i().trim().min(1),revision:u().int().nonnegative(),operation:y$,surface:b$,command:s1,objective:i().trim().min(1),state:S$,adapter:x$,actor:k$,scope:w$,context:Il,target:Ag,evidenceSnapshots:p(I$).default([]),tasksetRef:l1.nullable().default(null),targetSelection:c({status:b(["open","recommended","confirmed"]),preselectedKind:ch.nullable(),confirmedKind:ch.nullable()}).nullable().default(null),plan:R$.nullable(),workflowCapture:E$.nullable(),executionPolicy:$$.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:N$.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:p(i().trim().min(1)).default([]),questionIds:p(i().trim().min(1)).default([]),questions:p(T$).default([]),candidates:p(j$).default([]),evaluationReceipts:p(O$).default([]),checkRefs:p(i().trim().min(1)).default([]),sourceRefs:p(i().trim().min(1)).default([]),externalExecutionRefs:p(D$).default([]),localProfileCommit:Ve,hostedSourceCommit:Ve,hostedSourceRef:Ve,releaseOutcome:L$.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Ve,appliedActionIds:p(i().trim().min(1)).max(200).default([]),metadata:Na,createdAt:i().trim().min(1),updatedAt:i().trim().min(1)}),mo={runId:i().trim().min(1),expectedRevision:u().int().nonnegative(),actionId:i().trim().min(1)};vt("type",[c({...mo,type:S("answer_question"),questionId:i().trim().min(1),value:i().trim().min(1)}),c({...mo,type:S("approve_plan")}),c({...mo,type:S("revise_plan"),revision:i().trim().min(1)}),c({...mo,type:S("cancel"),reason:Ve.optional().default(null)}),c({...mo,type:S("pause")}),c({...mo,type:S("resume")}),c({...mo,type:S("open_pull_request"),candidateId:i().trim().min(1)}),c({...mo,type:S("apply_candidate"),candidateId:i().trim().min(1)}),c({...mo,type:S("reject_candidate"),candidateId:i().trim().min(1),reason:Ve.optional().default(null)}),c({...mo,type:S("reconcile_pull_request"),candidateId:i().trim().min(1)})]);c({schemaVersion:S("openpond.createImprove.runList.v1"),runs:p(bc),generatedAt:i().trim().min(1)});function HX(e){const t=C$.safeParse(e?.actionShape);return t.success?t.data:null}const Co=c({source:b(["local","github","openpond_git"]),repositoryId:i().trim().min(1),profileId:i().trim().min(1)}),H$=c({ref:Co,revision:i().nullable(),sourceHash:i()}),Ns=oe(i(),se()).default({}),Pa=u().int().nonnegative(),$u=i().trim().min(1).max(1e5),d1=c({kind:b(["personal","team"]),id:T}).strict(),U$=c({name:T,release:G.nullable(),revision:Pa}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:T,ownerScope:d1,name:i().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:i().trim().min(1).max(500),revision:Pa,dirty:A(),currentChannel:U$,createdAt:Ce,updatedAt:Ce,metadata:Ns}).strict();const ws=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),u1=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),m1=c({id:T,route:ws,operation:b(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),content:i().max(1e6).nullable(),contentHash:F.nullable(),effects:p(u1).min(1).max(20)}).strict().superRefine((e,t)=>{if(e.operation==="delete"){(e.content!==null||e.contentHash!==null)&&t.addIssue({code:"custom",message:"delete edits cannot include replacement content",path:["content"]});return}if(e.content===null||e.contentHash===null){t.addIssue({code:"custom",message:"create and update edits require content and contentHash",path:["content"]});return}const n=_t(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),p1=c({workspaceId:T,revision:Pa,sourceRevision:i().trim().min(1).max(500),channelRevision:Pa}).strict(),Ko=c({id:T,revision:Pa,contentHash:F}).strict(),q$=c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:T,workspaceRevision:Pa,sourceRevision:i().trim().min(1).max(500),channelName:T,channelRevision:Pa,harnessRelease:G,toolCatalogHash:F.nullable().optional(),overlay:Ko.nullable().optional().default(null)}).strict(),z$=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:T,runId:T,baseHarnessRelease:G,workspace:p1,revision:Pa,status:b(["active","frozen","abandoned"]),edits:p(m1).max(1e3),createdAt:Ce,updatedAt:Ce,metadata:Ns}).strict();z$.extend({contentHash:F}).strict();const f1=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:T,contentHash:F.nullable()}).strict(),h1=c({id:T,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:$u,required:A()}).strict(),B$=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:T,overlay:Ko,baseHarnessRelease:G,expectedWorkspace:p1,requestedScope:b(["personal","team","global"]),route:ws,risk:b(["low","review","restricted"]),effects:p(u1).min(1).max(20),evidence:p(f1).min(1).max(1e3),edits:p(m1).min(1).max(1e3),validationPlan:p(h1).min(1).max(100),expectedOutcome:$u,createdAt:Ce,metadata:Ns}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,o]of e.edits.entries()){o.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const r of o.effects)n.has(r)||t.addIssue({code:"custom",message:`edit effect ${r} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});B$.extend({contentHash:F}).strict();const F$=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:T,proposal:G,validationId:T,kind:h1.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:$u,evidenceRefs:p(f1).max(1e3),createdAt:Ce,metadata:Ns}).strict();F$.extend({contentHash:F}).strict();const V$=b(["advanced","retained","conflict","rolled_back"]),K$=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:T,workspaceId:T,ownerScope:d1,proposal:G.nullable(),expectedWorkspaceRevision:Pa,observedWorkspaceRevision:Pa,previousChannelRevision:Pa,nextChannelRevision:Pa,previousRelease:G.nullable(),nextRelease:G.nullable(),validationReceipts:p(G).max(100),decision:V$,reason:$u,rollbackOf:G.nullable(),createdAt:Ce,metadata:Ns}).strict().superRefine((e,t)=>{const n=e.nextChannelRevision===e.previousChannelRevision+1;["advanced","rolled_back"].includes(e.decision)!==n&&t.addIssue({code:"custom",message:"only successful advancement or rollback increments the channel revision",path:["nextChannelRevision"]}),e.decision==="rolled_back"&&e.rollbackOf===null&&t.addIssue({code:"custom",message:"rollback receipts require rollbackOf",path:["rollbackOf"]}),e.decision!=="rolled_back"&&e.rollbackOf!==null&&t.addIssue({code:"custom",message:"rollbackOf is only valid for rollback receipts",path:["rollbackOf"]})});K$.extend({contentHash:F}).strict();const W$=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:T,workspaceId:T,baseHarnessRelease:G,leftOverlay:Ko,rightOverlay:Ko,decision:b(["merged","conflict"]),mergedOverlay:Ko.nullable(),conflictTargets:p(i().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:Ce,metadata:Ns}).strict().superRefine((e,t)=>{e.decision==="merged"!=(e.mergedOverlay!==null)&&t.addIssue({code:"custom",message:"merged decisions require a merged overlay; conflicts cannot provide one",path:["mergedOverlay"]}),e.decision==="conflict"!=e.conflictTargets.length>0&&t.addIssue({code:"custom",message:"conflict decisions require conflict targets and merged decisions cannot include them",path:["conflictTargets"]})});W$.extend({contentHash:F}).strict();const Wo=i().trim().min(1).max(1e5),G$=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),J$=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),g1=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Tg=c({kind:b(["personal","team"]),id:T}).strict(),v1=c({policy:G,state:b(["authorized","revoked","deleted","expired"]),checkedAt:Ce}).strict(),Vl=c({evidence:G,kind:g1,sourceRef:T,sourcePolicy:v1,occurrenceKey:F,occurredAt:Ce}).strict(),Z$=c({evidence:G,sourcePolicy:v1.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),Hy=c({cursor:F,throughCreatedAt:Ce}).strict(),Y$=c({fingerprint:F,recurrenceFamily:i().trim().min(1).max(1e3),statement:Wo,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),b1=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),Q$=c({layer:b1,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:Wo,evidenceRefs:p(G).max(1e3)}).strict(),X$=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:T,ownerScope:Tg,workspaceRef:T,harnessRelease:G,previousWatermark:Hy.nullable(),nextWatermark:Hy,selectedEvidence:p(Vl).max(1e4),excludedEvidence:p(Z$).max(1e4),claim:Y$.nullable(),classification:G$,triage:p(Q$).max(16),reason:Wo,nextAuthority:J$,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:G.nullable(),evaluation:G.nullable(),trainingQualification:G.nullable(),policyVersion:T,createdAt:Ce,metadata:_n}).strict().superRefine((e,t)=>{const n=e.selectedEvidence.map(a=>`${a.evidence.id}:${a.evidence.contentHash}`);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"selected review evidence must be unique",path:["selectedEvidence"]}),e.selectedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"selected review evidence must be authorized at review time",path:["selectedEvidence"]}),e.classification==="no_action"?(e.nextAuthority!=="none"&&t.addIssue({code:"custom",message:"no-action review receipts require no next authority",path:["nextAuthority"]}),(e.tasksetProposal||e.evaluation||e.trainingQualification)&&t.addIssue({code:"custom",message:"no-action review receipts cannot carry downstream refs"})):(!e.claim||e.selectedEvidence.length===0)&&t.addIssue({code:"custom",message:"actionable review receipts require a claim and selected evidence"}),e.classification==="runtime"&&e.nextAuthority!=="runtime_service"&&t.addIssue({code:"custom",message:"runtime classifications route to runtime-service authority",path:["nextAuthority"]}),e.classification==="product"&&e.nextAuthority!=="product_team"&&t.addIssue({code:"custom",message:"product classifications route to product-team authority",path:["nextAuthority"]}),e.classification==="taskset"&&e.nextAuthority!=="human_review"&&t.addIssue({code:"custom",message:"Taskset classifications require human review"}),e.classification==="model_improvement"&&(!e.evaluation||!e.trainingQualification||!["human_review","training_system"].includes(e.nextAuthority))&&t.addIssue({code:"custom",message:"model-improvement classifications require Evaluation and qualification refs plus explicit authority"})});X$.extend({contentHash:F}).strict();c({id:T,evidence:G,kind:g1,sourceRef:T,occurredAt:Ce,payload:oe(i(),se())}).strict();const eN=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Wo,ignoredEvidence:p(c({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),tN=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(c({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:i().trim().min(1).max(1e3),statement:Wo,triageLayer:b1,expectedOutcome:Wo,counterevidence:i().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:Wo}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),nN=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:T,candidateFingerprint:F,selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(c({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:Wo}).strict();vt("decision",[eN,tN,nN]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(T).min(1).max(50),reason:Wo}).strict();const yc=c({name:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(2e3),inputSchema:oe(i(),se()),inputSchemaHash:F,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),Eg=c({id:T,required:A(),scopes:p(i().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),aN=c({portable:A(),blockers:p(i().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(T).max(1e4),hostPrivateAssetRefs:p(T).max(1e4)}).strict(),oN=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:T,sourceRelease:G.nullable(),instructions:p(cn).max(1e4),skills:p(cn).max(1e4),agents:p(cn).max(1e4),toolDeclarations:p(yc).max(200),capabilityRequirements:p(Eg).max(200),dependencyLock:cn,portability:aN,metadata:_n}).strict(),iN=oN.extend({contentHash:F}).strict(),y1=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),S1=c({visibleEvidence:p(T).max(1e3),privilegedEvidence:p(T).max(1e3),privateVerifierIsolation:A()}).strict(),rN=c({schemaVersion:S("openpond.harnessRelease.v2"),id:T,agentSnapshot:G,program:cn,tools:p(yc).max(200),lifecycle:y1,graderInterface:S1,files:p(cn).max(1e5),metadata:_n}).strict(),sN=rN.extend({contentHash:F}).strict(),lN=c({id:T,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:T.nullable(),arguments:oe(i(),se()),content:i().max(1e6).nullable()}).strict(),cN=c({actionId:T,turn:u().int().nonnegative(),terminal:A(),output:oe(i(),se()),artifactRefs:p(ha).max(1e5)}).strict(),dN=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:F,metadata:_n}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:G,taskId:T,seed:i().trim().min(1).max(500),events:p(dN).max(1e6),actions:p(lN).max(1e5),observations:p(cN).max(1e5),terminal:A(),failureClass:pc.nullable(),output:oe(i(),se()),contentHash:F}).strict();const Nu=i().trim().min(1).max(1e5),Sc=oe(i(),se()).default({}),uN=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),x1=c({kind:uN,eventSequence:u().int().nonnegative(),occurredAt:Ce}).strict(),k1=c({id:T,sequence:u().int().nonnegative().nullable(),contentHash:F}).strict(),mN=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),pN=b(["open","recovered","terminal"]),fN=c({name:i().trim().min(1).max(500),invocationKey:F}).strict(),hN=c({schemaVersion:S("openpond.improvementObservation.v1"),id:T,runRef:T,turnId:T,harnessRelease:G,overlay:Ko.nullable(),eventRefs:p(k1).min(1).max(100),kind:mN,state:pN,tool:fN.nullable(),deterministicClass:i().trim().min(1).max(500).nullable(),summary:Nu,createdAt:Ce,metadata:Sc}).strict().superRefine((e,t)=>{new Set(e.eventRefs.map(n=>n.id)).size!==e.eventRefs.length&&t.addIssue({code:"custom",message:"observation event refs must be unique",path:["eventRefs"]}),["tool_failure","retry","recovery","completion_detour"].includes(e.kind)&&e.tool===null&&t.addIssue({code:"custom",message:`${e.kind} observations require a tool identity`,path:["tool"]})});hN.extend({contentHash:F}).strict();const gN=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:u().finite().nonnegative(),cooldownMs:u().int().nonnegative(),maxPendingPlans:u().int().min(1).max(100),maxEvidenceEvents:u().int().min(1).max(1e3),maxProposalEdits:u().int().min(1).max(1e3),maxProposalBytes:u().int().min(1).max(1e7)}).strict(),vN=b(["no_action","route_deterministically","queue_refiner"]),bN=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:T,runRef:T,turnId:T,harnessRelease:G,overlay:Ko.nullable(),observations:p(G).max(100),decision:vN,deterministicRoute:ws.nullable(),suggestedRoutes:p(ws).max(8),reason:Nu,deduplicationKey:F,policy:gN,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:x1,cooldownUntil:Ce.nullable(),createdAt:Ce,metadata:Sc}).strict().superRefine((e,t)=>{e.estimatedMaxCostUsd>e.policy.maxEstimatedCostUsd&&t.addIssue({code:"custom",message:"estimated Refiner cost exceeds the trigger policy budget",path:["estimatedMaxCostUsd"]}),e.pendingPlanCount>e.policy.maxPendingPlans&&t.addIssue({code:"custom",message:"pending plan count exceeds the trigger policy limit",path:["pendingPlanCount"]}),e.observations.length>e.policy.maxEvidenceEvents&&t.addIssue({code:"custom",message:"trigger observations exceed the evidence budget",path:["observations"]}),e.decision==="route_deterministically"&&e.deterministicRoute===null&&t.addIssue({code:"custom",message:"deterministic decisions require a route",path:["deterministicRoute"]}),e.decision!=="route_deterministically"&&e.deterministicRoute!==null&&t.addIssue({code:"custom",message:"only deterministic decisions may declare a deterministic route",path:["deterministicRoute"]}),e.decision==="no_action"&&e.suggestedRoutes.length>0&&t.addIssue({code:"custom",message:"no-action decisions cannot suggest routes",path:["suggestedRoutes"]}),e.decision!=="no_action"&&e.observations.length===0&&t.addIssue({code:"custom",message:"actionable trigger decisions require observations",path:["observations"]})});bN.extend({contentHash:F}).strict();const yN=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),SN=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:T,trigger:G,route:ws,authority:yN,automatic:A(),reason:Nu,createdAt:Ce,metadata:Sc}).strict().superRefine((e,t)=>{e.automatic&&["human_review","evaluation_system","training_system"].includes(e.authority)&&t.addIssue({code:"custom",message:`${e.authority} routes cannot be marked automatic`,path:["automatic"]}),e.route==="training"&&e.automatic&&e.authority!=="training_system"&&t.addIssue({code:"custom",message:"automatic training routes require training-system authority",path:["authority"]})});SN.extend({contentHash:F}).strict();const xN=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:T,trigger:G,decision:b(["no_action","proposed"]),proposal:G.nullable(),reason:Nu,evidenceRefs:p(G).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:Ce,metadata:Sc}).strict().superRefine((e,t)=>{e.decision==="proposed"!=(e.proposal!==null)&&t.addIssue({code:"custom",message:"proposed Refiner outcomes require a proposal; no-action outcomes cannot include one",path:["proposal"]})});xN.extend({contentHash:F}).strict();const kN=b(["applied","retained","declined","conflict","rolled_back"]),wN=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:T,proposal:G,beforeOverlay:Ko,afterOverlay:Ko.nullable(),decision:kN,boundary:x1,validationRefs:p(G).max(100),outcomeEvidenceRefs:p(k1).max(1e3),rollbackOf:G.nullable(),createdAt:Ce,metadata:Sc}).strict().superRefine((e,t)=>{e.decision==="applied"!=(e.afterOverlay!==null)&&t.addIssue({code:"custom",message:"applied receipts require an after-overlay; other decisions cannot include one",path:["afterOverlay"]}),e.decision==="rolled_back"!=(e.rollbackOf!==null)&&t.addIssue({code:"custom",message:"only rollback receipts require rollbackOf",path:["rollbackOf"]})});wN.extend({contentHash:F}).strict();const IN=b(["memory","prompt","skill","agent"]),_N=b(["runtime","product","taskset","training"]),CN=c({id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:i().trim().min(1).max(1e4)}).strict(),w1=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:i().trim().min(1).max(120),name:i().trim().min(1).max(200),objective:i().trim().min(1).max(1e4),instructions:p(CN).max(100),allowedProposalRoutes:p(IN).max(4),allowedExternalRoutes:p(_N).max(4)}).strict().superRefine((e,t)=>{const n=e.instructions.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"instruction IDs must be unique",path:["instructions"]}),new Set(e.allowedProposalRoutes).size!==e.allowedProposalRoutes.length&&t.addIssue({code:"custom",message:"proposal routes must be unique",path:["allowedProposalRoutes"]}),new Set(e.allowedExternalRoutes).size!==e.allowedExternalRoutes.length&&t.addIssue({code:"custom",message:"external routes must be unique",path:["allowedExternalRoutes"]})}),Uy=c({schemaVersion:S("openpond.refinerRelease.v1"),id:i().trim().min(1).max(240),coreVersion:i().trim().min(1).max(120),coreHash:F,profile:w1,profileHash:F,composedPromptHash:F,createdAt:Ce,contentHash:F}).strict(),RN=c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:G,updatedAt:Ce}).strict(),PN=c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:i().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:G.nullable(),nextRelease:G,actor:i().trim().min(1).max(240),reason:i().trim().min(1).max(1e4),authoringSkillHash:F.nullable(),validation:c({valid:A(),messages:p(i().max(2e3)).max(100)}).strict(),createdAt:Ce,contentHash:F}).strict(),AN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:i().trim().min(1).max(1e4)}).strip(),TN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strip(),EN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),createContent:i().min(1).max(2e4).nullable(),find:i().min(1).max(8e3).nullable(),replace:i().max(8e3).nullable(),expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),MN=vt("decision",[AN,TN,EN]),jN=MN,Mg=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(i().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(i().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),ON=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:i().trim().min(1).max(1e4)}).strict(),$N=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),evidenceBasis:Mg,expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strict(),NN=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),evidenceBasis:Mg,createContent:i().min(1).max(2e4).nullable(),find:i().min(1).max(8e3).nullable(),replace:i().max(8e3).nullable(),expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),I1=vt("decision",[ON,$N,NN]);Tt([jN,I1]);const jg=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),_1=b(["memory","instruction","skill","agent"]),qy=c({path:i().trim().min(1).max(2e3),kind:_1,content:i().max(6e4),loaded:A()}).strict(),zy=c({path:i().trim().min(1).max(2e3),kind:_1,loaded:A()}).strict(),DN=c({capabilities:jg,trigger:oe(i(),se()),observations:p(oe(i(),se())).max(20),admissibleEvidenceIds:p(i().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:i().trim().min(1).max(2e3),status:i().trim().min(1).max(100).nullable(),error:i().max(2100).nullable(),prompt:i().max(8100).nullable(),assistantOutput:i().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:p(c({turnId:i().trim().min(1).max(2e3),status:i().trim().min(1).max(100).nullable(),prompt:i().max(3100).nullable(),assistantOutput:i().max(3100).nullable()}).strict()).max(3),timeline:p(oe(i(),se())).max(60),artifacts:p(oe(i(),se())).max(30),artifactDiagnostics:p(oe(i(),se())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:p(oe(i(),se())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:G,currentRelease:G,rebasedOntoCurrent:A(),admittedSourceFiles:p(qy).max(100),admittedSourceCatalog:p(zy).max(1e3)}).strict(),sourceFiles:p(qy).max(100),sourceCatalog:p(zy).max(1e3),additionalEvidence:se().nullable().optional()}).strict(),LN=c({id:i().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:F}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:i().trim().min(1).max(240),idempotencyKey:i().trim().min(1).max(240),evidenceHash:F,harness:c({admittedRelease:G,currentRelease:G,overlay:LN,workspace:c({id:i().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:F,channelRevision:u().int().nonnegative()}).strict(),capabilities:jg}).strict(),evidence:DN}).strict();const HN=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:i().trim().min(1).max(240),evidenceHash:F,admittedRelease:G,currentRelease:G,decision:I1,serviceRevision:i().trim().min(1).max(240),usage:HN}).strict();const UN=i().trim().min(1).max(2e3),Og=i().trim().min(1).max(1e5),qN=b(["create","update","delete"]),zN=b(["memory","prompt","skill","agent"]),BN=b(["runtime","product","taskset","training"]),FN=b(["no_action","routed","applied","retained","failed"]),VN=b(["not_applicable","pending","passed","rejected","failed"]),KN=b(["not_applicable","pending","passed","failed"]),WN=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:T,runRef:T,turnId:T,result:FN,decision:b(["no_action","route","propose"]).nullable(),route:ws.nullable(),operation:qN.nullable(),target:i().trim().min(1).max(2e3).nullable(),summary:UN,evidenceBasis:Mg.nullable(),critiqueStatus:VN,validationStatus:KN,trigger:G,outcome:G.nullable(),proposal:G.nullable(),applyReceipt:G.nullable(),inputHarness:G,outputHarness:G.nullable(),createdAt:Ce}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?By(t,e,{decision:"no_action",route:null,operation:null,target:null,evidenceBasis:null,proposal:null,applyReceipt:null,outputHarness:null,critiqueStatus:"not_applicable",validationStatus:"not_applicable"}):e.result==="routed"?((e.decision!=="route"||!BN.safeParse(e.route).success||e.operation!==null||e.target!==null||e.evidenceBasis===null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"routed activity requires an external route and evidence basis without proposal state"}),By(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!zN.safeParse(e.route).success||e.operation===null||e.target===null||e.evidenceBasis===null||e.proposal===null||e.applyReceipt===null)&&t.addIssue({code:"custom",message:"applied and retained activity requires complete proposal state"}),e.result==="applied"&&e.outputHarness===null&&t.addIssue({code:"custom",message:"applied activity requires the advanced Harness release",path:["outputHarness"]}),e.result==="applied"&&(e.critiqueStatus!=="passed"||e.validationStatus!=="passed")&&t.addIssue({code:"custom",message:"applied activity requires passed critique and validation"}),e.result==="retained"&&e.outputHarness!==null&&t.addIssue({code:"custom",message:"retained activity cannot report a new Harness release",path:["outputHarness"]})):(e.decision!==null||e.route!==null||e.operation!==null||e.target!==null||e.evidenceBasis!==null||e.outcome!==null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"failed activity cannot claim a decision, route, proposal, or release transition"}),e.result!=="failed"&&e.outcome===null&&t.addIssue({code:"custom",message:"terminal Refiner decisions require an outcome reference",path:["outcome"]})});WN.extend({contentHash:F}).strict();const GN=b(["unresolved","confirmed","resolved","rejected","expired"]),JN=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Og,evidenceRefs:p(G).max(1e3),resolvedAt:Ce}).strict(),ZN=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:T,ownerScope:Tg,workspaceRef:T,fingerprint:F,recurrenceFamily:i().trim().min(1).max(1e3),statement:Og,status:GN,occurrences:p(Vl).max(1e3),counterevidence:p(Vl).max(1e3),sourceReviews:p(G).min(1).max(100),relatedHarnessReleases:p(G).max(100),firstSeenAt:Ce,lastSeenAt:Ce,lastReviewedAt:Ce,expiresAt:Ce,resolution:JN.nullable(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{Yi(t,e.occurrences,"occurrences"),Yi(t,e.counterevidence,"counterevidence"),Yi(t,e.sourceReviews,"sourceReviews"),Yi(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(o=>o.occurrenceKey));e.counterevidence.some(o=>n.has(o.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(o=>o.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),tD(t,e)});ZN.extend({contentHash:F}).strict();const YN=b(["created","merged","rejected","expired","reopened","resolved"]),QN=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:T,candidateId:T,decision:YN,beforeCandidate:G.nullable(),afterCandidate:G,review:G,addedEvidence:p(Vl).max(1e3),removedEvidence:p(G).max(1e3),reason:Og,createdAt:Ce}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),Yi(t,e.addedEvidence,"addedEvidence"),Yi(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>dh(a)));e.addedEvidence.some(a=>n.has(dh(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});QN.extend({contentHash:F}).strict();const XN=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:T,ownerScope:Tg,workspaceRef:T,candidate:G,candidateFingerprint:F,review:G,admittedHarness:G,evidence:p(Vl).min(1).max(1e3),capabilities:jg,deduplicationKey:F,createdAt:Ce}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),Yi(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=eD(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});XN.extend({contentHash:F}).strict();function eD(e){return _t({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function By(e,t,n){for(const[a,o]of Object.entries(n))t[a]!==o&&e.addIssue({code:"custom",message:`${a} must be ${String(o)}`,path:[a]})}function Yi(e,t,n){const a=t.map(o=>dh(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function dh(e){if(!e||typeof e!="object"||Array.isArray(e))return String(e);const t=e;if(typeof t.occurrenceKey=="string")return t.occurrenceKey;const n=t.evidence;if(n&&typeof n=="object"&&!Array.isArray(n)){const a=n;return`${String(a.id)}:${String(a.contentHash)}`}return`${String(t.id)}:${String(t.contentHash)}`}function tD(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const o=n[a-1],r=n[a];Date.parse(o[1])<=Date.parse(r[1])||e.addIssue({code:"custom",message:`${r[0]} must not precede ${o[0]}`,path:[r[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}const nD=25*1024*1024,aD=c({path:cn.shape.path,base64:i().max(Math.ceil(nD/3)*4)}).strict(),C1=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:iN,harnessRelease:sN,files:p(aD).max(1e4)}).strict();C1.extend({contentHash:F}).strict();C1.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:F}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:G,sourcePackageHash:F.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});c({path:i().min(1).max(2e3),offset:u().int().nonnegative().default(0),length:u().int().positive().max(65536).default(16384)}).strict();const R1=i().regex(/^[a-z][a-z0-9_-]{0,119}$/),P1=i().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"workflow references require portable relative paths"),oD=c({id:R1,label:i().trim().min(1).max(240),description:i().max(4e3),inputSchema:oe(i(),se()),invocation:vt("kind",[c({kind:S("instructions"),instructions:i().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:S("agent_action"),actionId:i().trim().min(1).max(240)}).strict()]),skillPaths:p(P1).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:p(oD).max(1e3)}).strict();const iD=c({id:i().trim().min(1).max(240),agentId:i().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:i().trim().min(1).max(240),inputSchema:oe(i(),se())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:p(iD).max(200)}).strict();const rD=c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:G,catalogHash:F,workflowId:R1}).strict(),sD=c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:G,target:vt("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:P1}).strict(),c({kind:S("agent_action"),actionId:i().trim().min(1).max(240)}).strict()])}).strict(),$g=Symbol.for("yaml.alias"),lD=Symbol.for("yaml.document"),ar=Symbol.for("yaml.map"),A1=Symbol.for("yaml.pair"),Ng=Symbol.for("yaml.scalar"),xc=Symbol.for("yaml.seq"),Ro=Symbol.for("yaml.node.type"),Ds=e=>!!e&&typeof e=="object"&&e[Ro]===$g,Du=e=>!!e&&typeof e=="object"&&e[Ro]===lD,T1=e=>!!e&&typeof e=="object"&&e[Ro]===ar,On=e=>!!e&&typeof e=="object"&&e[Ro]===A1,In=e=>!!e&&typeof e=="object"&&e[Ro]===Ng,Dg=e=>!!e&&typeof e=="object"&&e[Ro]===xc;function ma(e){if(e&&typeof e=="object")switch(e[Ro]){case ar:case xc:return!0}return!1}function Hn(e){if(e&&typeof e=="object")switch(e[Ro]){case $g:case ar:case Ng:case xc:return!0}return!1}const E1=e=>(In(e)||ma(e))&&!!e.anchor,Wi=Symbol("break visit"),cD=Symbol("skip children"),Ml=Symbol("remove node");function Lu(e,t){const n=dD(t);Du(e)?ns(null,e.contents,n,Object.freeze([e]))===Ml&&(e.contents=null):ns(null,e,n,Object.freeze([]))}Lu.BREAK=Wi;Lu.SKIP=cD;Lu.REMOVE=Ml;function ns(e,t,n,a){const o=uD(e,t,n,a);if(Hn(o)||On(o))return mD(e,a,o),ns(e,o,n,a);if(typeof o!="symbol"){if(ma(t)){a=Object.freeze(a.concat(t));for(let r=0;r<t.items.length;++r){const s=ns(r,t.items[r],n,a);if(typeof s=="number")r=s-1;else{if(s===Wi)return Wi;s===Ml&&(t.items.splice(r,1),r-=1)}}}else if(On(t)){a=Object.freeze(a.concat(t));const r=ns("key",t.key,n,a);if(r===Wi)return Wi;r===Ml&&(t.key=null);const s=ns("value",t.value,n,a);if(s===Wi)return Wi;s===Ml&&(t.value=null)}}return o}function dD(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function uD(e,t,n,a){if(typeof n=="function")return n(e,t,a);if(T1(t))return n.Map?.(e,t,a);if(Dg(t))return n.Seq?.(e,t,a);if(On(t))return n.Pair?.(e,t,a);if(In(t))return n.Scalar?.(e,t,a);if(Ds(t))return n.Alias?.(e,t,a)}function mD(e,t,n){const a=t[t.length-1];if(ma(a))a.items[e]=n;else if(On(a))e==="key"?a.key=n:a.value=n;else if(Du(a))a.contents=n;else{const o=Ds(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}function M1(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function _l(e,t,n,a){if(a&&typeof a=="object")if(Array.isArray(a))for(let o=0,r=a.length;o<r;++o){const s=a[o],l=_l(e,a,String(o),s);l===void 0?delete a[o]:l!==s&&(a[o]=l)}else if(a instanceof Map)for(const o of Array.from(a.keys())){const r=a.get(o),s=_l(e,a,o,r);s===void 0?a.delete(o):s!==r&&a.set(o,s)}else if(a instanceof Set)for(const o of Array.from(a)){const r=_l(e,a,o,o);r===void 0?a.delete(o):r!==o&&(a.delete(o),a.add(r))}else for(const[o,r]of Object.entries(a)){const s=_l(e,a,o,r);s===void 0?delete a[o]:s!==r&&(a[o]=s)}return e.call(t,n,a)}function Ya(e,t,n){if(Array.isArray(e))return e.map((a,o)=>Ya(a,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!E1(e))return e.toJSON(t,n);const a={aliasCount:0,count:1,res:void 0};n.anchors.set(e,a),n.onCreate=r=>{a.res=r,delete n.onCreate};const o=e.toJSON(t,n);return n.onCreate&&n.onCreate(o),o}return typeof e=="bigint"&&!n?.keep?Number(e):e}class Lg{constructor(t){Object.defineProperty(this,Ro,{value:t})}clone(){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:a,onAnchor:o,reviver:r}={}){if(!Du(t))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof a=="number"?a:100},l=Ya(this,"",s);if(typeof o=="function")for(const{count:m,res:d}of s.anchors.values())o(d,m);return typeof r=="function"?_l(r,{"":l},"",l):l}}class pD extends Lg{constructor(t){super($g),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let a;n?.aliasResolveCache?a=n.aliasResolveCache:(a=[],Lu(t,{Node:(r,s)=>{(Ds(s)||E1(s))&&a.push(s)}}),n&&(n.aliasResolveCache=a));let o;for(const r of a){if(r===this)break;r.anchor===this.source&&(o=r)}return o}toJSON(t,n){if(!n)return{source:this.source};const{anchors:a,doc:o,maxAliasCount:r}=n,s=this.resolve(o,n);if(!s){const m=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(m)}let l=a.get(s);if(l||(Ya(s,null,n),l=a.get(s)),l?.res===void 0){const m="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(m)}if(r>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=Td(o,s,a)),l.count*l.aliasCount>r)){const m="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(m)}return l.res}toString(t,n,a){const o=`*${this.source}`;if(t){if(M1(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(t.implicitKey)return`${o} `}return o}}function Td(e,t,n){if(Ds(t)){const a=t.resolve(e),o=n&&a&&n.get(a);return o?o.count*o.aliasCount:0}else if(ma(t)){let a=0;for(const o of t.items){const r=Td(e,o,n);r>a&&(a=r)}return a}else if(On(t)){const a=Td(e,t.key,n),o=Td(e,t.value,n);return Math.max(a,o)}return 1}const j1=e=>!e||typeof e!="function"&&typeof e!="object";class an extends Lg{constructor(t){super(Ng),this.value=t}toJSON(t,n){return n?.keep?this.value:Ya(this.value,t,n)}toString(){return String(this.value)}}an.BLOCK_FOLDED="BLOCK_FOLDED";an.BLOCK_LITERAL="BLOCK_LITERAL";an.PLAIN="PLAIN";an.QUOTE_DOUBLE="QUOTE_DOUBLE";an.QUOTE_SINGLE="QUOTE_SINGLE";function fD(e,t,n){return n.find(a=>a.identify?.(e)&&!a.format)}function Xd(e,t,n){if(Du(e)&&(e=e.contents),Hn(e))return e;if(On(e)){const g=n.schema[ar].createNode?.(n.schema,null,n);return g.items.push(e),g}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:a,onAnchor:o,onTagObj:r,schema:s,sourceObjects:l}=n;let m;if(a&&e&&typeof e=="object"){if(m=l.get(e),m)return m.anchor??(m.anchor=o(e)),new pD(m.anchor);m={anchor:null,node:null},l.set(e,m)}let d=fD(e,t,s.tags);if(!d){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const g=new an(e);return m&&(m.node=g),g}d=e instanceof Map?s[ar]:Symbol.iterator in Object(e)?s[xc]:s[ar]}r&&(r(d),delete n.onTagObj);const h=d?.createNode?d.createNode(n.schema,e,n):typeof d?.nodeClass?.from=="function"?d.nodeClass.from(n.schema,e,n):new an(e);return d.default||(h.tag=d.tag),m&&(m.node=h),h}function Fy(e,t,n){let a=n;for(let o=t.length-1;o>=0;--o){const r=t[o];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const s=[];s[r]=a,a=s}else a=new Map([[r,a]])}return Xd(a,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}const hD=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class O1 extends Lg{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){const n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(a=>Hn(a)||On(a)?a.clone(t):a),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(hD(t))this.add(n);else{const[a,...o]=t,r=this.get(a,!0);if(ma(r))r.addIn(o,n);else if(r===void 0&&this.schema)this.set(a,Fy(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}deleteIn(t){const[n,...a]=t;if(a.length===0)return this.delete(n);const o=this.get(n,!0);if(ma(o))return o.deleteIn(a);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${a}`)}getIn(t,n){const[a,...o]=t,r=this.get(a,!0);return o.length===0?!n&&In(r)?r.value:r:ma(r)?r.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!On(n))return!1;const a=n.value;return a==null||t&&In(a)&&a.value==null&&!a.commentBefore&&!a.comment&&!a.tag})}hasIn(t){const[n,...a]=t;if(a.length===0)return this.has(n);const o=this.get(n,!0);return ma(o)?o.hasIn(a):!1}setIn(t,n){const[a,...o]=t;if(o.length===0)this.set(a,n);else{const r=this.get(a,!0);if(ma(r))r.setIn(o,n);else if(r===void 0&&this.schema)this.set(a,Fy(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}}const gD=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Kl(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const as=(e,t,n)=>e.endsWith(`
|
|
125
|
-
`)?Kl(n,t):n.includes(`
|
|
126
|
-
`)?`
|
|
127
|
-
`+Kl(n,t):(e.endsWith(" ")?"":" ")+n,$1="flow",uh="block",Ed="quoted";function Hu(e,t,n="flow",{indentAtStart:a,lineWidth:o=80,minContentWidth:r=20,onFold:s,onOverflow:l}={}){if(!o||o<0)return e;o<r&&(r=0);const m=Math.max(1+r,1+o-t.length);if(e.length<=m)return e;const d=[],h={};let g=o-t.length;typeof a=="number"&&(a>o-Math.max(2,r)?d.push(0):g=o-a);let y,w,_=!1,P=-1,M=-1,C=-1;n===uh&&(P=Vy(e,P,t.length),P!==-1&&(g=P+m));for(let O;O=e[P+=1];){if(n===Ed&&O==="\\"){switch(M=P,e[P+1]){case"x":P+=3;break;case"u":P+=5;break;case"U":P+=9;break;default:P+=1}C=P}if(O===`
|
|
128
|
-
`)n===uh&&(P=Vy(e,P,t.length)),g=P+t.length+m,y=void 0;else{if(O===" "&&w&&w!==" "&&w!==`
|
|
129
|
-
`&&w!==" "){const j=e[P+1];j&&j!==" "&&j!==`
|
|
130
|
-
`&&j!==" "&&(y=P)}if(P>=g)if(y)d.push(y),g=y+m,y=void 0;else if(n===Ed){for(;w===" "||w===" ";)w=O,O=e[P+=1],_=!0;const j=P>C+1?P-2:M-1;if(h[j])return e;d.push(j),h[j]=!0,g=j+m,y=void 0}else _=!0}w=O}if(_&&l&&l(),d.length===0)return e;s&&s();let $=e.slice(0,d[0]);for(let O=0;O<d.length;++O){const j=d[O],x=d[O+1]||e.length;j===0?$=`
|
|
131
|
-
${t}${e.slice(0,x)}`:(n===Ed&&h[j]&&($+=`${e[j]}\\`),$+=`
|
|
132
|
-
${t}${e.slice(j+1,x)}`)}return $}function Vy(e,t,n){let a=t,o=t+1,r=e[o];for(;r===" "||r===" ";)if(t<o+n)r=e[++t];else{do r=e[++t];while(r&&r!==`
|
|
133
|
-
`);a=t,o=t+1,r=e[o]}return a}const Uu=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),qu=e=>/^(%|---|\.\.\.)/m.test(e);function vD(e,t,n){if(!t||t<0)return!1;const a=t-n,o=e.length;if(o<=a)return!1;for(let r=0,s=0;r<o;++r)if(e[r]===`
|
|
134
|
-
`){if(r-s>a)return!0;if(s=r+1,o-s<=a)return!1}return!0}function jl(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:a}=t,o=t.options.doubleQuotedMinMultiLineLength,r=t.indent||(qu(e)?" ":"");let s="",l=0;for(let m=0,d=n[m];d;d=n[++m])if(d===" "&&n[m+1]==="\\"&&n[m+2]==="n"&&(s+=n.slice(l,m)+"\\ ",m+=1,l=m,d="\\"),d==="\\")switch(n[m+1]){case"u":{s+=n.slice(l,m);const h=n.substr(m+2,4);switch(h){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:h.substr(0,2)==="00"?s+="\\x"+h.substr(2):s+=n.substr(m,6)}m+=5,l=m+1}break;case"n":if(a||n[m+2]==='"'||n.length<o)m+=1;else{for(s+=n.slice(l,m)+`
|
|
135
|
-
|
|
136
|
-
`;n[m+2]==="\\"&&n[m+3]==="n"&&n[m+4]!=='"';)s+=`
|
|
137
|
-
`,m+=2;s+=r,n[m+2]===" "&&(s+="\\"),m+=1,l=m+1}break;default:m+=1}return s=l?s+n.slice(l):n,a?s:Hu(s,r,Ed,Uu(t,!1))}function mh(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
138
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return jl(e,t);const n=t.indent||(qu(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
139
|
-
${n}`)+"'";return t.implicitKey?a:Hu(a,n,$1,Uu(t,!1))}function os(e,t){const{singleQuote:n}=t.options;let a;if(n===!1)a=jl;else{const o=e.includes('"'),r=e.includes("'");o&&!r?a=mh:r&&!o?a=jl:a=n?mh:jl}return a(e,t)}let ph;try{ph=new RegExp(`(^|(?<!
|
|
140
|
-
))
|
|
141
|
-
+(?!
|
|
142
|
-
|$)`,"g")}catch{ph=/\n+(?!\n|$)/g}function Md({comment:e,type:t,value:n},a,o,r){const{blockQuote:s,commentString:l,lineWidth:m}=a.options;if(!s||/\n[\t ]+$/.test(n))return os(n,a);const d=a.indent||(a.forceBlockIndent||qu(n)?" ":""),h=s==="literal"?!0:s==="folded"||t===an.BLOCK_FOLDED?!1:t===an.BLOCK_LITERAL?!0:!vD(n,m,d.length);if(!n)return h?`|
|
|
143
|
-
`:`>
|
|
144
|
-
`;let g,y;for(y=n.length;y>0;--y){const x=n[y-1];if(x!==`
|
|
145
|
-
`&&x!==" "&&x!==" ")break}let w=n.substring(y);const _=w.indexOf(`
|
|
146
|
-
`);_===-1?g="-":n===w||_!==w.length-1?(g="+",r&&r()):g="",w&&(n=n.slice(0,-w.length),w[w.length-1]===`
|
|
147
|
-
`&&(w=w.slice(0,-1)),w=w.replace(ph,`$&${d}`));let P=!1,M,C=-1;for(M=0;M<n.length;++M){const x=n[M];if(x===" ")P=!0;else if(x===`
|
|
148
|
-
`)C=M;else break}let $=n.substring(0,C<M?C+1:M);$&&(n=n.substring($.length),$=$.replace(/\n+/g,`$&${d}`));let j=(P?d?"2":"1":"")+g;if(e&&(j+=" "+l(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!h){const x=n.replace(/\n+/g,`
|
|
149
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${d}`);let R=!1;const E=Uu(a,!0);s!=="folded"&&t!==an.BLOCK_FOLDED&&(E.onOverflow=()=>{R=!0});const H=Hu(`${$}${x}${w}`,d,uh,E);if(!R)return`>${j}
|
|
150
|
-
${d}${H}`}return n=n.replace(/\n+/g,`$&${d}`),`|${j}
|
|
151
|
-
${d}${$}${n}${w}`}function bD(e,t,n,a){const{type:o,value:r}=e,{actualString:s,implicitKey:l,indent:m,indentStep:d,inFlow:h}=t;if(l&&r.includes(`
|
|
152
|
-
`)||h&&/[[\]{},]/.test(r))return os(r,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return l||h||!r.includes(`
|
|
153
|
-
`)?os(r,t):Md(e,t,n,a);if(!l&&!h&&o!==an.PLAIN&&r.includes(`
|
|
154
|
-
`))return Md(e,t,n,a);if(qu(r)){if(m==="")return t.forceBlockIndent=!0,Md(e,t,n,a);if(l&&m===d)return os(r,t)}const g=r.replace(/\n+/g,`$&
|
|
155
|
-
${m}`);if(s){const y=P=>P.default&&P.tag!=="tag:yaml.org,2002:str"&&P.test?.test(g),{compat:w,tags:_}=t.doc.schema;if(_.some(y)||w?.some(y))return os(r,t)}return l?g:Hu(g,m,$1,Uu(t,!1))}function yD(e,t,n,a){const{implicitKey:o,inFlow:r}=t,s=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)});let{type:l}=e;l!==an.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(l=an.QUOTE_DOUBLE);const m=h=>{switch(h){case an.BLOCK_FOLDED:case an.BLOCK_LITERAL:return o||r?os(s.value,t):Md(s,t,n,a);case an.QUOTE_DOUBLE:return jl(s.value,t);case an.QUOTE_SINGLE:return mh(s.value,t);case an.PLAIN:return bD(s,t,n,a);default:return null}};let d=m(l);if(d===null){const{defaultKeyType:h,defaultStringType:g}=t.options,y=o&&h||g;if(d=m(y),d===null)throw new Error(`Unsupported default string type ${y}`)}return d}function SD(e,t){const n=Object.assign({blockQuote:!0,commentString:gD,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let a;switch(n.collectionStyle){case"block":a=!1;break;case"flow":a=!0;break;default:a=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:a,options:n}}function xD(e,t){if(t.tag){const o=e.filter(r=>r.tag===t.tag);if(o.length>0)return o.find(r=>r.format===t.format)??o[0]}let n,a;if(In(t)){a=t.value;let o=e.filter(r=>r.identify?.(a));if(o.length>1){const r=o.filter(s=>s.test);r.length>0&&(o=r)}n=o.find(r=>r.format===t.format)??o.find(r=>!r.format)}else a=t,n=e.find(o=>o.nodeClass&&a instanceof o.nodeClass);if(!n){const o=a?.constructor?.name??(a===null?"null":typeof a);throw new Error(`Tag not resolved for ${o} value`)}return n}function kD(e,t,{anchors:n,doc:a}){if(!a.directives)return"";const o=[],r=(In(e)||ma(e))&&e.anchor;r&&M1(r)&&(n.add(r),o.push(`&${r}`));const s=e.tag??(t.default?null:t.tag);return s&&o.push(a.directives.tagString(s)),o.join(" ")}function eu(e,t,n,a){if(On(e))return e.toString(t,n,a);if(Ds(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let o;const r=Hn(e)?e:t.doc.createNode(e,{onTagObj:m=>o=m});o??(o=xD(t.doc.schema.tags,r));const s=kD(r,o,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);const l=typeof o.stringify=="function"?o.stringify(r,t,n,a):In(r)?yD(r,t,n,a):r.toString(t,n,a);return s?In(r)||l[0]==="{"||l[0]==="["?`${s} ${l}`:`${s}
|
|
156
|
-
${t.indent}${l}`:l}function wD({key:e,value:t},n,a,o){const{allNullValues:r,doc:s,indent:l,indentStep:m,options:{commentString:d,indentSeq:h,simpleKeys:g}}=n;let y=Hn(e)&&e.comment||null;if(g){if(y)throw new Error("With simple keys, key nodes cannot have comments");if(ma(e)||!Hn(e)&&typeof e=="object"){const E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let w=!g&&(!e||y&&t==null&&!n.inFlow||ma(e)||(In(e)?e.type===an.BLOCK_FOLDED||e.type===an.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!w&&(g||!r),indent:l+m});let _=!1,P=!1,M=eu(e,n,()=>_=!0,()=>P=!0);if(!w&&!n.inFlow&&M.length>1024){if(g)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");w=!0}if(n.inFlow){if(r||t==null)return _&&a&&a(),M===""?"?":w?`? ${M}`:M}else if(r&&!g||t==null&&w)return M=`? ${M}`,y&&!_?M+=as(M,n.indent,d(y)):P&&o&&o(),M;_&&(y=null),w?(y&&(M+=as(M,n.indent,d(y))),M=`? ${M}
|
|
157
|
-
${l}:`):(M=`${M}:`,y&&(M+=as(M,n.indent,d(y))));let C,$,O;Hn(t)?(C=!!t.spaceBefore,$=t.commentBefore,O=t.comment):(C=!1,$=null,O=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!w&&!y&&In(t)&&(n.indentAtStart=M.length+1),P=!1,!h&&m.length>=2&&!n.inFlow&&!w&&Dg(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let j=!1;const x=eu(t,n,()=>j=!0,()=>P=!0);let R=" ";if(y||C||$){if(R=C?`
|
|
158
|
-
`:"",$){const E=d($);R+=`
|
|
159
|
-
${Kl(E,n.indent)}`}x===""&&!n.inFlow?R===`
|
|
160
|
-
`&&O&&(R=`
|
|
161
|
-
|
|
162
|
-
`):R+=`
|
|
163
|
-
${n.indent}`}else if(!w&&ma(t)){const E=x[0],H=x.indexOf(`
|
|
164
|
-
`),B=H!==-1,D=n.inFlow??t.flow??t.items.length===0;if(B||!D){let J=!1;if(B&&(E==="&"||E==="!")){let le=x.indexOf(" ");E==="&"&&le!==-1&&le<H&&x[le+1]==="!"&&(le=x.indexOf(" ",le+1)),(le===-1||H<le)&&(J=!0)}J||(R=`
|
|
165
|
-
${n.indent}`)}}else(x===""||x[0]===`
|
|
166
|
-
`)&&(R="");return M+=R+x,n.inFlow?j&&a&&a():O&&!j?M+=as(M,n.indent,d(O)):P&&o&&o(),M}function ID(e,t){(e==="debug"||e==="warn")&&console.warn(t)}const ud="<<",cf={identify:e=>e===ud||typeof e=="symbol"&&e.description===ud,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new an(Symbol(ud)),{addToJSMap:N1}),stringify:()=>ud},_D=(e,t)=>(cf.identify(t)||In(t)&&(!t.type||t.type===an.PLAIN)&&cf.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===cf.tag&&n.default);function N1(e,t,n){const a=D1(e,n);if(Dg(a))for(const o of a.items)df(e,t,o);else if(Array.isArray(a))for(const o of a)df(e,t,o);else df(e,t,a)}function df(e,t,n){const a=D1(e,n);if(!T1(a))throw new Error("Merge sources must be maps or map aliases");const o=a.toJSON(null,e,Map);for(const[r,s]of o)t instanceof Map?t.has(r)||t.set(r,s):t instanceof Set?t.add(r):Object.prototype.hasOwnProperty.call(t,r)||Object.defineProperty(t,r,{value:s,writable:!0,enumerable:!0,configurable:!0});return t}function D1(e,t){return e&&Ds(t)?t.resolve(e.doc,e):t}function L1(e,t,{key:n,value:a}){if(Hn(n)&&n.addToJSMap)n.addToJSMap(e,t,a);else if(_D(e,n))N1(e,t,a);else{const o=Ya(n,"",e);if(t instanceof Map)t.set(o,Ya(a,o,e));else if(t instanceof Set)t.add(o);else{const r=CD(n,o,e),s=Ya(a,r,e);r in t?Object.defineProperty(t,r,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[r]=s}}return t}function CD(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Hn(e)&&n?.doc){const a=SD(n.doc,{});a.anchors=new Set;for(const r of n.anchors.keys())a.anchors.add(r.anchor);a.inFlow=!0,a.inStringifyKey=!0;const o=e.toString(a);if(!n.mapKeyWarned){let r=JSON.stringify(o);r.length>40&&(r=r.substring(0,36)+'..."'),ID(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return o}return JSON.stringify(t)}function Hg(e,t,n){const a=Xd(e,void 0,n),o=Xd(t,void 0,n);return new Go(a,o)}class Go{constructor(t,n=null){Object.defineProperty(this,Ro,{value:A1}),this.key=t,this.value=n}clone(t){let{key:n,value:a}=this;return Hn(n)&&(n=n.clone(t)),Hn(a)&&(a=a.clone(t)),new Go(n,a)}toJSON(t,n){const a=n?.mapAsMap?new Map:{};return L1(n,a,this)}toString(t,n,a){return t?.doc?wD(this,t,n,a):JSON.stringify(this)}}function H1(e,t,n){return(t.inFlow??e.flow?PD:RD)(e,t,n)}function RD({comment:e,items:t},n,{blockItemPrefix:a,flowChars:o,itemIndent:r,onChompKeep:s,onComment:l}){const{indent:m,options:{commentString:d}}=n,h=Object.assign({},n,{indent:r,type:null});let g=!1;const y=[];for(let _=0;_<t.length;++_){const P=t[_];let M=null;if(Hn(P))!g&&P.spaceBefore&&y.push(""),tu(n,y,P.commentBefore,g),P.comment&&(M=P.comment);else if(On(P)){const $=Hn(P.key)?P.key:null;$&&(!g&&$.spaceBefore&&y.push(""),tu(n,y,$.commentBefore,g))}g=!1;let C=eu(P,h,()=>M=null,()=>g=!0);M&&(C+=as(C,r,d(M))),g&&M&&(g=!1),y.push(a+C)}let w;if(y.length===0)w=o.start+o.end;else{w=y[0];for(let _=1;_<y.length;++_){const P=y[_];w+=P?`
|
|
167
|
-
${m}${P}`:`
|
|
168
|
-
`}}return e?(w+=`
|
|
169
|
-
`+Kl(d(e),m),l&&l()):g&&s&&s(),w}function PD({items:e},t,{flowChars:n,itemIndent:a}){const{indent:o,indentStep:r,flowCollectionPadding:s,options:{commentString:l}}=t;a+=r;const m=Object.assign({},t,{indent:a,inFlow:!0,type:null});let d=!1,h=0;const g=[];for(let _=0;_<e.length;++_){const P=e[_];let M=null;if(Hn(P))P.spaceBefore&&g.push(""),tu(t,g,P.commentBefore,!1),P.comment&&(M=P.comment);else if(On(P)){const $=Hn(P.key)?P.key:null;$&&($.spaceBefore&&g.push(""),tu(t,g,$.commentBefore,!1),$.comment&&(d=!0));const O=Hn(P.value)?P.value:null;O?(O.comment&&(M=O.comment),O.commentBefore&&(d=!0)):P.value==null&&$?.comment&&(M=$.comment)}M&&(d=!0);let C=eu(P,m,()=>M=null);d||(d=g.length>h||C.includes(`
|
|
170
|
-
`)),_<e.length-1?C+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(d||(d=g.reduce(($,O)=>$+O.length+2,2)+(C.length+2)>t.options.lineWidth)),d&&(C+=",")),M&&(C+=as(C,a,l(M))),g.push(C),h=g.length}const{start:y,end:w}=n;if(g.length===0)return y+w;if(!d){const _=g.reduce((P,M)=>P+M.length+2,2);d=t.options.lineWidth>0&&_>t.options.lineWidth}if(d){let _=y;for(const P of g)_+=P?`
|
|
171
|
-
${r}${o}${P}`:`
|
|
172
|
-
`;return`${_}
|
|
173
|
-
${o}${w}`}else return`${y}${s}${g.join(" ")}${s}${w}`}function tu({indent:e,options:{commentString:t}},n,a,o){if(a&&o&&(a=a.replace(/^\n+/,"")),a){const r=Kl(t(a),e);n.push(r.trimStart())}}function Qi(e,t){const n=In(t)?t.value:t;for(const a of e)if(On(a)&&(a.key===t||a.key===n||In(a.key)&&a.key.value===n))return a}class Zr extends O1{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ar,t),this.items=[]}static from(t,n,a){const{keepUndefined:o,replacer:r}=a,s=new this(t),l=(m,d)=>{if(typeof r=="function")d=r.call(n,m,d);else if(Array.isArray(r)&&!r.includes(m))return;(d!==void 0||o)&&s.items.push(Hg(m,d,a))};if(n instanceof Map)for(const[m,d]of n)l(m,d);else if(n&&typeof n=="object")for(const m of Object.keys(n))l(m,n[m]);return typeof t.sortMapEntries=="function"&&s.items.sort(t.sortMapEntries),s}add(t,n){let a;On(t)?a=t:!t||typeof t!="object"||!("key"in t)?a=new Go(t,t?.value):a=new Go(t.key,t.value);const o=Qi(this.items,a.key),r=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${a.key} already set`);In(o.value)&&j1(a.value)?o.value.value=a.value:o.value=a.value}else if(r){const s=this.items.findIndex(l=>r(a,l)<0);s===-1?this.items.push(a):this.items.splice(s,0,a)}else this.items.push(a)}delete(t){const n=Qi(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const o=Qi(this.items,t)?.value;return(!n&&In(o)?o.value:o)??void 0}has(t){return!!Qi(this.items,t)}set(t,n){this.add(new Go(t,n),!0)}toJSON(t,n,a){const o=a?new a:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(o);for(const r of this.items)L1(n,o,r);return o}toString(t,n,a){if(!t)return JSON.stringify(this);for(const o of this.items)if(!On(o))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),H1(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:a,onComment:n})}}class U1 extends O1{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(xc,t),this.items=[]}add(t){this.items.push(t)}delete(t){const n=md(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const a=md(t);if(typeof a!="number")return;const o=this.items[a];return!n&&In(o)?o.value:o}has(t){const n=md(t);return typeof n=="number"&&n<this.items.length}set(t,n){const a=md(t);if(typeof a!="number")throw new Error(`Expected a valid index, not ${t}.`);const o=this.items[a];In(o)&&j1(n)?o.value=n:this.items[a]=n}toJSON(t,n){const a=[];n?.onCreate&&n.onCreate(a);let o=0;for(const r of this.items)a.push(Ya(r,String(o++),n));return a}toString(t,n,a){return t?H1(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:a,onComment:n}):JSON.stringify(this)}static from(t,n,a){const{replacer:o}=a,r=new this(t);if(n&&Symbol.iterator in Object(n)){let s=0;for(let l of n){if(typeof o=="function"){const m=n instanceof Set?l:String(s++);l=o.call(n,m,l)}r.items.push(Xd(l,void 0,a))}}return r}}function md(e){let t=In(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}function AD(e,t,n){const{replacer:a}=n,o=new U1(e);o.tag="tag:yaml.org,2002:pairs";let r=0;if(t&&Symbol.iterator in Object(t))for(let s of t){typeof a=="function"&&(s=a.call(t,String(r++),s));let l,m;if(Array.isArray(s))if(s.length===2)l=s[0],m=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){const d=Object.keys(s);if(d.length===1)l=d[0],m=s[l];else throw new TypeError(`Expected tuple with one key, not ${d.length} keys`)}else l=s;o.items.push(Hg(l,m,n))}return o}class Ug extends U1{constructor(){super(),this.add=Zr.prototype.add.bind(this),this.delete=Zr.prototype.delete.bind(this),this.get=Zr.prototype.get.bind(this),this.has=Zr.prototype.has.bind(this),this.set=Zr.prototype.set.bind(this),this.tag=Ug.tag}toJSON(t,n){if(!n)return super.toJSON(t);const a=new Map;n?.onCreate&&n.onCreate(a);for(const o of this.items){let r,s;if(On(o)?(r=Ya(o.key,"",n),s=Ya(o.value,r,n)):r=Ya(o,"",n),a.has(r))throw new Error("Ordered maps must not include duplicate keys");a.set(r,s)}return a}static from(t,n,a){const o=AD(t,n,a),r=new this;return r.items=o.items,r}}Ug.tag="tag:yaml.org,2002:omap";class qg extends Zr{constructor(t){super(t),this.tag=qg.tag}add(t){let n;On(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Go(t.key,null):n=new Go(t,null),Qi(this.items,n.key)||this.items.push(n)}get(t,n){const a=Qi(this.items,t);return!n&&On(a)?In(a.key)?a.key.value:a.key:a}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const a=Qi(this.items,t);a&&!n?this.items.splice(this.items.indexOf(a),1):!a&&n&&this.items.push(new Go(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,a){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,a);throw new Error("Set items must all have null values")}static from(t,n,a){const{replacer:o}=a,r=new this(t);if(n&&Symbol.iterator in Object(n))for(let s of n)typeof o=="function"&&(s=o.call(n,s,s)),r.items.push(Hg(s,null,a));return r}}qg.tag="tag:yaml.org,2002:set";new Set("0123456789ABCDEFabcdef");new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");new Set(",[]{}");new Set(` ,[]{}
|
|
174
|
-
\r `);const nu=i().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"source paths must be portable relative paths");i().regex(/^[a-z][a-z0-9_-]{0,119}$/);const TD={type:"object",properties:{},additionalProperties:!1};c({name:i().trim().min(1).max(240).optional(),description:i().max(4e3).optional(),skillPaths:p(nu).max(100).optional(),assetPaths:p(nu).max(100).optional()}).strict();c({actionId:i().trim().min(1).max(240),name:i().trim().min(1).max(240),description:i().max(4e3).default(""),inputSchema:oe(i(),se()).default(TD),skillPaths:p(nu).max(100).default([]),assetPaths:p(nu).max(100).default([])}).strict();const q1=b(["openpond.lab"]),Wl=c({id:i(),experience:Pg.default(v$),provider:$s,modelRef:un.nullable().optional(),openPondCommandAccessMode:gc.default(ju),systemKind:q1.nullable().optional(),hiddenFromDefaultSidebar:A().optional(),parentSessionId:i().nullable().optional(),parentTurnId:i().nullable().optional(),subagentRunId:i().nullable().optional(),subagentRoleId:Os.nullable().optional(),subagentDelegationMode:Tu.nullable().optional(),title:i(),appId:i().nullable(),appName:i().nullable(),workspaceKind:vc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:Co.nullable().optional(),profileWorkflowBinding:rD.nullable().optional(),profileComponentBinding:sD.nullable().optional(),metadata:oe(i(),se()).optional(),cwd:i().nullable(),codexThreadId:i().nullable(),createdAt:i(),updatedAt:i(),status:b(["idle","active","failed","closed"]),runtimeSeconds:u().int().nonnegative().optional(),runtimeRunningSince:i().nullable().optional(),pinned:A(),savedForLater:A().optional(),archived:A(),order:u()});c({id:i(),sessionId:i(),providerTurnId:i().nullable(),modelRef:un.nullable().optional(),prompt:i(),startedAt:i(),completedAt:i().nullable(),status:b(["in_progress","completed","failed","interrupted"]),error:i().nullable(),metadata:oe(i(),se()).optional().default({}),createImproveRun:bc.nullable().optional().default(null),profileSnapshot:H$.nullable().optional(),harnessSnapshot:q$.nullable().optional()});const ED=c({id:i(),sessionId:i(),turnId:i().nullable(),providerRequestId:Tt([i(),u()]),kind:b(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:i(),detail:i(),status:b(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:i()}),MD=c({key:b(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:i(),status:b(["placeholder","available","error"]),summary:i()}),z1=c({id:i().trim().min(1).max(191),agentId:i().trim().min(1).max(191).optional().nullable(),sourcePath:i().trim().min(1).max(2e3).optional().nullable(),sourceActionId:i().trim().min(1).max(191).optional().nullable(),name:i().trim().min(1).max(191).optional().nullable(),label:i().trim().min(1).max(160).optional().nullable(),description:i().trim().max(1e3).optional().nullable(),visibility:i().trim().max(80).optional().nullable(),inputSchema:Tt([i().trim().max(191),oe(i(),se())]).optional().nullable(),outputSchema:Tt([i().trim().max(191),oe(i(),se())]).optional().nullable(),approvalPolicy:oe(i(),se()).optional().nullable(),artifactPolicy:oe(i(),se()).optional().nullable(),setupRequirements:p(oe(i(),se())).optional(),mcp:oe(i(),se()).optional().nullable(),schedulePolicy:oe(i(),se()).optional().nullable(),trace:oe(i(),se()).optional().nullable(),implementation:oe(i(),se()).optional().nullable(),invokesModel:A().optional()}),jD=c({command:b(["inspect","build","validate","eval","traces","run"]),status:b(["passed","failed"]),checkedAt:i(),exitCode:u().nullable().optional(),sourceHead:i().nullable().optional()}),OD=c({id:i(),name:i(),path:i(),enabled:A()}),$D=c({name:i(),description:i(),path:i(),scope:S("profile"),enabled:A(),sourcePath:i(),charCount:u(),sourceHash:i(),validationStatus:b(["valid","warning","error"]),validationMessages:p(i()),resourceFiles:p(i()).optional().default([])}),ND=c({id:i(),name:i(),path:i(),agentId:i().nullable(),sourcePath:i()}),B1=c({path:i(),originalPath:i().nullable().optional(),indexStatus:i().nullable(),worktreeStatus:i().nullable(),status:i(),category:b(["added","modified","deleted","renamed","untracked","changed"])}),DD=c({isRepo:A(),branch:i().nullable(),head:i().nullable(),shortHead:i().nullable(),dirty:A(),upstream:i().nullable(),ahead:u().nullable(),behind:u().nullable(),remoteUrl:i().nullable(),files:p(B1),fileCount:u().int().nonnegative().optional(),error:i().nullable()}),LD=c({actionCount:u(),generatedAt:i().nullable(),manifestPath:i().nullable(),registryPath:i().nullable(),stale:A(),error:i().nullable()}),HD=c({skillCount:u(),generatedAt:i().nullable(),stale:A(),error:i().nullable()}),Ky=c({ref:i(),source:b(["action_catalog","source_upload_metadata"]),actionId:i().nullable(),kind:i().nullable(),label:i(),status:i(),required:A(),blocking:A()}),UD=c({status:b(["ready","setup_required","blocked"]),requirementCount:u(),blockingCount:u(),optionalMissingCount:u(),readyCount:u(),requirements:p(Ky),blockingRequirements:p(Ky)}),qD=c({changedAgents:p(i()),newAgents:p(i()),deletedAgents:p(i()),changedSkills:p(i()).optional().default([]),changedActions:p(i()),changedExtensions:p(i()),setupChanges:p(i()),envRequirementChanges:p(i()),files:p(B1),fileCount:u().int().nonnegative().optional()}),zD=c({status:i(),agentId:i().nullable().optional(),deployPlanStatus:i().nullable().optional(),canRun:A().nullable().optional(),canDeploy:A().nullable().optional(),sourceRef:i().nullable().optional(),sourceCommitSha:i().nullable().optional(),manifestHash:i().nullable().optional(),manifestPath:i().nullable().optional(),setupCommands:p(i()).optional(),validationCommands:p(i()).optional(),requiredChecks:p(i()).optional(),evalNames:p(i()).optional(),blockedReasons:p(i()).optional(),staleReasons:p(i()).optional(),runtimeId:i().nullable().optional(),sandboxId:i().nullable().optional(),traceArtifactRefs:p(i()).optional(),evalResultArtifactRefs:p(i()).optional(),validatorArtifactRefs:p(i()).optional(),checkedAt:i().nullable().optional(),error:i().nullable().optional()}),BD=c({status:i(),agentId:i().nullable().optional(),runtimeAgentId:i().nullable().optional(),projectId:i().nullable().optional(),sourceRoot:i().nullable().optional(),sourceRef:i().nullable().optional(),sourceCommitSha:i().nullable().optional(),manifestHash:i().nullable().optional(),manifestPath:i().nullable().optional(),manifestSyncedAt:i().nullable().optional(),fileCount:u().nullable().optional(),totalBytes:u().nullable().optional(),generatedManifestPath:i().nullable().optional(),synthesizedOpenPondYaml:A().nullable().optional(),uploadMetadataPath:i().nullable().optional(),setupCommands:p(i()).optional(),validationCommands:p(i()).optional(),materializedAt:i().nullable().optional(),error:i().nullable().optional()}),FD=c({status:i(),agentId:i().nullable().optional(),snapshotId:i().nullable().optional(),sourceRef:i().nullable().optional(),sourceCommitSha:i().nullable().optional(),manifestHash:i().nullable().optional(),manifestPath:i().nullable().optional(),buildStatus:i().nullable().optional(),validationStatus:i().nullable().optional(),evalStatus:i().nullable().optional(),publishedAt:i().nullable().optional(),error:i().nullable().optional()}),VD=c({status:i(),agentId:i().nullable().optional(),runId:i().nullable().optional(),runtimeId:i().nullable().optional(),sandboxId:i().nullable().optional(),sourceRef:i().nullable().optional(),sourceCommitSha:i().nullable().optional(),manifestHash:i().nullable().optional(),setupGateStatus:i().nullable().optional(),setupRequirementRefs:p(i()).optional(),artifactRefs:p(i()).optional(),traceArtifactRefs:p(i()).optional(),evalArtifactRefs:p(i()).optional(),startedAt:i().nullable().optional(),completedAt:i().nullable().optional(),error:i().nullable().optional()}),KD=c({teamId:i().nullable(),projectId:i().nullable(),sourceRef:i().nullable(),sourceCommitSha:i().nullable(),lastPushedAt:i().nullable(),lastPushedLocalHead:i().nullable(),lastPushedHostedHead:i().nullable(),promotionStatus:i().nullable().optional().default(null),hostedRunStatus:i().nullable().optional().default(null),hostedRunAgentId:i().nullable().optional().default(null),hostedRunId:i().nullable().optional().default(null),hostedRunAt:i().nullable().optional().default(null),hostedSourceMaterialization:BD.nullable().optional().default(null),hostedSourceCheck:zD.nullable().optional().default(null),hostedPublish:FD.nullable().optional().default(null),hostedRun:VD.nullable().optional().default(null)}),WD=c({state:b(["none","ready","dirty","pending_commit","error"]),message:i(),agentCount:u(),actionCount:u(),defaultAction:i().nullable(),checkFresh:A(),checkStaleReason:i().nullable(),localHead:i().nullable(),hostedHead:i().nullable()}),F1=c({mode:b(["none","local"]),repoPath:i().nullable(),activeProfile:i().nullable(),sourcePath:i().nullable(),manifestPath:i().nullable(),agents:p(OD),skills:p($D).optional().default([]),evals:p(ND).optional().default([]),git:DD.nullable(),catalog:LD,skillCatalog:HD.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:p(z1),sourceSetupRequirements:p(oe(i(),se())),setupGate:UD,diff:qD,hosted:KD.nullable(),summary:WD,lastCheck:jD.nullable(),error:i().nullable()}),GD=c({ref:Co,name:i(),repoPath:i(),sourcePath:i().nullable(),state:F1}),JD=c({lastUsed:Co.nullable(),profiles:p(GD)});function ZD(){return{lastUsed:null,profiles:[]}}function YD(){return{mode:"none",repoPath:null,activeProfile:null,sourcePath:null,manifestPath:null,agents:[],skills:[],evals:[],git:null,catalog:{actionCount:0,generatedAt:null,manifestPath:null,registryPath:null,stale:!0,error:null},skillCatalog:{skillCount:0,generatedAt:null,stale:!0,error:null},actionCatalog:[],sourceSetupRequirements:[],setupGate:{status:"ready",requirementCount:0,blockingCount:0,optionalMissingCount:0,readyCount:0,requirements:[],blockingRequirements:[]},diff:{changedAgents:[],newAgents:[],deletedAgents:[],changedSkills:[],changedActions:[],changedExtensions:[],setupChanges:[],envRequirementChanges:[],files:[]},hosted:null,summary:{state:"none",message:"No active OpenPond profile.",agentCount:0,actionCount:0,defaultAction:null,checkFresh:!1,checkStaleReason:"No active profile.",localHead:null,hostedHead:null},lastCheck:null,error:null}}const QD=c({name:i(),description:i(),path:i(),sourcePath:i(),enabled:A(),charCount:u().int().nonnegative(),sourceHash:i(),validationStatus:b(["valid","error"]),validationMessages:p(i()),resourceFiles:p(i()),updatedAt:i().nullable()}),XD=b(["codex","profile","extension"]);c({skillName:i(),scope:XD,path:i(),byteSize:u().int().nonnegative(),isBinary:A(),content:i().nullable()});const eL=[{name:"openpond-taskset-authoring",description:"Create, improve, inspect, test, or prepare an OpenPond Taskset from a capability, Profile Agent, consented evidence, or imported data.",path:"skills/openpond-taskset-authoring/SKILL.md",scope:"profile",enabled:!0,sourcePath:"bundled://openpond",charCount:0,sourceHash:"bundled",validationStatus:"valid",validationMessages:[],resourceFiles:["references/task-design.md","references/graders-and-rewards.md","references/method-selection.md","references/privacy-and-provenance.md"]},{name:"openpond-skill-authoring",description:"Create, copy, adapt, review, or update OpenPond Profile skill packages from slash commands or ordinary authoring requests.",path:"skills/openpond-skill-authoring/SKILL.md",scope:"profile",enabled:!0,sourcePath:"bundled://openpond",charCount:0,sourceHash:"bundled",validationStatus:"valid",validationMessages:[],resourceFiles:["references/skill-package-layout.md","references/copying-and-adaptation.md","references/validation-and-repair.md","scripts/validate-skill.mjs"]},{name:"openpond-agent-authoring",description:"Create, improve, review, or repair source-backed OpenPond Profile Agents and Agent SDK projects.",path:"skills/openpond-agent-authoring/SKILL.md",scope:"profile",enabled:!0,sourcePath:"bundled://openpond",charCount:0,sourceHash:"bundled",validationStatus:"valid",validationMessages:[],resourceFiles:["references/profile-layout.md","references/action-and-chat-design.md","references/integrations-and-setup.md","references/validation-and-repair.md"]},{name:"openpond-refiner-authoring",description:"Inspect, extend, validate, activate, or roll back the OpenPond Refiner Review Profile without changing the Refiner Core.",path:"skills/openpond-refiner-authoring/SKILL.md",scope:"profile",enabled:!0,sourcePath:"bundled://openpond",charCount:0,sourceHash:"bundled",validationStatus:"valid",validationMessages:[],resourceFiles:["references/review-profile.md","references/core-boundary.md","references/validation-and-activation.md"]}],tL=c({name:i(),description:i(),relativePath:i(),sourcePath:i(),charCount:u().int().nonnegative(),sourceHash:i(),resourceFiles:p(i()),validationStatus:b(["valid","error"]),validationMessages:p(i())}),V1=c({id:i(),source:S("github"),owner:i(),repo:i(),repositoryUrl:i().url(),requestedRef:i(),resolvedCommit:i(),sourcePath:i(),readmePath:i().nullable(),installedAt:i(),updatedAt:i(),packageHash:i(),skills:p(tL),validationStatus:b(["valid","error"]),validationMessages:p(i())});V1.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:mc()});const nL=c({rootPath:i(),registryPath:i(),extensions:p(V1),error:i().nullable()});c({source:i().trim().min(1),ref:i().trim().min(1).optional()});const aL=c({latestSequence:u().int().nonnegative(),oldestSequence:u().int().nonnegative(),totalEvents:u().int().nonnegative(),limit:u().int().nonnegative(),hasMoreBefore:A()});c({server:g$,account:r$,codex:s$,configuration:c({rawRevision:i(),effectiveRevision:i(),sources:p(c({layer:i(),path:i(),revision:i()})),provenance:oe(i(),c({layer:i(),path:i(),revision:i()}))}).optional(),preferences:Dy.optional().default(()=>Dy.parse({})),providers:iy.optional().default(()=>iy.parse({})),personalization:Ly.optional().default(()=>Ly.parse({soul:r1[0].content,soulPath:null,updatedAt:null})),apps:p(h2),localProjects:p(S2).optional().default([]),cloudProjects:p(y2).optional().default([]),profile:F1.optional().default(YD),profileLibrary:JD.optional().default(ZD),codexPersonalSkills:p(QD).optional().default([]),extensionCatalog:nL.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:p(Wl).optional().default([]),sidebarAppPreferences:X2,sidebarFileBookmarks:p(o1).optional().default([]),appsError:i().nullable(),appsMeta:Ny,accountMeta:Ny,sessions:p(Wl),events:p(ry),eventWindow:aL.optional(),approvals:p(ED),placeholders:p(MD),diagnostics:p(ry)});const zg=b(["openpond_hosted","local_byok","codex_app_server","unknown"]),K1=b(["provider_usage","codex_context_usage","missing"]),oL=b(["provider_usage_body","provider_response_headers"]),iL=b(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),rL=b(["foreground","tool_loop","compaction","subagent","refiner","other"]),W1=b(["user_facing","background","system"]),G1=b(["started","completed","failed","interrupted"]),Bg=b(["composer_selection","prompt_parse","server_parser","model_tool","api"]),J1=b(["chat","settings","goal","create_improve","compaction","system"]),Z1=b(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),sL=c({surface:J1,workflowKind:Z1,sessionId:i().trim().min(1).nullable().default(null),turnId:i().trim().min(1).nullable().default(null),goalId:i().trim().min(1).nullable().default(null),subagentRunId:i().trim().min(1).nullable().default(null),subagentRoleId:i().trim().min(1).nullable().default(null),createImproveRunId:i().trim().min(1).nullable().default(null),commandName:i().trim().min(1).max(160).nullable().default(null),commandSource:Bg.nullable().default(null),appId:i().trim().min(1).nullable().default(null),workspaceKind:vc.nullable().default(null),workspaceId:i().trim().min(1).nullable().default(null),localProjectId:i().trim().min(1).nullable().default(null),cloudProjectId:i().trim().min(1).nullable().default(null),sourceEventSequence:u().int().nonnegative().nullable().default(null)}),lL=c({surface:J1.optional(),workflowKind:Z1.optional(),goalId:i().trim().min(1).nullable().optional(),subagentRunId:i().trim().min(1).nullable().optional(),subagentRoleId:i().trim().min(1).nullable().optional(),createImproveRunId:i().trim().min(1).nullable().optional(),commandName:i().trim().min(1).max(160).nullable().optional(),commandSource:Bg.nullable().optional()}).strict(),fr=i().trim().min(1).max(160),cL=c({id:i().trim().min(1),requestId:i().trim().min(1),requestOrdinal:u().int().nonnegative(),sessionId:i().trim().min(1).nullable(),turnId:i().trim().min(1).nullable(),provider:fr,model:i().trim().min(1),route:zg,source:K1,requestKind:iL,visibility:W1,status:G1,startedAt:i().trim().min(1),completedAt:i().trim().min(1).nullable(),durationMs:u().int().nonnegative().nullable(),firstTokenMs:u().int().nonnegative().nullable(),promptTokens:u().int().nonnegative().nullable(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheTelemetrySource:oL.nullable(),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),errorType:i().trim().min(1).max(160).nullable(),errorMessage:i().trim().min(1).max(2e3).nullable(),attribution:sL}),Y1=c({from:i().trim().min(1),to:i().trim().min(1),bucket:b(["day","all_time"])}),Fg=Tt([S("all"),W1]),Vg=b(["all","started","completed","failed","interrupted","missing"]),dL=c({range:b(["7d","30d","90d","all"]).default("30d"),visibility:Fg.default("all"),status:Vg.default("all"),provider:fr.optional(),model:i().trim().min(1).optional()});dL.extend({sessionId:i().trim().min(1).optional(),turnId:i().trim().min(1).optional(),limit:u().int().positive().max(500).default(100)});c({sessionId:i().trim().min(1)});const hr=c({requests:u().int().nonnegative(),promptTokens:u().int().nonnegative().nullable(),cacheTelemetryRequests:u().int().nonnegative(),cacheHitRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheRequestHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),averageLatencyMs:u().nonnegative().nullable(),p95LatencyMs:u().nonnegative().nullable(),averageFirstTokenMs:u().nonnegative().nullable(),p95FirstTokenMs:u().nonnegative().nullable(),failures:u().int().nonnegative(),failureRate:u().nonnegative(),firstSeenAt:i().trim().min(1),lastSeenAt:i().trim().min(1)}),uL=hr.extend({provider:fr,model:i().trim().min(1),route:zg}),mL=hr.extend({sessionId:i().trim().min(1),title:i().trim().min(1).nullable(),workspaceKind:vc.nullable(),workspaceId:i().trim().min(1).nullable()}),pL=hr.extend({commandName:i().trim().min(1),commandSource:Bg.nullable()}),fL=hr.extend({route:zg}),hL=hr.extend({status:G1}),gL=hr.extend({source:K1}),vL=hr.extend({cohort:rL}),bL=c({date:i().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative(),models:p(c({provider:fr,model:i().trim().min(1),totalTokens:u().int().nonnegative(),requests:u().int().nonnegative()}))}),yL=c({requests:u().int().nonnegative(),completedRequests:u().int().nonnegative(),failedRequests:u().int().nonnegative(),missingUsageRequests:u().int().nonnegative(),promptTokens:u().int().nonnegative().nullable(),cacheTelemetryRequests:u().int().nonnegative(),cacheHitRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheRequestHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),completionTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),averageLatencyMs:u().nonnegative().nullable(),p95LatencyMs:u().nonnegative().nullable(),averageFirstTokenMs:u().nonnegative().nullable(),p95FirstTokenMs:u().nonnegative().nullable(),failureRate:u().nonnegative(),activeModelCount:u().int().nonnegative(),peakDailyTokens:u().int().nonnegative(),longestRequestMs:u().int().nonnegative().nullable(),activeDays:u().int().nonnegative(),currentStreakDays:u().int().nonnegative(),longestStreakDays:u().int().nonnegative()});c({generatedAt:i().trim().min(1),range:Y1,filters:c({visibility:Fg,status:Vg,provider:fr.nullable(),model:i().trim().min(1).nullable()}),totals:yL,daily:p(bL),models:p(uL),threads:p(mL),commands:p(pL),routes:p(fL),statuses:p(hL),sources:p(gL),cohorts:p(vL)});c({generatedAt:i().trim().min(1),range:Y1,filters:c({visibility:Fg,status:Vg,provider:fr.nullable(),model:i().trim().min(1).nullable(),sessionId:i().trim().min(1).nullable(),turnId:i().trim().min(1).nullable()}),limit:u().int().positive(),hasMore:A(),records:p(cL)});const SL=c({turnId:i().trim().min(1),requests:u().int().nonnegative(),cacheTelemetryRequests:u().int().nonnegative(),cachedPromptTokens:u().int().nonnegative().nullable(),uncachedPromptTokens:u().int().nonnegative().nullable(),cacheWritePromptTokens:u().int().nonnegative().nullable(),cacheHitRate:u().min(0).max(1).nullable(),cacheTelemetryCoverage:u().min(0).max(1),providers:p(fr)});c({generatedAt:i().trim().min(1),sessionId:i().trim().min(1),turns:p(SL)});const xL=b(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);c({type:xL,title:i().trim().min(1),summary:i().trim().min(1),severity:b(["nit","concern","blocker"]),payload:oe(i(),se()).default({})});const kL=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),wL=b(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),IL=b(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),_L=c({kind:S("integration"),provider:kL,appIds:p(wL).min(1).max(4),setupSurfaces:p(IL).min(1).max(4),connectionIds:p(i().trim().min(1)).max(8).optional(),capabilities:p(i().trim().min(1)).max(64).optional()}).strict(),Xi={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},CL=b(["image","text","file"]),RL=c({sessionId:i().trim().min(1).max(200),turnId:i().trim().min(1).max(200),attachmentId:i().trim().min(1).max(200),storageName:i().trim().min(1).max(240),contentType:i().trim().min(1).max(160)}),PL=c({sessionId:i().trim().min(1).max(200),turnId:i().trim().min(1).max(200),attachmentId:i().trim().min(1).max(200),storageName:i().trim().min(1).max(1024),contentType:i().trim().min(1).max(160)}),Q1=c({id:i().trim().min(1),name:i().trim().min(1).max(240),mediaType:i().trim().min(1).max(160),sizeBytes:u().int().nonnegative().max(Xi.maxAttachmentBytes),kind:CL,lineCount:u().int().nonnegative().max(Xi.maxAttachmentBytes+1).optional(),relativePath:i().trim().min(1).max(1024).optional(),text:i().max(Xi.maxTextChars).optional(),contentsBase64:i().max(Xi.maxAttachmentBase64Chars).optional()}),AL=Q1.omit({text:!0,contentsBase64:!0}).extend({imagePreview:RL.optional(),filePreview:PL.optional()});c({experience:Pg.optional(),provider:$s.default(ir),modelRef:un.optional(),openPondCommandAccessMode:gc.optional(),systemKind:q1.nullable().optional(),hiddenFromDefaultSidebar:A().optional(),parentSessionId:i().trim().min(1).max(200).nullable().optional(),parentTurnId:i().trim().min(1).max(200).nullable().optional(),subagentRunId:i().trim().min(1).max(200).nullable().optional(),subagentRoleId:Os.nullable().optional(),subagentDelegationMode:Tu.nullable().optional(),appId:i().nullable().optional(),appName:i().nullable().optional(),workspaceKind:vc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:Co.nullable().optional(),profileWorkflowBinding:Wl.shape.profileWorkflowBinding,profileComponentBinding:Wl.shape.profileComponentBinding,metadata:oe(i(),se()).optional(),cwd:i().nullable().optional(),title:i().optional(),autoTitlePrompt:i().trim().min(1).max(2e4).optional()});c({teamId:i().trim().min(1),projectName:i().trim().min(1).max(120).optional(),branch:i().trim().min(1).max(120).optional(),chatSessionId:i().trim().min(1).max(200).optional(),displayPrompt:i().trim().min(1).max(2e3).optional()});c({branch:i().trim().min(1).max(120).optional()});c({prompt:i().min(1),workflowInput:se().optional(),metadata:oe(i(),se()).optional(),usageAttribution:lL.optional().nullable(),cwd:i().nullable().optional(),model:i().nullable().optional(),modelRef:un.optional(),mentionedAppIds:p(i().trim().min(1)).max(8).optional(),mentionedConnectedApps:p(_L).max(8).optional(),openPondActionCatalog:p(z1).max(100).optional(),attachments:p(Q1).max(Xi.maxAttachments).optional(),createImproveRun:bc.optional().nullable(),approvalPolicy:b(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:b(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:Cg.default("default"),codexReasoningEffort:Ou.optional()});c({prompt:i().min(1),error:i().min(1),target:b(["cloud_workspace","hybrid_sandbox"])});c({reason:b(["manual"]).default("manual"),model:i().nullable().optional(),modelRef:un.optional()});c({experience:Pg.optional(),provider:$s.optional(),modelRef:un.nullable().optional(),openPondCommandAccessMode:gc.optional(),pinned:A().optional(),savedForLater:A().optional(),archived:A().optional(),order:u().optional(),title:i().optional(),parentSessionId:i().trim().min(1).max(200).nullable().optional(),parentTurnId:i().trim().min(1).max(200).nullable().optional(),subagentRunId:i().trim().min(1).max(200).nullable().optional(),subagentRoleId:Os.nullable().optional(),subagentDelegationMode:Tu.nullable().optional(),appId:i().nullable().optional(),appName:i().nullable().optional(),workspaceKind:vc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:Co.nullable().optional(),metadata:oe(i(),se()).optional(),cwd:i().nullable().optional()});c({command:i().trim().min(1),cwd:i().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:u().int().min(1).max(3600).optional()});c({appIds:p(i()).min(1)});c({expectedRevision:i().optional(),defaultChatProvider:$s.optional(),defaultChatModel:i().min(1).optional(),defaultChatModelRef:un.nullable().optional(),subagents:zl.optional(),codexPermissionMode:Cg.optional(),codexReasoningEffort:Ou.optional(),openPondCommandAccessMode:gc.optional(),defaultBranchPrefix:i().trim().max(48).optional(),defaultNewProjectDirectory:i().trim().max(4096).optional(),defaultTeamId:i().trim().max(191).nullable().optional(),advancedWorkspaceControls:A().optional(),steerActiveResponses:A().optional(),contextCompaction:sh.optional(),training:lh.optional(),sidebarWidth:u().int().min(244).max(560).optional(),diffPanelWidth:u().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:rh.optional(),editor:Qd.optional()});c({message:i().trim().min(1).max(4e3),surface:i().trim().min(1).max(120).default("app"),stack:i().max(12e3).nullable().optional(),context:oe(i(),se()).optional()}).strict();c({activeTemplateId:Rg,templateName:i().trim().min(1).max(80),soul:i().trim().min(1).max(8e3),saveAsNew:A().optional().default(!1)});c({decision:b(["accept","acceptForSession","decline","cancel"])});c({branch:i().trim().min(1).max(240).nullable().optional(),surface:b(["desktop","terminal"])});c({handle:i().min(1),baseUrl:i().nullable().optional()});c({handle:i().min(1),baseUrl:i().nullable().optional()});c({handle:i().min(1).optional(),apiKey:i().min(1),baseUrl:i().nullable().optional(),apiBaseUrl:i().nullable().optional(),chatApiBaseUrl:i().nullable().optional(),environment:i().nullable().optional(),setActive:A().optional()});c({handle:i().min(1),currentBaseUrl:i().nullable().optional(),apiKey:i().min(1).optional(),baseUrl:i().nullable().optional(),apiBaseUrl:i().nullable().optional(),chatApiBaseUrl:i().nullable().optional(),environment:i().nullable().optional(),setActive:A().optional()});c({appId:i(),exists:A(),configPath:i().nullable().optional(),envVar:i().nullable(),toolName:i().nullable(),version:Tt([i(),u()]).nullable(),source:b(["hosted_env","local_file","defaults","missing"]),currentConfig:oe(i(),se()).nullable(),defaults:oe(i(),se()).nullable(),schema:oe(i(),se()).nullable(),error:i().nullable().optional(),updatedAt:i()}).passthrough();const au=b(["create_sandbox_template_scaffold","resource_read","resource_search","list_files","read_files","search_files","preview_write_files","preview_write_file","preview_edit_file","preview_delete_file","write_files","write_file","edit_file","delete_file","workspace_status","validate_sandbox_template","build_sandbox_template","run_sandbox_template","git_init","git_status","git_diff","git_fetch","git_commit","git_push","publish_openpond_repo","sandbox_create","sandbox_templates","sandbox_template_launch","sandbox_status","sandbox_start","sandbox_list_files","sandbox_read_file","sandbox_search_files","sandbox_upload_file","sandbox_write_file","sandbox_edit_file","sandbox_delete_file","sandbox_mkdir","sandbox_move_file","sandbox_exec","sandbox_git_status","sandbox_git_diff","sandbox_git_export_patch","sandbox_git_apply_patch_local","sandbox_git_branch","sandbox_git_commit","sandbox_git_pull","sandbox_git_push","sandbox_preserve_source","sandbox_promote_source","sandbox_run_action","sandbox_open_port","sandbox_snapshot_catalog","sandbox_snapshot_create","sandbox_snapshot_update","sandbox_snapshot_validate","sandbox_snapshot_publish","sandbox_replays","sandbox_replay_start","sandbox_replay_get","sandbox_replay_logs","sandbox_replay_artifacts","sandbox_replay_cancel","sandbox_logs","sandbox_receipts","sandbox_prepare_agent","sandbox_save_agent_package","sandbox_save_output","work_agent_package_install","work_output_delete","work_output_read","sandbox_schedule_create","sandbox_stop"]);c({action:au,args:oe(i(),se()).optional().default({}),source:b(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});c({ok:A(),action:au,appId:i().nullable().optional(),output:i(),data:se().optional()});const kc=c({id:i().trim().min(1).max(200),title:i().trim().min(1).max(240),sourceTaskId:i().trim().min(1).max(200),sourceTurnId:i().trim().min(1).max(200),revision:u().int().positive().default(1),createdAt:i().datetime()}),wc=c({kind:b(["structural","visual","test","user_review"]),status:b(["passed","failed","not_run"]),label:i().trim().min(1).max(240),detail:i().trim().max(4e3).nullable().optional(),ref:i().trim().max(4096).nullable().optional()}),X1=c({kind:S("local"),path:i().trim().min(1).max(4096),deviceId:i().trim().min(1).max(200)}),ew=c({kind:S("managed"),fileId:i().trim().min(1).max(200),downloadPath:i().trim().min(1).max(4096)}),TL=c({kind:S("external"),provider:i().trim().min(1).max(120),resourceId:i().trim().min(1).max(500),url:i().url().nullable()}),tw=kc.extend({kind:S("file"),contentType:i().trim().min(1).max(200),sizeBytes:u().int().nonnegative(),sha256:i().regex(/^[a-f0-9]{64}$/),location:vt("kind",[X1,ew,TL]),validation:p(wc).max(32).default([])}),EL=kc.extend({kind:S("source_change"),projectId:i().trim().min(1).max(200),ref:i().trim().min(1).max(500),url:i().url().nullable(),validation:p(wc).max(32).default([])}),ML=kc.extend({kind:S("deployment"),deploymentId:i().trim().min(1).max(200),url:i().url(),validation:p(wc).max(32).default([])}),jL=kc.extend({kind:S("external_resource"),provider:i().trim().min(1).max(120),resourceId:i().trim().min(1).max(500),url:i().url(),contentType:i().trim().min(1).max(200).nullable(),validation:p(wc).max(32).default([])}),nw=c({id:i().trim().min(1).max(191),label:i().trim().min(1).max(160).nullable(),description:i().trim().max(1e3).nullable(),inputSchema:oe(i(),se()).nullable(),outputSchema:oe(i(),se()).nullable(),schedulePolicy:oe(i(),se()).nullable()}),aw=c({base:i().trim().min(1).max(200),resources:oe(i(),se()),modelPolicy:oe(i(),se()).nullable(),setup:oe(i(),se()).nullable()}),OL=c({id:i().trim().min(1).max(200),kind:b(["sdk_validation","sdk_eval"]),status:b(["passed","failed"]),summary:i().trim().min(1).max(2e3),artifactPath:i().trim().min(1).max(4096),artifactSha256:i().regex(/^[a-f0-9]{64}$/)}),$L=c({path:i().trim().min(1).max(4096),sizeBytes:u().int().nonnegative(),sha256:i().regex(/^[a-f0-9]{64}$/),contentsBase64:i()});c({schema:S("openpond.agent-package.v1"),agentId:i().trim().min(1).max(191),versionId:i().trim().min(1).max(200),digest:i().regex(/^[a-f0-9]{64}$/),title:i().trim().min(1).max(240),source:c({files:p($L).min(1).max(1e3),totalSizeBytes:u().int().nonnegative()}),manifest:oe(i(),se()),actions:p(nw).min(1).max(256),runtimeRequirements:aw,receipts:p(OL).min(2).max(64)});const NL=kc.extend({kind:S("agent_package"),agentId:i().trim().min(1).max(191),versionId:i().trim().min(1).max(200),digest:i().regex(/^[a-f0-9]{64}$/),packageFileId:i().trim().min(1).max(200),manifestFileId:i().trim().min(1).max(200),actions:p(nw).min(1).max(256),runtimeRequirements:aw,validationReceiptIds:p(i().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:p(i().trim().min(1).max(200)).min(1).max(32),sourceFileCount:u().int().positive(),sourceSizeBytes:u().int().nonnegative(),location:vt("kind",[X1,ew]),validation:p(wc).max(32).default([])}),UX=vt("kind",[tw,EL,ML,jL,NL]);c({outputs:p(tw)});const DL=b(["sandbox_template","sandbox","generic_git","plain_folder"]),LL=b(["sandbox_template"]).nullable();c({productKind:DL,actions:c({files:A(),git:A(),sandboxRuntime:A(),sandboxTemplate:A()}),checks:c({validate:au.nullable(),build:au.nullable(),postEdit:LL}),ui:c({showSandboxTemplateActions:A(),showSandboxRuntimeActions:A()})});const HL=c({id:i(),name:i(),dnsName:i().nullable(),os:i().nullable(),online:A(),active:A(),isSelf:A(),tailscaleIps:p(i()),lastSeen:i().nullable()}),UL=c({installed:A(),running:A(),version:i().nullable(),backendState:i().nullable(),tailnetName:i().nullable(),magicDnsSuffix:i().nullable(),machineName:i().nullable(),dnsName:i().nullable(),authUrl:i().nullable(),tailscaleIps:p(i()),health:p(i()),error:i().nullable(),peers:p(HL)}),qL=c({enabled:A(),reachable:A(),targetUrl:i().nullable(),httpsUrl:i().nullable(),httpsHost:i().nullable(),httpsPort:u().nullable(),setupUrl:i().nullable(),configText:i().nullable(),error:i().nullable()}),zL=c({localUrl:i(),localWebUrl:i(),remoteUrl:i().nullable(),remoteWebUrl:i().nullable(),tokenHash:i(),tailscaleUpCommand:i(),serveCommand:i(),disableCommand:i(),operatorCommand:i(),webUiAvailable:A(),updatedAt:i(),tailscale:UL,serve:qL});c({message:i(),status:zL});const ow=b(["github","openpond_git"]),iw=b(["private","public"]),BL=b(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),FL=c({agentIds:p(i().trim().min(1)).max(100),skillNames:p(i().trim().min(1)).max(200),optionalContent:p(BL).max(20).default([])}),rw=c({provider:ow,owner:i().trim().min(1).max(191).nullable().optional(),repository:i().trim().min(1).max(191),visibility:iw.default("private")}),VL=c({ref:Co,selection:FL,target:rw}),KL=c({path:i(),sizeBytes:u().int().nonnegative(),category:i()});c({sourceHash:i(),sourceRevision:i().nullable(),clean:A(),blockedReasons:p(i()),warnings:p(i()),files:p(KL),excludedFiles:p(i()),target:rw,replacesExisting:A()});VL.extend({expectedSourceHash:i().trim().min(1),confirmed:S(!0)});c({provider:ow,owner:i(),repository:i(),visibility:iw,remoteUrl:i(),webUrl:i(),revision:i()});const WL=b(["cron","rate"]),sw=b(["queued","running","succeeded","failed","skipped"]),Kg=c({id:i(),localProjectId:i(),localProjectName:i(),agentRootPath:i(),agentName:i(),scheduleName:i(),scheduleType:WL,scheduleExpression:i(),timezone:i().nullable(),targetAction:i(),input:oe(i(),se()).optional().default({}),enabledByDefault:A(),enabled:A(),sourceHash:i(),manifestHash:i().nullable(),agentVersionId:i().nullable().optional(),agentPackageDigest:i().nullable().optional(),nextRunAt:i().nullable(),lastRunAt:i().nullable(),lastRunStatus:sw.nullable(),lastRunId:i().nullable(),lastError:i().nullable(),createdAt:i(),updatedAt:i()}),lw=c({id:i(),scheduleId:i(),definitionSnapshot:Kg.optional(),configurationSnapshot:oe(i(),se()).optional(),inputSnapshot:oe(i(),se()).optional(),localProjectId:i(),scheduleName:i(),scheduledFor:i(),trigger:b(["schedule","manual"]),status:sw,targetAction:i(),agentVersionId:i().nullable().optional(),agentPackageDigest:i().nullable().optional(),startedAt:i().nullable(),completedAt:i().nullable(),exitCode:u().int().nullable(),stdout:i().nullable(),stderr:i().nullable(),result:oe(i(),se()).nullable(),traceArtifactRef:i().nullable(),error:i().nullable(),createdAt:i(),updatedAt:i()});c({schedules:p(Kg),scheduler:c({running:A(),nextTickAt:i().nullable(),lastSyncAt:i().nullable(),scanRunning:A()})});c({runs:p(lw)});c({enabled:A().optional()});c({input:oe(i(),se()).optional()});c({schedule:Kg,run:lw});const GL=b(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),Ls=c({version:S(1),kind:b(["once","daily","weekdays","weekly","monthly"]),timeZone:i().trim().min(1).max(100),startDate:i().regex(/^\d{4}-\d{2}-\d{2}$/),localTime:i().regex(/^([01]\d|2[0-3]):([0-5]\d)$/),weekdays:p(GL).min(1).max(7).optional(),dayOfMonth:u().int().min(1).max(31).optional(),end:vt("kind",[c({kind:S("never")}),c({kind:S("on_date"),date:i().regex(/^\d{4}-\d{2}-\d{2}$/)}),c({kind:S("after_occurrences"),occurrences:u().int().min(1).max(1e5)})])}).superRefine((e,t)=>{e.kind==="weekly"&&!e.weekdays?.length&&t.addIssue({code:"custom",message:"Weekly recurrence requires at least one weekday.",path:["weekdays"]}),e.kind==="monthly"&&e.dayOfMonth===void 0&&t.addIssue({code:"custom",message:"Monthly recurrence requires a day of month.",path:["dayOfMonth"]})}),JL=c({id:i(),expression:i().nullable(),timeZone:i(),recurrence:Ls.nullable(),configurationVersion:u().int(),enabled:A(),nextRunAt:i().nullable(),lastTriggeredAt:i().nullable(),delivery:oe(i(),se()).default({})}),ZL=c({id:i(),definitionKey:i(),version:u().int(),name:i(),prompt:i(),modelId:i(),schedules:p(JL)}),YL=c({id:i(),definitionId:i(),scheduleId:i().nullable(),definitionName:i(),definitionVersion:u().int(),conversationId:i(),triggerKind:b(["manual","schedule","webhook","retry"]),status:i(),notificationStatus:i(),deliveryStatus:i(),deliveryError:i().nullable(),createdAt:i()});c({definitions:p(ZL),runs:p(YL),asOf:i(),webBaseUrl:i().url().optional()});c({clientRequestId:i().trim().min(1).max(191),sourceTurnId:i().trim().min(1).max(191).nullable().optional(),targetSessionId:i().trim().min(1).max(191).nullable().optional(),name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:Ls,modelId:i().trim().min(1).max(191).default("openpond-chat")});Tt([c({enabled:A()}),c({name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:Ls})]);const cw=b(["queued","running","succeeded","failed"]),dw=c({id:i(),sessionId:i(),sessionTitle:i(),sourceTurnId:i().nullable(),name:i(),prompt:i(),profileRef:Co.optional(),profileWorkflowId:i().optional(),profileMigrationError:i().nullable().optional(),recurrence:Ls,enabled:A(),nextRunAt:i().nullable(),lastRunAt:i().nullable(),lastRunStatus:cw.nullable(),lastRunId:i().nullable(),lastError:i().nullable(),scheduledRunCount:u().int().nonnegative(),createdAt:i(),updatedAt:i()}),QL=c({definitionSnapshot:dw.optional(),configurationSnapshot:oe(i(),se()).optional(),id:i(),workflowId:i(),sessionId:i(),scheduledFor:i(),trigger:b(["schedule","manual"]),status:cw,turnId:i().nullable(),error:i().nullable(),createdAt:i(),startedAt:i().nullable(),completedAt:i().nullable(),updatedAt:i()});c({sessionId:i().trim().min(1).max(191),sourceTurnId:i().trim().min(1).max(191).nullable().optional(),name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:Ls});Tt([c({enabled:A()}),c({name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:Ls})]);c({workflows:p(dw),runs:p(QL),asOf:i()});const Wg=oe(i(),se());c({userId:i(),role:b(["owner","admin","member"]),name:i(),handle:i().nullable(),image:i().nullable()});const XL=c({userId:i(),role:b(["owner","admin","member"]),name:i(),handle:i().nullable(),image:i().nullable(),lastReadSequence:u().int().nonnegative()}),eH=c({id:i(),messageId:i(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:i(),preview:Wg,createdAt:i()}),uw=c({id:i(),messageId:i().nullable(),clientAttachmentId:i(),kind:S("image"),name:i(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:b(["pending","ready","failed"]),createdAt:i(),readyAt:i().nullable()});c({attachment:uw,uploadUrl:i().url().nullable(),uploadHeaders:oe(i(),i()),expiresAt:i().nullable()});c({url:i().url(),expiresAt:i()});const Gg=c({id:i(),threadId:i(),teamId:i(),clientRequestId:i().nullable(),authorType:b(["user","agent","system"]),authorUserId:i().nullable(),authorAgentId:i().nullable(),sequence:u().int().nonnegative(),kind:b(["text","system","command_result"]),body:i(),metadata:Wg,editedAt:i().nullable(),deletedAt:i().nullable(),createdAt:i(),refs:p(eH),attachments:p(uw)}),tH=c({id:i(),teamId:i(),kind:b(["general","dm","group","channel"]),title:i().nullable(),createdByUserId:i(),lastMessageId:i().nullable(),lastMessageSequence:u().int().nonnegative(),lastMessageAt:i(),createdAt:i(),updatedAt:i(),unreadCount:u().int().nonnegative(),pinnedAt:i().nullable(),mutedAt:i().nullable(),archivedAt:i().nullable(),participants:p(XL),lastMessage:Gg.nullable()});c({thread:tH,messages:p(Gg),hasMoreBefore:A()});c({threadId:i(),mutedAt:i().nullable()});const nH=b(["pending","running","completed","failed","interrupted","cancelled"]),Wy=c({id:i(),conversationId:i(),threadId:i(),teamId:i(),requestedByUserId:i(),executorUserId:i().nullable(),providerId:i(),modelId:i(),clientRequestId:i(),baseMessageSequence:u().int().nonnegative(),status:nH,partialBody:i().nullable(),userMessageId:i(),assistantMessageId:i().nullable(),errorCode:i().nullable(),cancelledByUserId:i().nullable(),leaseExpiresAt:i().nullable(),heartbeatAt:i().nullable(),createdAt:i(),updatedAt:i()}),aH=c({id:i(),conversationId:i(),sequence:u().int().nonnegative(),role:b(["user","assistant","system","action"]),body:i(),createdByUserId:i().nullable(),createdAt:i()});c({conversationId:i(),parentThreadId:i(),parentMessageId:i(),teamId:i(),title:i().nullable(),providerId:i().nullable(),modelId:i(),createdByUserId:i(),messages:p(aH),turns:p(Wy),activeTurn:Wy.nullable(),createdAt:i(),updatedAt:i()});const mw=c({id:u().int().nonnegative(),teamId:i(),threadId:i(),conversationId:i().nullable(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:Wg,createdAt:i()});c({events:p(mw),cursor:u().int().nonnegative(),hasMore:A()});c({httpUrl:i().min(1),realtimeUrl:i().min(1),region:i().min(1),token:i().min(1),expiresAt:i().min(1),teamId:i().min(1),userId:i().min(1)});const Jg=oe(i(),se()),Ea=i().nullable(),oH=b(["draft","published","archived"]),Zg=b(["owner","admin","member"]),pw=b(["active","left"]),fw=b(["mentions","all","none"]),hw=b(["public_preview","members"]),iH=b(["members","admins"]),rH=c({canPreview:A(),canJoin:A(),canLeave:A(),canRead:A(),canPost:A(),canUpload:A(),canMention:A(),canManage:A(),requiresRulesAcceptance:A(),currentRulesVersionId:i().nullable()}),gw=c({id:i(),communityId:i(),version:u().int().positive(),title:i(),requiresReacceptance:A(),publishedAt:i()}),sH=gw.extend({bodyMarkdown:i(),contentHash:i()}),lH=c({role:Zg,status:pw,notificationMode:fw}),cH=c({id:i(),communityId:i(),userId:i(),role:Zg,status:pw,notificationMode:fw,joinedAt:i(),leftAt:Ea,createdAt:i(),updatedAt:i()}),vw=c({id:i(),slug:i(),displayName:i(),description:i(),imageUrl:i().nullable(),status:oH,visibility:b(["public","private"]),joinPolicy:b(["open","closed"]),historyVisibility:hw,featuredAt:Ea,publishedAt:Ea,archivedAt:Ea,memberCount:u().int().nonnegative(),membership:lH.nullable(),capabilities:rH,currentRules:gw.nullable()});c({items:p(vw),nextCursor:i().nullable()});const bw=c({lastReadSequence:u().int().nonnegative(),lastReadAt:Ea.optional(),mutedAt:Ea,pinnedAt:Ea}),Yg=c({id:i(),communityId:i(),chatThreadId:i().nullable(),slug:i(),displayName:i(),topic:i(),position:u().int().nonnegative(),visibility:hw,postingPolicy:iH,isDefault:A(),archivedAt:Ea,lastMessageSequence:u().int().nonnegative(),unreadCount:u().int().nonnegative(),readState:bw.nullable()});vw.omit({currentRules:!0}).extend({currentRules:sH.nullable(),channels:p(Yg),previewMessageLimit:u().int().positive()});const dH=c({id:i(),messageId:i(),refType:b(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:i(),preview:Jg,createdAt:i()}),yw=c({id:i(),messageId:i().nullable(),clientAttachmentId:i(),kind:S("image"),name:i(),mediaType:b(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:u().int().positive(),status:b(["pending","ready","failed"]),createdAt:i(),readyAt:Ea});c({attachment:yw,uploadUrl:i().url().nullable(),uploadHeaders:oe(i(),i()),expiresAt:Ea});c({url:i().url(),expiresAt:i()});const Sw=c({id:i(),threadId:i(),teamId:mc(),clientRequestId:i().nullable(),authorType:b(["user","agent","system"]),authorUserId:i().nullable(),authorAgentId:i().nullable(),sequence:u().int().nonnegative(),kind:b(["text","system","command_result"]),body:i(),metadata:Jg,editedAt:Ea,deletedAt:Ea,createdAt:i(),refs:p(dH),attachments:p(yw)});c({messages:p(Sw),hasMoreBefore:A(),channelId:i(),readState:bw.omit({lastReadAt:!0}).nullable(),preview:A()});const uH=c({userId:i(),handle:i().nullable(),name:i().nullable(),role:Zg});c({items:p(uH),nextCursor:i().nullable()});const xw=c({id:u().int().nonnegative(),communityId:i(),channelId:i(),threadId:i(),type:b(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:Jg,createdAt:i()});c({events:p(xw),cursor:u().int().nonnegative(),hasMore:A()});c({httpUrl:i().min(1),realtimeUrl:i().min(1),region:i().min(1),token:i().min(1),expiresAt:i().min(1),communityId:i().min(1),userId:i().min(1),channel:i().min(1)});c({membership:cH,channels:p(Yg)});c({channels:p(Yg)});var Gl=i().trim().min(1).max(500),mH=i().regex(/^[a-f0-9]{64}$/),ou=c({id:Gl,revision:u().int().positive(),contentHash:mH}).strict(),pH=c({schemaVersion:S("openpond.hostedTasksetSummary.v1"),id:Gl,teamId:Gl,release:ou,name:i().min(1).max(500),description:i().max(2e4),taskCount:u().int().nonnegative(),buildIntent:i().min(1).max(100),methodHint:i().min(1).max(100).nullable(),packageBytes:u().int().nonnegative().nullable(),storedBytes:u().int().nonnegative().nullable(),createdAt:i().datetime({offset:!0})}).strict();c({afterId:i().trim().min(1).max(2e3).optional(),limit:u().int().min(1).max(100).default(30),modelProjectId:Gl.optional(),projectId:Gl.optional(),search:i().trim().max(100).optional(),sort:b(["id","name","updated"]).default("id")}).strict();c({items:p(pH).max(100),nextCursor:i().trim().min(1).max(2e3).nullable()}).strict();c({code:i().min(1),message:i().min(1)}).strict();class kw extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}var ww=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},fH=ww((e,t)=>{"use strict";t.exports=function n(a,o){if(a===o)return!0;if(a&&o&&typeof a=="object"&&typeof o=="object"){if(a.constructor!==o.constructor)return!1;var r,s,l;if(Array.isArray(a)){if(r=a.length,r!=o.length)return!1;for(s=r;s--!==0;)if(!n(a[s],o[s]))return!1;return!0}if(a.constructor===RegExp)return a.source===o.source&&a.flags===o.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===o.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===o.toString();if(l=Object.keys(a),r=l.length,r!==Object.keys(o).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(o,l[s]))return!1;for(s=r;s--!==0;){var m=l[s];if(!n(a[m],o[m]))return!1}return!0}return a!==a&&o!==o}}),hH=ww(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=fH();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),Gy=Dt,Jy={type:["object","boolean"],properties:{$schema:{const:"https://json-schema.org/draft/2020-12/schema"},$ref:{type:"string"},$comment:{type:"string"},$defs:{$ref:"#/$defs/schemaMap"},properties:{$ref:"#/$defs/schemaMap"},dependentSchemas:{$ref:"#/$defs/schemaMap"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},prefixItems:{$ref:"#/$defs/schemaArray"},items:{$ref:"#"},additionalProperties:{$ref:"#"},not:{$ref:"#"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},contains:{$ref:"#"},unevaluatedProperties:{$ref:"#"},unevaluatedItems:{$ref:"#"},propertyNames:{$ref:"#"},type:{anyOf:[{$ref:"#/$defs/schemaType"},{type:"array",items:{$ref:"#/$defs/schemaType"},minItems:1,uniqueItems:!0}]},enum:{type:"array",minItems:1},const:!0,default:!0,title:{type:"string"},description:{type:"string"},examples:{type:"array"},readOnly:{type:"boolean"},writeOnly:{type:"boolean"},deprecated:{type:"boolean"},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/natural"},minLength:{$ref:"#/$defs/natural"},maxItems:{$ref:"#/$defs/natural"},minItems:{$ref:"#/$defs/natural"},maxContains:{$ref:"#/$defs/natural"},minContains:{$ref:"#/$defs/natural"},maxProperties:{$ref:"#/$defs/natural"},minProperties:{$ref:"#/$defs/natural"},uniqueItems:{type:"boolean"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}},contentEncoding:{type:"string"},contentMediaType:{type:"string"}}},gH=Object.prototype.hasOwnProperty,vH=hH().default,wt={validate:Dt};function ua(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=ua.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(e&&typeof e=="object"&&!Array.isArray(e))for(let h in e){let g=l;wt.validate(e[h],{instancePath:t+"/"+h.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:h,rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=g===l;if(!d)break}else return ua.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return ua.errors=s,l===0}ua.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function Rn(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=Rn.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){if(e.length>32)return Rn.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return Rn.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var d=!0;let h=e.length;for(let g=0;g<h;g++){let y=l;wt.validate(e[g],{instancePath:t+"/"+g,parentData:e,parentDataProperty:g,rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=y===l;if(!d)break}}}else return Rn.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return Rn.errors=s,l===0}Rn.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var bH={enum:["array","boolean","integer","null","number","object","string"]};function vo(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=vo.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),e==="array"||e==="boolean"||e==="integer"||e==="null"||e==="number"||e==="object"||e==="string"?(vo.errors=s,l===0):(vo.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:bH.enum}}],!1)}vo.evaluated={dynamicProps:!1,dynamicItems:!1};function Lt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=Lt.evaluated;return m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),typeof e=="number"&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e=="number"&&isFinite(e)&&(e<0||isNaN(e))?(Lt.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):(Lt.errors=s,l===0):(Lt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}Lt.evaluated={dynamicProps:!1,dynamicItems:!1};function Ra(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=Ra.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),l===0)if(Array.isArray(e)){var d=!0;let h=e.length;for(let g=0;g<h;g++){let y=l;if(typeof e[g]!="string")return Ra.errors=[{instancePath:t+"/"+g,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var d=y===l;if(!d)break}if(d){let g=e.length,y;if(g>1){let w={};for(;g--;){let _=e[g];if(typeof _=="string"){if(typeof w[_]=="number")return y=w[_],Ra.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:g,j:y}}],!1;w[_]=g}}}}}else return Ra.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return Ra.errors=s,l===0}Ra.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function Dt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,l=0,m=Dt.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),!(e&&typeof e=="object"&&!Array.isArray(e))&&typeof e!="boolean")return Dt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:Jy.type}}],!1;if(l===0&&e&&typeof e=="object"&&!Array.isArray(e)){let w=l;for(let _ in e)if(!gH.call(Jy.properties,_))return Dt.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:_}}],!1;if(w===l){if(e.$schema!==void 0){let _=l;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return Dt.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var d=_===l}else var d=!0;if(d){if(e.$ref!==void 0){let P=l;if(typeof e.$ref!="string")return Dt.errors=[{instancePath:t+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type:"string"}}],!1;var d=P===l}else var d=!0;if(d){if(e.$comment!==void 0){let M=l;if(typeof e.$comment!="string")return Dt.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var d=M===l}else var d=!0;if(d){if(e.$defs!==void 0){let C=l;ua(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:o,dynamicAnchors:r})||(s=s===null?ua.errors:s.concat(ua.errors),l=s.length);var d=C===l}else var d=!0;if(d){if(e.properties!==void 0){let $=l;ua(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:o,dynamicAnchors:r})||(s=s===null?ua.errors:s.concat(ua.errors),l=s.length);var d=$===l}else var d=!0;if(d){if(e.dependentSchemas!==void 0){let O=l;ua(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:o,dynamicAnchors:r})||(s=s===null?ua.errors:s.concat(ua.errors),l=s.length);var d=O===l}else var d=!0;if(d){if(e.allOf!==void 0){let j=l;Rn(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:o,dynamicAnchors:r})||(s=s===null?Rn.errors:s.concat(Rn.errors),l=s.length);var d=j===l}else var d=!0;if(d){if(e.anyOf!==void 0){let x=l;Rn(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:o,dynamicAnchors:r})||(s=s===null?Rn.errors:s.concat(Rn.errors),l=s.length);var d=x===l}else var d=!0;if(d){if(e.oneOf!==void 0){let R=l;Rn(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:o,dynamicAnchors:r})||(s=s===null?Rn.errors:s.concat(Rn.errors),l=s.length);var d=R===l}else var d=!0;if(d){if(e.prefixItems!==void 0){let E=l;Rn(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:o,dynamicAnchors:r})||(s=s===null?Rn.errors:s.concat(Rn.errors),l=s.length);var d=E===l}else var d=!0;if(d){if(e.items!==void 0){let H=l;wt.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=H===l}else var d=!0;if(d){if(e.additionalProperties!==void 0){let B=l;wt.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=B===l}else var d=!0;if(d){if(e.not!==void 0){let D=l;wt.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=D===l}else var d=!0;if(d){if(e.if!==void 0){let J=l;wt.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=J===l}else var d=!0;if(d){if(e.then!==void 0){let le=l;wt.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=le===l}else var d=!0;if(d){if(e.else!==void 0){let ue=l;wt.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=ue===l}else var d=!0;if(d){if(e.contains!==void 0){let je=l;wt.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=je===l}else var d=!0;if(d){if(e.unevaluatedProperties!==void 0){let ke=l;wt.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=ke===l}else var d=!0;if(d){if(e.unevaluatedItems!==void 0){let te=l;wt.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=te===l}else var d=!0;if(d){if(e.propertyNames!==void 0){let Me=l;wt.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:o,dynamicAnchors:r})||(s=s===null?wt.validate.errors:s.concat(wt.validate.errors),l=s.length);var d=Me===l}else var d=!0;if(d){if(e.type!==void 0){let ye=e.type,ne=l,be=l,ae=!1,de=l;vo(ye,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:o,dynamicAnchors:r})||(s=s===null?vo.errors:s.concat(vo.errors),l=s.length);var g=de===l;ae=ae||g;let xe=l;if(l===xe)if(Array.isArray(ye))if(ye.length<1){let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit:1}};s===null?s=[we]:s.push(we),l++}else{var h=!0;let we=ye.length;for(let ie=0;ie<we;ie++){let Se=l;vo(ye[ie],{instancePath:t+"/type/"+ie,parentData:ye,parentDataProperty:ie,rootData:o,dynamicAnchors:r})||(s=s===null?vo.errors:s.concat(vo.errors),l=s.length);var h=Se===l;if(!h)break}if(h){let ie=ye.length,Se;if(ie>1){e:for(;ie--;)for(Se=ie;Se--;)if(vH(ye[ie],ye[Se])){let Ue={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:ie,j:Se}};s===null?s=[Ue]:s.push(Ue),l++;break e}}}}else{let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type:"array"}};s===null?s=[we]:s.push(we),l++}var g=xe===l;if(ae=ae||g,ae)l=be,s!==null&&(be?s.length=be:s=null);else{let we={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return s===null?s=[we]:s.push(we),l++,Dt.errors=s,!1}var d=ne===l}else var d=!0;if(d){if(e.enum!==void 0){let ne=e.enum,be=l;if(l===be)if(Array.isArray(ne)){if(ne.length<1)return Dt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return Dt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var d=be===l}else var d=!0;if(d){if(e.title!==void 0){let be=l;if(typeof e.title!="string")return Dt.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var d=be===l}else var d=!0;if(d){if(e.description!==void 0){let ae=l;if(typeof e.description!="string")return Dt.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var d=ae===l}else var d=!0;if(d){if(e.examples!==void 0){let de=l;if(!Array.isArray(e.examples))return Dt.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var d=de===l}else var d=!0;if(d){if(e.readOnly!==void 0){let xe=l;if(typeof e.readOnly!="boolean")return Dt.errors=[{instancePath:t+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=xe===l}else var d=!0;if(d){if(e.writeOnly!==void 0){let De=l;if(typeof e.writeOnly!="boolean")return Dt.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var d=De===l}else var d=!0;if(d){if(e.deprecated!==void 0){let we=l;if(typeof e.deprecated!="boolean")return Dt.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var d=we===l}else var d=!0;if(d){if(e.multipleOf!==void 0){let ie=e.multipleOf,Se=l;if(l===Se)if(typeof ie=="number"&&isFinite(ie)){if(ie<=0||isNaN(ie))return Dt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return Dt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var d=Se===l}else var d=!0;if(d){if(e.maximum!==void 0){let Se=e.maximum,Ue=l;if(!(typeof Se=="number"&&isFinite(Se)))return Dt.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Ue===l}else var d=!0;if(d){if(e.exclusiveMaximum!==void 0){let Ue=e.exclusiveMaximum,Je=l;if(!(typeof Ue=="number"&&isFinite(Ue)))return Dt.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var d=Je===l}else var d=!0;if(d){if(e.minimum!==void 0){let Je=e.minimum,Ke=l;if(!(typeof Je=="number"&&isFinite(Je)))return Dt.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var d=Ke===l}else var d=!0;if(d){if(e.exclusiveMinimum!==void 0){let Ke=e.exclusiveMinimum,tt=l;if(!(typeof Ke=="number"&&isFinite(Ke)))return Dt.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var d=tt===l}else var d=!0;if(d){if(e.maxLength!==void 0){let tt=l;Lt(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:o,dynamicAnchors:r})||(s=s===null?Lt.errors:s.concat(Lt.errors),l=s.length);var d=tt===l}else var d=!0;if(d){if(e.minLength!==void 0){let ze=l;Lt(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:o,dynamicAnchors:r})||(s=s===null?Lt.errors:s.concat(Lt.errors),l=s.length);var d=ze===l}else var d=!0;if(d){if(e.maxItems!==void 0){let Ge=l;Lt(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:o,dynamicAnchors:r})||(s=s===null?Lt.errors:s.concat(Lt.errors),l=s.length);var d=Ge===l}else var d=!0;if(d){if(e.minItems!==void 0){let qe=l;Lt(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:o,dynamicAnchors:r})||(s=s===null?Lt.errors:s.concat(Lt.errors),l=s.length);var d=qe===l}else var d=!0;if(d){if(e.maxContains!==void 0){let L=l;Lt(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:o,dynamicAnchors:r})||(s=s===null?Lt.errors:s.concat(Lt.errors),l=s.length);var d=L===l}else var d=!0;if(d){if(e.minContains!==void 0){let N=l;Lt(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:o,dynamicAnchors:r})||(s=s===null?Lt.errors:s.concat(Lt.errors),l=s.length);var d=N===l}else var d=!0;if(d){if(e.maxProperties!==void 0){let q=l;Lt(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:o,dynamicAnchors:r})||(s=s===null?Lt.errors:s.concat(Lt.errors),l=s.length);var d=q===l}else var d=!0;if(d){if(e.minProperties!==void 0){let X=l;Lt(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:o,dynamicAnchors:r})||(s=s===null?Lt.errors:s.concat(Lt.errors),l=s.length);var d=X===l}else var d=!0;if(d){if(e.uniqueItems!==void 0){let me=l;if(typeof e.uniqueItems!="boolean")return Dt.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var d=me===l}else var d=!0;if(d){if(e.required!==void 0){let $e=l;Ra(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:o,dynamicAnchors:r})||(s=s===null?Ra.errors:s.concat(Ra.errors),l=s.length);var d=$e===l}else var d=!0;if(d){if(e.dependentRequired!==void 0){let Le=e.dependentRequired,nt=l;if(l===nt)if(Le&&typeof Le=="object"&&!Array.isArray(Le))for(let lt in Le){let pt=l;Ra(Le[lt],{instancePath:t+"/dependentRequired/"+lt.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:Le,parentDataProperty:lt,rootData:o,dynamicAnchors:r})||(s=s===null?Ra.errors:s.concat(Ra.errors),l=s.length);var y=pt===l;if(!y)break}else return Dt.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var d=nt===l}else var d=!0;if(d){if(e.contentEncoding!==void 0){let nt=l;if(typeof e.contentEncoding!="string")return Dt.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var d=nt===l}else var d=!0;if(d)if(e.contentMediaType!==void 0){let nt=l;if(typeof e.contentMediaType!="string")return Dt.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var d=nt===l}else var d=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return Dt.errors=s,l===0}Dt.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const Zy="https://json-schema.org/draft/2020-12/schema",yH=1048576,SH=32768,xH=new Set(["properties","$defs","dependentSchemas"]),kH=new Set(["allOf","anyOf","oneOf","prefixItems"]),wH=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function oi(e,t=yH){const n=[{value:e,depth:0}],a=new Set;let o=0;for(;n.length;){const r=n.pop();if(r.exit){a.delete(r.value);continue}if(++o>1e5||r.depth>48)throw new Error("task_json_complexity_exceeded");if(r.value===null||typeof r.value=="string"||typeof r.value=="boolean"||typeof r.value=="number"&&Number.isFinite(r.value))continue;if(typeof r.value!="object")throw new Error("task_json_value_invalid");if(a.has(r.value))throw new Error("task_json_cycle");a.add(r.value),n.push({...r,exit:!0});const s=Object.getPrototypeOf(r.value);if(!Array.isArray(r.value)&&s!==Object.prototype&&s!==null)throw new Error("task_json_object_invalid");if(Object.getOwnPropertySymbols(r.value).length)throw new Error("task_json_symbol_invalid");if(Object.hasOwn(r.value,"toJSON"))throw new Error("task_json_serializer_invalid");if(Array.isArray(r.value)&&(r.value.length>1e4||Object.keys(r.value).length!==r.value.length))throw new Error("task_json_array_invalid");for(const[l,m]of Object.entries(Object.getOwnPropertyDescriptors(r.value))){if(m.get||m.set)throw new Error("task_json_accessor_invalid");if(Array.isArray(r.value)&&l!=="length"&&(!/^(0|[1-9]\d*)$/u.test(l)||Number(l)>=r.value.length))throw new Error("task_json_array_invalid");m.enumerable&&n.push({value:m.value,depth:r.depth+1})}}if(new TextEncoder().encode(JSON.stringify(e)).byteLength>t)throw new Error("task_json_size_exceeded")}function Qg(e){try{return IH(e),{valid:!0,issues:[]}}catch(t){return{valid:!1,issues:[{path:"",code:"task_schema_invalid",message:t instanceof Error?t.message:"Task schema is invalid."}]}}}function IH(e){if(oi(e,SH),Cl(e,e,new Set,0,{remaining:2048}),!Gy(e)){const t=Gy.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function Cl(e,t,n,a,o){if(--o.remaining<0)throw new Error("Task schema reference expansion exceeds the validation budget.");if(typeof e=="boolean")return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A task schema must be an object or boolean.");if(a>24||n.has(e))throw new Error("Recursive or deeply nested task schemas are not supported.");const r=new Set(n).add(e),s=e;if(s.$schema!==void 0&&s.$schema!==Zy)throw new Error(`Task schemas must use ${Zy}.`);for(const[l,m]of Object.entries(s))if(l==="$ref"){if(typeof m!="string"||!m.startsWith("#/$defs/"))throw new Error("Task schema references must be local JSON pointers into $defs.");let d=t;for(const h of m.slice(2).split("/")){if(/~(?![01])/u.test(h))throw new Error("Invalid task schema JSON pointer.");const g=h.replaceAll("~1","/").replaceAll("~0","~");if(!d||typeof d!="object"||!Object.hasOwn(d,g))throw new Error(`Task schema reference ${m} is missing.`);d=d[g]}Cl(d,t,r,a+1,o)}else if(xH.has(l)){if(!m||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid schema map ${l}.`);for(const d of Object.values(m))Cl(d,t,r,a+1,o)}else if(kH.has(l)){if(!Array.isArray(m)||m.length>32)throw new Error(`Schema ${l} must contain at most 32 alternatives.`);for(const d of m)Cl(d,t,r,a+1,o)}else wH.has(l)&&Cl(m,t,r,a+1,o)}const _H=c({schemaVersion:S("openpond.modelJudgeReceipt.v1"),providerId:i().trim().min(1).max(200),modelId:i().trim().min(1).max(500),modelRevision:i().trim().min(1).max(500).nullable(),responseId:i().trim().min(1).max(500).nullable(),requestHash:F,responseHash:F,inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable()}).strict(),CH=c({schemaVersion:S("openpond.graderEvidence.v1"),graderId:T,graderVersion:i().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:pc.nullable(),feedback:p(i().max(2e4)).max(1e3),visibleEvidenceRefs:p(T).max(1e4),privilegedEvidenceRefs:p(T).max(1e4),modelJudgeReceipt:_H.optional()}).strict(),Iw=CH.extend({contentHash:F}).strict(),RH=c({score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:pc.nullable(),gradingStatus:b(["scored","unscorable","not_configured"])}).strict(),_w=RH.extend({schemaVersion:S("openpond.taskGrade.v1"),taskHash:F,evidenceHash:F,graderSetHash:F,components:p(Iw).max(1e3),contentHash:F}).strict(),Yy=i().trim().min(1).max(240),PH=i().trim().min(1).max(1e3).refine(e=>!/[\\:\0]/.test(e)&&e.split("/").every(t=>t&&t!=="."&&t!==".."&&!t.startsWith(".env")),"Metric modules must use a safe relative path."),Ic=c({schemaVersion:S("openpond.tasksetMetricPolicy.v1"),primaryMetric:Yy,aggregation:b(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:b(["zero","exclude"]),taskWeights:oe(Yy,u().positive().max(1e6)).optional(),customAggregator:c({module:PH,exportName:i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:F,timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}).strict().nullable()}).strict().superRefine((e,t)=>{e.aggregation==="custom"!=(e.customAggregator!==null)&&t.addIssue({code:"custom",path:["customAggregator"],message:"Only custom aggregation requires a content-hashed module."}),(e.aggregation==="weighted_mean"?!e.taskWeights||!Object.keys(e.taskWeights).length:e.taskWeights!==void 0)&&t.addIssue({code:"custom",path:["taskWeights"],message:"Only weighted means require explicit positive task weights."})}),AH=c({schemaVersion:S("openpond.tasksetMetricResult.v1"),runManifest:G,tasksetRelease:G,policy:Ic,policyHash:F,receiptRefs:p(G).min(1).max(1e6),includedCount:u().int().nonnegative(),missingRewardCount:u().int().nonnegative(),excludedCount:u().int().nonnegative(),value:u().min(0).max(1).nullable()}).strict(),Cw=AH.extend({contentHash:F}).strict(),to=b(["train","validation","test","frozen_eval"]),TH=c({path:i().trim().min(1).max(2e3).refine(MH),mediaType:i().trim().min(1).max(200),schemaRef:cn.nullable().default(null),maxBytes:u().int().positive().max(25e7).nullable().default(null),metadata:_n}).strict(),EH=c({policyVisibleFields:p(T).max(1e3).default([]),privilegedFields:p(T).max(1e3).default([]),hiddenGraderRefs:p(T).max(1e3).default([]),connectedAppScopes:p(T).max(100).default([])}).strict(),Rw=c({protocolVersion:S("openpond.environment.v1"),kind:b(["text","agent","work","custom_program"]),entrypoint:i().trim().min(1).max(1e3),stateful:A(),deterministicSeeds:A(),lifecycle:p(b(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:u().int().positive().max(36e5)}).strict(),zu=c({id:T,version:i().trim().min(1).max(100),weight:u().nonnegative().max(1e3).default(1),hardGate:A().default(!1),rewardEligible:A().default(!1),privileged:A().default(!1)}),Pw=zu.extend({kind:b(["content","schema","artifact","runtime_event","state"]),config:oe(i(),se())}).strict(),Aw=zu.extend({kind:S("model_judge"),rubricRef:cn,calibrationStatus:b(["pending","passed","failed"]),model:c({providerId:T,modelId:T,revision:i().trim().min(1).max(500).nullable()}).strict().optional(),temperature:u().min(0).max(2).optional()}).strict(),Tw=b(["isolated_javascript","sandbox_process"]),Ew=zu.extend({kind:S("custom_verifier"),runtime:Tw.optional(),verifierRef:cn,exportName:i().trim().min(1).max(240).optional(),timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}).strict(),Mw=zu.extend({kind:S("human"),rubricRef:cn,reviewerRole:i().trim().min(1).max(500)}).strict(),jw=Tt([Pw,Aw,Ew,Mw]),Xg=c({id:T,clusterKey:T,split:to,input:oe(i(),se()),expectedOutput:oe(i(),se()).nullable(),policyVisibleContext:oe(i(),se()).default({}),privilegedContextRef:T.nullable(),artifactRefs:p(cn).max(1e3).default([]),requiredOutputs:p(TH).max(1e3).optional(),tags:p(T).max(100).default([])}).strict(),Ow=c({schemaVersion:S("openpond.tasksetRelease.v2"),id:T,revision:u().int().positive(),policy:EH,environment:Rw,environmentRelease:c({id:T,contentHash:F}).strict().optional(),tools:p(yc).max(200),capabilities:p(Eg).max(200),tasks:p(Xg).min(1).max(1e6),graders:p(jw).min(1).max(1e3),verifierSetRelease:c({id:T,contentHash:F}).strict().optional(),metrics:Ic.optional(),metadata:_n}).strict(),$w=Ow.extend({contentHash:F}).strict();function MH(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const pd={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},Bu=i().regex(/^[a-z][a-z0-9_]{0,79}$/);function qX(e){return e.feedbackKey??`reward_${_t(e.id).slice(0,24)}`}const jH=Tt([Pw.omit(pd),Aw.omit(pd),Ew.omit(pd),Mw.omit(pd),c({kind:S("learned_model"),modelVersion:G,inputContract:cn}).strict()]),Nw=c({schemaVersion:S("openpond.rewardRelease.v1"),id:T,revision:u().int().positive(),name:i().trim().min(1).max(500),description:i().max(1e4),feedbackKey:Bu.optional(),implementation:jH,rawScore:c({minimum:u().finite(),maximum:u().finite()}).strict(),assets:p(cn).max(1e3),fixtureSetRef:cn.optional(),calibrationCheckRef:G.extend({revision:u().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>_t(n)===_t(e.fixtureSetRef)))&&t.addIssue({code:"custom",path:["fixtureSetRef"],message:"Reward fixtures must be included as a private verifier asset."}),e.rawScore.minimum>=e.rawScore.maximum&&t.addIssue({code:"custom",path:["rawScore"],message:"A raw score contract requires minimum < maximum."}),e.implementation.kind!=="learned_model"&&(e.rawScore.minimum!==0||e.rawScore.maximum!==1)&&t.addIssue({code:"custom",path:["rawScore"],message:"Portable graders currently return scores in [0, 1]."}),e.implementation.kind==="schema"){const n=Qg(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),Fu=Nw.safeExtend({contentHash:F}).strict(),Hs=G.extend({revision:u().int().positive()}).strict(),OH=vt("kind",[c({kind:S("identity")}).strict(),c({kind:S("linear"),minimum:u().finite(),maximum:u().finite(),direction:b(["higher","lower"])}).strict()]),$H=c({graderId:T,reward:Hs,role:b(["training","evaluation"]),normalization:OH,weight:u().nonnegative().max(1e3),required:A(),hardGate:A(),privileged:A(),fixtureRefs:p(G).max(1e3)}).strict(),NH=c({schemaVersion:S("openpond.rewardBinding.v1"),id:T,revision:u().int().positive(),name:i().trim().min(1).max(500).optional(),description:i().max(1e4).optional(),recipeRef:Hs.optional(),sources:p($H).max(100),aggregation:S("weighted_mean"),unscorable:S("exclude_optional_require_all_required")}).strict().superRefine((e,t)=>{new Set(e.sources.map(n=>n.graderId)).size!==e.sources.length&&t.addIssue({code:"custom",path:["sources"],message:"Bound grader identities must be unique."}),e.sources.length&&!e.sources.some(n=>n.weight>0)&&t.addIssue({code:"custom",path:["sources"],message:"A configured binding needs at least one positively weighted source."});for(const[n,a]of e.sources.entries())a.hardGate&&!a.required&&t.addIssue({code:"custom",path:["sources",n],message:"A hard gate must be required."}),a.normalization.kind==="linear"&&a.normalization.minimum>=a.normalization.maximum&&t.addIssue({code:"custom",path:["sources",n,"normalization"],message:"Linear normalization requires minimum < maximum."})}),Vu=NH.safeExtend({contentHash:F}).strict(),DH=c({graderId:T,reward:Hs,role:b(["training","evaluation"]),status:b(["scored","pending","unavailable","failed"]),rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),passed:A().nullable(),evidenceHashes:p(F).max(1e3),graderEvidence:Iw.optional(),message:i().max(2e4).nullable()}).strict(),LH=c({schemaVersion:S("openpond.rewardComposition.v1"),binding:Hs,taskHash:F,outputHash:F,results:p(DH).max(100),training:c({status:b(["scored","unscorable","not_configured"]),score:u().min(0).max(1).nullable(),passed:A().nullable()}).strict(),evaluation:c({status:b(["scored","unscorable","not_configured"]),score:u().min(0).max(1).nullable(),passed:A().nullable()}).strict()}).strict(),Jl=LH.extend({contentHash:F}).strict();function zX(e){oi(e);const t=Nw.parse(e);return Fu.parse({...t,contentHash:_t(t)})}const HH=c({text:i().max(1e5),modelId:i().trim().min(1).max(500),modelRevision:i().trim().min(1).max(500).nullable(),responseId:i().trim().min(1).max(500).nullable(),inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),costUsd:u().finite().nonnegative().nullable()}).strict(),UH=c({id:T,requestHash:F,reservedUsd:u().finite().positive(),status:b(["reserved","settled","not_dispatched"]),response:HH.nullable()}).strict().superRefine((e,t)=>{e.status==="settled"!=(e.response!==null)&&t.addIssue({code:"custom",path:["response"],message:"Only settled calls have a provider response."})}),Dw=c({localTime:i().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/),timeZone:i().min(1).max(200).refine(e=>{try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Choose a valid IANA timezone.")}).strict(),Vt=oe(i(),or()),kt=Hs,yi=i().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),qH=c({schemaVersion:S("openpond.taskDefinition.v1"),id:T,revision:u().int().positive(),name:i().trim().min(1).max(500),description:i().max(1e4),instructions:i().trim().min(1).max(2e4),category:b(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:T,inputSchema:oe(i(),se()),outputSchema:oe(i(),se()),requiredOutputs:Xg.shape.requiredOutputs,contextRequirements:p(i().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:kt,harness:G.nullable(),execution:Ow.pick({policy:!0,environment:!0,environmentRelease:!0,tools:!0,capabilities:!0,verifierSetRelease:!0}).strict()}).strict().superRefine((e,t)=>{for(const n of["inputSchema","outputSchema"]){const a=e[n];a.type!=="object"&&t.addIssue({code:"custom",path:[n],message:"Task input/output use object envelopes; declare type: object."});const o=Qg(a);o.valid||t.addIssue({code:"custom",path:[n],message:o.issues[0].message})}!!e.execution.environmentRelease!=!!e.execution.verifierSetRelease&&t.addIssue({code:"custom",path:["execution"],message:"Bind both the environment and verifier-set releases."})}),Ku=qH.safeExtend({contentHash:F}).strict(),zH=c({schemaVersion:S("openpond.taskSourceMapping.v1"),exampleId:yi,attemptId:yi,occurredAt:yi,input:yi,observedOutput:yi.nullable(),expected:yi.nullable(),evaluatorContext:yi.nullable(),familyKey:yi,split:to}).strict(),BH=c({modelId:T,packageHash:F,taskset:kt,batch:kt,rewardBinding:kt}).strict(),FH=c({schemaVersion:S("openpond.learningSource.v1"),id:T,revision:u().int().positive(),name:i().trim().min(1).max(500),kind:b(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:kt,enabled:A(),allowedSplits:p(to).min(1).max(4),mapping:zH.nullable(),adapterVersion:i().trim().min(1).max(200).nullable(),reviewOrigin:BH.optional()}).strict().superRefine((e,t)=>{e.kind!=="direct"&&!e.mapping&&t.addIssue({code:"custom",path:["mapping"],message:"Mapped sources require an explicit mapping."}),e.mapping&&!e.allowedSplits.includes(e.mapping.split)&&t.addIssue({code:"custom",path:["allowedSplits"],message:"The mapping split must be allowed by this source."}),["opentelemetry","provider"].includes(e.kind)&&!e.adapterVersion&&t.addIssue({code:"custom",path:["adapterVersion"],message:"Trace adapters require a pinned version."})}),ev=FH.safeExtend({contentHash:F}).strict(),VH=c({schemaVersion:S("openpond.taskExample.v1"),sourceId:T,idempotencyKey:T,taskDefinition:kt,exampleId:T,attemptId:T,occurredAt:Ce,familyKey:T.nullable(),split:to,input:Vt,observedOutput:Vt.nullable(),expected:Vt.nullable(),evaluatorContext:Vt.nullable(),assets:p(cn).max(1e3),requiredOutputs:Xg.shape.requiredOutputs,provenance:c({sourceRecordRef:i().max(2e3).nullable(),mappingHash:F.nullable()}).strict()}).strict(),KH=c({schemaVersion:S("openpond.taskEvidence.v1"),id:T,revision:u().int().positive(),source:kt,submission:VH,supersedes:kt.nullable(),correctionFeedbackId:T.nullable(),receivedAt:Ce}).strict(),Wu=KH.extend({contentHash:F}).strict(),WH=c({schemaVersion:S("openpond.taskRating.v1"),criteria:i().trim().min(1).max(2e4),scale:c({minimum:u().finite(),maximum:u().finite()}).strict(),score:u().finite(),evidence:i().max(2e4),explanation:i().max(2e4)}).strict().superRefine((e,t)=>{e.scale.minimum>=e.scale.maximum&&t.addIssue({code:"custom",path:["scale"],message:"The score scale must have an increasing range."}),(e.score<e.scale.minimum||e.score>e.scale.maximum)&&t.addIssue({code:"custom",path:["score"],message:"The score must be within its declared scale."})}),GH=c({schemaVersion:S("openpond.taskFeedback.v1"),sourceId:T,idempotencyKey:T,exampleId:T,attemptId:T,expectedEvidenceHash:F.nullable(),occurredAt:Ce,kind:b(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Vt,note:i().max(2e4)}).strict().superRefine((e,t)=>{if(e.value.schemaVersion!=="openpond.taskRating.v1")return;e.expectedEvidenceHash===null&&t.addIssue({code:"custom",path:["expectedEvidenceHash"],message:"A rating must identify the exact evidence revision."}),e.kind!=="outcome"&&t.addIssue({code:"custom",path:["kind"],message:"Ratings must be submitted as outcomes."});const n=WH.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),Lw=c({schemaVersion:S("openpond.taskFeedbackRecord.v1"),id:T,submission:GH,status:b(["pending_example","pending_review","applied","superseded","rejected"]),evidence:kt.nullable(),createdAt:Ce,revision:u().int().positive(),submittedBy:c({id:T,role:b(["editor","reviewer","source"]),sourceId:T.nullable()}).strict().nullable().default(null),review:c({actorId:T,decision:kt.nullable(),note:i().max(2e4),resolvedAt:Ce}).strict().nullable().default(null)}).strict(),JH=c({schemaVersion:S("openpond.taskAdmissionDecision.v1"),id:T,revision:u().int().positive(),evidence:kt,supersedes:kt.nullable(),actor:c({kind:b(["human","qualified_policy"]),id:T,policy:kt.nullable()}).strict(),evidenceValidity:b(["valid","invalid","pending"]),taskAdmissibility:b(["approved","rejected","pending"]),observedQuality:b(["passed","failed","unscored","unavailable"]),targetApproval:b(["approved","rejected","pending","not_required"]),approvedTarget:Vt.nullable(),grade:Jl.nullable(),targetGrade:Jl.nullable(),note:i().max(2e4),decidedAt:Ce}).strict().superRefine((e,t)=>{e.targetApproval==="approved"&&e.approvedTarget===null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Target approval requires an actual target."}),e.targetApproval!=="approved"&&e.approvedTarget!==null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Only approved targets may be selected for supervised learning."}),e.actor.kind==="qualified_policy"&&!e.actor.policy&&t.addIssue({code:"custom",path:["actor"],message:"Automatic admission must pin its qualified policy."}),e.taskAdmissibility==="approved"&&e.evidenceValidity!=="valid"&&t.addIssue({code:"custom",path:["taskAdmissibility"],message:"Only valid evidence can produce an approved task."})}),tv=JH.safeExtend({contentHash:F}).strict(),ZH=c({schemaVersion:S("openpond.taskBatch.v1"),id:T,revision:S(1),taskDefinition:kt,rewardBinding:kt,purpose:b(["supervised_training","reward_training","evaluation"]),examples:p(c({evidence:kt,decision:kt,familyKey:T,inputHash:F,split:to}).strict()).min(1).max(1e4),sealedAt:Ce,sealedBy:T}).strict().superRefine((e,t)=>{new Set(e.examples.map(a=>a.evidence.id)).size!==e.examples.length&&t.addIssue({code:"custom",path:["examples"],message:"Each evidence identity can occur only once in a batch."});const n=new Map;for(const[a,o]of e.examples.entries()){e.purpose==="evaluation"==(o.split==="train")&&t.addIssue({code:"custom",path:["examples",a,"split"],message:"Training uses train examples; evaluation uses held-out examples."});for(const r of[`family:${o.familyKey}`,`input:${o.inputHash}`])n.has(r)&&n.get(r)!==o.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(r,o.split)}}),Hw=ZH.safeExtend({contentHash:F}).strict(),YH=c({schemaVersion:S("openpond.learningPolicy.v1"),id:T,revision:u().int().positive(),modelProjectId:T,executionOwner:b(["local","hosted"]),enabled:A(),sources:p(kt).min(1).max(100),taskDefinition:kt,rewardBinding:kt,admission:c({mode:b(["human","qualified_automatic"]),qualification:G.nullable(),minimumApprovedExamples:u().int().positive().max(1e5)}).strict(),trigger:vt("kind",[c({kind:S("manual")}).strict(),c({kind:S("approved_count")}).strict(),c({kind:S("schedule"),intervalSeconds:u().int().min(60).max(31536e3)}).strict(),Dw.extend({kind:S("nightly")}).strict(),c({kind:S("upstream_accepted"),modelProjectId:T}).strict()]),trainingParent:G,teacher:G.nullable(),training:c({method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:G,retentionEvaluation:G,replayBatches:p(G).max(100)}).strict(),limits:c({maxIterationSpendUsd:u().positive().max(1e5),maxDailySpendUsd:u().positive().max(1e6),cooldownSeconds:u().int().nonnegative().max(31536e3),maxRetries:u().int().nonnegative().max(10),maxBatchExamples:u().int().positive().max(1e4),maxBacklogExamples:u().int().positive().max(1e6)}).strict(),automation:c({collect:A(),train:A(),accept:A(),serve:A()}).strict(),acceptance:c({minimumScore:u().min(0).max(1),maximumRetentionRegression:u().min(0).max(1),requireImprovement:A(),rollbackVersion:G.nullable()}).strict()}).strict().superRefine((e,t)=>{e.admission.mode==="qualified_automatic"&&!e.admission.qualification&&t.addIssue({code:"custom",path:["admission"],message:"Automatic admission requires qualification evidence."}),e.automation.serve&&!e.automation.accept&&t.addIssue({code:"custom",path:["automation"],message:"Automatic serving requires configured acceptance."}),e.automation.accept&&!e.acceptance.rollbackVersion&&t.addIssue({code:"custom",path:["acceptance"],message:"Automatic acceptance requires a rollback version."}),e.trigger.kind==="upstream_accepted"&&e.trigger.modelProjectId===e.modelProjectId&&t.addIssue({code:"custom",path:["trigger"],message:"A model cannot trigger itself through upstream acceptance."}),e.limits.maxBatchExamples<e.admission.minimumApprovedExamples&&t.addIssue({code:"custom",path:["limits"],message:"The batch limit must permit the minimum approved example count."}),e.limits.maxDailySpendUsd<e.limits.maxIterationSpendUsd&&t.addIssue({code:"custom",path:["limits"],message:"Daily spend must permit the iteration budget."})}),QH=YH.safeExtend({contentHash:F}).strict(),XH=c({iterationId:T,iterationRevision:u().int().positive(),candidate:G,decision:kt,decidedAt:Ce}).strict(),eU=b(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),tU=c({schemaVersion:S("openpond.learningIteration.v1"),id:T,revision:u().int().positive(),policy:kt,status:eU,triggerIdentity:T,batch:kt.nullable(),sourceWatermarks:oe(T,u().int().nonnegative()),trainingParent:G,trainingParentSelection:XH.nullable().optional(),teacher:G.nullable(),upstreamEvent:G.nullable(),trainingJob:G.nullable(),evaluationJob:G.nullable(),candidateVersion:G.nullable(),candidateDecision:kt.nullable().default(null),candidateDecisionAt:Ce.nullable().optional(),dispatchId:T,retryCount:u().int().nonnegative(),spendUsd:u().nonnegative(),failure:c({code:T,message:i().max(2e4)}).strict().nullable(),createdAt:Ce,updatedAt:Ce}).strict(),nU=c({schemaVersion:S("openpond.taskGradeRun.v1"),id:T,revision:u().int().positive(),evidence:kt,binding:kt,target:b(["observed","proposed_target"]),output:Vt,status:b(["queued","running","completed","failed","cancelling","cancelled"]),composition:Jl.nullable(),leaseOwner:T.nullable(),leaseExpiresAt:Ce.nullable(),attemptCount:u().int().nonnegative(),timeoutMs:u().int().min(100).max(3e5),maximumSpendUsd:u().nonnegative().max(1e3),judgeCalls:p(UH).max(1e4).optional(),requestedBy:T.optional(),failure:i().max(2e4).nullable(),createdAt:Ce,updatedAt:Ce}).strict();Tt([Ku,Fu,Vu,ev,Wu,Lw,tv,Hw,QH,tU,nU]);function aU(e){return kt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function BX(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function FX(e){return oi(e,16777216),{...e,contentHash:_t(e)}}function VX(e){const{contentHash:t,...n}=e;if(oi(n,16777216),_t(n)!==t)throw new kw("learning_content_hash_mismatch",422)}const Uw=c({schemaVersion:S("openpond.learningTextAsset.v1"),id:T,revision:S(1),asset:cn,text:i().max(524288)}).strict().superRefine((e,t)=>{e.asset.id!==e.id&&t.addIssue({code:"custom",path:["asset","id"],message:"Asset identity must match the stored resource."}),(e.asset.sizeBytes!==new TextEncoder().encode(e.text).byteLength||e.asset.sizeBytes>524288)&&t.addIssue({code:"custom",path:["asset","sizeBytes"],message:"Authored source must match its byte count and fit within 512 KiB."}),e.asset.contentHash!==ug(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),Gu=Uw.safeExtend({contentHash:F}).strict();function KX(e){oi(e);const{text:t,...n}=e,a=ug(t),o=`asset-${a}-${_t(n).slice(0,16)}`,r=Uw.parse({schemaVersion:"openpond.learningTextAsset.v1",id:o,revision:1,asset:{...n,id:o,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return Gu.parse({...r,contentHash:_t(r)})}function WX(e,t){const{contentHash:n,...a}=Gu.parse(e);if(_t(a)!==n||_t(a.asset)!==_t(t))throw new kw("learning_asset_reference_mismatch",409);return a.text}const Wa={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},qw=b(["json","jsonl","csv","hermes","openclaw"]),oU=c({path:i().min(1).max(500),text:i()}).strict(),nv=c({id:i().min(1).max(200),familyKey:i().min(1).max(200),split:to,kind:b(["task","attempt"]),input:Vt,observedOutput:Vt.nullable(),expected:Vt.nullable(),sourceId:i().min(1).max(2e3),sourceHash:i().length(64),occurredAt:i().datetime().nullable(),metadata:Vt,warnings:p(i().max(2e3)).max(100),needsContext:A()}).strict(),zw=c({schemaVersion:S("openpond.taskIntakePreview.v1"),format:qw,contentHash:i().length(64),records:p(nv).max(Wa.records),issues:p(c({file:i(),row:u().int().positive().nullable(),message:i()}).strict()).max(1e3)}).strict();function iu(e,t){return`${e}-${_t(t)}`}function Bw(e){if(typeof e!="string"&&typeof e!="number")return null;const t=new Date(typeof e=="number"?e*1e3:e);return Number.isFinite(t.getTime())?t.toISOString():null}function iU(e){const t=[];let n=[],a="",o=!1,r=!1;const s=()=>{n.push(a),a="",r=!1},l=()=>{if(s(),n.some(h=>h.length)&&t.push(n),n=[],t.length>Wa.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let h=0;h<e.length;h++){const g=e[h];if(o)g==='"'&&e[h+1]==='"'?(a+='"',h++):g==='"'?(o=!1,r=!0):a+=g;else if(g===",")s();else if(g===`
|
|
175
|
-
`||g==="\r")g==="\r"&&e[h+1]===`
|
|
176
|
-
`&&h++,l();else if(g==='"'&&!a&&!r)o=!0;else{if(r||g==='"')throw new Error("CSV has an invalid quoted field.");a+=g}}if(o)throw new Error("CSV has an unterminated quoted field.");(a||n.length||r)&&l();const m=t.shift()?.map(h=>h.trim().replace(/^\uFEFF/u,""));if(!m?.includes("instruction"))throw new Error("CSV requires an instruction column.");const d=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(m.some(h=>!d.has(h))||new Set(m).size!==m.length)throw new Error("CSV has duplicate or unsupported columns. Use instruction, context, reference, labels, id, familyKey and split.");return t.map((h,g)=>{if(h.length!==m.length)throw new Error(`CSV record ${g+2} has a different number of columns from its header.`);return Object.fromEntries(m.map((y,w)=>[y,h[w]]).filter(([,y])=>y!==""))})}function GX(e){try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}catch{throw new Error("Import files must contain valid UTF-8 text. Binary attachments are not supported by this import format.")}}function Fw(e){return e.startsWith("\uFEFF")?e.slice(1):e}const Vw=c({role:i().min(1),content:or().nullable().optional()}).catchall(or()),rU=c({id:i().min(1),messages:p(Vw).min(1).max(Wa.messages),lineage_session_ids:p(i()).optional(),parent_session_id:i().nullable().optional()}).catchall(or());function sU(e){const t=rU.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:o,...r}=t;return Kw("hermes",t.id,n,t.messages,{sourceHash:_t(e),metadata:{session:r},warnings:["Imported session context and tools need review before this can become an executable task."]})}const lU=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:i().min(1),sessionId:i().min(1),leafId:i().nullable(),eventCount:u().int().nonnegative(),warnings:p(Vt).optional()}).catchall(or()),cU=c({traceSchema:S("openclaw-trajectory"),schemaVersion:S(1),traceId:i(),sessionId:i(),seq:u().int().nonnegative(),type:i(),ts:i()}).catchall(or()),dU=c({header:Vt.nullable(),leafId:i().nullable(),entries:p(c({id:i().min(1),type:i().min(1),parentId:i().nullable().optional(),message:Vw.optional()}).catchall(or())).max(Wa.messages)}).strict();function uU(e){const t=l=>{const m=e.find(d=>d.path===l);if(!m)throw new Error(`OpenClaw bundle is missing ${l}.`);return Fw(m.text)},n=lU.parse(JSON.parse(t("manifest.json"))),a=dU.parse(JSON.parse(t("session-branch.json")));if(a.leafId!==n.leafId)throw new Error("OpenClaw manifest and session branch identify different leaves.");const o=t("events.jsonl").split(/\r?\n/u).filter(l=>l.trim()).map(l=>cU.parse(JSON.parse(l)));if(o.length!==n.eventCount||o.some(l=>l.traceId!==n.traceId||l.sessionId!==n.sessionId))throw new Error("OpenClaw events do not match the manifest identity or count.");if(a.header&&a.header.id!==n.sessionId)throw new Error("OpenClaw session header does not match the manifest.");const r=new Set;for(const[l,m]of a.entries.entries()){if(r.has(m.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(l&&m.parentId!==a.entries[l-1].id)throw new Error("OpenClaw branch is incomplete or out of order.");r.add(m.id)}if(a.entries.length&&a.entries.at(-1).id!==a.leafId)throw new Error("OpenClaw branch does not reach its declared leaf.");const s=a.entries.filter(l=>l.type==="message"&&l.message).map(l=>({...l.message,entryId:l.id,timestamp:typeof l.timestamp=="string"?l.timestamp:typeof l.message.timestamp=="number"?new Date(l.message.timestamp).toISOString():null}));return Kw("openclaw",n.sessionId,n.sessionId,s,{sourceHash:_t(e),metadata:{manifest:n,sourceFiles:e.map(l=>l.path)},warnings:["Imported trajectory context and tools need review before this can become an executable task.",...(n.warnings??[]).map(l=>typeof l.message=="string"?l.message.slice(0,2e3):"The source exporter reported incomplete context.")]})}function Kw(e,t,n,a,o){const r=a.flatMap((l,m)=>l.role==="user"?[m]:[]);if(!r.length)throw new Error("This history contains no user request. Supply a session with its request context.");let s=0;return r.map((l,m)=>{const d=r[m+1]??a.length,h=a.slice(l+1,d),g=h.filter(P=>P.role==="assistant").at(-1),y=a[l],w=y.entryId??y.message_id??y.id??_t({start:l,request:y}),_={id:iu(e,[t,w]),familyKey:iu(e,n),split:"train",kind:"attempt",input:{request:y.content??null,messages:a.slice(0,l+1)},observedOutput:g?{response:g.content??null,messages:h}:null,expected:null,sourceId:`${e}:${t}:${String(w)}`,sourceHash:o.sourceHash,occurredAt:Bw(g?.timestamp??y.timestamp),metadata:o.metadata,warnings:[...o.warnings,...g?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(oi(_),s+=new TextEncoder().encode(JSON.stringify(_)).length,s>Wa.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return nv.parse(_)})}const mU=c({instruction:i().trim().min(1).max(1e5),context:Tt([i(),Vt]).optional(),reference:Tt([i(),Vt]).optional(),labels:Tt([i(),p(i()),Vt]).optional(),id:i().min(1).max(200).optional(),familyKey:i().min(1).max(200).optional(),split:to.optional()}).strict(),pU=c({input:Vt,observedOutput:Vt.nullable().optional(),expectedOutput:Vt.nullable().optional(),id:i().min(1).max(200).optional(),familyKey:i().min(1).max(200).optional(),split:to.optional(),occurredAt:i().datetime().optional(),labels:Vt.optional()}).strict();function fU(e){const t=qw.parse(e.format),n=p(oU).min(1).max(Wa.files).parse(e.files);if(n.reduce((d,h)=>d+new TextEncoder().encode(h.text).length,0)>Wa.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(d=>d.path.startsWith("/")||d.path.includes("\\")||d.path.split("/").some(h=>!h||h==="."||h===".."))||new Set(n.map(d=>d.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],o=[],r=new Map,s=new Map;let l=0;function m(d,h,g){try{const y=g();if(a.length+y.length>Wa.records)throw new Error("Import exceeds the 1,000-record limit.");const w=new Map(r),_=new Map(s);let P=0;for(const M of y){oi(M);const C=_t(M),$=w.get(M.id);if($&&$!==C)throw new Error("The same record identity has different content in this upload.");$||(P+=new TextEncoder().encode(JSON.stringify(M)).length),w.set(M.id,C);for(const O of[`family:${M.familyKey}`,`input:${_t(M.input)}`]){if(_.has(O)&&_.get(O)!==M.split)throw new Error("The same task family or request occurs in different splits.");_.set(O,M.split)}}if(l+P>Wa.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const M of y)r.has(M.id)||a.push(M),r.set(M.id,_t(M));for(const[M,C]of _)s.set(M,C);l+=P}catch(y){o.push({file:d,row:h,message:y instanceof ZM?`Unsupported record fields or values (${y.issues.slice(0,3).map(w=>w.path.join(".")||"record").join(", ")}).`:y instanceof SyntaxError?"Invalid JSON.":y instanceof Error?y.message:"Invalid import record."})}}if(t==="openclaw")m("manifest.json",null,()=>uU(n));else for(const d of n){const h=Fw(d.text);if(t==="jsonl"||t==="hermes"){for(const[g,y]of h.split(/\r?\n/u).entries())if(y.trim()){if(o.length>=Wa.records)break;m(d.path,g+1,()=>t==="hermes"?sU(JSON.parse(y)):[Qy(JSON.parse(y))])}}else{let g;try{const y=t==="csv"?iU(h):JSON.parse(h);g=Array.isArray(y)?y:[y]}catch(y){m(d.path,null,()=>{throw y});continue}if(g.length>Wa.records){m(d.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}g.forEach((y,w)=>m(d.path,w+(t==="csv"?2:1),()=>[Qy(y)]))}}return zw.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:_t({format:t,files:n}),records:a,issues:o.slice(0,1e3)})}function Qy(e){const t=Tt([mU,pU]).parse(e),n="instruction"in t,a=n?{instruction:t.instruction,...t.context===void 0?{}:{context:t.context}}:t.input,o=n?t.reference===void 0?null:typeof t.reference=="string"?{text:t.reference}:t.reference:t.expectedOutput??null,r=n?null:t.observedOutput??null,s=t.familyKey??iu("family",a),l=t.id??iu("task",{input:a,expected:o,observedOutput:r});return nv.parse({id:l,familyKey:s,split:t.split??"train",kind:r?"attempt":"task",input:a,expected:o,observedOutput:r,sourceId:l,sourceHash:_t(e),occurredAt:n?null:Bw(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}const Zl=i().trim().min(1).max(240),ki=i().regex(/^[a-f0-9]{64}$/),hU=c({id:Zl,name:i().trim().min(1).max(200),required:A(),role:b(["quality","retention","diagnostic"]).optional(),unit:i().trim().min(1).max(80).optional(),baselineReuse:c({maximumAgeSeconds:u().int().positive().max(31536e3),qualification:G}).strict().optional(),dataset:G,evaluator:G,executionHash:ki,populationHash:ki,metric:Zl,direction:b(["higher","lower"]),minimumCoverage:u().positive().max(1),threshold:u().finite(),maximumRegression:u().finite().nonnegative(),maximumSpendUsd:u().finite().positive()}).strict().superRefine((e,t)=>{e.role==="diagnostic"&&e.required&&t.addIssue({code:"custom",message:"Diagnostic checks cannot be required acceptance gates."})}),gU=c({schemaVersion:S("openpond.acceptancePlan.v1"),id:Zl,revision:u().int().positive(),checks:p(hU).min(1).max(100),maximumSpendUsd:u().finite().positive()}).strict().superRefine((e,t)=>{new Set(e.checks.map(n=>n.id)).size!==e.checks.length&&t.addIssue({code:"custom",message:"Acceptance check IDs must be unique."}),e.checks.some(n=>n.required)||t.addIssue({code:"custom",message:"An acceptance plan needs at least one required check."}),e.checks.reduce((n,a)=>n+a.maximumSpendUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Check budgets exceed the total plan budget."})}),vU=gU.safeExtend({contentHash:ki}),bU=c({runId:Zl,artifact:G,checkHash:ki,populationHash:ki,scoredPopulationHash:ki,executionHash:ki,evaluator:G,metric:Zl,expectedCount:u().int().positive(),scoredCount:u().int().nonnegative(),score:u().finite().nullable(),status:b(["pending","running","completed","failed","cancelled"]),evidenceHash:ki}).strict().superRefine((e,t)=>{e.scoredCount>e.expectedCount&&t.addIssue({code:"custom",message:"Scored count exceeds declared population."}),e.scoredCount===0!=(e.score===null)&&t.addIssue({code:"custom",message:"Scores require a nonempty scored population."})}),wi=i().trim().min(1).max(240),av=i().regex(/^[a-f0-9]{64}$/),ru=wn(),Xy=u().finite().nonnegative(),yU=new Set(["completed","failed","cancelled","budget_exhausted"]),SU=c({schemaVersion:S("openpond.acceptanceGroupManifest.v1"),id:wi,teamId:wi,trainingJob:G,baseline:G,candidate:G,plan:vU,maximumParallelAttempts:u().int().min(1).max(8),createdAt:ru}).strict().superRefine((e,t)=>{e.plan.checks.some(n=>!n.role||!n.unit)&&t.addIssue({code:"custom",message:"Durable acceptance checks require explicit roles and score units."})}),xU=SU.safeExtend({contentHash:av}),kU=c({id:wi,checkId:wi,subject:b(["baseline","candidate"]),ordinal:u().int().positive(),dispatchId:wi,state:b(["queued","dispatching","running","grading","cleaning","completed","failed","cancelled","budget_exhausted"]),artifact:G,checkHash:av,measurement:bU.nullable(),executionReceipt:G.nullable(),reusedFrom:c({group:G,attemptId:wi}).strict().nullable(),spendUsd:Xy,reservedUsd:Xy,cleanupComplete:A(),accountingComplete:A(),failureCode:wi.nullable(),createdAt:ru,updatedAt:ru}).strict().superRefine((e,t)=>{Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&t.addIssue({code:"custom",message:"Attempt timestamps are reversed."}),yU.has(e.state)&&(!e.cleanupComplete||!e.accountingComplete||e.reservedUsd!==0)&&t.addIssue({code:"custom",message:"Terminal attempts require cleanup and settled accounting."}),e.state==="completed"&&(e.measurement?.status!=="completed"||!e.executionReceipt)&&t.addIssue({code:"custom",message:"Completed attempts require retained measurement and execution receipts."}),e.reusedFrom&&(e.subject!=="baseline"||e.state!=="completed"||e.spendUsd!==0)&&t.addIssue({code:"custom",message:"Only completed baselines may reuse retained evidence without new spend."})}),wU=c({schemaVersion:S("openpond.acceptanceGroupSnapshot.v1"),manifest:xU,revision:u().int().positive(),state:b(["queued","running","blocked","cancelling","cleaning","completed","failed","cancelled","budget_exhausted"]),attempts:p(kU).max(2e3),failureCode:wi.nullable(),updatedAt:ru}).strict(),IU=wU.extend({contentHash:av});var rr=kt.shape.id,Yl=i().regex(/^[a-f0-9]{64}$/),_U=c({scopeId:rr,modelId:rr}).strict(),CU=c({schemaVersion:S("openpond.modelTasksetAuthoring.v1"),owner:_U,root:kt,parent:kt}).strict(),JX=c({schemaVersion:S("openpond.modelTasksetDraftRequest.v1"),operationId:rr,modelId:rr,expectedModelRevision:u().int().positive(),sourcePackageHash:Yl}).strict(),RU=c({schemaVersion:S("openpond.modelTasksetDraftPreparation.v1"),draftId:rr,requestHash:Yl,sourcePackageHash:Yl,sourceTasksetRef:kt,tasksetId:rr,tasksetRevision:u().int().positive(),lineage:CU,authoringGraph:S("bound").optional()}).strict(),_c=i().min(1).max(1024).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.includes("\0")&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."||t.startsWith(".env")),"Use a relative Taskset file path without environment files."),Ww=c({path:_c,sizeBytes:u().int().nonnegative(),writable:A()}).strict(),Gw=c({encoding:b(["utf8","base64"]),data:i().max(8e6)}).strict(),PU=Ww.extend({contentHash:Yl,content:Gw}).strict();c({draftId:rr,expectedDraftRevision:u().int().positive(),path:_c,expectedFileHash:Yl.nullable(),content:Gw.nullable()}).strict();var AU=Dw.extend({mode:b(["nightly","approved_count"]),minimumTasks:u().int().min(1).max(1e4),maximumSpendUsd:u().positive().max(1e5),maximumDailySpendUsd:u().positive().max(1e6)}).strict().superRefine((e,t)=>{e.maximumDailySpendUsd<e.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumDailySpendUsd"],message:"The daily budget must cover one update."})}),TU=67108864,fh=524288,Rl=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function ov(e){return JSON.stringify(hh(e))}function EU(e){return new TextEncoder().encode(ov(e)).byteLength}async function MU(e){const t=new TextEncoder().encode(ov(e)),n=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),a=>a.toString(16).padStart(2,"0")).join("")}function jU(e,t,n){const a=EU(e);if(a>t)throw new Rl("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function hh(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new Rl("non_json_value","Canonical JSON cannot contain a non-finite number.");return Object.is(e,-0)?0:e}if(Array.isArray(e))return e.map(t=>hh(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new Rl("non_json_value","Canonical JSON accepts only plain objects.");const n={};for(const a of Object.keys(e).sort()){const o=e[a];if(o===void 0||typeof o=="function"||typeof o=="symbol")throw new Rl("non_json_value",`Canonical JSON cannot contain ${typeof o} at ${a}.`);n[a]=hh(o)}return n}throw new Rl("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var Ot=i().trim().min(1).max(500),yo=i().regex(/^[a-f0-9]{64}$/),Ma=i().datetime({offset:!0}),Rt=c({id:Ot,contentHash:yo}).strict(),Wn=Rt.extend({revision:u().int().positive()}).strict(),gr=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:Ot,revision:i().trim().min(1).max(256).nullable(),tokenizerRevision:i().trim().min(1).max(256).nullable(),chatTemplateHash:i().trim().min(8).max(256).nullable(),modelAssetId:Ot.nullable(),source:b(["managed","local","builtin"])}).strict(),Jw=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),Zw=c({schemaVersion:i().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:Jw,parameterization:b(["lora","full"])}).catchall(se()),OU=c({profileProjectId:Ot,sourceRevision:i().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Rt}).strict(),$U=c({profileProjectId:Ot,sourceRevision:i().regex(/^[a-f0-9]{40,64}$/),catalogHash:yo,definitionId:Ot,harnessRelease:Rt,tasksetRelease:Rt}).strict(),Yw=c({tasksetRef:Wn.nullable().default(null),evaluationTasksetRef:Wn.nullable().optional(),profileSource:OU.nullable().optional(),profileEvaluation:$U.nullable().optional(),rewardBindingRef:Wn.nullable().optional(),tasksetRelease:Rt.nullable().default(null),harnessRelease:Rt.nullable().default(null),baseModel:gr.nullable().default(null),method:Jw.nullable().default(null),destinationId:Ot.nullable().default(null),managedRolloutPlacement:b(["local","remote"]).default("remote"),managedGpuPlacementObjective:b(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:b(["any","h100_hbm3"]).default("any"),runPreset:b(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:Zw.nullable().default(null),preferredMaximumSpendUsd:u().nonnegative().nullable().default(null),preferredRetentionDays:u().int().nonnegative().nullable().default(null)}).strict(),iv=Yw.omit({managedGpuRequirement:!0}),NU=c({schemaVersion:S("openpond.hostedModelProjectLink.v1"),apiOrigin:i().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:Ot,projectId:Ot,portableProjectId:Ot,revision:u().int().positive(),etag:yo,syncedSourceRevision:u().int().positive(),syncedAt:Ma,tasksets:p(c({localTasksetId:Ot,localTasksetHash:yo.nullable().default(null),releaseId:Ot,releaseRevision:u().int().positive(),releaseHash:yo,packageHash:yo.nullable().default(null),hostedTasksetId:Ot,syncedAt:Ma}).strict()).max(1e4).default([])}).strict(),DU=c({localTasksetId:Ot,releaseId:Ot,releaseRevision:u().int().positive(),releaseHash:yo,state:b(["syncing","synced","sync_failed"]),hostedTasksetId:Ot.nullable().default(null),lastAttemptAt:Ma,syncedAt:Ma.nullable().default(null),lastError:i().trim().min(1).max(5e3).nullable().default(null)}).strict(),Qw=c({schemaVersion:S("openpond.modelProject.v2"),id:Ot,profileId:Ot,revision:u().int().positive().default(1),name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:gr.nullable(),defaultDestinationId:Ot.nullable(),trainingSetup:Yw,hosted:NU.nullable().default(null),tasksetSyncs:p(DU).max(1e4).default([]),createdAt:Ma,updatedAt:Ma}).strict(),Xw=Qw.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),LU=c({schemaVersion:S("openpond.modelProjectSave.v1"),operationId:Ot,expectedRevision:u().int().nonnegative(),project:Xw,learning:AU.optional()}).strict().superRefine((e,t)=>{e.learning&&e.expectedRevision!==0&&t.addIssue({code:"custom",path:["learning"],message:"Use learning settings to edit an existing Model's policy."})}),eI=c({schemaVersion:S("openpond.modelProjectConfigurationCheck.v1"),configurationHash:yo,projectId:Ot,expectedRevision:u().int().nonnegative(),checkedAt:Ma,canSave:A(),deferred:p(b(["base_model","taskset"])).max(2),findings:p(c({code:Ot,severity:b(["error","warning"]),message:i().min(1).max(5e3),field:i().min(1).max(500).nullable()}).strict()).max(100)}).strict();c({id:Ot,name:i().min(1).max(500),available:A(),preference:gr}).strict();function HU(e){try{oi(e,fh)}catch{throw new BU(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return LU.parse(e)}async function UU(e,t,n){oi(e,fh);const a=Xw.parse(e);jU(a,fh,"Model configuration");const o=await MU({project:a,expectedRevision:t});return HU({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${o}`,expectedRevision:t,project:a})}var qU=c({schemaVersion:S("openpond.hostedModelProjectSync.v2"),portableProjectId:Ot,name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:gr.nullable(),defaultDestinationId:Ot.nullable(),trainingSetup:iv,sourceRevision:u().int().positive(),sourceUpdatedAt:Ma,expectedEtag:yo.nullable().default(null)}).strict(),tI=c({id:Ot,teamId:Ot,portableProjectId:Ot,name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:gr.nullable(),defaultDestinationId:Ot.nullable(),trainingSetup:iv,sourceRevision:u().int().positive(),sourceUpdatedAt:Ma,revision:u().int().positive(),etag:yo,createdAt:Ma,updatedAt:Ma}).strict(),zU=c({kind:b(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Rt,role:i().trim().min(1).max(200).nullable().default(null),updatedAt:Ma}).strict();c({project:tI,resources:p(zU).max(1e4),jobCount:u().int().nonnegative(),latestJobIds:p(Ot).max(100)}).strict();c({schemaVersion:S("openpond.modelProjectApiError.v2"),code:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3),retryable:A().default(!1),requestId:i().trim().min(1).max(500).nullable().default(null),details:oe(i(),se()).default({})}).strict();var BU=class extends Error{status;code;retryable;requestId;details;constructor(e,t){super(t.message),this.name="OpenPondModelProjectApiError",this.status=e,this.code=t.code,this.retryable=t.retryable,this.requestId=t.requestId,this.details=t.details}},FU=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),VU=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function KU(e){const t=typeof e=="string"?new TextEncoder().encode(e):e,n=Math.ceil((t.byteLength+9)/64)*64,a=new Uint8Array(n);a.set(t),a[t.byteLength]=128;const o=t.byteLength*8,r=new DataView(a.buffer);r.setUint32(n-8,Math.floor(o/4294967296),!1),r.setUint32(n-4,o>>>0,!1);const s=new Uint32Array(FU),l=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let C=0;C<16;C+=1)l[C]=r.getUint32(m+C*4,!1);for(let C=16;C<64;C+=1){const $=l[C-15],O=l[C-2],j=po($,7)^po($,18)^$>>>3,x=po(O,17)^po(O,19)^O>>>10;l[C]=l[C-16]+j+l[C-7]+x>>>0}let d=s[0],h=s[1],g=s[2],y=s[3],w=s[4],_=s[5],P=s[6],M=s[7];for(let C=0;C<64;C+=1){const $=w&_^~w&P,O=d&h^d&g^h&g,j=po(d,2)^po(d,13)^po(d,22),x=po(w,6)^po(w,11)^po(w,25),R=M+x+$+VU[C]+l[C]>>>0,E=j+O>>>0;M=P,P=_,_=w,w=y+R>>>0,y=g,g=h,h=d,d=R+E>>>0}s[0]=s[0]+d>>>0,s[1]=s[1]+h>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+y>>>0,s[4]=s[4]+w>>>0,s[5]=s[5]+_>>>0,s[6]=s[6]+P>>>0,s[7]=s[7]+M>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function po(e,t){return e>>>t|e<<32-t}var WU=2e3,nI=25e7,Fe=i().trim().min(1).max(240),Qe=i().regex(/^[a-f0-9]{64}$/),It=i().datetime({offset:!0}),Ju=oe(i(),se()).default({}),Ze=c({id:Fe,contentHash:Qe}).strict(),GU=Ze.extend({revision:u().int().positive()}).strict(),Fo=c({id:Fe,path:i().trim().min(1).max(WU).refine(YU),contentHash:Qe,sizeBytes:u().int().nonnegative().max(nI),mediaType:i().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"])}).strict(),JU=c({id:Fe,contentHash:Qe,mediaType:i().trim().min(1).max(200).nullable().default(null),sizeBytes:u().int().nonnegative().max(nI).nullable().default(null)}).strict(),aI=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function ZU(e){return`${JSON.stringify(gh(e),null,2)}
|
|
177
|
-
`}function oI(e){return KU(e)}function fa(e){return oI(ZU(e))}function YU(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function gh(e){return Array.isArray(e)?e.map(gh):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,gh(n)]))}var QU=b(["memory","prompt","skill","agent"]),XU=b(["runtime","product","taskset","training"]),eq=c({id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:i().trim().min(1).max(1e4)}).strict(),tq=c({schemaVersion:S("openpond.refinerReviewProfile.v1"),id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),version:i().trim().min(1).max(120),name:i().trim().min(1).max(200),objective:i().trim().min(1).max(1e4),instructions:p(eq).max(100),allowedProposalRoutes:p(QU).max(4),allowedExternalRoutes:p(XU).max(4)}).strict().superRefine((e,t)=>{const n=e.instructions.map(a=>a.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"instruction IDs must be unique",path:["instructions"]}),new Set(e.allowedProposalRoutes).size!==e.allowedProposalRoutes.length&&t.addIssue({code:"custom",message:"proposal routes must be unique",path:["allowedProposalRoutes"]}),new Set(e.allowedExternalRoutes).size!==e.allowedExternalRoutes.length&&t.addIssue({code:"custom",message:"external routes must be unique",path:["allowedExternalRoutes"]})});c({schemaVersion:S("openpond.refinerRelease.v1"),id:i().trim().min(1).max(240),coreVersion:i().trim().min(1).max(120),coreHash:Qe,profile:tq,profileHash:Qe,composedPromptHash:Qe,createdAt:It,contentHash:Qe}).strict();c({schemaVersion:S("openpond.refinerBinding.v1"),channel:S("active"),revision:u().int().nonnegative(),release:Ze,updatedAt:It}).strict();c({schemaVersion:S("openpond.refinerTransitionReceipt.v1"),id:i().trim().min(1).max(240),operation:b(["initialize","update","activate","rollback"]),bindingChanged:A(),previousRelease:Ze.nullable(),nextRelease:Ze,actor:i().trim().min(1).max(240),reason:i().trim().min(1).max(1e4),authoringSkillHash:Qe.nullable(),validation:c({valid:A(),messages:p(i().max(2e3)).max(100)}).strict(),createdAt:It,contentHash:Qe}).strict();var nq=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("no_action"),reason:i().trim().min(1).max(1e4)}).strip(),aq=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strip(),oq=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v1"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),createContent:i().min(1).max(2e4).nullable(),find:i().min(1).max(8e3).nullable(),replace:i().max(8e3).nullable(),expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strip().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),iq=vt("decision",[nq,aq,oq]),rq=iq,rv=c({kind:b(["single_deterministic","recurrent_independent"]),supportingEvidenceIds:p(i().trim().min(1).max(2e3)).min(1).max(100),counterevidence:p(i().trim().min(1).max(2e3)).max(20)}).strict().superRefine((e,t)=>{new Set(e.supportingEvidenceIds).size!==e.supportingEvidenceIds.length&&t.addIssue({code:"custom",message:"supporting evidence IDs must be unique",path:["supportingEvidenceIds"]}),e.kind==="recurrent_independent"&&e.supportingEvidenceIds.length<2&&t.addIssue({code:"custom",message:"recurrent independent evidence requires at least two supplied incidents",path:["supportingEvidenceIds"]})}),sq=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("no_action"),reason:i().trim().min(1).max(1e4)}).strict(),lq=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("route"),route:b(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),evidenceBasis:rv,expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strict(),cq=c({schemaVersion:S("openpond.localHarnessRefinerDecision.v2"),decision:S("propose"),route:b(["memory","prompt","skill","agent"]),operation:b(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),evidenceBasis:rv,createContent:i().min(1).max(2e4).nullable(),find:i().min(1).max(8e3).nullable(),replace:i().max(8e3).nullable(),expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strict().superRefine((e,t)=>{e.operation==="create"&&(e.createContent===null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"create proposals require createContent and null find/replace",path:["createContent"]}),e.operation==="update"&&(e.createContent!==null||e.find===null||e.replace===null)&&t.addIssue({code:"custom",message:"update proposals require one exact find/replace edit and null createContent",path:["find"]}),e.operation==="delete"&&(e.createContent!==null||e.find!==null||e.replace!==null)&&t.addIssue({code:"custom",message:"delete proposals require null createContent/find/replace",path:["createContent"]})}),iI=vt("decision",[sq,lq,cq]);Tt([rq,iI]);var sv=c({memory:A(),prompt:A(),skill:A(),agent:A()}).strict(),rI=b(["memory","instruction","skill","agent"]),e0=c({path:i().trim().min(1).max(2e3),kind:rI,content:i().max(6e4),loaded:A()}).strict(),t0=c({path:i().trim().min(1).max(2e3),kind:rI,loaded:A()}).strict(),dq=c({capabilities:sv,trigger:oe(i(),se()),observations:p(oe(i(),se())).max(20),admissibleEvidenceIds:p(i().trim().min(1).max(2e3)).max(1e4),reviewPacket:c({currentTurn:c({id:i().trim().min(1).max(2e3),status:i().trim().min(1).max(100).nullable(),error:i().max(2100).nullable(),prompt:i().max(8100).nullable(),assistantOutput:i().max(8100).nullable(),assistantOutputLinkCount:u().int().nonnegative()}).strict(),priorConversation:p(c({turnId:i().trim().min(1).max(2e3),status:i().trim().min(1).max(100).nullable(),prompt:i().max(3100).nullable(),assistantOutput:i().max(3100).nullable()}).strict()).max(3),timeline:p(oe(i(),se())).max(60),artifacts:p(oe(i(),se())).max(30),artifactDiagnostics:p(oe(i(),se())).max(20),executionProfile:c({modelRequestCount:u().int().nonnegative(),failedModelRequestCount:u().int().nonnegative(),promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),toolFailureCount:u().int().nonnegative(),retryCount:u().int().nonnegative(),recoveryCount:u().int().nonnegative()}).strict(),priorIncidents:p(oe(i(),se())).max(3),truncation:c({timelineEventCount:u().int().nonnegative(),includedTimelineEventCount:u().int().nonnegative(),timelineTruncated:A()}).strict()}).strict(),runtimeActivation:c({admittedRelease:Ze,currentRelease:Ze,rebasedOntoCurrent:A(),admittedSourceFiles:p(e0).max(100),admittedSourceCatalog:p(t0).max(1e3)}).strict(),sourceFiles:p(e0).max(100),sourceCatalog:p(t0).max(1e3),additionalEvidence:se().nullable().optional()}).strict(),uq=c({id:i().trim().min(1).max(240),revision:u().int().nonnegative(),contentHash:Qe}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerRequest.v2"),requestId:i().trim().min(1).max(240),idempotencyKey:i().trim().min(1).max(240),evidenceHash:Qe,harness:c({admittedRelease:Ze,currentRelease:Ze,overlay:uq,workspace:c({id:i().trim().min(1).max(240),revision:u().int().nonnegative(),sourceRevision:Qe,channelRevision:u().int().nonnegative()}).strict(),capabilities:sv}).strict(),evidence:dq}).strict();var mq=c({promptTokens:u().int().nonnegative(),completionTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative()}).strict();c({schemaVersion:S("openpond.hostedHarnessRefinerResponse.v2"),requestId:i().trim().min(1).max(240),evidenceHash:Qe,admittedRelease:Ze,currentRelease:Ze,decision:iI,serviceRevision:i().trim().min(1).max(240),usage:mq}).strict();const sI=c({adapterId:T,placement:b(["local","remote","colocated","provider_native"]),runtimeVersion:i().trim().min(1).max(200),capabilityReceipt:F}).strict(),lI=c({maxTurns:u().int().positive().max(1e5),timeoutMs:u().int().positive().max(864e5),maxOutputBytes:u().int().positive().max(25e7),maximumSpendUsd:u().nonnegative().nullable()}).strict(),pq=c({schemaVersion:S("openpond.runManifest.v1"),id:T,harnessRelease:G,tasksetRelease:G,model:Pu,runtimeTarget:sI,limits:lI,approval:c({id:T,contentHash:F}).strict().nullable(),createdAt:Ce,metadata:_n}).strict();pq.extend({contentHash:F}).strict();const fq=c({schemaVersion:S("openpond.attemptReceipt.v1"),id:T,runManifest:G,taskId:T,seed:i().trim().min(1).max(500),terminal:A(),failureClass:pc.nullable(),outputHash:F.nullable(),traceHash:F,artifactRefs:p(ha).max(1e5),graderEvidenceRefs:p(ha).max(1e4),startedAt:Ce,completedAt:Ce,latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),legacyAttemptRef:T.nullable().default(null),metadata:_n}).strict(),hq=fq.extend({contentHash:F}).strict(),gq=c({schemaVersion:S("openpond.evaluationResult.v1"),id:T,runManifest:G,harnessRelease:G,tasksetRelease:G,model:Pu,receiptRefs:p(G).min(1).max(1e6),attemptCount:u().int().positive(),rewardEligibleCount:u().int().nonnegative(),terminalCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),failureCounts:oe(pc,u().int().nonnegative()),authoredMetric:Cw.optional(),metadata:_n}).strict(),vq=gq.extend({contentHash:F}).strict(),bq=c({schemaVersion:S("openpond.harnessCompatibility.v1"),id:T,baseHarnessRelease:G,candidateHarnessRelease:G,tasksetRelease:G,environmentHash:F,toolContractHash:F,policyHash:F,graderInterfaceHash:F,metadata:_n}).strict();bq.extend({contentHash:F}).strict();const lv=b(["scored","unscorable"]),Zu=b(["policy","environment","collector","verifier","provider","host","user","scheduler"]),cI=b(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),yq=c({schemaVersion:S("openpond.environmentRelease.v1"),id:T,revision:u().int().positive(),contract:Rw,actionSchemaRef:cn.nullable(),observationSchemaRef:cn.nullable(),stateSchemaRef:cn.nullable(),artifactCollection:c({maxArtifacts:u().int().positive().max(1e5),maxTotalBytes:u().int().positive().max(1e10)}).strict(),adapterConformanceHashes:oe(T,F),metadata:_n}).strict(),cv=yq.extend({contentHash:F}).strict(),Sq=b(["collected","missing","skipped","failed"]),n0=b(["not_requested","passed","failed"]),xq=c({requiredOutputPath:i().trim().min(1).max(2e3).nullable(),collectedPath:i().trim().min(1).max(4e3).nullable(),declaredMediaType:i().trim().min(1).max(200).nullable(),detectedMediaType:i().trim().min(1).max(200).nullable(),artifact:ha.nullable(),status:Sq,parseStatus:n0,schemaStatus:n0,errorCode:T.nullable(),failureOwner:Zu.nullable(),evidenceRefs:p(ha).max(1e4),metadata:_n}).strict(),kq=c({schemaVersion:S("openpond.artifactManifest.v1"),id:T,attemptRef:G,entries:p(xq).max(1e5),createdAt:Ce,metadata:_n}).strict();kq.extend({contentHash:F}).strict();const wq=c({schemaVersion:S("openpond.verifierSetRelease.v1"),id:T,revision:u().int().positive(),graders:p(jw).min(1).max(1e3),isolation:c({processBoundary:b(["same_process","isolated_process","container"]),networkPolicy:S("none"),defaultTimeoutMs:u().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:p(G).max(1e4),metadata:_n}).strict(),dv=wq.extend({contentHash:F}).strict(),Iq=c({verifierId:T,verifierVersion:i().trim().min(1).max(100),status:lv,rawScore:u().finite().nullable(),normalizedScore:u().min(0).max(1).nullable(),weight:u().nonnegative().max(1e3),passed:A(),hardGate:A(),rewardEligible:A(),rewardContribution:u().min(0).max(1).nullable(),failureOwner:Zu.nullable(),feedback:p(i().max(2e4)).max(1e3),visibleEvidenceRefs:p(ha).max(1e4),privilegedEvidenceRefs:p(ha).max(1e4),metadata:_n}).strict().superRefine((e,t)=>{e.status==="scored"&&e.normalizedScore===null&&t.addIssue({code:"custom",message:"A scored component requires a normalized score.",path:["normalizedScore"]}),e.status==="unscorable"&&(e.normalizedScore!==null||e.rewardEligible)&&t.addIssue({code:"custom",message:"An unscorable component cannot contribute reward.",path:["status"]})}),dI=c({schemaVersion:S("openpond.rewardReceipt.v1"),id:T,attemptRef:G,verifierSetRef:G,artifactManifestRef:G,status:lv,reward:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:cI,failureOwner:Zu.nullable(),components:p(Iq).min(1).max(1e4),visibleEvidenceRefs:p(ha).max(1e5),privilegedEvidenceRefs:p(ha).max(1e5),supersedes:G.nullable(),createdAt:Ce,metadata:_n}).strict();function uI(e,t){e.status==="scored"&&(e.reward===null||!e.learningEligible)&&t.addIssue({code:"custom",message:"A scored receipt requires a reward and is learning-eligible.",path:["status"]}),e.status==="unscorable"&&(e.reward!==null||e.learningEligible)&&t.addIssue({code:"custom",message:"An unscorable receipt has null reward and is not learning-eligible.",path:["status"]})}dI.superRefine(uI);dI.extend({contentHash:F}).strict().superRefine(uI);const _q=i().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"evaluation paths must be portable and relative"),mI=vt("kind",[c({kind:S("profile")}).strict(),c({kind:S("workflow"),workflowId:T}).strict(),c({kind:S("skill"),skillPath:_q}).strict(),c({kind:S("agent_action"),actionId:T}).strict()]),Cq=c({id:T,label:i().trim().min(1).max(240),description:i().max(4e3),target:mI,tasksetRelease:G,split:to,taskIds:p(T).min(1).max(1e5),seeds:p(i().trim().min(1).max(500)).min(1).max(100),criterion:c({minimumPassRate:u().min(0).max(1),requireComplete:A()}).strict()}).strict().superRefine((e,t)=>{new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"Evaluation task identities must be unique."}),new Set(e.seeds).size!==e.seeds.length&&t.addIssue({code:"custom",path:["seeds"],message:"Evaluation seeds must be unique."})}),Rq=c({id:T,label:i().trim().min(1).max(240),scope:b(["component","profile"]),definitionIds:p(T).min(1).max(1e3)}).strict();c({schemaVersion:S("openpond.profileEvaluations.v1"),definitions:p(Cq).max(1e3),suites:p(Rq).max(100)}).strict();const Yu=c({profileId:T,sourceRevision:i().trim().min(1).max(240),harnessRelease:G,catalogHash:F,definitionId:T,definitionHash:F,target:mI,environmentHash:F}).strict(),Cc=c({harnessRelease:G,agentSnapshot:G,sourcePackageHash:F}).strict(),uf=i().trim().min(1).max(200),uv=c({sessionId:uf,turnId:uf,source:Cc,admissionHash:F,modelConfigurationHash:F,traceHash:F,runtimeEventRefs:p(uf).max(1e4),startedAt:Ce,completedAt:Ce,outputHash:F,partialOutputAvailable:A()}).strict().superRefine((e,t)=>{new Set(e.runtimeEventRefs).size!==e.runtimeEventRefs.length&&t.addIssue({code:"custom",path:["runtimeEventRefs"],message:"Native event references must be unique."}),Date.parse(e.completedAt)<Date.parse(e.startedAt)&&t.addIssue({code:"custom",path:["completedAt"],message:"Native completion precedes its start."})}),Pq=c({schemaVersion:S("openpond.nativeHarnessExperimentAttempt.v1"),taskId:i().min(1).max(500),status:b(["completed","cancelled","timed_out","policy_failure"]),output:i().max(8388608).nullable(),error:i().max(2e3).nullable(),messages:p(se()).max(4002),collected:A(),environmentCleanupComplete:S(!0),snapshot:mc(),native:uv}).strict().superRefine((e,t)=>{const n=e.status==="completed";(n!==e.collected||n!==(e.output!==null)||n!==(e.error===null))&&t.addIssue({code:"custom",message:"Native status, output, collection and error must agree."}),n&&(e.native.partialOutputAvailable||e.native.outputHash!==_t(e.output))&&t.addIssue({code:"custom",path:["native","outputHash"],message:"Native output differs from its retained evidence."})});Pq.extend({contentHash:F}).strict();const pI=u().finite().nonnegative(),Aq=vt("kind",[c({kind:S("model"),modelId:T,configurationHash:F}).strict(),c({kind:S("harness"),source:Yu,model:c({modelId:T,configurationHash:F}).strict()}).strict(),c({kind:S("agent"),source:Cc,model:c({modelId:T,configurationHash:F}).strict()}).strict(),c({kind:S("fixture"),configurationHash:F}).strict()]),fI=c({release:G.extend({revision:Tt([u().int().positive(),i().trim().min(1).max(200)])}).strict(),feedbackKey:Bu,configurationHash:F.optional(),output:b(["boolean","score","category"]),categories:p(i().trim().min(1).max(120)).max(50)}).strict().superRefine((e,t)=>{e.output==="category"!=e.categories.length>0&&t.addIssue({code:"custom",path:["categories"],message:"Only category feedback declares categories."}),new Set(e.categories).size!==e.categories.length&&t.addIssue({code:"custom",path:["categories"],message:"Feedback categories must be unique."})}),mv=c({caseId:T,seed:i().trim().min(1).max(500),fixtureId:T.nullable()}).strict();function Ql(e){const t=mv.parse(e);return JSON.stringify([t.caseId,t.seed,t.fixtureId])}const Tq=c({schemaVersion:S("openpond.experimentManifest.v1"),id:T,name:i().trim().min(1).max(500),teamId:T,operationId:T,maximumCostUsd:pI.nullable(),dataset:G.extend({revision:u().int().positive()}).strict(),target:Aq,execution:c({packageHash:F,runtimeTargetHash:F,metricPolicyHash:F,compatibility:c({protocol:S("openpond.evaluation-execution.v1"),targetKind:b(["model","agent","harness","fixture"])}).strict().optional()}).strict().optional(),lineage:c({definition:G.extend({revision:u().int().positive()}).strict().nullable(),execution:G,scoringPassId:T.nullable()}).strict().optional(),evaluators:p(fI).max(100),population:p(mv).min(1).max(1e4),createdAt:Ce}).strict().superRefine((e,t)=>{e.execution?.compatibility&&e.execution.compatibility.targetKind!==e.target.kind&&t.addIssue({code:"custom",path:["execution","compatibility"],message:"Execution compatibility differs from its admitted target kind."}),e.lineage&&e.id!==(e.lineage.scoringPassId??e.lineage.execution.id)&&t.addIssue({code:"custom",path:["lineage"],message:"Experiment identity must match its execution or independent scoring pass."}),new Set(e.population.map(Ql)).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Experiment cases must be unique."}),new Set(e.evaluators.map(n=>n.feedbackKey)).size!==e.evaluators.length&&t.addIssue({code:"custom",path:["evaluators"],message:"Experiment feedback keys must be unique."})}),pv=Tq.extend({contentHash:F}).strict(),Eq=c({feedbackKey:Bu,evaluator:fI.shape.release,status:b(["scored","unavailable","failed","pending"]),value:Tt([A(),u().finite(),i().max(120)]).nullable(),passed:A().nullable().optional(),reasoning:i().max(2e4).nullable(),evidenceRefs:p(ha).max(1e3)}).strict(),Mq=c({inputTokens:u().int().nonnegative().nullable(),outputTokens:u().int().nonnegative().nullable(),totalTokens:u().int().nonnegative().nullable(),costUsd:pI.nullable(),latencyMs:u().finite().nonnegative().nullable()}).strict().superRefine((e,t)=>{e.inputTokens!==null&&e.outputTokens!==null&&e.totalTokens!==null&&e.totalTokens<e.inputTokens+e.outputTokens&&t.addIssue({code:"custom",path:["totalTokens"],message:"Total tokens cannot be less than input plus output."})}),jq=c({identity:mv,status:b(["completed","failed","cancelled","unavailable"]),output:se().nullable(),error:c({code:T,message:i().max(2e3)}).strict().nullable(),feedback:p(Eq).max(100),usage:Mq,traceRef:ha.nullable(),startedAt:Ce.nullable(),completedAt:Ce.nullable()}).strict(),hI=c({schemaVersion:S("openpond.experimentResult.v1"),manifest:G,status:b(["completed","failed","cancelled"]),cases:p(jq).min(1).max(1e4),completedAt:Ce}).strict(),fv=hI.extend({contentHash:F}).strict();function Oq(e,t){pv.parse(t),rO(t,"Experiment manifest");const n=hI.parse(e);if(n.manifest.id!==t.id||n.manifest.contentHash!==t.contentHash)throw new Error("Experiment result differs from its manifest.");const a=new Set(t.population.map(Ql)),o=new Set,r=new Map(t.evaluators.map(s=>[s.feedbackKey,s]));for(const s of n.cases){const l=Ql(s.identity);if(!a.has(l)||o.has(l))throw new Error("Experiment result has an unexpected or repeated case.");o.add(l);const m=new Set;for(const d of s.feedback){const h=r.get(d.feedbackKey);if(!h||m.has(d.feedbackKey)||d.evaluator.id!==h.release.id||d.evaluator.contentHash!==h.release.contentHash||d.evaluator.revision!==h.release.revision)throw new Error("Experiment feedback differs from its pinned evaluator.");if(m.add(d.feedbackKey),d.status==="scored"){if(d.value===null||typeof d.value!=={boolean:"boolean",score:"number",category:"string"}[h.output]||h.output==="category"&&!h.categories.includes(d.value)||h.output==="score"&&(d.value<0||d.value>1))throw new Error("Experiment feedback value violates its output contract.")}else if(d.value!==null||d.passed!==null&&d.passed!==void 0)throw new Error("Unscored experiment feedback cannot claim a value or pass decision.")}}if(o.size!==a.size)throw new Error("Experiment result omits admitted cases.");return fv.parse({...n,contentHash:_t(n)})}function gI(e){const t=pv.parse(e.manifest),n=fv.parse(e.result),{contentHash:a,...o}=n;if(_t(o)!==a)throw new Error("Experiment result integrity failed.");return Oq(o,t),{manifest:t,result:n}}function ZX(e,t){for(const g of[e,t])gI(g);const n=[];e.manifest.teamId!==t.manifest.teamId&&n.push("different_workspace"),(e.manifest.dataset.id!==t.manifest.dataset.id||e.manifest.dataset.contentHash!==t.manifest.dataset.contentHash||e.manifest.dataset.revision!==t.manifest.dataset.revision)&&n.push("different_dataset_version"),e.manifest.target.kind!==t.manifest.target.kind&&n.push("different_target_kind");const a=g=>{const y=g.execution;if(!y?.compatibility)return y??null;const{runtimeTargetHash:w,..._}=y;return _};if(_t(a(e.manifest))!==_t(a(t.manifest))&&n.push("different_execution_contract"),e.manifest.target.kind==="harness"&&t.manifest.target.kind==="harness"){const g=e.manifest.target.source,y=t.manifest.target.source;(g.profileId!==y.profileId||_t(g.target)!==_t(y.target))&&n.push("different_component");const w=e.manifest.execution?.compatibility&&t.manifest.execution?.compatibility&&e.manifest.execution.packageHash===t.manifest.execution.packageHash;g.environmentHash!==y.environmentHash&&!w&&n.push("different_environment"),(g.definitionId!==y.definitionId||g.definitionHash!==y.definitionHash)&&n.push("different_evaluation_definition")}const o=g=>[...g.evaluators].sort((y,w)=>y.feedbackKey.localeCompare(w.feedbackKey));_t(o(e.manifest))!==_t(o(t.manifest))&&n.push("different_evaluators");const r=new Map(e.result.cases.map(g=>[Ql(g.identity),g])),s=new Map(t.result.cases.map(g=>[Ql(g.identity),g])),l=[...new Set([...r.keys(),...s.keys()])].sort();(r.size!==s.size||l.some(g=>!r.has(g)||!s.has(g)))&&n.push("different_population");const m=n.length===0,d=l.map(g=>{const y=r.get(g)??null,w=s.get(g)??null,_=new Map(y?.feedback.map(M=>[M.feedbackKey,M])??[]),P=new Map(w?.feedback.map(M=>[M.feedbackKey,M])??[]);return{identity:(y??w).identity,baseline:y,candidate:w,feedback:e.manifest.evaluators.map(M=>{const C=_.get(M.feedbackKey),$=P.get(M.feedbackKey),O=m?!y||!w?"missing_case":y.status!=="completed"||w.status!=="completed"||y.error||w.error?"case_not_completed":!C||!$||C.status!=="scored"||$.status!=="scored"?"feedback_unavailable":M.output==="category"?"categorical_feedback":null:"incompatible_experiments",j=H=>typeof H?.value=="boolean"?Number(H.value):typeof H?.value=="number"?H.value:null,x=O?null:j(C),R=O?null:j($),E=H=>O?null:typeof H?.value=="boolean"?H.value:H?.passed??null;return{feedbackKey:M.feedbackKey,eligible:O===null,reason:O,baseline:x,candidate:R,delta:x===null||R===null?null:R-x,baselinePassed:E(C),candidatePassed:E($)}})}}),h=e.manifest.evaluators.map((g,y)=>{const w=d.map(j=>j.feedback[y]).filter(j=>j.eligible),_=j=>w.length?w.reduce((x,R)=>x+R[j],0)/w.length:null,P=_("baseline"),M=_("candidate"),C=j=>w.length&&w.every(x=>x[j]!==null)?w.reduce((x,R)=>x+Number(R[j]),0)/w.length:null,$=C("baselinePassed"),O=C("candidatePassed");return{feedbackKey:g.feedbackKey,eligibleCount:w.length,excludedCount:d.length-w.length,baseline:P,candidate:M,delta:P===null||M===null?null:M-P,baselinePassRate:$,candidatePassRate:O,passRateDelta:$===null||O===null?null:O-$}});return{comparable:m,reasons:n,cases:d,metrics:h}}const $q=vt("kind",[c({kind:S("model"),model:Pu,configurationHash:F}).strict(),c({kind:S("fixture")}).strict()]),Nq=vt("kind",[c({kind:S("taskset"),environmentRelease:G,verifierSetRelease:G,policyHash:F}).strict(),c({kind:S("harness"),harnessRelease:G}).strict()]),vI=c({receiptId:T,taskId:T,seed:i().trim().min(1).max(500),fixtureId:T.nullable()}).strict(),Dq=c({schemaVersion:S("openpond.tasksetRunManifest.v1"),id:T,tasksetRelease:G,packageHash:F,execution:Nq,profileEvaluation:Yu.optional(),policy:$q,gradingRole:S("evaluation"),metricPolicy:Ic,population:p(vI).min(1).max(1e5),runtimeTarget:sI,limits:lI,createdAt:Ce,metadata:_n}).strict().superRefine((e,t)=>{new Set(e.population.map(n=>n.receiptId)).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),e.population.some(n=>n.fixtureId!==null!=(e.policy.kind==="fixture"))&&t.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),e.profileEvaluation&&(e.execution.kind!=="harness"||e.execution.harnessRelease.id!==e.profileEvaluation.harnessRelease.id||e.execution.harnessRelease.contentHash!==e.profileEvaluation.harnessRelease.contentHash)&&t.addIssue({code:"custom",path:["profileEvaluation"],message:"Profile evaluation must execute its exact bound Harness release."})}),bI=Dq.safeExtend({contentHash:F}),yI=c({schemaVersion:S("openpond.optimizerTrainingSample.v1"),tokenIds:p(u().int().nonnegative()).min(2).max(32768),mask:p(A()).min(2).max(32768),logprobs:p(u().finite()).min(2).max(32768),temperatures:p(u().positive().finite()).min(2).max(32768),envName:i().trim().min(1).max(200),modelRequestId:i().trim().min(1).max(1e3),promptTokenCount:u().int().positive(),completionTokenCount:u().int().positive(),servedPolicyVersion:u().int().nonnegative()}).strict().superRefine((e,t)=>{const n=e.tokenIds.length;for(const[a,o]of[["mask",e.mask],["logprobs",e.logprobs],["temperatures",e.temperatures]])o.length!==n&&t.addIssue({code:"custom",path:[a],message:`${a} must align with tokenIds`});e.promptTokenCount+e.completionTokenCount!==n&&t.addIssue({code:"custom",path:["completionTokenCount"],message:"prompt and completion token counts must span tokenIds"}),e.mask.filter(a=>!a).length!==e.promptTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"promptTokenCount must equal the non-trainable mask count"}),e.mask.filter(Boolean).length!==e.completionTokenCount&&t.addIssue({code:"custom",path:["mask"],message:"completionTokenCount must equal the trainable mask count"})}),Lq=c({id:T,environmentRelease:G,status:b(["completed","failed","timed_out","cancelled"]),startedAt:Ce,completedAt:Ce,traceRefs:p(ha).max(1e4),metadata:_n}).strict(),Hq=c({receiptRef:G,status:lv,value:u().min(0).max(1).nullable(),learningEligible:A(),passed:A(),outcomeClass:cI,failureOwner:Zu.nullable(),components:oe(T,u().min(0).max(1).nullable())}).strict(),SI=c({schemaVersion:S("openpond.canonicalRolloutRecord.v1"),id:T,attemptRef:G,artifactManifestRef:G,tasksetRelease:G,environmentRelease:G,verifierSetRelease:G,harnessRelease:G,taskId:T,split:to,model:Pu,seed:i().trim().min(1).max(500),reward:Hq,traceRef:ha,optimizerSample:yI.nullable(),environmentExecutions:p(Lq).min(1).max(1e5),startedAt:Ce,completedAt:Ce,metadata:_n}).strict();function xI(e,t){e.reward.status==="scored"&&(e.reward.value===null||!e.reward.learningEligible)&&t.addIssue({code:"custom",path:["reward","status"],message:"A scored rollout requires a numeric, learning-eligible reward."}),e.reward.status==="unscorable"&&(e.reward.value!==null||e.reward.learningEligible)&&t.addIssue({code:"custom",path:["reward","status"],message:"An unscorable rollout has no reward and cannot be learning-eligible."})}SI.superRefine(xI);c({...SI.shape,contentHash:F}).strict().superRefine(xI);const Uq=i().regex(/^(0|-?[1-9][0-9]*)$/).max(20).refine(e=>{if(e.length>20||!/^(0|-?[1-9][0-9]*)$/.test(e))return!1;const t=BigInt(e);return t>=-(1n<<63n)&&t<1n<<63n},"SQL integers must fit signed 64-bit storage."),kI=Tt([mc(),i().max(262144),u().finite(),c({integer:Uq}).strict(),c({blobBase64:i().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),a0=i().min(1).max(128).refine(e=>!e.includes("\0")),qq=c({tables:p(c({name:a0,columns:p(c({name:a0,type:b(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:p(p(kI).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,o]of e.tables.entries()){const r=o.name.toLowerCase();(n.has(r)||r.startsWith("sqlite_"))&&t.addIssue({code:"custom",path:["tables",a,"name"],message:"Table names must be unique and outside SQLite's reserved namespace."}),n.add(r),new Set(o.columns.map(s=>s.name.toLowerCase())).size!==o.columns.length&&t.addIssue({code:"custom",path:["tables",a,"columns"],message:"Column names must be unique."}),o.rows.some(s=>s.length!==o.columns.length)&&t.addIssue({code:"custom",path:["tables",a,"rows"],message:"Each row must match the declared columns."})}}),o0=c({schemaVersion:S("openpond.sqlExecution.v1"),snapshot:qq,sql:i().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:u().int().min(1).max(4096),maxResultBytes:u().int().min(256).max(262144)}).strict();vt("status",[c({status:S("completed"),columns:p(i()).max(128),rows:p(p(kI).max(128)).max(4096)}).strict(),c({status:S("rejected"),code:b(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const fd=c({scope:b(["input","initialState","state","arguments"]),path:p(i().min(1).max(256)).max(16)}).strict(),i0={id:i().min(1).max(128),operation:b(["step","collect"]),toolName:i().min(1).max(500).optional(),timeoutMs:u().int().min(1).max(2e4)},zq=vt("kind",[c({...i0,kind:S("sqlite.v1"),sql:fd,snapshot:fd,maxRows:o0.shape.maxRows,maxResultBytes:o0.shape.maxResultBytes}).strict(),c({...i0,kind:S("javascript.v1"),source:fd,cases:fd,exportName:i().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:u().int().min(1).max(32),maxResultBytes:u().int().min(256).max(262144)}).strict()]).superRefine((e,t)=>{e.operation==="step"!=(e.toolName!==void 0)&&t.addIssue({code:"custom",path:["toolName"],message:"Only step services require a declared tool name."}),e.operation==="collect"&&(e.kind==="sqlite.v1"?[e.sql,e.snapshot]:[e.source,e.cases]).some(a=>a.scope==="arguments")&&t.addIssue({code:"custom",message:"Collection has no tool arguments."})}),Bq=c({schemaVersion:S("openpond.javascriptEnvironment.v1"),id:i().trim().min(1).max(500),revision:u().int().positive(),module:cn.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:p(yc).min(1).max(200),maxSteps:u().int().min(1).max(1e3),maxStateBytes:u().int().min(1).max(1048576),maxObservationBytes:u().int().min(1).max(262144),operationTimeoutMs:u().int().min(1).max(3e4),executionServices:p(zq).min(1).max(16).optional()}).strict().superRefine((e,t)=>{new Set(e.tools.map(a=>a.name)).size!==e.tools.length&&t.addIssue({code:"custom",path:["tools"],message:"Environment tool names must be unique."}),e.tools.forEach((a,o)=>{Qg(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",o,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==_t(a.inputSchema)&&t.addIssue({code:"custom",path:["tools",o,"inputSchemaHash"],message:"Tool schema identity differs from its declared schema."})});const n=e.executionServices??[];new Set(n.map(a=>a.id)).size!==n.length&&t.addIssue({code:"custom",path:["executionServices"],message:"Execution service identities must be unique."}),n.forEach((a,o)=>{const r=e.tools.find(s=>s.name===a.toolName);a.operation==="step"&&!r&&t.addIssue({code:"custom",path:["executionServices",o,"toolName"],message:"Execution services must target a declared tool."}),a.timeoutMs>=Math.min(e.operationTimeoutMs,r?.timeoutMs??e.operationTimeoutMs)&&t.addIssue({code:"custom",path:["executionServices",o,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),Fq=Bq.safeExtend({contentHash:i().regex(/^[a-f0-9]{64}$/)});b(["create","reset","step","collect","destroy"]);c({state:oe(i(),se()),observation:oe(i(),se())}).strict();i().regex(/^[a-f0-9]{64}$/);var Vq=c({environment:cv,verifierSet:dv,javascript:Fq}).strict();c({actions:p(c({name:i().min(1).max(64),arguments:oe(i(),se())}).strict()).max(1e3)}).strict();var Kq=c({environment:cv,verifierSet:dv}).strict(),Wq=c({scopeId:i().trim().min(1).max(500),modelId:i().trim().min(1).max(500)}).strict();c({schemaVersion:S("openpond.modelTasksetDerivation.v1"),owner:Wq,root:Wn,parent:Wn}).strict();var Gq=c({taskset:$w,taskDefinition:Ku,rewardBinding:Vu,rewards:p(Fu).min(1).max(100),assets:p(Gu).max(1e3),executionResources:Kq.optional(),execution:Vq.optional(),instructionMode:S("per_task").optional()}).strict(),Jq=c({batch:Hw,evidence:p(Wu).min(1).max(1e4),decisions:p(tv).min(1).max(1e4),sources:p(ev).min(1).max(1e4),assets:p(Gu).max(1e3)}).strict(),Zq=64*1024*1024,Yq=c({asset:Fo,base64:i().max(Math.ceil(Zq/3)*4)}).strict(),Qq=Gq.omit({taskset:!0,executionResources:!0}),Xq=c({schemaVersion:S("openpond.tasksetPackage.v1"),taskset:$w,environment:cv,verifierSet:dv,files:p(Yq).max(1e4),modelResources:Qq.optional(),learningResources:Jq.optional()}).strict(),sr=Xq.extend({contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict(),bo=i().trim().min(1).max(500),jd=i().regex(/^[a-f0-9]{64}$/),ez=qU.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:iv.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();c({schemaVersion:S("openpond.tasksetPackagePublication.v1"),operationId:bo,modelProjectId:bo,expectedProjectEtag:jd.nullable(),name:i().trim().min(1).max(200),description:i().max(5e3),buildIntent:b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),methodHint:b(["sft","dpo","grpo","ppo"]).nullable(),package:sr,modelConfiguration:ez.optional(),evaluationPackage:sr.optional(),selection:b(["select","attach"]).optional()}).strict().refine(e=>e.selection!=="attach"||e.modelConfiguration===void 0,"Attachment-only publication cannot replace Model configuration.").refine(e=>!e.evaluationPackage||e.modelConfiguration!==void 0&&e.modelConfiguration.trainingSetup.evaluationTasksetRef!=null&&fa(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===fa(aU(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");c({schemaVersion:S("openpond.tasksetPackageReceipt.v1"),teamId:bo,modelProjectId:bo,operationId:bo,taskset:ou,packageHash:jd,hostedTasksetId:bo,projectEtag:jd,project:tI.optional(),selection:b(["select","attach"]).optional(),evaluation:c({taskset:ou,packageHash:jd,hostedTasksetId:bo}).strict().optional()}).strict();c({schemaVersion:S("openpond.tasksetPackageReadback.v1"),teamId:bo,modelProjectId:bo,package:sr}).strict();c({schemaVersion:S("openpond.tasksetReleasePackageReadback.v1"),teamId:bo,release:ou,package:sr}).strict();var wI=c({name:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(2e3),inputSchema:oe(i(),se()),inputSchemaHash:Qe,sideEffect:b(["read","write"]),timeoutMs:u().int().positive().max(36e5)}).strict(),tz=c({id:Fe,required:A(),scopes:p(i().trim().min(1).max(500)).max(100).default([]),portability:b(["portable","host_adapter","local_only","hosted_only"])}).strict(),nz=c({portable:A(),blockers:p(i().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(Fe).max(1e4),hostPrivateAssetRefs:p(Fe).max(1e4)}).strict(),az=c({schemaVersion:S("openpond.agentSnapshot.v2"),id:Fe,sourceRelease:Ze.nullable(),instructions:p(Fo).max(1e4),skills:p(Fo).max(1e4),agents:p(Fo).max(1e4),toolDeclarations:p(wI).max(200),capabilityRequirements:p(tz).max(200),dependencyLock:Fo,portability:nz,metadata:Ju}).strict(),oz=az.extend({contentHash:Qe}).strict(),iz=c({create:S(!0),reset:S(!0),step:S(!0),collect:S(!0),destroy:S(!0),resetScope:b(["task","attempt"])}).strict(),rz=c({visibleEvidence:p(Fe).max(1e3),privilegedEvidence:p(Fe).max(1e3),privateVerifierIsolation:A()}).strict(),sz=c({schemaVersion:S("openpond.harnessRelease.v2"),id:Fe,agentSnapshot:Ze,program:Fo,tools:p(wI).max(200),lifecycle:iz,graderInterface:rz,files:p(Fo).max(1e5),metadata:Ju}).strict(),lz=sz.extend({contentHash:Qe}).strict(),cz=c({id:Fe,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:Fe.nullable(),arguments:oe(i(),se()),content:i().max(1e6).nullable()}).strict(),dz=c({actionId:Fe,turn:u().int().nonnegative(),terminal:A(),output:oe(i(),se()),artifactRefs:p(JU).max(1e5)}).strict(),uz=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Qe,metadata:Ju}).strict();c({schemaVersion:S("openpond.harnessTrace.v1"),manifest:Ze,taskId:Fe,seed:i().trim().min(1).max(500),events:p(uz).max(1e6),actions:p(cz).max(1e5),observations:p(dz).max(1e5),terminal:A(),failureClass:aI.nullable(),output:oe(i(),se()),contentHash:Qe}).strict();var mz=25*1024*1024,pz=c({path:Fo.shape.path,base64:i().max(Math.ceil(mz/3)*4)}).strict(),II=c({schemaVersion:S("openpond.harnessSourcePackage.v1"),agentSnapshot:oz,harnessRelease:lz,files:p(pz).max(1e4)}).strict();II.extend({contentHash:Qe}).strict();II.extend({schemaVersion:S("openpond.harnessPolicySourcePackage.v1"),contentHash:Qe}).strict();c({schemaVersion:S("openpond.harnessSourceSelection.v1"),mode:b(["taskset_owned","selected_release"]),harnessRelease:Ze,sourcePackageHash:Qe.nullable()}).strict().superRefine((e,t)=>{e.mode==="selected_release"!=(e.sourcePackageHash!==null)&&t.addIssue({code:"custom",path:["sourcePackageHash"],message:"Only a selected release binds a source package."})});var Jo=i().trim().min(1).max(1e5),fz=b(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),hz=b(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),_I=b(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),hv=c({kind:b(["personal","team"]),id:Fe}).strict(),CI=c({policy:Ze,state:b(["authorized","revoked","deleted","expired"]),checkedAt:It}).strict(),Xl=c({evidence:Ze,kind:_I,sourceRef:Fe,sourcePolicy:CI,occurrenceKey:Qe,occurredAt:It}).strict(),gz=c({evidence:Ze,sourcePolicy:CI.nullable(),reason:b(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),r0=c({cursor:Qe,throughCreatedAt:It}).strict(),vz=c({fingerprint:Qe,recurrenceFamily:i().trim().min(1).max(1e3),statement:Jo,candidateDisposition:b(["observe","confirm"]).optional(),independentOccurrences:u().int().positive().max(1e6),unresolvedOccurrences:u().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),RI=b(["harness","runtime","product","retrieval","tools","evaluation","model"]),bz=c({layer:RI,status:b(["not_applicable","unresolved","resolved","blocked"]),reason:Jo,evidenceRefs:p(Ze).max(1e3)}).strict(),yz=c({schemaVersion:S("openpond.harnessEvaluationReviewReceipt.v1"),id:Fe,ownerScope:hv,workspaceRef:Fe,harnessRelease:Ze,previousWatermark:r0.nullable(),nextWatermark:r0,selectedEvidence:p(Xl).max(1e4),excludedEvidence:p(gz).max(1e4),claim:vz.nullable(),classification:fz,triage:p(bz).max(16),reason:Jo,nextAuthority:hz,maxEstimatedCostUsd:u().finite().nonnegative(),tasksetProposal:Ze.nullable(),evaluation:Ze.nullable(),trainingQualification:Ze.nullable(),policyVersion:Fe,createdAt:It,metadata:Ju}).strict().superRefine((e,t)=>{const n=e.selectedEvidence.map(a=>`${a.evidence.id}:${a.evidence.contentHash}`);new Set(n).size!==n.length&&t.addIssue({code:"custom",message:"selected review evidence must be unique",path:["selectedEvidence"]}),e.selectedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"selected review evidence must be authorized at review time",path:["selectedEvidence"]}),e.classification==="no_action"?(e.nextAuthority!=="none"&&t.addIssue({code:"custom",message:"no-action review receipts require no next authority",path:["nextAuthority"]}),(e.tasksetProposal||e.evaluation||e.trainingQualification)&&t.addIssue({code:"custom",message:"no-action review receipts cannot carry downstream refs"})):(!e.claim||e.selectedEvidence.length===0)&&t.addIssue({code:"custom",message:"actionable review receipts require a claim and selected evidence"}),e.classification==="runtime"&&e.nextAuthority!=="runtime_service"&&t.addIssue({code:"custom",message:"runtime classifications route to runtime-service authority",path:["nextAuthority"]}),e.classification==="product"&&e.nextAuthority!=="product_team"&&t.addIssue({code:"custom",message:"product classifications route to product-team authority",path:["nextAuthority"]}),e.classification==="taskset"&&e.nextAuthority!=="human_review"&&t.addIssue({code:"custom",message:"Taskset classifications require human review"}),e.classification==="model_improvement"&&(!e.evaluation||!e.trainingQualification||!["human_review","training_system"].includes(e.nextAuthority))&&t.addIssue({code:"custom",message:"model-improvement classifications require Evaluation and qualification refs plus explicit authority"})});yz.extend({contentHash:Qe}).strict();c({id:Fe,evidence:Ze,kind:_I,sourceRef:Fe,occurredAt:It,payload:oe(i(),se())}).strict();var Sz=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("no_action"),reason:Jo,ignoredEvidence:p(c({id:Fe,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),xz=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("review"),classification:b(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(Fe).min(1).max(1e3),ignoredEvidence:p(c({id:Fe,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:i().trim().min(1).max(1e3),statement:Jo,triageLayer:RI,expectedOutcome:Jo,counterevidence:i().trim().max(1e4),confidence:u().min(0).max(1),candidateDisposition:b(["observe","confirm"]).nullable(),reason:Jo}).strict().superRefine((e,t)=>{e.classification==="harness_maintenance"!==(e.candidateDisposition!==null)&&t.addIssue({code:"custom",message:"Harness maintenance requires a candidate disposition; external routes require null",path:["candidateDisposition"]})}),kz=c({schemaVersion:S("openpond.harnessEvaluationReviewModelDecision.v2"),decision:S("resolve_candidate"),candidateId:Fe,candidateFingerprint:Qe,selectedEvidenceIds:p(Fe).min(1).max(1e3),ignoredEvidence:p(c({id:Fe,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:u().min(0).max(1),reason:Jo}).strict();vt("decision",[Sz,xz,kz]);c({schemaVersion:S("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(Fe).min(1).max(50),reason:Jo}).strict();var Us=oe(i(),se()).default({}),Aa=u().int().nonnegative(),Qu=i().trim().min(1).max(1e5),PI=c({kind:b(["personal","team"]),id:Fe}).strict(),wz=c({name:Fe,release:Ze.nullable(),revision:Aa}).strict();c({schemaVersion:S("openpond.harnessWorkspace.v1"),id:Fe,ownerScope:PI,name:i().trim().min(1).max(240),location:b(["local","hosted"]),sourceRevision:i().trim().min(1).max(500),revision:Aa,dirty:A(),currentChannel:wz,createdAt:It,updatedAt:It,metadata:Us}).strict();var Is=b(["runtime","memory","prompt","skill","agent","product","taskset","training"]),AI=b(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),TI=c({id:Fe,route:Is,operation:b(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),content:i().max(1e6).nullable(),contentHash:Qe.nullable(),effects:p(AI).min(1).max(20)}).strict().superRefine((e,t)=>{if(e.operation==="delete"){(e.content!==null||e.contentHash!==null)&&t.addIssue({code:"custom",message:"delete edits cannot include replacement content",path:["content"]});return}if(e.content===null||e.contentHash===null){t.addIssue({code:"custom",message:"create and update edits require content and contentHash",path:["content"]});return}const n=fa(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),EI=c({workspaceId:Fe,revision:Aa,sourceRevision:i().trim().min(1).max(500),channelRevision:Aa}).strict(),Zo=c({id:Fe,revision:Aa,contentHash:Qe}).strict();c({schemaVersion:S("openpond.harnessTurnSnapshot.v1"),workspaceId:Fe,workspaceRevision:Aa,sourceRevision:i().trim().min(1).max(500),channelName:Fe,channelRevision:Aa,harnessRelease:Ze,toolCatalogHash:Qe.nullable().optional(),overlay:Zo.nullable().optional().default(null)}).strict();var Iz=c({schemaVersion:S("openpond.harnessRunOverlay.v1"),id:Fe,runId:Fe,baseHarnessRelease:Ze,workspace:EI,revision:Aa,status:b(["active","frozen","abandoned"]),edits:p(TI).max(1e3),createdAt:It,updatedAt:It,metadata:Us}).strict();Iz.extend({contentHash:Qe}).strict();var MI=c({kind:b(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:Fe,contentHash:Qe.nullable()}).strict(),jI=c({id:Fe,kind:b(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Qu,required:A()}).strict(),_z=c({schemaVersion:S("openpond.harnessImprovementProposal.v1"),id:Fe,overlay:Zo,baseHarnessRelease:Ze,expectedWorkspace:EI,requestedScope:b(["personal","team","global"]),route:Is,risk:b(["low","review","restricted"]),effects:p(AI).min(1).max(20),evidence:p(MI).min(1).max(1e3),edits:p(TI).min(1).max(1e3),validationPlan:p(jI).min(1).max(100),expectedOutcome:Qu,createdAt:It,metadata:Us}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,o]of e.edits.entries()){o.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const r of o.effects)n.has(r)||t.addIssue({code:"custom",message:`edit effect ${r} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});_z.extend({contentHash:Qe}).strict();var Cz=c({schemaVersion:S("openpond.harnessTargetedValidationReceipt.v1"),id:Fe,proposal:Ze,validationId:Fe,kind:jI.shape.kind,status:b(["passed","failed","blocked","skipped"]),summary:Qu,evidenceRefs:p(MI).max(1e3),createdAt:It,metadata:Us}).strict();Cz.extend({contentHash:Qe}).strict();var Rz=b(["advanced","retained","conflict","rolled_back"]),Pz=c({schemaVersion:S("openpond.harnessAdvanceReceipt.v1"),id:Fe,workspaceId:Fe,ownerScope:PI,proposal:Ze.nullable(),expectedWorkspaceRevision:Aa,observedWorkspaceRevision:Aa,previousChannelRevision:Aa,nextChannelRevision:Aa,previousRelease:Ze.nullable(),nextRelease:Ze.nullable(),validationReceipts:p(Ze).max(100),decision:Rz,reason:Qu,rollbackOf:Ze.nullable(),createdAt:It,metadata:Us}).strict().superRefine((e,t)=>{const n=e.nextChannelRevision===e.previousChannelRevision+1;["advanced","rolled_back"].includes(e.decision)!==n&&t.addIssue({code:"custom",message:"only successful advancement or rollback increments the channel revision",path:["nextChannelRevision"]}),e.decision==="rolled_back"&&e.rollbackOf===null&&t.addIssue({code:"custom",message:"rollback receipts require rollbackOf",path:["rollbackOf"]}),e.decision!=="rolled_back"&&e.rollbackOf!==null&&t.addIssue({code:"custom",message:"rollbackOf is only valid for rollback receipts",path:["rollbackOf"]})});Pz.extend({contentHash:Qe}).strict();var Az=c({schemaVersion:S("openpond.harnessOverlayMergeReceipt.v1"),id:Fe,workspaceId:Fe,baseHarnessRelease:Ze,leftOverlay:Zo,rightOverlay:Zo,decision:b(["merged","conflict"]),mergedOverlay:Zo.nullable(),conflictTargets:p(i().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:S(!0),createdAt:It,metadata:Us}).strict().superRefine((e,t)=>{e.decision==="merged"!=(e.mergedOverlay!==null)&&t.addIssue({code:"custom",message:"merged decisions require a merged overlay; conflicts cannot provide one",path:["mergedOverlay"]}),e.decision==="conflict"!=e.conflictTargets.length>0&&t.addIssue({code:"custom",message:"conflict decisions require conflict targets and merged decisions cannot include them",path:["conflictTargets"]})});Az.extend({contentHash:Qe}).strict();var Xu=i().trim().min(1).max(1e5),Rc=oe(i(),se()).default({}),Tz=b(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),OI=c({kind:Tz,eventSequence:u().int().nonnegative(),occurredAt:It}).strict(),$I=c({id:Fe,sequence:u().int().nonnegative().nullable(),contentHash:Qe}).strict(),Ez=b(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),Mz=b(["open","recovered","terminal"]),jz=c({name:i().trim().min(1).max(500),invocationKey:Qe}).strict(),Oz=c({schemaVersion:S("openpond.improvementObservation.v1"),id:Fe,runRef:Fe,turnId:Fe,harnessRelease:Ze,overlay:Zo.nullable(),eventRefs:p($I).min(1).max(100),kind:Ez,state:Mz,tool:jz.nullable(),deterministicClass:i().trim().min(1).max(500).nullable(),summary:Xu,createdAt:It,metadata:Rc}).strict().superRefine((e,t)=>{new Set(e.eventRefs.map(n=>n.id)).size!==e.eventRefs.length&&t.addIssue({code:"custom",message:"observation event refs must be unique",path:["eventRefs"]}),["tool_failure","retry","recovery","completion_detour"].includes(e.kind)&&e.tool===null&&t.addIssue({code:"custom",message:`${e.kind} observations require a tool identity`,path:["tool"]})});Oz.extend({contentHash:Qe}).strict();var $z=c({schemaVersion:S("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:u().finite().nonnegative(),cooldownMs:u().int().nonnegative(),maxPendingPlans:u().int().min(1).max(100),maxEvidenceEvents:u().int().min(1).max(1e3),maxProposalEdits:u().int().min(1).max(1e3),maxProposalBytes:u().int().min(1).max(1e7)}).strict(),Nz=b(["no_action","route_deterministically","queue_refiner"]),Dz=c({schemaVersion:S("openpond.refinementTriggerDecision.v1"),id:Fe,runRef:Fe,turnId:Fe,harnessRelease:Ze,overlay:Zo.nullable(),observations:p(Ze).max(100),decision:Nz,deterministicRoute:Is.nullable(),suggestedRoutes:p(Is).max(8),reason:Xu,deduplicationKey:Qe,policy:$z,estimatedMaxCostUsd:u().finite().nonnegative(),pendingPlanCount:u().int().nonnegative(),boundary:OI,cooldownUntil:It.nullable(),createdAt:It,metadata:Rc}).strict().superRefine((e,t)=>{e.estimatedMaxCostUsd>e.policy.maxEstimatedCostUsd&&t.addIssue({code:"custom",message:"estimated Refiner cost exceeds the trigger policy budget",path:["estimatedMaxCostUsd"]}),e.pendingPlanCount>e.policy.maxPendingPlans&&t.addIssue({code:"custom",message:"pending plan count exceeds the trigger policy limit",path:["pendingPlanCount"]}),e.observations.length>e.policy.maxEvidenceEvents&&t.addIssue({code:"custom",message:"trigger observations exceed the evidence budget",path:["observations"]}),e.decision==="route_deterministically"&&e.deterministicRoute===null&&t.addIssue({code:"custom",message:"deterministic decisions require a route",path:["deterministicRoute"]}),e.decision!=="route_deterministically"&&e.deterministicRoute!==null&&t.addIssue({code:"custom",message:"only deterministic decisions may declare a deterministic route",path:["deterministicRoute"]}),e.decision==="no_action"&&e.suggestedRoutes.length>0&&t.addIssue({code:"custom",message:"no-action decisions cannot suggest routes",path:["suggestedRoutes"]}),e.decision!=="no_action"&&e.observations.length===0&&t.addIssue({code:"custom",message:"actionable trigger decisions require observations",path:["observations"]})});Dz.extend({contentHash:Qe}).strict();var Lz=b(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),Hz=c({schemaVersion:S("openpond.improvementRouteDecision.v1"),id:Fe,trigger:Ze,route:Is,authority:Lz,automatic:A(),reason:Xu,createdAt:It,metadata:Rc}).strict().superRefine((e,t)=>{e.automatic&&["human_review","evaluation_system","training_system"].includes(e.authority)&&t.addIssue({code:"custom",message:`${e.authority} routes cannot be marked automatic`,path:["automatic"]}),e.route==="training"&&e.automatic&&e.authority!=="training_system"&&t.addIssue({code:"custom",message:"automatic training routes require training-system authority",path:["authority"]})});Hz.extend({contentHash:Qe}).strict();var Uz=c({schemaVersion:S("openpond.harnessRefinerOutcome.v1"),id:Fe,trigger:Ze,decision:b(["no_action","proposed"]),proposal:Ze.nullable(),reason:Xu,evidenceRefs:p(Ze).max(100),estimatedCostUsd:u().finite().nonnegative(),createdAt:It,metadata:Rc}).strict().superRefine((e,t)=>{e.decision==="proposed"!=(e.proposal!==null)&&t.addIssue({code:"custom",message:"proposed Refiner outcomes require a proposal; no-action outcomes cannot include one",path:["proposal"]})});Uz.extend({contentHash:Qe}).strict();var qz=b(["applied","retained","declined","conflict","rolled_back"]),zz=c({schemaVersion:S("openpond.improvementApplyReceipt.v1"),id:Fe,proposal:Ze,beforeOverlay:Zo,afterOverlay:Zo.nullable(),decision:qz,boundary:OI,validationRefs:p(Ze).max(100),outcomeEvidenceRefs:p($I).max(1e3),rollbackOf:Ze.nullable(),createdAt:It,metadata:Rc}).strict().superRefine((e,t)=>{e.decision==="applied"!=(e.afterOverlay!==null)&&t.addIssue({code:"custom",message:"applied receipts require an after-overlay; other decisions cannot include one",path:["afterOverlay"]}),e.decision==="rolled_back"!=(e.rollbackOf!==null)&&t.addIssue({code:"custom",message:"only rollback receipts require rollbackOf",path:["rollbackOf"]})});zz.extend({contentHash:Qe}).strict();c({provider:Fe,model:Fe,revision:i().trim().min(1).max(500).nullable().default(null),artifactHash:Qe.nullable().default(null),tokenizerRevision:i().trim().min(1).max(500).nullable().default(null),chatTemplateHash:Qe.nullable().default(null)}).strict();var Bz=["openpond","codex","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Fz=b(Bz),NI=c({providerId:Fz,modelId:i().trim().min(1).max(300)}),Vz=i().trim().min(1).max(2e3),gv=i().trim().min(1).max(1e5),Kz=b(["create","update","delete"]),Wz=b(["memory","prompt","skill","agent"]),Gz=b(["runtime","product","taskset","training"]),Jz=b(["no_action","routed","applied","retained","failed"]),Zz=b(["not_applicable","pending","passed","rejected","failed"]),Yz=b(["not_applicable","pending","passed","failed"]),Qz=c({schemaVersion:S("openpond.harnessRefinerActivityReceipt.v1"),id:Fe,runRef:Fe,turnId:Fe,result:Jz,decision:b(["no_action","route","propose"]).nullable(),route:Is.nullable(),operation:Kz.nullable(),target:i().trim().min(1).max(2e3).nullable(),summary:Vz,evidenceBasis:rv.nullable(),critiqueStatus:Zz,validationStatus:Yz,trigger:Ze,outcome:Ze.nullable(),proposal:Ze.nullable(),applyReceipt:Ze.nullable(),inputHarness:Ze,outputHarness:Ze.nullable(),createdAt:It}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?s0(t,e,{decision:"no_action",route:null,operation:null,target:null,evidenceBasis:null,proposal:null,applyReceipt:null,outputHarness:null,critiqueStatus:"not_applicable",validationStatus:"not_applicable"}):e.result==="routed"?((e.decision!=="route"||!Gz.safeParse(e.route).success||e.operation!==null||e.target!==null||e.evidenceBasis===null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"routed activity requires an external route and evidence basis without proposal state"}),s0(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!Wz.safeParse(e.route).success||e.operation===null||e.target===null||e.evidenceBasis===null||e.proposal===null||e.applyReceipt===null)&&t.addIssue({code:"custom",message:"applied and retained activity requires complete proposal state"}),e.result==="applied"&&e.outputHarness===null&&t.addIssue({code:"custom",message:"applied activity requires the advanced Harness release",path:["outputHarness"]}),e.result==="applied"&&(e.critiqueStatus!=="passed"||e.validationStatus!=="passed")&&t.addIssue({code:"custom",message:"applied activity requires passed critique and validation"}),e.result==="retained"&&e.outputHarness!==null&&t.addIssue({code:"custom",message:"retained activity cannot report a new Harness release",path:["outputHarness"]})):(e.decision!==null||e.route!==null||e.operation!==null||e.target!==null||e.evidenceBasis!==null||e.outcome!==null||e.proposal!==null||e.applyReceipt!==null||e.outputHarness!==null)&&t.addIssue({code:"custom",message:"failed activity cannot claim a decision, route, proposal, or release transition"}),e.result!=="failed"&&e.outcome===null&&t.addIssue({code:"custom",message:"terminal Refiner decisions require an outcome reference",path:["outcome"]})});Qz.extend({contentHash:Qe}).strict();var Xz=b(["unresolved","confirmed","resolved","rejected","expired"]),eB=c({kind:b(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:gv,evidenceRefs:p(Ze).max(1e3),resolvedAt:It}).strict(),tB=c({schemaVersion:S("openpond.harnessRefinementCandidate.v1"),id:Fe,ownerScope:hv,workspaceRef:Fe,fingerprint:Qe,recurrenceFamily:i().trim().min(1).max(1e3),statement:gv,status:Xz,occurrences:p(Xl).max(1e3),counterevidence:p(Xl).max(1e3),sourceReviews:p(Ze).min(1).max(100),relatedHarnessReleases:p(Ze).max(100),firstSeenAt:It,lastSeenAt:It,lastReviewedAt:It,expiresAt:It,resolution:eB.nullable(),createdAt:It,updatedAt:It}).strict().superRefine((e,t)=>{er(t,e.occurrences,"occurrences"),er(t,e.counterevidence,"counterevidence"),er(t,e.sourceReviews,"sourceReviews"),er(t,e.relatedHarnessReleases,"relatedHarnessReleases");const n=new Set(e.occurrences.map(o=>o.occurrenceKey));e.counterevidence.some(o=>n.has(o.occurrenceKey))&&t.addIssue({code:"custom",message:"supporting occurrences and counterevidence must be disjoint",path:["counterevidence"]});const a=e.status==="unresolved"||e.status==="confirmed";a&&e.occurrences.length===0&&t.addIssue({code:"custom",message:"actionable candidates require at least one supporting occurrence",path:["occurrences"]}),a&&[...e.occurrences,...e.counterevidence].some(o=>o.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"actionable candidates may contain only currently authorized evidence",path:["occurrences"]}),a!==(e.resolution===null)&&t.addIssue({code:"custom",message:"only resolved, rejected, or expired candidates require a resolution",path:["resolution"]}),e.status==="expired"&&e.resolution?.kind!=="expired"&&t.addIssue({code:"custom",message:"expired candidates require an expired resolution",path:["resolution","kind"]}),e.status==="rejected"&&e.resolution&&!["manual_rejection","source_revoked"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"rejected candidates require a rejection or revocation resolution",path:["resolution","kind"]}),e.status==="resolved"&&e.resolution&&!["applied_change","later_success"].includes(e.resolution.kind)&&t.addIssue({code:"custom",message:"resolved candidates require applied-change or later-success evidence",path:["resolution","kind"]}),rB(t,e)});tB.extend({contentHash:Qe}).strict();var nB=b(["created","merged","rejected","expired","reopened","resolved"]),aB=c({schemaVersion:S("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:Fe,candidateId:Fe,decision:nB,beforeCandidate:Ze.nullable(),afterCandidate:Ze,review:Ze,addedEvidence:p(Xl).max(1e3),removedEvidence:p(Ze).max(1e3),reason:gv,createdAt:It}).strict().superRefine((e,t)=>{e.decision==="created"!=(e.beforeCandidate===null)&&t.addIssue({code:"custom",message:"only candidate creation omits the previous candidate reference",path:["beforeCandidate"]}),e.beforeCandidate&&e.beforeCandidate.contentHash===e.afterCandidate.contentHash&&t.addIssue({code:"custom",message:"candidate lifecycle transitions must change candidate content",path:["afterCandidate"]}),["created","reopened"].includes(e.decision)&&e.addedEvidence.length===0&&t.addIssue({code:"custom",message:`${e.decision} candidate transitions require added evidence`,path:["addedEvidence"]}),e.addedEvidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"candidate transitions may add only authorized evidence",path:["addedEvidence"]}),er(t,e.addedEvidence,"addedEvidence"),er(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>vh(a)));e.addedEvidence.some(a=>n.has(vh(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});aB.extend({contentHash:Qe}).strict();var oB=c({schemaVersion:S("openpond.harnessCrossRunRefinementRequest.v1"),id:Fe,ownerScope:hv,workspaceRef:Fe,candidate:Ze,candidateFingerprint:Qe,review:Ze,admittedHarness:Ze,evidence:p(Xl).min(1).max(1e3),capabilities:sv,deduplicationKey:Qe,createdAt:It}).strict().superRefine((e,t)=>{e.evidence.some(a=>a.sourcePolicy.state!=="authorized")&&t.addIssue({code:"custom",message:"cross-run refinement requires currently authorized evidence",path:["evidence"]}),er(t,e.evidence,"evidence"),Object.values(e.capabilities).some(Boolean)||t.addIssue({code:"custom",message:"cross-run refinement requires at least one available Harness capability",path:["capabilities"]});const n=iB(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});oB.extend({contentHash:Qe}).strict();function iB(e){return fa({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function s0(e,t,n){for(const[a,o]of Object.entries(n))t[a]!==o&&e.addIssue({code:"custom",message:`${a} must be ${String(o)}`,path:[a]})}function er(e,t,n){const a=t.map(o=>vh(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function vh(e){if(!e||typeof e!="object"||Array.isArray(e))return String(e);const t=e;if(typeof t.occurrenceKey=="string")return t.occurrenceKey;const n=t.evidence;if(n&&typeof n=="object"&&!Array.isArray(n)){const a=n;return`${String(a.id)}:${String(a.contentHash)}`}return`${String(t.id)}:${String(t.contentHash)}`}function rB(e,t){const n=[["firstSeenAt",t.firstSeenAt],["lastSeenAt",t.lastSeenAt],["lastReviewedAt",t.lastReviewedAt],["updatedAt",t.updatedAt],["expiresAt",t.expiresAt]];for(let a=1;a<n.length;a+=1){const o=n[a-1],r=n[a];Date.parse(o[1])<=Date.parse(r[1])||e.addIssue({code:"custom",message:`${r[0]} must not precede ${o[0]}`,path:[r[0]]})}Date.parse(t.createdAt)>Date.parse(t.updatedAt)&&e.addIssue({code:"custom",message:"updatedAt must not precede createdAt",path:["updatedAt"]})}c({path:i().min(1).max(2e3),offset:u().int().nonnegative().default(0),length:u().int().positive().max(65536).default(16384)}).strict();var DI=i().regex(/^[a-z][a-z0-9_-]{0,119}$/),LI=i().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"workflow references require portable relative paths"),sB=c({id:DI,label:i().trim().min(1).max(240),description:i().max(4e3),inputSchema:oe(i(),se()),invocation:vt("kind",[c({kind:S("instructions"),instructions:i().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),c({kind:S("agent_action"),actionId:i().trim().min(1).max(240)}).strict()]),skillPaths:p(LI).max(100)}).strict();c({schemaVersion:S("openpond.profileWorkflows.v1"),workflows:p(sB).max(1e3)}).strict();var lB=c({id:i().trim().min(1).max(240),agentId:i().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:i().trim().min(1).max(240),inputSchema:oe(i(),se())}).strict();c({schemaVersion:S("openpond.profileWorkflowActions.v1"),actions:p(lB).max(200)}).strict();c({schemaVersion:S("openpond.profileWorkflowBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:Ze,catalogHash:Qe,workflowId:DI}).strict();c({schemaVersion:S("openpond.profileComponentBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:Ze,target:vt("kind",[c({kind:S("profile")}).strict(),c({kind:S("skill"),skillPath:LI}).strict(),c({kind:S("agent_action"),actionId:i().trim().min(1).max(240)}).strict()])}).strict();var su=i().min(1).max(2e3).refine(e=>!e.includes("\\")&&!e.includes(":")&&!e.startsWith("/")&&e.split("/").every(t=>t!==""&&t!=="."&&t!==".."),"source paths must be portable relative paths");i().regex(/^[a-z][a-z0-9_-]{0,119}$/);var cB={type:"object",properties:{},additionalProperties:!1};c({name:i().trim().min(1).max(240).optional(),description:i().max(4e3).optional(),skillPaths:p(su).max(100).optional(),assetPaths:p(su).max(100).optional()}).strict();c({actionId:i().trim().min(1).max(240),name:i().trim().min(1).max(240),description:i().max(4e3).default(""),inputSchema:oe(i(),se()).default(cB),skillPaths:p(su).max(100).default([]),assetPaths:p(su).max(100).default([])}).strict();var ja=i().trim().min(1).max(240),Yo=i().trim().min(1),Pi=i().trim().min(8).max(256),HI=i().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),Ei=b(["train","validation","test","frozen_eval"]),dB=c({name:i().trim().min(1).max(500),semanticRole:b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:b(["string","integer","float","boolean","json","messages"]),nullable:A(),policy:b(["visible","privileged","metadata"])}),uB=c({schemaVersion:S("openpond.datasetSemanticSchema.v1"),fields:p(dB).min(1).max(1e4),schemaHash:Pi}),mB=c({id:ja,split:Ei,path:HI,contentHash:Pi,schemaHash:Pi,sizeBytes:u().int().nonnegative(),rowCount:u().int().positive(),rowGroupCount:u().int().positive()}),vv=c({schemaVersion:S("openpond.datasetArtifact.v1"),id:ja,tasksetId:ja,tasksetRevision:u().int().positive(),contentHash:Pi,format:S("parquet"),schema:uB,shards:p(mB).min(1).max(1e5),rowCount:u().int().positive(),splitCounts:oe(Ei,u().int().nonnegative()),sourceReceiptRefs:p(ja).min(1).max(1e5),mappingHash:Pi,qualityReportHash:Pi,createdAt:Yo}),pB=c({schemaVersion:S("openpond.datasetArtifactSummary.v1"),artifactId:ja,tasksetId:ja,tasksetRevision:u().int().positive(),format:S("parquet"),rowCount:u().int().positive(),splitCounts:oe(Ei,u().int().nonnegative()),sizeBytes:u().int().nonnegative(),contentHash:Pi,available:A(),unavailableReason:i().trim().min(1).max(2e3).nullable(),createdAt:Yo}),fB=c({schemaVersion:S("openpond.datasetCatalogItem.v1"),tasksetId:ja,tasksetRevision:u().int().positive(),artifactId:ja.nullable(),name:i().trim().min(1).max(500),status:b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:b(["inline","parquet"]),rowCount:u().int().nonnegative(),splitCounts:oe(Ei,u().int().nonnegative()),sizeBytes:u().int().nonnegative().nullable(),available:A(),unavailableReason:i().trim().min(1).max(2e3).nullable(),createdAt:Yo,updatedAt:Yo});c({schemaVersion:S("openpond.datasetCatalog.v1"),profileId:ja,datasets:p(fB),generatedAt:Yo});c({schemaVersion:S("openpond.datasetArtifactRegistry.v1"),manifest:vv,profileId:ja,storageRoot:i().trim().min(1).max(4e3),relativeManifestPath:HI,available:A(),unavailableReason:i().trim().min(1).max(2e3).nullable(),verifiedAt:Yo.nullable(),createdAt:Yo,updatedAt:Yo});c({split:Ei.nullable().default(null),cursor:i().trim().min(1).max(2e3).nullable().default(null),limit:u().int().min(1).max(100).default(25),columns:p(i().trim().min(1).max(500)).max(100).default([])});c({schemaVersion:S("openpond.datasetRowPage.v1"),tasksetId:ja,tasksetRevision:u().int().positive(),artifactHash:Pi,split:Ei.nullable(),rows:p(oe(i(),se())).max(100),nextCursor:i().max(2e3).nullable(),totalRows:u().int().nonnegative(),returnedRows:u().int().nonnegative()});var hB=c({schemaVersion:S("openpond.datasetStorageSettings.v1"),datasetStorePath:i().trim().min(1).max(4e3),updatedAt:Yo}),gB=c({id:ja,label:i().trim().min(1).max(500),path:i().trim().min(1).max(4e3),datasetStorePath:i().trim().min(1).max(4e3),kind:b(["local","network","removable","cache"]),configured:A(),mounted:A(),writable:A(),totalBytes:u().int().nonnegative().nullable(),freeBytes:u().int().nonnegative().nullable()});c({schemaVersion:S("openpond.datasetStorageState.v1"),settings:hB,storageRoots:p(gB)});c({datasetStorePath:i().trim().min(1).max(4e3)});var fs=i().trim().min(1).max(240),vB=i().trim().min(1),_s=i().trim().min(8).max(256),bB=oe(i(),se()).default({}),yB=i().trim().min(7).max(256),SB=b(["pending","approved","review","blocked"]),em=c({id:fs,profileId:fs,title:i().trim().min(1).max(500),sourceHash:_s,occurredAt:vB,licensingStatus:SB,secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),metadata:bB}),xB=em.extend({schemaVersion:S("openpond.huggingFaceDatasetSource.v1"),kind:S("huggingface"),repositoryId:i().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:i().url().max(2e3),revision:yB,configuration:i().trim().min(1).max(500),upstreamSplits:p(i().trim().min(1).max(500)).min(1).max(1e3),gated:A(),private:A(),declaredLicense:i().trim().min(1).max(500).nullable(),sourceFileHashes:p(_s).min(1).max(1e5)}),kB=em.extend({schemaVersion:S("openpond.uploadedFileDatasetSource.v1"),kind:S("uploaded_file"),originalFileNames:p(i().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:p(i().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:p(_s).min(1).max(1e3),totalBytes:u().int().nonnegative(),parserVersion:i().trim().min(1).max(200)}),wB=em.extend({schemaVersion:S("openpond.generatedDatasetSource.v1"),kind:S("generated"),generatorId:fs,generatorVersion:i().trim().min(1).max(200),seed:u().int(),generatorHash:_s}),IB=em.extend({schemaVersion:S("openpond.learningBatchDatasetSource.v1"),kind:S("learning_batch"),batch:c({id:fs,revision:u().int().positive(),contentHash:_s}).strict(),taskDefinition:c({id:fs,revision:u().int().positive(),contentHash:_s}).strict(),admittedBy:fs}),_B=vt("kind",[xB,kB,wB,IB]),CB=c({schemaVersion:S("openpond.harnessActionBinding.v1"),actionId:Fe,modelToolName:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(1e3),inputSchema:oe(i(),se()),actionSchemaHash:Qe,agentRelease:Ze,implementationHash:Qe,runtimeBindingId:Fe,capabilityReceiptHash:Qe,sideEffect:b(["read","write"]),studentVisible:A(),timeoutMs:u().int().positive().max(36e5),episodeArgumentBindings:p(c({argument:Fe,source:S("case_id")}).strict()).max(20).default([])}).strict(),Pt=i().trim().min(1).max(240),bv=i().trim().min(1),RB=i().trim().min(8).max(256),yv=i().trim().regex(/^[a-f0-9]{64}$/),PB=i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),no=oe(i(),se()).default({}),tm=Pt.nullable();function Pc(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function AB(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var Cs=Ei,UI=b(["general","benchmark"]),qI=c({schemaVersion:S("openpond.tasksetBenchmark.v1"),definitionId:Pt,releaseId:Pt,releaseHash:yv,managedReleasePath:i().trim().min(1).max(1e3).refine(Pc,"Benchmark release paths must remain relative."),adaptationSplit:Cs,evaluationSplit:Cs,primaryMetric:b(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:b(["none","non_regression","all_pass"]),source:b(["builtin","imported"]),metadata:no}),zI=c({schemaVersion:S("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Pt,releaseHash:yv,publishedAt:bv,metadata:no}),TB=c({status:b(["pending","granted","denied","revoked"]),scope:b(["metadata_only","selected_turns","full_session"]),grantedBy:tm,grantedAt:bv.nullable(),purpose:S("task_authoring_and_evaluation")}),BI=c({schemaVersion:S("openpond.trainingSource.v1"),id:Pt,profileId:Pt,sessionId:Pt,turnIds:p(Pt).max(1e3).default([]),workspaceId:tm,sourceHash:RB,clusterKey:Pt,title:i().trim().min(1).max(500),occurredAt:bv,consent:TB,connectedAppIds:p(Pt).max(100).default([]),secretScanStatus:b(["pending","passed","blocked"]),piiScanStatus:b(["pending","passed","review","blocked"]),licensingStatus:b(["pending","approved","review","blocked"]),metadata:no}),FI=Tt([BI,_B]),Sv=c({policyVisibleFields:p(Pt).max(1e3).default([]),privilegedFields:p(Pt).max(1e3).default([]),hiddenGraderRefs:p(Pt).max(100).default([]),connectedAppScopes:p(Pt).max(100).default([])}),EB=c({id:Pt,sourceRefId:Pt,artifactRef:i().trim().min(1).max(4e3).refine(Pc,"Task asset references must be safe relative paths."),fileName:i().trim().min(1).max(500).refine(AB,"Task asset file names must not contain path separators."),mediaType:i().trim().min(1).max(200),sha256:yv,sizeBytes:u().int().nonnegative().max(25e7),split:Cs,metadata:no}),MB=c({path:i().trim().min(1).max(1e3).refine(Pc,"Required output paths must stay inside the Work output directory."),mediaType:i().trim().min(1).max(200),schemaRef:Pt.nullable().optional(),maxBytes:u().int().positive().max(1e7).optional(),metadata:no}),xv=c({schemaVersion:S("openpond.taskData.v1"),id:Pt,clusterKey:Pt,split:Cs,input:oe(i(),se()),expectedOutput:oe(i(),se()).nullable(),policyVisibleContext:oe(i(),se()).default({}),privilegedContextRef:tm,sourceRefs:p(Pt).min(1).max(100),assets:p(EB).max(1e3).optional(),resourceRefs:p(Pt).max(1e3).optional(),requiredOutputs:p(MB).max(100).optional(),tags:p(Pt).max(100).default([]),metadata:no}),jB=c({id:Pt,kind:b(["file","catalog","configuration","code_module"]),path:i().trim().min(1).max(1e3).refine(Pc,"Environment resource paths must remain relative."),mediaType:i().trim().min(1).max(200).nullable().optional(),visibility:b(["policy_visible","policy_hidden","privileged"]),required:A(),metadata:no}),qs=c({id:Pt,taskId:tm,sourceRefs:p(Pt).min(1).max(100),artifactRef:Pt,approved:A(),confidence:u().min(0).max(1),metadata:no}),VI=qs.extend({kind:S("demonstration"),prompt:i().max(1e5).nullable().default(null),response:i().max(2e5).nullable().default(null)}),KI=qs.extend({kind:S("preference"),prompt:i().max(1e5),chosen:i().max(2e5),rejected:i().max(2e5),rationale:i().max(1e5).nullable().default(null)}),WI=qs.extend({kind:S("correction"),original:i().max(2e5),corrected:i().max(2e5),rationale:i().max(1e5).nullable().default(null)}),GI=qs.extend({kind:S("feedback"),feedback:i().max(1e5),polarity:b(["positive","negative","mixed","neutral"])}),JI=qs.extend({kind:S("reward"),task:i().max(1e5),rules:p(c({id:Pt,points:u().finite(),condition:i().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:u().finite(),executable:A()}),ZI=qs.extend({kind:S("label"),labelKind:S("rubric"),task:i().max(1e5),criteria:p(c({id:Pt,label:i().trim().min(1).max(500),description:i().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:c({positive:i().trim().min(1).max(2e5),negative:i().trim().min(1).max(2e5),boundary:i().trim().min(1).max(2e5)})});vt("kind",[VI,KI,WI,GI,JI,ZI]);var YI=c({demonstrations:p(VI).max(1e5).default([]),preferences:p(KI).max(1e5).default([]),corrections:p(WI).max(1e5).default([]),feedback:p(GI).max(1e5).default([]),rewards:p(JI).max(1e5).default([]),labels:p(ZI).max(1e5).default([])}),QI=c({protocolVersion:S("openpond.taskEnvironment.v1"),kind:b(["chat","agent","program","stateful_harness","work"]),entrypoint:i().trim().min(1).max(1e3),stateful:A(),deterministicSeeds:A(),toolNames:p(Pt).max(200).default([]),actionBindings:p(CB).max(200).optional(),lifecycle:p(b(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:u().int().positive().max(36e5),networkPolicy:b(["none","declared_read_only","declared_scoped"]),resources:p(jB).max(1e4).optional(),metadata:no}),kv=c({schemaVersion:S("openpond.tasksetCapabilities.v1"),taskKind:b(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:p(b(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:p(b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:p(b(["none","exact","deterministic","model_judge","human"])),requiresTools:A(),requiresState:A(),requiresPrivilegedGrading:A(),environmentPlacements:p(b(["local","remote","colocated","provider_native"])),exportable:A(),portabilityBlockers:p(i().trim().min(1).max(2e3)).default([])}),nm=c({id:Pt,version:i().trim().min(1).max(100),label:i().trim().min(1).max(500),weight:u().min(0).max(1e3).default(1),hardGate:A().default(!1),rewardEligible:A().default(!1),privileged:A().default(!1),metadata:no}),OB=nm.extend({kind:b(["content","schema","file","diff","test","runtime_event","state"]),config:oe(i(),se())}),$B=nm.extend({kind:S("model_judge"),rubric:i().trim().min(1).max(5e4),judge:NI,calibrationFixtureRefs:p(Pt).min(1).max(500),calibrationStatus:b(["pending","passed","failed"]),temperature:u().min(0).max(2).default(0)}),NB=nm.extend({kind:S("human"),rubric:i().trim().min(1).max(5e4),reviewerRole:i().trim().min(1).max(500)}),DB=nm.extend({kind:S("custom_verifier"),runtime:Tw.optional(),module:i().trim().min(1).max(1e3).refine(Pc,"Custom verifier modules must use a safe relative path."),exportName:PB,timeoutMs:u().int().positive().max(3e5),networkPolicy:S("none")}),am=Tt([OB,$B,NB,DB]),wv=b(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),XI=c({id:Pt,taskId:Pt,label:wv,output:oe(i(),se()),infrastructureError:i().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:no}),So=i().trim().min(1).max(240),ec=i().trim().min(1),lu=i().trim().min(8).max(256),e_=oe(i(),se()).default({}),LB=So.nullable(),HB=b(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),t_=b(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),qn=i().trim().max(1e5),n_=vt("kind",[c({kind:S("demonstrations"),behavior:qn,examples:p(c({id:So,prompt:qn,response:qn})).max(1e3).default([])}),c({kind:S("preferences"),preference:qn,pairs:p(c({id:So,prompt:qn,chosen:qn,rejected:qn,rationale:qn})).max(1e3).default([])}),c({kind:S("verifiable_reward"),task:qn,rules:p(c({id:So,points:u().finite(),condition:qn})).max(1e3).default([]),otherwisePoints:u().finite().default(0)}),c({kind:S("rubric"),task:qn,criteria:p(c({id:So,label:i().trim().max(500),description:qn})).max(1e3).default([]),positiveExample:qn,negativeExample:qn,boundaryExample:qn})]),UB=c({path:i().trim().min(1).max(1e3),role:b(["environment","verifier","fixture"]),content:i().max(25e4)}),a_=c({primaryMethod:b(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:c({method:S("sft"),purpose:S("trajectory_bootstrap"),demonstrationRefs:p(So).min(1).max(1e5),limitations:p(i().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),o_=b(["taskset_not_ready","demonstrations_missing","preference_pairs_missing","preference_pairs_invalid","executable_reward_missing","reward_not_calibrated","reward_model_missing","value_model_required","frozen_eval_missing"]),qB=c({method:b(["sft","dpo","grpo","ppo"]),status:b(["recommended","compatible","needs_dataset_work"]),reasonCodes:p(o_).default([]),reasons:p(i().trim().min(1).max(5e3)).default([])}),l0=c({code:So,message:i().trim().min(1).max(5e3),path:i().trim().max(2e3).nullable()}),i_=c({schemaVersion:S("openpond.tasksetReadiness.v1"),tasksetId:So,tasksetHash:lu,ready:A(),recommendedMethod:b(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:a_.nullable().default(null),methodReadiness:p(qB).default([]),compatibleDestinationClasses:p(b(["export","custom","hosted_managed"])),blockers:p(l0).default([]),advisories:p(l0).default([]),warnings:p(i().trim().min(1).max(5e3)).default([]),generatedAt:ec}),r_=c({attempt:u().int().positive(),summary:i().trim().min(1).max(5e3),createdAt:ec}),zB=c({schemaVersion:S("openpond.taskAuthoringProvenance.v1"),model:NI.nullable(),modelConfig:e_,skillHash:lu,promptTemplateVersion:i().trim().min(1).max(200),buildIntent:t_.default("demonstrations"),buildSpecification:n_.nullable().default(null),evidenceHashes:p(lu).max(1e5),tasksetSdkVersion:i().trim().min(1).max(100),sourceCommit:i().trim().min(1).max(256).nullable(),repairHistory:p(r_).max(1e3),createdAt:ec}),c0=c({schemaVersion:S("openpond.taskset.v1"),id:So,revision:u().int().positive().default(1),profileId:So,profileRelease:GU.nullable().optional(),createImproveRunId:LB.default(null),name:i().trim().min(1).max(500),objective:i().trim().max(2e4),purpose:UI.default("general"),benchmark:qI.nullable().default(null),preferenceComparison:zI.nullable().default(null),status:HB,sourceRefs:p(FI).min(1).max(1e5),datasetArtifact:vv.nullable().optional(),policy:Sv,environment:QI,capabilities:kv,metrics:Ic.optional(),tasks:p(xv).max(1e6),graders:p(am).min(1).max(1e3),graderFixtures:p(XI).max(1e5),learningSignals:YI,authoringProvenance:zB,readiness:i_.nullable(),contentHash:lu,createdAt:ec,updatedAt:ec,metadata:e_}).superRefine((e,t)=>{e.purpose==="benchmark"&&!e.benchmark&&t.addIssue({code:"custom",message:"Benchmark Tasksets require an immutable benchmark binding.",path:["benchmark"]}),e.purpose!=="benchmark"&&e.benchmark&&t.addIssue({code:"custom",message:"Only benchmark Tasksets may carry a benchmark binding.",path:["benchmark"]}),e.datasetArtifact&&e.tasks.length>0&&t.addIssue({code:"custom",message:"Artifact-backed Tasksets may not duplicate canonical rows inline.",path:["tasks"]}),!e.datasetArtifact&&e.tasks.length===0&&t.addIssue({code:"custom",message:"A Taskset requires inline tasks or a Dataset artifact manifest.",path:["tasks"]})});function BB(e){return e.schemaVersion==="openpond.trainingSource.v1"}var is=i().trim().min(1).max(240),d0=i().trim().min(1),FB=i().trim().min(8).max(256),VB=i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),KB=oe(i(),se()).default({});function u0(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var s_=xv.extend({sourceRefs:p(is).max(100).default([])}),l_=b(["draft","validating","needs_review","published"]),WB=c({enabled:A(),candidateCount:u().int().min(2).max(4),minimumSamples:u().int().min(1).max(1e4).default(100),allowTies:A(),allowRejectAll:A(),rubric:i().trim().max(5e4),criteria:p(c({id:is,label:i().trim().min(1).max(500),description:i().trim().max(1e4),weight:u().nonnegative().max(1e3)})).max(100)}),GB=c({mode:b(["text","structured_json","artifacts"]),jsonSchema:oe(i(),se()).nullable(),renderer:c({module:i().trim().min(1).max(1e3).refine(u0,"Renderer modules must use a safe relative path."),exportName:VB,configRef:i().trim().min(1).max(1e3).refine(u0,"Renderer configuration must use a safe relative path.").nullable().default(null)}).nullable()}).superRefine((e,t)=>{e.mode==="structured_json"&&!e.jsonSchema&&t.addIssue({code:"custom",message:"Structured JSON output requires a JSON Schema.",path:["jsonSchema"]}),e.mode==="text"&&e.renderer&&t.addIssue({code:"custom",message:"Text output cannot configure an artifact renderer.",path:["renderer"]})}),Xa=c({schemaVersion:S("openpond.tasksetDraft.v1"),id:is,revision:u().int().positive(),profileId:is,modelScope:c({modelId:is,expectedModelRevision:u().int().positive(),source:RU.optional()}).strict().nullable().default(null),name:i().trim().max(500),objective:i().trim().max(2e4),purpose:UI.default("general"),benchmark:qI.nullable().default(null),preferenceComparison:zI.nullable().default(null),status:l_,sourceRefs:p(FI).max(1e5).default([]),datasetArtifact:vv.nullable().optional(),policy:Sv,environment:QI,output:GB.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:kv,metrics:Ic,review:WB,tasks:p(s_).max(1e6).default([]),graders:p(am).max(1e3).default([]),graderFixtures:p(XI).max(1e5).default([]),learningSignals:YI,publishedTasksetRef:c({id:is,revision:u().int().positive(),contentHash:FB}).nullable(),createdAt:d0,updatedAt:d0,metadata:KB}).superRefine((e,t)=>{e.purpose==="benchmark"&&!e.benchmark&&t.addIssue({code:"custom",message:"Benchmark drafts require an immutable benchmark binding.",path:["benchmark"]}),e.purpose!=="benchmark"&&e.benchmark&&t.addIssue({code:"custom",message:"Only benchmark drafts may carry a benchmark binding.",path:["benchmark"]}),e.datasetArtifact&&e.tasks.length>0&&t.addIssue({code:"custom",message:"Artifact-backed drafts may not duplicate canonical rows inline.",path:["tasks"]}),e.status==="published"&&!e.publishedTasksetRef&&t.addIssue({code:"custom",message:"Published drafts require an immutable Taskset reference.",path:["publishedTasksetRef"]})}),JB=6e6,ZB=new Set(["taskset.json","capabilities.json","data/tasks.jsonl","tasks/tasks.jsonl","graders/graders.json","fixtures/grader-fixtures.json","metrics/policy.json","assets/manifest.json","environment/contract.json","environment/taskset.ts","rubrics/preference-review.md","comparisons/policy.json"]);function YB(e){const t=_c.parse(e);return!ZB.has(t)&&!t.startsWith("source-artifacts/")}function m0(e,t){const n=YB(e);if(t.byteLength>JB)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const o=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(o)?p0(t):{encoding:"utf8",data:o}}catch{a=p0(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:oI(t)}}function p0(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return{encoding:"base64",data:btoa(t)}}var f0=64*1024*1024,c_=i().regex(/^[a-f0-9]{64}$/),QB=c({path:_c,contentHash:c_,sizeBytes:u().int().nonnegative().max(f0),base64:i().max(f0)}).strict(),XB=c({schemaVersion:S("openpond.tasksetDraftWorkspace.v1"),draft:Xa,files:p(QB).max(1e4)}).strict(),YX=XB.extend({contentHash:c_}).strict();function QX(e){const t=[];e.name.trim()||t.push({code:"name_missing",message:"Name is required.",path:"name"}),e.objective.trim()||t.push({code:"objective_missing",message:"Objective is required.",path:"objective"}),!e.datasetArtifact&&e.tasks.length===0&&t.push({code:"tasks_missing",message:"Add at least one task or Dataset artifact.",path:"tasks"}),e.graders.length===0&&t.push({code:"graders_missing",message:"Add at least one grader.",path:"graders"}),e.graderFixtures.length===0&&t.push({code:"grader_fixtures_missing",message:"Add grader fixtures before publishing.",path:"graderFixtures"});const n=new Set(e.sourceRefs.map(a=>a.id));for(const a of e.tasks)for(const o of a.sourceRefs)n.has(o)||t.push({code:"task_source_missing",message:`Task ${a.id} references missing source ${o}.`,path:`tasks.${a.id}.sourceRefs`});return t}var hs=i().trim().min(1).max(240),e4=Rt.extend({revision:u().int().positive()}).strict(),t4=e4.extend({teamId:hs,jobId:hs,plan:Rt,baseline:Rt,candidate:Rt,state:IU.shape.state,updatedAt:i().datetime()}).strict();c({schemaVersion:S("openpond.trainingAcceptanceGroupPage.v1"),teamId:hs,jobId:hs,groups:p(t4).max(100),nextCursor:hs.nullable()}).strict();c({cursor:hs.optional(),limit:u().int().min(1).max(100).default(25)}).strict();var Ta=i().trim().min(1).max(191),tc=i().regex(/^[a-f0-9]{64}$/),n4=c({schemaVersion:S("openpond.trainingPreparationRequest.v1"),teamId:Ta,operationId:Ta,projectId:Ta.nullable(),configuration:c({id:Ta,expectedRevision:u().int().positive(),expectedEtag:tc}).strict(),batch:Wn,name:i().trim().min(1).max(191),maximumSpendUsd:u().finite().positive().max(1e6)}).strict(),a4=c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),id:Ta,creatorUserId:Ta,request:n4,requestHash:tc,source:Sk(()=>u_),submissionHash:tc,createdAt:i().datetime({offset:!0})}).strict(),o4=a4.extend({contentHash:tc}).strict(),i4=c({schemaVersion:S("openpond.trainingPreparationReceipt.v1"),plan:o4,revision:u().int().positive(),state:b(["prepared","submitted","cancelled"]),jobId:Ta.nullable()}).strict().superRefine((e,t)=>{e.state==="submitted"!=!!e.jobId&&t.addIssue({code:"custom",path:["jobId"],message:"Only submitted preparations identify a job."})});c({teamId:Ta,planHash:tc,expectedRevision:u().int().positive()}).strict();c({projectId:Ta.optional(),state:b(["prepared","submitted","cancelled"]).optional(),afterId:Ta.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({schemaVersion:S("openpond.trainingPreparationPage.v1"),teamId:Ta,items:p(i4).max(100),nextCursor:Ta.nullable()}).strict();c({schemaVersion:S("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:Ze,sourcePackageHash:i().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().positive().max(TU)}).strict();p(c({id:i().trim().min(1)}).catchall(se())).min(1).max(1e3);c({binding:Vu,rewards:p(Fu).min(1).max(100)}).strict();var r4=c({id:i().trim().min(1),clusterKey:i().trim().min(1),split:b(["train","validation","frozen_eval"])}).passthrough();c({schemaVersion:S("openpond.trainingEvaluationSource.v1"),taskset:Wn,tasks:p(r4).min(1).max(1e4),assets:p(c({path:i().trim().min(1).max(2e3),sha256:i().regex(/^[a-f0-9]{64}$/),sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:i().max(32*1024*1024)}).strict()).max(1e4)}).strict().superRefine((e,t)=>{const n=new Set;e.tasks.forEach((a,o)=>{a.split==="train"&&t.addIssue({code:"custom",path:["tasks",o,"split"],message:"Evaluation sources require held-out tasks."}),n.has(a.id)&&t.addIssue({code:"custom",path:["tasks",o,"id"],message:"Evaluation task identities must be unique."}),n.add(a.id)})});var jn=i().trim().min(1).max(500),pa=i().regex(/^[a-f0-9]{64}$/),Qa=i().datetime({offset:!0});c({schemaVersion:S("openpond.trainingInputArtifactUpload.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:i().trim().min(1).max(500),sourceManifest:Rt,payload:se(),contentHash:pa}).strict();c({schemaVersion:S("openpond.trainingInputArtifact.v2"),kind:b(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Rt,artifactRef:i().trim().min(1).max(2e3),contentHash:pa,sizeBytes:u().int().positive(),createdAt:Qa}).strict();var d_=b(["reward_model_train","policy_optimize"]),s4=b(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),l4=c({id:jn,version:i().trim().min(1).max(200).nullable().default(null),required:A().default(!0)}).strict(),u_=c({modelProject:c({id:jn,portableProjectId:jn,revision:u().int().positive(),contentHash:pa}).strict(),harnessRunManifest:Rt,harnessRelease:Rt,taskset:Wn,tasksetRelease:Rt,evaluation:c({taskset:Wn,dataset:Rt}).strict().nullable().optional(),dataset:Rt,evidenceSets:p(Rt).max(1e4)}).strict(),c4=c({kind:S("reward_model_train"),baseModel:gr,preferenceDatasetRelease:Rt,processorRelease:Rt,recipe:c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head")}).catchall(se())}).strict(),d4=c({kind:S("deterministic"),grader:Rt,composer:Rt.nullable().default(null)}).strict(),u4=c({kind:S("learned_reward"),rewardModelVersion:Rt,qualificationReport:Rt.nullable().default(null),evaluationReferences:p(Rt).max(1e3).default([]),scorerArtifact:c({artifactRef:i().trim().min(1).max(2e3),contentHash:pa,executionReceipt:Rt}).strict(),processorRelease:Rt,rewardComposerRelease:Rt}).strict(),m4=c({kind:S("policy_optimize"),baseModel:gr,recipe:Zw,rewardSource:vt("kind",[d4,u4]),resumeFrom:Rt.nullable().default(null)}).strict(),p4=vt("kind",[c4,m4]),f4=c({approvalHash:pa,approvedAt:Qa,exportApproved:A(),maximumSpendUsd:u().nonnegative(),retentionDays:u().int().nonnegative().nullable(),region:i().trim().min(1).max(200).nullable().default(null)}).strict();c({schemaVersion:S("openpond.trainingJobSubmission.v2"),idempotencyKey:i().trim().min(1).max(500),name:i().trim().min(1).max(200),source:u_,job:p4,requestedCapabilities:p(l4).max(1e3),placementObjective:b(["fast","balanced","economical"]),budget:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive()}).strict(),approval:f4,contentHash:pa}).strict().superRefine((e,t)=>{e.approval.maximumSpendUsd!==e.budget.maximumSpendUsd&&t.addIssue({code:"custom",path:["approval","maximumSpendUsd"],message:"Approved spend must equal the immutable Job budget."})});var h4=c({schemaVersion:S("openpond.trainingJob.v2"),id:jn,teamId:jn,kind:d_,modelProjectId:jn,portableProjectId:jn,sourceProjectRevision:u().int().positive(),submissionHash:pa,state:s4,phase:i().trim().min(1).max(200),version:u().int().nonnegative(),progress:u().min(0).max(1),rolloutProgress:c({groupsCompleted:u().int().nonnegative(),groupsTarget:u().int().nonnegative(),optimizerUpdatesApplied:u().int().nonnegative(),optimizerUpdatesSkipped:u().int().nonnegative()}).strict(),accruedSpendUsd:u().nonnegative(),terminalReason:i().trim().min(1).max(5e3).nullable(),createdAt:Qa,updatedAt:Qa,completedAt:Qa.nullable()}).strict();c({schemaVersion:S("openpond.trainingJobPage.v2"),jobs:p(h4).max(1e3),nextCursor:i().trim().min(1).max(2e3).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobEvent.v2"),id:jn,jobId:jn,sequence:u().int().nonnegative(),type:jn,phase:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3).nullable(),data:oe(i(),se()).default({}),createdAt:Qa}).strict();c({schemaVersion:S("openpond.trainingJobLog.v2"),jobId:jn,sequence:u().int().nonnegative(),level:b(["debug","info","warning","error"]),message:i().max(2e4),createdAt:Qa}).strict();c({expectedVersion:u().int().nonnegative()}).strict();var g4=c({schemaVersion:S("openpond.trainingJobOutput.v2"),id:jn,jobId:jn,kind:b(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:i().trim().min(1).max(2e3),contentHash:pa,sizeBytes:u().int().nonnegative(),metadata:oe(i(),se()).default({}),createdAt:Qa}).strict(),v4=c({schemaVersion:S("openpond.trainingExecutionReceipt.v2"),id:jn,teamId:jn,jobId:jn,submissionHash:pa,manifestHash:pa,recipeHash:pa,capabilityHash:pa,runtimeRelease:Rt,inputs:p(Rt).max(1e4),outputs:p(Rt).max(1e4),spendUsd:u().nonnegative(),durationSeconds:u().nonnegative(),cleanupComplete:A(),issuer:jn,issuedAt:Qa,signature:i().trim().min(1).max(1e4).nullable()}).strict();c({schemaVersion:S("openpond.trainingJobOutputs.v2"),outputs:p(g4).max(1e4),receipt:v4.nullable()}).strict();c({schemaVersion:S("openpond.trainingApiError.v2"),code:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3),retryable:A().default(!1),requestId:i().trim().min(1).max(500).nullable().default(null),details:oe(i(),se()).default({})}).strict();c({schemaVersion:S("openpond.trainingCapabilities.v2"),capabilityHash:pa,jobKinds:p(d_),methods:p(i().trim().min(1).max(200)),placements:p(b(["local","remote","colocated","provider_native"])),controls:c({cancel:A(),stopAfterGroup:A(),resumeFromCheckpoint:A()}).strict(),limits:c({maximumSpendUsd:u().nonnegative(),maximumWallSeconds:u().int().positive(),maximumArtifactBytes:u().int().positive()}).strict(),checkedAt:Qa,expiresAt:Qa}).strict();var ko=Xa.shape.id,eo=u().int().positive(),lr=i().regex(/^[a-f0-9]{64}$/),vr={teamId:ko,modelId:ko};c({schemaVersion:S("openpond.tasksetDraftCreate.v1"),operationId:ko,modelId:ko,expectedModelRevision:eo,name:Xa.shape.name}).strict();c({schemaVersion:S("openpond.tasksetDraftSourceDescriptor.v1"),...vr,expectedModelRevision:eo,sourcePackageHash:lr}).strict();c({schemaVersion:S("openpond.tasksetDraftReadback.v1"),...vr,draft:Xa,workspaceHash:lr,projectEtag:lr}).strict().refine(e=>e.draft.profileId===e.teamId&&e.draft.modelScope?.modelId===e.modelId,"The hosted draft must belong to its declared workspace and Model.");var b4=c({id:ko,revision:eo,name:Xa.shape.name,status:l_,updatedAt:Xa.shape.updatedAt,sourceTasksetRef:kt.nullable()}).strict();c({schemaVersion:S("openpond.tasksetDraftList.v1"),...vr,drafts:p(b4).max(100),nextCursor:i().min(1).max(2e3).nullable()}).strict();c({expectedDraftRevision:eo,draft:Xa}).strict();c({expectedDraftRevision:eo,expectedModelRevision:eo}).strict();var y4=c({expectedDraftRevision:eo,expectedWorkspaceHash:lr}).strict();c({schemaVersion:S("openpond.tasksetDraftValidation.v1"),...vr,draftId:ko,draftRevision:eo,workspaceHash:lr,valid:A(),issues:p(c({code:i().min(1),severity:b(["warning","error"]),message:i(),path:i().nullable()}).strict()),packageHash:lr.nullable(),tasksetRef:kt.nullable()}).strict().refine(e=>e.valid?e.packageHash!==null&&e.tasksetRef!==null&&e.issues.every(t=>t.severity!=="error"):e.packageHash===null&&e.tasksetRef===null&&e.issues.some(t=>t.severity==="error"),"Validation must retain either a compiled package or publication errors.");y4.extend({operationId:ko,expectedPackageHash:lr,expectedTasksetRef:kt}).strict();c({schemaVersion:S("openpond.tasksetDraftFileList.v1"),...vr,draftId:ko,draftRevision:eo,files:p(Ww).max(10020)}).strict();c({schemaVersion:S("openpond.tasksetDraftFileReadback.v1"),...vr,draftId:ko,draftRevision:eo,file:PU}).strict();c({schemaVersion:S("openpond.tasksetDraftDeletion.v1"),...vr,draftId:ko,revision:eo,deleted:S(!0)}).strict();Xa.shape.id;u().int().positive();var Vo=i().trim().min(1).max(500),S4=c({projectId:Vo.optional(),tasksetId:Vo.optional(),draftId:Vo.optional(),taskId:Vo.optional(),query:i().trim().max(1e3).default(""),split:b(["train","validation","test","frozen_eval"]).optional(),after:i().min(1).max(2e3).optional(),limit:u().int().min(1).max(100).default(30)}).strict(),x4=c({id:Vo,method:b(["code","judge","human"]),required:A()}),m_=c({tasksetId:Vo,tasksetName:i(),tasksetRevision:u().int().positive(),tasksetHash:i(),taskId:Vo,ordinal:u().int().nonnegative(),title:i(),description:i(),split:i(),scoring:p(x4),configuration:b(["configured","needs_reward","needs_checks"]),draftId:Vo.nullable().default(null),modelId:Vo.nullable().default(null)}),k4=c({items:p(m_).max(100),nextCursor:i().nullable()});function XX(e,t){if(fU({format:e.format,files:t}).contentHash!==e.contentHash)throw new Error("The source files differ from the import preview.");const n=`private/intake/${e.contentHash}`,a=t.map((r,s)=>({file:r,path:`${n}/${String(s).padStart(4,"0")}.txt`})),o={schemaVersion:"openpond.taskIntakeSources.v1",format:e.format,previewHash:e.contentHash,files:a.map(({file:r,path:s})=>({originalPath:r.path,retainedPath:s}))};return[...a.map(({file:r,path:s})=>m0(s,new TextEncoder().encode(r.text))),m0(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(o)))]}function eee(e,t,n){const a=zw.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const o=[...e.tasks];for(const s of n){const l=a.records.find(h=>h.id===s);if(!l||l.kind!=="task"||l.needsContext)throw new Error("Recorded attempts and incomplete histories must be imported into Labeling for review.");const m=s_.parse({schemaVersion:"openpond.taskData.v1",id:l.id,clusterKey:l.familyKey,split:l.split,input:l.input,expectedOutput:l.expected,privilegedContextRef:null,metadata:{intake:{format:a.format,uploadHash:a.contentHash,sourceId:l.sourceId,sourceHash:l.sourceHash,metadata:l.metadata}}}),d=o.find(h=>h.id===m.id);if(d&&fa(d)!==fa(m))throw new Error(`Task ${m.id} already exists with different content. Import will not replace saved edits.`);d||o.push(m)}const r=new Map;for(const s of o)for(const l of[`family:${s.clusterKey}`,`input:${fa(s.input)}`]){if(r.has(l)&&r.get(l)!==s.split)throw new Error("The imported task family or request already occurs in another split.");r.set(l,s.split)}return Xa.parse({...e,tasks:o})}const aa=i().trim().min(1).max(240),Ci=i().trim().min(1),p_=oe(i(),se()).default({}),f_=b(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),h_=b(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),w4=c({id:aa,kind:b(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:p(aa).min(1).max(1e4),occurredAt:Ci,signature:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(5e3),confidence:u().min(0).max(1),consented:A(),metadata:p_}),I4=c({frequency:u().min(0).max(1),businessValue:u().min(0).max(1),frontierCost:u().min(0).max(1),signalQuality:u().min(0).max(1),verifiability:u().min(0).max(1),repeatability:u().min(0).max(1),privacyRisk:u().min(0).max(1),overall:u().min(0).max(1)}),_4=c({tactic:h_,eligible:A(),reasons:p(i().trim().min(1).max(5e3)).min(1).max(100),blockers:p(i().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:p(i().trim().min(1).max(500)).max(100).default([]),generatedBy:b(["decision_table","baseline_reassessment"])}),g_=c({schemaVersion:S("openpond.taskCandidate.v1"),id:aa,profileId:aa,status:f_,fingerprint:i().trim().min(1).max(512),title:i().trim().min(1).max(500),summary:i().trim().min(1).max(1e4),workflowSignature:i().trim().min(1).max(2e3),evidence:p(w4).min(1).max(1e5),scorecard:I4,recommendation:_4,mergedIntoId:aa.nullable(),createdAt:Ci,updatedAt:Ci,metadata:p_}),om=c({schemaVersion:S("openpond.taskMinerConfig.v1"),enabled:A().default(!1),localOnly:A().default(!0),observationWindowDays:u().int().min(1).max(365).default(30),minimumRecurrence:u().int().min(2).max(100).default(3),clustering:S("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:A().default(!0)});c({items:p(g_),generatedAt:Ci,config:om});c({status:f_.optional(),mergeIntoId:aa.nullable().optional()});c({profileId:aa,sourceIds:p(aa).max(1e5).default([]),sessionIds:p(aa).max(1e5).default([]),config:om.optional()});const C4=c({schemaVersion:S("openpond.taskMinerRun.v1"),id:aa,profileId:aa,status:b(["queued","running","cancelling","cancelled","succeeded","failed"]),config:om,sourceIds:p(aa).max(1e5),sessionIds:p(aa).max(1e5).default([]),progress:c({stage:b(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:u().int().nonnegative(),totalSources:u().int().nonnegative(),candidatesFound:u().int().nonnegative(),skippedSources:u().int().nonnegative().default(0)}),candidateIds:p(aa).max(1e5),cancelRequested:A(),error:i().trim().min(1).max(2e4).nullable(),createdAt:Ci,startedAt:Ci.nullable(),completedAt:Ci.nullable(),updatedAt:Ci});var R4=c({id:Fe,purpose:i().trim().min(1).max(500),audience:b(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:A(),ttlSeconds:u().int().positive().max(86400),scopes:p(i().trim().min(1).max(500)).max(100).default([])}).strict(),P4=c({declarationId:Fe,leaseRef:i().trim().min(8).max(1e3),audience:R4.shape.audience,expiresAt:It}).strict(),Iv=c({adapterId:Fe,placement:b(["local","remote","colocated","provider_native"]),capabilityReceipt:Qe,runtimeVersion:i().trim().min(1).max(200),dataPlane:c({provider:Fe,dataPlaneId:Fe,cellId:Fe,runnerPoolId:Fe,runtimeImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Qe}).strict().nullable()}).strict(),_v=c({adapterId:Fe,kind:b(["local","ssh","managed","custom"]),deviceOrPool:i().trim().min(1).max(1e3),capabilityReceipt:Qe,provider:Fe.nullable()}).strict(),Cv=c({adapterId:Fe,workerVersion:i().trim().min(1).max(200),workerImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:i().trim().min(1).max(500),capabilityReceipt:Qe}).strict(),A4=c({schemaVersion:S("openpond.harnessRunManifest.v1"),id:Fe,harnessRelease:Ze,datasetRelease:Ze,evidenceSets:p(Ze).max(1e4),model:c({source:i().trim().min(1).max(200),revision:i().trim().min(1).max(500),artifactHash:Qe.nullable(),tokenizerRevision:i().trim().min(1).max(500),chatTemplateHash:Qe}).strict(),recipe:c({method:i().trim().min(1).max(100),version:i().trim().min(1).max(200),configHash:Qe}).strict(),runtimeTarget:Iv,computeTarget:_v,engine:Cv,resolvedBundleHash:Qe,secretLeaseRefs:p(P4).max(1e3),approval:c({approvalHash:Qe,approvedAt:It,maximumSpendUsd:u().nonnegative().nullable()}).strict(),createdAt:It}).strict(),T4=A4.extend({contentHash:Qe}).strict(),E4=c({schemaVersion:S("openpond.resolvedTrainingBundle.v1"),projection:S("trainer"),harnessRelease:Ze,datasetRelease:Ze,evidenceSetRelease:Ze.nullable(),files:p(c({path:i().trim().min(1).max(2e3),sha256:Qe,sizeBytes:u().int().nonnegative()}).strict()).max(1e5)}).strict();E4.extend({contentHash:Qe}).strict();var v_=c({name:S("adamw").default("adamw"),weightDecay:u().nonnegative().max(1).default(0),beta1:u().positive().lt(1).default(.9),beta2:u().positive().lt(1).default(.999),epsilon:u().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const ft=i().trim().min(1).max(240),oa=i().trim().min(1),Rs=i().trim().min(8).max(256),Rv=oe(i(),se()).default({}),xo=ft.nullable(),M4=b(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),j4=b(["defaults","customize"]),O4=b(["automated","manual"]);c({schemaVersion:S("openpond.trainingSourceEstimate.v1"),sessionId:ft,messageCount:u().int().nonnegative(),estimatedTokens:u().int().nonnegative(),textBytes:u().int().nonnegative()});c({query:i().max(500).default(""),offset:u().int().nonnegative().default(0),limit:u().int().min(1).max(100).default(20),candidates:p(c({sessionId:ft,title:i().trim().min(1).max(500),updatedAt:oa})).max(500).default([])});const $4=c({sessionId:ft,title:i().trim().min(1).max(500),updatedAt:oa,snippet:i().max(2e3).nullable()});c({schemaVersion:S("openpond.trainingChatSearchResult.v1"),query:i(),offset:u().int().nonnegative(),limit:u().int().positive(),total:u().int().nonnegative(),hasMore:A(),indexedChats:u().int().nonnegative(),totalChats:u().int().nonnegative(),indexing:A(),entries:p($4)});const Pv=b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),N4=c({graderId:ft.nullable(),path:i().trim().min(1).max(1e3),language:b(["javascript","typescript","python","json","text"]),content:i().max(2e6),sha256:Rs,declaredSha256:Rs.nullable(),integrity:b(["verified","unverified","mismatch"])}),D4=c({protocolVersion:i().trim().min(1).max(200),module:i().trim().min(1).max(1e3),moduleSha256:Rs,command:p(i().max(2e3)).max(100),cwd:i().trim().min(1).max(4e3),maxTurns:u().int().positive().max(100)});c({schemaVersion:S("openpond.tasksetGraderDetails.v1"),taskset:Kt,sourceTasksetId:ft,graders:p(am).max(1e3),runtime:D4.nullable(),sources:p(N4).max(1e3),unavailableReason:i().max(2e3).nullable()});const L4=c({id:ft,taskIndex:u().int().nonnegative(),label:wv,output:oe(i(),se()),infrastructureError:i().trim().min(1).max(1e4).nullable(),expectedPassed:A(),expectedRewardEligible:A(),metadata:Rv}),H4=c({schemaVersion:S("openpond.taskAttempt.v1"),id:ft,tasksetId:ft,taskId:ft,split:Cs,attempt:u().int().nonnegative(),seed:u().int(),modelRef:un.nullable(),startedAt:oa,completedAt:oa,output:oe(i(),se()),runtimeEventRefs:p(ft).max(1e4).default([]),artifactRefs:p(ft).max(1e4).default([]),privilegedOutcomeRef:xo,infrastructureError:i().trim().min(1).max(1e4).nullable(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),userInterventions:u().int().nonnegative().default(0),metadata:Rv}),U4=c({schemaVersion:S("openpond.taskAttemptArtifact.v1"),id:ft,tasksetId:ft,taskId:ft,attemptId:ft,kind:b(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:i().trim().min(1).max(4e3),mediaType:i().trim().min(1).max(200).nullable().optional(),sha256:Rs,sizeBytes:u().int().nonnegative(),createdAt:oa,metadata:Rv}),q4=c({graderId:ft,graderVersion:i().trim().min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),hardGate:A(),rewardEligible:A(),feedback:i().trim().max(2e4).nullable(),evidenceRefs:p(ft).max(1e4).default([]),judge:un.nullable().optional().default(null),calibrationStatus:b(["not_applicable","pending","passed","failed"])}),z4=c({schemaVersion:S("openpond.gradeResult.v1"),id:ft,attemptId:ft,graderSetHash:Rs,score:u().min(0).max(1).nullable(),passed:A(),components:p(q4).min(1).max(1e3),failureClass:Pv.nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:A(),rewardComposition:Jl.optional(),createdAt:oa});b(["stable_hash_top_n","rft_easy_curriculum_v1"]);const B4=c({schemaVersion:S("openpond.graderAuditReport.v1"),id:ft,tasksetId:ft,tasksetHash:Rs,fixtureRefs:p(ft).min(1).max(1e5),gradeRefs:p(ft).min(1).max(1e5),passed:A(),hackingChecksPassed:A(),leakageChecksPassed:A(),infrastructureSafetyPassed:A(),failures:p(c({fixtureId:ft,label:wv,gradeId:ft,reason:i().trim().min(1).max(5e3)})).max(1e5),createdAt:oa}),F4=c({schemaVersion:S("openpond.capabilityDiagnosis.v1"),summary:i().trim().min(1).max(1e4),stableBehavior:p(i().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:p(i().trim().min(1).max(5e3)).max(100).default([]),requiredContext:p(i().trim().min(1).max(5e3)).max(100).default([]),requiredTools:p(ft).max(100).default([]),intervention:h_,trainingEligible:A(),rationale:p(i().trim().min(1).max(5e3)).min(1).max(100),confidence:u().min(0).max(1)}),V4=c({id:ft,sourceId:ft,sourceTurnId:xo,split:Cs,origin:b(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:i().trim().min(1).max(1e5),expectedOutputText:i().trim().min(1).max(2e5).nullable(),rationale:i().trim().min(1).max(5e3)}),K4=c({schemaVersion:S("openpond.taskDesignProposal.v1"),id:ft,name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),diagnosis:F4.default({schemaVersion:"openpond.capabilityDiagnosis.v1",summary:"Reproduce the selected approved behavior.",stableBehavior:[],changingKnowledge:[],requiredContext:[],requiredTools:[],intervention:"sft",trainingEligible:!0,rationale:["The selected examples were supplied as demonstrations."],confidence:.5}),taskKind:kv.shape.taskKind,sourceIds:p(ft).min(1).max(1e5),assumptions:p(i().trim().min(1).max(5e3)).max(1e3),successCriteria:p(i().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:p(am).max(1e3).default([]),graderFixtures:p(L4).max(1e5).default([]),generatedFiles:p(UB).max(1e3).default([]),proposedExamples:p(V4).max(1e5).default([]),proposedMethod:i_.shape.recommendedMethod,trainingPath:a_.nullable().default(null),policy:Sv,warnings:p(i().trim().min(1).max(5e3)).default([]),createdAt:oa}),W4=5;function tee(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,W4).join(" ")}const Ac=c({schemaVersion:S("openpond.baseModelPreference.v1"),modelId:ft,revision:i().trim().min(1).max(256).nullable(),tokenizerRevision:i().trim().min(1).max(256).nullable(),chatTemplateHash:i().trim().min(8).max(256).nullable(),modelAssetId:xo,source:b(["managed","local","builtin"])}),G4=c({schemaVersion:S("openpond.taskCreationRequest.v1"),id:ft,profileId:ft,surface:M4,mode:j4,entryMode:O4.default("manual"),resourceIntent:b(["workproduct","dataset"]).default("workproduct"),buildIntent:t_.default("demonstrations"),buildSpecification:n_.nullable().default(null),objective:i().trim().min(1).max(2e4).nullable(),methodHint:b(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:ft.nullable().default(null),preferredBaseModel:Ac.nullable().default(null),sourceIds:p(ft).max(1e5),candidateId:xo,analysisModel:un.nullable(),analysisReasoningEffort:Ou.nullable().default(null),createImproveRunId:xo.default(null),targetIntent:c({kind:b(["agent","skill","extension","model","configuration"]).nullable(),id:xo,displayName:i().trim().min(1).max(500).nullable(),operation:b(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:c({status:b(["not_required","pending","approved","declined"]),content:S("raw_excerpts"),sourceIds:p(ft).max(1e5),providerModel:un.nullable(),approvalId:xo,approvedAt:oa.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:oa}),b_=c({schemaVersion:S("openpond.taskCreationSnapshot.v1"),id:ft,request:G4,state:b(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:K4.nullable(),materializedTasksetId:xo,disclosureApprovalId:xo,materializationApprovalId:xo,blockingQuestions:p(c({id:ft,kind:b(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:i().trim().min(1).max(5e3),answer:i().trim().min(1).max(2e4).nullable()})).default([]),transcript:p(c({id:ft,role:b(["user","assistant","system","tool"]),text:i().max(1e5),createdAt:oa})).max(1e4).default([]),repairHistory:p(r_).max(1e3).default([]),blockedReason:i().trim().min(1).max(1e4).nullable(),createdAt:oa,updatedAt:oa});c({schemaVersion:S("openpond.taskCreationTranscript.v1"),creationId:ft,profileId:ft,messages:b_.shape.transcript,updatedAt:oa});const rs=i().trim().min(1).max(240),Od=i().trim().min(1),bh=i().trim().min(8).max(256),y_=oe(i(),se()).default({}),J4=b(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),S_=c({schemaVersion:S("openpond.huggingFaceDatasetLocator.v1"),repositoryId:i().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:i().url().max(2e3),requestedRevision:i().trim().min(1).max(256).nullable()}),Z4=c({path:i().trim().min(1).max(1e3),logicalType:i().trim().min(1).max(500),nullable:A(),sampleValues:p(se()).max(5)}),Y4=c({configuration:i().trim().min(1).max(500),split:i().trim().min(1).max(500),rowCount:u().int().nonnegative().nullable(),sizeBytes:u().int().nonnegative().nullable()}),Q4=c({schemaVersion:S("openpond.huggingFaceDatasetInspection.v1"),id:rs,locator:S_,resolvedRevision:i().trim().min(7).max(256),title:i().trim().min(1).max(500),description:i().max(2e4).nullable(),declaredLicense:i().trim().min(1).max(500).nullable(),gated:A(),private:A(),configurations:p(i().trim().min(1).max(500)).min(1).max(1e3),splits:p(Y4).min(1).max(1e4),columns:p(Z4).min(1).max(1e4),previewRows:p(oe(i(),se())).max(25),sourceFiles:p(c({path:i().trim().min(1).max(2e3),configuration:i().trim().min(1).max(500),split:i().trim().min(1).max(500),revision:i().trim().min(7).max(256),sizeBytes:u().int().nonnegative().nullable(),contentHash:bh.nullable()})).max(1e5),inspectedAt:Od,metadata:y_}),X4=b(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),eF=c({sourcePath:i().trim().min(1).max(1e3),target:X4,transform:b(["identity","string","json","messages","numeric","math_final_answer"]),policy:b(["visible","privileged","metadata"]),required:A()}),x_=c({schemaVersion:S("openpond.datasetImportMapping.v1"),sourceSchemaHash:bh,configuration:i().trim().min(1).max(500),upstreamSplits:p(i().trim().min(1).max(500)).min(1).max(1e3),preset:b(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:p(eF).min(1).max(1e4),nullPolicy:b(["reject","drop","preserve"]),invalidRowPolicy:b(["reject_import","drop_with_receipt"]),splitPolicy:c({seed:u().int(),assignments:oe(i(),Ei),validationPercent:u().min(0).max(100),frozenEvalPercent:u().min(0).max(100)}),importerVersion:i().trim().min(1).max(200),mappingHash:bh}),tF=c({phase:b(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:u().int().nonnegative(),totalBytes:u().int().nonnegative().nullable(),completedRows:u().int().nonnegative(),totalRows:u().int().nonnegative().nullable(),message:i().trim().min(1).max(2e3).nullable()}),nF=c({schemaVersion:S("openpond.datasetImportJob.v1"),id:rs,profileId:rs,sourceKind:b(["huggingface","uploaded_file"]),status:J4,locator:S_.nullable(),inspection:Q4.nullable(),mapping:x_.nullable(),progress:tF,targetStorageRoot:i().trim().min(1).max(4e3).nullable(),tasksetId:rs.nullable(),tasksetRevision:u().int().positive().nullable(),artifactId:rs.nullable(),error:i().trim().min(1).max(2e4).nullable(),cancellationRequested:A(),createdAt:Od,updatedAt:Od,completedAt:Od.nullable(),metadata:y_});c({profileId:rs,url:i().trim().min(1).max(2e3)});c({name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),mapping:x_,targetStorageRoot:i().trim().min(1).max(4e3).nullable(),licenseApproved:A().default(!1)});const Si=T.nullable(),Do=u().int().nonnegative(),aF=i().regex(/^[a-f0-9]{40}$/),oF=c({name:i().trim().min(1).max(160),startedAt:Ce,completedAt:Ce,durationMs:u().nonnegative(),clock:b(["monotonic","provider","wall"]),outcome:b(["succeeded","failed","cancelled"])}).strict(),iF=c({schemaVersion:S("openpond.correlatedTelemetryReceipt.v1"),stage:b(["training","evaluation","deployment","inference"]),correlation:c({modelRunId:Si,modelVersionId:Si,policyVersion:Do.nullable(),taskId:Si,rolloutGroupId:Si,providerResourceId:Si,deploymentId:Si,inferenceRequestId:Si}).strict(),spans:p(oF).max(1e4),usage:c({promptTokens:Do.nullable(),generatedTokens:Do.nullable(),gpuSeconds:u().nonnegative().nullable(),workerActiveSeconds:u().nonnegative().nullable(),optimizerSteps:Do.nullable(),rolloutGroups:Do.nullable(),successfulTrajectories:Do.nullable(),failedTrajectories:Do.nullable(),peakGpuMemoryBytes:Do.nullable(),peakGpuUtilizationPercent:u().min(0).max(100).nullable()}).strict(),resource:c({provider:T,resourceIds:p(T).max(1e3),gpuType:i().trim().min(1).max(300).nullable(),gpuCount:Do.nullable(),baseProfileId:Si,baseRepository:i().trim().min(1).max(512).nullable(),baseRevision:aF.nullable(),adapterContentHash:F.nullable()}).strict(),cost:c({currency:S("USD"),providerReportedUsd:u().nonnegative().nullable(),quotedHourlyUsd:u().nonnegative().nullable(),estimatedUsd:u().nonnegative().nullable(),methodologyVersion:i().trim().min(1).max(160),pricingInputs:oe(i().trim().min(1).max(160),u().finite()),unitEstimates:oe(i().trim().min(1).max(160),u().nonnegative())}).strict(),recordedAt:Ce,contentHash:F}).strict(),bn=i().trim().min(1).max(240),Qo=i().regex(/^[a-f0-9]{64}$/),Ii=i().datetime({offset:!0}),kn=c({id:bn,contentHash:Qo}).strict(),rF=kn.extend({revision:u().int().positive()}).strict(),k_=c({providerId:bn,modelId:i().trim().min(1).max(300)}).strict(),im=b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),sF=c({taskId:bn,taskContentHash:Qo,panelRole:im,passLabel:bn.nullable(),optimizerEligible:A(),criticalInvariantIds:p(bn).max(100).default([])}).strict().superRefine((e,t)=>{e.optimizerEligible!==(e.panelRole==="correction")&&t.addIssue({code:"custom",path:["optimizerEligible"],message:"Only correction cases may be optimizer eligible."})}),lF=c({schemaVersion:S("openpond.continualBenchIssuePacket.v1"),id:bn,revision:u().int().positive(),contentHash:Qo,familyId:bn,familyLabel:i().trim().min(1).max(500),severity:b(["low","medium","high","critical"]),cases:p(sF).min(2).max(1e4),duplicateEvidence:kn,leakageEvidence:kn,priorExposureEvidence:kn,observedAt:Ii,reviewedAt:Ii,queuedAt:Ii.nullable(),runAt:Ii.nullable(),createdBy:bn,createdAt:Ii}).strict().superRefine((e,t)=>{e.cases.some(n=>n.panelRole==="correction")||t.addIssue({code:"custom",path:["cases"],message:"An issue packet requires a correction case."}),e.cases.some(n=>n.panelRole==="sibling_verification")||t.addIssue({code:"custom",path:["cases"],message:"An issue packet requires a sibling-verification case."}),new Set(e.cases.map(n=>n.taskId)).size!==e.cases.length&&t.addIssue({code:"custom",path:["cases"],message:"Issue-packet task ids must be unique."})}),cF=c({id:bn,role:im,passLabel:bn.nullable(),taskset:rF,familyIds:p(bn).min(1).max(1e5),taskCount:u().int().positive().max(1e6),sealedAt:Ii}).strict().superRefine((e,t)=>{const n=e.role==="correction"||e.role==="sibling_verification"||e.role==="cumulative_known";n!==(e.passLabel!==null)&&t.addIssue({code:"custom",path:["passLabel"],message:n?"This panel role requires a pass label.":"This panel role is series-wide and cannot carry a pass label."})}),mf=vt("kind",[c({kind:S("base_model"),id:bn,revision:i().trim().min(1).max(500),contentHash:Qo}).strict(),c({kind:S("model_version"),id:bn,contentHash:Qo}).strict(),c({kind:S("external_reference"),id:bn,model:k_,providerRevision:i().trim().min(1).max(500),contentHash:Qo}).strict()]),dF=c({scheduleEntryId:bn,ordinal:u().int().nonnegative(),label:bn,role:b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:u().int().positive().max(1024),correctionPanelIds:p(bn).min(1).max(1e3),optimizerGroupsPerTask:u().int().positive().max(1e3),trajectoriesPerGroup:u().int().min(4).max(1e3)}).strict(),uF=c({revision:u().int().positive(),requireAllAttemptsTerminal:S(!0),criticalCorrectionPassRate:u().min(0).max(1),siblingPassRate:u().min(0).max(1),behavioralRetentionRate:u().min(0).max(1),maximumRetainedRegressionPoints:u().min(0).max(100),blockCriticalPriorRegression:A(),authorizedClaims:p(b(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),mF=c({schemaVersion:S("openpond.continualBenchmarkProtocol.v1"),id:bn,revision:u().int().positive(),contentHash:Qo,ownerId:bn,createdAt:Ii,sealedAt:Ii,creationReceipt:kn,predecessorSeries:c({id:bn,revision:u().int().positive(),contentHash:Qo}).strict().nullable(),scenarioPack:kn,issueFamilyLedger:kn,issuePacketRelease:kn,panels:p(cF).min(6).max(1e4),grader:kn,judge:c({release:kn,rubricRelease:kn,calibrationRelease:kn,model:k_}).strict().nullable(),policies:c({base:mf,master:mf.nullable(),externalReferences:p(mf).min(1).max(20)}).strict(),invariants:c({systemPromptHash:Qo,toolSchema:kn,application:kn,harness:kn,runtime:kn,workerImage:kn,autoRefiner:c({enabled:A(),release:kn.nullable()}).strict()}).strict(),schedule:p(dF).min(1).max(1e3),evaluation:c({seeds:p(u().int()).min(3).max(100),repetitions:u().int().min(3).max(20),powerRule:kn,pairedBootstrapSamples:u().int().min(1e3).max(1e6),confidenceLevel:S(.95)}).strict(),resources:c({maximumTrainingGpuSeconds:u().int().positive(),maximumEvaluationGpuSeconds:u().int().positive(),maximumProviderSpendUsd:u().positive(),maximumTotalSpendUsd:u().positive(),maximumConcurrentGroups:u().int().positive().max(1e3)}).strict(),currencyThresholds:uF}).strict().superRefine((e,t)=>{const n=e.panels.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const r of["development","retained","frozen_final","training_eligible"])e.panels.filter(s=>s.role===r).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${r} panel.`});[...e.schedule].sort((r,s)=>r.ordinal-s.ordinal).some((r,s)=>r.ordinal!==s)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const o=new Set(n);e.schedule.some(r=>r.correctionPanelIds.some(s=>!o.has(s)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),pF=b(["draft","active","completed","archived"]),fF=b(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),w_=b(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),hF=b(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),gF=b(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),vF=b(["live_client","evaluation_attempt","replay_evidence","manual"]),bF=c({id:T,ordinal:u().int().nonnegative(),label:i().trim().min(1).max(100),role:w_,parentRule:hF,taskSource:gF,trainableRank:u().int().positive().max(1024),minimumTasks:u().int().nonnegative().max(1e5),maximumTasks:u().int().positive().max(1e5)}).strict().superRefine((e,t)=>{e.minimumTasks>e.maximumTasks&&t.addIssue({code:"custom",path:["minimumTasks"],message:"The minimum task count cannot exceed the maximum task count."});const n={seed:{parentRules:["base_model"],taskSource:"seed_taskset"},daily_residual:{parentRules:["previous_release","accepted_daily_head"],taskSource:"nightly_selection"},rank_candidate:{parentRules:["seed_release"],taskSource:"eligible_task_pool"},weekly_rollup:{parentRules:["seed_release","accepted_seed"],taskSource:"daily_cohort_union"},full_refresh:{parentRules:["base_model"],taskSource:"eligible_task_pool"}},{parentRules:a,taskSource:o}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==o&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${o}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),yF=c({id:T,version:u().int().positive(),requireCheckpoint:A(),requireAppliedOptimizerUpdate:A(),minimumCurrentCohortMeanImprovement:u().finite(),maximumRetainedMeanRegression:u().finite().nonnegative(),blockCriticalInvariantRegression:A(),automaticDailyAdvancement:A()}).strict(),SF=c({schemaVersion:S("openpond.modelComparisonSeries.v1"),id:T,profileId:T,modelProjectId:T,name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),status:pF,revision:u().int().positive(),productionBinding:c({role:S("chat_manual"),roleTargetId:T}).strict(),baseModel:c({id:T,revision:i().trim().min(1).max(256)}).strict(),seedTaskset:Kt,eligibleTaskPool:Kt,evaluationTasksets:c({development:Kt,retained:Kt,frozenFinal:Kt}).strict(),grader:G,benchmarkProtocol:mF.nullable().default(null),automaticEvaluation:c({enabled:A()}).strict().default({enabled:!1}),residualProfile:c({profileId:T,serializedEnvelopeRank:u().int().positive().max(1024),maximumEnabledRank:u().int().positive().max(1024),topology:S("uniform_block_masked")}).strict(),schedule:p(bF).min(1).max(1e3),scheduleSealedAt:Ce.nullable(),advancementPolicy:yF,executionPolicy:c({startWhenReady:S(!1)}).strict(),acceptedSeedEntryId:T.nullable(),acceptedDailyHeadEntryId:T.nullable(),promotedBindingId:T.nullable(),createdBy:T,createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{[...e.schedule].sort((m,d)=>m.ordinal-d.ordinal).some((m,d)=>m.ordinal!==d)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(m=>m.id)).size!==e.schedule.length||new Set(e.schedule.map(m=>m.label)).size!==e.schedule.length)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ids and labels must be unique."}),e.residualProfile.maximumEnabledRank>e.residualProfile.serializedEnvelopeRank&&t.addIssue({code:"custom",path:["residualProfile"],message:"Maximum enabled rank cannot exceed the serialized envelope."});const a=Object.values(e.evaluationTasksets);new Set(a.map(m=>`${m.id}:${m.revision}:${m.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const o=e.schedule.find(m=>m.role==="seed");if(!o||e.schedule.filter(m=>m.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const r=e.schedule.filter(m=>m.role==="rank_candidate");r.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(r.map(m=>m.trainableRank)).size!==r.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[o.trainableRank+e.schedule.filter(m=>m.role==="daily_residual").reduce((m,d)=>m+d.trainableRank,0),...e.schedule.filter(m=>m.role==="weekly_rollup").map(m=>o.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="rank_candidate").map(m=>o.trainableRank+m.trainableRank),...e.schedule.filter(m=>m.role==="full_refresh").map(m=>m.trainableRank)].some(m=>m>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),I_=c({source:vF,taskIds:p(T).min(1).max(1e5),observedFrom:Ce,observedTo:Ce,reviewedAt:Ce,reviewedBy:T,sourceTaskset:Kt}).strict(),xF=I_.extend({derivedFamilyKeys:p(T).min(1).max(1e5),familyDerivation:c({algorithm:T,sourceTasksetHash:F}).strict(),selectionHash:F}).strict(),__=vt("kind",[c({kind:S("base_model"),id:T,revision:i().trim().min(1).max(256)}).strict(),c({kind:S("model_version"),id:T,contentHash:F}).strict()]),kF=c({id:T,branchOrdinal:u().int().nonnegative(),rank:u().int().positive().max(1024),offsetStart:u().int().nonnegative(),offsetEnd:u().int().positive(),optimizationRole:b(["frozen","trainable"]),artifactLineageId:T.nullable()}).strict().superRefine((e,t)=>{e.offsetEnd-e.offsetStart!==e.rank&&t.addIssue({code:"custom",path:["offsetEnd"],message:"Block offsets must span exactly the declared rank."})}),wF=c({disposition:b(["advance","hold","no_signal"]),policy:c({id:T,version:u().int().positive()}).strict(),reasonCodes:p(T).min(1).max(100),summary:i().trim().min(1).max(5e3),decidedBy:T,decidedAt:Ce}).strict(),IF=c({evaluationRunId:T,modelVersionId:T,taskset:Kt,grader:G,cohortRole:b(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:T.nullable().default(null),protocol:c({id:T,revision:u().int().positive(),contentHash:F}).strict().nullable().default(null)}).strict(),_F=c({attemptOrdinal:u().int().positive(),trainingPlanId:T.nullable(),modelRunId:T.nullable(),terminalStatus:b(["failed","cancelled"]),queuedAt:Ce.nullable(),startedAt:Ce.nullable(),completedAt:Ce}).strict(),Ps=c({seriesId:T,entryId:T,scheduleEntryId:T,ordinal:u().int().nonnegative(),releaseHash:F}).strict(),CF=c({schemaVersion:S("openpond.modelComparisonSeriesEntry.v1"),id:T,seriesId:T,profileId:T,modelProjectId:T,scheduleEntryId:T,releaseHash:F,ordinal:u().int().nonnegative(),label:i().trim().min(1).max(100),role:w_,branch:b(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:fF,parent:__,taskset:Kt,sourceTasksets:p(Kt).min(1).max(1e3),taskSelection:xF.nullable(),trainableRank:u().int().positive().max(1024),serializedEnvelopeRank:u().int().positive().max(1024),enabledCumulativeRank:u().int().positive().max(1024),trainableBlockId:T,residualBlocks:p(kF).min(1).max(1024),attemptOrdinal:u().int().positive().default(1),priorRunAttempts:p(_F).max(100).default([]),trainingPlanId:T.nullable(),modelRunId:T.nullable(),modelVersionId:T.nullable(),evaluations:p(IF).max(1e5),decision:wF.nullable(),promotionBindingId:T.nullable(),queuedAt:Ce.nullable(),startedAt:Ce.nullable(),completedAt:Ce.nullable(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,l)=>s.offsetStart-l.offsetStart);n.some((s,l)=>s.offsetStart!==(l===0?0:n[l-1].offsetEnd))&&t.addIssue({code:"custom",path:["residualBlocks"],message:"Residual block offsets must be contiguous from zero."});const a=n.at(-1)?.offsetEnd??0;(a!==e.enabledCumulativeRank||a>e.serializedEnvelopeRank)&&t.addIssue({code:"custom",path:["enabledCumulativeRank"],message:"Enabled rank must match the block inventory and fit the envelope."});const o=e.residualBlocks.filter(s=>s.optimizationRole==="trainable");(o.length!==1||o[0]?.id!==e.trainableBlockId||o[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const r=e.priorRunAttempts.map(s=>s.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||r.some((s,l)=>s!==l+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});c({seriesId:T,scheduleEntryId:T,taskSelection:I_.nullable(),expectedSeriesRevision:u().int().positive()}).strict();const RF=b(["base_reference","lora_adapter"]),C_=c({baseModel:c({source:S("huggingface"),repoId:T,revision:i().regex(/^[a-f0-9]{40}$/),configHash:F,tokenizerHash:F,licenseId:T,gated:A()}).strict(),processor:c({repository:T,revision:i().regex(/^[a-f0-9]{40}$/),configHash:F}).strict()}).strict().superRefine((e,t)=>{(e.baseModel.repoId!==e.processor.repository||e.baseModel.revision!==e.processor.revision)&&t.addIssue({code:"custom",path:["processor"],message:"Reward Model processor must match the pinned scorer base model."})}),PF=c({schemaVersion:S("openpond.modelVersion.v1"),id:T,modelId:T,profileId:T,version:u().int().nonnegative(),kind:RF,status:b(["available","failed"]),baseModel:Ac,taskset:Kt,comparisonSeriesEntry:Ps.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),releaseGraph:c({resolvedBundleHash:F,profileRelease:Kt,harnessRelease:G,agentRelease:G.nullable(),grader:c({id:T,contentHash:F}).strict()}).strict(),artifactLineageId:T.nullable(),adapterStatus:b(["not_trained","trained"]),createdAt:Ce,contentHash:F}).strict().superRefine((e,t)=>{e.kind==="base_reference"&&(e.version!==0||e.adapterStatus!=="not_trained"||e.artifactLineageId!==null)&&t.addIssue({code:"custom",message:"A base-reference Model Version must be version 0 without adapter lineage."}),e.kind==="lora_adapter"&&(e.version===0||e.adapterStatus!=="trained"||!e.artifactLineageId)&&t.addIssue({code:"custom",message:"A LoRA Model Version must be version 1+ with adapter lineage."})}),AF=c({schemaVersion:S("openpond.rewardModelVersion.v1"),id:T,modelId:T,profileId:T,version:u().int().positive(),role:S("reward"),status:b(["available","failed"]),scope:b(["synthetic_smoke","human_preference"]),baseModel:Ac,runtime:C_.nullable().default(null),taskset:Kt,preferenceDatasetRelease:G,releaseGraph:c({resolvedBundleHash:F,profileRelease:Kt,harnessRelease:G,grader:c({id:T,contentHash:F}).strict()}).strict(),artifacts:c({checkpoint:G.extend({objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:i().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:F}).strict()).min(4).max(128)}).strict(),adapter:G,scalarHead:G,bucketHead:G.nullable(),processorRelease:G}).strict(),qualificationReport:G.nullable(),createdAt:Ce,contentHash:F}).strict(),TF=c({schemaVersion:S("openpond.rewardModelRunReceipt.v1"),provider:T,providerRunId:T,resolvedBundleHash:F,finalCheckpoint:G.extend({objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:G,scalarHead:G,bucketHead:G.nullable(),processorRelease:G,optimizerEvidence:G,managedExecutionReceipt:G.nullable().default(null),parameterDeltaHash:F,cleanup:c({computeReleased:A(),providerTerminalObserved:A()}).strict(),contentHash:F}).strict(),EF=eO(e=>{if(!e||typeof e!="object"||Array.isArray(e))return e;const t=e;if(t.tasksetRelease!==void 0)return e;const n=t.taskset;if(!n||typeof n!="object"||Array.isArray(n))return e;const a=n;return typeof a.id!="string"||typeof a.contentHash!="string"?e:{...t,tasksetRelease:{id:a.id,contentHash:a.contentHash}}},c({schemaVersion:S("openpond.rewardModelRun.v1"),id:T,rewardModelId:T,rewardModelVersionId:T.nullable(),profileId:T,role:S("reward"),scope:b(["synthetic_smoke","human_preference"]),status:b(["prepared","running","succeeded","failed","cancelled"]),taskset:Kt,tasksetRelease:G,preferenceDatasetRelease:G,recipeRelease:G,destinationId:T,quote:c({maximumSpendUsd:u().positive(),hourlyCostUsd:u().nonnegative().nullable()}).strict(),managedRunId:T.nullable(),progress:c({completedSteps:u().int().nonnegative(),totalSteps:u().int().positive(),latestLoss:u().finite().nullable()}).strict(),receipt:TF.nullable(),qualificationReport:G.nullable(),accruedSpendUsd:u().nonnegative().nullable(),failureOwner:b(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:i().trim().min(1).max(5e3).nullable(),startedAt:Ce,completedAt:Ce.nullable(),updatedAt:Ce}).strict()).superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Reward Model Run requires a canonical receipt."}),e.status!=="succeeded"&&e.rewardModelVersionId!==null&&t.addIssue({code:"custom",message:"Only a successful Reward Model Run can publish a Reward Model Version."})}),MF=c({schemaVersion:S("openpond.modelRunReceipt.v1"),provider:T,providerRunId:T,assignmentHash:F,resultHash:F,transcriptHash:F,traceHash:F.nullable(),resolvedBundleHash:F,artifactPath:i().trim().min(1).max(2e3),cleanup:c({computeReleased:A(),tunnelClosed:A()}).strict(),telemetry:iF.nullable().default(null),contentHash:F}).strict(),xi=c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),costUsd:u().nonnegative().nullable()}).strict(),h0=i().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Av=c({phase:b(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:T,attemptId:T,sessionId:T.nullable(),turnId:T.nullable(),passed:A(),score:u().min(0).max(1).nullable(),failureClass:Pv.nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),latencyMs:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),startedAt:Ce}).strict(),g0=c({targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative()}).strict(),R_=c({target:S("all_tasks_lower"),targetTaskCount:u().int().nonnegative(),comparedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),lowerTaskCount:u().int().nonnegative(),higherTaskCount:u().int().nonnegative(),unchangedTaskCount:u().int().nonnegative(),baselineTokens:u().int().nonnegative(),refinedTokens:u().int().nonnegative(),tokenDelta:u().int(),tokenDeltaPercent:u().finite().nullable(),complete:A(),passed:A(),cohorts:c({adaptation:g0,heldOut:g0}).strict()}).strict(),Tv=c({baseline:xi,adaptation:xi,candidateAdaptation:xi,candidate:xi,refiner:xi,grader:xi}).strict(),jF=c({usage:Tv,observedSpendUsd:u().nonnegative(),attempts:p(Av).max(1e4)}).strict(),OF=c({id:T,contentHash:F,artifactPath:i().trim().min(1).max(2e3)}).strict(),$F=c({schemaVersion:S("openpond.modelEvaluationReceipt.v1"),benchmarkId:T,resultManifest:c({id:T,contentHash:F,artifactPath:i().trim().min(1).max(2e3)}).strict(),stages:c({baseline:G,adaptation:G,refiner:G,candidateAdaptation:G,candidate:G,comparison:G}).strict(),usage:Tv,quality:c({baselinePassRate:u().min(0).max(1),candidatePassRate:u().min(0).max(1),adaptationBaselinePassRate:u().min(0).max(1),adaptationCandidatePassRate:u().min(0).max(1),adaptationCandidatePassed:A(),heldOutCandidatePassed:A(),passed:A()}).strict(),foregroundTokenDelta:u().int(),foregroundTokenDeltaPercent:u().finite().nullable(),taskEfficiency:R_.optional(),efficiency:c({grossForegroundTokenSavings:u().int(),overheadTokens:u().int().nonnegative(),firstPassNetTokenSavings:u().int(),breakEvenReuseCount:u().int().nonnegative().nullable(),amortizedTokenSavings:u().int(),amortizedReuseCount:u().int().positive()}).strict(),budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:A()}).strict(),evidenceSnapshot:G,lineage:c({adaptationEvidenceHash:F,refinerInputHash:F,refinerOutcomeHash:F,validationHash:F,applyReceiptHash:F,candidateRelease:G,valid:A()}).strict(),invalidReasons:p(i().trim().min(1).max(2e3)).max(100),attempts:p(Av).max(1e4).default([]),terminalClassification:b(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:c({ref:i().trim().min(1).max(2e3),commit:h0,baseCommit:h0}).strict().nullable(),contentHash:F}).strict(),NF=c({schemaVersion:S("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:T,terminalClassification:S("inconclusive"),stopReason:b(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:i().trim().min(1).max(5e3),stoppedAfter:S("refiner"),baselineHarness:G,candidateHarness:G,refiner:c({id:T,contentHash:F,outcomeCount:u().int().nonnegative()}).strict(),usage:Tv,budget:c({maximumSpendUsd:u().nonnegative(),observedSpendUsd:u().nonnegative(),enforced:A()}).strict(),evidenceSnapshot:G,attempts:p(Av).max(1e4),contentHash:F}).strict(),v0=c({level:S(.95),lower:u().finite(),upper:u().finite()}).strict().superRefine((e,t)=>{e.lower>e.upper&&t.addIssue({code:"custom",message:"A confidence interval's lower bound cannot exceed its upper bound."})}),DF=c({schemaVersion:S("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:i().trim().min(1).max(300),modelVersionId:T.nullable(),model:un.nullable()}).strict(),taskset:Kt,grader:G,sampling:c({seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20)}).strict(),deterministic:c({attemptedTaskCount:u().int().nonnegative(),completedTaskCount:u().int().nonnegative(),passedTaskCount:u().int().nonnegative(),failedTaskCount:u().int().nonnegative(),meanScore:u().finite().nullable(),passRate:u().min(0).max(1).nullable(),passRateCi95:v0.nullable()}).strict(),judge:c({judgeModel:un,judgeRelease:G,rubricRelease:G,calibrationRelease:G,score:u().min(0).max(100),scoreCi95:v0,comparisonCount:u().int().positive(),wins:u().int().nonnegative(),ties:u().int().nonnegative(),losses:u().int().nonnegative(),referenceLabel:i().trim().min(1).max(300)}).strict().superRefine((e,t)=>{e.wins+e.ties+e.losses!==e.comparisonCount&&t.addIssue({code:"custom",message:"Judge win, tie, and loss counts must equal comparisonCount."})}).nullable(),attempts:p(c({attemptId:T.nullable().default(null),taskId:T,seed:u().int(),repetition:u().int().nonnegative(),status:b(["succeeded","failed"]),deterministicScore:u().finite().nullable(),passed:A().nullable(),judgeScore:u().min(0).max(100).nullable(),judgePreference:b(["win","tie","loss"]).nullable(),transcriptHash:F.nullable(),traceHash:F.nullable(),transcriptArtifact:c({artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:c({artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:u().int().nonnegative().nullable().default(null),failureClass:Pv.nullable()}).strict()).max(1e5),usage:c({policy:xi.nullable(),judge:xi.nullable(),observedSpendUsd:u().nonnegative().nullable(),evaluationGpuSeconds:u().nonnegative().nullable().default(null)}).strict(),managedServing:c({jobId:T,terminalState:b(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:u().int().nonnegative(),sourceAdapterSha256:F.nullable(),servedPolicyVersion:u().int().nonnegative().nullable(),servedAdapterSha256:F.nullable(),accruedSpendUsd:u().nonnegative(),cleanupAttestationHash:F,resourceCount:u().int().nonnegative(),activeResourceCount:S(0)}).strict().nullable().default(null),evidenceSnapshot:c({id:T,contentHash:F,artifactPath:i().trim().min(1).max(2e3)}).strict(),completedAt:Ce,contentHash:F}).strict().superRefine((e,t)=>{const n=e.deterministic;n.completedTaskCount>n.attemptedTaskCount&&t.addIssue({code:"custom",message:"Completed task count cannot exceed attempted task count."}),n.passedTaskCount+n.failedTaskCount!==n.completedTaskCount&&t.addIssue({code:"custom",message:"Passed and failed task counts must equal completed task count."}),n.completedTaskCount===0!=(n.meanScore===null)&&t.addIssue({code:"custom",message:"Deterministic mean score is available exactly when tasks completed."}),n.completedTaskCount===0!=(n.passRate===null)&&t.addIssue({code:"custom",message:"Deterministic pass rate is available exactly when tasks completed."})}),LF=c({benchmarkId:S("harness-refiner"),model:un,upstreamModel:c({providerId:T,modelId:i().trim().min(1).max(300),revision:i().trim().min(1).max(300),pricing:c({version:i().trim().min(1).max(300),source:i().trim().min(1).max(300),effectiveAt:Ce,inputUsdPerMillionTokens:u().nonnegative(),cachedInputUsdPerMillionTokens:u().nonnegative(),outputUsdPerMillionTokens:u().nonnegative()}).strict().optional()}).strict(),reasoningEffort:i().trim().min(1).max(100).nullable(),seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),attemptPlan:p(c({stage:b(["baseline","adaptation","candidate_adaptation","candidate"]),split:i().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(4)}).strict(),HF=c({benchmarkId:S("model-comparison"),target:c({kind:b(["base_model","model_version","external_reference"]),label:i().trim().min(1).max(300),modelVersionId:T.nullable(),model:un.nullable()}).strict(),grader:G,judge:c({model:un,release:G,rubricRelease:G,calibrationRelease:G,referenceLabel:i().trim().min(1).max(300)}).strict().nullable(),seeds:p(u().int()).min(1).max(100),repetitions:u().int().positive().max(20),maximumSpendUsd:u().nonnegative(),series:c({id:T,protocol:c({id:T,revision:u().int().positive(),contentHash:F}).strict()}).strict().nullable().default(null),panel:c({id:T,role:b(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:T.nullable()}).strict().nullable().default(null),comparisonPair:c({entryId:T,parent:__,candidateModelVersionId:T}).strict().nullable().default(null),attemptPlan:p(c({stage:S("comparison"),split:i().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:u().int().positive()}).strict()).length(1)}).strict(),UF=Tt([LF,HF]),qF=c({schemaVersion:S("openpond.modelRun.v1"),id:T,modelId:T,modelVersionId:T.nullable(),profileId:T,kind:b(["rollout_smoke","training","evaluation"]),status:b(["prepared","running","succeeded","failed","cancelled"]),method:b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:T.nullable(),taskset:Kt,comparisonSeriesEntry:Ps.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:G.nullable().optional(),quote:c({maximumSpendUsd:u().nonnegative(),hourlyCostUsd:u().nonnegative().nullable()}).strict().nullable(),evaluation:UF.nullable().default(null),evaluationProgress:c({stage:b(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:u().int().nonnegative(),totalAttempts:u().int().positive(),accounting:jF.nullable().default(null),evidenceSnapshot:OF.nullable().default(null)}).strict().nullable().default(null),reward:c({raw:u(),components:oe(i(),u())}).strict().nullable(),receipt:Tt([MF,$F,NF,DF]).nullable(),adapterArtifactLineageId:T.nullable(),failure:i().trim().min(1).max(5e3).nullable(),startedAt:Ce,completedAt:Ce.nullable(),updatedAt:Ce}).strict().superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Model Run requires a canonical receipt."}),e.kind==="evaluation"&&(e.method!==null||e.destinationId!==null||!e.evaluation||e.adapterArtifactLineageId!==null)&&t.addIssue({code:"custom",message:"An evaluation Model Run requires evaluation configuration and cannot claim training method, destination, or adapter lineage."}),e.kind==="evaluation"&&e.receipt&&e.receipt.schemaVersion!=="openpond.modelEvaluationReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelEvaluationStopReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelComparisonBenchmarkReceipt.v1"&&t.addIssue({code:"custom",message:"An evaluation Model Run requires an evaluation receipt."}),e.kind!=="evaluation"&&(e.method===null||e.destinationId===null||e.quote===null)&&t.addIssue({code:"custom",message:"A training or rollout Model Run requires method, destination, and quote."}),e.kind==="rollout_smoke"&&e.adapterArtifactLineageId!==null&&t.addIssue({code:"custom",message:"A rollout smoke cannot claim adapter artifacts."})});function nee(e){const t=new Map;for(const _ of e.attempts){const P=`${_.phase}\0${_.taskId}`,M=t.get(P);(!M||_.startedAt>M.startedAt||_.startedAt===M.startedAt&&_.attemptId>M.attemptId)&&t.set(P,_)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([_,P,M])=>{const C=new Map(n.filter($=>$.phase===M).map($=>[$.taskId,$]));return n.filter($=>$.phase===P).flatMap($=>{const O=C.get($.taskId);return O?[{cohort:_,taskId:$.taskId,baseline:$,refined:O,tokenDelta:O.totalTokens-$.totalTokens}]:[]})}),o=new Set(n.filter(_=>_.phase==="baseline"||_.phase==="adaptation").map(_=>_.taskId)).size,r=e.targetTaskCount??o;if(!Number.isInteger(r)||r<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const s={adaptation:new Set(n.filter(_=>_.phase==="adaptation").map(_=>_.taskId)).size,held_out:new Set(n.filter(_=>_.phase==="baseline").map(_=>_.taskId)).size},l=(_,P)=>({targetTaskCount:P,comparedTaskCount:_.length,passedTaskCount:_.filter(M=>M.tokenDelta<0).length,failedTaskCount:_.filter(M=>M.tokenDelta>=0).length,lowerTaskCount:_.filter(M=>M.tokenDelta<0).length,higherTaskCount:_.filter(M=>M.tokenDelta>0).length,unchangedTaskCount:_.filter(M=>M.tokenDelta===0).length}),m=l(a,r),d=a.reduce((_,P)=>_+P.baseline.totalTokens,0),h=a.reduce((_,P)=>_+P.refined.totalTokens,0),g=h-d,y=a.length===r;return{summary:R_.parse({target:"all_tasks_lower",...m,baselineTokens:d,refinedTokens:h,tokenDelta:g,tokenDeltaPercent:d>0?g/d*100:null,complete:y,passed:y&&m.passedTaskCount===r,cohorts:{adaptation:l(a.filter(_=>_.cohort==="adaptation"),s.adaptation),heldOut:l(a.filter(_=>_.cohort==="held_out"),s.held_out)}}),pairs:a}}const zF=b(["measuring","up_to_date","needs_attention"]),BF=b(["fixed","retained","regressed","unresolved","unavailable"]),b0=c({evaluationRunId:T,attemptKey:T,artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3),transcriptHash:F.nullable(),traceHash:F.nullable()}).strict(),yh=c({level:S(.95),lower:u().finite(),upper:u().finite()}).strict(),FF=c({panelId:T,panelRole:im,passLabel:T.nullable(),taskset:Kt,attempted:u().int().nonnegative(),available:u().int().nonnegative(),passed:u().int().nonnegative(),strictSuccess:u().min(0).max(1).nullable(),strictSuccessCi95:yh.nullable(),judgeScore:u().min(0).max(100).nullable(),judgeScoreCi95:yh.nullable()}).strict(),VF=c({schemaVersion:S("openpond.modelCurrencySnapshot.v1"),id:T,contentHash:F,seriesId:T,protocol:c({id:T,revision:u().int().positive(),contentHash:F}).strict(),entryId:T,passLabel:T,parent:vt("kind",[c({kind:S("base_model"),id:T,revision:i().trim().min(1).max(500)}).strict(),c({kind:S("model_version"),id:T,contentHash:F}).strict()]),candidate:c({kind:S("model_version"),id:T,contentHash:F}).strict(),sources:c({evaluationRunIds:p(T).max(1e5),attemptIds:p(T).max(1e6),tasksets:p(Kt).max(1e4),grader:G,judge:G.nullable(),calibration:G.nullable()}).strict(),matches:p(c({key:T,panelId:T,panelRole:im,taskId:T,issueFamilyId:T,seed:u().int(),repetition:u().int().nonnegative(),classification:BF,parentPassed:A().nullable(),candidatePassed:A().nullable(),parentAttempt:b0.nullable(),candidateAttempt:b0.nullable()}).strict()).max(1e6),taskIds:c({fixed:p(T).max(1e6),retained:p(T).max(1e6),regressed:p(T).max(1e6),unresolved:p(T).max(1e6),unavailable:p(T).max(1e6)}).strict(),panels:p(FF).max(1e4),metrics:c({knownIssueCoverage:u().min(0).max(1).nullable(),issueFamilyGeneralization:u().min(0).max(1).nullable(),behavioralRetention:u().min(0).max(1).nullable(),currentAcquisitionDelta:u().finite().nullable(),retainedDeltaPoints:u().finite().nullable(),frontierStrictDelta:u().finite().nullable(),pairedPValue:u().min(0).max(1).nullable(),wins:u().int().nonnegative(),ties:u().int().nonnegative(),losses:u().int().nonnegative()}).strict(),statistics:c({matchedAttemptCount:u().int().nonnegative(),strictDelta:u().finite().nullable(),strictDeltaCi95:yh.nullable(),exactPairedBinaryPValue:u().min(0).max(1).nullable(),pairedBootstrapSamples:u().int().positive()}).strict(),criteria:c({allRequiredAttemptsTerminal:A(),criticalCorrectionPassRate:u().min(0).max(1).nullable(),siblingPassRate:u().min(0).max(1).nullable(),behavioralRetentionRate:u().min(0).max(1).nullable(),retainedRegressionPoints:u().finite().nullable(),criticalPriorRegressionCount:u().int().nonnegative(),thresholdRelease:G}).strict(),efficiency:c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),totalTokens:u().int().nonnegative(),costUsd:u().nonnegative().nullable(),latencyMs:u().int().nonnegative(),tokensPerSuccess:u().nonnegative().nullable(),throughputPerHour:u().nonnegative().nullable(),gpuSeconds:u().nonnegative().nullable()}).strict(),invariants:c({systemPromptHash:F,toolSchema:G,application:G,harness:G,runtime:G,grader:G,autoRefinerEnabled:A()}).strict(),evidenceState:zF,evidenceReasons:p(T).max(100),projectedAt:Ce}).strict(),$d=vt("kind",[c({kind:S("base_model"),id:T,revision:i().trim().min(1).max(500),label:i().trim().min(1).max(300)}).strict(),c({kind:S("model_version"),id:T,label:i().trim().min(1).max(300)}).strict(),c({kind:S("captured_model"),id:T,label:i().trim().min(1).max(300)}).strict()]),Ol=Tt([c({source:S("evaluation_run").default("evaluation_run"),evaluationRunId:T,attemptId:T,modelLabel:i().trim().min(1).max(300).nullable().default(null),modelVersionId:T.nullable().default(null),reward:u().finite().nullable(),components:oe(i(),u().finite()).default({})}).strict(),c({source:S("imported_response"),modelLabel:i().trim().min(1).max(300),modelVersionId:T.nullable().default(null),response:se().refine(e=>e!==void 0,"An imported model response is required."),reward:u().finite().nullable().default(null),components:oe(i(),u().finite()).default({})}).strict()]),KF=Tt([c({taskId:T,target:$d,attempt:Ol}).strict(),c({taskId:T,target:b(["base","current"]).default("current"),attempt:Ol}).strict(),c({taskId:T,target:b(["base","current"]).default("current"),evaluationRunId:T,attemptId:T,reward:u().finite().nullable(),components:oe(i(),u().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);c({schemaVersion:S("openpond.continualLearningDailyBatchManifest.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:u().int().positive().max(1e4),sourceTaskset:Kt,taskIds:p(T).min(1).max(1e3),observedAttempts:p(KF).max(1e3).default([]),sourceFileName:i().trim().min(1).max(500).nullable().default(null),availableAt:Ce}).strict().superRefine((e,t)=>{new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"A daily batch cannot repeat a task."}),new Set(e.observedAttempts.map(a=>`${a.taskId}:${JF(a.target)}`)).size!==e.observedAttempts.length&&t.addIssue({code:"custom",path:["observedAttempts"],message:"An intake batch cannot repeat a task and Policy target pair."});const n=new Set(e.taskIds);e.observedAttempts.some(a=>!n.has(a.taskId))&&t.addIssue({code:"custom",path:["observedAttempts"],message:"Observed attempts must belong to tasks in the daily batch."})});const WF=c({schemaVersion:S("openpond.continualLearningDailyBatch.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:u().int().positive().max(1e4),label:i().trim().min(1).max(100),runMode:b(["automatic","manual"]).optional(),source:b(["json_upload","sealed_fixture"]),sourceFileName:i().trim().min(1).max(500).nullable(),sourceTaskset:Kt,tasks:p(c({taskId:T,taskContentHash:F,familyKey:T,disposition:b(["include","defer","exclude"]).nullable(),oracleReview:b(["pending","confirmed","needs_correction"]),note:i().trim().max(2e3),observedAttempt:Ol.nullable(),baselineAttempt:Ol.nullable().default(null),responses:p(c({target:$d,attempt:Ol}).strict()).max(100).default([]),stagedAt:Ce.nullable().default(null),queuedEntry:Ps.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:c({status:b(["awaiting","running","ready","failed"]),requestedTargets:p(b(["base","current"])).max(2).default(["base","current"]),requestedPolicies:p($d).max(100).default([]),runs:p(c({target:$d,runId:T}).strict()).max(100).default([]),baselineRunId:T.nullable(),currentRunId:T.nullable(),currentPolicy:vt("kind",[c({kind:S("base_model"),id:T}).strict(),c({kind:S("model_version"),id:T}).strict()]).nullable(),failure:i().trim().min(1).max(2e3).nullable()}).strict().default({status:"awaiting",requestedTargets:["base","current"],requestedPolicies:[],runs:[],baselineRunId:null,currentRunId:null,currentPolicy:null,failure:null}),status:b(["pending","reviewed","queued"]),queuedEntry:Ps.nullable(),reviewedBy:T.nullable(),reviewedAt:Ce.nullable(),availableAt:Ce,revision:u().int().positive(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{new Set(e.tasks.map(a=>a.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",path:["tasks"],message:"A daily batch cannot repeat a task."});for(const[a,o]of e.tasks.entries()){const r=o.responses.map(s=>P_(s.target));new Set(r).size!==r.length&&t.addIssue({code:"custom",path:["tasks",a,"responses"],message:"A task cannot repeat a model response target."})}const n=e.tasks.every(a=>a.disposition!==null&&a.oracleReview!=="pending"&&(a.oracleReview!=="needs_correction"||a.note.length>0));e.status!=="pending"&&!n&&t.addIssue({code:"custom",path:["tasks"],message:"Every task requires a decision and oracle review before the day completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued day carries an exact series-entry reference."}),e.status==="pending"&&(e.reviewedAt!==null||e.reviewedBy!==null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"A pending day cannot carry reviewer completion identity."}),e.status!=="pending"&&(e.reviewedAt===null||e.reviewedBy===null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"Reviewed identity is required after a day review completes."})}),GF=c({schemaVersion:S("openpond.continualBenchIssueReview.v1"),id:T,seriesId:T,scheduleEntryId:T,passLabel:T,packet:lF,splitManifest:c({id:T,contentHash:F}).strict(),decisions:p(c({taskId:T,disposition:b(["include","defer","exclude"]).nullable(),note:i().trim().max(2e3)}).strict()).min(2).max(1e4),status:b(["pending","reviewed","queued"]),queuedEntry:Ps.nullable(),reviewedBy:T.nullable(),reviewedAt:Ce.nullable(),revision:u().int().positive(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(r=>r.taskId)].sort(),a=[...e.decisions.map(r=>r.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const o=e.decisions.every(r=>r.disposition!==null&&r.note.length>0);e.status!=="pending"&&!o&&t.addIssue({code:"custom",path:["decisions"],message:"Every case requires a disposition and note before review completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued review carries an exact series-entry reference."})}).readonly();function P_(e){return`${e.kind}:${e.id}`}function JF(e){return typeof e=="string"?e:P_(e)}const Va=i().trim().min(1).max(240),_a=i().trim().min(8).max(256),A_=b(["grpo","dapo","gspo-token"]),nc=c({id:Va,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:_a}),ZF=c({maxRollouts:u().int().positive().max(1e6),maxEnvironmentExecutions:u().int().positive().max(1e6),maxInputTokens:u().int().positive(),maxOutputTokens:u().int().positive(),maxOptimizerSteps:u().int().positive().max(1e6),wallTimeMs:u().int().positive(),maximumCostUsd:u().nonnegative().nullable()}),YF=c({method:S("grpo"),groupSize:u().int().min(2).max(128),normalization:S("group_standardized"),advantageEpsilon:u().positive().max(.01).default(1e-8),loss:A_,clipRange:u().positive().max(1).default(.2),iterations:u().int().min(2).max(16).default(2),microbatchSize:u().int().positive().max(128).default(1),gradientAccumulationSteps:u().int().positive().max(128).default(1),adamw:v_}),T_=c({method:S("ppo"),valueModel:nc,gamma:u().min(0).max(1),gaeLambda:u().min(0).max(1),policyClip:u().positive().max(1),valueClip:u().positive().max(10),valueLossCoefficient:u().nonnegative().max(10),ppoEpochs:u().int().positive().max(100),minibatchSize:u().int().positive().max(1e5)}),QF=vt("method",[YF,T_]),E_=c({rewardModelVersion:c({id:Va,contentHash:_a}).strict(),qualificationReport:c({id:Va,contentHash:_a}).strict().nullable().default(null),evaluationReferences:p(c({id:Va,contentHash:_a}).strict()).max(1e3).default([]),checkpoint:c({id:Va,contentHash:_a,objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(c({path:i().trim().min(1).max(512),sizeBytes:u().int().positive(),sha256:_a}).strict()).min(4).max(128)}).strict(),runtime:C_,processorRelease:c({id:Va,contentHash:_a}).strict(),rewardComposerRelease:c({id:Va,contentHash:_a}).strict(),executionReceipt:c({id:Va,contentHash:_a}).strict()}).strict(),M_=c({schemaVersion:S("openpond.policyOptimization.v1"),policyModel:nc,referenceModel:nc,dataset:c({tasksetId:Va,tasksetHash:_a,split:S("train"),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:u().int(),maxExamples:u().int().positive().max(1e5)}),sampler:c({temperature:u().min(0).max(2),topP:u().min(0).max(1),maxOutputTokens:u().int().positive().max(32768),maxTurns:u().int().positive().max(1e3),concurrency:u().int().positive().max(1e3)}),environment:c({id:Va,version:i().trim().min(1).max(256),toolContractHash:_a}),reward:c({graderId:Va,graderHash:_a,learnedPreference:E_.nullable().default(null)}),kl:c({coefficient:u().nonnegative().nullable(),referenceConstraint:S("fixed_reference")}),budgets:ZF,checkpointEverySteps:u().int().positive(),seed:u().int(),evaluationSplit:S("frozen_eval"),optimizer:QF}),Ee=i().trim().min(1).max(240),At=i().trim().min(1),mt=i().trim().min(8).max(256),Tc=oe(i(),se()).default({}),j_=c({schemaVersion:S("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:b(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:b(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:i().max(2e4).nullable().default(null),contextWindowTokens:u().int().min(128).max(32768).default(1024),maxOutputTokens:u().int().min(1).max(512).default(64),temperature:u().min(0).max(2).default(0),repetitionPenalty:u().min(.5).max(2).default(1.1),noRepeatNgramSize:u().int().min(0).max(10).default(3),compaction:b(["off","when_needed"]).default("when_needed"),keepWarmSeconds:u().int().min(0).max(3600).default(300),updatedAt:At.nullable().default(null)}),XF=j_.parse({}),e5=c({schemaVersion:S("openpond.managedAdapterServingProjection.v1"),teamId:Ee.nullable().default(null),source:S("sandbox_managed_rl"),sourceRef:Ee,canonicalArtifactId:Ee.nullable(),canonicalArtifactState:b(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Ee.nullable(),canonicalDeploymentState:b(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:b(["pending","imported","ready","failed"]),customerBindingAllowed:A().default(!1),artifactContentHash:mt.nullable().default(null),baseProfileId:Ee.nullable().default(null),publishedAt:At.nullable(),lastSyncedAt:At,lastError:i().trim().min(1).max(5e3).nullable()});function aee(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function O_(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function oee(e){if(e.promotable&&e.frozenEvaluationArtifactId)return{kind:"source_frozen_evaluation",evaluationArtifactId:e.frozenEvaluationArtifactId,canonicalArtifactId:null,canonicalDeploymentId:null};const t=e.managedServing;return t?.source==="sandbox_managed_rl"&&O_(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function iee(e){const t=e.managedServing;return t?O_(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Ev="openpond.crossSystemOperations.v1",ree="1.0.0",$_="openpond.crossSystemTools.v1",t5=["search_crm","query_billing","search_support","run_python"],n5=b(["train","validation","frozen_eval"]),a5=b(["easy","medium","hard"]),o5=b(["renewal_risk_v2"]);b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);c({seed:u().int().nonnegative(),split:n5,difficulty:a5,scenarioProfile:o5.optional()});const pf={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},ff={type:"integer",minimum:1,maximum:50,default:25},N_=[{name:"search_crm",description:"Search synthetic CRM accounts and contacts. Results are scoped, projected, paginated, and budgeted.",parameters:{type:"object",additionalProperties:!1,required:["query","fields","cursor","limit"],properties:{query:{type:"string",minLength:1,maxLength:500},fields:{type:"array",minItems:1,maxItems:12,uniqueItems:!0,items:{type:"string",enum:["account_id","name","aliases","contact_ids","contract_value_usd_cents","renewal_date","tier","active_contract_id","contract_term_months"]}},cursor:pf,limit:ff}}},{name:"query_billing",description:"Query synthetic invoices and payments for explicit account IDs and a bounded date range.",parameters:{type:"object",additionalProperties:!1,required:["account_ids","date_range","status","cursor","limit"],properties:{account_ids:{type:"array",minItems:1,maxItems:50,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:100}},date_range:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",format:"date"},to:{type:"string",format:"date"}}},status:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{type:"string",enum:["open","overdue","paid","disputed","scheduled","void"]}},cursor:pf,limit:ff}}},{name:"search_support",description:"Search synthetic support cases for explicit account IDs, severity, and state filters.",parameters:{type:"object",additionalProperties:!1,required:["account_ids","severity","state","cursor","limit"],properties:{account_ids:{type:"array",minItems:1,maxItems:50,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:100}},severity:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{type:"string",enum:["P1","P2","P3","P4"]}},state:{type:"array",minItems:1,maxItems:5,uniqueItems:!0,items:{type:"string",enum:["new","investigating","waiting_customer","resolved","closed"]}},cursor:pf,limit:ff}}},{name:"run_python",description:"Run standard-library-only Python in the persistent synthetic attempt sandbox with strict limits and no network.",parameters:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",minLength:1,maxLength:1e4}}}}],Ec=h5({schemaVersion:$_,tools:N_}),i5=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${Ec}.`,"Treat every filter as exact. An overdue-only query_billing call returns invoice rows; payment rows are included only when paid is requested.","For cross-system joins, retrieve the bounded projected rows and use run_python for date filtering, set intersection, and arithmetic before answering.","Finish with ANSWER: JSON."].join(" "),r5=15;function s5(e="auto"){return[i5,"LOCAL TOOL PROTOCOL (strict):","Use only the registered functions below. Never invent, rename, or call any other tool.","For one tool call, output exactly one JSON object and no prose:",'{"type":"tool_call","name":"registered_name","arguments":{}}',"Tool results arrive as exactly one JSON object:",'{"type":"tool_result","name":"registered_name","ok":true,"result":{},"error":null}','After one tool result, either call one registered tool again or answer normally. A JSON final may use {"type":"final","content":"..."}.',`Tool choice: ${JSON.stringify(e)}. Maximum tool turns: ${r5}.`,`Registered tool signatures: ${N_.map(l5).join("; ")}`].join(`
|
|
178
|
-
`)}s5();function l5(e){const t=cu(e.parameters),n=cu(t.properties),a=D_(t.required),o=Object.fromEntries(a.map(r=>[r,Nd(n[r])]));return`${e.name}(${JSON.stringify(o)})`}function Nd(e){const t=cu(e),n=Sh(t.anyOf);if(n.length)return n.map(Nd).join("|");const a=Sh(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[Nd(t.items)];if(t.type==="object"){const o=cu(t.properties),r=D_(t.required);return Object.fromEntries(r.map(s=>[s,Nd(o[s])]))}return typeof t.type=="string"?t.type:"unknown"}function cu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Sh(e){return Array.isArray(e)?e:[]}function D_(e){return Sh(e).filter(t=>typeof t=="string")}const du=b(t5),c5=vt("kind",[c({kind:S("model"),turn:u().int().nonnegative(),content:i().max(1e5)}),c({kind:S("tool_call"),turn:u().int().nonnegative(),callId:i().trim().min(1).max(240),name:du,arguments:oe(i(),se())}),c({kind:S("tool_result"),turn:u().int().nonnegative(),callId:i().trim().min(1).max(240),name:du,ok:A(),result:se(),rows:u().int().nonnegative(),bytes:u().int().nonnegative(),durationMs:u().int().nonnegative(),error:i().trim().min(1).max(2e4).nullable()}),c({kind:S("final"),turn:u().int().nonnegative(),content:i().max(1e5)})]),d5=c({schemaVersion:S(Ev),id:i().trim().min(1).max(240),worldId:i().trim().min(1).max(240),taskId:i().trim().min(1).max(240),toolContractHash:S(Ec),modelRef:c({providerId:i().trim().min(1),modelId:i().trim().min(1)}).nullable(),status:b(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:p(c5).max(1e3),startedAt:i().trim().min(1),completedAt:i().trim().min(1),infrastructureError:i().trim().min(1).max(2e4).nullable(),metadata:oe(i(),se()).default({})}),u5=c({schemaVersion:S(Ev),trajectoryId:i().trim().min(1).max(240),outcome:b(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:u().min(0).max(1.15).nullable(),rewardEligible:A(),exactAnswer:A(),components:c({exactAnswer:u().min(0).max(1),efficiency:u().min(0).max(.1),conciseOutput:u().min(0).max(.05)}),metrics:c({toolCalls:u().int().nonnegative(),rowsRead:u().int().nonnegative(),bytesRead:u().int().nonnegative(),consecutiveRetrievalCalls:u().int().nonnegative(),wallTimeMs:u().int().nonnegative(),parseFailures:u().int().nonnegative(),budgetExhausted:A()}),parsedAnswer:se().nullable(),feedback:p(i().trim().min(1).max(5e3)).max(100)}),m5=c({id:i().trim().min(1).max(240),type:S("function"),function:c({name:du,arguments:i().max(2e4)})}),L_=c({role:b(["system","user","assistant","tool"]),content:i().max(2e5).nullable(),tool_call_id:i().trim().min(1).max(240).optional(),tool_calls:p(m5).max(4).optional()});c({schemaVersion:S(Ev),id:i().trim().min(1).max(240),taskId:i().trim().min(1).max(240),worldId:i().trim().min(1).max(240),trajectoryId:i().trim().min(1).max(240),toolContractHash:S(Ec),approval:c({status:S("approved"),approvedBy:i().trim().min(1).max(240),approvedAt:i().trim().min(1)}),messages:p(L_).min(3).max(1e3)});const p5=c({tasksetTaskId:i().trim().min(1).max(240),environmentTaskId:i().trim().min(1).max(240),family:b(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:i().trim().min(1).max(1e5),finalAnswer:i().trim().min(1).max(2e5),trajectoryId:i().trim().min(1).max(240),trajectoryHash:i().trim().min(8).max(256),toolNames:p(du).min(1).max(100),toolCallCount:u().int().positive(),messageCount:u().int().min(3),reward:u().min(0).max(1.15),messages:p(L_).min(3).max(1e3)}),f5=c({status:S("approved"),approvedBy:i().trim().min(1).max(240),approvedAt:i().trim().min(1),previewHash:i().trim().min(8).max(256),trajectoryCount:u().int().positive()});c({schemaVersion:S("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:i().trim().min(1).max(240),tasksetHash:i().trim().min(8).max(256),tasksetRevision:u().int().positive(),previewHash:i().trim().min(8).max(256),toolContractHash:S(Ec),status:b(["ready_for_review","approved"]),approval:f5.nullable(),tasks:p(p5).min(1).max(100)});function h5(e){const t=xh(e);let n=2166136261,a=2654435769;for(let o=0;o<t.length;o+=1){const r=t.charCodeAt(o);n=Math.imul(n^r,16777619),a=Math.imul(a^r,2246822507)}return`${$_}:${y0(n)}${y0(a)}`}function xh(e){return Array.isArray(e)?`[${e.map(xh).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${xh(n)}`).join(",")}}`:JSON.stringify(e)}function y0(e){return(e>>>0).toString(16).padStart(8,"0")}const g5=c({schemaVersion:S("openpond.singleTurnPolicyTrajectory.v1"),id:Ee,taskId:Ee,status:b(["completed","infrastructure_failure"]),promptHash:mt,responseText:i().max(2e6),infrastructureError:i().trim().min(1).max(1e4).nullable(),startedAt:At,completedAt:At,metadata:Tc}),v5=c({schemaVersion:S("openpond.ppoTrajectory.v1"),id:Ee,taskId:Ee,policyModelId:Ee,referenceModelId:Ee,valueModelId:Ee,steps:p(c({index:u().int().nonnegative(),observationHash:mt,actionTokenIds:p(u().int().nonnegative()).min(1),terminated:A(),truncated:A(),reward:u(),policyLogProbability:u(),referenceLogProbability:u(),valuePrediction:u(),return:u(),advantage:u(),mask:u().min(0).max(1)})).min(1).max(1e5),createdAt:At}),b5=c({schemaVersion:S("openpond.exactAnswerVerifierResult.v1"),outcome:b(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:mt,score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),expectedAnswerHash:mt,extractedAnswer:i().max(2e4).nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3)}),y5=c({schemaVersion:S("openpond.rolloutTrajectoryReceipt.v1"),id:Ee,jobId:Ee,planId:Ee,tasksetId:Ee,tasksetHash:mt,taskId:Ee,split:S("train"),correlationId:Ee,provider:Ee,providerTrace:c({invocationId:Ee,experimentId:Ee,rolloutId:Ee,runId:Ee,rowId:Ee}),optimizerMethod:b(["grpo","ppo"]).default("grpo"),evidenceLevels:c({requested:b(["trajectory","aggregate","provider_reported"]),observed:b(["trajectory","aggregate","provider_reported"]),providerReported:b(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:c({rollouts:u().int().nonnegative(),environmentExecutions:u().int().nonnegative(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),optimizerSteps:u().int().nonnegative(),costUsd:u().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:c({id:Ee,version:i().trim().min(1).max(256),worldId:Ee,worldHash:mt,toolContractHash:mt}),policy:c({modelId:Ee,checkpointId:Ee.nullable(),completionParametersHash:mt}),status:b(["received","running","succeeded","failed"]),failureClass:b(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:c({eligible:A(),raw:u().min(0).max(1.15).nullable(),normalized:u().min(0).max(1).nullable(),components:oe(i(),u())}),trajectory:Tt([d5,g5,v5]).nullable(),verifier:Tt([u5,b5]).nullable(),providerStatus:oe(i(),se()).default({}),receivedAt:At,startedAt:At.nullable(),completedAt:At.nullable(),updatedAt:At}),see="dataset-exact-answer",lee="dataset-exact-answer-v1",cee="no-tools-v1",Mi=b(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),rm=b(["lora","full"]),br=b(["openpond_managed"]),S5=c({schemaVersion:S("openpond.sftRecipe.v1"),method:S("sft"),parameterization:S("lora"),baseModel:c({id:Ee,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:mt}),dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),completionOnly:A(),maxSequenceLength:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:S("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:u().int().default(17)}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),optimizer:c({learningRate:u().positive(),epochs:u().positive().max(100),maxSteps:u().int().positive().max(1e6),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})});c({id:Ee,input:oe(i(),se()),expectedOutput:oe(i(),se()),tags:p(Ee).max(100).default([])});c({id:Ee,prompt:i().min(1).max(5e5),chosen:i().min(1).max(5e5),rejected:i().min(1).max(5e5),sourceRefs:p(Ee).min(1).max(1e4)});c({id:Ee,input:oe(i(),se()),tags:p(Ee).max(100).default([])});c({schemaVersion:S("openpond.rewardModelRecipe.v1"),method:S("reward_model"),parameterization:S("lora_with_scalar_head"),runScope:b(["synthetic_smoke","human_preference"]),baseModel:c({id:Ee,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),processorRevision:i().trim().min(1).max(256),chatTemplateHash:mt}).strict(),tasksetRelease:G,preferenceDatasetRelease:G,processorRelease:G,input:c({kind:S("structured_text"),serialization:b(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:u().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Ee).min(1).max(100)}).strict(),heads:c({scalar:S("pooled_hidden_state_linear"),bucket:b(["none","three_class"]).default("three_class")}).strict(),loss:c({ranking:S("bradley_terry"),rankingWeight:u().positive(),bucketWeight:u().nonnegative(),tieWeight:u().nonnegative()}).strict(),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int(),checkpointEverySteps:u().int().positive().max(1e5)}).strict(),resourceLimits:c({wallTimeMs:u().int().positive().max(1440*60*1e3),maxExamples:u().int().positive().max(1e5),maxInputCharacters:u().int().positive().max(5e5).default(32e3),maxImagePixels:u().int().positive().max(1e8).optional(),maximumSpendUsd:u().nonnegative().max(1e5)}).strict()}).superRefine((e,t)=>{e.runScope==="synthetic_smoke"&&(e.optimizer.maxSteps>100||e.resourceLimits.maximumSpendUsd>10)&&t.addIssue({code:"custom",path:["resourceLimits"],message:"Synthetic-smoke Reward Model runs are limited to 100 steps and USD 10."})});const x5=c({schemaVersion:S("openpond.rftRecipe.v1"),method:S("grpo"),parameterization:S("lora"),baseModel:c({id:Ee,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:mt}),dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),maxPromptTokens:u().int().positive().max(32768),maxExamples:u().int().positive().max(1e5).default(1e3),selectionStrategy:b(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:c({rank:u().int().positive().max(256)}),rollout:c({groupSize:u().int().min(2).max(64),concurrency:u().int().positive().max(32),maxTurns:u().int().positive().max(100),maxOutputTokens:u().int().positive().max(8192),temperature:u().min(0).max(2),topP:u().positive().max(1),seed:u().int()}),optimizer:c({learningRate:u().positive(),maxSteps:u().int().positive().max(1e5),clipRange:u().positive().max(1).default(.2),iterations:u().int().min(2).max(16).default(2),microbatchSize:u().int().positive().max(64).default(1),gradientAccumulationSteps:u().int().positive().max(64).default(1),advantageEpsilon:u().positive().max(.01).default(1e-8),adamw:v_}),loss:c({method:A_.default("grpo"),klBeta:u().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:c({graderId:Ee,graderHash:mt,environmentId:Ee,environmentVersion:i().trim().min(1).max(256),toolContractHash:mt,learnedPreference:E_.nullable().optional()}),resourceLimits:c({wallTimeMs:u().int().positive().max(1440*60*1e3),maxGpuSeconds:u().int().positive().max(10800).optional(),maxRollouts:u().int().positive().max(1e5),maxPayloadBytes:u().int().positive().max(10*1024*1024)}),policyOptimization:M_.nullable().default(null),continuation:c({schemaVersion:S("openpond.crossJobContinuationRequest.v1"),parentArtifact:G,sourceArtifact:c({jobId:Ee,artifactId:Ee,checkpointId:Ee,contentHash:mt}).strict(),optimizerMode:b(["continue","reset"])}).strict().optional()}),k5=c({schemaVersion:S("openpond.dpoRecipe.v1"),method:S("dpo"),parameterization:S("lora"),policyModel:nc,referenceModel:nc,dataset:c({trainSplit:S("train"),validationSplit:b(["validation","frozen_eval"]),maxPairs:u().int().positive().max(1e5),maxPromptTokens:u().int().positive().max(32768),maxCompletionTokens:u().int().positive().max(32768),selectionStrategy:S("stable_hash_top_n"),selectionSeed:u().int()}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),loss:c({variant:S("sigmoid"),beta:u().positive().max(10),labelSmoothing:u().min(0).max(.5).default(0)}),optimizer:c({learningRate:u().positive(),epochs:u().positive().max(100),maxSteps:u().int().positive().max(1e6),batchSize:u().int().positive().max(1e4),gradientAccumulationSteps:u().int().positive().max(1e4),seed:u().int()}),referenceLogprobs:c({cacheSchemaVersion:S("openpond.dpoReferenceLogprobs.v1"),cacheKey:mt,invalidationHash:mt}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),w5=c({schemaVersion:S("openpond.ppoRecipe.v1"),method:S("ppo"),parameterization:S("lora"),policyOptimization:M_.extend({optimizer:T_}),lora:c({rank:u().int().positive().max(256),alpha:u().positive().max(1024),dropout:u().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),valueHead:c({initialization:S("policy_hidden_state_linear"),optimizerLearningRate:u().positive(),artifactName:S("value_head.safetensors")}),policyLearningRate:u().positive(),resume:c({checkpointId:Ee.nullable(),policyHash:mt,referenceHash:mt,valueModelHash:mt,optimizerStateHash:mt.nullable()}),resourceLimits:c({cpuThreads:u().int().positive().max(256),memoryBytes:u().int().positive(),wallTimeMs:u().int().positive()})}),I5=c({schemaVersion:S("openpond.unsupportedRecipe.v1"),method:Mi.exclude(["sft","dpo","grpo","ppo"]),parameterization:rm,unsupportedReason:i().trim().min(1).max(5e3)}),H_=Tt([S5,k5,x5,w5,I5]),_5=c({schemaVersion:S("openpond.trainingDestinationCapabilities.v1"),destinationId:br,available:A(),methods:p(Mi),parameterizations:p(rm),modelAllowlist:p(Ee).default([]),maxDatasetBytes:u().int().nonnegative().nullable(),environmentPlacements:p(b(["none","local","remote","colocated","provider_native"])),nonProduction:A(),unavailableReason:i().trim().min(1).max(5e3).nullable(),checkedAt:At}),C5=c({destinationId:br,available:A(),methods:p(Mi),parameterizations:p(rm),nonProduction:A(),unavailableReason:i().trim().min(1).max(5e3).nullable()}),R5=c({schemaVersion:S("openpond.baseModelCandidate.v1"),selectionKey:Ee,label:i().trim().min(1).max(500),sourceLabel:i().trim().min(1).max(500),preference:Ac,available:A(),nonProduction:A(),unavailableReason:i().trim().min(1).max(5e3).nullable(),methods:p(Mi),executionOptions:p(C5).min(1)}),P5=c({code:Ee,severity:b(["warning","error"]),path:i().trim().max(2e3).nullable(),message:i().trim().min(1).max(5e3)}),A5=c({schemaVersion:S("openpond.trainingCompatibility.v1"),compatible:A(),destinationId:br,tasksetId:Ee,recipeMethod:Mi,issues:p(P5),checkedAt:At}),T5=Tt([o_,b(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);c({method:Mi,state:b(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:p(T5).default([]),reasons:p(i().trim().min(1).max(5e3)).default([]),destinationId:br.nullable().default(null)});b(["small","standard","custom","small_experiment"]);const E5=Qw,U_=c({schemaVersion:S("openpond.trainingPlan.v1"),id:Ee,modelId:Ee,tasksetId:Ee,tasksetHash:mt,comparisonSeriesEntry:Ps.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:G.nullable().optional(),modelImprovementQualification:G.nullable().optional(),destinationId:br,recipe:H_,environmentPlacement:b(["none","local","remote","colocated","provider_native"]),compatibility:A5,dataPolicy:c({exportApproved:A(),approvedSourceIds:p(Ee),retentionDays:u().int().nonnegative().nullable(),region:i().trim().min(1).max(200).nullable()}),estimatedCostUsd:u().nonnegative().nullable(),createdAt:At,contentHash:mt}),M5=c({path:i().trim().min(1).max(2e3),sha256:mt,sizeBytes:u().int().nonnegative(),role:b(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Mv=c({schemaVersion:S("openpond.trainingBundle.v1"),id:Ee,planId:Ee,tasksetId:Ee,tasksetHash:mt,recipeHash:mt,files:p(M5).min(1).max(1e6),totalSizeBytes:u().int().nonnegative(),sourceIds:p(Ee),excludedSourceIds:p(Ee),containsRawChats:S(!1),containsSecrets:S(!1),containsHiddenGraderAssets:S(!1),createdAt:At,contentHash:mt});c({schemaVersion:S("openpond.trainingBundleExport.v1"),manifest:Mv,files:p(c({path:i().trim().min(1).max(2e3),sha256:mt,sizeBytes:u().int().nonnegative(),encoding:S("base64"),content:i()})).min(1),contentHash:mt});c({schemaVersion:S("openpond.trainingPreparedStart.v1"),plan:U_,bundle:Mv,approvalActor:Ee.nullable(),preparedAt:At});c({schemaVersion:S("openpond.trainingApproval.v1"),evaluationTasksetRef:Kt.nullable().optional(),id:Ee,planId:Ee,bundleHash:mt,harnessRelease:G.nullable().optional(),modelImprovementQualification:G.nullable().optional(),destinationId:br,modelId:Ee,method:Mi,parameterization:rm,maximumCostUsd:u().nonnegative().nullable(),approvedBy:Ee,approvedAt:At});c({schemaVersion:S("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Kt.nullable().optional(),modelProjectId:Ee,sourceProjectRevision:u().int().positive(),profileId:Ee,taskset:c({id:Ee,revision:u().int().positive(),contentHash:mt}).strict(),tasksetRelease:G,harnessRelease:G,baseModel:Ac,method:Mi}).strict();const j5=b(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),q_=c({schemaVersion:S("openpond.trainingJob.v1"),id:Ee,planId:Ee,bundleHash:mt,approvalId:Ee,destinationId:br,status:j5,nonProduction:A(),workerPid:u().int().positive().nullable(),startedAt:At.nullable(),completedAt:At.nullable(),error:i().trim().min(1).max(2e4).nullable(),createdAt:At,updatedAt:At,metadata:Tc}),O5=c({schemaVersion:S("openpond.trainingJobEvent.v1"),id:Ee,jobId:Ee,sequence:u().int().nonnegative(),type:b(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:At,payload:Tc}),$5=c({schemaVersion:S("openpond.sftStepMetric.v1"),step:u().int().nonnegative(),maxSteps:u().int().positive(),timestamp:At,epoch:u().nonnegative().nullable(),loss:u().nullable(),learningRate:u().nonnegative().nullable(),gradientNorm:u().nonnegative().nullable(),entropy:u().nonnegative().nullable(),meanTokenAccuracy:u().min(0).max(1).nullable(),preferenceAccuracy:u().min(0).max(1).nullable().default(null),preferenceMargin:u().nullable().default(null),chosenReward:u().nullable().default(null),rejectedReward:u().nullable().default(null),chosenLogProbability:u().nullable().default(null),rejectedLogProbability:u().nullable().default(null),reward:u().nullable().default(null),policyLoss:u().nullable().default(null),advantageLoss:u().nullable().default(null),inputTokensSeen:u().int().nonnegative().nullable(),memoryBytes:u().int().nonnegative().nullable(),elapsedSeconds:u().nonnegative().nullable()}),N5=c({schemaVersion:S("openpond.policyOptimizationMetric.v1"),method:b(["grpo","ppo"]),step:u().int().nonnegative(),timestamp:At,learningRate:u().nonnegative().nullable().default(null),policyLoss:u().nullable(),valueLoss:u().nullable(),gradientNorm:u().nonnegative().nullable().default(null),meanReward:u().nullable(),meanReturn:u().nullable(),kl:u().nullable(),behaviorPolicyKlPreUpdate:u().nonnegative().nullable().default(null),entropy:u().nullable(),policyClipFraction:u().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:u().min(0).max(1).nullable().default(null),valueClipFraction:u().min(0).max(1).nullable(),explainedVariance:u().nullable(),rolloutLearnerLag:u().int().nonnegative().nullable(),inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),environmentExecutions:u().int().nonnegative(),trajectoryCount:u().int().nonnegative().nullable().default(null),costUsd:u().nonnegative().nullable()}),D5=c({schemaVersion:S("openpond.managedTrainingRunEvidence.v2"),provider:Ee,providerRunId:Ee,state:Ee,progress:c({targetOptimizerSteps:u().int().nonnegative(),committedOptimizerSteps:u().int().nonnegative(),skippedOptimizerSteps:u().int().nonnegative()}),reward:c({finalMean:u().nullable(),variance:u().nonnegative().nullable(),minimum:u().nullable(),maximum:u().nullable(),distinctValueCount:u().int().nonnegative(),noSignalGroupCount:u().int().nonnegative(),trajectoryCount:u().int().nonnegative(),eligibleTrajectoryCount:u().int().nonnegative()}),usage:c({inputTokens:u().int().nonnegative(),outputTokens:u().int().nonnegative(),environmentExecutions:u().int().nonnegative()}),resource:c({provider:Ee,gpuType:i().trim().min(1).max(300).nullable(),gpuCount:u().int().nonnegative().nullable(),hourlyCostUsd:u().nonnegative().nullable(),durationSeconds:u().nonnegative().nullable(),gpuSeconds:u().nonnegative().nullable()}),cost:c({totalUsd:u().nonnegative().nullable()}),checkpoint:c({id:Ee,policyVersion:u().int().nonnegative(),sha256:mt.nullable(),sizeBytes:u().int().nonnegative().nullable()}).nullable(),movement:c({adapterDeltaNorm:u().nonnegative().nullable()}),evaluations:p(c({reference:c({id:Ee,contentHash:mt}).nullable().optional(),kind:b(["baseline","candidate"]),policyVersion:u().int().nonnegative(),taskCount:u().int().nonnegative().nullable().optional(),targetTaskCount:u().int().nonnegative().nullable().optional(),score:u().nullable(),threshold:u().nullable(),passed:A().nullable()})),canonicalPublication:c({state:Ee.nullable(),artifactId:Ee.nullable()}),syncedAt:At}),S0=c({count:u().int().nonnegative(),scoredCount:u().int().nonnegative(),meanScore:u().min(0).max(1).nullable(),passedCount:u().int().nonnegative(),passRate:u().min(0).max(1).nullable()}),x0=c({status:b(["scored","unavailable"]),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3),components:p(c({graderId:Ee,score:u().min(0).max(1).nullable(),passed:A(),feedback:i().trim().max(2e4).nullable()})).max(1e3)}),L5=c({taskId:Ee,input:oe(i(),se()),baseOutput:oe(i(),se()).nullable(),trainedOutput:oe(i(),se()).nullable(),baseGrade:x0.nullable(),trainedGrade:x0.nullable()}),H5=c({schemaVersion:S("openpond.trainingEvaluationSummary.v1"),jobId:Ee,tasksetId:Ee,base:S0,trained:S0,meanScoreDelta:u().min(-1).max(1).nullable(),examples:p(L5).max(1e6)});c({schemaVersion:S("openpond.trainingRunDetail.v1"),job:q_,events:p(O5),stepMetrics:p($5),policyMetrics:p(N5).default([]),managedEvidence:D5.nullable().default(null),evaluation:H5.nullable(),generatedAt:At});const U5=c({schemaVersion:S("openpond.trainingArtifact.v1"),id:Ee,jobId:Ee,kind:b(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:i().trim().min(1).max(4e3),sha256:mt,sizeBytes:u().int().nonnegative(),baseModelId:Ee.nullable(),baseModelRevision:i().trim().min(1).max(256).nullable(),tokenizerRevision:i().trim().min(1).max(256).nullable(),chatTemplateHash:mt.nullable(),nonProduction:A(),createdAt:At,metadata:Tc}),q5=c({schemaVersion:S("openpond.modelArtifactLineage.v1"),id:Ee,modelId:Ee,artifactId:Ee,jobId:Ee,tasksetId:Ee,tasksetHash:mt,graderHash:mt,planHash:mt,bundleHash:mt,recipeHash:mt,workerVersion:i().trim().min(1).max(256),trainerVersion:i().trim().min(1).max(256),importedAt:At,frozenEvaluationArtifactId:Ee.nullable(),promotable:A(),pinned:A().default(!1),status:b(["imported","rejected"]).default("imported"),rejectedAt:At.nullable().default(null),rejectionReason:i().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:j_.default(XF),managedServing:e5.nullable().default(null)}),z5=b(["chat_manual","agent","extension","authoring_optimizer"]),B5=c({schemaVersion:S("openpond.modelBinding.v1"),id:Ee,profileId:Ee,role:z5,roleTargetId:Ee,modelArtifactLineageId:Ee,tasksetId:Ee,evaluationArtifactId:Ee.nullable(),status:b(["active","rolled_back"]),priorBindingId:Ee.nullable(),rollbackTargetBindingId:Ee.nullable(),promotedBy:Ee,promotedAt:At,rolledBackAt:At.nullable(),metadata:Tc});c({schemaVersion:S("openpond.trainingActivity.v1"),profileId:Ee,active:A(),activeCounts:c({jobs:u().int().nonnegative(),creations:u().int().nonnegative(),minerRuns:u().int().nonnegative(),datasetImports:u().int().nonnegative()}),revision:mt,generatedAt:At});c({schemaVersion:S("openpond.tasksetOperationalState.v1"),tasksetId:Ee,attempts:p(H4),artifacts:p(U4),grades:p(z4),evaluationResults:p(vq).default([]),generatedAt:At});const F5=c({schemaVersion:S("openpond.trainingState.v1"),profileId:Ee,sources:p(BI),creations:p(b_),tasksetDrafts:p(Xa).default([]),tasksets:p(c0),benchmarkRuns:p(jp()).default([]),benchmarkComparisons:p(jp()).default([]),datasetImports:p(nF).default([]),datasetArtifacts:p(pB).default([]),graderAuditReports:p(B4),evaluationResults:p(jp()).default([]),candidates:p(g_),minerConfig:om,minerRuns:p(C4).default([]),modelProjects:p(E5).default([]),modelVersions:p(PF).default([]),modelRuns:p(qF).default([]),comparisonSeries:p(SF).default([]),comparisonSeriesEntries:p(CF).default([]),modelCurrencySnapshots:p(VF).default([]),continualBenchIssueReviews:p(GF).default([]),continualLearningDailyBatches:p(WF).default([]),rewardModelVersions:p(AF).default([]),rewardModelRuns:p(EF).default([]),modelTasksets:p(c0).default([]),plans:p(U_),bundles:p(Mv),jobs:p(q_),artifacts:p(U5),models:p(q5),rolloutReceipts:p(y5).default([]),modelBindings:p(B5).default([]),destinations:p(_5),baseModelCandidates:p(R5).default([]),activityRevision:mt.optional(),generatedAt:At}),V5=b(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),K5=c({datasetRelease:G,harnessRelease:G,evidenceSetRelease:G.nullable(),profileRelease:G.nullable(),model:c({source:i().trim().min(1).max(200),revision:i().trim().min(1).max(500),artifactHash:F.nullable()}).strict(),environmentHash:F,graderHash:F,toolContractHash:F,verificationReceiptHash:F.nullable()}).strict(),ii=c({schemaVersion:S("openpond.learningSignal.v1"),id:T,taskId:T.nullable(),episodeId:T.nullable(),policyVersion:u().int().nonnegative().nullable(),lineage:K5,approved:A(),verifier:b(["deterministic","model_judge","human","none"]),createdAt:Ce,contentHash:F,metadata:oe(i(),se()).default({})}).strict(),W5=ii.extend({kind:S("trajectory"),payload:c({traceRef:i().trim().min(1).max(2e3),traceHash:F,terminal:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:yI.nullable().optional()}).strict()}).strict(),G5=ii.extend({kind:S("reward"),payload:c({reward:u().finite(),components:oe(i(),u().finite()),eligible:A(),graderEvidenceRefs:p(T).max(1e3)}).strict()}).strict(),J5=ii.extend({kind:S("demonstration"),payload:c({prompt:i().max(5e5),response:i().max(1e6)}).strict()}).strict(),Z5=ii.extend({kind:S("preference"),payload:c({prompt:i().max(5e5),chosen:i().max(1e6),rejected:i().max(1e6),rationale:i().max(5e5).nullable()}).strict()}).strict(),Y5=ii.extend({kind:S("correction"),payload:c({original:i().max(1e6),corrected:i().max(1e6),rationale:i().max(5e5).nullable()}).strict()}).strict(),Q5=ii.extend({kind:S("critique"),payload:c({response:i().max(1e6),critique:i().max(5e5),severity:b(["note","warning","error"])}).strict()}).strict(),X5=ii.extend({kind:S("targeted_feedback"),payload:c({turnIndex:u().int().nonnegative(),target:b(["reasoning","tool","answer","policy"]),feedback:i().max(5e5)}).strict()}).strict(),e3=ii.extend({kind:S("grader_evidence"),payload:c({graderId:T,score:u().finite().nullable(),passed:A(),privilegedArtifactRefs:p(i().trim().min(1).max(2e3))}).strict()}).strict(),t3=ii.extend({kind:S("infrastructure_failure"),approved:S(!1),verifier:S("none"),payload:c({code:T,phase:T,retryable:A(),rewardEligible:S(!1)}).strict()}).strict(),z_=vt("kind",[W5,G5,J5,Z5,Y5,Q5,X5,e3,t3]);c({schemaVersion:S("openpond.learningSignalBatch.v1"),manifestId:T,manifestHash:F,sequence:u().int().nonnegative(),signals:p(z_).min(1).max(1e5),contentHash:F}).strict();const n3=c({id:T,turn:u().int().nonnegative(),kind:b(["message","tool_call","terminal"]),name:T.nullable(),arguments:oe(i(),se()),content:i().max(1e6).nullable(),contentHash:F}).strict(),a3=c({actionId:T,turn:u().int().nonnegative(),terminal:A(),output:oe(i(),se()),artifactRefs:p(i().trim().min(1).max(2e3)),contentHash:F}).strict(),o3=c({sequence:u().int().nonnegative(),type:b(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:Ce,payloadHash:F,metadata:oe(i(),se()).default({})}).strict(),k0=c({graderId:T,graderVersion:i().trim().min(1).max(200),score:u().finite().nullable(),passed:A(),rewardEligible:A(),failureClass:b(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(i().max(5e5)),visibleEvidenceRefs:p(i().trim().min(1).max(2e3)),privilegedEvidenceRefs:p(i().trim().min(1).max(2e3)),contentHash:F}).strict();c({schemaVersion:S("openpond.harnessRunTrace.v1"),manifest:G,taskId:T,seed:i().trim().min(1).max(500),events:p(o3).max(1e6),actions:p(n3).max(1e5),observations:p(a3).max(1e5),graderEvidence:p(k0).max(1e4),learningSignals:p(z_).max(1e5),terminal:A(),failureClass:k0.shape.failureClass,artifactHash:F,contentHash:F}).strict();const i3=i().trim().min(1).max(2e3).refine(e=>{const t=e.replaceAll("\\","/");return!t.startsWith("/")&&!t.includes("\0")&&!t.split("/").some(n=>!n||n==="."||n==="..")},"path must be a safe relative path"),r3=b(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),s3=c({id:T,kind:r3,path:i3,parentId:T.nullable(),mediaType:i().trim().min(1).max(200),visibility:b(["policy","verifier","host_private"]),portability:b(["portable","local_only"])}).strict().superRefine((e,t)=>{e.kind==="skill_resource"!=(e.parentId!==null)&&t.addIssue({code:"custom",message:"only Skill resources require parentId",path:["parentId"]})});c({schemaVersion:S("openpond.harnessSourceManifest.v1"),name:i().trim().min(1).max(240),files:p(s3).min(2).max(1e5),toolDeclarations:p(yc).max(200),capabilityRequirements:p(Eg).max(200),lifecycle:y1,graderInterface:S1,runtimeProtocol:i().trim().min(1).max(500),metadata:oe(i(),se()).default({})}).strict().superRefine((e,t)=>{const n=new Set,a=new Map,o=new Set;for(const[r,s]of e.files.entries())n.has(s.id)&&t.addIssue({code:"custom",message:"file ids must be unique",path:["files",r,"id"]}),o.has(s.path)&&t.addIssue({code:"custom",message:"file paths must be unique",path:["files",r,"path"]}),n.add(s.id),a.set(s.id,s.kind),o.add(s.path);for(const[r,s]of e.files.entries())s.parentId&&!n.has(s.parentId)?t.addIssue({code:"custom",message:"parentId must reference a declared Skill",path:["files",r,"parentId"]}):s.parentId&&a.get(s.parentId)!=="skill"&&t.addIssue({code:"custom",message:"parentId must reference a primary Skill file",path:["files",r,"parentId"]});e.files.filter(r=>r.kind==="dependency_lock").length!==1&&t.addIssue({code:"custom",message:"exactly one dependency lock is required",path:["files"]}),e.files.filter(r=>r.kind==="program").length!==1&&t.addIssue({code:"custom",message:"exactly one Harness program is required",path:["files"]})});c({rootPath:i(),sourcePath:i(),binding:RN,currentRelease:Uy,releases:p(Uy),transitions:p(PN)}).strict();c({profile:w1,activate:A().default(!0),reason:i().trim().min(1).max(1e4),actor:i().trim().min(1).max(240).default("local-user"),authoringSkillHash:i().regex(/^[a-f0-9]{64}$/).nullable().default(null)}).strict();c({release:G,reason:i().trim().min(1).max(1e4),actor:i().trim().min(1).max(240).default("local-user")}).strict();const l3=c({schemaVersion:S("openpond.trainingEngineCapabilities.v1"),adapterId:T,available:A(),methods:p(i().trim().min(1).max(100)),signalKinds:p(V5),modelFamilies:p(i().trim().min(1).max(200)),precisions:p(b(["fp32","fp16","bf16","tf32","int8","int4"])),topologies:p(i().trim().min(1).max(200)),workerProtocolVersion:i().trim().min(1).max(200),upstreamRevision:i().trim().min(1).max(500),workerImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/).nullable().default(null),capabilityReceipt:F,checkedAt:Ce,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),c3=c({schemaVersion:S("openpond.computeTargetCapabilities.v1"),adapterId:T,kind:b(["local","ssh","managed","custom"]),provider:T.nullable(),available:A(),devices:p(c({id:T,kind:b(["cpu","gpu","accelerator"]),vendor:i().trim().min(1).max(200),name:i().trim().min(1).max(500),memoryBytes:u().int().nonnegative().nullable(),runtime:i().trim().min(1).max(200)}).strict()),supportsWorkerImages:A(),supportsArtifactTransfer:A(),supportsCancellation:A(),capabilityReceipt:F,checkedAt:Ce,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),d3=c({schemaVersion:S("openpond.harnessRuntimeCapabilities.v1"),adapterId:T,available:A(),placements:p(b(["local","remote","colocated","provider_native"])),lifecycle:p(b(["create","reset","step","grade","collect","destroy"])),deterministicReplay:A(),privilegedIsolation:A(),capabilityReceipt:F,checkedAt:Ce,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict();c({schemaVersion:S("openpond.resolvedTrainingPlan.v1"),manifest:T4,recipe:H_,runtime:Iv,compute:_v,engine:Cv,execution:c({trainingPlanId:T,approvalId:T}).strict().nullable(),maximumSpendUsd:u().nonnegative().nullable(),approvalHash:F,contentHash:F}).strict().superRefine((e,t)=>{const n=[["runtime",e.runtime,e.manifest.runtimeTarget],["compute",e.compute,e.manifest.computeTarget],["engine",e.engine,e.manifest.engine]];for(const[a,o,r]of n)JSON.stringify(o)!==JSON.stringify(r)&&t.addIssue({code:"custom",path:[a],message:`${a} must exactly match the Harness Run Manifest`});e.recipe.method!==e.manifest.recipe.method&&t.addIssue({code:"custom",path:["recipe","method"],message:"Recipe method must match the Harness Run Manifest"}),e.approvalHash!==e.manifest.approval.approvalHash&&t.addIssue({code:"custom",path:["approvalHash"],message:"Approval hash must match the Harness Run Manifest"}),e.maximumSpendUsd!==e.manifest.approval.maximumSpendUsd&&t.addIssue({code:"custom",path:["maximumSpendUsd"],message:"Maximum spend must match the Harness Run Manifest"})});c({schemaVersion:S("openpond.adapterValidationReceipt.v1"),adapterId:T,valid:A(),issues:p(c({code:T,path:i().trim().max(2e3).nullable(),message:i().trim().min(1).max(5e3)}).strict()),capabilityReceipt:F,planHash:F,createdAt:Ce,contentHash:F}).strict();c({runId:T,adapterId:T,protocolVersion:b(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:b(["training_v2","adapter_native"]).default("adapter_native"),routeId:T.optional(),providerJobId:i().trim().min(1).max(1e3).nullable(),tenantId:T.optional(),leaseId:T.nullable(),manifestHash:F.optional(),inputBundleHash:F.optional(),createdAt:Ce}).strict();c({runId:T,state:b(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:i().trim().min(1).max(200),progress:u().min(0).max(1).nullable(),rolloutProgress:c({groupsCompleted:u().int().nonnegative(),groupsTarget:u().int().nonnegative(),optimizerUpdatesApplied:u().int().nonnegative(),optimizerUpdatesSkipped:u().int().nonnegative()}).strict().optional(),updatedAt:Ce,errorCode:T.nullable()}).strict();c({runId:T,manifestHash:F,artifacts:p(c({kind:b(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:i().trim().min(1).max(2e3),sha256:F,sizeBytes:u().int().nonnegative(),metadata:oe(i(),se()).optional()}).strict()),contentHash:F}).strict();const kh=b(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),u3=c({id:T,label:i().trim().min(1).max(500),description:i().trim().min(1).max(2e3),destinationId:T,computeAdapterId:T,runtimeAdapterId:T,engineAdapterId:T,methods:p(i().trim().min(1).max(100)),capabilityPills:p(i().trim().min(1).max(100)),executionMode:b(["local_worker","provider_native"]),approvalPolicy:c({providerId:pr,providerLabel:i().trim().min(1).max(200),settingsActionLabel:i().trim().min(1).max(500).nullable(),exportApprovalRequired:A(),exportDescription:i().trim().min(1).max(2e3).nullable(),preparationRequired:A(),minimumSpendUsd:u().nonnegative(),maximumSpendUsd:u().positive(),defaultMaximumSpendUsd:u().positive(),minimumRetentionDays:u().int().positive(),maximumRetentionDays:u().int().positive(),defaultRetentionDays:u().int().positive(),methodRequirement:i().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:c({maximumSequenceLength:u().int().positive(),maximumOutputTokens:u().int().positive(),maximumTrainingExamples:u().int().positive().nullable()}).strict(),defaults:c({loraRank:u().int().positive(),maxSteps:u().int().positive(),rolloutGroupSize:u().int().min(2).max(32),rolloutConcurrency:u().int().positive().max(32),rolloutOutputTokens:u().int().positive()}).strict(),available:A(),unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),m3=c({selectionKey:T,label:i().trim().min(1).max(500),source:b(["local","builtin","huggingface","managed","search"]),modelId:i().trim().min(1).max(1e3),revision:i().trim().min(1).max(500).nullable(),tokenizerRevision:i().trim().min(1).max(500).nullable(),chatTemplateHash:F.nullable(),modelAssetId:T.nullable(),expectedBytes:u().int().nonnegative().nullable(),cached:A(),known:A(),searchResolved:A(),computeAdapterIds:p(T),engineAdapterIds:p(T),preparationState:kh,reason:i().trim().min(1).max(5e3).nullable(),compatibilities:p(c({targetId:T,methods:p(i().trim().min(1).max(100)),state:kh,reason:i().trim().min(1).max(5e3).nullable()}).strict())}).strict();c({schemaVersion:S("openpond.trainingCatalog.v1"),models:p(m3).max(1e5),engines:p(l3),compute:p(c3),runtimes:p(d3),targets:p(u3),generatedAt:Ce,contentHash:F}).strict();c({schemaVersion:S("openpond.trainingPreparationPlan.v1"),modelRunId:T,state:kh,reason:i().trim().min(1).max(5e3).nullable(),runtime:Iv.nullable(),compute:_v.nullable(),engine:Cv.nullable(),downloads:p(c({kind:S("model"),label:i().trim().min(1).max(500),expectedBytes:u().int().nonnegative(),digest:i().trim().min(8).max(500),cached:A(),state:b(["ready","required","downloading","cancelled","failed"]),progress:u().min(0).max(1).nullable(),cancellable:A(),diskImpactBytes:u().int().nonnegative()}).strict()),dataMovement:p(c({direction:b(["upload","download","none"]),label:i().trim().min(1).max(500),bytes:u().int().nonnegative().nullable()}).strict()),quoteUsd:u().nonnegative().nullable(),maximumSpendUsd:u().nonnegative().nullable(),retentionDays:u().int().nonnegative().nullable(),sideEffectsStarted:S(!1),contentHash:F}).strict();const jv=32e3,p3=b(["steer","message","followup","queued","result"]),f3=b(["pending","included","resolved","cancelled","rejected"]),B_=c({id:i().min(1),sequence:u().int().nonnegative(),sessionId:i().min(1),senderSessionId:i().min(1).nullable(),senderKind:b(["user","task","runtime"]),kind:p3,body:i().trim().min(1).max(jv),payload:oe(i(),se()).default({}),idempotencyKey:i().min(1).max(200),replyTo:i().min(1).nullable(),expectedTurnId:i().min(1).nullable(),turnId:i().min(1).nullable(),requestIds:p(i()),state:f3,revision:u().int().positive(),createdAt:i(),updatedAt:i(),error:i().nullable()}).strict();c({expectedTurnId:i().trim().min(1),idempotencyKey:i().trim().min(1).max(200),prompt:i().trim().min(1).max(jv)}).strict();vt("action",[c({action:S("resume"),expectedRevision:u().int().positive()}).strict(),c({action:S("cancel"),expectedRevision:u().int().positive()}).strict(),c({action:S("edit"),expectedRevision:u().int().positive(),body:i().trim().min(1).max(jv)}).strict(),c({action:S("steer"),expectedRevision:u().int().positive(),expectedTurnId:i().trim().min(1)}).strict()]);const h3=c({id:i().min(1),sessionId:i().min(1),turnId:i().min(1),targetSessionId:i().min(1).nullable(),targetTurnId:i().min(1).nullable(),targetInputId:i().min(1).nullable().default(null),afterSequence:u().int().nonnegative(),deadline:i(),state:b(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:i(),updatedAt:i()}).strict();c({sessionId:i(),activeTurnId:i().nullable(),acceptingInput:A(),paused:A(),inputs:p(B_),waits:p(h3)});var sm=c({id:i().trim().min(1).max(240),revision:u().int().positive(),contentHash:i().regex(/^[a-f0-9]{64}$/),targetId:i().trim().min(1).max(240).nullable()}).strict(),g3=p(c({role:b(["system","user","assistant"]),content:i().max(1e5)}).strict()).max(100).superRefine((e,t)=>{e.reduce((n,a)=>n+a.content.length,0)>1e5&&t.addIssue({code:"custom",message:"Evaluation prompt exceeds 100,000 characters."})}),F_=c({schemaVersion:S("openpond.experimentAttemptGrade.v1"),selectionHash:i().regex(/^[a-f0-9]{64}$/),grades:p(_w).min(1).max(100),score:u().min(0).max(1).nullable(),passed:A(),rewardEligible:A(),gradingStatus:b(["scored","unscorable","not_configured"]),failureClass:aI.nullable(),contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;fa(a)!==n&&t.addIssue({code:"custom",message:"Experiment grading integrity failed."});const o=e.grades.flatMap(r=>r.components);(o.length!==e.grades.length||new Set(o.map(r=>r.graderId)).size!==o.length)&&t.addIssue({code:"custom",message:"Each selected criterion requires exactly one distinct grader result."});for(const r of e.grades){const{contentHash:s,...l}=r;fa(l)!==s&&t.addIssue({code:"custom",message:"A retained criterion changed."});for(const m of r.components){const{contentHash:d,...h}=m;fa(h)!==d&&t.addIssue({code:"custom",message:"A retained grader result changed."})}}}),ln=i().trim().min(1).max(200),Pl=i().regex(/^[a-f0-9]{64}$/),V_=vt("kind",[c({kind:S("hosted_chat"),modelId:ln,harness:Cc.optional(),messages:g3.optional(),maxOutputTokens:u().int().min(1).max(4096).default(1024),temperature:u().min(0).max(2).default(0),topP:u().gt(0).max(1).default(1)}).strict(),c({kind:S("fixture"),fixtureId:ln}).strict()]),v3=c({schemaVersion:S("openpond.modelStarterAttemptRequest.v1"),operationId:ln,teamId:ln,modelProjectId:ln.nullable(),project:sm.optional(),taskset:Wn,taskId:ln,environmentSeed:u().int().min(0).max(2147483647).default(0),policy:V_}).strict();c({modelProjectId:ln.nullable(),taskset:Wn,afterTaskId:ln.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({modelProjectId:ln.nullable(),taskset:Wn,available:A(),unavailableReason:i().max(1e3).nullable(),models:p(c({id:ln,name:i().max(500)}).strict()).max(200),tasks:p(c({id:ln,split:to,inputPreview:i().max(500),fixtures:p(c({id:ln,label:i().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:ln.nullable()}).strict();var Ov=c({schemaVersion:S("openpond.modelStarterAttemptSummary.v1"),id:ln,revision:u().int().positive(),request:v3,status:b(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:c({modelId:ln,provider:ln,upstreamModelId:i().min(1).max(500),configurationHash:Pl}).strict().nullable(),createdAt:wn(),startedAt:wn().nullable(),completedAt:wn().nullable(),cleanupComplete:A(),resultAvailable:A(),score:u().min(0).max(1).nullable(),gradingStatus:b(["not_started","scored","unscorable","not_configured"]).default("not_started"),passed:A().nullable(),outputPreview:i().max(500).nullable(),error:c({code:ln,message:i().max(2e3)}).strict().nullable()}).strict().superRefine((e,t)=>{e.request.policy.kind==="fixture"!=(e.policySnapshot===null)&&t.addIssue({code:"custom",path:["policySnapshot"],message:"Fixture execution must not claim a model identity."}),e.status==="completed"&&(!e.cleanupComplete||!e.resultAvailable||!e.completedAt)&&t.addIssue({code:"custom",message:"Completed attempts require retained results and confirmed cleanup."})});c({modelProjectId:ln,afterId:ln.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({items:p(Ov).max(100),nextCursor:ln.nullable()}).strict();c({schemaVersion:S("openpond.modelStarterAttemptResult.v1"),attempt:Ov,output:i().max(1048576).nullable(),messages:p(oe(i(),se())).max(4002),composition:Jl.nullable(),grade:_w.nullable().optional(),experimentGrade:F_.nullable().optional(),environment:c({status:b(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:A(),definition:Wn,initialStateHash:Pl.nullable(),finalStateHash:Pl.nullable(),attemptHash:Pl}).strict(),native:uv.optional(),providerRequestIds:p(ln).max(1001),contentHash:Pl}).strict().superRefine((e,t)=>{const n=e.attempt.request.policy.kind==="hosted_chat"?e.attempt.request.policy.harness:void 0;!!n!=!!e.native&&t.addIssue({code:"custom",path:["native"],message:"Standalone Harness results require their exact native evidence."}),e.native&&(!n||fa(n)!==fa(e.native.source)||e.native.modelConfigurationHash!==e.attempt.policySnapshot?.configurationHash||e.environment.initialStateHash!==null||e.environment.finalStateHash!==null||e.environment.status==="completed"&&(!e.environment.collected||e.output===null||e.native.partialOutputAvailable||e.native.outputHash!==fa(e.output)))&&t.addIssue({code:"custom",path:["native"],message:"Native evidence differs from the admitted source, model or output."}),e.experimentGrade&&((e.grade||e.composition)&&t.addIssue({code:"custom",message:"Selected Experiment grading cannot claim another grade population."}),(!["completed","failed"].includes(e.attempt.status)||!e.attempt.resultAvailable||e.attempt.score!==e.experimentGrade.score||e.attempt.gradingStatus!==e.experimentGrade.gradingStatus||e.attempt.passed!==(e.experimentGrade.score===null?null:e.experimentGrade.passed))&&t.addIssue({code:"custom",message:"Experiment grading differs from its retained attempt summary."})),e.grade&&(e.composition&&t.addIssue({code:"custom",path:["grade"],message:"An ordinary grade cannot also claim a Reward composition."}),(!["completed","failed"].includes(e.attempt.status)||!e.attempt.resultAvailable||e.attempt.score!==e.grade.score||e.attempt.gradingStatus!==e.grade.gradingStatus||e.attempt.passed!==(e.grade.score===null?null:e.grade.passed))&&t.addIssue({code:"custom",path:["grade"],message:"Ordinary grade differs from its terminal attempt summary."}))});var w0=i().trim().min(1).max(240),I0=i().regex(/^[a-f0-9]{64}$/),b3=c({kind:S("hosted_harness"),modelId:w0,reasoningEffort:b(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:w0,source:Yu,modelConfigurationHash:I0,packageHash:I0}).strict(),Ja=i().trim().min(1).max(200),K_=i().regex(/^[a-f0-9]{64}$/),y3=vt("kind",[V_.options[0],c({kind:S("fixture")}).strict(),b3]),zs=c({schemaVersion:S("openpond.modelTasksetRunRequest.v1"),operationId:Ja,teamId:Ja,modelProjectId:Ja.nullable(),name:i().trim().min(1).max(200).optional(),project:sm.optional(),taskset:Wn,policy:y3,population:p(vI).min(1).max(1e4)}).strict().superRefine((e,t)=>{new Set(e.population.map(n=>n.receiptId)).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Run receipt identities must be unique."}),e.population.some(n=>n.fixtureId!==null!=(e.policy.kind==="fixture"))&&t.addIssue({code:"custom",path:["population"],message:"Only fixture runs require a fixture identity for every member."}),e.population.some(n=>!/^(0|[1-9][0-9]*)$/.test(n.seed)||Number(n.seed)>2147483647)&&t.addIssue({code:"custom",path:["population"],message:"Hosted environment seeds must be integers from 0 to 2147483647."}),e.policy.kind==="hosted_harness"&&e.modelProjectId!==null&&t.addIssue({code:"custom",path:["modelProjectId"],message:"A Harness target retains its released Profile binding separately from Model artifacts."}),e.policy.kind==="hosted_harness"&&new Set(e.population.map(n=>ov([n.taskId,n.seed]))).size!==e.population.length&&t.addIssue({code:"custom",path:["population"],message:"Harness case identities must be unique for each task and seed."})}),W_=c({schemaVersion:S("openpond.modelTasksetRunSummary.v1"),id:Ja,revision:u().int().positive(),teamId:Ja,modelProjectId:Ja.nullable(),name:i().trim().min(1).max(200).optional(),project:sm.optional(),operationId:Ja,taskset:Wn,policyKind:b(["hosted_chat","fixture","hosted_harness"]),manifestHash:K_,status:b(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:u().int().min(1).max(1e4),counts:c({pending:u().int().nonnegative(),running:u().int().nonnegative(),completed:u().int().nonnegative(),failed:u().int().nonnegative(),cancelled:u().int().nonnegative()}).strict(),createdAt:wn(),startedAt:wn().nullable(),completedAt:wn().nullable(),cleanupComplete:A(),resultAvailable:A(),score:u().min(0).max(1).nullable(),metricName:i().min(1).max(240),error:c({code:Ja,message:i().max(2e3)}).strict().nullable()}).strict().superRefine((e,t)=>{Object.values(e.counts).reduce((n,a)=>n+a,0)!==e.totalCount&&t.addIssue({code:"custom",path:["counts"],message:"Run counts must account for the complete population."}),e.status!=="completed"&&e.score!==null&&t.addIssue({code:"custom",path:["score"],message:"Only completed evaluations publish a metric value."}),["completed","failed","cancelled"].includes(e.status)&&(!e.completedAt||e.counts.pending||e.counts.running)&&t.addIssue({code:"custom",message:"Terminal runs require complete population accounting."}),e.status==="cancelled"&&!e.cleanupComplete&&t.addIssue({code:"custom",message:"Cancelled runs require confirmed cleanup."}),e.resultAvailable&&!["completed","failed","cancelled"].includes(e.status)&&t.addIssue({code:"custom",message:"Run results require terminal population accounting."}),e.status==="completed"&&(!e.cleanupComplete||!e.resultAvailable)&&t.addIssue({code:"custom",message:"Completed evaluations require retained results and confirmed cleanup."})}),G_=c({summary:W_,request:zs,manifest:bI,policySnapshot:Ov.shape.policySnapshot}).strict();c({modelProjectId:Ja.optional(),projectId:sm.shape.id.optional(),afterId:Ja.optional(),limit:u().int().min(1).max(100).default(25)}).strict();c({items:p(W_).max(100),nextCursor:Ja.nullable()}).strict();c({schemaVersion:S("openpond.modelTasksetRunResult.v1"),run:G_,receipts:p(hq).min(1).max(1e4),metric:Cw.nullable(),contentHash:K_}).strict();var J_=i().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),S3=p(J_).min(1).max(20),_0=b(["input","output","expectedOutput","evaluatorContext"]),x3=c({destination:_0,path:S3,source:_0,sourcePath:p(J_).max(20)}).strict(),$v=p(x3).max(100).superRefine((e,t)=>{for(const[n,a]of e.entries())e.slice(0,n).some(o=>o.destination===a.destination&&(C0(o.path,a.path)||C0(a.path,o.path)))&&t.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function C0(e,t){return e.length<=t.length&&e.every((n,a)=>n===t[a])}var Vn=i().trim().min(1).max(200),cr=i().regex(/^[a-f0-9]{64}$/),Mc=c({id:Vn,revision:u().int().positive(),contentHash:cr}).strict(),wo=c({id:Vn,version:i().min(1).max(200),contentHash:cr,name:i().trim().min(1).max(500).optional(),feedbackKey:Bu,release:Mc.nullable(),mappings:$v.optional()}).strict(),Nv=c({id:Vn,version:i().min(1).max(200),contentHash:cr,mappings:$v}).strict(),Dv=c({operationId:Vn,id:Vn.optional(),expectedRevision:u().int().nonnegative(),request:zs,maximumCostUsd:u().finite().positive().max(1e4),graders:p(Nv).min(1).max(100).optional()}).strict().superRefine((e,t)=>{e.request.name||t.addIssue({code:"custom",path:["request","name"],message:"Name this Experiment before saving it."}),!!e.id!=e.expectedRevision>0&&t.addIssue({code:"custom",path:["expectedRevision"],message:"An update requires its saved definition revision."}),Math.round(e.maximumCostUsd*1e6)<1&&t.addIssue({code:"custom",path:["maximumCostUsd"],message:"The budget must be at least $0.000001."}),e.graders&&new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."})}),k3=c({schemaVersion:S("openpond.experimentDefinition.v1"),id:Vn,teamId:Vn,revision:u().int().positive(),request:zs,maximumCostUsd:u().finite().positive().max(1e4),graders:p(wo).min(1).max(100),createdAt:wn(),updatedAt:wn()}).strict();k3.extend({contentHash:cr});c({operationId:Vn,definition:Mc}).strict();c({projectId:Vn.optional(),datasetHash:cr.optional(),search:i().trim().max(200).optional(),status:b(["queued","running","cancelling","completed","failed","cancelled"]).optional(),afterId:Vn.optional(),limit:u().int().min(1).max(100).default(30)}).strict();c({definition:Mc.nullable(),configurationHash:cr.optional(),admissionRequestHash:cr.optional(),sourceExperimentId:Vn.optional(),maximumCostUsd:u().finite().positive().max(1e4),graders:p(wo).min(1).max(100)}).strict().superRefine((e,t)=>{e.definition===null&&(!e.configurationHash||!e.admissionRequestHash)&&t.addIssue({code:"custom",path:["configurationHash"],message:"A flat Experiment requires its sealed configuration hash."})});c({operationId:Vn,profileRepositoryId:Vn,definitionId:Vn,modelId:Vn,reasoningEffort:b(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:u().finite().positive().max(1e4)}).strict();c({request:zs,manifest:bI,maximumCostUsd:u().finite().positive().max(1e4),graders:p(wo).min(1).max(100)}).strict();var R0=i().trim().min(1).max(200),Lv=c({operationId:R0,request:zs,maximumCostUsd:u().finite().positive().max(1e4),graders:p(Nv).min(1).max(100).optional(),sourceExperimentId:R0.optional()}).strict().superRefine((e,t)=>{e.request.name||t.addIssue({code:"custom",path:["request","name"],message:"Name this Experiment before starting it."}),e.operationId!==e.request.operationId&&t.addIssue({code:"custom",path:["request","operationId"],message:"Use one operation identity for this Experiment."}),Math.round(e.maximumCostUsd*1e6)<1&&t.addIssue({code:"custom",path:["maximumCostUsd"],message:"The spending cap must be at least $0.000001."}),e.graders&&new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."})}),Z_=i().regex(/^[a-f0-9]{64}$/),w3=c({request:zs,maximumCostUsd:u().finite().positive().max(1e4),graders:p(wo).min(1).max(100),admissionRequestHash:Z_.optional(),sourceExperimentId:i().trim().min(1).max(200).optional()}).strict(),I3=w3.extend({configurationHash:Z_}).strict();G_.extend({configuration:I3}).strict();var $l=i().trim().min(1).max(200),_3=c({operationId:$l,execution:Ze,graders:p(Hs).min(1).max(100),maximumCostUsd:u().finite().min(1e-6).max(1e4),mappings:p(c({graderId:$l,fields:$v}).strict()).max(100).optional()}).strict().superRefine((e,t)=>{new Set(e.graders.map(n=>n.id)).size!==e.graders.length&&t.addIssue({code:"custom",path:["graders"],message:"Select each grader once."}),e.mappings&&(new Set(e.mappings.map(n=>n.graderId)).size!==e.mappings.length||e.mappings.some(n=>!e.graders.some(a=>a.id===n.graderId)))&&t.addIssue({code:"custom",path:["mappings"],message:"Map each selected grader at most once."})}),C3=c({schemaVersion:S("openpond.experimentScoringPass.v1"),id:$l,teamId:$l,revision:u().int().positive(),request:_3,graders:p(wo).min(1).max(100),status:b(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:u().int().min(1).max(1e4),counts:c({pending:u().int().nonnegative(),running:u().int().nonnegative(),scored:u().int().nonnegative(),unavailable:u().int().nonnegative(),failed:u().int().nonnegative(),cancelled:u().int().nonnegative()}).strict(),resultAvailable:A(),createdAt:wn(),startedAt:wn().nullable(),completedAt:wn().nullable(),error:c({code:$l,message:i().max(2e3)}).strict().nullable()}).strict();C3.extend({contentHash:i().regex(/^[a-f0-9]{64}$/)});var dee=c({teamId:i().trim().min(1).max(240),items:p(c({name:i().trim().min(1).max(500),source:Cc,ready:A(),reason:i().min(1).max(2e3).nullable()}).strict()).max(8),nextCursor:i().min(1).max(8192).nullable()}).strict();i().trim().min(1).max(200);var gl=i().trim().min(1).max(500),Y_=i().regex(/^[a-f0-9]{64}$/),R3=c({schemaVersion:S("openpond.experimentCaseInspection.v1"),teamId:gl,executionId:gl,manifestHash:Y_,receiptId:gl,taskId:gl,seed:i().min(1),input:oe(i(),se()).nullable(),output:se().nullable(),error:i().nullable(),events:p(oe(i(),se())).max(25),nextEventCursor:gl.nullable(),eventCount:u().int().nonnegative()}).strict();R3.extend({contentHash:Y_}).strict();function P3(e){return JSON.stringify(e.release?["reward",e.release.id,e.release.revision,e.release.contentHash,e.feedbackKey]:["dataset",e.id,e.version,e.contentHash,e.feedbackKey])}function A3(e){const t=new Map;for(const n of e){const a=P3(n),o=t.get(a);o?o.aliases.push(n):t.set(a,{key:a,grader:n,aliases:[n]})}return[...t.values()]}function uee(e){const t=A3(e),n=new Map;for(const a of t){const o=n.get(a.grader.feedbackKey);if(o&&o!==a.key)throw new Error(`Different selected grader releases use feedback key "${a.grader.feedbackKey}". Select one, or publish graders with distinct feedback keys.`);n.set(a.grader.feedbackKey,a.key);const r=JSON.stringify(a.grader.mappings??[]);if(a.aliases.some(s=>JSON.stringify(s.mappings??[])!==r))throw new Error(`Aliases of grader "${a.grader.feedbackKey}" have different field mappings. Select one alias and review its mappings.`)}return t.map(a=>a.grader)}var uu=kt.shape.id,T3=c({schemaVersion:S("openpond.modelBatchReviewInspection.v1"),packageHash:i().regex(/^[a-f0-9]{64}$/),definition:Ku,binding:Vu,evidence:p(Wu).min(1).max(1e4),decisions:p(tv).min(1).max(1e4)}).strict(),mee=c({schemaVersion:S("openpond.modelBatchReviewRequest.v1"),operationId:uu,modelId:uu,expectedModelRevision:u().int().positive(),tasksetRef:kt,rewardBindingRef:kt.nullable(),definition:c({name:i().trim().min(1).max(500).optional(),instructions:i().trim().min(1).max(2e4).optional(),inputSchema:Vt.optional(),outputSchema:Vt.optional(),requiredOutputs:Ku.shape.requiredOutputs}).strict(),examples:p(c({evidence:kt,input:Vt.optional(),expected:Vt.nullable().optional(),evaluatorContext:Vt.nullable().optional(),proposedTarget:Vt.nullable().optional()}).strict()).max(1e4)}).strict(),E3=c({schemaVersion:S("openpond.modelBatchReviewReceipt.v1"),operationId:uu,modelId:uu,source:ev,evidence:p(Wu).min(1).max(1e4),proposals:p(Lw).max(1e4)}).strict();p(c({asset:Fo,sourcePath:i().min(1)}).strict()).max(1e4);c({draft:Xa,filePaths:p(c({assetId:i().min(1),paths:p(_c).min(1).max(1e4)}).strict()).max(1e4)}).strict();const on=i().trim().min(1).max(200),Kn=i().regex(/^[a-f0-9]{64}$/),Q_=b(["queued","running","cancelling","completed","failed","cancelled","interrupted"]),X_=c({providerId:S("openpond"),modelId:i().trim().min(1).max(500),configurationHash:Kn,maxOutputTokens:u().int().positive().max(262144),temperature:u().min(0).max(2).optional(),topP:u().positive().max(1).optional(),messages:p(c({role:b(["system","user","assistant"]),content:i().max(262144)}).strict()).max(200)}).strict();c({configuration:Dv,package:sr}).strict();c({configuration:Dv,expectedPackageHash:Kn.optional()}).strict();c({schemaVersion:S("openpond.localExperimentDefinition.v1"),location:S("local"),id:on,teamId:on,ownerActorId:on,revision:u().int().positive(),configuration:Dv,model:X_,packageHash:Kn,graders:p(wo).min(1).max(100),availableGraders:p(wo).min(1).max(1e3),createdAt:wn(),updatedAt:wn(),contentHash:Kn}).strict();c({operationId:on,definition:Mc}).strict();c({teamId:on,id:on}).strict();c({teamId:on,projectId:on.optional(),status:Q_.optional(),datasetHash:Kn.optional(),search:i().max(100).optional(),afterId:on.optional(),limit:u().int().min(1).max(100).default(30)}).strict();const Hv=c({schemaVersion:S("openpond.localExperimentExecution.v1"),location:S("local"),id:on,teamId:on,ownerActorId:on,operationId:on,definition:Mc,kind:b(["target","scoring"]),executionHash:Kn,sourceExecution:c({id:on,executionHash:Kn}).strict().nullable(),packageHash:Kn,maximumCostUsd:u().finite().positive(),status:Q_,createdAt:wn(),completedAt:wn().nullable(),counts:c({pending:u().int().nonnegative(),running:u().int().nonnegative(),completed:u().int().nonnegative(),failed:u().int().nonnegative(),cancelled:u().int().nonnegative(),unknown:u().int().nonnegative()}).strict(),usage:c({knownCostUsd:u().finite().nonnegative(),costUsd:u().finite().nonnegative().nullable(),heldUsd:u().finite().nonnegative(),uncertainRequests:u().int().nonnegative()}).strict(),cleanupComplete:A(),error:i().max(2e3).nullable()}).strict(),M3=Hv.omit({definition:!0});function Uv(e,t){e.kind==="scoring"!=(e.sourceExecution!==null)&&t.addIssue({code:"custom",message:"Only retained scoring passes name an original execution."}),["completed","failed","cancelled","interrupted"].includes(e.status)&&(!e.completedAt||e.counts.pending||e.counts.running)&&t.addIssue({code:"custom",message:"Terminal local execution requires complete population accounting."}),["completed","cancelled"].includes(e.status)&&!e.cleanupComplete&&t.addIssue({code:"custom",message:"Successful completion or cancellation requires confirmed local transport cleanup."}),e.usage.uncertainRequests>0&&e.usage.costUsd!==null&&t.addIssue({code:"custom",message:"Uncertain provider charges cannot claim a measured total."})}Hv.superRefine(Uv);const jc=M3.superRefine(Uv);c({configuration:Lv,package:sr}).strict();const pee=c({configuration:Lv,expectedPackageHash:i().regex(/^[a-f0-9]{64}$/).optional()}).strict(),P0=c({configuration:Lv,model:X_,packageHash:i().regex(/^[a-f0-9]{64}$/),graders:p(wo).min(1).max(100),availableGraders:p(wo).min(1).max(1e3),retainedConfigurationHash:i().regex(/^[a-f0-9]{64}$/).optional(),configurationHash:i().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{configurationHash:n,...a}=e;_t(a)!==n&&t.addIssue({code:"custom",message:"Local configuration snapshot bytes changed."})}),{definition:fee,...j3}=Hv.shape,qv=c({...j3,kind:S("target"),...P0.shape}).strict().superRefine((e,t)=>{const n={configuration:e.configuration,model:e.model,packageHash:e.packageHash,graders:e.graders,availableGraders:e.availableGraders,...e.retainedConfigurationHash?{retainedConfigurationHash:e.retainedConfigurationHash}:{},configurationHash:e.configurationHash};Uv(e,t),P0.safeParse(n).success||t.addIssue({code:"custom",message:"Local Experiment configuration changed."}),(e.operationId!==e.configuration.operationId||e.teamId!==e.configuration.request.teamId||e.maximumCostUsd!==e.configuration.maximumCostUsd)&&t.addIssue({code:"custom",message:"Local Experiment differs from its sealed admission."})}),hee=c({items:p(qv).max(100),nextCursor:i().nullable()}).strict();c({teamId:i().min(1).max(200),id:i().min(1).max(200),configurationHash:i().regex(/^[a-f0-9]{64}$/).optional()}).strict();const O3=c({operationId:on,execution:c({id:on,executionHash:Kn}).strict(),graderPackage:sr,graders:p(Nv).min(1).max(100),maximumCostUsd:u().finite().positive().max(1e4)}).strict(),gee=O3.omit({graderPackage:!0}),$3=uv,N3=c({sessionId:on,turnId:on,source:Yu,profileRef:Co,admissionHash:Kn,modelConfigurationHash:Kn,traceHash:Kn,runtimeEventRefs:p(on).max(1e4),startedAt:wn(),completedAt:wn(),outputHash:Kn,partialOutputAvailable:A()}).strict(),eC=c({receiptId:on,taskId:on,seed:i(),status:b(["pending","running","completed","failed","cancelled","unknown"]),input:oe(i(),se()),policyVisibleContext:oe(i(),se()),output:i().nullable(),messages:p(se()).max(4002),grade:F_.nullable(),error:i().nullable(),native:$3.optional(),profileNative:N3.optional()}).strict(),vee=c({execution:Tt([qv,jc]),cases:p(eC).max(1e4),contentHash:Kn}).strict(),D3=c({items:p(c({sequence:u().int().positive(),type:i().min(1),payload:se()}).strict()).max(500),nextCursor:u().int().positive().nullable()}).strict(),bee=c({location:S("local"),execution:Tt([qv,jc]),case:eC,trace:D3}).strict(),yee=c({items:p(jc).max(100),nextCursor:on.nullable()}).strict(),See=c({execution:jc,graders:p(wo).min(1).max(100),graderPackageHash:Kn}).strict(),A0=c({execution:jc,manifest:pv,result:fv}).strict().superRefine((e,t)=>{try{if(gI(e),e.manifest.id!==e.execution.id||e.manifest.teamId!==e.execution.teamId||e.manifest.lineage?.execution.id!==(e.execution.sourceExecution?.id??e.execution.id)||e.manifest.lineage.execution.contentHash!==(e.execution.sourceExecution?.executionHash??e.execution.executionHash)||e.manifest.lineage.scoringPassId!==(e.execution.kind==="scoring"?e.execution.id:null)||e.manifest.maximumCostUsd!==e.execution.maximumCostUsd)throw new Error("Portable evidence differs from its retained local execution.")}catch(n){t.addIssue({code:"custom",message:n instanceof Error?n.message:"Local portable evidence verification failed."})}}),xee=c({location:S("local"),baseline:A0,candidate:A0}).strict(),Wr=i().trim().min(1).max(240),hf=i().regex(/^[a-f0-9]{64}$/),kee=c({location:S("local"),harnesses:p(c({id:Wr,name:i().max(500),source:Cc}).strict()).max(100),profiles:p(c({id:Wr,name:i().max(500),profileRef:Co,sourceRevision:i().min(1).max(500),harnessRelease:c({id:Wr,contentHash:hf}).strict(),definitionId:Wr,definitionHash:hf,taskset:c({id:Wr,revision:u().int().positive(),contentHash:hf}).strict(),taskCount:u().int().nonnegative(),taskIds:p(Wr).max(1e4),seeds:p(i()).max(1e4)}).strict()).max(100)}).strict();function L3(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const o=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&o.searchParams.set("afterSequence",String(n)),{url:o.toString(),init:{headers:a,signal:t}}}function H3(e){return Math.min(500*2**Math.max(0,e),1e4)}async function U3(e,t,n,a){tC(e);const o=e.body.getReader(),r=new TextDecoder;let s="";for(;!a?.aborted;){const{done:l,value:m}=await o.read();if(l){s+=r.decode();break}s+=r.decode(m,{stream:!0});let d=s.indexOf(`
|
|
179
|
-
|
|
180
|
-
`);for(;d>=0;){const h=s.slice(0,d);s=s.slice(d+2),E0(h,t,n),d=s.indexOf(`
|
|
181
|
-
|
|
182
|
-
`)}}!a?.aborted&&s.trim()&&E0(s,t,n)}function tC(e){if(!e.ok)throw new Error(`event stream failed: ${e.status} ${e.statusText||"HTTP error"}`);if(!e.body)throw new Error("event stream did not return a response body")}function q3(e,t,n,a,o={}){const r=new AbortController,s=o.fetchImpl??fetch,l=o.reconnectDelayMs??H3;let m=T0(o.afterSequence),d=!1;return(async()=>{let h=0;for(;!r.signal.aborted;)try{const g=L3(e,r.signal,m),y=await s(g.url,g.init);if(tC(y),d=!0,h=0,await U3(y,w=>{const _=T0(w.sequence);_>0&&_<=m||(_>0&&(m=_),t(w))},a,r.signal),d=!1,r.signal.aborted)break;throw new Error("event stream ended")}catch(g){if(d=!1,r.signal.aborted)break;n(g),await z3(l(h),r.signal),h+=1}})().catch(()=>{}),{close(){r.abort()},isOpen(){return d}}}function T0(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function E0(e,t,n){let a="message";const o=[];for(const r of e.split(`
|
|
183
|
-
`))r.startsWith(":")||(r.startsWith("event: ")&&(a=r.slice(7).trim()),r.startsWith("data: ")&&o.push(r.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||o.length===0))try{t(JSON.parse(o.join(`
|
|
184
|
-
`)))}catch{}}async function z3(e,t){e<=0||t.aborted||await new Promise(n=>{const a=globalThis.setTimeout(n,e);t.addEventListener("abort",()=>{globalThis.clearTimeout(a),n()},{once:!0})})}class B3 extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function M0(e={}){const t=new URLSearchParams;return e.teamId&&t.set("teamId",e.teamId),e.projectId&&t.set("projectId",e.projectId),e.agentId&&t.set("agentId",e.agentId),t}const j0=new WeakMap,O0=new WeakMap,hd=new WeakMap;let F3=0;async function z(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const o=(hd.get(e)??Promise.resolve()).catch(()=>{}).then(()=>$0(e,t,n));hd.set(e,o);try{return await o}finally{hd.get(e)===o&&hd.delete(e)}}return $0(e,t,n)}async function $0(e,t,n){const a=++F3;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=j0.get(e);if(!m)throw new Error("Reload settings before saving so changes can be checked against the current file.");n={...n,body:JSON.stringify({expectedRevision:m,...JSON.parse(n.body)})}}const o=new Headers(n?.headers);o.set("Content-Type","application/json"),o.set("Authorization",`Bearer ${e.token}`);const r=await fetch(`${e.serverUrl}${t}`,{...n,headers:o});if(!r.ok){const m=await r.json().catch(()=>({})),d=m&&typeof m=="object"&&"error"in m?String(m.error):r.statusText;throw new B3(d,r.status)}if(r.status===204)return;const s=await r.json(),l=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof l=="string"&&a>=(O0.get(e)??0)&&(j0.set(e,l),O0.set(e,a)),s}function wee(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function Iee(e){return["openpond-terminal",`openpond-token.${K3(e.token)}`]}function V3(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const o=t.subarray(a,a+32768);n+=String.fromCharCode(...o)}return btoa(n)}function K3(e){return V3(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function W3(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)n[a]=t.charCodeAt(a);return new TextDecoder().decode(n)}const G3={teamInvitations:e=>z(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>z(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>z(e,"/v1/organizations"),createOrganization:(e,t)=>z(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>z(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>z(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>z(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>z(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>z(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>z(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},J3={taskInbox:(e,t)=>z(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`),steerTurn:(e,t,n)=>z(e,`/v1/sessions/${encodeURIComponent(t)}/turns/steer`,{method:"POST",body:JSON.stringify(n)}),queueTaskInput:(e,t,n,a)=>z(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`,{method:"POST",body:JSON.stringify({input:n,idempotencyKey:a})}),updateTaskInput:(e,t,n,a)=>z(e,`/v1/sessions/${encodeURIComponent(t)}/inbox/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),sendTurn:(e,t,n)=>z(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>z(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>z(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>z(e,`/v1/create-improve-runs?${Z3(t).toString()}`),getCreateImproveRun:(e,t)=>z(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>z(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>z(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>z(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>z(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>z(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>z(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function Z3(e){const t=new URLSearchParams;return e.profileId&&t.set("profileId",e.profileId),e.conversationId&&t.set("conversationId",e.conversationId),e.targetKind&&t.set("targetKind",e.targetKind),e.targetId&&t.set("targetId",e.targetId),e.limit&&t.set("limit",String(e.limit)),t}const Y3={sandboxFiles:(e,t,n={})=>{const a=new URLSearchParams({list:"1"});return n.path&&a.set("path",n.path),n.recursive!==void 0&&a.set("recursive",String(n.recursive)),n.maxEntries!==void 0&&a.set("maxEntries",String(n.maxEntries)),z(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const o=new URLSearchParams({path:n});a.offsetBytes!==void 0&&o.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&o.set("maxBytes",String(a.maxBytes));const r=await z(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${o.toString()}`);return{...r,contents:r.file.isBinary?"":W3(r.file.contentsBase64)}}},Q3={sandboxGitStatus:(e,t)=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},X3={connectedAppStatus:(e,t={})=>{const n=M0(t);return n.set("status",t.status??"all"),z(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=M0(t);return t.status&&n.set("status",t.status),z(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},e6={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return z(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return z(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return z(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>z(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return z(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:o,...r}=n;return z(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(r)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return z(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return z(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>z(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>z(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>z(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},t6={sandbox:(e,t)=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},n6={...X3,...e6,...t6,...Q3,...Y3},a6={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),z(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>z(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>z(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>z(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>z(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>z(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>z(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const o=new URLSearchParams;return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),z(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${o.size?`?${o}`:""}`)},sendCommunityMessage:(e,t,n,a)=>z(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,o)=>z(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:o})}),deleteCommunityMessage:(e,t,n,a)=>z(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>z(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>z(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/mute`,{method:"POST",body:JSON.stringify({muted:a})}),searchCommunityMembers:(e,t,n={})=>{const a=new URLSearchParams;return n.query&&a.set("query",n.query),n.cursor&&a.set("cursor",n.cursor),n.limit!=null&&a.set("limit",String(n.limit)),z(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>z(e,`/v1/communities/${encodeURIComponent(t)}/notifications`,{method:"POST",body:JSON.stringify({mode:n})}),communityEvents:(e,t,n={})=>{const a=new URLSearchParams;return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),z(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>z(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>z(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>z(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},zv="openpond-app-server-url",ac="openpond-app-token",o6=750;function nC(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function wh(e){const t=e.getItem(zv)?.trim(),n=e.getItem(ac)?.trim();return t&&n?{serverUrl:t,token:n}:null}function mu(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Gr(e,t){e.setItem(zv,t.serverUrl),e.setItem(ac,t.token)}function N0(e,t){const n=wh(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(zv),e.removeItem(ac))}function i6(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function r6(){const e=window.location.hash.startsWith("#")?window.location.hash.slice(1):window.location.hash;if(!e)return null;const t=new URLSearchParams(e),n=t.get("openpondToken")?.trim(),a=t.get("openpondServerUrl")?.trim()||nC();return!a||!n?null:{serverUrl:a,token:n}}function s6(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function gd(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function l6(){const e=[],t=mu(window.sessionStorage),n=mu(window.localStorage),a=nC(),o=t?.getItem(ac)??n?.getItem(ac);return gd(e,null),gd(e,a&&o?{serverUrl:a,token:o.trim()}:null),gd(e,t?wh(t):null),gd(e,n?wh(n):null),e}async function gf(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),o6);try{const a=await fetch(`${e}/health`,{signal:t.signal}),o=await a.json().catch(()=>null);return a.ok&&o?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function c6(){if(window.openpond)return window.openpond.getConnection();const e=mu(window.sessionStorage),t=mu(window.localStorage),n=r6();if(n&&await gf(n.serverUrl))return t&&Gr(t,n),e&&Gr(e,n),s6(),{...n,platform:navigator.platform};const a=i6();if(a&&await gf(a.serverUrl))return t&&Gr(t,a),e&&Gr(e,a),{...a,platform:navigator.platform};const o=l6();for(const r of o){if(await gf(r.serverUrl))return t&&Gr(t,r),e&&Gr(e,r),{...r,platform:navigator.platform};e&&N0(e,r),t&&N0(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Q={...a6,bootstrap:e=>z(e,"/v1/bootstrap?refreshCodex=1"),localProjectActions:(e,t)=>z(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>z(e,"/v1/extensions"),extensionPreview:(e,t)=>z(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>z(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>z(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>z(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>z(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>z(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>z(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>z(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>z(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>z(e,`/v1/team-chat/realtime-session?teamId=${encodeURIComponent(t)}`),teamChatEvents:(e,t,n={})=>{const a=new URLSearchParams({teamId:t});return n.after!=null&&a.set("after",String(n.after)),n.limit!=null&&a.set("limit",String(n.limit)),z(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>z(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>z(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const o=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&o.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&o.set("limit",String(a.limit)),z(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${o.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>z(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>z(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>z(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>z(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>z(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>z(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>z(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>z(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>z(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>z(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>z(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>z(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>z(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>z(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=D0(t),a=n.size?`?${n.toString()}`:"";return z(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=D0(t);t.sessionId&&n.set("sessionId",t.sessionId),t.turnId&&n.set("turnId",t.turnId),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return z(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>z(e,`/v1/usage/turn-cache?sessionId=${encodeURIComponent(t)}`),runtimeEventsPage:(e,t={})=>{const n=new URLSearchParams;t.sessionId&&n.set("sessionId",t.sessionId),t.afterSequence!==void 0&&n.set("afterSequence",String(t.afterSequence)),t.beforeSequence!==void 0&&t.beforeSequence!==null&&n.set("beforeSequence",String(t.beforeSequence)),t.limit!==void 0&&n.set("limit",String(t.limit));const a=n.size?`?${n.toString()}`:"";return z(e,`/v1/events/page${a}`)},workOutputs:e=>z(e,"/v1/work/outputs"),harnessHistory:e=>z(e,"/v1/harness"),refinerHistory:e=>z(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>z(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>z(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>z(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>z(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>z(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>z(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>z(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>z(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>z(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>z(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>z(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>z(e,`/v1/training/activity?profileId=${encodeURIComponent(t)}`),portableTrainingCatalog:(e,t="",n)=>{const a=new URLSearchParams;return t.trim()&&a.set("query",t.trim()),n&&a.set("method",n),z(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>z(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>z(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),candidateReview:(e,t,n=!1,a="models")=>z(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision?refresh=${n}`),recordCandidateReview:(e,t,n,a="models")=>z(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision`,{method:"POST",body:JSON.stringify(n)}),candidateReviewHistory:(e,t,n,a="models")=>z(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision-history?decisionId=${encodeURIComponent(n.id)}&decisionHash=${n.contentHash}`),trainingEvaluationTasks:async(e,t,n,a)=>{const o=new URLSearchParams({limit:"25"});return a&&o.set("cursor",a),z(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${o}`)},trainingRequest:(e,t,n,a="POST")=>z(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>z(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>z(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>z(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>z(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>z(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>z(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>z(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({clientRequestId:n})}),chatWorkflows:(e,t)=>{const n=t?`?sessionId=${encodeURIComponent(t)}`:"";return z(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>z(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>z(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>z(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>z(e,`/v1/chat-workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({})}),localAgentSchedules:(e,t={})=>{const n=new URLSearchParams;t.localProjectId&&n.set("localProjectId",t.localProjectId);const a=n.size?`?${n.toString()}`:"";return z(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>z(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>z(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>z(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),localAgentScheduleRuns:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit));const o=a.size?`?${a.toString()}`:"";return z(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${o}`)},refreshOpenPondAccounts:e=>z(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>z(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>z(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>z(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>z(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>z(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>z(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>z(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>z(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>z(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>z(e,"/v1/providers"),loadProviderModels:(e,t,n={})=>{const a=new URLSearchParams;n.query?.trim()&&a.set("query",n.query.trim()),n.limit&&a.set("limit",String(n.limit));const o=a.size?`?${a.toString()}`:"";return z(e,`/v1/providers/${encodeURIComponent(t)}/models${o}`)},refreshProviderModels:(e,t,n)=>z(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>z(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>z(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>z(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>z(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>z(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>z(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>z(e,"/v1/profile"),profileCatalog:e=>z(e,"/v1/profile/catalog"),profileWorkflows:e=>z(e,"/v1/profile/workflows"),profileEvaluations:e=>z(e,"/v1/profile/evaluations"),profileEvaluationPrepare:(e,t)=>z(e,"/v1/profile/evaluations/prepare",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRun:(e,t)=>z(e,"/v1/profile/evaluations/run",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRunSuite:(e,t)=>z(e,"/v1/profile/evaluations/run-suite",{method:"POST",body:JSON.stringify(t)}),profileEvaluationCompare:(e,t)=>z(e,"/v1/profile/evaluations/compare",{method:"POST",body:JSON.stringify({id:`comparison-${crypto.randomUUID()}`,runIds:t})}),profileEvaluationSaveReport:(e,t,n)=>z(e,"/v1/profile/evaluations/reports",{method:"POST",body:JSON.stringify({id:`report-${crypto.randomUUID()}`,evidenceKind:t,evidenceId:n})}),profileSelect:(e,t)=>z(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>z(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>z(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>z(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>z(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>z(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>z(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>z(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>z(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>z(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>z(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>z(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>z(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>z(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>z(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>z(e,"/v1/remote-access"),enableRemoteAccess:e=>z(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>z(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>z(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>z(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>z(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>z(e,`/v1/sessions/${t}`,{method:"PATCH",body:JSON.stringify(n)}),codexHistoryThread:(e,t,n={})=>{const a=new URLSearchParams;n.limit!==void 0&&a.set("limit",String(n.limit)),n.tail&&a.set("tail","1");const o=a.size?`?${a.toString()}`:"";return z(e,`/v1/codex-history/${encodeURIComponent(t)}${o}`)},codexHistoryThreadIncremental:(e,t,n={})=>{const a=new URLSearchParams({incremental:"1"});return n.afterEventId&&a.set("afterEventId",n.afterEventId),n.limit!==void 0&&a.set("limit",String(n.limit)),n.revision&&a.set("revision",n.revision),n.tail&&a.set("tail","1"),z(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>z(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>z(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>z(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>z(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>z(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>z(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>z(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>z(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>z(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>z(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),workspaceFile:(e,t,n)=>z(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>z(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>z(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>z(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>z(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>z(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>z(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>z(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>z(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>z(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...G3,...n6,createLocalProject:(e,t)=>z(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>z(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>z(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source`,{method:"POST",body:JSON.stringify(n)}),previewLocalProjectCloudSource:(e,t,n={})=>{const a=new URLSearchParams;n.branch?.trim()&&a.set("branch",n.branch.trim());const o=a.toString()?`?${a.toString()}`:"";return z(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${o}`)},deleteLocalProject:(e,t)=>z(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>z(e,"/v1/system/git"),installMacOSCommandLineTools:e=>z(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...J3,resolveApproval:(e,t,n)=>z(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function D0(e){const t=new URLSearchParams;return e.range&&t.set("range",e.range),e.visibility&&t.set("visibility",e.visibility),e.status&&t.set("status",e.status),e.provider&&t.set("provider",e.provider),e.model&&t.set("model",e.model),t}const d6=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),u6=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),L0=e=>{const t=u6(e);return t.charAt(0).toUpperCase()+t.slice(1)},aC=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),m6=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var p6={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const f6=v.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:r,iconNode:s,...l},m)=>v.createElement("svg",{ref:m,...p6,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:aC("lucide",o),...!r&&!m6(l)&&{"aria-hidden":"true"},...l},[...s.map(([d,h])=>v.createElement(d,h)),...Array.isArray(r)?r:[r]]));const dt=(e,t)=>{const n=v.forwardRef(({className:a,...o},r)=>v.createElement(f6,{ref:r,iconNode:t,className:aC(`lucide-${d6(L0(e))}`,`lucide-${e}`,a),...o}));return n.displayName=L0(e),n};const h6=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],g6=dt("activity",h6);const v6=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],b6=dt("archive-restore",v6);const y6=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],S6=dt("arrow-left",y6);const x6=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],oC=dt("bookmark",x6);const k6=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]],iC=dt("bookmark-x",k6);const w6=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]],H0=dt("book-open-text",w6);const I6=[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]],vd=dt("boxes",I6);const _6=[["path",{d:"M16 14v2.2l1.6 1",key:"fo4ql5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]],C6=dt("calendar-clock",_6);const R6=[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]],rC=dt("chart-column-stacked",R6);const P6=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Uo=dt("check",P6);const A6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Dd=dt("circle-check",A6);const T6=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ai=dt("chevron-down",T6);const E6=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],dr=dt("chevron-right",E6);const M6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],j6=dt("circle-alert",M6);const O6=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],lm=dt("cloud",O6);const $6=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],N6=dt("credit-card",$6);const D6=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],L6=dt("download",D6);const H6=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],vf=dt("external-link",H6);const U6=[["path",{d:"M4.226 20.925A2 2 0 0 0 6 22h12a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v3.127",key:"wfxp4w"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]],q6=dt("file-output",U6);const z6=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Bv=dt("file-text",z6);const B6=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],sC=dt("folder",B6);const F6=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],lC=dt("folder-git-2",F6);const V6=[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]],K6=dt("git-branch",V6);const W6=[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]],G6=dt("github",W6);const J6=[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],cC=dt("earth",J6);const Z6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Y6=dt("circle-question-mark",Z6);const Q6=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],X6=dt("list-filter",Q6);const eV=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],tV=dt("loader-circle",eV);const nV=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],aV=dt("maximize-2",nV);const oV=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],cm=dt("message-square",oV);const iV=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Oc=dt("ellipsis",iV);const rV=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],dC=dt("panel-left",rV);const sV=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Ih=dt("panel-right",sV);const lV=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],Fv=dt("pin",lV);const cV=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],Vv=dt("pin-off",cV);const dV=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],uV=dt("plus",dV);const mV=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],pV=dt("power",mV);const fV=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],hV=dt("search",fV);const gV=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],uC=dt("settings",gV);const vV=[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]],mC=dt("shapes",vV);const bV=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],U0=dt("shield",bV);const yV=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],dm=dt("square-pen",yV);const SV=[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]],pC=dt("square-terminal",SV);const xV=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],q0=dt("user-round",xV);const kV=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],$c=dt("x",kV);function wV({platform:e}){return!um()||Kv(e)?null:k.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[k.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{bf("minimize")},children:k.jsx(ai,{size:14})}),k.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{bf("toggleMaximize")},children:k.jsx(aV,{size:12})}),k.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{bf("close")},children:k.jsx($c,{size:13})})]})}function Kv(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function um(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function bf(e){const t=window.openpond;if(!(t&&(e==="minimize"?await t.minimizeWindow?.():e==="toggleMaximize"?await t.toggleMaximizeWindow?.():await t.closeWindow?.())!==!1)){if(e==="toggleMaximize"&&document.fullscreenEnabled){document.fullscreenElement?await document.exitFullscreen():await document.documentElement.requestFullscreen();return}if(e==="close"){window.close();return}console.warn("Window controls require the Electron desktop shell.")}}function IV({value:e,options:t,disabled:n,compact:a,className:o,icon:r,placement:s="bottom",label:l,tooltip:m,searchable:d=!1,floating:h=!1,onChange:g}){const[y,w]=v.useState(!1),[_,P]=v.useState(""),M=v.useRef(null),[C,$]=v.useState();v.useLayoutEffect(()=>{if(!y||!h)return;function R(){const E=M.current?.getBoundingClientRect();if(!E)return;const H=window.innerHeight-E.bottom-12,B=E.top-12,D=H<180&&B>H;$({position:"fixed",left:Math.max(12,E.left),width:Math.min(E.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:D?"auto":E.bottom+5,bottom:D?window.innerHeight-E.top+5:"auto",maxHeight:Math.max(80,Math.min(320,D?B-5:H-5)),overflowY:"auto",zIndex:1e3})}return R(),window.addEventListener("resize",R),window.addEventListener("scroll",R,!0),()=>{window.removeEventListener("resize",R),window.removeEventListener("scroll",R,!0)}},[y,h]);const O=t.find(R=>R.value===e)??t[0],j=_.trim().toLowerCase(),x=j?t.filter(R=>[R.label,R.shortLabel,R.description].some(E=>E?.toLowerCase().includes(j))):t;return v.useEffect(()=>{if(!y){P("");return}function R(H){M.current?.contains(H.target)||w(!1)}function E(H){H.key==="Escape"&&w(!1)}return document.addEventListener("pointerdown",R),document.addEventListener("keydown",E),()=>{document.removeEventListener("pointerdown",R),document.removeEventListener("keydown",E)}},[y]),k.jsxs("div",{className:`dropdown-select ${o??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:M,children:[k.jsxs("button",{type:"button",className:`dropdown-trigger ${y?"active":""}`,disabled:n,"aria-label":l,"aria-haspopup":"menu","aria-expanded":y,onClick:()=>w(R=>!R),children:[r,k.jsx("span",{children:O?.shortLabel??O?.label??e}),k.jsx(ai,{size:14})]}),y&&k.jsxs("div",{className:"dropdown-menu",role:"menu",style:h?C:void 0,children:[d?k.jsxs("label",{className:"dropdown-search",onClick:R=>R.stopPropagation(),children:[k.jsxs("span",{className:"sr-only",children:["Search ",l]}),k.jsx("input",{autoFocus:!0,placeholder:`Search ${l.toLowerCase()}`,value:_,onChange:R=>P(R.target.value)})]}):null,x.map(R=>k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":R.value===e,disabled:R.disabled,className:[R.value===e?"selected":"",R.separatorBefore?"separator-before":"",R.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{R.disabled||(g(R.value),P(""),w(!1))},children:[k.jsxs("span",{children:[R.icon==="plus"?k.jsx(uV,{size:13}):null,k.jsx("span",{children:R.label})]}),R.description&&k.jsx("small",{children:R.description})]},R.value)),x.length?null:k.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const _V=[{destination:"walkthroughs",icon:H0,label:"Walkthroughs"},{destination:"external",icon:H0,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:Bv,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:N6,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:cC,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:G6,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:cm,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function CV({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=v.useState(!1),o=v.useRef(null);return v.useEffect(()=>{if(!n)return;function r(l){o.current?.contains(l.target)||a(!1)}function s(l){l.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",r),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",r),document.removeEventListener("keydown",s)}},[n]),k.jsxs("div",{className:"sidebar-help-menu",ref:o,children:[k.jsx("button",{"aria-expanded":n,"aria-haspopup":"menu","aria-label":"Open docs and help menu",className:`sidebar-icon sidebar-help-trigger ${t?"active":""}`,"data-tooltip":"Help",onClick:()=>a(r=>!r),type:"button",children:k.jsx(Y6,{size:17})}),n?k.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:_V.map(r=>{const s=r.icon,l=k.jsxs(k.Fragment,{children:[k.jsx(s,{size:15}),k.jsx("span",{children:r.label})]});return r.destination==="walkthroughs"?k.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:l},r.label):k.jsx("a",{className:"sidebar-help-item",href:r.url,onClick:m=>{m.preventDefault(),a(!1),RV(r.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:l},r.label)})}):null]})}async function RV(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const _ee=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],yf=[{value:"chat",label:"Chat",description:"Chat and complete tasks"},{value:"models",label:"Models",description:"Evaluate, train, and serve models"},{value:"console",label:"Console",description:"Manage models and workspace resources"}];function fC(e){return e==="chat"?"New chat":"New task"}const _h=["get-started","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],PV={"get-started":"Get started",models:"Models",datasets:"Datasets",graders:"Graders",experiments:"Experiments",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},AV={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},TV={datasets:["tasks","experiments","graders","versions"],graders:["overview","checks","usage","versions"],experiments:["overview","cases","compare","configuration"],tasksets:["overview","tasks","reward","attempts","releases"],rewards:["definition","usage","evidence"],evaluations:["overview","comparison","activity"],runs:["details","metrics","evaluation","rollouts","activity","artifacts"],versions:["overview","metrics","evaluation","rollouts","activity","artifacts"]};function Za(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?Za("labeling",t,{...n,collection:"default"}):{page:e,modelId:["get-started","datasets","graders","experiments"].includes(e)?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function Wv(e){const t=e.pathname.split("/").filter(Boolean);if(t[0]!=="models"&&t[0]!=="console")return null;let n;try{n=t.slice(1).map(decodeURIComponent)}catch{return null}if(n.some(E=>!E.trim()||E.length>2e3||E.includes("\0")))return null;const a=n[0]&&!_h.includes(n[0])?n.shift():null;if(a&&(a.length>500||["projects","scorers"].includes(a)))return null;n[0]==="runs"&&n[1]==="evaluations"&&n.splice(0,2,"evaluations","results"),n[0]==="runs"&&n[1]==="comparisons"&&n.splice(0,2,"evaluations","comparisons");const o=n.shift(),r=o??"models";if(!_h.includes(r)||o==="models"||a&&r==="get-started")return null;let s=r==="evaluations"?"results":"default";if(AV[r]?.includes(n[0]))s=n.shift();else if(r==="evaluations"&&n.length)return null;if(r==="experiments"&&n[0]==="history")return null;const l=n.shift()??null,m=n.shift()??null;if(n.length||m&&!l||(r==="models"||r==="get-started")&&l)return null;if(s==="drafts"||s==="new"){if(!l||m)return null}else if(s!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(s)){if(m)return null}else if(m&&!TV[r]?.includes(m))return null}if(r==="serving"&&m)return null;const d=new URLSearchParams(e.search??"");if([...d.keys()].some(E=>!["model","q","after","source","project","pass","dataset","revision","hash","sort","location"].includes(E))||[...d.keys()].some(E=>d.getAll(E).length!==1))return null;const h=d.get("sort");if(h!==null&&(r!=="datasets"||!["id","name","updated"].includes(h)))return null;const g=d.has("revision")?Number(d.get("revision")):void 0,y=d.get("hash")??void 0,w=["datasets","graders"].includes(r);if((g!==void 0||y!==void 0)&&(!l||!w||!Number.isSafeInteger(g)||g<=0||!/^[a-f0-9]{64}$/.test(y??"")))return null;const _=d.get("source");if(_!==null&&(r!=="labeling"&&(r!=="evaluations"||s!=="review")||!_.trim()||_.length>500)||d.has("dataset")&&(r!=="datasets"||!l||d.get("dataset")!=="release"))return null;const P=["datasets","graders","experiments"].includes(r),M=d.get("location");if(M!==null&&(!P||!["local","hosted"].includes(M))||t[0]==="console"&&!P)return null;const C=d.get("project")==="all"?null:d.get("project"),$=d.get("pass");if([C,$].some(E=>E!==null&&(!E.trim()||E.length>240))||!P&&(C||$)||r!=="experiments"&&$||P&&a||$&&!l)return null;const O=d.get("model");if(P&&O!==null||a&&O&&a!==O)return null;const j=a??O;if(r==="get-started"&&d.size!==0)return null;const x=d.get("q")??"",R=d.get("after");return j!==null&&(!j.trim()||j.length>500)||x.length>1e3||R!==null&&(!R.trim()||R.length>2e3)?null:Za(r,j,{collection:s,resourceId:l,detailTab:m,query:x,after:R,...M?{executionLocation:M}:{},...h?{sort:h}:{},...g!==void 0?{revision:g,contentHash:y}:{},...d.get("dataset")==="release"?{datasetKind:"release"}:{},...t[0]==="console"?{area:"console"}:{},...P?{...d.has("project")?{projectId:C}:{},...d.has("pass")?{passId:$}:{}}:{},..._!==null?{sourceId:_}:{}})}function mm(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return mm(Za("labeling",e.modelId,{collection:"default",resourceId:e.resourceId,sourceId:e.sourceId,query:e.query,after:e.after}));e.page==="evaluations"?t.push("runs",e.collection==="comparisons"?"comparisons":"evaluations"):(e.page!=="models"&&t.push(e.page),e.collection!=="default"&&t.push(e.collection)),e.resourceId&&t.push(encodeURIComponent(e.resourceId)),e.resourceId&&e.detailTab&&t.push(encodeURIComponent(e.detailTab));const n=new URLSearchParams;return e.executionLocation&&n.set("location",e.executionLocation),e.projectId?n.set("project",e.projectId):e.projectId===null&&["datasets","graders","experiments"].includes(e.page)&&n.set("project","all"),e.page==="datasets"&&e.resourceId&&e.datasetKind==="release"&&n.set("dataset","release"),e.page==="datasets"&&e.sort&&n.set("sort",e.sort),e.revision!==void 0&&e.contentHash&&e.resourceId&&["datasets","graders"].includes(e.page)&&(n.set("revision",String(e.revision)),n.set("hash",e.contentHash)),e.passId&&n.set("pass",e.passId),e.query&&n.set("q",e.query),e.after&&n.set("after",e.after),(e.page==="labeling"||e.page==="evaluations"&&e.collection==="review")&&e.sourceId&&n.set("source",e.sourceId),`${t.join("/")}${n.size?`?${n}`:""}`}function EV(e,t){return Za(e.page,t,{...e.area?{area:e.area}:{},...["datasets","graders","experiments"].includes(e.page)&&e.projectId!==void 0?{projectId:e.projectId}:{},collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function Cee(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const pu=new Set,Ch=new Set,MV=new Set(["account","notifications","harness","harness-refiner","harness-continuous-review","harness-contents","harness-releases","profile","skills","configuration","context","training","subagents","editor","providers","dataset-storage","remote","usage","personalization","diagnostics"]),Rh={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let Ph=!1,Ah="",Ld=null,hC=null,oc="",Ka=0,vl=null,Nl=!1,Sf=null,Hd=!1;function Gv(e){const t=Wv(e);if(t)return{kind:"models",route:t};const n=e.pathname.split("/").filter(Boolean);if(n[0]==="models"||n[0]==="console")return{kind:"models_unavailable",pathname:e.pathname,search:e.search??""};if(n[0]==="settings"&&n.length===2&&MV.has(n[1])){const o=Jv(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...o?{returnTo:o}:{}}}if(n[0]==="chat"&&n.length<=2)try{return{kind:"chat",sessionId:n[1]&&n[1]!=="new"?decodeURIComponent(n[1]):null}}catch{return null}const a=Object.keys(Rh).find(o=>Rh[o]===e.pathname);return a?{kind:"view",view:a}:null}function gC(e){if(e.kind==="models")return mm(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=Jv(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":Rh[e.view]}function jV(e){const t=e?.kind==="settings"?Jv(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=Wv(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function Jv(e){if(!e||e.length>6e3||!["/models","/console"].some(a=>e.startsWith(a))||e.startsWith("//"))return null;const t=new URL(e,"https://local.openpond.invalid");if(t.origin!=="https://local.openpond.invalid"||t.hash)return null;const n=Wv(t);return n?mm(n):null}function Nc(){return`${window.location.pathname}${window.location.search}`}function Zv(){if(typeof window>"u")return;const e=Ph?oc:Nc();e!==Ah&&(Ah=e,Ld=Gv(new URL(e,window.location.origin)),hC=Ld?.kind==="models"?Ld.route:null)}function vC(){Ah="",Zv();for(const e of Ch)e()}async function Yv(e){if(Hd)return!1;Hd=!0;try{for(const t of[...pu].reverse())if(!await t(e))return!1;return!0}finally{Hd=!1}}function Qv(e){return{...window.history.state,openpondNavigationIndex:e}}async function OV(){const e=Nc(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:Ka-1;if(vl&&t===Ka){const a=vl;vl=null,a();return}if(Sf===t||pu.size===0){Sf=null,oc=e,Ka=t,window.history.replaceState(Qv(Ka),"",e),vC();return}if(t===Ka)return;if(Nl||Hd){vl??=()=>{},window.history.go(Ka-t);return}Nl=!0;const n=t-Ka;try{await new Promise(a=>{vl=a,window.history.go(-n)}),await Yv(e)&&(Sf=t,window.history.go(n))}finally{Nl=!1}}function Xv(){if(Ph||typeof window>"u")return;const e=Gv(window.location);oc=e?gC(e):Nc(),Ka=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(Qv(Ka),"",oc),window.addEventListener("popstate",OV),Ph=!0}function bC(e){return Ch.add(e),Xv(),()=>{Ch.delete(e)}}function Ree(e){return pu.add(e),Xv(),()=>{pu.delete(e)}}async function Pee(e){!Nl&&await Yv(Nc())&&e()}function $V(){return v.useSyncExternalStore(bC,()=>(Zv(),hC),()=>null)}function NV(){return v.useSyncExternalStore(bC,()=>(Zv(),Ld),()=>null)}async function Xt(e,t="push"){if(typeof window>"u"||(Xv(),Nl))return!1;if(e.kind==="settings"&&!e.returnTo){const a=Gv(window.location),o=a?.kind==="models"?mm(a.route):a?.kind==="settings"?a.returnTo:void 0;o&&(e={...e,returnTo:o})}const n=gC(e);return Nc()===n?!0:await Yv(n)?(t==="push"&&Ka++,window.history[t==="replace"?"replaceState":"pushState"](Qv(Ka),"",n),oc=n,vC(),!0):!1}function gs(e,t="push"){return Xt({kind:"models",route:e},t)}function DV({experience:e="work",beginNewChat:t}){return k.jsx("div",{className:"sidebar-new-task",children:k.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{Xt({kind:"chat",sessionId:null}),t(null)},children:[k.jsx(dm,{size:18}),k.jsx("span",{children:fC(e)})]})})}function LV({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:o,setView:r,view:s,modelProjects:l=[],modelTrainingActivityByProjectId:m={}}){const d=$V(),h=d?.modelId??null,g=d?.page??"models";function y(){n(null),a(null),o(null),t(null)}async function w(C){await gs(Za(C,["datasets","graders","experiments"].includes(C)?null:h,{...e==="console"?{area:"console"}:{},...d?.projectId!==void 0?{projectId:d.projectId}:{}}))&&(y(),r("labs"))}async function _(C){await gs(EV(d??Za(),C||null))&&(y(),r("labs"))}async function P(C){await Xt({kind:"view",view:C})&&(y(),r(C))}const M=h?m[h]??null:null;return k.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e!=="chat"?k.jsxs(k.Fragment,{children:[["datasets","graders","experiments"].includes(g)?null:k.jsxs("div",{className:"sidebar-model-project-picker",children:[k.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),k.jsx(IV,{label:"Model",searchable:l.length>8,value:h??"",options:[{value:"",label:"All models"},...h&&!l.some(C=>C.id===h)?[{value:h,label:"Unavailable model",disabled:!0}]:[],...l.map(C=>({value:C.id,label:C.name}))],onChange:C=>{_(C)}})]}),_h.filter(C=>e==="console"?["datasets","graders","experiments"].includes(C):C!=="tasksets"&&C!=="evaluations").map(C=>{const $={"get-started":vd,models:g6,datasets:vd,graders:U0,experiments:Dd,tasks:vd,tasksets:vd,labeling:Dd,rewards:U0,evaluations:Dd,runs:rC,versions:K6,serving:lm}[C];return k.jsxs("button",{className:`nav-command ${s==="labs"&&(g===C||C==="runs"&&g==="evaluations")?"active":""}`,"aria-current":s==="labs"&&(g===C||C==="runs"&&g==="evaluations")?"page":void 0,type:"button",onClick:()=>{w(C)},children:[k.jsx($,{size:16}),k.jsx("span",{children:PV[C]}),C==="runs"&&M?k.jsx("span",{className:"sidebar-running-dot","aria-label":M.label}):null]},C)})]}):null,e==="chat"?k.jsxs(k.Fragment,{children:[k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{P("scheduled")},children:[k.jsx(C6,{size:18}),k.jsx("span",{children:"Workflows"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{P("outputs")},children:[k.jsx(q6,{size:18}),k.jsx("span",{children:"Outputs"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{P("apps")},children:[k.jsx(mC,{size:18}),k.jsx("span",{children:"Apps"})]}),k.jsxs("button",{className:`nav-command nav-command-prominent ${s==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{P("projects")},children:[k.jsx(lC,{size:18}),k.jsx("span",{children:"Projects"})]})]}):null]})}function HV({setSectionMenuOpen:e,setSelectedAppId:t,setSelectedProjectId:n,setSelectedSessionId:a,setView:o,view:r}){function s(){t(null),n(null),a(null),e(null),o("get-started"),Xt({kind:"view",view:"get-started"})}return k.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:k.jsx(CV,{onOpenWalkthroughs:s,walkthroughsActive:r==="get-started"})})}const yC=Mp({chatMode:b(["chat","work"]).optional(),notificationMode:b(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:A().optional(),sidebarVisibility:Mp({showCodexChats:A(),onlyRunningTasks:A()}).optional(),scheduledWorkView:b(["calendar","list"]).optional(),editorControlsVisible:A().optional(),voiceNoticeAcknowledged:A().optional(),lessonProgress:oe(i().min(1).max(200),Mp({completed:A(),currentTime:u().finite().nonnegative(),duration:u().finite().positive(),updatedAt:u().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),Th={"openpond:last-chat-task-mode":"chatMode","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"},Eh=new Set;let Dl=null,Xo=null,Ga={},ic={},xf=!1,Ud=0,vs=null,z0=0;const UV="openpond-client-choices-changed";function eb(){Eh.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(UV))}function qV(){return vs}function zV(e){return Eh.add(e),()=>{Eh.delete(e)}}function Dc(e){const t=v.useRef(e);t.current=e,v.useEffect(()=>zV(()=>t.current()),[])}async function B0(e){const t=++z0,n=await z(e,"/v1/configuration");if(n.clientState?.revision===null){const o=BV();if(Object.keys(o.patch).length){n.clientState=await z(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:o.patch,importOnly:!0})});for(const r of o.keys)try{window.localStorage.removeItem(r)}catch{}}}if(t!==z0)return;const a=Dl?.serverUrl!==e.serverUrl||Dl?.token!==e.token||Xo?.owner!==n.clientState?.owner;a&&(Ud++,Ga={},ic={},vs=null),Dl=e,(a||(n.clientState?.revision??0)>=(Xo?.revision??0))&&(Xo=n.clientState),eb()}async function tb(){if(xf||!Dl||!Xo||!Object.keys(Ga).length)return;xf=!0;const e=Ga,t=Dl,n=Xo.owner,a=Ud;Ga={},ic=e;try{const o=await z(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===Ud&&(Xo=o,vs=null)}catch(o){a===Ud&&(Ga={...e,...Ga},vs=`Preference changes have not been saved. ${o instanceof Error?o.message:String(o)}`)}finally{ic={},xf=!1,eb(),!vs&&Object.keys(Ga).length&&tb()}}function Aee(){vs=null,tb()}const Lc={getItem(e){const t=Th[e];if(!t)return null;const n={...Xo?.value,...ic,...Ga}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!Xo)return;const n=Th[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const o=yC.parse({[n]:a});JSON.stringify({...Xo.value,...ic,...Ga}[n])!==JSON.stringify(o[n])&&(Ga={...Ga,...o},eb(),tb())}};function BV(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(Th))try{const o=window.localStorage.getItem(n);if(o===null)continue;let r;try{r=JSON.parse(o)}catch{r=o}const s=yC.safeParse({[a]:r});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const qd=5,En=15,Mh=10,Mt={defaultChatProvider:ir,subagents:TO(),codexPermissionMode:Ig,codexReasoningEffort:_g,openPondCommandAccessMode:ju,defaultBranchPrefix:"feat/",defaultNewProjectDirectory:"",advancedWorkspaceControls:!1,steerActiveResponses:!0,contextCompaction:{autoEnabled:!0,triggerPercent:85,summaryModel:"same_model"},training:{defaultModelRef:null,creationMode:"customize",autoApproveEvidence:!1},sidebarWidth:332,diffPanelWidth:560,sidebarSectionsCollapsed:{pinned:!1,projects:!1,cloudProjects:!1,chats:!1,savedForLater:!0},editor:{languageServers:"auto",diagnosticsWhileEditing:!0,checkOnSave:!0,languages:{typescript:{mode:"auto",customCommand:""},python:{mode:"auto",customCommand:""},rust:{mode:"auto",customCommand:""}}}},Tee={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},SC=[{value:"accounts/fireworks/models/deepseek-v4-pro",label:"DeepSeek V4 Pro",description:"reasoning"},{value:"accounts/fireworks/models/kimi-k3",label:"Kimi K3",description:"reasoning"},{value:"accounts/fireworks/models/glm-5p3",label:"GLM-5.3",description:"reasoning"},{value:"accounts/fireworks/models/deepseek-v4-flash",label:"DeepSeek V4 Flash",description:"reasoning"},{value:"accounts/fireworks/models/nemotron-lightning-3p5-30b-a3b",label:"Nemotron Lightning 3.5 30B A3B",description:"reasoning"},{value:"accounts/fireworks/models/minimax-m3",label:"MiniMax M3",description:"reasoning"}],kf=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],FV=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],VV=["openpond","codex",...FV],xC=new Set(VV),kC=[{value:wg,label:"GPT-5.6 Sol"},{value:"gpt-5.6-terra",label:"GPT-5.6 Terra"},{value:"gpt-5.6-luna",label:"GPT-5.6 Luna"},{value:"gpt-5.5",label:"GPT-5.5"},{value:"gpt-5.4",label:"GPT-5.4"},{value:"gpt-5.4-mini",label:"GPT-5.4 Mini"},{value:"gpt-5.3-codex",label:"GPT-5.3 Codex"},{value:"gpt-5.3-codex-spark",label:"GPT-5.3 Codex Spark"},{value:"gpt-5.2",label:"GPT-5.2"}],Eee=[{value:"default",label:"Default permissions",shortLabel:"Default",description:"Workspace sandbox; asks before crossing boundaries."},{value:"auto-review",label:"Auto-review",description:"Workspace sandbox; reviewer handles eligible approvals."},{value:"full-access",label:"Full access",description:"No sandbox or approval prompts."}],jh=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],KV=[{value:"off",label:"Off"},...jh,{value:"max",label:"Max"}],Mee=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],jee=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],Oee=[{value:"auto",label:"Auto",description:"Find the local executable automatically."},{value:"disabled",label:"Disabled",description:"Do not start this language server."},{value:"custom",label:"Custom",description:"Use a specific executable path or command name."}];function nb(e){return e.kind==="local"}function WV(e){return e.kind==="cloud"}function St(e,t){return`${e}:${t}`}function wC(e){const t=e?.trim();if(!t)return null;const n=t.indexOf(":");if(n<=0)return{kind:"local",id:t};const a=t.slice(0,n),o=t.slice(n+1);return(a==="local"||a==="cloud")&&o?{kind:a,id:o}:{kind:"local",id:t}}function tr(e){return`${e.type}:${e.id}`}function fu(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function hu(e,t,n,a="before"){if(t===n)return e;const o=e.filter(s=>s!==t),r=o.indexOf(n);return r===-1?e:(o.splice(a==="after"?r+1:r,0,t),o)}function F0(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function GV(e,t){if(!t)return e;const n=new Map(e.map(r=>[r.key,r])),a=t.map(r=>n.get(r)).filter(r=>!!r),o=new Set(a.map(r=>r.key));return[...a,...e.filter(r=>!o.has(r.key))]}function ab(e,t){return e?.statuses?.[t]??null}function IC(e,t){return e?.providers?.[t]??null}function ob(e,t){return e?.modelCaches?.[t]??null}function JV(e){const t=[e.contextWindow?`${Math.round(e.contextWindow/1e3)}K context`:"",e.capabilities.reasoning?"reasoning":"",e.source].filter(Boolean);return{value:e.id,label:e.displayName||e.id,description:t.join(" · ")||void 0}}function ZV(e){return e==="openpond"?SC:e==="codex"||e==="openai"?kC:[]}function YV(e){const t=new Set,n=[];for(const a of e)!a.value||t.has(a.value)||(t.add(a.value),n.push(a));return n}function $ee(e){return xC.has(e)}function Oh(e,t={}){if(!e)return t.localOnly,kf;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,o=[];for(const r of mg){if(!xC.has(r)||t.localOnly&&r==="openpond")continue;const s=ab(e,r);s&&(!n&&(r==="codex"&&!s.available&&!s.credential.connected||r!=="openpond"&&r!=="codex"&&!s.enabled)||a&&r!=="openpond"&&!s.enabled||a&&r==="codex"&&!s.available&&!s.credential.connected||o.push({value:r,label:r==="openpond"?"OpenPond Chat":s.displayName,description:r==="openpond"?void 0:s.available?"Connected":s.credential.connected?"Configured":s.routing.localByok?"Set up key":s.enabled?"Enabled":void 0}))}return o.length>0?o:kf}function rc(e,t){const a=(ob(t,e)?.models??[]).filter(l=>e!=="openpond"||l.id!==ks).map(JV),o=IC(t,e),r=[...o?.modelOverrides??[],o?.defaultModel].filter(l=>!!l?.trim()&&(e!=="openpond"||l!==ks)).map(l=>({value:l,label:l})),s=e==="openpond"&&a.length>0?[]:ZV(e);return YV([...a,...r,...s])}function _C(e,t,n){if(e!=="openpond")return jh;const a=ob(n,e)?.models.find(r=>r.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return jh;const o=new Set(a.reasoningEfforts);return KV.filter(r=>o.has(r.value))}function QV(e,t,n){const a=_C(e,t,n),o=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(r=>r.value===o)?o:a[0]?.value??"high"}function XV(e,t,n,a){return _C(e,t,a).some(o=>o.value===n)?n:QV(e,t,a)}function eK(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const o=ob(n,e)?.models.find(r=>r.id===a);return o?!!o.capabilities.reasoning:rc(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function gu(e,t){const n=IC(t,e)?.defaultModel?.trim();if(n)return n;const a=ab(t,e)?.defaultModel?.trim();if(a)return a;const o=rc(e,t)[0]?.value?.trim();return o||(e==="codex"?wg:e==="openpond"?ks:"")}function ji(e,t,n){const a=t?.trim();if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return wg;const o=rc(e,n);return a&&o.some(r=>r.value===a)||a&&e!=="codex"&&o.length===0&&!n?a:gu(e,n)}function CC(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:ji(n,e.modelRef?.modelId,t)}}function ib(e,t,n){return ji(e,t,n)||void 0}function Fa(e,t,n){const a=ib(e,t,n);return a?{providerId:e,modelId:a}:void 0}function V0(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function Ca(e){const t=e?.defaultChatProvider??Mt.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:ji(t,e?.defaultChatModel),subagents:zl.parse(e?.subagents??Mt.subagents),codexPermissionMode:e?.codexPermissionMode??Mt.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Mt.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Mt.openPondCommandAccessMode,defaultBranchPrefix:RC(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Mt.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Mt.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Mt.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Mt.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Mt.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Mt.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Mt.training.defaultModelRef,creationMode:e?.training?.creationMode??Mt.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Mt.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Mt.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Mt.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Mt.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Mt.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Mt.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Mt.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Mt.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Mt.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Mt.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Mt.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Mt.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Mt.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Mt.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Mt.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Mt.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Mt.editor.languages.rust.customCommand}}}}}function RC(e){const t=e?.trim()??Mt.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(o=>o.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function Nee(e,t){return e==="openpond"?"OpenPond Chat":ab(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function Dee(e,t,n){if(n){const a=rc(n,t).find(o=>o.value===e);if(a)return a.label}if(t)for(const a of mg){const o=rc(a,t).find(r=>r.value===e);if(o)return o.label}return[...SC,...kC].find(a=>a.value===e)?.label??e}function tK(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function nK(e){return e.experience==="chat"?"Chat":"Work"}const rb="taskDraft";function PC(e){if(e?.experience!=="work")return null;const t=e.metadata?.[rb];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function sc(e){return PC(e)!==null}function aK(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function wf(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[rb]:a}}function oK(e){const t={...e??{}};return delete t[rb],t}function ss(e){const t=bd(e.metadata?.trainingTasksetId)??bd(e.metadata?.tasksetId);return t?{id:t,name:bd(e.metadata?.trainingTasksetName)??bd(e.metadata?.tasksetName)??iK(t)}:null}function iK(e){const n=e.replace(/[-_][a-f0-9]{8,}$/i,"").replace(/^(?:benchmark[-_])?taskset[-_]/i,"").replace(/^benchmark[-_]/i,"").split(/[-_]+/).filter(Boolean);return n.length===0?"Taskset":n.map(a=>/^[A-Z0-9]{2,}$/.test(a)?a:`${a.charAt(0).toUpperCase()}${a.slice(1)}`).join(" ")}function bd(e){return typeof e=="string"&&e.trim()?e.trim():null}const rK="codex_history_";function qt(e){return!!e?.startsWith(rK)}function AC(e){const t=[],n=new Set;for(const a of e)for(const o of[a.workspacePath,a.path]){const r=pm(o);if(!r)continue;const s=`${a.id}:${r}`;n.has(s)||(n.add(s),t.push({projectId:a.id,path:r}))}return t.sort((a,o)=>o.path.length-a.path.length)}function sK(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return e.localProjectId;if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return e.workspaceId;if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=TC(e.cwd,n);if(r)return r}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!EC(e))return null;const o=pm(e.cwd);if(!o)return null;for(const r of n)if(sb(o,r.path))return r.projectId;return null}function K0(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return St("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return St("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=TC(e.cwd,n);if(r)return St("local",r)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return St("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!EC(e))return null;const o=pm(e.cwd);if(!o)return null;for(const r of n)if(sb(o,r.path))return St("local",r.projectId);return null}function TC(e,t){const n=pm(e);if(!n)return null;for(const a of t)if(sb(n,a.path))return a.projectId;return null}function EC(e){return e.workspaceKind==="local_project"||e.provider==="codex"||qt(e.id)}function pm(e){const t=e?.trim();if(!t)return null;let n=t.replace(/^file:\/\/+/i,"/").replace(/\\/g,"/").replace(/\/+/g,"/");return/^[a-z]:/i.test(n)&&(n=n[0].toUpperCase()+n.slice(1)),n=n.replace(/\/+$/g,""),n||"/"}function sb(e,t){const n=W0(e),a=W0(t);return n===a||n.startsWith(`${a}/`)}function W0(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const G0=[{value:"active",label:"Active"},{value:"in_progress",label:"In progress"},{value:"pinned",label:"Pinned"},{value:"saved_for_later",label:"Save for later"},{value:"tasksets",label:"Tasksets"},{value:"done",label:"Done"},{value:"all",label:"All"}],lK=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function J0(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(o=>!ss(o)));else if(e.filter==="all")t.push(...e.activeSessions.filter(o=>!ss(o)),...e.doneSessions.filter(o=>!ss(o)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(o=>Z0(o,e.selectedTasksetId)),...e.doneSessions.filter(o=>Z0(o,e.selectedTasksetId)));else for(const o of e.activeSessions)ss(o)||(e.filter==="active"?o.savedForLater||t.push(o):e.filter==="in_progress"?!o.savedForLater&&e.inProgressSessionIds.has(o.id)&&t.push(o):e.filter==="pinned"?o.pinned&&!o.savedForLater&&t.push(o):e.filter==="saved_for_later"&&o.savedForLater&&t.push(o));const n=t.filter(o=>zd(o,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((o,r)=>[o,r])):null;return e.sort==="recent"?n.sort((o,r)=>Q0(o,r,a)):n.sort((o,r)=>{const s=a?.get(o.id),l=a?.get(r.id);if(s!==void 0||l!==void 0){if(s===void 0)return 1;if(l===void 0)return-1;if(s!==l)return s-l}return o.order!==r.order?o.order-r.order:Q0(o,r)})}function zd(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||qt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Z0(e,t){const n=ss(e);return!!(n&&(!t||n.id===t))}function cK(e,t){switch(e){case"active":return`No active ${t}`;case"in_progress":return"No work in progress";case"pinned":return`No pinned ${t}`;case"saved_for_later":return"Nothing saved for later";case"tasksets":return"No Taskset chats yet";case"done":return`No done ${t}`;case"all":return`No ${t}`}}function Y0(e,t,n){const a=new Set(t);let o=0;return e.map(r=>{if(!a.has(r))return r;const s=n[o];return o+=1,s??r})}function Q0(e,t,n=null){const a=Ll(e),o=Ll(t);if(a!==o)return a?-1:1;if(a&&o){const s=n?.get(e.id),l=n?.get(t.id);if(s!==void 0||l!==void 0){if(s===void 0)return 1;if(l===void 0)return-1;if(s!==l)return s-l}if(e.order!==t.order)return e.order-t.order}const r=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return r!==0?r:e.title.localeCompare(t.title)}function Ll(e){return e.pinned&&!e.savedForLater&&!e.archived}const yd={showCodexChats:!0,onlyRunningTasks:!1},MC="openpond.sidebar-task-visibility.v1";function X0(e=jC()){try{const t=e?.getItem(MC);if(!t)return yd;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:yd.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:yd.onlyRunningTasks}}catch{return yd}}function eS(e,t=jC()){try{t?.setItem(MC,JSON.stringify(e))}catch{}}function jC(){return typeof window>"u"?null:Lc}function OC(e){return`${e.kind}:${e.id}`}function lc(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function dK(e){return{kind:"session",id:e}}function uK(e){return{kind:"project",id:e}}function mK(e){return{kind:"draft",id:e}}function pK(e){return e.selectedSessionId?dK(e.selectedSessionId):e.selectedProjectId?uK(e.selectedProjectId):mK(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function fK(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(lc(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>lc(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function Lee(e,t){return e.filter(n=>lc(n.scope,t))}function Hee(e,t){return!!(e&&lc(e.scope,t))}function hK(e){const t={};for(const n of e){const a=OC(n.scope),o=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};o.tabCount+=1,n.commandStatus==="running"&&(o.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(o.failedCount+=1),n.lastExitCode!==null&&(o.lastExitCode=n.lastExitCode),o.status=vK(o.status,n.status,n.commandStatus),t[a]=o}return t}function gK(e){return!e||e.status==="none"||e.tabCount===0?null:e.status==="running"?{status:"running",label:"Terminal running"}:e.status==="failed"?{status:"failed",label:"Terminal last command failed"}:e.status==="success"?{status:"success",label:"Terminal last command succeeded"}:e.status==="idle"?{status:"idle",label:"Terminal idle"}:{status:"unknown",label:"Terminal open"}}function vK(e,t,n){return n==="running"?"running":e==="running"?e:n==="failed"||t==="error"?"failed":e==="failed"?e:n==="success"?e==="none"||e==="unknown"||e==="idle"?"success":e:n==="idle"?e==="none"||e==="unknown"?"idle":e:e==="none"?"unknown":e}function $C(e,t){if(!e)return t?.path??"Use files on this machine";if(e.error)return"status unavailable";if(!e.initialized)return"not checked out";const a=[e.currentBranch??t?.branch??e.defaultBranch??"no branch"],o=yK(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return o?a.push(o):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(Ri("ahead",e.ahead)),e.behind>0&&a.push(Ri("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(Ri("ahead",e.ahead)),e.behind>0&&a.push(Ri("behind",e.behind))),e.changedFilesCount>0?a.push(`${e.changedFilesCount} changed`):e.dirty&&a.push("dirty"),e.untrackedFilesCount>0&&a.push(`${e.untrackedFilesCount} untracked`),a.length===1&&a.push("synced"),a.join(" / ")}function NC(e,t,n,a={}){const o=e?.linkedSandboxProject??null;if(!o?.projectId&&!t)return"upload required";if(o?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const r=o?.defaultBranch??t?.defaultBranch??"main",s=o?.manifestHash??null,l=e?.sandboxTemplate?.manifestHash??null,m=o?.syncedAt??t?.syncedAt??null,d=!!(s&&l&&s!==l),h=!!(o?.projectId&&n?.headCommit&&!o.lastUploadedCommit),g=SK(n);return g?`${r} / ${g}`:h?`${r} / upload required`:`${r} / ${d||!m?"needs sync":"setup ready"}`}function bK(e,t,n={}){if(!e)return"select a local project";if(e.linkedSandboxProject?.projectId&&n.cloudLinkTrusted===!1)return"sync to this account";if(!t)return e.linkedSandboxProject?"sync source to cloud":"push local source to cloud";if(t.error)return"repo status unavailable";if(!t.initialized)return"local repo unavailable";const a=[],o=t.aheadOfLinkedSource>0?t.aheadOfLinkedSource:t.ahead;return e.linkedSandboxProject?.projectId||a.push("upload required"),e.linkedSandboxProject?.projectId&&t.headCommit&&!e.linkedSandboxProject.lastUploadedCommit&&a.push("upload required"),o>0&&a.push(DC(o)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&o===0&&a.push("source changed"),t.changedFilesCount>0&&a.push(`${t.changedFilesCount} changed file${t.changedFilesCount===1?"":"s"}`),t.untrackedFilesCount>0&&a.push(`${t.untrackedFilesCount} untracked skipped`),a.length>0?a.join(" / "):"nothing to upload"}function yK(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?Ri("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?Ri("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function SK(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?Ri("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?Ri("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function Ri(e,t){return`${e} by ${DC(t)}`}function DC(e){return`${e} commit${e===1?"":"s"}`}function xK({size:e=14,className:t}){return k.jsxs("svg",{className:["lucide lucide-cloud-upload",t??""].filter(Boolean).join(" "),xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[k.jsx("path",{d:"M12 13v8"}),k.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),k.jsx("path",{d:"m8 17 4-4 4 4"})]})}function LC({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:o=15}){const r=e==="cloud"?"cloud":n?"folder-open":"folder";return k.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:k.jsxs("svg",{className:`lucide lucide-${r} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:o,height:o,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?k.jsx(IK,{}):n?k.jsx(wK,{}):k.jsx(kK,{}),t&&e==="local"?k.jsx(_K,{}):null]})})}function kK(){return k.jsx("path",{className:"project-kind-icon-base",d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"})}function wK(){return k.jsx("path",{className:"project-kind-icon-base",d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"})}function IK(){return k.jsx("path",{className:"project-kind-icon-base",d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"})}function _K(){return k.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[k.jsx("circle",{cx:"18",cy:"17",r:"5"}),k.jsx("path",{d:"M20.4 18.6h-4.2a2.2 2.2 0 1 1 2.08-2.9h.88a1.45 1.45 0 1 1 1.24 2.9Z"})]})}var vu=PP();function CK({title:e,pinned:t,savedForLater:n,archived:a,onRename:o,onTogglePin:r,onToggleSaveForLater:s,onDockRight:l,onArchive:m}){const d=v.useRef(null),h=v.useRef(null),[g,y]=v.useState(null),w=[...o?[{label:"Rename",Icon:dm,action:o}]:[],{label:t?"Unpin":"Pin",Icon:t?Vv:Fv,action:r},...s?[{label:n?"Return to active":"Save for later",Icon:n?iC:oC,action:s}]:[],...l?[{label:"Open in right panel",Icon:Ih,action:l}]:[],{label:a?"Reopen":"Mark done",Icon:a?b6:Uo,action:m}];function _(P=!1){y(null),P&&d.current?.focus()}return v.useEffect(()=>{if(!g)return;h.current?.querySelector("button")?.focus();const P=C=>{!h.current?.contains(C.target)&&!d.current?.contains(C.target)&&y(null)},M=()=>y(null);return document.addEventListener("pointerdown",P),window.addEventListener("resize",M),()=>{document.removeEventListener("pointerdown",P),window.removeEventListener("resize",M)}},[g]),k.jsxs(k.Fragment,{children:[k.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${g?" is-open":""}`,children:k.jsx("button",{ref:d,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!g,draggable:!1,onDoubleClick:P=>P.stopPropagation(),onClick:P=>{if(P.stopPropagation(),g){_(!0);return}const M=P.currentTarget.getBoundingClientRect();y({left:Math.max(8,Math.min(M.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(M.bottom+4,window.innerHeight-(w.length*32+17)))})},children:k.jsx(Oc,{size:16})})}),g&&vu.createPortal(k.jsx("div",{ref:h,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:g,onClick:P=>P.stopPropagation(),onDoubleClick:P=>P.stopPropagation(),onBlur:P=>{P.currentTarget.contains(P.relatedTarget)||_()},onKeyDown:P=>{P.stopPropagation();const M=Array.from(P.currentTarget.querySelectorAll("button")),C=M.indexOf(document.activeElement);if(P.key==="Escape"&&(P.preventDefault(),_(!0)),["ArrowDown","ArrowUp","Home","End"].includes(P.key)){P.preventDefault();const $=P.key==="Home"?0:P.key==="End"?M.length-1:(C+(P.key==="ArrowDown"?1:-1)+M.length)%M.length;M[$]?.focus()}},children:w.map(({label:P,Icon:M,action:C},$)=>k.jsxs("button",{type:"button",role:"menuitem",className:$===w.length-1?"task-menu-done":void 0,onClick:()=>{_(!0),C()},children:[k.jsx(M,{size:15}),P]},P))}),document.body)]})}function RK({session:e,onSave:t,onClose:n}){const[a,o]=v.useState(e.title),r=v.useRef(null);v.useEffect(()=>{const m=r.current;m&&(m.focus(),m.select())},[]),v.useEffect(()=>{function m(d){d.key==="Escape"&&n()}return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);function s(){const m=a.trim();m&&(t(m),n())}function l(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),s())}return k.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:k.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[k.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),k.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>o(m.target.value),onKeyDown:l,"aria-label":"Chat title"}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),k.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const PK=24;function AK({title:e}){const t=v.useRef(e),[n,a]=v.useState(e);return v.useEffect(()=>{const o=t.current;if(t.current=e,!e){a("");return}if(o||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const r=Array.from(e);let s=0;a("");const l=window.setInterval(()=>{s+=1,a(r.slice(0,s).join("")),s>=r.length&&window.clearInterval(l)},PK);return()=>window.clearInterval(l)},[e]),k.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const TK=2650,EK=304,MK=260,jK=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),OK=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),$K=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function NK(){return{animationDelay:`${-(Date.now()%TK)}ms`}}function DK(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),o=a>2;t.dataset.overflowing=String(o),t.style.setProperty("--sidebar-title-ticker-distance",`${-a}px`),t.style.setProperty("--sidebar-title-ticker-duration",`${Math.min(6.5,Math.max(2.8,a/42+2.4))}s`)}function If({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:o,children:r,collapsed:s=!1,titleActive:l=!1,onTitleClick:m,onToggleCollapsed:d}){return k.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[k.jsxs("div",{className:"section-header",children:[k.jsxs("div",{className:"section-title-row",children:[m?k.jsxs("div",{className:"section-title-combo",children:[k.jsx("button",{type:"button",className:`section-title-link${l?" active":""}`,onClick:m,children:k.jsx("span",{children:e})}),d&&k.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:s?k.jsx(dr,{size:13}):k.jsx(ai,{size:13})})]}):d?k.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:d,children:[k.jsx("span",{children:e}),s?k.jsx(dr,{size:13}):k.jsx(ai,{size:13})]}):k.jsx("span",{children:e}),o]}),t&&k.jsx("div",{className:"section-actions",children:t})]}),!s&&k.jsx("div",{className:"sidebar-section-body",children:r})]})}function tS({children:e,expanded:t=!1,onClick:n}){return k.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function _f({session:e,selected:t,icon:n,archived:a=!1,hideIcon:o=!1,nested:r=!1,dragging:s,placeholder:l,running:m,goalRuntime:d,subagentRuntime:h,terminalIndicator:g,projectLabel:y,ariaDescribedBy:w,childSessionCount:_=0,childSessionsExpanded:P=!1,onSelect:M,onToggleChildSessions:C,onTogglePin:$,onToggleSaveForLater:O,onDockRight:j,onArchive:x,onDragStart:R,onDragEnd:E,onDragOver:H,onDrop:B,onRename:D}){const[J,le]=v.useState(!1),ue=d?.status==="queued",je=d?.tone==="active"&&!ue,ke=(h?.activeCount??0)>0,te=_>0&&!!C,Me=o&&!te,ye=ke||je||!ue&&(m??e.status==="active"),ne=ke&&h?h.label:je&&d?HK(d):"Running",be=["sidebar-task-row",sc(e)?"is-draft":"",ye?"has-running-dot":""].filter(Boolean).join(" "),ae=v.useMemo(NK,[]),de=k.jsx(CK,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:D?()=>le(!0):void 0,onTogglePin:$,onToggleSaveForLater:O,onDockRight:j,onArchive:x}),xe=k.jsxs(lb,{selected:t,dataSessionId:e.id,dragging:s,iconless:Me,nested:r,placeholder:l,className:be||void 0,ariaExpanded:te?P:void 0,ariaDescribedBy:w,onSelect:M,onDragStart:R,onDragEnd:E,onDragOver:H,onDrop:B,onDoubleClick:D?()=>le(!0):void 0,children:[Me?null:te?k.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":P?"Hide subagent conversations":"Show subagent conversations","aria-label":`${P?"Hide":"Show"} ${_} subagent ${_===1?"conversation":"conversations"}`,"aria-expanded":P,onClick:we=>{we.stopPropagation(),C?.()},children:P?k.jsx(ai,{size:13}):k.jsx(dr,{size:13})}):n??k.jsx(cm,{size:15}),k.jsx("span",{className:"row-label-shell",title:y||void 0,children:k.jsx("span",{className:"sidebar-session-title-line",children:k.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:DK,children:k.jsx(AK,{title:e.title})})})}),k.jsxs("div",{className:"row-meta",children:[k.jsxs("span",{className:"row-meta-status",children:[g?k.jsx(HC,{indicator:g}):null,ye?k.jsx("span",{className:`sidebar-running-dot${ke?" subagent":je?" goal":""}`,style:ae,"aria-label":ne}):null]}),de]})]}),De=J&&D?k.jsx(RK,{session:e,onSave:we=>D(e,we),onClose:()=>le(!1)}):null;return k.jsxs(k.Fragment,{children:[xe,De]})}function LK({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:o,onToggleSaveForLater:r,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:d}){const h=e.path.split("/").at(-1)??e.path,g=`${e.workspaceName} · ${e.path}`;return k.jsxs(lb,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:l,onDragOver:m,onDrop:d,children:[e.available?k.jsx(Bv,{size:15}):k.jsx(j6,{size:15}),k.jsx("span",{className:"row-label-shell",title:g,children:k.jsx("span",{className:"row-label",children:h})}),k.jsx("div",{className:"row-meta",children:k.jsxs("div",{className:"sidebar-row-actions",children:[k.jsx(bu,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:o,children:e.status==="pinned"?k.jsx(Vv,{size:13}):k.jsx(Fv,{size:13})}),k.jsx(bu,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?k.jsx(iC,{size:13}):k.jsx(oC,{size:13})})]})})]})}function HK(e){return e.actionLabel}function UK({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:o=!1,disclosure:r=!0,workspaceState:s,cloudLinkTrusted:l=!0,cloudLinkWarning:m=null,placeholder:d,terminalIndicator:h,onSelect:g,onNewChat:y,onMoveToCloud:w,onWorkspaceTargetSelect:_,onTogglePin:P,onRemove:M,onDragStart:C,onDragEnd:$,onDragOver:O,onDrop:j}){const[x,R]=v.useState(!1),E=v.useRef(null),[H,B]=v.useState({}),D=!!w||!!M,J=e==="local"&&l!==!1&&!!t.linkedSandboxProject?.projectId,le=v.useCallback(()=>{if(typeof window>"u")return;const ke=E.current?.getBoundingClientRect();if(!ke)return;const te=Math.max(12,window.innerWidth-EK-12),Me=Math.max(12,window.innerHeight-MK),ye=Math.max(12,Math.min(ke.right+10,te)),ne=Math.max(12,Math.min(ke.top-4,Me)),be={"--sidebar-project-locations-left":`${Math.round(ye)}px`,"--sidebar-project-locations-top":`${Math.round(ne)}px`};B(ae=>ae["--sidebar-project-locations-left"]===be["--sidebar-project-locations-left"]&&ae["--sidebar-project-locations-top"]===be["--sidebar-project-locations-top"]?ae:be)},[]),ue=v.useCallback(()=>{le(),g()},[g,le]);function je(){R(!1)}return k.jsxs("div",{ref:E,className:["sidebar-project-row-shell",x?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:le,onPointerEnter:le,children:[k.jsxs(lb,{selected:a,placeholder:d,className:["sidebar-project-row",x?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?o:void 0,onSelect:ue,onDragStart:C,onDragEnd:$,onDragOver:O,onDrop:j,children:[k.jsx(LC,{kind:e,linkedCloud:J,open:e==="local"&&o,className:"sidebar-row-icon",baseSize:15}),k.jsx("span",{className:"row-label-shell",children:k.jsxs("span",{className:"sidebar-project-title-line",children:[k.jsx("span",{className:"row-label",children:t.name}),k.jsx(qK,{value:t.updatedAt}),r?k.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:o?k.jsx(ai,{size:13}):k.jsx(dr,{size:13})}):null]})}),k.jsxs("div",{className:"row-meta",children:[k.jsx("span",{className:"row-meta-status",children:h?k.jsx(HC,{indicator:h}):null}),k.jsxs("div",{className:"sidebar-row-actions",children:[k.jsx(bu,{label:n?"Unpin project":"Pin project",onClick:P,children:n?k.jsx(Vv,{size:13}):k.jsx(Fv,{size:13})}),D&&k.jsx(t9,{open:x,onToggleOpen:()=>R(ke=>!ke)}),k.jsx(bu,{label:"New task",onClick:y,children:k.jsx(dm,{size:13})})]})]})]}),k.jsx(BK,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:l,cloudLinkWarning:m,onWorkspaceTargetSelect:_,style:H}),x&&k.jsx(n9,{onClose:je,onMoveToCloud:w?()=>{je(),w()}:void 0,onRemove:()=>{je(),M()}})]})}function qK({value:e}){const t=zK(e);if(!t||!e)return null;const n=new Date(e);return k.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${$K.format(n)}`,children:t})}function zK(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=OK.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${jK.format(n)} ${a}`}function HC({indicator:e}){return k.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:k.jsx(pC,{size:13})})}function BK({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:o,onWorkspaceTargetSelect:r,style:s}){const l=KK(e,t,n,a,o);return k.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[k.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),k.jsx("div",{className:"sidebar-project-location-list",children:l.map(m=>{const d=["sidebar-project-location-row",m.tone??"",m.actionTarget?"clickable":""].filter(Boolean).join(" "),h=k.jsxs(k.Fragment,{children:[k.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),k.jsx("span",{className:"sidebar-project-location-copy",children:k.jsx(FK,{value:m.value})})]});return m.actionTarget?k.jsx("button",{type:"button",className:d,"data-workspace-target":m.actionTarget,disabled:m.disabled||!r,title:m.disabledReason??void 0,onClick:g=>{g.stopPropagation(),!m.disabled&&r?.(m.actionTarget)},children:h},m.key):k.jsx("div",{className:d,children:h},m.key)})})]})}function FK({value:e}){const t=VK(e);return k.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?k.jsxs(k.Fragment,{children:[k.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),k.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,k.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function VK(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function KK(e,t,n,a=!0,o=null){return e==="cloud"?GK(t):WK(t,n,a,o)}function WK(e,t,n=!0,a=null){const o=JK(e,t,n),r=ZK(t),s=QK(e,n),l=n===!1&&a;return[{key:"local",value:o,tone:r?"attention":"local",icon:e.source==="git"?k.jsx(lC,{size:13}):k.jsx(sC,{size:13}),actionTarget:"local"},{key:"cloud",value:l||(s?XK(e,t,n):"not in cloud"),tone:l?"attention":"cloud",icon:k.jsx(lm,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function GK(e){return[{key:"cloud",value:e9(e),tone:e.syncedAt?"cloud":"attention",icon:k.jsx(lm,{size:13}),actionTarget:"cloud"}]}function JK(e,t,n){const a=YK(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?$C(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function ZK(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function YK(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function QK(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function XK(e,t,n){return NC(e,null,t,{cloudLinkTrusted:n})}function e9(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function t9({open:e,onToggleOpen:t}){return k.jsx("button",{type:"button",className:`sidebar-row-action ${e?"active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-haspopup":"menu","aria-expanded":e,onClick:n=>{n.stopPropagation(),t()},children:k.jsx(Oc,{size:13})})}function n9({onClose:e,onMoveToCloud:t,onRemove:n}){return k.jsxs(k.Fragment,{children:[k.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),k.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&k.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[k.jsx(xK,{size:13}),k.jsx("span",{children:"Move to Cloud"})]}),k.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[k.jsx($c,{size:13}),k.jsx("span",{children:"Remove from Projects"})]})]})]})}function lb({children:e,className:t,dataSessionId:n,dragging:a,iconless:o=!1,nested:r=!1,placeholder:s=!1,selected:l,ariaExpanded:m,ariaDescribedBy:d,onSelect:h,onDragStart:g,onDragEnd:y,onDragOver:w,onDrop:_,onDoubleClick:P}){const M=!!g;return k.jsx("div",{className:["sidebar-row",t??"",l?"selected":"",a?"dragging":"",o?"iconless":"",r?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:M,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":d,onClick:h,onDoubleClick:P,onKeyDown:C=>{C.target===C.currentTarget&&(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),h())},onDragStart:g,onDragEnd:y,onDragEnter:C=>{w&&(C.preventDefault(),C.dataTransfer.dropEffect="move",w(C))},onDragOver:C=>{w&&(C.preventDefault(),C.dataTransfer.dropEffect="move",w(C))},onDrop:C=>{_&&(C.preventDefault(),_(C))},children:e})}function bu({children:e,label:t,onClick:n}){return k.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function a9({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:o,onOnlyRunningTasksChange:r,onShowCodexChatsChange:s,onTasksetChange:l,onSortChange:m,onlyRunningTasks:d,openMenu:h,setOpenMenu:g,showCodexChats:y,sort:w,selectedTasksetId:_,tasksets:P}){const M=v.useRef(null),[C,$]=v.useState(!1),j=P.find(E=>E.id===_)?.name??G0.find(E=>E.value===e)?.label??"Active",x=h==="tasks-filter",R=h==="chats";return v.useEffect(()=>{if(!x&&!R)return;function E(H){M.current?.contains(H.target)||g(null)}return document.addEventListener("pointerdown",E),()=>document.removeEventListener("pointerdown",E)},[x,g,R]),k.jsxs("div",{className:"sidebar-task-list-controls",ref:M,children:[k.jsxs("div",{className:"section-menu",children:[k.jsx("button",{type:"button",className:`section-icon ${R?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":R,onClick:()=>g(E=>E==="chats"?null:"chats"),children:k.jsx(Oc,{size:14})}),R?k.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":y,onClick:()=>s(!y),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:y?k.jsx(Uo,{size:13}):null}),k.jsx("span",{children:"Show Codex chats, including pinned"})]}),k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":d,onClick:()=>r(!d),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:d?k.jsx(Uo,{size:13}):null}),k.jsxs("span",{children:["Only running ",n,", including pinned"]})]}),n==="tasks"?k.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>o(!t),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?k.jsx(Uo,{size:13}):null}),k.jsx("span",{children:"Group by project"})]}):null,lK.map(E=>k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w===E.value,onClick:()=>{m(E.value),g(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:w===E.value?k.jsx(Uo,{size:13}):null}),k.jsx("span",{children:E.label})]},E.value))]}):null]}),k.jsxs("div",{className:"section-menu",children:[k.jsx("button",{type:"button",className:`section-icon ${x?"active":""}`,"aria-label":`Filter ${n}: ${j}`,"aria-haspopup":"menu","aria-expanded":x,onClick:()=>g(E=>E==="tasks-filter"?null:"tasks-filter"),children:k.jsx(X6,{size:14})}),x?k.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:G0.map(E=>k.jsxs(v.Fragment,{children:[E.value==="tasksets"?k.jsxs("button",{type:"button",role:"menuitem","aria-expanded":C,onClick:()=>$(H=>!H),children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:C?k.jsx(ai,{size:13}):k.jsx(dr,{size:13})}),k.jsx("span",{children:E.label})]}):k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===E.value,onClick:()=>{a(E.value),g(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===E.value?k.jsx(Uo,{size:13}):null}),k.jsx("span",{children:E.label})]}),E.value==="tasksets"&&C?k.jsxs(k.Fragment,{children:[k.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!_,onClick:()=>{l(null),g(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!_?k.jsx(Uo,{size:13}):null}),k.jsx("span",{children:"All Tasksets"})]}),P.map(H=>k.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&_===H.id,onClick:()=>{l(H.id),g(null)},children:[k.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&_===H.id?k.jsx(Uo,{size:13}):null}),k.jsx("span",{children:H.name}),k.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:H.chatCount})]},H.id))]}):null]},E.value))}):null]})]})}function o9({onAddProject:e,onViewProjects:t}){const[n,a]=v.useState(!1),o=v.useRef(null),r=v.useRef(null);return v.useEffect(()=>{if(!n)return;o.current?.querySelector('[role="menuitem"]')?.focus();const s=l=>{o.current?.contains(l.target)||a(!1)};return document.addEventListener("pointerdown",s),()=>document.removeEventListener("pointerdown",s)},[n]),k.jsxs(k.Fragment,{children:[k.jsxs("div",{className:"section-menu",ref:o,onKeyDown:s=>{s.key==="Escape"&&(s.stopPropagation(),a(!1),r.current?.focus())},children:[k.jsx("button",{ref:r,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(s=>!s),children:k.jsx(Oc,{size:14})}),n?k.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),k.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const i9=240,r9=36;function s9(e,t,n=!1){const a=Math.max(12,t.width-i9-12),o=Math.max(12,t.height-r9-(n?22:0)-12);return{"--sidebar-task-detail-left":`${Math.round(Math.max(12,Math.min(e.right+10,a)))}px`,"--sidebar-task-detail-top":`${Math.round(Math.max(12,Math.min(e.top-4,o)))}px`}}function l9({detail:e,onClose:t}){if(v.useEffect(()=>{if(!e||typeof window>"u")return;const o=l=>{l.key==="Escape"&&t()};let r=!1;const s=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),r=!0});return window.addEventListener("keydown",o),()=>{window.cancelAnimationFrame(s),window.removeEventListener("keydown",o),r&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return k.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[k.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?k.jsxs("div",{className:"sidebar-task-detail-folder",children:[k.jsx(sC,{size:13,"aria-hidden":"true"}),k.jsx("span",{children:e.folderName})]}):null]})}function c9({children:e,expanded:t,groupKey:n,kind:a,label:o,onToggle:r,onNewTask:s,onOpenProject:l,onRemoveProject:m,project:d}){const h=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,g=a==="draft"?Bv:cm,[y,w]=v.useState(!1),_=!!(s||l||m);return k.jsxs("section",{className:"sidebar-task-project-group",children:[k.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[k.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":h,"aria-expanded":t,onClick:()=>{w(!1),r()},children:[d?k.jsx(LC,{kind:d.kind,linkedCloud:!!(d.kind==="local"&&d.project.linkedSandboxProject?.projectId),open:d.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):k.jsx(g,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),k.jsx("span",{className:"sidebar-task-project-group-name",children:o}),k.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?k.jsx(ai,{size:13}):k.jsx(dr,{size:13})})]}),d&&_?k.jsxs("div",{className:"sidebar-task-project-group-actions",children:[l||m?k.jsx("button",{type:"button",className:`sidebar-row-action${y?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":y,"aria-haspopup":"menu",onClick:()=>w(P=>!P),children:k.jsx(Oc,{size:13})}):null,s?k.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:k.jsx(dm,{size:13})}):null]}):null,y?k.jsxs(k.Fragment,{children:[k.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>w(!1)}),k.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[l?k.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),l()},children:k.jsx("span",{children:"Open project"})}):null,m?k.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),m()},children:[k.jsx($c,{size:13}),k.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?k.jsx("div",{id:h,className:"sidebar-task-project-group-content",children:e}):null]})}const d9={},u9=new Map,m9=new Map;function p9(e,t){return Math.min(Math.max(e,En)+Mh,t)}function f9(e,t){const n=Math.max(En,Math.min(e,t));if(n<=En)return En;const a=Math.ceil((n-En)/Mh);return Math.max(En,En+(a-1)*Mh)}function h9(e,t){const n=new Map;for(const a of e){const o=t(a),r=n.get(o.key);r?r.sessions.push(a):n.set(o.key,{...o,sessions:[a]})}return[...n.values()]}function g9({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:o={},cloudProjectRows:r,beginProjectChat:s,onAddProject:l,commitTaskDrop:m,commitTaskPreviewDrop:d,dockSessionRight:h,experience:g="work",goalRuntimeBySessionId:y=u9,localProjectRows:w,openSidebarFile:_,pinnedCollapsed:P,pinnedRows:M,previewTaskDrop:C,previewPinnedDrop:$,projectRows:O,renameSession:j,restoreSession:x,runningSessionIds:R,sectionMenuOpen:E,selectedProjectId:H,selectedSessionId:B,setChatRowsVisibleCount:D,setSectionMenuOpen:J,setSelectedAppId:le,setSelectedProjectId:ue,setSelectedSessionId:je,setView:ke,sidebarProjectIdBySessionId:te,startTaskDrag:Me,startPinnedDrag:ye,subagentRuntimeBySessionId:ne=m9,taskDragSessionId:be,taskPreviewSessionIds:ae,terminalSummaries:de=d9,toggleSessionPinned:xe,toggleSessionSavedForLater:De,view:we,clearTaskDrag:ie,removeProject:Se,toggleProjectPinned:Ue,onTogglePinnedCollapsed:Je,setSidebarFileStatus:Ke,commitPinnedDrop:tt,commitPinnedPreviewDrop:ze,clearSidebarDrag:Ge,dragItem:qe}){const[L,N]=v.useState("active"),[q,X]=v.useState("recent"),[me,$e]=v.useState(!0);v.useEffect(()=>{g!=="chat"&&$e(!0)},[g]);const[Le,nt]=v.useState({work:!1,chat:!0}),[at,lt]=v.useState({work:!1,chat:!1}),pt=g==="chat"?"chat":"work",Oe=Le[pt],[Ye,f]=v.useState(X0);Dc(()=>f(X0()));const{onlyRunningTasks:U,showCodexChats:Y}=Ye,[he,re]=v.useState(null),[W,I]=v.useState(()=>new Set),[K,ee]=v.useState(()=>new Map),[Z,ce]=v.useState(null);v.useEffect(()=>{H&&nt(V=>V[pt]?{...V,[pt]:!1}:V)},[pt,H]);const pe=g==="chat"?"chats":"tasks",fe=O??[...w,...r],Ae=v.useMemo(()=>new Map(fe.map(V=>[V.id,V.project.name])),[fe]),_e=v.useMemo(()=>new Map(fe.map(V=>[V.id,V])),[fe]),Ne=v.useMemo(()=>{const V=new Set(R);for(const He of e){const Ie=y.get(He.id),Be=ne.get(He.id);(Ie?.tone==="active"&&Ie.status!=="queued"||(Be?.activeCount??0)>0||$t(He.id)?.status==="running")&&V.add(He.id)}return V},[e,y,R,ne,de]),Pe=v.useMemo(()=>J0({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:Ne,sort:"manual"}),[e,n,Ne]),Xe=v.useMemo(()=>J0({activeSessions:e,doneSessions:n,filter:L,inProgressSessionIds:Ne,onlyRunningTasks:U,selectedTasksetId:he,previewSessionIds:ae,showCodexChats:Y,sort:q}),[e,n,Ne,U,he,Y,L,ae,q]),st=v.useMemo(()=>{const V=new Map;for(const He of[...e,...n]){if(!zd(He,{inProgressSessionIds:Ne,onlyRunningTasks:U,showCodexChats:Y}))continue;const Ie=ss(He);if(!Ie)continue;const Be=V.get(Ie.id);Be?Be.chatCount+=1:V.set(Ie.id,{...Ie,chatCount:1})}return[...V.values()].sort((He,Ie)=>He.name.localeCompare(Ie.name))},[e,n,Ne,U,Y]),rn=v.useMemo(()=>M.filter(V=>V.type!=="session"||zd(V.session,{inProgressSessionIds:Ne,onlyRunningTasks:U,showCodexChats:Y})),[Ne,U,M,Y]),Et=v.useMemo(()=>Xe.filter(V=>!Ll(V)),[Xe]),tn=v.useMemo(()=>Et.slice(0,Math.max(En,a)),[a,Et]),mn=v.useMemo(()=>{const V=h9(tn,He=>{if(sc(He))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const Ie=te[He.id],Be=ht(He)??"Work";return{key:Ie?`project:${Ie}`:`projectless:${Be}`,label:Be,projectId:Ie??null,project:Ie?_e.get(Ie)??null:null,kind:Ie?"project":"projectless"}});for(const He of fe)V.some(Ie=>Ie.projectId===He.id)||V.push({key:`project:${He.id}`,label:He.project.name,projectId:He.id,project:He,kind:"project",sessions:[]});return V},[fe,Ae,_e,te,tn]),pn=tn.length<Et.length,Wt=tn.length>En,Da=v.useMemo(()=>new Set(mn.filter(V=>V.sessions.some(He=>He.id===B||Ne.has(He.id))).map(V=>V.key)),[mn,Ne,B]),ga=Pe.filter(V=>!Ll(V)).map(V=>V.id),$n=tn.map(V=>V.id),Pn=JSON.stringify(Object.entries(o).filter(([V,He])=>He.length>0&&(ne.get(V)?.activeCount??0)>0).flatMap(([V,He])=>He.map(Ie=>[V,Ie.id])).sort(([V,He],[Ie,Be])=>V.localeCompare(Ie)||He.localeCompare(Be)));v.useEffect(()=>{const V=JSON.parse(Pn);if(V.length===0)return;const He=new Set(V.map(([Ie])=>Ie));I(Ie=>[...He].every(Be=>Ie.has(Be))?Ie:new Set([...Ie,...He]))},[Pn]);function $t(V){return gK(de[OC({kind:"session",id:V})])}function ht(V){if(sc(V))return"Draft";const He=te[V.id];return He?Ae.get(He)??V.workspaceName??"Project":nK(V)}function fn(V){Xt({kind:"chat",sessionId:V.id}),je(V.id);const He=te[V.id]??null;le(He?null:V.appId),ue(He),ke("chat")}function bt(V){return(o[V.id]??[]).filter(He=>zd(He,{inProgressSessionIds:Ne,onlyRunningTasks:U,showCodexChats:Y}))}function jt(V,He){return W.has(V.id)||He.some(Ie=>Ie.id===B)}function va(V){I(He=>{const Ie=new Set(He);return Ie.has(V)?Ie.delete(V):Ie.add(V),Ie})}function Ut(V){const He=bt(V);return He.length===0||!jt(V,He)?null:k.jsx("div",{className:"sidebar-child-session-group",children:He.map(Ie=>k.jsx(_f,{session:Ie,selected:we==="chat"&&B===Ie.id,hideIcon:!0,nested:!0,running:Ne.has(Ie.id),goalRuntime:y.get(Ie.id)??null,subagentRuntime:ne.get(Ie.id)??null,terminalIndicator:$t(Ie.id),projectLabel:ht(V),onSelect:()=>fn(Ie),onTogglePin:()=>xe(Ie),onToggleSaveForLater:()=>De(Ie),onDockRight:()=>h(Ie),onArchive:()=>Ie.archived?x(Ie):t(Ie),onRename:j},Ie.id))})}function hn(V,He){if(typeof window>"u")return;const Ie=Ll(V)?ht(V):null;ce({descriptionId:`sidebar-task-detail-${V.id}`,sessionId:V.id,title:V.title,updatedAt:V.updatedAt,folderName:Ie,style:s9(He.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!Ie)})}function it(V,He={}){const Ie=V.archived,Be=be===V.id,yt=bt(V),Jn="sidebar-session-group",gn=q==="manual"?{onDragStart:We=>Me(We,{allSessionIds:ga,visibleSessionIds:$n,sessionId:V.id}),onDragEnd:ie,onDragOver:We=>{Be||C(We,V.id)},onDrop:We=>{Be?d():m(We,V.id)}}:{};return k.jsxs("div",{className:Jn,onPointerEnter:We=>hn(V,We.currentTarget),onPointerLeave:()=>ce(null),onFocusCapture:We=>hn(V,We.currentTarget),onBlurCapture:We=>{We.currentTarget.contains(We.relatedTarget)||ce(null)},children:[k.jsx(_f,{session:V,selected:!Ie&&we==="chat"&&B===V.id,archived:Ie,hideIcon:!0,placeholder:Be,running:Ne.has(V.id),goalRuntime:y.get(V.id)??null,subagentRuntime:ne.get(V.id)??null,terminalIndicator:$t(V.id),projectLabel:He.projectLabel===void 0?ht(V):He.projectLabel,metadataPresentation:He.metadataPresentation,ariaDescribedBy:Z?.sessionId===V.id?Z.descriptionId:void 0,childSessionCount:yt.length,childSessionsExpanded:jt(V,yt),onToggleChildSessions:()=>va(V.id),onSelect:()=>{ce(null),Ie&&x(V),fn(V)},onTogglePin:()=>xe(V),onToggleSaveForLater:()=>De(V),onDockRight:()=>h(V),onArchive:()=>Ie?x(V):t(V),onRename:j,...gn}),Be?null:Ut(V)]},V.id)}function Cn(V){V!=="tasksets"&&re(null),N(V),D(En)}function ao(V){re(V),N("tasksets"),D(En)}function oo(V){X(V),D(En)}function ra(){D(V=>p9(V,Et.length))}function ba(){D(V=>f9(V,Et.length))}function Nn(V){const He={id:V.id,type:V.type};return{onDragStart:Ie=>ye(Ie,He),onDragEnd:Ge,onDragOver:Ie=>$(Ie,He),onDrop:Ie=>{qe?.id===V.id&&qe.type===V.type?ze():tt(Ie,He)}}}function Po(V){const He=Nn(V),Ie=qe?.id===V.id&&qe.type===V.type;if(V.type==="project"){const yt=V.item;return k.jsx(UK,{kind:yt.kind,project:yt.project,pinned:!0,selected:we==="chat"&&H===yt.id,expanded:!1,disclosure:!1,placeholder:Ie,onSelect:()=>{le(null),ue(yt.id),je(null),ke("chat")},onNewChat:()=>s(yt.id),onTogglePin:()=>Ue(yt),onRemove:()=>Se(yt),...He},V.key)}if(V.type==="file")return k.jsx(LK,{file:V.file,placeholder:Ie,onSelect:()=>_(V.file),onTogglePin:()=>Ke(V.file,"none"),onToggleSaveForLater:()=>Ke(V.file,"saved_for_later"),...He},V.key);const Be=V.session;return k.jsx("div",{onPointerEnter:yt=>hn(Be,yt.currentTarget),onPointerLeave:()=>ce(null),onFocusCapture:yt=>hn(Be,yt.currentTarget),onBlurCapture:yt=>{yt.currentTarget.contains(yt.relatedTarget)||ce(null)},children:k.jsx(_f,{ariaDescribedBy:Z?.sessionId===Be.id?Z.descriptionId:void 0,session:Be,selected:we==="chat"&&B===Be.id,hideIcon:!0,placeholder:Ie,running:Ne.has(Be.id),goalRuntime:y.get(Be.id)??null,subagentRuntime:ne.get(Be.id)??null,terminalIndicator:$t(Be.id),projectLabel:ht(Be),metadataPresentation:"flyout",onSelect:()=>{ce(null),fn(Be)},onTogglePin:()=>xe(Be),onToggleSaveForLater:()=>De(Be),onDockRight:()=>h(Be),onArchive:()=>t(Be),onRename:j,...He})},V.key)}function La(V){const He=Da.has(V.key)||K.get(V.key)!==!1;return k.jsx(c9,{expanded:He,groupKey:V.key,kind:V.kind,label:V.label,onToggle:()=>{ee(Ie=>{const Be=new Map(Ie);return Be.set(V.key,!He),Be})},onNewTask:V.project?()=>s(V.project.id):void 0,onOpenProject:V.project?()=>{le(null),ue(V.project.id),je(null),ke("chat")}:void 0,onRemoveProject:V.project?()=>Se(V.project):void 0,project:V.project,children:V.sessions.map(Ie=>it(Ie,{metadataPresentation:"flyout",projectLabel:V.label}))},V.key)}return k.jsxs("div",{className:"sidebar-sections",children:[rn.length>0?k.jsx(If,{label:"Pinned",className:"sidebar-pinned-section",collapsed:P,onToggleCollapsed:Je,children:rn.map(Po)}):null,k.jsx(If,{label:"Projects",className:`sidebar-projects-section${g!=="chat"?" development":""}`,collapsed:Oe,onToggleCollapsed:()=>nt(V=>({...V,[pt]:!V[pt]})),actions:k.jsx(o9,{onAddProject:l,onViewProjects:()=>{(async()=>await Xt({kind:"view",view:"projects"})&&(le(null),ue(null),je(null),ke("projects")))()}}),children:mn.filter(V=>V.kind==="project").map(V=>La(g==="chat"||!me?{...V,sessions:[]}:V))}),k.jsxs(If,{label:g==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:at[pt],onToggleCollapsed:()=>lt(V=>({...V,[pt]:!V[pt]})),actionsVisible:E==="chats"||E==="tasks-filter"||L!=="active"||U||!Y,actions:k.jsx(a9,{filter:L,groupByProject:me,noun:pe,onFilterChange:Cn,onGroupByProjectChange:$e,onOnlyRunningTasksChange:V=>{f(He=>{const Ie={...He,onlyRunningTasks:V};return eS(Ie),Ie}),D(En)},onShowCodexChatsChange:V=>{f(He=>{const Ie={...He,showCodexChats:V};return eS(Ie),Ie}),D(En)},onTasksetChange:ao,onSortChange:oo,onlyRunningTasks:U,openMenu:E,setOpenMenu:J,showCodexChats:Y,sort:q,selectedTasksetId:he,tasksets:st}),children:[(g==="chat"||!me?tn:tn.filter(V=>!te[V.id])).map(V=>it(V)),Et.length===0&&rn.length===0?k.jsx("div",{className:"empty-row",children:cK(L,pe)}):null,Et.length>En&&(pn||Wt)?k.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${tn.length} of ${Et.length} ${pe}`,children:[pn?k.jsx(tS,{onClick:ra,children:"Show more"}):null,Wt?k.jsx(tS,{onClick:ba,children:"Show less"}):null]}):null]}),k.jsx(l9,{detail:Z,onClose:()=>ce(null)})]})}const v9="/";function na(e){return`${v9}${e.replace(/^\.?\//,"")}`}const b9=na("openpond-icon.png"),y9=na("openpond-wordlogo-white.png"),Uee=na("tutorials/what-is-an-openpond-agent-poster.png"),qee=na("tutorials/what-is-an-openpond-agent.vtt"),zee=na("tutorials/how-to-make-an-agent-poster.png"),Bee=na("tutorials/how-to-make-an-agent.vtt");function Fee(e){return na(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function Vee(e){return na(`tutorials/how-to-make-an-agent-${e}.vtt`)}const nS={github:na("connected-apps/github.svg"),google:na("connected-apps/google.svg"),microsoft_teams:na("connected-apps/microsoft.svg"),mcp:na("connected-apps/openpond-mcp.svg"),slack:na("connected-apps/slack.svg"),x:na("connected-apps/x.svg")};function Kee(e){return nS[e]??nS.mcp}function S9({value:e,onChange:t}){const[n,a]=v.useState(!1),o=v.useRef(null),r=v.useRef(null),s=v.useRef(null),l=v.useRef(null),m=yf.find(y=>y.value===e)??yf[0];v.useEffect(()=>{if(!n)return;const y=_=>{_.target instanceof Node&&!o.current?.contains(_.target)&&a(!1)},w=()=>a(!1);return window.addEventListener("pointerdown",y),window.addEventListener("blur",w),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("blur",w)}},[n]),v.useLayoutEffect(()=>{n&&l.current&&aS(s.current,l.current),l.current=null},[n]);const d=y=>{if(n){aS(s.current,y);return}l.current=y,a(!0)},h=y=>{y.key==="ArrowDown"?(y.preventDefault(),d("first")):y.key==="ArrowUp"&&(y.preventDefault(),d("last"))},g=y=>{const w=UC(s.current),_=w.findIndex(C=>C===document.activeElement);if(y.key==="Escape"){y.preventDefault(),a(!1),r.current?.focus();return}if(y.key==="Home"||y.key==="End"){y.preventDefault(),w[y.key==="Home"?0:w.length-1]?.focus();return}if(y.key!=="ArrowDown"&&y.key!=="ArrowUp")return;y.preventDefault();const P=y.key==="ArrowDown"?1:-1,M=_<0?0:(_+P+w.length)%w.length;w[M]?.focus()};return k.jsxs("div",{className:"sidebar-experience-menu",ref:o,children:[k.jsxs("button",{ref:r,type:"button",className:"sidebar-wordmark-button sidebar-experience-trigger","aria-label":`OpenPond product: ${m.label}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>{l.current=null,a(y=>!y)},onKeyDown:h,children:[k.jsx("img",{className:"sidebar-wordmark",src:y9,alt:""}),k.jsx("span",{className:"sidebar-experience-label",children:m.label}),k.jsx(ai,{size:13,"aria-hidden":"true"})]}),n?k.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:g,children:yf.map(y=>{const w=y.value===e;return k.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w,className:w?"active":"","data-product-area":y.value,onClick:()=>{a(!1),w||t(y.value)},children:[k.jsxs("span",{children:[k.jsx("strong",{children:y.label}),k.jsx("small",{children:y.description})]}),w?k.jsx(Uo,{size:14,"aria-hidden":"true"}):null]},y.value)})}):null]})}function UC(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function aS(e,t){const n=UC(e);(t==="first"?n[0]:n.at(-1))?.focus()}function x9(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function k9(e){const t=e?.accounts.find(s=>s.isActive)??null,n=e?.profile??null,a=e?.activeProfile?.handle??null;return{label:(e?.state==="signed_in"?x9(e?.label,n?.handle,n?.name,n?.email,t?.displayLabel,t?.handle,a,e?.email,"Signed in"):e?.state==="loading"||e?.state==="switching"?"Loading account":"Sign in")??"Account",image:e?.avatarUrl??n?.image??t?.avatarUrl??null}}function w9({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:o,onOpenChange:r,onOpenSettings:s,onSelectTeam:l,onLogOut:m}){const[d,h]=v.useState(null),[g,y]=v.useState(!1),w=v.useRef(null),_=v.useMemo(()=>k9(e),[e]),P=_.label.trim().slice(0,1).toUpperCase(),M=n.find(C=>C.teamId===a)??n[0]??null;return v.useEffect(()=>{if(!t)return;function C(O){w.current?.contains(O.target)||r(!1)}function $(O){O.key==="Escape"&&r(!1)}return document.addEventListener("pointerdown",C),document.addEventListener("keydown",$),()=>{document.removeEventListener("pointerdown",C),document.removeEventListener("keydown",$)}},[r,t]),k.jsxs("div",{className:"user-auth-footer",ref:w,children:[k.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${_.label} account menu`,onClick:()=>r(!t),children:[k.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:_.image?k.jsx("img",{src:_.image,alt:""}):P?k.jsx("span",{children:P}):k.jsx(q0,{size:16})}),k.jsx("span",{className:"user-auth-name",children:_.label})]}),t?k.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[k.jsxs("div",{className:"user-auth-menu-header",children:[k.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:_.image?k.jsx("img",{src:_.image,alt:""}):P?k.jsx("span",{children:P}):k.jsx(q0,{size:17})}),k.jsx("span",{className:"user-auth-menu-identity",children:k.jsx("strong",{children:_.label})})]}),n.length>0&&l?k.jsxs("label",{className:"user-auth-team-picker",children:[k.jsx(mC,{size:15,"aria-hidden":"true"}),k.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),k.jsx("select",{"aria-label":"Active team",disabled:d!==null,value:M?.teamId??"",onChange:async C=>{const $=C.currentTarget.value;h($);try{await l($)}catch{}finally{h(null)}},children:n.map(C=>k.jsx("option",{value:C.teamId,children:C.displayName},C.teamId))})]}):null,k.jsx("div",{className:"user-auth-menu-divider"}),o?k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),o()},children:[k.jsx(rC,{size:15}),k.jsx("span",{children:"Activity"})]}):null,k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),s()},children:[k.jsx(uC,{size:15}),k.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?k.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:g,onClick:async()=>{y(!0);try{await m(),r(!1)}catch{}finally{y(!1)}},children:[k.jsx(pV,{size:15}),k.jsx("span",{children:g?"Logging out…":"Log out"})]}):null]}):null]})}function oS(e){const t=/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(e?.trim()??"");return t?[Number.parseInt(t[1],10),Number.parseInt(t[2],10),Number.parseInt(t[3],10)]:null}function I9(e,t){const n=oS(e),a=oS(t);if(!n||!a)return!1;for(let o=0;o<a.length;o+=1){if(a[o]>n[o])return!0;if(a[o]<n[o])return!1}return!1}function qC(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function _9(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function C9(e,t,n){const a=qC(t),o=_9(n);if(a==="mac"){const r=e.filter(s=>/-mac-.*\.zip$/i.test(s.name));return o==="arm64"?r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??null:o==="x64"?r.find(s=>/-mac-x64\.zip$/i.test(s.name))??r.find(s=>/-mac-universal\.zip$/i.test(s.name))??null:r.find(s=>/-mac-universal\.zip$/i.test(s.name))??r.find(s=>/-mac-arm64\.zip$/i.test(s.name))??r[0]??null}if(a==="linux"){const r=e.filter(s=>/\.AppImage$/i.test(s.name));return o==="arm64"?r.find(s=>/(?:arm64|aarch64).*\.AppImage$/i.test(s.name))??null:o==="x64"?r.find(s=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(s.name))??r[0]??null:r[0]??null}return null}function R9(e){if(!e.payload||typeof e.payload!="object")return null;const t=e.payload,a=(typeof t.tag_name=="string"?t.tag_name.trim():"").replace(/^v/,"");if(!I9(e.currentVersion,a))return null;const o=typeof t.html_url=="string"?t.html_url:"",s=(Array.isArray(t.assets)?t.assets:[]).flatMap(m=>{if(!m||typeof m!="object")return[];const d=m;return typeof d.name!="string"||typeof d.browser_download_url!="string"?[]:[{name:d.name,downloadUrl:d.browser_download_url}]}),l=C9(s,e.platform,e.arch);return!l||!o?null:{version:a,releaseUrl:o,assetName:l.name,downloadUrl:l.downloadUrl}}const P9=3600*1e3,A9="https://api.github.com/repos/openpond/openpond/releases/latest";function T9(e){const[t,n]=v.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",o=e.platform??"",r=e.arch??"",s=e.enabled&&!!a&&!!qC(o);return v.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let l=!1;async function m(){n(h=>({...h,status:h.update?"available":"checking"}));try{const h=await fetch(A9,{headers:{Accept:"application/vnd.github+json"}});if(!h.ok)throw new Error(`GitHub release check failed: ${h.status}`);const g=await h.json(),y=R9({payload:g,currentVersion:a,platform:o,arch:r});if(l)return;n({status:y?"available":"current",update:y,lastCheckedAt:Date.now()})}catch{if(l)return;n(h=>({status:h.update?"available":"error",update:h.update,lastCheckedAt:Date.now()}))}}m();const d=window.setInterval(()=>{m()},P9);return()=>{l=!0,window.clearInterval(d)}},[r,a,s,o]),t}const zC="openpond.sidebar.continuous-learning.dismissed.v1";function iS(e=BC()){if(!e)return!1;try{return e.getItem(zC)==="true"}catch{return!1}}function E9(e=BC()){if(e)try{e.setItem(zC,"true")}catch{}}function BC(){return typeof window>"u"?null:Lc}function M9({connection:e,onOpenSettings:t}){const[n,a]=v.useState(null),[o,r]=v.useState(iS);Dc(()=>r(iS()));const s=v.useCallback(async()=>{if(!e){a(null);return}try{a(await Q.harnessHistory(e))}catch{a(null)}},[e]);if(v.useEffect(()=>{s()},[s]),o||!e||!n?.workspace)return null;const l=n.evaluationReviewSchedule,m=l.activityEnabled?`${l.activityBatchSize} outcomes${l.enabled?` + ${l.cadence}`:""}`:l.enabled?l.cadence:"Manual";return k.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[k.jsxs("header",{children:[k.jsx("strong",{children:"Continuous learning"}),k.jsxs("div",{className:"sidebar-learning-notice-actions",children:[k.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:k.jsx(uC,{size:14})}),k.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),E9()},type:"button",children:k.jsx($c,{size:14})})]})]}),k.jsxs("div",{className:"sidebar-learning-status",children:[k.jsx("strong",{children:"Refiner"}),k.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),k.jsxs("div",{className:"sidebar-learning-status",children:[k.jsx("strong",{children:"Continuous Review"}),k.jsx("span",{children:m})]})]})}function j9(e){const[t,n]=v.useState(!1),{beginNewChat:a,arch:o,currentVersion:r,experience:s,productArea:l,onProductAreaChange:m,onSidebarResizeStart:d,platform:h,setSectionMenuOpen:g,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setSidebarOpen:P,setView:M,view:C,modelProjects:$,modelTrainingActivityByProjectId:O}=e,j=v.useCallback(H=>{n(!1),g(H)},[g]),x=v.useCallback(H=>{n(H),H&&g(null)},[g]),R=T9({currentVersion:r,platform:h,arch:o,enabled:um()}),E=R.status==="available"?R.update:null;return k.jsxs("aside",{className:"sidebar",children:[k.jsxs("div",{className:"sidebar-toolbar",children:[k.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>P(!1),children:k.jsx(dC,{size:16})}),k.jsx(S9,{value:l,onChange:m}),E&&k.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${E.version}: ${E.assetName}`,"aria-label":`Download OpenPond ${E.version}`,onClick:()=>{O9(E.downloadUrl)},children:[k.jsx(L6,{size:14}),k.jsx("span",{children:"Update"})]})]}),l!=="chat"?null:k.jsx(DV,{experience:s,beginNewChat:a}),k.jsxs("div",{className:"sidebar-scroll",children:[l==="chat"&&e.account?.activeProfile&&e.onOpenPonder?k.jsxs("button",{type:"button",className:"sidebar-ponder-entry",onClick:e.onOpenPonder,children:[k.jsx("span",{"aria-hidden":"true",children:"✦"})," Ponder Pal"]}):null,k.jsx(LV,{productArea:l,setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:M,view:C,modelProjects:$,modelTrainingActivityByProjectId:O}),l!=="chat"?null:k.jsx(g9,{...e,setSectionMenuOpen:j})]}),k.jsxs("div",{className:"sidebar-bottom-stack",children:[l!=="chat"?null:k.jsx(M9,{connection:e.connection,onOpenSettings:()=>{g(null),Xt({kind:"settings",section:"harness"})}}),k.jsxs("div",{className:"sidebar-footer-row",children:[k.jsx(w9,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:x,onOpenActivity:()=>{g(null),Xt({kind:"settings",section:"usage"})},onOpenSettings:()=>{g(null),Xt({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),k.jsx(HV,{setSectionMenuOpen:j,setSelectedAppId:y,setSelectedProjectId:w,setSelectedSessionId:_,setView:M,view:C})]})]}),k.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:d})]})}async function O9(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const $9=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function FC(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?VC(a)?"Couldn’t connect to OpenPond.":a:t}function VC(e){const t=e.trim();return $9.some(n=>n.test(t))}const KC=v.createContext(null);function rS({children:e,showToast:t}){return k.jsx(KC.Provider,{value:t,children:e})}function N9(){return v.useContext(KC)}function sS(e,t={}){const n=N9(),a=v.useRef(null),o=t.enabled??!0,r=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",l=e==null||e===""?null:`${s}${s?": ":""}${FC(e,r)}`;v.useEffect(()=>{if(!o||!l){a.current=null;return}a.current!==l&&(a.current=l,n?.(l,"error"))},[o,l,n])}function D9({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(sS(e?.previewError,{prefix:"Upload preview"}),sS(e?.error,{prefix:"Cloud setup"}),!e)return null;const o=e.status==="uploading",r=e.status==="ready",s=e.status==="error",l=e.projectKind==="cloud",m=e.preview??null;return k.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:k.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[k.jsx("button",{className:"git-dialog-close",disabled:o,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:k.jsx($c,{size:14})}),k.jsx("div",{className:"git-dialog-icon",children:r?k.jsx(Dd,{size:18}):k.jsx(lm,{size:18})}),k.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),k.jsx("p",{children:r?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":l?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),k.jsxs("div",{className:"cloud-setup-summary",children:[k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Project"}),k.jsx("strong",{children:e.projectName})]}),k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Source"}),k.jsx("strong",{children:l?"OpenPond Git":"Local project upload"})]}),k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Branch"}),k.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!l&&k.jsxs("div",{className:"git-dialog-row",children:[k.jsx("span",{children:"Cloud project"}),k.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!l&&k.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Calculating upload preview"}),k.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Preview unavailable"}),k.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),k.jsx("span",{children:lS({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):k.jsxs(k.Fragment,{children:[k.jsx("strong",{children:"Upload preview pending"}),k.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),o&&k.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[k.jsx(tV,{className:"cloud-setup-spinner",size:16}),k.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&e.upload&&k.jsxs("div",{className:"cloud-setup-upload-result",children:[k.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),k.jsx("span",{children:lS({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&e.setupUrl&&k.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?k.jsxs("span",{children:["Your repo is ready here:"," ",k.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:d=>Cf(d,e.projectUrl,n,{newTab:!0}),children:["Project page",k.jsx(vf,{size:13})]})]}):k.jsx("span",{children:"Your repo is ready. Next step:"}),k.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Cf(d,e.setupUrl,n),children:["Setup the Cloud sandbox",k.jsx(vf,{size:13})]})]}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{className:"git-dialog-secondary",disabled:o,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?k.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:d=>Cf(d,e.setupUrl,n),children:["Open setup",k.jsx(vf,{size:13})]}):null:k.jsx("button",{className:"git-dialog-primary",disabled:o,type:"button",onClick:a,children:o?"Uploading":s?"Try again":l?"Show setup link":"Upload source"})]})]})})}function Cf(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function L9(e){return!Number.isFinite(e)||e<=0?"0 B":e<1024?`${Math.round(e)} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function lS({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const o=[L9(e),`${t} skipped`],r=H9(n);return r&&o.push(`local ${r}`),o.push(a),o.join(" · ")}function H9(e){const t=e?.trim();return t?t.slice(0,7):null}const U9=v.lazy(()=>ur(()=>import("./CommandMenu-DggN2ygj.js"),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.CommandMenu}))),q9=v.lazy(()=>ur(()=>import("./SettingsView-1XN7KLBl.js"),__vite__mapDeps([4,1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21])).then(e=>({default:e.SettingsView}))),z9=v.lazy(()=>ur(()=>import("./NewProjectDialog-B8pWvSkq.js"),__vite__mapDeps([22,1,2,8,13,23])).then(e=>({default:e.NewProjectDialog}))),B9=v.lazy(()=>ur(()=>import("./WorkspaceGitDialogs-mE3Og6Zo.js"),__vite__mapDeps([24,1,2,11,12,25,21])).then(e=>({default:e.CommitDialog}))),F9=v.lazy(()=>ur(()=>import("./WorkspaceGitDialogs-mE3Og6Zo.js"),__vite__mapDeps([24,1,2,11,12,25,21])).then(e=>({default:e.BranchDialog})));function V9({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:r,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:g,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:P,teamChatThreads:M,onTeamChatNotificationModeChange:C,onTeamChatThreadMuteChange:$,diffPanelWidth:O,diffPanelResizing:j,diffPanelExpanded:x,onDiffPanelResizeStart:R,onDiffPanelExpandedChange:E}){return k.jsx(v.Suspense,{fallback:null,children:k.jsx(q9,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:r,onToast:s,onBack:l,onOpenSourceSession:m,onStartRefinerAuthoring:d,onAcceptEvaluationReview:h,onOpenSkill:g,onOpenExtension:y,teamChatCurrentUserId:w,teamChatEnabled:_,teamChatNotificationMode:P,teamChatThreads:M,onTeamChatNotificationModeChange:C,onTeamChatThreadMuteChange:$,diffPanelWidth:O,diffPanelResizing:j,diffPanelExpanded:x,onDiffPanelResizeStart:R,onDiffPanelExpandedChange:E})})}function K9({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:o,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:l,canPublishOpenPondProject:m,expandProject:d,newProjectBusy:h,newProjectDialogOpen:g,newProjectDirectory:y,newProjectMode:w,newProjectName:_,newProjectPath:P,projectRows:M,query:C,searchOpen:$,visibleWorkspaceDiff:O,visibleWorkspaceState:j,workspaceBusy:x,appDispatch:R,beginNewChat:E,openDefaultsSettingsFromBranchDialog:H,setBranchDialogName:B,setBranchDialogOpen:D,setCommitDialogOpen:J,setCommitDraft:le,setCommitIncludeUnstaged:ue,setCommitMessage:je,setCommitNextStep:ke,setNewProjectDialogOpen:te,setNewProjectName:Me,setNewProjectPath:ye,setQuery:ne,setSearchOpen:be,submitCommitDialog:ae,submitCreateWorkspaceBranch:de,submitNewProjectDialog:xe}){return k.jsxs(k.Fragment,{children:[$&&k.jsx(v.Suspense,{fallback:null,children:k.jsx(U9,{open:$,query:C,projects:M,sessions:e,onQueryChange:ne,onClose:()=>{be(!1),ne("")},onNewChat:()=>{be(!1),ne(""),E()},onOpenProject:De=>{R({type:"selectProject",projectId:De.id}),R({type:"patch",patch:{searchOpen:!1,query:""}}),d(De.id)},onOpenSession:De=>{R({type:"selectSession",sessionId:De.id,appId:De.appId,projectId:De.workspaceKind==="local_project"&&De.workspaceId?St("local",De.workspaceId):null}),R({type:"patch",patch:{searchOpen:!1,query:""}})}})}),g&&k.jsx(v.Suspense,{fallback:null,children:k.jsx(z9,{open:g,mode:w,name:_,path:P,directory:y,busy:h,onNameChange:Me,onPathChange:ye,onClose:()=>{h||te(!1)},onSubmit:xe})}),a&&k.jsx(v.Suspense,{fallback:null,children:k.jsx(B9,{open:a,branch:j?.currentBranch??null,filesChanged:O?.filesChanged??j?.changedFilesCount??0,additions:O?.additions??0,deletions:O?.deletions??0,message:s,includeUnstaged:r,nextStep:l,draft:o,busy:x,canPush:!!j?.remoteUrl,canPublish:m,onMessageChange:je,onIncludeUnstagedChange:ue,onNextStepChange:ke,onDraftChange:le,onClose:()=>{x||J(!1)},onSubmit:ae})}),n&&k.jsx(v.Suspense,{fallback:null,children:k.jsx(F9,{open:n,branchName:t,busy:x,onBranchNameChange:B,onSetPrefix:H,onClose:()=>{x||D(!1)},onSubmit:de})})]})}function WC({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return k.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[k.jsx("span",{className:"app-toast-message",children:e.message}),n&&k.jsx("div",{className:"app-toast-actions",children:k.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}const yr=v.createContext(null);function W9({children:e}){const[t,n]=v.useState(null),[a,o]=v.useState(null),[r,s]=v.useState(null),l=v.useMemo(()=>({title:t,actions:a,activity:r,setTitle:n,setActions:o,setActivity:s}),[t,a,r]);return k.jsx(yr.Provider,{value:l,children:e})}function Wee({children:e}){return k.jsx(yr.Provider,{value:null,children:e})}function G9({children:e,className:t=""}){const n=v.useContext(yr);return k.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?k.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function J9({className:e=""}){const t=v.useContext(yr);return k.jsx("div",{ref:t?.setActions,className:e})}function Gee({title:e,actions:t,fallback:n,children:a}){const o=v.useContext(yr);return o?k.jsxs(k.Fragment,{children:[o.title?vu.createPortal(k.jsx("div",{className:"page-chrome-title",children:e}),o.title):null,o.actions&&t?vu.createPortal(t,o.actions):null,a]}):n??k.jsxs("header",{children:[e,t]})}function cS(){const e=v.useContext(yr);return k.jsx("div",{ref:e?.setActivity})}function Jee({children:e}){const t=v.useContext(yr);return t?.activity?vu.createPortal(e,t.activity):null}async function Z9(e){if(!e)return!1;try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch(t){console.warn("Clipboard write failed",t)}try{const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.left="-1000px",t.style.top="-1000px",document.body.appendChild(t),t.select();const n=document.execCommand("copy");return t.remove(),n}catch(t){return console.warn("Clipboard fallback failed",t),!1}}function Y9({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return k.jsxs("div",{className:"titlebar-collaboration-actions",children:[k.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:k.jsx(cm,{size:16})}),k.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:k.jsx(cC,{size:16})})]})}const Q9=v.lazy(()=>ur(()=>import("./WorkspaceEnvironmentMenu-Dr-E0c1j.js"),__vite__mapDeps([26,1,2,17,23,5,12,27,25,28])).then(e=>({default:e.WorkspaceEnvironmentMenu})));function X9({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:o,workspaceName:r,workspaceId:s,busy:l,workspaceState:m,workspaceKind:d,selectedApp:h,selectedProject:g,workspaceDiff:y,managedWorkspace:w,workspaceBusy:_,defaultTeamId:P,showDiffControls:M,diffPanelOpen:C,terminalOpen:$,rightSidebarAvailable:O=!1,rightSidebarOpen:j=!1,onToggleDiffPanel:x,onToggleRightSidebar:R,onOpenSearch:E,onToggleTerminal:H,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:J,onWorkspaceBranchChange:le,onWorkspaceBranchCreate:ue,connection:je,onBootstrap:ke,onOpenSandboxWorkspace:te,onShowSidebar:Me,onOpenTeamChat:ye,onDiscoverCommunities:ne,collaborationView:be=null,platform:ae,showWorkspaceControls:de=!0}){const xe=y?.filesChanged??0,De=um()&&!Kv(ae),we=!!(ye||ne)||de||O||De,[ie,Se]=v.useState(null);v.useEffect(()=>{if(!ie)return;const Ke=()=>Se(null);return window.addEventListener("pointerdown",Ke),window.addEventListener("blur",Ke),window.addEventListener("resize",Ke),()=>{window.removeEventListener("pointerdown",Ke),window.removeEventListener("blur",Ke),window.removeEventListener("resize",Ke)}},[ie]);const Ue=Ke=>{Ke.preventDefault(),Ke.stopPropagation();const tt=190,ze=n?76:42;Se({x:Math.min(Ke.clientX,window.innerWidth-tt-8),y:Math.min(Ke.clientY,window.innerHeight-ze-8)})},Je=Ke=>{Z9(Ke),Se(null)};return k.jsxs("header",{className:"app-titlebar",children:[k.jsxs("div",{className:"titlebar-left",children:[!e&&k.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:Me,children:k.jsx(dC,{size:16})}),o?k.jsx("button",{className:"titlebar-icon",type:"button","aria-label":o.label,title:o.label,onClick:o.onSelect,children:k.jsx(S6,{size:16})}):null,k.jsx(G9,{children:a?.length?k.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((Ke,tt)=>{const ze=tt===a.length-1;return k.jsxs("div",{className:"titlebar-breadcrumb-item",children:[Ke.onSelect&&!ze?k.jsx("button",{type:"button",onClick:Ke.onSelect,children:Ke.label}):k.jsx("strong",{children:Ke.label}),!ze&&k.jsx(dr,{size:14})]},`${Ke.label}-${tt}`)})}):k.jsxs("div",{className:"titlebar-title",children:[k.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:Ue,children:t}),r&&k.jsx("span",{children:r})]})})]}),we&&k.jsxs("div",{className:"titlebar-right",children:[k.jsx(J9,{className:"page-chrome-actions"}),de?null:k.jsx(cS,{}),k.jsx(Y9,{activeView:be,onDiscoverCommunities:ne,onOpenTeamChat:ye}),de&&k.jsxs("div",{className:"titlebar-actions",children:[k.jsx(v.Suspense,{fallback:null,children:k.jsx(Q9,{mode:"topbar",busy:l,workspaceState:m,workspaceId:s,workspaceKind:d,selectedApp:h,selectedProject:g,workspaceBusy:_,defaultTeamId:P,workspaceDiff:y,managedWorkspace:w,showDiffControls:M,diffPanelOpen:C,onToggleDiffPanel:x,onRunTerminalCommand:B,onWorkspaceToolAction:D,onOpenCommitDialog:J,onWorkspaceBranchChange:le,onWorkspaceBranchCreate:ue,connection:je,onBootstrap:ke,onOpenSandboxWorkspace:te})}),k.jsx(cS,{}),k.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:E,children:k.jsx(hV,{size:16})}),k.jsx("button",{type:"button",className:`titlebar-icon ${$?"active":""}`,title:`${$?"Hide":"Show"} terminal`,"aria-label":`${$?"Hide":"Show"} terminal`,"aria-pressed":$,onClick:H,children:k.jsx(pC,{size:16})}),M&&k.jsx("button",{type:"button",className:`topbar-diff-button ${j?"active":""}`,title:`${j?"Hide":"Show"} sidebar${xe?`, ${xe} changed files`:""}`,"aria-label":`${j?"Hide":"Show"} sidebar`,"aria-pressed":j,onClick:x,children:k.jsx(Ih,{size:16})})]}),O&&R&&!M?k.jsx("div",{className:"titlebar-actions",children:k.jsx("button",{type:"button",className:`topbar-diff-button ${j?"active":""}`,title:`${j?"Hide":"Show"} sidebar`,"aria-label":`${j?"Hide":"Show"} sidebar`,"aria-pressed":j,onClick:R,children:k.jsx(Ih,{size:16})})}):null,k.jsx(wV,{platform:ae})]}),ie&&k.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:ie.x,top:ie.y},onPointerDown:Ke=>Ke.stopPropagation(),children:[k.jsx("button",{type:"button",role:"menuitem",onClick:()=>Je(t),children:"Copy title"}),n&&k.jsx("button",{type:"button",role:"menuitem",onClick:()=>Je(n),children:"Copy conversation ID"})]})]})}function eW(){const[e,t]=v.useState(null),n=v.useRef(null),a=v.useCallback(r=>new Promise(s=>{n.current?.resolve(!1);const l={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:s};n.current=l,t(l)}),[]),o=v.useCallback(r=>{const s=n.current;n.current=null,t(null),s?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:o}}function tW({state:e,onResolve:t}){const n=v.useId(),a=v.useId();if(v.useEffect(()=>{if(!e)return;function r(s){s.key==="Escape"&&t(!1)}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,e]),!e)return null;const o=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return k.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:k.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:r=>r.stopPropagation(),children:[k.jsx("h2",{id:n,children:e.title}),k.jsx("p",{id:a,children:e.body}),k.jsxs("div",{className:"git-dialog-footer",children:[k.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),k.jsx("button",{type:"button",className:o,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function nW(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=eW();return{confirmProjectAction:v.useCallback(o=>e({tone:"danger",...o}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function aW({state:e,onResolve:t}){return k.jsx(tW,{state:e,onResolve:t})}const yu=new Map,oW=(e,t,n)=>{const a=yu.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,yu.set(e,a)};function iW({children:e,id:t}){return k.jsx(v.Profiler,{id:t,onRender:oW,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...yu.entries()].map(([e,t])=>[e,{...t}])),reset:()=>yu.clear()});const rW=v.lazy(()=>ur(()=>import("./MainPane-Cs2Kng_k.js").then(e=>e.o),__vite__mapDeps([29,1,2,11,30,7,27,8,5])).then(e=>({default:e.MainPane})));function sW({className:e,style:t,sidebar:n,topBar:a,mainPane:o,cloudSetup:r,projectConfirm:s,lazyPanels:l,toast:m}){return k.jsx(W9,{children:k.jsxs("div",{className:e,style:t,children:[k.jsx(iW,{id:"sidebar",children:k.jsx(j9,{...n})}),k.jsxs("div",{className:"content-shell",children:[k.jsx(X9,{...a}),k.jsx(v.Suspense,{fallback:k.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:k.jsx(rW,{...o})})]}),k.jsx(D9,{...r}),k.jsx(aW,{...s}),k.jsx(K9,{...l}),k.jsx(WC,{...m})]})})}function lW({settings:e,toast:t}){return k.jsxs(k.Fragment,{children:[k.jsx(V9,{...e}),k.jsx(WC,{...t})]})}const Bd="OpenPond".split("");function cW({visibleLetterCount:e=Bd.length}){const t=Bd.slice(0,Math.max(0,Math.min(e,Bd.length)));return k.jsxs("div",{className:"app-splash-lockup",children:[k.jsx("div",{className:"app-splash-mark",children:k.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:b9})}),k.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>k.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const Rf=Bd.length,dW=520,uW=240;function dS(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function mW({startup:e}){const[t,n]=v.useState(()=>dS()?Rf:0);return v.useEffect(()=>{if(dS()){n(Rf);return}const a=Array.from({length:Rf},(o,r)=>window.setTimeout(()=>n(r+1),dW+uW*r));return()=>{a.forEach(o=>window.clearTimeout(o))}},[]),k.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[k.jsx(cW,{visibleLetterCount:t}),k.jsx("span",{className:"app-splash-status",children:e.label})]})}const cb=5e3;function zo(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const o of[...e,...t])n.has(o.id)||(n.add(o.id),a.push(o));return a}function qo(e,t,n=cb){return Fd(zo(e,t),n)}function Fd(e,t=cb){return e.length<=t?e:e.slice(e.length-t)}function pW(e,t,n){return n.length===0?e:{...e,[t]:zo(e[t]??[],n)}}function fW(e,t){if(t.length===0)return Fd(e);if(e.length===0)return Fd(t);const n=new Map;let a=0;for(const o of[...e,...t])n.has(o.id)||n.set(o.id,{event:o,index:a}),a+=1;return Fd([...n.values()].sort((o,r)=>gW(o,r)).map(({event:o})=>o))}function Su(e){let t=null;for(const n of e)typeof n.sequence=="number"&&(t=t===null?n.sequence:Math.max(t,n.sequence));return t}function hW(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function gW(e,t){const n=e.event.sequence,a=t.event.sequence;if(typeof n=="number"&&typeof a=="number"){const s=n-a;if(s!==0)return s}const o=Date.parse(e.event.timestamp),r=Date.parse(t.event.timestamp);if(Number.isFinite(o)&&Number.isFinite(r)){const s=o-r;if(s!==0)return s}return e.index-t.index}function uS(e){if(e<1e3)return String(e);const t=e/1e3;return t>=10||Number.isInteger(t)?`${Math.round(t)}k`:`${t.toFixed(1)}k`}function vW(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function mS(e,t){const n=e?.triggerPercent??85;return e?.autoEnabled===!1?t>=n?"Auto compaction is off. Start a new chat or turn it on before the provider limit is reached.":"Auto compaction is off.":`Auto compacts at ${n}% context when supported.`}function bW(e){return e==="codex"}function yW(e){return e==="openpond"}function GC(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=c$.safeParse(n.data);if(a.success)return a.data}return null}function JC(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,o=Math.min(100,Math.round(e.snapshot.percentFull)),r=`${o}% full`,s=`${uS(n)} / ${uS(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:o,summary:r,tokensLabel:s,detail:mS(e.preferences,o),tooltip:`Context window: ${r} ${s}. ${mS(e.preferences,o)}`,tone:vW(o)}}if(bW(e.provider)){const n="Context is managed by Codex app-server.";return{usedTokens:0,maxTokens:null,percent:null,summary:"Managed externally",tokensLabel:"Codex app-server",detail:n,tooltip:`Context window: ${n}`,tone:"unknown"}}if(!yW(e.provider)){const n="Context pressure is unavailable until this provider has model context metadata.";return{usedTokens:0,maxTokens:null,percent:null,summary:"Limit unknown",tokensLabel:"Provider metadata unavailable",detail:n,tooltip:`Context window: ${n}`,tone:"unknown"}}const t="Send a message to measure hosted context.";return{usedTokens:0,maxTokens:null,percent:null,summary:"Not measured yet",tokensLabel:"Hosted context",detail:t,tooltip:`Context window: ${t}`,tone:"unknown"}}function db(e){let t=!1;const n=ZC(e);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(SW(o)){t=!0;continue}const r=As(o?.data);if(!(o?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const s=ub(As(r.goal),Xn(r.provider),n);if(s){const l=cc(s);return t&&l.tone==="active"?null:l}}if(r.kind==="goal_context"){const s=QC(o.output??"",Xn(r.provider)??"codex",n);if(s){const l=cc(s);return t&&l.tone==="active"?null:l}}}}return null}function xu(e){const t=ZC(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],o=As(a?.data);if(!(a?.name!=="diagnostic"||!o)){if(o.kind==="thread_goal_cleared"&&o.synthetic!==!0)return null;if(o.kind==="thread_goal"){const r=ub(As(o.goal),Xn(o.provider),t);if(!r)continue;const s=cc(r);return s.tone==="active"?s:null}if(o.kind==="goal_context"){const r=QC(a.output??"",Xn(o.provider)??"codex",t);if(!r)continue;const s=cc(r);return s.tone==="active"?s:null}}}return null}function Pf(e){const t=As(As(e)?.codexGoalRuntime),n=ub(t,Xn(t?.provider)??"codex");if(!n)return null;const a=cc(n);return a.tone==="active"?a:null}function SW(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function cc(e){const t=XC(e.status),n=nR(e.timeUsedSeconds),a=`Goal ${n}`,o=e.tokensUsed===null?null:e.tokenBudget===null?`${Af(e.tokensUsed)} tokens`:`${Af(e.tokensUsed)} / ${Af(e.tokenBudget)} tokens`,r=o?`${e.statusLabel} · ${o}`:e.statusLabel;return{objective:e.objective,status:e.status,timeUsedSeconds:e.timeUsedSeconds,tokensUsed:e.tokensUsed,tokenBudget:e.tokenBudget,actionLabel:t.actionLabel,timeLabel:n,label:a,detail:r,tooltip:`Goal runtime: ${aR(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function xW(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=YC(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,o=nR(a);return{...e,timeUsedSeconds:a,timeLabel:o,label:`Goal ${o}`,tooltip:`Goal runtime: ${aR(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function ub(e,t=null,n=null){if(!e)return null;const a=Xn(e.objective)??"Active goal",o=Xn(e.status)??"active";if(($h(t)??$h(Xn(e.provider)))!=="codex")return null;const s=n??Xn(e.updatedAt)??Xn(e.updated_at)??null,l=Jr(e.timeUsedSeconds)??Jr(e.time_used_seconds)??0,m=Xn(e.activeSinceAt)??Xn(e.active_since_at),d=XC(o).tone==="active"?YC(m??Xn(e.createdAt)??Xn(e.created_at),s):0,h=m?l+d:Math.max(l,d),g=Jr(e.tokensUsed)??Jr(e.tokens_used),y=Jr(e.tokenBudget)??Jr(e.token_budget);return{objective:a,status:o,statusLabel:tR(o),timeUsedSeconds:Math.max(0,Math.floor(h)),tokensUsed:g===null?null:Math.max(0,Math.floor(g)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),observedAt:s}}function ZC(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t]?.timestamp;if(n&&Number.isFinite(Date.parse(n)))return n}return null}function YC(e,t){if(!e||!t)return 0;const n=Date.parse(e),a=Date.parse(t);return!Number.isFinite(n)||!Number.isFinite(a)||a<=n?0:Math.floor((a-n)/1e3)}function QC(e,t=null,n=null){if(!e.trim()||$h(t)!=="codex")return null;const a=eR(e,"Status")??"active",o=bl(e,"Tokens used"),r=bl(e,"Token budget"),s=bl(e,"Time used seconds")??bl(e,"Time spent pursuing goal")??bl(e,"Elapsed seconds")??0;return{objective:pS(e,"objective")??pS(e,"untrusted_objective")??"Active goal",status:a,statusLabel:tR(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:o,tokenBudget:r,observedAt:n}}function XC(e){switch(kW(e)){case"active":case"running":return{tone:"active",actionLabel:"Pursuing goal"};case"paused":return{tone:"paused",actionLabel:"Goal paused"};case"blocked":return{tone:"limited",actionLabel:"Goal blocked"};case"complete":case"completed":case"achieved":return{tone:"done",actionLabel:"Goal achieved"};case"failed":return{tone:"limited",actionLabel:"Goal failed"};case"cancelled":case"canceled":case"stopped":return{tone:"limited",actionLabel:"Goal cancelled"};case"budget_limited":return{tone:"limited",actionLabel:"Goal budget limited"};default:return{tone:"active",actionLabel:"Goal status unknown"}}}function kW(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function eR(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function bl(e,t){const n=eR(e,t);if(!n)return null;const a=n.replace(/,/g,""),o=/-?\d+(?:\.\d+)?/.exec(a);if(!o)return null;const r=Number(o[0]);return Number.isFinite(r)?r:null}function pS(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function tR(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function nR(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),a=t%60;return a>0?`${n}h ${a}m`:`${n}h`}function aR(e){if(e<60)return`${e} ${e===1?"second":"seconds"}`;const t=Math.floor(e/60);if(t<60)return`${t} ${t===1?"minute":"minutes"}`;const n=Math.floor(t/60),a=t%60;return a===0?`${n} ${n===1?"hour":"hours"}`:`${n}h ${a}m`}function Af(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${fS(n,2)}M`:n<100?`${fS(n,1)}M`:`${Math.round(n)}M`}const t=e/1e3;return t>=10||Number.isInteger(t)?`${Math.round(t)}k`:`${t.toFixed(1)}k`}function fS(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function As(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Xn(e){return typeof e=="string"&&e.trim()?e.trim():null}function $h(e){return e?.trim().toLowerCase()||null}function Jr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const wW=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),IW=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function Nh(e){const t=oR(e);return t?PW(t):null}function oR(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=RW(jW(n.data));if(a)return a}return null}function _W(e){if(e.events)return oR(e.events);const t=e.messages??[];for(let n=t.length-1;n>=0;n-=1){const a=t[n]?.createImproveRun??null;if(a)return a}return null}function CW(e,t){const n=e?.target.displayName?.trim()??"",a=n.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();return n&&!/^(?:create|creating|improve|improving|new) (?:an )?agent$/.test(a)?n:t}function RW(e){const t=bc.safeParse(e?.createImproveRun);return t.success?t.data:null}function PW(e){const t=AW(e);if(!t)return null;const n=TW(e.createdAt,e.updatedAt),a=e.blockedReason??EW(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:MW(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function AW(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return wW.has(t)?{tone:"active",actionLabel:`${n} running`}:IW.has(t)?{tone:"active",actionLabel:`${n} awaiting input`}:t==="blocked"?{tone:"limited",actionLabel:`${n} blocked`}:t==="failed"?{tone:"limited",actionLabel:`${n} failed`}:t==="cancelled"?{tone:"limited",actionLabel:`${n} cancelled`}:t==="ready"||t==="ready_local"?{tone:"done",actionLabel:e.target.kind==="agent"?"Agent ready":"Workproduct ready"}:t==="published_hosted"?{tone:"done",actionLabel:e.target.kind==="agent"?"Agent published":"Workproduct published"}:null}function TW(e,t){const n=Date.parse(e),a=Date.parse(t);return!Number.isFinite(n)||!Number.isFinite(a)||a<n?0:Math.floor((a-n)/1e3)}function EW(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function MW(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),a=t%60;return a>0?`${n}h ${a}m`:`${n}h`}function jW(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function iR(e,t){if(!t)return null;const n=new Map,a=[];for(const j of e){if(!j.name.startsWith("subagent."))continue;const x=NW(j);x&&a.push(x);const R=$W(j);R?.parentSessionId===t&&n.set(R.id,R)}if(n.size===0)return null;const o=[...n.values()].sort((j,x)=>Yr(x).localeCompare(Yr(j))),r=o.filter(j=>j.status==="queued"||j.status==="running"),s=o.filter(j=>j.status==="completed"),l=o.filter(j=>j.status==="failed"),m=o.filter(j=>j.status==="cancelled"),d=o.filter(j=>j.status==="needs_resume"),h=[...s,...l,...m].sort((j,x)=>Yr(x).localeCompare(Yr(j))),g=o.reduce((j,x)=>{const R=Ts(x.metadata?.usage);return j.totalTokens+=xd(R?.totalTokens),j.promptTokens+=xd(R?.promptTokens),j.completionTokens+=xd(R?.completionTokens),j.requestCount+=xd(R?.requestCount),j},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=o.flatMap(j=>rR([...j.report?.blockers??[],j.error,j.progress.currentBlocker]).map(x=>({runId:j.id,roleId:j.roleId,status:j.status,message:x}))),w=o.flatMap(j=>sR([...j.report?.artifacts??[],j.report?.patchRef,j.report?.diffRef,...j.progress.patchRefs]).map(x=>({...x,runId:j.id,roleId:j.roleId}))),_=h.map(j=>OW(j,a)),P=o[0]??null,M=P?{runId:P.id,roleId:P.roleId,status:P.status,message:P.progress.latestMeaningfulActivity||P.report?.summary||P.objective,updatedAt:Yr(P)}:null,C=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${h.length} ${h.length===1?"child":"children"} finished`,$=[r.length?`${r.length} active`:null,s.length?`${s.length} completed`:null,l.length?`${l.length} failed`:null,m.length?`${m.length} cancelled`:null,d.length?`${d.length} paused`:null].filter(Boolean).join(" · "),O=M?`${HW(M.roleId)}: ${M.message}`:"";return{sessionId:t,runs:o,activeRuns:r,completedRuns:s,failedRuns:l,cancelledRuns:m,needsResumeRuns:d,terminalRuns:h,latestRun:P,latestMeaningfulUpdate:M,activeCount:r.length,completedCount:s.length,failedCount:l.length,cancelledCount:m.length,needsResumeCount:d.length,terminalCount:h.length,usage:g,blockers:y,evidenceRefs:w,finalResults:_,testsRunCount:o.reduce((j,x)=>j+x.progress.validationAttempts.length,0),label:C,tooltip:[$,O].filter(Boolean).join(". ")}}function OW(e,t){return{runId:e.id,roleId:e.roleId,status:e.status,objective:e.objective,summary:e.report?.summary||e.error||"Child conversation finished.",findings:e.report?.findings??[],changedFiles:e.progress.changedFiles,refs:sR([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:rR([...e.report?.blockers??[],e.error]),confidence:e.report?.confidence??null,importantMessages:t.filter(n=>n.fromRunId===e.id).map(n=>({id:n.id,runId:e.id,fromRunId:n.fromRunId,kind:n.kind,body:n.body,createdAt:n.createdAt})),workspaceRetention:DW(e),updatedAt:Yr(e)}}function $W(e){const t=Ts(e.data),n=[t?.run,Ts(t?.message)?.run];for(const a of n){const o=Pk.safeParse(a);if(o.success)return o.data}return null}function NW(e){const t=AO.safeParse(Ts(e.data)?.message);return t.success?t.data:null}function DW(e){const t=Ts(Ts(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Sd(t.reason),retainedAt:Sd(t.retainedAt),expiresAt:Sd(t.expiresAt),retentionDays:LW(t.retentionDays),trigger:Sd(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Yr(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function rR(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function sR(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function Ts(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Sd(e){return typeof e=="string"&&e.trim()?e.trim():null}function xd(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function LW(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function HW(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Dh=[];function Lh(e,t){return lR(e,t,null)}function lR(e,t,n){const a=n&&FW(n.events,e)?qW(n.indexes,n.events.length,e):UW(e),o=BW(t);return{...a,...o}}function UW(e){const t=new Map;for(const n of e){if(!n.sessionId)continue;const a=t.get(n.sessionId);a?a.push(n):t.set(n.sessionId,[n])}return zW(t)}function qW(e,t,n){const a=new Map(e.eventsBySessionId),o=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),l=new Set(e.activeGoalSessionIds),m=new Set(e.activeSubagentSessionIds),d=new Set;for(let h=t;h<n.length;h+=1){const g=n[h];if(!g.sessionId)continue;if(d.has(g.sessionId)){a.get(g.sessionId).push(g);continue}const y=a.get(g.sessionId);a.set(g.sessionId,y?[...y,g]:[g]),d.add(g.sessionId)}for(const h of d){const g=a.get(h)??Dh,y=GC(g);y?o.set(h,y):o.delete(h);const w=dR(g);w?(r.set(h,w),w.tone==="active"?l.add(h):l.delete(h)):(r.delete(h),l.delete(h));const _=iR(g,h);_?(s.set(h,_),cR({sessionEvents:g,sessionId:h,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:l}),_.activeCount>0?m.add(h):m.delete(h)):(s.delete(h),m.delete(h))}return{eventsBySessionId:a,latestContextUsageBySessionId:o,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:l,activeSubagentSessionIds:m}}function zW(e){const t=new Map,n=new Map,a=new Map,o=new Set,r=new Set;for(const[s,l]of e){const m=GC(l);m&&t.set(s,m);const d=dR(l);d&&(n.set(s,d),d.tone==="active"&&o.add(s))}for(const[s,l]of e){const m=iR(l,s);m&&(a.set(s,m),cR({sessionEvents:l,sessionId:s,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:o}),m.activeCount>0&&r.add(s))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:o,activeSubagentSessionIds:r}}function cR(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=xu(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function dR(e){return Nh(e)??db(e)??xu(e)}function BW(e){const t=new Map,n=new Map,a=new Map,o=new Map;for(const r of e){t.set(r.id,r);const s=n.get(r.status);if(s?s.push(r):n.set(r.status,[r]),r.status!=="pending")continue;const l=a.get(r.sessionId);l?l.push(r):a.set(r.sessionId,[r]);const m=o.get(r.sessionId);(!m||hS(r.createdAt)>hS(m.createdAt))&&o.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:o}}function FW(e,t){return e===t?!0:e.length>t.length||e.length===t.length?!1:e.length===0?!0:e[0]===t[0]&&e[e.length-1]===t[e.length-1]}function Hc(e,t){return t?e.eventsBySessionId.get(t)??Dh:Dh}function uR(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function mR(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function VW(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function KW(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function hS(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function WW(e,t){return e?.conversationId===t}function GW(e,t){return e?.id===t?null:e}function JW(e){const t=new Set;if(e.readmePath){const n=e.readmePath.replaceAll("\\","/").split("/").at(-1);n&&t.add(n)}for(const n of e.skills){t.add(n.relativePath);const a=n.relativePath.lastIndexOf("/"),o=a>=0?n.relativePath.slice(0,a):"";for(const r of n.resourceFiles)t.add(o?`${o}/${r}`:r)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function ZW(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function Zee(e,t){return e.profiles.find(n=>ZW(n.ref)===t)?.ref??null}function YW(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function Yee(e,t){return e.profiles.find(n=>YW(n.ref,t))?.state??null}function QW(e,t){const n=new Map(eL.map(a=>[a.name,{...a,validationMessages:[...a.validationMessages],resourceFiles:[...a.resourceFiles]}]));for(const a of e?.skills??[])n.has(a.name)||n.set(a.name,a);for(const a of t?.extensions??[])if(a.validationStatus==="valid")for(const o of a.skills)o.validationStatus!=="valid"||n.has(o.name)||n.set(o.name,{name:o.name,description:o.description,path:o.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:o.charCount,sourceHash:o.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:o.resourceFiles});return[...n.values()].sort((a,o)=>a.name.localeCompare(o.name))}function XW(e){return{sourceTaskId:e.sourceTaskId,sourceExperience:e.sourceExperience,targetExperience:e.targetExperience,sourceMessageIds:[...e.sourceMessageIds??[]],sourceContext:e.sourceContext?.trim()||null,outputId:e.output?.id??null,outputRevision:e.output?.revision??null,createdAt:e.createdAt??new Date().toISOString(),checkoutMutation:"none"}}function Qee(e,t){const n=`Continue from the attached Work output "${e.title}" (revision ${e.revision}).`;return t==="work"?`${n} Choose a Project or repository before making source changes; do not mutate a checkout until I choose it.`:n}const pR="openpond:last-chat-task-mode";function e8(e,t){return e==="labs"?"models":"chat"}function t8(e){try{return e.getItem(pR)==="work"?"work":"chat"}catch{return"chat"}}function mb(){if(typeof window>"u")return"chat";try{return t8(Lc)}catch{return"chat"}}function n8(e,t){try{e.setItem(pR,t==="chat"?"chat":"work")}catch{}}function a8(e){if(!(typeof window>"u"))try{n8(Lc,e)}catch{}}const o8="uploaded to a different account";function fR(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(o=>o.id===n.projectId&&o.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function Oa(e,t){const n=fR(e,t);return n.state==="confirmed"?n.cloudProject:null}function i8(e,t){return fR(e,t).state==="different_account"?o8:null}function Io(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function hR(e={}){return{...e,workspaceTarget:"hybrid"}}function r8(e={}){return{...e,workspaceTarget:"local"}}function _o(e){return e?.metadata?.workspaceTarget==="hybrid"}function s8(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function gR({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,o=e?Oa(n,e):null,r=t?.id??o?.id??(e?null:a?.projectId??null),s=t?.teamId??o?.teamId??(e?null:a?.teamId??null);return!r||!s?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:r,cloudTeamId:s,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??o?.name??a?.projectName??n?.name??"Hybrid workspace"}}function vR({modelRef:e,provider:t,target:n,title:a}){return{provider:t,...e?{modelRef:e}:{},appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:n.workspaceName,localProjectId:n.localProjectId,cloudProjectId:n.cloudProjectId,cloudTeamId:n.cloudTeamId,metadata:hR(),cwd:n.cwd,title:a}}function l8(e){return v.useEffect(()=>{const t=PC(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),v.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=aK(n);try{let o;const r=e.selectedSession;if(r&&sc(r))o=await Q.patchSession(e.connection,r.id,{title:a,metadata:wf(r.metadata,n)}),e.setSessions(s=>s.map(l=>l.id===o.id?o:l));else{const s=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,l=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),m=r?.modelRef??(l==="openpond"?{providerId:"openpond",modelId:ks}:{providerId:l,modelId:e.activeModel}),d=s?{workspaceTarget:s}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let h;if(!r&&e.workspaceTarget==="hybrid"){const g=gR({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(g.kind!=="ready")throw new Error(g.message);const y=vR({modelRef:m,provider:l,target:g,title:a});h={...y,experience:"work",metadata:wf(y.metadata,n)}}else h={experience:"work",provider:l,modelRef:m,openPondCommandAccessMode:r?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:r?.appId??null,appName:r?.appName??null,workspaceKind:r?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:r?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:r?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:r?.localProjectId??e.selectedProject?.id??null,cloudProjectId:r?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:r?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:r?.cwd??e.selectedProject?.workspacePath??null,metadata:wf(d,n),title:a};o=await Q.createSession(e.connection,h),e.setSessions(g=>[o,...g])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(o){return e.showToast(o instanceof Error?o.message:"Could not save task draft.","error"),!1}},[e.activeExperience,e.activeModel,e.activeOpenPondCommandAccessMode,e.activeProvider,e.cloudProjects,e.composerDraftStore,e.connection,e.requestComposerFocus,e.selectedCloudProject,e.selectedProject,e.selectedSession,e.setMentionedAppId,e.setSelectedSessionId,e.setSessions,e.setView,e.showToast,e.workspaceTarget])}const c8=[];function d8({primary:e,secondary:t}){const[n,a]=v.useState(null),o=v.useRef(new Set),[r,s]=v.useState(!1),[l,m]=v.useState(null),d=NV(),h=d?.kind==="models"&&["datasets","graders","experiments"].includes(d.route.page),{composerDraftStore:g,appDispatch:y,pendingTerminalCommand:w,setPendingTerminalCommand:_,terminalTabs:P,setTerminalTabs:M,trainingDetailTasksetId:C,setTrainingDetailTasksetId:$,mentionedAppId:O,setMentionedAppId:j,cloudSetupDialog:x,setCloudSetupDialog:R,rightPanelTabRequest:E,workspaceDiffPanelViewState:H,mainComposerFocusRequestId:B,requestMainComposerFocus:D,projectConfirmDialog:J,resolveProjectConfirmDialog:le,query:ue,searchOpen:je,archivedChatsOpen:ke,sectionMenuOpen:te,cloudProjectsExpanded:Me,sidebarOpen:ye,view:ne,selectedAppId:be,selectedProjectId:ae,selectedSessionId:de,codexPermissionMode:xe,codexReasoningEffort:De,busy:we,diffPanelOpen:ie,diffPanelExpanded:Se,rightPanelMode:Ue,activeExperience:Je,changeNewExperience:Ke,terminalOpen:tt,settingsSection:ze,newProjectDialogOpen:Ge,newProjectMode:qe,newProjectName:L,newProjectPath:N,newProjectBusy:q,commitDialogOpen:X,commitMessage:me,commitIncludeUnstaged:$e,commitNextStep:Le,commitDraft:nt,branchDialogOpen:at,branchDialogName:lt,toast:pt,labDetailNavigation:Oe,setQuery:Ye,setSearchOpen:f,setArchivedChatsOpen:U,setSectionMenuOpen:Y,setCloudProjectsExpanded:he,setChatRowsVisibleCount:re,setSidebarOpen:W,setView:I,setSelectedAppId:K,setSelectedProjectId:ee,setSelectedSessionId:Z,setPrompt:ce,setDraftProvider:pe,setDraftModel:fe,setDraftExperience:Ae,setDiffPanelOpen:_e,setDiffPanelExpanded:Ne,setRightPanelMode:Pe,setTerminalOpen:Xe,setSettingsSection:st,setNewProjectDialogOpen:rn,setNewProjectName:Et,setNewProjectPath:tn,setCommitDialogOpen:mn,setCommitMessage:pn,setCommitIncludeUnstaged:Wt,setCommitNextStep:Da,setCommitDraft:ga,setBranchDialogOpen:$n,setBranchDialogName:Pn,setError:$t,showToast:ht,applyBootstrapPayload:fn,bootstrap:bt,connection:jt,startup:va,training:Ut,pinnedCollapsed:hn,cloudProjectsCollapsed:it,chatsCollapsed:Cn,savedForLaterCollapsed:ao,sidebarWidth:oo,sidebarResizing:ra,diffPanelWidth:ba,diffPanelResizing:Nn,togglePinnedCollapsed:Po,toggleCloudProjectsCollapsed:La,toggleChatsCollapsed:V,toggleSavedForLaterCollapsed:He,startSidebarResize:Ie,startDiffPanelResize:Be,selectedApp:yt,selectedCloudProject:Jn,selectedProject:gn,selectedProjectLinkedApp:We,selectedSession:yn,sidebarSessions:ut,runtimeIndexes:An,runtimeEventStore:Ha,chatMentionApps:ri,connectedAppMentions:ya,pendingApproval:si,pendingChatUserMessages:$i,account:Ao,activeModel:Dn,activeProvider:Sa,appDefaults:Zn,startMessage:li,organizations:Ni,teamChatOrganization:ci,teamChatTeamId:di,teamChat:xt,publishTeamProfileAgent:Bs,communitySidebar:Di,communityView:Fs,teamAiThreadId:Sr,toggleTeamAiSidebar:Vs,activeOpenPondCommandAccessMode:To,viewWorkspaceAppId:Ks,viewWorkspaceId:xr,viewWorkspaceKind:kr,viewWorkspaceName:wr,selectedActionCatalog:Ws,expandedProjectIds:Gs,expandProject:io,toggleProjectExpanded:Js,changeCodexPermissionMode:Ir,changeCodexReasoningEffort:_r,changeOpenPondCommandAccessMode:ui,resolveApproval:Cr,beginNewChat:sa,beginNewChatWithTrainingModel:Zs,dismissTrainingChatHandoff:Li,trainingChatHandoff:Eo,selectTrainingChatTaskForComposer:Yn,chatHistoryLoadStates:Ys,loadMoreSelectedChatHistory:Qs,selectedPagedSessionEvents:Sn,activeSessions:mi,archivedSessions:xa,pinnedSessions:Ua,savedForLaterSessions:Hi,savedForLaterFiles:pi,sidebarFileBookmarks:Xs,setSidebarFileStatus:Rr,setSessions:Ui,projectRows:Mo,localProjectRows:fi,cloudProjectRows:hi,projectSessionRowsByProjectId:Pr,childSessionRowsByParentId:Ar,sidebarProjectIdBySessionId:ka,chatRows:wa,visibleChatRows:Tr,chatRowsVisibleCount:qi,sessionEvents:ro,goalRuntime:zi,subagentRuntime:jo,visibleChatMessages:Er,activeTerminalScope:Mr,terminalSummaries:jr,runningSessionIds:el,selectedSessionRunning:Or,sidebarGoalRuntimeBySessionId:$r,sidebarSubagentRuntimeBySessionId:tl,taskDragSessionId:gi,taskPreviewSessionIds:Nr,startTaskDrag:Bi,clearTaskDrag:so,previewTaskDrop:nl,commitTaskDrop:al,commitTaskPreviewDrop:ol,dragItem:il,startPinnedDrag:lo,clearSidebarDrag:Dr,previewPinnedDrop:rl,commitPinnedDrop:sl,commitPinnedPreviewDrop:ll,commandProjectRows:la,contextWindowStatus:Lr,pinnedRows:cl,workspaceBusy:ct,diffBusy:Yt,visibleWorkspaceState:Qn,visibleWorkspaceDiff:sn,refreshVisibleWorkspaceDiff:Tn,managedWorkspace:ca,canSyncActiveWorkspace:xm,canPublishOpenPondProject:km,projectTarget:wm,workspaceTarget:qc}=e,{title:Im,browserConversationId:Fi,handleWorkspaceDiffPanelViewStateChange:zc,openSessionInChat:Hr,changeProjectTarget:_m,submitNewProjectDialog:Cm,changeWorkspaceBranch:Rm,openCommitDialog:Pm,openCreateWorkspaceBranchDialog:Am,openDefaultsSettingsFromBranchDialog:Tm,runWorkspaceTool:Em,submitCommitDialog:Mm,submitCreateWorkspaceBranch:jm,syncWorkspaceLocally:Om,answerCreateImproveQuestion:Bc,applyCreateImproveCandidate:$m,approveCreateImproveRun:Nm,cancelCreateImproveRun:Dm,changeDraftProvider:dl,openCreateImprovePullRequest:Fc,reconcileCreateImprovePullRequest:Lm,rejectCreateImproveCandidate:Hm,pauseCreateImproveRun:Vc,resumeCreateImproveRun:Kc,reviseCreateImproveRun:Um,stopTurn:Ur,archiveSession:qm,restoreSession:Wc,renameSession:zm,toggleSessionPinned:ul,toggleProjectPinned:Gc,toggleSessionSavedForLater:Jc,moveProjectToCloud:Bm,startCloudSetupUpload:Zc,changeWorkspaceTarget:Fm,sendPromptFromMainComposer:Vm,openSandboxWorkspace:Yc,openCloudProjectDialog:Km,openExistingProjectPathDialog:Qc,openUrlInBrowserPanel:Wm,showBrowserPanel:Gm,showChangesPanel:Jm,showGoalSidebarTab:vi,rightChatTrainingLaunchRequest:Xc,setRightChatTrainingLaunchRequest:Zm,closeRightChatPanel:Ym,openRightChatPanel:ml,rightChatPanelViews:Qm,showRightChatPanel:Xm,showRightPanelDiffTab:ep,submitRightChatPrompt:tp,activateRightChatPanel:np,updateRightChatModel:ap,updateRightChatPrompt:op,updateRightChatProvider:ip,updateRightChatScrollState:rp,openProfileSettings:sp,diagnosticEvents:lp,toggleRightSidebar:ed,removeProject:cp}=t,qa=bt?.account.activeProfile&&bt?.preferences.defaultTeamId?`${bt.account.activeProfile.handle}:${bt.preferences.defaultTeamId}`:null;v.useEffect(()=>{if(!(!qa||ne!=="chat"||d?.kind!=="chat"||d.sessionId||de||o.current.has(qa))){o.current.add(qa);try{const Te=localStorage.getItem(`openpond:ponder-mode:v1:${qa}`);(Te==="clean"||Te==="activity")&&a(Te)}catch{}}},[qa,d,ne,de]),v.useEffect(()=>{if(!(!qa||!o.current.has(qa)))try{localStorage.setItem(`openpond:ponder-mode:v1:${qa}`,n??"off")}catch{}},[qa,n]);const qr=v.useCallback(Te=>{K(null),ee(Te),Z(null),I("chat"),io(Te),D()},[io,D,K,ee,Z,I]),dp=v.useCallback((Te=null)=>{a(null);const rt=de?ka[de]??null:null;if(!Te&&rt){qr(rt);return}sa(Te)},[sa,qr,de,ka]),up=v.useCallback(async Te=>{if(!(!jt||!bt))try{const rt=await Q.savePreferences(jt,{defaultTeamId:Te});fn({...bt,preferences:rt.preferences})}catch(rt){const Nt=rt instanceof Error?rt.message:String(rt);throw $t(Nt),ht("Could not switch teams","error"),rt}},[fn,bt,jt,$t,ht]),mp=v.useCallback(async()=>{if(jt)try{const Te=await Q.signOutOpenPondAccount(jt);fn(Te);const rt=await Q.savePreferences(jt,{defaultTeamId:null});fn({...Te,preferences:rt.preferences}),ht("Logged out","success")}catch(Te){const rt=Te instanceof Error?Te.message:String(Te);throw $t(rt),ht("Could not log out","error"),Te}},[fn,jt,$t,ht]),pl=di??Zn.defaultTeamId??null,pp=v.useMemo(()=>Mo.filter(Te=>Te.kind==="local"||pl!==null&&Te.project.teamId===pl),[Mo,pl]),fp=v.useMemo(()=>{const Te={};for(const rt of mi){const Nt=ka[rt.id];Nt&&(Te[Nt]=(Te[Nt]??0)+1)}for(const rt of fi){if(rt.kind!=="local")continue;const Nt=rt.project.linkedSandboxProject?.projectId;if(!Nt||!rt.cloudLinkTrusted)continue;const Ia=St("cloud",Nt);Te[rt.id]=(Te[rt.id]??0)+(Te[Ia]??0)}return Te},[mi,fi,ka]),[td,Oo]=v.useState(null),[zr,Br]=v.useState(null),hp=QW(bt?.profile,bt?.extensionCatalog),[Vi,fl]=v.useState(null),[Fr,hl]=v.useState(null),[co,nd]=v.useState(null),gp=v.useCallback(()=>{K(null),ee(null),Z(null),Y(null),I("team")},[Y,K,ee,Z,I]),vp=v.useCallback(()=>{K(null),ee(null),Z(null),Y(null),Di.discoverCommunities()},[Di.discoverCommunities,Y,K,ee,Z]),bp=l8({activeExperience:Je,activeModel:Dn,activeOpenPondCommandAccessMode:To,activeProvider:Sa,cloudProjects:bt?.cloudProjects??c8,composerDraftStore:g,connection:jt,requestComposerFocus:D,selectedCloudProject:Jn,selectedProject:gn,selectedSession:yn,setMentionedAppId:j,setSelectedSessionId:Z,setSessions:Ui,setView:I,showToast:ht,workspaceTarget:qc.value}),yp=v.useCallback(async Te=>{if(!jt)throw new Error("OpenPond is not connected.");let rt=Sa,Nt=Dn;rt==="codex"&&(rt=Oh(bt?.providers,{enabledOnly:!0}).find(xn=>xn.value!=="codex")?.value??ir,Nt=gu(rt,bt?.providers)??Fl);const Ia=ut.find(xn=>xn.id===Te.sourceSessionId),$o=await Q.createSession(jt,{experience:Te.target,provider:rt,modelRef:{providerId:rt,modelId:Nt},openPondCommandAccessMode:To,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${Ia?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:XW({sourceTaskId:Te.sourceSessionId,sourceExperience:Ia?.experience??null,targetExperience:Te.target,sourceMessageIds:Te.sourceMessageIds??[],sourceContext:Te.sourceContext,output:Te.output})}});return Ui(xn=>[$o,...xn]),Ae(Te.target),pe(rt),fe(Nt),g.set(Te.prompt),Xt({kind:"chat",sessionId:$o.id}),y({type:"selectSession",sessionId:$o.id,appId:null,projectId:null}),K(null),ee(null),Xe(!1),I("chat"),Pe("home"),_e(Te.target==="work"),Ne(!1),$o},[Dn,To,Sa,y,bt?.providers,g,jt,Ne,_e,Ae,fe,pe,Pe,K,ee,Ui,Xe,I,ut]),Sp=v.useCallback(Te=>{fl(Te),hl(null),sa(null),W(!0)},[sa,W]),xp=v.useCallback(Te=>{sa(null),Ae("work"),g.set(`$openpond-refiner-authoring ${Te}`),I("chat"),W(!0)},[sa,g,Ae,W,I]),ad=v.useCallback(Te=>{hl(JW(Te)),fl(null),sa(null),W(!0)},[sa,W]);v.useEffect(()=>{!Vi&&!Fr||ne!=="chat"||de||ae||be||(Oo(Vi),Br(Fr),fl(null),hl(null),Pe("home"),Ne(!1),_e(!0))},[Vi,Fr,be,ae,de,Ne,_e,Pe,ne]),v.useEffect(()=>{!td&&!zr||ne==="chat"&&ie&&Ue==="home"||(Oo(null),Br(null))},[ie,zr,td,Ue,ne]);const od=v.useCallback(()=>{Oo(null),Br(null),Ne(!1),_e(!1)},[Ne,_e]),kp=v.useCallback(Te=>{let rt;if(Te.workspaceKind==="local"){const Nt=St("local",Te.workspaceId);rt=`draft:${Nt}`,K(null),ee(Nt),Z(null),io(Nt),I("chat")}else{const Nt=ut.find(Ia=>Ia.id===Te.sourceSessionId||Ia.workspaceId===Te.workspaceId);if(!Nt){ht("This saved file's cloud chat is no longer available.","error");return}rt=Nt.id,Hr(Nt.id)}Pe("changes"),_e(!0),nd({id:Date.now(),conversationId:rt,file:Te}),Te.available||ht(`File unavailable: ${Te.path}`,"error")},[io,Hr,_e,Pe,K,ee,Z,I,ht,ut]);v.useEffect(()=>{if(!WW(co,Fi))return;const Te=window.setTimeout(()=>{Pe("changes"),_e(!0),nd(rt=>GW(rt,co.id))},0);return()=>window.clearTimeout(Te)},[Fi,_e,Pe,co]);const wp=d?.kind==="models"&&d.route.area==="console"?"console":e8(ne);v.useEffect(()=>{if(d){if(d.kind==="models"||d.kind==="models_unavailable"){ne!=="labs"&&I("labs");return}if(d.kind==="settings"){K(null),ee(null),Z(null),st(d.section),ne!=="settings"&&I("settings");return}if(d.kind==="view"){K(null),ee(null),Z(null),ne!==d.view&&I(d.view);return}d.sessionId!==null&&(a(null),K(null),ee(null)),Z(d.sessionId),ne!=="chat"&&I("chat")}},[d,K,ee,Z,st,I,ne]);const Ip=v.useCallback(Te=>{if(Y(null),K(null),ee(null),Z(null),Te==="models"||Te==="console"){gs(Te==="console"?Za("datasets",null,{area:"console"}):Za()),I("labs");return}Te==="chat"&&Xt({kind:"chat",sessionId:null}),Ke(mb())},[Ke,Xt,Y,K,ee,Z,I]),_p=v.useCallback(async(Te,rt)=>{const Nt=await Ut.actions.acceptHarnessReview(Te,rt,{providerId:Sa,modelId:Dn},De);return Nt?($(Nt.materializedTasksetId??null),gs(Za()),I("labs"),!0):(ht("Taskset review could not be opened.","error"),!1)},[Dn,Sa,De,gs,Za,$,I,ht,Ut.actions]);if(!va.ready)return k.jsx(mW,{startup:va});if(ne==="settings")return k.jsx(rS,{showToast:ht,children:k.jsx(lW,{settings:{payload:bt,connection:jt,diagnostics:lp,initialSection:ze,onPayload:fn,onError:$t,onToast:ht,onOpenSourceSession:Hr,onStartRefinerAuthoring:xp,onAcceptEvaluationReview:_p,onOpenSkill:Sp,onOpenExtension:ad,teamChatCurrentUserId:xt.currentUserId,teamChatEnabled:di!==null,teamChatNotificationMode:xt.notificationMode,teamChatThreads:xt.threads,onTeamChatNotificationModeChange:xt.setNotificationMode,onTeamChatThreadMuteChange:xt.setThreadMuted,diffPanelWidth:ba,diffPanelResizing:Nn,diffPanelExpanded:Se,onDiffPanelResizeStart:Be,onDiffPanelExpandedChange:Ne,onBack:()=>{const Te=jV(d);Xt(Te),I(Te.kind==="models"?"labs":"chat"),W(!0)}},toast:{toast:pt,onDismiss:()=>y({type:"field",key:"toast",value:null})}})});const ot=um(),zt=jt?.platform??navigator.platform,Bt=ot&&Kv(zt),Ft=Mr,za=Qn?.initialized?Qn.repoPath:yn?.cwd??null,Cp={"--sidebar-width":`${oo}px`,"--diff-panel-width":`${ba}px`},xP=ne==="chat"&&Je!=="chat"||ne==="labs"||ne==="scheduled"&&r||ne==="team"&&!!Sr,kP=["app-shell",Bt?"platform-macos":"",ye?"sidebar-open":"sidebar-closed",ra?"sidebar-resizing":"",Nn?"diff-panel-resizing":""].filter(Boolean).join(" "),Rp=de?Ys[de]:null,wP=de?Rp?.cursorSequence??hW(qo(Sn,Hc(An,de))):null,IP=!!de&&!!jt&&(qt(de)?!0:!!bt?.eventWindow?.hasMoreBefore&&!!wP)&&(Rp?.hasMore??!0),_P=!!Rp?.loading,CP=(()=>{const Te=Ut.payload;if(!Te)return{};const rt=new Map(Te.plans.map(xn=>[xn.id,xn])),Nt=new Set(["queued","starting","running","cancelling","reconciling"]),Ia={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},$o={};for(const xn of[...Te.modelRuns].sort((Ba,Vr)=>Vr.updatedAt.localeCompare(Ba.updatedAt))){if(xn.kind==="evaluation"||!["prepared","running"].includes(xn.status))continue;const Ba=Te.jobs.filter(Pp=>Pp.metadata.modelRunId===xn.id).sort((Pp,RP)=>RP.updatedAt.localeCompare(Pp.updatedAt))[0];if(Ba&&!Nt.has(Ba.status))continue;const Vr=Ba?.status??(xn.status==="prepared"?"starting":"running");$o[xn.modelId]={label:Ia[Vr]??"Running",status:Vr}}for(const xn of[...Te.jobs].sort((Ba,Vr)=>Vr.updatedAt.localeCompare(Ba.updatedAt))){if(!Nt.has(xn.status))continue;const Ba=rt.get(xn.planId)?.modelId;!Ba||$o[Ba]||($o[Ba]={label:Ia[xn.status]??"Active",status:xn.status})}return $o})();return k.jsx(rS,{showToast:ht,children:k.jsx(sW,{className:kP,style:Cp,sidebar:{onOpenPonder:()=>{Xt({kind:"chat",sessionId:null}),Z(null),I("chat"),a("activity")},productArea:wp,modelProjects:(Ut.payload?.modelProjects??[]).filter(Te=>Te.hosted===null||Te.hosted.teamId===(Zn.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:CP,onProductAreaChange:Ip,experience:Je,view:ne,selectedAppId:be,selectedProjectId:ae,selectedSessionId:de,selectedTeamThreadId:xt.selectedThreadId,teamChatEnabled:di!==null,organizations:Ni,teamChatOrganization:ci,teamChatLoading:xt.loading,currentUserId:xt.currentUserId,teamMembers:xt.members,teamThreads:xt.threads,...Di,account:Ao,connection:jt,profile:bt?.profile,pinnedCollapsed:hn,cloudProjectsCollapsed:it,chatsCollapsed:Cn,savedForLaterCollapsed:ao,archivedChatsOpen:ke,cloudProjectsExpanded:Me,sectionMenuOpen:te,dragItem:il,taskDragSessionId:gi,taskPreviewSessionIds:Nr,activeSessions:mi,archivedSessions:xa,pinnedRows:cl,pinnedSessions:Ua,savedForLaterSessions:Hi,savedForLaterFiles:pi,projectRows:Mo,localProjectRows:fi,cloudProjectRows:hi,projectSessionRowsByProjectId:Pr,childSessionRowsByParentId:Ar,sidebarProjectIdBySessionId:ka,terminalSummaries:jr,runningSessionIds:el,goalRuntimeBySessionId:$r,subagentRuntimeBySessionId:tl,visibleChatRows:Tr,chatRows:wa,chatRowsVisibleCount:qi,expandedProjectIds:Gs,currentVersion:bt?.server.version??null,platform:zt,arch:jt?.arch??null,onSidebarResizeStart:Ie,setSidebarOpen:W,setView:I,setSelectedAppId:K,setSelectedProjectId:ee,setSelectedSessionId:Z,setSearchOpen:f,setSectionMenuOpen:Y,setSettingsSection:st,onSelectTeam:up,onLogOut:mp,onTogglePinnedCollapsed:Po,onToggleCloudProjectsCollapsed:La,onToggleChatsCollapsed:V,onToggleSavedForLaterCollapsed:He,setArchivedChatsOpen:U,setCloudProjectsExpanded:he,setChatRowsVisibleCount:re,beginNewChat:dp,beginProjectChat:qr,onAddProject:Qc,dockSessionRight:ml,selectTeamThread:Te=>{I("team"),xt.selectThread(Te)},openTeamDm:Te=>{I("team"),xt.openDm(Te)},toggleSessionPinned:ul,toggleProjectPinned:Gc,toggleSessionSavedForLater:Jc,openSidebarFile:kp,setSidebarFileStatus:(Te,rt)=>{Rr(Te,rt)},archiveSession:qm,restoreSession:Wc,renameSession:zm,removeProject:cp,expandProject:io,toggleProjectExpanded:Js,startPinnedDrag:lo,clearSidebarDrag:Dr,previewPinnedDrop:rl,commitPinnedDrop:sl,commitPinnedPreviewDrop:ll,startTaskDrag:Bi,clearTaskDrag:so,previewTaskDrop:nl,commitTaskDrop:al,commitTaskPreviewDrop:ol},topBar:{sidebarOpen:ye,title:ne==="chat"&&n?"Ponder Pal":Im,backAction:Oe.backAction,breadcrumbs:Oe.breadcrumbs,conversationId:ne==="chat"?de:null,workspaceName:wr,workspaceId:xr,busy:we,workspaceState:Qn,workspaceKind:kr,selectedApp:We??yt,selectedProject:gn,workspaceDiff:sn,managedWorkspace:ca,workspaceBusy:ct,defaultTeamId:Zn.defaultTeamId,showDiffControls:ne==="chat"&&Je==="development",diffPanelOpen:ie,terminalOpen:tt,rightSidebarAvailable:xP,rightSidebarOpen:ne==="labs"&&h?l?.open??!1:ne==="scheduled"?r:ie,onToggleDiffPanel:ed,onToggleRightSidebar:ne==="labs"&&h?l?.toggle:ne==="scheduled"?()=>s(Te=>!Te):ne==="team"&&Sr?Vs:ed,onOpenSearch:()=>{Y(null),f(!0)},onToggleTerminal:()=>Xe(Te=>!Te),onRunTerminalCommand:Te=>{_({id:Date.now(),scope:Ft,command:Te}),Xe(!0)},onWorkspaceToolAction:Em,onOpenCommitDialog:Pm,onWorkspaceBranchChange:Rm,onWorkspaceBranchCreate:Am,connection:jt,onBootstrap:fn,onOpenSandboxWorkspace:Yc,onShowSidebar:()=>W(!0),onOpenTeamChat:gp,onDiscoverCommunities:vp,collaborationView:ne==="team"||ne==="community"?ne:null,platform:zt,showWorkspaceControls:ne!=="team"&&ne!=="community"&&ne!=="labs"&&ne!=="scheduled"&&ne!=="outputs"&&ne!=="projects"&&(Je==="development"||Je==="work"&&!!(gn||yn?.localProjectId||yn?.cloudProjectId||yn?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:Je,onNewExperienceChange:Ke,view:ne,teamChat:{currentUserId:xt.currentUserId,members:xt.members,agents:xt.agents,profile:bt?.profile??null,teamId:di,teamName:ci?.displayName??null,detail:xt.detail,aiThread:xt.aiThread,agentConversation:xt.agentConversation,loading:xt.loading,busy:xt.busy,error:xt.error,connection:jt,providerSettings:bt?.providers??null,provider:Sa,model:Dn,codexPermissionMode:xe,codexReasoningEffort:De,openPondCommandAccessMode:To,contextWindowStatus:Lr,showToast:ht,onProviderChange:dl,onModelChange:fe,onCodexPermissionModeChange:Ir,onCodexReasoningEffortChange:_r,onOpenPondCommandAccessModeChange:ui,onOpenProviderSettings:()=>{st("providers"),I("settings"),Xt({kind:"settings",section:"providers"})},onSendMessage:xt.sendMessage,onPublishProfileAgent:Bs,onOpenAiThread:async Te=>{await xt.openAiThread(Te),Pe("chat"),_e(!0)},onOpenAgentConversation:async Te=>{await xt.openAgentConversation(Te),Pe("chat"),_e(!0)},onCloseAiThread:()=>_e(!1),onCloseAgentConversation:()=>{xt.closeAgentConversation(),_e(!1)},onSendAgentTurn:xt.sendAgentTurn,onSendAiTurn:xt.sendAiTurn,onStopAiTurn:xt.stopAiTurn,onEditMessage:xt.editMessage,onDeleteMessage:xt.deleteMessage,onRetryMessage:xt.retryMessage,onDismissFailedMessage:xt.dismissFailedMessage,onLoadMoreMessages:xt.loadMoreMessages,onRetryLoad:xt.refresh},community:Fs,bootstrap:bt,runtimeEvents:ro,chatMessages:Er,pendingUserMessage:de?$i[de]??null:null,contextWindowStatus:Lr,goalRuntime:zi,subagentRuntime:jo,selectedSessionId:de,composerDraftStore:g,mainComposerFocusRequestId:B,labCloseDetailRequestId:Oe.closeDetailRequestId,labCloseDetailKind:Oe.closeDetailKind,sideChatTrainingLaunchRequest:Xc,onSideChatTrainingLaunchHandled:Te=>Zm(rt=>rt?.id===Te?null:rt),mentionApps:ri,connectedAppMentions:ya,profileSkills:hp,selectedMentionAppId:O,busy:we,turnRunning:Or,activeProvider:Sa,activeModel:Dn,codexPermissionMode:xe,codexReasoningEffort:De,openPondCommandAccessMode:To,pendingApproval:si,activeWorkspaceAppId:Ks,activeWorkspaceId:xr,activeWorkspaceKind:kr,projectTarget:wm,actionCatalog:Ws,workspaceTarget:qc,connection:jt,workspaceName:wr,workspaceState:Qn,workspaceDiff:sn,workspaceBusy:ct,diffBusy:Yt,forceChatThread:!!de,diffPanelOpen:ie,diffPanelExpanded:Se,rightPanelMode:Ue,rightPanelTabRequest:E,rightChatPanels:Qm,runtimeEventStore:Ha,nativeSkillSidebar:td,extensionSkillSidebar:zr,workspaceDiffPanelViewState:H,sidebarFileOpenRequest:co,sidebarFileBookmarks:Xs,onSetSidebarFileStatus:(Te,rt)=>{Rr(Te,rt)},browserConversationId:Fi,terminalScope:Ft,terminalTabs:P,terminalCwd:za,pendingTerminalCommand:w,terminalOpen:tt,onToggleTerminal:()=>Xe(Te=>!Te),onWorkspaceDiffPanelViewStateChange:zc,training:Ut,trainingSessions:ut,trainingChatHandoff:Eo,trainingDetailTasksetId:C,onTrainingDetailTasksetIdChange:$,onTrainingChatTaskSelect:Yn,onTrainingChatHandoffDismiss:Li,onOpenSession:Hr,onExperienceHandoff:yp,cloudProjects:bt?.cloudProjects??[],projects:pp,projectsAccountBaseUrl:Ao?.baseUrl??Ao?.activeProfile?.baseUrl??null,projectsTeamName:ci?.displayName??null,projectTaskCounts:fp,onNewCloudProject:Km,onNewLocalProject:Qc,onNewProjectTask:Te=>qr(Te.id),onToggleProjectPinned:Gc,onUploadLocalProject:Bm,chatHistoryHasMore:IP,chatHistoryLoading:_P,onDiffPanelResizeStart:Be,onToggleDiffPanelExpanded:()=>Ne(Te=>!Te),onShowDiffPanel:Jm,onShowBrowserPanel:Gm,onShowFilesPanel:()=>ep("files"),onShowGoalSidebarTab:vi,onShowTrainingDraftPanel:()=>{Pe("training"),_e(!0)},onShowRightChatPanel:Xm,onAddRightChat:()=>ml(null),onOpenRightChatForSession:(Te,rt)=>{const Nt=rt??ut.find(Ia=>Ia.id===Te)??null;Nt&&ml(Nt,{preserveView:!0})},onLabDetailOpenChange:Oe.onDetailOpenChange,evaluationSidebarActive:ne==="labs"&&h,onEvaluationSidebarControl:m,scheduledDetailOpen:r,onScheduledDetailOpenChange:s,onTerminalTabsChange:M,onCloseRightChatPanel:Ym,onCloseNativeSkillSidebar:od,onActivateRightChatPanel:np,onRightChatModelChange:ap,onRightChatPromptChange:op,onRightChatScrollStateChange:rp,onRightChatProviderChange:ip,onSubmitRightChat:tp,onStopRightChat:Te=>Ur(Te),onCloseTerminal:()=>Xe(!1),onLoadMoreChatHistory:Qs,canSyncWorkspace:xm,startMessage:li,onPayload:fn,onError:$t,setView:I,onOpenProfileSettings:sp,onOpenProviderSettings:()=>{Xt({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{Xt({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{Xt({kind:"settings",section:"dataset-storage"})},changeDraftProvider:dl,changeProjectTarget:_m,changeWorkspaceTarget:Fm,setDraftProvider:pe,setDraftModel:fe,onBeginNewChatWithModel:Zs,changeCodexPermissionMode:Ir,changeCodexReasoningEffort:_r,changeOpenPondCommandAccessMode:ui,resolveApproval:Cr,answerCreateImproveQuestion:Bc,applyCreateImproveCandidate:$m,approveCreateImproveRun:Nm,cancelCreateImproveRun:Dm,openCreateImprovePullRequest:Fc,reconcileCreateImprovePullRequest:Lm,rejectCreateImproveCandidate:Hm,pauseCreateImproveRun:Vc,resumeCreateImproveRun:Kc,reviseCreateImproveRun:Um,setMentionedAppId:j,showToast:ht,onSaveTaskDraft:bp,sendPrompt:Vm,stopTurn:Te=>Ur(void 0,Te),syncWorkspaceLocally:Om,refreshWorkspaceDiff:Tn},cloudSetup:{state:x,onClose:()=>R(null),onOpenBrowserUrl:Wm,onStart:()=>{Zc()}},projectConfirm:{state:J,onResolve:le},lazyPanels:{activeSessions:mi,branchDialogName:lt,branchDialogOpen:at,commitDialogOpen:X,commitDraft:nt,commitIncludeUnstaged:$e,commitMessage:me,commitNextStep:Le,canPublishOpenPondProject:km,connection:jt,expandProject:io,newProjectBusy:q,newProjectDialogOpen:Ge,newProjectDirectory:Zn.defaultNewProjectDirectory,newProjectMode:qe,newProjectName:L,newProjectPath:N,projectRows:la,query:ue,searchOpen:je,visibleWorkspaceDiff:sn,visibleWorkspaceState:Qn,workspaceBusy:ct,appDispatch:y,beginNewChat:()=>sa(null),openDefaultsSettingsFromBranchDialog:Tm,setBranchDialogName:Pn,setBranchDialogOpen:$n,setCommitDialogOpen:mn,setCommitDraft:ga,setCommitIncludeUnstaged:Wt,setCommitMessage:pn,setCommitNextStep:Da,setNewProjectDialogOpen:rn,setNewProjectName:Et,setNewProjectPath:tn,setPrompt:ce,setQuery:Ye,setSearchOpen:f,submitCommitDialog:Mm,submitCreateWorkspaceBranch:jm,submitNewProjectDialog:Cm},toast:{toast:pt,onDismiss:()=>y({type:"field",key:"toast",value:null})}})})}const ls=new Map,Vd=new Map;function Hh(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(o=>o.isActive)??null,n=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",a=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"";return[n,a,e.apiBaseUrl??"",e.chatApiBaseUrl??""].join("|")}function u8(e){const t=e?.trim();if(!t)return null;const n=ls.get(t);return n?.updatedAt?n.organizations:null}function m8(e,t){const n=e?.trim();if(n){ls.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of Vd.get(n)??[])a()}}function p8(e,t){const n=e?.trim();if(!n)return()=>{};const a=Vd.get(n)??new Set;return a.add(t),Vd.set(n,a),()=>{a.delete(t),a.size===0&&Vd.delete(n)}}function gS(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=ls.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(o=>(m8(t,o),o)).catch(o=>{const r=ls.get(t);throw r?.promise===a&&ls.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),o});return ls.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const Xee="openpond.config.json";function ete(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function bR(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function Tf(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function tte(e,t=null){const n=h8(e.openFilePaths.map(o=>bS(o,t)).filter(Boolean)),a=e.selectedPath&&bS(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function vS(e,t){return e.activeTab===t.activeTab&&e.selectedPath===t.selectedPath&&e.openFilePaths.length===t.openFilePaths.length&&e.openFilePaths.every((n,a)=>n===t.openFilePaths[a])}function bS(e,t=null){let n=f8(e);const a=t?.trim().replace(/\\/g,"/").replace(/\/+$/,"");if(!a)return n;if(n===a)return"";n.startsWith(`${a}/`)&&(n=n.slice(a.length+1));const o=a.split("/").filter(Boolean).at(-1);return o&&n.startsWith(`${o}/`)&&(n=n.slice(o.length+1)),n}function nte(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function ate(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function ote(e,t){const n=yS(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const o=yS(a);return!!(o&&o.startsWith(`${n}/`))})}function ite(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function rte(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function f8(e){let t=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(/^file:\/\//i.test(t))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.replace(/^file:\/\//i,"")}return t.replace(/\\/g,"/").replace(/^\.\/+/,"")}function h8(e){return Array.from(new Set(e))}function yS(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function g8(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(l=>l.isActive)??null,n=e.profile?.id?.trim()??"",a=e.activeProfile?.handle?.trim()||t?.handle?.trim()||e.label.trim()||"signed_in",o=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",r=e.apiBaseUrl??t?.apiBaseUrl??"",s=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,o,r,s].join("|")}function yR(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function v8(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function fm(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,o=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||yR(a),name:t.name||a,displayName:a,role:t.role==="owner"||t.role==="admin"||t.role==="member"?t.role:"member",workspaceKind:t.workspaceKind==="personal"||t.workspaceKind==="shared"?t.workspaceKind:o?"personal":"shared",status:t.status==="disabled"||t.status==="archived"?t.status:"active",kind:t.kind==="personal_default"||t.kind==="managed_client"||t.kind==="team"?t.kind:void 0,isPersonalDefault:o,isManagedClient:t.isManagedClient===!0||t.kind==="managed_client",primaryContactEmail:t.primaryContactEmail??null,customDomain:t.customDomain??null,planKey:typeof t.planKey=="string"?t.planKey:null,effectiveAccessState:t.effectiveAccessState==="checkout_pending"||t.effectiveAccessState==="active"||t.effectiveAccessState==="grace"||t.effectiveAccessState==="suspended"||t.effectiveAccessState==="cancelling"||t.effectiveAccessState==="cancelled"?t.effectiveAccessState:null,canManageBilling:t.canManageBilling===!0||t.role==="owner",createdAt:t.createdAt??"",updatedAt:t.updatedAt??""}}function b8(e){return e.find(t=>t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default")??e.find(t=>t.name.trim().toLowerCase()==="default")??e.find(t=>t.isManagedClient!==!0&&t.kind!=="managed_client")??e[0]??null}function y8(e,t){const n=e.filter(o=>o.status==="active"&&o.workspaceKind==="shared"),a=t?.trim()??"";if(a){const o=n.find(r=>r.teamId===a);if(o)return o}return n.find(o=>o.role==="owner")??n.find(o=>o.role==="admin")??n[0]??null}function S8(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function x8({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const k8=[{value:"action:new-local-project",label:"New local project",detail:"Create a new project folder on this machine",kind:"action"},{value:"action:add-local-project",label:"Use existing folder",detail:"Choose a folder on this machine",kind:"action"},{value:"action:add-local-project-path",label:"Use existing folder path",detail:"Enter a local folder path manually",kind:"action"},{value:"action:new-cloud-project",label:"New cloud project",detail:"Create a project in OpenPond Cloud",kind:"action"},{value:"action:create-cloud-environment",label:"Create cloud environment",detail:"Set up compute for a cloud project",kind:"action"}];function w8(...e){return S8(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function I8(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return w8(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function _8({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:o,selectedCloudProject:r,selectedProject:s,selectedSession:l,selectedSessionId:m,selectedSessionLinkedProject:d}){const h=l?.workspaceKind==="local_project"?l.workspaceId??null:d?.id??null,g=qt(m)&&!l,y=l?Io(l.workspaceKind):!1,w=_o(l),_=l?s8(l):!1,P=l?.cwd&&(!y||w)?t1(l.cwd):null,M=e?.providers??null,C=Oa(s,e?.cloudProjects??[]),$=x8({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:w}),O=ji($,t,M),j=Ca(e?.preferences),x=g?null:l?y?l.workspaceKind??"sandbox":_?"sandbox":h?"local_project":l.workspaceKind??(l.appId?"sandbox_app":P?"local_project":null):r?"sandbox":s?"local_project":o?"sandbox_app":null,R=g?null:l?y&&!w||_?null:h||(l.workspaceId??l.appId??P):r?null:s?.id??o,E=g?null:l?y?l.workspaceId??null:_?null:h??l.workspaceId??l.appId??P:r?null:s?.id??o,H=e?.account??null,B=!e||H?.state==="loading"||H?.state==="switching",D=!B&&H?.state==="signed_out",J=B?null:D?"Sign in":H?.label??H?.activeProfile?.handle??"Account",le=I8(H),ue=le?`Welcome, ${le}`:"Welcome",je=l?.workspaceName??l?.appName??r?.name??s?.name??a?.name??null,ke=Io(x)?"cloud":"local",te=s?.name??d?.name??(l?.workspaceKind==="local_project"?l.workspaceName:null)??"Local workspace",Me=(ke==="cloud"?je:null)??r?.name??C?.name??s?.name??"Cloud workspace",ye=!!(r?.id||C?.id||l?.cloudProjectId||ke==="cloud");return{account:H,accountLabel:J,accountPending:B,accountSignedOut:D,activeModel:O,activeProvider:$,activeWorkspaceAppId:R,activeWorkspaceId:E,activeWorkspaceKind:x,activeWorkspaceLocation:ke,appDefaults:j,cloudLinked:ye,cloudTargetName:Me,localTargetName:te,selectedCodexHistoryPending:g,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:P,selectedSessionPendingCloudStart:_,selectedSessionProjectId:h,startMessage:ue,workspaceName:je}}function C8({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:o,cloudLinked:r,selectedCloudProject:s,selectedProject:l,selectedSession:m,pendingWorkspaceTarget:d,workspaceStates:h,workspaceBusy:g}){const y=Oa(l,a?.cloudProjects??[]),_=!!!l?.linkedSandboxProject?.projectId||!!y,P=v.useMemo(()=>{const E=(a?.localProjects??[]).map(J=>({value:`local:${J.id}`,label:J.name,detail:J.workspacePath,kind:"local"})),H=(a?.cloudProjects??[]).map(J=>({value:`cloud:${J.id}`,label:J.name,detail:J.organizationName??J.sourceLabel??"OpenPond Cloud",kind:"cloud"})),B=l?`local:${l.id}`:s?`cloud:${s.id}`:"none",D=[...E,...H].find(J=>J.value===B)??null;return{value:B,label:D?.label??"Select Project",detail:D?.detail??"Choose a project for local or cloud work",busy:g||o,options:[...E,...H,...k8,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,o,s,l,g]),M=!!(r||l),C=!!(s?.id||y?.id||m?.cloudProjectId||_o(m)),$=l?h[l.id]??null:null,O=$C($,{branch:l?.linkedSandboxProject?.defaultBranch??null,path:l?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:l?.linkedSandboxProject?.projectId&&_?!!l.linkedSandboxProject.lastUploadedCommit||!$?.headCommit:!0}),j=NC(l,s??y,$,{cloudLinkTrusted:_}),x=bK(l,$,{cloudLinkTrusted:_}),R=v.useMemo(()=>{const E={value:"local",label:l?"Local checkout":"Local",detail:l?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:l?O:"App-managed local task workspace",disabled:!1,disabledReason:null},H={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:C?j:"upload required",disabled:e||t||!C,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},B={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:l||s?j:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},D={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:x,disabled:e||t||!l,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},J=n==="cloud"?"local":"cloud",le=J==="local"?E:B;let ue=n==="cloud"?B:E;return d==="cloud"?ue=B:d==="local"?ue=E:(_o(m)||d==="hybrid")&&(ue=H),{value:ue.value,label:ue.label,detail:ue.stateNote||ue.detail,busy:g,action:{...le,label:J==="cloud"?"Hosted":l?"Local checkout":"Check out locally"},uploadAction:l?D:null,options:[E,H,B]}},[n,e,t,r,M,j,C,O,d,l,m,x,g]);return{projectTarget:P,workspaceTarget:R}}function Un(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function SR(e){return Un(e.name||e.gitRepo||e.id)}function ste(e){return`@${SR(e)}`}function xR(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function R8(e,t){const n=xR(e);if(n.length===0)return!1;const a=new Set([Un(t.id),SR(t),t.gitRepo?Un(t.gitRepo):""].filter(Boolean));return n.some(o=>a.has(o))}function kR(e){return e.filter(t=>t.sandbox)}function P8(e,t){const n=xR(e);if(n.length===0)return null;const a=new Map;for(const o of n){const r=t.find(s=>{const l=Un(s.id),m=Un(s.name),d=s.gitRepo?Un(s.gitRepo):"";return o===l||o===m||o===d});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function lte(e,t){const n=e.slice(0,t),a=n.match(/(?:^|\s)@([A-Za-z0-9_-]*)$/);if(!a||typeof a.index!="number")return null;const o=n.slice(a.index).indexOf("@");return o<0?null:{query:Un(a[1]??""),start:a.index+o}}function A8(e){return new Set(e.map(t=>t.id))}function SS(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function T8({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:o,sessions:r}){const s=v.useMemo(()=>e?.apps.find(D=>D.id===o)??null,[e?.apps,o]),l=v.useMemo(()=>new Map((e?.localProjects??[]).map(D=>[D.id,D])),[e?.localProjects]),m=v.useMemo(()=>new Map((e?.cloudProjects??[]).map(D=>[D.id,D])),[e?.cloudProjects]),d=v.useMemo(()=>wC(n),[n]),h=v.useMemo(()=>d?.kind==="local"?l.get(d.id)??null:null,[l,d]),g=v.useMemo(()=>d?.kind==="cloud"?m.get(d.id)??null:null,[m,d]),y=v.useMemo(()=>A8(e?.apps??[]),[e?.apps]),w=v.useMemo(()=>kR(e?.apps??[]),[e?.apps]),_=v.useMemo(()=>{const D=[];for(const J of e?.localProjects??[]){const le=SS(J,y);le&&D.push([le.appId,J.id])}return new Map(D)},[e?.localProjects,y]),P=v.useMemo(()=>new Set((e?.localProjects??[]).map(D=>D.id)),[e?.localProjects]),M=v.useMemo(()=>AC(e?.localProjects??[]),[e?.localProjects]),C=v.useRef([]),$=v.useMemo(()=>E8(r,t,C.current),[t,r]),O=v.useMemo(()=>$.find(D=>D.id===a)??null,[$,a]),j=v.useMemo(()=>{if(!O)return null;if(O.localProjectId)return l.get(O.localProjectId)??null;if(O.workspaceKind==="local_project")return O.workspaceId?l.get(O.workspaceId)??null:null;const D=sK(O,P,M);if(D)return l.get(D)??null;if(!O.appId)return null;const J=_.get(O.appId);return J?l.get(J)??null:null},[_,l,P,M,O]),x=v.useMemo(()=>O?.cloudProjectId?m.get(O.cloudProjectId)??null:null,[m,O]),R=h??j,E=g??x,H=v.useMemo(()=>SS(R,y),[y,R]),B=v.useMemo(()=>H?e?.apps.find(D=>D.id===H.appId)??null:null,[e?.apps,H]);return{cloudProjectById:m,currentAppIds:y,linkedProjectByAppId:_,localProjectById:l,mentionableSandboxApps:w,selectedApp:s,selectedCloudProject:E,selectedProject:R,selectedProjectLinkedApp:B,selectedProjectLinkedOpenPondApp:H,selectedSession:O,selectedSessionLinkedProject:j,sidebarSessions:$}}function E8(e,t,n){const a=new Map;for(const d of e){const h=xS(d);a.set(h,d)}for(const d of t){const h=xS(d),g=a.get(h);a.set(h,g?M8(g,d):d)}const o=Array.from(a.entries());if(!n)return o.sort((d,h)=>kS(d[1],h[1])).map(d=>d[1]);const r=[],s=new Set;for(const d of n){const h=a.get(d);h&&(r.push([d,h]),s.add(d))}const m=[...o.filter(([d])=>!s.has(d)).sort((d,h)=>kS(d[1],h[1])),...r];return n.splice(0,n.length,...m.map(([d])=>d)),m.map(d=>d[1])}function M8(e,t){return{...e,metadata:j8(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:O8(e.updatedAt,t.updatedAt)}}function xS(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function kS(e,t){const n=wS(t)-wS(e);return n!==0?n:e.title.localeCompare(t.title)}function j8(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function O8(e,t){const n=Date.parse(e);if(!Number.isFinite(n))return t;const a=Date.parse(t);return Number.isFinite(a)&&a>n?t:e}function wS(e){const t=Date.parse(e.updatedAt);if(Number.isFinite(t))return t;const n=Date.parse(e.createdAt);return Number.isFinite(n)?n:0}function $8(e){return!!(e&&Io(e.workspaceKind)&&!_o(e)&&e.provider!=="openpond")}function N8(e,t){const n=CC(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function D8({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:o,linkedProjectByAppId:r,providerSettings:s,selectedAppId:l,selectedSession:m,selectedSessionId:d,selectedSessionProjectId:h,setDiffPanelExpanded:g,setDraftModel:y,setDraftProvider:w,setError:_,setSelectedAppId:P,setSelectedProjectId:M,setSessions:C,setTerminalOpen:$,toast:O}){const j=v.useRef(null);v.useEffect(()=>{if(!l)return;const x=h??(d?null:r.get(l)??null);if(!x)return;const R=St("local",x);P(null),M(R),o(R)},[o,r,l,d,h,P,M]),v.useEffect(()=>{if(!O||O.persistent)return;const x=window.setTimeout(()=>{n({type:"clearToast",toastId:O.id})},O.durationMs??(O.tone==="error"?7e3:3500));return()=>window.clearTimeout(x)},[n,O]),v.useEffect(()=>{function x(R){(R.metaKey||R.ctrlKey)&&R.key==="`"&&(R.preventDefault(),$(E=>!E))}return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[$]),v.useEffect(()=>{g(!1)},[e,t,g]),v.useEffect(()=>{if(!d){j.current=null;return}if(!m||m.id!==d)return;const x=N8(m,s);if(j.current===x)return;j.current=x;const R=CC(m,s);w(R.provider),y(R.model)},[s,m,d,y,w]),v.useEffect(()=>{!a||!m||!$8(m)||Q.patchSession(a,m.id,{provider:"openpond"}).then(x=>{C(R=>R.map(E=>E.id===x.id?x:E)),w("openpond"),y(R=>ji("openpond",R))}).catch(x=>{_(x instanceof Error?x.message:String(x))})},[a,m,y,w,_,C])}function L8({connection:e,setError:t}){return v.useCallback(async(n,a)=>{if(!e){const o=new Error("OpenPond App server is not connected.");throw t(o.message),o}t(null);try{await Q.resolveApproval(e,n,{decision:a})}catch(o){const r=o instanceof Error?o.message:String(o);throw t(r),o}},[e,t])}function H8({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:o,pinnedProjects:r,projectRows:s,visibleProjectRows:l}){const m=v.useMemo(()=>GV(a,o),[a,o]),d=v.useMemo(()=>JC({provider:e,snapshot:n,preferences:t}),[e,t,n]),h=v.useMemo(()=>Array.from(new Set([...r,...l].filter(nb).map(y=>y.project.id))),[r,l]);return{commandProjectRows:v.useMemo(()=>s,[s]),contextWindowStatus:d,pinnedRows:m,sidebarWorkspaceAppIds:h}}function U8({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:o,setMentionedAppId:r}){return v.useCallback((s=null)=>{o?.();const l=s?.id?n.get(s.id)??null:null;if(l){const m=St("local",l);r(null),e({type:"selectProject",projectId:m}),t(m),a();return}r(null),e({type:"beginNewChat",appId:s?.id??null}),a()},[e,t,n,o,a,r])}const wR={slack:["slack"],microsoft_teams:["teams","microsoft-teams","microsoft_teams"],github:["github","gh"],google:["google","drive","google-drive","docs"],turnkey:["turnkey","agent-wallet","agent_wallet","wallet"],x:["x","twitter"],mcp:["mcp","openpond-mcp"]};function cte(e){return`@${e.token}`}function q8(e){return`@${K8(e)}`}function z8(e){const t=new Map;for(const n of e){if(!n.connected||n.statusSource!=="integration_connection")continue;const a=t.get(n.providerFamily)??[];a.push(n),t.set(n.providerFamily,a)}return Array.from(t.entries()).map(([n,a])=>{const o=a[0],r=Qr(a.flatMap(g=>g.capabilities.map(y=>y.id))),s=Qr(a.flatMap(g=>g.capabilityLabels)),l=Qr(a.flatMap(g=>g.connections.map(y=>y.id).filter(G8))),m=Qr(a.map(g=>g.id)),d=Qr(a.map(g=>g.setupSurface)),h=V8(n);return{provider:n,label:o.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):o.description,token:h,tokens:F8(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:d,...l.length>0?{connectionIds:l}:{},...r.length>0?{capabilities:r}:{}}}})}function dte(e,t){const n=Un(t);return e.filter(a=>n?a.tokens.some(o=>o.includes(n)):!0).slice(0,8)}function B8(e,t){const n=W8(e);if(n.length===0)return[];const a=new Map;for(const o of n){const r=t.find(s=>s.tokens.includes(o));r&&a.set(r.provider,r)}return Array.from(a.values())}function ute(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const o=a[1]??"",r=Un(o);if(!r)continue;const s=t.find(g=>g.tokens.includes(r));if(!s)continue;const m=(a[0]??"").indexOf("@");if(m<0||typeof a.index!="number")continue;const d=a.index+m,h=`@${o}`;n.push({detail:s.detail,displayText:q8(s),end:d+h.length,label:s.label,provider:s.provider,start:d,text:h})}return n}function F8(e){return Qr(e.flatMap(t=>[...wR[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Un).filter(Boolean))}function V8(e){return Un(wR[e][0]??e)}function K8(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function W8(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function Qr(e){return Array.from(new Set(e))}function G8(e){return typeof e=="string"&&e.length>0}function J8({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:o,selectedCloudProject:r,selectedProject:s,selectedSession:l,selectedSessionId:m}){const d=v.useMemo(()=>{const _=new Map;for(const P of e?.cloudProjects??[]){const M=_.get(P.teamId)??[];M.push(P.id),_.set(P.teamId,M)}return _},[e?.cloudProjects]),g=!!(l||o||s||r)?[]:n,y=v.useMemo(()=>z8(t),[t]),w=v.useMemo(()=>KW(a,m),[a,m]);return{chatMentionApps:g,cloudProjectIdsByTeam:d,connectedAppMentions:y,pendingApproval:w}}function Z8({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:o}){const r=v.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}Q.savePreferences(e,{codexPermissionMode:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(d=>d&&{...d,preferences:m.preferences})}).catch(m=>{o(m instanceof Error?m.message:String(m))})},[e,t,n,a,o]),s=v.useCallback(l=>{if(!e){o("Connect to OpenPond before saving preferences.");return}Q.savePreferences(e,{codexReasoningEffort:l}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(d=>d&&{...d,preferences:m.preferences})}).catch(m=>{o(m instanceof Error?m.message:String(m))})},[e,t,n,a,o]);return{changeCodexPermissionMode:r,changeCodexReasoningEffort:s}}const Y8=6e4;function pb(e,t){if(!e)return t;const n=X8(e.updatedAt,t.updatedAt)?{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,status:e.status,updatedAt:e.updatedAt}:t;return _R(e,n)?e:n}function Q8(e,t){const n=pb(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&_R(e,a)?e:a}function Al(e,t){let n=!1,a=!1;const o=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=pb(r,t);return s!==r&&(a=!0),s});return n?a?o:e:[t,...e]}function hm(e,t){let n=!1,a=!1;const o=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=Q8(r,t);return s!==r&&(a=!0),s});return n?a?o:e:[t,...e]}function Uh(e,t,n,a=Date.now()){const o=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const s=o.get(r.id);if(s&&n){const l=tG(s,r,n,a);if(l)return l}return pb(s,r)})}function IS(e,t,n,a=Date.now()){const o=new Map(e.map(d=>[d.id,d])),r=new Map(Uh(e,t,n,a).map(d=>[d.id,d])),s=new Set(o.keys()),l=t.filter(d=>!s.has(d.id)).map(d=>r.get(d.id)??d),m=e.map(d=>{const h=r.get(d.id);return h||(IR(d,t)?d:null)}).filter(d=>!!d);return[...l,...m]}function IR(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=eG(t);return a===null||n>=a}function _S(e,t,n,a=Date.now()){const o=new Map(t.map(r=>[r.id,r]));for(const r of n){const s=o.get(r.id);s&&(CR(s,r)||(e[r.id]=a))}}function X8(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function _R(e,t){return JSON.stringify(e)===JSON.stringify(t)}function eG(e){let t=null;for(const n of e){const a=Date.parse(n.updatedAt);Number.isFinite(a)&&(t=t===null?a:Math.max(t,a))}return t}function tG(e,t,n,a){const o=n[t.id];return o===void 0?null:a-o>Y8||CR(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function CR(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const RR=800,nG=5e3,CS=5e4,aG=16,oG=3e4,ta=new Map;function iG(e,t){return ta.get(AR(e,t))?.payload??null}async function PR(e,t,n={}){const a=AR(e,t),o=ta.get(a),r=n.limit??RR,s=n.tail??!0;if(o?.promise)return o.promise;if(!n.force&&s&&o?.payload&&Date.now()-o.fetchedAt<=oG)return RS(a,o),o.payload;const l=!!(n.force&&s&&o?.payload),m=l?o?.payload?.events.at(-1)?.id:void 0,d=Q.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:r,revision:l?o?.revision:void 0,tail:s}).then(h=>{const g=ta.get(a)?.payload??o?.payload;if(h.unchanged){if(!g)throw new Error("Codex history revision matched without a cached thread.");return ta.set(a,{fetchedAt:Date.now(),payload:g,revision:h.revision}),RS(a,ta.get(a)),g}const y={session:h.session,events:h.events},w=s&&g&&!h.reset?{...y,events:rG(g.events,y.events)}:y;return ta.set(a,{fetchedAt:Date.now(),payload:w,revision:h.revision}),PS(),w}).catch(h=>{throw ta.get(a)?.promise===d&&ta.delete(a),h});return ta.set(a,{fetchedAt:o?.fetchedAt??0,payload:o?.payload,promise:d,revision:o?.revision}),PS(),d}function AR(e,t){return`${e.serverUrl}
|
|
185
|
-
${e.token}
|
|
186
|
-
${t}`}function RS(e,t){ta.delete(e),ta.set(e,t)}function PS(){for(;ta.size>aG;){const e=ta.keys().next().value;if(!e)return;ta.delete(e)}}function rG(e,t){const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values())}const sG=500,lG=2500,cG=15e3;function dG(e){return e.active?sG:e.surface==="thread"?lG:cG}function fb(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function uG(e={}){const t={cachedPayload:e.cachedPayload??iG,clearTimer:e.clearTimer??(d=>globalThis.clearTimeout(d)),loadPayload:e.loadPayload??PR,now:e.now??Date.now,setTimer:e.setTimer??((d,h)=>globalThis.setTimeout(d,h))},n=new Map;let a=1;function o(d){const h=pG(d.connection,d.sessionId);let g=n.get(h);g||(g={connection:d.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(d.connection,d.sessionId),nextRefreshAt:null,sessionId:d.sessionId,subscribers:new Map,timer:null},n.set(h,g));const y=a++;return g.subscribers.set(y,d),g.latestPayload&&d.onPayload(g.latestPayload),r(g,0),()=>{const w=n.get(h);if(w){if(w.subscribers.delete(y),w.subscribers.size>0){r(w,l(w));return}w.disposed=!0,m(w),n.delete(h)}}}function r(d,h){if(d.disposed||d.subscribers.size===0||d.inFlight)return;const g=t.now()+Math.max(0,h);d.timer&&d.nextRefreshAt!==null&&d.nextRefreshAt<=g||(m(d),d.nextRefreshAt=g,d.timer=t.setTimer(()=>{d.timer=null,d.nextRefreshAt=null,s(d)},Math.max(0,h)))}async function s(d){if(d.disposed||d.subscribers.size===0||d.inFlight)return;const h=t.loadPayload(d.connection,d.sessionId,{force:!!d.latestPayload});d.inFlight=h;try{const g=await h;if(d.disposed||g===d.latestPayload)return;d.latestPayload=g;for(const y of d.subscribers.values())y.onPayload(g)}catch(g){if(d.disposed)return;for(const y of d.subscribers.values())y.onError?.(g)}finally{d.inFlight===h&&(d.inFlight=null),d.disposed||r(d,l(d))}}function l(d){const h=[...d.subscribers.values()],g=h.some(w=>w.locallyActive||w.reportedActive)||d.latestPayload?.session.status==="active"||db(d.latestPayload?.events??[])?.tone==="active",y=h.some(w=>w.surface==="thread")?"thread":"sidebar";return dG({active:g,surface:y})}function m(d){d.timer&&t.clearTimer(d.timer),d.timer=null,d.nextRefreshAt=null}return{subscribe:o}}const mG=uG();function hb(e){return mG.subscribe(e)}function pG(e,t){return`${e.serverUrl}
|
|
187
|
-
${e.token}
|
|
188
|
-
${t}`}function fG({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:o,setError:r}){const[s,l]=v.useState({events:[],sessionId:null}),m=qt(t)?t:null,d=m&&s.sessionId===m?s.events:[],h=v.useCallback(g=>{l(y=>{if(!m)return{events:[],sessionId:null};const w=y.sessionId===m?y.events:[];return{events:typeof g=="function"?g(w):g,sessionId:m}})},[m]);return v.useEffect(()=>{if(!e||!m){l(w=>w.sessionId===null&&w.events.length===0?w:{events:[],sessionId:null});return}r(w=>w==="Session not found"?null:w);const g=n;return hb({connection:e,locallyActive:g,onError:w=>r(w instanceof Error?w.message:String(w)),onPayload:w=>{const _=fb(w,g);l(P=>P.sessionId!==m?{events:_.events,sessionId:m}:{events:qo(P.events,_.events),sessionId:m}),r(P=>P==="Session not found"?null:P),o(P=>hm(P,_.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,o,r]),{codexHistoryEvents:d,setCodexHistoryEvents:h}}function TR(e){const t=e.currentTarget,n=t.getBoundingClientRect(),a=t.cloneNode(!0);a.classList.add("sidebar-drag-preview"),a.style.width=`${n.width}px`,a.style.height=`${n.height}px`,a.style.position="fixed",a.style.top="-1000px",a.style.left="-1000px",a.style.pointerEvents="none",a.style.boxSizing="border-box",a.style.maxWidth="none",document.body.appendChild(a),e.dataTransfer.setDragImage(a,e.clientX-n.left,e.clientY-n.top),window.setTimeout(()=>a.remove(),0)}function hG({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:o,setCodexHistorySessions:r,setSessions:s,sidebarFileBookmarks:l,setSidebarFileBookmarks:m,setError:d}){const[h,g]=v.useState(null),[y,w]=v.useState(null),_=v.useRef(null),P=v.useRef(null);function M(R,E){R.dataTransfer.effectAllowed="move",R.dataTransfer.setData("text/plain",`${E.type}:${E.id}`),TR(R);const H=a.map(B=>B.key);_.current=E,P.current=H,g(E),w(H)}function C(){_.current=null,P.current=null,g(null),w(null)}function $(R,E){const H=_.current;if(!H)return;const B=fu(R),D=P.current??a.map(le=>le.key),J=hu(D,tr(H),tr(E),B);F0(D,J)||(P.current=J,w(J))}function O(R){if(!e)return;const E=a.map(ke=>ke.key),H=new Set(E),B=[...R.filter(ke=>H.has(ke)),...E.filter(ke=>!R.includes(ke))];if(F0(E,B))return;const D=t,J=new Map(n.map(ke=>[ke.id,ke])),le=l,ue=new Map(a.map(ke=>[ke.key,ke]));o(ke=>{const te={...ke};return B.forEach((Me,ye)=>{const ne=ue.get(Me);ne?.type==="project"&&(te[ne.id]={...te[ne.id]??{},pinned:!0,archived:!1,order:ye})}),te});const je=ke=>{const te=new Map(ke.map(ne=>[ne.id,ne])),Me=B.map((ne,be)=>{const ae=ue.get(ne),de=ae?.type==="session"?te.get(ae.id):null;return de?{...de,order:be}:null}).filter(ne=>!!ne),ye=new Map(Me.map(ne=>[ne.id,ne]));return ke.map(ne=>ye.get(ne.id)??ne)};s(je),r(je),m(ke=>{const te=new Map;return B.forEach((Me,ye)=>{const ne=ue.get(Me);ne?.type==="file"&&te.set(ne.id,ye)}),ke.map(Me=>{const ye=te.get(Me.id);return ye===void 0?Me:{...Me,order:ye}})}),Promise.all(B.map((ke,te)=>{const Me=ue.get(ke);return Me?Me.type==="project"?Q.patchSidebarAppPreference(e,Me.id,{pinned:!0,archived:!1,order:te}):Me.type==="session"?Q.patchSession(e,Me.id,{order:te}):Q.patchSidebarFile(e,{workspaceKind:Me.file.workspaceKind,workspaceId:Me.file.workspaceId,workspaceName:Me.file.workspaceName,path:Me.file.path,status:"pinned",order:te,sourceSessionId:Me.file.sourceSessionId}):Promise.resolve(null)})).catch(ke=>{d(ke instanceof Error?ke.message:String(ke)),o(D);const te=Me=>Me.map(ye=>J.get(ye.id)??ye);s(te),r(te),m(le)})}function j(R,E){const H=_.current;if(H){const B=P.current??a.map(J=>J.key),D=hu(B,tr(H),tr(E),fu(R));O(D)}C()}function x(){_.current&&O(P.current??a.map(E=>E.key)),C()}return{dragItem:h,pinnedPreviewKeys:y,startPinnedDrag:M,clearSidebarDrag:C,previewPinnedDrop:$,commitPinnedDrop:j,commitPinnedPreviewDrop:x}}function gG({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:o}){const[r,s]=v.useState(null),[l,m]=v.useState(null),d=v.useRef(null),h=v.useRef(null);function g(C,$){C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",`session:${$.sessionId}`),TR(C),d.current=$,h.current=$.visibleSessionIds,s($.sessionId),m($.visibleSessionIds)}function y(C,$){const O=d.current;if(!O)return;const j=h.current??O.visibleSessionIds,x=hu(j,O.sessionId,$,fu(C));vG(j,x)||(h.current=x,m(x))}function w(){d.current=null,h.current=null,s(null),m(null)}function _(C,$){const O=d.current;if(!O){w();return}const j=h.current??O.visibleSessionIds,x=hu(j,O.sessionId,$,fu(C));M(Y0(O.allSessionIds,O.visibleSessionIds,x)),w()}function P(){const C=d.current;C&&M(Y0(C.allSessionIds,C.visibleSessionIds,h.current??C.visibleSessionIds)),w()}function M(C){const $=new Map(C.map((R,E)=>[R,E])),O=new Map(t.map(R=>[R.id,R.order])),j=C.filter((R,E)=>O.get(R)!==E);if(j.length===0)return;const x=R=>R.map(E=>{const H=$.get(E.id);return H===void 0||H===E.order?E:{...E,order:H}});o(x),n(x),e&&Promise.all(j.map(R=>Q.patchSession(e,R,{order:$.get(R)}))).catch(R=>{const E=H=>H.map(B=>{const D=O.get(B.id);return D===void 0||D===B.order?B:{...B,order:D}});o(E),n(E),a(R instanceof Error?R.message:String(R))})}return{clearTaskDrag:w,commitTaskDrop:_,commitTaskPreviewDrop:P,previewTaskDrop:y,startTaskDrag:g,taskDragSessionId:r,taskPreviewSessionIds:l}}function vG(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function AS({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const o=new Date().toISOString(),r=`pending_user_${a}_${o}_${Math.random().toString(36).slice(2,8)}`,s=bG(t);return{id:r,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:o,turnId:r,...s.length>0?{attachments:s}:{}}}function ER(e,t){return!t||MR(e,t)?e:[...e,t]}function MR(e,t){const n=t.afterMessageId?e.findIndex(r=>r.id===t.afterMessageId):-1,a=n>=0?n+1:0,o=Date.parse(t.timestamp);for(let r=a;r<e.length;r+=1){const s=e[r];if(s.role!=="user"||s.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const l=Date.parse(s.timestamp);if(!Number.isFinite(o)||!Number.isFinite(l)||l>=o)return!0}return!1}function bG(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function ve(e,t){if(!e)return null;for(const n of t){const a=e[n];if(typeof a=="string"&&a.trim())return a}return null}function Oi(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function Re(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ei(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function yG(e,t,n){if(t.name==="workspace_action_result"){const a=ei(e,o=>o.role==="assistant"&&o.turnId===t.turnId&&o.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:qh([...a.actionRun.refs,...n.refs]),childCalls:n.childCalls.length>0?n.childCalls:a.actionRun.childCalls};return}}e.push({id:t.id,role:"assistant",actionRun:n,timestamp:t.timestamp,turnId:t.turnId})}function SG(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Re(e.data),n=Re(e.args),a=ve(n,["actionName"])??ve(Re(n?.input),["actionName"])??Ef(t)??Ef(Re(t?.run))??Ef(Re(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const r=Re(t?.run)??Re(t?.agentRun),s=Re(r?.metadata),l=Re(t?.actionSummary)??Re(r?.actionSummary)??Re(s?.actionSummary),m=Re(t?.action)??l??Re(s?.selectedAction)??null,d=Re(t?.responseSummary)??Re(r?.responseSummary)??Re(s?.responseSummary),h=Re(t?.sourceSummary)??Re(r?.sourceSummary)??Re(s?.sourceSummary),g=Re(t?.traceSummary)??Re(r?.traceSummary)??Re(s?.traceSummary),y=Re(t?.evalSummary)??Re(r?.evalSummary)??Re(s?.evalSummary),w=qh([...Lo("artifact",t?.artifactRefs,"Artifact"),...Lo("artifact",m?.artifactRefs,"Artifact"),...Lo("artifact",l?.artifactRefs,"Artifact"),...Lo("artifact",d?.artifactRefs,"Artifact"),...Lo("trace",t?.traceArtifactRefs,"Trace"),...Lo("trace",g?.artifactRefs,"Trace"),...Lo("eval",t?.evalResultArtifactRefs,"Eval"),...Lo("eval",y?.artifactRefs,"Eval"),...Lo("output",t?.outputRefs,"Output")]),_=ve(h,["sourceRef","ref"]);return _&&w.push({id:zh("source",_),kind:"source",label:"Source",target:_}),{actionName:a,title:ve(m,["label","title","name"])??ve(s,["selectedActionLabel"])??CG(a),status:xG(e,d,r),responseText:ve(d,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ve(r,["id","runId"])??ve(t,["runId","agentRunId"])??null,projectId:ve(r,["projectId"])??ve(t,["projectId"])??ve(n,["projectId"])??null,agentId:ve(r,["agentId"])??ve(t,["agentId"])??ve(n,["agentId"])??null,agentName:ve(Re(m?.implementation),["agentName"])??ve(m,["agentName"])??ve(s,["selectedAgentName"])??null,sandboxId:ve(r,["sandboxId"])??ve(t,["sandboxId"])??ve(Re(t?.sandbox),["id"])??ve(Re(t?.createdSandbox),["id"])??ve(n,["sandboxId"])??null,runtimeId:ve(r,["runtimeId"])??ve(t,["runtimeId"])??null,implementationType:ve(t,["implementationType"])??ve(m,["implementationType","type","kind"])??ve(Re(m?.implementation),["type","kind"])??ve(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:_,manifestHash:ve(h,["manifestHash"])??ve(t,["manifestHash"])??ve(s,["manifestHash"])??null,refs:qh(w),childCalls:wG(t,r,s)}}function Ef(e){return e?ve(e,["actionName","name"])??ve(Re(e.action),["actionName","name"])??ve(Re(e.actionSummary),["actionName","name"])??ve(Re(e.selectedEntrypoint),["name"]):null}function xG(e,t,n){if(e.status==="failed")return"failed";const a=ve(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const o=ve(n,["status"]);return o==="failed"?"failed":o==="succeeded"||o==="completed"?"completed":o==="queued"||o==="running"||o==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function Lo(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(o=>{const r=kG(e,o,n);return r?[r]:[]})}function kG(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:zh(e,s),kind:e,label:n,target:s}}const a=Re(t);if(!a)return null;const o=ve(a,["url","webUrl","artifactPath","path","ref"])??ve(Re(a.artifact),["url","webUrl","path","ref"]);if(!o)return null;const r=ve(a,["label","title","name","type","kind"])??n;return{id:zh(e,o),kind:e,label:r,target:o}}function qh(e){const t=new Set,n=[];for(const a of e){const o=`${a.kind}:${a.target}`;t.has(o)||(t.add(o),n.push(a))}return n}function zh(e,t){return`${e}:${t}`}function wG(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(o=>IG(o)).slice(0,6)}function IG(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const o=Re(n);if(!o)return[];const r=ve(o,["id","runId","callId"])??`child_${a+1}`,s=ve(o,["label","title","actionName","name","tool"])??ve(Re(o.action),["label","name"])??"Implementation call",l=ve(o,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:r,label:s,status:_G(o),detail:l}]})}function _G(e){const t=ve(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function CG(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const RG=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function jR(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:RG.has(t.slice(n).toLowerCase())}function OR(e){return e.split("/").filter(Boolean).pop()??e}function PG(e){if(!Fh(e))return;const t=Re(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??nr(e.data)??nr(e.args)??nr(e.output);if(!(!a||!jR(a)))return{path:a,appId:e.appId??null,title:OR(a)}}function AG(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return Bh(e.data,t,n),t.slice(0,12)}function Bh(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const l of e)Bh(l,t,n,a+1);return}const o=Re(e);if(!o)return;const r=ve(o,["path","artifactRef"]),s=ve(o,["contentType","mimeType"]);r&&s&&!n.has(r)&&(n.add(r),t.push({path:r,title:ve(o,["title","name"])??OR(r),contentType:s,sizeBytes:typeof o.sizeBytes=="number"?o.sizeBytes:null}));for(const l of Object.values(o))Bh(l,t,n,a+1)}function Fh(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=Re(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,ve(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ve(Re(t?.input),["tool","toolName","tool_name","name"]),ve(Re(t?.arguments),["tool","toolName","tool_name","name"]),ve(Re(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function nr(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(Mf(n)&&jR(e.trim()))return e.trim();const o=Oi(e);if(o!==null){const r=nr(o,t+1,n);if(r)return r}return TG(e)}if(Array.isArray(e)){for(const o of e){const r=nr(o,t+1,n);if(r)return r}return null}const a=Re(e);if(!a)return null;for(const[o,r]of Object.entries(a)){if(!Mf(o))continue;const s=nr(r,t+1,o);if(s)return s}for(const[o,r]of Object.entries(a)){if(Mf(o))continue;const s=nr(r,t+1,o);if(s)return s}return null}function Mf(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function TG(e){const t=/(?:file:\/\/)?(?:\/|\.\/|[\w.-]+\/)[^\s"'`<>]+\.(?:avif|gif|jpe?g|png|webp)\b/i.exec(e);if(!t)return null;if(!t[0].startsWith("file://"))return t[0];try{return decodeURIComponent(new URL(t[0]).pathname)}catch{return t[0].replace(/^file:\/\//i,"")}}function EG(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.action;if(t!=="connected_app_search"&&t!=="connected_app_read"&&t!=="connected_app_write")return null;const n=jG(e),a=e.status==="failed";return t==="connected_app_search"?e.name==="tool.started"?`${n} search`:a?`${n} search failed`:`${n} search`:t==="connected_app_read"?e.name==="tool.started"?`${n} lookup`:a?`${n} lookup failed`:`${n} lookup`:e.name==="tool.started"?`${n} update`:a?`${n} update failed`:`${n} update`}function MG(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=$R(e);return[t.providerOperation,t.operation&&t.operation!==t.providerOperation?t.operation:null,t.capabilityCount>0?`${t.capabilityCount} ${t.capabilityCount===1?"capability":"capabilities"}`:null].filter(a=>!!a).join(" / ")||t.providerLabel}function jG(e){return $R(e).providerLabel}function $R(e){const t=Re(e.args),n=Re(e.data),a=Re(n?.result),o=Mu(ve(t,["provider"])??ve(a,["provider"])??ve(n,["provider"])??void 0),r=ve(a,["providerLabel"])??ve(n,["providerLabel"])??(o?kg(o)?.label:null)??"connected app",s=ve(t,["operation"]),l=ve(a,["operation"])??ve(n,["operation"]),m=jf(t?.capabilityIds)||jf(a?.capabilityIds)||jf(n?.capabilityIds);return{providerLabel:r,providerOperation:s,operation:l,capabilityCount:m}}function jf(e){return Array.isArray(e)?e.length:0}function NR(e){const t=e.trim(),n=/^<(goal_context|turn_aborted)>\s*([\s\S]*?)\s*<\/\1>$/.exec(t);if(n){const a=n[1];return{kind:a,text:n[2]?.trim()||Of(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:Of("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:Of("goal_context")}:null}function Of(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function gm(e){return e.name==="diagnostic"&&Re(e.data)?.kind==="goal_context"}const OG="Steered by user";function $G(e){return e?.trim().toLowerCase()===OG.toLowerCase()}function NG(e,t){if(!t.turnId)return;qG(e,t.turnId);const n=DG(t);if(!n)return;const a=UG(e,t.turnId);if(a){a.refinerActivity=n;return}const o={id:`${t.id}:work-refiner`,role:"activity_group",activities:[],timestamp:t.timestamp,turnId:t.turnId,traceState:"completed",traceStartedAt:t.timestamp,traceCompletedAt:t.timestamp,refinerActivity:n},r=e.findIndex(s=>s.role==="assistant"&&s.turnId===t.turnId);r>=0?e.splice(r,0,o):e.push(o)}function DG(e){const t=Re(e.data),n=Re(t?.activity);return n?LG(n,e):HG(e,t)}function mte(e){if(e.state==="running")return"Refiner · Reviewing for a reusable improvement";if(e.state==="failed")return"Refiner · Review failed";if(e.result==="no_action")return"Refiner · No reusable change";if(e.result==="routed")return`Refiner · ${VG(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function LG(e,t){const n=go(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":go(e.result,["no_action","routed","applied","retained"]),o=Bn(e.reason)??t.output??t.error??null;return{state:n,visibility:go(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Bn(e.workspaceId),decision:go(e.decision,["no_action","route","propose"]),route:Bn(e.route),operation:go(e.operation,["create","update","delete"]),target:Bn(e.target),summary:Bn(e.summary)??DR(n,a),expectedOutcome:Bn(e.expectedOutcome),reason:o,evidenceBasis:zG(e.evidenceBasis),critiqueStatus:go(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:go(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:BG(e.validationReceipts),edits:FG(e.edits),refs:{trigger:ho(e.trigger),outcome:ho(e.outcome),proposal:ho(e.proposal),applyReceipt:ho(e.applyReceipt),advanceReceipt:ho(e.advanceReceipt),inputHarness:ho(e.inputHarness),outputHarness:ho(e.outputHarness)}}}function HG(e,t){if(!e.name.startsWith("harness.refiner."))return null;const n=e.name==="harness.refiner.failed"||e.status==="failed",a=e.name==="harness.refiner.completed",o=Re(t?.outcome),r=Re(t?.proposal),s=o?.routed===!0,l=Bn(t?.workspaceAdvance),m=n?"failed":a?r?l==="advanced"||/\bapplied\b/i.test(e.output??"")?"applied":"retained":s?"routed":"no_action":null;return{state:n?"failed":a?"completed":"running",visibility:"material_only",result:m,workspaceId:null,decision:r?"propose":s?"route":a?"no_action":null,route:Bn(o?.route),operation:null,target:null,summary:DR(n?"failed":a?"completed":"running",m),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:r?"passed":"not_applicable",validationStatus:r?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:ho(t?.trigger),outcome:ho(o),proposal:ho(r),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function UG(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.role==="activity_group"&&a.turnId===t&&!a.activities?.some(o=>o.subagentMessage))return a}return null}function qG(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a?.role==="status_divider"&&a.statusKind==="harness_refinement"&&a.turnId===t&&e.splice(n,1)}}function zG(e){const t=Re(e),n=go(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:TS(t.supportingEvidenceIds),counterevidence:TS(t.counterevidence)}}function BG(e){return Array.isArray(e)?e.flatMap(t=>{const n=Re(t),a=Bn(n?.id),o=go(n?.status,["passed","failed","blocked","skipped"]),r=Bn(n?.summary);return a&&o&&r?[{id:a,status:o,summary:r}]:[]}):[]}function FG(e){return Array.isArray(e)?e.flatMap(t=>{const n=Re(t),a=Bn(n?.id),o=go(n?.operation,["create","update","delete"]),r=Bn(n?.target),s=Bn(n?.summary);return!a||!o||!r||!s?[]:[{id:a,operation:o,target:r,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function ho(e){const t=Re(e),n=Bn(t?.id),a=Bn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function TS(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Bn(e){return typeof e=="string"&&e.trim()?e.trim():null}function go(e,t){return typeof e=="string"&&t.includes(e)?e:null}function DR(e,t){return e==="running"?"Reviewing for a reusable improvement":e==="failed"?"Review failed":t==="no_action"?"No reusable change":t==="routed"?"Issue routed":"Harness change"}function VG(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const ES=64*1024,MS=8*1024;function jS(e,t){const n=LR(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=KG(e,t.turnId);if(a){a.activities=JG(a.activities??[],t,n),a.timestamp=t.timestamp;return}Kd(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Kd(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(o=>o.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function KG(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a.turnId!==t||a.role!=="activity_group")return null;if(!a.activities?.some(o=>o.subagentMessage))return a}return null}function Vh(e,t,n){if(!t.turnId)return;const a=e.filter(l=>l.role==="activity_group"&&l.turnId===t.turnId&&!l.activities?.some(m=>m.subagentMessage)),o=a.filter(l=>l.traceState==="running"),r=o.length>0?o:a.length>0?[a[a.length-1]]:[];for(const l of r)l.traceState=n;const s=r.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function WG(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(a?.turnId!==t.turnId||a.role!=="activity_group")continue;const o=a.activities?.filter(r=>r.controlKind!=="turn_aborted")??[];o.length!==a.activities?.length&&(o.length===0?e.splice(n,1):a.activities=o)}Vh(e,t,"interrupted"),!$G(t.output)&&e.push({id:t.id,role:"status_divider",content:GG(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function GG(e){const t=e.output?.trim()||e.error?.trim();return t?/server shutting down|app restart|local app server stopped/i.test(t)?"Interrupted by app restart":/stopped by user|cancelled by user/i.test(t)?"Stopped by user":t:"Turn interrupted"}function JG(e,t,n=LR(t)){const a=[...e];return i7(a,t,n)||n7(a,t,n)||a7(a,t,n)||o7(a,t,n)?a:[...a,n]}function ZG(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function YG(e,t){const n={id:t.id,role:"status_divider",content:QG(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:XG(t),statusTone:e7(t)};if(t.name!=="session.compaction.started"){const a=ei(e,o=>o.role==="status_divider"&&o.statusKind==="compaction"&&o.statusState==="running"&&o.turnId===t.turnId);if(a){a.id=n.id,a.content=n.content,a.timestamp=n.timestamp,a.statusState=n.statusState,a.statusTone=n.statusTone;return}}e.push(n)}function QG(e){const t=t7(e);return e.name==="session.compaction.started"?t==="auto"?"Auto compacting context":"Compacting context":e.name==="session.compaction.completed"?t==="auto"?"Auto compacted context":"Compacted context":t==="auto"?"Auto compaction failed":"Context compaction failed"}function XG(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function e7(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function t7(e){return Re(e.data)?.reason==="auto"?"auto":"manual"}function LR(e){const t=PG(e),n=e.name==="assistant.reasoning.delta"?"reasoning":h7(e),a=g7(e),o=y7(e),r=b7(e),s=S7(e),l=x7(e),m=AG(e);return{id:e.id,label:l?l.direction==="received"?"Child message received":"Child message sent":l7(e),content:l?.summary??d7(e,t),timestamp:e.timestamp,...n?{kind:n}:{},...e.action?{action:e.action}:{},...a?{kind:"control",controlKind:a}:{},...e.name==="assistant.reasoning.delta"||e.name==="tool.started"||e.name==="tool.completed"||n==="command"?{callId:gb(e)??void 0}:{},...n&&e.name==="command.output"?{detail:Kh(e)}:{},...n==="command"?{terminal:R7(e)}:{},...r?{meta:r}:{},...o?{receipt:o}:{},...s?{openSession:s}:{},...l?{subagentMessage:l}:{},state:s7(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function n7(e,t,n){if(t.name==="tool.completed"){const a=OS(e,t);if(!a)return!1;const o=P7(a.timestamp,t.timestamp);a.label=t.status==="failed"?"Failed":"Ran",a.state=n.state,a.timestamp=t.timestamp,a.artifacts=n.artifacts,a.terminal={...a.terminal,...n.terminal,...o!==null?{durationMs:o}:{}};const r=Kh(t);return r&&r!==a.content&&(a.detail=ku(a.detail,r)),!0}if(t.name==="command.output"){const a=OS(e,t);if(!a)return!1;const o=Kh(t);return o&&(a.detail=ku(a.detail,o)),a.terminal={...a.terminal,...n.terminal},a.timestamp=t.timestamp,n.state==="failed"?a.state="failed":a.state!=="completed"&&a.state!=="failed"&&(a.state="running"),!0}return!1}function a7(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=gb(t),o=ei(e,s=>s.state==="running"&&s.kind!=="command"&&(a?s.callId===a:!!t.action&&s.action===t.action));if(!o)return!1;const r=n.content.trim();return o.id=n.id,o.label=n.label,o.timestamp=n.timestamp,o.state=n.state,r&&r!==o.content.trim()&&(o.content.trim()===o.action?o.content=r:o.detail=ku(o.detail,r)),n.detail&&(o.detail=ku(o.detail,n.detail)),o.meta=n.meta,o.receipt=n.receipt,o.imagePreview=n.imagePreview??o.imagePreview,o.artifacts=n.artifacts,!0}function o7(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=r7(e,t);return a?(a.id=n.id,a.label=n.label,a.content=n.content,a.timestamp=n.timestamp,a.state=n.state,a.detail=n.detail,a.meta=n.meta,a.receipt=n.receipt,a.imagePreview=n.imagePreview,!0):!1}function i7(e,t,n){if(t.name!=="assistant.reasoning.delta")return!1;const a=e[e.length-1];return!a||a.kind!=="reasoning"||n.kind!=="reasoning"||a.action!==n.action||(a.callId||n.callId)&&a.callId!==n.callId?!1:(a.content=`${a.content}${n.content}`,a.timestamp=t.timestamp,!0)}function OS(e,t){const n=gb(t);if(n){const a=ei(e,o=>o.kind==="command"&&o.callId===n);if(a)return a}return ei(e,a=>a.kind==="command")}function r7(e,t){const n=t.action??"",a=HR[n]??{started:"Running workspace action"};return ei(e,o=>o.state==="running"&&o.label===a.started&&o.kind!=="command"&&!o.controlKind)}function s7(e){if(e.name==="turn.interrupted"||e.status==="failed")return"failed";if(e.status==="pending"||e.name==="approval.requested")return"pending";if(e.name==="tool.started"||e.name==="workspace_action"||e.name==="command.output")return"running";if(e.name==="tool.completed"||e.name==="workspace_action_result")return"completed";if(e.status==="started")return"running";if(e.status==="completed")return"completed"}function l7(e){if(e.name==="assistant.reasoning.delta")return ve(Re(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(gm(e))return"Goal context";if(e.name==="turn.interrupted")return"Turn aborted";if(e.name==="subagent.started")return e.status==="started"?"Subagent running":"Started subagent";if(e.name==="subagent.reported")return"Subagent reported";if(e.name==="subagent.progress")return"Subagent progress";if(e.name==="subagent.completed")return"Subagent completed";if(e.name==="subagent.failed")return"Subagent failed";if(e.name==="subagent.workspace_retained")return"Subagent workspace retained";if(e.name==="subagent.archived")return"Subagent archived";if(e.name==="subagent.message")return"Subagent message";if(Fh(e)&&e.name==="tool.started")return"Reading image";if(Fh(e)&&e.name==="tool.completed")return"Read image";if(e.action==="resource_search"&&e.name==="tool.started")return"Searching resources";if(e.action==="resource_search"&&e.name==="tool.completed")return"Searched resources";if(e.action==="resource_read"&&e.name==="tool.started")return"Reading resource";if(e.action==="resource_read"&&e.name==="tool.completed")return"Read resource";if(e.action==="web_fetch"&&e.name==="tool.started")return"Fetching web page";if(e.action==="web_fetch"&&e.name==="tool.completed")return"Fetched web page";if(e.action==="web_search"&&e.name==="tool.started")return"Searching web";if(e.action==="web_search"&&e.name==="tool.completed")return"Searched web";if(e.action==="openpond_action_search"&&e.name==="tool.started")return"Searching actions";if(e.action==="openpond_action_search"&&e.name==="tool.completed")return"Searched actions";if(e.action==="openpond_action_run"&&e.name==="tool.started")return"Running OpenPond action";if(e.action==="openpond_action_run"&&e.name==="tool.completed")return"Ran OpenPond action";const t=EG(e);if(t)return t;const n=m7(e);if(n)return n;const a=u7(e);return a||(e.name==="skill.selected"?"Selected skill":e.name==="skill.loaded"?"Loaded skill":e.name==="skill.load_failed"?"Skill load failed":e.name==="tool.started"?"Started":e.name==="tool.completed"?"Ran":e.name==="command.output"?"Output":e.name==="workspace_action"||e.name==="workspace_action_result"?c7(e):e.name==="approval.requested"?"Approval requested":e.name==="session.compaction.started"?"Compacting context":e.name==="session.compaction.completed"?"Compacted conversation context":e.name==="session.compaction.failed"?"Context compaction failed":e.name.replace("."," "))}const HR={workspace_status:{started:"Checking workspace",completed:"Checked workspace"},resource_search:{started:"Searching resources",completed:"Searched resources"},resource_read:{started:"Reading resource",completed:"Read resource"},list_files:{started:"Listing files",completed:"Listed files"},read_files:{started:"Reading files",completed:"Read files"},search_files:{started:"Searching files",completed:"Searched files"},preview_write_files:{started:"Previewing files",completed:"Previewed files"},preview_write_file:{started:"Previewing file",completed:"Previewed file"},preview_edit_file:{started:"Previewing edit",completed:"Previewed edit"},preview_delete_file:{started:"Previewing delete",completed:"Previewed delete"},write_files:{started:"Editing files",completed:"Edited files",failed:"File checks failed"},write_file:{started:"Editing file",completed:"Edited file",failed:"File checks failed"},edit_file:{started:"Editing file",completed:"Edited file",failed:"File checks failed"},delete_file:{started:"Deleting file",completed:"Deleted file",failed:"File checks failed"},validate_sandbox_template:{started:"Validating template",completed:"Validated template",failed:"Template validation failed"},build_sandbox_template:{started:"Building template",completed:"Built template",failed:"Template build failed"},run_sandbox_template:{started:"Running sandbox template",pending:"Sandbox template log",completed:"Ran sandbox template",failed:"Sandbox template failed"},git_status:{started:"Checking git status",completed:"Checked git status"},git_fetch:{started:"Fetching git",completed:"Fetched git",failed:"Git fetch failed"},git_commit:{started:"Committing changes",completed:"Committed changes",failed:"Commit failed"},git_push:{started:"Pushing changes",completed:"Pushed changes",failed:"Push failed"},publish_openpond_repo:{started:"Publishing to OpenPond",completed:"Published to OpenPond",failed:"Publish failed"},upload_cloud_source:{started:"Uploading source",completed:"Uploaded source",failed:"Upload failed"},sandbox_create:{started:"Starting sandbox",completed:"Started sandbox",failed:"Sandbox start failed"},sandbox_status:{started:"Checking sandbox",completed:"Checked sandbox",failed:"Sandbox status failed"},sandbox_list_files:{started:"Listing sandbox files",completed:"Listed sandbox files",failed:"Sandbox file list failed"},sandbox_read_file:{started:"Reading sandbox file",completed:"Read sandbox file",failed:"Sandbox file read failed"},sandbox_search_files:{started:"Searching sandbox files",completed:"Searched sandbox files",failed:"Sandbox search failed"},sandbox_run_action:{started:"Running sandbox action",completed:"Ran sandbox action",failed:"Sandbox action failed"},sandbox_upload_file:{started:"Uploading file",completed:"Uploaded file",failed:"Upload failed"},sandbox_write_file:{started:"Writing sandbox file",completed:"Wrote sandbox file",failed:"Write failed"},sandbox_edit_file:{started:"Editing sandbox file",completed:"Edited sandbox file",failed:"Edit failed"},sandbox_delete_file:{started:"Deleting sandbox file",completed:"Deleted sandbox file",failed:"Delete failed"},sandbox_mkdir:{started:"Creating sandbox directory",completed:"Created sandbox directory",failed:"Directory create failed"},sandbox_move_file:{started:"Moving sandbox file",completed:"Moved sandbox file",failed:"Move failed"},sandbox_exec:{started:"Running sandbox command",completed:"Ran sandbox command",failed:"Sandbox command failed"},sandbox_git_status:{started:"Checking sandbox git",completed:"Checked sandbox git"},sandbox_git_diff:{started:"Reading sandbox diff",completed:"Read sandbox diff"},sandbox_git_export_patch:{started:"Exporting sandbox patch",completed:"Exported sandbox patch",failed:"Patch export failed"},sandbox_git_apply_patch_local:{started:"Applying sandbox patch locally",completed:"Applied locally",failed:"Apply locally failed"},sandbox_git_branch:{started:"Switching sandbox branch",completed:"Switched sandbox branch",failed:"Branch failed"},sandbox_git_commit:{started:"Committing sandbox changes",completed:"Committed sandbox changes",failed:"Commit failed"},sandbox_git_pull:{started:"Pulling sandbox changes",completed:"Pulled sandbox changes",failed:"Pull failed"},sandbox_git_push:{started:"Pushing sandbox changes",completed:"Pushed sandbox changes",failed:"Push failed"},sandbox_preserve_source:{started:"Preserving sandbox source",completed:"Preserved sandbox source",failed:"Preserve failed"},sandbox_promote_source:{started:"Promoting sandbox source",completed:"Promoted sandbox source",failed:"Promote failed"},sandbox_logs:{started:"Reading sandbox logs",completed:"Read sandbox logs",failed:"Sandbox logs failed"},sandbox_receipts:{started:"Reading sandbox receipts",completed:"Read sandbox receipts",failed:"Sandbox receipts failed"},sandbox_stop:{started:"Stopping sandbox",completed:"Stopped sandbox",failed:"Sandbox stop failed"},file_change:{started:"Editing files",completed:"Edited files"}};function c7(e){const t=e.action??"",n=HR[t]??{started:"Running workspace action",completed:"Workspace action completed",failed:"Workspace action failed"};return e.name==="workspace_action"?e.status==="pending"?n.pending??n.started:n.started:e.status==="failed"?n.failed??`${n.completed} failed`:n.completed}function d7(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=NR(e.output??"");if(n)return n.text;if(gm(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=p7(e);if(a)return a;const o=f7(e);if(o)return o;const r=MG(e);if(r)return r;const s=UR(e);if(s)return s;if(e.name==="command.output")return zR(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const l=e.data;if(l&&typeof l=="object"){const m=l.command;if(typeof m=="string"&&m.trim())return m;const d=l.tool;if(typeof d=="string"&&d.trim())return d;const h=l.type;if(typeof h=="string"&&h.trim())return h}}return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"?e.error??e.output??"":e.output??e.action??""}function u7(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.status==="failed";return e.action==="openpond_create_improve"?e.name==="tool.started"?"Starting Create Pipeline":t?"Create Pipeline failed":"Started Create Pipeline":null}function m7(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return null;const t=e.status==="failed",n=e.name==="tool.completed";switch(e.action){case"openpond_browser_open":return n?t?"Browser open failed":"Opened browser":"Opening browser";case"openpond_browser_snapshot":return n?t?"Browser capture failed":"Captured browser":"Capturing browser";case"openpond_browser_move_cursor":return n?t?"Cursor move failed":"Moved browser cursor":"Moving browser cursor";case"openpond_browser_click":return n?t?"Browser click failed":"Clicked browser":"Clicking browser";case"openpond_browser_type":return n?t?"Browser typing failed":"Typed in browser":"Typing in browser";case"openpond_browser_key":return n?t?"Browser key failed":"Pressed browser key":"Pressing browser key";case"openpond_browser_scroll":return n?t?"Browser scroll failed":"Scrolled browser":"Scrolling browser";default:return null}}function p7(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Re(Re(e.data)?.result),n=ve(t,["output"]);if(n)return n;const a=Re(Oi(e.output??"")),o=ve(a,["output"]);if(o)return o;const r=Re(e.args),s=ve(r,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function f7(e){if(e.action!=="openpond_create_improve")return null;const t=Re(Re(e.data)?.result),n=ve(t,["nextStep"]);if(n)return n;const a=Re(Oi(e.output??"")),o=ve(a,["output"]);if(o)return o;const r=Re(e.args),s=ve(r,["reason"]);if(s)return s;const l=ve(r,["objective"]);return l||(e.error??null)}function h7(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Re(e.data),n=ve(t,["type"]),a=ve(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||UR(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function g7(e){if(e.name==="turn.interrupted")return"turn_aborted";if(gm(e))return"goal_context"}function UR(e){const t=Re(e.data),n=ve(t,["type"]),a=ve(t,["tool","toolName","tool_name","name","functionName","function_name"]),o=Re(t?.result),r=Re(Oi(e.output??"")),s=Re(r?.data),l=ve(t,["command","cmd"])??ve(Re(t?.input),["command","cmd"])??ve(Re(t?.arguments),["command","cmd"])??ve(Re(t?.args),["command","cmd"])??v7(ve(t,["arguments","args","input"]))??ve(Re(e.args),["command","cmd"])??ve(o,["command","cmd"])??ve(s,["command","cmd"]);return l||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function v7(e){if(!e)return null;const t=Oi(e),n=Re(t);return ve(n,["command","cmd"])}function gb(e){const t=Re(e.data);return ve(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function b7(e){const t=Re(e.data);if(!t)return null;const n=[],a=Re(t.workspaceToolTiming),o=typeof a?.durationMs=="number"?a.durationMs:null;o!==null&&n.push(I7(o));const r=Re(t.workspaceExecutionTarget),s=ve(r,["target"]);if(s==="sandbox"){const d=r?.hybrid===!0,h=ve(r,["sandboxId","workspaceId"]);n.push(`${d?"Hybrid ":""}sandbox${h?` ${$S(h)}`:""}`)}else s==="local"&&n.push("local workspace");const l=Re(t.sourcePreservation);if(l?.attempted===!0)if(l.ok!==!0)n.push("checkpoint failed");else if(l.preserved===!0){const d=ve(l,["preservedSha"]);n.push(d?`checkpoint ${C7(d)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=qR(t);return m&&(n.push(`receipt ${$S(m.id)}`),n.push(`${_7(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function y7(e){const t=qR(Re(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function S7(e){if(!e.name.startsWith("subagent."))return;const t=Re(e.data),n=Re(t?.run),a=ve(t,["childSessionId"])??ve(n,["childSessionId"]);if(!a)return;const o=ve(n,["roleId"])??ve(t,["roleId"]),r=ve(n,["status"])??ve(t,["status"]);return{sessionId:a,label:"Open conversation",...o?{roleId:o}:{},...r?{status:r}:{}}}function x7(e){if(e.name!=="subagent.message")return;const t=Re(e.data),n=Re(t?.message);if(!n)return;const a=ve(n,["id"]),o=ve(n,["kind"]),r=ve(n,["fromRunId"]),s=ve(n,["body"]);if(!a||!o||!r||!s)return;const l=Re(t?.delivery??n.delivery),m=Re(t?.modelRef),d=ve(m,["providerId"]),h=ve(m,["modelId"]),y=ve(l,["deliveredParentSessionId"])===e.sessionId&&!r.startsWith("parent:")?"received":"sent",w=Array.isArray(n.refs)?n.refs.flatMap(_=>{const P=Re(_),M=ve(P,["kind"]),C=ve(P,["id"]),$=ve(P,["label"]);return M&&C&&$?[{kind:M,id:C,label:$}]:[]}):[];return{direction:y,summary:k7(s),body:s,messageId:a,kind:o,fromRunId:r,toRunId:ve(n,["toRunId"]),toRole:ve(n,["toRole"]),childSessionId:ve(t,["childSessionId"]),roleId:ve(t,["roleId"]),modelRef:d&&h?{providerId:d,modelId:h}:null,deliveryStatus:ve(l,["status"]),wakeReason:ve(l,["wakeParentReason"]),createdAt:ve(n,["createdAt"]),refs:w}}function k7(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return w7(n,96)}function w7(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),o=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,o).trimEnd()}...`}function qR(e){const t=Re(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const o=Re(n[a]),r=ve(o,["id"]),s=ve(o,["status"]),l=ve(o,["totalUsd","retailTotalUsd"]);if(r&&s&&l)return{id:r,status:s,totalUsd:l}}return null}function I7(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function _7(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function C7(e){return e.length>12?e.slice(0,12):e}function $S(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function zR(e){let t=e.replace(/\r\n/g,`
|
|
189
|
-
`).trim();if(!t)return"";const n=A7(t);if(n!==null)return bs(n);const a=`
|
|
190
|
-
Output:
|
|
191
|
-
`,o=t.indexOf(a);return o>=0&&T7(t.slice(0,o))&&(t=t.slice(o+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),bs(t.trim())}function Kh(e){const t=zR(e.output??"");if(t)return t;const n=Re(Re(e.data)?.result);return n?bs(BR(n)):""}function R7(e){const t=Re(e.data),n=Re(t?.result),a=Re(Oi(e.output??"")),o=Re(a?.data),r=Re(t?.workspaceToolTiming),s=[n?.exitCode,o?.exitCode,t?.exitCode].find(m=>typeof m=="number"),l=r?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof l=="number"?{durationMs:l}:{}}}function P7(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function A7(e){const t=Re(Oi(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=Re(t.data);return a?BR(a,ve(t,["output"])):typeof t.output=="string"?t.output.trim():""}function BR(e,t=null){const n=ve(e,["stdout"])?.replace(/\r\n/g,`
|
|
192
|
-
`).trimEnd()??"",a=ve(e,["stderr"])?.replace(/\r\n/g,`
|
|
193
|
-
`).trimEnd()??"",o=[n,a].filter(Boolean);return o.length>0?o.join(`
|
|
194
|
-
`):t?.replace(/\r\n/g,`
|
|
195
|
-
`).trim()??""}function T7(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function ku(e,t){const n=e??"";if(!n)return bs(t);if(n===t||n.includes(t))return n;if(t.includes(n))return bs(t);const a=n.endsWith(`
|
|
196
|
-
`)||t.startsWith(`
|
|
197
|
-
`)?"":`
|
|
198
|
-
`;return bs(`${n}${a}${t}`)}function bs(e){if(e.length<=ES)return e;const t=`
|
|
199
|
-
|
|
200
|
-
… output omitted from live view; full output remains in task history …
|
|
201
|
-
|
|
202
|
-
`,n=Math.max(0,ES-MS-t.length);return`${e.slice(0,MS)}${t}${e.slice(-n)}`}const E7=/\bopenpond\s+opchat\b/i,M7=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function FR(e){const t=e?.trim()||"Turn failed";return E7.test(t)&&M7.test(t)?"Server connection lost. Retry your message.":t}function j7(e,t){if((kd(t,"code")??kd(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(kd(a,"code")??kd(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const o=e??"";return/\bopchat_quota_exceeded\b/i.test(o)||/OpChat token allowance is exhausted/i.test(o)?"opchat_quota_exceeded":null}function kd(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function O7(e){const t=new Map,n=new Set;for(const a of e)a.turnId&&(a.role==="assistant"&&a.content?.trim()&&t.set(a.turnId,a.content),(a.role==="error"||a.role==="status_divider"&&a.statusState!=="running"||a.role==="activity_group"&&a.traceState!=="running")&&n.add(a.turnId));for(const a of e){if(a.role!=="activity_group"||!a.turnId||a.activities?.some(l=>l.subagentMessage))continue;const o=$7(a.activities??[]);if(o.length===0){a.deliverables=void 0;continue}const r=t.get(a.turnId)??"",s=r?N7(o,r):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[o[o.length-1]]:void 0}}function $7(e){const t=new Set(e.map(a=>a.imagePreview?.path).filter(a=>!!a)),n=new Map;for(const a of e)if(!a.imagePreview)for(const o of a.artifacts??[])t.has(o.path)||(n.delete(o.path),n.set(o.path,o));return[...n.values()]}function N7(e,t){const n=VR(t);return e.filter(a=>D7(a).some(o=>t.includes(o)||n.includes(o)))}function D7(e){const t=new Set;for(const n of[e.path,e.title,L7(e.path)]){const a=n.trim();a&&(t.add(a),t.add(VR(a)))}return[...t]}function L7(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function VR(e){try{return decodeURIComponent(e)}catch{return e}}const KR=8;function H7(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=Gh(e.data),n=e.output?Gh(Oi(e.output)):null;return U7(t??n)}function Wh(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const o of[...e??[],...t]){const r=WR(o.url);if(!(!r||a.has(r))&&(a.add(r),n.push(o),n.length>=KR))break}return n.length>0?n:void 0}function Gh(e,t=0){if(t>5)return null;const n=Re(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:ve(n,["url"])?[n]:null;if(a)return{provider:ve(n,["provider"]),results:a};for(const o of["result","data","output"]){const r=Gh(n[o],t+1);if(r)return r}return null}function U7(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const o=q7(e.results[a],a,e.provider);if(!o)continue;const r=WR(o.url);if(!(!r||n.has(r))&&(n.add(r),t.push(o),t.length>=KR))break}return t}function q7(e,t,n){const a=Re(e);if(!a)return null;const o=ve(a,["url","href"]);if(!o||!z7(o))return null;const r=ve(a,["title"])??NS(o)??`Source ${t+1}`;return{id:ve(a,["id"])??`source_${t+1}`,title:r,url:o,sourceName:ve(a,["sourceName","source_name","source"])??NS(o),snippet:ve(a,["snippet","description"]),provider:n,faviconUrl:B7(ve(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??F7(o),publishedAt:ve(a,["publishedAt","published_at"]),updatedAt:ve(a,["updatedAt","updated_at"])}}function z7(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function WR(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function B7(e){if(!e)return null;try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.toString()}catch{return null}}function F7(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function NS(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const DS=new WeakMap;function vm(e){const t=DS.get(e);if(t)return t;const n=V7(e);return DS.set(e,n),n}function V7(e){const t=[],n=new Set,a=new Map;for(const o of e){if(o.name==="task.input"){const r=B_.safeParse(Re(o.data)?.input);r.success&&r.data.senderKind==="user"&&r.data.kind==="steer"&&!n.has(r.data.id)&&(n.add(r.data.id),t.push({id:`task-input:${r.data.id}`,role:"user",content:r.data.body,timestamp:o.timestamp,turnId:r.data.turnId??void 0}));continue}if(o.name==="turn.started"){Kd(t,o),K7(t,o);const r=Z7(o.args);if(r){const s=NR(r);if(s){jS(t,{...o,name:s.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:s.text,data:{...Re(o.data)??{},kind:s.kind}});continue}t.push({id:o.id,role:"user",content:r,attachments:Y7(o.args),timestamp:o.timestamp,turnId:o.turnId});const l=HS(o.args);l&&t.push({id:`${o.id}:create-improve`,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,createImproveRun:l})}continue}if(o.name==="create_improve.updated"){const r=HS(o.data);if(!r)continue;const s=ei(t,l=>l.turnId===o.turnId&&!!l.createImproveRun);s?(s.createImproveRun=r,s.timestamp=o.timestamp):t.push({id:`${o.id}:create-improve`,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,createImproveRun:r});continue}if(o.name==="assistant.delta"){const r=o.output??"";if(!r)continue;Kd(t,o);const s=t[t.length-1];if(s?.role==="assistant"&&s.turnId===o.turnId&&!s.createImproveRun)s.content=`${s.content??""}${r}`,s.timestamp=o.timestamp,s.sources=Wh(s.sources,LS(a,o.turnId)??[]);else{const l=LS(a,o.turnId);t.push({id:o.id,role:"assistant",content:r,timestamp:o.timestamp,turnId:o.turnId,...l?.length?{sources:l}:{}})}continue}if(o.name==="assistant.reasoning.delta"){const r=o.output??"";if(!r)continue;Kd(t,o);const s=t[t.length-1];s?.role==="assistant"&&s.turnId===o.turnId&&s.reasoningContent!==void 0&&!s.createImproveRun?(s.reasoningContent=`${s.reasoningContent}${r}`,s.timestamp=o.timestamp):s?.role==="assistant"&&s.turnId===o.turnId&&!s.reasoningContent&&!s.createImproveRun?(s.reasoningContent=r,s.timestamp=o.timestamp):t.push({id:o.id,role:"assistant",reasoningContent:r,timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="user_question.asked"){const r=Re(o.data),s=OO.safeParse(r?.question);if(!s.success)continue;t.push({id:o.id,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,userQuestion:s.data});continue}if(o.name==="user_question.answered"||o.name==="user_question.dismissed"){const r=Re(o.data),s=$O.safeParse(r?.resolution);if(!s.success)continue;const l=ei(t,m=>m.userQuestion?.id===s.data.questionId);if(!l?.userQuestion||l.userQuestion.status!=="pending")continue;l.userQuestion={...l.userQuestion,status:s.data.action==="answer"?"answered":"dismissed",answer:s.data.action==="answer"?{optionId:s.data.optionId,text:s.data.text}:null,answeredAt:o.timestamp},l.timestamp=o.timestamp;continue}if(o.name==="turn.completed"){Vh(t,o,"completed");continue}if(o.name==="turn.failed"){Vh(t,o,"failed");const r=o.error??"Turn failed",s=j7(r,o.data);t.push({id:o.id,role:"error",content:FR(r),...s?{errorKind:s}:{},timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="turn.interrupted"){WG(t,o);continue}if(ZG(o)){YG(t,o);continue}if(o.name.startsWith("harness.refiner.")){NG(t,o);continue}if(o.name==="tool.started"||o.name==="tool.completed"||o.name==="skill.selected"||o.name==="skill.loaded"||o.name==="skill.load_failed"||o.name==="command.output"||o.name==="workspace_action"||o.name==="workspace_action_result"||o.name==="approval.requested"||o.name.startsWith("subagent.")||gm(o)){if(G7(o))continue;const r=SG(o);if(r){yG(t,o,r);continue}const s=H7(o);s.length>0&&W7(t,a,o.turnId,s),jS(t,o)}if(o.name==="workspace.diff"){const r=J7(o.data);if(!r||r.filesChanged===0)continue;const s=ei(t,l=>l.role==="assistant"&&l.turnId===o.turnId);s&&(s.changeSummary=r,s.timestamp=o.timestamp)}}return O7(t),t}function K7(e,t){if(Re(t.args)?.interactionKind!=="steer")return;const n=e.at(-1);n?.role==="status_divider"&&n.statusKind==="interruption"&&n.content==="Stopped by user"&&e.pop()}function W7(e,t,n,a){if(!n)return;const o=e[e.length-1];if(o?.role!=="assistant"||o.turnId!==n){t.set(n,Wh(t.get(n),a));return}o.sources=Wh(o.sources,a)}function LS(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function G7(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=Re(e.data),n=Re(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function J7(e){const t=G2.safeParse(e);return t.success?t.data:null}function Z7(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function Y7(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=AL.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function HS(e){const t=Re(e);if(!t)return null;const n=bc.safeParse(t.createImproveRun);return n.success?n.data:null}function pte(e){if(!e)return"";const t=new Date(e).getTime();if(Number.isNaN(t))return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h`:`${Math.floor(o/24)}d`}function fte(e){const t=GR(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function hte(e){const t=GR(e);return t?t.toLocaleString():""}function GR(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function Q7(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[o,r]=v.useState({}),s=v.useCallback(m=>{r(d=>({...d,[m.sessionId]:m}))},[]);v.useEffect(()=>{r(m=>{let d=m;for(const[h,g]of Object.entries(m)){const y=vm(Hc(n,h));MR(y,g)&&(d===m&&(d={...m}),delete d[h])}return d})},[n]);const l=v.useMemo(()=>ER(t,a?o[a]:null),[t,o,a]);return{pendingChatUserMessages:o,recordPendingChatUserMessage:s,visibleChatMessages:l}}function X7({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:o,setSessions:r}){return{changeOpenPondCommandAccessMode:v.useCallback((l,m=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const d=m?.provider==="codex"?null:m;Q.savePreferences(e,{openPondCommandAccessMode:l}).then(h=>{o(h.preferences.openPondCommandAccessMode),n(g=>g&&{...g,preferences:h.preferences})}).catch(h=>{a(h instanceof Error?h.message:String(h))}),d&&Q.patchSession(e,d.id,{openPondCommandAccessMode:l}).then(h=>{r(g=>g.map(y=>y.id===h.id?h:y))}).catch(h=>{a(h instanceof Error?h.message:String(h))})},[e,t,n,a,o,r])}}function eJ({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:o,selectedSessionId:r,selectedProjectId:s,archivedChatsOpen:l,projectsExpanded:m,chatRowsVisibleCount:d,sidebarFileBookmarks:h=[]}){const g=v.useMemo(()=>e.filter(ie=>!ie.hiddenFromDefaultSidebar),[e]),y=v.useMemo(()=>n.filter(ie=>!ie.archived&&US(ie)),[n]),w=v.useMemo(()=>y.filter(ie=>ie.pinned),[y]),_=v.useMemo(()=>y.filter(ie=>!!ie.savedForLater),[y]),P=v.useMemo(()=>n.filter(ie=>ie.archived&&US(ie)),[n]),M=v.useMemo(()=>new Set(e.map(ie=>ie.id)),[e]),C=v.useMemo(()=>new Set(t.map(ie=>ie.id)),[t]),$=v.useMemo(()=>AC(e),[e]),O=v.useMemo(()=>{const ie={};for(const Se of[...y,...P]){const Ue=K0(Se,M,$,C);Ue&&(ie[Se.id]=Ue)}return ie},[y,P,C,M,$]),j=v.useMemo(()=>y.filter(ie=>!ie.pinned&&!ie.savedForLater&&!ie.appId&&!O[ie.id]),[y,O]),x=v.useMemo(()=>P.filter(ie=>!ie.appId&&!K0(ie,M,$,C)),[P,C,M,$]),R=v.useMemo(()=>{const ie={};for(const Se of y){if(Se.pinned||Se.savedForLater)continue;const Ue=O[Se.id];if(!Ue)continue;const Je=ie[Ue];Je?Je.push(Se):ie[Ue]=[Se]}return ie},[y,O]),E=v.useMemo(()=>{const ie={};for(const Se of n){if(Se.archived||!JR(Se))continue;const Ue=ie[Se.parentSessionId];Ue?Ue.push(Se):ie[Se.parentSessionId]=[Se]}for(const Se of Object.values(ie))Se.sort((Ue,Je)=>Date.parse(Je.updatedAt)-Date.parse(Ue.updatedAt));return ie},[n]),H=v.useMemo(()=>g.map((ie,Se)=>{const Ue=St("local",ie.id),Je=i8(ie,t);return{id:Ue,kind:"local",project:ie,pinned:!!o[Ue]?.pinned,order:o[Ue]?.order??Se,cloudLinkTrusted:!Je,cloudLinkWarning:Je}}).sort($f),[o,t,g]),B=v.useMemo(()=>t.map((ie,Se)=>{const Ue=St("cloud",ie.id);return{id:Ue,kind:"cloud",project:ie,pinned:!!o[Ue]?.pinned,order:o[Ue]?.order??Se,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort($f),[o,t]),D=v.useMemo(()=>new Set(g.map(ie=>Oa(ie,t)?.id??null).filter(ie=>!!ie)),[t,g]),J=v.useMemo(()=>B.filter(ie=>!D.has(ie.project.id)),[B,D]),le=v.useMemo(()=>[...H,...J].sort($f),[J,H]),ue=v.useMemo(()=>le.filter(ie=>ie.pinned),[le]),je=v.useMemo(()=>h.filter(ie=>ie.status==="pinned"),[h]),ke=v.useMemo(()=>h.filter(ie=>ie.status==="saved_for_later"),[h]),te=le,Me=v.useMemo(()=>tJ(te,m,s),[te,m,s]),ye=v.useMemo(()=>[...ue.map(ie=>({type:"project",key:tr({type:"project",id:ie.id}),id:ie.id,item:ie,order:ie.order})),...w.map(ie=>({type:"session",key:tr({type:"session",id:ie.id}),id:ie.id,session:ie,order:ie.order})),...je.map((ie,Se)=>({type:"file",key:tr({type:"file",id:ie.id}),id:ie.id,file:ie,order:ie.order??ue.length+w.length+Se}))].sort((ie,Se)=>{if(ie.order!==Se.order)return ie.order-Se.order;if(ie.type!==Se.type){const Ke={project:0,session:1,file:2};return Ke[ie.type]-Ke[Se.type]}const Ue=ie.type==="project"?ie.item.project.name:ie.type==="session"?ie.session.title:ie.file.path,Je=Se.type==="project"?Se.item.project.name:Se.type==="session"?Se.session.title:Se.file.path;return Ue.localeCompare(Je)}),[je,ue,w]),ne=v.useMemo(()=>l?[...j,...x]:j,[l,x,j]),be=v.useMemo(()=>ne.slice(0,Math.max(En,d)),[ne,d]),ae=v.useMemo(()=>Hc(a,r),[a,r]),de=v.useMemo(()=>vm(ae),[ae]),xe=uR(a,r),De=mR(a,r),we=VW(a,r);return{activeSessions:y,pinnedSessions:w,savedForLaterSessions:_,pinnedFiles:je,savedForLaterFiles:ke,chatSessions:j,archivedSessions:P,pinnedProjects:ue,pinnedItems:ye,projectRows:te,localProjectRows:H,visibleProjectRows:Me,cloudProjectRows:J,projectSessionRowsByProjectId:R,childSessionRowsByParentId:E,sidebarProjectIdBySessionId:O,chatRows:ne,visibleChatRows:be,sessionEvents:ae,chatMessages:de,contextUsage:xe,goalRuntime:De,subagentRuntime:we}}function US(e){return JR(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function JR(e){return!!(e.parentSessionId&&e.subagentRunId)}function $f(e,t){return e.pinned!==t.pinned?e.pinned?-1:1:e.order!==t.order?e.order-t.order:e.project.name.localeCompare(t.project.name)}function tJ(e,t,n){if(t||e.length<=qd)return e;const a=e.slice(0,qd);if(!n||a.some(r=>r.id===n))return a;const o=e.find(r=>r.id===n);return o?[...a.slice(0,qd-1),o]:a}function nJ(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function ZR(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(o?.name==="turn.started"){t=a,n=o.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const o=e[a];if(!(!o||!nJ(o))&&!(n&&o.turnId&&o.turnId!==n))return o.name==="turn.completed"?"completed":"blocked"}return"pending"}function qS(e,t){if(e.systemKind)return!1;const n=Hc(t,e.id);if(n.length===0)return!1;const a=ZR(n);return a==="pending"||a==="none"&&YR(n)==="pending"}function zS(e,t){if(e.systemKind||e.status!=="active")return!1;const n=Hc(t,e.id);if(n.length===0)return!0;const a=ZR(n);return a==="pending"||a==="none"&&YR(n)!=="terminal"}function YR(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n){if(n.name==="turn.completed"||n.name==="turn.failed"||n.name==="turn.interrupted")return"terminal";if(n.name==="assistant.delta"||n.name==="assistant.reasoning.delta"||n.name==="tool.started"||n.name==="tool.completed"||n.name==="skill.selected"||n.name==="skill.loaded"||n.name==="skill.load_failed"||n.name==="approval.requested"||n.name==="approval.resolved"||n.name==="command.output"||n.name==="workspace_action"||n.name==="workspace_action_result")return"pending"}}return"none"}function aJ({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:o,sidebarSessions:r,subagentRuntimeBySessionId:s}){const l=v.useMemo(()=>new Map(r.map(y=>[y.id,y])),[r]),m=v.useMemo(()=>{const y=new Set;for(const[w,_]of t??[]){const P=l.get(w);_.tone==="active"&&!P?.systemKind&&y.add(w)}for(const w of n.activeGoalSessionIds)l.get(w)?.systemKind||y.add(w);return o&&!a?.systemKind&&e?.tone==="active"&&y.add(o),y},[e,t,n,a,o,l]),d=v.useMemo(()=>{const y=new Set(m);for(const[w,_]of s??[]){const P=l.get(w);_.activeCount>0&&!P?.systemKind&&y.add(w)}for(const w of n.activeSubagentSessionIds)l.get(w)?.systemKind||y.add(w);for(const w of r)w.systemKind||qS(w,n)&&y.add(w.id);return a&&qS(a,n)&&y.add(a.id),y},[m,n,a,r,l,s]),h=v.useMemo(()=>{const y=new Set(d);for(const w of r)zS(w,n)&&y.add(w.id);return a&&zS(a,n)&&y.add(a.id),y},[d,n,a,r]),g=!!(a&&!a.systemKind&&d.has(a.id));return{runningSessionIds:h,selectedSessionRunning:g}}const oJ=1e3;function iJ(e){const[t,n]=v.useState(()=>new Date().toISOString());return v.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const o=window.setInterval(a,oJ);return()=>window.clearInterval(o)},[e]),t}function rJ(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:o,goalRuntime:r,locallyActiveCodexHistorySessionIds:s,pinnedSessions:l,savedForLaterSessions:m,projectSessionRowsByProjectId:d,rightChatHistoryEvents:h,runtimeIndexes:g,selectedSession:y,selectedSessionId:w,serverId:_,setCodexHistorySessions:P,sidebarSessions:M,subagentRuntime:C,visibleChatRows:$,visibleProjectRows:O}=e,[j,x]=v.useState({});v.useEffect(()=>{x({})},[_]);const R=v.useMemo(()=>{const ne=[],be=new Set,ae=xe=>{!xe||xe.id===w||!qt(xe.id)||be.has(xe.id)||(be.add(xe.id),ne.push(xe.id))};for(const xe of n)(xe.status==="active"||s.has(xe.id))&&ae(xe);const de=ne.length;for(const xe of O)for(const De of(d[xe.id]??[]).slice(0,2))ae(De);for(const xe of o)for(const De of(d[xe]??[]).slice(0,qd))ae(De);for(const xe of l)ae(xe);for(const xe of m)ae(xe);for(const xe of $)ae(xe);return[...ne.slice(0,de),...ne.slice(de,de+8)].join(`
|
|
203
|
-
`)},[n,o,s,l,m,d,w,$,O]),E=v.useCallback(ne=>{x(be=>be[ne.session.id]===ne.events?be:{...be,[ne.session.id]:ne.events}),P(be=>hm(be,ne.session))},[P]),H=v.useMemo(()=>{if(!R)return"";const ne=new Set(R.split(`
|
|
204
|
-
`).filter(Boolean));return M.filter(be=>ne.has(be.id)&&be.status==="active").map(be=>be.id).join(`
|
|
205
|
-
`)},[R,M]),B=v.useMemo(()=>R?R.split(`
|
|
206
|
-
`).filter(ne=>s.has(ne)).join(`
|
|
207
|
-
`):"",[R,s]);v.useEffect(()=>{!y||!w||!qt(w)||t.length===0||E({session:y,events:t})},[E,t,y,w]),v.useEffect(()=>{if(!a||!R)return;const ne=a,be=R.split(`
|
|
208
|
-
`).filter(Boolean),ae=new Set(H.split(`
|
|
209
|
-
`).filter(Boolean)),de=new Set(B.split(`
|
|
210
|
-
`).filter(Boolean)),xe=be.map(De=>hb({connection:ne,locallyActive:de.has(De),onPayload:we=>E(fb(we,de.has(De))),reportedActive:ae.has(De),sessionId:De,surface:"sidebar"}));return()=>xe.forEach(De=>De())},[E,H,B,R,a]);const D=v.useMemo(()=>new Map(M.map(ne=>[ne.id,ne])),[M]),J=v.useMemo(()=>{const ne=new Map(g.latestGoalRuntimeBySessionId);for(const be of M){const ae=be.status==="active"?Pf(be.metadata):null;ae&&ne.set(be.id,ae)}for(const be of[j,h])for(const[ae,de]of Object.entries(be)){const xe=D.get(ae),De=xe?.status==="active"?Pf(xe.metadata):null,we=Nh(de)??db(de)??(xe?.status==="active"?xu(de)??De:null);we?ne.set(ae,we):ne.delete(ae)}if(w)if(r)ne.set(w,r);else if(y?.status==="active"&&t.length>0){const be=Nh(t)??xu(t)??Pf(y.metadata);be?ne.set(w,be):ne.delete(w)}else(!qt(w)||t.length>0)&&ne.delete(w);return ne},[t.length,j,r,h,g.latestGoalRuntimeBySessionId,y?.status,y?.metadata,w,D,M]),le=v.useMemo(()=>[...J.values()].some(ne=>ne.tone==="active"&&!!ne.observedAt),[J]),ue=iJ(le),je=v.useMemo(()=>le?new Map([...J].map(([ne,be])=>[ne,xW(be,ue)??be])):J,[J,ue,le]),ke=w?je.get(w)??r:r,te=v.useMemo(()=>{const ne=new Map(g.latestSubagentRuntimeBySessionId);return w&&(C?ne.set(w,C):ne.delete(w)),ne},[g.latestSubagentRuntimeBySessionId,w,C]),{runningSessionIds:Me,selectedSessionRunning:ye}=aJ({goalRuntime:ke,goalRuntimeBySessionId:je,runtimeIndexes:g,selectedSession:y,selectedSessionId:w,sidebarSessions:M,subagentRuntimeBySessionId:te});return{goalRuntime:ke,runningSessionIds:Me,selectedSessionRunning:ye,sidebarGoalRuntimeBySessionId:je,sidebarSubagentRuntimeBySessionId:te}}function sJ({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:o}){v.useEffect(()=>{const r=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(l=>!l);return}if(s.key==="Escape"&&e){s.preventDefault(),a(!1),o(""),n(null);return}s.key==="Escape"&&t&&(s.preventDefault(),n(null))};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[e,t,o,a,n])}function lJ({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:o,setError:r,onDisconnected:s}){v.useEffect(()=>{if(!n?.token||e===null)return;const l=n;let m=null,d=[],h=null,g=null,y=!1;const w=new Map;let _=0;const P=16;function M(){m!==null&&(window.clearTimeout(m),m=null)}function C(){r(D=>D==="Event stream disconnected"?null:D)}function $(){h=null;const D=d;if(d=[],D.length===0)return;_=Date.now(),t(D);const J=cJ(D);J.length>0&&o(le=>J.reduce(Al,le)),a(le=>{let ue=le;for(const je of D)if(je.name==="approval.requested"&&je.data&&(ue=[je.data,...ue]),je.name==="approval.resolved"&&je.data&&typeof je.data=="object"){const ke=je.data;ke.approvalId&&(ue=ue.filter(te=>te.id!==ke.approvalId))}return ue})}function O(){const D=Date.now()-_;if(D>=P){h!==null&&(window.clearTimeout(h),h=null),$();return}h===null&&(h=window.setTimeout($,P-D))}function j(D){x(D),d.push(D),O()}function x(D){if(!(!D.sessionId||!D.name.startsWith("harness.refiner."))){if(D.name==="harness.refiner.completed"||D.name==="harness.refiner.failed"){w.delete(D.sessionId);return}(D.name==="harness.refiner.queued"||D.name==="harness.refiner.started")&&(w.set(D.sessionId,typeof D.sequence=="number"?D.sequence:0),R())}}function R(){g!==null||w.size===0||(g=window.setTimeout(()=>{g=null,E()},1e3))}async function E(){if(!(y||w.size===0)){y=!0;try{await Promise.all([...w].map(async([D,J])=>{const le=await Q.runtimeEventsPage(l,{sessionId:D,afterSequence:J,limit:100});for(const ue of le.events){const je=ue.event;w.set(D,Math.max(w.get(D)??0,ue.sequence)),j(je)}}))}catch{}finally{y=!1,R()}}}function H(){h!==null&&(window.clearTimeout(h),h=null),$()}document.addEventListener("visibilitychange",H);const B=q3(n,D=>{M(),C(),j(D)},()=>{M(),m=window.setTimeout(()=>{B.isOpen()||(r("Event stream disconnected"),s?.())},2e3)},()=>{M(),C(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{M(),h!==null&&window.clearTimeout(h),g!==null&&window.clearTimeout(g),h=null,g=null,d=[],document.removeEventListener("visibilitychange",H),B.close()}},[e,t,n,s,a,r,o])}function cJ(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const o=n.name==="session.started"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!o)continue;const r=Wl.safeParse(a[o]);r.success&&t.set(r.data.id,r.data)}return[...t.values()]}function Nf(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function dJ(e){return typeof e=="string"&&e.trim()?e.trim():null}function uJ(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=Nf(n.data),o=Nf(a?.createImproveRun);if(o?.state!=="ready_local"&&o?.state!=="released"||Nf(o.adapter)?.kind!=="local")continue;const s=dJ(o.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const mJ=332,BS=244,FS=560,pJ=560,VS=320,KS=2400,fJ=440;function Df(e){const t=typeof window>"u"?FS:Math.min(FS,Math.max(BS,window.innerWidth-420));return Math.min(t,Math.max(BS,Math.round(e)))}function Lf(e){const t=typeof window>"u"?KS:Math.min(KS,Math.max(VS,window.innerWidth-fJ));return Math.min(t,Math.max(VS,Math.round(e)))}function hJ(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const cs=new Map;function vb(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function QR(e,t){const n=vb(e,t);if(!n)return null;const a=cs.get(n);return a?.updatedAt?a.agents:null}function gJ(e,t,n){const a=vb(e,n);a&&cs.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function bb(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=vb(t,e.accountKey);if(!n)return Promise.resolve([]);const a=cs.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const o=e.fetchAgents(t).then(r=>(gJ(t,r,e.accountKey),r)).catch(r=>{const s=cs.get(n);throw s?.promise===o&&cs.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),r});return cs.set(n,{agents:a?.agents??[],promise:o,updatedAt:a?.updatedAt??0}),o}const vJ=6e4,bJ=6e4,yJ=6e4,yb=["pinned","projects","cloudProjects","chats","savedForLater"];function SJ(e,t,n,a=Date.now()){for(const o of IJ(t,n))XR(t[o],n[o])||(e[o]=a)}function xJ(e,t,n,a=Date.now()){const o={...t};for(const[r,s]of Object.entries(n)){if(a-s>vJ){delete n[r];continue}const l=CJ(e,r),m=e[r];!l||XR(m,t[r])||(o[r]=m)}return o}function kJ(e,t,n,a=Date.now()){for(const o of yb)t[o]!==n[o]&&(e[o]=a)}function wJ(e,t,n,a=Date.now()){const o={...t};for(const r of yb){const s=n[r];if(s!==void 0){if(a-s>bJ){delete n[r];continue}if(e[r]===t[r]){delete n[r];continue}o[r]=e[r]}}return _J(e,o)?e:o}function WS(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function GS(e,t,n=Date.now()){return t?n-t.changedAt>yJ?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function IJ(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function XR(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function _J(e,t){return yb.every(n=>e[n]===t[n])}function CJ(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const RJ=5e4,_i="\0openpond-unscoped-runtime-events",fo=[];class PJ{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=fo;summaryEventsSnapshot=fo;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=YS(t.perSessionLimit??cb,"perSessionLimit"),this.totalLimit=YS(t.totalLimit??RJ,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return ZS();const n=new Map;let a=0;for(const d of t){if(this.eventKeyById.has(d.id)){a+=1;continue}const h=d.sessionId||_i,g=n.get(h);g?g.push(d):n.set(h,[d]),this.eventKeyById.set(d.id,h)}if(n.size===0)return{...ZS(),duplicateEventCount:a};const o=new Set;let r=0,s=0,l=!1;for(const[d,h]of n){h.some(QS)&&(l=!0);const g=this.entries.get(d),y=g?.snapshot.events??fo,w=Math.max(0,Math.min(y.length,this.perSessionLimit-h.length)),_=h.length>this.perSessionLimit?h.slice(h.length-this.perSessionLimit):h,P=w===y.length?y:y.slice(y.length-w),M=P.length===0?_:[...P,..._],C=y.slice(0,y.length-P.length);C.some(QS)&&(l=!0);for(const j of C)this.eventKeyById.delete(j.id);for(const j of h.slice(0,h.length-_.length))this.eventKeyById.delete(j.id);const O={eventIds:new Set(M.map(j=>j.id)),lastTouched:++this.clock,retained:g?.retained??this.retainedKeys.has(d),snapshot:{events:M,latestSequence:Su(M),revision:(g?.snapshot.revision??0)+1}};this.entries.set(d,O),this.eventCount+=M.length-y.length,r+=_.length,s+=C.length+h.length-_.length,o.add(d)}const m=this.enforceTotalLimit(o);return s+=m,this.publish(o,l||m>0),TJ({acceptedEventCount:r,duplicateEventCount:a,evictedEventCount:s,changedKeys:o})}mergeBootstrap(t){const n=AJ(t),a=new Set([...this.entries.keys(),...n.keys()]),o=[];for(const r of a){const s=n.get(r)??fo,l=this.entries.get(r)?.snapshot.events??fo;o.push(...fW(s,l))}return this.replace(o)}replace(t){const n=new Set(this.eventKeyById.keys()),a=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=fo,this.summaryEventsSnapshot=fo;const o=this.append(t);for(const m of this.retainedKeys){const d=this.entries.get(m);d&&(d.retained=!0)}const r=this.eventKeyById;let s=0;for(const m of n)r.has(m)||(s+=1);const l=new Set([...a].filter(m=>!this.entries.has(m)));return l.size>0&&this.publish(l,!0),{...o,evictedEventCount:o.evictedEventCount+s,changedSessionIds:new Set([...o.changedSessionIds,...[...l].filter(m=>m!==_i)]),unscopedEventsChanged:o.unscopedEventsChanged||l.has(_i)}}clear(){if(this.entries.size===0)return;const t=new Set(this.entries.keys());this.entries.clear(),this.eventKeyById.clear(),this.eventCount=0,this.allEventsSnapshot=fo,this.summaryEventsSnapshot=fo,this.publish(t,!0)}retainSession(t,n=!0){n?this.retainedKeys.add(t):this.retainedKeys.delete(t);const a=this.entries.get(t);a&&(a.retained=n)}getSessionSnapshot=t=>t?this.entries.get(t)?.snapshot??JS:JS;getSessionEvents(t){return this.getSessionSnapshot(t).events}getAllEvents=()=>{if(this.allEventsSnapshot)return this.allEventsSnapshot;const t=[...this.entries.values()].flatMap(n=>n.snapshot.events);return t.sort(EJ),this.allEventsSnapshot=t,t};getSummaryEvents=()=>this.summaryEventsSnapshot?this.summaryEventsSnapshot:(this.summaryEventsSnapshot=this.getAllEvents(),this.summaryEventsSnapshot);getStats(){let t=0;for(const[n,a]of this.entries)n!==_i&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(_i)?1:0),perSessionLimit:this.perSessionLimit,totalLimit:this.totalLimit}}subscribeAll=t=>(this.allListeners.add(t),()=>this.allListeners.delete(t));subscribeSummary=t=>(this.summaryListeners.add(t),()=>this.summaryListeners.delete(t));subscribeSession(t,n){let a=this.listenersByKey.get(t);return a||(a=new Set,this.listenersByKey.set(t,a)),a.add(n),()=>{a?.delete(n),a?.size===0&&this.listenersByKey.delete(t)}}enforceTotalLimit(t){let n=0;for(;this.eventCount>this.totalLimit&&this.entries.size>0;){const a=this.oldestEvictionCandidate(!1)??this.oldestEvictionCandidate(!0);if(!a)break;const[o,r]=a,s=this.eventCount-this.totalLimit;if(!r.retained||r.snapshot.events.length<=s){n+=r.snapshot.events.length,this.removeEntry(o),t.add(o);continue}const l=r.snapshot.events.slice(0,s),m=r.snapshot.events.slice(s);for(const d of l)this.eventKeyById.delete(d.id);r.eventIds=new Set(m.map(d=>d.id)),r.snapshot={events:m,latestSequence:Su(m),revision:r.snapshot.revision+1},this.eventCount-=l.length,n+=l.length,t.add(o)}return n}oldestEvictionCandidate(t){let n=null;for(const a of this.entries)!t&&a[1].retained||(!n||a[1].lastTouched<n[1].lastTouched)&&(n=a);return n}removeEntry(t){const n=this.entries.get(t);if(n){for(const a of n.snapshot.events)this.eventKeyById.delete(a.id);this.eventCount-=n.snapshot.events.length,this.entries.delete(t)}}publish(t,n=!1){if(t.size!==0){this.allEventsSnapshot=null,n&&(this.summaryEventsSnapshot=null);for(const a of t)for(const o of this.listenersByKey.get(a)??[])o();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const JS=Object.freeze({events:fo,latestSequence:null,revision:0});function AJ(e){const t=new Map;for(const n of e){const a=n.sessionId||_i,o=t.get(a);o?o.push(n):t.set(a,[n])}return t}function TJ(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==_i)),unscopedEventsChanged:e.changedKeys.has(_i)}}function ZS(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function EJ(e,t){if(e.sequence!==void 0&&t.sequence!==void 0)return e.sequence-t.sequence;const n=Date.parse(e.timestamp)-Date.parse(t.timestamp);return Number.isFinite(n)&&n!==0?n:e.id.localeCompare(t.id)}function YS(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function QS(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const MJ=256,jJ=15e3,OJ=5e3,$J=3e4;class NJ{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){DJ(this.connection,t)||(this.connection=t,this.clear())}activateAccountScope(t){t!==this.accountScope&&(this.accountScope=t,this.clear())}get(t){const n=this.now(),a=this.entries.get(t);return a?this.expired(a,n)?(this.entries.delete(t),null):(a.lastAccessedAt=n,LJ(this.entries,t,a),a.state==="ready"?a.url:null):null}load(t,n){const a=this.get(t);if(a)return Promise.resolve(a);const o=this.now(),r=this.entries.get(t);if(r?.state==="loading"&&!this.expired(r,o))return r.promise;if(r?.state==="failed"&&!this.expired(r,o))return Promise.resolve(null);const s=this.generation,l=n().then(m=>this.generation!==s?null:(this.entries.set(t,{state:"ready",url:m.url,expiresAt:m.expiresAt,lastAccessedAt:this.now()}),this.prune(),m.url)).catch(()=>{if(this.generation!==s)return null;const m=this.now();return this.entries.set(t,{state:"failed",expiresAt:m+(this.options.failureTtlMs??OJ),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:l,expiresAt:o+(this.options.loadingTtlMs??$J),lastAccessedAt:o}),this.prune(),l}clear(){this.generation+=1,this.entries.clear()}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,o]of this.entries)this.expired(o,t)&&this.entries.delete(a);const n=this.options.maxEntries??MJ;for(;this.entries.size>n;){const a=this.entries.keys().next().value;if(!a)break;this.entries.delete(a)}}expired(t,n){const a=t.state==="ready"?this.options.expirySkewMs??jJ:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const XS=new NJ;function gte(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function DJ(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function LJ(e,t,n){e.delete(t),e.set(t,n)}const HJ={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function UJ(e){return{label:HJ[e],ready:e==="ready",stage:e}}const qJ=650,zJ=1200,BJ=6e4;function FJ(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:o,setOpenPondCommandAccessMode:r,setError:s,setSelectedAppId:l,setSelectedProjectId:m,setSelectedSessionId:d}=e,[h,g]=v.useState(null),[y,w]=v.useState(null),[_]=v.useState(()=>new PJ),P=v.useSyncExternalStore(_.subscribeSummary,_.getSummaryEvents,_.getSummaryEvents),M=v.useCallback(N=>{const q=_.getAllEvents(),X=typeof N=="function"?N(q):N;X!==q&&_.replace(X)},[_]),C=v.useCallback(N=>{_.append(N)},[_]),[$,O]=v.useState(null),[j,x]=v.useState([]),[R,E]=v.useState([]),[H,B]=v.useState([]),[D,J]=v.useState({}),[le,ue]=v.useState("connecting"),je=Hh(y?.account),ke=v.useRef({}),te=v.useRef({}),Me=v.useRef({}),ye=v.useRef([]),ne=v.useRef([]),be=v.useRef(null),ae=v.useRef(null),de=v.useRef(!1),xe=v.useRef(Date.now()),De=v.useRef(null),we=v.useRef(null);v.useEffect(()=>{XS.activateConnection(h),XS.activateAccountScope(je)},[h,je]);const ie=v.useCallback(N=>{de.current||ue(N)},[]),Se=v.useCallback(N=>{J(q=>{const X=typeof N=="function"?N(q):N;return SJ(ke.current,q,X),X})},[]),Ue=v.useCallback(N=>{x(q=>{const X=typeof N=="function"?N(q):N;return _S(te.current,q,X),ye.current=X,X})},[]),Je=v.useCallback(N=>{E(q=>{const X=typeof N=="function"?N(q):N;return _S(Me.current,q,X),ne.current=X,X})},[]),Ke=v.useCallback(()=>{if(de.current||De.current!==null)return;const N=()=>{De.current=null,!de.current&&(de.current=!0,ue("ready"))},q=Date.now()-xe.current,X=VJ(q);if(X===0){N();return}De.current=window.setTimeout(N,X)},[]);v.useEffect(()=>()=>{De.current!==null&&window.clearTimeout(De.current)},[]);const tt=v.useCallback(N=>{const q=be.current,X=!q||q===N.server.id;be.current=N.server.id,O(me=>me?.serverId===N.server.id?me:{afterSequence:N.eventWindow?.latestSequence??Su(N.events)??0,serverId:N.server.id}),w(N),X?_.mergeBootstrap(N.events):_.replace(N.events),x(me=>{const $e=X?IS(me,N.sessions,te.current):Uh(me,N.sessions,te.current);return ye.current=$e,$e}),E(me=>{const $e=X?IS(me,N.codexHistorySessions??[],Me.current):Uh(me,N.codexHistorySessions??[],Me.current);return ne.current=$e,$e}),B(N.approvals),J(me=>xJ(me,N.sidebarAppPreferences,ke.current)),l(me=>me&&N.apps.some($e=>$e.id===me)?me:null),m(me=>{if(!me)return null;const $e=wC(me);return $e?.kind==="local"&&N.localProjects.some(Le=>Le.id===$e.id)?St("local",$e.id):$e?.kind==="cloud"&&(N.cloudProjects??[]).some(Le=>Le.id===$e.id)?St("cloud",$e.id):N.localProjects.some(Le=>Le.id===me)?St("local",me):(N.cloudProjects??[]).some(Le=>Le.id===me)?St("cloud",me):null}),d(me=>{if(!me)return null;const $e=[...N.sessions,...N.codexHistorySessions??[]];if($e.some(nt=>nt.id===me&&!nt.archived))return me;if(!X)return null;const Le=ye.current.find(nt=>nt.id===me)??ne.current.find(nt=>nt.id===me)??null;return Le&&!Le.archived&&IR(Le,$e)?me:null})},[_,l,m,d]),ze=v.useCallback(N=>{w(q=>q&&{...q,preferences:N.preferences})},[]);v.useEffect(()=>{const N=Ca(y?.preferences);n(N.defaultChatProvider),t(N.defaultChatModel)},[y?.preferences.defaultChatProvider,y?.preferences.defaultChatModel,t,n]),v.useEffect(()=>{a(Ca(y?.preferences).codexPermissionMode)},[y?.preferences.codexPermissionMode,a]),v.useEffect(()=>{o(Ca(y?.preferences).codexReasoningEffort)},[y?.preferences.codexReasoningEffort,o]),v.useEffect(()=>{r(Ca(y?.preferences).openPondCommandAccessMode)},[y?.preferences.openPondCommandAccessMode,r]),v.useEffect(()=>{if(!h||!y){ae.current=null;return}if(y.account.state!=="signed_in"){ae.current=null,Ke();return}const N=Hh(y.account);if(!N){ae.current=null,Ke();return}Ke(),ie("team");const q=y.preferences.defaultTeamId?.trim()??"",X=KJ(N,q,y.accountMeta.asOf??"initial");if(ae.current===X)return;ae.current=X;let me=!1;const $e=Le=>bb({teamId:Le,accountKey:N,fetchAgents:async nt=>(await Q.listSandboxAgents(h,{teamId:nt})).agents}).catch(()=>{!me&&ae.current===X&&(ae.current=null)});return gS({accountKey:N,force:!0,fetchOrganizations:()=>ex(h)}).then(async Le=>{if(me)return;if(Le.length===0){Ke();return}if(!!q&&Le.some(lt=>lt.teamId===q)){await $e(q),Ke();return}const at=b8(Le)?.teamId;if(!at){Ke();return}if(q){s("The configured default team is unavailable for this account. Select an available team in account settings."),Ke();return}await $e(at),me||Ke()}).catch(Le=>{me||(ae.current=null,s(Le instanceof Error?Le.message:String(Le)),Ke())}),()=>{me=!0}},[tt,ze,y?.account,y?.accountMeta.asOf,y?.preferences.defaultTeamId,Ke,h,ie,s]),v.useEffect(()=>{if(!h||!je)return;let N=!1;const q=()=>{N||(N=!0,gS({accountKey:je,force:!0,fetchOrganizations:()=>ex(h)}).catch(()=>{}).finally(()=>{N=!1}))},X=()=>{document.visibilityState==="visible"&&q()},me=window.setInterval(q,BJ);return window.addEventListener("focus",q),document.addEventListener("visibilitychange",X),()=>{window.clearInterval(me),window.removeEventListener("focus",q),document.removeEventListener("visibilitychange",X)}},[h,je]),Dc(()=>{const N=qV();s(N||(q=>q?.startsWith("Preference changes have not been saved.")?null:q))}),v.useEffect(()=>{h&&B0(h).catch(N=>s(String(N)))},[h,je,s]);const Ge=v.useCallback(async()=>{ie("connecting"),O(null);const N=await c6();g(X=>hJ(X,N)?X:N),ie("account");const q=await Q.bootstrap(N);await B0(N),tt(q),Ke(),s(X=>X&&(VC(X)||X==="Event stream disconnected")?null:X)},[tt,Ke,ie,s]);v.useEffect(()=>{let N=!1,q=null;const X=async me=>{try{await Ge()}catch($e){if(N)return;s($e instanceof Error?$e.message:String($e));const Le=Math.min(5e3,750+me*750);q=window.setTimeout(()=>{X(me+1)},Le)}};return X(0),()=>{N=!0,q!==null&&window.clearTimeout(q)}},[Ge,s]);const qe=v.useCallback(()=>{Ge().catch(()=>{})},[Ge]);lJ({afterSequence:$?.afterSequence??null,appendEvents:C,connection:h,setApprovals:B,setSessions:Ue,setError:s,onDisconnected:qe}),v.useEffect(()=>{if(!h||!y){we.current=null;return}const N=uJ(P);!N||we.current===N||(we.current=N,Q.profileCurrent(h).then(q=>{w(X=>X&&{...X,profile:q})}).catch(q=>{we.current=null,s(q instanceof Error?q.message:String(q))}))},[y,h,P,s]);const L=v.useCallback(()=>{h&&Q.refreshOpenPondAccount(h).then(({account:N,accountMeta:q})=>{w(X=>X&&{...X,account:N,accountMeta:q})}).catch(N=>s(N instanceof Error?N.message:String(N)))},[h,s]);return{appPreferences:D,applyBootstrapPayload:tt,approvals:H,bootstrap:y,codexHistorySessions:R,connection:h,events:P,runtimeEventStore:_,refreshOpenPondAccount:L,sessions:j,startup:UJ(le),setAppPreferences:Se,setBootstrap:w,setCodexHistorySessions:Je,setEvents:M,setSessions:Ue}}async function ex(e){return(await Q.organizations(e)).organizations.map(fm).filter(n=>!!n).filter(n=>n.status==="active")}function VJ(e){return e>=zJ?0:Math.max(0,qJ-e)}function KJ(e,t,n){return`${e}::${t||"none"}::${n}`}function WJ({appDispatch:e,error:t,setErrorState:n}){const a=v.useRef(null),o=v.useRef(null),r=v.useRef(null),s=v.useRef(0),l=v.useCallback((d,h="info",g={})=>{const y=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:y,message:d,tone:h,...g}}),y},[e]),m=v.useCallback(d=>{const h=o.current,g=typeof d=="function"?d(h):d;if(Object.is(h,g))return;if(o.current=g,n(g),!g){r.current!==null&&(e({type:"clearToast",toastId:r.current}),r.current=null);return}r.current=l(GJ(g),"error");const y=a.current;y&&Q.recordClientDiagnostic(y,{message:g,surface:"app",context:{href:window.location.href}}).catch(w=>{console.warn("Unable to record client diagnostic.",w)})},[e,n,l]);return v.useEffect(()=>{o.current=t,!(t||r.current===null)&&(e({type:"clearToast",toastId:r.current}),r.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:l}}function GJ(e){return FC(e)}const JJ={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:En,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:ir,draftModel:Fl,draftExperience:"chat",codexPermissionMode:Ig,codexReasoningEffort:_g,openPondCommandAccessMode:ju,busy:!1,diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[],terminalOpen:!1,syncingWorkspaceAppId:null,settingsSection:"account",newProjectDialogOpen:!1,newProjectMode:"local",newProjectName:"",newProjectPath:"",newProjectBusy:!1,commitDialogOpen:!1,commitMessage:"",commitIncludeUnstaged:!0,commitNextStep:"commit",commitDraft:!0,branchDialogOpen:!1,branchDialogName:"",toast:null,error:null};function Sb(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function wu(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...o}=e;return o}return e[t]===n?e:{...e,[t]:n}}function ZJ(e){return wu(e.promptDrafts,Sb(e),e.prompt)}function yl(e,t,n={}){const a={...e,...t},o=Sb(a),r=ZJ(e),s=n.clearSelectedDraft?wu(r,o,""):n.preserveCurrentPrompt?wu(r,o,e.prompt):r;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[o]??""}}function YJ(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function QJ(e,t){switch(t.type){case"field":{const n=e[t.key],a=typeof t.value=="function"?t.value(n):t.value;if(Object.is(n,a))return e;if(t.key==="prompt"){const o=String(a);return{...e,prompt:o,promptDrafts:wu(e.promptDrafts,Sb(e),o)}}return YJ(t.key)?yl(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return yl(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return yl(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return yl(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return yl(e,{selectedSessionId:null,selectedAppId:t.appId,selectedProjectId:null,error:null,view:"chat"});case"openCommitDialog":return{...e,commitMessage:"",commitIncludeUnstaged:!0,commitNextStep:t.nextStep,commitDraft:!0,commitDialogOpen:!0,error:null,view:"chat"};case"openBranchDialog":return{...e,branchDialogName:t.branchName,branchDialogOpen:!0,error:null,view:"chat"};case"showToast":return{...e,toast:t.toast};case"clearToast":return e.toast?.id===t.toastId?{...e,toast:null}:e;default:return e}}function gt(e,t){return n=>e({type:"field",key:t,value:n})}function XJ(e){return{setQuery:gt(e,"query"),setSearchOpen:gt(e,"searchOpen"),setArchivedChatsOpen:gt(e,"archivedChatsOpen"),setSectionMenuOpen:gt(e,"sectionMenuOpen"),setProjectsExpanded:gt(e,"projectsExpanded"),setCloudProjectsExpanded:gt(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:gt(e,"chatRowsVisibleCount"),setSidebarOpen:gt(e,"sidebarOpen"),setView:gt(e,"view"),setSelectedAppId:gt(e,"selectedAppId"),setSelectedProjectId:gt(e,"selectedProjectId"),setSelectedSessionId:gt(e,"selectedSessionId"),setPrompt:gt(e,"prompt"),setDraftProvider:gt(e,"draftProvider"),setDraftModel:gt(e,"draftModel"),setDraftExperience:gt(e,"draftExperience"),setCodexPermissionMode:gt(e,"codexPermissionMode"),setCodexReasoningEffort:gt(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:gt(e,"openPondCommandAccessMode"),setBusy:gt(e,"busy"),setDiffPanelOpen:gt(e,"diffPanelOpen"),setDiffPanelExpanded:gt(e,"diffPanelExpanded"),setRightPanelMode:gt(e,"rightPanelMode"),setRightChatPanels:gt(e,"rightChatPanels"),setTerminalOpen:gt(e,"terminalOpen"),setSyncingWorkspaceAppId:gt(e,"syncingWorkspaceAppId"),setSettingsSection:gt(e,"settingsSection"),setNewProjectDialogOpen:gt(e,"newProjectDialogOpen"),setNewProjectMode:gt(e,"newProjectMode"),setNewProjectName:gt(e,"newProjectName"),setNewProjectPath:gt(e,"newProjectPath"),setNewProjectBusy:gt(e,"newProjectBusy"),setCommitDialogOpen:gt(e,"commitDialogOpen"),setCommitMessage:gt(e,"commitMessage"),setCommitIncludeUnstaged:gt(e,"commitIncludeUnstaged"),setCommitNextStep:gt(e,"commitNextStep"),setCommitDraft:gt(e,"commitDraft"),setBranchDialogOpen:gt(e,"branchDialogOpen"),setBranchDialogName:gt(e,"branchDialogName"),setToast:gt(e,"toast"),setError:gt(e,"error")}}function Sl(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function eZ(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,o=new Set,r=d=>{if(!Object.is(n,d)){n=d;for(const h of o)h()}},s=()=>{const d=Sl(t);n?a.set(d,n):a.delete(d)},l=(d,h={})=>{const g=n;s(),t={...t,...d};const y=Sl(t);if(h.clear&&a.delete(y),h.preserveCurrentDraft){g?a.set(y,g):a.delete(y),r(g);return}r(h.clear?"":a.get(y)??"")},m={getScopeKey:()=>Sl(t),getSnapshot:()=>n,subscribe(d){return o.add(d),()=>o.delete(d)},set:d=>m.setForScope(Sl(t),d),setForScope(d,h){const g=Sl(t),y=d===g?n:a.get(d)??"",w=typeof h=="function"?h(y):h;Object.is(y,w)||(w?a.set(d,w):a.delete(d),d===g&&r(w))},applyAppAction(d){if(d.type==="field"){if(d.key==="prompt"){m.set(d.value);return}if(d.key==="selectedAppId"||d.key==="selectedProjectId"||d.key==="selectedSessionId"){const h=t[d.key],g=typeof d.value=="function"?d.value(h):d.value;Object.is(h,g)||l({[d.key]:g})}return}if(d.type==="patch"){const h={};"selectedAppId"in d.patch&&(h.selectedAppId=d.patch.selectedAppId),"selectedProjectId"in d.patch&&(h.selectedProjectId=d.patch.selectedProjectId),"selectedSessionId"in d.patch&&(h.selectedSessionId=d.patch.selectedSessionId),Object.keys(h).length>0&&l(h),"prompt"in d.patch&&typeof d.patch.prompt=="string"&&m.set(d.patch.prompt);return}if(d.type==="selectApp"){l({selectedAppId:d.appId,selectedProjectId:null,selectedSessionId:null});return}if(d.type==="selectProject"){l({selectedAppId:null,selectedProjectId:d.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(d.type==="selectSession"){const h=d.projectId??null;l({selectedSessionId:d.sessionId,selectedAppId:h?null:d.appId??null,selectedProjectId:h});return}d.type==="beginNewChat"&&l({selectedSessionId:null,selectedAppId:d.appId,selectedProjectId:null})}};return m}function vte(e){return v.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function tZ(e){return{...e,draftExperience:mb()}}function nZ(){const[e,t]=v.useReducer(QJ,JJ,tZ),[n]=v.useState(()=>eZ()),a=v.useCallback(r=>{n.applyAppAction(r),t(r)},[n]),o=v.useMemo(()=>({...XJ(a),setPrompt:n.set}),[n,a]);return Dc(()=>o.setDraftExperience(mb())),{composerDraftStore:n,dispatch:a,setters:o,state:e}}function aZ(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function oZ(e){const{connection:t,events:n,showToast:a}=e,o=v.useRef(new Set),r=v.useCallback(async()=>{if(t)try{const l=await Q.installMacOSCommandLineTools(t);a(l.message,"info")}catch(l){a(l instanceof Error?l.message:String(l),"error")}},[t,a]),s=v.useCallback((l="OpenPond needs Git to create and sync local projects.")=>{a(l,"error",{actionLabel:"Install Tools",onAction:()=>{r()},persistent:!0})},[a,r]);v.useEffect(()=>{if(!t)return;let l=!1;return Q.gitAvailability(t).then(m=>{l||m.ok||m.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{l=!0}},[t,s]),v.useEffect(()=>{for(const l of n){if(o.current.has(l.id))continue;const m=l.error??l.output??null;l.name==="workspace_action_result"&&l.status==="failed"&&aZ(m)&&(o.current.add(l.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function iZ({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:o,setError:r}){const[s,l]=v.useState(()=>Ca().sidebarSectionsCollapsed),m=v.useRef(s),d=v.useRef({}),h=v.useRef(null),g=v.useRef(null),[y,w]=v.useState(mJ),[_,P]=v.useState(!1),[M,C]=v.useState(pJ),[$,O]=v.useState(!1),{pinned:j,projects:x,cloudProjects:R,chats:E,savedForLater:H}=s;v.useEffect(()=>{if(_)return;const ae=Df(Ca(t).sidebarWidth),de=GS(ae,h.current);h.current=de.localChange,w(de.value)},[t,_]),v.useEffect(()=>{if($)return;const ae=Lf(Ca(t).diffPanelWidth),de=GS(ae,g.current);g.current=de.localChange,C(de.value)},[$,t]),v.useEffect(()=>{const ae=Ca(t).sidebarSectionsCollapsed;l(de=>{const xe=wJ(de,ae,d.current);return m.current=xe,xe})},[t]);const B=v.useCallback(ae=>{o(de=>de&&{...de,preferences:ae.preferences})},[o]),D=v.useCallback(async ae=>{if(e&&Df(Ca(t).sidebarWidth)!==ae)try{B(await Q.savePreferences(e,{sidebarWidth:ae}))}catch(de){r(de instanceof Error?de.message:String(de))}},[e,t,r,B]),J=v.useCallback(async ae=>{if(e&&Lf(Ca(t).diffPanelWidth)!==ae)try{B(await Q.savePreferences(e,{diffPanelWidth:ae}))}catch(de){r(de instanceof Error?de.message:String(de))}},[e,t,r,B]),le=v.useCallback(async ae=>{if(!e)return;const de=Ca(t).sidebarSectionsCollapsed;if(!rZ(de,ae))try{B(await Q.savePreferences(e,{sidebarSectionsCollapsed:ae}))}catch(xe){r(xe instanceof Error?xe.message:String(xe))}},[e,t,r,B]),ue=v.useCallback(ae=>{const de=m.current;kJ(d.current,de,ae),m.current=ae,l(ae),le(ae)},[le]),je=v.useCallback(()=>{const ae=m.current;ue({...ae,pinned:!ae.pinned})},[ue]),ke=v.useCallback(()=>{const ae=m.current;ue({...ae,projects:!ae.projects})},[ue]),te=v.useCallback(()=>{const ae=m.current;ue({...ae,cloudProjects:!ae.cloudProjects})},[ue]),Me=v.useCallback(()=>{const ae=m.current;ue({...ae,chats:!ae.chats})},[ue]),ye=v.useCallback(()=>{const ae=m.current;ue({...ae,savedForLater:!ae.savedForLater})},[ue]),ne=v.useCallback(ae=>{if(!n)return;ae.preventDefault();const de=ae.clientX,xe=y;let De=xe;P(!0);function we(Se){De=Df(xe+Se.clientX-de),w(De)}function ie(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",ie);const Se=WS(xe,De);Se&&(h.current=Se),P(!1),D(De)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",ie,{once:!0})},[D,n,y]),be=v.useCallback(ae=>{if(a)return;ae.preventDefault();const de=ae.clientX,xe=M;let De=xe;O(!0);function we(Se){De=Lf(xe-(Se.clientX-de)),C(De)}function ie(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",ie);const Se=WS(xe,De);Se&&(g.current=Se),O(!1),J(De)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",ie,{once:!0})},[a,M,J]);return{pinnedCollapsed:j,projectsCollapsed:x,cloudProjectsCollapsed:R,chatsCollapsed:E,savedForLaterCollapsed:H,sidebarWidth:y,sidebarResizing:_,diffPanelWidth:M,diffPanelResizing:$,togglePinnedCollapsed:je,toggleProjectsCollapsed:ke,toggleCloudProjectsCollapsed:te,toggleChatsCollapsed:Me,toggleSavedForLaterCollapsed:ye,startSidebarResize:ne,startDiffPanelResize:be}}function rZ(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function sZ(e){const[t,n]=v.useState({id:0,kind:null}),[a,o]=v.useState(null),r=v.useCallback((d=null)=>{n(h=>({id:h.id+1,kind:d}))},[]),s=v.useCallback(d=>{o(d)},[]),l=null,m=v.useMemo(()=>{if(e)return lZ(a,r)},[e,a,r]);return{backAction:l,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function lZ(e,t){return e?[{label:e.rootLabel??"Models",onSelect:()=>t(null)},{label:e.kindLabel,onSelect:e.kindOnSelect??(()=>t(e.kind))},...e.workproductLabel?[{label:e.workproductLabel,onSelect:e.workproductOnSelect}]:[],...e.segments]:[{label:"Models"}]}const tx=new WeakMap,Jh=new WeakMap;function cZ(e){if(!e)return"disconnected";let t=tx.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},tx.set(e,t)),t.id}function bte(e,t){return Jh.set(e,t),e}function yte(e){if(!e)return["learning","disconnected"];let t=Jh.get(e);return t||(t=["learning",crypto.randomUUID()],Jh.set(e,t)),t}function dZ(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return T3.parse(await Q.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const o=await n(a);return o?E3.parse(o):null}}}function uZ(e,t,n,a){async function o(r,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const l=S4.parse(s),m=new URLSearchParams({profileId:t});for(const[d,h]of Object.entries(l))h!==void 0&&m.set(d,String(h));return Q.trainingRequest(e,`${r}?${m}`,{},"GET")}return{taskInventory:async(r={})=>k4.parse(await o("/tasks",r)),taskInventoryDetail:async r=>{const s=await o("/tasks/detail",r);return{item:m_.parse(s.item),task:xv.parse(s.task)}},tasksetDraftFiles:async r=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/files?${new URLSearchParams({profileId:t})}`,{},"GET")}catch(s){return a(s),null}},tasksetDraftFile:async(r,s)=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/file?${new URLSearchParams({profileId:t,path:s})}`,{},"GET")}catch(l){return a(l),null}},saveTasksetDraftFile:r=>n("save-taskset-draft-file",`/taskset-drafts/${encodeURIComponent(r.draftId)}/file`,{profileId:t,...r},"PATCH"),inspectTasksetDraftSource:(r,s)=>n("inspect-taskset-draft-source","/taskset-drafts/source",{profileId:t,modelId:r,expectedModelRevision:s}),createTasksetDraftFromSource:r=>n("create-taskset-draft","/taskset-drafts",{profileId:t,sourceRequest:r}),createTasksetDraft:(r="",s)=>n("create-taskset-draft","/taskset-drafts",{profileId:t,name:r,modelId:s??null}),importTasksetDraftPackage:r=>n("import-taskset-draft-package","/taskset-drafts/import",{packagePath:r,profileId:t}),saveTasksetDraft:r=>n("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(r.id)}`,r,"PUT"),tasksetDraftWorkspace:async r=>{if(!e)return null;try{return await Q.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/workspace`,{},"GET")}catch(s){return a(s),null}},publishTasksetDraft:(r,s)=>n("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(r)}/publish`,{modelId:s??null}),refreshTasksetDraftModel:(r,s)=>n("refresh-taskset-draft-model",`/taskset-drafts/${encodeURIComponent(r.id)}/model-revision`,{expectedDraftRevision:r.revision,expectedModelRevision:s}),deleteTasksetDraft:r=>n("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(r)}`,{},"DELETE")}}function eP(e,t){return UU({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function mZ(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await eP(t,n);return eI.parse(await Q.trainingRequest(e,"/models/check",a,"POST"))}function pZ(e,t){return{listModelStarters:async(n,a=!1)=>{if(!e)throw new Error("Connect to OpenPond to browse model starters.");return Q.trainingRequest(e,`/model-starters?limit=30${n?`&afterId=${encodeURIComponent(n)}`:""}${a?"&fresh=true":""}`,{},"GET")},previewModelStarter:async n=>{if(!e)throw new Error("Connect to OpenPond to preview a starter.");return Q.trainingRequest(e,"/model-starters/preview",{id:n.id,revision:n.revision,contentHash:n.contentHash})},checkModelStarter:async n=>{if(!e)throw new Error("Connect to OpenPond to check this starter.");return eI.parse(await Q.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const nx=1e4,ax=3e4;function fZ(e){const{connection:t,profileId:n}=e,a=_x(),o=cZ(t),r=v.useMemo(()=>["training",o,n],[o,n]),s=v.useCallback(async()=>F5.parse(await Q.trainingState(t,n)),[t,n]),l=mA({queryKey:r,queryFn:s,enabled:!!t}),m=l.data??null,d=!!t&&l.isPending,[h,g]=v.useState(null),[y,w]=v.useState(null),_=v.useRef(null);_.current=m?.activityRevision??null;const P=v.useCallback(async()=>{if(!t)return null;try{const x=await a.fetchQuery({queryKey:r,queryFn:s,staleTime:0});return w(null),x}catch(x){return w(Ho(x)),null}},[t,a,r,s]),M=v.useCallback(async()=>(await a.cancelQueries({queryKey:r,exact:!0}),await a.invalidateQueries({queryKey:r,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",o,n]}),P()),[a,r,o,n,P]),C=v.useCallback(async(x,R,E,H="POST",B={})=>{if(!t)return null;B.silent||g(x);try{const D=await Q.trainingRequest(t,R,E,H);return await M(),B.silent||w(null),D}catch(D){return B.silent||w(Ho(D)),null}finally{B.silent||g(null)}},[t,M]),$=m?[m.jobs.some(x=>["queued","starting","running","cancelling","reconciling"].includes(x.status)),m.creations.some(x=>["planning","materializing","validating"].includes(x.state)),m.minerRuns.some(x=>["queued","running","cancelling"].includes(x.status)),m.datasetImports.some(x=>["inspecting","materializing","validating","cancelling"].includes(x.status))].some(Boolean):!1;v.useEffect(()=>{if(!t)return;let x=!0,R=null;const E=$?nx:ax,H=async()=>{let B=E;try{const D=await Q.trainingActivity(t,n);B=D.active?nx:ax,(_.current===null||_.current!==D.revision)&&await P()}catch(D){w(Ho(D))}x&&(R=window.setTimeout(()=>{H()},B))};return R=window.setTimeout(()=>{H()},E),()=>{x=!1,R!==null&&window.clearTimeout(R)}},[t,$,n,P]);const O=v.useMemo(()=>({...pZ(t,C),saveComparisonSeries:x=>C("save-comparison-series","/comparison-series",{series:x}),saveContinualBenchIssueReview:x=>C("save-continual-support-issue-review","/continual-support/issue-reviews",{review:x},"PUT"),importContinualLearningDailyBatch:(x,R="json_upload")=>C("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:x,source:R}),saveContinualLearningDailyBatch:x=>C("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:x},"PUT"),generateContinualLearningResponses:x=>C("generate-continual-learning-responses","/continual-learning/responses",x),sealComparisonSeries:(x,R)=>C("seal-comparison-series",`/comparison-series/${encodeURIComponent(x)}/seal`,{expectedRevision:R}),archiveComparisonSeries:(x,R)=>C("archive-comparison-series",`/comparison-series/${encodeURIComponent(x)}/archive`,{expectedRevision:R}),queueComparisonRelease:x=>C("queue-comparison-release",`/comparison-series/${encodeURIComponent(x.seriesId)}/releases`,x),startComparisonEvaluation:x=>C("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/evaluations`,x),loadComparisonAttemptEvidence:x=>t?Q.trainingRequest(t,`/model-runs/${encodeURIComponent(x.runId)}/attempts/${encodeURIComponent(x.attemptId)}/evidence?kind=${x.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:x=>C("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/run`,x,"PATCH"),decideComparisonEntry:x=>C("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/decision`,x),recordComparisonPromotion:x=>C("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(x.entryId)}/promotion`,x),checkModelProject:(x,R=x.revision)=>mZ(t,x,R),...dZ(t,n,x=>C("begin-model-batch-review","/models/batch-review",{profileId:n,request:x})),saveModelProject:async(x,R=x.revision)=>C("save-model-project","/models",await eP(x,R),"PUT"),listHostedModelProjects:async(x={})=>{if(!t)return null;x.silent||g("list-hosted-model-projects");try{const R=await Q.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${x.refresh===!0}`,{},"GET");return x.silent||w(null),R}catch(R){return x.silent||w(Ho(R)),null}finally{x.silent||g(R=>R==="list-hosted-model-projects"?null:R)}},openHostedModelProject:(x,R,E,H={})=>C(`open-hosted-model-project:${x}`,`/hosted-model-projects/${encodeURIComponent(x)}/open`,{profileId:n,teamId:R,apiOrigin:E},"POST",H),pullHostedModelProject:x=>C(`pull-hosted-model-project:${x}`,`/hosted-model-projects/${encodeURIComponent(x)}/pull`,{profileId:n}),syncModelProject:x=>C("sync-model-project",`/models/${encodeURIComponent(x)}/sync`,{}),publishModelProjectTaskset:(x,R)=>C("publish-model-project-taskset",`/models/${encodeURIComponent(x)}/tasksets/${encodeURIComponent(R)}/publish`,{}),createScorer:(x,R,E)=>C("create-scorer","/scorers",{grader:x,tasksetId:R,modelProjectId:E??null}),prepareLearningBatch:x=>C("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:x}),...uZ(t,n,C,x=>w(Ho(x))),tasksetGraderDetails:async x=>{if(!t)return null;try{return await Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/graders`,{},"GET")}catch(R){return w(Ho(R)),null}},inspectHuggingFaceDataset:x=>C("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:x}),materializeDatasetImport:(x,R)=>C("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/materialize`,R),cancelDatasetImport:x=>C("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(x)}/cancel`,{}),datasetRows:(x,R={})=>{if(!t)return Promise.resolve(null);const E=new URLSearchParams;R.split&&E.set("split",R.split),R.cursor&&E.set("cursor",R.cursor),E.set("limit",String(R.limit??25));for(const H of R.columns??[])E.append("column",H);return Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/rows?${E}`,{},"GET")},addSource:(x,R)=>C("add-source","/sources",{profileId:n,sessionId:x,turnIds:R}),addSources:x=>C("add-sources","/sources/batch",{profileId:n,sessionIds:x}),estimateSources:x=>t?Q.trainingRequest(t,"/sources/estimate",{sessionIds:x}):Promise.resolve([]),searchChats:(x,R,E=0,H=20)=>t?Q.trainingRequest(t,"/sources/search",{query:x,candidates:R,offset:E,limit:H}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:x,offset:E,limit:H,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:x=>C("remove-source",`/sources/${encodeURIComponent(x)}`,{},"DELETE"),deleteTaskset:x=>C("delete-model",`/tasksets/${encodeURIComponent(x)}`,{},"DELETE"),runBenchmark:(x,R,E,H)=>C(`run-benchmark-${R}`,`/tasksets/${encodeURIComponent(x)}/benchmark-runs`,{phase:R,model:E,reasoningEffort:H,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(x,R,E)=>C("run-harness-refiner-benchmark",`/models/${encodeURIComponent(x)}/harness-refiner-benchmark`,{profileId:n,model:R,reasoningEffort:E,maximumSpendUsd:10}),acceptHarnessReview:(x,R,E=null,H=null)=>C("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:x,reviewRef:R,analysisModel:E,analysisReasoningEffort:H}),startCreation:(x,R={})=>C("create-taskset","/task-creations",{profileId:n,sourceIds:x,surface:R.surface??"training_page",mode:R.mode??"defaults",entryMode:R.entryMode??"manual",resourceIntent:R.resourceIntent??"workproduct",buildIntent:R.buildIntent??"demonstrations",buildSpecification:R.buildSpecification??null,objective:R.objective??null,methodHint:R.methodHint??null,preferredBaseModelId:R.preferredBaseModel?.modelId??null,preferredBaseModel:R.preferredBaseModel??null,candidateId:R.candidateId??null,analysisModel:R.analysisModel??null,analysisReasoningEffort:R.analysisReasoningEffort??null,createImproveRunId:R.createImproveRunId??null,targetIntent:R.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(x,R)=>C("create-model","/models/from-taskset",{profileId:n,tasksetId:x,preferredBaseModelId:R.modelId,preferredBaseModel:R}),scanBaseModels:async()=>{if(!t)return null;g("scan-base-models");try{const x=await P();return w(null),x}catch(x){return w(Ho(x)),null}finally{g(null)}},approveDisclosure:(x,R)=>C("approve-disclosure",`/task-creations/${encodeURIComponent(x)}/disclosure`,{approved:R}),retryCreation:x=>C("retry-creation",`/task-creations/${encodeURIComponent(x)}/retry`,{}),answerQuestions:(x,R)=>C("answer-questions",`/task-creations/${encodeURIComponent(x)}/questions`,{answers:R}),materialize:(x,R)=>C("materialize",`/task-creations/${encodeURIComponent(x)}/materialize`,{approved:R}),chatCreation:(x,R)=>C("task-creator-chat",`/task-creations/${encodeURIComponent(x)}/chat`,{message:R}),renameCreation:(x,R)=>C("rename-creation",`/task-creations/${encodeURIComponent(x)}/name`,{name:R},"PATCH"),cancelCreation:x=>C("cancel-creation",`/task-creations/${encodeURIComponent(x)}/cancel`,{}),runMiner:(x=[],R=[],E)=>C("run-miner","/miner/run",{profileId:n,sourceIds:x,sessionIds:R,config:E}),cancelMinerRun:x=>C("cancel-miner-run",`/miner/runs/${encodeURIComponent(x)}/cancel`,{}),configureMiner:x=>C("configure-miner","/miner/config",{profileId:n,config:x},"PUT"),patchCandidate:(x,R)=>C("candidate",`/candidates/${encodeURIComponent(x)}`,R,"PATCH"),createCandidate:(x,R,E,H)=>C("create-candidate",`/candidates/${encodeURIComponent(x)}/create`,{mode:R,analysisModel:E??null,analysisReasoningEffort:H??null}),auditGraders:x=>C("audit-graders","/audit-graders",{tasksetId:x}),executeTasksetAttempt:(x,R,E)=>C("execute-taskset-attempt",`/tasksets/${encodeURIComponent(x)}/attempts`,{taskId:R,model:E,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:x=>C("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(x.tasksetId)}/synthetic-preference-collection`,x),tasksetOperationalState:x=>t?Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:x=>C("calibrate-judges","/calibrate-judges",{tasksetId:x}),nextPreferenceComparison:(x,R)=>C("next-preference-comparison",`/tasksets/${encodeURIComponent(x)}/preference-comparisons/next`,{reviewerKey:R}),submitPreferenceComparison:x=>C("submit-preference-comparison",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/submit`,x),submitSyntheticFixturePreference:x=>C("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/fixture-submit`,{...x,id:crypto.randomUUID()}),listPreferenceDatasets:x=>t?Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:x=>C("materialize-preference-dataset",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-datasets`,{...x,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:x=>C("launch-reward-model-run",`/tasksets/${encodeURIComponent(x.tasksetId)}/reward-model-runs`,{...x,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:x=>C("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(x.tasksetId)}/learned-preference-reward-binding`,x),retryRewardModelQualification:x=>C("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(x.runId)}/retry-qualification`,x),cancelRewardModelRun:x=>C("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(x)}/cancel`,{}),markPreferenceComparisonUnreviewable:x=>C("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/unreviewable`,x),preferenceCalibrationStatus:(x,R,E)=>{if(!t)return Promise.resolve(null);const H=new URLSearchParams({reviewerKey:R});return E&&H.set("comparisonReleaseId",E),Q.trainingRequest(t,`/tasksets/${encodeURIComponent(x)}/preference-comparisons/calibration/status?${H}`,{},"GET")},startPreferenceCalibrationBatch:x=>C("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches`,{...x,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:x=>C("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(x.jobId)}/sync`,x),reviewPreferenceComparisonWithModel:x=>C("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/${encodeURIComponent(x.assignmentId)}/model-review`,{...x,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:x=>C("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...x,id:crypto.randomUUID()}),savePreferenceCalibration:x=>C("save-preference-calibration",`/tasksets/${encodeURIComponent(x.tasksetId)}/preference-comparisons/calibration/report`,{...x,id:crypto.randomUUID()}),preferenceArtifactUrl:async x=>{if(!t)return null;const R=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!R.ok)throw new Error(await R.text());return URL.createObjectURL(await R.blob())},readiness:x=>C("readiness","/readiness",{tasksetId:x}),previewExpertBootstrap:x=>C("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(x,R)=>C("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(x)}/expert-bootstrap/approve`,{previewHash:R}),createPlan:x=>C("create-plan","/plans",{...x,tasksetId:x.tasksetId}),buildBundle:x=>C("build-bundle","/bundles",{planId:x}),approveTraining:(x,R)=>C("approve-training","/approvals",{planId:x,bundleId:R}),launch:(x,R)=>C("launch","/launch",{planId:x,approvalId:R}),prepareTraining:x=>C("prepare-training","/prepare",x),prepareModelRun:(x,R)=>C("prepare-model-run",`/model-projects/${encodeURIComponent(x)}/training/prepare`,R),startModelRun:(x,R)=>C("start-model-run",`/model-projects/${encodeURIComponent(x)}/training/start`,R),startPreparedTraining:x=>C("start-prepared-training","/start/prepared",x),startTraining:x=>C("start-training","/start",x),cancelJob:x=>C("cancel-job",`/jobs/${encodeURIComponent(x)}/cancel`,{}),retryModelRunCollection:x=>C("retry-model-run-collection",`/model-runs/${encodeURIComponent(x)}/retry-collection`,{}),cancelModelRun:x=>C("cancel-model-run",`/model-runs/${encodeURIComponent(x)}/cancel`,{}),rejectModel:(x,R)=>C("reject-model",`/models/${encodeURIComponent(x)}/reject`,{reason:R}),bindModel:(x,R,E)=>C("bind-model",`/models/${encodeURIComponent(x)}/bind`,{profileId:n,role:R,roleTargetId:E,promotedBy:n}),rollbackModelBinding:x=>C("rollback-model-binding",`/bindings/${encodeURIComponent(x)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(x,R)=>C("update-model-configuration",`/models/${encodeURIComponent(x)}/configuration`,R,"PATCH",{silent:!0}),setModelPinned:(x,R)=>C("pin-model-version",`/models/${encodeURIComponent(x)}/pin`,{pinned:R},"PATCH"),downloadArtifact:async x=>{if(!t)return!1;g("download-artifact");try{const R=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(x)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!R.ok)throw new Error(await R.text());const E=R.headers.get("content-disposition")??"",H=/filename="([^"]+)"/.exec(E)?.[1]??"openpond-model-artifact",B=URL.createObjectURL(await R.blob()),D=document.createElement("a");return D.href=B,D.download=H,D.click(),URL.revokeObjectURL(B),!0}catch(R){return w(Ho(R)),!1}finally{g(null)}},downloadModelPackage:async x=>j(`/models/${encodeURIComponent(x)}/download`,`${x}.openpond-lora.tar`),downloadBundle:async x=>j(`/bundles/${encodeURIComponent(x)}/download`,"openpond-model-improvement-bundle.json")}),[t,C,n,P]);async function j(x,R){if(!t)return!1;g("download-bundle");try{const E=await fetch(`${t.serverUrl}/v1/training${x}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!E.ok)throw new Error(await E.text());const H=E.headers.get("content-disposition")??"",B=/filename="([^"]+)"/.exec(H)?.[1]??R,D=URL.createObjectURL(await E.blob()),J=document.createElement("a");return J.href=D,J.download=B,J.click(),URL.revokeObjectURL(D),!0}catch(E){return w(Ho(E)),!1}finally{g(null)}}return{connection:t,payload:m,loading:d,busyAction:h,error:y??l.error?.message??null,refresh:P,actions:O}}function Ho(e){return e instanceof Error?e.message:String(e)}function Ste({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===Ec?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?bZ(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:yZ(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function xte(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function Xr(e){return e?.tasks.length?e.tasks[aP(e,e.selectedTaskIndex)]??null:null}function tP(e,t){return{...e,selectedTaskIndex:aP(e,t)}}function hZ(e){return tP(e,e.selectedTaskIndex+1)}function gZ(e,t,n){if(!e||nP(e,n))return null;const a=Xr(e);return!a||t.trim()!==a.prompt.trim()?null:{...e.taskRuntime==="cross_system"?{crossSystemTaskId:a.generatedTaskId}:{trainingHarnessTaskId:a.generatedTaskId},trainingTasksetId:e.tasksetId,trainingTasksetName:e.tasksetName,source:"training_model_chat_handoff"}}function nP(e,t){return!e?.sourceProjectId||e.sourceProjectId===t?null:"This generated Taskset question is bound to its source Cross-System Operations project. Return to Models and choose Chat again to restore the correct project."}async function vZ({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function bZ(e,t){const n=new Set;return e.tasks.flatMap(a=>{const o=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,r=typeof o=="string"?o.trim():"",s=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!r||!s||n.has(r)?[]:(n.add(r),[{authoredTaskId:a.id,generatedTaskId:r,prompt:s,split:a.split}])})}function yZ(e){const t=new Set(e.sourceRefs.filter(BB).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function aP(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function SZ({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:o,connection:r,requestComposerFocus:s,selectedLocalProjectId:l,selectedSessionId:m,selectLocalProject:d,setDraftModel:h,setDraftProvider:g,setError:y,view:w}){const[_,P]=v.useState(null),M=v.useCallback(E=>{E.sourceProjectId?d(E.sourceProjectId):a(null)},[a,d]),C=v.useCallback(E=>{if(!_)return;const H={...tP(_,E),sessionId:_.sessionId?null:_.sessionId},B=Xr(H);P(H),B&&(_.sessionId&&M(H),o.set(B.prompt),s())},[M,o,_,s]),$=v.useCallback(()=>{const E=Xr(_);E&&o.getSnapshot().trim()===E.prompt.trim()&&o.set(""),P(null)},[o,_]),O=v.useCallback(E=>{const H=E.model;vZ({model:H,connection:r,loadBootstrap:Q.bootstrap,applyBootstrap:n}).then(()=>{const B={...E,selectedTaskIndex:0,sessionId:null};g(H.providerId),h(H.modelId),P(B.tasks.length?B:null),M(B);const D=Xr(B);D&&o.set(D.prompt)}).catch(y)},[n,M,o,r,h,g,y]),j=v.useCallback(E=>{const H=!!(_&&_.model.providerId===t&&_.model.modelId===e);return{active:H,error:H?nP(_,l):null,metadata:H?gZ(_,E,l):null}},[e,t,_,l]),x=v.useCallback(E=>{P(H=>H&&{...H,sessionId:E})},[]),R=v.useCallback(()=>{if(!_)return;const E={...hZ(_),sessionId:null},H=Xr(E);P(E),H&&(M(E),o.set(H.prompt),s())},[M,o,_,s]);return v.useEffect(()=>{const E=Xr(_);!E||w!=="chat"||m||o.set(H=>H.trim()?H:E.prompt)},[o,_,l,m,w]),v.useEffect(()=>{_&&m&&_.sessionId!==m&&P(null)},[_?.sessionId,m]),{advanceAfterTurn:R,begin:O,bindSession:x,dismiss:$,handoff:_,prepareTurn:j,selectTask:C}}const xl=[],Hf=500;function xZ(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:o,runtimeIndexes:r,runtimeEventStore:s,selectedSessionId:l,serverId:m,setCodexHistoryEvents:d,setCodexHistorySessions:h,setError:g}=e,[y,w]=v.useState({}),[_,P]=v.useState({}),M=v.useRef(new Set);v.useEffect(()=>{w({}),P({}),M.current.clear()},[m]);const C=v.useCallback(async()=>{if(!a||!l||M.current.has(l))return!1;const R=_[l];if(R?.hasMore===!1)return!1;if(qt(l)){const B=Math.max(R?.totalMatchingEvents??0,n.length,RR),D=Math.min(CS,Math.max(nG,B*2));M.current.add(l),P(J=>({...J,[l]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:J[l]?.totalMatchingEvents??n.length}}));try{const J=await PR(a,l,{force:!0,limit:D,tail:!1});return d(J.events),h(le=>hm(le,J.session)),P(le=>({...le,[l]:{cursorSequence:null,hasMore:J.events.length>=D&&D<CS,loading:!1,totalMatchingEvents:D}})),J.events.length>n.length}catch(J){return g(J instanceof Error?J.message:String(J)),P(le=>({...le,[l]:{cursorSequence:null,hasMore:le[l]?.hasMore??!0,loading:!1,totalMatchingEvents:le[l]?.totalMatchingEvents??n.length}})),!1}finally{M.current.delete(l)}}const E=zo(y[l]??xl,s.getSessionEvents(l)),H=R?.cursorSequence??kZ(E);if(!H)return!1;M.current.add(l),P(B=>({...B,[l]:{cursorSequence:B[l]?.cursorSequence??H,hasMore:B[l]?.hasMore??!0,loading:!0,totalMatchingEvents:B[l]?.totalMatchingEvents??null}}));try{const B=await Q.runtimeEventsPage(a,{sessionId:l,beforeSequence:H,limit:Hf}),D=B.events.map(J=>J.event);return w(J=>({...J,[l]:zo(D,J[l]??xl)})),P(J=>({...J,[l]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}})),D.length>0}catch(B){return g(B instanceof Error?B.message:String(B)),P(D=>({...D,[l]:{cursorSequence:D[l]?.cursorSequence??H,hasMore:D[l]?.hasMore??!0,loading:!1,totalMatchingEvents:D[l]?.totalMatchingEvents??null}})),!1}finally{M.current.delete(l)}},[_,n.length,a,y,s,l,d,h,g]),$=l?y[l]??xl:xl,O=v.useMemo(()=>s.getSessionEvents(l).length,[s,l]),j=v.useRef(null);v.useEffect(()=>{if(!a||!l||qt(l)||M.current.has(l)||$.length>0||O>0)return;const R=o;if(!R)return;const E=l,H=R+1;M.current.add(E),P(B=>({...B,[E]:{cursorSequence:B[E]?.cursorSequence??H,hasMore:B[E]?.hasMore??!0,loading:!0,totalMatchingEvents:B[E]?.totalMatchingEvents??null}})),Q.runtimeEventsPage(a,{sessionId:E,beforeSequence:H,limit:Hf}).then(B=>{const D=B.events.map(J=>J.event);w(J=>({...J,[E]:zo(D,J[E]??xl)})),P(J=>({...J,[E]:{cursorSequence:B.previousSequence,hasMore:B.hasMore,loading:!1,totalMatchingEvents:B.totalMatchingEvents}}))}).catch(B=>{g(B instanceof Error?B.message:String(B)),P(D=>({...D,[E]:{cursorSequence:D[E]?.cursorSequence??H,hasMore:D[E]?.hasMore??!0,loading:!1,totalMatchingEvents:D[E]?.totalMatchingEvents??null}}))}).finally(()=>{M.current.delete(E)})},[o,a,$.length,O,l,g]),v.useEffect(()=>{if(!a||!l||qt(l)||M.current.has(l)||!o)return;const R=zo($,s.getSessionEvents(l)),E=Su(R);if(!E||E>=o)return;const H=`${l}:${E}:${o}`;if(j.current===H)return;j.current=H;let B=!1;return Q.runtimeEventsPage(a,{sessionId:l,afterSequence:E,limit:Hf}).then(D=>{if(B)return;const J=D.events.map(le=>le.event);J.length!==0&&w(le=>pW(le,l,J))}).catch(D=>{B||(j.current=null,g(D instanceof Error?D.message:String(D)))}),()=>{B=!0}},[o,a,s,$,l,g]);const x=v.useMemo(()=>qt(l)?Lh(n,[]):!l||$.length===0?r:Lh(zo($,s.getSessionEvents(l)),t),[t,n,r,$,l]);return{chatHistoryLoadStates:_,loadMoreSelectedChatHistory:C,selectedPagedSessionEvents:$,selectedRuntimeIndexes:x}}function kZ(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function wZ(e,t){const n=v.useRef(null);return v.useMemo(()=>{const a=lR(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function ds(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Uf(e){return Array.isArray(e)?e.filter(t=>!!ds(t)):[]}function Gi(e){return typeof e=="string"&&e.trim()?e.trim():null}function ox(e){return Gi(e)??ds(e)}function IZ(e){if(!e)return[];const t=ds(e.sandboxActionRegistry),n=ds(e.sandboxManifest),a=new Map;for(const o of[...Uf(n?.actionCatalog),...Uf(t?.actions),...Uf(n?.actions)]){const r=Gi(o.id)??Gi(o.name);if(!r)continue;const s=a.get(r);a.set(r,{id:r,name:Gi(o.name)??s?.name??r,label:Gi(o.label)??s?.label??_Z(r),description:Gi(o.description)??s?.description??null,visibility:Gi(o.visibility)??s?.visibility??"default",inputSchema:ox(o.inputSchema)??s?.inputSchema??null,outputSchema:ox(o.outputSchema)??s?.outputSchema??null,implementation:ds(o.implementation)??s?.implementation??null,mcp:ds(o.mcp)??s?.mcp??null,invokesModel:typeof o.invokesModel=="boolean"?o.invokesModel:s?.invokesModel})}return Array.from(a.values()).filter(o=>o.visibility!=="internal"&&o.visibility!=="debug")}function _Z(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function oP(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:St("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?Oa(e.selectedProject,e.cloudProjects):null;return e.cloudProjects&&!n?null:{id:n?.id??t.projectId,teamId:n?.teamId??t.teamId,name:n?.name??t.projectName??e.selectedProject?.name??"Cloud Project",selectionKey:St("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const iP="openpond-agent",rP="openpond-profile-action";function bm(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Bo(e){return typeof e=="string"&&e.trim()?e.trim():null}function xb(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function CZ(e){const t=bm(e),n=Bo(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:Bo(t?.name)}}function RZ(e){const t=Bo(e);return t!=="readonly"&&t!=="attempt"&&t!=="feature"&&t!=="rollout"&&t!=="replay"&&t!=="template_build"&&t!=="scheduled_run"&&t!=="patch_only"&&t!=="hotfix"&&t!=="multi_feature_batch"?null:t}function PZ(e,t=null){return{id:`agent:${e.id}`,name:e.slug||e.name,label:e.name,description:e.description||(t?`Agent for ${t}`:"OpenPond Agent"),visibility:"default",inputSchema:null,outputSchema:null,implementation:{type:iP,agentId:e.id,agentName:e.name,teamId:e.teamId,projectId:e.projectId,projectName:t,selectedEntrypoint:e.selectedEntrypoint,workflowMode:e.defaultWorkflowMode},mcp:null,invokesModel:!0}}function AZ(e){const t=bm(e.implementation);if(t?.type!==iP)return null;const n=Bo(t.agentId),a=Bo(t.teamId),o=Bo(t.projectId),r=CZ(t.selectedEntrypoint),s=RZ(t.workflowMode);return!n||!a||!o||!r||!s?null:{agentId:n,agentName:Bo(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:o,projectName:Bo(t.projectName),selectedEntrypoint:r,workflowMode:s}}function TZ(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...bm(e.implementation)??{},type:rP,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function EZ(e){if(!e)return[];const t=new Map(e.agents.filter(n=>n.enabled).map(n=>[n.id,n.name]));return e.actionCatalog.filter(n=>!n.agentId||t.has(n.agentId)).map(n=>TZ(n,{agentName:n.agentId?t.get(n.agentId):null}))}function kte(e){return!!(e&&kb(e))}function wte(e){return!!(e&&kb(e)&&e.sourceActionId==="chat")}function kb(e){const t=bm(e.implementation);if(t?.type!==rP)return null;const n=Bo(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function MZ({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:o}){return{action:e.actionId,input:{prompt:a,message:a,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedActionId:e.actionId,selectedActionLabel:e.actionLabel,selectedBy:xb({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...o?{sessionId:o}:{}}}}function jZ({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:o}){return{teamId:o,triggerType:"manual",entrypoint:{scope:"action",name:e.id},input:{prompt:a,message:a,actionName:e.id,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedActionId:e.id,selectedActionLabel:e.label??e.name??e.id,selectedBy:xb({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function OZ({agent:e,attachments:t=[],displayPrompt:n,prompt:a}){return{teamId:e.teamId,triggerType:"manual",entrypoint:e.selectedEntrypoint,input:{prompt:a,message:a,source:"openpond_app",...t.length>0?{attachments:t}:{}},metadata:{source:"openpond_app",selectedAgentId:e.agentId,selectedAgentName:e.agentName,selectedActionId:`agent:${e.agentId}`,selectedActionLabel:e.agentName,selectedBy:xb({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const us=new Map;function wb(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function $Z(e,t){const n=wb(e,t);if(!n)return null;const a=us.get(n);return a?.updatedAt?a.projects:null}function NZ(e,t,n){const a=wb(e,n);a&&us.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function DZ(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=wb(t,e.accountKey);if(!n)return Promise.resolve([]);const a=us.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const o=e.fetchProjects(t).then(r=>(NZ(t,r,e.accountKey),r)).catch(r=>{const s=us.get(n);throw s?.promise===o&&us.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),r});return us.set(n,{projects:a?.projects??[],promise:o,updatedAt:a?.updatedAt??0}),o}function qf(e){const t=new Map;for(const n of e)n.archivedAt||n.status!=="active"||t.set(n.id,n);return[...t.values()].sort((n,a)=>n.name.localeCompare(a.name))}function LZ({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:o,localProjects:r,profile:s,selectedCloudProject:l,selectedProject:m,reportError:d}){const[h,g]=v.useState(null),[y,w]=v.useState([]),[_,P]=v.useState([]),M=v.useMemo(()=>{const E=new Set;a&&E.add(a);for(const H of t)E.add(H.teamId);for(const H of r){const B=t.find(D=>D.id===H.linkedSandboxProject?.projectId&&D.teamId===H.linkedSandboxProject?.teamId);B?.teamId&&E.add(B.teamId)}return[...E].sort()},[t,a,r]),C=M.join("\0"),$=v.useMemo(()=>oP({cloudProjects:t,selectedCloudProject:l,selectedProject:m}),[t,l,m]);v.useEffect(()=>{if(!n||M.length===0){P([]);return}let E=!1;const H=M.flatMap(B=>QR(B,o)??[]);return P(qf(H)),Promise.all(M.map(B=>bb({teamId:B,accountKey:o,fetchAgents:async D=>(await Q.listSandboxAgents(n,{teamId:D})).agents}))).then(B=>{E||P(qf(B.flat()))}).catch(()=>{E||P(qf(H))}),()=>{E=!0}},[o,n,C]),v.useEffect(()=>{if(!n||!$){g(null);return}const E=$Z($.teamId,o);E&&g(E.find(B=>B.id===$.id)??null);let H=!1;return DZ({teamId:$.teamId,accountKey:o,fetchProjects:async B=>(await Q.listSandboxProjects(n,{teamId:B})).projects}).then(B=>{H||g(B.find(D=>D.id===$.id)??null)}).catch(()=>{H||g(null)}),()=>{H=!0}},[o,n,$?.id,$?.teamId]),v.useEffect(()=>{if(!n||!m){w([]);return}let E=!1;return Q.localProjectActions(n,m.id).then(H=>{E||w(H.actions)}).catch(H=>{E||(w([]),d?.(`Could not load Project Actions for ${m.name}: ${H instanceof Error?H.message:String(H)}`))}),()=>{E=!0}},[n,d,m?.id,m?.name,m?.updatedAt]);const O=v.useMemo(()=>{const E=new Map;for(const H of IZ(h))E.set(H.id,H);for(const H of y)E.set(H.id,H);return[...E.values()]},[y,h]),j=v.useMemo(()=>EZ(s),[s]),x=v.useMemo(()=>[..._.map(E=>PZ(E,e.get(E.projectId)?.name??null)),...j,...O],[e,j,O,_]);return{openPondActionCatalog:v.useMemo(()=>[...j,...O],[j,O]),selectedActionCatalog:x,selectedProjectActionCatalog:O}}function HZ({selectedProjectId:e}){const[t,n]=v.useState(()=>new Set),a=v.useCallback(r=>{n(s=>{if(s.has(r))return s;const l=new Set(s);return l.add(r),l})},[]),o=v.useCallback(r=>{n(s=>{const l=new Set(s);return l.has(r)?l.delete(r):l.add(r),l})},[]);return v.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:o,setExpandedProjectIds:n}}function UZ(){const e=new Map;function t(o,r){const s=e.get(o);if(s)return s.consumers+=1,n(o,s,!0);const l=new AbortController,m={controller:l,consumers:1,settled:!1,promise:Promise.resolve().then(()=>r(l.signal)).finally(()=>{m.settled=!0,e.get(o)===m&&e.delete(o)})};return e.set(o,m),n(o,m,!1)}function n(o,r,s){let l=!1;return{key:o,promise:r.promise,shared:s,release:()=>{l||(l=!0,r.consumers=Math.max(0,r.consumers-1),r.consumers===0&&!r.settled&&r.controller.abort())}}}function a(){for(const o of e.values())o.consumers=0,o.settled||o.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function zf(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function qZ(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function Bf(e){return e instanceof Error&&e.name==="AbortError"}function zZ({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:o,setError:r}){const[s,l]=v.useState(null),[m,d]=v.useState({}),[h,g]=v.useState(null),[y,w]=v.useState(!1),[_,P]=v.useState(!1),M=v.useRef(new Set),C=v.useRef(new Set),$=v.useRef(UZ()),O=t?m[t]??(s?.appId===t?s:null):null,j=h?.appId===t?h:null,x=n==="chat"||n==="labs",R=v.useCallback(B=>{M.current.add(B.appId),l(B),d(D=>({...D,[B.appId]:B}))},[]),E=v.useCallback(async(B,D=!1)=>{if(!e||!B)return l(null),null;w(!0);const J=$.current.request(zf(e,B,D),le=>Q.workspaceStatus(e,B,D,{signal:le}));try{const le=await J.promise;return R(le),D&&le.error?r(`Workspace sync failed: ${le.error}`):D&&r(null),le}catch(le){return Bf(le)||(l(null),r(le instanceof Error?le.message:String(le))),null}finally{J.release(),w(!1)}},[e,R,r]),H=v.useCallback(async(B=t,D={})=>{if(!e||!B)return g(null),null;D.silent||P(!0);const J=$.current.request(qZ(e,B),le=>Q.workspaceDiff(e,B,{signal:le}));try{const le=await J.promise;return g(le),le}catch(le){return Bf(le)||(g(null),r(le instanceof Error?le.message:String(le))),null}finally{J.release(),D.silent||P(!1)}},[t,e,r]);return v.useEffect(()=>{if(!e||!t||!x){l(null),g(null),w(!1);return}let B=!1;const D=$.current.request(zf(e,t,!1),J=>Q.workspaceStatus(e,t,!1,{signal:J}));return w(!0),D.promise.then(J=>{B||(R(J),J.initialized||g(le=>le?.appId===J.appId?null:le))}).catch(J=>{Bf(J)||B||(l(null),r(J instanceof Error?J.message:String(J)))}).finally(()=>{D.release(),B||w(!1)}),()=>{B=!0,D.release()}},[t,e,R,r,x]),v.useEffect(()=>{if(!e||!t||!x){g(null);return}if(!O?.initialized){O&&!O.initialized&&g(B=>B?.appId===t?null:B);return}a&&H(t)},[t,e,H,a,x,O?.dirty,O?.initialized]),v.useEffect(()=>{if(!e||o.length===0)return;const B=o.filter(le=>!M.current.has(le)&&!C.current.has(le));if(B.length===0)return;B.forEach(le=>C.current.add(le));let D=!1;const J=B.map(le=>({appId:le,request:$.current.request(zf(e,le,!1),ue=>Q.workspaceStatus(e,le,!1,{signal:ue}))}));return Promise.all(J.map(({appId:le,request:ue})=>ue.promise.then(je=>({appId:le,state:je})).catch(()=>({appId:le,state:null})).finally(()=>{ue.release(),C.current.delete(le)}))).then(le=>{if(!D)for(const ue of le)ue.state&&R(ue.state)}),()=>{D=!0,J.forEach(({appId:le,request:ue})=>{ue.release(),C.current.delete(le)})}},[e,R,o]),v.useEffect(()=>()=>$.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:h,workspaceBusy:y,diffBusy:_,visibleWorkspaceState:O,visibleWorkspaceDiff:j,rememberWorkspaceState:R,refreshWorkspace:E,refreshWorkspaceDiff:H,setWorkspaceBusy:w}}const BZ=1,FZ=15e3,VZ=15e3,sP=5*6e4,KZ=5e3,WZ=1e4;function lP(e,t=(a,o)=>new WebSocket(a,o),n={}){const a=new GZ(e,t,n.reconnectDelayMs??JZ);return a.open(),{close:()=>a.close()}}class GZ{constructor(t,n,a){this.input=t,this.webSocketFactory=n,this.reconnectDelayMs=a}input;webSocketFactory;reconnectDelayMs;socket=null;closed=!1;generation=0;reconnectAttempt=0;reconnectTimer=null;connectionAckTimer=null;subscriptionAckTimer=null;keepAliveTimer=null;keepAliveTimeoutMs=sP;lastKeepAliveAt=Date.now();ready=!1;subscriptionChannels=new Map;acknowledgedSubscriptions=new Set;open(){this.connect()}close(){if(this.closed)return;this.closed=!0,this.clearTimers();const t=this.socket;if(this.socket=null,!!t){if(t.readyState===BZ)for(const n of this.subscriptionChannels.keys())t.send(JSON.stringify({type:"unsubscribe",id:n}));t.onclose=null,t.onerror=null,t.onmessage=null,t.onopen=null,t.close(1e3,"Client closed")}}connect(){if(this.closed)return;const t=++this.generation;this.subscriptionChannels.clear(),this.acknowledgedSubscriptions.clear(),this.ready=!1,this.clearConnectionTimers();let n;try{n=this.webSocketFactory(this.input.realtimeUrl,["aws-appsync-event-ws",`header-${ZZ(JSON.stringify({Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host}))}`])}catch(a){this.reportError(a),this.scheduleReconnect();return}this.socket=n,n.onopen=()=>{this.isCurrent(n,t)&&(n.send(JSON.stringify({type:"connection_init"})),this.connectionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime connection acknowledgement timed out."))},FZ))},n.onmessage=a=>{this.isCurrent(n,t)&&this.handleMessage(n,a)},n.onerror=()=>{this.isCurrent(n,t)&&this.failConnection(new Error("Team chat realtime socket failed."),!1)},n.onclose=a=>{this.isCurrent(n,t)&&(this.socket=null,this.clearConnectionTimers(),this.closed||((a.code===4401||a.code===4403)&&this.reportError(new Error("Team chat realtime authorization expired.")),this.scheduleReconnect()))}}handleMessage(t,n){if(typeof n.data!="string")return;let a;try{const r=JSON.parse(n.data);if(!r||typeof r!="object"||Array.isArray(r))return;a=r}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const o=typeof a.type=="string"?a.type:"";if(o==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=QZ(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(o==="ka"){this.lastKeepAliveAt=Date.now();return}if(o==="subscribe_success"){const r=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(r))return;this.acknowledgedSubscriptions.add(r),this.markReadyWhenSubscribed();return}if(o==="data"){if(this.lastKeepAliveAt=Date.now(),typeof a.event!="string")return;try{this.input.onEvent(JSON.parse(a.event))}catch{this.reportError(new Error("Team chat realtime returned an invalid event."))}return}if(o==="connection_error"||o==="subscribe_error"){const r=XZ(a);if(this.reportError(r),o==="connection_error")this.failConnection(r,!1);else{const s=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(s),this.acknowledgedSubscriptions.delete(s),this.markReadyWhenSubscribed()}}}subscribe(t){const n={Authorization:this.input.authorizationToken,host:new URL(this.input.httpUrl).host};for(const a of Array.from(new Set(this.input.channels))){const o=YZ();this.subscriptionChannels.set(o,a),t.send(JSON.stringify({type:"subscribe",id:o,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},VZ)}startKeepAliveMonitor(){this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.keepAliveTimer=setInterval(()=>{Date.now()-this.lastKeepAliveAt<=this.keepAliveTimeoutMs||this.failConnection(new Error("Team chat realtime connection became stale."))},KZ)}markReadyWhenSubscribed(){this.ready||this.subscriptionChannels.size===0||this.acknowledgedSubscriptions.size!==this.subscriptionChannels.size||(this.ready=!0,this.subscriptionAckTimer&&clearTimeout(this.subscriptionAckTimer),this.subscriptionAckTimer=null,this.reconnectAttempt=0,this.input.onReady?.())}failConnection(t,n=!0){if(this.closed)return;n&&this.reportError(t);const a=this.socket;if(this.clearConnectionTimers(),!a){this.scheduleReconnect();return}a.close(4e3,"Reconnect")}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;const t=Math.max(0,Math.floor(this.reconnectDelayMs(this.reconnectAttempt)));this.reconnectAttempt+=1,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},t)}reportError(t){this.input.onError?.(t)}isCurrent(t,n){return!this.closed&&this.socket===t&&this.generation===n}clearConnectionTimers(){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.subscriptionAckTimer&&clearTimeout(this.subscriptionAckTimer),this.keepAliveTimer&&clearInterval(this.keepAliveTimer),this.connectionAckTimer=null,this.subscriptionAckTimer=null,this.keepAliveTimer=null}clearTimers(){this.clearConnectionTimers(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null}}function JZ(e){const t=Math.min(WZ,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function ZZ(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function YZ(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function QZ(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:sP}function XZ(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,o=typeof a.errorType=="string"?a.errorType:"RealtimeError",r=typeof a.message=="string"?a.message:"Request failed";return new Error(`${o}: ${r}`)}return new Error("Team chat realtime request failed.")}function eY(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(o=>`/team-chat/threads/${o}`)];return lP({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:o=>{const r=mw.safeParse(o);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function tY(e){return e.refs.find(t=>t.refType==="message_reply")??null}function nY(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function Ite(e,t){const n=tY(e);if(!n)return null;const a=t.get(n.refId);return a?nY(a):oY(n)}function aY(e){const t=e.body.slice(0,500);return{authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:t,truncated:t.length<e.body.length}}function _te(e,t){return e.authorUserId?t.get(e.authorUserId)?.name??"Team member":e.authorType==="agent"||e.authorAgentId?"Agent":e.authorType==="system"?"System":"Team member"}function Cte(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function oY(e){const t=e.preview;return{id:e.refId,authorType:iY(t.authorType),authorUserId:typeof t.authorUserId=="string"?t.authorUserId:null,authorAgentId:typeof t.authorAgentId=="string"?t.authorAgentId:null,body:typeof t.body=="string"?t.body:"",deleted:t.deleted===!0}}function iY(e){return e==="agent"||e==="system"?e:"user"}function ix(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function rY(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:Uc([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function Ff(e,t){const n=Array.from(t.values()).filter(o=>o.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const o of n)a=Es(a,o,"message.created",!0,o.authorUserId);return{...e,thread:a,messages:Uc([...e.messages,...n])}}function sY(e,t){const n=new Set(e.map(o=>o.lastMessage?.clientRequestId).filter(o=>!!o)),a=new Map;for(const o of t.values()){if(o.clientRequestId&&n.has(o.clientRequestId))continue;const r=a.get(o.threadId)??[];r.push(o),a.set(o.threadId,r)}return e.map(o=>{let r=o;for(const s of a.get(o.id)??[])r=Es(r,s,"message.created",!0,s.authorUserId);return r}).sort((o,r)=>r.lastMessageAt.localeCompare(o.lastMessageAt))}function Vf(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Kf(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function rx(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function Uc(e){const t=new Map,n=new Set(e.filter(a=>!a.id.startsWith("pending:")).map(a=>a.clientRequestId).filter(a=>!!a));for(const a of e)a.id.startsWith("pending:")&&a.clientRequestId&&n.has(a.clientRequestId)||t.set(a.id,a);return Array.from(t.values()).sort((a,o)=>a.sequence!==o.sequence?a.sequence-o.sequence:a.createdAt.localeCompare(o.createdAt))}function cP(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:Gg.safeParse(e.payload.message).data??null}function dP(e,t,n){const a=cP(t);if(a){const o=e.selectedThreadId===a.threadId,r=e.detail?.thread.id===a.threadId?{...e.detail,thread:Es(e.detail.thread,a,t.type,o,n),messages:Uc([...e.detail.messages,a])}:e.detail,l=e.threads.some(m=>m.id===a.threadId)?e.threads.map(m=>m.id===a.threadId?Es(m,a,t.type,o,n):m).sort((m,d)=>d.lastMessageAt.localeCompare(m.lastMessageAt)):e.threads;return{...e,detail:r,threads:l,error:null}}if(t.type==="read.updated"){const o=typeof t.payload.userId=="string"?t.payload.userId:null,r=Number(t.payload.sequence);if(!o||!Number.isSafeInteger(r)||r<0)return e;const s=l=>({...l,participants:l.participants.map(m=>m.userId===o?{...m,lastReadSequence:Math.max(m.lastReadSequence,r)}:m)});return{...e,threads:e.threads.map(l=>l.id===t.threadId?s(l):l),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function Es(e,t,n,a,o){const r=n==="message.created",s=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:s?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:s?t.createdAt:e.lastMessageAt,updatedAt:s?t.createdAt:e.updatedAt,lastMessage:s?t:e.lastMessage,unreadCount:a||t.authorUserId===o?0:r?e.unreadCount+1:e.unreadCount}}function lY(e){const t=new Date().toISOString(),n=`pending:${e.clientRequestId}`;return{id:n,threadId:e.threadId,teamId:e.teamId,clientRequestId:e.clientRequestId,authorType:"user",authorUserId:e.userId,authorAgentId:null,sequence:e.sequence,kind:"text",body:e.body,metadata:{deliveryStatus:"sending",mentionUserIds:e.mentionUserIds,localAttachmentPreviews:e.attachments.map(a=>({id:a.id,url:`data:${a.mediaType};base64,${a.contentsBase64}`}))},editedAt:null,deletedAt:null,createdAt:t,refs:e.replyToMessage?[{id:`pending-reply:${e.clientRequestId}`,messageId:n,refType:"message_reply",refId:e.replyToMessage.id,preview:aY(e.replyToMessage),createdAt:t}]:[],attachments:e.attachments.map(a=>({id:a.id,messageId:null,clientAttachmentId:a.id,kind:"image",name:a.name,mediaType:a.mediaType,sizeBytes:a.sizeBytes,status:"pending",createdAt:t,readyAt:null}))}}function cY(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:Es(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:Uc([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?Es(a,t,"message.created",!0,t.authorUserId):a).sort((a,o)=>o.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function sx(e,t,n){return dP(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function dY(e,t){return Zh(e,t,"failed")}function Zh(e,t,n){const a=o=>o.clientRequestId===t&&o.id.startsWith("pending:")?{...o,metadata:{...o.metadata,deliveryStatus:n}}:o;return{...e,detail:e.detail?{...e.detail,thread:{...e.detail.thread,lastMessage:e.detail.thread.lastMessage?a(e.detail.thread.lastMessage):null},messages:e.detail.messages.map(a)}:null,threads:e.threads.map(o=>({...o,lastMessage:o.lastMessage?a(o.lastMessage):null}))}}function lx(e,t,n){const a=o=>o.clientRequestId===t&&o.id.startsWith("pending:")?{...o,metadata:{...o.metadata,uploadProgress:n}}:o;return{...e,detail:e.detail?{...e.detail,thread:{...e.detail.thread,lastMessage:e.detail.thread.lastMessage?a(e.detail.thread.lastMessage):null},messages:e.detail.messages.map(a)}:null,threads:e.threads.map(o=>({...o,lastMessage:o.lastMessage?a(o.lastMessage):null}))}}function uY(e,t){const n=e.detail?.messages.filter(r=>r.id!==t)??[],a=n.at(-1)??null,o=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?cx(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:o,threads:e.threads.map(r=>r.lastMessageId===t?cx(r,a):r)}}function mY(e){if(e.length>Xi.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!pY(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Xi.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function cx(e,t){return{...e,lastMessageId:t?.id??null,lastMessageSequence:t?.sequence??0,lastMessageAt:t?.createdAt??e.createdAt,updatedAt:t?.createdAt??e.createdAt,lastMessage:t}}function pY(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const fY={team_chat_team_not_found:"You no longer have access to this workspace.",workspace_membership_required:"You no longer have access to this workspace.",team_chat_billing_inactive:"Workspace chat is unavailable while its subscription is inactive. Ask the workspace owner to review billing.",workspace_billing_suspended:"Workspace billing is suspended. Ask the workspace owner to update billing.",workspace_billing_cancelled:"This workspace subscription is cancelled. Ask the workspace owner to reactivate it.",workspace_checkout_pending:"Workspace checkout is still pending. Ask the workspace owner to finish setup.",member_paid_usage_disabled:"The workspace owner has not enabled paid model usage for your account.",member_spend_cap_exceeded:"You reached your workspace member spending limit. Ask the workspace owner to adjust it.",member_opchat_quota_exceeded:"You reached your workspace member OpChat limit. Ask the workspace owner to adjust it.",member_search_quota_exceeded:"You reached your workspace member Search limit. Ask the workspace owner to adjust it.",workspace_prepaid_credit_required:"This workspace needs more prepaid credits. Ask the workspace owner to add credits.",workspace_spend_cap_exceeded:"This workspace reached its spend cap. Ask the workspace owner to review billing.",opchat_workspace_quota_exceeded:"This workspace reached its included OpChat limit for the period.",search_workspace_quota_exceeded:"This workspace reached its included Search limit for the period."};function hY(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,o]of Object.entries(fY))if(n.includes(a))return o;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":FR(t)}const uP="openpond.team-chat.notification-mode";function mP(){try{return typeof window>"u"?null:Lc}catch{return null}}function dx(e=mP()){const t=e?.getItem(uP);return t==="direct_mentions"||t==="none"?t:"all"}function gY(e,t=mP()){try{t?.setItem(uP,e)}catch{}}function vY(e){return e.mode==="none"||!e.currentUserId||!e.thread||e.thread.mutedAt||e.message.deletedAt||e.message.authorUserId===e.currentUserId?!1:e.mode==="all"||e.thread.kind==="dm"?!0:(Array.isArray(e.message.metadata.mentionUserIds)?e.message.metadata.mentionUserIds:[]).includes(e.currentUserId)}function bY(e){const t=e.message.authorUserId?e.members.find(s=>s.userId===e.message.authorUserId)?.name??"Team member":e.message.authorType==="agent"?"Agent":"Team",n=e.thread.title?.trim()||(e.thread.kind==="general"?"general":"conversation"),a=e.thread.kind==="dm"?t:`${t} in #${n}`,r=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:r.length>160?`${r.slice(0,157)}…`:r}}const ux={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function wd(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function Id(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function yY(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function SY(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function mx(e,t=Q.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function xY(e){const[t,n]=v.useState(ux),a=v.useRef(t);a.current=t;const[o,r]=v.useState(dx);Dc(()=>r(dx()));const[s,l]=v.useState(null),m=v.useRef(null),d=v.useRef(null),h=v.useRef(0),g=v.useRef(new Map),y=v.useRef(new Map),w=v.useRef(0),_=v.useRef(null),P=v.useRef(0),M=v.useRef(new Set),C=v.useRef(0),$=v.useRef(!1),O=v.useRef(new Map),j=v.useRef(new Map),[x,R]=v.useState(null),[E,H]=v.useState(null),B=v.useCallback(L=>{r(L),gY(L)},[]),D=v.useCallback(L=>{l(N=>N?.eventId===L?null:N)},[]),J=v.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const L=await Q.teamChatThreads(e.connection,e.teamId),N=sY(L.threads,O.current);return n(q=>({...q,threads:N})),N},[e.connection,e.teamId]),le=v.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[L,N]=await Promise.all([Q.teamChatMembers(e.connection,e.teamId),Q.teamChatAgents(e.connection,e.teamId)]);return n(q=>({...q,members:L.members,agents:N.agents})),{members:L.members,agents:N.agents}},[e.connection,e.teamId]),ue=v.useCallback(async L=>{const N=L??m.current;if(!e.connection||!e.teamId||!N)return null;const q=(y.current.get(N)??0)+1;y.current.set(N,q);const X=await Q.teamChatThread(e.connection,e.teamId,N);Vf(X.messages,O.current,j.current);const me=Ff(X,O.current);return y.current.get(N)!==q||(n($e=>$e.selectedThreadId===N?{...$e,threads:wd($e.threads,N),detail:Id(rY($e.detail,me))}:$e),m.current===N&&me.thread.lastMessageSequence>0&&await Q.markTeamChatRead(e.connection,N,e.teamId,me.thread.lastMessageSequence).catch(()=>{})),me},[e.connection,e.teamId]),je=v.useCallback(async L=>{const N=L??d.current;if(!e.connection||!e.teamId||!N)return null;const q=(g.current.get(N)??0)+1;g.current.set(N,q);const X=await Q.teamChatAiThread(e.connection,e.teamId,N);return g.current.get(N)===q&&d.current===N&&n(me=>ix(me,X,d.current)),X},[e.connection,e.teamId]),ke=v.useCallback(async L=>{const N=L??_.current;if(!e.connection||!e.teamId||!N)return null;const q=await Q.teamChatAgentConversation(e.connection,e.teamId,N);return n(X=>X.agentConversation?.run.id===N?{...X,agentConversation:q}:X),q},[e.connection,e.teamId]);v.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),v.useEffect(()=>{_.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),v.useEffect(()=>{const L=t.agentConversation?.run.status;if(!L||!["pending","queued","running"].includes(L))return;const N=window.setInterval(()=>{ke().catch(q=>{n(X=>({...X,error:vn(q)}))})},2500);return()=>window.clearInterval(N)},[ke,t.agentConversation?.run.status]),v.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(ux),R(null),H(null),j.current.clear(),O.current.clear(),y.current.clear(),g.current.clear(),w.current+=1,l(null),M.current.clear(),C.current=0,P.current=0;return}let L=!1;return d.current=null,h.current+=1,w.current+=1,R(null),H(null),j.current.clear(),O.current.clear(),M.current.clear(),C.current=0,n(N=>({...N,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const N=await Q.teamChatEvents(e.connection,e.teamId);if(L)return;P.current=N.cursor;const q=Q.teamChatMembers(e.connection,e.teamId),X=Q.teamChatAgents(e.connection,e.teamId),me=await Q.teamChatGeneral(e.connection,e.teamId),[$e,Le,nt]=await Promise.all([q,X,Q.teamChatThreads(e.connection,e.teamId)]);if(L)return;const at=m.current&&nt.threads.some(Oe=>Oe.id===m.current)?m.current:me.thread.id,lt=at===me.thread.id?me:await Q.teamChatThread(e.connection,e.teamId,at);if(L)return;const pt=Id(lt);n(Oe=>({...Oe,members:$e.members,agents:Le.agents,threads:wd(nt.threads,at),selectedThreadId:at,detail:pt,loading:!1,error:null})),mx({connection:e.connection,teamId:e.teamId,threadId:at,lastMessageSequence:pt?.thread.lastMessageSequence??0}),H(e.teamId)}catch(N){if(L)return;n(q=>({...q,loading:!1,error:vn(N)}))}})(),()=>{L=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const te=v.useCallback(L=>{if(M.current.has(L.id))return;if(M.current.add(L.id),M.current.size>2e3){const q=M.current.values().next().value;typeof q=="number"&&M.current.delete(q)}const N=cP(L);if(N&&L.type==="message.created"){const q=a.current,X=q.threads.find($e=>$e.id===N.threadId)??(q.detail?.thread.id===N.threadId?q.detail.thread:null),me=$e=>{L.id<=C.current||vY({mode:o,currentUserId:e.currentUserId,message:N,thread:$e})&&(C.current=L.id,l(bY({eventId:L.id,message:N,thread:$e,members:q.members})))};X?me(X):J().then($e=>{const Le=$e.find(nt=>nt.id===N.threadId);Le&&me(Le)}).catch(()=>{})}N?.clientRequestId&&!N.id.startsWith("pending:")&&(O.current.delete(N.clientRequestId),j.current.delete(N.clientRequestId)),n(q=>dP(q,L,e.currentUserId)),L.type==="thread.created"&&J().catch(q=>{n(X=>({...X,error:vn(q)}))}),(L.type==="ai_thread.created"||L.type==="ai_turn.updated")&&(ue(L.threadId).catch(q=>{n(X=>({...X,error:vn(q)}))}),L.conversationId===d.current&&je(L.conversationId).catch(q=>{n(X=>({...X,error:vn(q)}))})),N&&L.type==="message.created"&&m.current===N.threadId&&N.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&Q.markTeamChatRead(e.connection,N.threadId,e.teamId,N.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,o,je,ue,J]),Me=v.useCallback(async()=>{if(!(!e.connection||!e.teamId||$.current)){$.current=!0;try{let L=!0;for(;L;){const N=await Q.teamChatEvents(e.connection,e.teamId,{after:P.current,limit:250});for(const q of N.events)te(q);P.current=N.cursor,L=N.hasMore}}finally{$.current=!1}}},[te,e.connection,e.teamId]);v.useEffect(()=>{if(!e.connection||!e.teamId||E!==e.teamId)return;let L=!1,N=null;const q=async()=>{try{const X=await Q.teamChatRealtimeSession(e.connection,e.teamId);if(L||(await Me(),L))return;R(X);const me=Math.max(3e4,new Date(X.expiresAt).getTime()-Date.now()-3e4);N=window.setTimeout(()=>{q()},me)}catch{L||(Me().catch(()=>{}),N=window.setTimeout(()=>{q()},1e4))}};return q(),()=>{L=!0,N!==null&&window.clearTimeout(N),R(null)}},[Me,e.connection,e.teamId,E]);const ye=t.threads.map(L=>L.id).sort().join(",");v.useEffect(()=>{if(!x)return;const L=eY({session:x,threadIds:ye?ye.split(","):[],onEvent:te,onReady:()=>{Me().catch(N=>{n(q=>({...q,error:vn(N)}))})},onError:()=>{Me().catch(()=>{})}});return()=>{L.close()}},[te,Me,x,ye]),v.useEffect(()=>{if(!e.connection||!e.teamId||E!==e.teamId)return;const L=window.setInterval(()=>{Me().catch(()=>{})},15e3);return()=>window.clearInterval(L)},[Me,e.connection,e.teamId,E]);const ne=v.useCallback(async L=>{if(!e.connection||!e.teamId)return;const N=w.current+1;w.current=N;const q=m.current!==L;m.current=L,q&&(h.current+=1,d.current=null),n(X=>({...X,threads:wd(X.threads,L),selectedThreadId:L,detail:X.detail?.thread.id===L?Id(X.detail):null,aiThread:q?null:X.aiThread,agentConversation:q?null:X.agentConversation,loading:!0,error:null}));try{const X=await Q.teamChatThread(e.connection,e.teamId,L);if(w.current!==N||m.current!==L)return;Vf(X.messages,O.current,j.current);const me=Ff(X,O.current);n($e=>({...$e,threads:wd($e.threads,L),detail:Id(me),loading:!1})),await Q.markTeamChatRead(e.connection,L,e.teamId,me.thread.lastMessageSequence).catch(()=>{})}catch(X){if(w.current!==N)return;n(me=>({...me,loading:!1,error:vn(X)}))}},[e.connection,e.teamId]),be=v.useCallback(async L=>{if(!e.connection||!e.teamId)return null;const N=w.current+1;w.current=N,n(q=>({...q,busy:!0,error:null}));try{const q=await Q.teamChatDm(e.connection,e.teamId,L);if(w.current!==N)return null;Vf(q.messages,O.current,j.current);const X=Ff(q,O.current),me=m.current!==X.thread.id;return m.current=X.thread.id,me&&(h.current+=1,d.current=null),n($e=>({...$e,selectedThreadId:X.thread.id,detail:X,aiThread:me?null:$e.aiThread,agentConversation:me?null:$e.agentConversation,busy:!1})),await mx({connection:e.connection,teamId:e.teamId,threadId:X.thread.id,lastMessageSequence:X.thread.lastMessageSequence}),await J(),X}catch(q){return w.current!==N||n(X=>({...X,busy:!1,error:vn(q)})),null}},[e.connection,e.teamId,J]),ae=v.useCallback(async()=>{const L=t.detail,N=L?.messages[0]?.sequence;if(!e.connection||!e.teamId||!L||!L.hasMoreBefore||N==null)return!1;n(q=>({...q,loading:!0,error:null}));try{const q=await Q.teamChatThread(e.connection,e.teamId,L.thread.id,{beforeSequence:N,limit:50});return n(X=>{if(X.detail?.thread.id!==L.thread.id)return X;const me=[...q.messages,...X.detail.messages];return{...X,loading:!1,detail:{...X.detail,messages:Uc(me),hasMoreBefore:q.hasMoreBefore}}}),!0}catch(q){return n(X=>({...X,loading:!1,error:vn(q)})),!1}},[e.connection,e.teamId,t.detail]),de=v.useCallback(async L=>{const N=m.current,q=mY(L.attachments??[]);if(!q)return n($e=>({...$e,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!N||!L.body.trim()&&q.length===0)return!1;if(L.replyToMessage&&(L.replyToMessage.threadId!==N||L.replyToMessage.teamId!==e.teamId||L.replyToMessage.id.startsWith("pending:")||L.replyToMessage.deletedAt))return n($e=>({...$e,error:"That message is no longer available to reply to."})),!1;if(L.useModel){if(q.length>0)return n(Le=>({...Le,error:"Images can be sent to the team thread with Use model turned off."})),!1;const $e=h.current;n(Le=>({...Le,busy:!0,error:null}));try{const Le=await Q.createTeamChatAiThread(e.connection,N,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId}),nt=h.current===$e&&m.current===N;return nt&&(h.current+=1,d.current=Le.conversationId),n(at=>({...at,aiThread:nt?Le:at.aiThread})),Le.activeTurn&&await Q.executeTeamChatAiTurn(e.connection,Le.activeTurn.id,e.teamId),await Promise.all([ue(N),J()]),n(at=>({...at,busy:!1})),!0}catch(Le){return n(nt=>({...nt,busy:!1,error:vn(Le)})),!1}}const X=crypto.randomUUID();if(L.selectedActionKey){if(q.length>0)return n($e=>({...$e,error:"Agent invocations do not support image attachments yet."})),!1;n($e=>({...$e,busy:!0,error:null}));try{return await Q.createTeamChatAgentRun(e.connection,N,SY({teamId:e.teamId,body:L.body,clientRequestId:X,selectedActionKey:L.selectedActionKey,approvalId:L.approvalId})),await Promise.all([ue(N),J()]),n($e=>({...$e,busy:!1})),!0}catch($e){return n(Le=>({...Le,busy:!1,error:vn($e)})),!1}}j.current.set(X,{inputs:q,uploaded:null});const me=lY({clientRequestId:X,threadId:N,teamId:e.teamId,userId:e.currentUserId,body:L.body.trim(),mentionUserIds:L.mentionUserIds??[],attachments:q,replyToMessage:L.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});O.current.set(X,me),n($e=>cY($e,me));try{const $e=[];for(const[at,lt]of q.entries())$e.push(await Q.uploadTeamChatAttachment(e.connection,N,{teamId:e.teamId,attachment:lt})),rx(O.current,X,`${at+1} of ${q.length}`),n(pt=>lx(pt,X,`${at+1} of ${q.length}`));const Le=j.current.get(X);Le&&(Le.uploaded=$e);const nt=await Q.sendTeamChatMessage(e.connection,N,{teamId:e.teamId,body:L.body.trim(),clientRequestId:X,mentionUserIds:L.mentionUserIds,attachmentIds:$e.map(at=>at.id),replyToMessageId:L.replyToMessage?.id??null});return j.current.delete(X),O.current.delete(X),n(at=>sx(at,nt,e.currentUserId)),!0}catch($e){return Kf(O.current,X,"failed"),n(Le=>({...dY(Le,X),error:vn($e)})),!1}},[e.connection,e.currentUserId,e.teamId,ue,J,t.detail?.thread.lastMessageSequence]),xe=v.useCallback(async L=>{if(!(!e.connection||!e.teamId)){h.current+=1,d.current=L,n(N=>({...N,aiThread:N.aiThread?.conversationId===L?N.aiThread:null,busy:!0,error:null}));try{const N=await Q.teamChatAiThread(e.connection,e.teamId,L);if(d.current!==L)return;n(q=>({...q,aiThread:N,busy:!1}))}catch(N){if(d.current!==L)return;n(q=>({...q,busy:!1,error:vn(N)}))}}},[e.connection,e.teamId]),De=v.useCallback(async L=>{if(!(!e.connection||!e.teamId)){_.current=L,n(N=>({...N,busy:!0,error:null}));try{const N=await Q.teamChatAgentConversation(e.connection,e.teamId,L);n(q=>({...q,agentConversation:N,busy:!1}))}catch(N){n(q=>({...q,busy:!1,error:vn(N)}))}}},[e.connection,e.teamId]),we=v.useCallback(()=>{_.current=null,n(L=>({...L,agentConversation:null}))},[]),ie=v.useCallback(async L=>{const N=m.current,q=t.agentConversation;if(!e.connection||!e.teamId||!N||!q||!L.body.trim())return!1;n(X=>({...X,busy:!0,error:null}));try{const X=await Q.createTeamChatAgentRun(e.connection,N,yY({teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,conversation:q}));_.current=X.run.id;const[me]=await Promise.all([Q.teamChatAgentConversation(e.connection,e.teamId,X.run.id),ue(N),J()]);return n($e=>({...$e,agentConversation:me,busy:!1})),!0}catch(X){return n(me=>({...me,busy:!1,error:vn(X)})),!1}},[e.connection,e.teamId,ue,J,t.agentConversation]),Se=v.useCallback(()=>{h.current+=1,d.current=null,n(L=>({...L,aiThread:null}))},[]),Ue=v.useCallback(async L=>{const N=d.current;if(!e.connection||!e.teamId||!N||!L.body.trim())return!1;n(q=>({...q,busy:!0,error:null}));try{const q=await Q.sendTeamChatAiTurn(e.connection,N,{teamId:e.teamId,body:L.body.trim(),clientRequestId:crypto.randomUUID(),providerId:L.providerId,modelId:L.modelId});return n(X=>({...ix(X,q,d.current),busy:!1})),q.activeTurn&&await Q.executeTeamChatAiTurn(e.connection,q.activeTurn.id,e.teamId),!0}catch(q){return n(X=>({...X,busy:!1,error:vn(q)})),!1}},[e.connection,e.teamId]),Je=v.useCallback(async()=>{const L=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!L?!1:(await Q.cancelTeamChatAiTurnExecution(e.connection,L,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),Ke=v.useCallback(async(L,N)=>{if(!e.connection||!e.teamId)return!1;try{return await Q.editTeamChatMessage(e.connection,L.threadId,L.id,{teamId:e.teamId,body:N}),await ue(L.threadId),!0}catch(q){return n(X=>({...X,error:vn(q)})),!1}},[e.connection,e.teamId,ue]),tt=v.useCallback(async L=>{if(!e.connection||!e.teamId)return!1;try{return await Q.deleteTeamChatMessage(e.connection,L.threadId,L.id,e.teamId),await ue(L.threadId),!0}catch(N){return n(q=>({...q,error:vn(N)})),!1}},[e.connection,e.teamId,ue]),ze=v.useCallback(async L=>{if(!e.connection||!e.teamId||!L.clientRequestId||!L.id.startsWith("pending:"))return!1;const N=Array.isArray(L.metadata.mentionUserIds)?L.metadata.mentionUserIds.filter(me=>typeof me=="string"):[],q=j.current.get(L.clientRequestId),X=L.refs.find(me=>me.refType==="message_reply");Kf(O.current,L.clientRequestId,"sending"),n(me=>Zh(me,L.clientRequestId,"sending"));try{let me=q?.uploaded??[];if(q&&!q.uploaded){me=[];for(const[Le,nt]of q.inputs.entries())me.push(await Q.uploadTeamChatAttachment(e.connection,L.threadId,{teamId:e.teamId,attachment:nt})),rx(O.current,L.clientRequestId,`${Le+1} of ${q.inputs.length}`),n(at=>lx(at,L.clientRequestId,`${Le+1} of ${q.inputs.length}`));q.uploaded=me}const $e=await Q.sendTeamChatMessage(e.connection,L.threadId,{teamId:e.teamId,body:L.body,clientRequestId:L.clientRequestId,mentionUserIds:N,attachmentIds:me.map(Le=>Le.id),replyToMessageId:X?.refId??null});return j.current.delete(L.clientRequestId),O.current.delete(L.clientRequestId),n(Le=>sx(Le,$e,e.currentUserId)),!0}catch(me){return Kf(O.current,L.clientRequestId,"failed"),n($e=>({...Zh($e,L.clientRequestId,"failed"),error:vn(me)})),!1}},[e.connection,e.currentUserId,e.teamId]),Ge=v.useCallback(L=>{L.id.startsWith("pending:")&&(L.clientRequestId&&j.current.delete(L.clientRequestId),L.clientRequestId&&O.current.delete(L.clientRequestId),n(N=>uY(N,L.id)))},[]),qe=v.useCallback(async(L,N)=>{if(!e.connection||!e.teamId)return!1;try{const q=await Q.setTeamChatThreadMuted(e.connection,L,e.teamId,N),X=me=>me.id===q.threadId?{...me,mutedAt:q.mutedAt}:me;return n(me=>({...me,threads:me.threads.map(X),detail:me.detail?.thread.id===q.threadId?{...me.detail,thread:X(me.detail.thread)}:me.detail,error:null})),!0}catch(q){return n(X=>({...X,error:vn(q)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:o,incomingNotification:s,setNotificationMode:B,dismissIncomingNotification:D,setThreadMuted:qe,selectThread:ne,openDm:be,loadMoreMessages:ae,sendMessage:de,openAiThread:xe,openAgentConversation:De,closeAgentConversation:we,sendAgentTurn:ie,closeAiThread:Se,sendAiTurn:Ue,stopAiTurn:Je,editMessage:Ke,deleteMessage:tt,retryMessage:ze,dismissFailedMessage:Ge,refreshDirectory:le,refresh:async()=>{await Promise.all([le(),J(),ue(),je(),ke()])}}}function vn(e){return hY(e)}const pP="local-profile-agent";function Rte(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(s=>{const l=s.implementation;return l?.type!=="openpond-agent"||l.profileName!==t.activeProfile?[]:[Ji(l.agentName),Ji(s.name),Ji(s.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,o=new Set(e.hostedActions.map(s=>s.implementation?.agentId).filter(s=>typeof s=="string")),r=t.agents.flatMap(s=>s.enabled?a?.agentId===s.id&&!!(a.runtimeAgentId&&o.has(a.runtimeAgentId))||n.has(Ji(s.name))||n.has(Ji(s.id))?[]:[IY(t,s)]:[]);return[...e.hostedActions,...r]}function Pte(e){return e?.implementation?.type===pP}function Ate(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function kY(e,t){if(!e||e.mode!=="local")return"Load a local OpenPond profile before publishing an agent to Team.";const n=e.agents.find(a=>a.id===t);return n?n.enabled?e.git?.head?e.git.dirty?`Commit your profile changes before publishing ${n.name} to Team.`:e.setupGate.blockingCount>0?`${n.name} has ${e.setupGate.blockingCount} blocking setup requirement${e.setupGate.blockingCount===1?"":"s"}. Complete setup before publishing it to Team.`:null:`Commit ${n.name} before publishing it to Team.`:`${n.name} is disabled in the active profile.`:`Profile agent not found: ${t}`}function wY(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",o=Ji(t.agentName);return e.find(r=>{const s=r.implementation;return s?.type!=="openpond-agent"?!1:n&&typeof s.agentId=="string"&&s.agentId===n?!0:!!(a&&s.profileName===a&&o&&[s.agentName,r.name,r.label].some(l=>Ji(l)===o))})??null}function IY(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:_Y(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:pP,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function _Y(e){return e.git?.head?e.git.dirty?"My Agent · Commit profile changes before publishing to this Team":e.setupGate.blockingCount>0?"My Agent · Complete required setup before publishing to this Team":"My Agent · Publishes to this Team on first use":"My Agent · Commit the profile before publishing to this Team"}function Ji(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const px=5;function CY(e){return v.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await Q.profileCheck(e.connection,{kind:"all"}),a=kY(n,t);if(a)throw new Error(a);const o=n?.agents.find(d=>d.id===t);if(!o)throw new Error(`Profile agent not found: ${t}`);const s=(await Q.profilePush(e.connection,{teamId:e.teamId,ensureHosted:!0,hostedSourceAgentId:t,message:null})).localProfile?.hosted?.hostedSourceMaterialization,l=s?.agentId===t?s.runtimeAgentId:null;e.applyBootstrapPayload(await Q.bootstrap(e.connection));let m=null;for(let d=0;d<px;d+=1){const h=await e.refreshDirectory();if(m=wY(h.agents,{runtimeAgentId:l,profileName:n.activeProfile,agentName:o.name}),m)break;d<px-1&&await RY(200*(d+1))}if(!m)throw new Error(`${o.name} was published, but the Team agent directory has not refreshed yet. Retry the mention in a moment.`);return m},[e.applyBootstrapPayload,e.connection,e.refreshDirectory,e.teamId])}function RY(e){return new Promise(t=>{setTimeout(t,e)})}function PY(e){v.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:o}=e.notification;e.showToast(`${a}: ${o}`,"info",{actionLabel:"Open",onAction:()=>{e.setView("team"),e.selectThread(n)},durationMs:6500,placement:"top-right"}),e.dismiss(t)},[e.dismiss,e.notification,e.selectThread,e.setView,e.showToast])}function AY(e){const{connection:t,refreshToken:n=null}=e,[a,o]=v.useState([]),[r,s]=v.useState(null),[l,m]=v.useState(null),[d,h]=v.useState(null),[g,y]=v.useState(!1),[w,_]=v.useState(!1),[P,M]=v.useState(!1),[C,$]=v.useState(null),[O,j]=v.useState(null),[x,R]=v.useState(null),[E,H]=v.useState(0),B=v.useRef(0),D=v.useMemo(()=>a.find(ae=>ae.id===l)??null,[a,l]),J=v.useCallback(async()=>{if(!t)return!1;y(!0),$(null);try{const ae=await Q.communities(t);return o(ae.items),s(ae.nextCursor),m(de=>de&&ae.items.some(xe=>xe.id===de)?de:null),!0}catch(ae){return $(Wd(ae)),!1}finally{y(!1)}},[t]),le=v.useCallback(async()=>{if(!t||!r||g)return!1;y(!0),$(null);try{const ae=await Q.communities(t,r);return o(de=>TY(de,ae.items)),s(ae.nextCursor),!0}catch(ae){return $(Wd(ae)),!1}finally{y(!1)}},[t,g,r]),ue=v.useCallback(async ae=>{if(!t)return null;const de=++B.current;_(!0),j(null);try{const xe=await Q.communityPreview(t,ae.slug);return B.current===de&&h(xe),xe}catch(xe){return B.current===de&&j(Wd(xe)),null}finally{B.current===de&&_(!1)}},[t]),je=v.useCallback(ae=>{const de=a.find(xe=>xe.id===ae);de&&(m(de.id),h(xe=>xe?.id===de.id?xe:null),R(null),ue(de))},[a,ue]),ke=v.useCallback(()=>{B.current+=1,m(null),h(null),j(null),R(null)},[]);v.useEffect(()=>{if(!t){o([]),h(null),m(null);return}J()},[t,J,n]),v.useEffect(()=>{!D||d?.id===D.id||w||ue(D)},[ue,d?.id,w,D]);const te=v.useCallback(async()=>{const ae=D;await J(),ae&&await ue(ae)},[ue,J,D]),Me=v.useCallback(async()=>{if(!t||!d?.currentRules||P)return!1;M(!0),R(null);try{return await Q.joinCommunity(t,d.id,d.currentRules.id),H(ae=>ae+1),await te(),!0}catch(ae){const de=_d(ae);return R(de),de.kind==="rules_stale"&&await te(),!1}finally{M(!1)}},[t,P,d,te]),ye=v.useCallback(async()=>{if(!t||!d?.currentRules||P)return!1;M(!0),R(null);try{return await Q.acceptCommunityRules(t,d.id,d.currentRules.id),H(ae=>ae+1),await te(),!0}catch(ae){const de=_d(ae);return R(de),de.kind==="rules_stale"&&await te(),!1}finally{M(!1)}},[t,P,d,te]),ne=v.useCallback(async()=>{if(!t||!d||P)return!1;M(!0),R(null);try{return await Q.leaveCommunity(t,d.id),H(ae=>ae+1),await te(),!0}catch(ae){return R(_d(ae)),!1}finally{M(!1)}},[t,P,d,te]),be=v.useCallback(async ae=>{if(!t||!d||P)return!1;M(!0),R(null);try{return await Q.updateCommunityNotifications(t,d.id,ae),o(de=>de.map(xe=>xe.id===d.id&&xe.membership?{...xe,membership:{...xe.membership,notificationMode:ae}}:xe)),h(de=>de?.id===d.id&&de.membership?{...de,membership:{...de.membership,notificationMode:ae}}:de),!0}catch(de){return R(_d(de)),!1}finally{M(!1)}},[t,P,d]);return{items:a,nextCursor:r,selectedCommunityId:l,selectedSummary:D,preview:d,discoveryLoading:g,previewLoading:w,membershipBusy:P,discoveryError:C,previewError:O,membershipError:x,membershipVersion:E,refresh:J,loadMore:le,showDiscovery:ke,selectCommunity:je,join:Me,acceptRules:ye,leave:ne,updateNotifications:be,clearMembershipError:()=>R(null)}}function TY(e,t){const n=new Map(e.map(a=>[a.id,a]));for(const a of t)n.set(a.id,a);return[...n.values()]}function Wd(e){return e instanceof Error?e.message:String(e)}function _d(e){const t=Wd(e);return t.includes("community_rules_version_stale")?{kind:"rules_stale",message:"The community rules changed. Review the newest version and try again."}:t.includes("community_membership_required")?{kind:"membership_lost",message:"Your community membership is no longer active."}:t.includes("community_join_closed")||t.includes("community_invalid_request")?{kind:"join_conflict",message:"The community could not be joined in its current state."}:{kind:"unknown",message:t}}function EY(e,t,n){return lP({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const o=xw.safeParse(a);o.success&&e.onEvent(o.data)},onReady:e.onReady,onError:e.onError},t,n)}function MY(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:o}=e,r=n?.id??null,s=n?.membership?.status==="active",l=!n?.capabilities.requiresRulesAcceptance,[m,d]=v.useState([]),[h,g]=v.useState(null),[y,w]=v.useState({}),[_,P]=v.useState([]),[M,C]=v.useState(!1),[$,O]=v.useState(!1),[j,x]=v.useState(!1),[R,E]=v.useState(!1),[H,B]=v.useState(null),[D,J]=v.useState(null),[le,ue]=v.useState(null),[je,ke]=v.useState(null),[te,Me]=v.useState(!1),[ye,ne]=v.useState(null),[be,ae]=v.useState(null),de=v.useRef(null),xe=v.useRef([]),De=v.useRef("mentions"),we=v.useRef(0),ie=v.useRef({}),Se=v.useRef(new Set),Ue=v.useMemo(()=>m.find(Oe=>Oe.id===h)??null,[m,h]),Je=h?y[h]??null:null;v.useEffect(()=>{de.current=h},[h]),v.useEffect(()=>{xe.current=m},[m]),v.useEffect(()=>{De.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const Ke=v.useCallback(async()=>{if(!t||!r)return!1;C(!0),B(null);try{const Oe=await Q.communityChannels(t,r);return d(Oe.channels),g(Ye=>Ye&&Oe.channels.some(f=>f.id===Ye)?Ye:Oe.channels.find(f=>f.isDefault)?.id??Oe.channels[0]?.id??null),Me(!1),!0}catch(Oe){const Ye=da(Oe);return B(Ye),kl(Ye)&&Me(!0),!1}finally{C(!1)}},[r,t]),tt=v.useCallback(async Oe=>{if(!t||!r)return!1;const Ye=++we.current;O(!0),J(null);try{const f=await Q.communityMessages(t,r,Oe,{limit:50});return Ye!==we.current?!1:(w(U=>({...U,[Oe]:{items:f.messages,hasMoreBefore:f.hasMoreBefore,preview:f.preview}})),Me(!1),!0)}catch(f){if(Ye!==we.current)return!1;const U=da(f);return J(U),kl(U)&&Me(!0),!1}finally{Ye===we.current&&O(!1)}},[r,t]);v.useEffect(()=>{d(n?.channels??[]),w({}),g(n?.channels.find(Oe=>Oe.isDefault)?.id??n?.channels[0]?.id??null),B(null),J(null),ue(null),Me(!1),Se.current.clear(),r&&Ke()},[r,Ke,o]),v.useEffect(()=>{h&&tt(h)},[tt,h]);const ze=v.useCallback(async(Oe,Ye)=>{if(!t||!r||!s||!l||Ye<=0)return!1;if((ie.current[Oe]??0)>=Ye)return!0;ie.current[Oe]=Ye;try{const f=await Q.markCommunityRead(t,r,Oe,Ye);return d(U=>U.map(Y=>Y.id===Oe?{...Y,unreadCount:0,readState:Y.readState?{...Y.readState,lastReadSequence:f.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:f.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:Y)),!0}catch(f){const U=da(f);return kl(U)&&Me(!0),!1}},[r,t,s,l]);v.useEffect(()=>{const Oe=Je?.items.at(-1)?.sequence??0;h&&Oe>0&&ze(h,Oe)},[ze,h,Je?.items]);const Ge=v.useCallback(Oe=>{if(Oe.communityId!==r||Se.current.has(Oe.id))return;Se.current.add(Oe.id);const Ye=Sw.safeParse(Oe.payload.message);if(Ye.success&&Oe.type!=="read.updated"){const f=Ye.data;if(w(U=>{const Y=U[Oe.channelId];if(!Y)return U;const re=Y.items.some(W=>W.id===f.id)?Y.items.map(W=>W.id===f.id?f:W):[...Y.items,f].sort((W,I)=>W.sequence-I.sequence);return{...U,[Oe.channelId]:{...Y,items:re}}}),d(U=>U.map(Y=>Y.id===Oe.channelId?{...Y,lastMessageSequence:Math.max(Y.lastMessageSequence,f.sequence),unreadCount:de.current===Oe.channelId||f.authorUserId===a?0:Math.max(Y.unreadCount+(Oe.type==="message.created"?1:0),0)}:Y)),Oe.type==="message.created"&&f.authorUserId!==a){const U=xe.current.find(re=>re.id===Oe.channelId),Y=jY(f).includes(a??""),he=De.current;!U?.readState?.mutedAt&&(he==="all"||he==="mentions"&&Y)&&ae({communityId:Oe.communityId,channelId:Oe.channelId,message:f})}de.current===Oe.channelId&&ze(Oe.channelId,f.sequence);return}Oe.type==="read.updated"&&Oe.payload.userId===a&&Ke()},[r,a,Ke,ze]);v.useEffect(()=>{if(!t||!r||!s||!l)return;let Oe=!1,Ye=null;return ue(null),Promise.all([Q.communityRealtimeSession(t,r),Q.communityEvents(t,r)]).then(async([f,U])=>{if(Oe)return;const Y=async()=>{let re=U.cursor;for(;;){const W=await Q.communityEvents(t,r,{after:re,limit:200});if(Oe)return;for(const I of W.events)Ge(I);if(re=W.cursor,!W.hasMore)return}},he=EY({session:f,onEvent:Ge,onReady:()=>{ue(null),Y().catch(re=>ue(da(re)))},onError:re=>ue(da(re))});Ye=()=>he.close(),await Y()}).catch(f=>{if(!Oe){const U=da(f);ue(U),kl(U)&&Me(!0)}}),()=>{Oe=!0,Ye?.()}},[Ge,r,t,s,o,l]);const qe=v.useCallback(async()=>{if(!t||!r||!h||j)return!1;const Oe=y[h],Ye=Oe?.items[0]?.sequence;if(!Oe?.hasMoreBefore||Ye==null)return!1;x(!0),J(null);try{const f=await Q.communityMessages(t,r,h,{beforeSequence:Ye,limit:50});return w(U=>{const Y=U[h]??Oe,he=new Set(Y.items.map(re=>re.id));return{...U,[h]:{...Y,items:[...f.messages.filter(re=>!he.has(re.id)),...Y.items],hasMoreBefore:f.hasMoreBefore}}}),!0}catch(f){return J(da(f)),!1}finally{x(!1)}},[r,t,y,j,h]),L=v.useCallback(async Oe=>{if(!t||!r||!h||R)return!1;E(!0),ke(null),ne(null);try{const Ye=await Promise.all(Oe.attachments.map(U=>Q.uploadCommunityAttachment(t,r,h,U))),f=await Q.sendCommunityMessage(t,r,h,{body:Oe.body,clientRequestId:Oe.clientRequestId,mentionUserIds:Oe.mentionUserIds,attachmentIds:Ye.map(U=>U.id),replyToMessageId:Oe.replyToMessageId});return w(U=>{const Y=U[h]??{items:[],hasMoreBefore:!1,preview:!1};return Y.items.some(he=>he.id===f.id)?U:{...U,[h]:{...Y,items:[...Y.items,f]}}}),await ze(h,f.sequence),!0}catch(Ye){const f=da(Ye);return ke(f),ne({...Oe,message:f}),kl(f)&&Me(!0),!1}finally{E(!1)}},[r,t,ze,h,R]),N=v.useCallback(Oe=>L({body:Oe.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Oe.mentionUserIds??[],attachments:Oe.attachments??[],replyToMessageId:Oe.replyToMessageId??null}),[L]),q=v.useCallback(async(Oe,Ye)=>{if(!t||!r||!h)return!1;ke(null);try{const f=await Q.editCommunityMessage(t,r,h,Oe,Ye);return fx(w,h,f),!0}catch(f){return ke(da(f)),!1}},[r,t,h]),X=v.useCallback(async Oe=>{if(!t||!r||!h)return!1;ke(null);try{const Ye=await Q.deleteCommunityMessage(t,r,h,Oe);return fx(w,h,Ye),!0}catch(Ye){return ke(da(Ye)),!1}},[r,t,h]),me=v.useCallback(async(Oe,Ye)=>{if(!t||!r)return!1;ke(null);try{const f=await Q.setCommunityChannelMuted(t,r,Oe,Ye);return d(U=>U.map(Y=>Y.id===Oe&&Y.readState?{...Y,readState:{...Y.readState,mutedAt:f.mutedAt}}:Y)),!0}catch(f){return ke(da(f)),!1}},[r,t]),$e=v.useCallback(async(Oe="")=>{if(!t||!r||!s)return[];try{const Ye=await Q.searchCommunityMembers(t,r,{query:Oe,limit:50});return P(f=>OY(f,Ye.items)),Ye.items}catch(Ye){return ke(da(Ye)),[]}},[r,t,s]);v.useEffect(()=>{s&&l?$e():P([])},[s,l,$e]);const Le=v.useCallback(async Oe=>{if(!t||!r||!h)return!1;try{const Ye=await Q.communityAttachmentDownload(t,r,h,Oe);return window.open(Ye.url,"_blank","noopener,noreferrer"),!0}catch(Ye){return ke(da(Ye)),!1}},[r,t,h]),nt=v.useCallback(()=>h?tt(h):Promise.resolve(!1),[tt,h]),at=v.useCallback(()=>ye?L(ye):Promise.resolve(!1),[ye,L]),lt=v.useCallback(()=>ne(null),[]),pt=v.useCallback(()=>ae(null),[]);return{channels:m,selectedChannelId:h,selectedChannel:Ue,messages:Je?.items??[],hasMoreBefore:Je?.hasMoreBefore??!1,previewMode:Je?.preview??!s,members:_,channelsLoading:M,messagesLoading:$,olderMessagesLoading:j,sending:R,channelsError:H,messagesError:D,realtimeError:le,actionError:je,lostMembership:te,failedSend:ye,incomingNotification:be,selectChannel:g,loadChannels:Ke,loadMessages:nt,loadOlder:qe,sendMessage:N,retrySend:at,dismissFailedSend:lt,editMessage:q,deleteMessage:X,setMuted:me,searchMembers:$e,downloadAttachment:Le,dismissIncomingNotification:pt}}function fx(e,t,n){e(a=>{const o=a[t];return o?{...a,[t]:{...o,items:o.items.map(r=>r.id===n.id?n:r)}}:a})}function jY(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function OY(e,t){const n=new Map(e.map(a=>[a.userId,a]));for(const a of t)n.set(a.userId,a);return[...n.values()].slice(-200)}function kl(e){return e.includes("community_membership_required")||e.includes("community_rules")}function da(e){return e instanceof Error?e.message:String(e)}function $Y(e){const t=AY({connection:e.connection,refreshToken:e.refreshToken}),n=MY({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,o=t.items,r=n.channels,s=t.selectCommunity,l=n.selectChannel,m=n.dismissIncomingNotification,{setView:d,showToast:h}=e,g=v.useCallback(()=>{t.showDiscovery(),d("community")},[t.showDiscovery,d]),y=v.useCallback(_=>{t.selectCommunity(_),d("community")},[t.selectCommunity,d]),w=v.useCallback(_=>{n.selectChannel(_),d("community")},[n.selectChannel,d]);return v.useEffect(()=>{if(!a)return;const _=o.find(M=>M.id===a.communityId),P=r.find(M=>M.id===a.channelId);h(`${_?.displayName??"Community"} · #${P?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),l(a.channelId),d("community")},placement:"top-right"}),m()},[r,o,m,a,l,s,d,h]),{communities:t,chat:n,sidebar:{communityItems:t.items,communityChannels:n.channels,communityLoading:t.discoveryLoading,communityError:t.discoveryError,selectedCommunityId:t.selectedCommunityId,selectedCommunityChannelId:n.selectedChannelId,discoverCommunities:g,selectCommunity:y,selectCommunityChannel:w},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const NY=[];function DY(e){const t=v.useCallback(a=>p8(e,a),[e]),n=v.useCallback(()=>u8(e)??NY,[e]);return v.useSyncExternalStore(t,n,n)}function LY(e){const[t,n]=v.useState(()=>lf());return v.useEffect(()=>{let a=!0;return e?(Q.connectedAppStatus(e,{status:"all"}).then(o=>{a&&n(o.apps)}).catch(o=>{console.warn("Unable to load connected app mention status.",o),a&&n(lf())}),()=>{a=!1}):(n(lf()),()=>{a=!1})},[e]),t}function HY(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=nZ(),[o,r]=v.useState(null),[s,l]=v.useState([]),[m,d]=v.useState(null),[h,g]=v.useState(null),[y,w]=v.useState([]),[_,P]=v.useState(null),[M,C]=v.useState(null),[$,O]=v.useState(bR),[j,x]=v.useState({}),[R,E]=v.useState(()=>new Set),H=v.useCallback((ot,zt)=>{E(Bt=>{if(Bt.has(ot)===zt)return Bt;const Ft=new Set(Bt);return zt?Ft.add(ot):Ft.delete(ot),Ft})},[]),[B,D]=v.useState(0),[J,le]=v.useState(null),ue=v.useRef(null),{confirmProjectAction:je,projectConfirmDialog:ke,resolveProjectConfirmDialog:te}=nW(),{query:Me,searchOpen:ye,archivedChatsOpen:ne,sectionMenuOpen:be,projectsExpanded:ae,cloudProjectsExpanded:de,chatRowsVisibleCount:xe,sidebarOpen:De,view:we,selectedAppId:ie,selectedProjectId:Se,selectedSessionId:Ue,draftProvider:Je,draftModel:Ke,draftExperience:tt,codexPermissionMode:ze,codexReasoningEffort:Ge,openPondCommandAccessMode:qe,busy:L,diffPanelOpen:N,diffPanelExpanded:q,rightPanelMode:X,rightChatPanels:me,terminalOpen:$e,settingsSection:Le,newProjectDialogOpen:nt,newProjectMode:at,newProjectName:lt,newProjectPath:pt,newProjectBusy:Oe,commitDialogOpen:Ye,commitMessage:f,commitIncludeUnstaged:U,commitNextStep:Y,commitDraft:he,branchDialogOpen:re,branchDialogName:W,toast:I,error:K}=a,ee=sZ(we==="labs"),{setQuery:Z,setSearchOpen:ce,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:Ae,setCloudProjectsExpanded:_e,setChatRowsVisibleCount:Ne,setSidebarOpen:Pe,setView:Xe,setSelectedAppId:st,setSelectedProjectId:rn,setSelectedSessionId:Et,setPrompt:tn,setDraftProvider:mn,setDraftModel:pn,setDraftExperience:Wt,setCodexPermissionMode:Da,setCodexReasoningEffort:ga,setOpenPondCommandAccessMode:$n,setDiffPanelOpen:Pn,setDiffPanelExpanded:$t,setRightPanelMode:ht,setRightChatPanels:fn,setTerminalOpen:bt,setSyncingWorkspaceAppId:jt,setSettingsSection:va,setNewProjectDialogOpen:Ut,setNewProjectMode:hn,setNewProjectName:it,setNewProjectPath:Cn,setNewProjectBusy:ao,setCommitDialogOpen:oo,setCommitMessage:ra,setCommitIncludeUnstaged:ba,setCommitNextStep:Nn,setCommitDraft:Po,setBranchDialogOpen:La,setBranchDialogName:V,setError:He}=n,{connectionRef:Ie,setError:Be,showToast:yt}=WJ({appDispatch:t,error:K,setErrorState:He}),{appPreferences:Jn,applyBootstrapPayload:gn,bootstrap:We,codexHistorySessions:yn,connection:ut,events:An,runtimeEventStore:Ha,approvals:ri,sessions:ya,startup:si,setAppPreferences:$i,setBootstrap:Ao,setCodexHistorySessions:Dn,setEvents:Sa,setSessions:Zn}=FJ({setDraftModel:pn,setDraftProvider:mn,setCodexPermissionMode:Da,setCodexReasoningEffort:ga,setOpenPondCommandAccessMode:$n,setError:Be,setSelectedAppId:st,setSelectedProjectId:rn,setSelectedSessionId:Et});Ie.current=ut,v.useEffect(()=>{We&&w(We.sidebarFileBookmarks??[])},[We?.sidebarFileBookmarks]);const li=v.useMemo(()=>[...An].reverse().find(ot=>ot.name==="tool.completed"&&ot.action==="manage_sidebar_file")??null,[An]),Ni=v.useRef(null);v.useEffect(()=>{!ut||!li||Ni.current===li.id||(Ni.current=li.id,Q.sidebarFiles(ut).then(ot=>w(ot.items)).catch(ot=>Be(ot instanceof Error?ot.message:String(ot))))},[ut,li,Be]);const ci=v.useCallback(async(ot,zt)=>{if(!ut)return;const Bt=y;w(Ft=>zt==="none"?Ft.filter(za=>za.id!==ot.id):Ft.some(za=>za.id===ot.id)?Ft.map(za=>za.id===ot.id?{...za,status:zt}:za):[...Ft,{...ot,status:zt}]);try{const Ft=await Q.patchSidebarFile(ut,{workspaceKind:ot.workspaceKind,workspaceId:ot.workspaceId,workspaceName:ot.workspaceName,path:ot.path,status:zt,sourceSessionId:ot.sourceSessionId});w(Ft.items)}catch(Ft){w(Bt),Be(Ft instanceof Error?Ft.message:String(Ft))}},[ut,Be,y]),di=LY(ut),xt=fZ({connection:ut,profileId:We?.profile?.activeProfile??"default"}),{pinnedCollapsed:Bs,projectsCollapsed:Di,cloudProjectsCollapsed:Fs,chatsCollapsed:Sr,savedForLaterCollapsed:Vs,sidebarWidth:To,sidebarResizing:Ks,diffPanelWidth:xr,diffPanelResizing:kr,togglePinnedCollapsed:wr,toggleProjectsCollapsed:Ws,toggleCloudProjectsCollapsed:Gs,toggleChatsCollapsed:io,toggleSavedForLaterCollapsed:Js,startSidebarResize:Ir,startDiffPanelResize:_r}=iZ({connection:ut,preferences:We?.preferences,sidebarOpen:De,diffPanelExpanded:q,setBootstrap:Ao,setError:Be}),{cloudProjectById:ui,linkedProjectByAppId:Cr,localProjectById:sa,mentionableSandboxApps:Zs,selectedApp:Li,selectedCloudProject:Eo,selectedProject:Yn,selectedProjectLinkedApp:Ys,selectedProjectLinkedOpenPondApp:Qs,selectedSession:Sn,selectedSessionLinkedProject:mi,sidebarSessions:xa}=T8({bootstrap:We,codexHistorySessions:yn,selectedAppId:ie,selectedProjectId:Se,selectedSessionId:Ue,sessions:ya}),Ua=Sn?.experience??tt;v.useEffect(()=>{a8(Ua)},[Ua]);const Hi=v.useMemo(()=>tK(xa,Ua),[Ua,xa]),pi=wZ(An,ri),{chatMentionApps:Xs,connectedAppMentions:Rr,pendingApproval:Ui}=J8({bootstrap:We,connectedAppRows:di,mentionableSandboxApps:Zs,runtimeIndexes:pi,selectedApp:Li,selectedCloudProject:Eo,selectedProject:Yn,selectedSession:Sn,selectedSessionId:Ue}),{codexHistoryEvents:Mo,setCodexHistoryEvents:fi}=fG({connection:ut,selectedSessionId:Ue,selectedSessionLocallyActive:!!(Ue&&R.has(Ue)),selectedSessionStatus:Sn?.status,setCodexHistorySessions:Dn,setError:Be}),{account:hi,accountPending:Pr,accountSignedOut:Ar,activeModel:ka,activeProvider:wa,activeWorkspaceAppId:Tr,activeWorkspaceId:qi,activeWorkspaceKind:ro,activeWorkspaceLocation:zi,appDefaults:jo,cloudLinked:Er,selectedCodexHistoryPending:Mr,selectedSessionProjectId:jr,startMessage:el,workspaceName:Or}=_8({bootstrap:We,draftModel:Ke,draftProvider:Je,selectedApp:Li,selectedAppId:ie,selectedCloudProject:Eo,selectedProject:Yn,selectedSession:Sn,selectedSessionId:Ue,selectedSessionLinkedProject:mi}),$r=v.useMemo(()=>g8(We?.account??null),[We?.account]),tl=v.useMemo(()=>Hh(We?.account??null),[We?.account]),gi=DY(tl),Nr=v.useMemo(()=>y8(gi,jo.defaultTeamId),[jo.defaultTeamId,gi]),Bi=Nr?.teamId??null,so=xY({connection:ut,teamId:Bi,currentUserId:hi?.profile?.id??null,refreshToken:We?.accountMeta.asOf??null}),nl=CY({connection:ut,teamId:Bi,applyBootstrapPayload:gn,refreshDirectory:so.refreshDirectory});PY({notification:so.incomingNotification,dismiss:so.dismissIncomingNotification,selectThread:so.selectThread,setView:Xe,showToast:yt});const{communities:al,sidebar:ol,view:il}=$Y({connection:ut,currentUserId:hi?.profile?.id??null,refreshToken:We?.accountMeta.asOf??null,setView:Xe,showToast:yt}),lo=so.aiThread?.conversationId??null,Dr=we==="team"&&!!lo&&N&&X==="chat";v.useEffect(()=>{if(we==="team"){if(lo){ht("chat"),Pn(!0);return}X==="chat"&&Pn(!1)}},[X,Pn,ht,lo,we]);const rl=v.useCallback(()=>{if(lo){if(Dr){Pn(!1);return}ht("chat"),Pn(!0)}},[Pn,ht,Dr,lo]),sl=v.useMemo(()=>Oa(Yn,We?.cloudProjects??[]),[We?.cloudProjects,Yn]),ll=Sn?.provider==="codex"?qe:Sn?.openPondCommandAccessMode??qe,la=Tr,Lr=qi,cl=ro,ct=Or,{openPondActionCatalog:Yt,selectedActionCatalog:Qn}=LZ({cloudProjectById:ui,cloudProjects:We?.cloudProjects??[],connection:ut,defaultTeamId:jo.defaultTeamId,accountScopeKey:$r,localProjects:We?.localProjects??[],profile:We?.profile,selectedCloudProject:Eo,selectedProject:Yn,reportError:Be}),{expandedProjectIds:sn,expandProject:Tn,toggleProjectExpanded:ca,setExpandedProjectIds:xm}=HZ({selectedProjectId:Se});D8({activeWorkspaceId:qi,activeWorkspaceKind:ro,appDispatch:t,connection:ut,expandProject:Tn,linkedProjectByAppId:Cr,providerSettings:We?.providers??null,selectedAppId:ie,selectedSession:Sn,selectedSessionId:Ue,selectedSessionProjectId:jr,setDiffPanelExpanded:$t,setDraftModel:pn,setDraftProvider:mn,setError:Be,setSelectedAppId:st,setSelectedProjectId:rn,setSessions:Zn,setTerminalOpen:bt,toast:I});const{changeCodexPermissionMode:km,changeCodexReasoningEffort:wm}=Z8({connection:ut,setBootstrap:Ao,setCodexPermissionMode:Da,setCodexReasoningEffort:ga,setError:Be}),{changeOpenPondCommandAccessMode:qc}=X7({connection:ut,selectedSession:Sn,setBootstrap:Ao,setError:Be,setOpenPondCommandAccessMode:$n,setSessions:Zn}),Im=L8({connection:ut,setError:Be}),Fi=v.useCallback(()=>{D(ot=>ot+1)},[]),zc=U8({appDispatch:t,expandProject:Tn,linkedProjectByAppId:Cr,requestComposerFocus:Fi,onBeginNewChat:()=>{Xt({kind:"chat",sessionId:null}),le(null),Wt(ot=>ot==="development"?"work":ot)},setMentionedAppId:g}),Hr=v.useCallback(ot=>{const zt=St("local",ot);t({type:"selectProject",projectId:zt}),Tn(zt)},[t,Tn]),{advanceAfterTurn:_m,begin:Cm,bindSession:Rm,dismiss:Pm,handoff:Am,prepareTurn:Tm,selectTask:Em}=SZ({activeModel:ka,activeProvider:wa,applyBootstrapPayload:gn,beginNewChat:zc,composerDraftStore:e,connection:ut,requestComposerFocus:Fi,selectedLocalProjectId:Yn?.id??null,selectedSessionId:Ue,selectLocalProject:Hr,setDraftModel:pn,setDraftProvider:mn,setError:Be,view:we});oZ({connection:ut,events:An,showToast:yt}),sJ({searchOpen:ye,sectionMenuOpen:be,setSectionMenuOpen:fe,setSearchOpen:ce,setQuery:Z}),v.useEffect(()=>{x({})},[We?.server.id]);const{chatHistoryLoadStates:Mm,loadMoreSelectedChatHistory:jm,selectedPagedSessionEvents:Om,selectedRuntimeIndexes:Bc}=xZ({approvals:ri,codexHistoryEvents:Mo,connection:ut,latestServerSequence:We?.eventWindow?.latestSequence,runtimeIndexes:pi,runtimeEventStore:Ha,selectedSessionId:Ue,serverId:We?.server.id,setCodexHistoryEvents:fi,setCodexHistorySessions:Dn,setError:Be}),{activeSessions:$m,archivedSessions:Nm,pinnedProjects:Dm,pinnedSessions:dl,savedForLaterSessions:Fc,pinnedFiles:Lm,savedForLaterFiles:Hm,pinnedItems:Vc,projectRows:Kc,localProjectRows:Um,visibleProjectRows:Ur,cloudProjectRows:qm,projectSessionRowsByProjectId:Wc,childSessionRowsByParentId:zm,sidebarProjectIdBySessionId:ul,chatRows:Gc,visibleChatRows:Jc,sessionEvents:Bm,chatMessages:Zc,contextUsage:Fm,goalRuntime:Vm,subagentRuntime:Yc}=eJ({localProjects:We?.localProjects??[],cloudProjects:We?.cloudProjects??[],sessions:Hi,runtimeIndexes:Bc,appPreferences:Jn,selectedSessionId:Ue,selectedProjectId:Se,archivedChatsOpen:ne,projectsExpanded:ae,chatRowsVisibleCount:xe,sidebarFileBookmarks:y}),Km=v.useCallback(ot=>{Wt(ot);const zt=[...Hi].filter(Bt=>ot==="work"?Bt.experience==="work"||Bt.experience==="development":Bt.experience===ot).sort((Bt,Ft)=>Ft.updatedAt.localeCompare(Bt.updatedAt))[0]??[...xa].filter(Bt=>Bt.experience===ot).sort((Bt,Ft)=>Ft.updatedAt.localeCompare(Bt.updatedAt))[0]??null;if(zt)t({type:"selectSession",sessionId:zt.id,appId:ot!=="chat"?zt.appId:null,projectId:ot!=="chat"?ul[zt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),ot==="chat"&&wa==="codex"){const Bt=Oh(We?.providers,{enabledOnly:!0}).find(Ft=>Ft.value!=="codex")?.value??ir;mn(Bt),pn(gu(Bt,We?.providers)??Fl)}ot==="chat"&&(bt(!1),$t(!1),ht("home")),Xe("chat")},[t,wa,We?.providers,Hi,$t,Wt,pn,mn,ht,bt,Xe,ul,xa]),Qc=v.useCallback(ot=>{const zt=e.getSnapshot();if(Wt(ot),(Ue||ie||Se)&&(t({type:"beginNewChat",appId:null}),zt&&e.set(zt)),ot==="chat"&&wa==="codex"){const Bt=Oh(We?.providers,{enabledOnly:!0}).find(Ft=>Ft.value!=="codex")?.value??ir;mn(Bt),pn(gu(Bt,We?.providers)??Fl)}ot==="chat"&&(bt(!1),$t(!1),ht("home")),Xe("chat")},[wa,t,We?.providers,e,ie,Se,Ue,$t,Wt,pn,mn,ht,bt,Xe]),{pendingChatUserMessages:Wm,recordPendingChatUserMessage:Gm,visibleChatMessages:Jm}=Q7({chatMessages:Zc,runtimeIndexes:Bc,selectedSessionId:Ue}),vi=v.useMemo(()=>pK({selectedAppId:ie,selectedProjectId:Se,selectedSessionId:Ue}),[ie,Se,Ue]),Xc=v.useRef(null);v.useEffect(()=>{const ot=Xc.current;Xc.current=vi,!(!ot||ot.kind!=="draft"||vi.kind!=="session")&&(lc(ot,vi)||l(zt=>{const Bt=fK({tabs:zt,previousScope:ot,activeScope:vi});return Bt.some((za,Cp)=>za!==zt[Cp])?Bt:zt}))},[vi]);const Zm=v.useMemo(()=>hK(s),[s]),{goalRuntime:Ym,runningSessionIds:ml,selectedSessionRunning:Qm,sidebarGoalRuntimeBySessionId:Xm,sidebarSubagentRuntimeBySessionId:ep}=rJ({codexHistoryEvents:Mo,codexHistorySessions:yn,connection:ut,expandedProjectIds:sn,goalRuntime:Vm,locallyActiveCodexHistorySessionIds:R,pinnedSessions:dl,savedForLaterSessions:Fc,projectSessionRowsByProjectId:Wc,rightChatHistoryEvents:j,runtimeIndexes:pi,selectedSession:Sn,selectedSessionId:Ue,serverId:We?.server.id,setCodexHistorySessions:Dn,sidebarSessions:xa,subagentRuntime:Yc,visibleChatRows:Jc,visibleProjectRows:Ur}),{dragItem:tp,pinnedPreviewKeys:np,startPinnedDrag:ap,clearSidebarDrag:op,previewPinnedDrop:ip,commitPinnedDrop:rp,commitPinnedPreviewDrop:sp}=hG({connection:ut,appPreferences:Jn,sessions:xa,pinnedItems:Vc,setAppPreferences:$i,setCodexHistorySessions:Dn,setSessions:Zn,sidebarFileBookmarks:y,setSidebarFileBookmarks:w,setError:Be}),{clearTaskDrag:lp,commitTaskDrop:ed,commitTaskPreviewDrop:cp,previewTaskDrop:qa,startTaskDrag:qr,taskDragSessionId:dp,taskPreviewSessionIds:up}=gG({connection:ut,sessions:xa,setCodexHistorySessions:Dn,setError:Be,setSessions:Zn}),{commandProjectRows:mp,contextWindowStatus:pl,pinnedRows:pp,sidebarWorkspaceAppIds:fp}=H8({activeProvider:wa,contextCompaction:jo.contextCompaction,contextUsage:Fm,pinnedItems:Vc,pinnedPreviewKeys:np??[],pinnedProjects:Dm,projectRows:Kc,visibleProjectRows:Ur}),Oo=!!(la&&(we==="chat"||we==="labs")&&(Ye||N&&(X==="changes"||X==="goal"))),{workspaceStates:zr,workspaceBusy:Br,diffBusy:hp,visibleWorkspaceState:Vi,visibleWorkspaceDiff:fl,rememberWorkspaceState:Fr,refreshWorkspace:hl,refreshWorkspaceDiff:co,setWorkspaceBusy:nd}=zZ({connection:ut,activeWorkspaceAppId:la,view:we,shouldLoadWorkspaceDiff:Oo,sidebarWorkspaceAppIds:fp,setError:Be});ue.current=Fr;const gp=v.useCallback((ot=la)=>!ot||ot!==la||!Oo?Promise.resolve(null):co(ot),[co,Oo,la]),vp=v.useCallback(async(ot={})=>{!la||!Oo||await co(la,ot)},[co,Oo,la]),bp=!1,yp=!!(Sn?.provider==="codex"&&Sn.cwd&&!Io(Sn.workspaceKind)),Sp=!!(Vi&&!Vi.initialized&&ro!=="local_project"&&wa!=="codex"&&!yp&&!Mr),xp=ro==="local_project"&&!!Yn?.sandboxTemplate?.detected&&!Yn?.linkedOpenPondApp?.appId,[ad,od]=v.useState(null),[kp,wp]=v.useState(null),{projectTarget:Ip,workspaceTarget:_p}=C8({accountPending:Pr,accountSignedOut:Ar,activeWorkspaceLocation:zi,bootstrap:We,busy:L,cloudLinked:Er,selectedCloudProject:Eo,selectedProject:Yn,selectedSession:Sn,pendingWorkspaceTarget:ad,workspaceStates:zr,workspaceBusy:Br});return v.useEffect(()=>{od(null)},[Sn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:o,setPendingTerminalCommand:r,terminalTabs:s,setTerminalTabs:l,trainingDetailTasksetId:m,setTrainingDetailTasksetId:d,mentionedAppId:h,setMentionedAppId:g,cloudSetupDialog:_,setCloudSetupDialog:P,rightPanelTabRequest:M,setRightPanelTabRequest:C,workspaceDiffPanelViewState:$,setWorkspaceDiffPanelViewState:O,rightChatHistoryEvents:j,setRightChatHistoryEvents:x,locallyActiveCodexHistorySessionIds:R,setCodexHistoryTurnLocallyActive:H,mainComposerFocusRequestId:B,requestMainComposerFocus:Fi,draftSubagentDelegationMode:J,setDraftSubagentDelegationMode:le,confirmProjectAction:je,projectConfirmDialog:ke,resolveProjectConfirmDialog:te,query:Me,searchOpen:ye,archivedChatsOpen:ne,sectionMenuOpen:be,projectsExpanded:ae,cloudProjectsExpanded:de,sidebarOpen:De,view:we,selectedAppId:ie,selectedProjectId:Se,selectedSessionId:Ue,draftProvider:Je,draftModel:Ke,draftExperience:tt,activeExperience:Ua,changeExperience:Km,changeNewExperience:Qc,codexPermissionMode:ze,codexReasoningEffort:Ge,openPondCommandAccessMode:qe,busy:L,diffPanelOpen:N,diffPanelExpanded:q,rightPanelMode:X,rightChatPanels:me,terminalOpen:$e,settingsSection:Le,newProjectDialogOpen:nt,newProjectMode:at,newProjectName:lt,newProjectPath:pt,newProjectBusy:Oe,commitDialogOpen:Ye,commitMessage:f,commitIncludeUnstaged:U,commitNextStep:Y,commitDraft:he,branchDialogOpen:re,branchDialogName:W,toast:I,error:K,labDetailNavigation:ee,setQuery:Z,setSearchOpen:ce,setArchivedChatsOpen:pe,setSectionMenuOpen:fe,setProjectsExpanded:Ae,setCloudProjectsExpanded:_e,setChatRowsVisibleCount:Ne,setSidebarOpen:Pe,setView:Xe,setSelectedAppId:st,setSelectedProjectId:rn,setSelectedSessionId:Et,setPrompt:tn,setDraftProvider:mn,setDraftModel:pn,setDraftExperience:Wt,setDiffPanelOpen:Pn,setDiffPanelExpanded:$t,setRightPanelMode:ht,setRightChatPanels:fn,setTerminalOpen:bt,setSyncingWorkspaceAppId:jt,setSettingsSection:va,setNewProjectDialogOpen:Ut,setNewProjectMode:hn,setNewProjectName:it,setNewProjectPath:Cn,setNewProjectBusy:ao,setCommitDialogOpen:oo,setCommitMessage:ra,setCommitIncludeUnstaged:ba,setCommitNextStep:Nn,setCommitDraft:Po,setBranchDialogOpen:La,setBranchDialogName:V,setError:Be,showToast:yt,appPreferences:Jn,applyBootstrapPayload:gn,approvals:ri,bootstrap:We,connection:ut,events:An,runtimeEventStore:Ha,sessions:ya,startup:si,setAppPreferences:$i,setCodexHistorySessions:Dn,setEvents:Sa,setSessions:Zn,training:xt,pinnedCollapsed:Bs,projectsCollapsed:Di,cloudProjectsCollapsed:Fs,chatsCollapsed:Sr,savedForLaterCollapsed:Vs,sidebarWidth:To,sidebarResizing:Ks,diffPanelWidth:xr,diffPanelResizing:kr,togglePinnedCollapsed:wr,toggleProjectsCollapsed:Ws,toggleCloudProjectsCollapsed:Gs,toggleChatsCollapsed:io,toggleSavedForLaterCollapsed:Js,startSidebarResize:Ir,startDiffPanelResize:_r,cloudProjectById:ui,localProjectById:sa,selectedApp:Li,selectedCloudProject:Eo,selectedProject:Yn,selectedProjectLinkedApp:Ys,selectedProjectLinkedOpenPondApp:Qs,selectedSession:Sn,sidebarSessions:xa,runtimeIndexes:pi,chatMentionApps:Xs,connectedAppMentions:Rr,pendingApproval:Ui,codexHistoryEvents:Mo,setCodexHistoryEvents:fi,account:hi,accountPending:Pr,accountSignedOut:Ar,activeModel:ka,activeProvider:wa,activeWorkspaceAppId:Tr,activeWorkspaceId:qi,activeWorkspaceKind:ro,activeWorkspaceLocation:zi,appDefaults:jo,selectedSessionProjectId:jr,startMessage:el,workspaceName:Or,accountScopeKey:$r,organizations:gi,teamChatOrganization:Nr,teamChatTeamId:Bi,teamChat:so,publishTeamProfileAgent:nl,communities:al,communitySidebar:ol,communityView:il,teamAiThreadId:lo,toggleTeamAiSidebar:rl,selectedProjectConfirmedCloudProject:sl,activeOpenPondCommandAccessMode:ll,viewWorkspaceAppId:la,viewWorkspaceId:Lr,viewWorkspaceKind:cl,viewWorkspaceName:ct,openPondActionCatalog:Yt,selectedActionCatalog:Qn,expandedProjectIds:sn,expandProject:Tn,toggleProjectExpanded:ca,setExpandedProjectIds:xm,changeCodexPermissionMode:km,changeCodexReasoningEffort:wm,changeOpenPondCommandAccessMode:qc,resolveApproval:Im,beginNewChat:zc,advanceTrainingModelChatAfterTurn:_m,beginNewChatWithTrainingModel:Cm,bindTrainingModelChatSession:Rm,dismissTrainingChatHandoff:Pm,trainingChatHandoff:Am,prepareTrainingModelChatTurn:Tm,selectTrainingChatTaskForComposer:Em,chatHistoryLoadStates:Mm,loadMoreSelectedChatHistory:jm,selectedPagedSessionEvents:Om,activeSessions:$m,archivedSessions:Nm,pinnedSessions:dl,savedForLaterSessions:Fc,pinnedFiles:Lm,savedForLaterFiles:Hm,sidebarFileBookmarks:y,setSidebarFileStatus:ci,projectRows:Kc,localProjectRows:Um,visibleProjectRows:Ur,cloudProjectRows:qm,projectSessionRowsByProjectId:Wc,childSessionRowsByParentId:zm,sidebarProjectIdBySessionId:ul,chatRows:Gc,visibleChatRows:Jc,chatRowsVisibleCount:xe,sessionEvents:Bm,chatMessages:Zc,goalRuntime:Ym,subagentRuntime:Yc,pendingChatUserMessages:Wm,recordPendingChatUserMessage:Gm,visibleChatMessages:Jm,activeTerminalScope:vi,terminalSummaries:Zm,runningSessionIds:ml,selectedSessionRunning:Qm,sidebarGoalRuntimeBySessionId:Xm,sidebarSubagentRuntimeBySessionId:ep,taskDragSessionId:dp,taskPreviewSessionIds:up,startTaskDrag:qr,clearTaskDrag:lp,previewTaskDrop:qa,commitTaskDrop:ed,commitTaskPreviewDrop:cp,dragItem:tp,startPinnedDrag:ap,clearSidebarDrag:op,previewPinnedDrop:ip,commitPinnedDrop:rp,commitPinnedPreviewDrop:sp,commandProjectRows:mp,contextWindowStatus:pl,pinnedRows:pp,workspaceStates:zr,workspaceBusy:Br,diffBusy:hp,visibleWorkspaceState:Vi,visibleWorkspaceDiff:fl,rememberWorkspaceState:Fr,refreshWorkspace:hl,refreshWorkspaceDiff:co,setWorkspaceBusy:nd,refreshWorkspaceDiffWhenNeeded:gp,refreshVisibleWorkspaceDiff:vp,managedWorkspace:bp,canSyncActiveWorkspace:Sp,canPublishOpenPondProject:xp,pendingWorkspaceTarget:ad,setPendingWorkspaceTarget:od,pendingSidebarWorkspaceTarget:kp,setPendingSidebarWorkspaceTarget:wp,projectTarget:Ip,workspaceTarget:_p}}const UY=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,qY=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function zY(e,t={}){const n=e.trim().replace(/^['"`]+|['"`]+$/g,"");if(!n||/\s/.test(n))return null;const a=n.toLowerCase();return a.startsWith("javascript:")||a.startsWith("data:")?null:/^https?:\/\//i.test(n)?Cd(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?Cd(n,new Set(["file:"])):null:UY.test(n)?Cd(`http://${n}`,new Set(["http:"])):qY.test(n)?Cd(`https://${n}`,new Set(["https:"])):null}function Cd(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function BY(e){const t=zY(e.href,{explicitFile:e.explicitFile});if(!t)return!1;const n=window.openpond?.browser;return n?(e.newTab?await n.newTab({conversationId:e.conversationId,url:t,explicitFile:e.explicitFile}):await n.open({conversationId:e.conversationId,url:t,explicitFile:e.explicitFile}),!0):(window.open(t,"_blank","noopener,noreferrer"),!0)}const FY="openpond-coding-core-v1",VY="feature";function Yh(e){const t=new URL("/sandboxes",Ib(e.accountBaseUrl));return t.searchParams.set("teamId",e.teamId),t.searchParams.set("create","sandbox"),t.searchParams.set("intent","cloud-coding"),t.searchParams.set("source",e.source),t.searchParams.set("projectId",e.projectId),t.searchParams.set("workflowMode",VY),t.searchParams.set("runtimeProfileId",FY),e.projectName?.trim()&&t.searchParams.set("projectName",e.projectName.trim()),e.baseBranch?.trim()&&t.searchParams.set("baseBranch",e.baseBranch.trim()),e.localProjectId?.trim()&&t.searchParams.set("localProjectId",e.localProjectId.trim()),t.toString()}function Tte(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Ib(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function hx(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Ib(e.accountBaseUrl)).toString()}function Ib(e){const t=e?.trim();if(!t)return"https://openpond.ai";try{const n=new URL(t);return`${n.protocol}//${n.host}`}catch{return"https://openpond.ai"}}function KY({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:o,rightPanelMode:r,selectedProjectId:s,setDiffPanelOpen:l,setNewProjectDialogOpen:m,setNewProjectMode:d,setNewProjectName:h,setRightPanelMode:g}){const y=v.useCallback(()=>{g("changes"),l(!0)},[l,g]),w=v.useCallback(()=>{if(o&&r==="changes"){l(!1);return}y()},[o,r,l,y]),_=v.useCallback(()=>{g("browser"),l(!0)},[l,g]),P=v.useCallback(()=>{g("goal"),l(!0)},[l,g]),M=v.useCallback((j,x)=>{BY({conversationId:t,href:j,explicitFile:x?.explicitFile,newTab:x?.newTab}).then(R=>{R&&_()})},[t,_]),C=v.useCallback(()=>{d("cloud"),h(""),m(!0)},[m,d,h]),$=v.useCallback(j=>{const x=n.get(j);x&&M(Yh({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:x.teamId,projectId:x.id,projectName:x.name,baseBranch:x.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,M]);return{createCloudEnvironmentFromSidebar:v.useCallback(()=>{const j=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(j){$(j);return}C()},[a,C,s,$]),openCloudProjectDialog:C,openUrlInBrowserPanel:M,showBrowserPanel:_,showChangesPanel:y,showGoalSidebarTab:P,toggleChangesPanel:w}}function WY(e){const t=e.requestConversationId.trim();return t?t===e.currentConversationId?{reveal:!0,sessionIdToOpen:null}:new Set(e.sessionIds).has(t)?{reveal:!0,sessionIdToOpen:t}:{reveal:!1,sessionIdToOpen:null}:{reveal:!1,sessionIdToOpen:null}}function GY({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){v.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(r=>{const s=WY({currentConversationId:e,requestConversationId:r.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const JY="chat",ZY=["help me","please","can you","could you","make","create","build"],YY=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function gx(e){const t=Wf(e.label);if(t&&!Qh(t))return vx(t);const n=Wf(e.name);if(n&&!Qh(n))return vx(n);const a=Wf(e.actionId)?.replace(/\.chat$/i,"")??"";return QY(a||t||"Profile Agent")}function Qh(e){return e.trim().toLowerCase()===JY}function QY(e){const t=XY(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(o=>o.replace(/[^a-z0-9]/g,"")).filter(o=>o&&!YY.has(o)).slice(0,3);return fP(a.length?a.join(" "):t||e)}function vx(e){return fP(e).split(/\s+/).slice(0,4).join(" ")}function XY(e){let t=e.trim();for(const n of ZY)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function Wf(e){return typeof e=="string"&&e.trim()?e.trim():null}function fP(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const eQ="openpond-profile-action";function tQ(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Rd(e){return typeof e=="string"&&e.trim()?e.trim():null}function nQ(e){const t=tQ(e.implementation);if(t?.type!==eQ)return null;const n=Rd(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=Rd(e.label);if(a&&!Qh(a))return gx({label:a,description:e.description});const o=Rd(t.agentName)??Rd(e.name);return gx({actionId:n,description:e.description,name:o})}function aQ(e){const t=nQ(e);return t||e.label?.trim()||e.name?.trim()||e.id}function hP(e){const t=typeof e.implementation?.type=="string"?e.implementation.type:null;return t==="openpond-agent"?"OpenPond Agent":t==="openpond-profile-action"&&(e.sourceActionId==="chat"||e.id==="chat"||e.id.endsWith(".chat"))?"Profile agent":t==="workflow"?"Workflow-backed action":t==="agent"?"Agent-backed action":t==="remote-agent"?"Remote-agent action":t==="chat"||t==="intent-router"?"Chat action":e.id}const oQ=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function gP(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ms(e){return typeof e=="string"&&e.trim()?e.trim():null}function ms(e,t,n={}){const a=Ms(t)?Un(String(t)):"";a&&(!n.generic&&oQ.has(a)||e.add(a))}function Pd(e,t){const n=Ms(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))ms(e,a)}function iQ(e,t){const n=Ms(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||ms(e,a)}function vP(e){const t=new Set,n=gP(e.implementation),a=Ms(n?.actionId);return ms(t,e.id,{generic:!0}),Pd(t,e.id),ms(t,a,{generic:!0}),Pd(t,a),ms(t,e.name,{generic:!0}),Pd(t,e.name),ms(t,e.label,{generic:!0}),Pd(t,e.label),iQ(t,e.description),t}function rQ(e){const t=gP(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",Ms(t?.actionId)??"",Ms(t?.agentName)??"",hP(e),...Array.from(vP(e))].join(" ").toLowerCase()}function Ete(e,t,n=8){const a=Un(t);return e.length===0?[]:e.filter(o=>a?rQ(o).includes(a):!0).slice(0,n)}function sQ(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function lQ(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function cQ(e,t){const n=sQ(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const r of n)for(const s of t)vP(s).has(r)&&a.set(s.id,{action:s,mention:r});if(a.size!==1)return null;const o=Array.from(a.values())[0];return{action:o.action,mention:o.mention,prompt:lQ(e,o.mention)}}function Mte(e){return aQ(e)}function jte(e){return e.description||hP(e)}const _b=[{id:"agent",command:"/agent",label:"Author Agent",description:"Create or improve a Profile Agent in a normal skill-backed turn.",subcommands:["create","improve","help"]},{id:"skill",command:"/skill",label:"Manage skills",description:"Create, edit, and use reusable skills for the selected provider.",subcommands:["create","edit","list","help"]},{id:"goal",command:"/goal",label:"Codex goal",description:"Use Codex-native Goal mode."},{id:"workflow",command:"/workflow",label:"Schedule workflow",description:"Create a recurring prompt that posts each run back into this chat."},{id:"submit-issue",command:"/submit-issue",label:"Submit issue",description:"File a GitHub issue in openpond/openpond through the connected GitHub app."},{id:"train",command:"/train",label:"Create training task",description:"Create a training plan from this chat or select chats in Training."},{id:"sync-cloud",command:"/sync-cloud",label:"Upload/sync to Cloud",description:"Start a chat-visible source upload for the selected Project."}];function dQ(e){return _b.filter(t=>t.id!=="goal"||e==="codex")}function bP(e,t){return t==="work"?e.id==="submit-issue"||e.id==="workflow":t==="development"?e.id!=="workflow":t==="chat"?e.id!=="sync-cloud":!0}function Ote(e,t){return dQ(e).filter(n=>bP(n,t))}const uQ=new Set(_b.map(e=>e.id));function $te(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function mQ(e){return[e.id,e.command,e.label,e.description].join(" ")}function pQ(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function fQ(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return uQ.has(n)?{command:n,args:t[2]?.trim()??""}:null}function hQ(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function Nte({commands:e=_b,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const o=e.filter(l=>l.id.startsWith(a));if(o.length>0)return o.slice(0,n);const r=e.filter(l=>mQ(l).toLowerCase().includes(a));return(r.length>0?r:e.filter(l=>pQ(l).toLowerCase().includes(a))).slice(0,n)}function Dte(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function ym(e){return e?.role==="owner"||e?.role==="admin"}function Lte(e){const t=Sm(e.organizations,e.defaultTeamId),n=ym(t),a=e.localProject??null;if(!a)return gQ("Open a local project to set up an Agent.");const o=vQ(a,e.projects),r=bQ(a,o,e.agents),s=!!a.sandboxTemplate?.detected,l=t&&!n?"Ask an owner or admin to connect this project.":null;return s?o?yQ(a,o)?Ad({state:"needs_sync",actionLabel:"Sync Project",project:o,agent:r,canManage:n,actionBlockedReason:l}):r?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:o,agent:r}:Ad({state:"needs_agent",actionLabel:"Create Agent",project:o,agent:null,canManage:n,actionBlockedReason:l}):Ad({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:l}):Ad({state:"missing_config",actionLabel:"Add Agent config",project:o,agent:r,canManage:n,actionBlockedReason:l})}function Ad(e){return e.canManage?{state:e.state,actionLabel:e.actionLabel,canAct:!0,reason:null,project:e.project,agent:e.agent}:{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e.actionBlockedReason,project:e.project,agent:e.agent}}function gQ(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function Sm(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(o=>o.teamId===n);if(a)return a}return e.length===1?e[0]??null:e.find(a=>a.role==="owner")??e.find(a=>a.role==="admin")??e[0]??null}function vQ(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function bQ(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const o=n.find(r=>r.id===a&&r.projectId===t.id);if(o)return o}return n.find(o=>o.projectId===t.id)??null}function yQ(e,t){if(t.sandboxManifestError||!t.sandboxManifestSyncedAt||!t.sandboxManifestHash)return!0;if(e.sandboxTemplate?.manifestHash&&t.sandboxManifestHash)return e.sandboxTemplate.manifestHash!==t.sandboxManifestHash;if(e.linkedSandboxProject?.manifestHash&&t.sandboxManifestHash)return e.linkedSandboxProject.manifestHash!==t.sandboxManifestHash;const n=e.sandboxTemplate?.manifestPath;return n&&t.sandboxManifestPath?!n.endsWith(t.sandboxManifestPath):!1}const Ki=e=>e.slice(0,2e4);function SQ({model:e,provider:t,providerSettings:n}){return{model:ib(t,e,n),modelRef:Fa(t,e,n)}}function xQ(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function kQ(e,t){const n=new Date().toISOString(),a=`codex_history_optimistic_${n}_${Math.random().toString(36).slice(2,8)}`;return{id:a,sessionId:e,turnId:`${a}_turn`,name:"turn.started",timestamp:n,source:"chat_action",args:{prompt:t},status:"started"}}function wQ(e,t){return{id:`${e.id}_failed`,sessionId:e.sessionId,turnId:e.turnId,name:"turn.failed",timestamp:new Date().toISOString(),source:"server",status:"failed",error:t instanceof Error?t.message:String(t)}}function bx({action:e,prompt:t,runPayload:n,sessionId:a}){const o=new Date().toISOString(),r=`openpond_action_${n.run.id}`,s=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${r}_user`,sessionId:a,turnId:r,name:"turn.started",timestamp:o,source:"chat_action",args:{prompt:t}},{id:`${r}_result`,sessionId:a,turnId:r,name:"workspace_action_result",timestamp:n.run.updatedAt??o,source:"chat_action",action:"sandbox_run_action",appId:null,status:s,output:s==="completed"?`Ran ${e.label??e.name??e.id}`:`Started ${e.label??e.name??e.id}`,data:{openPondActionRun:!0,action:{name:e.id,label:e.label??e.name??e.id,implementation:e.implementation},agent:n.agent,run:n.run,sandbox:n.sandbox??null,actionSummary:n.run.actionSummary??null,responseSummary:n.run.responseSummary??null,traceSummary:n.run.traceSummary??null,evalSummary:n.run.evalSummary??null,sourceSummary:n.run.sourceSummary??null}}]}function IQ({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:o,draftModel:r,draftProvider:s,experience:l,expandProject:m,ensureCloudSessionReady:d,getPrompt:h,bootstrap:g,chatMessages:y,apps:w,connectedAppMentions:_,mentionedAppId:P,refreshWorkspace:M,refreshWorkspaceDiff:C,selectedApp:$,selectedActionCatalog:O,openPondActionCatalog:j,cloudProjects:x,accountScopeKey:R,selectedCloudProject:E,selectedProject:H,selectedProjectLinkedOpenPondApp:B,selectedSession:D,workspaceTarget:J,subagentDelegationMode:le,setDraftModel:ue,setDraftProvider:je,setError:ke,setPrompt:te,setMentionedAppId:Me,setCodexHistoryEvents:ye,setCodexHistorySessions:ne,onCodexHistoryTurnActivityChange:be,onCodexHistoryTurnPayload:ae,onPendingUserMessage:de,setEvents:xe,setSelectedAppId:De,setSelectedProjectId:we,setSelectedSessionId:ie,setSessions:Se,setView:Ue,setWorkspaceBusy:Je}){function Ke(W){Q.bootstrap(W).then(e).catch(I=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",I);const K=I instanceof Error?I.message:String(I);ke(`Message sent, but the chat list could not refresh: ${K}`)})}const tt=v.useRef(new Set),ze=g?.providers??null;function Ge(W,I){return W==="codex"?void 0:I}function qe(W){return!!(W&&W.provider!=="codex"&&(W.workspaceKind==="local_project"&&W.cwd?.trim()||(W.workspaceKind==="sandbox"||W.workspaceKind==="sandbox_template"||W.workspaceKind==="sandbox_app")&&W.workspaceId))}function L(W){je(W),ue(I=>ji(W,I,ze)),Ue("chat")}async function N(W,I){return(QR(I,R)??await bb({teamId:I,accountKey:R,fetchAgents:async Z=>(await Q.listSandboxAgents(t,{teamId:Z})).agents})).find(Z=>Z.projectId===W)??null}async function q(){if(!t)throw new Error("OpenPond App server is not connected.");if(g?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const W=await Q.organizations(t),I=Sm(W.organizations.map(fm).filter(K=>!!K).filter(K=>K.status==="active"),g?.preferences.defaultTeamId??null);if(!I)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!ym(I))throw new Error(`You need owner or admin access to create projects in ${I.displayName}.`);return I}async function X(W){if(!t)return!1;const I=H;if(!I)throw new Error("Select a local Project before using /sync-cloud.");const K=await q(),ee=I.linkedSandboxProject?.defaultBranch?.trim()||"main",Z=St("local",I.id),ce=Oa(I,x),pe=await Q.createSession(t,{provider:"openpond",modelRef:Fa("openpond",ks,ze),openPondCommandAccessMode:Ge("openpond",o),appId:null,appName:null,workspaceKind:"local_project",workspaceId:I.id,workspaceName:I.name,localProjectId:I.id,cloudProjectId:ce?.id??null,cloudTeamId:ce?.teamId??null,cwd:I.workspacePath,title:`Sync ${I.name} to Cloud`});Se(fe=>[pe,...fe]),W.onSessionCreated?.(pe),W.selectSession&&(ie(pe.id),we(Z),De(null),Ue("chat"),m(Z)),W.clearPromptForTurn(),Je(!0);try{const fe=await Q.uploadLocalProjectCloudSource(t,I.id,{teamId:K.teamId,projectName:I.name,branch:ee,chatSessionId:pe.id,displayPrompt:W.displayPrompt});return e(fe.bootstrap),m(Z),m(St("cloud",fe.project.id)),!0}catch(fe){const Ae=await Q.bootstrap(t).catch(()=>null);throw Ae&&e(Ae),fe}finally{Je(!1)}}async function me(W){if(!t||W.providerForTurn==="codex"||W.selectedSessionForTurn?.provider==="codex")return!1;let I=qe(W.selectedSessionForTurn)?W.selectedSessionForTurn:null;if(!I&&W.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!I)if(E){const ee=St("cloud",E.id),Z=W.providerForTurn;I=await Q.createSession(t,{provider:Z,modelRef:Fa(Z,W.modelForTurnValue,ze),openPondCommandAccessMode:Ge(Z,W.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:E.id,workspaceName:E.name,localProjectId:null,cloudProjectId:E.id,cloudTeamId:E.teamId,cwd:null,autoTitlePrompt:Ki(W.command)}),Se(ce=>[I,...ce]),W.onSessionCreated?.(I),W.selectSession&&(ie(I.id),we(ee),De(null),Ue("chat"),m(ee))}else{const ee=H;if(!ee)throw new Error("Select a project to use this.");const Z=Oa(ee,x),ce=St("local",ee.id),pe=W.providerForTurn;I=await Q.createSession(t,{provider:pe,modelRef:Fa(pe,W.modelForTurnValue,ze),openPondCommandAccessMode:Ge(pe,W.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:ee.id,workspaceName:ee.name,localProjectId:ee.id,cloudProjectId:Z?.id??null,cloudTeamId:Z?.teamId??null,cwd:ee.workspacePath,autoTitlePrompt:Ki(W.command)}),Se(fe=>[I,...fe]),W.onSessionCreated?.(I),W.selectSession&&(ie(I.id),we(ce),De(null),Ue("chat"),m(ce))}if(!I)throw new Error("Select a project to use this.");W.clearPromptForTurn();const K=await Q.runSessionCommand(t,I.id,{command:W.command,cwd:I.cwd});return Se(ee=>Al(ee,K.session)),xe(ee=>qo(ee,K.events)),!0}async function $e(W=[],I=null,K,ee={}){const Z=K??h();let ce=Z.trim()||(W.length>0?"Please review the attached files.":"");if(!t||!ce)return!1;const pe=ee.displayPrompt?.trim()||ce,fe=ee.provider??s,Ae=ee.model??r,_e=ee.openPondCommandAccessMode??o,Ne=ee.session!==void 0,Pe=Ne?ee.session??null:D,Xe=ee.experience??Pe?.experience??l,st=Xe==="development"||Xe==="work"&&(Pe?.workspaceKind==="local_project"||!!Pe?.localProjectId||!!Pe?.cloudProjectId||!Ne&&!!(H||E||$||J==="hybrid"||J==="local")),rn=Ne||!st?null:$,Et=Ne||!st?null:H,tn=Ne||!st?null:E,mn=Ne||!st?null:B,pn=!Ne&&st&&J==="hybrid",Wt=ee.selectSession??!0,Da=ee.chatMessages??y,ga=ee.session!==void 0?null:P,$n=ee.clearPrompt===void 0?()=>{te(""),Me(null)}:ee.clearPrompt,Pn=I?null:cQ(ce,O),$t=I??Pn?.action??null,ht=Pn?.prompt||ce,fn=st&&!$t?hQ(ce):null,bt=$t||fn?null:fQ(ce),jt=bt&&!bP({id:bt.command},Xe)?bt:null,va=ee.usageAttribution??(bt?{surface:"chat",workflowKind:"slash_command",commandName:`/${bt.command}`,commandSource:"prompt_parse"}:void 0);ke(null);let Ut=null,hn=null;try{if(!st&&fe==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(jt)throw new Error(`/${jt.command} isn't available in ${Xe}.`);if(fn&&fe!=="codex"&&Pe?.provider!=="codex"){if(W.length>0)throw new Error("Direct commands do not accept attachments.");return await me({command:fn.command,clearPromptForTurn:$n,modelForTurnValue:Ae,onSessionCreated:ee.onSessionCreated,openPondCommandAccessModeForTurn:_e,providerForTurn:fe,selectedSessionForTurn:Pe,selectSession:Wt})}if(!Ne&&bt?.command==="sync-cloud")return await X({clearPromptForTurn:$n,displayPrompt:pe,onSessionCreated:ee.onSessionCreated,selectSession:Wt});if($t){const V=AZ($t);if(V){let We=Pe;if(!We||We.cloudProjectId!==V.projectId){We=await Q.createSession(t,{provider:"openpond",modelRef:Fa("openpond",Ae,ze),openPondCommandAccessMode:Ge("openpond",_e),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:V.projectId,workspaceName:V.projectName??V.agentName,localProjectId:null,cloudProjectId:V.projectId,cloudTeamId:V.teamId,cwd:null,autoTitlePrompt:Ki(pe)}),Se(Ha=>[We,...Ha]),ee.onSessionCreated?.(We),Wt&&ie(We.id);const An=St("cloud",V.projectId);Wt&&we(An),Wt&&m(An)}const yn=await Q.runSandboxAgent(t,V.agentId,OZ({agent:V,attachments:W,displayPrompt:pe,prompt:ht})),ut=await Q.bootstrap(t);return e(ut),$n(),xe(An=>qo(An,bx({action:$t,prompt:pe,runPayload:yn,sessionId:We.id}))),!0}const He=kb($t);if(He){let We=Pe;(!We||We.provider!=="openpond")&&(We=await Q.createSession(t,{provider:"openpond",modelRef:Fa("openpond",Ae,ze),openPondCommandAccessMode:Ge("openpond",_e),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:Ki(pe)}),Se(ut=>[We,...ut]),ee.onSessionCreated?.(We),Wt&&ie(We.id)),await Q.runProfileAction(t,MZ({action:He,attachments:W,displayPrompt:pe,prompt:ht,sessionId:We.id}));const yn=await Q.bootstrap(t);return e(yn),$n(),!0}const Ie=oP({cloudProjects:x,selectedCloudProject:E,selectedProject:H});if(!Ie)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let Be=Pe;(!Be||Be.cloudProjectId!==Ie.id)&&(Be=await Q.createSession(t,{provider:"openpond",modelRef:Fa("openpond",Ae,ze),openPondCommandAccessMode:Ge("openpond",_e),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:Ie.id,workspaceName:Ie.name,localProjectId:Ie.localProjectId,cloudProjectId:Ie.id,cloudTeamId:Ie.teamId,cwd:null,autoTitlePrompt:Ki(pe)}),Se(We=>[Be,...We]),ee.onSessionCreated?.(Be),Wt&&(ie(Be.id),we(Ie.selectionKey),m(Ie.selectionKey)));const yt=await N(Ie.id,Ie.teamId);if(!yt)throw new Error("No OpenPond Agent is available for this Project.");$n();const Jn=await Q.runSandboxAgent(t,yt.id,jZ({action:$t,attachments:W,displayPrompt:pe,prompt:ht,teamId:Ie.teamId})),gn=await Q.bootstrap(t);return e(gn),xe(We=>qo(We,bx({action:$t,prompt:pe,runPayload:Jn,sessionId:Be.id}))),!0}let it=Pe;if(it&&qt(it.id)){hn=AS({afterMessageId:Da.at(-1)?.id??null,attachments:W,content:ce,sessionId:it.id}),$n(),Ut=it.id,tt.current.add(Ut),de?.(hn),be?.(Ut,!0);const V=kQ(it.id,ce),He=Be=>{(!Ne||D?.id===it.id)&&ye(yt=>xQ(yt,Be)),ee.onCodexHistoryOptimisticEvent?.(Be)};He(V),ne(Be=>Be.map(yt=>yt.id===it.id?{...yt,status:"active"}:yt));const Ie=await Q.sendCodexHistoryTurn(t,it.id,{prompt:ce,attachments:W.length>0?W:void 0,model:ib("codex",Ae,ze),modelRef:Fa("codex",Ae,ze),...V0(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(Be=>{throw He(wQ(V,Be)),Be});return(!Ne||D?.id===it.id)&&ye(Be=>qo(Be,Ie.events)),ne(Be=>Al(Be,Ie.session)),ae?.(Ie),Ke(t),!0}const ao=(ga?w.find(V=>V.id===ga&&R8(Z,V)&&V.sandbox)??null:null)??P8(Z,kR(w)),oo=Xe==="chat"?[]:B8(Z,_).map(V=>V.ref);if(!it){const V=mn?.appId??rn?.id??null,He=mn?.appName??rn?.name??null,Ie=tn,Be=Ne?null:Oa(Et,x),yt=pn?gR({cloudProjects:x,selectedCloudProject:Ie,selectedProject:Et}):null;if(yt?.kind==="missing_cloud_project")throw new Error(yt.message);const Jn=yt?.kind==="ready",gn=Jn?fe:Ie?"openpond":fe,We=Fa(gn,Ae,ze),yn=Ge(gn,_e),ut=Jn?vR({modelRef:We,provider:gn,target:yt,title:ce.slice(0,64)}):null;it=await Q.createSession(t,ut?{...ut,subagentDelegationMode:le,metadata:{...ut.metadata,...ee.sessionMetadata??{}},...yn?{openPondCommandAccessMode:yn}:{},autoTitlePrompt:Ki(ce)}:{experience:Xe,provider:gn,modelRef:We,subagentDelegationMode:le,...yn?{openPondCommandAccessMode:yn}:{},appId:V,appName:He,workspaceKind:Ie?"sandbox":Et?"local_project":rn?"sandbox_app":void 0,workspaceId:Et?.id??(rn?V:void 0),workspaceName:Ie?.name??Et?.name??He,localProjectId:Et?.id??null,cloudProjectId:Ie?.id??Be?.id??null,cloudTeamId:Ie?.teamId??Be?.teamId??null,...!Ie&&!Et&&!rn&&J==="local"?{metadata:{...r8(),...ee.sessionMetadata??{}}}:{cwd:Et?Et.workspacePath:null,...ee.sessionMetadata?{metadata:ee.sessionMetadata}:{}},autoTitlePrompt:Ki(ce)}),Se(An=>[it,...An]),ee.onSessionCreated?.(it),Wt&&(ie(it.id),Ie&&we(St("cloud",Ie.id)),it.workspaceKind==="local_project"&&it.workspaceId&&m(St("local",it.workspaceId)),Ie&&m(St("cloud",Ie.id)))}if(yx(it)&&Io(it.workspaceKind)&&it.provider!=="openpond"&&!_o(it))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(yx(it)&&Io(it.workspaceKind)&&d)try{it=await d(it)}catch(V){const He=V instanceof Error?V.message:String(V);throw await Q.recordPreflightTurnFailure(t,it.id,{prompt:ce,error:He,target:_o(it)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),V}hn=AS({afterMessageId:Da.at(-1)?.id??null,attachments:W,content:ce,sessionId:it.id}),$n(),Ut=it.id,tt.current.add(Ut),de?.(hn),Se(V=>V.map(He=>He.id===Ut?{...He,status:"active"}:He));const ra=fe,ba=SQ({provider:ra,model:Ae,providerSettings:ze}),Nn=eK(ra,ba.model??Ae,ze),Po=ra==="codex"?V0(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await Q.sendTurn(t,it.id,{prompt:ce,metadata:ee.turnMetadata,attachments:W.length>0?W:void 0,mentionedAppIds:ao?[ao.id]:void 0,mentionedConnectedApps:oo.length>0?oo:void 0,openPondActionCatalog:j.length>0?j:void 0,usageAttribution:va,...ba,...Po,codexPermissionMode:ra==="codex"?n:"default",codexReasoningEffort:Nn?XV(ra,ba.model??Ae,a,ze):void 0}),Ke(t);const La=it.workspaceId??it.appId;return La&&it.workspaceKind!=="sandbox"&&it.workspaceKind!=="sandbox_template"&&M(La,!1).then(V=>{V?.initialized&&C(La)}),!0}catch(it){return ke(it instanceof Error?it.message:String(it)),!1}finally{Ut&&tt.current.delete(Ut),Ut&&qt(Ut)&&be?.(Ut,!1),Ut&&(qt(Ut)?ne(it=>it.map(Cn=>Cn.id===Ut&&Cn.status==="active"?{...Cn,status:"idle"}:Cn)):Se(it=>it.map(Cn=>Cn.id===Ut&&Cn.status==="active"?{...Cn,status:"idle"}:Cn)))}}async function Le(W,I){const K=tt.current.values().next().value??null,ee=W??D?.id??K;if(!t||!ee)return!1;if(ke(null),qt(ee))try{const Z=await Q.interruptCodexHistoryTurn(t,ee);if(!Z.interrupted){if(Z.reason==="no_active_openpond_turn"){const pe=await Q.codexHistoryThread(t,ee,{tail:!0}),fe={...pe.session,status:"idle"};return D?.id===ee&&ye(Ae=>qo(Ae,pe.events)),ne(Ae=>Al(Ae,fe)),ke("OpenPond no longer has a live interrupt handle for this Codex history turn. The chat was marked idle so you can send again."),!0}return ke("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const ce=await Q.codexHistoryThread(t,ee,{tail:!0});return D?.id===ee&&ye(pe=>qo(pe,ce.events)),ne(pe=>Al(pe,ce.session)),!0}catch(Z){const ce=Z instanceof Error?Z.message:String(Z);return ke(ce==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":ce),!1}try{await Q.interruptTurn(t,ee,I);const Z=await Q.bootstrap(t);return e(Z),!0}catch(Z){return ke(Z instanceof Error?Z.message:String(Z)),!1}}async function nt(W,I){if(!t){ke("OpenPond App server is not connected.");return}ke(null),await Q.applyCreateImproveAction(t,W.id,{...I,runId:W.id,expectedRevision:W.revision,actionId:`web:${I.type}:${crypto.randomUUID()}`});const K=await Q.bootstrap(t);e(K)}async function at(W){await nt(W.run,{type:"approve_plan"})}async function lt(W){await nt(W.run,{type:"cancel",reason:null})}async function pt(W,I){await nt(W.run,{type:"revise_plan",revision:I})}async function Oe(W,I,K){await nt(W.run,{type:"answer_question",questionId:I,value:K})}async function Ye(W){await nt(W.run,{type:"pause"})}async function f(W){await nt(W.run,{type:"resume"})}async function U(W,I){await nt(W.run,{type:"open_pull_request",candidateId:I})}async function Y(W,I){await nt(W.run,{type:"apply_candidate",candidateId:I})}async function he(W,I){await nt(W.run,{type:"reject_candidate",candidateId:I,reason:null})}async function re(W,I){await nt(W.run,{type:"reconcile_pull_request",candidateId:I})}return{answerCreateImproveQuestion:Oe,approveCreateImproveRun:at,applyCreateImproveCandidate:Y,cancelCreateImproveRun:lt,changeDraftProvider:L,openCreateImprovePullRequest:U,pauseCreateImproveRun:Ye,reconcileCreateImprovePullRequest:re,rejectCreateImproveCandidate:he,resumeCreateImproveRun:f,reviseCreateImproveRun:pt,sendPrompt:$e,stopTurn:Le}}function yx(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function _Q({branch:e,connection:t,session:n}){if(!Io(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await Q.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await Q.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function CQ(e){return _o(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function RQ(e,t){if(e==="already_running")return null;const n=_o(t)?"Hybrid sandbox":"Cloud workspace";return e==="waited_for_creating"?`${n} is ready.`:e==="started"?`Started ${n}.`:e==="resumed"?`Resumed ${n}.`:e==="restored"?`Restored ${n}.`:`Recreated ${n}.`}function PQ(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function AQ({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:o,selectedProject:r,setWorkspaceBusy:s,showToast:l,visibleWorkspaceState:m}){return v.useCallback(async d=>{if(!n)throw new Error("OpenPond App server is not connected.");const h=r??(d.localProjectId?a.get(d.localProjectId)??null:null);if(d.cloudProjectId&&d.cloudTeamId&&!PQ(d,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");d.workspaceId||l(CQ(d),"info"),s(!0);try{const g=await _Q({branch:r?.linkedSandboxProject?.defaultBranch??o?.defaultBranch??m?.currentBranch??null,connection:n,localProject:h,session:d,source:_o(d)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});g.bootstrap&&e(g.bootstrap);const y=RQ(g.status,d);return y&&l(y,"success"),g.session}finally{s(!1)}},[e,t,n,a,o,r,s,l,m?.currentBranch])}function TQ(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function EQ(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function Sx(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function MQ(e,t){return e.diffPanelOpen!==t.diffPanelOpen||e.diffPanelExpanded!==t.diffPanelExpanded||e.rightPanelMode!==t.rightPanelMode||e.rightChatPanels.length!==t.rightChatPanels.length?!1:e.rightChatPanels.every((n,a)=>{const o=t.rightChatPanels[a];return!!(o&&n.id===o.id&&n.activationVersion===o.activationVersion&&n.sessionId===o.sessionId&&n.prompt===o.prompt&&n.provider===o.provider&&n.model===o.model&&n.scrollTop===o.scrollTop&&n.stickyToBottom===o.stickyToBottom)})}function jQ(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function OQ(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:r,selectedAppId:s,selectedCloudProject:l,selectedProjectId:m,selectedSession:d,selectedSessionId:h,setWorkspaceDiffPanelViewState:g,view:y,viewWorkspaceAppId:w,viewWorkspaceId:_,viewWorkspaceKind:P,workspaceDiffPanelViewState:M}=e,C=v.useRef(new Map),$=v.useRef(new Map),O=v.useRef(null),j=v.useRef(null),x=h??`draft:${m??s??l?.id??"general"}`,R=v.useMemo(()=>_?`${P??"workspace"}:${_}`:w?`app:${w}`:d?.cwd&&!Io(d.workspaceKind)?`cwd:${d.cwd}`:"none",[d?.cwd,d?.workspaceKind,y,w,_,P]),E=jQ({conversationId:x,workspaceSourceKey:R}),H=v.useMemo(()=>EQ({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:r}),[n,a,o,r]);v.useEffect(()=>{const D=O.current;D&&C.current.set(D,Sx(H))},[x,H]),v.useEffect(()=>{if(O.current===x)return;O.current=x;const J=C.current.get(x)??TQ();MQ(H,J)||t({type:"patch",patch:Sx(J)})},[x,H]),v.useEffect(()=>{const D=j.current;D&&$.current.set(D,Tf(M))},[E,M]),v.useEffect(()=>{if(j.current===E)return;j.current=E;const J=$.current.get(E)??bR();g(le=>vS(le,J)?le:Tf(J))},[E]);const B=v.useCallback(D=>{g(J=>vS(J,D)?J:Tf(D))},[]);return{browserConversationId:x,handleWorkspaceDiffPanelViewStateChange:B}}function $Q({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:o,appDispatch:r,applyBootstrapPayload:s,busy:l,cloudSetupDialog:m,cloudProjects:d,connection:h,defaultTeamId:g,expandProject:y,localProjectById:w,selectedCloudProject:_,selectedProject:P,selectedSession:M,selectedSessionProjectId:C,setCloudSetupDialog:$,setDiffPanelOpen:O,setError:j,setSessions:x,setWorkspaceBusy:R,showToast:E,visibleWorkspaceState:H,workspaceBusy:B}){const D=e?.baseUrl??e?.activeProfile?.baseUrl??null,J=v.useCallback(async(te,Me)=>{if(h)try{const ye=await Q.previewLocalProjectCloudSource(h,te.id,{branch:Me});$(ne=>!ne||ne.status!=="confirm"||ne.localProjectId!==te.id||ne.branch!==Me?ne:{...ne,branch:ye.preview.branch,cloudProjectId:ye.preview.targetProjectId,preview:ye.preview,previewLoading:!1,previewError:null})}catch(ye){const ne=ye instanceof Error?ye.message:String(ye);$(be=>!be||be.status!=="confirm"||be.localProjectId!==te.id||be.branch!==Me?be:{...be,preview:null,previewLoading:!1,previewError:ne})}},[h,$]),le=v.useCallback(async()=>{const te=m;if(!te||te.status==="uploading")return;if(te.projectKind==="cloud"){$(be=>be&&{...be,status:"ready",error:null});return}if(!h){$(be=>be&&{...be,status:"error",error:"OpenPond App server is not connected."});return}const Me=te.localProjectId??"",ye=w.get(Me);if(!ye){$(be=>be&&{...be,status:"error",error:"Project is no longer available."});return}R(!0);const ne=Oa(ye,d);$(be=>be&&{...be,status:"uploading",error:null,previewLoading:!1});try{const be=await Q.organizations(h),ae=Sm(be.organizations.map(fm).filter(Ue=>!!Ue).filter(Ue=>Ue.status==="active"),g);if(!ae)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!ym(ae))throw new Error(`You need owner or admin access to create projects in ${ae.displayName}.`);const de=te.branch||ye.linkedSandboxProject?.defaultBranch||"main",xe=St("local",ye.id),De=await Q.createSession(h,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:ye.id,workspaceName:ye.name,localProjectId:ye.id,cloudProjectId:ne?.id??null,cloudTeamId:ne?.teamId??null,cwd:ye.workspacePath,title:`Sync ${ye.name} to Cloud`});x(Ue=>[De,...Ue]),r({type:"selectSession",sessionId:De.id,projectId:xe}),y(xe);const we=await Q.uploadLocalProjectCloudSource(h,ye.id,{teamId:ae.teamId,projectName:ye.name,branch:de,chatSessionId:De.id,displayPrompt:`/sync-cloud ${ye.name}`});s(we.bootstrap),y(xe),y(St("cloud",we.project.id));const ie=Yh({accountBaseUrl:D,teamId:we.project.teamId,projectId:we.project.id,projectName:we.project.name,baseBranch:we.upload.branch,localProjectId:ye.id,source:"openpond-app"}),Se=hx({accountBaseUrl:D,organizationSlug:we.project.organizationSlug,projectSlug:we.project.slug});$({status:"ready",localProjectId:ye.id,cloudProjectId:we.project.id,teamId:we.project.teamId,projectName:we.project.name,projectKind:"local",projectUrl:Se,setupUrl:ie,branch:we.upload.branch,preview:te.preview??null,previewLoading:!1,previewError:null,upload:{branch:we.upload.branch,headCommit:we.upload.headCommit,fileCount:we.upload.fileCount,byteCount:we.upload.byteCount,skippedCount:we.upload.skippedCount,initializedEmptyProject:we.upload.initializedEmptyProject},error:null}),E("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(be){const ae=be instanceof Error?be.message:String(be),de=h?await Q.bootstrap(h).catch(()=>null):null;de&&s(de),j(ae),$(xe=>xe&&{...xe,status:"error",error:ae})}finally{R(!1)}},[D,r,s,m,d,h,g,y,w,$,j,x,R,E]),ue=v.useCallback((te,Me)=>{if(!h){E("OpenPond App server is not connected.","error");return}if(t){E("Checking OpenPond account. Try again in a moment.","info");return}if(n){E("Add an OpenPond account before using Cloud.","error");return}const ye=Me||te.linkedSandboxProject?.defaultBranch||"main";$({status:"confirm",localProjectId:te.id,projectName:te.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:ye,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),J(te,ye)},[t,n,h,J,$,E]),je=v.useCallback(async te=>{if(te===o||B||l)return;if(j(null),te==="upload_cloud"){if(!P){E("Select a local Project before uploading source.","error");return}ue(P,H?.currentBranch??null);return}if(te==="local"){const ne=M?.localProjectId??P?.id??C??null,be=ne?w.get(ne)??null:null;if(!be){E("No linked local workspace for this Cloud chat.","error");return}if(Io(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const ae=St("local",be.id);r({type:"selectProject",projectId:ae}),y(ae),O(!1),E(`Switched to Local: ${be.name}`,"info");return}if(!h){E("OpenPond App server is not connected.","error");return}if(t){E("Checking OpenPond account. Try again in a moment.","info");return}if(n){E("Add an OpenPond account before using Cloud.","error");return}if(_){$({status:"ready",cloudProjectId:_.id,teamId:_.teamId,projectName:_.name,projectKind:"cloud",projectUrl:hx({accountBaseUrl:D,organizationSlug:_.organizationSlug,projectSlug:_.slug}),setupUrl:Yh({accountBaseUrl:D,teamId:_.teamId,projectId:_.id,projectName:_.name,baseBranch:_.defaultBranch,source:"openpond-app"}),branch:_.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const Me=P;if(!Me){E("Select a Project before Cloud coding.","error");return}const ye=H?.currentBranch||Me.linkedSandboxProject?.defaultBranch||"main";ue(Me,ye)},[D,t,n,a,o,r,l,h,d,y,w,ue,_,P,M,C,$,O,j,E,H?.currentBranch,B]),ke=v.useCallback(te=>{nb(te)&&ue(te.project)},[ue]);return{changeWorkspaceTarget:je,moveProjectToCloud:ke,openCloudSetupForLocalProject:ue,startCloudSetupUpload:le}}function NQ({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:o,prepareTrainingTurn:r,sendPrompt:s,setMentionedAppId:l,showToast:m}){return v.useCallback(async(d=[],h=null,g,y={})=>{const w=g??n.getSnapshot(),_=r(w);if(_.active&&w.trim()&&!_.metadata)return m(_.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const P=await s(d,h,g,{clearPrompt:y.preservePrompt?()=>{}:void 0,displayPrompt:y.displayPrompt,onSessionCreated:M=>{a(M),_.metadata&&t(M.id)},turnMetadata:_.metadata||y.turnMetadata?{..._.metadata??{},...y.turnMetadata??{}}:void 0,sessionMetadata:_.metadata?{trainingTasksetId:_.metadata.trainingTasksetId,trainingTasksetName:_.metadata.trainingTasksetName}:void 0});return P&&await o?.(),P&&_.metadata&&e(),P},[e,t,n,a,o,r,s,l,m])}function DQ({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:o,setSessions:r,setView:s}){return v.useCallback(async l=>{if(!t)return;const m=n.find(g=>!g.archived&&g.workspaceKind==="sandbox"&&g.workspaceId===l.sandboxId);if(m){e({type:"selectSession",sessionId:m.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat");return}const d=l.name??`Sandbox ${l.sandboxId.slice(0,8)}`,h=await Q.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:l.sandboxId,workspaceName:d,cwd:null,title:d});r(g=>[h,...g]),e({type:"selectSession",sessionId:h.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat")},[e,t,n,a,o,r,s])}function LQ({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:o,applyBootstrapPayload:r,expandProject:s,setExpandedProjectIds:l,setSelectedAppId:m,setSelectedProjectId:d,setSelectedSessionId:h,setError:g,setView:y,showToast:w}){function _(O){const j=St("local",O.id);m(null),d(j),h(null),y("chat"),s(j)}async function P(O){if(!e)return!1;g(null);try{const j=await Q.createLocalProject(e,O);return r(j.bootstrap),_(j.project),w(j.created===!1?`Opened ${j.project.name}`:`Created ${j.project.name}`,"success"),!0}catch(j){const x=j instanceof Error?j.message:String(j);return g(x),w(x,"error"),!1}}async function M(O){if(!e)return!1;const j=O.trim();if(!j)return!1;g(null);try{const x=await Q.createLocalProject(e,{createNew:!0,name:j});return r(x.bootstrap),_(x.project),w(`Created ${x.project.name}`,"success"),!0}catch(x){return g(x instanceof Error?x.message:String(x)),w("Project could not be created","error"),!1}}async function C(O){if(!e)return!1;const j=O.trim();if(!j)return!1;g(null);try{const x=await Q.organizations(e),R=Sm(x.organizations.map(fm).filter(J=>!!J).filter(J=>J.status==="active"),t);if(!R)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!ym(R))throw new Error(`You need owner or admin access to create projects in ${R.displayName}.`);const E=`${yR(j)}-${Date.now().toString(36)}`;let H=(await Q.upsertSandboxProject(e,{teamId:R.teamId,name:j,sourceType:"internal_repo",normalizedSourceIdentity:E,internalRepoPath:E,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:E},metadata:{source:"openpond-app-new-cloud-project"}})).project;H=(await Q.uploadSandboxProjectSource(e,H.id,{teamId:R.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:v8(`# ${j}
|
|
211
|
-
|
|
212
|
-
Created in OpenPond Cloud.
|
|
213
|
-
`)}]})).project;const B=await Q.bootstrap(e);r(B);const D=St("cloud",H.id);return m(null),d(D),h(null),y("chat"),s(D),w(`Created Cloud Project: ${H.name}`,"success"),!0}catch(x){const R=x instanceof Error?x.message:String(x);return g(R),w(R,"error"),!1}}async function $(O){if(!e)return;if(WV(O)){const E=`Archive ${O.project.name} in OpenPond Cloud?`;if(!(o?await o({title:"Archive Cloud Project",body:`${O.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(E)))return;g(null);try{await Q.archiveSandboxProject(e,O.project.id,{teamId:O.project.teamId}),r(await Q.bootstrap(e)),l(B=>{const D=new Set(B);return D.delete(O.id),D}),a===O.id&&(d(null),h(null)),w(`Archived ${O.project.name}`,"success")}catch(B){g(B instanceof Error?B.message:String(B)),w("Cloud Project could not be archived","error")}return}if(!nb(O))return;const j=O.project,x=`Remove ${j.name} from Projects? The folder will not be deleted.`;if(o?await o({title:"Remove Project",body:`${j.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(x)){g(null);try{const E=await Q.deleteLocalProject(e,j.id);r(E),l(H=>{const B=new Set(H);return B.delete(O.id),B}),a===O.id&&(d(null),h(H=>{const B=n.find(D=>D.id===H);return B?.workspaceKind==="local_project"&&B.workspaceId===j.id?null:H})),w(`Removed ${j.name}`,"success")}catch(E){g(E instanceof Error?E.message:String(E)),w("Project could not be removed","error")}}}return{createCloudProjectFromScratch:C,createProjectFromScratch:M,createProjectCollection:P,removeProject:$}}function HQ({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:o,createProjectCollection:r,expandProject:s,localProjectById:l,onCreateCloudEnvironment:m,onNewCloudProject:d,onNewLocalProject:h,onUseExistingFolderPath:g,newProjectBusy:y,newProjectMode:w,newProjectName:_,projectTargetValue:P,setDiffPanelOpen:M,setDraftModel:C,setDraftProvider:$,setError:O,setNewProjectBusy:j,setNewProjectDialogOpen:x,setNewProjectName:R,setNewProjectPath:E,showToast:H,workspaceBusy:B}){const D=v.useCallback(le=>{if(le===P||t||B)return;if(O(null),le==="action:new-local-project"){h();return}if(le==="action:add-local-project"){g();return}if(le==="action:add-local-project-path"){g();return}if(le==="action:new-cloud-project"){d();return}if(le==="action:create-cloud-environment"){m();return}if(le==="none"){e({type:"selectProject",projectId:null}),M(!1),H("Started a chat without project files.","info");return}const ue=le.indexOf(":"),je=ue>=0?le.slice(0,ue):"",ke=ue>=0?le.slice(ue+1):"";if(je==="local"){const te=l.get(ke);if(!te){H("Project is no longer available.","error");return}const Me=St("local",te.id);e({type:"selectProject",projectId:Me}),s(Me),M(!1);return}if(je==="cloud"){const te=n.get(ke);if(!te){H("Cloud Project is no longer available.","error");return}const Me=St("cloud",te.id);e({type:"selectProject",projectId:Me}),s(Me),$("openpond"),C(ye=>ji("openpond",ye)),M(!1)}},[e,t,n,s,l,m,d,h,g,P,M,C,$,O,H,B]),J=v.useCallback(async le=>{const ue=_.trim();if(!y){if(w==="existing-local"?!le?.name.trim()||!le.sourceFolders.length:!ue)return!1;j(!0);try{const je=w==="cloud"?await a(ue):w==="existing-local"?await r(le):await o(ue);return je&&(x(!1),R(""),E("")),!!je}finally{j(!1)}}},[a,o,r,y,w,_,j,x,R,E]);return{changeProjectTarget:D,submitNewProjectDialog:J}}function UQ(e){return{id:`right-chat-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,activationVersion:1,sessionId:e.sessionId,prompt:e.prompt??"",provider:e.provider,model:e.model,scrollTop:0,stickyToBottom:!0}}function Hte(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function qQ(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const o=e.map(r=>r.id!==t?r:(a=!0,{...r,activationVersion:n}));return a?o:[...e]}function zQ(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const o=e.map(r=>r.sessionId!==t.sessionId?r:(a=!0,{...r,activationVersion:n,prompt:t.prompt??r.prompt}));return a?o:[...e]}function yP(e){return!!(e.parentSessionId&&e.subagentRunId)}function BQ(e){const t=e.sessions.filter(yP);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function FQ(e,t){const n=new Set(e.map(o=>o.sessionId).filter(Boolean)),a=t.filter(yP).filter(o=>!n.has(o.id)).map(o=>({id:`right-subagent-${o.id}`,activationVersion:1,sessionId:o.id,prompt:"",provider:o.provider,model:o.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const xx="openpond/openpond",VQ="github.issue.write";function KQ(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(VQ))}function Ute(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
|
|
214
|
-
`)}function WQ(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${xx}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${xx}, a concise title, and a complete issue body that preserves the request.`,"This slash command is the user's explicit intent to create the issue.","Before creating, search open issues in the repository for an obvious duplicate. If a clear duplicate exists, do not create a new issue; report the existing issue instead.","",`Issue request:
|
|
215
|
-
${t}`].join(`
|
|
216
|
-
`)}function GQ(e,t){const n=t.trim();switch(e.id){case"agent":return{kind:"send_prompt",prompt:`/agent ${n}`,requiresInstructions:!0};case"skill":return{kind:"send_prompt",prompt:`/skill ${n}`,requiresInstructions:!1};case"goal":return{kind:"send_prompt",prompt:`/goal ${n}`,requiresInstructions:!0};case"workflow":return{kind:"send_prompt",prompt:["Create a scheduled workflow attached to this chat.","Use the schedule_work tool after resolving the exact cadence, local date/time, and timezone from my request. Ask a concise clarification only if a required scheduling detail is genuinely missing.",`Workflow request: ${n}`].join(`
|
|
217
|
-
|
|
218
|
-
`),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:WQ(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const kx=[];function JQ(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:o,rightChatHistoryEvents:r,rightChatPanels:s,runningSessionIds:l,selectedSessionId:m,sidebarSessions:d}=e;return v.useMemo(()=>{const h=new Map(d.map(y=>[y.id,y])),g=ZQ(t);return s.map(y=>{const w=y.sessionId?h.get(y.sessionId)??null:null,_=qt(y.sessionId),P=_?(y.sessionId?r[y.sessionId]:void 0)??(y.sessionId===m?n:kx):kx,M=Lh(P,[]),C=y.sessionId?g.get(y.sessionId)??null:null,$=!!(w&&l.has(w.id)),O=_?_W({events:P}):null,j=w?.cwd??null,x=w?.appId??w?.localProjectId??(w?.workspaceKind==="local_project"?w.workspaceId??null:null)??(w?.cwd&&!Io(w.workspaceKind)?t1(w.cwd):null),R=y.sessionId?o[y.sessionId]??null:null;return{...y,session:w,title:CW(O,w?.title??"New task"),messages:_?ER(vm(P),R):[],createImproveRun:O,contextWindowStatus:JC({provider:y.provider,snapshot:uR(M,y.sessionId),preferences:a}),goalRuntime:mR(M,y.sessionId),pendingApproval:C,running:$,workspaceRootPath:j,activeWorkspaceAppId:x,pendingUserMessage:R,runtimeSource:_?"history":"live"}})},[t,n,a,o,r,s,l,m,d])}function ZQ(e){const t=new Map;for(const n of e){if(n.status!=="pending")continue;const a=t.get(n.sessionId);(!a||Date.parse(n.createdAt)>Date.parse(a.createdAt))&&t.set(n.sessionId,n)}return t}function YQ(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:o,sessions:r,setError:s}=e,l=v.useMemo(()=>{const h=new Set,g=[];for(const y of o)!qt(y.sessionId)||!y.sessionId||h.has(y.sessionId)||(h.add(y.sessionId),g.push(y.sessionId));return g.join(`
|
|
219
|
-
`)},[o]),m=v.useMemo(()=>{if(!l)return"";const h=new Set(l.split(`
|
|
220
|
-
`).filter(Boolean));return r.filter(g=>h.has(g.id)&&g.status==="active").map(g=>g.id).join(`
|
|
221
|
-
`)},[l,r]),d=v.useMemo(()=>l?l.split(`
|
|
222
|
-
`).filter(h=>a.has(h)).join(`
|
|
223
|
-
`):"",[a,l]);v.useEffect(()=>{if(!n||!l)return;const h=l.split(`
|
|
224
|
-
`).filter(Boolean),g=new Set(m.split(`
|
|
225
|
-
`).filter(Boolean)),y=new Set(d.split(`
|
|
226
|
-
`).filter(Boolean)),w=h.map(_=>hb({connection:n,locallyActive:y.has(_),onError:P=>s(P instanceof Error?P.message:String(P)),onPayload:P=>t(fb(P,y.has(_))),reportedActive:g.has(_),sessionId:_,surface:"thread"}));return()=>w.forEach(_=>_())},[m,t,n,d,l,s])}const wx=[];function QQ(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:o,codexHistoryEvents:r,connectedAppMentions:s,connection:l,contextCompaction:m,openLabTraining:d,locallyActiveCodexHistorySessionIds:h,openPondCommandAccessMode:g,pendingChatUserMessages:y,providerSettings:w,rightChatHistoryEvents:_,rightChatPanels:P,rightPanelMode:M,runtimeIndexes:C,runtimeEventStore:$,runningSessionIds:O,selectedSession:j,selectedSessionId:x,sendPrompt:R,setDiffPanelOpen:E,setError:H,setRightChatHistoryEvents:B,setRightChatPanels:D,setRightPanelMode:J,setRightPanelTabRequest:le,setView:ue,showChangesPanel:je,showToast:ke,sidebarSessions:te,startupReady:Me}=e,ye=v.useRef(null),ne=v.useRef(new Map),be=v.useRef(new Set);v.useEffect(()=>{if(!l)return;const ze=P.flatMap(Ge=>Ge.sessionId&&!qt(Ge.sessionId)?[Ge.sessionId]:[]);for(const Ge of ze)Object.hasOwn(_,Ge)||be.current.has(Ge)||(be.current.add(Ge),Q.runtimeEventsPage(l,{sessionId:Ge,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(qe=>{const L=qe.events.map(N=>N.event);B(N=>({...N,[Ge]:zo(N[Ge]??wx,L)}))}).catch(qe=>{H(qe instanceof Error?qe.message:String(qe))}).finally(()=>{be.current.delete(Ge)}))},[l,_,P,H,B]);const ae=v.useCallback(ze=>{le(Ge=>({id:(Ge?.id??0)+1,tab:ze})),je()},[je]),de=v.useCallback((ze=null,Ge={})=>{const qe=ze?.id?P.find(N=>N.sessionId===ze.id)??null:null;if(qe)return D(N=>zQ(N,{sessionId:ze.id,prompt:Ge.prompt})),E(!0),J("chat"),Ge.preserveView||ue("chat"),qe.id;const L=UQ({sessionId:ze?.id??null,provider:ze?.provider??n,model:ze?.modelRef?.modelId??t,prompt:Ge.prompt});return D(N=>[...N,L]),E(!0),J("chat"),Ge.preserveView||ue("chat"),L.id},[t,n,P,E,D,J,ue]);v.useEffect(()=>{if(!Me)return;const ze=ye.current;if(!ze){ye.current=new Set(te.filter(N=>!!(N.parentSessionId&&N.subagentRunId)).map(N=>N.id));return}const Ge=BQ({sessions:te,knownSessionIds:ze});ye.current=Ge.knownSessionIds;for(const N of Ge.newSessions)ne.current.set(N.id,N);const qe=j?.parentSessionId??j?.id??null;if(!qe)return;const L=[...ne.current.values()].filter(N=>N.parentSessionId===qe);if(L.length!==0){for(const N of L)ne.current.delete(N.id);D(N=>FQ(N,L)),E(!0),J("chat")}},[j?.id,j?.parentSessionId,E,D,J,te,Me]);const xe=v.useCallback(()=>{if(P.length===0){de(null);return}E(!0),J("chat"),ue("chat")},[de,P.length,E,J,ue]),De=v.useCallback(ze=>{const Ge=P.length<=1&&P.some(L=>L.id===ze),qe=()=>{D(L=>L.filter(N=>N.id!==ze))};if(Ge&&M==="chat"){if(ae("files"),typeof window>"u"){qe();return}window.requestAnimationFrame(qe);return}qe()},[P,M,D,ae]),we=v.useCallback((ze,Ge)=>{D(qe=>qe.map(L=>L.id===ze?{...L,prompt:Ge}:L))},[D]),ie=v.useCallback(ze=>{D(Ge=>qQ(Ge,ze))},[D]),Se=v.useCallback((ze,Ge)=>{D(qe=>qe.map(L=>L.id===ze?{...L,...Ge}:L))},[D]),Ue=v.useCallback((ze,Ge)=>{D(qe=>qe.map(L=>L.id===ze?{...L,model:Ge}:L))},[D]),Je=v.useCallback((ze,Ge)=>{D(qe=>qe.map(L=>L.id===ze?{...L,provider:Ge,model:ji(Ge,L.model,w)}:L))},[w,D]);YQ({applyPayload:o,connection:l,locallyActiveSessionIds:h,panels:P,sessions:te,setError:H});const Ke=JQ({approvals:a,codexHistoryEvents:r,contextCompaction:m,pendingChatUserMessages:y,rightChatHistoryEvents:_,rightChatPanels:P,runningSessionIds:O,selectedSessionId:x,sidebarSessions:te}),tt=v.useCallback(async(ze,Ge=[],qe=null,L=null,N={})=>{const q=P.find(pt=>pt.id===ze);if(!q)return!1;const X=N.promptOverride??q.prompt,me=L?GQ(L,X):null;if(me?.kind==="open_training")return Ge.length>0?(ke("/train uses this chat; add other chats from Models.","error"),!1):(d({objective:me.objective,sessionId:q.sessionId}),N.preservePrompt||we(ze,""),!0);if(L&&me?.kind==="send_prompt"&&me.requiresInstructions&&!X.trim())return ke(`Add instructions after ${L.command}.`,"info"),!1;if(L&&Ge.length>0)return ke(`${L.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(L?.id==="submit-issue"&&!KQ(s))return ke("Connect the GitHub app before using /submit-issue.","error"),!1;const $e=q.sessionId?te.find(pt=>pt.id===q.sessionId)??null:null,Le=q.provider==="codex"?g:$e?.openPondCommandAccessMode??g,nt=me?.kind==="send_prompt"?me.prompt:X,at=qt(q.sessionId)?(q.sessionId?_[q.sessionId]:void 0)??(q.sessionId===x?r:wx):$.getSessionEvents(q.sessionId),lt=qt(q.sessionId)&&q.sessionId?pt=>{const Oe=q.sessionId;B(Ye=>({...Ye,[Oe]:zo(Ye[Oe]??at,[pt])}))}:void 0;return R(Ge,qe,nt,{session:$e,selectSession:!1,provider:q.provider,model:q.model,openPondCommandAccessMode:Le,chatMessages:vm(at),displayPrompt:N.displayPrompt,turnMetadata:N.turnMetadata,usageAttribution:L?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:L.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:lt,clearPrompt:N.preservePrompt?()=>{}:()=>we(ze,""),onSessionCreated:pt=>{D(Oe=>Oe.map(Ye=>Ye.id===ze?{...Ye,sessionId:pt.id,provider:pt.provider,model:pt.modelRef?.modelId??Ye.model}:Ye))}})},[r,s,_,P,C,$,x,d,g,R,D,ue,te,ke,we]);return{activateRightChatPanel:ie,closeRightChatPanel:De,openRightChatPanel:de,rightChatPanelViews:Ke,showRightChatPanel:xe,showRightPanelDiffTab:ae,submitRightChatPrompt:tt,updateRightChatModel:Ue,updateRightChatPrompt:we,updateRightChatProvider:Je,updateRightChatScrollState:Se}}function XQ(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:o,setCodexHistorySessions:r,setError:s,setSelectedSessionId:l,setSessions:m}=e;async function d(C,$){if(!n)return;const O=t[C]??{},j={...O,...$,archived:$.pinned?!1:$.archived??O.archived};o(x=>({...x,[C]:j}));try{const x=await Q.patchSidebarAppPreference(n,C,$);o(R=>({...R,[C]:x}))}catch(x){s(x instanceof Error?x.message:String(x)),o(R=>({...R,[C]:O}))}}function h(C){d(C.id,{pinned:!C.pinned,archived:!1})}async function g(C,$){if(!n)return;const O=qt(C.id)?r:m,j={...C,...$};O(x=>x.some(R=>R.id===C.id)?x.map(R=>R.id===C.id?j:R):[j,...x]);try{const x=await Q.patchSession(n,C.id,$);O(R=>R.some(E=>E.id===x.id)?R.map(E=>E.id===x.id?x:E):[x,...R])}catch(x){s(x instanceof Error?x.message:String(x)),O(R=>R.map(E=>E.id===C.id?C:E))}}function y(C){g(C,{pinned:!1,savedForLater:!C.savedForLater,archived:!1})}function w(C){g(C,{pinned:!C.pinned,savedForLater:!1,archived:!1})}function _(C){g(C,{pinned:!1,savedForLater:!1,archived:!0}),a===C.id&&l(null)}function P(C){g(C,{archived:!1})}function M(C,$){const O=$.trim();!O||O===C.title||g(C,{title:O})}return{archiveSession:_,renameSession:M,restoreSession:P,toggleProjectPinned:h,toggleSessionPinned:w,toggleSessionSavedForLater:y}}function eX(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function tX({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:o,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:l,draftModel:m,draftProvider:d,cloudProjects:h,selectedApp:g,selectedProject:y,selectedProjectLinkedOpenPondApp:w,selectedSession:_,sessions:P,title:M,visibleWorkspaceDiff:C,visibleWorkspaceState:$,workspaceBusy:O,workspaceName:j,appDispatch:x,applyBootstrapPayload:R,expandProject:E,refreshWorkspace:H,refreshWorkspaceDiff:B,rememberWorkspaceState:D,setBranchDialogOpen:J,setCommitDialogOpen:le,setError:ue,setSessions:je,setSettingsSection:ke,setSyncingWorkspaceAppId:te,setView:Me,setWorkspaceBusy:ye,showToast:ne}){function be(){return`${RC(n.defaultBranchPrefix)}${eX(j??M??"new-branch")}`}function ae(){return j?`Update ${j}`:(C?.filesChanged??$?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function de(qe="commit"){x({type:"openCommitDialog",nextStep:qe})}function xe(){x({type:"openBranchDialog",branchName:be()})}function De(){O||J(!1),ke("configuration"),Me("settings"),Xt({kind:"settings",section:"configuration"})}async function we(qe){if(!(!e||!t)){ye(!0),ue(null);try{const L=await Q.checkoutWorkspaceBranch(e,t,{branch:qe});D(L),L.initialized&&B(t)}catch(L){ue(L instanceof Error?L.message:String(L))}finally{ye(!1)}}}async function ie(){if(!e||!t)return;const qe=o.trim();if(qe){ye(!0),ue(null);try{const L=await Q.createWorkspaceBranch(e,t,{branch:qe});D(L),L.initialized&&B(t),J(!1),ne(`Checked out ${qe}`,"success")}catch(L){ue(L instanceof Error?L.message:String(L))}finally{ye(!1)}}}async function Se(qe){te(qe);const L=a?.apps.find(N=>N.id===qe)?.name??a?.localProjects.find(N=>N.id===qe)?.name??"Workspace";try{const N=await H(qe,!0);N?.initialized&&qe===t&&B(qe),N?.initialized&&!N.error?ne(`${L} synced locally`,"success"):N?.error&&ne("Workspace sync failed","error")}finally{te(N=>N===qe?null:N)}}async function Ue(){t&&await Se(t)}async function Je(qe,L,N={}){if(!e)return null;const q=_&&!qt(_.id)?_:null;if(iX(L,q,N)||q&&nX(q,y,g))return q;const X=q?await Ke(q):null;if(X)return X;const me=aX(P,y,g);if(me){const at=me.workspaceKind==="local_project"&&me.workspaceId?St("local",me.workspaceId):null;return x({type:"selectSession",sessionId:me.id,appId:me.appId,projectId:at}),me.workspaceKind==="local_project"&&me.workspaceId&&E(St("local",me.workspaceId)),me}const $e=Oa(y,h),Le=await Q.createSession(e,{provider:d,modelRef:Fa(d,m,a?.providers??null),appId:w?.appId??g?.id??null,appName:w?.appName??g?.name??null,workspaceKind:y?"local_project":g?"sandbox_app":void 0,workspaceId:y?.id??g?.id??null,workspaceName:y?.name??g?.name??null,localProjectId:y?.id??null,cloudProjectId:$e?.id??null,cloudTeamId:$e?.teamId??null,cwd:y?y.workspacePath:null,title:qe});je(at=>[Le,...at]);const nt=Le.workspaceKind==="local_project"&&Le.workspaceId?St("local",Le.workspaceId):null;return x({type:"selectSession",sessionId:Le.id,appId:Le.appId,projectId:nt}),Le.workspaceKind==="local_project"&&Le.workspaceId&&E(St("local",Le.workspaceId)),Le}async function Ke(qe){if(!e||!y||!w?.appId||qt(qe.id)||qe.workspaceKind==="local_project"||qe.appId!==w.appId)return null;const L=Oa(y,h),N=await Q.patchSession(e,qe.id,{appId:w.appId,appName:w.appName,workspaceKind:"local_project",workspaceId:y.id,workspaceName:y.name,localProjectId:y.id,cloudProjectId:L?.id??null,cloudTeamId:L?.teamId??null,cwd:y.workspacePath});return je(q=>q.map(X=>X.id===N.id?N:X)),x({type:"selectSession",sessionId:N.id,appId:N.appId,projectId:St("local",y.id)}),E(St("local",y.id)),N}async function tt(qe,L={}){if(!e)return null;const N=await Je(j?`${j} workspace`:"Workspace action",qe,L);if(!N)return null;const q=await Q.workspaceTool(e,N.id,{action:qe,args:L,source:"ui_button"});ne(q.output,q.ok?"success":"error"),R(await Q.bootstrap(e));const X=q.appId??oX(N);return X&&(await H(X,!1))?.initialized&&await B(X),q}async function ze(qe,L={}){if(qe==="git_commit"&&typeof L.message!="string")return de("commit"),null;ye(!0),ue(null);try{return await tt(qe,L)}catch(N){return ue(N instanceof Error?N.message:String(N)),null}finally{ye(!1)}}async function Ge(){const qe=s.trim()||ae(),L=l==="commit_publish",N=L&&!!$?.remoteUrl;if(!(N&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){ye(!0),ue(null);try{if(!(await tt("git_commit",{message:qe,includeUnstaged:r}))?.ok||l==="commit_push"&&!(await tt("git_push",{runChecks:!1}))?.ok||L&&!(await tt("publish_openpond_repo",{replaceOrigin:N}))?.ok)return;le(!1)}catch(q){ue(q instanceof Error?q.message:String(q))}finally{ye(!1)}}}return{changeWorkspaceBranch:we,openCommitDialog:de,openCreateWorkspaceBranchDialog:xe,openDefaultsSettingsFromBranchDialog:De,runWorkspaceTool:ze,submitCommitDialog:Ge,submitCreateWorkspaceBranch:ie,syncWorkspaceLocally:Ue,syncWorkspaceLocallyForApp:Se}}function nX(e,t,n){return!t&&!n?!0:SP(e,t,n)}function aX(e,t,n){if(!t&&!n)return null;let a=null,o=Number.NEGATIVE_INFINITY;for(const r of e){if(r.archived||!SP(r,t,n))continue;const s=Date.parse(r.updatedAt),l=Number.isFinite(s)?s:0;(!a||l>o)&&(a=r,o=l)}return a}function SP(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function oX(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function iX(e,t,n={}){return(rX(e)||lX(e,n))&&sX(t)}function rX(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function sX(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function lX(e,t){if(e!=="sandbox_create")return!1;const n=t.runtime;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.runtimeId=="string"&&n.runtimeId.trim())}function cX(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const dX=[];function uX(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:o,cloudSetupDialog:r,setCloudSetupDialog:s,setRightPanelTabRequest:l,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:d,rightChatHistoryEvents:h,setRightChatHistoryEvents:g,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:w,draftSubagentDelegationMode:_,setDraftSubagentDelegationMode:P,confirmProjectAction:M,view:C,selectedAppId:$,selectedProjectId:O,selectedSessionId:j,draftProvider:x,draftModel:R,activeExperience:E,codexPermissionMode:H,codexReasoningEffort:B,openPondCommandAccessMode:D,busy:J,diffPanelOpen:le,diffPanelExpanded:ue,rightPanelMode:je,rightChatPanels:ke,newProjectMode:te,newProjectName:Me,newProjectBusy:ye,commitMessage:ne,commitIncludeUnstaged:be,commitNextStep:ae,branchDialogName:de,setSectionMenuOpen:xe,setView:De,setSelectedAppId:we,setSelectedProjectId:ie,setSelectedSessionId:Se,setPrompt:Ue,setDraftProvider:Je,setDraftModel:Ke,setDiffPanelOpen:tt,setRightPanelMode:ze,setRightChatPanels:Ge,setSyncingWorkspaceAppId:qe,setSettingsSection:L,setNewProjectDialogOpen:N,setNewProjectMode:q,setNewProjectName:X,setNewProjectPath:me,setNewProjectBusy:$e,setCommitDialogOpen:Le,setBranchDialogOpen:nt,setError:at,showToast:lt,appPreferences:pt,applyBootstrapPayload:Oe,approvals:Ye,bootstrap:f,connection:U,events:Y,runtimeEventStore:he,sessions:re,startup:W,setAppPreferences:I,setCodexHistorySessions:K,setEvents:ee,setSessions:Z,cloudProjectById:ce,localProjectById:pe,selectedApp:fe,selectedCloudProject:Ae,selectedProject:_e,selectedProjectLinkedOpenPondApp:Ne,selectedSession:Pe,sidebarSessions:Xe,runtimeIndexes:st,connectedAppMentions:rn,codexHistoryEvents:Et,setCodexHistoryEvents:tn,account:mn,accountPending:pn,accountSignedOut:Wt,activeModel:Da,activeProvider:ga,activeWorkspaceAppId:$n,activeWorkspaceKind:Pn,activeWorkspaceLocation:$t,appDefaults:ht,selectedSessionProjectId:fn,workspaceName:bt,accountScopeKey:jt,teamChat:va,communities:Ut,selectedProjectConfirmedCloudProject:hn,activeOpenPondCommandAccessMode:it,viewWorkspaceAppId:Cn,viewWorkspaceId:ao,viewWorkspaceKind:oo,openPondActionCatalog:ra,selectedActionCatalog:ba,expandProject:Nn,setExpandedProjectIds:Po,advanceTrainingModelChatAfterTurn:La,bindTrainingModelChatSession:V,prepareTrainingModelChatTurn:He,chatMessages:Ie,pendingChatUserMessages:Be,recordPendingChatUserMessage:yt,runningSessionIds:Jn,workspaceBusy:gn,visibleWorkspaceState:We,visibleWorkspaceDiff:yn,rememberWorkspaceState:ut,refreshWorkspace:An,setWorkspaceBusy:Ha,refreshWorkspaceDiffWhenNeeded:ri,setPendingWorkspaceTarget:ya,pendingSidebarWorkspaceTarget:si,setPendingSidebarWorkspaceTarget:$i,projectTarget:Ao,workspaceTarget:Dn}=e,Sa=C==="apps"?"Apps":C==="get-started"?"Walkthroughs":C==="labs"?"Models":C==="scheduled"?"Workflows":C==="outputs"?"Outputs":C==="projects"?"Projects":C==="team"?va.detail?cX(va.detail.thread,va.currentUserId):"Team Chat":C==="community"?Ut.preview?.displayName??"Communities":Pe?.title??fC(E),{browserConversationId:Zn,handleWorkspaceDiffPanelViewStateChange:li}=OQ({appDispatch:n,diffPanelExpanded:ue,diffPanelOpen:le,rightChatPanels:ke,rightPanelMode:je,selectedAppId:$,selectedCloudProject:Ae,selectedProjectId:O,selectedSession:Pe,selectedSessionId:j,setWorkspaceDiffPanelViewState:d,view:C,viewWorkspaceAppId:Cn,viewWorkspaceId:ao,viewWorkspaceKind:oo,workspaceDiffPanelViewState:m}),Ni=v.useCallback(ct=>{Xt({kind:"chat",sessionId:ct}),Se(ct),we(null),ie(null),De("chat")},[we,ie,Se,De]),ci=v.useCallback(()=>{q("existing-local"),X(""),me(""),N(!0)},[N,q,X,me]),di=v.useCallback(()=>{q("local"),X(""),me(""),N(!0)},[N,q,X,me]),{createCloudProjectFromScratch:xt,createProjectFromScratch:Bs,createProjectCollection:Di,removeProject:Fs}=LQ({connection:U,defaultTeamId:ht.defaultTeamId,sessions:re,selectedProjectId:O,confirmProjectAction:M,applyBootstrapPayload:Oe,expandProject:Nn,setExpandedProjectIds:Po,setSelectedAppId:we,setSelectedProjectId:ie,setSelectedSessionId:Se,setError:at,setView:De,showToast:lt}),{changeWorkspaceBranch:Sr,openCommitDialog:Vs,openCreateWorkspaceBranchDialog:To,openDefaultsSettingsFromBranchDialog:Ks,runWorkspaceTool:xr,submitCommitDialog:kr,submitCreateWorkspaceBranch:wr,syncWorkspaceLocally:Ws}=tX({connection:U,activeWorkspaceAppId:$n,appDefaults:ht,bootstrap:f,branchDialogName:de,commitIncludeUnstaged:be,commitMessage:ne,commitNextStep:ae,draftModel:R,draftProvider:x,cloudProjects:f?.cloudProjects??[],selectedApp:fe,selectedProject:_e,selectedProjectLinkedOpenPondApp:Ne,selectedSession:Pe,sessions:re,title:Sa,visibleWorkspaceDiff:yn,visibleWorkspaceState:We,workspaceBusy:gn,workspaceName:bt,appDispatch:n,applyBootstrapPayload:Oe,expandProject:Nn,refreshWorkspace:An,refreshWorkspaceDiff:ri,rememberWorkspaceState:ut,setBranchDialogOpen:nt,setCommitDialogOpen:Le,setError:at,setSessions:Z,setSettingsSection:L,setSyncingWorkspaceAppId:qe,setView:De,setWorkspaceBusy:Ha,showToast:lt}),Gs=AQ({applyBootstrapPayload:Oe,cloudProjects:f?.cloudProjects??[],connection:U,localProjectById:pe,selectedCloudProject:Ae,selectedProject:_e,setWorkspaceBusy:Ha,showToast:lt,visibleWorkspaceState:We}),io=f?.preferences.subagents.delegationMode??"manual",Js=Pe?.subagentDelegationMode??_,Ir=!!(E==="development"&&f?.preferences.subagents.enabled&&ga!=="codex"&&!qt(j)&&!Pe?.subagentRunId),_r=v.useCallback(ct=>{if(!Pe){P(ct);return}if(!U||qt(Pe.id)||Pe.subagentRunId)return;const Yt=Pe.id,Qn=Pe.subagentDelegationMode??null;Z(sn=>sn.map(Tn=>Tn.id===Yt?{...Tn,subagentDelegationMode:ct}:Tn)),Q.patchSession(U,Yt,{subagentDelegationMode:ct}).then(sn=>{Z(Tn=>Tn.map(ca=>ca.id===sn.id?sn:ca))}).catch(sn=>{Z(Tn=>Tn.map(ca=>ca.id===Yt?{...ca,subagentDelegationMode:Qn}:ca)),at(sn instanceof Error?sn.message:String(sn))})},[U,Pe,at,Z]),ui=v.useCallback(ct=>{g(Yt=>Yt[ct.session.id]===ct.events?Yt:{...Yt,[ct.session.id]:ct.events}),K(Yt=>hm(Yt,ct.session))},[K]),{answerCreateImproveQuestion:Cr,applyCreateImproveCandidate:sa,approveCreateImproveRun:Zs,cancelCreateImproveRun:Li,changeDraftProvider:Eo,openCreateImprovePullRequest:Yn,reconcileCreateImprovePullRequest:Ys,rejectCreateImproveCandidate:Qs,pauseCreateImproveRun:Sn,resumeCreateImproveRun:mi,reviseCreateImproveRun:xa,sendPrompt:Ua,stopTurn:Hi}=IQ({applyBootstrapPayload:Oe,bootstrap:f,chatMessages:Ie,connection:U,codexPermissionMode:H,codexReasoningEffort:B,openPondCommandAccessMode:it,draftModel:R,draftProvider:x,experience:E,expandProject:Nn,getPrompt:t.getSnapshot,apps:f?.apps??[],connectedAppMentions:rn,mentionedAppId:a,ensureCloudSessionReady:Gs,refreshWorkspace:An,refreshWorkspaceDiff:ri,selectedApp:fe,selectedActionCatalog:ba,openPondActionCatalog:ra,cloudProjects:f?.cloudProjects??[],accountScopeKey:jt,selectedCloudProject:Ae,selectedProject:_e,selectedProjectLinkedOpenPondApp:Ne,selectedSession:Pe,sessions:re,workspaceTarget:Dn.value,subagentDelegationMode:Pe?.subagentDelegationMode??_,setDraftModel:Ke,setDraftProvider:Je,setError:at,setPrompt:Ue,setMentionedAppId:o,setCodexHistoryEvents:tn,setCodexHistorySessions:K,onCodexHistoryTurnActivityChange:w,onCodexHistoryTurnPayload:ui,onPendingUserMessage:yt,setEvents:ee,setSelectedAppId:we,setSelectedProjectId:ie,setSelectedSessionId:Se,setSessions:Z,setView:De,setWorkspaceBusy:Ha}),{archiveSession:pi,restoreSession:Xs,renameSession:Rr,toggleProjectPinned:Ui,toggleSessionPinned:Mo,toggleSessionSavedForLater:fi}=XQ({appPreferences:pt,connection:U,selectedSessionId:j,setAppPreferences:I,setCodexHistorySessions:K,setError:at,setSelectedSessionId:Se,setSessions:Z}),{changeWorkspaceTarget:hi,moveProjectToCloud:Pr,startCloudSetupUpload:Ar}=$Q({account:mn,accountPending:pn,accountSignedOut:Wt,activeWorkspaceKind:Pn,activeWorkspaceLocation:$t,appDispatch:n,applyBootstrapPayload:Oe,busy:J,cloudSetupDialog:r,cloudProjects:f?.cloudProjects??[],connection:U,defaultTeamId:ht.defaultTeamId,expandProject:Nn,localProjectById:pe,selectedCloudProject:Ae,selectedProject:_e,selectedSession:Pe,selectedSessionProjectId:fn,setCloudSetupDialog:s,setDiffPanelOpen:tt,setError:at,setSessions:Z,setWorkspaceBusy:Ha,showToast:lt,visibleWorkspaceState:We,workspaceBusy:gn}),ka=v.useCallback(async ct=>{if(E==="work"&&!Pe){if(ct==="local"){ya("local"),lt(_e?`Next task will use the local ${_e.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(ct==="cloud"&&!_e&&!Ae){if(pn){lt("Checking OpenPond account. Try again in a moment.","info");return}if(Wt){lt("Add an OpenPond account before using Hosted.","error");return}ya("cloud"),lt("Next task will use Hosted without a Project.","info");return}}if(ct==="hybrid"){const Yt=Ae?.id??hn?.id??Pe?.cloudProjectId??null,Qn=Ae?.teamId??hn?.teamId??Pe?.cloudTeamId??null;if(pn){lt("Checking OpenPond account. Try again in a moment.","info");return}if(Wt){lt("Add an OpenPond account before using Hybrid.","error");return}if(!Yt||!Qn){ya(null),lt("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Pe&&!qt(Pe.id)){if(_o(Pe))return;if(!U){lt("OpenPond App server is not connected.","error");return}const sn=await Q.patchSession(U,Pe.id,{provider:x,modelRef:Fa(x,R,f?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Ae?.name??hn?.name??_e?.name??Pe.workspaceName??"Hybrid workspace",localProjectId:_e?.id??Pe.localProjectId??null,cloudProjectId:Yt,cloudTeamId:Qn,metadata:hR(Pe.metadata),cwd:_e?.workspacePath??Pe.cwd??null});Z(Tn=>Tn.map(ca=>ca.id===sn.id?sn:ca)),ya(null),lt("Hybrid will use your selected model with hosted sandbox edits.","info");return}ya("hybrid"),lt("Next message will use Hybrid with a hosted sandbox.","info");return}ya(null),await hi(ct)},[pn,Wt,E,f?.providers,hi,U,R,x,Ae?.id,Ae?.name,Ae?.teamId,_e?.id,hn?.id,hn?.name,hn?.teamId,_e?.name,_e?.workspacePath,Pe,ya,Z,lt]),wa=v.useCallback((ct,Yt)=>{we(null),ie(ct),Se(null),De("chat"),Nn(ct),$i({projectId:ct,target:Yt})},[Nn,we,ie,Se,De]);v.useEffect(()=>{if(!si||C!=="chat"||O!==si.projectId||j!==null)return;const ct=si.target;$i(null),ka(ct)},[ka,si,O,j,C]);const Tr=NQ({advanceTrainingTurn:La,bindTrainingSession:V,composerDraftStore:t,onSessionCreated:ct=>{Se(ct.id),De("chat"),Xt({kind:"chat",sessionId:ct.id}),P(null)},onSubmitted:async()=>{const ct=Pe;if(!(!U||!ct||!sc(ct)))try{const Yt=await Q.patchSession(U,ct.id,{metadata:oK(ct.metadata)});Z(Qn=>Qn.map(sn=>sn.id===Yt.id?Yt:sn))}catch(Yt){lt(Yt instanceof Error?`Task started, but its Draft label could not be cleared: ${Yt.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:He,sendPrompt:Ua,setMentionedAppId:o,showToast:lt}),qi=DQ({appDispatch:n,connection:U,sessions:re,setDiffPanelOpen:tt,setRightPanelMode:ze,setSessions:Z,setView:De}),{createCloudEnvironmentFromSidebar:ro,openCloudProjectDialog:zi,openUrlInBrowserPanel:jo,showBrowserPanel:Er,showChangesPanel:Mr,showGoalSidebarTab:jr}=KY({account:mn,browserConversationId:Zn,cloudProjectById:ce,cloudProjects:f?.cloudProjects??[],diffPanelOpen:le,rightPanelMode:je,selectedProjectId:O,setDiffPanelOpen:tt,setNewProjectDialogOpen:N,setNewProjectMode:q,setNewProjectName:X,setRightPanelMode:ze}),{changeProjectTarget:el,submitNewProjectDialog:Or}=HQ({appDispatch:n,busy:J,cloudProjectById:ce,createCloudProjectFromScratch:xt,createProjectFromScratch:Bs,createProjectCollection:Di,expandProject:Nn,localProjectById:pe,newProjectBusy:ye,newProjectMode:te,newProjectName:Me,onCreateCloudEnvironment:ro,onNewCloudProject:zi,onNewLocalProject:di,onUseExistingFolderPath:ci,projectTargetValue:Ao.value,setDiffPanelOpen:tt,setDraftModel:Ke,setDraftProvider:Je,setError:at,setNewProjectBusy:$e,setNewProjectDialogOpen:N,setNewProjectName:X,setNewProjectPath:me,showToast:lt,workspaceBusy:gn}),$r=v.useMemo(()=>re.map(ct=>ct.id),[re]);GY({browserConversationId:Zn,sessionIds:$r,onOpenSession:Ni,onShowBrowserPanel:Er});const[tl,gi]=v.useState(null),Nr=v.useCallback(ct=>{gi({id:Date.now(),objective:ct.objective,initialSessionIds:ct.sessionId?[ct.sessionId]:[]}),gs(Za()),De("labs")},[De]),{activateRightChatPanel:Bi,closeRightChatPanel:so,openRightChatPanel:nl,rightChatPanelViews:al,showRightChatPanel:ol,showRightPanelDiffTab:il,submitRightChatPrompt:lo,updateRightChatModel:Dr,updateRightChatPrompt:rl,updateRightChatProvider:sl,updateRightChatScrollState:ll}=QQ({activeModel:Da,activeProvider:ga,approvals:Ye,applyRightCodexHistoryPayload:ui,codexHistoryEvents:Et,connectedAppMentions:rn,connection:U,contextCompaction:ht.contextCompaction,openLabTraining:Nr,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:D,pendingChatUserMessages:Be,providerSettings:f?.providers??null,rightChatHistoryEvents:h,rightChatPanels:ke,rightPanelMode:je,runtimeIndexes:st,runtimeEventStore:he,runningSessionIds:Jn,selectedSession:Pe,selectedSessionId:j,sendPrompt:Ua,setDiffPanelOpen:tt,setError:at,setRightChatHistoryEvents:g,setRightChatPanels:Ge,setRightPanelMode:ze,setRightPanelTabRequest:l,setView:De,showChangesPanel:Mr,showToast:lt,sidebarSessions:Xe,startupReady:W.ready}),la=v.useCallback(()=>{xe(null),L("profile"),De("settings"),Xt({kind:"settings",section:"profile"})},[xe,L,De]),Lr=v.useMemo(()=>qo(f?.diagnostics??dX,Y.filter(ct=>ct.name==="diagnostic")),[f?.diagnostics,Y]),cl=v.useCallback(()=>{if(le){tt(!1);return}if(C==="labs"){ze("changes"),l({id:Date.now(),tab:"summary"}),tt(!0);return}ze("home"),tt(!0)},[le,tt,ze,l,C]);return{title:Sa,browserConversationId:Zn,handleWorkspaceDiffPanelViewStateChange:li,openSessionInChat:Ni,openExistingProjectPathDialog:ci,removeProject:Fs,changeProjectTarget:el,submitNewProjectDialog:Or,changeWorkspaceBranch:Sr,openCommitDialog:Vs,openCreateWorkspaceBranchDialog:To,openDefaultsSettingsFromBranchDialog:Ks,runWorkspaceTool:xr,submitCommitDialog:kr,submitCreateWorkspaceBranch:wr,syncWorkspaceLocally:Ws,subagentDelegationDefaultMode:io,subagentDelegationMode:Js,subagentDelegationAvailable:Ir,changeSubagentDelegationMode:_r,answerCreateImproveQuestion:Cr,applyCreateImproveCandidate:sa,approveCreateImproveRun:Zs,cancelCreateImproveRun:Li,changeDraftProvider:Eo,openCreateImprovePullRequest:Yn,reconcileCreateImprovePullRequest:Ys,rejectCreateImproveCandidate:Qs,pauseCreateImproveRun:Sn,resumeCreateImproveRun:mi,reviseCreateImproveRun:xa,sendPrompt:Ua,stopTurn:Hi,archiveSession:pi,restoreSession:Xs,renameSession:Rr,toggleProjectPinned:Ui,toggleSessionPinned:Mo,toggleSessionSavedForLater:fi,moveProjectToCloud:Pr,startCloudSetupUpload:Ar,changeWorkspaceTarget:ka,switchProjectWorkspaceTarget:wa,sendPromptFromMainComposer:Tr,openSandboxWorkspace:qi,createCloudEnvironmentFromSidebar:ro,openCloudProjectDialog:zi,openUrlInBrowserPanel:jo,showBrowserPanel:Er,showChangesPanel:Mr,showGoalSidebarTab:jr,rightChatTrainingLaunchRequest:tl,setRightChatTrainingLaunchRequest:gi,closeRightChatPanel:so,openRightChatPanel:nl,rightChatPanelViews:al,showRightChatPanel:ol,showRightPanelDiffTab:il,submitRightChatPrompt:lo,activateRightChatPanel:Bi,updateRightChatModel:Dr,updateRightChatPrompt:rl,updateRightChatProvider:sl,updateRightChatScrollState:ll,openProfileSettings:la,diagnosticEvents:Lr,toggleRightSidebar:cl}}const mX=pA();function pX(){return k.jsx(AP,{client:mX,children:k.jsx(fX,{})})}function fX(){const e=HY(),t=uX(e);return k.jsx(d8,{primary:e,secondary:t})}const qte=Object.freeze(Object.defineProperty({__proto__:null,App:pX},Symbol.toStringTag,{value:"Module"}));export{lte as $,B3 as A,H0 as B,ai as C,IV as D,Mee as E,sC as F,pC as G,rc as H,gu as I,QV as J,G6 as K,xx as L,Xi as M,_b as N,b9 as O,uV as P,Un as Q,Ete as R,U0 as S,SR as T,dte as U,Nte as V,ji as W,$c as X,Ote as Y,Oh as Z,Nee as _,V0 as a,Hh as a$,R8 as a0,Ute as a1,fQ as a2,ste as a3,cte as a4,wte as a5,vte as a6,iW as a7,Fa as a8,_W as a9,zo as aA,ER as aB,Yee as aC,QW as aD,EZ as aE,Zee as aF,WW as aG,kte as aH,TZ as aI,Ca as aJ,Io as aK,bP as aL,KQ as aM,WQ as aN,BY as aO,Qee as aP,WV as aQ,Fv as aR,oC as aS,cm as aT,pte as aU,nb as aV,qV as aW,Aee as aX,sS as aY,uC as aZ,eW as a_,Xr as aa,XS as ab,gte as ac,gx as ad,Qh as ae,Dd as af,K6 as ag,mte as ah,Ih as ai,vu as aj,Z9 as ak,OR as al,j6 as am,dm as an,X6 as ao,hV as ap,cC as aq,HX as ar,fte as as,hte as at,Tte as au,N6 as av,Y6 as aw,vf as ax,z as ay,qt as az,V7 as b,Bee as b$,b8 as b0,Dte as b1,u8 as b2,gS as b3,fm as b4,tW as b5,bb as b6,RC as b7,L6 as b8,jee as b9,Lte as bA,Sm as bB,aV as bC,Mu as bD,Vv as bE,iC as bF,Oc as bG,ete as bH,ite as bI,rte as bJ,bS as bK,nte as bL,Tf as bM,ote as bN,ate as bO,tte as bP,vS as bQ,Xee as bR,Mt as bS,t$ as bT,LX as bU,bR as bV,UX as bW,_ee as bX,lf as bY,DX as bZ,zee as b_,Oee as ba,SO as bb,YW as bc,ZW as bd,lC as be,tV as bf,mg as bg,$ee as bh,Dee as bi,pV as bj,rC as bk,NX as bl,kg as bm,Tee as bn,um as bo,Kv as bp,Xt as bq,wV as br,jR as bs,na as bt,$X as bu,hg as bv,gg as bw,vd as bx,OX as by,g6 as bz,dt as c,$w as c$,Fee as c0,Vee as c1,zV as c2,Uee as c3,qee as c4,GP as c5,bX as c6,vX as c7,dc as c8,Ap as c9,T as cA,u as cB,b as cC,XH as cD,vt as cE,Hs as cF,Bu as cG,$H as cH,Tt as cI,qw as cJ,oU as cK,Uw as cL,qH as cM,Nw as cN,NH as cO,FH as cP,YH as cQ,GH as cR,G as cS,A as cT,Dw as cU,WX as cV,KX as cW,zX as cX,qX as cY,DH as cZ,UH as c_,Hl as ca,YP as cb,Mn as cc,ea as cd,Tx as ce,uA as cf,yX as cg,mk as ch,ev as ci,VX as cj,oi as ck,VH as cl,kw as cm,BX as cn,_t as co,c as cp,Vu as cq,Ku as cr,kt as cs,p as ct,Vt as cu,i as cv,Fu as cw,S as cx,Ce as cy,F as cz,cZ as d,nee as d$,nU as d0,tU as d1,QH as d2,Hw as d3,tv as d4,Lw as d5,Wu as d6,Gu as d7,aU as d8,WH as d9,Ic as dA,QX as dB,bte as dC,yte as dD,FX as dE,Gee as dF,dee as dG,uee as dH,Wv as dI,Lv as dJ,pee as dK,Wa as dL,GX as dM,fU as dN,xv as dO,BB as dP,tee as dQ,iee as dR,oee as dS,aee as dT,mee as dU,JX as dV,Jw as dW,gr as dX,Wn as dY,Vq as dZ,AU as d_,Jee as da,hee as db,Ree as dc,Fe as dd,wn as de,to as df,fa as dg,$v as dh,qv as di,yee as dj,vee as dk,See as dl,bee as dm,xee as dn,ZX as dp,A3 as dq,gee as dr,jc as ds,YX as dt,ou as du,Xg as dv,oe as dw,se as dx,wo as dy,kee as dz,mA as e,D5 as e0,Ec as e1,ree as e2,cee as e3,lee as e4,see as e5,x5 as e6,tI as e7,PV as e8,gs as e9,OC as eA,Lee as eB,lc as eC,wee as eD,Iee as eE,Hee as eF,Pee as eG,qte as eH,Za as ea,$V as eb,Cee as ec,XX as ed,eee as ee,mm as ef,Ste as eg,xte as eh,Wee as ei,C6 as ej,hx as ek,zY as el,Lh as em,mR as en,JC as eo,uR as ep,Hte as eq,Cte as er,Ite as es,_te as et,nY as eu,cX as ev,Rte as ew,Pte as ex,Ate as ey,q0 as ez,dr as f,S6 as g,Uo as h,lm as i,XV as j,ute as k,Kee as l,Bv as m,aQ as n,Mte as o,$te as p,hP as q,_C as r,J3 as s,jte as t,_x as u,Dc as v,Q as w,Lc as x,eK as y,Eee as z};
|