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
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalOverlay-DaonK5C0.js","assets/index-DIaKfM8a.js","assets/index-1cMIFBxZ.css","assets/TerminalOverlay-DwBiZLwk.css","assets/CommandMenu-D-M-xomh.js","assets/CommandMenu-Cb3vNGJr.css","assets/SettingsView-0KMs-r2I.js","assets/save-CX2kF74j.js","assets/MarkdownText-BxPHz4je.js","assets/folder-open-B9ixJQJX.js","assets/play-C1XWyKh6.js","assets/wifi-off-DbDXaV1N.js","assets/useLocalAgentSchedules-BHxWmOeC.js","assets/cloud-upload-Dv6kFnfC.js","assets/git-commit-horizontal-C1lQvfxe.js","assets/folder-plus-DqSKvtNB.js","assets/AppDialog-CaxeNfsu.js","assets/WorkspaceDiffPanel-CThoTqe4.js","assets/training-model-data-CKOkpBBL.js","assets/info-BEvaynAD.js","assets/minimize-2-DT8t8wwP.js","assets/clipboard-DDIvAWKp.js","assets/SettingsView-CVsuQeCZ.css","assets/git-dialogs-C-F47S10.css","assets/NewProjectDialog-CS6sw2oD.js","assets/monitor-DGqnfsK9.js","assets/WorkspaceGitDialogs-CBarJYF-.js","assets/upload-giKOPnl1.js","assets/WorkspaceEnvironmentMenu-DeODKxvW.js","assets/square-DMkXeYeV.js","assets/WorkspaceEnvironmentMenu-DGIFdG3o.css","assets/MainPane-DJcd4tPk.js","assets/arrow-up-right-BV2IHfb9.js","assets/MainPane-DOWsSew1.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as y,j as x,a as ST,_ as Go}from"./index-DIaKfM8a.js";const Vk=y.createContext(void 0),Kk=e=>{const t=y.useContext(Vk);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},xT=({client:e,children:t})=>(y.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),x.jsx(Vk.Provider,{value:e,children:t})),kT={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var wT=class{#e=kT;#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 vr=new wT;function IT(e){setTimeout(e,0)}const _T=typeof window>"u"||"Deno"in globalThis;function la(){}function CT(e,t){return typeof e=="function"?e(t):e}function Wk(e){return typeof e=="number"&&e>=0&&e!==1/0}function Gk(e,t){return Math.max(e+(t||0)-Date.now(),0)}function un(e,t){return typeof e=="function"?e(t):e}function Dy(e,t){const{type:n="all",exact:a,fetchStatus:o,predicate:r,queryKey:s,stale:c}=e;if(s){if(a){if(t.queryHash!==ov(s,t.options))return!1}else if(!Bs(t.queryKey,s))return!1}if(n!=="all"){const m=t.isActive();if(n==="active"&&!m||n==="inactive"&&m)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||o&&o!==t.state.fetchStatus||r&&!r(t))}function Hy(e,t){const{exact:n,status:a,predicate:o,mutationKey:r}=e;if(r){if(!t.options.mutationKey)return!1;if(n){if(gc(t.options.mutationKey)!==gc(r))return!1}else if(!Bs(t.options.mutationKey,r))return!1}return!(a&&t.state.status!==a||o&&!o(t))}function ov(e,t){return(t?.queryKeyHashFn||gc)(e)}function gc(e){return JSON.stringify(e,(t,n)=>Yh(n)?Object.keys(n).sort().reduce((a,o)=>(a[o]=n[o],a),{}):n)}function Bs(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(!Bs(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!Bs(e[a],t[a]))return!1;return!0}return!1}const RT=Object.prototype.hasOwnProperty;function Jk(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Ly(e)&&Ly(t);if(!a&&!(Yh(e)&&Yh(t)))return t;const o=(a?e:Object.keys(e)).length,r=a?t:Object.keys(t),s=r.length,c=a?new Array(s):{};let m=0;for(let u=0;u<s;u++){const f=a?u:r[u],g=e[f],S=t[f];if(g===S){c[f]=g,(a?u<o:RT.call(e,f))&&m++;continue}if(g===null||S===null||typeof g!="object"||typeof S!="object"){c[f]=S;continue}const k=Jk(g,S,n+1);c[f]=k,k===g&&m++}return o===s&&m===o?e:c}function Rf(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 Ly(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Yh(e){if(!qy(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!qy(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function qy(e){return Object.prototype.toString.call(e)==="[object Object]"}function PT(e){return new Promise(t=>{vr.setTimeout(t,e)})}function Qh(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Jk(e,t):t}function AT(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function TT(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const rv=Symbol();function Zk(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===rv?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Yk(e,t){return typeof e=="function"?e(...t):!!e}function ET(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 jT=()=>_T;const sv=()=>jT();var Fc=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(){}},MT=class extends Fc{#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 lv=new MT,OT=IT;function $T(){let e=[],t=0,n=c=>{c()},a=c=>{c()},o=OT;const r=c=>{t?e.push(c):o(()=>{n(c)})},s=()=>{const c=e;e=[],c.length&&o(()=>{a(()=>{c.forEach(m=>{n(m)})})})};return{batch:c=>{let m;t++;try{m=c()}finally{t--,t||s()}return m},batchCalls:c=>(...m)=>{r(()=>{c(...m)})},schedule:r,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{a=c},setScheduler:c=>{o=c}}}const Ln=$T();var NT=class extends Fc{#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 Lu=new NT;function DT(e){return Math.min(1e3*2**e,3e4)}function Qk(e){return(e??"online")==="online"?Lu.isOnline():!0}var Xh=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Xk(e){let t=!1,n=0,a,o="pending",r,s;const c=new Promise(($,O)=>{r=$,s=O});c.catch(la);const m=()=>o!=="pending",u=$=>{if(!m()){const O=new Xh($);P(O),e.onCancel?.(O)}},f=()=>{t=!0},g=()=>{t=!1},S=()=>lv.isFocused()&&(e.networkMode==="always"||Lu.isOnline())&&e.canRun(),k=()=>Qk(e.networkMode)&&e.canRun(),C=$=>{m()||(a?.(),o="resolved",r($))},P=$=>{m()||(a?.(),o="rejected",s($))},j=()=>new Promise($=>{a=O=>{(m()||S())&&$(O)},e.onPause?.()}).then(()=>{a=void 0,m()||e.onContinue?.()}),R=()=>{if(m())return;let $;const O=n===0?e.initialPromise:void 0;try{$=O??e.fn()}catch(M){$=Promise.reject(M)}Promise.resolve($).then(C).catch(M=>{if(m())return;const w=e.retry??(sv()?0:3),A=e.retryDelay??DT,E=typeof A=="function"?A(n,M):A,D=w===!0||typeof w=="number"&&n<w||typeof w=="function"&&w(n,M);if(t||!D){P(M);return}n++,e.onFail?.(n,M),PT(E).then(()=>S()?void 0:j()).then(()=>{t?P(M):R()})})};return{promise:c,status:()=>o,cancel:u,continue:()=>(a?.(),c),cancelRetry:f,continueRetry:g,canStart:k,start:()=>(k()?R():j().then(R),c)}}var ew=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Wk(this.gcTime)&&(this.#e=vr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(sv()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(vr.clearTimeout(this.#e),this.#e=void 0)}};function HT(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 c={pages:[],pageParams:[]},m=0;const u=async()=>{let f=!1;const g=C=>{ET(C,()=>t.signal,()=>f=!0)},S=Zk(t.options,t.fetchOptions),k=async(C,P,j)=>{if(f)return Promise.reject(t.signal.reason);if(P==null&&C.pages.length)return Promise.resolve(C);const $=(()=>{const A={client:t.client,queryKey:t.queryKey,pageParam:P,direction:j?"backward":"forward",meta:t.options.meta};return g(A),A})(),O=await S($),{maxPages:M}=t.options,w=j?TT:AT;return{pages:w(C.pages,O,M),pageParams:w(C.pageParams,P,M)}};if(o&&r.length){const C=o==="backward",P=C?tw:eg,j={pages:r,pageParams:s};c=await k(j,P(a,j),C)}else{const C=e??r.length;do{const P=m===0?s[0]??a.initialPageParam:eg(a,c);if(m>0&&P==null)break;c=await k(c,P),m++}while(m<C)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function eg(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 tw(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Wne(e,t){return t?eg(e,t)!=null:!1}function Gne(e,t){return!t||!e.getPreviousPageParam?!1:tw(e,t)!=null}var LT=class extends ew{#e;#t;#n;#a;#o;#i;#r;#l;constructor(e){super(),this.#l=!1,this.#r=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#o=e.client,this.#a=this.#o.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=zy(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.#i?.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=zy(this.options);t.data!==void 0&&(this.setState(Uy(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=Qh(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.#i?.promise;return this.#i?.cancel(e),t?t.then(la).catch(la):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=>un(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===rv||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>un(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:!Gk(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.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.#i&&(this.#l||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#i.cancel({revert:!0}):this.#i.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.#i?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(e&&this.setOptions(e),!this.options.queryFn){const m=this.observers.find(u=>u.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=Zk(this.options,t),f=(()=>{const g={client:this.#o,queryKey:this.queryKey,meta:this.meta};return a(g),g})();return this.#l=!1,this.options.persister?this.options.persister(m,f,this):m(f)},s=(()=>{const m={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#o,state:this.state,fetchFn:o};return a(m),m})();(this.#e==="infinite"?HT(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 c=this.#i=Xk({initialPromise:t?.initialPromise,fn:s.fetchFn,onCancel:m=>{m instanceof Xh&&m.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(m,u)=>{this.#s({type:"failed",failureCount:m,error:u})},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 c.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 Xh){if(m.silent)return this.#i.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.#i===c&&(this.#i=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,...nw(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Uy(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),Ln.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function nw(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Qk(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Uy(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function zy(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 qT=class extends Fc{#e;#t=void 0;#n=void 0;#a=void 0;#o;#i;#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),By(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return tg(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return tg(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 un(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&&!Rf(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&Fy(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||un(this.options.enabled,this.#t)!==un(t.enabled,this.#t)||un(this.options.staleTime,this.#t)!==un(t.staleTime,this.#t))&&this.#g();const o=this.#v();a&&(this.#t!==n||un(this.options.enabled,this.#t)!==un(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 Rf(this.getCurrentResult(),n)||(this.#a=n,this.#i=this.options,this.#o=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(c=>{c.type==="updated"&&c.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(la)),t}#h(e){return!sv()&&un(this.options.enabled,this.#t)!==!1&&Wk(e)}#g(){this.#S();const e=un(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=Gk(this.#a.dataUpdatedAt,e)+1;this.#d=vr.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=vr.setInterval(()=>{(this.options.refetchIntervalInBackground||lv.isFocused())&&this.#m()},this.#c))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(vr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(vr.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,o=this.#a,r=this.#o,s=this.#i,c=e!==n?e.state:this.#n,{state:m}=e;let u={...m},f=!1,g;if(t._optimisticResults){const w=this.hasListeners(),A=!w&&By(e,t),E=w&&Fy(e,n,t,a);(A||E)&&(u={...u,...nw(m.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:S,errorUpdatedAt:k,status:C}=u;g=u.data;let P=!1;if(t.placeholderData!==void 0&&g===void 0&&C==="pending"){let w;o?.isPlaceholderData&&t.placeholderData===s?.placeholderData?(w=o.data,P=!0):w=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,w!==void 0&&(C="success",g=Qh(o?.data,w,t),f=!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=Qh(o?.data,g,t),this.#s=g,this.#r=null}catch(w){this.#r=w}else g===void 0&&(this.#r=null);this.#r&&(S=this.#r,g=this.#s,k=Date.now(),C="error",f=!1);const j=u.fetchStatus==="fetching",R=C==="pending",$=C==="error",O=R&&j,M=g!==void 0;return{status:C,fetchStatus:u.fetchStatus,isPending:R,isSuccess:C==="success",isError:$,isInitialLoading:O,isLoading:O,data:g,dataUpdatedAt:u.dataUpdatedAt,error:S,errorUpdatedAt:k,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:u.dataUpdateCount>c.dataUpdateCount||u.errorUpdateCount>c.errorUpdateCount,isFetching:j,isRefetching:j&&!R,isLoadingError:$&&!M,isPaused:u.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:$&&M,isStale:cv(e,t),refetch:this.refetch,isEnabled:un(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#o=this.#t.state,this.#i=this.options,this.#o.data!==void 0&&(this.#p=this.#t),Rf(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(c=>{const m=c;return this.#a[m]!==e[m]&&s.has(m)})})();Ln.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 UT(e,t){return un(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&un(t.retryOnMount,e)===!1)}function By(e,t){return UT(e,t)||e.state.data!==void 0&&tg(e,t,t.refetchOnMount)}function tg(e,t,n){if(un(t.enabled,e)!==!1&&un(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&cv(e,t)}return!1}function Fy(e,t,n,a){return(e!==t||un(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&cv(e,n)}function cv(e,t){return un(t.enabled,e)!==!1&&e.isStaleByTime(un(t.staleTime,e))}var zT=class extends ew{#e;#t;#n;#a;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#n=t.mutationCache,this.#t=[],this.state=t.state||BT(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#n.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(n=>n!==t),this.scheduleGc(),this.#n.notify({type:"observerRemoved",mutation:this,observer:t})}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(t){const n=()=>{this.#o({type:"continue"})},a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},o=this.#a=Xk({fn:()=>this.options.mutationFn?this.options.mutationFn(t,a):Promise.reject(new Error("No mutationFn found")),onFail:(c,m)=>{this.#o({type:"failed",failureCount:c,error:m})},onPause:()=>{this.#o({type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),r=this.state.status==="pending",s=!o.canStart();try{if(r)n();else{this.#o({type:"pending",variables:t,isPaused:s}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,a);const m=await this.options.onMutate?.(t,a);m!==this.state.context&&this.#o({type:"pending",context:m,variables:t,isPaused:s})}const c=await o.start();return await this.#n.config.onSuccess?.(c,t,this.state.context,this,a),await this.options.onSuccess?.(c,t,this.state.context,a),await this.#n.config.onSettled?.(c,null,this.state.variables,this.state.context,this,a),await this.options.onSettled?.(c,null,t,this.state.context,a),this.#o({type:"success",data:c}),c}catch(c){try{await this.#n.config.onError?.(c,t,this.state.context,this,a)}catch(m){Promise.reject(m)}try{await this.options.onError?.(c,t,this.state.context,a)}catch(m){Promise.reject(m)}try{await this.#n.config.onSettled?.(void 0,c,this.state.variables,this.state.context,this,a)}catch(m){Promise.reject(m)}try{await this.options.onSettled?.(void 0,c,t,this.state.context,a)}catch(m){Promise.reject(m)}throw this.#o({type:"error",error:c}),c}finally{this.#a===o&&(this.#a=void 0),this.#n.runNext(this)}}#o(t){const n=a=>{switch(t.type){case"failed":return{...a,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...a,isPaused:!0};case"continue":return{...a,isPaused:!1};case"pending":return{...a,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...a,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...a,data:void 0,error:t.error,failureCount:a.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Ln.batch(()=>{this.#t.forEach(a=>{a.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function BT(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var FT=class extends Fc{#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 zT({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=Fd(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=Fd(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=Fd(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=Fd(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Ln.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=>Hy(t,n))}findAll(e={}){return this.getAll().filter(t=>Hy(e,t))}notify(e){Ln.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Ln.batch(()=>Promise.all(e.map(t=>t.continue().catch(la))))}};function Fd(e){return e.options.scope?.id}var VT=class extends Fc{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,o=t.queryHash??ov(a,t);let r=this.get(o);return r||(r=new LT({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(){Ln.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=>Dy(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Dy(e,n)):t}notify(e){Ln.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Ln.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Ln.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},KT=class{#e;#t;#n;#a;#o;#i;#r;#l;constructor(e={}){this.#e=e.queryCache||new VT,this.#t=e.mutationCache||new FT,this.#n=e.defaultOptions||{},this.#a=new Map,this.#o=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#r=lv.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#l=Lu.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===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(un(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=CT(t,o);if(r!==void 0)return this.#e.build(this,a).setData(r,{...n,manual:!0})}setQueriesData(e,t,n){return Ln.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;Ln.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Ln.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=Ln.batch(()=>this.#e.findAll(e).map(o=>o.cancel(n)));return Promise.all(a).then(la).catch(la)}invalidateQueries(e,t={}){return Ln.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=Ln.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(la)),o.state.fetchStatus==="paused"?Promise.resolve():r}));return Promise.all(a).then(la)}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(un(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(un(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(la).catch(la)}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(la).catch(la)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return Lu.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(gc(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{Bs(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#o.set(gc(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#o.values()],n={};return t.forEach(a=>{Bs(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=ov(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===rv&&(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 aw=y.createContext(!1),WT=()=>y.useContext(aw);aw.Provider;function GT(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const JT=y.createContext(GT()),ZT=()=>y.useContext(JT),YT=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?Yk(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},QT=e=>{y.useEffect(()=>{e.clearReset()},[e])},XT=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(o&&e.data===void 0||Yk(n,[e.error,a])),eE=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))}},tE=(e,t)=>e?.suspense&&t.isPending,nE=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function aE(e,t,n){const a=WT(),o=ZT(),r=Kk(),s=r.defaultQueryOptions(e),c=r.getQueryCache().get(s.queryHash),m=e.subscribed!==!1;s._optimisticResults=a?"isRestoring":m?"optimistic":void 0,eE(s),YT(s,o,c),QT(o);const[u]=y.useState(()=>new t(r,s)),f=u.getOptimisticResult(s),g=!a&&m;if(y.useSyncExternalStore(y.useCallback(S=>{const k=g?u.subscribe(Ln.batchCalls(S)):la;return u.updateResult(),k},[u,g]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),y.useEffect(()=>{u.setOptions(s)},[s,u]),tE(s,f))throw nE(s,u,o);if(XT({result:f,errorResetBoundary:o,throwOnError:s.throwOnError,query:c,suspense:s.suspense}))throw f.error;return s.notifyOnChangeProps?f:u.trackResult(f)}function iw(e,t){return aE(e,qT)}function iE(){return new KT({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}var Vy;function ve(e,t,n){function a(c,m){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:m,constr:s,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,m);const u=s.prototype,f=Object.keys(u);for(let g=0;g<f.length;g++){const S=f[g];S in c||(c[S]=u[S].bind(c))}}const o=n?.Parent??Object;class r extends o{}Object.defineProperty(r,"name",{value:e});function s(c){var m;const u=n?.Parent?new r:this;a(u,c),(m=u._zod).deferred??(m.deferred=[]);for(const f of u._zod.deferred)f();return u}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class Ds extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ow extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Vy=globalThis).__zod_globalConfig??(Vy.__zod_globalConfig={});const dv=globalThis.__zod_globalConfig;function vo(e){return dv}function rw(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 ng(e,t){return typeof t=="bigint"?t.toString():t}function ym(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function uv(e){return e==null}function mv(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function oE(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 Ky=Symbol("evaluating");function At(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==Ky)return a===void 0&&(a=Ky,a=n()),a},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Or(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Jo(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function Wy(e){return JSON.stringify(e)}function rE(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const sw="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function vc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const sE=ym(()=>{if(dv.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Fs(e){if(vc(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(vc(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function lw(e){return Fs(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const lE=new Set(["string","number","symbol"]);function Vs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zo(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 cE(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const dE={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 uE(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=Jo(e._zod.def,{get shape(){const s={};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(s[c]=n.shape[c])}return Or(this,"shape",s),s},checks:[]});return Zo(e,r)}function mE(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=Jo(e._zod.def,{get shape(){const s={...e._zod.def.shape};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete s[c]}return Or(this,"shape",s),s},checks:[]});return Zo(e,r)}function pE(e,t){if(!Fs(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=Jo(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Or(this,"shape",r),r}});return Zo(e,o)}function fE(e,t){if(!Fs(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Jo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Or(this,"shape",a),a}});return Zo(e,n)}function hE(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=Jo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Or(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Zo(e,n)}function gE(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=Jo(t._zod.def,{get shape(){const c=t._zod.def.shape,m={...c};if(n)for(const u in n){if(!(u in c))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(m[u]=e?new e({type:"optional",innerType:c[u]}):c[u])}else for(const u in c)m[u]=e?new e({type:"optional",innerType:c[u]}):c[u];return Or(this,"shape",m),m},checks:[]});return Zo(t,s)}function vE(e,t,n){const a=Jo(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 Or(this,"shape",r),r}});return Zo(t,a)}function ks(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 bE(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 ws(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function Vd(e){return typeof e=="string"?e:e?.message}function bo(e,t,n){const a=e.message?e.message:Vd(e.inst?._zod.def?.error?.(e))??Vd(t?.error?.(e))??Vd(n.customError?.(e))??Vd(n.localeError?.(e))??"Invalid input",{inst:o,continue:r,input:s,...c}=e;return c.path??(c.path=[]),c.message=a,t?.reportInput&&(c.input=s),c}function pv(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function bc(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const cw=(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,ng,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},dw=ve("$ZodError",cw),uw=ve("$ZodError",cw,{Parent:Error});function yE(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 SE(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(c=>a({issues:c},[...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 c=[...r,...s.path];if(c.length===0)n._errors.push(t(s));else{let m=n,u=0;for(;u<c.length;){const f=c[u];u===c.length-1?(m[f]=m[f]||{_errors:[]},m[f]._errors.push(t(s))):m[f]=m[f]||{_errors:[]},m=m[f],u++}}}};return a(e),n}const fv=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 Ds;if(s.issues.length){const c=new(o?.Err??e)(s.issues.map(m=>bo(m,r,vo())));throw sw(c,o?.callee),c}return s.value},hv=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 c=new(o?.Err??e)(s.issues.map(m=>bo(m,r,vo())));throw sw(c,o?.callee),c}return s.value},Sm=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 Ds;return r.issues.length?{success:!1,error:new(e??dw)(r.issues.map(s=>bo(s,o,vo())))}:{success:!0,data:r.value}},xE=Sm(uw),xm=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=>bo(s,o,vo())))}:{success:!0,data:r.value}},kE=xm(uw),wE=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return fv(e)(t,n,o)},IE=e=>(t,n,a)=>fv(e)(t,n,a),_E=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return hv(e)(t,n,o)},CE=e=>async(t,n,a)=>hv(e)(t,n,a),RE=e=>(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return Sm(e)(t,n,o)},PE=e=>(t,n,a)=>Sm(e)(t,n,a),AE=e=>async(t,n,a)=>{const o=a?{...a,direction:"backward"}:{direction:"backward"};return xm(e)(t,n,o)},TE=e=>async(t,n,a)=>xm(e)(t,n,a),EE=/^[cC][0-9a-z]{6,}$/,jE=/^[0-9a-z]+$/,ME=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,OE=/^[0-9a-vA-V]{20}$/,$E=/^[A-Za-z0-9]{27}$/,NE=/^[a-zA-Z0-9_-]{21}$/,DE=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,HE=/^([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})$/,Gy=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)$/,LE=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,qE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function UE(){return new RegExp(qE,"u")}const zE=/^(?:(?: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])$/,BE=/^(([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}|:))$/,FE=/^((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])$/,VE=/^(([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])$/,KE=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mw=/^[A-Za-z0-9_-]*$/,WE=/^https?$/,GE=/^\+[1-9]\d{6,14}$/,pw="(?:(?:\\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])))",JE=new RegExp(`^${pw}$`);function fw(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 ZE(e){return new RegExp(`^${fw(e)}$`)}function YE(e){const t=fw({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(`^${pw}T(?:${a})$`)}const QE=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},XE=/^-?\d+$/,hw=/^-?\d+(?:\.\d+)?$/,ej=/^(?:true|false)$/i,tj=/^null$/i,nj=/^[^A-Z]*$/,aj=/^[^a-z]*$/,fa=ve("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gw={number:"number",bigint:"bigint",object:"date"},vw=ve("$ZodCheckLessThan",(e,t)=>{fa.init(e,t);const n=gw[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})}}),bw=ve("$ZodCheckGreaterThan",(e,t)=>{fa.init(e,t);const n=gw[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})}}),ij=ve("$ZodCheckMultipleOf",(e,t)=>{fa.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):oE(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})}}),oj=ve("$ZodCheckNumberFormat",(e,t)=>{fa.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[o,r]=dE[t.format];e._zod.onattach.push(s=>{const c=s._zod.bag;c.format=t.format,c.minimum=o,c.maximum=r,n&&(c.pattern=XE)}),e._zod.check=s=>{const c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,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:c,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}}c<o&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),c>r&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),rj=ve("$ZodCheckMaxLength",(e,t)=>{var n;fa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!uv(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=pv(o);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),sj=ve("$ZodCheckMinLength",(e,t)=>{var n;fa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!uv(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=pv(o);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),lj=ve("$ZodCheckLengthEquals",(e,t)=>{var n;fa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const o=a.value;return!uv(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=pv(o),c=r>t.length;a.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),km=ve("$ZodCheckStringFormat",(e,t)=>{var n,a;fa.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=()=>{})}),cj=ve("$ZodCheckRegex",(e,t)=>{km.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})}}),dj=ve("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=nj),km.init(e,t)}),uj=ve("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=aj),km.init(e,t)}),mj=ve("$ZodCheckIncludes",(e,t)=>{fa.init(e,t);const n=Vs(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})}}),pj=ve("$ZodCheckStartsWith",(e,t)=>{fa.init(e,t);const n=new RegExp(`^${Vs(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})}}),fj=ve("$ZodCheckEndsWith",(e,t)=>{fa.init(e,t);const n=new RegExp(`.*${Vs(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})}}),hj=ve("$ZodCheckOverwrite",(e,t)=>{fa.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class gj{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 vj={major:4,minor:4,patch:3},an=ve("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=vj;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,c,m)=>{let u=ks(s),f;for(const g of c){if(g._zod.def.when){if(bE(s)||!g._zod.def.when(s))continue}else if(u)continue;const S=s.issues.length,k=g._zod.check(s);if(k instanceof Promise&&m?.async===!1)throw new Ds;if(f||k instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await k,s.issues.length!==S&&(u||(u=ks(s,S)))});else{if(s.issues.length===S)continue;u||(u=ks(s,S))}}return f?f.then(()=>s):s},r=(s,c,m)=>{if(ks(s))return s.aborted=!0,s;const u=o(c,a,m);if(u instanceof Promise){if(m.async===!1)throw new Ds;return u.then(f=>e._zod.parse(f,m))}return e._zod.parse(u,m)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){const u=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(f=>r(f,s,c)):r(u,s,c)}const m=e._zod.parse(s,c);if(m instanceof Promise){if(c.async===!1)throw new Ds;return m.then(u=>o(u,a,c))}return o(m,a,c)}}At(e,"~standard",()=>({validate:o=>{try{const r=xE(e,o);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return kE(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),gv=ve("$ZodString",(e,t)=>{an.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??QE(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}}),sn=ve("$ZodStringFormat",(e,t)=>{km.init(e,t),gv.init(e,t)}),bj=ve("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=HE),sn.init(e,t)}),yj=ve("$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=Gy(a))}else t.pattern??(t.pattern=Gy());sn.init(e,t)}),Sj=ve("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=LE),sn.init(e,t)}),xj=ve("$ZodURL",(e,t)=>{sn.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===WE.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})}}}),kj=ve("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=UE()),sn.init(e,t)}),wj=ve("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=NE),sn.init(e,t)}),Ij=ve("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=EE),sn.init(e,t)}),_j=ve("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=jE),sn.init(e,t)}),Cj=ve("$ZodULID",(e,t)=>{t.pattern??(t.pattern=ME),sn.init(e,t)}),Rj=ve("$ZodXID",(e,t)=>{t.pattern??(t.pattern=OE),sn.init(e,t)}),Pj=ve("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=$E),sn.init(e,t)}),Aj=ve("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=YE(t)),sn.init(e,t)}),Tj=ve("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=JE),sn.init(e,t)}),Ej=ve("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=ZE(t)),sn.init(e,t)}),jj=ve("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=DE),sn.init(e,t)}),Mj=ve("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=zE),sn.init(e,t),e._zod.bag.format="ipv4"}),Oj=ve("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=BE),sn.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})}}}),$j=ve("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=FE),sn.init(e,t)}),Nj=ve("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=VE),sn.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 yw(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const Dj=ve("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=KE),sn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{yw(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function Hj(e){if(!mw.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return yw(n)}const Lj=ve("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=mw),sn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{Hj(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),qj=ve("$ZodE164",(e,t)=>{t.pattern??(t.pattern=GE),sn.init(e,t)});function Uj(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 zj=ve("$ZodJWT",(e,t)=>{sn.init(e,t),e._zod.check=n=>{Uj(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Sw=ve("$ZodNumber",(e,t)=>{an.init(e,t),e._zod.pattern=e._zod.bag.pattern??hw,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}}),Bj=ve("$ZodNumberFormat",(e,t)=>{oj.init(e,t),Sw.init(e,t)}),Fj=ve("$ZodBoolean",(e,t)=>{an.init(e,t),e._zod.pattern=ej,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}}),Vj=ve("$ZodNull",(e,t)=>{an.init(e,t),e._zod.pattern=tj,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}}),Kj=ve("$ZodUnknown",(e,t)=>{an.init(e,t),e._zod.parse=n=>n}),Wj=ve("$ZodNever",(e,t)=>{an.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Jy(e,t,n){e.issues.length&&t.issues.push(...ws(n,e.issues)),t.value[n]=e.value}const Gj=ve("$ZodArray",(e,t)=>{an.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 c=o[s],m=t.element._zod.run({value:c,issues:[]},a);m instanceof Promise?r.push(m.then(u=>Jy(u,n,s))):Jy(m,n,s)}return r.length?Promise.all(r).then(()=>n):n}});function qu(e,t,n,a,o,r){const s=n in a;if(e.issues.length){if(o&&r&&!s)return;t.issues.push(...ws(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 xw(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=cE(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function kw(e,t,n,a,o,r){const s=[],c=o.keySet,m=o.catchall._zod,u=m.def.type,f=m.optin==="optional",g=m.optout==="optional";for(const S in t){if(S==="__proto__"||c.has(S))continue;if(u==="never"){s.push(S);continue}const k=m.run({value:t[S],issues:[]},a);k instanceof Promise?e.push(k.then(C=>qu(C,n,S,t,f,g))):qu(k,n,S,t,f,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 Jj=ve("$ZodObject",(e,t)=>{if(an.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const m={...c};return Object.defineProperty(t,"shape",{value:m}),m}})}const a=ym(()=>xw(t));At(e._zod,"propValues",()=>{const c=t.shape,m={};for(const u in c){const f=c[u]._zod;if(f.values){m[u]??(m[u]=new Set);for(const g of f.values)m[u].add(g)}}return m});const o=vc,r=t.catchall;let s;e._zod.parse=(c,m)=>{s??(s=a.value);const u=c.value;if(!o(u))return c.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),c;c.value={};const f=[],g=s.shape;for(const S of s.keys){const k=g[S],C=k._zod.optin==="optional",P=k._zod.optout==="optional",j=k._zod.run({value:u[S],issues:[]},m);j instanceof Promise?f.push(j.then(R=>qu(R,c,S,u,C,P))):qu(j,c,S,u,C,P)}return r?kw(f,u,c,m,a.value,e):f.length?Promise.all(f).then(()=>c):c}}),Zj=ve("$ZodObjectJIT",(e,t)=>{Jj.init(e,t);const n=e._zod.parse,a=ym(()=>xw(t)),o=S=>{const k=new gj(["shape","payload","ctx"]),C=a.value,P=O=>{const M=Wy(O);return`shape[${M}]._zod.run({ value: input[${M}], issues: [] }, ctx)`};k.write("const input = payload.value;");const j=Object.create(null);let R=0;for(const O of C.keys)j[O]=`key_${R++}`;k.write("const newResult = {};");for(const O of C.keys){const M=j[O],w=Wy(O),A=S[O],E=A?._zod?.optin==="optional",D=A?._zod?.optout==="optional";k.write(`const ${M} = ${P(O)};`),E&&D?k.write(`
|
|
5
|
+
if (${M}.issues.length) {
|
|
6
|
+
if (${w} in input) {
|
|
7
|
+
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
|
|
8
|
+
...iss,
|
|
9
|
+
path: iss.path ? [${w}, ...iss.path] : [${w}]
|
|
10
|
+
})));
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (${M}.value === undefined) {
|
|
15
|
+
if (${w} in input) {
|
|
16
|
+
newResult[${w}] = undefined;
|
|
17
|
+
}
|
|
18
|
+
} else {
|
|
19
|
+
newResult[${w}] = ${M}.value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
`):E?k.write(`
|
|
23
|
+
if (${M}.issues.length) {
|
|
24
|
+
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
|
|
25
|
+
...iss,
|
|
26
|
+
path: iss.path ? [${w}, ...iss.path] : [${w}]
|
|
27
|
+
})));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
if (${M}.value === undefined) {
|
|
31
|
+
if (${w} in input) {
|
|
32
|
+
newResult[${w}] = undefined;
|
|
33
|
+
}
|
|
34
|
+
} else {
|
|
35
|
+
newResult[${w}] = ${M}.value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
`):k.write(`
|
|
39
|
+
const ${M}_present = ${w} in input;
|
|
40
|
+
if (${M}.issues.length) {
|
|
41
|
+
payload.issues = payload.issues.concat(${M}.issues.map(iss => ({
|
|
42
|
+
...iss,
|
|
43
|
+
path: iss.path ? [${w}, ...iss.path] : [${w}]
|
|
44
|
+
})));
|
|
45
|
+
}
|
|
46
|
+
if (!${M}_present && !${M}.issues.length) {
|
|
47
|
+
payload.issues.push({
|
|
48
|
+
code: "invalid_type",
|
|
49
|
+
expected: "nonoptional",
|
|
50
|
+
input: undefined,
|
|
51
|
+
path: [${w}]
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (${M}_present) {
|
|
56
|
+
if (${M}.value === undefined) {
|
|
57
|
+
newResult[${w}] = undefined;
|
|
58
|
+
} else {
|
|
59
|
+
newResult[${w}] = ${M}.value;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
`)}k.write("payload.value = newResult;"),k.write("return payload;");const $=k.compile();return(O,M)=>$(S,O,M)};let r;const s=vc,c=!dv.jitless,u=c&&sE.value,f=t.catchall;let g;e._zod.parse=(S,k)=>{g??(g=a.value);const C=S.value;return s(C)?c&&u&&k?.async===!1&&k.jitless!==!0?(r||(r=o(t.shape)),S=r(S,k),f?kw([],C,S,k,g,e):S):n(S,k):(S.issues.push({expected:"object",code:"invalid_type",input:C,inst:e}),S)}});function Zy(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=>!ks(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=>bo(s,a,vo())))}),t)}const ww=ve("$ZodUnion",(e,t)=>{an.init(e,t),At(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),At(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),At(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),At(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=>mv(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 c of t.options){const m=c._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(c=>Zy(c,a,e,o)):Zy(s,a,e,o)}}),Yj=ve("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,ww.init(e,t);const n=e._zod.parse;At(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[c,m]of Object.entries(s)){o[c]||(o[c]=new Set);for(const u of m)o[c].add(u)}}return o});const a=ym(()=>{const o=t.options,r=new Map;for(const s of o){const c=s._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const m of c){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(!vc(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;const c=a.value.get(s?.[t.discriminator]);return c?c._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)}}),Qj=ve("$ZodIntersection",(e,t)=>{an.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,u])=>Yy(n,m,u)):Yy(n,r,s)}});function ag(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(Fs(e)&&Fs(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=ag(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=ag(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 Yy(e,t,n){const a=new Map;let o;for(const c of t.issues)if(c.code==="unrecognized_keys"){o??(o=c);for(const m of c.keys)a.has(m)||a.set(m,{}),a.get(m).l=!0}else e.issues.push(c);for(const c of n.issues)if(c.code==="unrecognized_keys")for(const m of c.keys)a.has(m)||a.set(m,{}),a.get(m).r=!0;else e.issues.push(c);const r=[...a].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(r.length&&o&&e.issues.push({...o,keys:r}),ks(e))return e;const s=ag(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 Xj=ve("$ZodRecord",(e,t)=>{an.init(e,t),e._zod.parse=(n,a)=>{const o=n.value;if(!Fs(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 c=new Set;for(const u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){c.add(typeof u=="number"?u.toString():u);const f=t.keyType._zod.run({value:u,issues:[]},a);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(k=>bo(k,a,vo())),input:u,path:[u],inst:e});continue}const g=f.value,S=t.valueType._zod.run({value:o[u],issues:[]},a);S instanceof Promise?r.push(S.then(k=>{k.issues.length&&n.issues.push(...ws(u,k.issues)),n.value[g]=k.value})):(S.issues.length&&n.issues.push(...ws(u,S.issues)),n.value[g]=S.value)}let m;for(const u in o)c.has(u)||(m=m??[],m.push(u));m&&m.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:m})}else{n.value={};for(const c of Reflect.ownKeys(o)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,c))continue;let m=t.keyType._zod.run({value:c,issues:[]},a);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&hw.test(c)&&m.issues.length){const g=t.keyType._zod.run({value:Number(c),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[c]=o[c]:n.issues.push({code:"invalid_key",origin:"record",issues:m.issues.map(g=>bo(g,a,vo())),input:c,path:[c],inst:e});continue}const f=t.valueType._zod.run({value:o[c],issues:[]},a);f instanceof Promise?r.push(f.then(g=>{g.issues.length&&n.issues.push(...ws(c,g.issues)),n.value[m.value]=g.value})):(f.issues.length&&n.issues.push(...ws(c,f.issues)),n.value[m.value]=f.value)}}return r.length?Promise.all(r).then(()=>n):n}}),eM=ve("$ZodEnum",(e,t)=>{an.init(e,t);const n=rw(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(o=>lE.has(typeof o)).map(o=>typeof o=="string"?Vs(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}}),tM=ve("$ZodLiteral",(e,t)=>{if(an.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"?Vs(a):a?Vs(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}}),nM=ve("$ZodTransform",(e,t)=>{an.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new ow(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 Ds;return n.value=o,n.fallback=!0,n}});function Qy(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Iw=ve("$ZodOptional",(e,t)=>{an.init(e,t),e._zod.optin="optional",e._zod.optout="optional",At(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),At(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mv(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=>Qy(s,o)):Qy(r,o)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),aM=ve("$ZodExactOptional",(e,t)=>{Iw.init(e,t),At(e._zod,"values",()=>t.innerType._zod.values),At(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),iM=ve("$ZodNullable",(e,t)=>{an.init(e,t),At(e._zod,"optin",()=>t.innerType._zod.optin),At(e._zod,"optout",()=>t.innerType._zod.optout),At(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${mv(n.source)}|null)$`):void 0}),At(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)}),oM=ve("$ZodDefault",(e,t)=>{an.init(e,t),e._zod.optin="optional",At(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=>Xy(r,t)):Xy(o,t)}});function Xy(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const rM=ve("$ZodPrefault",(e,t)=>{an.init(e,t),e._zod.optin="optional",At(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))}),sM=ve("$ZodNonOptional",(e,t)=>{an.init(e,t),At(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=>e0(r,e)):e0(o,e)}});function e0(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 lM=ve("$ZodCatch",(e,t)=>{an.init(e,t),e._zod.optin="optional",At(e._zod,"optout",()=>t.innerType._zod.optout),At(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=>bo(s,a,vo()))},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=>bo(r,a,vo()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),_w=ve("$ZodPipe",(e,t)=>{an.init(e,t),At(e._zod,"values",()=>t.in._zod.values),At(e._zod,"optin",()=>t.in._zod.optin),At(e._zod,"optout",()=>t.out._zod.optout),At(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=>Kd(s,t.in,a)):Kd(r,t.in,a)}const o=t.in._zod.run(n,a);return o instanceof Promise?o.then(r=>Kd(r,t.out,a)):Kd(o,t.out,a)}});function Kd(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 cM=ve("$ZodPreprocess",(e,t)=>{_w.init(e,t)}),dM=ve("$ZodReadonly",(e,t)=>{an.init(e,t),At(e._zod,"propValues",()=>t.innerType._zod.propValues),At(e._zod,"values",()=>t.innerType._zod.values),At(e._zod,"optin",()=>t.innerType?._zod?.optin),At(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(t0):t0(o)}});function t0(e){return e.value=Object.freeze(e.value),e}const uM=ve("$ZodLazy",(e,t)=>{an.init(e,t),At(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),At(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),At(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),At(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),At(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),mM=ve("$ZodCustom",(e,t)=>{fa.init(e,t),an.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=>n0(r,n,a,e));n0(o,n,a,e)}});function n0(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(bc(o))}}var a0;class pM{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 fM(){return new pM}(a0=globalThis).__zod_globalRegistry??(a0.__zod_globalRegistry=fM());const Zl=globalThis.__zod_globalRegistry;function hM(e,t){return new e({type:"string",...et(t)})}function gM(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...et(t)})}function i0(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...et(t)})}function Cw(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...et(t)})}function vM(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...et(t)})}function bM(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...et(t)})}function yM(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...et(t)})}function SM(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...et(t)})}function xM(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...et(t)})}function kM(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...et(t)})}function wM(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...et(t)})}function IM(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...et(t)})}function _M(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...et(t)})}function CM(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...et(t)})}function RM(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...et(t)})}function PM(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...et(t)})}function AM(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...et(t)})}function TM(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...et(t)})}function EM(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...et(t)})}function jM(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...et(t)})}function MM(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...et(t)})}function OM(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...et(t)})}function $M(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...et(t)})}function NM(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...et(t)})}function DM(e,t){return new e({type:"string",format:"date",check:"string_format",...et(t)})}function HM(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...et(t)})}function LM(e,t){return new e({type:"string",format:"duration",check:"string_format",...et(t)})}function qM(e,t){return new e({type:"number",checks:[],...et(t)})}function Zne(e,t){return new e({type:"number",coerce:!0,checks:[],...et(t)})}function UM(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...et(t)})}function zM(e,t){return new e({type:"boolean",...et(t)})}function BM(e,t){return new e({type:"null",...et(t)})}function FM(e){return new e({type:"unknown"})}function VM(e,t){return new e({type:"never",...et(t)})}function o0(e,t){return new vw({check:"less_than",...et(t),value:e,inclusive:!1})}function Pf(e,t){return new vw({check:"less_than",...et(t),value:e,inclusive:!0})}function r0(e,t){return new bw({check:"greater_than",...et(t),value:e,inclusive:!1})}function Af(e,t){return new bw({check:"greater_than",...et(t),value:e,inclusive:!0})}function s0(e,t){return new ij({check:"multiple_of",...et(t),value:e})}function Rw(e,t){return new rj({check:"max_length",...et(t),maximum:e})}function Uu(e,t){return new sj({check:"min_length",...et(t),minimum:e})}function Pw(e,t){return new lj({check:"length_equals",...et(t),length:e})}function KM(e,t){return new cj({check:"string_format",format:"regex",...et(t),pattern:e})}function WM(e){return new dj({check:"string_format",format:"lowercase",...et(e)})}function GM(e){return new uj({check:"string_format",format:"uppercase",...et(e)})}function JM(e,t){return new mj({check:"string_format",format:"includes",...et(t),includes:e})}function ZM(e,t){return new pj({check:"string_format",format:"starts_with",...et(t),prefix:e})}function YM(e,t){return new fj({check:"string_format",format:"ends_with",...et(t),suffix:e})}function rl(e){return new hj({check:"overwrite",tx:e})}function QM(e){return rl(t=>t.normalize(e))}function XM(){return rl(e=>e.trim())}function eO(){return rl(e=>e.toLowerCase())}function tO(){return rl(e=>e.toUpperCase())}function nO(){return rl(e=>rE(e))}function aO(e,t,n){return new e({type:"array",element:t,...et(n)})}function iO(e,t,n){const a=et(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function oO(e,t,n){return new e({type:"custom",check:"custom",fn:t,...et(n)})}function rO(e,t){const n=sO(a=>(a.addIssue=o=>{if(typeof o=="string")a.issues.push(bc(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(bc(r))}},e(a.value,a)),t);return n}function sO(e,t){const n=new fa({check:"custom",...et(t)});return n._zod.check=e,n}function Aw(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??Zl,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 vn(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 c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{const f={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,f);else{const S=s.schema,k=t.processors[o.type];if(!k)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);k(e,t,S,f)}const g=e._zod.parent;g&&(s.ref||(s.ref=g),vn(g,t,f),t.seen.get(g).isParent=!0)}const m=t.metadataRegistry.get(e);return m&&Object.assign(s.schema,m),t.io==="input"&&Jn(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 Tw(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 c=e.metadataRegistry.get(s[0])?.id;if(c){const m=a.get(c);if(m&&m!==s[0])throw new Error(`Duplicate schema id "${c}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);a.set(c,s[0])}}const o=s=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(s[0])?.id,S=e.external.uri??(C=>C);if(g)return{ref:S(g)};const k=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=k,{defId:k,ref:`${S("__shared")}#/${c}/${k}`}}if(s[1]===n)return{ref:"#"};const u=`#/${c}/`,f=s[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:u+f}},r=s=>{if(s[1].schema.$ref)return;const c=s[1],{ref:m,defId:u}=o(s);c.def={...c.schema},u&&(c.defId=u);const f=c.schema;for(const g in f)delete f[g];f.$ref=m};if(e.cycles==="throw")for(const s of e.seen.entries()){const c=s[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.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 c=s[1];if(t===s[0]){r(s);continue}if(e.external){const u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){r(s);continue}}if(e.metadataRegistry.get(s[0])?.id){r(s);continue}if(c.cycle){r(s);continue}if(c.count>1&&e.reused==="ref"){r(s);continue}}}function Ew(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=c=>{const m=e.seen.get(c);if(m.ref===null)return;const u=m.def??m.schema,f={...u},g=m.ref;if(m.ref=null,g){a(g);const k=e.seen.get(g),C=k.schema;if(C.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(C)):Object.assign(u,C),Object.assign(u,f),c._zod.parent===g)for(const j in u)j==="$ref"||j==="allOf"||j in f||delete u[j];if(C.$ref&&k.def)for(const j in u)j==="$ref"||j==="allOf"||j in k.def&&JSON.stringify(u[j])===JSON.stringify(k.def[j])&&delete u[j]}const S=c._zod.parent;if(S&&S!==g){a(S);const k=e.seen.get(S);if(k?.schema.$ref&&(u.$ref=k.schema.$ref,k.def))for(const C in u)C==="$ref"||C==="allOf"||C in k.def&&JSON.stringify(u[C])===JSON.stringify(k.def[C])&&delete u[C]}e.override({zodSchema:c,jsonSchema:u,path:m.path??[]})};for(const c of[...e.seen.entries()].reverse())a(c[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 c=e.external.registry.get(t)?.id;if(!c)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(c)}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 c of e.seen.entries()){const m=c[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 c=JSON.parse(JSON.stringify(o));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:zu(t,"input",e.processors),output:zu(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function Jn(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 Jn(a.element,n);if(a.type==="set")return Jn(a.valueType,n);if(a.type==="lazy")return Jn(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 Jn(a.innerType,n);if(a.type==="intersection")return Jn(a.left,n)||Jn(a.right,n);if(a.type==="record"||a.type==="map")return Jn(a.keyType,n)||Jn(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Jn(a.in,n)||Jn(a.out,n);if(a.type==="object"){for(const o in a.shape)if(Jn(a.shape[o],n))return!0;return!1}if(a.type==="union"){for(const o of a.options)if(Jn(o,n))return!0;return!1}if(a.type==="tuple"){for(const o of a.items)if(Jn(o,n))return!0;return!!(a.rest&&Jn(a.rest,n))}return!1}const lO=(e,t={})=>n=>{const a=Aw({...n,processors:t});return vn(e,a),Tw(a,e),Ew(a,e)},zu=(e,t,n={})=>a=>{const{libraryOptions:o,target:r}=a??{},s=Aw({...o??{},target:r,io:t,processors:n});return vn(e,s),Tw(s,e),Ew(s,e)},cO={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dO=(e,t,n,a)=>{const o=n;o.type="string";const{minimum:r,maximum:s,format:c,patterns:m,contentEncoding:u}=e._zod.bag;if(typeof r=="number"&&(o.minLength=r),typeof s=="number"&&(o.maxLength=s),c&&(o.format=cO[c]??c,o.format===""&&delete o.format,c==="time"&&delete o.format),u&&(o.contentEncoding=u),m&&m.size>0){const f=[...m];f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},uO=(e,t,n,a)=>{const o=n,{minimum:r,maximum:s,format:c,multipleOf:m,exclusiveMaximum:u,exclusiveMinimum:f}=e._zod.bag;typeof c=="string"&&c.includes("int")?o.type="integer":o.type="number";const g=typeof f=="number"&&f>=(r??Number.NEGATIVE_INFINITY),S=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),k=t.target==="draft-04"||t.target==="openapi-3.0";g?k?(o.minimum=f,o.exclusiveMinimum=!0):o.exclusiveMinimum=f:typeof r=="number"&&(o.minimum=r),S?k?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof s=="number"&&(o.maximum=s),typeof m=="number"&&(o.multipleOf=m)},mO=(e,t,n,a)=>{n.type="boolean"},pO=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},fO=(e,t,n,a)=>{n.not={}},hO=(e,t,n,a)=>{},gO=(e,t,n,a)=>{const o=e._zod.def,r=rw(o.entries);r.every(s=>typeof s=="number")&&(n.type="number"),r.every(s=>typeof s=="string")&&(n.type="string"),n.enum=r},vO=(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},bO=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},yO=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},SO=(e,t,n,a)=>{const o=n,r=e._zod.def,{minimum:s,maximum:c}=e._zod.bag;typeof s=="number"&&(o.minItems=s),typeof c=="number"&&(o.maxItems=c),o.type="array",o.items=vn(r.element,t,{...a,path:[...a.path,"items"]})},xO=(e,t,n,a)=>{const o=n,r=e._zod.def;o.type="object",o.properties={};const s=r.shape;for(const u in s)o.properties[u]=vn(s[u],t,{...a,path:[...a.path,"properties",u]});const c=new Set(Object.keys(s)),m=new Set([...c].filter(u=>{const f=r.shape[u]._zod;return t.io==="input"?f.optin===void 0:f.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=vn(r.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},kO=(e,t,n,a)=>{const o=e._zod.def,r=o.inclusive===!1,s=o.options.map((c,m)=>vn(c,t,{...a,path:[...a.path,r?"oneOf":"anyOf",m]}));r?n.oneOf=s:n.anyOf=s},wO=(e,t,n,a)=>{const o=e._zod.def,r=vn(o.left,t,{...a,path:[...a.path,"allOf",0]}),s=vn(o.right,t,{...a,path:[...a.path,"allOf",1]}),c=u=>"allOf"in u&&Object.keys(u).length===1,m=[...c(r)?r.allOf:[r],...c(s)?s.allOf:[s]];n.allOf=m},IO=(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 f=vn(r.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});o.patternProperties={};for(const g of m)o.patternProperties[g.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=vn(r.keyType,t,{...a,path:[...a.path,"propertyNames"]})),o.additionalProperties=vn(r.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const u=s._zod.values;if(u){const f=[...u].filter(g=>typeof g=="string"||typeof g=="number");f.length>0&&(o.required=f)}},_O=(e,t,n,a)=>{const o=e._zod.def,r=vn(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"}]},CO=(e,t,n,a)=>{const o=e._zod.def;vn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType},RO=(e,t,n,a)=>{const o=e._zod.def;vn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},PO=(e,t,n,a)=>{const o=e._zod.def;vn(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)))},AO=(e,t,n,a)=>{const o=e._zod.def;vn(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},TO=(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;vn(s,t,a);const c=t.seen.get(e);c.ref=s},EO=(e,t,n,a)=>{const o=e._zod.def;vn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType,n.readOnly=!0},jw=(e,t,n,a)=>{const o=e._zod.def;vn(o.innerType,t,a);const r=t.seen.get(e);r.ref=o.innerType},jO=(e,t,n,a)=>{const o=e._zod.innerType;vn(o,t,a);const r=t.seen.get(e);r.ref=o},MO=ve("ZodISODateTime",(e,t)=>{Aj.init(e,t),cn.init(e,t)});function nn(e){return NM(MO,e)}const OO=ve("ZodISODate",(e,t)=>{Tj.init(e,t),cn.init(e,t)});function $O(e){return DM(OO,e)}const NO=ve("ZodISOTime",(e,t)=>{Ej.init(e,t),cn.init(e,t)});function DO(e){return HM(NO,e)}const HO=ve("ZodISODuration",(e,t)=>{jj.init(e,t),cn.init(e,t)});function LO(e){return LM(HO,e)}const Mw=(e,t)=>{dw.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>SE(e,n)},flatten:{value:n=>yE(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,ng,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,ng,2)}},isEmpty:{get(){return e.issues.length===0}}})},qO=ve("ZodError",Mw),Va=ve("ZodError",Mw,{Parent:Error}),UO=fv(Va),zO=hv(Va),BO=Sm(Va),FO=xm(Va),VO=wE(Va),KO=IE(Va),WO=_E(Va),GO=CE(Va),JO=RE(Va),ZO=PE(Va),YO=AE(Va),QO=TE(Va),l0=new WeakMap;function Vc(e,t,n){const a=Object.getPrototypeOf(e);let o=l0.get(a);if(o||(o=new Set,l0.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 c=s.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}const on=ve("ZodType",(e,t)=>(an.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:zu(e,"input"),output:zu(e,"output")}}),e.toJSONSchema=lO(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>UO(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>BO(e,n,a),e.parseAsync=async(n,a)=>zO(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>FO(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>VO(e,n,a),e.decode=(n,a)=>KO(e,n,a),e.encodeAsync=async(n,a)=>WO(e,n,a),e.decodeAsync=async(n,a)=>GO(e,n,a),e.safeEncode=(n,a)=>JO(e,n,a),e.safeDecode=(n,a)=>ZO(e,n,a),e.safeEncodeAsync=async(n,a)=>YO(e,n,a),e.safeDecodeAsync=async(n,a)=>QO(e,n,a),Vc(e,"ZodType",{check(...n){const a=this.def;return this.clone(Jo(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 Zo(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(z2(n,a))},superRefine(n,a){return this.check(B2(n,a))},overwrite(n){return this.check(rl(n))},optional(){return m0(this)},exactOptional(){return A2(this)},nullable(){return p0(this)},nullish(){return m0(p0(this))},nonoptional(n){return $2(this,n)},array(){return p(this)},or(n){return gt([this,n])},and(n){return _2(this,n)},transform(n){return f0(this,Lw(n))},default(n){return j2(this,n)},prefault(n){return O2(this,n)},catch(n){return D2(this,n)},pipe(n){return f0(this,n)},readonly(){return q2(this)},describe(n){const a=this.clone();return Zl.add(a,{description:n}),a},meta(...n){if(n.length===0)return Zl.get(this);const a=this.clone();return Zl.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 Zl.get(e)?.description},configurable:!0}),e)),Ow=ve("_ZodString",(e,t)=>{gv.init(e,t),on.init(e,t),e._zod.processJSONSchema=(a,o,r)=>dO(e,a,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Vc(e,"_ZodString",{regex(...a){return this.check(KM(...a))},includes(...a){return this.check(JM(...a))},startsWith(...a){return this.check(ZM(...a))},endsWith(...a){return this.check(YM(...a))},min(...a){return this.check(Uu(...a))},max(...a){return this.check(Rw(...a))},length(...a){return this.check(Pw(...a))},nonempty(...a){return this.check(Uu(1,...a))},lowercase(a){return this.check(WM(a))},uppercase(a){return this.check(GM(a))},trim(){return this.check(XM())},normalize(...a){return this.check(QM(...a))},toLowerCase(){return this.check(eO())},toUpperCase(){return this.check(tO())},slugify(){return this.check(nO())}})}),XO=ve("ZodString",(e,t)=>{gv.init(e,t),Ow.init(e,t),e.email=n=>e.check(gM(e2,n)),e.url=n=>e.check(SM(t2,n)),e.jwt=n=>e.check($M(g2,n)),e.emoji=n=>e.check(xM(n2,n)),e.guid=n=>e.check(i0(c0,n)),e.uuid=n=>e.check(Cw(Yl,n)),e.uuidv4=n=>e.check(vM(Yl,n)),e.uuidv6=n=>e.check(bM(Yl,n)),e.uuidv7=n=>e.check(yM(Yl,n)),e.nanoid=n=>e.check(kM(a2,n)),e.guid=n=>e.check(i0(c0,n)),e.cuid=n=>e.check(wM(i2,n)),e.cuid2=n=>e.check(IM(o2,n)),e.ulid=n=>e.check(_M(r2,n)),e.base64=n=>e.check(jM(p2,n)),e.base64url=n=>e.check(MM(f2,n)),e.xid=n=>e.check(CM(s2,n)),e.ksuid=n=>e.check(RM(l2,n)),e.ipv4=n=>e.check(PM(c2,n)),e.ipv6=n=>e.check(AM(d2,n)),e.cidrv4=n=>e.check(TM(u2,n)),e.cidrv6=n=>e.check(EM(m2,n)),e.e164=n=>e.check(OM(h2,n)),e.datetime=n=>e.check(nn(n)),e.date=n=>e.check($O(n)),e.time=n=>e.check(DO(n)),e.duration=n=>e.check(LO(n))});function i(e){return hM(XO,e)}const cn=ve("ZodStringFormat",(e,t)=>{sn.init(e,t),Ow.init(e,t)}),e2=ve("ZodEmail",(e,t)=>{Sj.init(e,t),cn.init(e,t)}),c0=ve("ZodGUID",(e,t)=>{bj.init(e,t),cn.init(e,t)}),Yl=ve("ZodUUID",(e,t)=>{yj.init(e,t),cn.init(e,t)});function wm(e){return Cw(Yl,e)}const t2=ve("ZodURL",(e,t)=>{xj.init(e,t),cn.init(e,t)}),n2=ve("ZodEmoji",(e,t)=>{kj.init(e,t),cn.init(e,t)}),a2=ve("ZodNanoID",(e,t)=>{wj.init(e,t),cn.init(e,t)}),i2=ve("ZodCUID",(e,t)=>{Ij.init(e,t),cn.init(e,t)}),o2=ve("ZodCUID2",(e,t)=>{_j.init(e,t),cn.init(e,t)}),r2=ve("ZodULID",(e,t)=>{Cj.init(e,t),cn.init(e,t)}),s2=ve("ZodXID",(e,t)=>{Rj.init(e,t),cn.init(e,t)}),l2=ve("ZodKSUID",(e,t)=>{Pj.init(e,t),cn.init(e,t)}),c2=ve("ZodIPv4",(e,t)=>{Mj.init(e,t),cn.init(e,t)}),d2=ve("ZodIPv6",(e,t)=>{Oj.init(e,t),cn.init(e,t)}),u2=ve("ZodCIDRv4",(e,t)=>{$j.init(e,t),cn.init(e,t)}),m2=ve("ZodCIDRv6",(e,t)=>{Nj.init(e,t),cn.init(e,t)}),p2=ve("ZodBase64",(e,t)=>{Dj.init(e,t),cn.init(e,t)}),f2=ve("ZodBase64URL",(e,t)=>{Lj.init(e,t),cn.init(e,t)}),h2=ve("ZodE164",(e,t)=>{qj.init(e,t),cn.init(e,t)}),g2=ve("ZodJWT",(e,t)=>{zj.init(e,t),cn.init(e,t)}),$w=ve("ZodNumber",(e,t)=>{Sw.init(e,t),on.init(e,t),e._zod.processJSONSchema=(a,o,r)=>uO(e,a,o),Vc(e,"ZodNumber",{gt(a,o){return this.check(r0(a,o))},gte(a,o){return this.check(Af(a,o))},min(a,o){return this.check(Af(a,o))},lt(a,o){return this.check(o0(a,o))},lte(a,o){return this.check(Pf(a,o))},max(a,o){return this.check(Pf(a,o))},int(a){return this.check(d0(a))},safe(a){return this.check(d0(a))},positive(a){return this.check(r0(0,a))},nonnegative(a){return this.check(Af(0,a))},negative(a){return this.check(o0(0,a))},nonpositive(a){return this.check(Pf(0,a))},multipleOf(a,o){return this.check(s0(a,o))},step(a,o){return this.check(s0(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 d(e){return qM($w,e)}const v2=ve("ZodNumberFormat",(e,t)=>{Bj.init(e,t),$w.init(e,t)});function d0(e){return UM(v2,e)}const b2=ve("ZodBoolean",(e,t)=>{Fj.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>mO(e,n,a)});function I(e){return zM(b2,e)}const y2=ve("ZodNull",(e,t)=>{Vj.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>pO(e,n,a)});function sl(e){return BM(y2,e)}const S2=ve("ZodUnknown",(e,t)=>{Kj.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>hO()});function ie(){return FM(S2)}const x2=ve("ZodNever",(e,t)=>{Wj.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>fO(e,n,a)});function Nw(e){return VM(x2,e)}const k2=ve("ZodArray",(e,t)=>{Gj.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>SO(e,n,a,o),e.element=t.element,Vc(e,"ZodArray",{min(n,a){return this.check(Uu(n,a))},nonempty(n){return this.check(Uu(1,n))},max(n,a){return this.check(Rw(n,a))},length(n,a){return this.check(Pw(n,a))},unwrap(){return this.element}})});function p(e,t){return aO(k2,e,t)}const Dw=ve("ZodObject",(e,t)=>{Zj.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>xO(e,n,a,o),At(e,"shape",()=>t.shape),Vc(e,"ZodObject",{keyof(){return v(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ie()})},loose(){return this.clone({...this._zod.def,catchall:ie()})},strict(){return this.clone({...this._zod.def,catchall:Nw()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return pE(this,n)},safeExtend(n){return fE(this,n)},merge(n){return hE(this,n)},pick(n){return uE(this,n)},omit(n){return mE(this,n)},partial(...n){return gE(qw,this,n[0])},required(...n){return vE(Uw,this,n[0])}})});function l(e,t){const n={type:"object",shape:e??{},...et(t)};return new Dw(n)}function Tf(e,t){return new Dw({type:"object",shape:e,catchall:Nw(),...et(t)})}const Hw=ve("ZodUnion",(e,t)=>{ww.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>kO(e,n,a,o),e.options=t.options});function gt(e,t){return new Hw({type:"union",options:e,...et(t)})}const w2=ve("ZodDiscriminatedUnion",(e,t)=>{Hw.init(e,t),Yj.init(e,t)});function rt(e,t,n){return new w2({type:"union",options:t,discriminator:e,...et(n)})}const I2=ve("ZodIntersection",(e,t)=>{Qj.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>wO(e,n,a,o)});function _2(e,t){return new I2({type:"intersection",left:e,right:t})}const u0=ve("ZodRecord",(e,t)=>{Xj.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>IO(e,n,a,o),e.keyType=t.keyType,e.valueType=t.valueType});function te(e,t,n){return!t||!t._zod?new u0({type:"record",keyType:i(),valueType:e,...et(t)}):new u0({type:"record",keyType:e,valueType:t,...et(n)})}const ig=ve("ZodEnum",(e,t)=>{eM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(a,o,r)=>gO(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 ig({...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 ig({...t,checks:[],...et(o),entries:r})}});function v(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new ig({type:"enum",entries:n,...et(t)})}const C2=ve("ZodLiteral",(e,t)=>{tM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>vO(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 b(e,t){return new C2({type:"literal",values:Array.isArray(e)?e:[e],...et(t)})}const R2=ve("ZodTransform",(e,t)=>{nM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>yO(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new ow(e.constructor.name);n.addIssue=r=>{if(typeof r=="string")n.issues.push(bc(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(bc(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 Lw(e){return new R2({type:"transform",transform:e})}const qw=ve("ZodOptional",(e,t)=>{Iw.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>jw(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function m0(e){return new qw({type:"optional",innerType:e})}const P2=ve("ZodExactOptional",(e,t)=>{aM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>jw(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function A2(e){return new P2({type:"optional",innerType:e})}const T2=ve("ZodNullable",(e,t)=>{iM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>_O(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function p0(e){return new T2({type:"nullable",innerType:e})}const E2=ve("ZodDefault",(e,t)=>{oM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>RO(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function j2(e,t){return new E2({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():lw(t)}})}const M2=ve("ZodPrefault",(e,t)=>{rM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>PO(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function O2(e,t){return new M2({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():lw(t)}})}const Uw=ve("ZodNonOptional",(e,t)=>{sM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>CO(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function $2(e,t){return new Uw({type:"nonoptional",innerType:e,...et(t)})}const N2=ve("ZodCatch",(e,t)=>{lM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>AO(e,n,a,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function D2(e,t){return new N2({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const zw=ve("ZodPipe",(e,t)=>{_w.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>TO(e,n,a,o),e.in=t.in,e.out=t.out});function f0(e,t){return new zw({type:"pipe",in:e,out:t})}const H2=ve("ZodPreprocess",(e,t)=>{zw.init(e,t),cM.init(e,t)}),L2=ve("ZodReadonly",(e,t)=>{dM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>EO(e,n,a,o),e.unwrap=()=>e._zod.def.innerType});function q2(e){return new L2({type:"readonly",innerType:e})}const U2=ve("ZodLazy",(e,t)=>{uM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>jO(e,n,a,o),e.unwrap=()=>e._zod.def.getter()});function Bw(e){return new U2({type:"lazy",getter:e})}const Fw=ve("ZodCustom",(e,t)=>{mM.init(e,t),on.init(e,t),e._zod.processJSONSchema=(n,a,o)=>bO(e,n)});function Ef(e,t){return iO(Fw,(()=>!0),t)}function z2(e,t={}){return oO(Fw,e,t)}function B2(e,t){return rO(e,t)}function Ko(e){const t=Bw(()=>gt([i(e),d(),I(),sl(),p(t),te(i(),t)]));return t}function F2(e,t){return new H2({type:"pipe",in:Lw(e),out:t})}const Yn={custom:"custom"},V2=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),K2=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 W2(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(V2),c=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let R=0;R<16;R+=1)c[R]=r.getUint32(m+R*4,!1);for(let R=16;R<64;R+=1){const $=c[R-15],O=c[R-2],M=xi($,7)^xi($,18)^$>>>3,w=xi(O,17)^xi(O,19)^O>>>10;c[R]=c[R-16]+M+c[R-7]+w>>>0}let u=s[0],f=s[1],g=s[2],S=s[3],k=s[4],C=s[5],P=s[6],j=s[7];for(let R=0;R<64;R+=1){const $=k&C^~k&P,O=u&f^u&g^f&g,M=xi(u,2)^xi(u,13)^xi(u,22),w=xi(k,6)^xi(k,11)^xi(k,25),A=j+w+$+K2[R]+c[R]>>>0,E=M+O>>>0;j=P,P=C,C=k,k=S+A>>>0,S=g,g=f,f=u,u=A+E>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+f>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+S>>>0,s[4]=s[4]+k>>>0,s[5]=s[5]+C>>>0,s[6]=s[6]+P>>>0,s[7]=s[7]+j>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function xi(e,t){return e>>>t|e<<32-t}const G2=2e3,Vw=25e7,T=i().trim().min(1).max(240),H=i().regex(/^[a-f0-9]{64}$/),pe=i().datetime({offset:!0}),jn=te(i(),ie()).default({}),V=l({id:T,contentHash:H}).strict(),Zt=V.extend({revision:d().int().positive()}).strict(),gn=l({id:T,path:i().trim().min(1).max(G2).refine(Y2),contentHash:H,sizeBytes:d().int().nonnegative().max(Vw),mediaType:i().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),Ia=l({id:T,contentHash:H,mediaType:i().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(Vw).nullable().default(null)}).strict(),Kc=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function J2(e){return`${JSON.stringify(og(e),null,2)}
|
|
66
|
+
`}function vv(e){return W2(e)}function ct(e){return vv(J2(e))}function Z2(e,t){const{contentHash:n,...a}=e,o=ct(a);if(n!==o)throw new Error(`${t} contentHash is ${n}; expected ${o}.`)}function Y2(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function og(e){return Array.isArray(e)?e.map(og):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,og(n)]))}const Im=l({provider:T,model:T,revision:i().trim().min(1).max(500).nullable().default(null),artifactHash:H.nullable().default(null),tokenizerRevision:i().trim().min(1).max(500).nullable().default(null),chatTemplateHash:H.nullable().default(null)}).strict(),bv=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],$r=v(bv),bn=l({providerId:$r,modelId:i().trim().min(1).max(300)}),_m=v(["active","preview","planned","deprecated"]),Kw=v(["openpond-account","openpond-managed","codex-login","native-agent-login","chatgpt-subscription","local-byok","hosted-byok","custom"]),Q2=v(["none","local_secret","env","openpond_account","codex_login","native_agent_login","chatgpt_subscription","hosted"]),h0=l({connected:I().default(!1),source:Q2.default("none"),redacted:i().nullable().default(null),lastValidatedAt:i().nullable().default(null),lastError:i().nullable().default(null)}),rg=l({hostedOpChat:I().default(!1),localRuntime:I().default(!0),localByok:I().default(!1),hostedByok:I().default(!1)}),X2=v(["hosted","provider","manual","none"]),sg=l({chatCompletions:I().default(!0),streaming:I().default(!0),modelDiscovery:X2.default("none"),toolCalling:I().default(!1),reasoning:I().default(!1),imageInput:I().default(!1),structuredOutput:I().default(!1)}),e$=v(["hosted","provider","curated","manual","cache"]),lg=l({streaming:I().default(!0),toolCalling:I().default(!1),reasoning:I().default(!1),reasoningEfforts:p(v(["off","low","medium","high","xhigh","max"])).default([]),vision:I().default(!1),structuredOutput:I().default(!1)}),t$=l({id:i().trim().min(1).max(300),providerId:$r,displayName:i().trim().min(1).max(300),contextWindow:d().int().positive().nullable().default(null),outputLimit:d().int().positive().nullable().default(null),lifecycleStatus:_m.default("active"),source:e$,capabilities:lg.default(()=>lg.parse({})),raw:te(i(),ie()).optional()}),n$=l({providerId:$r,models:p(t$).default([]),fetchedAt:i().nullable().default(null),lastError:i().nullable().default(null),source:v(["none","hosted","provider","curated","manual"]).default("none")}),a$=l({nativeMode:i().max(200).nullable().default(null),nativeOptions:te(i().max(200),i().max(300)).default({}),binaryPath:i().trim().min(1).max(4096).nullable().default(null),sourceHome:i().trim().min(1).max(4096).nullable().default(null),enabled:I().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)}),i$=l({nativeMode:i().max(200).nullable().optional(),nativeOptions:te(i().max(200),i().max(300)).optional(),binaryPath:i().trim().min(1).max(4096).nullable().optional(),sourceHome:i().trim().min(1).max(4096).nullable().optional(),enabled:I().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()}),o$=l({id:i().trim().min(1).max(300),displayName:i().trim().min(1).max(300),contextWindow:d().int().positive().nullable().optional(),outputLimit:d().int().positive().nullable().optional(),lifecycleStatus:_m.optional(),capabilities:lg.partial().optional()}),r$=l({id:$r,displayName:i().trim().min(1).max(160),lifecycleStatus:_m.default("active"),credentialModes:p(Kw).default([]),routing:rg,capabilities:sg,defaultEnabled:I().optional(),defaultBaseUrl:i().trim().min(1).max(2048).nullable().optional(),defaultModel:i().trim().min(1).max(300).nullable().optional(),modelCacheSource:v(["none","hosted","provider","curated","manual"]),models:p(o$).default([])});l({version:b(1).default(1),generatedAt:i().datetime(),providers:p(r$)});const s$=l({id:$r,displayName:i().trim().min(1).max(160),lifecycleStatus:_m.default("active"),credentialModes:p(Kw).default([]),routing:rg.default(()=>rg.parse({})),capabilities:sg.default(()=>sg.parse({})),credential:h0.default(()=>h0.parse({})),enabled:I().default(!1),available:I().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)}),g0=l({version:b(1).default(1),providers:te(i(),a$).default({}),statuses:te(i(),s$).default({}),modelCaches:te(i(),n$).default({}),updatedAt:i().nullable().default(null)});l({providers:te(i(),i$).optional()});l({source:v(["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."})});l({source:v(["local_secret","env","chatgpt_subscription"]).optional()});l({modelId:i().trim().min(1).max(300).optional(),baseUrl:i().trim().min(1).max(2048).optional()});l({query:i().trim().max(200).optional(),refresh:I().default(!1),limit:d().int().positive().max(500).default(100)});l({query:i().trim().max(200).optional(),force:I().default(!1)});const l$=["coding","research","review","test","docs","planner","summarizer"];v(l$);const ll=i().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),Ww=v(["none","worktree","copy_on_write"]),Gw=v(["read_only","workspace_write","full_tools"]),Jw=v(["disabled","parent_scoped"]),Cm=v(["manual","balanced","proactive"]),c$=v(["queued","running","completed","failed","cancelled","needs_resume"]),Zw=["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"];v(Zw);const d$=[{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"}],yv=l({id:ll,enabled:I().default(!0),modelRef:bn.nullable().default(null),isolationMode:Ww.default("none"),maxConcurrentRuns:d().int().min(1).max(16).default(1),toolPolicy:Gw.default("read_only"),background:I().default(!0),peerMessages:Jw.default("parent_scoped")}),yc=l({enabled:I().default(!0),workspaceDefaultsVersion:b(1).default(1),toolDefaultsVersion:b(1).default(1),delegationMode:Cm.default("manual"),defaultModelRef:bn.nullable().default(null),roles:p(yv).max(64).default(()=>Xw()),maxConcurrentRuns:d().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:d().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:d().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:x$(e.roles)})),oc=l({kind:v(["session","turn","file","diff","artifact"]),id:i().trim().min(1).max(500),label:i().trim().min(1).max(500)}),u$=l({kind:v(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:d().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:d().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:I().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),m$=v(["orient","edit","validate","report"]),p$=l({command:i().trim().min(1).max(2e3),status:v(["passed","failed","unknown"]).default("unknown"),exitCode:d().int().nullable().default(null),outputSummary:i().trim().max(5e3).nullable().default(null),startedAt:i().nullable().default(null),completedAt:i().nullable().default(null)}),f$=l({phase:m$.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(oc).max(100).default([]),validationAttempts:p(p$).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})),h$=l({summary:i().trim().max(2e4).default(""),findings:p(i().trim().min(1).max(5e3)).max(200).default([]),artifacts:p(oc).max(200).default([]),patchRef:oc.nullable().default(null),diffRef:oc.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:v(["low","medium","high"]).nullable().default(null),followUpNeeded:I().default(!1)}),Yw=l({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:ll,objective:i().trim().min(1).max(5e4),modelRef:bn.nullable().default(null),isolationMode:Ww.default("none"),toolPolicy:Gw.default("read_only"),background:I().default(!0),peerMessages:Jw.default("parent_scoped"),status:c$.default("queued"),progress:f$,evidenceRetention:u$,createdAt:i(),startedAt:i().nullable().default(null),completedAt:i().nullable().default(null),updatedAt:i().nullable().default(null),error:i().nullable().default(null),report:h$.nullable().default(null),metadata:te(i(),ie()).optional().default({})}),Qw=v(["cleanup","archive","cleanup_and_archive"]);l({action:Qw,reason:i().trim().min(1).max(2e3).nullable().default(null)});l({action:Qw,run:Yw,workspaceCleanup:te(i(),ie()).nullable().default(null),sessionArchive:te(i(),ie()).nullable().default(null),nextStep:i()});const g$=v(["question","answer","handoff","artifact","status","blocker"]),v$=v(["normal","interrupt"]),b$=l({inputIds:p(i()).default([]),status:v(["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)}),y$=l({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:ll.nullable().default(null),kind:g$,priority:v$.optional(),body:i().trim().min(1).max(5e4),refs:p(oc).max(100).default([]),delivery:b$.optional(),createdAt:i()});function Xw(){return d$.map(e=>yv.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function S$(){return yc.parse({})}function x$(e){const t=Xw(),n=new Map(t.map(o=>[o.id,o])),a=[];for(const o of e??[]){const r=yv.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 k$=v(["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",...Zw,"diagnostic"]),v0=l({id:i(),sequence:d().int().positive().optional(),sessionId:i().optional(),turnId:i().optional(),name:k$,timestamp:i(),source:v(["ui_button","chat_action","terminal_command","hook","provider","server"]).optional(),action:i().optional(),appId:i().nullable().optional(),args:te(i(),ie()).optional(),status:v(["started","completed","failed","pending"]).optional(),output:i().optional(),error:i().optional(),relatedDeploymentId:i().optional(),data:ie().optional()}),w$=l({id:i().trim().min(1).max(80),label:i().trim().min(1).max(160),description:i().trim().max(500).nullable().optional().default(null)}),I$=l({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(w$).max(5).default([]),allowFreeform:I().default(!0),status:v(["pending","answered","dismissed"]),answer:l({optionId:i().trim().min(1).nullable(),text:i().max(4e3)}).nullable(),createdAt:i(),answeredAt:i().nullable()}),_$=l({questionId:i().trim().min(1),action:v(["answer","dismiss"]),optionId:i().trim().min(1).nullable().optional().default(null),text:i().trim().max(4e3).optional().default("")});l({kind:v(["session","project","draft"]),id:i().trim().min(1).max(300)});v(["unknown","idle","running","success","failed"]);v(["none","idle","running","success","failed","unknown"]);function C$(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Vn={},Wd={},Mo={},b0;function Wc(){if(b0)return Mo;b0=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,c){if(c){const m=Object.keys(c);for(let u=0,f=m.length;u<f;u+=1){const g=m[u];s[g]=c[g]}}return s}function o(s,c){let m="";for(let u=0;u<c;u+=1)m+=s;return m}function r(s){return s===0&&Number.NEGATIVE_INFINITY===1/s}return Mo.isNothing=e,Mo.isObject=t,Mo.toArray=n,Mo.repeat=o,Mo.isNegativeZero=r,Mo.extend=a,Mo}var jf,y0;function Gc(){if(y0)return jf;y0=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)},jf=t,jf}var Mf,S0;function R$(){if(S0)return Mf;S0=1;const e=Wc();function t(o,r,s,c,m){let u="",f="";const g=Math.floor(m/2)-1;return c-r>g&&(u=" ... ",r=c-g+u.length),s-c>g&&(f=" ...",s=c+g-f.length),{str:u+o.slice(r,s).replace(/\t/g,"→")+f,pos:c-r+u.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,c=[0],m=[];let u,f=-1;for(;u=s.exec(o.buffer);)m.push(u.index),c.push(u.index+u[0].length),o.position<=u.index&&f<0&&(f=c.length-2);f<0&&(f=c.length-1);let g="";const S=Math.min(o.line+r.linesAfter,m.length).toString().length,k=r.maxLength-(r.indent+S+3);for(let P=1;P<=r.linesBefore&&!(f-P<0);P++){const j=t(o.buffer,c[f-P],m[f-P],o.position-(c[f]-c[f-P]),k);g=e.repeat(" ",r.indent)+n((o.line-P+1).toString(),S)+" | "+j.str+`
|
|
69
|
+
`+g}const C=t(o.buffer,c[f],m[f],o.position,k);g+=e.repeat(" ",r.indent)+n((o.line+1).toString(),S)+" | "+C.str+`
|
|
70
|
+
`,g+=e.repeat("-",r.indent+S+3+C.pos)+`^
|
|
71
|
+
`;for(let P=1;P<=r.linesAfter&&!(f+P>=m.length);P++){const j=t(o.buffer,c[f+P],m[f+P],o.position-(c[f]-c[f+P]),k);g+=e.repeat(" ",r.indent)+n((o.line+P+1).toString(),S)+" | "+j.str+`
|
|
72
|
+
`}return g.replace(/\n$/,"")}return Mf=a,Mf}var Of,x0;function ta(){if(x0)return Of;x0=1;const e=Gc(),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(c){r[c].forEach(function(m){s[String(m)]=c})}),s}function o(r,s){if(s=s||{},Object.keys(s).forEach(function(c){if(t.indexOf(c)===-1)throw new e('Unknown option "'+c+'" 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(c){return c},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 Of=o,Of}var $f,k0;function e1(){if(k0)return $f;k0=1;const e=Gc(),t=ta();function n(r,s){const c=[];return r[s].forEach(function(m){let u=c.length;c.forEach(function(f,g){f.tag===m.tag&&f.kind===m.kind&&f.multi===m.multi&&(u=g)}),c[u]=m}),c}function a(){const r={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function s(c){c.multi?(r.multi[c.kind].push(c),r.multi.fallback.push(c)):r[c.kind][c.tag]=r.fallback[c.tag]=c}for(let c=0,m=arguments.length;c<m;c+=1)arguments[c].forEach(s);return r}function o(r){return this.extend(r)}return o.prototype.extend=function(s){let c=[],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&&(c=c.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: [...] })");c.forEach(function(f){if(!(f instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(f.loadKind&&f.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(f.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(f){if(!(f instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const u=Object.create(o.prototype);return u.implicit=(this.implicit||[]).concat(c),u.explicit=(this.explicit||[]).concat(m),u.compiledImplicit=n(u,"implicit"),u.compiledExplicit=n(u,"explicit"),u.compiledTypeMap=a(u.compiledImplicit,u.compiledExplicit),u},$f=o,$f}var Nf,w0;function t1(){if(w0)return Nf;w0=1;const e=ta();return Nf=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),Nf}var Df,I0;function n1(){if(I0)return Df;I0=1;const e=ta();return Df=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Df}var Hf,_0;function a1(){if(_0)return Hf;_0=1;const e=ta();return Hf=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),Hf}var Lf,C0;function i1(){if(C0)return Lf;C0=1;const e=e1();return Lf=new e({explicit:[t1(),n1(),a1()]}),Lf}var qf,R0;function o1(){if(R0)return qf;R0=1;const e=ta();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 qf=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"}),qf}var Uf,P0;function r1(){if(P0)return Uf;P0=1;const e=ta();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 Uf=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"}),Uf}var zf,A0;function s1(){if(A0)return zf;A0=1;const e=Wc(),t=ta();function n(u){return u>=48&&u<=57||u>=65&&u<=70||u>=97&&u<=102}function a(u){return u>=48&&u<=55}function o(u){return u>=48&&u<=57}function r(u){if(u===null)return!1;const f=u.length;let g=0,S=!1;if(!f)return!1;let k=u[g];if((k==="-"||k==="+")&&(k=u[++g]),k==="0"){if(g+1===f)return!0;if(k=u[++g],k==="b"){for(g++;g<f;g++){if(k=u[g],k!=="0"&&k!=="1")return!1;S=!0}return S&&isFinite(s(u))}if(k==="x"){for(g++;g<f;g++){if(!n(u.charCodeAt(g)))return!1;S=!0}return S&&isFinite(s(u))}if(k==="o"){for(g++;g<f;g++){if(!a(u.charCodeAt(g)))return!1;S=!0}return S&&isFinite(s(u))}}for(;g<f;g++){if(!o(u.charCodeAt(g)))return!1;S=!0}return S?isFinite(s(u)):!1}function s(u){let f=u,g=1,S=f[0];if((S==="-"||S==="+")&&(S==="-"&&(g=-1),f=f.slice(1),S=f[0]),f==="0")return 0;if(S==="0"){if(f[1]==="b")return g*parseInt(f.slice(2),2);if(f[1]==="x")return g*parseInt(f.slice(2),16);if(f[1]==="o")return g*parseInt(f.slice(2),8)}return g*parseInt(f,10)}function c(u){return s(u)}function m(u){return Object.prototype.toString.call(u)==="[object Number]"&&u%1===0&&!e.isNegativeZero(u)}return zf=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:r,construct:c,predicate:m,represent:{binary:function(u){return u>=0?"0b"+u.toString(2):"-0b"+u.toString(2).slice(1)},octal:function(u){return u>=0?"0o"+u.toString(8):"-0o"+u.toString(8).slice(1)},decimal:function(u){return u.toString(10)},hexadecimal:function(u){return u>=0?"0x"+u.toString(16).toUpperCase():"-0x"+u.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),zf}var Bf,T0;function l1(){if(T0)return Bf;T0=1;const e=Wc(),t=ta(),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(u){return u===null||!n.test(u)?!1:isFinite(parseFloat(u,10))?!0:a.test(u)}function r(u){let f=u.toLowerCase();const g=f[0]==="-"?-1:1;return"+-".indexOf(f[0])>=0&&(f=f.slice(1)),f===".inf"?g===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:f===".nan"?NaN:g*parseFloat(f,10)}const s=/^[-+]?[0-9]+e/;function c(u,f){if(isNaN(u))switch(f){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===u)switch(f){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===u)switch(f){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(u))return"-0.0";const g=u.toString(10);return s.test(g)?g.replace("e",".e"):g}function m(u){return Object.prototype.toString.call(u)==="[object Number]"&&(u%1!==0||e.isNegativeZero(u))}return Bf=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:o,construct:r,predicate:m,represent:c,defaultStyle:"lowercase"}),Bf}var Ff,E0;function c1(){return E0||(E0=1,Ff=i1().extend({implicit:[o1(),r1(),s1(),l1()]})),Ff}var Vf,j0;function d1(){return j0||(j0=1,Vf=c1()),Vf}var Kf,M0;function u1(){if(M0)return Kf;M0=1;const e=ta(),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 c=0,m=null,u=t.exec(s);if(u===null&&(u=n.exec(s)),u===null)throw new Error("Date resolve error");const f=+u[1],g=+u[2]-1,S=+u[3];if(!u[4])return new Date(Date.UTC(f,g,S));const k=+u[4],C=+u[5],P=+u[6];if(u[7]){for(c=u[7].slice(0,3);c.length<3;)c+="0";c=+c}if(u[9]){const R=+u[10],$=+(u[11]||0);m=(R*60+$)*6e4,u[9]==="-"&&(m=-m)}const j=new Date(Date.UTC(f,g,S,k,C,P,c));return m&&j.setTime(j.getTime()-m),j}function r(s){return s.toISOString()}return Kf=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:a,construct:o,instanceOf:Date,represent:r}),Kf}var Wf,O0;function m1(){if(O0)return Wf;O0=1;const e=ta();function t(n){return n==="<<"||n===null}return Wf=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),Wf}var Gf,$0;function p1(){if($0)return Gf;$0=1;const e=ta(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
73
|
+
\r`;function n(s){if(s===null)return!1;let c=0;const m=s.length,u=t;for(let f=0;f<m;f++){const g=u.indexOf(s.charAt(f));if(!(g>64)){if(g<0)return!1;c+=6}}return c%8===0}function a(s){const c=s.replace(/[\r\n=]/g,""),m=c.length,u=t;let f=0;const g=[];for(let k=0;k<m;k++)k%4===0&&k&&(g.push(f>>16&255),g.push(f>>8&255),g.push(f&255)),f=f<<6|u.indexOf(c.charAt(k));const S=m%4*6;return S===0?(g.push(f>>16&255),g.push(f>>8&255),g.push(f&255)):S===18?(g.push(f>>10&255),g.push(f>>2&255)):S===12&&g.push(f>>4&255),new Uint8Array(g)}function o(s){let c="",m=0;const u=s.length,f=t;for(let S=0;S<u;S++)S%3===0&&S&&(c+=f[m>>18&63],c+=f[m>>12&63],c+=f[m>>6&63],c+=f[m&63]),m=(m<<8)+s[S];const g=u%3;return g===0?(c+=f[m>>18&63],c+=f[m>>12&63],c+=f[m>>6&63],c+=f[m&63]):g===2?(c+=f[m>>10&63],c+=f[m>>4&63],c+=f[m<<2&63],c+=f[64]):g===1&&(c+=f[m>>2&63],c+=f[m<<4&63],c+=f[64],c+=f[64]),c}function r(s){return Object.prototype.toString.call(s)==="[object Uint8Array]"}return Gf=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:n,construct:a,predicate:r,represent:o}),Gf}var Jf,N0;function f1(){if(N0)return Jf;N0=1;const e=ta(),t=Object.prototype.hasOwnProperty,n=Object.prototype.toString;function a(r){if(r===null)return!0;const s=[],c=r;for(let m=0,u=c.length;m<u;m+=1){const f=c[m];let g=!1;if(n.call(f)!=="[object Object]")return!1;let S;for(S in f)if(t.call(f,S))if(!g)g=!0;else return!1;if(!g)return!1;if(s.indexOf(S)===-1)s.push(S);else return!1}return!0}function o(r){return r!==null?r:[]}return Jf=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:a,construct:o}),Jf}var Zf,D0;function h1(){if(D0)return Zf;D0=1;const e=ta(),t=Object.prototype.toString;function n(o){if(o===null)return!0;const r=o,s=new Array(r.length);for(let c=0,m=r.length;c<m;c+=1){const u=r[c];if(t.call(u)!=="[object Object]")return!1;const f=Object.keys(u);if(f.length!==1)return!1;s[c]=[f[0],u[f[0]]]}return!0}function a(o){if(o===null)return[];const r=o,s=new Array(r.length);for(let c=0,m=r.length;c<m;c+=1){const u=r[c],f=Object.keys(u);s[c]=[f[0],u[f[0]]]}return s}return Zf=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:n,construct:a}),Zf}var Yf,H0;function g1(){if(H0)return Yf;H0=1;const e=ta(),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 Yf=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:n,construct:a}),Yf}var Qf,L0;function Sv(){return L0||(L0=1,Qf=d1().extend({implicit:[u1(),m1()],explicit:[p1(),f1(),h1(),g1()]})),Qf}var q0;function P$(){if(q0)return Wd;q0=1;const e=Wc(),t=Gc(),n=R$(),a=Sv(),o=Object.prototype.hasOwnProperty,r=1,s=2,c=3,m=4,u=1,f=2,g=3,S=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,k=/[\x85\u2028\u2029]/,C=/[,\[\]{}]/,P=/^(?:!|!!|![0-9A-Za-z-]+!)$/,j=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function R(h){return Object.prototype.toString.call(h)}function $(h){return h===10||h===13}function O(h){return h===9||h===32}function M(h){return h===9||h===32||h===10||h===13}function w(h){return h===44||h===91||h===93||h===123||h===125}function A(h){if(h>=48&&h<=57)return h-48;const B=h|32;return B>=97&&B<=102?B-97+10:-1}function E(h){return h===120?2:h===117?4:h===85?8:0}function D(h){return h>=48&&h<=57?h-48:-1}function U(h){switch(h){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 L(h){return h<=65535?String.fromCharCode(h):String.fromCharCode((h-65536>>10)+55296,(h-65536&1023)+56320)}function J(h,B,Y){B==="__proto__"?Object.defineProperty(h,B,{configurable:!0,enumerable:!0,writable:!0,value:Y}):h[B]=Y}const X=new Array(256),de=new Array(256);for(let h=0;h<256;h++)X[h]=U(h)?1:0,de[h]=U(h);function Me(h,B){this.input=h,this.filename=B.filename||null,this.schema=B.schema||a,this.onWarning=B.onWarning||null,this.legacy=B.legacy||!1,this.json=B.json||!1,this.listener=B.listener||null,this.maxDepth=typeof B.maxDepth=="number"?B.maxDepth:100,this.maxTotalMergeKeys=typeof B.maxTotalMergeKeys=="number"?B.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=h.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 Ie(h,B){const Y={name:h.filename,buffer:h.input.slice(0,-1),position:h.position,line:h.line,column:h.position-h.lineStart};return Y.snippet=n(Y),new t(B,Y)}function ne(h,B){throw Ie(h,B)}function je(h,B){h.onWarning&&h.onWarning.call(null,Ie(h,B))}function Se(h,B,Y){const ge=h.anchorMapTransactions;if(ge.length!==0){const se=ge[ge.length-1];o.call(se,B)||(se[B]={existed:o.call(h.anchorMap,B),value:h.anchorMap[B]})}h.anchorMap[B]=Y}function oe(h){h.anchorMapTransactions.push(Object.create(null))}function be(h){const B=h.anchorMapTransactions.pop(),Y=h.anchorMapTransactions;if(Y.length===0)return;const ge=Y[Y.length-1],se=Object.keys(B);for(let G=0,_=se.length;G<_;G+=1){const W=se[G];o.call(ge,W)||(ge[W]=B[W])}}function re(h){const B=h.anchorMapTransactions.pop(),Y=Object.keys(B);for(let ge=Y.length-1;ge>=0;ge-=1){const se=B[Y[ge]];se.existed?h.anchorMap[Y[ge]]=se.value:delete h.anchorMap[Y[ge]]}}function ue(h){return{position:h.position,line:h.line,lineStart:h.lineStart,lineIndent:h.lineIndent,firstTabInLine:h.firstTabInLine,tag:h.tag,anchor:h.anchor,kind:h.kind,result:h.result}}function ke(h,B){h.position=B.position,h.line=B.line,h.lineStart=B.lineStart,h.lineIndent=B.lineIndent,h.firstTabInLine=B.firstTabInLine,h.tag=B.tag,h.anchor=B.anchor,h.kind=B.kind,h.result=B.result}const Le={YAML:function(B,Y,ge){B.version!==null&&ne(B,"duplication of %YAML directive"),ge.length!==1&&ne(B,"YAML directive accepts exactly one argument");const se=/^([0-9]+)\.([0-9]+)$/.exec(ge[0]);se===null&&ne(B,"ill-formed argument of the YAML directive");const G=parseInt(se[1],10),_=parseInt(se[2],10);G!==1&&ne(B,"unacceptable YAML version of the document"),B.version=ge[0],B.checkLineBreaks=_<2,_!==1&&_!==2&&je(B,"unsupported YAML version of the document")},TAG:function(B,Y,ge){let se;ge.length!==2&&ne(B,"TAG directive accepts exactly two arguments");const G=ge[0];se=ge[1],P.test(G)||ne(B,"ill-formed tag handle (first argument) of the TAG directive"),o.call(B.tagMap,G)&&ne(B,'there is a previously declared suffix for "'+G+'" tag handle'),j.test(se)||ne(B,"ill-formed tag prefix (second argument) of the TAG directive");try{se=decodeURIComponent(se)}catch{ne(B,"tag prefix is malformed: "+se)}B.tagMap[G]=se}};function we(h,B,Y,ge){if(B<Y){const se=h.input.slice(B,Y);if(ge)for(let G=0,_=se.length;G<_;G+=1){const W=se.charCodeAt(G);W===9||W>=32&&W<=1114111||ne(h,"expected valid JSON character")}else S.test(se)&&ne(h,"the stream contains non-printable characters");h.result+=se}}function le(h,B,Y,ge){e.isObject(Y)||ne(h,"cannot merge mappings; the provided source object is unacceptable");const se=Object.keys(Y);for(let G=0,_=se.length;G<_;G+=1){const W=se[G];h.maxTotalMergeKeys!==-1&&++h.totalMergeKeys>h.maxTotalMergeKeys&&ne(h,"merge keys exceeded maxTotalMergeKeys ("+h.maxTotalMergeKeys+")"),o.call(B,W)||(J(B,W,Y[W]),ge[W]=!0)}}function xe(h,B,Y,ge,se,G,_,W,ae){if(Array.isArray(se)){se=Array.prototype.slice.call(se);for(let Z=0,ce=se.length;Z<ce;Z+=1)Array.isArray(se[Z])&&ne(h,"nested arrays are not supported inside keys"),typeof se=="object"&&R(se[Z])==="[object Object]"&&(se[Z]="[object Object]")}if(typeof se=="object"&&R(se)==="[object Object]"&&(se="[object Object]"),se=String(se),B===null&&(B={}),ge==="tag:yaml.org,2002:merge")if(Array.isArray(G))for(let Z=0,ce=G.length;Z<ce;Z+=1)le(h,B,G[Z],Y);else le(h,B,G,Y);else!h.json&&!o.call(Y,se)&&o.call(B,se)&&(h.line=_||h.line,h.lineStart=W||h.lineStart,h.position=ae||h.position,ne(h,"duplicated mapping key")),J(B,se,G),delete Y[se];return B}function Ue(h){const B=h.input.charCodeAt(h.position);B===10?h.position++:B===13?(h.position++,h.input.charCodeAt(h.position)===10&&h.position++):ne(h,"a line break is expected"),h.line+=1,h.lineStart=h.position,h.firstTabInLine=-1}function Ze(h,B,Y){let ge=0,se=h.input.charCodeAt(h.position);for(;se!==0;){for(;O(se);)se===9&&h.firstTabInLine===-1&&(h.firstTabInLine=h.position),se=h.input.charCodeAt(++h.position);if(B&&se===35)do se=h.input.charCodeAt(++h.position);while(se!==10&&se!==13&&se!==0);if($(se))for(Ue(h),se=h.input.charCodeAt(h.position),ge++,h.lineIndent=0;se===32;)h.lineIndent++,se=h.input.charCodeAt(++h.position);else break}return Y!==-1&&ge!==0&&h.lineIndent<Y&&je(h,"deficient indentation"),ge}function it(h){let B=h.position,Y=h.input.charCodeAt(B);return!!((Y===45||Y===46)&&Y===h.input.charCodeAt(B+1)&&Y===h.input.charCodeAt(B+2)&&(B+=3,Y=h.input.charCodeAt(B),Y===0||M(Y)))}function at(h,B){B===1?h.result+=" ":B>1&&(h.result+=e.repeat(`
|
|
75
|
+
`,B-1))}function Ne(h,B,Y){let ge,se,G,_,W,ae;const Z=h.kind,ce=h.result;let fe=h.input.charCodeAt(h.position);if(M(fe)||w(fe)||fe===35||fe===38||fe===42||fe===33||fe===124||fe===62||fe===39||fe===34||fe===37||fe===64||fe===96)return!1;if(fe===63||fe===45){const he=h.input.charCodeAt(h.position+1);if(M(he)||Y&&w(he))return!1}for(h.kind="scalar",h.result="",ge=se=h.position,G=!1;fe!==0;){if(fe===58){const he=h.input.charCodeAt(h.position+1);if(M(he)||Y&&w(he))break}else if(fe===35){const he=h.input.charCodeAt(h.position-1);if(M(he))break}else{if(h.position===h.lineStart&&it(h)||Y&&w(fe))break;if($(fe))if(_=h.line,W=h.lineStart,ae=h.lineIndent,Ze(h,!1,-1),h.lineIndent>=B){G=!0,fe=h.input.charCodeAt(h.position);continue}else{h.position=se,h.line=_,h.lineStart=W,h.lineIndent=ae;break}}G&&(we(h,ge,se,!1),at(h,h.line-_),ge=se=h.position,G=!1),O(fe)||(se=h.position+1),fe=h.input.charCodeAt(++h.position)}return we(h,ge,se,!1),h.result?!0:(h.kind=Z,h.result=ce,!1)}function We(h,B){let Y,ge,se=h.input.charCodeAt(h.position);if(se!==39)return!1;for(h.kind="scalar",h.result="",h.position++,Y=ge=h.position;(se=h.input.charCodeAt(h.position))!==0;)if(se===39)if(we(h,Y,h.position,!0),se=h.input.charCodeAt(++h.position),se===39)Y=h.position,h.position++,ge=h.position;else return!0;else $(se)?(we(h,Y,ge,!0),at(h,Ze(h,!1,B)),Y=ge=h.position):h.position===h.lineStart&&it(h)?ne(h,"unexpected end of the document within a single quoted scalar"):(h.position++,O(se)||(ge=h.position));ne(h,"unexpected end of the stream within a single quoted scalar")}function qe(h,B){let Y,ge,se,G=h.input.charCodeAt(h.position);if(G!==34)return!1;for(h.kind="scalar",h.result="",h.position++,Y=ge=h.position;(G=h.input.charCodeAt(h.position))!==0;){if(G===34)return we(h,Y,h.position,!0),h.position++,!0;if(G===92){if(we(h,Y,h.position,!0),G=h.input.charCodeAt(++h.position),$(G))Ze(h,!1,B);else if(G<256&&X[G])h.result+=de[G],h.position++;else if((se=E(G))>0){let _=se,W=0;for(;_>0;_--)G=h.input.charCodeAt(++h.position),(se=A(G))>=0?W=(W<<4)+se:ne(h,"expected hexadecimal character");h.result+=L(W),h.position++}else ne(h,"unknown escape sequence");Y=ge=h.position}else $(G)?(we(h,Y,ge,!0),at(h,Ze(h,!1,B)),Y=ge=h.position):h.position===h.lineStart&&it(h)?ne(h,"unexpected end of the document within a double quoted scalar"):(h.position++,O(G)||(ge=h.position))}ne(h,"unexpected end of the stream within a double quoted scalar")}function q(h,B){let Y=!0,ge,se,G;const _=h.tag;let W;const ae=h.anchor;let Z,ce,fe,he;const Ae=Object.create(null);let Ce,He,Pe,Xe=h.input.charCodeAt(h.position);if(Xe===91)Z=93,he=!1,W=[];else if(Xe===123)Z=125,he=!0,W={};else return!1;for(h.anchor!==null&&Se(h,h.anchor,W),Xe=h.input.charCodeAt(++h.position);Xe!==0;){if(Ze(h,!0,B),Xe=h.input.charCodeAt(h.position),Xe===Z)return h.position++,h.tag=_,h.anchor=ae,h.kind=he?"mapping":"sequence",h.result=W,!0;if(Y?Xe===44&&ne(h,"expected the node content, but found ','"):ne(h,"missed comma between flow collection entries"),He=Ce=Pe=null,ce=fe=!1,Xe===63){const mt=h.input.charCodeAt(h.position+1);M(mt)&&(ce=fe=!0,h.position++,Ze(h,!0,B))}ge=h.line,se=h.lineStart,G=h.position,nt(h,B,r,!1,!0),He=h.tag,Ce=h.result,Ze(h,!0,B),Xe=h.input.charCodeAt(h.position),(fe||h.line===ge)&&Xe===58&&(ce=!0,Xe=h.input.charCodeAt(++h.position),Ze(h,!0,B),nt(h,B,r,!1,!0),Pe=h.result),he?xe(h,W,Ae,He,Ce,Pe,ge,se,G):ce?W.push(xe(h,null,Ae,He,Ce,Pe,ge,se,G)):W.push(Ce),Ze(h,!0,B),Xe=h.input.charCodeAt(h.position),Xe===44?(Y=!0,Xe=h.input.charCodeAt(++h.position)):Y=!1}ne(h,"unexpected end of the stream within a flow collection")}function N(h,B){let Y,ge=u,se=!1,G=!1,_=B,W=0,ae=!1,Z,ce=h.input.charCodeAt(h.position);if(ce===124)Y=!1;else if(ce===62)Y=!0;else return!1;for(h.kind="scalar",h.result="";ce!==0;)if(ce=h.input.charCodeAt(++h.position),ce===43||ce===45)u===ge?ge=ce===43?g:f:ne(h,"repeat of a chomping mode identifier");else if((Z=D(ce))>=0)Z===0?ne(h,"bad explicit indentation width of a block scalar; it cannot be less than one"):G?ne(h,"repeat of an indentation width identifier"):(_=B+Z-1,G=!0);else break;if(O(ce)){do ce=h.input.charCodeAt(++h.position);while(O(ce));if(ce===35)do ce=h.input.charCodeAt(++h.position);while(!$(ce)&&ce!==0)}for(;ce!==0;){for(Ue(h),h.lineIndent=0,ce=h.input.charCodeAt(h.position);(!G||h.lineIndent<_)&&ce===32;)h.lineIndent++,ce=h.input.charCodeAt(++h.position);if(!G&&h.lineIndent>_&&(_=h.lineIndent),$(ce)){W++;continue}if(!G&&_===0&&ne(h,"missing indentation for block scalar"),h.lineIndent<_){ge===g?h.result+=e.repeat(`
|
|
76
|
+
`,se?1+W:W):ge===u&&se&&(h.result+=`
|
|
77
|
+
`);break}Y?O(ce)?(ae=!0,h.result+=e.repeat(`
|
|
78
|
+
`,se?1+W:W)):ae?(ae=!1,h.result+=e.repeat(`
|
|
79
|
+
`,W+1)):W===0?se&&(h.result+=" "):h.result+=e.repeat(`
|
|
80
|
+
`,W):h.result+=e.repeat(`
|
|
81
|
+
`,se?1+W:W),se=!0,G=!0,W=0;const fe=h.position;for(;!$(ce)&&ce!==0;)ce=h.input.charCodeAt(++h.position);we(h,fe,h.position,!1)}return!0}function F(h,B){const Y=h.tag,ge=h.anchor,se=[];let G=!1;if(h.firstTabInLine!==-1)return!1;h.anchor!==null&&Se(h,h.anchor,se);let _=h.input.charCodeAt(h.position);for(;_!==0&&(h.firstTabInLine!==-1&&(h.position=h.firstTabInLine,ne(h,"tab characters must not be used in indentation")),_===45);){const W=h.input.charCodeAt(h.position+1);if(!M(W))break;if(G=!0,h.position++,Ze(h,!0,-1)&&h.lineIndent<=B){se.push(null),_=h.input.charCodeAt(h.position);continue}const ae=h.line;if(nt(h,B,c,!1,!0),se.push(h.result),Ze(h,!0,-1),_=h.input.charCodeAt(h.position),(h.line===ae||h.lineIndent>B)&&_!==0)ne(h,"bad indentation of a sequence entry");else if(h.lineIndent<B)break}return G?(h.tag=Y,h.anchor=ge,h.kind="sequence",h.result=se,!0):!1}function ee(h,B,Y){let ge,se,G,_;const W=h.tag,ae=h.anchor,Z={},ce=Object.create(null);let fe=null,he=null,Ae=null,Ce=!1,He=!1;if(h.firstTabInLine!==-1)return!1;h.anchor!==null&&Se(h,h.anchor,Z);let Pe=h.input.charCodeAt(h.position);for(;Pe!==0;){!Ce&&h.firstTabInLine!==-1&&(h.position=h.firstTabInLine,ne(h,"tab characters must not be used in indentation"));const Xe=h.input.charCodeAt(h.position+1),mt=h.line;if((Pe===63||Pe===58)&&M(Xe))Pe===63?(Ce&&(xe(h,Z,ce,fe,he,null,se,G,_),fe=he=Ae=null),He=!0,Ce=!0,ge=!0):Ce?(Ce=!1,ge=!0):ne(h,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),h.position+=1,Pe=Xe;else{if(se=h.line,G=h.lineStart,_=h.position,!nt(h,Y,s,!1,!0))break;if(h.line===mt){for(Pe=h.input.charCodeAt(h.position);O(Pe);)Pe=h.input.charCodeAt(++h.position);if(Pe===58)Pe=h.input.charCodeAt(++h.position),M(Pe)||ne(h,"a whitespace character is expected after the key-value separator within a block mapping"),Ce&&(xe(h,Z,ce,fe,he,null,se,G,_),fe=he=Ae=null),He=!0,Ce=!1,ge=!1,fe=h.tag,he=h.result;else if(He)ne(h,"can not read an implicit mapping pair; a colon is missed");else return h.tag=W,h.anchor=ae,!0}else if(He)ne(h,"can not read a block mapping entry; a multiline key may not be an implicit key");else return h.tag=W,h.anchor=ae,!0}if((h.line===mt||h.lineIndent>B)&&(Ce&&(se=h.line,G=h.lineStart,_=h.position),nt(h,B,m,!0,ge)&&(Ce?he=h.result:Ae=h.result),Ce||(xe(h,Z,ce,fe,he,Ae,se,G,_),fe=he=Ae=null),Ze(h,!0,-1),Pe=h.input.charCodeAt(h.position)),(h.line===mt||h.lineIndent>B)&&Pe!==0)ne(h,"bad indentation of a mapping entry");else if(h.lineIndent<B)break}return Ce&&xe(h,Z,ce,fe,he,null,se,G,_),He&&(h.tag=W,h.anchor=ae,h.kind="mapping",h.result=Z),He}function me(h){let B=!1,Y=!1,ge,se,G=h.input.charCodeAt(h.position);if(G!==33)return!1;h.tag!==null&&ne(h,"duplication of a tag property"),G=h.input.charCodeAt(++h.position),G===60?(B=!0,G=h.input.charCodeAt(++h.position)):G===33?(Y=!0,ge="!!",G=h.input.charCodeAt(++h.position)):ge="!";let _=h.position;if(B){do G=h.input.charCodeAt(++h.position);while(G!==0&&G!==62);h.position<h.length?(se=h.input.slice(_,h.position),G=h.input.charCodeAt(++h.position)):ne(h,"unexpected end of the stream within a verbatim tag")}else{for(;G!==0&&!M(G);)G===33&&(Y?ne(h,"tag suffix cannot contain exclamation marks"):(ge=h.input.slice(_-1,h.position+1),P.test(ge)||ne(h,"named tag handle cannot contain such characters"),Y=!0,_=h.position+1)),G=h.input.charCodeAt(++h.position);se=h.input.slice(_,h.position),C.test(se)&&ne(h,"tag suffix cannot contain flow indicator characters")}se&&!j.test(se)&&ne(h,"tag name cannot contain such characters: "+se);try{se=decodeURIComponent(se)}catch{ne(h,"tag name is malformed: "+se)}return B?h.tag=se:o.call(h.tagMap,ge)?h.tag=h.tagMap[ge]+se:ge==="!"?h.tag="!"+se:ge==="!!"?h.tag="tag:yaml.org,2002:"+se:ne(h,'undeclared tag handle "'+ge+'"'),!0}function $e(h){let B=h.input.charCodeAt(h.position);if(B!==38)return!1;h.anchor!==null&&ne(h,"duplication of an anchor property"),B=h.input.charCodeAt(++h.position);const Y=h.position;for(;B!==0&&!M(B)&&!w(B);)B=h.input.charCodeAt(++h.position);return h.position===Y&&ne(h,"name of an anchor node must contain at least one character"),h.anchor=h.input.slice(Y,h.position),!0}function ze(h){let B=h.input.charCodeAt(h.position);if(B!==42)return!1;B=h.input.charCodeAt(++h.position);const Y=h.position;for(;B!==0&&!M(B)&&!w(B);)B=h.input.charCodeAt(++h.position);h.position===Y&&ne(h,"name of an alias node must contain at least one character");const ge=h.input.slice(Y,h.position);return o.call(h.anchorMap,ge)||ne(h,'unidentified alias "'+ge+'"'),h.result=h.anchorMap[ge],Ze(h,!0,-1),!0}function tt(h,B,Y,ge){const se=ue(h);return oe(h),ke(h,B),h.tag=null,h.anchor=null,h.kind=null,h.result=null,ee(h,Y,ge)&&h.kind==="mapping"?(be(h),!0):(re(h),ke(h,se),!1)}function nt(h,B,Y,ge,se){let G,_,W=1,ae=!1,Z=!1,ce=null,fe,he,Ae;h.depth>=h.maxDepth&&ne(h,"nesting exceeded maxDepth ("+h.maxDepth+")"),h.depth+=1,h.listener!==null&&h.listener("open",h),h.tag=null,h.anchor=null,h.kind=null,h.result=null;const Ce=G=_=m===Y||c===Y;if(ge&&Ze(h,!0,-1)&&(ae=!0,h.lineIndent>B?W=1:h.lineIndent===B?W=0:h.lineIndent<B&&(W=-1)),W===1)for(;;){const He=h.input.charCodeAt(h.position),Pe=ue(h);if(ae&&(He===33&&h.tag!==null||He===38&&h.anchor!==null)||!me(h)&&!$e(h))break;ce===null&&(ce=Pe),Ze(h,!0,-1)?(ae=!0,_=Ce,h.lineIndent>B?W=1:h.lineIndent===B?W=0:h.lineIndent<B&&(W=-1)):_=!1}if(_&&(_=ae||se),W===1||m===Y)if(r===Y||s===Y?he=B:he=B+1,Ae=h.position-h.lineStart,W===1)if(_&&(F(h,Ae)||ee(h,Ae,he))||q(h,he))Z=!0;else{const He=h.input.charCodeAt(h.position);ce!==null&&Ce&&!_&&He!==124&&He!==62&&tt(h,ce,ce.position-ce.lineStart,he)||G&&N(h,he)||We(h,he)||qe(h,he)?Z=!0:ze(h)?(Z=!0,(h.tag!==null||h.anchor!==null)&&ne(h,"alias node should not have any properties")):Ne(h,he,r===Y)&&(Z=!0,h.tag===null&&(h.tag="?")),h.anchor!==null&&Se(h,h.anchor,h.result)}else W===0&&(Z=_&&F(h,Ae));if(h.tag===null)h.anchor!==null&&Se(h,h.anchor,h.result);else if(h.tag==="?"){h.result!==null&&h.kind!=="scalar"&&ne(h,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+h.kind+'"');for(let He=0,Pe=h.implicitTypes.length;He<Pe;He+=1)if(fe=h.implicitTypes[He],fe.resolve(h.result)){h.result=fe.construct(h.result),h.tag=fe.tag,h.anchor!==null&&Se(h,h.anchor,h.result);break}}else if(h.tag!=="!"){if(o.call(h.typeMap[h.kind||"fallback"],h.tag))fe=h.typeMap[h.kind||"fallback"][h.tag];else{fe=null;const He=h.typeMap.multi[h.kind||"fallback"];for(let Pe=0,Xe=He.length;Pe<Xe;Pe+=1)if(h.tag.slice(0,He[Pe].tag.length)===He[Pe].tag){fe=He[Pe];break}}fe||ne(h,"unknown tag !<"+h.tag+">"),h.result!==null&&fe.kind!==h.kind&&ne(h,"unacceptable node kind for !<"+h.tag+'> tag; it should be "'+fe.kind+'", not "'+h.kind+'"'),fe.resolve(h.result,h.tag)?(h.result=fe.construct(h.result,h.tag),h.anchor!==null&&Se(h,h.anchor,h.result)):ne(h,"cannot resolve a node with !<"+h.tag+"> explicit tag")}return h.listener!==null&&h.listener("close",h),h.depth-=1,h.tag!==null||h.anchor!==null||Z}function pt(h){const B=h.position;let Y=!1,ge;for(h.version=null,h.checkLineBreaks=h.legacy,h.tagMap=Object.create(null),h.anchorMap=Object.create(null);(ge=h.input.charCodeAt(h.position))!==0&&(Ze(h,!0,-1),ge=h.input.charCodeAt(h.position),!(h.lineIndent>0||ge!==37));){Y=!0,ge=h.input.charCodeAt(++h.position);let se=h.position;for(;ge!==0&&!M(ge);)ge=h.input.charCodeAt(++h.position);const G=h.input.slice(se,h.position),_=[];for(G.length<1&&ne(h,"directive name must not be less than one character in length");ge!==0;){for(;O(ge);)ge=h.input.charCodeAt(++h.position);if(ge===35){do ge=h.input.charCodeAt(++h.position);while(ge!==0&&!$(ge));break}if($(ge))break;for(se=h.position;ge!==0&&!M(ge);)ge=h.input.charCodeAt(++h.position);_.push(h.input.slice(se,h.position))}ge!==0&&Ue(h),o.call(Le,G)?Le[G](h,G,_):je(h,'unknown document directive "'+G+'"')}if(Ze(h,!0,-1),h.lineIndent===0&&h.input.charCodeAt(h.position)===45&&h.input.charCodeAt(h.position+1)===45&&h.input.charCodeAt(h.position+2)===45?(h.position+=3,Ze(h,!0,-1)):Y&&ne(h,"directives end mark is expected"),nt(h,h.lineIndent-1,m,!1,!0),Ze(h,!0,-1),h.checkLineBreaks&&k.test(h.input.slice(B,h.position))&&je(h,"non-ASCII line breaks are interpreted as content"),h.documents.push(h.result),h.position===h.lineStart&&it(h)){h.input.charCodeAt(h.position)===46&&(h.position+=3,Ze(h,!0,-1));return}h.position<h.length-1&&ne(h,"end of the stream or a document separator is expected")}function bt(h,B){h=String(h),B=B||{},h.length!==0&&(h.charCodeAt(h.length-1)!==10&&h.charCodeAt(h.length-1)!==13&&(h+=`
|
|
82
|
+
`),h.charCodeAt(0)===65279&&(h=h.slice(1)));const Y=new Me(h,B),ge=h.indexOf("\0");for(ge!==-1&&(Y.position=ge,ne(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;)pt(Y);return Y.documents}function Oe(h,B,Y){B!==null&&typeof B=="object"&&typeof Y>"u"&&(Y=B,B=null);const ge=bt(h,Y);if(typeof B!="function")return ge;for(let se=0,G=ge.length;se<G;se+=1)B(ge[se])}function Ye(h,B){const Y=bt(h,B);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 Wd.loadAll=Oe,Wd.load=Ye,Wd}var Xf={},U0;function A$(){if(U0)return Xf;U0=1;const e=Wc(),t=Gc(),n=Sv(),a=Object.prototype.toString,o=Object.prototype.hasOwnProperty,r=65279,s=9,c=10,m=13,u=32,f=33,g=34,S=35,k=37,C=38,P=39,j=42,R=44,$=45,O=58,M=61,w=62,A=63,E=64,D=91,U=93,L=96,J=123,X=124,de=125,Me={};Me[0]="\\0",Me[7]="\\a",Me[8]="\\b",Me[9]="\\t",Me[10]="\\n",Me[11]="\\v",Me[12]="\\f",Me[13]="\\r",Me[27]="\\e",Me[34]='\\"',Me[92]="\\\\",Me[133]="\\N",Me[160]="\\_",Me[8232]="\\L",Me[8233]="\\P";const Ie=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],ne=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function je(_,W){if(W===null)return{};const ae={},Z=Object.keys(W);for(let ce=0,fe=Z.length;ce<fe;ce+=1){let he=Z[ce],Ae=String(W[he]);he.slice(0,2)==="!!"&&(he="tag:yaml.org,2002:"+he.slice(2));const Ce=_.compiledTypeMap.fallback[he];Ce&&o.call(Ce.styleAliases,Ae)&&(Ae=Ce.styleAliases[Ae]),ae[he]=Ae}return ae}function Se(_){let W,ae;const Z=_.toString(16).toUpperCase();if(_<=255)W="x",ae=2;else if(_<=65535)W="u",ae=4;else if(_<=4294967295)W="U",ae=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+W+e.repeat("0",ae-Z.length)+Z}const oe=1,be=2;function re(_){this.schema=_.schema||n,this.indent=Math.max(1,_.indent||2),this.noArrayIndent=_.noArrayIndent||!1,this.skipInvalid=_.skipInvalid||!1,this.flowLevel=e.isNothing(_.flowLevel)?-1:_.flowLevel,this.styleMap=je(this.schema,_.styles||null),this.sortKeys=_.sortKeys||!1,this.lineWidth=_.lineWidth||80,this.noRefs=_.noRefs||!1,this.noCompatMode=_.noCompatMode||!1,this.condenseFlow=_.condenseFlow||!1,this.quotingType=_.quotingType==='"'?be:oe,this.forceQuotes=_.forceQuotes||!1,this.replacer=typeof _.replacer=="function"?_.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ue(_,W){const ae=e.repeat(" ",W);let Z=0,ce="";const fe=_.length;for(;Z<fe;){let he;const Ae=_.indexOf(`
|
|
83
|
+
`,Z);Ae===-1?(he=_.slice(Z),Z=fe):(he=_.slice(Z,Ae+1),Z=Ae+1),he.length&&he!==`
|
|
84
|
+
`&&(ce+=ae),ce+=he}return ce}function ke(_,W){return`
|
|
85
|
+
`+e.repeat(" ",_.indent*W)}function Le(_,W){for(let ae=0,Z=_.implicitTypes.length;ae<Z;ae+=1)if(_.implicitTypes[ae].resolve(W))return!0;return!1}function we(_){return _===u||_===s}function le(_){return _>=32&&_<=126||_>=161&&_<=55295&&_!==8232&&_!==8233||_>=57344&&_<=65533&&_!==r||_>=65536&&_<=1114111}function xe(_){return le(_)&&_!==r&&_!==m&&_!==c}function Ue(_,W,ae){const Z=xe(_),ce=Z&&!we(_);return(ae?Z:Z&&_!==R&&_!==D&&_!==U&&_!==J&&_!==de)&&_!==S&&!(W===O&&!ce)||xe(W)&&!we(W)&&_===S||W===O&&ce}function Ze(_){return le(_)&&_!==r&&!we(_)&&_!==$&&_!==A&&_!==O&&_!==R&&_!==D&&_!==U&&_!==J&&_!==de&&_!==S&&_!==C&&_!==j&&_!==f&&_!==X&&_!==M&&_!==w&&_!==P&&_!==g&&_!==k&&_!==E&&_!==L}function it(_){return!we(_)&&_!==O}function at(_,W){const ae=_.charCodeAt(W);let Z;return ae>=55296&&ae<=56319&&W+1<_.length&&(Z=_.charCodeAt(W+1),Z>=56320&&Z<=57343)?(ae-55296)*1024+Z-56320+65536:ae}function Ne(_){return/^\n* /.test(_)}const We=1,qe=2,q=3,N=4,F=5;function ee(_,W,ae,Z,ce,fe,he,Ae){let Ce,He=0,Pe=null,Xe=!1,mt=!1;const fn=Z!==-1;let Mt=-1,dn=Ze(at(_,0))&&it(at(_,_.length-1));if(W||he)for(Ce=0;Ce<_.length;He>=65536?Ce+=2:Ce++){if(He=at(_,Ce),!le(He))return F;dn=dn&&Ue(He,Pe,Ae),Pe=He}else{for(Ce=0;Ce<_.length;He>=65536?Ce+=2:Ce++){if(He=at(_,Ce),He===c)Xe=!0,fn&&(mt=mt||Ce-Mt-1>Z&&_[Mt+1]!==" ",Mt=Ce);else if(!le(He))return F;dn=dn&&Ue(He,Pe,Ae),Pe=He}mt=mt||fn&&Ce-Mt-1>Z&&_[Mt+1]!==" "}return!Xe&&!mt?dn&&!he&&!ce(_)?We:fe===be?F:qe:ae>9&&Ne(_)?F:he?fe===be?F:qe:mt?N:q}function me(_,W,ae,Z,ce){_.dump=(function(){if(W.length===0)return _.quotingType===be?'""':"''";if(!_.noCompatMode&&(Ie.indexOf(W)!==-1||ne.test(W)))return _.quotingType===be?'"'+W+'"':"'"+W+"'";const fe=_.indent*Math.max(1,ae),he=_.lineWidth===-1?-1:Math.max(Math.min(_.lineWidth,40),_.lineWidth-fe),Ae=Z||_.flowLevel>-1&&ae>=_.flowLevel;function Ce(He){return Le(_,He)}switch(ee(W,Ae,_.indent,he,Ce,_.quotingType,_.forceQuotes&&!Z,ce)){case We:return W;case qe:return"'"+W.replace(/'/g,"''")+"'";case q:return"|"+$e(W,_.indent)+ze(ue(W,fe));case N:return">"+$e(W,_.indent)+ze(ue(tt(W,he),fe));case F:return'"'+pt(W)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function $e(_,W){const ae=Ne(_)?String(W):"",Z=_[_.length-1]===`
|
|
86
|
+
`,fe=Z&&(_[_.length-2]===`
|
|
87
|
+
`||_===`
|
|
88
|
+
`)?"+":Z?"":"-";return ae+fe+`
|
|
89
|
+
`}function ze(_){return _[_.length-1]===`
|
|
90
|
+
`?_.slice(0,-1):_}function tt(_,W){const ae=/(\n+)([^\n]*)/g;let Z=(function(){let Ae=_.indexOf(`
|
|
91
|
+
`);return Ae=Ae!==-1?Ae:_.length,ae.lastIndex=Ae,nt(_.slice(0,Ae),W)})(),ce=_[0]===`
|
|
92
|
+
`||_[0]===" ",fe,he;for(;he=ae.exec(_);){const Ae=he[1],Ce=he[2];fe=Ce[0]===" ",Z+=Ae+(!ce&&!fe&&Ce!==""?`
|
|
93
|
+
`:"")+nt(Ce,W),ce=fe}return Z}function nt(_,W){if(_===""||_[0]===" ")return _;const ae=/ [^ ]/g;let Z,ce=0,fe,he=0,Ae=0,Ce="";for(;Z=ae.exec(_);)Ae=Z.index,Ae-ce>W&&(fe=he>ce?he:Ae,Ce+=`
|
|
94
|
+
`+_.slice(ce,fe),ce=fe+1),he=Ae;return Ce+=`
|
|
95
|
+
`,_.length-ce>W&&he>ce?Ce+=_.slice(ce,he)+`
|
|
96
|
+
`+_.slice(he+1):Ce+=_.slice(ce),Ce.slice(1)}function pt(_){let W="",ae=0;for(let Z=0;Z<_.length;ae>=65536?Z+=2:Z++){ae=at(_,Z);const ce=Me[ae];!ce&&le(ae)?(W+=_[Z],ae>=65536&&(W+=_[Z+1])):W+=ce||Se(ae)}return W}function bt(_,W,ae){let Z="";const ce=_.tag;for(let fe=0,he=ae.length;fe<he;fe+=1){let Ae=ae[fe];_.replacer&&(Ae=_.replacer.call(ae,String(fe),Ae)),(Y(_,W,Ae,!1,!1)||typeof Ae>"u"&&Y(_,W,null,!1,!1))&&(Z!==""&&(Z+=","+(_.condenseFlow?"":" ")),Z+=_.dump)}_.tag=ce,_.dump="["+Z+"]"}function Oe(_,W,ae,Z){let ce="";const fe=_.tag;for(let he=0,Ae=ae.length;he<Ae;he+=1){let Ce=ae[he];_.replacer&&(Ce=_.replacer.call(ae,String(he),Ce)),(Y(_,W+1,Ce,!0,!0,!1,!0)||typeof Ce>"u"&&Y(_,W+1,null,!0,!0,!1,!0))&&((!Z||ce!=="")&&(ce+=ke(_,W)),_.dump&&c===_.dump.charCodeAt(0)?ce+="-":ce+="- ",ce+=_.dump)}_.tag=fe,_.dump=ce||"[]"}function Ye(_,W,ae){let Z="";const ce=_.tag,fe=Object.keys(ae);for(let he=0,Ae=fe.length;he<Ae;he+=1){let Ce="";Z!==""&&(Ce+=", "),_.condenseFlow&&(Ce+='"');const He=fe[he];let Pe=ae[He];_.replacer&&(Pe=_.replacer.call(ae,He,Pe)),Y(_,W,He,!1,!1)&&(_.dump.length>1024&&(Ce+="? "),Ce+=_.dump+(_.condenseFlow?'"':"")+":"+(_.condenseFlow?"":" "),Y(_,W,Pe,!1,!1)&&(Ce+=_.dump,Z+=Ce))}_.tag=ce,_.dump="{"+Z+"}"}function h(_,W,ae,Z){let ce="";const fe=_.tag,he=Object.keys(ae);if(_.sortKeys===!0)he.sort();else if(typeof _.sortKeys=="function")he.sort(_.sortKeys);else if(_.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Ae=0,Ce=he.length;Ae<Ce;Ae+=1){let He="";(!Z||ce!=="")&&(He+=ke(_,W));const Pe=he[Ae];let Xe=ae[Pe];if(_.replacer&&(Xe=_.replacer.call(ae,Pe,Xe)),!Y(_,W+1,Pe,!0,!0,!0))continue;const mt=_.tag!==null&&_.tag!=="?"||_.dump&&_.dump.length>1024;mt&&(_.dump&&c===_.dump.charCodeAt(0)?He+="?":He+="? "),He+=_.dump,mt&&(He+=ke(_,W)),Y(_,W+1,Xe,!0,mt)&&(_.dump&&c===_.dump.charCodeAt(0)?He+=":":He+=": ",He+=_.dump,ce+=He)}_.tag=fe,_.dump=ce||"{}"}function B(_,W,ae){const Z=ae?_.explicitTypes:_.implicitTypes;for(let ce=0,fe=Z.length;ce<fe;ce+=1){const he=Z[ce];if((he.instanceOf||he.predicate)&&(!he.instanceOf||typeof W=="object"&&W instanceof he.instanceOf)&&(!he.predicate||he.predicate(W))){if(ae?he.multi&&he.representName?_.tag=he.representName(W):_.tag=he.tag:_.tag="?",he.represent){const Ae=_.styleMap[he.tag]||he.defaultStyle;let Ce;if(a.call(he.represent)==="[object Function]")Ce=he.represent(W,Ae);else if(o.call(he.represent,Ae))Ce=he.represent[Ae](W,Ae);else throw new t("!<"+he.tag+'> tag resolver accepts not "'+Ae+'" style');_.dump=Ce}return!0}}return!1}function Y(_,W,ae,Z,ce,fe,he){_.tag=null,_.dump=ae,B(_,ae,!1)||B(_,ae,!0);const Ae=a.call(_.dump),Ce=Z;Z&&(Z=_.flowLevel<0||_.flowLevel>W);const He=Ae==="[object Object]"||Ae==="[object Array]";let Pe,Xe;if(He&&(Pe=_.duplicates.indexOf(ae),Xe=Pe!==-1),(_.tag!==null&&_.tag!=="?"||Xe||_.indent!==2&&W>0)&&(ce=!1),Xe&&_.usedDuplicates[Pe])_.dump="*ref_"+Pe;else{if(He&&Xe&&!_.usedDuplicates[Pe]&&(_.usedDuplicates[Pe]=!0),Ae==="[object Object]")Z&&Object.keys(_.dump).length!==0?(h(_,W,_.dump,ce),Xe&&(_.dump="&ref_"+Pe+_.dump)):(Ye(_,W,_.dump),Xe&&(_.dump="&ref_"+Pe+" "+_.dump));else if(Ae==="[object Array]")Z&&_.dump.length!==0?(_.noArrayIndent&&!he&&W>0?Oe(_,W-1,_.dump,ce):Oe(_,W,_.dump,ce),Xe&&(_.dump="&ref_"+Pe+_.dump)):(bt(_,W,_.dump),Xe&&(_.dump="&ref_"+Pe+" "+_.dump));else if(Ae==="[object String]")_.tag!=="?"&&me(_,_.dump,W,fe,Ce);else{if(Ae==="[object Undefined]")return!1;if(_.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Ae)}if(_.tag!==null&&_.tag!=="?"){let mt=encodeURI(_.tag[0]==="!"?_.tag.slice(1):_.tag).replace(/!/g,"%21");_.tag[0]==="!"?mt="!"+mt:mt.slice(0,18)==="tag:yaml.org,2002:"?mt="!!"+mt.slice(18):mt="!<"+mt+">",_.dump=mt+" "+_.dump}}return!0}function ge(_,W){const ae=[],Z=[];se(_,ae,Z);const ce=Z.length;for(let fe=0;fe<ce;fe+=1)W.duplicates.push(ae[Z[fe]]);W.usedDuplicates=new Array(ce)}function se(_,W,ae){if(_!==null&&typeof _=="object"){const Z=W.indexOf(_);if(Z!==-1)ae.indexOf(Z)===-1&&ae.push(Z);else if(W.push(_),Array.isArray(_))for(let ce=0,fe=_.length;ce<fe;ce+=1)se(_[ce],W,ae);else{const ce=Object.keys(_);for(let fe=0,he=ce.length;fe<he;fe+=1)se(_[ce[fe]],W,ae)}}}function G(_,W){W=W||{};const ae=new re(W);ae.noRefs||ge(_,ae);let Z=_;return ae.replacer&&(Z=ae.replacer.call({"":Z},"",Z)),Y(ae,0,Z,!0,!0)?ae.dump+`
|
|
97
|
+
`:""}return Xf.dump=G,Xf}var z0;function T$(){if(z0)return Vn;z0=1;const e=P$(),t=A$();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 Vn.Type=ta(),Vn.Schema=e1(),Vn.FAILSAFE_SCHEMA=i1(),Vn.JSON_SCHEMA=c1(),Vn.CORE_SCHEMA=d1(),Vn.DEFAULT_SCHEMA=Sv(),Vn.load=e.load,Vn.loadAll=e.loadAll,Vn.dump=t.dump,Vn.YAMLException=Gc(),Vn.types={binary:p1(),float:l1(),map:a1(),null:o1(),pairs:h1(),set:g1(),timestamp:u1(),bool:r1(),int:s1(),merge:m1(),omap:f1(),seq:n1(),str:t1()},Vn.safeLoad=n("safeLoad","load"),Vn.safeLoadAll=n("safeLoadAll","loadAll"),Vn.safeDump=n("safeDump","dump"),Vn}var E$=T$();const j$=C$(E$),{Type:Yne,Schema:Qne,FAILSAFE_SCHEMA:Xne,JSON_SCHEMA:eae,CORE_SCHEMA:tae,DEFAULT_SCHEMA:nae,load:aae,loadAll:iae,dump:oae,YAMLException:rae,types:sae,safeLoad:lae,safeLoadAll:cae,safeDump:dae}=j$,xv=3e3,kv=9999,uae="openpond.yaml",M$=["google","github","x"],wv=new Set([22,2222,2375,2376,3108,5900,5901,6080,7818]),B0=p(i().trim().min(1).max(1e3)).max(50),Sc=i().trim().min(1).max(4096).refine(S1,{message:"path must be a relative workspace path"}),O$=i().trim().min(1).max(500).refine(e=>!e.includes("\0")&&!/\s/.test(e),"image ref must be a single OCI reference"),$$=i().trim().regex(/^sha256:[0-9a-f]{64}$/i),v1=i().trim().min(1).max(500).refine(e=>e.startsWith("/")&&!e.includes("\0"),"workspaceRoot must be an absolute guest path"),N$=l({ref:O$,digest:$$.optional(),registrySecretRef:i().trim().min(1).max(500).optional(),platform:b("linux/amd64").optional(),workspaceRoot:v1.optional()}).strict(),D$=l({context:Sc.default("."),path:Sc.default("Dockerfile"),target:i().trim().min(1).max(191).optional(),buildArgs:te(i().max(191),i().max(500)).optional(),registrySecretRefs:p(i().trim().min(1).max(500)).max(10).optional(),platform:b("linux/amd64").optional(),workspaceRoot:v1.optional()}).strict(),H$=l({base:i().trim().min(1).max(120).optional(),snapshot:i().trim().min(1).max(191).optional(),image:N$.optional(),dockerfile:D$.optional()}).strict().superRefine((e,t)=>{[e.base,e.snapshot,e.image,e.dockerfile].filter(Boolean).length!==1&&t.addIssue({code:Yn.custom,message:"runtime must declare exactly one of base, snapshot, image, or dockerfile"})}),b1=l({cpu:d().positive().max(8).optional(),memoryGb:d().positive().max(32).optional(),diskGb:d().positive().max(100).optional()}).strict(),L$=l({provider:v(M$),scopes:p(i().trim().min(1).max(200)).max(100).default([]),capabilities:p(i().trim().min(1).max(200)).max(100).default([])}).strict(),q$=l({models:p(i().trim().min(1).max(200)).max(100).default([]),scopes:p(i().trim().min(1).max(200)).max(100).default([])}).strict(),U$=l({opchat:q$.optional()}).catchall(te(i(),ie())).default({}),z$=l({name:i().trim().regex(/^[A-Za-z_][A-Za-z0-9_-]*$/).max(63).optional(),mountPath:i().trim().min(1).max(256).optional(),storageGb:d().int().positive().max(100).optional(),deleteOnSandboxDelete:I().optional()}).strict(),B$=l({port:d().int().min(xv).max(kv).refine(e=>!wv.has(e),{message:"preview port is reserved"}),protocol:b("http").default("http"),label:i().trim().min(1).max(80).optional(),access:v(["private","public"]).default("private"),path:i().trim().min(1).max(512).refine(e=>e.startsWith("/"),{message:"preview path must start with /"}).default("/")}).strict(),y1=l({command:i().trim().min(1).max(1e3),cwd:Sc.optional(),timeoutSeconds:d().int().positive().max(86400).optional(),requiresStart:I().default(!1),ports:p(B$).max(20).default([]),artifactPaths:p(Sc).max(100).default([])}).strict(),F0=y1.extend({name:i().trim().min(1).max(80)}).strict(),F$=l({name:i().trim().min(1).max(80).optional(),service:i().trim().min(1).max(80).optional(),port:d().int().min(xv).max(kv).refine(e=>!wv.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(),V$=l({name:i().trim().min(1).max(80).optional(),port:d().int().min(xv).max(kv).refine(e=>!wv.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:d().int().min(100).max(599).default(200)}).strict(),K$=te(i(),ie()).refine(e=>e.type==="object","input schema must be a JSON schema object"),W$=l({name:i().trim().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).max(191),required:I().default(!1),secret:I().default(!0),description:i().trim().max(500).optional()}).strict(),eh=i().trim().min(1).max(120),G$=l({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:eh.optional(),scheduleType:v(["rate","cron","once"]).optional(),scheduleExpression:i().trim().min(1).max(500).optional(),timezone:i().trim().min(1).max(100).optional(),enabled:I().default(!0),startAt:eh.optional(),endAt:eh.optional(),maxRuns:d().int().positive().nullable().optional(),runtimePolicy:v(["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:l({kind:v(["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:I().optional()}).strict().optional(),requiresStart:I().optional(),budget:l({maxUsd:i().trim().min(1).max(40).optional()}).strict().optional(),resources:b1.optional(),quotas:te(i(),ie()).optional(),lifecycle:te(i(),ie()).optional(),retentionPolicy:te(i(),ie()).optional(),env:p(l({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(te(i(),ie())).max(20).optional(),metadata:te(i(),ie()).optional()}).strict().superRefine((e,t)=>{[e.cron,e.rate,e.once,e.scheduleExpression].filter(c=>typeof c=="string"&&c.trim()).length!==1&&t.addIssue({code:Yn.custom,path:["scheduleExpression"],message:"schedule must declare exactly one of cron, rate, once, or scheduleExpression"}),e.scheduleExpression&&!e.scheduleType&&t.addIssue({code:Yn.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:Yn.custom,path:["action"],message:"schedule action target is required"}),s==="service"&&!o&&t.addIssue({code:Yn.custom,path:["target","name"],message:"schedule service target name is required"}),s==="command"&&!a&&t.addIssue({code:Yn.custom,path:["command"],message:"schedule command target is required"})}),J$=l({schemaVersion:b(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:H$,resources:b1.optional(),setup:l({commands:B0.default([])}).strict().default({commands:[]}),validation:l({commands:B0.min(1),probes:p(V$).max(20).default([])}).strict(),start:y1,actions:p(F0).max(20).default([]),services:p(F0).max(20).default([]),schedules:p(G$).max(20).default([]),mcp:l({endpoints:p(F$).max(10).default([])}).strict().default({endpoints:[]}),volumes:p(z$).max(5).default([]),integrations:l({requiredLeases:p(L$).max(20).default([])}).strict().default({requiredLeases:[]}),permissions:U$,inputs:l({schema:K$.default({type:"object"}),env:p(W$).max(100).default([])}).strict().default({schema:{type:"object"},env:[]}),artifacts:l({paths:p(Sc).max(100).default([])}).strict().default({paths:[]}),network:l({egress:v(["restricted","allow","block"]).default("restricted")}).strict().default({egress:"restricted"})}).strict().superRefine((e,t)=>{Y$(e,t),Iv(t,e.volumes.flatMap(n=>n.name?[n.name]:[]),"volume names must be unique","volumes"),Q$(e,t),X$(e,t),eN(e,t),tN(e,t)}),Z$=l({path:i(),message:i(),code:i()});function mae(e){return[{kind:"start",name:"start",...e.start,artifactPaths:nh(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:nh(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:nh(t,e)}))]}function S1(e){return!e.includes("\0")&&!e.startsWith("/")&&!e.split(/[\\/]+/).some(t=>t===".."||t==="")}function Iv(e,t,n,a){const o=new Set;for(const r of t){if(o.has(r)){e.addIssue({code:Yn.custom,path:[a],message:n});return}o.add(r)}}function Y$(e,t){const n=["start",...e.actions.map(a=>a.name),...e.services.map(a=>a.name)];Iv(t,n,"start, action, and service names must be unique","actions")}function Q$(e,t){const n=th(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=th(r),c=th(s["x-openpond-upload"]??s.xOpenPondUpload),m=typeof c.targetPath=="string"&&c.targetPath.trim()?c.targetPath.trim():typeof c.path=="string"&&c.path.trim()?c.path.trim():"";if(!m)continue;const u=m.replace(/^workspace\//,"").replace(/^\/+/,"").replace(/\/+$/,"");if(!S1(u)){t.addIssue({code:Yn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target must be a relative workspace path"});continue}const f=u.split("/");f[0]==="volumes"&&(!f[1]||!a.has(f[1]))&&t.addIssue({code:Yn.custom,path:["inputs","schema","properties",o,"x-openpond-upload","targetPath"],message:"upload target references an undeclared volume"})}}function X$(e,t){Iv(t,e.inputs.env.map(n=>n.name),"env input names must be unique","inputs")}function eN(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:Yn.custom,path:["mcp","endpoints",o,"service"],message:`app MCP service does not exist: ${r.service}`});continue}s.has(r.port)||t.addIssue({code:Yn.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:Yn.custom,path:["mcp","endpoints",o,"port"],message:`app MCP port ${r.port} is not declared on start or services`})}}function tN(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 c=r.actionName??r.action??r.target?.actionName??(r.target?.kind==="action"?r.target?.name:null);if(c&&!n.has(c)&&t.addIssue({code:Yn.custom,path:["schedules",o,"action"],message:`schedule action target does not exist: ${c}`}),r.target?.kind==="service"){const m=r.target.name??"";m&&!a.has(m)&&t.addIssue({code:Yn.custom,path:["schedules",o,"target","name"],message:`schedule service target does not exist: ${m}`})}}}function th(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function nh(e,t){return e.artifactPaths.length>0?e.artifactPaths:t.artifacts.paths}const nN=l({id:i(),name:i(),description:i().nullable(),scheduleType:i(),scheduleExpression:i(),enabled:I(),rawEnabled:I().optional(),syncStatus:i().nullable(),syncError:i().nullable().optional(),startAt:i().nullable(),endAt:i().nullable(),maxRuns:d().nullable(),executionCount:d().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:I().optional(),payload:ie().optional()}).passthrough(),aN=l({total:d().int().nonnegative(),active:d().int().nonnegative(),paused:d().int().nonnegative(),enabled:d().int().nonnegative().optional(),disabled:d().int().nonnegative().optional(),nextRunAt:i().nullable().optional(),lastRunAt:i().nullable().optional(),schedules:p(nN).optional().default([]),truncated:I().optional()}).passthrough(),ah=l({name:i(),kind:v(["start","action","service"]),command:i(),cwd:i().nullable(),timeoutSeconds:d().nullable(),requiresStart:I(),ports:p(l({port:d(),protocol:i(),label:i().nullable(),access:i(),path:i()}).passthrough()).default([]),artifactPaths:p(i()).default([])}).passthrough(),iN=l({schemaVersion:b(1),source:b("openpond.yaml"),manifestName:i(),manifestVersion:i(),manifestUseCase:i(),manifestDescription:i(),manifestPath:i(),manifestHash:i(),inputSchema:te(i(),ie()).default({}),env:p(l({name:i(),required:I(),secret:I(),description:i().nullable()}).passthrough()).default([]),start:ah,actions:p(ah).default([]),services:p(ah).default([]),defaultActionName:i().nullable(),updatedAt:i()}).passthrough(),oN=l({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:I().optional().default(!1),sandboxActionRegistry:iN.nullable().optional(),sandboxManifestHash:i().nullable().optional(),sandboxManifestPath:i().nullable().optional(),sandboxManifestSyncedAt:i().nullable().optional(),sandboxManifestError:i().nullable().optional(),updatedAt:i().nullable().optional(),latestDeployment:l({id:i().optional(),status:i().optional(),deploymentDomain:i().nullable().optional(),createdAt:i().optional(),isProduction:I().nullable().optional(),gitBranch:i().nullable().optional()}).nullable().optional(),scheduleSummary:aN.nullable().optional()}),rN=l({detected:I(),rootPath:i(),manifestPath:i(),manifestHash:i().nullable().optional().default(null),manifest:te(i(),ie()).nullable().optional().default(null),normalizedManifest:J$.nullable().optional().default(null),valid:I().optional().default(!1),diagnostics:p(Z$).optional().default([])}),sN=l({appId:i(),appName:i(),gitOwner:i().nullable(),gitRepo:i().nullable(),gitHost:i().nullable(),defaultBranch:i().nullable(),linkedAt:i()}),x1=l({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:v(["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()}),lN=v(["github_repo","internal_repo","template","manual"]),cN=l({id:i(),teamId:i(),name:i(),slug:i().nullable().optional().default(null),sourceType:lN.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)}),dN=l({id:i(),name:i(),path:i(),workspacePath:i(),repoPath:i().nullable(),source:v(["folder","git"]),sourceFolders:p(i().min(1)).min(1).optional(),hiddenFromDefaultSidebar:I().optional(),sandboxTemplate:rN.nullable().optional().default(null),linkedOpenPondApp:sN.nullable().optional().default(null),linkedSandboxProject:x1.nullable().optional().default(null),preferredSandboxAgentId:i().nullable().optional().default(null),createdAt:i(),updatedAt:i()});l({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:I().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."})});l({linkedSandboxProject:x1.nullable().optional(),preferredSandboxAgentId:i().nullable().optional(),hiddenFromDefaultSidebar:I().optional()});const uN=["connected_app_search","connected_app_read","connected_app_write"],ih="https://openpond.ai",_v=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Cv={slack:[Xt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Xt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Xt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Xt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Xt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Xt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Xt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Xt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Xt("google.comments.read","Read comments","Read Google file comments.","read",!0),Xt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Xt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Xt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Xt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Xt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Xt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Xt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Xt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Xt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Xt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Xt("x.search.read","Search X","Search public X posts when granted.","read",!0),Xt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Xt("x.post.write","Post","Create approved X posts.","write",!0),Xt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Xt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Xt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},Rv={slack:[],microsoft_teams:[],google:[Bt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Bt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Bt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Bt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Bt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Bt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Bt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Bt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Bt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Bt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Bt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Bt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Bt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Bt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Bt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Bt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Bt("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"]}),Bt("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:[Bt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Bt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Bt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Bt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Bt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Bt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Bt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Bt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Bt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Bt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},mN={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
|
+
`)},pae=_v.map(e=>{const t=w1(e),n=mN[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${jN(n)}`,charCount:n.length}});function pN(e){const t=Pv(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=RN(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(c=>c.access===a&&c.leaseable).map(c=>c.id)),r=e.capabilityIds.filter(c=>!o.has(c));if(r.length>0)return{ok:!1,error:`Connected app capability ${r[0]} is not allowed for ${e.provider} ${e.operation}.`};const s=hN(e);return s.ok?{ok:!0,request:e}:s}function fN(e){const t=Pm(e);return t?Rv[t]:[]}function hN(e){const t=yN(e.args),n=fN(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=xN(e.args,e.operation);for(const s of a.input?.requiredKeys??[]){const c=r[s];if(c==null||typeof c=="string"&&!c.trim())return{ok:!1,error:`Connected app operation ${a.id} requires input.${s}.`}}return{ok:!0,request:e}}const gN=[{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"}],Rm=gN,vN=_v.map(e=>{const t=Rm.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:rc(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Cv[e],skills:_N(e),tools:CN(e),operations:Rv[e],leasePolicy:PN(e)}});function k1(e){const t=bN(e);return t?Rm.find(n=>n.id===t)??null:null}function Pv(e){const t=Pm(e);return t?vN.find(n=>n.id===t)??null:null}function fae(e){const t=k1(e.appId),n=wN(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 bN(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Rm.some(n=>n.id===t)?t:null:null}function Pm(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":_v.includes(t)?t:k1(t)?.providerFamily??null:null}function oh(e={}){const t=AN(e.connections??[]);return Rm.map(n=>{const a=Pv(n.providerFamily),o=n.statusSource==="integration_connection"?t.filter(c=>c.provider===n.providerFamily):[],r=o.some(c=>c.status==="active"),s=TN(n,r);return{...n,providerLabel:a.label,setupSurfaceLabel:IN(n.setupSurface),status:s,statusLabel:EN(n,s,o),connections:o,connected:r,capabilities:V0(n,a.capabilities),capabilityLabels:V0(n,a.capabilities).map(c=>c.label),leasePolicy:a.leasePolicy}})}function Xt(e,t,n,a,o){return{id:e,label:t,description:n,access:a,leaseable:o}}function Bt(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 yN(e){return SN(e.operation)}function SN(e){return typeof e=="string"&&e.trim()?e.trim():null}function xN(e,t){return t==="write"?kN(e.input)?e.input:{}:e}function kN(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function wN(e){const t=e?.trim();if(!t)return ih;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?ih:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return ih}}function rc(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function IN(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function _N(e){return[w1(e)]}function w1(e){return{name:`${e}-connected-app`,description:`Use ${rc(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function CN(e){if(e==="mcp")return[];const t=Cv[e],n=Rv[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 ${rc(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 ${rc(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 ${rc(e)} write through a server-owned connected app connector.`,capabilityIds:o,write:!0}),r}function RN(e){return e==="search"?"connected_app_search":e==="read"?"connected_app_read":"connected_app_write"}function PN(e){const t=Cv[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 V0(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 AN(e){return e.flatMap(t=>{const n=Pm(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 TN(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function EN(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 jN(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 MN=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),ON=v(["search","read","write"]),$N=v(uN);l({provider:MN,operation:ON,toolName:$N,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:te(i(),ie()).default({})}).strict().superRefine((e,t)=>{const n=pN(e);n.ok||t.addIssue({code:Yn.custom,message:n.error})});l({ok:I(),output:i().nullable().optional(),data:ie().optional()}).strict();const NN="local_path:";function I1(e){return`${NN}${e.trim()}`}l({appId:i(),source:v(["openpond","github","local_git","local_folder","unknown"]),workspacePath:i(),repoPath:i(),initialized:I(),remoteUrl:i().nullable(),expectedRemoteUrl:i().nullable(),currentBranch:i().nullable(),headCommit:i().nullable().optional().default(null),upstreamBranch:i().nullable().optional().default(null),ahead:d().int().nonnegative().optional().default(0),behind:d().int().nonnegative().optional().default(0),diverged:I().optional().default(!1),linkedSourceHeadCommit:i().nullable().optional().default(null),aheadOfLinkedSource:d().int().nonnegative().optional().default(0),behindLinkedSource:d().int().nonnegative().optional().default(0),divergedFromLinkedSource:I().optional().default(!1),linkedSourceComparisonError:i().nullable().optional().default(null),lastFetchAt:i().nullable().optional().default(null),defaultBranch:i().nullable(),branches:p(i()),dirty:I(),changedFilesCount:d(),untrackedFilesCount:d(),error:i().nullable(),updatedAt:i()});const DN=l({path:i(),status:i(),additions:d(),deletions:d(),patch:i(),content:i().nullable().optional().default(null)}),HN=l({appId:i(),repoPath:i(),initialized:I(),dirty:I(),filesChanged:d(),additions:d(),deletions:d(),repoFiles:p(i()).optional().default([]),files:p(DN),error:i().nullable(),updatedAt:i()});l({branch:i().trim().min(1).max(160)});l({path:i().trim().min(1),content:i()});const K0=l({line:d().int().nonnegative(),character:d().int().nonnegative()}),LN=l({start:K0,end:K0}),qN=l({path:i(),range:LN,severity:v(["error","warning","info","hint"]),message:i(),source:i().nullable().optional().default(null),code:i().nullable().optional().default(null)}),_1=l({id:i(),root:i(),status:v(["connected","unavailable","error"]),message:i().nullable().optional().default(null)});l({path:i().trim().min(1),content:i().optional(),waitForDiagnostics:I().optional().default(!0)});l({appId:i(),path:i(),diagnostics:p(qN),servers:p(_1),updatedAt:i()});const UN=l({operation:v(["hover","definition","references","documentSymbol"]),path:i().trim().min(1),content:i().optional(),line:d().int().nonnegative().optional(),character:d().int().nonnegative().optional()});l({appId:i(),operation:UN.shape.operation,path:i(),results:ie(),servers:p(_1),updatedAt:i()});const zN=l({pinned:I().optional(),archived:I().optional(),order:d().optional()}),BN=te(i(),zN),C1=v(["local","sandbox"]),FN=v(["pinned","saved_for_later"]),R1=l({id:i().min(1),workspaceKind:C1,workspaceId:i().min(1),workspaceName:i().min(1),path:i().min(1),status:FN,order:d().int().nonnegative().nullable().default(null),sourceSessionId:i().min(1).nullable().default(null),available:I().default(!0),createdAt:i().min(1),updatedAt:i().min(1)});l({items:p(R1)});l({workspaceKind:C1,workspaceId:i().trim().min(1),workspaceName:i().trim().min(1),path:i().trim().min(1),status:v(["pinned","saved_for_later","none"]),order:d().int().nonnegative().nullable().optional(),sourceSessionId:i().trim().min(1).nullable().optional()});v(["pin","save_for_later","remove","list"]);function VN(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 hae(e){return["sidebar-file",e.workspaceKind,encodeURIComponent(e.workspaceId),encodeURIComponent(VN(e.path))].join(":")}const KN=l({id:i(),name:i(),type:i(),status:i(),isActive:I().nullable(),price:i().nullable(),currency:i().nullable(),credits:i().nullable()}).passthrough(),WN=l({reachable:I(),authenticated:I().nullable(),apiBase:i(),latencyMs:d(),status:d().nullable(),service:i().nullable(),checkedAt:i(),error:i().nullable()}),GN=l({id:i().nullable(),email:i().nullable(),name:i().nullable(),handle:i().nullable(),image:i().nullable(),timezone:i().nullable(),isAdmin:I().nullable(),isVerified:I().nullable(),dailyAgentAppId:i().nullable(),dailyAgentDeploymentId:i().nullable(),credits:i().nullable()}),JN=l({handle:i(),baseUrl:i().nullable().optional()}),ZN=l({state:v(["signed_out","signed_in","loading","switching","auth_error"]),activeProfile:JN.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:GN.nullable(),products:p(KN),apiHealth:WN.nullable(),accounts:p(l({handle:i(),baseUrl:i().nullable(),apiBaseUrl:i().nullable().optional().default(null),chatApiBaseUrl:i().nullable().optional(),environment:i().nullable(),isActive:I(),authHealth:v(["signed_out","signed_in","auth_error","unknown"]),displayLabel:i().nullable(),email:i().nullable().optional().default(null),avatarUrl:i().nullable(),apiKeyHint:i().nullable().optional(),apiKeyAccess:l({ownerType:v(["user","team","organization","service"]).nullable(),teamId:i().nullable(),scopes:p(i())}).nullable().optional().default(null)})),error:i().nullable()}),W0=l({asOf:i().nullable(),refreshing:I(),lastRefreshError:i().nullable(),source:v(["fresh","cache","empty"])}),YN=l({available:I(),binaryPath:i().nullable(),version:i().nullable(),authHealth:v(["unknown","signed_in","signed_out","auth_error"]),account:l({type:i(),email:i().nullable(),planType:i().nullable(),label:i().nullable()}).nullable().default(null),appServer:l({status:v(["idle","starting","ready","error"]),lastError:i().nullable()})}),Av="gpt-5.6-sol",Ks="openpond-chat",Pr="openpond",xc=Ks,Tv="default",Ev="high",Am="ask",cl=$r,jv=v(["default","auto-review","full-access"]),Jc=v(["ask","full-access","disabled"]),Tm=v(["off","low","medium","high","xhigh","max"]),Zc=v(["sandbox_app","local_project","sandbox","sandbox_template"]);v(["openpond"]);const QN=v(["provider_usage","provider_tokenizer","model_family","heuristic"]),XN=l({provider:cl,model:i().min(1),usedTokens:d().int().nonnegative(),maxContextTokens:d().int().positive(),usableContextTokens:d().int().positive(),percentFull:d().min(0).max(100),source:QN,updatedAtEventId:i().nullable()}),cg=l({pinned:I().default(!1),projects:I().default(!1),cloudProjects:I().default(!1),chats:I().default(!1),savedForLater:I().default(!0)}),eD=v(["auto","off"]),tD=v(["typescript","python","rust"]),P1=v(["auto","disabled","custom"]),Zi=l({mode:P1.default("auto"),customCommand:i().trim().max(4096).default("")}),Bu=l({languageServers:eD.default("auto"),diagnosticsWhileEditing:I().default(!0),checkOnSave:I().default(!0),languages:l({typescript:Zi.optional().default(()=>Zi.parse({})),python:Zi.optional().default(()=>Zi.parse({})),rust:Zi.optional().default(()=>Zi.parse({}))}).optional().default(()=>({typescript:Zi.parse({}),python:Zi.parse({}),rust:Zi.parse({})}))}),nD=l({language:tD,label:i(),mode:P1,status:v(["found","missing","disabled","error"]),command:i().nullable(),message:i().nullable()});l({settings:Bu,languages:p(nD),updatedAt:i()});const aD=l({id:i(),root:i(),status:v(["starting","connected","unavailable","error"]),message:i().nullable().optional().default(null),openedDocuments:d().int().nonnegative(),pendingRequests:d().int().nonnegative(),lastUsedAt:i(),stderrTail:i()});l({clients:p(aD),maxClients:d().int().positive(),idleTimeoutMs:d().int().positive(),updatedAt:i()});const dg=l({autoEnabled:I().default(!0),triggerPercent:d().int().min(50).max(95).default(85),summaryModel:v(["same_model"]).default("same_model")}),ug=l({defaultModelRef:bn.nullable().default(null),creationMode:v(["defaults","customize"]).default("customize"),autoApproveEvidence:I().default(!1)}),G0=l({defaultChatProvider:cl.default(Pr),defaultChatModel:i().min(1).default(xc),defaultChatModelRef:bn.nullable().optional(),subagents:yc.optional().default(()=>yc.parse({})),codexPermissionMode:jv.default(Tv),codexReasoningEffort:Tm.default(Ev),openPondCommandAccessMode:Jc.default(Am),defaultBranchPrefix:i().trim().max(48).default("feat/"),defaultNewProjectDirectory:i().trim().max(4096).default(""),defaultTeamId:i().trim().max(191).nullable().default(null),advancedWorkspaceControls:I().default(!1),steerActiveResponses:I().default(!0),contextCompaction:dg.optional().default(()=>dg.parse({})),training:ug.optional().default(()=>ug.parse({})),sidebarWidth:d().int().min(244).max(560).default(332),diffPanelWidth:d().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:cg.optional().default(()=>cg.parse({})),editor:Bu.optional().default(()=>Bu.parse({}))}),iD="default",A1=[{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.`}],Mv=i().trim().min(1).max(120),oD=l({id:Mv,name:i(),source:v(["built_in","custom"]).default("custom"),description:i(),content:i()}),J0=l({activeTemplateId:Mv.default(iD),customized:I().default(!1),soul:i(),soulPath:i().nullable(),updatedAt:i().nullable(),templates:p(oD).default(()=>[...A1])}),rD=l({id:i(),host:i(),port:d(),startedAt:i(),storePath:i(),version:i(),runtimeVersion:i()}),Ov=v(["chat","work","development"]);v(["chat","models","console","development"]);const sD="work",Ge=i().trim().min(1).nullable(),Ka=te(i(),ie()).default({}),lD=v(["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"]),T1=v(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),cD=v(["create","improve","import","promote"]),dD=v(["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"]),Gd=v(["always_require_plan_approval","approval_already_granted"]);v(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const uD=rt("kind",[l({kind:b("local"),sourceAuthority:b("local_profile"),activeProfile:i().trim().min(1).nullable(),repoPath:Ge,sourcePath:Ge,localHead:Ge,confirmationPolicy:Gd.default("always_require_plan_approval")}),l({kind:b("hosted"),sourceAuthority:b("hosted_profile"),teamId:Ge,projectId:Ge,activeProfile:i().trim().min(1).nullable(),sourceRef:Ge,baseSha:Ge,confirmationPolicy:Gd.default("always_require_plan_approval")}),l({kind:b("promote_local_to_hosted"),sourceAuthority:b("promote_local_to_hosted"),teamId:Ge,projectId:Ge,activeProfile:i().trim().min(1).nullable(),repoPath:Ge,sourcePath:Ge,localHead:Ge,hostedHead:Ge,sourceRef:Ge,confirmationPolicy:Gd.default("always_require_plan_approval")}),l({kind:b("managed_artifact"),sourceAuthority:b("managed_artifact"),activeProfile:i().trim().min(1).nullable(),confirmationPolicy:Gd.default("always_require_plan_approval")})]),mD=l({id:Ge,kind:v(["user","system","automation"]).default("user"),label:Ge}),pD=l({profileId:i().trim().min(1),conversationId:Ge,originTurnId:Ge,projectId:Ge,targetProject:l({id:Ge,name:Ge,workspacePath:Ge,sourceRef:Ge,baseSha:Ge}).nullable()}),Ql=l({messageIds:p(i().trim().min(1)).default([]),conversationExcerpts:p(l({messageId:Ge,role:i().trim().min(1).nullable(),excerpt:i().trim().min(1),reason:i().trim().min(1).nullable()})).default([]),attachments:p(l({id:Ge,name:i().trim().min(1),mediaType:Ge,ref:Ge})).default([]),apps:p(l({id:i().trim().min(1),name:i().trim().min(1),connectionId:Ge,required:I().default(!1)})).default([]),tools:p(l({name:i().trim().min(1),inputSummary:Ge,outputSummary:Ge,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([])}),ps={id:Ge,displayName:Ge},$v=rt("kind",[l({kind:b("unselected"),...ps}),l({kind:b("agent"),...ps,defaultActionKey:Ge}),l({kind:b("skill"),...ps,skillName:Ge}),l({kind:b("extension"),...ps,slot:Ge}),l({kind:b("model"),...ps,trainingPlanId:Ge,trainingJobId:Ge,artifactId:Ge}),l({kind:b("configuration"),...ps,key:Ge})]),mg=v(["agent","skill","extension","model","configuration"]),fD=l({schemaVersion:b("openpond.createImprove.evidenceSnapshot.v1"),id:i().trim().min(1),contentHash:i().trim().min(8),consent:l({status:v(["granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Ge,reviewedAt:i().trim().min(1)}),sources:p(l({kind:v(["signal","conversation","direct_correction","manual_intent","artifact"]),id:i().trim().min(1),sourceHash:i().trim().min(8),excerptRef:Ge})).min(1),reviewerIntent:i().trim().min(1),createdAt:i().trim().min(1),metadata:Ka}),E1=l({schemaVersion:b("openpond.createImprove.tasksetRef.v1"),id:i().trim().min(1),revision:d().int().positive(),contentHash:i().trim().min(8),evidenceSnapshotIds:p(i().trim().min(1)).min(1),policyBoundary:l({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:l({kind:mg,rationale:p(i().trim().min(1)).min(1),confidence:d().min(0).max(1)}),authoringSplitRefs:p(i().trim().min(1)).default([]),privateSplitRefs:p(i().trim().min(1)).default([]),approvedBy:Ge,approvedAt:i().trim().min(1),metadata:Ka}),hD=l({kind:v(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:i().trim().min(1),status:v(["declared","required","blocked","satisfied"]).default("declared"),detail:Ge,metadata:Ka}),gD=l({mode:v(["chat","direct_action","chat_and_direct_actions"]),label:i().trim().min(1),detail:i().trim().min(1),defaultActionKey:Ge,directActionHint:Ge,artifactPolicy:i().trim().min(1)}),vD=l({schemaVersion:b("openpond.createImprove.plan.v1"),id:i().trim().min(1),runId:i().trim().min(1),status:v(["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:l({key:Ge,label:Ge,required:I().default(!0)}),sourcePlan:p(l({path:i().trim().min(1),operation:v(["create","update","delete","inspect"]),reason:i().trim().min(1)})).default([]),requirements:p(hD).default([]),checks:p(l({name:i().trim().min(1),command:i().trim().min(1),required:I().default(!0)})).default([]),approvalId:Ge,approvedAt:Ge,editedFromPlanId:Ge,metadata:Ka,createdAt:i().trim().min(1),updatedAt:i().trim().min(1)}),bD=l({id:i().trim().min(1),label:i().trim().min(1),value:i().trim().min(1),description:Ge,metadata:Ka}),yD=l({value:i().trim().min(1),label:Ge,detail:Ge,answeredAt:i().trim().min(1),metadata:Ka}),SD=l({id:i().trim().min(1),kind:v(["single_choice","free_text"]).default("single_choice"),title:i().trim().min(1),prompt:i().trim().min(1),required:I().default(!0),status:v(["pending","answered","skipped"]).default("pending"),options:p(bD).default([]),answer:yD.nullable().default(null),metadata:Ka}),xD=l({schemaVersion:b("openpond.createImprove.workflowCapture.v1"),id:i().trim().min(1),runId:i().trim().min(1),command:T1,objective:i().trim().min(1),conversationExcerpts:Ql.shape.conversationExcerpts,attachments:Ql.shape.attachments,apps:Ql.shape.apps,tools:Ql.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:Ka,createdAt:i().trim().min(1)}),j1=l({provider:b("github"),number:d().int().positive(),url:i().url(),state:v(["open","merged","closed"]),baseBranch:i().trim().min(1),headBranch:i().trim().min(1),mergeCommit:Ge,openedAt:i().trim().min(1),updatedAt:i().trim().min(1)}),kD=l({baseBranch:i().trim().min(1),baseCommit:i().trim().min(1),branch:i().trim().min(1),headCommit:Ge,remoteName:i().trim().min(1).default("origin"),remoteUrl:Ge,worktreePath:Ge,changedPaths:p(i().trim().min(1)).default([]),diffStat:Ge,pullRequest:j1.nullable().default(null)}),wD=l({id:i().trim().min(1),target:$v,status:v(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:kD.nullable().default(null),parentCandidateId:Ge.default(null),tasksetRef:E1.nullable().default(null),authoringModelRef:Ge.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:Ka}),ID=l({id:i().trim().min(1),candidateId:Ge,target:$v,evaluatorKind:v(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:v(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Ge.default(null),sourceBranch:Ge.default(null),tasksetId:Ge.default(null),tasksetHash:Ge.default(null),taskAttemptRefs:p(i().trim().min(1)).default([]),status:v(["pending","passed","failed","blocked"]),publishGate:v(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:l({total:d().int().nonnegative(),passed:d().int().nonnegative(),failed:d().int().nonnegative()}).nullable().default(null),evalRefs:p(i().trim().min(1)).default([]),artifactRefs:p(i().trim().min(1)).default([]),summary:Ge,createdAt:i().trim().min(1),metadata:Ka}),_D=l({mode:v(["foreground","background"]).default("background"),pauseAllowed:I().default(!0),cancellationAllowed:I().default(!0)}),CD=l({mode:v(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:d().int().min(1).max(20).default(1),currentAttempt:d().int().min(0).max(20).default(0)}),RD=l({kind:v(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:i().trim().min(1),status:Ge,metadata:Ka}),PD=l({status:v(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ge,profileTag:Ge,releaseReceiptRef:Ge,pullRequest:j1.nullable().default(null),updatedAt:Ge}),Yc=l({schemaVersion:b("openpond.createImprove.run.v1"),id:i().trim().min(1),revision:d().int().nonnegative(),operation:cD,surface:lD,command:T1,objective:i().trim().min(1),state:dD,adapter:uD,actor:mD,scope:pD,context:Ql,target:$v,evidenceSnapshots:p(fD).default([]),tasksetRef:E1.nullable().default(null),targetSelection:l({status:v(["open","recommended","confirmed"]),preselectedKind:mg.nullable(),confirmedKind:mg.nullable()}).nullable().default(null),plan:vD.nullable(),workflowCapture:xD.nullable(),executionPolicy:_D.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:CD.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:p(i().trim().min(1)).default([]),questionIds:p(i().trim().min(1)).default([]),questions:p(SD).default([]),candidates:p(wD).default([]),evaluationReceipts:p(ID).default([]),checkRefs:p(i().trim().min(1)).default([]),sourceRefs:p(i().trim().min(1)).default([]),externalExecutionRefs:p(RD).default([]),localProfileCommit:Ge,hostedSourceCommit:Ge,hostedSourceRef:Ge,releaseOutcome:PD.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Ge,appliedActionIds:p(i().trim().min(1)).max(200).default([]),metadata:Ka,createdAt:i().trim().min(1),updatedAt:i().trim().min(1)}),ki={runId:i().trim().min(1),expectedRevision:d().int().nonnegative(),actionId:i().trim().min(1)};rt("type",[l({...ki,type:b("answer_question"),questionId:i().trim().min(1),value:i().trim().min(1)}),l({...ki,type:b("approve_plan")}),l({...ki,type:b("revise_plan"),revision:i().trim().min(1)}),l({...ki,type:b("cancel"),reason:Ge.optional().default(null)}),l({...ki,type:b("pause")}),l({...ki,type:b("resume")}),l({...ki,type:b("open_pull_request"),candidateId:i().trim().min(1)}),l({...ki,type:b("apply_candidate"),candidateId:i().trim().min(1)}),l({...ki,type:b("reject_candidate"),candidateId:i().trim().min(1),reason:Ge.optional().default(null)}),l({...ki,type:b("reconcile_pull_request"),candidateId:i().trim().min(1)})]);l({schemaVersion:b("openpond.createImprove.runList.v1"),runs:p(Yc),generatedAt:i().trim().min(1)});function gae(e){const t=gD.safeParse(e?.actionShape);return t.success?t.data:null}const qi=l({source:v(["local","github","openpond_git"]),repositoryId:i().trim().min(1),profileId:i().trim().min(1)}),AD=l({ref:qi,revision:i().nullable(),sourceHash:i()}),dl=te(i(),ie()).default({}),Da=d().int().nonnegative(),Em=i().trim().min(1).max(1e5),M1=l({kind:v(["personal","team"]),id:T}).strict(),TD=l({name:T,release:V.nullable(),revision:Da}).strict();l({schemaVersion:b("openpond.harnessWorkspace.v1"),id:T,ownerScope:M1,name:i().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:i().trim().min(1).max(500),revision:Da,dirty:I(),currentChannel:TD,createdAt:pe,updatedAt:pe,metadata:dl}).strict();const Ws=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),O1=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),$1=l({id:T,route:Ws,operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),content:i().max(1e6).nullable(),contentHash:H.nullable(),effects:p(O1).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=ct(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),N1=l({workspaceId:T,revision:Da,sourceRevision:i().trim().min(1).max(500),channelRevision:Da}).strict(),io=l({id:T,revision:Da,contentHash:H}).strict(),ED=l({schemaVersion:b("openpond.harnessTurnSnapshot.v1"),workspaceId:T,workspaceRevision:Da,sourceRevision:i().trim().min(1).max(500),channelName:T,channelRevision:Da,harnessRelease:V,toolCatalogHash:H.nullable().optional(),overlay:io.nullable().optional().default(null)}).strict(),jD=l({schemaVersion:b("openpond.harnessRunOverlay.v1"),id:T,runId:T,baseHarnessRelease:V,workspace:N1,revision:Da,status:v(["active","frozen","abandoned"]),edits:p($1).max(1e3),createdAt:pe,updatedAt:pe,metadata:dl}).strict();jD.extend({contentHash:H}).strict();const D1=l({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:T,contentHash:H.nullable()}).strict(),H1=l({id:T,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Em,required:I()}).strict(),MD=l({schemaVersion:b("openpond.harnessImprovementProposal.v1"),id:T,overlay:io,baseHarnessRelease:V,expectedWorkspace:N1,requestedScope:v(["personal","team","global"]),route:Ws,risk:v(["low","review","restricted"]),effects:p(O1).min(1).max(20),evidence:p(D1).min(1).max(1e3),edits:p($1).min(1).max(1e3),validationPlan:p(H1).min(1).max(100),expectedOutcome:Em,createdAt:pe,metadata:dl}).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"]})});MD.extend({contentHash:H}).strict();const OD=l({schemaVersion:b("openpond.harnessTargetedValidationReceipt.v1"),id:T,proposal:V,validationId:T,kind:H1.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Em,evidenceRefs:p(D1).max(1e3),createdAt:pe,metadata:dl}).strict();OD.extend({contentHash:H}).strict();const $D=v(["advanced","retained","conflict","rolled_back"]),ND=l({schemaVersion:b("openpond.harnessAdvanceReceipt.v1"),id:T,workspaceId:T,ownerScope:M1,proposal:V.nullable(),expectedWorkspaceRevision:Da,observedWorkspaceRevision:Da,previousChannelRevision:Da,nextChannelRevision:Da,previousRelease:V.nullable(),nextRelease:V.nullable(),validationReceipts:p(V).max(100),decision:$D,reason:Em,rollbackOf:V.nullable(),createdAt:pe,metadata:dl}).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"]})});ND.extend({contentHash:H}).strict();const DD=l({schemaVersion:b("openpond.harnessOverlayMergeReceipt.v1"),id:T,workspaceId:T,baseHarnessRelease:V,leftOverlay:io,rightOverlay:io,decision:v(["merged","conflict"]),mergedOverlay:io.nullable(),conflictTargets:p(i().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:b(!0),createdAt:pe,metadata:dl}).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"]})});DD.extend({contentHash:H}).strict();const oo=i().trim().min(1).max(1e5),HD=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),LD=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),L1=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),Nv=l({kind:v(["personal","team"]),id:T}).strict(),q1=l({policy:V,state:v(["authorized","revoked","deleted","expired"]),checkedAt:pe}).strict(),kc=l({evidence:V,kind:L1,sourceRef:T,sourcePolicy:q1,occurrenceKey:H,occurredAt:pe}).strict(),qD=l({evidence:V,sourcePolicy:q1.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),Z0=l({cursor:H,throughCreatedAt:pe}).strict(),UD=l({fingerprint:H,recurrenceFamily:i().trim().min(1).max(1e3),statement:oo,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:d().int().positive().max(1e6),unresolvedOccurrences:d().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),U1=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),zD=l({layer:U1,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:oo,evidenceRefs:p(V).max(1e3)}).strict(),BD=l({schemaVersion:b("openpond.harnessEvaluationReviewReceipt.v1"),id:T,ownerScope:Nv,workspaceRef:T,harnessRelease:V,previousWatermark:Z0.nullable(),nextWatermark:Z0,selectedEvidence:p(kc).max(1e4),excludedEvidence:p(qD).max(1e4),claim:UD.nullable(),classification:HD,triage:p(zD).max(16),reason:oo,nextAuthority:LD,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:V.nullable(),evaluation:V.nullable(),trainingQualification:V.nullable(),policyVersion:T,createdAt:pe,metadata:jn}).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"})});BD.extend({contentHash:H}).strict();l({id:T,evidence:V,kind:L1,sourceRef:T,occurredAt:pe,payload:te(i(),ie())}).strict();const FD=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("no_action"),reason:oo,ignoredEvidence:p(l({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),VD=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(l({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:i().trim().min(1).max(1e3),statement:oo,triageLayer:U1,expectedOutcome:oo,counterevidence:i().trim().max(1e4),confidence:d().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:oo}).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"]})}),KD=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("resolve_candidate"),candidateId:T,candidateFingerprint:H,selectedEvidenceIds:p(T).min(1).max(1e3),ignoredEvidence:p(l({id:T,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:d().min(0).max(1),reason:oo}).strict();rt("decision",[FD,VD,KD]);l({schemaVersion:b("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(T).min(1).max(50),reason:oo}).strict();const Qc=l({name:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(2e3),inputSchema:te(i(),ie()),inputSchemaHash:H,sideEffect:v(["read","write"]),timeoutMs:d().int().positive().max(36e5)}).strict(),Dv=l({id:T,required:I(),scopes:p(i().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),WD=l({portable:I(),blockers:p(i().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(T).max(1e4),hostPrivateAssetRefs:p(T).max(1e4)}).strict(),GD=l({schemaVersion:b("openpond.agentSnapshot.v2"),id:T,sourceRelease:V.nullable(),instructions:p(gn).max(1e4),skills:p(gn).max(1e4),agents:p(gn).max(1e4),toolDeclarations:p(Qc).max(200),capabilityRequirements:p(Dv).max(200),dependencyLock:gn,portability:WD,metadata:jn}).strict(),JD=GD.extend({contentHash:H}).strict(),z1=l({create:b(!0),reset:b(!0),step:b(!0),collect:b(!0),destroy:b(!0),resetScope:v(["task","attempt"])}).strict(),B1=l({visibleEvidence:p(T).max(1e3),privilegedEvidence:p(T).max(1e3),privateVerifierIsolation:I()}).strict(),ZD=l({schemaVersion:b("openpond.harnessRelease.v2"),id:T,agentSnapshot:V,program:gn,tools:p(Qc).max(200),lifecycle:z1,graderInterface:B1,files:p(gn).max(1e5),metadata:jn}).strict(),YD=ZD.extend({contentHash:H}).strict(),QD=l({id:T,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:T.nullable(),arguments:te(i(),ie()),content:i().max(1e6).nullable()}).strict(),XD=l({actionId:T,turn:d().int().nonnegative(),terminal:I(),output:te(i(),ie()),artifactRefs:p(Ia).max(1e5)}).strict(),eH=l({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:H,metadata:jn}).strict();l({schemaVersion:b("openpond.harnessTrace.v1"),manifest:V,taskId:T,seed:i().trim().min(1).max(500),events:p(eH).max(1e6),actions:p(QD).max(1e5),observations:p(XD).max(1e5),terminal:I(),failureClass:Kc.nullable(),output:te(i(),ie()),contentHash:H}).strict();const jm=i().trim().min(1).max(1e5),Xc=te(i(),ie()).default({}),tH=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),F1=l({kind:tH,eventSequence:d().int().nonnegative(),occurredAt:pe}).strict(),V1=l({id:T,sequence:d().int().nonnegative().nullable(),contentHash:H}).strict(),nH=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),aH=v(["open","recovered","terminal"]),iH=l({name:i().trim().min(1).max(500),invocationKey:H}).strict(),oH=l({schemaVersion:b("openpond.improvementObservation.v1"),id:T,runRef:T,turnId:T,harnessRelease:V,overlay:io.nullable(),eventRefs:p(V1).min(1).max(100),kind:nH,state:aH,tool:iH.nullable(),deterministicClass:i().trim().min(1).max(500).nullable(),summary:jm,createdAt:pe,metadata:Xc}).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"]})});oH.extend({contentHash:H}).strict();const rH=l({schemaVersion:b("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:d().finite().nonnegative(),cooldownMs:d().int().nonnegative(),maxPendingPlans:d().int().min(1).max(100),maxEvidenceEvents:d().int().min(1).max(1e3),maxProposalEdits:d().int().min(1).max(1e3),maxProposalBytes:d().int().min(1).max(1e7)}).strict(),sH=v(["no_action","route_deterministically","queue_refiner"]),lH=l({schemaVersion:b("openpond.refinementTriggerDecision.v1"),id:T,runRef:T,turnId:T,harnessRelease:V,overlay:io.nullable(),observations:p(V).max(100),decision:sH,deterministicRoute:Ws.nullable(),suggestedRoutes:p(Ws).max(8),reason:jm,deduplicationKey:H,policy:rH,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:F1,cooldownUntil:pe.nullable(),createdAt:pe,metadata:Xc}).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"]})});lH.extend({contentHash:H}).strict();const cH=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),dH=l({schemaVersion:b("openpond.improvementRouteDecision.v1"),id:T,trigger:V,route:Ws,authority:cH,automatic:I(),reason:jm,createdAt:pe,metadata:Xc}).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"]})});dH.extend({contentHash:H}).strict();const uH=l({schemaVersion:b("openpond.harnessRefinerOutcome.v1"),id:T,trigger:V,decision:v(["no_action","proposed"]),proposal:V.nullable(),reason:jm,evidenceRefs:p(V).max(100),estimatedCostUsd:d().finite().nonnegative(),createdAt:pe,metadata:Xc}).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"]})});uH.extend({contentHash:H}).strict();const mH=v(["applied","retained","declined","conflict","rolled_back"]),pH=l({schemaVersion:b("openpond.improvementApplyReceipt.v1"),id:T,proposal:V,beforeOverlay:io,afterOverlay:io.nullable(),decision:mH,boundary:F1,validationRefs:p(V).max(100),outcomeEvidenceRefs:p(V1).max(1e3),rollbackOf:V.nullable(),createdAt:pe,metadata:Xc}).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"]})});pH.extend({contentHash:H}).strict();const fH=v(["memory","prompt","skill","agent"]),hH=v(["runtime","product","taskset","training"]),gH=l({id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:i().trim().min(1).max(1e4)}).strict(),K1=l({schemaVersion:b("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(gH).max(100),allowedProposalRoutes:p(fH).max(4),allowedExternalRoutes:p(hH).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"]})}),Y0=l({schemaVersion:b("openpond.refinerRelease.v1"),id:i().trim().min(1).max(240),coreVersion:i().trim().min(1).max(120),coreHash:H,profile:K1,profileHash:H,composedPromptHash:H,createdAt:pe,contentHash:H}).strict(),vH=l({schemaVersion:b("openpond.refinerBinding.v1"),channel:b("active"),revision:d().int().nonnegative(),release:V,updatedAt:pe}).strict(),bH=l({schemaVersion:b("openpond.refinerTransitionReceipt.v1"),id:i().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:I(),previousRelease:V.nullable(),nextRelease:V,actor:i().trim().min(1).max(240),reason:i().trim().min(1).max(1e4),authoringSkillHash:H.nullable(),validation:l({valid:I(),messages:p(i().max(2e3)).max(100)}).strict(),createdAt:pe,contentHash:H}).strict(),yH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("no_action"),reason:i().trim().min(1).max(1e4)}).strip(),SH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("route"),route:v(["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(),xH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["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"]})}),kH=rt("decision",[yH,SH,xH]),wH=kH,Hv=l({kind:v(["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"]})}),IH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("no_action"),reason:i().trim().min(1).max(1e4)}).strict(),_H=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),evidenceBasis:Hv,expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strict(),CH=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),evidenceBasis:Hv,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"]})}),W1=rt("decision",[IH,_H,CH]);gt([wH,W1]);const Lv=l({memory:I(),prompt:I(),skill:I(),agent:I()}).strict(),G1=v(["memory","instruction","skill","agent"]),Q0=l({path:i().trim().min(1).max(2e3),kind:G1,content:i().max(6e4),loaded:I()}).strict(),X0=l({path:i().trim().min(1).max(2e3),kind:G1,loaded:I()}).strict(),RH=l({capabilities:Lv,trigger:te(i(),ie()),observations:p(te(i(),ie())).max(20),admissibleEvidenceIds:p(i().trim().min(1).max(2e3)).max(1e4),reviewPacket:l({currentTurn:l({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:d().int().nonnegative()}).strict(),priorConversation:p(l({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(te(i(),ie())).max(60),artifacts:p(te(i(),ie())).max(30),artifactDiagnostics:p(te(i(),ie())).max(20),executionProfile:l({modelRequestCount:d().int().nonnegative(),failedModelRequestCount:d().int().nonnegative(),promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),toolFailureCount:d().int().nonnegative(),retryCount:d().int().nonnegative(),recoveryCount:d().int().nonnegative()}).strict(),priorIncidents:p(te(i(),ie())).max(3),truncation:l({timelineEventCount:d().int().nonnegative(),includedTimelineEventCount:d().int().nonnegative(),timelineTruncated:I()}).strict()}).strict(),runtimeActivation:l({admittedRelease:V,currentRelease:V,rebasedOntoCurrent:I(),admittedSourceFiles:p(Q0).max(100),admittedSourceCatalog:p(X0).max(1e3)}).strict(),sourceFiles:p(Q0).max(100),sourceCatalog:p(X0).max(1e3),additionalEvidence:ie().nullable().optional()}).strict(),PH=l({id:i().trim().min(1).max(240),revision:d().int().nonnegative(),contentHash:H}).strict();l({schemaVersion:b("openpond.hostedHarnessRefinerRequest.v2"),requestId:i().trim().min(1).max(240),idempotencyKey:i().trim().min(1).max(240),evidenceHash:H,harness:l({admittedRelease:V,currentRelease:V,overlay:PH,workspace:l({id:i().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:H,channelRevision:d().int().nonnegative()}).strict(),capabilities:Lv}).strict(),evidence:RH}).strict();const AH=l({promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict();l({schemaVersion:b("openpond.hostedHarnessRefinerResponse.v2"),requestId:i().trim().min(1).max(240),evidenceHash:H,admittedRelease:V,currentRelease:V,decision:W1,serviceRevision:i().trim().min(1).max(240),usage:AH}).strict();const TH=i().trim().min(1).max(2e3),qv=i().trim().min(1).max(1e5),EH=v(["create","update","delete"]),jH=v(["memory","prompt","skill","agent"]),MH=v(["runtime","product","taskset","training"]),OH=v(["no_action","routed","applied","retained","failed"]),$H=v(["not_applicable","pending","passed","rejected","failed"]),NH=v(["not_applicable","pending","passed","failed"]),DH=l({schemaVersion:b("openpond.harnessRefinerActivityReceipt.v1"),id:T,runRef:T,turnId:T,result:OH,decision:v(["no_action","route","propose"]).nullable(),route:Ws.nullable(),operation:EH.nullable(),target:i().trim().min(1).max(2e3).nullable(),summary:TH,evidenceBasis:Hv.nullable(),critiqueStatus:$H,validationStatus:NH,trigger:V,outcome:V.nullable(),proposal:V.nullable(),applyReceipt:V.nullable(),inputHarness:V,outputHarness:V.nullable(),createdAt:pe}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?eS(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"||!MH.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"}),eS(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!jH.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"]})});DH.extend({contentHash:H}).strict();const HH=v(["unresolved","confirmed","resolved","rejected","expired"]),LH=l({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:qv,evidenceRefs:p(V).max(1e3),resolvedAt:pe}).strict(),qH=l({schemaVersion:b("openpond.harnessRefinementCandidate.v1"),id:T,ownerScope:Nv,workspaceRef:T,fingerprint:H,recurrenceFamily:i().trim().min(1).max(1e3),statement:qv,status:HH,occurrences:p(kc).max(1e3),counterevidence:p(kc).max(1e3),sourceReviews:p(V).min(1).max(100),relatedHarnessReleases:p(V).max(100),firstSeenAt:pe,lastSeenAt:pe,lastReviewedAt:pe,expiresAt:pe,resolution:LH.nullable(),createdAt:pe,updatedAt:pe}).strict().superRefine((e,t)=>{br(t,e.occurrences,"occurrences"),br(t,e.counterevidence,"counterevidence"),br(t,e.sourceReviews,"sourceReviews"),br(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"]}),VH(t,e)});qH.extend({contentHash:H}).strict();const UH=v(["created","merged","rejected","expired","reopened","resolved"]),zH=l({schemaVersion:b("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:T,candidateId:T,decision:UH,beforeCandidate:V.nullable(),afterCandidate:V,review:V,addedEvidence:p(kc).max(1e3),removedEvidence:p(V).max(1e3),reason:qv,createdAt:pe}).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"]}),br(t,e.addedEvidence,"addedEvidence"),br(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>pg(a)));e.addedEvidence.some(a=>n.has(pg(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});zH.extend({contentHash:H}).strict();const BH=l({schemaVersion:b("openpond.harnessCrossRunRefinementRequest.v1"),id:T,ownerScope:Nv,workspaceRef:T,candidate:V,candidateFingerprint:H,review:V,admittedHarness:V,evidence:p(kc).min(1).max(1e3),capabilities:Lv,deduplicationKey:H,createdAt:pe}).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"]}),br(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=FH(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});BH.extend({contentHash:H}).strict();function FH(e){return ct({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function eS(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 br(e,t,n){const a=t.map(o=>pg(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function pg(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 VH(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 KH=25*1024*1024,WH=l({path:gn.shape.path,base64:i().max(Math.ceil(KH/3)*4)}).strict(),J1=l({schemaVersion:b("openpond.harnessSourcePackage.v1"),agentSnapshot:JD,harnessRelease:YD,files:p(WH).max(1e4)}).strict();J1.extend({contentHash:H}).strict();J1.extend({schemaVersion:b("openpond.harnessPolicySourcePackage.v1"),contentHash:H}).strict();l({schemaVersion:b("openpond.harnessSourceSelection.v1"),mode:v(["taskset_owned","selected_release"]),harnessRelease:V,sourcePackageHash:H.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."})});l({path:i().min(1).max(2e3),offset:d().int().nonnegative().default(0),length:d().int().positive().max(65536).default(16384)}).strict();const Z1=i().regex(/^[a-z][a-z0-9_-]{0,119}$/),Y1=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"),GH=l({id:Z1,label:i().trim().min(1).max(240),description:i().max(4e3),inputSchema:te(i(),ie()),invocation:rt("kind",[l({kind:b("instructions"),instructions:i().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),l({kind:b("agent_action"),actionId:i().trim().min(1).max(240)}).strict()]),skillPaths:p(Y1).max(100)}).strict();l({schemaVersion:b("openpond.profileWorkflows.v1"),workflows:p(GH).max(1e3)}).strict();const JH=l({id:i().trim().min(1).max(240),agentId:i().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:i().trim().min(1).max(240),inputSchema:te(i(),ie())}).strict();l({schemaVersion:b("openpond.profileWorkflowActions.v1"),actions:p(JH).max(200)}).strict();const ZH=l({schemaVersion:b("openpond.profileWorkflowBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:V,catalogHash:H,workflowId:Z1}).strict(),YH=l({schemaVersion:b("openpond.profileComponentBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:V,target:rt("kind",[l({kind:b("profile")}).strict(),l({kind:b("skill"),skillPath:Y1}).strict(),l({kind:b("agent_action"),actionId:i().trim().min(1).max(240)}).strict()])}).strict(),Uv=Symbol.for("yaml.alias"),QH=Symbol.for("yaml.document"),Cr=Symbol.for("yaml.map"),Q1=Symbol.for("yaml.pair"),zv=Symbol.for("yaml.scalar"),ed=Symbol.for("yaml.seq"),Ui=Symbol.for("yaml.node.type"),ul=e=>!!e&&typeof e=="object"&&e[Ui]===Uv,Mm=e=>!!e&&typeof e=="object"&&e[Ui]===QH,X1=e=>!!e&&typeof e=="object"&&e[Ui]===Cr,Un=e=>!!e&&typeof e=="object"&&e[Ui]===Q1,En=e=>!!e&&typeof e=="object"&&e[Ui]===zv,Bv=e=>!!e&&typeof e=="object"&&e[Ui]===ed;function ka(e){if(e&&typeof e=="object")switch(e[Ui]){case Cr:case ed:return!0}return!1}function Kn(e){if(e&&typeof e=="object")switch(e[Ui]){case Uv:case Cr:case zv:case ed:return!0}return!1}const eI=e=>(En(e)||ka(e))&&!!e.anchor,fr=Symbol("break visit"),XH=Symbol("skip children"),sc=Symbol("remove node");function Om(e,t){const n=eL(t);Mm(e)?Is(null,e.contents,n,Object.freeze([e]))===sc&&(e.contents=null):Is(null,e,n,Object.freeze([]))}Om.BREAK=fr;Om.SKIP=XH;Om.REMOVE=sc;function Is(e,t,n,a){const o=tL(e,t,n,a);if(Kn(o)||Un(o))return nL(e,a,o),Is(e,o,n,a);if(typeof o!="symbol"){if(ka(t)){a=Object.freeze(a.concat(t));for(let r=0;r<t.items.length;++r){const s=Is(r,t.items[r],n,a);if(typeof s=="number")r=s-1;else{if(s===fr)return fr;s===sc&&(t.items.splice(r,1),r-=1)}}}else if(Un(t)){a=Object.freeze(a.concat(t));const r=Is("key",t.key,n,a);if(r===fr)return fr;r===sc&&(t.key=null);const s=Is("value",t.value,n,a);if(s===fr)return fr;s===sc&&(t.value=null)}}return o}function eL(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 tL(e,t,n,a){if(typeof n=="function")return n(e,t,a);if(X1(t))return n.Map?.(e,t,a);if(Bv(t))return n.Seq?.(e,t,a);if(Un(t))return n.Pair?.(e,t,a);if(En(t))return n.Scalar?.(e,t,a);if(ul(t))return n.Alias?.(e,t,a)}function nL(e,t,n){const a=t[t.length-1];if(ka(a))a.items[e]=n;else if(Un(a))e==="key"?a.key=n:a.value=n;else if(Mm(a))a.contents=n;else{const o=ul(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}function tI(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 Xl(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],c=Xl(e,a,String(o),s);c===void 0?delete a[o]:c!==s&&(a[o]=c)}else if(a instanceof Map)for(const o of Array.from(a.keys())){const r=a.get(o),s=Xl(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=Xl(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=Xl(e,a,o,r);s===void 0?delete a[o]:s!==r&&(a[o]=s)}return e.call(t,n,a)}function ci(e,t,n){if(Array.isArray(e))return e.map((a,o)=>ci(a,String(o),n));if(e&&typeof e.toJSON=="function"){if(!n||!eI(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 Fv{constructor(t){Object.defineProperty(this,Ui,{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(!Mm(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},c=ci(this,"",s);if(typeof o=="function")for(const{count:m,res:u}of s.anchors.values())o(u,m);return typeof r=="function"?Xl(r,{"":c},"",c):c}}class aL extends Fv{constructor(t){super(Uv),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=[],Om(t,{Node:(r,s)=>{(ul(s)||eI(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 c=a.get(s);if(c||(ci(s,null,n),c=a.get(s)),c?.res===void 0){const m="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(m)}if(r>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=xu(o,s,a)),c.count*c.aliasCount>r)){const m="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(m)}return c.res}toString(t,n,a){const o=`*${this.source}`;if(t){if(tI(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 xu(e,t,n){if(ul(t)){const a=t.resolve(e),o=n&&a&&n.get(a);return o?o.count*o.aliasCount:0}else if(ka(t)){let a=0;for(const o of t.items){const r=xu(e,o,n);r>a&&(a=r)}return a}else if(Un(t)){const a=xu(e,t.key,n),o=xu(e,t.value,n);return Math.max(a,o)}return 1}const nI=e=>!e||typeof e!="function"&&typeof e!="object";class mn extends Fv{constructor(t){super(zv),this.value=t}toJSON(t,n){return n?.keep?this.value:ci(this.value,t,n)}toString(){return String(this.value)}}mn.BLOCK_FOLDED="BLOCK_FOLDED";mn.BLOCK_LITERAL="BLOCK_LITERAL";mn.PLAIN="PLAIN";mn.QUOTE_DOUBLE="QUOTE_DOUBLE";mn.QUOTE_SINGLE="QUOTE_SINGLE";function iL(e,t,n){return n.find(a=>a.identify?.(e)&&!a.format)}function Fu(e,t,n){if(Mm(e)&&(e=e.contents),Kn(e))return e;if(Un(e)){const g=n.schema[Cr].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:c}=n;let m;if(a&&e&&typeof e=="object"){if(m=c.get(e),m)return m.anchor??(m.anchor=o(e)),new aL(m.anchor);m={anchor:null,node:null},c.set(e,m)}let u=iL(e,t,s.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const g=new mn(e);return m&&(m.node=g),g}u=e instanceof Map?s[Cr]:Symbol.iterator in Object(e)?s[ed]:s[Cr]}r&&(r(u),delete n.onTagObj);const f=u?.createNode?u.createNode(n.schema,e,n):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(n.schema,e,n):new mn(e);return u.default||(f.tag=u.tag),m&&(m.node=f),f}function tS(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 Fu(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 oL=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done;class aI extends Fv{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=>Kn(a)||Un(a)?a.clone(t):a),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(oL(t))this.add(n);else{const[a,...o]=t,r=this.get(a,!0);if(ka(r))r.addIn(o,n);else if(r===void 0&&this.schema)this.set(a,tS(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(ka(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&&En(r)?r.value:r:ka(r)?r.getIn(o,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!Un(n))return!1;const a=n.value;return a==null||t&&En(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 ka(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(ka(r))r.setIn(o,n);else if(r===void 0&&this.schema)this.set(a,tS(this.schema,o,n));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${o}`)}}}const rL=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function wc(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}const _s=(e,t,n)=>e.endsWith(`
|
|
125
|
+
`)?wc(n,t):n.includes(`
|
|
126
|
+
`)?`
|
|
127
|
+
`+wc(n,t):(e.endsWith(" ")?"":" ")+n,iI="flow",fg="block",ku="quoted";function $m(e,t,n="flow",{indentAtStart:a,lineWidth:o=80,minContentWidth:r=20,onFold:s,onOverflow:c}={}){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 u=[],f={};let g=o-t.length;typeof a=="number"&&(a>o-Math.max(2,r)?u.push(0):g=o-a);let S,k,C=!1,P=-1,j=-1,R=-1;n===fg&&(P=nS(e,P,t.length),P!==-1&&(g=P+m));for(let O;O=e[P+=1];){if(n===ku&&O==="\\"){switch(j=P,e[P+1]){case"x":P+=3;break;case"u":P+=5;break;case"U":P+=9;break;default:P+=1}R=P}if(O===`
|
|
128
|
+
`)n===fg&&(P=nS(e,P,t.length)),g=P+t.length+m,S=void 0;else{if(O===" "&&k&&k!==" "&&k!==`
|
|
129
|
+
`&&k!==" "){const M=e[P+1];M&&M!==" "&&M!==`
|
|
130
|
+
`&&M!==" "&&(S=P)}if(P>=g)if(S)u.push(S),g=S+m,S=void 0;else if(n===ku){for(;k===" "||k===" ";)k=O,O=e[P+=1],C=!0;const M=P>R+1?P-2:j-1;if(f[M])return e;u.push(M),f[M]=!0,g=M+m,S=void 0}else C=!0}k=O}if(C&&c&&c(),u.length===0)return e;s&&s();let $=e.slice(0,u[0]);for(let O=0;O<u.length;++O){const M=u[O],w=u[O+1]||e.length;M===0?$=`
|
|
131
|
+
${t}${e.slice(0,w)}`:(n===ku&&f[M]&&($+=`${e[M]}\\`),$+=`
|
|
132
|
+
${t}${e.slice(M+1,w)}`)}return $}function nS(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 Nm=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Dm=e=>/^(%|---|\.\.\.)/m.test(e);function sL(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 lc(e,t){const n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;const{implicitKey:a}=t,o=t.options.doubleQuotedMinMultiLineLength,r=t.indent||(Dm(e)?" ":"");let s="",c=0;for(let m=0,u=n[m];u;u=n[++m])if(u===" "&&n[m+1]==="\\"&&n[m+2]==="n"&&(s+=n.slice(c,m)+"\\ ",m+=1,c=m,u="\\"),u==="\\")switch(n[m+1]){case"u":{s+=n.slice(c,m);const f=n.substr(m+2,4);switch(f){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:f.substr(0,2)==="00"?s+="\\x"+f.substr(2):s+=n.substr(m,6)}m+=5,c=m+1}break;case"n":if(a||n[m+2]==='"'||n.length<o)m+=1;else{for(s+=n.slice(c,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,c=m+1}break;default:m+=1}return s=c?s+n.slice(c):n,a?s:$m(s,r,ku,Nm(t,!1))}function hg(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
138
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return lc(e,t);const n=t.indent||(Dm(e)?" ":""),a="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
139
|
+
${n}`)+"'";return t.implicitKey?a:$m(a,n,iI,Nm(t,!1))}function Cs(e,t){const{singleQuote:n}=t.options;let a;if(n===!1)a=lc;else{const o=e.includes('"'),r=e.includes("'");o&&!r?a=hg:r&&!o?a=lc:a=n?hg:lc}return a(e,t)}let gg;try{gg=new RegExp(`(^|(?<!
|
|
140
|
+
))
|
|
141
|
+
+(?!
|
|
142
|
+
|$)`,"g")}catch{gg=/\n+(?!\n|$)/g}function wu({comment:e,type:t,value:n},a,o,r){const{blockQuote:s,commentString:c,lineWidth:m}=a.options;if(!s||/\n[\t ]+$/.test(n))return Cs(n,a);const u=a.indent||(a.forceBlockIndent||Dm(n)?" ":""),f=s==="literal"?!0:s==="folded"||t===mn.BLOCK_FOLDED?!1:t===mn.BLOCK_LITERAL?!0:!sL(n,m,u.length);if(!n)return f?`|
|
|
143
|
+
`:`>
|
|
144
|
+
`;let g,S;for(S=n.length;S>0;--S){const w=n[S-1];if(w!==`
|
|
145
|
+
`&&w!==" "&&w!==" ")break}let k=n.substring(S);const C=k.indexOf(`
|
|
146
|
+
`);C===-1?g="-":n===k||C!==k.length-1?(g="+",r&&r()):g="",k&&(n=n.slice(0,-k.length),k[k.length-1]===`
|
|
147
|
+
`&&(k=k.slice(0,-1)),k=k.replace(gg,`$&${u}`));let P=!1,j,R=-1;for(j=0;j<n.length;++j){const w=n[j];if(w===" ")P=!0;else if(w===`
|
|
148
|
+
`)R=j;else break}let $=n.substring(0,R<j?R+1:j);$&&(n=n.substring($.length),$=$.replace(/\n+/g,`$&${u}`));let M=(P?u?"2":"1":"")+g;if(e&&(M+=" "+c(e.replace(/ ?[\r\n]+/g," ")),o&&o()),!f){const w=n.replace(/\n+/g,`
|
|
149
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let A=!1;const E=Nm(a,!0);s!=="folded"&&t!==mn.BLOCK_FOLDED&&(E.onOverflow=()=>{A=!0});const D=$m(`${$}${w}${k}`,u,fg,E);if(!A)return`>${M}
|
|
150
|
+
${u}${D}`}return n=n.replace(/\n+/g,`$&${u}`),`|${M}
|
|
151
|
+
${u}${$}${n}${k}`}function lL(e,t,n,a){const{type:o,value:r}=e,{actualString:s,implicitKey:c,indent:m,indentStep:u,inFlow:f}=t;if(c&&r.includes(`
|
|
152
|
+
`)||f&&/[[\]{},]/.test(r))return Cs(r,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return c||f||!r.includes(`
|
|
153
|
+
`)?Cs(r,t):wu(e,t,n,a);if(!c&&!f&&o!==mn.PLAIN&&r.includes(`
|
|
154
|
+
`))return wu(e,t,n,a);if(Dm(r)){if(m==="")return t.forceBlockIndent=!0,wu(e,t,n,a);if(c&&m===u)return Cs(r,t)}const g=r.replace(/\n+/g,`$&
|
|
155
|
+
${m}`);if(s){const S=P=>P.default&&P.tag!=="tag:yaml.org,2002:str"&&P.test?.test(g),{compat:k,tags:C}=t.doc.schema;if(C.some(S)||k?.some(S))return Cs(r,t)}return c?g:$m(g,m,iI,Nm(t,!1))}function cL(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:c}=e;c!==mn.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(c=mn.QUOTE_DOUBLE);const m=f=>{switch(f){case mn.BLOCK_FOLDED:case mn.BLOCK_LITERAL:return o||r?Cs(s.value,t):wu(s,t,n,a);case mn.QUOTE_DOUBLE:return lc(s.value,t);case mn.QUOTE_SINGLE:return hg(s.value,t);case mn.PLAIN:return lL(s,t,n,a);default:return null}};let u=m(c);if(u===null){const{defaultKeyType:f,defaultStringType:g}=t.options,S=o&&f||g;if(u=m(S),u===null)throw new Error(`Unsupported default string type ${S}`)}return u}function dL(e,t){const n=Object.assign({blockQuote:!0,commentString:rL,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 uL(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(En(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 mL(e,t,{anchors:n,doc:a}){if(!a.directives)return"";const o=[],r=(En(e)||ka(e))&&e.anchor;r&&tI(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 Vu(e,t,n,a){if(Un(e))return e.toString(t,n,a);if(ul(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=Kn(e)?e:t.doc.createNode(e,{onTagObj:m=>o=m});o??(o=uL(t.doc.schema.tags,r));const s=mL(r,o,t);s.length>0&&(t.indentAtStart=(t.indentAtStart??0)+s.length+1);const c=typeof o.stringify=="function"?o.stringify(r,t,n,a):En(r)?cL(r,t,n,a):r.toString(t,n,a);return s?En(r)||c[0]==="{"||c[0]==="["?`${s} ${c}`:`${s}
|
|
156
|
+
${t.indent}${c}`:c}function pL({key:e,value:t},n,a,o){const{allNullValues:r,doc:s,indent:c,indentStep:m,options:{commentString:u,indentSeq:f,simpleKeys:g}}=n;let S=Kn(e)&&e.comment||null;if(g){if(S)throw new Error("With simple keys, key nodes cannot have comments");if(ka(e)||!Kn(e)&&typeof e=="object"){const E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let k=!g&&(!e||S&&t==null&&!n.inFlow||ka(e)||(En(e)?e.type===mn.BLOCK_FOLDED||e.type===mn.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!k&&(g||!r),indent:c+m});let C=!1,P=!1,j=Vu(e,n,()=>C=!0,()=>P=!0);if(!k&&!n.inFlow&&j.length>1024){if(g)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");k=!0}if(n.inFlow){if(r||t==null)return C&&a&&a(),j===""?"?":k?`? ${j}`:j}else if(r&&!g||t==null&&k)return j=`? ${j}`,S&&!C?j+=_s(j,n.indent,u(S)):P&&o&&o(),j;C&&(S=null),k?(S&&(j+=_s(j,n.indent,u(S))),j=`? ${j}
|
|
157
|
+
${c}:`):(j=`${j}:`,S&&(j+=_s(j,n.indent,u(S))));let R,$,O;Kn(t)?(R=!!t.spaceBefore,$=t.commentBefore,O=t.comment):(R=!1,$=null,O=null,t&&typeof t=="object"&&(t=s.createNode(t))),n.implicitKey=!1,!k&&!S&&En(t)&&(n.indentAtStart=j.length+1),P=!1,!f&&m.length>=2&&!n.inFlow&&!k&&Bv(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let M=!1;const w=Vu(t,n,()=>M=!0,()=>P=!0);let A=" ";if(S||R||$){if(A=R?`
|
|
158
|
+
`:"",$){const E=u($);A+=`
|
|
159
|
+
${wc(E,n.indent)}`}w===""&&!n.inFlow?A===`
|
|
160
|
+
`&&O&&(A=`
|
|
161
|
+
|
|
162
|
+
`):A+=`
|
|
163
|
+
${n.indent}`}else if(!k&&ka(t)){const E=w[0],D=w.indexOf(`
|
|
164
|
+
`),U=D!==-1,L=n.inFlow??t.flow??t.items.length===0;if(U||!L){let J=!1;if(U&&(E==="&"||E==="!")){let X=w.indexOf(" ");E==="&"&&X!==-1&&X<D&&w[X+1]==="!"&&(X=w.indexOf(" ",X+1)),(X===-1||D<X)&&(J=!0)}J||(A=`
|
|
165
|
+
${n.indent}`)}}else(w===""||w[0]===`
|
|
166
|
+
`)&&(A="");return j+=A+w,n.inFlow?M&&a&&a():O&&!M?j+=_s(j,n.indent,u(O)):P&&o&&o(),j}function fL(e,t){(e==="debug"||e==="warn")&&console.warn(t)}const Jd="<<",rh={identify:e=>e===Jd||typeof e=="symbol"&&e.description===Jd,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new mn(Symbol(Jd)),{addToJSMap:oI}),stringify:()=>Jd},hL=(e,t)=>(rh.identify(t)||En(t)&&(!t.type||t.type===mn.PLAIN)&&rh.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===rh.tag&&n.default);function oI(e,t,n){const a=rI(e,n);if(Bv(a))for(const o of a.items)sh(e,t,o);else if(Array.isArray(a))for(const o of a)sh(e,t,o);else sh(e,t,a)}function sh(e,t,n){const a=rI(e,n);if(!X1(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 rI(e,t){return e&&ul(t)?t.resolve(e.doc,e):t}function sI(e,t,{key:n,value:a}){if(Kn(n)&&n.addToJSMap)n.addToJSMap(e,t,a);else if(hL(e,n))oI(e,t,a);else{const o=ci(n,"",e);if(t instanceof Map)t.set(o,ci(a,o,e));else if(t instanceof Set)t.add(o);else{const r=gL(n,o,e),s=ci(a,r,e);r in t?Object.defineProperty(t,r,{value:s,writable:!0,enumerable:!0,configurable:!0}):t[r]=s}}return t}function gL(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Kn(e)&&n?.doc){const a=dL(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)+'..."'),fL(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 Vv(e,t,n){const a=Fu(e,void 0,n),o=Fu(t,void 0,n);return new ro(a,o)}class ro{constructor(t,n=null){Object.defineProperty(this,Ui,{value:Q1}),this.key=t,this.value=n}clone(t){let{key:n,value:a}=this;return Kn(n)&&(n=n.clone(t)),Kn(a)&&(a=a.clone(t)),new ro(n,a)}toJSON(t,n){const a=n?.mapAsMap?new Map:{};return sI(n,a,this)}toString(t,n,a){return t?.doc?pL(this,t,n,a):JSON.stringify(this)}}function lI(e,t,n){return(t.inFlow??e.flow?bL:vL)(e,t,n)}function vL({comment:e,items:t},n,{blockItemPrefix:a,flowChars:o,itemIndent:r,onChompKeep:s,onComment:c}){const{indent:m,options:{commentString:u}}=n,f=Object.assign({},n,{indent:r,type:null});let g=!1;const S=[];for(let C=0;C<t.length;++C){const P=t[C];let j=null;if(Kn(P))!g&&P.spaceBefore&&S.push(""),Ku(n,S,P.commentBefore,g),P.comment&&(j=P.comment);else if(Un(P)){const $=Kn(P.key)?P.key:null;$&&(!g&&$.spaceBefore&&S.push(""),Ku(n,S,$.commentBefore,g))}g=!1;let R=Vu(P,f,()=>j=null,()=>g=!0);j&&(R+=_s(R,r,u(j))),g&&j&&(g=!1),S.push(a+R)}let k;if(S.length===0)k=o.start+o.end;else{k=S[0];for(let C=1;C<S.length;++C){const P=S[C];k+=P?`
|
|
167
|
+
${m}${P}`:`
|
|
168
|
+
`}}return e?(k+=`
|
|
169
|
+
`+wc(u(e),m),c&&c()):g&&s&&s(),k}function bL({items:e},t,{flowChars:n,itemIndent:a}){const{indent:o,indentStep:r,flowCollectionPadding:s,options:{commentString:c}}=t;a+=r;const m=Object.assign({},t,{indent:a,inFlow:!0,type:null});let u=!1,f=0;const g=[];for(let C=0;C<e.length;++C){const P=e[C];let j=null;if(Kn(P))P.spaceBefore&&g.push(""),Ku(t,g,P.commentBefore,!1),P.comment&&(j=P.comment);else if(Un(P)){const $=Kn(P.key)?P.key:null;$&&($.spaceBefore&&g.push(""),Ku(t,g,$.commentBefore,!1),$.comment&&(u=!0));const O=Kn(P.value)?P.value:null;O?(O.comment&&(j=O.comment),O.commentBefore&&(u=!0)):P.value==null&&$?.comment&&(j=$.comment)}j&&(u=!0);let R=Vu(P,m,()=>j=null);u||(u=g.length>f||R.includes(`
|
|
170
|
+
`)),C<e.length-1?R+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(u||(u=g.reduce(($,O)=>$+O.length+2,2)+(R.length+2)>t.options.lineWidth)),u&&(R+=",")),j&&(R+=_s(R,a,c(j))),g.push(R),f=g.length}const{start:S,end:k}=n;if(g.length===0)return S+k;if(!u){const C=g.reduce((P,j)=>P+j.length+2,2);u=t.options.lineWidth>0&&C>t.options.lineWidth}if(u){let C=S;for(const P of g)C+=P?`
|
|
171
|
+
${r}${o}${P}`:`
|
|
172
|
+
`;return`${C}
|
|
173
|
+
${o}${k}`}else return`${S}${s}${g.join(" ")}${s}${k}`}function Ku({indent:e,options:{commentString:t}},n,a,o){if(a&&o&&(a=a.replace(/^\n+/,"")),a){const r=wc(t(a),e);n.push(r.trimStart())}}function yr(e,t){const n=En(t)?t.value:t;for(const a of e)if(Un(a)&&(a.key===t||a.key===n||En(a.key)&&a.key.value===n))return a}class bs extends aI{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Cr,t),this.items=[]}static from(t,n,a){const{keepUndefined:o,replacer:r}=a,s=new this(t),c=(m,u)=>{if(typeof r=="function")u=r.call(n,m,u);else if(Array.isArray(r)&&!r.includes(m))return;(u!==void 0||o)&&s.items.push(Vv(m,u,a))};if(n instanceof Map)for(const[m,u]of n)c(m,u);else if(n&&typeof n=="object")for(const m of Object.keys(n))c(m,n[m]);return typeof t.sortMapEntries=="function"&&s.items.sort(t.sortMapEntries),s}add(t,n){let a;Un(t)?a=t:!t||typeof t!="object"||!("key"in t)?a=new ro(t,t?.value):a=new ro(t.key,t.value);const o=yr(this.items,a.key),r=this.schema?.sortMapEntries;if(o){if(!n)throw new Error(`Key ${a.key} already set`);En(o.value)&&nI(a.value)?o.value.value=a.value:o.value=a.value}else if(r){const s=this.items.findIndex(c=>r(a,c)<0);s===-1?this.items.push(a):this.items.splice(s,0,a)}else this.items.push(a)}delete(t){const n=yr(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const o=yr(this.items,t)?.value;return(!n&&En(o)?o.value:o)??void 0}has(t){return!!yr(this.items,t)}set(t,n){this.add(new ro(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)sI(n,o,r);return o}toString(t,n,a){if(!t)return JSON.stringify(this);for(const o of this.items)if(!Un(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})),lI(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:a,onComment:n})}}class cI extends aI{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ed,t),this.items=[]}add(t){this.items.push(t)}delete(t){const n=Zd(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const a=Zd(t);if(typeof a!="number")return;const o=this.items[a];return!n&&En(o)?o.value:o}has(t){const n=Zd(t);return typeof n=="number"&&n<this.items.length}set(t,n){const a=Zd(t);if(typeof a!="number")throw new Error(`Expected a valid index, not ${t}.`);const o=this.items[a];En(o)&&nI(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(ci(r,String(o++),n));return a}toString(t,n,a){return t?lI(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 c of n){if(typeof o=="function"){const m=n instanceof Set?c:String(s++);c=o.call(n,m,c)}r.items.push(Fu(c,void 0,a))}}return r}}function Zd(e){let t=En(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}function yL(e,t,n){const{replacer:a}=n,o=new cI(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 c,m;if(Array.isArray(s))if(s.length===2)c=s[0],m=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){const u=Object.keys(s);if(u.length===1)c=u[0],m=s[c];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else c=s;o.items.push(Vv(c,m,n))}return o}class Kv extends cI{constructor(){super(),this.add=bs.prototype.add.bind(this),this.delete=bs.prototype.delete.bind(this),this.get=bs.prototype.get.bind(this),this.has=bs.prototype.has.bind(this),this.set=bs.prototype.set.bind(this),this.tag=Kv.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(Un(o)?(r=ci(o.key,"",n),s=ci(o.value,r,n)):r=ci(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=yL(t,n,a),r=new this;return r.items=o.items,r}}Kv.tag="tag:yaml.org,2002:omap";class Wv extends bs{constructor(t){super(t),this.tag=Wv.tag}add(t){let n;Un(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new ro(t.key,null):n=new ro(t,null),yr(this.items,n.key)||this.items.push(n)}get(t,n){const a=yr(this.items,t);return!n&&Un(a)?En(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=yr(this.items,t);a&&!n?this.items.splice(this.items.indexOf(a),1):!a&&n&&this.items.push(new ro(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(Vv(s,null,a));return r}}Wv.tag="tag:yaml.org,2002:set";new Set("0123456789ABCDEFabcdef");new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");new Set(",[]{}");new Set(` ,[]{}
|
|
174
|
+
\r `);const Wu=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 SL={type:"object",properties:{},additionalProperties:!1};l({name:i().trim().min(1).max(240).optional(),description:i().max(4e3).optional(),skillPaths:p(Wu).max(100).optional(),assetPaths:p(Wu).max(100).optional()}).strict();l({actionId:i().trim().min(1).max(240),name:i().trim().min(1).max(240),description:i().max(4e3).default(""),inputSchema:te(i(),ie()).default(SL),skillPaths:p(Wu).max(100).default([]),assetPaths:p(Wu).max(100).default([])}).strict();const dI=v(["openpond.lab"]),Ic=l({id:i(),experience:Ov.default(sD),provider:cl,modelRef:bn.nullable().optional(),openPondCommandAccessMode:Jc.default(Am),systemKind:dI.nullable().optional(),hiddenFromDefaultSidebar:I().optional(),parentSessionId:i().nullable().optional(),parentTurnId:i().nullable().optional(),subagentRunId:i().nullable().optional(),subagentRoleId:ll.nullable().optional(),subagentDelegationMode:Cm.nullable().optional(),title:i(),appId:i().nullable(),appName:i().nullable(),workspaceKind:Zc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:qi.nullable().optional(),profileWorkflowBinding:ZH.nullable().optional(),profileComponentBinding:YH.nullable().optional(),metadata:te(i(),ie()).optional(),cwd:i().nullable(),codexThreadId:i().nullable(),nativeAgent:l({provider:v(["claude-code","grok-build","opencode"]),instanceId:i().min(1),sessionId:i().min(1),cwd:i().min(1)}).nullable().optional(),createdAt:i(),updatedAt:i(),status:v(["idle","active","failed","closed"]),runtimeSeconds:d().int().nonnegative().optional(),runtimeRunningSince:i().nullable().optional(),pinned:I(),savedForLater:I().optional(),archived:I(),order:d()});l({id:i(),sessionId:i(),providerTurnId:i().nullable(),modelRef:bn.nullable().optional(),prompt:i(),startedAt:i(),completedAt:i().nullable(),status:v(["in_progress","completed","failed","interrupted"]),error:i().nullable(),metadata:te(i(),ie()).optional().default({}),createImproveRun:Yc.nullable().optional().default(null),profileSnapshot:AD.nullable().optional(),harnessSnapshot:ED.nullable().optional()});const xL=l({id:i(),sessionId:i(),turnId:i().nullable(),providerRequestId:gt([i(),d()]),kind:v(["command","file_change","permissions","user_input","create_plan","subagent_patch_apply","legacy_exec","legacy_patch"]),title:i(),detail:i(),status:v(["pending","accepted","accepted_for_session","declined","cancelled"]),createdAt:i()}),kL=l({key:v(["files","diffs","checks","deploys","sources","schedules","tool_runs","logs","app_config"]),label:i(),status:v(["placeholder","available","error"]),summary:i()}),uI=l({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:gt([i().trim().max(191),te(i(),ie())]).optional().nullable(),outputSchema:gt([i().trim().max(191),te(i(),ie())]).optional().nullable(),approvalPolicy:te(i(),ie()).optional().nullable(),artifactPolicy:te(i(),ie()).optional().nullable(),setupRequirements:p(te(i(),ie())).optional(),mcp:te(i(),ie()).optional().nullable(),schedulePolicy:te(i(),ie()).optional().nullable(),trace:te(i(),ie()).optional().nullable(),implementation:te(i(),ie()).optional().nullable(),invokesModel:I().optional()}),wL=l({command:v(["inspect","build","validate","eval","traces","run"]),status:v(["passed","failed"]),checkedAt:i(),exitCode:d().nullable().optional(),sourceHead:i().nullable().optional()}),IL=l({id:i(),name:i(),path:i(),enabled:I()}),_L=l({name:i(),description:i(),path:i(),scope:b("profile"),enabled:I(),sourcePath:i(),charCount:d(),sourceHash:i(),validationStatus:v(["valid","warning","error"]),validationMessages:p(i()),resourceFiles:p(i()).optional().default([])}),CL=l({id:i(),name:i(),path:i(),agentId:i().nullable(),sourcePath:i()}),mI=l({path:i(),originalPath:i().nullable().optional(),indexStatus:i().nullable(),worktreeStatus:i().nullable(),status:i(),category:v(["added","modified","deleted","renamed","untracked","changed"])}),RL=l({isRepo:I(),branch:i().nullable(),head:i().nullable(),shortHead:i().nullable(),dirty:I(),upstream:i().nullable(),ahead:d().nullable(),behind:d().nullable(),remoteUrl:i().nullable(),files:p(mI),fileCount:d().int().nonnegative().optional(),error:i().nullable()}),PL=l({actionCount:d(),generatedAt:i().nullable(),manifestPath:i().nullable(),registryPath:i().nullable(),stale:I(),error:i().nullable()}),AL=l({skillCount:d(),generatedAt:i().nullable(),stale:I(),error:i().nullable()}),aS=l({ref:i(),source:v(["action_catalog","source_upload_metadata"]),actionId:i().nullable(),kind:i().nullable(),label:i(),status:i(),required:I(),blocking:I()}),TL=l({status:v(["ready","setup_required","blocked"]),requirementCount:d(),blockingCount:d(),optionalMissingCount:d(),readyCount:d(),requirements:p(aS),blockingRequirements:p(aS)}),EL=l({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(mI),fileCount:d().int().nonnegative().optional()}),jL=l({status:i(),agentId:i().nullable().optional(),deployPlanStatus:i().nullable().optional(),canRun:I().nullable().optional(),canDeploy:I().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()}),ML=l({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:d().nullable().optional(),totalBytes:d().nullable().optional(),generatedManifestPath:i().nullable().optional(),synthesizedOpenPondYaml:I().nullable().optional(),uploadMetadataPath:i().nullable().optional(),setupCommands:p(i()).optional(),validationCommands:p(i()).optional(),materializedAt:i().nullable().optional(),error:i().nullable().optional()}),OL=l({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()}),$L=l({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()}),NL=l({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:ML.nullable().optional().default(null),hostedSourceCheck:jL.nullable().optional().default(null),hostedPublish:OL.nullable().optional().default(null),hostedRun:$L.nullable().optional().default(null)}),DL=l({state:v(["none","ready","dirty","pending_commit","error"]),message:i(),agentCount:d(),actionCount:d(),defaultAction:i().nullable(),checkFresh:I(),checkStaleReason:i().nullable(),localHead:i().nullable(),hostedHead:i().nullable()}),pI=l({mode:v(["none","local"]),repoPath:i().nullable(),activeProfile:i().nullable(),sourcePath:i().nullable(),manifestPath:i().nullable(),agents:p(IL),skills:p(_L).optional().default([]),evals:p(CL).optional().default([]),git:RL.nullable(),catalog:PL,skillCatalog:AL.optional().default({skillCount:0,generatedAt:null,stale:!0,error:null}),actionCatalog:p(uI),sourceSetupRequirements:p(te(i(),ie())),setupGate:TL,diff:EL,hosted:NL.nullable(),summary:DL,lastCheck:wL.nullable(),error:i().nullable()}),HL=l({ref:qi,name:i(),repoPath:i(),sourcePath:i().nullable(),state:pI}),LL=l({lastUsed:qi.nullable(),profiles:p(HL)});function qL(){return{lastUsed:null,profiles:[]}}function UL(){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 zL=l({name:i(),description:i(),path:i(),sourcePath:i(),enabled:I(),charCount:d().int().nonnegative(),sourceHash:i(),validationStatus:v(["valid","error"]),validationMessages:p(i()),resourceFiles:p(i()),updatedAt:i().nullable()}),BL=v(["codex","profile","extension"]);l({skillName:i(),scope:BL,path:i(),byteSize:d().int().nonnegative(),isBinary:I(),content:i().nullable()});const FL=[{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"]}],VL=l({name:i(),description:i(),relativePath:i(),sourcePath:i(),charCount:d().int().nonnegative(),sourceHash:i(),resourceFiles:p(i()),validationStatus:v(["valid","error"]),validationMessages:p(i())}),fI=l({id:i(),source:b("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(VL),validationStatus:v(["valid","error"]),validationMessages:p(i())});fI.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:sl()});const KL=l({rootPath:i(),registryPath:i(),extensions:p(fI),error:i().nullable()});l({source:i().trim().min(1),ref:i().trim().min(1).optional()});const WL=l({latestSequence:d().int().nonnegative(),oldestSequence:d().int().nonnegative(),totalEvents:d().int().nonnegative(),limit:d().int().nonnegative(),hasMoreBefore:I()});l({server:rD,account:ZN,codex:YN,configuration:l({rawRevision:i(),effectiveRevision:i(),sources:p(l({layer:i(),path:i(),revision:i()})),provenance:te(i(),l({layer:i(),path:i(),revision:i()}))}).optional(),preferences:G0.optional().default(()=>G0.parse({})),providers:g0.optional().default(()=>g0.parse({})),personalization:J0.optional().default(()=>J0.parse({soul:A1[0].content,soulPath:null,updatedAt:null})),apps:p(oN),localProjects:p(dN).optional().default([]),cloudProjects:p(cN).optional().default([]),profile:pI.optional().default(UL),profileLibrary:LL.optional().default(qL),codexPersonalSkills:p(zL).optional().default([]),extensionCatalog:KL.optional().default({rootPath:"",registryPath:"",extensions:[],error:null}),codexHistorySessions:p(Ic).optional().default([]),sidebarAppPreferences:BN,sidebarFileBookmarks:p(R1).optional().default([]),appsError:i().nullable(),appsMeta:W0,accountMeta:W0,sessions:p(Ic),events:p(v0),eventWindow:WL.optional(),approvals:p(xL),placeholders:p(kL),diagnostics:p(v0)});const Gv=v(["openpond_hosted","local_byok","codex_app_server","unknown"]),hI=v(["provider_usage","codex_context_usage","missing"]),GL=v(["provider_usage_body","provider_response_headers"]),JL=v(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),ZL=v(["foreground","tool_loop","compaction","subagent","refiner","other"]),gI=v(["user_facing","background","system"]),vI=v(["started","completed","failed","interrupted"]),Jv=v(["composer_selection","prompt_parse","server_parser","model_tool","api"]),bI=v(["chat","settings","goal","create_improve","compaction","system"]),yI=v(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),YL=l({surface:bI,workflowKind:yI,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:Jv.nullable().default(null),appId:i().trim().min(1).nullable().default(null),workspaceKind:Zc.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:d().int().nonnegative().nullable().default(null)}),QL=l({surface:bI.optional(),workflowKind:yI.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:Jv.nullable().optional()}).strict(),Nr=i().trim().min(1).max(160),XL=l({id:i().trim().min(1),requestId:i().trim().min(1),requestOrdinal:d().int().nonnegative(),sessionId:i().trim().min(1).nullable(),turnId:i().trim().min(1).nullable(),provider:Nr,model:i().trim().min(1),route:Gv,source:hI,requestKind:JL,visibility:gI,status:vI,startedAt:i().trim().min(1),completedAt:i().trim().min(1).nullable(),durationMs:d().int().nonnegative().nullable(),firstTokenMs:d().int().nonnegative().nullable(),promptTokens:d().int().nonnegative().nullable(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheTelemetrySource:GL.nullable(),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),errorType:i().trim().min(1).max(160).nullable(),errorMessage:i().trim().min(1).max(2e3).nullable(),attribution:YL}),SI=l({from:i().trim().min(1),to:i().trim().min(1),bucket:v(["day","all_time"])}),Zv=gt([b("all"),gI]),Yv=v(["all","started","completed","failed","interrupted","missing"]),eq=l({range:v(["7d","30d","90d","all"]).default("30d"),visibility:Zv.default("all"),status:Yv.default("all"),provider:Nr.optional(),model:i().trim().min(1).optional()});eq.extend({sessionId:i().trim().min(1).optional(),turnId:i().trim().min(1).optional(),limit:d().int().positive().max(500).default(100)});l({sessionId:i().trim().min(1)});const Dr=l({requests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failures:d().int().nonnegative(),failureRate:d().nonnegative(),firstSeenAt:i().trim().min(1),lastSeenAt:i().trim().min(1)}),tq=Dr.extend({provider:Nr,model:i().trim().min(1),route:Gv}),nq=Dr.extend({sessionId:i().trim().min(1),title:i().trim().min(1).nullable(),workspaceKind:Zc.nullable(),workspaceId:i().trim().min(1).nullable()}),aq=Dr.extend({commandName:i().trim().min(1),commandSource:Jv.nullable()}),iq=Dr.extend({route:Gv}),oq=Dr.extend({status:vI}),rq=Dr.extend({source:hI}),sq=Dr.extend({cohort:ZL}),lq=l({date:i().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative(),models:p(l({provider:Nr,model:i().trim().min(1),totalTokens:d().int().nonnegative(),requests:d().int().nonnegative()}))}),cq=l({requests:d().int().nonnegative(),completedRequests:d().int().nonnegative(),failedRequests:d().int().nonnegative(),missingUsageRequests:d().int().nonnegative(),promptTokens:d().int().nonnegative().nullable(),cacheTelemetryRequests:d().int().nonnegative(),cacheHitRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheRequestHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),completionTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),averageLatencyMs:d().nonnegative().nullable(),p95LatencyMs:d().nonnegative().nullable(),averageFirstTokenMs:d().nonnegative().nullable(),p95FirstTokenMs:d().nonnegative().nullable(),failureRate:d().nonnegative(),activeModelCount:d().int().nonnegative(),peakDailyTokens:d().int().nonnegative(),longestRequestMs:d().int().nonnegative().nullable(),activeDays:d().int().nonnegative(),currentStreakDays:d().int().nonnegative(),longestStreakDays:d().int().nonnegative()});l({generatedAt:i().trim().min(1),range:SI,filters:l({visibility:Zv,status:Yv,provider:Nr.nullable(),model:i().trim().min(1).nullable()}),totals:cq,daily:p(lq),models:p(tq),threads:p(nq),commands:p(aq),routes:p(iq),statuses:p(oq),sources:p(rq),cohorts:p(sq)});l({generatedAt:i().trim().min(1),range:SI,filters:l({visibility:Zv,status:Yv,provider:Nr.nullable(),model:i().trim().min(1).nullable(),sessionId:i().trim().min(1).nullable(),turnId:i().trim().min(1).nullable()}),limit:d().int().positive(),hasMore:I(),records:p(XL)});const dq=l({turnId:i().trim().min(1),requests:d().int().nonnegative(),cacheTelemetryRequests:d().int().nonnegative(),cachedPromptTokens:d().int().nonnegative().nullable(),uncachedPromptTokens:d().int().nonnegative().nullable(),cacheWritePromptTokens:d().int().nonnegative().nullable(),cacheHitRate:d().min(0).max(1).nullable(),cacheTelemetryCoverage:d().min(0).max(1),providers:p(Nr)});l({generatedAt:i().trim().min(1),sessionId:i().trim().min(1),turns:p(dq)});const uq=v(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);l({type:uq,title:i().trim().min(1),summary:i().trim().min(1),severity:v(["nit","concern","blocker"]),payload:te(i(),ie()).default({})});const mq=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),pq=v(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),fq=v(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),hq=l({kind:b("integration"),provider:mq,appIds:p(pq).min(1).max(4),setupSurfaces:p(fq).min(1).max(4),connectionIds:p(i().trim().min(1)).max(8).optional(),capabilities:p(i().trim().min(1)).max(64).optional()}).strict(),Sr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},gq=v(["image","text","file"]),vq=l({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)}),bq=l({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)}),xI=l({id:i().trim().min(1),name:i().trim().min(1).max(240),mediaType:i().trim().min(1).max(160),sizeBytes:d().int().nonnegative().max(Sr.maxAttachmentBytes),kind:gq,lineCount:d().int().nonnegative().max(Sr.maxAttachmentBytes+1).optional(),relativePath:i().trim().min(1).max(1024).optional(),text:i().max(Sr.maxTextChars).optional(),contentsBase64:i().max(Sr.maxAttachmentBase64Chars).optional()}),yq=xI.omit({text:!0,contentsBase64:!0}).extend({imagePreview:vq.optional(),filePreview:bq.optional()});l({experience:Ov.optional(),provider:cl.default(Pr),modelRef:bn.optional(),openPondCommandAccessMode:Jc.optional(),systemKind:dI.nullable().optional(),hiddenFromDefaultSidebar: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:ll.nullable().optional(),subagentDelegationMode:Cm.nullable().optional(),appId:i().nullable().optional(),appName:i().nullable().optional(),workspaceKind:Zc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:qi.nullable().optional(),profileWorkflowBinding:Ic.shape.profileWorkflowBinding,profileComponentBinding:Ic.shape.profileComponentBinding,metadata:te(i(),ie()).optional(),cwd:i().nullable().optional(),title:i().optional(),autoTitlePrompt:i().trim().min(1).max(2e4).optional()});l({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()});l({branch:i().trim().min(1).max(120).optional()});l({prompt:i().min(1),workflowInput:ie().optional(),metadata:te(i(),ie()).optional(),usageAttribution:QL.optional().nullable(),cwd:i().nullable().optional(),model:i().nullable().optional(),modelRef:bn.optional(),mentionedAppIds:p(i().trim().min(1)).max(8).optional(),mentionedConnectedApps:p(hq).max(8).optional(),openPondActionCatalog:p(uI).max(100).optional(),attachments:p(xI).max(Sr.maxAttachments).optional(),createImproveRun:Yc.optional().nullable(),approvalPolicy:v(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:v(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:jv.default("default"),codexReasoningEffort:Tm.optional()});l({prompt:i().min(1),error:i().min(1),target:v(["cloud_workspace","hybrid_sandbox"])});l({reason:v(["manual"]).default("manual"),model:i().nullable().optional(),modelRef:bn.optional()});l({experience:Ov.optional(),provider:cl.optional(),modelRef:bn.nullable().optional(),openPondCommandAccessMode:Jc.optional(),pinned:I().optional(),savedForLater:I().optional(),archived:I().optional(),order:d().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:ll.nullable().optional(),subagentDelegationMode:Cm.nullable().optional(),appId:i().nullable().optional(),appName:i().nullable().optional(),workspaceKind:Zc.optional(),workspaceId:i().nullable().optional(),workspaceName:i().nullable().optional(),localProjectId:i().nullable().optional(),cloudProjectId:i().nullable().optional(),cloudTeamId:i().nullable().optional(),currentProfile:qi.nullable().optional(),metadata:te(i(),ie()).optional(),cwd:i().nullable().optional()});l({command:i().trim().min(1),cwd:i().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:d().int().min(1).max(3600).optional()});l({appIds:p(i()).min(1)});l({expectedRevision:i().optional(),defaultChatProvider:cl.optional(),defaultChatModel:i().min(1).optional(),defaultChatModelRef:bn.nullable().optional(),subagents:yc.optional(),codexPermissionMode:jv.optional(),codexReasoningEffort:Tm.optional(),openPondCommandAccessMode:Jc.optional(),defaultBranchPrefix:i().trim().max(48).optional(),defaultNewProjectDirectory:i().trim().max(4096).optional(),defaultTeamId:i().trim().max(191).nullable().optional(),advancedWorkspaceControls:I().optional(),steerActiveResponses:I().optional(),contextCompaction:dg.optional(),training:ug.optional(),sidebarWidth:d().int().min(244).max(560).optional(),diffPanelWidth:d().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:cg.optional(),editor:Bu.optional()});l({message:i().trim().min(1).max(4e3),surface:i().trim().min(1).max(120).default("app"),stack:i().max(12e3).nullable().optional(),context:te(i(),ie()).optional()}).strict();l({activeTemplateId:Mv,templateName:i().trim().min(1).max(80),soul:i().trim().min(1).max(8e3),saveAsNew:I().optional().default(!1)});l({decision:v(["accept","acceptForSession","decline","cancel"]),answers:te(i().min(1).max(2e3),i().trim().min(1).max(8e3)).optional()});l({branch:i().trim().min(1).max(240).nullable().optional(),surface:v(["desktop","terminal"])});l({handle:i().min(1),baseUrl:i().nullable().optional()});l({handle:i().min(1),baseUrl:i().nullable().optional()});l({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:I().optional()});l({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:I().optional()});l({appId:i(),exists:I(),configPath:i().nullable().optional(),envVar:i().nullable(),toolName:i().nullable(),version:gt([i(),d()]).nullable(),source:v(["hosted_env","local_file","defaults","missing"]),currentConfig:te(i(),ie()).nullable(),defaults:te(i(),ie()).nullable(),schema:te(i(),ie()).nullable(),error:i().nullable().optional(),updatedAt:i()}).passthrough();const Gu=v(["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"]);l({action:Gu,args:te(i(),ie()).optional().default({}),source:v(["ui_button","chat_action","terminal_command","hook"]).default("chat_action")});l({ok:I(),action:Gu,appId:i().nullable().optional(),output:i(),data:ie().optional()});const td=l({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:d().int().positive().default(1),createdAt:i().datetime()}),nd=l({kind:v(["structural","visual","test","user_review"]),status:v(["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()}),kI=l({kind:b("local"),path:i().trim().min(1).max(4096),deviceId:i().trim().min(1).max(200)}),wI=l({kind:b("managed"),fileId:i().trim().min(1).max(200),downloadPath:i().trim().min(1).max(4096)}),Sq=l({kind:b("external"),provider:i().trim().min(1).max(120),resourceId:i().trim().min(1).max(500),url:i().url().nullable()}),II=td.extend({kind:b("file"),contentType:i().trim().min(1).max(200),sizeBytes:d().int().nonnegative(),sha256:i().regex(/^[a-f0-9]{64}$/),location:rt("kind",[kI,wI,Sq]),validation:p(nd).max(32).default([])}),xq=td.extend({kind:b("source_change"),projectId:i().trim().min(1).max(200),ref:i().trim().min(1).max(500),url:i().url().nullable(),validation:p(nd).max(32).default([])}),kq=td.extend({kind:b("deployment"),deploymentId:i().trim().min(1).max(200),url:i().url(),validation:p(nd).max(32).default([])}),wq=td.extend({kind:b("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(nd).max(32).default([])}),_I=l({id:i().trim().min(1).max(191),label:i().trim().min(1).max(160).nullable(),description:i().trim().max(1e3).nullable(),inputSchema:te(i(),ie()).nullable(),outputSchema:te(i(),ie()).nullable(),schedulePolicy:te(i(),ie()).nullable()}),CI=l({base:i().trim().min(1).max(200),resources:te(i(),ie()),modelPolicy:te(i(),ie()).nullable(),setup:te(i(),ie()).nullable()}),Iq=l({id:i().trim().min(1).max(200),kind:v(["sdk_validation","sdk_eval"]),status:v(["passed","failed"]),summary:i().trim().min(1).max(2e3),artifactPath:i().trim().min(1).max(4096),artifactSha256:i().regex(/^[a-f0-9]{64}$/)}),_q=l({path:i().trim().min(1).max(4096),sizeBytes:d().int().nonnegative(),sha256:i().regex(/^[a-f0-9]{64}$/),contentsBase64:i()});l({schema:b("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:l({files:p(_q).min(1).max(1e3),totalSizeBytes:d().int().nonnegative()}),manifest:te(i(),ie()),actions:p(_I).min(1).max(256),runtimeRequirements:CI,receipts:p(Iq).min(2).max(64)});const Cq=td.extend({kind:b("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(_I).min(1).max(256),runtimeRequirements:CI,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:d().int().positive(),sourceSizeBytes:d().int().nonnegative(),location:rt("kind",[kI,wI]),validation:p(nd).max(32).default([])}),vae=rt("kind",[II,xq,kq,wq,Cq]);l({outputs:p(II)});const Rq=v(["sandbox_template","sandbox","generic_git","plain_folder"]),Pq=v(["sandbox_template"]).nullable();l({productKind:Rq,actions:l({files:I(),git:I(),sandboxRuntime:I(),sandboxTemplate:I()}),checks:l({validate:Gu.nullable(),build:Gu.nullable(),postEdit:Pq}),ui:l({showSandboxTemplateActions:I(),showSandboxRuntimeActions:I()})});const Aq=l({id:i(),name:i(),dnsName:i().nullable(),os:i().nullable(),online:I(),active:I(),isSelf:I(),tailscaleIps:p(i()),lastSeen:i().nullable()}),Tq=l({installed:I(),running:I(),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(Aq)}),Eq=l({enabled:I(),reachable:I(),targetUrl:i().nullable(),httpsUrl:i().nullable(),httpsHost:i().nullable(),httpsPort:d().nullable(),setupUrl:i().nullable(),configText:i().nullable(),error:i().nullable()}),jq=l({localUrl:i(),localWebUrl:i(),remoteUrl:i().nullable(),remoteWebUrl:i().nullable(),tokenHash:i(),tailscaleUpCommand:i(),serveCommand:i(),disableCommand:i(),operatorCommand:i(),webUiAvailable:I(),updatedAt:i(),tailscale:Tq,serve:Eq});l({message:i(),status:jq});const RI=v(["github","openpond_git"]),PI=v(["private","public"]),Mq=v(["actions","workflows","instructions","prompts","goals","evals","examples","tasksets","extensions"]),Oq=l({agentIds:p(i().trim().min(1)).max(100),skillNames:p(i().trim().min(1)).max(200),optionalContent:p(Mq).max(20).default([])}),AI=l({provider:RI,owner:i().trim().min(1).max(191).nullable().optional(),repository:i().trim().min(1).max(191),visibility:PI.default("private")}),$q=l({ref:qi,selection:Oq,target:AI}),Nq=l({path:i(),sizeBytes:d().int().nonnegative(),category:i()});l({sourceHash:i(),sourceRevision:i().nullable(),clean:I(),blockedReasons:p(i()),warnings:p(i()),files:p(Nq),excludedFiles:p(i()),target:AI,replacesExisting:I()});$q.extend({expectedSourceHash:i().trim().min(1),confirmed:b(!0)});l({provider:RI,owner:i(),repository:i(),visibility:PI,remoteUrl:i(),webUrl:i(),revision:i()});const Dq=v(["cron","rate"]),TI=v(["queued","running","succeeded","failed","skipped"]),Qv=l({id:i(),localProjectId:i(),localProjectName:i(),agentRootPath:i(),agentName:i(),scheduleName:i(),scheduleType:Dq,scheduleExpression:i(),timezone:i().nullable(),targetAction:i(),input:te(i(),ie()).optional().default({}),enabledByDefault:I(),enabled:I(),sourceHash:i(),manifestHash:i().nullable(),agentVersionId:i().nullable().optional(),agentPackageDigest:i().nullable().optional(),nextRunAt:i().nullable(),lastRunAt:i().nullable(),lastRunStatus:TI.nullable(),lastRunId:i().nullable(),lastError:i().nullable(),createdAt:i(),updatedAt:i()}),EI=l({id:i(),scheduleId:i(),definitionSnapshot:Qv.optional(),configurationSnapshot:te(i(),ie()).optional(),inputSnapshot:te(i(),ie()).optional(),localProjectId:i(),scheduleName:i(),scheduledFor:i(),trigger:v(["schedule","manual"]),status:TI,targetAction:i(),agentVersionId:i().nullable().optional(),agentPackageDigest:i().nullable().optional(),startedAt:i().nullable(),completedAt:i().nullable(),exitCode:d().int().nullable(),stdout:i().nullable(),stderr:i().nullable(),result:te(i(),ie()).nullable(),traceArtifactRef:i().nullable(),error:i().nullable(),createdAt:i(),updatedAt:i()});l({schedules:p(Qv),scheduler:l({running:I(),nextTickAt:i().nullable(),lastSyncAt:i().nullable(),scanRunning:I()})});l({runs:p(EI)});l({enabled:I().optional()});l({input:te(i(),ie()).optional()});l({schedule:Qv,run:EI});const Hq=v(["sunday","monday","tuesday","wednesday","thursday","friday","saturday"]),ml=l({version:b(1),kind:v(["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(Hq).min(1).max(7).optional(),dayOfMonth:d().int().min(1).max(31).optional(),end:rt("kind",[l({kind:b("never")}),l({kind:b("on_date"),date:i().regex(/^\d{4}-\d{2}-\d{2}$/)}),l({kind:b("after_occurrences"),occurrences:d().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"]})}),Lq=l({id:i(),expression:i().nullable(),timeZone:i(),recurrence:ml.nullable(),configurationVersion:d().int(),enabled:I(),nextRunAt:i().nullable(),lastTriggeredAt:i().nullable(),delivery:te(i(),ie()).default({})}),qq=l({id:i(),definitionKey:i(),version:d().int(),name:i(),prompt:i(),modelId:i(),schedules:p(Lq)}),Uq=l({id:i(),definitionId:i(),scheduleId:i().nullable(),definitionName:i(),definitionVersion:d().int(),conversationId:i(),triggerKind:v(["manual","schedule","webhook","retry"]),status:i(),notificationStatus:i(),deliveryStatus:i(),deliveryError:i().nullable(),createdAt:i()});l({definitions:p(qq),runs:p(Uq),asOf:i(),webBaseUrl:i().url().optional()});l({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:ml,modelId:i().trim().min(1).max(191).default("openpond-chat")});gt([l({enabled:I()}),l({name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:ml})]);const jI=v(["queued","running","succeeded","failed"]),MI=l({id:i(),sessionId:i(),sessionTitle:i(),sourceTurnId:i().nullable(),name:i(),prompt:i(),profileRef:qi.optional(),profileWorkflowId:i().optional(),profileMigrationError:i().nullable().optional(),recurrence:ml,enabled:I(),nextRunAt:i().nullable(),lastRunAt:i().nullable(),lastRunStatus:jI.nullable(),lastRunId:i().nullable(),lastError:i().nullable(),scheduledRunCount:d().int().nonnegative(),createdAt:i(),updatedAt:i()}),zq=l({definitionSnapshot:MI.optional(),configurationSnapshot:te(i(),ie()).optional(),id:i(),workflowId:i(),sessionId:i(),scheduledFor:i(),trigger:v(["schedule","manual"]),status:jI,turnId:i().nullable(),error:i().nullable(),createdAt:i(),startedAt:i().nullable(),completedAt:i().nullable(),updatedAt:i()});l({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:ml});gt([l({enabled:I()}),l({name:i().trim().min(1).max(180),prompt:i().trim().min(1).max(2e4),recurrence:ml})]);l({workflows:p(MI),runs:p(zq),asOf:i()});const Xv=te(i(),ie());l({userId:i(),role:v(["owner","admin","member"]),name:i(),handle:i().nullable(),image:i().nullable()});const Bq=l({userId:i(),role:v(["owner","admin","member"]),name:i(),handle:i().nullable(),image:i().nullable(),lastReadSequence:d().int().nonnegative()}),Fq=l({id:i(),messageId:i(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:i(),preview:Xv,createdAt:i()}),OI=l({id:i(),messageId:i().nullable(),clientAttachmentId:i(),kind:b("image"),name:i(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:v(["pending","ready","failed"]),createdAt:i(),readyAt:i().nullable()});l({attachment:OI,uploadUrl:i().url().nullable(),uploadHeaders:te(i(),i()),expiresAt:i().nullable()});l({url:i().url(),expiresAt:i()});const eb=l({id:i(),threadId:i(),teamId:i(),clientRequestId:i().nullable(),authorType:v(["user","agent","system"]),authorUserId:i().nullable(),authorAgentId:i().nullable(),sequence:d().int().nonnegative(),kind:v(["text","system","command_result"]),body:i(),metadata:Xv,editedAt:i().nullable(),deletedAt:i().nullable(),createdAt:i(),refs:p(Fq),attachments:p(OI)}),Vq=l({id:i(),teamId:i(),kind:v(["general","dm","group","channel"]),title:i().nullable(),createdByUserId:i(),lastMessageId:i().nullable(),lastMessageSequence:d().int().nonnegative(),lastMessageAt:i(),createdAt:i(),updatedAt:i(),unreadCount:d().int().nonnegative(),pinnedAt:i().nullable(),mutedAt:i().nullable(),archivedAt:i().nullable(),participants:p(Bq),lastMessage:eb.nullable()});l({thread:Vq,messages:p(eb),hasMoreBefore:I()});l({threadId:i(),mutedAt:i().nullable()});const Kq=v(["pending","running","completed","failed","interrupted","cancelled"]),iS=l({id:i(),conversationId:i(),threadId:i(),teamId:i(),requestedByUserId:i(),executorUserId:i().nullable(),providerId:i(),modelId:i(),clientRequestId:i(),baseMessageSequence:d().int().nonnegative(),status:Kq,partialBody:i().nullable(),userMessageId:i(),assistantMessageId:i().nullable(),errorCode:i().nullable(),cancelledByUserId:i().nullable(),leaseExpiresAt:i().nullable(),heartbeatAt:i().nullable(),createdAt:i(),updatedAt:i()}),Wq=l({id:i(),conversationId:i(),sequence:d().int().nonnegative(),role:v(["user","assistant","system","action"]),body:i(),createdByUserId:i().nullable(),createdAt:i()});l({conversationId:i(),parentThreadId:i(),parentMessageId:i(),teamId:i(),title:i().nullable(),providerId:i().nullable(),modelId:i(),createdByUserId:i(),messages:p(Wq),turns:p(iS),activeTurn:iS.nullable(),createdAt:i(),updatedAt:i()});const $I=l({id:d().int().nonnegative(),teamId:i(),threadId:i(),conversationId:i().nullable(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:Xv,createdAt:i()});l({events:p($I),cursor:d().int().nonnegative(),hasMore:I()});l({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 tb=te(i(),ie()),qa=i().nullable(),Gq=v(["draft","published","archived"]),nb=v(["owner","admin","member"]),NI=v(["active","left"]),DI=v(["mentions","all","none"]),HI=v(["public_preview","members"]),Jq=v(["members","admins"]),Zq=l({canPreview:I(),canJoin:I(),canLeave:I(),canRead:I(),canPost:I(),canUpload:I(),canMention:I(),canManage:I(),requiresRulesAcceptance:I(),currentRulesVersionId:i().nullable()}),LI=l({id:i(),communityId:i(),version:d().int().positive(),title:i(),requiresReacceptance:I(),publishedAt:i()}),Yq=LI.extend({bodyMarkdown:i(),contentHash:i()}),Qq=l({role:nb,status:NI,notificationMode:DI}),Xq=l({id:i(),communityId:i(),userId:i(),role:nb,status:NI,notificationMode:DI,joinedAt:i(),leftAt:qa,createdAt:i(),updatedAt:i()}),qI=l({id:i(),slug:i(),displayName:i(),description:i(),imageUrl:i().nullable(),status:Gq,visibility:v(["public","private"]),joinPolicy:v(["open","closed"]),historyVisibility:HI,featuredAt:qa,publishedAt:qa,archivedAt:qa,memberCount:d().int().nonnegative(),membership:Qq.nullable(),capabilities:Zq,currentRules:LI.nullable()});l({items:p(qI),nextCursor:i().nullable()});const UI=l({lastReadSequence:d().int().nonnegative(),lastReadAt:qa.optional(),mutedAt:qa,pinnedAt:qa}),ab=l({id:i(),communityId:i(),chatThreadId:i().nullable(),slug:i(),displayName:i(),topic:i(),position:d().int().nonnegative(),visibility:HI,postingPolicy:Jq,isDefault:I(),archivedAt:qa,lastMessageSequence:d().int().nonnegative(),unreadCount:d().int().nonnegative(),readState:UI.nullable()});qI.omit({currentRules:!0}).extend({currentRules:Yq.nullable(),channels:p(ab),previewMessageLimit:d().int().positive()});const eU=l({id:i(),messageId:i(),refType:v(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:i(),preview:tb,createdAt:i()}),zI=l({id:i(),messageId:i().nullable(),clientAttachmentId:i(),kind:b("image"),name:i(),mediaType:v(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:d().int().positive(),status:v(["pending","ready","failed"]),createdAt:i(),readyAt:qa});l({attachment:zI,uploadUrl:i().url().nullable(),uploadHeaders:te(i(),i()),expiresAt:qa});l({url:i().url(),expiresAt:i()});const BI=l({id:i(),threadId:i(),teamId:sl(),clientRequestId:i().nullable(),authorType:v(["user","agent","system"]),authorUserId:i().nullable(),authorAgentId:i().nullable(),sequence:d().int().nonnegative(),kind:v(["text","system","command_result"]),body:i(),metadata:tb,editedAt:qa,deletedAt:qa,createdAt:i(),refs:p(eU),attachments:p(zI)});l({messages:p(BI),hasMoreBefore:I(),channelId:i(),readState:UI.omit({lastReadAt:!0}).nullable(),preview:I()});const tU=l({userId:i(),handle:i().nullable(),name:i().nullable(),role:nb});l({items:p(tU),nextCursor:i().nullable()});const FI=l({id:d().int().nonnegative(),communityId:i(),channelId:i(),threadId:i(),type:v(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:tb,createdAt:i()});l({events:p(FI),cursor:d().int().nonnegative(),hasMore:I()});l({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)});l({membership:Xq,channels:p(ab)});l({channels:p(ab)});var _c=i().trim().min(1).max(500),nU=i().regex(/^[a-f0-9]{64}$/),Ju=l({id:_c,revision:d().int().positive(),contentHash:nU}).strict(),aU=l({schemaVersion:b("openpond.hostedTasksetSummary.v1"),id:_c,teamId:_c,release:Ju,name:i().min(1).max(500),description:i().max(2e4),taskCount:d().int().nonnegative(),buildIntent:i().min(1).max(100),methodHint:i().min(1).max(100).nullable(),packageBytes:d().int().nonnegative().nullable(),storedBytes:d().int().nonnegative().nullable(),createdAt:i().datetime({offset:!0})}).strict();l({afterId:i().trim().min(1).max(2e3).optional(),limit:d().int().min(1).max(100).default(30),modelProjectId:_c.optional(),projectId:_c.optional(),search:i().trim().max(100).optional(),sort:v(["id","name","updated"]).default("id")}).strict();l({items:p(aU).max(100),nextCursor:i().trim().min(1).max(2e3).nullable()}).strict();l({code:i().min(1),message:i().min(1)}).strict();const iU=l({candidateId:i().min(1).max(240),frozenRevision:d().int().positive(),frozenHash:i().regex(/^[a-f0-9]{64}$/),harnessRelease:V,protectedClosureHash:i().regex(/^[a-f0-9]{64}$/)}).strict(),oS=i().trim().min(1).max(240),oU=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."),ad=l({schemaVersion:b("openpond.tasksetMetricPolicy.v1"),primaryMetric:oS,aggregation:v(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:v(["zero","exclude"]),taskWeights:te(oS,d().positive().max(1e6)).optional(),customAggregator:l({module:oU,exportName:i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:H,timeoutMs:d().int().positive().max(3e5),networkPolicy:b("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."})}),rU=l({schemaVersion:b("openpond.tasksetMetricResult.v1"),runManifest:V,tasksetRelease:V,policy:ad,policyHash:H,receiptRefs:p(V).min(1).max(1e6),includedCount:d().int().nonnegative(),missingRewardCount:d().int().nonnegative(),excludedCount:d().int().nonnegative(),value:d().min(0).max(1).nullable()}).strict(),ib=rU.extend({contentHash:H}).strict(),Yt=T,Ho=H,VI=l({id:Yt,revision:d().int().positive(),contentHash:Ho}).strict(),ob=l({kind:b("owner_attested_local"),ownerActorId:Yt,teamId:Yt,executionHash:Ho,configurationHash:Ho,retainedAttemptHash:Ho,traceHash:Ho,publicationCutoffHash:Ho}).strict(),sU=ob.omit({publicationCutoffHash:!0,kind:!0}).extend({kind:b("native_local")}).strict(),lU=l({origin:ob,executionId:Yt,receiptId:Yt,taskId:Yt,targetId:Yt,familyKey:Yt,split:v(["train","validation","test","frozen_eval"]),input:te(i(),ie()),policyVisibleContext:te(i(),ie()),output:i().nullable(),error:i().nullable(),events:p(te(i(),ie())).max(1e3),coverage:l({sourceEventCount:d().int().nonnegative().max(2e4),publishedEventCount:d().int().nonnegative().max(1e3),traceLimited:I(),artifactsIncluded:b(!1)}).strict()}).strict().superRefine((e,t)=>{(e.events.length!==e.coverage.publishedEventCount||e.coverage.sourceEventCount<e.events.length||e.coverage.traceLimited!==e.coverage.sourceEventCount>e.events.length)&&t.addIssue({code:"custom",message:"Publication coverage must describe its actual retained event population."}),ct(e.events)!==e.origin.publicationCutoffHash&&t.addIssue({code:"custom",message:"Published trace cutoff changed."})}),cU=l({schemaVersion:b("openpond.humanLocalEvidenceExport.v1"),actorId:Yt,scope:Yt,projectId:Yt,dataset:VI,graderId:Yt,compiledGraderHash:Ho,attempts:p(lU).min(1).max(2),sealedAt:pe}).strict().superRefine((e,t)=>{e.attempts.some(n=>n.origin.ownerActorId!==e.actorId||n.origin.teamId!==e.scope)&&t.addIssue({code:"custom",message:"Local publication belongs to another actor/workspace."})}),dU=cU.safeExtend({contentHash:Ho}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;ct(a)!==n&&t.addIssue({code:"custom",message:"Local evidence export bytes changed."})}),KI=l({endpoint:b("export_local"),scope:Yt,projectId:Yt,graderId:Yt,selections:p(l({executionId:Yt,receiptId:Yt}).strict()).min(1).max(2)}).strict(),uU=l({endpoint:b("publish_local"),scope:Yt,projectId:Yt,operationId:Yt,audience:p(Yt).max(100),workspaceVisible:I(),evidence:dU}).strict(),mU=KI.omit({endpoint:!0}).extend({endpoint:b("share_local"),operationId:Yt,audience:p(Yt).max(100),workspaceVisible:I()}).strict(),pU=l({endpoint:b("local_publications"),scope:Yt,executionId:Yt}).strict(),fU=l({endpoint:b("revoke_local"),scope:Yt,publication:VI}).strict();var WI=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},hU=WI((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,c;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(c=Object.keys(a),r=c.length,r!==Object.keys(o).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(o,c[s]))return!1;for(s=r;s--!==0;){var m=c[s];if(!n(a[m],o[m]))return!1}return!0}return a!==a&&o!==o}}),gU=WI(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=hU();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),rS=Ut,sS={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"}}},vU=Object.prototype.hasOwnProperty,bU=gU().default,Ct={validate:Ut};function Sa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=Sa.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),c===0)if(e&&typeof e=="object"&&!Array.isArray(e))for(let f in e){let g=c;Ct.validate(e[f],{instancePath:t+"/"+f.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:f,rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=g===c;if(!u)break}else return Sa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return Sa.errors=s,c===0}Sa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function On(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=On.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),c===0)if(Array.isArray(e)){if(e.length>32)return On.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return On.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var u=!0;let f=e.length;for(let g=0;g<f;g++){let S=c;Ct.validate(e[g],{instancePath:t+"/"+g,parentData:e,parentDataProperty:g,rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=S===c;if(!u)break}}}else return On.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return On.errors=s,c===0}On.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var yU={enum:["array","boolean","integer","null","number","object","string"]};function Ai(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=Ai.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"?(Ai.errors=s,c===0):(Ai.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:yU.enum}}],!1)}Ai.evaluated={dynamicProps:!1,dynamicItems:!1};function zt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=zt.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))?(zt.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):(zt.errors=s,c===0):(zt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}zt.evaluated={dynamicProps:!1,dynamicItems:!1};function Na(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=Na.evaluated;if(m.dynamicProps&&(m.props=void 0),m.dynamicItems&&(m.items=void 0),c===0)if(Array.isArray(e)){var u=!0;let f=e.length;for(let g=0;g<f;g++){let S=c;if(typeof e[g]!="string")return Na.errors=[{instancePath:t+"/"+g,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var u=S===c;if(!u)break}if(u){let g=e.length,S;if(g>1){let k={};for(;g--;){let C=e[g];if(typeof C=="string"){if(typeof k[C]=="number")return S=k[C],Na.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:g,j:S}}],!1;k[C]=g}}}}}else return Na.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return Na.errors=s,c===0}Na.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function Ut(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:o=e,dynamicAnchors:r={}}={}){let s=null,c=0,m=Ut.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 Ut.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:sS.type}}],!1;if(c===0&&e&&typeof e=="object"&&!Array.isArray(e)){let k=c;for(let C in e)if(!vU.call(sS.properties,C))return Ut.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:C}}],!1;if(k===c){if(e.$schema!==void 0){let C=c;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return Ut.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var u=C===c}else var u=!0;if(u){if(e.$ref!==void 0){let P=c;if(typeof e.$ref!="string")return Ut.errors=[{instancePath:t+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type:"string"}}],!1;var u=P===c}else var u=!0;if(u){if(e.$comment!==void 0){let j=c;if(typeof e.$comment!="string")return Ut.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var u=j===c}else var u=!0;if(u){if(e.$defs!==void 0){let R=c;Sa(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:o,dynamicAnchors:r})||(s=s===null?Sa.errors:s.concat(Sa.errors),c=s.length);var u=R===c}else var u=!0;if(u){if(e.properties!==void 0){let $=c;Sa(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:o,dynamicAnchors:r})||(s=s===null?Sa.errors:s.concat(Sa.errors),c=s.length);var u=$===c}else var u=!0;if(u){if(e.dependentSchemas!==void 0){let O=c;Sa(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:o,dynamicAnchors:r})||(s=s===null?Sa.errors:s.concat(Sa.errors),c=s.length);var u=O===c}else var u=!0;if(u){if(e.allOf!==void 0){let M=c;On(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:o,dynamicAnchors:r})||(s=s===null?On.errors:s.concat(On.errors),c=s.length);var u=M===c}else var u=!0;if(u){if(e.anyOf!==void 0){let w=c;On(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:o,dynamicAnchors:r})||(s=s===null?On.errors:s.concat(On.errors),c=s.length);var u=w===c}else var u=!0;if(u){if(e.oneOf!==void 0){let A=c;On(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:o,dynamicAnchors:r})||(s=s===null?On.errors:s.concat(On.errors),c=s.length);var u=A===c}else var u=!0;if(u){if(e.prefixItems!==void 0){let E=c;On(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:o,dynamicAnchors:r})||(s=s===null?On.errors:s.concat(On.errors),c=s.length);var u=E===c}else var u=!0;if(u){if(e.items!==void 0){let D=c;Ct.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=D===c}else var u=!0;if(u){if(e.additionalProperties!==void 0){let U=c;Ct.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=U===c}else var u=!0;if(u){if(e.not!==void 0){let L=c;Ct.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=L===c}else var u=!0;if(u){if(e.if!==void 0){let J=c;Ct.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=J===c}else var u=!0;if(u){if(e.then!==void 0){let X=c;Ct.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=X===c}else var u=!0;if(u){if(e.else!==void 0){let de=c;Ct.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=de===c}else var u=!0;if(u){if(e.contains!==void 0){let Me=c;Ct.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=Me===c}else var u=!0;if(u){if(e.unevaluatedProperties!==void 0){let Ie=c;Ct.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=Ie===c}else var u=!0;if(u){if(e.unevaluatedItems!==void 0){let ne=c;Ct.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=ne===c}else var u=!0;if(u){if(e.propertyNames!==void 0){let je=c;Ct.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:o,dynamicAnchors:r})||(s=s===null?Ct.validate.errors:s.concat(Ct.validate.errors),c=s.length);var u=je===c}else var u=!0;if(u){if(e.type!==void 0){let Se=e.type,oe=c,be=c,re=!1,ue=c;Ai(Se,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:o,dynamicAnchors:r})||(s=s===null?Ai.errors:s.concat(Ai.errors),c=s.length);var g=ue===c;re=re||g;let ke=c;if(c===ke)if(Array.isArray(Se))if(Se.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),c++}else{var f=!0;let we=Se.length;for(let le=0;le<we;le++){let xe=c;Ai(Se[le],{instancePath:t+"/type/"+le,parentData:Se,parentDataProperty:le,rootData:o,dynamicAnchors:r})||(s=s===null?Ai.errors:s.concat(Ai.errors),c=s.length);var f=xe===c;if(!f)break}if(f){let le=Se.length,xe;if(le>1){e:for(;le--;)for(xe=le;xe--;)if(bU(Se[le],Se[xe])){let Ue={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:le,j:xe}};s===null?s=[Ue]:s.push(Ue),c++;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),c++}var g=ke===c;if(re=re||g,re)c=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),c++,Ut.errors=s,!1}var u=oe===c}else var u=!0;if(u){if(e.enum!==void 0){let oe=e.enum,be=c;if(c===be)if(Array.isArray(oe)){if(oe.length<1)return Ut.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return Ut.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var u=be===c}else var u=!0;if(u){if(e.title!==void 0){let be=c;if(typeof e.title!="string")return Ut.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var u=be===c}else var u=!0;if(u){if(e.description!==void 0){let re=c;if(typeof e.description!="string")return Ut.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var u=re===c}else var u=!0;if(u){if(e.examples!==void 0){let ue=c;if(!Array.isArray(e.examples))return Ut.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var u=ue===c}else var u=!0;if(u){if(e.readOnly!==void 0){let ke=c;if(typeof e.readOnly!="boolean")return Ut.errors=[{instancePath:t+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var u=ke===c}else var u=!0;if(u){if(e.writeOnly!==void 0){let Le=c;if(typeof e.writeOnly!="boolean")return Ut.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var u=Le===c}else var u=!0;if(u){if(e.deprecated!==void 0){let we=c;if(typeof e.deprecated!="boolean")return Ut.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var u=we===c}else var u=!0;if(u){if(e.multipleOf!==void 0){let le=e.multipleOf,xe=c;if(c===xe)if(typeof le=="number"&&isFinite(le)){if(le<=0||isNaN(le))return Ut.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return Ut.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var u=xe===c}else var u=!0;if(u){if(e.maximum!==void 0){let xe=e.maximum,Ue=c;if(!(typeof xe=="number"&&isFinite(xe)))return Ut.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var u=Ue===c}else var u=!0;if(u){if(e.exclusiveMaximum!==void 0){let Ue=e.exclusiveMaximum,Ze=c;if(!(typeof Ue=="number"&&isFinite(Ue)))return Ut.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var u=Ze===c}else var u=!0;if(u){if(e.minimum!==void 0){let Ze=e.minimum,it=c;if(!(typeof Ze=="number"&&isFinite(Ze)))return Ut.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var u=it===c}else var u=!0;if(u){if(e.exclusiveMinimum!==void 0){let it=e.exclusiveMinimum,at=c;if(!(typeof it=="number"&&isFinite(it)))return Ut.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var u=at===c}else var u=!0;if(u){if(e.maxLength!==void 0){let at=c;zt(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:o,dynamicAnchors:r})||(s=s===null?zt.errors:s.concat(zt.errors),c=s.length);var u=at===c}else var u=!0;if(u){if(e.minLength!==void 0){let Ne=c;zt(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:o,dynamicAnchors:r})||(s=s===null?zt.errors:s.concat(zt.errors),c=s.length);var u=Ne===c}else var u=!0;if(u){if(e.maxItems!==void 0){let We=c;zt(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:o,dynamicAnchors:r})||(s=s===null?zt.errors:s.concat(zt.errors),c=s.length);var u=We===c}else var u=!0;if(u){if(e.minItems!==void 0){let qe=c;zt(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:o,dynamicAnchors:r})||(s=s===null?zt.errors:s.concat(zt.errors),c=s.length);var u=qe===c}else var u=!0;if(u){if(e.maxContains!==void 0){let q=c;zt(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:o,dynamicAnchors:r})||(s=s===null?zt.errors:s.concat(zt.errors),c=s.length);var u=q===c}else var u=!0;if(u){if(e.minContains!==void 0){let N=c;zt(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:o,dynamicAnchors:r})||(s=s===null?zt.errors:s.concat(zt.errors),c=s.length);var u=N===c}else var u=!0;if(u){if(e.maxProperties!==void 0){let F=c;zt(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:o,dynamicAnchors:r})||(s=s===null?zt.errors:s.concat(zt.errors),c=s.length);var u=F===c}else var u=!0;if(u){if(e.minProperties!==void 0){let ee=c;zt(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:o,dynamicAnchors:r})||(s=s===null?zt.errors:s.concat(zt.errors),c=s.length);var u=ee===c}else var u=!0;if(u){if(e.uniqueItems!==void 0){let me=c;if(typeof e.uniqueItems!="boolean")return Ut.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var u=me===c}else var u=!0;if(u){if(e.required!==void 0){let $e=c;Na(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:o,dynamicAnchors:r})||(s=s===null?Na.errors:s.concat(Na.errors),c=s.length);var u=$e===c}else var u=!0;if(u){if(e.dependentRequired!==void 0){let ze=e.dependentRequired,tt=c;if(c===tt)if(ze&&typeof ze=="object"&&!Array.isArray(ze))for(let pt in ze){let bt=c;Na(ze[pt],{instancePath:t+"/dependentRequired/"+pt.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:ze,parentDataProperty:pt,rootData:o,dynamicAnchors:r})||(s=s===null?Na.errors:s.concat(Na.errors),c=s.length);var S=bt===c;if(!S)break}else return Ut.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var u=tt===c}else var u=!0;if(u){if(e.contentEncoding!==void 0){let tt=c;if(typeof e.contentEncoding!="string")return Ut.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var u=tt===c}else var u=!0;if(u)if(e.contentMediaType!==void 0){let tt=c;if(typeof e.contentMediaType!="string")return Ut.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var u=tt===c}else var u=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return Ut.errors=s,c===0}Ut.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const lS="https://json-schema.org/draft/2020-12/schema",SU=1048576,xU=32768,kU=new Set(["properties","$defs","dependentSchemas"]),wU=new Set(["allOf","anyOf","oneOf","prefixItems"]),IU=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Wa(e,t=SU){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[c,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)&&c!=="length"&&(!/^(0|[1-9]\d*)$/u.test(c)||Number(c)>=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 rb(e){try{return _U(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 _U(e){if(Wa(e,xU),ec(e,e,new Set,0,{remaining:2048}),!rS(e)){const t=rS.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function ec(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!==lS)throw new Error(`Task schemas must use ${lS}.`);for(const[c,m]of Object.entries(s))if(c==="$ref"){if(typeof m!="string"||!m.startsWith("#/$defs/"))throw new Error("Task schema references must be local JSON pointers into $defs.");let u=t;for(const f of m.slice(2).split("/")){if(/~(?![01])/u.test(f))throw new Error("Invalid task schema JSON pointer.");const g=f.replaceAll("~1","/").replaceAll("~0","~");if(!u||typeof u!="object"||!Object.hasOwn(u,g))throw new Error(`Task schema reference ${m} is missing.`);u=u[g]}ec(u,t,r,a+1,o)}else if(kU.has(c)){if(!m||typeof m!="object"||Array.isArray(m))throw new Error(`Invalid schema map ${c}.`);for(const u of Object.values(m))ec(u,t,r,a+1,o)}else if(wU.has(c)){if(!Array.isArray(m)||m.length>32)throw new Error(`Schema ${c} must contain at most 32 alternatives.`);for(const u of m)ec(u,t,r,a+1,o)}else IU.has(c)&&ec(m,t,r,a+1,o)}const GI=l({taskId:T,input:te(i(),ie()),policyVisibleContext:te(i(),ie()),expectedOutput:te(i(),ie()).nullable().optional(),tags:p(T).max(100).optional()}).strict(),Gs=l({schemaVersion:b("openpond.humanTaskProposal.v1"),tasks:p(GI).min(1).max(1e3),contentHash:H}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;n!==ct(a)&&t.addIssue({code:"custom",message:"Task proposal content hash differs."}),new Set(e.tasks.map(o=>o.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",message:"Each task may be proposed once."});try{Wa(e,1048576)}catch{t.addIssue({code:"custom",message:"Task proposal exceeds retained data bounds."})}}),cS=l({schemaVersion:b("openpond.humanTaskProposal.v1"),tasks:p(GI).min(1).max(1e3),contentHash:H,referenceRedacted:b(!0).optional()}).strict().superRefine((e,t)=>{e.referenceRedacted?e.tasks.some(n=>n.expectedOutput!==void 0)&&t.addIssue({code:"custom",message:"Redacted proposals cannot include reference outputs."}):Gs.safeParse(e).success||t.addIssue({code:"custom",message:"Task proposal integrity differs."})});function bae(e){const t={schemaVersion:"openpond.humanTaskProposal.v1",tasks:e};return Gs.parse({...t,contentHash:ct(t)})}const Fe=T,_n=l({id:Fe,revision:d().int().positive(),contentHash:H}).strict(),CU=rt("kind",[l({id:Fe,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(l({value:gt([d(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("score"),minimum:d().finite(),maximum:d().finite(),step:d().positive().finite()}).strict().refine(e=>e.minimum<e.maximum&&e.step<=e.maximum-e.minimum,"Use an increasing raw score range and a step within that range."),l({id:Fe,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(l({value:gt([d(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("category"),options:p(i().trim().min(1).max(500)).min(2).max(100)}).strict().refine(e=>new Set(e.options).size===e.options.length,"Category options must be unique."),l({id:Fe,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(l({value:gt([d(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("boolean")}).strict(),l({id:Fe,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(l({value:gt([d(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("text"),minimumLength:d().int().nonnegative().max(2e4).optional(),maximumLength:d().int().positive().max(2e4)}).strict(),l({id:Fe,label:i().trim().min(1).max(500),instructions:i().max(2e4),required:I(),allowAbstain:I(),requireRationale:I().optional(),anchors:p(l({value:gt([d(),i(),I()]),description:i().min(1).max(2e3)}).strict()).max(100).optional(),kind:b("preference"),requireStrength:I().optional(),allowTie:I()}).strict()]),id=l({schemaVersion:b("openpond.humanForm.v1"),mode:v(["individual","pairwise"]),instructions:i().max(2e4),criteria:p(CU).min(1).max(100)}).strict().superRefine((e,t)=>{e.criteria.forEach((n,a)=>{n.kind==="text"&&(n.minimumLength??0)>n.maximumLength&&t.addIssue({code:"custom",path:["criteria",a,"minimumLength"],message:"Minimum text length must not exceed maximum length."});const o=new Set;n.anchors?.forEach((r,s)=>{const c=r.value,m=n.kind==="score"?typeof c=="number"&&Number.isFinite(c)&&c>=n.minimum&&c<=n.maximum&&Math.abs((c-n.minimum)/n.step-Math.round((c-n.minimum)/n.step))<1e-8:n.kind==="category"?typeof c=="string"&&n.options.includes(c):n.kind==="boolean"?typeof c=="boolean":n.kind==="preference"?["A","B",...n.allowTie?["tie"]:[]].includes(String(c)):typeof c=="string",u=JSON.stringify(c);(!m||o.has(u))&&t.addIssue({code:"custom",path:["criteria",a,"anchors",s,"value"],message:"Each anchor must describe a unique valid raw value."}),o.add(u)})}),new Set(e.criteria.map(n=>n.id)).size!==e.criteria.length&&t.addIssue({code:"custom",path:["criteria"],message:"Criterion IDs must be unique."}),e.mode==="individual"&&e.criteria.some(n=>n.kind==="preference")&&t.addIssue({code:"custom",path:["criteria"],message:"Preferences require an explicit pair."})}),RU=l({localSource:gt([ob,sU]).optional(),recordedSource:l({id:Fe,snapshotHash:H,boundaryId:Fe,boundaryRevisionHash:H}).strict().optional(),experimentId:Fe,attemptId:Fe,taskId:Fe,targetId:Fe,output:_n,trace:_n.nullable(),familyKey:Fe,split:v(["train","validation","test","frozen_eval"])}).strict(),sb=l({publication:_n.optional(),dataset:_n,grader:_n,graderBinding:l({id:Fe,version:i().min(1).max(100),contentHash:H}).strict(),rubric:_n,attempts:p(RU).max(2),taskIds:p(Fe).min(1).max(1e3).optional()}).strict().superRefine((e,t)=>{!e.attempts.length&&!e.taskIds?.length&&t.addIssue({code:"custom",message:"Select retained attempts or exact tasks."}),e.taskIds&&new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"Select each task once."}),e.attempts.length===2&&(e.attempts[0].attemptId===e.attempts[1].attemptId||e.attempts[0].taskId!==e.attempts[1].taskId||e.attempts[0].familyKey!==e.attempts[1].familyKey||e.attempts[0].split!==e.attempts[1].split)&&t.addIssue({code:"custom",path:["attempts"],message:"A/B review requires distinct attempts of the same task, family and split."})}),Js=l({criterionId:Fe,value:gt([d().finite(),I(),i().max(2e4),sl()]),abstain:I(),note:i().max(2e4),strength:v(["slight","moderate","strong"]).optional()}).strict(),JI=l({approval:v(["none","manager"]),minimumRaters:d().int().min(1).max(100),managerIds:p(Fe).max(100),reviewerIds:p(Fe).max(100),queueClaim:I(),teamVisible:I(),distinctManager:I().optional(),independentRaters:I().optional(),blindPair:I().optional()}).strict().superRefine((e,t)=>{e.approval==="none"&&e.minimumRaters!==1&&t.addIssue({code:"custom",path:["minimumRaters"],message:"Multi-rater review requires explicit adjudication."})}),ZI=l({taskProposal:Gs.optional(),id:Fe,revision:d().int().positive(),actorId:Fe,generation:d().int().positive(),evidenceHash:H,formHash:H,answers:p(Js).max(100),note:i().max(2e4),submittedAt:pe,supersedes:Fe.nullable(),contentHash:H}).strict(),tc=l({taskProposalHash:H.optional(),id:Fe,revision:d().int().positive(),actorId:Fe,outcome:v(["accept","reject","request_changes"]),submissions:p(l({id:Fe,contentHash:H}).strict()).min(1).max(100),answers:p(Js).max(100),note:i().max(2e4),decidedAt:pe,contentHash:H}).strict(),Zu=l({schemaVersion:b("openpond.humanReview.v1"),id:Fe,revision:d().int().positive(),scope:Fe,projectId:Fe,createdBy:Fe,kind:v(["author","execute","grade"]),dueAt:pe.optional(),title:i().trim().min(1).max(500),authorPublication:l({proposalHash:H,dataset:_n,operationId:Fe,publishedBy:Fe,publishedAt:pe}).strict().nullable(),evidence:sb,form:id,policy:JI,status:v(["queued","assigned","in_progress","submitted","returned","accepted","rejected","cancelled"]),assigneeId:Fe.nullable(),generation:d().int().positive(),drafts:p(l({taskProposal:Gs.optional(),actorId:Fe,generation:d().int().positive(),answers:p(Js).max(100),note:i().max(2e4),updatedAt:pe}).strict()).max(100),submissions:p(ZI).max(1e3),decisions:p(tc).max(1e3),audit:p(l({actorId:Fe,action:v(["claim","reassign","cancel"]),priorAssigneeId:Fe.nullable(),assigneeId:Fe.nullable(),generation:d().int().positive(),note:i().max(2e4),occurredAt:pe}).strict()).max(1e3),execution:l({executionId:Fe.nullable(),operationId:Fe,boundBy:Fe,configurationHash:H,generation:d().int().positive(),result:_n.nullable()}).strict().nullable(),createdAt:pe,updatedAt:pe,contentHash:H}).strict(),wi={operationId:Fe,id:Fe,expectedRevision:d().int().nonnegative()},PU=rt("action",[l({...wi,action:b("create"),projectId:Fe,kind:Zu.shape.kind,title:Zu.shape.title,dueAt:pe.optional(),evidence:sb,form:id,policy:JI,assigneeId:Fe.nullable()}).strict(),l({...wi,action:b("claim")}).strict(),l({...wi,action:b("bind_author_publication"),proposalHash:H,dataset:_n}).strict(),l({...wi,action:b("reserve_execution"),generation:d().int().positive(),runOperationId:Fe,configurationHash:H}).strict(),l({...wi,action:b("bind_execution"),generation:d().int().positive(),executionId:Fe,runOperationId:Fe,configurationHash:H}).strict(),l({...wi,action:b("reassign"),assigneeId:Fe.nullable(),note:i().trim().min(1).max(2e4)}).strict(),l({...wi,action:b("cancel"),note:i().max(2e4)}).strict(),l({...wi,action:b("save_draft"),taskProposal:Gs.optional(),generation:d().int().positive(),answers:p(Js).max(100),note:i().max(2e4)}).strict(),l({...wi,action:b("submit"),taskProposal:Gs.optional(),generation:d().int().positive(),evidenceHash:H,formHash:H,executionResult:_n.optional(),answers:p(Js).max(100),note:i().max(2e4)}).strict(),l({...wi,action:b("decide"),taskProposalHash:H.optional(),outcome:tc.shape.outcome,submissions:tc.shape.submissions,answers:tc.shape.answers,note:tc.shape.note}).strict()]),AU=rt("endpoint",[l({endpoint:b("command"),scope:Fe,command:PU}).strict(),l({endpoint:b("get"),scope:Fe,id:Fe,revision:d().int().positive().optional()}).strict(),l({endpoint:b("inbox"),scope:Fe,projectId:Fe.optional(),view:v(["mine","team","approval"]),status:v(["active","history"]),afterId:Fe.optional(),limit:d().int().min(1).max(100)}).strict()]),YI=Zu.omit({evidence:!0,drafts:!0,submissions:!0}).extend({drafts:p(Zu.shape.drafts.element.omit({taskProposal:!0}).extend({taskProposal:cS.optional()})).max(100),submissions:p(ZI.omit({taskProposal:!0}).extend({taskProposal:cS.optional()})).max(1e3),evidence:sb.nullable(),evidenceHash:H,formHash:H,permissions:l({owner:I(),manager:I(),reviewer:I(),claim:I()}).strict()}).strict(),TU=l({items:p(YI).max(100),nextCursor:Fe.nullable(),actionCount:d().int().nonnegative(),approvalAvailable:I()}).strict(),QI=l({endpoint:b("snapshot"),scope:Fe,projectId:Fe,graderId:Fe,selections:p(l({executionId:Fe,receiptId:Fe}).strict()).min(1).max(2)}).strict(),EU=l({endpoint:b("snapshot_tasks"),scope:Fe,projectId:Fe,graderId:Fe,dataset:_n,taskIds:p(Fe).min(1).max(1e3).optional(),all:b(!0).optional()}).strict().refine(e=>!!e.all!=!!e.taskIds,"Choose an exact selected task list or the server-frozen full Dataset."),jU=l({endpoint:b("inspect"),scope:Fe,id:Fe,slot:d().int().min(0).max(1).optional(),afterId:i().min(1).max(500).optional()}).strict(),MU=l({endpoint:b("results"),scope:Fe,executionId:Fe,selection:p(_n).max(1e4).optional()}).strict(),OU=l({endpoint:b("members"),scope:Fe}).strict(),$U=l({endpoint:b("execute"),scope:Fe,id:Fe,expectedRevision:d().int().positive(),generation:d().int().positive(),operationId:Fe,configuration:ie()}).strict(),NU=l({endpoint:b("execution"),scope:Fe,id:Fe,action:v(["status","result","cancel"])}).strict(),DU=QI.omit({endpoint:!0}).extend({endpoint:b("publish_evidence"),operationId:Fe,audience:p(Fe).max(100),workspaceVisible:I()}).strict(),HU=l({endpoint:b("publication_access"),scope:Fe,projectId:Fe}).strict(),LU=l({endpoint:b("revoke_publication"),scope:Fe,publication:_n}).strict(),qU=l({endpoint:b("publish_author"),scope:Fe,id:Fe,expectedRevision:d().int().positive(),operationId:Fe,proposalHash:H,workspaceId:Fe.optional(),expectedWorkspaceRevision:d().int().positive().optional()}).strict(),UU=l({endpoint:b("author_tasks"),scope:Fe,id:Fe,includeReference:b(!0).optional()}).strict(),zU=l({endpoint:b("graders"),scope:Fe,projectId:Fe,dataset:_n}).strict(),yae=p(l({id:Fe,name:i(),version:i(),contentHash:H,mode:v(["individual","pairwise"])}).strict()).max(1e3),BU=gt([fU,pU,KI,uU,mU,HU,qU,UU,zU,DU,LU,$U,NU,AU,QI,EU,jU,MU,OU]),FU=p(l({origin:b("owner_attested_local").optional(),coverage:l({sourceEventCount:d().int().nonnegative(),publishedEventCount:d().int().nonnegative(),traceLimited:I(),artifactsIncluded:b(!1)}).strict().optional(),reviewId:Fe,reviewRevision:d().int().positive(),evidenceHash:H,slot:i(),input:ie(),output:ie(),error:i().nullable(),events:p(te(i(),ie())),eventCount:d().int().nonnegative(),evidenceLimited:I(),nextEventCursor:i().nullable(),slotIndex:d().int().nonnegative(),executionId:Fe.optional(),receiptId:Fe.optional()}).strict()).max(1e3),Ga=v(["train","validation","test","frozen_eval"]),VU=l({path:i().trim().min(1).max(2e3).refine(WU),mediaType:i().trim().min(1).max(200),schemaRef:gn.nullable().default(null),maxBytes:d().int().positive().max(25e7).nullable().default(null),metadata:jn}).strict(),KU=l({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(),XI=l({protocolVersion:b("openpond.environment.v1"),kind:v(["text","agent","work","custom_program"]),entrypoint:i().trim().min(1).max(1e3),stateful:I(),deterministicSeeds:I(),lifecycle:p(v(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:d().int().positive().max(36e5)}).strict(),Hm=l({id:T,version:i().trim().min(1).max(100),weight:d().nonnegative().max(1e3).default(1),hardGate:I().default(!1),rewardEligible:I().default(!1),privileged:I().default(!1)}),e_=Hm.extend({kind:v(["content","schema","artifact","runtime_event","state"]),config:te(i(),ie())}).strict(),t_=Hm.extend({kind:b("model_judge"),rubricRef:gn,calibrationStatus:v(["pending","passed","failed"]),model:l({providerId:T,modelId:T,revision:i().trim().min(1).max(500).nullable()}).strict().optional(),temperature:d().min(0).max(2).optional()}).strict(),n_=v(["isolated_javascript","sandbox_process"]),a_=Hm.extend({kind:b("custom_verifier"),runtime:n_.optional(),verifierRef:gn,exportName:i().trim().min(1).max(240).optional(),timeoutMs:d().int().positive().max(3e5),networkPolicy:b("none")}).strict(),i_=Hm.extend({kind:b("human"),rubricRef:gn,reviewerRole:i().trim().min(1).max(500),form:id.optional()}).strict(),o_=gt([e_,t_,a_,i_]),lb=l({id:T,clusterKey:T,split:Ga,input:te(i(),ie()),expectedOutput:te(i(),ie()).nullable(),policyVisibleContext:te(i(),ie()).default({}),privilegedContextRef:T.nullable(),artifactRefs:p(gn).max(1e3).default([]),requiredOutputs:p(VU).max(1e3).optional(),tags:p(T).max(100).default([])}).strict(),r_=l({schemaVersion:b("openpond.tasksetRelease.v2"),id:T,revision:d().int().positive(),policy:KU,environment:XI,environmentRelease:l({id:T,contentHash:H}).strict().optional(),tools:p(Qc).max(200),capabilities:p(Dv).max(200),tasks:p(lb).min(1).max(1e6),graders:p(o_).min(1).max(1e3),verifierSetRelease:l({id:T,contentHash:H}).strict().optional(),metrics:ad.optional(),metadata:jn}).strict(),s_=r_.extend({contentHash:H}).strict();function WU(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const GU=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."),cb=rt("kind",[l({kind:b("profile")}).strict(),l({kind:b("workflow"),workflowId:T}).strict(),l({kind:b("skill"),skillPath:GU}).strict(),l({kind:b("agent_action"),actionId:T}).strict()]),JU=l({taskId:T,seed:i().min(1).max(500),fixtureId:T.nullable()}).strict(),dS=i().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),uS=v(["input","output","expectedOutput","evaluatorContext"]),ZU=p(l({graderId:T,fields:p(l({destination:uS,path:p(dS).min(1).max(20),source:uS,sourcePath:p(dS).max(20)}).strict()).max(100)}).strict()).max(100),YU=l({execution:V,originalEvidence:V,members:p(l({caseId:T,seed:i().min(1).max(500),fixtureId:H,sourceId:T,snapshotHash:H,boundaryRevisionHash:H}).strict()).min(1).max(500)}).strict(),QU=l({release:V.extend({revision:gt([d().int().positive(),i().min(1).max(200)])}).strict(),feedbackKey:i().min(1).max(240),configurationHash:H,output:v(["boolean","score","category"]),categories:p(i().min(1).max(120)).max(50)}).strict(),XU=l({schemaVersion:b("openpond.profileExternalDatasetBinding.v1"),dataset:V.extend({revision:d().int().positive()}).strict(),packageHash:H,profileId:T,target:cb,declaredProfileCatalogHash:H.nullable(),protectedProfileClosureHash:H,recordedOrigin:YU.optional(),gradingSource:l({pass:V,evidence:V}).strict().optional(),split:Ga,population:p(JU).min(1).max(1e4),evaluators:p(QU).min(1).max(100),fieldMappingsHash:H,fieldMappings:ZU,environmentHash:H,privateDatasetClosureHash:H,criterion:l({minimumPassRate:d().min(0).max(1),requireComplete:I()}).strict()}).strict().superRefine((e,t)=>{e.recordedOrigin&&(e.recordedOrigin.members.length!==e.population.length||e.recordedOrigin.members.some((n,a)=>n.caseId!==e.population[a].taskId||n.seed!==e.population[a].seed||n.fixtureId!==n.snapshotHash||e.population[a].fixtureId!==null))&&t.addIssue({code:"custom",message:"Recorded-to-rerun mapping must preserve every exact ordered cutoff and seed while admitting new target attempts."}),ct(e.fieldMappings)!==e.fieldMappingsHash&&t.addIssue({code:"custom",message:"Field mappings differ from their sealed hash."}),new Set(e.fieldMappings.map(n=>n.graderId)).size!==e.fieldMappings.length&&t.addIssue({code:"custom",message:"Field mappings must name each grader once."}),new Set(e.population.map(n=>JSON.stringify([n.taskId,n.seed,n.fixtureId]))).size!==e.population.length&&t.addIssue({code:"custom",message:"External Dataset population must be unique."}),new Set(e.evaluators.map(n=>n.feedbackKey)).size!==e.evaluators.length&&t.addIssue({code:"custom",message:"External Dataset feedback keys must be unique."});for(const n of e.evaluators)n.output==="category"!=n.categories.length>0&&t.addIssue({code:"custom",message:"Only category grading declares categories."})}),Wo=XU.safeExtend({contentHash:H}).strict();function vg(e){const t=Wo.parse(e),{contentHash:n,...a}=t;if(ct(a)!==n)throw new Error("External Dataset binding integrity failed.");return t}const l_=l({id:T,label:i().trim().min(1).max(240),description:i().max(4e3),target:cb,tasksetRelease:V,split:Ga,taskIds:p(T).min(1).max(1e5),seeds:p(i().trim().min(1).max(500)).min(1).max(100),criterion:l({minimumPassRate:d().min(0).max(1),requireComplete:I()}).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."})}),c_=l({id:T,label:i().trim().min(1).max(240),scope:v(["component","profile"]),definitionIds:p(T).min(1).max(1e3)}).strict();l({schemaVersion:b("openpond.profileEvaluations.v1"),definitions:p(l_).max(1e3),suites:p(c_).max(100)}).strict();const Zs=l({profileId:T,sourceRevision:i().trim().min(1).max(240),harnessRelease:V,catalogHash:H,definitionId:T,definitionHash:H,target:cb,environmentHash:H,externalDatasetBinding:Wo.optional(),sourceCandidate:iU.optional()}).strict();class ui extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}const ez=l({schemaVersion:b("openpond.modelJudgeTransportPolicy.v1"),responseFormat:b("judgment_json_schema"),reasoningEffort:v(["off","low","medium","high","xhigh","max"]),maximumOutputTokens:d().int().positive().max(1e6)}).strict(),tz=l({schemaVersion:b("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:H,responseHash:H,inputTokens:d().int().nonnegative().nullable(),outputTokens:d().int().nonnegative().nullable(),costUsd:d().finite().nonnegative().nullable(),transportPolicy:ez.optional(),effectiveRequestHash:H.optional(),finishReason:i().trim().min(1).max(200).nullable().optional(),reasoningTokens:d().int().nonnegative().nullable().optional()}).strict(),nz=l({schemaVersion:b("openpond.graderEvidence.v1"),graderId:T,graderVersion:i().trim().min(1).max(100),status:v(["scored","pending","unavailable","failed"]).optional(),score:d().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),failureClass:Kc.nullable(),feedback:p(i().max(2e4)).max(1e3),visibleEvidenceRefs:p(T).max(1e4),privilegedEvidenceRefs:p(T).max(1e4),modelJudgeReceipt:tz.optional()}).strict(),d_=nz.extend({contentHash:H}).strict(),az=l({score:d().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),failureClass:Kc.nullable(),gradingStatus:v(["scored","pending","unscorable","not_configured"])}).strict(),u_=az.extend({schemaVersion:b("openpond.taskGrade.v1"),taskHash:H,evidenceHash:H,graderSetHash:H,components:p(d_).max(1e3),contentHash:H}).strict(),Yd={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},od=i().regex(/^[a-z][a-z0-9_]{0,79}$/);function iz(e){return e.feedbackKey??`reward_${ct(e.id).slice(0,24)}`}const oz=gt([e_.omit(Yd),t_.omit(Yd),a_.omit(Yd),i_.omit(Yd),l({kind:b("learned_model"),modelVersion:V,inputContract:gn}).strict()]),m_=l({schemaVersion:b("openpond.rewardRelease.v1"),id:T,revision:d().int().positive(),name:i().trim().min(1).max(500),description:i().max(1e4),feedbackKey:od.optional(),implementation:oz,rawScore:l({minimum:d().finite(),maximum:d().finite()}).strict(),assets:p(gn).max(1e3),fixtureSetRef:gn.optional(),calibrationCheckRef:V.extend({revision:d().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>ct(n)===ct(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=rb(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),rd=m_.safeExtend({contentHash:H}).strict(),Yo=V.extend({revision:d().int().positive()}).strict(),rz=rt("kind",[l({kind:b("identity")}).strict(),l({kind:b("linear"),minimum:d().finite(),maximum:d().finite(),direction:v(["higher","lower"])}).strict()]),db=l({graderId:T,reward:Yo,role:v(["training","evaluation"]),normalization:rz,weight:d().nonnegative().max(1e3),required:I(),hardGate:I(),privileged:I(),fixtureRefs:p(V).max(1e3)}).strict(),sz=l({schemaVersion:b("openpond.rewardBinding.v1"),id:T,revision:d().int().positive(),name:i().trim().min(1).max(500).optional(),description:i().max(1e4).optional(),recipeRef:Yo.optional(),sources:p(db).max(100),aggregation:b("weighted_mean"),unscorable:b("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."})}),Lm=sz.safeExtend({contentHash:H}).strict(),p_=l({graderId:T,reward:Yo,role:v(["training","evaluation"]),status:v(["scored","pending","unavailable","failed"]),rawScore:d().finite().nullable(),normalizedScore:d().min(0).max(1).nullable(),passed:I().nullable(),evidenceHashes:p(H).max(1e3),graderEvidence:d_.optional(),message:i().max(2e4).nullable()}).strict(),lz=l({schemaVersion:b("openpond.rewardComposition.v1"),binding:Yo,taskHash:H,outputHash:H,results:p(p_).max(100),training:l({status:v(["scored","pending","unscorable","not_configured"]),score:d().min(0).max(1).nullable(),passed:I().nullable()}).strict(),evaluation:l({status:v(["scored","pending","unscorable","not_configured"]),score:d().min(0).max(1).nullable(),passed:I().nullable()}).strict()}).strict(),Cc=lz.extend({contentHash:H}).strict();function cz(e){Wa(e);const t=m_.parse(e);return rd.parse({...t,contentHash:ct(t)})}const sd=l({harnessRelease:V,agentSnapshot:V,sourcePackageHash:H}).strict(),lh=i().trim().min(1).max(200),ub=l({sessionId:lh,turnId:lh,source:sd,admissionHash:H,modelConfigurationHash:H,traceHash:H,runtimeEventRefs:p(lh).max(1e4),startedAt:pe,completedAt:pe,outputHash:H,partialOutputAvailable:I()}).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."})}),dz=l({schemaVersion:b("openpond.nativeHarnessExperimentAttempt.v1"),taskId:i().min(1).max(500),status:v(["completed","cancelled","timed_out","policy_failure"]),output:i().max(8388608).nullable(),error:i().max(2e3).nullable(),messages:p(ie()).max(4002),collected:I(),environmentCleanupComplete:b(!0),snapshot:sl(),native:ub}).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!==ct(e.output))&&t.addIssue({code:"custom",path:["native","outputHash"],message:"Native output differs from its retained evidence."})});dz.extend({contentHash:H}).strict();const f_=d().finite().nonnegative(),h_=rt("kind",[l({kind:b("model"),modelId:T,configurationHash:H}).strict(),l({kind:b("harness"),source:Zs,model:l({modelId:T,configurationHash:H}).strict()}).strict(),l({kind:b("agent"),source:sd,model:l({modelId:T,configurationHash:H}).strict()}).strict(),l({kind:b("fixture"),configurationHash:H}).strict()]),g_=l({release:V.extend({revision:gt([d().int().positive(),i().trim().min(1).max(200)])}).strict(),feedbackKey:od,configurationHash:H.optional(),output:v(["boolean","score","category"]),categories:p(i().trim().min(1).max(500)).max(100)}).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."})}),mb=l({caseId:T,seed:i().trim().min(1).max(500),fixtureId:T.nullable()}).strict();function Rc(e){const t=mb.parse(e);return JSON.stringify([t.caseId,t.seed,t.fixtureId])}function uz(e,t,n){return`human-projection-${ct({originalManifest:e,selectionHash:t,rulesHash:n}).slice(0,48)}`}const mz=l({schemaVersion:b("openpond.experimentManifest.v1"),id:T,name:i().trim().min(1).max(500),teamId:T,operationId:T,maximumCostUsd:f_.nullable(),dataset:V.extend({revision:d().int().positive()}).strict(),target:h_,execution:l({packageHash:H,runtimeTargetHash:H,metricPolicyHash:H,compatibility:l({protocol:b("openpond.evaluation-execution.v1"),targetKind:v(["model","agent","harness","fixture"])}).strict().optional()}).strict().optional(),lineage:l({definition:V.extend({revision:d().int().positive()}).strict().nullable(),execution:V,scoringPassId:T.nullable(),humanProjection:l({originalManifest:V,selectionHash:H,rulesHash:H}).strict().optional()}).strict().optional(),evaluators:p(g_).max(100),population:p(mb).min(1).max(1e4),createdAt:pe}).strict().superRefine((e,t)=>{if(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){const n=e.lineage.scoringPassId??e.lineage.execution.id,a=e.lineage.humanProjection;a?(a.originalManifest.id!==n||a.originalManifest.id.startsWith("human-projection-")||e.id!==uz(a.originalManifest,a.selectionHash,a.rulesHash))&&t.addIssue({code:"custom",path:["lineage","humanProjection"],message:"Human view must bind its original execution or scoring pass and deterministic selection identity."}):e.id!==n&&t.addIssue({code:"custom",path:["lineage"],message:"Experiment identity must match its execution or independent scoring pass."})}new Set(e.population.map(Rc)).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."})}),so=mz.extend({contentHash:H}).strict(),pz=l({feedbackKey:od,evaluator:g_.shape.release,status:v(["scored","unavailable","failed","pending"]),value:gt([I(),d().finite(),i().max(500)]).nullable(),passed:I().nullable().optional(),reasoning:i().max(2e4).nullable(),evidenceRefs:p(Ia).max(1e3)}).strict(),fz=l({inputTokens:d().int().nonnegative().nullable(),outputTokens:d().int().nonnegative().nullable(),totalTokens:d().int().nonnegative().nullable(),costUsd:f_.nullable(),latencyMs:d().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."})}),hz=l({identity:mb,status:v(["completed","failed","cancelled","unavailable"]),output:ie().nullable(),error:l({code:T,message:i().max(2e3)}).strict().nullable(),feedback:p(pz).max(100),usage:fz,traceRef:Ia.nullable(),startedAt:pe.nullable(),completedAt:pe.nullable()}).strict(),v_=l({schemaVersion:b("openpond.experimentResult.v1"),manifest:V,status:v(["completed","failed","cancelled"]),cases:p(hz).min(1).max(1e4),completedAt:pe}).strict(),lo=v_.extend({contentHash:H}).strict();function gz(e,t){so.parse(t),Z2(t,"Experiment manifest");const n=v_.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(Rc)),o=new Set,r=new Map(t.evaluators.map(s=>[s.feedbackKey,s]));for(const s of n.cases){const c=Rc(s.identity);if(!a.has(c)||o.has(c))throw new Error("Experiment result has an unexpected or repeated case.");o.add(c);const m=new Set;for(const u of s.feedback){const f=r.get(u.feedbackKey);if(!f||m.has(u.feedbackKey)||u.evaluator.id!==f.release.id||u.evaluator.contentHash!==f.release.contentHash||u.evaluator.revision!==f.release.revision)throw new Error("Experiment feedback differs from its pinned evaluator.");if(m.add(u.feedbackKey),u.status==="scored"){if(u.value===null||typeof u.value!=={boolean:"boolean",score:"number",category:"string"}[f.output]||f.output==="category"&&!f.categories.includes(u.value)||f.output==="score"&&(u.value<0||u.value>1))throw new Error("Experiment feedback value violates its output contract.")}else if(u.value!==null||u.passed!==null&&u.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 lo.parse({...n,contentHash:ct(n)})}function Rr(e){const t=so.parse(e.manifest),n=lo.parse(e.result),{contentHash:a,...o}=n;if(ct(o)!==a)throw new Error("Experiment result integrity failed.");return gz(o,t),{manifest:t,result:n}}function vz(e,t){for(const g of[e,t])Rr(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 S=g.execution;if(!S?.compatibility)return S??null;const{runtimeTargetHash:k,...C}=S;return C};if(ct(a(e.manifest))!==ct(a(t.manifest))&&n.push("different_execution_contract"),e.manifest.target.kind==="harness"&&t.manifest.target.kind==="harness"){const g=e.manifest.target.source,S=t.manifest.target.source;(g.profileId!==S.profileId||ct(g.target)!==ct(S.target))&&n.push("different_component");const k=e.manifest.execution?.compatibility&&t.manifest.execution?.compatibility&&e.manifest.execution.packageHash===t.manifest.execution.packageHash;g.environmentHash!==S.environmentHash&&!k&&n.push("different_environment"),(g.definitionId!==S.definitionId||g.definitionHash!==S.definitionHash)&&n.push("different_evaluation_definition")}const o=g=>[...g.evaluators].sort((S,k)=>S.feedbackKey.localeCompare(k.feedbackKey));ct(o(e.manifest))!==ct(o(t.manifest))&&n.push("different_evaluators");const r=new Map(e.result.cases.map(g=>[Rc(g.identity),g])),s=new Map(t.result.cases.map(g=>[Rc(g.identity),g])),c=[...new Set([...r.keys(),...s.keys()])].sort();(r.size!==s.size||c.some(g=>!r.has(g)||!s.has(g)))&&n.push("different_population");const m=n.length===0,u=c.map(g=>{const S=r.get(g)??null,k=s.get(g)??null,C=new Map(S?.feedback.map(j=>[j.feedbackKey,j])??[]),P=new Map(k?.feedback.map(j=>[j.feedbackKey,j])??[]);return{identity:(S??k).identity,baseline:S,candidate:k,feedback:e.manifest.evaluators.map(j=>{const R=C.get(j.feedbackKey),$=P.get(j.feedbackKey),O=m?!S||!k?"missing_case":S.status!=="completed"||k.status!=="completed"||S.error||k.error?"case_not_completed":!R||!$||R.status!=="scored"||$.status!=="scored"?"feedback_unavailable":j.output==="category"?"categorical_feedback":null:"incompatible_experiments",M=D=>typeof D?.value=="boolean"?Number(D.value):typeof D?.value=="number"?D.value:null,w=O?null:M(R),A=O?null:M($),E=D=>O?null:typeof D?.value=="boolean"?D.value:D?.passed??null;return{feedbackKey:j.feedbackKey,eligible:O===null,reason:O,baseline:w,candidate:A,delta:w===null||A===null?null:A-w,baselinePassed:E(R),candidatePassed:E($)}})}}),f=e.manifest.evaluators.map((g,S)=>{const k=u.map(M=>M.feedback[S]).filter(M=>M.eligible),C=M=>k.length?k.reduce((w,A)=>w+A[M],0)/k.length:null,P=C("baseline"),j=C("candidate"),R=M=>k.length&&k.every(w=>w[M]!==null)?k.reduce((w,A)=>w+Number(A[M]),0)/k.length:null,$=R("baselinePassed"),O=R("candidatePassed");return{feedbackKey:g.feedbackKey,eligibleCount:k.length,excludedCount:u.length-k.length,baseline:P,candidate:j,delta:P===null||j===null?null:j-P,baselinePassRate:$,candidatePassRate:O,passRateDelta:$===null||O===null?null:O-$}});return{comparable:m,reasons:n,cases:u,metrics:f}}const No=i().trim().min(1).max(200),nc=i().regex(/^[a-f0-9]{64}$/),bz=l({id:No,contentHash:nc}).strict(),qm=l({schemaVersion:b("openpond.trainingHandoffOrigin.v1"),teamId:No,projectId:No.nullable(),configurationId:No,source:l({executionId:No,passId:No.nullable(),manifestHash:nc,resultHash:nc}).strict(),dataset:l({id:No,revision:d().int().positive(),contentHash:nc}).strict(),target:h_,graders:p(l({feedbackKey:No,evaluator:bz,expectedCount:d().int().positive(),scoredCount:d().int().nonnegative(),score:d().finite().nullable()}).strict()).max(100),contentHash:nc}).strict(),yz=l({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:d().int().nonnegative().nullable(),outputTokens:d().int().nonnegative().nullable(),costUsd:d().finite().nonnegative().nullable(),effectiveRequestHash:i().regex(/^[a-f0-9]{64}$/).optional(),finishReason:i().trim().min(1).max(200).nullable().optional(),reasoningTokens:d().int().nonnegative().nullable().optional()}).strict(),b_=l({id:T,requestHash:H,reservedUsd:d().finite().positive(),status:v(["reserved","settled","not_dispatched"]),response:yz.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."})}),y_=l({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(),Nt=te(i(),Ko()),lt=Yo,Oo=i().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),Sz=l({schemaVersion:b("openpond.taskDefinition.v1"),id:T,revision:d().int().positive(),name:i().trim().min(1).max(500),description:i().max(1e4),instructions:i().trim().min(1).max(2e4),category:v(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:T,inputSchema:te(i(),ie()),outputSchema:te(i(),ie()),requiredOutputs:lb.shape.requiredOutputs,contextRequirements:p(i().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:lt,harness:V.nullable(),execution:r_.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=rb(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."})}),ld=Sz.safeExtend({contentHash:H}).strict(),xz=l({schemaVersion:b("openpond.taskSourceMapping.v1"),exampleId:Oo,attemptId:Oo,occurredAt:Oo,input:Oo,observedOutput:Oo.nullable(),expected:Oo.nullable(),evaluatorContext:Oo.nullable(),familyKey:Oo,split:Ga}).strict(),kz=l({modelId:T,packageHash:H,taskset:lt,batch:lt,rewardBinding:lt}).strict(),wz=l({schemaVersion:b("openpond.learningSource.v1"),id:T,revision:d().int().positive(),name:i().trim().min(1).max(500),kind:v(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:lt,enabled:I(),allowedSplits:p(Ga).min(1).max(4),mapping:xz.nullable(),adapterVersion:i().trim().min(1).max(200).nullable(),reviewOrigin:kz.optional(),capturedOrigin:l({receiptId:T,ownerUserId:T,modelId:T,packageHash:H,taskset:lt}).strict().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."})}),Um=wz.safeExtend({contentHash:H}).strict(),Iz=l({schemaVersion:b("openpond.taskExample.v1"),sourceId:T,idempotencyKey:T,taskDefinition:lt,exampleId:T,attemptId:T,occurredAt:pe,familyKey:T.nullable(),split:Ga,input:Nt,observedOutput:Nt.nullable(),expected:Nt.nullable(),evaluatorContext:Nt.nullable(),assets:p(gn).max(1e3),requiredOutputs:lb.shape.requiredOutputs,provenance:l({sourceRecordRef:i().max(2e3).nullable(),mappingHash:H.nullable()}).strict()}).strict(),_z=l({schemaVersion:b("openpond.taskEvidence.v1"),id:T,revision:d().int().positive(),source:lt,submission:Iz,supersedes:lt.nullable(),correctionFeedbackId:T.nullable(),receivedAt:pe}).strict(),zm=_z.extend({contentHash:H}).strict(),Cz=l({schemaVersion:b("openpond.taskRating.v1"),criteria:i().trim().min(1).max(2e4),scale:l({minimum:d().finite(),maximum:d().finite()}).strict(),score:d().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."})}),Rz=l({schemaVersion:b("openpond.taskFeedback.v1"),sourceId:T,idempotencyKey:T,exampleId:T,attemptId:T,expectedEvidenceHash:H.nullable(),occurredAt:pe,kind:v(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Nt,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=Cz.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),S_=l({schemaVersion:b("openpond.taskFeedbackRecord.v1"),id:T,submission:Rz,status:v(["pending_example","pending_review","applied","superseded","rejected"]),evidence:lt.nullable(),createdAt:pe,revision:d().int().positive(),submittedBy:l({id:T,role:v(["editor","reviewer","source"]),sourceId:T.nullable()}).strict().nullable().default(null),review:l({actorId:T,decision:lt.nullable(),note:i().max(2e4),resolvedAt:pe}).strict().nullable().default(null)}).strict(),Pz=l({schemaVersion:b("openpond.taskAdmissionDecision.v1"),id:T,revision:d().int().positive(),evidence:lt,supersedes:lt.nullable(),actor:l({kind:v(["human","qualified_policy"]),id:T,policy:lt.nullable()}).strict(),evidenceValidity:v(["valid","invalid","pending"]),taskAdmissibility:v(["approved","rejected","pending"]),observedQuality:v(["passed","failed","unscored","unavailable"]),targetApproval:v(["approved","rejected","pending","not_required"]),approvedTarget:Nt.nullable(),grade:Cc.nullable(),targetGrade:Cc.nullable(),note:i().max(2e4),decidedAt:pe}).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."})}),pb=Pz.safeExtend({contentHash:H}).strict(),Az=l({schemaVersion:b("openpond.taskBatch.v1"),id:T,revision:b(1),taskDefinition:lt,rewardBinding:lt,purpose:v(["supervised_training","reward_training","evaluation"]),examples:p(l({evidence:lt,decision:lt,familyKey:T,inputHash:H,split:Ga}).strict()).min(1).max(1e4),sealedAt:pe,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)}}),fb=Az.safeExtend({contentHash:H}).strict(),Tz=l({origin:qm.optional(),schemaVersion:b("openpond.learningPolicy.v1"),id:T,revision:d().int().positive(),modelProjectId:T,executionOwner:v(["local","hosted"]),enabled:I(),sources:p(lt).min(1).max(100),taskDefinition:lt,rewardBinding:lt,admission:l({mode:v(["human","qualified_automatic"]),qualification:V.nullable(),minimumApprovedExamples:d().int().positive().max(1e5)}).strict(),trigger:rt("kind",[l({kind:b("manual")}).strict(),l({kind:b("approved_count")}).strict(),l({kind:b("schedule"),intervalSeconds:d().int().min(60).max(31536e3)}).strict(),y_.extend({kind:b("nightly")}).strict(),l({kind:b("upstream_accepted"),modelProjectId:T}).strict()]),trainingParent:V,teacher:V.nullable(),training:l({method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:V,retentionEvaluation:V,replayBatches:p(V).max(100)}).strict(),limits:l({maxIterationSpendUsd:d().positive().max(1e5),maxDailySpendUsd:d().positive().max(1e6),cooldownSeconds:d().int().nonnegative().max(31536e3),maxRetries:d().int().nonnegative().max(10),maxBatchExamples:d().int().positive().max(1e4),maxBacklogExamples:d().int().positive().max(1e6)}).strict(),automation:l({collect:I(),train:I(),accept:I(),serve:I()}).strict(),acceptance:l({minimumScore:d().min(0).max(1),maximumRetentionRegression:d().min(0).max(1),requireImprovement:I(),rollbackVersion:V.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."})}),x_=Tz.safeExtend({contentHash:H}).strict(),hb=l({iterationId:T,iterationRevision:d().int().positive(),candidate:V,decision:lt,decidedAt:pe}).strict(),Ez=v(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),k_=l({schemaVersion:b("openpond.learningIteration.v1"),id:T,revision:d().int().positive(),policy:lt,status:Ez,triggerIdentity:T,batch:lt.nullable(),sourceWatermarks:te(T,d().int().nonnegative()),trainingParent:V,trainingParentSelection:hb.nullable().optional(),teacher:V.nullable(),upstreamEvent:V.nullable(),trainingJob:V.nullable(),evaluationJob:V.nullable(),candidateVersion:V.nullable(),candidateDecision:lt.nullable().default(null),candidateDecisionAt:pe.nullable().optional(),dispatchId:T,retryCount:d().int().nonnegative(),spendUsd:d().nonnegative(),failure:l({code:T,message:i().max(2e4)}).strict().nullable(),createdAt:pe,updatedAt:pe}).strict(),jz=l({schemaVersion:b("openpond.taskGradeRun.v1"),id:T,revision:d().int().positive(),evidence:lt,binding:lt,target:v(["observed","proposed_target"]),output:Nt,status:v(["queued","running","completed","failed","cancelling","cancelled"]),composition:Cc.nullable(),leaseOwner:T.nullable(),leaseExpiresAt:pe.nullable(),attemptCount:d().int().nonnegative(),timeoutMs:d().int().min(100).max(3e5),maximumSpendUsd:d().nonnegative().max(1e3),judgeCalls:p(b_).max(1e4).optional(),requestedBy:T.optional(),failure:i().max(2e4).nullable(),createdAt:pe,updatedAt:pe}).strict();gt([ld,rd,Lm,Um,zm,S_,pb,fb,x_,k_,jz]);function Mz(e){return lt.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function Sae(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function xae(e){return Wa(e,16777216),{...e,contentHash:ct(e)}}function kae(e){const{contentHash:t,...n}=e;if(Wa(n,16777216),ct(n)!==t)throw new ui("learning_content_hash_mismatch",422)}const w_=l({schemaVersion:b("openpond.learningTextAsset.v1"),id:T,revision:b(1),asset:gn,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!==vv(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),Bm=w_.safeExtend({contentHash:H}).strict();function Qd(e){Wa(e);const{text:t,...n}=e,a=vv(t),o=`asset-${a}-${ct(n).slice(0,16)}`,r=w_.parse({schemaVersion:"openpond.learningTextAsset.v1",id:o,revision:1,asset:{...n,id:o,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return Bm.parse({...r,contentHash:ct(r)})}function mS(e,t){const{contentHash:n,...a}=Bm.parse(e);if(ct(a)!==n||ct(a.asset)!==ct(t))throw new ui("learning_asset_reference_mismatch",409);return a.text}const Oz=rt("kind",[l({kind:b("manual"),identity:T}).strict(),l({kind:b("schedule"),scheduledAt:pe}).strict(),l({kind:b("approved_count"),checkedAt:pe}).strict()]),$z=l({schemaVersion:b("openpond.learningChain.v1"),id:T,revision:d().int().positive(),modelProjectId:T,activeIterationId:T.nullable(),acceptedParent:hb.nullable().optional(),latestIterationId:T,lastReservedAt:pe.nullable(),updatedAt:pe}).strict(),I_=l({eligible:d().int().nonnegative(),awaitingReview:d().int().nonnegative(),excluded:d().int().nonnegative(),consumed:d().int().nonnegative()}).strict(),wae=l({schemaVersion:b("openpond.learningConsumption.v1"),id:T,revision:b(1),chainId:T,iterationId:T,evidence:lt,decision:lt,reservedAt:pe}).strict(),Iae=l({schemaVersion:b("openpond.learningIterationReservation.v1"),id:T,revision:d().int().positive(),chainId:T,iterationId:T,policy:lt,trigger:Oz,requestHash:H,outcome:v(["reserved","waiting_for_data","waiting_for_review"]),counts:I_,budget:l({maximumSpendUsd:d().nonnegative(),reservedSpendUsd:d().nonnegative(),settledSpendUsd:d().nonnegative(),settledAt:pe.nullable()}).strict(),createdAt:pe,updatedAt:pe}).strict(),__=l({id:T,name:i().max(500),input:i(),output:i(),expectedOutput:i(),evaluatorContext:i(),artifactRefs:p(i().max(500)).max(100),runtimeEventRefs:p(i().max(500)).max(100),infrastructureError:i().max(2e4),expectedStatus:v(["scored","pending","unavailable","failed"]),minimumScore:i(),maximumScore:i(),expectedPassed:v(["true","false","any"]),sourceLabel:l({evidence:lt,feedback:l({id:T,revision:d().int().positive()}).strict()}).strict().optional()}).strict(),C_=l({name:i().max(500),description:i().max(1e4),feedbackKey:od.optional(),kind:v(["custom_verifier","state","content","schema","artifact","runtime_event","model_judge","learned_model","human"]),fields:i(),outputField:i(),expectedField:i(),expectedValue:i(),schema:i(),reference:i(),events:i(),code:i(),exportName:i(),timeout:i(),verifierRuntime:v(["isolated_javascript","sandbox_process"]).optional(),rubric:i(),providerId:i(),modelId:i(),modelRevision:i(),temperature:i(),reviewerRole:i(),humanForm:i().max(131072).optional(),learnedId:i(),learnedHash:i(),inputContract:i(),minimum:i(),maximum:i(),fixtures:p(__).max(50).optional()}).strict(),Nz=l({name:i().max(500),description:i().max(1e4),instructions:i().max(2e4),input:i(),output:i(),familyNamespace:i(),sources:p(db).max(100),recipeRef:Yo.optional()}).strict(),Dz=l({name:i().max(500),description:i().max(1e4),sources:p(db).max(100)}).strict(),Hz=v(["definition","reward","binding"]),ch=l({id:T,targetId:T,baseRelease:lt.nullable(),editorVersion:b("openpond.modelsEditor.v1")}),dh=rt("targetKind",[ch.extend({targetKind:b("definition"),fields:Nz}).strict(),ch.extend({targetKind:b("reward"),fields:C_}).strict(),ch.extend({targetKind:b("binding"),fields:Dz}).strict()]),uh={schemaVersion:b("openpond.authoringDraft.v1"),revision:d().int().positive(),status:v(["draft","archived","published"]),publishedRelease:lt.nullable(),createdAt:pe,updatedAt:pe},mh=rt("targetKind",[dh.options[0].extend(uh).strict(),dh.options[1].extend(uh).strict(),dh.options[2].extend(uh).strict()]),_ae=rt("targetKind",[mh.options[0].extend({contentHash:H}).strict(),mh.options[1].extend({contentHash:H}).strict(),mh.options[2].extend({contentHash:H}).strict()]),Cae=l({draft:lt,targetKind:Hz,release:lt}).strict(),oi={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},R_=v(["json","jsonl","csv","hermes","openclaw"]),Lz=l({path:i().min(1).max(500),text:i()}).strict(),gb=l({id:i().min(1).max(200),familyKey:i().min(1).max(200),split:Ga,kind:v(["task","attempt"]),input:Nt,observedOutput:Nt.nullable(),expected:Nt.nullable(),sourceId:i().min(1).max(2e3),sourceHash:i().length(64),occurredAt:i().datetime().nullable(),metadata:Nt,warnings:p(i().max(2e3)).max(100),needsContext:I()}).strict(),P_=l({schemaVersion:b("openpond.taskIntakePreview.v1"),format:R_,contentHash:i().length(64),records:p(gb).max(oi.records),issues:p(l({file:i(),row:d().int().positive().nullable(),message:i()}).strict()).max(1e3)}).strict();function Yu(e,t){return`${e}-${ct(t)}`}function A_(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}const qz=`export function verify({ output, expectedOutput }) {
|
|
175
|
+
if (!expectedOutput || !Object.hasOwn(expectedOutput, "answer")) {
|
|
176
|
+
throw new Error("An expected answer is required.");
|
|
177
|
+
}
|
|
178
|
+
const passed = output.answer === expectedOutput.answer;
|
|
179
|
+
return { score: passed ? 1 : 0, passed, feedback: passed ? "Answer matched" : "Answer differed" };
|
|
180
|
+
}`;function Rae(e){Wa(e,262144);const t=C_.parse(e.fields),n=e.base?rd.parse(e.base):null;if(n&&n.id!==e.id)throw new ui("reward_authoring_base_mismatch",422);const a=t.fixtures?.length?Qd({text:JSON.stringify(t.fixtures),path:"reward-fixtures.json",mediaType:"application/json",visibility:"verifier"}):null;let o=null,r,s;if(t.kind==="custom_verifier")o=Qd({text:t.code,path:"verifier.mjs",mediaType:"application/javascript",visibility:"verifier"}),r={kind:t.kind,verifierRef:o.asset,exportName:t.exportName,timeoutMs:Ps(t.timeout,"Time limit"),networkPolicy:"none",...t.verifierRuntime??(n?.implementation.kind==="custom_verifier"?n.implementation.runtime:void 0)?{runtime:t.verifierRuntime??(n?.implementation.kind==="custom_verifier"?n.implementation.runtime:void 0)}:{}};else if(t.kind==="model_judge"||t.kind==="human"){if(!t.rubric.trim())throw new ui("reward_rubric_required",422,"Write the rubric before checking or publishing this Reward.");if(o=Qd({text:t.rubric,path:"rubric.md",mediaType:"text/markdown",visibility:"verifier"}),t.kind==="human")r={kind:t.kind,rubricRef:o.asset,reviewerRole:t.reviewerRole,form:id.parse(JSON.parse(t.humanForm||JSON.stringify({schemaVersion:"openpond.humanForm.v1",mode:"individual",instructions:t.rubric,criteria:[{id:"quality",label:"Quality",instructions:t.rubric,required:!0,allowAbstain:!0,kind:"score",minimum:0,maximum:1,step:.1}]})))};else{const u={providerId:t.providerId,modelId:t.modelId,revision:t.modelRevision.trim()||null},f=Ps(t.temperature,"Temperature"),g=n?.implementation,S=g?.kind==="model_judge"&&g.rubricRef.contentHash===o.asset.contentHash&&g.model?.providerId===u.providerId&&g.model?.modelId===u.modelId&&g.model?.revision===u.revision&&(g.temperature??0)===f&&n?.fixtureSetRef?.contentHash===a?.asset.contentHash;r={kind:t.kind,rubricRef:o.asset,model:u,temperature:f,calibrationStatus:S?g.calibrationStatus:"pending"},S&&(s=n?.calibrationCheckRef)}}else t.kind==="learned_model"?(Rs(t.inputContract,"Model input contract"),o=Qd({text:t.inputContract,path:"input-contract.json",mediaType:"application/json",visibility:"verifier"}),r={kind:t.kind,modelVersion:{id:t.learnedId,contentHash:t.learnedHash},inputContract:o.asset}):t.kind==="state"?r={kind:t.kind,config:{fields:fS(t.fields)}}:t.kind==="content"?r={kind:t.kind,config:{outputField:t.outputField,expectedField:t.expectedField,...t.expectedValue?{expectedValue:t.expectedValue}:{}}}:t.kind==="schema"?r={kind:t.kind,config:{jsonSchema:Rs(t.schema,"Output schema")}}:t.kind==="artifact"?r={kind:t.kind,config:{refIncludes:t.reference}}:r={kind:t.kind,config:{requiredEvents:fS(t.events)}};const c=[...o?[o]:[],...a?[a]:[]];return{reward:cz({schemaVersion:"openpond.rewardRelease.v1",id:e.id,revision:(n?.revision??0)+1,name:t.name,description:t.description,feedbackKey:t.feedbackKey??iz({id:e.id}),implementation:r,rawScore:t.kind==="learned_model"?{minimum:Ps(t.minimum,"Minimum score"),maximum:Ps(t.maximum,"Maximum score")}:{minimum:0,maximum:1},assets:c.map(u=>u.asset),...a?{fixtureSetRef:a.asset}:{},...s?{calibrationCheckRef:s}:{}}),assets:c}}function Pae(e,t,n=null){const a=e?.implementation,o=a&&"verifierRef"in a?a.verifierRef:a&&"rubricRef"in a?a.rubricRef:a&&"inputContract"in a?a.inputContract:null;if(o&&!t)throw new ui("reward_source_required",422);const r=o&&t?mS(t,o):"";if(e?.fixtureSetRef&&!n)throw new ui("reward_fixtures_required",422);const s=e?.fixtureSetRef&&n?__.array().max(50).parse(JSON.parse(mS(n,e.fixtureSetRef))):[],c=a&&"config"in a?a.config:{};return{name:e?.name??"",description:e?.description??"",...e?.feedbackKey?{feedbackKey:e.feedbackKey}:{},kind:a?.kind??"state",fields:pS(c.fields).join(", ")||"answer",outputField:Xd(c.outputField)||"text",expectedField:Xd(c.expectedField)||"text",expectedValue:Xd(c.expectedValue),schema:JSON.stringify(c.jsonSchema??{type:"object",properties:{answer:{type:"string"}},required:["answer"]},null,2),reference:Xd(c.refIncludes),events:pS(c.requiredEvents).join(", "),code:a?.kind==="custom_verifier"?r:qz,verifierRuntime:a?.kind==="custom_verifier"?a.runtime??"isolated_javascript":"isolated_javascript",exportName:a?.kind==="custom_verifier"?a.exportName??"verify":"verify",timeout:String(a?.kind==="custom_verifier"?a.timeoutMs:5e3),rubric:a?.kind==="model_judge"||a?.kind==="human"?r:"",providerId:a?.kind==="model_judge"?a.model?.providerId??"":"",modelId:a?.kind==="model_judge"?a.model?.modelId??"":"",modelRevision:a?.kind==="model_judge"?a.model?.revision??"":"",temperature:String(a?.kind==="model_judge"?a.temperature??0:0),reviewerRole:a?.kind==="human"?a.reviewerRole:"Subject matter reviewer",humanForm:a?.kind==="human"&&a.form?JSON.stringify(a.form,null,2):"",learnedId:a?.kind==="learned_model"?a.modelVersion.id:"",learnedHash:a?.kind==="learned_model"?a.modelVersion.contentHash:"",inputContract:a?.kind==="learned_model"?r:"{}",minimum:String(e?.rawScore.minimum??0),maximum:String(e?.rawScore.maximum??1),...s.length?{fixtures:s}:{}}}function Rs(e,t){try{const n=JSON.parse(e);return Wa(n,131072),Nt.parse(n)}catch{throw new ui("reward_authoring_json_invalid",422,`${t} must be a JSON object.`)}}function Ps(e,t){const n=Number(e);if(!e.trim()||!Number.isFinite(n))throw new ui("reward_authoring_number_invalid",422,`${t} must be a finite number.`);return n}function Xd(e){return typeof e=="string"?e:""}function pS(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function fS(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}const T_=l({id:T,name:i().trim().min(1).max(500),input:Nt,output:Nt,expectedOutput:Nt.nullable(),evaluatorContext:Nt.nullable(),artifactRefs:p(T).max(100),runtimeEventRefs:p(T).max(100),infrastructureError:i().max(2e4).nullable(),expected:rt("status",[l({status:b("scored"),minimum:d().finite(),maximum:d().finite(),passed:I().nullable()}).strict(),l({status:v(["pending","unavailable","failed"])}).strict()])}).strict().superRefine((e,t)=>{e.expected.status==="scored"&&e.expected.minimum>e.expected.maximum&&t.addIssue({code:"custom",path:["expected"],message:"Expected score minimum must not exceed maximum."})}),Uz=l({id:T,packageVersion:i().min(1).max(100),engine:i().min(1).max(200)}).strict(),zz=l({fixture:l({id:T,contentHash:H}).strict(),result:p_,matchesExpectation:I()}).strict(),Aae=l({schemaVersion:b("openpond.rewardCheckRun.v1"),id:T,revision:d().int().positive(),draft:lt,reward:lt,snapshotHash:H,fixtureRefs:p(l({id:T,contentHash:H}).strict()).min(1).max(50),status:v(["queued","running","completed","failed","cancelling","cancelled"]),runtime:Uz.nullable(),results:p(zz).max(50),matchesExpectations:I().nullable(),failure:i().max(2e4).nullable(),timeoutMs:d().int().min(100).max(3e5),maximumSpendUsd:d().nonnegative().max(1e3),judgeCalls:p(b_).max(1e3).optional(),requestedBy:T.optional(),leaseOwner:T.nullable(),leaseExpiresAt:pe.nullable(),attemptCount:d().int().nonnegative(),createdAt:pe,updatedAt:pe}).strict();function Tae(e){if(!e.length||e.length>50)throw new ui("reward_check_fixtures_required",422,"Add between one and 50 fixtures before checking this Reward.");if(new Set(e.map(t=>t.id)).size!==e.length)throw new ui("reward_fixture_id_duplicate",422);return e.map(t=>T_.parse({id:t.id,name:t.name,input:Rs(t.input,`${t.name}: input`),output:Rs(t.output,`${t.name}: output`),expectedOutput:t.expectedOutput.trim()?Rs(t.expectedOutput,`${t.name}: expected answer`):null,evaluatorContext:t.evaluatorContext.trim()?Rs(t.evaluatorContext,`${t.name}: evaluator context`):null,artifactRefs:t.artifactRefs.map(n=>n.trim()).filter(Boolean),runtimeEventRefs:t.runtimeEventRefs.map(n=>n.trim()).filter(Boolean),infrastructureError:t.infrastructureError||null,expected:t.expectedStatus==="scored"?{status:t.expectedStatus,minimum:Ps(t.minimumScore,`${t.name}: minimum score`),maximum:Ps(t.maximumScore,`${t.name}: maximum score`),passed:t.expectedPassed==="any"?null:t.expectedPassed==="true"}:{status:t.expectedStatus}}))}const Bz=l({policy:lt,modelProjectId:T,inspectedAt:pe,chain:$z.nullable(),trainingParent:l({reference:V,selection:hb.nullable()}).strict().nullable().default(null),counts:I_.nullable(),minimumApprovedExamples:d().int().positive(),canReserve:I(),blockers:p(l({code:i().min(1).max(200),message:i().min(1).max(2e4)}).strict()).max(20),cooldownUntil:pe.nullable(),budget:l({reservedSpendUsd:d().nonnegative(),settledSpendUsd:d().nonnegative(),committedSpendUsd:d().nonnegative(),maximumIterationSpendUsd:d().nonnegative(),maximumDailySpendUsd:d().nonnegative()}).strict()}).strict();function Fz(e){const t=[];let n=[],a="",o=!1,r=!1;const s=()=>{n.push(a),a="",r=!1},c=()=>{if(s(),n.some(f=>f.length)&&t.push(n),n=[],t.length>oi.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let f=0;f<e.length;f++){const g=e[f];if(o)g==='"'&&e[f+1]==='"'?(a+='"',f++):g==='"'?(o=!1,r=!0):a+=g;else if(g===",")s();else if(g===`
|
|
181
|
+
`||g==="\r")g==="\r"&&e[f+1]===`
|
|
182
|
+
`&&f++,c();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)&&c();const m=t.shift()?.map(f=>f.trim().replace(/^\uFEFF/u,""));if(!m?.includes("instruction"))throw new Error("CSV requires an instruction column.");const u=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(m.some(f=>!u.has(f))||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((f,g)=>{if(f.length!==m.length)throw new Error(`CSV record ${g+2} has a different number of columns from its header.`);return Object.fromEntries(m.map((S,k)=>[S,f[k]]).filter(([,S])=>S!==""))})}function Eae(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 E_(e){return e.startsWith("\uFEFF")?e.slice(1):e}const j_=l({role:i().min(1),content:Ko().nullable().optional()}).catchall(Ko()),Vz=l({id:i().min(1),messages:p(j_).min(1).max(oi.messages),lineage_session_ids:p(i()).optional(),parent_session_id:i().nullable().optional()}).catchall(Ko());function Kz(e){const t=Vz.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:o,...r}=t;return M_("hermes",t.id,n,t.messages,{sourceHash:ct(e),metadata:{session:r},warnings:["Imported session context and tools need review before this can become an executable task."]})}const Wz=l({traceSchema:b("openclaw-trajectory"),schemaVersion:b(1),traceId:i().min(1),sessionId:i().min(1),leafId:i().nullable(),eventCount:d().int().nonnegative(),warnings:p(Nt).optional()}).catchall(Ko()),Gz=l({traceSchema:b("openclaw-trajectory"),schemaVersion:b(1),traceId:i(),sessionId:i(),seq:d().int().nonnegative(),type:i(),ts:i()}).catchall(Ko()),Jz=l({header:Nt.nullable(),leafId:i().nullable(),entries:p(l({id:i().min(1),type:i().min(1),parentId:i().nullable().optional(),message:j_.optional()}).catchall(Ko())).max(oi.messages)}).strict();function Zz(e){const t=c=>{const m=e.find(u=>u.path===c);if(!m)throw new Error(`OpenClaw bundle is missing ${c}.`);return E_(m.text)},n=Wz.parse(JSON.parse(t("manifest.json"))),a=Jz.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(c=>c.trim()).map(c=>Gz.parse(JSON.parse(c)));if(o.length!==n.eventCount||o.some(c=>c.traceId!==n.traceId||c.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[c,m]of a.entries.entries()){if(r.has(m.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(c&&m.parentId!==a.entries[c-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(c=>c.type==="message"&&c.message).map(c=>({...c.message,entryId:c.id,timestamp:typeof c.timestamp=="string"?c.timestamp:typeof c.message.timestamp=="number"?new Date(c.message.timestamp).toISOString():null}));return M_("openclaw",n.sessionId,n.sessionId,s,{sourceHash:ct(e),metadata:{manifest:n,sourceFiles:e.map(c=>c.path)},warnings:["Imported trajectory context and tools need review before this can become an executable task.",...(n.warnings??[]).map(c=>typeof c.message=="string"?c.message.slice(0,2e3):"The source exporter reported incomplete context.")]})}function M_(e,t,n,a,o){const r=a.flatMap((c,m)=>c.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((c,m)=>{const u=r[m+1]??a.length,f=a.slice(c+1,u),g=f.filter(P=>P.role==="assistant").at(-1),S=a[c],k=S.entryId??S.message_id??S.id??ct({start:c,request:S}),C={id:Yu(e,[t,k]),familyKey:Yu(e,n),split:"train",kind:"attempt",input:{request:S.content??null,messages:a.slice(0,c+1)},observedOutput:g?{response:g.content??null,messages:f}:null,expected:null,sourceId:`${e}:${t}:${String(k)}`,sourceHash:o.sourceHash,occurredAt:A_(g?.timestamp??S.timestamp),metadata:o.metadata,warnings:[...o.warnings,...g?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Wa(C),s+=new TextEncoder().encode(JSON.stringify(C)).length,s>oi.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return gb.parse(C)})}const Yz=l({instruction:i().trim().min(1).max(1e5),context:gt([i(),Nt]).optional(),reference:gt([i(),Nt]).optional(),labels:gt([i(),p(i()),Nt]).optional(),id:i().min(1).max(200).optional(),familyKey:i().min(1).max(200).optional(),split:Ga.optional()}).strict(),Qz=l({input:Nt,observedOutput:Nt.nullable().optional(),expectedOutput:Nt.nullable().optional(),id:i().min(1).max(200).optional(),familyKey:i().min(1).max(200).optional(),split:Ga.optional(),occurredAt:i().datetime().optional(),labels:Nt.optional()}).strict();function Xz(e){const t=R_.parse(e.format),n=p(Lz).min(1).max(oi.files).parse(e.files);if(n.reduce((u,f)=>u+new TextEncoder().encode(f.text).length,0)>oi.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(u=>u.path.startsWith("/")||u.path.includes("\\")||u.path.split("/").some(f=>!f||f==="."||f===".."))||new Set(n.map(u=>u.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 c=0;function m(u,f,g){try{const S=g();if(a.length+S.length>oi.records)throw new Error("Import exceeds the 1,000-record limit.");const k=new Map(r),C=new Map(s);let P=0;for(const j of S){Wa(j);const R=ct(j),$=k.get(j.id);if($&&$!==R)throw new Error("The same record identity has different content in this upload.");$||(P+=new TextEncoder().encode(JSON.stringify(j)).length),k.set(j.id,R);for(const O of[`family:${j.familyKey}`,`input:${ct(j.input)}`]){if(C.has(O)&&C.get(O)!==j.split)throw new Error("The same task family or request occurs in different splits.");C.set(O,j.split)}}if(c+P>oi.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const j of S)r.has(j.id)||a.push(j),r.set(j.id,ct(j));for(const[j,R]of C)s.set(j,R);c+=P}catch(S){o.push({file:u,row:f,message:S instanceof qO?`Unsupported record fields or values (${S.issues.slice(0,3).map(k=>k.path.join(".")||"record").join(", ")}).`:S instanceof SyntaxError?"Invalid JSON.":S instanceof Error?S.message:"Invalid import record."})}}if(t==="openclaw")m("manifest.json",null,()=>Zz(n));else for(const u of n){const f=E_(u.text);if(t==="jsonl"||t==="hermes"){for(const[g,S]of f.split(/\r?\n/u).entries())if(S.trim()){if(o.length>=oi.records)break;m(u.path,g+1,()=>t==="hermes"?Kz(JSON.parse(S)):[hS(JSON.parse(S))])}}else{let g;try{const S=t==="csv"?Fz(f):JSON.parse(f);g=Array.isArray(S)?S:[S]}catch(S){m(u.path,null,()=>{throw S});continue}if(g.length>oi.records){m(u.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}g.forEach((S,k)=>m(u.path,k+(t==="csv"?2:1),()=>[hS(S)]))}}return P_.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:ct({format:t,files:n}),records:a,issues:o.slice(0,1e3)})}function hS(e){const t=gt([Yz,Qz]).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??Yu("family",a),c=t.id??Yu("task",{input:a,expected:o,observedOutput:r});return gb.parse({id:c,familyKey:s,split:t.split??"train",kind:r?"attempt":"task",input:a,expected:o,observedOutput:r,sourceId:c,sourceHash:ct(e),occurredAt:n?null:A_(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}const Pc=i().trim().min(1).max(240),Lo=i().regex(/^[a-f0-9]{64}$/),e4=l({id:Pc,name:i().trim().min(1).max(200),required:I(),role:v(["quality","retention","diagnostic"]).optional(),unit:i().trim().min(1).max(80).optional(),baselineReuse:l({maximumAgeSeconds:d().int().positive().max(31536e3),qualification:V}).strict().optional(),dataset:V,evaluator:V,executionHash:Lo,populationHash:Lo,metric:Pc,direction:v(["higher","lower"]),minimumCoverage:d().positive().max(1),threshold:d().finite(),maximumRegression:d().finite().nonnegative(),maximumSpendUsd:d().finite().positive()}).strict().superRefine((e,t)=>{e.role==="diagnostic"&&e.required&&t.addIssue({code:"custom",message:"Diagnostic checks cannot be required acceptance gates."})}),O_=l({schemaVersion:b("openpond.acceptancePlan.v1"),id:Pc,revision:d().int().positive(),checks:p(e4).min(1).max(100),maximumSpendUsd:d().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."})}),$_=O_.safeExtend({contentHash:Lo});function jae(e){const t=O_.parse(e);return{...t,contentHash:ct(t)}}const t4=l({runId:Pc,artifact:V,checkHash:Lo,populationHash:Lo,scoredPopulationHash:Lo,executionHash:Lo,evaluator:V,metric:Pc,expectedCount:d().int().positive(),scoredCount:d().int().nonnegative(),score:d().finite().nullable(),status:v(["pending","running","completed","failed","cancelled"]),evidenceHash:Lo}).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."})}),qo=i().trim().min(1).max(240),vb=i().regex(/^[a-f0-9]{64}$/),Qu=nn(),gS=d().finite().nonnegative(),n4=new Set(["completed","failed","cancelled","budget_exhausted"]),a4=l({schemaVersion:b("openpond.acceptanceGroupManifest.v1"),id:qo,teamId:qo,trainingJob:V,baseline:V,candidate:V,plan:$_,maximumParallelAttempts:d().int().min(1).max(8),createdAt:Qu}).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."})}),i4=a4.safeExtend({contentHash:vb}),o4=l({id:qo,checkId:qo,subject:v(["baseline","candidate"]),ordinal:d().int().positive(),dispatchId:qo,state:v(["queued","dispatching","running","grading","cleaning","completed","failed","cancelled","budget_exhausted"]),artifact:V,checkHash:vb,measurement:t4.nullable(),executionReceipt:V.nullable(),reusedFrom:l({group:V,attemptId:qo}).strict().nullable(),spendUsd:gS,reservedUsd:gS,cleanupComplete:I(),accountingComplete:I(),failureCode:qo.nullable(),createdAt:Qu,updatedAt:Qu}).strict().superRefine((e,t)=>{Date.parse(e.updatedAt)<Date.parse(e.createdAt)&&t.addIssue({code:"custom",message:"Attempt timestamps are reversed."}),n4.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."})}),r4=l({schemaVersion:b("openpond.acceptanceGroupSnapshot.v1"),manifest:i4,revision:d().int().positive(),state:v(["queued","running","blocked","cancelling","cleaning","completed","failed","cancelled","budget_exhausted"]),attempts:p(o4).max(2e3),failureCode:qo.nullable(),updatedAt:Qu}).strict(),s4=r4.extend({contentHash:vb});var Ar=lt.shape.id,Ac=i().regex(/^[a-f0-9]{64}$/),l4=l({scopeId:Ar,modelId:Ar}).strict(),c4=l({schemaVersion:b("openpond.modelTasksetAuthoring.v1"),owner:l4,root:lt,parent:lt}).strict(),Mae=l({schemaVersion:b("openpond.modelTasksetDraftRequest.v1"),operationId:Ar,modelId:Ar,expectedModelRevision:d().int().positive(),sourcePackageHash:Ac}).strict(),d4=l({schemaVersion:b("openpond.modelTasksetDraftPreparation.v1"),draftId:Ar,requestHash:Ac,sourcePackageHash:Ac,sourceTasksetRef:lt,tasksetId:Ar,tasksetRevision:d().int().positive(),lineage:c4,authoringGraph:b("bound").optional()}).strict(),cd=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."),N_=l({path:cd,sizeBytes:d().int().nonnegative(),writable:I()}).strict(),D_=l({encoding:v(["utf8","base64"]),data:i().max(8e6)}).strict(),u4=N_.extend({contentHash:Ac,content:D_}).strict();l({draftId:Ar,expectedDraftRevision:d().int().positive(),path:cd,expectedFileHash:Ac.nullable(),content:D_.nullable()}).strict();var m4=y_.extend({mode:v(["nightly","approved_count"]),minimumTasks:d().int().min(1).max(1e4),maximumSpendUsd:d().positive().max(1e5),maximumDailySpendUsd:d().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."})}),p4=67108864,bg=524288,ac=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function bb(e){return JSON.stringify(yg(e))}function f4(e){return new TextEncoder().encode(bb(e)).byteLength}async function h4(e){const t=new TextEncoder().encode(bb(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 g4(e,t,n){const a=f4(e);if(a>t)throw new ac("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function yg(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new ac("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=>yg(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new ac("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 ac("non_json_value",`Canonical JSON cannot contain ${typeof o} at ${a}.`);n[a]=yg(o)}return n}throw new ac("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var Ht=i().trim().min(1).max(500),Ei=i().regex(/^[a-f0-9]{64}$/),Ua=i().datetime({offset:!0}),Tt=l({id:Ht,contentHash:Ei}).strict(),ea=Tt.extend({revision:d().int().positive()}).strict(),Hr=l({schemaVersion:b("openpond.baseModelPreference.v1"),modelId:Ht,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:Ht.nullable(),source:v(["managed","local","builtin"])}).strict(),H_=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),L_=l({schemaVersion:i().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:H_,parameterization:v(["lora","full"])}).catchall(ie()),v4=l({profileProjectId:Ht,sourceRevision:i().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Tt}).strict(),b4=l({profileProjectId:Ht,sourceRevision:i().regex(/^[a-f0-9]{40,64}$/),catalogHash:Ei,definitionId:Ht,harnessRelease:Tt,tasksetRelease:Tt}).strict(),q_=l({tasksetRef:ea.nullable().default(null),evaluationTasksetRef:ea.nullable().optional(),profileSource:v4.nullable().optional(),profileEvaluation:b4.nullable().optional(),rewardBindingRef:ea.nullable().optional(),tasksetRelease:Tt.nullable().default(null),harnessRelease:Tt.nullable().default(null),baseModel:Hr.nullable().default(null),method:H_.nullable().default(null),destinationId:Ht.nullable().default(null),managedRolloutPlacement:v(["local","remote"]).default("remote"),managedGpuPlacementObjective:v(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:v(["any","h100_hbm3"]).default("any"),runPreset:v(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:L_.nullable().default(null),preferredMaximumSpendUsd:d().nonnegative().nullable().default(null),preferredRetentionDays:d().int().nonnegative().nullable().default(null)}).strict(),yb=q_.omit({managedGpuRequirement:!0}),y4=l({schemaVersion:b("openpond.hostedModelProjectLink.v1"),apiOrigin:i().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:Ht,projectId:Ht,portableProjectId:Ht,revision:d().int().positive(),etag:Ei,syncedSourceRevision:d().int().positive(),syncedAt:Ua,tasksets:p(l({localTasksetId:Ht,localTasksetHash:Ei.nullable().default(null),releaseId:Ht,releaseRevision:d().int().positive(),releaseHash:Ei,packageHash:Ei.nullable().default(null),hostedTasksetId:Ht,syncedAt:Ua}).strict()).max(1e4).default([])}).strict(),S4=l({localTasksetId:Ht,releaseId:Ht,releaseRevision:d().int().positive(),releaseHash:Ei,state:v(["syncing","synced","sync_failed"]),hostedTasksetId:Ht.nullable().default(null),lastAttemptAt:Ua,syncedAt:Ua.nullable().default(null),lastError:i().trim().min(1).max(5e3).nullable().default(null)}).strict(),U_=l({schemaVersion:b("openpond.modelProject.v2"),id:Ht,profileId:Ht,revision:d().int().positive().default(1),name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:Hr.nullable(),defaultDestinationId:Ht.nullable(),trainingSetup:q_,hosted:y4.nullable().default(null),tasksetSyncs:p(S4).max(1e4).default([]),createdAt:Ua,updatedAt:Ua}).strict(),z_=U_.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),x4=l({schemaVersion:b("openpond.modelProjectSave.v1"),operationId:Ht,expectedRevision:d().int().nonnegative(),project:z_,learning:m4.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."})}),B_=l({schemaVersion:b("openpond.modelProjectConfigurationCheck.v1"),configurationHash:Ei,projectId:Ht,expectedRevision:d().int().nonnegative(),checkedAt:Ua,canSave:I(),deferred:p(v(["base_model","taskset"])).max(2),findings:p(l({code:Ht,severity:v(["error","warning"]),message:i().min(1).max(5e3),field:i().min(1).max(500).nullable()}).strict()).max(100)}).strict();l({id:Ht,name:i().min(1).max(500),available:I(),preference:Hr}).strict();function k4(e){try{Wa(e,bg)}catch{throw new C4(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return x4.parse(e)}async function w4(e,t,n){Wa(e,bg);const a=z_.parse(e);g4(a,bg,"Model configuration");const o=await h4({project:a,expectedRevision:t});return k4({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${o}`,expectedRevision:t,project:a})}var I4=l({schemaVersion:b("openpond.hostedModelProjectSync.v2"),portableProjectId:Ht,name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:Hr.nullable(),defaultDestinationId:Ht.nullable(),trainingSetup:yb,sourceRevision:d().int().positive(),sourceUpdatedAt:Ua,expectedEtag:Ei.nullable().default(null)}).strict(),Fm=l({id:Ht,teamId:Ht,portableProjectId:Ht,name:i().trim().min(1).max(200),objective:i().trim().max(5e3).nullable(),defaultBaseModel:Hr.nullable(),defaultDestinationId:Ht.nullable(),trainingSetup:yb,sourceRevision:d().int().positive(),sourceUpdatedAt:Ua,revision:d().int().positive(),etag:Ei,createdAt:Ua,updatedAt:Ua}).strict(),_4=l({kind:v(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Tt,role:i().trim().min(1).max(200).nullable().default(null),updatedAt:Ua}).strict();l({project:Fm,resources:p(_4).max(1e4),jobCount:d().int().nonnegative(),latestJobIds:p(Ht).max(100)}).strict();l({schemaVersion:b("openpond.modelProjectApiError.v2"),code:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3),retryable:I().default(!1),requestId:i().trim().min(1).max(500).nullable().default(null),details:te(i(),ie()).default({})}).strict();var C4=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}},R4=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),P4=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 A4(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(R4),c=new Uint32Array(64);for(let m=0;m<n;m+=64){for(let R=0;R<16;R+=1)c[R]=r.getUint32(m+R*4,!1);for(let R=16;R<64;R+=1){const $=c[R-15],O=c[R-2],M=Ii($,7)^Ii($,18)^$>>>3,w=Ii(O,17)^Ii(O,19)^O>>>10;c[R]=c[R-16]+M+c[R-7]+w>>>0}let u=s[0],f=s[1],g=s[2],S=s[3],k=s[4],C=s[5],P=s[6],j=s[7];for(let R=0;R<64;R+=1){const $=k&C^~k&P,O=u&f^u&g^f&g,M=Ii(u,2)^Ii(u,13)^Ii(u,22),w=Ii(k,6)^Ii(k,11)^Ii(k,25),A=j+w+$+P4[R]+c[R]>>>0,E=M+O>>>0;j=P,P=C,C=k,k=S+A>>>0,S=g,g=f,f=u,u=A+E>>>0}s[0]=s[0]+u>>>0,s[1]=s[1]+f>>>0,s[2]=s[2]+g>>>0,s[3]=s[3]+S>>>0,s[4]=s[4]+k>>>0,s[5]=s[5]+C>>>0,s[6]=s[6]+P>>>0,s[7]=s[7]+j>>>0}return Array.from(s,m=>m.toString(16).padStart(8,"0")).join("")}function Ii(e,t){return e>>>t|e<<32-t}var T4=2e3,F_=25e7,Ke=i().trim().min(1).max(240),Qe=i().regex(/^[a-f0-9]{64}$/),Rt=i().datetime({offset:!0}),Vm=te(i(),ie()).default({}),De=l({id:Ke,contentHash:Qe}).strict(),E4=De.extend({revision:d().int().positive()}).strict(),li=l({id:Ke,path:i().trim().min(1).max(T4).refine(O4),contentHash:Qe,sizeBytes:d().int().nonnegative().max(F_),mediaType:i().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"])}).strict(),j4=l({id:Ke,contentHash:Qe,mediaType:i().trim().min(1).max(200).nullable().default(null),sizeBytes:d().int().nonnegative().max(F_).nullable().default(null)}).strict(),V_=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function M4(e){return`${JSON.stringify(Sg(e),null,2)}
|
|
183
|
+
`}function K_(e){return A4(e)}function Pt(e){return K_(M4(e))}function Oae(e,t){const{contentHash:n,...a}=e,o=Pt(a);if(n!==o)throw new Error(`${t} contentHash is ${n}; expected ${o}.`)}function O4(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Sg(e){return Array.isArray(e)?e.map(Sg):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Sg(n)]))}var $4=v(["memory","prompt","skill","agent"]),N4=v(["runtime","product","taskset","training"]),D4=l({id:i().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),text:i().trim().min(1).max(1e4)}).strict(),H4=l({schemaVersion:b("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(D4).max(100),allowedProposalRoutes:p($4).max(4),allowedExternalRoutes:p(N4).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"]})});l({schemaVersion:b("openpond.refinerRelease.v1"),id:i().trim().min(1).max(240),coreVersion:i().trim().min(1).max(120),coreHash:Qe,profile:H4,profileHash:Qe,composedPromptHash:Qe,createdAt:Rt,contentHash:Qe}).strict();l({schemaVersion:b("openpond.refinerBinding.v1"),channel:b("active"),revision:d().int().nonnegative(),release:De,updatedAt:Rt}).strict();l({schemaVersion:b("openpond.refinerTransitionReceipt.v1"),id:i().trim().min(1).max(240),operation:v(["initialize","update","activate","rollback"]),bindingChanged:I(),previousRelease:De.nullable(),nextRelease:De,actor:i().trim().min(1).max(240),reason:i().trim().min(1).max(1e4),authoringSkillHash:Qe.nullable(),validation:l({valid:I(),messages:p(i().max(2e3)).max(100)}).strict(),createdAt:Rt,contentHash:Qe}).strict();var L4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("no_action"),reason:i().trim().min(1).max(1e4)}).strip(),q4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("route"),route:v(["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(),U4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v1"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["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"]})}),z4=rt("decision",[L4,q4,U4]),B4=z4,Sb=l({kind:v(["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"]})}),F4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("no_action"),reason:i().trim().min(1).max(1e4)}).strict(),V4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("route"),route:v(["runtime","product","taskset","training"]),summary:i().trim().min(1).max(2e3),evidenceBasis:Sb,expectedOutcome:i().trim().min(1).max(1e4),reason:i().trim().min(1).max(1e4)}).strict(),K4=l({schemaVersion:b("openpond.localHarnessRefinerDecision.v2"),decision:b("propose"),route:v(["memory","prompt","skill","agent"]),operation:v(["create","update","delete"]),target:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(2e3),evidenceBasis:Sb,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"]})}),W_=rt("decision",[F4,V4,K4]);gt([B4,W_]);var xb=l({memory:I(),prompt:I(),skill:I(),agent:I()}).strict(),G_=v(["memory","instruction","skill","agent"]),vS=l({path:i().trim().min(1).max(2e3),kind:G_,content:i().max(6e4),loaded:I()}).strict(),bS=l({path:i().trim().min(1).max(2e3),kind:G_,loaded:I()}).strict(),W4=l({capabilities:xb,trigger:te(i(),ie()),observations:p(te(i(),ie())).max(20),admissibleEvidenceIds:p(i().trim().min(1).max(2e3)).max(1e4),reviewPacket:l({currentTurn:l({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:d().int().nonnegative()}).strict(),priorConversation:p(l({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(te(i(),ie())).max(60),artifacts:p(te(i(),ie())).max(30),artifactDiagnostics:p(te(i(),ie())).max(20),executionProfile:l({modelRequestCount:d().int().nonnegative(),failedModelRequestCount:d().int().nonnegative(),promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),toolFailureCount:d().int().nonnegative(),retryCount:d().int().nonnegative(),recoveryCount:d().int().nonnegative()}).strict(),priorIncidents:p(te(i(),ie())).max(3),truncation:l({timelineEventCount:d().int().nonnegative(),includedTimelineEventCount:d().int().nonnegative(),timelineTruncated:I()}).strict()}).strict(),runtimeActivation:l({admittedRelease:De,currentRelease:De,rebasedOntoCurrent:I(),admittedSourceFiles:p(vS).max(100),admittedSourceCatalog:p(bS).max(1e3)}).strict(),sourceFiles:p(vS).max(100),sourceCatalog:p(bS).max(1e3),additionalEvidence:ie().nullable().optional()}).strict(),G4=l({id:i().trim().min(1).max(240),revision:d().int().nonnegative(),contentHash:Qe}).strict();l({schemaVersion:b("openpond.hostedHarnessRefinerRequest.v2"),requestId:i().trim().min(1).max(240),idempotencyKey:i().trim().min(1).max(240),evidenceHash:Qe,harness:l({admittedRelease:De,currentRelease:De,overlay:G4,workspace:l({id:i().trim().min(1).max(240),revision:d().int().nonnegative(),sourceRevision:Qe,channelRevision:d().int().nonnegative()}).strict(),capabilities:xb}).strict(),evidence:W4}).strict();var J4=l({promptTokens:d().int().nonnegative(),completionTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative()}).strict();l({schemaVersion:b("openpond.hostedHarnessRefinerResponse.v2"),requestId:i().trim().min(1).max(240),evidenceHash:Qe,admittedRelease:De,currentRelease:De,decision:W_,serviceRevision:i().trim().min(1).max(240),usage:J4}).strict();l({provider:Ke,model:Ke,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 Z4=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Y4=v(Z4),kb=l({providerId:Y4,modelId:i().trim().min(1).max(300)}),J_=l({name:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(2e3),inputSchema:te(i(),ie()),inputSchemaHash:Qe,sideEffect:v(["read","write"]),timeoutMs:d().int().positive().max(36e5)}).strict(),Q4=l({id:Ke,required:I(),scopes:p(i().trim().min(1).max(500)).max(100).default([]),portability:v(["portable","host_adapter","local_only","hosted_only"])}).strict(),X4=l({portable:I(),blockers:p(i().trim().min(1).max(2e3)).max(1e3),localOnlyAssetRefs:p(Ke).max(1e4),hostPrivateAssetRefs:p(Ke).max(1e4)}).strict(),eB=l({schemaVersion:b("openpond.agentSnapshot.v2"),id:Ke,sourceRelease:De.nullable(),instructions:p(li).max(1e4),skills:p(li).max(1e4),agents:p(li).max(1e4),toolDeclarations:p(J_).max(200),capabilityRequirements:p(Q4).max(200),dependencyLock:li,portability:X4,metadata:Vm}).strict(),tB=eB.extend({contentHash:Qe}).strict(),nB=l({create:b(!0),reset:b(!0),step:b(!0),collect:b(!0),destroy:b(!0),resetScope:v(["task","attempt"])}).strict(),aB=l({visibleEvidence:p(Ke).max(1e3),privilegedEvidence:p(Ke).max(1e3),privateVerifierIsolation:I()}).strict(),iB=l({schemaVersion:b("openpond.harnessRelease.v2"),id:Ke,agentSnapshot:De,program:li,tools:p(J_).max(200),lifecycle:nB,graderInterface:aB,files:p(li).max(1e5),metadata:Vm}).strict(),oB=iB.extend({contentHash:Qe}).strict(),rB=l({id:Ke,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:Ke.nullable(),arguments:te(i(),ie()),content:i().max(1e6).nullable()}).strict(),sB=l({actionId:Ke,turn:d().int().nonnegative(),terminal:I(),output:te(i(),ie()),artifactRefs:p(j4).max(1e5)}).strict(),lB=l({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","failure","collected","destroyed"]),payloadHash:Qe,metadata:Vm}).strict();l({schemaVersion:b("openpond.harnessTrace.v1"),manifest:De,taskId:Ke,seed:i().trim().min(1).max(500),events:p(lB).max(1e6),actions:p(rB).max(1e5),observations:p(sB).max(1e5),terminal:I(),failureClass:V_.nullable(),output:te(i(),ie()),contentHash:Qe}).strict();var cB=25*1024*1024,dB=l({path:li.shape.path,base64:i().max(Math.ceil(cB/3)*4)}).strict(),Z_=l({schemaVersion:b("openpond.harnessSourcePackage.v1"),agentSnapshot:tB,harnessRelease:oB,files:p(dB).max(1e4)}).strict();Z_.extend({contentHash:Qe}).strict();var $ae=Z_.extend({schemaVersion:b("openpond.harnessPolicySourcePackage.v1"),contentHash:Qe}).strict();l({schemaVersion:b("openpond.harnessSourceSelection.v1"),mode:v(["taskset_owned","selected_release"]),harnessRelease:De,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 co=i().trim().min(1).max(1e5),uB=v(["no_action","harness_maintenance","runtime","product","taskset","model_improvement"]),mB=v(["none","runtime_service","product_team","human_review","evaluation_system","training_system"]),Y_=v(["observation","trigger","route_decision","refiner_outcome","proposal","validation","apply_receipt","harness_advance","rollback","work_outcome","taskset","evaluation","training_qualification","model_candidate"]),wb=l({kind:v(["personal","team"]),id:Ke}).strict(),Q_=l({policy:De,state:v(["authorized","revoked","deleted","expired"]),checkedAt:Rt}).strict(),Tc=l({evidence:De,kind:Y_,sourceRef:Ke,sourcePolicy:Q_,occurrenceKey:Qe,occurredAt:Rt}).strict(),pB=l({evidence:De,sourcePolicy:Q_.nullable(),reason:v(["outside_scope","before_watermark","duplicate","resolved","revoked","deleted","expired","sensitive","unverified","budget"])}).strict(),yS=l({cursor:Qe,throughCreatedAt:Rt}).strict(),fB=l({fingerprint:Qe,recurrenceFamily:i().trim().min(1).max(1e3),statement:co,candidateDisposition:v(["observe","confirm"]).optional(),independentOccurrences:d().int().positive().max(1e6),unresolvedOccurrences:d().int().positive().max(1e6)}).strict().refine(e=>e.unresolvedOccurrences<=e.independentOccurrences,"unresolved occurrences cannot exceed independent occurrences"),X_=v(["harness","runtime","product","retrieval","tools","evaluation","model"]),hB=l({layer:X_,status:v(["not_applicable","unresolved","resolved","blocked"]),reason:co,evidenceRefs:p(De).max(1e3)}).strict(),gB=l({schemaVersion:b("openpond.harnessEvaluationReviewReceipt.v1"),id:Ke,ownerScope:wb,workspaceRef:Ke,harnessRelease:De,previousWatermark:yS.nullable(),nextWatermark:yS,selectedEvidence:p(Tc).max(1e4),excludedEvidence:p(pB).max(1e4),claim:fB.nullable(),classification:uB,triage:p(hB).max(16),reason:co,nextAuthority:mB,maxEstimatedCostUsd:d().finite().nonnegative(),tasksetProposal:De.nullable(),evaluation:De.nullable(),trainingQualification:De.nullable(),policyVersion:Ke,createdAt:Rt,metadata:Vm}).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"})});gB.extend({contentHash:Qe}).strict();l({id:Ke,evidence:De,kind:Y_,sourceRef:Ke,occurredAt:Rt,payload:te(i(),ie())}).strict();var vB=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("no_action"),reason:co,ignoredEvidence:p(l({id:Ke,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3)}).strict(),bB=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("review"),classification:v(["harness_maintenance","runtime","product","taskset"]),selectedEvidenceIds:p(Ke).min(1).max(1e3),ignoredEvidence:p(l({id:Ke,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),recurrenceFamily:i().trim().min(1).max(1e3),statement:co,triageLayer:X_,expectedOutcome:co,counterevidence:i().trim().max(1e4),confidence:d().min(0).max(1),candidateDisposition:v(["observe","confirm"]).nullable(),reason:co}).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"]})}),yB=l({schemaVersion:b("openpond.harnessEvaluationReviewModelDecision.v2"),decision:b("resolve_candidate"),candidateId:Ke,candidateFingerprint:Qe,selectedEvidenceIds:p(Ke).min(1).max(1e3),ignoredEvidence:p(l({id:Ke,reason:i().trim().min(1).max(2e3)}).strict()).max(1e3),confidence:d().min(0).max(1),reason:co}).strict();rt("decision",[vB,bB,yB]);l({schemaVersion:b("openpond.harnessEvaluationReviewNavigationDecision.v1"),selectedEvidenceIds:p(Ke).min(1).max(50),reason:co}).strict();var pl=te(i(),ie()).default({}),Ha=d().int().nonnegative(),Km=i().trim().min(1).max(1e5),eC=l({kind:v(["personal","team"]),id:Ke}).strict(),SB=l({name:Ke,release:De.nullable(),revision:Ha}).strict();l({schemaVersion:b("openpond.harnessWorkspace.v1"),id:Ke,ownerScope:eC,name:i().trim().min(1).max(240),location:v(["local","hosted"]),sourceRevision:i().trim().min(1).max(500),revision:Ha,dirty:I(),currentChannel:SB,createdAt:Rt,updatedAt:Rt,metadata:pl}).strict();var Ys=v(["runtime","memory","prompt","skill","agent","product","taskset","training"]),tC=v(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),nC=l({id:Ke,route:Ys,operation:v(["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(tC).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=Pt(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),aC=l({workspaceId:Ke,revision:Ha,sourceRevision:i().trim().min(1).max(500),channelRevision:Ha}).strict(),uo=l({id:Ke,revision:Ha,contentHash:Qe}).strict();l({schemaVersion:b("openpond.harnessTurnSnapshot.v1"),workspaceId:Ke,workspaceRevision:Ha,sourceRevision:i().trim().min(1).max(500),channelName:Ke,channelRevision:Ha,harnessRelease:De,toolCatalogHash:Qe.nullable().optional(),overlay:uo.nullable().optional().default(null)}).strict();var xB=l({schemaVersion:b("openpond.harnessRunOverlay.v1"),id:Ke,runId:Ke,baseHarnessRelease:De,workspace:aC,revision:Ha,status:v(["active","frozen","abandoned"]),edits:p(nC).max(1e3),createdAt:Rt,updatedAt:Rt,metadata:pl}).strict();xB.extend({contentHash:Qe}).strict();var iC=l({kind:v(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:Ke,contentHash:Qe.nullable()}).strict(),oC=l({id:Ke,kind:v(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Km,required:I()}).strict(),kB=l({schemaVersion:b("openpond.harnessImprovementProposal.v1"),id:Ke,overlay:uo,baseHarnessRelease:De,expectedWorkspace:aC,requestedScope:v(["personal","team","global"]),route:Ys,risk:v(["low","review","restricted"]),effects:p(tC).min(1).max(20),evidence:p(iC).min(1).max(1e3),edits:p(nC).min(1).max(1e3),validationPlan:p(oC).min(1).max(100),expectedOutcome:Km,createdAt:Rt,metadata:pl}).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"]})});kB.extend({contentHash:Qe}).strict();var wB=l({schemaVersion:b("openpond.harnessTargetedValidationReceipt.v1"),id:Ke,proposal:De,validationId:Ke,kind:oC.shape.kind,status:v(["passed","failed","blocked","skipped"]),summary:Km,evidenceRefs:p(iC).max(1e3),createdAt:Rt,metadata:pl}).strict();wB.extend({contentHash:Qe}).strict();var IB=v(["advanced","retained","conflict","rolled_back"]),_B=l({schemaVersion:b("openpond.harnessAdvanceReceipt.v1"),id:Ke,workspaceId:Ke,ownerScope:eC,proposal:De.nullable(),expectedWorkspaceRevision:Ha,observedWorkspaceRevision:Ha,previousChannelRevision:Ha,nextChannelRevision:Ha,previousRelease:De.nullable(),nextRelease:De.nullable(),validationReceipts:p(De).max(100),decision:IB,reason:Km,rollbackOf:De.nullable(),createdAt:Rt,metadata:pl}).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"]})});_B.extend({contentHash:Qe}).strict();var CB=l({schemaVersion:b("openpond.harnessOverlayMergeReceipt.v1"),id:Ke,workspaceId:Ke,baseHarnessRelease:De,leftOverlay:uo,rightOverlay:uo,decision:v(["merged","conflict"]),mergedOverlay:uo.nullable(),conflictTargets:p(i().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:b(!0),createdAt:Rt,metadata:pl}).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"]})});CB.extend({contentHash:Qe}).strict();var Wm=i().trim().min(1).max(1e5),dd=te(i(),ie()).default({}),RB=v(["completed_tool_batch","before_model_step","turn_completed","turn_paused"]),rC=l({kind:RB,eventSequence:d().int().nonnegative(),occurredAt:Rt}).strict(),sC=l({id:Ke,sequence:d().int().nonnegative().nullable(),contentHash:Qe}).strict(),PB=v(["tool_failure","retry","recovery","validation","user_turn","reusable_success","completion_detour"]),AB=v(["open","recovered","terminal"]),TB=l({name:i().trim().min(1).max(500),invocationKey:Qe}).strict(),EB=l({schemaVersion:b("openpond.improvementObservation.v1"),id:Ke,runRef:Ke,turnId:Ke,harnessRelease:De,overlay:uo.nullable(),eventRefs:p(sC).min(1).max(100),kind:PB,state:AB,tool:TB.nullable(),deterministicClass:i().trim().min(1).max(500).nullable(),summary:Wm,createdAt:Rt,metadata:dd}).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"]})});EB.extend({contentHash:Qe}).strict();var jB=l({schemaVersion:b("openpond.refinementTriggerPolicy.v1"),maxEstimatedCostUsd:d().finite().nonnegative(),cooldownMs:d().int().nonnegative(),maxPendingPlans:d().int().min(1).max(100),maxEvidenceEvents:d().int().min(1).max(1e3),maxProposalEdits:d().int().min(1).max(1e3),maxProposalBytes:d().int().min(1).max(1e7)}).strict(),MB=v(["no_action","route_deterministically","queue_refiner"]),OB=l({schemaVersion:b("openpond.refinementTriggerDecision.v1"),id:Ke,runRef:Ke,turnId:Ke,harnessRelease:De,overlay:uo.nullable(),observations:p(De).max(100),decision:MB,deterministicRoute:Ys.nullable(),suggestedRoutes:p(Ys).max(8),reason:Wm,deduplicationKey:Qe,policy:jB,estimatedMaxCostUsd:d().finite().nonnegative(),pendingPlanCount:d().int().nonnegative(),boundary:rC,cooldownUntil:Rt.nullable(),createdAt:Rt,metadata:dd}).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"]})});OB.extend({contentHash:Qe}).strict();var $B=v(["runtime_service","refiner_model","human_review","evaluation_system","training_system"]),NB=l({schemaVersion:b("openpond.improvementRouteDecision.v1"),id:Ke,trigger:De,route:Ys,authority:$B,automatic:I(),reason:Wm,createdAt:Rt,metadata:dd}).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"]})});NB.extend({contentHash:Qe}).strict();var DB=l({schemaVersion:b("openpond.harnessRefinerOutcome.v1"),id:Ke,trigger:De,decision:v(["no_action","proposed"]),proposal:De.nullable(),reason:Wm,evidenceRefs:p(De).max(100),estimatedCostUsd:d().finite().nonnegative(),createdAt:Rt,metadata:dd}).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"]})});DB.extend({contentHash:Qe}).strict();var HB=v(["applied","retained","declined","conflict","rolled_back"]),LB=l({schemaVersion:b("openpond.improvementApplyReceipt.v1"),id:Ke,proposal:De,beforeOverlay:uo,afterOverlay:uo.nullable(),decision:HB,boundary:rC,validationRefs:p(De).max(100),outcomeEvidenceRefs:p(sC).max(1e3),rollbackOf:De.nullable(),createdAt:Rt,metadata:dd}).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"]})});LB.extend({contentHash:Qe}).strict();var qB=i().trim().min(1).max(2e3),Ib=i().trim().min(1).max(1e5),UB=v(["create","update","delete"]),zB=v(["memory","prompt","skill","agent"]),BB=v(["runtime","product","taskset","training"]),FB=v(["no_action","routed","applied","retained","failed"]),VB=v(["not_applicable","pending","passed","rejected","failed"]),KB=v(["not_applicable","pending","passed","failed"]),WB=l({schemaVersion:b("openpond.harnessRefinerActivityReceipt.v1"),id:Ke,runRef:Ke,turnId:Ke,result:FB,decision:v(["no_action","route","propose"]).nullable(),route:Ys.nullable(),operation:UB.nullable(),target:i().trim().min(1).max(2e3).nullable(),summary:qB,evidenceBasis:Sb.nullable(),critiqueStatus:VB,validationStatus:KB,trigger:De,outcome:De.nullable(),proposal:De.nullable(),applyReceipt:De.nullable(),inputHarness:De,outputHarness:De.nullable(),createdAt:Rt}).strict().superRefine((e,t)=>{const n=e.result==="applied"||e.result==="retained";e.result==="no_action"?SS(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"||!BB.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"}),SS(t,e,{critiqueStatus:"not_applicable",validationStatus:"not_applicable"})):n?((e.decision!=="propose"||!zB.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"]})});WB.extend({contentHash:Qe}).strict();var GB=v(["unresolved","confirmed","resolved","rejected","expired"]),JB=l({kind:v(["applied_change","later_success","manual_rejection","source_revoked","expired"]),reason:Ib,evidenceRefs:p(De).max(1e3),resolvedAt:Rt}).strict(),ZB=l({schemaVersion:b("openpond.harnessRefinementCandidate.v1"),id:Ke,ownerScope:wb,workspaceRef:Ke,fingerprint:Qe,recurrenceFamily:i().trim().min(1).max(1e3),statement:Ib,status:GB,occurrences:p(Tc).max(1e3),counterevidence:p(Tc).max(1e3),sourceReviews:p(De).min(1).max(100),relatedHarnessReleases:p(De).max(100),firstSeenAt:Rt,lastSeenAt:Rt,lastReviewedAt:Rt,expiresAt:Rt,resolution:JB.nullable(),createdAt:Rt,updatedAt:Rt}).strict().superRefine((e,t)=>{xr(t,e.occurrences,"occurrences"),xr(t,e.counterevidence,"counterevidence"),xr(t,e.sourceReviews,"sourceReviews"),xr(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"]}),tF(t,e)});ZB.extend({contentHash:Qe}).strict();var YB=v(["created","merged","rejected","expired","reopened","resolved"]),QB=l({schemaVersion:b("openpond.harnessRefinementCandidateLifecycleReceipt.v1"),id:Ke,candidateId:Ke,decision:YB,beforeCandidate:De.nullable(),afterCandidate:De,review:De,addedEvidence:p(Tc).max(1e3),removedEvidence:p(De).max(1e3),reason:Ib,createdAt:Rt}).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"]}),xr(t,e.addedEvidence,"addedEvidence"),xr(t,e.removedEvidence,"removedEvidence");const n=new Set(e.removedEvidence.map(a=>xg(a)));e.addedEvidence.some(a=>n.has(xg(a.evidence)))&&t.addIssue({code:"custom",message:"candidate lifecycle evidence cannot be added and removed together",path:["removedEvidence"]})});QB.extend({contentHash:Qe}).strict();var XB=l({schemaVersion:b("openpond.harnessCrossRunRefinementRequest.v1"),id:Ke,ownerScope:wb,workspaceRef:Ke,candidate:De,candidateFingerprint:Qe,review:De,admittedHarness:De,evidence:p(Tc).min(1).max(1e3),capabilities:xb,deduplicationKey:Qe,createdAt:Rt}).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"]}),xr(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=eF(e);e.deduplicationKey!==n&&t.addIssue({code:"custom",message:`cross-run refinement deduplicationKey is ${e.deduplicationKey}; expected ${n}`,path:["deduplicationKey"]})});XB.extend({contentHash:Qe}).strict();function eF(e){return Pt({schemaVersion:"openpond.harnessCrossRunRefinementIdentity.v1",workspaceRef:e.workspaceRef,candidateFingerprint:e.candidateFingerprint,admittedHarness:e.admittedHarness})}function SS(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 xr(e,t,n){const a=t.map(o=>xg(o));new Set(a).size!==a.length&&e.addIssue({code:"custom",message:`${n} references must be unique`,path:[n]})}function xg(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 tF(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"]})}l({path:i().min(1).max(2e3),offset:d().int().nonnegative().default(0),length:d().int().positive().max(65536).default(16384)}).strict();var lC=i().regex(/^[a-z][a-z0-9_-]{0,119}$/),cC=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"),nF=l({id:lC,label:i().trim().min(1).max(240),description:i().max(4e3),inputSchema:te(i(),ie()),invocation:rt("kind",[l({kind:b("instructions"),instructions:i().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),l({kind:b("agent_action"),actionId:i().trim().min(1).max(240)}).strict()]),skillPaths:p(cC).max(100)}).strict();l({schemaVersion:b("openpond.profileWorkflows.v1"),workflows:p(nF).max(1e3)}).strict();var aF=l({id:i().trim().min(1).max(240),agentId:i().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:i().trim().min(1).max(240),inputSchema:te(i(),ie())}).strict();l({schemaVersion:b("openpond.profileWorkflowActions.v1"),actions:p(aF).max(200)}).strict();l({schemaVersion:b("openpond.profileWorkflowBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:De,catalogHash:Qe,workflowId:lC}).strict();l({schemaVersion:b("openpond.profileComponentBinding.v1"),profileId:i().trim().min(1).max(240),sourceRevision:i().trim().min(1).max(240),harnessRelease:De,target:rt("kind",[l({kind:b("profile")}).strict(),l({kind:b("skill"),skillPath:cC}).strict(),l({kind:b("agent_action"),actionId:i().trim().min(1).max(240)}).strict()])}).strict();var Xu=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 iF={type:"object",properties:{},additionalProperties:!1};l({name:i().trim().min(1).max(240).optional(),description:i().max(4e3).optional(),skillPaths:p(Xu).max(100).optional(),assetPaths:p(Xu).max(100).optional()}).strict();l({actionId:i().trim().min(1).max(240),name:i().trim().min(1).max(240),description:i().max(4e3).default(""),inputSchema:te(i(),ie()).default(iF),skillPaths:p(Xu).max(100).default([]),assetPaths:p(Xu).max(100).default([])}).strict();const oF="openpond.connectedEvidence.v1",rF="connected-evidence-1",eu={files:100,sourceBytes:32*1024*1024,events:1e5,sessions:1e3,boundaries:5e3},xa=i().min(1).max(500),cc=i().regex(/^[a-f0-9]{64}$/),sF=i().datetime().nullable(),tu=d().int().nonnegative().nullable(),dC=v(["native_chat","native_work","codex","claude_code","hermes","openclaw","opencode","grok_build","pi","oh_my_pi"]),lF=l({invocationId:xa,inputTokens:tu,outputTokens:tu,cachedInputTokens:tu,totalTokens:tu,provenance:v(["billed_invocation","reported_invocation","reported_cumulative"])}).strict(),xS=l({id:xa,sequence:d().int().nonnegative(),occurredAt:sF,kind:v(["message","tool_call","tool_result","compaction","artifact","terminal","usage","unknown"]),role:v(["user","assistant","system","tool"]).nullable(),callId:xa.nullable(),parentId:xa.nullable(),content:Ko(),usage:lF.nullable()}).strict(),cF=l({id:xa,familyKey:xa,projection:v(["turn","conversation"]),requestEventId:xa,start:d().int().nonnegative(),end:d().int().positive(),inputHash:cc,outputHash:cc.nullable(),revisionHash:cc,terminal:v(["completed","failed","cancelled","unknown"]),coverage:l({answer:I(),context:v(["retained","compacted","unknown"]),process:v(["retained","partial","absent"]),artifacts:v(["retained","references_only","absent"]),replay:b("unavailable"),gaps:p(i().max(500)).max(100)}).strict()}).strict();l({schemaVersion:b(oF),normalizerVersion:b(rF),origin:dC,sessionId:xa,branchId:xa.nullable(),parentSessionId:xa.nullable(),exporterVersion:i().max(200).nullable(),acquisition:l({machineId:xa,sourceInstanceId:xa}).strict().optional(),sourceFiles:p(l({path:xa,contentHash:cc,sizeBytes:d().int().nonnegative()}).strict()).max(eu.files),events:p(xS).max(eu.events),unmappedEvents:p(xS).max(eu.events),boundaries:p(cF).max(eu.boundaries),warnings:p(i().max(500)).max(100),contentHash:cc}).strict();const dF=l({schemaVersion:b("openpond.humanResultView.v1"),executionId:i().min(1),executionHash:i().regex(/^[a-f0-9]{64}$/),selection:p(_n).max(1e4),coverage:l({pending:d().int().nonnegative(),submitted:d().int().nonnegative(),accepted:d().int().nonnegative(),rejected:d().int().nonnegative(),cancelled:d().int().nonnegative()}).strict(),results:p(l({review:_n,decision:_n.nullable(),attemptIds:p(i().min(1)).min(1).max(2),mode:v(["individual","pairwise"]),origin:v(["hosted_retained","recorded_evidence","owner_attested_local","native_local"]),status:v(["pending","submitted","accepted","rejected","cancelled"]),grader:_n,answers:p(Js).max(100)}).strict()).max(1e4)}).strict(),kS=dF.extend({contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict(),em=i().regex(/^[a-f0-9]{64}$/),Ec=i().min(1).max(240),nu={feedbackKey:Ec,criterionId:Ec},uF=rt("kind",[l({...nu,kind:b("normalized_score"),minimum:d().finite(),maximum:d().finite(),passThreshold:d().min(0).max(1).optional()}).strict(),l({...nu,kind:b("boolean")}).strict(),l({...nu,kind:b("category")}).strict(),l({...nu,kind:b("preference_score"),tieScore:d().min(0).max(1).nullable()}).strict()]),wS=l({execution:V,resultHash:em,reviews:p(l({review:_n,decision:_n}).strict()).min(1).max(1e4)}).strict(),uC=l({rules:p(uF).min(1).max(100),baseline:wS,candidate:wS}).strict().superRefine((e,t)=>{new Set(e.rules.map(n=>n.feedbackKey)).size!==e.rules.length&&t.addIssue({code:"custom",message:"Select each Human feedback key once."})}),IS=l({manifest:so,result:lo}).strict(),_S=l({id:Ec,manifestHash:em,resultHash:em}).strict(),mF=l({schemaVersion:b("openpond.humanComparisonProjection.v1"),teamId:Ec,projectId:Ec,selections:uC,original:l({baseline:_S,candidate:_S}).strict(),humanResults:l({baseline:kS,candidate:kS}).strict(),baseline:IS,candidate:IS}).strict(),kg=mF.extend({contentHash:em}).strict();function ph(e){throw new ui(e,409)}function pF(e,t){const n=kg.parse(e),{contentHash:a,...o}=n;a!==ct(o)&&ph("human_comparison_projection_invalid");for(const r of["baseline","candidate"]){const s=Rr(n[r]),c=s.manifest.lineage,m=c?.humanProjection,u=n.original[r],f=n.selections[r];(!c||!m||m.originalManifest.id!==u.id||m.originalManifest.contentHash!==u.manifestHash||m.selectionHash!==ct(f)||m.rulesHash!==ct(n.selections.rules)||ct(c.execution)!==ct(f.execution)||s.manifest.teamId!==n.teamId||n.humanResults[r].contentHash!==f.resultHash)&&ph("human_comparison_projection_lineage_changed");const{contentHash:g,...S}=n.humanResults[r];(ct(S)!==g||S.executionId!==f.execution.id||S.executionHash!==f.execution.contentHash||ct(S.selection)!==ct(f.reviews.map(k=>k.review)))&&ph("human_comparison_human_result_changed")}return n}const mC=l({adapterId:T,placement:v(["local","remote","colocated","provider_native"]),runtimeVersion:i().trim().min(1).max(200),capabilityReceipt:H}).strict(),pC=l({maxTurns:d().int().positive().max(1e5),timeoutMs:d().int().positive().max(864e5),maxOutputBytes:d().int().positive().max(25e7),maximumSpendUsd:d().nonnegative().nullable()}).strict(),fF=l({schemaVersion:b("openpond.runManifest.v1"),id:T,harnessRelease:V,tasksetRelease:V,model:Im,runtimeTarget:mC,limits:pC,approval:l({id:T,contentHash:H}).strict().nullable(),createdAt:pe,metadata:jn}).strict();fF.extend({contentHash:H}).strict();const hF=l({schemaVersion:b("openpond.attemptReceipt.v1"),id:T,runManifest:V,taskId:T,seed:i().trim().min(1).max(500),terminal:I(),failureClass:Kc.nullable(),outputHash:H.nullable(),traceHash:H,artifactRefs:p(Ia).max(1e5),graderEvidenceRefs:p(Ia).max(1e4),startedAt:pe,completedAt:pe,latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),legacyAttemptRef:T.nullable().default(null),metadata:jn}).strict(),gF=hF.extend({contentHash:H}).strict(),vF=l({schemaVersion:b("openpond.evaluationResult.v1"),id:T,runManifest:V,harnessRelease:V,tasksetRelease:V,model:Im,receiptRefs:p(V).min(1).max(1e6),attemptCount:d().int().positive(),rewardEligibleCount:d().int().nonnegative(),terminalCount:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable(),failureCounts:te(Kc,d().int().nonnegative()),authoredMetric:ib.optional(),metadata:jn}).strict(),bF=vF.extend({contentHash:H}).strict(),yF=l({schemaVersion:b("openpond.harnessCompatibility.v1"),id:T,baseHarnessRelease:V,candidateHarnessRelease:V,tasksetRelease:V,environmentHash:H,toolContractHash:H,policyHash:H,graderInterfaceHash:H,metadata:jn}).strict();yF.extend({contentHash:H}).strict();const _b=v(["scored","unscorable"]),Gm=v(["policy","environment","collector","verifier","provider","host","user","scheduler"]),fC=v(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),SF=l({schemaVersion:b("openpond.environmentRelease.v1"),id:T,revision:d().int().positive(),contract:XI,actionSchemaRef:gn.nullable(),observationSchemaRef:gn.nullable(),stateSchemaRef:gn.nullable(),artifactCollection:l({maxArtifacts:d().int().positive().max(1e5),maxTotalBytes:d().int().positive().max(1e10)}).strict(),adapterConformanceHashes:te(T,H),metadata:jn}).strict(),Cb=SF.extend({contentHash:H}).strict(),xF=v(["collected","missing","skipped","failed"]),CS=v(["not_requested","passed","failed"]),kF=l({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:Ia.nullable(),status:xF,parseStatus:CS,schemaStatus:CS,errorCode:T.nullable(),failureOwner:Gm.nullable(),evidenceRefs:p(Ia).max(1e4),metadata:jn}).strict(),wF=l({schemaVersion:b("openpond.artifactManifest.v1"),id:T,attemptRef:V,entries:p(kF).max(1e5),createdAt:pe,metadata:jn}).strict();wF.extend({contentHash:H}).strict();const IF=l({schemaVersion:b("openpond.verifierSetRelease.v1"),id:T,revision:d().int().positive(),graders:p(o_).min(1).max(1e3),isolation:l({processBoundary:v(["same_process","isolated_process","container"]),networkPolicy:b("none"),defaultTimeoutMs:d().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:p(V).max(1e4),metadata:jn}).strict(),Rb=IF.extend({contentHash:H}).strict(),_F=l({verifierId:T,verifierVersion:i().trim().min(1).max(100),status:_b,rawScore:d().finite().nullable(),normalizedScore:d().min(0).max(1).nullable(),weight:d().nonnegative().max(1e3),passed:I(),hardGate:I(),rewardEligible:I(),rewardContribution:d().min(0).max(1).nullable(),failureOwner:Gm.nullable(),feedback:p(i().max(2e4)).max(1e3),visibleEvidenceRefs:p(Ia).max(1e4),privilegedEvidenceRefs:p(Ia).max(1e4),metadata:jn}).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"]})}),hC=l({schemaVersion:b("openpond.rewardReceipt.v1"),id:T,attemptRef:V,verifierSetRef:V,artifactManifestRef:V,status:_b,reward:d().min(0).max(1).nullable(),learningEligible:I(),passed:I(),outcomeClass:fC,failureOwner:Gm.nullable(),components:p(_F).min(1).max(1e4),visibleEvidenceRefs:p(Ia).max(1e5),privilegedEvidenceRefs:p(Ia).max(1e5),supersedes:V.nullable(),createdAt:pe,metadata:jn}).strict();function gC(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"]})}hC.superRefine(gC);hC.extend({contentHash:H}).strict().superRefine(gC);const CF=rt("kind",[l({kind:b("model"),model:Im,configurationHash:H}).strict(),l({kind:b("fixture")}).strict()]),RF=rt("kind",[l({kind:b("taskset"),environmentRelease:V,verifierSetRelease:V,policyHash:H}).strict(),l({kind:b("harness"),harnessRelease:V}).strict()]),vC=l({receiptId:T,taskId:T,seed:i().trim().min(1).max(500),fixtureId:T.nullable()}).strict(),PF=l({schemaVersion:b("openpond.tasksetRunManifest.v1"),id:T,tasksetRelease:V,packageHash:H,execution:RF,profileEvaluation:Zs.optional(),policy:CF,gradingRole:b("evaluation"),metricPolicy:ad,population:p(vC).min(1).max(1e5),runtimeTarget:mC,limits:pC,createdAt:pe,metadata:jn}).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."})}),Jm=PF.safeExtend({contentHash:H}),AF=l({schemaVersion:b("openpond.profileEvaluationComparison.v1"),id:T,tasksetRelease:V,populationHash:H,environmentHash:H,metricPolicyHash:H,limitsHash:H,members:p(l({runManifest:V,metricResultHash:H,source:Zs,policy:Jm.shape.policy,score:d().min(0).max(1).nullable()}).strict()).min(2).max(100),createdAt:pe}).strict(),TF=AF.extend({contentHash:H}).strict(),EF=l({profileId:T,sourceRevision:i().trim().min(1).max(240),harnessRelease:V}).strict(),jF=l({kind:v(["run","suite","comparison"]),id:T,contentHash:H}).strict(),MF=l({schemaVersion:b("openpond.profileEvaluationReport.v1"),id:T,createdAt:pe,testedSources:p(EF).min(1).max(100),tasksetReleases:p(V).min(1).max(100),metricPolicyHashes:p(H).min(1).max(100),modelConfigurationHashes:p(H).min(1).max(100),evidence:p(jF).min(1).max(100),summary:l({totalChecks:d().int().nonnegative(),passedChecks:d().int().nonnegative(),failedChecks:d().int().nonnegative(),unscoredChecks:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable()}).strict()}).strict().superRefine((e,t)=>{const{summary:n}=e;n.passedChecks+n.failedChecks+n.unscoredChecks!==n.totalChecks&&t.addIssue({code:"custom",path:["summary"],message:"Report check counts must add up."}),new Set(e.evidence.map(({kind:a,id:o})=>`${a}:${o}`)).size!==e.evidence.length&&t.addIssue({code:"custom",path:["evidence"],message:"Report evidence must be unique."})}),OF=MF.safeExtend({contentHash:H}),$F=l({schemaVersion:b("openpond.profileEvaluationSuiteRun.v1"),id:T,suiteId:T,suiteHash:H,catalogHash:H,profileId:T,sourceRevision:i().trim().min(1).max(240),harnessRelease:V,members:p(l({definitionId:T,runManifest:V,runHash:H,passed:I(),score:d().min(0).max(1).nullable()}).strict()).min(1).max(1e3),passed:I(),createdAt:pe,completedAt:pe}).strict(),NF=$F.extend({contentHash:H}).strict(),bC=l({schemaVersion:b("openpond.optimizerTrainingSample.v1"),tokenIds:p(d().int().nonnegative()).min(2).max(32768),mask:p(I()).min(2).max(32768),logprobs:p(d().finite()).min(2).max(32768),temperatures:p(d().positive().finite()).min(2).max(32768),envName:i().trim().min(1).max(200),modelRequestId:i().trim().min(1).max(1e3),promptTokenCount:d().int().positive(),completionTokenCount:d().int().positive(),servedPolicyVersion:d().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"})}),DF=l({id:T,environmentRelease:V,status:v(["completed","failed","timed_out","cancelled"]),startedAt:pe,completedAt:pe,traceRefs:p(Ia).max(1e4),metadata:jn}).strict(),HF=l({receiptRef:V,status:_b,value:d().min(0).max(1).nullable(),learningEligible:I(),passed:I(),outcomeClass:fC,failureOwner:Gm.nullable(),components:te(T,d().min(0).max(1).nullable())}).strict(),yC=l({schemaVersion:b("openpond.canonicalRolloutRecord.v1"),id:T,attemptRef:V,artifactManifestRef:V,tasksetRelease:V,environmentRelease:V,verifierSetRelease:V,harnessRelease:V,taskId:T,split:Ga,model:Im,seed:i().trim().min(1).max(500),reward:HF,traceRef:Ia,optimizerSample:bC.nullable(),environmentExecutions:p(DF).min(1).max(1e5),startedAt:pe,completedAt:pe,metadata:jn}).strict();function SC(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."})}yC.superRefine(SC);l({...yC.shape,contentHash:H}).strict().superRefine(SC);const LF=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."),xC=gt([sl(),i().max(262144),d().finite(),l({integer:LF}).strict(),l({blobBase64:i().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),RS=i().min(1).max(128).refine(e=>!e.includes("\0")),qF=l({tables:p(l({name:RS,columns:p(l({name:RS,type:v(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:p(p(xC).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."})}}),PS=l({schemaVersion:b("openpond.sqlExecution.v1"),snapshot:qF,sql:i().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:d().int().min(1).max(4096),maxResultBytes:d().int().min(256).max(262144)}).strict();rt("status",[l({status:b("completed"),columns:p(i()).max(128),rows:p(p(xC).max(128)).max(4096)}).strict(),l({status:b("rejected"),code:v(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const au=l({scope:v(["input","initialState","state","arguments"]),path:p(i().min(1).max(256)).max(16)}).strict(),AS={id:i().min(1).max(128),operation:v(["step","collect"]),toolName:i().min(1).max(500).optional(),timeoutMs:d().int().min(1).max(2e4)},UF=rt("kind",[l({...AS,kind:b("sqlite.v1"),sql:au,snapshot:au,maxRows:PS.shape.maxRows,maxResultBytes:PS.shape.maxResultBytes}).strict(),l({...AS,kind:b("javascript.v1"),source:au,cases:au,exportName:i().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:d().int().min(1).max(32),maxResultBytes:d().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."})}),zF=l({schemaVersion:b("openpond.javascriptEnvironment.v1"),id:i().trim().min(1).max(500),revision:d().int().positive(),module:gn.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:p(Qc).min(1).max(200),maxSteps:d().int().min(1).max(1e3),maxStateBytes:d().int().min(1).max(1048576),maxObservationBytes:d().int().min(1).max(262144),operationTimeoutMs:d().int().min(1).max(3e4),executionServices:p(UF).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)=>{rb(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",o,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==ct(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."})})}),BF=zF.safeExtend({contentHash:i().regex(/^[a-f0-9]{64}$/)});v(["create","reset","step","collect","destroy"]);l({state:te(i(),ie()),observation:te(i(),ie())}).strict();var FF=l({schemaVersion:b("openpond.connectedDatasetSource.v1"),kind:b("connected_activity"),id:i().min(1).max(240),profileId:i().min(1).max(240),title:i().min(1).max(500),sourceHash:i().regex(/^[a-f0-9]{64}$/),occurredAt:i().datetime(),licensingStatus:v(["pending","approved","review","blocked"]),secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),origin:dC,sourceId:i().min(1).max(500),sessionId:i().min(1).max(500),normalizerVersion:i().min(1).max(200),projection:v(["turn","conversation"]),ownerUserId:i().min(1).max(500),purpose:b("recorded_evaluation"),metadata:te(i(),ie()).default({})}).strict(),za=i().trim().min(1).max(240),mo=i().trim().min(1),Vo=i().trim().min(8).max(256),kC=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."),Qo=v(["train","validation","test","frozen_eval"]),VF=l({name:i().trim().min(1).max(500),semanticRole:v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:v(["string","integer","float","boolean","json","messages"]),nullable:I(),policy:v(["visible","privileged","metadata"])}),KF=l({schemaVersion:b("openpond.datasetSemanticSchema.v1"),fields:p(VF).min(1).max(1e4),schemaHash:Vo}),WF=l({id:za,split:Qo,path:kC,contentHash:Vo,schemaHash:Vo,sizeBytes:d().int().nonnegative(),rowCount:d().int().positive(),rowGroupCount:d().int().positive()}),Pb=l({schemaVersion:b("openpond.datasetArtifact.v1"),id:za,tasksetId:za,tasksetRevision:d().int().positive(),contentHash:Vo,format:b("parquet"),schema:KF,shards:p(WF).min(1).max(1e5),rowCount:d().int().positive(),splitCounts:te(Qo,d().int().nonnegative()),sourceReceiptRefs:p(za).min(1).max(1e5),mappingHash:Vo,qualityReportHash:Vo,createdAt:mo}),GF=l({schemaVersion:b("openpond.datasetArtifactSummary.v1"),artifactId:za,tasksetId:za,tasksetRevision:d().int().positive(),format:b("parquet"),rowCount:d().int().positive(),splitCounts:te(Qo,d().int().nonnegative()),sizeBytes:d().int().nonnegative(),contentHash:Vo,available:I(),unavailableReason:i().trim().min(1).max(2e3).nullable(),createdAt:mo}),JF=l({schemaVersion:b("openpond.datasetCatalogItem.v1"),tasksetId:za,tasksetRevision:d().int().positive(),artifactId:za.nullable(),name:i().trim().min(1).max(500),status:v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:v(["inline","parquet"]),rowCount:d().int().nonnegative(),splitCounts:te(Qo,d().int().nonnegative()),sizeBytes:d().int().nonnegative().nullable(),available:I(),unavailableReason:i().trim().min(1).max(2e3).nullable(),createdAt:mo,updatedAt:mo});l({schemaVersion:b("openpond.datasetCatalog.v1"),profileId:za,datasets:p(JF),generatedAt:mo});l({schemaVersion:b("openpond.datasetArtifactRegistry.v1"),manifest:Pb,profileId:za,storageRoot:i().trim().min(1).max(4e3),relativeManifestPath:kC,available:I(),unavailableReason:i().trim().min(1).max(2e3).nullable(),verifiedAt:mo.nullable(),createdAt:mo,updatedAt:mo});l({split:Qo.nullable().default(null),cursor:i().trim().min(1).max(2e3).nullable().default(null),limit:d().int().min(1).max(100).default(25),columns:p(i().trim().min(1).max(500)).max(100).default([])});l({schemaVersion:b("openpond.datasetRowPage.v1"),tasksetId:za,tasksetRevision:d().int().positive(),artifactHash:Vo,split:Qo.nullable(),rows:p(te(i(),ie())).max(100),nextCursor:i().max(2e3).nullable(),totalRows:d().int().nonnegative(),returnedRows:d().int().nonnegative()});var ZF=l({schemaVersion:b("openpond.datasetStorageSettings.v1"),datasetStorePath:i().trim().min(1).max(4e3),updatedAt:mo}),YF=l({id:za,label:i().trim().min(1).max(500),path:i().trim().min(1).max(4e3),datasetStorePath:i().trim().min(1).max(4e3),kind:v(["local","network","removable","cache"]),configured:I(),mounted:I(),writable:I(),totalBytes:d().int().nonnegative().nullable(),freeBytes:d().int().nonnegative().nullable()});l({schemaVersion:b("openpond.datasetStorageState.v1"),settings:ZF,storageRoots:p(YF)});l({datasetStorePath:i().trim().min(1).max(4e3)});var Hs=i().trim().min(1).max(240),QF=i().trim().min(1),Qs=i().trim().min(8).max(256),XF=te(i(),ie()).default({}),e5=i().trim().min(7).max(256),t5=v(["pending","approved","review","blocked"]),Zm=l({id:Hs,profileId:Hs,title:i().trim().min(1).max(500),sourceHash:Qs,occurredAt:QF,licensingStatus:t5,secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),metadata:XF}),n5=Zm.extend({schemaVersion:b("openpond.huggingFaceDatasetSource.v1"),kind:b("huggingface"),repositoryId:i().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:i().url().max(2e3),revision:e5,configuration:i().trim().min(1).max(500),upstreamSplits:p(i().trim().min(1).max(500)).min(1).max(1e3),gated:I(),private:I(),declaredLicense:i().trim().min(1).max(500).nullable(),sourceFileHashes:p(Qs).min(1).max(1e5)}),a5=Zm.extend({schemaVersion:b("openpond.uploadedFileDatasetSource.v1"),kind:b("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(Qs).min(1).max(1e3),totalBytes:d().int().nonnegative(),parserVersion:i().trim().min(1).max(200)}),i5=Zm.extend({schemaVersion:b("openpond.generatedDatasetSource.v1"),kind:b("generated"),generatorId:Hs,generatorVersion:i().trim().min(1).max(200),seed:d().int(),generatorHash:Qs}),o5=Zm.extend({schemaVersion:b("openpond.learningBatchDatasetSource.v1"),kind:b("learning_batch"),batch:l({id:Hs,revision:d().int().positive(),contentHash:Qs}).strict(),taskDefinition:l({id:Hs,revision:d().int().positive(),contentHash:Qs}).strict(),admittedBy:Hs}),r5=rt("kind",[n5,a5,i5,o5]),s5=l({schemaVersion:b("openpond.harnessActionBinding.v1"),actionId:Ke,modelToolName:i().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:i().trim().min(1).max(1e3),inputSchema:te(i(),ie()),actionSchemaHash:Qe,agentRelease:De,implementationHash:Qe,runtimeBindingId:Ke,capabilityReceiptHash:Qe,sideEffect:v(["read","write"]),studentVisible:I(),timeoutMs:d().int().positive().max(36e5),episodeArgumentBindings:p(l({argument:Ke,source:b("case_id")}).strict()).max(20).default([])}).strict(),Et=i().trim().min(1).max(240),Ab=i().trim().min(1),l5=i().trim().min(8).max(256),Tb=i().trim().regex(/^[a-f0-9]{64}$/),c5=i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),pi=te(i(),ie()).default({}),Ym=Et.nullable();function ud(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function d5(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var Xs=Qo,wC=v(["general","benchmark"]),IC=l({schemaVersion:b("openpond.tasksetBenchmark.v1"),definitionId:Et,releaseId:Et,releaseHash:Tb,managedReleasePath:i().trim().min(1).max(1e3).refine(ud,"Benchmark release paths must remain relative."),adaptationSplit:Xs,evaluationSplit:Xs,primaryMetric:v(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:v(["none","non_regression","all_pass"]),source:v(["builtin","imported"]),metadata:pi}),_C=l({schemaVersion:b("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:Et,releaseHash:Tb,publishedAt:Ab,metadata:pi}),u5=l({status:v(["pending","granted","denied","revoked"]),scope:v(["metadata_only","selected_turns","full_session"]),grantedBy:Ym,grantedAt:Ab.nullable(),purpose:b("task_authoring_and_evaluation")}),CC=l({schemaVersion:b("openpond.trainingSource.v1"),id:Et,profileId:Et,sessionId:Et,turnIds:p(Et).max(1e3).default([]),workspaceId:Ym,sourceHash:l5,clusterKey:Et,title:i().trim().min(1).max(500),occurredAt:Ab,consent:u5,connectedAppIds:p(Et).max(100).default([]),secretScanStatus:v(["pending","passed","blocked"]),piiScanStatus:v(["pending","passed","review","blocked"]),licensingStatus:v(["pending","approved","review","blocked"]),metadata:pi}),RC=gt([CC,r5,FF]),Eb=l({policyVisibleFields:p(Et).max(1e3).default([]),privilegedFields:p(Et).max(1e3).default([]),hiddenGraderRefs:p(Et).max(100).default([]),connectedAppScopes:p(Et).max(100).default([])}),m5=l({id:Et,sourceRefId:Et,artifactRef:i().trim().min(1).max(4e3).refine(ud,"Task asset references must be safe relative paths."),fileName:i().trim().min(1).max(500).refine(d5,"Task asset file names must not contain path separators."),mediaType:i().trim().min(1).max(200),sha256:Tb,sizeBytes:d().int().nonnegative().max(25e7),split:Xs,metadata:pi}),p5=l({path:i().trim().min(1).max(1e3).refine(ud,"Required output paths must stay inside the Work output directory."),mediaType:i().trim().min(1).max(200),schemaRef:Et.nullable().optional(),maxBytes:d().int().positive().max(1e7).optional(),metadata:pi}),Qm=l({schemaVersion:b("openpond.taskData.v1"),id:Et,clusterKey:Et,split:Xs,input:te(i(),ie()),expectedOutput:te(i(),ie()).nullable(),policyVisibleContext:te(i(),ie()).default({}),privilegedContextRef:Ym,sourceRefs:p(Et).min(1).max(100),assets:p(m5).max(1e3).optional(),resourceRefs:p(Et).max(1e3).optional(),requiredOutputs:p(p5).max(100).optional(),tags:p(Et).max(100).default([]),metadata:pi}),f5=l({id:Et,kind:v(["file","catalog","configuration","code_module"]),path:i().trim().min(1).max(1e3).refine(ud,"Environment resource paths must remain relative."),mediaType:i().trim().min(1).max(200).nullable().optional(),visibility:v(["policy_visible","policy_hidden","privileged"]),required:I(),metadata:pi}),fl=l({id:Et,taskId:Ym,sourceRefs:p(Et).min(1).max(100),artifactRef:Et,approved:I(),confidence:d().min(0).max(1),metadata:pi}),PC=fl.extend({kind:b("demonstration"),prompt:i().max(1e5).nullable().default(null),response:i().max(2e5).nullable().default(null)}),AC=fl.extend({kind:b("preference"),prompt:i().max(1e5),chosen:i().max(2e5),rejected:i().max(2e5),rationale:i().max(1e5).nullable().default(null)}),TC=fl.extend({kind:b("correction"),original:i().max(2e5),corrected:i().max(2e5),rationale:i().max(1e5).nullable().default(null)}),EC=fl.extend({kind:b("feedback"),feedback:i().max(1e5),polarity:v(["positive","negative","mixed","neutral"])}),jC=fl.extend({kind:b("reward"),task:i().max(1e5),rules:p(l({id:Et,points:d().finite(),condition:i().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:d().finite(),executable:I()}),MC=fl.extend({kind:b("label"),labelKind:b("rubric"),task:i().max(1e5),criteria:p(l({id:Et,label:i().trim().min(1).max(500),description:i().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:l({positive:i().trim().min(1).max(2e5),negative:i().trim().min(1).max(2e5),boundary:i().trim().min(1).max(2e5)})});rt("kind",[PC,AC,TC,EC,jC,MC]);var OC=l({demonstrations:p(PC).max(1e5).default([]),preferences:p(AC).max(1e5).default([]),corrections:p(TC).max(1e5).default([]),feedback:p(EC).max(1e5).default([]),rewards:p(jC).max(1e5).default([]),labels:p(MC).max(1e5).default([])}),$C=l({protocolVersion:b("openpond.taskEnvironment.v1"),kind:v(["chat","agent","program","stateful_harness","work"]),entrypoint:i().trim().min(1).max(1e3),stateful:I(),deterministicSeeds:I(),toolNames:p(Et).max(200).default([]),actionBindings:p(s5).max(200).optional(),lifecycle:p(v(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:d().int().positive().max(36e5),networkPolicy:v(["none","declared_read_only","declared_scoped"]),resources:p(f5).max(1e4).optional(),metadata:pi}),jb=l({schemaVersion:b("openpond.tasksetCapabilities.v1"),taskKind:v(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:p(v(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:p(v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:p(v(["none","exact","deterministic","model_judge","human"])),requiresTools:I(),requiresState:I(),requiresPrivilegedGrading:I(),environmentPlacements:p(v(["local","remote","colocated","provider_native"])),exportable:I(),portabilityBlockers:p(i().trim().min(1).max(2e3)).default([])}),Xm=l({id:Et,version:i().trim().min(1).max(100),label:i().trim().min(1).max(500),weight:d().min(0).max(1e3).default(1),hardGate:I().default(!1),rewardEligible:I().default(!1),privileged:I().default(!1),metadata:pi}),h5=Xm.extend({kind:v(["content","schema","file","diff","test","runtime_event","state"]),config:te(i(),ie())}),g5=Xm.extend({kind:b("model_judge"),rubric:i().trim().min(1).max(5e4),judge:kb,calibrationFixtureRefs:p(Et).min(1).max(500),calibrationStatus:v(["pending","passed","failed"]),temperature:d().min(0).max(2).default(0)}),v5=Xm.extend({kind:b("human"),form:id.optional(),rubric:i().trim().min(1).max(5e4),reviewerRole:i().trim().min(1).max(500)}),b5=Xm.extend({kind:b("custom_verifier"),runtime:n_.optional(),module:i().trim().min(1).max(1e3).refine(ud,"Custom verifier modules must use a safe relative path."),exportName:c5,timeoutMs:d().int().positive().max(3e5),networkPolicy:b("none")}),ep=gt([h5,g5,v5,b5]),Mb=v(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),NC=l({id:Et,taskId:Et,label:Mb,output:te(i(),ie()),infrastructureError:i().trim().min(1).max(1e4).nullable(),expectedPassed:I(),expectedRewardEligible:I(),metadata:pi});i().regex(/^[a-f0-9]{64}$/);var y5=l({environment:Cb,verifierSet:Rb,javascript:BF}).strict();l({actions:p(l({name:i().min(1).max(64),arguments:te(i(),ie())}).strict()).max(1e3)}).strict();var S5=l({environment:Cb,verifierSet:Rb}).strict(),x5=l({scopeId:i().trim().min(1).max(500),modelId:i().trim().min(1).max(500)}).strict();l({schemaVersion:b("openpond.modelTasksetDerivation.v1"),owner:x5,root:ea,parent:ea}).strict();var k5=l({taskset:s_,taskDefinition:ld,rewardBinding:Lm,rewards:p(rd).min(1).max(100),assets:p(Bm).max(1e3),executionResources:S5.optional(),execution:y5.optional(),instructionMode:b("per_task").optional()}).strict(),w5=l({batch:fb,evidence:p(zm).min(1).max(1e4),decisions:p(pb).min(1).max(1e4),sources:p(Um).min(1).max(1e4),assets:p(Bm).max(1e3)}).strict(),I5=64*1024*1024,_5=l({asset:li,base64:i().max(Math.ceil(I5/3)*4)}).strict();l({schemaVersion:b("openpond.connectedRewardCalibrationProjection.v1"),sourceReward:Yo,fixtureSet:li,calibrationCheck:lt,fixture:T_,fixtureHash:i().regex(/^[a-f0-9]{64}$/),checkResultHash:i().regex(/^[a-f0-9]{64}$/),independentCalibrationTask:b(!0),closureRef:li,graderId:i().min(1).max(240).optional()}).strict();var C5=k5.omit({taskset:!0,executionResources:!0}),R5=l({schemaVersion:b("openpond.tasksetPackage.v1"),taskset:s_,environment:Cb,verifierSet:Rb,files:p(_5).max(1e4),modelResources:C5.optional(),learningResources:w5.optional()}).strict(),Tr=R5.extend({contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict(),Ti=i().trim().min(1).max(500),Iu=i().regex(/^[a-f0-9]{64}$/),P5=I4.pick({portableProjectId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,sourceRevision:!0,sourceUpdatedAt:!0}).extend({trainingSetup:yb.omit({tasksetRef:!0,rewardBindingRef:!0,tasksetRelease:!0})}).strict();l({schemaVersion:b("openpond.tasksetPackagePublication.v1"),operationId:Ti,modelProjectId:Ti,expectedProjectEtag:Iu.nullable(),name:i().trim().min(1).max(200),description:i().max(5e3),buildIntent:v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),methodHint:v(["sft","dpo","grpo","ppo"]).nullable(),package:Tr,modelConfiguration:P5.optional(),evaluationPackage:Tr.optional(),selection:v(["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&&Pt(e.modelConfiguration.trainingSetup.evaluationTasksetRef)===Pt(Mz(e.evaluationPackage.taskset)),"Evaluation package must match the selected immutable evaluation in Model configuration.");l({schemaVersion:b("openpond.tasksetPackageReceipt.v1"),teamId:Ti,modelProjectId:Ti,operationId:Ti,taskset:Ju,packageHash:Iu,hostedTasksetId:Ti,projectEtag:Iu,project:Fm.optional(),selection:v(["select","attach"]).optional(),evaluation:l({taskset:Ju,packageHash:Iu,hostedTasksetId:Ti}).strict().optional()}).strict();l({schemaVersion:b("openpond.tasksetPackageReadback.v1"),teamId:Ti,modelProjectId:Ti,package:Tr}).strict();l({schemaVersion:b("openpond.tasksetReleasePackageReadback.v1"),teamId:Ti,release:Ju,package:Tr}).strict();var ji=i().trim().min(1).max(240),jc=i().trim().min(1),tm=i().trim().min(8).max(256),DC=te(i(),ie()).default({}),A5=ji.nullable(),T5=["work_capabilities","work_environment","work_list_files","work_read_file","work_read_document","work_write_file","work_write_docx","work_edit_file","work_delete_file","work_exec","work_save_output","work_stop"],E5=v(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),HC=v(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Gn=i().trim().max(1e5),LC=rt("kind",[l({kind:b("demonstrations"),behavior:Gn,examples:p(l({id:ji,prompt:Gn,response:Gn})).max(1e3).default([])}),l({kind:b("preferences"),preference:Gn,pairs:p(l({id:ji,prompt:Gn,chosen:Gn,rejected:Gn,rationale:Gn})).max(1e3).default([])}),l({kind:b("verifiable_reward"),task:Gn,rules:p(l({id:ji,points:d().finite(),condition:Gn})).max(1e3).default([]),otherwisePoints:d().finite().default(0)}),l({kind:b("rubric"),task:Gn,criteria:p(l({id:ji,label:i().trim().max(500),description:Gn})).max(1e3).default([]),positiveExample:Gn,negativeExample:Gn,boundaryExample:Gn})]),j5=l({path:i().trim().min(1).max(1e3),role:v(["environment","verifier","fixture"]),content:i().max(25e4)}),qC=l({primaryMethod:v(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:l({method:b("sft"),purpose:b("trajectory_bootstrap"),demonstrationRefs:p(ji).min(1).max(1e5),limitations:p(i().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),UC=v(["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"]),M5=l({method:v(["sft","dpo","grpo","ppo"]),status:v(["recommended","compatible","needs_dataset_work"]),reasonCodes:p(UC).default([]),reasons:p(i().trim().min(1).max(5e3)).default([])}),TS=l({code:ji,message:i().trim().min(1).max(5e3),path:i().trim().max(2e3).nullable()}),zC=l({schemaVersion:b("openpond.tasksetReadiness.v1"),tasksetId:ji,tasksetHash:tm,ready:I(),recommendedMethod:v(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:qC.nullable().default(null),methodReadiness:p(M5).default([]),compatibleDestinationClasses:p(v(["export","custom","hosted_managed"])),blockers:p(TS).default([]),advisories:p(TS).default([]),warnings:p(i().trim().min(1).max(5e3)).default([]),generatedAt:jc}),BC=l({attempt:d().int().positive(),summary:i().trim().min(1).max(5e3),createdAt:jc}),O5=l({schemaVersion:b("openpond.taskAuthoringProvenance.v1"),model:kb.nullable(),modelConfig:DC,skillHash:tm,promptTemplateVersion:i().trim().min(1).max(200),buildIntent:HC.default("demonstrations"),buildSpecification:LC.nullable().default(null),evidenceHashes:p(tm).max(1e5),tasksetSdkVersion:i().trim().min(1).max(100),sourceCommit:i().trim().min(1).max(256).nullable(),repairHistory:p(BC).max(1e3),createdAt:jc}),Mc=l({schemaVersion:b("openpond.taskset.v1"),id:ji,revision:d().int().positive().default(1),profileId:ji,profileRelease:E4.nullable().optional(),createImproveRunId:A5.default(null),name:i().trim().min(1).max(500),objective:i().trim().max(2e4),purpose:wC.default("general"),benchmark:IC.nullable().default(null),preferenceComparison:_C.nullable().default(null),status:E5,sourceRefs:p(RC).min(1).max(1e5),datasetArtifact:Pb.nullable().optional(),policy:Eb,environment:$C,capabilities:jb,metrics:ad.optional(),tasks:p(Qm).max(1e6),graders:p(ep).min(1).max(1e3),graderFixtures:p(NC).max(1e5),learningSignals:OC,authoringProvenance:O5,readiness:zC.nullable(),contentHash:tm,createdAt:jc,updatedAt:jc,metadata:DC}).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 FC(e){return e.schemaVersion==="openpond.trainingSource.v1"}function $5(e,t={}){const n=Mc.safeParse(e);if(!n.success)return{valid:!1,taskset:null,computedHash:null,issues:n.error.issues.map(s=>({code:"schema_invalid",severity:"error",message:s.message,path:s.path.join(".")}))};const a=n.data,o=[];L5(a,o),D5(a,o),q5(a,o),z5(a,o),B5(a,o),N5(a,o,t),F5(a,o),V5(a.capabilities,o,a),U5(a,o);const r=VC(a);return a.contentHash!==r&&o.push({code:"content_hash_mismatch",severity:"error",message:`Taskset contentHash is ${a.contentHash}, expected ${r}.`,path:"contentHash"}),{valid:!o.some(s=>s.severity==="error"),taskset:a,computedHash:r,issues:o}}function N5(e,t,n){const a=e.graders.length>0&&e.graders.every(s=>s.kind==="human");!a&&!e.graderFixtures.length&&!(n.allowUnscoredOnlineRewardBatch&&e.metadata.trainingMethod==="grpo"&&e.metadata.learning)&&t.push({code:"grader_fixtures_required",severity:"error",message:"Taskset admission requires authored grader fixtures.",path:"graderFixtures"});const o=new Set(e.tasks.map(s=>s.id)),r=new Set(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]);for(const s of e.graderFixtures)!e.datasetArtifact&&!o.has(s.taskId)&&t.push({code:"grader_fixture_task_missing",severity:"warning",message:`Fixture ${s.id} references a task outside this Taskset revision (${s.taskId}).`,path:`graderFixtures.${s.id}.taskId`}),r.delete(s.label),s.label==="infrastructure_failure"&&!s.infrastructureError&&t.push({code:"infrastructure_fixture_error_missing",severity:"error",message:`Infrastructure fixture ${s.id} must declare an infrastructure error.`,path:`graderFixtures.${s.id}.infrastructureError`});for(const s of a?[]:r)t.push({code:"grader_fixture_missing",severity:"warning",message:`Taskset does not include the optional ${s} grader calibration fixture.`,path:"graderFixtures"})}function D5(e,t){const n=e.datasetArtifact;if(!n)return;(n.tasksetId!==e.id||n.tasksetRevision!==e.revision)&&t.push({code:"dataset_artifact_taskset_mismatch",severity:"error",message:"Dataset artifact identity does not match its Taskset revision.",path:"datasetArtifact"});const a=Object.values(n.splitCounts).reduce((m,u)=>m+u,0),o=n.shards.reduce((m,u)=>m+u.rowCount,0);(a!==n.rowCount||o!==n.rowCount)&&t.push({code:"dataset_artifact_row_count_mismatch",severity:"error",message:"Dataset artifact row, split, and shard counts do not agree.",path:"datasetArtifact.rowCount"});const r=new Map;for(const m of n.shards)r.set(m.split,(r.get(m.split)??0)+m.rowCount);for(const[m,u]of Object.entries(n.splitCounts))(r.get(m)??0)!==u&&t.push({code:"dataset_artifact_split_count_mismatch",severity:"error",message:`Dataset artifact ${m} shard counts do not match its manifest.`,path:`datasetArtifact.splitCounts.${m}`});const{contentHash:s,...c}=n;Pt(c)!==n.contentHash&&t.push({code:"dataset_artifact_hash_mismatch",severity:"error",message:"Dataset artifact manifest content hash is invalid.",path:"datasetArtifact.contentHash"})}function H5(e){return VC(e)}function VC(e){const{contentHash:t,status:n,readiness:a,updatedAt:o,...r}=e;return Pt(r)}function L5(e,t){for(const[n,a]of e.sourceRefs.entries())FC(a)&&a.consent.status!=="granted"&&t.push({code:"source_consent_missing",severity:"error",message:`Source ${a.id} is not consented.`,path:`sourceRefs.${n}.consent.status`}),a.secretScanStatus!=="passed"&&t.push({code:"source_secret_scan",severity:"error",message:`Source ${a.id} did not pass secret scanning.`,path:`sourceRefs.${n}.secretScanStatus`}),a.piiScanStatus!=="passed"&&t.push({code:"source_pii_scan",severity:"error",message:`Source ${a.id} has unresolved PII policy.`,path:`sourceRefs.${n}.piiScanStatus`}),a.licensingStatus!=="approved"&&t.push({code:"source_license",severity:"error",message:`Source ${a.id} has unresolved licensing policy.`,path:`sourceRefs.${n}.licensingStatus`})}function q5(e,t){const n=new Map;for(const o of e.tasks){const r=n.get(o.clusterKey)??new Set;r.add(o.split),n.set(o.clusterKey,r)}for(const[o,r]of n)r.size>1&&t.push({code:"split_cluster_contamination",severity:"error",message:`Source cluster ${o} appears in multiple splits: ${[...r].join(", ")}.`,path:"tasks"});(e.datasetArtifact?e.datasetArtifact.splitCounts.frozen_eval??0:e.tasks.filter(o=>o.split==="frozen_eval").length)===0&&t.push({code:"frozen_eval_missing",severity:"warning",message:"Add an independent test example before training.",path:"tasks"})}function U5(e,t){if(e.environment.kind!=="work")return;e.environment.entrypoint!=="openpond-work-v1"&&t.push({code:"work_entrypoint_invalid",severity:"error",message:"Work Tasksets must use the openpond-work-v1 entrypoint.",path:"environment.entrypoint"}),(!e.environment.lifecycle.includes("reset")||!e.environment.lifecycle.includes("cleanup"))&&t.push({code:"work_reset_lifecycle_missing",severity:"error",message:"Work attempts require reset and cleanup; filesystem state belongs to one attempt.",path:"environment.lifecycle"});const n=new Set(T5),a=e.environment.toolNames.filter(r=>!n.has(r));a.length&&t.push({code:"work_tool_unknown",severity:"error",message:`Work Taskset declares unknown tools: ${a.join(", ")}.`,path:"environment.toolNames"}),e.environment.toolNames.includes("work_save_output")||t.push({code:"work_output_tool_missing",severity:"error",message:"Work Tasksets must declare work_save_output.",path:"environment.toolNames"});for(const r of["create","reset","step","grade","cleanup"])e.environment.lifecycle.includes(r)||t.push({code:"work_lifecycle_incomplete",severity:"error",message:`Work Tasksets require the ${r} lifecycle stage.`,path:"environment.lifecycle"});const o=new Map(e.sourceRefs.map(r=>[r.id,r]));for(const[r,s]of e.tasks.entries()){const c=new Set,m=new Set;for(const[f,g]of(s.assets??[]).entries()){const S=`tasks.${r}.assets.${f}`;c.has(g.id)&&t.push({code:"work_asset_duplicate_id",severity:"error",message:`Task ${s.id} repeats asset id ${g.id}.`,path:`${S}.id`}),m.has(g.fileName)&&t.push({code:"work_asset_duplicate_name",severity:"error",message:`Task ${s.id} repeats staged file name ${g.fileName}.`,path:`${S}.fileName`}),c.add(g.id),m.add(g.fileName),s.sourceRefs.includes(g.sourceRefId)||t.push({code:"work_asset_task_source_missing",severity:"error",message:`Asset ${g.id} references source ${g.sourceRefId} outside task ${s.id}.`,path:`${S}.sourceRefId`});const k=o.get(g.sourceRefId);k?"sourceFileHashes"in k&&!k.sourceFileHashes.includes(g.sha256)&&t.push({code:"work_asset_hash_unregistered",severity:"error",message:`Asset ${g.id} hash is not registered by source ${g.sourceRefId}.`,path:`${S}.sha256`}):t.push({code:"work_asset_source_missing",severity:"error",message:`Asset ${g.id} references missing source ${g.sourceRefId}.`,path:`${S}.sourceRefId`}),k&&"kind"in k&&k.kind==="uploaded_file"&&!k.originalFileNames.includes(g.fileName)&&t.push({code:"work_asset_name_unregistered",severity:"error",message:`Asset ${g.id} file name is not registered by source ${g.sourceRefId}.`,path:`${S}.fileName`}),k&&"kind"in k&&k.kind==="uploaded_file"&&!k.mediaTypes.includes(g.mediaType)&&t.push({code:"work_asset_media_type_unregistered",severity:"error",message:`Asset ${g.id} media type is not registered by source ${g.sourceRefId}.`,path:`${S}.mediaType`}),g.split!==s.split&&t.push({code:"work_asset_split_mismatch",severity:"error",message:`Asset ${g.id} is assigned to ${g.split}, not task split ${s.split}.`,path:`${S}.split`})}const u=new Set;for(const[f,g]of(s.requiredOutputs??[]).entries()){const S=g.path.replaceAll("\\","/"),k=`tasks.${r}.requiredOutputs.${f}.path`;u.has(S)&&t.push({code:"work_output_duplicate_path",severity:"error",message:`Task ${s.id} repeats required output path ${S}.`,path:k}),u.add(S)}(s.requiredOutputs??[]).length===0&&t.push({code:"work_output_missing",severity:"error",message:`Work task ${s.id} must declare at least one required output.`,path:`tasks.${r}.requiredOutputs`})}}function z5(e,t){const n=new Set(e.policy.policyVisibleFields);for(const a of e.policy.privilegedFields)n.has(a)&&t.push({code:"privileged_field_visible",severity:"error",message:`Field ${a} is both policy-visible and privileged.`,path:"policy"});for(const a of e.tasks)a.privilegedContextRef&&Object.keys(a.policyVisibleContext).includes(a.privilegedContextRef)&&t.push({code:"privileged_context_leak",severity:"error",message:`Task ${a.id} exposes its privileged context reference.`,path:`tasks.${a.id}.policyVisibleContext`})}function B5(e,t){const n=new Set;for(const a of e.graders)n.has(a.id)&&t.push({code:"grader_duplicate",severity:"error",message:`Duplicate grader id ${a.id}.`,path:"graders"}),n.add(a.id),a.kind==="model_judge"&&a.rewardEligible&&a.calibrationStatus!=="passed"&&t.push({code:"judge_calibration_pending",severity:"warning",message:`Model judge ${a.id} is selected for reward without a passing advisory calibration report.`,path:`graders.${a.id}`}),a.kind==="model_judge"&&a.calibrationStatus==="passed"&&typeof a.metadata.calibrationEvidenceHash!="string"&&t.push({code:"judge_calibration_evidence_missing",severity:"warning",message:`Model judge ${a.id} declares calibration without an OpenPond fixture evidence hash.`,path:`graders.${a.id}.metadata.calibrationEvidenceHash`}),a.kind==="human"&&a.rewardEligible&&t.push({code:"human_online_reward",severity:"error",message:`Human grader ${a.id} cannot be an online optimizer reward.`,path:`graders.${a.id}`})}function F5(e,t){const n=new Set(e.tasks.map(o=>o.id)),a=new Set(e.sourceRefs.map(o=>o.id));for(const o of[...e.learningSignals.demonstrations,...e.learningSignals.preferences,...e.learningSignals.corrections,...e.learningSignals.feedback,...e.learningSignals.rewards,...e.learningSignals.labels])o.taskId&&!e.datasetArtifact&&!n.has(o.taskId)&&t.push({code:"learning_signal_task_missing",severity:"error",message:`Signal ${o.id} references missing task ${o.taskId}.`,path:`learningSignals.${o.kind}.${o.id}.taskId`}),o.sourceRefs.some(r=>!a.has(r))&&t.push({code:"learning_signal_source_missing",severity:"error",message:`Signal ${o.id} references a source outside the Dataset.`,path:`learningSignals.${o.kind}.${o.id}.sourceRefs`});for(const o of e.learningSignals.preferences)o.chosen.trim()===o.rejected.trim()&&t.push({code:"preference_pair_identical",severity:"error",message:`Preference ${o.id} has identical chosen and rejected responses.`,path:`learningSignals.preferences.${o.id}`});for(const o of e.learningSignals.rewards)o.executable||t.push({code:"reward_not_executable",severity:"warning",message:`Reward ${o.id} is a reviewed specification but has no executable verifier yet.`,path:`learningSignals.rewards.${o.id}.executable`})}function V5(e,t,n){!e.exportable&&e.portabilityBlockers.length===0&&t.push({code:"portability_reason_missing",severity:"error",message:"Non-exportable Tasksets must declare a portability blocker.",path:"capabilities.portabilityBlockers"}),e.compatibleMethods.includes("grpo")&&!e.rewardKinds.some(a=>a==="exact"||a==="deterministic"||a==="model_judge")&&t.push({code:"grpo_reward_missing",severity:"error",message:"GRPO compatibility requires a scalar reward kind.",path:"capabilities.rewardKinds"}),n?.capabilities.compatibleMethods.includes("sft")&&n.learningSignals.demonstrations.length===0&&t.push({code:"sft_demonstrations_missing",severity:"error",message:"SFT compatibility requires approved demonstrations.",path:"learningSignals.demonstrations"}),n?.capabilities.compatibleMethods.includes("dpo")&&n.learningSignals.preferences.length===0&&t.push({code:"dpo_preferences_missing",severity:"error",message:"DPO compatibility requires chosen and rejected response pairs.",path:"learningSignals.preferences"}),n&&(n.capabilities.compatibleMethods.includes("grpo")||n.capabilities.compatibleMethods.includes("ppo"))&&!n.learningSignals.rewards.some(a=>a.executable)&&!n.graders.some(a=>a.rewardEligible&&a.weight>0&&a.kind!=="human")&&t.push({code:"online_reward_not_executable",severity:"error",message:"GRPO/PPO compatibility requires an executable scalar reward.",path:"learningSignals.rewards"})}var As=i().trim().min(1).max(240),ES=i().trim().min(1),K5=i().trim().min(8).max(256),W5=i().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),G5=te(i(),ie()).default({});function jS(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var KC=Qm.extend({sourceRefs:p(As).max(100).default([])}),WC=v(["draft","validating","needs_review","published"]),J5=l({enabled:I(),candidateCount:d().int().min(2).max(4),minimumSamples:d().int().min(1).max(1e4).default(100),allowTies:I(),allowRejectAll:I(),rubric:i().trim().max(5e4),criteria:p(l({id:As,label:i().trim().min(1).max(500),description:i().trim().max(1e4),weight:d().nonnegative().max(1e3)})).max(100)}),Z5=l({mode:v(["text","structured_json","artifacts"]),jsonSchema:te(i(),ie()).nullable(),renderer:l({module:i().trim().min(1).max(1e3).refine(jS,"Renderer modules must use a safe relative path."),exportName:W5,configRef:i().trim().min(1).max(1e3).refine(jS,"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"]})}),Fa=l({schemaVersion:b("openpond.tasksetDraft.v1"),id:As,revision:d().int().positive(),profileId:As,modelScope:l({modelId:As,expectedModelRevision:d().int().positive(),source:d4.optional()}).strict().nullable().default(null),name:i().trim().max(500),objective:i().trim().max(2e4),purpose:wC.default("general"),benchmark:IC.nullable().default(null),preferenceComparison:_C.nullable().default(null),status:WC,sourceRefs:p(RC).max(1e5).default([]),datasetArtifact:Pb.nullable().optional(),policy:Eb,environment:$C,output:Z5.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:jb,metrics:ad,review:J5,tasks:p(KC).max(1e6).default([]),graders:p(ep).max(1e3).default([]),graderFixtures:p(NC).max(1e5).default([]),learningSignals:OC,publishedTasksetRef:l({id:As,revision:d().int().positive(),contentHash:K5}).nullable(),createdAt:ES,updatedAt:ES,metadata:G5}).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"]})}),Y5=6e6,Q5=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 X5(e){const t=cd.parse(e);return!Q5.has(t)&&!t.startsWith("source-artifacts/")}function MS(e,t){const n=X5(e);if(t.byteLength>Y5)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)?OS(t):{encoding:"utf8",data:o}}catch{a=OS(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:K_(t)}}function OS(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 $S=64*1024*1024,GC=i().regex(/^[a-f0-9]{64}$/),e3=l({path:cd,contentHash:GC,sizeBytes:d().int().nonnegative().max($S),base64:i().max($S)}).strict(),t3=l({schemaVersion:b("openpond.tasksetDraftWorkspace.v1"),draft:Fa,files:p(e3).max(1e4)}).strict(),Nae=t3.extend({contentHash:GC}).strict(),NS=class extends Error{issues;constructor(e){super(e.map(t=>t.message).join(`
|
|
184
|
+
`)),this.name="TasksetDraftPublishError",this.issues=e}};function n3(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.graders.length>0&&e.graders.every(o=>o.kind==="human"))&&e.graderFixtures.length===0&&t.push({code:"grader_fixtures_missing",message:"Add grader fixtures before publishing.",path:"graderFixtures"});const a=new Set(e.sourceRefs.map(o=>o.id));for(const o of e.tasks)for(const r of o.sourceRefs)a.has(r)||t.push({code:"task_source_missing",message:`Task ${o.id} references missing source ${r}.`,path:`tasks.${o.id}.sourceRefs`});return t}function Dae(e){const t=Fa.parse(e.draft),n=e.now??new Date().toISOString(),a=n3(t);if(a.length)throw new NS(a);const o=t.modelScope?.source;if(o&&e.tasksetId&&e.tasksetId!==o.tasksetId)throw new Error("Taskset draft publication differs from its prepared identity.");const r=o?.tasksetId||e.tasksetId?.trim()||t.publishedTasksetRef?.id||t.id.replace(/-draft$/,""),s=o?.tasksetRevision??(t.publishedTasksetRef?.id===r?t.publishedTasksetRef.revision+1:1),c=t.sourceRefs.length?t.sourceRefs:[a3(t,r,n)],m=c[0].id,u=t.tasks.map(O=>Qm.parse({...O,sourceRefs:O.sourceRefs.length?O.sourceRefs:[m],metadata:{exampleOrigin:"expert_authored",...O.metadata}})),f=t.capabilities.compatibleMethods.find(O=>O!=="none"&&O!=="retrieval")??null,g=i3(t),S=t.graders.filter(O=>O.rewardEligible&&O.weight>0&&O.kind!=="human"),k=f===null&&g==="verifiable_reward"&&S.length>0,C=f??(k?"grpo":null),P=Mc.parse({schemaVersion:"openpond.taskset.v1",id:r,revision:s,profileId:t.profileId,profileRelease:null,createImproveRunId:null,name:t.name,objective:t.objective,purpose:t.purpose,benchmark:t.benchmark,preferenceComparison:t.preferenceComparison,status:"needs_review",sourceRefs:c,datasetArtifact:t.datasetArtifact??null,policy:t.policy,environment:t.environment,capabilities:k?{...t.capabilities,compatibleMethods:["grpo"],rewardKinds:[...new Set(S.map(O=>O.kind==="model_judge"?"model_judge":"deterministic"))]}:t.capabilities,metrics:t.metrics,tasks:u,graders:t.graders,graderFixtures:t.graderFixtures,learningSignals:t.learningSignals,authoringProvenance:{schemaVersion:"openpond.taskAuthoringProvenance.v1",model:null,modelConfig:{},skillHash:Pt("openpond-taskset-draft-authoring-v1"),promptTemplateVersion:"taskset-draft-v1",buildIntent:g,buildSpecification:null,evidenceHashes:c.map(O=>O.sourceHash),tasksetSdkVersion:"draft-v1",sourceCommit:null,repairHistory:[],createdAt:n},readiness:null,contentHash:"00000000",createdAt:s===1?t.createdAt:n,updatedAt:n,metadata:{...t.metadata,...o?{modelTasksetAuthoring:o.lineage}:{},tasksetReviewPolicy:t.review,tasksetOutputContract:t.output,...e.sourcePackageHash?{sourcePackageHash:e.sourcePackageHash}:{},...C?{trainingMethod:C}:{},diagnosis:{schemaVersion:"openpond.capabilityDiagnosis.v1",summary:t.objective,stableBehavior:[t.objective],changingKnowledge:[],requiredContext:[],requiredTools:t.environment.toolNames,intervention:C==="dpo"?"preference":C==="grpo"||C==="ppo"?"grpo_rft":C==="sft"?"sft":"no_training",trainingEligible:C!==null,rationale:C?[`The author selected ${C.toUpperCase()} compatibility.`]:["The Taskset is currently configured for evaluation only."],confidence:1}}}),j=Mc.parse({...P,contentHash:H5(P)}),$=$5(j).issues.filter(O=>O.severity==="error");if($.length)throw new NS($.map(O=>({code:O.code,message:O.message,path:O.path})));return j}function a3(e,t,n){const a=Pt({draftId:e.id,draftRevision:e.revision,tasks:e.tasks});return{schemaVersion:"openpond.generatedDatasetSource.v1",kind:"generated",id:`source-${t}`,profileId:e.profileId,title:`${e.name} manual authoring`,sourceHash:a,occurredAt:n,licensingStatus:"approved",secretScanStatus:"passed",piiScanStatus:"passed",generatorId:"openpond-taskset-draft",generatorVersion:"1",seed:0,generatorHash:a,metadata:{draftId:e.id,draftRevision:e.revision}}}function i3(e){return e.learningSignals.preferences.length?"preferences":e.learningSignals.rewards.length?"verifiable_reward":e.learningSignals.labels.length?"rubric":!e.capabilities.compatibleMethods.some(t=>t!=="none"&&t!=="retrieval")&&e.graders.some(t=>t.rewardEligible&&t.weight>0&&t.kind!=="human")?"verifiable_reward":"demonstrations"}var Ls=i().regex(/^[a-f0-9]{64}$/),JC=l({providerId:b("claude-code"),configurationHash:Ls,executableHash:Ls,version:i().regex(/^2\.\d+\.\d+$/),capabilityHash:Ls,maximumRequestCostUsd:d().finite().positive().max(1e4),requestTimeoutMs:d().int().min(1e3).max(3e5),maximumTurns:d().int().min(1).max(100),holdOpen:I()}).strict();l({id:i().min(1).max(200),receiptId:i().min(1).max(200),sessionId:wm(),operationId:i().min(1).max(200),action:v(["message","seal"]),text:i().max(262144).optional()}).strict().superRefine((e,t)=>{e.action==="message"&&!e.text?.trim()&&t.addIssue({code:"custom",message:"A human intervention requires a message."}),e.action==="seal"&&e.text!==void 0&&t.addIssue({code:"custom",message:"Sealing does not add a prompt."})});var o3=l({provider:b("claude-code"),sessionId:wm(),requestId:i().min(1).max(200),modelId:i().min(1).max(500),runtime:JC,sourceHash:Ls,outputHash:Ls,traceHash:Ls,runtimeEventRefs:p(i().min(1).max(200)).min(1).max(2e4),eventCount:d().int().positive().max(2e4),startedAt:nn(),completedAt:nn(),cleanupComplete:b(!0)}).strict().superRefine((e,t)=>{(e.runtimeEventRefs.length!==e.eventCount||new Set(e.runtimeEventRefs).size!==e.eventCount)&&t.addIssue({code:"custom",message:"Process event references must match the exact retained trace population."})}),tp=l({id:i().trim().min(1).max(240),revision:d().int().positive(),contentHash:i().regex(/^[a-f0-9]{64}$/),targetId:i().trim().min(1).max(240).nullable()}).strict(),r3=p(l({role:v(["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."})}),ZC=l({schemaVersion:b("openpond.experimentAttemptGrade.v1"),selectionHash:i().regex(/^[a-f0-9]{64}$/),grades:p(u_).min(1).max(100),score:d().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),gradingStatus:v(["scored","pending","unscorable","not_configured"]),failureClass:V_.nullable(),contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;Pt(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,...c}=r;Pt(c)!==s&&t.addIssue({code:"custom",message:"A retained criterion changed."});for(const m of r.components){const{contentHash:u,...f}=m;Pt(f)!==u&&t.addIssue({code:"custom",message:"A retained grader result changed."})}}}),tn=i().trim().min(1).max(200),kr=i().regex(/^[a-f0-9]{64}$/),YC=rt("kind",[l({kind:b("hosted_chat"),modelId:tn,localRuntime:gt([l({providerId:b("custom-openai-compatible"),configurationHash:kr,maximumRequestCostUsd:d().finite().positive().max(1e4),requestTimeoutMs:d().int().min(1e3).max(3e5)}).strict(),JC]).optional(),candidate:l({artifactId:tn,contentHash:kr,preparationId:tn,dispatchId:tn,baseProfileId:tn,workerImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),harness:sd.optional(),messages:r3.optional(),maxOutputTokens:d().int().min(1).max(4096).default(1024),temperature:d().min(0).max(2).default(0),topP:d().gt(0).max(1).default(1)}).strict(),l({kind:b("fixture"),fixtureId:tn}).strict()]),s3=l({schemaVersion:b("openpond.modelStarterAttemptRequest.v1"),operationId:tn,teamId:tn,modelProjectId:tn.nullable(),project:tp.optional(),taskset:ea,taskId:tn,environmentSeed:d().int().min(0).max(2147483647).default(0),policy:YC}).strict();l({modelProjectId:tn.nullable(),taskset:ea,afterTaskId:tn.optional(),limit:d().int().min(1).max(100).default(25)}).strict();l({modelProjectId:tn.nullable(),taskset:ea,available:I(),unavailableReason:i().max(1e3).nullable(),models:p(l({id:tn,name:i().max(500)}).strict()).max(200),tasks:p(l({id:tn,split:Ga,inputPreview:i().max(500),fixtures:p(l({id:tn,label:i().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:tn.nullable()}).strict();var Ob=l({schemaVersion:b("openpond.modelStarterAttemptSummary.v1"),id:tn,revision:d().int().positive(),request:s3,status:v(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:l({modelId:tn,provider:tn,upstreamModelId:i().min(1).max(500),configurationHash:kr}).strict().nullable(),createdAt:nn(),startedAt:nn().nullable(),completedAt:nn().nullable(),cleanupComplete:I(),resultAvailable:I(),score:d().min(0).max(1).nullable(),gradingStatus:v(["not_started","pending","scored","unscorable","not_configured"]).default("not_started"),passed:I().nullable(),outputPreview:i().max(500).nullable(),error:l({code:tn,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."})});l({modelProjectId:tn,afterId:tn.optional(),limit:d().int().min(1).max(100).default(25)}).strict();l({items:p(Ob).max(100),nextCursor:tn.nullable()}).strict();l({schemaVersion:b("openpond.modelStarterAttemptResult.v1"),attempt:Ob,output:i().max(1048576).nullable(),messages:p(te(i(),ie())).max(4002),composition:Cc.nullable(),grade:u_.nullable().optional(),experimentGrade:ZC.nullable().optional(),environment:l({status:v(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:I(),definition:ea,initialStateHash:kr.nullable(),finalStateHash:kr.nullable(),attemptHash:kr}).strict(),native:ub.optional(),providerRequestIds:p(tn).max(1001),contentHash:kr}).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||Pt(n)!==Pt(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!==Pt(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 fs=i().trim().min(1).max(240),fh=i().regex(/^[a-f0-9]{64}$/),QC=l({kind:b("hosted_harness"),modelId:fs,candidate:l({artifactId:fs,contentHash:fh,preparationId:fs,dispatchId:fs,baseProfileId:fs,workerImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),sourceCandidate:Zs.shape.sourceCandidate,reasoningEffort:v(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:fs,source:Zs,modelConfigurationHash:fh,packageHash:fh,externalDatasetBinding:Wo.optional()}).strict().superRefine((e,t)=>{JSON.stringify(e.externalDatasetBinding??null)!==JSON.stringify(e.source.externalDatasetBinding??null)&&t.addIssue({code:"custom",message:"The policy and source must bind the same external Dataset recipe."}),JSON.stringify(e.sourceCandidate??null)!==JSON.stringify(e.source.sourceCandidate??null)&&t.addIssue({code:"custom",message:"The policy and prepared source must bind the same actual source candidate."})}),si=i().trim().min(1).max(200),XC=i().regex(/^[a-f0-9]{64}$/),l3=rt("kind",[YC.options[0],l({kind:b("fixture")}).strict(),QC]),hl=l({schemaVersion:b("openpond.modelTasksetRunRequest.v1"),operationId:si,teamId:si,modelProjectId:si.nullable(),name:i().trim().min(1).max(200).optional(),project:tp.optional(),taskset:ea,policy:l3,population:p(vC).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=>bb([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."})}),eR=l({schemaVersion:b("openpond.modelTasksetRunSummary.v1"),id:si,revision:d().int().positive(),teamId:si,modelProjectId:si.nullable(),name:i().trim().min(1).max(200).optional(),project:tp.optional(),operationId:si,taskset:ea,policyKind:v(["hosted_chat","fixture","hosted_harness"]),manifestHash:XC,status:v(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:d().int().min(1).max(1e4),counts:l({pending:d().int().nonnegative(),running:d().int().nonnegative(),completed:d().int().nonnegative(),failed:d().int().nonnegative(),cancelled:d().int().nonnegative()}).strict(),createdAt:nn(),startedAt:nn().nullable(),completedAt:nn().nullable(),cleanupComplete:I(),resultAvailable:I(),score:d().min(0).max(1).nullable(),metricName:i().min(1).max(240),error:l({code:si,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."})}),tR=l({summary:eR,request:hl,manifest:Jm,policySnapshot:Ob.shape.policySnapshot}).strict();l({modelProjectId:si.optional(),projectId:tp.shape.id.optional(),afterId:si.optional(),limit:d().int().min(1).max(100).default(25)}).strict();l({items:p(eR).max(100),nextCursor:si.nullable()}).strict();l({schemaVersion:b("openpond.modelTasksetRunResult.v1"),run:tR,receipts:p(gF).min(1).max(1e4),metric:ib.nullable(),contentHash:XC}).strict();var nR=i().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),c3=p(nR).min(1).max(20),DS=v(["input","output","expectedOutput","evaluatorContext"]),d3=l({destination:DS,path:c3,source:DS,sourcePath:p(nR).max(20)}).strict(),$b=p(d3).max(100).superRefine((e,t)=>{for(const[n,a]of e.entries())e.slice(0,n).some(o=>o.destination===a.destination&&(HS(o.path,a.path)||HS(a.path,o.path)))&&t.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function HS(e,t){return e.length<=t.length&&e.every((n,a)=>n===t[a])}var Qn=i().trim().min(1).max(200),Er=i().regex(/^[a-f0-9]{64}$/),md=l({id:Qn,revision:d().int().positive(),contentHash:Er}).strict(),Ni=l({id:Qn,version:i().min(1).max(200),contentHash:Er,name:i().trim().min(1).max(500).optional(),feedbackKey:od,release:md.nullable(),mappings:$b.optional()}).strict(),Nb=l({id:Qn,version:i().min(1).max(200),contentHash:Er,mappings:$b}).strict(),Db=l({operationId:Qn,id:Qn.optional(),expectedRevision:d().int().nonnegative(),request:hl,maximumCostUsd:d().finite().positive().max(1e4),graders:p(Nb).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."})}),u3=l({schemaVersion:b("openpond.experimentDefinition.v1"),id:Qn,teamId:Qn,revision:d().int().positive(),request:hl,maximumCostUsd:d().finite().positive().max(1e4),graders:p(Ni).min(1).max(100),createdAt:nn(),updatedAt:nn()}).strict();u3.extend({contentHash:Er});l({operationId:Qn,definition:md}).strict();l({projectId:Qn.optional(),datasetHash:Er.optional(),search:i().trim().max(200).optional(),status:v(["queued","running","cancelling","completed","failed","cancelled"]).optional(),afterId:Qn.optional(),limit:d().int().min(1).max(100).default(30)}).strict();l({definition:md.nullable(),configurationHash:Er.optional(),admissionRequestHash:Er.optional(),sourceExperimentId:Qn.optional(),maximumCostUsd:d().finite().positive().max(1e4),graders:p(Ni).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."})});l({operationId:Qn,profileRepositoryId:Qn,definitionId:Qn,modelId:Qn,reasoningEffort:v(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:d().finite().positive().max(1e4),externalDatasetBinding:Wo.optional(),sourceCandidate:QC.shape.sourceCandidate}).strict();l({request:hl,manifest:Jm,maximumCostUsd:d().finite().positive().max(1e4),graders:p(Ni).min(1).max(100)}).strict();var LS=i().trim().min(1).max(200),pd=l({operationId:LS,request:hl,maximumCostUsd:d().finite().positive().max(1e4),graders:p(Nb).min(1).max(100).optional(),sourceExperimentId:LS.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."})}),Ft=i().trim().min(1).max(200),Mi=i().regex(/^[a-f0-9]{64}$/),nm=l({id:Ft,contentHash:Mi}).strict(),Hae=l({available:I(),reason:i().max(1e3).nullable(),origin:qm.nullable()}).strict(),aR=l({schemaVersion:b("openpond.postTrainingAttachment.v1"),binding:l({kind:v(["preparation","policy"]),id:Ft,revision:d().int().positive(),contentHash:Mi}).strict(),projectId:Ft.nullable(),automatic:I(),maximumSpendUsd:d().finite().positive().max(1e4),experiments:p(l({id:Ft,configuration:pd}).strict()).min(1).max(20),acceptancePlan:$_.nullable()}).strict().superRefine((e,t)=>{if(new Set(e.experiments.map(n=>n.id)).size!==e.experiments.length&&t.addIssue({code:"custom",message:"Attach each evaluation once."}),e.experiments.reduce((n,a)=>n+a.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Attached evaluation budgets exceed the total approved budget."}),e.experiments.some(n=>(n.configuration.request.project?.id??null)!==e.projectId)&&t.addIssue({code:"custom",message:"Attached experiments must use the training Project."}),e.acceptancePlan){const n=new Set(e.acceptancePlan.checks.map(o=>o.id));e.acceptancePlan.checks.some(o=>!e.experiments.some(r=>r.id===o.id))&&t.addIssue({code:"custom",message:"Select the frozen Experiment for each acceptance check."}),e.acceptancePlan.maximumSpendUsd+e.experiments.filter(o=>!n.has(o.id)).reduce((o,r)=>o+r.configuration.maximumCostUsd,0)>e.maximumSpendUsd+1e-9&&t.addIssue({code:"custom",message:"Paired acceptance and diagnostic ceilings exceed the approved evaluation budget."})}});function Lae(e){const{modelId:t,candidate:n,...a}=e.request.policy.kind==="fixture"?{modelId:null,candidate:null,...e.request.policy}:e.request.policy;return"modelConfigurationHash"in a&&delete a.modelConfigurationHash,{dataset:{id:e.request.taskset.id,contentHash:e.request.taskset.contentHash},populationHash:Pt(e.request.population.map(o=>({caseId:o.taskId,seed:o.seed,fixtureId:o.fixtureId}))),executionHash:Pt({settings:a,graders:e.graders??null})}}var m3=l({baseline:nm,checks:p(l({id:Ft,sourceRunId:Ft,sourceManifestHash:Mi,targetConfigurationHash:Mi,executionHash:Mi,populationHash:Mi,evaluator:nm,feedbackKey:Ft,output:v(["boolean","score"]),unit:i().min(1).max(80)}).strict()).min(1).max(100)}).strict(),p3=v(["waiting_for_training","ready","preparing","queued","running","cleaning","completed","failed","blocked","cancelled","budget_exhausted"]),f3=l({schemaVersion:b("openpond.postTrainingSummary.v1"),id:Ft,teamId:Ft,jobId:Ft,revision:d().int().positive(),planHash:Mi,automatic:I(),candidate:nm.nullable(),state:p3,total:d().int().positive(),completed:d().int().nonnegative(),failed:d().int().nonnegative(),requiredOutcome:v(["none","pending","passed","failed","blocked"]),reason:i().max(500).nullable(),groupId:Ft.nullable(),experimentIds:p(Ft).max(20),updatedAt:nn()}).strict().superRefine((e,t)=>{e.completed+e.failed>e.total&&t.addIssue({code:"custom",message:"Evaluation totals are inconsistent."}),["preparing","queued","running","cleaning","completed"].includes(e.state)&&!e.candidate&&t.addIssue({code:"custom",message:"Evaluation execution requires the exact trained candidate."})}),qae=l({operationId:Ft,expectedRevision:d().int().positive(),planHash:Mi}).strict();l({operationId:Ft,attachment:aR}).strict();l({id:Ft,teamId:Ft,ownerUserId:Ft,attachment:aR,qualification:m3.nullable(),contentHash:Mi,createdAt:nn()}).strict();function Uae(e){return!!(e&&["preparing","queued","running","cleaning"].includes(e.state))}var zae=l({teamId:Ft,actorId:Ft,projectId:Ft.nullable(),configuration:Fm,batches:p(fb).max(1e4),sources:p(Um).max(1e4),definitions:p(ld).max(1e4),experiments:p(l({id:Ft,name:i().max(500),configuration:pd,graders:p(l({feedbackKey:Ft,name:i().max(500),ref:nm}).strict()).max(100)}).strict()).max(1e4)}).strict();v(["prepare","start","cancel","publish","attach"]);var Bae=l({teamId:Ft,actorId:Ft,configuration:Fm,policy:x_,inspection:Bz,iterations:p(l({iteration:k_,evals:f3.nullable()}).strict()).max(100),nextCursor:Ft.nullable()}).strict(),Fae=l({id:Ft,expectedRevision:d().int().positive(),policyHash:Mi,operationId:Ft,action:v(["pause","resume","reserve","cancel-iteration","retry-iteration"]),iterationId:Ft.optional(),iterationRevision:d().int().positive().optional()}).strict(),qs=i().trim().min(1).max(240),h3=Tt.extend({revision:d().int().positive()}).strict(),g3=h3.extend({teamId:qs,jobId:qs,plan:Tt,baseline:Tt,candidate:Tt,state:s4.shape.state,updatedAt:i().datetime()}).strict();l({schemaVersion:b("openpond.trainingAcceptanceGroupPage.v1"),teamId:qs,jobId:qs,groups:p(g3).max(100),nextCursor:qs.nullable()}).strict();l({cursor:qs.optional(),limit:d().int().min(1).max(100).default(25)}).strict();var La=i().trim().min(1).max(191),Oc=i().regex(/^[a-f0-9]{64}$/),v3=l({schemaVersion:b("openpond.trainingPreparationRequest.v1"),teamId:La,operationId:La,projectId:La.nullable(),configuration:l({id:La,expectedRevision:d().int().positive(),expectedEtag:Oc}).strict(),origin:qm.optional(),batch:ea,name:i().trim().min(1).max(191),maximumSpendUsd:d().finite().positive().max(1e6)}).strict(),b3=l({schemaVersion:b("openpond.trainingPreparationPlan.v1"),id:La,creatorUserId:La,request:v3,requestHash:Oc,source:Bw(()=>oR),submissionHash:Oc,createdAt:i().datetime({offset:!0})}).strict(),y3=b3.extend({contentHash:Oc}).strict(),S3=l({schemaVersion:b("openpond.trainingPreparationReceipt.v1"),plan:y3,revision:d().int().positive(),state:v(["prepared","submitted","cancelled"]),jobId:La.nullable()}).strict().superRefine((e,t)=>{e.state==="submitted"!=!!e.jobId&&t.addIssue({code:"custom",path:["jobId"],message:"Only submitted preparations identify a job."})});l({teamId:La,planHash:Oc,expectedRevision:d().int().positive()}).strict();l({projectId:La.optional(),state:v(["prepared","submitted","cancelled"]).optional(),afterId:La.optional(),limit:d().int().min(1).max(100).default(25)}).strict();l({schemaVersion:b("openpond.trainingPreparationPage.v1"),teamId:La,items:p(S3).max(100),nextCursor:La.nullable()}).strict();l({schemaVersion:b("openpond.trainingHarnessSourcePublication.v1"),harnessRelease:De,sourcePackageHash:i().regex(/^[a-f0-9]{64}$/),sizeBytes:d().int().positive().max(p4)}).strict();p(l({id:i().trim().min(1)}).catchall(ie())).min(1).max(1e3);l({binding:Lm,rewards:p(rd).min(1).max(100)}).strict();var x3=l({id:i().trim().min(1),clusterKey:i().trim().min(1),split:v(["train","validation","frozen_eval"])}).passthrough();l({schemaVersion:b("openpond.trainingEvaluationSource.v1"),taskset:ea,tasks:p(x3).min(1).max(1e4),assets:p(l({path:i().trim().min(1).max(2e3),sha256:i().regex(/^[a-f0-9]{64}$/),sizeBytes:d().int().nonnegative(),encoding:b("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 qn=i().trim().min(1).max(500),wa=i().regex(/^[a-f0-9]{64}$/),di=i().datetime({offset:!0});l({schemaVersion:b("openpond.trainingInputArtifactUpload.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),idempotencyKey:i().trim().min(1).max(500),sourceManifest:Tt,payload:ie(),contentHash:wa}).strict();l({schemaVersion:b("openpond.trainingInputArtifact.v2"),kind:v(["portable_training_bundle","reward_model_dataset"]),sourceManifest:Tt,artifactRef:i().trim().min(1).max(2e3),contentHash:wa,sizeBytes:d().int().positive(),createdAt:di}).strict();var iR=v(["reward_model_train","policy_optimize"]),k3=v(["queued","admitting","provisioning","running","stopping","cancelling","succeeded","failed","cancelled"]),w3=l({id:qn,version:i().trim().min(1).max(200).nullable().default(null),required:I().default(!0)}).strict(),oR=l({origin:qm.optional(),modelProject:l({id:qn,portableProjectId:qn,revision:d().int().positive(),contentHash:wa}).strict(),harnessRunManifest:Tt,harnessRelease:Tt,taskset:ea,tasksetRelease:Tt,evaluation:l({taskset:ea,dataset:Tt}).strict().nullable().optional(),dataset:Tt,evidenceSets:p(Tt).max(1e4)}).strict(),I3=l({kind:b("reward_model_train"),baseModel:Hr,preferenceDatasetRelease:Tt,processorRelease:Tt,recipe:l({schemaVersion:b("openpond.rewardModelRecipe.v1"),method:b("reward_model"),parameterization:b("lora_with_scalar_head")}).catchall(ie())}).strict(),_3=l({kind:b("deterministic"),grader:Tt,composer:Tt.nullable().default(null)}).strict(),C3=l({kind:b("learned_reward"),rewardModelVersion:Tt,qualificationReport:Tt.nullable().default(null),evaluationReferences:p(Tt).max(1e3).default([]),scorerArtifact:l({artifactRef:i().trim().min(1).max(2e3),contentHash:wa,executionReceipt:Tt}).strict(),processorRelease:Tt,rewardComposerRelease:Tt}).strict(),R3=l({kind:b("policy_optimize"),baseModel:Hr,recipe:L_,rewardSource:rt("kind",[_3,C3]),resumeFrom:Tt.nullable().default(null)}).strict(),P3=rt("kind",[I3,R3]),A3=l({approvalHash:wa,approvedAt:di,exportApproved:I(),maximumSpendUsd:d().nonnegative(),retentionDays:d().int().nonnegative().nullable(),region:i().trim().min(1).max(200).nullable().default(null)}).strict();l({schemaVersion:b("openpond.trainingJobSubmission.v2"),idempotencyKey:i().trim().min(1).max(500),name:i().trim().min(1).max(200),source:oR,job:P3,requestedCapabilities:p(w3).max(1e3),placementObjective:v(["fast","balanced","economical"]),budget:l({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive()}).strict(),approval:A3,contentHash:wa}).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 T3=l({schemaVersion:b("openpond.trainingJob.v2"),id:qn,teamId:qn,kind:iR,modelProjectId:qn,portableProjectId:qn,sourceProjectRevision:d().int().positive(),submissionHash:wa,state:k3,phase:i().trim().min(1).max(200),version:d().int().nonnegative(),progress:d().min(0).max(1),rolloutProgress:l({groupsCompleted:d().int().nonnegative(),groupsTarget:d().int().nonnegative(),optimizerUpdatesApplied:d().int().nonnegative(),optimizerUpdatesSkipped:d().int().nonnegative()}).strict(),accruedSpendUsd:d().nonnegative(),terminalReason:i().trim().min(1).max(5e3).nullable(),createdAt:di,updatedAt:di,completedAt:di.nullable()}).strict();l({schemaVersion:b("openpond.trainingJobPage.v2"),jobs:p(T3).max(1e3),nextCursor:i().trim().min(1).max(2e3).nullable()}).strict();var Vae=l({schemaVersion:b("openpond.trainingJobEvent.v2"),id:qn,jobId:qn,sequence:d().int().nonnegative(),type:qn,phase:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3).nullable(),data:te(i(),ie()).default({}),createdAt:di}).strict();l({schemaVersion:b("openpond.trainingJobLog.v2"),jobId:qn,sequence:d().int().nonnegative(),level:v(["debug","info","warning","error"]),message:i().max(2e4),createdAt:di}).strict();l({expectedVersion:d().int().nonnegative()}).strict();var E3=l({schemaVersion:b("openpond.trainingJobOutput.v2"),id:qn,jobId:qn,kind:v(["checkpoint","adapter","scorer","metrics","evaluation","trace","receipt"]),artifactRef:i().trim().min(1).max(2e3),contentHash:wa,sizeBytes:d().int().nonnegative(),metadata:te(i(),ie()).default({}),createdAt:di}).strict(),j3=l({schemaVersion:b("openpond.trainingExecutionReceipt.v2"),id:qn,teamId:qn,jobId:qn,submissionHash:wa,manifestHash:wa,recipeHash:wa,capabilityHash:wa,runtimeRelease:Tt,inputs:p(Tt).max(1e4),outputs:p(Tt).max(1e4),spendUsd:d().nonnegative(),durationSeconds:d().nonnegative(),cleanupComplete:I(),issuer:qn,issuedAt:di,signature:i().trim().min(1).max(1e4).nullable()}).strict(),Kae=l({schemaVersion:b("openpond.trainingJobOutputs.v2"),outputs:p(E3).max(1e4),receipt:j3.nullable()}).strict();l({schemaVersion:b("openpond.trainingApiError.v2"),code:i().trim().min(1).max(200),message:i().trim().min(1).max(5e3),retryable:I().default(!1),requestId:i().trim().min(1).max(500).nullable().default(null),details:te(i(),ie()).default({})}).strict();l({schemaVersion:b("openpond.trainingCapabilities.v2"),capabilityHash:wa,jobKinds:p(iR),methods:p(i().trim().min(1).max(200)),placements:p(v(["local","remote","colocated","provider_native"])),controls:l({cancel:I(),stopAfterGroup:I(),resumeFromCheckpoint:I()}).strict(),limits:l({maximumSpendUsd:d().nonnegative(),maximumWallSeconds:d().int().positive(),maximumArtifactBytes:d().int().positive()}).strict(),checkedAt:di,expiresAt:di}).strict();var Di=Fa.shape.id,mi=d().int().positive(),jr=i().regex(/^[a-f0-9]{64}$/),Lr={teamId:Di,modelId:Di};l({schemaVersion:b("openpond.tasksetDraftCreate.v1"),operationId:Di,modelId:Di,expectedModelRevision:mi,name:Fa.shape.name}).strict();l({schemaVersion:b("openpond.tasksetDraftSourceDescriptor.v1"),...Lr,expectedModelRevision:mi,sourcePackageHash:jr}).strict();l({schemaVersion:b("openpond.tasksetDraftReadback.v1"),...Lr,draft:Fa,workspaceHash:jr,projectEtag:jr}).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 M3=l({id:Di,revision:mi,name:Fa.shape.name,status:WC,updatedAt:Fa.shape.updatedAt,sourceTasksetRef:lt.nullable()}).strict();l({schemaVersion:b("openpond.tasksetDraftList.v1"),...Lr,drafts:p(M3).max(100),nextCursor:i().min(1).max(2e3).nullable()}).strict();l({expectedDraftRevision:mi,draft:Fa}).strict();l({expectedDraftRevision:mi,expectedModelRevision:mi}).strict();var O3=l({expectedDraftRevision:mi,expectedWorkspaceHash:jr}).strict();l({schemaVersion:b("openpond.tasksetDraftValidation.v1"),...Lr,draftId:Di,draftRevision:mi,workspaceHash:jr,valid:I(),issues:p(l({code:i().min(1),severity:v(["warning","error"]),message:i(),path:i().nullable()}).strict()),packageHash:jr.nullable(),tasksetRef:lt.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.");O3.extend({operationId:Di,expectedPackageHash:jr,expectedTasksetRef:lt}).strict();l({schemaVersion:b("openpond.tasksetDraftFileList.v1"),...Lr,draftId:Di,draftRevision:mi,files:p(N_).max(10020)}).strict();l({schemaVersion:b("openpond.tasksetDraftFileReadback.v1"),...Lr,draftId:Di,draftRevision:mi,file:u4}).strict();l({schemaVersion:b("openpond.tasksetDraftDeletion.v1"),...Lr,draftId:Di,revision:mi,deleted:b(!0)}).strict();Fa.shape.id;d().int().positive();var ao=i().trim().min(1).max(500),$3=l({projectId:ao.optional(),tasksetId:ao.optional(),draftId:ao.optional(),taskId:ao.optional(),query:i().trim().max(1e3).default(""),split:v(["train","validation","test","frozen_eval"]).optional(),after:i().min(1).max(2e3).optional(),limit:d().int().min(1).max(100).default(30)}).strict(),N3=l({id:ao,method:v(["code","judge","human"]),required:I()}),rR=l({tasksetId:ao,tasksetName:i(),tasksetRevision:d().int().positive(),tasksetHash:i(),taskId:ao,ordinal:d().int().nonnegative(),title:i(),description:i(),split:i(),scoring:p(N3),configuration:v(["configured","needs_reward","needs_checks"]),draftId:ao.nullable().default(null),modelId:ao.nullable().default(null)}),D3=l({items:p(rR).max(100),nextCursor:i().nullable()});function Wae(e,t){if(Xz({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})=>MS(s,new TextEncoder().encode(r.text))),MS(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(o)))]}function Gae(e,t,n){const a=P_.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 c=a.records.find(f=>f.id===s);if(!c||c.kind!=="task"||c.needsContext)throw new Error("Recorded attempts and incomplete histories must be imported into Labeling for review.");const m=KC.parse({schemaVersion:"openpond.taskData.v1",id:c.id,clusterKey:c.familyKey,split:c.split,input:c.input,expectedOutput:c.expected,privilegedContextRef:null,metadata:{intake:{format:a.format,uploadHash:a.contentHash,sourceId:c.sourceId,sourceHash:c.sourceHash,metadata:c.metadata}}}),u=o.find(f=>f.id===m.id);if(u&&Pt(u)!==Pt(m))throw new Error(`Task ${m.id} already exists with different content. Import will not replace saved edits.`);u||o.push(m)}const r=new Map;for(const s of o)for(const c of[`family:${s.clusterKey}`,`input:${Pt(s.input)}`]){if(r.has(c)&&r.get(c)!==s.split)throw new Error("The imported task family or request already occurs in another split.");r.set(c,s.split)}return Fa.parse({...e,tasks:o})}const ua=i().trim().min(1).max(240),Bo=i().trim().min(1),sR=te(i(),ie()).default({}),lR=v(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),cR=v(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),H3=l({id:ua,kind:v(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:p(ua).min(1).max(1e4),occurredAt:Bo,signature:i().trim().min(1).max(2e3),summary:i().trim().min(1).max(5e3),confidence:d().min(0).max(1),consented:I(),metadata:sR}),L3=l({frequency:d().min(0).max(1),businessValue:d().min(0).max(1),frontierCost:d().min(0).max(1),signalQuality:d().min(0).max(1),verifiability:d().min(0).max(1),repeatability:d().min(0).max(1),privacyRisk:d().min(0).max(1),overall:d().min(0).max(1)}),q3=l({tactic:cR,eligible:I(),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:v(["decision_table","baseline_reassessment"])}),dR=l({schemaVersion:b("openpond.taskCandidate.v1"),id:ua,profileId:ua,status:lR,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(H3).min(1).max(1e5),scorecard:L3,recommendation:q3,mergedIntoId:ua.nullable(),createdAt:Bo,updatedAt:Bo,metadata:sR}),np=l({schemaVersion:b("openpond.taskMinerConfig.v1"),enabled:I().default(!1),localOnly:I().default(!0),observationWindowDays:d().int().min(1).max(365).default(30),minimumRecurrence:d().int().min(2).max(100).default(3),clustering:b("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:I().default(!0)});l({items:p(dR),generatedAt:Bo,config:np});l({status:lR.optional(),mergeIntoId:ua.nullable().optional()});l({profileId:ua,sourceIds:p(ua).max(1e5).default([]),sessionIds:p(ua).max(1e5).default([]),config:np.optional()});const U3=l({schemaVersion:b("openpond.taskMinerRun.v1"),id:ua,profileId:ua,status:v(["queued","running","cancelling","cancelled","succeeded","failed"]),config:np,sourceIds:p(ua).max(1e5),sessionIds:p(ua).max(1e5).default([]),progress:l({stage:v(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:d().int().nonnegative(),totalSources:d().int().nonnegative(),candidatesFound:d().int().nonnegative(),skippedSources:d().int().nonnegative().default(0)}),candidateIds:p(ua).max(1e5),cancelRequested:I(),error:i().trim().min(1).max(2e4).nullable(),createdAt:Bo,startedAt:Bo.nullable(),completedAt:Bo.nullable(),updatedAt:Bo});var z3=l({id:Ke,purpose:i().trim().min(1).max(500),audience:v(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:I(),ttlSeconds:d().int().positive().max(86400),scopes:p(i().trim().min(1).max(500)).max(100).default([])}).strict(),B3=l({declarationId:Ke,leaseRef:i().trim().min(8).max(1e3),audience:z3.shape.audience,expiresAt:Rt}).strict(),Hb=l({adapterId:Ke,placement:v(["local","remote","colocated","provider_native"]),capabilityReceipt:Qe,runtimeVersion:i().trim().min(1).max(200),dataPlane:l({provider:Ke,dataPlaneId:Ke,cellId:Ke,runnerPoolId:Ke,runtimeImageDigest:i().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:Qe}).strict().nullable()}).strict(),Lb=l({adapterId:Ke,kind:v(["local","ssh","managed","custom"]),deviceOrPool:i().trim().min(1).max(1e3),capabilityReceipt:Qe,provider:Ke.nullable()}).strict(),qb=l({adapterId:Ke,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(),F3=l({schemaVersion:b("openpond.harnessRunManifest.v1"),id:Ke,harnessRelease:De,datasetRelease:De,evidenceSets:p(De).max(1e4),model:l({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:l({method:i().trim().min(1).max(100),version:i().trim().min(1).max(200),configHash:Qe}).strict(),runtimeTarget:Hb,computeTarget:Lb,engine:qb,resolvedBundleHash:Qe,secretLeaseRefs:p(B3).max(1e3),approval:l({approvalHash:Qe,approvedAt:Rt,maximumSpendUsd:d().nonnegative().nullable()}).strict(),createdAt:Rt}).strict(),V3=F3.extend({contentHash:Qe}).strict(),K3=l({schemaVersion:b("openpond.resolvedTrainingBundle.v1"),projection:b("trainer"),harnessRelease:De,datasetRelease:De,evidenceSetRelease:De.nullable(),files:p(l({path:i().trim().min(1).max(2e3),sha256:Qe,sizeBytes:d().int().nonnegative()}).strict()).max(1e5)}).strict();K3.extend({contentHash:Qe}).strict();var uR=l({name:b("adamw").default("adamw"),weightDecay:d().nonnegative().max(1).default(0),beta1:d().positive().lt(1).default(.9),beta2:d().positive().lt(1).default(.999),epsilon:d().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const yt=i().trim().min(1).max(240),pa=i().trim().min(1),el=i().trim().min(8).max(256),Ub=te(i(),ie()).default({}),Oi=yt.nullable(),W3=v(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),G3=v(["defaults","customize"]),J3=v(["automated","manual"]);l({schemaVersion:b("openpond.trainingSourceEstimate.v1"),sessionId:yt,messageCount:d().int().nonnegative(),estimatedTokens:d().int().nonnegative(),textBytes:d().int().nonnegative()});l({query:i().max(500).default(""),offset:d().int().nonnegative().default(0),limit:d().int().min(1).max(100).default(20),candidates:p(l({sessionId:yt,title:i().trim().min(1).max(500),updatedAt:pa})).max(500).default([])});const Z3=l({sessionId:yt,title:i().trim().min(1).max(500),updatedAt:pa,snippet:i().max(2e3).nullable()});l({schemaVersion:b("openpond.trainingChatSearchResult.v1"),query:i(),offset:d().int().nonnegative(),limit:d().int().positive(),total:d().int().nonnegative(),hasMore:I(),indexedChats:d().int().nonnegative(),totalChats:d().int().nonnegative(),indexing:I(),entries:p(Z3)});const zb=v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),Y3=l({graderId:yt.nullable(),path:i().trim().min(1).max(1e3),language:v(["javascript","typescript","python","json","text"]),content:i().max(2e6),sha256:el,declaredSha256:el.nullable(),integrity:v(["verified","unverified","mismatch"])}),Q3=l({protocolVersion:i().trim().min(1).max(200),module:i().trim().min(1).max(1e3),moduleSha256:el,command:p(i().max(2e3)).max(100),cwd:i().trim().min(1).max(4e3),maxTurns:d().int().positive().max(100)});l({schemaVersion:b("openpond.tasksetGraderDetails.v1"),taskset:Zt,sourceTasksetId:yt,graders:p(ep).max(1e3),runtime:Q3.nullable(),sources:p(Y3).max(1e3),unavailableReason:i().max(2e3).nullable()});const X3=l({id:yt,taskIndex:d().int().nonnegative(),label:Mb,output:te(i(),ie()),infrastructureError:i().trim().min(1).max(1e4).nullable(),expectedPassed:I(),expectedRewardEligible:I(),metadata:Ub}),e6=l({schemaVersion:b("openpond.taskAttempt.v1"),id:yt,tasksetId:yt,taskId:yt,split:Xs,attempt:d().int().nonnegative(),seed:d().int(),modelRef:bn.nullable(),startedAt:pa,completedAt:pa,output:te(i(),ie()),runtimeEventRefs:p(yt).max(1e4).default([]),artifactRefs:p(yt).max(1e4).default([]),privilegedOutcomeRef:Oi,infrastructureError:i().trim().min(1).max(1e4).nullable(),costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),userInterventions:d().int().nonnegative().default(0),metadata:Ub}),t6=l({schemaVersion:b("openpond.taskAttemptArtifact.v1"),id:yt,tasksetId:yt,taskId:yt,attemptId:yt,kind:v(["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:el,sizeBytes:d().int().nonnegative(),createdAt:pa,metadata:Ub}),n6=l({graderId:yt,graderVersion:i().trim().min(1).max(100),score:d().min(0).max(1).nullable(),passed:I(),hardGate:I(),rewardEligible:I(),feedback:i().trim().max(2e4).nullable(),evidenceRefs:p(yt).max(1e4).default([]),judge:bn.nullable().optional().default(null),calibrationStatus:v(["not_applicable","pending","passed","failed"])}),a6=l({schemaVersion:b("openpond.gradeResult.v1"),id:yt,attemptId:yt,graderSetHash:el,score:d().min(0).max(1).nullable(),passed:I(),components:p(n6).min(1).max(1e3),failureClass:zb.nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:I(),rewardComposition:Cc.optional(),createdAt:pa});v(["stable_hash_top_n","rft_easy_curriculum_v1"]);const i6=l({schemaVersion:b("openpond.graderAuditReport.v1"),id:yt,tasksetId:yt,tasksetHash:el,fixtureRefs:p(yt).min(1).max(1e5),gradeRefs:p(yt).min(1).max(1e5),passed:I(),hackingChecksPassed:I(),leakageChecksPassed:I(),infrastructureSafetyPassed:I(),failures:p(l({fixtureId:yt,label:Mb,gradeId:yt,reason:i().trim().min(1).max(5e3)})).max(1e5),createdAt:pa}),o6=l({schemaVersion:b("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(yt).max(100).default([]),intervention:cR,trainingEligible:I(),rationale:p(i().trim().min(1).max(5e3)).min(1).max(100),confidence:d().min(0).max(1)}),r6=l({id:yt,sourceId:yt,sourceTurnId:Oi,split:Xs,origin:v(["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)}),s6=l({schemaVersion:b("openpond.taskDesignProposal.v1"),id:yt,name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),diagnosis:o6.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:jb.shape.taskKind,sourceIds:p(yt).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(ep).max(1e3).default([]),graderFixtures:p(X3).max(1e5).default([]),generatedFiles:p(j5).max(1e3).default([]),proposedExamples:p(r6).max(1e5).default([]),proposedMethod:zC.shape.recommendedMethod,trainingPath:qC.nullable().default(null),policy:Eb,warnings:p(i().trim().min(1).max(5e3)).default([]),createdAt:pa}),l6=5;function Jae(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,l6).join(" ")}const fd=l({schemaVersion:b("openpond.baseModelPreference.v1"),modelId:yt,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:Oi,source:v(["managed","local","builtin"])}),c6=l({schemaVersion:b("openpond.taskCreationRequest.v1"),id:yt,profileId:yt,surface:W3,mode:G3,entryMode:J3.default("manual"),resourceIntent:v(["workproduct","dataset"]).default("workproduct"),buildIntent:HC.default("demonstrations"),buildSpecification:LC.nullable().default(null),objective:i().trim().min(1).max(2e4).nullable(),methodHint:v(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:yt.nullable().default(null),preferredBaseModel:fd.nullable().default(null),sourceIds:p(yt).max(1e5),candidateId:Oi,analysisModel:bn.nullable(),analysisReasoningEffort:Tm.nullable().default(null),createImproveRunId:Oi.default(null),targetIntent:l({kind:v(["agent","skill","extension","model","configuration"]).nullable(),id:Oi,displayName:i().trim().min(1).max(500).nullable(),operation:v(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:l({status:v(["not_required","pending","approved","declined"]),content:b("raw_excerpts"),sourceIds:p(yt).max(1e5),providerModel:bn.nullable(),approvalId:Oi,approvedAt:pa.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:pa}),mR=l({schemaVersion:b("openpond.taskCreationSnapshot.v1"),id:yt,request:c6,state:v(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:s6.nullable(),materializedTasksetId:Oi,disclosureApprovalId:Oi,materializationApprovalId:Oi,blockingQuestions:p(l({id:yt,kind:v(["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(l({id:yt,role:v(["user","assistant","system","tool"]),text:i().max(1e5),createdAt:pa})).max(1e4).default([]),repairHistory:p(BC).max(1e3).default([]),blockedReason:i().trim().min(1).max(1e4).nullable(),createdAt:pa,updatedAt:pa});l({schemaVersion:b("openpond.taskCreationTranscript.v1"),creationId:yt,profileId:yt,messages:mR.shape.transcript,updatedAt:pa});const Ts=i().trim().min(1).max(240),_u=i().trim().min(1),wg=i().trim().min(8).max(256),pR=te(i(),ie()).default({}),d6=v(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),fR=l({schemaVersion:b("openpond.huggingFaceDatasetLocator.v1"),repositoryId:i().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:i().url().max(2e3),requestedRevision:i().trim().min(1).max(256).nullable()}),u6=l({path:i().trim().min(1).max(1e3),logicalType:i().trim().min(1).max(500),nullable:I(),sampleValues:p(ie()).max(5)}),m6=l({configuration:i().trim().min(1).max(500),split:i().trim().min(1).max(500),rowCount:d().int().nonnegative().nullable(),sizeBytes:d().int().nonnegative().nullable()}),p6=l({schemaVersion:b("openpond.huggingFaceDatasetInspection.v1"),id:Ts,locator:fR,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:I(),private:I(),configurations:p(i().trim().min(1).max(500)).min(1).max(1e3),splits:p(m6).min(1).max(1e4),columns:p(u6).min(1).max(1e4),previewRows:p(te(i(),ie())).max(25),sourceFiles:p(l({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:d().int().nonnegative().nullable(),contentHash:wg.nullable()})).max(1e5),inspectedAt:_u,metadata:pR}),f6=v(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),h6=l({sourcePath:i().trim().min(1).max(1e3),target:f6,transform:v(["identity","string","json","messages","numeric","math_final_answer"]),policy:v(["visible","privileged","metadata"]),required:I()}),hR=l({schemaVersion:b("openpond.datasetImportMapping.v1"),sourceSchemaHash:wg,configuration:i().trim().min(1).max(500),upstreamSplits:p(i().trim().min(1).max(500)).min(1).max(1e3),preset:v(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:p(h6).min(1).max(1e4),nullPolicy:v(["reject","drop","preserve"]),invalidRowPolicy:v(["reject_import","drop_with_receipt"]),splitPolicy:l({seed:d().int(),assignments:te(i(),Qo),validationPercent:d().min(0).max(100),frozenEvalPercent:d().min(0).max(100)}),importerVersion:i().trim().min(1).max(200),mappingHash:wg}),g6=l({phase:v(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:d().int().nonnegative(),totalBytes:d().int().nonnegative().nullable(),completedRows:d().int().nonnegative(),totalRows:d().int().nonnegative().nullable(),message:i().trim().min(1).max(2e3).nullable()}),v6=l({schemaVersion:b("openpond.datasetImportJob.v1"),id:Ts,profileId:Ts,sourceKind:v(["huggingface","uploaded_file"]),status:d6,locator:fR.nullable(),inspection:p6.nullable(),mapping:hR.nullable(),progress:g6,targetStorageRoot:i().trim().min(1).max(4e3).nullable(),tasksetId:Ts.nullable(),tasksetRevision:d().int().positive().nullable(),artifactId:Ts.nullable(),error:i().trim().min(1).max(2e4).nullable(),cancellationRequested:I(),createdAt:_u,updatedAt:_u,completedAt:_u.nullable(),metadata:pR});l({profileId:Ts,url:i().trim().min(1).max(2e3)});l({name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),mapping:hR,targetStorageRoot:i().trim().min(1).max(4e3).nullable(),licenseApproved:I().default(!1)});var dc=i().trim().min(1).max(200),Ig=l({operationId:dc,execution:De,executionKind:b("recorded_evidence").optional(),graders:p(Yo).min(1).max(100),maximumCostUsd:d().finite().min(1e-6).max(1e4),mappings:p(l({graderId:dc,fields:$b}).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."})}),b6=l({schemaVersion:b("openpond.experimentScoringPass.v1"),id:dc,teamId:dc,revision:d().int().positive(),request:Ig,graders:p(Ni).min(1).max(100),status:v(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:d().int().min(1).max(1e4),counts:l({pending:d().int().nonnegative(),running:d().int().nonnegative(),scored:d().int().nonnegative(),unavailable:d().int().nonnegative(),failed:d().int().nonnegative(),cancelled:d().int().nonnegative()}).strict(),resultAvailable:I(),createdAt:nn(),startedAt:nn().nullable(),completedAt:nn().nullable(),error:l({code:dc,message:i().max(2e3)}).strict().nullable()}).strict();b6.extend({contentHash:i().regex(/^[a-f0-9]{64}$/)});var gR=l({sourcePass:De,graders:Ig.shape.graders,mappings:Ig.shape.mappings,maximumCostUsd:d().finite().positive().max(1e4)}).strict(),vR=l({externalDatasetBinding:Wo,scoring:gR.optional(),modelId:i().min(1).max(300),maximumCostUsd:d().finite().positive().max(1e4)}).strict(),Bb=l({source:v(["local","github","openpond_git"]),repositoryId:i().trim().min(1),profileId:i().trim().min(1)}).strict(),$t=i().min(1).max(240),ra=i().regex(/^[a-f0-9]{64}$/),uc=l({schemaVersion:b("openpond.experimentImprovement.v1"),id:$t,operationId:$t,requestHash:ra,actorId:$t,teamId:$t,projectId:$t.nullable(),ownerWorkspaceId:$t,ownerRevision:d().int().nonnegative(),ownerSourceRevision:i().min(1).max(500),baseRelease:De,profileRef:Bb,baseProfileSourceRevision:i().min(1).max(500),evidence:l({manifest:so,result:lo}).strict(),component:l({kind:v(["skill","workflow","agent","instruction"]),path:i().min(1).max(2e3),workflowId:$t.optional()}).strict(),mode:v(["manual","llm_assisted"]),status:v(["draft","authoring_queued","authoring","frozen","testing","ready_for_review","adopting","accepted","rolled_back","declined","failed","cancelled"]),revision:d().int().positive(),limits:l({maximumCostUsd:d().finite().positive(),maximumAuthoringSteps:d().int().min(1).max(500),maximumDurationMs:d().int().min(1e3).max(864e5)}).strict(),authoringSteps:d().int().nonnegative().max(500),work:l({sessionId:$t,turnId:$t,revision:d().int().positive(),startedAt:i().datetime()}).strict().nullable(),frozen:l({release:De,sourceRevision:i().min(1).max(500),profileSourceRevision:i().min(1).max(500),authoringHash:ra,partitionHash:ra,executableSourceHash:ra,protectedClosureHash:ra,candidateRevision:d().int().positive(),diff:p(l({path:i(),before:ra.nullable(),after:ra.nullable()}).strict()).max(1e4)}).strict().nullable(),test:l({recipe:vR,recipeHash:i().regex(/^[a-f0-9]{64}$/),baselineOperationId:i(),candidateOperationId:i(),cancelRequestedAt:i().datetime().nullable(),dispatching:l({kind:v(["baseline","candidate"]),token:$t,pid:d().int().positive(),processStart:i().nullable(),startedAt:i().datetime()}).strict().nullable()}).strict().nullable(),comparison:l({baseline:l({manifest:so,result:lo}).strict(),candidate:l({manifest:so,result:lo}).strict(),frozenHash:ra,humanProjection:kg.optional()}).strict().nullable(),adoptionIntent:l({operationId:$t,expectedOwnerRevision:d().int().nonnegative(),frozenHash:ra,humanProjection:kg.optional()}).strict().nullable(),acceptance:De.nullable(),rollback:De.nullable(),error:i().max(2e3).nullable(),createdAt:i().datetime(),updatedAt:i().datetime(),contentHash:ra}).strict();function Zae(e){const t=uc.parse(e),{contentHash:n,...a}=t;if(Pt(a)!==n)throw new Error("Improvement state integrity failed.");if(Rr(t.evidence),t.evidence.manifest.teamId!==t.teamId||t.evidence.result.status!=="completed"||!t.evidence.result.cases.some(o=>o.status==="completed"))throw new Error("Improvement requires usable completed owner evidence.");if(t.test&&(Pt(t.test.recipe)!==t.test.recipeHash||vg(t.test.recipe.externalDatasetBinding).profileId!==t.profileRef.profileId))throw new Error("The test recipe changed its exact selected Profile.");if(t.comparison?.humanProjection){const o=pF(t.comparison.humanProjection);if(o.teamId!==t.teamId||o.projectId!==t.projectId||Pt(o.baseline)!==Pt(t.comparison.baseline)||Pt(o.candidate)!==Pt(t.comparison.candidate))throw new Error("Human comparison projection differs from its exact owner evidence.")}if(t.comparison&&(Rr(t.comparison.baseline),Rr(t.comparison.candidate),!t.frozen||t.comparison.frozenHash!==Pt(t.frozen)||!vz(t.comparison.baseline,t.comparison.candidate).comparable))throw new Error("Improvement comparison is not bound to a comparable frozen candidate.");if(t.status==="ready_for_review"&&(!t.frozen||!t.comparison))throw new Error("Improvement is missing qualification.");if(t.status==="adopting"&&(!t.adoptionIntent||!t.frozen||t.adoptionIntent.frozenHash!==Pt(t.frozen)))throw new Error("Improvement adoption intent is not bound to its tested revision.");if(t.status==="accepted"&&(!t.acceptance||!t.comparison||!t.frozen))throw new Error("Improvement acceptance is missing its exact qualification receipt.");if(t.status==="rolled_back"&&(!t.acceptance||!t.rollback))throw new Error("Profile rollback is missing its durable owner receipt.");return t}var Yae=l({states:p(uc).max(50),nextCursor:$t.nullable()}).strict(),y6=l({operationId:$t,ownerWorkspaceId:$t,expectedOwnerRevision:d().int().nonnegative(),baseRelease:De,profileRef:Bb,profileSourceRevision:i().min(1).max(500),projectId:$t.nullable(),evidence:De,component:uc.shape.component,mode:uc.shape.mode,limits:uc.shape.limits}).strict(),Qae=rt("operation",[l({operation:b("list"),limit:d().int().min(1).max(50).default(30),cursor:$t.optional()}).strict(),l({operation:b("options"),evidence:De}).strict(),l({operation:b("start"),request:y6}).strict(),l({operation:v(["read","humanComparisonOptions"]),id:$t}).strict(),l({operation:b("instructions"),id:$t}).strict(),l({operation:b("edit"),id:$t,revision:d().int().positive(),expectedFileHash:ra,text:i().max(25e4)}).strict(),l({operation:b("mode"),id:$t,revision:d().int().positive(),mode:v(["manual","llm_assisted"])}).strict(),l({operation:b("author"),id:$t,revision:d().int().positive(),modelId:$t,prompt:i().min(1).max(2e4)}).strict(),l({operation:v(["freeze","finishAuthoring","useCandidate","discard","cancel","rollback"]),id:$t,revision:d().int().positive()}).strict(),l({operation:b("test"),id:$t,revision:d().int().positive(),recipe:vR}).strict(),l({operation:b("compare"),id:$t,revision:d().int().positive(),baseline:De,candidate:De,humanSelections:uC.optional()}).strict()]),bR=l({teamId:$t,evidence:De,scoring:gR.optional(),profiles:p(l({id:ra,name:i(),profileRef:Bb,ownerWorkspaceId:$t,ownerRevision:d().int().nonnegative(),baseRelease:De,profileSourceRevision:i(),components:p(l({kind:v(["skill","instruction","agent","workflow"]),path:i(),agentId:i().optional(),workflowId:i().optional(),label:i(),binding:Wo}).strict()).max(500)}).strict()).max(100)}).strict(),S6=l({candidateId:$t,actorId:$t,teamId:$t,projectId:$t.nullable(),candidateRevision:d().int().positive(),recipeHash:ra,baseline:l({manifest:so,result:lo}).strict(),candidate:l({manifest:so,result:lo}).strict(),contentHash:ra}).strict();function Xae(e){const t=S6.parse(e),{contentHash:n,...a}=t;if(Pt(a)!==n)throw new Error("Accepted Human discovery integrity failed.");for(const o of[t.baseline,t.candidate])if(Rr(o),o.manifest.teamId!==t.teamId||o.manifest.lineage?.humanProjection)throw new Error("Discovery must retain original owner evidence.");return t}var en=i().trim().min(1).max(240),$i=i().regex(/^[a-f0-9]{64}$/),Fb=l({schemaVersion:b("openpond.advancedRefinerEvaluation.v1"),operationId:en,actorId:en,teamId:en,projectId:en.nullable(),mode:v(["review_quality","downstream_adaptation"]),profileRef:l({source:v(["local","github","openpond_git"]),repositoryId:en,profileId:en}).strict(),sourceRevision:i().min(1).max(500),baselineRelease:De,refinerRelease:De,evidence:De,externalDatasetBinding:Wo,adaptationDatasetBinding:Wo,privateClosureHash:$i,adaptationTaskIds:p(en).min(1).max(1e4),holdoutTaskIds:p(en).min(1).max(1e4),adaptationSplit:v(["train","validation","test","frozen_eval"]),holdoutSplit:v(["train","validation","test","frozen_eval"]),environmentPolicy:rt("kind",[l({kind:b("resettable"),environmentHash:$i}).strict(),l({kind:b("frozen_observations"),environmentHash:$i}).strict()]),maximumCostUsd:d().finite().positive().max(1e4),maximumDurationMs:d().int().min(1e3).max(864e5),maximumModelSteps:d().int().min(1).max(1e3),contentHash:$i}).strict();function eie(e){const t=Fb.parse(e),{contentHash:n,...a}=t;if(Pt(a)!==n)throw new Error("Advanced Refiner evaluation admission changed.");const o=vg(t.externalDatasetBinding);if(o.profileId!==t.profileRef.profileId||o.protectedProfileClosureHash!==t.privateClosureHash)throw new Error("Advanced evaluation changed its Profile or protected evaluator closure.");if(t.adaptationSplit===t.holdoutSplit||new Set([...t.adaptationTaskIds,...t.holdoutTaskIds]).size!==t.adaptationTaskIds.length+t.holdoutTaskIds.length)throw new Error("Adaptation and private holdout must be disjoint ordered cases.");const r=vg(t.adaptationDatasetBinding);if(r.profileId!==o.profileId||r.packageHash!==o.packageHash||Pt(r.dataset)!==Pt(o.dataset)||Pt(r.target)!==Pt(o.target)||r.protectedProfileClosureHash!==o.protectedProfileClosureHash)throw new Error("This native advanced adapter needs separate adaptation and holdout recipes from the same exact released package and target.");if(r.split!==t.adaptationSplit||o.split!==t.holdoutSplit)throw new Error("Advanced split policies differ from their exact admitted recipes.");const s=new Set(o.population.map(m=>m.taskId)),c=new Set(r.population.map(m=>m.taskId));if(t.holdoutTaskIds.some(m=>!s.has(m))||t.adaptationTaskIds.some(m=>!c.has(m)))throw new Error("Advanced evaluation selected cases outside its exact Dataset recipe.");return t}var x6=l({pin:Fb,modelId:en,profileId:en,model:kb,seed:d().int(),reasoningEffort:v(["none","off","low","medium","high","xhigh","max"]).nullable()}).strict(),k6=rt("operation",[l({operation:b("start"),request:x6}).strict(),l({operation:v(["read","cancel","resume"]),id:en}).strict(),l({operation:b("list")}).strict()]),w6=l({taskId:en,sourceCaseHash:$i,reviewSessionId:en,reviewTurnId:en,inputHarness:De,trigger:De,decision:v(["no_action","route_deterministically","queue_refiner"]),outcome:De.nullable(),proposal:De.nullable(),validations:p(De).max(100),grade:l({id:en,contentHash:$i,score:d().min(0).max(1).nullable(),passed:I(),failureClass:i().nullable()}).strict(),resetComplete:I()}).strict(),I6=l({schemaVersion:b("openpond.advancedRefinerReviewReceipt.v1"),id:en,runId:en,pinHash:$i,ownerActorId:en,teamId:en,privateClosureHash:$i,refinerRelease:De,cases:p(w6).min(1).max(1e4),reviewScore:d().min(0).max(1).nullable(),completedCases:d().int().nonnegative(),noActionCases:d().int().nonnegative(),routedCases:d().int().nonnegative(),proposalCases:d().int().nonnegative(),costUsd:d().finite().nonnegative().nullable(),cleanupComplete:I(),createdAt:i().datetime(),contentHash:$i}).strict(),qS=bR.shape.profiles.element,tie=bR.extend({profiles:p(qS.extend({components:p(qS.shape.components.element.extend({adaptationSplits:p(l({split:v(["train","validation","test","frozen_eval"]),taskIds:p(en)})),environmentHash:$i,resettable:I(),reviewQuality:I()}))})),refinerReleases:p(De),activeRefiner:De.nullable(),models:p(l({id:en,profileId:en,name:i(),location:v(["local","hosted"])}))}),_6=l({operation:b("prepare"),evidence:De,profileOptionId:en,componentLabel:en,mode:v(["review_quality","downstream_adaptation"]),adaptationSplit:v(["train","validation","test","frozen_eval"]),operationId:en,refinerRelease:De,maximumCostUsd:d().positive(),maximumDurationMs:d().int().positive(),maximumModelSteps:d().int().positive()}).strict();gt([k6,_6,l({operation:b("options"),evidence:De}).strict()]);var C6=l({modelRequests:d().int().nonnegative(),knownSpendUsd:d().nonnegative(),totalSpendUsd:d().nonnegative().nullable(),heldUsd:d().nonnegative(),uncertainRequests:d().int().nonnegative()}).strict();const $o=T.nullable(),Yi=d().int().nonnegative(),R6=i().regex(/^[a-f0-9]{40}$/),P6=l({name:i().trim().min(1).max(160),startedAt:pe,completedAt:pe,durationMs:d().nonnegative(),clock:v(["monotonic","provider","wall"]),outcome:v(["succeeded","failed","cancelled"])}).strict(),A6=l({schemaVersion:b("openpond.correlatedTelemetryReceipt.v1"),stage:v(["training","evaluation","deployment","inference"]),correlation:l({modelRunId:$o,modelVersionId:$o,policyVersion:Yi.nullable(),taskId:$o,rolloutGroupId:$o,providerResourceId:$o,deploymentId:$o,inferenceRequestId:$o}).strict(),spans:p(P6).max(1e4),usage:l({promptTokens:Yi.nullable(),generatedTokens:Yi.nullable(),gpuSeconds:d().nonnegative().nullable(),workerActiveSeconds:d().nonnegative().nullable(),optimizerSteps:Yi.nullable(),rolloutGroups:Yi.nullable(),successfulTrajectories:Yi.nullable(),failedTrajectories:Yi.nullable(),peakGpuMemoryBytes:Yi.nullable(),peakGpuUtilizationPercent:d().min(0).max(100).nullable()}).strict(),resource:l({provider:T,resourceIds:p(T).max(1e3),gpuType:i().trim().min(1).max(300).nullable(),gpuCount:Yi.nullable(),baseProfileId:$o,baseRepository:i().trim().min(1).max(512).nullable(),baseRevision:R6.nullable(),adapterContentHash:H.nullable()}).strict(),cost:l({currency:b("USD"),providerReportedUsd:d().nonnegative().nullable(),quotedHourlyUsd:d().nonnegative().nullable(),estimatedUsd:d().nonnegative().nullable(),methodologyVersion:i().trim().min(1).max(160),pricingInputs:te(i().trim().min(1).max(160),d().finite()),unitEstimates:te(i().trim().min(1).max(160),d().nonnegative())}).strict(),recordedAt:pe,contentHash:H}).strict(),Cn=i().trim().min(1).max(240),po=i().regex(/^[a-f0-9]{64}$/),Uo=i().datetime({offset:!0}),Tn=l({id:Cn,contentHash:po}).strict(),T6=Tn.extend({revision:d().int().positive()}).strict(),yR=l({providerId:Cn,modelId:i().trim().min(1).max(300)}).strict(),ap=v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),E6=l({taskId:Cn,taskContentHash:po,panelRole:ap,passLabel:Cn.nullable(),optimizerEligible:I(),criticalInvariantIds:p(Cn).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."})}),j6=l({schemaVersion:b("openpond.continualBenchIssuePacket.v1"),id:Cn,revision:d().int().positive(),contentHash:po,familyId:Cn,familyLabel:i().trim().min(1).max(500),severity:v(["low","medium","high","critical"]),cases:p(E6).min(2).max(1e4),duplicateEvidence:Tn,leakageEvidence:Tn,priorExposureEvidence:Tn,observedAt:Uo,reviewedAt:Uo,queuedAt:Uo.nullable(),runAt:Uo.nullable(),createdBy:Cn,createdAt:Uo}).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."})}),M6=l({id:Cn,role:ap,passLabel:Cn.nullable(),taskset:T6,familyIds:p(Cn).min(1).max(1e5),taskCount:d().int().positive().max(1e6),sealedAt:Uo}).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."})}),hh=rt("kind",[l({kind:b("base_model"),id:Cn,revision:i().trim().min(1).max(500),contentHash:po}).strict(),l({kind:b("model_version"),id:Cn,contentHash:po}).strict(),l({kind:b("external_reference"),id:Cn,model:yR,providerRevision:i().trim().min(1).max(500),contentHash:po}).strict()]),O6=l({scheduleEntryId:Cn,ordinal:d().int().nonnegative(),label:Cn,role:v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:d().int().positive().max(1024),correctionPanelIds:p(Cn).min(1).max(1e3),optimizerGroupsPerTask:d().int().positive().max(1e3),trajectoriesPerGroup:d().int().min(4).max(1e3)}).strict(),$6=l({revision:d().int().positive(),requireAllAttemptsTerminal:b(!0),criticalCorrectionPassRate:d().min(0).max(1),siblingPassRate:d().min(0).max(1),behavioralRetentionRate:d().min(0).max(1),maximumRetainedRegressionPoints:d().min(0).max(100),blockCriticalPriorRegression:I(),authorizedClaims:p(v(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),N6=l({schemaVersion:b("openpond.continualBenchmarkProtocol.v1"),id:Cn,revision:d().int().positive(),contentHash:po,ownerId:Cn,createdAt:Uo,sealedAt:Uo,creationReceipt:Tn,predecessorSeries:l({id:Cn,revision:d().int().positive(),contentHash:po}).strict().nullable(),scenarioPack:Tn,issueFamilyLedger:Tn,issuePacketRelease:Tn,panels:p(M6).min(6).max(1e4),grader:Tn,judge:l({release:Tn,rubricRelease:Tn,calibrationRelease:Tn,model:yR}).strict().nullable(),policies:l({base:hh,master:hh.nullable(),externalReferences:p(hh).min(1).max(20)}).strict(),invariants:l({systemPromptHash:po,toolSchema:Tn,application:Tn,harness:Tn,runtime:Tn,workerImage:Tn,autoRefiner:l({enabled:I(),release:Tn.nullable()}).strict()}).strict(),schedule:p(O6).min(1).max(1e3),evaluation:l({seeds:p(d().int()).min(3).max(100),repetitions:d().int().min(3).max(20),powerRule:Tn,pairedBootstrapSamples:d().int().min(1e3).max(1e6),confidenceLevel:b(.95)}).strict(),resources:l({maximumTrainingGpuSeconds:d().int().positive(),maximumEvaluationGpuSeconds:d().int().positive(),maximumProviderSpendUsd:d().positive(),maximumTotalSpendUsd:d().positive(),maximumConcurrentGroups:d().int().positive().max(1e3)}).strict(),currencyThresholds:$6}).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."})}),D6=v(["draft","active","completed","archived"]),H6=v(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),SR=v(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),L6=v(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),q6=v(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),U6=v(["live_client","evaluation_attempt","replay_evidence","manual"]),z6=l({id:T,ordinal:d().int().nonnegative(),label:i().trim().min(1).max(100),role:SR,parentRule:L6,taskSource:q6,trainableRank:d().int().positive().max(1024),minimumTasks:d().int().nonnegative().max(1e5),maximumTasks:d().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."})}),B6=l({id:T,version:d().int().positive(),requireCheckpoint:I(),requireAppliedOptimizerUpdate:I(),minimumCurrentCohortMeanImprovement:d().finite(),maximumRetainedMeanRegression:d().finite().nonnegative(),blockCriticalInvariantRegression:I(),automaticDailyAdvancement:I()}).strict(),F6=l({schemaVersion:b("openpond.modelComparisonSeries.v1"),id:T,profileId:T,modelProjectId:T,name:i().trim().min(1).max(500),objective:i().trim().min(1).max(2e4),status:D6,revision:d().int().positive(),productionBinding:l({role:b("chat_manual"),roleTargetId:T}).strict(),baseModel:l({id:T,revision:i().trim().min(1).max(256)}).strict(),seedTaskset:Zt,eligibleTaskPool:Zt,evaluationTasksets:l({development:Zt,retained:Zt,frozenFinal:Zt}).strict(),grader:V,benchmarkProtocol:N6.nullable().default(null),automaticEvaluation:l({enabled:I()}).strict().default({enabled:!1}),residualProfile:l({profileId:T,serializedEnvelopeRank:d().int().positive().max(1024),maximumEnabledRank:d().int().positive().max(1024),topology:b("uniform_block_masked")}).strict(),schedule:p(z6).min(1).max(1e3),scheduleSealedAt:pe.nullable(),advancementPolicy:B6,executionPolicy:l({startWhenReady:b(!1)}).strict(),acceptedSeedEntryId:T.nullable(),acceptedDailyHeadEntryId:T.nullable(),promotedBindingId:T.nullable(),createdBy:T,createdAt:pe,updatedAt:pe}).strict().superRefine((e,t)=>{[...e.schedule].sort((m,u)=>m.ordinal-u.ordinal).some((m,u)=>m.ordinal!==u)&&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,u)=>m+u.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."})}),xR=l({source:U6,taskIds:p(T).min(1).max(1e5),observedFrom:pe,observedTo:pe,reviewedAt:pe,reviewedBy:T,sourceTaskset:Zt}).strict(),V6=xR.extend({derivedFamilyKeys:p(T).min(1).max(1e5),familyDerivation:l({algorithm:T,sourceTasksetHash:H}).strict(),selectionHash:H}).strict(),kR=rt("kind",[l({kind:b("base_model"),id:T,revision:i().trim().min(1).max(256)}).strict(),l({kind:b("model_version"),id:T,contentHash:H}).strict()]),K6=l({id:T,branchOrdinal:d().int().nonnegative(),rank:d().int().positive().max(1024),offsetStart:d().int().nonnegative(),offsetEnd:d().int().positive(),optimizationRole:v(["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."})}),W6=l({disposition:v(["advance","hold","no_signal"]),policy:l({id:T,version:d().int().positive()}).strict(),reasonCodes:p(T).min(1).max(100),summary:i().trim().min(1).max(5e3),decidedBy:T,decidedAt:pe}).strict(),G6=l({evaluationRunId:T,modelVersionId:T,taskset:Zt,grader:V,cohortRole:v(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:T.nullable().default(null),protocol:l({id:T,revision:d().int().positive(),contentHash:H}).strict().nullable().default(null)}).strict(),J6=l({attemptOrdinal:d().int().positive(),trainingPlanId:T.nullable(),modelRunId:T.nullable(),terminalStatus:v(["failed","cancelled"]),queuedAt:pe.nullable(),startedAt:pe.nullable(),completedAt:pe}).strict(),tl=l({seriesId:T,entryId:T,scheduleEntryId:T,ordinal:d().int().nonnegative(),releaseHash:H}).strict(),Z6=l({schemaVersion:b("openpond.modelComparisonSeriesEntry.v1"),id:T,seriesId:T,profileId:T,modelProjectId:T,scheduleEntryId:T,releaseHash:H,ordinal:d().int().nonnegative(),label:i().trim().min(1).max(100),role:SR,branch:v(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:H6,parent:kR,taskset:Zt,sourceTasksets:p(Zt).min(1).max(1e3),taskSelection:V6.nullable(),trainableRank:d().int().positive().max(1024),serializedEnvelopeRank:d().int().positive().max(1024),enabledCumulativeRank:d().int().positive().max(1024),trainableBlockId:T,residualBlocks:p(K6).min(1).max(1024),attemptOrdinal:d().int().positive().default(1),priorRunAttempts:p(J6).max(100).default([]),trainingPlanId:T.nullable(),modelRunId:T.nullable(),modelVersionId:T.nullable(),evaluations:p(G6).max(1e5),decision:W6.nullable(),promotionBindingId:T.nullable(),queuedAt:pe.nullable(),startedAt:pe.nullable(),completedAt:pe.nullable(),createdAt:pe,updatedAt:pe}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((s,c)=>s.offsetStart-c.offsetStart);n.some((s,c)=>s.offsetStart!==(c===0?0:n[c-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,c)=>s!==c+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});l({seriesId:T,scheduleEntryId:T,taskSelection:xR.nullable(),expectedSeriesRevision:d().int().positive()}).strict();const Y6=v(["base_reference","lora_adapter"]),wR=l({baseModel:l({source:b("huggingface"),repoId:T,revision:i().regex(/^[a-f0-9]{40}$/),configHash:H,tokenizerHash:H,licenseId:T,gated:I()}).strict(),processor:l({repository:T,revision:i().regex(/^[a-f0-9]{40}$/),configHash:H}).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."})}),Q6=l({schemaVersion:b("openpond.modelVersion.v1"),id:T,modelId:T,profileId:T,version:d().int().nonnegative(),kind:Y6,status:v(["available","failed"]),baseModel:fd,taskset:Zt,comparisonSeriesEntry:tl.nullable().optional(),evaluationTasksetRef:Zt.nullable().optional(),releaseGraph:l({resolvedBundleHash:H,profileRelease:Zt,harnessRelease:V,agentRelease:V.nullable(),grader:l({id:T,contentHash:H}).strict()}).strict(),artifactLineageId:T.nullable(),adapterStatus:v(["not_trained","trained"]),createdAt:pe,contentHash:H}).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."})}),X6=l({schemaVersion:b("openpond.rewardModelVersion.v1"),id:T,modelId:T,profileId:T,version:d().int().positive(),role:b("reward"),status:v(["available","failed"]),scope:v(["synthetic_smoke","human_preference"]),baseModel:fd,runtime:wR.nullable().default(null),taskset:Zt,preferenceDatasetRelease:V,releaseGraph:l({resolvedBundleHash:H,profileRelease:Zt,harnessRelease:V,grader:l({id:T,contentHash:H}).strict()}).strict(),artifacts:l({checkpoint:V.extend({objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(l({path:i().trim().min(1).max(512),sizeBytes:d().int().positive(),sha256:H}).strict()).min(4).max(128)}).strict(),adapter:V,scalarHead:V,bucketHead:V.nullable(),processorRelease:V}).strict(),qualificationReport:V.nullable(),createdAt:pe,contentHash:H}).strict(),eV=l({schemaVersion:b("openpond.rewardModelRunReceipt.v1"),provider:T,providerRunId:T,resolvedBundleHash:H,finalCheckpoint:V.extend({objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:V,scalarHead:V,bucketHead:V.nullable(),processorRelease:V,optimizerEvidence:V,managedExecutionReceipt:V.nullable().default(null),parameterDeltaHash:H,cleanup:l({computeReleased:I(),providerTerminalObserved:I()}).strict(),contentHash:H}).strict(),tV=F2(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}}},l({schemaVersion:b("openpond.rewardModelRun.v1"),id:T,rewardModelId:T,rewardModelVersionId:T.nullable(),profileId:T,role:b("reward"),scope:v(["synthetic_smoke","human_preference"]),status:v(["prepared","running","succeeded","failed","cancelled"]),taskset:Zt,tasksetRelease:V,preferenceDatasetRelease:V,recipeRelease:V,destinationId:T,quote:l({maximumSpendUsd:d().positive(),hourlyCostUsd:d().nonnegative().nullable()}).strict(),managedRunId:T.nullable(),progress:l({completedSteps:d().int().nonnegative(),totalSteps:d().int().positive(),latestLoss:d().finite().nullable()}).strict(),receipt:eV.nullable(),qualificationReport:V.nullable(),accruedSpendUsd:d().nonnegative().nullable(),failureOwner:v(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:i().trim().min(1).max(5e3).nullable(),startedAt:pe,completedAt:pe.nullable(),updatedAt:pe}).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."})}),nV=l({schemaVersion:b("openpond.modelRunReceipt.v1"),provider:T,providerRunId:T,assignmentHash:H,resultHash:H,transcriptHash:H,traceHash:H.nullable(),resolvedBundleHash:H,artifactPath:i().trim().min(1).max(2e3),cleanup:l({computeReleased:I(),tunnelClosed:I()}).strict(),telemetry:A6.nullable().default(null),contentHash:H}).strict(),Do=l({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),costUsd:d().nonnegative().nullable()}).strict(),US=i().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Vb=l({phase:v(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:T,attemptId:T,sessionId:T.nullable(),turnId:T.nullable(),passed:I(),score:d().min(0).max(1).nullable(),failureClass:zb.nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),latencyMs:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),startedAt:pe}).strict(),zS=l({targetTaskCount:d().int().nonnegative(),comparedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),lowerTaskCount:d().int().nonnegative(),higherTaskCount:d().int().nonnegative(),unchangedTaskCount:d().int().nonnegative()}).strict(),IR=l({target:b("all_tasks_lower"),targetTaskCount:d().int().nonnegative(),comparedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),lowerTaskCount:d().int().nonnegative(),higherTaskCount:d().int().nonnegative(),unchangedTaskCount:d().int().nonnegative(),baselineTokens:d().int().nonnegative(),refinedTokens:d().int().nonnegative(),tokenDelta:d().int(),tokenDeltaPercent:d().finite().nullable(),complete:I(),passed:I(),cohorts:l({adaptation:zS,heldOut:zS}).strict()}).strict(),Kb=l({baseline:Do,adaptation:Do,candidateAdaptation:Do,candidate:Do,refiner:Do,grader:Do}).strict(),aV=l({usage:Kb,observedSpendUsd:d().nonnegative(),attempts:p(Vb).max(1e4)}).strict(),iV=l({id:T,contentHash:H,artifactPath:i().trim().min(1).max(2e3)}).strict(),oV=l({schemaVersion:b("openpond.modelEvaluationReceipt.v1"),benchmarkId:T,resultManifest:l({id:T,contentHash:H,artifactPath:i().trim().min(1).max(2e3)}).strict(),stages:l({baseline:V,adaptation:V,refiner:V,candidateAdaptation:V,candidate:V,comparison:V}).strict(),usage:Kb,quality:l({baselinePassRate:d().min(0).max(1),candidatePassRate:d().min(0).max(1),adaptationBaselinePassRate:d().min(0).max(1),adaptationCandidatePassRate:d().min(0).max(1),adaptationCandidatePassed:I(),heldOutCandidatePassed:I(),passed:I()}).strict(),foregroundTokenDelta:d().int(),foregroundTokenDeltaPercent:d().finite().nullable(),taskEfficiency:IR.optional(),efficiency:l({grossForegroundTokenSavings:d().int(),overheadTokens:d().int().nonnegative(),firstPassNetTokenSavings:d().int(),breakEvenReuseCount:d().int().nonnegative().nullable(),amortizedTokenSavings:d().int(),amortizedReuseCount:d().int().positive()}).strict(),budget:l({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:I()}).strict(),evidenceSnapshot:V,lineage:l({adaptationEvidenceHash:H,refinerInputHash:H,refinerOutcomeHash:H,validationHash:H,applyReceiptHash:H,candidateRelease:V,valid:I()}).strict(),invalidReasons:p(i().trim().min(1).max(2e3)).max(100),attempts:p(Vb).max(1e4).default([]),terminalClassification:v(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:l({ref:i().trim().min(1).max(2e3),commit:US,baseCommit:US}).strict().nullable(),contentHash:H}).strict(),rV=l({schemaVersion:b("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:T,terminalClassification:b("inconclusive"),stopReason:v(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:i().trim().min(1).max(5e3),stoppedAfter:b("refiner"),baselineHarness:V,candidateHarness:V,refiner:l({id:T,contentHash:H,outcomeCount:d().int().nonnegative()}).strict(),usage:Kb,budget:l({maximumSpendUsd:d().nonnegative(),observedSpendUsd:d().nonnegative(),enforced:I()}).strict(),evidenceSnapshot:V,attempts:p(Vb).max(1e4),contentHash:H}).strict(),BS=l({level:b(.95),lower:d().finite(),upper:d().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."})}),sV=l({schemaVersion:b("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:b("model-comparison"),target:l({kind:v(["base_model","model_version","external_reference"]),label:i().trim().min(1).max(300),modelVersionId:T.nullable(),model:bn.nullable()}).strict(),taskset:Zt,grader:V,sampling:l({seeds:p(d().int()).min(1).max(100),repetitions:d().int().positive().max(20)}).strict(),deterministic:l({attemptedTaskCount:d().int().nonnegative(),completedTaskCount:d().int().nonnegative(),passedTaskCount:d().int().nonnegative(),failedTaskCount:d().int().nonnegative(),meanScore:d().finite().nullable(),passRate:d().min(0).max(1).nullable(),passRateCi95:BS.nullable()}).strict(),judge:l({judgeModel:bn,judgeRelease:V,rubricRelease:V,calibrationRelease:V,score:d().min(0).max(100),scoreCi95:BS,comparisonCount:d().int().positive(),wins:d().int().nonnegative(),ties:d().int().nonnegative(),losses:d().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(l({attemptId:T.nullable().default(null),taskId:T,seed:d().int(),repetition:d().int().nonnegative(),status:v(["succeeded","failed"]),deterministicScore:d().finite().nullable(),passed:I().nullable(),judgeScore:d().min(0).max(100).nullable(),judgePreference:v(["win","tie","loss"]).nullable(),transcriptHash:H.nullable(),traceHash:H.nullable(),transcriptArtifact:l({artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:l({artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:d().int().nonnegative().nullable().default(null),failureClass:zb.nullable()}).strict()).max(1e5),usage:l({policy:Do.nullable(),judge:Do.nullable(),observedSpendUsd:d().nonnegative().nullable(),evaluationGpuSeconds:d().nonnegative().nullable().default(null)}).strict(),managedServing:l({jobId:T,terminalState:v(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:d().int().nonnegative(),sourceAdapterSha256:H.nullable(),servedPolicyVersion:d().int().nonnegative().nullable(),servedAdapterSha256:H.nullable(),accruedSpendUsd:d().nonnegative(),cleanupAttestationHash:H,resourceCount:d().int().nonnegative(),activeResourceCount:b(0)}).strict().nullable().default(null),evidenceSnapshot:l({id:T,contentHash:H,artifactPath:i().trim().min(1).max(2e3)}).strict(),completedAt:pe,contentHash:H}).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."})}),lV=l({advancedEvaluation:Fb.optional(),benchmarkId:b("harness-refiner"),model:bn,upstreamModel:l({providerId:T,modelId:i().trim().min(1).max(300),revision:i().trim().min(1).max(300),pricing:l({version:i().trim().min(1).max(300),source:i().trim().min(1).max(300),effectiveAt:pe,inputUsdPerMillionTokens:d().nonnegative(),cachedInputUsdPerMillionTokens:d().nonnegative(),outputUsdPerMillionTokens:d().nonnegative()}).strict().optional()}).strict(),reasoningEffort:i().trim().min(1).max(100).nullable(),seeds:p(d().int()).min(1).max(100),repetitions:d().int().positive().max(20),maximumSpendUsd:d().nonnegative(),attemptPlan:p(l({stage:v(["baseline","adaptation","candidate_adaptation","candidate"]),split:i().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:d().int().positive()}).strict()).length(4)}).strict(),cV=l({benchmarkId:b("model-comparison"),target:l({kind:v(["base_model","model_version","external_reference"]),label:i().trim().min(1).max(300),modelVersionId:T.nullable(),model:bn.nullable()}).strict(),grader:V,judge:l({model:bn,release:V,rubricRelease:V,calibrationRelease:V,referenceLabel:i().trim().min(1).max(300)}).strict().nullable(),seeds:p(d().int()).min(1).max(100),repetitions:d().int().positive().max(20),maximumSpendUsd:d().nonnegative(),series:l({id:T,protocol:l({id:T,revision:d().int().positive(),contentHash:H}).strict()}).strict().nullable().default(null),panel:l({id:T,role:v(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:T.nullable()}).strict().nullable().default(null),comparisonPair:l({entryId:T,parent:kR,candidateModelVersionId:T}).strict().nullable().default(null),attemptPlan:p(l({stage:b("comparison"),split:i().trim().min(1).max(100),taskIds:p(T).min(1).max(1e5),attemptCount:d().int().positive()}).strict()).length(1)}).strict(),dV=gt([lV,cV]),uV=l({schemaVersion:b("openpond.modelRun.v1"),id:T,modelId:T,modelVersionId:T.nullable(),profileId:T,kind:v(["rollout_smoke","training","evaluation"]),status:v(["prepared","running","succeeded","failed","cancelled"]),method:v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:T.nullable(),taskset:Zt,comparisonSeriesEntry:tl.nullable().optional(),evaluationTasksetRef:Zt.nullable().optional(),harnessRelease:V.nullable().optional(),quote:l({maximumSpendUsd:d().nonnegative(),hourlyCostUsd:d().nonnegative().nullable()}).strict().nullable(),evaluation:dV.nullable().default(null),evaluationProgress:l({stage:v(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:d().int().nonnegative(),totalAttempts:d().int().positive(),accounting:aV.nullable().default(null),advancedAccounting:C6.optional(),evidenceSnapshot:iV.nullable().default(null)}).strict().nullable().default(null),reward:l({raw:d(),components:te(i(),d())}).strict().nullable(),receipt:gt([nV,oV,rV,sV,I6]).nullable(),adapterArtifactLineageId:T.nullable(),failure:i().trim().min(1).max(5e3).nullable(),startedAt:pe,completedAt:pe.nullable(),updatedAt:pe}).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"&&e.receipt.schemaVersion!=="openpond.advancedRefinerReviewReceipt.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 nie(e){const t=new Map;for(const C of e.attempts){const P=`${C.phase}\0${C.taskId}`,j=t.get(P);(!j||C.startedAt>j.startedAt||C.startedAt===j.startedAt&&C.attemptId>j.attemptId)&&t.set(P,C)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([C,P,j])=>{const R=new Map(n.filter($=>$.phase===j).map($=>[$.taskId,$]));return n.filter($=>$.phase===P).flatMap($=>{const O=R.get($.taskId);return O?[{cohort:C,taskId:$.taskId,baseline:$,refined:O,tokenDelta:O.totalTokens-$.totalTokens}]:[]})}),o=new Set(n.filter(C=>C.phase==="baseline"||C.phase==="adaptation").map(C=>C.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(C=>C.phase==="adaptation").map(C=>C.taskId)).size,held_out:new Set(n.filter(C=>C.phase==="baseline").map(C=>C.taskId)).size},c=(C,P)=>({targetTaskCount:P,comparedTaskCount:C.length,passedTaskCount:C.filter(j=>j.tokenDelta<0).length,failedTaskCount:C.filter(j=>j.tokenDelta>=0).length,lowerTaskCount:C.filter(j=>j.tokenDelta<0).length,higherTaskCount:C.filter(j=>j.tokenDelta>0).length,unchangedTaskCount:C.filter(j=>j.tokenDelta===0).length}),m=c(a,r),u=a.reduce((C,P)=>C+P.baseline.totalTokens,0),f=a.reduce((C,P)=>C+P.refined.totalTokens,0),g=f-u,S=a.length===r;return{summary:IR.parse({target:"all_tasks_lower",...m,baselineTokens:u,refinedTokens:f,tokenDelta:g,tokenDeltaPercent:u>0?g/u*100:null,complete:S,passed:S&&m.passedTaskCount===r,cohorts:{adaptation:c(a.filter(C=>C.cohort==="adaptation"),s.adaptation),heldOut:c(a.filter(C=>C.cohort==="held_out"),s.held_out)}}),pairs:a}}const mV=v(["measuring","up_to_date","needs_attention"]),pV=v(["fixed","retained","regressed","unresolved","unavailable"]),FS=l({evaluationRunId:T,attemptKey:T,artifactPath:i().trim().min(1).max(2e3),jsonPointer:i().trim().min(1).max(1e3),transcriptHash:H.nullable(),traceHash:H.nullable()}).strict(),_g=l({level:b(.95),lower:d().finite(),upper:d().finite()}).strict(),fV=l({panelId:T,panelRole:ap,passLabel:T.nullable(),taskset:Zt,attempted:d().int().nonnegative(),available:d().int().nonnegative(),passed:d().int().nonnegative(),strictSuccess:d().min(0).max(1).nullable(),strictSuccessCi95:_g.nullable(),judgeScore:d().min(0).max(100).nullable(),judgeScoreCi95:_g.nullable()}).strict(),hV=l({schemaVersion:b("openpond.modelCurrencySnapshot.v1"),id:T,contentHash:H,seriesId:T,protocol:l({id:T,revision:d().int().positive(),contentHash:H}).strict(),entryId:T,passLabel:T,parent:rt("kind",[l({kind:b("base_model"),id:T,revision:i().trim().min(1).max(500)}).strict(),l({kind:b("model_version"),id:T,contentHash:H}).strict()]),candidate:l({kind:b("model_version"),id:T,contentHash:H}).strict(),sources:l({evaluationRunIds:p(T).max(1e5),attemptIds:p(T).max(1e6),tasksets:p(Zt).max(1e4),grader:V,judge:V.nullable(),calibration:V.nullable()}).strict(),matches:p(l({key:T,panelId:T,panelRole:ap,taskId:T,issueFamilyId:T,seed:d().int(),repetition:d().int().nonnegative(),classification:pV,parentPassed:I().nullable(),candidatePassed:I().nullable(),parentAttempt:FS.nullable(),candidateAttempt:FS.nullable()}).strict()).max(1e6),taskIds:l({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(fV).max(1e4),metrics:l({knownIssueCoverage:d().min(0).max(1).nullable(),issueFamilyGeneralization:d().min(0).max(1).nullable(),behavioralRetention:d().min(0).max(1).nullable(),currentAcquisitionDelta:d().finite().nullable(),retainedDeltaPoints:d().finite().nullable(),frontierStrictDelta:d().finite().nullable(),pairedPValue:d().min(0).max(1).nullable(),wins:d().int().nonnegative(),ties:d().int().nonnegative(),losses:d().int().nonnegative()}).strict(),statistics:l({matchedAttemptCount:d().int().nonnegative(),strictDelta:d().finite().nullable(),strictDeltaCi95:_g.nullable(),exactPairedBinaryPValue:d().min(0).max(1).nullable(),pairedBootstrapSamples:d().int().positive()}).strict(),criteria:l({allRequiredAttemptsTerminal:I(),criticalCorrectionPassRate:d().min(0).max(1).nullable(),siblingPassRate:d().min(0).max(1).nullable(),behavioralRetentionRate:d().min(0).max(1).nullable(),retainedRegressionPoints:d().finite().nullable(),criticalPriorRegressionCount:d().int().nonnegative(),thresholdRelease:V}).strict(),efficiency:l({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),totalTokens:d().int().nonnegative(),costUsd:d().nonnegative().nullable(),latencyMs:d().int().nonnegative(),tokensPerSuccess:d().nonnegative().nullable(),throughputPerHour:d().nonnegative().nullable(),gpuSeconds:d().nonnegative().nullable()}).strict(),invariants:l({systemPromptHash:H,toolSchema:V,application:V,harness:V,runtime:V,grader:V,autoRefinerEnabled:I()}).strict(),evidenceState:mV,evidenceReasons:p(T).max(100),projectedAt:pe}).strict(),Cu=rt("kind",[l({kind:b("base_model"),id:T,revision:i().trim().min(1).max(500),label:i().trim().min(1).max(300)}).strict(),l({kind:b("model_version"),id:T,label:i().trim().min(1).max(300)}).strict(),l({kind:b("captured_model"),id:T,label:i().trim().min(1).max(300)}).strict()]),mc=gt([l({source:b("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:d().finite().nullable(),components:te(i(),d().finite()).default({})}).strict(),l({source:b("imported_response"),modelLabel:i().trim().min(1).max(300),modelVersionId:T.nullable().default(null),response:ie().refine(e=>e!==void 0,"An imported model response is required."),reward:d().finite().nullable().default(null),components:te(i(),d().finite()).default({})}).strict()]),gV=gt([l({taskId:T,target:Cu,attempt:mc}).strict(),l({taskId:T,target:v(["base","current"]).default("current"),attempt:mc}).strict(),l({taskId:T,target:v(["base","current"]).default("current"),evaluationRunId:T,attemptId:T,reward:d().finite().nullable(),components:te(i(),d().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);l({schemaVersion:b("openpond.continualLearningDailyBatchManifest.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:d().int().positive().max(1e4),sourceTaskset:Zt,taskIds:p(T).min(1).max(1e3),observedAttempts:p(gV).max(1e3).default([]),sourceFileName:i().trim().min(1).max(500).nullable().default(null),availableAt:pe}).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}:${yV(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 vV=l({schemaVersion:b("openpond.continualLearningDailyBatch.v1"),id:T,seriesId:T,scheduleEntryId:T,dayOrdinal:d().int().positive().max(1e4),label:i().trim().min(1).max(100),runMode:v(["automatic","manual"]).optional(),source:v(["json_upload","sealed_fixture"]),sourceFileName:i().trim().min(1).max(500).nullable(),sourceTaskset:Zt,tasks:p(l({taskId:T,taskContentHash:H,familyKey:T,disposition:v(["include","defer","exclude"]).nullable(),oracleReview:v(["pending","confirmed","needs_correction"]),note:i().trim().max(2e3),observedAttempt:mc.nullable(),baselineAttempt:mc.nullable().default(null),responses:p(l({target:Cu,attempt:mc}).strict()).max(100).default([]),stagedAt:pe.nullable().default(null),queuedEntry:tl.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:l({status:v(["awaiting","running","ready","failed"]),requestedTargets:p(v(["base","current"])).max(2).default(["base","current"]),requestedPolicies:p(Cu).max(100).default([]),runs:p(l({target:Cu,runId:T}).strict()).max(100).default([]),baselineRunId:T.nullable(),currentRunId:T.nullable(),currentPolicy:rt("kind",[l({kind:b("base_model"),id:T}).strict(),l({kind:b("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:v(["pending","reviewed","queued"]),queuedEntry:tl.nullable(),reviewedBy:T.nullable(),reviewedAt:pe.nullable(),availableAt:pe,revision:d().int().positive(),createdAt:pe,updatedAt:pe}).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=>_R(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."})}),bV=l({schemaVersion:b("openpond.continualBenchIssueReview.v1"),id:T,seriesId:T,scheduleEntryId:T,passLabel:T,packet:j6,splitManifest:l({id:T,contentHash:H}).strict(),decisions:p(l({taskId:T,disposition:v(["include","defer","exclude"]).nullable(),note:i().trim().max(2e3)}).strict()).min(2).max(1e4),status:v(["pending","reviewed","queued"]),queuedEntry:tl.nullable(),reviewedBy:T.nullable(),reviewedAt:pe.nullable(),revision:d().int().positive(),createdAt:pe,updatedAt:pe}).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 _R(e){return`${e.kind}:${e.id}`}function yV(e){return typeof e=="string"?e:_R(e)}const ai=i().trim().min(1).max(240),Oa=i().trim().min(8).max(256),CR=v(["grpo","dapo","gspo-token"]),$c=l({id:ai,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:Oa}),SV=l({maxRollouts:d().int().positive().max(1e6),maxEnvironmentExecutions:d().int().positive().max(1e6),maxInputTokens:d().int().positive(),maxOutputTokens:d().int().positive(),maxOptimizerSteps:d().int().positive().max(1e6),wallTimeMs:d().int().positive(),maximumCostUsd:d().nonnegative().nullable()}),xV=l({method:b("grpo"),groupSize:d().int().min(2).max(128),normalization:b("group_standardized"),advantageEpsilon:d().positive().max(.01).default(1e-8),loss:CR,clipRange:d().positive().max(1).default(.2),iterations:d().int().min(2).max(16).default(2),microbatchSize:d().int().positive().max(128).default(1),gradientAccumulationSteps:d().int().positive().max(128).default(1),adamw:uR}),RR=l({method:b("ppo"),valueModel:$c,gamma:d().min(0).max(1),gaeLambda:d().min(0).max(1),policyClip:d().positive().max(1),valueClip:d().positive().max(10),valueLossCoefficient:d().nonnegative().max(10),ppoEpochs:d().int().positive().max(100),minibatchSize:d().int().positive().max(1e5)}),kV=rt("method",[xV,RR]),PR=l({rewardModelVersion:l({id:ai,contentHash:Oa}).strict(),qualificationReport:l({id:ai,contentHash:Oa}).strict().nullable().default(null),evaluationReferences:p(l({id:ai,contentHash:Oa}).strict()).max(1e3).default([]),checkpoint:l({id:ai,contentHash:Oa,objectRef:i().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:p(l({path:i().trim().min(1).max(512),sizeBytes:d().int().positive(),sha256:Oa}).strict()).min(4).max(128)}).strict(),runtime:wR,processorRelease:l({id:ai,contentHash:Oa}).strict(),rewardComposerRelease:l({id:ai,contentHash:Oa}).strict(),executionReceipt:l({id:ai,contentHash:Oa}).strict()}).strict(),AR=l({schemaVersion:b("openpond.policyOptimization.v1"),policyModel:$c,referenceModel:$c,dataset:l({tasksetId:ai,tasksetHash:Oa,split:b("train"),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:d().int(),maxExamples:d().int().positive().max(1e5)}),sampler:l({temperature:d().min(0).max(2),topP:d().min(0).max(1),maxOutputTokens:d().int().positive().max(32768),maxTurns:d().int().positive().max(1e3),concurrency:d().int().positive().max(1e3)}),environment:l({id:ai,version:i().trim().min(1).max(256),toolContractHash:Oa}),reward:l({graderId:ai,graderHash:Oa,learnedPreference:PR.nullable().default(null)}),kl:l({coefficient:d().nonnegative().nullable(),referenceConstraint:b("fixed_reference")}),budgets:SV,checkpointEverySteps:d().int().positive(),seed:d().int(),evaluationSplit:b("frozen_eval"),optimizer:kV}),Ee=i().trim().min(1).max(240),jt=i().trim().min(1),vt=i().trim().min(8).max(256),hd=te(i(),ie()).default({}),TR=l({schemaVersion:b("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:v(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:v(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:i().max(2e4).nullable().default(null),contextWindowTokens:d().int().min(128).max(32768).default(1024),maxOutputTokens:d().int().min(1).max(512).default(64),temperature:d().min(0).max(2).default(0),repetitionPenalty:d().min(.5).max(2).default(1.1),noRepeatNgramSize:d().int().min(0).max(10).default(3),compaction:v(["off","when_needed"]).default("when_needed"),keepWarmSeconds:d().int().min(0).max(3600).default(300),updatedAt:jt.nullable().default(null)}),wV=TR.parse({}),IV=l({schemaVersion:b("openpond.managedAdapterServingProjection.v1"),teamId:Ee.nullable().default(null),source:b("sandbox_managed_rl"),sourceRef:Ee,canonicalArtifactId:Ee.nullable(),canonicalArtifactState:v(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:Ee.nullable(),canonicalDeploymentState:v(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:v(["pending","imported","ready","failed"]),customerBindingAllowed:I().default(!1),artifactContentHash:vt.nullable().default(null),baseProfileId:Ee.nullable().default(null),publishedAt:jt.nullable(),lastSyncedAt:jt,lastError:i().trim().min(1).max(5e3).nullable()});function aie(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function ER(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function iie(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"&&ER(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function oie(e){const t=e.managedServing;return t?ER(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Wb="openpond.crossSystemOperations.v1",rie="1.0.0",jR="openpond.crossSystemTools.v1",_V=["search_crm","query_billing","search_support","run_python"],CV=v(["train","validation","frozen_eval"]),RV=v(["easy","medium","hard"]),PV=v(["renewal_risk_v2"]);v(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);l({seed:d().int().nonnegative(),split:CV,difficulty:RV,scenarioProfile:PV.optional()});const gh={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},vh={type:"integer",minimum:1,maximum:50,default:25},MR=[{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:gh,limit:vh}}},{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:gh,limit:vh}}},{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:gh,limit:vh}}},{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}}}}],gd=LV({schemaVersion:jR,tools:MR}),AV=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${gd}.`,"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(" "),TV=15;function EV(e="auto"){return[AV,"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: ${TV}.`,`Registered tool signatures: ${MR.map(jV).join("; ")}`].join(`
|
|
185
|
+
`)}EV();function jV(e){const t=am(e.parameters),n=am(t.properties),a=OR(t.required),o=Object.fromEntries(a.map(r=>[r,Ru(n[r])]));return`${e.name}(${JSON.stringify(o)})`}function Ru(e){const t=am(e),n=Cg(t.anyOf);if(n.length)return n.map(Ru).join("|");const a=Cg(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[Ru(t.items)];if(t.type==="object"){const o=am(t.properties),r=OR(t.required);return Object.fromEntries(r.map(s=>[s,Ru(o[s])]))}return typeof t.type=="string"?t.type:"unknown"}function am(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Cg(e){return Array.isArray(e)?e:[]}function OR(e){return Cg(e).filter(t=>typeof t=="string")}const im=v(_V),MV=rt("kind",[l({kind:b("model"),turn:d().int().nonnegative(),content:i().max(1e5)}),l({kind:b("tool_call"),turn:d().int().nonnegative(),callId:i().trim().min(1).max(240),name:im,arguments:te(i(),ie())}),l({kind:b("tool_result"),turn:d().int().nonnegative(),callId:i().trim().min(1).max(240),name:im,ok:I(),result:ie(),rows:d().int().nonnegative(),bytes:d().int().nonnegative(),durationMs:d().int().nonnegative(),error:i().trim().min(1).max(2e4).nullable()}),l({kind:b("final"),turn:d().int().nonnegative(),content:i().max(1e5)})]),OV=l({schemaVersion:b(Wb),id:i().trim().min(1).max(240),worldId:i().trim().min(1).max(240),taskId:i().trim().min(1).max(240),toolContractHash:b(gd),modelRef:l({providerId:i().trim().min(1),modelId:i().trim().min(1)}).nullable(),status:v(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:p(MV).max(1e3),startedAt:i().trim().min(1),completedAt:i().trim().min(1),infrastructureError:i().trim().min(1).max(2e4).nullable(),metadata:te(i(),ie()).default({})}),$V=l({schemaVersion:b(Wb),trajectoryId:i().trim().min(1).max(240),outcome:v(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:d().min(0).max(1.15).nullable(),rewardEligible:I(),exactAnswer:I(),components:l({exactAnswer:d().min(0).max(1),efficiency:d().min(0).max(.1),conciseOutput:d().min(0).max(.05)}),metrics:l({toolCalls:d().int().nonnegative(),rowsRead:d().int().nonnegative(),bytesRead:d().int().nonnegative(),consecutiveRetrievalCalls:d().int().nonnegative(),wallTimeMs:d().int().nonnegative(),parseFailures:d().int().nonnegative(),budgetExhausted:I()}),parsedAnswer:ie().nullable(),feedback:p(i().trim().min(1).max(5e3)).max(100)}),NV=l({id:i().trim().min(1).max(240),type:b("function"),function:l({name:im,arguments:i().max(2e4)})}),$R=l({role:v(["system","user","assistant","tool"]),content:i().max(2e5).nullable(),tool_call_id:i().trim().min(1).max(240).optional(),tool_calls:p(NV).max(4).optional()});l({schemaVersion:b(Wb),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:b(gd),approval:l({status:b("approved"),approvedBy:i().trim().min(1).max(240),approvedAt:i().trim().min(1)}),messages:p($R).min(3).max(1e3)});const DV=l({tasksetTaskId:i().trim().min(1).max(240),environmentTaskId:i().trim().min(1).max(240),family:v(["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(im).min(1).max(100),toolCallCount:d().int().positive(),messageCount:d().int().min(3),reward:d().min(0).max(1.15),messages:p($R).min(3).max(1e3)}),HV=l({status:b("approved"),approvedBy:i().trim().min(1).max(240),approvedAt:i().trim().min(1),previewHash:i().trim().min(8).max(256),trajectoryCount:d().int().positive()});l({schemaVersion:b("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:i().trim().min(1).max(240),tasksetHash:i().trim().min(8).max(256),tasksetRevision:d().int().positive(),previewHash:i().trim().min(8).max(256),toolContractHash:b(gd),status:v(["ready_for_review","approved"]),approval:HV.nullable(),tasks:p(DV).min(1).max(100)});function LV(e){const t=Rg(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`${jR}:${VS(n)}${VS(a)}`}function Rg(e){return Array.isArray(e)?`[${e.map(Rg).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Rg(n)}`).join(",")}}`:JSON.stringify(e)}function VS(e){return(e>>>0).toString(16).padStart(8,"0")}const qV=l({schemaVersion:b("openpond.singleTurnPolicyTrajectory.v1"),id:Ee,taskId:Ee,status:v(["completed","infrastructure_failure"]),promptHash:vt,responseText:i().max(2e6),infrastructureError:i().trim().min(1).max(1e4).nullable(),startedAt:jt,completedAt:jt,metadata:hd}),UV=l({schemaVersion:b("openpond.ppoTrajectory.v1"),id:Ee,taskId:Ee,policyModelId:Ee,referenceModelId:Ee,valueModelId:Ee,steps:p(l({index:d().int().nonnegative(),observationHash:vt,actionTokenIds:p(d().int().nonnegative()).min(1),terminated:I(),truncated:I(),reward:d(),policyLogProbability:d(),referenceLogProbability:d(),valuePrediction:d(),return:d(),advantage:d(),mask:d().min(0).max(1)})).min(1).max(1e5),createdAt:jt}),zV=l({schemaVersion:b("openpond.exactAnswerVerifierResult.v1"),outcome:v(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:vt,score:d().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),expectedAnswerHash:vt,extractedAnswer:i().max(2e4).nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3)}),BV=l({schemaVersion:b("openpond.rolloutTrajectoryReceipt.v1"),id:Ee,jobId:Ee,planId:Ee,tasksetId:Ee,tasksetHash:vt,taskId:Ee,split:b("train"),correlationId:Ee,provider:Ee,providerTrace:l({invocationId:Ee,experimentId:Ee,rolloutId:Ee,runId:Ee,rowId:Ee}),optimizerMethod:v(["grpo","ppo"]).default("grpo"),evidenceLevels:l({requested:v(["trajectory","aggregate","provider_reported"]),observed:v(["trajectory","aggregate","provider_reported"]),providerReported:v(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:l({rollouts:d().int().nonnegative(),environmentExecutions:d().int().nonnegative(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),optimizerSteps:d().int().nonnegative(),costUsd:d().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:l({id:Ee,version:i().trim().min(1).max(256),worldId:Ee,worldHash:vt,toolContractHash:vt}),policy:l({modelId:Ee,checkpointId:Ee.nullable(),completionParametersHash:vt}),status:v(["received","running","succeeded","failed"]),failureClass:v(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:l({eligible:I(),raw:d().min(0).max(1.15).nullable(),normalized:d().min(0).max(1).nullable(),components:te(i(),d())}),trajectory:gt([OV,qV,UV]).nullable(),verifier:gt([$V,zV]).nullable(),providerStatus:te(i(),ie()).default({}),receivedAt:jt,startedAt:jt.nullable(),completedAt:jt.nullable(),updatedAt:jt}),sie="dataset-exact-answer",lie="dataset-exact-answer-v1",cie="no-tools-v1",Xo=v(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),ip=v(["lora","full"]),qr=v(["openpond_managed"]),FV=l({schemaVersion:b("openpond.sftRecipe.v1"),method:b("sft"),parameterization:b("lora"),baseModel:l({id:Ee,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:vt}),dataset:l({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),completionOnly:I(),maxSequenceLength:d().int().positive().max(32768),maxExamples:d().int().positive().max(1e5).default(1e3),selectionStrategy:b("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:d().int().default(17)}),lora:l({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),optimizer:l({learningRate:d().positive(),epochs:d().positive().max(100),maxSteps:d().int().positive().max(1e6),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int()}),resourceLimits:l({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})});l({id:Ee,input:te(i(),ie()),expectedOutput:te(i(),ie()),tags:p(Ee).max(100).default([])});l({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)});l({id:Ee,input:te(i(),ie()),tags:p(Ee).max(100).default([])});l({schemaVersion:b("openpond.rewardModelRecipe.v1"),method:b("reward_model"),parameterization:b("lora_with_scalar_head"),runScope:v(["synthetic_smoke","human_preference"]),baseModel:l({id:Ee,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),processorRevision:i().trim().min(1).max(256),chatTemplateHash:vt}).strict(),tasksetRelease:V,preferenceDatasetRelease:V,processorRelease:V,input:l({kind:b("structured_text"),serialization:v(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:d().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:l({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:p(Ee).min(1).max(100)}).strict(),heads:l({scalar:b("pooled_hidden_state_linear"),bucket:v(["none","three_class"]).default("three_class")}).strict(),loss:l({ranking:b("bradley_terry"),rankingWeight:d().positive(),bucketWeight:d().nonnegative(),tieWeight:d().nonnegative()}).strict(),optimizer:l({learningRate:d().positive(),maxSteps:d().int().positive().max(1e5),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int(),checkpointEverySteps:d().int().positive().max(1e5)}).strict(),resourceLimits:l({wallTimeMs:d().int().positive().max(1440*60*1e3),maxExamples:d().int().positive().max(1e5),maxInputCharacters:d().int().positive().max(5e5).default(32e3),maxImagePixels:d().int().positive().max(1e8).optional(),maximumSpendUsd:d().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 VV=l({schemaVersion:b("openpond.rftRecipe.v1"),method:b("grpo"),parameterization:b("lora"),baseModel:l({id:Ee,revision:i().trim().min(1).max(256),tokenizerRevision:i().trim().min(1).max(256),chatTemplateHash:vt}),dataset:l({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),maxPromptTokens:d().int().positive().max(32768),maxExamples:d().int().positive().max(1e5).default(1e3),selectionStrategy:v(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:l({rank:d().int().positive().max(256)}),rollout:l({groupSize:d().int().min(2).max(64),concurrency:d().int().positive().max(32),maxTurns:d().int().positive().max(100),maxOutputTokens:d().int().positive().max(8192),temperature:d().min(0).max(2),topP:d().positive().max(1),seed:d().int()}),optimizer:l({learningRate:d().positive(),maxSteps:d().int().positive().max(1e5),clipRange:d().positive().max(1).default(.2),iterations:d().int().min(2).max(16).default(2),microbatchSize:d().int().positive().max(64).default(1),gradientAccumulationSteps:d().int().positive().max(64).default(1),advantageEpsilon:d().positive().max(.01).default(1e-8),adamw:uR}),loss:l({method:CR.default("grpo"),klBeta:d().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:l({graderId:Ee,graderHash:vt,environmentId:Ee,environmentVersion:i().trim().min(1).max(256),toolContractHash:vt,learnedPreference:PR.nullable().optional()}),resourceLimits:l({wallTimeMs:d().int().positive().max(1440*60*1e3),maxGpuSeconds:d().int().positive().max(10800).optional(),maxRollouts:d().int().positive().max(1e5),maxPayloadBytes:d().int().positive().max(10*1024*1024)}),policyOptimization:AR.nullable().default(null),continuation:l({schemaVersion:b("openpond.crossJobContinuationRequest.v1"),parentArtifact:V,sourceArtifact:l({jobId:Ee,artifactId:Ee,checkpointId:Ee,contentHash:vt}).strict(),optimizerMode:v(["continue","reset"])}).strict().optional()}),KV=l({schemaVersion:b("openpond.dpoRecipe.v1"),method:b("dpo"),parameterization:b("lora"),policyModel:$c,referenceModel:$c,dataset:l({trainSplit:b("train"),validationSplit:v(["validation","frozen_eval"]),maxPairs:d().int().positive().max(1e5),maxPromptTokens:d().int().positive().max(32768),maxCompletionTokens:d().int().positive().max(32768),selectionStrategy:b("stable_hash_top_n"),selectionSeed:d().int()}),lora:l({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),loss:l({variant:b("sigmoid"),beta:d().positive().max(10),labelSmoothing:d().min(0).max(.5).default(0)}),optimizer:l({learningRate:d().positive(),epochs:d().positive().max(100),maxSteps:d().int().positive().max(1e6),batchSize:d().int().positive().max(1e4),gradientAccumulationSteps:d().int().positive().max(1e4),seed:d().int()}),referenceLogprobs:l({cacheSchemaVersion:b("openpond.dpoReferenceLogprobs.v1"),cacheKey:vt,invalidationHash:vt}),resourceLimits:l({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})}),WV=l({schemaVersion:b("openpond.ppoRecipe.v1"),method:b("ppo"),parameterization:b("lora"),policyOptimization:AR.extend({optimizer:RR}),lora:l({rank:d().int().positive().max(256),alpha:d().positive().max(1024),dropout:d().min(0).max(1),targetModules:p(Ee).min(1).max(100)}),valueHead:l({initialization:b("policy_hidden_state_linear"),optimizerLearningRate:d().positive(),artifactName:b("value_head.safetensors")}),policyLearningRate:d().positive(),resume:l({checkpointId:Ee.nullable(),policyHash:vt,referenceHash:vt,valueModelHash:vt,optimizerStateHash:vt.nullable()}),resourceLimits:l({cpuThreads:d().int().positive().max(256),memoryBytes:d().int().positive(),wallTimeMs:d().int().positive()})}),GV=l({schemaVersion:b("openpond.unsupportedRecipe.v1"),method:Xo.exclude(["sft","dpo","grpo","ppo"]),parameterization:ip,unsupportedReason:i().trim().min(1).max(5e3)}),NR=gt([FV,KV,VV,WV,GV]),JV=l({schemaVersion:b("openpond.trainingDestinationCapabilities.v1"),destinationId:qr,available:I(),methods:p(Xo),parameterizations:p(ip),modelAllowlist:p(Ee).default([]),maxDatasetBytes:d().int().nonnegative().nullable(),environmentPlacements:p(v(["none","local","remote","colocated","provider_native"])),nonProduction:I(),unavailableReason:i().trim().min(1).max(5e3).nullable(),checkedAt:jt}),ZV=l({destinationId:qr,available:I(),methods:p(Xo),parameterizations:p(ip),nonProduction:I(),unavailableReason:i().trim().min(1).max(5e3).nullable()}),YV=l({schemaVersion:b("openpond.baseModelCandidate.v1"),selectionKey:Ee,label:i().trim().min(1).max(500),sourceLabel:i().trim().min(1).max(500),preference:fd,available:I(),nonProduction:I(),unavailableReason:i().trim().min(1).max(5e3).nullable(),methods:p(Xo),executionOptions:p(ZV).min(1)}),QV=l({code:Ee,severity:v(["warning","error"]),path:i().trim().max(2e3).nullable(),message:i().trim().min(1).max(5e3)}),XV=l({schemaVersion:b("openpond.trainingCompatibility.v1"),compatible:I(),destinationId:qr,tasksetId:Ee,recipeMethod:Xo,issues:p(QV),checkedAt:jt}),eK=gt([UC,v(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);l({method:Xo,state:v(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:p(eK).default([]),reasons:p(i().trim().min(1).max(5e3)).default([]),destinationId:qr.nullable().default(null)});v(["small","standard","custom","small_experiment"]);const tK=U_,DR=l({schemaVersion:b("openpond.trainingPlan.v1"),id:Ee,modelId:Ee,tasksetId:Ee,tasksetHash:vt,comparisonSeriesEntry:tl.nullable().optional(),evaluationTasksetRef:Zt.nullable().optional(),harnessRelease:V.nullable().optional(),modelImprovementQualification:V.nullable().optional(),destinationId:qr,recipe:NR,environmentPlacement:v(["none","local","remote","colocated","provider_native"]),compatibility:XV,dataPolicy:l({exportApproved:I(),approvedSourceIds:p(Ee),retentionDays:d().int().nonnegative().nullable(),region:i().trim().min(1).max(200).nullable()}),estimatedCostUsd:d().nonnegative().nullable(),createdAt:jt,contentHash:vt}),nK=l({path:i().trim().min(1).max(2e3),sha256:vt,sizeBytes:d().int().nonnegative(),role:v(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Gb=l({schemaVersion:b("openpond.trainingBundle.v1"),id:Ee,planId:Ee,tasksetId:Ee,tasksetHash:vt,recipeHash:vt,files:p(nK).min(1).max(1e6),totalSizeBytes:d().int().nonnegative(),sourceIds:p(Ee),excludedSourceIds:p(Ee),containsRawChats:b(!1),containsSecrets:b(!1),containsHiddenGraderAssets:b(!1),createdAt:jt,contentHash:vt});l({schemaVersion:b("openpond.trainingBundleExport.v1"),manifest:Gb,files:p(l({path:i().trim().min(1).max(2e3),sha256:vt,sizeBytes:d().int().nonnegative(),encoding:b("base64"),content:i()})).min(1),contentHash:vt});l({schemaVersion:b("openpond.trainingPreparedStart.v1"),plan:DR,bundle:Gb,approvalActor:Ee.nullable(),preparedAt:jt});l({schemaVersion:b("openpond.trainingApproval.v1"),evaluationTasksetRef:Zt.nullable().optional(),id:Ee,planId:Ee,bundleHash:vt,harnessRelease:V.nullable().optional(),modelImprovementQualification:V.nullable().optional(),destinationId:qr,modelId:Ee,method:Xo,parameterization:ip,maximumCostUsd:d().nonnegative().nullable(),approvedBy:Ee,approvedAt:jt});l({schemaVersion:b("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Zt.nullable().optional(),modelProjectId:Ee,sourceProjectRevision:d().int().positive(),profileId:Ee,taskset:l({id:Ee,revision:d().int().positive(),contentHash:vt}).strict(),tasksetRelease:V,harnessRelease:V,baseModel:fd,method:Xo}).strict();const aK=v(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),HR=l({schemaVersion:b("openpond.trainingJob.v1"),id:Ee,planId:Ee,bundleHash:vt,approvalId:Ee,destinationId:qr,status:aK,nonProduction:I(),workerPid:d().int().positive().nullable(),startedAt:jt.nullable(),completedAt:jt.nullable(),error:i().trim().min(1).max(2e4).nullable(),createdAt:jt,updatedAt:jt,metadata:hd}),iK=l({schemaVersion:b("openpond.trainingJobEvent.v1"),id:Ee,jobId:Ee,sequence:d().int().nonnegative(),type:v(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:jt,payload:hd}),oK=l({schemaVersion:b("openpond.sftStepMetric.v1"),step:d().int().nonnegative(),maxSteps:d().int().positive(),timestamp:jt,epoch:d().nonnegative().nullable(),loss:d().nullable(),learningRate:d().nonnegative().nullable(),gradientNorm:d().nonnegative().nullable(),entropy:d().nonnegative().nullable(),meanTokenAccuracy:d().min(0).max(1).nullable(),preferenceAccuracy:d().min(0).max(1).nullable().default(null),preferenceMargin:d().nullable().default(null),chosenReward:d().nullable().default(null),rejectedReward:d().nullable().default(null),chosenLogProbability:d().nullable().default(null),rejectedLogProbability:d().nullable().default(null),reward:d().nullable().default(null),policyLoss:d().nullable().default(null),advantageLoss:d().nullable().default(null),inputTokensSeen:d().int().nonnegative().nullable(),memoryBytes:d().int().nonnegative().nullable(),elapsedSeconds:d().nonnegative().nullable()}),rK=l({schemaVersion:b("openpond.policyOptimizationMetric.v1"),method:v(["grpo","ppo"]),step:d().int().nonnegative(),timestamp:jt,learningRate:d().nonnegative().nullable().default(null),policyLoss:d().nullable(),valueLoss:d().nullable(),gradientNorm:d().nonnegative().nullable().default(null),meanReward:d().nullable(),meanReturn:d().nullable(),kl:d().nullable(),behaviorPolicyKlPreUpdate:d().nonnegative().nullable().default(null),entropy:d().nullable(),policyClipFraction:d().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:d().min(0).max(1).nullable().default(null),valueClipFraction:d().min(0).max(1).nullable(),explainedVariance:d().nullable(),rolloutLearnerLag:d().int().nonnegative().nullable(),inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),environmentExecutions:d().int().nonnegative(),trajectoryCount:d().int().nonnegative().nullable().default(null),costUsd:d().nonnegative().nullable()}),sK=l({schemaVersion:b("openpond.managedTrainingRunEvidence.v2"),provider:Ee,providerRunId:Ee,state:Ee,progress:l({targetOptimizerSteps:d().int().nonnegative(),committedOptimizerSteps:d().int().nonnegative(),skippedOptimizerSteps:d().int().nonnegative()}),reward:l({finalMean:d().nullable(),variance:d().nonnegative().nullable(),minimum:d().nullable(),maximum:d().nullable(),distinctValueCount:d().int().nonnegative(),noSignalGroupCount:d().int().nonnegative(),trajectoryCount:d().int().nonnegative(),eligibleTrajectoryCount:d().int().nonnegative()}),usage:l({inputTokens:d().int().nonnegative(),outputTokens:d().int().nonnegative(),environmentExecutions:d().int().nonnegative()}),resource:l({provider:Ee,gpuType:i().trim().min(1).max(300).nullable(),gpuCount:d().int().nonnegative().nullable(),hourlyCostUsd:d().nonnegative().nullable(),durationSeconds:d().nonnegative().nullable(),gpuSeconds:d().nonnegative().nullable()}),cost:l({totalUsd:d().nonnegative().nullable()}),checkpoint:l({id:Ee,policyVersion:d().int().nonnegative(),sha256:vt.nullable(),sizeBytes:d().int().nonnegative().nullable()}).nullable(),movement:l({adapterDeltaNorm:d().nonnegative().nullable()}),evaluations:p(l({reference:l({id:Ee,contentHash:vt}).nullable().optional(),kind:v(["baseline","candidate"]),policyVersion:d().int().nonnegative(),taskCount:d().int().nonnegative().nullable().optional(),targetTaskCount:d().int().nonnegative().nullable().optional(),score:d().nullable(),threshold:d().nullable(),passed:I().nullable()})),canonicalPublication:l({state:Ee.nullable(),artifactId:Ee.nullable()}),syncedAt:jt}),KS=l({count:d().int().nonnegative(),scoredCount:d().int().nonnegative(),meanScore:d().min(0).max(1).nullable(),passedCount:d().int().nonnegative(),passRate:d().min(0).max(1).nullable()}),WS=l({status:v(["scored","unavailable"]),score:d().min(0).max(1).nullable(),passed:I(),rewardEligible:I(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:p(i().trim().min(1).max(2e4)).max(1e3),components:p(l({graderId:Ee,score:d().min(0).max(1).nullable(),passed:I(),feedback:i().trim().max(2e4).nullable()})).max(1e3)}),lK=l({taskId:Ee,input:te(i(),ie()),baseOutput:te(i(),ie()).nullable(),trainedOutput:te(i(),ie()).nullable(),baseGrade:WS.nullable(),trainedGrade:WS.nullable()}),cK=l({schemaVersion:b("openpond.trainingEvaluationSummary.v1"),jobId:Ee,tasksetId:Ee,base:KS,trained:KS,meanScoreDelta:d().min(-1).max(1).nullable(),examples:p(lK).max(1e6)});l({schemaVersion:b("openpond.trainingRunDetail.v1"),job:HR,events:p(iK),stepMetrics:p(oK),policyMetrics:p(rK).default([]),managedEvidence:sK.nullable().default(null),evaluation:cK.nullable(),generatedAt:jt});const dK=l({schemaVersion:b("openpond.trainingArtifact.v1"),id:Ee,jobId:Ee,kind:v(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:i().trim().min(1).max(4e3),sha256:vt,sizeBytes:d().int().nonnegative(),baseModelId:Ee.nullable(),baseModelRevision:i().trim().min(1).max(256).nullable(),tokenizerRevision:i().trim().min(1).max(256).nullable(),chatTemplateHash:vt.nullable(),nonProduction:I(),createdAt:jt,metadata:hd}),uK=l({schemaVersion:b("openpond.modelArtifactLineage.v1"),id:Ee,modelId:Ee,artifactId:Ee,jobId:Ee,tasksetId:Ee,tasksetHash:vt,graderHash:vt,planHash:vt,bundleHash:vt,recipeHash:vt,workerVersion:i().trim().min(1).max(256),trainerVersion:i().trim().min(1).max(256),importedAt:jt,frozenEvaluationArtifactId:Ee.nullable(),promotable:I(),pinned:I().default(!1),status:v(["imported","rejected"]).default("imported"),rejectedAt:jt.nullable().default(null),rejectionReason:i().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:TR.default(wV),managedServing:IV.nullable().default(null)}),mK=v(["chat_manual","agent","extension","authoring_optimizer"]),pK=l({schemaVersion:b("openpond.modelBinding.v1"),id:Ee,profileId:Ee,role:mK,roleTargetId:Ee,modelArtifactLineageId:Ee,tasksetId:Ee,evaluationArtifactId:Ee.nullable(),status:v(["active","rolled_back"]),priorBindingId:Ee.nullable(),rollbackTargetBindingId:Ee.nullable(),promotedBy:Ee,promotedAt:jt,rolledBackAt:jt.nullable(),metadata:hd});l({schemaVersion:b("openpond.trainingActivity.v1"),profileId:Ee,active:I(),activeCounts:l({jobs:d().int().nonnegative(),creations:d().int().nonnegative(),minerRuns:d().int().nonnegative(),datasetImports:d().int().nonnegative()}),revision:vt,generatedAt:jt});l({schemaVersion:b("openpond.tasksetOperationalState.v1"),tasksetId:Ee,attempts:p(e6),artifacts:p(t6),grades:p(a6),evaluationResults:p(bF).default([]),generatedAt:jt});const fK=l({schemaVersion:b("openpond.trainingState.v1"),profileId:Ee,sources:p(CC),creations:p(mR),tasksetDrafts:p(Fa).default([]),tasksets:p(Mc),benchmarkRuns:p(Ef()).default([]),benchmarkComparisons:p(Ef()).default([]),datasetImports:p(v6).default([]),datasetArtifacts:p(GF).default([]),graderAuditReports:p(i6),evaluationResults:p(Ef()).default([]),candidates:p(dR),minerConfig:np,minerRuns:p(U3).default([]),modelProjects:p(tK).default([]),modelVersions:p(Q6).default([]),modelRuns:p(uV).default([]),comparisonSeries:p(F6).default([]),comparisonSeriesEntries:p(Z6).default([]),modelCurrencySnapshots:p(hV).default([]),continualBenchIssueReviews:p(bV).default([]),continualLearningDailyBatches:p(vV).default([]),rewardModelVersions:p(X6).default([]),rewardModelRuns:p(tV).default([]),modelTasksets:p(Mc).default([]),plans:p(DR),bundles:p(Gb),jobs:p(HR),artifacts:p(dK),models:p(uK),rolloutReceipts:p(BV).default([]),modelBindings:p(pK).default([]),destinations:p(JV),baseModelCandidates:p(YV).default([]),activityRevision:vt.optional(),generatedAt:jt}),hK=v(["trajectory","reward","demonstration","preference","correction","critique","targeted_feedback","grader_evidence","infrastructure_failure"]),gK=l({datasetRelease:V,harnessRelease:V,evidenceSetRelease:V.nullable(),profileRelease:V.nullable(),model:l({source:i().trim().min(1).max(200),revision:i().trim().min(1).max(500),artifactHash:H.nullable()}).strict(),environmentHash:H,graderHash:H,toolContractHash:H,verificationReceiptHash:H.nullable()}).strict(),So=l({schemaVersion:b("openpond.learningSignal.v1"),id:T,taskId:T.nullable(),episodeId:T.nullable(),policyVersion:d().int().nonnegative().nullable(),lineage:gK,approved:I(),verifier:v(["deterministic","model_judge","human","none"]),createdAt:pe,contentHash:H,metadata:te(i(),ie()).default({})}).strict(),vK=So.extend({kind:b("trajectory"),payload:l({traceRef:i().trim().min(1).max(2e3),traceHash:H,terminal:I(),failureClass:v(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),optimizerSample:bC.nullable().optional()}).strict()}).strict(),bK=So.extend({kind:b("reward"),payload:l({reward:d().finite(),components:te(i(),d().finite()),eligible:I(),graderEvidenceRefs:p(T).max(1e3)}).strict()}).strict(),yK=So.extend({kind:b("demonstration"),payload:l({prompt:i().max(5e5),response:i().max(1e6)}).strict()}).strict(),SK=So.extend({kind:b("preference"),payload:l({prompt:i().max(5e5),chosen:i().max(1e6),rejected:i().max(1e6),rationale:i().max(5e5).nullable()}).strict()}).strict(),xK=So.extend({kind:b("correction"),payload:l({original:i().max(1e6),corrected:i().max(1e6),rationale:i().max(5e5).nullable()}).strict()}).strict(),kK=So.extend({kind:b("critique"),payload:l({response:i().max(1e6),critique:i().max(5e5),severity:v(["note","warning","error"])}).strict()}).strict(),wK=So.extend({kind:b("targeted_feedback"),payload:l({turnIndex:d().int().nonnegative(),target:v(["reasoning","tool","answer","policy"]),feedback:i().max(5e5)}).strict()}).strict(),IK=So.extend({kind:b("grader_evidence"),payload:l({graderId:T,score:d().finite().nullable(),passed:I(),privilegedArtifactRefs:p(i().trim().min(1).max(2e3))}).strict()}).strict(),_K=So.extend({kind:b("infrastructure_failure"),approved:b(!1),verifier:b("none"),payload:l({code:T,phase:T,retryable:I(),rewardEligible:b(!1)}).strict()}).strict(),LR=rt("kind",[vK,bK,yK,SK,xK,kK,wK,IK,_K]);l({schemaVersion:b("openpond.learningSignalBatch.v1"),manifestId:T,manifestHash:H,sequence:d().int().nonnegative(),signals:p(LR).min(1).max(1e5),contentHash:H}).strict();const CK=l({id:T,turn:d().int().nonnegative(),kind:v(["message","tool_call","terminal"]),name:T.nullable(),arguments:te(i(),ie()),content:i().max(1e6).nullable(),contentHash:H}).strict(),RK=l({actionId:T,turn:d().int().nonnegative(),terminal:I(),output:te(i(),ie()),artifactRefs:p(i().trim().min(1).max(2e3)),contentHash:H}).strict(),PK=l({sequence:d().int().nonnegative(),type:v(["created","reset","action","observation","terminal","graded","feedback","failure","collected","destroyed"]),timestamp:pe,payloadHash:H,metadata:te(i(),ie()).default({})}).strict(),GS=l({graderId:T,graderVersion:i().trim().min(1).max(200),score:d().finite().nullable(),passed:I(),rewardEligible:I(),failureClass:v(["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:H}).strict();l({schemaVersion:b("openpond.harnessRunTrace.v1"),manifest:V,taskId:T,seed:i().trim().min(1).max(500),events:p(PK).max(1e6),actions:p(CK).max(1e5),observations:p(RK).max(1e5),graderEvidence:p(GS).max(1e4),learningSignals:p(LR).max(1e5),terminal:I(),failureClass:GS.shape.failureClass,artifactHash:H,contentHash:H}).strict();const AK=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"),TK=v(["instruction","skill","skill_resource","agent","workflow","dependency_lock","program","asset"]),EK=l({id:T,kind:TK,path:AK,parentId:T.nullable(),mediaType:i().trim().min(1).max(200),visibility:v(["policy","verifier","host_private"]),portability:v(["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"]})});l({schemaVersion:b("openpond.harnessSourceManifest.v1"),name:i().trim().min(1).max(240),files:p(EK).min(2).max(1e5),toolDeclarations:p(Qc).max(200),capabilityRequirements:p(Dv).max(200),lifecycle:z1,graderInterface:B1,runtimeProtocol:i().trim().min(1).max(500),metadata:te(i(),ie()).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"]})});l({rootPath:i(),sourcePath:i(),binding:vH,currentRelease:Y0,releases:p(Y0),transitions:p(bH)}).strict();l({profile:K1,activate:I().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();l({release:V,reason:i().trim().min(1).max(1e4),actor:i().trim().min(1).max(240).default("local-user")}).strict();const jK=l({schemaVersion:b("openpond.trainingEngineCapabilities.v1"),adapterId:T,available:I(),methods:p(i().trim().min(1).max(100)),signalKinds:p(hK),modelFamilies:p(i().trim().min(1).max(200)),precisions:p(v(["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:H,checkedAt:pe,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),MK=l({schemaVersion:b("openpond.computeTargetCapabilities.v1"),adapterId:T,kind:v(["local","ssh","managed","custom"]),provider:T.nullable(),available:I(),devices:p(l({id:T,kind:v(["cpu","gpu","accelerator"]),vendor:i().trim().min(1).max(200),name:i().trim().min(1).max(500),memoryBytes:d().int().nonnegative().nullable(),runtime:i().trim().min(1).max(200)}).strict()),supportsWorkerImages:I(),supportsArtifactTransfer:I(),supportsCancellation:I(),capabilityReceipt:H,checkedAt:pe,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),OK=l({schemaVersion:b("openpond.harnessRuntimeCapabilities.v1"),adapterId:T,available:I(),placements:p(v(["local","remote","colocated","provider_native"])),lifecycle:p(v(["create","reset","step","grade","collect","destroy"])),deterministicReplay:I(),privilegedIsolation:I(),capabilityReceipt:H,checkedAt:pe,unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict();l({schemaVersion:b("openpond.resolvedTrainingPlan.v1"),manifest:V3,recipe:NR,runtime:Hb,compute:Lb,engine:qb,execution:l({trainingPlanId:T,approvalId:T}).strict().nullable(),maximumSpendUsd:d().nonnegative().nullable(),approvalHash:H,contentHash:H}).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"})});l({schemaVersion:b("openpond.adapterValidationReceipt.v1"),adapterId:T,valid:I(),issues:p(l({code:T,path:i().trim().max(2e3).nullable(),message:i().trim().min(1).max(5e3)}).strict()),capabilityReceipt:H,planHash:H,createdAt:pe,contentHash:H}).strict();l({runId:T,adapterId:T,protocolVersion:v(["openpond.training.v2","adapter.native.v1"]).default("adapter.native.v1"),routeFamily:v(["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:H.optional(),inputBundleHash:H.optional(),createdAt:pe}).strict();l({runId:T,state:v(["queued","preparing","running","cancelling","cancelled","succeeded","failed"]),phase:i().trim().min(1).max(200),progress:d().min(0).max(1).nullable(),rolloutProgress:l({groupsCompleted:d().int().nonnegative(),groupsTarget:d().int().nonnegative(),optimizerUpdatesApplied:d().int().nonnegative(),optimizerUpdatesSkipped:d().int().nonnegative()}).strict().optional(),updatedAt:pe,errorCode:T.nullable()}).strict();l({runId:T,manifestHash:H,artifacts:p(l({kind:v(["checkpoint","adapter","metrics","trace","evaluation","receipt"]),objectRef:i().trim().min(1).max(2e3),sha256:H,sizeBytes:d().int().nonnegative(),metadata:te(i(),ie()).optional()}).strict()),contentHash:H}).strict();const Pg=v(["ready","model_download_required","compute_setup_required","provider_managed","unsupported"]),$K=l({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:v(["local_worker","provider_native"]),approvalPolicy:l({providerId:$r,providerLabel:i().trim().min(1).max(200),settingsActionLabel:i().trim().min(1).max(500).nullable(),exportApprovalRequired:I(),exportDescription:i().trim().min(1).max(2e3).nullable(),preparationRequired:I(),minimumSpendUsd:d().nonnegative(),maximumSpendUsd:d().positive(),defaultMaximumSpendUsd:d().positive(),minimumRetentionDays:d().int().positive(),maximumRetentionDays:d().int().positive(),defaultRetentionDays:d().int().positive(),methodRequirement:i().trim().min(1).max(2e3).nullable()}).strict().nullable(),limits:l({maximumSequenceLength:d().int().positive(),maximumOutputTokens:d().int().positive(),maximumTrainingExamples:d().int().positive().nullable()}).strict(),defaults:l({loraRank:d().int().positive(),maxSteps:d().int().positive(),rolloutGroupSize:d().int().min(2).max(32),rolloutConcurrency:d().int().positive().max(32),rolloutOutputTokens:d().int().positive()}).strict(),available:I(),unavailableReason:i().trim().min(1).max(5e3).nullable()}).strict(),NK=l({selectionKey:T,label:i().trim().min(1).max(500),source:v(["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:H.nullable(),modelAssetId:T.nullable(),expectedBytes:d().int().nonnegative().nullable(),cached:I(),known:I(),searchResolved:I(),computeAdapterIds:p(T),engineAdapterIds:p(T),preparationState:Pg,reason:i().trim().min(1).max(5e3).nullable(),compatibilities:p(l({targetId:T,methods:p(i().trim().min(1).max(100)),state:Pg,reason:i().trim().min(1).max(5e3).nullable()}).strict())}).strict();l({schemaVersion:b("openpond.trainingCatalog.v1"),models:p(NK).max(1e5),engines:p(jK),compute:p(MK),runtimes:p(OK),targets:p($K),generatedAt:pe,contentHash:H}).strict();l({schemaVersion:b("openpond.trainingPreparationPlan.v1"),modelRunId:T,state:Pg,reason:i().trim().min(1).max(5e3).nullable(),runtime:Hb.nullable(),compute:Lb.nullable(),engine:qb.nullable(),downloads:p(l({kind:b("model"),label:i().trim().min(1).max(500),expectedBytes:d().int().nonnegative(),digest:i().trim().min(8).max(500),cached:I(),state:v(["ready","required","downloading","cancelled","failed"]),progress:d().min(0).max(1).nullable(),cancellable:I(),diskImpactBytes:d().int().nonnegative()}).strict()),dataMovement:p(l({direction:v(["upload","download","none"]),label:i().trim().min(1).max(500),bytes:d().int().nonnegative().nullable()}).strict()),quoteUsd:d().nonnegative().nullable(),maximumSpendUsd:d().nonnegative().nullable(),retentionDays:d().int().nonnegative().nullable(),sideEffectsStarted:b(!1),contentHash:H}).strict();const Jb=32e3,DK=v(["steer","message","followup","queued","result"]),HK=v(["pending","included","resolved","cancelled","rejected"]),qR=l({id:i().min(1),sequence:d().int().nonnegative(),sessionId:i().min(1),senderSessionId:i().min(1).nullable(),senderKind:v(["user","task","runtime"]),kind:DK,body:i().trim().min(1).max(Jb),payload:te(i(),ie()).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:HK,revision:d().int().positive(),createdAt:i(),updatedAt:i(),error:i().nullable()}).strict();l({expectedTurnId:i().trim().min(1),idempotencyKey:i().trim().min(1).max(200),prompt:i().trim().min(1).max(Jb)}).strict();rt("action",[l({action:b("resume"),expectedRevision:d().int().positive()}).strict(),l({action:b("cancel"),expectedRevision:d().int().positive()}).strict(),l({action:b("edit"),expectedRevision:d().int().positive(),body:i().trim().min(1).max(Jb)}).strict(),l({action:b("steer"),expectedRevision:d().int().positive(),expectedTurnId:i().trim().min(1)}).strict()]);const LK=l({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:d().int().nonnegative(),deadline:i(),state:v(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:i(),updatedAt:i()}).strict();l({sessionId:i(),activeTurnId:i().nullable(),acceptingInput:I(),paused:I(),inputs:p(qR),waits:p(LK)});var UR=i().regex(/^[a-f0-9]{64}$/),qK=l({request:hl,maximumCostUsd:d().finite().positive().max(1e4),graders:p(Ni).min(1).max(100),admissionRequestHash:UR.optional(),sourceExperimentId:i().trim().min(1).max(200).optional()}).strict(),UK=qK.extend({configurationHash:UR}).strict();tR.extend({configuration:UK}).strict();var die=l({teamId:i().trim().min(1).max(240),items:p(l({name:i().trim().min(1).max(500),source:sd,ready:I(),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 Bl=i().trim().min(1).max(500),zR=i().regex(/^[a-f0-9]{64}$/),zK=l({schemaVersion:b("openpond.experimentCaseInspection.v1"),teamId:Bl,executionId:Bl,manifestHash:zR,receiptId:Bl,taskId:Bl,seed:i().min(1),input:te(i(),ie()).nullable(),output:ie().nullable(),error:i().nullable(),events:p(te(i(),ie())).max(25),nextEventCursor:Bl.nullable(),eventCount:d().int().nonnegative()}).strict();zK.extend({contentHash:zR}).strict();function BK(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 FK(e){const t=new Map;for(const n of e){const a=BK(n),o=t.get(a);o?o.aliases.push(n):t.set(a,{key:a,grader:n,aliases:[n]})}return[...t.values()]}function uie(e){const t=FK(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 wr=i().trim().min(1).max(240),mie=l({profileRef:l({source:v(["local","github","openpond_git"]),repositoryId:wr,profileId:wr}).strict(),sourceRevision:i().min(1).max(500),harnessRelease:De,catalogHash:i().regex(/^[a-f0-9]{64}$/).nullable(),definitions:p(l_).max(1e3),suites:p(c_).max(100),runs:p(l({profileRef:l({source:v(["local","github","openpond_git"]),repositoryId:wr,profileId:wr}).strict(),manifest:Jm,metric:ib,gradeRefs:p(De),receiptRefs:p(De),passRate:d().min(0).max(1),passed:I(),completedAt:nn(),contentHash:i().regex(/^[a-f0-9]{64}$/)}).strict()).max(1e3),comparisons:p(TF).max(1e3),suiteRuns:p(NF).max(1e3),reports:p(OF).max(1e3)}).strict();l({teamId:wr,profileRepositoryId:wr,trainingProjectId:wr.optional()}).strict();var om=lt.shape.id,VK=l({schemaVersion:b("openpond.modelBatchReviewInspection.v1"),packageHash:i().regex(/^[a-f0-9]{64}$/),definition:ld,binding:Lm,evidence:p(zm).min(1).max(1e4),decisions:p(pb).min(1).max(1e4)}).strict(),pie=l({schemaVersion:b("openpond.modelBatchReviewRequest.v1"),operationId:om,modelId:om,expectedModelRevision:d().int().positive(),tasksetRef:lt,rewardBindingRef:lt.nullable(),definition:l({name:i().trim().min(1).max(500).optional(),instructions:i().trim().min(1).max(2e4).optional(),inputSchema:Nt.optional(),outputSchema:Nt.optional(),requiredOutputs:ld.shape.requiredOutputs}).strict(),examples:p(l({evidence:lt,input:Nt.optional(),expected:Nt.nullable().optional(),evaluatorContext:Nt.nullable().optional(),proposedTarget:Nt.nullable().optional()}).strict()).max(1e4)}).strict(),KK=l({schemaVersion:b("openpond.modelBatchReviewReceipt.v1"),operationId:om,modelId:om,source:Um,evidence:p(zm).min(1).max(1e4),proposals:p(S_).max(1e4)}).strict();p(l({asset:li,sourcePath:i().min(1)}).strict()).max(1e4);l({draft:Fa,filePaths:p(l({assetId:i().min(1),paths:p(cd).min(1).max(1e4)}).strict()).max(1e4)}).strict();const pn=i().trim().min(1).max(200),Xn=i().regex(/^[a-f0-9]{64}$/),BR=v(["queued","running","cancelling","completed","failed","cancelled","interrupted"]),FR=l({providerId:v(["openpond","custom-openai-compatible","claude-code"]),modelId:i().trim().min(1).max(500),configurationHash:Xn,maxOutputTokens:d().int().positive().max(262144),temperature:d().min(0).max(2).optional(),topP:d().positive().max(1).optional(),messages:p(l({role:v(["system","user","assistant"]),content:i().max(262144)}).strict()).max(200)}).strict();l({configuration:Db,package:Tr}).strict();l({configuration:Db,expectedPackageHash:Xn.optional()}).strict();l({schemaVersion:b("openpond.localExperimentDefinition.v1"),location:b("local"),id:pn,teamId:pn,ownerActorId:pn,revision:d().int().positive(),configuration:Db,model:FR,packageHash:Xn,graders:p(Ni).min(1).max(100),availableGraders:p(Ni).min(1).max(1e3),createdAt:nn(),updatedAt:nn(),contentHash:Xn}).strict();l({operationId:pn,definition:md}).strict();l({teamId:pn,id:pn}).strict();l({teamId:pn,projectId:pn.optional(),status:BR.optional(),datasetHash:Xn.optional(),search:i().max(100).optional(),afterId:pn.optional(),limit:d().int().min(1).max(100).default(30)}).strict();const Zb=l({schemaVersion:b("openpond.localExperimentExecution.v1"),location:b("local"),id:pn,teamId:pn,ownerActorId:pn,operationId:pn,definition:md,kind:v(["target","scoring"]),executionHash:Xn,sourceExecution:l({id:pn,executionHash:Xn}).strict().nullable(),packageHash:Xn,maximumCostUsd:d().finite().positive(),status:BR,createdAt:nn(),completedAt:nn().nullable(),counts:l({pending:d().int().nonnegative(),running:d().int().nonnegative(),completed:d().int().nonnegative(),failed:d().int().nonnegative(),cancelled:d().int().nonnegative(),unknown:d().int().nonnegative()}).strict(),usage:l({knownCostUsd:d().finite().nonnegative(),costUsd:d().finite().nonnegative().nullable(),heldUsd:d().finite().nonnegative(),uncertainRequests:d().int().nonnegative()}).strict(),cleanupComplete:I(),error:i().max(2e3).nullable()}).strict(),WK=Zb.omit({definition:!0});function Yb(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."})}Zb.superRefine(Yb);const vd=WK.superRefine(Yb);l({configuration:pd,package:Tr}).strict();const fie=l({configuration:pd,expectedPackageHash:i().regex(/^[a-f0-9]{64}$/).optional()}).strict(),JS=l({configuration:pd,model:FR,packageHash:i().regex(/^[a-f0-9]{64}$/),graders:p(Ni).min(1).max(100),availableGraders:p(Ni).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;ct(a)!==n&&t.addIssue({code:"custom",message:"Local configuration snapshot bytes changed."})}),{definition:hie,...GK}=Zb.shape,Qb=l({...GK,kind:b("target"),...JS.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};Yb(e,t),JS.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."})}),gie=l({items:p(Qb).max(100),nextCursor:i().nullable()}).strict();l({teamId:i().min(1).max(200),id:i().min(1).max(200),configurationHash:i().regex(/^[a-f0-9]{64}$/).optional()}).strict();const JK=l({operationId:pn,execution:l({id:pn,executionHash:Xn}).strict(),graderPackage:Tr,graders:p(Nb).min(1).max(100),maximumCostUsd:d().finite().positive().max(1e4)}).strict(),vie=JK.omit({graderPackage:!0}),ZK=ub,YK=l({sessionId:pn,turnId:pn,source:Zs,profileRef:qi,admissionHash:Xn,modelConfigurationHash:Xn,traceHash:Xn,runtimeEventRefs:p(pn).max(1e4),startedAt:nn(),completedAt:nn(),outputHash:Xn,partialOutputAvailable:I()}).strict(),VR=l({receiptId:pn,taskId:pn,seed:i(),status:v(["pending","running","completed","failed","cancelled","unknown"]),input:te(i(),ie()),policyVisibleContext:te(i(),ie()),output:i().nullable(),messages:p(ie()).max(4002),grade:ZC.nullable(),error:i().nullable(),native:ZK.optional(),profileNative:YK.optional(),externalProcess:o3.optional()}).strict(),bie=l({execution:gt([Qb,vd]),cases:p(VR).max(1e4),contentHash:Xn}).strict(),QK=l({items:p(l({sequence:d().int().positive(),type:i().min(1),payload:ie()}).strict()).max(500),nextCursor:d().int().positive().nullable()}).strict(),yie=l({location:b("local"),execution:gt([Qb,vd]),case:VR,trace:QK}).strict(),Sie=l({items:p(vd).max(100),nextCursor:pn.nullable()}).strict(),xie=l({execution:vd,graders:p(Ni).min(1).max(100),graderPackageHash:Xn}).strict(),ZS=l({execution:vd,manifest:so,result:lo}).strict().superRefine((e,t)=>{try{if(Rr(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."})}}),kie=l({location:b("local"),baseline:ZS,candidate:ZS}).strict(),hs=i().trim().min(1).max(240),bh=i().regex(/^[a-f0-9]{64}$/),wie=l({location:b("local"),harnesses:p(l({id:hs,name:i().max(500),source:sd}).strict()).max(100),profiles:p(l({id:hs,name:i().max(500),profileRef:qi,sourceRevision:i().min(1).max(500),harnessRelease:l({id:hs,contentHash:bh}).strict(),definitionId:hs,definitionHash:bh,taskset:l({id:hs,revision:d().int().positive(),contentHash:bh}).strict(),taskCount:d().int().nonnegative(),taskIds:p(hs).max(1e4),seeds:p(i()).max(1e4)}).strict()).max(100)}).strict(),XK=l({id:wm(),action:v(["advanced-refiner-start","experiment-evaluation-schedule"]),intentHash:i().regex(/^[a-f0-9]{64}$/),createdAt:nn(),reviewedIntent:ie().nullable(),command:ie().nullable(),phase:v(["reviewed","dispatching"]).nullable(),recoveryReady:I()}).strict().superRefine((e,t)=>{e.recoveryReady!==(e.reviewedIntent!==null&&e.command!==null&&e.phase!==null)&&t.addIssue({code:"custom",message:"Only the actual retained intent and command admit automatic recovery."})}),Iie=l({items:p(XK).max(100),nextCursor:wm().nullable()}).strict();function e9(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 t9(e){return Math.min(500*2**Math.max(0,e),1e4)}async function n9(e,t,n,a){KR(e);const o=e.body.getReader(),r=new TextDecoder;let s="";for(;!a?.aborted;){const{done:c,value:m}=await o.read();if(c){s+=r.decode();break}s+=r.decode(m,{stream:!0});let u=s.indexOf(`
|
|
186
|
+
|
|
187
|
+
`);for(;u>=0;){const f=s.slice(0,u);s=s.slice(u+2),QS(f,t,n),u=s.indexOf(`
|
|
188
|
+
|
|
189
|
+
`)}}!a?.aborted&&s.trim()&&QS(s,t,n)}function KR(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 a9(e,t,n,a,o={}){const r=new AbortController,s=o.fetchImpl??fetch,c=o.reconnectDelayMs??t9;let m=YS(o.afterSequence),u=!1;return(async()=>{let f=0;for(;!r.signal.aborted;)try{const g=e9(e,r.signal,m),S=await s(g.url,g.init);if(KR(S),u=!0,f=0,await n9(S,k=>{const C=YS(k.sequence);C>0&&C<=m||(C>0&&(m=C),t(k))},a,r.signal),u=!1,r.signal.aborted)break;throw new Error("event stream ended")}catch(g){if(u=!1,r.signal.aborted)break;n(g),await i9(c(f),r.signal),f+=1}})().catch(()=>{}),{close(){r.abort()},isOpen(){return u}}}function YS(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function QS(e,t,n){let a="message";const o=[];for(const r of e.split(`
|
|
190
|
+
`))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(`
|
|
191
|
+
`)))}catch{}}async function i9(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 o9 extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function XS(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 ex=new WeakMap,tx=new WeakMap,iu=new WeakMap;let r9=0;async function z(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const o=(iu.get(e)??Promise.resolve()).catch(()=>{}).then(()=>nx(e,t,n));iu.set(e,o);try{return await o}finally{iu.get(e)===o&&iu.delete(e)}}return nx(e,t,n)}async function nx(e,t,n){const a=++r9;if(t==="/v1/preferences"&&typeof n?.body=="string"){const m=ex.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(()=>({})),u=m&&typeof m=="object"&&"error"in m?String(m.error):r.statusText;throw new o9(u,r.status)}if(r.status===204)return;const s=await r.json(),c=s?.configuration?.rawRevision??(t==="/v1/preferences"?s?.rawRevision:void 0);return typeof c=="string"&&a>=(tx.get(e)??0)&&(ex.set(e,c),tx.set(e,a)),s}function _ie(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function Cie(e){return["openpond-terminal",`openpond-token.${l9(e.token)}`]}function s9(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 l9(e){return s9(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function c9(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 d9={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"})},u9={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?${m9(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 m9(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 p9={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?"":c9(r.file.contentsBase64)}}},f9={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)})},h9={connectedAppStatus:(e,t={})=>{const n=XS(t);return n.set("status",t.status??"all"),z(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=XS(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})})},g9={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)})},v9={sandbox:(e,t)=>z(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},b9={...h9,...g9,...v9,...f9,...p9},y9={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`)},Xb="openpond-app-server-url",Nc="openpond-app-token",S9=750;function WR(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function Ag(e){const t=e.getItem(Xb)?.trim(),n=e.getItem(Nc)?.trim();return t&&n?{serverUrl:t,token:n}:null}function rm(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function gs(e,t){e.setItem(Xb,t.serverUrl),e.setItem(Nc,t.token)}function ax(e,t){const n=Ag(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(Xb),e.removeItem(Nc))}function x9(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function k9(){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()||WR();return!a||!n?null:{serverUrl:a,token:n}}function w9(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function ou(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function I9(){const e=[],t=rm(window.sessionStorage),n=rm(window.localStorage),a=WR(),o=t?.getItem(Nc)??n?.getItem(Nc);return ou(e,null),ou(e,a&&o?{serverUrl:a,token:o.trim()}:null),ou(e,t?Ag(t):null),ou(e,n?Ag(n):null),e}async function yh(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),S9);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 _9(){if(window.openpond)return window.openpond.getConnection();const e=rm(window.sessionStorage),t=rm(window.localStorage),n=k9();if(n&&await yh(n.serverUrl))return t&&gs(t,n),e&&gs(e,n),w9(),{...n,platform:navigator.platform};const a=x9();if(a&&await yh(a.serverUrl))return t&&gs(t,a),e&&gs(e,a),{...a,platform:navigator.platform};const o=I9();for(const r of o){if(await yh(r.serverUrl))return t&&gs(t,r),e&&gs(e,r),{...r,platform:navigator.platform};e&&ax(e,r),t&&ax(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Q={...y9,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=ix(t),a=n.size?`?${n.toString()}`:"";return z(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=ix(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"),profileEvaluationDiscovery:(e,t,n)=>z(e,"/v1/profile/evaluations/discover",{method:"POST",body:JSON.stringify({profileRef:t}),signal:n}),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`),...d9,...b9,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({})}),...u9,resolveApproval:(e,t,n)=>z(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function ix(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 C9=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),R9=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),ox=e=>{const t=R9(e);return t.charAt(0).toUpperCase()+t.slice(1)},GR=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),P9=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var A9={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 T9=y.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:o="",children:r,iconNode:s,...c},m)=>y.createElement("svg",{ref:m,...A9,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:GR("lucide",o),...!r&&!P9(c)&&{"aria-hidden":"true"},...c},[...s.map(([u,f])=>y.createElement(u,f)),...Array.isArray(r)?r:[r]]));const dt=(e,t)=>{const n=y.forwardRef(({className:a,...o},r)=>y.createElement(T9,{ref:r,iconNode:t,className:GR(`lucide-${C9(ox(e))}`,`lucide-${e}`,a),...o}));return n.displayName=ox(e),n};const E9=[["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"}]],j9=dt("activity",E9);const M9=[["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"}]],O9=dt("archive-restore",M9);const $9=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],N9=dt("arrow-left",$9);const D9=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],JR=dt("bookmark",D9);const H9=[["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"}]],ZR=dt("bookmark-x",H9);const L9=[["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"}]],rx=dt("book-open-text",L9);const q9=[["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"}]],ru=dt("boxes",q9);const U9=[["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"}]],z9=dt("calendar-clock",U9);const B9=[["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"}]],YR=dt("chart-column-stacked",B9);const F9=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ci=dt("check",F9);const V9=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Pu=dt("circle-check",V9);const K9=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],yo=dt("chevron-down",K9);const W9=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Mr=dt("chevron-right",W9);const G9=[["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"}]],sm=dt("circle-alert",G9);const J9=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],op=dt("cloud",J9);const Z9=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],Y9=dt("credit-card",Z9);const Q9=[["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"}]],X9=dt("download",Q9);const eW=[["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"}]],Sh=dt("external-link",eW);const tW=[["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"}]],nW=dt("file-output",tW);const aW=[["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"}]],ey=dt("file-text",aW);const iW=[["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"}]],QR=dt("folder",iW);const oW=[["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"}]],XR=dt("folder-git-2",oW);const rW=[["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"}]],sW=dt("git-branch",rW);const lW=[["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"}]],cW=dt("github",lW);const dW=[["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"}]],eP=dt("earth",dW);const uW=[["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"}]],mW=dt("circle-question-mark",uW);const pW=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],fW=dt("list-filter",pW);const hW=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ty=dt("loader-circle",hW);const gW=[["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"}]],vW=dt("maximize-2",gW);const bW=[["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"}]],rp=dt("message-square",bW);const yW=[["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"}]],bd=dt("ellipsis",yW);const SW=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],tP=dt("panel-left",SW);const xW=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Tg=dt("panel-right",xW);const kW=[["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"}]],ny=dt("pin",kW);const wW=[["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"}]],ay=dt("pin-off",wW);const IW=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],_W=dt("plus",IW);const CW=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],RW=dt("power",CW);const PW=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],AW=dt("refresh-cw",PW);const TW=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],EW=dt("search",TW);const jW=[["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"}]],nP=dt("settings",jW);const MW=[["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"}]],aP=dt("shapes",MW);const OW=[["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"}]],sx=dt("shield",OW);const $W=[["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"}]],sp=dt("square-pen",$W);const NW=[["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"}]],iP=dt("square-terminal",NW);const DW=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],lx=dt("user-round",DW);const HW=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],yd=dt("x",HW);function LW({platform:e}){return!lp()||iy(e)?null:x.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[x.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{xh("minimize")},children:x.jsx(yo,{size:14})}),x.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{xh("toggleMaximize")},children:x.jsx(vW,{size:12})}),x.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{xh("close")},children:x.jsx(yd,{size:13})})]})}function iy(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function lp(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function xh(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.")}}const qW=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],UW=dt("house",qW);const zW=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],oP=dt("inbox",zW);function BW({value:e,options:t,disabled:n,compact:a,className:o,icon:r,placement:s="bottom",label:c,tooltip:m,searchable:u=!1,floating:f=!1,onChange:g}){const[S,k]=y.useState(!1),[C,P]=y.useState(""),j=y.useRef(null),[R,$]=y.useState();y.useLayoutEffect(()=>{if(!S||!f)return;function A(){const E=j.current?.getBoundingClientRect();if(!E)return;const D=window.innerHeight-E.bottom-12,U=E.top-12,L=D<180&&U>D;$({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:L?"auto":E.bottom+5,bottom:L?window.innerHeight-E.top+5:"auto",maxHeight:Math.max(80,Math.min(320,L?U-5:D-5)),overflowY:"auto",zIndex:1e3})}return A(),window.addEventListener("resize",A),window.addEventListener("scroll",A,!0),()=>{window.removeEventListener("resize",A),window.removeEventListener("scroll",A,!0)}},[S,f]);const O=t.find(A=>A.value===e)??t[0],M=C.trim().toLowerCase(),w=M?t.filter(A=>[A.label,A.shortLabel,A.description].some(E=>E?.toLowerCase().includes(M))):t;return y.useEffect(()=>{if(!S){P("");return}function A(D){j.current?.contains(D.target)||k(!1)}function E(D){D.key==="Escape"&&k(!1)}return document.addEventListener("pointerdown",A),document.addEventListener("keydown",E),()=>{document.removeEventListener("pointerdown",A),document.removeEventListener("keydown",E)}},[S]),x.jsxs("div",{className:`dropdown-select ${o??""} ${a?"compact":""} ${s==="top"?"open-up":""}`,"data-tooltip":m,ref:j,children:[x.jsxs("button",{type:"button",className:`dropdown-trigger ${S?"active":""}`,disabled:n,"aria-label":c,"aria-haspopup":"menu","aria-expanded":S,onClick:()=>k(A=>!A),children:[r,x.jsx("span",{children:O?.shortLabel??O?.label??e}),x.jsx(yo,{size:14})]}),S&&x.jsxs("div",{className:"dropdown-menu",role:"menu",style:f?R:void 0,children:[u?x.jsxs("label",{className:"dropdown-search",onClick:A=>A.stopPropagation(),children:[x.jsxs("span",{className:"sr-only",children:["Search ",c]}),x.jsx("input",{autoFocus:!0,placeholder:`Search ${c.toLowerCase()}`,value:C,onChange:A=>P(A.target.value)})]}):null,w.map(A=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":A.value===e,disabled:A.disabled,className:[A.value===e?"selected":"",A.separatorBefore?"separator-before":"",A.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{A.disabled||(g(A.value),P(""),k(!1))},children:[x.jsxs("span",{children:[A.icon==="plus"?x.jsx(_W,{size:13}):null,x.jsx("span",{children:A.label})]}),A.description&&x.jsx("small",{children:A.description})]},A.value)),w.length?null:x.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const FW=[{destination:"walkthroughs",icon:rx,label:"Walkthroughs"},{destination:"external",icon:rx,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:ey,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:Y9,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:eP,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:cW,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:rp,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function VW({onOpenWalkthroughs:e,walkthroughsActive:t}){const[n,a]=y.useState(!1),o=y.useRef(null);return y.useEffect(()=>{if(!n)return;function r(c){o.current?.contains(c.target)||a(!1)}function s(c){c.key==="Escape"&&a(!1)}return document.addEventListener("pointerdown",r),document.addEventListener("keydown",s),()=>{document.removeEventListener("pointerdown",r),document.removeEventListener("keydown",s)}},[n]),x.jsxs("div",{className:"sidebar-help-menu",ref:o,children:[x.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:x.jsx(mW,{size:17})}),n?x.jsx("div",{className:"sidebar-help-popover",role:"menu","aria-label":"Help",children:FW.map(r=>{const s=r.icon,c=x.jsxs(x.Fragment,{children:[x.jsx(s,{size:15}),x.jsx("span",{children:r.label})]});return r.destination==="walkthroughs"?x.jsx("button",{"aria-current":t?"page":void 0,className:"sidebar-help-item",onClick:()=>{a(!1),e()},role:"menuitem",type:"button",children:c},r.label):x.jsx("a",{className:"sidebar-help-item",href:r.url,onClick:m=>{m.preventDefault(),a(!1),KW(r.url)},rel:"noreferrer",role:"menuitem",target:"_blank",children:c},r.label)})}):null]})}async function KW(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const Rie=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}],kh=[{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 rP(e){return e==="chat"?"New chat":"New task"}const Eg=["get-started","home","inbox","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],WW={"get-started":"Get started",home:"Home",inbox:"Inbox",models:"Models",datasets:"Datasets",graders:"Graders",experiments:"Experiments",tasks:"Tasks",tasksets:"Tasksets",labeling:"Labeling",rewards:"Rewards",evaluations:"Runs",runs:"Runs",versions:"Versions",serving:"Serving"},GW={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},JW={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 ma(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?ma("labeling",t,{...n,collection:"default"}):{page:e,modelId:["get-started","home","inbox","datasets","graders","experiments"].includes(e)?null:t,collection:e==="evaluations"?"results":"default",resourceId:null,detailTab:null,query:"",after:null,...n}}function Dc(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(X=>!X.trim()||X.length>2e3||X.includes("\0")))return null;const a=n[0]&&!Eg.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(!Eg.includes(r)||o==="models"||a&&r==="get-started")return null;let s=r==="evaluations"?"results":"default";if(GW[r]?.includes(n[0]))s=n.shift();else if(r==="evaluations"&&n.length)return null;if(r==="experiments"&&n[0]==="history")return null;const c=n.shift()??null,m=n.shift()??null;if(n.length||m&&!c||(r==="models"||r==="get-started"||r==="home")&&c)return null;if(s==="drafts"||s==="new"){if(!c||m)return null}else if(s!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(s)){if(m)return null}else if(m&&!JW[r]?.includes(m))return null}if(r==="serving"&&m)return null;const u=new URLSearchParams(e.search??"");if([...u.keys()].some(X=>!["model","q","after","source","project","pass","dataset","revision","hash","sort","location","kind","review_source","review_snapshot","review_boundary","review_revision"].includes(X))||[...u.keys()].some(X=>u.getAll(X).length!==1))return null;const f=["review_source","review_snapshot","review_boundary","review_revision"],g=f.some(X=>u.has(X));if(g&&(r!=="datasets"||c||u.get("location")==="local"||f.some(X=>!u.get(X))||[u.get("review_source"),u.get("review_boundary")].some(X=>!X.trim()||X.length>500||X.includes("\0"))||[u.get("review_snapshot"),u.get("review_revision")].some(X=>!/^[a-f0-9]{64}$/.test(X))))return null;const S=g?{id:u.get("review_source"),snapshotHash:u.get("review_snapshot"),boundaryId:u.get("review_boundary"),boundaryRevisionHash:u.get("review_revision")}:void 0,k=u.get("sort");if(k!==null&&(r!=="datasets"||!["id","name","updated"].includes(k)))return null;const C=u.has("revision")?Number(u.get("revision")):void 0,P=u.get("hash")??void 0,j=["datasets","graders"].includes(r);if((C!==void 0||P!==void 0)&&(!c||!j||!Number.isSafeInteger(C)||C<=0||!/^[a-f0-9]{64}$/.test(P??"")))return null;const R=u.get("source");if(R!==null&&(r!=="labeling"&&(r!=="evaluations"||s!=="review")||!R.trim()||R.length>500)||u.has("dataset")&&(r!=="datasets"||!c||u.get("dataset")!=="release"))return null;const $=["home","inbox","datasets","graders","experiments"].includes(r),O=r==="runs"&&!!(c?.startsWith("hosted-run:")||c?.startsWith("hosted-policy:")),M=u.get("location");if(M!==null&&(!$||!["local","hosted"].includes(M)))return null;const w=u.get("kind");if(w!==null&&(r!=="experiments"||!c||M==="local"||w!=="recorded_evidence")||t[0]==="console"&&!$)return null;const A=u.get("project")==="all"?null:u.get("project"),E=u.get("pass");if([A,E].some(X=>X!==null&&(!X.trim()||X.length>240))||!$&&!O&&(A||E)||r!=="experiments"&&E||($||O)&&a||E&&!c)return null;const D=u.get("model");if($&&D!==null||a&&D&&a!==D)return null;const U=a??D;if(r==="get-started"&&u.size!==0)return null;const L=u.get("q")??"",J=u.get("after");return U!==null&&(!U.trim()||U.length>500)||L.length>1e3||J!==null&&(!J.trim()||J.length>2e3)?null:ma(r,U,{...S?{reviewSource:S}:{},collection:s,resourceId:c,detailTab:m,query:L,after:J,...w?{executionKind:"recorded_evidence"}:{},...M?{executionLocation:M}:{},...k?{sort:k}:{},...C!==void 0?{revision:C,contentHash:P}:{},...u.get("dataset")==="release"?{datasetKind:"release"}:{},...t[0]==="console"?{area:"console"}:{},...$||O?{...u.has("project")?{projectId:A}:{},...u.has("pass")?{passId:E}:{}}:{},...R!==null?{sourceId:R}:{}})}function cp(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return cp(ma("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.page==="datasets"&&!e.resourceId&&e.reviewSource&&(n.set("review_source",e.reviewSource.id),n.set("review_snapshot",e.reviewSource.snapshotHash),n.set("review_boundary",e.reviewSource.boundaryId),n.set("review_revision",e.reviewSource.boundaryRevisionHash)),e.executionLocation&&n.set("location",e.executionLocation),e.projectId?n.set("project",e.projectId):e.projectId===null&&["home","inbox","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.page==="experiments"&&e.resourceId&&e.executionKind&&n.set("kind",e.executionKind),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 ZW(e,t){return ma(e.page,t,{...e.area?{area:e.area}:{},...["home","inbox","datasets","graders","experiments"].includes(e.page)&&e.projectId!==void 0?{projectId:e.projectId}:{},collection:e.collection==="new"||e.collection==="drafts"?"default":e.collection})}function Pie(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const lm=new Set,jg=new Set,YW=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"]),Mg={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started"};let Og=!1,$g="",Au=null,sP=null,Hc="",ii=0,Fl=null,pc=!1,wh=null,Tu=!1;function oy(e){const t=Dc(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&&YW.has(n[1])){const o=ry(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(Mg).find(o=>Mg[o]===e.pathname);return a?{kind:"view",view:a}:null}function lP(e){if(e.kind==="models")return cp(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=ry(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":Mg[e.view]}function QW(e){const t=e?.kind==="settings"?ry(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=Dc(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function ry(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=Dc(t);return n?cp(n):null}function Sd(){return`${window.location.pathname}${window.location.search}`}function sy(){if(typeof window>"u")return;const e=Og?Hc:Sd();e!==$g&&($g=e,Au=oy(new URL(e,window.location.origin)),sP=Au?.kind==="models"?Au.route:null)}function cP(){$g="",sy();for(const e of jg)e()}async function ly(e){if(Tu)return!1;Tu=!0;try{for(const t of[...lm].reverse())if(!await t(e))return!1;return!0}finally{Tu=!1}}function cy(e){return{...window.history.state,openpondNavigationIndex:e}}async function XW(){const e=Sd(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:ii-1;if(Fl&&t===ii){const a=Fl;Fl=null,a();return}if(wh===t||lm.size===0){wh=null,Hc=e,ii=t,window.history.replaceState(cy(ii),"",e),cP();return}if(t===ii)return;if(pc||Tu){Fl??=()=>{},window.history.go(ii-t);return}pc=!0;const n=t-ii;try{await new Promise(a=>{Fl=a,window.history.go(-n)}),await ly(e)&&(wh=t,window.history.go(n))}finally{pc=!1}}function dy(){if(Og||typeof window>"u")return;const e=oy(window.location);Hc=e?lP(e):Sd(),ii=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(cy(ii),"",Hc),window.addEventListener("popstate",XW),Og=!0}function dP(e){return jg.add(e),dy(),()=>{jg.delete(e)}}function Aie(e){return lm.add(e),dy(),()=>{lm.delete(e)}}async function Tie(e){!pc&&await ly(Sd())&&e()}function e8(){return y.useSyncExternalStore(dP,()=>(sy(),sP),()=>null)}function t8(){return y.useSyncExternalStore(dP,()=>(sy(),Au),()=>null)}async function ln(e,t="push"){if(typeof window>"u"||(dy(),pc))return!1;if(e.kind==="settings"&&!e.returnTo){const a=oy(window.location),o=a?.kind==="models"?cp(a.route):a?.kind==="settings"?a.returnTo:void 0;o&&(e={...e,returnTo:o})}const n=lP(e);return Sd()===n?!0:await ly(n)?(t==="push"&&ii++,window.history[t==="replace"?"replaceState":"pushState"](cy(ii),"",n),Hc=n,cP(),!0):!1}function fo(e,t="push"){return ln({kind:"models",route:e},t)}function n8({experience:e="work",beginNewChat:t}){return x.jsx("div",{className:"sidebar-new-task",children:x.jsxs("button",{className:"nav-command nav-command-new-task",type:"button",onClick:()=>{ln({kind:"chat",sessionId:null}),t(null)},children:[x.jsx(sp,{size:18}),x.jsx("span",{children:rP(e)})]})})}function a8({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:o,setView:r,view:s,modelProjects:c=[],modelTrainingActivityByProjectId:m={}}){const u=e8(),f=u?.modelId??null,g=u?.page??"models";function S(){n(null),a(null),o(null),t(null)}async function k(R){await fo(ma(R,["home","inbox","datasets","graders","experiments"].includes(R)?null:f,{...e==="console"?{area:"console"}:{},...u?.projectId!==void 0?{projectId:u.projectId}:{}}))&&(S(),r("labs"))}async function C(R){await fo(ZW(u??ma(),R||null))&&(S(),r("labs"))}async function P(R){await ln({kind:"view",view:R})&&(S(),r(R))}const j=f?m[f]??null:null;return x.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e!=="chat"?x.jsxs(x.Fragment,{children:[["home","inbox","datasets","graders","experiments"].includes(g)?null:x.jsxs("div",{className:"sidebar-model-project-picker",children:[x.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),x.jsx(BW,{label:"Model",searchable:c.length>8,value:f??"",options:[{value:"",label:"All models"},...f&&!c.some(R=>R.id===f)?[{value:f,label:"Unavailable model",disabled:!0}]:[],...c.map(R=>({value:R.id,label:R.name}))],onChange:R=>{C(R)}})]}),Eg.filter(R=>e==="console"?["home","inbox","datasets","graders","experiments"].includes(R):R!=="home"&&R!=="tasksets"&&R!=="evaluations").map(R=>{const $={"get-started":ru,home:UW,inbox:oP,models:j9,datasets:ru,graders:sx,experiments:Pu,tasks:ru,tasksets:ru,labeling:Pu,rewards:sx,evaluations:Pu,runs:YR,versions:sW,serving:op}[R];return x.jsxs("button",{className:`nav-command ${s==="labs"&&(g===R||R==="runs"&&g==="evaluations")?"active":""}`,"aria-current":s==="labs"&&(g===R||R==="runs"&&g==="evaluations")?"page":void 0,type:"button",onClick:()=>{k(R)},children:[x.jsx($,{size:16}),x.jsx("span",{children:WW[R]}),R==="runs"&&j?x.jsx("span",{className:"sidebar-running-dot","aria-label":j.label}):null]},R)})]}):null,e==="chat"?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{P("scheduled")},children:[x.jsx(z9,{size:18}),x.jsx("span",{children:"Workflows"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{P("outputs")},children:[x.jsx(nW,{size:18}),x.jsx("span",{children:"Outputs"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{P("apps")},children:[x.jsx(aP,{size:18}),x.jsx("span",{children:"Apps"})]}),x.jsxs("button",{className:`nav-command nav-command-prominent ${s==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{P("projects")},children:[x.jsx(XR,{size:18}),x.jsx("span",{children:"Projects"})]})]}):null]})}function i8({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"),ln({kind:"view",view:"get-started"})}return x.jsx("nav",{className:"sidebar-utility-nav","aria-label":"Resources",children:x.jsx(VW,{onOpenWalkthroughs:s,walkthroughsActive:r==="get-started"})})}const uP=Tf({chatMode:v(["chat","work"]).optional(),notificationMode:v(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:I().optional(),sidebarVisibility:Tf({showCodexChats:I(),onlyRunningTasks:I()}).optional(),scheduledWorkView:v(["calendar","list"]).optional(),editorControlsVisible:I().optional(),voiceNoticeAcknowledged:I().optional(),lessonProgress:te(i().min(1).max(200),Tf({completed:I(),currentTime:d().finite().nonnegative(),duration:d().finite().positive(),updatedAt:d().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),Ng={"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"},Dg=new Set;let fc=null,ho=null,ri={},Lc={},Ih=!1,Eu=0,Us=null,cx=0;const o8="openpond-client-choices-changed";function uy(){Dg.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(o8))}function r8(){return Us}function s8(e){return Dg.add(e),()=>{Dg.delete(e)}}function xd(e){const t=y.useRef(e);t.current=e,y.useEffect(()=>s8(()=>t.current()),[])}async function dx(e){const t=++cx,n=await z(e,"/v1/configuration");if(n.clientState?.revision===null){const o=l8();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!==cx)return;const a=fc?.serverUrl!==e.serverUrl||fc?.token!==e.token||ho?.owner!==n.clientState?.owner;a&&(Eu++,ri={},Lc={},Us=null),fc=e,(a||(n.clientState?.revision??0)>=(ho?.revision??0))&&(ho=n.clientState),uy()}async function my(){if(Ih||!fc||!ho||!Object.keys(ri).length)return;Ih=!0;const e=ri,t=fc,n=ho.owner,a=Eu;ri={},Lc=e;try{const o=await z(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===Eu&&(ho=o,Us=null)}catch(o){a===Eu&&(ri={...e,...ri},Us=`Preference changes have not been saved. ${o instanceof Error?o.message:String(o)}`)}finally{Lc={},Ih=!1,uy(),!Us&&Object.keys(ri).length&&my()}}function Eie(){Us=null,my()}const kd={getItem(e){const t=Ng[e];if(!t)return null;const n={...ho?.value,...Lc,...ri}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!ho)return;const n=Ng[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const o=uP.parse({[n]:a});JSON.stringify({...ho.value,...Lc,...ri}[n])!==JSON.stringify(o[n])&&(ri={...ri,...o},uy(),my())}};function l8(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(Ng))try{const o=window.localStorage.getItem(n);if(o===null)continue;let r;try{r=JSON.parse(o)}catch{r=o}const s=uP.safeParse({[a]:r});s.success&&(Object.assign(e,s.data),t.push(n))}catch{}return{patch:e,keys:t}}const ju=5,Hn=15,Hg=10,Ot={defaultChatProvider:Pr,subagents:S$(),codexPermissionMode:Tv,codexReasoningEffort:Ev,openPondCommandAccessMode:Am,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:""}}}},jie={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},mP=[{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"}],_h=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],c8=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],d8=["openpond","codex","claude-code","grok-build","opencode",...c8],pP=new Set(d8),fP=[{value:Av,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"}],Mie=[{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."}],Lg=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],u8=[{value:"off",label:"Off"},...Lg,{value:"max",label:"Max"}],Oie=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],$ie=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],Nie=[{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 py(e){return e.kind==="local"}function m8(e){return e.kind==="cloud"}function It(e,t){return`${e}:${t}`}function hP(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 Ir(e){return`${e.type}:${e.id}`}function cm(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function dm(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 ux(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function p8(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 fy(e,t){return e?.statuses?.[t]??null}function gP(e,t){return e?.providers?.[t]??null}function hy(e,t){return e?.modelCaches?.[t]??null}function f8(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 h8(e){return e==="openpond"?mP:e==="codex"||e==="openai"?fP:[]}function g8(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 Die(e){return pP.has(e)}function qg(e,t={}){if(!e)return t.localOnly,_h;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,o=[];for(const r of bv){if(!["openpond","codex","openai","claude-code","grok-build","opencode"].includes(r)||!pP.has(r)||t.localOnly&&r==="openpond")continue;const s=fy(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:_h}function qc(e,t){const a=(hy(t,e)?.models??[]).filter(c=>e!=="openpond"||c.id!==Ks).map(f8),o=gP(t,e),r=[...o?.modelOverrides??[],o?.defaultModel].filter(c=>!!c?.trim()&&(e!=="openpond"||c!==Ks)).map(c=>({value:c,label:c})),s=e==="openpond"&&a.length>0?[]:h8(e);return g8([...a,...r,...s])}function vP(e,t,n){if(e!=="openpond")return Lg;const a=hy(n,e)?.models.find(r=>r.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return Lg;const o=new Set(a.reasoningEfforts);return u8.filter(r=>o.has(r.value))}function v8(e,t,n){const a=vP(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 b8(e,t,n,a){return vP(e,t,a).some(o=>o.value===n)?n:v8(e,t,a)}function y8(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const o=hy(n,e)?.models.find(r=>r.id===a);return o?!!o.capabilities.reasoning:qc(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function um(e,t){const n=gP(t,e)?.defaultModel?.trim();if(n)return n;const a=fy(t,e)?.defaultModel?.trim();if(a)return a;const o=qc(e,t)[0]?.value?.trim();return o||(e==="codex"?Av:e==="openpond"?Ks:"")}function er(e,t,n){const a=t?.trim();if(a&&["opencode","grok-build","claude-code"].includes(e))return a;if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return Av;const o=qc(e,n);return a&&o.some(r=>r.value===a)||a&&e!=="codex"&&o.length===0&&!n?a:um(e,n)}function bP(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:er(n,e.modelRef?.modelId,t)}}function gy(e,t,n){return er(e,t,n)||void 0}function ni(e,t,n){const a=gy(e,t,n);return a?{providerId:e,modelId:a}:void 0}function mx(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function $a(e){const t=e?.defaultChatProvider??Ot.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:er(t,e?.defaultChatModel),subagents:yc.parse(e?.subagents??Ot.subagents),codexPermissionMode:e?.codexPermissionMode??Ot.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Ot.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Ot.openPondCommandAccessMode,defaultBranchPrefix:yP(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Ot.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Ot.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Ot.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Ot.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Ot.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Ot.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Ot.training.defaultModelRef,creationMode:e?.training?.creationMode??Ot.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Ot.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Ot.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Ot.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Ot.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Ot.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Ot.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Ot.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Ot.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Ot.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Ot.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Ot.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Ot.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Ot.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Ot.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Ot.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Ot.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Ot.editor.languages.rust.customCommand}}}}}function yP(e){const t=e?.trim()??Ot.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 Hie(e,t){return e==="openpond"?"OpenPond Chat":fy(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function Lie(e,t,n){if(n){const a=qc(n,t).find(o=>o.value===e);if(a)return a.label}if(t)for(const a of bv){const o=qc(a,t).find(r=>r.value===e);if(o)return o.label}return[...mP,...fP].find(a=>a.value===e)?.label??e}function S8(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function x8(e){return e.experience==="chat"?"Chat":"Work"}const vy="taskDraft";function SP(e){if(e?.experience!=="work")return null;const t=e.metadata?.[vy];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Uc(e){return SP(e)!==null}function k8(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function Ch(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[vy]:a}}function w8(e){const t={...e??{}};return delete t[vy],t}function Es(e){const t=su(e.metadata?.trainingTasksetId)??su(e.metadata?.tasksetId);return t?{id:t,name:su(e.metadata?.trainingTasksetName)??su(e.metadata?.tasksetName)??I8(t)}:null}function I8(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 su(e){return typeof e=="string"&&e.trim()?e.trim():null}const _8="codex_history_";function Kt(e){return!!e?.startsWith(_8)}function xP(e){const t=[],n=new Set;for(const a of e)for(const o of[a.workspacePath,a.path]){const r=dp(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 C8(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=kP(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"||!wP(e))return null;const o=dp(e.cwd);if(!o)return null;for(const r of n)if(by(o,r.path))return r.projectId;return null}function px(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return It("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return It("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=kP(e.cwd,n);if(r)return It("local",r)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return It("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!wP(e))return null;const o=dp(e.cwd);if(!o)return null;for(const r of n)if(by(o,r.path))return It("local",r.projectId);return null}function kP(e,t){const n=dp(e);if(!n)return null;for(const a of t)if(by(n,a.path))return a.projectId;return null}function wP(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Kt(e.id)}function dp(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 by(e,t){const n=fx(e),a=fx(t);return n===a||n.startsWith(`${a}/`)}function fx(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const hx=[{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"}],R8=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function gx(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(o=>!Es(o)));else if(e.filter==="all")t.push(...e.activeSessions.filter(o=>!Es(o)),...e.doneSessions.filter(o=>!Es(o)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(o=>vx(o,e.selectedTasksetId)),...e.doneSessions.filter(o=>vx(o,e.selectedTasksetId)));else for(const o of e.activeSessions)Es(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=>Mu(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)=>yx(o,r,a)):n.sort((o,r)=>{const s=a?.get(o.id),c=a?.get(r.id);if(s!==void 0||c!==void 0){if(s===void 0)return 1;if(c===void 0)return-1;if(s!==c)return s-c}return o.order!==r.order?o.order-r.order:yx(o,r)})}function Mu(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Kt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function vx(e,t){const n=Es(e);return!!(n&&(!t||n.id===t))}function P8(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 bx(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 yx(e,t,n=null){const a=hc(e),o=hc(t);if(a!==o)return a?-1:1;if(a&&o){const s=n?.get(e.id),c=n?.get(t.id);if(s!==void 0||c!==void 0){if(s===void 0)return 1;if(c===void 0)return-1;if(s!==c)return s-c}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 hc(e){return e.pinned&&!e.savedForLater&&!e.archived}const lu={showCodexChats:!0,onlyRunningTasks:!1},IP="openpond.sidebar-task-visibility.v1";function Sx(e=_P()){try{const t=e?.getItem(IP);if(!t)return lu;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:lu.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:lu.onlyRunningTasks}}catch{return lu}}function xx(e,t=_P()){try{t?.setItem(IP,JSON.stringify(e))}catch{}}function _P(){return typeof window>"u"?null:kd}function CP(e){return`${e.kind}:${e.id}`}function zc(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function A8(e){return{kind:"session",id:e}}function T8(e){return{kind:"project",id:e}}function E8(e){return{kind:"draft",id:e}}function j8(e){return e.selectedSessionId?A8(e.selectedSessionId):e.selectedProjectId?T8(e.selectedProjectId):E8(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function M8(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(zc(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>zc(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function qie(e,t){return e.filter(n=>zc(n.scope,t))}function Uie(e,t){return!!(e&&zc(e.scope,t))}function O8(e){const t={};for(const n of e){const a=CP(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=N8(o.status,n.status,n.commandStatus),t[a]=o}return t}function $8(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 N8(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 RP(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=H8(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return o?a.push(o):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(Fo("ahead",e.ahead)),e.behind>0&&a.push(Fo("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(Fo("ahead",e.ahead)),e.behind>0&&a.push(Fo("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 PP(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,c=e?.sandboxTemplate?.manifestHash??null,m=o?.syncedAt??t?.syncedAt??null,u=!!(s&&c&&s!==c),f=!!(o?.projectId&&n?.headCommit&&!o.lastUploadedCommit),g=L8(n);return g?`${r} / ${g}`:f?`${r} / upload required`:`${r} / ${u||!m?"needs sync":"setup ready"}`}function D8(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(AP(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 H8(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?Fo("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?Fo("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function L8(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?Fo("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?Fo("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function Fo(e,t){return`${e} by ${AP(t)}`}function AP(e){return`${e} commit${e===1?"":"s"}`}function q8({size:e=14,className:t}){return x.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:[x.jsx("path",{d:"M12 13v8"}),x.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),x.jsx("path",{d:"m8 17 4-4 4 4"})]})}function TP({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:o=15}){const r=e==="cloud"?"cloud":n?"folder-open":"folder";return x.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:x.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"?x.jsx(B8,{}):n?x.jsx(z8,{}):x.jsx(U8,{}),t&&e==="local"?x.jsx(F8,{}):null]})})}function U8(){return x.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 z8(){return x.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 B8(){return x.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 F8(){return x.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[x.jsx("circle",{cx:"18",cy:"17",r:"5"}),x.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 mm=ST();function V8({title:e,pinned:t,savedForLater:n,archived:a,onRename:o,onTogglePin:r,onToggleSaveForLater:s,onDockRight:c,onArchive:m}){const u=y.useRef(null),f=y.useRef(null),[g,S]=y.useState(null),k=[...o?[{label:"Rename",Icon:sp,action:o}]:[],{label:t?"Unpin":"Pin",Icon:t?ay:ny,action:r},...s?[{label:n?"Return to active":"Save for later",Icon:n?ZR:JR,action:s}]:[],...c?[{label:"Open in right panel",Icon:Tg,action:c}]:[],{label:a?"Reopen":"Mark done",Icon:a?O9:Ci,action:m}];function C(P=!1){S(null),P&&u.current?.focus()}return y.useEffect(()=>{if(!g)return;f.current?.querySelector("button")?.focus();const P=R=>{!f.current?.contains(R.target)&&!u.current?.contains(R.target)&&S(null)},j=()=>S(null);return document.addEventListener("pointerdown",P),window.addEventListener("resize",j),()=>{document.removeEventListener("pointerdown",P),window.removeEventListener("resize",j)}},[g]),x.jsxs(x.Fragment,{children:[x.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${g?" is-open":""}`,children:x.jsx("button",{ref:u,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){C(!0);return}const j=P.currentTarget.getBoundingClientRect();S({left:Math.max(8,Math.min(j.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(j.bottom+4,window.innerHeight-(k.length*32+17)))})},children:x.jsx(bd,{size:16})})}),g&&mm.createPortal(x.jsx("div",{ref:f,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)||C()},onKeyDown:P=>{P.stopPropagation();const j=Array.from(P.currentTarget.querySelectorAll("button")),R=j.indexOf(document.activeElement);if(P.key==="Escape"&&(P.preventDefault(),C(!0)),["ArrowDown","ArrowUp","Home","End"].includes(P.key)){P.preventDefault();const $=P.key==="Home"?0:P.key==="End"?j.length-1:(R+(P.key==="ArrowDown"?1:-1)+j.length)%j.length;j[$]?.focus()}},children:k.map(({label:P,Icon:j,action:R},$)=>x.jsxs("button",{type:"button",role:"menuitem",className:$===k.length-1?"task-menu-done":void 0,onClick:()=>{C(!0),R()},children:[x.jsx(j,{size:15}),P]},P))}),document.body)]})}function K8({session:e,onSave:t,onClose:n}){const[a,o]=y.useState(e.title),r=y.useRef(null);y.useEffect(()=>{const m=r.current;m&&(m.focus(),m.select())},[]),y.useEffect(()=>{function m(u){u.key==="Escape"&&n()}return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[n]);function s(){const m=a.trim();m&&(t(m),n())}function c(m){m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),s())}return x.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:x.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:m=>m.stopPropagation(),children:[x.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),x.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:m=>o(m.target.value),onKeyDown:c,"aria-label":"Chat title"}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),x.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:s,disabled:!a.trim(),children:"Save"})]})]})})}const W8=24;function G8({title:e}){const t=y.useRef(e),[n,a]=y.useState(e);return y.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 c=window.setInterval(()=>{s+=1,a(r.slice(0,s).join("")),s>=r.length&&window.clearInterval(c)},W8);return()=>window.clearInterval(c)},[e]),x.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const J8=2650,Z8=304,Y8=260,Q8=new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric"}),X8=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit"}),eG=new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"});function tG(){return{animationDelay:`${-(Date.now()%J8)}ms`}}function nG(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 Rh({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:o,children:r,collapsed:s=!1,titleActive:c=!1,onTitleClick:m,onToggleCollapsed:u}){return x.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[x.jsxs("div",{className:"section-header",children:[x.jsxs("div",{className:"section-title-row",children:[m?x.jsxs("div",{className:"section-title-combo",children:[x.jsx("button",{type:"button",className:`section-title-link${c?" active":""}`,onClick:m,children:x.jsx("span",{children:e})}),u&&x.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:u,children:s?x.jsx(Mr,{size:13}):x.jsx(yo,{size:13})})]}):u?x.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${s?"Expand":"Collapse"} ${e}`,"aria-expanded":!s,onClick:u,children:[x.jsx("span",{children:e}),s?x.jsx(Mr,{size:13}):x.jsx(yo,{size:13})]}):x.jsx("span",{children:e}),o]}),t&&x.jsx("div",{className:"section-actions",children:t})]}),!s&&x.jsx("div",{className:"sidebar-section-body",children:r})]})}function kx({children:e,expanded:t=!1,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Ph({session:e,selected:t,icon:n,archived:a=!1,hideIcon:o=!1,nested:r=!1,dragging:s,placeholder:c,running:m,goalRuntime:u,subagentRuntime:f,terminalIndicator:g,projectLabel:S,ariaDescribedBy:k,childSessionCount:C=0,childSessionsExpanded:P=!1,onSelect:j,onToggleChildSessions:R,onTogglePin:$,onToggleSaveForLater:O,onDockRight:M,onArchive:w,onDragStart:A,onDragEnd:E,onDragOver:D,onDrop:U,onRename:L}){const[J,X]=y.useState(!1),de=u?.status==="queued",Me=u?.tone==="active"&&!de,Ie=(f?.activeCount??0)>0,ne=C>0&&!!R,je=o&&!ne,Se=Ie||Me||!de&&(m??e.status==="active"),oe=Ie&&f?f.label:Me&&u?iG(u):"Running",be=["sidebar-task-row",Uc(e)?"is-draft":"",Se?"has-running-dot":""].filter(Boolean).join(" "),re=y.useMemo(tG,[]),ue=x.jsx(V8,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:L?()=>X(!0):void 0,onTogglePin:$,onToggleSaveForLater:O,onDockRight:M,onArchive:w}),ke=x.jsxs(yy,{selected:t,dataSessionId:e.id,dragging:s,iconless:je,nested:r,placeholder:c,className:be||void 0,ariaExpanded:ne?P:void 0,ariaDescribedBy:k,onSelect:j,onDragStart:A,onDragEnd:E,onDragOver:D,onDrop:U,onDoubleClick:L?()=>X(!0):void 0,children:[je?null:ne?x.jsx("button",{type:"button",className:"sidebar-child-toggle","data-tooltip":P?"Hide subagent conversations":"Show subagent conversations","aria-label":`${P?"Hide":"Show"} ${C} subagent ${C===1?"conversation":"conversations"}`,"aria-expanded":P,onClick:we=>{we.stopPropagation(),R?.()},children:P?x.jsx(yo,{size:13}):x.jsx(Mr,{size:13})}):n??x.jsx(rp,{size:15}),x.jsx("span",{className:"row-label-shell",title:S||void 0,children:x.jsx("span",{className:"sidebar-session-title-line",children:x.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:nG,children:x.jsx(G8,{title:e.title})})})}),x.jsxs("div",{className:"row-meta",children:[x.jsxs("span",{className:"row-meta-status",children:[g?x.jsx(EP,{indicator:g}):null,Se?x.jsx("span",{className:`sidebar-running-dot${Ie?" subagent":Me?" goal":""}`,style:re,"aria-label":oe}):null]}),ue]})]}),Le=J&&L?x.jsx(K8,{session:e,onSave:we=>L(e,we),onClose:()=>X(!1)}):null;return x.jsxs(x.Fragment,{children:[ke,Le]})}function aG({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:o,onToggleSaveForLater:r,onDragStart:s,onDragEnd:c,onDragOver:m,onDrop:u}){const f=e.path.split("/").at(-1)??e.path,g=`${e.workspaceName} · ${e.path}`;return x.jsxs(yy,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:s,onDragEnd:c,onDragOver:m,onDrop:u,children:[e.available?x.jsx(ey,{size:15}):x.jsx(sm,{size:15}),x.jsx("span",{className:"row-label-shell",title:g,children:x.jsx("span",{className:"row-label",children:f})}),x.jsx("div",{className:"row-meta",children:x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(pm,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:o,children:e.status==="pinned"?x.jsx(ay,{size:13}):x.jsx(ny,{size:13})}),x.jsx(pm,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?x.jsx(ZR,{size:13}):x.jsx(JR,{size:13})})]})})]})}function iG(e){return e.actionLabel}function oG({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:o=!1,disclosure:r=!0,workspaceState:s,cloudLinkTrusted:c=!0,cloudLinkWarning:m=null,placeholder:u,terminalIndicator:f,onSelect:g,onNewChat:S,onMoveToCloud:k,onWorkspaceTargetSelect:C,onTogglePin:P,onRemove:j,onDragStart:R,onDragEnd:$,onDragOver:O,onDrop:M}){const[w,A]=y.useState(!1),E=y.useRef(null),[D,U]=y.useState({}),L=!!k||!!j,J=e==="local"&&c!==!1&&!!t.linkedSandboxProject?.projectId,X=y.useCallback(()=>{if(typeof window>"u")return;const Ie=E.current?.getBoundingClientRect();if(!Ie)return;const ne=Math.max(12,window.innerWidth-Z8-12),je=Math.max(12,window.innerHeight-Y8),Se=Math.max(12,Math.min(Ie.right+10,ne)),oe=Math.max(12,Math.min(Ie.top-4,je)),be={"--sidebar-project-locations-left":`${Math.round(Se)}px`,"--sidebar-project-locations-top":`${Math.round(oe)}px`};U(re=>re["--sidebar-project-locations-left"]===be["--sidebar-project-locations-left"]&&re["--sidebar-project-locations-top"]===be["--sidebar-project-locations-top"]?re:be)},[]),de=y.useCallback(()=>{X(),g()},[g,X]);function Me(){A(!1)}return x.jsxs("div",{ref:E,className:["sidebar-project-row-shell",w?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:X,onPointerEnter:X,children:[x.jsxs(yy,{selected:a,placeholder:u,className:["sidebar-project-row",w?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?o:void 0,onSelect:de,onDragStart:R,onDragEnd:$,onDragOver:O,onDrop:M,children:[x.jsx(TP,{kind:e,linkedCloud:J,open:e==="local"&&o,className:"sidebar-row-icon",baseSize:15}),x.jsx("span",{className:"row-label-shell",children:x.jsxs("span",{className:"sidebar-project-title-line",children:[x.jsx("span",{className:"row-label",children:t.name}),x.jsx(rG,{value:t.updatedAt}),r?x.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:o?x.jsx(yo,{size:13}):x.jsx(Mr,{size:13})}):null]})}),x.jsxs("div",{className:"row-meta",children:[x.jsx("span",{className:"row-meta-status",children:f?x.jsx(EP,{indicator:f}):null}),x.jsxs("div",{className:"sidebar-row-actions",children:[x.jsx(pm,{label:n?"Unpin project":"Pin project",onClick:P,children:n?x.jsx(ay,{size:13}):x.jsx(ny,{size:13})}),L&&x.jsx(SG,{open:w,onToggleOpen:()=>A(Ie=>!Ie)}),x.jsx(pm,{label:"New task",onClick:S,children:x.jsx(sp,{size:13})})]})]})]}),x.jsx(lG,{kind:e,project:t,workspaceState:s,cloudLinkTrusted:c,cloudLinkWarning:m,onWorkspaceTargetSelect:C,style:D}),w&&x.jsx(xG,{onClose:Me,onMoveToCloud:k?()=>{Me(),k()}:void 0,onRemove:()=>{Me(),j()}})]})}function rG({value:e}){const t=sG(e);if(!t||!e)return null;const n=new Date(e);return x.jsx("time",{className:"sidebar-row-updated-at",dateTime:e,title:`Last updated ${eG.format(n)}`,children:t})}function sG(e,t=new Date){if(!e)return null;const n=new Date(e);if(Number.isNaN(n.getTime()))return null;const a=X8.format(n);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()?a:`${Q8.format(n)} ${a}`}function EP({indicator:e}){return x.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:x.jsx(iP,{size:13})})}function lG({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:o,onWorkspaceTargetSelect:r,style:s}){const c=uG(e,t,n,a,o);return x.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:s,children:[x.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),x.jsx("div",{className:"sidebar-project-location-list",children:c.map(m=>{const u=["sidebar-project-location-row",m.tone??"",m.actionTarget?"clickable":""].filter(Boolean).join(" "),f=x.jsxs(x.Fragment,{children:[x.jsx("span",{className:["sidebar-project-location-icon",m.key].filter(Boolean).join(" "),"aria-hidden":"true",children:m.icon}),x.jsx("span",{className:"sidebar-project-location-copy",children:x.jsx(cG,{value:m.value})})]});return m.actionTarget?x.jsx("button",{type:"button",className:u,"data-workspace-target":m.actionTarget,disabled:m.disabled||!r,title:m.disabledReason??void 0,onClick:g=>{g.stopPropagation(),!m.disabled&&r?.(m.actionTarget)},children:f},m.key):x.jsx("div",{className:u,children:f},m.key)})})]})}function cG({value:e}){const t=dG(e);return x.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?x.jsxs(x.Fragment,{children:[x.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),x.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,x.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function dG(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function uG(e,t,n,a=!0,o=null){return e==="cloud"?pG(t):mG(t,n,a,o)}function mG(e,t,n=!0,a=null){const o=fG(e,t,n),r=hG(t),s=vG(e,n),c=n===!1&&a;return[{key:"local",value:o,tone:r?"attention":"local",icon:e.source==="git"?x.jsx(XR,{size:13}):x.jsx(QR,{size:13}),actionTarget:"local"},{key:"cloud",value:c||(s?bG(e,t,n):"not in cloud"),tone:c?"attention":"cloud",icon:x.jsx(op,{size:13}),actionTarget:s?"cloud":"upload_cloud"}]}function pG(e){return[{key:"cloud",value:yG(e),tone:e.syncedAt?"cloud":"attention",icon:x.jsx(op,{size:13}),actionTarget:"cloud"}]}function fG(e,t,n){const a=gG(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?RP(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function hG(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function gG(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function vG(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function bG(e,t,n){return PP(e,null,t,{cloudLinkTrusted:n})}function yG(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function SG({open:e,onToggleOpen:t}){return x.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:x.jsx(bd,{size:13})})}function xG({onClose:e,onMoveToCloud:t,onRemove:n}){return x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),x.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[x.jsx(q8,{size:13}),x.jsx("span",{children:"Move to Cloud"})]}),x.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[x.jsx(yd,{size:13}),x.jsx("span",{children:"Remove from Projects"})]})]})]})}function yy({children:e,className:t,dataSessionId:n,dragging:a,iconless:o=!1,nested:r=!1,placeholder:s=!1,selected:c,ariaExpanded:m,ariaDescribedBy:u,onSelect:f,onDragStart:g,onDragEnd:S,onDragOver:k,onDrop:C,onDoubleClick:P}){const j=!!g;return x.jsx("div",{className:["sidebar-row",t??"",c?"selected":"",a?"dragging":"",o?"iconless":"",r?"nested":"",s?"placeholder":""].filter(Boolean).join(" "),draggable:j,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":m,"aria-describedby":u,onClick:f,onDoubleClick:P,onKeyDown:R=>{R.target===R.currentTarget&&(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),f())},onDragStart:g,onDragEnd:S,onDragEnter:R=>{k&&(R.preventDefault(),R.dataTransfer.dropEffect="move",k(R))},onDragOver:R=>{k&&(R.preventDefault(),R.dataTransfer.dropEffect="move",k(R))},onDrop:R=>{C&&(R.preventDefault(),C(R))},children:e})}function pm({children:e,label:t,onClick:n}){return x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function kG({filter:e,groupByProject:t,noun:n,onFilterChange:a,onGroupByProjectChange:o,onOnlyRunningTasksChange:r,onShowCodexChatsChange:s,onTasksetChange:c,onSortChange:m,onlyRunningTasks:u,openMenu:f,setOpenMenu:g,showCodexChats:S,sort:k,selectedTasksetId:C,tasksets:P}){const j=y.useRef(null),[R,$]=y.useState(!1),M=P.find(E=>E.id===C)?.name??hx.find(E=>E.value===e)?.label??"Active",w=f==="tasks-filter",A=f==="chats";return y.useEffect(()=>{if(!w&&!A)return;function E(D){j.current?.contains(D.target)||g(null)}return document.addEventListener("pointerdown",E),()=>document.removeEventListener("pointerdown",E)},[w,g,A]),x.jsxs("div",{className:"sidebar-task-list-controls",ref:j,children:[x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${A?"active":""}`,"aria-label":`${n==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":A,onClick:()=>g(E=>E==="chats"?null:"chats"),children:x.jsx(bd,{size:14})}),A?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${n==="tasks"?"Task":"Chat"} list options`,children:[x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":S,onClick:()=>s(!S),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:S?x.jsx(Ci,{size:13}):null}),x.jsx("span",{children:"Show Codex chats, including pinned"})]}),x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":u,onClick:()=>r(!u),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:u?x.jsx(Ci,{size:13}):null}),x.jsxs("span",{children:["Only running ",n,", including pinned"]})]}),n==="tasks"?x.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":t,onClick:()=>o(!t),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:t?x.jsx(Ci,{size:13}):null}),x.jsx("span",{children:"Group by project"})]}):null,R8.map(E=>x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":k===E.value,onClick:()=>{m(E.value),g(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:k===E.value?x.jsx(Ci,{size:13}):null}),x.jsx("span",{children:E.label})]},E.value))]}):null]}),x.jsxs("div",{className:"section-menu",children:[x.jsx("button",{type:"button",className:`section-icon ${w?"active":""}`,"aria-label":`Filter ${n}: ${M}`,"aria-haspopup":"menu","aria-expanded":w,onClick:()=>g(E=>E==="tasks-filter"?null:"tasks-filter"),children:x.jsx(fW,{size:14})}),w?x.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${n}`,children:hx.map(E=>x.jsxs(y.Fragment,{children:[E.value==="tasksets"?x.jsxs("button",{type:"button",role:"menuitem","aria-expanded":R,onClick:()=>$(D=>!D),children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:R?x.jsx(yo,{size:13}):x.jsx(Mr,{size:13})}),x.jsx("span",{children:E.label})]}):x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===E.value,onClick:()=>{a(E.value),g(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===E.value?x.jsx(Ci,{size:13}):null}),x.jsx("span",{children:E.label})]}),E.value==="tasksets"&&R?x.jsxs(x.Fragment,{children:[x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!C,onClick:()=>{c(null),g(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!C?x.jsx(Ci,{size:13}):null}),x.jsx("span",{children:"All Tasksets"})]}),P.map(D=>x.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&C===D.id,onClick:()=>{c(D.id),g(null)},children:[x.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&C===D.id?x.jsx(Ci,{size:13}):null}),x.jsx("span",{children:D.name}),x.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:D.chatCount})]},D.id))]}):null]},E.value))}):null]})]})}function wG({onAddProject:e,onViewProjects:t}){const[n,a]=y.useState(!1),o=y.useRef(null),r=y.useRef(null);return y.useEffect(()=>{if(!n)return;o.current?.querySelector('[role="menuitem"]')?.focus();const s=c=>{o.current?.contains(c.target)||a(!1)};return document.addEventListener("pointerdown",s),()=>document.removeEventListener("pointerdown",s)},[n]),x.jsxs(x.Fragment,{children:[x.jsxs("div",{className:"section-menu",ref:o,onKeyDown:s=>{s.key==="Escape"&&(s.stopPropagation(),a(!1),r.current?.focus())},children:[x.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:x.jsx(bd,{size:14})}),n?x.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),x.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const IG=240,_G=36;function CG(e,t,n=!1){const a=Math.max(12,t.width-IG-12),o=Math.max(12,t.height-_G-(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 RG({detail:e,onClose:t}){if(y.useEffect(()=>{if(!e||typeof window>"u")return;const o=c=>{c.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 x.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[x.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?x.jsxs("div",{className:"sidebar-task-detail-folder",children:[x.jsx(QR,{size:13,"aria-hidden":"true"}),x.jsx("span",{children:e.folderName})]}):null]})}function PG({children:e,expanded:t,groupKey:n,kind:a,label:o,onToggle:r,onNewTask:s,onOpenProject:c,onRemoveProject:m,project:u}){const f=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,g=a==="draft"?ey:rp,[S,k]=y.useState(!1),C=!!(s||c||m);return x.jsxs("section",{className:"sidebar-task-project-group",children:[x.jsxs("div",{className:`sidebar-task-project-group-header-shell${S?" menu-open":""}`,children:[x.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":f,"aria-expanded":t,onClick:()=>{k(!1),r()},children:[u?x.jsx(TP,{kind:u.kind,linkedCloud:!!(u.kind==="local"&&u.project.linkedSandboxProject?.projectId),open:u.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):x.jsx(g,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),x.jsx("span",{className:"sidebar-task-project-group-name",children:o}),x.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?x.jsx(yo,{size:13}):x.jsx(Mr,{size:13})})]}),u&&C?x.jsxs("div",{className:"sidebar-task-project-group-actions",children:[c||m?x.jsx("button",{type:"button",className:`sidebar-row-action${S?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":S,"aria-haspopup":"menu",onClick:()=>k(P=>!P),children:x.jsx(bd,{size:13})}):null,s?x.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:s,children:x.jsx(sp,{size:13})}):null]}):null,S?x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>k(!1)}),x.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[c?x.jsx("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),c()},children:x.jsx("span",{children:"Open project"})}):null,m?x.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{k(!1),m()},children:[x.jsx(yd,{size:13}),x.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?x.jsx("div",{id:f,className:"sidebar-task-project-group-content",children:e}):null]})}const AG={},TG=new Map,EG=new Map;function jG(e,t){return Math.min(Math.max(e,Hn)+Hg,t)}function MG(e,t){const n=Math.max(Hn,Math.min(e,t));if(n<=Hn)return Hn;const a=Math.ceil((n-Hn)/Hg);return Math.max(Hn,Hn+(a-1)*Hg)}function OG(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 $G({activeSessions:e,archiveSession:t,archivedSessions:n,chatRowsVisibleCount:a,childSessionRowsByParentId:o={},cloudProjectRows:r,beginProjectChat:s,onAddProject:c,commitTaskDrop:m,commitTaskPreviewDrop:u,dockSessionRight:f,experience:g="work",goalRuntimeBySessionId:S=TG,localProjectRows:k,openSidebarFile:C,pinnedCollapsed:P,pinnedRows:j,previewTaskDrop:R,previewPinnedDrop:$,projectRows:O,renameSession:M,restoreSession:w,runningSessionIds:A,sectionMenuOpen:E,selectedProjectId:D,selectedSessionId:U,setChatRowsVisibleCount:L,setSectionMenuOpen:J,setSelectedAppId:X,setSelectedProjectId:de,setSelectedSessionId:Me,setView:Ie,sidebarProjectIdBySessionId:ne,startTaskDrag:je,startPinnedDrag:Se,subagentRuntimeBySessionId:oe=EG,taskDragSessionId:be,taskPreviewSessionIds:re,terminalSummaries:ue=AG,toggleSessionPinned:ke,toggleSessionSavedForLater:Le,view:we,clearTaskDrag:le,removeProject:xe,toggleProjectPinned:Ue,onTogglePinnedCollapsed:Ze,setSidebarFileStatus:it,commitPinnedDrop:at,commitPinnedPreviewDrop:Ne,clearSidebarDrag:We,dragItem:qe}){const[q,N]=y.useState("active"),[F,ee]=y.useState("recent"),[me,$e]=y.useState(!0);y.useEffect(()=>{g!=="chat"&&$e(!0)},[g]);const[ze,tt]=y.useState({work:!1,chat:!0}),[nt,pt]=y.useState({work:!1,chat:!1}),bt=g==="chat"?"chat":"work",Oe=ze[bt],[Ye,h]=y.useState(Sx);xd(()=>h(Sx()));const{onlyRunningTasks:B,showCodexChats:Y}=Ye,[ge,se]=y.useState(null),[G,_]=y.useState(()=>new Set),[W,ae]=y.useState(()=>new Map),[Z,ce]=y.useState(null);y.useEffect(()=>{D&&tt(K=>K[bt]?{...K,[bt]:!1}:K)},[bt,D]);const fe=g==="chat"?"chats":"tasks",he=O??[...k,...r],Ae=y.useMemo(()=>new Map(he.map(K=>[K.id,K.project.name])),[he]),Ce=y.useMemo(()=>new Map(he.map(K=>[K.id,K])),[he]),He=y.useMemo(()=>{const K=new Set(A);for(const Be of e){const _e=S.get(Be.id),Ve=oe.get(Be.id);(_e?.tone==="active"&&_e.status!=="queued"||(Ve?.activeCount??0)>0||Lt(Be.id)?.status==="running")&&K.add(Be.id)}return K},[e,S,A,oe,ue]),Pe=y.useMemo(()=>gx({activeSessions:e,doneSessions:n,filter:"all",inProgressSessionIds:He,sort:"manual"}),[e,n,He]),Xe=y.useMemo(()=>gx({activeSessions:e,doneSessions:n,filter:q,inProgressSessionIds:He,onlyRunningTasks:B,selectedTasksetId:ge,previewSessionIds:re,showCodexChats:Y,sort:F}),[e,n,He,B,ge,Y,q,re,F]),mt=y.useMemo(()=>{const K=new Map;for(const Be of[...e,...n]){if(!Mu(Be,{inProgressSessionIds:He,onlyRunningTasks:B,showCodexChats:Y}))continue;const _e=Es(Be);if(!_e)continue;const Ve=K.get(_e.id);Ve?Ve.chatCount+=1:K.set(_e.id,{..._e,chatCount:1})}return[...K.values()].sort((Be,_e)=>Be.name.localeCompare(_e.name))},[e,n,He,B,Y]),fn=y.useMemo(()=>j.filter(K=>K.type!=="session"||Mu(K.session,{inProgressSessionIds:He,onlyRunningTasks:B,showCodexChats:Y})),[He,B,j,Y]),Mt=y.useMemo(()=>Xe.filter(K=>!hc(K)),[Xe]),dn=y.useMemo(()=>Mt.slice(0,Math.max(Hn,a)),[a,Mt]),yn=y.useMemo(()=>{const K=OG(dn,Be=>{if(Uc(Be))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const _e=ne[Be.id],Ve=St(Be)??"Work";return{key:_e?`project:${_e}`:`projectless:${Ve}`,label:Ve,projectId:_e??null,project:_e?Ce.get(_e)??null:null,kind:_e?"project":"projectless"}});for(const Be of he)K.some(_e=>_e.projectId===Be.id)||K.push({key:`project:${Be.id}`,label:Be.project.name,projectId:Be.id,project:Be,kind:"project",sessions:[]});return K},[he,Ae,Ce,ne,dn]),Sn=dn.length<Mt.length,Qt=dn.length>Hn,Ja=y.useMemo(()=>new Set(yn.filter(K=>K.sessions.some(Be=>Be.id===U||He.has(Be.id))).map(K=>K.key)),[yn,He,U]),_a=Pe.filter(K=>!hc(K)).map(K=>K.id),zn=dn.map(K=>K.id),$n=JSON.stringify(Object.entries(o).filter(([K,Be])=>Be.length>0&&(oe.get(K)?.activeCount??0)>0).flatMap(([K,Be])=>Be.map(_e=>[K,_e.id])).sort(([K,Be],[_e,Ve])=>K.localeCompare(_e)||Be.localeCompare(Ve)));y.useEffect(()=>{const K=JSON.parse($n);if(K.length===0)return;const Be=new Set(K.map(([_e])=>_e));_(_e=>[...Be].every(Ve=>_e.has(Ve))?_e:new Set([..._e,...Be]))},[$n]);function Lt(K){return $8(ue[CP({kind:"session",id:K})])}function St(K){if(Uc(K))return"Draft";const Be=ne[K.id];return Be?Ae.get(Be)??K.workspaceName??"Project":x8(K)}function xn(K){ln({kind:"chat",sessionId:K.id}),Me(K.id);const Be=ne[K.id]??null;X(Be?null:K.appId),de(Be),Ie("chat")}function xt(K){return(o[K.id]??[]).filter(Be=>Mu(Be,{inProgressSessionIds:He,onlyRunningTasks:B,showCodexChats:Y}))}function Dt(K,Be){return G.has(K.id)||Be.some(_e=>_e.id===U)}function Ca(K){_(Be=>{const _e=new Set(Be);return _e.has(K)?_e.delete(K):_e.add(K),_e})}function Vt(K){const Be=xt(K);return Be.length===0||!Dt(K,Be)?null:x.jsx("div",{className:"sidebar-child-session-group",children:Be.map(_e=>x.jsx(Ph,{session:_e,selected:we==="chat"&&U===_e.id,hideIcon:!0,nested:!0,running:He.has(_e.id),goalRuntime:S.get(_e.id)??null,subagentRuntime:oe.get(_e.id)??null,terminalIndicator:Lt(_e.id),projectLabel:St(K),onSelect:()=>xn(_e),onTogglePin:()=>ke(_e),onToggleSaveForLater:()=>Le(_e),onDockRight:()=>f(_e),onArchive:()=>_e.archived?w(_e):t(_e),onRename:M},_e.id))})}function kn(K,Be){if(typeof window>"u")return;const _e=hc(K)?St(K):null;ce({descriptionId:`sidebar-task-detail-${K.id}`,sessionId:K.id,title:K.title,updatedAt:K.updatedAt,folderName:_e,style:CG(Be.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!_e)})}function st(K,Be={}){const _e=K.archived,Ve=be===K.id,wt=xt(K),na="sidebar-session-group",wn=F==="manual"?{onDragStart:Je=>je(Je,{allSessionIds:_a,visibleSessionIds:zn,sessionId:K.id}),onDragEnd:le,onDragOver:Je=>{Ve||R(Je,K.id)},onDrop:Je=>{Ve?u():m(Je,K.id)}}:{};return x.jsxs("div",{className:na,onPointerEnter:Je=>kn(K,Je.currentTarget),onPointerLeave:()=>ce(null),onFocusCapture:Je=>kn(K,Je.currentTarget),onBlurCapture:Je=>{Je.currentTarget.contains(Je.relatedTarget)||ce(null)},children:[x.jsx(Ph,{session:K,selected:!_e&&we==="chat"&&U===K.id,archived:_e,hideIcon:!0,placeholder:Ve,running:He.has(K.id),goalRuntime:S.get(K.id)??null,subagentRuntime:oe.get(K.id)??null,terminalIndicator:Lt(K.id),projectLabel:Be.projectLabel===void 0?St(K):Be.projectLabel,metadataPresentation:Be.metadataPresentation,ariaDescribedBy:Z?.sessionId===K.id?Z.descriptionId:void 0,childSessionCount:wt.length,childSessionsExpanded:Dt(K,wt),onToggleChildSessions:()=>Ca(K.id),onSelect:()=>{ce(null),_e&&w(K),xn(K)},onTogglePin:()=>ke(K),onToggleSaveForLater:()=>Le(K),onDockRight:()=>f(K),onArchive:()=>_e?w(K):t(K),onRename:M,...wn}),Ve?null:Vt(K)]},K.id)}function Mn(K){K!=="tasksets"&&se(null),N(K),L(Hn)}function fi(K){se(K),N("tasksets"),L(Hn)}function hi(K){ee(K),L(Hn)}function ha(){L(K=>jG(K,Mt.length))}function Ra(){L(K=>MG(K,Mt.length))}function Bn(K){const Be={id:K.id,type:K.type};return{onDragStart:_e=>Se(_e,Be),onDragEnd:We,onDragOver:_e=>$(_e,Be),onDrop:_e=>{qe?.id===K.id&&qe.type===K.type?Ne():at(_e,Be)}}}function zi(K){const Be=Bn(K),_e=qe?.id===K.id&&qe.type===K.type;if(K.type==="project"){const wt=K.item;return x.jsx(oG,{kind:wt.kind,project:wt.project,pinned:!0,selected:we==="chat"&&D===wt.id,expanded:!1,disclosure:!1,placeholder:_e,onSelect:()=>{X(null),de(wt.id),Me(null),Ie("chat")},onNewChat:()=>s(wt.id),onTogglePin:()=>Ue(wt),onRemove:()=>xe(wt),...Be},K.key)}if(K.type==="file")return x.jsx(aG,{file:K.file,placeholder:_e,onSelect:()=>C(K.file),onTogglePin:()=>it(K.file,"none"),onToggleSaveForLater:()=>it(K.file,"saved_for_later"),...Be},K.key);const Ve=K.session;return x.jsx("div",{onPointerEnter:wt=>kn(Ve,wt.currentTarget),onPointerLeave:()=>ce(null),onFocusCapture:wt=>kn(Ve,wt.currentTarget),onBlurCapture:wt=>{wt.currentTarget.contains(wt.relatedTarget)||ce(null)},children:x.jsx(Ph,{ariaDescribedBy:Z?.sessionId===Ve.id?Z.descriptionId:void 0,session:Ve,selected:we==="chat"&&U===Ve.id,hideIcon:!0,placeholder:_e,running:He.has(Ve.id),goalRuntime:S.get(Ve.id)??null,subagentRuntime:oe.get(Ve.id)??null,terminalIndicator:Lt(Ve.id),projectLabel:St(Ve),metadataPresentation:"flyout",onSelect:()=>{ce(null),xn(Ve)},onTogglePin:()=>ke(Ve),onToggleSaveForLater:()=>Le(Ve),onDockRight:()=>f(Ve),onArchive:()=>t(Ve),onRename:M,...Be})},K.key)}function Za(K){const Be=Ja.has(K.key)||W.get(K.key)!==!1;return x.jsx(PG,{expanded:Be,groupKey:K.key,kind:K.kind,label:K.label,onToggle:()=>{ae(_e=>{const Ve=new Map(_e);return Ve.set(K.key,!Be),Ve})},onNewTask:K.project?()=>s(K.project.id):void 0,onOpenProject:K.project?()=>{X(null),de(K.project.id),Me(null),Ie("chat")}:void 0,onRemoveProject:K.project?()=>xe(K.project):void 0,project:K.project,children:K.sessions.map(_e=>st(_e,{metadataPresentation:"flyout",projectLabel:K.label}))},K.key)}return x.jsxs("div",{className:"sidebar-sections",children:[fn.length>0?x.jsx(Rh,{label:"Pinned",className:"sidebar-pinned-section",collapsed:P,onToggleCollapsed:Ze,children:fn.map(zi)}):null,x.jsx(Rh,{label:"Projects",className:`sidebar-projects-section${g!=="chat"?" development":""}`,collapsed:Oe,onToggleCollapsed:()=>tt(K=>({...K,[bt]:!K[bt]})),actions:x.jsx(wG,{onAddProject:c,onViewProjects:()=>{(async()=>await ln({kind:"view",view:"projects"})&&(X(null),de(null),Me(null),Ie("projects")))()}}),children:yn.filter(K=>K.kind==="project").map(K=>Za(g==="chat"||!me?{...K,sessions:[]}:K))}),x.jsxs(Rh,{label:g==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:nt[bt],onToggleCollapsed:()=>pt(K=>({...K,[bt]:!K[bt]})),actionsVisible:E==="chats"||E==="tasks-filter"||q!=="active"||B||!Y,actions:x.jsx(kG,{filter:q,groupByProject:me,noun:fe,onFilterChange:Mn,onGroupByProjectChange:$e,onOnlyRunningTasksChange:K=>{h(Be=>{const _e={...Be,onlyRunningTasks:K};return xx(_e),_e}),L(Hn)},onShowCodexChatsChange:K=>{h(Be=>{const _e={...Be,showCodexChats:K};return xx(_e),_e}),L(Hn)},onTasksetChange:fi,onSortChange:hi,onlyRunningTasks:B,openMenu:E,setOpenMenu:J,showCodexChats:Y,sort:F,selectedTasksetId:ge,tasksets:mt}),children:[(g==="chat"||!me?dn:dn.filter(K=>!ne[K.id])).map(K=>st(K)),Mt.length===0&&fn.length===0?x.jsx("div",{className:"empty-row",children:P8(q,fe)}):null,Mt.length>Hn&&(Sn||Qt)?x.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${dn.length} of ${Mt.length} ${fe}`,children:[Sn?x.jsx(kx,{onClick:ha,children:"Show more"}):null,Qt?x.jsx(kx,{onClick:Ra,children:"Show less"}):null]}):null]}),x.jsx(RG,{detail:Z,onClose:()=>ce(null)})]})}const NG=y.lazy(()=>Go(()=>import("./TerminalOverlay-DaonK5C0.js"),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.TerminalOverlay})));function DG({connection:e,command:t,onClose:n,onComplete:a}){const[o,r]=y.useState([]),[s]=y.useState(()=>({kind:"draft",id:`native-setup-${crypto.randomUUID()}`})),c=y.useRef(!1),[m]=y.useState(()=>({id:Date.now(),scope:s,command:t}));return y.useEffect(()=>{!c.current&&o.some(u=>u.lastExitCode!==null&&(u.commandStatus==="success"||u.commandStatus==="failed"))&&(c.current=!0,a?.())},[o,a]),mm.createPortal(x.jsx("div",{className:"native-setup-terminal",children:x.jsx(y.Suspense,{fallback:x.jsx("p",{role:"status",children:"Opening setup terminal…"}),children:x.jsx(NG,{open:!0,disposeOnUnmount:!0,connection:e,scope:s,tabs:o,onTabsChange:r,cwd:null,appId:null,workspaceName:"Agent setup",queuedCommand:m,onClose:n})})}),document.body)}const cu={codex:"Codex",claude_code:"Claude Code",opencode:"OpenCode",grok_build:"Grok Build",hermes:"Hermes",pi:"Pi",oh_my_pi:"Oh My Pi",openclaw:"OpenClaw"};function HG({status:e,busy:t,onControl:n,onConnectionControl:a,onReconnect:o}){const r=e.desiredState==="stopped",s=r?"Importer stopped":e.running?"Importer running":"Importer offline";return x.jsxs("div",{className:"sidebar-section native-importer-status",children:[x.jsx("strong",{children:s}),e.connections.map(c=>{const m=c.backfill,u=m.stage==="complete",f=m.admitted+m.skipped;return x.jsxs("div",{className:"native-importer-connection",children:[x.jsxs("span",{children:[c.error?x.jsx(sm,{size:12}):u?x.jsx(Ci,{size:12}):x.jsx(ty,{size:12}),cu[c.source]??c.source]}),x.jsx("small",{children:c.state==="paused"?"Paused":c.state==="disconnected"?"Disconnected":u?e.running&&!r?"Watching for new conversations":`${m.admitted} conversations imported`:m.stage==="discovering"?"Finding conversations":`${f} of ${m.total} conversations processed`}),x.jsxs("small",{children:[c.admitted," tasks admitted",m.skipped>0?`, ${m.skipped} conversations skipped`:"",m.failed>0?`, ${m.failed} failed`:""]}),!u&&m.total>0?x.jsx("progress",{"aria-label":`${cu[c.source]??c.source} import progress`,value:f,max:m.total}):null,c.queued>0?x.jsxs("small",{children:[c.queued," updates waiting to upload (",new Intl.NumberFormat(void 0,{notation:"compact"}).format(c.pendingBytes)," bytes)"]}):null,c.lastAdmissionAt?x.jsxs("small",{children:["Last synced ",x.jsx("time",{dateTime:c.lastAdmissionAt,children:new Date(c.lastAdmissionAt).toLocaleString()})]}):x.jsx("small",{children:"No uploads acknowledged yet"}),c.destinationLinks?.tasks?x.jsx("a",{href:c.destinationLinks.tasks,target:"_blank",rel:"noopener noreferrer",children:"View tasks"}):null,c.destinationLinks?.conversations?x.jsx("a",{href:c.destinationLinks.conversations,target:"_blank",rel:"noopener noreferrer",children:"View conversations"}):null,c.error?x.jsx("small",{role:"status",children:c.error}):null,c.state==="disconnected"?x.jsx("button",{type:"button",disabled:t,onClick:()=>o(c.id),children:"Reconnect source"}):x.jsxs("div",{children:[x.jsxs("button",{type:"button",disabled:t,onClick:()=>a(c.state==="paused"?"resume":"pause",c.id),children:[c.state==="paused"?"Resume":"Pause"," ",cu[c.source]??c.source]}),x.jsxs("button",{type:"button",disabled:t,onClick:()=>a("disconnect",c.id),children:["Disconnect ",cu[c.source]??c.source]})]})]},c.id)}),x.jsx("button",{type:"button",disabled:t||r,onClick:()=>n("sync"),children:"Sync now"}),x.jsxs("button",{type:"button",disabled:t,onClick:()=>n(r||!e.running?"start":"stop"),children:[r?"Start":e.running?"Stop":"Restart"," importer"]}),!e.running&&!r?x.jsx("button",{type:"button",disabled:t,onClick:()=>n("stop"),children:"Stop importer"}):null,!e.running&&!r?x.jsx("button",{type:"button",disabled:t,onClick:()=>n("install"),children:"Reinstall background service"}):null]})}function LG({title:e,inspection:t,busy:n,onSelect:a,onRefresh:o,onClose:r}){return x.jsxs("section",{className:"native-branch-picker","aria-label":"Choose Claude conversation branch",children:[x.jsx("strong",{children:e||"Claude conversation"}),x.jsx("p",{children:"This conversation has multiple branches. Choose the history to view. Each branch opens as a read-only snapshot."}),t.branches.map(s=>x.jsxs("button",{type:"button",disabled:n,onClick:()=>a({leafId:s.leafId,revision:t.revision}),children:[x.jsx("span",{children:s.title||"Branch without a text message"}),x.jsxs("small",{children:[s.messages," messages · ",s.updatedAt?new Date(s.updatedAt).toLocaleString():"Date unavailable"]}),x.jsx("code",{children:s.leafId})]},s.leafId)),x.jsxs("div",{children:[x.jsx("button",{type:"button",disabled:n,onClick:o,children:"Refresh branches"}),x.jsx("button",{type:"button",disabled:n,onClick:r,children:"Cancel"})]})]})}function qG({connection:e,selectedSessionId:t,onOpen:n}){const[a,o]=y.useState(null),[r,s]=y.useState(null),[c,m]=y.useState(null),[u,f]=y.useState(null),[g,S]=y.useState(null),[k,C]=y.useState(!1),[P,j]=y.useState(null),R=y.useCallback(async()=>{if(e){S("refresh");try{m(await z(e,"/v1/native-history/list",{method:"POST",body:"{}"})),f(null)}catch(E){f(E instanceof Error?E.message:"Local history is unavailable.")}finally{S(null)}}},[e]);y.useEffect(()=>{R()},[R]),y.useEffect(()=>{if(!k)return;const E=window.setInterval(()=>{document.hidden||R()},3e4);return()=>window.clearInterval(E)},[k,R]),y.useEffect(()=>{if(!e||!a||a.sessionId!==t)return;const E=window.setInterval(()=>{document.hidden||z(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:a.id})}).catch(D=>f(D.message))},1e4);return()=>window.clearInterval(E)},[e,a,t]);async function $(){if(!(!e||!c)){S("more");try{const E=await z(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({cursors:c.nextCursors})});m(D=>({...E,items:[...new Map([...D?.items??[],...E.items].map(U=>[U.id,U])).values()]}))}catch(E){f(E instanceof Error?E.message:"Could not load more conversations.")}finally{S(null)}}}async function O(E,D){if(e){S(E);try{if(!D){const L=await z(e,"/v1/native-history/branches",{method:"POST",body:JSON.stringify({id:E})});if(L.branches.length>1){j({id:E,inspection:L}),f(null);return}}const U=await z(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:E,branch:D})});o(D?null:{id:E,sessionId:U.id}),j(null),f(U.metadata?.nativeHistoryProjection&&!U.nativeAgent?typeof U.metadata.nativeReadOnlyReason=="string"?U.metadata.nativeReadOnlyReason:"Read-only history: the native source does not report its original working directory.":null),n(U)}catch(U){f(U instanceof Error?U.message:"Could not read this conversation.")}finally{S(null)}}}async function M(E){if(e){S(E);try{await z(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:E})}),await R()}catch(D){f(D instanceof Error?D.message:"Collector action failed.")}finally{S(null)}}}async function w(E,D){if(e){S(E);try{const U=await z(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:E,connectionId:D})});s(U.command),f(null)}catch(U){f(U instanceof Error?U.message:"Could not change Importer connection.")}finally{S(null)}}}async function A(E){if(e){S("connect");try{const D=await z(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:E?"reconnect":"connect",connectionId:E})});s(D.command),f(null)}catch(D){f(D instanceof Error?D.message:"Could not open Importer setup.")}finally{S(null)}}}return e?x.jsxs("section",{className:"sidebar-section native-conversations","aria-label":"Local agent conversations",children:[x.jsxs("div",{className:"sidebar-section-heading",children:[x.jsxs("button",{type:"button",onClick:()=>C(E=>!E),"aria-expanded":k,children:["Local agents",c?` (${c.items.length})`:""]}),x.jsx("button",{type:"button",className:"sidebar-icon","aria-label":"Refresh local agents",disabled:g!==null,onClick:()=>{R()},children:g==="refresh"?x.jsx(ty,{size:14}):x.jsx(AW,{size:14})})]}),r?x.jsx(DG,{connection:e,command:r,onClose:()=>{s(null),R()}}):null,k?x.jsxs(x.Fragment,{children:[x.jsx("button",{type:"button",disabled:g!==null,onClick:()=>{A()},children:"Import conversations"}),P?x.jsx(LG,{title:c?.items.find(E=>E.id===P.id)?.title??"",inspection:P.inspection,busy:g!==null,onSelect:E=>{O(P.id,E)},onRefresh:()=>{O(P.id)},onClose:()=>j(null)}):null,c?.items.map(E=>x.jsxs("button",{type:"button",className:"sidebar-row sidebar-task-row native-conversation-row",disabled:g!==null,title:`${E.source}
|
|
192
|
+
${E.cwd??"Working directory unavailable"}
|
|
193
|
+
${E.updatedAt}`,onClick:()=>{O(E.id)},children:[x.jsx("span",{children:E.title||"Untitled conversation"}),x.jsxs("small",{children:[E.source,E.cwd?"":" (read-only)"]})]},E.id)),c&&Object.keys(c.nextCursors).length?x.jsx("button",{type:"button",disabled:g!==null,onClick:()=>{$()},children:"Load more conversations"}):null,c&&c.items.length===0?x.jsx("p",{children:"No saved conversations found in configured source locations."}):null,c?.warnings.map(E=>x.jsxs("p",{children:[x.jsx(sm,{size:12,"aria-hidden":"true"})," ",E]},E)),c?.collector.connections.length?x.jsx(HG,{status:c.collector,busy:g!==null,onControl:E=>{M(E)},onConnectionControl:(E,D)=>{w(E,D)},onReconnect:E=>{A(E)}}):x.jsx("p",{children:"To upload these conversations, connect a source with the OpenPond Importer. Local history stays available without cloud sync."})]}):null,u?x.jsxs("p",{role:"status",children:[x.jsx(sm,{size:12,"aria-hidden":"true"})," ",u]}):null]}):null}const UG="/";function da(e){return`${UG}${e.replace(/^\.?\//,"")}`}const zG=da("openpond-icon.png"),BG=da("openpond-wordlogo-white.png"),zie=da("tutorials/what-is-an-openpond-agent-poster.png"),Bie=da("tutorials/what-is-an-openpond-agent.vtt"),Fie=da("tutorials/how-to-make-an-agent-poster.png"),Vie=da("tutorials/how-to-make-an-agent.vtt");function Kie(e){return da(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function Wie(e){return da(`tutorials/how-to-make-an-agent-${e}.vtt`)}const wx={github:da("connected-apps/github.svg"),google:da("connected-apps/google.svg"),microsoft_teams:da("connected-apps/microsoft.svg"),mcp:da("connected-apps/openpond-mcp.svg"),slack:da("connected-apps/slack.svg"),x:da("connected-apps/x.svg")};function Gie(e){return wx[e]??wx.mcp}function FG({value:e,onChange:t}){const[n,a]=y.useState(!1),o=y.useRef(null),r=y.useRef(null),s=y.useRef(null),c=y.useRef(null),m=kh.find(S=>S.value===e)??kh[0];y.useEffect(()=>{if(!n)return;const S=C=>{C.target instanceof Node&&!o.current?.contains(C.target)&&a(!1)},k=()=>a(!1);return window.addEventListener("pointerdown",S),window.addEventListener("blur",k),()=>{window.removeEventListener("pointerdown",S),window.removeEventListener("blur",k)}},[n]),y.useLayoutEffect(()=>{n&&c.current&&Ix(s.current,c.current),c.current=null},[n]);const u=S=>{if(n){Ix(s.current,S);return}c.current=S,a(!0)},f=S=>{S.key==="ArrowDown"?(S.preventDefault(),u("first")):S.key==="ArrowUp"&&(S.preventDefault(),u("last"))},g=S=>{const k=jP(s.current),C=k.findIndex(R=>R===document.activeElement);if(S.key==="Escape"){S.preventDefault(),a(!1),r.current?.focus();return}if(S.key==="Home"||S.key==="End"){S.preventDefault(),k[S.key==="Home"?0:k.length-1]?.focus();return}if(S.key!=="ArrowDown"&&S.key!=="ArrowUp")return;S.preventDefault();const P=S.key==="ArrowDown"?1:-1,j=C<0?0:(C+P+k.length)%k.length;k[j]?.focus()};return x.jsxs("div",{className:"sidebar-experience-menu",ref:o,children:[x.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:()=>{c.current=null,a(S=>!S)},onKeyDown:f,children:[x.jsx("img",{className:"sidebar-wordmark",src:BG,alt:""}),x.jsx("span",{className:"sidebar-experience-label",children:m.label}),x.jsx(yo,{size:13,"aria-hidden":"true"})]}),n?x.jsx("div",{ref:s,className:"sidebar-experience-popover",role:"menu","aria-label":"Choose product",onKeyDown:g,children:kh.map(S=>{const k=S.value===e;return x.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":k,className:k?"active":"","data-product-area":S.value,onClick:()=>{a(!1),k||t(S.value)},children:[x.jsxs("span",{children:[x.jsx("strong",{children:S.label}),x.jsx("small",{children:S.description})]}),k?x.jsx(Ci,{size:14,"aria-hidden":"true"}):null]},S.value)})}):null]})}function jP(e){return e?Array.from(e.querySelectorAll('[role="menuitemradio"]')):[]}function Ix(e,t){const n=jP(e);(t==="first"?n[0]:n.at(-1))?.focus()}function VG(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function KG(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"?VG(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 WG({account:e,open:t,organizations:n,selectedTeamId:a,onOpenActivity:o,onOpenChange:r,onOpenSettings:s,onSelectTeam:c,onLogOut:m}){const[u,f]=y.useState(null),[g,S]=y.useState(!1),k=y.useRef(null),C=y.useMemo(()=>KG(e),[e]),P=C.label.trim().slice(0,1).toUpperCase(),j=n.find(R=>R.teamId===a)??n[0]??null;return y.useEffect(()=>{if(!t)return;function R(O){k.current?.contains(O.target)||r(!1)}function $(O){O.key==="Escape"&&r(!1)}return document.addEventListener("pointerdown",R),document.addEventListener("keydown",$),()=>{document.removeEventListener("pointerdown",R),document.removeEventListener("keydown",$)}},[r,t]),x.jsxs("div",{className:"user-auth-footer",ref:k,children:[x.jsxs("button",{type:"button",className:`user-auth-trigger ${t?"active":""}`,"aria-haspopup":"menu","aria-expanded":t,"aria-label":`${C.label} account menu`,onClick:()=>r(!t),children:[x.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:C.image?x.jsx("img",{src:C.image,alt:""}):P?x.jsx("span",{children:P}):x.jsx(lx,{size:16})}),x.jsx("span",{className:"user-auth-name",children:C.label})]}),t?x.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[x.jsxs("div",{className:"user-auth-menu-header",children:[x.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:C.image?x.jsx("img",{src:C.image,alt:""}):P?x.jsx("span",{children:P}):x.jsx(lx,{size:17})}),x.jsx("span",{className:"user-auth-menu-identity",children:x.jsx("strong",{children:C.label})})]}),n.length>0&&c?x.jsxs("label",{className:"user-auth-team-picker",children:[x.jsx(aP,{size:15,"aria-hidden":"true"}),x.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),x.jsx("select",{"aria-label":"Active team",disabled:u!==null,value:j?.teamId??"",onChange:async R=>{const $=R.currentTarget.value;f($);try{await c($)}catch{}finally{f(null)}},children:n.map(R=>x.jsx("option",{value:R.teamId,children:R.displayName},R.teamId))})]}):null,x.jsx("div",{className:"user-auth-menu-divider"}),o?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),o()},children:[x.jsx(YR,{size:15}),x.jsx("span",{children:"Activity"})]}):null,x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{r(!1),s()},children:[x.jsx(nP,{size:15}),x.jsx("span",{children:"Settings"})]}),e?.state==="signed_in"&&m?x.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:g,onClick:async()=>{S(!0);try{await m(),r(!1)}catch{}finally{S(!1)}},children:[x.jsx(RW,{size:15}),x.jsx("span",{children:g?"Logging out…":"Log out"})]}):null]}):null]})}function _x(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 GG(e,t){const n=_x(e),a=_x(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 MP(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function JG(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function ZG(e,t,n){const a=MP(t),o=JG(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 YG(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(!GG(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 u=m;return typeof u.name!="string"||typeof u.browser_download_url!="string"?[]:[{name:u.name,downloadUrl:u.browser_download_url}]}),c=ZG(s,e.platform,e.arch);return!c||!o?null:{version:a,releaseUrl:o,assetName:c.name,downloadUrl:c.downloadUrl}}const QG=3600*1e3,XG="https://api.github.com/repos/openpond/openpond/releases/latest";function e7(e){const[t,n]=y.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",o=e.platform??"",r=e.arch??"",s=e.enabled&&!!a&&!!MP(o);return y.useEffect(()=>{if(!s){n({status:"idle",update:null,lastCheckedAt:null});return}let c=!1;async function m(){n(f=>({...f,status:f.update?"available":"checking"}));try{const f=await fetch(XG,{headers:{Accept:"application/vnd.github+json"}});if(!f.ok)throw new Error(`GitHub release check failed: ${f.status}`);const g=await f.json(),S=YG({payload:g,currentVersion:a,platform:o,arch:r});if(c)return;n({status:S?"available":"current",update:S,lastCheckedAt:Date.now()})}catch{if(c)return;n(f=>({status:f.update?"available":"error",update:f.update,lastCheckedAt:Date.now()}))}}m();const u=window.setInterval(()=>{m()},QG);return()=>{c=!0,window.clearInterval(u)}},[r,a,s,o]),t}const OP="openpond.sidebar.continuous-learning.dismissed.v1";function Cx(e=$P()){if(!e)return!1;try{return e.getItem(OP)==="true"}catch{return!1}}function t7(e=$P()){if(e)try{e.setItem(OP,"true")}catch{}}function $P(){return typeof window>"u"?null:kd}function n7({connection:e,onOpenSettings:t}){const[n,a]=y.useState(null),[o,r]=y.useState(Cx);xd(()=>r(Cx()));const s=y.useCallback(async()=>{if(!e){a(null);return}try{a(await Q.harnessHistory(e))}catch{a(null)}},[e]);if(y.useEffect(()=>{s()},[s]),o||!e||!n?.workspace)return null;const c=n.evaluationReviewSchedule,m=c.activityEnabled?`${c.activityBatchSize} outcomes${c.enabled?` + ${c.cadence}`:""}`:c.enabled?c.cadence:"Manual";return x.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[x.jsxs("header",{children:[x.jsx("strong",{children:"Continuous learning"}),x.jsxs("div",{className:"sidebar-learning-notice-actions",children:[x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:x.jsx(nP,{size:14})}),x.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),t7()},type:"button",children:x.jsx(yd,{size:14})})]})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Refiner"}),x.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),x.jsxs("div",{className:"sidebar-learning-status",children:[x.jsx("strong",{children:"Continuous Review"}),x.jsx("span",{children:m})]})]})}function a7(e){const[t,n]=y.useState(!1),{beginNewChat:a,arch:o,currentVersion:r,experience:s,productArea:c,onProductAreaChange:m,onSidebarResizeStart:u,platform:f,setSectionMenuOpen:g,setSelectedAppId:S,setSelectedProjectId:k,setSelectedSessionId:C,setSidebarOpen:P,setView:j,view:R,modelProjects:$,modelTrainingActivityByProjectId:O}=e,M=y.useCallback(D=>{n(!1),g(D)},[g]),w=y.useCallback(D=>{n(D),D&&g(null)},[g]),A=e7({currentVersion:r,platform:f,arch:o,enabled:lp()}),E=A.status==="available"?A.update:null;return x.jsxs("aside",{className:"sidebar",children:[x.jsxs("div",{className:"sidebar-toolbar",children:[x.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>P(!1),children:x.jsx(tP,{size:16})}),x.jsx(FG,{value:c,onChange:m}),E&&x.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${E.version}: ${E.assetName}`,"aria-label":`Download OpenPond ${E.version}`,onClick:()=>{i7(E.downloadUrl)},children:[x.jsx(X9,{size:14}),x.jsx("span",{children:"Update"})]})]}),c!=="chat"?null:x.jsx(n8,{experience:s,beginNewChat:a}),x.jsxs("div",{className:"sidebar-scroll",children:[c==="chat"&&e.account?.activeProfile&&e.onOpenPonder?x.jsxs("button",{type:"button",className:"sidebar-ponder-entry",onClick:e.onOpenPonder,children:[x.jsx("span",{"aria-hidden":"true",children:"✦"})," Ponder Pal"]}):null,x.jsx(a8,{productArea:c,setSectionMenuOpen:M,setSelectedAppId:S,setSelectedProjectId:k,setSelectedSessionId:C,setView:j,view:R,modelProjects:$,modelTrainingActivityByProjectId:O}),c!=="chat"?null:x.jsx($G,{...e,setSectionMenuOpen:M}),c==="chat"?x.jsx(qG,{selectedSessionId:e.selectedSessionId,connection:e.connection,onOpen:D=>{C(D.id),j("chat")}}):null]}),x.jsxs("div",{className:"sidebar-bottom-stack",children:[c!=="chat"?null:x.jsx(n7,{connection:e.connection,onOpenSettings:()=>{g(null),ln({kind:"settings",section:"harness"})}}),x.jsxs("div",{className:"sidebar-footer-row",children:[x.jsx(WG,{account:e.account,open:t,organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onOpenChange:w,onOpenActivity:()=>{g(null),ln({kind:"settings",section:"usage"})},onOpenSettings:()=>{g(null),ln({kind:"settings",section:"account"})},onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut}),x.jsx(i8,{setSectionMenuOpen:M,setSelectedAppId:S,setSelectedProjectId:k,setSelectedSessionId:C,setView:j,view:R})]})]}),x.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:u})]})}async function i7(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const o7=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function NP(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?DP(a)?"Couldn’t connect to OpenPond.":a:t}function DP(e){const t=e.trim();return o7.some(n=>n.test(t))}const HP=y.createContext(null);function Rx({children:e,showToast:t}){return x.jsx(HP.Provider,{value:t,children:e})}function r7(){return y.useContext(HP)}function Px(e,t={}){const n=r7(),a=y.useRef(null),o=t.enabled??!0,r=t.fallback??"Something went wrong.",s=t.prefix?.trim()??"",c=e==null||e===""?null:`${s}${s?": ":""}${NP(e,r)}`;y.useEffect(()=>{if(!o||!c){a.current=null;return}a.current!==c&&(a.current=c,n?.(c,"error"))},[o,c,n])}function s7({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(Px(e?.previewError,{prefix:"Upload preview"}),Px(e?.error,{prefix:"Cloud setup"}),!e)return null;const o=e.status==="uploading",r=e.status==="ready",s=e.status==="error",c=e.projectKind==="cloud",m=e.preview??null;return x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:x.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[x.jsx("button",{className:"git-dialog-close",disabled:o,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:x.jsx(yd,{size:14})}),x.jsx("div",{className:"git-dialog-icon",children:r?x.jsx(Pu,{size:18}):x.jsx(op,{size:18})}),x.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),x.jsx("p",{children:r?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":c?"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."}),x.jsxs("div",{className:"cloud-setup-summary",children:[x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Project"}),x.jsx("strong",{children:e.projectName})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Source"}),x.jsx("strong",{children:c?"OpenPond Git":"Local project upload"})]}),x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Branch"}),x.jsx("strong",{children:m?.branch??e.branch??"main"})]}),!c&&x.jsxs("div",{className:"git-dialog-row",children:[x.jsx("span",{children:"Cloud project"}),x.jsx("strong",{children:m?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!c&&x.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Calculating upload preview"}),x.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Preview unavailable"}),x.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):m?x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:m.initializedEmptyProject?"Will initialize an empty project":`Will upload ${m.fileCount} files`}),x.jsx("span",{children:Ax({byteCount:m.byteCount,skippedCount:m.skippedCount,headCommit:m.headCommit,targetProjectName:m.targetProjectName})})]}):x.jsxs(x.Fragment,{children:[x.jsx("strong",{children:"Upload preview pending"}),x.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),o&&x.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[x.jsx(ty,{className:"cloud-setup-spinner",size:16}),x.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&e.upload&&x.jsxs("div",{className:"cloud-setup-upload-result",children:[x.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),x.jsx("span",{children:Ax({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&e.setupUrl&&x.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?x.jsxs("span",{children:["Your repo is ready here:"," ",x.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:u=>Ah(u,e.projectUrl,n,{newTab:!0}),children:["Project page",x.jsx(Sh,{size:13})]})]}):x.jsx("span",{children:"Your repo is ready. Next step:"}),x.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>Ah(u,e.setupUrl,n),children:["Setup the Cloud sandbox",x.jsx(Sh,{size:13})]})]}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{className:"git-dialog-secondary",disabled:o,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?x.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:u=>Ah(u,e.setupUrl,n),children:["Open setup",x.jsx(Sh,{size:13})]}):null:x.jsx("button",{className:"git-dialog-primary",disabled:o,type:"button",onClick:a,children:o?"Uploading":s?"Try again":c?"Show setup link":"Upload source"})]})]})})}function Ah(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function l7(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 Ax({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const o=[l7(e),`${t} skipped`],r=c7(n);return r&&o.push(`local ${r}`),o.push(a),o.join(" · ")}function c7(e){const t=e?.trim();return t?t.slice(0,7):null}const d7=y.lazy(()=>Go(()=>import("./CommandMenu-D-M-xomh.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.CommandMenu}))),u7=y.lazy(()=>Go(()=>import("./SettingsView-0KMs-r2I.js"),__vite__mapDeps([6,1,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23])).then(e=>({default:e.SettingsView}))),m7=y.lazy(()=>Go(()=>import("./NewProjectDialog-CS6sw2oD.js"),__vite__mapDeps([24,1,2,9,15,25])).then(e=>({default:e.NewProjectDialog}))),p7=y.lazy(()=>Go(()=>import("./WorkspaceGitDialogs-CBarJYF-.js"),__vite__mapDeps([26,1,2,13,14,27,23])).then(e=>({default:e.CommitDialog}))),f7=y.lazy(()=>Go(()=>import("./WorkspaceGitDialogs-CBarJYF-.js"),__vite__mapDeps([26,1,2,13,14,27,23])).then(e=>({default:e.BranchDialog})));function h7({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:r,onToast:s,onBack:c,onOpenSourceSession:m,onStartRefinerAuthoring:u,onAcceptEvaluationReview:f,onOpenSkill:g,onOpenExtension:S,teamChatCurrentUserId:k,teamChatEnabled:C,teamChatNotificationMode:P,teamChatThreads:j,onTeamChatNotificationModeChange:R,onTeamChatThreadMuteChange:$,diffPanelWidth:O,diffPanelResizing:M,diffPanelExpanded:w,onDiffPanelResizeStart:A,onDiffPanelExpandedChange:E}){return x.jsx(y.Suspense,{fallback:null,children:x.jsx(u7,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:o,onError:r,onToast:s,onBack:c,onOpenSourceSession:m,onStartRefinerAuthoring:u,onAcceptEvaluationReview:f,onOpenSkill:g,onOpenExtension:S,teamChatCurrentUserId:k,teamChatEnabled:C,teamChatNotificationMode:P,teamChatThreads:j,onTeamChatNotificationModeChange:R,onTeamChatThreadMuteChange:$,diffPanelWidth:O,diffPanelResizing:M,diffPanelExpanded:w,onDiffPanelResizeStart:A,onDiffPanelExpandedChange:E})})}function g7({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:o,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:c,canPublishOpenPondProject:m,expandProject:u,newProjectBusy:f,newProjectDialogOpen:g,newProjectDirectory:S,newProjectMode:k,newProjectName:C,newProjectPath:P,projectRows:j,query:R,searchOpen:$,visibleWorkspaceDiff:O,visibleWorkspaceState:M,workspaceBusy:w,appDispatch:A,beginNewChat:E,openDefaultsSettingsFromBranchDialog:D,setBranchDialogName:U,setBranchDialogOpen:L,setCommitDialogOpen:J,setCommitDraft:X,setCommitIncludeUnstaged:de,setCommitMessage:Me,setCommitNextStep:Ie,setNewProjectDialogOpen:ne,setNewProjectName:je,setNewProjectPath:Se,setQuery:oe,setSearchOpen:be,submitCommitDialog:re,submitCreateWorkspaceBranch:ue,submitNewProjectDialog:ke}){return x.jsxs(x.Fragment,{children:[$&&x.jsx(y.Suspense,{fallback:null,children:x.jsx(d7,{open:$,query:R,projects:j,sessions:e,onQueryChange:oe,onClose:()=>{be(!1),oe("")},onNewChat:()=>{be(!1),oe(""),E()},onOpenProject:Le=>{A({type:"selectProject",projectId:Le.id}),A({type:"patch",patch:{searchOpen:!1,query:""}}),u(Le.id)},onOpenSession:Le=>{A({type:"selectSession",sessionId:Le.id,appId:Le.appId,projectId:Le.workspaceKind==="local_project"&&Le.workspaceId?It("local",Le.workspaceId):null}),A({type:"patch",patch:{searchOpen:!1,query:""}})}})}),g&&x.jsx(y.Suspense,{fallback:null,children:x.jsx(m7,{open:g,mode:k,name:C,path:P,directory:S,busy:f,onNameChange:je,onPathChange:Se,onClose:()=>{f||ne(!1)},onSubmit:ke})}),a&&x.jsx(y.Suspense,{fallback:null,children:x.jsx(p7,{open:a,branch:M?.currentBranch??null,filesChanged:O?.filesChanged??M?.changedFilesCount??0,additions:O?.additions??0,deletions:O?.deletions??0,message:s,includeUnstaged:r,nextStep:c,draft:o,busy:w,canPush:!!M?.remoteUrl,canPublish:m,onMessageChange:Me,onIncludeUnstagedChange:de,onNextStepChange:Ie,onDraftChange:X,onClose:()=>{w||J(!1)},onSubmit:re})}),n&&x.jsx(y.Suspense,{fallback:null,children:x.jsx(f7,{open:n,branchName:t,busy:w,onBranchNameChange:U,onSetPrefix:D,onClose:()=>{w||L(!1)},onSubmit:ue})})]})}function LP({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return x.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[x.jsx("span",{className:"app-toast-message",children:e.message}),n&&x.jsx("div",{className:"app-toast-actions",children:x.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}async function du(e,t,n){if(t.scope!==e.scope)throw new Error("Review workspace changed. Reload the assignment.");return z(e.connection,`/v1/human-review?location=${e.location}`,{method:"POST",body:JSON.stringify(BU.parse(t)),signal:n})}function Tx(e,t,n){const a=YI.parse(e);if(a.scope!==t.scope||a.id!==n)throw new Error("Review response identity differs from the requested assignment.");return a}const v7={inbox:async(e,t,n)=>b7(await du(e,{...t,endpoint:"inbox",scope:e.scope},n),e),get:async(e,t,n)=>Tx(await du(e,{endpoint:"get",scope:e.scope,id:t},n),e,t),inspect:async(e,t,n,a,o)=>y7(await du(e,{endpoint:"inspect",scope:e.scope,id:t,...n===void 0?{}:{slot:n},...a?{afterId:a}:{}},o),t),command:async(e,t)=>Tx(await du(e,{endpoint:"command",scope:e.scope,command:t}),e,t.id)};function b7(e,t){const n=TU.parse(e);if(n.items.some(a=>a.scope!==t.scope))throw new Error("Inbox response belongs to another workspace.");return n}function y7(e,t){const n=FU.parse(e);if(n.some(a=>a.reviewId!==t))throw new Error("Evidence response belongs to another assignment.");return n}function S7({context:e,onOpen:t}){const[n,a]=y.useState(null);return y.useEffect(()=>{const o=new AbortController;let r=0;async function s(){const m=++r;try{const u=await v7.inbox(e,{view:"mine",status:"active",limit:1},o.signal);!o.signal.aborted&&m===r&&a(u.actionCount)}catch{!o.signal.aborted&&m===r&&a(null)}}a(null),s();const c=window.setInterval(()=>{document.visibilityState==="visible"&&s()},15e3);return window.addEventListener("human-review-changed",s),()=>{o.abort(),window.clearInterval(c),window.removeEventListener("human-review-changed",s)}},[e.scope,e.actorId,e.location,e.connection]),x.jsxs("button",{type:"button",className:"evaluation-panel-icon","aria-label":n?`Inbox, ${n} actions`:"Inbox",onClick:t,children:[x.jsx(oP,{size:16}),n?x.jsx("span",{children:n}):null]})}function x7({summary:e,scopeKey:t,loading:n,error:a,onRetry:o,onSelect:r}){const[s,c]=y.useState(!1),m=y.useRef(null),u=e?.scopeKey===t?e:null,f=!!(u&&u.counts.training+u.counts.experiments>0),g=k=>new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(k),S=a?u?"Activity reconnecting":"Activity unavailable":n&&!u?"Checking activity":f?"Active work":"No active work";return y.useEffect(()=>{if(!s)return;const k=P=>{m.current?.contains(P.target)||c(!1)},C=P=>{P.key==="Escape"&&(c(!1),m.current?.querySelector("button")?.focus())};return document.addEventListener("pointerdown",k),document.addEventListener("keydown",C),()=>{document.removeEventListener("pointerdown",k),document.removeEventListener("keydown",C)}},[s]),x.jsxs("div",{className:"execution-activity",ref:m,children:[x.jsxs("button",{className:"execution-activity-trigger",type:"button","aria-expanded":s,"aria-controls":"execution-activity-list","aria-label":`${S}${u?`: ${u.counts.training} training, ${u.counts.experiments} experiments`:""}`,onClick:()=>c(k=>!k),children:[x.jsx("span",{"aria-hidden":"true",className:`execution-activity-ring${f?" is-active":""}`}),u?x.jsxs(x.Fragment,{children:[x.jsxs("span",{className:"execution-activity-training",children:[g(u.counts.training)," training"]}),x.jsxs("span",{className:"execution-activity-experiments",children:[g(u.counts.experiments)," experiments"]})]}):x.jsx("span",{children:S})]}),x.jsxs("div",{id:"execution-activity-list",className:"execution-activity-list",hidden:!s,children:[x.jsx("p",{className:"execution-activity-scope",children:"Activity in the selected workspace and Project"}),a?x.jsxs("p",{role:"status",children:[S,". ",x.jsx("button",{type:"button",onClick:o,children:"Retry"})]}):null,x.jsx("ul",{children:u?.items.map(k=>x.jsx("li",{children:x.jsxs("button",{type:"button",onClick:()=>r(k),children:[x.jsx("span",{children:k.name}),x.jsxs("small",{children:[k.kind==="training"?"Training":"Experiment"," ",k.phase.replaceAll("_"," ")]})]})},`${k.kind}:${k.location}:${k.id}`))}),u?.items.length?null:x.jsx("p",{role:"status",children:S}),u?.hasMore?x.jsx("p",{children:"Counts include all active work."}):null]})]})}function k7({connection:e,teamId:t,actorId:n,projectId:a}){const o=JSON.stringify([t,n,a]),r=iw({queryKey:["workspace-execution-activity",e?.serverUrl,o],enabled:!!(e&&t&&n),staleTime:4e3,refetchInterval:8e3,queryFn:({signal:c})=>z(e,`/v1/training/execution-activity?${new URLSearchParams({teamId:t,...a?{projectId:a}:{}})}`,{signal:c})});if(!e||!t||!n)return null;const s=()=>{fo(ma("inbox",null,{area:"console",projectId:a}))};return x.jsxs(x.Fragment,{children:[x.jsx(x7,{summary:r.data??null,scopeKey:o,loading:r.isPending,error:r.error?.message??null,onRetry:()=>{r.refetch()},onSelect:c=>{if(c.kind==="experiment"){const m=c.href?Dc(new URL(c.href,"https://native.openpond.invalid")):null;fo(m?{...m,executionLocation:c.location}:ma("experiments",null,{area:"console",resourceId:c.id,projectId:a,executionLocation:c.location}))}else{const m=c.href?Dc(new URL(c.href,"https://native.openpond.invalid")):null;fo(c.location==="local"&&m?m:ma("runs",null,{resourceId:`hosted-run:${c.id}`}))}}}),x.jsx(S7,{context:{connection:e,scope:t,actorId:n,location:"hosted"},onOpen:s})]})}const wd=y.createContext(null);function w7({children:e}){const[t,n]=y.useState(null),[a,o]=y.useState(null),[r,s]=y.useState(null),c=y.useMemo(()=>({title:t,actions:a,activity:r,setTitle:n,setActions:o,setActivity:s}),[t,a,r]);return x.jsx(wd.Provider,{value:c,children:e})}function Jie({children:e}){return x.jsx(wd.Provider,{value:null,children:e})}function I7({children:e,className:t=""}){const n=y.useContext(wd);return x.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?x.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function _7({className:e=""}){const t=y.useContext(wd);return x.jsx("div",{ref:t?.setActions,className:e})}function Zie({title:e,actions:t,fallback:n,children:a}){const o=y.useContext(wd);return o?x.jsxs(x.Fragment,{children:[o.title?mm.createPortal(x.jsx("div",{className:"page-chrome-title",children:e}),o.title):null,o.actions&&t?mm.createPortal(t,o.actions):null,a]}):n??x.jsxs("header",{children:[e,t]})}async function C7(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 R7({activeView:e,onDiscoverCommunities:t,onOpenTeamChat:n}){return x.jsxs("div",{className:"titlebar-collaboration-actions",children:[x.jsx("button",{type:"button",className:`titlebar-icon${e==="team"?" active":""}`,"aria-label":"Team chat",title:"Team chat",onClick:n,children:x.jsx(rp,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon${e==="community"?" active":""}`,"aria-label":"Discover communities",title:"Discover communities",onClick:t,children:x.jsx(eP,{size:16})})]})}const P7=y.lazy(()=>Go(()=>import("./WorkspaceEnvironmentMenu-DeODKxvW.js"),__vite__mapDeps([28,1,2,19,25,10,14,29,27,30])).then(e=>({default:e.WorkspaceEnvironmentMenu})));function A7({sidebarOpen:e,title:t,conversationId:n,breadcrumbs:a,backAction:o,workspaceName:r,workspaceId:s,busy:c,workspaceState:m,workspaceKind:u,selectedApp:f,selectedProject:g,workspaceDiff:S,managedWorkspace:k,workspaceBusy:C,defaultTeamId:P,activityActorId:j,activityProjectId:R,showDiffControls:$,diffPanelOpen:O,terminalOpen:M,rightSidebarAvailable:w=!1,rightSidebarOpen:A=!1,onToggleDiffPanel:E,onToggleRightSidebar:D,onOpenSearch:U,onToggleTerminal:L,onRunTerminalCommand:J,onWorkspaceToolAction:X,onOpenCommitDialog:de,onWorkspaceBranchChange:Me,onWorkspaceBranchCreate:Ie,connection:ne,onBootstrap:je,onOpenSandboxWorkspace:Se,onShowSidebar:oe,onOpenTeamChat:be,onDiscoverCommunities:re,collaborationView:ue=null,platform:ke,showWorkspaceControls:Le=!0}){const we=S?.filesChanged??0,le=lp()&&!iy(ke),xe=!!(be||re)||Le||w||le,[Ue,Ze]=y.useState(null);y.useEffect(()=>{if(!Ue)return;const Ne=()=>Ze(null);return window.addEventListener("pointerdown",Ne),window.addEventListener("blur",Ne),window.addEventListener("resize",Ne),()=>{window.removeEventListener("pointerdown",Ne),window.removeEventListener("blur",Ne),window.removeEventListener("resize",Ne)}},[Ue]);const it=Ne=>{Ne.preventDefault(),Ne.stopPropagation();const We=190,qe=n?76:42;Ze({x:Math.min(Ne.clientX,window.innerWidth-We-8),y:Math.min(Ne.clientY,window.innerHeight-qe-8)})},at=Ne=>{C7(Ne),Ze(null)};return x.jsxs("header",{className:"app-titlebar",children:[x.jsxs("div",{className:"titlebar-left",children:[!e&&x.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:oe,children:x.jsx(tP,{size:16})}),o?x.jsx("button",{className:"titlebar-icon",type:"button","aria-label":o.label,title:o.label,onClick:o.onSelect,children:x.jsx(N9,{size:16})}):null,x.jsx(I7,{children:a?.length?x.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((Ne,We)=>{const qe=We===a.length-1;return x.jsxs("div",{className:"titlebar-breadcrumb-item",children:[Ne.onSelect&&!qe?x.jsx("button",{type:"button",onClick:Ne.onSelect,children:Ne.label}):x.jsx("strong",{children:Ne.label}),!qe&&x.jsx(Mr,{size:14})]},`${Ne.label}-${We}`)})}):x.jsxs("div",{className:"titlebar-title",children:[x.jsx("strong",{className:"titlebar-copy-target",title:"Double-click to select; right-click for copy options",onContextMenu:it,children:t}),r&&x.jsx("span",{children:r})]})})]}),xe&&x.jsxs("div",{className:"titlebar-right",children:[x.jsx(_7,{className:"page-chrome-actions"}),x.jsx(k7,{connection:ne,teamId:P??null,actorId:j??null,projectId:R??null}),x.jsx(R7,{activeView:ue,onDiscoverCommunities:re,onOpenTeamChat:be}),Le&&x.jsxs("div",{className:"titlebar-actions",children:[x.jsx(y.Suspense,{fallback:null,children:x.jsx(P7,{mode:"topbar",busy:c,workspaceState:m,workspaceId:s,workspaceKind:u,selectedApp:f,selectedProject:g,workspaceBusy:C,defaultTeamId:P,workspaceDiff:S,managedWorkspace:k,showDiffControls:$,diffPanelOpen:O,onToggleDiffPanel:E,onRunTerminalCommand:J,onWorkspaceToolAction:X,onOpenCommitDialog:de,onWorkspaceBranchChange:Me,onWorkspaceBranchCreate:Ie,connection:ne,onBootstrap:je,onOpenSandboxWorkspace:Se})}),x.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:U,children:x.jsx(EW,{size:16})}),x.jsx("button",{type:"button",className:`titlebar-icon ${M?"active":""}`,title:`${M?"Hide":"Show"} terminal`,"aria-label":`${M?"Hide":"Show"} terminal`,"aria-pressed":M,onClick:L,children:x.jsx(iP,{size:16})}),$&&x.jsx("button",{type:"button",className:`topbar-diff-button ${A?"active":""}`,title:`${A?"Hide":"Show"} sidebar${we?`, ${we} changed files`:""}`,"aria-label":`${A?"Hide":"Show"} sidebar`,"aria-pressed":A,onClick:E,children:x.jsx(Tg,{size:16})})]}),w&&D&&!$?x.jsx("div",{className:"titlebar-actions",children:x.jsx("button",{type:"button",className:`topbar-diff-button ${A?"active":""}`,title:`${A?"Hide":"Show"} sidebar`,"aria-label":`${A?"Hide":"Show"} sidebar`,"aria-pressed":A,onClick:D,children:x.jsx(Tg,{size:16})})}):null,x.jsx(LW,{platform:ke})]}),Ue&&x.jsxs("div",{className:"titlebar-copy-menu",role:"menu","aria-label":"Conversation title actions",style:{left:Ue.x,top:Ue.y},onPointerDown:Ne=>Ne.stopPropagation(),children:[x.jsx("button",{type:"button",role:"menuitem",onClick:()=>at(t),children:"Copy title"}),n&&x.jsx("button",{type:"button",role:"menuitem",onClick:()=>at(n),children:"Copy conversation ID"})]})]})}function T7(){const[e,t]=y.useState(null),n=y.useRef(null),a=y.useCallback(r=>new Promise(s=>{n.current?.resolve(!1);const c={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:s};n.current=c,t(c)}),[]),o=y.useCallback(r=>{const s=n.current;n.current=null,t(null),s?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:o}}function E7({state:e,onResolve:t}){const n=y.useId(),a=y.useId();if(y.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 x.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:x.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:r=>r.stopPropagation(),children:[x.jsx("h2",{id:n,children:e.title}),x.jsx("p",{id:a,children:e.body}),x.jsxs("div",{className:"git-dialog-footer",children:[x.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),x.jsx("button",{type:"button",className:o,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function j7(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=T7();return{confirmProjectAction:y.useCallback(o=>e({tone:"danger",...o}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function M7({state:e,onResolve:t}){return x.jsx(E7,{state:e,onResolve:t})}const fm=new Map,O7=(e,t,n)=>{const a=fm.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,fm.set(e,a)};function $7({children:e,id:t}){return x.jsx(y.Profiler,{id:t,onRender:O7,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...fm.entries()].map(([e,t])=>[e,{...t}])),reset:()=>fm.clear()});const N7=y.lazy(()=>Go(()=>import("./MainPane-DJcd4tPk.js").then(e=>e.o),__vite__mapDeps([31,1,2,13,32,8,29,9,10,33])).then(e=>({default:e.MainPane})));function D7({className:e,style:t,sidebar:n,topBar:a,mainPane:o,cloudSetup:r,projectConfirm:s,lazyPanels:c,toast:m}){return x.jsx(w7,{children:x.jsxs("div",{className:e,style:t,children:[x.jsx($7,{id:"sidebar",children:x.jsx(a7,{...n})}),x.jsxs("div",{className:"content-shell",children:[x.jsx(A7,{...a}),x.jsx(y.Suspense,{fallback:x.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:x.jsx(N7,{...o})})]}),x.jsx(s7,{...r}),x.jsx(M7,{...s}),x.jsx(g7,{...c}),x.jsx(LP,{...m})]})})}function H7({settings:e,toast:t}){return x.jsxs(x.Fragment,{children:[x.jsx(h7,{...e}),x.jsx(LP,{...t})]})}const Ou="OpenPond".split("");function L7({visibleLetterCount:e=Ou.length}){const t=Ou.slice(0,Math.max(0,Math.min(e,Ou.length)));return x.jsxs("div",{className:"app-splash-lockup",children:[x.jsx("div",{className:"app-splash-mark",children:x.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:zG})}),x.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>x.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const Th=Ou.length,q7=520,U7=240;function Ex(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function z7({startup:e}){const[t,n]=y.useState(()=>Ex()?Th:0);return y.useEffect(()=>{if(Ex()){n(Th);return}const a=Array.from({length:Th},(o,r)=>window.setTimeout(()=>n(r+1),q7+U7*r));return()=>{a.forEach(o=>window.clearTimeout(o))}},[]),x.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[x.jsx(L7,{visibleLetterCount:t}),x.jsx("span",{className:"app-splash-status",children:e.label})]})}const Sy=5e3;function to(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 eo(e,t,n=Sy){return $u(to(e,t),n)}function $u(e,t=Sy){return e.length<=t?e:e.slice(e.length-t)}function B7(e,t,n){return n.length===0?e:{...e,[t]:to(e[t]??[],n)}}function F7(e,t){if(t.length===0)return $u(e);if(e.length===0)return $u(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 $u([...n.values()].sort((o,r)=>K7(o,r)).map(({event:o})=>o))}function hm(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 V7(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function K7(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 jx(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 W7(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function Mx(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 G7(e){return e==="codex"}function J7(e){return e==="openpond"}function qP(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=XN.safeParse(n.data);if(a.success)return a.data}return null}function UP(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=`${jx(n)} / ${jx(a)} tokens used`;return{usedTokens:n,maxTokens:a,percent:o,summary:r,tokensLabel:s,detail:Mx(e.preferences,o),tooltip:`Context window: ${r} ${s}. ${Mx(e.preferences,o)}`,tone:W7(o)}}if(G7(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(!J7(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 xy(e){let t=!1;const n=zP(e);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(Z7(o)){t=!0;continue}const r=nl(o?.data);if(!(o?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const s=ky(nl(r.goal),sa(r.provider),n);if(s){const c=Bc(s);return t&&c.tone==="active"?null:c}}if(r.kind==="goal_context"){const s=FP(o.output??"",sa(r.provider)??"codex",n);if(s){const c=Bc(s);return t&&c.tone==="active"?null:c}}}}return null}function gm(e){const t=zP(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],o=nl(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=ky(nl(o.goal),sa(o.provider),t);if(!r)continue;const s=Bc(r);return s.tone==="active"?s:null}if(o.kind==="goal_context"){const r=FP(a.output??"",sa(o.provider)??"codex",t);if(!r)continue;const s=Bc(r);return s.tone==="active"?s:null}}}return null}function Eh(e){const t=nl(nl(e)?.codexGoalRuntime),n=ky(t,sa(t?.provider)??"codex");if(!n)return null;const a=Bc(n);return a.tone==="active"?a:null}function Z7(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Bc(e){const t=VP(e.status),n=GP(e.timeUsedSeconds),a=`Goal ${n}`,o=e.tokensUsed===null?null:e.tokenBudget===null?`${jh(e.tokensUsed)} tokens`:`${jh(e.tokensUsed)} / ${jh(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: ${JP(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function Y7(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=BP(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,o=GP(a);return{...e,timeUsedSeconds:a,timeLabel:o,label:`Goal ${o}`,tooltip:`Goal runtime: ${JP(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function ky(e,t=null,n=null){if(!e)return null;const a=sa(e.objective)??"Active goal",o=sa(e.status)??"active";if((Ug(t)??Ug(sa(e.provider)))!=="codex")return null;const s=n??sa(e.updatedAt)??sa(e.updated_at)??null,c=vs(e.timeUsedSeconds)??vs(e.time_used_seconds)??0,m=sa(e.activeSinceAt)??sa(e.active_since_at),u=VP(o).tone==="active"?BP(m??sa(e.createdAt)??sa(e.created_at),s):0,f=m?c+u:Math.max(c,u),g=vs(e.tokensUsed)??vs(e.tokens_used),S=vs(e.tokenBudget)??vs(e.token_budget);return{objective:a,status:o,statusLabel:WP(o),timeUsedSeconds:Math.max(0,Math.floor(f)),tokensUsed:g===null?null:Math.max(0,Math.floor(g)),tokenBudget:S===null?null:Math.max(0,Math.floor(S)),observedAt:s}}function zP(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 BP(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 FP(e,t=null,n=null){if(!e.trim()||Ug(t)!=="codex")return null;const a=KP(e,"Status")??"active",o=Vl(e,"Tokens used"),r=Vl(e,"Token budget"),s=Vl(e,"Time used seconds")??Vl(e,"Time spent pursuing goal")??Vl(e,"Elapsed seconds")??0;return{objective:Ox(e,"objective")??Ox(e,"untrusted_objective")??"Active goal",status:a,statusLabel:WP(a),timeUsedSeconds:Math.max(0,Math.floor(s)),tokensUsed:o,tokenBudget:r,observedAt:n}}function VP(e){switch(Q7(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 Q7(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function KP(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function Vl(e,t){const n=KP(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 Ox(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function WP(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function GP(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 JP(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 jh(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${$x(n,2)}M`:n<100?`${$x(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 $x(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function nl(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function sa(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ug(e){return e?.trim().toLowerCase()||null}function vs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const X7=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),eJ=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function zg(e){const t=ZP(e);return t?iJ(t):null}function ZP(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=aJ(cJ(n.data));if(a)return a}return null}function tJ(e){if(e.events)return ZP(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 nJ(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 aJ(e){const t=Yc.safeParse(e?.createImproveRun);return t.success?t.data:null}function iJ(e){const t=oJ(e);if(!t)return null;const n=rJ(e.createdAt,e.updatedAt),a=e.blockedReason??sJ(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:lJ(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function oJ(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return X7.has(t)?{tone:"active",actionLabel:`${n} running`}:eJ.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 rJ(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 sJ(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function lJ(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 cJ(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function YP(e,t){if(!t)return null;const n=new Map,a=[];for(const M of e){if(!M.name.startsWith("subagent."))continue;const w=mJ(M);w&&a.push(w);const A=uJ(M);A?.parentSessionId===t&&n.set(A.id,A)}if(n.size===0)return null;const o=[...n.values()].sort((M,w)=>ys(w).localeCompare(ys(M))),r=o.filter(M=>M.status==="queued"||M.status==="running"),s=o.filter(M=>M.status==="completed"),c=o.filter(M=>M.status==="failed"),m=o.filter(M=>M.status==="cancelled"),u=o.filter(M=>M.status==="needs_resume"),f=[...s,...c,...m].sort((M,w)=>ys(w).localeCompare(ys(M))),g=o.reduce((M,w)=>{const A=al(w.metadata?.usage);return M.totalTokens+=mu(A?.totalTokens),M.promptTokens+=mu(A?.promptTokens),M.completionTokens+=mu(A?.completionTokens),M.requestCount+=mu(A?.requestCount),M},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),S=o.flatMap(M=>QP([...M.report?.blockers??[],M.error,M.progress.currentBlocker]).map(w=>({runId:M.id,roleId:M.roleId,status:M.status,message:w}))),k=o.flatMap(M=>XP([...M.report?.artifacts??[],M.report?.patchRef,M.report?.diffRef,...M.progress.patchRefs]).map(w=>({...w,runId:M.id,roleId:M.roleId}))),C=f.map(M=>dJ(M,a)),P=o[0]??null,j=P?{runId:P.id,roleId:P.roleId,status:P.status,message:P.progress.latestMeaningfulActivity||P.report?.summary||P.objective,updatedAt:ys(P)}:null,R=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${f.length} ${f.length===1?"child":"children"} finished`,$=[r.length?`${r.length} active`:null,s.length?`${s.length} completed`:null,c.length?`${c.length} failed`:null,m.length?`${m.length} cancelled`:null,u.length?`${u.length} paused`:null].filter(Boolean).join(" · "),O=j?`${hJ(j.roleId)}: ${j.message}`:"";return{sessionId:t,runs:o,activeRuns:r,completedRuns:s,failedRuns:c,cancelledRuns:m,needsResumeRuns:u,terminalRuns:f,latestRun:P,latestMeaningfulUpdate:j,activeCount:r.length,completedCount:s.length,failedCount:c.length,cancelledCount:m.length,needsResumeCount:u.length,terminalCount:f.length,usage:g,blockers:S,evidenceRefs:k,finalResults:C,testsRunCount:o.reduce((M,w)=>M+w.progress.validationAttempts.length,0),label:R,tooltip:[$,O].filter(Boolean).join(". ")}}function dJ(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:XP([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:QP([...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:pJ(e),updatedAt:ys(e)}}function uJ(e){const t=al(e.data),n=[t?.run,al(t?.message)?.run];for(const a of n){const o=Yw.safeParse(a);if(o.success)return o.data}return null}function mJ(e){const t=y$.safeParse(al(e.data)?.message);return t.success?t.data:null}function pJ(e){const t=al(al(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:uu(t.reason),retainedAt:uu(t.retainedAt),expiresAt:uu(t.expiresAt),retentionDays:fJ(t.retentionDays),trigger:uu(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function ys(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function QP(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function XP(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function al(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function uu(e){return typeof e=="string"&&e.trim()?e.trim():null}function mu(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function fJ(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function hJ(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Bg=[];function Fg(e,t){return eA(e,t,null)}function eA(e,t,n){const a=n&&SJ(n.events,e)?vJ(n.indexes,n.events.length,e):gJ(e),o=yJ(t);return{...a,...o}}function gJ(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 bJ(t)}function vJ(e,t,n){const a=new Map(e.eventsBySessionId),o=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),s=new Map(e.latestSubagentRuntimeBySessionId),c=new Set(e.activeGoalSessionIds),m=new Set(e.activeSubagentSessionIds),u=new Set;for(let f=t;f<n.length;f+=1){const g=n[f];if(!g.sessionId)continue;if(u.has(g.sessionId)){a.get(g.sessionId).push(g);continue}const S=a.get(g.sessionId);a.set(g.sessionId,S?[...S,g]:[g]),u.add(g.sessionId)}for(const f of u){const g=a.get(f)??Bg,S=qP(g);S?o.set(f,S):o.delete(f);const k=nA(g);k?(r.set(f,k),k.tone==="active"?c.add(f):c.delete(f)):(r.delete(f),c.delete(f));const C=YP(g,f);C?(s.set(f,C),tA({sessionEvents:g,sessionId:f,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:c}),C.activeCount>0?m.add(f):m.delete(f)):(s.delete(f),m.delete(f))}return{eventsBySessionId:a,latestContextUsageBySessionId:o,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:s,activeGoalSessionIds:c,activeSubagentSessionIds:m}}function bJ(e){const t=new Map,n=new Map,a=new Map,o=new Set,r=new Set;for(const[s,c]of e){const m=qP(c);m&&t.set(s,m);const u=nA(c);u&&(n.set(s,u),u.tone==="active"&&o.add(s))}for(const[s,c]of e){const m=YP(c,s);m&&(a.set(s,m),tA({sessionEvents:c,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 tA(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=gm(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function nA(e){return zg(e)??xy(e)??gm(e)}function yJ(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 c=a.get(r.sessionId);c?c.push(r):a.set(r.sessionId,[r]);const m=o.get(r.sessionId);(!m||Nx(r.createdAt)>Nx(m.createdAt))&&o.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:o}}function SJ(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 Id(e,t){return t?e.eventsBySessionId.get(t)??Bg:Bg}function aA(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function iA(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function xJ(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function kJ(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function Nx(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function wJ(e,t){return e?.conversationId===t}function IJ(e,t){return e?.id===t?null:e}function _J(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 CJ(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function Yie(e,t){return e.profiles.find(n=>CJ(n.ref)===t)?.ref??null}function RJ(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function Qie(e,t){return e.profiles.find(n=>RJ(n.ref,t))?.state??null}function PJ(e,t){const n=new Map(FL.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 AJ(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 Xie(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 oA="openpond:last-chat-task-mode";function TJ(e,t){return e==="labs"?"models":"chat"}function EJ(e){try{return e.getItem(oA)==="work"?"work":"chat"}catch{return"chat"}}function wy(){if(typeof window>"u")return"chat";try{return EJ(kd)}catch{return"chat"}}function jJ(e,t){try{e.setItem(oA,t==="chat"?"chat":"work")}catch{}}function MJ(e){if(!(typeof window>"u"))try{jJ(kd,e)}catch{}}const OJ="uploaded to a different account";function rA(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 Ba(e,t){const n=rA(e,t);return n.state==="confirmed"?n.cloudProject:null}function $J(e,t){return rA(e,t).state==="different_account"?OJ:null}function Hi(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function sA(e={}){return{...e,workspaceTarget:"hybrid"}}function NJ(e={}){return{...e,workspaceTarget:"local"}}function Li(e){return e?.metadata?.workspaceTarget==="hybrid"}function DJ(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function lA({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,o=e?Ba(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 cA({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:sA(),cwd:n.cwd,title:a}}function HJ(e){return y.useEffect(()=>{const t=SP(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),y.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=k8(n);try{let o;const r=e.selectedSession;if(r&&Uc(r))o=await Q.patchSession(e.connection,r.id,{title:a,metadata:Ch(r.metadata,n)}),e.setSessions(s=>s.map(c=>c.id===o.id?o:c));else{const s=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,c=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),m=r?.modelRef??(c==="openpond"?{providerId:"openpond",modelId:Ks}:{providerId:c,modelId:e.activeModel}),u=s?{workspaceTarget:s}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let f;if(!r&&e.workspaceTarget==="hybrid"){const g=lA({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(g.kind!=="ready")throw new Error(g.message);const S=cA({modelRef:m,provider:c,target:g,title:a});f={...S,experience:"work",metadata:Ch(S.metadata,n)}}else f={experience:"work",provider:c,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:Ch(u,n),title:a};o=await Q.createSession(e.connection,f),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 LJ=[];function qJ({primary:e,secondary:t}){const[n,a]=y.useState(null),o=y.useRef(new Set),[r,s]=y.useState(!1),[c,m]=y.useState(null),u=t8(),f=u?.kind==="models"&&["home","inbox","datasets","graders","experiments"].includes(u.route.page),{composerDraftStore:g,appDispatch:S,pendingTerminalCommand:k,setPendingTerminalCommand:C,terminalTabs:P,setTerminalTabs:j,trainingDetailTasksetId:R,setTrainingDetailTasksetId:$,mentionedAppId:O,setMentionedAppId:M,cloudSetupDialog:w,setCloudSetupDialog:A,rightPanelTabRequest:E,workspaceDiffPanelViewState:D,mainComposerFocusRequestId:U,requestMainComposerFocus:L,projectConfirmDialog:J,resolveProjectConfirmDialog:X,query:de,searchOpen:Me,archivedChatsOpen:Ie,sectionMenuOpen:ne,cloudProjectsExpanded:je,sidebarOpen:Se,view:oe,selectedAppId:be,selectedProjectId:re,selectedSessionId:ue,codexPermissionMode:ke,codexReasoningEffort:Le,busy:we,diffPanelOpen:le,diffPanelExpanded:xe,rightPanelMode:Ue,activeExperience:Ze,changeNewExperience:it,terminalOpen:at,settingsSection:Ne,newProjectDialogOpen:We,newProjectMode:qe,newProjectName:q,newProjectPath:N,newProjectBusy:F,commitDialogOpen:ee,commitMessage:me,commitIncludeUnstaged:$e,commitNextStep:ze,commitDraft:tt,branchDialogOpen:nt,branchDialogName:pt,toast:bt,labDetailNavigation:Oe,setQuery:Ye,setSearchOpen:h,setArchivedChatsOpen:B,setSectionMenuOpen:Y,setCloudProjectsExpanded:ge,setChatRowsVisibleCount:se,setSidebarOpen:G,setView:_,setSelectedAppId:W,setSelectedProjectId:ae,setSelectedSessionId:Z,setPrompt:ce,setDraftProvider:fe,setDraftModel:he,setDraftExperience:Ae,setDiffPanelOpen:Ce,setDiffPanelExpanded:He,setRightPanelMode:Pe,setTerminalOpen:Xe,setSettingsSection:mt,setNewProjectDialogOpen:fn,setNewProjectName:Mt,setNewProjectPath:dn,setCommitDialogOpen:yn,setCommitMessage:Sn,setCommitIncludeUnstaged:Qt,setCommitNextStep:Ja,setCommitDraft:_a,setBranchDialogOpen:zn,setBranchDialogName:$n,setError:Lt,showToast:St,applyBootstrapPayload:xn,bootstrap:xt,connection:Dt,startup:Ca,training:Vt,pinnedCollapsed:kn,cloudProjectsCollapsed:st,chatsCollapsed:Mn,savedForLaterCollapsed:fi,sidebarWidth:hi,sidebarResizing:ha,diffPanelWidth:Ra,diffPanelResizing:Bn,togglePinnedCollapsed:zi,toggleCloudProjectsCollapsed:Za,toggleChatsCollapsed:K,toggleSavedForLaterCollapsed:Be,startSidebarResize:_e,startDiffPanelResize:Ve,selectedApp:wt,selectedCloudProject:na,selectedProject:wn,selectedProjectLinkedApp:Je,selectedSession:Rn,sidebarSessions:ht,runtimeIndexes:Nn,runtimeEventStore:Ya,chatMentionApps:xo,connectedAppMentions:Pa,pendingApproval:ko,pendingChatUserMessages:nr,account:Bi,activeModel:Fn,activeProvider:Aa,appDefaults:aa,startMessage:wo,organizations:ar,teamChatOrganization:Io,teamChatTeamId:_o,teamChat:_t,publishTeamProfileAgent:gl,communitySidebar:ir,communityView:vl,teamAiThreadId:Ur,toggleTeamAiSidebar:bl,activeOpenPondCommandAccessMode:Fi,viewWorkspaceAppId:yl,viewWorkspaceId:zr,viewWorkspaceKind:Br,viewWorkspaceName:Fr,selectedActionCatalog:Sl,expandedProjectIds:xl,expandProject:gi,toggleProjectExpanded:kl,changeCodexPermissionMode:Vr,changeCodexReasoningEffort:Kr,changeOpenPondCommandAccessMode:Co,resolveApproval:Wr,beginNewChat:ga,beginNewChatWithTrainingModel:wl,dismissTrainingChatHandoff:or,trainingChatHandoff:Vi,selectTrainingChatTaskForComposer:ia,chatHistoryLoadStates:Il,loadMoreSelectedChatHistory:_l,selectedPagedSessionEvents:Pn,activeSessions:Ro,archivedSessions:Ta,pinnedSessions:Qa,savedForLaterSessions:rr,savedForLaterFiles:Po,sidebarFileBookmarks:Cl,setSidebarFileStatus:Gr,setSessions:sr,projectRows:Ki,localProjectRows:Ao,cloudProjectRows:To,projectSessionRowsByProjectId:Jr,childSessionRowsByParentId:Zr,sidebarProjectIdBySessionId:Ea,chatRows:ja,visibleChatRows:Yr,chatRowsVisibleCount:lr,sessionEvents:vi,goalRuntime:cr,subagentRuntime:Wi,visibleChatMessages:Qr,activeTerminalScope:Xr,terminalSummaries:es,runningSessionIds:Rl,selectedSessionRunning:ts,sidebarGoalRuntimeBySessionId:ns,sidebarSubagentRuntimeBySessionId:Pl,taskDragSessionId:Eo,taskPreviewSessionIds:as,startTaskDrag:dr,clearTaskDrag:bi,previewTaskDrop:Al,commitTaskDrop:Tl,commitTaskPreviewDrop:El,dragItem:jl,startPinnedDrag:yi,clearSidebarDrag:is,previewPinnedDrop:Ml,commitPinnedDrop:Ol,commitPinnedPreviewDrop:$l,commandProjectRows:va,contextWindowStatus:os,pinnedRows:Nl,workspaceBusy:ft,diffBusy:rn,visibleWorkspaceState:oa,visibleWorkspaceDiff:hn,refreshVisibleWorkspaceDiff:Dn,managedWorkspace:ba,canSyncActiveWorkspace:bp,canPublishOpenPondProject:yp,projectTarget:Sp,workspaceTarget:Cd}=e,{title:xp,browserConversationId:ur,handleWorkspaceDiffPanelViewStateChange:Rd,openSessionInChat:rs,changeProjectTarget:kp,submitNewProjectDialog:wp,changeWorkspaceBranch:Ip,openCommitDialog:_p,openCreateWorkspaceBranchDialog:Cp,openDefaultsSettingsFromBranchDialog:Rp,runWorkspaceTool:Pp,submitCommitDialog:Ap,submitCreateWorkspaceBranch:Tp,syncWorkspaceLocally:Ep,answerCreateImproveQuestion:Pd,applyCreateImproveCandidate:jp,approveCreateImproveRun:Mp,cancelCreateImproveRun:Op,changeDraftProvider:Dl,openCreateImprovePullRequest:Ad,reconcileCreateImprovePullRequest:$p,rejectCreateImproveCandidate:Np,pauseCreateImproveRun:Td,resumeCreateImproveRun:Ed,reviseCreateImproveRun:Dp,stopTurn:ss,archiveSession:Hp,restoreSession:jd,renameSession:Lp,toggleSessionPinned:Hl,toggleProjectPinned:Md,toggleSessionSavedForLater:Od,moveProjectToCloud:qp,startCloudSetupUpload:$d,changeWorkspaceTarget:Up,sendPromptFromMainComposer:zp,openSandboxWorkspace:Nd,openCloudProjectDialog:Bp,openExistingProjectPathDialog:Dd,openUrlInBrowserPanel:Fp,showBrowserPanel:Vp,showChangesPanel:Kp,showGoalSidebarTab:jo,rightChatTrainingLaunchRequest:Hd,setRightChatTrainingLaunchRequest:Wp,closeRightChatPanel:Gp,openRightChatPanel:Ll,rightChatPanelViews:Jp,showRightChatPanel:Zp,showRightPanelDiffTab:Yp,submitRightChatPrompt:Qp,activateRightChatPanel:Xp,updateRightChatModel:ef,updateRightChatPrompt:tf,updateRightChatProvider:nf,updateRightChatScrollState:af,openProfileSettings:of,diagnosticEvents:rf,toggleRightSidebar:Ld,removeProject:sf}=t,Xa=xt?.account.activeProfile&&xt?.preferences.defaultTeamId?`${xt.account.activeProfile.handle}:${xt.preferences.defaultTeamId}`:null;y.useEffect(()=>{if(!(!Xa||oe!=="chat"||u?.kind!=="chat"||u.sessionId||ue||o.current.has(Xa))){o.current.add(Xa);try{const Te=localStorage.getItem(`openpond:ponder-mode:v1:${Xa}`);(Te==="clean"||Te==="activity")&&a(Te)}catch{}}},[Xa,u,oe,ue]),y.useEffect(()=>{if(!(!Xa||!o.current.has(Xa)))try{localStorage.setItem(`openpond:ponder-mode:v1:${Xa}`,n??"off")}catch{}},[Xa,n]);const ls=y.useCallback(Te=>{W(null),ae(Te),Z(null),_("chat"),gi(Te),L()},[gi,L,W,ae,Z,_]),lf=y.useCallback((Te=null)=>{a(null);const ut=ue?Ea[ue]??null:null;if(!Te&&ut){ls(ut);return}ga(Te)},[ga,ls,ue,Ea]),cf=y.useCallback(async Te=>{if(!(!Dt||!xt))try{const ut=await Q.savePreferences(Dt,{defaultTeamId:Te});xn({...xt,preferences:ut.preferences})}catch(ut){const qt=ut instanceof Error?ut.message:String(ut);throw Lt(qt),St("Could not switch teams","error"),ut}},[xn,xt,Dt,Lt,St]),df=y.useCallback(async()=>{if(Dt)try{const Te=await Q.signOutOpenPondAccount(Dt);xn(Te);const ut=await Q.savePreferences(Dt,{defaultTeamId:null});xn({...Te,preferences:ut.preferences}),St("Logged out","success")}catch(Te){const ut=Te instanceof Error?Te.message:String(Te);throw Lt(ut),St("Could not log out","error"),Te}},[xn,Dt,Lt,St]),ql=_o??aa.defaultTeamId??null,uf=y.useMemo(()=>Ki.filter(Te=>Te.kind==="local"||ql!==null&&Te.project.teamId===ql),[Ki,ql]),mf=y.useMemo(()=>{const Te={};for(const ut of Ro){const qt=Ea[ut.id];qt&&(Te[qt]=(Te[qt]??0)+1)}for(const ut of Ao){if(ut.kind!=="local")continue;const qt=ut.project.linkedSandboxProject?.projectId;if(!qt||!ut.cloudLinkTrusted)continue;const Ma=It("cloud",qt);Te[ut.id]=(Te[ut.id]??0)+(Te[Ma]??0)}return Te},[Ro,Ao,Ea]),[qd,Gi]=y.useState(null),[cs,ds]=y.useState(null),pf=PJ(xt?.profile,xt?.extensionCatalog),[mr,Ul]=y.useState(null),[us,zl]=y.useState(null),[Si,Ud]=y.useState(null),ff=y.useCallback(()=>{W(null),ae(null),Z(null),Y(null),_("team")},[Y,W,ae,Z,_]),hf=y.useCallback(()=>{W(null),ae(null),Z(null),Y(null),ir.discoverCommunities()},[ir.discoverCommunities,Y,W,ae,Z]),gf=HJ({activeExperience:Ze,activeModel:Fn,activeOpenPondCommandAccessMode:Fi,activeProvider:Aa,cloudProjects:xt?.cloudProjects??LJ,composerDraftStore:g,connection:Dt,requestComposerFocus:L,selectedCloudProject:na,selectedProject:wn,selectedSession:Rn,setMentionedAppId:M,setSelectedSessionId:Z,setSessions:sr,setView:_,showToast:St,workspaceTarget:Cd.value}),vf=y.useCallback(async Te=>{if(!Dt)throw new Error("OpenPond is not connected.");let ut=Aa,qt=Fn;ut==="codex"&&(ut=qg(xt?.providers,{enabledOnly:!0}).find(An=>An.value!=="codex")?.value??Pr,qt=um(ut,xt?.providers)??xc);const Ma=ht.find(An=>An.id===Te.sourceSessionId),Ji=await Q.createSession(Dt,{experience:Te.target,provider:ut,modelRef:{providerId:ut,modelId:qt},openPondCommandAccessMode:Fi,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${Ma?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:AJ({sourceTaskId:Te.sourceSessionId,sourceExperience:Ma?.experience??null,targetExperience:Te.target,sourceMessageIds:Te.sourceMessageIds??[],sourceContext:Te.sourceContext,output:Te.output})}});return sr(An=>[Ji,...An]),Ae(Te.target),fe(ut),he(qt),g.set(Te.prompt),ln({kind:"chat",sessionId:Ji.id}),S({type:"selectSession",sessionId:Ji.id,appId:null,projectId:null}),W(null),ae(null),Xe(!1),_("chat"),Pe("home"),Ce(Te.target==="work"),He(!1),Ji},[Fn,Fi,Aa,S,xt?.providers,g,Dt,He,Ce,Ae,he,fe,Pe,W,ae,sr,Xe,_,ht]),bf=y.useCallback(Te=>{Ul(Te),zl(null),ga(null),G(!0)},[ga,G]),yf=y.useCallback(Te=>{ga(null),Ae("work"),g.set(`$openpond-refiner-authoring ${Te}`),_("chat"),G(!0)},[ga,g,Ae,G,_]),zd=y.useCallback(Te=>{zl(_J(Te)),Ul(null),ga(null),G(!0)},[ga,G]);y.useEffect(()=>{!mr&&!us||oe!=="chat"||ue||re||be||(Gi(mr),ds(us),Ul(null),zl(null),Pe("home"),He(!1),Ce(!0))},[mr,us,be,re,ue,He,Ce,Pe,oe]),y.useEffect(()=>{!qd&&!cs||oe==="chat"&&le&&Ue==="home"||(Gi(null),ds(null))},[le,cs,qd,Ue,oe]);const Bd=y.useCallback(()=>{Gi(null),ds(null),He(!1),Ce(!1)},[He,Ce]),Sf=y.useCallback(Te=>{let ut;if(Te.workspaceKind==="local"){const qt=It("local",Te.workspaceId);ut=`draft:${qt}`,W(null),ae(qt),Z(null),gi(qt),_("chat")}else{const qt=ht.find(Ma=>Ma.id===Te.sourceSessionId||Ma.workspaceId===Te.workspaceId);if(!qt){St("This saved file's cloud chat is no longer available.","error");return}ut=qt.id,rs(qt.id)}Pe("changes"),Ce(!0),Ud({id:Date.now(),conversationId:ut,file:Te}),Te.available||St(`File unavailable: ${Te.path}`,"error")},[gi,rs,Ce,Pe,W,ae,Z,_,St,ht]);y.useEffect(()=>{if(!wJ(Si,ur))return;const Te=window.setTimeout(()=>{Pe("changes"),Ce(!0),Ud(ut=>IJ(ut,Si.id))},0);return()=>window.clearTimeout(Te)},[ur,Ce,Pe,Si]);const xf=u?.kind==="models"&&u.route.area==="console"?"console":TJ(oe);y.useEffect(()=>{if(u){if(u.kind==="models"||u.kind==="models_unavailable"){oe!=="labs"&&_("labs");return}if(u.kind==="settings"){W(null),ae(null),Z(null),mt(u.section),oe!=="settings"&&_("settings");return}if(u.kind==="view"){W(null),ae(null),Z(null),oe!==u.view&&_(u.view);return}u.sessionId!==null&&(a(null),W(null),ae(null)),Z(u.sessionId),oe!=="chat"&&_("chat")}},[u,W,ae,Z,mt,_,oe]);const kf=y.useCallback(Te=>{if(Y(null),W(null),ae(null),Z(null),Te==="models"||Te==="console"){fo(Te==="console"?ma("datasets",null,{area:"console"}):ma()),_("labs");return}Te==="chat"&&ln({kind:"chat",sessionId:null}),it(wy())},[it,ln,Y,W,ae,Z,_]),wf=y.useCallback(async(Te,ut)=>{const qt=await Vt.actions.acceptHarnessReview(Te,ut,{providerId:Aa,modelId:Fn},Le);return qt?($(qt.materializedTasksetId??null),fo(ma()),_("labs"),!0):(St("Taskset review could not be opened.","error"),!1)},[Fn,Aa,Le,fo,ma,$,_,St,Vt.actions]);if(!Ca.ready)return x.jsx(z7,{startup:Ca});if(oe==="settings")return x.jsx(Rx,{showToast:St,children:x.jsx(H7,{settings:{payload:xt,connection:Dt,diagnostics:rf,initialSection:Ne,onPayload:xn,onError:Lt,onToast:St,onOpenSourceSession:rs,onStartRefinerAuthoring:yf,onAcceptEvaluationReview:wf,onOpenSkill:bf,onOpenExtension:zd,teamChatCurrentUserId:_t.currentUserId,teamChatEnabled:_o!==null,teamChatNotificationMode:_t.notificationMode,teamChatThreads:_t.threads,onTeamChatNotificationModeChange:_t.setNotificationMode,onTeamChatThreadMuteChange:_t.setThreadMuted,diffPanelWidth:Ra,diffPanelResizing:Bn,diffPanelExpanded:xe,onDiffPanelResizeStart:Ve,onDiffPanelExpandedChange:He,onBack:()=>{const Te=QW(u);ln(Te),_(Te.kind==="models"?"labs":"chat"),G(!0)}},toast:{toast:bt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})});const ot=lp(),Wt=Dt?.platform??navigator.platform,Gt=ot&&iy(Wt),Jt=Xr,ei=oa?.initialized?oa.repoPath:Rn?.cwd??null,If={"--sidebar-width":`${hi}px`,"--diff-panel-width":`${Ra}px`},pT=oe==="chat"&&Ze!=="chat"||oe==="labs"||oe==="scheduled"&&r||oe==="team"&&!!Ur,fT=["app-shell",Gt?"platform-macos":"",Se?"sidebar-open":"sidebar-closed",ha?"sidebar-resizing":"",Bn?"diff-panel-resizing":""].filter(Boolean).join(" "),_f=ue?Il[ue]:null,hT=ue?_f?.cursorSequence??V7(eo(Pn,Id(Nn,ue))):null,gT=!!ue&&!!Dt&&(Kt(ue)?!0:!!xt?.eventWindow?.hasMoreBefore&&!!hT)&&(_f?.hasMore??!0),vT=!!_f?.loading,bT=(()=>{const Te=Vt.payload;if(!Te)return{};const ut=new Map(Te.plans.map(An=>[An.id,An])),qt=new Set(["queued","starting","running","cancelling","reconciling"]),Ma={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},Ji={};for(const An of[...Te.modelRuns].sort((ti,ms)=>ms.updatedAt.localeCompare(ti.updatedAt))){if(An.kind==="evaluation"||!["prepared","running"].includes(An.status))continue;const ti=Te.jobs.filter(Cf=>Cf.metadata.modelRunId===An.id).sort((Cf,yT)=>yT.updatedAt.localeCompare(Cf.updatedAt))[0];if(ti&&!qt.has(ti.status))continue;const ms=ti?.status??(An.status==="prepared"?"starting":"running");Ji[An.modelId]={label:Ma[ms]??"Running",status:ms}}for(const An of[...Te.jobs].sort((ti,ms)=>ms.updatedAt.localeCompare(ti.updatedAt))){if(!qt.has(An.status))continue;const ti=ut.get(An.planId)?.modelId;!ti||Ji[ti]||(Ji[ti]={label:Ma[An.status]??"Active",status:An.status})}return Ji})();return x.jsx(Rx,{showToast:St,children:x.jsx(D7,{className:fT,style:If,sidebar:{onOpenPonder:()=>{ln({kind:"chat",sessionId:null}),Z(null),_("chat"),a("activity")},productArea:xf,modelProjects:(Vt.payload?.modelProjects??[]).filter(Te=>Te.hosted===null||Te.hosted.teamId===(aa.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:bT,onProductAreaChange:kf,experience:Ze,view:oe,selectedAppId:be,selectedProjectId:re,selectedSessionId:ue,selectedTeamThreadId:_t.selectedThreadId,teamChatEnabled:_o!==null,organizations:ar,teamChatOrganization:Io,teamChatLoading:_t.loading,currentUserId:_t.currentUserId,teamMembers:_t.members,teamThreads:_t.threads,...ir,account:Bi,connection:Dt,profile:xt?.profile,pinnedCollapsed:kn,cloudProjectsCollapsed:st,chatsCollapsed:Mn,savedForLaterCollapsed:fi,archivedChatsOpen:Ie,cloudProjectsExpanded:je,sectionMenuOpen:ne,dragItem:jl,taskDragSessionId:Eo,taskPreviewSessionIds:as,activeSessions:Ro,archivedSessions:Ta,pinnedRows:Nl,pinnedSessions:Qa,savedForLaterSessions:rr,savedForLaterFiles:Po,projectRows:Ki,localProjectRows:Ao,cloudProjectRows:To,projectSessionRowsByProjectId:Jr,childSessionRowsByParentId:Zr,sidebarProjectIdBySessionId:Ea,terminalSummaries:es,runningSessionIds:Rl,goalRuntimeBySessionId:ns,subagentRuntimeBySessionId:Pl,visibleChatRows:Yr,chatRows:ja,chatRowsVisibleCount:lr,expandedProjectIds:xl,currentVersion:xt?.server.version??null,platform:Wt,arch:Dt?.arch??null,onSidebarResizeStart:_e,setSidebarOpen:G,setView:_,setSelectedAppId:W,setSelectedProjectId:ae,setSelectedSessionId:Z,setSearchOpen:h,setSectionMenuOpen:Y,setSettingsSection:mt,onSelectTeam:cf,onLogOut:df,onTogglePinnedCollapsed:zi,onToggleCloudProjectsCollapsed:Za,onToggleChatsCollapsed:K,onToggleSavedForLaterCollapsed:Be,setArchivedChatsOpen:B,setCloudProjectsExpanded:ge,setChatRowsVisibleCount:se,beginNewChat:lf,beginProjectChat:ls,onAddProject:Dd,dockSessionRight:Ll,selectTeamThread:Te=>{_("team"),_t.selectThread(Te)},openTeamDm:Te=>{_("team"),_t.openDm(Te)},toggleSessionPinned:Hl,toggleProjectPinned:Md,toggleSessionSavedForLater:Od,openSidebarFile:Sf,setSidebarFileStatus:(Te,ut)=>{Gr(Te,ut)},archiveSession:Hp,restoreSession:jd,renameSession:Lp,removeProject:sf,expandProject:gi,toggleProjectExpanded:kl,startPinnedDrag:yi,clearSidebarDrag:is,previewPinnedDrop:Ml,commitPinnedDrop:Ol,commitPinnedPreviewDrop:$l,startTaskDrag:dr,clearTaskDrag:bi,previewTaskDrop:Al,commitTaskDrop:Tl,commitTaskPreviewDrop:El},topBar:{sidebarOpen:Se,title:oe==="chat"&&n?"Ponder Pal":xp,backAction:Oe.backAction,breadcrumbs:Oe.breadcrumbs,conversationId:oe==="chat"?ue:null,workspaceName:Fr,workspaceId:zr,busy:we,workspaceState:oa,workspaceKind:Br,selectedApp:Je??wt,selectedProject:wn,workspaceDiff:hn,managedWorkspace:ba,workspaceBusy:ft,defaultTeamId:aa.defaultTeamId,activityActorId:xt?.account.profile?.id??null,activityProjectId:u?.kind==="models"?u.route.projectId??null:null,showDiffControls:oe==="chat"&&Ze==="development",diffPanelOpen:le,terminalOpen:at,rightSidebarAvailable:pT,rightSidebarOpen:oe==="labs"&&f?c?.open??!1:oe==="scheduled"?r:le,onToggleDiffPanel:Ld,onToggleRightSidebar:oe==="labs"&&f?c?.toggle:oe==="scheduled"?()=>s(Te=>!Te):oe==="team"&&Ur?bl:Ld,onOpenSearch:()=>{Y(null),h(!0)},onToggleTerminal:()=>Xe(Te=>!Te),onRunTerminalCommand:Te=>{C({id:Date.now(),scope:Jt,command:Te}),Xe(!0)},onWorkspaceToolAction:Pp,onOpenCommitDialog:_p,onWorkspaceBranchChange:Ip,onWorkspaceBranchCreate:Cp,connection:Dt,onBootstrap:xn,onOpenSandboxWorkspace:Nd,onShowSidebar:()=>G(!0),onOpenTeamChat:ff,onDiscoverCommunities:hf,collaborationView:oe==="team"||oe==="community"?oe:null,platform:Wt,showWorkspaceControls:oe!=="team"&&oe!=="community"&&oe!=="labs"&&oe!=="scheduled"&&oe!=="outputs"&&oe!=="projects"&&(Ze==="development"||Ze==="work"&&!!(wn||Rn?.localProjectId||Rn?.cloudProjectId||Rn?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:Ze,onNewExperienceChange:it,view:oe,teamChat:{currentUserId:_t.currentUserId,members:_t.members,agents:_t.agents,profile:xt?.profile??null,teamId:_o,teamName:Io?.displayName??null,detail:_t.detail,aiThread:_t.aiThread,agentConversation:_t.agentConversation,loading:_t.loading,busy:_t.busy,error:_t.error,connection:Dt,providerSettings:xt?.providers??null,provider:Aa,model:Fn,codexPermissionMode:ke,codexReasoningEffort:Le,openPondCommandAccessMode:Fi,contextWindowStatus:os,showToast:St,onProviderChange:Dl,onModelChange:he,onCodexPermissionModeChange:Vr,onCodexReasoningEffortChange:Kr,onOpenPondCommandAccessModeChange:Co,onOpenProviderSettings:()=>{mt("providers"),_("settings"),ln({kind:"settings",section:"providers"})},onSendMessage:_t.sendMessage,onPublishProfileAgent:gl,onOpenAiThread:async Te=>{await _t.openAiThread(Te),Pe("chat"),Ce(!0)},onOpenAgentConversation:async Te=>{await _t.openAgentConversation(Te),Pe("chat"),Ce(!0)},onCloseAiThread:()=>Ce(!1),onCloseAgentConversation:()=>{_t.closeAgentConversation(),Ce(!1)},onSendAgentTurn:_t.sendAgentTurn,onSendAiTurn:_t.sendAiTurn,onStopAiTurn:_t.stopAiTurn,onEditMessage:_t.editMessage,onDeleteMessage:_t.deleteMessage,onRetryMessage:_t.retryMessage,onDismissFailedMessage:_t.dismissFailedMessage,onLoadMoreMessages:_t.loadMoreMessages,onRetryLoad:_t.refresh},community:vl,bootstrap:xt,runtimeEvents:vi,chatMessages:Qr,pendingUserMessage:ue?nr[ue]??null:null,contextWindowStatus:os,goalRuntime:cr,subagentRuntime:Wi,selectedSessionId:ue,composerDraftStore:g,mainComposerFocusRequestId:U,labCloseDetailRequestId:Oe.closeDetailRequestId,labCloseDetailKind:Oe.closeDetailKind,sideChatTrainingLaunchRequest:Hd,onSideChatTrainingLaunchHandled:Te=>Wp(ut=>ut?.id===Te?null:ut),mentionApps:xo,connectedAppMentions:Pa,profileSkills:pf,selectedMentionAppId:O,busy:we,turnRunning:ts,activeProvider:Aa,activeModel:Fn,codexPermissionMode:ke,codexReasoningEffort:Le,openPondCommandAccessMode:Fi,pendingApproval:ko,activeWorkspaceAppId:yl,activeWorkspaceId:zr,activeWorkspaceKind:Br,projectTarget:Sp,actionCatalog:Sl,workspaceTarget:Cd,connection:Dt,workspaceName:Fr,workspaceState:oa,workspaceDiff:hn,workspaceBusy:ft,diffBusy:rn,forceChatThread:!!ue,diffPanelOpen:le,diffPanelExpanded:xe,rightPanelMode:Ue,rightPanelTabRequest:E,rightChatPanels:Jp,runtimeEventStore:Ya,nativeSkillSidebar:qd,extensionSkillSidebar:cs,workspaceDiffPanelViewState:D,sidebarFileOpenRequest:Si,sidebarFileBookmarks:Cl,onSetSidebarFileStatus:(Te,ut)=>{Gr(Te,ut)},browserConversationId:ur,terminalScope:Jt,terminalTabs:P,terminalCwd:ei,pendingTerminalCommand:k,terminalOpen:at,onToggleTerminal:()=>Xe(Te=>!Te),onWorkspaceDiffPanelViewStateChange:Rd,training:Vt,trainingSessions:ht,trainingChatHandoff:Vi,trainingDetailTasksetId:R,onTrainingDetailTasksetIdChange:$,onTrainingChatTaskSelect:ia,onTrainingChatHandoffDismiss:or,onOpenSession:rs,onExperienceHandoff:vf,cloudProjects:xt?.cloudProjects??[],projects:uf,projectsAccountBaseUrl:Bi?.baseUrl??Bi?.activeProfile?.baseUrl??null,projectsTeamName:Io?.displayName??null,projectTaskCounts:mf,onNewCloudProject:Bp,onNewLocalProject:Dd,onNewProjectTask:Te=>ls(Te.id),onToggleProjectPinned:Md,onUploadLocalProject:qp,chatHistoryHasMore:gT,chatHistoryLoading:vT,onDiffPanelResizeStart:Ve,onToggleDiffPanelExpanded:()=>He(Te=>!Te),onShowDiffPanel:Kp,onShowBrowserPanel:Vp,onShowFilesPanel:()=>Yp("files"),onShowGoalSidebarTab:jo,onShowTrainingDraftPanel:()=>{Pe("training"),Ce(!0)},onShowRightChatPanel:Zp,onAddRightChat:()=>Ll(null),onOpenRightChatForSession:(Te,ut)=>{const qt=ut??ht.find(Ma=>Ma.id===Te)??null;qt&&Ll(qt,{preserveView:!0})},onLabDetailOpenChange:Oe.onDetailOpenChange,evaluationSidebarActive:oe==="labs"&&f,onEvaluationSidebarControl:m,scheduledDetailOpen:r,onScheduledDetailOpenChange:s,onTerminalTabsChange:j,onCloseRightChatPanel:Gp,onCloseNativeSkillSidebar:Bd,onActivateRightChatPanel:Xp,onRightChatModelChange:ef,onRightChatPromptChange:tf,onRightChatScrollStateChange:af,onRightChatProviderChange:nf,onSubmitRightChat:Qp,onStopRightChat:Te=>ss(Te),onCloseTerminal:()=>Xe(!1),onLoadMoreChatHistory:_l,canSyncWorkspace:bp,startMessage:wo,onPayload:xn,onError:Lt,setView:_,onOpenProfileSettings:of,onOpenProviderSettings:()=>{ln({kind:"settings",section:"providers"})},onOpenTrainingSettings:()=>{ln({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{ln({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Dl,changeProjectTarget:kp,changeWorkspaceTarget:Up,setDraftProvider:fe,setDraftModel:he,onBeginNewChatWithModel:wl,changeCodexPermissionMode:Vr,changeCodexReasoningEffort:Kr,changeOpenPondCommandAccessMode:Co,resolveApproval:Wr,answerCreateImproveQuestion:Pd,applyCreateImproveCandidate:jp,approveCreateImproveRun:Mp,cancelCreateImproveRun:Op,openCreateImprovePullRequest:Ad,reconcileCreateImprovePullRequest:$p,rejectCreateImproveCandidate:Np,pauseCreateImproveRun:Td,resumeCreateImproveRun:Ed,reviseCreateImproveRun:Dp,setMentionedAppId:M,showToast:St,onSaveTaskDraft:gf,sendPrompt:zp,stopTurn:Te=>ss(void 0,Te),syncWorkspaceLocally:Ep,refreshWorkspaceDiff:Dn},cloudSetup:{state:w,onClose:()=>A(null),onOpenBrowserUrl:Fp,onStart:()=>{$d()}},projectConfirm:{state:J,onResolve:X},lazyPanels:{activeSessions:Ro,branchDialogName:pt,branchDialogOpen:nt,commitDialogOpen:ee,commitDraft:tt,commitIncludeUnstaged:$e,commitMessage:me,commitNextStep:ze,canPublishOpenPondProject:yp,connection:Dt,expandProject:gi,newProjectBusy:F,newProjectDialogOpen:We,newProjectDirectory:aa.defaultNewProjectDirectory,newProjectMode:qe,newProjectName:q,newProjectPath:N,projectRows:va,query:de,searchOpen:Me,visibleWorkspaceDiff:hn,visibleWorkspaceState:oa,workspaceBusy:ft,appDispatch:S,beginNewChat:()=>ga(null),openDefaultsSettingsFromBranchDialog:Rp,setBranchDialogName:$n,setBranchDialogOpen:zn,setCommitDialogOpen:yn,setCommitDraft:_a,setCommitIncludeUnstaged:Qt,setCommitMessage:Sn,setCommitNextStep:Ja,setNewProjectDialogOpen:fn,setNewProjectName:Mt,setNewProjectPath:dn,setPrompt:ce,setQuery:Ye,setSearchOpen:h,submitCommitDialog:Ap,submitCreateWorkspaceBranch:Tp,submitNewProjectDialog:wp},toast:{toast:bt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})})}const js=new Map,Nu=new Map;function Vg(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 UJ(e){const t=e?.trim();if(!t)return null;const n=js.get(t);return n?.updatedAt?n.organizations:null}function zJ(e,t){const n=e?.trim();if(n){js.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of Nu.get(n)??[])a()}}function BJ(e,t){const n=e?.trim();if(!n)return()=>{};const a=Nu.get(n)??new Set;return a.add(t),Nu.set(n,a),()=>{a.delete(t),a.size===0&&Nu.delete(n)}}function Dx(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=js.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=>(zJ(t,o),o)).catch(o=>{const r=js.get(t);throw r?.promise===a&&js.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),o});return js.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const eoe="openpond.config.json";function toe(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function dA(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function Mh(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function noe(e,t=null){const n=VJ(e.openFilePaths.map(o=>Lx(o,t)).filter(Boolean)),a=e.selectedPath&&Lx(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function Hx(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 Lx(e,t=null){let n=FJ(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 aoe(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function ioe(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function ooe(e,t){const n=qx(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const o=qx(a);return!!(o&&o.startsWith(`${n}/`))})}function roe(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function soe(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function FJ(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 VJ(e){return Array.from(new Set(e))}function qx(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function KJ(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(c=>c.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 uA(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function WJ(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function up(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||uA(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 GJ(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 JJ(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 ZJ(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function YJ({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const QJ=[{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 XJ(...e){return ZJ(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function eZ(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return XJ(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function tZ({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:o,selectedCloudProject:r,selectedProject:s,selectedSession:c,selectedSessionId:m,selectedSessionLinkedProject:u}){const f=c?.workspaceKind==="local_project"?c.workspaceId??null:u?.id??null,g=Kt(m)&&!c,S=c?Hi(c.workspaceKind):!1,k=Li(c),C=c?DJ(c):!1,P=c?.cwd&&(!S||k)?I1(c.cwd):null,j=e?.providers??null,R=Ba(s,e?.cloudProjects??[]),$=YJ({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:k}),O=er($,t,j),M=$a(e?.preferences),w=g?null:c?S?c.workspaceKind??"sandbox":C?"sandbox":f?"local_project":c.workspaceKind??(c.appId?"sandbox_app":P?"local_project":null):r?"sandbox":s?"local_project":o?"sandbox_app":null,A=g?null:c?S&&!k||C?null:f||(c.workspaceId??c.appId??P):r?null:s?.id??o,E=g?null:c?S?c.workspaceId??null:C?null:f??c.workspaceId??c.appId??P:r?null:s?.id??o,D=e?.account??null,U=!e||D?.state==="loading"||D?.state==="switching",L=!U&&D?.state==="signed_out",J=U?null:L?"Sign in":D?.label??D?.activeProfile?.handle??"Account",X=eZ(D),de=X?`Welcome, ${X}`:"Welcome",Me=c?.workspaceName??c?.appName??r?.name??s?.name??a?.name??null,Ie=Hi(w)?"cloud":"local",ne=s?.name??u?.name??(c?.workspaceKind==="local_project"?c.workspaceName:null)??"Local workspace",je=(Ie==="cloud"?Me:null)??r?.name??R?.name??s?.name??"Cloud workspace",Se=!!(r?.id||R?.id||c?.cloudProjectId||Ie==="cloud");return{account:D,accountLabel:J,accountPending:U,accountSignedOut:L,activeModel:O,activeProvider:$,activeWorkspaceAppId:A,activeWorkspaceId:E,activeWorkspaceKind:w,activeWorkspaceLocation:Ie,appDefaults:M,cloudLinked:Se,cloudTargetName:je,localTargetName:ne,selectedCodexHistoryPending:g,selectedSessionCloudWorkspace:S,selectedSessionLocalPathWorkspaceId:P,selectedSessionPendingCloudStart:C,selectedSessionProjectId:f,startMessage:de,workspaceName:Me}}function nZ({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:o,cloudLinked:r,selectedCloudProject:s,selectedProject:c,selectedSession:m,pendingWorkspaceTarget:u,workspaceStates:f,workspaceBusy:g}){const S=Ba(c,a?.cloudProjects??[]),C=!!!c?.linkedSandboxProject?.projectId||!!S,P=y.useMemo(()=>{const E=(a?.localProjects??[]).map(J=>({value:`local:${J.id}`,label:J.name,detail:J.workspacePath,kind:"local"})),D=(a?.cloudProjects??[]).map(J=>({value:`cloud:${J.id}`,label:J.name,detail:J.organizationName??J.sourceLabel??"OpenPond Cloud",kind:"cloud"})),U=c?`local:${c.id}`:s?`cloud:${s.id}`:"none",L=[...E,...D].find(J=>J.value===U)??null;return{value:U,label:L?.label??"Select Project",detail:L?.detail??"Choose a project for local or cloud work",busy:g||o,options:[...E,...D,...QJ,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,o,s,c,g]),j=!!(r||c),R=!!(s?.id||S?.id||m?.cloudProjectId||Li(m)),$=c?f[c.id]??null:null,O=RP($,{branch:c?.linkedSandboxProject?.defaultBranch??null,path:c?.workspacePath??m?.cwd??null,linkedCloudSourceKnown:c?.linkedSandboxProject?.projectId&&C?!!c.linkedSandboxProject.lastUploadedCommit||!$?.headCommit:!0}),M=PP(c,s??S,$,{cloudLinkTrusted:C}),w=D8(c,$,{cloudLinkTrusted:C}),A=y.useMemo(()=>{const E={value:"local",label:c?"Local checkout":"Local",detail:c?"Use the selected checkout on this machine.":"Use an app-managed task workspace on this machine.",stateNote:c?O:"App-managed local task workspace",disabled:!1,disabledReason:null},D={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:R?M:"upload required",disabled:e||t||!R,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},U={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:c||s?M:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},L={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:w,disabled:e||t||!c,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},J=n==="cloud"?"local":"cloud",X=J==="local"?E:U;let de=n==="cloud"?U:E;return u==="cloud"?de=U:u==="local"?de=E:(Li(m)||u==="hybrid")&&(de=D),{value:de.value,label:de.label,detail:de.stateNote||de.detail,busy:g,action:{...X,label:J==="cloud"?"Hosted":c?"Local checkout":"Check out locally"},uploadAction:c?L:null,options:[E,D,U]}},[n,e,t,r,j,M,R,O,u,c,m,w,g]);return{projectTarget:P,workspaceTarget:A}}function Wn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function mA(e){return Wn(e.name||e.gitRepo||e.id)}function loe(e){return`@${mA(e)}`}function pA(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Wn(t[1]??"")).filter(Boolean)}function aZ(e,t){const n=pA(e);if(n.length===0)return!1;const a=new Set([Wn(t.id),mA(t),t.gitRepo?Wn(t.gitRepo):""].filter(Boolean));return n.some(o=>a.has(o))}function fA(e){return e.filter(t=>t.sandbox)}function iZ(e,t){const n=pA(e);if(n.length===0)return null;const a=new Map;for(const o of n){const r=t.find(s=>{const c=Wn(s.id),m=Wn(s.name),u=s.gitRepo?Wn(s.gitRepo):"";return o===c||o===m||o===u});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function coe(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:Wn(a[1]??""),start:a.index+o}}function oZ(e){return new Set(e.map(t=>t.id))}function Ux(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function rZ({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:o,sessions:r}){const s=y.useMemo(()=>e?.apps.find(L=>L.id===o)??null,[e?.apps,o]),c=y.useMemo(()=>new Map((e?.localProjects??[]).map(L=>[L.id,L])),[e?.localProjects]),m=y.useMemo(()=>new Map((e?.cloudProjects??[]).map(L=>[L.id,L])),[e?.cloudProjects]),u=y.useMemo(()=>hP(n),[n]),f=y.useMemo(()=>u?.kind==="local"?c.get(u.id)??null:null,[c,u]),g=y.useMemo(()=>u?.kind==="cloud"?m.get(u.id)??null:null,[m,u]),S=y.useMemo(()=>oZ(e?.apps??[]),[e?.apps]),k=y.useMemo(()=>fA(e?.apps??[]),[e?.apps]),C=y.useMemo(()=>{const L=[];for(const J of e?.localProjects??[]){const X=Ux(J,S);X&&L.push([X.appId,J.id])}return new Map(L)},[e?.localProjects,S]),P=y.useMemo(()=>new Set((e?.localProjects??[]).map(L=>L.id)),[e?.localProjects]),j=y.useMemo(()=>xP(e?.localProjects??[]),[e?.localProjects]),R=y.useRef([]),$=y.useMemo(()=>sZ(r,t,R.current),[t,r]),O=y.useMemo(()=>$.find(L=>L.id===a)??null,[$,a]),M=y.useMemo(()=>{if(!O)return null;if(O.localProjectId)return c.get(O.localProjectId)??null;if(O.workspaceKind==="local_project")return O.workspaceId?c.get(O.workspaceId)??null:null;const L=C8(O,P,j);if(L)return c.get(L)??null;if(!O.appId)return null;const J=C.get(O.appId);return J?c.get(J)??null:null},[C,c,P,j,O]),w=y.useMemo(()=>O?.cloudProjectId?m.get(O.cloudProjectId)??null:null,[m,O]),A=f??M,E=g??w,D=y.useMemo(()=>Ux(A,S),[S,A]),U=y.useMemo(()=>D?e?.apps.find(L=>L.id===D.appId)??null:null,[e?.apps,D]);return{cloudProjectById:m,currentAppIds:S,linkedProjectByAppId:C,localProjectById:c,mentionableSandboxApps:k,selectedApp:s,selectedCloudProject:E,selectedProject:A,selectedProjectLinkedApp:U,selectedProjectLinkedOpenPondApp:D,selectedSession:O,selectedSessionLinkedProject:M,sidebarSessions:$}}function sZ(e,t,n){const a=new Map;for(const u of e){const f=zx(u);a.set(f,u)}for(const u of t){const f=zx(u),g=a.get(f);a.set(f,g?lZ(g,u):u)}const o=Array.from(a.entries());if(!n)return o.sort((u,f)=>Bx(u[1],f[1])).map(u=>u[1]);const r=[],s=new Set;for(const u of n){const f=a.get(u);f&&(r.push([u,f]),s.add(u))}const m=[...o.filter(([u])=>!s.has(u)).sort((u,f)=>Bx(u[1],f[1])),...r];return n.splice(0,n.length,...m.map(([u])=>u)),m.map(u=>u[1])}function lZ(e,t){return{...e,metadata:cZ(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:dZ(e.updatedAt,t.updatedAt)}}function zx(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function Bx(e,t){const n=Fx(t)-Fx(e);return n!==0?n:e.title.localeCompare(t.title)}function cZ(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function dZ(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 Fx(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 uZ(e){return!!(e&&Hi(e.workspaceKind)&&!Li(e)&&e.provider!=="openpond")}function mZ(e,t){const n=bP(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function pZ({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:o,linkedProjectByAppId:r,providerSettings:s,selectedAppId:c,selectedSession:m,selectedSessionId:u,selectedSessionProjectId:f,setDiffPanelExpanded:g,setDraftModel:S,setDraftProvider:k,setError:C,setSelectedAppId:P,setSelectedProjectId:j,setSessions:R,setTerminalOpen:$,toast:O}){const M=y.useRef(null);y.useEffect(()=>{if(!c)return;const w=f??(u?null:r.get(c)??null);if(!w)return;const A=It("local",w);P(null),j(A),o(A)},[o,r,c,u,f,P,j]),y.useEffect(()=>{if(!O||O.persistent)return;const w=window.setTimeout(()=>{n({type:"clearToast",toastId:O.id})},O.durationMs??(O.tone==="error"?7e3:3500));return()=>window.clearTimeout(w)},[n,O]),y.useEffect(()=>{function w(A){(A.metaKey||A.ctrlKey)&&A.key==="`"&&(A.preventDefault(),$(E=>!E))}return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[$]),y.useEffect(()=>{g(!1)},[e,t,g]),y.useEffect(()=>{if(!u){M.current=null;return}if(!m||m.id!==u)return;const w=mZ(m,s);if(M.current===w)return;M.current=w;const A=bP(m,s);k(A.provider),S(A.model)},[s,m,u,S,k]),y.useEffect(()=>{!a||!m||!uZ(m)||Q.patchSession(a,m.id,{provider:"openpond"}).then(w=>{R(A=>A.map(E=>E.id===w.id?w:E)),k("openpond"),S(A=>er("openpond",A))}).catch(w=>{C(w instanceof Error?w.message:String(w))})},[a,m,S,k,C,R])}function fZ({connection:e,setError:t}){return y.useCallback(async(n,a,o)=>{if(!e){const r=new Error("OpenPond App server is not connected.");throw t(r.message),r}t(null);try{await Q.resolveApproval(e,n,{decision:a,answers:o})}catch(r){const s=r instanceof Error?r.message:String(r);throw t(s),r}},[e,t])}function hZ({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:o,pinnedProjects:r,projectRows:s,visibleProjectRows:c}){const m=y.useMemo(()=>p8(a,o),[a,o]),u=y.useMemo(()=>UP({provider:e,snapshot:n,preferences:t}),[e,t,n]),f=y.useMemo(()=>Array.from(new Set([...r,...c].filter(py).map(S=>S.project.id))),[r,c]);return{commandProjectRows:y.useMemo(()=>s,[s]),contextWindowStatus:u,pinnedRows:m,sidebarWorkspaceAppIds:f}}function gZ({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:o,setMentionedAppId:r}){return y.useCallback((s=null)=>{o?.();const c=s?.id?n.get(s.id)??null:null;if(c){const m=It("local",c);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 hA={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 doe(e){return`@${e.token}`}function vZ(e){return`@${kZ(e)}`}function bZ(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=Ss(a.flatMap(g=>g.capabilities.map(S=>S.id))),s=Ss(a.flatMap(g=>g.capabilityLabels)),c=Ss(a.flatMap(g=>g.connections.map(S=>S.id).filter(IZ))),m=Ss(a.map(g=>g.id)),u=Ss(a.map(g=>g.setupSurface)),f=xZ(n);return{provider:n,label:o.providerLabel,detail:s.length>0?s.slice(0,4).join(", "):o.description,token:f,tokens:SZ(a),ref:{kind:"integration",provider:n,appIds:m,setupSurfaces:u,...c.length>0?{connectionIds:c}:{},...r.length>0?{capabilities:r}:{}}}})}function uoe(e,t){const n=Wn(t);return e.filter(a=>n?a.tokens.some(o=>o.includes(n)):!0).slice(0,8)}function yZ(e,t){const n=wZ(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 moe(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=Wn(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 u=a.index+m,f=`@${o}`;n.push({detail:s.detail,displayText:vZ(s),end:u+f.length,label:s.label,provider:s.provider,start:u,text:f})}return n}function SZ(e){return Ss(e.flatMap(t=>[...hA[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Wn).filter(Boolean))}function xZ(e){return Wn(hA[e][0]??e)}function kZ(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function wZ(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Wn(t[1]??"")).filter(Boolean)}function Ss(e){return Array.from(new Set(e))}function IZ(e){return typeof e=="string"&&e.length>0}function _Z({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:o,selectedCloudProject:r,selectedProject:s,selectedSession:c,selectedSessionId:m}){const u=y.useMemo(()=>{const C=new Map;for(const P of e?.cloudProjects??[]){const j=C.get(P.teamId)??[];j.push(P.id),C.set(P.teamId,j)}return C},[e?.cloudProjects]),g=!!(c||o||s||r)?[]:n,S=y.useMemo(()=>bZ(t),[t]),k=y.useMemo(()=>kJ(a,m),[a,m]);return{chatMentionApps:g,cloudProjectIdsByTeam:u,connectedAppMentions:S,pendingApproval:k}}function CZ({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:o}){const r=y.useCallback(c=>{if(!e){o("Connect to OpenPond before saving preferences.");return}Q.savePreferences(e,{codexPermissionMode:c}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:m.preferences})}).catch(m=>{o(m instanceof Error?m.message:String(m))})},[e,t,n,a,o]),s=y.useCallback(c=>{if(!e){o("Connect to OpenPond before saving preferences.");return}Q.savePreferences(e,{codexReasoningEffort:c}).then(m=>{n(m.preferences.codexPermissionMode),a(m.preferences.codexReasoningEffort),t(u=>u&&{...u,preferences:m.preferences})}).catch(m=>{o(m instanceof Error?m.message:String(m))})},[e,t,n,a,o]);return{changeCodexPermissionMode:r,changeCodexReasoningEffort:s}}const RZ=6e4;function Iy(e,t){if(!e)return t;const n=AZ(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 vA(e,n)?e:n}function PZ(e,t){const n=Iy(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&vA(e,a)?e:a}function ic(e,t){let n=!1,a=!1;const o=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=Iy(r,t);return s!==r&&(a=!0),s});return n?a?o:e:[t,...e]}function mp(e,t){let n=!1,a=!1;const o=e.map(r=>{if(r.id!==t.id)return r;n=!0;const s=PZ(r,t);return s!==r&&(a=!0),s});return n?a?o:e:[t,...e]}function Kg(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 c=EZ(s,r,n,a);if(c)return c}return Iy(s,r)})}function Vx(e,t,n,a=Date.now()){const o=new Map(e.map(u=>[u.id,u])),r=new Map(Kg(e,t,n,a).map(u=>[u.id,u])),s=new Set(o.keys()),c=t.filter(u=>!s.has(u.id)).map(u=>r.get(u.id)??u),m=e.map(u=>{const f=r.get(u.id);return f||(gA(u,t)?u:null)}).filter(u=>!!u);return[...c,...m]}function gA(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=TZ(t);return a===null||n>=a}function Kx(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&&(bA(s,r)||(e[r.id]=a))}}function AZ(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function vA(e,t){return JSON.stringify(e)===JSON.stringify(t)}function TZ(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 EZ(e,t,n,a){const o=n[t.id];return o===void 0?null:a-o>RZ||bA(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function bA(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const yA=800,jZ=5e3,Wx=5e4,MZ=16,OZ=3e4,ca=new Map;function $Z(e,t){return ca.get(xA(e,t))?.payload??null}async function SA(e,t,n={}){const a=xA(e,t),o=ca.get(a),r=n.limit??yA,s=n.tail??!0;if(o?.promise)return o.promise;if(!n.force&&s&&o?.payload&&Date.now()-o.fetchedAt<=OZ)return Gx(a,o),o.payload;const c=!!(n.force&&s&&o?.payload),m=c?o?.payload?.events.at(-1)?.id:void 0,u=Q.codexHistoryThreadIncremental(e,t,{afterEventId:m,limit:r,revision:c?o?.revision:void 0,tail:s}).then(f=>{const g=ca.get(a)?.payload??o?.payload;if(f.unchanged){if(!g)throw new Error("Codex history revision matched without a cached thread.");return ca.set(a,{fetchedAt:Date.now(),payload:g,revision:f.revision}),Gx(a,ca.get(a)),g}const S={session:f.session,events:f.events},k=s&&g&&!f.reset?{...S,events:NZ(g.events,S.events)}:S;return ca.set(a,{fetchedAt:Date.now(),payload:k,revision:f.revision}),Jx(),k}).catch(f=>{throw ca.get(a)?.promise===u&&ca.delete(a),f});return ca.set(a,{fetchedAt:o?.fetchedAt??0,payload:o?.payload,promise:u,revision:o?.revision}),Jx(),u}function xA(e,t){return`${e.serverUrl}
|
|
194
|
+
${e.token}
|
|
195
|
+
${t}`}function Gx(e,t){ca.delete(e),ca.set(e,t)}function Jx(){for(;ca.size>MZ;){const e=ca.keys().next().value;if(!e)return;ca.delete(e)}}function NZ(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 DZ=500,HZ=2500,LZ=15e3;function qZ(e){return e.active?DZ:e.surface==="thread"?HZ:LZ}function _y(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function UZ(e={}){const t={cachedPayload:e.cachedPayload??$Z,clearTimer:e.clearTimer??(u=>globalThis.clearTimeout(u)),loadPayload:e.loadPayload??SA,now:e.now??Date.now,setTimer:e.setTimer??((u,f)=>globalThis.setTimeout(u,f))},n=new Map;let a=1;function o(u){const f=BZ(u.connection,u.sessionId);let g=n.get(f);g||(g={connection:u.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(u.connection,u.sessionId),nextRefreshAt:null,sessionId:u.sessionId,subscribers:new Map,timer:null},n.set(f,g));const S=a++;return g.subscribers.set(S,u),g.latestPayload&&u.onPayload(g.latestPayload),r(g,0),()=>{const k=n.get(f);if(k){if(k.subscribers.delete(S),k.subscribers.size>0){r(k,c(k));return}k.disposed=!0,m(k),n.delete(f)}}}function r(u,f){if(u.disposed||u.subscribers.size===0||u.inFlight)return;const g=t.now()+Math.max(0,f);u.timer&&u.nextRefreshAt!==null&&u.nextRefreshAt<=g||(m(u),u.nextRefreshAt=g,u.timer=t.setTimer(()=>{u.timer=null,u.nextRefreshAt=null,s(u)},Math.max(0,f)))}async function s(u){if(u.disposed||u.subscribers.size===0||u.inFlight)return;const f=t.loadPayload(u.connection,u.sessionId,{force:!!u.latestPayload});u.inFlight=f;try{const g=await f;if(u.disposed||g===u.latestPayload)return;u.latestPayload=g;for(const S of u.subscribers.values())S.onPayload(g)}catch(g){if(u.disposed)return;for(const S of u.subscribers.values())S.onError?.(g)}finally{u.inFlight===f&&(u.inFlight=null),u.disposed||r(u,c(u))}}function c(u){const f=[...u.subscribers.values()],g=f.some(k=>k.locallyActive||k.reportedActive)||u.latestPayload?.session.status==="active"||xy(u.latestPayload?.events??[])?.tone==="active",S=f.some(k=>k.surface==="thread")?"thread":"sidebar";return qZ({active:g,surface:S})}function m(u){u.timer&&t.clearTimer(u.timer),u.timer=null,u.nextRefreshAt=null}return{subscribe:o}}const zZ=UZ();function Cy(e){return zZ.subscribe(e)}function BZ(e,t){return`${e.serverUrl}
|
|
196
|
+
${e.token}
|
|
197
|
+
${t}`}function FZ({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:o,setError:r}){const[s,c]=y.useState({events:[],sessionId:null}),m=Kt(t)?t:null,u=m&&s.sessionId===m?s.events:[],f=y.useCallback(g=>{c(S=>{if(!m)return{events:[],sessionId:null};const k=S.sessionId===m?S.events:[];return{events:typeof g=="function"?g(k):g,sessionId:m}})},[m]);return y.useEffect(()=>{if(!e||!m){c(k=>k.sessionId===null&&k.events.length===0?k:{events:[],sessionId:null});return}r(k=>k==="Session not found"?null:k);const g=n;return Cy({connection:e,locallyActive:g,onError:k=>r(k instanceof Error?k.message:String(k)),onPayload:k=>{const C=_y(k,g);c(P=>P.sessionId!==m?{events:C.events,sessionId:m}:{events:eo(P.events,C.events),sessionId:m}),r(P=>P==="Session not found"?null:P),o(P=>mp(P,C.session))},reportedActive:a==="active",sessionId:m,surface:"thread"})},[e,m,n,a,o,r]),{codexHistoryEvents:u,setCodexHistoryEvents:f}}function kA(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 VZ({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:o,setCodexHistorySessions:r,setSessions:s,sidebarFileBookmarks:c,setSidebarFileBookmarks:m,setError:u}){const[f,g]=y.useState(null),[S,k]=y.useState(null),C=y.useRef(null),P=y.useRef(null);function j(A,E){A.dataTransfer.effectAllowed="move",A.dataTransfer.setData("text/plain",`${E.type}:${E.id}`),kA(A);const D=a.map(U=>U.key);C.current=E,P.current=D,g(E),k(D)}function R(){C.current=null,P.current=null,g(null),k(null)}function $(A,E){const D=C.current;if(!D)return;const U=cm(A),L=P.current??a.map(X=>X.key),J=dm(L,Ir(D),Ir(E),U);ux(L,J)||(P.current=J,k(J))}function O(A){if(!e)return;const E=a.map(Ie=>Ie.key),D=new Set(E),U=[...A.filter(Ie=>D.has(Ie)),...E.filter(Ie=>!A.includes(Ie))];if(ux(E,U))return;const L=t,J=new Map(n.map(Ie=>[Ie.id,Ie])),X=c,de=new Map(a.map(Ie=>[Ie.key,Ie]));o(Ie=>{const ne={...Ie};return U.forEach((je,Se)=>{const oe=de.get(je);oe?.type==="project"&&(ne[oe.id]={...ne[oe.id]??{},pinned:!0,archived:!1,order:Se})}),ne});const Me=Ie=>{const ne=new Map(Ie.map(oe=>[oe.id,oe])),je=U.map((oe,be)=>{const re=de.get(oe),ue=re?.type==="session"?ne.get(re.id):null;return ue?{...ue,order:be}:null}).filter(oe=>!!oe),Se=new Map(je.map(oe=>[oe.id,oe]));return Ie.map(oe=>Se.get(oe.id)??oe)};s(Me),r(Me),m(Ie=>{const ne=new Map;return U.forEach((je,Se)=>{const oe=de.get(je);oe?.type==="file"&&ne.set(oe.id,Se)}),Ie.map(je=>{const Se=ne.get(je.id);return Se===void 0?je:{...je,order:Se}})}),Promise.all(U.map((Ie,ne)=>{const je=de.get(Ie);return je?je.type==="project"?Q.patchSidebarAppPreference(e,je.id,{pinned:!0,archived:!1,order:ne}):je.type==="session"?Q.patchSession(e,je.id,{order:ne}):Q.patchSidebarFile(e,{workspaceKind:je.file.workspaceKind,workspaceId:je.file.workspaceId,workspaceName:je.file.workspaceName,path:je.file.path,status:"pinned",order:ne,sourceSessionId:je.file.sourceSessionId}):Promise.resolve(null)})).catch(Ie=>{u(Ie instanceof Error?Ie.message:String(Ie)),o(L);const ne=je=>je.map(Se=>J.get(Se.id)??Se);s(ne),r(ne),m(X)})}function M(A,E){const D=C.current;if(D){const U=P.current??a.map(J=>J.key),L=dm(U,Ir(D),Ir(E),cm(A));O(L)}R()}function w(){C.current&&O(P.current??a.map(E=>E.key)),R()}return{dragItem:f,pinnedPreviewKeys:S,startPinnedDrag:j,clearSidebarDrag:R,previewPinnedDrop:$,commitPinnedDrop:M,commitPinnedPreviewDrop:w}}function KZ({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:o}){const[r,s]=y.useState(null),[c,m]=y.useState(null),u=y.useRef(null),f=y.useRef(null);function g(R,$){R.dataTransfer.effectAllowed="move",R.dataTransfer.setData("text/plain",`session:${$.sessionId}`),kA(R),u.current=$,f.current=$.visibleSessionIds,s($.sessionId),m($.visibleSessionIds)}function S(R,$){const O=u.current;if(!O)return;const M=f.current??O.visibleSessionIds,w=dm(M,O.sessionId,$,cm(R));WZ(M,w)||(f.current=w,m(w))}function k(){u.current=null,f.current=null,s(null),m(null)}function C(R,$){const O=u.current;if(!O){k();return}const M=f.current??O.visibleSessionIds,w=dm(M,O.sessionId,$,cm(R));j(bx(O.allSessionIds,O.visibleSessionIds,w)),k()}function P(){const R=u.current;R&&j(bx(R.allSessionIds,R.visibleSessionIds,f.current??R.visibleSessionIds)),k()}function j(R){const $=new Map(R.map((A,E)=>[A,E])),O=new Map(t.map(A=>[A.id,A.order])),M=R.filter((A,E)=>O.get(A)!==E);if(M.length===0)return;const w=A=>A.map(E=>{const D=$.get(E.id);return D===void 0||D===E.order?E:{...E,order:D}});o(w),n(w),e&&Promise.all(M.map(A=>Q.patchSession(e,A,{order:$.get(A)}))).catch(A=>{const E=D=>D.map(U=>{const L=O.get(U.id);return L===void 0||L===U.order?U:{...U,order:L}});o(E),n(E),a(A instanceof Error?A.message:String(A))})}return{clearTaskDrag:k,commitTaskDrop:C,commitTaskPreviewDrop:P,previewTaskDrop:S,startTaskDrag:g,taskDragSessionId:r,taskPreviewSessionIds:c}}function WZ(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function Zx({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=GZ(t);return{id:r,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:o,turnId:r,...s.length>0?{attachments:s}:{}}}function wA(e,t){return!t||IA(e,t)?e:[...e,t]}function IA(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 c=Date.parse(s.timestamp);if(!Number.isFinite(o)||!Number.isFinite(c)||c>=o)return!0}return!1}function GZ(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}function ye(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 tr(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 go(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function JZ(e,t,n){if(t.name==="workspace_action_result"){const a=go(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:Wg([...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 ZZ(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=Re(e.data),n=Re(e.args),a=ye(n,["actionName"])??ye(Re(n?.input),["actionName"])??Oh(t)??Oh(Re(t?.run))??Oh(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),c=Re(t?.actionSummary)??Re(r?.actionSummary)??Re(s?.actionSummary),m=Re(t?.action)??c??Re(s?.selectedAction)??null,u=Re(t?.responseSummary)??Re(r?.responseSummary)??Re(s?.responseSummary),f=Re(t?.sourceSummary)??Re(r?.sourceSummary)??Re(s?.sourceSummary),g=Re(t?.traceSummary)??Re(r?.traceSummary)??Re(s?.traceSummary),S=Re(t?.evalSummary)??Re(r?.evalSummary)??Re(s?.evalSummary),k=Wg([...Qi("artifact",t?.artifactRefs,"Artifact"),...Qi("artifact",m?.artifactRefs,"Artifact"),...Qi("artifact",c?.artifactRefs,"Artifact"),...Qi("artifact",u?.artifactRefs,"Artifact"),...Qi("trace",t?.traceArtifactRefs,"Trace"),...Qi("trace",g?.artifactRefs,"Trace"),...Qi("eval",t?.evalResultArtifactRefs,"Eval"),...Qi("eval",S?.artifactRefs,"Eval"),...Qi("output",t?.outputRefs,"Output")]),C=ye(f,["sourceRef","ref"]);return C&&k.push({id:Gg("source",C),kind:"source",label:"Source",target:C}),{actionName:a,title:ye(m,["label","title","name"])??ye(s,["selectedActionLabel"])??nY(a),status:YZ(e,u,r),responseText:ye(u,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ye(r,["id","runId"])??ye(t,["runId","agentRunId"])??null,projectId:ye(r,["projectId"])??ye(t,["projectId"])??ye(n,["projectId"])??null,agentId:ye(r,["agentId"])??ye(t,["agentId"])??ye(n,["agentId"])??null,agentName:ye(Re(m?.implementation),["agentName"])??ye(m,["agentName"])??ye(s,["selectedAgentName"])??null,sandboxId:ye(r,["sandboxId"])??ye(t,["sandboxId"])??ye(Re(t?.sandbox),["id"])??ye(Re(t?.createdSandbox),["id"])??ye(n,["sandboxId"])??null,runtimeId:ye(r,["runtimeId"])??ye(t,["runtimeId"])??null,implementationType:ye(t,["implementationType"])??ye(m,["implementationType","type","kind"])??ye(Re(m?.implementation),["type","kind"])??ye(s,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:C,manifestHash:ye(f,["manifestHash"])??ye(t,["manifestHash"])??ye(s,["manifestHash"])??null,refs:Wg(k),childCalls:XZ(t,r,s)}}function Oh(e){return e?ye(e,["actionName","name"])??ye(Re(e.action),["actionName","name"])??ye(Re(e.actionSummary),["actionName","name"])??ye(Re(e.selectedEntrypoint),["name"]):null}function YZ(e,t,n){if(e.status==="failed")return"failed";const a=ye(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const o=ye(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 Qi(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(o=>{const r=QZ(e,o,n);return r?[r]:[]})}function QZ(e,t,n){if(typeof t=="string"&&t.trim()){const s=t.trim();return{id:Gg(e,s),kind:e,label:n,target:s}}const a=Re(t);if(!a)return null;const o=ye(a,["url","webUrl","artifactPath","path","ref"])??ye(Re(a.artifact),["url","webUrl","path","ref"]);if(!o)return null;const r=ye(a,["label","title","name","type","kind"])??n;return{id:Gg(e,o),kind:e,label:r,target:o}}function Wg(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 Gg(e,t){return`${e}:${t}`}function XZ(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(o=>eY(o)).slice(0,6)}function eY(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const o=Re(n);if(!o)return[];const r=ye(o,["id","runId","callId"])??`child_${a+1}`,s=ye(o,["label","title","actionName","name","tool"])??ye(Re(o.action),["label","name"])??"Implementation call",c=ye(o,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:r,label:s,status:tY(o),detail:c}]})}function tY(e){const t=ye(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function nY(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const aY=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function _A(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:aY.has(t.slice(n).toLowerCase())}function CA(e){return e.split("/").filter(Boolean).pop()??e}function iY(e){if(!Zg(e))return;const t=Re(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??_r(e.data)??_r(e.args)??_r(e.output);if(!(!a||!_A(a)))return{path:a,appId:e.appId??null,title:CA(a)}}function oY(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return Jg(e.data,t,n),t.slice(0,12)}function Jg(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const c of e)Jg(c,t,n,a+1);return}const o=Re(e);if(!o)return;const r=ye(o,["path","artifactRef"]),s=ye(o,["contentType","mimeType"]);r&&s&&!n.has(r)&&(n.add(r),t.push({path:r,title:ye(o,["title","name"])??CA(r),contentType:s,sizeBytes:typeof o.sizeBytes=="number"?o.sizeBytes:null}));for(const c of Object.values(o))Jg(c,t,n,a+1)}function Zg(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,ye(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ye(Re(t?.input),["tool","toolName","tool_name","name"]),ye(Re(t?.arguments),["tool","toolName","tool_name","name"]),ye(Re(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function _r(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if($h(n)&&_A(e.trim()))return e.trim();const o=tr(e);if(o!==null){const r=_r(o,t+1,n);if(r)return r}return rY(e)}if(Array.isArray(e)){for(const o of e){const r=_r(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(!$h(o))continue;const s=_r(r,t+1,o);if(s)return s}for(const[o,r]of Object.entries(a)){if($h(o))continue;const s=_r(r,t+1,o);if(s)return s}return null}function $h(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function rY(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 sY(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=cY(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 lY(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=RA(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 cY(e){return RA(e).providerLabel}function RA(e){const t=Re(e.args),n=Re(e.data),a=Re(n?.result),o=Pm(ye(t,["provider"])??ye(a,["provider"])??ye(n,["provider"])??void 0),r=ye(a,["providerLabel"])??ye(n,["providerLabel"])??(o?Pv(o)?.label:null)??"connected app",s=ye(t,["operation"]),c=ye(a,["operation"])??ye(n,["operation"]),m=Nh(t?.capabilityIds)||Nh(a?.capabilityIds)||Nh(n?.capabilityIds);return{providerLabel:r,providerOperation:s,operation:c,capabilityCount:m}}function Nh(e){return Array.isArray(e)?e.length:0}function PA(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()||Dh(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:Dh("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:Dh("goal_context")}:null}function Dh(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function pp(e){return e.name==="diagnostic"&&Re(e.data)?.kind==="goal_context"}const dY="Steered by user";function uY(e){return e?.trim().toLowerCase()===dY.toLowerCase()}function mY(e,t){if(!t.turnId)return;vY(e,t.turnId);const n=pY(t);if(!n)return;const a=gY(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 pY(e){const t=Re(e.data),n=Re(t?.activity);return n?fY(n,e):hY(e,t)}function poe(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 · ${xY(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function fY(e,t){const n=Pi(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":Pi(e.result,["no_action","routed","applied","retained"]),o=Zn(e.reason)??t.output??t.error??null;return{state:n,visibility:Pi(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Zn(e.workspaceId),decision:Pi(e.decision,["no_action","route","propose"]),route:Zn(e.route),operation:Pi(e.operation,["create","update","delete"]),target:Zn(e.target),summary:Zn(e.summary)??AA(n,a),expectedOutcome:Zn(e.expectedOutcome),reason:o,evidenceBasis:bY(e.evidenceBasis),critiqueStatus:Pi(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:Pi(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:yY(e.validationReceipts),edits:SY(e.edits),refs:{trigger:Ri(e.trigger),outcome:Ri(e.outcome),proposal:Ri(e.proposal),applyReceipt:Ri(e.applyReceipt),advanceReceipt:Ri(e.advanceReceipt),inputHarness:Ri(e.inputHarness),outputHarness:Ri(e.outputHarness)}}}function hY(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,c=Zn(t?.workspaceAdvance),m=n?"failed":a?r?c==="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:Zn(o?.route),operation:null,target:null,summary:AA(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:Ri(t?.trigger),outcome:Ri(o),proposal:Ri(r),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function gY(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 vY(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 bY(e){const t=Re(e),n=Pi(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:Yx(t.supportingEvidenceIds),counterevidence:Yx(t.counterevidence)}}function yY(e){return Array.isArray(e)?e.flatMap(t=>{const n=Re(t),a=Zn(n?.id),o=Pi(n?.status,["passed","failed","blocked","skipped"]),r=Zn(n?.summary);return a&&o&&r?[{id:a,status:o,summary:r}]:[]}):[]}function SY(e){return Array.isArray(e)?e.flatMap(t=>{const n=Re(t),a=Zn(n?.id),o=Pi(n?.operation,["create","update","delete"]),r=Zn(n?.target),s=Zn(n?.summary);return!a||!o||!r||!s?[]:[{id:a,operation:o,target:r,summary:s,content:typeof n?.content=="string"?n.content:null}]}):[]}function Ri(e){const t=Re(e),n=Zn(t?.id),a=Zn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function Yx(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Zn(e){return typeof e=="string"&&e.trim()?e.trim():null}function Pi(e,t){return typeof e=="string"&&t.includes(e)?e:null}function AA(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 xY(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const Qx=64*1024,Xx=8*1024;function ek(e,t){const n=TA(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=kY(e,t.turnId);if(a){a.activities=_Y(a.activities??[],t,n),a.timestamp=t.timestamp;return}Du(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Du(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 kY(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 Yg(e,t,n){if(!t.turnId)return;const a=e.filter(c=>c.role==="activity_group"&&c.turnId===t.turnId&&!c.activities?.some(m=>m.subagentMessage)),o=a.filter(c=>c.traceState==="running"),r=o.length>0?o:a.length>0?[a[a.length-1]]:[];for(const c of r)c.traceState=n;const s=r.at(-1);s&&(s.traceCompletedAt=t.timestamp,s.timestamp=t.timestamp)}function wY(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)}Yg(e,t,"interrupted"),!uY(t.output)&&e.push({id:t.id,role:"status_divider",content:IY(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function IY(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 _Y(e,t,n=TA(t)){const a=[...e];return $Y(a,t,n)||jY(a,t,n)||MY(a,t,n)||OY(a,t,n)?a:[...a,n]}function CY(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function RY(e,t){const n={id:t.id,role:"status_divider",content:PY(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:AY(t),statusTone:TY(t)};if(t.name!=="session.compaction.started"){const a=go(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 PY(e){const t=EY(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 AY(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function TY(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function EY(e){return Re(e.data)?.reason==="auto"?"auto":"manual"}function TA(e){const t=iY(e),n=e.name==="assistant.reasoning.delta"?"reasoning":VY(e),a=KY(e),o=JY(e),r=GY(e),s=ZY(e),c=YY(e),m=oY(e);return{id:e.id,label:c?c.direction==="received"?"Child message received":"Child message sent":HY(e),content:c?.summary??qY(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:Ry(e)??void 0}:{},...n&&e.name==="command.output"?{detail:Qg(e)}:{},...n==="command"?{terminal:aQ(e)}:{},...r?{meta:r}:{},...o?{receipt:o}:{},...s?{openSession:s}:{},...c?{subagentMessage:c}:{},state:DY(e),...t?{imagePreview:t}:{},...m.length>0?{artifacts:m}:{}}}function jY(e,t,n){if(t.name==="tool.completed"){const a=tk(e,t);if(!a)return!1;const o=iQ(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=Qg(t);return r&&r!==a.content&&(a.detail=vm(a.detail,r)),!0}if(t.name==="command.output"){const a=tk(e,t);if(!a)return!1;const o=Qg(t);return o&&(a.detail=vm(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 MY(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=Ry(t),o=go(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=vm(o.detail,r)),n.detail&&(o.detail=vm(o.detail,n.detail)),o.meta=n.meta,o.receipt=n.receipt,o.imagePreview=n.imagePreview??o.imagePreview,o.artifacts=n.artifacts,!0}function OY(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=NY(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 $Y(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 tk(e,t){const n=Ry(t);if(n){const a=go(e,o=>o.kind==="command"&&o.callId===n);if(a)return a}return go(e,a=>a.kind==="command")}function NY(e,t){const n=t.action??"",a=EA[n]??{started:"Running workspace action"};return go(e,o=>o.state==="running"&&o.label===a.started&&o.kind!=="command"&&!o.controlKind)}function DY(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 HY(e){if(e.name==="assistant.reasoning.delta")return ye(Re(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(pp(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(Zg(e)&&e.name==="tool.started")return"Reading image";if(Zg(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=sY(e);if(t)return t;const n=zY(e);if(n)return n;const a=UY(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"?LY(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 EA={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 LY(e){const t=e.action??"",n=EA[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 qY(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=PA(e.output??"");if(n)return n.text;if(pp(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=BY(e);if(a)return a;const o=FY(e);if(o)return o;const r=lY(e);if(r)return r;const s=jA(e);if(s)return s;if(e.name==="command.output")return OA(e.output??"");if(e.name==="tool.started"||e.name==="tool.completed"){const c=e.data;if(c&&typeof c=="object"){const m=c.command;if(typeof m=="string"&&m.trim())return m;const u=c.tool;if(typeof u=="string"&&u.trim())return u;const f=c.type;if(typeof f=="string"&&f.trim())return f}}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 UY(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 zY(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 BY(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=Re(Re(e.data)?.result),n=ye(t,["output"]);if(n)return n;const a=Re(tr(e.output??"")),o=ye(a,["output"]);if(o)return o;const r=Re(e.args),s=ye(r,["url"]);return s||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function FY(e){if(e.action!=="openpond_create_improve")return null;const t=Re(Re(e.data)?.result),n=ye(t,["nextStep"]);if(n)return n;const a=Re(tr(e.output??"")),o=ye(a,["output"]);if(o)return o;const r=Re(e.args),s=ye(r,["reason"]);if(s)return s;const c=ye(r,["objective"]);return c||(e.error??null)}function VY(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=Re(e.data),n=ye(t,["type"]),a=ye(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||jA(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function KY(e){if(e.name==="turn.interrupted")return"turn_aborted";if(pp(e))return"goal_context"}function jA(e){const t=Re(e.data),n=ye(t,["type"]),a=ye(t,["tool","toolName","tool_name","name","functionName","function_name"]),o=Re(t?.result),r=Re(tr(e.output??"")),s=Re(r?.data),c=ye(t,["command","cmd"])??ye(Re(t?.input),["command","cmd"])??ye(Re(t?.arguments),["command","cmd"])??ye(Re(t?.args),["command","cmd"])??WY(ye(t,["arguments","args","input"]))??ye(Re(e.args),["command","cmd"])??ye(o,["command","cmd"])??ye(s,["command","cmd"]);return c||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function WY(e){if(!e)return null;const t=tr(e),n=Re(t);return ye(n,["command","cmd"])}function Ry(e){const t=Re(e.data);return ye(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function GY(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(eQ(o));const r=Re(t.workspaceExecutionTarget),s=ye(r,["target"]);if(s==="sandbox"){const u=r?.hybrid===!0,f=ye(r,["sandboxId","workspaceId"]);n.push(`${u?"Hybrid ":""}sandbox${f?` ${nk(f)}`:""}`)}else s==="local"&&n.push("local workspace");const c=Re(t.sourcePreservation);if(c?.attempted===!0)if(c.ok!==!0)n.push("checkpoint failed");else if(c.preserved===!0){const u=ye(c,["preservedSha"]);n.push(u?`checkpoint ${nQ(u)}`:"checkpoint saved")}else n.push("checkpoint clean");const m=MA(t);return m&&(n.push(`receipt ${nk(m.id)}`),n.push(`${tQ(m.totalUsd)} ${m.status}`)),n.length>0?n.join(" · "):null}function JY(e){const t=MA(Re(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function ZY(e){if(!e.name.startsWith("subagent."))return;const t=Re(e.data),n=Re(t?.run),a=ye(t,["childSessionId"])??ye(n,["childSessionId"]);if(!a)return;const o=ye(n,["roleId"])??ye(t,["roleId"]),r=ye(n,["status"])??ye(t,["status"]);return{sessionId:a,label:"Open conversation",...o?{roleId:o}:{},...r?{status:r}:{}}}function YY(e){if(e.name!=="subagent.message")return;const t=Re(e.data),n=Re(t?.message);if(!n)return;const a=ye(n,["id"]),o=ye(n,["kind"]),r=ye(n,["fromRunId"]),s=ye(n,["body"]);if(!a||!o||!r||!s)return;const c=Re(t?.delivery??n.delivery),m=Re(t?.modelRef),u=ye(m,["providerId"]),f=ye(m,["modelId"]),S=ye(c,["deliveredParentSessionId"])===e.sessionId&&!r.startsWith("parent:")?"received":"sent",k=Array.isArray(n.refs)?n.refs.flatMap(C=>{const P=Re(C),j=ye(P,["kind"]),R=ye(P,["id"]),$=ye(P,["label"]);return j&&R&&$?[{kind:j,id:R,label:$}]:[]}):[];return{direction:S,summary:QY(s),body:s,messageId:a,kind:o,fromRunId:r,toRunId:ye(n,["toRunId"]),toRole:ye(n,["toRole"]),childSessionId:ye(t,["childSessionId"]),roleId:ye(t,["roleId"]),modelRef:u&&f?{providerId:u,modelId:f}:null,deliveryStatus:ye(c,["status"]),wakeReason:ye(c,["wakeParentReason"]),createdAt:ye(n,["createdAt"]),refs:k}}function QY(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return XY(n,96)}function XY(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 MA(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=ye(o,["id"]),s=ye(o,["status"]),c=ye(o,["totalUsd","retailTotalUsd"]);if(r&&s&&c)return{id:r,status:s,totalUsd:c}}return null}function eQ(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function tQ(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function nQ(e){return e.length>12?e.slice(0,12):e}function nk(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function OA(e){let t=e.replace(/\r\n/g,`
|
|
198
|
+
`).trim();if(!t)return"";const n=oQ(t);if(n!==null)return zs(n);const a=`
|
|
199
|
+
Output:
|
|
200
|
+
`,o=t.indexOf(a);return o>=0&&rQ(t.slice(0,o))&&(t=t.slice(o+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),zs(t.trim())}function Qg(e){const t=OA(e.output??"");if(t)return t;const n=Re(Re(e.data)?.result);return n?zs($A(n)):""}function aQ(e){const t=Re(e.data),n=Re(t?.result),a=Re(tr(e.output??"")),o=Re(a?.data),r=Re(t?.workspaceToolTiming),s=[n?.exitCode,o?.exitCode,t?.exitCode].find(m=>typeof m=="number"),c=r?.durationMs;return{...typeof s=="number"?{exitCode:s}:{},...typeof c=="number"?{durationMs:c}:{}}}function iQ(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function oQ(e){const t=Re(tr(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?$A(a,ye(t,["output"])):typeof t.output=="string"?t.output.trim():""}function $A(e,t=null){const n=ye(e,["stdout"])?.replace(/\r\n/g,`
|
|
201
|
+
`).trimEnd()??"",a=ye(e,["stderr"])?.replace(/\r\n/g,`
|
|
202
|
+
`).trimEnd()??"",o=[n,a].filter(Boolean);return o.length>0?o.join(`
|
|
203
|
+
`):t?.replace(/\r\n/g,`
|
|
204
|
+
`).trim()??""}function rQ(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function vm(e,t){const n=e??"";if(!n)return zs(t);if(n===t||n.includes(t))return n;if(t.includes(n))return zs(t);const a=n.endsWith(`
|
|
205
|
+
`)||t.startsWith(`
|
|
206
|
+
`)?"":`
|
|
207
|
+
`;return zs(`${n}${a}${t}`)}function zs(e){if(e.length<=Qx)return e;const t=`
|
|
208
|
+
|
|
209
|
+
… output omitted from live view; full output remains in task history …
|
|
210
|
+
|
|
211
|
+
`,n=Math.max(0,Qx-Xx-t.length);return`${e.slice(0,Xx)}${t}${e.slice(-n)}`}const sQ=/\bopenpond\s+opchat\b/i,lQ=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function NA(e){const t=e?.trim()||"Turn failed";return sQ.test(t)&&lQ.test(t)?"Server connection lost. Retry your message.":t}function cQ(e,t){if((pu(t,"code")??pu(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(pu(a,"code")??pu(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 pu(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function dQ(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(c=>c.subagentMessage))continue;const o=uQ(a.activities??[]);if(o.length===0){a.deliverables=void 0;continue}const r=t.get(a.turnId)??"",s=r?mQ(o,r):[];if(s.length>0){a.deliverables=s;continue}a.deliverables=n.has(a.turnId)?[o[o.length-1]]:void 0}}function uQ(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 mQ(e,t){const n=DA(t);return e.filter(a=>pQ(a).some(o=>t.includes(o)||n.includes(o)))}function pQ(e){const t=new Set;for(const n of[e.path,e.title,fQ(e.path)]){const a=n.trim();a&&(t.add(a),t.add(DA(a)))}return[...t]}function fQ(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function DA(e){try{return decodeURIComponent(e)}catch{return e}}const HA=8;function hQ(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=ev(e.data),n=e.output?ev(tr(e.output)):null;return gQ(t??n)}function Xg(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const o of[...e??[],...t]){const r=LA(o.url);if(!(!r||a.has(r))&&(a.add(r),n.push(o),n.length>=HA))break}return n.length>0?n:void 0}function ev(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:ye(n,["url"])?[n]:null;if(a)return{provider:ye(n,["provider"]),results:a};for(const o of["result","data","output"]){const r=ev(n[o],t+1);if(r)return r}return null}function gQ(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const o=vQ(e.results[a],a,e.provider);if(!o)continue;const r=LA(o.url);if(!(!r||n.has(r))&&(n.add(r),t.push(o),t.length>=HA))break}return t}function vQ(e,t,n){const a=Re(e);if(!a)return null;const o=ye(a,["url","href"]);if(!o||!bQ(o))return null;const r=ye(a,["title"])??ak(o)??`Source ${t+1}`;return{id:ye(a,["id"])??`source_${t+1}`,title:r,url:o,sourceName:ye(a,["sourceName","source_name","source"])??ak(o),snippet:ye(a,["snippet","description"]),provider:n,faviconUrl:yQ(ye(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??SQ(o),publishedAt:ye(a,["publishedAt","published_at"]),updatedAt:ye(a,["updatedAt","updated_at"])}}function bQ(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function LA(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function yQ(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 SQ(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function ak(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}const ik=new WeakMap;function fp(e){const t=ik.get(e);if(t)return t;const n=xQ(e);return ik.set(e,n),n}function xQ(e){const t=[],n=new Set,a=new Map;for(const o of e){if(o.name==="task.input"){const r=qR.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"){Du(t,o),kQ(t,o);const r=CQ(o.args);if(r){const s=PA(r);if(s){ek(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:RQ(o.args),timestamp:o.timestamp,turnId:o.turnId});const c=rk(o.args);c&&t.push({id:`${o.id}:create-improve`,role:"assistant",timestamp:o.timestamp,turnId:o.turnId,createImproveRun:c})}continue}if(o.name==="create_improve.updated"){const r=rk(o.data);if(!r)continue;const s=go(t,c=>c.turnId===o.turnId&&!!c.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;Du(t,o);const s=Re(o.data);if(s?.retainedHistory===!0&&typeof s.nativeMessageId=="string"){const m=s.nativeMessageId,u=t.find(f=>f.id===m);u?(u.content=r,u.timestamp=o.timestamp):t.push({id:m,role:"assistant",content:r,timestamp:o.timestamp,turnId:o.turnId});continue}const c=t[t.length-1];if(c?.role==="assistant"&&c.turnId===o.turnId&&!c.createImproveRun)c.content=`${c.content??""}${r}`,c.timestamp=o.timestamp,c.sources=Xg(c.sources,ok(a,o.turnId)??[]);else{const m=ok(a,o.turnId);t.push({id:o.id,role:"assistant",content:r,timestamp:o.timestamp,turnId:o.turnId,...m?.length?{sources:m}:{}})}continue}if(o.name==="assistant.reasoning.delta"){const r=o.output??"";if(!r)continue;Du(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=I$.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=_$.safeParse(r?.resolution);if(!s.success)continue;const c=go(t,m=>m.userQuestion?.id===s.data.questionId);if(!c?.userQuestion||c.userQuestion.status!=="pending")continue;c.userQuestion={...c.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},c.timestamp=o.timestamp;continue}if(o.name==="turn.completed"){Yg(t,o,"completed");continue}if(o.name==="turn.failed"){Yg(t,o,"failed");const r=o.error??"Turn failed",s=cQ(r,o.data);t.push({id:o.id,role:"error",content:NA(r),...s?{errorKind:s}:{},timestamp:o.timestamp,turnId:o.turnId});continue}if(o.name==="turn.interrupted"){wY(t,o);continue}if(CY(o)){RY(t,o);continue}if(o.name.startsWith("harness.refiner.")){mY(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.")||pp(o)){if(IQ(o))continue;const r=ZZ(o);if(r){JZ(t,o,r);continue}const s=hQ(o);s.length>0&&wQ(t,a,o.turnId,s),ek(t,o)}if(o.name==="workspace.diff"){const r=_Q(o.data);if(!r||r.filesChanged===0)continue;const s=go(t,c=>c.role==="assistant"&&c.turnId===o.turnId);s&&(s.changeSummary=r,s.timestamp=o.timestamp)}}return dQ(t),t}function kQ(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 wQ(e,t,n,a){if(!n)return;const o=e[e.length-1];if(o?.role!=="assistant"||o.turnId!==n){t.set(n,Xg(t.get(n),a));return}o.sources=Xg(o.sources,a)}function ok(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function IQ(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 _Q(e){const t=HN.safeParse(e);return t.success?t.data:null}function CQ(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function RQ(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=yq.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function rk(e){const t=Re(e);if(!t)return null;const n=Yc.safeParse(t.createImproveRun);return n.success?n.data:null}function foe(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 hoe(e){const t=qA(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function goe(e){const t=qA(e);return t?t.toLocaleString():""}function qA(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function PQ(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[o,r]=y.useState({}),s=y.useCallback(m=>{r(u=>({...u,[m.sessionId]:m}))},[]);y.useEffect(()=>{r(m=>{let u=m;for(const[f,g]of Object.entries(m)){const S=fp(Id(n,f));IA(S,g)&&(u===m&&(u={...m}),delete u[f])}return u})},[n]);const c=y.useMemo(()=>wA(t,a?o[a]:null),[t,o,a]);return{pendingChatUserMessages:o,recordPendingChatUserMessage:s,visibleChatMessages:c}}function AQ({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:o,setSessions:r}){return{changeOpenPondCommandAccessMode:y.useCallback((c,m=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const u=m?.provider==="codex"?null:m;Q.savePreferences(e,{openPondCommandAccessMode:c}).then(f=>{o(f.preferences.openPondCommandAccessMode),n(g=>g&&{...g,preferences:f.preferences})}).catch(f=>{a(f instanceof Error?f.message:String(f))}),u&&Q.patchSession(e,u.id,{openPondCommandAccessMode:c}).then(f=>{r(g=>g.map(S=>S.id===f.id?f:S))}).catch(f=>{a(f instanceof Error?f.message:String(f))})},[e,t,n,a,o,r])}}function TQ({localProjects:e,cloudProjects:t,sessions:n,runtimeIndexes:a,appPreferences:o,selectedSessionId:r,selectedProjectId:s,archivedChatsOpen:c,projectsExpanded:m,chatRowsVisibleCount:u,sidebarFileBookmarks:f=[]}){const g=y.useMemo(()=>e.filter(le=>!le.hiddenFromDefaultSidebar),[e]),S=y.useMemo(()=>n.filter(le=>!le.archived&&sk(le)),[n]),k=y.useMemo(()=>S.filter(le=>le.pinned),[S]),C=y.useMemo(()=>S.filter(le=>!!le.savedForLater),[S]),P=y.useMemo(()=>n.filter(le=>le.archived&&sk(le)),[n]),j=y.useMemo(()=>new Set(e.map(le=>le.id)),[e]),R=y.useMemo(()=>new Set(t.map(le=>le.id)),[t]),$=y.useMemo(()=>xP(e),[e]),O=y.useMemo(()=>{const le={};for(const xe of[...S,...P]){const Ue=px(xe,j,$,R);Ue&&(le[xe.id]=Ue)}return le},[S,P,R,j,$]),M=y.useMemo(()=>S.filter(le=>!le.pinned&&!le.savedForLater&&!le.appId&&!O[le.id]),[S,O]),w=y.useMemo(()=>P.filter(le=>!le.appId&&!px(le,j,$,R)),[P,R,j,$]),A=y.useMemo(()=>{const le={};for(const xe of S){if(xe.pinned||xe.savedForLater)continue;const Ue=O[xe.id];if(!Ue)continue;const Ze=le[Ue];Ze?Ze.push(xe):le[Ue]=[xe]}return le},[S,O]),E=y.useMemo(()=>{const le={};for(const xe of n){if(xe.archived||!UA(xe))continue;const Ue=le[xe.parentSessionId];Ue?Ue.push(xe):le[xe.parentSessionId]=[xe]}for(const xe of Object.values(le))xe.sort((Ue,Ze)=>Date.parse(Ze.updatedAt)-Date.parse(Ue.updatedAt));return le},[n]),D=y.useMemo(()=>g.map((le,xe)=>{const Ue=It("local",le.id),Ze=$J(le,t);return{id:Ue,kind:"local",project:le,pinned:!!o[Ue]?.pinned,order:o[Ue]?.order??xe,cloudLinkTrusted:!Ze,cloudLinkWarning:Ze}}).sort(Hh),[o,t,g]),U=y.useMemo(()=>t.map((le,xe)=>{const Ue=It("cloud",le.id);return{id:Ue,kind:"cloud",project:le,pinned:!!o[Ue]?.pinned,order:o[Ue]?.order??xe,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(Hh),[o,t]),L=y.useMemo(()=>new Set(g.map(le=>Ba(le,t)?.id??null).filter(le=>!!le)),[t,g]),J=y.useMemo(()=>U.filter(le=>!L.has(le.project.id)),[U,L]),X=y.useMemo(()=>[...D,...J].sort(Hh),[J,D]),de=y.useMemo(()=>X.filter(le=>le.pinned),[X]),Me=y.useMemo(()=>f.filter(le=>le.status==="pinned"),[f]),Ie=y.useMemo(()=>f.filter(le=>le.status==="saved_for_later"),[f]),ne=X,je=y.useMemo(()=>EQ(ne,m,s),[ne,m,s]),Se=y.useMemo(()=>[...de.map(le=>({type:"project",key:Ir({type:"project",id:le.id}),id:le.id,item:le,order:le.order})),...k.map(le=>({type:"session",key:Ir({type:"session",id:le.id}),id:le.id,session:le,order:le.order})),...Me.map((le,xe)=>({type:"file",key:Ir({type:"file",id:le.id}),id:le.id,file:le,order:le.order??de.length+k.length+xe}))].sort((le,xe)=>{if(le.order!==xe.order)return le.order-xe.order;if(le.type!==xe.type){const it={project:0,session:1,file:2};return it[le.type]-it[xe.type]}const Ue=le.type==="project"?le.item.project.name:le.type==="session"?le.session.title:le.file.path,Ze=xe.type==="project"?xe.item.project.name:xe.type==="session"?xe.session.title:xe.file.path;return Ue.localeCompare(Ze)}),[Me,de,k]),oe=y.useMemo(()=>c?[...M,...w]:M,[c,w,M]),be=y.useMemo(()=>oe.slice(0,Math.max(Hn,u)),[oe,u]),re=y.useMemo(()=>Id(a,r),[a,r]),ue=y.useMemo(()=>fp(re),[re]),ke=aA(a,r),Le=iA(a,r),we=xJ(a,r);return{activeSessions:S,pinnedSessions:k,savedForLaterSessions:C,pinnedFiles:Me,savedForLaterFiles:Ie,chatSessions:M,archivedSessions:P,pinnedProjects:de,pinnedItems:Se,projectRows:ne,localProjectRows:D,visibleProjectRows:je,cloudProjectRows:J,projectSessionRowsByProjectId:A,childSessionRowsByParentId:E,sidebarProjectIdBySessionId:O,chatRows:oe,visibleChatRows:be,sessionEvents:re,chatMessages:ue,contextUsage:ke,goalRuntime:Le,subagentRuntime:we}}function sk(e){return UA(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function UA(e){return!!(e.parentSessionId&&e.subagentRunId)}function Hh(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 EQ(e,t,n){if(t||e.length<=ju)return e;const a=e.slice(0,ju);if(!n||a.some(r=>r.id===n))return a;const o=e.find(r=>r.id===n);return o?[...a.slice(0,ju-1),o]:a}function jQ(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function zA(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||!jQ(o))&&!(n&&o.turnId&&o.turnId!==n))return o.name==="turn.completed"?"completed":"blocked"}return"pending"}function lk(e,t){if(e.systemKind)return!1;const n=Id(t,e.id);if(n.length===0)return!1;const a=zA(n);return a==="pending"||a==="none"&&BA(n)==="pending"}function ck(e,t){if(e.systemKind||e.status!=="active")return!1;const n=Id(t,e.id);if(n.length===0)return!0;const a=zA(n);return a==="pending"||a==="none"&&BA(n)!=="terminal"}function BA(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 MQ({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:o,sidebarSessions:r,subagentRuntimeBySessionId:s}){const c=y.useMemo(()=>new Map(r.map(S=>[S.id,S])),[r]),m=y.useMemo(()=>{const S=new Set;for(const[k,C]of t??[]){const P=c.get(k);C.tone==="active"&&!P?.systemKind&&S.add(k)}for(const k of n.activeGoalSessionIds)c.get(k)?.systemKind||S.add(k);return o&&!a?.systemKind&&e?.tone==="active"&&S.add(o),S},[e,t,n,a,o,c]),u=y.useMemo(()=>{const S=new Set(m);for(const[k,C]of s??[]){const P=c.get(k);C.activeCount>0&&!P?.systemKind&&S.add(k)}for(const k of n.activeSubagentSessionIds)c.get(k)?.systemKind||S.add(k);for(const k of r)k.systemKind||lk(k,n)&&S.add(k.id);return a&&lk(a,n)&&S.add(a.id),S},[m,n,a,r,c,s]),f=y.useMemo(()=>{const S=new Set(u);for(const k of r)ck(k,n)&&S.add(k.id);return a&&ck(a,n)&&S.add(a.id),S},[u,n,a,r]),g=!!(a&&!a.systemKind&&u.has(a.id));return{runningSessionIds:f,selectedSessionRunning:g}}const OQ=1e3;function $Q(e){const[t,n]=y.useState(()=>new Date().toISOString());return y.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const o=window.setInterval(a,OQ);return()=>window.clearInterval(o)},[e]),t}function NQ(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:o,goalRuntime:r,locallyActiveCodexHistorySessionIds:s,pinnedSessions:c,savedForLaterSessions:m,projectSessionRowsByProjectId:u,rightChatHistoryEvents:f,runtimeIndexes:g,selectedSession:S,selectedSessionId:k,serverId:C,setCodexHistorySessions:P,sidebarSessions:j,subagentRuntime:R,visibleChatRows:$,visibleProjectRows:O}=e,[M,w]=y.useState({});y.useEffect(()=>{w({})},[C]);const A=y.useMemo(()=>{const oe=[],be=new Set,re=ke=>{!ke||ke.id===k||!Kt(ke.id)||be.has(ke.id)||(be.add(ke.id),oe.push(ke.id))};for(const ke of n)(ke.status==="active"||s.has(ke.id))&&re(ke);const ue=oe.length;for(const ke of O)for(const Le of(u[ke.id]??[]).slice(0,2))re(Le);for(const ke of o)for(const Le of(u[ke]??[]).slice(0,ju))re(Le);for(const ke of c)re(ke);for(const ke of m)re(ke);for(const ke of $)re(ke);return[...oe.slice(0,ue),...oe.slice(ue,ue+8)].join(`
|
|
212
|
+
`)},[n,o,s,c,m,u,k,$,O]),E=y.useCallback(oe=>{w(be=>be[oe.session.id]===oe.events?be:{...be,[oe.session.id]:oe.events}),P(be=>mp(be,oe.session))},[P]),D=y.useMemo(()=>{if(!A)return"";const oe=new Set(A.split(`
|
|
213
|
+
`).filter(Boolean));return j.filter(be=>oe.has(be.id)&&be.status==="active").map(be=>be.id).join(`
|
|
214
|
+
`)},[A,j]),U=y.useMemo(()=>A?A.split(`
|
|
215
|
+
`).filter(oe=>s.has(oe)).join(`
|
|
216
|
+
`):"",[A,s]);y.useEffect(()=>{!S||!k||!Kt(k)||t.length===0||E({session:S,events:t})},[E,t,S,k]),y.useEffect(()=>{if(!a||!A)return;const oe=a,be=A.split(`
|
|
217
|
+
`).filter(Boolean),re=new Set(D.split(`
|
|
218
|
+
`).filter(Boolean)),ue=new Set(U.split(`
|
|
219
|
+
`).filter(Boolean)),ke=be.map(Le=>Cy({connection:oe,locallyActive:ue.has(Le),onPayload:we=>E(_y(we,ue.has(Le))),reportedActive:re.has(Le),sessionId:Le,surface:"sidebar"}));return()=>ke.forEach(Le=>Le())},[E,D,U,A,a]);const L=y.useMemo(()=>new Map(j.map(oe=>[oe.id,oe])),[j]),J=y.useMemo(()=>{const oe=new Map(g.latestGoalRuntimeBySessionId);for(const be of j){const re=be.status==="active"?Eh(be.metadata):null;re&&oe.set(be.id,re)}for(const be of[M,f])for(const[re,ue]of Object.entries(be)){const ke=L.get(re),Le=ke?.status==="active"?Eh(ke.metadata):null,we=zg(ue)??xy(ue)??(ke?.status==="active"?gm(ue)??Le:null);we?oe.set(re,we):oe.delete(re)}if(k)if(r)oe.set(k,r);else if(S?.status==="active"&&t.length>0){const be=zg(t)??gm(t)??Eh(S.metadata);be?oe.set(k,be):oe.delete(k)}else(!Kt(k)||t.length>0)&&oe.delete(k);return oe},[t.length,M,r,f,g.latestGoalRuntimeBySessionId,S?.status,S?.metadata,k,L,j]),X=y.useMemo(()=>[...J.values()].some(oe=>oe.tone==="active"&&!!oe.observedAt),[J]),de=$Q(X),Me=y.useMemo(()=>X?new Map([...J].map(([oe,be])=>[oe,Y7(be,de)??be])):J,[J,de,X]),Ie=k?Me.get(k)??r:r,ne=y.useMemo(()=>{const oe=new Map(g.latestSubagentRuntimeBySessionId);return k&&(R?oe.set(k,R):oe.delete(k)),oe},[g.latestSubagentRuntimeBySessionId,k,R]),{runningSessionIds:je,selectedSessionRunning:Se}=MQ({goalRuntime:Ie,goalRuntimeBySessionId:Me,runtimeIndexes:g,selectedSession:S,selectedSessionId:k,sidebarSessions:j,subagentRuntimeBySessionId:ne});return{goalRuntime:Ie,runningSessionIds:je,selectedSessionRunning:Se,sidebarGoalRuntimeBySessionId:Me,sidebarSubagentRuntimeBySessionId:ne}}function DQ({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:o}){y.useEffect(()=>{const r=s=>{if((s.metaKey||s.ctrlKey)&&s.key.toLowerCase()==="k"){s.preventDefault(),n(null),a(c=>!c);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 HQ({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:o,setError:r,onDisconnected:s}){y.useEffect(()=>{if(!n?.token||e===null)return;const c=n;let m=null,u=[],f=null,g=null,S=!1;const k=new Map;let C=0;const P=16;function j(){m!==null&&(window.clearTimeout(m),m=null)}function R(){r(L=>L==="Event stream disconnected"?null:L)}function $(){f=null;const L=u;if(u=[],L.length===0)return;C=Date.now(),t(L);const J=LQ(L);J.length>0&&o(X=>J.reduce(ic,X)),a(X=>{let de=X;for(const Me of L)if(Me.name==="approval.requested"&&Me.data&&(de=[Me.data,...de]),Me.name==="approval.resolved"&&Me.data&&typeof Me.data=="object"){const Ie=Me.data;Ie.approvalId&&(de=de.filter(ne=>ne.id!==Ie.approvalId))}return de})}function O(){const L=Date.now()-C;if(L>=P){f!==null&&(window.clearTimeout(f),f=null),$();return}f===null&&(f=window.setTimeout($,P-L))}function M(L){w(L),u.push(L),O()}function w(L){if(!(!L.sessionId||!L.name.startsWith("harness.refiner."))){if(L.name==="harness.refiner.completed"||L.name==="harness.refiner.failed"){k.delete(L.sessionId);return}(L.name==="harness.refiner.queued"||L.name==="harness.refiner.started")&&(k.set(L.sessionId,typeof L.sequence=="number"?L.sequence:0),A())}}function A(){g!==null||k.size===0||(g=window.setTimeout(()=>{g=null,E()},1e3))}async function E(){if(!(S||k.size===0)){S=!0;try{await Promise.all([...k].map(async([L,J])=>{const X=await Q.runtimeEventsPage(c,{sessionId:L,afterSequence:J,limit:100});for(const de of X.events){const Me=de.event;k.set(L,Math.max(k.get(L)??0,de.sequence)),M(Me)}}))}catch{}finally{S=!1,A()}}}function D(){f!==null&&(window.clearTimeout(f),f=null),$()}document.addEventListener("visibilitychange",D);const U=a9(n,L=>{j(),R(),M(L)},()=>{j(),m=window.setTimeout(()=>{U.isOpen()||(r("Event stream disconnected"),s?.())},2e3)},()=>{j(),R(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{j(),f!==null&&window.clearTimeout(f),g!==null&&window.clearTimeout(g),f=null,g=null,u=[],document.removeEventListener("visibilitychange",D),U.close()}},[e,t,n,s,a,r,o])}function LQ(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=Ic.safeParse(a[o]);r.success&&t.set(r.data.id,r.data)}return[...t.values()]}function Lh(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function qQ(e){return typeof e=="string"&&e.trim()?e.trim():null}function UQ(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=Lh(n.data),o=Lh(a?.createImproveRun);if(o?.state!=="ready_local"&&o?.state!=="released"||Lh(o.adapter)?.kind!=="local")continue;const s=qQ(o.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",s].join(":")}return null}const zQ=332,dk=244,uk=560,BQ=560,mk=320,pk=2400,FQ=440;function qh(e){const t=typeof window>"u"?uk:Math.min(uk,Math.max(dk,window.innerWidth-420));return Math.min(t,Math.max(dk,Math.round(e)))}function Uh(e){const t=typeof window>"u"?pk:Math.min(pk,Math.max(mk,window.innerWidth-FQ));return Math.min(t,Math.max(mk,Math.round(e)))}function VQ(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Ms=new Map;function Py(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function FA(e,t){const n=Py(e,t);if(!n)return null;const a=Ms.get(n);return a?.updatedAt?a.agents:null}function KQ(e,t,n){const a=Py(e,n);a&&Ms.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function Ay(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Py(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Ms.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=>(KQ(t,r,e.accountKey),r)).catch(r=>{const s=Ms.get(n);throw s?.promise===o&&Ms.set(n,{agents:s.agents,promise:null,updatedAt:s.updatedAt}),r});return Ms.set(n,{agents:a?.agents??[],promise:o,updatedAt:a?.updatedAt??0}),o}const WQ=6e4,GQ=6e4,JQ=6e4,Ty=["pinned","projects","cloudProjects","chats","savedForLater"];function ZQ(e,t,n,a=Date.now()){for(const o of eX(t,n))VA(t[o],n[o])||(e[o]=a)}function YQ(e,t,n,a=Date.now()){const o={...t};for(const[r,s]of Object.entries(n)){if(a-s>WQ){delete n[r];continue}const c=nX(e,r),m=e[r];!c||VA(m,t[r])||(o[r]=m)}return o}function QQ(e,t,n,a=Date.now()){for(const o of Ty)t[o]!==n[o]&&(e[o]=a)}function XQ(e,t,n,a=Date.now()){const o={...t};for(const r of Ty){const s=n[r];if(s!==void 0){if(a-s>GQ){delete n[r];continue}if(e[r]===t[r]){delete n[r];continue}o[r]=e[r]}}return tX(e,o)?e:o}function fk(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function hk(e,t,n=Date.now()){return t?n-t.changedAt>JQ?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function eX(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function VA(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function tX(e,t){return Ty.every(n=>e[n]===t[n])}function nX(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const aX=5e4,zo="\0openpond-unscoped-runtime-events",_i=[];class iX{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=_i;summaryEventsSnapshot=_i;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=bk(t.perSessionLimit??Sy,"perSessionLimit"),this.totalLimit=bk(t.totalLimit??aX,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return vk();const n=new Map;let a=0;for(const u of t){if(this.eventKeyById.has(u.id)){a+=1;continue}const f=u.sessionId||zo,g=n.get(f);g?g.push(u):n.set(f,[u]),this.eventKeyById.set(u.id,f)}if(n.size===0)return{...vk(),duplicateEventCount:a};const o=new Set;let r=0,s=0,c=!1;for(const[u,f]of n){f.some(yk)&&(c=!0);const g=this.entries.get(u),S=g?.snapshot.events??_i,k=Math.max(0,Math.min(S.length,this.perSessionLimit-f.length)),C=f.length>this.perSessionLimit?f.slice(f.length-this.perSessionLimit):f,P=k===S.length?S:S.slice(S.length-k),j=P.length===0?C:[...P,...C],R=S.slice(0,S.length-P.length);R.some(yk)&&(c=!0);for(const M of R)this.eventKeyById.delete(M.id);for(const M of f.slice(0,f.length-C.length))this.eventKeyById.delete(M.id);const O={eventIds:new Set(j.map(M=>M.id)),lastTouched:++this.clock,retained:g?.retained??this.retainedKeys.has(u),snapshot:{events:j,latestSequence:hm(j),revision:(g?.snapshot.revision??0)+1}};this.entries.set(u,O),this.eventCount+=j.length-S.length,r+=C.length,s+=R.length+f.length-C.length,o.add(u)}const m=this.enforceTotalLimit(o);return s+=m,this.publish(o,c||m>0),rX({acceptedEventCount:r,duplicateEventCount:a,evictedEventCount:s,changedKeys:o})}mergeBootstrap(t){const n=oX(t),a=new Set([...this.entries.keys(),...n.keys()]),o=[];for(const r of a){const s=n.get(r)??_i,c=this.entries.get(r)?.snapshot.events??_i;o.push(...F7(s,c))}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=_i,this.summaryEventsSnapshot=_i;const o=this.append(t);for(const m of this.retainedKeys){const u=this.entries.get(m);u&&(u.retained=!0)}const r=this.eventKeyById;let s=0;for(const m of n)r.has(m)||(s+=1);const c=new Set([...a].filter(m=>!this.entries.has(m)));return c.size>0&&this.publish(c,!0),{...o,evictedEventCount:o.evictedEventCount+s,changedSessionIds:new Set([...o.changedSessionIds,...[...c].filter(m=>m!==zo)]),unscopedEventsChanged:o.unscopedEventsChanged||c.has(zo)}}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=_i,this.summaryEventsSnapshot=_i,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??gk:gk;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(sX),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!==zo&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(zo)?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 c=r.snapshot.events.slice(0,s),m=r.snapshot.events.slice(s);for(const u of c)this.eventKeyById.delete(u.id);r.eventIds=new Set(m.map(u=>u.id)),r.snapshot={events:m,latestSequence:hm(m),revision:r.snapshot.revision+1},this.eventCount-=c.length,n+=c.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 gk=Object.freeze({events:_i,latestSequence:null,revision:0});function oX(e){const t=new Map;for(const n of e){const a=n.sessionId||zo,o=t.get(a);o?o.push(n):t.set(a,[n])}return t}function rX(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==zo)),unscopedEventsChanged:e.changedKeys.has(zo)}}function vk(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function sX(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 bk(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function yk(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const lX=256,cX=15e3,dX=5e3,uX=3e4;class mX{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){pX(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,fX(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,c=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??dX),lastAccessedAt:m}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:c,expiresAt:o+(this.options.loadingTtlMs??uX),lastAccessedAt:o}),this.prune(),c}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??lX;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??cX:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const Sk=new mX;function voe(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function pX(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function fX(e,t,n){e.delete(t),e.set(t,n)}const hX={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function gX(e){return{label:hX[e],ready:e==="ready",stage:e}}const vX=650,bX=1200,yX=6e4;function SX(e){const{setDraftModel:t,setDraftProvider:n,setCodexPermissionMode:a,setCodexReasoningEffort:o,setOpenPondCommandAccessMode:r,setError:s,setSelectedAppId:c,setSelectedProjectId:m,setSelectedSessionId:u}=e,[f,g]=y.useState(null),[S,k]=y.useState(null),[C]=y.useState(()=>new iX),P=y.useSyncExternalStore(C.subscribeSummary,C.getSummaryEvents,C.getSummaryEvents),j=y.useCallback(N=>{const F=C.getAllEvents(),ee=typeof N=="function"?N(F):N;ee!==F&&C.replace(ee)},[C]),R=y.useCallback(N=>{C.append(N)},[C]),[$,O]=y.useState(null),[M,w]=y.useState([]),[A,E]=y.useState([]),[D,U]=y.useState([]),[L,J]=y.useState({}),[X,de]=y.useState("connecting"),Me=Vg(S?.account),Ie=y.useRef({}),ne=y.useRef({}),je=y.useRef({}),Se=y.useRef([]),oe=y.useRef([]),be=y.useRef(null),re=y.useRef(null),ue=y.useRef(!1),ke=y.useRef(Date.now()),Le=y.useRef(null),we=y.useRef(null);y.useEffect(()=>{Sk.activateConnection(f),Sk.activateAccountScope(Me)},[f,Me]);const le=y.useCallback(N=>{ue.current||de(N)},[]),xe=y.useCallback(N=>{J(F=>{const ee=typeof N=="function"?N(F):N;return ZQ(Ie.current,F,ee),ee})},[]),Ue=y.useCallback(N=>{w(F=>{const ee=typeof N=="function"?N(F):N;return Kx(ne.current,F,ee),Se.current=ee,ee})},[]),Ze=y.useCallback(N=>{E(F=>{const ee=typeof N=="function"?N(F):N;return Kx(je.current,F,ee),oe.current=ee,ee})},[]),it=y.useCallback(()=>{if(ue.current||Le.current!==null)return;const N=()=>{Le.current=null,!ue.current&&(ue.current=!0,de("ready"))},F=Date.now()-ke.current,ee=xX(F);if(ee===0){N();return}Le.current=window.setTimeout(N,ee)},[]);y.useEffect(()=>()=>{Le.current!==null&&window.clearTimeout(Le.current)},[]);const at=y.useCallback(N=>{const F=be.current,ee=!F||F===N.server.id;be.current=N.server.id,O(me=>me?.serverId===N.server.id?me:{afterSequence:N.eventWindow?.latestSequence??hm(N.events)??0,serverId:N.server.id}),k(N),ee?C.mergeBootstrap(N.events):C.replace(N.events),w(me=>{const $e=ee?Vx(me,N.sessions,ne.current):Kg(me,N.sessions,ne.current);return Se.current=$e,$e}),E(me=>{const $e=ee?Vx(me,N.codexHistorySessions??[],je.current):Kg(me,N.codexHistorySessions??[],je.current);return oe.current=$e,$e}),U(N.approvals),J(me=>YQ(me,N.sidebarAppPreferences,Ie.current)),c(me=>me&&N.apps.some($e=>$e.id===me)?me:null),m(me=>{if(!me)return null;const $e=hP(me);return $e?.kind==="local"&&N.localProjects.some(ze=>ze.id===$e.id)?It("local",$e.id):$e?.kind==="cloud"&&(N.cloudProjects??[]).some(ze=>ze.id===$e.id)?It("cloud",$e.id):N.localProjects.some(ze=>ze.id===me)?It("local",me):(N.cloudProjects??[]).some(ze=>ze.id===me)?It("cloud",me):null}),u(me=>{if(!me)return null;const $e=[...N.sessions,...N.codexHistorySessions??[]];if($e.some(tt=>tt.id===me&&!tt.archived))return me;if(!ee)return null;const ze=Se.current.find(tt=>tt.id===me)??oe.current.find(tt=>tt.id===me)??null;return ze&&!ze.archived&&gA(ze,$e)?me:null})},[C,c,m,u]),Ne=y.useCallback(N=>{k(F=>F&&{...F,preferences:N.preferences})},[]);y.useEffect(()=>{const N=$a(S?.preferences);n(N.defaultChatProvider),t(N.defaultChatModel)},[S?.preferences.defaultChatProvider,S?.preferences.defaultChatModel,t,n]),y.useEffect(()=>{a($a(S?.preferences).codexPermissionMode)},[S?.preferences.codexPermissionMode,a]),y.useEffect(()=>{o($a(S?.preferences).codexReasoningEffort)},[S?.preferences.codexReasoningEffort,o]),y.useEffect(()=>{r($a(S?.preferences).openPondCommandAccessMode)},[S?.preferences.openPondCommandAccessMode,r]),y.useEffect(()=>{if(!f||!S){re.current=null;return}if(S.account.state!=="signed_in"){re.current=null,it();return}const N=Vg(S.account);if(!N){re.current=null,it();return}it(),le("team");const F=S.preferences.defaultTeamId?.trim()??"",ee=kX(N,F,S.accountMeta.asOf??"initial");if(re.current===ee)return;re.current=ee;let me=!1;const $e=ze=>Ay({teamId:ze,accountKey:N,fetchAgents:async tt=>(await Q.listSandboxAgents(f,{teamId:tt})).agents}).catch(()=>{!me&&re.current===ee&&(re.current=null)});return Dx({accountKey:N,force:!0,fetchOrganizations:()=>xk(f)}).then(async ze=>{if(me)return;if(ze.length===0){it();return}if(!!F&&ze.some(pt=>pt.teamId===F)){await $e(F),it();return}const nt=GJ(ze)?.teamId;if(!nt){it();return}if(F){s("The configured default team is unavailable for this account. Select an available team in account settings."),it();return}await $e(nt),me||it()}).catch(ze=>{me||(re.current=null,s(ze instanceof Error?ze.message:String(ze)),it())}),()=>{me=!0}},[at,Ne,S?.account,S?.accountMeta.asOf,S?.preferences.defaultTeamId,it,f,le,s]),y.useEffect(()=>{if(!f||!Me)return;let N=!1;const F=()=>{N||(N=!0,Dx({accountKey:Me,force:!0,fetchOrganizations:()=>xk(f)}).catch(()=>{}).finally(()=>{N=!1}))},ee=()=>{document.visibilityState==="visible"&&F()},me=window.setInterval(F,yX);return window.addEventListener("focus",F),document.addEventListener("visibilitychange",ee),()=>{window.clearInterval(me),window.removeEventListener("focus",F),document.removeEventListener("visibilitychange",ee)}},[f,Me]),xd(()=>{const N=r8();s(N||(F=>F?.startsWith("Preference changes have not been saved.")?null:F))}),y.useEffect(()=>{f&&dx(f).catch(N=>s(String(N)))},[f,Me,s]);const We=y.useCallback(async()=>{le("connecting"),O(null);const N=await _9();g(ee=>VQ(ee,N)?ee:N),le("account");const F=await Q.bootstrap(N);await dx(N),at(F),it(),s(ee=>ee&&(DP(ee)||ee==="Event stream disconnected")?null:ee)},[at,it,le,s]);y.useEffect(()=>{let N=!1,F=null;const ee=async me=>{try{await We()}catch($e){if(N)return;s($e instanceof Error?$e.message:String($e));const ze=Math.min(5e3,750+me*750);F=window.setTimeout(()=>{ee(me+1)},ze)}};return ee(0),()=>{N=!0,F!==null&&window.clearTimeout(F)}},[We,s]);const qe=y.useCallback(()=>{We().catch(()=>{})},[We]);HQ({afterSequence:$?.afterSequence??null,appendEvents:R,connection:f,setApprovals:U,setSessions:Ue,setError:s,onDisconnected:qe}),y.useEffect(()=>{if(!f||!S){we.current=null;return}const N=UQ(P);!N||we.current===N||(we.current=N,Q.profileCurrent(f).then(F=>{k(ee=>ee&&{...ee,profile:F})}).catch(F=>{we.current=null,s(F instanceof Error?F.message:String(F))}))},[S,f,P,s]);const q=y.useCallback(()=>{f&&Q.refreshOpenPondAccount(f).then(({account:N,accountMeta:F})=>{k(ee=>ee&&{...ee,account:N,accountMeta:F})}).catch(N=>s(N instanceof Error?N.message:String(N)))},[f,s]);return{appPreferences:L,applyBootstrapPayload:at,approvals:D,bootstrap:S,codexHistorySessions:A,connection:f,events:P,runtimeEventStore:C,refreshOpenPondAccount:q,sessions:M,startup:gX(X),setAppPreferences:xe,setBootstrap:k,setCodexHistorySessions:Ze,setEvents:j,setSessions:Ue}}async function xk(e){return(await Q.organizations(e)).organizations.map(up).filter(n=>!!n).filter(n=>n.status==="active")}function xX(e){return e>=bX?0:Math.max(0,vX-e)}function kX(e,t,n){return`${e}::${t||"none"}::${n}`}function wX({appDispatch:e,error:t,setErrorState:n}){const a=y.useRef(null),o=y.useRef(null),r=y.useRef(null),s=y.useRef(0),c=y.useCallback((u,f="info",g={})=>{const S=Date.now()+ ++s.current;return e({type:"showToast",toast:{id:S,message:u,tone:f,...g}}),S},[e]),m=y.useCallback(u=>{const f=o.current,g=typeof u=="function"?u(f):u;if(Object.is(f,g))return;if(o.current=g,n(g),!g){r.current!==null&&(e({type:"clearToast",toastId:r.current}),r.current=null);return}r.current=c(IX(g),"error");const S=a.current;S&&Q.recordClientDiagnostic(S,{message:g,surface:"app",context:{href:window.location.href}}).catch(k=>{console.warn("Unable to record client diagnostic.",k)})},[e,n,c]);return y.useEffect(()=>{o.current=t,!(t||r.current===null)&&(e({type:"clearToast",toastId:r.current}),r.current=null)},[e,t]),{connectionRef:a,setError:m,showToast:c}}function IX(e){return NP(e)}const _X={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:Hn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Pr,draftModel:xc,draftExperience:"chat",codexPermissionMode:Tv,codexReasoningEffort:Ev,openPondCommandAccessMode:Am,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 Ey(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function bm(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 CX(e){return bm(e.promptDrafts,Ey(e),e.prompt)}function Kl(e,t,n={}){const a={...e,...t},o=Ey(a),r=CX(e),s=n.clearSelectedDraft?bm(r,o,""):n.preserveCurrentPrompt?bm(r,o,e.prompt):r;return{...e,...t,promptDrafts:s,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:s[o]??""}}function RX(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function PX(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:bm(e.promptDrafts,Ey(e),o)}}return RX(t.key)?Kl(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return Kl(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return Kl(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return Kl(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return Kl(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 kt(e,t){return n=>e({type:"field",key:t,value:n})}function AX(e){return{setQuery:kt(e,"query"),setSearchOpen:kt(e,"searchOpen"),setArchivedChatsOpen:kt(e,"archivedChatsOpen"),setSectionMenuOpen:kt(e,"sectionMenuOpen"),setProjectsExpanded:kt(e,"projectsExpanded"),setCloudProjectsExpanded:kt(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:kt(e,"chatRowsVisibleCount"),setSidebarOpen:kt(e,"sidebarOpen"),setView:kt(e,"view"),setSelectedAppId:kt(e,"selectedAppId"),setSelectedProjectId:kt(e,"selectedProjectId"),setSelectedSessionId:kt(e,"selectedSessionId"),setPrompt:kt(e,"prompt"),setDraftProvider:kt(e,"draftProvider"),setDraftModel:kt(e,"draftModel"),setDraftExperience:kt(e,"draftExperience"),setCodexPermissionMode:kt(e,"codexPermissionMode"),setCodexReasoningEffort:kt(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:kt(e,"openPondCommandAccessMode"),setBusy:kt(e,"busy"),setDiffPanelOpen:kt(e,"diffPanelOpen"),setDiffPanelExpanded:kt(e,"diffPanelExpanded"),setRightPanelMode:kt(e,"rightPanelMode"),setRightChatPanels:kt(e,"rightChatPanels"),setTerminalOpen:kt(e,"terminalOpen"),setSyncingWorkspaceAppId:kt(e,"syncingWorkspaceAppId"),setSettingsSection:kt(e,"settingsSection"),setNewProjectDialogOpen:kt(e,"newProjectDialogOpen"),setNewProjectMode:kt(e,"newProjectMode"),setNewProjectName:kt(e,"newProjectName"),setNewProjectPath:kt(e,"newProjectPath"),setNewProjectBusy:kt(e,"newProjectBusy"),setCommitDialogOpen:kt(e,"commitDialogOpen"),setCommitMessage:kt(e,"commitMessage"),setCommitIncludeUnstaged:kt(e,"commitIncludeUnstaged"),setCommitNextStep:kt(e,"commitNextStep"),setCommitDraft:kt(e,"commitDraft"),setBranchDialogOpen:kt(e,"branchDialogOpen"),setBranchDialogName:kt(e,"branchDialogName"),setToast:kt(e,"toast"),setError:kt(e,"error")}}function Wl(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function TX(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,o=new Set,r=u=>{if(!Object.is(n,u)){n=u;for(const f of o)f()}},s=()=>{const u=Wl(t);n?a.set(u,n):a.delete(u)},c=(u,f={})=>{const g=n;s(),t={...t,...u};const S=Wl(t);if(f.clear&&a.delete(S),f.preserveCurrentDraft){g?a.set(S,g):a.delete(S),r(g);return}r(f.clear?"":a.get(S)??"")},m={getScopeKey:()=>Wl(t),getSnapshot:()=>n,subscribe(u){return o.add(u),()=>o.delete(u)},set:u=>m.setForScope(Wl(t),u),setForScope(u,f){const g=Wl(t),S=u===g?n:a.get(u)??"",k=typeof f=="function"?f(S):f;Object.is(S,k)||(k?a.set(u,k):a.delete(u),u===g&&r(k))},applyAppAction(u){if(u.type==="field"){if(u.key==="prompt"){m.set(u.value);return}if(u.key==="selectedAppId"||u.key==="selectedProjectId"||u.key==="selectedSessionId"){const f=t[u.key],g=typeof u.value=="function"?u.value(f):u.value;Object.is(f,g)||c({[u.key]:g})}return}if(u.type==="patch"){const f={};"selectedAppId"in u.patch&&(f.selectedAppId=u.patch.selectedAppId),"selectedProjectId"in u.patch&&(f.selectedProjectId=u.patch.selectedProjectId),"selectedSessionId"in u.patch&&(f.selectedSessionId=u.patch.selectedSessionId),Object.keys(f).length>0&&c(f),"prompt"in u.patch&&typeof u.patch.prompt=="string"&&m.set(u.patch.prompt);return}if(u.type==="selectApp"){c({selectedAppId:u.appId,selectedProjectId:null,selectedSessionId:null});return}if(u.type==="selectProject"){c({selectedAppId:null,selectedProjectId:u.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(u.type==="selectSession"){const f=u.projectId??null;c({selectedSessionId:u.sessionId,selectedAppId:f?null:u.appId??null,selectedProjectId:f});return}u.type==="beginNewChat"&&c({selectedSessionId:null,selectedAppId:u.appId,selectedProjectId:null})}};return m}function boe(e){return y.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function EX(e){return{...e,draftExperience:wy()}}function jX(){const[e,t]=y.useReducer(PX,_X,EX),[n]=y.useState(()=>TX()),a=y.useCallback(r=>{n.applyAppAction(r),t(r)},[n]),o=y.useMemo(()=>({...AX(a),setPrompt:n.set}),[n,a]);return xd(()=>o.setDraftExperience(wy())),{composerDraftStore:n,dispatch:a,setters:o,state:e}}function MX(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function OX(e){const{connection:t,events:n,showToast:a}=e,o=y.useRef(new Set),r=y.useCallback(async()=>{if(t)try{const c=await Q.installMacOSCommandLineTools(t);a(c.message,"info")}catch(c){a(c instanceof Error?c.message:String(c),"error")}},[t,a]),s=y.useCallback((c="OpenPond needs Git to create and sync local projects.")=>{a(c,"error",{actionLabel:"Install Tools",onAction:()=>{r()},persistent:!0})},[a,r]);y.useEffect(()=>{if(!t)return;let c=!1;return Q.gitAvailability(t).then(m=>{c||m.ok||m.installAction!=="macos_command_line_tools"||s("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{c=!0}},[t,s]),y.useEffect(()=>{for(const c of n){if(o.current.has(c.id))continue;const m=c.error??c.output??null;c.name==="workspace_action_result"&&c.status==="failed"&&MX(m)&&(o.current.add(c.id),s("OpenPond needs Git before it can update this project."))}},[n,s])}function $X({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:o,setError:r}){const[s,c]=y.useState(()=>$a().sidebarSectionsCollapsed),m=y.useRef(s),u=y.useRef({}),f=y.useRef(null),g=y.useRef(null),[S,k]=y.useState(zQ),[C,P]=y.useState(!1),[j,R]=y.useState(BQ),[$,O]=y.useState(!1),{pinned:M,projects:w,cloudProjects:A,chats:E,savedForLater:D}=s;y.useEffect(()=>{if(C)return;const re=qh($a(t).sidebarWidth),ue=hk(re,f.current);f.current=ue.localChange,k(ue.value)},[t,C]),y.useEffect(()=>{if($)return;const re=Uh($a(t).diffPanelWidth),ue=hk(re,g.current);g.current=ue.localChange,R(ue.value)},[$,t]),y.useEffect(()=>{const re=$a(t).sidebarSectionsCollapsed;c(ue=>{const ke=XQ(ue,re,u.current);return m.current=ke,ke})},[t]);const U=y.useCallback(re=>{o(ue=>ue&&{...ue,preferences:re.preferences})},[o]),L=y.useCallback(async re=>{if(e&&qh($a(t).sidebarWidth)!==re)try{U(await Q.savePreferences(e,{sidebarWidth:re}))}catch(ue){r(ue instanceof Error?ue.message:String(ue))}},[e,t,r,U]),J=y.useCallback(async re=>{if(e&&Uh($a(t).diffPanelWidth)!==re)try{U(await Q.savePreferences(e,{diffPanelWidth:re}))}catch(ue){r(ue instanceof Error?ue.message:String(ue))}},[e,t,r,U]),X=y.useCallback(async re=>{if(!e)return;const ue=$a(t).sidebarSectionsCollapsed;if(!NX(ue,re))try{U(await Q.savePreferences(e,{sidebarSectionsCollapsed:re}))}catch(ke){r(ke instanceof Error?ke.message:String(ke))}},[e,t,r,U]),de=y.useCallback(re=>{const ue=m.current;QQ(u.current,ue,re),m.current=re,c(re),X(re)},[X]),Me=y.useCallback(()=>{const re=m.current;de({...re,pinned:!re.pinned})},[de]),Ie=y.useCallback(()=>{const re=m.current;de({...re,projects:!re.projects})},[de]),ne=y.useCallback(()=>{const re=m.current;de({...re,cloudProjects:!re.cloudProjects})},[de]),je=y.useCallback(()=>{const re=m.current;de({...re,chats:!re.chats})},[de]),Se=y.useCallback(()=>{const re=m.current;de({...re,savedForLater:!re.savedForLater})},[de]),oe=y.useCallback(re=>{if(!n)return;re.preventDefault();const ue=re.clientX,ke=S;let Le=ke;P(!0);function we(xe){Le=qh(ke+xe.clientX-ue),k(Le)}function le(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",le);const xe=fk(ke,Le);xe&&(f.current=xe),P(!1),L(Le)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",le,{once:!0})},[L,n,S]),be=y.useCallback(re=>{if(a)return;re.preventDefault();const ue=re.clientX,ke=j;let Le=ke;O(!0);function we(xe){Le=Uh(ke-(xe.clientX-ue)),R(Le)}function le(){window.removeEventListener("pointermove",we),window.removeEventListener("pointerup",le);const xe=fk(ke,Le);xe&&(g.current=xe),O(!1),J(Le)}window.addEventListener("pointermove",we),window.addEventListener("pointerup",le,{once:!0})},[a,j,J]);return{pinnedCollapsed:M,projectsCollapsed:w,cloudProjectsCollapsed:A,chatsCollapsed:E,savedForLaterCollapsed:D,sidebarWidth:S,sidebarResizing:C,diffPanelWidth:j,diffPanelResizing:$,togglePinnedCollapsed:Me,toggleProjectsCollapsed:Ie,toggleCloudProjectsCollapsed:ne,toggleChatsCollapsed:je,toggleSavedForLaterCollapsed:Se,startSidebarResize:oe,startDiffPanelResize:be}}function NX(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function DX(e){const[t,n]=y.useState({id:0,kind:null}),[a,o]=y.useState(null),r=y.useCallback((u=null)=>{n(f=>({id:f.id+1,kind:u}))},[]),s=y.useCallback(u=>{o(u)},[]),c=null,m=y.useMemo(()=>{if(e)return HX(a,r)},[e,a,r]);return{backAction:c,breadcrumbs:m,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:s}}function HX(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 kk=new WeakMap,tv=new WeakMap;function LX(e){if(!e)return"disconnected";let t=kk.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},kk.set(e,t)),t.id}function yoe(e,t){return tv.set(e,t),e}function Soe(e){if(!e)return["learning","disconnected"];let t=tv.get(e);return t||(t=["learning",crypto.randomUUID()],tv.set(e,t)),t}function qX(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return VK.parse(await Q.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const o=await n(a);return o?KK.parse(o):null}}}function UX(e,t,n,a){async function o(r,s){if(!e)throw new Error("Connect to OpenPond to load tasks.");const c=$3.parse(s),m=new URLSearchParams({profileId:t});for(const[u,f]of Object.entries(c))f!==void 0&&m.set(u,String(f));return Q.trainingRequest(e,`${r}?${m}`,{},"GET")}return{taskInventory:async(r={})=>D3.parse(await o("/tasks",r)),taskInventoryDetail:async r=>{const s=await o("/tasks/detail",r);return{item:rR.parse(s.item),task:Qm.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(c){return a(c),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 KA(e,t){return w4({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function zX(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await KA(t,n);return B_.parse(await Q.trainingRequest(e,"/models/check",a,"POST"))}function BX(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 B_.parse(await Q.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const wk=1e4,Ik=3e4;function FX(e){const{connection:t,profileId:n}=e,a=Kk(),o=LX(t),r=y.useMemo(()=>["training",o,n],[o,n]),s=y.useCallback(async()=>fK.parse(await Q.trainingState(t,n)),[t,n]),c=iw({queryKey:r,queryFn:s,enabled:!!t}),m=c.data??null,u=!!t&&c.isPending,[f,g]=y.useState(null),[S,k]=y.useState(null),C=y.useRef(null);C.current=m?.activityRevision??null;const P=y.useCallback(async()=>{if(!t)return null;try{const w=await a.fetchQuery({queryKey:r,queryFn:s,staleTime:0});return k(null),w}catch(w){return k(Xi(w)),null}},[t,a,r,s]),j=y.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]),R=y.useCallback(async(w,A,E,D="POST",U={})=>{if(!t)return null;U.silent||g(w);try{const L=await Q.trainingRequest(t,A,E,D);return await j(),U.silent||k(null),L}catch(L){return U.silent||k(Xi(L)),null}finally{U.silent||g(null)}},[t,j]),$=m?[m.jobs.some(w=>["queued","starting","running","cancelling","reconciling"].includes(w.status)),m.creations.some(w=>["planning","materializing","validating"].includes(w.state)),m.minerRuns.some(w=>["queued","running","cancelling"].includes(w.status)),m.datasetImports.some(w=>["inspecting","materializing","validating","cancelling"].includes(w.status))].some(Boolean):!1;y.useEffect(()=>{if(!t)return;let w=!0,A=null;const E=$?wk:Ik,D=async()=>{let U=E;try{const L=await Q.trainingActivity(t,n);U=L.active?wk:Ik,(C.current===null||C.current!==L.revision)&&await P()}catch(L){k(Xi(L))}w&&(A=window.setTimeout(()=>{D()},U))};return A=window.setTimeout(()=>{D()},E),()=>{w=!1,A!==null&&window.clearTimeout(A)}},[t,$,n,P]);const O=y.useMemo(()=>({...BX(t,R),saveComparisonSeries:w=>R("save-comparison-series","/comparison-series",{series:w}),saveContinualBenchIssueReview:w=>R("save-continual-support-issue-review","/continual-support/issue-reviews",{review:w},"PUT"),importContinualLearningDailyBatch:(w,A="json_upload")=>R("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:w,source:A}),saveContinualLearningDailyBatch:w=>R("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:w},"PUT"),generateContinualLearningResponses:w=>R("generate-continual-learning-responses","/continual-learning/responses",w),sealComparisonSeries:(w,A)=>R("seal-comparison-series",`/comparison-series/${encodeURIComponent(w)}/seal`,{expectedRevision:A}),archiveComparisonSeries:(w,A)=>R("archive-comparison-series",`/comparison-series/${encodeURIComponent(w)}/archive`,{expectedRevision:A}),queueComparisonRelease:w=>R("queue-comparison-release",`/comparison-series/${encodeURIComponent(w.seriesId)}/releases`,w),startComparisonEvaluation:w=>R("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(w.entryId)}/evaluations`,w),loadComparisonAttemptEvidence:w=>t?Q.trainingRequest(t,`/model-runs/${encodeURIComponent(w.runId)}/attempts/${encodeURIComponent(w.attemptId)}/evidence?kind=${w.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:w=>R("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(w.entryId)}/run`,w,"PATCH"),decideComparisonEntry:w=>R("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(w.entryId)}/decision`,w),recordComparisonPromotion:w=>R("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(w.entryId)}/promotion`,w),checkModelProject:(w,A=w.revision)=>zX(t,w,A),...qX(t,n,w=>R("begin-model-batch-review","/models/batch-review",{profileId:n,request:w})),saveModelProject:async(w,A=w.revision)=>R("save-model-project","/models",await KA(w,A),"PUT"),listHostedModelProjects:async(w={})=>{if(!t)return null;w.silent||g("list-hosted-model-projects");try{const A=await Q.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${w.refresh===!0}`,{},"GET");return w.silent||k(null),A}catch(A){return w.silent||k(Xi(A)),null}finally{w.silent||g(A=>A==="list-hosted-model-projects"?null:A)}},openHostedModelProject:(w,A,E,D={})=>R(`open-hosted-model-project:${w}`,`/hosted-model-projects/${encodeURIComponent(w)}/open`,{profileId:n,teamId:A,apiOrigin:E},"POST",D),pullHostedModelProject:w=>R(`pull-hosted-model-project:${w}`,`/hosted-model-projects/${encodeURIComponent(w)}/pull`,{profileId:n}),syncModelProject:w=>R("sync-model-project",`/models/${encodeURIComponent(w)}/sync`,{}),publishModelProjectTaskset:(w,A)=>R("publish-model-project-taskset",`/models/${encodeURIComponent(w)}/tasksets/${encodeURIComponent(A)}/publish`,{}),createScorer:(w,A,E)=>R("create-scorer","/scorers",{grader:w,tasksetId:A,modelProjectId:E??null}),prepareLearningBatch:w=>R("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:w}),...UX(t,n,R,w=>k(Xi(w))),tasksetGraderDetails:async w=>{if(!t)return null;try{return await Q.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/graders`,{},"GET")}catch(A){return k(Xi(A)),null}},inspectHuggingFaceDataset:w=>R("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:w}),materializeDatasetImport:(w,A)=>R("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(w)}/materialize`,A),cancelDatasetImport:w=>R("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(w)}/cancel`,{}),datasetRows:(w,A={})=>{if(!t)return Promise.resolve(null);const E=new URLSearchParams;A.split&&E.set("split",A.split),A.cursor&&E.set("cursor",A.cursor),E.set("limit",String(A.limit??25));for(const D of A.columns??[])E.append("column",D);return Q.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/rows?${E}`,{},"GET")},addSource:(w,A)=>R("add-source","/sources",{profileId:n,sessionId:w,turnIds:A}),addSources:w=>R("add-sources","/sources/batch",{profileId:n,sessionIds:w}),estimateSources:w=>t?Q.trainingRequest(t,"/sources/estimate",{sessionIds:w}):Promise.resolve([]),searchChats:(w,A,E=0,D=20)=>t?Q.trainingRequest(t,"/sources/search",{query:w,candidates:A,offset:E,limit:D}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:w,offset:E,limit:D,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:w=>R("remove-source",`/sources/${encodeURIComponent(w)}`,{},"DELETE"),deleteTaskset:w=>R("delete-model",`/tasksets/${encodeURIComponent(w)}`,{},"DELETE"),runBenchmark:(w,A,E,D)=>R(`run-benchmark-${A}`,`/tasksets/${encodeURIComponent(w)}/benchmark-runs`,{phase:A,model:E,reasoningEffort:D,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(w,A,E)=>R("run-harness-refiner-benchmark",`/models/${encodeURIComponent(w)}/harness-refiner-benchmark`,{profileId:n,model:A,reasoningEffort:E,maximumSpendUsd:10}),acceptHarnessReview:(w,A,E=null,D=null)=>R("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:w,reviewRef:A,analysisModel:E,analysisReasoningEffort:D}),startCreation:(w,A={})=>R("create-taskset","/task-creations",{profileId:n,sourceIds:w,surface:A.surface??"training_page",mode:A.mode??"defaults",entryMode:A.entryMode??"manual",resourceIntent:A.resourceIntent??"workproduct",buildIntent:A.buildIntent??"demonstrations",buildSpecification:A.buildSpecification??null,objective:A.objective??null,methodHint:A.methodHint??null,preferredBaseModelId:A.preferredBaseModel?.modelId??null,preferredBaseModel:A.preferredBaseModel??null,candidateId:A.candidateId??null,analysisModel:A.analysisModel??null,analysisReasoningEffort:A.analysisReasoningEffort??null,createImproveRunId:A.createImproveRunId??null,targetIntent:A.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(w,A)=>R("create-model","/models/from-taskset",{profileId:n,tasksetId:w,preferredBaseModelId:A.modelId,preferredBaseModel:A}),scanBaseModels:async()=>{if(!t)return null;g("scan-base-models");try{const w=await P();return k(null),w}catch(w){return k(Xi(w)),null}finally{g(null)}},approveDisclosure:(w,A)=>R("approve-disclosure",`/task-creations/${encodeURIComponent(w)}/disclosure`,{approved:A}),retryCreation:w=>R("retry-creation",`/task-creations/${encodeURIComponent(w)}/retry`,{}),answerQuestions:(w,A)=>R("answer-questions",`/task-creations/${encodeURIComponent(w)}/questions`,{answers:A}),materialize:(w,A)=>R("materialize",`/task-creations/${encodeURIComponent(w)}/materialize`,{approved:A}),chatCreation:(w,A)=>R("task-creator-chat",`/task-creations/${encodeURIComponent(w)}/chat`,{message:A}),renameCreation:(w,A)=>R("rename-creation",`/task-creations/${encodeURIComponent(w)}/name`,{name:A},"PATCH"),cancelCreation:w=>R("cancel-creation",`/task-creations/${encodeURIComponent(w)}/cancel`,{}),runMiner:(w=[],A=[],E)=>R("run-miner","/miner/run",{profileId:n,sourceIds:w,sessionIds:A,config:E}),cancelMinerRun:w=>R("cancel-miner-run",`/miner/runs/${encodeURIComponent(w)}/cancel`,{}),configureMiner:w=>R("configure-miner","/miner/config",{profileId:n,config:w},"PUT"),patchCandidate:(w,A)=>R("candidate",`/candidates/${encodeURIComponent(w)}`,A,"PATCH"),createCandidate:(w,A,E,D)=>R("create-candidate",`/candidates/${encodeURIComponent(w)}/create`,{mode:A,analysisModel:E??null,analysisReasoningEffort:D??null}),auditGraders:w=>R("audit-graders","/audit-graders",{tasksetId:w}),executeTasksetAttempt:(w,A,E)=>R("execute-taskset-attempt",`/tasksets/${encodeURIComponent(w)}/attempts`,{taskId:A,model:E,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:w=>R("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(w.tasksetId)}/synthetic-preference-collection`,w),tasksetOperationalState:w=>t?Q.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:w=>R("calibrate-judges","/calibrate-judges",{tasksetId:w}),nextPreferenceComparison:(w,A)=>R("next-preference-comparison",`/tasksets/${encodeURIComponent(w)}/preference-comparisons/next`,{reviewerKey:A}),submitPreferenceComparison:w=>R("submit-preference-comparison",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/${encodeURIComponent(w.assignmentId)}/submit`,w),submitSyntheticFixturePreference:w=>R("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/${encodeURIComponent(w.assignmentId)}/fixture-submit`,{...w,id:crypto.randomUUID()}),listPreferenceDatasets:w=>t?Q.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:w=>R("materialize-preference-dataset",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-datasets`,{...w,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:w=>R("launch-reward-model-run",`/tasksets/${encodeURIComponent(w.tasksetId)}/reward-model-runs`,{...w,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:w=>R("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(w.tasksetId)}/learned-preference-reward-binding`,w),retryRewardModelQualification:w=>R("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(w.runId)}/retry-qualification`,w),cancelRewardModelRun:w=>R("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(w)}/cancel`,{}),markPreferenceComparisonUnreviewable:w=>R("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/${encodeURIComponent(w.assignmentId)}/unreviewable`,w),preferenceCalibrationStatus:(w,A,E)=>{if(!t)return Promise.resolve(null);const D=new URLSearchParams({reviewerKey:A});return E&&D.set("comparisonReleaseId",E),Q.trainingRequest(t,`/tasksets/${encodeURIComponent(w)}/preference-comparisons/calibration/status?${D}`,{},"GET")},startPreferenceCalibrationBatch:w=>R("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/calibration/batches`,{...w,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:w=>R("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(w.jobId)}/sync`,w),reviewPreferenceComparisonWithModel:w=>R("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/${encodeURIComponent(w.assignmentId)}/model-review`,{...w,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:w=>R("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...w,id:crypto.randomUUID()}),savePreferenceCalibration:w=>R("save-preference-calibration",`/tasksets/${encodeURIComponent(w.tasksetId)}/preference-comparisons/calibration/report`,{...w,id:crypto.randomUUID()}),preferenceArtifactUrl:async w=>{if(!t)return null;const A=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(w)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!A.ok)throw new Error(await A.text());return URL.createObjectURL(await A.blob())},readiness:w=>R("readiness","/readiness",{tasksetId:w}),previewExpertBootstrap:w=>R("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(w)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(w,A)=>R("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(w)}/expert-bootstrap/approve`,{previewHash:A}),createPlan:w=>R("create-plan","/plans",{...w,tasksetId:w.tasksetId}),buildBundle:w=>R("build-bundle","/bundles",{planId:w}),approveTraining:(w,A)=>R("approve-training","/approvals",{planId:w,bundleId:A}),launch:(w,A)=>R("launch","/launch",{planId:w,approvalId:A}),prepareTraining:w=>R("prepare-training","/prepare",w),prepareModelRun:(w,A)=>R("prepare-model-run",`/model-projects/${encodeURIComponent(w)}/training/prepare`,A),startModelRun:(w,A)=>R("start-model-run",`/model-projects/${encodeURIComponent(w)}/training/start`,A),startPreparedTraining:w=>R("start-prepared-training","/start/prepared",w),startTraining:w=>R("start-training","/start",w),cancelJob:w=>R("cancel-job",`/jobs/${encodeURIComponent(w)}/cancel`,{}),retryModelRunCollection:w=>R("retry-model-run-collection",`/model-runs/${encodeURIComponent(w)}/retry-collection`,{}),cancelModelRun:w=>R("cancel-model-run",`/model-runs/${encodeURIComponent(w)}/cancel`,{}),rejectModel:(w,A)=>R("reject-model",`/models/${encodeURIComponent(w)}/reject`,{reason:A}),bindModel:(w,A,E)=>R("bind-model",`/models/${encodeURIComponent(w)}/bind`,{profileId:n,role:A,roleTargetId:E,promotedBy:n}),rollbackModelBinding:w=>R("rollback-model-binding",`/bindings/${encodeURIComponent(w)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(w,A)=>R("update-model-configuration",`/models/${encodeURIComponent(w)}/configuration`,A,"PATCH",{silent:!0}),setModelPinned:(w,A)=>R("pin-model-version",`/models/${encodeURIComponent(w)}/pin`,{pinned:A},"PATCH"),downloadArtifact:async w=>{if(!t)return!1;g("download-artifact");try{const A=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(w)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!A.ok)throw new Error(await A.text());const E=A.headers.get("content-disposition")??"",D=/filename="([^"]+)"/.exec(E)?.[1]??"openpond-model-artifact",U=URL.createObjectURL(await A.blob()),L=document.createElement("a");return L.href=U,L.download=D,L.click(),URL.revokeObjectURL(U),!0}catch(A){return k(Xi(A)),!1}finally{g(null)}},downloadModelPackage:async w=>M(`/models/${encodeURIComponent(w)}/download`,`${w}.openpond-lora.tar`),downloadBundle:async w=>M(`/bundles/${encodeURIComponent(w)}/download`,"openpond-model-improvement-bundle.json")}),[t,R,n,P]);async function M(w,A){if(!t)return!1;g("download-bundle");try{const E=await fetch(`${t.serverUrl}/v1/training${w}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!E.ok)throw new Error(await E.text());const D=E.headers.get("content-disposition")??"",U=/filename="([^"]+)"/.exec(D)?.[1]??A,L=URL.createObjectURL(await E.blob()),J=document.createElement("a");return J.href=L,J.download=U,J.click(),URL.revokeObjectURL(L),!0}catch(E){return k(Xi(E)),!1}finally{g(null)}}return{connection:t,payload:m,loading:u,busyAction:f,error:S??c.error?.message??null,refresh:P,actions:O}}function Xi(e){return e instanceof Error?e.message:String(e)}function xoe({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===gd?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?GX(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:JX(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function koe(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function xs(e){return e?.tasks.length?e.tasks[JA(e,e.selectedTaskIndex)]??null:null}function WA(e,t){return{...e,selectedTaskIndex:JA(e,t)}}function VX(e){return WA(e,e.selectedTaskIndex+1)}function KX(e,t,n){if(!e||GA(e,n))return null;const a=xs(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 GA(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 WX({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function GX(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 JX(e){const t=new Set(e.sourceRefs.filter(FC).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function JA(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function ZX({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:o,connection:r,requestComposerFocus:s,selectedLocalProjectId:c,selectedSessionId:m,selectLocalProject:u,setDraftModel:f,setDraftProvider:g,setError:S,view:k}){const[C,P]=y.useState(null),j=y.useCallback(E=>{E.sourceProjectId?u(E.sourceProjectId):a(null)},[a,u]),R=y.useCallback(E=>{if(!C)return;const D={...WA(C,E),sessionId:C.sessionId?null:C.sessionId},U=xs(D);P(D),U&&(C.sessionId&&j(D),o.set(U.prompt),s())},[j,o,C,s]),$=y.useCallback(()=>{const E=xs(C);E&&o.getSnapshot().trim()===E.prompt.trim()&&o.set(""),P(null)},[o,C]),O=y.useCallback(E=>{const D=E.model;WX({model:D,connection:r,loadBootstrap:Q.bootstrap,applyBootstrap:n}).then(()=>{const U={...E,selectedTaskIndex:0,sessionId:null};g(D.providerId),f(D.modelId),P(U.tasks.length?U:null),j(U);const L=xs(U);L&&o.set(L.prompt)}).catch(S)},[n,j,o,r,f,g,S]),M=y.useCallback(E=>{const D=!!(C&&C.model.providerId===t&&C.model.modelId===e);return{active:D,error:D?GA(C,c):null,metadata:D?KX(C,E,c):null}},[e,t,C,c]),w=y.useCallback(E=>{P(D=>D&&{...D,sessionId:E})},[]),A=y.useCallback(()=>{if(!C)return;const E={...VX(C),sessionId:null},D=xs(E);P(E),D&&(j(E),o.set(D.prompt),s())},[j,o,C,s]);return y.useEffect(()=>{const E=xs(C);!E||k!=="chat"||m||o.set(D=>D.trim()?D:E.prompt)},[o,C,c,m,k]),y.useEffect(()=>{C&&m&&C.sessionId!==m&&P(null)},[C?.sessionId,m]),{advanceAfterTurn:A,begin:O,bindSession:w,dismiss:$,handoff:C,prepareTurn:M,selectTask:R}}const Gl=[],zh=500;function YX(e){const{approvals:t,codexHistoryEvents:n,connection:a,latestServerSequence:o,runtimeIndexes:r,runtimeEventStore:s,selectedSessionId:c,serverId:m,setCodexHistoryEvents:u,setCodexHistorySessions:f,setError:g}=e,[S,k]=y.useState({}),[C,P]=y.useState({}),j=y.useRef(new Set);y.useEffect(()=>{k({}),P({}),j.current.clear()},[m]);const R=y.useCallback(async()=>{if(!a||!c||j.current.has(c))return!1;const A=C[c];if(A?.hasMore===!1)return!1;if(Kt(c)){const U=Math.max(A?.totalMatchingEvents??0,n.length,yA),L=Math.min(Wx,Math.max(jZ,U*2));j.current.add(c),P(J=>({...J,[c]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:J[c]?.totalMatchingEvents??n.length}}));try{const J=await SA(a,c,{force:!0,limit:L,tail:!1});return u(J.events),f(X=>mp(X,J.session)),P(X=>({...X,[c]:{cursorSequence:null,hasMore:J.events.length>=L&&L<Wx,loading:!1,totalMatchingEvents:L}})),J.events.length>n.length}catch(J){return g(J instanceof Error?J.message:String(J)),P(X=>({...X,[c]:{cursorSequence:null,hasMore:X[c]?.hasMore??!0,loading:!1,totalMatchingEvents:X[c]?.totalMatchingEvents??n.length}})),!1}finally{j.current.delete(c)}}const E=to(S[c]??Gl,s.getSessionEvents(c)),D=A?.cursorSequence??QX(E);if(!D)return!1;j.current.add(c),P(U=>({...U,[c]:{cursorSequence:U[c]?.cursorSequence??D,hasMore:U[c]?.hasMore??!0,loading:!0,totalMatchingEvents:U[c]?.totalMatchingEvents??null}}));try{const U=await Q.runtimeEventsPage(a,{sessionId:c,beforeSequence:D,limit:zh}),L=U.events.map(J=>J.event);return k(J=>({...J,[c]:to(L,J[c]??Gl)})),P(J=>({...J,[c]:{cursorSequence:U.previousSequence,hasMore:U.hasMore,loading:!1,totalMatchingEvents:U.totalMatchingEvents}})),L.length>0}catch(U){return g(U instanceof Error?U.message:String(U)),P(L=>({...L,[c]:{cursorSequence:L[c]?.cursorSequence??D,hasMore:L[c]?.hasMore??!0,loading:!1,totalMatchingEvents:L[c]?.totalMatchingEvents??null}})),!1}finally{j.current.delete(c)}},[C,n.length,a,S,s,c,u,f,g]),$=c?S[c]??Gl:Gl,O=y.useMemo(()=>s.getSessionEvents(c).length,[s,c]),M=y.useRef(null);y.useEffect(()=>{if(!a||!c||Kt(c)||j.current.has(c)||$.length>0||O>0)return;const A=o;if(!A)return;const E=c,D=A+1;j.current.add(E),P(U=>({...U,[E]:{cursorSequence:U[E]?.cursorSequence??D,hasMore:U[E]?.hasMore??!0,loading:!0,totalMatchingEvents:U[E]?.totalMatchingEvents??null}})),Q.runtimeEventsPage(a,{sessionId:E,beforeSequence:D,limit:zh}).then(U=>{const L=U.events.map(J=>J.event);k(J=>({...J,[E]:to(L,J[E]??Gl)})),P(J=>({...J,[E]:{cursorSequence:U.previousSequence,hasMore:U.hasMore,loading:!1,totalMatchingEvents:U.totalMatchingEvents}}))}).catch(U=>{g(U instanceof Error?U.message:String(U)),P(L=>({...L,[E]:{cursorSequence:L[E]?.cursorSequence??D,hasMore:L[E]?.hasMore??!0,loading:!1,totalMatchingEvents:L[E]?.totalMatchingEvents??null}}))}).finally(()=>{j.current.delete(E)})},[o,a,$.length,O,c,g]),y.useEffect(()=>{if(!a||!c||Kt(c)||j.current.has(c)||!o)return;const A=to($,s.getSessionEvents(c)),E=hm(A);if(!E||E>=o)return;const D=`${c}:${E}:${o}`;if(M.current===D)return;M.current=D;let U=!1;return Q.runtimeEventsPage(a,{sessionId:c,afterSequence:E,limit:zh}).then(L=>{if(U)return;const J=L.events.map(X=>X.event);J.length!==0&&k(X=>B7(X,c,J))}).catch(L=>{U||(M.current=null,g(L instanceof Error?L.message:String(L)))}),()=>{U=!0}},[o,a,s,$,c,g]);const w=y.useMemo(()=>Kt(c)?Fg(n,[]):!c||$.length===0?r:Fg(to($,s.getSessionEvents(c)),t),[t,n,r,$,c]);return{chatHistoryLoadStates:C,loadMoreSelectedChatHistory:R,selectedPagedSessionEvents:$,selectedRuntimeIndexes:w}}function QX(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function XX(e,t){const n=y.useRef(null);return y.useMemo(()=>{const a=eA(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Os(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Bh(e){return Array.isArray(e)?e.filter(t=>!!Os(t)):[]}function hr(e){return typeof e=="string"&&e.trim()?e.trim():null}function _k(e){return hr(e)??Os(e)}function eee(e){if(!e)return[];const t=Os(e.sandboxActionRegistry),n=Os(e.sandboxManifest),a=new Map;for(const o of[...Bh(n?.actionCatalog),...Bh(t?.actions),...Bh(n?.actions)]){const r=hr(o.id)??hr(o.name);if(!r)continue;const s=a.get(r);a.set(r,{id:r,name:hr(o.name)??s?.name??r,label:hr(o.label)??s?.label??tee(r),description:hr(o.description)??s?.description??null,visibility:hr(o.visibility)??s?.visibility??"default",inputSchema:_k(o.inputSchema)??s?.inputSchema??null,outputSchema:_k(o.outputSchema)??s?.outputSchema??null,implementation:Os(o.implementation)??s?.implementation??null,mcp:Os(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 tee(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function ZA(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:It("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?Ba(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:It("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const YA="openpond-agent",QA="openpond-profile-action";function hp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function no(e){return typeof e=="string"&&e.trim()?e.trim():null}function jy(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function nee(e){const t=hp(e),n=no(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:no(t?.name)}}function aee(e){const t=no(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 iee(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:YA,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 oee(e){const t=hp(e.implementation);if(t?.type!==YA)return null;const n=no(t.agentId),a=no(t.teamId),o=no(t.projectId),r=nee(t.selectedEntrypoint),s=aee(t.workflowMode);return!n||!a||!o||!r||!s?null:{agentId:n,agentName:no(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:o,projectName:no(t.projectName),selectedEntrypoint:r,workflowMode:s}}function ree(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...hp(e.implementation)??{},type:QA,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function see(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=>ree(n,{agentName:n.agentId?t.get(n.agentId):null}))}function woe(e){return!!(e&&My(e))}function Ioe(e){return!!(e&&My(e)&&e.sourceActionId==="chat")}function My(e){const t=hp(e.implementation);if(t?.type!==QA)return null;const n=no(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function lee({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:jy({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...o?{sessionId:o}:{}}}}function cee({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:jy({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function dee({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:jy({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const $s=new Map;function Oy(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function uee(e,t){const n=Oy(e,t);if(!n)return null;const a=$s.get(n);return a?.updatedAt?a.projects:null}function mee(e,t,n){const a=Oy(e,n);a&&$s.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function pee(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Oy(t,e.accountKey);if(!n)return Promise.resolve([]);const a=$s.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=>(mee(t,r,e.accountKey),r)).catch(r=>{const s=$s.get(n);throw s?.promise===o&&$s.set(n,{projects:s.projects,promise:null,updatedAt:s.updatedAt}),r});return $s.set(n,{projects:a?.projects??[],promise:o,updatedAt:a?.updatedAt??0}),o}function Fh(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 fee({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:o,localProjects:r,profile:s,selectedCloudProject:c,selectedProject:m,reportError:u}){const[f,g]=y.useState(null),[S,k]=y.useState([]),[C,P]=y.useState([]),j=y.useMemo(()=>{const E=new Set;a&&E.add(a);for(const D of t)E.add(D.teamId);for(const D of r){const U=t.find(L=>L.id===D.linkedSandboxProject?.projectId&&L.teamId===D.linkedSandboxProject?.teamId);U?.teamId&&E.add(U.teamId)}return[...E].sort()},[t,a,r]),R=j.join("\0"),$=y.useMemo(()=>ZA({cloudProjects:t,selectedCloudProject:c,selectedProject:m}),[t,c,m]);y.useEffect(()=>{if(!n||j.length===0){P([]);return}let E=!1;const D=j.flatMap(U=>FA(U,o)??[]);return P(Fh(D)),Promise.all(j.map(U=>Ay({teamId:U,accountKey:o,fetchAgents:async L=>(await Q.listSandboxAgents(n,{teamId:L})).agents}))).then(U=>{E||P(Fh(U.flat()))}).catch(()=>{E||P(Fh(D))}),()=>{E=!0}},[o,n,R]),y.useEffect(()=>{if(!n||!$){g(null);return}const E=uee($.teamId,o);E&&g(E.find(U=>U.id===$.id)??null);let D=!1;return pee({teamId:$.teamId,accountKey:o,fetchProjects:async U=>(await Q.listSandboxProjects(n,{teamId:U})).projects}).then(U=>{D||g(U.find(L=>L.id===$.id)??null)}).catch(()=>{D||g(null)}),()=>{D=!0}},[o,n,$?.id,$?.teamId]),y.useEffect(()=>{if(!n||!m){k([]);return}let E=!1;return Q.localProjectActions(n,m.id).then(D=>{E||k(D.actions)}).catch(D=>{E||(k([]),u?.(`Could not load Project Actions for ${m.name}: ${D instanceof Error?D.message:String(D)}`))}),()=>{E=!0}},[n,u,m?.id,m?.name,m?.updatedAt]);const O=y.useMemo(()=>{const E=new Map;for(const D of eee(f))E.set(D.id,D);for(const D of S)E.set(D.id,D);return[...E.values()]},[S,f]),M=y.useMemo(()=>see(s),[s]),w=y.useMemo(()=>[...C.map(E=>iee(E,e.get(E.projectId)?.name??null)),...M,...O],[e,M,O,C]);return{openPondActionCatalog:y.useMemo(()=>[...M,...O],[M,O]),selectedActionCatalog:w,selectedProjectActionCatalog:O}}function hee({selectedProjectId:e}){const[t,n]=y.useState(()=>new Set),a=y.useCallback(r=>{n(s=>{if(s.has(r))return s;const c=new Set(s);return c.add(r),c})},[]),o=y.useCallback(r=>{n(s=>{const c=new Set(s);return c.has(r)?c.delete(r):c.add(r),c})},[]);return y.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:o,setExpandedProjectIds:n}}function gee(){const e=new Map;function t(o,r){const s=e.get(o);if(s)return s.consumers+=1,n(o,s,!0);const c=new AbortController,m={controller:c,consumers:1,settled:!1,promise:Promise.resolve().then(()=>r(c.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 c=!1;return{key:o,promise:r.promise,shared:s,release:()=>{c||(c=!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 Vh(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function vee(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function Kh(e){return e instanceof Error&&e.name==="AbortError"}function bee({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:o,setError:r}){const[s,c]=y.useState(null),[m,u]=y.useState({}),[f,g]=y.useState(null),[S,k]=y.useState(!1),[C,P]=y.useState(!1),j=y.useRef(new Set),R=y.useRef(new Set),$=y.useRef(gee()),O=t?m[t]??(s?.appId===t?s:null):null,M=f?.appId===t?f:null,w=n==="chat"||n==="labs",A=y.useCallback(U=>{j.current.add(U.appId),c(U),u(L=>({...L,[U.appId]:U}))},[]),E=y.useCallback(async(U,L=!1)=>{if(!e||!U)return c(null),null;k(!0);const J=$.current.request(Vh(e,U,L),X=>Q.workspaceStatus(e,U,L,{signal:X}));try{const X=await J.promise;return A(X),L&&X.error?r(`Workspace sync failed: ${X.error}`):L&&r(null),X}catch(X){return Kh(X)||(c(null),r(X instanceof Error?X.message:String(X))),null}finally{J.release(),k(!1)}},[e,A,r]),D=y.useCallback(async(U=t,L={})=>{if(!e||!U)return g(null),null;L.silent||P(!0);const J=$.current.request(vee(e,U),X=>Q.workspaceDiff(e,U,{signal:X}));try{const X=await J.promise;return g(X),X}catch(X){return Kh(X)||(g(null),r(X instanceof Error?X.message:String(X))),null}finally{J.release(),L.silent||P(!1)}},[t,e,r]);return y.useEffect(()=>{if(!e||!t||!w){c(null),g(null),k(!1);return}let U=!1;const L=$.current.request(Vh(e,t,!1),J=>Q.workspaceStatus(e,t,!1,{signal:J}));return k(!0),L.promise.then(J=>{U||(A(J),J.initialized||g(X=>X?.appId===J.appId?null:X))}).catch(J=>{Kh(J)||U||(c(null),r(J instanceof Error?J.message:String(J)))}).finally(()=>{L.release(),U||k(!1)}),()=>{U=!0,L.release()}},[t,e,A,r,w]),y.useEffect(()=>{if(!e||!t||!w){g(null);return}if(!O?.initialized){O&&!O.initialized&&g(U=>U?.appId===t?null:U);return}a&&D(t)},[t,e,D,a,w,O?.dirty,O?.initialized]),y.useEffect(()=>{if(!e||o.length===0)return;const U=o.filter(X=>!j.current.has(X)&&!R.current.has(X));if(U.length===0)return;U.forEach(X=>R.current.add(X));let L=!1;const J=U.map(X=>({appId:X,request:$.current.request(Vh(e,X,!1),de=>Q.workspaceStatus(e,X,!1,{signal:de}))}));return Promise.all(J.map(({appId:X,request:de})=>de.promise.then(Me=>({appId:X,state:Me})).catch(()=>({appId:X,state:null})).finally(()=>{de.release(),R.current.delete(X)}))).then(X=>{if(!L)for(const de of X)de.state&&A(de.state)}),()=>{L=!0,J.forEach(({appId:X,request:de})=>{de.release(),R.current.delete(X)})}},[e,A,o]),y.useEffect(()=>()=>$.current.cancelAll(),[]),{workspaceState:s,workspaceStates:m,workspaceDiff:f,workspaceBusy:S,diffBusy:C,visibleWorkspaceState:O,visibleWorkspaceDiff:M,rememberWorkspaceState:A,refreshWorkspace:E,refreshWorkspaceDiff:D,setWorkspaceBusy:k}}const yee=1,See=15e3,xee=15e3,XA=5*6e4,kee=5e3,wee=1e4;function eT(e,t=(a,o)=>new WebSocket(a,o),n={}){const a=new Iee(e,t,n.reconnectDelayMs??_ee);return a.open(),{close:()=>a.close()}}class Iee{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=XA;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===yee)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-${Cee(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."))},See))},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=Pee(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=Aee(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=Ree();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."))},xee)}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."))},kee)}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 _ee(e){const t=Math.min(wee,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function Cee(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 Ree(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function Pee(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:XA}function Aee(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 Tee(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 eT({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:o=>{const r=$I.safeParse(o);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function Eee(e){return e.refs.find(t=>t.refType==="message_reply")??null}function jee(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function _oe(e,t){const n=Eee(e);if(!n)return null;const a=t.get(n.refId);return a?jee(a):Oee(n)}function Mee(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 Coe(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 Roe(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function Oee(e){const t=e.preview;return{id:e.refId,authorType:$ee(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 $ee(e){return e==="agent"||e==="system"?e:"user"}function Ck(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function Nee(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:_d([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function Wh(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=il(a,o,"message.created",!0,o.authorUserId);return{...e,thread:a,messages:_d([...e.messages,...n])}}function Dee(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=il(r,s,"message.created",!0,s.authorUserId);return r}).sort((o,r)=>r.lastMessageAt.localeCompare(o.lastMessageAt))}function Gh(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Jh(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function Rk(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function _d(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 tT(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:eb.safeParse(e.payload.message).data??null}function nT(e,t,n){const a=tT(t);if(a){const o=e.selectedThreadId===a.threadId,r=e.detail?.thread.id===a.threadId?{...e.detail,thread:il(e.detail.thread,a,t.type,o,n),messages:_d([...e.detail.messages,a])}:e.detail,c=e.threads.some(m=>m.id===a.threadId)?e.threads.map(m=>m.id===a.threadId?il(m,a,t.type,o,n):m).sort((m,u)=>u.lastMessageAt.localeCompare(m.lastMessageAt)):e.threads;return{...e,detail:r,threads:c,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=c=>({...c,participants:c.participants.map(m=>m.userId===o?{...m,lastReadSequence:Math.max(m.lastReadSequence,r)}:m)});return{...e,threads:e.threads.map(c=>c.id===t.threadId?s(c):c),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:s(e.detail.thread)}:e.detail}}return e}function il(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 Hee(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:Mee(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 Lee(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:il(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:_d([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?il(a,t,"message.created",!0,t.authorUserId):a).sort((a,o)=>o.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function Pk(e,t,n){return nT(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function qee(e,t){return nv(e,t,"failed")}function nv(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 Ak(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 Uee(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?Tk(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:o,threads:e.threads.map(r=>r.lastMessageId===t?Tk(r,a):r)}}function zee(e){if(e.length>Sr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!Bee(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Sr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function Tk(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 Bee(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const Fee={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 Vee(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,o]of Object.entries(Fee))if(n.includes(a))return o;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":NA(t)}const aT="openpond.team-chat.notification-mode";function iT(){try{return typeof window>"u"?null:kd}catch{return null}}function Ek(e=iT()){const t=e?.getItem(aT);return t==="direct_mentions"||t==="none"?t:"all"}function Kee(e,t=iT()){try{t?.setItem(aT,e)}catch{}}function Wee(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 Gee(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 jk={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function fu(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function hu(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function Jee(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function Zee(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function Mk(e,t=Q.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function Yee(e){const[t,n]=y.useState(jk),a=y.useRef(t);a.current=t;const[o,r]=y.useState(Ek);xd(()=>r(Ek()));const[s,c]=y.useState(null),m=y.useRef(null),u=y.useRef(null),f=y.useRef(0),g=y.useRef(new Map),S=y.useRef(new Map),k=y.useRef(0),C=y.useRef(null),P=y.useRef(0),j=y.useRef(new Set),R=y.useRef(0),$=y.useRef(!1),O=y.useRef(new Map),M=y.useRef(new Map),[w,A]=y.useState(null),[E,D]=y.useState(null),U=y.useCallback(q=>{r(q),Kee(q)},[]),L=y.useCallback(q=>{c(N=>N?.eventId===q?null:N)},[]),J=y.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const q=await Q.teamChatThreads(e.connection,e.teamId),N=Dee(q.threads,O.current);return n(F=>({...F,threads:N})),N},[e.connection,e.teamId]),X=y.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[q,N]=await Promise.all([Q.teamChatMembers(e.connection,e.teamId),Q.teamChatAgents(e.connection,e.teamId)]);return n(F=>({...F,members:q.members,agents:N.agents})),{members:q.members,agents:N.agents}},[e.connection,e.teamId]),de=y.useCallback(async q=>{const N=q??m.current;if(!e.connection||!e.teamId||!N)return null;const F=(S.current.get(N)??0)+1;S.current.set(N,F);const ee=await Q.teamChatThread(e.connection,e.teamId,N);Gh(ee.messages,O.current,M.current);const me=Wh(ee,O.current);return S.current.get(N)!==F||(n($e=>$e.selectedThreadId===N?{...$e,threads:fu($e.threads,N),detail:hu(Nee($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]),Me=y.useCallback(async q=>{const N=q??u.current;if(!e.connection||!e.teamId||!N)return null;const F=(g.current.get(N)??0)+1;g.current.set(N,F);const ee=await Q.teamChatAiThread(e.connection,e.teamId,N);return g.current.get(N)===F&&u.current===N&&n(me=>Ck(me,ee,u.current)),ee},[e.connection,e.teamId]),Ie=y.useCallback(async q=>{const N=q??C.current;if(!e.connection||!e.teamId||!N)return null;const F=await Q.teamChatAgentConversation(e.connection,e.teamId,N);return n(ee=>ee.agentConversation?.run.id===N?{...ee,agentConversation:F}:ee),F},[e.connection,e.teamId]);y.useEffect(()=>{m.current=t.selectedThreadId},[t.selectedThreadId]),y.useEffect(()=>{C.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),y.useEffect(()=>{const q=t.agentConversation?.run.status;if(!q||!["pending","queued","running"].includes(q))return;const N=window.setInterval(()=>{Ie().catch(F=>{n(ee=>({...ee,error:In(F)}))})},2500);return()=>window.clearInterval(N)},[Ie,t.agentConversation?.run.status]),y.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(jk),A(null),D(null),M.current.clear(),O.current.clear(),S.current.clear(),g.current.clear(),k.current+=1,c(null),j.current.clear(),R.current=0,P.current=0;return}let q=!1;return u.current=null,f.current+=1,k.current+=1,A(null),D(null),M.current.clear(),O.current.clear(),j.current.clear(),R.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(q)return;P.current=N.cursor;const F=Q.teamChatMembers(e.connection,e.teamId),ee=Q.teamChatAgents(e.connection,e.teamId),me=await Q.teamChatGeneral(e.connection,e.teamId),[$e,ze,tt]=await Promise.all([F,ee,Q.teamChatThreads(e.connection,e.teamId)]);if(q)return;const nt=m.current&&tt.threads.some(Oe=>Oe.id===m.current)?m.current:me.thread.id,pt=nt===me.thread.id?me:await Q.teamChatThread(e.connection,e.teamId,nt);if(q)return;const bt=hu(pt);n(Oe=>({...Oe,members:$e.members,agents:ze.agents,threads:fu(tt.threads,nt),selectedThreadId:nt,detail:bt,loading:!1,error:null})),Mk({connection:e.connection,teamId:e.teamId,threadId:nt,lastMessageSequence:bt?.thread.lastMessageSequence??0}),D(e.teamId)}catch(N){if(q)return;n(F=>({...F,loading:!1,error:In(N)}))}})(),()=>{q=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const ne=y.useCallback(q=>{if(j.current.has(q.id))return;if(j.current.add(q.id),j.current.size>2e3){const F=j.current.values().next().value;typeof F=="number"&&j.current.delete(F)}const N=tT(q);if(N&&q.type==="message.created"){const F=a.current,ee=F.threads.find($e=>$e.id===N.threadId)??(F.detail?.thread.id===N.threadId?F.detail.thread:null),me=$e=>{q.id<=R.current||Wee({mode:o,currentUserId:e.currentUserId,message:N,thread:$e})&&(R.current=q.id,c(Gee({eventId:q.id,message:N,thread:$e,members:F.members})))};ee?me(ee):J().then($e=>{const ze=$e.find(tt=>tt.id===N.threadId);ze&&me(ze)}).catch(()=>{})}N?.clientRequestId&&!N.id.startsWith("pending:")&&(O.current.delete(N.clientRequestId),M.current.delete(N.clientRequestId)),n(F=>nT(F,q,e.currentUserId)),q.type==="thread.created"&&J().catch(F=>{n(ee=>({...ee,error:In(F)}))}),(q.type==="ai_thread.created"||q.type==="ai_turn.updated")&&(de(q.threadId).catch(F=>{n(ee=>({...ee,error:In(F)}))}),q.conversationId===u.current&&Me(q.conversationId).catch(F=>{n(ee=>({...ee,error:In(F)}))})),N&&q.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,Me,de,J]),je=y.useCallback(async()=>{if(!(!e.connection||!e.teamId||$.current)){$.current=!0;try{let q=!0;for(;q;){const N=await Q.teamChatEvents(e.connection,e.teamId,{after:P.current,limit:250});for(const F of N.events)ne(F);P.current=N.cursor,q=N.hasMore}}finally{$.current=!1}}},[ne,e.connection,e.teamId]);y.useEffect(()=>{if(!e.connection||!e.teamId||E!==e.teamId)return;let q=!1,N=null;const F=async()=>{try{const ee=await Q.teamChatRealtimeSession(e.connection,e.teamId);if(q||(await je(),q))return;A(ee);const me=Math.max(3e4,new Date(ee.expiresAt).getTime()-Date.now()-3e4);N=window.setTimeout(()=>{F()},me)}catch{q||(je().catch(()=>{}),N=window.setTimeout(()=>{F()},1e4))}};return F(),()=>{q=!0,N!==null&&window.clearTimeout(N),A(null)}},[je,e.connection,e.teamId,E]);const Se=t.threads.map(q=>q.id).sort().join(",");y.useEffect(()=>{if(!w)return;const q=Tee({session:w,threadIds:Se?Se.split(","):[],onEvent:ne,onReady:()=>{je().catch(N=>{n(F=>({...F,error:In(N)}))})},onError:()=>{je().catch(()=>{})}});return()=>{q.close()}},[ne,je,w,Se]),y.useEffect(()=>{if(!e.connection||!e.teamId||E!==e.teamId)return;const q=window.setInterval(()=>{je().catch(()=>{})},15e3);return()=>window.clearInterval(q)},[je,e.connection,e.teamId,E]);const oe=y.useCallback(async q=>{if(!e.connection||!e.teamId)return;const N=k.current+1;k.current=N;const F=m.current!==q;m.current=q,F&&(f.current+=1,u.current=null),n(ee=>({...ee,threads:fu(ee.threads,q),selectedThreadId:q,detail:ee.detail?.thread.id===q?hu(ee.detail):null,aiThread:F?null:ee.aiThread,agentConversation:F?null:ee.agentConversation,loading:!0,error:null}));try{const ee=await Q.teamChatThread(e.connection,e.teamId,q);if(k.current!==N||m.current!==q)return;Gh(ee.messages,O.current,M.current);const me=Wh(ee,O.current);n($e=>({...$e,threads:fu($e.threads,q),detail:hu(me),loading:!1})),await Q.markTeamChatRead(e.connection,q,e.teamId,me.thread.lastMessageSequence).catch(()=>{})}catch(ee){if(k.current!==N)return;n(me=>({...me,loading:!1,error:In(ee)}))}},[e.connection,e.teamId]),be=y.useCallback(async q=>{if(!e.connection||!e.teamId)return null;const N=k.current+1;k.current=N,n(F=>({...F,busy:!0,error:null}));try{const F=await Q.teamChatDm(e.connection,e.teamId,q);if(k.current!==N)return null;Gh(F.messages,O.current,M.current);const ee=Wh(F,O.current),me=m.current!==ee.thread.id;return m.current=ee.thread.id,me&&(f.current+=1,u.current=null),n($e=>({...$e,selectedThreadId:ee.thread.id,detail:ee,aiThread:me?null:$e.aiThread,agentConversation:me?null:$e.agentConversation,busy:!1})),await Mk({connection:e.connection,teamId:e.teamId,threadId:ee.thread.id,lastMessageSequence:ee.thread.lastMessageSequence}),await J(),ee}catch(F){return k.current!==N||n(ee=>({...ee,busy:!1,error:In(F)})),null}},[e.connection,e.teamId,J]),re=y.useCallback(async()=>{const q=t.detail,N=q?.messages[0]?.sequence;if(!e.connection||!e.teamId||!q||!q.hasMoreBefore||N==null)return!1;n(F=>({...F,loading:!0,error:null}));try{const F=await Q.teamChatThread(e.connection,e.teamId,q.thread.id,{beforeSequence:N,limit:50});return n(ee=>{if(ee.detail?.thread.id!==q.thread.id)return ee;const me=[...F.messages,...ee.detail.messages];return{...ee,loading:!1,detail:{...ee.detail,messages:_d(me),hasMoreBefore:F.hasMoreBefore}}}),!0}catch(F){return n(ee=>({...ee,loading:!1,error:In(F)})),!1}},[e.connection,e.teamId,t.detail]),ue=y.useCallback(async q=>{const N=m.current,F=zee(q.attachments??[]);if(!F)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||!q.body.trim()&&F.length===0)return!1;if(q.replyToMessage&&(q.replyToMessage.threadId!==N||q.replyToMessage.teamId!==e.teamId||q.replyToMessage.id.startsWith("pending:")||q.replyToMessage.deletedAt))return n($e=>({...$e,error:"That message is no longer available to reply to."})),!1;if(q.useModel){if(F.length>0)return n(ze=>({...ze,error:"Images can be sent to the team thread with Use model turned off."})),!1;const $e=f.current;n(ze=>({...ze,busy:!0,error:null}));try{const ze=await Q.createTeamChatAiThread(e.connection,N,{teamId:e.teamId,body:q.body.trim(),clientRequestId:crypto.randomUUID(),providerId:q.providerId,modelId:q.modelId}),tt=f.current===$e&&m.current===N;return tt&&(f.current+=1,u.current=ze.conversationId),n(nt=>({...nt,aiThread:tt?ze:nt.aiThread})),ze.activeTurn&&await Q.executeTeamChatAiTurn(e.connection,ze.activeTurn.id,e.teamId),await Promise.all([de(N),J()]),n(nt=>({...nt,busy:!1})),!0}catch(ze){return n(tt=>({...tt,busy:!1,error:In(ze)})),!1}}const ee=crypto.randomUUID();if(q.selectedActionKey){if(F.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,Zee({teamId:e.teamId,body:q.body,clientRequestId:ee,selectedActionKey:q.selectedActionKey,approvalId:q.approvalId})),await Promise.all([de(N),J()]),n($e=>({...$e,busy:!1})),!0}catch($e){return n(ze=>({...ze,busy:!1,error:In($e)})),!1}}M.current.set(ee,{inputs:F,uploaded:null});const me=Hee({clientRequestId:ee,threadId:N,teamId:e.teamId,userId:e.currentUserId,body:q.body.trim(),mentionUserIds:q.mentionUserIds??[],attachments:F,replyToMessage:q.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});O.current.set(ee,me),n($e=>Lee($e,me));try{const $e=[];for(const[nt,pt]of F.entries())$e.push(await Q.uploadTeamChatAttachment(e.connection,N,{teamId:e.teamId,attachment:pt})),Rk(O.current,ee,`${nt+1} of ${F.length}`),n(bt=>Ak(bt,ee,`${nt+1} of ${F.length}`));const ze=M.current.get(ee);ze&&(ze.uploaded=$e);const tt=await Q.sendTeamChatMessage(e.connection,N,{teamId:e.teamId,body:q.body.trim(),clientRequestId:ee,mentionUserIds:q.mentionUserIds,attachmentIds:$e.map(nt=>nt.id),replyToMessageId:q.replyToMessage?.id??null});return M.current.delete(ee),O.current.delete(ee),n(nt=>Pk(nt,tt,e.currentUserId)),!0}catch($e){return Jh(O.current,ee,"failed"),n(ze=>({...qee(ze,ee),error:In($e)})),!1}},[e.connection,e.currentUserId,e.teamId,de,J,t.detail?.thread.lastMessageSequence]),ke=y.useCallback(async q=>{if(!(!e.connection||!e.teamId)){f.current+=1,u.current=q,n(N=>({...N,aiThread:N.aiThread?.conversationId===q?N.aiThread:null,busy:!0,error:null}));try{const N=await Q.teamChatAiThread(e.connection,e.teamId,q);if(u.current!==q)return;n(F=>({...F,aiThread:N,busy:!1}))}catch(N){if(u.current!==q)return;n(F=>({...F,busy:!1,error:In(N)}))}}},[e.connection,e.teamId]),Le=y.useCallback(async q=>{if(!(!e.connection||!e.teamId)){C.current=q,n(N=>({...N,busy:!0,error:null}));try{const N=await Q.teamChatAgentConversation(e.connection,e.teamId,q);n(F=>({...F,agentConversation:N,busy:!1}))}catch(N){n(F=>({...F,busy:!1,error:In(N)}))}}},[e.connection,e.teamId]),we=y.useCallback(()=>{C.current=null,n(q=>({...q,agentConversation:null}))},[]),le=y.useCallback(async q=>{const N=m.current,F=t.agentConversation;if(!e.connection||!e.teamId||!N||!F||!q.body.trim())return!1;n(ee=>({...ee,busy:!0,error:null}));try{const ee=await Q.createTeamChatAgentRun(e.connection,N,Jee({teamId:e.teamId,body:q.body,clientRequestId:q.clientRequestId,conversation:F}));C.current=ee.run.id;const[me]=await Promise.all([Q.teamChatAgentConversation(e.connection,e.teamId,ee.run.id),de(N),J()]);return n($e=>({...$e,agentConversation:me,busy:!1})),!0}catch(ee){return n(me=>({...me,busy:!1,error:In(ee)})),!1}},[e.connection,e.teamId,de,J,t.agentConversation]),xe=y.useCallback(()=>{f.current+=1,u.current=null,n(q=>({...q,aiThread:null}))},[]),Ue=y.useCallback(async q=>{const N=u.current;if(!e.connection||!e.teamId||!N||!q.body.trim())return!1;n(F=>({...F,busy:!0,error:null}));try{const F=await Q.sendTeamChatAiTurn(e.connection,N,{teamId:e.teamId,body:q.body.trim(),clientRequestId:crypto.randomUUID(),providerId:q.providerId,modelId:q.modelId});return n(ee=>({...Ck(ee,F,u.current),busy:!1})),F.activeTurn&&await Q.executeTeamChatAiTurn(e.connection,F.activeTurn.id,e.teamId),!0}catch(F){return n(ee=>({...ee,busy:!1,error:In(F)})),!1}},[e.connection,e.teamId]),Ze=y.useCallback(async()=>{const q=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!q?!1:(await Q.cancelTeamChatAiTurnExecution(e.connection,q,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),it=y.useCallback(async(q,N)=>{if(!e.connection||!e.teamId)return!1;try{return await Q.editTeamChatMessage(e.connection,q.threadId,q.id,{teamId:e.teamId,body:N}),await de(q.threadId),!0}catch(F){return n(ee=>({...ee,error:In(F)})),!1}},[e.connection,e.teamId,de]),at=y.useCallback(async q=>{if(!e.connection||!e.teamId)return!1;try{return await Q.deleteTeamChatMessage(e.connection,q.threadId,q.id,e.teamId),await de(q.threadId),!0}catch(N){return n(F=>({...F,error:In(N)})),!1}},[e.connection,e.teamId,de]),Ne=y.useCallback(async q=>{if(!e.connection||!e.teamId||!q.clientRequestId||!q.id.startsWith("pending:"))return!1;const N=Array.isArray(q.metadata.mentionUserIds)?q.metadata.mentionUserIds.filter(me=>typeof me=="string"):[],F=M.current.get(q.clientRequestId),ee=q.refs.find(me=>me.refType==="message_reply");Jh(O.current,q.clientRequestId,"sending"),n(me=>nv(me,q.clientRequestId,"sending"));try{let me=F?.uploaded??[];if(F&&!F.uploaded){me=[];for(const[ze,tt]of F.inputs.entries())me.push(await Q.uploadTeamChatAttachment(e.connection,q.threadId,{teamId:e.teamId,attachment:tt})),Rk(O.current,q.clientRequestId,`${ze+1} of ${F.inputs.length}`),n(nt=>Ak(nt,q.clientRequestId,`${ze+1} of ${F.inputs.length}`));F.uploaded=me}const $e=await Q.sendTeamChatMessage(e.connection,q.threadId,{teamId:e.teamId,body:q.body,clientRequestId:q.clientRequestId,mentionUserIds:N,attachmentIds:me.map(ze=>ze.id),replyToMessageId:ee?.refId??null});return M.current.delete(q.clientRequestId),O.current.delete(q.clientRequestId),n(ze=>Pk(ze,$e,e.currentUserId)),!0}catch(me){return Jh(O.current,q.clientRequestId,"failed"),n($e=>({...nv($e,q.clientRequestId,"failed"),error:In(me)})),!1}},[e.connection,e.currentUserId,e.teamId]),We=y.useCallback(q=>{q.id.startsWith("pending:")&&(q.clientRequestId&&M.current.delete(q.clientRequestId),q.clientRequestId&&O.current.delete(q.clientRequestId),n(N=>Uee(N,q.id)))},[]),qe=y.useCallback(async(q,N)=>{if(!e.connection||!e.teamId)return!1;try{const F=await Q.setTeamChatThreadMuted(e.connection,q,e.teamId,N),ee=me=>me.id===F.threadId?{...me,mutedAt:F.mutedAt}:me;return n(me=>({...me,threads:me.threads.map(ee),detail:me.detail?.thread.id===F.threadId?{...me.detail,thread:ee(me.detail.thread)}:me.detail,error:null})),!0}catch(F){return n(ee=>({...ee,error:In(F)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:o,incomingNotification:s,setNotificationMode:U,dismissIncomingNotification:L,setThreadMuted:qe,selectThread:oe,openDm:be,loadMoreMessages:re,sendMessage:ue,openAiThread:ke,openAgentConversation:Le,closeAgentConversation:we,sendAgentTurn:le,closeAiThread:xe,sendAiTurn:Ue,stopAiTurn:Ze,editMessage:it,deleteMessage:at,retryMessage:Ne,dismissFailedMessage:We,refreshDirectory:X,refresh:async()=>{await Promise.all([X(),J(),de(),Me(),Ie()])}}}function In(e){return Vee(e)}const oT="local-profile-agent";function Poe(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(s=>{const c=s.implementation;return c?.type!=="openpond-agent"||c.profileName!==t.activeProfile?[]:[gr(c.agentName),gr(s.name),gr(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(gr(s.name))||n.has(gr(s.id))?[]:[ete(t,s)]:[]);return[...e.hostedActions,...r]}function Aoe(e){return e?.implementation?.type===oT}function Toe(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function Qee(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 Xee(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",o=gr(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(c=>gr(c)===o))})??null}function ete(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:tte(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:oT,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function tte(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 gr(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const Ok=5;function nte(e){return y.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=Qee(n,t);if(a)throw new Error(a);const o=n?.agents.find(u=>u.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,c=s?.agentId===t?s.runtimeAgentId:null;e.applyBootstrapPayload(await Q.bootstrap(e.connection));let m=null;for(let u=0;u<Ok;u+=1){const f=await e.refreshDirectory();if(m=Xee(f.agents,{runtimeAgentId:c,profileName:n.activeProfile,agentName:o.name}),m)break;u<Ok-1&&await ate(200*(u+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 ate(e){return new Promise(t=>{setTimeout(t,e)})}function ite(e){y.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 ote(e){const{connection:t,refreshToken:n=null}=e,[a,o]=y.useState([]),[r,s]=y.useState(null),[c,m]=y.useState(null),[u,f]=y.useState(null),[g,S]=y.useState(!1),[k,C]=y.useState(!1),[P,j]=y.useState(!1),[R,$]=y.useState(null),[O,M]=y.useState(null),[w,A]=y.useState(null),[E,D]=y.useState(0),U=y.useRef(0),L=y.useMemo(()=>a.find(re=>re.id===c)??null,[a,c]),J=y.useCallback(async()=>{if(!t)return!1;S(!0),$(null);try{const re=await Q.communities(t);return o(re.items),s(re.nextCursor),m(ue=>ue&&re.items.some(ke=>ke.id===ue)?ue:null),!0}catch(re){return $(Hu(re)),!1}finally{S(!1)}},[t]),X=y.useCallback(async()=>{if(!t||!r||g)return!1;S(!0),$(null);try{const re=await Q.communities(t,r);return o(ue=>rte(ue,re.items)),s(re.nextCursor),!0}catch(re){return $(Hu(re)),!1}finally{S(!1)}},[t,g,r]),de=y.useCallback(async re=>{if(!t)return null;const ue=++U.current;C(!0),M(null);try{const ke=await Q.communityPreview(t,re.slug);return U.current===ue&&f(ke),ke}catch(ke){return U.current===ue&&M(Hu(ke)),null}finally{U.current===ue&&C(!1)}},[t]),Me=y.useCallback(re=>{const ue=a.find(ke=>ke.id===re);ue&&(m(ue.id),f(ke=>ke?.id===ue.id?ke:null),A(null),de(ue))},[a,de]),Ie=y.useCallback(()=>{U.current+=1,m(null),f(null),M(null),A(null)},[]);y.useEffect(()=>{if(!t){o([]),f(null),m(null);return}J()},[t,J,n]),y.useEffect(()=>{!L||u?.id===L.id||k||de(L)},[de,u?.id,k,L]);const ne=y.useCallback(async()=>{const re=L;await J(),re&&await de(re)},[de,J,L]),je=y.useCallback(async()=>{if(!t||!u?.currentRules||P)return!1;j(!0),A(null);try{return await Q.joinCommunity(t,u.id,u.currentRules.id),D(re=>re+1),await ne(),!0}catch(re){const ue=gu(re);return A(ue),ue.kind==="rules_stale"&&await ne(),!1}finally{j(!1)}},[t,P,u,ne]),Se=y.useCallback(async()=>{if(!t||!u?.currentRules||P)return!1;j(!0),A(null);try{return await Q.acceptCommunityRules(t,u.id,u.currentRules.id),D(re=>re+1),await ne(),!0}catch(re){const ue=gu(re);return A(ue),ue.kind==="rules_stale"&&await ne(),!1}finally{j(!1)}},[t,P,u,ne]),oe=y.useCallback(async()=>{if(!t||!u||P)return!1;j(!0),A(null);try{return await Q.leaveCommunity(t,u.id),D(re=>re+1),await ne(),!0}catch(re){return A(gu(re)),!1}finally{j(!1)}},[t,P,u,ne]),be=y.useCallback(async re=>{if(!t||!u||P)return!1;j(!0),A(null);try{return await Q.updateCommunityNotifications(t,u.id,re),o(ue=>ue.map(ke=>ke.id===u.id&&ke.membership?{...ke,membership:{...ke.membership,notificationMode:re}}:ke)),f(ue=>ue?.id===u.id&&ue.membership?{...ue,membership:{...ue.membership,notificationMode:re}}:ue),!0}catch(ue){return A(gu(ue)),!1}finally{j(!1)}},[t,P,u]);return{items:a,nextCursor:r,selectedCommunityId:c,selectedSummary:L,preview:u,discoveryLoading:g,previewLoading:k,membershipBusy:P,discoveryError:R,previewError:O,membershipError:w,membershipVersion:E,refresh:J,loadMore:X,showDiscovery:Ie,selectCommunity:Me,join:je,acceptRules:Se,leave:oe,updateNotifications:be,clearMembershipError:()=>A(null)}}function rte(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 Hu(e){return e instanceof Error?e.message:String(e)}function gu(e){const t=Hu(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 ste(e,t,n){return eT({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const o=FI.safeParse(a);o.success&&e.onEvent(o.data)},onReady:e.onReady,onError:e.onError},t,n)}function lte(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:o}=e,r=n?.id??null,s=n?.membership?.status==="active",c=!n?.capabilities.requiresRulesAcceptance,[m,u]=y.useState([]),[f,g]=y.useState(null),[S,k]=y.useState({}),[C,P]=y.useState([]),[j,R]=y.useState(!1),[$,O]=y.useState(!1),[M,w]=y.useState(!1),[A,E]=y.useState(!1),[D,U]=y.useState(null),[L,J]=y.useState(null),[X,de]=y.useState(null),[Me,Ie]=y.useState(null),[ne,je]=y.useState(!1),[Se,oe]=y.useState(null),[be,re]=y.useState(null),ue=y.useRef(null),ke=y.useRef([]),Le=y.useRef("mentions"),we=y.useRef(0),le=y.useRef({}),xe=y.useRef(new Set),Ue=y.useMemo(()=>m.find(Oe=>Oe.id===f)??null,[m,f]),Ze=f?S[f]??null:null;y.useEffect(()=>{ue.current=f},[f]),y.useEffect(()=>{ke.current=m},[m]),y.useEffect(()=>{Le.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const it=y.useCallback(async()=>{if(!t||!r)return!1;R(!0),U(null);try{const Oe=await Q.communityChannels(t,r);return u(Oe.channels),g(Ye=>Ye&&Oe.channels.some(h=>h.id===Ye)?Ye:Oe.channels.find(h=>h.isDefault)?.id??Oe.channels[0]?.id??null),je(!1),!0}catch(Oe){const Ye=ya(Oe);return U(Ye),Jl(Ye)&&je(!0),!1}finally{R(!1)}},[r,t]),at=y.useCallback(async Oe=>{if(!t||!r)return!1;const Ye=++we.current;O(!0),J(null);try{const h=await Q.communityMessages(t,r,Oe,{limit:50});return Ye!==we.current?!1:(k(B=>({...B,[Oe]:{items:h.messages,hasMoreBefore:h.hasMoreBefore,preview:h.preview}})),je(!1),!0)}catch(h){if(Ye!==we.current)return!1;const B=ya(h);return J(B),Jl(B)&&je(!0),!1}finally{Ye===we.current&&O(!1)}},[r,t]);y.useEffect(()=>{u(n?.channels??[]),k({}),g(n?.channels.find(Oe=>Oe.isDefault)?.id??n?.channels[0]?.id??null),U(null),J(null),de(null),je(!1),xe.current.clear(),r&&it()},[r,it,o]),y.useEffect(()=>{f&&at(f)},[at,f]);const Ne=y.useCallback(async(Oe,Ye)=>{if(!t||!r||!s||!c||Ye<=0)return!1;if((le.current[Oe]??0)>=Ye)return!0;le.current[Oe]=Ye;try{const h=await Q.markCommunityRead(t,r,Oe,Ye);return u(B=>B.map(Y=>Y.id===Oe?{...Y,unreadCount:0,readState:Y.readState?{...Y.readState,lastReadSequence:h.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:h.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:Y)),!0}catch(h){const B=ya(h);return Jl(B)&&je(!0),!1}},[r,t,s,c]);y.useEffect(()=>{const Oe=Ze?.items.at(-1)?.sequence??0;f&&Oe>0&&Ne(f,Oe)},[Ne,f,Ze?.items]);const We=y.useCallback(Oe=>{if(Oe.communityId!==r||xe.current.has(Oe.id))return;xe.current.add(Oe.id);const Ye=BI.safeParse(Oe.payload.message);if(Ye.success&&Oe.type!=="read.updated"){const h=Ye.data;if(k(B=>{const Y=B[Oe.channelId];if(!Y)return B;const se=Y.items.some(G=>G.id===h.id)?Y.items.map(G=>G.id===h.id?h:G):[...Y.items,h].sort((G,_)=>G.sequence-_.sequence);return{...B,[Oe.channelId]:{...Y,items:se}}}),u(B=>B.map(Y=>Y.id===Oe.channelId?{...Y,lastMessageSequence:Math.max(Y.lastMessageSequence,h.sequence),unreadCount:ue.current===Oe.channelId||h.authorUserId===a?0:Math.max(Y.unreadCount+(Oe.type==="message.created"?1:0),0)}:Y)),Oe.type==="message.created"&&h.authorUserId!==a){const B=ke.current.find(se=>se.id===Oe.channelId),Y=cte(h).includes(a??""),ge=Le.current;!B?.readState?.mutedAt&&(ge==="all"||ge==="mentions"&&Y)&&re({communityId:Oe.communityId,channelId:Oe.channelId,message:h})}ue.current===Oe.channelId&&Ne(Oe.channelId,h.sequence);return}Oe.type==="read.updated"&&Oe.payload.userId===a&&it()},[r,a,it,Ne]);y.useEffect(()=>{if(!t||!r||!s||!c)return;let Oe=!1,Ye=null;return de(null),Promise.all([Q.communityRealtimeSession(t,r),Q.communityEvents(t,r)]).then(async([h,B])=>{if(Oe)return;const Y=async()=>{let se=B.cursor;for(;;){const G=await Q.communityEvents(t,r,{after:se,limit:200});if(Oe)return;for(const _ of G.events)We(_);if(se=G.cursor,!G.hasMore)return}},ge=ste({session:h,onEvent:We,onReady:()=>{de(null),Y().catch(se=>de(ya(se)))},onError:se=>de(ya(se))});Ye=()=>ge.close(),await Y()}).catch(h=>{if(!Oe){const B=ya(h);de(B),Jl(B)&&je(!0)}}),()=>{Oe=!0,Ye?.()}},[We,r,t,s,o,c]);const qe=y.useCallback(async()=>{if(!t||!r||!f||M)return!1;const Oe=S[f],Ye=Oe?.items[0]?.sequence;if(!Oe?.hasMoreBefore||Ye==null)return!1;w(!0),J(null);try{const h=await Q.communityMessages(t,r,f,{beforeSequence:Ye,limit:50});return k(B=>{const Y=B[f]??Oe,ge=new Set(Y.items.map(se=>se.id));return{...B,[f]:{...Y,items:[...h.messages.filter(se=>!ge.has(se.id)),...Y.items],hasMoreBefore:h.hasMoreBefore}}}),!0}catch(h){return J(ya(h)),!1}finally{w(!1)}},[r,t,S,M,f]),q=y.useCallback(async Oe=>{if(!t||!r||!f||A)return!1;E(!0),Ie(null),oe(null);try{const Ye=await Promise.all(Oe.attachments.map(B=>Q.uploadCommunityAttachment(t,r,f,B))),h=await Q.sendCommunityMessage(t,r,f,{body:Oe.body,clientRequestId:Oe.clientRequestId,mentionUserIds:Oe.mentionUserIds,attachmentIds:Ye.map(B=>B.id),replyToMessageId:Oe.replyToMessageId});return k(B=>{const Y=B[f]??{items:[],hasMoreBefore:!1,preview:!1};return Y.items.some(ge=>ge.id===h.id)?B:{...B,[f]:{...Y,items:[...Y.items,h]}}}),await Ne(f,h.sequence),!0}catch(Ye){const h=ya(Ye);return Ie(h),oe({...Oe,message:h}),Jl(h)&&je(!0),!1}finally{E(!1)}},[r,t,Ne,f,A]),N=y.useCallback(Oe=>q({body:Oe.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Oe.mentionUserIds??[],attachments:Oe.attachments??[],replyToMessageId:Oe.replyToMessageId??null}),[q]),F=y.useCallback(async(Oe,Ye)=>{if(!t||!r||!f)return!1;Ie(null);try{const h=await Q.editCommunityMessage(t,r,f,Oe,Ye);return $k(k,f,h),!0}catch(h){return Ie(ya(h)),!1}},[r,t,f]),ee=y.useCallback(async Oe=>{if(!t||!r||!f)return!1;Ie(null);try{const Ye=await Q.deleteCommunityMessage(t,r,f,Oe);return $k(k,f,Ye),!0}catch(Ye){return Ie(ya(Ye)),!1}},[r,t,f]),me=y.useCallback(async(Oe,Ye)=>{if(!t||!r)return!1;Ie(null);try{const h=await Q.setCommunityChannelMuted(t,r,Oe,Ye);return u(B=>B.map(Y=>Y.id===Oe&&Y.readState?{...Y,readState:{...Y.readState,mutedAt:h.mutedAt}}:Y)),!0}catch(h){return Ie(ya(h)),!1}},[r,t]),$e=y.useCallback(async(Oe="")=>{if(!t||!r||!s)return[];try{const Ye=await Q.searchCommunityMembers(t,r,{query:Oe,limit:50});return P(h=>dte(h,Ye.items)),Ye.items}catch(Ye){return Ie(ya(Ye)),[]}},[r,t,s]);y.useEffect(()=>{s&&c?$e():P([])},[s,c,$e]);const ze=y.useCallback(async Oe=>{if(!t||!r||!f)return!1;try{const Ye=await Q.communityAttachmentDownload(t,r,f,Oe);return window.open(Ye.url,"_blank","noopener,noreferrer"),!0}catch(Ye){return Ie(ya(Ye)),!1}},[r,t,f]),tt=y.useCallback(()=>f?at(f):Promise.resolve(!1),[at,f]),nt=y.useCallback(()=>Se?q(Se):Promise.resolve(!1),[Se,q]),pt=y.useCallback(()=>oe(null),[]),bt=y.useCallback(()=>re(null),[]);return{channels:m,selectedChannelId:f,selectedChannel:Ue,messages:Ze?.items??[],hasMoreBefore:Ze?.hasMoreBefore??!1,previewMode:Ze?.preview??!s,members:C,channelsLoading:j,messagesLoading:$,olderMessagesLoading:M,sending:A,channelsError:D,messagesError:L,realtimeError:X,actionError:Me,lostMembership:ne,failedSend:Se,incomingNotification:be,selectChannel:g,loadChannels:it,loadMessages:tt,loadOlder:qe,sendMessage:N,retrySend:nt,dismissFailedSend:pt,editMessage:F,deleteMessage:ee,setMuted:me,searchMembers:$e,downloadAttachment:ze,dismissIncomingNotification:bt}}function $k(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 cte(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function dte(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 Jl(e){return e.includes("community_membership_required")||e.includes("community_rules")}function ya(e){return e instanceof Error?e.message:String(e)}function ute(e){const t=ote({connection:e.connection,refreshToken:e.refreshToken}),n=lte({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,o=t.items,r=n.channels,s=t.selectCommunity,c=n.selectChannel,m=n.dismissIncomingNotification,{setView:u,showToast:f}=e,g=y.useCallback(()=>{t.showDiscovery(),u("community")},[t.showDiscovery,u]),S=y.useCallback(C=>{t.selectCommunity(C),u("community")},[t.selectCommunity,u]),k=y.useCallback(C=>{n.selectChannel(C),u("community")},[n.selectChannel,u]);return y.useEffect(()=>{if(!a)return;const C=o.find(j=>j.id===a.communityId),P=r.find(j=>j.id===a.channelId);f(`${C?.displayName??"Community"} · #${P?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{s(a.communityId),c(a.channelId),u("community")},placement:"top-right"}),m()},[r,o,m,a,c,s,u,f]),{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:S,selectCommunityChannel:k},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const mte=[];function pte(e){const t=y.useCallback(a=>BJ(e,a),[e]),n=y.useCallback(()=>UJ(e)??mte,[e]);return y.useSyncExternalStore(t,n,n)}function fte(e){const[t,n]=y.useState(()=>oh());return y.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(oh())}),()=>{a=!1}):(n(oh()),()=>{a=!1})},[e]),t}function hte(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=jX(),[o,r]=y.useState(null),[s,c]=y.useState([]),[m,u]=y.useState(null),[f,g]=y.useState(null),[S,k]=y.useState([]),[C,P]=y.useState(null),[j,R]=y.useState(null),[$,O]=y.useState(dA),[M,w]=y.useState({}),[A,E]=y.useState(()=>new Set),D=y.useCallback((ot,Wt)=>{E(Gt=>{if(Gt.has(ot)===Wt)return Gt;const Jt=new Set(Gt);return Wt?Jt.add(ot):Jt.delete(ot),Jt})},[]),[U,L]=y.useState(0),[J,X]=y.useState(null),de=y.useRef(null),{confirmProjectAction:Me,projectConfirmDialog:Ie,resolveProjectConfirmDialog:ne}=j7(),{query:je,searchOpen:Se,archivedChatsOpen:oe,sectionMenuOpen:be,projectsExpanded:re,cloudProjectsExpanded:ue,chatRowsVisibleCount:ke,sidebarOpen:Le,view:we,selectedAppId:le,selectedProjectId:xe,selectedSessionId:Ue,draftProvider:Ze,draftModel:it,draftExperience:at,codexPermissionMode:Ne,codexReasoningEffort:We,openPondCommandAccessMode:qe,busy:q,diffPanelOpen:N,diffPanelExpanded:F,rightPanelMode:ee,rightChatPanels:me,terminalOpen:$e,settingsSection:ze,newProjectDialogOpen:tt,newProjectMode:nt,newProjectName:pt,newProjectPath:bt,newProjectBusy:Oe,commitDialogOpen:Ye,commitMessage:h,commitIncludeUnstaged:B,commitNextStep:Y,commitDraft:ge,branchDialogOpen:se,branchDialogName:G,toast:_,error:W}=a,ae=DX(we==="labs"),{setQuery:Z,setSearchOpen:ce,setArchivedChatsOpen:fe,setSectionMenuOpen:he,setProjectsExpanded:Ae,setCloudProjectsExpanded:Ce,setChatRowsVisibleCount:He,setSidebarOpen:Pe,setView:Xe,setSelectedAppId:mt,setSelectedProjectId:fn,setSelectedSessionId:Mt,setPrompt:dn,setDraftProvider:yn,setDraftModel:Sn,setDraftExperience:Qt,setCodexPermissionMode:Ja,setCodexReasoningEffort:_a,setOpenPondCommandAccessMode:zn,setDiffPanelOpen:$n,setDiffPanelExpanded:Lt,setRightPanelMode:St,setRightChatPanels:xn,setTerminalOpen:xt,setSyncingWorkspaceAppId:Dt,setSettingsSection:Ca,setNewProjectDialogOpen:Vt,setNewProjectMode:kn,setNewProjectName:st,setNewProjectPath:Mn,setNewProjectBusy:fi,setCommitDialogOpen:hi,setCommitMessage:ha,setCommitIncludeUnstaged:Ra,setCommitNextStep:Bn,setCommitDraft:zi,setBranchDialogOpen:Za,setBranchDialogName:K,setError:Be}=n,{connectionRef:_e,setError:Ve,showToast:wt}=wX({appDispatch:t,error:W,setErrorState:Be}),{appPreferences:na,applyBootstrapPayload:wn,bootstrap:Je,codexHistorySessions:Rn,connection:ht,events:Nn,runtimeEventStore:Ya,approvals:xo,sessions:Pa,startup:ko,setAppPreferences:nr,setBootstrap:Bi,setCodexHistorySessions:Fn,setEvents:Aa,setSessions:aa}=SX({setDraftModel:Sn,setDraftProvider:yn,setCodexPermissionMode:Ja,setCodexReasoningEffort:_a,setOpenPondCommandAccessMode:zn,setError:Ve,setSelectedAppId:mt,setSelectedProjectId:fn,setSelectedSessionId:Mt});_e.current=ht,y.useEffect(()=>{Je&&k(Je.sidebarFileBookmarks??[])},[Je?.sidebarFileBookmarks]);const wo=y.useMemo(()=>[...Nn].reverse().find(ot=>ot.name==="tool.completed"&&ot.action==="manage_sidebar_file")??null,[Nn]),ar=y.useRef(null);y.useEffect(()=>{!ht||!wo||ar.current===wo.id||(ar.current=wo.id,Q.sidebarFiles(ht).then(ot=>k(ot.items)).catch(ot=>Ve(ot instanceof Error?ot.message:String(ot))))},[ht,wo,Ve]);const Io=y.useCallback(async(ot,Wt)=>{if(!ht)return;const Gt=S;k(Jt=>Wt==="none"?Jt.filter(ei=>ei.id!==ot.id):Jt.some(ei=>ei.id===ot.id)?Jt.map(ei=>ei.id===ot.id?{...ei,status:Wt}:ei):[...Jt,{...ot,status:Wt}]);try{const Jt=await Q.patchSidebarFile(ht,{workspaceKind:ot.workspaceKind,workspaceId:ot.workspaceId,workspaceName:ot.workspaceName,path:ot.path,status:Wt,sourceSessionId:ot.sourceSessionId});k(Jt.items)}catch(Jt){k(Gt),Ve(Jt instanceof Error?Jt.message:String(Jt))}},[ht,Ve,S]),_o=fte(ht),_t=FX({connection:ht,profileId:Je?.profile?.activeProfile??"default"}),{pinnedCollapsed:gl,projectsCollapsed:ir,cloudProjectsCollapsed:vl,chatsCollapsed:Ur,savedForLaterCollapsed:bl,sidebarWidth:Fi,sidebarResizing:yl,diffPanelWidth:zr,diffPanelResizing:Br,togglePinnedCollapsed:Fr,toggleProjectsCollapsed:Sl,toggleCloudProjectsCollapsed:xl,toggleChatsCollapsed:gi,toggleSavedForLaterCollapsed:kl,startSidebarResize:Vr,startDiffPanelResize:Kr}=$X({connection:ht,preferences:Je?.preferences,sidebarOpen:Le,diffPanelExpanded:F,setBootstrap:Bi,setError:Ve}),{cloudProjectById:Co,linkedProjectByAppId:Wr,localProjectById:ga,mentionableSandboxApps:wl,selectedApp:or,selectedCloudProject:Vi,selectedProject:ia,selectedProjectLinkedApp:Il,selectedProjectLinkedOpenPondApp:_l,selectedSession:Pn,selectedSessionLinkedProject:Ro,sidebarSessions:Ta}=rZ({bootstrap:Je,codexHistorySessions:Rn,selectedAppId:le,selectedProjectId:xe,selectedSessionId:Ue,sessions:Pa}),Qa=Pn?.experience??at;y.useEffect(()=>{MJ(Qa)},[Qa]);const rr=y.useMemo(()=>S8(Ta,Qa),[Qa,Ta]),Po=XX(Nn,xo),{chatMentionApps:Cl,connectedAppMentions:Gr,pendingApproval:sr}=_Z({bootstrap:Je,connectedAppRows:_o,mentionableSandboxApps:wl,runtimeIndexes:Po,selectedApp:or,selectedCloudProject:Vi,selectedProject:ia,selectedSession:Pn,selectedSessionId:Ue}),{codexHistoryEvents:Ki,setCodexHistoryEvents:Ao}=FZ({connection:ht,selectedSessionId:Ue,selectedSessionLocallyActive:!!(Ue&&A.has(Ue)),selectedSessionStatus:Pn?.status,setCodexHistorySessions:Fn,setError:Ve}),{account:To,accountPending:Jr,accountSignedOut:Zr,activeModel:Ea,activeProvider:ja,activeWorkspaceAppId:Yr,activeWorkspaceId:lr,activeWorkspaceKind:vi,activeWorkspaceLocation:cr,appDefaults:Wi,cloudLinked:Qr,selectedCodexHistoryPending:Xr,selectedSessionProjectId:es,startMessage:Rl,workspaceName:ts}=tZ({bootstrap:Je,draftModel:it,draftProvider:Ze,selectedApp:or,selectedAppId:le,selectedCloudProject:Vi,selectedProject:ia,selectedSession:Pn,selectedSessionId:Ue,selectedSessionLinkedProject:Ro}),ns=y.useMemo(()=>KJ(Je?.account??null),[Je?.account]),Pl=y.useMemo(()=>Vg(Je?.account??null),[Je?.account]),Eo=pte(Pl),as=y.useMemo(()=>JJ(Eo,Wi.defaultTeamId),[Wi.defaultTeamId,Eo]),dr=as?.teamId??null,bi=Yee({connection:ht,teamId:dr,currentUserId:To?.profile?.id??null,refreshToken:Je?.accountMeta.asOf??null}),Al=nte({connection:ht,teamId:dr,applyBootstrapPayload:wn,refreshDirectory:bi.refreshDirectory});ite({notification:bi.incomingNotification,dismiss:bi.dismissIncomingNotification,selectThread:bi.selectThread,setView:Xe,showToast:wt});const{communities:Tl,sidebar:El,view:jl}=ute({connection:ht,currentUserId:To?.profile?.id??null,refreshToken:Je?.accountMeta.asOf??null,setView:Xe,showToast:wt}),yi=bi.aiThread?.conversationId??null,is=we==="team"&&!!yi&&N&&ee==="chat";y.useEffect(()=>{if(we==="team"){if(yi){St("chat"),$n(!0);return}ee==="chat"&&$n(!1)}},[ee,$n,St,yi,we]);const Ml=y.useCallback(()=>{if(yi){if(is){$n(!1);return}St("chat"),$n(!0)}},[$n,St,is,yi]),Ol=y.useMemo(()=>Ba(ia,Je?.cloudProjects??[]),[Je?.cloudProjects,ia]),$l=Pn?.provider==="codex"?qe:Pn?.openPondCommandAccessMode??qe,va=Yr,os=lr,Nl=vi,ft=ts,{openPondActionCatalog:rn,selectedActionCatalog:oa}=fee({cloudProjectById:Co,cloudProjects:Je?.cloudProjects??[],connection:ht,defaultTeamId:Wi.defaultTeamId,accountScopeKey:ns,localProjects:Je?.localProjects??[],profile:Je?.profile,selectedCloudProject:Vi,selectedProject:ia,reportError:Ve}),{expandedProjectIds:hn,expandProject:Dn,toggleProjectExpanded:ba,setExpandedProjectIds:bp}=hee({selectedProjectId:xe});pZ({activeWorkspaceId:lr,activeWorkspaceKind:vi,appDispatch:t,connection:ht,expandProject:Dn,linkedProjectByAppId:Wr,providerSettings:Je?.providers??null,selectedAppId:le,selectedSession:Pn,selectedSessionId:Ue,selectedSessionProjectId:es,setDiffPanelExpanded:Lt,setDraftModel:Sn,setDraftProvider:yn,setError:Ve,setSelectedAppId:mt,setSelectedProjectId:fn,setSessions:aa,setTerminalOpen:xt,toast:_});const{changeCodexPermissionMode:yp,changeCodexReasoningEffort:Sp}=CZ({connection:ht,setBootstrap:Bi,setCodexPermissionMode:Ja,setCodexReasoningEffort:_a,setError:Ve}),{changeOpenPondCommandAccessMode:Cd}=AQ({connection:ht,selectedSession:Pn,setBootstrap:Bi,setError:Ve,setOpenPondCommandAccessMode:zn,setSessions:aa}),xp=fZ({connection:ht,setError:Ve}),ur=y.useCallback(()=>{L(ot=>ot+1)},[]),Rd=gZ({appDispatch:t,expandProject:Dn,linkedProjectByAppId:Wr,requestComposerFocus:ur,onBeginNewChat:()=>{ln({kind:"chat",sessionId:null}),X(null),Qt(ot=>ot==="development"?"work":ot)},setMentionedAppId:g}),rs=y.useCallback(ot=>{const Wt=It("local",ot);t({type:"selectProject",projectId:Wt}),Dn(Wt)},[t,Dn]),{advanceAfterTurn:kp,begin:wp,bindSession:Ip,dismiss:_p,handoff:Cp,prepareTurn:Rp,selectTask:Pp}=ZX({activeModel:Ea,activeProvider:ja,applyBootstrapPayload:wn,beginNewChat:Rd,composerDraftStore:e,connection:ht,requestComposerFocus:ur,selectedLocalProjectId:ia?.id??null,selectedSessionId:Ue,selectLocalProject:rs,setDraftModel:Sn,setDraftProvider:yn,setError:Ve,view:we});OX({connection:ht,events:Nn,showToast:wt}),DQ({searchOpen:Se,sectionMenuOpen:be,setSectionMenuOpen:he,setSearchOpen:ce,setQuery:Z}),y.useEffect(()=>{w({})},[Je?.server.id]);const{chatHistoryLoadStates:Ap,loadMoreSelectedChatHistory:Tp,selectedPagedSessionEvents:Ep,selectedRuntimeIndexes:Pd}=YX({approvals:xo,codexHistoryEvents:Ki,connection:ht,latestServerSequence:Je?.eventWindow?.latestSequence,runtimeIndexes:Po,runtimeEventStore:Ya,selectedSessionId:Ue,serverId:Je?.server.id,setCodexHistoryEvents:Ao,setCodexHistorySessions:Fn,setError:Ve}),{activeSessions:jp,archivedSessions:Mp,pinnedProjects:Op,pinnedSessions:Dl,savedForLaterSessions:Ad,pinnedFiles:$p,savedForLaterFiles:Np,pinnedItems:Td,projectRows:Ed,localProjectRows:Dp,visibleProjectRows:ss,cloudProjectRows:Hp,projectSessionRowsByProjectId:jd,childSessionRowsByParentId:Lp,sidebarProjectIdBySessionId:Hl,chatRows:Md,visibleChatRows:Od,sessionEvents:qp,chatMessages:$d,contextUsage:Up,goalRuntime:zp,subagentRuntime:Nd}=TQ({localProjects:Je?.localProjects??[],cloudProjects:Je?.cloudProjects??[],sessions:rr,runtimeIndexes:Pd,appPreferences:na,selectedSessionId:Ue,selectedProjectId:xe,archivedChatsOpen:oe,projectsExpanded:re,chatRowsVisibleCount:ke,sidebarFileBookmarks:S}),Bp=y.useCallback(ot=>{Qt(ot);const Wt=[...rr].filter(Gt=>ot==="work"?Gt.experience==="work"||Gt.experience==="development":Gt.experience===ot).sort((Gt,Jt)=>Jt.updatedAt.localeCompare(Gt.updatedAt))[0]??[...Ta].filter(Gt=>Gt.experience===ot).sort((Gt,Jt)=>Jt.updatedAt.localeCompare(Gt.updatedAt))[0]??null;if(Wt)t({type:"selectSession",sessionId:Wt.id,appId:ot!=="chat"?Wt.appId:null,projectId:ot!=="chat"?Hl[Wt.id]??null:null});else if(t({type:"beginNewChat",appId:null}),ot==="chat"&&ja==="codex"){const Gt=qg(Je?.providers,{enabledOnly:!0}).find(Jt=>Jt.value!=="codex")?.value??Pr;yn(Gt),Sn(um(Gt,Je?.providers)??xc)}ot==="chat"&&(xt(!1),Lt(!1),St("home")),Xe("chat")},[t,ja,Je?.providers,rr,Lt,Qt,Sn,yn,St,xt,Xe,Hl,Ta]),Dd=y.useCallback(ot=>{const Wt=e.getSnapshot();if(Qt(ot),(Ue||le||xe)&&(t({type:"beginNewChat",appId:null}),Wt&&e.set(Wt)),ot==="chat"&&ja==="codex"){const Gt=qg(Je?.providers,{enabledOnly:!0}).find(Jt=>Jt.value!=="codex")?.value??Pr;yn(Gt),Sn(um(Gt,Je?.providers)??xc)}ot==="chat"&&(xt(!1),Lt(!1),St("home")),Xe("chat")},[ja,t,Je?.providers,e,le,xe,Ue,Lt,Qt,Sn,yn,St,xt,Xe]),{pendingChatUserMessages:Fp,recordPendingChatUserMessage:Vp,visibleChatMessages:Kp}=PQ({chatMessages:$d,runtimeIndexes:Pd,selectedSessionId:Ue}),jo=y.useMemo(()=>j8({selectedAppId:le,selectedProjectId:xe,selectedSessionId:Ue}),[le,xe,Ue]),Hd=y.useRef(null);y.useEffect(()=>{const ot=Hd.current;Hd.current=jo,!(!ot||ot.kind!=="draft"||jo.kind!=="session")&&(zc(ot,jo)||c(Wt=>{const Gt=M8({tabs:Wt,previousScope:ot,activeScope:jo});return Gt.some((ei,If)=>ei!==Wt[If])?Gt:Wt}))},[jo]);const Wp=y.useMemo(()=>O8(s),[s]),{goalRuntime:Gp,runningSessionIds:Ll,selectedSessionRunning:Jp,sidebarGoalRuntimeBySessionId:Zp,sidebarSubagentRuntimeBySessionId:Yp}=NQ({codexHistoryEvents:Ki,codexHistorySessions:Rn,connection:ht,expandedProjectIds:hn,goalRuntime:zp,locallyActiveCodexHistorySessionIds:A,pinnedSessions:Dl,savedForLaterSessions:Ad,projectSessionRowsByProjectId:jd,rightChatHistoryEvents:M,runtimeIndexes:Po,selectedSession:Pn,selectedSessionId:Ue,serverId:Je?.server.id,setCodexHistorySessions:Fn,sidebarSessions:Ta,subagentRuntime:Nd,visibleChatRows:Od,visibleProjectRows:ss}),{dragItem:Qp,pinnedPreviewKeys:Xp,startPinnedDrag:ef,clearSidebarDrag:tf,previewPinnedDrop:nf,commitPinnedDrop:af,commitPinnedPreviewDrop:of}=VZ({connection:ht,appPreferences:na,sessions:Ta,pinnedItems:Td,setAppPreferences:nr,setCodexHistorySessions:Fn,setSessions:aa,sidebarFileBookmarks:S,setSidebarFileBookmarks:k,setError:Ve}),{clearTaskDrag:rf,commitTaskDrop:Ld,commitTaskPreviewDrop:sf,previewTaskDrop:Xa,startTaskDrag:ls,taskDragSessionId:lf,taskPreviewSessionIds:cf}=KZ({connection:ht,sessions:Ta,setCodexHistorySessions:Fn,setError:Ve,setSessions:aa}),{commandProjectRows:df,contextWindowStatus:ql,pinnedRows:uf,sidebarWorkspaceAppIds:mf}=hZ({activeProvider:ja,contextCompaction:Wi.contextCompaction,contextUsage:Up,pinnedItems:Td,pinnedPreviewKeys:Xp??[],pinnedProjects:Op,projectRows:Ed,visibleProjectRows:ss}),Gi=!!(va&&(we==="chat"||we==="labs")&&(Ye||N&&(ee==="changes"||ee==="goal"))),{workspaceStates:cs,workspaceBusy:ds,diffBusy:pf,visibleWorkspaceState:mr,visibleWorkspaceDiff:Ul,rememberWorkspaceState:us,refreshWorkspace:zl,refreshWorkspaceDiff:Si,setWorkspaceBusy:Ud}=bee({connection:ht,activeWorkspaceAppId:va,view:we,shouldLoadWorkspaceDiff:Gi,sidebarWorkspaceAppIds:mf,setError:Ve});de.current=us;const ff=y.useCallback((ot=va)=>!ot||ot!==va||!Gi?Promise.resolve(null):Si(ot),[Si,Gi,va]),hf=y.useCallback(async(ot={})=>{!va||!Gi||await Si(va,ot)},[Si,Gi,va]),gf=!1,vf=!!(Pn?.provider==="codex"&&Pn.cwd&&!Hi(Pn.workspaceKind)),bf=!!(mr&&!mr.initialized&&vi!=="local_project"&&ja!=="codex"&&!vf&&!Xr),yf=vi==="local_project"&&!!ia?.sandboxTemplate?.detected&&!ia?.linkedOpenPondApp?.appId,[zd,Bd]=y.useState(null),[Sf,xf]=y.useState(null),{projectTarget:kf,workspaceTarget:wf}=nZ({accountPending:Jr,accountSignedOut:Zr,activeWorkspaceLocation:cr,bootstrap:Je,busy:q,cloudLinked:Qr,selectedCloudProject:Vi,selectedProject:ia,selectedSession:Pn,pendingWorkspaceTarget:zd,workspaceStates:cs,workspaceBusy:ds});return y.useEffect(()=>{Bd(null)},[Pn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:o,setPendingTerminalCommand:r,terminalTabs:s,setTerminalTabs:c,trainingDetailTasksetId:m,setTrainingDetailTasksetId:u,mentionedAppId:f,setMentionedAppId:g,cloudSetupDialog:C,setCloudSetupDialog:P,rightPanelTabRequest:j,setRightPanelTabRequest:R,workspaceDiffPanelViewState:$,setWorkspaceDiffPanelViewState:O,rightChatHistoryEvents:M,setRightChatHistoryEvents:w,locallyActiveCodexHistorySessionIds:A,setCodexHistoryTurnLocallyActive:D,mainComposerFocusRequestId:U,requestMainComposerFocus:ur,draftSubagentDelegationMode:J,setDraftSubagentDelegationMode:X,confirmProjectAction:Me,projectConfirmDialog:Ie,resolveProjectConfirmDialog:ne,query:je,searchOpen:Se,archivedChatsOpen:oe,sectionMenuOpen:be,projectsExpanded:re,cloudProjectsExpanded:ue,sidebarOpen:Le,view:we,selectedAppId:le,selectedProjectId:xe,selectedSessionId:Ue,draftProvider:Ze,draftModel:it,draftExperience:at,activeExperience:Qa,changeExperience:Bp,changeNewExperience:Dd,codexPermissionMode:Ne,codexReasoningEffort:We,openPondCommandAccessMode:qe,busy:q,diffPanelOpen:N,diffPanelExpanded:F,rightPanelMode:ee,rightChatPanels:me,terminalOpen:$e,settingsSection:ze,newProjectDialogOpen:tt,newProjectMode:nt,newProjectName:pt,newProjectPath:bt,newProjectBusy:Oe,commitDialogOpen:Ye,commitMessage:h,commitIncludeUnstaged:B,commitNextStep:Y,commitDraft:ge,branchDialogOpen:se,branchDialogName:G,toast:_,error:W,labDetailNavigation:ae,setQuery:Z,setSearchOpen:ce,setArchivedChatsOpen:fe,setSectionMenuOpen:he,setProjectsExpanded:Ae,setCloudProjectsExpanded:Ce,setChatRowsVisibleCount:He,setSidebarOpen:Pe,setView:Xe,setSelectedAppId:mt,setSelectedProjectId:fn,setSelectedSessionId:Mt,setPrompt:dn,setDraftProvider:yn,setDraftModel:Sn,setDraftExperience:Qt,setDiffPanelOpen:$n,setDiffPanelExpanded:Lt,setRightPanelMode:St,setRightChatPanels:xn,setTerminalOpen:xt,setSyncingWorkspaceAppId:Dt,setSettingsSection:Ca,setNewProjectDialogOpen:Vt,setNewProjectMode:kn,setNewProjectName:st,setNewProjectPath:Mn,setNewProjectBusy:fi,setCommitDialogOpen:hi,setCommitMessage:ha,setCommitIncludeUnstaged:Ra,setCommitNextStep:Bn,setCommitDraft:zi,setBranchDialogOpen:Za,setBranchDialogName:K,setError:Ve,showToast:wt,appPreferences:na,applyBootstrapPayload:wn,approvals:xo,bootstrap:Je,connection:ht,events:Nn,runtimeEventStore:Ya,sessions:Pa,startup:ko,setAppPreferences:nr,setCodexHistorySessions:Fn,setEvents:Aa,setSessions:aa,training:_t,pinnedCollapsed:gl,projectsCollapsed:ir,cloudProjectsCollapsed:vl,chatsCollapsed:Ur,savedForLaterCollapsed:bl,sidebarWidth:Fi,sidebarResizing:yl,diffPanelWidth:zr,diffPanelResizing:Br,togglePinnedCollapsed:Fr,toggleProjectsCollapsed:Sl,toggleCloudProjectsCollapsed:xl,toggleChatsCollapsed:gi,toggleSavedForLaterCollapsed:kl,startSidebarResize:Vr,startDiffPanelResize:Kr,cloudProjectById:Co,localProjectById:ga,selectedApp:or,selectedCloudProject:Vi,selectedProject:ia,selectedProjectLinkedApp:Il,selectedProjectLinkedOpenPondApp:_l,selectedSession:Pn,sidebarSessions:Ta,runtimeIndexes:Po,chatMentionApps:Cl,connectedAppMentions:Gr,pendingApproval:sr,codexHistoryEvents:Ki,setCodexHistoryEvents:Ao,account:To,accountPending:Jr,accountSignedOut:Zr,activeModel:Ea,activeProvider:ja,activeWorkspaceAppId:Yr,activeWorkspaceId:lr,activeWorkspaceKind:vi,activeWorkspaceLocation:cr,appDefaults:Wi,selectedSessionProjectId:es,startMessage:Rl,workspaceName:ts,accountScopeKey:ns,organizations:Eo,teamChatOrganization:as,teamChatTeamId:dr,teamChat:bi,publishTeamProfileAgent:Al,communities:Tl,communitySidebar:El,communityView:jl,teamAiThreadId:yi,toggleTeamAiSidebar:Ml,selectedProjectConfirmedCloudProject:Ol,activeOpenPondCommandAccessMode:$l,viewWorkspaceAppId:va,viewWorkspaceId:os,viewWorkspaceKind:Nl,viewWorkspaceName:ft,openPondActionCatalog:rn,selectedActionCatalog:oa,expandedProjectIds:hn,expandProject:Dn,toggleProjectExpanded:ba,setExpandedProjectIds:bp,changeCodexPermissionMode:yp,changeCodexReasoningEffort:Sp,changeOpenPondCommandAccessMode:Cd,resolveApproval:xp,beginNewChat:Rd,advanceTrainingModelChatAfterTurn:kp,beginNewChatWithTrainingModel:wp,bindTrainingModelChatSession:Ip,dismissTrainingChatHandoff:_p,trainingChatHandoff:Cp,prepareTrainingModelChatTurn:Rp,selectTrainingChatTaskForComposer:Pp,chatHistoryLoadStates:Ap,loadMoreSelectedChatHistory:Tp,selectedPagedSessionEvents:Ep,activeSessions:jp,archivedSessions:Mp,pinnedSessions:Dl,savedForLaterSessions:Ad,pinnedFiles:$p,savedForLaterFiles:Np,sidebarFileBookmarks:S,setSidebarFileStatus:Io,projectRows:Ed,localProjectRows:Dp,visibleProjectRows:ss,cloudProjectRows:Hp,projectSessionRowsByProjectId:jd,childSessionRowsByParentId:Lp,sidebarProjectIdBySessionId:Hl,chatRows:Md,visibleChatRows:Od,chatRowsVisibleCount:ke,sessionEvents:qp,chatMessages:$d,goalRuntime:Gp,subagentRuntime:Nd,pendingChatUserMessages:Fp,recordPendingChatUserMessage:Vp,visibleChatMessages:Kp,activeTerminalScope:jo,terminalSummaries:Wp,runningSessionIds:Ll,selectedSessionRunning:Jp,sidebarGoalRuntimeBySessionId:Zp,sidebarSubagentRuntimeBySessionId:Yp,taskDragSessionId:lf,taskPreviewSessionIds:cf,startTaskDrag:ls,clearTaskDrag:rf,previewTaskDrop:Xa,commitTaskDrop:Ld,commitTaskPreviewDrop:sf,dragItem:Qp,startPinnedDrag:ef,clearSidebarDrag:tf,previewPinnedDrop:nf,commitPinnedDrop:af,commitPinnedPreviewDrop:of,commandProjectRows:df,contextWindowStatus:ql,pinnedRows:uf,workspaceStates:cs,workspaceBusy:ds,diffBusy:pf,visibleWorkspaceState:mr,visibleWorkspaceDiff:Ul,rememberWorkspaceState:us,refreshWorkspace:zl,refreshWorkspaceDiff:Si,setWorkspaceBusy:Ud,refreshWorkspaceDiffWhenNeeded:ff,refreshVisibleWorkspaceDiff:hf,managedWorkspace:gf,canSyncActiveWorkspace:bf,canPublishOpenPondProject:yf,pendingWorkspaceTarget:zd,setPendingWorkspaceTarget:Bd,pendingSidebarWorkspaceTarget:Sf,setPendingSidebarWorkspaceTarget:xf,projectTarget:kf,workspaceTarget:wf}}const gte=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,vte=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function bte(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)?vu(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?vu(n,new Set(["file:"])):null:gte.test(n)?vu(`http://${n}`,new Set(["http:"])):vte.test(n)?vu(`https://${n}`,new Set(["https:"])):null}function vu(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function yte(e){const t=bte(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 Ste="openpond-coding-core-v1",xte="feature";function av(e){const t=new URL("/sandboxes",$y(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",xte),t.searchParams.set("runtimeProfileId",Ste),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 Eoe(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,$y(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function Nk(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,$y(e.accountBaseUrl)).toString()}function $y(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 kte({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:o,rightPanelMode:r,selectedProjectId:s,setDiffPanelOpen:c,setNewProjectDialogOpen:m,setNewProjectMode:u,setNewProjectName:f,setRightPanelMode:g}){const S=y.useCallback(()=>{g("changes"),c(!0)},[c,g]),k=y.useCallback(()=>{if(o&&r==="changes"){c(!1);return}S()},[o,r,c,S]),C=y.useCallback(()=>{g("browser"),c(!0)},[c,g]),P=y.useCallback(()=>{g("goal"),c(!0)},[c,g]),j=y.useCallback((M,w)=>{yte({conversationId:t,href:M,explicitFile:w?.explicitFile,newTab:w?.newTab}).then(A=>{A&&C()})},[t,C]),R=y.useCallback(()=>{u("cloud"),f(""),m(!0)},[m,u,f]),$=y.useCallback(M=>{const w=n.get(M);w&&j(av({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:w.teamId,projectId:w.id,projectName:w.name,baseBranch:w.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,j]);return{createCloudEnvironmentFromSidebar:y.useCallback(()=>{const M=s?.startsWith("cloud:")?s.slice(6):a[0]?.id??null;if(M){$(M);return}R()},[a,R,s,$]),openCloudProjectDialog:R,openUrlInBrowserPanel:j,showBrowserPanel:C,showChangesPanel:S,showGoalSidebarTab:P,toggleChangesPanel:k}}function wte(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 Ite({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){y.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(r=>{const s=wte({currentConversationId:e,requestConversationId:r.conversationId,sessionIds:t});s.reveal&&(s.sessionIdToOpen&&n(s.sessionIdToOpen),a())}),[e,n,a,t])}const _te="chat",Cte=["help me","please","can you","could you","make","create","build"],Rte=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function Dk(e){const t=Zh(e.label);if(t&&!iv(t))return Hk(t);const n=Zh(e.name);if(n&&!iv(n))return Hk(n);const a=Zh(e.actionId)?.replace(/\.chat$/i,"")??"";return Pte(a||t||"Profile Agent")}function iv(e){return e.trim().toLowerCase()===_te}function Pte(e){const t=Ate(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&&!Rte.has(o)).slice(0,3);return rT(a.length?a.join(" "):t||e)}function Hk(e){return rT(e).split(/\s+/).slice(0,4).join(" ")}function Ate(e){let t=e.trim();for(const n of Cte)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function Zh(e){return typeof e=="string"&&e.trim()?e.trim():null}function rT(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const Tte="openpond-profile-action";function Ete(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function bu(e){return typeof e=="string"&&e.trim()?e.trim():null}function jte(e){const t=Ete(e.implementation);if(t?.type!==Tte)return null;const n=bu(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=bu(e.label);if(a&&!iv(a))return Dk({label:a,description:e.description});const o=bu(t.agentName)??bu(e.name);return Dk({actionId:n,description:e.description,name:o})}function Mte(e){const t=jte(e);return t||e.label?.trim()||e.name?.trim()||e.id}function sT(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 Ote=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function lT(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function ol(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ns(e,t,n={}){const a=ol(t)?Wn(String(t)):"";a&&(!n.generic&&Ote.has(a)||e.add(a))}function yu(e,t){const n=ol(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Ns(e,a)}function $te(e,t){const n=ol(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Ns(e,a)}function cT(e){const t=new Set,n=lT(e.implementation),a=ol(n?.actionId);return Ns(t,e.id,{generic:!0}),yu(t,e.id),Ns(t,a,{generic:!0}),yu(t,a),Ns(t,e.name,{generic:!0}),yu(t,e.name),Ns(t,e.label,{generic:!0}),yu(t,e.label),$te(t,e.description),t}function Nte(e){const t=lT(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",ol(t?.actionId)??"",ol(t?.agentName)??"",sT(e),...Array.from(cT(e))].join(" ").toLowerCase()}function joe(e,t,n=8){const a=Wn(t);return e.length===0?[]:e.filter(o=>a?Nte(o).includes(a):!0).slice(0,n)}function Dte(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Wn(t[1]??"")).filter(Boolean)}function Hte(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function Lte(e,t){const n=Dte(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const r of n)for(const s of t)cT(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:Hte(e,o.mention)}}function Moe(e){return Mte(e)}function Ooe(e){return e.description||sT(e)}const Ny=[{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 qte(e){return Ny.filter(t=>t.id!=="goal"||e==="codex")}function dT(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 $oe(e,t){return qte(e).filter(n=>dT(n,t))}const Ute=new Set(Ny.map(e=>e.id));function Noe(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function zte(e){return[e.id,e.command,e.label,e.description].join(" ")}function Bte(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function Fte(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return Ute.has(n)?{command:n,args:t[2]?.trim()??""}:null}function Vte(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function Doe({commands:e=Ny,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(c=>c.id.startsWith(a));if(o.length>0)return o.slice(0,n);const r=e.filter(c=>zte(c).toLowerCase().includes(a));return(r.length>0?r:e.filter(c=>Bte(c).toLowerCase().includes(a))).slice(0,n)}function Hoe(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function gp(e){return e?.role==="owner"||e?.role==="admin"}function Loe(e){const t=vp(e.organizations,e.defaultTeamId),n=gp(t),a=e.localProject??null;if(!a)return Kte("Open a local project to set up an Agent.");const o=Wte(a,e.projects),r=Gte(a,o,e.agents),s=!!a.sandboxTemplate?.detected,c=t&&!n?"Ask an owner or admin to connect this project.":null;return s?o?Jte(a,o)?Su({state:"needs_sync",actionLabel:"Sync Project",project:o,agent:r,canManage:n,actionBlockedReason:c}):r?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:o,agent:r}:Su({state:"needs_agent",actionLabel:"Create Agent",project:o,agent:null,canManage:n,actionBlockedReason:c}):Su({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:c}):Su({state:"missing_config",actionLabel:"Add Agent config",project:o,agent:r,canManage:n,actionBlockedReason:c})}function Su(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 Kte(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function vp(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 Wte(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function Gte(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 Jte(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 pr=e=>e.slice(0,2e4);function Zte({model:e,provider:t,providerSettings:n}){return{model:gy(t,e,n),modelRef:ni(t,e,n)}}function Yte(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function Qte(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 Xte(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 Lk({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 ene({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:o,draftModel:r,draftProvider:s,experience:c,expandProject:m,ensureCloudSessionReady:u,getPrompt:f,bootstrap:g,chatMessages:S,apps:k,connectedAppMentions:C,mentionedAppId:P,refreshWorkspace:j,refreshWorkspaceDiff:R,selectedApp:$,selectedActionCatalog:O,openPondActionCatalog:M,cloudProjects:w,accountScopeKey:A,selectedCloudProject:E,selectedProject:D,selectedProjectLinkedOpenPondApp:U,selectedSession:L,workspaceTarget:J,subagentDelegationMode:X,setDraftModel:de,setDraftProvider:Me,setError:Ie,setPrompt:ne,setMentionedAppId:je,setCodexHistoryEvents:Se,setCodexHistorySessions:oe,onCodexHistoryTurnActivityChange:be,onCodexHistoryTurnPayload:re,onPendingUserMessage:ue,setEvents:ke,setSelectedAppId:Le,setSelectedProjectId:we,setSelectedSessionId:le,setSessions:xe,setView:Ue,setWorkspaceBusy:Ze}){function it(G){Q.bootstrap(G).then(e).catch(_=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",_);const W=_ instanceof Error?_.message:String(_);Ie(`Message sent, but the chat list could not refresh: ${W}`)})}const at=y.useRef(new Set),Ne=g?.providers??null;function We(G,_){return G==="codex"?void 0:_}function qe(G){return!!(G&&G.provider!=="codex"&&(G.workspaceKind==="local_project"&&G.cwd?.trim()||(G.workspaceKind==="sandbox"||G.workspaceKind==="sandbox_template"||G.workspaceKind==="sandbox_app")&&G.workspaceId))}function q(G){Me(G),de(_=>er(G,_,Ne)),Ue("chat")}async function N(G,_){return(FA(_,A)??await Ay({teamId:_,accountKey:A,fetchAgents:async Z=>(await Q.listSandboxAgents(t,{teamId:Z})).agents})).find(Z=>Z.projectId===G)??null}async function F(){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 G=await Q.organizations(t),_=vp(G.organizations.map(up).filter(W=>!!W).filter(W=>W.status==="active"),g?.preferences.defaultTeamId??null);if(!_)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!gp(_))throw new Error(`You need owner or admin access to create projects in ${_.displayName}.`);return _}async function ee(G){if(!t)return!1;const _=D;if(!_)throw new Error("Select a local Project before using /sync-cloud.");const W=await F(),ae=_.linkedSandboxProject?.defaultBranch?.trim()||"main",Z=It("local",_.id),ce=Ba(_,w),fe=await Q.createSession(t,{provider:"openpond",modelRef:ni("openpond",Ks,Ne),openPondCommandAccessMode:We("openpond",o),appId:null,appName:null,workspaceKind:"local_project",workspaceId:_.id,workspaceName:_.name,localProjectId:_.id,cloudProjectId:ce?.id??null,cloudTeamId:ce?.teamId??null,cwd:_.workspacePath,title:`Sync ${_.name} to Cloud`});xe(he=>[fe,...he]),G.onSessionCreated?.(fe),G.selectSession&&(le(fe.id),we(Z),Le(null),Ue("chat"),m(Z)),G.clearPromptForTurn(),Ze(!0);try{const he=await Q.uploadLocalProjectCloudSource(t,_.id,{teamId:W.teamId,projectName:_.name,branch:ae,chatSessionId:fe.id,displayPrompt:G.displayPrompt});return e(he.bootstrap),m(Z),m(It("cloud",he.project.id)),!0}catch(he){const Ae=await Q.bootstrap(t).catch(()=>null);throw Ae&&e(Ae),he}finally{Ze(!1)}}async function me(G){if(!t||G.providerForTurn==="codex"||G.selectedSessionForTurn?.provider==="codex")return!1;let _=qe(G.selectedSessionForTurn)?G.selectedSessionForTurn:null;if(!_&&G.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!_)if(E){const ae=It("cloud",E.id),Z=G.providerForTurn;_=await Q.createSession(t,{provider:Z,modelRef:ni(Z,G.modelForTurnValue,Ne),openPondCommandAccessMode:We(Z,G.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:E.id,workspaceName:E.name,localProjectId:null,cloudProjectId:E.id,cloudTeamId:E.teamId,cwd:null,autoTitlePrompt:pr(G.command)}),xe(ce=>[_,...ce]),G.onSessionCreated?.(_),G.selectSession&&(le(_.id),we(ae),Le(null),Ue("chat"),m(ae))}else{const ae=D;if(!ae)throw new Error("Select a project to use this.");const Z=Ba(ae,w),ce=It("local",ae.id),fe=G.providerForTurn;_=await Q.createSession(t,{provider:fe,modelRef:ni(fe,G.modelForTurnValue,Ne),openPondCommandAccessMode:We(fe,G.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:ae.id,workspaceName:ae.name,localProjectId:ae.id,cloudProjectId:Z?.id??null,cloudTeamId:Z?.teamId??null,cwd:ae.workspacePath,autoTitlePrompt:pr(G.command)}),xe(he=>[_,...he]),G.onSessionCreated?.(_),G.selectSession&&(le(_.id),we(ce),Le(null),Ue("chat"),m(ce))}if(!_)throw new Error("Select a project to use this.");G.clearPromptForTurn();const W=await Q.runSessionCommand(t,_.id,{command:G.command,cwd:_.cwd});return xe(ae=>ic(ae,W.session)),ke(ae=>eo(ae,W.events)),!0}async function $e(G=[],_=null,W,ae={}){const Z=W??f();let ce=Z.trim()||(G.length>0?"Please review the attached files.":"");if(!t||!ce)return!1;const fe=ae.displayPrompt?.trim()||ce,he=ae.provider??s,Ae=ae.model??r,Ce=ae.openPondCommandAccessMode??o,He=ae.session!==void 0,Pe=He?ae.session??null:L,Xe=ae.experience??Pe?.experience??c,mt=Xe==="development"||Xe==="work"&&(Pe?.workspaceKind==="local_project"||!!Pe?.localProjectId||!!Pe?.cloudProjectId||!He&&!!(D||E||$||J==="hybrid"||J==="local")),fn=He||!mt?null:$,Mt=He||!mt?null:D,dn=He||!mt?null:E,yn=He||!mt?null:U,Sn=!He&&mt&&J==="hybrid",Qt=ae.selectSession??!0,Ja=ae.chatMessages??S,_a=ae.session!==void 0?null:P,zn=ae.clearPrompt===void 0?()=>{ne(""),je(null)}:ae.clearPrompt,$n=_?null:Lte(ce,O),Lt=_??$n?.action??null,St=$n?.prompt||ce,xn=mt&&!Lt?Vte(ce):null,xt=Lt||xn?null:Fte(ce),Dt=xt&&!dT({id:xt.command},Xe)?xt:null,Ca=ae.usageAttribution??(xt?{surface:"chat",workflowKind:"slash_command",commandName:`/${xt.command}`,commandSource:"prompt_parse"}:void 0);Ie(null);let Vt=null,kn=null;try{if(!mt&&he==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(Dt)throw new Error(`/${Dt.command} isn't available in ${Xe}.`);if(xn&&he!=="codex"&&Pe?.provider!=="codex"){if(G.length>0)throw new Error("Direct commands do not accept attachments.");return await me({command:xn.command,clearPromptForTurn:zn,modelForTurnValue:Ae,onSessionCreated:ae.onSessionCreated,openPondCommandAccessModeForTurn:Ce,providerForTurn:he,selectedSessionForTurn:Pe,selectSession:Qt})}if(!He&&xt?.command==="sync-cloud")return await ee({clearPromptForTurn:zn,displayPrompt:fe,onSessionCreated:ae.onSessionCreated,selectSession:Qt});if(Lt){const K=oee(Lt);if(K){let Je=Pe;if(!Je||Je.cloudProjectId!==K.projectId){Je=await Q.createSession(t,{provider:"openpond",modelRef:ni("openpond",Ae,Ne),openPondCommandAccessMode:We("openpond",Ce),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:K.projectId,workspaceName:K.projectName??K.agentName,localProjectId:null,cloudProjectId:K.projectId,cloudTeamId:K.teamId,cwd:null,autoTitlePrompt:pr(fe)}),xe(Ya=>[Je,...Ya]),ae.onSessionCreated?.(Je),Qt&&le(Je.id);const Nn=It("cloud",K.projectId);Qt&&we(Nn),Qt&&m(Nn)}const Rn=await Q.runSandboxAgent(t,K.agentId,dee({agent:K,attachments:G,displayPrompt:fe,prompt:St})),ht=await Q.bootstrap(t);return e(ht),zn(),ke(Nn=>eo(Nn,Lk({action:Lt,prompt:fe,runPayload:Rn,sessionId:Je.id}))),!0}const Be=My(Lt);if(Be){let Je=Pe;(!Je||Je.provider!=="openpond")&&(Je=await Q.createSession(t,{provider:"openpond",modelRef:ni("openpond",Ae,Ne),openPondCommandAccessMode:We("openpond",Ce),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:pr(fe)}),xe(ht=>[Je,...ht]),ae.onSessionCreated?.(Je),Qt&&le(Je.id)),await Q.runProfileAction(t,lee({action:Be,attachments:G,displayPrompt:fe,prompt:St,sessionId:Je.id}));const Rn=await Q.bootstrap(t);return e(Rn),zn(),!0}const _e=ZA({cloudProjects:w,selectedCloudProject:E,selectedProject:D});if(!_e)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let Ve=Pe;(!Ve||Ve.cloudProjectId!==_e.id)&&(Ve=await Q.createSession(t,{provider:"openpond",modelRef:ni("openpond",Ae,Ne),openPondCommandAccessMode:We("openpond",Ce),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:_e.id,workspaceName:_e.name,localProjectId:_e.localProjectId,cloudProjectId:_e.id,cloudTeamId:_e.teamId,cwd:null,autoTitlePrompt:pr(fe)}),xe(Je=>[Ve,...Je]),ae.onSessionCreated?.(Ve),Qt&&(le(Ve.id),we(_e.selectionKey),m(_e.selectionKey)));const wt=await N(_e.id,_e.teamId);if(!wt)throw new Error("No OpenPond Agent is available for this Project.");zn();const na=await Q.runSandboxAgent(t,wt.id,cee({action:Lt,attachments:G,displayPrompt:fe,prompt:St,teamId:_e.teamId})),wn=await Q.bootstrap(t);return e(wn),ke(Je=>eo(Je,Lk({action:Lt,prompt:fe,runPayload:na,sessionId:Ve.id}))),!0}let st=Pe;if(st&&Kt(st.id)){kn=Zx({afterMessageId:Ja.at(-1)?.id??null,attachments:G,content:ce,sessionId:st.id}),zn(),Vt=st.id,at.current.add(Vt),ue?.(kn),be?.(Vt,!0);const K=Qte(st.id,ce),Be=Ve=>{(!He||L?.id===st.id)&&Se(wt=>Yte(wt,Ve)),ae.onCodexHistoryOptimisticEvent?.(Ve)};Be(K),oe(Ve=>Ve.map(wt=>wt.id===st.id?{...wt,status:"active"}:wt));const _e=await Q.sendCodexHistoryTurn(t,st.id,{prompt:ce,attachments:G.length>0?G:void 0,model:gy("codex",Ae,Ne),modelRef:ni("codex",Ae,Ne),...mx(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(Ve=>{throw Be(Xte(K,Ve)),Ve});return(!He||L?.id===st.id)&&Se(Ve=>eo(Ve,_e.events)),oe(Ve=>ic(Ve,_e.session)),re?.(_e),it(t),!0}const fi=(_a?k.find(K=>K.id===_a&&aZ(Z,K)&&K.sandbox)??null:null)??iZ(Z,fA(k)),hi=Xe==="chat"?[]:yZ(Z,C).map(K=>K.ref);if(!st){const K=yn?.appId??fn?.id??null,Be=yn?.appName??fn?.name??null,_e=dn,Ve=He?null:Ba(Mt,w),wt=Sn?lA({cloudProjects:w,selectedCloudProject:_e,selectedProject:Mt}):null;if(wt?.kind==="missing_cloud_project")throw new Error(wt.message);const na=wt?.kind==="ready",wn=na?he:_e?"openpond":he,Je=ni(wn,Ae,Ne),Rn=We(wn,Ce),ht=na?cA({modelRef:Je,provider:wn,target:wt,title:ce.slice(0,64)}):null;st=await Q.createSession(t,ht?{...ht,subagentDelegationMode:X,metadata:{...ht.metadata,...ae.sessionMetadata??{}},...Rn?{openPondCommandAccessMode:Rn}:{},autoTitlePrompt:pr(ce)}:{experience:Xe,provider:wn,modelRef:Je,subagentDelegationMode:X,...Rn?{openPondCommandAccessMode:Rn}:{},appId:K,appName:Be,workspaceKind:_e?"sandbox":Mt?"local_project":fn?"sandbox_app":void 0,workspaceId:Mt?.id??(fn?K:void 0),workspaceName:_e?.name??Mt?.name??Be,localProjectId:Mt?.id??null,cloudProjectId:_e?.id??Ve?.id??null,cloudTeamId:_e?.teamId??Ve?.teamId??null,...!_e&&!Mt&&!fn&&J==="local"?{metadata:{...NJ(),...ae.sessionMetadata??{}}}:{cwd:Mt?Mt.workspacePath:null,...ae.sessionMetadata?{metadata:ae.sessionMetadata}:{}},autoTitlePrompt:pr(ce)}),xe(Nn=>[st,...Nn]),ae.onSessionCreated?.(st),Qt&&(le(st.id),_e&&we(It("cloud",_e.id)),st.workspaceKind==="local_project"&&st.workspaceId&&m(It("local",st.workspaceId)),_e&&m(It("cloud",_e.id)))}if(qk(st)&&Hi(st.workspaceKind)&&st.provider!=="openpond"&&!Li(st))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(qk(st)&&Hi(st.workspaceKind)&&u)try{st=await u(st)}catch(K){const Be=K instanceof Error?K.message:String(K);throw await Q.recordPreflightTurnFailure(t,st.id,{prompt:ce,error:Be,target:Li(st)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),K}kn=Zx({afterMessageId:Ja.at(-1)?.id??null,attachments:G,content:ce,sessionId:st.id}),zn(),Vt=st.id,at.current.add(Vt),ue?.(kn),xe(K=>K.map(Be=>Be.id===Vt?{...Be,status:"active"}:Be));const ha=he,Ra=Zte({provider:ha,model:Ae,providerSettings:Ne}),Bn=y8(ha,Ra.model??Ae,Ne),zi=ha==="codex"?mx(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await Q.sendTurn(t,st.id,{prompt:ce,metadata:ae.turnMetadata,attachments:G.length>0?G:void 0,mentionedAppIds:fi?[fi.id]:void 0,mentionedConnectedApps:hi.length>0?hi:void 0,openPondActionCatalog:M.length>0?M:void 0,usageAttribution:Ca,...Ra,...zi,codexPermissionMode:ha==="codex"?n:"default",codexReasoningEffort:Bn?b8(ha,Ra.model??Ae,a,Ne):void 0}),it(t);const Za=st.workspaceId??st.appId;return Za&&st.workspaceKind!=="sandbox"&&st.workspaceKind!=="sandbox_template"&&j(Za,!1).then(K=>{K?.initialized&&R(Za)}),!0}catch(st){return Ie(st instanceof Error?st.message:String(st)),!1}finally{Vt&&at.current.delete(Vt),Vt&&Kt(Vt)&&be?.(Vt,!1),Vt&&(Kt(Vt)?oe(st=>st.map(Mn=>Mn.id===Vt&&Mn.status==="active"?{...Mn,status:"idle"}:Mn)):xe(st=>st.map(Mn=>Mn.id===Vt&&Mn.status==="active"?{...Mn,status:"idle"}:Mn)))}}async function ze(G,_){const W=at.current.values().next().value??null,ae=G??L?.id??W;if(!t||!ae)return!1;if(Ie(null),Kt(ae))try{const Z=await Q.interruptCodexHistoryTurn(t,ae);if(!Z.interrupted){if(Z.reason==="no_active_openpond_turn"){const fe=await Q.codexHistoryThread(t,ae,{tail:!0}),he={...fe.session,status:"idle"};return L?.id===ae&&Se(Ae=>eo(Ae,fe.events)),oe(Ae=>ic(Ae,he)),Ie("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 Ie("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const ce=await Q.codexHistoryThread(t,ae,{tail:!0});return L?.id===ae&&Se(fe=>eo(fe,ce.events)),oe(fe=>ic(fe,ce.session)),!0}catch(Z){const ce=Z instanceof Error?Z.message:String(Z);return Ie(ce==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":ce),!1}try{await Q.interruptTurn(t,ae,_);const Z=await Q.bootstrap(t);return e(Z),!0}catch(Z){return Ie(Z instanceof Error?Z.message:String(Z)),!1}}async function tt(G,_){if(!t){Ie("OpenPond App server is not connected.");return}Ie(null),await Q.applyCreateImproveAction(t,G.id,{..._,runId:G.id,expectedRevision:G.revision,actionId:`web:${_.type}:${crypto.randomUUID()}`});const W=await Q.bootstrap(t);e(W)}async function nt(G){await tt(G.run,{type:"approve_plan"})}async function pt(G){await tt(G.run,{type:"cancel",reason:null})}async function bt(G,_){await tt(G.run,{type:"revise_plan",revision:_})}async function Oe(G,_,W){await tt(G.run,{type:"answer_question",questionId:_,value:W})}async function Ye(G){await tt(G.run,{type:"pause"})}async function h(G){await tt(G.run,{type:"resume"})}async function B(G,_){await tt(G.run,{type:"open_pull_request",candidateId:_})}async function Y(G,_){await tt(G.run,{type:"apply_candidate",candidateId:_})}async function ge(G,_){await tt(G.run,{type:"reject_candidate",candidateId:_,reason:null})}async function se(G,_){await tt(G.run,{type:"reconcile_pull_request",candidateId:_})}return{answerCreateImproveQuestion:Oe,approveCreateImproveRun:nt,applyCreateImproveCandidate:Y,cancelCreateImproveRun:pt,changeDraftProvider:q,openCreateImprovePullRequest:B,pauseCreateImproveRun:Ye,reconcileCreateImprovePullRequest:se,rejectCreateImproveCandidate:ge,resumeCreateImproveRun:h,reviseCreateImproveRun:bt,sendPrompt:$e,stopTurn:ze}}function qk(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function tne({branch:e,connection:t,session:n}){if(!Hi(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 nne(e){return Li(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function ane(e,t){if(e==="already_running")return null;const n=Li(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 ine(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function one({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:o,selectedProject:r,setWorkspaceBusy:s,showToast:c,visibleWorkspaceState:m}){return y.useCallback(async u=>{if(!n)throw new Error("OpenPond App server is not connected.");const f=r??(u.localProjectId?a.get(u.localProjectId)??null:null);if(u.cloudProjectId&&u.cloudTeamId&&!ine(u,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");u.workspaceId||c(nne(u),"info"),s(!0);try{const g=await tne({branch:r?.linkedSandboxProject?.defaultBranch??o?.defaultBranch??m?.currentBranch??null,connection:n,localProject:f,session:u,source:Li(u)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});g.bootstrap&&e(g.bootstrap);const S=ane(g.status,u);return S&&c(S,"success"),g.session}finally{s(!1)}},[e,t,n,a,o,r,s,c,m?.currentBranch])}function rne(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function sne(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function Uk(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function lne(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 cne(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function dne(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:r,selectedAppId:s,selectedCloudProject:c,selectedProjectId:m,selectedSession:u,selectedSessionId:f,setWorkspaceDiffPanelViewState:g,view:S,viewWorkspaceAppId:k,viewWorkspaceId:C,viewWorkspaceKind:P,workspaceDiffPanelViewState:j}=e,R=y.useRef(new Map),$=y.useRef(new Map),O=y.useRef(null),M=y.useRef(null),w=f??`draft:${m??s??c?.id??"general"}`,A=y.useMemo(()=>C?`${P??"workspace"}:${C}`:k?`app:${k}`:u?.cwd&&!Hi(u.workspaceKind)?`cwd:${u.cwd}`:"none",[u?.cwd,u?.workspaceKind,S,k,C,P]),E=cne({conversationId:w,workspaceSourceKey:A}),D=y.useMemo(()=>sne({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:o,rightPanelMode:r}),[n,a,o,r]);y.useEffect(()=>{const L=O.current;L&&R.current.set(L,Uk(D))},[w,D]),y.useEffect(()=>{if(O.current===w)return;O.current=w;const J=R.current.get(w)??rne();lne(D,J)||t({type:"patch",patch:Uk(J)})},[w,D]),y.useEffect(()=>{const L=M.current;L&&$.current.set(L,Mh(j))},[E,j]),y.useEffect(()=>{if(M.current===E)return;M.current=E;const J=$.current.get(E)??dA();g(X=>Hx(X,J)?X:Mh(J))},[E]);const U=y.useCallback(L=>{g(J=>Hx(J,L)?J:Mh(L))},[]);return{browserConversationId:w,handleWorkspaceDiffPanelViewStateChange:U}}function une({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:o,appDispatch:r,applyBootstrapPayload:s,busy:c,cloudSetupDialog:m,cloudProjects:u,connection:f,defaultTeamId:g,expandProject:S,localProjectById:k,selectedCloudProject:C,selectedProject:P,selectedSession:j,selectedSessionProjectId:R,setCloudSetupDialog:$,setDiffPanelOpen:O,setError:M,setSessions:w,setWorkspaceBusy:A,showToast:E,visibleWorkspaceState:D,workspaceBusy:U}){const L=e?.baseUrl??e?.activeProfile?.baseUrl??null,J=y.useCallback(async(ne,je)=>{if(f)try{const Se=await Q.previewLocalProjectCloudSource(f,ne.id,{branch:je});$(oe=>!oe||oe.status!=="confirm"||oe.localProjectId!==ne.id||oe.branch!==je?oe:{...oe,branch:Se.preview.branch,cloudProjectId:Se.preview.targetProjectId,preview:Se.preview,previewLoading:!1,previewError:null})}catch(Se){const oe=Se instanceof Error?Se.message:String(Se);$(be=>!be||be.status!=="confirm"||be.localProjectId!==ne.id||be.branch!==je?be:{...be,preview:null,previewLoading:!1,previewError:oe})}},[f,$]),X=y.useCallback(async()=>{const ne=m;if(!ne||ne.status==="uploading")return;if(ne.projectKind==="cloud"){$(be=>be&&{...be,status:"ready",error:null});return}if(!f){$(be=>be&&{...be,status:"error",error:"OpenPond App server is not connected."});return}const je=ne.localProjectId??"",Se=k.get(je);if(!Se){$(be=>be&&{...be,status:"error",error:"Project is no longer available."});return}A(!0);const oe=Ba(Se,u);$(be=>be&&{...be,status:"uploading",error:null,previewLoading:!1});try{const be=await Q.organizations(f),re=vp(be.organizations.map(up).filter(Ue=>!!Ue).filter(Ue=>Ue.status==="active"),g);if(!re)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!gp(re))throw new Error(`You need owner or admin access to create projects in ${re.displayName}.`);const ue=ne.branch||Se.linkedSandboxProject?.defaultBranch||"main",ke=It("local",Se.id),Le=await Q.createSession(f,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:Se.id,workspaceName:Se.name,localProjectId:Se.id,cloudProjectId:oe?.id??null,cloudTeamId:oe?.teamId??null,cwd:Se.workspacePath,title:`Sync ${Se.name} to Cloud`});w(Ue=>[Le,...Ue]),r({type:"selectSession",sessionId:Le.id,projectId:ke}),S(ke);const we=await Q.uploadLocalProjectCloudSource(f,Se.id,{teamId:re.teamId,projectName:Se.name,branch:ue,chatSessionId:Le.id,displayPrompt:`/sync-cloud ${Se.name}`});s(we.bootstrap),S(ke),S(It("cloud",we.project.id));const le=av({accountBaseUrl:L,teamId:we.project.teamId,projectId:we.project.id,projectName:we.project.name,baseBranch:we.upload.branch,localProjectId:Se.id,source:"openpond-app"}),xe=Nk({accountBaseUrl:L,organizationSlug:we.project.organizationSlug,projectSlug:we.project.slug});$({status:"ready",localProjectId:Se.id,cloudProjectId:we.project.id,teamId:we.project.teamId,projectName:we.project.name,projectKind:"local",projectUrl:xe,setupUrl:le,branch:we.upload.branch,preview:ne.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 re=be instanceof Error?be.message:String(be),ue=f?await Q.bootstrap(f).catch(()=>null):null;ue&&s(ue),M(re),$(ke=>ke&&{...ke,status:"error",error:re})}finally{A(!1)}},[L,r,s,m,u,f,g,S,k,$,M,w,A,E]),de=y.useCallback((ne,je)=>{if(!f){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 Se=je||ne.linkedSandboxProject?.defaultBranch||"main";$({status:"confirm",localProjectId:ne.id,projectName:ne.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:Se,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),J(ne,Se)},[t,n,f,J,$,E]),Me=y.useCallback(async ne=>{if(ne===o||U||c)return;if(M(null),ne==="upload_cloud"){if(!P){E("Select a local Project before uploading source.","error");return}de(P,D?.currentBranch??null);return}if(ne==="local"){const oe=j?.localProjectId??P?.id??R??null,be=oe?k.get(oe)??null:null;if(!be){E("No linked local workspace for this Cloud chat.","error");return}if(Hi(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const re=It("local",be.id);r({type:"selectProject",projectId:re}),S(re),O(!1),E(`Switched to Local: ${be.name}`,"info");return}if(!f){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(C){$({status:"ready",cloudProjectId:C.id,teamId:C.teamId,projectName:C.name,projectKind:"cloud",projectUrl:Nk({accountBaseUrl:L,organizationSlug:C.organizationSlug,projectSlug:C.slug}),setupUrl:av({accountBaseUrl:L,teamId:C.teamId,projectId:C.id,projectName:C.name,baseBranch:C.defaultBranch,source:"openpond-app"}),branch:C.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const je=P;if(!je){E("Select a Project before Cloud coding.","error");return}const Se=D?.currentBranch||je.linkedSandboxProject?.defaultBranch||"main";de(je,Se)},[L,t,n,a,o,r,c,f,u,S,k,de,C,P,j,R,$,O,M,E,D?.currentBranch,U]),Ie=y.useCallback(ne=>{py(ne)&&de(ne.project)},[de]);return{changeWorkspaceTarget:Me,moveProjectToCloud:Ie,openCloudSetupForLocalProject:de,startCloudSetupUpload:X}}function mne({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:o,prepareTrainingTurn:r,sendPrompt:s,setMentionedAppId:c,showToast:m}){return y.useCallback(async(u=[],f=null,g,S={})=>{const k=g??n.getSnapshot(),C=r(k);if(C.active&&k.trim()&&!C.metadata)return m(C.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(u,f,g,{clearPrompt:S.preservePrompt?()=>{}:void 0,displayPrompt:S.displayPrompt,onSessionCreated:j=>{a(j),C.metadata&&t(j.id)},turnMetadata:C.metadata||S.turnMetadata?{...C.metadata??{},...S.turnMetadata??{}}:void 0,sessionMetadata:C.metadata?{trainingTasksetId:C.metadata.trainingTasksetId,trainingTasksetName:C.metadata.trainingTasksetName}:void 0});return P&&await o?.(),P&&C.metadata&&e(),P},[e,t,n,a,o,r,s,c,m])}function pne({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:o,setSessions:r,setView:s}){return y.useCallback(async c=>{if(!t)return;const m=n.find(g=>!g.archived&&g.workspaceKind==="sandbox"&&g.workspaceId===c.sandboxId);if(m){e({type:"selectSession",sessionId:m.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat");return}const u=c.name??`Sandbox ${c.sandboxId.slice(0,8)}`,f=await Q.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:c.sandboxId,workspaceName:u,cwd:null,title:u});r(g=>[f,...g]),e({type:"selectSession",sessionId:f.id,appId:null,projectId:null}),o("changes"),a(!0),s("chat")},[e,t,n,a,o,r,s])}function fne({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:o,applyBootstrapPayload:r,expandProject:s,setExpandedProjectIds:c,setSelectedAppId:m,setSelectedProjectId:u,setSelectedSessionId:f,setError:g,setView:S,showToast:k}){function C(O){const M=It("local",O.id);m(null),u(M),f(null),S("chat"),s(M)}async function P(O){if(!e)return!1;g(null);try{const M=await Q.createLocalProject(e,O);return r(M.bootstrap),C(M.project),k(M.created===!1?`Opened ${M.project.name}`:`Created ${M.project.name}`,"success"),!0}catch(M){const w=M instanceof Error?M.message:String(M);return g(w),k(w,"error"),!1}}async function j(O){if(!e)return!1;const M=O.trim();if(!M)return!1;g(null);try{const w=await Q.createLocalProject(e,{createNew:!0,name:M});return r(w.bootstrap),C(w.project),k(`Created ${w.project.name}`,"success"),!0}catch(w){return g(w instanceof Error?w.message:String(w)),k("Project could not be created","error"),!1}}async function R(O){if(!e)return!1;const M=O.trim();if(!M)return!1;g(null);try{const w=await Q.organizations(e),A=vp(w.organizations.map(up).filter(J=>!!J).filter(J=>J.status==="active"),t);if(!A)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!gp(A))throw new Error(`You need owner or admin access to create projects in ${A.displayName}.`);const E=`${uA(M)}-${Date.now().toString(36)}`;let D=(await Q.upsertSandboxProject(e,{teamId:A.teamId,name:M,sourceType:"internal_repo",normalizedSourceIdentity:E,internalRepoPath:E,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:E},metadata:{source:"openpond-app-new-cloud-project"}})).project;D=(await Q.uploadSandboxProjectSource(e,D.id,{teamId:A.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:WJ(`# ${M}
|
|
220
|
+
|
|
221
|
+
Created in OpenPond Cloud.
|
|
222
|
+
`)}]})).project;const U=await Q.bootstrap(e);r(U);const L=It("cloud",D.id);return m(null),u(L),f(null),S("chat"),s(L),k(`Created Cloud Project: ${D.name}`,"success"),!0}catch(w){const A=w instanceof Error?w.message:String(w);return g(A),k(A,"error"),!1}}async function $(O){if(!e)return;if(m8(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)),c(U=>{const L=new Set(U);return L.delete(O.id),L}),a===O.id&&(u(null),f(null)),k(`Archived ${O.project.name}`,"success")}catch(U){g(U instanceof Error?U.message:String(U)),k("Cloud Project could not be archived","error")}return}if(!py(O))return;const M=O.project,w=`Remove ${M.name} from Projects? The folder will not be deleted.`;if(o?await o({title:"Remove Project",body:`${M.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(w)){g(null);try{const E=await Q.deleteLocalProject(e,M.id);r(E),c(D=>{const U=new Set(D);return U.delete(O.id),U}),a===O.id&&(u(null),f(D=>{const U=n.find(L=>L.id===D);return U?.workspaceKind==="local_project"&&U.workspaceId===M.id?null:D})),k(`Removed ${M.name}`,"success")}catch(E){g(E instanceof Error?E.message:String(E)),k("Project could not be removed","error")}}}return{createCloudProjectFromScratch:R,createProjectFromScratch:j,createProjectCollection:P,removeProject:$}}function hne({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:o,createProjectCollection:r,expandProject:s,localProjectById:c,onCreateCloudEnvironment:m,onNewCloudProject:u,onNewLocalProject:f,onUseExistingFolderPath:g,newProjectBusy:S,newProjectMode:k,newProjectName:C,projectTargetValue:P,setDiffPanelOpen:j,setDraftModel:R,setDraftProvider:$,setError:O,setNewProjectBusy:M,setNewProjectDialogOpen:w,setNewProjectName:A,setNewProjectPath:E,showToast:D,workspaceBusy:U}){const L=y.useCallback(X=>{if(X===P||t||U)return;if(O(null),X==="action:new-local-project"){f();return}if(X==="action:add-local-project"){g();return}if(X==="action:add-local-project-path"){g();return}if(X==="action:new-cloud-project"){u();return}if(X==="action:create-cloud-environment"){m();return}if(X==="none"){e({type:"selectProject",projectId:null}),j(!1),D("Started a chat without project files.","info");return}const de=X.indexOf(":"),Me=de>=0?X.slice(0,de):"",Ie=de>=0?X.slice(de+1):"";if(Me==="local"){const ne=c.get(Ie);if(!ne){D("Project is no longer available.","error");return}const je=It("local",ne.id);e({type:"selectProject",projectId:je}),s(je),j(!1);return}if(Me==="cloud"){const ne=n.get(Ie);if(!ne){D("Cloud Project is no longer available.","error");return}const je=It("cloud",ne.id);e({type:"selectProject",projectId:je}),s(je),$("openpond"),R(Se=>er("openpond",Se)),j(!1)}},[e,t,n,s,c,m,u,f,g,P,j,R,$,O,D,U]),J=y.useCallback(async X=>{const de=C.trim();if(!S){if(k==="existing-local"?!X?.name.trim()||!X.sourceFolders.length:!de)return!1;M(!0);try{const Me=k==="cloud"?await a(de):k==="existing-local"?await r(X):await o(de);return Me&&(w(!1),A(""),E("")),!!Me}finally{M(!1)}}},[a,o,r,S,k,C,M,w,A,E]);return{changeProjectTarget:L,submitNewProjectDialog:J}}function gne(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 qoe(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function vne(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 bne(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 uT(e){return!!(e.parentSessionId&&e.subagentRunId)}function yne(e){const t=e.sessions.filter(uT);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function Sne(e,t){const n=new Set(e.map(o=>o.sessionId).filter(Boolean)),a=t.filter(uT).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 zk="openpond/openpond",xne="github.issue.write";function kne(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(xne))}function Uoe(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
|
|
223
|
+
`)}function wne(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${zk}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${zk}, 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:
|
|
224
|
+
${t}`].join(`
|
|
225
|
+
`)}function Ine(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(`
|
|
226
|
+
|
|
227
|
+
`),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:wne(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const Bk=[];function _ne(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:o,rightChatHistoryEvents:r,rightChatPanels:s,runningSessionIds:c,selectedSessionId:m,sidebarSessions:u}=e;return y.useMemo(()=>{const f=new Map(u.map(S=>[S.id,S])),g=Cne(t);return s.map(S=>{const k=S.sessionId?f.get(S.sessionId)??null:null,C=Kt(S.sessionId),P=C?(S.sessionId?r[S.sessionId]:void 0)??(S.sessionId===m?n:Bk):Bk,j=Fg(P,[]),R=S.sessionId?g.get(S.sessionId)??null:null,$=!!(k&&c.has(k.id)),O=C?tJ({events:P}):null,M=k?.cwd??null,w=k?.appId??k?.localProjectId??(k?.workspaceKind==="local_project"?k.workspaceId??null:null)??(k?.cwd&&!Hi(k.workspaceKind)?I1(k.cwd):null),A=S.sessionId?o[S.sessionId]??null:null;return{...S,session:k,title:nJ(O,k?.title??"New task"),messages:C?wA(fp(P),A):[],createImproveRun:O,contextWindowStatus:UP({provider:S.provider,snapshot:aA(j,S.sessionId),preferences:a}),goalRuntime:iA(j,S.sessionId),pendingApproval:R,running:$,workspaceRootPath:M,activeWorkspaceAppId:w,pendingUserMessage:A,runtimeSource:C?"history":"live"}})},[t,n,a,o,r,s,c,m,u])}function Cne(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 Rne(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:o,sessions:r,setError:s}=e,c=y.useMemo(()=>{const f=new Set,g=[];for(const S of o)!Kt(S.sessionId)||!S.sessionId||f.has(S.sessionId)||(f.add(S.sessionId),g.push(S.sessionId));return g.join(`
|
|
228
|
+
`)},[o]),m=y.useMemo(()=>{if(!c)return"";const f=new Set(c.split(`
|
|
229
|
+
`).filter(Boolean));return r.filter(g=>f.has(g.id)&&g.status==="active").map(g=>g.id).join(`
|
|
230
|
+
`)},[c,r]),u=y.useMemo(()=>c?c.split(`
|
|
231
|
+
`).filter(f=>a.has(f)).join(`
|
|
232
|
+
`):"",[a,c]);y.useEffect(()=>{if(!n||!c)return;const f=c.split(`
|
|
233
|
+
`).filter(Boolean),g=new Set(m.split(`
|
|
234
|
+
`).filter(Boolean)),S=new Set(u.split(`
|
|
235
|
+
`).filter(Boolean)),k=f.map(C=>Cy({connection:n,locallyActive:S.has(C),onError:P=>s(P instanceof Error?P.message:String(P)),onPayload:P=>t(_y(P,S.has(C))),reportedActive:g.has(C),sessionId:C,surface:"thread"}));return()=>k.forEach(C=>C())},[m,t,n,u,c,s])}const Fk=[];function Pne(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:o,codexHistoryEvents:r,connectedAppMentions:s,connection:c,contextCompaction:m,openLabTraining:u,locallyActiveCodexHistorySessionIds:f,openPondCommandAccessMode:g,pendingChatUserMessages:S,providerSettings:k,rightChatHistoryEvents:C,rightChatPanels:P,rightPanelMode:j,runtimeIndexes:R,runtimeEventStore:$,runningSessionIds:O,selectedSession:M,selectedSessionId:w,sendPrompt:A,setDiffPanelOpen:E,setError:D,setRightChatHistoryEvents:U,setRightChatPanels:L,setRightPanelMode:J,setRightPanelTabRequest:X,setView:de,showChangesPanel:Me,showToast:Ie,sidebarSessions:ne,startupReady:je}=e,Se=y.useRef(null),oe=y.useRef(new Map),be=y.useRef(new Set);y.useEffect(()=>{if(!c)return;const Ne=P.flatMap(We=>We.sessionId&&!Kt(We.sessionId)?[We.sessionId]:[]);for(const We of Ne)Object.hasOwn(C,We)||be.current.has(We)||(be.current.add(We),Q.runtimeEventsPage(c,{sessionId:We,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(qe=>{const q=qe.events.map(N=>N.event);U(N=>({...N,[We]:to(N[We]??Fk,q)}))}).catch(qe=>{D(qe instanceof Error?qe.message:String(qe))}).finally(()=>{be.current.delete(We)}))},[c,C,P,D,U]);const re=y.useCallback(Ne=>{X(We=>({id:(We?.id??0)+1,tab:Ne})),Me()},[Me]),ue=y.useCallback((Ne=null,We={})=>{const qe=Ne?.id?P.find(N=>N.sessionId===Ne.id)??null:null;if(qe)return L(N=>bne(N,{sessionId:Ne.id,prompt:We.prompt})),E(!0),J("chat"),We.preserveView||de("chat"),qe.id;const q=gne({sessionId:Ne?.id??null,provider:Ne?.provider??n,model:Ne?.modelRef?.modelId??t,prompt:We.prompt});return L(N=>[...N,q]),E(!0),J("chat"),We.preserveView||de("chat"),q.id},[t,n,P,E,L,J,de]);y.useEffect(()=>{if(!je)return;const Ne=Se.current;if(!Ne){Se.current=new Set(ne.filter(N=>!!(N.parentSessionId&&N.subagentRunId)).map(N=>N.id));return}const We=yne({sessions:ne,knownSessionIds:Ne});Se.current=We.knownSessionIds;for(const N of We.newSessions)oe.current.set(N.id,N);const qe=M?.parentSessionId??M?.id??null;if(!qe)return;const q=[...oe.current.values()].filter(N=>N.parentSessionId===qe);if(q.length!==0){for(const N of q)oe.current.delete(N.id);L(N=>Sne(N,q)),E(!0),J("chat")}},[M?.id,M?.parentSessionId,E,L,J,ne,je]);const ke=y.useCallback(()=>{if(P.length===0){ue(null);return}E(!0),J("chat"),de("chat")},[ue,P.length,E,J,de]),Le=y.useCallback(Ne=>{const We=P.length<=1&&P.some(q=>q.id===Ne),qe=()=>{L(q=>q.filter(N=>N.id!==Ne))};if(We&&j==="chat"){if(re("files"),typeof window>"u"){qe();return}window.requestAnimationFrame(qe);return}qe()},[P,j,L,re]),we=y.useCallback((Ne,We)=>{L(qe=>qe.map(q=>q.id===Ne?{...q,prompt:We}:q))},[L]),le=y.useCallback(Ne=>{L(We=>vne(We,Ne))},[L]),xe=y.useCallback((Ne,We)=>{L(qe=>qe.map(q=>q.id===Ne?{...q,...We}:q))},[L]),Ue=y.useCallback((Ne,We)=>{L(qe=>qe.map(q=>q.id===Ne?{...q,model:We}:q))},[L]),Ze=y.useCallback((Ne,We)=>{L(qe=>qe.map(q=>q.id===Ne?{...q,provider:We,model:er(We,q.model,k)}:q))},[k,L]);Rne({applyPayload:o,connection:c,locallyActiveSessionIds:f,panels:P,sessions:ne,setError:D});const it=_ne({approvals:a,codexHistoryEvents:r,contextCompaction:m,pendingChatUserMessages:S,rightChatHistoryEvents:C,rightChatPanels:P,runningSessionIds:O,selectedSessionId:w,sidebarSessions:ne}),at=y.useCallback(async(Ne,We=[],qe=null,q=null,N={})=>{const F=P.find(bt=>bt.id===Ne);if(!F)return!1;const ee=N.promptOverride??F.prompt,me=q?Ine(q,ee):null;if(me?.kind==="open_training")return We.length>0?(Ie("/train uses this chat; add other chats from Models.","error"),!1):(u({objective:me.objective,sessionId:F.sessionId}),N.preservePrompt||we(Ne,""),!0);if(q&&me?.kind==="send_prompt"&&me.requiresInstructions&&!ee.trim())return Ie(`Add instructions after ${q.command}.`,"info"),!1;if(q&&We.length>0)return Ie(`${q.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(q?.id==="submit-issue"&&!kne(s))return Ie("Connect the GitHub app before using /submit-issue.","error"),!1;const $e=F.sessionId?ne.find(bt=>bt.id===F.sessionId)??null:null,ze=F.provider==="codex"?g:$e?.openPondCommandAccessMode??g,tt=me?.kind==="send_prompt"?me.prompt:ee,nt=Kt(F.sessionId)?(F.sessionId?C[F.sessionId]:void 0)??(F.sessionId===w?r:Fk):$.getSessionEvents(F.sessionId),pt=Kt(F.sessionId)&&F.sessionId?bt=>{const Oe=F.sessionId;U(Ye=>({...Ye,[Oe]:to(Ye[Oe]??nt,[bt])}))}:void 0;return A(We,qe,tt,{session:$e,selectSession:!1,provider:F.provider,model:F.model,openPondCommandAccessMode:ze,chatMessages:fp(nt),displayPrompt:N.displayPrompt,turnMetadata:N.turnMetadata,usageAttribution:q?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:q.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:pt,clearPrompt:N.preservePrompt?()=>{}:()=>we(Ne,""),onSessionCreated:bt=>{L(Oe=>Oe.map(Ye=>Ye.id===Ne?{...Ye,sessionId:bt.id,provider:bt.provider,model:bt.modelRef?.modelId??Ye.model}:Ye))}})},[r,s,C,P,R,$,w,u,g,A,L,de,ne,Ie,we]);return{activateRightChatPanel:le,closeRightChatPanel:Le,openRightChatPanel:ue,rightChatPanelViews:it,showRightChatPanel:ke,showRightPanelDiffTab:re,submitRightChatPrompt:at,updateRightChatModel:Ue,updateRightChatPrompt:we,updateRightChatProvider:Ze,updateRightChatScrollState:xe}}function Ane(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:o,setCodexHistorySessions:r,setError:s,setSelectedSessionId:c,setSessions:m}=e;async function u(R,$){if(!n)return;const O=t[R]??{},M={...O,...$,archived:$.pinned?!1:$.archived??O.archived};o(w=>({...w,[R]:M}));try{const w=await Q.patchSidebarAppPreference(n,R,$);o(A=>({...A,[R]:w}))}catch(w){s(w instanceof Error?w.message:String(w)),o(A=>({...A,[R]:O}))}}function f(R){u(R.id,{pinned:!R.pinned,archived:!1})}async function g(R,$){if(!n)return;const O=Kt(R.id)?r:m,M={...R,...$};O(w=>w.some(A=>A.id===R.id)?w.map(A=>A.id===R.id?M:A):[M,...w]);try{const w=await Q.patchSession(n,R.id,$);O(A=>A.some(E=>E.id===w.id)?A.map(E=>E.id===w.id?w:E):[w,...A])}catch(w){s(w instanceof Error?w.message:String(w)),O(A=>A.map(E=>E.id===R.id?R:E))}}function S(R){g(R,{pinned:!1,savedForLater:!R.savedForLater,archived:!1})}function k(R){g(R,{pinned:!R.pinned,savedForLater:!1,archived:!1})}function C(R){g(R,{pinned:!1,savedForLater:!1,archived:!0}),a===R.id&&c(null)}function P(R){g(R,{archived:!1})}function j(R,$){const O=$.trim();!O||O===R.title||g(R,{title:O})}return{archiveSession:C,renameSession:j,restoreSession:P,toggleProjectPinned:f,toggleSessionPinned:k,toggleSessionSavedForLater:S}}function Tne(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function Ene({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:o,commitIncludeUnstaged:r,commitMessage:s,commitNextStep:c,draftModel:m,draftProvider:u,cloudProjects:f,selectedApp:g,selectedProject:S,selectedProjectLinkedOpenPondApp:k,selectedSession:C,sessions:P,title:j,visibleWorkspaceDiff:R,visibleWorkspaceState:$,workspaceBusy:O,workspaceName:M,appDispatch:w,applyBootstrapPayload:A,expandProject:E,refreshWorkspace:D,refreshWorkspaceDiff:U,rememberWorkspaceState:L,setBranchDialogOpen:J,setCommitDialogOpen:X,setError:de,setSessions:Me,setSettingsSection:Ie,setSyncingWorkspaceAppId:ne,setView:je,setWorkspaceBusy:Se,showToast:oe}){function be(){return`${yP(n.defaultBranchPrefix)}${Tne(M??j??"new-branch")}`}function re(){return M?`Update ${M}`:(R?.filesChanged??$?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function ue(qe="commit"){w({type:"openCommitDialog",nextStep:qe})}function ke(){w({type:"openBranchDialog",branchName:be()})}function Le(){O||J(!1),Ie("configuration"),je("settings"),ln({kind:"settings",section:"configuration"})}async function we(qe){if(!(!e||!t)){Se(!0),de(null);try{const q=await Q.checkoutWorkspaceBranch(e,t,{branch:qe});L(q),q.initialized&&U(t)}catch(q){de(q instanceof Error?q.message:String(q))}finally{Se(!1)}}}async function le(){if(!e||!t)return;const qe=o.trim();if(qe){Se(!0),de(null);try{const q=await Q.createWorkspaceBranch(e,t,{branch:qe});L(q),q.initialized&&U(t),J(!1),oe(`Checked out ${qe}`,"success")}catch(q){de(q instanceof Error?q.message:String(q))}finally{Se(!1)}}}async function xe(qe){ne(qe);const q=a?.apps.find(N=>N.id===qe)?.name??a?.localProjects.find(N=>N.id===qe)?.name??"Workspace";try{const N=await D(qe,!0);N?.initialized&&qe===t&&U(qe),N?.initialized&&!N.error?oe(`${q} synced locally`,"success"):N?.error&&oe("Workspace sync failed","error")}finally{ne(N=>N===qe?null:N)}}async function Ue(){t&&await xe(t)}async function Ze(qe,q,N={}){if(!e)return null;const F=C&&!Kt(C.id)?C:null;if($ne(q,F,N)||F&&jne(F,S,g))return F;const ee=F?await it(F):null;if(ee)return ee;const me=Mne(P,S,g);if(me){const nt=me.workspaceKind==="local_project"&&me.workspaceId?It("local",me.workspaceId):null;return w({type:"selectSession",sessionId:me.id,appId:me.appId,projectId:nt}),me.workspaceKind==="local_project"&&me.workspaceId&&E(It("local",me.workspaceId)),me}const $e=Ba(S,f),ze=await Q.createSession(e,{provider:u,modelRef:ni(u,m,a?.providers??null),appId:k?.appId??g?.id??null,appName:k?.appName??g?.name??null,workspaceKind:S?"local_project":g?"sandbox_app":void 0,workspaceId:S?.id??g?.id??null,workspaceName:S?.name??g?.name??null,localProjectId:S?.id??null,cloudProjectId:$e?.id??null,cloudTeamId:$e?.teamId??null,cwd:S?S.workspacePath:null,title:qe});Me(nt=>[ze,...nt]);const tt=ze.workspaceKind==="local_project"&&ze.workspaceId?It("local",ze.workspaceId):null;return w({type:"selectSession",sessionId:ze.id,appId:ze.appId,projectId:tt}),ze.workspaceKind==="local_project"&&ze.workspaceId&&E(It("local",ze.workspaceId)),ze}async function it(qe){if(!e||!S||!k?.appId||Kt(qe.id)||qe.workspaceKind==="local_project"||qe.appId!==k.appId)return null;const q=Ba(S,f),N=await Q.patchSession(e,qe.id,{appId:k.appId,appName:k.appName,workspaceKind:"local_project",workspaceId:S.id,workspaceName:S.name,localProjectId:S.id,cloudProjectId:q?.id??null,cloudTeamId:q?.teamId??null,cwd:S.workspacePath});return Me(F=>F.map(ee=>ee.id===N.id?N:ee)),w({type:"selectSession",sessionId:N.id,appId:N.appId,projectId:It("local",S.id)}),E(It("local",S.id)),N}async function at(qe,q={}){if(!e)return null;const N=await Ze(M?`${M} workspace`:"Workspace action",qe,q);if(!N)return null;const F=await Q.workspaceTool(e,N.id,{action:qe,args:q,source:"ui_button"});oe(F.output,F.ok?"success":"error"),A(await Q.bootstrap(e));const ee=F.appId??One(N);return ee&&(await D(ee,!1))?.initialized&&await U(ee),F}async function Ne(qe,q={}){if(qe==="git_commit"&&typeof q.message!="string")return ue("commit"),null;Se(!0),de(null);try{return await at(qe,q)}catch(N){return de(N instanceof Error?N.message:String(N)),null}finally{Se(!1)}}async function We(){const qe=s.trim()||re(),q=c==="commit_publish",N=q&&!!$?.remoteUrl;if(!(N&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){Se(!0),de(null);try{if(!(await at("git_commit",{message:qe,includeUnstaged:r}))?.ok||c==="commit_push"&&!(await at("git_push",{runChecks:!1}))?.ok||q&&!(await at("publish_openpond_repo",{replaceOrigin:N}))?.ok)return;X(!1)}catch(F){de(F instanceof Error?F.message:String(F))}finally{Se(!1)}}}return{changeWorkspaceBranch:we,openCommitDialog:ue,openCreateWorkspaceBranchDialog:ke,openDefaultsSettingsFromBranchDialog:Le,runWorkspaceTool:Ne,submitCommitDialog:We,submitCreateWorkspaceBranch:le,syncWorkspaceLocally:Ue,syncWorkspaceLocallyForApp:xe}}function jne(e,t,n){return!t&&!n?!0:mT(e,t,n)}function Mne(e,t,n){if(!t&&!n)return null;let a=null,o=Number.NEGATIVE_INFINITY;for(const r of e){if(r.archived||!mT(r,t,n))continue;const s=Date.parse(r.updatedAt),c=Number.isFinite(s)?s:0;(!a||c>o)&&(a=r,o=c)}return a}function mT(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function One(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function $ne(e,t,n={}){return(Nne(e)||Hne(e,n))&&Dne(t)}function Nne(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function Dne(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function Hne(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 Lne(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const qne=[];function Une(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:o,cloudSetupDialog:r,setCloudSetupDialog:s,setRightPanelTabRequest:c,workspaceDiffPanelViewState:m,setWorkspaceDiffPanelViewState:u,rightChatHistoryEvents:f,setRightChatHistoryEvents:g,locallyActiveCodexHistorySessionIds:S,setCodexHistoryTurnLocallyActive:k,draftSubagentDelegationMode:C,setDraftSubagentDelegationMode:P,confirmProjectAction:j,view:R,selectedAppId:$,selectedProjectId:O,selectedSessionId:M,draftProvider:w,draftModel:A,activeExperience:E,codexPermissionMode:D,codexReasoningEffort:U,openPondCommandAccessMode:L,busy:J,diffPanelOpen:X,diffPanelExpanded:de,rightPanelMode:Me,rightChatPanels:Ie,newProjectMode:ne,newProjectName:je,newProjectBusy:Se,commitMessage:oe,commitIncludeUnstaged:be,commitNextStep:re,branchDialogName:ue,setSectionMenuOpen:ke,setView:Le,setSelectedAppId:we,setSelectedProjectId:le,setSelectedSessionId:xe,setPrompt:Ue,setDraftProvider:Ze,setDraftModel:it,setDiffPanelOpen:at,setRightPanelMode:Ne,setRightChatPanels:We,setSyncingWorkspaceAppId:qe,setSettingsSection:q,setNewProjectDialogOpen:N,setNewProjectMode:F,setNewProjectName:ee,setNewProjectPath:me,setNewProjectBusy:$e,setCommitDialogOpen:ze,setBranchDialogOpen:tt,setError:nt,showToast:pt,appPreferences:bt,applyBootstrapPayload:Oe,approvals:Ye,bootstrap:h,connection:B,events:Y,runtimeEventStore:ge,sessions:se,startup:G,setAppPreferences:_,setCodexHistorySessions:W,setEvents:ae,setSessions:Z,cloudProjectById:ce,localProjectById:fe,selectedApp:he,selectedCloudProject:Ae,selectedProject:Ce,selectedProjectLinkedOpenPondApp:He,selectedSession:Pe,sidebarSessions:Xe,runtimeIndexes:mt,connectedAppMentions:fn,codexHistoryEvents:Mt,setCodexHistoryEvents:dn,account:yn,accountPending:Sn,accountSignedOut:Qt,activeModel:Ja,activeProvider:_a,activeWorkspaceAppId:zn,activeWorkspaceKind:$n,activeWorkspaceLocation:Lt,appDefaults:St,selectedSessionProjectId:xn,workspaceName:xt,accountScopeKey:Dt,teamChat:Ca,communities:Vt,selectedProjectConfirmedCloudProject:kn,activeOpenPondCommandAccessMode:st,viewWorkspaceAppId:Mn,viewWorkspaceId:fi,viewWorkspaceKind:hi,openPondActionCatalog:ha,selectedActionCatalog:Ra,expandProject:Bn,setExpandedProjectIds:zi,advanceTrainingModelChatAfterTurn:Za,bindTrainingModelChatSession:K,prepareTrainingModelChatTurn:Be,chatMessages:_e,pendingChatUserMessages:Ve,recordPendingChatUserMessage:wt,runningSessionIds:na,workspaceBusy:wn,visibleWorkspaceState:Je,visibleWorkspaceDiff:Rn,rememberWorkspaceState:ht,refreshWorkspace:Nn,setWorkspaceBusy:Ya,refreshWorkspaceDiffWhenNeeded:xo,setPendingWorkspaceTarget:Pa,pendingSidebarWorkspaceTarget:ko,setPendingSidebarWorkspaceTarget:nr,projectTarget:Bi,workspaceTarget:Fn}=e,Aa=R==="apps"?"Apps":R==="get-started"?"Walkthroughs":R==="labs"?"Models":R==="scheduled"?"Workflows":R==="outputs"?"Outputs":R==="projects"?"Projects":R==="team"?Ca.detail?Lne(Ca.detail.thread,Ca.currentUserId):"Team Chat":R==="community"?Vt.preview?.displayName??"Communities":Pe?.title??rP(E),{browserConversationId:aa,handleWorkspaceDiffPanelViewStateChange:wo}=dne({appDispatch:n,diffPanelExpanded:de,diffPanelOpen:X,rightChatPanels:Ie,rightPanelMode:Me,selectedAppId:$,selectedCloudProject:Ae,selectedProjectId:O,selectedSession:Pe,selectedSessionId:M,setWorkspaceDiffPanelViewState:u,view:R,viewWorkspaceAppId:Mn,viewWorkspaceId:fi,viewWorkspaceKind:hi,workspaceDiffPanelViewState:m}),ar=y.useCallback(ft=>{ln({kind:"chat",sessionId:ft}),xe(ft),we(null),le(null),Le("chat")},[we,le,xe,Le]),Io=y.useCallback(()=>{F("existing-local"),ee(""),me(""),N(!0)},[N,F,ee,me]),_o=y.useCallback(()=>{F("local"),ee(""),me(""),N(!0)},[N,F,ee,me]),{createCloudProjectFromScratch:_t,createProjectFromScratch:gl,createProjectCollection:ir,removeProject:vl}=fne({connection:B,defaultTeamId:St.defaultTeamId,sessions:se,selectedProjectId:O,confirmProjectAction:j,applyBootstrapPayload:Oe,expandProject:Bn,setExpandedProjectIds:zi,setSelectedAppId:we,setSelectedProjectId:le,setSelectedSessionId:xe,setError:nt,setView:Le,showToast:pt}),{changeWorkspaceBranch:Ur,openCommitDialog:bl,openCreateWorkspaceBranchDialog:Fi,openDefaultsSettingsFromBranchDialog:yl,runWorkspaceTool:zr,submitCommitDialog:Br,submitCreateWorkspaceBranch:Fr,syncWorkspaceLocally:Sl}=Ene({connection:B,activeWorkspaceAppId:zn,appDefaults:St,bootstrap:h,branchDialogName:ue,commitIncludeUnstaged:be,commitMessage:oe,commitNextStep:re,draftModel:A,draftProvider:w,cloudProjects:h?.cloudProjects??[],selectedApp:he,selectedProject:Ce,selectedProjectLinkedOpenPondApp:He,selectedSession:Pe,sessions:se,title:Aa,visibleWorkspaceDiff:Rn,visibleWorkspaceState:Je,workspaceBusy:wn,workspaceName:xt,appDispatch:n,applyBootstrapPayload:Oe,expandProject:Bn,refreshWorkspace:Nn,refreshWorkspaceDiff:xo,rememberWorkspaceState:ht,setBranchDialogOpen:tt,setCommitDialogOpen:ze,setError:nt,setSessions:Z,setSettingsSection:q,setSyncingWorkspaceAppId:qe,setView:Le,setWorkspaceBusy:Ya,showToast:pt}),xl=one({applyBootstrapPayload:Oe,cloudProjects:h?.cloudProjects??[],connection:B,localProjectById:fe,selectedCloudProject:Ae,selectedProject:Ce,setWorkspaceBusy:Ya,showToast:pt,visibleWorkspaceState:Je}),gi=h?.preferences.subagents.delegationMode??"manual",kl=Pe?.subagentDelegationMode??C,Vr=!!(E==="development"&&h?.preferences.subagents.enabled&&_a!=="codex"&&!Kt(M)&&!Pe?.subagentRunId),Kr=y.useCallback(ft=>{if(!Pe){P(ft);return}if(!B||Kt(Pe.id)||Pe.subagentRunId)return;const rn=Pe.id,oa=Pe.subagentDelegationMode??null;Z(hn=>hn.map(Dn=>Dn.id===rn?{...Dn,subagentDelegationMode:ft}:Dn)),Q.patchSession(B,rn,{subagentDelegationMode:ft}).then(hn=>{Z(Dn=>Dn.map(ba=>ba.id===hn.id?hn:ba))}).catch(hn=>{Z(Dn=>Dn.map(ba=>ba.id===rn?{...ba,subagentDelegationMode:oa}:ba)),nt(hn instanceof Error?hn.message:String(hn))})},[B,Pe,nt,Z]),Co=y.useCallback(ft=>{g(rn=>rn[ft.session.id]===ft.events?rn:{...rn,[ft.session.id]:ft.events}),W(rn=>mp(rn,ft.session))},[W]),{answerCreateImproveQuestion:Wr,applyCreateImproveCandidate:ga,approveCreateImproveRun:wl,cancelCreateImproveRun:or,changeDraftProvider:Vi,openCreateImprovePullRequest:ia,reconcileCreateImprovePullRequest:Il,rejectCreateImproveCandidate:_l,pauseCreateImproveRun:Pn,resumeCreateImproveRun:Ro,reviseCreateImproveRun:Ta,sendPrompt:Qa,stopTurn:rr}=ene({applyBootstrapPayload:Oe,bootstrap:h,chatMessages:_e,connection:B,codexPermissionMode:D,codexReasoningEffort:U,openPondCommandAccessMode:st,draftModel:A,draftProvider:w,experience:E,expandProject:Bn,getPrompt:t.getSnapshot,apps:h?.apps??[],connectedAppMentions:fn,mentionedAppId:a,ensureCloudSessionReady:xl,refreshWorkspace:Nn,refreshWorkspaceDiff:xo,selectedApp:he,selectedActionCatalog:Ra,openPondActionCatalog:ha,cloudProjects:h?.cloudProjects??[],accountScopeKey:Dt,selectedCloudProject:Ae,selectedProject:Ce,selectedProjectLinkedOpenPondApp:He,selectedSession:Pe,sessions:se,workspaceTarget:Fn.value,subagentDelegationMode:Pe?.subagentDelegationMode??C,setDraftModel:it,setDraftProvider:Ze,setError:nt,setPrompt:Ue,setMentionedAppId:o,setCodexHistoryEvents:dn,setCodexHistorySessions:W,onCodexHistoryTurnActivityChange:k,onCodexHistoryTurnPayload:Co,onPendingUserMessage:wt,setEvents:ae,setSelectedAppId:we,setSelectedProjectId:le,setSelectedSessionId:xe,setSessions:Z,setView:Le,setWorkspaceBusy:Ya}),{archiveSession:Po,restoreSession:Cl,renameSession:Gr,toggleProjectPinned:sr,toggleSessionPinned:Ki,toggleSessionSavedForLater:Ao}=Ane({appPreferences:bt,connection:B,selectedSessionId:M,setAppPreferences:_,setCodexHistorySessions:W,setError:nt,setSelectedSessionId:xe,setSessions:Z}),{changeWorkspaceTarget:To,moveProjectToCloud:Jr,startCloudSetupUpload:Zr}=une({account:yn,accountPending:Sn,accountSignedOut:Qt,activeWorkspaceKind:$n,activeWorkspaceLocation:Lt,appDispatch:n,applyBootstrapPayload:Oe,busy:J,cloudSetupDialog:r,cloudProjects:h?.cloudProjects??[],connection:B,defaultTeamId:St.defaultTeamId,expandProject:Bn,localProjectById:fe,selectedCloudProject:Ae,selectedProject:Ce,selectedSession:Pe,selectedSessionProjectId:xn,setCloudSetupDialog:s,setDiffPanelOpen:at,setError:nt,setSessions:Z,setWorkspaceBusy:Ya,showToast:pt,visibleWorkspaceState:Je,workspaceBusy:wn}),Ea=y.useCallback(async ft=>{if(E==="work"&&!Pe){if(ft==="local"){Pa("local"),pt(Ce?`Next task will use the local ${Ce.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(ft==="cloud"&&!Ce&&!Ae){if(Sn){pt("Checking OpenPond account. Try again in a moment.","info");return}if(Qt){pt("Add an OpenPond account before using Hosted.","error");return}Pa("cloud"),pt("Next task will use Hosted without a Project.","info");return}}if(ft==="hybrid"){const rn=Ae?.id??kn?.id??Pe?.cloudProjectId??null,oa=Ae?.teamId??kn?.teamId??Pe?.cloudTeamId??null;if(Sn){pt("Checking OpenPond account. Try again in a moment.","info");return}if(Qt){pt("Add an OpenPond account before using Hybrid.","error");return}if(!rn||!oa){Pa(null),pt("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Pe&&!Kt(Pe.id)){if(Li(Pe))return;if(!B){pt("OpenPond App server is not connected.","error");return}const hn=await Q.patchSession(B,Pe.id,{provider:w,modelRef:ni(w,A,h?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:Ae?.name??kn?.name??Ce?.name??Pe.workspaceName??"Hybrid workspace",localProjectId:Ce?.id??Pe.localProjectId??null,cloudProjectId:rn,cloudTeamId:oa,metadata:sA(Pe.metadata),cwd:Ce?.workspacePath??Pe.cwd??null});Z(Dn=>Dn.map(ba=>ba.id===hn.id?hn:ba)),Pa(null),pt("Hybrid will use your selected model with hosted sandbox edits.","info");return}Pa("hybrid"),pt("Next message will use Hybrid with a hosted sandbox.","info");return}Pa(null),await To(ft)},[Sn,Qt,E,h?.providers,To,B,A,w,Ae?.id,Ae?.name,Ae?.teamId,Ce?.id,kn?.id,kn?.name,kn?.teamId,Ce?.name,Ce?.workspacePath,Pe,Pa,Z,pt]),ja=y.useCallback((ft,rn)=>{we(null),le(ft),xe(null),Le("chat"),Bn(ft),nr({projectId:ft,target:rn})},[Bn,we,le,xe,Le]);y.useEffect(()=>{if(!ko||R!=="chat"||O!==ko.projectId||M!==null)return;const ft=ko.target;nr(null),Ea(ft)},[Ea,ko,O,M,R]);const Yr=mne({advanceTrainingTurn:Za,bindTrainingSession:K,composerDraftStore:t,onSessionCreated:ft=>{xe(ft.id),Le("chat"),ln({kind:"chat",sessionId:ft.id}),P(null)},onSubmitted:async()=>{const ft=Pe;if(!(!B||!ft||!Uc(ft)))try{const rn=await Q.patchSession(B,ft.id,{metadata:w8(ft.metadata)});Z(oa=>oa.map(hn=>hn.id===rn.id?rn:hn))}catch(rn){pt(rn instanceof Error?`Task started, but its Draft label could not be cleared: ${rn.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:Be,sendPrompt:Qa,setMentionedAppId:o,showToast:pt}),lr=pne({appDispatch:n,connection:B,sessions:se,setDiffPanelOpen:at,setRightPanelMode:Ne,setSessions:Z,setView:Le}),{createCloudEnvironmentFromSidebar:vi,openCloudProjectDialog:cr,openUrlInBrowserPanel:Wi,showBrowserPanel:Qr,showChangesPanel:Xr,showGoalSidebarTab:es}=kte({account:yn,browserConversationId:aa,cloudProjectById:ce,cloudProjects:h?.cloudProjects??[],diffPanelOpen:X,rightPanelMode:Me,selectedProjectId:O,setDiffPanelOpen:at,setNewProjectDialogOpen:N,setNewProjectMode:F,setNewProjectName:ee,setRightPanelMode:Ne}),{changeProjectTarget:Rl,submitNewProjectDialog:ts}=hne({appDispatch:n,busy:J,cloudProjectById:ce,createCloudProjectFromScratch:_t,createProjectFromScratch:gl,createProjectCollection:ir,expandProject:Bn,localProjectById:fe,newProjectBusy:Se,newProjectMode:ne,newProjectName:je,onCreateCloudEnvironment:vi,onNewCloudProject:cr,onNewLocalProject:_o,onUseExistingFolderPath:Io,projectTargetValue:Bi.value,setDiffPanelOpen:at,setDraftModel:it,setDraftProvider:Ze,setError:nt,setNewProjectBusy:$e,setNewProjectDialogOpen:N,setNewProjectName:ee,setNewProjectPath:me,showToast:pt,workspaceBusy:wn}),ns=y.useMemo(()=>se.map(ft=>ft.id),[se]);Ite({browserConversationId:aa,sessionIds:ns,onOpenSession:ar,onShowBrowserPanel:Qr});const[Pl,Eo]=y.useState(null),as=y.useCallback(ft=>{Eo({id:Date.now(),objective:ft.objective,initialSessionIds:ft.sessionId?[ft.sessionId]:[]}),fo(ma()),Le("labs")},[Le]),{activateRightChatPanel:dr,closeRightChatPanel:bi,openRightChatPanel:Al,rightChatPanelViews:Tl,showRightChatPanel:El,showRightPanelDiffTab:jl,submitRightChatPrompt:yi,updateRightChatModel:is,updateRightChatPrompt:Ml,updateRightChatProvider:Ol,updateRightChatScrollState:$l}=Pne({activeModel:Ja,activeProvider:_a,approvals:Ye,applyRightCodexHistoryPayload:Co,codexHistoryEvents:Mt,connectedAppMentions:fn,connection:B,contextCompaction:St.contextCompaction,openLabTraining:as,locallyActiveCodexHistorySessionIds:S,openPondCommandAccessMode:L,pendingChatUserMessages:Ve,providerSettings:h?.providers??null,rightChatHistoryEvents:f,rightChatPanels:Ie,rightPanelMode:Me,runtimeIndexes:mt,runtimeEventStore:ge,runningSessionIds:na,selectedSession:Pe,selectedSessionId:M,sendPrompt:Qa,setDiffPanelOpen:at,setError:nt,setRightChatHistoryEvents:g,setRightChatPanels:We,setRightPanelMode:Ne,setRightPanelTabRequest:c,setView:Le,showChangesPanel:Xr,showToast:pt,sidebarSessions:Xe,startupReady:G.ready}),va=y.useCallback(()=>{ke(null),q("profile"),Le("settings"),ln({kind:"settings",section:"profile"})},[ke,q,Le]),os=y.useMemo(()=>eo(h?.diagnostics??qne,Y.filter(ft=>ft.name==="diagnostic")),[h?.diagnostics,Y]),Nl=y.useCallback(()=>{if(X){at(!1);return}if(R==="labs"){Ne("changes"),c({id:Date.now(),tab:"summary"}),at(!0);return}Ne("home"),at(!0)},[X,at,Ne,c,R]);return{title:Aa,browserConversationId:aa,handleWorkspaceDiffPanelViewStateChange:wo,openSessionInChat:ar,openExistingProjectPathDialog:Io,removeProject:vl,changeProjectTarget:Rl,submitNewProjectDialog:ts,changeWorkspaceBranch:Ur,openCommitDialog:bl,openCreateWorkspaceBranchDialog:Fi,openDefaultsSettingsFromBranchDialog:yl,runWorkspaceTool:zr,submitCommitDialog:Br,submitCreateWorkspaceBranch:Fr,syncWorkspaceLocally:Sl,subagentDelegationDefaultMode:gi,subagentDelegationMode:kl,subagentDelegationAvailable:Vr,changeSubagentDelegationMode:Kr,answerCreateImproveQuestion:Wr,applyCreateImproveCandidate:ga,approveCreateImproveRun:wl,cancelCreateImproveRun:or,changeDraftProvider:Vi,openCreateImprovePullRequest:ia,reconcileCreateImprovePullRequest:Il,rejectCreateImproveCandidate:_l,pauseCreateImproveRun:Pn,resumeCreateImproveRun:Ro,reviseCreateImproveRun:Ta,sendPrompt:Qa,stopTurn:rr,archiveSession:Po,restoreSession:Cl,renameSession:Gr,toggleProjectPinned:sr,toggleSessionPinned:Ki,toggleSessionSavedForLater:Ao,moveProjectToCloud:Jr,startCloudSetupUpload:Zr,changeWorkspaceTarget:Ea,switchProjectWorkspaceTarget:ja,sendPromptFromMainComposer:Yr,openSandboxWorkspace:lr,createCloudEnvironmentFromSidebar:vi,openCloudProjectDialog:cr,openUrlInBrowserPanel:Wi,showBrowserPanel:Qr,showChangesPanel:Xr,showGoalSidebarTab:es,rightChatTrainingLaunchRequest:Pl,setRightChatTrainingLaunchRequest:Eo,closeRightChatPanel:bi,openRightChatPanel:Al,rightChatPanelViews:Tl,showRightChatPanel:El,showRightPanelDiffTab:jl,submitRightChatPrompt:yi,activateRightChatPanel:dr,updateRightChatModel:is,updateRightChatPrompt:Ml,updateRightChatProvider:Ol,updateRightChatScrollState:$l,openProfileSettings:va,diagnosticEvents:os,toggleRightSidebar:Nl}}const zne=iE();function Bne(){return x.jsx(xT,{client:zne,children:x.jsx(Fne,{})})}function Fne(){const e=hte(),t=Une(e);return x.jsx(qJ,{primary:e,secondary:t})}const zoe=Object.freeze(Object.defineProperty({__proto__:null,App:Bne},Symbol.toStringTag,{value:"Module"}));export{qg as $,o9 as A,rx as B,yo as C,qc as D,BW as E,QR as F,Mie as G,Oie as H,iP as I,um as J,v8 as K,cW as L,zk as M,Sr as N,zG as O,_W as P,Ny as Q,Wn as R,sx as S,joe as T,mA as U,uoe as V,Doe as W,yd as X,Ic as Y,er as Z,$oe as _,mx as a,nP as a$,Hie as a0,coe as a1,aZ as a2,Uoe as a3,Fte as a4,loe as a5,doe as a6,Ioe as a7,boe as a8,$7 as a9,Sh as aA,Kt as aB,to as aC,wA as aD,Qie as aE,PJ as aF,see as aG,Yie as aH,wJ as aI,woe as aJ,ree as aK,$a as aL,Hi as aM,dT as aN,kne as aO,wne as aP,yte as aQ,Xie as aR,m8 as aS,ny as aT,JR as aU,rp as aV,foe as aW,py as aX,r8 as aY,Eie as aZ,Px as a_,ni as aa,tJ as ab,xs as ac,Sk as ad,voe as ae,Dk as af,iv as ag,Pu as ah,sW as ai,AW as aj,poe as ak,Tg as al,mm as am,C7 as an,CA as ao,sm as ap,sp as aq,fW as ar,EW as as,eP as at,gae as au,hoe as av,goe as aw,Eoe as ax,Y9 as ay,mW as az,xQ as b,ooe as b$,T7 as b0,Vg as b1,GJ as b2,Hoe as b3,UJ as b4,Dx as b5,up as b6,E7 as b7,Ay as b8,yP as b9,uae as bA,j9 as bB,Loe as bC,vp as bD,CP as bE,qie as bF,zc as bG,_ie as bH,Cie as bI,Uie as bJ,vW as bK,ma as bL,fo as bM,l as bN,i as bO,p as bP,ct as bQ,Pm as bR,ay as bS,ZR as bT,bd as bU,toe as bV,roe as bW,soe as bX,Lx as bY,aoe as bZ,Mh as b_,X9 as ba,$ie as bb,Nie as bc,d$ as bd,RJ as be,CJ as bf,XR as bg,ty as bh,DG as bi,Die as bj,Lie as bk,RW as bl,YR as bm,pae as bn,Pv as bo,jie as bp,lp as bq,iy as br,ln as bs,LW as bt,_A as bu,da as bv,mae as bw,xv as bx,kv as by,ru as bz,dt as c,I as c$,ioe as c0,noe as c1,Hx as c2,eoe as c3,Ot as c4,VN as c5,hae as c6,dA as c7,vae as c8,Rie as c9,ui as cA,Sae as cB,Lm as cC,ld as cD,lt as cE,Nt as cF,rd as cG,b as cH,gt as cI,T as cJ,d as cK,R_ as cL,Oz as cM,dh as cN,rt as cO,w_ as cP,Sz as cQ,m_ as cR,sz as cS,wz as cT,Tz as cU,Cae as cV,Rz as cW,v as cX,Lz as cY,pe as cZ,V as c_,oh as ca,fae as cb,Fie as cc,Vie as cd,Kie as ce,Wie as cf,s8 as cg,zie as ch,Bie as ci,qT as cj,Gne as ck,Wne as cl,Fc as cm,Rf as cn,gc as co,BT as cp,Ln as cq,la as cr,Yk as cs,aE as ct,Zne as cu,$w as cv,Um as cw,kae as cx,Wa as cy,Iz as cz,LX as d,iz as d$,H as d0,y_ as d1,s_ as d2,jz as d3,k_ as d4,Iae as d5,wae as d6,$z as d7,x_ as d8,fb as d9,pd as dA,De as dB,Nw as dC,nn as dD,die as dE,wie as dF,$b as dG,FK as dH,uie as dI,Dc as dJ,Qb as dK,fie as dL,YI as dM,du as dN,bae as dO,_n as dP,GI as dQ,ie as dR,v7 as dS,id as dT,sb as dU,kS as dV,yae as dW,Rc as dX,Bz as dY,Ke as dZ,Ga as d_,pb as da,S_ as db,zm as dc,Bm as dd,Aae as de,_ae as df,Mz as dg,Cz as dh,XK as di,Iie as dj,Zie as dk,qae as dl,Uae as dm,f3 as dn,Kae as dp,T3 as dq,Vae as dr,Tie as ds,uV as dt,k6 as du,eie as dv,tie as dw,Aie as dx,Pt as dy,Oae as dz,iw as e,rie as e$,Hae as e0,Lae as e1,jae as e2,aR as e3,zae as e4,S3 as e5,Qae as e6,bR as e7,Xae as e8,K_ as e9,yoe as eA,Soe as eB,xae as eC,Pae as eD,Tae as eE,Rae as eF,Fae as eG,Bae as eH,oi as eI,Eae as eJ,Xz as eK,Qm as eL,FC as eM,Jae as eN,oie as eO,iie as eP,aie as eQ,pie as eR,Mae as eS,H_ as eT,Hr as eU,ea as eV,y5 as eW,m4 as eX,nie as eY,sK as eZ,gd as e_,Yae as ea,Zae as eb,$ae as ec,uc as ed,vR as ee,vz as ef,Sie as eg,bie as eh,xie as ei,kie as ej,gie as ek,wm as el,yie as em,vie as en,vd as eo,Ju as ep,lb as eq,te as er,Ni as es,mie as et,qi as eu,aU as ev,eu as ew,ad as ex,Dae as ey,n3 as ez,Mr as f,cie as f0,lie as f1,sie as f2,VV as f3,Fm as f4,WW as f5,e8 as f6,Pie as f7,Wae as f8,Gae as f9,Toe as fA,lx as fB,zoe as fC,cp as fa,xoe as fb,koe as fc,Nae as fd,so as fe,dC as ff,cF as fg,Yo as fh,Ko as fi,xS as fj,Jie as fk,z9 as fl,Nk as fm,bte as fn,Fg as fo,iA as fp,UP as fq,aA as fr,qoe as fs,Roe as ft,_oe as fu,Coe as fv,jee as fw,Lne as fx,Poe as fy,Aoe as fz,N9 as g,Ci as h,op as i,b8 as j,moe as k,Gie as l,ey as m,Mte as n,Moe as o,Noe as p,sT as q,vP as r,u9 as s,Ooe as t,Kk as u,z as v,xd as w,Q as x,kd as y,y8 as z};
|