openpond 0.2.55 → 0.2.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-server.d.ts +10545 -10254
- package/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-QU4H53OG.js +2 -0
- package/dist/chunks/{app-layer-Y2UERCPY.js → app-layer-NSTE5HIT.js} +1 -1
- package/dist/chunks/app-server-connected-apps-JHGWLBXT.js +2 -0
- package/dist/chunks/app-server-evaluations-GJPFWIDA.js +2 -0
- package/dist/chunks/app-server-harness-services-IH4G6POY.js +2 -0
- package/dist/chunks/app-server-runtime-DVKOZ5B6.js +2 -0
- package/dist/chunks/apps-BKTOR4F7.js +2 -0
- package/dist/chunks/chunk-25MBPJVY.js +2 -0
- package/dist/chunks/chunk-2D4Y3HNW.js +2 -0
- package/dist/chunks/chunk-2IHO4GDJ.js +2 -0
- package/dist/chunks/chunk-2QUCCP6Z.js +2 -0
- package/dist/chunks/chunk-3K4VVB7S.js +6 -0
- package/dist/chunks/chunk-3QIB5FXI.js +10 -0
- package/dist/chunks/chunk-3RCRSMWZ.js +17 -0
- package/dist/chunks/chunk-3VUATFZD.js +2 -0
- package/dist/chunks/chunk-3Z47M3YY.js +2 -0
- package/dist/chunks/{chunk-UA5DA5I2.js → chunk-4D7HWVWD.js} +1 -1
- package/dist/chunks/chunk-4EPSHPZL.js +2 -0
- package/dist/chunks/chunk-4NESNOK5.js +2 -0
- package/dist/chunks/chunk-523TE4BI.js +2 -0
- package/dist/chunks/{chunk-B7QDZPNX.js → chunk-5MCNZCVQ.js} +1 -1
- package/dist/chunks/{chunk-DLVPSCTB.js → chunk-6QSSIT62.js} +1 -1
- package/dist/chunks/chunk-6ZFPQYHG.js +2 -0
- package/dist/chunks/chunk-74IIXVAE.js +2 -0
- package/dist/chunks/chunk-74ZXXBGN.js +6 -0
- package/dist/chunks/chunk-773TH7FN.js +2 -0
- package/dist/chunks/chunk-7E6T7GP5.js +2 -0
- package/dist/chunks/chunk-7ED24PP6.js +2 -0
- package/dist/chunks/chunk-7HPDGZOR.js +86 -0
- package/dist/chunks/chunk-7KWD2I6W.js +2 -0
- package/dist/chunks/chunk-7PXZ4X4P.js +2 -0
- package/dist/chunks/chunk-A6USMRWK.js +2 -0
- package/dist/chunks/chunk-ABD5M2D2.js +2 -0
- package/dist/chunks/chunk-ACYFMLWG.js +10 -0
- package/dist/chunks/chunk-AN525SPP.js +6 -0
- package/dist/chunks/chunk-APB2STJK.js +2 -0
- package/dist/chunks/chunk-AY64VY4E.js +2 -0
- package/dist/chunks/{chunk-G6JMQGX7.js → chunk-B7RFL4N2.js} +1 -1
- package/dist/chunks/chunk-BLXEAZCQ.js +12 -0
- package/dist/chunks/chunk-D74JEERO.js +5 -0
- package/dist/chunks/{chunk-U2YMBCX7.js → chunk-DARVPBZ4.js} +1 -1
- package/dist/chunks/chunk-DBK66CJP.js +8 -0
- package/dist/chunks/chunk-DDMZSZFL.js +1 -0
- package/dist/chunks/chunk-DIO5CB6U.js +2 -0
- package/dist/chunks/chunk-DMFUEUAZ.js +5 -0
- package/dist/chunks/chunk-DMVD2RFZ.js +2 -0
- package/dist/chunks/chunk-DUURYZOI.js +2 -0
- package/dist/chunks/chunk-DZUAT3TP.js +1 -0
- package/dist/chunks/chunk-EIEZHFIW.js +6 -0
- package/dist/chunks/chunk-EIRYMSEG.js +19 -0
- package/dist/chunks/{chunk-R27YGT77.js → chunk-EKM2D7JU.js} +1 -1
- package/dist/chunks/chunk-EQFGBL3O.js +2 -0
- package/dist/chunks/chunk-EYPCBBMS.js +2 -0
- package/dist/chunks/chunk-F4KOGISR.js +10 -0
- package/dist/chunks/chunk-F74GBN6K.js +2 -0
- package/dist/chunks/chunk-FEAKTSRS.js +2 -0
- package/dist/chunks/chunk-FFRFSDBM.js +2 -0
- package/dist/chunks/chunk-FTEOCCPB.js +23 -0
- package/dist/chunks/chunk-FUOEIDMA.js +8 -0
- package/dist/chunks/{chunk-BQAF5P7K.js → chunk-FV2R5RUN.js} +2 -2
- package/dist/chunks/chunk-FWIPHEVA.js +12 -0
- package/dist/chunks/chunk-FY5KHLMW.js +2 -0
- package/dist/chunks/chunk-G3RXYI2L.js +6 -0
- package/dist/chunks/chunk-GJ2ZJFDD.js +2 -0
- package/dist/chunks/chunk-GLDYJM7O.js +1 -0
- package/dist/chunks/chunk-GPVCOEUH.js +2 -0
- package/dist/chunks/chunk-GW766ZSO.js +5 -0
- package/dist/chunks/chunk-GWCHDF2C.js +4 -0
- package/dist/chunks/chunk-GZ7M5XBP.js +2 -0
- package/dist/chunks/chunk-H6IW2R22.js +140 -0
- package/dist/chunks/chunk-HCYX6RHP.js +2 -0
- package/dist/chunks/chunk-HDL5YSAA.js +2 -0
- package/dist/chunks/chunk-HIOKCIL7.js +2 -0
- package/dist/chunks/{chunk-IODUCRBA.js → chunk-HY3GOBFJ.js} +1 -1
- package/dist/chunks/chunk-HZEIRHEB.js +2 -0
- package/dist/chunks/chunk-I2NXNMRZ.js +2 -0
- package/dist/chunks/chunk-I7AQMAQI.js +33 -0
- package/dist/chunks/chunk-IZ6DLEVY.js +2 -0
- package/dist/chunks/chunk-J2TWKFML.js +1871 -0
- package/dist/chunks/chunk-JDEEWOD7.js +2 -0
- package/dist/chunks/chunk-JFXWI3EN.js +6 -0
- package/dist/chunks/chunk-JYKRR7E5.js +5 -0
- package/dist/chunks/chunk-KCJVFLBB.js +2 -0
- package/dist/chunks/{chunk-5CMKGD43.js → chunk-KG325WTN.js} +1 -1
- package/dist/chunks/chunk-KUERKVEU.js +3 -0
- package/dist/chunks/chunk-KVTBX2UP.js +2 -0
- package/dist/chunks/chunk-L3KS6MOV.js +2 -0
- package/dist/chunks/chunk-L6K7ERG5.js +2 -0
- package/dist/chunks/{chunk-MH3LHSGX.js → chunk-LQQNBVEB.js} +1 -1
- package/dist/chunks/{chunk-BTI4N7YO.js → chunk-M4JWQSV7.js} +1 -1
- package/dist/chunks/chunk-MQULU465.js +2 -0
- package/dist/chunks/chunk-N4FFQPLR.js +2 -0
- package/dist/chunks/chunk-N73MU2C3.js +2 -0
- package/dist/chunks/chunk-NHQ36THU.js +3 -0
- package/dist/chunks/chunk-O6ULLQJ6.js +2 -0
- package/dist/chunks/chunk-O72BSKSO.js +2 -0
- package/dist/chunks/chunk-OGDADQGH.js +143 -0
- package/dist/chunks/chunk-OIUTWU6K.js +2 -0
- package/dist/chunks/chunk-OLLLZVHF.js +2 -0
- package/dist/chunks/chunk-OPNRWESL.js +3 -0
- package/dist/chunks/chunk-OQKJGTTO.js +4 -0
- package/dist/chunks/chunk-OQPJ7FJF.js +9 -0
- package/dist/chunks/{chunk-TERVLCRG.js → chunk-OS3LO5J3.js} +1 -1
- package/dist/chunks/chunk-OUVIWDL2.js +2 -0
- package/dist/chunks/chunk-PCSIOUHF.js +7 -0
- package/dist/chunks/chunk-PF5R6CMP.js +21 -0
- package/dist/chunks/chunk-PPAPVGJP.js +3 -0
- package/dist/chunks/chunk-PRGBLQVH.js +2 -0
- package/dist/chunks/chunk-PSGGOZFM.js +2 -0
- package/dist/chunks/chunk-PUZQU66L.js +2 -0
- package/dist/chunks/{chunk-NOTXPD2T.js → chunk-Q2QL6UWN.js} +1 -1
- package/dist/chunks/chunk-Q4TBTRIG.js +2 -0
- package/dist/chunks/chunk-Q5LEXXJG.js +16 -0
- package/dist/chunks/chunk-QDC4OW3S.js +2 -0
- package/dist/chunks/chunk-QEFHOJFE.js +7 -0
- package/dist/chunks/chunk-QHWGQ3A4.js +5 -0
- package/dist/chunks/chunk-QIKWJ2AA.js +11 -0
- package/dist/chunks/chunk-QNG27G3T.js +6 -0
- package/dist/chunks/chunk-QOGJAQDO.js +3 -0
- package/dist/chunks/chunk-QOTVNQDI.js +4 -0
- package/dist/chunks/{chunk-NNIRIUSY.js → chunk-RAXOSUSW.js} +1 -1
- package/dist/chunks/chunk-RNIAFXMB.js +50 -0
- package/dist/chunks/{chunk-SHQOIROR.js → chunk-S5ESN275.js} +3 -3
- package/dist/chunks/chunk-SDAUS5PY.js +2 -0
- package/dist/chunks/chunk-SDXFLO7J.js +5 -0
- package/dist/chunks/chunk-SH5CBAFC.js +2 -0
- package/dist/chunks/chunk-SWUEFLOH.js +2 -0
- package/dist/chunks/chunk-SYUKES6H.js +3 -0
- package/dist/chunks/chunk-T5AACNJI.js +2 -0
- package/dist/chunks/chunk-TRQQNFMO.js +4 -0
- package/dist/chunks/chunk-TVQAPBLZ.js +2 -0
- package/dist/chunks/chunk-UCPGRPWY.js +2 -0
- package/dist/chunks/chunk-UGL7WF3W.js +2 -0
- package/dist/chunks/chunk-UHFZHBGW.js +2 -0
- package/dist/chunks/{chunk-C6D4WAYN.js → chunk-UKMA4R6X.js} +2 -2
- package/dist/chunks/{chunk-4WEUCGJ3.js → chunk-VRIEKBBH.js} +1 -1
- package/dist/chunks/chunk-VYLGI3IH.js +13 -0
- package/dist/chunks/chunk-W45RKGM6.js +1 -0
- package/dist/chunks/chunk-WJ43MJ3F.js +2 -0
- package/dist/chunks/chunk-WMKYHXVM.js +3 -0
- package/dist/chunks/chunk-WN3V6KDN.js +3 -0
- package/dist/chunks/chunk-X4OSOOSU.js +3 -0
- package/dist/chunks/chunk-XDQMGUWL.js +2 -0
- package/dist/chunks/chunk-XTFPDQMH.js +3 -0
- package/dist/chunks/chunk-XVDFJ3ZF.js +2 -0
- package/dist/chunks/chunk-XW6HGSIT.js +8 -0
- package/dist/chunks/chunk-XXYGGNVM.js +2 -0
- package/dist/chunks/chunk-Y4OWBBDD.js +184 -0
- package/dist/chunks/chunk-YBT2NB32.js +2 -0
- package/dist/chunks/chunk-YCJO3YVD.js +10 -0
- package/dist/chunks/{chunk-QRAKXZOC.js → chunk-YOBN7KTF.js} +6 -6
- package/dist/chunks/chunk-YOQRYNLP.js +2 -0
- package/dist/chunks/chunk-YY7LEQGP.js +2 -0
- package/dist/chunks/chunk-Z4Z5UOZM.js +22 -0
- package/dist/chunks/chunk-Z54O534A.js +3 -0
- package/dist/chunks/chunk-ZCHXGRRU.js +2 -0
- package/dist/chunks/chunk-ZFSHBFG5.js +40 -0
- package/dist/chunks/chunk-ZGTOK7ZK.js +12 -0
- package/dist/chunks/{chunk-Q7AXHFZV.js → chunk-ZRDGQDZL.js} +1 -1
- package/dist/chunks/chunk-ZUJ3XUCP.js +2 -0
- package/dist/chunks/chunk-ZZWAQBA2.js +2 -0
- package/dist/chunks/cli-X25RSO2X.js +2 -0
- package/dist/chunks/configuration-command-6C5UO7GE.js +2 -0
- package/dist/chunks/connected-app-executor-IVLGQP65.js +2 -0
- package/dist/chunks/connected-evidence-GH2ATNEX.js +2 -0
- package/dist/chunks/connection-HTF6CC7M.js +2 -0
- package/dist/chunks/{continual-TTGJ6YTR.js → continual-6CQAMTTR.js} +3 -3
- package/dist/chunks/core-commands-A2DGGIPS.js +2 -0
- package/dist/chunks/datasets-7BNMVJOY.js +2 -0
- package/dist/chunks/desktop-test-3CUHVLXV.js +3 -0
- package/dist/chunks/dist-OMGUJYPD.js +2 -0
- package/dist/chunks/dist-VYC5VMQB.js +2 -0
- package/dist/chunks/{dist-FAJX2UBW.js → dist-ZVJPJLXR.js} +1 -1
- package/dist/chunks/enclave-QS4BUNDU.js +2 -0
- package/dist/chunks/evaluation-coordination-XEF5L7KZ.js +2 -0
- package/dist/chunks/experiment-improvements-KRX2DP27.js +2 -0
- package/dist/chunks/experiments-DFGQYA4O.js +2 -0
- package/dist/chunks/experiments-VFQGE4HC.js +2 -0
- package/dist/chunks/{extension-DWMY6D2R.js → extension-XKXXOP5N.js} +1 -1
- package/dist/chunks/{help-A72QDRNG.js → help-S7THC6IE.js} +1 -1
- package/dist/chunks/host-profile-evaluation-tools-JJQWJUBT.js +2 -0
- package/dist/chunks/host-profile-external-dataset-K3ICDHIP.js +2 -0
- package/dist/chunks/hosted-app-server-composition-BCOO5ANF.js +2 -0
- package/dist/chunks/hosted-experiment-improvement-NFSVS5TU.js +3 -0
- package/dist/chunks/hosted-harness-runtime-723S5ZSH.js +2 -0
- package/dist/chunks/hosted-profile-candidate-2S5LFUWD.js +3 -0
- package/dist/chunks/hosted-profile-compiler-2DQIFSXW.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-control-76BTRTYD.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-inspection-V6Z3A5XJ.js +3 -0
- package/dist/chunks/hosted-profile-evaluation-preparation-IDJYREW3.js +3 -0
- package/dist/chunks/hosted-tasksets-ANAE2PIW.js +2 -0
- package/dist/chunks/human-review-WR777ODH.js +2 -0
- package/dist/chunks/import-MLZUHITH.js +4 -0
- package/dist/chunks/learning-ACEVFL5M.js +2 -0
- package/dist/chunks/local-harness-improvement-runtime-JIQ6ZVDW.js +2 -0
- package/dist/chunks/local-harness-taskset-review-XVYTGAGK.js +2 -0
- package/dist/chunks/local-scope-HVF2GZ5W.js +2 -0
- package/dist/chunks/model-projects-QPO22JPA.js +2 -0
- package/dist/chunks/opchat-T4QTNEIY.js +3 -0
- package/dist/chunks/organizations-75L5DZDV.js +2 -0
- package/dist/chunks/{profile-NOZ6TVXL.js → profile-TFZMUEDR.js} +1 -1
- package/dist/chunks/profile-training-source-6GOT7AHM.js +2 -0
- package/dist/chunks/project-action-payload-7VGL7OER.js +2 -0
- package/dist/chunks/project-agent-6RRO233B.js +2 -0
- package/dist/chunks/published-experiment-source-DZFENAQA.js +2 -0
- package/dist/chunks/refiner-profile-service-UUIWFJVT.js +2 -0
- package/dist/chunks/runtime-A7OZXM43.js +6 -0
- package/dist/chunks/sandbox-command-IU5XFTJP.js +2 -0
- package/dist/chunks/{sandbox-template-LKGBDVJ4.js → sandbox-template-C4V6T36U.js} +1 -1
- package/dist/chunks/saved-work-6BMBFP43.js +2 -0
- package/dist/chunks/send-turn-XTAIS2JN.js +2 -0
- package/dist/chunks/src-CJM6HY5Y.js +326 -0
- package/dist/chunks/{src-ZWJ5IO7A.js → src-LMC3K6LH.js} +1 -1
- package/dist/chunks/standalone-experiment-turn-owner-JCY5LL5R.js +2 -0
- package/dist/chunks/store-chat-workflows-S72HZXQR.js +18 -0
- package/dist/chunks/store-continual-support-reviews-HHA6NX7K.js +7 -0
- package/dist/chunks/store-conversation-serving-KPC62UEY.js +2 -0
- package/dist/chunks/store-create-improve-QV54XIZW.js +40 -0
- package/dist/chunks/store-datasets-RXJ33SUN.js +86 -0
- package/dist/chunks/store-evaluation-results-3F3P527G.js +7 -0
- package/dist/chunks/store-harness-evaluation-review-settings-I2R3HPO3.js +29 -0
- package/dist/chunks/store-harness-memory-VINCZ4GK.js +17 -0
- package/dist/chunks/store-harness-refinement-candidates-EA5KFQPH.js +21 -0
- package/dist/chunks/store-harness-workspaces-XUM4Z66X.js +2 -0
- package/dist/chunks/store-human-review-RAH7WMIP.js +7 -0
- package/dist/chunks/store-learned-preference-migration-validation-4CI2IRUF.js +2 -0
- package/dist/chunks/store-learning-WLG6KFIO.js +2 -0
- package/dist/chunks/store-learning-credentials-WZQJ4HPJ.js +2 -0
- package/dist/chunks/store-local-experiments-5LUJR7GI.js +97 -0
- package/dist/chunks/store-model-batch-review-YEGX327M.js +2 -0
- package/dist/chunks/store-model-configuration-5ZURQATB.js +3 -0
- package/dist/chunks/store-preference-comparison-LV32MHVL.js +6 -0
- package/dist/chunks/store-schedules-VGTEQVKH.js +53 -0
- package/dist/chunks/store-sidebar-file-bookmarks-VB5GTLFY.js +18 -0
- package/dist/chunks/store-sidebar-preferences-GWIOG2NH.js +16 -0
- package/dist/chunks/store-subagents-T7R2Z6TB.js +67 -0
- package/dist/chunks/store-task-inbox-JJTBW76C.js +33 -0
- package/dist/chunks/store-task-inventory-OB3F2APC.js +10 -0
- package/dist/chunks/store-taskset-drafts-EKQWWFYQ.js +9 -0
- package/dist/chunks/store-training-G6YLFSIR.js +70 -0
- package/dist/chunks/store-training-jobs-RC46YBF6.js +19 -0
- package/dist/chunks/store-training-models-6BA43IPP.js +49 -0
- package/dist/chunks/store-usage-IE2U2FD3.js +63 -0
- package/dist/chunks/store-work-evidence-QQDKM5AQ.js +8 -0
- package/dist/chunks/taskset-EQRFQBYM.js +2 -0
- package/dist/chunks/taskset-packages-XC6HEE3K.js +2 -0
- package/dist/chunks/{teams-bot-H7XT23XB.js → teams-bot-EAPGPTHZ.js} +1 -1
- package/dist/chunks/training-UF6RPI4T.js +2 -0
- package/dist/chunks/web-search-CZ3NCLPY.js +2 -0
- package/dist/chunks/workspaces-EKKE5NAC.js +2 -0
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/assets/{App-CTlAPuCY.css → App-CaRMZoxo.css} +1 -1
- package/dist/web/assets/App-s-CJswyt.js +154 -0
- package/dist/web/assets/{AppDialog-CPHTPqrx.js → AppDialog-t2Fx5tK3.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-BVj5Tj93.js → AppTerminalPanel-Dj1Y32oI.js} +2 -2
- package/dist/web/assets/{AppsView-O69zEBY3.js → AppsView-BYE5EBDJ.js} +1 -1
- package/dist/web/assets/{BrowserSidebar-Pr_Kpe8p.js → BrowserSidebar-jhWi4rVm.js} +1 -1
- package/dist/web/assets/{CartesianChart-JPqo6YOf.js → CartesianChart-C1DIx0Ia.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-CAJcQFn2.js → CollaborationTabs-Bdr-HmOL.js} +1 -1
- package/dist/web/assets/{CommandMenu-B-w53n9A.js → CommandMenu-Ux2yOHAc.js} +1 -1
- package/dist/web/assets/{CommunityView-DbZKK8_P.js → CommunityView-DPEeVKFn.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-3_083PF4.js → ComposerCreateImproveStrip-CEgh4OtN.js} +1 -1
- package/dist/web/assets/{GetStartedView-D7JGm_6c.js → GetStartedView-CFHP0AaI.js} +1 -1
- package/dist/web/assets/{HostedModelLearningReview-DwgMfZ7_.js → HostedModelLearningReview-D8BGTPVN.js} +1 -1
- package/dist/web/assets/{HostedModelLearningSettings-JRfQadRl.js → HostedModelLearningSettings-JS1S7vNO.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-BUYflJY_.js → LabModelVersionDetailPage-Dx5Q3xV2.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-BBiqk7Rf.js → LabSkillSidebar-BxffN-pN.js} +1 -1
- package/dist/web/assets/{LabsRoute-Ci6vUnSd.js → LabsRoute-CyYF8-dw.js} +4 -4
- package/dist/web/assets/{MainChatThread-BQK3oI2N.js → MainChatThread-DZpcFRFl.js} +2 -2
- package/dist/web/assets/MainPane-5DTtwVCk.js +65 -0
- package/dist/web/assets/MainPane-BIM_UJ3q.css +1 -0
- package/dist/web/assets/{MarkdownText-DOdOVFXL.js → MarkdownText-BR4V6lNO.js} +21 -21
- package/dist/web/assets/{NativeSkillSidebar-CRI_ri8z.js → NativeSkillSidebar-DU9IEgIO.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-DhYtfE68.js → NewExperienceSwitcher-mIy6FzCj.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-D8sy1gOz.js → NewProjectDialog-RfTZTHxl.js} +1 -1
- package/dist/web/assets/{OutputsPage-CbWgrhXA.js → OutputsPage-Cr1Spf7S.js} +1 -1
- package/dist/web/assets/{ProjectsPage-DLB67lyA.js → ProjectsPage-CE6QUB-b.js} +1 -1
- package/dist/web/assets/{RightChatPanelStack-ozSKnDyX.js → RightChatPanelStack-T6VRWuHo.js} +1 -1
- package/dist/web/assets/RightSidebarHomePanel-CK0rP3WT.js +1 -0
- package/dist/web/assets/{ScheduledWorkPage-Cafv_QnR.js → ScheduledWorkPage-vOrYv8pp.js} +1 -1
- package/dist/web/assets/SettingsView-DCKVrfjj.js +5 -0
- package/dist/web/assets/SettingsView-Dulr_xlq.css +1 -0
- package/dist/web/assets/{TeamChatView-vIrmXOY_.js → TeamChatView-Bwrjr-vk.js} +2 -2
- package/dist/web/assets/{TerminalOverlay-CAmF__Dq.js → TerminalOverlay-DhPoKZAq.js} +1 -1
- package/dist/web/assets/TrainingCreationPanel-BXHfohNm.js +1 -0
- package/dist/web/assets/{TrainingDraftPanel-D7XZePAk.js → TrainingDraftPanel-C9cRX5qf.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-CYTmp7PG.js → UsageSettingsSection-CrdcSGeW.js} +1 -1
- package/dist/web/assets/WorkSidebarPanel-DSSikNFQ.js +1 -0
- package/dist/web/assets/{WorkspaceDiffPanel-DQGoIjH9.js → WorkspaceDiffPanel-BAFo0CPN.js} +6 -6
- package/dist/web/assets/{WorkspaceEnvironmentMenu-c1pHDskn.js → WorkspaceEnvironmentMenu-BVHAhwnJ.js} +1 -1
- package/dist/web/assets/WorkspaceGitDialogs-CwVoiDQ2.js +1 -0
- package/dist/web/assets/{WorkspaceMonacoEditor-BCKzvSj2.js → WorkspaceMonacoEditor-TxLyhzNp.js} +3 -3
- package/dist/web/assets/{arrow-up-right-CP4hZdrJ.js → arrow-up-right-C9aE8Mfz.js} +1 -1
- package/dist/web/assets/{chunk-NOJECMB7-Bhcms-w5.js → chunk-P3BRSSRD-DUGfuKA8.js} +1 -1
- package/dist/web/assets/{clipboard-BgrXorn-.js → clipboard-Dk158Qp4.js} +1 -1
- package/dist/web/assets/{cloud-upload-B_zYztb6.js → cloud-upload-k9eqBsHr.js} +1 -1
- package/dist/web/assets/{cssMode-DanjGgA8.js → cssMode-CO35ARZp.js} +1 -1
- package/dist/web/assets/{folder-open-CdVKbtGq.js → folder-open-sYgceW_f.js} +1 -1
- package/dist/web/assets/{folder-plus-Cc5KElB6.js → folder-plus-CS0R49m9.js} +1 -1
- package/dist/web/assets/{git-commit-horizontal-CjGIIgRi.js → git-commit-horizontal-DrGxH2h4.js} +1 -1
- package/dist/web/assets/{htmlMode-DRGDF_UL.js → htmlMode-REMmzdfq.js} +1 -1
- package/dist/web/assets/index-3iPNbbER.css +1 -0
- package/dist/web/assets/{index-BE-wXZ5R.js → index-C8aCGagb.js} +2 -2
- package/dist/web/assets/{info-BLj0RvhA.js → info-DLdbiUrh.js} +1 -1
- package/dist/web/assets/{jsonMode-CCu0j2GD.js → jsonMode-KEdMfkIf.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-s_Lhm7P6.js → lspLanguageFeatures-5KZwEoxW.js} +1 -1
- package/dist/web/assets/{minimize-2-Cyg_zD9z.js → minimize-2-CqcI4zcM.js} +1 -1
- package/dist/web/assets/{monaco.contribution-CY7mRgOB.js → monaco.contribution-BJGj65F9.js} +2 -2
- package/dist/web/assets/{monaco.contribution-CAzXvYkn.js → monaco.contribution-Cly9Wt7L.js} +2 -2
- package/dist/web/assets/{monaco.contribution-mUPNK9ra.js → monaco.contribution-DO10L0zW.js} +2 -2
- package/dist/web/assets/{monaco.contribution-aUeLcBEg.js → monaco.contribution-omszXBEj.js} +2 -2
- package/dist/web/assets/{monitor-DZvOs_wC.js → monitor-BFVCcbxp.js} +1 -1
- package/dist/web/assets/{play-BJPzemuY.js → play-C469pVZq.js} +1 -1
- package/dist/web/assets/{python-B_qnnVaG.js → python-Dw0YcVy9.js} +1 -1
- package/dist/web/assets/{save-BDy9tA3E.js → save-CtSjPydi.js} +1 -1
- package/dist/web/assets/{square-Cb2c5td4.js → square-BuImvLhT.js} +1 -1
- package/dist/web/assets/{toggleHighContrast-MhO1JLyR.js → toggleHighContrast-DjCO9lIP.js} +1 -1
- package/dist/web/assets/{tsMode-DfBXJb9V.js → tsMode-BAOnxKd6.js} +1 -1
- package/dist/web/assets/{upload-D56kThRh.js → upload-2JkFZo3h.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-DMnGfswi.js → useLocalAgentSchedules-BNqAisfS.js} +1 -1
- package/dist/web/assets/useProviderSettings-C4L4wDoh.js +5 -0
- package/dist/web/assets/{useProviderSettings-Bw-csWbH.css → useProviderSettings-CmL_BaxP.css} +1 -1
- package/dist/web/assets/{useSessionTurnCache-ClAY8gze.js → useSessionTurnCache-BHU2-Jmz.js} +1 -1
- package/dist/web/assets/{wifi-off-C9lWJmVm.js → wifi-off-CpOAH62M.js} +1 -1
- package/dist/web/assets/{workers-BYzrH8by.js → workers-0QvlA2T5.js} +1 -1
- package/dist/web/assets/{yaml-D3T8UkT3.js → yaml-BK3qxo7D.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunks/actions-command-WTFZA7LF.js +0 -2
- package/dist/chunks/app-server-runtime-2RM3N4I6.js +0 -2
- package/dist/chunks/apps-KDNWYO3G.js +0 -2
- package/dist/chunks/chunk-2DFR7PJ4.js +0 -2460
- package/dist/chunks/chunk-4CRM2ADK.js +0 -2
- package/dist/chunks/chunk-55G6B54U.js +0 -6
- package/dist/chunks/chunk-73G5UYBB.js +0 -12
- package/dist/chunks/chunk-ARQEJOEK.js +0 -33
- package/dist/chunks/chunk-CGBI2VYJ.js +0 -2
- package/dist/chunks/chunk-GGIG3XU7.js +0 -3
- package/dist/chunks/chunk-JIMU3KDA.js +0 -24
- package/dist/chunks/chunk-JUJSA7KI.js +0 -22
- package/dist/chunks/chunk-K5SBVO3B.js +0 -195
- package/dist/chunks/chunk-KD3QVRIJ.js +0 -21
- package/dist/chunks/chunk-L4235TRQ.js +0 -140
- package/dist/chunks/chunk-MVF3F5QS.js +0 -2
- package/dist/chunks/chunk-OULAKUIN.js +0 -2
- package/dist/chunks/chunk-OWNLDB2O.js +0 -2
- package/dist/chunks/chunk-QDHMP5FS.js +0 -2
- package/dist/chunks/chunk-QKD5OMDI.js +0 -2
- package/dist/chunks/chunk-R2BSIRYL.js +0 -3
- package/dist/chunks/chunk-STDMBJOQ.js +0 -9
- package/dist/chunks/chunk-T4QGDQHP.js +0 -4
- package/dist/chunks/chunk-USMZT5FZ.js +0 -18
- package/dist/chunks/chunk-VJEZPDBS.js +0 -5
- package/dist/chunks/chunk-WDFLCNRC.js +0 -8
- package/dist/chunks/chunk-WZYRAR7X.js +0 -16
- package/dist/chunks/chunk-YDT7L3VZ.js +0 -24
- package/dist/chunks/chunk-YUPBAWBJ.js +0 -554
- package/dist/chunks/cli-465VC2WP.js +0 -2
- package/dist/chunks/configuration-command-LAAP2EXT.js +0 -2
- package/dist/chunks/connected-evidence-XM626247.js +0 -2
- package/dist/chunks/core-commands-W7EK552V.js +0 -2
- package/dist/chunks/datasets-QJWYTTQL.js +0 -2
- package/dist/chunks/desktop-test-3B2D34NF.js +0 -3
- package/dist/chunks/dist-HUAE2KFZ.js +0 -2
- package/dist/chunks/evaluation-coordination-2MONR4AX.js +0 -2
- package/dist/chunks/experiment-improvements-WVQ5FK46.js +0 -2
- package/dist/chunks/experiments-S5UQ32QB.js +0 -2
- package/dist/chunks/hosted-experiment-improvement-2OWOQLHC.js +0 -3
- package/dist/chunks/hosted-harness-runtime-TGFMAV7W.js +0 -2
- package/dist/chunks/hosted-profile-candidate-WQSI6HZO.js +0 -3
- package/dist/chunks/hosted-profile-compiler-Z2A4TEA6.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-control-FKGARUEE.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-inspection-QOY2JKV4.js +0 -3
- package/dist/chunks/hosted-profile-evaluation-preparation-WVP6CALP.js +0 -3
- package/dist/chunks/human-review-TGHQKXFZ.js +0 -2
- package/dist/chunks/import-4UE5XNSG.js +0 -4
- package/dist/chunks/learning-R2XBMMEM.js +0 -2
- package/dist/chunks/opchat-WULL6CUP.js +0 -3
- package/dist/chunks/organizations-I37HISVX.js +0 -2
- package/dist/chunks/project-agent-T6XKC54C.js +0 -2
- package/dist/chunks/sandbox-command-STB47FRY.js +0 -2
- package/dist/chunks/src-T3KWWCAH.js +0 -322
- package/dist/chunks/taskset-RNYDR4GS.js +0 -2
- package/dist/chunks/training-M6FAPRSJ.js +0 -2
- package/dist/chunks/workspaces-MFZ3OO6O.js +0 -2
- package/dist/web/assets/App-CLFfy_Av.js +0 -154
- package/dist/web/assets/MainPane-D3ojiN-p.js +0 -18
- package/dist/web/assets/MainPane-DOWsSew1.css +0 -1
- package/dist/web/assets/RightSidebarHomePanel-CKs3OwhD.js +0 -1
- package/dist/web/assets/SettingsView-BnANbPLS.css +0 -1
- package/dist/web/assets/SettingsView-T1vYDPjh.js +0 -5
- package/dist/web/assets/TrainingCreationPanel-D75K0yk5.js +0 -1
- package/dist/web/assets/WorkSidebarPanel-CODMjVHY.js +0 -1
- package/dist/web/assets/WorkspaceGitDialogs-DrVtapQQ.js +0 -1
- package/dist/web/assets/index-B5re-RJy.css +0 -1
- package/dist/web/assets/useProviderSettings-Bv5B9eNk.js +0 -5
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalOverlay-DhPoKZAq.js","assets/index-C8aCGagb.js","assets/index-3iPNbbER.css","assets/TerminalOverlay-DwBiZLwk.css","assets/CommandMenu-Ux2yOHAc.js","assets/CommandMenu-Cb3vNGJr.css","assets/SettingsView-DCKVrfjj.js","assets/useProviderSettings-C4L4wDoh.js","assets/save-CtSjPydi.js","assets/MarkdownText-BR4V6lNO.js","assets/useProviderSettings-CmL_BaxP.css","assets/folder-open-sYgceW_f.js","assets/play-C469pVZq.js","assets/wifi-off-CpOAH62M.js","assets/cloud-upload-k9eqBsHr.js","assets/git-commit-horizontal-DrGxH2h4.js","assets/useLocalAgentSchedules-BNqAisfS.js","assets/folder-plus-CS0R49m9.js","assets/AppDialog-t2Fx5tK3.js","assets/WorkspaceDiffPanel-BAFo0CPN.js","assets/training-model-data-CKOkpBBL.js","assets/info-DLdbiUrh.js","assets/minimize-2-CqcI4zcM.js","assets/clipboard-Dk158Qp4.js","assets/SettingsView-Dulr_xlq.css","assets/git-dialogs-C-F47S10.css","assets/NewProjectDialog-RfTZTHxl.js","assets/monitor-BFVCcbxp.js","assets/WorkspaceGitDialogs-CwVoiDQ2.js","assets/upload-2JkFZo3h.js","assets/WorkspaceEnvironmentMenu-BVHAhwnJ.js","assets/square-BuImvLhT.js","assets/WorkspaceEnvironmentMenu-DGIFdG3o.css","assets/MainPane-5DTtwVCk.js","assets/arrow-up-right-C9aE8Mfz.js","assets/MainPane-BIM_UJ3q.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as h,j as g,a as g_,g as p0,_ as fs}from"./index-C8aCGagb.js";const f0=h.createContext(void 0),h0=e=>{const t=h.useContext(f0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},v_=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),g.jsx(f0.Provider,{value:e,children:t})),b_={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var y_=class{#e=b_;#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 zs=new y_;function S_(e){setTimeout(e,0)}const x_=typeof window>"u"||"Deno"in globalThis;function Yn(){}function k_(e,t){return typeof e=="function"?e(t):e}function g0(e){return typeof e=="number"&&e>=0&&e!==1/0}function v0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function on(e,t){return typeof e=="function"?e(t):e}function Gg(e,t){const{type:n="all",exact:a,fetchStatus:r,predicate:s,queryKey:i,stale:c}=e;if(i){if(a){if(t.queryHash!==Hf(i,t.options))return!1}else if(!ri(t.queryKey,i))return!1}if(n!=="all"){const d=t.isActive();if(n==="active"&&!d||n==="inactive"&&d)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||r&&r!==t.state.fetchStatus||s&&!s(t))}function Zg(e,t){const{exact:n,status:a,predicate:r,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(bc(t.options.mutationKey)!==bc(s))return!1}else if(!ri(t.options.mutationKey,s))return!1}return!(a&&t.state.status!==a||r&&!r(t))}function Hf(e,t){return(t?.queryKeyHashFn||bc)(e)}function bc(e){return JSON.stringify(e,(t,n)=>Np(n)?Object.keys(n).sort().reduce((a,r)=>(a[r]=n[r],a),{}):n)}function ri(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(!ri(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!ri(e[a],t[a]))return!1;return!0}return!1}const w_=Object.prototype.hasOwnProperty;function b0(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Jg(e)&&Jg(t);if(!a&&!(Np(e)&&Np(t)))return t;const r=(a?e:Object.keys(e)).length,s=a?t:Object.keys(t),i=s.length,c=a?new Array(i):{};let d=0;for(let l=0;l<i;l++){const p=a?l:s[l],f=e[p],S=t[p];if(f===S){c[p]=f,(a?l<r:w_.call(e,p))&&d++;continue}if(f===null||S===null||typeof f!="object"||typeof S!="object"){c[p]=S;continue}const b=b0(f,S,n+1);c[p]=b,b===f&&d++}return r===i&&d===r?e:c}function Hm(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 Jg(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Np(e){if(!Qg(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Qg(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Qg(e){return Object.prototype.toString.call(e)==="[object Object]"}function I_(e){return new Promise(t=>{zs.setTimeout(t,e)})}function Dp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?b0(e,t):t}function __(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function C_(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const Uf=Symbol();function y0(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Uf?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function S0(e,t){return typeof e=="function"?e(...t):!!e}function R_(e,t,n){let a=!1,r;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(r??=t(),a||(a=!0,r.aborted?n():r.addEventListener("abort",n,{once:!0})),r)}),e}let P_=()=>x_;const qf=()=>P_();var Lc=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(){}},T_=class extends Lc{#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 Bf=new T_,A_=S_;function E_(){let e=[],t=0,n=c=>{c()},a=c=>{c()},r=A_;const s=c=>{t?e.push(c):r(()=>{n(c)})},i=()=>{const c=e;e=[],c.length&&r(()=>{a(()=>{c.forEach(d=>{n(d)})})})};return{batch:c=>{let d;t++;try{d=c()}finally{t--,t||i()}return d},batchCalls:c=>(...d)=>{s(()=>{c(...d)})},schedule:s,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{a=c},setScheduler:c=>{r=c}}}const Dn=E_();var j_=class extends Lc{#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 vd=new j_;function M_(e){return Math.min(1e3*2**e,3e4)}function x0(e){return(e??"online")==="online"?vd.isOnline():!0}var Lp=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function k0(e){let t=!1,n=0,a,r="pending",s,i;const c=new Promise((M,A)=>{s=M,i=A});c.catch(Yn);const d=()=>r!=="pending",l=M=>{if(!d()){const A=new Lp(M);C(A),e.onCancel?.(A)}},p=()=>{t=!0},f=()=>{t=!1},S=()=>Bf.isFocused()&&(e.networkMode==="always"||vd.isOnline())&&e.canRun(),b=()=>x0(e.networkMode)&&e.canRun(),I=M=>{d()||(a?.(),r="resolved",s(M))},C=M=>{d()||(a?.(),r="rejected",i(M))},P=()=>new Promise(M=>{a=A=>{(d()||S())&&M(A)},e.onPause?.()}).then(()=>{a=void 0,d()||e.onContinue?.()}),_=()=>{if(d())return;let M;const A=n===0?e.initialPromise:void 0;try{M=A??e.fn()}catch(T){M=Promise.reject(T)}Promise.resolve(M).then(I).catch(T=>{if(d())return;const y=e.retry??(qf()?0:3),w=e.retryDelay??M_,R=typeof w=="function"?w(n,T):w,O=y===!0||typeof y=="number"&&n<y||typeof y=="function"&&y(n,T);if(t||!O){C(T);return}n++,e.onFail?.(n,T),I_(R).then(()=>S()?void 0:P()).then(()=>{t?C(T):_()})})};return{promise:c,status:()=>r,cancel:l,continue:()=>(a?.(),c),cancelRetry:p,continueRetry:f,canStart:b,start:()=>(b()?_():P().then(_),c)}}var w0=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),g0(this.gcTime)&&(this.#e=zs.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(qf()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(zs.clearTimeout(this.#e),this.#e=void 0)}};function O_(e){return{onFetch:(t,n)=>{const a=t.options,r=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],i=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},d=0;const l=async()=>{let p=!1;const f=I=>{R_(I,()=>t.signal,()=>p=!0)},S=y0(t.options,t.fetchOptions),b=async(I,C,P)=>{if(p)return Promise.reject(t.signal.reason);if(C==null&&I.pages.length)return Promise.resolve(I);const M=(()=>{const w={client:t.client,queryKey:t.queryKey,pageParam:C,direction:P?"backward":"forward",meta:t.options.meta};return f(w),w})(),A=await S(M),{maxPages:T}=t.options,y=P?C_:__;return{pages:y(I.pages,A,T),pageParams:y(I.pageParams,C,T)}};if(r&&s.length){const I=r==="backward",C=I?I0:zp,P={pages:s,pageParams:i};c=await b(P,C(a,P),I)}else{const I=e??s.length;do{const C=d===0?i[0]??a.initialPageParam:zp(a,c);if(d>0&&C==null)break;c=await b(c,C),d++}while(d<I)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function zp(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 I0(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function d8(e,t){return t?zp(e,t)!=null:!1}function u8(e,t){return!t||!e.getPreviousPageParam?!1:I0(e,t)!=null}var $_=class extends w0{#e;#t;#n;#a;#s;#r;#o;#c;constructor(e){super(),this.#c=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#s=e.client,this.#a=this.#s.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Xg(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.#r?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Xg(this.options);t.data!==void 0&&(this.setState(Yg(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=Dp(this.state.data,e,this.options);return this.#i({data:n,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#i({type:"setState",state:e})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(Yn).catch(Yn):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=>on(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Uf||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>on(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:!v0(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.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.#r&&(this.#c||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#a.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const d=this.observers.find(l=>l.options.queryFn);d&&this.setOptions(d.options)}const n=new AbortController,a=d=>{Object.defineProperty(d,"signal",{enumerable:!0,get:()=>(this.#c=!0,n.signal)})},r=()=>{const d=y0(this.options,t),p=(()=>{const f={client:this.#s,queryKey:this.queryKey,meta:this.meta};return a(f),f})();return this.#c=!1,this.options.persister?this.options.persister(d,p,this):d(p)},i=(()=>{const d={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#s,state:this.state,fetchFn:r};return a(d),d})();(this.#e==="infinite"?O_(this.options.pages):this.options.behavior)?.onFetch(i,this),this.#n=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==i.fetchOptions?.meta)&&this.#i({type:"fetch",meta:i.fetchOptions?.meta});const c=this.#r=k0({initialPromise:t?.initialPromise,fn:i.fetchFn,onCancel:d=>{d instanceof Lp&&d.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(d,l)=>{this.#i({type:"failed",failureCount:d,error:l})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:i.options.retry,retryDelay:i.options.retryDelay,networkMode:i.options.networkMode,canRun:()=>!0});try{const d=await c.start();if(d===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(d),this.#a.config.onSuccess?.(d,this),this.#a.config.onSettled?.(d,this.state.error,this),d}catch(d){if(d instanceof Lp){if(d.silent)return this.#r.promise;if(d.revert){if(this.state.data===void 0)throw d;return this.state.data}}throw this.#i({type:"error",error:d}),this.#a.config.onError?.(d,this),this.#a.config.onSettled?.(this.state.data,d,this),d}finally{this.#r===c&&(this.#r=void 0),this.scheduleGc()}}#i(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,..._0(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Yg(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 r=e.error;return{...n,error:r,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Dn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function _0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:x0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Yg(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Xg(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 N_=class extends Lc{#e;#t=void 0;#n=void 0;#a=void 0;#s;#r;#o;#c;#i;#p;#d;#u;#l;#f=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),ev(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Hp(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Hp(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 on(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&&!Hm(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&tv(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||on(this.options.enabled,this.#t)!==on(t.enabled,this.#t)||on(this.options.staleTime,this.#t)!==on(t.staleTime,this.#t))&&this.#g();const r=this.#v();a&&(this.#t!==n||on(this.options.enabled,this.#t)!==on(t.enabled,this.#t)||r!==this.#l)&&this.#b(r)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Hm(this.getCurrentResult(),n)||(this.#a=n,this.#r=this.options,this.#s=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=()=>{},r;const s=new Promise(i=>{r=i,a=this.#e.getQueryCache().subscribe(c=>{c.type==="updated"&&c.query.queryHash===n.queryHash&&n.state.data!==void 0&&(a(),i(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{const i=this.createResult(n,t);return r?.(i),i}).finally(()=>{a()}),s])}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(Yn)),t}#h(e){return!qf()&&on(this.options.enabled,this.#t)!==!1&&g0(e)}#g(){this.#S();const e=on(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=v0(this.#a.dataUpdatedAt,e)+1;this.#d=zs.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.#l=e,!(this.#l===0||!this.#h(this.#l))&&(this.#u=zs.setInterval(()=>{(this.options.refetchIntervalInBackground||Bf.isFocused())&&this.#m()},this.#l))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(zs.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(zs.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,r=this.#a,s=this.#s,i=this.#r,c=e!==n?e.state:this.#n,{state:d}=e;let l={...d},p=!1,f;if(t._optimisticResults){const y=this.hasListeners(),w=!y&&ev(e,t),R=y&&tv(e,n,t,a);(w||R)&&(l={...l,..._0(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(l.fetchStatus="idle")}let{error:S,errorUpdatedAt:b,status:I}=l;f=l.data;let C=!1;if(t.placeholderData!==void 0&&f===void 0&&I==="pending"){let y;r?.isPlaceholderData&&t.placeholderData===i?.placeholderData?(y=r.data,C=!0):y=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,y!==void 0&&(I="success",f=Dp(r?.data,y,t),p=!0)}if(t.select&&f!==void 0&&!C)if(r&&f===s?.data&&t.select===this.#c)f=this.#i;else try{this.#c=t.select,f=t.select(f),f=Dp(r?.data,f,t),this.#i=f,this.#o=null}catch(y){this.#o=y}else f===void 0&&(this.#o=null);this.#o&&(S=this.#o,f=this.#i,b=Date.now(),I="error",p=!1);const P=l.fetchStatus==="fetching",_=I==="pending",M=I==="error",A=_&&P,T=f!==void 0;return{status:I,fetchStatus:l.fetchStatus,isPending:_,isSuccess:I==="success",isError:M,isInitialLoading:A,isLoading:A,data:f,dataUpdatedAt:l.dataUpdatedAt,error:S,errorUpdatedAt:b,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>c.dataUpdateCount||l.errorUpdateCount>c.errorUpdateCount,isFetching:P,isRefetching:P&&!_,isLoadingError:M&&!T,isPaused:l.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:M&&T,isStale:Ff(e,t),refetch:this.refetch,isEnabled:on(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#s=this.#t.state,this.#r=this.options,this.#s.data!==void 0&&(this.#p=this.#t),Hm(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,s=typeof r=="function"?r():r;if(s==="all"||!s&&!this.#f.size)return!0;const i=new Set(s??this.#f);return this.options.throwOnError&&i.add("error"),Object.keys(this.#a).some(c=>{const d=c;return this.#a[d]!==e[d]&&i.has(d)})})();Dn.batch(()=>{a&&this.listeners.forEach(r=>{r(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 D_(e,t){return on(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&on(t.retryOnMount,e)===!1)}function ev(e,t){return D_(e,t)||e.state.data!==void 0&&Hp(e,t,t.refetchOnMount)}function Hp(e,t,n){if(on(t.enabled,e)!==!1&&on(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&Ff(e,t)}return!1}function tv(e,t,n,a){return(e!==t||on(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ff(e,n)}function Ff(e,t){return on(t.enabled,e)!==!1&&e.isStaleByTime(on(t.staleTime,e))}var L_=class extends w0{#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||z_(),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.#s({type:"continue"})},a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#a=k0({fn:()=>this.options.mutationFn?this.options.mutationFn(t,a):Promise.reject(new Error("No mutationFn found")),onFail:(c,d)=>{this.#s({type:"failed",failureCount:c,error:d})},onPause:()=>{this.#s({type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),s=this.state.status==="pending",i=!r.canStart();try{if(s)n();else{this.#s({type:"pending",variables:t,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,a);const d=await this.options.onMutate?.(t,a);d!==this.state.context&&this.#s({type:"pending",context:d,variables:t,isPaused:i})}const c=await r.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.#s({type:"success",data:c}),c}catch(c){try{await this.#n.config.onError?.(c,t,this.state.context,this,a)}catch(d){Promise.reject(d)}try{await this.options.onError?.(c,t,this.state.context,a)}catch(d){Promise.reject(d)}try{await this.#n.config.onSettled?.(void 0,c,this.state.variables,this.state.context,this,a)}catch(d){Promise.reject(d)}try{await this.options.onSettled?.(void 0,c,t,this.state.context,a)}catch(d){Promise.reject(d)}throw this.#s({type:"error",error:c}),c}finally{this.#a===r&&(this.#a=void 0),this.#n.runNext(this)}}#s(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),Dn.batch(()=>{this.#t.forEach(a=>{a.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function z_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var H_=class extends Lc{#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 L_({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=Il(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=Il(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=Il(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=Il(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Dn.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=>Zg(t,n))}findAll(e={}){return this.getAll().filter(t=>Zg(e,t))}notify(e){Dn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Dn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Yn))))}};function Il(e){return e.options.scope?.id}var U_=class extends Lc{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,r=t.queryHash??Hf(a,t);let s=this.get(r);return s||(s=new $_({client:e,queryKey:a,queryHash:r,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(s)),s}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(){Dn.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=>Gg(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Gg(e,n)):t}notify(e){Dn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Dn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Dn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},q_=class{#e;#t;#n;#a;#s;#r;#o;#c;constructor(e={}){this.#e=e.queryCache||new U_,this.#t=e.mutationCache||new H_,this.#n=e.defaultOptions||{},this.#a=new Map,this.#s=new Map,this.#r=0}mount(){this.#r++,this.#r===1&&(this.#o=Bf.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#c=vd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#r--,this.#r===0&&(this.#o?.(),this.#o=void 0,this.#c?.(),this.#c=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(on(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}),r=this.#e.get(a.queryHash)?.state.data,s=k_(t,r);if(s!==void 0)return this.#e.build(this,a).setData(s,{...n,manual:!0})}setQueriesData(e,t,n){return Dn.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;Dn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Dn.batch(()=>{const a=n.findAll(e),r=new Set(a);return a.forEach(s=>{s.reset()}),this.refetchQueries({type:"active",predicate:s=>r.has(s)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Dn.batch(()=>this.#e.findAll(e).map(r=>r.cancel(n)));return Promise.all(a).then(Yn).catch(Yn)}invalidateQueries(e,t={}){return Dn.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=Dn.batch(()=>this.#e.findAll(e).filter(r=>!r.isDisabled()&&!r.isStatic()).map(r=>{let s=r.fetch(void 0,n);return n.throwOnError||(s=s.catch(Yn)),r.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(a).then(Yn)}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(on(t.staleTime,n))?await n.fetch(t):n.state.data,r=t.select;return r?r(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(on(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Yn).catch(Yn)}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(Yn).catch(Yn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return vd.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(bc(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{ri(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#s.set(bc(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#s.values()],n={};return t.forEach(a=>{ri(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=Hf(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===Uf&&(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 C0=h.createContext(!1),B_=()=>h.useContext(C0);C0.Provider;function F_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const V_=h.createContext(F_()),K_=()=>h.useContext(V_),W_=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?S0(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},G_=e=>{h.useEffect(()=>{e.clearReset()},[e])},Z_=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:r})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(r&&e.data===void 0||S0(n,[e.error,a])),J_=e=>{if(e.suspense){const n=r=>r==="static"?r:Math.max(r??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...r)=>n(a(...r)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Q_=(e,t)=>e?.suspense&&t.isPending,Y_=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function X_(e,t,n){const a=B_(),r=K_(),s=h0(),i=s.defaultQueryOptions(e),c=s.getQueryCache().get(i.queryHash),d=e.subscribed!==!1;i._optimisticResults=a?"isRestoring":d?"optimistic":void 0,J_(i),W_(i,r,c),G_(r);const[l]=h.useState(()=>new t(s,i)),p=l.getOptimisticResult(i),f=!a&&d;if(h.useSyncExternalStore(h.useCallback(S=>{const b=f?l.subscribe(Dn.batchCalls(S)):Yn;return l.updateResult(),b},[l,f]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),h.useEffect(()=>{l.setOptions(i)},[i,l]),Q_(i,p))throw Y_(i,l,r);if(Z_({result:p,errorResetBoundary:r,throwOnError:i.throwOnError,query:c,suspense:i.suspense}))throw p.error;return i.notifyOnChangeProps?p:l.trackResult(p)}function R0(e,t){return X_(e,N_)}function eC(){return new q_({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}const tC=new Set(["turn.started","turn.completed","turn.failed","turn.interrupted","approval.requested","approval.resolved","task.input","task.wait"]);function nC(e){const t={};for(const n of e)n.sessionId&&tC.has(n.name)&&(Date.parse(n.timestamp)>Date.parse(t[n.sessionId]??"")||!t[n.sessionId]&&Number.isFinite(Date.parse(n.timestamp)))&&(t[n.sessionId]=n.timestamp);return t}function aC(e,t,n){return[...new Map(e.map(a=>[a.id,a])).values()].sort((a,r)=>Number(n.has(r.id))-Number(n.has(a.id))||bd(r,t)-bd(a,t)||a.id.localeCompare(r.id))}function bd(e,t){const n=typeof e.metadata?.sidebarActivityAt=="string"?e.metadata.sidebarActivityAt:null;return Math.max(Date.parse(t[e.id]??"")||0,Date.parse(n??e.createdAt)||0)}function rC(e,t,n,a=new Date){const r=c=>`${c.getFullYear()}-${c.getMonth()}-${c.getDate()}`,s=new Date(a);s.setDate(a.getDate()-1);const i=[];for(const c of e){const d=new Date(bd(c,t)),l=n.has(c.id),p=l?"running":r(d);let f=i.at(-1);f?.key!==p&&(f={key:p,label:l||p===r(a)?null:p===r(s)?"Yesterday":d.toLocaleDateString(void 0,{month:"short",day:"numeric",...d.getFullYear()!==a.getFullYear()?{year:"numeric"}:{}}),sessions:[]},i.push(f)),f.sessions.push(c)}return i}function sC(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const r=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&r.searchParams.set("afterSequence",String(n)),{url:r.toString(),init:{headers:a,signal:t}}}function oC(e){return Math.min(500*2**Math.max(0,e),1e4)}async function iC(e,t,n,a){P0(e);const r=e.body.getReader(),s=new TextDecoder;let i="";for(;!a?.aborted;){const{done:c,value:d}=await r.read();if(c){i+=s.decode();break}i+=s.decode(d,{stream:!0});let l=i.indexOf(`
|
|
3
|
+
|
|
4
|
+
`);for(;l>=0;){const p=i.slice(0,l);i=i.slice(l+2),av(p,t,n),l=i.indexOf(`
|
|
5
|
+
|
|
6
|
+
`)}}!a?.aborted&&i.trim()&&av(i,t,n)}function P0(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 cC(e,t,n,a,r={}){const s=new AbortController,i=r.fetchImpl??fetch,c=r.reconnectDelayMs??oC;let d=nv(r.afterSequence),l=!1;return(async()=>{let p=0;for(;!s.signal.aborted;)try{const f=sC(e,s.signal,d),S=await i(f.url,f.init);if(P0(S),l=!0,p=0,await iC(S,b=>{const I=nv(b.sequence);I>0&&I<=d||(I>0&&(d=I),t(b))},a,s.signal),l=!1,s.signal.aborted)break;throw new Error("event stream ended")}catch(f){if(l=!1,s.signal.aborted)break;n(f),await lC(c(p),s.signal),p+=1}})().catch(()=>{}),{close(){s.abort()},isOpen(){return l}}}function nv(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function av(e,t,n){let a="message";const r=[];for(const s of e.split(`
|
|
7
|
+
`))s.startsWith(":")||(s.startsWith("event: ")&&(a=s.slice(7).trim()),s.startsWith("data: ")&&r.push(s.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||r.length===0))try{t(JSON.parse(r.join(`
|
|
8
|
+
`)))}catch{}}async function lC(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 dC extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function rv(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 sv=new WeakMap,ov=new WeakMap,_l=new WeakMap;let uC=0;async function L(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const r=(_l.get(e)??Promise.resolve()).catch(()=>{}).then(()=>iv(e,t,n));_l.set(e,r);try{return await r}finally{_l.get(e)===r&&_l.delete(e)}}return iv(e,t,n)}async function iv(e,t,n){const a=++uC;if(t==="/v1/preferences"&&typeof n?.body=="string"){const d=sv.get(e);if(!d)throw new Error("Reload settings before saving so changes can be checked against the current file.");n={...n,body:JSON.stringify({expectedRevision:d,...JSON.parse(n.body)})}}const r=new Headers(n?.headers);r.set("Content-Type","application/json"),r.set("Authorization",`Bearer ${e.token}`);const s=await fetch(`${e.serverUrl}${t}`,{...n,headers:r});if(!s.ok){const d=await s.json().catch(()=>({})),l=d&&typeof d=="object"&&"error"in d?String(d.error):s.statusText;throw new dC(l,s.status)}if(s.status===204)return;const i=await s.json(),c=i?.configuration?.rawRevision??(t==="/v1/preferences"?i?.rawRevision:void 0);return typeof c=="string"&&a>=(ov.get(e)??0)&&(sv.set(e,c),ov.set(e,a)),i}function p8(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function f8(e){return["openpond-terminal",`openpond-token.${pC(e.token)}`]}function mC(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const r=t.subarray(a,a+32768);n+=String.fromCharCode(...r)}return btoa(n)}function pC(e){return mC(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fC(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)}function hC(e,t,n){const a=h.useRef(n);a.current=n,h.useEffect(()=>{if(!e||!t)return;let r=!1,s=!1,i=null;const c=new Set,d=new Map,l=C=>`openpond:ponder-notification-delivery:${t}:${C}`;async function p(C){if(!(r||!i))try{const P=await L(e,"/v1/ponder/notifications");if(r||P.bindingId!==i||!P.items.some(_=>_.id===C)||(await L(e,`/v1/ponder/notifications/${encodeURIComponent(C)}/read`,{method:"POST",body:"{}"}),r))return;window.focus(),a.current?.()}catch{}}const f=window.openpond?.onPonderNotification?.(C=>{p(C.id)});async function S(){if(!(r||s)){s=!0;try{const[C,P]=await Promise.all([L(e,"/v1/ponder/settings"),L(e,"/v1/ponder/notifications")]);if(r||C.bindingId!==P.bindingId)return;if(i!==P.bindingId){i=P.bindingId,c.clear();try{const M=JSON.parse(localStorage.getItem(l(i))??"[]");if(Array.isArray(M))for(const A of M)typeof A=="string"&&c.add(A)}catch{}}const _=new Set(P.items.filter(M=>!M.readAt).map(M=>M.id));for(const[M,A]of d)_.has(M)||(A.close(),d.delete(M));if(localStorage.getItem("openpond:ponder-notifications")!=="on"||C.settings.notifications==="off")return;for(const M of P.items){if(r||M.readAt||c.has(M.id))continue;const A={id:M.id,title:M.title.slice(0,160),body:M.body.slice(0,500),ponder:!0};let T=!1;if(window.openpond?.notify)T=await window.openpond.notify(A);else if("Notification"in window&&Notification.permission==="granted"){const y=new Notification(A.title,{body:A.body,tag:A.id});y.onclick=()=>{y.close(),p(M.id)},d.set(M.id,y),T=!0}if(r)return;T&&c.add(M.id)}for(;c.size>500;)c.delete(c.values().next().value);try{localStorage.setItem(l(i),JSON.stringify([...c]))}catch{}}catch{}finally{s=!1}}}S();const b=window.setInterval(()=>{S()},1e4),I=()=>{S()};return window.addEventListener("ponder-settings-changed",I),()=>{r=!0,window.clearInterval(b),f?.(),window.removeEventListener("ponder-settings-changed",I);for(const C of d.values())C.close()}},[e,t])}var cv;function ie(e,t,n){function a(c,d){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:d,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,d);const l=i.prototype,p=Object.keys(l);for(let f=0;f<p.length;f++){const S=p[f];S in c||(c[S]=l[S].bind(c))}}const r=n?.Parent??Object;class s extends r{}Object.defineProperty(s,"name",{value:e});function i(c){var d;const l=n?.Parent?new s:this;a(l,c),(d=l._zod).deferred??(d.deferred=[]);for(const p of l._zod.deferred)p();return l}return Object.defineProperty(i,"init",{value:a}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class Yo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class T0 extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(cv=globalThis).__zod_globalConfig??(cv.__zod_globalConfig={});const Vf=globalThis.__zod_globalConfig;function Br(e){return Vf}function A0(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,r])=>t.indexOf(+a)===-1).map(([a,r])=>r)}function Up(e,t){return typeof t=="bigint"?t.toString():t}function Fd(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Kf(e){return e==null}function Wf(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function gC(e,t){const n=e/t,a=Math.round(n),r=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<r?0:n-a}const lv=Symbol("evaluating");function xt(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==lv)return a===void 0&&(a=lv,a=n()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function Qs(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function hs(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function dv(e){return JSON.stringify(e)}function vC(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const E0="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function yc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const bC=Fd(()=>{if(Vf.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function si(e){if(yc(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(yc(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function j0(e){return si(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const yC=new Set(["string","number","symbol"]),SC=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Vs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gs(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function ze(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 xC(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const kC={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 wC(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 s=hs(e._zod.def,{get shape(){const i={};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(i[c]=n.shape[c])}return Qs(this,"shape",i),i},checks:[]});return gs(e,s)}function IC(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 s=hs(e._zod.def,{get shape(){const i={...e._zod.def.shape};for(const c in t){if(!(c in n.shape))throw new Error(`Unrecognized key: "${c}"`);t[c]&&delete i[c]}return Qs(this,"shape",i),i},checks:[]});return gs(e,s)}function _C(e,t){if(!si(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const s=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=hs(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return Qs(this,"shape",s),s}});return gs(e,r)}function CC(e,t){if(!si(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=hs(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Qs(this,"shape",a),a}});return gs(e,n)}function RC(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=hs(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Qs(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return gs(e,n)}function PC(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=hs(t._zod.def,{get shape(){const c=t._zod.def.shape,d={...c};if(n)for(const l in n){if(!(l in c))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(d[l]=e?new e({type:"optional",innerType:c[l]}):c[l])}else for(const l in c)d[l]=e?new e({type:"optional",innerType:c[l]}):c[l];return Qs(this,"shape",d),d},checks:[]});return gs(t,i)}function TC(e,t,n){const a=hs(t._zod.def,{get shape(){const r=t._zod.def.shape,s={...r};if(n)for(const i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new e({type:"nonoptional",innerType:r[i]}))}else for(const i in r)s[i]=new e({type:"nonoptional",innerType:r[i]});return Qs(this,"shape",s),s}});return gs(t,a)}function zo(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 AC(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 Ho(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function Cl(e){return typeof e=="string"?e:e?.message}function Fr(e,t,n){const a=e.message?e.message:Cl(e.inst?._zod.def?.error?.(e))??Cl(t?.error?.(e))??Cl(n.customError?.(e))??Cl(n.localeError?.(e))??"Invalid input",{inst:r,continue:s,input:i,...c}=e;return c.path??(c.path=[]),c.message=a,t?.reportInput&&(c.input=i),c}function Gf(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Sc(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const M0=(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,Up,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},O0=ie("$ZodError",M0),$0=ie("$ZodError",M0,{Parent:Error});function EC(e,t=n=>n.message){const n={},a=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):a.push(t(r));return{formErrors:a,fieldErrors:n}}function jC(e,t=n=>n.message){const n={_errors:[]},a=(r,s=[])=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(c=>a({issues:c},[...s,...i.path]));else if(i.code==="invalid_key")a({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")a({issues:i.issues},[...s,...i.path]);else{const c=[...s,...i.path];if(c.length===0)n._errors.push(t(i));else{let d=n,l=0;for(;l<c.length;){const p=c[l];l===c.length-1?(d[p]=d[p]||{_errors:[]},d[p]._errors.push(t(i))):d[p]=d[p]||{_errors:[]},d=d[p],l++}}}};return a(e),n}const Zf=e=>(t,n,a,r)=>{const s=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Yo;if(i.issues.length){const c=new(r?.Err??e)(i.issues.map(d=>Fr(d,s,Br())));throw E0(c,r?.callee),c}return i.value},Jf=e=>async(t,n,a,r)=>{const s=a?{...a,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(r?.Err??e)(i.issues.map(d=>Fr(d,s,Br())));throw E0(c,r?.callee),c}return i.value},Vd=e=>(t,n,a)=>{const r=a?{...a,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},r);if(s instanceof Promise)throw new Yo;return s.issues.length?{success:!1,error:new(e??O0)(s.issues.map(i=>Fr(i,r,Br())))}:{success:!0,data:s.value}},MC=Vd($0),Kd=e=>async(t,n,a)=>{const r=a?{...a,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},r);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>Fr(i,r,Br())))}:{success:!0,data:s.value}},OC=Kd($0),$C=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Zf(e)(t,n,r)},NC=e=>(t,n,a)=>Zf(e)(t,n,a),DC=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Jf(e)(t,n,r)},LC=e=>async(t,n,a)=>Jf(e)(t,n,a),zC=e=>(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Vd(e)(t,n,r)},HC=e=>(t,n,a)=>Vd(e)(t,n,a),UC=e=>async(t,n,a)=>{const r=a?{...a,direction:"backward"}:{direction:"backward"};return Kd(e)(t,n,r)},qC=e=>async(t,n,a)=>Kd(e)(t,n,a),BC=/^[cC][0-9a-z]{6,}$/,FC=/^[0-9a-z]+$/,VC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,KC=/^[0-9a-vA-V]{20}$/,WC=/^[A-Za-z0-9]{27}$/,GC=/^[a-zA-Z0-9_-]{21}$/,ZC=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,JC=/^([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})$/,uv=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)$/,QC=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,YC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function XC(){return new RegExp(YC,"u")}const eR=/^(?:(?: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])$/,tR=/^(([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}|:))$/,nR=/^((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])$/,aR=/^(([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])$/,rR=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,N0=/^[A-Za-z0-9_-]*$/,sR=/^https?$/,oR=/^\+[1-9]\d{6,14}$/,D0="(?:(?:\\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])))",iR=new RegExp(`^${D0}$`);function L0(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 cR(e){return new RegExp(`^${L0(e)}$`)}function lR(e){const t=L0({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(`^${D0}T(?:${a})$`)}const dR=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},uR=/^-?\d+$/,z0=/^-?\d+(?:\.\d+)?$/,mR=/^(?:true|false)$/i,pR=/^null$/i,fR=/^[^A-Z]*$/,hR=/^[^a-z]*$/,sa=ie("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),H0={number:"number",bigint:"bigint",object:"date"},U0=ie("$ZodCheckLessThan",(e,t)=>{sa.init(e,t);const n=H0[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,s=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?r.maximum=t.value:r.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})}}),q0=ie("$ZodCheckGreaterThan",(e,t)=>{sa.init(e,t);const n=H0[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,s=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?r.minimum=t.value:r.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})}}),gR=ie("$ZodCheckMultipleOf",(e,t)=>{sa.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):gC(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})}}),vR=ie("$ZodCheckNumberFormat",(e,t)=>{sa.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[r,s]=kC[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=r,c.maximum=s,n&&(c.pattern=uR)}),e._zod.check=i=>{const c=i.value;if(n){if(!Number.isInteger(c)){i.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.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}):i.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<r&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>s&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),bR=ie("$ZodCheckMaxLength",(e,t)=>{var n;sa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Kf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const r=a.value;if(r.length<=t.maximum)return;const i=Gf(r);a.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),yR=ie("$ZodCheckMinLength",(e,t)=>{var n;sa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Kf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const r=a.value;if(r.length>=t.minimum)return;const i=Gf(r);a.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),SR=ie("$ZodCheckLengthEquals",(e,t)=>{var n;sa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!Kf(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=a=>{const r=a.value,s=r.length;if(s===t.length)return;const i=Gf(r),c=s>t.length;a.issues.push({origin:i,...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})}}),Wd=ie("$ZodCheckStringFormat",(e,t)=>{var n,a;sa.init(e,t),e._zod.onattach.push(r=>{const s=r._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),xR=ie("$ZodCheckRegex",(e,t)=>{Wd.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})}}),kR=ie("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=fR),Wd.init(e,t)}),wR=ie("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=hR),Wd.init(e,t)}),IR=ie("$ZodCheckIncludes",(e,t)=>{sa.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(r=>{const s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),_R=ie("$ZodCheckStartsWith",(e,t)=>{sa.init(e,t);const n=new RegExp(`^${Vs(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.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})}}),CR=ie("$ZodCheckEndsWith",(e,t)=>{sa.init(e,t);const n=new RegExp(`.*${Vs(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.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})}}),RR=ie("$ZodCheckOverwrite",(e,t)=>{sa.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class PR{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(`
|
|
9
|
+
`).filter(i=>i),r=Math.min(...a.map(i=>i.length-i.trimStart().length)),s=a.map(i=>i.slice(r)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,r.join(`
|
|
10
|
+
`))}}const TR={major:4,minor:4,patch:3},Zt=ie("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=TR;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const r of a)for(const s of r._zod.onattach)s(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=(i,c,d)=>{let l=zo(i),p;for(const f of c){if(f._zod.def.when){if(AC(i)||!f._zod.def.when(i))continue}else if(l)continue;const S=i.issues.length,b=f._zod.check(i);if(b instanceof Promise&&d?.async===!1)throw new Yo;if(p||b instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await b,i.issues.length!==S&&(l||(l=zo(i,S)))});else{if(i.issues.length===S)continue;l||(l=zo(i,S))}}return p?p.then(()=>i):i},s=(i,c,d)=>{if(zo(i))return i.aborted=!0,i;const l=r(c,a,d);if(l instanceof Promise){if(d.async===!1)throw new Yo;return l.then(p=>e._zod.parse(p,d))}return e._zod.parse(l,d)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const l=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(p=>s(p,i,c)):s(l,i,c)}const d=e._zod.parse(i,c);if(d instanceof Promise){if(c.async===!1)throw new Yo;return d.then(l=>r(l,a,c))}return r(d,a,c)}}xt(e,"~standard",()=>({validate:r=>{try{const s=MC(e,r);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return OC(e,r).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Qf=ie("$ZodString",(e,t)=>{Zt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??dR(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}}),nn=ie("$ZodStringFormat",(e,t)=>{Wd.init(e,t),Qf.init(e,t)}),AR=ie("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=JC),nn.init(e,t)}),ER=ie("$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=uv(a))}else t.pattern??(t.pattern=uv());nn.init(e,t)}),jR=ie("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=QC),nn.init(e,t)}),MR=ie("$ZodURL",(e,t)=>{nn.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===sR.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 r=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.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(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.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=r.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),OR=ie("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=XC()),nn.init(e,t)}),$R=ie("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=GC),nn.init(e,t)}),NR=ie("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=BC),nn.init(e,t)}),DR=ie("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=FC),nn.init(e,t)}),LR=ie("$ZodULID",(e,t)=>{t.pattern??(t.pattern=VC),nn.init(e,t)}),zR=ie("$ZodXID",(e,t)=>{t.pattern??(t.pattern=KC),nn.init(e,t)}),HR=ie("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=WC),nn.init(e,t)}),UR=ie("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=lR(t)),nn.init(e,t)}),qR=ie("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=iR),nn.init(e,t)}),BR=ie("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=cR(t)),nn.init(e,t)}),FR=ie("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ZC),nn.init(e,t)}),VR=ie("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=eR),nn.init(e,t),e._zod.bag.format="ipv4"}),KR=ie("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=tR),nn.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})}}}),WR=ie("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=nR),nn.init(e,t)}),GR=ie("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=aR),nn.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[r,s]=a;if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function B0(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const ZR=ie("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rR),nn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{B0(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function JR(e){if(!N0.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return B0(n)}const QR=ie("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=N0),nn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{JR(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),YR=ie("$ZodE164",(e,t)=>{t.pattern??(t.pattern=oR),nn.init(e,t)});function XR(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const r=JSON.parse(atob(a));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const eP=ie("$ZodJWT",(e,t)=>{nn.init(e,t),e._zod.check=n=>{XR(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),F0=ie("$ZodNumber",(e,t)=>{Zt.init(e,t),e._zod.pattern=e._zod.bag.pattern??z0,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const s=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...s?{received:s}:{}}),n}}),tP=ie("$ZodNumberFormat",(e,t)=>{vR.init(e,t),F0.init(e,t)}),nP=ie("$ZodBoolean",(e,t)=>{Zt.init(e,t),e._zod.pattern=mR,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),aP=ie("$ZodNull",(e,t)=>{Zt.init(e,t),e._zod.pattern=pR,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),rP=ie("$ZodUnknown",(e,t)=>{Zt.init(e,t),e._zod.parse=n=>n}),sP=ie("$ZodNever",(e,t)=>{Zt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function mv(e,t,n){e.issues.length&&t.issues.push(...Ho(n,e.issues)),t.value[n]=e.value}const oP=ie("$ZodArray",(e,t)=>{Zt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const s=[];for(let i=0;i<r.length;i++){const c=r[i],d=t.element._zod.run({value:c,issues:[]},a);d instanceof Promise?s.push(d.then(l=>mv(l,n,i))):mv(d,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function yd(e,t,n,a,r,s){const i=n in a;if(e.issues.length){if(r&&s&&!i)return;t.issues.push(...Ho(n,e.issues))}if(!i&&!r){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?i&&(t.value[n]=void 0):t.value[n]=e.value}function V0(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=xC(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function K0(e,t,n,a,r,s){const i=[],c=r.keySet,d=r.catchall._zod,l=d.def.type,p=d.optin==="optional",f=d.optout==="optional";for(const S in t){if(S==="__proto__"||c.has(S))continue;if(l==="never"){i.push(S);continue}const b=d.run({value:t[S],issues:[]},a);b instanceof Promise?e.push(b.then(I=>yd(I,n,S,t,p,f))):yd(b,n,S,t,p,f)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}const iP=ie("$ZodObject",(e,t)=>{if(Zt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const d={...c};return Object.defineProperty(t,"shape",{value:d}),d}})}const a=Fd(()=>V0(t));xt(e._zod,"propValues",()=>{const c=t.shape,d={};for(const l in c){const p=c[l]._zod;if(p.values){d[l]??(d[l]=new Set);for(const f of p.values)d[l].add(f)}}return d});const r=yc,s=t.catchall;let i;e._zod.parse=(c,d)=>{i??(i=a.value);const l=c.value;if(!r(l))return c.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),c;c.value={};const p=[],f=i.shape;for(const S of i.keys){const b=f[S],I=b._zod.optin==="optional",C=b._zod.optout==="optional",P=b._zod.run({value:l[S],issues:[]},d);P instanceof Promise?p.push(P.then(_=>yd(_,c,S,l,I,C))):yd(P,c,S,l,I,C)}return s?K0(p,l,c,d,a.value,e):p.length?Promise.all(p).then(()=>c):c}}),cP=ie("$ZodObjectJIT",(e,t)=>{iP.init(e,t);const n=e._zod.parse,a=Fd(()=>V0(t)),r=S=>{const b=new PR(["shape","payload","ctx"]),I=a.value,C=A=>{const T=dv(A);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};b.write("const input = payload.value;");const P=Object.create(null);let _=0;for(const A of I.keys)P[A]=`key_${_++}`;b.write("const newResult = {};");for(const A of I.keys){const T=P[A],y=dv(A),w=S[A],R=w?._zod?.optin==="optional",O=w?._zod?.optout==="optional";b.write(`const ${T} = ${C(A)};`),R&&O?b.write(`
|
|
11
|
+
if (${T}.issues.length) {
|
|
12
|
+
if (${y} in input) {
|
|
13
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
14
|
+
...iss,
|
|
15
|
+
path: iss.path ? [${y}, ...iss.path] : [${y}]
|
|
16
|
+
})));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (${T}.value === undefined) {
|
|
21
|
+
if (${y} in input) {
|
|
22
|
+
newResult[${y}] = undefined;
|
|
23
|
+
}
|
|
24
|
+
} else {
|
|
25
|
+
newResult[${y}] = ${T}.value;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
`):R?b.write(`
|
|
29
|
+
if (${T}.issues.length) {
|
|
30
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
31
|
+
...iss,
|
|
32
|
+
path: iss.path ? [${y}, ...iss.path] : [${y}]
|
|
33
|
+
})));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (${T}.value === undefined) {
|
|
37
|
+
if (${y} in input) {
|
|
38
|
+
newResult[${y}] = undefined;
|
|
39
|
+
}
|
|
40
|
+
} else {
|
|
41
|
+
newResult[${y}] = ${T}.value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
`):b.write(`
|
|
45
|
+
const ${T}_present = ${y} in input;
|
|
46
|
+
if (${T}.issues.length) {
|
|
47
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
48
|
+
...iss,
|
|
49
|
+
path: iss.path ? [${y}, ...iss.path] : [${y}]
|
|
50
|
+
})));
|
|
51
|
+
}
|
|
52
|
+
if (!${T}_present && !${T}.issues.length) {
|
|
53
|
+
payload.issues.push({
|
|
54
|
+
code: "invalid_type",
|
|
55
|
+
expected: "nonoptional",
|
|
56
|
+
input: undefined,
|
|
57
|
+
path: [${y}]
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (${T}_present) {
|
|
62
|
+
if (${T}.value === undefined) {
|
|
63
|
+
newResult[${y}] = undefined;
|
|
64
|
+
} else {
|
|
65
|
+
newResult[${y}] = ${T}.value;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
`)}b.write("payload.value = newResult;"),b.write("return payload;");const M=b.compile();return(A,T)=>M(S,A,T)};let s;const i=yc,c=!Vf.jitless,l=c&&bC.value,p=t.catchall;let f;e._zod.parse=(S,b)=>{f??(f=a.value);const I=S.value;return i(I)?c&&l&&b?.async===!1&&b.jitless!==!0?(s||(s=r(t.shape)),S=s(S,b),p?K0([],I,S,b,f,e):S):n(S,b):(S.issues.push({expected:"object",code:"invalid_type",input:I,inst:e}),S)}});function pv(e,t,n,a){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const r=e.filter(s=>!zo(s));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(i=>Fr(i,a,Br())))}),t)}const W0=ie("$ZodUnion",(e,t)=>{Zt.init(e,t),xt(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),xt(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),xt(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),xt(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(r=>r._zod.pattern);return new RegExp(`^(${a.map(r=>Wf(r.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,r)=>{if(n)return n(a,r);let s=!1;const i=[];for(const c of t.options){const d=c._zod.run({value:a.value,issues:[]},r);if(d instanceof Promise)i.push(d),s=!0;else{if(d.issues.length===0)return d;i.push(d)}}return s?Promise.all(i).then(c=>pv(c,a,e,r)):pv(i,a,e,r)}}),lP=ie("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,W0.init(e,t);const n=e._zod.parse;xt(e._zod,"propValues",()=>{const r={};for(const s of t.options){const i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[c,d]of Object.entries(i)){r[c]||(r[c]=new Set);for(const l of d)r[c].add(l)}}return r});const a=Fd(()=>{const r=t.options,s=new Map;for(const i of r){const c=i._zod.propValues?.[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const d of c){if(s.has(d))throw new Error(`Duplicate discriminator value "${String(d)}"`);s.set(d,i)}}return s});e._zod.parse=(r,s)=>{const i=r.value;if(!yc(i))return r.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),r;const c=a.value.get(i?.[t.discriminator]);return c?c._zod.run(r,s):t.unionFallback||s.direction==="backward"?n(r,s):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(a.value.keys()),input:i,path:[t.discriminator],inst:e}),r)}}),dP=ie("$ZodIntersection",(e,t)=>{Zt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value,s=t.left._zod.run({value:r,issues:[]},a),i=t.right._zod.run({value:r,issues:[]},a);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([d,l])=>fv(n,d,l)):fv(n,s,i)}});function qp(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(si(e)&&si(t)){const n=Object.keys(t),a=Object.keys(e).filter(s=>n.indexOf(s)!==-1),r={...e,...t};for(const s of a){const i=qp(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};r[s]=i.data}return{valid:!0,data:r}}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 r=e[a],s=t[a],i=qp(r,s);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function fv(e,t,n){const a=new Map;let r;for(const c of t.issues)if(c.code==="unrecognized_keys"){r??(r=c);for(const d of c.keys)a.has(d)||a.set(d,{}),a.get(d).l=!0}else e.issues.push(c);for(const c of n.issues)if(c.code==="unrecognized_keys")for(const d of c.keys)a.has(d)||a.set(d,{}),a.get(d).r=!0;else e.issues.push(c);const s=[...a].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(s.length&&r&&e.issues.push({...r,keys:s}),zo(e))return e;const i=qp(t.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return e.value=i.data,e}const uP=ie("$ZodRecord",(e,t)=>{Zt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;if(!si(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const s=[],i=t.keyType._zod.values;if(i){n.value={};const c=new Set;for(const l of i)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){c.add(typeof l=="number"?l.toString():l);const p=t.keyType._zod.run({value:l,issues:[]},a);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(b=>Fr(b,a,Br())),input:l,path:[l],inst:e});continue}const f=p.value,S=t.valueType._zod.run({value:r[l],issues:[]},a);S instanceof Promise?s.push(S.then(b=>{b.issues.length&&n.issues.push(...Ho(l,b.issues)),n.value[f]=b.value})):(S.issues.length&&n.issues.push(...Ho(l,S.issues)),n.value[f]=S.value)}let d;for(const l in r)c.has(l)||(d=d??[],d.push(l));d&&d.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:d})}else{n.value={};for(const c of Reflect.ownKeys(r)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(r,c))continue;let d=t.keyType._zod.run({value:c,issues:[]},a);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&z0.test(c)&&d.issues.length){const f=t.keyType._zod.run({value:Number(c),issues:[]},a);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");f.issues.length===0&&(d=f)}if(d.issues.length){t.mode==="loose"?n.value[c]=r[c]:n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(f=>Fr(f,a,Br())),input:c,path:[c],inst:e});continue}const p=t.valueType._zod.run({value:r[c],issues:[]},a);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&n.issues.push(...Ho(c,f.issues)),n.value[d.value]=f.value})):(p.issues.length&&n.issues.push(...Ho(c,p.issues)),n.value[d.value]=p.value)}}return s.length?Promise.all(s).then(()=>n):n}}),mP=ie("$ZodEnum",(e,t)=>{Zt.init(e,t);const n=A0(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(r=>yC.has(typeof r)).map(r=>typeof r=="string"?Vs(r):r.toString()).join("|")})$`),e._zod.parse=(r,s)=>{const i=r.value;return a.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:e}),r}}),pP=ie("$ZodLiteral",(e,t)=>{if(Zt.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,r)=>{const s=a.value;return n.has(s)||a.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),a}}),fP=ie("$ZodTransform",(e,t)=>{Zt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new T0(e.constructor.name);const r=t.transform(n.value,n);if(a.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(n.value=i,n.fallback=!0,n));if(r instanceof Promise)throw new Yo;return n.value=r,n.fallback=!0,n}});function hv(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const G0=ie("$ZodOptional",(e,t)=>{Zt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",xt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),xt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Wf(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const r=n.value,s=t.innerType._zod.run(n,a);return s instanceof Promise?s.then(i=>hv(i,r)):hv(s,r)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),hP=ie("$ZodExactOptional",(e,t)=>{G0.init(e,t),xt(e._zod,"values",()=>t.innerType._zod.values),xt(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),gP=ie("$ZodNullable",(e,t)=>{Zt.init(e,t),xt(e._zod,"optin",()=>t.innerType._zod.optin),xt(e._zod,"optout",()=>t.innerType._zod.optout),xt(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Wf(n.source)}|null)$`):void 0}),xt(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)}),vP=ie("$ZodDefault",(e,t)=>{Zt.init(e,t),e._zod.optin="optional",xt(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 r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(s=>gv(s,t)):gv(r,t)}});function gv(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const bP=ie("$ZodPrefault",(e,t)=>{Zt.init(e,t),e._zod.optin="optional",xt(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))}),yP=ie("$ZodNonOptional",(e,t)=>{Zt.init(e,t),xt(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 r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(s=>vv(s,e)):vv(r,e)}});function vv(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 SP=ie("$ZodCatch",(e,t)=>{Zt.init(e,t),e._zod.optin="optional",xt(e._zod,"optout",()=>t.innerType._zod.optout),xt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(i=>Fr(i,a,Br()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(s=>Fr(s,a,Br()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),Z0=ie("$ZodPipe",(e,t)=>{Zt.init(e,t),xt(e._zod,"values",()=>t.in._zod.values),xt(e._zod,"optin",()=>t.in._zod.optin),xt(e._zod,"optout",()=>t.out._zod.optout),xt(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const s=t.out._zod.run(n,a);return s instanceof Promise?s.then(i=>Rl(i,t.in,a)):Rl(s,t.in,a)}const r=t.in._zod.run(n,a);return r instanceof Promise?r.then(s=>Rl(s,t.out,a)):Rl(r,t.out,a)}});function Rl(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 xP=ie("$ZodPreprocess",(e,t)=>{Z0.init(e,t)}),kP=ie("$ZodReadonly",(e,t)=>{Zt.init(e,t),xt(e._zod,"propValues",()=>t.innerType._zod.propValues),xt(e._zod,"values",()=>t.innerType._zod.values),xt(e._zod,"optin",()=>t.innerType?._zod?.optin),xt(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(bv):bv(r)}});function bv(e){return e.value=Object.freeze(e.value),e}const wP=ie("$ZodTemplateLiteral",(e,t)=>{Zt.init(e,t);const n=[];for(const a of t.parts)if(typeof a=="object"&&a!==null){if(!a._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...a._zod.traits].shift()}`);const r=a._zod.pattern instanceof RegExp?a._zod.pattern.source:a._zod.pattern;if(!r)throw new Error(`Invalid template literal part: ${a._zod.traits}`);const s=r.startsWith("^")?1:0,i=r.endsWith("$")?r.length-1:r.length;n.push(r.slice(s,i))}else if(a===null||SC.has(typeof a))n.push(Vs(`${a}`));else throw new Error(`Invalid template literal part: ${a}`);e._zod.pattern=new RegExp(`^${n.join("")}$`),e._zod.parse=(a,r)=>typeof a.value!="string"?(a.issues.push({input:a.value,inst:e,expected:"string",code:"invalid_type"}),a):(e._zod.pattern.lastIndex=0,e._zod.pattern.test(a.value)||a.issues.push({input:a.value,inst:e,code:"invalid_format",format:t.format??"template_literal",pattern:e._zod.pattern.source}),a)}),IP=ie("$ZodLazy",(e,t)=>{Zt.init(e,t),xt(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),xt(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),xt(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),xt(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),xt(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),_P=ie("$ZodCustom",(e,t)=>{sa.init(e,t),Zt.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,r=t.fn(a);if(r instanceof Promise)return r.then(s=>yv(s,n,a,e));yv(r,n,a,e)}});function yv(e,t,n,a){if(!e){const r={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(r.params=a._zod.def.params),t.issues.push(Sc(r))}}var Sv;class CP{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 r={...a,...this._map.get(t)};return Object.keys(r).length?r:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function RP(){return new CP}(Sv=globalThis).__zod_globalRegistry??(Sv.__zod_globalRegistry=RP());const tc=globalThis.__zod_globalRegistry;function PP(e,t){return new e({type:"string",...ze(t)})}function TP(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...ze(t)})}function xv(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...ze(t)})}function J0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...ze(t)})}function AP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ze(t)})}function EP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ze(t)})}function jP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ze(t)})}function MP(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...ze(t)})}function OP(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...ze(t)})}function $P(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...ze(t)})}function NP(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...ze(t)})}function DP(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...ze(t)})}function LP(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...ze(t)})}function zP(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...ze(t)})}function HP(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...ze(t)})}function UP(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...ze(t)})}function qP(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...ze(t)})}function BP(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ze(t)})}function FP(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ze(t)})}function VP(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...ze(t)})}function KP(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...ze(t)})}function WP(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...ze(t)})}function GP(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...ze(t)})}function ZP(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ze(t)})}function JP(e,t){return new e({type:"string",format:"date",check:"string_format",...ze(t)})}function QP(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...ze(t)})}function YP(e,t){return new e({type:"string",format:"duration",check:"string_format",...ze(t)})}function XP(e,t){return new e({type:"number",checks:[],...ze(t)})}function h8(e,t){return new e({type:"number",coerce:!0,checks:[],...ze(t)})}function eT(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...ze(t)})}function tT(e,t){return new e({type:"boolean",...ze(t)})}function nT(e,t){return new e({type:"null",...ze(t)})}function aT(e){return new e({type:"unknown"})}function rT(e,t){return new e({type:"never",...ze(t)})}function kv(e,t){return new U0({check:"less_than",...ze(t),value:e,inclusive:!1})}function Um(e,t){return new U0({check:"less_than",...ze(t),value:e,inclusive:!0})}function wv(e,t){return new q0({check:"greater_than",...ze(t),value:e,inclusive:!1})}function qm(e,t){return new q0({check:"greater_than",...ze(t),value:e,inclusive:!0})}function Iv(e,t){return new gR({check:"multiple_of",...ze(t),value:e})}function Q0(e,t){return new bR({check:"max_length",...ze(t),maximum:e})}function Sd(e,t){return new yR({check:"min_length",...ze(t),minimum:e})}function Y0(e,t){return new SR({check:"length_equals",...ze(t),length:e})}function sT(e,t){return new xR({check:"string_format",format:"regex",...ze(t),pattern:e})}function oT(e){return new kR({check:"string_format",format:"lowercase",...ze(e)})}function iT(e){return new wR({check:"string_format",format:"uppercase",...ze(e)})}function cT(e,t){return new IR({check:"string_format",format:"includes",...ze(t),includes:e})}function lT(e,t){return new _R({check:"string_format",format:"starts_with",...ze(t),prefix:e})}function dT(e,t){return new CR({check:"string_format",format:"ends_with",...ze(t),suffix:e})}function bi(e){return new RR({check:"overwrite",tx:e})}function uT(e){return bi(t=>t.normalize(e))}function mT(){return bi(e=>e.trim())}function pT(){return bi(e=>e.toLowerCase())}function fT(){return bi(e=>e.toUpperCase())}function hT(){return bi(e=>vC(e))}function gT(e,t,n){return new e({type:"array",element:t,...ze(n)})}function vT(e,t,n){const a=ze(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function bT(e,t,n){return new e({type:"custom",check:"custom",fn:t,...ze(n)})}function yT(e,t){const n=ST(a=>(a.addIssue=r=>{if(typeof r=="string")a.issues.push(Sc(r,a.value,n._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=a.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),a.issues.push(Sc(s))}},e(a.value,a)),t);return n}function ST(e,t){const n=new sa({check:"custom",...ze(t)});return n._zod.check=e,n}function X0(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??tc,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 cn(e,t,n={path:[],schemaPath:[]}){var a;const r=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const i={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,i);const c=e._zod.toJSONSchema?.();if(c)i.schema=c;else{const p={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,p);else{const S=i.schema,b=t.processors[r.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);b(e,t,S,p)}const f=e._zod.parent;f&&(i.ref||(i.ref=f),cn(f,t,p),t.seen.get(f).isParent=!0)}const d=t.metadataRegistry.get(e);return d&&Object.assign(i.schema,d),t.io==="input"&&Vn(e)&&(delete i.schema.examples,delete i.schema.default),t.io==="input"&&"_prefault"in i.schema&&((a=i.schema).default??(a.default=i.schema._prefault)),delete i.schema._prefault,t.seen.get(e).schema}function eS(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 i of e.seen.entries()){const c=e.metadataRegistry.get(i[0])?.id;if(c){const d=a.get(c);if(d&&d!==i[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,i[0])}}const r=i=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const f=e.external.registry.get(i[0])?.id,S=e.external.uri??(I=>I);if(f)return{ref:S(f)};const b=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=b,{defId:b,ref:`${S("__shared")}#/${c}/${b}`}}if(i[1]===n)return{ref:"#"};const l=`#/${c}/`,p=i[1].schema.id??`__schema${e.counter++}`;return{defId:p,ref:l+p}},s=i=>{if(i[1].schema.$ref)return;const c=i[1],{ref:d,defId:l}=r(i);c.def={...c.schema},l&&(c.defId=l);const p=c.schema;for(const f in p)delete p[f];p.$ref=d};if(e.cycles==="throw")for(const i of e.seen.entries()){const c=i[1];if(c.cycle)throw new Error(`Cycle detected: #/${c.cycle?.join("/")}/<root>
|
|
70
|
+
|
|
71
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const i of e.seen.entries()){const c=i[1];if(t===i[0]){s(i);continue}if(e.external){const l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(c.cycle){s(i);continue}if(c.count>1&&e.reused==="ref"){s(i);continue}}}function tS(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 d=e.seen.get(c);if(d.ref===null)return;const l=d.def??d.schema,p={...l},f=d.ref;if(d.ref=null,f){a(f);const b=e.seen.get(f),I=b.schema;if(I.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(I)):Object.assign(l,I),Object.assign(l,p),c._zod.parent===f)for(const P in l)P==="$ref"||P==="allOf"||P in p||delete l[P];if(I.$ref&&b.def)for(const P in l)P==="$ref"||P==="allOf"||P in b.def&&JSON.stringify(l[P])===JSON.stringify(b.def[P])&&delete l[P]}const S=c._zod.parent;if(S&&S!==f){a(S);const b=e.seen.get(S);if(b?.schema.$ref&&(l.$ref=b.schema.$ref,b.def))for(const I in l)I==="$ref"||I==="allOf"||I in b.def&&JSON.stringify(l[I])===JSON.stringify(b.def[I])&&delete l[I]}e.override({zodSchema:c,jsonSchema:l,path:d.path??[]})};for(const c of[...e.seen.entries()].reverse())a(c[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$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");r.$id=e.external.uri(c)}Object.assign(r,n.def??n.schema);const s=e.metadataRegistry.get(t)?.id;s!==void 0&&r.id===s&&delete r.id;const i=e.external?.defs??{};for(const c of e.seen.entries()){const d=c[1];d.def&&d.defId&&(d.def.id===d.defId&&delete d.def.id,i[d.defId]=d.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const c=JSON.parse(JSON.stringify(r));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:xd(t,"input",e.processors),output:xd(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function Vn(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 Vn(a.element,n);if(a.type==="set")return Vn(a.valueType,n);if(a.type==="lazy")return Vn(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 Vn(a.innerType,n);if(a.type==="intersection")return Vn(a.left,n)||Vn(a.right,n);if(a.type==="record"||a.type==="map")return Vn(a.keyType,n)||Vn(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Vn(a.in,n)||Vn(a.out,n);if(a.type==="object"){for(const r in a.shape)if(Vn(a.shape[r],n))return!0;return!1}if(a.type==="union"){for(const r of a.options)if(Vn(r,n))return!0;return!1}if(a.type==="tuple"){for(const r of a.items)if(Vn(r,n))return!0;return!!(a.rest&&Vn(a.rest,n))}return!1}const xT=(e,t={})=>n=>{const a=X0({...n,processors:t});return cn(e,a),eS(a,e),tS(a,e)},xd=(e,t,n={})=>a=>{const{libraryOptions:r,target:s}=a??{},i=X0({...r??{},target:s,io:t,processors:n});return cn(e,i),eS(i,e),tS(i,e)},kT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},wT=(e,t,n,a)=>{const r=n;r.type="string";const{minimum:s,maximum:i,format:c,patterns:d,contentEncoding:l}=e._zod.bag;if(typeof s=="number"&&(r.minLength=s),typeof i=="number"&&(r.maxLength=i),c&&(r.format=kT[c]??c,r.format===""&&delete r.format,c==="time"&&delete r.format),l&&(r.contentEncoding=l),d&&d.size>0){const p=[...d];p.length===1?r.pattern=p[0].source:p.length>1&&(r.allOf=[...p.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},IT=(e,t,n,a)=>{const r=n,{minimum:s,maximum:i,format:c,multipleOf:d,exclusiveMaximum:l,exclusiveMinimum:p}=e._zod.bag;typeof c=="string"&&c.includes("int")?r.type="integer":r.type="number";const f=typeof p=="number"&&p>=(s??Number.NEGATIVE_INFINITY),S=typeof l=="number"&&l<=(i??Number.POSITIVE_INFINITY),b=t.target==="draft-04"||t.target==="openapi-3.0";f?b?(r.minimum=p,r.exclusiveMinimum=!0):r.exclusiveMinimum=p:typeof s=="number"&&(r.minimum=s),S?b?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l:typeof i=="number"&&(r.maximum=i),typeof d=="number"&&(r.multipleOf=d)},_T=(e,t,n,a)=>{n.type="boolean"},CT=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},RT=(e,t,n,a)=>{n.not={}},PT=(e,t,n,a)=>{},TT=(e,t,n,a)=>{const r=e._zod.def,s=A0(r.entries);s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),n.enum=s},AT=(e,t,n,a)=>{const r=e._zod.def,s=[];for(const i of r.values)if(i===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){const i=s[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else s.every(i=>typeof i=="number")&&(n.type="number"),s.every(i=>typeof i=="string")&&(n.type="string"),s.every(i=>typeof i=="boolean")&&(n.type="boolean"),s.every(i=>i===null)&&(n.type="null"),n.enum=s},ET=(e,t,n,a)=>{const r=n,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=s.source},jT=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},MT=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},OT=(e,t,n,a)=>{const r=n,s=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(r.minItems=i),typeof c=="number"&&(r.maxItems=c),r.type="array",r.items=cn(s.element,t,{...a,path:[...a.path,"items"]})},$T=(e,t,n,a)=>{const r=n,s=e._zod.def;r.type="object",r.properties={};const i=s.shape;for(const l in i)r.properties[l]=cn(i[l],t,{...a,path:[...a.path,"properties",l]});const c=new Set(Object.keys(i)),d=new Set([...c].filter(l=>{const p=s.shape[l]._zod;return t.io==="input"?p.optin===void 0:p.optout===void 0}));d.size>0&&(r.required=Array.from(d)),s.catchall?._zod.def.type==="never"?r.additionalProperties=!1:s.catchall?s.catchall&&(r.additionalProperties=cn(s.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},NT=(e,t,n,a)=>{const r=e._zod.def,s=r.inclusive===!1,i=r.options.map((c,d)=>cn(c,t,{...a,path:[...a.path,s?"oneOf":"anyOf",d]}));s?n.oneOf=i:n.anyOf=i},DT=(e,t,n,a)=>{const r=e._zod.def,s=cn(r.left,t,{...a,path:[...a.path,"allOf",0]}),i=cn(r.right,t,{...a,path:[...a.path,"allOf",1]}),c=l=>"allOf"in l&&Object.keys(l).length===1,d=[...c(s)?s.allOf:[s],...c(i)?i.allOf:[i]];n.allOf=d},LT=(e,t,n,a)=>{const r=n,s=e._zod.def;r.type="object";const i=s.keyType,d=i._zod.bag?.patterns;if(s.mode==="loose"&&d&&d.size>0){const p=cn(s.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});r.patternProperties={};for(const f of d)r.patternProperties[f.source]=p}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=cn(s.keyType,t,{...a,path:[...a.path,"propertyNames"]})),r.additionalProperties=cn(s.valueType,t,{...a,path:[...a.path,"additionalProperties"]});const l=i._zod.values;if(l){const p=[...l].filter(f=>typeof f=="string"||typeof f=="number");p.length>0&&(r.required=p)}},zT=(e,t,n,a)=>{const r=e._zod.def,s=cn(r.innerType,t,a),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=r.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},HT=(e,t,n,a)=>{const r=e._zod.def;cn(r.innerType,t,a);const s=t.seen.get(e);s.ref=r.innerType},UT=(e,t,n,a)=>{const r=e._zod.def;cn(r.innerType,t,a);const s=t.seen.get(e);s.ref=r.innerType,n.default=JSON.parse(JSON.stringify(r.defaultValue))},qT=(e,t,n,a)=>{const r=e._zod.def;cn(r.innerType,t,a);const s=t.seen.get(e);s.ref=r.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},BT=(e,t,n,a)=>{const r=e._zod.def;cn(r.innerType,t,a);const s=t.seen.get(e);s.ref=r.innerType;let i;try{i=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},FT=(e,t,n,a)=>{const r=e._zod.def,s=r.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?r.out:r.in:r.out;cn(i,t,a);const c=t.seen.get(e);c.ref=i},VT=(e,t,n,a)=>{const r=e._zod.def;cn(r.innerType,t,a);const s=t.seen.get(e);s.ref=r.innerType,n.readOnly=!0},nS=(e,t,n,a)=>{const r=e._zod.def;cn(r.innerType,t,a);const s=t.seen.get(e);s.ref=r.innerType},KT=(e,t,n,a)=>{const r=e._zod.innerType;cn(r,t,a);const s=t.seen.get(e);s.ref=r},WT=ie("ZodISODateTime",(e,t)=>{UR.init(e,t),an.init(e,t)});function na(e){return ZP(WT,e)}const GT=ie("ZodISODate",(e,t)=>{qR.init(e,t),an.init(e,t)});function ZT(e){return JP(GT,e)}const JT=ie("ZodISOTime",(e,t)=>{BR.init(e,t),an.init(e,t)});function QT(e){return QP(JT,e)}const YT=ie("ZodISODuration",(e,t)=>{FR.init(e,t),an.init(e,t)});function XT(e){return YP(YT,e)}const aS=(e,t)=>{O0.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>jC(e,n)},flatten:{value:n=>EC(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Up,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Up,2)}},isEmpty:{get(){return e.issues.length===0}}})},eA=ie("ZodError",aS),Pa=ie("ZodError",aS,{Parent:Error}),tA=Zf(Pa),nA=Jf(Pa),aA=Vd(Pa),rA=Kd(Pa),sA=$C(Pa),oA=NC(Pa),iA=DC(Pa),cA=LC(Pa),lA=zC(Pa),dA=HC(Pa),uA=UC(Pa),mA=qC(Pa),_v=new WeakMap;function zc(e,t,n){const a=Object.getPrototypeOf(e);let r=_v.get(a);if(r||(r=new Set,_v.set(a,r)),!r.has(t)){r.add(t);for(const s in n){const i=n[s];Object.defineProperty(a,s,{configurable:!0,enumerable:!1,get(){const c=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}const Jt=ie("ZodType",(e,t)=>(Zt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:xd(e,"input"),output:xd(e,"output")}}),e.toJSONSchema=xT(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>tA(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>aA(e,n,a),e.parseAsync=async(n,a)=>nA(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>rA(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>sA(e,n,a),e.decode=(n,a)=>oA(e,n,a),e.encodeAsync=async(n,a)=>iA(e,n,a),e.decodeAsync=async(n,a)=>cA(e,n,a),e.safeEncode=(n,a)=>lA(e,n,a),e.safeDecode=(n,a)=>dA(e,n,a),e.safeEncodeAsync=async(n,a)=>uA(e,n,a),e.safeDecodeAsync=async(n,a)=>mA(e,n,a),zc(e,"ZodType",{check(...n){const a=this.def;return this.clone(hs(a,{checks:[...a.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return gs(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(rE(n,a))},superRefine(n,a){return this.check(sE(n,a))},overwrite(n){return this.check(bi(n))},optional(){return Tv(this)},exactOptional(){return BA(this)},nullable(){return Av(this)},nullish(){return Tv(Av(this))},nonoptional(n){return ZA(this,n)},array(){return v(this)},or(n){return dt([this,n])},and(n){return zA(this,n)},transform(n){return Ev(this,lS(n))},default(n){return KA(this,n)},prefault(n){return GA(this,n)},catch(n){return QA(this,n)},pipe(n){return Ev(this,n)},readonly(){return eE(this)},describe(n){const a=this.clone();return tc.add(a,{description:n}),a},meta(...n){if(n.length===0)return tc.get(this);const a=this.clone();return tc.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 tc.get(e)?.description},configurable:!0}),e)),rS=ie("_ZodString",(e,t)=>{Qf.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(a,r,s)=>wT(e,a,r);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,zc(e,"_ZodString",{regex(...a){return this.check(sT(...a))},includes(...a){return this.check(cT(...a))},startsWith(...a){return this.check(lT(...a))},endsWith(...a){return this.check(dT(...a))},min(...a){return this.check(Sd(...a))},max(...a){return this.check(Q0(...a))},length(...a){return this.check(Y0(...a))},nonempty(...a){return this.check(Sd(1,...a))},lowercase(a){return this.check(oT(a))},uppercase(a){return this.check(iT(a))},trim(){return this.check(mT())},normalize(...a){return this.check(uT(...a))},toLowerCase(){return this.check(pT())},toUpperCase(){return this.check(fT())},slugify(){return this.check(hT())}})}),pA=ie("ZodString",(e,t)=>{Qf.init(e,t),rS.init(e,t),e.email=n=>e.check(TP(fA,n)),e.url=n=>e.check(MP(hA,n)),e.jwt=n=>e.check(GP(AA,n)),e.emoji=n=>e.check(OP(gA,n)),e.guid=n=>e.check(xv(Cv,n)),e.uuid=n=>e.check(J0(nc,n)),e.uuidv4=n=>e.check(AP(nc,n)),e.uuidv6=n=>e.check(EP(nc,n)),e.uuidv7=n=>e.check(jP(nc,n)),e.nanoid=n=>e.check($P(vA,n)),e.guid=n=>e.check(xv(Cv,n)),e.cuid=n=>e.check(NP(bA,n)),e.cuid2=n=>e.check(DP(yA,n)),e.ulid=n=>e.check(LP(SA,n)),e.base64=n=>e.check(VP(RA,n)),e.base64url=n=>e.check(KP(PA,n)),e.xid=n=>e.check(zP(xA,n)),e.ksuid=n=>e.check(HP(kA,n)),e.ipv4=n=>e.check(UP(wA,n)),e.ipv6=n=>e.check(qP(IA,n)),e.cidrv4=n=>e.check(BP(_A,n)),e.cidrv6=n=>e.check(FP(CA,n)),e.e164=n=>e.check(WP(TA,n)),e.datetime=n=>e.check(na(n)),e.date=n=>e.check(ZT(n)),e.time=n=>e.check(QT(n)),e.duration=n=>e.check(XT(n))});function o(e){return PP(pA,e)}const an=ie("ZodStringFormat",(e,t)=>{nn.init(e,t),rS.init(e,t)}),fA=ie("ZodEmail",(e,t)=>{jR.init(e,t),an.init(e,t)}),Cv=ie("ZodGUID",(e,t)=>{AR.init(e,t),an.init(e,t)}),nc=ie("ZodUUID",(e,t)=>{ER.init(e,t),an.init(e,t)});function sS(e){return J0(nc,e)}const hA=ie("ZodURL",(e,t)=>{MR.init(e,t),an.init(e,t)}),gA=ie("ZodEmoji",(e,t)=>{OR.init(e,t),an.init(e,t)}),vA=ie("ZodNanoID",(e,t)=>{$R.init(e,t),an.init(e,t)}),bA=ie("ZodCUID",(e,t)=>{NR.init(e,t),an.init(e,t)}),yA=ie("ZodCUID2",(e,t)=>{DR.init(e,t),an.init(e,t)}),SA=ie("ZodULID",(e,t)=>{LR.init(e,t),an.init(e,t)}),xA=ie("ZodXID",(e,t)=>{zR.init(e,t),an.init(e,t)}),kA=ie("ZodKSUID",(e,t)=>{HR.init(e,t),an.init(e,t)}),wA=ie("ZodIPv4",(e,t)=>{VR.init(e,t),an.init(e,t)}),IA=ie("ZodIPv6",(e,t)=>{KR.init(e,t),an.init(e,t)}),_A=ie("ZodCIDRv4",(e,t)=>{WR.init(e,t),an.init(e,t)}),CA=ie("ZodCIDRv6",(e,t)=>{GR.init(e,t),an.init(e,t)}),RA=ie("ZodBase64",(e,t)=>{ZR.init(e,t),an.init(e,t)}),PA=ie("ZodBase64URL",(e,t)=>{QR.init(e,t),an.init(e,t)}),TA=ie("ZodE164",(e,t)=>{YR.init(e,t),an.init(e,t)}),AA=ie("ZodJWT",(e,t)=>{eP.init(e,t),an.init(e,t)}),oS=ie("ZodNumber",(e,t)=>{F0.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(a,r,s)=>IT(e,a,r),zc(e,"ZodNumber",{gt(a,r){return this.check(wv(a,r))},gte(a,r){return this.check(qm(a,r))},min(a,r){return this.check(qm(a,r))},lt(a,r){return this.check(kv(a,r))},lte(a,r){return this.check(Um(a,r))},max(a,r){return this.check(Um(a,r))},int(a){return this.check(Rv(a))},safe(a){return this.check(Rv(a))},positive(a){return this.check(wv(0,a))},nonnegative(a){return this.check(qm(0,a))},negative(a){return this.check(kv(0,a))},nonpositive(a){return this.check(Um(0,a))},multipleOf(a,r){return this.check(Iv(a,r))},step(a,r){return this.check(Iv(a,r))},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 m(e){return XP(oS,e)}const EA=ie("ZodNumberFormat",(e,t)=>{tP.init(e,t),oS.init(e,t)});function Rv(e){return eT(EA,e)}const jA=ie("ZodBoolean",(e,t)=>{nP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>_T(e,n,a)});function j(e){return tT(jA,e)}const MA=ie("ZodNull",(e,t)=>{aP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>CT(e,n,a)});function yi(e){return nT(MA,e)}const OA=ie("ZodUnknown",(e,t)=>{rP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>PT()});function ke(){return aT(OA)}const $A=ie("ZodNever",(e,t)=>{sP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>RT(e,n,a)});function iS(e){return rT($A,e)}const NA=ie("ZodArray",(e,t)=>{oP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>OT(e,n,a,r),e.element=t.element,zc(e,"ZodArray",{min(n,a){return this.check(Sd(n,a))},nonempty(n){return this.check(Sd(1,n))},max(n,a){return this.check(Q0(n,a))},length(n,a){return this.check(Y0(n,a))},unwrap(){return this.element}})});function v(e,t){return gT(NA,e,t)}const Yf=ie("ZodObject",(e,t)=>{cP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>$T(e,n,a,r),xt(e,"shape",()=>t.shape),zc(e,"ZodObject",{keyof(){return k(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:ke()})},loose(){return this.clone({...this._zod.def,catchall:ke()})},strict(){return this.clone({...this._zod.def,catchall:iS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return _C(this,n)},safeExtend(n){return CC(this,n)},merge(n){return RC(this,n)},pick(n){return wC(this,n)},omit(n){return IC(this,n)},partial(...n){return PC(dS,this,n[0])},required(...n){return TC(uS,this,n[0])}})});function u(e,t){const n={type:"object",shape:e??{},...ze(t)};return new Yf(n)}function Bm(e,t){return new Yf({type:"object",shape:e,catchall:iS(),...ze(t)})}const cS=ie("ZodUnion",(e,t)=>{W0.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>NT(e,n,a,r),e.options=t.options});function dt(e,t){return new cS({type:"union",options:e,...ze(t)})}const DA=ie("ZodDiscriminatedUnion",(e,t)=>{cS.init(e,t),lP.init(e,t)});function st(e,t,n){return new DA({type:"union",options:t,discriminator:e,...ze(n)})}const LA=ie("ZodIntersection",(e,t)=>{dP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>DT(e,n,a,r)});function zA(e,t){return new LA({type:"intersection",left:e,right:t})}const Pv=ie("ZodRecord",(e,t)=>{uP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>LT(e,n,a,r),e.keyType=t.keyType,e.valueType=t.valueType});function ve(e,t,n){return!t||!t._zod?new Pv({type:"record",keyType:o(),valueType:e,...ze(t)}):new Pv({type:"record",keyType:e,valueType:t,...ze(n)})}const Bp=ie("ZodEnum",(e,t)=>{mP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(a,r,s)=>TT(e,a,r),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,r)=>{const s={};for(const i of a)if(n.has(i))s[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Bp({...t,checks:[],...ze(r),entries:s})},e.exclude=(a,r)=>{const s={...t.entries};for(const i of a)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Bp({...t,checks:[],...ze(r),entries:s})}});function k(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new Bp({type:"enum",entries:n,...ze(t)})}const HA=ie("ZodLiteral",(e,t)=>{pP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>AT(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 x(e,t){return new HA({type:"literal",values:Array.isArray(e)?e:[e],...ze(t)})}const UA=ie("ZodTransform",(e,t)=>{fP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>MT(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new T0(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Sc(s,n.value,t));else{const i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(Sc(i))}};const r=t.transform(n.value,n);return r instanceof Promise?r.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=r,n.fallback=!0,n)}});function lS(e){return new UA({type:"transform",transform:e})}const dS=ie("ZodOptional",(e,t)=>{G0.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>nS(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function Tv(e){return new dS({type:"optional",innerType:e})}const qA=ie("ZodExactOptional",(e,t)=>{hP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>nS(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function BA(e){return new qA({type:"optional",innerType:e})}const FA=ie("ZodNullable",(e,t)=>{gP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>zT(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function Av(e){return new FA({type:"nullable",innerType:e})}const VA=ie("ZodDefault",(e,t)=>{vP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>UT(e,n,a,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function KA(e,t){return new VA({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():j0(t)}})}const WA=ie("ZodPrefault",(e,t)=>{bP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>qT(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function GA(e,t){return new WA({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():j0(t)}})}const uS=ie("ZodNonOptional",(e,t)=>{yP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>HT(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function ZA(e,t){return new uS({type:"nonoptional",innerType:e,...ze(t)})}const JA=ie("ZodCatch",(e,t)=>{SP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>BT(e,n,a,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function QA(e,t){return new JA({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const mS=ie("ZodPipe",(e,t)=>{Z0.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>FT(e,n,a,r),e.in=t.in,e.out=t.out});function Ev(e,t){return new mS({type:"pipe",in:e,out:t})}const YA=ie("ZodPreprocess",(e,t)=>{mS.init(e,t),xP.init(e,t)}),XA=ie("ZodReadonly",(e,t)=>{kP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>VT(e,n,a,r),e.unwrap=()=>e._zod.def.innerType});function eE(e){return new XA({type:"readonly",innerType:e})}const tE=ie("ZodTemplateLiteral",(e,t)=>{wP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>ET(e,n,a)});function pS(e,t){return new tE({type:"template_literal",parts:e,...ze(t)})}const nE=ie("ZodLazy",(e,t)=>{IP.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>KT(e,n,a,r),e.unwrap=()=>e._zod.def.getter()});function aE(e){return new nE({type:"lazy",getter:e})}const fS=ie("ZodCustom",(e,t)=>{_P.init(e,t),Jt.init(e,t),e._zod.processJSONSchema=(n,a,r)=>jT(e,n)});function Fm(e,t){return vT(fS,(()=>!0),t)}function rE(e,t={}){return bT(fS,e,t)}function sE(e,t){return yT(e,t)}function ds(e){const t=aE(()=>dt([o(e),m(),j(),yi(),v(t),ve(o(),t)]));return t}function oE(e,t){return new YA({type:"pipe",in:lS(e),out:t})}const iE=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cE=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]);let lE=class hS{state=new Uint32Array(iE);pending=new Uint8Array(64);pendingLength=0;byteLength=0;words=new Uint32Array(64);update(t){const n=typeof t=="string"?new TextEncoder().encode(t):t;if(!Number.isSafeInteger(this.byteLength+n.length))throw new RangeError("SHA-256 input is too large");this.byteLength+=n.length;let a=0;if(this.pendingLength){const r=Math.min(64-this.pendingLength,n.length);this.pending.set(n.subarray(0,r),this.pendingLength),this.pendingLength+=r,a+=r,this.pendingLength===64&&(this.compress(this.pending),this.pendingLength=0)}for(;a+64<=n.length;)this.compress(n.subarray(a,a+64)),a+=64;return a<n.length&&(this.pending.set(n.subarray(a)),this.pendingLength=n.length-a),this}clone(){const t=new hS;return t.state.set(this.state),t.pending.set(this.pending),t.pendingLength=this.pendingLength,t.byteLength=this.byteLength,t}digestHex(){const t=this.clone(),n=new Uint8Array(t.pendingLength<56?64:128);n.set(t.pending.subarray(0,t.pendingLength)),n[t.pendingLength]=128;const a=t.byteLength*8,r=new DataView(n.buffer);return r.setUint32(n.length-8,Math.floor(a/4294967296),!1),r.setUint32(n.length-4,a>>>0,!1),t.compress(n.subarray(0,64)),n.length===128&&t.compress(n.subarray(64)),Array.from(t.state,s=>s.toString(16).padStart(8,"0")).join("")}compress(t){const n=new DataView(t.buffer,t.byteOffset,64),a=this.state,r=this.words;for(let b=0;b<16;b+=1)r[b]=n.getUint32(b*4,!1);for(let b=16;b<64;b+=1){const I=r[b-15],C=r[b-2],P=rr(I,7)^rr(I,18)^I>>>3,_=rr(C,17)^rr(C,19)^C>>>10;r[b]=r[b-16]+P+r[b-7]+_>>>0}let s=a[0],i=a[1],c=a[2],d=a[3],l=a[4],p=a[5],f=a[6],S=a[7];for(let b=0;b<64;b+=1){const I=l&p^~l&f,C=s&i^s&c^i&c,P=rr(s,2)^rr(s,13)^rr(s,22),_=rr(l,6)^rr(l,11)^rr(l,25),M=S+_+I+cE[b]+r[b]>>>0,A=P+C>>>0;S=f,f=p,p=l,l=d+M>>>0,d=c,c=i,i=s,s=M+A>>>0}a[0]=a[0]+s>>>0,a[1]=a[1]+i>>>0,a[2]=a[2]+c>>>0,a[3]=a[3]+d>>>0,a[4]=a[4]+l>>>0,a[5]=a[5]+p>>>0,a[6]=a[6]+f>>>0,a[7]=a[7]+S>>>0}};function dE(e){return new lE().update(e).digestHex()}function rr(e,t){return e>>>t|e<<32-t}const uE=2e3,gS=25e7,E=o().trim().min(1).max(240),W=o().regex(/^[a-f0-9]{64}$/),Ce=o().datetime({offset:!0}),ha=ve(o(),ke()).default({}),se=u({id:E,contentHash:W}).strict(),Kt=se.extend({revision:m().int().positive()}).strict(),aa=u({id:E,path:o().trim().min(1).max(uE).refine(fE),contentHash:W,sizeBytes:m().int().nonnegative().max(gS),mediaType:o().trim().min(1).max(200),visibility:k(["policy","verifier","host_private"])}).strict(),br=u({id:E,contentHash:W,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:m().int().nonnegative().max(gS).nullable().default(null)}).strict(),Gd=k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function mE(e){return`${JSON.stringify(Fp(e),null,2)}
|
|
72
|
+
`}function Xf(e){return dE(e)}function Qe(e){return Xf(mE(e))}function pE(e,t){const{contentHash:n,...a}=e,r=Qe(a);if(n!==r)throw new Error(`${t} contentHash is ${n}; expected ${r}.`)}function fE(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Fp(e){return Array.isArray(e)?e.map(Fp):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Fp(n)]))}const eh=u({provider:E,model:E,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:W.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:W.nullable().default(null)}).strict(),hE=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],vS=pS(["acp:",o().regex(/^[a-z0-9][a-z0-9-]{0,100}$/)]),bS=dt([k(hE),vS]);function xc(e){return/^acp:[a-z0-9][a-z0-9-]{0,100}$/.test(e)}const ln=u({providerId:bS,modelId:o().trim().min(1).max(300)}),gE=["coding","research","review","test","docs","planner","summarizer"];k(gE);const Si=o().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),yS=k(["none","worktree","copy_on_write"]),SS=k(["read_only","workspace_write","full_tools"]),xS=k(["disabled","parent_scoped"]),Zd=k(["manual","balanced","proactive"]),vE=k(["queued","running","completed","failed","cancelled","needs_resume"]),bE=["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"];k(bE);const yE=[{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"}],th=u({id:Si,enabled:j().default(!0),modelRef:ln.nullable().default(null),isolationMode:yS.default("none"),maxConcurrentRuns:m().int().min(1).max(16).default(1),toolPolicy:SS.default("read_only"),background:j().default(!0),peerMessages:xS.default("parent_scoped")}),kc=u({enabled:j().default(!0),workspaceDefaultsVersion:x(1).default(1),toolDefaultsVersion:x(1).default(1),delegationMode:Zd.default("manual"),defaultModelRef:ln.nullable().default(null),roles:v(th).max(64).default(()=>IS()),maxConcurrentRuns:m().int().min(1).max(32).default(4),maxConcurrentRunsPerProvider:m().int().min(1).max(32).nullable().default(2),maxConcurrentRunsPerWorkspaceTarget:m().int().min(1).max(32).nullable().default(1)}).transform(e=>({...e,roles:AE(e.roles)})),lc=u({kind:k(["session","turn","file","diff","artifact"]),id:o().trim().min(1).max(500),label:o().trim().min(1).max(500)}),SE=u({kind:k(["retain_with_parent"]).default("retain_with_parent"),messageRetentionDays:m().int().min(1).max(3650).nullable().default(null),artifactRetentionDays:m().int().min(1).max(3650).nullable().default(null),cleanupAfterExpiry:j().default(!1)}).default(()=>({kind:"retain_with_parent",messageRetentionDays:null,artifactRetentionDays:null,cleanupAfterExpiry:!1})),xE=k(["orient","edit","validate","report"]),kE=u({command:o().trim().min(1).max(2e3),status:k(["passed","failed","unknown"]).default("unknown"),exitCode:m().int().nullable().default(null),outputSummary:o().trim().max(5e3).nullable().default(null),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null)}),wE=u({phase:xE.default("orient"),inspectedFiles:v(o().trim().min(1).max(1e3)).max(500).default([]),inspectedResources:v(o().trim().min(1).max(1e3)).max(500).default([]),repeatedSearches:v(o().trim().min(1).max(1e3)).max(200).default([]),repeatedReads:v(o().trim().min(1).max(1e3)).max(200).default([]),repeatedCommands:v(o().trim().min(1).max(1e3)).max(200).default([]),changedFiles:v(o().trim().min(1).max(1e3)).max(500).default([]),patchRefs:v(lc).max(100).default([]),validationAttempts:v(kE).max(100).default([]),latestMeaningfulActivity:o().trim().max(5e3).nullable().default(null),currentBlocker:o().trim().max(5e3).nullable().default(null),updatedAt:o().nullable().default(null)}).default(()=>({phase:"orient",inspectedFiles:[],inspectedResources:[],repeatedSearches:[],repeatedReads:[],repeatedCommands:[],changedFiles:[],patchRefs:[],validationAttempts:[],latestMeaningfulActivity:null,currentBlocker:null,updatedAt:null})),IE=u({summary:o().trim().max(2e4).default(""),findings:v(o().trim().min(1).max(5e3)).max(200).default([]),artifacts:v(lc).max(200).default([]),patchRef:lc.nullable().default(null),diffRef:lc.nullable().default(null),testsRun:v(o().trim().min(1).max(2e3)).max(100).default([]),blockers:v(o().trim().min(1).max(5e3)).max(100).default([]),confidence:k(["low","medium","high"]).nullable().default(null),followUpNeeded:j().default(!1)}),kS=u({id:o().trim().min(1).max(200),parentSessionId:o().trim().min(1).max(200),parentTurnId:o().trim().min(1).max(200).nullable().default(null),childSessionId:o().trim().min(1).max(200).nullable().default(null),roleId:Si,objective:o().trim().min(1).max(5e4),modelRef:ln.nullable().default(null),isolationMode:yS.default("none"),toolPolicy:SS.default("read_only"),background:j().default(!0),peerMessages:xS.default("parent_scoped"),status:vE.default("queued"),progress:wE,evidenceRetention:SE,createdAt:o(),startedAt:o().nullable().default(null),completedAt:o().nullable().default(null),updatedAt:o().nullable().default(null),error:o().nullable().default(null),report:IE.nullable().default(null),metadata:ve(o(),ke()).optional().default({})}),wS=k(["cleanup","archive","cleanup_and_archive"]);u({action:wS,reason:o().trim().min(1).max(2e3).nullable().default(null)});u({action:wS,run:kS,workspaceCleanup:ve(o(),ke()).nullable().default(null),sessionArchive:ve(o(),ke()).nullable().default(null),nextStep:o()});const _E=k(["question","answer","handoff","artifact","status","blocker"]),CE=k(["normal","interrupt"]),RE=u({inputIds:v(o()).default([]),status:k(["pending","delivered","undelivered"]).default("pending"),deliveredRunIds:v(o().trim().min(1).max(200)).max(200).default([]),acknowledgedRunIds:v(o().trim().min(1).max(200)).max(200).default([]),deliveredParentSessionId:o().trim().min(1).max(200).nullable().default(null),acknowledgedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeRequestedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeQueuedParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeDeferredParentSessionId:o().trim().min(1).max(200).nullable().default(null),wakeParentReason:o().trim().min(1).max(1e3).nullable().default(null),wakeRequestedRunIds:v(o().trim().min(1).max(200)).max(200).default([]),wakeInterruptedRunIds:v(o().trim().min(1).max(200)).max(200).default([]),wakeDeferredRunIds:v(o().trim().min(1).max(200)).max(200).default([]),reason:o().trim().min(1).max(1e3).nullable().default(null)}),PE=u({id:o().trim().min(1).max(200),fromRunId:o().trim().min(1).max(200),toRunId:o().trim().min(1).max(200).nullable().default(null),toRole:Si.nullable().default(null),kind:_E,priority:CE.optional(),body:o().trim().min(1).max(5e4),refs:v(lc).max(100).default([]),delivery:RE.optional(),createdAt:o()});function IS(){return yE.map(e=>th.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function TE(){return kc.parse({})}function AE(e){const t=IS(),n=new Map(t.map(r=>[r.id,r])),a=[];for(const r of e??[]){const s=th.parse(r);n.has(s.id)?n.set(s.id,s):a.push(s)}return[...t.map(r=>n.get(r.id)??r),...a]}const EE=u({id:o().trim().min(1).max(80),label:o().trim().min(1).max(160),description:o().trim().max(500).nullable().optional().default(null)}),jE=u({id:o().trim().min(1),sessionId:o().trim().min(1),turnId:o().trim().min(1),toolCallId:o().trim().min(1),question:o().trim().min(1).max(2e3),reason:o().trim().max(1e3).nullable().optional().default(null),options:v(EE).max(5).default([]),allowFreeform:j().default(!0),status:k(["pending","answered","dismissed"]),answer:u({optionId:o().trim().min(1).nullable(),text:o().max(4e3)}).nullable(),createdAt:o(),answeredAt:o().nullable()}),ME=u({questionId:o().trim().min(1),action:k(["answer","dismiss"]),optionId:o().trim().min(1).nullable().optional().default(null),text:o().trim().max(4e3).optional().default("")}),Vm="https://openpond.ai",nh=["slack","google","github","turnkey","x","microsoft_teams","mcp"],ah={slack:[Qt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Qt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Qt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Qt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Qt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Qt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Qt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Qt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Qt("google.comments.read","Read comments","Read Google file comments.","read",!0),Qt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Qt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Qt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Qt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Qt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Qt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Qt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Qt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Qt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Qt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Qt("x.search.read","Search X","Search public X posts when granted.","read",!0),Qt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Qt("x.post.write","Post","Create approved X posts.","write",!0),Qt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Qt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Qt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},_S={slack:[],microsoft_teams:[],google:[zt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),zt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),zt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),zt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),zt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),zt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),zt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[zt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),zt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),zt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),zt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),zt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),zt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),zt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),zt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),zt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),zt("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"]}),zt("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:[zt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),zt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),zt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[zt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),zt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),zt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),zt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),zt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),zt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),zt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},OE={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(`
|
|
73
|
+
`),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(`
|
|
74
|
+
`),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(`
|
|
75
|
+
`),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(`
|
|
76
|
+
`),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(`
|
|
77
|
+
`),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(`
|
|
78
|
+
`),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(`
|
|
79
|
+
`)},g8=nh.map(e=>{const t=PS(e),n=OE[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${KE(n)}`,charCount:n.length}}),$E=[{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"}],Jd=$E,NE=nh.map(e=>{const t=Jd.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:dc(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:ah[e],skills:HE(e),tools:UE(e),operations:_S[e],leasePolicy:qE(e)}});function CS(e){const t=DE(e);return t?Jd.find(n=>n.id===t)??null:null}function RS(e){const t=rh(e);return t?NE.find(n=>n.id===t)??null:null}function v8(e){const t=CS(e.appId),n=LE(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",r=new URL(a,n);t?.kind!=="mcp"&&r.searchParams.set("app",t?.deepLinkAppId??e.appId);const s=e.teamId?.trim();return s&&r.searchParams.set("teamId",s),r.toString()}function DE(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Jd.some(n=>n.id===t)?t:null:null}function rh(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":nh.includes(t)?t:CS(t)?.providerFamily??null:null}function Km(e={}){const t=BE(e.connections??[]);return Jd.map(n=>{const a=RS(n.providerFamily),r=n.statusSource==="integration_connection"?t.filter(c=>c.provider===n.providerFamily):[],s=r.some(c=>c.status==="active"),i=FE(n,s);return{...n,providerLabel:a.label,setupSurfaceLabel:zE(n.setupSurface),status:i,statusLabel:VE(n,i,r),connections:r,connected:s,capabilities:jv(n,a.capabilities),capabilityLabels:jv(n,a.capabilities).map(c=>c.label),leasePolicy:a.leasePolicy}})}function Qt(e,t,n,a,r){return{id:e,label:t,description:n,access:a,leaseable:r}}function zt(e,t,n,a,r,s){return{id:e,operation:t,label:n,description:a,capabilityIds:r,...s?{input:s}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function LE(e){const t=e?.trim();if(!t)return Vm;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Vm:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Vm}}function dc(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function zE(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function HE(e){return[PS(e)]}function PS(e){return{name:`${e}-connected-app`,description:`Use ${dc(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function UE(e){if(e==="mcp")return[];const t=ah[e],n=_S[e],a=t.filter(i=>i.access==="read").map(i=>i.id),r=t.filter(i=>i.access==="write").map(i=>i.id),s=[];return n.some(i=>i.operation==="search")&&s.push({name:"connected_app_search",description:`Search ${dc(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(i=>i.operation==="read")&&s.push({name:"connected_app_read",description:`Read a grounded ${dc(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),r.length>0&&n.some(i=>i.operation==="write")&&s.push({name:"connected_app_write",description:`Perform an explicitly approved ${dc(e)} write through a server-owned connected app connector.`,capabilityIds:r,write:!0}),s}function qE(e){const t=ah[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 jv(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 BE(e){return e.flatMap(t=>{const n=rh(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 FE(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function VE(e,t,n){if(t==="connected"){const a=n.filter(r=>r.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function KE(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 WE="local_path:";function TS(e){return`${WE}${e.trim()}`}u({appId:o(),source:k(["openpond","github","local_git","local_folder","unknown"]),workspacePath:o(),repoPath:o(),initialized:j(),remoteUrl:o().nullable(),expectedRemoteUrl:o().nullable(),currentBranch:o().nullable(),headCommit:o().nullable().optional().default(null),upstreamBranch:o().nullable().optional().default(null),ahead:m().int().nonnegative().optional().default(0),behind:m().int().nonnegative().optional().default(0),diverged:j().optional().default(!1),linkedSourceHeadCommit:o().nullable().optional().default(null),aheadOfLinkedSource:m().int().nonnegative().optional().default(0),behindLinkedSource:m().int().nonnegative().optional().default(0),divergedFromLinkedSource:j().optional().default(!1),linkedSourceComparisonError:o().nullable().optional().default(null),lastFetchAt:o().nullable().optional().default(null),defaultBranch:o().nullable(),branches:v(o()),dirty:j(),changedFilesCount:m(),untrackedFilesCount:m(),error:o().nullable(),updatedAt:o()});const GE=u({path:o(),status:o(),additions:m(),deletions:m(),patch:o(),content:o().nullable().optional().default(null)}),ZE=u({appId:o(),repoPath:o(),initialized:j(),dirty:j(),filesChanged:m(),additions:m(),deletions:m(),repoFiles:v(o()).optional().default([]),files:v(GE),error:o().nullable(),updatedAt:o()});u({branch:o().trim().min(1).max(160)});u({path:o().trim().min(1),content:o()});const Mv=u({line:m().int().nonnegative(),character:m().int().nonnegative()}),JE=u({start:Mv,end:Mv}),QE=u({path:o(),range:JE,severity:k(["error","warning","info","hint"]),message:o(),source:o().nullable().optional().default(null),code:o().nullable().optional().default(null)}),AS=u({id:o(),root:o(),status:k(["connected","unavailable","error"]),message:o().nullable().optional().default(null)});u({path:o().trim().min(1),content:o().optional(),waitForDiagnostics:j().optional().default(!0)});u({appId:o(),path:o(),diagnostics:v(QE),servers:v(AS),updatedAt:o()});const YE=u({operation:k(["hover","definition","references","documentSymbol"]),path:o().trim().min(1),content:o().optional(),line:m().int().nonnegative().optional(),character:m().int().nonnegative().optional()});u({appId:o(),operation:YE.shape.operation,path:o(),results:ke(),servers:v(AS),updatedAt:o()});const XE=u({pinned:j().optional(),archived:j().optional(),order:m().optional()});ve(o(),XE);const sh="gpt-5.6-sol",oi="openpond-chat",Ks="openpond",wc=oi,oh="default",ih="high",Qd="ask",xi=bS,ch=k(["default","auto-review","full-access"]),Hc=k(["ask","full-access","disabled"]),Yd=k(["off","low","medium","high","xhigh","max"]),Uc=k(["sandbox_app","local_project","sandbox","sandbox_template"]);k(["openpond"]);const ej=k(["provider_usage","provider_tokenizer","model_family","heuristic"]),tj=u({provider:xi,model:o().min(1),usedTokens:m().int().nonnegative(),maxContextTokens:m().int().positive(),usableContextTokens:m().int().positive(),percentFull:m().min(0).max(100),source:ej,updatedAtEventId:o().nullable()}),Vp=u({pinned:j().default(!1),projects:j().default(!1),cloudProjects:j().default(!1),chats:j().default(!1),savedForLater:j().default(!0)}),nj=k(["auto","off"]),aj=k(["typescript","python","rust"]),ES=k(["auto","disabled","custom"]),Mr=u({mode:ES.default("auto"),customCommand:o().trim().max(4096).default("")}),kd=u({languageServers:nj.default("auto"),diagnosticsWhileEditing:j().default(!0),checkOnSave:j().default(!0),languages:u({typescript:Mr.optional().default(()=>Mr.parse({})),python:Mr.optional().default(()=>Mr.parse({})),rust:Mr.optional().default(()=>Mr.parse({}))}).optional().default(()=>({typescript:Mr.parse({}),python:Mr.parse({}),rust:Mr.parse({})}))}),rj=u({language:aj,label:o(),mode:ES,status:k(["found","missing","disabled","error"]),command:o().nullable(),message:o().nullable()});u({settings:kd,languages:v(rj),updatedAt:o()});const sj=u({id:o(),root:o(),status:k(["starting","connected","unavailable","error"]),message:o().nullable().optional().default(null),openedDocuments:m().int().nonnegative(),pendingRequests:m().int().nonnegative(),lastUsedAt:o(),stderrTail:o()});u({clients:v(sj),maxClients:m().int().positive(),idleTimeoutMs:m().int().positive(),updatedAt:o()});const Kp=u({autoEnabled:j().default(!0),triggerPercent:m().int().min(50).max(95).default(85),summaryModel:k(["same_model"]).default("same_model")}),Wp=u({defaultModelRef:ln.nullable().default(null),creationMode:k(["defaults","customize"]).default("customize"),autoApproveEvidence:j().default(!1)});u({defaultChatProvider:xi.default(Ks),defaultChatModel:o().min(1).default(wc),defaultChatModelRef:ln.nullable().optional(),subagents:kc.optional().default(()=>kc.parse({})),codexPermissionMode:ch.default(oh),codexReasoningEffort:Yd.default(ih),openPondCommandAccessMode:Hc.default(Qd),defaultBranchPrefix:o().trim().max(48).default("feat/"),defaultNewProjectDirectory:o().trim().max(4096).default(""),defaultTeamId:o().trim().max(191).nullable().default(null),advancedWorkspaceControls:j().default(!1),steerActiveResponses:j().default(!0),contextCompaction:Kp.optional().default(()=>Kp.parse({})),training:Wp.optional().default(()=>Wp.parse({})),sidebarWidth:m().int().min(244).max(560).default(332),diffPanelWidth:m().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Vp.optional().default(()=>Vp.parse({})),editor:kd.optional().default(()=>kd.parse({}))});const oj="default",ij=[{id:"default",name:"Balanced",source:"built_in",description:"Clear, useful, and concise.",content:`You are OpenPond Chat, a clear and useful AI assistant.
|
|
80
|
+
Be concise, accurate, and direct.
|
|
81
|
+
Do not use emojis.
|
|
82
|
+
Ask only when missing information would materially change the answer.
|
|
83
|
+
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.
|
|
84
|
+
Be direct, concrete, and outcome-focused.
|
|
85
|
+
Do not use emojis.
|
|
86
|
+
Prefer simple working solutions over clever abstractions.
|
|
87
|
+
Call out weak assumptions plainly.`},{id:"friendly",name:"Friendly",source:"built_in",description:"Warm, conversational, and approachable.",content:`You are a friendly AI assistant.
|
|
88
|
+
Use a warm, conversational tone without filler.
|
|
89
|
+
Do not use emojis.
|
|
90
|
+
Explain decisions clearly and keep the user moving.
|
|
91
|
+
Be patient when clarifying tradeoffs.`},{id:"formal",name:"Formal",source:"built_in",description:"Polished, careful, and professional.",content:`You are a formal AI assistant.
|
|
92
|
+
Use precise, professional language.
|
|
93
|
+
Do not use emojis.
|
|
94
|
+
Structure answers clearly and avoid casual phrasing.
|
|
95
|
+
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.
|
|
96
|
+
Prioritize correctness, implementation detail, and edge cases.
|
|
97
|
+
Do not use emojis.
|
|
98
|
+
Use concise explanations, but include necessary specifics.
|
|
99
|
+
Surface risks, constraints, and verification steps.`}],lh=o().trim().min(1).max(120),cj=u({id:lh,name:o(),source:k(["built_in","custom"]).default("custom"),description:o(),content:o()});u({activeTemplateId:lh.default(oj),customized:j().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:v(cj).default(()=>[...ij])});u({id:o(),host:o(),port:m(),startedAt:o(),storePath:o(),version:o(),runtimeVersion:o()});const dh=k(["chat","work","development"]);k(["chat","models","console","development"]);const lj="work",Ee=o().trim().min(1).nullable(),Ta=ve(o(),ke()).default({}),dj=k(["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"]),jS=k(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),uj=k(["create","improve","import","promote"]),mj=k(["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"]),Pl=k(["always_require_plan_approval","approval_already_granted"]);k(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const pj=st("kind",[u({kind:x("local"),sourceAuthority:x("local_profile"),activeProfile:o().trim().min(1).nullable(),repoPath:Ee,sourcePath:Ee,localHead:Ee,confirmationPolicy:Pl.default("always_require_plan_approval")}),u({kind:x("hosted"),sourceAuthority:x("hosted_profile"),teamId:Ee,projectId:Ee,activeProfile:o().trim().min(1).nullable(),sourceRef:Ee,baseSha:Ee,confirmationPolicy:Pl.default("always_require_plan_approval")}),u({kind:x("promote_local_to_hosted"),sourceAuthority:x("promote_local_to_hosted"),teamId:Ee,projectId:Ee,activeProfile:o().trim().min(1).nullable(),repoPath:Ee,sourcePath:Ee,localHead:Ee,hostedHead:Ee,sourceRef:Ee,confirmationPolicy:Pl.default("always_require_plan_approval")}),u({kind:x("managed_artifact"),sourceAuthority:x("managed_artifact"),activeProfile:o().trim().min(1).nullable(),confirmationPolicy:Pl.default("always_require_plan_approval")})]),fj=u({id:Ee,kind:k(["user","system","automation"]).default("user"),label:Ee}),hj=u({profileId:o().trim().min(1),conversationId:Ee,originTurnId:Ee,projectId:Ee,targetProject:u({id:Ee,name:Ee,workspacePath:Ee,sourceRef:Ee,baseSha:Ee}).nullable()}),ac=u({messageIds:v(o().trim().min(1)).default([]),conversationExcerpts:v(u({messageId:Ee,role:o().trim().min(1).nullable(),excerpt:o().trim().min(1),reason:o().trim().min(1).nullable()})).default([]),attachments:v(u({id:Ee,name:o().trim().min(1),mediaType:Ee,ref:Ee})).default([]),apps:v(u({id:o().trim().min(1),name:o().trim().min(1),connectionId:Ee,required:j().default(!1)})).default([]),tools:v(u({name:o().trim().min(1),inputSummary:Ee,outputSummary:Ee,artifactRefs:v(o().trim().min(1)).default([]),sideEffects:v(o().trim().min(1)).default([])})).default([]),signalRefs:v(o().trim().min(1)).default([]),evalRefs:v(o().trim().min(1)).default([]),targetRepoAssumptions:v(o().trim().min(1)).default([])}),Ao={id:Ee,displayName:Ee},uh=st("kind",[u({kind:x("unselected"),...Ao}),u({kind:x("agent"),...Ao,defaultActionKey:Ee}),u({kind:x("skill"),...Ao,skillName:Ee}),u({kind:x("extension"),...Ao,slot:Ee}),u({kind:x("model"),...Ao,trainingPlanId:Ee,trainingJobId:Ee,artifactId:Ee}),u({kind:x("configuration"),...Ao,key:Ee})]),Gp=k(["agent","skill","extension","model","configuration"]),gj=u({schemaVersion:x("openpond.createImprove.evidenceSnapshot.v1"),id:o().trim().min(1),contentHash:o().trim().min(8),consent:u({status:k(["granted","denied","revoked"]),scope:k(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Ee,reviewedAt:o().trim().min(1)}),sources:v(u({kind:k(["signal","conversation","direct_correction","manual_intent","artifact"]),id:o().trim().min(1),sourceHash:o().trim().min(8),excerptRef:Ee})).min(1),reviewerIntent:o().trim().min(1),createdAt:o().trim().min(1),metadata:Ta}),MS=u({schemaVersion:x("openpond.createImprove.tasksetRef.v1"),id:o().trim().min(1),revision:m().int().positive(),contentHash:o().trim().min(8),evidenceSnapshotIds:v(o().trim().min(1)).min(1),policyBoundary:u({policyVisibleFields:v(o().trim().min(1)).default([]),privilegedFields:v(o().trim().min(1)).default([]),hiddenGraderRefs:v(o().trim().min(1)).default([]),connectedAppScopes:v(o().trim().min(1)).default([])}),targetRecommendation:u({kind:Gp,rationale:v(o().trim().min(1)).min(1),confidence:m().min(0).max(1)}),authoringSplitRefs:v(o().trim().min(1)).default([]),privateSplitRefs:v(o().trim().min(1)).default([]),approvedBy:Ee,approvedAt:o().trim().min(1),metadata:Ta}),vj=u({kind:k(["npm_package","runtime_tool","setup_command","secret","integration","volume","target_project","external_service"]),name:o().trim().min(1),status:k(["declared","required","blocked","satisfied"]).default("declared"),detail:Ee,metadata:Ta}),bj=u({mode:k(["chat","direct_action","chat_and_direct_actions"]),label:o().trim().min(1),detail:o().trim().min(1),defaultActionKey:Ee,directActionHint:Ee,artifactPolicy:o().trim().min(1)}),yj=u({schemaVersion:x("openpond.createImprove.plan.v1"),id:o().trim().min(1),runId:o().trim().min(1),status:k(["draft","pending_approval","approved","rejected","cancelled","superseded"]).default("pending_approval"),objective:o().trim().min(1),summary:o().trim().min(1),capturedContextSummary:o().trim().min(1),defaultChatAction:u({key:Ee,label:Ee,required:j().default(!0)}),sourcePlan:v(u({path:o().trim().min(1),operation:k(["create","update","delete","inspect"]),reason:o().trim().min(1)})).default([]),requirements:v(vj).default([]),checks:v(u({name:o().trim().min(1),command:o().trim().min(1),required:j().default(!0)})).default([]),approvalId:Ee,approvedAt:Ee,editedFromPlanId:Ee,metadata:Ta,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Sj=u({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:Ee,metadata:Ta}),xj=u({value:o().trim().min(1),label:Ee,detail:Ee,answeredAt:o().trim().min(1),metadata:Ta}),kj=u({id:o().trim().min(1),kind:k(["single_choice","free_text"]).default("single_choice"),title:o().trim().min(1),prompt:o().trim().min(1),required:j().default(!0),status:k(["pending","answered","skipped"]).default("pending"),options:v(Sj).default([]),answer:xj.nullable().default(null),metadata:Ta}),wj=u({schemaVersion:x("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:jS,objective:o().trim().min(1),conversationExcerpts:ac.shape.conversationExcerpts,attachments:ac.shape.attachments,apps:ac.shape.apps,tools:ac.shape.tools,sideEffects:v(o().trim().min(1)).default([]),profileActions:v(o().trim().min(1)).default([]),externalProviders:v(o().trim().min(1)).default([]),environmentVariables:v(o().trim().min(1)).default([]),files:v(o().trim().min(1)).default([]),schedules:v(o().trim().min(1)).default([]),webhooks:v(o().trim().min(1)).default([]),channelTargets:v(o().trim().min(1)).default([]),outputArtifacts:v(o().trim().min(1)).default([]),targetRepoAssumptions:v(o().trim().min(1)).default([]),traceRefs:v(o().trim().min(1)).default([]),metadata:Ta,createdAt:o().trim().min(1)}),OS=u({provider:x("github"),number:m().int().positive(),url:o().url(),state:k(["open","merged","closed"]),baseBranch:o().trim().min(1),headBranch:o().trim().min(1),mergeCommit:Ee,openedAt:o().trim().min(1),updatedAt:o().trim().min(1)}),Ij=u({baseBranch:o().trim().min(1),baseCommit:o().trim().min(1),branch:o().trim().min(1),headCommit:Ee,remoteName:o().trim().min(1).default("origin"),remoteUrl:Ee,worktreePath:Ee,changedPaths:v(o().trim().min(1)).default([]),diffStat:Ee,pullRequest:OS.nullable().default(null)}),_j=u({id:o().trim().min(1),target:uh,status:k(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:Ij.nullable().default(null),parentCandidateId:Ee.default(null),tasksetRef:MS.nullable().default(null),authoringModelRef:Ee.default(null),allowedPaths:v(o().trim().min(1)).default([]),sourceRefs:v(o().trim().min(1)).default([]),artifactRefs:v(o().trim().min(1)).default([]),checkRefs:v(o().trim().min(1)).default([]),evaluationReceiptRefs:v(o().trim().min(1)).default([]),createdAt:o().trim().min(1),updatedAt:o().trim().min(1),metadata:Ta}),Cj=u({id:o().trim().min(1),candidateId:Ee,target:uh,evaluatorKind:k(["agent_sdk","taskset","extension","skill","configuration","checks"]).default("checks"),subject:k(["active","candidate","post_release","standalone"]).default("standalone"),sourceCommit:Ee.default(null),sourceBranch:Ee.default(null),tasksetId:Ee.default(null),tasksetHash:Ee.default(null),taskAttemptRefs:v(o().trim().min(1)).default([]),status:k(["pending","passed","failed","blocked"]),publishGate:k(["passed","failed","not_applicable"]).default("not_applicable"),summaryCounts:u({total:m().int().nonnegative(),passed:m().int().nonnegative(),failed:m().int().nonnegative()}).nullable().default(null),evalRefs:v(o().trim().min(1)).default([]),artifactRefs:v(o().trim().min(1)).default([]),summary:Ee,createdAt:o().trim().min(1),metadata:Ta}),Rj=u({mode:k(["foreground","background"]).default("background"),pauseAllowed:j().default(!0),cancellationAllowed:j().default(!0)}),Pj=u({mode:k(["single","bounded","until_evals_pass"]).default("single"),maximumAttempts:m().int().min(1).max(20).default(1),currentAttempt:m().int().min(0).max(20).default(0)}),Tj=u({kind:k(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:Ee,metadata:Ta}),Aj=u({status:k(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ee,profileTag:Ee,releaseReceiptRef:Ee,pullRequest:OS.nullable().default(null),updatedAt:Ee}),qc=u({schemaVersion:x("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:m().int().nonnegative(),operation:uj,surface:dj,command:jS,objective:o().trim().min(1),state:mj,adapter:pj,actor:fj,scope:hj,context:ac,target:uh,evidenceSnapshots:v(gj).default([]),tasksetRef:MS.nullable().default(null),targetSelection:u({status:k(["open","recommended","confirmed"]),preselectedKind:Gp.nullable(),confirmedKind:Gp.nullable()}).nullable().default(null),plan:yj.nullable(),workflowCapture:wj.nullable(),executionPolicy:Rj.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:Pj.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:v(o().trim().min(1)).default([]),questionIds:v(o().trim().min(1)).default([]),questions:v(kj).default([]),candidates:v(_j).default([]),evaluationReceipts:v(Cj).default([]),checkRefs:v(o().trim().min(1)).default([]),sourceRefs:v(o().trim().min(1)).default([]),externalExecutionRefs:v(Tj).default([]),localProfileCommit:Ee,hostedSourceCommit:Ee,hostedSourceRef:Ee,releaseOutcome:Aj.default({status:"not_requested",profileCommit:null,profileTag:null,releaseReceiptRef:null,pullRequest:null,updatedAt:null}),blockedReason:Ee,appliedActionIds:v(o().trim().min(1)).max(200).default([]),metadata:Ta,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),sr={runId:o().trim().min(1),expectedRevision:m().int().nonnegative(),actionId:o().trim().min(1)};st("type",[u({...sr,type:x("answer_question"),questionId:o().trim().min(1),value:o().trim().min(1)}),u({...sr,type:x("approve_plan")}),u({...sr,type:x("revise_plan"),revision:o().trim().min(1)}),u({...sr,type:x("cancel"),reason:Ee.optional().default(null)}),u({...sr,type:x("pause")}),u({...sr,type:x("resume")}),u({...sr,type:x("open_pull_request"),candidateId:o().trim().min(1)}),u({...sr,type:x("apply_candidate"),candidateId:o().trim().min(1)}),u({...sr,type:x("reject_candidate"),candidateId:o().trim().min(1),reason:Ee.optional().default(null)}),u({...sr,type:x("reconcile_pull_request"),candidateId:o().trim().min(1)})]);u({schemaVersion:x("openpond.createImprove.runList.v1"),runs:v(qc),generatedAt:o().trim().min(1)});function b8(e){const t=bj.safeParse(e?.actionShape);return t.success?t.data:null}const Xd=u({source:k(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}),Ej=u({ref:Xd,revision:o().nullable(),sourceHash:o()}),ki=ve(o(),ke()).default({}),ka=m().int().nonnegative(),eu=o().trim().min(1).max(1e5),$S=u({kind:k(["personal","team"]),id:E}).strict(),jj=u({name:E,release:se.nullable(),revision:ka}).strict();u({schemaVersion:x("openpond.harnessWorkspace.v1"),id:E,ownerScope:$S,name:o().trim().min(1).max(240),location:k(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:ka,dirty:j(),currentChannel:jj,createdAt:Ce,updatedAt:Ce,metadata:ki}).strict();const NS=k(["runtime","memory","prompt","skill","agent","product","taskset","training"]),DS=k(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),LS=u({id:E,route:NS,operation:k(["create","update","delete"]),target:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(2e3),content:o().max(1e6).nullable(),contentHash:W.nullable(),effects:v(DS).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=Qe(e.content);e.contentHash!==n&&t.addIssue({code:"custom",message:`edit contentHash is ${e.contentHash}; expected ${n}`,path:["contentHash"]})}),zS=u({workspaceId:E,revision:ka,sourceRevision:o().trim().min(1).max(500),channelRevision:ka}).strict(),uc=u({id:E,revision:ka,contentHash:W}).strict(),Mj=u({schemaVersion:x("openpond.harnessTurnSnapshot.v1"),workspaceId:E,workspaceRevision:ka,sourceRevision:o().trim().min(1).max(500),channelName:E,channelRevision:ka,harnessRelease:se,toolCatalogHash:W.nullable().optional(),overlay:uc.nullable().optional().default(null)}).strict(),Oj=u({schemaVersion:x("openpond.harnessRunOverlay.v1"),id:E,runId:E,baseHarnessRelease:se,workspace:zS,revision:ka,status:k(["active","frozen","abandoned"]),edits:v(LS).max(1e3),createdAt:Ce,updatedAt:Ce,metadata:ki}).strict();Oj.extend({contentHash:W}).strict();const HS=u({kind:k(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:E,contentHash:W.nullable()}).strict(),US=u({id:E,kind:k(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:eu,required:j()}).strict(),$j=u({schemaVersion:x("openpond.harnessImprovementProposal.v1"),id:E,overlay:uc,baseHarnessRelease:se,expectedWorkspace:zS,requestedScope:k(["personal","team","global"]),route:NS,risk:k(["low","review","restricted"]),effects:v(DS).min(1).max(20),evidence:v(HS).min(1).max(1e3),edits:v(LS).min(1).max(1e3),validationPlan:v(US).min(1).max(100),expectedOutcome:eu,createdAt:Ce,metadata:ki}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,r]of e.edits.entries()){r.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const s of r.effects)n.has(s)||t.addIssue({code:"custom",message:`edit effect ${s} 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"]})});$j.extend({contentHash:W}).strict();const Nj=u({schemaVersion:x("openpond.harnessTargetedValidationReceipt.v1"),id:E,proposal:se,validationId:E,kind:US.shape.kind,status:k(["passed","failed","blocked","skipped"]),summary:eu,evidenceRefs:v(HS).max(1e3),createdAt:Ce,metadata:ki}).strict();Nj.extend({contentHash:W}).strict();const Dj=k(["advanced","retained","conflict","rolled_back"]),Lj=u({schemaVersion:x("openpond.harnessAdvanceReceipt.v1"),id:E,workspaceId:E,ownerScope:$S,proposal:se.nullable(),expectedWorkspaceRevision:ka,observedWorkspaceRevision:ka,previousChannelRevision:ka,nextChannelRevision:ka,previousRelease:se.nullable(),nextRelease:se.nullable(),validationReceipts:v(se).max(100),decision:Dj,reason:eu,rollbackOf:se.nullable(),createdAt:Ce,metadata:ki}).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"]})});Lj.extend({contentHash:W}).strict();const zj=u({schemaVersion:x("openpond.harnessOverlayMergeReceipt.v1"),id:E,workspaceId:E,baseHarnessRelease:se,leftOverlay:uc,rightOverlay:uc,decision:k(["merged","conflict"]),mergedOverlay:uc.nullable(),conflictTargets:v(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:x(!0),createdAt:Ce,metadata:ki}).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"]})});zj.extend({contentHash:W}).strict();const qS=u({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:ve(o(),ke()),inputSchemaHash:W,sideEffect:k(["read","write"]),timeoutMs:m().int().positive().max(36e5)}).strict(),Hj=u({id:E,required:j(),scopes:v(o().trim().min(1).max(500)).max(100).default([]),portability:k(["portable","host_adapter","local_only","hosted_only"])}).strict(),BS=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),FS=o().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"),Uj=u({id:BS,label:o().trim().min(1).max(240),description:o().max(4e3),inputSchema:ve(o(),ke()),invocation:st("kind",[u({kind:x("instructions"),instructions:o().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),u({kind:x("agent_action"),actionId:o().trim().min(1).max(240)}).strict()]),skillPaths:v(FS).max(100)}).strict();u({schemaVersion:x("openpond.profileWorkflows.v1"),workflows:v(Uj).max(1e3)}).strict();const qj=u({id:o().trim().min(1).max(240),agentId:o().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:o().trim().min(1).max(240),inputSchema:ve(o(),ke())}).strict();u({schemaVersion:x("openpond.profileWorkflowActions.v1"),actions:v(qj).max(200)}).strict();const Bj=u({schemaVersion:x("openpond.profileWorkflowBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:se,catalogHash:W,workflowId:BS}).strict(),Fj=u({schemaVersion:x("openpond.profileComponentBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:se,target:st("kind",[u({kind:x("profile")}).strict(),u({kind:x("skill"),skillPath:FS}).strict(),u({kind:x("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict(),VS=k(["openpond.lab"]),Zp=u({id:o(),experience:dh.default(lj),provider:xi,modelRef:ln.nullable().optional(),openPondCommandAccessMode:Hc.default(Qd),systemKind:VS.nullable().optional(),hiddenFromDefaultSidebar:j().optional(),parentSessionId:o().nullable().optional(),parentTurnId:o().nullable().optional(),subagentRunId:o().nullable().optional(),subagentRoleId:Si.nullable().optional(),subagentDelegationMode:Zd.nullable().optional(),title:o(),appId:o().nullable(),appName:o().nullable(),workspaceKind:Uc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Xd.nullable().optional(),profileWorkflowBinding:Bj.nullable().optional(),profileComponentBinding:Fj.nullable().optional(),metadata:ve(o(),ke()).optional(),cwd:o().nullable(),codexThreadId:o().nullable(),nativeAgent:u({provider:dt([k(["claude-code","grok-build","opencode"]),vS]),instanceId:o().min(1),sessionId:o().min(1),cwd:o().min(1)}).nullable().optional(),createdAt:o(),updatedAt:o(),status:k(["idle","active","failed","closed"]),runtimeSeconds:m().int().nonnegative().optional(),runtimeRunningSince:o().nullable().optional(),pinned:j(),savedForLater:j().optional(),archived:j(),order:m()});u({id:o(),sessionId:o(),providerTurnId:o().nullable(),modelRef:ln.nullable().optional(),prompt:o(),startedAt:o(),completedAt:o().nullable(),status:k(["in_progress","completed","failed","interrupted"]),error:o().nullable(),metadata:ve(o(),ke()).optional().default({}),createImproveRun:qc.nullable().optional().default(null),profileSnapshot:Ej.nullable().optional(),harnessSnapshot:Mj.nullable().optional()});const Vj=u({id:o().trim().min(1).max(191),agentId:o().trim().min(1).max(191).optional().nullable(),sourcePath:o().trim().min(1).max(2e3).optional().nullable(),sourceActionId:o().trim().min(1).max(191).optional().nullable(),name:o().trim().min(1).max(191).optional().nullable(),label:o().trim().min(1).max(160).optional().nullable(),description:o().trim().max(1e3).optional().nullable(),visibility:o().trim().max(80).optional().nullable(),inputSchema:dt([o().trim().max(191),ve(o(),ke())]).optional().nullable(),outputSchema:dt([o().trim().max(191),ve(o(),ke())]).optional().nullable(),approvalPolicy:ve(o(),ke()).optional().nullable(),artifactPolicy:ve(o(),ke()).optional().nullable(),setupRequirements:v(ve(o(),ke())).optional(),mcp:ve(o(),ke()).optional().nullable(),schedulePolicy:ve(o(),ke()).optional().nullable(),trace:ve(o(),ke()).optional().nullable(),implementation:ve(o(),ke()).optional().nullable(),invokesModel:j().optional()}),Kj=[{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"]}],Wj=u({name:o(),description:o(),relativePath:o(),sourcePath:o(),charCount:m().int().nonnegative(),sourceHash:o(),resourceFiles:v(o()),validationStatus:k(["valid","error"]),validationMessages:v(o())}),KS=u({id:o(),source:x("github"),owner:o(),repo:o(),repositoryUrl:o().url(),requestedRef:o(),resolvedCommit:o(),sourcePath:o(),readmePath:o().nullable(),installedAt:o(),updatedAt:o(),packageHash:o(),skills:v(Wj),validationStatus:k(["valid","error"]),validationMessages:v(o())});KS.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:yi()});u({rootPath:o(),registryPath:o(),extensions:v(KS),error:o().nullable()});u({source:o().trim().min(1),ref:o().trim().min(1).optional()});const mh=k(["openpond_hosted","local_byok","codex_app_server","unknown"]),WS=k(["provider_usage","codex_context_usage","missing"]),Gj=k(["provider_usage_body","provider_response_headers"]),Zj=k(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),Jj=k(["foreground","tool_loop","compaction","subagent","refiner","other"]),GS=k(["user_facing","background","system"]),ZS=k(["started","completed","failed","interrupted"]),ph=k(["composer_selection","prompt_parse","server_parser","model_tool","api"]),JS=k(["chat","settings","goal","create_improve","compaction","system"]),QS=k(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),Qj=u({surface:JS,workflowKind:QS,sessionId:o().trim().min(1).nullable().default(null),turnId:o().trim().min(1).nullable().default(null),goalId:o().trim().min(1).nullable().default(null),subagentRunId:o().trim().min(1).nullable().default(null),subagentRoleId:o().trim().min(1).nullable().default(null),createImproveRunId:o().trim().min(1).nullable().default(null),commandName:o().trim().min(1).max(160).nullable().default(null),commandSource:ph.nullable().default(null),appId:o().trim().min(1).nullable().default(null),workspaceKind:Uc.nullable().default(null),workspaceId:o().trim().min(1).nullable().default(null),localProjectId:o().trim().min(1).nullable().default(null),cloudProjectId:o().trim().min(1).nullable().default(null),sourceEventSequence:m().int().nonnegative().nullable().default(null)}),Yj=u({surface:JS.optional(),workflowKind:QS.optional(),goalId:o().trim().min(1).nullable().optional(),subagentRunId:o().trim().min(1).nullable().optional(),subagentRoleId:o().trim().min(1).nullable().optional(),createImproveRunId:o().trim().min(1).nullable().optional(),commandName:o().trim().min(1).max(160).nullable().optional(),commandSource:ph.nullable().optional()}).strict(),Ys=o().trim().min(1).max(160),Xj=u({id:o().trim().min(1),requestId:o().trim().min(1),requestOrdinal:m().int().nonnegative(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable(),provider:Ys,model:o().trim().min(1),route:mh,source:WS,requestKind:Zj,visibility:GS,status:ZS,startedAt:o().trim().min(1),completedAt:o().trim().min(1).nullable(),durationMs:m().int().nonnegative().nullable(),firstTokenMs:m().int().nonnegative().nullable(),promptTokens:m().int().nonnegative().nullable(),cachedPromptTokens:m().int().nonnegative().nullable(),uncachedPromptTokens:m().int().nonnegative().nullable(),cacheWritePromptTokens:m().int().nonnegative().nullable(),cacheTelemetrySource:Gj.nullable(),completionTokens:m().int().nonnegative().nullable(),totalTokens:m().int().nonnegative().nullable(),errorType:o().trim().min(1).max(160).nullable(),errorMessage:o().trim().min(1).max(2e3).nullable(),attribution:Qj}),YS=u({from:o().trim().min(1),to:o().trim().min(1),bucket:k(["day","all_time"])}),fh=dt([x("all"),GS]),hh=k(["all","started","completed","failed","interrupted","missing"]),eM=u({range:k(["7d","30d","90d","all"]).default("30d"),visibility:fh.default("all"),status:hh.default("all"),provider:Ys.optional(),model:o().trim().min(1).optional()});eM.extend({sessionId:o().trim().min(1).optional(),turnId:o().trim().min(1).optional(),limit:m().int().positive().max(500).default(100)});u({sessionId:o().trim().min(1)});const Xs=u({requests:m().int().nonnegative(),promptTokens:m().int().nonnegative().nullable(),cacheTelemetryRequests:m().int().nonnegative(),cacheHitRequests:m().int().nonnegative(),cachedPromptTokens:m().int().nonnegative().nullable(),uncachedPromptTokens:m().int().nonnegative().nullable(),cacheWritePromptTokens:m().int().nonnegative().nullable(),cacheHitRate:m().min(0).max(1).nullable(),cacheRequestHitRate:m().min(0).max(1).nullable(),cacheTelemetryCoverage:m().min(0).max(1),completionTokens:m().int().nonnegative().nullable(),totalTokens:m().int().nonnegative().nullable(),averageLatencyMs:m().nonnegative().nullable(),p95LatencyMs:m().nonnegative().nullable(),averageFirstTokenMs:m().nonnegative().nullable(),p95FirstTokenMs:m().nonnegative().nullable(),failures:m().int().nonnegative(),failureRate:m().nonnegative(),firstSeenAt:o().trim().min(1),lastSeenAt:o().trim().min(1)}),tM=Xs.extend({provider:Ys,model:o().trim().min(1),route:mh}),nM=Xs.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:Uc.nullable(),workspaceId:o().trim().min(1).nullable()}),aM=Xs.extend({commandName:o().trim().min(1),commandSource:ph.nullable()}),rM=Xs.extend({route:mh}),sM=Xs.extend({status:ZS}),oM=Xs.extend({source:WS}),iM=Xs.extend({cohort:Jj}),cM=u({date:o().trim().min(1),totalTokens:m().int().nonnegative(),requests:m().int().nonnegative(),models:v(u({provider:Ys,model:o().trim().min(1),totalTokens:m().int().nonnegative(),requests:m().int().nonnegative()}))}),lM=u({requests:m().int().nonnegative(),completedRequests:m().int().nonnegative(),failedRequests:m().int().nonnegative(),missingUsageRequests:m().int().nonnegative(),promptTokens:m().int().nonnegative().nullable(),cacheTelemetryRequests:m().int().nonnegative(),cacheHitRequests:m().int().nonnegative(),cachedPromptTokens:m().int().nonnegative().nullable(),uncachedPromptTokens:m().int().nonnegative().nullable(),cacheWritePromptTokens:m().int().nonnegative().nullable(),cacheHitRate:m().min(0).max(1).nullable(),cacheRequestHitRate:m().min(0).max(1).nullable(),cacheTelemetryCoverage:m().min(0).max(1),completionTokens:m().int().nonnegative().nullable(),totalTokens:m().int().nonnegative().nullable(),averageLatencyMs:m().nonnegative().nullable(),p95LatencyMs:m().nonnegative().nullable(),averageFirstTokenMs:m().nonnegative().nullable(),p95FirstTokenMs:m().nonnegative().nullable(),failureRate:m().nonnegative(),activeModelCount:m().int().nonnegative(),peakDailyTokens:m().int().nonnegative(),longestRequestMs:m().int().nonnegative().nullable(),activeDays:m().int().nonnegative(),currentStreakDays:m().int().nonnegative(),longestStreakDays:m().int().nonnegative()});u({generatedAt:o().trim().min(1),range:YS,filters:u({visibility:fh,status:hh,provider:Ys.nullable(),model:o().trim().min(1).nullable()}),totals:lM,daily:v(cM),models:v(tM),threads:v(nM),commands:v(aM),routes:v(rM),statuses:v(sM),sources:v(oM),cohorts:v(iM)});u({generatedAt:o().trim().min(1),range:YS,filters:u({visibility:fh,status:hh,provider:Ys.nullable(),model:o().trim().min(1).nullable(),sessionId:o().trim().min(1).nullable(),turnId:o().trim().min(1).nullable()}),limit:m().int().positive(),hasMore:j(),records:v(Xj)});const dM=u({turnId:o().trim().min(1),requests:m().int().nonnegative(),cacheTelemetryRequests:m().int().nonnegative(),cachedPromptTokens:m().int().nonnegative().nullable(),uncachedPromptTokens:m().int().nonnegative().nullable(),cacheWritePromptTokens:m().int().nonnegative().nullable(),cacheHitRate:m().min(0).max(1).nullable(),cacheTelemetryCoverage:m().min(0).max(1),providers:v(Ys)});u({generatedAt:o().trim().min(1),sessionId:o().trim().min(1),turns:v(dM)});const uM=k(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);u({type:uM,title:o().trim().min(1),summary:o().trim().min(1),severity:k(["nit","concern","blocker"]),payload:ve(o(),ke()).default({})});const mM=k(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),pM=k(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),fM=k(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),hM=u({kind:x("integration"),provider:mM,appIds:v(pM).min(1).max(4),setupSurfaces:v(fM).min(1).max(4),connectionIds:v(o().trim().min(1)).max(8).optional(),capabilities:v(o().trim().min(1)).max(64).optional()}).strict(),Hs={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},gM=k(["image","text","file"]),vM=u({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(240),contentType:o().trim().min(1).max(160)}),bM=u({sessionId:o().trim().min(1).max(200),turnId:o().trim().min(1).max(200),attachmentId:o().trim().min(1).max(200),storageName:o().trim().min(1).max(1024),contentType:o().trim().min(1).max(160)}),XS=u({id:o().trim().min(1),name:o().trim().min(1).max(240),mediaType:o().trim().min(1).max(160),sizeBytes:m().int().nonnegative().max(Hs.maxAttachmentBytes),kind:gM,lineCount:m().int().nonnegative().max(Hs.maxAttachmentBytes+1).optional(),relativePath:o().trim().min(1).max(1024).optional(),text:o().max(Hs.maxTextChars).optional(),contentsBase64:o().max(Hs.maxAttachmentBase64Chars).optional()}),yM=XS.omit({text:!0,contentsBase64:!0}).extend({imagePreview:vM.optional(),filePreview:bM.optional()});u({experience:dh.optional(),provider:xi.default(Ks),modelRef:ln.optional(),openPondCommandAccessMode:Hc.optional(),systemKind:VS.nullable().optional(),hiddenFromDefaultSidebar:j().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:Si.nullable().optional(),subagentDelegationMode:Zd.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:Uc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Xd.nullable().optional(),profileWorkflowBinding:Zp.shape.profileWorkflowBinding,profileComponentBinding:Zp.shape.profileComponentBinding,metadata:ve(o(),ke()).optional(),cwd:o().nullable().optional(),title:o().optional(),autoTitlePrompt:o().trim().min(1).max(2e4).optional()});u({teamId:o().trim().min(1),projectName:o().trim().min(1).max(120).optional(),branch:o().trim().min(1).max(120).optional(),chatSessionId:o().trim().min(1).max(200).optional(),displayPrompt:o().trim().min(1).max(2e3).optional()});u({branch:o().trim().min(1).max(120).optional()});u({prompt:o().min(1),workflowInput:ke().optional(),metadata:ve(o(),ke()).optional(),usageAttribution:Yj.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:ln.optional(),mentionedAppIds:v(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:v(hM).max(8).optional(),openPondActionCatalog:v(Vj).max(100).optional(),attachments:v(XS).max(Hs.maxAttachments).optional(),createImproveRun:qc.optional().nullable(),approvalPolicy:k(["untrusted","on-failure","on-request","never"]).default("on-request"),sandbox:k(["read-only","workspace-write","danger-full-access"]).default("workspace-write"),codexPermissionMode:ch.default("default"),codexReasoningEffort:Yd.optional()});u({prompt:o().min(1),error:o().min(1),target:k(["cloud_workspace","hybrid_sandbox"])});u({reason:k(["manual"]).default("manual"),model:o().nullable().optional(),modelRef:ln.optional()});u({experience:dh.optional(),provider:xi.optional(),modelRef:ln.nullable().optional(),openPondCommandAccessMode:Hc.optional(),pinned:j().optional(),savedForLater:j().optional(),archived:j().optional(),order:m().optional(),title:o().optional(),parentSessionId:o().trim().min(1).max(200).nullable().optional(),parentTurnId:o().trim().min(1).max(200).nullable().optional(),subagentRunId:o().trim().min(1).max(200).nullable().optional(),subagentRoleId:Si.nullable().optional(),subagentDelegationMode:Zd.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:Uc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Xd.nullable().optional(),metadata:ve(o(),ke()).optional(),cwd:o().nullable().optional()});u({command:o().trim().min(1),cwd:o().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:m().int().min(1).max(3600).optional()});u({appIds:v(o()).min(1)});u({expectedRevision:o().optional(),defaultChatProvider:xi.optional(),defaultChatModel:o().min(1).optional(),defaultChatModelRef:ln.nullable().optional(),subagents:kc.optional(),codexPermissionMode:ch.optional(),codexReasoningEffort:Yd.optional(),openPondCommandAccessMode:Hc.optional(),defaultBranchPrefix:o().trim().max(48).optional(),defaultNewProjectDirectory:o().trim().max(4096).optional(),defaultTeamId:o().trim().max(191).nullable().optional(),advancedWorkspaceControls:j().optional(),steerActiveResponses:j().optional(),contextCompaction:Kp.optional(),training:Wp.optional(),sidebarWidth:m().int().min(244).max(560).optional(),diffPanelWidth:m().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Vp.optional(),editor:kd.optional()});u({message:o().trim().min(1).max(4e3),surface:o().trim().min(1).max(120).default("app"),stack:o().max(12e3).nullable().optional(),context:ve(o(),ke()).optional()}).strict();u({activeTemplateId:lh,templateName:o().trim().min(1).max(80),soul:o().trim().min(1).max(8e3),saveAsNew:j().optional().default(!1)});u({decision:k(["accept","acceptForSession","decline","cancel"]),answers:ve(o().min(1).max(2e3),o().trim().min(1).max(8e3)).optional()});u({branch:o().trim().min(1).max(240).nullable().optional(),surface:k(["desktop","terminal"])});u({handle:o().min(1),baseUrl:o().nullable().optional()});u({handle:o().min(1),baseUrl:o().nullable().optional()});u({handle:o().min(1).optional(),apiKey:o().min(1),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:j().optional()});u({handle:o().min(1),currentBaseUrl:o().nullable().optional(),apiKey:o().min(1).optional(),baseUrl:o().nullable().optional(),apiBaseUrl:o().nullable().optional(),chatApiBaseUrl:o().nullable().optional(),environment:o().nullable().optional(),setActive:j().optional()});const Bc=u({id:o().trim().min(1).max(200),title:o().trim().min(1).max(240),sourceTaskId:o().trim().min(1).max(200),sourceTurnId:o().trim().min(1).max(200),revision:m().int().positive().default(1),createdAt:o().datetime()}),Fc=u({kind:k(["structural","visual","test","user_review"]),status:k(["passed","failed","not_run"]),label:o().trim().min(1).max(240),detail:o().trim().max(4e3).nullable().optional(),ref:o().trim().max(4096).nullable().optional()}),ex=u({kind:x("local"),path:o().trim().min(1).max(4096),deviceId:o().trim().min(1).max(200)}),tx=u({kind:x("managed"),fileId:o().trim().min(1).max(200),downloadPath:o().trim().min(1).max(4096)}),SM=u({kind:x("external"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url().nullable()}),gh=Bc.extend({kind:x("file"),contentType:o().trim().min(1).max(200),sizeBytes:m().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),location:st("kind",[ex,tx,SM]),validation:v(Fc).max(32).default([])}),xM=Bc.extend({kind:x("source_change"),projectId:o().trim().min(1).max(200),ref:o().trim().min(1).max(500),url:o().url().nullable(),validation:v(Fc).max(32).default([])}),kM=Bc.extend({kind:x("deployment"),deploymentId:o().trim().min(1).max(200),url:o().url(),validation:v(Fc).max(32).default([])}),wM=Bc.extend({kind:x("external_resource"),provider:o().trim().min(1).max(120),resourceId:o().trim().min(1).max(500),url:o().url(),contentType:o().trim().min(1).max(200).nullable(),validation:v(Fc).max(32).default([])}),nx=u({id:o().trim().min(1).max(191),label:o().trim().min(1).max(160).nullable(),description:o().trim().max(1e3).nullable(),inputSchema:ve(o(),ke()).nullable(),outputSchema:ve(o(),ke()).nullable(),schedulePolicy:ve(o(),ke()).nullable()}),ax=u({base:o().trim().min(1).max(200),resources:ve(o(),ke()),modelPolicy:ve(o(),ke()).nullable(),setup:ve(o(),ke()).nullable()}),IM=u({id:o().trim().min(1).max(200),kind:k(["sdk_validation","sdk_eval"]),status:k(["passed","failed"]),summary:o().trim().min(1).max(2e3),artifactPath:o().trim().min(1).max(4096),artifactSha256:o().regex(/^[a-f0-9]{64}$/)}),_M=u({path:o().trim().min(1).max(4096),sizeBytes:m().int().nonnegative(),sha256:o().regex(/^[a-f0-9]{64}$/),contentsBase64:o()});u({schema:x("openpond.agent-package.v1"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),title:o().trim().min(1).max(240),source:u({files:v(_M).min(1).max(1e3),totalSizeBytes:m().int().nonnegative()}),manifest:ve(o(),ke()),actions:v(nx).min(1).max(256),runtimeRequirements:ax,receipts:v(IM).min(2).max(64)});const CM=Bc.extend({kind:x("agent_package"),agentId:o().trim().min(1).max(191),versionId:o().trim().min(1).max(200),digest:o().regex(/^[a-f0-9]{64}$/),packageFileId:o().trim().min(1).max(200),manifestFileId:o().trim().min(1).max(200),actions:v(nx).min(1).max(256),runtimeRequirements:ax,validationReceiptIds:v(o().trim().min(1).max(200)).min(1).max(32),evalReceiptIds:v(o().trim().min(1).max(200)).min(1).max(32),sourceFileCount:m().int().positive(),sourceSizeBytes:m().int().nonnegative(),location:st("kind",[ex,tx]),validation:v(Fc).max(32).default([])}),y8=st("kind",[gh,xM,kM,wM,CM]);u({outputs:v(gh)});const vh=ve(o(),ke());u({userId:o(),role:k(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const RM=u({userId:o(),role:k(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:m().int().nonnegative()}),PM=u({id:o(),messageId:o(),refType:k(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:vh,createdAt:o()}),rx=u({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:x("image"),name:o(),mediaType:k(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:m().int().positive(),status:k(["pending","ready","failed"]),createdAt:o(),readyAt:o().nullable()});u({attachment:rx,uploadUrl:o().url().nullable(),uploadHeaders:ve(o(),o()),expiresAt:o().nullable()});u({url:o().url(),expiresAt:o()});const bh=u({id:o(),threadId:o(),teamId:o(),clientRequestId:o().nullable(),authorType:k(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:m().int().nonnegative(),kind:k(["text","system","command_result"]),body:o(),metadata:vh,editedAt:o().nullable(),deletedAt:o().nullable(),createdAt:o(),refs:v(PM),attachments:v(rx)}),TM=u({id:o(),teamId:o(),kind:k(["general","dm","group","channel"]),title:o().nullable(),createdByUserId:o(),lastMessageId:o().nullable(),lastMessageSequence:m().int().nonnegative(),lastMessageAt:o(),createdAt:o(),updatedAt:o(),unreadCount:m().int().nonnegative(),pinnedAt:o().nullable(),mutedAt:o().nullable(),archivedAt:o().nullable(),participants:v(RM),lastMessage:bh.nullable()});u({thread:TM,messages:v(bh),hasMoreBefore:j()});u({threadId:o(),mutedAt:o().nullable()});const AM=k(["pending","running","completed","failed","interrupted","cancelled"]),Ov=u({id:o(),conversationId:o(),threadId:o(),teamId:o(),requestedByUserId:o(),executorUserId:o().nullable(),providerId:o(),modelId:o(),clientRequestId:o(),baseMessageSequence:m().int().nonnegative(),status:AM,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),EM=u({id:o(),conversationId:o(),sequence:m().int().nonnegative(),role:k(["user","assistant","system","action"]),body:o(),createdByUserId:o().nullable(),createdAt:o()});u({conversationId:o(),parentThreadId:o(),parentMessageId:o(),teamId:o(),title:o().nullable(),providerId:o().nullable(),modelId:o(),createdByUserId:o(),messages:v(EM),turns:v(Ov),activeTurn:Ov.nullable(),createdAt:o(),updatedAt:o()});const sx=u({id:m().int().nonnegative(),teamId:o(),threadId:o(),conversationId:o().nullable(),type:k(["thread.created","message.created","message.updated","message.deleted","read.updated","ai_thread.created","ai_turn.updated"]),payload:vh,createdAt:o()});u({events:v(sx),cursor:m().int().nonnegative(),hasMore:j()});u({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),teamId:o().min(1),userId:o().min(1)});const yh=ve(o(),ke()),Ia=o().nullable(),jM=k(["draft","published","archived"]),Sh=k(["owner","admin","member"]),ox=k(["active","left"]),ix=k(["mentions","all","none"]),cx=k(["public_preview","members"]),MM=k(["members","admins"]),OM=u({canPreview:j(),canJoin:j(),canLeave:j(),canRead:j(),canPost:j(),canUpload:j(),canMention:j(),canManage:j(),requiresRulesAcceptance:j(),currentRulesVersionId:o().nullable()}),lx=u({id:o(),communityId:o(),version:m().int().positive(),title:o(),requiresReacceptance:j(),publishedAt:o()}),$M=lx.extend({bodyMarkdown:o(),contentHash:o()}),NM=u({role:Sh,status:ox,notificationMode:ix}),DM=u({id:o(),communityId:o(),userId:o(),role:Sh,status:ox,notificationMode:ix,joinedAt:o(),leftAt:Ia,createdAt:o(),updatedAt:o()}),dx=u({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:jM,visibility:k(["public","private"]),joinPolicy:k(["open","closed"]),historyVisibility:cx,featuredAt:Ia,publishedAt:Ia,archivedAt:Ia,memberCount:m().int().nonnegative(),membership:NM.nullable(),capabilities:OM,currentRules:lx.nullable()});u({items:v(dx),nextCursor:o().nullable()});const ux=u({lastReadSequence:m().int().nonnegative(),lastReadAt:Ia.optional(),mutedAt:Ia,pinnedAt:Ia}),xh=u({id:o(),communityId:o(),chatThreadId:o().nullable(),slug:o(),displayName:o(),topic:o(),position:m().int().nonnegative(),visibility:cx,postingPolicy:MM,isDefault:j(),archivedAt:Ia,lastMessageSequence:m().int().nonnegative(),unreadCount:m().int().nonnegative(),readState:ux.nullable()});dx.omit({currentRules:!0}).extend({currentRules:$M.nullable(),channels:v(xh),previewMessageLimit:m().int().positive()});const LM=u({id:o(),messageId:o(),refType:k(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:yh,createdAt:o()}),mx=u({id:o(),messageId:o().nullable(),clientAttachmentId:o(),kind:x("image"),name:o(),mediaType:k(["image/png","image/jpeg","image/webp","image/gif"]),sizeBytes:m().int().positive(),status:k(["pending","ready","failed"]),createdAt:o(),readyAt:Ia});u({attachment:mx,uploadUrl:o().url().nullable(),uploadHeaders:ve(o(),o()),expiresAt:Ia});u({url:o().url(),expiresAt:o()});const px=u({id:o(),threadId:o(),teamId:yi(),clientRequestId:o().nullable(),authorType:k(["user","agent","system"]),authorUserId:o().nullable(),authorAgentId:o().nullable(),sequence:m().int().nonnegative(),kind:k(["text","system","command_result"]),body:o(),metadata:yh,editedAt:Ia,deletedAt:Ia,createdAt:o(),refs:v(LM),attachments:v(mx)});u({messages:v(px),hasMoreBefore:j(),channelId:o(),readState:ux.omit({lastReadAt:!0}).nullable(),preview:j()});const zM=u({userId:o(),handle:o().nullable(),name:o().nullable(),role:Sh});u({items:v(zM),nextCursor:o().nullable()});const fx=u({id:m().int().nonnegative(),communityId:o(),channelId:o(),threadId:o(),type:k(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:yh,createdAt:o()});u({events:v(fx),cursor:m().int().nonnegative(),hasMore:j()});u({httpUrl:o().min(1),realtimeUrl:o().min(1),region:o().min(1),token:o().min(1),expiresAt:o().min(1),communityId:o().min(1),userId:o().min(1),channel:o().min(1)});u({membership:DM,channels:v(xh)});u({channels:v(xh)});const HM=u({candidateId:o().min(1).max(240),frozenRevision:m().int().positive(),frozenHash:o().regex(/^[a-f0-9]{64}$/),harnessRelease:se,protectedClosureHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),$v=o().trim().min(1).max(240),UM=o().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."),Vc=u({schemaVersion:x("openpond.tasksetMetricPolicy.v1"),primaryMetric:$v,aggregation:k(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:k(["zero","exclude"]),taskWeights:ve($v,m().positive().max(1e6)).optional(),customAggregator:u({module:UM,exportName:o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),contentHash:W,timeoutMs:m().int().positive().max(3e5),networkPolicy:x("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."})}),qM=u({schemaVersion:x("openpond.tasksetMetricResult.v1"),runManifest:se,tasksetRelease:se,policy:Vc,policyHash:W,receiptRefs:v(se).min(1).max(1e6),includedCount:m().int().nonnegative(),missingRewardCount:m().int().nonnegative(),excludedCount:m().int().nonnegative(),value:m().min(0).max(1).nullable()}).strict(),hx=qM.extend({contentHash:W}).strict(),Wt=E,ts=W,gx=u({id:Wt,revision:m().int().positive(),contentHash:ts}).strict(),kh=u({kind:x("owner_attested_local"),ownerActorId:Wt,teamId:Wt,executionHash:ts,configurationHash:ts,retainedAttemptHash:ts,traceHash:ts,publicationCutoffHash:ts}).strict(),BM=kh.omit({publicationCutoffHash:!0,kind:!0}).extend({kind:x("native_local")}).strict(),FM=u({origin:kh,executionId:Wt,receiptId:Wt,taskId:Wt,targetId:Wt,familyKey:Wt,split:k(["train","validation","test","frozen_eval"]),input:ve(o(),ke()),policyVisibleContext:ve(o(),ke()),output:o().nullable(),error:o().nullable(),events:v(ve(o(),ke())).max(1e3),coverage:u({sourceEventCount:m().int().nonnegative().max(2e4),publishedEventCount:m().int().nonnegative().max(1e3),traceLimited:j(),artifactsIncluded:x(!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."}),Qe(e.events)!==e.origin.publicationCutoffHash&&t.addIssue({code:"custom",message:"Published trace cutoff changed."})}),VM=u({schemaVersion:x("openpond.humanLocalEvidenceExport.v1"),actorId:Wt,scope:Wt,projectId:Wt,dataset:gx,graderId:Wt,compiledGraderHash:ts,attempts:v(FM).min(1).max(2),sealedAt:Ce}).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."})}),KM=VM.safeExtend({contentHash:ts}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;Qe(a)!==n&&t.addIssue({code:"custom",message:"Local evidence export bytes changed."})}),vx=u({endpoint:x("export_local"),scope:Wt,projectId:Wt,graderId:Wt,selections:v(u({executionId:Wt,receiptId:Wt}).strict()).min(1).max(2)}).strict(),WM=u({endpoint:x("publish_local"),scope:Wt,projectId:Wt,operationId:Wt,audience:v(Wt).max(100),workspaceVisible:j(),evidence:KM}).strict(),GM=vx.omit({endpoint:!0}).extend({endpoint:x("share_local"),operationId:Wt,audience:v(Wt).max(100),workspaceVisible:j()}).strict(),ZM=u({endpoint:x("local_publications"),scope:Wt,executionId:Wt}).strict(),JM=u({endpoint:x("revoke_local"),scope:Wt,publication:gx}).strict();var bx=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},QM=bx((e,t)=>{"use strict";t.exports=function n(a,r){if(a===r)return!0;if(a&&r&&typeof a=="object"&&typeof r=="object"){if(a.constructor!==r.constructor)return!1;var s,i,c;if(Array.isArray(a)){if(s=a.length,s!=r.length)return!1;for(i=s;i--!==0;)if(!n(a[i],r[i]))return!1;return!0}if(a.constructor===RegExp)return a.source===r.source&&a.flags===r.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===r.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===r.toString();if(c=Object.keys(a),s=c.length,s!==Object.keys(r).length)return!1;for(i=s;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,c[i]))return!1;for(i=s;i--!==0;){var d=c[i];if(!n(a[d],r[d]))return!1}return!0}return a!==a&&r!==r}}),YM=bx(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=QM();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),Nv=Nt,Dv={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"}}},XM=Object.prototype.hasOwnProperty,eO=YM().default,vt={validate:Nt};function pa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:s={}}={}){let i=null,c=0,d=pa.evaluated;if(d.dynamicProps&&(d.props=void 0),d.dynamicItems&&(d.items=void 0),c===0)if(e&&typeof e=="object"&&!Array.isArray(e))for(let p in e){let f=c;vt.validate(e[p],{instancePath:t+"/"+p.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:p,rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=f===c;if(!l)break}else return pa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return pa.errors=i,c===0}pa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function En(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:s={}}={}){let i=null,c=0,d=En.evaluated;if(d.dynamicProps&&(d.props=void 0),d.dynamicItems&&(d.items=void 0),c===0)if(Array.isArray(e)){if(e.length>32)return En.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return En.errors=[{instancePath:t,schemaPath:"#/minItems",keyword:"minItems",params:{limit:1}}],!1;{var l=!0;let p=e.length;for(let f=0;f<p;f++){let S=c;vt.validate(e[f],{instancePath:t+"/"+f,parentData:e,parentDataProperty:f,rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=S===c;if(!l)break}}}else return En.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return En.errors=i,c===0}En.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var tO={enum:["array","boolean","integer","null","number","object","string"]};function mr(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:s={}}={}){let i=null,c=0,d=mr.evaluated;return d.dynamicProps&&(d.props=void 0),d.dynamicItems&&(d.items=void 0),e==="array"||e==="boolean"||e==="integer"||e==="null"||e==="number"||e==="object"||e==="string"?(mr.errors=i,c===0):(mr.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:tO.enum}}],!1)}mr.evaluated={dynamicProps:!1,dynamicItems:!1};function Dt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:s={}}={}){let i=null,c=0,d=Dt.evaluated;return d.dynamicProps&&(d.props=void 0),d.dynamicItems&&(d.items=void 0),typeof e=="number"&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e=="number"&&isFinite(e)&&(e<0||isNaN(e))?(Dt.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):(Dt.errors=i,c===0):(Dt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}Dt.evaluated={dynamicProps:!1,dynamicItems:!1};function xa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:s={}}={}){let i=null,c=0,d=xa.evaluated;if(d.dynamicProps&&(d.props=void 0),d.dynamicItems&&(d.items=void 0),c===0)if(Array.isArray(e)){var l=!0;let p=e.length;for(let f=0;f<p;f++){let S=c;if(typeof e[f]!="string")return xa.errors=[{instancePath:t+"/"+f,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var l=S===c;if(!l)break}if(l){let f=e.length,S;if(f>1){let b={};for(;f--;){let I=e[f];if(typeof I=="string"){if(typeof b[I]=="number")return S=b[I],xa.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:f,j:S}}],!1;b[I]=f}}}}}else return xa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return xa.errors=i,c===0}xa.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function Nt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:r=e,dynamicAnchors:s={}}={}){let i=null,c=0,d=Nt.evaluated;if(d.dynamicProps&&(d.props=void 0),d.dynamicItems&&(d.items=void 0),!(e&&typeof e=="object"&&!Array.isArray(e))&&typeof e!="boolean")return Nt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:Dv.type}}],!1;if(c===0&&e&&typeof e=="object"&&!Array.isArray(e)){let b=c;for(let I in e)if(!XM.call(Dv.properties,I))return Nt.errors=[{instancePath:t,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:I}}],!1;if(b===c){if(e.$schema!==void 0){let I=c;if(e.$schema!=="https://json-schema.org/draft/2020-12/schema")return Nt.errors=[{instancePath:t+"/$schema",schemaPath:"#/properties/%24schema/const",keyword:"const",params:{allowedValue:"https://json-schema.org/draft/2020-12/schema"}}],!1;var l=I===c}else var l=!0;if(l){if(e.$ref!==void 0){let C=c;if(typeof e.$ref!="string")return Nt.errors=[{instancePath:t+"/$ref",schemaPath:"#/properties/%24ref/type",keyword:"type",params:{type:"string"}}],!1;var l=C===c}else var l=!0;if(l){if(e.$comment!==void 0){let P=c;if(typeof e.$comment!="string")return Nt.errors=[{instancePath:t+"/$comment",schemaPath:"#/properties/%24comment/type",keyword:"type",params:{type:"string"}}],!1;var l=P===c}else var l=!0;if(l){if(e.$defs!==void 0){let _=c;pa(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:r,dynamicAnchors:s})||(i=i===null?pa.errors:i.concat(pa.errors),c=i.length);var l=_===c}else var l=!0;if(l){if(e.properties!==void 0){let M=c;pa(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:r,dynamicAnchors:s})||(i=i===null?pa.errors:i.concat(pa.errors),c=i.length);var l=M===c}else var l=!0;if(l){if(e.dependentSchemas!==void 0){let A=c;pa(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:r,dynamicAnchors:s})||(i=i===null?pa.errors:i.concat(pa.errors),c=i.length);var l=A===c}else var l=!0;if(l){if(e.allOf!==void 0){let T=c;En(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:r,dynamicAnchors:s})||(i=i===null?En.errors:i.concat(En.errors),c=i.length);var l=T===c}else var l=!0;if(l){if(e.anyOf!==void 0){let y=c;En(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:r,dynamicAnchors:s})||(i=i===null?En.errors:i.concat(En.errors),c=i.length);var l=y===c}else var l=!0;if(l){if(e.oneOf!==void 0){let w=c;En(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:r,dynamicAnchors:s})||(i=i===null?En.errors:i.concat(En.errors),c=i.length);var l=w===c}else var l=!0;if(l){if(e.prefixItems!==void 0){let R=c;En(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:r,dynamicAnchors:s})||(i=i===null?En.errors:i.concat(En.errors),c=i.length);var l=R===c}else var l=!0;if(l){if(e.items!==void 0){let O=c;vt.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=O===c}else var l=!0;if(l){if(e.additionalProperties!==void 0){let z=c;vt.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=z===c}else var l=!0;if(l){if(e.not!==void 0){let $=c;vt.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=$===c}else var l=!0;if(l){if(e.if!==void 0){let V=c;vt.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=V===c}else var l=!0;if(l){if(e.then!==void 0){let Y=c;vt.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=Y===c}else var l=!0;if(l){if(e.else!==void 0){let re=c;vt.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=re===c}else var l=!0;if(l){if(e.contains!==void 0){let ee=c;vt.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=ee===c}else var l=!0;if(l){if(e.unevaluatedProperties!==void 0){let H=c;vt.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=H===c}else var l=!0;if(l){if(e.unevaluatedItems!==void 0){let F=c;vt.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=F===c}else var l=!0;if(l){if(e.propertyNames!==void 0){let J=c;vt.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:r,dynamicAnchors:s})||(i=i===null?vt.validate.errors:i.concat(vt.validate.errors),c=i.length);var l=J===c}else var l=!0;if(l){if(e.type!==void 0){let K=e.type,B=c,ne=c,G=!1,te=c;mr(K,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:r,dynamicAnchors:s})||(i=i===null?mr.errors:i.concat(mr.errors),c=i.length);var f=te===c;G=G||f;let oe=c;if(c===oe)if(Array.isArray(K))if(K.length<1){let me={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/minItems",keyword:"minItems",params:{limit:1}};i===null?i=[me]:i.push(me),c++}else{var p=!0;let me=K.length;for(let Re=0;Re<me;Re++){let Q=c;mr(K[Re],{instancePath:t+"/type/"+Re,parentData:K,parentDataProperty:Re,rootData:r,dynamicAnchors:s})||(i=i===null?mr.errors:i.concat(mr.errors),c=i.length);var p=Q===c;if(!p)break}if(p){let Re=K.length,Q;if(Re>1){e:for(;Re--;)for(Q=Re;Q--;)if(eO(K[Re],K[Q])){let xe={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/uniqueItems",keyword:"uniqueItems",params:{i:Re,j:Q}};i===null?i=[xe]:i.push(xe),c++;break e}}}}else{let me={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf/1/type",keyword:"type",params:{type:"array"}};i===null?i=[me]:i.push(me),c++}var f=oe===c;if(G=G||f,G)c=ne,i!==null&&(ne?i.length=ne:i=null);else{let me={instancePath:t+"/type",schemaPath:"#/properties/type/anyOf",keyword:"anyOf",params:{}};return i===null?i=[me]:i.push(me),c++,Nt.errors=i,!1}var l=B===c}else var l=!0;if(l){if(e.enum!==void 0){let B=e.enum,ne=c;if(c===ne)if(Array.isArray(B)){if(B.length<1)return Nt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return Nt.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/type",keyword:"type",params:{type:"array"}}],!1;var l=ne===c}else var l=!0;if(l){if(e.title!==void 0){let ne=c;if(typeof e.title!="string")return Nt.errors=[{instancePath:t+"/title",schemaPath:"#/properties/title/type",keyword:"type",params:{type:"string"}}],!1;var l=ne===c}else var l=!0;if(l){if(e.description!==void 0){let G=c;if(typeof e.description!="string")return Nt.errors=[{instancePath:t+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"}}],!1;var l=G===c}else var l=!0;if(l){if(e.examples!==void 0){let te=c;if(!Array.isArray(e.examples))return Nt.errors=[{instancePath:t+"/examples",schemaPath:"#/properties/examples/type",keyword:"type",params:{type:"array"}}],!1;var l=te===c}else var l=!0;if(l){if(e.readOnly!==void 0){let oe=c;if(typeof e.readOnly!="boolean")return Nt.errors=[{instancePath:t+"/readOnly",schemaPath:"#/properties/readOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var l=oe===c}else var l=!0;if(l){if(e.writeOnly!==void 0){let be=c;if(typeof e.writeOnly!="boolean")return Nt.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var l=be===c}else var l=!0;if(l){if(e.deprecated!==void 0){let me=c;if(typeof e.deprecated!="boolean")return Nt.errors=[{instancePath:t+"/deprecated",schemaPath:"#/properties/deprecated/type",keyword:"type",params:{type:"boolean"}}],!1;var l=me===c}else var l=!0;if(l){if(e.multipleOf!==void 0){let Re=e.multipleOf,Q=c;if(c===Q)if(typeof Re=="number"&&isFinite(Re)){if(Re<=0||isNaN(Re))return Nt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return Nt.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/type",keyword:"type",params:{type:"number"}}],!1;var l=Q===c}else var l=!0;if(l){if(e.maximum!==void 0){let Q=e.maximum,xe=c;if(!(typeof Q=="number"&&isFinite(Q)))return Nt.errors=[{instancePath:t+"/maximum",schemaPath:"#/properties/maximum/type",keyword:"type",params:{type:"number"}}],!1;var l=xe===c}else var l=!0;if(l){if(e.exclusiveMaximum!==void 0){let xe=e.exclusiveMaximum,je=c;if(!(typeof xe=="number"&&isFinite(xe)))return Nt.errors=[{instancePath:t+"/exclusiveMaximum",schemaPath:"#/properties/exclusiveMaximum/type",keyword:"type",params:{type:"number"}}],!1;var l=je===c}else var l=!0;if(l){if(e.minimum!==void 0){let je=e.minimum,De=c;if(!(typeof je=="number"&&isFinite(je)))return Nt.errors=[{instancePath:t+"/minimum",schemaPath:"#/properties/minimum/type",keyword:"type",params:{type:"number"}}],!1;var l=De===c}else var l=!0;if(l){if(e.exclusiveMinimum!==void 0){let De=e.exclusiveMinimum,He=c;if(!(typeof De=="number"&&isFinite(De)))return Nt.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var l=He===c}else var l=!0;if(l){if(e.maxLength!==void 0){let He=c;Dt(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:r,dynamicAnchors:s})||(i=i===null?Dt.errors:i.concat(Dt.errors),c=i.length);var l=He===c}else var l=!0;if(l){if(e.minLength!==void 0){let Ie=c;Dt(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:r,dynamicAnchors:s})||(i=i===null?Dt.errors:i.concat(Dt.errors),c=i.length);var l=Ie===c}else var l=!0;if(l){if(e.maxItems!==void 0){let Me=c;Dt(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:r,dynamicAnchors:s})||(i=i===null?Dt.errors:i.concat(Dt.errors),c=i.length);var l=Me===c}else var l=!0;if(l){if(e.minItems!==void 0){let Te=c;Dt(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:r,dynamicAnchors:s})||(i=i===null?Dt.errors:i.concat(Dt.errors),c=i.length);var l=Te===c}else var l=!0;if(l){if(e.maxContains!==void 0){let N=c;Dt(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:r,dynamicAnchors:s})||(i=i===null?Dt.errors:i.concat(Dt.errors),c=i.length);var l=N===c}else var l=!0;if(l){if(e.minContains!==void 0){let q=c;Dt(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:r,dynamicAnchors:s})||(i=i===null?Dt.errors:i.concat(Dt.errors),c=i.length);var l=q===c}else var l=!0;if(l){if(e.maxProperties!==void 0){let X=c;Dt(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:r,dynamicAnchors:s})||(i=i===null?Dt.errors:i.concat(Dt.errors),c=i.length);var l=X===c}else var l=!0;if(l){if(e.minProperties!==void 0){let U=c;Dt(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:r,dynamicAnchors:s})||(i=i===null?Dt.errors:i.concat(Dt.errors),c=i.length);var l=U===c}else var l=!0;if(l){if(e.uniqueItems!==void 0){let ae=c;if(typeof e.uniqueItems!="boolean")return Nt.errors=[{instancePath:t+"/uniqueItems",schemaPath:"#/properties/uniqueItems/type",keyword:"type",params:{type:"boolean"}}],!1;var l=ae===c}else var l=!0;if(l){if(e.required!==void 0){let de=c;xa(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:r,dynamicAnchors:s})||(i=i===null?xa.errors:i.concat(xa.errors),c=i.length);var l=de===c}else var l=!0;if(l){if(e.dependentRequired!==void 0){let ye=e.dependentRequired,Oe=c;if(c===Oe)if(ye&&typeof ye=="object"&&!Array.isArray(ye))for(let Ge in ye){let yt=c;xa(ye[Ge],{instancePath:t+"/dependentRequired/"+Ge.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:ye,parentDataProperty:Ge,rootData:r,dynamicAnchors:s})||(i=i===null?xa.errors:i.concat(xa.errors),c=i.length);var S=yt===c;if(!S)break}else return Nt.errors=[{instancePath:t+"/dependentRequired",schemaPath:"#/properties/dependentRequired/type",keyword:"type",params:{type:"object"}}],!1;var l=Oe===c}else var l=!0;if(l){if(e.contentEncoding!==void 0){let Oe=c;if(typeof e.contentEncoding!="string")return Nt.errors=[{instancePath:t+"/contentEncoding",schemaPath:"#/properties/contentEncoding/type",keyword:"type",params:{type:"string"}}],!1;var l=Oe===c}else var l=!0;if(l)if(e.contentMediaType!==void 0){let Oe=c;if(typeof e.contentMediaType!="string")return Nt.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var l=Oe===c}else var l=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return Nt.errors=i,c===0}Nt.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const Lv="https://json-schema.org/draft/2020-12/schema",nO=1048576,aO=32768,rO=new Set(["properties","$defs","dependentSchemas"]),sO=new Set(["allOf","anyOf","oneOf","prefixItems"]),oO=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Aa(e,t=nO){const n=[{value:e,depth:0}],a=new Set;let r=0;for(;n.length;){const s=n.pop();if(s.exit){a.delete(s.value);continue}if(++r>1e5||s.depth>48)throw new Error("task_json_complexity_exceeded");if(s.value===null||typeof s.value=="string"||typeof s.value=="boolean"||typeof s.value=="number"&&Number.isFinite(s.value))continue;if(typeof s.value!="object")throw new Error("task_json_value_invalid");if(a.has(s.value))throw new Error("task_json_cycle");a.add(s.value),n.push({...s,exit:!0});const i=Object.getPrototypeOf(s.value);if(!Array.isArray(s.value)&&i!==Object.prototype&&i!==null)throw new Error("task_json_object_invalid");if(Object.getOwnPropertySymbols(s.value).length)throw new Error("task_json_symbol_invalid");if(Object.hasOwn(s.value,"toJSON"))throw new Error("task_json_serializer_invalid");if(Array.isArray(s.value)&&(s.value.length>1e4||Object.keys(s.value).length!==s.value.length))throw new Error("task_json_array_invalid");for(const[c,d]of Object.entries(Object.getOwnPropertyDescriptors(s.value))){if(d.get||d.set)throw new Error("task_json_accessor_invalid");if(Array.isArray(s.value)&&c!=="length"&&(!/^(0|[1-9]\d*)$/u.test(c)||Number(c)>=s.value.length))throw new Error("task_json_array_invalid");d.enumerable&&n.push({value:d.value,depth:s.depth+1})}}if(new TextEncoder().encode(JSON.stringify(e)).byteLength>t)throw new Error("task_json_size_exceeded")}function wh(e){try{return iO(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 iO(e){if(Aa(e,aO),rc(e,e,new Set,0,{remaining:2048}),!Nv(e)){const t=Nv.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function rc(e,t,n,a,r){if(--r.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 s=new Set(n).add(e),i=e;if(i.$schema!==void 0&&i.$schema!==Lv)throw new Error(`Task schemas must use ${Lv}.`);for(const[c,d]of Object.entries(i))if(c==="$ref"){if(typeof d!="string"||!d.startsWith("#/$defs/"))throw new Error("Task schema references must be local JSON pointers into $defs.");let l=t;for(const p of d.slice(2).split("/")){if(/~(?![01])/u.test(p))throw new Error("Invalid task schema JSON pointer.");const f=p.replaceAll("~1","/").replaceAll("~0","~");if(!l||typeof l!="object"||!Object.hasOwn(l,f))throw new Error(`Task schema reference ${d} is missing.`);l=l[f]}rc(l,t,s,a+1,r)}else if(rO.has(c)){if(!d||typeof d!="object"||Array.isArray(d))throw new Error(`Invalid schema map ${c}.`);for(const l of Object.values(d))rc(l,t,s,a+1,r)}else if(sO.has(c)){if(!Array.isArray(d)||d.length>32)throw new Error(`Schema ${c} must contain at most 32 alternatives.`);for(const l of d)rc(l,t,s,a+1,r)}else oO.has(c)&&rc(d,t,s,a+1,r)}const yx=u({taskId:E,input:ve(o(),ke()),policyVisibleContext:ve(o(),ke()),expectedOutput:ve(o(),ke()).nullable().optional(),tags:v(E).max(100).optional()}).strict(),ii=u({schemaVersion:x("openpond.humanTaskProposal.v1"),tasks:v(yx).min(1).max(1e3),contentHash:W}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;n!==Qe(a)&&t.addIssue({code:"custom",message:"Task proposal content hash differs."}),new Set(e.tasks.map(r=>r.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",message:"Each task may be proposed once."});try{Aa(e,1048576)}catch{t.addIssue({code:"custom",message:"Task proposal exceeds retained data bounds."})}}),zv=u({schemaVersion:x("openpond.humanTaskProposal.v1"),tasks:v(yx).min(1).max(1e3),contentHash:W,referenceRedacted:x(!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."}):ii.safeParse(e).success||t.addIssue({code:"custom",message:"Task proposal integrity differs."})});function S8(e){const t={schemaVersion:"openpond.humanTaskProposal.v1",tasks:e};return ii.parse({...t,contentHash:Qe(t)})}const _e=E,gn=u({id:_e,revision:m().int().positive(),contentHash:W}).strict(),cO=st("kind",[u({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(u({value:dt([m(),o(),j()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:x("score"),minimum:m().finite(),maximum:m().finite(),step:m().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."),u({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(u({value:dt([m(),o(),j()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:x("category"),options:v(o().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."),u({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(u({value:dt([m(),o(),j()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:x("boolean")}).strict(),u({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(u({value:dt([m(),o(),j()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:x("text"),minimumLength:m().int().nonnegative().max(2e4).optional(),maximumLength:m().int().positive().max(2e4)}).strict(),u({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(u({value:dt([m(),o(),j()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:x("preference"),requireStrength:j().optional(),allowTie:j()}).strict()]),Kc=u({schemaVersion:x("openpond.humanForm.v1"),mode:k(["individual","pairwise"]),instructions:o().max(2e4),criteria:v(cO).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 r=new Set;n.anchors?.forEach((s,i)=>{const c=s.value,d=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",l=JSON.stringify(c);(!d||r.has(l))&&t.addIssue({code:"custom",path:["criteria",a,"anchors",i,"value"],message:"Each anchor must describe a unique valid raw value."}),r.add(l)})}),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."})}),lO=u({localSource:dt([kh,BM]).optional(),recordedSource:u({id:_e,snapshotHash:W,boundaryId:_e,boundaryRevisionHash:W}).strict().optional(),experimentId:_e,attemptId:_e,taskId:_e,targetId:_e,output:gn,trace:gn.nullable(),familyKey:_e,split:k(["train","validation","test","frozen_eval"])}).strict(),Ih=u({publication:gn.optional(),dataset:gn,grader:gn,graderBinding:u({id:_e,version:o().min(1).max(100),contentHash:W}).strict(),rubric:gn,attempts:v(lO).max(2),taskIds:v(_e).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."})}),ci=u({criterionId:_e,value:dt([m().finite(),j(),o().max(2e4),yi()]),abstain:j(),note:o().max(2e4),strength:k(["slight","moderate","strong"]).optional()}).strict(),Sx=u({approval:k(["none","manager"]),minimumRaters:m().int().min(1).max(100),managerIds:v(_e).max(100),reviewerIds:v(_e).max(100),queueClaim:j(),teamVisible:j(),distinctManager:j().optional(),independentRaters:j().optional(),blindPair:j().optional()}).strict().superRefine((e,t)=>{e.approval==="none"&&e.minimumRaters!==1&&t.addIssue({code:"custom",path:["minimumRaters"],message:"Multi-rater review requires explicit adjudication."})}),xx=u({taskProposal:ii.optional(),id:_e,revision:m().int().positive(),actorId:_e,generation:m().int().positive(),evidenceHash:W,formHash:W,answers:v(ci).max(100),note:o().max(2e4),submittedAt:Ce,supersedes:_e.nullable(),contentHash:W}).strict(),sc=u({taskProposalHash:W.optional(),id:_e,revision:m().int().positive(),actorId:_e,outcome:k(["accept","reject","request_changes"]),submissions:v(u({id:_e,contentHash:W}).strict()).min(1).max(100),answers:v(ci).max(100),note:o().max(2e4),decidedAt:Ce,contentHash:W}).strict(),wd=u({schemaVersion:x("openpond.humanReview.v1"),id:_e,revision:m().int().positive(),scope:_e,projectId:_e,createdBy:_e,kind:k(["author","execute","grade"]),dueAt:Ce.optional(),title:o().trim().min(1).max(500),authorPublication:u({proposalHash:W,dataset:gn,operationId:_e,publishedBy:_e,publishedAt:Ce}).strict().nullable(),evidence:Ih,form:Kc,policy:Sx,status:k(["queued","assigned","in_progress","submitted","returned","accepted","rejected","cancelled"]),assigneeId:_e.nullable(),generation:m().int().positive(),drafts:v(u({taskProposal:ii.optional(),actorId:_e,generation:m().int().positive(),answers:v(ci).max(100),note:o().max(2e4),updatedAt:Ce}).strict()).max(100),submissions:v(xx).max(1e3),decisions:v(sc).max(1e3),audit:v(u({actorId:_e,action:k(["claim","reassign","cancel"]),priorAssigneeId:_e.nullable(),assigneeId:_e.nullable(),generation:m().int().positive(),note:o().max(2e4),occurredAt:Ce}).strict()).max(1e3),execution:u({executionId:_e.nullable(),operationId:_e,boundBy:_e,configurationHash:W,generation:m().int().positive(),result:gn.nullable()}).strict().nullable(),createdAt:Ce,updatedAt:Ce,contentHash:W}).strict(),or={operationId:_e,id:_e,expectedRevision:m().int().nonnegative()},dO=st("action",[u({...or,action:x("create"),projectId:_e,kind:wd.shape.kind,title:wd.shape.title,dueAt:Ce.optional(),evidence:Ih,form:Kc,policy:Sx,assigneeId:_e.nullable()}).strict(),u({...or,action:x("claim")}).strict(),u({...or,action:x("bind_author_publication"),proposalHash:W,dataset:gn}).strict(),u({...or,action:x("reserve_execution"),generation:m().int().positive(),runOperationId:_e,configurationHash:W}).strict(),u({...or,action:x("bind_execution"),generation:m().int().positive(),executionId:_e,runOperationId:_e,configurationHash:W}).strict(),u({...or,action:x("reassign"),assigneeId:_e.nullable(),note:o().trim().min(1).max(2e4)}).strict(),u({...or,action:x("cancel"),note:o().max(2e4)}).strict(),u({...or,action:x("save_draft"),taskProposal:ii.optional(),generation:m().int().positive(),answers:v(ci).max(100),note:o().max(2e4)}).strict(),u({...or,action:x("submit"),taskProposal:ii.optional(),generation:m().int().positive(),evidenceHash:W,formHash:W,executionResult:gn.optional(),answers:v(ci).max(100),note:o().max(2e4)}).strict(),u({...or,action:x("decide"),taskProposalHash:W.optional(),outcome:sc.shape.outcome,submissions:sc.shape.submissions,answers:sc.shape.answers,note:sc.shape.note}).strict()]),uO=st("endpoint",[u({endpoint:x("command"),scope:_e,command:dO}).strict(),u({endpoint:x("get"),scope:_e,id:_e,revision:m().int().positive().optional()}).strict(),u({endpoint:x("inbox"),scope:_e,projectId:_e.optional(),view:k(["mine","team","approval"]),status:k(["active","history"]),afterId:_e.optional(),limit:m().int().min(1).max(100)}).strict()]),kx=wd.omit({evidence:!0,drafts:!0,submissions:!0}).extend({drafts:v(wd.shape.drafts.element.omit({taskProposal:!0}).extend({taskProposal:zv.optional()})).max(100),submissions:v(xx.omit({taskProposal:!0}).extend({taskProposal:zv.optional()})).max(1e3),evidence:Ih.nullable(),evidenceHash:W,formHash:W,permissions:u({owner:j(),manager:j(),reviewer:j(),claim:j()}).strict()}).strict(),mO=u({items:v(kx).max(100),nextCursor:_e.nullable(),actionCount:m().int().nonnegative(),approvalAvailable:j()}).strict(),wx=u({endpoint:x("snapshot"),scope:_e,projectId:_e,graderId:_e,selections:v(u({executionId:_e,receiptId:_e}).strict()).min(1).max(2)}).strict(),pO=u({endpoint:x("snapshot_tasks"),scope:_e,projectId:_e,graderId:_e,dataset:gn,taskIds:v(_e).min(1).max(1e3).optional(),all:x(!0).optional()}).strict().refine(e=>!!e.all!=!!e.taskIds,"Choose an exact selected task list or the server-frozen full Dataset."),fO=u({endpoint:x("inspect"),scope:_e,id:_e,slot:m().int().min(0).max(1).optional(),afterId:o().min(1).max(500).optional()}).strict(),hO=u({endpoint:x("results"),scope:_e,executionId:_e,selection:v(gn).max(1e4).optional()}).strict(),gO=u({endpoint:x("members"),scope:_e}).strict(),vO=u({endpoint:x("execute"),scope:_e,id:_e,expectedRevision:m().int().positive(),generation:m().int().positive(),operationId:_e,configuration:ke()}).strict(),bO=u({endpoint:x("execution"),scope:_e,id:_e,action:k(["status","result","cancel"])}).strict(),yO=wx.omit({endpoint:!0}).extend({endpoint:x("publish_evidence"),operationId:_e,audience:v(_e).max(100),workspaceVisible:j()}).strict(),SO=u({endpoint:x("publication_access"),scope:_e,projectId:_e}).strict(),xO=u({endpoint:x("revoke_publication"),scope:_e,publication:gn}).strict(),kO=u({endpoint:x("publish_author"),scope:_e,id:_e,expectedRevision:m().int().positive(),operationId:_e,proposalHash:W,workspaceId:_e.optional(),expectedWorkspaceRevision:m().int().positive().optional()}).strict(),wO=u({endpoint:x("author_tasks"),scope:_e,id:_e,includeReference:x(!0).optional()}).strict(),IO=u({endpoint:x("graders"),scope:_e,projectId:_e,dataset:gn}).strict(),x8=v(u({id:_e,name:o(),version:o(),contentHash:W,mode:k(["individual","pairwise"])}).strict()).max(1e3),_O=dt([JM,ZM,vx,WM,GM,SO,kO,wO,IO,yO,xO,vO,bO,uO,wx,pO,fO,hO,gO]),CO=v(u({origin:x("owner_attested_local").optional(),coverage:u({sourceEventCount:m().int().nonnegative(),publishedEventCount:m().int().nonnegative(),traceLimited:j(),artifactsIncluded:x(!1)}).strict().optional(),reviewId:_e,reviewRevision:m().int().positive(),evidenceHash:W,slot:o(),input:ke(),output:ke(),error:o().nullable(),events:v(ve(o(),ke())),eventCount:m().int().nonnegative(),evidenceLimited:j(),nextEventCursor:o().nullable(),slotIndex:m().int().nonnegative(),executionId:_e.optional(),receiptId:_e.optional()}).strict()).max(1e3),Wa=k(["train","validation","test","frozen_eval"]),RO=u({path:o().trim().min(1).max(2e3).refine(TO),mediaType:o().trim().min(1).max(200),schemaRef:aa.nullable().default(null),maxBytes:m().int().positive().max(25e7).nullable().default(null),metadata:ha}).strict(),PO=u({policyVisibleFields:v(E).max(1e3).default([]),privilegedFields:v(E).max(1e3).default([]),hiddenGraderRefs:v(E).max(1e3).default([]),connectedAppScopes:v(E).max(100).default([])}).strict(),Ix=u({protocolVersion:x("openpond.environment.v1"),kind:k(["text","agent","work","custom_program"]),entrypoint:o().trim().min(1).max(1e3),stateful:j(),deterministicSeeds:j(),lifecycle:v(k(["create","reset","step","collect","destroy"])).min(5).max(5),networkPolicy:k(["none","declared_read_only","declared_scoped"]),defaultTimeoutMs:m().int().positive().max(36e5)}).strict(),tu=u({id:E,version:o().trim().min(1).max(100),weight:m().nonnegative().max(1e3).default(1),hardGate:j().default(!1),rewardEligible:j().default(!1),privileged:j().default(!1)}),_x=tu.extend({kind:k(["content","schema","artifact","runtime_event","state"]),config:ve(o(),ke())}).strict(),Cx=tu.extend({kind:x("model_judge"),rubricRef:aa,calibrationStatus:k(["pending","passed","failed"]),model:u({providerId:E,modelId:E,revision:o().trim().min(1).max(500).nullable()}).strict().optional(),temperature:m().min(0).max(2).optional()}).strict(),Rx=k(["isolated_javascript","sandbox_process"]),Px=tu.extend({kind:x("custom_verifier"),runtime:Rx.optional(),verifierRef:aa,exportName:o().trim().min(1).max(240).optional(),timeoutMs:m().int().positive().max(3e5),networkPolicy:x("none")}).strict(),Tx=tu.extend({kind:x("human"),rubricRef:aa,reviewerRole:o().trim().min(1).max(500),form:Kc.optional()}).strict(),Ax=dt([_x,Cx,Px,Tx]),_h=u({id:E,clusterKey:E,split:Wa,input:ve(o(),ke()),expectedOutput:ve(o(),ke()).nullable(),policyVisibleContext:ve(o(),ke()).default({}),privilegedContextRef:E.nullable(),artifactRefs:v(aa).max(1e3).default([]),requiredOutputs:v(RO).max(1e3).optional(),tags:v(E).max(100).default([])}).strict(),Ex=u({schemaVersion:x("openpond.tasksetRelease.v2"),id:E,revision:m().int().positive(),policy:PO,environment:Ix,environmentRelease:u({id:E,contentHash:W}).strict().optional(),tools:v(qS).max(200),capabilities:v(Hj).max(200),tasks:v(_h).min(1).max(1e6),graders:v(Ax).max(1e3),verifierSetRelease:u({id:E,contentHash:W}).strict().optional(),metrics:Vc.optional(),metadata:ha}).strict(),jx=Ex.extend({contentHash:W}).strict();function TO(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const AO=o().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."),Ch=st("kind",[u({kind:x("profile")}).strict(),u({kind:x("workflow"),workflowId:E}).strict(),u({kind:x("skill"),skillPath:AO}).strict(),u({kind:x("agent_action"),actionId:E}).strict()]),EO=u({taskId:E,seed:o().min(1).max(500),fixtureId:E.nullable()}).strict(),Hv=o().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),Uv=k(["input","output","expectedOutput","evaluatorContext"]),jO=v(u({graderId:E,fields:v(u({destination:Uv,path:v(Hv).min(1).max(20),source:Uv,sourcePath:v(Hv).max(20)}).strict()).max(100)}).strict()).max(100),MO=u({execution:se,originalEvidence:se,members:v(u({caseId:E,seed:o().min(1).max(500),fixtureId:W,sourceId:E,snapshotHash:W,boundaryRevisionHash:W}).strict()).min(1).max(500)}).strict(),OO=u({release:se.extend({revision:dt([m().int().positive(),o().min(1).max(200)])}).strict(),feedbackKey:o().min(1).max(240),configurationHash:W,output:k(["boolean","score","category"]),categories:v(o().min(1).max(120)).max(50)}).strict(),$O=u({schemaVersion:x("openpond.profileExternalDatasetBinding.v1"),dataset:se.extend({revision:m().int().positive()}).strict(),packageHash:W,profileId:E,target:Ch,declaredProfileCatalogHash:W.nullable(),protectedProfileClosureHash:W,recordedOrigin:MO.optional(),gradingSource:u({pass:se,evidence:se}).strict().optional(),split:Wa,population:v(EO).min(1).max(1e4),evaluators:v(OO).min(1).max(100),fieldMappingsHash:W,fieldMappings:jO,environmentHash:W,privateDatasetClosureHash:W,criterion:u({minimumPassRate:m().min(0).max(1),requireComplete:j()}).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."}),Qe(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."})}),us=$O.safeExtend({contentHash:W}).strict();function Jp(e){const t=us.parse(e),{contentHash:n,...a}=t;if(Qe(a)!==n)throw new Error("External Dataset binding integrity failed.");return t}const NO=u({id:E,label:o().trim().min(1).max(240),description:o().max(4e3),target:Ch,tasksetRelease:se,split:Wa,taskIds:v(E).min(1).max(1e5),seeds:v(o().trim().min(1).max(500)).min(1).max(100),criterion:u({minimumPassRate:m().min(0).max(1),requireComplete:j()}).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."})}),DO=u({id:E,label:o().trim().min(1).max(240),scope:k(["component","profile"]),definitionIds:v(E).min(1).max(1e3)}).strict();u({schemaVersion:x("openpond.profileEvaluations.v1"),definitions:v(NO).max(1e3),suites:v(DO).max(100)}).strict();const Id=u({profileId:E,sourceRevision:o().trim().min(1).max(240),harnessRelease:se,catalogHash:W,definitionId:E,definitionHash:W,target:Ch,environmentHash:W,externalDatasetBinding:us.optional(),sourceCandidate:HM.optional()}).strict();class Fa extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}const LO=u({schemaVersion:x("openpond.modelJudgeTransportPolicy.v1"),responseFormat:x("judgment_json_schema"),reasoningEffort:k(["off","low","medium","high","xhigh","max"]),maximumOutputTokens:m().int().positive().max(1e6)}).strict(),zO=u({schemaVersion:x("openpond.modelJudgeReceipt.v1"),providerId:o().trim().min(1).max(200),modelId:o().trim().min(1).max(500),modelRevision:o().trim().min(1).max(500).nullable(),responseId:o().trim().min(1).max(500).nullable(),requestHash:W,responseHash:W,inputTokens:m().int().nonnegative().nullable(),outputTokens:m().int().nonnegative().nullable(),costUsd:m().finite().nonnegative().nullable(),transportPolicy:LO.optional(),effectiveRequestHash:W.optional(),finishReason:o().trim().min(1).max(200).nullable().optional(),reasoningTokens:m().int().nonnegative().nullable().optional()}).strict(),HO=u({schemaVersion:x("openpond.graderEvidence.v1"),graderId:E,graderVersion:o().trim().min(1).max(100),status:k(["scored","pending","unavailable","failed"]).optional(),score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),failureClass:Gd.nullable(),feedback:v(o().max(2e4)).max(1e3),visibleEvidenceRefs:v(E).max(1e4),privilegedEvidenceRefs:v(E).max(1e4),modelJudgeReceipt:zO.optional()}).strict(),Mx=HO.extend({contentHash:W}).strict(),UO=u({score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),failureClass:Gd.nullable(),gradingStatus:k(["scored","pending","unscorable","not_configured"])}).strict(),Ox=UO.extend({schemaVersion:x("openpond.taskGrade.v1"),taskHash:W,evidenceHash:W,graderSetHash:W,components:v(Mx).max(1e3),contentHash:W}).strict(),Tl={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},Wc=o().regex(/^[a-z][a-z0-9_]{0,79}$/);function qO(e){return e.feedbackKey??`reward_${Qe(e.id).slice(0,24)}`}const BO=dt([_x.omit(Tl),Cx.omit(Tl),Px.omit(Tl),Tx.omit(Tl),u({kind:x("learned_model"),modelVersion:se,inputContract:aa}).strict()]),$x=u({schemaVersion:x("openpond.rewardRelease.v1"),id:E,revision:m().int().positive(),name:o().trim().min(1).max(500),description:o().max(1e4),feedbackKey:Wc.optional(),implementation:BO,rawScore:u({minimum:m().finite(),maximum:m().finite()}).strict(),assets:v(aa).max(1e3),fixtureSetRef:aa.optional(),calibrationCheckRef:se.extend({revision:m().int().positive()}).optional()}).strict().superRefine((e,t)=>{if(e.fixtureSetRef&&(e.fixtureSetRef.visibility!=="verifier"||!e.assets.some(n=>Qe(n)===Qe(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=wh(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),nu=$x.safeExtend({contentHash:W}).strict(),vs=se.extend({revision:m().int().positive()}).strict(),FO=st("kind",[u({kind:x("identity")}).strict(),u({kind:x("linear"),minimum:m().finite(),maximum:m().finite(),direction:k(["higher","lower"])}).strict()]),Rh=u({graderId:E,reward:vs,role:k(["training","evaluation"]),normalization:FO,weight:m().nonnegative().max(1e3),required:j(),hardGate:j(),privileged:j(),fixtureRefs:v(se).max(1e3)}).strict(),VO=u({schemaVersion:x("openpond.rewardBinding.v1"),id:E,revision:m().int().positive(),name:o().trim().min(1).max(500).optional(),description:o().max(1e4).optional(),recipeRef:vs.optional(),sources:v(Rh).max(100),aggregation:x("weighted_mean"),unscorable:x("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."})}),Ph=VO.safeExtend({contentHash:W}).strict(),Nx=u({graderId:E,reward:vs,role:k(["training","evaluation"]),status:k(["scored","pending","unavailable","failed"]),rawScore:m().finite().nullable(),normalizedScore:m().min(0).max(1).nullable(),passed:j().nullable(),evidenceHashes:v(W).max(1e3),graderEvidence:Mx.optional(),message:o().max(2e4).nullable()}).strict(),KO=u({schemaVersion:x("openpond.rewardComposition.v1"),binding:vs,taskHash:W,outputHash:W,results:v(Nx).max(100),training:u({status:k(["scored","pending","unscorable","not_configured"]),score:m().min(0).max(1).nullable(),passed:j().nullable()}).strict(),evaluation:u({status:k(["scored","pending","unscorable","not_configured"]),score:m().min(0).max(1).nullable(),passed:j().nullable()}).strict()}).strict(),Ic=KO.extend({contentHash:W}).strict();function WO(e){Aa(e);const t=$x.parse(e);return nu.parse({...t,contentHash:Qe(t)})}const Th=u({harnessRelease:se,agentSnapshot:se,sourcePackageHash:W}).strict(),Wm=o().trim().min(1).max(200),Dx=u({sessionId:Wm,turnId:Wm,source:Th,admissionHash:W,modelConfigurationHash:W,traceHash:W,runtimeEventRefs:v(Wm).max(1e4),startedAt:Ce,completedAt:Ce,outputHash:W,partialOutputAvailable:j()}).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."})}),GO=u({schemaVersion:x("openpond.nativeHarnessExperimentAttempt.v1"),taskId:o().min(1).max(500),status:k(["completed","cancelled","timed_out","policy_failure"]),output:o().max(8388608).nullable(),error:o().max(2e3).nullable(),messages:v(ke()).max(4002),collected:j(),environmentCleanupComplete:x(!0),snapshot:yi(),native:Dx}).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!==Qe(e.output))&&t.addIssue({code:"custom",path:["native","outputHash"],message:"Native output differs from its retained evidence."})});GO.extend({contentHash:W}).strict();const Lx=m().finite().nonnegative(),zx=st("kind",[u({kind:x("model"),modelId:E,configurationHash:W}).strict(),u({kind:x("harness"),source:Id,model:u({modelId:E,configurationHash:W}).strict()}).strict(),u({kind:x("agent"),source:Th,model:u({modelId:E,configurationHash:W}).strict()}).strict(),u({kind:x("fixture"),configurationHash:W}).strict()]),Hx=u({release:se.extend({revision:dt([m().int().positive(),o().trim().min(1).max(200)])}).strict(),feedbackKey:Wc,configurationHash:W.optional(),output:k(["boolean","score","category"]),categories:v(o().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."})}),Ah=u({caseId:E,seed:o().trim().min(1).max(500),fixtureId:E.nullable()}).strict();function _c(e){const t=Ah.parse(e);return JSON.stringify([t.caseId,t.seed,t.fixtureId])}function ZO(e,t,n){return`human-projection-${Qe({originalManifest:e,selectionHash:t,rulesHash:n}).slice(0,48)}`}const JO=u({schemaVersion:x("openpond.experimentManifest.v1"),id:E,name:o().trim().min(1).max(500),teamId:E,operationId:E,maximumCostUsd:Lx.nullable(),dataset:se.extend({revision:m().int().positive()}).strict(),target:zx,execution:u({packageHash:W,runtimeTargetHash:W,metricPolicyHash:W,compatibility:u({protocol:x("openpond.evaluation-execution.v1"),targetKind:k(["model","agent","harness","fixture"])}).strict().optional()}).strict().optional(),lineage:u({definition:se.extend({revision:m().int().positive()}).strict().nullable(),execution:se,scoringPassId:E.nullable(),humanProjection:u({originalManifest:se,selectionHash:W,rulesHash:W}).strict().optional()}).strict().optional(),evaluators:v(Hx).max(100),population:v(Ah).min(1).max(1e4),createdAt:Ce}).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!==ZO(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(_c)).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."})}),os=JO.extend({contentHash:W}).strict(),QO=u({feedbackKey:Wc,evaluator:Hx.shape.release,status:k(["scored","unavailable","failed","pending"]),value:dt([j(),m().finite(),o().max(500)]).nullable(),passed:j().nullable().optional(),reasoning:o().max(2e4).nullable(),evidenceRefs:v(br).max(1e3)}).strict(),YO=u({inputTokens:m().int().nonnegative().nullable(),outputTokens:m().int().nonnegative().nullable(),totalTokens:m().int().nonnegative().nullable(),costUsd:Lx.nullable(),latencyMs:m().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."})}),XO=u({identity:Ah,status:k(["completed","failed","cancelled","unavailable"]),output:ke().nullable(),error:u({code:E,message:o().max(2e3)}).strict().nullable(),feedback:v(QO).max(100),usage:YO,traceRef:br.nullable(),startedAt:Ce.nullable(),completedAt:Ce.nullable()}).strict(),Ux=u({schemaVersion:x("openpond.experimentResult.v1"),manifest:se,status:k(["completed","failed","cancelled"]),cases:v(XO).min(1).max(1e4),completedAt:Ce}).strict(),is=Ux.extend({contentHash:W}).strict();function e$(e,t){os.parse(t),pE(t,"Experiment manifest");const n=Ux.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(_c)),r=new Set,s=new Map(t.evaluators.map(i=>[i.feedbackKey,i]));for(const i of n.cases){const c=_c(i.identity);if(!a.has(c)||r.has(c))throw new Error("Experiment result has an unexpected or repeated case.");r.add(c);const d=new Set;for(const l of i.feedback){const p=s.get(l.feedbackKey);if(!p||d.has(l.feedbackKey)||l.evaluator.id!==p.release.id||l.evaluator.contentHash!==p.release.contentHash||l.evaluator.revision!==p.release.revision)throw new Error("Experiment feedback differs from its pinned evaluator.");if(d.add(l.feedbackKey),l.status==="scored"){if(l.value===null||typeof l.value!=={boolean:"boolean",score:"number",category:"string"}[p.output]||p.output==="category"&&!p.categories.includes(l.value)||p.output==="score"&&(l.value<0||l.value>1))throw new Error("Experiment feedback value violates its output contract.")}else if(l.value!==null||l.passed!==null&&l.passed!==void 0)throw new Error("Unscored experiment feedback cannot claim a value or pass decision.")}}if(r.size!==a.size)throw new Error("Experiment result omits admitted cases.");return is.parse({...n,contentHash:Qe(n)})}function Xo(e){const t=os.parse(e.manifest),n=is.parse(e.result),{contentHash:a,...r}=n;if(Qe(r)!==a)throw new Error("Experiment result integrity failed.");return e$(r,t),{manifest:t,result:n}}function t$(e,t){for(const f of[e,t])Xo(f);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=f=>{const S=f.execution;if(!S?.compatibility)return S??null;const{runtimeTargetHash:b,...I}=S;return I};if(Qe(a(e.manifest))!==Qe(a(t.manifest))&&n.push("different_execution_contract"),e.manifest.target.kind==="harness"&&t.manifest.target.kind==="harness"){const f=e.manifest.target.source,S=t.manifest.target.source;(f.profileId!==S.profileId||Qe(f.target)!==Qe(S.target))&&n.push("different_component");const b=e.manifest.execution?.compatibility&&t.manifest.execution?.compatibility&&e.manifest.execution.packageHash===t.manifest.execution.packageHash;f.environmentHash!==S.environmentHash&&!b&&n.push("different_environment"),(f.definitionId!==S.definitionId||f.definitionHash!==S.definitionHash)&&n.push("different_evaluation_definition")}const r=f=>[...f.evaluators].sort((S,b)=>S.feedbackKey.localeCompare(b.feedbackKey));Qe(r(e.manifest))!==Qe(r(t.manifest))&&n.push("different_evaluators");const s=new Map(e.result.cases.map(f=>[_c(f.identity),f])),i=new Map(t.result.cases.map(f=>[_c(f.identity),f])),c=[...new Set([...s.keys(),...i.keys()])].sort();(s.size!==i.size||c.some(f=>!s.has(f)||!i.has(f)))&&n.push("different_population");const d=n.length===0,l=c.map(f=>{const S=s.get(f)??null,b=i.get(f)??null,I=new Map(S?.feedback.map(P=>[P.feedbackKey,P])??[]),C=new Map(b?.feedback.map(P=>[P.feedbackKey,P])??[]);return{identity:(S??b).identity,baseline:S,candidate:b,feedback:e.manifest.evaluators.map(P=>{const _=I.get(P.feedbackKey),M=C.get(P.feedbackKey),A=d?!S||!b?"missing_case":S.status!=="completed"||b.status!=="completed"||S.error||b.error?"case_not_completed":!_||!M||_.status!=="scored"||M.status!=="scored"?"feedback_unavailable":P.output==="category"?"categorical_feedback":null:"incompatible_experiments",T=O=>typeof O?.value=="boolean"?Number(O.value):typeof O?.value=="number"?O.value:null,y=A?null:T(_),w=A?null:T(M),R=O=>A?null:typeof O?.value=="boolean"?O.value:O?.passed??null;return{feedbackKey:P.feedbackKey,eligible:A===null,reason:A,baseline:y,candidate:w,delta:y===null||w===null?null:w-y,baselinePassed:R(_),candidatePassed:R(M)}})}}),p=e.manifest.evaluators.map((f,S)=>{const b=l.map(T=>T.feedback[S]).filter(T=>T.eligible),I=T=>b.length?b.reduce((y,w)=>y+w[T],0)/b.length:null,C=I("baseline"),P=I("candidate"),_=T=>b.length&&b.every(y=>y[T]!==null)?b.reduce((y,w)=>y+Number(w[T]),0)/b.length:null,M=_("baselinePassed"),A=_("candidatePassed");return{feedbackKey:f.feedbackKey,eligibleCount:b.length,excludedCount:l.length-b.length,baseline:C,candidate:P,delta:C===null||P===null?null:P-C,baselinePassRate:M,candidatePassRate:A,passRateDelta:M===null||A===null?null:A-M}});return{comparable:d,reasons:n,cases:l,metrics:p}}const Xr=o().trim().min(1).max(200),oc=o().regex(/^[a-f0-9]{64}$/),n$=u({id:Xr,contentHash:oc}).strict(),a$=u({schemaVersion:x("openpond.trainingHandoffOrigin.v1"),teamId:Xr,projectId:Xr.nullable(),configurationId:Xr,source:u({executionId:Xr,passId:Xr.nullable(),manifestHash:oc,resultHash:oc}).strict(),dataset:u({id:Xr,revision:m().int().positive(),contentHash:oc}).strict(),target:zx,graders:v(u({feedbackKey:Xr,evaluator:n$,expectedCount:m().int().positive(),scoredCount:m().int().nonnegative(),score:m().finite().nullable()}).strict()).max(100),contentHash:oc}).strict(),r$=u({text:o().max(1e5),modelId:o().trim().min(1).max(500),modelRevision:o().trim().min(1).max(500).nullable(),responseId:o().trim().min(1).max(500).nullable(),inputTokens:m().int().nonnegative().nullable(),outputTokens:m().int().nonnegative().nullable(),costUsd:m().finite().nonnegative().nullable(),effectiveRequestHash:o().regex(/^[a-f0-9]{64}$/).optional(),finishReason:o().trim().min(1).max(200).nullable().optional(),reasoningTokens:m().int().nonnegative().nullable().optional()}).strict(),qx=u({id:E,requestHash:W,reservedUsd:m().finite().positive(),status:k(["reserved","settled","not_dispatched"]),response:r$.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."})}),Bx=u({localTime:o().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/),timeZone:o().min(1).max(200).refine(e=>{try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Choose a valid IANA timezone.")}).strict(),Tt=ve(o(),ds()),Ye=vs,Qr=o().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),s$=u({schemaVersion:x("openpond.taskDefinition.v1"),id:E,revision:m().int().positive(),name:o().trim().min(1).max(500),description:o().max(1e4),instructions:o().trim().min(1).max(2e4),category:k(["structured","question_answering","coding","tool_workflow","custom"]),familyNamespace:E,inputSchema:ve(o(),ke()),outputSchema:ve(o(),ke()),requiredOutputs:_h.shape.requiredOutputs,contextRequirements:v(o().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:Ye,harness:se.nullable(),execution:Ex.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 r=wh(a);r.valid||t.addIssue({code:"custom",path:[n],message:r.issues[0].message})}!!e.execution.environmentRelease!=!!e.execution.verifierSetRelease&&t.addIssue({code:"custom",path:["execution"],message:"Bind both the environment and verifier-set releases."})}),au=s$.safeExtend({contentHash:W}).strict(),o$=u({schemaVersion:x("openpond.taskSourceMapping.v1"),exampleId:Qr,attemptId:Qr,occurredAt:Qr,input:Qr,observedOutput:Qr.nullable(),expected:Qr.nullable(),evaluatorContext:Qr.nullable(),familyKey:Qr,split:Wa}).strict(),i$=u({modelId:E,packageHash:W,taskset:Ye,batch:Ye,rewardBinding:Ye}).strict(),c$=u({schemaVersion:x("openpond.learningSource.v1"),id:E,revision:m().int().positive(),name:o().trim().min(1).max(500),kind:k(["direct","benchmark","work","opentelemetry","provider"]),taskDefinition:Ye,enabled:j(),allowedSplits:v(Wa).min(1).max(4),mapping:o$.nullable(),adapterVersion:o().trim().min(1).max(200).nullable(),reviewOrigin:i$.optional(),capturedOrigin:u({receiptId:E,ownerUserId:E,modelId:E,packageHash:W,taskset:Ye}).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."})}),Eh=c$.safeExtend({contentHash:W}).strict(),l$=u({schemaVersion:x("openpond.taskExample.v1"),sourceId:E,idempotencyKey:E,taskDefinition:Ye,exampleId:E,attemptId:E,occurredAt:Ce,familyKey:E.nullable(),split:Wa,input:Tt,observedOutput:Tt.nullable(),expected:Tt.nullable(),evaluatorContext:Tt.nullable(),assets:v(aa).max(1e3),requiredOutputs:_h.shape.requiredOutputs,provenance:u({sourceRecordRef:o().max(2e3).nullable(),mappingHash:W.nullable()}).strict()}).strict(),d$=u({schemaVersion:x("openpond.taskEvidence.v1"),id:E,revision:m().int().positive(),source:Ye,submission:l$,supersedes:Ye.nullable(),correctionFeedbackId:E.nullable(),receivedAt:Ce}).strict(),ru=d$.extend({contentHash:W}).strict(),u$=u({schemaVersion:x("openpond.taskRating.v1"),criteria:o().trim().min(1).max(2e4),scale:u({minimum:m().finite(),maximum:m().finite()}).strict(),score:m().finite(),evidence:o().max(2e4),explanation:o().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."})}),m$=u({schemaVersion:x("openpond.taskFeedback.v1"),sourceId:E,idempotencyKey:E,exampleId:E,attemptId:E,expectedEvidenceHash:W.nullable(),occurredAt:Ce,kind:k(["outcome","target_correction","ground_truth_correction","input_correction","family_resolution"]),value:Tt,note:o().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=u$.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),Fx=u({schemaVersion:x("openpond.taskFeedbackRecord.v1"),id:E,submission:m$,status:k(["pending_example","pending_review","applied","superseded","rejected"]),evidence:Ye.nullable(),createdAt:Ce,revision:m().int().positive(),submittedBy:u({id:E,role:k(["editor","reviewer","source"]),sourceId:E.nullable()}).strict().nullable().default(null),review:u({actorId:E,decision:Ye.nullable(),note:o().max(2e4),resolvedAt:Ce}).strict().nullable().default(null)}).strict(),p$=u({schemaVersion:x("openpond.taskAdmissionDecision.v1"),id:E,revision:m().int().positive(),evidence:Ye,supersedes:Ye.nullable(),actor:u({kind:k(["human","qualified_policy"]),id:E,policy:Ye.nullable()}).strict(),evidenceValidity:k(["valid","invalid","pending"]),taskAdmissibility:k(["approved","rejected","pending"]),observedQuality:k(["passed","failed","unscored","unavailable"]),targetApproval:k(["approved","rejected","pending","not_required"]),approvedTarget:Tt.nullable(),grade:Ic.nullable(),targetGrade:Ic.nullable(),note:o().max(2e4),decidedAt:Ce}).strict().superRefine((e,t)=>{e.targetApproval==="approved"&&e.approvedTarget===null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Target approval requires an actual target."}),e.targetApproval!=="approved"&&e.approvedTarget!==null&&t.addIssue({code:"custom",path:["approvedTarget"],message:"Only approved targets may be selected for supervised learning."}),e.actor.kind==="qualified_policy"&&!e.actor.policy&&t.addIssue({code:"custom",path:["actor"],message:"Automatic admission must pin its qualified policy."}),e.taskAdmissibility==="approved"&&e.evidenceValidity!=="valid"&&t.addIssue({code:"custom",path:["taskAdmissibility"],message:"Only valid evidence can produce an approved task."})}),jh=p$.safeExtend({contentHash:W}).strict(),f$=u({schemaVersion:x("openpond.taskBatch.v1"),id:E,revision:x(1),taskDefinition:Ye,rewardBinding:Ye,purpose:k(["supervised_training","reward_training","evaluation"]),examples:v(u({evidence:Ye,decision:Ye,familyKey:E,inputHash:W,split:Wa}).strict()).min(1).max(1e4),sealedAt:Ce,sealedBy:E}).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,r]of e.examples.entries()){e.purpose==="evaluation"==(r.split==="train")&&t.addIssue({code:"custom",path:["examples",a,"split"],message:"Training uses train examples; evaluation uses held-out examples."});for(const s of[`family:${r.familyKey}`,`input:${r.inputHash}`])n.has(s)&&n.get(s)!==r.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(s,r.split)}}),Vx=f$.safeExtend({contentHash:W}).strict(),h$=u({origin:a$.optional(),schemaVersion:x("openpond.learningPolicy.v1"),id:E,revision:m().int().positive(),modelProjectId:E,executionOwner:k(["local","hosted"]),enabled:j(),sources:v(Ye).min(1).max(100),taskDefinition:Ye,rewardBinding:Ye,admission:u({mode:k(["human","qualified_automatic"]),qualification:se.nullable(),minimumApprovedExamples:m().int().positive().max(1e5)}).strict(),trigger:st("kind",[u({kind:x("manual")}).strict(),u({kind:x("approved_count")}).strict(),u({kind:x("schedule"),intervalSeconds:m().int().min(60).max(31536e3)}).strict(),Bx.extend({kind:x("nightly")}).strict(),u({kind:x("upstream_accepted"),modelProjectId:E}).strict()]),trainingParent:se,teacher:se.nullable(),training:u({method:k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:se,retentionEvaluation:se,replayBatches:v(se).max(100)}).strict(),limits:u({maxIterationSpendUsd:m().positive().max(1e5),maxDailySpendUsd:m().positive().max(1e6),cooldownSeconds:m().int().nonnegative().max(31536e3),maxRetries:m().int().nonnegative().max(10),maxBatchExamples:m().int().positive().max(1e4),maxBacklogExamples:m().int().positive().max(1e6)}).strict(),automation:u({collect:j(),train:j(),accept:j(),serve:j()}).strict(),acceptance:u({minimumScore:m().min(0).max(1),maximumRetentionRegression:m().min(0).max(1),requireImprovement:j(),rollbackVersion:se.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."})}),g$=h$.safeExtend({contentHash:W}).strict(),v$=u({iterationId:E,iterationRevision:m().int().positive(),candidate:se,decision:Ye,decidedAt:Ce}).strict(),b$=k(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),y$=u({schemaVersion:x("openpond.learningIteration.v1"),id:E,revision:m().int().positive(),policy:Ye,status:b$,triggerIdentity:E,batch:Ye.nullable(),sourceWatermarks:ve(E,m().int().nonnegative()),trainingParent:se,trainingParentSelection:v$.nullable().optional(),teacher:se.nullable(),upstreamEvent:se.nullable(),trainingJob:se.nullable(),evaluationJob:se.nullable(),candidateVersion:se.nullable(),candidateDecision:Ye.nullable().default(null),candidateDecisionAt:Ce.nullable().optional(),dispatchId:E,retryCount:m().int().nonnegative(),spendUsd:m().nonnegative(),failure:u({code:E,message:o().max(2e4)}).strict().nullable(),createdAt:Ce,updatedAt:Ce}).strict(),S$=u({schemaVersion:x("openpond.taskGradeRun.v1"),id:E,revision:m().int().positive(),evidence:Ye,binding:Ye,target:k(["observed","proposed_target"]),output:Tt,status:k(["queued","running","completed","failed","cancelling","cancelled"]),composition:Ic.nullable(),leaseOwner:E.nullable(),leaseExpiresAt:Ce.nullable(),attemptCount:m().int().nonnegative(),timeoutMs:m().int().min(100).max(3e5),maximumSpendUsd:m().nonnegative().max(1e3),judgeCalls:v(qx).max(1e4).optional(),requestedBy:E.optional(),failure:o().max(2e4).nullable(),createdAt:Ce,updatedAt:Ce}).strict();dt([au,nu,Ph,Eh,ru,Fx,jh,Vx,g$,y$,S$]);function k8(e){return Ye.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function w8(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function I8(e){return Aa(e,16777216),{...e,contentHash:Qe(e)}}function _8(e){const{contentHash:t,...n}=e;if(Aa(n,16777216),Qe(n)!==t)throw new Fa("learning_content_hash_mismatch",422)}const Kx=u({schemaVersion:x("openpond.learningTextAsset.v1"),id:E,revision:x(1),asset:aa,text:o().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!==Xf(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),su=Kx.safeExtend({contentHash:W}).strict();function Al(e){Aa(e);const{text:t,...n}=e,a=Xf(t),r=`asset-${a}-${Qe(n).slice(0,16)}`,s=Kx.parse({schemaVersion:"openpond.learningTextAsset.v1",id:r,revision:1,asset:{...n,id:r,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return su.parse({...s,contentHash:Qe(s)})}function qv(e,t){const{contentHash:n,...a}=su.parse(e);if(Qe(a)!==n||Qe(a.asset)!==Qe(t))throw new Fa("learning_asset_reference_mismatch",409);return a.text}const Wx=u({id:E,name:o().max(500),input:o(),output:o(),expectedOutput:o(),evaluatorContext:o(),artifactRefs:v(o().max(500)).max(100),runtimeEventRefs:v(o().max(500)).max(100),infrastructureError:o().max(2e4),expectedStatus:k(["scored","pending","unavailable","failed"]),minimumScore:o(),maximumScore:o(),expectedPassed:k(["true","false","any"]),sourceLabel:u({evidence:Ye,feedback:u({id:E,revision:m().int().positive()}).strict()}).strict().optional()}).strict(),Gx=u({name:o().max(500),description:o().max(1e4),feedbackKey:Wc.optional(),kind:k(["custom_verifier","state","content","schema","artifact","runtime_event","model_judge","learned_model","human"]),fields:o(),outputField:o(),expectedField:o(),expectedValue:o(),schema:o(),reference:o(),events:o(),code:o(),exportName:o(),timeout:o(),verifierRuntime:k(["isolated_javascript","sandbox_process"]).optional(),rubric:o(),providerId:o(),modelId:o(),modelRevision:o(),temperature:o(),reviewerRole:o(),humanForm:o().max(131072).optional(),learnedId:o(),learnedHash:o(),inputContract:o(),minimum:o(),maximum:o(),fixtures:v(Wx).max(50).optional()}).strict(),x$=u({name:o().max(500),description:o().max(1e4),instructions:o().max(2e4),input:o(),output:o(),familyNamespace:o(),sources:v(Rh).max(100),recipeRef:vs.optional()}).strict(),k$=u({name:o().max(500),description:o().max(1e4),sources:v(Rh).max(100)}).strict(),w$=k(["definition","reward","binding"]),Gm=u({id:E,targetId:E,baseRelease:Ye.nullable(),editorVersion:x("openpond.modelsEditor.v1")}),Zm=st("targetKind",[Gm.extend({targetKind:x("definition"),fields:x$}).strict(),Gm.extend({targetKind:x("reward"),fields:Gx}).strict(),Gm.extend({targetKind:x("binding"),fields:k$}).strict()]),Jm={schemaVersion:x("openpond.authoringDraft.v1"),revision:m().int().positive(),status:k(["draft","archived","published"]),publishedRelease:Ye.nullable(),createdAt:Ce,updatedAt:Ce},Qm=st("targetKind",[Zm.options[0].extend(Jm).strict(),Zm.options[1].extend(Jm).strict(),Zm.options[2].extend(Jm).strict()]),C8=st("targetKind",[Qm.options[0].extend({contentHash:W}).strict(),Qm.options[1].extend({contentHash:W}).strict(),Qm.options[2].extend({contentHash:W}).strict()]),R8=u({draft:Ye,targetKind:w$,release:Ye}).strict(),Ha={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},Zx=k(["json","jsonl","csv","hermes","openclaw"]),I$=u({path:o().min(1).max(500),text:o()}).strict(),Mh=u({id:o().min(1).max(200),familyKey:o().min(1).max(200),split:Wa,kind:k(["task","attempt"]),input:Tt,observedOutput:Tt.nullable(),expected:Tt.nullable(),sourceId:o().min(1).max(2e3),sourceHash:o().length(64),occurredAt:o().datetime().nullable(),metadata:Tt,warnings:v(o().max(2e3)).max(100),needsContext:j()}).strict(),Jx=u({schemaVersion:x("openpond.taskIntakePreview.v1"),format:Zx,contentHash:o().length(64),records:v(Mh).max(Ha.records),issues:v(u({file:o(),row:m().int().positive().nullable(),message:o()}).strict()).max(1e3)}).strict();function _d(e,t){return`${e}-${Qe(t)}`}function Qx(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 _$=`export function verify({ output, expectedOutput }) {
|
|
100
|
+
if (!expectedOutput || !Object.hasOwn(expectedOutput, "answer")) {
|
|
101
|
+
throw new Error("An expected answer is required.");
|
|
102
|
+
}
|
|
103
|
+
const passed = output.answer === expectedOutput.answer;
|
|
104
|
+
return { score: passed ? 1 : 0, passed, feedback: passed ? "Answer matched" : "Answer differed" };
|
|
105
|
+
}`;function P8(e){Aa(e,262144);const t=Gx.parse(e.fields),n=e.base?nu.parse(e.base):null;if(n&&n.id!==e.id)throw new Fa("reward_authoring_base_mismatch",422);const a=t.fixtures?.length?Al({text:JSON.stringify(t.fixtures),path:"reward-fixtures.json",mediaType:"application/json",visibility:"verifier"}):null;let r=null,s,i;if(t.kind==="custom_verifier")r=Al({text:t.code,path:"verifier.mjs",mediaType:"application/javascript",visibility:"verifier"}),s={kind:t.kind,verifierRef:r.asset,exportName:t.exportName,timeoutMs:qo(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 Fa("reward_rubric_required",422,"Write the rubric before checking or publishing this Reward.");if(r=Al({text:t.rubric,path:"rubric.md",mediaType:"text/markdown",visibility:"verifier"}),t.kind==="human")s={kind:t.kind,rubricRef:r.asset,reviewerRole:t.reviewerRole,form:Kc.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 l={providerId:t.providerId,modelId:t.modelId,revision:t.modelRevision.trim()||null},p=qo(t.temperature,"Temperature"),f=n?.implementation,S=f?.kind==="model_judge"&&f.rubricRef.contentHash===r.asset.contentHash&&f.model?.providerId===l.providerId&&f.model?.modelId===l.modelId&&f.model?.revision===l.revision&&(f.temperature??0)===p&&n?.fixtureSetRef?.contentHash===a?.asset.contentHash;s={kind:t.kind,rubricRef:r.asset,model:l,temperature:p,calibrationStatus:S?f.calibrationStatus:"pending"},S&&(i=n?.calibrationCheckRef)}}else t.kind==="learned_model"?(Uo(t.inputContract,"Model input contract"),r=Al({text:t.inputContract,path:"input-contract.json",mediaType:"application/json",visibility:"verifier"}),s={kind:t.kind,modelVersion:{id:t.learnedId,contentHash:t.learnedHash},inputContract:r.asset}):t.kind==="state"?s={kind:t.kind,config:{fields:Fv(t.fields)}}:t.kind==="content"?s={kind:t.kind,config:{outputField:t.outputField,expectedField:t.expectedField,...t.expectedValue?{expectedValue:t.expectedValue}:{}}}:t.kind==="schema"?s={kind:t.kind,config:{jsonSchema:Uo(t.schema,"Output schema")}}:t.kind==="artifact"?s={kind:t.kind,config:{refIncludes:t.reference}}:s={kind:t.kind,config:{requiredEvents:Fv(t.events)}};const c=[...r?[r]:[],...a?[a]:[]];return{reward:WO({schemaVersion:"openpond.rewardRelease.v1",id:e.id,revision:(n?.revision??0)+1,name:t.name,description:t.description,feedbackKey:t.feedbackKey??qO({id:e.id}),implementation:s,rawScore:t.kind==="learned_model"?{minimum:qo(t.minimum,"Minimum score"),maximum:qo(t.maximum,"Maximum score")}:{minimum:0,maximum:1},assets:c.map(l=>l.asset),...a?{fixtureSetRef:a.asset}:{},...i?{calibrationCheckRef:i}:{}}),assets:c}}function T8(e,t,n=null){const a=e?.implementation,r=a&&"verifierRef"in a?a.verifierRef:a&&"rubricRef"in a?a.rubricRef:a&&"inputContract"in a?a.inputContract:null;if(r&&!t)throw new Fa("reward_source_required",422);const s=r&&t?qv(t,r):"";if(e?.fixtureSetRef&&!n)throw new Fa("reward_fixtures_required",422);const i=e?.fixtureSetRef&&n?Wx.array().max(50).parse(JSON.parse(qv(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:Bv(c.fields).join(", ")||"answer",outputField:El(c.outputField)||"text",expectedField:El(c.expectedField)||"text",expectedValue:El(c.expectedValue),schema:JSON.stringify(c.jsonSchema??{type:"object",properties:{answer:{type:"string"}},required:["answer"]},null,2),reference:El(c.refIncludes),events:Bv(c.requiredEvents).join(", "),code:a?.kind==="custom_verifier"?s:_$,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"?s:"",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"?s:"{}",minimum:String(e?.rawScore.minimum??0),maximum:String(e?.rawScore.maximum??1),...i.length?{fixtures:i}:{}}}function Uo(e,t){try{const n=JSON.parse(e);return Aa(n,131072),Tt.parse(n)}catch{throw new Fa("reward_authoring_json_invalid",422,`${t} must be a JSON object.`)}}function qo(e,t){const n=Number(e);if(!e.trim()||!Number.isFinite(n))throw new Fa("reward_authoring_number_invalid",422,`${t} must be a finite number.`);return n}function El(e){return typeof e=="string"?e:""}function Bv(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Fv(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}const Yx=u({id:E,name:o().trim().min(1).max(500),input:Tt,output:Tt,expectedOutput:Tt.nullable(),evaluatorContext:Tt.nullable(),artifactRefs:v(E).max(100),runtimeEventRefs:v(E).max(100),infrastructureError:o().max(2e4).nullable(),expected:st("status",[u({status:x("scored"),minimum:m().finite(),maximum:m().finite(),passed:j().nullable()}).strict(),u({status:k(["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."})}),C$=u({id:E,packageVersion:o().min(1).max(100),engine:o().min(1).max(200)}).strict(),R$=u({fixture:u({id:E,contentHash:W}).strict(),result:Nx,matchesExpectation:j()}).strict(),A8=u({schemaVersion:x("openpond.rewardCheckRun.v1"),id:E,revision:m().int().positive(),draft:Ye,reward:Ye,snapshotHash:W,fixtureRefs:v(u({id:E,contentHash:W}).strict()).min(1).max(50),status:k(["queued","running","completed","failed","cancelling","cancelled"]),runtime:C$.nullable(),results:v(R$).max(50),matchesExpectations:j().nullable(),failure:o().max(2e4).nullable(),timeoutMs:m().int().min(100).max(3e5),maximumSpendUsd:m().nonnegative().max(1e3),judgeCalls:v(qx).max(1e3).optional(),requestedBy:E.optional(),leaseOwner:E.nullable(),leaseExpiresAt:Ce.nullable(),attemptCount:m().int().nonnegative(),createdAt:Ce,updatedAt:Ce}).strict();function E8(e){if(!e.length||e.length>50)throw new Fa("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 Fa("reward_fixture_id_duplicate",422);return e.map(t=>Yx.parse({id:t.id,name:t.name,input:Uo(t.input,`${t.name}: input`),output:Uo(t.output,`${t.name}: output`),expectedOutput:t.expectedOutput.trim()?Uo(t.expectedOutput,`${t.name}: expected answer`):null,evaluatorContext:t.evaluatorContext.trim()?Uo(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:qo(t.minimumScore,`${t.name}: minimum score`),maximum:qo(t.maximumScore,`${t.name}: maximum score`),passed:t.expectedPassed==="any"?null:t.expectedPassed==="true"}:{status:t.expectedStatus}}))}function P$(e){const t=[];let n=[],a="",r=!1,s=!1;const i=()=>{n.push(a),a="",s=!1},c=()=>{if(i(),n.some(p=>p.length)&&t.push(n),n=[],t.length>Ha.records+1)throw new Error("CSV exceeds the 1,000-record limit.")};for(let p=0;p<e.length;p++){const f=e[p];if(r)f==='"'&&e[p+1]==='"'?(a+='"',p++):f==='"'?(r=!1,s=!0):a+=f;else if(f===",")i();else if(f===`
|
|
106
|
+
`||f==="\r")f==="\r"&&e[p+1]===`
|
|
107
|
+
`&&p++,c();else if(f==='"'&&!a&&!s)r=!0;else{if(s||f==='"')throw new Error("CSV has an invalid quoted field.");a+=f}}if(r)throw new Error("CSV has an unterminated quoted field.");(a||n.length||s)&&c();const d=t.shift()?.map(p=>p.trim().replace(/^\uFEFF/u,""));if(!d?.includes("instruction"))throw new Error("CSV requires an instruction column.");const l=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(d.some(p=>!l.has(p))||new Set(d).size!==d.length)throw new Error("CSV has duplicate or unsupported columns. Use instruction, context, reference, labels, id, familyKey and split.");return t.map((p,f)=>{if(p.length!==d.length)throw new Error(`CSV record ${f+2} has a different number of columns from its header.`);return Object.fromEntries(d.map((S,b)=>[S,p[b]]).filter(([,S])=>S!==""))})}function j8(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 Xx(e){return e.startsWith("\uFEFF")?e.slice(1):e}const ek=u({role:o().min(1),content:ds().nullable().optional()}).catchall(ds()),T$=u({id:o().min(1),messages:v(ek).min(1).max(Ha.messages),lineage_session_ids:v(o()).optional(),parent_session_id:o().nullable().optional()}).catchall(ds());function A$(e){const t=T$.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:r,...s}=t;return tk("hermes",t.id,n,t.messages,{sourceHash:Qe(e),metadata:{session:s},warnings:["Imported session context and tools need review before this can become an executable task."]})}const E$=u({traceSchema:x("openclaw-trajectory"),schemaVersion:x(1),traceId:o().min(1),sessionId:o().min(1),leafId:o().nullable(),eventCount:m().int().nonnegative(),warnings:v(Tt).optional()}).catchall(ds()),j$=u({traceSchema:x("openclaw-trajectory"),schemaVersion:x(1),traceId:o(),sessionId:o(),seq:m().int().nonnegative(),type:o(),ts:o()}).catchall(ds()),M$=u({header:Tt.nullable(),leafId:o().nullable(),entries:v(u({id:o().min(1),type:o().min(1),parentId:o().nullable().optional(),message:ek.optional()}).catchall(ds())).max(Ha.messages)}).strict();function O$(e){const t=c=>{const d=e.find(l=>l.path===c);if(!d)throw new Error(`OpenClaw bundle is missing ${c}.`);return Xx(d.text)},n=E$.parse(JSON.parse(t("manifest.json"))),a=M$.parse(JSON.parse(t("session-branch.json")));if(a.leafId!==n.leafId)throw new Error("OpenClaw manifest and session branch identify different leaves.");const r=t("events.jsonl").split(/\r?\n/u).filter(c=>c.trim()).map(c=>j$.parse(JSON.parse(c)));if(r.length!==n.eventCount||r.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 s=new Set;for(const[c,d]of a.entries.entries()){if(s.has(d.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(c&&d.parentId!==a.entries[c-1].id)throw new Error("OpenClaw branch is incomplete or out of order.");s.add(d.id)}if(a.entries.length&&a.entries.at(-1).id!==a.leafId)throw new Error("OpenClaw branch does not reach its declared leaf.");const i=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 tk("openclaw",n.sessionId,n.sessionId,i,{sourceHash:Qe(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 tk(e,t,n,a,r){const s=a.flatMap((c,d)=>c.role==="user"?[d]:[]);if(!s.length)throw new Error("This history contains no user request. Supply a session with its request context.");let i=0;return s.map((c,d)=>{const l=s[d+1]??a.length,p=a.slice(c+1,l),f=p.filter(C=>C.role==="assistant").at(-1),S=a[c],b=S.entryId??S.message_id??S.id??Qe({start:c,request:S}),I={id:_d(e,[t,b]),familyKey:_d(e,n),split:"train",kind:"attempt",input:{request:S.content??null,messages:a.slice(0,c+1)},observedOutput:f?{response:f.content??null,messages:p}:null,expected:null,sourceId:`${e}:${t}:${String(b)}`,sourceHash:r.sourceHash,occurredAt:Qx(f?.timestamp??S.timestamp),metadata:r.metadata,warnings:[...r.warnings,...f?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Aa(I),i+=new TextEncoder().encode(JSON.stringify(I)).length,i>Ha.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return Mh.parse(I)})}const $$=u({instruction:o().trim().min(1).max(1e5),context:dt([o(),Tt]).optional(),reference:dt([o(),Tt]).optional(),labels:dt([o(),v(o()),Tt]).optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Wa.optional()}).strict(),N$=u({input:Tt,observedOutput:Tt.nullable().optional(),expectedOutput:Tt.nullable().optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Wa.optional(),occurredAt:o().datetime().optional(),labels:Tt.optional()}).strict();function D$(e){const t=Zx.parse(e.format),n=v(I$).min(1).max(Ha.files).parse(e.files);if(n.reduce((l,p)=>l+new TextEncoder().encode(p.text).length,0)>Ha.bytes)throw new Error("Import exceeds the 5 MiB size limit.");if(n.some(l=>l.path.startsWith("/")||l.path.includes("\\")||l.path.split("/").some(p=>!p||p==="."||p===".."))||new Set(n.map(l=>l.path)).size!==n.length)throw new Error("Import contains an unsafe or duplicate file path.");const a=[],r=[],s=new Map,i=new Map;let c=0;function d(l,p,f){try{const S=f();if(a.length+S.length>Ha.records)throw new Error("Import exceeds the 1,000-record limit.");const b=new Map(s),I=new Map(i);let C=0;for(const P of S){Aa(P);const _=Qe(P),M=b.get(P.id);if(M&&M!==_)throw new Error("The same record identity has different content in this upload.");M||(C+=new TextEncoder().encode(JSON.stringify(P)).length),b.set(P.id,_);for(const A of[`family:${P.familyKey}`,`input:${Qe(P.input)}`]){if(I.has(A)&&I.get(A)!==P.split)throw new Error("The same task family or request occurs in different splits.");I.set(A,P.split)}}if(c+C>Ha.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const P of S)s.has(P.id)||a.push(P),s.set(P.id,Qe(P));for(const[P,_]of I)i.set(P,_);c+=C}catch(S){r.push({file:l,row:p,message:S instanceof eA?`Unsupported record fields or values (${S.issues.slice(0,3).map(b=>b.path.join(".")||"record").join(", ")}).`:S instanceof SyntaxError?"Invalid JSON.":S instanceof Error?S.message:"Invalid import record."})}}if(t==="openclaw")d("manifest.json",null,()=>O$(n));else for(const l of n){const p=Xx(l.text);if(t==="jsonl"||t==="hermes"){for(const[f,S]of p.split(/\r?\n/u).entries())if(S.trim()){if(r.length>=Ha.records)break;d(l.path,f+1,()=>t==="hermes"?A$(JSON.parse(S)):[Vv(JSON.parse(S))])}}else{let f;try{const S=t==="csv"?P$(p):JSON.parse(p);f=Array.isArray(S)?S:[S]}catch(S){d(l.path,null,()=>{throw S});continue}if(f.length>Ha.records){d(l.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}f.forEach((S,b)=>d(l.path,b+(t==="csv"?2:1),()=>[Vv(S)]))}}return Jx.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:Qe({format:t,files:n}),records:a,issues:r.slice(0,1e3)})}function Vv(e){const t=dt([$$,N$]).parse(e),n="instruction"in t,a=n?{instruction:t.instruction,...t.context===void 0?{}:{context:t.context}}:t.input,r=n?t.reference===void 0?null:typeof t.reference=="string"?{text:t.reference}:t.reference:t.expectedOutput??null,s=n?null:t.observedOutput??null,i=t.familyKey??_d("family",a),c=t.id??_d("task",{input:a,expected:r,observedOutput:s});return Mh.parse({id:c,familyKey:i,split:t.split??"train",kind:s?"attempt":"task",input:a,expected:r,observedOutput:s,sourceId:c,sourceHash:Qe(e),occurredAt:n?null:Qx(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}var Ws=Ye.shape.id,Cc=o().regex(/^[a-f0-9]{64}$/),L$=u({scopeId:Ws,modelId:Ws}).strict(),z$=u({schemaVersion:x("openpond.modelTasksetAuthoring.v1"),owner:L$,root:Ye,parent:Ye}).strict(),M8=u({schemaVersion:x("openpond.modelTasksetDraftRequest.v1"),operationId:Ws,modelId:Ws,expectedModelRevision:m().int().positive(),sourcePackageHash:Cc}).strict(),H$=u({schemaVersion:x("openpond.modelTasksetDraftPreparation.v1"),draftId:Ws,requestHash:Cc,sourcePackageHash:Cc,sourceTasksetRef:Ye,tasksetId:Ws,tasksetRevision:m().int().positive(),lineage:z$,authoringGraph:x("bound").optional()}).strict(),ou=o().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."),nk=u({path:ou,sizeBytes:m().int().nonnegative(),writable:j()}).strict(),ak=u({encoding:k(["utf8","base64"]),data:o().max(8e6)}).strict(),U$=nk.extend({contentHash:Cc,content:ak}).strict();u({draftId:Ws,expectedDraftRevision:m().int().positive(),path:ou,expectedFileHash:Cc.nullable(),content:ak.nullable()}).strict();var q$=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),B$=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]),F$=class rk{state=new Uint32Array(q$);pending=new Uint8Array(64);pendingLength=0;byteLength=0;words=new Uint32Array(64);update(t){const n=typeof t=="string"?new TextEncoder().encode(t):t;if(!Number.isSafeInteger(this.byteLength+n.length))throw new RangeError("SHA-256 input is too large");this.byteLength+=n.length;let a=0;if(this.pendingLength){const r=Math.min(64-this.pendingLength,n.length);this.pending.set(n.subarray(0,r),this.pendingLength),this.pendingLength+=r,a+=r,this.pendingLength===64&&(this.compress(this.pending),this.pendingLength=0)}for(;a+64<=n.length;)this.compress(n.subarray(a,a+64)),a+=64;return a<n.length&&(this.pending.set(n.subarray(a)),this.pendingLength=n.length-a),this}clone(){const t=new rk;return t.state.set(this.state),t.pending.set(this.pending),t.pendingLength=this.pendingLength,t.byteLength=this.byteLength,t}digestHex(){const t=this.clone(),n=new Uint8Array(t.pendingLength<56?64:128);n.set(t.pending.subarray(0,t.pendingLength)),n[t.pendingLength]=128;const a=t.byteLength*8,r=new DataView(n.buffer);return r.setUint32(n.length-8,Math.floor(a/4294967296),!1),r.setUint32(n.length-4,a>>>0,!1),t.compress(n.subarray(0,64)),n.length===128&&t.compress(n.subarray(64)),Array.from(t.state,s=>s.toString(16).padStart(8,"0")).join("")}compress(t){const n=new DataView(t.buffer,t.byteOffset,64),a=this.state,r=this.words;for(let b=0;b<16;b+=1)r[b]=n.getUint32(b*4,!1);for(let b=16;b<64;b+=1){const I=r[b-15],C=r[b-2],P=ir(I,7)^ir(I,18)^I>>>3,_=ir(C,17)^ir(C,19)^C>>>10;r[b]=r[b-16]+P+r[b-7]+_>>>0}let s=a[0],i=a[1],c=a[2],d=a[3],l=a[4],p=a[5],f=a[6],S=a[7];for(let b=0;b<64;b+=1){const I=l&p^~l&f,C=s&i^s&c^i&c,P=ir(s,2)^ir(s,13)^ir(s,22),_=ir(l,6)^ir(l,11)^ir(l,25),M=S+_+I+B$[b]+r[b]>>>0,A=P+C>>>0;S=f,f=p,p=l,l=d+M>>>0,d=c,c=i,i=s,s=M+A>>>0}a[0]=a[0]+s>>>0,a[1]=a[1]+i>>>0,a[2]=a[2]+c>>>0,a[3]=a[3]+d>>>0,a[4]=a[4]+l>>>0,a[5]=a[5]+p>>>0,a[6]=a[6]+f>>>0,a[7]=a[7]+S>>>0}};function V$(e){return new F$().update(e).digestHex()}function ir(e,t){return e>>>t|e<<32-t}var K$=2e3,sk=25e7,Cn=o().trim().min(1).max(240),hn=o().regex(/^[a-f0-9]{64}$/),Qp=o().datetime({offset:!0}),O8=ve(o(),ke()).default({}),bt=u({id:Cn,contentHash:hn}).strict(),W$=bt.extend({revision:m().int().positive()}).strict(),Yp=u({id:Cn,path:o().trim().min(1).max(K$).refine(J$),contentHash:hn,sizeBytes:m().int().nonnegative().max(sk),mediaType:o().trim().min(1).max(200),visibility:k(["policy","verifier","host_private"])}).strict(),$8=u({id:Cn,contentHash:hn,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:m().int().nonnegative().max(sk).nullable().default(null)}).strict(),G$=k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function Z$(e){return`${JSON.stringify(Xp(e),null,2)}
|
|
108
|
+
`}function ok(e){return V$(e)}function Ht(e){return ok(Z$(e))}function N8(e,t){const{contentHash:n,...a}=e,r=Ht(a);if(n!==r)throw new Error(`${t} contentHash is ${n}; expected ${r}.`)}function J$(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Xp(e){return Array.isArray(e)?e.map(Xp):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Xp(n)]))}u({provider:Cn,model:Cn,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:hn.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:hn.nullable().default(null)}).strict();var Q$=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],Y$=pS(["acp:",o().regex(/^[a-z0-9][a-z0-9-]{0,100}$/)]),X$=dt([k(Q$),Y$]),Oh=u({providerId:X$,modelId:o().trim().min(1).max(300)}),e2=Bx.extend({mode:k(["nightly","approved_count"]),minimumTasks:m().int().min(1).max(1e4),maximumSpendUsd:m().positive().max(1e5),maximumDailySpendUsd:m().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."})}),D8=67108864,ef=524288,ic=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function $h(e){return JSON.stringify(tf(e))}function t2(e){return new TextEncoder().encode($h(e)).byteLength}async function n2(e){const t=new TextEncoder().encode($h(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 a2(e,t,n){const a=t2(e);if(a>t)throw new ic("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function tf(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new ic("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=>tf(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new ic("non_json_value","Canonical JSON accepts only plain objects.");const n={};for(const a of Object.keys(e).sort()){const r=e[a];if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new ic("non_json_value",`Canonical JSON cannot contain ${typeof r} at ${a}.`);n[a]=tf(r)}return n}throw new ic("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var jt=o().trim().min(1).max(500),pr=o().regex(/^[a-f0-9]{64}$/),_a=o().datetime({offset:!0}),Gs=u({id:jt,contentHash:pr}).strict(),Ba=Gs.extend({revision:m().int().positive()}).strict(),Gc=u({schemaVersion:x("openpond.baseModelPreference.v1"),modelId:jt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:jt.nullable(),source:k(["managed","local","builtin"])}).strict(),ik=k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),r2=u({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:ik,parameterization:k(["lora","full"])}).catchall(ke()),s2=u({profileProjectId:jt,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Gs}).strict(),o2=u({profileProjectId:jt,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),catalogHash:pr,definitionId:jt,harnessRelease:Gs,tasksetRelease:Gs}).strict(),ck=u({tasksetRef:Ba.nullable().default(null),evaluationTasksetRef:Ba.nullable().optional(),profileSource:s2.nullable().optional(),profileEvaluation:o2.nullable().optional(),rewardBindingRef:Ba.nullable().optional(),tasksetRelease:Gs.nullable().default(null),harnessRelease:Gs.nullable().default(null),baseModel:Gc.nullable().default(null),method:ik.nullable().default(null),destinationId:jt.nullable().default(null),managedRolloutPlacement:k(["local","remote"]).default("remote"),managedGpuPlacementObjective:k(["fast","balanced","economical"]).default("balanced"),managedGpuRequirement:k(["any","h100_hbm3"]).default("any"),runPreset:k(["small","standard","custom","small_experiment"]).nullable().default(null),recipe:r2.nullable().default(null),preferredMaximumSpendUsd:m().nonnegative().nullable().default(null),preferredRetentionDays:m().int().nonnegative().nullable().default(null)}).strict(),lk=ck.omit({managedGpuRequirement:!0}),i2=u({schemaVersion:x("openpond.hostedModelProjectLink.v1"),apiOrigin:o().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:jt,projectId:jt,portableProjectId:jt,revision:m().int().positive(),etag:pr,syncedSourceRevision:m().int().positive(),syncedAt:_a,tasksets:v(u({localTasksetId:jt,localTasksetHash:pr.nullable().default(null),releaseId:jt,releaseRevision:m().int().positive(),releaseHash:pr,packageHash:pr.nullable().default(null),hostedTasksetId:jt,syncedAt:_a}).strict()).max(1e4).default([])}).strict(),c2=u({localTasksetId:jt,releaseId:jt,releaseRevision:m().int().positive(),releaseHash:pr,state:k(["syncing","synced","sync_failed"]),hostedTasksetId:jt.nullable().default(null),lastAttemptAt:_a,syncedAt:_a.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),dk=u({schemaVersion:x("openpond.modelProject.v2"),id:jt,profileId:jt,revision:m().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Gc.nullable(),defaultDestinationId:jt.nullable(),trainingSetup:ck,hosted:i2.nullable().default(null),tasksetSyncs:v(c2).max(1e4).default([]),createdAt:_a,updatedAt:_a}).strict(),uk=dk.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),l2=u({schemaVersion:x("openpond.modelProjectSave.v1"),operationId:jt,expectedRevision:m().int().nonnegative(),project:uk,learning:e2.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."})}),mk=u({schemaVersion:x("openpond.modelProjectConfigurationCheck.v1"),configurationHash:pr,projectId:jt,expectedRevision:m().int().nonnegative(),checkedAt:_a,canSave:j(),deferred:v(k(["base_model","taskset"])).max(2),findings:v(u({code:jt,severity:k(["error","warning"]),message:o().min(1).max(5e3),field:o().min(1).max(500).nullable()}).strict()).max(100)}).strict();u({id:jt,name:o().min(1).max(500),available:j(),preference:Gc}).strict();function d2(e){try{Aa(e,ef)}catch{throw new f2(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return l2.parse(e)}async function u2(e,t,n){Aa(e,ef);const a=uk.parse(e);a2(a,ef,"Model configuration");const r=await n2({project:a,expectedRevision:t});return d2({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${r}`,expectedRevision:t,project:a})}u({schemaVersion:x("openpond.hostedModelProjectSync.v2"),portableProjectId:jt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Gc.nullable(),defaultDestinationId:jt.nullable(),trainingSetup:lk,sourceRevision:m().int().positive(),sourceUpdatedAt:_a,expectedEtag:pr.nullable().default(null)}).strict();var m2=u({id:jt,teamId:jt,portableProjectId:jt,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Gc.nullable(),defaultDestinationId:jt.nullable(),trainingSetup:lk,sourceRevision:m().int().positive(),sourceUpdatedAt:_a,revision:m().int().positive(),etag:pr,createdAt:_a,updatedAt:_a}).strict(),p2=u({kind:k(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Gs,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:_a}).strict();u({project:m2,resources:v(p2).max(1e4),jobCount:m().int().nonnegative(),latestJobIds:v(jt).max(100)}).strict();u({schemaVersion:x("openpond.modelProjectApiError.v2"),code:o().trim().min(1).max(200),message:o().trim().min(1).max(5e3),retryable:j().default(!1),requestId:o().trim().min(1).max(500).nullable().default(null),details:ve(o(),ke()).default({})}).strict();var f2=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}};const h2="openpond.connectedEvidence.v1",g2="connected-evidence-1",jl={files:100,sourceBytes:32*1024*1024,events:1e5,sessions:1e3,boundaries:5e3},fa=o().min(1).max(500),mc=o().regex(/^[a-f0-9]{64}$/),v2=o().datetime().nullable(),Ml=m().int().nonnegative().nullable(),pk=k(["native_chat","native_work","codex","claude_code","hermes","openclaw","opencode","grok_build","pi","oh_my_pi"]),b2=u({invocationId:fa,inputTokens:Ml,outputTokens:Ml,cachedInputTokens:Ml,totalTokens:Ml,provenance:k(["billed_invocation","reported_invocation","reported_cumulative"])}).strict(),Kv=u({id:fa,sequence:m().int().nonnegative(),occurredAt:v2,kind:k(["message","tool_call","tool_result","compaction","artifact","terminal","usage","unknown"]),role:k(["user","assistant","system","tool"]).nullable(),callId:fa.nullable(),parentId:fa.nullable(),content:ds(),usage:b2.nullable()}).strict(),y2=u({id:fa,familyKey:fa,projection:k(["turn","conversation"]),requestEventId:fa,start:m().int().nonnegative(),end:m().int().positive(),inputHash:mc,outputHash:mc.nullable(),revisionHash:mc,terminal:k(["completed","failed","cancelled","unknown"]),coverage:u({answer:j(),context:k(["retained","compacted","unknown"]),process:k(["retained","partial","absent"]),artifacts:k(["retained","references_only","absent"]),replay:x("unavailable"),gaps:v(o().max(500)).max(100)}).strict()}).strict();u({schemaVersion:x(h2),normalizerVersion:x(g2),origin:pk,sessionId:fa,branchId:fa.nullable(),parentSessionId:fa.nullable(),exporterVersion:o().max(200).nullable(),acquisition:u({machineId:fa,sourceInstanceId:fa}).strict().optional(),sourceFiles:v(u({path:fa,contentHash:mc,sizeBytes:m().int().nonnegative()}).strict()).max(jl.files),events:v(Kv).max(jl.events),unmappedEvents:v(Kv).max(jl.events),boundaries:v(y2).max(jl.boundaries),warnings:v(o().max(500)).max(100),contentHash:mc}).strict();const S2=u({schemaVersion:x("openpond.humanResultView.v1"),executionId:o().min(1),executionHash:o().regex(/^[a-f0-9]{64}$/),selection:v(gn).max(1e4),coverage:u({pending:m().int().nonnegative(),submitted:m().int().nonnegative(),accepted:m().int().nonnegative(),rejected:m().int().nonnegative(),cancelled:m().int().nonnegative()}).strict(),results:v(u({review:gn,decision:gn.nullable(),attemptIds:v(o().min(1)).min(1).max(2),mode:k(["individual","pairwise"]),origin:k(["hosted_retained","recorded_evidence","owner_attested_local","native_local"]),status:k(["pending","submitted","accepted","rejected","cancelled"]),grader:gn,answers:v(ci).max(100)}).strict()).max(1e4)}).strict(),Wv=S2.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),Cd=o().regex(/^[a-f0-9]{64}$/),Rc=o().min(1).max(240),Ol={feedbackKey:Rc,criterionId:Rc},x2=st("kind",[u({...Ol,kind:x("normalized_score"),minimum:m().finite(),maximum:m().finite(),passThreshold:m().min(0).max(1).optional()}).strict(),u({...Ol,kind:x("boolean")}).strict(),u({...Ol,kind:x("category")}).strict(),u({...Ol,kind:x("preference_score"),tieScore:m().min(0).max(1).nullable()}).strict()]),Gv=u({execution:se,resultHash:Cd,reviews:v(u({review:gn,decision:gn}).strict()).min(1).max(1e4)}).strict(),fk=u({rules:v(x2).min(1).max(100),baseline:Gv,candidate:Gv}).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."})}),Zv=u({manifest:os,result:is}).strict(),Jv=u({id:Rc,manifestHash:Cd,resultHash:Cd}).strict(),k2=u({schemaVersion:x("openpond.humanComparisonProjection.v1"),teamId:Rc,projectId:Rc,selections:fk,original:u({baseline:Jv,candidate:Jv}).strict(),humanResults:u({baseline:Wv,candidate:Wv}).strict(),baseline:Zv,candidate:Zv}).strict(),nf=k2.extend({contentHash:Cd}).strict();function Ym(e){throw new Fa(e,409)}function w2(e,t){const n=nf.parse(e),{contentHash:a,...r}=n;a!==Qe(r)&&Ym("human_comparison_projection_invalid");for(const s of["baseline","candidate"]){const i=Xo(n[s]),c=i.manifest.lineage,d=c?.humanProjection,l=n.original[s],p=n.selections[s];(!c||!d||d.originalManifest.id!==l.id||d.originalManifest.contentHash!==l.manifestHash||d.selectionHash!==Qe(p)||d.rulesHash!==Qe(n.selections.rules)||Qe(c.execution)!==Qe(p.execution)||i.manifest.teamId!==n.teamId||n.humanResults[s].contentHash!==p.resultHash)&&Ym("human_comparison_projection_lineage_changed");const{contentHash:f,...S}=n.humanResults[s];(Qe(S)!==f||S.executionId!==p.execution.id||S.executionHash!==p.execution.contentHash||Qe(S.selection)!==Qe(p.reviews.map(b=>b.review)))&&Ym("human_comparison_human_result_changed")}return n}const hk=u({adapterId:E,placement:k(["local","remote","colocated","provider_native"]),runtimeVersion:o().trim().min(1).max(200),capabilityReceipt:W}).strict(),gk=u({maxTurns:m().int().positive().max(1e5),timeoutMs:m().int().positive().max(864e5),maxOutputBytes:m().int().positive().max(25e7),maximumSpendUsd:m().nonnegative().nullable()}).strict(),I2=u({schemaVersion:x("openpond.runManifest.v1"),id:E,harnessRelease:se,tasksetRelease:se,model:eh,runtimeTarget:hk,limits:gk,approval:u({id:E,contentHash:W}).strict().nullable(),createdAt:Ce,metadata:ha}).strict();I2.extend({contentHash:W}).strict();const _2=u({schemaVersion:x("openpond.attemptReceipt.v1"),id:E,runManifest:se,taskId:E,seed:o().trim().min(1).max(500),terminal:j(),failureClass:Gd.nullable(),outputHash:W.nullable(),traceHash:W,artifactRefs:v(br).max(1e5),graderEvidenceRefs:v(br).max(1e4),startedAt:Ce,completedAt:Ce,latencyMs:m().int().nonnegative(),costUsd:m().nonnegative().nullable(),legacyAttemptRef:E.nullable().default(null),metadata:ha}).strict(),C2=_2.extend({contentHash:W}).strict(),R2=u({schemaVersion:x("openpond.evaluationResult.v1"),id:E,runManifest:se,harnessRelease:se,tasksetRelease:se,model:eh,receiptRefs:v(se).min(1).max(1e6),attemptCount:m().int().positive(),rewardEligibleCount:m().int().nonnegative(),terminalCount:m().int().nonnegative(),meanScore:m().min(0).max(1).nullable(),failureCounts:ve(Gd,m().int().nonnegative()),authoredMetric:hx.optional(),metadata:ha}).strict(),P2=R2.extend({contentHash:W}).strict(),T2=u({schemaVersion:x("openpond.harnessCompatibility.v1"),id:E,baseHarnessRelease:se,candidateHarnessRelease:se,tasksetRelease:se,environmentHash:W,toolContractHash:W,policyHash:W,graderInterfaceHash:W,metadata:ha}).strict();T2.extend({contentHash:W}).strict();const vk=k(["scored","unscorable"]),Nh=k(["policy","environment","collector","verifier","provider","host","user","scheduler"]),A2=k(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),E2=u({schemaVersion:x("openpond.environmentRelease.v1"),id:E,revision:m().int().positive(),contract:Ix,actionSchemaRef:aa.nullable(),observationSchemaRef:aa.nullable(),stateSchemaRef:aa.nullable(),artifactCollection:u({maxArtifacts:m().int().positive().max(1e5),maxTotalBytes:m().int().positive().max(1e10)}).strict(),adapterConformanceHashes:ve(E,W),metadata:ha}).strict(),Dh=E2.extend({contentHash:W}).strict(),j2=k(["collected","missing","skipped","failed"]),Qv=k(["not_requested","passed","failed"]),M2=u({requiredOutputPath:o().trim().min(1).max(2e3).nullable(),collectedPath:o().trim().min(1).max(4e3).nullable(),declaredMediaType:o().trim().min(1).max(200).nullable(),detectedMediaType:o().trim().min(1).max(200).nullable(),artifact:br.nullable(),status:j2,parseStatus:Qv,schemaStatus:Qv,errorCode:E.nullable(),failureOwner:Nh.nullable(),evidenceRefs:v(br).max(1e4),metadata:ha}).strict(),O2=u({schemaVersion:x("openpond.artifactManifest.v1"),id:E,attemptRef:se,entries:v(M2).max(1e5),createdAt:Ce,metadata:ha}).strict();O2.extend({contentHash:W}).strict();const $2=u({schemaVersion:x("openpond.verifierSetRelease.v1"),id:E,revision:m().int().positive(),graders:v(Ax).max(1e3),isolation:u({processBoundary:k(["same_process","isolated_process","container"]),networkPolicy:x("none"),defaultTimeoutMs:m().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:v(se).max(1e4),metadata:ha}).strict(),Lh=$2.extend({contentHash:W}).strict(),N2=u({verifierId:E,verifierVersion:o().trim().min(1).max(100),status:vk,rawScore:m().finite().nullable(),normalizedScore:m().min(0).max(1).nullable(),weight:m().nonnegative().max(1e3),passed:j(),hardGate:j(),rewardEligible:j(),rewardContribution:m().min(0).max(1).nullable(),failureOwner:Nh.nullable(),feedback:v(o().max(2e4)).max(1e3),visibleEvidenceRefs:v(br).max(1e4),privilegedEvidenceRefs:v(br).max(1e4),metadata:ha}).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"]})}),bk=u({schemaVersion:x("openpond.rewardReceipt.v1"),id:E,attemptRef:se,verifierSetRef:se,artifactManifestRef:se,status:vk,reward:m().min(0).max(1).nullable(),learningEligible:j(),passed:j(),outcomeClass:A2,failureOwner:Nh.nullable(),components:v(N2).min(1).max(1e4),visibleEvidenceRefs:v(br).max(1e5),privilegedEvidenceRefs:v(br).max(1e5),supersedes:se.nullable(),createdAt:Ce,metadata:ha}).strict();function yk(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"]})}bk.superRefine(yk);bk.extend({contentHash:W}).strict().superRefine(yk);const D2=st("kind",[u({kind:x("model"),model:eh,configurationHash:W}).strict(),u({kind:x("fixture")}).strict()]),L2=st("kind",[u({kind:x("taskset"),environmentRelease:se,verifierSetRelease:se,policyHash:W}).strict(),u({kind:x("harness"),harnessRelease:se}).strict()]),Sk=u({receiptId:E,taskId:E,seed:o().trim().min(1).max(500),fixtureId:E.nullable()}).strict(),z2=u({schemaVersion:x("openpond.tasksetRunManifest.v1"),id:E,tasksetRelease:se,packageHash:W,execution:L2,profileEvaluation:Id.optional(),policy:D2,gradingRole:x("evaluation"),metricPolicy:Vc,population:v(Sk).min(1).max(1e5),runtimeTarget:hk,limits:gk,createdAt:Ce,metadata:ha}).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."})}),xk=z2.safeExtend({contentHash:W}),H2=o().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."),kk=dt([yi(),o().max(262144),m().finite(),u({integer:H2}).strict(),u({blobBase64:o().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),Yv=o().min(1).max(128).refine(e=>!e.includes("\0")),U2=u({tables:v(u({name:Yv,columns:v(u({name:Yv,type:k(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:v(v(kk).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,r]of e.tables.entries()){const s=r.name.toLowerCase();(n.has(s)||s.startsWith("sqlite_"))&&t.addIssue({code:"custom",path:["tables",a,"name"],message:"Table names must be unique and outside SQLite's reserved namespace."}),n.add(s),new Set(r.columns.map(i=>i.name.toLowerCase())).size!==r.columns.length&&t.addIssue({code:"custom",path:["tables",a,"columns"],message:"Column names must be unique."}),r.rows.some(i=>i.length!==r.columns.length)&&t.addIssue({code:"custom",path:["tables",a,"rows"],message:"Each row must match the declared columns."})}}),Xv=u({schemaVersion:x("openpond.sqlExecution.v1"),snapshot:U2,sql:o().min(1).max(65536).refine(e=>!e.includes("\0")),maxRows:m().int().min(1).max(4096),maxResultBytes:m().int().min(256).max(262144)}).strict();st("status",[u({status:x("completed"),columns:v(o()).max(128),rows:v(v(kk).max(128)).max(4096)}).strict(),u({status:x("rejected"),code:k(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const $l=u({scope:k(["input","initialState","state","arguments"]),path:v(o().min(1).max(256)).max(16)}).strict(),eb={id:o().min(1).max(128),operation:k(["step","collect"]),toolName:o().min(1).max(500).optional(),timeoutMs:m().int().min(1).max(2e4)},q2=st("kind",[u({...eb,kind:x("sqlite.v1"),sql:$l,snapshot:$l,maxRows:Xv.shape.maxRows,maxResultBytes:Xv.shape.maxResultBytes}).strict(),u({...eb,kind:x("javascript.v1"),source:$l,cases:$l,exportName:o().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/).max(128),maxCases:m().int().min(1).max(32),maxResultBytes:m().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."})}),B2=u({schemaVersion:x("openpond.javascriptEnvironment.v1"),id:o().trim().min(1).max(500),revision:m().int().positive(),module:aa.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:v(qS).min(1).max(200),maxSteps:m().int().min(1).max(1e3),maxStateBytes:m().int().min(1).max(1048576),maxObservationBytes:m().int().min(1).max(262144),operationTimeoutMs:m().int().min(1).max(3e4),executionServices:v(q2).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,r)=>{wh(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",r,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==Qe(a.inputSchema)&&t.addIssue({code:"custom",path:["tools",r,"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,r)=>{const s=e.tools.find(i=>i.name===a.toolName);a.operation==="step"&&!s&&t.addIssue({code:"custom",path:["executionServices",r,"toolName"],message:"Execution services must target a declared tool."}),a.timeoutMs>=Math.min(e.operationTimeoutMs,s?.timeoutMs??e.operationTimeoutMs)&&t.addIssue({code:"custom",path:["executionServices",r,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),F2=B2.safeExtend({contentHash:o().regex(/^[a-f0-9]{64}$/)});k(["create","reset","step","collect","destroy"]);u({state:ve(o(),ke()),observation:ve(o(),ke())}).strict();var V2=u({schemaVersion:x("openpond.connectedDatasetSource.v1"),kind:x("connected_activity"),id:o().min(1).max(240),profileId:o().min(1).max(240),title:o().min(1).max(500),sourceHash:o().regex(/^[a-f0-9]{64}$/),occurredAt:o().datetime(),licensingStatus:k(["pending","approved","review","blocked"]),secretScanStatus:k(["pending","passed","blocked"]),piiScanStatus:k(["pending","passed","review","blocked"]),origin:pk,sourceId:o().min(1).max(500),sessionId:o().min(1).max(500),normalizerVersion:o().min(1).max(200),projection:k(["turn","conversation"]),ownerUserId:o().min(1).max(500),purpose:x("recorded_evaluation"),metadata:ve(o(),ke()).default({})}).strict(),Ca=o().trim().min(1).max(240),Hr=o().trim().min(1),cs=o().trim().min(8).max(256),wk=o().trim().min(1).max(1e3).refine(e=>!e.startsWith("/")&&!e.startsWith("\\")&&!e.split(/[\\/]/).includes(".."),"Artifact paths must be relative and stay inside the Dataset."),bs=k(["train","validation","test","frozen_eval"]),K2=u({name:o().trim().min(1).max(500),semanticRole:k(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),logicalType:k(["string","integer","float","boolean","json","messages"]),nullable:j(),policy:k(["visible","privileged","metadata"])}),W2=u({schemaVersion:x("openpond.datasetSemanticSchema.v1"),fields:v(K2).min(1).max(1e4),schemaHash:cs}),G2=u({id:Ca,split:bs,path:wk,contentHash:cs,schemaHash:cs,sizeBytes:m().int().nonnegative(),rowCount:m().int().positive(),rowGroupCount:m().int().positive()}),zh=u({schemaVersion:x("openpond.datasetArtifact.v1"),id:Ca,tasksetId:Ca,tasksetRevision:m().int().positive(),contentHash:cs,format:x("parquet"),schema:W2,shards:v(G2).min(1).max(1e5),rowCount:m().int().positive(),splitCounts:ve(bs,m().int().nonnegative()),sourceReceiptRefs:v(Ca).min(1).max(1e5),mappingHash:cs,qualityReportHash:cs,createdAt:Hr}),Z2=u({schemaVersion:x("openpond.datasetArtifactSummary.v1"),artifactId:Ca,tasksetId:Ca,tasksetRevision:m().int().positive(),format:x("parquet"),rowCount:m().int().positive(),splitCounts:ve(bs,m().int().nonnegative()),sizeBytes:m().int().nonnegative(),contentHash:cs,available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:Hr}),J2=u({schemaVersion:x("openpond.datasetCatalogItem.v1"),tasksetId:Ca,tasksetRevision:m().int().positive(),artifactId:Ca.nullable(),name:o().trim().min(1).max(500),status:k(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),storageKind:k(["inline","parquet"]),rowCount:m().int().nonnegative(),splitCounts:ve(bs,m().int().nonnegative()),sizeBytes:m().int().nonnegative().nullable(),available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:Hr,updatedAt:Hr});u({schemaVersion:x("openpond.datasetCatalog.v1"),profileId:Ca,datasets:v(J2),generatedAt:Hr});u({schemaVersion:x("openpond.datasetArtifactRegistry.v1"),manifest:zh,profileId:Ca,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:wk,available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),verifiedAt:Hr.nullable(),createdAt:Hr,updatedAt:Hr});u({split:bs.nullable().default(null),cursor:o().trim().min(1).max(2e3).nullable().default(null),limit:m().int().min(1).max(100).default(25),columns:v(o().trim().min(1).max(500)).max(100).default([])});u({schemaVersion:x("openpond.datasetRowPage.v1"),tasksetId:Ca,tasksetRevision:m().int().positive(),artifactHash:cs,split:bs.nullable(),rows:v(ve(o(),ke())).max(100),nextCursor:o().max(2e3).nullable(),totalRows:m().int().nonnegative(),returnedRows:m().int().nonnegative()});var Q2=u({schemaVersion:x("openpond.datasetStorageSettings.v1"),datasetStorePath:o().trim().min(1).max(4e3),updatedAt:Hr}),Y2=u({id:Ca,label:o().trim().min(1).max(500),path:o().trim().min(1).max(4e3),datasetStorePath:o().trim().min(1).max(4e3),kind:k(["local","network","removable","cache"]),configured:j(),mounted:j(),writable:j(),totalBytes:m().int().nonnegative().nullable(),freeBytes:m().int().nonnegative().nullable()});u({schemaVersion:x("openpond.datasetStorageState.v1"),settings:Q2,storageRoots:v(Y2)});u({datasetStorePath:o().trim().min(1).max(4e3)});var ei=o().trim().min(1).max(240),X2=o().trim().min(1),li=o().trim().min(8).max(256),eN=ve(o(),ke()).default({}),tN=o().trim().min(7).max(256),nN=k(["pending","approved","review","blocked"]),iu=u({id:ei,profileId:ei,title:o().trim().min(1).max(500),sourceHash:li,occurredAt:X2,licensingStatus:nN,secretScanStatus:k(["pending","passed","blocked"]),piiScanStatus:k(["pending","passed","review","blocked"]),metadata:eN}),aN=iu.extend({schemaVersion:x("openpond.huggingFaceDatasetSource.v1"),kind:x("huggingface"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),revision:tN,configuration:o().trim().min(1).max(500),upstreamSplits:v(o().trim().min(1).max(500)).min(1).max(1e3),gated:j(),private:j(),declaredLicense:o().trim().min(1).max(500).nullable(),sourceFileHashes:v(li).min(1).max(1e5)}),rN=iu.extend({schemaVersion:x("openpond.uploadedFileDatasetSource.v1"),kind:x("uploaded_file"),originalFileNames:v(o().trim().min(1).max(500)).min(1).max(1e3),mediaTypes:v(o().trim().min(1).max(200)).min(1).max(1e3),sourceFileHashes:v(li).min(1).max(1e3),totalBytes:m().int().nonnegative(),parserVersion:o().trim().min(1).max(200)}),sN=iu.extend({schemaVersion:x("openpond.generatedDatasetSource.v1"),kind:x("generated"),generatorId:ei,generatorVersion:o().trim().min(1).max(200),seed:m().int(),generatorHash:li}),oN=iu.extend({schemaVersion:x("openpond.learningBatchDatasetSource.v1"),kind:x("learning_batch"),batch:u({id:ei,revision:m().int().positive(),contentHash:li}).strict(),taskDefinition:u({id:ei,revision:m().int().positive(),contentHash:li}).strict(),admittedBy:ei}),iN=st("kind",[aN,rN,sN,oN]),cN=u({schemaVersion:x("openpond.harnessActionBinding.v1"),actionId:Cn,modelToolName:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(1e3),inputSchema:ve(o(),ke()),actionSchemaHash:hn,agentRelease:bt,implementationHash:hn,runtimeBindingId:Cn,capabilityReceiptHash:hn,sideEffect:k(["read","write"]),studentVisible:j(),timeoutMs:m().int().positive().max(36e5),episodeArgumentBindings:v(u({argument:Cn,source:x("case_id")}).strict()).max(20).default([])}).strict(),wt=o().trim().min(1).max(240),Hh=o().trim().min(1),lN=o().trim().min(8).max(256),Uh=o().trim().regex(/^[a-f0-9]{64}$/),dN=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Ga=ve(o(),ke()).default({}),cu=wt.nullable();function Zc(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function uN(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var di=bs,Ik=k(["general","benchmark"]),_k=u({schemaVersion:x("openpond.tasksetBenchmark.v1"),definitionId:wt,releaseId:wt,releaseHash:Uh,managedReleasePath:o().trim().min(1).max(1e3).refine(Zc,"Benchmark release paths must remain relative."),adaptationSplit:di,evaluationSplit:di,primaryMetric:k(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:k(["none","non_regression","all_pass"]),source:k(["builtin","imported"]),metadata:Ga}),Ck=u({schemaVersion:x("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:wt,releaseHash:Uh,publishedAt:Hh,metadata:Ga}),mN=u({status:k(["pending","granted","denied","revoked"]),scope:k(["metadata_only","selected_turns","full_session"]),grantedBy:cu,grantedAt:Hh.nullable(),purpose:x("task_authoring_and_evaluation")}),Rk=u({schemaVersion:x("openpond.trainingSource.v1"),id:wt,profileId:wt,sessionId:wt,turnIds:v(wt).max(1e3).default([]),workspaceId:cu,sourceHash:lN,clusterKey:wt,title:o().trim().min(1).max(500),occurredAt:Hh,consent:mN,connectedAppIds:v(wt).max(100).default([]),secretScanStatus:k(["pending","passed","blocked"]),piiScanStatus:k(["pending","passed","review","blocked"]),licensingStatus:k(["pending","approved","review","blocked"]),metadata:Ga}),Pk=dt([Rk,iN,V2]),qh=u({policyVisibleFields:v(wt).max(1e3).default([]),privilegedFields:v(wt).max(1e3).default([]),hiddenGraderRefs:v(wt).max(100).default([]),connectedAppScopes:v(wt).max(100).default([])}),pN=u({id:wt,sourceRefId:wt,artifactRef:o().trim().min(1).max(4e3).refine(Zc,"Task asset references must be safe relative paths."),fileName:o().trim().min(1).max(500).refine(uN,"Task asset file names must not contain path separators."),mediaType:o().trim().min(1).max(200),sha256:Uh,sizeBytes:m().int().nonnegative().max(25e7),split:di,metadata:Ga}),fN=u({path:o().trim().min(1).max(1e3).refine(Zc,"Required output paths must stay inside the Work output directory."),mediaType:o().trim().min(1).max(200),schemaRef:wt.nullable().optional(),maxBytes:m().int().positive().max(1e7).optional(),metadata:Ga}),lu=u({schemaVersion:x("openpond.taskData.v1"),id:wt,clusterKey:wt,split:di,input:ve(o(),ke()),expectedOutput:ve(o(),ke()).nullable(),policyVisibleContext:ve(o(),ke()).default({}),privilegedContextRef:cu,sourceRefs:v(wt).min(1).max(100),assets:v(pN).max(1e3).optional(),resourceRefs:v(wt).max(1e3).optional(),requiredOutputs:v(fN).max(100).optional(),tags:v(wt).max(100).default([]),metadata:Ga}),hN=u({id:wt,kind:k(["file","catalog","configuration","code_module"]),path:o().trim().min(1).max(1e3).refine(Zc,"Environment resource paths must remain relative."),mediaType:o().trim().min(1).max(200).nullable().optional(),visibility:k(["policy_visible","policy_hidden","privileged"]),required:j(),metadata:Ga}),wi=u({id:wt,taskId:cu,sourceRefs:v(wt).min(1).max(100),artifactRef:wt,approved:j(),confidence:m().min(0).max(1),metadata:Ga}),Tk=wi.extend({kind:x("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),Ak=wi.extend({kind:x("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),Ek=wi.extend({kind:x("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),jk=wi.extend({kind:x("feedback"),feedback:o().max(1e5),polarity:k(["positive","negative","mixed","neutral"])}),Mk=wi.extend({kind:x("reward"),task:o().max(1e5),rules:v(u({id:wt,points:m().finite(),condition:o().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:m().finite(),executable:j()}),Ok=wi.extend({kind:x("label"),labelKind:x("rubric"),task:o().max(1e5),criteria:v(u({id:wt,label:o().trim().min(1).max(500),description:o().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:u({positive:o().trim().min(1).max(2e5),negative:o().trim().min(1).max(2e5),boundary:o().trim().min(1).max(2e5)})});st("kind",[Tk,Ak,Ek,jk,Mk,Ok]);var $k=u({demonstrations:v(Tk).max(1e5).default([]),preferences:v(Ak).max(1e5).default([]),corrections:v(Ek).max(1e5).default([]),feedback:v(jk).max(1e5).default([]),rewards:v(Mk).max(1e5).default([]),labels:v(Ok).max(1e5).default([])}),Nk=u({protocolVersion:x("openpond.taskEnvironment.v1"),kind:k(["chat","agent","program","stateful_harness","work"]),entrypoint:o().trim().min(1).max(1e3),stateful:j(),deterministicSeeds:j(),toolNames:v(wt).max(200).default([]),actionBindings:v(cN).max(200).optional(),lifecycle:v(k(["create","reset","step","grade","cleanup"])).min(1),defaultTimeoutMs:m().int().positive().max(36e5),networkPolicy:k(["none","declared_read_only","declared_scoped"]),resources:v(hN).max(1e4).optional(),metadata:Ga}),Bh=u({schemaVersion:x("openpond.tasksetCapabilities.v1"),taskKind:k(["chat","single_agent","multi_agent","custom_program"]),supportedSignals:v(k(["demonstration","preference","correction","feedback","reward","label"])),compatibleMethods:v(k(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"])),rewardKinds:v(k(["none","exact","deterministic","model_judge","human"])),requiresTools:j(),requiresState:j(),requiresPrivilegedGrading:j(),environmentPlacements:v(k(["local","remote","colocated","provider_native"])),exportable:j(),portabilityBlockers:v(o().trim().min(1).max(2e3)).default([])}),du=u({id:wt,version:o().trim().min(1).max(100),label:o().trim().min(1).max(500),weight:m().min(0).max(1e3).default(1),hardGate:j().default(!1),rewardEligible:j().default(!1),privileged:j().default(!1),metadata:Ga}),gN=du.extend({kind:k(["content","schema","file","diff","test","runtime_event","state"]),config:ve(o(),ke())}),vN=du.extend({kind:x("model_judge"),rubric:o().trim().min(1).max(5e4),judge:Oh,calibrationFixtureRefs:v(wt).min(1).max(500),calibrationStatus:k(["pending","passed","failed"]),temperature:m().min(0).max(2).default(0)}),bN=du.extend({kind:x("human"),form:Kc.optional(),rubric:o().trim().min(1).max(5e4),reviewerRole:o().trim().min(1).max(500)}),yN=du.extend({kind:x("custom_verifier"),runtime:Rx.optional(),module:o().trim().min(1).max(1e3).refine(Zc,"Custom verifier modules must use a safe relative path."),exportName:dN,timeoutMs:m().int().positive().max(3e5),networkPolicy:x("none")}),uu=dt([gN,vN,bN,yN]),Fh=k(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),Dk=u({id:wt,taskId:wt,label:Fh,output:ve(o(),ke()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:j(),expectedRewardEligible:j(),metadata:Ga});o().regex(/^[a-f0-9]{64}$/);var SN=u({environment:Dh,verifierSet:Lh,javascript:F2}).strict();u({actions:v(u({name:o().min(1).max(64),arguments:ve(o(),ke())}).strict()).max(1e3)}).strict();var xN=u({environment:Dh,verifierSet:Lh}).strict(),kN=u({scopeId:o().trim().min(1).max(500),modelId:o().trim().min(1).max(500)}).strict();u({schemaVersion:x("openpond.modelTasksetDerivation.v1"),owner:kN,root:Ba,parent:Ba}).strict();var wN=u({taskset:jx,taskDefinition:au,rewardBinding:Ph,rewards:v(nu).min(1).max(100),assets:v(su).max(1e3),executionResources:xN.optional(),execution:SN.optional(),instructionMode:x("per_task").optional()}).strict(),IN=u({batch:Vx,evidence:v(ru).min(1).max(1e4),decisions:v(jh).min(1).max(1e4),sources:v(Eh).min(1).max(1e4),assets:v(su).max(1e3)}).strict(),_N=64*1024*1024,CN=u({asset:Yp,base64:o().max(Math.ceil(_N/3)*4)}).strict();u({schemaVersion:x("openpond.connectedRewardCalibrationProjection.v1"),sourceReward:vs,fixtureSet:Yp,calibrationCheck:Ye,fixture:Yx,fixtureHash:o().regex(/^[a-f0-9]{64}$/),checkResultHash:o().regex(/^[a-f0-9]{64}$/),independentCalibrationTask:x(!0),closureRef:Yp,graderId:o().min(1).max(240).optional()}).strict();var RN=wN.omit({taskset:!0,executionResources:!0}),PN=u({schemaVersion:x("openpond.tasksetPackage.v1"),taskset:jx,environment:Dh,verifierSet:Lh,files:v(CN).max(1e4),modelResources:RN.optional(),learningResources:IN.optional()}).strict(),L8=PN.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),fr=o().trim().min(1).max(240),Pc=o().trim().min(1),Rd=o().trim().min(8).max(256),Lk=ve(o(),ke()).default({}),TN=fr.nullable(),AN=["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"],EN=k(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),zk=k(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Fn=o().trim().max(1e5),Hk=st("kind",[u({kind:x("demonstrations"),behavior:Fn,examples:v(u({id:fr,prompt:Fn,response:Fn})).max(1e3).default([])}),u({kind:x("preferences"),preference:Fn,pairs:v(u({id:fr,prompt:Fn,chosen:Fn,rejected:Fn,rationale:Fn})).max(1e3).default([])}),u({kind:x("verifiable_reward"),task:Fn,rules:v(u({id:fr,points:m().finite(),condition:Fn})).max(1e3).default([]),otherwisePoints:m().finite().default(0)}),u({kind:x("rubric"),task:Fn,criteria:v(u({id:fr,label:o().trim().max(500),description:Fn})).max(1e3).default([]),positiveExample:Fn,negativeExample:Fn,boundaryExample:Fn})]),jN=u({path:o().trim().min(1).max(1e3),role:k(["environment","verifier","fixture"]),content:o().max(25e4)}),Uk=u({primaryMethod:k(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:u({method:x("sft"),purpose:x("trajectory_bootstrap"),demonstrationRefs:v(fr).min(1).max(1e5),limitations:v(o().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),qk=k(["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"]),MN=u({method:k(["sft","dpo","grpo","ppo"]),status:k(["recommended","compatible","needs_dataset_work"]),reasonCodes:v(qk).default([]),reasons:v(o().trim().min(1).max(5e3)).default([])}),tb=u({code:fr,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()}),Bk=u({schemaVersion:x("openpond.tasksetReadiness.v1"),tasksetId:fr,tasksetHash:Rd,ready:j(),recommendedMethod:k(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:Uk.nullable().default(null),methodReadiness:v(MN).default([]),compatibleDestinationClasses:v(k(["export","custom","hosted_managed"])),blockers:v(tb).default([]),advisories:v(tb).default([]),warnings:v(o().trim().min(1).max(5e3)).default([]),generatedAt:Pc}),Fk=u({attempt:m().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:Pc}),ON=u({schemaVersion:x("openpond.taskAuthoringProvenance.v1"),model:Oh.nullable(),modelConfig:Lk,skillHash:Rd,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:zk.default("demonstrations"),buildSpecification:Hk.nullable().default(null),evidenceHashes:v(Rd).max(1e5),tasksetSdkVersion:o().trim().min(1).max(100),sourceCommit:o().trim().min(1).max(256).nullable(),repairHistory:v(Fk).max(1e3),createdAt:Pc}),Tc=u({schemaVersion:x("openpond.taskset.v1"),id:fr,revision:m().int().positive().default(1),profileId:fr,profileRelease:W$.nullable().optional(),createImproveRunId:TN.default(null),name:o().trim().min(1).max(500),objective:o().trim().max(2e4),purpose:Ik.default("general"),benchmark:_k.nullable().default(null),preferenceComparison:Ck.nullable().default(null),status:EN,sourceRefs:v(Pk).min(1).max(1e5),datasetArtifact:zh.nullable().optional(),policy:qh,environment:Nk,capabilities:Bh,metrics:Vc.optional(),tasks:v(lu).max(1e6),graders:v(uu).max(1e3),graderFixtures:v(Dk).max(1e5),learningSignals:$k,authoringProvenance:ON,readiness:Bk.nullable(),contentHash:Rd,createdAt:Pc,updatedAt:Pc,metadata:Lk}).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 Vk(e){return e.schemaVersion==="openpond.trainingSource.v1"}function $N(e,t={}){const n=Tc.safeParse(e);if(!n.success)return{valid:!1,taskset:null,computedHash:null,issues:n.error.issues.map(i=>({code:"schema_invalid",severity:"error",message:i.message,path:i.path.join(".")}))};const a=n.data,r=[];zN(a,r),DN(a,r),HN(a,r),qN(a,r),BN(a,r),t.purpose!=="publication"&&(a.graders.length||r.push({code:"graders_required",severity:"error",message:"Scored execution requires at least one grader.",path:"graders"}),NN(a,r,t)),FN(a,r),VN(a.capabilities,r,a),UN(a,r);const s=Kk(a);return a.contentHash!==s&&r.push({code:"content_hash_mismatch",severity:"error",message:`Taskset contentHash is ${a.contentHash}, expected ${s}.`,path:"contentHash"}),{valid:!r.some(i=>i.severity==="error"),taskset:a,computedHash:s,issues:r}}function NN(e,t,n){const a=e.graders.length>0&&e.graders.every(i=>i.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 r=new Set(e.tasks.map(i=>i.id)),s=new Set(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]);for(const i of e.graderFixtures)!e.datasetArtifact&&!r.has(i.taskId)&&t.push({code:"grader_fixture_task_missing",severity:"warning",message:`Fixture ${i.id} references a task outside this Taskset revision (${i.taskId}).`,path:`graderFixtures.${i.id}.taskId`}),s.delete(i.label),i.label==="infrastructure_failure"&&!i.infrastructureError&&t.push({code:"infrastructure_fixture_error_missing",severity:"error",message:`Infrastructure fixture ${i.id} must declare an infrastructure error.`,path:`graderFixtures.${i.id}.infrastructureError`});for(const i of a?[]:s)t.push({code:"grader_fixture_missing",severity:"warning",message:`Taskset does not include the optional ${i} grader calibration fixture.`,path:"graderFixtures"})}function DN(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((d,l)=>d+l,0),r=n.shards.reduce((d,l)=>d+l.rowCount,0);(a!==n.rowCount||r!==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 s=new Map;for(const d of n.shards)s.set(d.split,(s.get(d.split)??0)+d.rowCount);for(const[d,l]of Object.entries(n.splitCounts))(s.get(d)??0)!==l&&t.push({code:"dataset_artifact_split_count_mismatch",severity:"error",message:`Dataset artifact ${d} shard counts do not match its manifest.`,path:`datasetArtifact.splitCounts.${d}`});const{contentHash:i,...c}=n;Ht(c)!==n.contentHash&&t.push({code:"dataset_artifact_hash_mismatch",severity:"error",message:"Dataset artifact manifest content hash is invalid.",path:"datasetArtifact.contentHash"})}function LN(e){return Kk(e)}function Kk(e){const{contentHash:t,status:n,readiness:a,updatedAt:r,...s}=e;return Ht(s)}function zN(e,t){for(const[n,a]of e.sourceRefs.entries())Vk(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 HN(e,t){const n=new Map;for(const r of e.tasks){const s=n.get(r.clusterKey)??new Set;s.add(r.split),n.set(r.clusterKey,s)}for(const[r,s]of n)s.size>1&&t.push({code:"split_cluster_contamination",severity:"error",message:`Source cluster ${r} appears in multiple splits: ${[...s].join(", ")}.`,path:"tasks"});(e.datasetArtifact?e.datasetArtifact.splitCounts.frozen_eval??0:e.tasks.filter(r=>r.split==="frozen_eval").length)===0&&t.push({code:"frozen_eval_missing",severity:"warning",message:"Add an independent test example before training.",path:"tasks"})}function UN(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(AN),a=e.environment.toolNames.filter(s=>!n.has(s));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 s of["create","reset","step","grade","cleanup"])e.environment.lifecycle.includes(s)||t.push({code:"work_lifecycle_incomplete",severity:"error",message:`Work Tasksets require the ${s} lifecycle stage.`,path:"environment.lifecycle"});const r=new Map(e.sourceRefs.map(s=>[s.id,s]));for(const[s,i]of e.tasks.entries()){const c=new Set,d=new Set;for(const[p,f]of(i.assets??[]).entries()){const S=`tasks.${s}.assets.${p}`;c.has(f.id)&&t.push({code:"work_asset_duplicate_id",severity:"error",message:`Task ${i.id} repeats asset id ${f.id}.`,path:`${S}.id`}),d.has(f.fileName)&&t.push({code:"work_asset_duplicate_name",severity:"error",message:`Task ${i.id} repeats staged file name ${f.fileName}.`,path:`${S}.fileName`}),c.add(f.id),d.add(f.fileName),i.sourceRefs.includes(f.sourceRefId)||t.push({code:"work_asset_task_source_missing",severity:"error",message:`Asset ${f.id} references source ${f.sourceRefId} outside task ${i.id}.`,path:`${S}.sourceRefId`});const b=r.get(f.sourceRefId);b?"sourceFileHashes"in b&&!b.sourceFileHashes.includes(f.sha256)&&t.push({code:"work_asset_hash_unregistered",severity:"error",message:`Asset ${f.id} hash is not registered by source ${f.sourceRefId}.`,path:`${S}.sha256`}):t.push({code:"work_asset_source_missing",severity:"error",message:`Asset ${f.id} references missing source ${f.sourceRefId}.`,path:`${S}.sourceRefId`}),b&&"kind"in b&&b.kind==="uploaded_file"&&!b.originalFileNames.includes(f.fileName)&&t.push({code:"work_asset_name_unregistered",severity:"error",message:`Asset ${f.id} file name is not registered by source ${f.sourceRefId}.`,path:`${S}.fileName`}),b&&"kind"in b&&b.kind==="uploaded_file"&&!b.mediaTypes.includes(f.mediaType)&&t.push({code:"work_asset_media_type_unregistered",severity:"error",message:`Asset ${f.id} media type is not registered by source ${f.sourceRefId}.`,path:`${S}.mediaType`}),f.split!==i.split&&t.push({code:"work_asset_split_mismatch",severity:"error",message:`Asset ${f.id} is assigned to ${f.split}, not task split ${i.split}.`,path:`${S}.split`})}const l=new Set;for(const[p,f]of(i.requiredOutputs??[]).entries()){const S=f.path.replaceAll("\\","/"),b=`tasks.${s}.requiredOutputs.${p}.path`;l.has(S)&&t.push({code:"work_output_duplicate_path",severity:"error",message:`Task ${i.id} repeats required output path ${S}.`,path:b}),l.add(S)}(i.requiredOutputs??[]).length===0&&t.push({code:"work_output_missing",severity:"error",message:`Work task ${i.id} must declare at least one required output.`,path:`tasks.${s}.requiredOutputs`})}}function qN(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 BN(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 FN(e,t){const n=new Set(e.tasks.map(r=>r.id)),a=new Set(e.sourceRefs.map(r=>r.id));for(const r of[...e.learningSignals.demonstrations,...e.learningSignals.preferences,...e.learningSignals.corrections,...e.learningSignals.feedback,...e.learningSignals.rewards,...e.learningSignals.labels])r.taskId&&!e.datasetArtifact&&!n.has(r.taskId)&&t.push({code:"learning_signal_task_missing",severity:"error",message:`Signal ${r.id} references missing task ${r.taskId}.`,path:`learningSignals.${r.kind}.${r.id}.taskId`}),r.sourceRefs.some(s=>!a.has(s))&&t.push({code:"learning_signal_source_missing",severity:"error",message:`Signal ${r.id} references a source outside the Dataset.`,path:`learningSignals.${r.kind}.${r.id}.sourceRefs`});for(const r of e.learningSignals.preferences)r.chosen.trim()===r.rejected.trim()&&t.push({code:"preference_pair_identical",severity:"error",message:`Preference ${r.id} has identical chosen and rejected responses.`,path:`learningSignals.preferences.${r.id}`});for(const r of e.learningSignals.rewards)r.executable||t.push({code:"reward_not_executable",severity:"warning",message:`Reward ${r.id} is a reviewed specification but has no executable verifier yet.`,path:`learningSignals.rewards.${r.id}.executable`})}function VN(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 Bo=o().trim().min(1).max(240),nb=o().trim().min(1),KN=o().trim().min(8).max(256),WN=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),GN=ve(o(),ke()).default({});function ab(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var Wk=lu.extend({sourceRefs:v(Bo).max(100).default([])}),Gk=k(["draft","validating","needs_review","published"]),ZN=u({enabled:j(),candidateCount:m().int().min(2).max(4),minimumSamples:m().int().min(1).max(1e4).default(100),allowTies:j(),allowRejectAll:j(),rubric:o().trim().max(5e4),criteria:v(u({id:Bo,label:o().trim().min(1).max(500),description:o().trim().max(1e4),weight:m().nonnegative().max(1e3)})).max(100)}),JN=u({mode:k(["text","structured_json","artifacts"]),jsonSchema:ve(o(),ke()).nullable(),renderer:u({module:o().trim().min(1).max(1e3).refine(ab,"Renderer modules must use a safe relative path."),exportName:WN,configRef:o().trim().min(1).max(1e3).refine(ab,"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"]})}),Va=u({schemaVersion:x("openpond.tasksetDraft.v1"),id:Bo,revision:m().int().positive(),profileId:Bo,modelScope:u({modelId:Bo,expectedModelRevision:m().int().positive(),source:H$.optional()}).strict().nullable().default(null),name:o().trim().max(500),objective:o().trim().max(2e4),purpose:Ik.default("general"),benchmark:_k.nullable().default(null),preferenceComparison:Ck.nullable().default(null),status:Gk,sourceRefs:v(Pk).max(1e5).default([]),datasetArtifact:zh.nullable().optional(),policy:qh,environment:Nk,output:JN.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Bh,metrics:Vc,review:ZN,tasks:v(Wk).max(1e6).default([]),graders:v(uu).max(1e3).default([]),graderFixtures:v(Dk).max(1e5).default([]),learningSignals:$k,publishedTasksetRef:u({id:Bo,revision:m().int().positive(),contentHash:KN}).nullable(),createdAt:nb,updatedAt:nb,metadata:GN}).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"]})}),QN=6e6,YN=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 XN(e){const t=ou.parse(e);return!YN.has(t)&&!t.startsWith("source-artifacts/")}function rb(e,t){const n=XN(e);if(t.byteLength>QN)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const r=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(r)?sb(t):{encoding:"utf8",data:r}}catch{a=sb(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:ok(t)}}function sb(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 ob=64*1024*1024,Zk=o().regex(/^[a-f0-9]{64}$/),eD=u({path:ou,contentHash:Zk,sizeBytes:m().int().nonnegative().max(ob),base64:o().max(ob)}).strict(),tD=u({schemaVersion:x("openpond.tasksetDraftWorkspace.v1"),draft:Va,files:v(eD).max(1e4)}).strict(),z8=tD.extend({contentHash:Zk}).strict(),ib=class extends Error{issues;constructor(e){super(e.map(t=>t.message).join(`
|
|
109
|
+
`)),this.name="TasksetDraftPublishError",this.issues=e}};function nD(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"});const n=new Set(e.sourceRefs.map(a=>a.id));for(const a of e.tasks)for(const r of a.sourceRefs)n.has(r)||t.push({code:"task_source_missing",message:`Task ${a.id} references missing source ${r}.`,path:`tasks.${a.id}.sourceRefs`});return t}function H8(e){const t=Va.parse(e.draft),n=e.now??new Date().toISOString(),a=nD(t);if(a.length)throw new ib(a);const r=t.modelScope?.source;if(r&&e.tasksetId&&e.tasksetId!==r.tasksetId)throw new Error("Taskset draft publication differs from its prepared identity.");const s=r?.tasksetId||e.tasksetId?.trim()||t.publishedTasksetRef?.id||t.id.replace(/-draft$/,""),i=r?.tasksetRevision??(t.publishedTasksetRef?.id===s?t.publishedTasksetRef.revision+1:1),c=t.sourceRefs.length?t.sourceRefs:[aD(t,s,n)],d=c[0].id,l=t.tasks.map(A=>lu.parse({...A,sourceRefs:A.sourceRefs.length?A.sourceRefs:[d],metadata:{exampleOrigin:"expert_authored",...A.metadata}})),p=t.capabilities.compatibleMethods.find(A=>A!=="none"&&A!=="retrieval")??null,f=rD(t),S=t.graders.filter(A=>A.rewardEligible&&A.weight>0&&A.kind!=="human"),b=p===null&&f==="verifiable_reward"&&S.length>0,I=p??(b?"grpo":null),C=Tc.parse({schemaVersion:"openpond.taskset.v1",id:s,revision:i,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:b?{...t.capabilities,compatibleMethods:["grpo"],rewardKinds:[...new Set(S.map(A=>A.kind==="model_judge"?"model_judge":"deterministic"))]}:t.capabilities,metrics:t.metrics,tasks:l,graders:t.graders,graderFixtures:t.graderFixtures,learningSignals:t.learningSignals,authoringProvenance:{schemaVersion:"openpond.taskAuthoringProvenance.v1",model:null,modelConfig:{},skillHash:Ht("openpond-taskset-draft-authoring-v1"),promptTemplateVersion:"taskset-draft-v1",buildIntent:f,buildSpecification:null,evidenceHashes:c.map(A=>A.sourceHash),tasksetSdkVersion:"draft-v1",sourceCommit:null,repairHistory:[],createdAt:n},readiness:null,contentHash:"00000000",createdAt:i===1?t.createdAt:n,updatedAt:n,metadata:{...t.metadata,...r?{modelTasksetAuthoring:r.lineage}:{},tasksetReviewPolicy:t.review,tasksetOutputContract:t.output,...e.sourcePackageHash?{sourcePackageHash:e.sourcePackageHash}:{},...I?{trainingMethod:I}:{},diagnosis:{schemaVersion:"openpond.capabilityDiagnosis.v1",summary:t.objective,stableBehavior:[t.objective],changingKnowledge:[],requiredContext:[],requiredTools:t.environment.toolNames,intervention:I==="dpo"?"preference":I==="grpo"||I==="ppo"?"grpo_rft":I==="sft"?"sft":"no_training",trainingEligible:I!==null,rationale:I?[`The author selected ${I.toUpperCase()} compatibility.`]:["The Taskset is currently configured for evaluation only."],confidence:1}}}),P=Tc.parse({...C,contentHash:LN(C)}),M=$N(P,{purpose:"publication"}).issues.filter(A=>A.severity==="error");if(M.length)throw new ib(M.map(A=>({code:A.code,message:A.message,path:A.path})));return P}function aD(e,t,n){const a=Ht({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 rD(e){return e.metadata.buildIntent==="discovery"||!e.graders.length&&!e.learningSignals.preferences.length&&!e.learningSignals.rewards.length&&!e.learningSignals.labels.length?"discovery":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 ti=o().regex(/^[a-f0-9]{64}$/),Jk=u({providerId:x("claude-code"),configurationHash:ti,executableHash:ti,version:o().regex(/^2\.\d+\.\d+$/),capabilityHash:ti,maximumRequestCostUsd:m().finite().positive().max(1e4),requestTimeoutMs:m().int().min(1e3).max(3e5),maximumTurns:m().int().min(1).max(100),holdOpen:j()}).strict();u({id:o().min(1).max(200),receiptId:o().min(1).max(200),sessionId:sS(),operationId:o().min(1).max(200),action:k(["message","seal"]),text:o().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 U8=u({provider:x("claude-code"),sessionId:sS(),requestId:o().min(1).max(200),modelId:o().min(1).max(500),runtime:Jk,sourceHash:ti,outputHash:ti,traceHash:ti,runtimeEventRefs:v(o().min(1).max(200)).min(1).max(2e4),eventCount:m().int().positive().max(2e4),startedAt:na(),completedAt:na(),cleanupComplete:x(!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."})}),mu=u({id:o().trim().min(1).max(240),revision:m().int().positive(),contentHash:o().regex(/^[a-f0-9]{64}$/),targetId:o().trim().min(1).max(240).nullable()}).strict(),sD=v(u({role:k(["system","user","assistant"]),content:o().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."})}),oD=u({schemaVersion:x("openpond.experimentAttemptGrade.v1"),selectionHash:o().regex(/^[a-f0-9]{64}$/),grades:v(Ox).min(1).max(100),score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),gradingStatus:k(["scored","pending","unscorable","not_configured"]),failureClass:G$.nullable(),contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;Ht(a)!==n&&t.addIssue({code:"custom",message:"Experiment grading integrity failed."});const r=e.grades.flatMap(s=>s.components);(r.length!==e.grades.length||new Set(r.map(s=>s.graderId)).size!==r.length)&&t.addIssue({code:"custom",message:"Each selected criterion requires exactly one distinct grader result."});for(const s of e.grades){const{contentHash:i,...c}=s;Ht(c)!==i&&t.addIssue({code:"custom",message:"A retained criterion changed."});for(const d of s.components){const{contentHash:l,...p}=d;Ht(p)!==l&&t.addIssue({code:"custom",message:"A retained grader result changed."})}}}),Xt=o().trim().min(1).max(200),Us=o().regex(/^[a-f0-9]{64}$/),Qk=st("kind",[u({kind:x("hosted_chat"),modelId:Xt,localRuntime:dt([u({providerId:x("custom-openai-compatible"),configurationHash:Us,maximumRequestCostUsd:m().finite().positive().max(1e4),requestTimeoutMs:m().int().min(1e3).max(3e5)}).strict(),Jk]).optional(),candidate:u({artifactId:Xt,contentHash:Us,preparationId:Xt,dispatchId:Xt,baseProfileId:Xt,workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),harness:Th.optional(),messages:sD.optional(),maxOutputTokens:m().int().min(1).max(1e6).default(1e5),temperature:m().min(0).max(2).default(0),topP:m().gt(0).max(1).default(1)}).strict(),u({kind:x("fixture"),fixtureId:Xt}).strict()]),iD=u({schemaVersion:x("openpond.modelStarterAttemptRequest.v1"),operationId:Xt,teamId:Xt,modelProjectId:Xt.nullable(),project:mu.optional(),taskset:Ba,taskId:Xt,environmentSeed:m().int().min(0).max(2147483647).default(0),policy:Qk}).strict();u({modelProjectId:Xt.nullable(),taskset:Ba,afterTaskId:Xt.optional(),limit:m().int().min(1).max(100).default(25)}).strict();u({modelProjectId:Xt.nullable(),taskset:Ba,available:j(),unavailableReason:o().max(1e3).nullable(),models:v(u({id:Xt,name:o().max(500),maximumOutputTokens:m().int().min(1).max(1e6).optional()}).strict()).max(200),tasks:v(u({id:Xt,split:Wa,inputPreview:o().max(500),fixtures:v(u({id:Xt,label:o().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:Xt.nullable()}).strict();var Vh=u({schemaVersion:x("openpond.modelStarterAttemptSummary.v1"),id:Xt,revision:m().int().positive(),request:iD,status:k(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:u({modelId:Xt,provider:Xt,upstreamModelId:o().min(1).max(500),configurationHash:Us}).strict().nullable(),createdAt:na(),startedAt:na().nullable(),completedAt:na().nullable(),cleanupComplete:j(),resultAvailable:j(),score:m().min(0).max(1).nullable(),gradingStatus:k(["not_started","pending","scored","unscorable","not_configured"]).default("not_started"),passed:j().nullable(),outputPreview:o().max(500).nullable(),error:u({code:Xt,message:o().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."})});u({modelProjectId:Xt,afterId:Xt.optional(),limit:m().int().min(1).max(100).default(25)}).strict();u({items:v(Vh).max(100),nextCursor:Xt.nullable()}).strict();u({schemaVersion:x("openpond.modelStarterAttemptResult.v1"),attempt:Vh,output:o().max(1048576).nullable(),messages:v(ve(o(),ke())).max(4002),composition:Ic.nullable(),grade:Ox.nullable().optional(),experimentGrade:oD.nullable().optional(),environment:u({status:k(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:j(),definition:Ba,initialStateHash:Us.nullable(),finalStateHash:Us.nullable(),attemptHash:Us}).strict(),native:Dx.optional(),providerRequestIds:v(Xt).max(1001),contentHash:Us}).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||Ht(n)!==Ht(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!==Ht(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 Eo=o().trim().min(1).max(240),Xm=o().regex(/^[a-f0-9]{64}$/),Yk=u({kind:x("hosted_harness"),modelId:Eo,candidate:u({artifactId:Eo,contentHash:Xm,preparationId:Eo,dispatchId:Eo,baseProfileId:Eo,workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),sourceCandidate:Id.shape.sourceCandidate,reasoningEffort:k(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:Eo,source:Id,modelConfigurationHash:Xm,packageHash:Xm,externalDatasetBinding:us.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."})}),qa=o().trim().min(1).max(200),Xk=o().regex(/^[a-f0-9]{64}$/),cD=st("kind",[Qk.options[0],u({kind:x("fixture")}).strict(),Yk]),pu=u({schemaVersion:x("openpond.modelTasksetRunRequest.v1"),operationId:qa,teamId:qa,modelProjectId:qa.nullable(),name:o().trim().min(1).max(200).optional(),project:mu.optional(),taskset:Ba,policy:cD,population:v(Sk).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=>$h([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."})}),ew=u({schemaVersion:x("openpond.modelTasksetRunSummary.v1"),id:qa,revision:m().int().positive(),teamId:qa,modelProjectId:qa.nullable(),name:o().trim().min(1).max(200).optional(),project:mu.optional(),operationId:qa,taskset:Ba,policyKind:k(["hosted_chat","fixture","hosted_harness"]),manifestHash:Xk,status:k(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:m().int().min(1).max(1e4),counts:u({pending:m().int().nonnegative(),running:m().int().nonnegative(),completed:m().int().nonnegative(),failed:m().int().nonnegative(),cancelled:m().int().nonnegative()}).strict(),createdAt:na(),startedAt:na().nullable(),completedAt:na().nullable(),cleanupComplete:j(),resultAvailable:j(),score:m().min(0).max(1).nullable(),metricName:o().min(1).max(240),error:u({code:qa,message:o().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."})}),lD=u({summary:ew,request:pu,manifest:xk,policySnapshot:Vh.shape.policySnapshot}).strict();u({modelProjectId:qa.optional(),projectId:mu.shape.id.optional(),afterId:qa.optional(),limit:m().int().min(1).max(100).default(25)}).strict();u({items:v(ew).max(100),nextCursor:qa.nullable()}).strict();u({schemaVersion:x("openpond.modelTasksetRunResult.v1"),run:lD,receipts:v(C2).min(1).max(1e4),metric:hx.nullable(),contentHash:Xk}).strict();var tw=o().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),dD=v(tw).min(1).max(20),cb=k(["input","output","expectedOutput","evaluatorContext"]),uD=u({destination:cb,path:dD,source:cb,sourcePath:v(tw).max(20)}).strict(),Kh=v(uD).max(100).superRefine((e,t)=>{for(const[n,a]of e.entries())e.slice(0,n).some(r=>r.destination===a.destination&&(lb(r.path,a.path)||lb(a.path,r.path)))&&t.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function lb(e,t){return e.length<=t.length&&e.every((n,a)=>n===t[a])}var Wn=o().trim().min(1).max(200),Zs=o().regex(/^[a-f0-9]{64}$/),Wh=u({id:Wn,revision:m().int().positive(),contentHash:Zs}).strict(),fu=u({id:Wn,version:o().min(1).max(200),contentHash:Zs,name:o().trim().min(1).max(500).optional(),feedbackKey:Wc,release:Wh.nullable(),mappings:Kh.optional()}).strict(),mD=u({id:Wn,version:o().min(1).max(200),contentHash:Zs,mappings:Kh}).strict(),q8=u({operationId:Wn,id:Wn.optional(),expectedRevision:m().int().nonnegative(),request:pu,maximumCostUsd:m().finite().positive().max(1e4),graders:v(mD).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."})}),pD=u({schemaVersion:x("openpond.experimentDefinition.v1"),id:Wn,teamId:Wn,revision:m().int().positive(),request:pu,maximumCostUsd:m().finite().positive().max(1e4),graders:v(fu).min(1).max(100),createdAt:na(),updatedAt:na()}).strict();pD.extend({contentHash:Zs});u({operationId:Wn,definition:Wh}).strict();u({projectId:Wn.optional(),datasetHash:Zs.optional(),search:o().trim().max(200).optional(),status:k(["queued","running","cancelling","completed","failed","cancelled"]).optional(),afterId:Wn.optional(),limit:m().int().min(1).max(100).default(30)}).strict();u({definition:Wh.nullable(),configurationHash:Zs.optional(),admissionRequestHash:Zs.optional(),sourceExperimentId:Wn.optional(),maximumCostUsd:m().finite().positive().max(1e4),graders:v(fu).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."})});u({operationId:Wn,profileRepositoryId:Wn,definitionId:Wn,modelId:Wn,reasoningEffort:k(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:m().finite().positive().max(1e4),externalDatasetBinding:us.optional(),sourceCandidate:Yk.shape.sourceCandidate}).strict();u({request:pu,manifest:xk,maximumCostUsd:m().finite().positive().max(1e4),graders:v(fu).min(1).max(100)}).strict();var yr=Va.shape.id,Ka=m().int().positive(),Js=o().regex(/^[a-f0-9]{64}$/),eo={teamId:yr,modelId:yr};u({schemaVersion:x("openpond.tasksetDraftCreate.v1"),operationId:yr,modelId:yr,expectedModelRevision:Ka,name:Va.shape.name}).strict();u({schemaVersion:x("openpond.tasksetDraftSourceDescriptor.v1"),...eo,expectedModelRevision:Ka,sourcePackageHash:Js}).strict();u({schemaVersion:x("openpond.tasksetDraftReadback.v1"),...eo,draft:Va,workspaceHash:Js,projectEtag:Js}).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 fD=u({id:yr,revision:Ka,name:Va.shape.name,status:Gk,updatedAt:Va.shape.updatedAt,sourceTasksetRef:Ye.nullable()}).strict();u({schemaVersion:x("openpond.tasksetDraftList.v1"),...eo,drafts:v(fD).max(100),nextCursor:o().min(1).max(2e3).nullable()}).strict();u({expectedDraftRevision:Ka,draft:Va}).strict();u({expectedDraftRevision:Ka,expectedModelRevision:Ka}).strict();var hD=u({expectedDraftRevision:Ka,expectedWorkspaceHash:Js}).strict();u({schemaVersion:x("openpond.tasksetDraftValidation.v1"),...eo,draftId:yr,draftRevision:Ka,workspaceHash:Js,valid:j(),issues:v(u({code:o().min(1),severity:k(["warning","error"]),message:o(),path:o().nullable()}).strict()),packageHash:Js.nullable(),tasksetRef:Ye.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.");hD.extend({operationId:yr,expectedPackageHash:Js,expectedTasksetRef:Ye}).strict();u({schemaVersion:x("openpond.tasksetDraftFileList.v1"),...eo,draftId:yr,draftRevision:Ka,files:v(nk).max(10020)}).strict();u({schemaVersion:x("openpond.tasksetDraftFileReadback.v1"),...eo,draftId:yr,draftRevision:Ka,file:U$}).strict();u({schemaVersion:x("openpond.tasksetDraftDeletion.v1"),...eo,draftId:yr,revision:Ka,deleted:x(!0)}).strict();Va.shape.id;m().int().positive();var zr=o().trim().min(1).max(500),gD=u({projectId:zr.optional(),tasksetId:zr.optional(),draftId:zr.optional(),taskId:zr.optional(),query:o().trim().max(1e3).default(""),split:k(["train","validation","test","frozen_eval"]).optional(),after:o().min(1).max(2e3).optional(),limit:m().int().min(1).max(100).default(30)}).strict(),vD=u({id:zr,method:k(["code","judge","human"]),required:j()}),nw=u({tasksetId:zr,tasksetName:o(),tasksetRevision:m().int().positive(),tasksetHash:o(),taskId:zr,ordinal:m().int().nonnegative(),title:o(),description:o(),split:o(),scoring:v(vD),configuration:k(["configured","needs_reward","needs_checks"]),draftId:zr.nullable().default(null),modelId:zr.nullable().default(null)}),bD=u({items:v(nw).max(100),nextCursor:o().nullable()});function B8(e,t){if(D$({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((s,i)=>({file:s,path:`${n}/${String(i).padStart(4,"0")}.txt`})),r={schemaVersion:"openpond.taskIntakeSources.v1",format:e.format,previewHash:e.contentHash,files:a.map(({file:s,path:i})=>({originalPath:s.path,retainedPath:i}))};return[...a.map(({file:s,path:i})=>rb(i,new TextEncoder().encode(s.text))),rb(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(r)))]}function F8(e,t,n){const a=Jx.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const r=[...e.tasks];for(const i of n){const c=a.records.find(p=>p.id===i);if(!c||c.kind!=="task"||c.needsContext)throw new Error("Recorded attempts and incomplete histories must be imported into Labeling for review.");const d=Wk.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}}}),l=r.find(p=>p.id===d.id);if(l&&Ht(l)!==Ht(d))throw new Error(`Task ${d.id} already exists with different content. Import will not replace saved edits.`);l||r.push(d)}const s=new Map;for(const i of r)for(const c of[`family:${i.clusterKey}`,`input:${Ht(i.input)}`]){if(s.has(c)&&s.get(c)!==i.split)throw new Error("The imported task family or request already occurs in another split.");s.set(c,i.split)}return Va.parse({...e,tasks:r})}const ta=o().trim().min(1).max(240),rs=o().trim().min(1),aw=ve(o(),ke()).default({}),rw=k(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),sw=k(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),yD=u({id:ta,kind:k(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:v(ta).min(1).max(1e4),occurredAt:rs,signature:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(5e3),confidence:m().min(0).max(1),consented:j(),metadata:aw}),SD=u({frequency:m().min(0).max(1),businessValue:m().min(0).max(1),frontierCost:m().min(0).max(1),signalQuality:m().min(0).max(1),verifiability:m().min(0).max(1),repeatability:m().min(0).max(1),privacyRisk:m().min(0).max(1),overall:m().min(0).max(1)}),xD=u({tactic:sw,eligible:j(),reasons:v(o().trim().min(1).max(5e3)).min(1).max(100),blockers:v(o().trim().min(1).max(5e3)).max(100).default([]),requiredSignals:v(o().trim().min(1).max(500)).max(100).default([]),generatedBy:k(["decision_table","baseline_reassessment"])}),ow=u({schemaVersion:x("openpond.taskCandidate.v1"),id:ta,profileId:ta,status:rw,fingerprint:o().trim().min(1).max(512),title:o().trim().min(1).max(500),summary:o().trim().min(1).max(1e4),workflowSignature:o().trim().min(1).max(2e3),evidence:v(yD).min(1).max(1e5),scorecard:SD,recommendation:xD,mergedIntoId:ta.nullable(),createdAt:rs,updatedAt:rs,metadata:aw}),hu=u({schemaVersion:x("openpond.taskMinerConfig.v1"),enabled:j().default(!1),localOnly:j().default(!0),observationWindowDays:m().int().min(1).max(365).default(30),minimumRecurrence:m().int().min(2).max(100).default(3),clustering:x("hybrid_deterministic_first").default("hybrid_deterministic_first"),consentRequired:j().default(!0)});u({items:v(ow),generatedAt:rs,config:hu});u({status:rw.optional(),mergeIntoId:ta.nullable().optional()});u({profileId:ta,sourceIds:v(ta).max(1e5).default([]),sessionIds:v(ta).max(1e5).default([]),config:hu.optional()});const kD=u({schemaVersion:x("openpond.taskMinerRun.v1"),id:ta,profileId:ta,status:k(["queued","running","cancelling","cancelled","succeeded","failed"]),config:hu,sourceIds:v(ta).max(1e5),sessionIds:v(ta).max(1e5).default([]),progress:u({stage:k(["queued","ingesting","preparing","clustering","persisting","complete"]),processedSources:m().int().nonnegative(),totalSources:m().int().nonnegative(),candidatesFound:m().int().nonnegative(),skippedSources:m().int().nonnegative().default(0)}),candidateIds:v(ta).max(1e5),cancelRequested:j(),error:o().trim().min(1).max(2e4).nullable(),createdAt:rs,startedAt:rs.nullable(),completedAt:rs.nullable(),updatedAt:rs});var wD=u({id:Cn,purpose:o().trim().min(1).max(500),audience:k(["orchestrator","environment","privileged_scorer","trainer","infrastructure"]),required:j(),ttlSeconds:m().int().positive().max(86400),scopes:v(o().trim().min(1).max(500)).max(100).default([])}).strict(),ID=u({declarationId:Cn,leaseRef:o().trim().min(8).max(1e3),audience:wD.shape.audience,expiresAt:Qp}).strict(),_D=u({adapterId:Cn,placement:k(["local","remote","colocated","provider_native"]),capabilityReceipt:hn,runtimeVersion:o().trim().min(1).max(200),dataPlane:u({provider:Cn,dataPlaneId:Cn,cellId:Cn,runnerPoolId:Cn,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:hn}).strict().nullable()}).strict(),CD=u({adapterId:Cn,kind:k(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:hn,provider:Cn.nullable()}).strict(),RD=u({adapterId:Cn,workerVersion:o().trim().min(1).max(200),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:o().trim().min(1).max(500),capabilityReceipt:hn}).strict(),PD=u({schemaVersion:x("openpond.harnessRunManifest.v1"),id:Cn,harnessRelease:bt,datasetRelease:bt,evidenceSets:v(bt).max(1e4),model:u({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:hn.nullable(),tokenizerRevision:o().trim().min(1).max(500),chatTemplateHash:hn}).strict(),recipe:u({method:o().trim().min(1).max(100),version:o().trim().min(1).max(200),configHash:hn}).strict(),runtimeTarget:_D,computeTarget:CD,engine:RD,resolvedBundleHash:hn,secretLeaseRefs:v(ID).max(1e3),approval:u({approvalHash:hn,approvedAt:Qp,maximumSpendUsd:m().nonnegative().nullable()}).strict(),createdAt:Qp}).strict();PD.extend({contentHash:hn}).strict();var TD=u({schemaVersion:x("openpond.resolvedTrainingBundle.v1"),projection:x("trainer"),harnessRelease:bt,datasetRelease:bt,evidenceSetRelease:bt.nullable(),files:v(u({path:o().trim().min(1).max(2e3),sha256:hn,sizeBytes:m().int().nonnegative()}).strict()).max(1e5)}).strict();TD.extend({contentHash:hn}).strict();var iw=u({name:x("adamw").default("adamw"),weightDecay:m().nonnegative().max(1).default(0),beta1:m().positive().lt(1).default(.9),beta2:m().positive().lt(1).default(.999),epsilon:m().positive().max(.01).default(1e-8)}).strict().default({name:"adamw",weightDecay:0,beta1:.9,beta2:.999,epsilon:1e-8});const nt=o().trim().min(1).max(240),ra=o().trim().min(1),ui=o().trim().min(8).max(256),Gh=ve(o(),ke()).default({}),hr=nt.nullable(),AD=k(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),ED=k(["defaults","customize"]),jD=k(["automated","manual"]);u({schemaVersion:x("openpond.trainingSourceEstimate.v1"),sessionId:nt,messageCount:m().int().nonnegative(),estimatedTokens:m().int().nonnegative(),textBytes:m().int().nonnegative()});u({query:o().max(500).default(""),offset:m().int().nonnegative().default(0),limit:m().int().min(1).max(100).default(20),candidates:v(u({sessionId:nt,title:o().trim().min(1).max(500),updatedAt:ra})).max(500).default([])});const MD=u({sessionId:nt,title:o().trim().min(1).max(500),updatedAt:ra,snippet:o().max(2e3).nullable()});u({schemaVersion:x("openpond.trainingChatSearchResult.v1"),query:o(),offset:m().int().nonnegative(),limit:m().int().positive(),total:m().int().nonnegative(),hasMore:j(),indexedChats:m().int().nonnegative(),totalChats:m().int().nonnegative(),indexing:j(),entries:v(MD)});const Zh=k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),OD=u({graderId:nt.nullable(),path:o().trim().min(1).max(1e3),language:k(["javascript","typescript","python","json","text"]),content:o().max(2e6),sha256:ui,declaredSha256:ui.nullable(),integrity:k(["verified","unverified","mismatch"])}),$D=u({protocolVersion:o().trim().min(1).max(200),module:o().trim().min(1).max(1e3),moduleSha256:ui,command:v(o().max(2e3)).max(100),cwd:o().trim().min(1).max(4e3),maxTurns:m().int().positive().max(100)});u({schemaVersion:x("openpond.tasksetGraderDetails.v1"),taskset:Kt,sourceTasksetId:nt,graders:v(uu).max(1e3),runtime:$D.nullable(),sources:v(OD).max(1e3),unavailableReason:o().max(2e3).nullable()});const ND=u({id:nt,taskIndex:m().int().nonnegative(),label:Fh,output:ve(o(),ke()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:j(),expectedRewardEligible:j(),metadata:Gh}),DD=u({schemaVersion:x("openpond.taskAttempt.v1"),id:nt,tasksetId:nt,taskId:nt,split:di,attempt:m().int().nonnegative(),seed:m().int(),modelRef:ln.nullable(),startedAt:ra,completedAt:ra,output:ve(o(),ke()),runtimeEventRefs:v(nt).max(1e4).default([]),artifactRefs:v(nt).max(1e4).default([]),privilegedOutcomeRef:hr,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:m().nonnegative().nullable(),latencyMs:m().int().nonnegative(),userInterventions:m().int().nonnegative().default(0),metadata:Gh}),LD=u({schemaVersion:x("openpond.taskAttemptArtifact.v1"),id:nt,tasksetId:nt,taskId:nt,attemptId:nt,kind:k(["raw_model_response","runtime_trace","environment_state","grader_evidence","output_artifact"]),path:o().trim().min(1).max(4e3),mediaType:o().trim().min(1).max(200).nullable().optional(),sha256:ui,sizeBytes:m().int().nonnegative(),createdAt:ra,metadata:Gh}),zD=u({graderId:nt,graderVersion:o().trim().min(1).max(100),score:m().min(0).max(1).nullable(),passed:j(),hardGate:j(),rewardEligible:j(),feedback:o().trim().max(2e4).nullable(),evidenceRefs:v(nt).max(1e4).default([]),judge:ln.nullable().optional().default(null),calibrationStatus:k(["not_applicable","pending","passed","failed"])}),HD=u({schemaVersion:x("openpond.gradeResult.v1"),id:nt,attemptId:nt,graderSetHash:ui,score:m().min(0).max(1).nullable(),passed:j(),components:v(zD).min(1).max(1e3),failureClass:Zh.nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:j(),rewardComposition:Ic.optional(),createdAt:ra});k(["stable_hash_top_n","rft_easy_curriculum_v1"]);const UD=u({schemaVersion:x("openpond.graderAuditReport.v1"),id:nt,tasksetId:nt,tasksetHash:ui,fixtureRefs:v(nt).min(1).max(1e5),gradeRefs:v(nt).min(1).max(1e5),passed:j(),hackingChecksPassed:j(),leakageChecksPassed:j(),infrastructureSafetyPassed:j(),failures:v(u({fixtureId:nt,label:Fh,gradeId:nt,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:ra}),qD=u({schemaVersion:x("openpond.capabilityDiagnosis.v1"),summary:o().trim().min(1).max(1e4),stableBehavior:v(o().trim().min(1).max(5e3)).max(100).default([]),changingKnowledge:v(o().trim().min(1).max(5e3)).max(100).default([]),requiredContext:v(o().trim().min(1).max(5e3)).max(100).default([]),requiredTools:v(nt).max(100).default([]),intervention:sw,trainingEligible:j(),rationale:v(o().trim().min(1).max(5e3)).min(1).max(100),confidence:m().min(0).max(1)}),BD=u({id:nt,sourceId:nt,sourceTurnId:hr,split:di,origin:k(["extracted","corrected","synthetic","expert_authored"]),inputPrompt:o().trim().min(1).max(1e5),expectedOutputText:o().trim().min(1).max(2e5).nullable(),rationale:o().trim().min(1).max(5e3)}),FD=u({schemaVersion:x("openpond.taskDesignProposal.v1"),id:nt,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:qD.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:Bh.shape.taskKind,sourceIds:v(nt).min(1).max(1e5),assumptions:v(o().trim().min(1).max(5e3)).max(1e3),successCriteria:v(o().trim().min(1).max(5e3)).min(1).max(1e3),proposedGraders:v(uu).max(1e3).default([]),graderFixtures:v(ND).max(1e5).default([]),generatedFiles:v(jN).max(1e3).default([]),proposedExamples:v(BD).max(1e5).default([]),proposedMethod:Bk.shape.recommendedMethod,trainingPath:Uk.nullable().default(null),policy:qh,warnings:v(o().trim().min(1).max(5e3)).default([]),createdAt:ra}),VD=5;function V8(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,VD).join(" ")}const Jc=u({schemaVersion:x("openpond.baseModelPreference.v1"),modelId:nt,revision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:o().trim().min(8).max(256).nullable(),modelAssetId:hr,source:k(["managed","local","builtin"])}),KD=u({schemaVersion:x("openpond.taskCreationRequest.v1"),id:nt,profileId:nt,surface:AD,mode:ED,entryMode:jD.default("manual"),resourceIntent:k(["workproduct","dataset"]).default("workproduct"),buildIntent:zk.default("demonstrations"),buildSpecification:Hk.nullable().default(null),objective:o().trim().min(1).max(2e4).nullable(),methodHint:k(["sft","dpo","grpo","ppo"]).nullable().default(null),preferredBaseModelId:nt.nullable().default(null),preferredBaseModel:Jc.nullable().default(null),sourceIds:v(nt).max(1e5),candidateId:hr,analysisModel:ln.nullable(),analysisReasoningEffort:Yd.nullable().default(null),createImproveRunId:hr.default(null),targetIntent:u({kind:k(["agent","skill","extension","model","configuration"]).nullable(),id:hr,displayName:o().trim().min(1).max(500).nullable(),operation:k(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:u({status:k(["not_required","pending","approved","declined"]),content:x("raw_excerpts"),sourceIds:v(nt).max(1e5),providerModel:ln.nullable(),approvalId:hr,approvedAt:ra.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:ra}),cw=u({schemaVersion:x("openpond.taskCreationSnapshot.v1"),id:nt,request:KD,state:k(["planning","awaiting_disclosure_approval","awaiting_questions","recommendation_ready","awaiting_materialization_approval","materializing","validating","ready","blocked","failed","cancelled"]),proposal:FD.nullable(),materializedTasksetId:hr,disclosureApprovalId:hr,materializationApprovalId:hr,blockingQuestions:v(u({id:nt,kind:k(["objective","consent","success_signal","privacy_licensing","interpretation"]),prompt:o().trim().min(1).max(5e3),answer:o().trim().min(1).max(2e4).nullable()})).default([]),transcript:v(u({id:nt,role:k(["user","assistant","system","tool"]),text:o().max(1e5),createdAt:ra})).max(1e4).default([]),repairHistory:v(Fk).max(1e3).default([]),blockedReason:o().trim().min(1).max(1e4).nullable(),createdAt:ra,updatedAt:ra});u({schemaVersion:x("openpond.taskCreationTranscript.v1"),creationId:nt,profileId:nt,messages:cw.shape.transcript,updatedAt:ra});u({sessionId:o().min(1).max(200),creationHash:o().regex(/^[a-f0-9]{64}$/),sessionRevision:o().regex(/^[a-f0-9]{64}$/),executionRevision:o().regex(/^[a-f0-9]{64}$/)}).strict();const it=o().trim().min(1).max(200),Vr=o().regex(/^[a-f0-9]{64}$/),gu=u({installationId:o().uuid(),profileId:it,ownerUserId:it,teamId:it,bindingId:it,bindingRevision:m().int().positive()}).strict();u({version:x(1),scope:gu,epoch:o().uuid().nullable(),runtimeId:o().uuid(),audience:o().url(),nonce:o().uuid(),issuedAt:o().datetime(),payloadHash:Vr,signature:o().regex(/^[A-Za-z0-9+/]{86}==$/)}).strict();const Jh=u({id:it,kind:k(["session","starter"]),title:o().trim().min(1).max(300),providerId:it,modelId:o().trim().min(1).max(300).nullable(),experience:k(["chat","work"]),workspaceId:it,workspaceLabel:o().trim().min(1).max(300),profileSelectionId:it.nullable(),revision:Vr,available:j(),unavailableReason:o().max(500).nullable(),canMessage:j(),canSteer:j(),canStop:j(),activeTurnId:it.nullable()}).strict(),lw=2e4;u({revision:Vr,capturedAt:o().datetime(),targets:v(Jh).max(lw)}).strict();const td=100,dw=u({revision:Vr,capturedAt:o().datetime(),targetCount:m().int().min(0).max(lw),pageCount:m().int().min(0).max(200)}).strict().refine(e=>e.pageCount===Math.ceil(e.targetCount/td),{message:"ponder_desktop_catalog_page_count_invalid"});u({catalog:dw,index:m().int().min(0).max(199),targets:Jh.array().min(1).max(td)}).strict().refine(e=>e.index<e.catalog.pageCount&&e.targets.length===Math.min(td,e.catalog.targetCount-e.index*td),{message:"ponder_desktop_catalog_page_size_invalid"});const K8=u({revision:Vr,pageIndex:m().int().min(0).max(199)}).strict();u({scope:gu,publicKey:o().min(1).max(512),runtimeId:o().uuid(),epoch:o().uuid(),authorizationRevision:m().int().positive(),reauthorizationGeneration:m().int().nonnegative().default(0),state:k(["attached","revoked"]),leaseExpiresAt:o().datetime(),catalog:dw.nullable()}).strict();const jo={targetId:it,targetRevision:Vr},ep=o().trim().min(1).max(32e3),WD=st("action",[u({...jo,action:x("create"),prompt:ep,title:o().trim().min(1).max(300)}).strict(),u({...jo,action:x("message"),prompt:ep}).strict(),u({...jo,action:x("steer"),prompt:ep,expectedTurnId:it}).strict(),u({...jo,action:x("stop"),expectedTurnId:it}).strict(),u({...jo,action:x("observe"),expectedTurnId:it}).strict(),u({...jo,action:x("inspect"),expectedTurnId:it}).strict()]),GD=u({scope:gu,epoch:o().uuid(),originChatTurnId:it,originToolCallId:it,humanControlId:it.optional(),authorizationRevision:m().int().positive()}).strict();u({scope:gu,epoch:o().uuid(),runtimeId:o().uuid(),authorizationRevision:m().int().positive()}).strict();const ZD=u({id:it,origin:GD,payloadHash:Vr,intent:WD,target:Jh,state:k(["ready","dispatching","admitted","completed","failed","cancelled","expired","attention"]),claimId:o().uuid().nullable(),claimedEpoch:o().uuid().nullable(),expiresAt:o().datetime(),admittedAt:o().datetime().nullable(),createdAt:o().datetime(),updatedAt:o().datetime(),receipt:u({sessionId:it,sessionTitle:o().min(1).max(300),inputId:it.nullable(),turnId:it.nullable(),state:it}).strict().nullable(),error:o().max(1e3).nullable()}).strict(),JD=u({operationId:it,payloadHash:Vr,sessionId:it,sessionTitle:o().min(1).max(300),inputId:it.nullable(),turnId:it,completedAt:o().datetime(),outcome:k(["completed","failed","cancelled"]),body:o().max(128e3),bodyTruncated:j(),assistantEventIds:v(it).max(2e3),providerId:it,modelId:it.nullable(),workspaceId:it,outputs:v(u({id:it,title:o().min(1).max(300),contentType:it,sizeBytes:m().int().nonnegative(),sha256:Vr}).strict()).max(100),error:o().max(2e3).nullable()}).strict(),W8=u({version:x(1),direction:k(["sent","received"]),operationId:it,installationId:o().uuid(),profileId:it,ownerUserId:it,teamId:it,sessionId:it,title:o().min(1).max(300),turnId:it.nullable(),receiptId:it,status:it,body:o(),outputs:JD.shape.outputs}).strict(),Fo=o().trim().min(1).max(240),nd=o().trim().min(1),af=o().trim().min(8).max(256),uw=ve(o(),ke()).default({}),QD=k(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),mw=u({schemaVersion:x("openpond.huggingFaceDatasetLocator.v1"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),requestedRevision:o().trim().min(1).max(256).nullable()}),YD=u({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:j(),sampleValues:v(ke()).max(5)}),XD=u({configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),rowCount:m().int().nonnegative().nullable(),sizeBytes:m().int().nonnegative().nullable()}),eL=u({schemaVersion:x("openpond.huggingFaceDatasetInspection.v1"),id:Fo,locator:mw,resolvedRevision:o().trim().min(7).max(256),title:o().trim().min(1).max(500),description:o().max(2e4).nullable(),declaredLicense:o().trim().min(1).max(500).nullable(),gated:j(),private:j(),configurations:v(o().trim().min(1).max(500)).min(1).max(1e3),splits:v(XD).min(1).max(1e4),columns:v(YD).min(1).max(1e4),previewRows:v(ve(o(),ke())).max(25),sourceFiles:v(u({path:o().trim().min(1).max(2e3),configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),revision:o().trim().min(7).max(256),sizeBytes:m().int().nonnegative().nullable(),contentHash:af.nullable()})).max(1e5),inspectedAt:nd,metadata:uw}),tL=k(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),nL=u({sourcePath:o().trim().min(1).max(1e3),target:tL,transform:k(["identity","string","json","messages","numeric","math_final_answer"]),policy:k(["visible","privileged","metadata"]),required:j()}),pw=u({schemaVersion:x("openpond.datasetImportMapping.v1"),sourceSchemaHash:af,configuration:o().trim().min(1).max(500),upstreamSplits:v(o().trim().min(1).max(500)).min(1).max(1e3),preset:k(["prompt_only","prompt_completion","messages","preference","prompt_expected_answer","prompt_privileged_solution","prompt_feedback"]),bindings:v(nL).min(1).max(1e4),nullPolicy:k(["reject","drop","preserve"]),invalidRowPolicy:k(["reject_import","drop_with_receipt"]),splitPolicy:u({seed:m().int(),assignments:ve(o(),bs),validationPercent:m().min(0).max(100),frozenEvalPercent:m().min(0).max(100)}),importerVersion:o().trim().min(1).max(200),mappingHash:af}),aL=u({phase:k(["idle","metadata","download","mapping","parquet_write","verification","publish"]),completedBytes:m().int().nonnegative(),totalBytes:m().int().nonnegative().nullable(),completedRows:m().int().nonnegative(),totalRows:m().int().nonnegative().nullable(),message:o().trim().min(1).max(2e3).nullable()}),rL=u({schemaVersion:x("openpond.datasetImportJob.v1"),id:Fo,profileId:Fo,sourceKind:k(["huggingface","uploaded_file"]),status:QD,locator:mw.nullable(),inspection:eL.nullable(),mapping:pw.nullable(),progress:aL,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),tasksetId:Fo.nullable(),tasksetRevision:m().int().positive().nullable(),artifactId:Fo.nullable(),error:o().trim().min(1).max(2e4).nullable(),cancellationRequested:j(),createdAt:nd,updatedAt:nd,completedAt:nd.nullable(),metadata:uw});u({profileId:Fo,url:o().trim().min(1).max(2e3)});u({name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),mapping:pw,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:j().default(!1)});function ht(e){let t;return new Yf({type:"object",get shape(){return t??=e()}})}var pc=o().trim().min(1).max(200),rf=u({operationId:pc,execution:bt,executionKind:x("recorded_evidence").optional(),graders:v(vs).min(1).max(100),maximumCostUsd:m().finite().min(1e-6).max(1e4),mappings:v(u({graderId:pc,fields:Kh}).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."})}),sL=u({schemaVersion:x("openpond.experimentScoringPass.v1"),id:pc,teamId:pc,revision:m().int().positive(),request:rf,graders:v(fu).min(1).max(100),status:k(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:m().int().min(1).max(1e4),counts:u({pending:m().int().nonnegative(),running:m().int().nonnegative(),scored:m().int().nonnegative(),unavailable:m().int().nonnegative(),failed:m().int().nonnegative(),cancelled:m().int().nonnegative()}).strict(),resultAvailable:j(),createdAt:na(),startedAt:na().nullable(),completedAt:na().nullable(),error:u({code:pc,message:o().max(2e3)}).strict().nullable()}).strict();sL.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)});var fw=u({sourcePass:bt,graders:rf.shape.graders,mappings:rf.shape.mappings,maximumCostUsd:m().finite().positive().max(1e4)}).strict(),hw=u({externalDatasetBinding:us,scoring:fw.optional(),modelId:o().min(1).max(300),maximumCostUsd:m().finite().positive().max(1e4)}).strict(),Qh=u({source:k(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}).strict(),Pt=o().min(1).max(240),Jn=o().regex(/^[a-f0-9]{64}$/),fc=u({schemaVersion:x("openpond.experimentImprovement.v1"),id:Pt,operationId:Pt,requestHash:Jn,actorId:Pt,teamId:Pt,projectId:Pt.nullable(),ownerWorkspaceId:Pt,ownerRevision:m().int().nonnegative(),ownerSourceRevision:o().min(1).max(500),baseRelease:bt,profileRef:Qh,baseProfileSourceRevision:o().min(1).max(500),evidence:u({manifest:os,result:is}).strict(),component:u({kind:k(["skill","workflow","agent","instruction"]),path:o().min(1).max(2e3),workflowId:Pt.optional()}).strict(),mode:k(["manual","llm_assisted"]),status:k(["draft","authoring_queued","authoring","frozen","testing","ready_for_review","adopting","accepted","rolled_back","declined","failed","cancelled"]),revision:m().int().positive(),limits:u({maximumCostUsd:m().finite().positive(),maximumAuthoringSteps:m().int().min(1).max(500),maximumDurationMs:m().int().min(1e3).max(864e5)}).strict(),authoringSteps:m().int().nonnegative().max(500),work:u({sessionId:Pt,turnId:Pt,revision:m().int().positive(),startedAt:o().datetime()}).strict().nullable(),frozen:u({release:bt,sourceRevision:o().min(1).max(500),profileSourceRevision:o().min(1).max(500),authoringHash:Jn,partitionHash:Jn,executableSourceHash:Jn,protectedClosureHash:Jn,candidateRevision:m().int().positive(),diff:v(u({path:o(),before:Jn.nullable(),after:Jn.nullable()}).strict()).max(1e4)}).strict().nullable(),test:u({recipe:hw,recipeHash:o().regex(/^[a-f0-9]{64}$/),baselineOperationId:o(),candidateOperationId:o(),cancelRequestedAt:o().datetime().nullable(),dispatching:u({kind:k(["baseline","candidate"]),token:Pt,pid:m().int().positive(),processStart:o().nullable(),startedAt:o().datetime()}).strict().nullable()}).strict().nullable(),comparison:u({baseline:u({manifest:os,result:is}).strict(),candidate:u({manifest:os,result:is}).strict(),frozenHash:Jn,humanProjection:nf.optional()}).strict().nullable(),adoptionIntent:u({operationId:Pt,expectedOwnerRevision:m().int().nonnegative(),frozenHash:Jn,humanProjection:nf.optional()}).strict().nullable(),acceptance:bt.nullable(),rollback:bt.nullable(),error:o().max(2e3).nullable(),createdAt:o().datetime(),updatedAt:o().datetime(),contentHash:Jn}).strict();function G8(e){const t=fc.parse(e),{contentHash:n,...a}=t;if(Ht(a)!==n)throw new Error("Improvement state integrity failed.");if(Xo(t.evidence),t.evidence.manifest.teamId!==t.teamId||t.evidence.result.status!=="completed"||!t.evidence.result.cases.some(r=>r.status==="completed"))throw new Error("Improvement requires usable completed owner evidence.");if(t.test&&(Ht(t.test.recipe)!==t.test.recipeHash||Jp(t.test.recipe.externalDatasetBinding).profileId!==t.profileRef.profileId))throw new Error("The test recipe changed its exact selected Profile.");if(t.comparison?.humanProjection){const r=w2(t.comparison.humanProjection);if(r.teamId!==t.teamId||r.projectId!==t.projectId||Ht(r.baseline)!==Ht(t.comparison.baseline)||Ht(r.candidate)!==Ht(t.comparison.candidate))throw new Error("Human comparison projection differs from its exact owner evidence.")}if(t.comparison&&(Xo(t.comparison.baseline),Xo(t.comparison.candidate),!t.frozen||t.comparison.frozenHash!==Ht(t.frozen)||!t$(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!==Ht(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 Z8=u({states:v(fc).max(50),nextCursor:Pt.nullable()}).strict(),oL=u({operationId:Pt,ownerWorkspaceId:Pt,expectedOwnerRevision:m().int().nonnegative(),baseRelease:bt,profileRef:Qh,profileSourceRevision:o().min(1).max(500),projectId:Pt.nullable(),evidence:bt,component:fc.shape.component,mode:fc.shape.mode,limits:fc.shape.limits}).strict(),J8=st("operation",[u({operation:x("list"),limit:m().int().min(1).max(50).default(30),cursor:Pt.optional()}).strict(),u({operation:x("options"),evidence:bt}).strict(),u({operation:x("start"),request:oL}).strict(),u({operation:k(["read","humanComparisonOptions"]),id:Pt}).strict(),u({operation:x("instructions"),id:Pt}).strict(),u({operation:x("edit"),id:Pt,revision:m().int().positive(),expectedFileHash:Jn,text:o().max(25e4)}).strict(),u({operation:x("mode"),id:Pt,revision:m().int().positive(),mode:k(["manual","llm_assisted"])}).strict(),u({operation:x("author"),id:Pt,revision:m().int().positive(),modelId:Pt,prompt:o().min(1).max(2e4)}).strict(),u({operation:k(["freeze","finishAuthoring","useCandidate","discard","cancel","rollback"]),id:Pt,revision:m().int().positive()}).strict(),u({operation:x("test"),id:Pt,revision:m().int().positive(),recipe:hw}).strict(),u({operation:x("compare"),id:Pt,revision:m().int().positive(),baseline:bt,candidate:bt,humanSelections:fk.optional()}).strict()]),gw=u({teamId:Pt,evidence:bt,scoring:fw.optional(),profiles:v(u({id:Jn,name:o(),profileRef:Qh,ownerWorkspaceId:Pt,ownerRevision:m().int().nonnegative(),baseRelease:bt,profileSourceRevision:o(),components:v(u({kind:k(["skill","instruction","agent","workflow"]),path:o(),agentId:o().optional(),workflowId:o().optional(),label:o(),binding:us}).strict()).max(500)}).strict()).max(100)}).strict(),iL=u({candidateId:Pt,actorId:Pt,teamId:Pt,projectId:Pt.nullable(),candidateRevision:m().int().positive(),recipeHash:Jn,baseline:u({manifest:os,result:is}).strict(),candidate:u({manifest:os,result:is}).strict(),contentHash:Jn}).strict();function Q8(e){const t=iL.parse(e),{contentHash:n,...a}=t;if(Ht(a)!==n)throw new Error("Accepted Human discovery integrity failed.");for(const r of[t.baseline,t.candidate])if(Xo(r),r.manifest.teamId!==t.teamId||r.manifest.lineage?.humanProjection)throw new Error("Discovery must retain original owner evidence.");return t}var Yt=o().trim().min(1).max(240),gr=o().regex(/^[a-f0-9]{64}$/),Yh=u({schemaVersion:x("openpond.advancedRefinerEvaluation.v1"),operationId:Yt,actorId:Yt,teamId:Yt,projectId:Yt.nullable(),mode:k(["review_quality","downstream_adaptation"]),profileRef:u({source:k(["local","github","openpond_git"]),repositoryId:Yt,profileId:Yt}).strict(),sourceRevision:o().min(1).max(500),baselineRelease:bt,refinerRelease:bt,evidence:bt,externalDatasetBinding:us,adaptationDatasetBinding:us,privateClosureHash:gr,adaptationTaskIds:v(Yt).min(1).max(1e4),holdoutTaskIds:v(Yt).min(1).max(1e4),adaptationSplit:k(["train","validation","test","frozen_eval"]),holdoutSplit:k(["train","validation","test","frozen_eval"]),environmentPolicy:st("kind",[u({kind:x("resettable"),environmentHash:gr}).strict(),u({kind:x("frozen_observations"),environmentHash:gr}).strict()]),maximumCostUsd:m().finite().positive().max(1e4),maximumDurationMs:m().int().min(1e3).max(864e5),maximumModelSteps:m().int().min(1).max(1e3),contentHash:gr}).strict();function Y8(e){const t=Yh.parse(e),{contentHash:n,...a}=t;if(Ht(a)!==n)throw new Error("Advanced Refiner evaluation admission changed.");const r=Jp(t.externalDatasetBinding);if(r.profileId!==t.profileRef.profileId||r.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 s=Jp(t.adaptationDatasetBinding);if(s.profileId!==r.profileId||s.packageHash!==r.packageHash||Ht(s.dataset)!==Ht(r.dataset)||Ht(s.target)!==Ht(r.target)||s.protectedProfileClosureHash!==r.protectedProfileClosureHash)throw new Error("This native advanced adapter needs separate adaptation and holdout recipes from the same exact released package and target.");if(s.split!==t.adaptationSplit||r.split!==t.holdoutSplit)throw new Error("Advanced split policies differ from their exact admitted recipes.");const i=new Set(r.population.map(d=>d.taskId)),c=new Set(s.population.map(d=>d.taskId));if(t.holdoutTaskIds.some(d=>!i.has(d))||t.adaptationTaskIds.some(d=>!c.has(d)))throw new Error("Advanced evaluation selected cases outside its exact Dataset recipe.");return t}var cL=u({pin:Yh,modelId:Yt,profileId:Yt,model:Oh,seed:m().int(),reasoningEffort:k(["none","off","low","medium","high","xhigh","max"]).nullable()}).strict(),lL=st("operation",[u({operation:x("start"),request:cL}).strict(),u({operation:k(["read","cancel","resume"]),id:Yt}).strict(),u({operation:x("list")}).strict()]),dL=u({taskId:Yt,sourceCaseHash:gr,reviewSessionId:Yt,reviewTurnId:Yt,inputHarness:bt,trigger:bt,decision:k(["no_action","route_deterministically","queue_refiner"]),outcome:bt.nullable(),proposal:bt.nullable(),validations:v(bt).max(100),grade:u({id:Yt,contentHash:gr,score:m().min(0).max(1).nullable(),passed:j(),failureClass:o().nullable()}).strict(),resetComplete:j()}).strict(),uL=u({schemaVersion:x("openpond.advancedRefinerReviewReceipt.v1"),id:Yt,runId:Yt,pinHash:gr,ownerActorId:Yt,teamId:Yt,privateClosureHash:gr,refinerRelease:bt,cases:v(dL).min(1).max(1e4),reviewScore:m().min(0).max(1).nullable(),completedCases:m().int().nonnegative(),noActionCases:m().int().nonnegative(),routedCases:m().int().nonnegative(),proposalCases:m().int().nonnegative(),costUsd:m().finite().nonnegative().nullable(),cleanupComplete:j(),createdAt:o().datetime(),contentHash:gr}).strict(),db=gw.shape.profiles.element,X8=gw.extend({profiles:v(db.extend({components:v(db.shape.components.element.extend({adaptationSplits:v(u({split:k(["train","validation","test","frozen_eval"]),taskIds:v(Yt)})),environmentHash:gr,resettable:j(),reviewQuality:j()}))})),refinerReleases:v(bt),activeRefiner:bt.nullable(),models:v(u({id:Yt,profileId:Yt,name:o(),location:k(["local","hosted"])}))}),mL=u({operation:x("prepare"),evidence:bt,profileOptionId:Yt,componentLabel:Yt,mode:k(["review_quality","downstream_adaptation"]),adaptationSplit:k(["train","validation","test","frozen_eval"]),operationId:Yt,refinerRelease:bt,maximumCostUsd:m().positive(),maximumDurationMs:m().int().positive(),maximumModelSteps:m().int().positive()}).strict();dt([lL,mL,u({operation:x("options"),evidence:bt}).strict()]);var pL=u({modelRequests:m().int().nonnegative(),knownSpendUsd:m().nonnegative(),totalSpendUsd:m().nonnegative().nullable(),heldUsd:m().nonnegative(),uncertainRequests:m().int().nonnegative()}).strict();const Yr=E.nullable(),Or=m().int().nonnegative(),fL=o().regex(/^[a-f0-9]{40}$/),hL=u({name:o().trim().min(1).max(160),startedAt:Ce,completedAt:Ce,durationMs:m().nonnegative(),clock:k(["monotonic","provider","wall"]),outcome:k(["succeeded","failed","cancelled"])}).strict(),gL=u({schemaVersion:x("openpond.correlatedTelemetryReceipt.v1"),stage:k(["training","evaluation","deployment","inference"]),correlation:u({modelRunId:Yr,modelVersionId:Yr,policyVersion:Or.nullable(),taskId:Yr,rolloutGroupId:Yr,providerResourceId:Yr,deploymentId:Yr,inferenceRequestId:Yr}).strict(),spans:v(hL).max(1e4),usage:u({promptTokens:Or.nullable(),generatedTokens:Or.nullable(),gpuSeconds:m().nonnegative().nullable(),workerActiveSeconds:m().nonnegative().nullable(),optimizerSteps:Or.nullable(),rolloutGroups:Or.nullable(),successfulTrajectories:Or.nullable(),failedTrajectories:Or.nullable(),peakGpuMemoryBytes:Or.nullable(),peakGpuUtilizationPercent:m().min(0).max(100).nullable()}).strict(),resource:u({provider:E,resourceIds:v(E).max(1e3),gpuType:o().trim().min(1).max(300).nullable(),gpuCount:Or.nullable(),baseProfileId:Yr,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:fL.nullable(),adapterContentHash:W.nullable()}).strict(),cost:u({currency:x("USD"),providerReportedUsd:m().nonnegative().nullable(),quotedHourlyUsd:m().nonnegative().nullable(),estimatedUsd:m().nonnegative().nullable(),methodologyVersion:o().trim().min(1).max(160),pricingInputs:ve(o().trim().min(1).max(160),m().finite()),unitEstimates:ve(o().trim().min(1).max(160),m().nonnegative())}).strict(),recordedAt:Ce,contentHash:W}).strict(),vn=o().trim().min(1).max(240),Ur=o().regex(/^[a-f0-9]{64}$/),ns=o().datetime({offset:!0}),_n=u({id:vn,contentHash:Ur}).strict(),vL=_n.extend({revision:m().int().positive()}).strict(),vw=u({providerId:vn,modelId:o().trim().min(1).max(300)}).strict(),vu=k(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),bL=u({taskId:vn,taskContentHash:Ur,panelRole:vu,passLabel:vn.nullable(),optimizerEligible:j(),criticalInvariantIds:v(vn).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."})}),yL=u({schemaVersion:x("openpond.continualBenchIssuePacket.v1"),id:vn,revision:m().int().positive(),contentHash:Ur,familyId:vn,familyLabel:o().trim().min(1).max(500),severity:k(["low","medium","high","critical"]),cases:v(bL).min(2).max(1e4),duplicateEvidence:_n,leakageEvidence:_n,priorExposureEvidence:_n,observedAt:ns,reviewedAt:ns,queuedAt:ns.nullable(),runAt:ns.nullable(),createdBy:vn,createdAt:ns}).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."})}),SL=u({id:vn,role:vu,passLabel:vn.nullable(),taskset:vL,familyIds:v(vn).min(1).max(1e5),taskCount:m().int().positive().max(1e6),sealedAt:ns}).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."})}),tp=st("kind",[u({kind:x("base_model"),id:vn,revision:o().trim().min(1).max(500),contentHash:Ur}).strict(),u({kind:x("model_version"),id:vn,contentHash:Ur}).strict(),u({kind:x("external_reference"),id:vn,model:vw,providerRevision:o().trim().min(1).max(500),contentHash:Ur}).strict()]),xL=u({scheduleEntryId:vn,ordinal:m().int().nonnegative(),label:vn,role:k(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),parentRule:k(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),trainableRank:m().int().positive().max(1024),correctionPanelIds:v(vn).min(1).max(1e3),optimizerGroupsPerTask:m().int().positive().max(1e3),trajectoriesPerGroup:m().int().min(4).max(1e3)}).strict(),kL=u({revision:m().int().positive(),requireAllAttemptsTerminal:x(!0),criticalCorrectionPassRate:m().min(0).max(1),siblingPassRate:m().min(0).max(1),behavioralRetentionRate:m().min(0).max(1),maximumRetainedRegressionPoints:m().min(0).max(100),blockCriticalPriorRegression:j(),authorizedClaims:v(k(["systems_complete","correction_absorbed","issue_generalized","continually_current","frontier_pareto_result"])).min(1).max(5)}).strict(),wL=u({schemaVersion:x("openpond.continualBenchmarkProtocol.v1"),id:vn,revision:m().int().positive(),contentHash:Ur,ownerId:vn,createdAt:ns,sealedAt:ns,creationReceipt:_n,predecessorSeries:u({id:vn,revision:m().int().positive(),contentHash:Ur}).strict().nullable(),scenarioPack:_n,issueFamilyLedger:_n,issuePacketRelease:_n,panels:v(SL).min(6).max(1e4),grader:_n,judge:u({release:_n,rubricRelease:_n,calibrationRelease:_n,model:vw}).strict().nullable(),policies:u({base:tp,master:tp.nullable(),externalReferences:v(tp).min(1).max(20)}).strict(),invariants:u({systemPromptHash:Ur,toolSchema:_n,application:_n,harness:_n,runtime:_n,workerImage:_n,autoRefiner:u({enabled:j(),release:_n.nullable()}).strict()}).strict(),schedule:v(xL).min(1).max(1e3),evaluation:u({seeds:v(m().int()).min(3).max(100),repetitions:m().int().min(3).max(20),powerRule:_n,pairedBootstrapSamples:m().int().min(1e3).max(1e6),confidenceLevel:x(.95)}).strict(),resources:u({maximumTrainingGpuSeconds:m().int().positive(),maximumEvaluationGpuSeconds:m().int().positive(),maximumProviderSpendUsd:m().positive(),maximumTotalSpendUsd:m().positive(),maximumConcurrentGroups:m().int().positive().max(1e3)}).strict(),currencyThresholds:kL}).strict().superRefine((e,t)=>{const n=e.panels.map(s=>s.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const s of["development","retained","frozen_final","training_eligible"])e.panels.filter(i=>i.role===s).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${s} panel.`});[...e.schedule].sort((s,i)=>s.ordinal-i.ordinal).some((s,i)=>s.ordinal!==i)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const r=new Set(n);e.schedule.some(s=>s.correctionPanelIds.some(i=>!r.has(i)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),IL=k(["draft","active","completed","archived"]),_L=k(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),bw=k(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),CL=k(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),RL=k(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),PL=k(["live_client","evaluation_attempt","replay_evidence","manual"]),TL=u({id:E,ordinal:m().int().nonnegative(),label:o().trim().min(1).max(100),role:bw,parentRule:CL,taskSource:RL,trainableRank:m().int().positive().max(1024),minimumTasks:m().int().nonnegative().max(1e5),maximumTasks:m().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:r}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==r&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${r}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),AL=u({id:E,version:m().int().positive(),requireCheckpoint:j(),requireAppliedOptimizerUpdate:j(),minimumCurrentCohortMeanImprovement:m().finite(),maximumRetainedMeanRegression:m().finite().nonnegative(),blockCriticalInvariantRegression:j(),automaticDailyAdvancement:j()}).strict(),EL=u({schemaVersion:x("openpond.modelComparisonSeries.v1"),id:E,profileId:E,modelProjectId:E,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),status:IL,revision:m().int().positive(),productionBinding:u({role:x("chat_manual"),roleTargetId:E}).strict(),baseModel:u({id:E,revision:o().trim().min(1).max(256)}).strict(),seedTaskset:Kt,eligibleTaskPool:Kt,evaluationTasksets:u({development:Kt,retained:Kt,frozenFinal:Kt}).strict(),grader:se,benchmarkProtocol:wL.nullable().default(null),automaticEvaluation:u({enabled:j()}).strict().default({enabled:!1}),residualProfile:u({profileId:E,serializedEnvelopeRank:m().int().positive().max(1024),maximumEnabledRank:m().int().positive().max(1024),topology:x("uniform_block_masked")}).strict(),schedule:v(TL).min(1).max(1e3),scheduleSealedAt:Ce.nullable(),advancementPolicy:AL,executionPolicy:u({startWhenReady:x(!1)}).strict(),acceptedSeedEntryId:E.nullable(),acceptedDailyHeadEntryId:E.nullable(),promotedBindingId:E.nullable(),createdBy:E,createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{[...e.schedule].sort((d,l)=>d.ordinal-l.ordinal).some((d,l)=>d.ordinal!==l)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(d=>d.id)).size!==e.schedule.length||new Set(e.schedule.map(d=>d.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(d=>`${d.id}:${d.revision}:${d.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const r=e.schedule.find(d=>d.role==="seed");if(!r||e.schedule.filter(d=>d.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const s=e.schedule.filter(d=>d.role==="rank_candidate");s.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(s.map(d=>d.trainableRank)).size!==s.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[r.trainableRank+e.schedule.filter(d=>d.role==="daily_residual").reduce((d,l)=>d+l.trainableRank,0),...e.schedule.filter(d=>d.role==="weekly_rollup").map(d=>r.trainableRank+d.trainableRank),...e.schedule.filter(d=>d.role==="rank_candidate").map(d=>r.trainableRank+d.trainableRank),...e.schedule.filter(d=>d.role==="full_refresh").map(d=>d.trainableRank)].some(d=>d>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),yw=u({source:PL,taskIds:v(E).min(1).max(1e5),observedFrom:Ce,observedTo:Ce,reviewedAt:Ce,reviewedBy:E,sourceTaskset:Kt}).strict(),jL=yw.extend({derivedFamilyKeys:v(E).min(1).max(1e5),familyDerivation:u({algorithm:E,sourceTasksetHash:W}).strict(),selectionHash:W}).strict(),Sw=st("kind",[u({kind:x("base_model"),id:E,revision:o().trim().min(1).max(256)}).strict(),u({kind:x("model_version"),id:E,contentHash:W}).strict()]),ML=u({id:E,branchOrdinal:m().int().nonnegative(),rank:m().int().positive().max(1024),offsetStart:m().int().nonnegative(),offsetEnd:m().int().positive(),optimizationRole:k(["frozen","trainable"]),artifactLineageId:E.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."})}),OL=u({disposition:k(["advance","hold","no_signal"]),policy:u({id:E,version:m().int().positive()}).strict(),reasonCodes:v(E).min(1).max(100),summary:o().trim().min(1).max(5e3),decidedBy:E,decidedAt:Ce}).strict(),$L=u({evaluationRunId:E,modelVersionId:E,taskset:Kt,grader:se,cohortRole:k(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:E.nullable().default(null),protocol:u({id:E,revision:m().int().positive(),contentHash:W}).strict().nullable().default(null)}).strict(),NL=u({attemptOrdinal:m().int().positive(),trainingPlanId:E.nullable(),modelRunId:E.nullable(),terminalStatus:k(["failed","cancelled"]),queuedAt:Ce.nullable(),startedAt:Ce.nullable(),completedAt:Ce}).strict(),mi=u({seriesId:E,entryId:E,scheduleEntryId:E,ordinal:m().int().nonnegative(),releaseHash:W}).strict(),DL=u({schemaVersion:x("openpond.modelComparisonSeriesEntry.v1"),id:E,seriesId:E,profileId:E,modelProjectId:E,scheduleEntryId:E,releaseHash:W,ordinal:m().int().nonnegative(),label:o().trim().min(1).max(100),role:bw,branch:k(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:_L,parent:Sw,taskset:Kt,sourceTasksets:v(Kt).min(1).max(1e3),taskSelection:jL.nullable(),trainableRank:m().int().positive().max(1024),serializedEnvelopeRank:m().int().positive().max(1024),enabledCumulativeRank:m().int().positive().max(1024),trainableBlockId:E,residualBlocks:v(ML).min(1).max(1024),attemptOrdinal:m().int().positive().default(1),priorRunAttempts:v(NL).max(100).default([]),trainingPlanId:E.nullable(),modelRunId:E.nullable(),modelVersionId:E.nullable(),evaluations:v($L).max(1e5),decision:OL.nullable(),promotionBindingId:E.nullable(),queuedAt:Ce.nullable(),startedAt:Ce.nullable(),completedAt:Ce.nullable(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{const n=[...e.residualBlocks].sort((i,c)=>i.offsetStart-c.offsetStart);n.some((i,c)=>i.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 r=e.residualBlocks.filter(i=>i.optimizationRole==="trainable");(r.length!==1||r[0]?.id!==e.trainableBlockId||r[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const s=e.priorRunAttempts.map(i=>i.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||s.some((i,c)=>i!==c+1))&&t.addIssue({code:"custom",path:["priorRunAttempts"],message:"Prior Run attempts must be a contiguous history before the active attempt."})});u({seriesId:E,scheduleEntryId:E,taskSelection:yw.nullable(),expectedSeriesRevision:m().int().positive()}).strict();const LL=k(["base_reference","lora_adapter"]),xw=u({baseModel:u({source:x("huggingface"),repoId:E,revision:o().regex(/^[a-f0-9]{40}$/),configHash:W,tokenizerHash:W,licenseId:E,gated:j()}).strict(),processor:u({repository:E,revision:o().regex(/^[a-f0-9]{40}$/),configHash:W}).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."})}),zL=u({schemaVersion:x("openpond.modelVersion.v1"),id:E,modelId:E,profileId:E,version:m().int().nonnegative(),kind:LL,status:k(["available","failed"]),baseModel:Jc,taskset:Kt,comparisonSeriesEntry:mi.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),releaseGraph:u({resolvedBundleHash:W,profileRelease:Kt,harnessRelease:se,agentRelease:se.nullable(),grader:u({id:E,contentHash:W}).strict()}).strict(),artifactLineageId:E.nullable(),adapterStatus:k(["not_trained","trained"]),createdAt:Ce,contentHash:W}).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."})}),HL=u({schemaVersion:x("openpond.rewardModelVersion.v1"),id:E,modelId:E,profileId:E,version:m().int().positive(),role:x("reward"),status:k(["available","failed"]),scope:k(["synthetic_smoke","human_preference"]),baseModel:Jc,runtime:xw.nullable().default(null),taskset:Kt,preferenceDatasetRelease:se,releaseGraph:u({resolvedBundleHash:W,profileRelease:Kt,harnessRelease:se,grader:u({id:E,contentHash:W}).strict()}).strict(),artifacts:u({checkpoint:se.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:v(u({path:o().trim().min(1).max(512),sizeBytes:m().int().positive(),sha256:W}).strict()).min(4).max(128)}).strict(),adapter:se,scalarHead:se,bucketHead:se.nullable(),processorRelease:se}).strict(),qualificationReport:se.nullable(),createdAt:Ce,contentHash:W}).strict(),UL=u({schemaVersion:x("openpond.rewardModelRunReceipt.v1"),provider:E,providerRunId:E,resolvedBundleHash:W,finalCheckpoint:se.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:se,scalarHead:se,bucketHead:se.nullable(),processorRelease:se,optimizerEvidence:se,managedExecutionReceipt:se.nullable().default(null),parameterDeltaHash:W,cleanup:u({computeReleased:j(),providerTerminalObserved:j()}).strict(),contentHash:W}).strict(),qL=oE(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}}},u({schemaVersion:x("openpond.rewardModelRun.v1"),id:E,rewardModelId:E,rewardModelVersionId:E.nullable(),profileId:E,role:x("reward"),scope:k(["synthetic_smoke","human_preference"]),status:k(["prepared","running","succeeded","failed","cancelled"]),taskset:Kt,tasksetRelease:se,preferenceDatasetRelease:se,recipeRelease:se,destinationId:E,quote:u({maximumSpendUsd:m().positive(),hourlyCostUsd:m().nonnegative().nullable()}).strict(),managedRunId:E.nullable(),progress:u({completedSteps:m().int().nonnegative(),totalSteps:m().int().positive(),latestLoss:m().finite().nullable()}).strict(),receipt:UL.nullable(),qualificationReport:se.nullable(),accruedSpendUsd:m().nonnegative().nullable(),failureOwner:k(["authoring","admission","provider","runner","artifact","qualification","cleanup"]).nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:Ce,completedAt:Ce.nullable(),updatedAt:Ce}).strict()).superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Reward Model Run requires a canonical receipt."}),e.status!=="succeeded"&&e.rewardModelVersionId!==null&&t.addIssue({code:"custom",message:"Only a successful Reward Model Run can publish a Reward Model Version."})}),BL=u({schemaVersion:x("openpond.modelRunReceipt.v1"),provider:E,providerRunId:E,assignmentHash:W,resultHash:W,transcriptHash:W,traceHash:W.nullable(),resolvedBundleHash:W,artifactPath:o().trim().min(1).max(2e3),cleanup:u({computeReleased:j(),tunnelClosed:j()}).strict(),telemetry:gL.nullable().default(null),contentHash:W}).strict(),es=u({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),totalTokens:m().int().nonnegative(),costUsd:m().nonnegative().nullable()}).strict(),ub=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Xh=u({phase:k(["baseline","adaptation","candidate_adaptation","candidate"]),taskId:E,attemptId:E,sessionId:E.nullable(),turnId:E.nullable(),passed:j(),score:m().min(0).max(1).nullable(),failureClass:Zh.nullable(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),totalTokens:m().int().nonnegative(),latencyMs:m().int().nonnegative(),costUsd:m().nonnegative().nullable(),startedAt:Ce}).strict(),mb=u({targetTaskCount:m().int().nonnegative(),comparedTaskCount:m().int().nonnegative(),passedTaskCount:m().int().nonnegative(),failedTaskCount:m().int().nonnegative(),lowerTaskCount:m().int().nonnegative(),higherTaskCount:m().int().nonnegative(),unchangedTaskCount:m().int().nonnegative()}).strict(),kw=u({target:x("all_tasks_lower"),targetTaskCount:m().int().nonnegative(),comparedTaskCount:m().int().nonnegative(),passedTaskCount:m().int().nonnegative(),failedTaskCount:m().int().nonnegative(),lowerTaskCount:m().int().nonnegative(),higherTaskCount:m().int().nonnegative(),unchangedTaskCount:m().int().nonnegative(),baselineTokens:m().int().nonnegative(),refinedTokens:m().int().nonnegative(),tokenDelta:m().int(),tokenDeltaPercent:m().finite().nullable(),complete:j(),passed:j(),cohorts:u({adaptation:mb,heldOut:mb}).strict()}).strict(),eg=u({baseline:es,adaptation:es,candidateAdaptation:es,candidate:es,refiner:es,grader:es}).strict(),FL=u({usage:eg,observedSpendUsd:m().nonnegative(),attempts:v(Xh).max(1e4)}).strict(),VL=u({id:E,contentHash:W,artifactPath:o().trim().min(1).max(2e3)}).strict(),KL=u({schemaVersion:x("openpond.modelEvaluationReceipt.v1"),benchmarkId:E,resultManifest:u({id:E,contentHash:W,artifactPath:o().trim().min(1).max(2e3)}).strict(),stages:u({baseline:se,adaptation:se,refiner:se,candidateAdaptation:se,candidate:se,comparison:se}).strict(),usage:eg,quality:u({baselinePassRate:m().min(0).max(1),candidatePassRate:m().min(0).max(1),adaptationBaselinePassRate:m().min(0).max(1),adaptationCandidatePassRate:m().min(0).max(1),adaptationCandidatePassed:j(),heldOutCandidatePassed:j(),passed:j()}).strict(),foregroundTokenDelta:m().int(),foregroundTokenDeltaPercent:m().finite().nullable(),taskEfficiency:kw.optional(),efficiency:u({grossForegroundTokenSavings:m().int(),overheadTokens:m().int().nonnegative(),firstPassNetTokenSavings:m().int(),breakEvenReuseCount:m().int().nonnegative().nullable(),amortizedTokenSavings:m().int(),amortizedReuseCount:m().int().positive()}).strict(),budget:u({maximumSpendUsd:m().nonnegative(),observedSpendUsd:m().nonnegative(),enforced:j()}).strict(),evidenceSnapshot:se,lineage:u({adaptationEvidenceHash:W,refinerInputHash:W,refinerOutcomeHash:W,validationHash:W,applyReceiptHash:W,candidateRelease:se,valid:j()}).strict(),invalidReasons:v(o().trim().min(1).max(2e3)).max(100),attempts:v(Xh).max(1e4).default([]),terminalClassification:k(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:u({ref:o().trim().min(1).max(2e3),commit:ub,baseCommit:ub}).strict().nullable(),contentHash:W}).strict(),WL=u({schemaVersion:x("openpond.modelEvaluationStopReceipt.v1"),benchmarkId:E,terminalClassification:x("inconclusive"),stopReason:k(["candidate_harness_unchanged","candidate_lineage_invalid"]),reason:o().trim().min(1).max(5e3),stoppedAfter:x("refiner"),baselineHarness:se,candidateHarness:se,refiner:u({id:E,contentHash:W,outcomeCount:m().int().nonnegative()}).strict(),usage:eg,budget:u({maximumSpendUsd:m().nonnegative(),observedSpendUsd:m().nonnegative(),enforced:j()}).strict(),evidenceSnapshot:se,attempts:v(Xh).max(1e4),contentHash:W}).strict(),pb=u({level:x(.95),lower:m().finite(),upper:m().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."})}),GL=u({schemaVersion:x("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:x("model-comparison"),target:u({kind:k(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:E.nullable(),model:ln.nullable()}).strict(),taskset:Kt,grader:se,sampling:u({seeds:v(m().int()).min(1).max(100),repetitions:m().int().positive().max(20)}).strict(),deterministic:u({attemptedTaskCount:m().int().nonnegative(),completedTaskCount:m().int().nonnegative(),passedTaskCount:m().int().nonnegative(),failedTaskCount:m().int().nonnegative(),meanScore:m().finite().nullable(),passRate:m().min(0).max(1).nullable(),passRateCi95:pb.nullable()}).strict(),judge:u({judgeModel:ln,judgeRelease:se,rubricRelease:se,calibrationRelease:se,score:m().min(0).max(100),scoreCi95:pb,comparisonCount:m().int().positive(),wins:m().int().nonnegative(),ties:m().int().nonnegative(),losses:m().int().nonnegative(),referenceLabel:o().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:v(u({attemptId:E.nullable().default(null),taskId:E,seed:m().int(),repetition:m().int().nonnegative(),status:k(["succeeded","failed"]),deterministicScore:m().finite().nullable(),passed:j().nullable(),judgeScore:m().min(0).max(100).nullable(),judgePreference:k(["win","tie","loss"]).nullable(),transcriptHash:W.nullable(),traceHash:W.nullable(),transcriptArtifact:u({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:u({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),latencyMs:m().int().nonnegative().nullable().default(null),failureClass:Zh.nullable()}).strict()).max(1e5),usage:u({policy:es.nullable(),judge:es.nullable(),observedSpendUsd:m().nonnegative().nullable(),evaluationGpuSeconds:m().nonnegative().nullable().default(null)}).strict(),managedServing:u({jobId:E,terminalState:k(["completed","cancelled","failed","budget_exhausted"]),sourcePolicyVersion:m().int().nonnegative(),sourceAdapterSha256:W.nullable(),servedPolicyVersion:m().int().nonnegative().nullable(),servedAdapterSha256:W.nullable(),accruedSpendUsd:m().nonnegative(),cleanupAttestationHash:W,resourceCount:m().int().nonnegative(),activeResourceCount:x(0)}).strict().nullable().default(null),evidenceSnapshot:u({id:E,contentHash:W,artifactPath:o().trim().min(1).max(2e3)}).strict(),completedAt:Ce,contentHash:W}).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."})}),ZL=u({advancedEvaluation:Yh.optional(),benchmarkId:x("harness-refiner"),model:ln,upstreamModel:u({providerId:E,modelId:o().trim().min(1).max(300),revision:o().trim().min(1).max(300),pricing:u({version:o().trim().min(1).max(300),source:o().trim().min(1).max(300),effectiveAt:Ce,inputUsdPerMillionTokens:m().nonnegative(),cachedInputUsdPerMillionTokens:m().nonnegative(),outputUsdPerMillionTokens:m().nonnegative()}).strict().optional()}).strict(),reasoningEffort:o().trim().min(1).max(100).nullable(),seeds:v(m().int()).min(1).max(100),repetitions:m().int().positive().max(20),maximumSpendUsd:m().nonnegative(),attemptPlan:v(u({stage:k(["baseline","adaptation","candidate_adaptation","candidate"]),split:o().trim().min(1).max(100),taskIds:v(E).min(1).max(1e5),attemptCount:m().int().positive()}).strict()).length(4)}).strict(),JL=u({benchmarkId:x("model-comparison"),target:u({kind:k(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:E.nullable(),model:ln.nullable()}).strict(),grader:se,judge:u({model:ln,release:se,rubricRelease:se,calibrationRelease:se,referenceLabel:o().trim().min(1).max(300)}).strict().nullable(),seeds:v(m().int()).min(1).max(100),repetitions:m().int().positive().max(20),maximumSpendUsd:m().nonnegative(),series:u({id:E,protocol:u({id:E,revision:m().int().positive(),contentHash:W}).strict()}).strict().nullable().default(null),panel:u({id:E,role:k(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:E.nullable()}).strict().nullable().default(null),comparisonPair:u({entryId:E,parent:Sw,candidateModelVersionId:E}).strict().nullable().default(null),attemptPlan:v(u({stage:x("comparison"),split:o().trim().min(1).max(100),taskIds:v(E).min(1).max(1e5),attemptCount:m().int().positive()}).strict()).length(1)}).strict(),QL=dt([ZL,JL]),YL=u({schemaVersion:x("openpond.modelRun.v1"),id:E,modelId:E,modelVersionId:E.nullable(),profileId:E,kind:k(["rollout_smoke","training","evaluation"]),status:k(["prepared","running","succeeded","failed","cancelled"]),method:k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]).nullable(),destinationId:E.nullable(),taskset:Kt,comparisonSeriesEntry:mi.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:se.nullable().optional(),quote:u({maximumSpendUsd:m().nonnegative(),hourlyCostUsd:m().nonnegative().nullable()}).strict().nullable(),evaluation:QL.nullable().default(null),evaluationProgress:u({stage:k(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:m().int().nonnegative(),totalAttempts:m().int().positive(),accounting:FL.nullable().default(null),advancedAccounting:pL.optional(),evidenceSnapshot:VL.nullable().default(null)}).strict().nullable().default(null),reward:u({raw:m(),components:ve(o(),m())}).strict().nullable(),receipt:dt([BL,KL,WL,GL,uL]).nullable(),adapterArtifactLineageId:E.nullable(),failure:o().trim().min(1).max(5e3).nullable(),startedAt:Ce,completedAt:Ce.nullable(),updatedAt:Ce}).strict().superRefine((e,t)=>{e.status==="succeeded"&&!e.receipt&&t.addIssue({code:"custom",message:"A successful Model Run requires a canonical receipt."}),e.kind==="evaluation"&&(e.method!==null||e.destinationId!==null||!e.evaluation||e.adapterArtifactLineageId!==null)&&t.addIssue({code:"custom",message:"An evaluation Model Run requires evaluation configuration and cannot claim training method, destination, or adapter lineage."}),e.kind==="evaluation"&&e.receipt&&e.receipt.schemaVersion!=="openpond.modelEvaluationReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelEvaluationStopReceipt.v1"&&e.receipt.schemaVersion!=="openpond.modelComparisonBenchmarkReceipt.v1"&&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 eG(e){const t=new Map;for(const I of e.attempts){const C=`${I.phase}\0${I.taskId}`,P=t.get(C);(!P||I.startedAt>P.startedAt||I.startedAt===P.startedAt&&I.attemptId>P.attemptId)&&t.set(C,I)}const n=[...t.values()],a=[["adaptation","adaptation","candidate_adaptation"],["held_out","baseline","candidate"]].flatMap(([I,C,P])=>{const _=new Map(n.filter(M=>M.phase===P).map(M=>[M.taskId,M]));return n.filter(M=>M.phase===C).flatMap(M=>{const A=_.get(M.taskId);return A?[{cohort:I,taskId:M.taskId,baseline:M,refined:A,tokenDelta:A.totalTokens-M.totalTokens}]:[]})}),r=new Set(n.filter(I=>I.phase==="baseline"||I.phase==="adaptation").map(I=>I.taskId)).size,s=e.targetTaskCount??r;if(!Number.isInteger(s)||s<0)throw new Error("Benchmark task-efficiency target must be a non-negative integer.");const i={adaptation:new Set(n.filter(I=>I.phase==="adaptation").map(I=>I.taskId)).size,held_out:new Set(n.filter(I=>I.phase==="baseline").map(I=>I.taskId)).size},c=(I,C)=>({targetTaskCount:C,comparedTaskCount:I.length,passedTaskCount:I.filter(P=>P.tokenDelta<0).length,failedTaskCount:I.filter(P=>P.tokenDelta>=0).length,lowerTaskCount:I.filter(P=>P.tokenDelta<0).length,higherTaskCount:I.filter(P=>P.tokenDelta>0).length,unchangedTaskCount:I.filter(P=>P.tokenDelta===0).length}),d=c(a,s),l=a.reduce((I,C)=>I+C.baseline.totalTokens,0),p=a.reduce((I,C)=>I+C.refined.totalTokens,0),f=p-l,S=a.length===s;return{summary:kw.parse({target:"all_tasks_lower",...d,baselineTokens:l,refinedTokens:p,tokenDelta:f,tokenDeltaPercent:l>0?f/l*100:null,complete:S,passed:S&&d.passedTaskCount===s,cohorts:{adaptation:c(a.filter(I=>I.cohort==="adaptation"),i.adaptation),heldOut:c(a.filter(I=>I.cohort==="held_out"),i.held_out)}}),pairs:a}}const XL=k(["measuring","up_to_date","needs_attention"]),ez=k(["fixed","retained","regressed","unresolved","unavailable"]),fb=u({evaluationRunId:E,attemptKey:E,artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3),transcriptHash:W.nullable(),traceHash:W.nullable()}).strict(),sf=u({level:x(.95),lower:m().finite(),upper:m().finite()}).strict(),tz=u({panelId:E,panelRole:vu,passLabel:E.nullable(),taskset:Kt,attempted:m().int().nonnegative(),available:m().int().nonnegative(),passed:m().int().nonnegative(),strictSuccess:m().min(0).max(1).nullable(),strictSuccessCi95:sf.nullable(),judgeScore:m().min(0).max(100).nullable(),judgeScoreCi95:sf.nullable()}).strict(),nz=u({schemaVersion:x("openpond.modelCurrencySnapshot.v1"),id:E,contentHash:W,seriesId:E,protocol:u({id:E,revision:m().int().positive(),contentHash:W}).strict(),entryId:E,passLabel:E,parent:st("kind",[u({kind:x("base_model"),id:E,revision:o().trim().min(1).max(500)}).strict(),u({kind:x("model_version"),id:E,contentHash:W}).strict()]),candidate:u({kind:x("model_version"),id:E,contentHash:W}).strict(),sources:u({evaluationRunIds:v(E).max(1e5),attemptIds:v(E).max(1e6),tasksets:v(Kt).max(1e4),grader:se,judge:se.nullable(),calibration:se.nullable()}).strict(),matches:v(u({key:E,panelId:E,panelRole:vu,taskId:E,issueFamilyId:E,seed:m().int(),repetition:m().int().nonnegative(),classification:ez,parentPassed:j().nullable(),candidatePassed:j().nullable(),parentAttempt:fb.nullable(),candidateAttempt:fb.nullable()}).strict()).max(1e6),taskIds:u({fixed:v(E).max(1e6),retained:v(E).max(1e6),regressed:v(E).max(1e6),unresolved:v(E).max(1e6),unavailable:v(E).max(1e6)}).strict(),panels:v(tz).max(1e4),metrics:u({knownIssueCoverage:m().min(0).max(1).nullable(),issueFamilyGeneralization:m().min(0).max(1).nullable(),behavioralRetention:m().min(0).max(1).nullable(),currentAcquisitionDelta:m().finite().nullable(),retainedDeltaPoints:m().finite().nullable(),frontierStrictDelta:m().finite().nullable(),pairedPValue:m().min(0).max(1).nullable(),wins:m().int().nonnegative(),ties:m().int().nonnegative(),losses:m().int().nonnegative()}).strict(),statistics:u({matchedAttemptCount:m().int().nonnegative(),strictDelta:m().finite().nullable(),strictDeltaCi95:sf.nullable(),exactPairedBinaryPValue:m().min(0).max(1).nullable(),pairedBootstrapSamples:m().int().positive()}).strict(),criteria:u({allRequiredAttemptsTerminal:j(),criticalCorrectionPassRate:m().min(0).max(1).nullable(),siblingPassRate:m().min(0).max(1).nullable(),behavioralRetentionRate:m().min(0).max(1).nullable(),retainedRegressionPoints:m().finite().nullable(),criticalPriorRegressionCount:m().int().nonnegative(),thresholdRelease:se}).strict(),efficiency:u({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),totalTokens:m().int().nonnegative(),costUsd:m().nonnegative().nullable(),latencyMs:m().int().nonnegative(),tokensPerSuccess:m().nonnegative().nullable(),throughputPerHour:m().nonnegative().nullable(),gpuSeconds:m().nonnegative().nullable()}).strict(),invariants:u({systemPromptHash:W,toolSchema:se,application:se,harness:se,runtime:se,grader:se,autoRefinerEnabled:j()}).strict(),evidenceState:XL,evidenceReasons:v(E).max(100),projectedAt:Ce}).strict(),ad=st("kind",[u({kind:x("base_model"),id:E,revision:o().trim().min(1).max(500),label:o().trim().min(1).max(300)}).strict(),u({kind:x("model_version"),id:E,label:o().trim().min(1).max(300)}).strict(),u({kind:x("captured_model"),id:E,label:o().trim().min(1).max(300)}).strict()]),hc=dt([u({source:x("evaluation_run").default("evaluation_run"),evaluationRunId:E,attemptId:E,modelLabel:o().trim().min(1).max(300).nullable().default(null),modelVersionId:E.nullable().default(null),reward:m().finite().nullable(),components:ve(o(),m().finite()).default({})}).strict(),u({source:x("imported_response"),modelLabel:o().trim().min(1).max(300),modelVersionId:E.nullable().default(null),response:ke().refine(e=>e!==void 0,"An imported model response is required."),reward:m().finite().nullable().default(null),components:ve(o(),m().finite()).default({})}).strict()]),az=dt([u({taskId:E,target:ad,attempt:hc}).strict(),u({taskId:E,target:k(["base","current"]).default("current"),attempt:hc}).strict(),u({taskId:E,target:k(["base","current"]).default("current"),evaluationRunId:E,attemptId:E,reward:m().finite().nullable(),components:ve(o(),m().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);u({schemaVersion:x("openpond.continualLearningDailyBatchManifest.v1"),id:E,seriesId:E,scheduleEntryId:E,dayOrdinal:m().int().positive().max(1e4),sourceTaskset:Kt,taskIds:v(E).min(1).max(1e3),observedAttempts:v(az).max(1e3).default([]),sourceFileName:o().trim().min(1).max(500).nullable().default(null),availableAt:Ce}).strict().superRefine((e,t)=>{new Set(e.taskIds).size!==e.taskIds.length&&t.addIssue({code:"custom",path:["taskIds"],message:"A daily batch cannot repeat a task."}),new Set(e.observedAttempts.map(a=>`${a.taskId}:${oz(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 rz=u({schemaVersion:x("openpond.continualLearningDailyBatch.v1"),id:E,seriesId:E,scheduleEntryId:E,dayOrdinal:m().int().positive().max(1e4),label:o().trim().min(1).max(100),runMode:k(["automatic","manual"]).optional(),source:k(["json_upload","sealed_fixture"]),sourceFileName:o().trim().min(1).max(500).nullable(),sourceTaskset:Kt,tasks:v(u({taskId:E,taskContentHash:W,familyKey:E,disposition:k(["include","defer","exclude"]).nullable(),oracleReview:k(["pending","confirmed","needs_correction"]),note:o().trim().max(2e3),observedAttempt:hc.nullable(),baselineAttempt:hc.nullable().default(null),responses:v(u({target:ad,attempt:hc}).strict()).max(100).default([]),stagedAt:Ce.nullable().default(null),queuedEntry:mi.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:u({status:k(["awaiting","running","ready","failed"]),requestedTargets:v(k(["base","current"])).max(2).default(["base","current"]),requestedPolicies:v(ad).max(100).default([]),runs:v(u({target:ad,runId:E}).strict()).max(100).default([]),baselineRunId:E.nullable(),currentRunId:E.nullable(),currentPolicy:st("kind",[u({kind:x("base_model"),id:E}).strict(),u({kind:x("model_version"),id:E}).strict()]).nullable(),failure:o().trim().min(1).max(2e3).nullable()}).strict().default({status:"awaiting",requestedTargets:["base","current"],requestedPolicies:[],runs:[],baselineRunId:null,currentRunId:null,currentPolicy:null,failure:null}),status:k(["pending","reviewed","queued"]),queuedEntry:mi.nullable(),reviewedBy:E.nullable(),reviewedAt:Ce.nullable(),availableAt:Ce,revision:m().int().positive(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{new Set(e.tasks.map(a=>a.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",path:["tasks"],message:"A daily batch cannot repeat a task."});for(const[a,r]of e.tasks.entries()){const s=r.responses.map(i=>ww(i.target));new Set(s).size!==s.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."})}),sz=u({schemaVersion:x("openpond.continualBenchIssueReview.v1"),id:E,seriesId:E,scheduleEntryId:E,passLabel:E,packet:yL,splitManifest:u({id:E,contentHash:W}).strict(),decisions:v(u({taskId:E,disposition:k(["include","defer","exclude"]).nullable(),note:o().trim().max(2e3)}).strict()).min(2).max(1e4),status:k(["pending","reviewed","queued"]),queuedEntry:mi.nullable(),reviewedBy:E.nullable(),reviewedAt:Ce.nullable(),revision:m().int().positive(),createdAt:Ce,updatedAt:Ce}).strict().superRefine((e,t)=>{const n=[...e.packet.cases.map(s=>s.taskId)].sort(),a=[...e.decisions.map(s=>s.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 r=e.decisions.every(s=>s.disposition!==null&&s.note.length>0);e.status!=="pending"&&!r&&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 ww(e){return`${e.kind}:${e.id}`}function oz(e){return typeof e=="string"?e:ww(e)}const La=o().trim().min(1).max(240),ya=o().trim().min(8).max(256),Iw=k(["grpo","dapo","gspo-token"]),Ac=u({id:La,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ya}),iz=u({maxRollouts:m().int().positive().max(1e6),maxEnvironmentExecutions:m().int().positive().max(1e6),maxInputTokens:m().int().positive(),maxOutputTokens:m().int().positive(),maxOptimizerSteps:m().int().positive().max(1e6),wallTimeMs:m().int().positive(),maximumCostUsd:m().nonnegative().nullable()}),cz=u({method:x("grpo"),groupSize:m().int().min(2).max(128),normalization:x("group_standardized"),advantageEpsilon:m().positive().max(.01).default(1e-8),loss:Iw,clipRange:m().positive().max(1).default(.2),iterations:m().int().min(2).max(16).default(2),microbatchSize:m().int().positive().max(128).default(1),gradientAccumulationSteps:m().int().positive().max(128).default(1),adamw:iw}),_w=u({method:x("ppo"),valueModel:Ac,gamma:m().min(0).max(1),gaeLambda:m().min(0).max(1),policyClip:m().positive().max(1),valueClip:m().positive().max(10),valueLossCoefficient:m().nonnegative().max(10),ppoEpochs:m().int().positive().max(100),minibatchSize:m().int().positive().max(1e5)}),lz=st("method",[cz,_w]),Cw=u({rewardModelVersion:u({id:La,contentHash:ya}).strict(),qualificationReport:u({id:La,contentHash:ya}).strict().nullable().default(null),evaluationReferences:v(u({id:La,contentHash:ya}).strict()).max(1e3).default([]),checkpoint:u({id:La,contentHash:ya,objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:v(u({path:o().trim().min(1).max(512),sizeBytes:m().int().positive(),sha256:ya}).strict()).min(4).max(128)}).strict(),runtime:xw,processorRelease:u({id:La,contentHash:ya}).strict(),rewardComposerRelease:u({id:La,contentHash:ya}).strict(),executionReceipt:u({id:La,contentHash:ya}).strict()}).strict(),Rw=u({schemaVersion:x("openpond.policyOptimization.v1"),policyModel:Ac,referenceModel:Ac,dataset:u({tasksetId:La,tasksetHash:ya,split:x("train"),selectionStrategy:k(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:m().int(),maxExamples:m().int().positive().max(1e5)}),sampler:u({temperature:m().min(0).max(2),topP:m().min(0).max(1),maxOutputTokens:m().int().positive().max(32768),maxTurns:m().int().positive().max(1e3),concurrency:m().int().positive().max(1e3)}),environment:u({id:La,version:o().trim().min(1).max(256),toolContractHash:ya}),reward:u({graderId:La,graderHash:ya,learnedPreference:Cw.nullable().default(null)}),kl:u({coefficient:m().nonnegative().nullable(),referenceConstraint:x("fixed_reference")}),budgets:iz,checkpointEverySteps:m().int().positive(),seed:m().int(),evaluationSplit:x("frozen_eval"),optimizer:lz}),ge=o().trim().min(1).max(240),It=o().trim().min(1),tt=o().trim().min(8).max(256),Qc=ve(o(),ke()).default({}),Pw=u({schemaVersion:x("openpond.localModelChatConfiguration.v1").default("openpond.localModelChatConfiguration.v1"),profile:k(["efficient","full_harness","custom"]).default("efficient"),systemPromptMode:k(["lean","full_harness","custom"]).default("lean"),customSystemPrompt:o().max(2e4).nullable().default(null),contextWindowTokens:m().int().min(128).max(32768).default(1024),maxOutputTokens:m().int().min(1).max(512).default(64),temperature:m().min(0).max(2).default(0),repetitionPenalty:m().min(.5).max(2).default(1.1),noRepeatNgramSize:m().int().min(0).max(10).default(3),compaction:k(["off","when_needed"]).default("when_needed"),keepWarmSeconds:m().int().min(0).max(3600).default(300),updatedAt:It.nullable().default(null)}),dz=Pw.parse({}),uz=u({schemaVersion:x("openpond.managedAdapterServingProjection.v1"),teamId:ge.nullable().default(null),source:x("sandbox_managed_rl"),sourceRef:ge,canonicalArtifactId:ge.nullable(),canonicalArtifactState:k(["imported_unvalidated","evaluating","promotable","rejected","deleted"]).nullable(),canonicalDeploymentId:ge.nullable(),canonicalDeploymentState:k(["requested","deploying","ready","degraded","deleting","deleted","failed"]).nullable(),state:k(["pending","imported","ready","failed"]),customerBindingAllowed:j().default(!1),artifactContentHash:tt.nullable().default(null),baseProfileId:ge.nullable().default(null),publishedAt:It.nullable(),lastSyncedAt:It,lastError:o().trim().min(1).max(5e3).nullable()});function tG(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function Tw(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function nG(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"&&Tw(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function aG(e){const t=e.managedServing;return t?Tw(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const tg="openpond.crossSystemOperations.v1",rG="1.0.0",Aw="openpond.crossSystemTools.v1",mz=["search_crm","query_billing","search_support","run_python"],pz=k(["train","validation","frozen_eval"]),fz=k(["easy","medium","hard"]),hz=k(["renewal_risk_v2"]);k(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);u({seed:m().int().nonnegative(),split:pz,difficulty:fz,scenarioProfile:hz.optional()});const np={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},ap={type:"integer",minimum:1,maximum:50,default:25},Ew=[{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:np,limit:ap}}},{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:np,limit:ap}}},{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:np,limit:ap}}},{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}}}}],Yc=Cz({schemaVersion:Aw,tools:Ew}),gz=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${Yc}.`,"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(" "),vz=15;function bz(e="auto"){return[gz,"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: ${vz}.`,`Registered tool signatures: ${Ew.map(yz).join("; ")}`].join(`
|
|
110
|
+
`)}bz();function yz(e){const t=Pd(e.parameters),n=Pd(t.properties),a=jw(t.required),r=Object.fromEntries(a.map(s=>[s,rd(n[s])]));return`${e.name}(${JSON.stringify(r)})`}function rd(e){const t=Pd(e),n=of(t.anyOf);if(n.length)return n.map(rd).join("|");const a=of(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[rd(t.items)];if(t.type==="object"){const r=Pd(t.properties),s=jw(t.required);return Object.fromEntries(s.map(i=>[i,rd(r[i])]))}return typeof t.type=="string"?t.type:"unknown"}function Pd(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function of(e){return Array.isArray(e)?e:[]}function jw(e){return of(e).filter(t=>typeof t=="string")}const Td=k(mz),Sz=st("kind",[u({kind:x("model"),turn:m().int().nonnegative(),content:o().max(1e5)}),u({kind:x("tool_call"),turn:m().int().nonnegative(),callId:o().trim().min(1).max(240),name:Td,arguments:ve(o(),ke())}),u({kind:x("tool_result"),turn:m().int().nonnegative(),callId:o().trim().min(1).max(240),name:Td,ok:j(),result:ke(),rows:m().int().nonnegative(),bytes:m().int().nonnegative(),durationMs:m().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),u({kind:x("final"),turn:m().int().nonnegative(),content:o().max(1e5)})]),xz=u({schemaVersion:x(tg),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:x(Yc),modelRef:u({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:k(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:v(Sz).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:ve(o(),ke()).default({})}),kz=u({schemaVersion:x(tg),trajectoryId:o().trim().min(1).max(240),outcome:k(["correct","incorrect","parse_failure","budget_exhausted","tool_schema_violation","infrastructure_failure","cancelled"]),reward:m().min(0).max(1.15).nullable(),rewardEligible:j(),exactAnswer:j(),components:u({exactAnswer:m().min(0).max(1),efficiency:m().min(0).max(.1),conciseOutput:m().min(0).max(.05)}),metrics:u({toolCalls:m().int().nonnegative(),rowsRead:m().int().nonnegative(),bytesRead:m().int().nonnegative(),consecutiveRetrievalCalls:m().int().nonnegative(),wallTimeMs:m().int().nonnegative(),parseFailures:m().int().nonnegative(),budgetExhausted:j()}),parsedAnswer:ke().nullable(),feedback:v(o().trim().min(1).max(5e3)).max(100)}),wz=u({id:o().trim().min(1).max(240),type:x("function"),function:u({name:Td,arguments:o().max(2e4)})}),Mw=u({role:k(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:v(wz).max(4).optional()});u({schemaVersion:x(tg),id:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),trajectoryId:o().trim().min(1).max(240),toolContractHash:x(Yc),approval:u({status:x("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:v(Mw).min(3).max(1e3)});const Iz=u({tasksetTaskId:o().trim().min(1).max(240),environmentTaskId:o().trim().min(1).max(240),family:k(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]),prompt:o().trim().min(1).max(1e5),finalAnswer:o().trim().min(1).max(2e5),trajectoryId:o().trim().min(1).max(240),trajectoryHash:o().trim().min(8).max(256),toolNames:v(Td).min(1).max(100),toolCallCount:m().int().positive(),messageCount:m().int().min(3),reward:m().min(0).max(1.15),messages:v(Mw).min(3).max(1e3)}),_z=u({status:x("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1),previewHash:o().trim().min(8).max(256),trajectoryCount:m().int().positive()});u({schemaVersion:x("openpond.crossSystemExpertBootstrapPreview.v1"),tasksetId:o().trim().min(1).max(240),tasksetHash:o().trim().min(8).max(256),tasksetRevision:m().int().positive(),previewHash:o().trim().min(8).max(256),toolContractHash:x(Yc),status:k(["ready_for_review","approved"]),approval:_z.nullable(),tasks:v(Iz).min(1).max(100)});function Cz(e){const t=cf(e);let n=2166136261,a=2654435769;for(let r=0;r<t.length;r+=1){const s=t.charCodeAt(r);n=Math.imul(n^s,16777619),a=Math.imul(a^s,2246822507)}return`${Aw}:${hb(n)}${hb(a)}`}function cf(e){return Array.isArray(e)?`[${e.map(cf).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${cf(n)}`).join(",")}}`:JSON.stringify(e)}function hb(e){return(e>>>0).toString(16).padStart(8,"0")}const Rz=u({schemaVersion:x("openpond.singleTurnPolicyTrajectory.v1"),id:ge,taskId:ge,status:k(["completed","infrastructure_failure"]),promptHash:tt,responseText:o().max(2e6),infrastructureError:o().trim().min(1).max(1e4).nullable(),startedAt:It,completedAt:It,metadata:Qc}),Pz=u({schemaVersion:x("openpond.ppoTrajectory.v1"),id:ge,taskId:ge,policyModelId:ge,referenceModelId:ge,valueModelId:ge,steps:v(u({index:m().int().nonnegative(),observationHash:tt,actionTokenIds:v(m().int().nonnegative()).min(1),terminated:j(),truncated:j(),reward:m(),policyLogProbability:m(),referenceLogProbability:m(),valuePrediction:m(),return:m(),advantage:m(),mask:m().min(0).max(1)})).min(1).max(1e5),createdAt:It}),Tz=u({schemaVersion:x("openpond.exactAnswerVerifierResult.v1"),outcome:k(["correct","incorrect","parse_failure","infrastructure_failure"]),graderSetHash:tt,score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),expectedAnswerHash:tt,extractedAnswer:o().max(2e4).nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3)}),Az=u({schemaVersion:x("openpond.rolloutTrajectoryReceipt.v1"),id:ge,jobId:ge,planId:ge,tasksetId:ge,tasksetHash:tt,taskId:ge,split:x("train"),correlationId:ge,provider:ge,providerTrace:u({invocationId:ge,experimentId:ge,rolloutId:ge,runId:ge,rowId:ge}),optimizerMethod:k(["grpo","ppo"]).default("grpo"),evidenceLevels:u({requested:k(["trajectory","aggregate","provider_reported"]),observed:k(["trajectory","aggregate","provider_reported"]),providerReported:k(["trajectory","aggregate","provider_reported"])}).default({requested:"trajectory",observed:"trajectory",providerReported:"provider_reported"}),budgetUsage:u({rollouts:m().int().nonnegative(),environmentExecutions:m().int().nonnegative(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),optimizerSteps:m().int().nonnegative(),costUsd:m().nonnegative()}).default({rollouts:0,environmentExecutions:0,inputTokens:0,outputTokens:0,optimizerSteps:0,costUsd:0}),environment:u({id:ge,version:o().trim().min(1).max(256),worldId:ge,worldHash:tt,toolContractHash:tt}),policy:u({modelId:ge,checkpointId:ge.nullable(),completionParametersHash:tt}),status:k(["received","running","succeeded","failed"]),failureClass:k(["policy_failure","parse_failure","tool_schema_violation","budget_exhausted","cancelled","environment_failure","infrastructure_failure"]).nullable(),reward:u({eligible:j(),raw:m().min(0).max(1.15).nullable(),normalized:m().min(0).max(1).nullable(),components:ve(o(),m())}),trajectory:dt([xz,Rz,Pz]).nullable(),verifier:dt([kz,Tz]).nullable(),providerStatus:ve(o(),ke()).default({}),receivedAt:It,startedAt:It.nullable(),completedAt:It.nullable(),updatedAt:It}),sG="dataset-exact-answer",oG="dataset-exact-answer-v1",iG="no-tools-v1",ys=k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),bu=k(["lora","full"]),to=k(["openpond_managed"]),Ez=ht(()=>({schemaVersion:x("openpond.sftRecipe.v1"),method:x("sft"),parameterization:x("lora"),baseModel:u({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:tt}),dataset:u({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),completionOnly:j(),maxSequenceLength:m().int().positive().max(32768),maxExamples:m().int().positive().max(1e5).default(1e3),selectionStrategy:x("stable_hash_top_n").default("stable_hash_top_n"),selectionSeed:m().int().default(17)}),lora:u({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),optimizer:u({learningRate:m().positive(),epochs:m().positive().max(100),maxSteps:m().int().positive().max(1e6),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int()}),resourceLimits:u({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})}));ht(()=>({id:ge,input:ve(o(),ke()),expectedOutput:ve(o(),ke()),tags:v(ge).max(100).default([])}));ht(()=>({id:ge,prompt:o().min(1).max(5e5),chosen:o().min(1).max(5e5),rejected:o().min(1).max(5e5),sourceRefs:v(ge).min(1).max(1e4)}));ht(()=>({id:ge,input:ve(o(),ke()),tags:v(ge).max(100).default([])}));ht(()=>({schemaVersion:x("openpond.rewardModelRecipe.v1"),method:x("reward_model"),parameterization:x("lora_with_scalar_head"),runScope:k(["synthetic_smoke","human_preference"]),baseModel:u({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),processorRevision:o().trim().min(1).max(256),chatTemplateHash:tt}).strict(),tasksetRelease:se,preferenceDatasetRelease:se,processorRelease:se,input:u({kind:x("structured_text"),serialization:k(["scenario_input_and_candidate_json_v1","visible_agent_trajectory_v1"]),maxCharacters:m().int().positive().max(5e5)}).strict().default({kind:"structured_text",serialization:"scenario_input_and_candidate_json_v1",maxCharacters:32e3}),lora:u({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}).strict(),heads:u({scalar:x("pooled_hidden_state_linear"),bucket:k(["none","three_class"]).default("three_class")}).strict(),loss:u({ranking:x("bradley_terry"),rankingWeight:m().positive(),bucketWeight:m().nonnegative(),tieWeight:m().nonnegative()}).strict(),optimizer:u({learningRate:m().positive(),maxSteps:m().int().positive().max(1e5),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int(),checkpointEverySteps:m().int().positive().max(1e5)}).strict(),resourceLimits:u({wallTimeMs:m().int().positive().max(1440*60*1e3),maxExamples:m().int().positive().max(1e5),maxInputCharacters:m().int().positive().max(5e5).default(32e3),maxImagePixels:m().int().positive().max(1e8).optional(),maximumSpendUsd:m().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 jz=ht(()=>({schemaVersion:x("openpond.rftRecipe.v1"),method:x("grpo"),parameterization:x("lora"),baseModel:u({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:tt}),dataset:u({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),maxPromptTokens:m().int().positive().max(32768),maxExamples:m().int().positive().max(1e5).default(1e3),selectionStrategy:k(["stable_hash_top_n","rft_easy_curriculum_v1"]).default("stable_hash_top_n")}),lora:u({rank:m().int().positive().max(256)}),rollout:u({groupSize:m().int().min(2).max(64),concurrency:m().int().positive().max(32),maxTurns:m().int().positive().max(100),maxOutputTokens:m().int().positive().max(8192),temperature:m().min(0).max(2),topP:m().positive().max(1),seed:m().int()}),optimizer:u({learningRate:m().positive(),maxSteps:m().int().positive().max(1e5),clipRange:m().positive().max(1).default(.2),iterations:m().int().min(2).max(16).default(2),microbatchSize:m().int().positive().max(64).default(1),gradientAccumulationSteps:m().int().positive().max(64).default(1),advantageEpsilon:m().positive().max(.01).default(1e-8),adamw:iw}),loss:u({method:Iw.default("grpo"),klBeta:m().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:u({graderId:ge,graderHash:tt,environmentId:ge,environmentVersion:o().trim().min(1).max(256),toolContractHash:tt,learnedPreference:Cw.nullable().optional()}),resourceLimits:u({wallTimeMs:m().int().positive().max(1440*60*1e3),maxGpuSeconds:m().int().positive().max(10800).optional(),maxRollouts:m().int().positive().max(1e5),maxPayloadBytes:m().int().positive().max(10*1024*1024)}),policyOptimization:Rw.nullable().default(null),continuation:u({schemaVersion:x("openpond.crossJobContinuationRequest.v1"),parentArtifact:se,sourceArtifact:u({jobId:ge,artifactId:ge,checkpointId:ge,contentHash:tt}).strict(),optimizerMode:k(["continue","reset"])}).strict().optional()})),Mz=ht(()=>({schemaVersion:x("openpond.dpoRecipe.v1"),method:x("dpo"),parameterization:x("lora"),policyModel:Ac,referenceModel:Ac,dataset:u({trainSplit:x("train"),validationSplit:k(["validation","frozen_eval"]),maxPairs:m().int().positive().max(1e5),maxPromptTokens:m().int().positive().max(32768),maxCompletionTokens:m().int().positive().max(32768),selectionStrategy:x("stable_hash_top_n"),selectionSeed:m().int()}),lora:u({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),loss:u({variant:x("sigmoid"),beta:m().positive().max(10),labelSmoothing:m().min(0).max(.5).default(0)}),optimizer:u({learningRate:m().positive(),epochs:m().positive().max(100),maxSteps:m().int().positive().max(1e6),batchSize:m().int().positive().max(1e4),gradientAccumulationSteps:m().int().positive().max(1e4),seed:m().int()}),referenceLogprobs:u({cacheSchemaVersion:x("openpond.dpoReferenceLogprobs.v1"),cacheKey:tt,invalidationHash:tt}),resourceLimits:u({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})})),Oz=ht(()=>({schemaVersion:x("openpond.ppoRecipe.v1"),method:x("ppo"),parameterization:x("lora"),policyOptimization:Rw.extend({optimizer:_w}),lora:u({rank:m().int().positive().max(256),alpha:m().positive().max(1024),dropout:m().min(0).max(1),targetModules:v(ge).min(1).max(100)}),valueHead:u({initialization:x("policy_hidden_state_linear"),optimizerLearningRate:m().positive(),artifactName:x("value_head.safetensors")}),policyLearningRate:m().positive(),resume:u({checkpointId:ge.nullable(),policyHash:tt,referenceHash:tt,valueModelHash:tt,optimizerStateHash:tt.nullable()}),resourceLimits:u({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})})),$z=ht(()=>({schemaVersion:x("openpond.unsupportedRecipe.v1"),method:ys.exclude(["sft","dpo","grpo","ppo"]),parameterization:bu,unsupportedReason:o().trim().min(1).max(5e3)})),Nz=dt([Ez,Mz,jz,Oz,$z]),Dz=ht(()=>({schemaVersion:x("openpond.trainingDestinationCapabilities.v1"),destinationId:to,available:j(),methods:v(ys),parameterizations:v(bu),modelAllowlist:v(ge).default([]),maxDatasetBytes:m().int().nonnegative().nullable(),environmentPlacements:v(k(["none","local","remote","colocated","provider_native"])),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable(),checkedAt:It})),Lz=ht(()=>({destinationId:to,available:j(),methods:v(ys),parameterizations:v(bu),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable()})),zz=ht(()=>({schemaVersion:x("openpond.baseModelCandidate.v1"),selectionKey:ge,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:Jc,available:j(),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:v(ys),executionOptions:v(Lz).min(1)})),Hz=ht(()=>({code:ge,severity:k(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)})),Uz=ht(()=>({schemaVersion:x("openpond.trainingCompatibility.v1"),compatible:j(),destinationId:to,tasksetId:ge,recipeMethod:ys,issues:v(Hz),checkedAt:It})),qz=dt([qk,k(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);ht(()=>({method:ys,state:k(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:v(qz).default([]),reasons:v(o().trim().min(1).max(5e3)).default([]),destinationId:to.nullable().default(null)}));k(["small","standard","custom","small_experiment"]);const Bz=dk,Ow=ht(()=>({schemaVersion:x("openpond.trainingPlan.v1"),id:ge,modelId:ge,tasksetId:ge,tasksetHash:tt,comparisonSeriesEntry:mi.nullable().optional(),evaluationTasksetRef:Kt.nullable().optional(),harnessRelease:se.nullable().optional(),modelImprovementQualification:se.nullable().optional(),destinationId:to,recipe:Nz,environmentPlacement:k(["none","local","remote","colocated","provider_native"]),compatibility:Uz,dataPolicy:u({exportApproved:j(),approvedSourceIds:v(ge),retentionDays:m().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:m().nonnegative().nullable(),createdAt:It,contentHash:tt})),Fz=ht(()=>({path:o().trim().min(1).max(2e3),sha256:tt,sizeBytes:m().int().nonnegative(),role:k(["manifest","task_data","grader","environment","recipe","policy","provenance"])})),ng=ht(()=>({schemaVersion:x("openpond.trainingBundle.v1"),id:ge,planId:ge,tasksetId:ge,tasksetHash:tt,recipeHash:tt,files:v(Fz).min(1).max(1e6),totalSizeBytes:m().int().nonnegative(),sourceIds:v(ge),excludedSourceIds:v(ge),containsRawChats:x(!1),containsSecrets:x(!1),containsHiddenGraderAssets:x(!1),createdAt:It,contentHash:tt}));ht(()=>({schemaVersion:x("openpond.trainingBundleExport.v1"),manifest:ng,files:v(u({path:o().trim().min(1).max(2e3),sha256:tt,sizeBytes:m().int().nonnegative(),encoding:x("base64"),content:o()})).min(1),contentHash:tt}));ht(()=>({schemaVersion:x("openpond.trainingPreparedStart.v1"),plan:Ow,bundle:ng,approvalActor:ge.nullable(),preparedAt:It}));ht(()=>({schemaVersion:x("openpond.trainingApproval.v1"),evaluationTasksetRef:Kt.nullable().optional(),id:ge,planId:ge,bundleHash:tt,harnessRelease:se.nullable().optional(),modelImprovementQualification:se.nullable().optional(),destinationId:to,modelId:ge,method:ys,parameterization:bu,maximumCostUsd:m().nonnegative().nullable(),approvedBy:ge,approvedAt:It}));ht(()=>({schemaVersion:x("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Kt.nullable().optional(),modelProjectId:ge,sourceProjectRevision:m().int().positive(),profileId:ge,taskset:u({id:ge,revision:m().int().positive(),contentHash:tt}).strict(),tasksetRelease:se,harnessRelease:se,baseModel:Jc,method:ys})).strict();const Vz=k(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),$w=ht(()=>({schemaVersion:x("openpond.trainingJob.v1"),id:ge,planId:ge,bundleHash:tt,approvalId:ge,destinationId:to,status:Vz,nonProduction:j(),workerPid:m().int().positive().nullable(),startedAt:It.nullable(),completedAt:It.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:It,updatedAt:It,metadata:Qc})),Kz=ht(()=>({schemaVersion:x("openpond.trainingJobEvent.v1"),id:ge,jobId:ge,sequence:m().int().nonnegative(),type:k(["queued","start","progress","metric","checkpoint","cancel","complete","failure","reconcile"]),timestamp:It,payload:Qc})),Wz=ht(()=>({schemaVersion:x("openpond.sftStepMetric.v1"),step:m().int().nonnegative(),maxSteps:m().int().positive(),timestamp:It,epoch:m().nonnegative().nullable(),loss:m().nullable(),learningRate:m().nonnegative().nullable(),gradientNorm:m().nonnegative().nullable(),entropy:m().nonnegative().nullable(),meanTokenAccuracy:m().min(0).max(1).nullable(),preferenceAccuracy:m().min(0).max(1).nullable().default(null),preferenceMargin:m().nullable().default(null),chosenReward:m().nullable().default(null),rejectedReward:m().nullable().default(null),chosenLogProbability:m().nullable().default(null),rejectedLogProbability:m().nullable().default(null),reward:m().nullable().default(null),policyLoss:m().nullable().default(null),advantageLoss:m().nullable().default(null),inputTokensSeen:m().int().nonnegative().nullable(),memoryBytes:m().int().nonnegative().nullable(),elapsedSeconds:m().nonnegative().nullable()})),Gz=ht(()=>({schemaVersion:x("openpond.policyOptimizationMetric.v1"),method:k(["grpo","ppo"]),step:m().int().nonnegative(),timestamp:It,learningRate:m().nonnegative().nullable().default(null),policyLoss:m().nullable(),valueLoss:m().nullable(),gradientNorm:m().nonnegative().nullable().default(null),meanReward:m().nullable(),meanReturn:m().nullable(),kl:m().nullable(),behaviorPolicyKlPreUpdate:m().nonnegative().nullable().default(null),entropy:m().nullable(),policyClipFraction:m().min(0).max(1).nullable(),behaviorPolicyClipFractionPreUpdate:m().min(0).max(1).nullable().default(null),valueClipFraction:m().min(0).max(1).nullable(),explainedVariance:m().nullable(),rolloutLearnerLag:m().int().nonnegative().nullable(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),environmentExecutions:m().int().nonnegative(),trajectoryCount:m().int().nonnegative().nullable().default(null),costUsd:m().nonnegative().nullable()})),Zz=ht(()=>({schemaVersion:x("openpond.managedTrainingRunEvidence.v2"),provider:ge,providerRunId:ge,state:ge,progress:u({targetOptimizerSteps:m().int().nonnegative(),committedOptimizerSteps:m().int().nonnegative(),skippedOptimizerSteps:m().int().nonnegative()}),reward:u({finalMean:m().nullable(),variance:m().nonnegative().nullable(),minimum:m().nullable(),maximum:m().nullable(),distinctValueCount:m().int().nonnegative(),noSignalGroupCount:m().int().nonnegative(),trajectoryCount:m().int().nonnegative(),eligibleTrajectoryCount:m().int().nonnegative()}),usage:u({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),environmentExecutions:m().int().nonnegative()}),resource:u({provider:ge,gpuType:o().trim().min(1).max(300).nullable(),gpuCount:m().int().nonnegative().nullable(),hourlyCostUsd:m().nonnegative().nullable(),durationSeconds:m().nonnegative().nullable(),gpuSeconds:m().nonnegative().nullable()}),cost:u({totalUsd:m().nonnegative().nullable()}),checkpoint:u({id:ge,policyVersion:m().int().nonnegative(),sha256:tt.nullable(),sizeBytes:m().int().nonnegative().nullable()}).nullable(),movement:u({adapterDeltaNorm:m().nonnegative().nullable()}),evaluations:v(u({reference:u({id:ge,contentHash:tt}).nullable().optional(),kind:k(["baseline","candidate"]),policyVersion:m().int().nonnegative(),taskCount:m().int().nonnegative().nullable().optional(),targetTaskCount:m().int().nonnegative().nullable().optional(),score:m().nullable(),threshold:m().nullable(),passed:j().nullable()})),canonicalPublication:u({state:ge.nullable(),artifactId:ge.nullable()}),syncedAt:It})),gb=ht(()=>({count:m().int().nonnegative(),scoredCount:m().int().nonnegative(),meanScore:m().min(0).max(1).nullable(),passedCount:m().int().nonnegative(),passRate:m().min(0).max(1).nullable()})),vb=ht(()=>({status:k(["scored","unavailable"]),score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),failureClass:k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]).nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3),components:v(u({graderId:ge,score:m().min(0).max(1).nullable(),passed:j(),feedback:o().trim().max(2e4).nullable()})).max(1e3)})),Jz=ht(()=>({taskId:ge,input:ve(o(),ke()),baseOutput:ve(o(),ke()).nullable(),trainedOutput:ve(o(),ke()).nullable(),baseGrade:vb.nullable(),trainedGrade:vb.nullable()})),Qz=ht(()=>({schemaVersion:x("openpond.trainingEvaluationSummary.v1"),jobId:ge,tasksetId:ge,base:gb,trained:gb,meanScoreDelta:m().min(-1).max(1).nullable(),examples:v(Jz).max(1e6)}));ht(()=>({schemaVersion:x("openpond.trainingRunDetail.v1"),job:$w,events:v(Kz),stepMetrics:v(Wz),policyMetrics:v(Gz).default([]),managedEvidence:Zz.nullable().default(null),evaluation:Qz.nullable(),generatedAt:It}));const Yz=ht(()=>({schemaVersion:x("openpond.trainingArtifact.v1"),id:ge,jobId:ge,kind:k(["adapter","checkpoint","metrics","log","manifest","evaluation"]),path:o().trim().min(1).max(4e3),sha256:tt,sizeBytes:m().int().nonnegative(),baseModelId:ge.nullable(),baseModelRevision:o().trim().min(1).max(256).nullable(),tokenizerRevision:o().trim().min(1).max(256).nullable(),chatTemplateHash:tt.nullable(),nonProduction:j(),createdAt:It,metadata:Qc})),Xz=ht(()=>({schemaVersion:x("openpond.modelArtifactLineage.v1"),id:ge,modelId:ge,artifactId:ge,jobId:ge,tasksetId:ge,tasksetHash:tt,graderHash:tt,planHash:tt,bundleHash:tt,recipeHash:tt,workerVersion:o().trim().min(1).max(256),trainerVersion:o().trim().min(1).max(256),importedAt:It,frozenEvaluationArtifactId:ge.nullable(),promotable:j(),pinned:j().default(!1),status:k(["imported","rejected"]).default("imported"),rejectedAt:It.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:Pw.default(dz),managedServing:uz.nullable().default(null)})),eH=k(["chat_manual","agent","extension","authoring_optimizer"]),tH=ht(()=>({schemaVersion:x("openpond.modelBinding.v1"),id:ge,profileId:ge,role:eH,roleTargetId:ge,modelArtifactLineageId:ge,tasksetId:ge,evaluationArtifactId:ge.nullable(),status:k(["active","rolled_back"]),priorBindingId:ge.nullable(),rollbackTargetBindingId:ge.nullable(),promotedBy:ge,promotedAt:It,rolledBackAt:It.nullable(),metadata:Qc}));ht(()=>({schemaVersion:x("openpond.trainingActivity.v1"),profileId:ge,active:j(),activeCounts:u({jobs:m().int().nonnegative(),creations:m().int().nonnegative(),minerRuns:m().int().nonnegative(),datasetImports:m().int().nonnegative()}),revision:tt,generatedAt:It}));ht(()=>({schemaVersion:x("openpond.tasksetOperationalState.v1"),tasksetId:ge,attempts:v(DD),artifacts:v(LD),grades:v(HD),evaluationResults:v(P2).default([]),generatedAt:It}));const nH=ht(()=>({schemaVersion:x("openpond.trainingState.v1"),profileId:ge,sources:v(Rk),creations:v(cw),tasksetDrafts:v(Va).default([]),tasksets:v(Tc),benchmarkRuns:v(Fm()).default([]),benchmarkComparisons:v(Fm()).default([]),datasetImports:v(rL).default([]),datasetArtifacts:v(Z2).default([]),graderAuditReports:v(UD),evaluationResults:v(Fm()).default([]),candidates:v(ow),minerConfig:hu,minerRuns:v(kD).default([]),modelProjects:v(Bz).default([]),modelVersions:v(zL).default([]),modelRuns:v(YL).default([]),comparisonSeries:v(EL).default([]),comparisonSeriesEntries:v(DL).default([]),modelCurrencySnapshots:v(nz).default([]),continualBenchIssueReviews:v(sz).default([]),continualLearningDailyBatches:v(rz).default([]),rewardModelVersions:v(HL).default([]),rewardModelRuns:v(qL).default([]),modelTasksets:v(Tc).default([]),plans:v(Ow),bundles:v(ng),jobs:v($w),artifacts:v(Yz),models:v(Xz),rolloutReceipts:v(Az).default([]),modelBindings:v(tH).default([]),destinations:v(Dz),baseModelCandidates:v(zz).default([]),activityRevision:tt.optional(),generatedAt:It})),ag=32e3,aH=k(["steer","message","followup","queued","result"]),rH=k(["pending","included","resolved","cancelled","rejected"]),rg=u({id:o().min(1),sequence:m().int().nonnegative(),sessionId:o().min(1),senderSessionId:o().min(1).nullable(),senderKind:k(["user","task","runtime","ponder"]),kind:aH,body:o().trim().min(1).max(ag),payload:ve(o(),ke()).default({}),idempotencyKey:o().min(1).max(200),replyTo:o().min(1).nullable(),expectedTurnId:o().min(1).nullable(),turnId:o().min(1).nullable(),requestIds:v(o()),state:rH,revision:m().int().positive(),createdAt:o(),updatedAt:o(),error:o().nullable()}).strict();u({expectedTurnId:o().trim().min(1),idempotencyKey:o().trim().min(1).max(200),prompt:o().trim().min(1).max(ag)}).strict();st("action",[u({action:x("resume"),expectedRevision:m().int().positive()}).strict(),u({action:x("cancel"),expectedRevision:m().int().positive()}).strict(),u({action:x("edit"),expectedRevision:m().int().positive(),body:o().trim().min(1).max(ag)}).strict(),u({action:x("steer"),expectedRevision:m().int().positive(),expectedTurnId:o().trim().min(1)}).strict()]);const sH=u({id:o().min(1),sessionId:o().min(1),turnId:o().min(1),targetSessionId:o().min(1).nullable(),targetTurnId:o().min(1).nullable(),targetInputId:o().min(1).nullable().default(null),afterSequence:m().int().nonnegative(),deadline:o(),state:k(["waiting","message","completed","failed","interrupted","unavailable","timeout","cancelled"]),createdAt:o(),updatedAt:o()}).strict();u({sessionId:o(),activeTurnId:o().nullable(),acceptingInput:j(),paused:j(),inputs:v(rg),waits:v(sH)});var Ad=Ye.shape.id,oH=u({schemaVersion:x("openpond.modelBatchReviewInspection.v1"),packageHash:o().regex(/^[a-f0-9]{64}$/),definition:au,binding:Ph,evidence:v(ru).min(1).max(1e4),decisions:v(jh).min(1).max(1e4)}).strict(),cG=u({schemaVersion:x("openpond.modelBatchReviewRequest.v1"),operationId:Ad,modelId:Ad,expectedModelRevision:m().int().positive(),tasksetRef:Ye,rewardBindingRef:Ye.nullable(),definition:u({name:o().trim().min(1).max(500).optional(),instructions:o().trim().min(1).max(2e4).optional(),inputSchema:Tt.optional(),outputSchema:Tt.optional(),requiredOutputs:au.shape.requiredOutputs}).strict(),examples:v(u({evidence:Ye,input:Tt.optional(),expected:Tt.nullable().optional(),evaluatorContext:Tt.nullable().optional(),proposedTarget:Tt.nullable().optional()}).strict()).max(1e4)}).strict(),iH=u({schemaVersion:x("openpond.modelBatchReviewReceipt.v1"),operationId:Ad,modelId:Ad,source:Eh,evidence:v(ru).min(1).max(1e4),proposals:v(Fx).max(1e4)}).strict();const cH={teamInvitations:e=>L(e,"/v1/team-invitations"),decideTeamInvitation:(e,t,n)=>L(e,`/v1/team-invitations/${t}`,{method:"POST",body:JSON.stringify({token:n})}),organizations:e=>L(e,"/v1/organizations"),createOrganization:(e,t)=>L(e,"/v1/organizations",{method:"POST",body:JSON.stringify(t)}),updateOrganization:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),organizationMembers:(e,t)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/members`),upsertOrganizationMember:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify(n)}),organizationMcpServer:(e,t)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`),generateOrganizationMcpServer:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server`,{method:"POST",body:JSON.stringify(n)}),setOrganizationMcpServerStatus:(e,t,n)=>L(e,`/v1/organizations/${encodeURIComponent(t)}/mcp-server/${n}`,{method:"POST"})},lH={taskInbox:(e,t)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`),steerTurn:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/turns/steer`,{method:"POST",body:JSON.stringify(n)}),queueTaskInput:(e,t,n,a)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox`,{method:"POST",body:JSON.stringify({input:n,idempotencyKey:a})}),updateTaskInput:(e,t,n,a)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/inbox/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),sendTurn:(e,t,n)=>L(e,`/v1/sessions/${t}/turns`,{method:"POST",body:JSON.stringify(n)}),runSessionCommand:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/commands`,{method:"POST",body:JSON.stringify(n)}),recordPreflightTurnFailure:(e,t,n)=>L(e,`/v1/sessions/${t}/preflight-turns/failure`,{method:"POST",body:JSON.stringify(n)}),listCreateImproveRuns:(e,t={})=>L(e,`/v1/create-improve-runs?${dH(t).toString()}`),getCreateImproveRun:(e,t)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}`),getCreateImproveCandidateDiff:(e,t,n)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/candidates/${encodeURIComponent(n)}/diff`),applyCreateImproveAction:(e,t,n)=>L(e,`/v1/create-improve-runs/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)}),interruptTurn:(e,t,n)=>L(e,`/v1/sessions/${t}/turns/interrupt`,{method:"POST",body:JSON.stringify({reason:n})}),compactSession:(e,t,n={reason:"manual"})=>L(e,`/v1/sessions/${t}/compact`,{method:"POST",body:JSON.stringify(n)}),workspaceTool:(e,t,n)=>L(e,`/v1/sessions/${t}/workspace-tools`,{method:"POST",body:JSON.stringify(n)}),ensureCloudWorkspaceReady:(e,t,n)=>L(e,`/v1/sessions/${encodeURIComponent(t)}/workspace/ensure-ready`,{method:"POST",body:JSON.stringify(n)})};function dH(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 uH={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)),L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${a.toString()}`)},sandboxUploadFile:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files`,{method:"POST",body:JSON.stringify(n)}),preserveSandboxSource:(e,t,n={})=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/preserve-source`,{method:"POST",body:JSON.stringify(n)}),sandboxDownloadFile:async(e,t,n,a={})=>{const r=new URLSearchParams({path:n});a.offsetBytes!==void 0&&r.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&r.set("maxBytes",String(a.maxBytes));const s=await L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${r.toString()}`);return{...s,contents:s.file.isBinary?"":fC(s.file.contentsBase64)}}},mH={sandboxGitStatus:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/status`),sandboxGitDiff:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/git/diff`,{method:"POST",body:JSON.stringify(n)})},pH={connectedAppStatus:(e,t={})=>{const n=rv(t);return n.set("status",t.status??"all"),L(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=rv(t);return t.status&&n.set("status",t.status),L(e,`/v1/integrations/connections${n.size>0?`?${n.toString()}`:""}`)},sandboxIntegrationLeases:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`),attachSandboxIntegrationConnection:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"POST",body:JSON.stringify(n)}),removeSandboxIntegrationLease:(e,t,n)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}/integrations`,{method:"DELETE",body:JSON.stringify({leaseId:n})})},fH={listSandboxProjects:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return L(e,`/v1/sandbox-projects?${n.toString()}`)},getSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`)},getSandboxProjectWorkspace:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/workspace?${a.toString()}`)},upsertSandboxProject:(e,t)=>L(e,"/v1/sandbox-projects",{method:"POST",body:JSON.stringify(t)}),syncSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/sync?${a.toString()}`,{method:"POST"})},uploadSandboxProjectSource:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId}),{teamId:r,...s}=n;return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(s)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}?${a.toString()}`,{method:"DELETE"})},listSandboxAgents:(e,t)=>{const n=new URLSearchParams({teamId:t.teamId});return L(e,`/v1/sandbox-agents?${n.toString()}`)},upsertSandboxAgent:(e,t)=>L(e,"/v1/sandbox-agents",{method:"POST",body:JSON.stringify(t)}),runSandboxAgent:(e,t,n)=>L(e,`/v1/sandbox-agents/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n)}),runProfileAction:(e,t)=>L(e,"/v1/profile/run",{method:"POST",body:JSON.stringify(t)})},hH={sandbox:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},gH={...pH,...fH,...hH,...mH,...uH},vH={communities:(e,t)=>{const n=new URLSearchParams;return t&&n.set("cursor",t),L(e,`/v1/communities${n.size?`?${n}`:""}`)},communityPreview:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/preview`),communityRules:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/rules/current`),joinCommunity:(e,t,n)=>L(e,`/v1/communities/${encodeURIComponent(t)}/join`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),acceptCommunityRules:(e,t,n)=>L(e,`/v1/communities/${encodeURIComponent(t)}/rules/accept`,{method:"POST",body:JSON.stringify({acceptedRulesVersionId:n})}),leaveCommunity:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/leave`,{method:"POST",body:"{}"}),communityChannels:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels`),communityMessages:(e,t,n,a={})=>{const r=new URLSearchParams;return a.beforeSequence!=null&&r.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&r.set("limit",String(a.limit)),L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${r.size?`?${r}`:""}`)},sendCommunityMessage:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages`,{method:"POST",body:JSON.stringify(a)}),editCommunityMessage:(e,t,n,a,r)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:r})}),deleteCommunityMessage:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"DELETE",body:"{}"}),markCommunityRead:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/read`,{method:"POST",body:JSON.stringify({sequence:a})}),setCommunityChannelMuted:(e,t,n,a)=>L(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)),L(e,`/v1/communities/${encodeURIComponent(t)}/members/search${a.size?`?${a}`:""}`)},updateCommunityNotifications:(e,t,n)=>L(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)),L(e,`/v1/communities/${encodeURIComponent(t)}/events${a.size?`?${a}`:""}`)},communityRealtimeSession:(e,t)=>L(e,`/v1/communities/${encodeURIComponent(t)}/realtime-session`),uploadCommunityAttachment:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/upload`,{method:"POST",body:JSON.stringify({attachment:a})}),communityAttachmentDownload:(e,t,n,a)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/attachments/${encodeURIComponent(a)}/download`)},sg="openpond-app-server-url",Ec="openpond-app-token",bH=750;function Nw(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function lf(e){const t=e.getItem(sg)?.trim(),n=e.getItem(Ec)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Ed(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Mo(e,t){e.setItem(sg,t.serverUrl),e.setItem(Ec,t.token)}function bb(e,t){const n=lf(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(sg),e.removeItem(Ec))}function yH(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function SH(){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()||Nw();return!a||!n?null:{serverUrl:a,token:n}}function xH(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function Nl(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function kH(){const e=[],t=Ed(window.sessionStorage),n=Ed(window.localStorage),a=Nw(),r=t?.getItem(Ec)??n?.getItem(Ec);return Nl(e,null),Nl(e,a&&r?{serverUrl:a,token:r.trim()}:null),Nl(e,t?lf(t):null),Nl(e,n?lf(n):null),e}async function rp(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),bH);try{const a=await fetch(`${e}/health`,{signal:t.signal}),r=await a.json().catch(()=>null);return a.ok&&r?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function wH(){if(window.openpond)return window.openpond.getConnection();const e=Ed(window.sessionStorage),t=Ed(window.localStorage),n=SH();if(n&&await rp(n.serverUrl))return t&&Mo(t,n),e&&Mo(e,n),xH(),{...n,platform:navigator.platform};const a=yH();if(a&&await rp(a.serverUrl))return t&&Mo(t,a),e&&Mo(e,a),{...a,platform:navigator.platform};const r=kH();for(const s of r){if(await rp(s.serverUrl))return t&&Mo(t,s),e&&Mo(e,s),{...s,platform:navigator.platform};e&&bb(e,s),t&&bb(t,s)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Z={...vH,bootstrap:e=>L(e,"/v1/bootstrap?refreshCodex=1"),accountScopeSnapshot:e=>L(e,"/v1/bootstrap?ensureProfile=0"),localProjectActions:(e,t)=>L(e,`/v1/projects/${encodeURIComponent(t)}/actions`),extensionCatalog:e=>L(e,"/v1/extensions"),extensionPreview:(e,t)=>L(e,"/v1/extensions/preview",{method:"POST",body:JSON.stringify(t)}),extensionAdd:(e,t)=>L(e,"/v1/extensions",{method:"POST",body:JSON.stringify(t)}),extensionUpdate:(e,t,n={})=>L(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}/update`,{method:"POST",body:JSON.stringify(n)}),extensionUpdateAll:e=>L(e,"/v1/extensions/update-all",{method:"POST"}),extensionRemove:(e,t)=>L(e,`/v1/extensions/github/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`,{method:"DELETE"}),skillSourceFile:(e,t,n,a)=>L(e,`/v1/skills/${t}/${encodeURIComponent(n)}/source?path=${encodeURIComponent(a)}`),teamChatMembers:(e,t)=>L(e,`/v1/team-chat/members?teamId=${encodeURIComponent(t)}`),teamChatAgents:(e,t)=>L(e,`/v1/team-chat/agents?teamId=${encodeURIComponent(t)}`),teamChatThreads:(e,t)=>L(e,`/v1/team-chat/threads?teamId=${encodeURIComponent(t)}`),teamChatRealtimeSession:(e,t)=>L(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)),L(e,`/v1/team-chat/events?${a.toString()}`)},teamChatGeneral:(e,t)=>L(e,"/v1/team-chat/threads/general",{method:"POST",body:JSON.stringify({teamId:t})}),teamChatDm:(e,t,n)=>L(e,"/v1/team-chat/threads/dm",{method:"POST",body:JSON.stringify({teamId:t,otherUserId:n})}),teamChatThread:(e,t,n,a={})=>{const r=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&r.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&r.set("limit",String(a.limit)),L(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${r.toString()}`)},uploadTeamChatAttachment:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/attachments/upload`,{method:"POST",body:JSON.stringify(n)}),teamChatAttachmentDownload:(e,t,n)=>L(e,`/v1/team-chat/attachments/${encodeURIComponent(n)}/download?teamId=${encodeURIComponent(t)}`),sendTeamChatMessage:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages`,{method:"POST",body:JSON.stringify(n)}),createTeamChatAgentRun:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/agent-runs`,{method:"POST",body:JSON.stringify(n)}),teamChatAgentConversation:(e,t,n)=>L(e,`/v1/team-chat/agent-runs/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),editTeamChatMessage:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)}),deleteTeamChatMessage:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/messages/${encodeURIComponent(n)}`,{method:"DELETE",body:JSON.stringify({teamId:a})}),markTeamChatRead:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/read`,{method:"POST",body:JSON.stringify({teamId:n,sequence:a})}),setTeamChatThreadMuted:(e,t,n,a)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/mute`,{method:"POST",body:JSON.stringify({teamId:n,muted:a})}),createTeamChatAiThread:(e,t,n)=>L(e,`/v1/team-chat/threads/${encodeURIComponent(t)}/ai-threads`,{method:"POST",body:JSON.stringify(n)}),teamChatAiThread:(e,t,n)=>L(e,`/v1/team-chat/ai-threads/${encodeURIComponent(n)}?teamId=${encodeURIComponent(t)}`),sendTeamChatAiTurn:(e,t,n)=>L(e,`/v1/team-chat/ai-threads/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),executeTeamChatAiTurn:(e,t,n)=>L(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute`,{method:"POST",body:JSON.stringify({teamId:n})}),cancelTeamChatAiTurnExecution:(e,t,n)=>L(e,`/v1/team-chat/ai-turns/${encodeURIComponent(t)}/execute/cancel`,{method:"POST",body:JSON.stringify({teamId:n})}),usage:(e,t={})=>{const n=yb(t),a=n.size?`?${n.toString()}`:"";return L(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=yb(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 L(e,`/v1/usage/records${a}`)},usageTurnCache:(e,t)=>L(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 L(e,`/v1/events/page${a}`)},workOutputs:e=>L(e,"/v1/work/outputs"),harnessHistory:e=>L(e,"/v1/harness"),refinerHistory:e=>L(e,"/v1/refiner"),updateRefinerProfile:(e,t)=>L(e,"/v1/refiner/update",{method:"POST",body:JSON.stringify(t)}),activateRefinerRelease:(e,t)=>L(e,"/v1/refiner/activate",{method:"POST",body:JSON.stringify(t)}),rollbackRefinerRelease:(e,t)=>L(e,"/v1/refiner/rollback",{method:"POST",body:JSON.stringify(t)}),updateHarnessBackgroundReview:(e,t)=>L(e,"/v1/harness/background-review",{method:"POST",body:JSON.stringify(t)}),reviewHarnessEvaluation:(e,t)=>L(e,"/v1/harness/evaluation-review",{method:"POST",body:JSON.stringify(t)}),updateHarnessEvaluationReviewSchedule:(e,t)=>L(e,"/v1/harness/evaluation-review/settings",{method:"POST",body:JSON.stringify(t)}),harnessReleaseDiff:(e,t)=>L(e,"/v1/harness/diff",{method:"POST",body:JSON.stringify(t)}),rollbackHarness:(e,t)=>L(e,"/v1/harness/rollback",{method:"POST",body:JSON.stringify(t)}),reviewHarnessProposal:(e,t)=>L(e,"/v1/harness/review",{method:"POST",body:JSON.stringify(t)}),runSubagentLifecycleAction:(e,t,n)=>L(e,`/v1/subagents/${encodeURIComponent(t)}/lifecycle`,{method:"POST",body:JSON.stringify(n)}),trainingState:(e,t)=>L(e,`/v1/training?profileId=${encodeURIComponent(t)}`),trainingActivity:(e,t)=>L(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),L(e,`/v1/training/catalog${a.size?`?${a.toString()}`:""}`)},datasetCatalog:(e,t)=>L(e,`/v1/training/datasets?profileId=${encodeURIComponent(t)}`),trainingRunDetail:(e,t,n={})=>L(e,`/v1/training/jobs/${encodeURIComponent(t)}/detail?evaluation=${n.includeEvaluation===!1?"false":"true"}`),candidateReview:(e,t,n=!1,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision?refresh=${n}`),recordCandidateReview:(e,t,n,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision`,{method:"POST",body:JSON.stringify(n)}),candidateReviewHistory:(e,t,n,a="models")=>L(e,`/v1/training/${a}/${encodeURIComponent(t)}/candidate-decision-history?decisionId=${encodeURIComponent(n.id)}&decisionHash=${n.contentHash}`),trainingEvaluationTasks:async(e,t,n,a)=>{const r=new URLSearchParams({limit:"25"});return a&&r.set("cursor",a),L(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${r}`)},trainingRequest:(e,t,n,a="POST")=>L(e,`/v1/training${t}`,{method:a,body:a==="GET"||a==="DELETE"?void 0:JSON.stringify(n)}),datasetStorageState:e=>L(e,"/v1/settings/dataset-storage"),updateDatasetStorage:(e,t)=>L(e,"/v1/settings/dataset-storage",{method:"PATCH",body:JSON.stringify({datasetStorePath:t})}),hostedSavedWork:e=>L(e,"/v1/saved-work"),createHostedSavedWork:(e,t)=>L(e,"/v1/saved-work",{method:"POST",body:JSON.stringify(t)}),updateHostedSavedWork:(e,t,n)=>L(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteHostedSavedWork:(e,t)=>L(e,`/v1/saved-work/schedules/${encodeURIComponent(t)}`,{method:"DELETE"}),runHostedSavedWork:(e,t,n)=>L(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 L(e,`/v1/chat-workflows${n}`)},createChatWorkflow:(e,t)=>L(e,"/v1/chat-workflows",{method:"POST",body:JSON.stringify(t)}),updateChatWorkflow:(e,t,n)=>L(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),deleteChatWorkflow:(e,t)=>L(e,`/v1/chat-workflows/${encodeURIComponent(t)}`,{method:"DELETE"}),runChatWorkflow:(e,t)=>L(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 L(e,`/v1/local-agent-schedules${a}`)},syncLocalAgentSchedules:e=>L(e,"/v1/local-agent-schedules/sync",{method:"POST",body:JSON.stringify({})}),patchLocalAgentSchedule:(e,t,n)=>L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),runLocalAgentSchedule:(e,t,n={})=>L(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 r=a.size?`?${a.toString()}`:"";return L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${r}`)},refreshOpenPondAccounts:e=>L(e,"/v1/openpond/accounts/refresh",{method:"POST",body:JSON.stringify({})}),refreshOpenPondAccount:e=>L(e,"/v1/openpond/account?refresh=1"),loadMoreOpenPondApps:(e,t)=>L(e,`/v1/openpond/apps/more?offset=${encodeURIComponent(String(t.offset))}&limit=${encodeURIComponent(String(t.limit))}`),switchOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts/switch",{method:"POST",body:JSON.stringify(t)}),removeOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts",{method:"DELETE",body:JSON.stringify(t)}),signOutOpenPondAccount:e=>L(e,"/v1/openpond/accounts/logout",{method:"POST",body:JSON.stringify({})}),saveOpenPondAccount:(e,t)=>L(e,"/v1/openpond/accounts/login",{method:"POST",body:JSON.stringify(t)}),updateOpenPondAccountConfig:(e,t)=>L(e,"/v1/openpond/accounts/config",{method:"PATCH",body:JSON.stringify(t)}),savePreferences:(e,t)=>L(e,"/v1/preferences",{method:"PATCH",body:JSON.stringify(t)}),saveProviderSettings:(e,t)=>L(e,"/v1/providers",{method:"PATCH",body:JSON.stringify(t)}),providerSettings:e=>L(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 r=a.size?`?${a.toString()}`:"";return L(e,`/v1/providers/${encodeURIComponent(t)}/models${r}`)},refreshProviderModels:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/models`,{method:"POST",body:JSON.stringify(n)}),saveProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"PUT",body:JSON.stringify(n)}),deleteProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/credential`,{method:"DELETE",body:JSON.stringify(n)}),startOpenAiSubscriptionAuth:(e,t)=>L(e,"/v1/providers/openai/subscription-auth",{method:"POST",body:JSON.stringify(t)}),validateProviderCredential:(e,t,n)=>L(e,`/v1/providers/${encodeURIComponent(t)}/validate`,{method:"POST",body:JSON.stringify(n)}),savePersonalization:(e,t)=>L(e,"/v1/personalization",{method:"PATCH",body:JSON.stringify(t)}),recordClientDiagnostic:(e,t)=>L(e,"/v1/diagnostics/client",{method:"POST",body:JSON.stringify(t)}),profileCurrent:e=>L(e,"/v1/profile"),profileCatalog:e=>L(e,"/v1/profile/catalog"),profileWorkflows:e=>L(e,"/v1/profile/workflows"),profileEvaluations:e=>L(e,"/v1/profile/evaluations"),profileEvaluationDiscovery:(e,t,n)=>L(e,"/v1/profile/evaluations/discover",{method:"POST",body:JSON.stringify({profileRef:t}),signal:n}),profileEvaluationPrepare:(e,t)=>L(e,"/v1/profile/evaluations/prepare",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRun:(e,t)=>L(e,"/v1/profile/evaluations/run",{method:"POST",body:JSON.stringify(t)}),profileEvaluationRunSuite:(e,t)=>L(e,"/v1/profile/evaluations/run-suite",{method:"POST",body:JSON.stringify(t)}),profileEvaluationCompare:(e,t)=>L(e,"/v1/profile/evaluations/compare",{method:"POST",body:JSON.stringify({id:`comparison-${crypto.randomUUID()}`,runIds:t})}),profileEvaluationSaveReport:(e,t,n)=>L(e,"/v1/profile/evaluations/reports",{method:"POST",body:JSON.stringify({id:`report-${crypto.randomUUID()}`,evidenceKind:t,evidenceId:n})}),profileSelect:(e,t)=>L(e,"/v1/profile/select",{method:"POST",body:JSON.stringify({ref:t})}),profileRemove:(e,t)=>L(e,"/v1/profile/remove",{method:"POST",body:JSON.stringify({ref:t})}),profilePublicationPreview:(e,t)=>L(e,"/v1/profile/publication/preview",{method:"POST",body:JSON.stringify(t)}),profilePublicationPublish:(e,t)=>L(e,"/v1/profile/publication/publish",{method:"POST",body:JSON.stringify(t)}),profileInstall:(e,t)=>L(e,"/v1/profile/install",{method:"POST",body:JSON.stringify(t)}),profileUpdate:(e,t)=>L(e,"/v1/profile/update",{method:"POST",body:JSON.stringify({ref:t})}),profileInit:(e,t)=>L(e,"/v1/profile/init",{method:"POST",body:JSON.stringify(t)}),profileLoad:(e,t)=>L(e,"/v1/profile/load",{method:"POST",body:JSON.stringify(t)}),profileCheck:(e,t)=>L(e,"/v1/profile/check",{method:"POST",body:JSON.stringify(t)}),profileAgentRename:(e,t,n)=>L(e,`/v1/profile/agents/${encodeURIComponent(t)}/name`,{method:"PATCH",body:JSON.stringify(n)}),profileCommit:(e,t)=>L(e,"/v1/profile/commit",{method:"POST",body:JSON.stringify(t)}),profilePush:(e,t)=>L(e,"/v1/profile/push",{method:"POST",body:JSON.stringify(t)}),workspaceLspSettingsStatus:e=>L(e,"/v1/lsp/settings-status"),workspaceLspRuntimeStatus:e=>L(e,"/v1/lsp/status"),restartWorkspaceLsp:e=>L(e,"/v1/lsp/restart",{method:"POST"}),remoteAccess:e=>L(e,"/v1/remote-access"),enableRemoteAccess:e=>L(e,"/v1/remote-access/enable",{method:"POST"}),disableRemoteAccess:e=>L(e,"/v1/remote-access/disable",{method:"POST"}),voiceTranscriptionStatus:(e,t={})=>L(e,"/v1/audio/transcriptions/status",{signal:t.signal}),transcribeVoice:(e,t,n={})=>L(e,"/v1/audio/transcriptions",{method:"POST",body:JSON.stringify(t),signal:n.signal}),createSession:(e,t)=>L(e,"/v1/sessions",{method:"POST",body:JSON.stringify(t)}),patchSession:(e,t,n)=>L(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 r=a.size?`?${a.toString()}`:"";return L(e,`/v1/codex-history/${encodeURIComponent(t)}${r}`)},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"),L(e,`/v1/codex-history/${encodeURIComponent(t)}?${a.toString()}`)},sendCodexHistoryTurn:(e,t,n)=>L(e,`/v1/codex-history/${encodeURIComponent(t)}/turns`,{method:"POST",body:JSON.stringify(n)}),interruptCodexHistoryTurn:(e,t)=>L(e,`/v1/codex-history/${encodeURIComponent(t)}/turns/interrupt`,{method:"POST"}),patchSidebarAppPreference:(e,t,n)=>L(e,`/v1/sidebar/apps/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),reorderSidebarApps:(e,t)=>L(e,"/v1/sidebar/apps/reorder",{method:"POST",body:JSON.stringify(t)}),sidebarFiles:e=>L(e,"/v1/sidebar/files"),patchSidebarFile:(e,t)=>L(e,"/v1/sidebar/files",{method:"PATCH",body:JSON.stringify(t)}),workspaceStatus:(e,t,n=!1,a={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}${n?"?ensure=1":""}`,{signal:a.signal}),createWorkspaceBranch:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/branches`,{method:"POST",body:JSON.stringify(n)}),checkoutWorkspaceBranch:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/branch`,{method:"PATCH",body:JSON.stringify(n)}),workspaceDiff:(e,t,n={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/diff`,{signal:n.signal}),resolveWorkspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/resolve-file?path=${encodeURIComponent(n)}`),workspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`),saveWorkspaceFile:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/file`,{method:"PATCH",body:JSON.stringify(n)}),signWorkspaceImageUrl:(e,t)=>L(e,"/v1/assets/workspace-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalImageUrl:(e,t)=>L(e,"/v1/assets/local-image-url",{method:"POST",body:JSON.stringify(t)}),signLocalVideoUrl:(e,t)=>L(e,"/v1/assets/local-video-url",{method:"POST",body:JSON.stringify(t)}),signChatAttachmentImageUrl:(e,t)=>L(e,"/v1/assets/chat-attachment-image-url",{method:"POST",body:JSON.stringify(t)}),chatAttachmentFile:(e,t)=>L(e,"/v1/assets/chat-attachment-file",{method:"POST",body:JSON.stringify(t)}),workspaceLspTouch:(e,t,n,a={})=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/touch`,{method:"POST",body:JSON.stringify(n),signal:a.signal}),workspaceLspAction:(e,t,n)=>L(e,`/v1/workspaces/${encodeURIComponent(t)}/lsp/action`,{method:"POST",body:JSON.stringify(n)}),workspaceTemplateConfig:(e,t)=>L(e,`/v1/openpond/apps/${encodeURIComponent(t)}/template-config`),...cH,...gH,createLocalProject:(e,t)=>L(e,"/v1/projects",{method:"POST",body:JSON.stringify(t)}),updateLocalProjectAgentSetup:(e,t,n)=>L(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)}),uploadLocalProjectCloudSource:(e,t,n)=>L(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 r=a.toString()?`?${a.toString()}`:"";return L(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${r}`)},deleteLocalProject:(e,t)=>L(e,`/v1/projects/${encodeURIComponent(t)}`,{method:"DELETE"}),gitAvailability:e=>L(e,"/v1/system/git"),installMacOSCommandLineTools:e=>L(e,"/v1/system/git/install-command-line-tools",{method:"POST",body:JSON.stringify({})}),...lH,resolveApproval:(e,t,n)=>L(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function yb(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 IH=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_H=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),Sb=e=>{const t=_H(e);return t.charAt(0).toUpperCase()+t.slice(1)},Dw=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),CH=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var RH={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 PH=h.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:s,iconNode:i,...c},d)=>h.createElement("svg",{ref:d,...RH,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:Dw("lucide",r),...!s&&!CH(c)&&{"aria-hidden":"true"},...c},[...i.map(([l,p])=>h.createElement(l,p)),...Array.isArray(s)?s:[s]]));const We=(e,t)=>{const n=h.forwardRef(({className:a,...r},s)=>h.createElement(PH,{ref:s,iconNode:t,className:Dw(`lucide-${IH(Sb(e))}`,`lucide-${e}`,a),...r}));return n.displayName=Sb(e),n};const TH=[["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"}]],AH=We("activity",TH);const EH=[["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"}]],jH=We("archive-restore",EH);const MH=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],OH=We("arrow-left",MH);const $H=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],Lw=We("bookmark",$H);const NH=[["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"}]],zw=We("bookmark-x",NH);const DH=[["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"}]],xb=We("book-open-text",DH);const LH=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],kb=We("bot",LH);const zH=[["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"}]],Dl=We("boxes",zH);const HH=[["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"}]],Hw=We("calendar-clock",HH);const UH=[["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"}]],Uw=We("chart-column-stacked",UH);const qH=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],lr=We("check",qH);const BH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],sd=We("circle-check",BH);const FH=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ms=We("chevron-down",FH);const VH=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ps=We("chevron-right",VH);const KH=[["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"}]],jd=We("circle-alert",KH);const WH=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],yu=We("cloud",WH);const GH=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],ZH=We("credit-card",GH);const JH=[["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"}]],QH=We("download",JH);const YH=[["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"}]],sp=We("external-link",YH);const XH=[["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"}]],qw=We("file-output",XH);const eU=[["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"}]],og=We("file-text",eU);const tU=[["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"}]],Bw=We("folder",tU);const nU=[["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"}]],ig=We("folder-git-2",nU);const aU=[["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"}]],rU=We("git-branch",aU);const sU=[["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"}]],oU=We("github",sU);const iU=[["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"}]],Fw=We("earth",iU);const cU=[["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"}]],lU=We("circle-question-mark",cU);const dU=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],uU=We("list-filter",dU);const mU=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],cg=We("loader-circle",mU);const pU=[["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"}]],fU=We("maximize-2",pU);const hU=[["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"}]],Su=We("message-square",hU);const gU=[["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"}]],Xc=We("ellipsis",gU);const vU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Vw=We("panel-left",vU);const bU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],df=We("panel-right",bU);const yU=[["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"}]],lg=We("pin",yU);const SU=[["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"}]],dg=We("pin-off",SU);const xU=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],kU=We("plus",xU);const wU=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],IU=We("power",wU);const _U=[["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"}]],Kw=We("refresh-cw",_U);const CU=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],RU=We("rotate-ccw",CU);const PU=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],TU=We("search",PU);const AU=[["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"}]],Ww=We("settings",AU);const EU=[["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"}]],ug=We("shapes",EU);const jU=[["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"}]],wb=We("shield",jU);const MU=[["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"}]],xu=We("square-pen",MU);const OU=[["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"}]],Gw=We("square-terminal",OU);const $U=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],Ib=We("user-round",$U);const NU=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],el=We("x",NU);const DU=[["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"}]],mg=We("inbox",DU);const LU=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],zU=We("list",LU);const HU=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],UU=We("terminal",HU);function qU({platform:e}){return!ku()||Zw(e)?null:g.jsxs("div",{className:"window-controls","aria-label":"Window controls",children:[g.jsx("button",{type:"button",className:"window-control minimize",title:"Minimize",onClick:()=>{op("minimize")},children:g.jsx(ms,{size:14})}),g.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{op("toggleMaximize")},children:g.jsx(fU,{size:12})}),g.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{op("close")},children:g.jsx(el,{size:13})})]})}function Zw(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function ku(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function op(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 BU=[["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"}]],Jw=We("house",BU);const FU=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]],VU=We("panels-top-left",FU);function KU({value:e,options:t,disabled:n,compact:a,className:r,icon:s,placement:i="bottom",label:c,tooltip:d,searchable:l=!1,floating:p=!1,onChange:f}){const[S,b]=h.useState(!1),[I,C]=h.useState(""),P=h.useRef(null),[_,M]=h.useState();h.useLayoutEffect(()=>{if(!S||!p)return;function w(){const R=P.current?.getBoundingClientRect();if(!R)return;const O=window.innerHeight-R.bottom-12,z=R.top-12,$=O<180&&z>O;M({position:"fixed",left:Math.max(12,R.left),width:Math.min(R.width,window.innerWidth-24),minWidth:0,maxWidth:"calc(100vw - 24px)",right:"auto",top:$?"auto":R.bottom+5,bottom:$?window.innerHeight-R.top+5:"auto",maxHeight:Math.max(80,Math.min(320,$?z-5:O-5)),overflowY:"auto",zIndex:1e3})}return w(),window.addEventListener("resize",w),window.addEventListener("scroll",w,!0),()=>{window.removeEventListener("resize",w),window.removeEventListener("scroll",w,!0)}},[S,p]);const A=t.find(w=>w.value===e)??t[0],T=I.trim().toLowerCase(),y=T?t.filter(w=>[w.label,w.shortLabel,w.description].some(R=>R?.toLowerCase().includes(T))):t;return h.useEffect(()=>{if(!S){C("");return}function w(O){P.current?.contains(O.target)||b(!1)}function R(O){O.key==="Escape"&&b(!1)}return document.addEventListener("pointerdown",w),document.addEventListener("keydown",R),()=>{document.removeEventListener("pointerdown",w),document.removeEventListener("keydown",R)}},[S]),g.jsxs("div",{className:`dropdown-select ${r??""} ${a?"compact":""} ${i==="top"?"open-up":""}`,"data-tooltip":d,ref:P,children:[g.jsxs("button",{type:"button",className:`dropdown-trigger ${S?"active":""}`,disabled:n,"aria-label":c,"aria-haspopup":"menu","aria-expanded":S,onClick:()=>b(w=>!w),children:[s,g.jsx("span",{children:A?.shortLabel??A?.label??e}),g.jsx(ms,{size:14})]}),S&&g.jsxs("div",{className:"dropdown-menu",role:"menu",style:p?_:void 0,children:[l?g.jsxs("label",{className:"dropdown-search",onClick:w=>w.stopPropagation(),children:[g.jsxs("span",{className:"sr-only",children:["Search ",c]}),g.jsx("input",{autoFocus:!0,placeholder:`Search ${c.toLowerCase()}`,value:I,onChange:w=>C(w.target.value)})]}):null,y.map(w=>g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":w.value===e,disabled:w.disabled,className:[w.value===e?"selected":"",w.separatorBefore?"separator-before":"",w.icon?"with-icon":""].filter(Boolean).join(" "),onClick:()=>{w.disabled||(f(w.value),C(""),b(!1))},children:[g.jsxs("span",{children:[w.icon==="plus"?g.jsx(kU,{size:13}):null,g.jsx("span",{children:w.label})]}),w.description&&g.jsx("small",{children:w.description})]},w.value)),y.length?null:g.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const lG=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}];function Qw(e){return e==="chat"?"New chat":"New task"}const uf=["get-started","home","inbox","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],WU={"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"},GU={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},ZU={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 wa(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?wa("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 pg(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(Y=>!Y.trim()||Y.length>2e3||Y.includes("\0")))return null;const a=n[0]&&!uf.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 r=n.shift(),s=r??"models";if(!uf.includes(s)||r==="models"||a&&s==="get-started")return null;let i=s==="evaluations"?"results":"default";if(GU[s]?.includes(n[0]))i=n.shift();else if(s==="evaluations"&&n.length)return null;if(s==="experiments"&&n[0]==="history")return null;const c=n.shift()??null,d=n.shift()??null;if(n.length||d&&!c||(s==="models"||s==="get-started"||s==="home")&&c)return null;if(i==="drafts"||i==="new"){if(!c||d)return null}else if(i!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(i)){if(d)return null}else if(d&&!ZU[s]?.includes(d))return null}if(s==="serving"&&d)return null;const l=new URLSearchParams(e.search??"");if([...l.keys()].some(Y=>!["model","q","after","source","project","pass","dataset","revision","hash","sort","location","kind","review_source","review_snapshot","review_boundary","review_revision"].includes(Y))||[...l.keys()].some(Y=>l.getAll(Y).length!==1))return null;const p=["review_source","review_snapshot","review_boundary","review_revision"],f=p.some(Y=>l.has(Y));if(f&&(s!=="datasets"||c||l.get("location")==="local"||p.some(Y=>!l.get(Y))||[l.get("review_source"),l.get("review_boundary")].some(Y=>!Y.trim()||Y.length>500||Y.includes("\0"))||[l.get("review_snapshot"),l.get("review_revision")].some(Y=>!/^[a-f0-9]{64}$/.test(Y))))return null;const S=f?{id:l.get("review_source"),snapshotHash:l.get("review_snapshot"),boundaryId:l.get("review_boundary"),boundaryRevisionHash:l.get("review_revision")}:void 0,b=l.get("sort");if(b!==null&&(s!=="datasets"||!["id","name","updated"].includes(b)))return null;const I=l.has("revision")?Number(l.get("revision")):void 0,C=l.get("hash")??void 0,P=["datasets","graders"].includes(s);if((I!==void 0||C!==void 0)&&(!c||!P||!Number.isSafeInteger(I)||I<=0||!/^[a-f0-9]{64}$/.test(C??"")))return null;const _=l.get("source");if(_!==null&&(s!=="labeling"&&(s!=="evaluations"||i!=="review")||!_.trim()||_.length>500)||l.has("dataset")&&(s!=="datasets"||!c||l.get("dataset")!=="release"))return null;const M=["home","inbox","datasets","graders","experiments"].includes(s),A=s==="runs"&&!!(c?.startsWith("hosted-run:")||c?.startsWith("hosted-policy:")),T=l.get("location");if(T!==null&&(!M||!["local","hosted"].includes(T)))return null;const y=l.get("kind");if(y!==null&&(s!=="experiments"||!c||T==="local"||y!=="recorded_evidence")||t[0]==="console"&&!M)return null;const w=l.get("project")==="all"?null:l.get("project"),R=l.get("pass");if([w,R].some(Y=>Y!==null&&(!Y.trim()||Y.length>240))||!M&&!A&&(w||R)||s!=="experiments"&&R||(M||A)&&a||R&&!c)return null;const O=l.get("model");if(M&&O!==null||a&&O&&a!==O)return null;const z=a??O;if(s==="get-started"&&l.size!==0)return null;const $=l.get("q")??"",V=l.get("after");return z!==null&&(!z.trim()||z.length>500)||$.length>1e3||V!==null&&(!V.trim()||V.length>2e3)?null:wa(s,z,{...S?{reviewSource:S}:{},collection:i,resourceId:c,detailTab:d,query:$,after:V,...y?{executionKind:"recorded_evidence"}:{},...T?{executionLocation:T}:{},...b?{sort:b}:{},...I!==void 0?{revision:I,contentHash:C}:{},...l.get("dataset")==="release"?{datasetKind:"release"}:{},...t[0]==="console"?{area:"console"}:{},...M||A?{...l.has("project")?{projectId:w}:{},...l.has("pass")?{passId:R}:{}}:{},..._!==null?{sourceId:_}:{}})}function wu(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return wu(wa("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 JU(e,t){return wa(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 dG(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const Md=new Set,mf=new Set,QU=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"]),pf={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started",team:"/team",community:"/community"};let ff=!1,hf="",od=null,Yw=null,jc="",za=0,Ji=null,gc=!1,ip=null,id=!1;function fg(e){const t=pg(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&&QU.has(n[1])){const r=hg(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...r?{returnTo:r}:{}}}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(pf).find(r=>pf[r]===e.pathname);return a?{kind:"view",view:a}:null}function Xw(e){if(e.kind==="models")return wu(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=hg(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":pf[e.view]}function YU(e){const t=e?.kind==="settings"?hg(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=pg(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function hg(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=pg(t);return n?wu(n):null}function tl(){return`${window.location.pathname}${window.location.search}`}function gg(){if(typeof window>"u")return;const e=ff?jc:tl();e!==hf&&(hf=e,od=fg(new URL(e,window.location.origin)),Yw=od?.kind==="models"?od.route:null)}function eI(){hf="",gg();for(const e of mf)e()}async function vg(e){if(id)return!1;id=!0;try{for(const t of[...Md].reverse())if(!await t(e))return!1;return!0}finally{id=!1}}function bg(e){return{...window.history.state,openpondNavigationIndex:e}}async function XU(){const e=tl(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:za-1;if(Ji&&t===za){const a=Ji;Ji=null,a();return}if(ip===t||Md.size===0){ip=null,jc=e,za=t,window.history.replaceState(bg(za),"",e),eI();return}if(t===za)return;if(gc||id){Ji??=()=>{},window.history.go(za-t);return}gc=!0;const n=t-za;try{await new Promise(a=>{Ji=a,window.history.go(-n)}),await vg(e)&&(ip=t,window.history.go(n))}finally{gc=!1}}function yg(){if(ff||typeof window>"u")return;const e=fg(window.location);jc=e?Xw(e):tl(),za=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(bg(za),"",jc),window.addEventListener("popstate",XU),ff=!0}function tI(e){return mf.add(e),yg(),()=>{mf.delete(e)}}function uG(e){return Md.add(e),yg(),()=>{Md.delete(e)}}async function mG(e){!gc&&await vg(tl())&&e()}function eq(){return h.useSyncExternalStore(tI,()=>(gg(),Yw),()=>null)}function tq(){return h.useSyncExternalStore(tI,()=>(gg(),od),()=>null)}async function Lt(e,t="push"){if(typeof window>"u"||(yg(),gc))return!1;if(e.kind==="settings"&&!e.returnTo){const a=fg(window.location),r=a?.kind==="models"?wu(a.route):a?.kind==="settings"?a.returnTo:void 0;r&&(e={...e,returnTo:r})}const n=Xw(e);return tl()===n?!0:await vg(n)?(t==="push"&&za++,window.history[t==="replace"?"replaceState":"pushState"](bg(za),"",n),jc=n,eI(),!0):!1}function Fs(e,t="push"){return Lt({kind:"models",route:e},t)}function nq({experience:e="work",beginNewChat:t}){return g.jsx("div",{className:"sidebar-new-task",children:g.jsxs("button",{className:"sidebar-row sidebar-task-row sidebar-new-task-entry",type:"button",onClick:async()=>{await Lt({kind:"chat",sessionId:null})&&t(null)},children:[g.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:g.jsx(xu,{size:18})}),g.jsx("span",{children:Qw(e)})]})})}function aq({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:r,setView:s,view:i,modelProjects:c=[],modelTrainingActivityByProjectId:d={}}){const l=eq(),p=l?.modelId??null,f=l?.page??"models";function S(){n(null),a(null),r(null),t(null)}async function b(_){await Fs(wa(_,["home","inbox","datasets","graders","experiments"].includes(_)?null:p,{...e==="console"?{area:"console"}:{},...l?.projectId!==void 0?{projectId:l.projectId}:{}}))&&(S(),s("labs"))}async function I(_){await Fs(JU(l??wa(),_||null))&&(S(),s("labs"))}async function C(_){await Lt({kind:"view",view:_})&&(S(),s(_))}const P=p?d[p]??null:null;return g.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[e!=="chat"?g.jsxs(g.Fragment,{children:[["home","inbox","datasets","graders","experiments"].includes(f)?null:g.jsxs("div",{className:"sidebar-model-project-picker",children:[g.jsx("span",{className:"sidebar-nav-group-label",children:"Model"}),g.jsx(KU,{label:"Model",searchable:c.length>8,value:p??"",options:[{value:"",label:"All models"},...p&&!c.some(_=>_.id===p)?[{value:p,label:"Unavailable model",disabled:!0}]:[],...c.map(_=>({value:_.id,label:_.name}))],onChange:_=>{I(_)}})]}),uf.filter(_=>e==="console"?["home","inbox","datasets","graders","experiments"].includes(_):_!=="home"&&_!=="tasksets"&&_!=="evaluations").map(_=>{const M={"get-started":Dl,home:Jw,inbox:mg,models:AH,datasets:Dl,graders:wb,experiments:sd,tasks:Dl,tasksets:Dl,labeling:sd,rewards:wb,evaluations:sd,runs:Uw,versions:rU,serving:yu}[_];return g.jsxs("button",{className:`nav-command ${i==="labs"&&(f===_||_==="runs"&&f==="evaluations")?"active":""}`,"aria-current":i==="labs"&&(f===_||_==="runs"&&f==="evaluations")?"page":void 0,type:"button",onClick:()=>{b(_)},children:[g.jsx(M,{size:16}),g.jsx("span",{children:WU[_]}),_==="runs"&&P?g.jsx("span",{className:"sidebar-running-dot","aria-label":P.label}):null]},_)})]}):null,e==="chat"?g.jsxs(g.Fragment,{children:[g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="scheduled"?"active":""}`,"aria-label":"Workflows",type:"button",onClick:()=>{C("scheduled")},children:[g.jsx(Hw,{size:18}),g.jsx("span",{children:"Workflows"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="outputs"?"active":""}`,"aria-label":"Outputs",type:"button",onClick:()=>{C("outputs")},children:[g.jsx(qw,{size:18}),g.jsx("span",{children:"Outputs"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="apps"?"active":""}`,"aria-label":"Apps",type:"button",onClick:()=>{C("apps")},children:[g.jsx(ug,{size:18}),g.jsx("span",{children:"Apps"})]}),g.jsxs("button",{className:`nav-command nav-command-prominent ${i==="projects"?"active":""}`,"aria-label":"Projects",type:"button",onClick:()=>{C("projects")},children:[g.jsx(ig,{size:18}),g.jsx("span",{children:"Projects"})]})]}):null]})}const nI=Bm({chatMode:k(["chat","work"]).optional(),sidebarPresentation:k(["grouped","inbox"]).optional(),notificationMode:k(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:j().optional(),sidebarVisibility:Bm({showCodexChats:j(),onlyRunningTasks:j()}).optional(),scheduledWorkView:k(["calendar","list"]).optional(),editorControlsVisible:j().optional(),voiceNoticeAcknowledged:j().optional(),lessonProgress:ve(o().min(1).max(200),Bm({completed:j(),currentTime:m().finite().nonnegative(),duration:m().finite().positive(),updatedAt:m().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),gf={"openpond:last-chat-task-mode":"chatMode","openpond.sidebar.presentation.v1":"sidebarPresentation","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"},vf=new Set;let vc=null,qr=null,Ua={},Mc={},cp=!1,cd=0,ni=null,_b=0;const rq="openpond-client-choices-changed";function Sg(){vf.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event(rq))}function sq(){return ni}function oq(e){return vf.add(e),()=>{vf.delete(e)}}function pi(e){const t=h.useRef(e);t.current=e,h.useEffect(()=>oq(()=>t.current()),[])}async function Cb(e){const t=++_b,n=await L(e,"/v1/configuration");if(n.clientState?.revision===null){const r=iq();if(Object.keys(r.patch).length){n.clientState=await L(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:r.patch,importOnly:!0})});for(const s of r.keys)try{window.localStorage.removeItem(s)}catch{}}}if(t!==_b)return;const a=vc?.serverUrl!==e.serverUrl||vc?.token!==e.token||qr?.owner!==n.clientState?.owner;a&&(cd++,Ua={},Mc={},ni=null),vc=e,(a||(n.clientState?.revision??0)>=(qr?.revision??0))&&(qr=n.clientState),Sg()}async function xg(){if(cp||!vc||!qr||!Object.keys(Ua).length)return;cp=!0;const e=Ua,t=vc,n=qr.owner,a=cd;Ua={},Mc=e;try{const r=await L(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===cd&&(qr=r,ni=null)}catch(r){a===cd&&(Ua={...e,...Ua},ni=`Preference changes have not been saved. ${r instanceof Error?r.message:String(r)}`)}finally{Mc={},cp=!1,Sg(),!ni&&Object.keys(Ua).length&&xg()}}function pG(){ni=null,xg()}const no={getItem(e){const t=gf[e];if(!t)return null;const n={...qr?.value,...Mc,...Ua}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!qr)return;const n=gf[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const r=nI.parse({[n]:a});JSON.stringify({...qr.value,...Mc,...Ua}[n])!==JSON.stringify(r[n])&&(Ua={...Ua,...r},Sg(),xg())}};function iq(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(gf))try{const r=window.localStorage.getItem(n);if(r===null)continue;let s;try{s=JSON.parse(r)}catch{s=r}const i=nI.safeParse({[a]:s});i.success&&(Object.assign(e,i.data),t.push(n))}catch{}return{patch:e,keys:t}}function aI(e){return e.replace(/\s+\(default\)$/i,"").replace(/^(?:openai|anthropic|google|xai|deepseek|qwen|meta-llama)\//i,"").replace(/^gpt-/i,"GPT-")}const ld=5,Nn=15,bf=10,Rt={defaultChatProvider:Ks,subagents:TE(),codexPermissionMode:oh,codexReasoningEffort:ih,openPondCommandAccessMode:Qd,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:""}}}},fG={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},rI=[{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"}],lp=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],cq=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],lq=["openpond","codex","claude-code","grok-build","opencode",...cq],dq=new Set(lq),sI=[{value:sh,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"}],hG=[{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."}],yf=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],uq=[{value:"off",label:"Off"},...yf,{value:"max",label:"Max"}],gG=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],vG=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],bG=[{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 kg(e){return e.kind==="local"}function mq(e){return e.kind==="cloud"}function ct(e,t){return`${e}:${t}`}function oI(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),r=t.slice(n+1);return(a==="local"||a==="cloud")&&r?{kind:a,id:r}:{kind:"local",id:t}}function qs(e){return`${e.type}:${e.id}`}function Od(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function $d(e,t,n,a="before"){if(t===n)return e;const r=e.filter(i=>i!==t),s=r.indexOf(n);return s===-1?e:(r.splice(a==="after"?s+1:s,0,t),r)}function Rb(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function pq(e,t){if(!t)return e;const n=new Map(e.map(s=>[s.key,s])),a=t.map(s=>n.get(s)).filter(s=>!!s),r=new Set(a.map(s=>s.key));return[...a,...e.filter(s=>!r.has(s.key))]}function wg(e,t){return e?.statuses?.[t]??null}function iI(e,t){return e?.providers?.[t]??null}function Ig(e,t){return e?.modelCaches?.[t]??null}function fq(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:aI(e.displayName||e.id),description:t.join(" · ")||void 0}}function hq(e){return e==="openpond"?rI:e==="codex"||e==="openai"?sI:[]}function gq(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 vq(e){return xc(e)||dq.has(e)}function Sf(e,t={}){if(!e)return t.localOnly,lp;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,r=[];for(const s of Object.keys(e.statuses)){if(!xc(s)&&!["openpond","codex","openai","claude-code","grok-build","opencode","custom-openai-compatible"].includes(s)||!vq(s)||t.localOnly&&s==="openpond")continue;const i=wg(e,s);i&&(!n&&(s==="codex"&&!i.available&&!i.credential.connected||s!=="openpond"&&s!=="codex"&&!i.enabled)||a&&s!=="openpond"&&!i.enabled||a&&s==="codex"&&!i.available&&!i.credential.connected||r.push({value:s,label:s==="openpond"?"OpenPond Chat":i.displayName,description:s==="openpond"?void 0:i.available?"Connected":i.credential.connected?"Configured":i.routing.localByok?"Set up key":i.enabled?"Enabled":void 0}))}return r.length>0?r:lp}function Oc(e,t){const a=(Ig(t,e)?.models??[]).filter(c=>e!=="openpond"||c.id!==oi).map(fq),r=iI(t,e),s=[...r?.modelOverrides??[],r?.defaultModel].filter(c=>!!c?.trim()&&(e!=="openpond"||c!==oi)).map(c=>({value:c,label:aI(c)})),i=e==="openpond"&&a.length>0?[]:hq(e);return gq([...a,...s,...i])}function cI(e,t,n){if(e!=="openpond")return yf;const a=Ig(n,e)?.models.find(s=>s.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return yf;const r=new Set(a.reasoningEfforts);return uq.filter(s=>r.has(s.value))}function bq(e,t,n){const a=cI(e,t,n),r=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(s=>s.value===r)?r:a[0]?.value??"high"}function yq(e,t,n,a){return cI(e,t,a).some(r=>r.value===n)?n:bq(e,t,a)}function Sq(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const r=Ig(n,e)?.models.find(s=>s.id===a);return r?!!r.capabilities.reasoning:Oc(e,n).some(s=>s.value===a&&/\breasoning\b/i.test(s.description??""))}function Nd(e,t){const n=iI(t,e)?.defaultModel?.trim();if(n)return n;const a=wg(t,e)?.defaultModel?.trim();if(a)return a;const r=Oc(e,t)[0]?.value?.trim();return r||(e==="codex"?sh:e==="openpond"?oi:"")}function Ss(e,t,n){const a=t?.trim();if(xc(e))return a??"";if(a&&["opencode","grok-build","claude-code"].includes(e))return a;if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return sh;const r=Oc(e,n);return a&&r.some(s=>s.value===a)||a&&e!=="codex"&&r.length===0&&!n?a:Nd(e,n)}function lI(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:Ss(n,e.modelRef?.modelId,t)}}function _g(e,t,n){return Ss(e,t,n)||void 0}function Da(e,t,n){const a=_g(e,t,n);return a?{providerId:e,modelId:a}:void 0}function Pb(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function Sa(e){const t=e?.defaultChatProvider??Rt.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:Ss(t,e?.defaultChatModel),subagents:kc.parse(e?.subagents??Rt.subagents),codexPermissionMode:e?.codexPermissionMode??Rt.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Rt.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Rt.openPondCommandAccessMode,defaultBranchPrefix:dI(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Rt.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Rt.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Rt.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Rt.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Rt.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Rt.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Rt.training.defaultModelRef,creationMode:e?.training?.creationMode??Rt.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Rt.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Rt.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Rt.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Rt.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Rt.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Rt.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Rt.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Rt.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Rt.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Rt.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Rt.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Rt.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Rt.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Rt.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Rt.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Rt.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Rt.editor.languages.rust.customCommand}}}}}function dI(e){const t=e?.trim()??Rt.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(r=>r.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function yG(e,t){return e==="openpond"?"OpenPond Chat":wg(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function SG(e,t,n){if(n){const a=Oc(n,t).find(r=>r.value===e);if(a)return a.label}if(t)for(const a of Object.keys(t.statuses)){const r=Oc(a,t).find(s=>s.value===e);if(r)return r.label}return[...rI,...sI].find(a=>a.value===e)?.label??e}function xq(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function kq(e){return e.experience==="chat"?"Chat":"Work"}const Cg="taskDraft";function uI(e){if(e?.experience!=="work")return null;const t=e.metadata?.[Cg];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function $c(e){return uI(e)!==null}function wq(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function dp(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[Cg]:a}}function Iq(e){const t={...e??{}};return delete t[Cg],t}function Vo(e){const t=Ll(e.metadata?.trainingTasksetId)??Ll(e.metadata?.tasksetId);return t?{id:t,name:Ll(e.metadata?.trainingTasksetName)??Ll(e.metadata?.tasksetName)??_q(t)}:null}function _q(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 Ll(e){return typeof e=="string"&&e.trim()?e.trim():null}const Cq="codex_history_";function Gt(e){return!!e?.startsWith(Cq)}function mI(e){const t=[],n=new Set;for(const a of e)for(const r of[a.workspacePath,a.path]){const s=Iu(r);if(!s)continue;const i=`${a.id}:${s}`;n.has(i)||(n.add(i),t.push({projectId:a.id,path:s}))}return t.sort((a,r)=>r.path.length-a.path.length)}function Rq(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 s=pI(e.cwd,n);if(s)return s}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!fI(e))return null;const r=Iu(e.cwd);if(!r)return null;for(const s of n)if(Rg(r,s.path))return s.projectId;return null}function Tb(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return ct("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return ct("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const s=pI(e.cwd,n);if(s)return ct("local",s)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return ct("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!fI(e))return null;const r=Iu(e.cwd);if(!r)return null;for(const s of n)if(Rg(r,s.path))return ct("local",s.projectId);return null}function pI(e,t){const n=Iu(e);if(!n)return null;for(const a of t)if(Rg(n,a.path))return a.projectId;return null}function fI(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Gt(e.id)}function Iu(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 Rg(e,t){const n=Ab(e),a=Ab(t);return n===a||n.startsWith(`${a}/`)}function Ab(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const Eb=[{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"}],Pq=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function up(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(r=>!Vo(r)));else if(e.filter==="all")t.push(...e.activeSessions.filter(r=>!Vo(r)),...e.doneSessions.filter(r=>!Vo(r)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(r=>jb(r,e.selectedTasksetId)),...e.doneSessions.filter(r=>jb(r,e.selectedTasksetId)));else for(const r of e.activeSessions)Vo(r)||(e.filter==="active"?r.savedForLater||t.push(r):e.filter==="in_progress"?!r.savedForLater&&e.inProgressSessionIds.has(r.id)&&t.push(r):e.filter==="pinned"?r.pinned&&!r.savedForLater&&t.push(r):e.filter==="saved_for_later"&&r.savedForLater&&t.push(r));const n=t.filter(r=>dd(r,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((r,s)=>[r,s])):null;return e.sort==="recent"?n.sort((r,s)=>$b(r,s,a)):n.sort((r,s)=>{const i=a?.get(r.id),c=a?.get(s.id);if(i!==void 0||c!==void 0){if(i===void 0)return 1;if(c===void 0)return-1;if(i!==c)return i-c}return r.order!==s.order?r.order-s.order:$b(r,s)})}function dd(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Gt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function jb(e,t){const n=Vo(e);return!!(n&&(!t||n.id===t))}function Mb(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 Ob(e,t,n){const a=new Set(t);let r=0;return e.map(s=>{if(!a.has(s))return s;const i=n[r];return r+=1,i??s})}function $b(e,t,n=null){const a=Ko(e),r=Ko(t);if(a!==r)return a?-1:1;if(a&&r){const i=n?.get(e.id),c=n?.get(t.id);if(i!==void 0||c!==void 0){if(i===void 0)return 1;if(c===void 0)return-1;if(i!==c)return i-c}if(e.order!==t.order)return e.order-t.order}const s=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return s!==0?s:e.title.localeCompare(t.title)}function Ko(e){return e.pinned&&!e.savedForLater&&!e.archived}const zl={showCodexChats:!0,onlyRunningTasks:!1},hI="openpond.sidebar-task-visibility.v1";function Nb(e=gI()){try{const t=e?.getItem(hI);if(!t)return zl;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:zl.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:zl.onlyRunningTasks}}catch{return zl}}function Db(e,t=gI()){try{t?.setItem(hI,JSON.stringify(e))}catch{}}function gI(){return typeof window>"u"?null:no}function vI(e){return`${e.kind}:${e.id}`}function Nc(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function Tq(e){return{kind:"session",id:e}}function Aq(e){return{kind:"project",id:e}}function Eq(e){return{kind:"draft",id:e}}function jq(e){return e.selectedSessionId?Tq(e.selectedSessionId):e.selectedProjectId?Aq(e.selectedProjectId):Eq(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function Mq(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Nc(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Nc(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function xG(e,t){return e.filter(n=>Nc(n.scope,t))}function kG(e,t){return!!(e&&Nc(e.scope,t))}function Oq(e){const t={};for(const n of e){const a=vI(n.scope),r=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};r.tabCount+=1,n.commandStatus==="running"&&(r.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(r.failedCount+=1),n.lastExitCode!==null&&(r.lastExitCode=n.lastExitCode),r.status=Nq(r.status,n.status,n.commandStatus),t[a]=r}return t}function $q(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 Nq(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 bI(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"],r=Lq(e),s=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return r?a.push(r):s?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(ss("ahead",e.ahead)),e.behind>0&&a.push(ss("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(ss("ahead",e.ahead)),e.behind>0&&a.push(ss("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 yI(e,t,n,a={}){const r=e?.linkedSandboxProject??null;if(!r?.projectId&&!t)return"upload required";if(r?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const s=r?.defaultBranch??t?.defaultBranch??"main",i=r?.manifestHash??null,c=e?.sandboxTemplate?.manifestHash??null,d=r?.syncedAt??t?.syncedAt??null,l=!!(i&&c&&i!==c),p=!!(r?.projectId&&n?.headCommit&&!r.lastUploadedCommit),f=zq(n);return f?`${s} / ${f}`:p?`${s} / upload required`:`${s} / ${l||!d?"needs sync":"setup ready"}`}function Dq(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=[],r=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"),r>0&&a.push(SI(r)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&r===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 Lq(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?ss("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?ss("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function zq(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?ss("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?ss("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function ss(e,t){return`${e} by ${SI(t)}`}function SI(e){return`${e} commit${e===1?"":"s"}`}function Hq({size:e=14,className:t}){return g.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:[g.jsx("path",{d:"M12 13v8"}),g.jsx("path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"}),g.jsx("path",{d:"m8 17 4-4 4 4"})]})}function xI({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:r=15}){const s=e==="cloud"?"cloud":n?"folder-open":"folder";return g.jsx("span",{className:["project-kind-icon",e,t?"linked-cloud":"",a??""].filter(Boolean).join(" "),"aria-hidden":"true",children:g.jsxs("svg",{className:`lucide lucide-${s} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:r,height:r,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?g.jsx(Bq,{}):n?g.jsx(qq,{}):g.jsx(Uq,{}),t&&e==="local"?g.jsx(Fq,{}):null]})})}function Uq(){return g.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 qq(){return g.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 Bq(){return g.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 Fq(){return g.jsxs("g",{className:"project-kind-icon-cloud-badge",children:[g.jsx("circle",{cx:"18",cy:"17",r:"5"}),g.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 Dd=g_();function Vq({title:e,pinned:t,savedForLater:n,archived:a,onRename:r,onTogglePin:s,onToggleSaveForLater:i,onDockRight:c,onArchive:d}){const l=h.useRef(null),p=h.useRef(null),[f,S]=h.useState(null),b=[...r?[{label:"Rename",Icon:xu,action:r}]:[],{label:t?"Unpin":"Pin",Icon:t?dg:lg,action:s},...i?[{label:n?"Return to active":"Save for later",Icon:n?zw:Lw,action:i}]:[],...c?[{label:"Open in right panel",Icon:df,action:c}]:[],{label:a?"Reopen":"Mark done",Icon:a?jH:lr,action:d}];function I(C=!1){S(null),C&&l.current?.focus()}return h.useEffect(()=>{if(!f)return;p.current?.querySelector("button")?.focus();const C=_=>{!p.current?.contains(_.target)&&!l.current?.contains(_.target)&&S(null)},P=()=>S(null);return document.addEventListener("pointerdown",C),window.addEventListener("resize",P),()=>{document.removeEventListener("pointerdown",C),window.removeEventListener("resize",P)}},[f]),g.jsxs(g.Fragment,{children:[g.jsx("div",{className:`sidebar-row-actions sidebar-task-menu-trigger${f?" is-open":""}`,children:g.jsx("button",{ref:l,type:"button",className:"sidebar-row-action","aria-label":`More actions for task ${e}`,"aria-haspopup":"menu","aria-expanded":!!f,draggable:!1,onDoubleClick:C=>C.stopPropagation(),onClick:C=>{if(C.stopPropagation(),f){I(!0);return}const P=C.currentTarget.getBoundingClientRect();S({left:Math.max(8,Math.min(P.right-192,window.innerWidth-200)),top:Math.max(8,Math.min(P.bottom+4,window.innerHeight-(b.length*32+17)))})},children:g.jsx(Xc,{size:16})})}),f&&Dd.createPortal(g.jsx("div",{ref:p,role:"menu","aria-label":`Actions for ${e}`,className:"sidebar-task-menu",style:f,onClick:C=>C.stopPropagation(),onDoubleClick:C=>C.stopPropagation(),onBlur:C=>{C.currentTarget.contains(C.relatedTarget)||I()},onKeyDown:C=>{C.stopPropagation();const P=Array.from(C.currentTarget.querySelectorAll("button")),_=P.indexOf(document.activeElement);if(C.key==="Escape"&&(C.preventDefault(),I(!0)),["ArrowDown","ArrowUp","Home","End"].includes(C.key)){C.preventDefault();const M=C.key==="Home"?0:C.key==="End"?P.length-1:(_+(C.key==="ArrowDown"?1:-1)+P.length)%P.length;P[M]?.focus()}},children:b.map(({label:C,Icon:P,action:_},M)=>g.jsxs("button",{type:"button",role:"menuitem",className:M===b.length-1?"task-menu-done":void 0,onClick:()=>{I(!0),_()},children:[g.jsx(P,{size:15}),C]},C))}),document.body)]})}function Kq({session:e,onSave:t,onClose:n}){const[a,r]=h.useState(e.title),s=h.useRef(null);h.useEffect(()=>{const d=s.current;d&&(d.focus(),d.select())},[]),h.useEffect(()=>{function d(l){l.key==="Escape"&&n()}return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[n]);function i(){const d=a.trim();d&&(t(d),n())}function c(d){d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),i())}return g.jsx("div",{className:"git-dialog-backdrop rename-chat-backdrop",role:"presentation",onMouseDown:n,children:g.jsxs("section",{className:"git-dialog rename-chat-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"rename-chat-title",onMouseDown:d=>d.stopPropagation(),children:[g.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),g.jsx("textarea",{ref:s,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:d=>r(d.target.value),onKeyDown:c,"aria-label":"Chat title"}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:n,children:"Cancel"}),g.jsx("button",{type:"button",className:"git-dialog-primary",autoFocus:!0,onClick:i,disabled:!a.trim(),children:"Save"})]})]})})}const Wq=24;function Gq({title:e}){const t=h.useRef(e),[n,a]=h.useState(e);return h.useEffect(()=>{const r=t.current;if(t.current=e,!e){a("");return}if(r||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const s=Array.from(e);let i=0;a("");const c=window.setInterval(()=>{i+=1,a(s.slice(0,i).join("")),i>=s.length&&window.clearInterval(c)},Wq);return()=>window.clearInterval(c)},[e]),g.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const Zq="/";function ea(e){return`${Zq}${e.replace(/^\.?\//,"")}`}const Pg=ea("openpond-icon.png"),Jq=ea("openpond-wordlogo-white.png"),wG=ea("tutorials/what-is-an-openpond-agent-poster.png"),IG=ea("tutorials/what-is-an-openpond-agent.vtt"),_G=ea("tutorials/how-to-make-an-agent-poster.png"),CG=ea("tutorials/how-to-make-an-agent.vtt");function RG(e){return ea(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function PG(e){return ea(`tutorials/how-to-make-an-agent-${e}.vtt`)}const Lb={github:ea("connected-apps/github.svg"),google:ea("connected-apps/google.svg"),microsoft_teams:ea("connected-apps/microsoft.svg"),mcp:ea("connected-apps/openpond-mcp.svg"),slack:ea("connected-apps/slack.svg"),x:ea("connected-apps/x.svg")};function TG(e){return Lb[e]??Lb.mcp}const Qq={codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode","grok-build":"Grok Build"};function Yq({session:e}){const t=Qq[e.provider],n=t??(xc(e.provider)?typeof e.metadata?.acpAgentName=="string"?e.metadata.acpAgentName:"ACP agent":e.provider==="openpond"?"OpenPond":e.provider);return g.jsx("span",{className:"conversation-source-icon",role:"img","aria-label":n,title:n,children:t?g.jsx("img",{src:`/agent-sources/${e.provider}.svg`,alt:""}):e.provider==="openpond"?g.jsx("img",{src:Pg,alt:""}):xc(e.provider)?g.jsx(kb,{size:15,"aria-hidden":"true"}):e.metadata?.nativeSource?g.jsx(UU,{size:15,"aria-hidden":"true"}):e.provider==="openai"?g.jsx(kb,{size:15,"aria-hidden":"true"}):g.jsx(Su,{size:15,"aria-hidden":"true"})})}var ud={exports:{}},Xq=ud.exports,zb;function e4(){return zb||(zb=1,(function(e,t){(function(n,a){e.exports=a()})(Xq,(function(){var n=1e3,a=6e4,r=36e5,s="millisecond",i="second",c="minute",d="hour",l="day",p="week",f="month",S="quarter",b="year",I="date",C="Invalid Date",P=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,_=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(ee){var H=["th","st","nd","rd"],F=ee%100;return"["+ee+(H[(F-20)%10]||H[F]||H[0])+"]"}},A=function(ee,H,F){var J=String(ee);return!J||J.length>=H?ee:""+Array(H+1-J.length).join(F)+ee},T={s:A,z:function(ee){var H=-ee.utcOffset(),F=Math.abs(H),J=Math.floor(F/60),K=F%60;return(H<=0?"+":"-")+A(J,2,"0")+":"+A(K,2,"0")},m:function ee(H,F){if(H.date()<F.date())return-ee(F,H);var J=12*(F.year()-H.year())+(F.month()-H.month()),K=H.clone().add(J,f),B=F-K<0,ne=H.clone().add(J+(B?-1:1),f);return+(-(J+(F-K)/(B?K-ne:ne-K))||0)},a:function(ee){return ee<0?Math.ceil(ee)||0:Math.floor(ee)},p:function(ee){return{M:f,y:b,w:p,d:l,D:I,h:d,m:c,s:i,ms:s,Q:S}[ee]||String(ee||"").toLowerCase().replace(/s$/,"")},u:function(ee){return ee===void 0}},y="en",w={};w[y]=M;var R="$isDayjsObject",O=function(ee){return ee instanceof Y||!(!ee||!ee[R])},z=function ee(H,F,J){var K;if(!H)return y;if(typeof H=="string"){var B=H.toLowerCase();w[B]&&(K=B),F&&(w[B]=F,K=B);var ne=H.split("-");if(!K&&ne.length>1)return ee(ne[0])}else{var G=H.name;w[G]=H,K=G}return!J&&K&&(y=K),K||!J&&y},$=function(ee,H){if(O(ee))return ee.clone();var F=typeof H=="object"?H:{};return F.date=ee,F.args=arguments,new Y(F)},V=T;V.l=z,V.i=O,V.w=function(ee,H){return $(ee,{locale:H.$L,utc:H.$u,x:H.$x,$offset:H.$offset})};var Y=(function(){function ee(F){this.$L=z(F.locale,null,!0),this.parse(F),this.$x=this.$x||F.x||{},this[R]=!0}var H=ee.prototype;return H.parse=function(F){this.$d=(function(J){var K=J.date,B=J.utc;if(K===null)return new Date(NaN);if(V.u(K))return new Date;if(K instanceof Date)return new Date(K);if(typeof K=="string"&&!/Z$/i.test(K)){var ne=K.match(P);if(ne){var G=ne[2]-1||0,te=(ne[7]||"0").substring(0,3);return B?new Date(Date.UTC(ne[1],G,ne[3]||1,ne[4]||0,ne[5]||0,ne[6]||0,te)):new Date(ne[1],G,ne[3]||1,ne[4]||0,ne[5]||0,ne[6]||0,te)}}return new Date(K)})(F),this.init()},H.init=function(){var F=this.$d;this.$y=F.getFullYear(),this.$M=F.getMonth(),this.$D=F.getDate(),this.$W=F.getDay(),this.$H=F.getHours(),this.$m=F.getMinutes(),this.$s=F.getSeconds(),this.$ms=F.getMilliseconds()},H.$utils=function(){return V},H.isValid=function(){return this.$d.toString()!==C},H.isSame=function(F,J){var K=$(F);return this.startOf(J)<=K&&K<=this.endOf(J)},H.isAfter=function(F,J){return $(F)<this.startOf(J)},H.isBefore=function(F,J){return this.endOf(J)<$(F)},H.$g=function(F,J,K){return V.u(F)?this[J]:this.set(K,F)},H.unix=function(){return Math.floor(this.valueOf()/1e3)},H.valueOf=function(){return this.$d.getTime()},H.startOf=function(F,J){var K=this,B=!!V.u(J)||J,ne=V.p(F),G=function(je,De){var He=V.w(K.$u?Date.UTC(K.$y,De,je):new Date(K.$y,De,je),K);return B?He:He.endOf(l)},te=function(je,De){return V.w(K.toDate()[je].apply(K.toDate("s"),(B?[0,0,0,0]:[23,59,59,999]).slice(De)),K)},oe=this.$W,be=this.$M,me=this.$D,Re="set"+(this.$u?"UTC":"");switch(ne){case b:return B?G(1,0):G(31,11);case f:return B?G(1,be):G(0,be+1);case p:var Q=this.$locale().weekStart||0,xe=(oe<Q?oe+7:oe)-Q;return G(B?me-xe:me+(6-xe),be);case l:case I:return te(Re+"Hours",0);case d:return te(Re+"Minutes",1);case c:return te(Re+"Seconds",2);case i:return te(Re+"Milliseconds",3);default:return this.clone()}},H.endOf=function(F){return this.startOf(F,!1)},H.$set=function(F,J){var K,B=V.p(F),ne="set"+(this.$u?"UTC":""),G=(K={},K[l]=ne+"Date",K[I]=ne+"Date",K[f]=ne+"Month",K[b]=ne+"FullYear",K[d]=ne+"Hours",K[c]=ne+"Minutes",K[i]=ne+"Seconds",K[s]=ne+"Milliseconds",K)[B],te=B===l?this.$D+(J-this.$W):J;if(B===f||B===b){var oe=this.clone().set(I,1);oe.$d[G](te),oe.init(),this.$d=oe.set(I,Math.min(this.$D,oe.daysInMonth())).$d}else G&&this.$d[G](te);return this.init(),this},H.set=function(F,J){return this.clone().$set(F,J)},H.get=function(F){return this[V.p(F)]()},H.add=function(F,J){var K,B=this;F=Number(F);var ne=V.p(J),G=function(be){var me=$(B);return V.w(me.date(me.date()+Math.round(be*F)),B)};if(ne===f)return this.set(f,this.$M+F);if(ne===b)return this.set(b,this.$y+F);if(ne===l)return G(1);if(ne===p)return G(7);var te=(K={},K[c]=a,K[d]=r,K[i]=n,K)[ne]||1,oe=this.$d.getTime()+F*te;return V.w(oe,this)},H.subtract=function(F,J){return this.add(-1*F,J)},H.format=function(F){var J=this,K=this.$locale();if(!this.isValid())return K.invalidDate||C;var B=F||"YYYY-MM-DDTHH:mm:ssZ",ne=V.z(this),G=this.$H,te=this.$m,oe=this.$M,be=K.weekdays,me=K.months,Re=K.meridiem,Q=function(De,He,Ie,Me){return De&&(De[He]||De(J,B))||Ie[He].slice(0,Me)},xe=function(De){return V.s(G%12||12,De,"0")},je=Re||function(De,He,Ie){var Me=De<12?"AM":"PM";return Ie?Me.toLowerCase():Me};return B.replace(_,(function(De,He){return He||(function(Ie){switch(Ie){case"YY":return String(J.$y).slice(-2);case"YYYY":return V.s(J.$y,4,"0");case"M":return oe+1;case"MM":return V.s(oe+1,2,"0");case"MMM":return Q(K.monthsShort,oe,me,3);case"MMMM":return Q(me,oe);case"D":return J.$D;case"DD":return V.s(J.$D,2,"0");case"d":return String(J.$W);case"dd":return Q(K.weekdaysMin,J.$W,be,2);case"ddd":return Q(K.weekdaysShort,J.$W,be,3);case"dddd":return be[J.$W];case"H":return String(G);case"HH":return V.s(G,2,"0");case"h":return xe(1);case"hh":return xe(2);case"a":return je(G,te,!0);case"A":return je(G,te,!1);case"m":return String(te);case"mm":return V.s(te,2,"0");case"s":return String(J.$s);case"ss":return V.s(J.$s,2,"0");case"SSS":return V.s(J.$ms,3,"0");case"Z":return ne}return null})(De)||ne.replace(":","")}))},H.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},H.diff=function(F,J,K){var B,ne=this,G=V.p(J),te=$(F),oe=(te.utcOffset()-this.utcOffset())*a,be=this-te,me=function(){return V.m(ne,te)};switch(G){case b:B=me()/12;break;case f:B=me();break;case S:B=me()/3;break;case p:B=(be-oe)/6048e5;break;case l:B=(be-oe)/864e5;break;case d:B=be/r;break;case c:B=be/a;break;case i:B=be/n;break;default:B=be}return K?B:V.a(B)},H.daysInMonth=function(){return this.endOf(f).$D},H.$locale=function(){return w[this.$L]},H.locale=function(F,J){if(!F)return this.$L;var K=this.clone(),B=z(F,J,!0);return B&&(K.$L=B),K},H.clone=function(){return V.w(this.$d,this)},H.toDate=function(){return new Date(this.valueOf())},H.toJSON=function(){return this.isValid()?this.toISOString():null},H.toISOString=function(){return this.$d.toISOString()},H.toString=function(){return this.$d.toUTCString()},ee})(),re=Y.prototype;return $.prototype=re,[["$ms",s],["$s",i],["$m",c],["$H",d],["$W",l],["$M",f],["$y",b],["$D",I]].forEach((function(ee){re[ee[1]]=function(H){return this.$g(H,ee[0],ee[1])}})),$.extend=function(ee,H){return ee.$i||(ee(H,Y,$),ee.$i=!0),$},$.locale=z,$.isDayjs=O,$.unix=function(ee){return $(1e3*ee)},$.en=w[y],$.Ls=w,$.p={},$}))})(ud)),ud.exports}var t4=e4();const kI=p0(t4);var md={exports:{}},n4=md.exports,Hb;function a4(){return Hb||(Hb=1,(function(e,t){(function(n,a){e.exports=a()})(n4,(function(){return function(n,a,r){n=n||{};var s=a.prototype,i={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function c(l,p,f,S){return s.fromToBase(l,p,f,S)}r.en.relativeTime=i,s.fromToBase=function(l,p,f,S,b){for(var I,C,P,_=f.$locale().relativeTime||i,M=n.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],A=M.length,T=0;T<A;T+=1){var y=M[T];y.d&&(I=S?r(l).diff(f,y.d,!0):f.diff(l,y.d,!0));var w=(n.rounding||Math.round)(Math.abs(I));if(P=I>0,w<=y.r||!y.r){w<=1&&T>0&&(y=M[T-1]);var R=_[y.l];b&&(w=b(""+w)),C=typeof R=="string"?R.replace("%d",w):R(w,p,y.l,P);break}}if(p)return C;var O=P?_.future:_.past;return typeof O=="function"?O(C):O.replace("%s",C)},s.to=function(l,p){return c(l,p,this,!0)},s.from=function(l,p){return c(l,p,this)};var d=function(l){return l.$u?r.utc():r()};s.toNow=function(l){return this.to(d(this),l)},s.fromNow=function(l){return this.from(d(this),l)}}}))})(md)),md.exports}var r4=a4();const s4=p0(r4);kI.extend(s4);let xf=Date.now(),Hl;const Ul=new Set,Ub=()=>xf;function o4(e){return Ul.add(e),Hl||(xf=Date.now(),Hl=setInterval(()=>{xf=Date.now();for(const t of Ul)t()},3e4)),()=>{Ul.delete(e),Ul.size===0&&(clearInterval(Hl),Hl=void 0)}}function wI({value:e,className:t}){const n=h.useSyncExternalStore(o4,Ub,Ub),a=e==null?null:kI(e);return a?.isValid()?g.jsx("time",{className:t,dateTime:a.toISOString(),title:`Last activity ${a.format("MMM D, YYYY h:mm A")}`,children:a.from(n)}):null}const i4=2650,c4=304,l4=260;function d4(){return{animationDelay:`${-(Date.now()%i4)}ms`}}function u4(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),r=a>2;t.dataset.overflowing=String(r),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 mp({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:r,children:s,collapsed:i=!1,titleActive:c=!1,onTitleClick:d,onToggleCollapsed:l}){return g.jsxs("section",{className:["sidebar-section",a,n?"actions-visible":""].filter(Boolean).join(" "),children:[g.jsxs("div",{className:"section-header",children:[g.jsxs("div",{className:"section-title-row",children:[d?g.jsxs("div",{className:"section-title-combo",children:[g.jsx("button",{type:"button",className:`section-title-link${c?" active":""}`,onClick:d,children:g.jsx("span",{children:e})}),l&&g.jsx("button",{type:"button",className:"section-chevron-button","aria-label":`${i?"Expand":"Collapse"} ${e}`,"aria-expanded":!i,onClick:l,children:i?g.jsx(ps,{size:13}):g.jsx(ms,{size:13})})]}):l?g.jsxs("button",{type:"button",className:"section-title-button","aria-label":`${i?"Expand":"Collapse"} ${e}`,"aria-expanded":!i,onClick:l,children:[g.jsx("span",{children:e}),i?g.jsx(ps,{size:13}):g.jsx(ms,{size:13})]}):g.jsx("span",{children:e}),r]}),t&&g.jsx("div",{className:"section-actions",children:t})]}),!i&&g.jsx("div",{className:"sidebar-section-body",children:s})]})}function qb({children:e,expanded:t=!1,onClick:n}){return g.jsx("button",{type:"button",className:"sidebar-show-more",onClick:n,children:e??(t?"Show less":"Show more")})}function Bb({session:e,selected:t,icon:n,archived:a=!1,nested:r=!1,dragging:s,placeholder:i,running:c,goalRuntime:d,subagentRuntime:l,terminalIndicator:p,projectLabel:f,inbox:S=!1,activityAt:b,ariaDescribedBy:I,childSessionCount:C=0,childSessionsExpanded:P=!1,onSelect:_,onToggleChildSessions:M,onTogglePin:A,onToggleSaveForLater:T,onDockRight:y,onArchive:w,onDragStart:R,onDragEnd:O,onDragOver:z,onDrop:$,onRename:V}){const[Y,re]=h.useState(!1),ee=d?.status==="queued",H=d?.tone==="active"&&!ee,F=(l?.activeCount??0)>0,J=C>0&&!!M,K=F||H||!ee&&(c??e.status==="active"),B=F&&l?l.label:H&&d?p4(d):"Running",ne=["sidebar-task-row",$c(e)?"is-draft":"",K?"has-running-dot":"",S?"sidebar-inbox-row":""].filter(Boolean).join(" "),G=h.useMemo(d4,[]),te=g.jsx(Vq,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:V?()=>re(!0):void 0,onTogglePin:A,onToggleSaveForLater:T,onDockRight:y,onArchive:w}),oe=g.jsxs(Tg,{selected:t,dataSessionId:e.id,dragging:s,nested:r,placeholder:i,className:ne||void 0,ariaExpanded:J?P:void 0,ariaDescribedBy:I,onSelect:_,onDragStart:R,onDragEnd:O,onDragOver:z,onDrop:$,onDoubleClick:V?()=>re(!0):void 0,children:[g.jsx("span",{className:"sidebar-source-slot",children:n??g.jsx(Yq,{session:e})}),g.jsxs("span",{className:"sidebar-title-slot",children:[J?g.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:me=>{me.stopPropagation(),M?.()},children:P?g.jsx(ms,{size:13}):g.jsx(ps,{size:13})}):null,g.jsxs("span",{className:"row-label-shell",title:e.title,children:[g.jsx("span",{className:"sidebar-session-title-line",children:g.jsx("span",{className:"row-label sidebar-task-title","data-overflowing":"false",onPointerEnter:u4,children:g.jsx(Gq,{title:e.title})})}),S?g.jsxs("span",{className:"sidebar-inbox-project",children:[f?g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"sidebar-inbox-project-name",children:f}),g.jsx("span",{"aria-hidden":"true",children:"|"})]}):null,g.jsx(wI,{value:b??e.createdAt})]}):null]})]}),g.jsxs("div",{className:"row-meta",children:[g.jsxs("span",{className:"row-meta-status",children:[p?g.jsx(II,{indicator:p}):null,K?g.jsx("span",{className:`sidebar-running-dot${F?" subagent":H?" goal":""}`,style:G,"aria-label":B}):null]}),te,S?g.jsx("button",{type:"button",className:"sidebar-inbox-done","aria-label":`${a?"Reopen":"Mark done"}: ${e.title}`,title:a?"Reopen":"Mark done (does not stop running work)",onClick:me=>{me.stopPropagation(),w()},children:a?g.jsx(RU,{size:19}):g.jsx(lr,{size:21})}):null]})]}),be=Y&&V?g.jsx(Kq,{session:e,onSave:me=>V(e,me),onClose:()=>re(!1)}):null;return g.jsxs(g.Fragment,{children:[oe,be]})}function m4({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:r,onToggleSaveForLater:s,onDragStart:i,onDragEnd:c,onDragOver:d,onDrop:l}){const p=e.path.split("/").at(-1)??e.path,f=`${e.workspaceName} · ${e.path}`;return g.jsxs(Tg,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:i,onDragEnd:c,onDragOver:d,onDrop:l,children:[e.available?g.jsx(og,{size:15}):g.jsx(jd,{size:15}),g.jsx("span",{className:"row-label-shell",title:f,children:g.jsx("span",{className:"row-label",children:p})}),g.jsx("div",{className:"row-meta",children:g.jsxs("div",{className:"sidebar-row-actions",children:[g.jsx(Ld,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:r,children:e.status==="pinned"?g.jsx(dg,{size:13}):g.jsx(lg,{size:13})}),g.jsx(Ld,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:s,children:e.status==="saved_for_later"?g.jsx(zw,{size:13}):g.jsx(Lw,{size:13})})]})})]})}function p4(e){return e.actionLabel}function f4({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:r=!1,disclosure:s=!0,workspaceState:i,cloudLinkTrusted:c=!0,cloudLinkWarning:d=null,placeholder:l,terminalIndicator:p,onSelect:f,onNewChat:S,onMoveToCloud:b,onWorkspaceTargetSelect:I,onTogglePin:C,onRemove:P,onDragStart:_,onDragEnd:M,onDragOver:A,onDrop:T}){const[y,w]=h.useState(!1),R=h.useRef(null),[O,z]=h.useState({}),$=!!b||!!P,V=e==="local"&&c!==!1&&!!t.linkedSandboxProject?.projectId,Y=h.useCallback(()=>{if(typeof window>"u")return;const H=R.current?.getBoundingClientRect();if(!H)return;const F=Math.max(12,window.innerWidth-c4-12),J=Math.max(12,window.innerHeight-l4),K=Math.max(12,Math.min(H.right+10,F)),B=Math.max(12,Math.min(H.top-4,J)),ne={"--sidebar-project-locations-left":`${Math.round(K)}px`,"--sidebar-project-locations-top":`${Math.round(B)}px`};z(G=>G["--sidebar-project-locations-left"]===ne["--sidebar-project-locations-left"]&&G["--sidebar-project-locations-top"]===ne["--sidebar-project-locations-top"]?G:ne)},[]),re=h.useCallback(()=>{Y(),f()},[f,Y]);function ee(){w(!1)}return g.jsxs("div",{ref:R,className:["sidebar-project-row-shell",y?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:Y,onPointerEnter:Y,children:[g.jsxs(Tg,{selected:a,placeholder:l,className:["sidebar-project-row",y?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:s?r:void 0,onSelect:re,onDragStart:_,onDragEnd:M,onDragOver:A,onDrop:T,children:[g.jsx(xI,{kind:e,linkedCloud:V,open:e==="local"&&r,className:"sidebar-row-icon",baseSize:15}),g.jsx("span",{className:"row-label-shell",children:g.jsxs("span",{className:"sidebar-project-title-line",children:[g.jsx("span",{className:"row-label",children:t.name}),g.jsxs("span",{className:"sidebar-row-updated-at",children:[g.jsx("span",{"aria-hidden":"true",children:"| "}),g.jsx(wI,{value:t.updatedAt})]}),s?g.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:r?g.jsx(ms,{size:13}):g.jsx(ps,{size:13})}):null]})}),g.jsxs("div",{className:"row-meta",children:[g.jsx("span",{className:"row-meta-status",children:p?g.jsx(II,{indicator:p}):null}),g.jsxs("div",{className:"sidebar-row-actions",children:[g.jsx(Ld,{label:n?"Unpin project":"Pin project",onClick:C,children:n?g.jsx(dg,{size:13}):g.jsx(lg,{size:13})}),$&&g.jsx(R4,{open:y,onToggleOpen:()=>w(H=>!H)}),g.jsx(Ld,{label:"New task",onClick:S,children:g.jsx(xu,{size:13})})]})]})]}),g.jsx(h4,{kind:e,project:t,workspaceState:i,cloudLinkTrusted:c,cloudLinkWarning:d,onWorkspaceTargetSelect:I,style:O}),y&&g.jsx(P4,{onClose:ee,onMoveToCloud:b?()=>{ee(),b()}:void 0,onRemove:()=>{ee(),P()}})]})}function II({indicator:e}){return g.jsx("span",{className:`sidebar-terminal-indicator ${e.status}`,"data-tooltip":e.label,"aria-label":e.label,title:e.label,children:g.jsx(Gw,{size:13})})}function h4({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:r,onWorkspaceTargetSelect:s,style:i}){const c=b4(e,t,n,a,r);return g.jsxs("aside",{className:"sidebar-project-locations-popover","aria-label":`${t.name} status`,style:i,children:[g.jsx("div",{className:"sidebar-project-locations-title",children:t.name}),g.jsx("div",{className:"sidebar-project-location-list",children:c.map(d=>{const l=["sidebar-project-location-row",d.tone??"",d.actionTarget?"clickable":""].filter(Boolean).join(" "),p=g.jsxs(g.Fragment,{children:[g.jsx("span",{className:["sidebar-project-location-icon",d.key].filter(Boolean).join(" "),"aria-hidden":"true",children:d.icon}),g.jsx("span",{className:"sidebar-project-location-copy",children:g.jsx(g4,{value:d.value})})]});return d.actionTarget?g.jsx("button",{type:"button",className:l,"data-workspace-target":d.actionTarget,disabled:d.disabled||!s,title:d.disabledReason??void 0,onClick:f=>{f.stopPropagation(),!d.disabled&&s?.(d.actionTarget)},children:p},d.key):g.jsx("div",{className:l,children:p},d.key)})})]})}function g4({value:e}){const t=v4(e);return g.jsxs("span",{className:"sidebar-project-location-value","aria-label":e,children:[t.branch?g.jsxs(g.Fragment,{children:[g.jsx("span",{className:"sidebar-project-location-branch",children:t.branch}),g.jsx("span",{className:"sidebar-project-location-separator","aria-hidden":"true",children:"/"})]}):null,g.jsx("span",{className:"sidebar-project-location-status",children:t.status})]})}function v4(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function b4(e,t,n,a=!0,r=null){return e==="cloud"?S4(t):y4(t,n,a,r)}function y4(e,t,n=!0,a=null){const r=x4(e,t,n),s=k4(t),i=I4(e,n),c=n===!1&&a;return[{key:"local",value:r,tone:s?"attention":"local",icon:e.source==="git"?g.jsx(ig,{size:13}):g.jsx(Bw,{size:13}),actionTarget:"local"},{key:"cloud",value:c||(i?_4(e,t,n):"not in cloud"),tone:c?"attention":"cloud",icon:g.jsx(yu,{size:13}),actionTarget:i?"cloud":"upload_cloud"}]}function S4(e){return[{key:"cloud",value:C4(e),tone:e.syncedAt?"cloud":"attention",icon:g.jsx(yu,{size:13}),actionTarget:"cloud"}]}function x4(e,t,n){const a=w4(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?bI(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function k4(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function w4(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function I4(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function _4(e,t,n){return yI(e,null,t,{cloudLinkTrusted:n})}function C4(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function R4({open:e,onToggleOpen:t}){return g.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:g.jsx(Xc,{size:13})})}function P4({onClose:e,onMoveToCloud:t,onRemove:n}){return g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",className:"sidebar-project-menu-backdrop","aria-label":"Close project actions",onClick:a=>{a.stopPropagation(),e()}}),g.jsxs("div",{className:"section-menu-popover sidebar-project-row-popover",role:"menu",children:[t&&g.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),t()},children:[g.jsx(Hq,{size:13}),g.jsx("span",{children:"Move to Cloud"})]}),g.jsxs("button",{type:"button",role:"menuitem",onClick:a=>{a.stopPropagation(),n()},children:[g.jsx(el,{size:13}),g.jsx("span",{children:"Remove from Projects"})]})]})]})}function Tg({children:e,className:t,dataSessionId:n,dragging:a,iconless:r=!1,nested:s=!1,placeholder:i=!1,selected:c,ariaExpanded:d,ariaDescribedBy:l,onSelect:p,onDragStart:f,onDragEnd:S,onDragOver:b,onDrop:I,onDoubleClick:C}){const P=!!f;return g.jsx("div",{className:["sidebar-row",t??"",c?"selected":"",a?"dragging":"",r?"iconless":"",s?"nested":"",i?"placeholder":""].filter(Boolean).join(" "),draggable:P,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":d,"aria-describedby":l,onClick:p,onDoubleClick:C,onKeyDown:_=>{_.target===_.currentTarget&&(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),p())},onDragStart:f,onDragEnd:S,onDragEnter:_=>{b&&(_.preventDefault(),_.dataTransfer.dropEffect="move",b(_))},onDragOver:_=>{b&&(_.preventDefault(),_.dataTransfer.dropEffect="move",b(_))},onDrop:_=>{I&&(_.preventDefault(),I(_))},children:e})}function Ld({children:e,label:t,onClick:n}){return g.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":t,"aria-label":t,onClick:a=>{a.stopPropagation(),n()},children:e})}function T4({filter:e,activityOrder:t=!1,groupByProject:n,noun:a,onFilterChange:r,onGroupByProjectChange:s,onOnlyRunningTasksChange:i,onShowCodexChatsChange:c,onTasksetChange:d,onSortChange:l,onlyRunningTasks:p,openMenu:f,setOpenMenu:S,showCodexChats:b,sort:I,selectedTasksetId:C,tasksets:P}){const _=h.useRef(null),[M,A]=h.useState(!1),y=P.find(O=>O.id===C)?.name??Eb.find(O=>O.value===e)?.label??"Active",w=f==="tasks-filter",R=f==="chats";return h.useEffect(()=>{if(!w&&!R)return;function O(z){_.current?.contains(z.target)||S(null)}return document.addEventListener("pointerdown",O),()=>document.removeEventListener("pointerdown",O)},[w,S,R]),g.jsxs("div",{className:"sidebar-task-list-controls",ref:_,children:[g.jsxs("div",{className:"section-menu",children:[g.jsx("button",{type:"button",className:`section-icon ${R?"active":""}`,"aria-label":`${a==="tasks"?"Task":"Chat"} list options`,"aria-haspopup":"menu","aria-expanded":R,onClick:()=>S(O=>O==="chats"?null:"chats"),children:g.jsx(Xc,{size:14})}),R?g.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":`${a==="tasks"?"Task":"Chat"} list options`,children:[g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":b,onClick:()=>c(!b),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:b?g.jsx(lr,{size:13}):null}),g.jsx("span",{children:"Show Codex chats, including pinned"})]}),g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":p,onClick:()=>i(!p),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:p?g.jsx(lr,{size:13}):null}),g.jsxs("span",{children:["Only running ",a,", including pinned"]})]}),a==="tasks"&&!t?g.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,onClick:()=>s(!n),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:n?g.jsx(lr,{size:13}):null}),g.jsx("span",{children:"Group by project"})]}):null,t?g.jsx("p",{className:"empty-row",children:"Latest activity first"}):Pq.map(O=>g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":I===O.value,onClick:()=>{l(O.value),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:I===O.value?g.jsx(lr,{size:13}):null}),g.jsx("span",{children:O.label})]},O.value))]}):null]}),g.jsxs("div",{className:"section-menu",children:[g.jsx("button",{type:"button",className:`section-icon ${w?"active":""}`,"aria-label":`Filter ${a}: ${y}`,"aria-haspopup":"menu","aria-expanded":w,onClick:()=>S(O=>O==="tasks-filter"?null:"tasks-filter"),children:g.jsx(uU,{size:14})}),w?g.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${a}`,children:Eb.map(O=>g.jsxs(h.Fragment,{children:[O.value==="tasksets"?g.jsxs("button",{type:"button",role:"menuitem","aria-expanded":M,onClick:()=>A(z=>!z),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:M?g.jsx(ms,{size:13}):g.jsx(ps,{size:13})}),g.jsx("span",{children:O.label})]}):g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===O.value,onClick:()=>{r(O.value),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===O.value?g.jsx(lr,{size:13}):null}),g.jsx("span",{children:O.label})]}),O.value==="tasksets"&&M?g.jsxs(g.Fragment,{children:[g.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&!C,onClick:()=>{d(null),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!C?g.jsx(lr,{size:13}):null}),g.jsx("span",{children:"All Tasksets"})]}),P.map(z=>g.jsxs("button",{className:"section-menu-taskset-option",type:"button",role:"menuitemradio","aria-checked":e==="tasksets"&&C===z.id,onClick:()=>{d(z.id),S(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&C===z.id?g.jsx(lr,{size:13}):null}),g.jsx("span",{children:z.name}),g.jsx("span",{className:"section-menu-option-count","aria-hidden":"true",children:z.chatCount})]},z.id))]}):null]},O.value))}):null]})]})}function A4({onAddProject:e,onViewProjects:t}){const[n,a]=h.useState(!1),r=h.useRef(null),s=h.useRef(null);return h.useEffect(()=>{if(!n)return;r.current?.querySelector('[role="menuitem"]')?.focus();const i=c=>{r.current?.contains(c.target)||a(!1)};return document.addEventListener("pointerdown",i),()=>document.removeEventListener("pointerdown",i)},[n]),g.jsxs(g.Fragment,{children:[g.jsxs("div",{className:"section-menu",ref:r,onKeyDown:i=>{i.key==="Escape"&&(i.stopPropagation(),a(!1),s.current?.focus())},children:[g.jsx("button",{ref:s,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(i=>!i),children:g.jsx(Xc,{size:14})}),n?g.jsxs("div",{className:"section-menu-popover",role:"menu","aria-label":"Project options",children:[g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},children:"View all projects"}),g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),e()},children:"Add project"})]}):null]}),g.jsx("button",{type:"button",className:"section-icon",onClick:e,"aria-label":"Add project",title:"Add project",children:"+"})]})}const E4=240,j4=36;function M4(e,t,n=!1){const a=Math.max(12,t.width-E4-12),r=Math.max(12,t.height-j4-(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,r)))}px`}}function O4({detail:e,onClose:t}){if(h.useEffect(()=>{if(!e||typeof window>"u")return;const r=c=>{c.key==="Escape"&&t()};let s=!1;const i=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),s=!0});return window.addEventListener("keydown",r),()=>{window.cancelAnimationFrame(i),window.removeEventListener("keydown",r),s&&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 g.jsxs("aside",{id:e.descriptionId,className:"sidebar-task-detail-popover",style:e.style,role:"tooltip","aria-label":`Last updated for ${e.title}`,children:[g.jsx("time",{dateTime:e.updatedAt,children:a}),e.folderName?g.jsxs("div",{className:"sidebar-task-detail-folder",children:[g.jsx(Bw,{size:13,"aria-hidden":"true"}),g.jsx("span",{children:e.folderName})]}):null]})}function $4({children:e,expanded:t,groupKey:n,kind:a,label:r,onToggle:s,onNewTask:i,onOpenProject:c,onRemoveProject:d,project:l}){const p=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,f=a==="draft"?og:Su,[S,b]=h.useState(!1),I=!!(i||c||d);return g.jsxs("section",{className:"sidebar-task-project-group",children:[g.jsxs("div",{className:`sidebar-task-project-group-header-shell${S?" menu-open":""}`,children:[g.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":p,"aria-expanded":t,onClick:()=>{b(!1),s()},children:[l?g.jsx(xI,{kind:l.kind,linkedCloud:!!(l.kind==="local"&&l.project.linkedSandboxProject?.projectId),open:l.kind==="local"&&t,className:"sidebar-task-project-group-icon",baseSize:14}):g.jsx(f,{className:"sidebar-task-project-group-icon",size:14,"aria-hidden":"true"}),g.jsx("span",{className:"sidebar-task-project-group-name",children:r}),g.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?g.jsx(ms,{size:13}):g.jsx(ps,{size:13})})]}),l&&I?g.jsxs("div",{className:"sidebar-task-project-group-actions",children:[c||d?g.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:()=>b(C=>!C),children:g.jsx(Xc,{size:13})}):null,i?g.jsx("button",{type:"button",className:"sidebar-row-action","data-tooltip":"New task","aria-label":"New task",onClick:i,children:g.jsx(xu,{size:13})}):null]}):null,S?g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",className:"sidebar-task-project-group-menu-backdrop","aria-label":"Close project actions",onClick:()=>b(!1)}),g.jsxs("div",{className:"section-menu-popover sidebar-task-project-group-menu",role:"menu",children:[c?g.jsx("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),c()},children:g.jsx("span",{children:"Open project"})}):null,d?g.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),d()},children:[g.jsx(el,{size:13}),g.jsx("span",{children:"Remove from Projects"})]}):null]})]}):null]}),t?g.jsx("div",{id:p,className:"sidebar-task-project-group-content",children:e}):null]})}const N4={},D4=new Map,L4=new Map;function Fb(){const e=no.getItem("openpond.sidebar.presentation.v1");return e==="inbox"||e==="grouped"?e:ku()?"inbox":"grouped"}function z4(e,t){return Math.min(Math.max(e,Nn)+bf,t)}function H4(e,t){const n=Math.max(Nn,Math.min(e,t));if(n<=Nn)return Nn;const a=Math.ceil((n-Nn)/bf);return Math.max(Nn,Nn+(a-1)*bf)}function U4(e,t){const n=new Map;for(const a of e){const r=t(a),s=n.get(r.key);s?s.sessions.push(a):n.set(r.key,{...r,sessions:[a]})}return[...n.values()]}function q4({activeSessions:e,activityTimes:t={},onSelectSession:n,archiveSession:a,archivedSessions:r,chatRowsVisibleCount:s,childSessionRowsByParentId:i={},cloudProjectRows:c,beginProjectChat:d,onAddProject:l,commitTaskDrop:p,commitTaskPreviewDrop:f,dockSessionRight:S,experience:b="work",goalRuntimeBySessionId:I=D4,localProjectRows:C,openSidebarFile:P,pinnedCollapsed:_,pinnedRows:M,previewTaskDrop:A,previewPinnedDrop:T,projectRows:y,renameSession:w,restoreSession:R,runningSessionIds:O,sectionMenuOpen:z,selectedProjectId:$,selectedSessionId:V,setChatRowsVisibleCount:Y,setSectionMenuOpen:re,setSelectedAppId:ee,setSelectedProjectId:H,setSelectedSessionId:F,setView:J,sidebarProjectIdBySessionId:K,startTaskDrag:B,startPinnedDrag:ne,subagentRuntimeBySessionId:G=L4,taskDragSessionId:te,taskPreviewSessionIds:oe,terminalSummaries:be=N4,toggleSessionPinned:me,toggleSessionSavedForLater:Re,view:Q,clearTaskDrag:xe,removeProject:je,toggleProjectPinned:De,onTogglePinnedCollapsed:He,setSidebarFileStatus:Ie,commitPinnedDrop:Me,commitPinnedPreviewDrop:Te,clearSidebarDrag:N,dragItem:q}){const[X,U]=h.useState(Fb);pi(()=>U(Fb()));const ae=X==="inbox",[de,ye]=h.useState("active"),[Oe,$e]=h.useState("recent"),[Ge,yt]=h.useState(!0);h.useEffect(()=>{b!=="chat"&&yt(!0)},[b]);const[Se,Le]=h.useState({work:!1,chat:!0}),[Ae,qe]=h.useState({work:!1,chat:!1}),Ue=b==="chat"?"chat":"work",bn=Se[Ue],[Mt,pe]=h.useState(Nb);pi(()=>pe(Nb()));const{onlyRunningTasks:fe,showCodexChats:Fe}=Mt,[Pe,Ne]=h.useState(null),[ot,ut]=h.useState(()=>new Set),[At,mt]=h.useState(()=>new Map),[at,Ct]=h.useState(null);h.useEffect(()=>{$&&Le(D=>D[Ue]?{...D,[Ue]:!1}:D)},[Ue,$]);const Be=b==="chat"?"chats":"tasks",Et=y??[...C,...c],dn=h.useMemo(()=>new Map(Et.map(D=>[D.id,D.project.name])),[Et]),jn=h.useMemo(()=>new Map(Et.map(D=>[D.id,D])),[Et]),kt=h.useMemo(()=>{const D=new Set(O);for(const we of[...e,...Object.values(i).flat()]){const le=I.get(we.id),Je=G.get(we.id);(le?.tone==="active"&&le.status!=="queued"||(Je?.activeCount??0)>0||_t(we.id)?.status==="running")&&D.add(we.id)}return D},[e,i,I,O,G,be]),kr=h.useMemo(()=>up({activeSessions:e,doneSessions:r,filter:"all",inProgressSessionIds:kt,sort:"manual"}),[e,r,kt]),un=h.useMemo(()=>up({activeSessions:e,doneSessions:r,filter:de,inProgressSessionIds:kt,onlyRunningTasks:fe,selectedTasksetId:Pe,previewSessionIds:oe,showCodexChats:Fe,sort:Oe}),[e,r,kt,fe,Pe,Fe,de,oe,Oe]),yn=h.useMemo(()=>{const D=new Map;for(const we of[...e,...r]){if(!dd(we,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe}))continue;const le=Vo(we);if(!le)continue;const Je=D.get(le.id);Je?Je.chatCount+=1:D.set(le.id,{...le,chatCount:1})}return[...D.values()].sort((we,le)=>we.name.localeCompare(le.name))},[e,r,kt,fe,Fe]),Ut=h.useMemo(()=>M.filter(D=>D.type!=="session"||dd(D.session,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe})),[kt,fe,M,Fe]),Rn=h.useMemo(()=>un.filter(D=>!Ko(D)),[un]),Sn=h.useMemo(()=>Rn.slice(0,Math.max(Nn,s)),[s,Rn]),Pn=h.useMemo(()=>{const D=U4(Sn,we=>{if($c(we))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const le=K[we.id],Je=Ot(we)??"Work";return{key:le?`project:${le}`:`projectless:${Je}`,label:Je,projectId:le??null,project:le?jn.get(le)??null:null,kind:le?"project":"projectless"}});for(const we of Et)D.some(le=>le.projectId===we.id)||D.push({key:`project:${we.id}`,label:we.project.name,projectId:we.id,project:we,kind:"project",sessions:[]});return D},[Et,dn,jn,K,Sn]),Mn=Sn.length<Rn.length,qt=Sn.length>Nn,gt=h.useMemo(()=>new Set(Pn.filter(D=>D.sessions.some(we=>we.id===V||kt.has(we.id))).map(D=>D.key)),[Pn,kt,V]),qn=kr.filter(D=>!Ko(D)).map(D=>D.id),mn=Sn.map(D=>D.id),pt=JSON.stringify(Object.entries(i).filter(([D,we])=>we.some(le=>!le.archived)&&(G.get(D)?.activeCount??0)>0).flatMap(([D,we])=>we.filter(le=>!le.archived).map(le=>[D,le.id])).sort(([D,we],[le,Je])=>D.localeCompare(le)||we.localeCompare(Je)));h.useEffect(()=>{const D=JSON.parse(pt);if(D.length===0)return;const we=new Set(D.map(([le])=>le));ut(le=>[...we].every(Je=>le.has(Je))?le:new Set([...le,...we]))},[pt]);function _t(D){return $q(be[vI({kind:"session",id:D})])}function Ot(D){if($c(D))return"Draft";const we=K[D.id];return we?dn.get(we)??D.workspaceName??"Project":kq(D)}function pn(D){if(n){n(D);return}Lt({kind:"chat",sessionId:D.id}),F(D.id);const we=K[D.id]??null;ee(we?null:D.appId),H(we),J("chat")}function oa(D){return(i[D.id]??[]).filter(we=>!we.archived&&dd(we,{inProgressSessionIds:kt,onlyRunningTasks:fe,showCodexChats:Fe}))}function Ze(D,we){return ot.has(D.id)||we.some(le=>le.id===V)}function Tn(D){ut(we=>{const le=new Set(we);return le.has(D)?le.delete(D):le.add(D),le})}function Za(D){const we=oa(D);return we.length===0||!Ze(D,we)?null:g.jsx("div",{className:"sidebar-child-session-group",children:we.map(le=>g.jsx(Bb,{session:le,selected:Q==="chat"&&V===le.id,nested:!0,running:kt.has(le.id),goalRuntime:I.get(le.id)??null,subagentRuntime:G.get(le.id)??null,terminalIndicator:_t(le.id),projectLabel:Ot(D),onSelect:()=>pn(le),onTogglePin:()=>me(le),onToggleSaveForLater:()=>Re(le),onDockRight:()=>S(le),onArchive:()=>le.archived?R(le):a(le),onRename:w},le.id))})}function Ea(D,we){if(typeof window>"u")return;const le=Ko(D)?Ot(D):null;Ct({descriptionId:`sidebar-task-detail-${D.id}`,sessionId:D.id,title:D.title,updatedAt:D.updatedAt,folderName:le,style:M4(we.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!le)})}function Ln(D,we={}){const le=D.archived,Je=we.pinnedRow?.placeholder??te===D.id,ga=oa(D),Bn="sidebar-session-group",Ma=we.pinnedRow?.dragProps??(!ae&&Oe==="manual"?{onDragStart:kn=>B(kn,{allSessionIds:qn,visibleSessionIds:mn,sessionId:D.id}),onDragEnd:xe,onDragOver:kn=>{Je||A(kn,D.id)},onDrop:kn=>{Je?f():p(kn,D.id)}}:{});return g.jsxs("div",{className:Bn,onPointerEnter:kn=>Ea(D,kn.currentTarget),onPointerLeave:()=>Ct(null),onFocusCapture:kn=>Ea(D,kn.currentTarget),onBlurCapture:kn=>{kn.currentTarget.contains(kn.relatedTarget)||Ct(null)},children:[g.jsx(Bb,{session:D,selected:!le&&Q==="chat"&&V===D.id,archived:le,inbox:ae,activityAt:bd(D,t),placeholder:Je,running:kt.has(D.id),goalRuntime:I.get(D.id)??null,subagentRuntime:G.get(D.id)??null,terminalIndicator:_t(D.id),projectLabel:we.projectLabel===void 0?Ot(D):we.projectLabel,metadataPresentation:we.metadataPresentation,ariaDescribedBy:at?.sessionId===D.id?at.descriptionId:void 0,childSessionCount:ga.length,childSessionsExpanded:Ze(D,ga),onToggleChildSessions:()=>Tn(D.id),onSelect:()=>{Ct(null),le&&R(D),pn(D)},onTogglePin:()=>me(D),onToggleSaveForLater:()=>Re(D),onDockRight:()=>S(D),onArchive:()=>le?R(D):a(D),onRename:w,...Ma}),!ae&&!Je?Za(D):null]},we.pinnedRow?.key??D.id)}function An(D){D!=="tasksets"&&Ne(null),ye(D),Y(Nn)}function Ja(D){Ne(D),ye("tasksets"),Y(Nn)}function wr(D){$e(D),Y(Nn)}function ja(){Y(D=>z4(D,Rn.length))}function lt(){Y(D=>H4(D,Rn.length))}function rn(D){const we={id:D.id,type:D.type};return{onDragStart:le=>ne(le,we),onDragEnd:N,onDragOver:le=>T(le,we),onDrop:le=>{q?.id===D.id&&q.type===D.type?Te():Me(le,we)}}}function Ke(D){const we=rn(D),le=q?.id===D.id&&q.type===D.type;if(D.type==="project"){const Je=D.item;return g.jsx(f4,{kind:Je.kind,project:Je.project,pinned:!0,selected:Q==="chat"&&$===Je.id,expanded:!1,disclosure:!1,placeholder:le,onSelect:()=>{ee(null),H(Je.id),F(null),J("chat")},onNewChat:()=>d(Je.id),onTogglePin:()=>De(Je),onRemove:()=>je(Je),...we},D.key)}return D.type==="file"?g.jsx(m4,{file:D.file,placeholder:le,onSelect:()=>P(D.file),onTogglePin:()=>Ie(D.file,"none"),onToggleSaveForLater:()=>Ie(D.file,"saved_for_later"),...we},D.key):Ln(D.session,{projectLabel:ae&&!K[D.session.id]?null:Ot(D.session),pinnedRow:{key:D.key,dragProps:we,placeholder:le}})}function St(D){const we=gt.has(D.key)||At.get(D.key)!==!1;return g.jsx($4,{expanded:we,groupKey:D.key,kind:D.kind,label:D.label,onToggle:()=>{mt(le=>{const Je=new Map(le);return Je.set(D.key,!we),Je})},onNewTask:D.project?()=>d(D.project.id):void 0,onOpenProject:D.project?()=>{ee(null),H(D.project.id),F(null),J("chat")}:void 0,onRemoveProject:D.project?()=>je(D.project):void 0,project:D.project,children:D.sessions.map(le=>Ln(le,{metadataPresentation:"flyout",projectLabel:D.label}))},D.key)}const en=g.jsx(T4,{activityOrder:ae,filter:de,groupByProject:Ge,noun:Be,onFilterChange:An,onGroupByProjectChange:yt,onOnlyRunningTasksChange:D=>{pe(we=>{const le={...we,onlyRunningTasks:D};return Db(le),le}),Y(Nn)},onShowCodexChatsChange:D=>{pe(we=>{const le={...we,showCodexChats:D};return Db(le),le}),Y(Nn)},onTasksetChange:Ja,onSortChange:wr,onlyRunningTasks:fe,openMenu:z,setOpenMenu:re,showCodexChats:Fe,sort:Oe,selectedTasksetId:Pe,tasksets:yn}),zn=up({activeSessions:Object.values(i).flat().filter(D=>!D.archived),doneSessions:Object.values(i).flat().filter(D=>D.archived),filter:de,inProgressSessionIds:kt,onlyRunningTasks:fe,selectedTasksetId:Pe,showCodexChats:Fe,sort:"recent"}),xn=aC([...un,...zn].filter(D=>!Ko(D)),t,kt);return g.jsxs("div",{className:"sidebar-sections",children:[g.jsxs("div",{className:"sidebar-threads-header",children:[g.jsx("span",{children:"Threads"}),g.jsxs("div",{className:"sidebar-threads-header-actions",children:[ae?en:null,g.jsx("button",{type:"button",className:`sidebar-icon${ae?" active":""}`,"aria-label":ae?"Show grouped threads":"Show thread inbox",title:ae?"Grouped threads":"Thread inbox","aria-pressed":ae,onClick:()=>{const D=ae?"grouped":"inbox";U(D),no.setItem("openpond.sidebar.presentation.v1",D)},children:ae?g.jsx(zU,{size:16}):g.jsx(mg,{size:16})})]})]}),Ut.length>0?g.jsx(mp,{label:"Pinned",className:"sidebar-pinned-section",collapsed:_,onToggleCollapsed:He,children:Ut.map(Ke)}):null,ae?g.jsxs("section",{className:"sidebar-thread-inbox","aria-label":"Thread inbox",children:[rC(xn,t,kt).map(D=>g.jsxs("div",{children:[D.label?g.jsx("h3",{className:"sidebar-inbox-date",children:D.label}):null,D.sessions.map(we=>Ln(we,{projectLabel:K[we.id]?Ot(we):null}))]},D.key)),xn.length===0&&Ut.length===0?g.jsx("div",{className:"empty-row",children:Mb(de,Be)}):null]}):g.jsxs(g.Fragment,{children:[g.jsx(mp,{label:"Projects",className:`sidebar-projects-section${b!=="chat"?" development":""}`,collapsed:bn,onToggleCollapsed:()=>Le(D=>({...D,[Ue]:!D[Ue]})),actions:g.jsx(A4,{onAddProject:l,onViewProjects:()=>{(async()=>await Lt({kind:"view",view:"projects"})&&(ee(null),H(null),F(null),J("projects")))()}}),children:Pn.filter(D=>D.kind==="project").map(D=>St(b==="chat"||!Ge?{...D,sessions:[]}:D))}),g.jsxs(mp,{label:b==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:Ae[Ue],onToggleCollapsed:()=>qe(D=>({...D,[Ue]:!D[Ue]})),actionsVisible:z==="chats"||z==="tasks-filter"||de!=="active"||fe||!Fe,actions:en,children:[(b==="chat"||!Ge?Sn:Sn.filter(D=>!K[D.id])).map(D=>Ln(D)),Rn.length===0&&Ut.length===0?g.jsx("div",{className:"empty-row",children:Mb(de,Be)}):null,Rn.length>Nn&&(Mn||qt)?g.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${Sn.length} of ${Rn.length} ${Be}`,children:[Mn?g.jsx(qb,{onClick:ja,children:"Show more"}):null,qt?g.jsx(qb,{onClick:lt,children:"Show less"}):null]}):null]})]}),g.jsx(O4,{detail:at,onClose:()=>Ct(null)})]})}const B4=h.lazy(()=>fs(()=>import("./TerminalOverlay-DhPoKZAq.js"),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.TerminalOverlay})));function F4({connection:e,command:t,onClose:n,onComplete:a}){const[r,s]=h.useState([]),[i]=h.useState(()=>({kind:"draft",id:`native-setup-${crypto.randomUUID()}`})),c=h.useRef(!1),[d]=h.useState(()=>({id:Date.now(),scope:i,command:t}));return h.useEffect(()=>{!c.current&&r.some(l=>l.lastExitCode!==null&&(l.commandStatus==="success"||l.commandStatus==="failed"))&&(c.current=!0,a?.())},[r,a]),Dd.createPortal(g.jsx("div",{className:"native-setup-terminal",children:g.jsx(h.Suspense,{fallback:g.jsx("p",{role:"status",children:"Opening setup terminal…"}),children:g.jsx(B4,{open:!0,disposeOnUnmount:!0,connection:e,scope:i,tabs:r,onTabsChange:s,cwd:null,appId:null,workspaceName:"Agent setup",queuedCommand:d,onClose:n})})}),document.body)}const ql={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 V4({status:e,busy:t,onControl:n,onConnectionControl:a,onReconnect:r}){const s=e.desiredState==="stopped",i=s?"Importer stopped":e.running?"Importer running":"Importer offline";return g.jsxs("div",{className:"sidebar-section native-importer-status",children:[g.jsx("strong",{children:i}),e.connections.map(c=>{const d=c.backfill,l=d.stage==="complete",p=d.admitted+d.skipped;return g.jsxs("div",{className:"native-importer-connection",children:[g.jsxs("span",{children:[c.error?g.jsx(jd,{size:12}):l?g.jsx(lr,{size:12}):g.jsx(cg,{size:12}),ql[c.source]??c.source]}),g.jsx("small",{children:c.state==="paused"?"Paused":c.state==="disconnected"?"Disconnected":l?e.running&&!s?"Watching for new conversations":`${d.admitted} conversations imported`:d.stage==="discovering"?"Finding conversations":`${p} of ${d.total} conversations processed`}),g.jsxs("small",{children:[c.admitted," tasks admitted",d.skipped>0?`, ${d.skipped} conversations skipped`:"",d.failed>0?`, ${d.failed} failed`:""]}),!l&&d.total>0?g.jsx("progress",{"aria-label":`${ql[c.source]??c.source} import progress`,value:p,max:d.total}):null,c.queued>0?g.jsxs("small",{children:[c.queued," updates waiting to upload (",new Intl.NumberFormat(void 0,{notation:"compact"}).format(c.pendingBytes)," bytes)"]}):null,c.lastAdmissionAt?g.jsxs("small",{children:["Last synced ",g.jsx("time",{dateTime:c.lastAdmissionAt,children:new Date(c.lastAdmissionAt).toLocaleString()})]}):g.jsx("small",{children:"No uploads acknowledged yet"}),c.destinationLinks?.tasks?g.jsx("a",{href:c.destinationLinks.tasks,target:"_blank",rel:"noopener noreferrer",children:"View tasks"}):null,c.destinationLinks?.conversations?g.jsx("a",{href:c.destinationLinks.conversations,target:"_blank",rel:"noopener noreferrer",children:"View conversations"}):null,c.error?g.jsx("small",{role:"status",children:c.error}):null,c.state==="disconnected"?g.jsx("button",{type:"button",disabled:t,onClick:()=>r(c.id),children:"Reconnect source"}):g.jsxs("div",{children:[g.jsxs("button",{type:"button",disabled:t,onClick:()=>a(c.state==="paused"?"resume":"pause",c.id),children:[c.state==="paused"?"Resume":"Pause"," ",ql[c.source]??c.source]}),g.jsxs("button",{type:"button",disabled:t,onClick:()=>a("disconnect",c.id),children:["Disconnect ",ql[c.source]??c.source]})]})]},c.id)}),g.jsx("button",{type:"button",disabled:t||s,onClick:()=>n("sync"),children:"Sync now"}),g.jsxs("button",{type:"button",disabled:t,onClick:()=>n(s||!e.running?"start":"stop"),children:[s?"Start":e.running?"Stop":"Restart"," importer"]}),!e.running&&!s?g.jsx("button",{type:"button",disabled:t,onClick:()=>n("stop"),children:"Stop importer"}):null,!e.running&&!s?g.jsx("button",{type:"button",disabled:t,onClick:()=>n("install"),children:"Reinstall background service"}):null]})}function K4({title:e,inspection:t,busy:n,onSelect:a,onRefresh:r,onClose:s}){return g.jsxs("section",{className:"native-branch-picker","aria-label":"Choose Claude conversation branch",children:[g.jsx("strong",{children:e||"Claude conversation"}),g.jsx("p",{children:"This conversation has multiple branches. Choose the history to view. Each branch opens as a read-only snapshot."}),t.branches.map(i=>g.jsxs("button",{type:"button",disabled:n,onClick:()=>a({leafId:i.leafId,revision:t.revision}),children:[g.jsx("span",{children:i.title||"Branch without a text message"}),g.jsxs("small",{children:[i.messages," messages · ",i.updatedAt?new Date(i.updatedAt).toLocaleString():"Date unavailable"]}),g.jsx("code",{children:i.leafId})]},i.leafId)),g.jsxs("div",{children:[g.jsx("button",{type:"button",disabled:n,onClick:r,children:"Refresh branches"}),g.jsx("button",{type:"button",disabled:n,onClick:s,children:"Cancel"})]})]})}function W4({connection:e,selectedSessionId:t,selectedSession:n,active:a=!0,onOpen:r}){const s=h.useRef({selectedSessionId:t,active:a});s.current={selectedSessionId:t,active:a};const i=h.useRef(null),c=h.useRef(0),d=h.useRef(null);h.useEffect(()=>(c.current++,i.current=null,M(null),I(null),P(null),S(null),w(null),p(null),()=>{c.current++}),[e]);const[l,p]=h.useState(null),[f,S]=h.useState(null),[b,I]=h.useState(null),[C,P]=h.useState(null),[_,M]=h.useState(null),[A,T]=h.useState(!1),[y,w]=h.useState(null),R=h.useCallback(async()=>{if(!e||d.current===c.current)return;const ee=c.current;d.current=ee,M("refresh");try{const H=await L(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({retain:!0})});ee===c.current&&(I(H),P(null))}catch(H){ee===c.current&&P(H instanceof Error?H.message:"Local history is unavailable.")}finally{d.current===ee&&(d.current=null),ee===c.current&&M(null)}},[e]);h.useEffect(()=>{R()},[R]),h.useEffect(()=>{const ee=window.setInterval(()=>{document.hidden||R()},3e4);return()=>window.clearInterval(ee)},[R]),h.useEffect(()=>{if(!a||!e||!l||l.sessionId!==t)return;const ee=c.current,H=window.setInterval(()=>{document.hidden||L(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:l.id})}).catch(F=>{ee===c.current&&P(F.message)})},1e4);return()=>window.clearInterval(H)},[a,e,l,t]);async function O(){const ee=c.current;if(!(!e||!b)){M("more");try{const H=await L(e,"/v1/native-history/list",{method:"POST",body:JSON.stringify({cursors:b.nextCursors,retain:!0})});if(ee!==c.current)return;I(F=>({...H,items:[...new Map([...F?.items??[],...H.items].map(J=>[J.id,J])).values()]}))}catch(H){ee===c.current&&P(H instanceof Error?H.message:"Could not load more conversations.")}finally{ee===c.current&&M(null)}}}async function z(ee,H,F=s.current.selectedSessionId){const J=c.current;if(e&&_===null){M(ee);try{if(!H){const B=await L(e,"/v1/native-history/branches",{method:"POST",body:JSON.stringify({id:ee})});if(J!==c.current)return;if(B.branches.length>1){s.current.active&&s.current.selectedSessionId===F&&w({id:ee,inspection:B,originSessionId:F}),P(null);return}}const K=await L(e,"/v1/native-history/open",{method:"POST",body:JSON.stringify({id:ee,branch:H})});if(J!==c.current)return;p(H?null:{id:ee,sessionId:K.id}),w(null),P(K.metadata?.nativeHistoryProjection&&!K.nativeAgent?typeof K.metadata.nativeReadOnlyReason=="string"?K.metadata.nativeReadOnlyReason:"Read-only history: the native source does not report its original working directory.":null),s.current.active&&s.current.selectedSessionId===F&&await r(K)}catch(K){J===c.current&&P(K instanceof Error?K.message:"Could not read this conversation.")}finally{J===c.current&&M(null)}}}h.useEffect(()=>{if(!a||!e||_!==null||!n||n.metadata?.nativeHistoryLoaded!==!1||n.metadata.nativeBranch)return;const ee=n.metadata.nativeHistoryId;if(typeof ee!="string")return;const H=`${c.current}:${n.id}`;i.current!==H&&(i.current=H,z(ee,void 0,n.id))},[e,n,_,a]);async function $(ee){const H=c.current;if(e){M(ee);try{await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee})}),H===c.current&&await R()}catch(F){H===c.current&&P(F instanceof Error?F.message:"Collector action failed.")}finally{H===c.current&&M(null)}}}async function V(ee,H){const F=c.current;if(e){M(ee);try{const J=await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee,connectionId:H})});if(F!==c.current)return;S(J.command),P(null)}catch(J){F===c.current&&P(J instanceof Error?J.message:"Could not change Importer connection.")}finally{F===c.current&&M(null)}}}async function Y(ee){const H=c.current;if(e){M("connect");try{const F=await L(e,"/v1/native-history/collector",{method:"POST",body:JSON.stringify({command:ee?"reconnect":"connect",connectionId:ee})});if(H!==c.current)return;S(F.command),P(null)}catch(F){H===c.current&&P(F instanceof Error?F.message:"Could not open Importer setup.")}finally{H===c.current&&M(null)}}}async function re(ee){const H=ee.metadata?.nativeHistoryId;await r(ee)&&ee.metadata?.nativeHistoryProjection&&!ee.metadata.nativeBranch&&typeof H=="string"&&z(H,void 0,ee.id)}return{connection:e,history:b,error:C,busy:_,command:f,expanded:A,branchSelection:y,setCommand:S,setExpanded:T,setBranchSelection:w,refresh:R,more:O,open:z,control:$,connectionControl:V,connect:Y,select:re}}function G4({history:e}){const{connection:t,history:n,error:a,busy:r,command:s,expanded:i,branchSelection:c,setCommand:d,setExpanded:l,setBranchSelection:p,refresh:f,more:S,open:b,control:I,connectionControl:C,connect:P}=e;return t?g.jsxs("section",{className:"sidebar-section native-conversations","aria-label":"Conversation import controls",children:[g.jsxs("div",{className:"sidebar-section-heading",children:[g.jsx("button",{type:"button",onClick:()=>l(_=>!_),"aria-expanded":i,children:"Import conversations"}),g.jsx("button",{type:"button",className:"sidebar-icon","aria-label":"Refresh saved conversation history",disabled:r!==null,onClick:()=>{f()},children:r==="refresh"?g.jsx(cg,{size:14}):g.jsx(Kw,{size:14})})]}),s?g.jsx(F4,{connection:t,command:s,onClose:()=>{d(null),f()}}):null,c?g.jsx(K4,{title:n?.items.find(_=>_.id===c.id)?.title??"",inspection:c.inspection,busy:r!==null,onSelect:_=>{b(c.id,_,c.originSessionId??null)},onRefresh:()=>{b(c.id,void 0,c.originSessionId??null)},onClose:()=>p(null)}):null,i?g.jsxs(g.Fragment,{children:[g.jsx("button",{type:"button",disabled:r!==null,onClick:()=>{P()},children:"Connect an import source"}),n&&Object.keys(n.nextCursors).length?g.jsx("button",{type:"button",disabled:r!==null,onClick:()=>{S()},children:"Load more saved conversations"}):null,n&&n.items.length===0?g.jsx("p",{children:"No saved conversations found in configured source locations."}):null,n?.warnings.map(_=>g.jsxs("p",{children:[g.jsx(jd,{size:12,"aria-hidden":"true"})," ",_]},_)),n?.collector.connections.length?g.jsx(V4,{status:n.collector,busy:r!==null,onControl:_=>{I(_)},onConnectionControl:(_,M)=>{C(_,M)},onReconnect:_=>{P(_)}}):g.jsx("p",{children:"Connect an import source to upload conversations. Local history remains available without cloud sync."})]}):null,a?g.jsxs("p",{role:"status",children:[g.jsx(jd,{size:12,"aria-hidden":"true"})," ",a]}):null]}):null}function Vb(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 Z4(e,t){const n=Vb(e),a=Vb(t);if(!n||!a)return!1;for(let r=0;r<a.length;r+=1){if(a[r]>n[r])return!0;if(a[r]<n[r])return!1}return!1}function _I(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function J4(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function Q4(e,t,n){const a=_I(t),r=J4(n);if(a==="mac"){const s=e.filter(i=>/-mac-.*\.zip$/i.test(i.name));return r==="arm64"?s.find(i=>/-mac-arm64\.zip$/i.test(i.name))??null:r==="x64"?s.find(i=>/-mac-x64\.zip$/i.test(i.name))??s.find(i=>/-mac-universal\.zip$/i.test(i.name))??null:s.find(i=>/-mac-universal\.zip$/i.test(i.name))??s.find(i=>/-mac-arm64\.zip$/i.test(i.name))??s[0]??null}if(a==="linux"){const s=e.filter(i=>/\.AppImage$/i.test(i.name));return r==="arm64"?s.find(i=>/(?:arm64|aarch64).*\.AppImage$/i.test(i.name))??null:r==="x64"?s.find(i=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(i.name))??s[0]??null:s[0]??null}return null}function Y4(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(!Z4(e.currentVersion,a))return null;const r=typeof t.html_url=="string"?t.html_url:"",i=(Array.isArray(t.assets)?t.assets:[]).flatMap(d=>{if(!d||typeof d!="object")return[];const l=d;return typeof l.name!="string"||typeof l.browser_download_url!="string"?[]:[{name:l.name,downloadUrl:l.browser_download_url}]}),c=Q4(i,e.platform,e.arch);return!c||!r?null:{version:a,releaseUrl:r,assetName:c.name,downloadUrl:c.downloadUrl}}const X4=3600*1e3,eB="https://api.github.com/repos/openpond/openpond/releases/latest";function tB(e){const[t,n]=h.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",r=e.platform??"",s=e.arch??"",i=e.enabled&&!!a&&!!_I(r);return h.useEffect(()=>{if(!i){n({status:"idle",update:null,lastCheckedAt:null});return}let c=!1;async function d(){n(p=>({...p,status:p.update?"available":"checking"}));try{const p=await fetch(eB,{headers:{Accept:"application/vnd.github+json"}});if(!p.ok)throw new Error(`GitHub release check failed: ${p.status}`);const f=await p.json(),S=Y4({payload:f,currentVersion:a,platform:r,arch:s});if(c)return;n({status:S?"available":"current",update:S,lastCheckedAt:Date.now()})}catch{if(c)return;n(p=>({status:p.update?"available":"error",update:p.update,lastCheckedAt:Date.now()}))}}d();const l=window.setInterval(()=>{d()},X4);return()=>{c=!0,window.clearInterval(l)}},[s,a,i,r]),t}const CI="openpond.sidebar.continuous-learning.dismissed.v1";function Kb(e=RI()){if(!e)return!1;try{return e.getItem(CI)==="true"}catch{return!1}}function nB(e=RI()){if(e)try{e.setItem(CI,"true")}catch{}}function RI(){return typeof window>"u"?null:no}function aB({connection:e,onOpenSettings:t}){const[n,a]=h.useState(null),[r,s]=h.useState(Kb);pi(()=>s(Kb()));const i=h.useCallback(async()=>{if(!e){a(null);return}try{a(await Z.harnessHistory(e))}catch{a(null)}},[e]);if(h.useEffect(()=>{i()},[i]),r||!e||!n?.workspace)return null;const c=n.evaluationReviewSchedule,d=c.activityEnabled?`${c.activityBatchSize} outcomes${c.enabled?` + ${c.cadence}`:""}`:c.enabled?c.cadence:"Manual";return g.jsxs("section",{className:"sidebar-learning-notice","aria-label":"Continuous learning",children:[g.jsxs("header",{children:[g.jsx("strong",{children:"Continuous learning"}),g.jsxs("div",{className:"sidebar-learning-notice-actions",children:[g.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Open Continuous learning settings",onClick:t,type:"button",children:g.jsx(Ww,{size:14})}),g.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{s(!0),nB()},type:"button",children:g.jsx(el,{size:14})})]})]}),g.jsxs("div",{className:"sidebar-learning-status",children:[g.jsx("strong",{children:"Refiner"}),g.jsx("span",{children:n.backgroundReview.enabled?"On":"Off"})]}),g.jsxs("div",{className:"sidebar-learning-status",children:[g.jsx("strong",{children:"Continuous Review"}),g.jsx("span",{children:d})]})]})}function rB(e){const{arch:t,currentVersion:n,productArea:a,platform:r,setSectionMenuOpen:s,setSelectedAppId:i,setSelectedProjectId:c,setSelectedSessionId:d,setSidebarOpen:l,setView:p,view:f,modelProjects:S,modelTrainingActivityByProjectId:b}=e,I=h.useCallback(A=>{s(A)},[s]),C=tB({currentVersion:n,platform:r,arch:t,enabled:ku()}),P=C.status==="available"?C.update:null,_=h.useCallback(async A=>{if(!await Lt({kind:"chat",sessionId:A.id}))return!1;d(A.id);const T=e.sidebarProjectIdBySessionId[A.id]??null;return c(T),i(T?null:A.appId),p("chat"),!0},[d,c,i,p,e.sidebarProjectIdBySessionId]),M=W4({connection:a==="chat"?e.connection:null,active:f==="chat",selectedSessionId:e.selectedSessionId,selectedSession:[...e.activeSessions,...e.archivedSessions,...Object.values(e.childSessionRowsByParentId??{}).flat()].find(A=>A.id===e.selectedSessionId)??null,onOpen:_});return g.jsxs("aside",{className:"sidebar",inert:e.open===!1,children:[g.jsxs("div",{className:"sidebar-toolbar",children:[g.jsx("button",{className:"sidebar-icon","aria-label":"Hide sidebar",onClick:()=>l(!1),children:g.jsx(Vw,{size:16})}),g.jsx("div",{className:"sidebar-brand",children:g.jsx("img",{className:"sidebar-wordmark",src:Jq,alt:"OpenPond"})}),P&&g.jsxs("button",{type:"button",className:"sidebar-update-pill",title:`Download OpenPond ${P.version}: ${P.assetName}`,"aria-label":`Download OpenPond ${P.version}`,onClick:()=>{sB(P.downloadUrl)},children:[g.jsx(QH,{size:14}),g.jsx("span",{children:"Update"})]})]}),a==="chat"?g.jsxs("div",{className:"sidebar-fixed-actions",children:[g.jsx(nq,{experience:e.experience,beginNewChat:e.beginNewChat}),a==="chat"&&f==="chat"&&e.account?.activeProfile&&e.onOpenPonder?g.jsx("div",{className:"sidebar-ponder-fixed",children:g.jsxs("button",{type:"button",className:"sidebar-row sidebar-task-row sidebar-ponder-entry",onClick:e.onOpenPonder,children:[g.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:g.jsx("img",{src:Pg,alt:""})}),g.jsx("span",{children:"Ponder Pal"})]})}):null]}):null,g.jsxs("div",{className:"sidebar-scroll",children:[a!=="chat"?g.jsx(aq,{productArea:a,setSectionMenuOpen:I,setSelectedAppId:i,setSelectedProjectId:c,setSelectedSessionId:d,setView:p,view:f,modelProjects:S,modelTrainingActivityByProjectId:b}):null,a!=="chat"||f!=="chat"?null:g.jsx(q4,{...e,onSelectSession:M.select,setSectionMenuOpen:I}),a==="chat"&&f==="chat"?g.jsx(G4,{history:M}):null]}),g.jsx("div",{className:"sidebar-bottom-stack",children:a!=="chat"?null:g.jsx(aB,{connection:e.connection,onOpenSettings:()=>{s(null),Lt({kind:"settings",section:"harness"})}})})]})}async function sB(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const oB=[{destination:"walkthroughs",icon:xb,label:"Walkthroughs"},{destination:"external",icon:xb,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:og,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:ZH,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:Fw,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:oU,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:Su,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function iB({onOpenWalkthroughs:e,onCloseAccount:t,walkthroughsActive:n}){const[a,r]=h.useState(!1),s=h.useRef(null),i=h.useRef(null);h.useLayoutEffect(()=>{a&&i.current?.querySelector('[role="menuitem"]')?.focus()},[a]);function c(){r(!0)}function d(){r(!1),s.current?.focus()}return g.jsxs("div",{className:"user-auth-help",onKeyDown:l=>{a&&(l.key==="Escape"||l.key==="ArrowLeft")&&(l.preventDefault(),l.stopPropagation(),d())},children:[g.jsxs("button",{ref:s,type:"button",className:"user-auth-menu-link",role:"menuitem","aria-haspopup":"menu","aria-expanded":a,onClick:()=>a?d():c(),onKeyDown:l=>{l.key==="ArrowRight"&&(l.preventDefault(),c())},children:[g.jsx(lU,{size:15}),g.jsx("span",{children:"Help"}),g.jsx(ps,{className:"user-auth-help-chevron",size:14})]}),a?g.jsx("div",{ref:i,className:"user-auth-help-submenu",role:"menu","aria-label":"Help",onKeyDown:l=>{if(!["ArrowDown","ArrowUp","Home","End"].includes(l.key))return;l.preventDefault();const p=Array.from(i.current?.querySelectorAll('[role="menuitem"]')??[]),f=p.indexOf(document.activeElement),S=l.key==="Home"?0:l.key==="End"?p.length-1:(f+(l.key==="ArrowDown"?1:-1)+p.length)%p.length;p[S]?.focus()},children:oB.map(l=>{const p=l.icon,f=g.jsxs(g.Fragment,{children:[g.jsx(p,{size:15}),g.jsx("span",{children:l.label})]});return l.destination==="walkthroughs"?g.jsx("button",{type:"button",role:"menuitem",className:"user-auth-menu-link","aria-current":n?"page":void 0,onClick:()=>{t(),e()},children:f},l.label):g.jsx("a",{className:"user-auth-menu-link",role:"menuitem",href:l.url,target:"_blank",rel:"noreferrer",onClick:S=>{S.preventDefault(),t(),cB(l.url)},children:f},l.label)})}):null]})}async function cB(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const Wb=new WeakMap,kf=new WeakMap;function PI(e){if(!e)return"disconnected";let t=Wb.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},Wb.set(e,t)),t.id}function AG(e,t){return kf.set(e,t),e}function EG(e){if(!e)return["learning","disconnected"];let t=kf.get(e);return t||(t=["learning",crypto.randomUUID()],kf.set(e,t)),t}function lB(e,t){return R0({queryKey:["provider-plan-usage",PI(e),t],enabled:!!e,queryFn:({signal:n})=>L(e,`/v1/providers/${t}/plan-usage`,{signal:AbortSignal.any([n,AbortSignal.timeout(25e3)])}),staleTime:3e4,refetchInterval:6e4,refetchOnWindowFocus:"always",retry:!1,gcTime:3e5})}function pp(e){return`${Math.floor(e)}%`}function Gb(e){return e.resetsAt?`Resets ${new Date(e.resetsAt).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}`:"Reset time unavailable"}function dB(e,t){return t?"Loading…":e?.status==="signed_out"?"Sign in":e?.status==="unsupported"?"Not available":"Unavailable"}function uB({connection:e,provider:t,compact:n=!1,onOpen:a}){const r=lB(e,t),s=r.data,i=s?.windows.filter(b=>b.shared)??[],c=!!s?.windows.some(b=>b.resetsAt&&Date.parse(b.resetsAt)<=Date.now()),d=r.isError||c||!!(s&&Date.parse(s.refreshAfter)+6e4<Date.now()),l=t==="claude-code"?"Claude":"Codex",p=s?.status==="ready",f=dB(s,r.isPending&&!!e),S=s?.windows.map(b=>`${b.label}: ${pp(b.remainingPercent)} remaining. ${Gb(b)}.`).join(`
|
|
111
|
+
`);return n?g.jsxs("button",{type:"button",role:"menuitem",className:"plan-usage-compact",onClick:a,title:d?`Usage needs refreshing. ${S??""}`:S||s?.message||"View plan usage in Providers",children:[g.jsx("span",{children:l}),g.jsx("span",{className:"plan-usage-compact-values",children:!d&&p&&i.length?i.map(b=>g.jsxs("span",{className:"plan-usage-compact-value",children:[g.jsx("small",{children:b.label}),g.jsx("strong",{children:pp(b.remainingPercent)})]},b.id)):g.jsx("strong",{children:d?"Unavailable":f})})]}):g.jsxs("section",{className:"provider-plan-usage","aria-label":`${l} plan usage`,children:[g.jsx("div",{className:"plan-usage-heading",children:g.jsx("button",{type:"button",className:"plan-usage-refresh","aria-label":`Refresh ${l} plan usage`,title:`Check usage (cached for up to ${t==="claude-code"?"5 minutes":"1 minute"})`,disabled:!e||r.isFetching,onClick:()=>{r.refetch()},children:g.jsx(Kw,{size:13,className:r.isFetching?"settings-spin":void 0})})}),p?g.jsxs(g.Fragment,{children:[s.windows.map(b=>g.jsxs("div",{className:"plan-usage-window",children:[g.jsxs("div",{children:[g.jsx("span",{children:b.label}),g.jsxs("strong",{children:[pp(b.remainingPercent),d?" · last known":""]})]}),g.jsx("meter",{min:0,max:100,low:10,high:25,optimum:100,value:b.remainingPercent,"aria-label":`${l} ${b.label} remaining`}),g.jsx("small",{children:Gb(b)})]},b.id)),d?g.jsxs("small",{role:"status",children:["Usage needs refreshing. Last checked ",new Date(s.fetchedAt).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}),"."]}):g.jsx("small",{className:"plan-usage-note",children:"Shared across your account. Updates automatically."})]}):g.jsx("p",{role:"status",children:r.isError?"Could not load usage. Try refreshing.":s?.message??(e?"Loading plan usage…":"Connect to load plan usage.")})]})}function mB(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function pB(e){const t=e?.accounts.find(i=>i.isActive)??null,n=e?.profile??null,a=e?.activeProfile?.handle??null;return{label:(e?.state==="signed_in"?mB(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 fB({connection:e,onOpenProviders:t,account:n,open:a,organizations:r,selectedTeamId:s,onOpenActivity:i,onOpenChange:c,onOpenSettings:d,onOpenWalkthroughs:l,walkthroughsActive:p,onSelectTeam:f,onLogOut:S,railTooltip:b}){const[I,C]=h.useState(null),[P,_]=h.useState(!1),M=h.useRef(null),A=h.useMemo(()=>pB(n),[n]),T=A.label.trim().slice(0,1).toUpperCase();return h.useEffect(()=>{if(!a)return;function y(R){M.current?.contains(R.target)||c(!1)}function w(R){R.key==="Escape"&&c(!1)}return document.addEventListener("pointerdown",y),document.addEventListener("keydown",w),()=>{document.removeEventListener("pointerdown",y),document.removeEventListener("keydown",w)}},[c,a]),g.jsxs("div",{className:"user-auth-footer",ref:M,children:[g.jsxs("button",{type:"button",className:`user-auth-trigger ${a?"active":""}`,"aria-haspopup":"menu","aria-expanded":a,"aria-label":`${A.label} account menu`,"data-rail-tooltip":b,onClick:()=>c(!a),children:[g.jsx("span",{className:"user-auth-avatar","aria-hidden":"true",children:A.image?g.jsx("img",{src:A.image,alt:""}):T?g.jsx("span",{children:T}):g.jsx(Ib,{size:16})}),g.jsx("span",{className:"user-auth-name",children:A.label})]}),a?g.jsxs("div",{className:"user-auth-menu",role:"menu","aria-label":"Account",children:[g.jsxs("div",{className:"user-auth-menu-header",children:[g.jsx("span",{className:"user-auth-menu-avatar","aria-hidden":"true",children:A.image?g.jsx("img",{src:A.image,alt:""}):T?g.jsx("span",{children:T}):g.jsx(Ib,{size:17})}),g.jsxs("span",{className:"user-auth-menu-identity",children:[g.jsx("strong",{children:A.label}),n?.state==="signed_in"&&n.environment?g.jsx("small",{title:n.baseUrl??void 0,children:n.environment==="production"?"Production":n.environment==="staging"?"Staging":n.environment}):null]})]}),r.length>0&&f?g.jsxs("div",{children:[g.jsxs("label",{className:"user-auth-team-picker",children:[g.jsx(ug,{size:15,"aria-hidden":"true"}),g.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),g.jsxs("select",{"aria-label":"Active team","aria-describedby":"account-task-ownership-hint",disabled:I!==null,value:s??"",onChange:async y=>{const w=y.currentTarget.value;C(w);try{await f(w||null)}catch{}finally{C(null)}},children:[g.jsx("option",{value:"",children:"Personal account"}),s&&!r.some(y=>y.teamId===s)?g.jsx("option",{value:s,disabled:!0,children:"Selected workspace unavailable"}):null,r.map(y=>g.jsx("option",{value:y.teamId,children:y.displayName},y.teamId))]})]}),g.jsx("p",{className:"user-auth-task-ownership-hint",id:"account-task-ownership-hint",children:"New tasks use this selection. Existing tasks keep their owner."})]}):null,g.jsx("div",{className:"user-auth-plan-usage",children:["claude-code","codex"].map(y=>g.jsx(uB,{connection:e,provider:y,compact:!0,onOpen:()=>{c(!1),t()}},y))}),g.jsx("div",{className:"user-auth-menu-divider"}),i?g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{c(!1),i()},children:[g.jsx(Uw,{size:15}),g.jsx("span",{children:"Activity"})]}):null,g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{c(!1),d()},children:[g.jsx(Ww,{size:15}),g.jsx("span",{children:"Settings"})]}),g.jsx(iB,{onOpenWalkthroughs:l,walkthroughsActive:p,onCloseAccount:()=>c(!1)}),n?.state==="signed_in"&&S?g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:P,onClick:async()=>{_(!0);try{await S(),c(!1)}catch{}finally{_(!1)}},children:[g.jsx(IU,{size:15}),g.jsx("span",{children:P?"Logging out…":"Log out"})]}):null]}):null]})}function hB({sidebar:e,open:t}){const[n,a]=h.useState(!1),r=[{view:"chat",label:"Home",Icon:Jw},{view:"scheduled",label:"Workflows",Icon:Hw},{view:"outputs",label:"Outputs",Icon:qw},{view:"apps",label:"Apps",Icon:ug},{view:"projects",label:"Projects",Icon:ig}];async function s(c){if(a(!1),e.productArea==="chat"&&e.view===c){c==="chat"&&e.setSidebarOpen(!t);return}const d=c==="chat"?{kind:"chat",sessionId:e.selectedSessionId}:{kind:"view",view:c};await Lt(d)&&(e.setSectionMenuOpen(null),e.setView(c),c==="chat"&&e.setSidebarOpen(!0))}async function i(){await Lt({kind:"view",view:"get-started"})&&(e.setSelectedAppId(null),e.setSelectedProjectId(null),e.setSelectedSessionId(null),e.setSectionMenuOpen(null),e.setView("get-started"))}return g.jsxs("nav",{className:"desktop-navigation-rail","aria-label":"Desktop destinations",children:[g.jsxs("div",{className:"desktop-rail-destinations",children:[g.jsx("button",{type:"button","data-rail-tooltip":"Training","aria-label":"Training",className:`desktop-rail-button desktop-training-entry${e.productArea==="console"?" active":""}`,"aria-expanded":e.productArea==="console"&&t,onClick:()=>{e.productArea==="console"?e.setSidebarOpen(!t):(e.onProductAreaChange("console"),e.setSidebarOpen(!0))},children:g.jsx(VU,{size:19})}),r.map(({view:c,label:d,Icon:l})=>{const p=e.productArea==="chat"&&e.view===c;return g.jsx("button",{type:"button","data-rail-tooltip":d,"aria-label":d,"aria-current":p?"page":void 0,"aria-expanded":c==="chat"?p&&t:void 0,className:`desktop-rail-button${p?" active":""}`,onClick:()=>{s(c)},children:g.jsx(l,{size:19})},c)}),[{view:"team",label:"Team chat",Icon:Su,onOpen:e.onOpenTeamChat},{view:"community",label:"Discover communities",Icon:Fw,onOpen:e.discoverCommunities}].map(({view:c,label:d,Icon:l,onOpen:p})=>g.jsx("button",{type:"button","data-rail-tooltip":d,"aria-label":d,className:`desktop-rail-button${e.productArea==="chat"&&e.view===c?" active":""}`,"aria-current":e.productArea==="chat"&&e.view===c?"page":void 0,onClick:()=>{a(!1),(e.productArea!=="chat"||e.view!==c)&&p()},children:g.jsx(l,{size:19})},c))]}),g.jsx("div",{className:"desktop-rail-account",children:g.jsx(fB,{account:e.account,open:n,onOpenChange:a,connection:e.connection,onOpenProviders:()=>{Lt({kind:"settings",section:"providers"})},railTooltip:n?void 0:"Account",organizations:e.organizations,selectedTeamId:e.selectedTeamId,onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut,walkthroughsActive:e.view==="get-started",onOpenWalkthroughs:()=>{i()},onOpenActivity:()=>{Lt({kind:"settings",section:"usage"})},onOpenSettings:()=>{Lt({kind:"settings",section:"account"})}})})]})}const gB=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function TI(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?AI(a)?"Couldn’t connect to OpenPond.":a:t}function AI(e){const t=e.trim();return gB.some(n=>n.test(t))}const EI=h.createContext(null);function Zb({children:e,showToast:t}){return g.jsx(EI.Provider,{value:t,children:e})}function vB(){return h.useContext(EI)}function Jb(e,t={}){const n=vB(),a=h.useRef(null),r=t.enabled??!0,s=t.fallback??"Something went wrong.",i=t.prefix?.trim()??"",c=e==null||e===""?null:`${i}${i?": ":""}${TI(e,s)}`;h.useEffect(()=>{if(!r||!c){a.current=null;return}a.current!==c&&(a.current=c,n?.(c,"error"))},[r,c,n])}function bB({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(Jb(e?.previewError,{prefix:"Upload preview"}),Jb(e?.error,{prefix:"Cloud setup"}),!e)return null;const r=e.status==="uploading",s=e.status==="ready",i=e.status==="error",c=e.projectKind==="cloud",d=e.preview??null;return g.jsx("div",{className:"git-dialog-backdrop",role:"presentation",children:g.jsxs("section",{className:"git-dialog cloud-setup-dialog",role:"dialog","aria-modal":"true","aria-label":"Set up Cloud coding",children:[g.jsx("button",{className:"git-dialog-close",disabled:r,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:g.jsx(el,{size:14})}),g.jsx("div",{className:"git-dialog-icon",children:s?g.jsx(sd,{size:18}):g.jsx(yu,{size:18})}),g.jsx("h2",{children:s?"Cloud repo ready":"Set up Cloud coding"}),g.jsx("p",{children:s?"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."}),g.jsxs("div",{className:"cloud-setup-summary",children:[g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Project"}),g.jsx("strong",{children:e.projectName})]}),g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Source"}),g.jsx("strong",{children:c?"OpenPond Git":"Local project upload"})]}),g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Branch"}),g.jsx("strong",{children:d?.branch??e.branch??"main"})]}),!c&&g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Cloud project"}),g.jsx("strong",{children:d?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!s&&!c&&g.jsx("div",{className:"cloud-setup-upload-preview",role:"status","aria-live":"polite",children:e.previewLoading?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Calculating upload preview"}),g.jsx("span",{children:"Checking tracked and unignored files before anything is pushed."})]}):e.previewError?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Preview unavailable"}),g.jsx("span",{children:"Close and reopen setup to try the preview again."})]}):d?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:d.initializedEmptyProject?"Will initialize an empty project":`Will upload ${d.fileCount} files`}),g.jsx("span",{children:Qb({byteCount:d.byteCount,skippedCount:d.skippedCount,headCommit:d.headCommit,targetProjectName:d.targetProjectName})})]}):g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:"Upload preview pending"}),g.jsx("span",{children:"File count, byte count, and skipped files will appear here before upload."})]})}),r&&g.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[g.jsx(cg,{className:"cloud-setup-spinner",size:16}),g.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),s&&e.upload&&g.jsxs("div",{className:"cloud-setup-upload-result",children:[g.jsx("strong",{children:e.upload.initializedEmptyProject?"Initialized empty project":`Uploaded ${e.upload.fileCount} files`}),g.jsx("span",{children:Qb({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),s&&e.setupUrl&&g.jsxs("div",{className:"cloud-setup-next",children:[e.projectUrl?g.jsxs("span",{children:["Your repo is ready here:"," ",g.jsxs("a",{href:e.projectUrl,target:"_blank",rel:"noreferrer",onClick:l=>fp(l,e.projectUrl,n,{newTab:!0}),children:["Project page",g.jsx(sp,{size:13})]})]}):g.jsx("span",{children:"Your repo is ready. Next step:"}),g.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:l=>fp(l,e.setupUrl,n),children:["Setup the Cloud sandbox",g.jsx(sp,{size:13})]})]}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{className:"git-dialog-secondary",disabled:r,type:"button",onClick:t,children:s?"Done":"Cancel"}),s?e.setupUrl?g.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:l=>fp(l,e.setupUrl,n),children:["Open setup",g.jsx(sp,{size:13})]}):null:g.jsx("button",{className:"git-dialog-primary",disabled:r,type:"button",onClick:a,children:r?"Uploading":i?"Try again":c?"Show setup link":"Upload source"})]})]})})}function fp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function yB(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 Qb({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const r=[yB(e),`${t} skipped`],s=SB(n);return s&&r.push(`local ${s}`),r.push(a),r.join(" · ")}function SB(e){const t=e?.trim();return t?t.slice(0,7):null}const xB=h.lazy(()=>fs(()=>import("./CommandMenu-Ux2yOHAc.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.CommandMenu}))),kB=h.lazy(()=>fs(()=>import("./SettingsView-DCKVrfjj.js"),__vite__mapDeps([6,1,2,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])).then(e=>({default:e.SettingsView}))),wB=h.lazy(()=>fs(()=>import("./NewProjectDialog-RfTZTHxl.js"),__vite__mapDeps([26,1,2,11,17,27])).then(e=>({default:e.NewProjectDialog}))),IB=h.lazy(()=>fs(()=>import("./WorkspaceGitDialogs-CwVoiDQ2.js"),__vite__mapDeps([28,1,2,14,15,29,25])).then(e=>({default:e.CommitDialog}))),_B=h.lazy(()=>fs(()=>import("./WorkspaceGitDialogs-CwVoiDQ2.js"),__vite__mapDeps([28,1,2,14,15,29,25])).then(e=>({default:e.BranchDialog})));function CB({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:r,onError:s,onToast:i,onBack:c,onOpenSourceSession:d,onStartRefinerAuthoring:l,onAcceptEvaluationReview:p,onOpenSkill:f,onOpenExtension:S,teamChatCurrentUserId:b,teamChatEnabled:I,teamChatNotificationMode:C,teamChatThreads:P,onTeamChatNotificationModeChange:_,onTeamChatThreadMuteChange:M,diffPanelWidth:A,diffPanelResizing:T,diffPanelExpanded:y,onDiffPanelResizeStart:w,onDiffPanelExpandedChange:R}){return g.jsx(h.Suspense,{fallback:null,children:g.jsx(kB,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:r,onError:s,onToast:i,onBack:c,onOpenSourceSession:d,onStartRefinerAuthoring:l,onAcceptEvaluationReview:p,onOpenSkill:f,onOpenExtension:S,teamChatCurrentUserId:b,teamChatEnabled:I,teamChatNotificationMode:C,teamChatThreads:P,onTeamChatNotificationModeChange:_,onTeamChatThreadMuteChange:M,diffPanelWidth:A,diffPanelResizing:T,diffPanelExpanded:y,onDiffPanelResizeStart:w,onDiffPanelExpandedChange:R})})}function RB({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:r,commitIncludeUnstaged:s,commitMessage:i,commitNextStep:c,canPublishOpenPondProject:d,expandProject:l,newProjectBusy:p,newProjectDialogOpen:f,newProjectDirectory:S,newProjectMode:b,newProjectName:I,newProjectPath:C,projectRows:P,query:_,searchOpen:M,visibleWorkspaceDiff:A,visibleWorkspaceState:T,workspaceBusy:y,appDispatch:w,beginNewChat:R,openDefaultsSettingsFromBranchDialog:O,setBranchDialogName:z,setBranchDialogOpen:$,setCommitDialogOpen:V,setCommitDraft:Y,setCommitIncludeUnstaged:re,setCommitMessage:ee,setCommitNextStep:H,setNewProjectDialogOpen:F,setNewProjectName:J,setNewProjectPath:K,setQuery:B,setSearchOpen:ne,submitCommitDialog:G,submitCreateWorkspaceBranch:te,submitNewProjectDialog:oe}){return g.jsxs(g.Fragment,{children:[M&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(xB,{open:M,query:_,projects:P,sessions:e,onQueryChange:B,onClose:()=>{ne(!1),B("")},onNewChat:()=>{ne(!1),B(""),R()},onOpenProject:be=>{w({type:"selectProject",projectId:be.id}),w({type:"patch",patch:{searchOpen:!1,query:""}}),l(be.id)},onOpenSession:be=>{w({type:"selectSession",sessionId:be.id,appId:be.appId,projectId:be.workspaceKind==="local_project"&&be.workspaceId?ct("local",be.workspaceId):null}),w({type:"patch",patch:{searchOpen:!1,query:""}})}})}),f&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(wB,{open:f,mode:b,name:I,path:C,directory:S,busy:p,onNameChange:J,onPathChange:K,onClose:()=>{p||F(!1)},onSubmit:oe})}),a&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(IB,{open:a,branch:T?.currentBranch??null,filesChanged:A?.filesChanged??T?.changedFilesCount??0,additions:A?.additions??0,deletions:A?.deletions??0,message:i,includeUnstaged:s,nextStep:c,draft:r,busy:y,canPush:!!T?.remoteUrl,canPublish:d,onMessageChange:ee,onIncludeUnstagedChange:re,onNextStepChange:H,onDraftChange:Y,onClose:()=>{y||V(!1)},onSubmit:G})}),n&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(_B,{open:n,branchName:t,busy:y,onBranchNameChange:z,onSetPrefix:O,onClose:()=>{y||$(!1)},onSubmit:te})})]})}function jI({toast:e,onDismiss:t}){if(!e)return null;const n=!!(e.actionLabel&&e.onAction);return g.jsxs("div",{className:`app-toast ${e.tone} ${e.placement??"bottom-right"}`,role:e.tone==="error"?"alert":"status","aria-live":"polite",children:[g.jsx("span",{className:"app-toast-message",children:e.message}),n&&g.jsx("div",{className:"app-toast-actions",children:g.jsx("button",{type:"button","aria-label":e.actionLabel,onClick:()=>{t(),e.onAction?.()},children:e.actionLabel})})]})}async function Bl(e,t,n){if(t.scope!==e.scope)throw new Error("Review workspace changed. Reload the assignment.");return L(e.connection,`/v1/human-review?location=${e.location}`,{method:"POST",body:JSON.stringify(_O.parse(t)),signal:n})}function Yb(e,t,n){const a=kx.parse(e);if(a.scope!==t.scope||a.id!==n)throw new Error("Review response identity differs from the requested assignment.");return a}const PB={inbox:async(e,t,n)=>TB(await Bl(e,{...t,endpoint:"inbox",scope:e.scope},n),e),get:async(e,t,n)=>Yb(await Bl(e,{endpoint:"get",scope:e.scope,id:t},n),e,t),inspect:async(e,t,n,a,r)=>AB(await Bl(e,{endpoint:"inspect",scope:e.scope,id:t,...n===void 0?{}:{slot:n},...a?{afterId:a}:{}},r),t),command:async(e,t)=>Yb(await Bl(e,{endpoint:"command",scope:e.scope,command:t}),e,t.id)};function TB(e,t){const n=mO.parse(e);if(n.items.some(a=>a.scope!==t.scope))throw new Error("Inbox response belongs to another workspace.");return n}function AB(e,t){const n=CO.parse(e);if(n.some(a=>a.reviewId!==t))throw new Error("Evidence response belongs to another assignment.");return n}function EB({context:e,onOpen:t}){const[n,a]=h.useState(null);return h.useEffect(()=>{const r=new AbortController;let s=0;async function i(){const d=++s;try{const l=await PB.inbox(e,{view:"mine",status:"active",limit:1},r.signal);!r.signal.aborted&&d===s&&a(l.actionCount)}catch{!r.signal.aborted&&d===s&&a(null)}}a(null),i();const c=window.setInterval(()=>{document.visibilityState==="visible"&&i()},15e3);return window.addEventListener("human-review-changed",i),()=>{r.abort(),window.clearInterval(c),window.removeEventListener("human-review-changed",i)}},[e.scope,e.actorId,e.location,e.connection]),g.jsxs("button",{type:"button",className:"titlebar-icon human-review-inbox-control",title:n?`Inbox · ${n} actions`:"Inbox","aria-label":n?`Inbox, ${n} actions`:"Inbox",onClick:t,children:[g.jsx(mg,{size:17,"aria-hidden":"true"}),n?g.jsx("span",{className:"human-review-inbox-count","aria-hidden":"true",children:n>99?"99+":n}):null]})}function jB({connection:e,teamId:t,actorId:n,projectId:a}){if(!e||!t||!n)return null;const r=()=>{Fs(wa("inbox",null,{area:"console",projectId:a}))};return g.jsx(EB,{context:{connection:e,scope:t,actorId:n,location:"hosted"},onOpen:r})}const nl=h.createContext(null);function MB({children:e}){const[t,n]=h.useState(null),[a,r]=h.useState(null),[s,i]=h.useState(null),c=h.useMemo(()=>({title:t,actions:a,activity:s,setTitle:n,setActions:r,setActivity:i}),[t,a,s]);return g.jsx(nl.Provider,{value:c,children:e})}function jG({children:e}){return g.jsx(nl.Provider,{value:null,children:e})}function OB({children:e,className:t=""}){const n=h.useContext(nl);return g.jsx("div",{ref:n?.setTitle,className:`page-chrome-title-target ${t}`,children:e?g.jsx("div",{className:"page-chrome-fallback",children:e}):null})}function $B({className:e=""}){const t=h.useContext(nl);return g.jsx("div",{ref:t?.setActions,className:e})}function MG({title:e,actions:t,fallback:n,children:a}){const r=h.useContext(nl);return r?g.jsxs(g.Fragment,{children:[r.title?Dd.createPortal(g.jsx("div",{className:"page-chrome-title",children:e}),r.title):null,r.actions&&t?Dd.createPortal(t,r.actions):null,a]}):n??g.jsxs("header",{children:[e,t]})}const NB=h.lazy(()=>fs(()=>import("./WorkspaceEnvironmentMenu-BVHAhwnJ.js"),__vite__mapDeps([30,1,2,21,27,12,15,31,29,32])).then(e=>({default:e.WorkspaceEnvironmentMenu})));function DB({sidebarOpen:e,sidebarAvailable:t=!0,title:n,breadcrumbs:a,backAction:r,workspaceName:s,workspaceId:i,busy:c,workspaceState:d,workspaceKind:l,selectedApp:p,selectedProject:f,workspaceDiff:S,managedWorkspace:b,workspaceBusy:I,defaultTeamId:C,activityActorId:P,activityProjectId:_,showDiffControls:M,diffPanelOpen:A,terminalOpen:T,rightSidebarAvailable:y=!1,rightSidebarOpen:w=!1,onToggleDiffPanel:R,onToggleRightSidebar:O,onOpenSearch:z,onToggleTerminal:$,onRunTerminalCommand:V,onWorkspaceToolAction:Y,onOpenCommitDialog:re,onWorkspaceBranchChange:ee,onWorkspaceBranchCreate:H,connection:F,onBootstrap:J,onOpenSandboxWorkspace:K,onShowSidebar:B,platform:ne,showWorkspaceControls:G=!0}){const te=S?.filesChanged??0;return g.jsxs("header",{className:"app-titlebar",children:[g.jsxs("div",{className:"titlebar-left",children:[t&&!e&&g.jsx("button",{className:"titlebar-icon",title:"Show sidebar",onClick:B,children:g.jsx(Vw,{size:16})}),r?g.jsx("button",{className:"titlebar-icon",type:"button","aria-label":r.label,title:r.label,onClick:r.onSelect,children:g.jsx(OH,{size:16})}):null,g.jsx(OB,{children:a?.length?g.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((oe,be)=>{const me=be===a.length-1;return g.jsxs("div",{className:"titlebar-breadcrumb-item",children:[oe.onSelect&&!me?g.jsx("button",{type:"button",onClick:oe.onSelect,children:oe.label}):g.jsx("strong",{children:oe.label}),!me&&g.jsx(ps,{size:14})]},`${oe.label}-${be}`)})}):g.jsxs("div",{className:"titlebar-title",children:[g.jsx("strong",{children:n}),s&&g.jsx("span",{children:s})]})})]}),g.jsxs("div",{className:"titlebar-right",children:[g.jsx($B,{className:"page-chrome-actions"}),g.jsx(jB,{connection:F,teamId:C??null,actorId:P??null,projectId:_??null}),G&&g.jsxs("div",{className:"titlebar-actions",children:[g.jsx(h.Suspense,{fallback:null,children:g.jsx(NB,{mode:"topbar",busy:c,workspaceState:d,workspaceId:i,workspaceKind:l,selectedApp:p,selectedProject:f,workspaceBusy:I,defaultTeamId:C,workspaceDiff:S,managedWorkspace:b,showDiffControls:M,diffPanelOpen:A,onToggleDiffPanel:R,onRunTerminalCommand:V,onWorkspaceToolAction:Y,onOpenCommitDialog:re,onWorkspaceBranchChange:ee,onWorkspaceBranchCreate:H,connection:F,onBootstrap:J,onOpenSandboxWorkspace:K})}),g.jsx("button",{type:"button",className:"titlebar-icon",title:"Search chats and projects","aria-label":"Search chats and projects",onClick:z,children:g.jsx(TU,{size:16})}),g.jsx("button",{type:"button",className:`titlebar-icon ${T?"active":""}`,title:`${T?"Hide":"Show"} terminal`,"aria-label":`${T?"Hide":"Show"} terminal`,"aria-pressed":T,onClick:$,children:g.jsx(Gw,{size:16})}),M&&g.jsx("button",{type:"button",className:`topbar-diff-button ${w?"active":""}`,title:`${w?"Hide":"Show"} sidebar${te?`, ${te} changed files`:""}`,"aria-label":`${w?"Hide":"Show"} sidebar`,"aria-pressed":w,onClick:R,children:g.jsx(df,{size:16})})]}),y&&O&&!M?g.jsx("div",{className:"titlebar-actions",children:g.jsx("button",{type:"button",className:`topbar-diff-button ${w?"active":""}`,title:`${w?"Hide":"Show"} sidebar`,"aria-label":`${w?"Hide":"Show"} sidebar`,"aria-pressed":w,onClick:O,children:g.jsx(df,{size:16})})}):null,g.jsx(qU,{platform:ne})]})]})}function LB(){const[e,t]=h.useState(null),n=h.useRef(null),a=h.useCallback(s=>new Promise(i=>{n.current?.resolve(!1);const c={...s,cancelLabel:s.cancelLabel??"Cancel",tone:s.tone??"default",resolve:i};n.current=c,t(c)}),[]),r=h.useCallback(s=>{const i=n.current;n.current=null,t(null),i?.resolve(s)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:r}}function zB({state:e,onResolve:t}){const n=h.useId(),a=h.useId();if(h.useEffect(()=>{if(!e)return;function s(i){i.key==="Escape"&&t(!1)}return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[t,e]),!e)return null;const r=e.tone==="danger"?"git-dialog-primary danger":"git-dialog-primary";return g.jsx("div",{className:"git-dialog-backdrop",role:"presentation",onMouseDown:()=>t(!1),children:g.jsxs("section",{className:"git-dialog project-confirm-dialog",role:"alertdialog","aria-modal":"true","aria-labelledby":n,"aria-describedby":a,onMouseDown:s=>s.stopPropagation(),children:[g.jsx("h2",{id:n,children:e.title}),g.jsx("p",{id:a,children:e.body}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{type:"button",className:"git-dialog-secondary",onClick:()=>t(!1),children:e.cancelLabel}),g.jsx("button",{type:"button",className:r,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function HB(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=LB();return{confirmProjectAction:h.useCallback(r=>e({tone:"danger",...r}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function UB({state:e,onResolve:t}){return g.jsx(zB,{state:e,onResolve:t})}const zd=new Map,qB=(e,t,n)=>{const a=zd.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,zd.set(e,a)};function BB({children:e,id:t}){return g.jsx(h.Profiler,{id:t,onRender:qB,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...zd.entries()].map(([e,t])=>[e,{...t}])),reset:()=>zd.clear()});const FB=h.lazy(()=>fs(()=>import("./MainPane-5DTtwVCk.js").then(e=>e.q),__vite__mapDeps([33,1,2,9,14,34,31,11,12,35])).then(e=>({default:e.MainPane})));function VB({className:e,style:t,sidebar:n,topBar:a,mainPane:r,cloudSetup:s,projectConfirm:i,lazyPanels:c,toast:d}){return g.jsx(MB,{children:g.jsxs("div",{className:e,style:t,children:[g.jsx(hB,{sidebar:n,open:a.sidebarOpen}),a.sidebarAvailable!==!1?g.jsxs(BB,{id:"sidebar",children:[g.jsx(rB,{...n,open:a.sidebarOpen}),a.sidebarOpen?g.jsx("div",{className:"sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",onPointerDown:n.onSidebarResizeStart}):null]}):null,g.jsxs("div",{className:"content-shell",children:[g.jsx(DB,{...a}),g.jsx(h.Suspense,{fallback:g.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:g.jsx(FB,{...r})})]}),g.jsx(bB,{...s}),g.jsx(UB,{...i}),g.jsx(RB,{...c}),g.jsx(jI,{...d})]})})}function KB({settings:e,toast:t}){return g.jsxs(g.Fragment,{children:[g.jsx(CB,{...e}),g.jsx(jI,{...t})]})}const pd="OpenPond".split("");function WB({visibleLetterCount:e=pd.length}){const t=pd.slice(0,Math.max(0,Math.min(e,pd.length)));return g.jsxs("div",{className:"app-splash-lockup",children:[g.jsx("div",{className:"app-splash-mark",children:g.jsx("img",{alt:"OpenPond",className:"app-splash-logo",decoding:"async",src:Pg})}),g.jsx("span",{"aria-hidden":"true",className:`app-splash-wordmark${t.length>0?" is-visible":""}`,children:t.map((n,a)=>g.jsx("span",{className:"app-splash-letter",children:n},`${n}-${a}`))})]})}const hp=pd.length,GB=520,ZB=240;function Xb(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function JB({startup:e}){const[t,n]=h.useState(()=>Xb()?hp:0);return h.useEffect(()=>{if(Xb()){n(hp);return}const a=Array.from({length:hp},(r,s)=>window.setTimeout(()=>n(s+1),GB+ZB*s));return()=>{a.forEach(r=>window.clearTimeout(r))}},[]),g.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[g.jsx(WB,{visibleLetterCount:t}),g.jsx("span",{className:"app-splash-status",children:e.label})]})}const Ag=5e3;function ai(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const r of[...e,...t])n.has(r.id)||(n.add(r.id),a.push(r));return a}function Dr(e,t,n=Ag){return fd(ai(e,t),n)}function fd(e,t=Ag){return e.length<=t?e:e.slice(e.length-t)}function QB(e,t){if(t.length===0)return fd(e);if(e.length===0)return fd(t);const n=new Map;let a=0;for(const r of[...e,...t])n.has(r.id)||n.set(r.id,{event:r,index:a}),a+=1;return fd([...n.values()].sort((r,s)=>XB(r,s)).map(({event:r})=>r))}function wf(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 YB(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function XB(e,t){const n=e.event.sequence,a=t.event.sequence;if(typeof n=="number"&&typeof a=="number"){const i=n-a;if(i!==0)return i}const r=Date.parse(e.event.timestamp),s=Date.parse(t.event.timestamp);if(Number.isFinite(r)&&Number.isFinite(s)){const i=r-s;if(i!==0)return i}return e.index-t.index}function ey(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 eF(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function tF(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 ty(e){return e==="codex"||e==="claude-code"}function nF(e){return e==="openpond"}function MI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=tj.safeParse(n.data);if(a.success)return a.data}return null}function OI(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,r=Math.min(100,Math.round(e.snapshot.percentFull)),s=`${r}% full`,i=`${ey(n)} / ${ey(a)} tokens used`,c=ty(e.provider)?`Context and compaction are managed by ${e.provider==="claude-code"?"Claude Code":"Codex app-server"}.`:tF(e.preferences,r);return{usedTokens:n,maxTokens:a,percent:r,summary:s,tokensLabel:i,detail:c,tooltip:`Context window: ${s} ${i}. ${c}`,tone:eF(r)}}if(ty(e.provider)){const n=e.provider==="claude-code"?"Claude Code":"Codex app-server",a=`Context is managed by ${n}.`;return{usedTokens:0,maxTokens:null,percent:null,summary:"Managed externally",tokensLabel:n,detail:a,tooltip:`Context window: ${a}`,tone:"unknown"}}if(!nF(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 Eg(e){let t=!1;const n=$I(e);for(let a=e.length-1;a>=0;a-=1){const r=e[a];if(aF(r)){t=!0;continue}const s=fi(r?.data);if(!(r?.name!=="diagnostic"||!s)){if(s.kind==="thread_goal_cleared")return null;if(s.kind==="thread_goal"){const i=jg(fi(s.goal),Qn(s.provider),n);if(i){const c=Dc(i);return t&&c.tone==="active"?null:c}}if(s.kind==="goal_context"){const i=DI(r.output??"",Qn(s.provider)??"codex",n);if(i){const c=Dc(i);return t&&c.tone==="active"?null:c}}}}return null}function Hd(e){const t=$I(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],r=fi(a?.data);if(!(a?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared"&&r.synthetic!==!0)return null;if(r.kind==="thread_goal"){const s=jg(fi(r.goal),Qn(r.provider),t);if(!s)continue;const i=Dc(s);return i.tone==="active"?i:null}if(r.kind==="goal_context"){const s=DI(a.output??"",Qn(r.provider)??"codex",t);if(!s)continue;const i=Dc(s);return i.tone==="active"?i:null}}}return null}function gp(e){const t=fi(fi(e)?.codexGoalRuntime),n=jg(t,Qn(t?.provider)??"codex");if(!n)return null;const a=Dc(n);return a.tone==="active"?a:null}function aF(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function Dc(e){const t=LI(e.status),n=UI(e.timeUsedSeconds),a=`Goal ${n}`,r=e.tokensUsed===null?null:e.tokenBudget===null?`${vp(e.tokensUsed)} tokens`:`${vp(e.tokensUsed)} / ${vp(e.tokenBudget)} tokens`,s=r?`${e.statusLabel} · ${r}`: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:s,tooltip:`Goal runtime: ${qI(e.timeUsedSeconds)}. ${s}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function rF(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=NI(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,r=UI(a);return{...e,timeUsedSeconds:a,timeLabel:r,label:`Goal ${r}`,tooltip:`Goal runtime: ${qI(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function jg(e,t=null,n=null){if(!e)return null;const a=Qn(e.objective)??"Active goal",r=Qn(e.status)??"active";if((If(t)??If(Qn(e.provider)))!=="codex")return null;const i=n??Qn(e.updatedAt)??Qn(e.updated_at)??null,c=Oo(e.timeUsedSeconds)??Oo(e.time_used_seconds)??0,d=Qn(e.activeSinceAt)??Qn(e.active_since_at),l=LI(r).tone==="active"?NI(d??Qn(e.createdAt)??Qn(e.created_at),i):0,p=d?c+l:Math.max(c,l),f=Oo(e.tokensUsed)??Oo(e.tokens_used),S=Oo(e.tokenBudget)??Oo(e.token_budget);return{objective:a,status:r,statusLabel:HI(r),timeUsedSeconds:Math.max(0,Math.floor(p)),tokensUsed:f===null?null:Math.max(0,Math.floor(f)),tokenBudget:S===null?null:Math.max(0,Math.floor(S)),observedAt:i}}function $I(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 NI(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 DI(e,t=null,n=null){if(!e.trim()||If(t)!=="codex")return null;const a=zI(e,"Status")??"active",r=Qi(e,"Tokens used"),s=Qi(e,"Token budget"),i=Qi(e,"Time used seconds")??Qi(e,"Time spent pursuing goal")??Qi(e,"Elapsed seconds")??0;return{objective:ny(e,"objective")??ny(e,"untrusted_objective")??"Active goal",status:a,statusLabel:HI(a),timeUsedSeconds:Math.max(0,Math.floor(i)),tokensUsed:r,tokenBudget:s,observedAt:n}}function LI(e){switch(sF(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 sF(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function zI(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function Qi(e,t){const n=zI(e,t);if(!n)return null;const a=n.replace(/,/g,""),r=/-?\d+(?:\.\d+)?/.exec(a);if(!r)return null;const s=Number(r[0]);return Number.isFinite(s)?s:null}function ny(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function HI(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function UI(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 qI(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 vp(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${ay(n,2)}M`:n<100?`${ay(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 ay(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function fi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Qn(e){return typeof e=="string"&&e.trim()?e.trim():null}function If(e){return e?.trim().toLowerCase()||null}function Oo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const oF=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),iF=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function _f(e){const t=BI(e);return t?uF(t):null}function BI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=dF(gF(n.data));if(a)return a}return null}function cF(e){if(e.events)return BI(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 lF(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 dF(e){const t=qc.safeParse(e?.createImproveRun);return t.success?t.data:null}function uF(e){const t=mF(e);if(!t)return null;const n=pF(e.createdAt,e.updatedAt),a=e.blockedReason??fF(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:hF(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function mF(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return oF.has(t)?{tone:"active",actionLabel:`${n} running`}:iF.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 pF(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 fF(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function hF(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 gF(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function FI(e,t){if(!t)return null;const n=new Map,a=[];for(const T of e){if(!T.name.startsWith("subagent."))continue;const y=yF(T);y&&a.push(y);const w=bF(T);w?.parentSessionId===t&&n.set(w.id,w)}if(n.size===0)return null;const r=[...n.values()].sort((T,y)=>$o(y).localeCompare($o(T))),s=r.filter(T=>T.status==="queued"||T.status==="running"),i=r.filter(T=>T.status==="completed"),c=r.filter(T=>T.status==="failed"),d=r.filter(T=>T.status==="cancelled"),l=r.filter(T=>T.status==="needs_resume"),p=[...i,...c,...d].sort((T,y)=>$o(y).localeCompare($o(T))),f=r.reduce((T,y)=>{const w=hi(y.metadata?.usage);return T.totalTokens+=Vl(w?.totalTokens),T.promptTokens+=Vl(w?.promptTokens),T.completionTokens+=Vl(w?.completionTokens),T.requestCount+=Vl(w?.requestCount),T},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),S=r.flatMap(T=>VI([...T.report?.blockers??[],T.error,T.progress.currentBlocker]).map(y=>({runId:T.id,roleId:T.roleId,status:T.status,message:y}))),b=r.flatMap(T=>KI([...T.report?.artifacts??[],T.report?.patchRef,T.report?.diffRef,...T.progress.patchRefs]).map(y=>({...y,runId:T.id,roleId:T.roleId}))),I=p.map(T=>vF(T,a)),C=r[0]??null,P=C?{runId:C.id,roleId:C.roleId,status:C.status,message:C.progress.latestMeaningfulActivity||C.report?.summary||C.objective,updatedAt:$o(C)}:null,_=s.length>0?`${s.length} ${s.length===1?"child":"children"} running`:`${p.length} ${p.length===1?"child":"children"} finished`,M=[s.length?`${s.length} active`:null,i.length?`${i.length} completed`:null,c.length?`${c.length} failed`:null,d.length?`${d.length} cancelled`:null,l.length?`${l.length} paused`:null].filter(Boolean).join(" · "),A=P?`${kF(P.roleId)}: ${P.message}`:"";return{sessionId:t,runs:r,activeRuns:s,completedRuns:i,failedRuns:c,cancelledRuns:d,needsResumeRuns:l,terminalRuns:p,latestRun:C,latestMeaningfulUpdate:P,activeCount:s.length,completedCount:i.length,failedCount:c.length,cancelledCount:d.length,needsResumeCount:l.length,terminalCount:p.length,usage:f,blockers:S,evidenceRefs:b,finalResults:I,testsRunCount:r.reduce((T,y)=>T+y.progress.validationAttempts.length,0),label:_,tooltip:[M,A].filter(Boolean).join(". ")}}function vF(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:KI([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:VI([...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:SF(e),updatedAt:$o(e)}}function bF(e){const t=hi(e.data),n=[t?.run,hi(t?.message)?.run];for(const a of n){const r=kS.safeParse(a);if(r.success)return r.data}return null}function yF(e){const t=PE.safeParse(hi(e.data)?.message);return t.success?t.data:null}function SF(e){const t=hi(hi(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Fl(t.reason),retainedAt:Fl(t.retainedAt),expiresAt:Fl(t.expiresAt),retentionDays:xF(t.retentionDays),trigger:Fl(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function $o(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function VI(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function KI(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function hi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Vl(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function xF(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function kF(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const Cf=[];function Rf(e,t){return WI(e,t,null)}function WI(e,t,n){const a=n&&RF(n.events,e)?IF(n.indexes,n.events.length,e):wF(e),r=CF(t);return{...a,...r}}function wF(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 _F(t)}function IF(e,t,n){const a=new Map(e.eventsBySessionId),r=new Map(e.latestContextUsageBySessionId),s=new Map(e.latestGoalRuntimeBySessionId),i=new Map(e.latestSubagentRuntimeBySessionId),c=new Set(e.activeGoalSessionIds),d=new Set(e.activeSubagentSessionIds),l=new Set;for(let p=t;p<n.length;p+=1){const f=n[p];if(!f.sessionId)continue;if(l.has(f.sessionId)){a.get(f.sessionId).push(f);continue}const S=a.get(f.sessionId);a.set(f.sessionId,S?[...S,f]:[f]),l.add(f.sessionId)}for(const p of l){const f=a.get(p)??Cf,S=MI(f);S?r.set(p,S):r.delete(p);const b=ZI(f);b?(s.set(p,b),b.tone==="active"?c.add(p):c.delete(p)):(s.delete(p),c.delete(p));const I=FI(f,p);I?(i.set(p,I),GI({sessionEvents:f,sessionId:p,latestGoalRuntimeBySessionId:s,activeGoalSessionIds:c}),I.activeCount>0?d.add(p):d.delete(p)):(i.delete(p),d.delete(p))}return{eventsBySessionId:a,latestContextUsageBySessionId:r,latestGoalRuntimeBySessionId:s,latestSubagentRuntimeBySessionId:i,activeGoalSessionIds:c,activeSubagentSessionIds:d}}function _F(e){const t=new Map,n=new Map,a=new Map,r=new Set,s=new Set;for(const[i,c]of e){const d=MI(c);d&&t.set(i,d);const l=ZI(c);l&&(n.set(i,l),l.tone==="active"&&r.add(i))}for(const[i,c]of e){const d=FI(c,i);d&&(a.set(i,d),GI({sessionEvents:c,sessionId:i,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:r}),d.activeCount>0&&s.add(i))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:r,activeSubagentSessionIds:s}}function GI(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=Hd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function ZI(e){return _f(e)??Eg(e)??Hd(e)}function CF(e){const t=new Map,n=new Map,a=new Map,r=new Map;for(const s of e){t.set(s.id,s);const i=n.get(s.status);if(i?i.push(s):n.set(s.status,[s]),s.status!=="pending")continue;const c=a.get(s.sessionId);c?c.push(s):a.set(s.sessionId,[s]);const d=r.get(s.sessionId);(!d||ry(s.createdAt)>ry(d.createdAt))&&r.set(s.sessionId,s)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:r}}function RF(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 al(e,t){return t?e.eventsBySessionId.get(t)??Cf:Cf}function JI(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function QI(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function PF(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function TF(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function ry(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function AF(e,t){return e?.conversationId===t}function EF(e,t){return e?.id===t?null:e}function jF(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("/"),r=a>=0?n.relativePath.slice(0,a):"";for(const s of n.resourceFiles)t.add(r?`${r}/${s}`:s)}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 MF(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function OG(e,t){return e.profiles.find(n=>MF(n.ref)===t)?.ref??null}function OF(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function $G(e,t){return e.profiles.find(n=>OF(n.ref,t))?.state??null}function $F(e,t){const n=new Map(Kj.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 r of a.skills)r.validationStatus!=="valid"||n.has(r.name)||n.set(r.name,{name:r.name,description:r.description,path:r.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:r.charCount,sourceHash:r.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:r.resourceFiles});return[...n.values()].sort((a,r)=>a.name.localeCompare(r.name))}function NF(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 NG(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 YI="openpond:last-chat-task-mode";function DF(e,t){return e==="labs"?"models":"chat"}function LF(e){try{return e.getItem(YI)==="work"?"work":"chat"}catch{return"chat"}}function Mg(){if(typeof window>"u")return"chat";try{return LF(no)}catch{return"chat"}}function zF(e,t){try{e.setItem(YI,t==="chat"?"chat":"work")}catch{}}function HF(e){if(!(typeof window>"u"))try{zF(no,e)}catch{}}const UF="uploaded to a different account";function XI(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(r=>r.id===n.projectId&&r.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function Ra(e,t){const n=XI(e,t);return n.state==="confirmed"?n.cloudProject:null}function qF(e,t){return XI(e,t).state==="different_account"?UF:null}function Sr(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function e1(e={}){return{...e,workspaceTarget:"hybrid"}}function BF(e={}){return{...e,workspaceTarget:"local"}}function xr(e){return e?.metadata?.workspaceTarget==="hybrid"}function FF(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function t1({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,r=e?Ra(n,e):null,s=t?.id??r?.id??(e?null:a?.projectId??null),i=t?.teamId??r?.teamId??(e?null:a?.teamId??null);return!s||!i?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:s,cloudTeamId:i,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??r?.name??a?.projectName??n?.name??"Hybrid workspace"}}function n1({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:e1(),cwd:n.cwd,title:a}}function VF(e){return h.useEffect(()=>{const t=uI(e.selectedSession);!t||e.composerDraftStore.getSnapshot()||e.composerDraftStore.set(t)},[e.composerDraftStore,e.selectedSession?.id]),h.useCallback(async t=>{const n=t.trim();if(!e.connection||!n||e.activeExperience==="chat")return!1;const a=wq(n);try{let r;const s=e.selectedSession;if(s&&$c(s))r=await Z.patchSession(e.connection,s.id,{title:a,metadata:dp(s.metadata,n)}),e.setSessions(i=>i.map(c=>c.id===r.id?r:c));else{const i=s?.metadata?.workspaceTarget==="hybrid"?"hybrid":s?.metadata?.workspaceTarget==="local"?"local":null,c=s?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),d=s?.modelRef??(c==="openpond"?{providerId:"openpond",modelId:oi}:{providerId:c,modelId:e.activeModel}),l=i?{workspaceTarget:i}:!s&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let p;if(!s&&e.workspaceTarget==="hybrid"){const f=t1({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(f.kind!=="ready")throw new Error(f.message);const S=n1({modelRef:d,provider:c,target:f,title:a});p={...S,experience:"work",metadata:dp(S.metadata,n)}}else p={experience:"work",provider:c,modelRef:d,openPondCommandAccessMode:s?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:s?.appId??null,appName:s?.appName??null,workspaceKind:s?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:s?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:s?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:s?.localProjectId??e.selectedProject?.id??null,cloudProjectId:s?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:s?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:s?.cwd??e.selectedProject?.workspacePath??null,metadata:dp(l,n),title:a};r=await Z.createSession(e.connection,p),e.setSessions(f=>[r,...f])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(r){return e.showToast(r instanceof Error?r.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 KF=[];function WF({primary:e,secondary:t}){const[n,a]=h.useState(null),r=h.useRef(new Set),[s,i]=h.useState(!1),[c,d]=h.useState(null),l=tq(),p=l?.kind==="models"&&["home","inbox","datasets","graders","experiments"].includes(l.route.page),{composerDraftStore:f,appDispatch:S,pendingTerminalCommand:b,setPendingTerminalCommand:I,terminalTabs:C,setTerminalTabs:P,trainingDetailTasksetId:_,setTrainingDetailTasksetId:M,mentionedAppId:A,setMentionedAppId:T,cloudSetupDialog:y,setCloudSetupDialog:w,rightPanelTabRequest:R,workspaceDiffPanelViewState:O,mainComposerFocusRequestId:z,requestMainComposerFocus:$,projectConfirmDialog:V,resolveProjectConfirmDialog:Y,query:re,searchOpen:ee,archivedChatsOpen:H,sectionMenuOpen:F,cloudProjectsExpanded:J,sidebarOpen:K,view:B,selectedAppId:ne,selectedProjectId:G,selectedSessionId:te,codexPermissionMode:oe,codexReasoningEffort:be,busy:me,diffPanelOpen:Re,diffPanelExpanded:Q,rightPanelMode:xe,activeExperience:je,changeNewExperience:De,terminalOpen:He,settingsSection:Ie,newProjectDialogOpen:Me,newProjectMode:Te,newProjectName:N,newProjectPath:q,newProjectBusy:X,commitDialogOpen:U,commitMessage:ae,commitIncludeUnstaged:de,commitNextStep:ye,commitDraft:Oe,branchDialogOpen:$e,branchDialogName:Ge,toast:yt,labDetailNavigation:Se,setQuery:Le,setSearchOpen:Ae,setArchivedChatsOpen:qe,setSectionMenuOpen:Ue,setCloudProjectsExpanded:bn,setChatRowsVisibleCount:Mt,setSidebarOpen:pe,setView:fe,setSelectedAppId:Fe,setSelectedProjectId:Pe,setSelectedSessionId:Ne,setPrompt:ot,setDraftProvider:ut,setDraftModel:At,setDraftExperience:mt,setDiffPanelOpen:at,setDiffPanelExpanded:Ct,setRightPanelMode:Be,setTerminalOpen:Et,setSettingsSection:dn,setNewProjectDialogOpen:jn,setNewProjectName:kt,setNewProjectPath:kr,setCommitDialogOpen:un,setCommitMessage:yn,setCommitIncludeUnstaged:Ut,setCommitNextStep:Rn,setCommitDraft:Sn,setBranchDialogOpen:Pn,setBranchDialogName:Mn,setError:qt,showToast:gt,applyBootstrapPayload:qn,applyPreferencesPayload:mn,bootstrap:pt,connection:_t,startup:Ot,training:pn,pinnedCollapsed:oa,cloudProjectsCollapsed:Ze,chatsCollapsed:Tn,savedForLaterCollapsed:Za,sidebarWidth:Ea,sidebarResizing:Ln,diffPanelWidth:An,diffPanelResizing:Ja,togglePinnedCollapsed:wr,toggleCloudProjectsCollapsed:ja,toggleChatsCollapsed:lt,toggleSavedForLaterCollapsed:rn,startSidebarResize:Ke,startDiffPanelResize:St,selectedApp:en,selectedCloudProject:zn,selectedProject:xn,selectedProjectLinkedApp:D,selectedSession:we,sidebarSessions:le,runtimeIndexes:Je,runtimeEventStore:ga,chatMentionApps:Bn,connectedAppMentions:Ma,pendingApproval:kn,pendingChatUserMessages:ao,account:Ir,activeModel:On,activeProvider:ia,appDefaults:ca,startMessage:_r,organizations:ks,teamChatOrganization:ws,teamChatTeamId:Is,teamChat:ft,publishTeamProfileAgent:Ii,communitySidebar:_s,communityView:_i,teamAiThreadId:ro,toggleTeamAiSidebar:Ci,activeOpenPondCommandAccessMode:Cr,viewWorkspaceAppId:Ri,viewWorkspaceId:so,viewWorkspaceKind:oo,viewWorkspaceName:io,selectedActionCatalog:Pi,expandedProjectIds:Ti,expandProject:Qa,toggleProjectExpanded:Ai,changeCodexPermissionMode:co,changeCodexReasoningEffort:Cs,changeOpenPondCommandAccessMode:Rs,resolveApproval:lo,beginNewChat:la,beginNewChatWithTrainingModel:Ei,dismissTrainingChatHandoff:Ps,trainingChatHandoff:Rr,selectTrainingChatTaskForComposer:Gn,chatHistoryLoadStates:ji,loadMoreSelectedChatHistory:Mi,selectedPagedSessionEvents:wn,activeSessions:Kr,archivedSessions:Zn,pinnedSessions:Pr,savedForLaterSessions:Ts,savedForLaterFiles:Wr,sidebarFileBookmarks:Oi,setSidebarFileStatus:uo,setSessions:As,projectRows:Tr,localProjectRows:Ar,cloudProjectRows:Es,projectSessionRowsByProjectId:mo,childSessionRowsByParentId:Gr,sidebarProjectIdBySessionId:Ya,chatRows:va,visibleChatRows:po,chatRowsVisibleCount:Zr,sessionEvents:Xa,goalRuntime:fo,subagentRuntime:Oa,visibleChatMessages:ho,activeTerminalScope:$i,terminalSummaries:go,runningSessionIds:Ni,selectedSessionRunning:vo,sidebarGoalRuntimeBySessionId:bo,sidebarSubagentRuntimeBySessionId:yo,taskDragSessionId:js,taskPreviewSessionIds:So,startTaskDrag:Ms,clearTaskDrag:er,previewTaskDrop:Di,commitTaskDrop:Li,commitTaskPreviewDrop:zi,dragItem:Hi,startPinnedDrag:tr,clearSidebarDrag:xo,previewPinnedDrop:Ui,commitPinnedDrop:qi,commitPinnedPreviewDrop:Bi,commandProjectRows:da,contextWindowStatus:ko,pinnedRows:et,workspaceBusy:Ft,diffBusy:nr,visibleWorkspaceState:sn,visibleWorkspaceDiff:Hn,refreshVisibleWorkspaceDiff:$n,managedWorkspace:ju,canSyncActiveWorkspace:Mu,canPublishOpenPondProject:Ou,projectTarget:$u,workspaceTarget:sl}=e,{title:Nu,browserConversationId:Os,handleWorkspaceDiffPanelViewStateChange:ol,openSessionInChat:wo,changeProjectTarget:Du,submitNewProjectDialog:Lu,changeWorkspaceBranch:zu,openCommitDialog:Hu,openCreateWorkspaceBranchDialog:Uu,openDefaultsSettingsFromBranchDialog:qu,runWorkspaceTool:Bu,submitCommitDialog:Fu,submitCreateWorkspaceBranch:Vu,syncWorkspaceLocally:Ku,answerCreateImproveQuestion:il,applyCreateImproveCandidate:Wu,approveCreateImproveRun:Gu,cancelCreateImproveRun:Zu,changeDraftProvider:Fi,openCreateImprovePullRequest:cl,reconcileCreateImprovePullRequest:Ju,rejectCreateImproveCandidate:Qu,pauseCreateImproveRun:ll,resumeCreateImproveRun:dl,reviseCreateImproveRun:Yu,stopTurn:Io,archiveSession:Xu,restoreSession:ul,renameSession:em,toggleSessionPinned:Vi,toggleProjectPinned:ml,toggleSessionSavedForLater:pl,moveProjectToCloud:tm,startCloudSetupUpload:fl,changeWorkspaceTarget:nm,sendPromptFromMainComposer:am,openSandboxWorkspace:hl,openCloudProjectDialog:rm,openExistingProjectPathDialog:gl,openUrlInBrowserPanel:sm,showBrowserPanel:om,showChangesPanel:im,showGoalSidebarTab:Jr,rightChatTrainingLaunchRequest:vl,setRightChatTrainingLaunchRequest:cm,closeRightChatPanel:lm,openRightChatPanel:Ki,rightChatPanelViews:dm,showRightChatPanel:um,showRightPanelDiffTab:mm,submitRightChatPrompt:pm,activateRightChatPanel:fm,updateRightChatModel:hm,updateRightChatPrompt:gm,updateRightChatProvider:vm,updateRightChatScrollState:bm,openProfileSettings:ym,diagnosticEvents:Sm,toggleRightSidebar:bl,removeProject:xm}=t;hC(_t,pt?.account.activeProfile&&pt.preferences.defaultTeamId?JSON.stringify([pt.account.baseUrl,pt.account.activeProfile,pt.account.profile?.id,pt.account.state,pt.preferences.defaultTeamId]):null,()=>{Lt({kind:"chat",sessionId:null}).then(he=>{he&&(Ne(null),fe("chat"),a("activity"))})});const $a=pt?.account.activeProfile&&pt?.preferences.defaultTeamId?`${pt.account.activeProfile.handle}:${pt.preferences.defaultTeamId}`:null;h.useEffect(()=>{if(!(!$a||B!=="chat"||l?.kind!=="chat"||l.sessionId||te||r.current.has($a))){r.current.add($a);try{const he=localStorage.getItem(`openpond:ponder-mode:v1:${$a}`);(he==="clean"||he==="activity")&&a(he)}catch{}}},[$a,l,B,te]),h.useEffect(()=>{if(!(!$a||!r.current.has($a)))try{localStorage.setItem(`openpond:ponder-mode:v1:${$a}`,n??"off")}catch{}},[$a,n]);const _o=h.useCallback(he=>{Fe(null),Pe(he),Ne(null),fe("chat"),Qa(he),$()},[Qa,$,Fe,Pe,Ne,fe]),km=h.useCallback((he=null)=>{a(null);const Xe=te?Ya[te]??null:null;if(!he&&Xe){_o(Xe);return}la(he)},[la,_o,te,Ya]),wm=h.useCallback(async he=>{if(!(!_t||!pt))try{const Xe=await Z.savePreferences(_t,{defaultTeamId:he});mn(Xe)}catch(Xe){const $t=Xe instanceof Error?Xe.message:String(Xe);throw qt($t),gt("Could not switch teams","error"),Xe}},[mn,pt,_t,qt,gt]),Im=h.useCallback(async()=>{if(_t)try{const he=await Z.signOutOpenPondAccount(_t);qn(he),gt("Logged out","success")}catch(he){const Xe=he instanceof Error?he.message:String(he);throw qt(Xe),gt("Could not log out","error"),he}},[qn,_t,qt,gt]),Wi=ca.defaultTeamId??null,_m=h.useMemo(()=>Tr.filter(he=>he.kind==="local"||Wi!==null&&he.project.teamId===Wi),[Tr,Wi]),Cm=h.useMemo(()=>{const he={};for(const Xe of Kr){const $t=Ya[Xe.id];$t&&(he[$t]=(he[$t]??0)+1)}for(const Xe of Ar){if(Xe.kind!=="local")continue;const $t=Xe.project.linkedSandboxProject?.projectId;if(!$t||!Xe.cloudLinkTrusted)continue;const ba=ct("cloud",$t);he[Xe.id]=(he[Xe.id]??0)+(he[ba]??0)}return he},[Kr,Ar,Ya]),[yl,Er]=h.useState(null),[Co,Ro]=h.useState(null),Rm=$F(pt?.profile,pt?.extensionCatalog),[$s,Gi]=h.useState(null),[Po,Zi]=h.useState(null),[ar,Sl]=h.useState(null),Pm=h.useCallback(async()=>{await Lt({kind:"view",view:"team"})&&(Fe(null),Pe(null),Ne(null),Ue(null),fe("team"))},[Ue,Fe,Pe,Ne,fe]),Tm=h.useCallback(async()=>{await Lt({kind:"view",view:"community"})&&(Fe(null),Pe(null),Ne(null),Ue(null),_s.discoverCommunities())},[_s.discoverCommunities,Ue,Fe,Pe,Ne]),Am=VF({activeExperience:je,activeModel:On,activeOpenPondCommandAccessMode:Cr,activeProvider:ia,cloudProjects:pt?.cloudProjects??KF,composerDraftStore:f,connection:_t,requestComposerFocus:$,selectedCloudProject:zn,selectedProject:xn,selectedSession:we,setMentionedAppId:T,setSelectedSessionId:Ne,setSessions:As,setView:fe,showToast:gt,workspaceTarget:sl.value}),Em=h.useCallback(async he=>{if(!_t)throw new Error("OpenPond is not connected.");let Xe=ia,$t=On;Xe==="codex"&&(Xe=Sf(pt?.providers,{enabledOnly:!0}).find(In=>In.value!=="codex")?.value??Ks,$t=Nd(Xe,pt?.providers)??wc);const ba=le.find(In=>In.id===he.sourceSessionId),jr=await Z.createSession(_t,{experience:he.target,provider:Xe,modelRef:{providerId:Xe,modelId:$t},openPondCommandAccessMode:Cr,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${ba?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:NF({sourceTaskId:he.sourceSessionId,sourceExperience:ba?.experience??null,targetExperience:he.target,sourceMessageIds:he.sourceMessageIds??[],sourceContext:he.sourceContext,output:he.output})}});return As(In=>[jr,...In]),mt(he.target),ut(Xe),At($t),f.set(he.prompt),Lt({kind:"chat",sessionId:jr.id}),S({type:"selectSession",sessionId:jr.id,appId:null,projectId:null}),Fe(null),Pe(null),Et(!1),fe("chat"),Be("home"),at(he.target==="work"),Ct(!1),jr},[On,Cr,ia,S,pt?.providers,f,_t,Ct,at,mt,At,ut,Be,Fe,Pe,As,Et,fe,le]),jm=h.useCallback(he=>{Gi(he),Zi(null),la(null),pe(!0)},[la,pe]),Mm=h.useCallback(he=>{la(null),mt("work"),f.set(`$openpond-refiner-authoring ${he}`),fe("chat"),pe(!0)},[la,f,mt,pe,fe]),xl=h.useCallback(he=>{Zi(jF(he)),Gi(null),la(null),pe(!0)},[la,pe]);h.useEffect(()=>{!$s&&!Po||B!=="chat"||te||G||ne||(Er($s),Ro(Po),Gi(null),Zi(null),Be("home"),Ct(!1),at(!0))},[$s,Po,ne,G,te,Ct,at,Be,B]),h.useEffect(()=>{!yl&&!Co||B==="chat"&&Re&&xe==="home"||(Er(null),Ro(null))},[Re,Co,yl,xe,B]);const kl=h.useCallback(()=>{Er(null),Ro(null),Ct(!1),at(!1)},[Ct,at]),Om=h.useCallback(he=>{let Xe;if(he.workspaceKind==="local"){const $t=ct("local",he.workspaceId);Xe=`draft:${$t}`,Fe(null),Pe($t),Ne(null),Qa($t),fe("chat")}else{const $t=le.find(ba=>ba.id===he.sourceSessionId||ba.workspaceId===he.workspaceId);if(!$t){gt("This saved file's cloud chat is no longer available.","error");return}Xe=$t.id,wo($t.id)}Be("changes"),at(!0),Sl({id:Date.now(),conversationId:Xe,file:he}),he.available||gt(`File unavailable: ${he.path}`,"error")},[Qa,wo,at,Be,Fe,Pe,Ne,fe,gt,le]);h.useEffect(()=>{if(!AF(ar,Os))return;const he=window.setTimeout(()=>{Be("changes"),at(!0),Sl(Xe=>EF(Xe,ar.id))},0);return()=>window.clearTimeout(he)},[Os,at,Be,ar]);const wl=l?.kind==="models"&&l.route.area==="console"?"console":DF(B);h.useEffect(()=>{if(l){if(l.kind==="models"||l.kind==="models_unavailable"){B!=="labs"&&fe("labs");return}if(l.kind==="settings"){Fe(null),Pe(null),Ne(null),dn(l.section),B!=="settings"&&fe("settings");return}if(l.kind==="view"){Fe(null),Pe(null),Ne(null),B!==l.view&&fe(l.view);return}l.sessionId!==null&&(a(null),Fe(null),Pe(null)),Ne(l.sessionId),B!=="chat"&&fe("chat")}},[l,Fe,Pe,Ne,dn,fe,B]);const $m=h.useCallback(he=>{if(Ue(null),Fe(null),Pe(null),Ne(null),he==="models"||he==="console"){Fs(he==="console"?wa("datasets",null,{area:"console"}):wa()),fe("labs");return}he==="chat"&&Lt({kind:"chat",sessionId:null}),De(Mg())},[De,Lt,Ue,Fe,Pe,Ne,fe]),Nm=h.useCallback(async(he,Xe)=>{const $t=await pn.actions.acceptHarnessReview(he,Xe,{providerId:ia,modelId:On},be);return $t?(M($t.materializedTasksetId??null),Fs(wa()),fe("labs"),!0):(gt("Taskset review could not be opened.","error"),!1)},[On,ia,be,Fs,wa,M,fe,gt,pn.actions]),Ve=h.useMemo(()=>nC([...Je.eventsBySessionId.values()].flat()),[Je.eventsBySessionId]);if(!Ot.ready)return g.jsx(JB,{startup:Ot});if(B==="settings")return g.jsx(Zb,{showToast:gt,children:g.jsx(KB,{settings:{payload:pt,connection:_t,diagnostics:Sm,initialSection:Ie,onPayload:qn,onError:qt,onToast:gt,onOpenSourceSession:wo,onStartRefinerAuthoring:Mm,onAcceptEvaluationReview:Nm,onOpenSkill:jm,onOpenExtension:xl,teamChatCurrentUserId:ft.currentUserId,teamChatEnabled:Is!==null,teamChatNotificationMode:ft.notificationMode,teamChatThreads:ft.threads,onTeamChatNotificationModeChange:ft.setNotificationMode,onTeamChatThreadMuteChange:ft.setThreadMuted,diffPanelWidth:An,diffPanelResizing:Ja,diffPanelExpanded:Q,onDiffPanelResizeStart:St,onDiffPanelExpandedChange:Ct,onBack:()=>{const he=YU(l);Lt(he),fe(he.kind==="models"?"labs":"chat"),pe(!0)}},toast:{toast:yt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})});const tn=ku(),Bt=wl==="console"||B==="chat",Vt=Bt&&K,ua=_t?.platform??navigator.platform,Dm=tn&&Zw(ua),Wg=$i,i_=sn?.initialized?sn.repoPath:we?.cwd??null,c_={"--sidebar-width":`${Ea}px`,"--diff-panel-width":`${An}px`},l_=B==="chat"&&je!=="chat"||B==="labs"||B==="scheduled"&&s||B==="team"&&!!ro,d_=["app-shell",Dm?"platform-macos":"",Vt?"sidebar-open":"sidebar-closed",Ln?"sidebar-resizing":"",Ja?"diff-panel-resizing":""].filter(Boolean).join(" "),Lm=te?ji[te]:null,u_=te?Lm?.cursorSequence??YB(Dr(wn,al(Je,te))):null,m_=!!te&&!!_t&&(Gt(te)?!0:!!pt?.eventWindow?.hasMoreBefore&&!!u_)&&(Lm?.hasMore??!0),p_=!!Lm?.loading,f_=(()=>{const he=pn.payload;if(!he)return{};const Xe=new Map(he.plans.map(In=>[In.id,In])),$t=new Set(["queued","starting","running","cancelling","reconciling"]),ba={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},jr={};for(const In of[...he.modelRuns].sort((Na,To)=>To.updatedAt.localeCompare(Na.updatedAt))){if(In.kind==="evaluation"||!["prepared","running"].includes(In.status))continue;const Na=he.jobs.filter(zm=>zm.metadata.modelRunId===In.id).sort((zm,h_)=>h_.updatedAt.localeCompare(zm.updatedAt))[0];if(Na&&!$t.has(Na.status))continue;const To=Na?.status??(In.status==="prepared"?"starting":"running");jr[In.modelId]={label:ba[To]??"Running",status:To}}for(const In of[...he.jobs].sort((Na,To)=>To.updatedAt.localeCompare(Na.updatedAt))){if(!$t.has(In.status))continue;const Na=Xe.get(In.planId)?.modelId;!Na||jr[Na]||(jr[Na]={label:ba[In.status]??"Active",status:In.status})}return jr})();return g.jsx(Zb,{showToast:gt,children:g.jsx(VB,{className:d_,style:c_,sidebar:{activityTimes:Ve,onOpenPonder:()=>{Lt({kind:"chat",sessionId:null}),Ne(null),fe("chat"),a("activity")},productArea:wl,modelProjects:(pn.payload?.modelProjects??[]).filter(he=>he.hosted===null||he.hosted.teamId===(ca.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:f_,onProductAreaChange:$m,experience:je,view:B,selectedAppId:ne,selectedProjectId:G,selectedSessionId:te,selectedTeamThreadId:ft.selectedThreadId,teamChatEnabled:Is!==null,organizations:ks,selectedTeamId:ca.defaultTeamId??null,teamChatOrganization:ws,teamChatLoading:ft.loading,currentUserId:ft.currentUserId,teamMembers:ft.members,teamThreads:ft.threads,..._s,onOpenTeamChat:Pm,discoverCommunities:Tm,account:Ir,connection:_t,profile:pt?.profile,pinnedCollapsed:oa,cloudProjectsCollapsed:Ze,chatsCollapsed:Tn,savedForLaterCollapsed:Za,archivedChatsOpen:H,cloudProjectsExpanded:J,sectionMenuOpen:F,dragItem:Hi,taskDragSessionId:js,taskPreviewSessionIds:So,activeSessions:Kr,archivedSessions:Zn,pinnedRows:et,pinnedSessions:Pr,savedForLaterSessions:Ts,savedForLaterFiles:Wr,projectRows:Tr,localProjectRows:Ar,cloudProjectRows:Es,projectSessionRowsByProjectId:mo,childSessionRowsByParentId:Gr,sidebarProjectIdBySessionId:Ya,terminalSummaries:go,runningSessionIds:Ni,goalRuntimeBySessionId:bo,subagentRuntimeBySessionId:yo,visibleChatRows:po,chatRows:va,chatRowsVisibleCount:Zr,expandedProjectIds:Ti,currentVersion:pt?.server.version??null,platform:ua,arch:_t?.arch??null,onSidebarResizeStart:Ke,setSidebarOpen:pe,setView:fe,setSelectedAppId:Fe,setSelectedProjectId:Pe,setSelectedSessionId:Ne,setSearchOpen:Ae,setSectionMenuOpen:Ue,setSettingsSection:dn,onSelectTeam:wm,onLogOut:Im,onTogglePinnedCollapsed:wr,onToggleCloudProjectsCollapsed:ja,onToggleChatsCollapsed:lt,onToggleSavedForLaterCollapsed:rn,setArchivedChatsOpen:qe,setCloudProjectsExpanded:bn,setChatRowsVisibleCount:Mt,beginNewChat:km,beginProjectChat:_o,onAddProject:gl,dockSessionRight:Ki,selectTeamThread:he=>{fe("team"),ft.selectThread(he)},openTeamDm:he=>{fe("team"),ft.openDm(he)},toggleSessionPinned:Vi,toggleProjectPinned:ml,toggleSessionSavedForLater:pl,openSidebarFile:Om,setSidebarFileStatus:(he,Xe)=>{uo(he,Xe)},archiveSession:Xu,restoreSession:ul,renameSession:em,removeProject:xm,expandProject:Qa,toggleProjectExpanded:Ai,startPinnedDrag:tr,clearSidebarDrag:xo,previewPinnedDrop:Ui,commitPinnedDrop:qi,commitPinnedPreviewDrop:Bi,startTaskDrag:Ms,clearTaskDrag:er,previewTaskDrop:Di,commitTaskDrop:Li,commitTaskPreviewDrop:zi},topBar:{sidebarOpen:Vt,sidebarAvailable:Bt,title:B==="chat"&&n?"Ponder Pal":Nu,backAction:Se.backAction,breadcrumbs:Se.breadcrumbs,workspaceName:io,workspaceId:so,busy:me,workspaceState:sn,workspaceKind:oo,selectedApp:D??en,selectedProject:xn,workspaceDiff:Hn,managedWorkspace:ju,workspaceBusy:Ft,defaultTeamId:ca.defaultTeamId,activityActorId:pt?.account.profile?.id??null,activityProjectId:l?.kind==="models"?l.route.projectId??null:null,showDiffControls:B==="chat"&&je==="development",diffPanelOpen:Re,terminalOpen:He,rightSidebarAvailable:l_,rightSidebarOpen:B==="labs"&&p?c?.open??!1:B==="scheduled"?s:Re,onToggleDiffPanel:bl,onToggleRightSidebar:B==="labs"&&p?c?.toggle:B==="scheduled"?()=>i(he=>!he):B==="team"&&ro?Ci:bl,onOpenSearch:()=>{Ue(null),Ae(!0)},onToggleTerminal:()=>Et(he=>!he),onRunTerminalCommand:he=>{I({id:Date.now(),scope:Wg,command:he}),Et(!0)},onWorkspaceToolAction:Bu,onOpenCommitDialog:Hu,onWorkspaceBranchChange:zu,onWorkspaceBranchCreate:Uu,connection:_t,onBootstrap:qn,onOpenSandboxWorkspace:hl,onShowSidebar:()=>pe(!0),platform:ua,showWorkspaceControls:B!=="team"&&B!=="community"&&B!=="labs"&&B!=="scheduled"&&B!=="outputs"&&B!=="projects"&&(je==="development"||je==="work"&&!!(xn||we?.localProjectId||we?.cloudProjectId||we?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:je,onNewExperienceChange:De,view:B,teamChat:{currentUserId:ft.currentUserId,members:ft.members,agents:ft.agents,profile:pt?.profile??null,teamId:Is,teamName:ws?.displayName??null,detail:ft.detail,aiThread:ft.aiThread,agentConversation:ft.agentConversation,loading:ft.loading,busy:ft.busy,error:ft.error,connection:_t,providerSettings:pt?.providers??null,provider:ia,model:On,codexPermissionMode:oe,codexReasoningEffort:be,openPondCommandAccessMode:Cr,contextWindowStatus:ko,showToast:gt,onProviderChange:Fi,onModelChange:At,onCodexPermissionModeChange:co,onCodexReasoningEffortChange:Cs,onOpenPondCommandAccessModeChange:Rs,onOpenProviderSettings:()=>{Lt({kind:"view",view:"apps"})},onSendMessage:ft.sendMessage,onPublishProfileAgent:Ii,onOpenAiThread:async he=>{await ft.openAiThread(he),Be("chat"),at(!0)},onOpenAgentConversation:async he=>{await ft.openAgentConversation(he),Be("chat"),at(!0)},onCloseAiThread:()=>at(!1),onCloseAgentConversation:()=>{ft.closeAgentConversation(),at(!1)},onSendAgentTurn:ft.sendAgentTurn,onSendAiTurn:ft.sendAiTurn,onStopAiTurn:ft.stopAiTurn,onEditMessage:ft.editMessage,onDeleteMessage:ft.deleteMessage,onRetryMessage:ft.retryMessage,onDismissFailedMessage:ft.dismissFailedMessage,onLoadMoreMessages:ft.loadMoreMessages,onRetryLoad:ft.refresh},community:_i,bootstrap:pt,runtimeEvents:Xa,chatMessages:ho,pendingUserMessage:te?ao[te]??null:null,contextWindowStatus:ko,goalRuntime:fo,subagentRuntime:Oa,selectedSessionId:te,composerDraftStore:f,mainComposerFocusRequestId:z,labCloseDetailRequestId:Se.closeDetailRequestId,labCloseDetailKind:Se.closeDetailKind,sideChatTrainingLaunchRequest:vl,onSideChatTrainingLaunchHandled:he=>cm(Xe=>Xe?.id===he?null:Xe),mentionApps:Bn,connectedAppMentions:Ma,profileSkills:Rm,selectedMentionAppId:A,busy:me,turnRunning:vo,activeProvider:ia,activeModel:On,codexPermissionMode:oe,codexReasoningEffort:be,openPondCommandAccessMode:Cr,pendingApproval:kn,activeWorkspaceAppId:Ri,activeWorkspaceId:so,activeWorkspaceKind:oo,projectTarget:$u,actionCatalog:Pi,workspaceTarget:sl,connection:_t,workspaceName:io,workspaceState:sn,workspaceDiff:Hn,workspaceBusy:Ft,diffBusy:nr,forceChatThread:!!te,diffPanelOpen:Re,diffPanelExpanded:Q,rightPanelMode:xe,rightPanelTabRequest:R,rightChatPanels:dm,runtimeEventStore:ga,nativeSkillSidebar:yl,extensionSkillSidebar:Co,workspaceDiffPanelViewState:O,sidebarFileOpenRequest:ar,sidebarFileBookmarks:Oi,onSetSidebarFileStatus:(he,Xe)=>{uo(he,Xe)},browserConversationId:Os,terminalScope:Wg,terminalTabs:C,terminalCwd:i_,pendingTerminalCommand:b,terminalOpen:He,onToggleTerminal:()=>Et(he=>!he),onWorkspaceDiffPanelViewStateChange:ol,training:pn,trainingSessions:le,trainingChatHandoff:Rr,trainingDetailTasksetId:_,onTrainingDetailTasksetIdChange:M,onTrainingChatTaskSelect:Gn,onTrainingChatHandoffDismiss:Ps,onOpenSession:wo,onExperienceHandoff:Em,cloudProjects:pt?.cloudProjects??[],projects:_m,projectsAccountBaseUrl:Ir?.baseUrl??Ir?.activeProfile?.baseUrl??null,projectsTeamName:ws?.displayName??null,projectTaskCounts:Cm,onNewCloudProject:rm,onNewLocalProject:gl,onNewProjectTask:he=>_o(he.id),onToggleProjectPinned:ml,onUploadLocalProject:tm,chatHistoryHasMore:m_,chatHistoryLoading:p_,onDiffPanelResizeStart:St,onToggleDiffPanelExpanded:()=>Ct(he=>!he),onShowDiffPanel:im,onShowBrowserPanel:om,onShowFilesPanel:()=>mm("files"),onShowGoalSidebarTab:Jr,onShowTrainingDraftPanel:()=>{Be("training"),at(!0)},onShowRightChatPanel:um,onAddRightChat:()=>Ki(null),onOpenRightChatForSession:(he,Xe)=>{const $t=Xe??le.find(ba=>ba.id===he)??null;$t&&Ki($t,{preserveView:!0})},onLabDetailOpenChange:Se.onDetailOpenChange,evaluationSidebarActive:B==="labs"&&p,onEvaluationSidebarControl:d,scheduledDetailOpen:s,onScheduledDetailOpenChange:i,onTerminalTabsChange:P,onCloseRightChatPanel:lm,onCloseNativeSkillSidebar:kl,onActivateRightChatPanel:fm,onRightChatModelChange:hm,onRightChatPromptChange:gm,onRightChatScrollStateChange:bm,onRightChatProviderChange:vm,onSubmitRightChat:pm,onStopRightChat:he=>Io(he),onCloseTerminal:()=>Et(!1),onLoadMoreChatHistory:Mi,canSyncWorkspace:Mu,startMessage:_r,onPayload:qn,onError:qt,setView:fe,onOpenProfileSettings:ym,onOpenProviderSettings:()=>{Lt({kind:"view",view:"apps"})},onOpenTrainingSettings:()=>{Lt({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{Lt({kind:"settings",section:"dataset-storage"})},changeDraftProvider:Fi,changeProjectTarget:Du,changeWorkspaceTarget:nm,setDraftProvider:ut,setDraftModel:At,onBeginNewChatWithModel:Ei,changeCodexPermissionMode:co,changeCodexReasoningEffort:Cs,changeOpenPondCommandAccessMode:Rs,resolveApproval:lo,answerCreateImproveQuestion:il,applyCreateImproveCandidate:Wu,approveCreateImproveRun:Gu,cancelCreateImproveRun:Zu,openCreateImprovePullRequest:cl,reconcileCreateImprovePullRequest:Ju,rejectCreateImproveCandidate:Qu,pauseCreateImproveRun:ll,resumeCreateImproveRun:dl,reviseCreateImproveRun:Yu,setMentionedAppId:T,showToast:gt,onSaveTaskDraft:Am,sendPrompt:am,stopTurn:he=>Io(void 0,he),syncWorkspaceLocally:Ku,refreshWorkspaceDiff:$n},cloudSetup:{state:y,onClose:()=>w(null),onOpenBrowserUrl:sm,onStart:()=>{fl()}},projectConfirm:{state:V,onResolve:Y},lazyPanels:{activeSessions:Kr,branchDialogName:Ge,branchDialogOpen:$e,commitDialogOpen:U,commitDraft:Oe,commitIncludeUnstaged:de,commitMessage:ae,commitNextStep:ye,canPublishOpenPondProject:Ou,connection:_t,expandProject:Qa,newProjectBusy:X,newProjectDialogOpen:Me,newProjectDirectory:ca.defaultNewProjectDirectory,newProjectMode:Te,newProjectName:N,newProjectPath:q,projectRows:da,query:re,searchOpen:ee,visibleWorkspaceDiff:Hn,visibleWorkspaceState:sn,workspaceBusy:Ft,appDispatch:S,beginNewChat:()=>la(null),openDefaultsSettingsFromBranchDialog:qu,setBranchDialogName:Mn,setBranchDialogOpen:Pn,setCommitDialogOpen:un,setCommitDraft:Sn,setCommitIncludeUnstaged:Ut,setCommitMessage:yn,setCommitNextStep:Rn,setNewProjectDialogOpen:jn,setNewProjectName:kt,setNewProjectPath:kr,setPrompt:ot,setQuery:Le,setSearchOpen:Ae,submitCommitDialog:Fu,submitCreateWorkspaceBranch:Vu,submitNewProjectDialog:Lu},toast:{toast:yt,onDismiss:()=>S({type:"field",key:"toast",value:null})}})})}const Wo=new Map,hd=new Map;function Pf(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(r=>r.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 GF(e){const t=e?.trim();if(!t)return null;const n=Wo.get(t);return n?.updatedAt?n.organizations:null}function ZF(e,t){const n=e?.trim();if(n){Wo.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of hd.get(n)??[])a()}}function JF(e,t){const n=e?.trim();if(!n)return()=>{};const a=hd.get(n)??new Set;return a.add(t),hd.set(n,a),()=>{a.delete(t),a.size===0&&hd.delete(n)}}function sy(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Wo.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(r=>(ZF(t,r),r)).catch(r=>{const s=Wo.get(t);throw s?.promise===a&&Wo.set(t,{organizations:s.organizations,promise:null,updatedAt:s.updatedAt}),r});return Wo.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const DG="openpond.config.json";function LG(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function a1(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function bp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function zG(e,t=null){const n=YF(e.openFilePaths.map(r=>iy(r,t)).filter(Boolean)),a=e.selectedPath&&iy(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function oy(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 iy(e,t=null){let n=QF(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 r=a.split("/").filter(Boolean).at(-1);return r&&n.startsWith(`${r}/`)&&(n=n.slice(r.length+1)),n}function HG(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function UG(e){return{path:e,status:"unchanged",additions:0,deletions:0,patch:"",content:null}}function qG(e,t){const n=cy(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const r=cy(a);return!!(r&&r.startsWith(`${n}/`))})}function BG(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function FG(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function QF(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 YF(e){return Array.from(new Set(e))}function cy(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function XF(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",r=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",s=e.apiBaseUrl??t?.apiBaseUrl??"",i=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,r,s,i].join("|")}function r1(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function e5(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function _u(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,r=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||r1(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:r?"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:r,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 t5(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 n5(e,t){const n=e.filter(r=>r.status==="active"&&r.workspaceKind==="shared"),a=t?.trim()??"";if(a){const r=n.find(s=>s.teamId===a);if(r)return r}return n.find(r=>r.role==="owner")??n.find(r=>r.role==="admin")??n[0]??null}function a5(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function r5({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const s5=[{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 o5(...e){return a5(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function i5(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return o5(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function c5({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:r,selectedCloudProject:s,selectedProject:i,selectedSession:c,selectedSessionId:d,selectedSessionLinkedProject:l}){const p=c?.workspaceKind==="local_project"?c.workspaceId??null:l?.id??null,f=Gt(d)&&!c,S=c?Sr(c.workspaceKind):!1,b=xr(c),I=c?FF(c):!1,C=c?.cwd&&(!S||b)?TS(c.cwd):null,P=e?.providers??null,_=Ra(i,e?.cloudProjects??[]),M=r5({draftProvider:n,hasSelectedCloudProject:!!s,selectedSessionHybridWorkspace:b}),A=Ss(M,t,P),T=Sa(e?.preferences),y=f?null:c?S?c.workspaceKind??"sandbox":I?"sandbox":p?"local_project":c.workspaceKind??(c.appId?"sandbox_app":C?"local_project":null):s?"sandbox":i?"local_project":r?"sandbox_app":null,w=f?null:c?S&&!b||I?null:p||(c.workspaceId??c.appId??C):s?null:i?.id??r,R=f?null:c?S?c.workspaceId??null:I?null:p??c.workspaceId??c.appId??C:s?null:i?.id??r,O=e?.account??null,z=!e||O?.state==="loading"||O?.state==="switching",$=!z&&O?.state==="signed_out",V=z?null:$?"Sign in":O?.label??O?.activeProfile?.handle??"Account",Y=i5(O),re=Y?`Welcome, ${Y}`:"Welcome",ee=c?.workspaceName??c?.appName??s?.name??i?.name??a?.name??null,H=Sr(y)?"cloud":"local",F=i?.name??l?.name??(c?.workspaceKind==="local_project"?c.workspaceName:null)??"Local workspace",J=(H==="cloud"?ee:null)??s?.name??_?.name??i?.name??"Cloud workspace",K=!!(s?.id||_?.id||c?.cloudProjectId||H==="cloud");return{account:O,accountLabel:V,accountPending:z,accountSignedOut:$,activeModel:A,activeProvider:M,activeWorkspaceAppId:w,activeWorkspaceId:R,activeWorkspaceKind:y,activeWorkspaceLocation:H,appDefaults:T,cloudLinked:K,cloudTargetName:J,localTargetName:F,selectedCodexHistoryPending:f,selectedSessionCloudWorkspace:S,selectedSessionLocalPathWorkspaceId:C,selectedSessionPendingCloudStart:I,selectedSessionProjectId:p,startMessage:re,workspaceName:ee}}function l5({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:r,cloudLinked:s,selectedCloudProject:i,selectedProject:c,selectedSession:d,pendingWorkspaceTarget:l,workspaceStates:p,workspaceBusy:f}){const S=Ra(c,a?.cloudProjects??[]),I=!!!c?.linkedSandboxProject?.projectId||!!S,C=h.useMemo(()=>{const R=(a?.localProjects??[]).map(V=>({value:`local:${V.id}`,label:V.name,detail:V.workspacePath,kind:"local"})),O=(a?.cloudProjects??[]).map(V=>({value:`cloud:${V.id}`,label:V.name,detail:V.organizationName??V.sourceLabel??"OpenPond Cloud",kind:"cloud"})),z=c?`local:${c.id}`:i?`cloud:${i.id}`:"none",$=[...R,...O].find(V=>V.value===z)??null;return{value:z,label:$?.label??"Select Project",detail:$?.detail??"Choose a project for local or cloud work",busy:f||r,options:[...R,...O,...s5,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,r,i,c,f]),P=!!(s||c),_=!!(i?.id||S?.id||d?.cloudProjectId||xr(d)),M=c?p[c.id]??null:null,A=bI(M,{branch:c?.linkedSandboxProject?.defaultBranch??null,path:c?.workspacePath??d?.cwd??null,linkedCloudSourceKnown:c?.linkedSandboxProject?.projectId&&I?!!c.linkedSandboxProject.lastUploadedCommit||!M?.headCommit:!0}),T=yI(c,i??S,M,{cloudLinkTrusted:I}),y=Dq(c,M,{cloudLinkTrusted:I}),w=h.useMemo(()=>{const R={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?A:"App-managed local task workspace",disabled:!1,disabledReason:null},O={value:"hybrid",label:"Hybrid",detail:"Use your selected model with hosted sandbox edits.",stateNote:_?T:"upload required",disabled:e||t||!_,disabledReason:t?"Add an OpenPond account before using Hybrid.":"Upload/sync this Project to Cloud before using Hybrid."},z={value:"cloud",label:"Hosted",detail:"Run with hosted compute, with or without a Project.",stateNote:c||i?T:"Projectless hosted task",disabled:e||t,disabledReason:t?"Add an OpenPond account before using Cloud.":e?"Checking OpenPond account.":null},$={value:"upload_cloud",label:"Upload/sync to cloud",detail:"Push local source to OpenPond Git before cloud work.",stateNote:y,disabled:e||t||!c,disabledReason:t?"Add an OpenPond account before uploading source.":"Select a local Project before uploading source."},V=n==="cloud"?"local":"cloud",Y=V==="local"?R:z;let re=n==="cloud"?z:R;return l==="cloud"?re=z:l==="local"?re=R:(xr(d)||l==="hybrid")&&(re=O),{value:re.value,label:re.label,detail:re.stateNote||re.detail,busy:f,action:{...Y,label:V==="cloud"?"Hosted":c?"Local checkout":"Check out locally"},uploadAction:c?$:null,options:[R,O,z]}},[n,e,t,s,P,T,_,A,l,c,d,y,f]);return{projectTarget:C,workspaceTarget:w}}function Un(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function s1(e){return Un(e.name||e.gitRepo||e.id)}function VG(e){return`@${s1(e)}`}function o1(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function d5(e,t){const n=o1(e);if(n.length===0)return!1;const a=new Set([Un(t.id),s1(t),t.gitRepo?Un(t.gitRepo):""].filter(Boolean));return n.some(r=>a.has(r))}function i1(e){return e.filter(t=>t.sandbox)}function u5(e,t){const n=o1(e);if(n.length===0)return null;const a=new Map;for(const r of n){const s=t.find(i=>{const c=Un(i.id),d=Un(i.name),l=i.gitRepo?Un(i.gitRepo):"";return r===c||r===d||r===l});s&&a.set(s.id,s)}return a.size===1?Array.from(a.values())[0]??null:null}function KG(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 r=n.slice(a.index).indexOf("@");return r<0?null:{query:Un(a[1]??""),start:a.index+r}}function m5(e){return new Set(e.map(t=>t.id))}function ly(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function p5({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:r,sessions:s}){const i=h.useMemo(()=>e?.apps.find($=>$.id===r)??null,[e?.apps,r]),c=h.useMemo(()=>new Map((e?.localProjects??[]).map($=>[$.id,$])),[e?.localProjects]),d=h.useMemo(()=>new Map((e?.cloudProjects??[]).map($=>[$.id,$])),[e?.cloudProjects]),l=h.useMemo(()=>oI(n),[n]),p=h.useMemo(()=>l?.kind==="local"?c.get(l.id)??null:null,[c,l]),f=h.useMemo(()=>l?.kind==="cloud"?d.get(l.id)??null:null,[d,l]),S=h.useMemo(()=>m5(e?.apps??[]),[e?.apps]),b=h.useMemo(()=>i1(e?.apps??[]),[e?.apps]),I=h.useMemo(()=>{const $=[];for(const V of e?.localProjects??[]){const Y=ly(V,S);Y&&$.push([Y.appId,V.id])}return new Map($)},[e?.localProjects,S]),C=h.useMemo(()=>new Set((e?.localProjects??[]).map($=>$.id)),[e?.localProjects]),P=h.useMemo(()=>mI(e?.localProjects??[]),[e?.localProjects]),_=h.useRef([]),M=h.useMemo(()=>f5(s,t,_.current),[t,s]),A=h.useMemo(()=>M.find($=>$.id===a)??null,[M,a]),T=h.useMemo(()=>{if(!A)return null;if(A.localProjectId)return c.get(A.localProjectId)??null;if(A.workspaceKind==="local_project")return A.workspaceId?c.get(A.workspaceId)??null:null;const $=Rq(A,C,P);if($)return c.get($)??null;if(!A.appId)return null;const V=I.get(A.appId);return V?c.get(V)??null:null},[I,c,C,P,A]),y=h.useMemo(()=>A?.cloudProjectId?d.get(A.cloudProjectId)??null:null,[d,A]),w=p??T,R=f??y,O=h.useMemo(()=>ly(w,S),[S,w]),z=h.useMemo(()=>O?e?.apps.find($=>$.id===O.appId)??null:null,[e?.apps,O]);return{cloudProjectById:d,currentAppIds:S,linkedProjectByAppId:I,localProjectById:c,mentionableSandboxApps:b,selectedApp:i,selectedCloudProject:R,selectedProject:w,selectedProjectLinkedApp:z,selectedProjectLinkedOpenPondApp:O,selectedSession:A,selectedSessionLinkedProject:T,sidebarSessions:M}}function f5(e,t,n){const a=new Map;for(const l of e){const p=dy(l);a.set(p,l)}for(const l of t){const p=dy(l),f=a.get(p);a.set(p,f?h5(f,l):l)}const r=Array.from(a.entries());if(!n)return r.sort((l,p)=>uy(l[1],p[1])).map(l=>l[1]);const s=[],i=new Set;for(const l of n){const p=a.get(l);p&&(s.push([l,p]),i.add(l))}const d=[...r.filter(([l])=>!i.has(l)).sort((l,p)=>uy(l[1],p[1])),...s];return n.splice(0,n.length,...d.map(([l])=>l)),d.map(l=>l[1])}function h5(e,t){return{...e,metadata:g5(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:v5(e.updatedAt,t.updatedAt)}}function dy(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function uy(e,t){const n=my(t)-my(e);return n!==0?n:e.title.localeCompare(t.title)}function g5(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function v5(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 my(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 b5(e){return!!(e&&Sr(e.workspaceKind)&&!xr(e)&&e.provider!=="openpond")}function y5(e,t){const n=lI(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function S5({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:r,linkedProjectByAppId:s,providerSettings:i,selectedAppId:c,selectedSession:d,selectedSessionId:l,selectedSessionProjectId:p,setDiffPanelExpanded:f,setDraftModel:S,setDraftProvider:b,setError:I,setSelectedAppId:C,setSelectedProjectId:P,setSessions:_,setTerminalOpen:M,toast:A}){const T=h.useRef(null);h.useEffect(()=>{if(!c)return;const y=p??(l?null:s.get(c)??null);if(!y)return;const w=ct("local",y);C(null),P(w),r(w)},[r,s,c,l,p,C,P]),h.useEffect(()=>{if(!A||A.persistent)return;const y=window.setTimeout(()=>{n({type:"clearToast",toastId:A.id})},A.durationMs??(A.tone==="error"?7e3:3500));return()=>window.clearTimeout(y)},[n,A]),h.useEffect(()=>{function y(w){(w.metaKey||w.ctrlKey)&&w.key==="`"&&(w.preventDefault(),M(R=>!R))}return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[M]),h.useEffect(()=>{f(!1)},[e,t,f]),h.useEffect(()=>{if(!l){T.current=null;return}if(!d||d.id!==l)return;const y=y5(d,i);if(T.current===y)return;T.current=y;const w=lI(d,i);b(w.provider),S(w.model)},[i,d,l,S,b]),h.useEffect(()=>{!a||!d||!b5(d)||Z.patchSession(a,d.id,{provider:"openpond"}).then(y=>{_(w=>w.map(R=>R.id===y.id?y:R)),b("openpond"),S(w=>Ss("openpond",w))}).catch(y=>{I(y instanceof Error?y.message:String(y))})},[a,d,S,b,I,_])}function x5({connection:e,setError:t}){return h.useCallback(async(n,a,r)=>{if(!e){const s=new Error("OpenPond App server is not connected.");throw t(s.message),s}t(null);try{await Z.resolveApproval(e,n,{decision:a,answers:r})}catch(s){const i=s instanceof Error?s.message:String(s);throw t(i),s}},[e,t])}function k5({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:r,pinnedProjects:s,projectRows:i,visibleProjectRows:c}){const d=h.useMemo(()=>pq(a,r),[a,r]),l=h.useMemo(()=>OI({provider:e,snapshot:n,preferences:t}),[e,t,n]),p=h.useMemo(()=>Array.from(new Set([...s,...c].filter(kg).map(S=>S.project.id))),[s,c]);return{commandProjectRows:h.useMemo(()=>i,[i]),contextWindowStatus:l,pinnedRows:d,sidebarWorkspaceAppIds:p}}function w5({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:r,setMentionedAppId:s}){return h.useCallback((i=null)=>{r?.();const c=i?.id?n.get(i.id)??null:null;if(c){const d=ct("local",c);s(null),e({type:"selectProject",projectId:d}),t(d),a();return}s(null),e({type:"beginNewChat",appId:i?.id??null}),a()},[e,t,n,r,a,s])}const c1={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 WG(e){return`@${e.token}`}function I5(e){return`@${T5(e)}`}function _5(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 r=a[0],s=No(a.flatMap(f=>f.capabilities.map(S=>S.id))),i=No(a.flatMap(f=>f.capabilityLabels)),c=No(a.flatMap(f=>f.connections.map(S=>S.id).filter(E5))),d=No(a.map(f=>f.id)),l=No(a.map(f=>f.setupSurface)),p=P5(n);return{provider:n,label:r.providerLabel,detail:i.length>0?i.slice(0,4).join(", "):r.description,token:p,tokens:R5(a),ref:{kind:"integration",provider:n,appIds:d,setupSurfaces:l,...c.length>0?{connectionIds:c}:{},...s.length>0?{capabilities:s}:{}}}})}function GG(e,t){const n=Un(t);return e.filter(a=>n?a.tokens.some(r=>r.includes(n)):!0).slice(0,8)}function C5(e,t){const n=A5(e);if(n.length===0)return[];const a=new Map;for(const r of n){const s=t.find(i=>i.tokens.includes(r));s&&a.set(s.provider,s)}return Array.from(a.values())}function ZG(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const r=a[1]??"",s=Un(r);if(!s)continue;const i=t.find(f=>f.tokens.includes(s));if(!i)continue;const d=(a[0]??"").indexOf("@");if(d<0||typeof a.index!="number")continue;const l=a.index+d,p=`@${r}`;n.push({detail:i.detail,displayText:I5(i),end:l+p.length,label:i.label,provider:i.provider,start:l,text:p})}return n}function R5(e){return No(e.flatMap(t=>[...c1[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Un).filter(Boolean))}function P5(e){return Un(c1[e][0]??e)}function T5(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function A5(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function No(e){return Array.from(new Set(e))}function E5(e){return typeof e=="string"&&e.length>0}function j5({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:r,selectedCloudProject:s,selectedProject:i,selectedSession:c,selectedSessionId:d}){const l=h.useMemo(()=>{const I=new Map;for(const C of e?.cloudProjects??[]){const P=I.get(C.teamId)??[];P.push(C.id),I.set(C.teamId,P)}return I},[e?.cloudProjects]),f=!!(c||r||i||s)?[]:n,S=h.useMemo(()=>_5(t),[t]),b=h.useMemo(()=>TF(a,d),[a,d]);return{chatMentionApps:f,cloudProjectIdsByTeam:l,connectedAppMentions:S,pendingApproval:b}}function M5({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:r}){const s=h.useCallback(c=>{if(!e){r("Connect to OpenPond before saving preferences.");return}Z.savePreferences(e,{codexPermissionMode:c}).then(d=>{n(d.preferences.codexPermissionMode),a(d.preferences.codexReasoningEffort),t(l=>l&&{...l,preferences:d.preferences})}).catch(d=>{r(d instanceof Error?d.message:String(d))})},[e,t,n,a,r]),i=h.useCallback(c=>{if(!e){r("Connect to OpenPond before saving preferences.");return}Z.savePreferences(e,{codexReasoningEffort:c}).then(d=>{n(d.preferences.codexPermissionMode),a(d.preferences.codexReasoningEffort),t(l=>l&&{...l,preferences:d.preferences})}).catch(d=>{r(d instanceof Error?d.message:String(d))})},[e,t,n,a,r]);return{changeCodexPermissionMode:s,changeCodexReasoningEffort:i}}const O5=6e4;function Og(e,t){if(!e)return t;const n=N5(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 d1(e,n)?e:n}function $5(e,t){const n=Og(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&d1(e,a)?e:a}function cc(e,t){let n=!1,a=!1;const r=e.map(s=>{if(s.id!==t.id)return s;n=!0;const i=Og(s,t);return i!==s&&(a=!0),i});return n?a?r:e:[t,...e]}function Cu(e,t){let n=!1,a=!1;const r=e.map(s=>{if(s.id!==t.id)return s;n=!0;const i=$5(s,t);return i!==s&&(a=!0),i});return n?a?r:e:[t,...e]}function Tf(e,t,n,a=Date.now()){const r=new Map(e.map(s=>[s.id,s]));return t.map(s=>{const i=r.get(s.id);if(i&&n){const c=L5(i,s,n,a);if(c)return c}return Og(i,s)})}function py(e,t,n,a=Date.now()){const r=new Map(e.map(l=>[l.id,l])),s=new Map(Tf(e,t,n,a).map(l=>[l.id,l])),i=new Set(r.keys()),c=t.filter(l=>!i.has(l.id)).map(l=>s.get(l.id)??l),d=e.map(l=>{const p=s.get(l.id);return p||(l1(l,t)?l:null)}).filter(l=>!!l);return[...c,...d]}function l1(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=D5(t);return a===null||n>=a}function fy(e,t,n,a=Date.now()){const r=new Map(t.map(s=>[s.id,s]));for(const s of n){const i=r.get(s.id);i&&(u1(i,s)||(e[s.id]=a))}}function N5(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function d1(e,t){return JSON.stringify(e)===JSON.stringify(t)}function D5(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 L5(e,t,n,a){const r=n[t.id];return r===void 0?null:a-r>O5||u1(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function u1(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const m1=800,z5=5e3,hy=5e4,H5=16,U5=3e4,Xn=new Map;function q5(e,t){return Xn.get(f1(e,t))?.payload??null}async function p1(e,t,n={}){const a=f1(e,t),r=Xn.get(a),s=n.limit??m1,i=n.tail??!0;if(r?.promise)return r.promise;if(!n.force&&i&&r?.payload&&Date.now()-r.fetchedAt<=U5)return gy(a,r),r.payload;const c=!!(n.force&&i&&r?.payload),d=c?r?.payload?.events.at(-1)?.id:void 0,l=Z.codexHistoryThreadIncremental(e,t,{afterEventId:d,limit:s,revision:c?r?.revision:void 0,tail:i}).then(p=>{const f=Xn.get(a)?.payload??r?.payload;if(p.unchanged){if(!f)throw new Error("Codex history revision matched without a cached thread.");return Xn.set(a,{fetchedAt:Date.now(),payload:f,revision:p.revision}),gy(a,Xn.get(a)),f}const S={session:p.session,events:p.events},b=i&&f&&!p.reset?{...S,events:B5(f.events,S.events)}:S;return Xn.set(a,{fetchedAt:Date.now(),payload:b,revision:p.revision}),vy(),b}).catch(p=>{throw Xn.get(a)?.promise===l&&Xn.delete(a),p});return Xn.set(a,{fetchedAt:r?.fetchedAt??0,payload:r?.payload,promise:l,revision:r?.revision}),vy(),l}function f1(e,t){return`${e.serverUrl}
|
|
112
|
+
${e.token}
|
|
113
|
+
${t}`}function gy(e,t){Xn.delete(e),Xn.set(e,t)}function vy(){for(;Xn.size>H5;){const e=Xn.keys().next().value;if(!e)return;Xn.delete(e)}}function B5(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 F5=500,V5=2500,K5=15e3;function W5(e){return e.active?F5:e.surface==="thread"?V5:K5}function $g(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function G5(e={}){const t={cachedPayload:e.cachedPayload??q5,clearTimer:e.clearTimer??(l=>globalThis.clearTimeout(l)),loadPayload:e.loadPayload??p1,now:e.now??Date.now,setTimer:e.setTimer??((l,p)=>globalThis.setTimeout(l,p))},n=new Map;let a=1;function r(l){const p=J5(l.connection,l.sessionId);let f=n.get(p);f||(f={connection:l.connection,disposed:!1,inFlight:null,latestPayload:t.cachedPayload(l.connection,l.sessionId),nextRefreshAt:null,sessionId:l.sessionId,subscribers:new Map,timer:null},n.set(p,f));const S=a++;return f.subscribers.set(S,l),f.latestPayload&&l.onPayload(f.latestPayload),s(f,0),()=>{const b=n.get(p);if(b){if(b.subscribers.delete(S),b.subscribers.size>0){s(b,c(b));return}b.disposed=!0,d(b),n.delete(p)}}}function s(l,p){if(l.disposed||l.subscribers.size===0||l.inFlight)return;const f=t.now()+Math.max(0,p);l.timer&&l.nextRefreshAt!==null&&l.nextRefreshAt<=f||(d(l),l.nextRefreshAt=f,l.timer=t.setTimer(()=>{l.timer=null,l.nextRefreshAt=null,i(l)},Math.max(0,p)))}async function i(l){if(l.disposed||l.subscribers.size===0||l.inFlight)return;const p=t.loadPayload(l.connection,l.sessionId,{force:!!l.latestPayload});l.inFlight=p;try{const f=await p;if(l.disposed||f===l.latestPayload)return;l.latestPayload=f;for(const S of l.subscribers.values())S.onPayload(f)}catch(f){if(l.disposed)return;for(const S of l.subscribers.values())S.onError?.(f)}finally{l.inFlight===p&&(l.inFlight=null),l.disposed||s(l,c(l))}}function c(l){const p=[...l.subscribers.values()],f=p.some(b=>b.locallyActive||b.reportedActive)||l.latestPayload?.session.status==="active"||Eg(l.latestPayload?.events??[])?.tone==="active",S=p.some(b=>b.surface==="thread")?"thread":"sidebar";return W5({active:f,surface:S})}function d(l){l.timer&&t.clearTimer(l.timer),l.timer=null,l.nextRefreshAt=null}return{subscribe:r}}const Z5=G5();function Ng(e){return Z5.subscribe(e)}function J5(e,t){return`${e.serverUrl}
|
|
114
|
+
${e.token}
|
|
115
|
+
${t}`}function Q5({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:r,setError:s}){const[i,c]=h.useState({events:[],sessionId:null}),d=Gt(t)?t:null,l=d&&i.sessionId===d?i.events:[],p=h.useCallback(f=>{c(S=>{if(!d)return{events:[],sessionId:null};const b=S.sessionId===d?S.events:[];return{events:typeof f=="function"?f(b):f,sessionId:d}})},[d]);return h.useEffect(()=>{if(!e||!d){c(b=>b.sessionId===null&&b.events.length===0?b:{events:[],sessionId:null});return}s(b=>b==="Session not found"?null:b);const f=n;return Ng({connection:e,locallyActive:f,onError:b=>s(b instanceof Error?b.message:String(b)),onPayload:b=>{const I=$g(b,f);c(C=>C.sessionId!==d?{events:I.events,sessionId:d}:{events:Dr(C.events,I.events),sessionId:d}),s(C=>C==="Session not found"?null:C),r(C=>Cu(C,I.session))},reportedActive:a==="active",sessionId:d,surface:"thread"})},[e,d,n,a,r,s]),{codexHistoryEvents:l,setCodexHistoryEvents:p}}function h1(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 Y5({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:r,setCodexHistorySessions:s,setSessions:i,sidebarFileBookmarks:c,setSidebarFileBookmarks:d,setError:l}){const[p,f]=h.useState(null),[S,b]=h.useState(null),I=h.useRef(null),C=h.useRef(null);function P(w,R){w.dataTransfer.effectAllowed="move",w.dataTransfer.setData("text/plain",`${R.type}:${R.id}`),h1(w);const O=a.map(z=>z.key);I.current=R,C.current=O,f(R),b(O)}function _(){I.current=null,C.current=null,f(null),b(null)}function M(w,R){const O=I.current;if(!O)return;const z=Od(w),$=C.current??a.map(Y=>Y.key),V=$d($,qs(O),qs(R),z);Rb($,V)||(C.current=V,b(V))}function A(w){if(!e)return;const R=a.map(H=>H.key),O=new Set(R),z=[...w.filter(H=>O.has(H)),...R.filter(H=>!w.includes(H))];if(Rb(R,z))return;const $=t,V=new Map(n.map(H=>[H.id,H])),Y=c,re=new Map(a.map(H=>[H.key,H]));r(H=>{const F={...H};return z.forEach((J,K)=>{const B=re.get(J);B?.type==="project"&&(F[B.id]={...F[B.id]??{},pinned:!0,archived:!1,order:K})}),F});const ee=H=>{const F=new Map(H.map(B=>[B.id,B])),J=z.map((B,ne)=>{const G=re.get(B),te=G?.type==="session"?F.get(G.id):null;return te?{...te,order:ne}:null}).filter(B=>!!B),K=new Map(J.map(B=>[B.id,B]));return H.map(B=>K.get(B.id)??B)};i(ee),s(ee),d(H=>{const F=new Map;return z.forEach((J,K)=>{const B=re.get(J);B?.type==="file"&&F.set(B.id,K)}),H.map(J=>{const K=F.get(J.id);return K===void 0?J:{...J,order:K}})}),Promise.all(z.map((H,F)=>{const J=re.get(H);return J?J.type==="project"?Z.patchSidebarAppPreference(e,J.id,{pinned:!0,archived:!1,order:F}):J.type==="session"?Z.patchSession(e,J.id,{order:F}):Z.patchSidebarFile(e,{workspaceKind:J.file.workspaceKind,workspaceId:J.file.workspaceId,workspaceName:J.file.workspaceName,path:J.file.path,status:"pinned",order:F,sourceSessionId:J.file.sourceSessionId}):Promise.resolve(null)})).catch(H=>{l(H instanceof Error?H.message:String(H)),r($);const F=J=>J.map(K=>V.get(K.id)??K);i(F),s(F),d(Y)})}function T(w,R){const O=I.current;if(O){const z=C.current??a.map(V=>V.key),$=$d(z,qs(O),qs(R),Od(w));A($)}_()}function y(){I.current&&A(C.current??a.map(R=>R.key)),_()}return{dragItem:p,pinnedPreviewKeys:S,startPinnedDrag:P,clearSidebarDrag:_,previewPinnedDrop:M,commitPinnedDrop:T,commitPinnedPreviewDrop:y}}function X5({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:r}){const[s,i]=h.useState(null),[c,d]=h.useState(null),l=h.useRef(null),p=h.useRef(null);function f(_,M){_.dataTransfer.effectAllowed="move",_.dataTransfer.setData("text/plain",`session:${M.sessionId}`),h1(_),l.current=M,p.current=M.visibleSessionIds,i(M.sessionId),d(M.visibleSessionIds)}function S(_,M){const A=l.current;if(!A)return;const T=p.current??A.visibleSessionIds,y=$d(T,A.sessionId,M,Od(_));e6(T,y)||(p.current=y,d(y))}function b(){l.current=null,p.current=null,i(null),d(null)}function I(_,M){const A=l.current;if(!A){b();return}const T=p.current??A.visibleSessionIds,y=$d(T,A.sessionId,M,Od(_));P(Ob(A.allSessionIds,A.visibleSessionIds,y)),b()}function C(){const _=l.current;_&&P(Ob(_.allSessionIds,_.visibleSessionIds,p.current??_.visibleSessionIds)),b()}function P(_){const M=new Map(_.map((w,R)=>[w,R])),A=new Map(t.map(w=>[w.id,w.order])),T=_.filter((w,R)=>A.get(w)!==R);if(T.length===0)return;const y=w=>w.map(R=>{const O=M.get(R.id);return O===void 0||O===R.order?R:{...R,order:O}});r(y),n(y),e&&Promise.all(T.map(w=>Z.patchSession(e,w,{order:M.get(w)}))).catch(w=>{const R=O=>O.map(z=>{const $=A.get(z.id);return $===void 0||$===z.order?z:{...z,order:$}});r(R),n(R),a(w instanceof Error?w.message:String(w))})}return{clearTaskDrag:b,commitTaskDrop:I,commitTaskPreviewDrop:C,previewTaskDrop:S,startTaskDrag:f,taskDragSessionId:s,taskPreviewSessionIds:c}}function e6(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function by({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const r=new Date().toISOString(),s=`pending_user_${a}_${r}_${Math.random().toString(36).slice(2,8)}`,i=t6(t);return{id:s,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:r,turnId:s,...i.length>0?{attachments:i}:{}}}function g1(e,t){return!t||v1(e,t)?e:[...e,t]}function v1(e,t){const n=t.afterMessageId?e.findIndex(s=>s.id===t.afterMessageId):-1,a=n>=0?n+1:0,r=Date.parse(t.timestamp);for(let s=a;s<e.length;s+=1){const i=e[s];if(i.role!=="user"||i.content!==t.content)continue;if(n>=0||!t.afterMessageId)return!0;const c=Date.parse(i.timestamp);if(!Number.isFinite(r)||!Number.isFinite(c)||c>=r)return!0}return!1}function t6(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}const n6=64e3,a6=2400,r6=680,s6={"--bg":"#141414","--panel":"#101010","--panel-soft":"#1f1f1f","--text":"#f4f4f5","--muted":"#9a9a9a","--border":"rgba(255,255,255,.08)","--font-web":'"Figtree",Inter,system-ui,sans-serif',"--orange":"#ff7a2f","--cyan":"#06b6d4","--blue":"#3aa3ff"};ve(k(Object.keys(s6)),o().min(1).max(300));const b1=u({width:m().int().min(280).max(1440),height:m().int().min(80).max(a6)}),o6=u({visualId:o().regex(/^visual_[a-f0-9]{32}$/),publicationId:o().regex(/^visual_pub_[a-f0-9]{32}$/),sessionId:o().min(1),turnId:o().min(1),output:gh,heights:v(b1).min(1).max(4)});u({html:o().min(1).max(n6),width:m().int().min(280).max(1440).default(r6),assets:v(u({name:o().regex(/^[a-zA-Z0-9_-]{1,64}$/),path:o().min(1).max(4096)})).max(8).default([])});u({previewId:o().uuid(),title:o().trim().min(1).max(200).regex(/^[^\u0000-\u001f\u007f]+$/,"Use a single-line title without control characters."),visualId:o().regex(/^visual_[a-f0-9]{32}$/).optional()});u({screenshots:v(o().min(1).max(56e5)).min(1).max(2),heights:v(b1).min(1).max(4),console:v(u({level:k(["log","warn","error"]),text:o().max(2e3)})).max(40)}).refine(e=>e.screenshots.length===e.heights.length,"Each measured width needs a screenshot.");function ue(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 xs(e){const t=e.trim();if(!t||!t.startsWith("{")&&!t.startsWith("["))return null;try{return JSON.parse(t)}catch{return null}}function ce(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function vr(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function i6(e,t,n){if(t.name==="workspace_action_result"){const a=vr(e,r=>r.role==="assistant"&&r.turnId===t.turnId&&r.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:Af([...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 c6(e){if(e.name!=="workspace_action"&&e.name!=="workspace_action_result")return null;const t=ce(e.data),n=ce(e.args),a=ue(n,["actionName"])??ue(ce(n?.input),["actionName"])??yp(t)??yp(ce(t?.run))??yp(ce(t?.agentRun));if(!(e.action==="sandbox_run_action"||e.action==="profile_run_action"||!!a||t?.openPondActionRun===!0||t?.openPondProfileActionRun===!0)||!a)return null;const s=ce(t?.run)??ce(t?.agentRun),i=ce(s?.metadata),c=ce(t?.actionSummary)??ce(s?.actionSummary)??ce(i?.actionSummary),d=ce(t?.action)??c??ce(i?.selectedAction)??null,l=ce(t?.responseSummary)??ce(s?.responseSummary)??ce(i?.responseSummary),p=ce(t?.sourceSummary)??ce(s?.sourceSummary)??ce(i?.sourceSummary),f=ce(t?.traceSummary)??ce(s?.traceSummary)??ce(i?.traceSummary),S=ce(t?.evalSummary)??ce(s?.evalSummary)??ce(i?.evalSummary),b=Af([...$r("artifact",t?.artifactRefs,"Artifact"),...$r("artifact",d?.artifactRefs,"Artifact"),...$r("artifact",c?.artifactRefs,"Artifact"),...$r("artifact",l?.artifactRefs,"Artifact"),...$r("trace",t?.traceArtifactRefs,"Trace"),...$r("trace",f?.artifactRefs,"Trace"),...$r("eval",t?.evalResultArtifactRefs,"Eval"),...$r("eval",S?.artifactRefs,"Eval"),...$r("output",t?.outputRefs,"Output")]),I=ue(p,["sourceRef","ref"]);return I&&b.push({id:Ef("source",I),kind:"source",label:"Source",target:I}),{actionName:a,title:ue(d,["label","title","name"])??ue(i,["selectedActionLabel"])??f6(a),status:l6(e,l,s),responseText:ue(l,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ue(s,["id","runId"])??ue(t,["runId","agentRunId"])??null,projectId:ue(s,["projectId"])??ue(t,["projectId"])??ue(n,["projectId"])??null,agentId:ue(s,["agentId"])??ue(t,["agentId"])??ue(n,["agentId"])??null,agentName:ue(ce(d?.implementation),["agentName"])??ue(d,["agentName"])??ue(i,["selectedAgentName"])??null,sandboxId:ue(s,["sandboxId"])??ue(t,["sandboxId"])??ue(ce(t?.sandbox),["id"])??ue(ce(t?.createdSandbox),["id"])??ue(n,["sandboxId"])??null,runtimeId:ue(s,["runtimeId"])??ue(t,["runtimeId"])??null,implementationType:ue(t,["implementationType"])??ue(d,["implementationType","type","kind"])??ue(ce(d?.implementation),["type","kind"])??ue(i,["implementationType"])??(e.action==="profile_run_action"||t?.openPondProfileActionRun===!0?"openpond-profile-action":null),sourceRef:I,manifestHash:ue(p,["manifestHash"])??ue(t,["manifestHash"])??ue(i,["manifestHash"])??null,refs:Af(b),childCalls:u6(t,s,i)}}function yp(e){return e?ue(e,["actionName","name"])??ue(ce(e.action),["actionName","name"])??ue(ce(e.actionSummary),["actionName","name"])??ue(ce(e.selectedEntrypoint),["name"]):null}function l6(e,t,n){if(e.status==="failed")return"failed";const a=ue(t,["status"]);if(a==="failed")return"failed";if(a==="running"||a==="pending")return a;if(a==="available"||e.status==="completed")return"completed";const r=ue(n,["status"]);return r==="failed"?"failed":r==="succeeded"||r==="completed"?"completed":r==="queued"||r==="running"||r==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function $r(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(r=>{const s=d6(e,r,n);return s?[s]:[]})}function d6(e,t,n){if(typeof t=="string"&&t.trim()){const i=t.trim();return{id:Ef(e,i),kind:e,label:n,target:i}}const a=ce(t);if(!a)return null;const r=ue(a,["url","webUrl","artifactPath","path","ref"])??ue(ce(a.artifact),["url","webUrl","path","ref"]);if(!r)return null;const s=ue(a,["label","title","name","type","kind"])??n;return{id:Ef(e,r),kind:e,label:s,target:r}}function Af(e){const t=new Set,n=[];for(const a of e){const r=`${a.kind}:${a.target}`;t.has(r)||(t.add(r),n.push(a))}return n}function Ef(e,t){return`${e}:${t}`}function u6(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(r=>m6(r)).slice(0,6)}function m6(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const r=ce(n);if(!r)return[];const s=ue(r,["id","runId","callId"])??`child_${a+1}`,i=ue(r,["label","title","actionName","name","tool"])??ue(ce(r.action),["label","name"])??"Implementation call",c=ue(r,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:s,label:i,status:p6(r),detail:c}]})}function p6(e){const t=ue(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function f6(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const h6=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function y1(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:h6.has(t.slice(n).toLowerCase())}function S1(e){return e.split("/").filter(Boolean).pop()??e}function g6(e){if(!Mf(e))return;const t=ce(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??Bs(e.data)??Bs(e.args)??Bs(e.output);if(!(!a||!y1(a)))return{path:a,appId:e.appId??null,title:S1(a)}}function v6(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return jf(e.data,t,n),t.slice(0,12)}function jf(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const c of e)jf(c,t,n,a+1);return}const r=ce(e);if(!r)return;const s=ue(r,["path","artifactRef"]),i=ue(r,["contentType","mimeType"]);s&&i&&!n.has(s)&&(n.add(s),t.push({path:s,title:ue(r,["title","name"])??S1(s),contentType:i,sizeBytes:typeof r.sizeBytes=="number"?r.sizeBytes:null}));for(const c of Object.values(r))jf(c,t,n,a+1)}function Mf(e){if(e.name!=="tool.started"&&e.name!=="tool.completed")return!1;const t=ce(e.data);return typeof t?.openpondImagePreviewPath=="string"&&t.openpondImagePreviewPath.trim()?!0:[e.output,e.action,ue(t,["tool","toolName","tool_name","name","functionName","function_name","command"]),ue(ce(t?.input),["tool","toolName","tool_name","name"]),ue(ce(t?.arguments),["tool","toolName","tool_name","name"]),ue(ce(t?.args),["tool","toolName","tool_name","name"])].filter(a=>!!a).some(a=>a.toLowerCase().includes("view_image"))}function Bs(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(Sp(n)&&y1(e.trim()))return e.trim();const r=xs(e);if(r!==null){const s=Bs(r,t+1,n);if(s)return s}return b6(e)}if(Array.isArray(e)){for(const r of e){const s=Bs(r,t+1,n);if(s)return s}return null}const a=ce(e);if(!a)return null;for(const[r,s]of Object.entries(a)){if(!Sp(r))continue;const i=Bs(s,t+1,r);if(i)return i}for(const[r,s]of Object.entries(a)){if(Sp(r))continue;const i=Bs(s,t+1,r);if(i)return i}return null}function Sp(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function b6(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 y6(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=x6(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 S6(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=x1(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 x6(e){return x1(e).providerLabel}function x1(e){const t=ce(e.args),n=ce(e.data),a=ce(n?.result),r=rh(ue(t,["provider"])??ue(a,["provider"])??ue(n,["provider"])??void 0),s=ue(a,["providerLabel"])??ue(n,["providerLabel"])??(r?RS(r)?.label:null)??"connected app",i=ue(t,["operation"]),c=ue(a,["operation"])??ue(n,["operation"]),d=xp(t?.capabilityIds)||xp(a?.capabilityIds)||xp(n?.capabilityIds);return{providerLabel:s,providerOperation:i,operation:c,capabilityCount:d}}function xp(e){return Array.isArray(e)?e.length:0}function k1(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()||kp(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:kp("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:kp("goal_context")}:null}function kp(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function Ru(e){return e.name==="diagnostic"&&ce(e.data)?.kind==="goal_context"}const k6="Steered by user";function w6(e){return e?.trim().toLowerCase()===k6.toLowerCase()}function I6(e,t){if(!t.turnId)return;T6(e,t.turnId);const n=_6(t);if(!n)return;const a=P6(e,t.turnId);if(a){a.refinerActivity=n;return}const r={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},s=e.findIndex(i=>i.role==="assistant"&&i.turnId===t.turnId);s>=0?e.splice(s,0,r):e.push(r)}function _6(e){const t=ce(e.data),n=ce(t?.activity);return n?C6(n,e):R6(e,t)}function JG(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 · ${M6(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function C6(e,t){const n=ur(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":ur(e.result,["no_action","routed","applied","retained"]),r=Kn(e.reason)??t.output??t.error??null;return{state:n,visibility:ur(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Kn(e.workspaceId),decision:ur(e.decision,["no_action","route","propose"]),route:Kn(e.route),operation:ur(e.operation,["create","update","delete"]),target:Kn(e.target),summary:Kn(e.summary)??w1(n,a),expectedOutcome:Kn(e.expectedOutcome),reason:r,evidenceBasis:A6(e.evidenceBasis),critiqueStatus:ur(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:ur(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:E6(e.validationReceipts),edits:j6(e.edits),refs:{trigger:dr(e.trigger),outcome:dr(e.outcome),proposal:dr(e.proposal),applyReceipt:dr(e.applyReceipt),advanceReceipt:dr(e.advanceReceipt),inputHarness:dr(e.inputHarness),outputHarness:dr(e.outputHarness)}}}function R6(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",r=ce(t?.outcome),s=ce(t?.proposal),i=r?.routed===!0,c=Kn(t?.workspaceAdvance),d=n?"failed":a?s?c==="advanced"||/\bapplied\b/i.test(e.output??"")?"applied":"retained":i?"routed":"no_action":null;return{state:n?"failed":a?"completed":"running",visibility:"material_only",result:d,workspaceId:null,decision:s?"propose":i?"route":a?"no_action":null,route:Kn(r?.route),operation:null,target:null,summary:w1(n?"failed":a?"completed":"running",d),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:s?"passed":"not_applicable",validationStatus:s?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:dr(t?.trigger),outcome:dr(r),proposal:dr(s),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function P6(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(r=>r.subagentMessage))return a}return null}function T6(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 A6(e){const t=ce(e),n=ur(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:yy(t.supportingEvidenceIds),counterevidence:yy(t.counterevidence)}}function E6(e){return Array.isArray(e)?e.flatMap(t=>{const n=ce(t),a=Kn(n?.id),r=ur(n?.status,["passed","failed","blocked","skipped"]),s=Kn(n?.summary);return a&&r&&s?[{id:a,status:r,summary:s}]:[]}):[]}function j6(e){return Array.isArray(e)?e.flatMap(t=>{const n=ce(t),a=Kn(n?.id),r=ur(n?.operation,["create","update","delete"]),s=Kn(n?.target),i=Kn(n?.summary);return!a||!r||!s||!i?[]:[{id:a,operation:r,target:s,summary:i,content:typeof n?.content=="string"?n.content:null}]}):[]}function dr(e){const t=ce(e),n=Kn(t?.id),a=Kn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function yy(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Kn(e){return typeof e=="string"&&e.trim()?e.trim():null}function ur(e,t){return typeof e=="string"&&t.includes(e)?e:null}function w1(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 M6(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const Sy=64*1024,xy=8*1024;function ky(e,t){const n=I1(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=O6(e,t.turnId);if(a){a.activities=D6(a.activities??[],t,n),a.timestamp=t.timestamp;return}Do(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function Do(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(r=>r.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function O6(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(r=>r.subagentMessage))return a}return null}function Of(e,t,n){if(!t.turnId)return;const a=e.filter(c=>c.role==="activity_group"&&c.turnId===t.turnId&&!c.activities?.some(d=>d.subagentMessage)),r=a.filter(c=>c.traceState==="running"),s=r.length>0?r:a.length>0?[a[a.length-1]]:[];for(const c of s)c.traceState=n;const i=s.at(-1);i&&(i.traceCompletedAt=t.timestamp,i.timestamp=t.timestamp)}function $6(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 r=a.activities?.filter(s=>s.controlKind!=="turn_aborted")??[];r.length!==a.activities?.length&&(r.length===0?e.splice(n,1):a.activities=r)}Of(e,t,"interrupted"),!w6(t.output)&&e.push({id:t.id,role:"status_divider",content:N6(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function N6(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 D6(e,t,n=I1(t)){const a=[...e];if(t.name==="tool.started"&&ce(t.data)?.nativeTool===!0&&n.callId){const r=vr(a,s=>s.callId===n.callId&&s.state==="running");if(r){const s=r.timestamp;return Object.assign(r,n,{timestamp:s}),a}}return W6(a,t,n)||F6(a,t,n)||V6(a,t,n)||K6(a,t,n)?a:[...a,n]}function L6(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function z6(e,t){const n={id:t.id,role:"status_divider",content:H6(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:U6(t),statusTone:q6(t)};if(t.name!=="session.compaction.started"){const a=vr(e,r=>r.role==="status_divider"&&r.statusKind==="compaction"&&r.statusState==="running"&&r.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 H6(e){const t=B6(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 U6(e){return e.name==="session.compaction.started"?"running":e.name==="session.compaction.completed"?"completed":"failed"}function q6(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function B6(e){return ce(e.data)?.reason==="auto"?"auto":"manual"}function I1(e){const t=g6(e),n=e.name==="assistant.reasoning.delta"?"reasoning":a3(e),a=r3(e),r=i3(e),s=o3(e),i=c3(e),c=l3(e),d=v6(e);return{id:e.id,label:c?c.direction==="received"?"Child message received":"Child message sent":J6(e),content:c?.summary??Y6(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:Dg(e)??void 0}:{},...n&&e.name==="command.output"?{detail:$f(e)}:{},...n!=="command"&&e.name==="tool.started"&&ce(e.data)?.nativeTool===!0&&e.args&&Object.keys(e.args).length>0?{detail:ls(JSON.stringify(e.args,null,2))}:{},...n!=="command"&&e.name==="tool.completed"&&ce(e.data)?.nativeTool===!0&&e.output?{detail:ls(e.output)}:{},...n==="command"?{terminal:h3(e)}:{},...s?{meta:s}:{},...r?{receipt:r}:{},...i?{openSession:i}:{},...c?{subagentMessage:c}:{},state:Z6(e),...t?{imagePreview:t}:{},...d.length>0?{artifacts:d}:{}}}function F6(e,t,n){if(t.name==="tool.completed"){const a=wy(e,t);if(!a)return!1;const r=g3(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,...r!==null?{durationMs:r}:{}};const s=$f(t);return s&&s!==a.content&&(a.detail=Ud(a.detail,s)),!0}if(t.name==="command.output"){const a=wy(e,t);if(!a)return!1;const r=$f(t);return r&&(a.detail=Ud(a.detail,r)),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 V6(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=Dg(t),r=vr(e,i=>i.state==="running"&&i.kind!=="command"&&(a?i.callId===a:!!t.action&&i.action===t.action));if(!r)return!1;const s=n.content.trim();return r.id=n.id,r.label=n.label,r.timestamp=n.timestamp,r.state=n.state,s&&s!==r.content.trim()&&(r.content.trim()===r.action?r.content=s:r.detail=Ud(r.detail,s)),n.detail&&(r.detail=Ud(r.detail,n.detail)),r.meta=n.meta,r.receipt=n.receipt,r.imagePreview=n.imagePreview??r.imagePreview,r.artifacts=n.artifacts,!0}function K6(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=G6(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 W6(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 wy(e,t){const n=Dg(t);if(n){const a=vr(e,r=>r.kind==="command"&&r.callId===n);if(a)return a}return vr(e,a=>a.kind==="command")}function G6(e,t){const n=t.action??"",a=_1[n]??{started:"Running workspace action"};return vr(e,r=>r.state==="running"&&r.label===a.started&&r.kind!=="command"&&!r.controlKind)}function Z6(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 J6(e){if(e.name==="assistant.reasoning.delta")return ue(ce(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(Ru(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(Mf(e)&&e.name==="tool.started")return"Reading image";if(Mf(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=y6(e);if(t)return t;const n=e3(e);if(n)return n;const a=X6(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"?e.status==="failed"?"Failed":"Ran":e.name==="command.output"?"Output":e.name==="workspace_action"||e.name==="workspace_action_result"?Q6(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 _1={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 Q6(e){const t=e.action??"",n=_1[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 Y6(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=k1(e.output??"");if(n)return n.text;if(Ru(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=t3(e);if(a)return a;const r=n3(e);if(r)return r;const s=S6(e);if(s)return s;const i=C1(e);if(i)return i;if(e.name==="command.output")return P1(e.output??"");if(ce(e.data)?.nativeTool===!0)return ue(ce(e.data),["filePath","toolName"])??e.action??"Tool";if(e.name==="tool.started"||e.name==="tool.completed"){const c=e.data;if(c&&typeof c=="object"){const d=c.command;if(typeof d=="string"&&d.trim())return d;const l=c.tool;if(typeof l=="string"&&l.trim())return l;const p=c.type;if(typeof p=="string"&&p.trim())return p}}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 X6(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 e3(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 t3(e){if(!e.action?.startsWith("openpond_browser_"))return null;const t=ce(ce(e.data)?.result),n=ue(t,["output"]);if(n)return n;const a=ce(xs(e.output??"")),r=ue(a,["output"]);if(r)return r;const s=ce(e.args),i=ue(s,["url"]);return i||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function n3(e){if(e.action!=="openpond_create_improve")return null;const t=ce(ce(e.data)?.result),n=ue(t,["nextStep"]);if(n)return n;const a=ce(xs(e.output??"")),r=ue(a,["output"]);if(r)return r;const s=ce(e.args),i=ue(s,["reason"]);if(i)return i;const c=ue(s,["objective"]);return c||(e.error??null)}function a3(e){if(e.name==="command.output")return"command";if(e.name!=="tool.started"&&e.name!=="tool.completed")return;const t=ce(e.data),n=ue(t,["type"]),a=ue(t,["tool","toolName","tool_name","name","functionName","function_name"]);if(e.action==="commandExecution"||n==="commandExecution"||C1(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function r3(e){if(e.name==="turn.interrupted")return"turn_aborted";if(Ru(e))return"goal_context"}function C1(e){const t=ce(e.data),n=ue(t,["type"]),a=ue(t,["tool","toolName","tool_name","name","functionName","function_name"]),r=ce(t?.result),s=ce(xs(e.output??"")),i=ce(s?.data),c=ue(t,["command","cmd"])??ue(ce(t?.input),["command","cmd"])??ue(ce(t?.arguments),["command","cmd"])??ue(ce(t?.args),["command","cmd"])??s3(ue(t,["arguments","args","input"]))??ue(ce(e.args),["command","cmd"])??ue(r,["command","cmd"])??ue(i,["command","cmd"]);return c||e.name==="tool.started"&&(e.action==="commandExecution"||n==="commandExecution"||/(^|[._-])exec_command$/i.test(a??""))&&e.output?.trim()||null}function s3(e){if(!e)return null;const t=xs(e),n=ce(t);return ue(n,["command","cmd"])}function Dg(e){const t=ce(e.data);return ue(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function o3(e){const t=ce(e.data);if(!t)return null;const n=[],a=ce(t.workspaceToolTiming),r=typeof a?.durationMs=="number"?a.durationMs:null;r!==null&&n.push(m3(r));const s=ce(t.workspaceExecutionTarget),i=ue(s,["target"]);if(i==="sandbox"){const l=s?.hybrid===!0,p=ue(s,["sandboxId","workspaceId"]);n.push(`${l?"Hybrid ":""}sandbox${p?` ${Iy(p)}`:""}`)}else i==="local"&&n.push("local workspace");const c=ce(t.sourcePreservation);if(c?.attempted===!0)if(c.ok!==!0)n.push("checkpoint failed");else if(c.preserved===!0){const l=ue(c,["preservedSha"]);n.push(l?`checkpoint ${f3(l)}`:"checkpoint saved")}else n.push("checkpoint clean");const d=R1(t);return d&&(n.push(`receipt ${Iy(d.id)}`),n.push(`${p3(d.totalUsd)} ${d.status}`)),n.length>0?n.join(" · "):null}function i3(e){const t=R1(ce(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function c3(e){if(!e.name.startsWith("subagent."))return;const t=ce(e.data),n=ce(t?.run),a=ue(t,["childSessionId"])??ue(n,["childSessionId"]);if(!a)return;const r=ue(n,["roleId"])??ue(t,["roleId"]),s=ue(n,["status"])??ue(t,["status"]);return{sessionId:a,label:"Open conversation",...r?{roleId:r}:{},...s?{status:s}:{}}}function l3(e){if(e.name!=="subagent.message")return;const t=ce(e.data),n=ce(t?.message);if(!n)return;const a=ue(n,["id"]),r=ue(n,["kind"]),s=ue(n,["fromRunId"]),i=ue(n,["body"]);if(!a||!r||!s||!i)return;const c=ce(t?.delivery??n.delivery),d=ce(t?.modelRef),l=ue(d,["providerId"]),p=ue(d,["modelId"]),S=ue(c,["deliveredParentSessionId"])===e.sessionId&&!s.startsWith("parent:")?"received":"sent",b=Array.isArray(n.refs)?n.refs.flatMap(I=>{const C=ce(I),P=ue(C,["kind"]),_=ue(C,["id"]),M=ue(C,["label"]);return P&&_&&M?[{kind:P,id:_,label:M}]:[]}):[];return{direction:S,summary:d3(i),body:i,messageId:a,kind:r,fromRunId:s,toRunId:ue(n,["toRunId"]),toRole:ue(n,["toRole"]),childSessionId:ue(t,["childSessionId"]),roleId:ue(t,["roleId"]),modelRef:l&&p?{providerId:l,modelId:p}:null,deliveryStatus:ue(c,["status"]),wakeReason:ue(c,["wakeParentReason"]),createdAt:ue(n,["createdAt"]),refs:b}}function d3(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return u3(n,96)}function u3(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),r=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,r).trimEnd()}...`}function R1(e){const t=ce(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const r=ce(n[a]),s=ue(r,["id"]),i=ue(r,["status"]),c=ue(r,["totalUsd","retailTotalUsd"]);if(s&&i&&c)return{id:s,status:i,totalUsd:c}}return null}function m3(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function p3(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function f3(e){return e.length>12?e.slice(0,12):e}function Iy(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function P1(e){let t=e.replace(/\r\n/g,`
|
|
116
|
+
`).trim();if(!t)return"";const n=v3(t);if(n!==null)return ls(n);const a=`
|
|
117
|
+
Output:
|
|
118
|
+
`,r=t.indexOf(a);return r>=0&&b3(t.slice(0,r))&&(t=t.slice(r+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),ls(t.trim())}function $f(e){const t=P1(e.output??"");if(t)return t;const n=ce(ce(e.data)?.result);return n?ls(T1(n)):""}function h3(e){const t=ce(e.data),n=ce(t?.result),a=ce(xs(e.output??"")),r=ce(a?.data),s=ce(t?.workspaceToolTiming),i=[n?.exitCode,r?.exitCode,t?.exitCode].find(d=>typeof d=="number"),c=s?.durationMs;return{...typeof i=="number"?{exitCode:i}:{},...typeof c=="number"?{durationMs:c}:{}}}function g3(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function v3(e){const t=ce(xs(e)),n=typeof t?.action=="string"?t.action:"";if(!t||typeof t.ok!="boolean"||!n||typeof t.output!="string")return null;const a=ce(t.data);return a?T1(a,ue(t,["output"])):typeof t.output=="string"?t.output.trim():""}function T1(e,t=null){const n=ue(e,["stdout"])?.replace(/\r\n/g,`
|
|
119
|
+
`).trimEnd()??"",a=ue(e,["stderr"])?.replace(/\r\n/g,`
|
|
120
|
+
`).trimEnd()??"",r=[n,a].filter(Boolean);return r.length>0?r.join(`
|
|
121
|
+
`):t?.replace(/\r\n/g,`
|
|
122
|
+
`).trim()??""}function b3(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function Ud(e,t){const n=e??"";if(!n)return ls(t);if(n===t||n.includes(t))return n;if(t.includes(n))return ls(t);const a=n.endsWith(`
|
|
123
|
+
`)||t.startsWith(`
|
|
124
|
+
`)?"":`
|
|
125
|
+
`;return ls(`${n}${a}${t}`)}function ls(e){if(e.length<=Sy)return e;const t=`
|
|
126
|
+
|
|
127
|
+
… output omitted from live view; full output remains in task history …
|
|
128
|
+
|
|
129
|
+
`,n=Math.max(0,Sy-xy-t.length);return`${e.slice(0,xy)}${t}${e.slice(-n)}`}const y3=/\bopenpond\s+opchat\b/i,S3=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function A1(e){const t=e?.trim()||"Turn failed";return y3.test(t)&&S3.test(t)?"Server connection lost. Retry your message.":t}function x3(e,t){if((Kl(t,"code")??Kl(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(Kl(a,"code")??Kl(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const r=e??"";return/\bopchat_quota_exceeded\b/i.test(r)||/OpChat token allowance is exhausted/i.test(r)?"opchat_quota_exceeded":null}function Kl(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function k3(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 r=w3(a.activities??[]);if(r.length===0){a.deliverables=void 0;continue}const s=t.get(a.turnId)??"",i=s?I3(r,s):[];if(i.length>0){a.deliverables=i;continue}a.deliverables=n.has(a.turnId)?[r[r.length-1]]:void 0}}function w3(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 r of a.artifacts??[])t.has(r.path)||(n.delete(r.path),n.set(r.path,r));return[...n.values()]}function I3(e,t){const n=E1(t);return e.filter(a=>_3(a).some(r=>t.includes(r)||n.includes(r)))}function _3(e){const t=new Set;for(const n of[e.path,e.title,C3(e.path)]){const a=n.trim();a&&(t.add(a),t.add(E1(a)))}return[...t]}function C3(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function E1(e){try{return decodeURIComponent(e)}catch{return e}}const j1=8;function R3(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=Nf(e.data),n=e.output?Nf(xs(e.output)):null;return P3(t??n)}function qd(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const r of[...e??[],...t]){const s=M1(r.url);if(!(!s||a.has(s))&&(a.add(s),n.push(r),n.length>=j1))break}return n.length>0?n:void 0}function Nf(e,t=0){if(t>5)return null;const n=ce(e);if(!n)return null;const a=Array.isArray(n.results)?n.results:Array.isArray(n.items)?n.items:ue(n,["url"])?[n]:null;if(a)return{provider:ue(n,["provider"]),results:a};for(const r of["result","data","output"]){const s=Nf(n[r],t+1);if(s)return s}return null}function P3(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const r=T3(e.results[a],a,e.provider);if(!r)continue;const s=M1(r.url);if(!(!s||n.has(s))&&(n.add(s),t.push(r),t.length>=j1))break}return t}function T3(e,t,n){const a=ce(e);if(!a)return null;const r=ue(a,["url","href"]);if(!r||!A3(r))return null;const s=ue(a,["title"])??_y(r)??`Source ${t+1}`;return{id:ue(a,["id"])??`source_${t+1}`,title:s,url:r,sourceName:ue(a,["sourceName","source_name","source"])??_y(r),snippet:ue(a,["snippet","description"]),provider:n,faviconUrl:E3(ue(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??j3(r),publishedAt:ue(a,["publishedAt","published_at"]),updatedAt:ue(a,["updatedAt","updated_at"])}}function A3(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function M1(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function E3(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 j3(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function _y(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}function M3(e){const t=ce(e.data),n=rg.safeParse(t?.input);if(!n.success||n.data.senderKind==="user")return null;const a=n.data,r=ce(t?.delivery);if(a.senderKind==="ponder"){const l=ZD.safeParse(ce(a.payload.ponderDesktop)?.operation),p=ce(r?.peer);return!l.success||a.senderSessionId!==null||e.sessionId!==a.sessionId||p?.kind!=="ponder"||p.bindingId!==l.data.origin.scope.bindingId?null:{id:`task-input:${a.id}:received`,role:"task_message",content:a.body,timestamp:a.createdAt,turnId:a.turnId??void 0,taskMessage:{input:a,direction:"received",peer:{kind:"ponder",bindingId:l.data.origin.scope.bindingId,ponderScope:l.data.origin.scope,sessionId:"",title:"Ponder Pal",provider:"openpond"}}}}if(!a.senderSessionId)return null;const s=r?.direction==="sent"&&e.sessionId===a.senderSessionId;if(!s&&e.sessionId!==a.sessionId)return null;const i=s?a.sessionId:a.senderSessionId,c=ce(r?.peer),d=c?.sessionId===i;return{id:`task-input:${a.id}:${s?"sent":"received"}`,role:"task_message",content:a.body,timestamp:a.createdAt,turnId:s?void 0:a.turnId??void 0,taskMessage:{input:a,direction:s?"sent":"received",peer:{sessionId:i,title:d&&typeof c.title=="string"?c.title:"Another task",provider:d&&typeof c.provider=="string"?c.provider:""}}}}function Cy(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.every(n=>typeof ce(n)?.text=="string")?e.map(n=>ce(n).text).join(`
|
|
130
|
+
`):JSON.stringify(e);const t=ce(e);return typeof t?.text=="string"?t.text:e==null?"":JSON.stringify(e)}function O3(e,t){const n=ce(e.data);if(!n?.retainedHistory||e.action!=="native_tool"||!["tool.started","tool.completed"].includes(e.name))return e;const a=ce(n.content)??{},r=e.name==="tool.started",s=typeof n.callId=="string"?n.callId:null,i=r&&typeof a.name=="string"?a.name:(s?t.get(s):void 0)??"native_tool";r&&s&&t.set(s,i);let c=a.input??a.arguments;if(typeof c=="string")try{c=JSON.parse(c)}catch{c={input:c}}const d=a.error||(a.is_error===!0?a.content:null);return{...e,action:i,status:r?"started":d!=null||a.status==="error"?"failed":"completed",...r?{args:ce(c)??{}}:{output:Cy(a.output??a.content??n.content),...d!=null?{error:Cy(d)}:{}}}}function $3(e,t,n){const a=ce(n.data),r=n.name==="assistant.delta"&&a?.phase==="final_answer"&&a.nativeMessageSnapshot===!0,s=n.name==="assistant.reasoning.delta"&&(a?.phase==="commentary"||a?.phase==="reasoning");if(!r&&!s||typeof a?.nativeMessageId!="string"||!n.output)return null;const i=a.nativeMessageId;let c=t.get(i);if(c||(c={id:i,role:"assistant",turnId:n.turnId,timestamp:n.timestamp},t.set(i,c),e.push(c)),r){c.content=n.output,delete c.reasoningContent;const d=e.indexOf(c);d!==e.length-1&&(e.splice(d,1),e.push(c))}else c.content===void 0&&(c.reasoningContent=`${c.reasoningContent??""}${n.output}`);return c.timestamp=n.timestamp,c}const Ry=new WeakMap;function Pu(e){const t=Ry.get(e);if(t)return t;const n=N3(e);return Ry.set(e,n),n}function N3(e){const t=[],n=new Set,a=new Map,r=new Map,s=new Map,i=new Map;for(const c of e){const d=O3(c,s);if(d.name==="visual.published"){const p=o6.safeParse(ce(d.data)?.visual);p.success&&p.data.sessionId===d.sessionId&&!t.some(f=>f.id===p.data.publicationId)&&(Do(t,d),t.push({id:p.data.publicationId,role:"visual",visual:p.data,timestamp:d.timestamp,turnId:d.turnId}));continue}if(d.name==="task.input"){const p=M3(d);if(p){const S=a.get(p.id);if(!S)a.set(p.id,p),t.push(p);else{const b=p.taskMessage.input,I=S.taskMessage.input;(b.revision>I.revision||b.revision===I.revision&&b.updatedAt>=I.updatedAt)&&Object.assign(S,p)}continue}const f=rg.safeParse(ce(d.data)?.input);f.success&&f.data.senderKind==="user"&&f.data.kind==="steer"&&!n.has(f.data.id)&&(n.add(f.data.id),t.push({id:`task-input:${f.data.id}`,role:"user",content:f.data.body,timestamp:d.timestamp,turnId:f.data.turnId??void 0}));continue}if(d.name==="turn.started"){Do(t,d),D3(t,d);const p=U3(d.args);if(p){const f=ce(d.args)?.taskInputId,S=typeof f=="string"?a.get(`task-input:${f}:received`):null;if(S?.taskMessage?.input.kind==="followup"){S.turnId=d.turnId;continue}const b=k1(p);if(b){ky(t,{...d,name:b.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:b.text,data:{...ce(d.data)??{},kind:b.kind}});continue}t.push({id:d.id,role:"user",content:p,attachments:q3(d.args),timestamp:d.timestamp,turnId:d.turnId});const I=Py(d.args);I&&t.push({id:`${d.id}:create-improve`,role:"assistant",timestamp:d.timestamp,turnId:d.turnId,createImproveRun:I})}continue}if(d.name==="create_improve.updated"){const p=Py(d.data);if(!p)continue;const f=vr(t,S=>S.turnId===d.turnId&&!!S.createImproveRun);f?(f.createImproveRun=p,f.timestamp=d.timestamp):t.push({id:`${d.id}:create-improve`,role:"assistant",timestamp:d.timestamp,turnId:d.turnId,createImproveRun:p});continue}const l=$3(t,i,d);if(l){Do(t,d),l.sources=qd(l.sources,wp(r,d.turnId)??[]);continue}if(d.name==="assistant.delta"){const p=d.output??"";if(!p)continue;Do(t,d);const f=ce(d.data);if(f?.retainedHistory===!0&&typeof f.nativeMessageId=="string"){const b=f.nativeMessageId,I=t.find(C=>C.id===b);I?(I.content=p,I.timestamp=d.timestamp):t.push({id:b,role:"assistant",content:p,timestamp:d.timestamp,turnId:d.turnId});continue}const S=t[t.length-1];if(S?.role==="assistant"&&S.turnId===d.turnId&&!S.createImproveRun)S.content=`${S.content??""}${p}`,S.timestamp=d.timestamp,S.sources=qd(S.sources,wp(r,d.turnId)??[]);else{const b=wp(r,d.turnId);t.push({id:d.id,role:"assistant",content:p,timestamp:d.timestamp,turnId:d.turnId,...b?.length?{sources:b}:{}})}continue}if(d.name==="assistant.reasoning.delta"){const p=d.output??"";if(!p)continue;Do(t,d);const f=t[t.length-1];f?.role==="assistant"&&f.turnId===d.turnId&&f.reasoningContent!==void 0&&!f.createImproveRun?(f.reasoningContent=`${f.reasoningContent}${p}`,f.timestamp=d.timestamp):f?.role==="assistant"&&f.turnId===d.turnId&&!f.reasoningContent&&!f.createImproveRun?(f.reasoningContent=p,f.timestamp=d.timestamp):t.push({id:d.id,role:"assistant",reasoningContent:p,timestamp:d.timestamp,turnId:d.turnId});continue}if(d.name==="user_question.asked"){const p=ce(d.data),f=jE.safeParse(p?.question);if(!f.success)continue;t.push({id:d.id,role:"assistant",timestamp:d.timestamp,turnId:d.turnId,userQuestion:f.data});continue}if(d.name==="user_question.answered"||d.name==="user_question.dismissed"){const p=ce(d.data),f=ME.safeParse(p?.resolution);if(!f.success)continue;const S=vr(t,b=>b.userQuestion?.id===f.data.questionId);if(!S?.userQuestion||S.userQuestion.status!=="pending")continue;S.userQuestion={...S.userQuestion,status:f.data.action==="answer"?"answered":"dismissed",answer:f.data.action==="answer"?{optionId:f.data.optionId,text:f.data.text}:null,answeredAt:d.timestamp},S.timestamp=d.timestamp;continue}if(d.name==="turn.completed"){Of(t,d,"completed");continue}if(d.name==="turn.failed"){Of(t,d,"failed");const p=d.error??"Turn failed",f=x3(p,d.data);t.push({id:d.id,role:"error",content:A1(p),...f?{errorKind:f}:{},timestamp:d.timestamp,turnId:d.turnId});continue}if(d.name==="turn.interrupted"){$6(t,d);continue}if(L6(d)){z6(t,d);continue}if(d.name.startsWith("harness.refiner.")){I6(t,d);continue}if(d.name==="tool.started"||d.name==="tool.completed"||d.name==="skill.selected"||d.name==="skill.loaded"||d.name==="skill.load_failed"||d.name==="command.output"||d.name==="workspace_action"||d.name==="workspace_action_result"||d.name==="approval.requested"||d.name.startsWith("subagent.")||Ru(d)){if(z3(d))continue;const p=c6(d);if(p){i6(t,d,p);continue}const f=R3(d);f.length>0&&L3(t,r,d.turnId,f),ky(t,d)}if(d.name==="workspace.diff"){const p=H3(d.data);if(!p||p.filesChanged===0)continue;const f=vr(t,S=>S.role==="assistant"&&S.turnId===d.turnId);f&&(f.changeSummary=p,f.timestamp=d.timestamp)}}return k3(t),t}function D3(e,t){if(ce(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 L3(e,t,n,a){if(!n)return;const r=e[e.length-1];if(r?.role!=="assistant"||r.turnId!==n){t.set(n,qd(t.get(n),a));return}r.sources=qd(r.sources,a)}function wp(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function z3(e){if(e.name!=="approval.requested")return!1;if(e.action==="create_plan")return!0;const t=ce(e.data),n=ce(t?.approval);return t?.kind==="create_plan"||n?.kind==="create_plan"}function H3(e){const t=ZE.safeParse(e);return t.success?t.data:null}function U3(e){if(!e||typeof e!="object"||!("prompt"in e))return"";const t=e.prompt;return typeof t=="string"?t:""}function q3(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=yM.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function Py(e){const t=ce(e);if(!t)return null;const n=qc.safeParse(t.createImproveRun);return n.success?n.data:null}function QG(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 r=Math.floor(a/60);return r<48?`${r}h`:`${Math.floor(r/24)}d`}function YG(e){const t=O1(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function XG(e){const t=O1(e);return t?t.toLocaleString():""}function O1(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function B3(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[r,s]=h.useState({}),i=h.useCallback(d=>{s(l=>({...l,[d.sessionId]:d}))},[]);h.useEffect(()=>{s(d=>{let l=d;for(const[p,f]of Object.entries(d)){const S=Pu(al(n,p));v1(S,f)&&(l===d&&(l={...d}),delete l[p])}return l})},[n]);const c=h.useMemo(()=>g1(t,a?r[a]:null),[t,r,a]);return{pendingChatUserMessages:r,recordPendingChatUserMessage:i,visibleChatMessages:c}}function F3({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:r,setSessions:s}){return{changeOpenPondCommandAccessMode:h.useCallback((c,d=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const l=d?.provider==="codex"?null:d;Z.savePreferences(e,{openPondCommandAccessMode:c}).then(p=>{r(p.preferences.openPondCommandAccessMode),n(f=>f&&{...f,preferences:p.preferences})}).catch(p=>{a(p instanceof Error?p.message:String(p))}),l&&Z.patchSession(e,l.id,{openPondCommandAccessMode:c}).then(p=>{s(f=>f.map(S=>S.id===p.id?p:S))}).catch(p=>{a(p instanceof Error?p.message:String(p))})},[e,t,n,a,r,s])}}function V3({localProjects:e,cloudProjects:t,teamId:n,sessions:a,runtimeIndexes:r,appPreferences:s,selectedSessionId:i,selectedProjectId:c,archivedChatsOpen:d,projectsExpanded:l,chatRowsVisibleCount:p,sidebarFileBookmarks:f=[]}){const S=h.useMemo(()=>e.filter(Q=>!Q.hiddenFromDefaultSidebar),[e]),b=h.useMemo(()=>a.filter(Q=>!Q.archived&&Ty(Q)),[a]),I=h.useMemo(()=>b.filter(Q=>Q.pinned),[b]),C=h.useMemo(()=>b.filter(Q=>!!Q.savedForLater),[b]),P=h.useMemo(()=>a.filter(Q=>Q.archived&&Ty(Q)),[a]),_=h.useMemo(()=>new Set(e.map(Q=>Q.id)),[e]),M=h.useMemo(()=>new Set(t.map(Q=>Q.id)),[t]),A=h.useMemo(()=>mI(e),[e]),T=h.useMemo(()=>{const Q={};for(const je of a){const De=Tb(je,_,A,M);De&&(Q[je.id]=De)}const xe=new Map(a.map(je=>[je.id,je]));for(const je of a){if(Q[je.id])continue;const De=new Set([je.id]);let He=je.parentSessionId;for(;He&&!De.has(He);){if(Q[He]){Q[je.id]=Q[He];break}De.add(He),He=xe.get(He)?.parentSessionId}}return Q},[a,M,_,A]),y=h.useMemo(()=>b.filter(Q=>!Q.pinned&&!Q.savedForLater&&!Q.appId&&!T[Q.id]),[b,T]),w=h.useMemo(()=>P.filter(Q=>!Q.appId&&!Tb(Q,_,A,M)),[P,M,_,A]),R=h.useMemo(()=>{const Q={};for(const xe of b){if(xe.pinned||xe.savedForLater)continue;const je=T[xe.id];if(!je)continue;const De=Q[je];De?De.push(xe):Q[je]=[xe]}return Q},[b,T]),O=h.useMemo(()=>{const Q={};for(const xe of a){if(!$1(xe))continue;const je=Q[xe.parentSessionId];je?je.push(xe):Q[xe.parentSessionId]=[xe]}for(const xe of Object.values(Q))xe.sort((je,De)=>Date.parse(De.updatedAt)-Date.parse(je.updatedAt));return Q},[a]),z=h.useMemo(()=>S.map((Q,xe)=>{const je=ct("local",Q.id),De=qF(Q,t);return{id:je,kind:"local",project:Q,pinned:!!s[je]?.pinned,order:s[je]?.order??xe,cloudLinkTrusted:!De,cloudLinkWarning:De}}).sort(Ip),[s,t,S]),$=h.useMemo(()=>t.filter(Q=>!!n&&Q.teamId===n).map((Q,xe)=>{const je=ct("cloud",Q.id);return{id:je,kind:"cloud",project:Q,pinned:!!s[je]?.pinned,order:s[je]?.order??xe,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(Ip),[s,t,n]),V=h.useMemo(()=>new Set(S.map(Q=>Ra(Q,t)?.id??null).filter(Q=>!!Q)),[t,S]),Y=h.useMemo(()=>$.filter(Q=>!V.has(Q.project.id)),[$,V]),re=h.useMemo(()=>[...z,...Y].sort(Ip),[Y,z]),ee=h.useMemo(()=>re.filter(Q=>Q.pinned),[re]),H=h.useMemo(()=>f.filter(Q=>Q.status==="pinned"),[f]),F=h.useMemo(()=>f.filter(Q=>Q.status==="saved_for_later"),[f]),J=re,K=h.useMemo(()=>K3(J,l,c),[J,l,c]),B=h.useMemo(()=>[...ee.map(Q=>({type:"project",key:qs({type:"project",id:Q.id}),id:Q.id,item:Q,order:Q.order})),...I.map(Q=>({type:"session",key:qs({type:"session",id:Q.id}),id:Q.id,session:Q,order:Q.order})),...H.map((Q,xe)=>({type:"file",key:qs({type:"file",id:Q.id}),id:Q.id,file:Q,order:Q.order??ee.length+I.length+xe}))].sort((Q,xe)=>{if(Q.order!==xe.order)return Q.order-xe.order;if(Q.type!==xe.type){const He={project:0,session:1,file:2};return He[Q.type]-He[xe.type]}const je=Q.type==="project"?Q.item.project.name:Q.type==="session"?Q.session.title:Q.file.path,De=xe.type==="project"?xe.item.project.name:xe.type==="session"?xe.session.title:xe.file.path;return je.localeCompare(De)}),[H,ee,I]),ne=h.useMemo(()=>d?[...y,...w]:y,[d,w,y]),G=h.useMemo(()=>ne.slice(0,Math.max(Nn,p)),[ne,p]),te=h.useMemo(()=>al(r,i),[r,i]),oe=h.useMemo(()=>Pu(te),[te]),be=JI(r,i),me=QI(r,i),Re=PF(r,i);return{activeSessions:b,pinnedSessions:I,savedForLaterSessions:C,pinnedFiles:H,savedForLaterFiles:F,chatSessions:y,archivedSessions:P,pinnedProjects:ee,pinnedItems:B,projectRows:J,localProjectRows:z,visibleProjectRows:K,cloudProjectRows:Y,projectSessionRowsByProjectId:R,childSessionRowsByParentId:O,sidebarProjectIdBySessionId:T,chatRows:ne,visibleChatRows:G,sessionEvents:te,chatMessages:oe,contextUsage:be,goalRuntime:me,subagentRuntime:Re}}function Ty(e){return $1(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function $1(e){return!!(e.parentSessionId&&e.subagentRunId)}function Ip(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 K3(e,t,n){if(t||e.length<=ld)return e;const a=e.slice(0,ld);if(!n||a.some(s=>s.id===n))return a;const r=e.find(s=>s.id===n);return r?[...a.slice(0,ld-1),r]:a}function W3(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function N1(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const r=e[a];if(r?.name==="turn.started"){t=a,n=r.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const r=e[a];if(!(!r||!W3(r))&&!(n&&r.turnId&&r.turnId!==n))return r.name==="turn.completed"?"completed":"blocked"}return"pending"}function Ay(e,t){if(e.systemKind)return!1;const n=al(t,e.id);if(n.length===0)return!1;const a=N1(n);return a==="pending"||a==="none"&&D1(n)==="pending"}function Ey(e,t){if(e.systemKind||e.status!=="active")return!1;const n=al(t,e.id);if(n.length===0)return!0;const a=N1(n);return a==="pending"||a==="none"&&D1(n)!=="terminal"}function D1(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 G3({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:r,sidebarSessions:s,subagentRuntimeBySessionId:i}){const c=h.useMemo(()=>new Map(s.map(S=>[S.id,S])),[s]),d=h.useMemo(()=>{const S=new Set;for(const[b,I]of t??[]){const C=c.get(b);I.tone==="active"&&!C?.systemKind&&S.add(b)}for(const b of n.activeGoalSessionIds)c.get(b)?.systemKind||S.add(b);return r&&!a?.systemKind&&e?.tone==="active"&&S.add(r),S},[e,t,n,a,r,c]),l=h.useMemo(()=>{const S=new Set(d);for(const[b,I]of i??[]){const C=c.get(b);I.activeCount>0&&!C?.systemKind&&S.add(b)}for(const b of n.activeSubagentSessionIds)c.get(b)?.systemKind||S.add(b);for(const b of s)b.systemKind||Ay(b,n)&&S.add(b.id);return a&&Ay(a,n)&&S.add(a.id),S},[d,n,a,s,c,i]),p=h.useMemo(()=>{const S=new Set(l);for(const b of s)Ey(b,n)&&S.add(b.id);return a&&Ey(a,n)&&S.add(a.id),S},[l,n,a,s]),f=!!(a&&!a.systemKind&&l.has(a.id));return{runningSessionIds:p,selectedSessionRunning:f}}const Z3=1e3;function J3(e){const[t,n]=h.useState(()=>new Date().toISOString());return h.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const r=window.setInterval(a,Z3);return()=>window.clearInterval(r)},[e]),t}function Q3(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:r,goalRuntime:s,locallyActiveCodexHistorySessionIds:i,pinnedSessions:c,savedForLaterSessions:d,projectSessionRowsByProjectId:l,rightChatHistoryEvents:p,runtimeIndexes:f,selectedSession:S,selectedSessionId:b,serverId:I,setCodexHistorySessions:C,sidebarSessions:P,subagentRuntime:_,visibleChatRows:M,visibleProjectRows:A}=e,[T,y]=h.useState({});h.useEffect(()=>{y({})},[I]);const w=h.useMemo(()=>{const B=[],ne=new Set,G=oe=>{!oe||oe.id===b||!Gt(oe.id)||ne.has(oe.id)||(ne.add(oe.id),B.push(oe.id))};for(const oe of n)(oe.status==="active"||i.has(oe.id))&&G(oe);const te=B.length;for(const oe of A)for(const be of(l[oe.id]??[]).slice(0,2))G(be);for(const oe of r)for(const be of(l[oe]??[]).slice(0,ld))G(be);for(const oe of c)G(oe);for(const oe of d)G(oe);for(const oe of M)G(oe);return[...B.slice(0,te),...B.slice(te,te+8)].join(`
|
|
131
|
+
`)},[n,r,i,c,d,l,b,M,A]),R=h.useCallback(B=>{y(ne=>ne[B.session.id]===B.events?ne:{...ne,[B.session.id]:B.events}),C(ne=>Cu(ne,B.session))},[C]),O=h.useMemo(()=>{if(!w)return"";const B=new Set(w.split(`
|
|
132
|
+
`).filter(Boolean));return P.filter(ne=>B.has(ne.id)&&ne.status==="active").map(ne=>ne.id).join(`
|
|
133
|
+
`)},[w,P]),z=h.useMemo(()=>w?w.split(`
|
|
134
|
+
`).filter(B=>i.has(B)).join(`
|
|
135
|
+
`):"",[w,i]);h.useEffect(()=>{!S||!b||!Gt(b)||t.length===0||R({session:S,events:t})},[R,t,S,b]),h.useEffect(()=>{if(!a||!w)return;const B=a,ne=w.split(`
|
|
136
|
+
`).filter(Boolean),G=new Set(O.split(`
|
|
137
|
+
`).filter(Boolean)),te=new Set(z.split(`
|
|
138
|
+
`).filter(Boolean)),oe=ne.map(be=>Ng({connection:B,locallyActive:te.has(be),onPayload:me=>R($g(me,te.has(be))),reportedActive:G.has(be),sessionId:be,surface:"sidebar"}));return()=>oe.forEach(be=>be())},[R,O,z,w,a]);const $=h.useMemo(()=>new Map(P.map(B=>[B.id,B])),[P]),V=h.useMemo(()=>{const B=new Map(f.latestGoalRuntimeBySessionId);for(const ne of P){const G=ne.status==="active"?gp(ne.metadata):null;G&&B.set(ne.id,G)}for(const ne of[T,p])for(const[G,te]of Object.entries(ne)){const oe=$.get(G),be=oe?.status==="active"?gp(oe.metadata):null,me=_f(te)??Eg(te)??(oe?.status==="active"?Hd(te)??be:null);me?B.set(G,me):B.delete(G)}if(b)if(s)B.set(b,s);else if(S?.status==="active"&&t.length>0){const ne=_f(t)??Hd(t)??gp(S.metadata);ne?B.set(b,ne):B.delete(b)}else(!Gt(b)||t.length>0)&&B.delete(b);return B},[t.length,T,s,p,f.latestGoalRuntimeBySessionId,S?.status,S?.metadata,b,$,P]),Y=h.useMemo(()=>[...V.values()].some(B=>B.tone==="active"&&!!B.observedAt),[V]),re=J3(Y),ee=h.useMemo(()=>Y?new Map([...V].map(([B,ne])=>[B,rF(ne,re)??ne])):V,[V,re,Y]),H=b?ee.get(b)??s:s,F=h.useMemo(()=>{const B=new Map(f.latestSubagentRuntimeBySessionId);return b&&(_?B.set(b,_):B.delete(b)),B},[f.latestSubagentRuntimeBySessionId,b,_]),{runningSessionIds:J,selectedSessionRunning:K}=G3({goalRuntime:H,goalRuntimeBySessionId:ee,runtimeIndexes:f,selectedSession:S,selectedSessionId:b,sidebarSessions:P,subagentRuntimeBySessionId:F});return{goalRuntime:H,runningSessionIds:J,selectedSessionRunning:K,sidebarGoalRuntimeBySessionId:ee,sidebarSubagentRuntimeBySessionId:F}}function Y3({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:r}){h.useEffect(()=>{const s=i=>{if((i.metaKey||i.ctrlKey)&&i.key.toLowerCase()==="k"){i.preventDefault(),n(null),a(c=>!c);return}if(i.key==="Escape"&&e){i.preventDefault(),a(!1),r(""),n(null);return}i.key==="Escape"&&t&&(i.preventDefault(),n(null))};return document.addEventListener("keydown",s),()=>document.removeEventListener("keydown",s)},[e,t,r,a,n])}function X3({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:r,setError:s,onDisconnected:i}){h.useEffect(()=>{if(!n?.token||e===null)return;const c=n;let d=null,l=[],p=null,f=null,S=!1;const b=new Map;let I=0;const C=16;function P(){d!==null&&(window.clearTimeout(d),d=null)}function _(){s($=>$==="Event stream disconnected"?null:$)}function M(){p=null;const $=l;if(l=[],$.length===0)return;I=Date.now(),t($);const V=eV($);V.length>0&&r(Y=>V.reduce(cc,Y)),a(Y=>{let re=Y;for(const ee of $)if(ee.name==="approval.requested"&&ee.data&&(re=[ee.data,...re]),ee.name==="approval.resolved"&&ee.data&&typeof ee.data=="object"){const H=ee.data;H.approvalId&&(re=re.filter(F=>F.id!==H.approvalId))}return re})}function A(){const $=Date.now()-I;if($>=C){p!==null&&(window.clearTimeout(p),p=null),M();return}p===null&&(p=window.setTimeout(M,C-$))}function T($){y($),l.push($),A()}function y($){if(!(!$.sessionId||!$.name.startsWith("harness.refiner."))){if($.name==="harness.refiner.completed"||$.name==="harness.refiner.failed"){b.delete($.sessionId);return}($.name==="harness.refiner.queued"||$.name==="harness.refiner.started")&&(b.set($.sessionId,typeof $.sequence=="number"?$.sequence:0),w())}}function w(){f!==null||b.size===0||(f=window.setTimeout(()=>{f=null,R()},1e3))}async function R(){if(!(S||b.size===0)){S=!0;try{await Promise.all([...b].map(async([$,V])=>{const Y=await Z.runtimeEventsPage(c,{sessionId:$,afterSequence:V,limit:100});for(const re of Y.events){const ee=re.event;b.set($,Math.max(b.get($)??0,re.sequence)),T(ee)}}))}catch{}finally{S=!1,w()}}}function O(){p!==null&&(window.clearTimeout(p),p=null),M()}document.addEventListener("visibilitychange",O);const z=cC(n,$=>{P(),_(),T($)},()=>{P(),d=window.setTimeout(()=>{z.isOpen()||(s("Event stream disconnected"),i?.())},2e3)},()=>{P(),_(),window.dispatchEvent(new Event("openpond-runtime-connected"))},{afterSequence:e});return()=>{P(),p!==null&&window.clearTimeout(p),f!==null&&window.clearTimeout(f),p=null,f=null,l=[],document.removeEventListener("visibilitychange",O),z.close()}},[e,t,n,i,a,s,r])}function eV(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const r=n.name==="session.started"||n.name==="session.updated"||n.name==="session.title.updated"?"session":n.name==="subagent.started"||n.name==="subagent.failed"?"childSession":null;if(!r)continue;const s=Zp.safeParse(a[r]);s.success&&t.set(s.data.id,s.data)}return[...t.values()]}function _p(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function tV(e){return typeof e=="string"&&e.trim()?e.trim():null}function nV(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=_p(n.data),r=_p(a?.createImproveRun);if(r?.state!=="ready_local"&&r?.state!=="released"||_p(r.adapter)?.kind!=="local")continue;const i=tV(r.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",i].join(":")}return null}const aV=332,jy=244,My=560,rV=560,Oy=320,$y=2400,sV=440;function Cp(e){const t=typeof window>"u"?My:Math.min(My,Math.max(jy,window.innerWidth-420));return Math.min(t,Math.max(jy,Math.round(e)))}function Rp(e){const t=typeof window>"u"?$y:Math.min($y,Math.max(Oy,window.innerWidth-sV));return Math.min(t,Math.max(Oy,Math.round(e)))}function oV(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Go=new Map;function Lg(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function L1(e,t){const n=Lg(e,t);if(!n)return null;const a=Go.get(n);return a?.updatedAt?a.agents:null}function iV(e,t,n){const a=Lg(e,n);a&&Go.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function zg(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Lg(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Go.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const r=e.fetchAgents(t).then(s=>(iV(t,s,e.accountKey),s)).catch(s=>{const i=Go.get(n);throw i?.promise===r&&Go.set(n,{agents:i.agents,promise:null,updatedAt:i.updatedAt}),s});return Go.set(n,{agents:a?.agents??[],promise:r,updatedAt:a?.updatedAt??0}),r}const cV=6e4,lV=6e4,dV=6e4,Hg=["pinned","projects","cloudProjects","chats","savedForLater"];function uV(e,t,n,a=Date.now()){for(const r of hV(t,n))z1(t[r],n[r])||(e[r]=a)}function mV(e,t,n,a=Date.now()){const r={...t};for(const[s,i]of Object.entries(n)){if(a-i>cV){delete n[s];continue}const c=vV(e,s),d=e[s];!c||z1(d,t[s])||(r[s]=d)}return r}function pV(e,t,n,a=Date.now()){for(const r of Hg)t[r]!==n[r]&&(e[r]=a)}function fV(e,t,n,a=Date.now()){const r={...t};for(const s of Hg){const i=n[s];if(i!==void 0){if(a-i>lV){delete n[s];continue}if(e[s]===t[s]){delete n[s];continue}r[s]=e[s]}}return gV(e,r)?e:r}function Ny(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function Dy(e,t,n=Date.now()){return t?n-t.changedAt>dV?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function hV(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function z1(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function gV(e,t){return Hg.every(n=>e[n]===t[n])}function vV(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const bV=5e4,as="\0openpond-unscoped-runtime-events",cr=[];class yV{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=cr;summaryEventsSnapshot=cr;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=Hy(t.perSessionLimit??Ag,"perSessionLimit"),this.totalLimit=Hy(t.totalLimit??bV,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return zy();const n=new Map;let a=0;for(const l of t){if(this.eventKeyById.has(l.id)){a+=1;continue}const p=l.sessionId||as,f=n.get(p);f?f.push(l):n.set(p,[l]),this.eventKeyById.set(l.id,p)}if(n.size===0)return{...zy(),duplicateEventCount:a};const r=new Set;let s=0,i=0,c=!1;for(const[l,p]of n){p.some(Uy)&&(c=!0);const f=this.entries.get(l),S=f?.snapshot.events??cr,b=Math.max(0,Math.min(S.length,this.perSessionLimit-p.length)),I=p.length>this.perSessionLimit?p.slice(p.length-this.perSessionLimit):p,C=b===S.length?S:S.slice(S.length-b),P=C.length===0?I:[...C,...I],_=S.slice(0,S.length-C.length);_.some(Uy)&&(c=!0);for(const T of _)this.eventKeyById.delete(T.id);for(const T of p.slice(0,p.length-I.length))this.eventKeyById.delete(T.id);const A={eventIds:new Set(P.map(T=>T.id)),lastTouched:++this.clock,retained:f?.retained??this.retainedKeys.has(l),snapshot:{events:P,latestSequence:wf(P),revision:(f?.snapshot.revision??0)+1}};this.entries.set(l,A),this.eventCount+=P.length-S.length,s+=I.length,i+=_.length+p.length-I.length,r.add(l)}const d=this.enforceTotalLimit(r);return i+=d,this.publish(r,c||d>0),xV({acceptedEventCount:s,duplicateEventCount:a,evictedEventCount:i,changedKeys:r})}mergeBootstrap(t){const n=SV(t),a=new Set([...this.entries.keys(),...n.keys()]),r=[];for(const s of a){const i=n.get(s)??cr,c=this.entries.get(s)?.snapshot.events??cr;r.push(...QB(i,c))}return this.replace(r)}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=cr,this.summaryEventsSnapshot=cr;const r=this.append(t);for(const d of this.retainedKeys){const l=this.entries.get(d);l&&(l.retained=!0)}const s=this.eventKeyById;let i=0;for(const d of n)s.has(d)||(i+=1);const c=new Set([...a].filter(d=>!this.entries.has(d)));return c.size>0&&this.publish(c,!0),{...r,evictedEventCount:r.evictedEventCount+i,changedSessionIds:new Set([...r.changedSessionIds,...[...c].filter(d=>d!==as)]),unscopedEventsChanged:r.unscopedEventsChanged||c.has(as)}}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=cr,this.summaryEventsSnapshot=cr,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??Ly:Ly;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(kV),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!==as&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(as)?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[r,s]=a,i=this.eventCount-this.totalLimit;if(!s.retained||s.snapshot.events.length<=i){n+=s.snapshot.events.length,this.removeEntry(r),t.add(r);continue}const c=s.snapshot.events.slice(0,i),d=s.snapshot.events.slice(i);for(const l of c)this.eventKeyById.delete(l.id);s.eventIds=new Set(d.map(l=>l.id)),s.snapshot={events:d,latestSequence:wf(d),revision:s.snapshot.revision+1},this.eventCount-=c.length,n+=c.length,t.add(r)}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 r of this.listenersByKey.get(a)??[])r();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const Ly=Object.freeze({events:cr,latestSequence:null,revision:0});function SV(e){const t=new Map;for(const n of e){const a=n.sessionId||as,r=t.get(a);r?r.push(n):t.set(a,[n])}return t}function xV(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==as)),unscopedEventsChanged:e.changedKeys.has(as)}}function zy(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function kV(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 Hy(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function Uy(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const wV=256,qy=15e3,IV=5e3,_V=3e4;class CV{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){RV(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,PV(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 r=this.now(),s=this.entries.get(t);if(s?.state==="loading"&&!this.expired(s,r))return s.promise;if(s?.state==="failed"&&!this.expired(s,r))return Promise.resolve(null);const i=this.generation,c=n().then(d=>this.generation!==i?null:(this.entries.set(t,{state:"ready",url:d.url,expiresAt:d.expiresAt,lastAccessedAt:this.now()}),this.prune(),d.url)).catch(()=>{if(this.generation!==i)return null;const d=this.now();return this.entries.set(t,{state:"failed",expiresAt:d+(this.options.failureTtlMs??IV),lastAccessedAt:d}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:c,expiresAt:r+(this.options.loadingTtlMs??_V),lastAccessedAt:r}),this.prune(),c}clear(){this.generation+=1,this.entries.clear()}watch(t,n,a){let r=!1,s=0,i=0,c;const d=async(l=!1)=>{if(r)return;const p=++s;clearTimeout(c),l&&this.entries.get(t)?.state!=="loading"&&this.entries.delete(t);const f=this.get(t);a({url:f,status:f?"ready":"loading"});const S=await this.load(t,n);if(r||p!==s)return;if(a({url:S,status:S?"ready":"error"}),!S){++i<=3&&(c=setTimeout(()=>{d()},[5e3,15e3,3e4][i-1]));return}i=0;const b=this.entries.get(t),I=Math.max(1e3,(b?.expiresAt??this.now()+6e4)-this.now()-(this.options.expirySkewMs??qy));c=setTimeout(()=>{d()},I)};return d(),{refresh:(l=!1)=>{i=0,d(l)},close:()=>{r=!0,s+=1,clearTimeout(c)}}}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,r]of this.entries)this.expired(r,t)&&this.entries.delete(a);const n=this.options.maxEntries??wV;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??qy:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const By=new CV;function e7(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function RV(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function PV(e,t,n){e.delete(t),e.set(t,n)}const TV={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function AV(e){return{label:TV[e],ready:e==="ready",stage:e}}function EV(e){let t=0,n=!1,a=!1,r=null;async function s(){for(;n&&!a;){n=!1;const i=t;try{const c=await e.fetch();!a&&i===t&&e.apply(c)}catch(c){!a&&i===t&&e.onError(c)}}}return{refresh(){return a?Promise.resolve():(t+=1,n=!0,r??=s().finally(()=>{r=null}),r)},invalidate(){t+=1,r&&(n=!0)},dispose(){a=!0,t+=1,n=!1}}}function jV({connection:e,events:t,refreshRef:n,setBootstrap:a,setError:r}){h.useEffect(()=>{if(!e)return;const i=EV({fetch:()=>Z.accountScopeSnapshot(e),apply:d=>a(l=>l&&{...l,account:d.account,accountMeta:d.accountMeta,preferences:d.preferences,configuration:d.configuration,providers:d.providers,apps:d.apps,appsError:d.appsError,appsMeta:d.appsMeta,cloudProjects:d.cloudProjects}),onError:d=>r(d instanceof Error?d.message:String(d))});n.current=i;const c=()=>{i.refresh()};return window.addEventListener("focus",c),i.refresh(),()=>{i.dispose(),n.current=null,window.removeEventListener("focus",c)}},[e,n,a,r]);let s;for(let i=t.length-1;i>=0;i-=1){const c=t[i];if(c.name==="diagnostic"&&c.status==="completed"&&(c.action?.startsWith("openpond.account.")||c.action==="openpond.preferences.update")){s=c.id;break}}h.useEffect(()=>{s&&n.current?.refresh()},[e,n,s])}const MV=650,OV=1200,$V=6e4;function NV(e){const{selectedSessionId:t,setDraftModel:n,setDraftProvider:a,setCodexPermissionMode:r,setCodexReasoningEffort:s,setOpenPondCommandAccessMode:i,setError:c,setSelectedAppId:d,setSelectedProjectId:l,setSelectedSessionId:p}=e,[f,S]=h.useState(null),[b,I]=h.useState(null),[C]=h.useState(()=>new yV),P=h.useSyncExternalStore(C.subscribeSummary,C.getSummaryEvents,C.getSummaryEvents),_=h.useCallback(U=>{const ae=C.getAllEvents(),de=typeof U=="function"?U(ae):U;de!==ae&&C.replace(de)},[C]),M=h.useCallback(U=>{C.append(U)},[C]),[A,T]=h.useState(null),[y,w]=h.useState([]),[R,O]=h.useState([]),[z,$]=h.useState([]),[V,Y]=h.useState({}),[re,ee]=h.useState("connecting"),H=Pf(b?.account),F=h.useRef({}),J=h.useRef({}),K=h.useRef({}),B=h.useRef([]),ne=h.useRef([]),G=h.useRef(null),te=h.useRef(null),oe=h.useRef(!1),be=h.useRef(Date.now()),me=h.useRef(null),Re=h.useRef(null),Q=h.useRef(null);h.useEffect(()=>{By.activateConnection(f),By.activateAccountScope(H)},[f,H]);const xe=h.useCallback(U=>{oe.current||ee(U)},[]),je=h.useCallback(U=>{Y(ae=>{const de=typeof U=="function"?U(ae):U;return uV(F.current,ae,de),de})},[]),De=h.useCallback(U=>{w(ae=>{const de=typeof U=="function"?U(ae):U;return fy(J.current,ae,de),B.current=de,de})},[]),He=h.useCallback(U=>{O(ae=>{const de=typeof U=="function"?U(ae):U;return fy(K.current,ae,de),ne.current=de,de})},[]),Ie=h.useCallback(()=>{if(oe.current||me.current!==null)return;const U=()=>{me.current=null,!oe.current&&(oe.current=!0,ee("ready"))},ae=Date.now()-be.current,de=DV(ae);if(de===0){U();return}me.current=window.setTimeout(U,de)},[]);h.useEffect(()=>()=>{me.current!==null&&window.clearTimeout(me.current)},[]);const Me=h.useCallback(U=>{Q.current?.invalidate();const ae=G.current,de=!ae||ae===U.server.id;G.current=U.server.id,T(ye=>ye?.serverId===U.server.id?ye:{afterSequence:U.eventWindow?.latestSequence??wf(U.events)??0,serverId:U.server.id}),I(U),de?C.mergeBootstrap(U.events):C.replace(U.events),w(ye=>{const Oe=de?py(ye,U.sessions,J.current):Tf(ye,U.sessions,J.current);return B.current=Oe,Oe}),O(ye=>{const Oe=de?py(ye,U.codexHistorySessions??[],K.current):Tf(ye,U.codexHistorySessions??[],K.current);return ne.current=Oe,Oe}),$(U.approvals),Y(ye=>mV(ye,U.sidebarAppPreferences,F.current)),d(ye=>ye&&U.apps.some(Oe=>Oe.id===ye)?ye:null),l(ye=>{if(!ye)return null;const Oe=oI(ye);return Oe?.kind==="local"&&U.localProjects.some($e=>$e.id===Oe.id)?ct("local",Oe.id):Oe?.kind==="cloud"&&(U.cloudProjects??[]).some($e=>$e.id===Oe.id)?ct("cloud",Oe.id):U.localProjects.some($e=>$e.id===ye)?ct("local",ye):(U.cloudProjects??[]).some($e=>$e.id===ye)?ct("cloud",ye):null}),p(ye=>{if(!ye)return null;const Oe=[...U.sessions,...U.codexHistorySessions??[]];if(Oe.some(Ge=>Ge.id===ye&&!Ge.archived))return ye;if(!de)return null;const $e=B.current.find(Ge=>Ge.id===ye)??ne.current.find(Ge=>Ge.id===ye)??null;return $e&&!$e.archived&&l1($e,Oe)?ye:null})},[C,d,l,p]),Te=h.useCallback(U=>{Q.current?.invalidate(),I(ae=>ae&&{...ae,preferences:U.preferences})},[]);jV({connection:f,events:P,refreshRef:Q,setBootstrap:I,setError:c}),h.useEffect(()=>{if(t)return;const U=Sa(b?.preferences);a(U.defaultChatProvider),n(U.defaultChatModel)},[t,b?.preferences.defaultChatProvider,b?.preferences.defaultChatModel,n,a]),h.useEffect(()=>{r(Sa(b?.preferences).codexPermissionMode)},[b?.preferences.codexPermissionMode,r]),h.useEffect(()=>{s(Sa(b?.preferences).codexReasoningEffort)},[b?.preferences.codexReasoningEffort,s]),h.useEffect(()=>{i(Sa(b?.preferences).openPondCommandAccessMode)},[b?.preferences.openPondCommandAccessMode,i]),h.useEffect(()=>{if(!f||!b){te.current=null;return}if(b.account.state!=="signed_in"){te.current=null,Ie();return}const U=Pf(b.account);if(!U){te.current=null,Ie();return}Ie(),xe("team");const ae=b.preferences.defaultTeamId?.trim()??"",de=LV(U,ae,b.accountMeta.asOf??"initial");if(te.current===de)return;te.current=de;let ye=!1;const Oe=$e=>zg({teamId:$e,accountKey:U,fetchAgents:async Ge=>(await Z.listSandboxAgents(f,{teamId:Ge})).agents}).catch(()=>{!ye&&te.current===de&&(te.current=null)});return sy({accountKey:U,force:!0,fetchOrganizations:()=>Fy(f)}).then(async $e=>{if(ye)return;if($e.length===0){Ie();return}if(!!ae&&$e.some(Se=>Se.teamId===ae)){await Oe(ae),Ie();return}const yt=t5($e)?.teamId;if(!yt){Ie();return}if(ae){c("The configured default team is unavailable for this account. Select an available team in account settings."),Ie();return}await Oe(yt),ye||Ie()}).catch($e=>{ye||(te.current=null,c($e instanceof Error?$e.message:String($e)),Ie())}),()=>{ye=!0}},[Me,Te,b?.account,b?.accountMeta.asOf,b?.preferences.defaultTeamId,Ie,f,xe,c]),h.useEffect(()=>{if(!f||!H)return;let U=!1;const ae=()=>{U||(U=!0,sy({accountKey:H,force:!0,fetchOrganizations:()=>Fy(f)}).catch(()=>{}).finally(()=>{U=!1}))},de=()=>{document.visibilityState==="visible"&&ae()},ye=window.setInterval(ae,$V);return window.addEventListener("focus",ae),document.addEventListener("visibilitychange",de),()=>{window.clearInterval(ye),window.removeEventListener("focus",ae),document.removeEventListener("visibilitychange",de)}},[f,H]),pi(()=>{const U=sq();c(U||(ae=>ae?.startsWith("Preference changes have not been saved.")?null:ae))}),h.useEffect(()=>{f&&Cb(f).catch(U=>c(String(U)))},[f,H,c]);const N=h.useCallback(async()=>{xe("connecting"),T(null);const U=await wH();S(de=>oV(de,U)?de:U),xe("account");const ae=await Z.bootstrap(U);await Cb(U),Me(ae),Ie(),c(de=>de&&(AI(de)||de==="Event stream disconnected")?null:de)},[Me,Ie,xe,c]);h.useEffect(()=>{let U=!1,ae=null;const de=async ye=>{try{await N()}catch(Oe){if(U)return;c(Oe instanceof Error?Oe.message:String(Oe));const $e=Math.min(5e3,750+ye*750);ae=window.setTimeout(()=>{de(ye+1)},$e)}};return de(0),()=>{U=!0,ae!==null&&window.clearTimeout(ae)}},[N,c]);const q=h.useCallback(()=>{N().catch(()=>{})},[N]);X3({afterSequence:A?.afterSequence??null,appendEvents:M,connection:f,setApprovals:$,setSessions:De,setError:c,onDisconnected:q}),h.useEffect(()=>{if(!f||!b){Re.current=null;return}const U=nV(P);!U||Re.current===U||(Re.current=U,Z.profileCurrent(f).then(ae=>{I(de=>de&&{...de,profile:ae})}).catch(ae=>{Re.current=null,c(ae instanceof Error?ae.message:String(ae))}))},[b,f,P,c]);const X=h.useCallback(()=>{f&&Z.refreshOpenPondAccount(f).then(({account:U,accountMeta:ae})=>{I(de=>de&&{...de,account:U,accountMeta:ae})}).catch(U=>c(U instanceof Error?U.message:String(U)))},[f,c]);return{appPreferences:V,applyBootstrapPayload:Me,applyPreferencesPayload:Te,approvals:z,bootstrap:b,codexHistorySessions:R,connection:f,events:P,runtimeEventStore:C,refreshOpenPondAccount:X,sessions:y,startup:AV(re),setAppPreferences:je,setBootstrap:I,setCodexHistorySessions:He,setEvents:_,setSessions:De}}async function Fy(e){return(await Z.organizations(e)).organizations.map(_u).filter(n=>!!n).filter(n=>n.status==="active")}function DV(e){return e>=OV?0:Math.max(0,MV-e)}function LV(e,t,n){return`${e}::${t||"none"}::${n}`}function zV({appDispatch:e,error:t,setErrorState:n}){const a=h.useRef(null),r=h.useRef(null),s=h.useRef(null),i=h.useRef(0),c=h.useCallback((l,p="info",f={})=>{const S=Date.now()+ ++i.current;return e({type:"showToast",toast:{id:S,message:l,tone:p,...f}}),S},[e]),d=h.useCallback(l=>{const p=r.current,f=typeof l=="function"?l(p):l;if(Object.is(p,f))return;if(r.current=f,n(f),!f){s.current!==null&&(e({type:"clearToast",toastId:s.current}),s.current=null);return}s.current=c(HV(f),"error");const S=a.current;S&&Z.recordClientDiagnostic(S,{message:f,surface:"app",context:{href:window.location.href}}).catch(b=>{console.warn("Unable to record client diagnostic.",b)})},[e,n,c]);return h.useEffect(()=>{r.current=t,!(t||s.current===null)&&(e({type:"clearToast",toastId:s.current}),s.current=null)},[e,t]),{connectionRef:a,setError:d,showToast:c}}function HV(e){return TI(e)}const UV={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:Nn,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Ks,draftModel:wc,draftExperience:"chat",codexPermissionMode:oh,codexReasoningEffort:ih,openPondCommandAccessMode:Qd,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 Ug(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function Bd(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...r}=e;return r}return e[t]===n?e:{...e,[t]:n}}function qV(e){return Bd(e.promptDrafts,Ug(e),e.prompt)}function Yi(e,t,n={}){const a={...e,...t},r=Ug(a),s=qV(e),i=n.clearSelectedDraft?Bd(s,r,""):n.preserveCurrentPrompt?Bd(s,r,e.prompt):s;return{...e,...t,promptDrafts:i,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:i[r]??""}}function BV(e){return e==="draftExperience"||e==="selectedAppId"||e==="selectedProjectId"||e==="selectedSessionId"}function FV(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 r=String(a);return{...e,prompt:r,promptDrafts:Bd(e.promptDrafts,Ug(e),r)}}return BV(t.key)?Yi(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return Yi(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return Yi(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return Yi(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return Yi(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 rt(e,t){return n=>e({type:"field",key:t,value:n})}function VV(e){return{setQuery:rt(e,"query"),setSearchOpen:rt(e,"searchOpen"),setArchivedChatsOpen:rt(e,"archivedChatsOpen"),setSectionMenuOpen:rt(e,"sectionMenuOpen"),setProjectsExpanded:rt(e,"projectsExpanded"),setCloudProjectsExpanded:rt(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:rt(e,"chatRowsVisibleCount"),setSidebarOpen:rt(e,"sidebarOpen"),setView:rt(e,"view"),setSelectedAppId:rt(e,"selectedAppId"),setSelectedProjectId:rt(e,"selectedProjectId"),setSelectedSessionId:rt(e,"selectedSessionId"),setPrompt:rt(e,"prompt"),setDraftProvider:rt(e,"draftProvider"),setDraftModel:rt(e,"draftModel"),setDraftExperience:rt(e,"draftExperience"),setCodexPermissionMode:rt(e,"codexPermissionMode"),setCodexReasoningEffort:rt(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:rt(e,"openPondCommandAccessMode"),setBusy:rt(e,"busy"),setDiffPanelOpen:rt(e,"diffPanelOpen"),setDiffPanelExpanded:rt(e,"diffPanelExpanded"),setRightPanelMode:rt(e,"rightPanelMode"),setRightChatPanels:rt(e,"rightChatPanels"),setTerminalOpen:rt(e,"terminalOpen"),setSyncingWorkspaceAppId:rt(e,"syncingWorkspaceAppId"),setSettingsSection:rt(e,"settingsSection"),setNewProjectDialogOpen:rt(e,"newProjectDialogOpen"),setNewProjectMode:rt(e,"newProjectMode"),setNewProjectName:rt(e,"newProjectName"),setNewProjectPath:rt(e,"newProjectPath"),setNewProjectBusy:rt(e,"newProjectBusy"),setCommitDialogOpen:rt(e,"commitDialogOpen"),setCommitMessage:rt(e,"commitMessage"),setCommitIncludeUnstaged:rt(e,"commitIncludeUnstaged"),setCommitNextStep:rt(e,"commitNextStep"),setCommitDraft:rt(e,"commitDraft"),setBranchDialogOpen:rt(e,"branchDialogOpen"),setBranchDialogName:rt(e,"branchDialogName"),setToast:rt(e,"toast"),setError:rt(e,"error")}}function Xi(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function KV(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,r=new Set,s=l=>{if(!Object.is(n,l)){n=l;for(const p of r)p()}},i=()=>{const l=Xi(t);n?a.set(l,n):a.delete(l)},c=(l,p={})=>{const f=n;i(),t={...t,...l};const S=Xi(t);if(p.clear&&a.delete(S),p.preserveCurrentDraft){f?a.set(S,f):a.delete(S),s(f);return}s(p.clear?"":a.get(S)??"")},d={getScopeKey:()=>Xi(t),getSnapshot:()=>n,subscribe(l){return r.add(l),()=>r.delete(l)},set:l=>d.setForScope(Xi(t),l),setForScope(l,p){const f=Xi(t),S=l===f?n:a.get(l)??"",b=typeof p=="function"?p(S):p;Object.is(S,b)||(b?a.set(l,b):a.delete(l),l===f&&s(b))},applyAppAction(l){if(l.type==="field"){if(l.key==="prompt"){d.set(l.value);return}if(l.key==="selectedAppId"||l.key==="selectedProjectId"||l.key==="selectedSessionId"){const p=t[l.key],f=typeof l.value=="function"?l.value(p):l.value;Object.is(p,f)||c({[l.key]:f})}return}if(l.type==="patch"){const p={};"selectedAppId"in l.patch&&(p.selectedAppId=l.patch.selectedAppId),"selectedProjectId"in l.patch&&(p.selectedProjectId=l.patch.selectedProjectId),"selectedSessionId"in l.patch&&(p.selectedSessionId=l.patch.selectedSessionId),Object.keys(p).length>0&&c(p),"prompt"in l.patch&&typeof l.patch.prompt=="string"&&d.set(l.patch.prompt);return}if(l.type==="selectApp"){c({selectedAppId:l.appId,selectedProjectId:null,selectedSessionId:null});return}if(l.type==="selectProject"){c({selectedAppId:null,selectedProjectId:l.projectId,selectedSessionId:null},{preserveCurrentDraft:!0});return}if(l.type==="selectSession"){const p=l.projectId??null;c({selectedSessionId:l.sessionId,selectedAppId:p?null:l.appId??null,selectedProjectId:p});return}l.type==="beginNewChat"&&c({selectedSessionId:null,selectedAppId:l.appId,selectedProjectId:null})}};return d}function t7(e){return h.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function WV(e){return{...e,draftExperience:Mg()}}function GV(){const[e,t]=h.useReducer(FV,UV,WV),[n]=h.useState(()=>KV()),a=h.useCallback(s=>{n.applyAppAction(s),t(s)},[n]),r=h.useMemo(()=>({...VV(a),setPrompt:n.set}),[n,a]);return pi(()=>r.setDraftExperience(Mg())),{composerDraftStore:n,dispatch:a,setters:r,state:e}}function ZV(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function JV(e){const{connection:t,events:n,showToast:a}=e,r=h.useRef(new Set),s=h.useCallback(async()=>{if(t)try{const c=await Z.installMacOSCommandLineTools(t);a(c.message,"info")}catch(c){a(c instanceof Error?c.message:String(c),"error")}},[t,a]),i=h.useCallback((c="OpenPond needs Git to create and sync local projects.")=>{a(c,"error",{actionLabel:"Install Tools",onAction:()=>{s()},persistent:!0})},[a,s]);h.useEffect(()=>{if(!t)return;let c=!1;return Z.gitAvailability(t).then(d=>{c||d.ok||d.installAction!=="macos_command_line_tools"||i("OpenPond needs Git before it can create local projects.")}).catch(()=>{}),()=>{c=!0}},[t,i]),h.useEffect(()=>{for(const c of n){if(r.current.has(c.id))continue;const d=c.error??c.output??null;c.name==="workspace_action_result"&&c.status==="failed"&&ZV(d)&&(r.current.add(c.id),i("OpenPond needs Git before it can update this project."))}},[n,i])}function QV({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:r,setError:s}){const[i,c]=h.useState(()=>Sa().sidebarSectionsCollapsed),d=h.useRef(i),l=h.useRef({}),p=h.useRef(null),f=h.useRef(null),[S,b]=h.useState(aV),[I,C]=h.useState(!1),[P,_]=h.useState(rV),[M,A]=h.useState(!1),{pinned:T,projects:y,cloudProjects:w,chats:R,savedForLater:O}=i;h.useEffect(()=>{if(I)return;const G=Cp(Sa(t).sidebarWidth),te=Dy(G,p.current);p.current=te.localChange,b(te.value)},[t,I]),h.useEffect(()=>{if(M)return;const G=Rp(Sa(t).diffPanelWidth),te=Dy(G,f.current);f.current=te.localChange,_(te.value)},[M,t]),h.useEffect(()=>{const G=Sa(t).sidebarSectionsCollapsed;c(te=>{const oe=fV(te,G,l.current);return d.current=oe,oe})},[t]);const z=h.useCallback(G=>{r(te=>te&&{...te,preferences:G.preferences})},[r]),$=h.useCallback(async G=>{if(e&&Cp(Sa(t).sidebarWidth)!==G)try{z(await Z.savePreferences(e,{sidebarWidth:G}))}catch(te){s(te instanceof Error?te.message:String(te))}},[e,t,s,z]),V=h.useCallback(async G=>{if(e&&Rp(Sa(t).diffPanelWidth)!==G)try{z(await Z.savePreferences(e,{diffPanelWidth:G}))}catch(te){s(te instanceof Error?te.message:String(te))}},[e,t,s,z]),Y=h.useCallback(async G=>{if(!e)return;const te=Sa(t).sidebarSectionsCollapsed;if(!YV(te,G))try{z(await Z.savePreferences(e,{sidebarSectionsCollapsed:G}))}catch(oe){s(oe instanceof Error?oe.message:String(oe))}},[e,t,s,z]),re=h.useCallback(G=>{const te=d.current;pV(l.current,te,G),d.current=G,c(G),Y(G)},[Y]),ee=h.useCallback(()=>{const G=d.current;re({...G,pinned:!G.pinned})},[re]),H=h.useCallback(()=>{const G=d.current;re({...G,projects:!G.projects})},[re]),F=h.useCallback(()=>{const G=d.current;re({...G,cloudProjects:!G.cloudProjects})},[re]),J=h.useCallback(()=>{const G=d.current;re({...G,chats:!G.chats})},[re]),K=h.useCallback(()=>{const G=d.current;re({...G,savedForLater:!G.savedForLater})},[re]),B=h.useCallback(G=>{if(!n)return;G.preventDefault();const te=G.clientX,oe=S;let be=oe;C(!0);function me(Q){be=Cp(oe+Q.clientX-te),b(be)}function Re(){window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",Re);const Q=Ny(oe,be);Q&&(p.current=Q),C(!1),$(be)}window.addEventListener("pointermove",me),window.addEventListener("pointerup",Re,{once:!0})},[$,n,S]),ne=h.useCallback(G=>{if(a)return;G.preventDefault();const te=G.clientX,oe=P;let be=oe;A(!0);function me(Q){be=Rp(oe-(Q.clientX-te)),_(be)}function Re(){window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",Re);const Q=Ny(oe,be);Q&&(f.current=Q),A(!1),V(be)}window.addEventListener("pointermove",me),window.addEventListener("pointerup",Re,{once:!0})},[a,P,V]);return{pinnedCollapsed:T,projectsCollapsed:y,cloudProjectsCollapsed:w,chatsCollapsed:R,savedForLaterCollapsed:O,sidebarWidth:S,sidebarResizing:I,diffPanelWidth:P,diffPanelResizing:M,togglePinnedCollapsed:ee,toggleProjectsCollapsed:H,toggleCloudProjectsCollapsed:F,toggleChatsCollapsed:J,toggleSavedForLaterCollapsed:K,startSidebarResize:B,startDiffPanelResize:ne}}function YV(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function XV(e){const[t,n]=h.useState({id:0,kind:null}),[a,r]=h.useState(null),s=h.useCallback((l=null)=>{n(p=>({id:p.id+1,kind:l}))},[]),i=h.useCallback(l=>{r(l)},[]),c=null,d=h.useMemo(()=>{if(e)return eK(a,s)},[e,a,s]);return{backAction:c,breadcrumbs:d,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:i}}function eK(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"}]}function tK(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return oH.parse(await Z.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const r=await n(a);return r?iH.parse(r):null}}}function nK(e,t,n,a){async function r(s,i){if(!e)throw new Error("Connect to OpenPond to load tasks.");const c=gD.parse(i),d=new URLSearchParams({profileId:t});for(const[l,p]of Object.entries(c))p!==void 0&&d.set(l,String(p));return Z.trainingRequest(e,`${s}?${d}`,{},"GET")}return{taskInventory:async(s={})=>bD.parse(await r("/tasks",s)),taskInventoryDetail:async s=>{const i=await r("/tasks/detail",s);return{item:nw.parse(i.item),task:lu.parse(i.task)}},tasksetDraftFiles:async s=>{if(!e)return null;try{return await Z.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(s)}/files?${new URLSearchParams({profileId:t})}`,{},"GET")}catch(i){return a(i),null}},tasksetDraftFile:async(s,i)=>{if(!e)return null;try{return await Z.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(s)}/file?${new URLSearchParams({profileId:t,path:i})}`,{},"GET")}catch(c){return a(c),null}},saveTasksetDraftFile:s=>n("save-taskset-draft-file",`/taskset-drafts/${encodeURIComponent(s.draftId)}/file`,{profileId:t,...s},"PATCH"),inspectTasksetDraftSource:(s,i)=>n("inspect-taskset-draft-source","/taskset-drafts/source",{profileId:t,modelId:s,expectedModelRevision:i}),createTasksetDraftFromSource:s=>n("create-taskset-draft","/taskset-drafts",{profileId:t,sourceRequest:s}),createTasksetDraft:(s="",i)=>n("create-taskset-draft","/taskset-drafts",{profileId:t,name:s,modelId:i??null}),importTasksetDraftPackage:s=>n("import-taskset-draft-package","/taskset-drafts/import",{packagePath:s,profileId:t}),saveTasksetDraft:s=>n("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(s.id)}`,s,"PUT"),tasksetDraftWorkspace:async s=>{if(!e)return null;try{return await Z.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(s)}/workspace`,{},"GET")}catch(i){return a(i),null}},publishTasksetDraft:(s,i)=>n("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(s)}/publish`,{modelId:i??null}),refreshTasksetDraftModel:(s,i)=>n("refresh-taskset-draft-model",`/taskset-drafts/${encodeURIComponent(s.id)}/model-revision`,{expectedDraftRevision:s.revision,expectedModelRevision:i}),deleteTasksetDraft:s=>n("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(s)}`,{},"DELETE")}}function H1(e,t){return u2({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function aK(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await H1(t,n);return mk.parse(await Z.trainingRequest(e,"/models/check",a,"POST"))}function rK(e,t){return{listModelStarters:async(n,a=!1)=>{if(!e)throw new Error("Connect to OpenPond to browse model starters.");return Z.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 Z.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 mk.parse(await Z.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const Vy=1e4,Ky=3e4;function sK(e){const{connection:t,profileId:n}=e,a=h0(),r=PI(t),s=h.useMemo(()=>["training",r,n],[r,n]),i=h.useCallback(async()=>nH.parse(await Z.trainingState(t,n)),[t,n]),c=R0({queryKey:s,queryFn:i,enabled:!!t}),d=c.data??null,l=!!t&&c.isPending,[p,f]=h.useState(null),[S,b]=h.useState(null),I=h.useRef(null);I.current=d?.activityRevision??null;const C=h.useCallback(async()=>{if(!t)return null;try{const y=await a.fetchQuery({queryKey:s,queryFn:i,staleTime:0});return b(null),y}catch(y){return b(Nr(y)),null}},[t,a,s,i]),P=h.useCallback(async()=>(await a.cancelQueries({queryKey:s,exact:!0}),await a.invalidateQueries({queryKey:s,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",r,n]}),C()),[a,s,r,n,C]),_=h.useCallback(async(y,w,R,O="POST",z={})=>{if(!t)return null;z.silent||f(y);try{const $=await Z.trainingRequest(t,w,R,O);return await P(),z.silent||b(null),$}catch($){return z.silent||b(Nr($)),null}finally{z.silent||f(null)}},[t,P]),M=d?[d.jobs.some(y=>["queued","starting","running","cancelling","reconciling"].includes(y.status)),d.creations.some(y=>["planning","materializing","validating"].includes(y.state)),d.minerRuns.some(y=>["queued","running","cancelling"].includes(y.status)),d.datasetImports.some(y=>["inspecting","materializing","validating","cancelling"].includes(y.status))].some(Boolean):!1;h.useEffect(()=>{if(!t)return;let y=!0,w=null;const R=M?Vy:Ky,O=async()=>{let z=R;try{const $=await Z.trainingActivity(t,n);z=$.active?Vy:Ky,(I.current===null||I.current!==$.revision)&&await C()}catch($){b(Nr($))}y&&(w=window.setTimeout(()=>{O()},z))};return w=window.setTimeout(()=>{O()},R),()=>{y=!1,w!==null&&window.clearTimeout(w)}},[t,M,n,C]);const A=h.useMemo(()=>({...rK(t,_),saveComparisonSeries:y=>_("save-comparison-series","/comparison-series",{series:y}),saveContinualBenchIssueReview:y=>_("save-continual-support-issue-review","/continual-support/issue-reviews",{review:y},"PUT"),importContinualLearningDailyBatch:(y,w="json_upload")=>_("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:y,source:w}),saveContinualLearningDailyBatch:y=>_("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:y},"PUT"),generateContinualLearningResponses:y=>_("generate-continual-learning-responses","/continual-learning/responses",y),sealComparisonSeries:(y,w)=>_("seal-comparison-series",`/comparison-series/${encodeURIComponent(y)}/seal`,{expectedRevision:w}),archiveComparisonSeries:(y,w)=>_("archive-comparison-series",`/comparison-series/${encodeURIComponent(y)}/archive`,{expectedRevision:w}),queueComparisonRelease:y=>_("queue-comparison-release",`/comparison-series/${encodeURIComponent(y.seriesId)}/releases`,y),startComparisonEvaluation:y=>_("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(y.entryId)}/evaluations`,y),loadComparisonAttemptEvidence:y=>t?Z.trainingRequest(t,`/model-runs/${encodeURIComponent(y.runId)}/attempts/${encodeURIComponent(y.attemptId)}/evidence?kind=${y.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:y=>_("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(y.entryId)}/run`,y,"PATCH"),decideComparisonEntry:y=>_("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(y.entryId)}/decision`,y),recordComparisonPromotion:y=>_("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(y.entryId)}/promotion`,y),checkModelProject:(y,w=y.revision)=>aK(t,y,w),...tK(t,n,y=>_("begin-model-batch-review","/models/batch-review",{profileId:n,request:y})),saveModelProject:async(y,w=y.revision)=>_("save-model-project","/models",await H1(y,w),"PUT"),listHostedModelProjects:async(y={})=>{if(!t)return null;y.silent||f("list-hosted-model-projects");try{const w=await Z.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${y.refresh===!0}`,{},"GET");return y.silent||b(null),w}catch(w){return y.silent||b(Nr(w)),null}finally{y.silent||f(w=>w==="list-hosted-model-projects"?null:w)}},openHostedModelProject:(y,w,R,O={})=>_(`open-hosted-model-project:${y}`,`/hosted-model-projects/${encodeURIComponent(y)}/open`,{profileId:n,teamId:w,apiOrigin:R},"POST",O),pullHostedModelProject:y=>_(`pull-hosted-model-project:${y}`,`/hosted-model-projects/${encodeURIComponent(y)}/pull`,{profileId:n}),syncModelProject:y=>_("sync-model-project",`/models/${encodeURIComponent(y)}/sync`,{}),publishModelProjectTaskset:(y,w)=>_("publish-model-project-taskset",`/models/${encodeURIComponent(y)}/tasksets/${encodeURIComponent(w)}/publish`,{}),createScorer:(y,w,R)=>_("create-scorer","/scorers",{grader:y,tasksetId:w,modelProjectId:R??null}),prepareLearningBatch:y=>_("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:y}),...nK(t,n,_,y=>b(Nr(y))),tasksetGraderDetails:async y=>{if(!t)return null;try{return await Z.trainingRequest(t,`/tasksets/${encodeURIComponent(y)}/graders`,{},"GET")}catch(w){return b(Nr(w)),null}},inspectHuggingFaceDataset:y=>_("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:y}),materializeDatasetImport:(y,w)=>_("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(y)}/materialize`,w),cancelDatasetImport:y=>_("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(y)}/cancel`,{}),datasetRows:(y,w={})=>{if(!t)return Promise.resolve(null);const R=new URLSearchParams;w.split&&R.set("split",w.split),w.cursor&&R.set("cursor",w.cursor),R.set("limit",String(w.limit??25));for(const O of w.columns??[])R.append("column",O);return Z.trainingRequest(t,`/tasksets/${encodeURIComponent(y)}/rows?${R}`,{},"GET")},addSource:(y,w)=>_("add-source","/sources",{profileId:n,sessionId:y,turnIds:w}),addSources:y=>_("add-sources","/sources/batch",{profileId:n,sessionIds:y}),estimateSources:y=>t?Z.trainingRequest(t,"/sources/estimate",{sessionIds:y}):Promise.resolve([]),searchChats:(y,w,R=0,O=20)=>t?Z.trainingRequest(t,"/sources/search",{query:y,candidates:w,offset:R,limit:O}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:y,offset:R,limit:O,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:y=>_("remove-source",`/sources/${encodeURIComponent(y)}`,{},"DELETE"),deleteTaskset:y=>_("delete-model",`/tasksets/${encodeURIComponent(y)}`,{},"DELETE"),runBenchmark:(y,w,R,O)=>_(`run-benchmark-${w}`,`/tasksets/${encodeURIComponent(y)}/benchmark-runs`,{phase:w,model:R,reasoningEffort:O,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(y,w,R)=>_("run-harness-refiner-benchmark",`/models/${encodeURIComponent(y)}/harness-refiner-benchmark`,{profileId:n,model:w,reasoningEffort:R,maximumSpendUsd:10}),acceptHarnessReview:(y,w,R=null,O=null)=>_("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:y,reviewRef:w,analysisModel:R,analysisReasoningEffort:O}),startCreation:(y,w={})=>_("create-taskset","/task-creations",{profileId:n,sourceIds:y,surface:w.surface??"training_page",mode:w.mode??"defaults",entryMode:w.entryMode??"manual",resourceIntent:w.resourceIntent??"workproduct",buildIntent:w.buildIntent??"demonstrations",buildSpecification:w.buildSpecification??null,objective:w.objective??null,methodHint:w.methodHint??null,preferredBaseModelId:w.preferredBaseModel?.modelId??null,preferredBaseModel:w.preferredBaseModel??null,candidateId:w.candidateId??null,analysisModel:w.analysisModel??null,analysisReasoningEffort:w.analysisReasoningEffort??null,createImproveRunId:w.createImproveRunId??null,targetIntent:w.targetIntent??{kind:"model",id:null,displayName:null,operation:"create"}}),createModelFromTaskset:(y,w)=>_("create-model","/models/from-taskset",{profileId:n,tasksetId:y,preferredBaseModelId:w.modelId,preferredBaseModel:w}),scanBaseModels:async()=>{if(!t)return null;f("scan-base-models");try{const y=await C();return b(null),y}catch(y){return b(Nr(y)),null}finally{f(null)}},approveDisclosure:(y,w)=>_("approve-disclosure",`/task-creations/${encodeURIComponent(y)}/disclosure`,{approved:w}),retryCreation:y=>_("retry-creation",`/task-creations/${encodeURIComponent(y)}/retry`,{}),answerQuestions:(y,w)=>_("answer-questions",`/task-creations/${encodeURIComponent(y)}/questions`,{answers:w}),materialize:(y,w)=>_("materialize",`/task-creations/${encodeURIComponent(y)}/materialize`,{approved:w}),chatCreation:(y,w)=>_("task-creator-chat",`/task-creations/${encodeURIComponent(y)}/chat`,{message:w}),renameCreation:(y,w)=>_("rename-creation",`/task-creations/${encodeURIComponent(y)}/name`,{name:w},"PATCH"),cancelCreation:y=>_("cancel-creation",`/task-creations/${encodeURIComponent(y)}/cancel`,{}),runMiner:(y=[],w=[],R)=>_("run-miner","/miner/run",{profileId:n,sourceIds:y,sessionIds:w,config:R}),cancelMinerRun:y=>_("cancel-miner-run",`/miner/runs/${encodeURIComponent(y)}/cancel`,{}),configureMiner:y=>_("configure-miner","/miner/config",{profileId:n,config:y},"PUT"),patchCandidate:(y,w)=>_("candidate",`/candidates/${encodeURIComponent(y)}`,w,"PATCH"),createCandidate:(y,w,R,O)=>_("create-candidate",`/candidates/${encodeURIComponent(y)}/create`,{mode:w,analysisModel:R??null,analysisReasoningEffort:O??null}),auditGraders:y=>_("audit-graders","/audit-graders",{tasksetId:y}),executeTasksetAttempt:(y,w,R)=>_("execute-taskset-attempt",`/tasksets/${encodeURIComponent(y)}/attempts`,{taskId:w,model:R,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:y=>_("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(y.tasksetId)}/synthetic-preference-collection`,y),tasksetOperationalState:y=>t?Z.trainingRequest(t,`/tasksets/${encodeURIComponent(y)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:y=>_("calibrate-judges","/calibrate-judges",{tasksetId:y}),nextPreferenceComparison:(y,w)=>_("next-preference-comparison",`/tasksets/${encodeURIComponent(y)}/preference-comparisons/next`,{reviewerKey:w}),submitPreferenceComparison:y=>_("submit-preference-comparison",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-comparisons/${encodeURIComponent(y.assignmentId)}/submit`,y),submitSyntheticFixturePreference:y=>_("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-comparisons/${encodeURIComponent(y.assignmentId)}/fixture-submit`,{...y,id:crypto.randomUUID()}),listPreferenceDatasets:y=>t?Z.trainingRequest(t,`/tasksets/${encodeURIComponent(y)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:y=>_("materialize-preference-dataset",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-datasets`,{...y,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:y=>_("launch-reward-model-run",`/tasksets/${encodeURIComponent(y.tasksetId)}/reward-model-runs`,{...y,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:y=>_("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(y.tasksetId)}/learned-preference-reward-binding`,y),retryRewardModelQualification:y=>_("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(y.runId)}/retry-qualification`,y),cancelRewardModelRun:y=>_("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(y)}/cancel`,{}),markPreferenceComparisonUnreviewable:y=>_("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-comparisons/${encodeURIComponent(y.assignmentId)}/unreviewable`,y),preferenceCalibrationStatus:(y,w,R)=>{if(!t)return Promise.resolve(null);const O=new URLSearchParams({reviewerKey:w});return R&&O.set("comparisonReleaseId",R),Z.trainingRequest(t,`/tasksets/${encodeURIComponent(y)}/preference-comparisons/calibration/status?${O}`,{},"GET")},startPreferenceCalibrationBatch:y=>_("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-comparisons/calibration/batches`,{...y,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:y=>_("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(y.jobId)}/sync`,y),reviewPreferenceComparisonWithModel:y=>_("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-comparisons/${encodeURIComponent(y.assignmentId)}/model-review`,{...y,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:y=>_("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...y,id:crypto.randomUUID()}),savePreferenceCalibration:y=>_("save-preference-calibration",`/tasksets/${encodeURIComponent(y.tasksetId)}/preference-comparisons/calibration/report`,{...y,id:crypto.randomUUID()}),preferenceArtifactUrl:async y=>{if(!t)return null;const w=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(y)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)throw new Error(await w.text());return URL.createObjectURL(await w.blob())},readiness:y=>_("readiness","/readiness",{tasksetId:y}),previewExpertBootstrap:y=>_("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(y)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(y,w)=>_("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(y)}/expert-bootstrap/approve`,{previewHash:w}),createPlan:y=>_("create-plan","/plans",{...y,tasksetId:y.tasksetId}),buildBundle:y=>_("build-bundle","/bundles",{planId:y}),approveTraining:(y,w)=>_("approve-training","/approvals",{planId:y,bundleId:w}),launch:(y,w)=>_("launch","/launch",{planId:y,approvalId:w}),prepareTraining:y=>_("prepare-training","/prepare",y),prepareModelRun:(y,w)=>_("prepare-model-run",`/model-projects/${encodeURIComponent(y)}/training/prepare`,w),startModelRun:(y,w)=>_("start-model-run",`/model-projects/${encodeURIComponent(y)}/training/start`,w),startPreparedTraining:y=>_("start-prepared-training","/start/prepared",y),startTraining:y=>_("start-training","/start",y),cancelJob:y=>_("cancel-job",`/jobs/${encodeURIComponent(y)}/cancel`,{}),retryModelRunCollection:y=>_("retry-model-run-collection",`/model-runs/${encodeURIComponent(y)}/retry-collection`,{}),cancelModelRun:y=>_("cancel-model-run",`/model-runs/${encodeURIComponent(y)}/cancel`,{}),rejectModel:(y,w)=>_("reject-model",`/models/${encodeURIComponent(y)}/reject`,{reason:w}),bindModel:(y,w,R)=>_("bind-model",`/models/${encodeURIComponent(y)}/bind`,{profileId:n,role:w,roleTargetId:R,promotedBy:n}),rollbackModelBinding:y=>_("rollback-model-binding",`/bindings/${encodeURIComponent(y)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(y,w)=>_("update-model-configuration",`/models/${encodeURIComponent(y)}/configuration`,w,"PATCH",{silent:!0}),setModelPinned:(y,w)=>_("pin-model-version",`/models/${encodeURIComponent(y)}/pin`,{pinned:w},"PATCH"),downloadArtifact:async y=>{if(!t)return!1;f("download-artifact");try{const w=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(y)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)throw new Error(await w.text());const R=w.headers.get("content-disposition")??"",O=/filename="([^"]+)"/.exec(R)?.[1]??"openpond-model-artifact",z=URL.createObjectURL(await w.blob()),$=document.createElement("a");return $.href=z,$.download=O,$.click(),URL.revokeObjectURL(z),!0}catch(w){return b(Nr(w)),!1}finally{f(null)}},downloadModelPackage:async y=>T(`/models/${encodeURIComponent(y)}/download`,`${y}.openpond-lora.tar`),downloadBundle:async y=>T(`/bundles/${encodeURIComponent(y)}/download`,"openpond-model-improvement-bundle.json")}),[t,_,n,C]);async function T(y,w){if(!t)return!1;f("download-bundle");try{const R=await fetch(`${t.serverUrl}/v1/training${y}`,{headers:{Authorization:`Bearer ${t.token}`}});if(!R.ok)throw new Error(await R.text());const O=R.headers.get("content-disposition")??"",z=/filename="([^"]+)"/.exec(O)?.[1]??w,$=URL.createObjectURL(await R.blob()),V=document.createElement("a");return V.href=$,V.download=z,V.click(),URL.revokeObjectURL($),!0}catch(R){return b(Nr(R)),!1}finally{f(null)}}return{connection:t,payload:d,loading:l,busyAction:p,error:S??c.error?.message??null,refresh:C,actions:A}}function Nr(e){return e instanceof Error?e.message:String(e)}function n7({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===Yc?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?lK(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:dK(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function a7(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function Lo(e){return e?.tasks.length?e.tasks[B1(e,e.selectedTaskIndex)]??null:null}function U1(e,t){return{...e,selectedTaskIndex:B1(e,t)}}function oK(e){return U1(e,e.selectedTaskIndex+1)}function iK(e,t,n){if(!e||q1(e,n))return null;const a=Lo(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 q1(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 cK({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function lK(e,t){const n=new Set;return e.tasks.flatMap(a=>{const r=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,s=typeof r=="string"?r.trim():"",i=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!s||!i||n.has(s)?[]:(n.add(s),[{authoredTaskId:a.id,generatedTaskId:s,prompt:i,split:a.split}])})}function dK(e){const t=new Set(e.sourceRefs.filter(Vk).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function B1(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function uK({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:r,connection:s,requestComposerFocus:i,selectedLocalProjectId:c,selectedSessionId:d,selectLocalProject:l,setDraftModel:p,setDraftProvider:f,setError:S,view:b}){const[I,C]=h.useState(null),P=h.useCallback(R=>{R.sourceProjectId?l(R.sourceProjectId):a(null)},[a,l]),_=h.useCallback(R=>{if(!I)return;const O={...U1(I,R),sessionId:I.sessionId?null:I.sessionId},z=Lo(O);C(O),z&&(I.sessionId&&P(O),r.set(z.prompt),i())},[P,r,I,i]),M=h.useCallback(()=>{const R=Lo(I);R&&r.getSnapshot().trim()===R.prompt.trim()&&r.set(""),C(null)},[r,I]),A=h.useCallback(R=>{const O=R.model;cK({model:O,connection:s,loadBootstrap:Z.bootstrap,applyBootstrap:n}).then(()=>{const z={...R,selectedTaskIndex:0,sessionId:null};f(O.providerId),p(O.modelId),C(z.tasks.length?z:null),P(z);const $=Lo(z);$&&r.set($.prompt)}).catch(S)},[n,P,r,s,p,f,S]),T=h.useCallback(R=>{const O=!!(I&&I.model.providerId===t&&I.model.modelId===e);return{active:O,error:O?q1(I,c):null,metadata:O?iK(I,R,c):null}},[e,t,I,c]),y=h.useCallback(R=>{C(O=>O&&{...O,sessionId:R})},[]),w=h.useCallback(()=>{if(!I)return;const R={...oK(I),sessionId:null},O=Lo(R);C(R),O&&(P(R),r.set(O.prompt),i())},[P,r,I,i]);return h.useEffect(()=>{const R=Lo(I);!R||b!=="chat"||d||r.set(O=>O.trim()?O:R.prompt)},[r,I,c,d,b]),h.useEffect(()=>{I&&d&&I.sessionId!==d&&C(null)},[I?.sessionId,d]),{advanceAfterTurn:w,begin:A,bindSession:y,dismiss:M,handoff:I,prepareTurn:T,selectTask:_}}function mK(e){let t=null,n=!1,a=null,r=!1;async function s(){try{do{r=!1;let i;do{const c=t===null,d=t,l=await e.fetchPage({sessionId:e.sessionId,limit:500,...c?{beforeSequence:Number.MAX_SAFE_INTEGER}:{afterSequence:t}});if(n)return;if(!c&&l.hasMore&&l.nextSequence<=d)throw new Error("Chat history did not advance. Reopen the task to retry.");const p=new Set(e.store.getSessionEvents(e.sessionId).map(f=>f.id));l.events.some(f=>!p.has(f.event.id))&&e.store.mergeBootstrap(l.events.map(f=>f.event)),t=l.events.at(-1)?.sequence??d??0,e.onPage(l,c),i=!c&&l.hasMore}while(i&&!n)}while(r&&!n)}catch(i){n||e.onError(i)}}return{refresh(){return n?Promise.resolve():a?(r=!0,a):(a=s().finally(()=>{a=null}),a)},close(){n=!0}}}const Wl=[],pK=500;function fK(e){const{approvals:t,codexHistoryEvents:n,connection:a,runtimeIndexes:r,runtimeEventStore:s,selectedSessionId:i,serverId:c,setCodexHistoryEvents:d,setCodexHistorySessions:l,setError:p}=e,[f,S]=h.useState({}),[b,I]=h.useState({}),C=h.useRef(new Set);h.useEffect(()=>{S({}),I({}),C.current.clear()},[c]);const P=h.useCallback(async()=>{if(!a||!i||C.current.has(i))return!1;const A=b[i];if(A?.hasMore===!1)return!1;if(Gt(i)){const w=Math.max(A?.totalMatchingEvents??0,n.length,m1),R=Math.min(hy,Math.max(z5,w*2));C.current.add(i),I(O=>({...O,[i]:{cursorSequence:null,hasMore:!0,loading:!0,totalMatchingEvents:O[i]?.totalMatchingEvents??n.length}}));try{const O=await p1(a,i,{force:!0,limit:R,tail:!1});return d(O.events),l(z=>Cu(z,O.session)),I(z=>({...z,[i]:{cursorSequence:null,hasMore:O.events.length>=R&&R<hy,loading:!1,totalMatchingEvents:R}})),O.events.length>n.length}catch(O){return p(O instanceof Error?O.message:String(O)),I(z=>({...z,[i]:{cursorSequence:null,hasMore:z[i]?.hasMore??!0,loading:!1,totalMatchingEvents:z[i]?.totalMatchingEvents??n.length}})),!1}finally{C.current.delete(i)}}const T=ai(f[i]??Wl,s.getSessionEvents(i)),y=A?.cursorSequence??hK(T);if(!y)return!1;C.current.add(i),I(w=>({...w,[i]:{cursorSequence:w[i]?.cursorSequence??y,hasMore:w[i]?.hasMore??!0,loading:!0,totalMatchingEvents:w[i]?.totalMatchingEvents??null}}));try{const w=await Z.runtimeEventsPage(a,{sessionId:i,beforeSequence:y,limit:pK}),R=w.events.map(O=>O.event);return S(O=>({...O,[i]:ai(R,O[i]??Wl)})),I(O=>({...O,[i]:{cursorSequence:w.previousSequence,hasMore:w.hasMore,loading:!1,totalMatchingEvents:w.totalMatchingEvents}})),R.length>0}catch(w){return p(w instanceof Error?w.message:String(w)),I(R=>({...R,[i]:{cursorSequence:R[i]?.cursorSequence??y,hasMore:R[i]?.hasMore??!0,loading:!1,totalMatchingEvents:R[i]?.totalMatchingEvents??null}})),!1}finally{C.current.delete(i)}},[b,n.length,a,f,s,i,d,l,p]),_=i?f[i]??Wl:Wl;h.useEffect(()=>{if(!a||!i||Gt(i))return;const A=i,T=mK({sessionId:A,store:s,fetchPage:R=>Z.runtimeEventsPage(a,R),onPage:(R,O)=>{O&&I(z=>{const $=z[A],V=$?.cursorSequence!=null&&$.cursorSequence<R.previousSequence;return{...z,[A]:{cursorSequence:V?$.cursorSequence:R.previousSequence,hasMore:V?$.hasMore:R.hasMore,loading:$?.loading??!1,totalMatchingEvents:R.totalMatchingEvents}}})},onError:R=>p(R instanceof Error?R.message:String(R))}),y=()=>{document.visibilityState==="visible"&&T.refresh()};T.refresh();const w=window.setInterval(y,1e4);return window.addEventListener("focus",y),window.addEventListener("openpond-runtime-connected",y),document.addEventListener("visibilitychange",y),()=>{T.close(),window.clearInterval(w),window.removeEventListener("focus",y),window.removeEventListener("openpond-runtime-connected",y),document.removeEventListener("visibilitychange",y)}},[a,s,i,c,p]);const M=h.useMemo(()=>Gt(i)?Rf(n,[]):!i||_.length===0?r:Rf(ai(_,s.getSessionEvents(i)),t),[t,n,r,_,i]);return{chatHistoryLoadStates:b,loadMoreSelectedChatHistory:P,selectedPagedSessionEvents:_,selectedRuntimeIndexes:M}}function hK(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function gK(e,t){const n=h.useRef(null);return h.useMemo(()=>{const a=WI(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Zo(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Pp(e){return Array.isArray(e)?e.filter(t=>!!Zo(t)):[]}function Ds(e){return typeof e=="string"&&e.trim()?e.trim():null}function Wy(e){return Ds(e)??Zo(e)}function vK(e){if(!e)return[];const t=Zo(e.sandboxActionRegistry),n=Zo(e.sandboxManifest),a=new Map;for(const r of[...Pp(n?.actionCatalog),...Pp(t?.actions),...Pp(n?.actions)]){const s=Ds(r.id)??Ds(r.name);if(!s)continue;const i=a.get(s);a.set(s,{id:s,name:Ds(r.name)??i?.name??s,label:Ds(r.label)??i?.label??bK(s),description:Ds(r.description)??i?.description??null,visibility:Ds(r.visibility)??i?.visibility??"default",inputSchema:Wy(r.inputSchema)??i?.inputSchema??null,outputSchema:Wy(r.outputSchema)??i?.outputSchema??null,implementation:Zo(r.implementation)??i?.implementation??null,mcp:Zo(r.mcp)??i?.mcp??null,invokesModel:typeof r.invokesModel=="boolean"?r.invokesModel:i?.invokesModel})}return Array.from(a.values()).filter(r=>r.visibility!=="internal"&&r.visibility!=="debug")}function bK(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function F1(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:ct("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?Ra(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:ct("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const V1="openpond-agent",K1="openpond-profile-action";function Tu(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Lr(e){return typeof e=="string"&&e.trim()?e.trim():null}function qg(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function yK(e){const t=Tu(e),n=Lr(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:Lr(t?.name)}}function SK(e){const t=Lr(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 xK(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:V1,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 kK(e){const t=Tu(e.implementation);if(t?.type!==V1)return null;const n=Lr(t.agentId),a=Lr(t.teamId),r=Lr(t.projectId),s=yK(t.selectedEntrypoint),i=SK(t.workflowMode);return!n||!a||!r||!s||!i?null:{agentId:n,agentName:Lr(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:r,projectName:Lr(t.projectName),selectedEntrypoint:s,workflowMode:i}}function wK(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{...Tu(e.implementation)??{},type:K1,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function IK(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=>wK(n,{agentName:n.agentId?t.get(n.agentId):null}))}function r7(e){return!!(e&&Bg(e))}function s7(e){return!!(e&&Bg(e)&&e.sourceActionId==="chat")}function Bg(e){const t=Tu(e.implementation);if(t?.type!==K1)return null;const n=Lr(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function _K({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:r}){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:qg({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...r?{sessionId:r}:{}}}}function CK({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:r}){return{teamId:r,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:qg({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function RK({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:qg({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Jo=new Map;function Fg(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function PK(e,t){const n=Fg(e,t);if(!n)return null;const a=Jo.get(n);return a?.updatedAt?a.projects:null}function TK(e,t,n){const a=Fg(e,n);a&&Jo.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function AK(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Fg(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Jo.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const r=e.fetchProjects(t).then(s=>(TK(t,s,e.accountKey),s)).catch(s=>{const i=Jo.get(n);throw i?.promise===r&&Jo.set(n,{projects:i.projects,promise:null,updatedAt:i.updatedAt}),s});return Jo.set(n,{projects:a?.projects??[],promise:r,updatedAt:a?.updatedAt??0}),r}function Tp(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 EK({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:r,localProjects:s,profile:i,selectedCloudProject:c,selectedProject:d,reportError:l}){const[p,f]=h.useState(null),[S,b]=h.useState([]),[I,C]=h.useState([]),P=h.useMemo(()=>{const R=new Set;a&&R.add(a);for(const O of t)R.add(O.teamId);for(const O of s){const z=t.find($=>$.id===O.linkedSandboxProject?.projectId&&$.teamId===O.linkedSandboxProject?.teamId);z?.teamId&&R.add(z.teamId)}return[...R].sort()},[t,a,s]),_=P.join("\0"),M=h.useMemo(()=>F1({cloudProjects:t,selectedCloudProject:c,selectedProject:d}),[t,c,d]);h.useEffect(()=>{if(!n||P.length===0){C([]);return}let R=!1;const O=P.flatMap(z=>L1(z,r)??[]);return C(Tp(O)),Promise.all(P.map(z=>zg({teamId:z,accountKey:r,fetchAgents:async $=>(await Z.listSandboxAgents(n,{teamId:$})).agents}))).then(z=>{R||C(Tp(z.flat()))}).catch(()=>{R||C(Tp(O))}),()=>{R=!0}},[r,n,_]),h.useEffect(()=>{if(!n||!M){f(null);return}const R=PK(M.teamId,r);R&&f(R.find(z=>z.id===M.id)??null);let O=!1;return AK({teamId:M.teamId,accountKey:r,fetchProjects:async z=>(await Z.listSandboxProjects(n,{teamId:z})).projects}).then(z=>{O||f(z.find($=>$.id===M.id)??null)}).catch(()=>{O||f(null)}),()=>{O=!0}},[r,n,M?.id,M?.teamId]),h.useEffect(()=>{if(!n||!d){b([]);return}let R=!1;return Z.localProjectActions(n,d.id).then(O=>{R||b(O.actions)}).catch(O=>{R||(b([]),l?.(`Could not load Project Actions for ${d.name}: ${O instanceof Error?O.message:String(O)}`))}),()=>{R=!0}},[n,l,d?.id,d?.name,d?.updatedAt]);const A=h.useMemo(()=>{const R=new Map;for(const O of vK(p))R.set(O.id,O);for(const O of S)R.set(O.id,O);return[...R.values()]},[S,p]),T=h.useMemo(()=>IK(i),[i]),y=h.useMemo(()=>[...I.map(R=>xK(R,e.get(R.projectId)?.name??null)),...T,...A],[e,T,A,I]);return{openPondActionCatalog:h.useMemo(()=>[...T,...A],[T,A]),selectedActionCatalog:y,selectedProjectActionCatalog:A}}function jK({selectedProjectId:e}){const[t,n]=h.useState(()=>new Set),a=h.useCallback(s=>{n(i=>{if(i.has(s))return i;const c=new Set(i);return c.add(s),c})},[]),r=h.useCallback(s=>{n(i=>{const c=new Set(i);return c.has(s)?c.delete(s):c.add(s),c})},[]);return h.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:r,setExpandedProjectIds:n}}function MK(){const e=new Map;function t(r,s){const i=e.get(r);if(i)return i.consumers+=1,n(r,i,!0);const c=new AbortController,d={controller:c,consumers:1,settled:!1,promise:Promise.resolve().then(()=>s(c.signal)).finally(()=>{d.settled=!0,e.get(r)===d&&e.delete(r)})};return e.set(r,d),n(r,d,!1)}function n(r,s,i){let c=!1;return{key:r,promise:s.promise,shared:i,release:()=>{c||(c=!0,s.consumers=Math.max(0,s.consumers-1),s.consumers===0&&!s.settled&&s.controller.abort())}}}function a(){for(const r of e.values())r.consumers=0,r.settled||r.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function Ap(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function OK(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function Ep(e){return e instanceof Error&&e.name==="AbortError"}function $K({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:r,setError:s}){const[i,c]=h.useState(null),[d,l]=h.useState({}),[p,f]=h.useState(null),[S,b]=h.useState(!1),[I,C]=h.useState(!1),P=h.useRef(new Set),_=h.useRef(new Set),M=h.useRef(MK()),A=t?d[t]??(i?.appId===t?i:null):null,T=p?.appId===t?p:null,y=n==="chat"||n==="labs",w=h.useCallback(z=>{P.current.add(z.appId),c(z),l($=>({...$,[z.appId]:z}))},[]),R=h.useCallback(async(z,$=!1)=>{if(!e||!z)return c(null),null;b(!0);const V=M.current.request(Ap(e,z,$),Y=>Z.workspaceStatus(e,z,$,{signal:Y}));try{const Y=await V.promise;return w(Y),$&&Y.error?s(`Workspace sync failed: ${Y.error}`):$&&s(null),Y}catch(Y){return Ep(Y)||(c(null),s(Y instanceof Error?Y.message:String(Y))),null}finally{V.release(),b(!1)}},[e,w,s]),O=h.useCallback(async(z=t,$={})=>{if(!e||!z)return f(null),null;$.silent||C(!0);const V=M.current.request(OK(e,z),Y=>Z.workspaceDiff(e,z,{signal:Y}));try{const Y=await V.promise;return f(Y),Y}catch(Y){return Ep(Y)||(f(null),s(Y instanceof Error?Y.message:String(Y))),null}finally{V.release(),$.silent||C(!1)}},[t,e,s]);return h.useEffect(()=>{if(!e||!t||!y){c(null),f(null),b(!1);return}let z=!1;const $=M.current.request(Ap(e,t,!1),V=>Z.workspaceStatus(e,t,!1,{signal:V}));return b(!0),$.promise.then(V=>{z||(w(V),V.initialized||f(Y=>Y?.appId===V.appId?null:Y))}).catch(V=>{Ep(V)||z||(c(null),s(V instanceof Error?V.message:String(V)))}).finally(()=>{$.release(),z||b(!1)}),()=>{z=!0,$.release()}},[t,e,w,s,y]),h.useEffect(()=>{if(!e||!t||!y){f(null);return}if(!A?.initialized){A&&!A.initialized&&f(z=>z?.appId===t?null:z);return}a&&O(t)},[t,e,O,a,y,A?.dirty,A?.initialized]),h.useEffect(()=>{if(!e||r.length===0)return;const z=r.filter(Y=>!P.current.has(Y)&&!_.current.has(Y));if(z.length===0)return;z.forEach(Y=>_.current.add(Y));let $=!1;const V=z.map(Y=>({appId:Y,request:M.current.request(Ap(e,Y,!1),re=>Z.workspaceStatus(e,Y,!1,{signal:re}))}));return Promise.all(V.map(({appId:Y,request:re})=>re.promise.then(ee=>({appId:Y,state:ee})).catch(()=>({appId:Y,state:null})).finally(()=>{re.release(),_.current.delete(Y)}))).then(Y=>{if(!$)for(const re of Y)re.state&&w(re.state)}),()=>{$=!0,V.forEach(({appId:Y,request:re})=>{re.release(),_.current.delete(Y)})}},[e,w,r]),h.useEffect(()=>()=>M.current.cancelAll(),[]),{workspaceState:i,workspaceStates:d,workspaceDiff:p,workspaceBusy:S,diffBusy:I,visibleWorkspaceState:A,visibleWorkspaceDiff:T,rememberWorkspaceState:w,refreshWorkspace:R,refreshWorkspaceDiff:O,setWorkspaceBusy:b}}const NK=1,DK=15e3,LK=15e3,W1=5*6e4,zK=5e3,HK=1e4;function G1(e,t=(a,r)=>new WebSocket(a,r),n={}){const a=new UK(e,t,n.reconnectDelayMs??qK);return a.open(),{close:()=>a.close()}}class UK{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=W1;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===NK)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-${BK(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."))},DK))},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 s=JSON.parse(n.data);if(!s||typeof s!="object"||Array.isArray(s))return;a=s}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const r=typeof a.type=="string"?a.type:"";if(r==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=VK(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(r==="ka"){this.lastKeepAliveAt=Date.now();return}if(r==="subscribe_success"){const s=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(s))return;this.acknowledgedSubscriptions.add(s),this.markReadyWhenSubscribed();return}if(r==="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(r==="connection_error"||r==="subscribe_error"){const s=KK(a);if(this.reportError(s),r==="connection_error")this.failConnection(s,!1);else{const i=typeof a.id=="string"?a.id:"";this.subscriptionChannels.delete(i),this.acknowledgedSubscriptions.delete(i),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 r=FK();this.subscriptionChannels.set(r,a),t.send(JSON.stringify({type:"subscribe",id:r,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},LK)}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."))},zK)}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 qK(e){const t=Math.min(HK,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function BK(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 FK(){return globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`}function VK(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:W1}function KK(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,r=typeof a.errorType=="string"?a.errorType:"RealtimeError",s=typeof a.message=="string"?a.message:"Request failed";return new Error(`${r}: ${s}`)}return new Error("Team chat realtime request failed.")}function WK(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(r=>`/team-chat/threads/${r}`)];return G1({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:r=>{const s=sx.safeParse(r);s.success&&e.onEvent(s.data)},onReady:e.onReady,onError:e.onError},t,n)}function GK(e){return e.refs.find(t=>t.refType==="message_reply")??null}function ZK(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function o7(e,t){const n=GK(e);if(!n)return null;const a=t.get(n.refId);return a?ZK(a):QK(n)}function JK(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 i7(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 c7(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function QK(e){const t=e.preview;return{id:e.refId,authorType:YK(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 YK(e){return e==="agent"||e==="system"?e:"user"}function Gy(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function XK(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:rl([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function jp(e,t){const n=Array.from(t.values()).filter(r=>r.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const r of n)a=gi(a,r,"message.created",!0,r.authorUserId);return{...e,thread:a,messages:rl([...e.messages,...n])}}function e9(e,t){const n=new Set(e.map(r=>r.lastMessage?.clientRequestId).filter(r=>!!r)),a=new Map;for(const r of t.values()){if(r.clientRequestId&&n.has(r.clientRequestId))continue;const s=a.get(r.threadId)??[];s.push(r),a.set(r.threadId,s)}return e.map(r=>{let s=r;for(const i of a.get(r.id)??[])s=gi(s,i,"message.created",!0,i.authorUserId);return s}).sort((r,s)=>s.lastMessageAt.localeCompare(r.lastMessageAt))}function Mp(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Op(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function Zy(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function rl(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,r)=>a.sequence!==r.sequence?a.sequence-r.sequence:a.createdAt.localeCompare(r.createdAt))}function Z1(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:bh.safeParse(e.payload.message).data??null}function J1(e,t,n){const a=Z1(t);if(a){const r=e.selectedThreadId===a.threadId,s=e.detail?.thread.id===a.threadId?{...e.detail,thread:gi(e.detail.thread,a,t.type,r,n),messages:rl([...e.detail.messages,a])}:e.detail,c=e.threads.some(d=>d.id===a.threadId)?e.threads.map(d=>d.id===a.threadId?gi(d,a,t.type,r,n):d).sort((d,l)=>l.lastMessageAt.localeCompare(d.lastMessageAt)):e.threads;return{...e,detail:s,threads:c,error:null}}if(t.type==="read.updated"){const r=typeof t.payload.userId=="string"?t.payload.userId:null,s=Number(t.payload.sequence);if(!r||!Number.isSafeInteger(s)||s<0)return e;const i=c=>({...c,participants:c.participants.map(d=>d.userId===r?{...d,lastReadSequence:Math.max(d.lastReadSequence,s)}:d)});return{...e,threads:e.threads.map(c=>c.id===t.threadId?i(c):c),detail:e.detail?.thread.id===t.threadId?{...e.detail,thread:i(e.detail.thread)}:e.detail}}return e}function gi(e,t,n,a,r){const s=n==="message.created",i=t.sequence>=e.lastMessageSequence;return{...e,lastMessageId:i?t.id:e.lastMessageId,lastMessageSequence:Math.max(e.lastMessageSequence,t.sequence),lastMessageAt:i?t.createdAt:e.lastMessageAt,updatedAt:i?t.createdAt:e.updatedAt,lastMessage:i?t:e.lastMessage,unreadCount:a||t.authorUserId===r?0:s?e.unreadCount+1:e.unreadCount}}function t9(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:JK(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 n9(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:gi(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:rl([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?gi(a,t,"message.created",!0,t.authorUserId):a).sort((a,r)=>r.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function Jy(e,t,n){return J1(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function a9(e,t){return Df(e,t,"failed")}function Df(e,t,n){const a=r=>r.clientRequestId===t&&r.id.startsWith("pending:")?{...r,metadata:{...r.metadata,deliveryStatus:n}}:r;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(r=>({...r,lastMessage:r.lastMessage?a(r.lastMessage):null}))}}function Qy(e,t,n){const a=r=>r.clientRequestId===t&&r.id.startsWith("pending:")?{...r,metadata:{...r.metadata,uploadProgress:n}}:r;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(r=>({...r,lastMessage:r.lastMessage?a(r.lastMessage):null}))}}function r9(e,t){const n=e.detail?.messages.filter(s=>s.id!==t)??[],a=n.at(-1)??null,r=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?Yy(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:r,threads:e.threads.map(s=>s.lastMessageId===t?Yy(s,a):s)}}function s9(e){if(e.length>Hs.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!o9(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>Hs.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function Yy(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 o9(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const i9={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 c9(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,r]of Object.entries(i9))if(n.includes(a))return r;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":A1(t)}const Q1="openpond.team-chat.notification-mode";function Y1(){try{return typeof window>"u"?null:no}catch{return null}}function Xy(e=Y1()){const t=e?.getItem(Q1);return t==="direct_mentions"||t==="none"?t:"all"}function l9(e,t=Y1()){try{t?.setItem(Q1,e)}catch{}}function d9(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 u9(e){const t=e.message.authorUserId?e.members.find(i=>i.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}`,s=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:s.length>160?`${s.slice(0,157)}…`:s}}const e0={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function Gl(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function Zl(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function m9(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function p9(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function t0(e,t=Z.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function f9(e){const[t,n]=h.useState(e0),a=h.useRef(t);a.current=t;const[r,s]=h.useState(Xy);pi(()=>s(Xy()));const[i,c]=h.useState(null),d=h.useRef(null),l=h.useRef(null),p=h.useRef(0),f=h.useRef(new Map),S=h.useRef(new Map),b=h.useRef(0),I=h.useRef(null),C=h.useRef(0),P=h.useRef(new Set),_=h.useRef(0),M=h.useRef(!1),A=h.useRef(new Map),T=h.useRef(new Map),[y,w]=h.useState(null),[R,O]=h.useState(null),z=h.useCallback(N=>{s(N),l9(N)},[]),$=h.useCallback(N=>{c(q=>q?.eventId===N?null:q)},[]),V=h.useCallback(async()=>{if(!e.connection||!e.teamId)return[];const N=await Z.teamChatThreads(e.connection,e.teamId),q=e9(N.threads,A.current);return n(X=>({...X,threads:q})),q},[e.connection,e.teamId]),Y=h.useCallback(async()=>{if(!e.connection||!e.teamId)return{members:[],agents:[]};const[N,q]=await Promise.all([Z.teamChatMembers(e.connection,e.teamId),Z.teamChatAgents(e.connection,e.teamId)]);return n(X=>({...X,members:N.members,agents:q.agents})),{members:N.members,agents:q.agents}},[e.connection,e.teamId]),re=h.useCallback(async N=>{const q=N??d.current;if(!e.connection||!e.teamId||!q)return null;const X=(S.current.get(q)??0)+1;S.current.set(q,X);const U=await Z.teamChatThread(e.connection,e.teamId,q);Mp(U.messages,A.current,T.current);const ae=jp(U,A.current);return S.current.get(q)!==X||(n(de=>de.selectedThreadId===q?{...de,threads:Gl(de.threads,q),detail:Zl(XK(de.detail,ae))}:de),d.current===q&&ae.thread.lastMessageSequence>0&&await Z.markTeamChatRead(e.connection,q,e.teamId,ae.thread.lastMessageSequence).catch(()=>{})),ae},[e.connection,e.teamId]),ee=h.useCallback(async N=>{const q=N??l.current;if(!e.connection||!e.teamId||!q)return null;const X=(f.current.get(q)??0)+1;f.current.set(q,X);const U=await Z.teamChatAiThread(e.connection,e.teamId,q);return f.current.get(q)===X&&l.current===q&&n(ae=>Gy(ae,U,l.current)),U},[e.connection,e.teamId]),H=h.useCallback(async N=>{const q=N??I.current;if(!e.connection||!e.teamId||!q)return null;const X=await Z.teamChatAgentConversation(e.connection,e.teamId,q);return n(U=>U.agentConversation?.run.id===q?{...U,agentConversation:X}:U),X},[e.connection,e.teamId]);h.useEffect(()=>{d.current=t.selectedThreadId},[t.selectedThreadId]),h.useEffect(()=>{I.current=t.agentConversation?.run.id??null},[t.agentConversation?.run.id]),h.useEffect(()=>{const N=t.agentConversation?.run.status;if(!N||!["pending","queued","running"].includes(N))return;const q=window.setInterval(()=>{H().catch(X=>{n(U=>({...U,error:fn(X)}))})},2500);return()=>window.clearInterval(q)},[H,t.agentConversation?.run.status]),h.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(e0),w(null),O(null),T.current.clear(),A.current.clear(),S.current.clear(),f.current.clear(),b.current+=1,c(null),P.current.clear(),_.current=0,C.current=0;return}let N=!1;return l.current=null,p.current+=1,b.current+=1,w(null),O(null),T.current.clear(),A.current.clear(),P.current.clear(),_.current=0,n(q=>({...q,aiThread:null,agentConversation:null,loading:!0,error:null})),(async()=>{try{const q=await Z.teamChatEvents(e.connection,e.teamId);if(N)return;C.current=q.cursor;const X=Z.teamChatMembers(e.connection,e.teamId),U=Z.teamChatAgents(e.connection,e.teamId),ae=await Z.teamChatGeneral(e.connection,e.teamId),[de,ye,Oe]=await Promise.all([X,U,Z.teamChatThreads(e.connection,e.teamId)]);if(N)return;const $e=d.current&&Oe.threads.some(Se=>Se.id===d.current)?d.current:ae.thread.id,Ge=$e===ae.thread.id?ae:await Z.teamChatThread(e.connection,e.teamId,$e);if(N)return;const yt=Zl(Ge);n(Se=>({...Se,members:de.members,agents:ye.agents,threads:Gl(Oe.threads,$e),selectedThreadId:$e,detail:yt,loading:!1,error:null})),t0({connection:e.connection,teamId:e.teamId,threadId:$e,lastMessageSequence:yt?.thread.lastMessageSequence??0}),O(e.teamId)}catch(q){if(N)return;n(X=>({...X,loading:!1,error:fn(q)}))}})(),()=>{N=!0}},[e.connection,e.currentUserId,e.refreshToken,e.teamId]);const F=h.useCallback(N=>{if(P.current.has(N.id))return;if(P.current.add(N.id),P.current.size>2e3){const X=P.current.values().next().value;typeof X=="number"&&P.current.delete(X)}const q=Z1(N);if(q&&N.type==="message.created"){const X=a.current,U=X.threads.find(de=>de.id===q.threadId)??(X.detail?.thread.id===q.threadId?X.detail.thread:null),ae=de=>{N.id<=_.current||d9({mode:r,currentUserId:e.currentUserId,message:q,thread:de})&&(_.current=N.id,c(u9({eventId:N.id,message:q,thread:de,members:X.members})))};U?ae(U):V().then(de=>{const ye=de.find(Oe=>Oe.id===q.threadId);ye&&ae(ye)}).catch(()=>{})}q?.clientRequestId&&!q.id.startsWith("pending:")&&(A.current.delete(q.clientRequestId),T.current.delete(q.clientRequestId)),n(X=>J1(X,N,e.currentUserId)),N.type==="thread.created"&&V().catch(X=>{n(U=>({...U,error:fn(X)}))}),(N.type==="ai_thread.created"||N.type==="ai_turn.updated")&&(re(N.threadId).catch(X=>{n(U=>({...U,error:fn(X)}))}),N.conversationId===l.current&&ee(N.conversationId).catch(X=>{n(U=>({...U,error:fn(X)}))})),q&&N.type==="message.created"&&d.current===q.threadId&&q.authorUserId!==e.currentUserId&&e.connection&&e.teamId&&Z.markTeamChatRead(e.connection,q.threadId,e.teamId,q.sequence).catch(()=>{})},[e.connection,e.currentUserId,e.teamId,r,ee,re,V]),J=h.useCallback(async()=>{if(!(!e.connection||!e.teamId||M.current)){M.current=!0;try{let N=!0;for(;N;){const q=await Z.teamChatEvents(e.connection,e.teamId,{after:C.current,limit:250});for(const X of q.events)F(X);C.current=q.cursor,N=q.hasMore}}finally{M.current=!1}}},[F,e.connection,e.teamId]);h.useEffect(()=>{if(!e.connection||!e.teamId||R!==e.teamId)return;let N=!1,q=null;const X=async()=>{try{const U=await Z.teamChatRealtimeSession(e.connection,e.teamId);if(N||(await J(),N))return;w(U);const ae=Math.max(3e4,new Date(U.expiresAt).getTime()-Date.now()-3e4);q=window.setTimeout(()=>{X()},ae)}catch{N||(J().catch(()=>{}),q=window.setTimeout(()=>{X()},1e4))}};return X(),()=>{N=!0,q!==null&&window.clearTimeout(q),w(null)}},[J,e.connection,e.teamId,R]);const K=t.threads.map(N=>N.id).sort().join(",");h.useEffect(()=>{if(!y)return;const N=WK({session:y,threadIds:K?K.split(","):[],onEvent:F,onReady:()=>{J().catch(q=>{n(X=>({...X,error:fn(q)}))})},onError:()=>{J().catch(()=>{})}});return()=>{N.close()}},[F,J,y,K]),h.useEffect(()=>{if(!e.connection||!e.teamId||R!==e.teamId)return;const N=window.setInterval(()=>{J().catch(()=>{})},15e3);return()=>window.clearInterval(N)},[J,e.connection,e.teamId,R]);const B=h.useCallback(async N=>{if(!e.connection||!e.teamId)return;const q=b.current+1;b.current=q;const X=d.current!==N;d.current=N,X&&(p.current+=1,l.current=null),n(U=>({...U,threads:Gl(U.threads,N),selectedThreadId:N,detail:U.detail?.thread.id===N?Zl(U.detail):null,aiThread:X?null:U.aiThread,agentConversation:X?null:U.agentConversation,loading:!0,error:null}));try{const U=await Z.teamChatThread(e.connection,e.teamId,N);if(b.current!==q||d.current!==N)return;Mp(U.messages,A.current,T.current);const ae=jp(U,A.current);n(de=>({...de,threads:Gl(de.threads,N),detail:Zl(ae),loading:!1})),await Z.markTeamChatRead(e.connection,N,e.teamId,ae.thread.lastMessageSequence).catch(()=>{})}catch(U){if(b.current!==q)return;n(ae=>({...ae,loading:!1,error:fn(U)}))}},[e.connection,e.teamId]),ne=h.useCallback(async N=>{if(!e.connection||!e.teamId)return null;const q=b.current+1;b.current=q,n(X=>({...X,busy:!0,error:null}));try{const X=await Z.teamChatDm(e.connection,e.teamId,N);if(b.current!==q)return null;Mp(X.messages,A.current,T.current);const U=jp(X,A.current),ae=d.current!==U.thread.id;return d.current=U.thread.id,ae&&(p.current+=1,l.current=null),n(de=>({...de,selectedThreadId:U.thread.id,detail:U,aiThread:ae?null:de.aiThread,agentConversation:ae?null:de.agentConversation,busy:!1})),await t0({connection:e.connection,teamId:e.teamId,threadId:U.thread.id,lastMessageSequence:U.thread.lastMessageSequence}),await V(),U}catch(X){return b.current!==q||n(U=>({...U,busy:!1,error:fn(X)})),null}},[e.connection,e.teamId,V]),G=h.useCallback(async()=>{const N=t.detail,q=N?.messages[0]?.sequence;if(!e.connection||!e.teamId||!N||!N.hasMoreBefore||q==null)return!1;n(X=>({...X,loading:!0,error:null}));try{const X=await Z.teamChatThread(e.connection,e.teamId,N.thread.id,{beforeSequence:q,limit:50});return n(U=>{if(U.detail?.thread.id!==N.thread.id)return U;const ae=[...X.messages,...U.detail.messages];return{...U,loading:!1,detail:{...U.detail,messages:rl(ae),hasMoreBefore:X.hasMoreBefore}}}),!0}catch(X){return n(U=>({...U,loading:!1,error:fn(X)})),!1}},[e.connection,e.teamId,t.detail]),te=h.useCallback(async N=>{const q=d.current,X=s9(N.attachments??[]);if(!X)return n(de=>({...de,error:"Team chat supports up to 10 PNG, JPEG, WebP, or GIF images per message."})),!1;if(!e.connection||!e.teamId||!q||!N.body.trim()&&X.length===0)return!1;if(N.replyToMessage&&(N.replyToMessage.threadId!==q||N.replyToMessage.teamId!==e.teamId||N.replyToMessage.id.startsWith("pending:")||N.replyToMessage.deletedAt))return n(de=>({...de,error:"That message is no longer available to reply to."})),!1;if(N.useModel){if(X.length>0)return n(ye=>({...ye,error:"Images can be sent to the team thread with Use model turned off."})),!1;const de=p.current;n(ye=>({...ye,busy:!0,error:null}));try{const ye=await Z.createTeamChatAiThread(e.connection,q,{teamId:e.teamId,body:N.body.trim(),clientRequestId:crypto.randomUUID(),providerId:N.providerId,modelId:N.modelId}),Oe=p.current===de&&d.current===q;return Oe&&(p.current+=1,l.current=ye.conversationId),n($e=>({...$e,aiThread:Oe?ye:$e.aiThread})),ye.activeTurn&&await Z.executeTeamChatAiTurn(e.connection,ye.activeTurn.id,e.teamId),await Promise.all([re(q),V()]),n($e=>({...$e,busy:!1})),!0}catch(ye){return n(Oe=>({...Oe,busy:!1,error:fn(ye)})),!1}}const U=crypto.randomUUID();if(N.selectedActionKey){if(X.length>0)return n(de=>({...de,error:"Agent invocations do not support image attachments yet."})),!1;n(de=>({...de,busy:!0,error:null}));try{return await Z.createTeamChatAgentRun(e.connection,q,p9({teamId:e.teamId,body:N.body,clientRequestId:U,selectedActionKey:N.selectedActionKey,approvalId:N.approvalId})),await Promise.all([re(q),V()]),n(de=>({...de,busy:!1})),!0}catch(de){return n(ye=>({...ye,busy:!1,error:fn(de)})),!1}}T.current.set(U,{inputs:X,uploaded:null});const ae=t9({clientRequestId:U,threadId:q,teamId:e.teamId,userId:e.currentUserId,body:N.body.trim(),mentionUserIds:N.mentionUserIds??[],attachments:X,replyToMessage:N.replyToMessage,sequence:(t.detail?.thread.lastMessageSequence??0)+1});A.current.set(U,ae),n(de=>n9(de,ae));try{const de=[];for(const[$e,Ge]of X.entries())de.push(await Z.uploadTeamChatAttachment(e.connection,q,{teamId:e.teamId,attachment:Ge})),Zy(A.current,U,`${$e+1} of ${X.length}`),n(yt=>Qy(yt,U,`${$e+1} of ${X.length}`));const ye=T.current.get(U);ye&&(ye.uploaded=de);const Oe=await Z.sendTeamChatMessage(e.connection,q,{teamId:e.teamId,body:N.body.trim(),clientRequestId:U,mentionUserIds:N.mentionUserIds,attachmentIds:de.map($e=>$e.id),replyToMessageId:N.replyToMessage?.id??null});return T.current.delete(U),A.current.delete(U),n($e=>Jy($e,Oe,e.currentUserId)),!0}catch(de){return Op(A.current,U,"failed"),n(ye=>({...a9(ye,U),error:fn(de)})),!1}},[e.connection,e.currentUserId,e.teamId,re,V,t.detail?.thread.lastMessageSequence]),oe=h.useCallback(async N=>{if(!(!e.connection||!e.teamId)){p.current+=1,l.current=N,n(q=>({...q,aiThread:q.aiThread?.conversationId===N?q.aiThread:null,busy:!0,error:null}));try{const q=await Z.teamChatAiThread(e.connection,e.teamId,N);if(l.current!==N)return;n(X=>({...X,aiThread:q,busy:!1}))}catch(q){if(l.current!==N)return;n(X=>({...X,busy:!1,error:fn(q)}))}}},[e.connection,e.teamId]),be=h.useCallback(async N=>{if(!(!e.connection||!e.teamId)){I.current=N,n(q=>({...q,busy:!0,error:null}));try{const q=await Z.teamChatAgentConversation(e.connection,e.teamId,N);n(X=>({...X,agentConversation:q,busy:!1}))}catch(q){n(X=>({...X,busy:!1,error:fn(q)}))}}},[e.connection,e.teamId]),me=h.useCallback(()=>{I.current=null,n(N=>({...N,agentConversation:null}))},[]),Re=h.useCallback(async N=>{const q=d.current,X=t.agentConversation;if(!e.connection||!e.teamId||!q||!X||!N.body.trim())return!1;n(U=>({...U,busy:!0,error:null}));try{const U=await Z.createTeamChatAgentRun(e.connection,q,m9({teamId:e.teamId,body:N.body,clientRequestId:N.clientRequestId,conversation:X}));I.current=U.run.id;const[ae]=await Promise.all([Z.teamChatAgentConversation(e.connection,e.teamId,U.run.id),re(q),V()]);return n(de=>({...de,agentConversation:ae,busy:!1})),!0}catch(U){return n(ae=>({...ae,busy:!1,error:fn(U)})),!1}},[e.connection,e.teamId,re,V,t.agentConversation]),Q=h.useCallback(()=>{p.current+=1,l.current=null,n(N=>({...N,aiThread:null}))},[]),xe=h.useCallback(async N=>{const q=l.current;if(!e.connection||!e.teamId||!q||!N.body.trim())return!1;n(X=>({...X,busy:!0,error:null}));try{const X=await Z.sendTeamChatAiTurn(e.connection,q,{teamId:e.teamId,body:N.body.trim(),clientRequestId:crypto.randomUUID(),providerId:N.providerId,modelId:N.modelId});return n(U=>({...Gy(U,X,l.current),busy:!1})),X.activeTurn&&await Z.executeTeamChatAiTurn(e.connection,X.activeTurn.id,e.teamId),!0}catch(X){return n(U=>({...U,busy:!1,error:fn(X)})),!1}},[e.connection,e.teamId]),je=h.useCallback(async()=>{const N=t.aiThread?.activeTurn?.id;return!e.connection||!e.teamId||!N?!1:(await Z.cancelTeamChatAiTurnExecution(e.connection,N,e.teamId)).cancelled},[e.connection,e.teamId,t.aiThread?.activeTurn?.id]),De=h.useCallback(async(N,q)=>{if(!e.connection||!e.teamId)return!1;try{return await Z.editTeamChatMessage(e.connection,N.threadId,N.id,{teamId:e.teamId,body:q}),await re(N.threadId),!0}catch(X){return n(U=>({...U,error:fn(X)})),!1}},[e.connection,e.teamId,re]),He=h.useCallback(async N=>{if(!e.connection||!e.teamId)return!1;try{return await Z.deleteTeamChatMessage(e.connection,N.threadId,N.id,e.teamId),await re(N.threadId),!0}catch(q){return n(X=>({...X,error:fn(q)})),!1}},[e.connection,e.teamId,re]),Ie=h.useCallback(async N=>{if(!e.connection||!e.teamId||!N.clientRequestId||!N.id.startsWith("pending:"))return!1;const q=Array.isArray(N.metadata.mentionUserIds)?N.metadata.mentionUserIds.filter(ae=>typeof ae=="string"):[],X=T.current.get(N.clientRequestId),U=N.refs.find(ae=>ae.refType==="message_reply");Op(A.current,N.clientRequestId,"sending"),n(ae=>Df(ae,N.clientRequestId,"sending"));try{let ae=X?.uploaded??[];if(X&&!X.uploaded){ae=[];for(const[ye,Oe]of X.inputs.entries())ae.push(await Z.uploadTeamChatAttachment(e.connection,N.threadId,{teamId:e.teamId,attachment:Oe})),Zy(A.current,N.clientRequestId,`${ye+1} of ${X.inputs.length}`),n($e=>Qy($e,N.clientRequestId,`${ye+1} of ${X.inputs.length}`));X.uploaded=ae}const de=await Z.sendTeamChatMessage(e.connection,N.threadId,{teamId:e.teamId,body:N.body,clientRequestId:N.clientRequestId,mentionUserIds:q,attachmentIds:ae.map(ye=>ye.id),replyToMessageId:U?.refId??null});return T.current.delete(N.clientRequestId),A.current.delete(N.clientRequestId),n(ye=>Jy(ye,de,e.currentUserId)),!0}catch(ae){return Op(A.current,N.clientRequestId,"failed"),n(de=>({...Df(de,N.clientRequestId,"failed"),error:fn(ae)})),!1}},[e.connection,e.currentUserId,e.teamId]),Me=h.useCallback(N=>{N.id.startsWith("pending:")&&(N.clientRequestId&&T.current.delete(N.clientRequestId),N.clientRequestId&&A.current.delete(N.clientRequestId),n(q=>r9(q,N.id)))},[]),Te=h.useCallback(async(N,q)=>{if(!e.connection||!e.teamId)return!1;try{const X=await Z.setTeamChatThreadMuted(e.connection,N,e.teamId,q),U=ae=>ae.id===X.threadId?{...ae,mutedAt:X.mutedAt}:ae;return n(ae=>({...ae,threads:ae.threads.map(U),detail:ae.detail?.thread.id===X.threadId?{...ae.detail,thread:U(ae.detail.thread)}:ae.detail,error:null})),!0}catch(X){return n(U=>({...U,error:fn(X)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:r,incomingNotification:i,setNotificationMode:z,dismissIncomingNotification:$,setThreadMuted:Te,selectThread:B,openDm:ne,loadMoreMessages:G,sendMessage:te,openAiThread:oe,openAgentConversation:be,closeAgentConversation:me,sendAgentTurn:Re,closeAiThread:Q,sendAiTurn:xe,stopAiTurn:je,editMessage:De,deleteMessage:He,retryMessage:Ie,dismissFailedMessage:Me,refreshDirectory:Y,refresh:async()=>{await Promise.all([Y(),V(),re(),ee(),H()])}}}function fn(e){return c9(e)}const X1="local-profile-agent";function l7(e){const t=e.profile;if(!t||t.mode!=="local")return e.hostedActions;const n=new Set(e.hostedActions.flatMap(i=>{const c=i.implementation;return c?.type!=="openpond-agent"||c.profileName!==t.activeProfile?[]:[Ls(c.agentName),Ls(i.name),Ls(i.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,r=new Set(e.hostedActions.map(i=>i.implementation?.agentId).filter(i=>typeof i=="string")),s=t.agents.flatMap(i=>i.enabled?a?.agentId===i.id&&!!(a.runtimeAgentId&&r.has(a.runtimeAgentId))||n.has(Ls(i.name))||n.has(Ls(i.id))?[]:[v9(t,i)]:[]);return[...e.hostedActions,...s]}function d7(e){return e?.implementation?.type===X1}function u7(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function h9(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 g9(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",r=Ls(t.agentName);return e.find(s=>{const i=s.implementation;return i?.type!=="openpond-agent"?!1:n&&typeof i.agentId=="string"&&i.agentId===n?!0:!!(a&&i.profileName===a&&r&&[i.agentName,s.name,s.label].some(c=>Ls(c)===r))})??null}function v9(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:b9(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:X1,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function b9(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 Ls(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const n0=5;function y9(e){return h.useCallback(async t=>{if(!e.connection||!e.teamId)throw new Error("Connect OpenPond to a Team before publishing an agent.");const n=await Z.profileCheck(e.connection,{kind:"all"}),a=h9(n,t);if(a)throw new Error(a);const r=n?.agents.find(l=>l.id===t);if(!r)throw new Error(`Profile agent not found: ${t}`);const i=(await Z.profilePush(e.connection,{teamId:e.teamId,ensureHosted:!0,hostedSourceAgentId:t,message:null})).localProfile?.hosted?.hostedSourceMaterialization,c=i?.agentId===t?i.runtimeAgentId:null;e.applyBootstrapPayload(await Z.bootstrap(e.connection));let d=null;for(let l=0;l<n0;l+=1){const p=await e.refreshDirectory();if(d=g9(p.agents,{runtimeAgentId:c,profileName:n.activeProfile,agentName:r.name}),d)break;l<n0-1&&await S9(200*(l+1))}if(!d)throw new Error(`${r.name} was published, but the Team agent directory has not refreshed yet. Retry the mention in a moment.`);return d},[e.applyBootstrapPayload,e.connection,e.refreshDirectory,e.teamId])}function S9(e){return new Promise(t=>{setTimeout(t,e)})}function x9(e){h.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:r}=e.notification;e.showToast(`${a}: ${r}`,"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 k9(e){const{connection:t,refreshToken:n=null}=e,[a,r]=h.useState([]),[s,i]=h.useState(null),[c,d]=h.useState(null),[l,p]=h.useState(null),[f,S]=h.useState(!1),[b,I]=h.useState(!1),[C,P]=h.useState(!1),[_,M]=h.useState(null),[A,T]=h.useState(null),[y,w]=h.useState(null),[R,O]=h.useState(0),z=h.useRef(0),$=h.useMemo(()=>a.find(G=>G.id===c)??null,[a,c]),V=h.useCallback(async()=>{if(!t)return!1;S(!0),M(null);try{const G=await Z.communities(t);return r(G.items),i(G.nextCursor),d(te=>te&&G.items.some(oe=>oe.id===te)?te:null),!0}catch(G){return M(gd(G)),!1}finally{S(!1)}},[t]),Y=h.useCallback(async()=>{if(!t||!s||f)return!1;S(!0),M(null);try{const G=await Z.communities(t,s);return r(te=>w9(te,G.items)),i(G.nextCursor),!0}catch(G){return M(gd(G)),!1}finally{S(!1)}},[t,f,s]),re=h.useCallback(async G=>{if(!t)return null;const te=++z.current;I(!0),T(null);try{const oe=await Z.communityPreview(t,G.slug);return z.current===te&&p(oe),oe}catch(oe){return z.current===te&&T(gd(oe)),null}finally{z.current===te&&I(!1)}},[t]),ee=h.useCallback(G=>{const te=a.find(oe=>oe.id===G);te&&(d(te.id),p(oe=>oe?.id===te.id?oe:null),w(null),re(te))},[a,re]),H=h.useCallback(()=>{z.current+=1,d(null),p(null),T(null),w(null)},[]);h.useEffect(()=>{if(!t){r([]),p(null),d(null);return}V()},[t,V,n]),h.useEffect(()=>{!$||l?.id===$.id||b||re($)},[re,l?.id,b,$]);const F=h.useCallback(async()=>{const G=$;await V(),G&&await re(G)},[re,V,$]),J=h.useCallback(async()=>{if(!t||!l?.currentRules||C)return!1;P(!0),w(null);try{return await Z.joinCommunity(t,l.id,l.currentRules.id),O(G=>G+1),await F(),!0}catch(G){const te=Jl(G);return w(te),te.kind==="rules_stale"&&await F(),!1}finally{P(!1)}},[t,C,l,F]),K=h.useCallback(async()=>{if(!t||!l?.currentRules||C)return!1;P(!0),w(null);try{return await Z.acceptCommunityRules(t,l.id,l.currentRules.id),O(G=>G+1),await F(),!0}catch(G){const te=Jl(G);return w(te),te.kind==="rules_stale"&&await F(),!1}finally{P(!1)}},[t,C,l,F]),B=h.useCallback(async()=>{if(!t||!l||C)return!1;P(!0),w(null);try{return await Z.leaveCommunity(t,l.id),O(G=>G+1),await F(),!0}catch(G){return w(Jl(G)),!1}finally{P(!1)}},[t,C,l,F]),ne=h.useCallback(async G=>{if(!t||!l||C)return!1;P(!0),w(null);try{return await Z.updateCommunityNotifications(t,l.id,G),r(te=>te.map(oe=>oe.id===l.id&&oe.membership?{...oe,membership:{...oe.membership,notificationMode:G}}:oe)),p(te=>te?.id===l.id&&te.membership?{...te,membership:{...te.membership,notificationMode:G}}:te),!0}catch(te){return w(Jl(te)),!1}finally{P(!1)}},[t,C,l]);return{items:a,nextCursor:s,selectedCommunityId:c,selectedSummary:$,preview:l,discoveryLoading:f,previewLoading:b,membershipBusy:C,discoveryError:_,previewError:A,membershipError:y,membershipVersion:R,refresh:V,loadMore:Y,showDiscovery:H,selectCommunity:ee,join:J,acceptRules:K,leave:B,updateNotifications:ne,clearMembershipError:()=>w(null)}}function w9(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 gd(e){return e instanceof Error?e.message:String(e)}function Jl(e){const t=gd(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 I9(e,t,n){return G1({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const r=fx.safeParse(a);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function _9(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:r}=e,s=n?.id??null,i=n?.membership?.status==="active",c=!n?.capabilities.requiresRulesAcceptance,[d,l]=h.useState([]),[p,f]=h.useState(null),[S,b]=h.useState({}),[I,C]=h.useState([]),[P,_]=h.useState(!1),[M,A]=h.useState(!1),[T,y]=h.useState(!1),[w,R]=h.useState(!1),[O,z]=h.useState(null),[$,V]=h.useState(null),[Y,re]=h.useState(null),[ee,H]=h.useState(null),[F,J]=h.useState(!1),[K,B]=h.useState(null),[ne,G]=h.useState(null),te=h.useRef(null),oe=h.useRef([]),be=h.useRef("mentions"),me=h.useRef(0),Re=h.useRef({}),Q=h.useRef(new Set),xe=h.useMemo(()=>d.find(Se=>Se.id===p)??null,[d,p]),je=p?S[p]??null:null;h.useEffect(()=>{te.current=p},[p]),h.useEffect(()=>{oe.current=d},[d]),h.useEffect(()=>{be.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const De=h.useCallback(async()=>{if(!t||!s)return!1;_(!0),z(null);try{const Se=await Z.communityChannels(t,s);return l(Se.channels),f(Le=>Le&&Se.channels.some(Ae=>Ae.id===Le)?Le:Se.channels.find(Ae=>Ae.isDefault)?.id??Se.channels[0]?.id??null),J(!1),!0}catch(Se){const Le=ma(Se);return z(Le),ec(Le)&&J(!0),!1}finally{_(!1)}},[s,t]),He=h.useCallback(async Se=>{if(!t||!s)return!1;const Le=++me.current;A(!0),V(null);try{const Ae=await Z.communityMessages(t,s,Se,{limit:50});return Le!==me.current?!1:(b(qe=>({...qe,[Se]:{items:Ae.messages,hasMoreBefore:Ae.hasMoreBefore,preview:Ae.preview}})),J(!1),!0)}catch(Ae){if(Le!==me.current)return!1;const qe=ma(Ae);return V(qe),ec(qe)&&J(!0),!1}finally{Le===me.current&&A(!1)}},[s,t]);h.useEffect(()=>{l(n?.channels??[]),b({}),f(n?.channels.find(Se=>Se.isDefault)?.id??n?.channels[0]?.id??null),z(null),V(null),re(null),J(!1),Q.current.clear(),s&&De()},[s,De,r]),h.useEffect(()=>{p&&He(p)},[He,p]);const Ie=h.useCallback(async(Se,Le)=>{if(!t||!s||!i||!c||Le<=0)return!1;if((Re.current[Se]??0)>=Le)return!0;Re.current[Se]=Le;try{const Ae=await Z.markCommunityRead(t,s,Se,Le);return l(qe=>qe.map(Ue=>Ue.id===Se?{...Ue,unreadCount:0,readState:Ue.readState?{...Ue.readState,lastReadSequence:Ae.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:Ae.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:Ue)),!0}catch(Ae){const qe=ma(Ae);return ec(qe)&&J(!0),!1}},[s,t,i,c]);h.useEffect(()=>{const Se=je?.items.at(-1)?.sequence??0;p&&Se>0&&Ie(p,Se)},[Ie,p,je?.items]);const Me=h.useCallback(Se=>{if(Se.communityId!==s||Q.current.has(Se.id))return;Q.current.add(Se.id);const Le=px.safeParse(Se.payload.message);if(Le.success&&Se.type!=="read.updated"){const Ae=Le.data;if(b(qe=>{const Ue=qe[Se.channelId];if(!Ue)return qe;const Mt=Ue.items.some(pe=>pe.id===Ae.id)?Ue.items.map(pe=>pe.id===Ae.id?Ae:pe):[...Ue.items,Ae].sort((pe,fe)=>pe.sequence-fe.sequence);return{...qe,[Se.channelId]:{...Ue,items:Mt}}}),l(qe=>qe.map(Ue=>Ue.id===Se.channelId?{...Ue,lastMessageSequence:Math.max(Ue.lastMessageSequence,Ae.sequence),unreadCount:te.current===Se.channelId||Ae.authorUserId===a?0:Math.max(Ue.unreadCount+(Se.type==="message.created"?1:0),0)}:Ue)),Se.type==="message.created"&&Ae.authorUserId!==a){const qe=oe.current.find(Mt=>Mt.id===Se.channelId),Ue=C9(Ae).includes(a??""),bn=be.current;!qe?.readState?.mutedAt&&(bn==="all"||bn==="mentions"&&Ue)&&G({communityId:Se.communityId,channelId:Se.channelId,message:Ae})}te.current===Se.channelId&&Ie(Se.channelId,Ae.sequence);return}Se.type==="read.updated"&&Se.payload.userId===a&&De()},[s,a,De,Ie]);h.useEffect(()=>{if(!t||!s||!i||!c)return;let Se=!1,Le=null;return re(null),Promise.all([Z.communityRealtimeSession(t,s),Z.communityEvents(t,s)]).then(async([Ae,qe])=>{if(Se)return;const Ue=async()=>{let Mt=qe.cursor;for(;;){const pe=await Z.communityEvents(t,s,{after:Mt,limit:200});if(Se)return;for(const fe of pe.events)Me(fe);if(Mt=pe.cursor,!pe.hasMore)return}},bn=I9({session:Ae,onEvent:Me,onReady:()=>{re(null),Ue().catch(Mt=>re(ma(Mt)))},onError:Mt=>re(ma(Mt))});Le=()=>bn.close(),await Ue()}).catch(Ae=>{if(!Se){const qe=ma(Ae);re(qe),ec(qe)&&J(!0)}}),()=>{Se=!0,Le?.()}},[Me,s,t,i,r,c]);const Te=h.useCallback(async()=>{if(!t||!s||!p||T)return!1;const Se=S[p],Le=Se?.items[0]?.sequence;if(!Se?.hasMoreBefore||Le==null)return!1;y(!0),V(null);try{const Ae=await Z.communityMessages(t,s,p,{beforeSequence:Le,limit:50});return b(qe=>{const Ue=qe[p]??Se,bn=new Set(Ue.items.map(Mt=>Mt.id));return{...qe,[p]:{...Ue,items:[...Ae.messages.filter(Mt=>!bn.has(Mt.id)),...Ue.items],hasMoreBefore:Ae.hasMoreBefore}}}),!0}catch(Ae){return V(ma(Ae)),!1}finally{y(!1)}},[s,t,S,T,p]),N=h.useCallback(async Se=>{if(!t||!s||!p||w)return!1;R(!0),H(null),B(null);try{const Le=await Promise.all(Se.attachments.map(qe=>Z.uploadCommunityAttachment(t,s,p,qe))),Ae=await Z.sendCommunityMessage(t,s,p,{body:Se.body,clientRequestId:Se.clientRequestId,mentionUserIds:Se.mentionUserIds,attachmentIds:Le.map(qe=>qe.id),replyToMessageId:Se.replyToMessageId});return b(qe=>{const Ue=qe[p]??{items:[],hasMoreBefore:!1,preview:!1};return Ue.items.some(bn=>bn.id===Ae.id)?qe:{...qe,[p]:{...Ue,items:[...Ue.items,Ae]}}}),await Ie(p,Ae.sequence),!0}catch(Le){const Ae=ma(Le);return H(Ae),B({...Se,message:Ae}),ec(Ae)&&J(!0),!1}finally{R(!1)}},[s,t,Ie,p,w]),q=h.useCallback(Se=>N({body:Se.body,clientRequestId:crypto.randomUUID(),mentionUserIds:Se.mentionUserIds??[],attachments:Se.attachments??[],replyToMessageId:Se.replyToMessageId??null}),[N]),X=h.useCallback(async(Se,Le)=>{if(!t||!s||!p)return!1;H(null);try{const Ae=await Z.editCommunityMessage(t,s,p,Se,Le);return a0(b,p,Ae),!0}catch(Ae){return H(ma(Ae)),!1}},[s,t,p]),U=h.useCallback(async Se=>{if(!t||!s||!p)return!1;H(null);try{const Le=await Z.deleteCommunityMessage(t,s,p,Se);return a0(b,p,Le),!0}catch(Le){return H(ma(Le)),!1}},[s,t,p]),ae=h.useCallback(async(Se,Le)=>{if(!t||!s)return!1;H(null);try{const Ae=await Z.setCommunityChannelMuted(t,s,Se,Le);return l(qe=>qe.map(Ue=>Ue.id===Se&&Ue.readState?{...Ue,readState:{...Ue.readState,mutedAt:Ae.mutedAt}}:Ue)),!0}catch(Ae){return H(ma(Ae)),!1}},[s,t]),de=h.useCallback(async(Se="")=>{if(!t||!s||!i)return[];try{const Le=await Z.searchCommunityMembers(t,s,{query:Se,limit:50});return C(Ae=>R9(Ae,Le.items)),Le.items}catch(Le){return H(ma(Le)),[]}},[s,t,i]);h.useEffect(()=>{i&&c?de():C([])},[i,c,de]);const ye=h.useCallback(async Se=>{if(!t||!s||!p)return!1;try{const Le=await Z.communityAttachmentDownload(t,s,p,Se);return window.open(Le.url,"_blank","noopener,noreferrer"),!0}catch(Le){return H(ma(Le)),!1}},[s,t,p]),Oe=h.useCallback(()=>p?He(p):Promise.resolve(!1),[He,p]),$e=h.useCallback(()=>K?N(K):Promise.resolve(!1),[K,N]),Ge=h.useCallback(()=>B(null),[]),yt=h.useCallback(()=>G(null),[]);return{channels:d,selectedChannelId:p,selectedChannel:xe,messages:je?.items??[],hasMoreBefore:je?.hasMoreBefore??!1,previewMode:je?.preview??!i,members:I,channelsLoading:P,messagesLoading:M,olderMessagesLoading:T,sending:w,channelsError:O,messagesError:$,realtimeError:Y,actionError:ee,lostMembership:F,failedSend:K,incomingNotification:ne,selectChannel:f,loadChannels:De,loadMessages:Oe,loadOlder:Te,sendMessage:q,retrySend:$e,dismissFailedSend:Ge,editMessage:X,deleteMessage:U,setMuted:ae,searchMembers:de,downloadAttachment:ye,dismissIncomingNotification:yt}}function a0(e,t,n){e(a=>{const r=a[t];return r?{...a,[t]:{...r,items:r.items.map(s=>s.id===n.id?n:s)}}:a})}function C9(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function R9(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 ec(e){return e.includes("community_membership_required")||e.includes("community_rules")}function ma(e){return e instanceof Error?e.message:String(e)}function P9(e){const t=k9({connection:e.connection,refreshToken:e.refreshToken}),n=_9({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,r=t.items,s=n.channels,i=t.selectCommunity,c=n.selectChannel,d=n.dismissIncomingNotification,{setView:l,showToast:p}=e,f=h.useCallback(()=>{t.showDiscovery(),l("community")},[t.showDiscovery,l]),S=h.useCallback(I=>{t.selectCommunity(I),l("community")},[t.selectCommunity,l]),b=h.useCallback(I=>{n.selectChannel(I),l("community")},[n.selectChannel,l]);return h.useEffect(()=>{if(!a)return;const I=r.find(P=>P.id===a.communityId),C=s.find(P=>P.id===a.channelId);p(`${I?.displayName??"Community"} · #${C?.displayName??"channel"}: ${a.message.body.slice(0,120)||"New message"}`,"info",{actionLabel:"View",onAction:()=>{i(a.communityId),c(a.channelId),l("community")},placement:"top-right"}),d()},[s,r,d,a,c,i,l,p]),{communities:t,chat:n,sidebar:{communityItems:t.items,communityChannels:n.channels,communityLoading:t.discoveryLoading,communityError:t.discoveryError,selectedCommunityId:t.selectedCommunityId,selectedCommunityChannelId:n.selectedChannelId,discoverCommunities:f,selectCommunity:S,selectCommunityChannel:b},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const T9=[];function A9(e){const t=h.useCallback(a=>JF(e,a),[e]),n=h.useCallback(()=>GF(e)??T9,[e]);return h.useSyncExternalStore(t,n,n)}function E9(e){const[t,n]=h.useState(()=>Km());return h.useEffect(()=>{let a=!0;return e?(Z.connectedAppStatus(e,{status:"all"}).then(r=>{a&&n(r.apps)}).catch(r=>{console.warn("Unable to load connected app mention status.",r),a&&n(Km())}),()=>{a=!1}):(n(Km()),()=>{a=!1})},[e]),t}function j9(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=GV(),[r,s]=h.useState(null),[i,c]=h.useState([]),[d,l]=h.useState(null),[p,f]=h.useState(null),[S,b]=h.useState([]),[I,C]=h.useState(null),[P,_]=h.useState(null),[M,A]=h.useState(a1),[T,y]=h.useState({}),[w,R]=h.useState(()=>new Set),O=h.useCallback((Ve,tn)=>{R(Bt=>{if(Bt.has(Ve)===tn)return Bt;const Vt=new Set(Bt);return tn?Vt.add(Ve):Vt.delete(Ve),Vt})},[]),[z,$]=h.useState(0),[V,Y]=h.useState(null),re=h.useRef(null),{confirmProjectAction:ee,projectConfirmDialog:H,resolveProjectConfirmDialog:F}=HB(),{query:J,searchOpen:K,archivedChatsOpen:B,sectionMenuOpen:ne,projectsExpanded:G,cloudProjectsExpanded:te,chatRowsVisibleCount:oe,sidebarOpen:be,view:me,selectedAppId:Re,selectedProjectId:Q,selectedSessionId:xe,draftProvider:je,draftModel:De,draftExperience:He,codexPermissionMode:Ie,codexReasoningEffort:Me,openPondCommandAccessMode:Te,busy:N,diffPanelOpen:q,diffPanelExpanded:X,rightPanelMode:U,rightChatPanels:ae,terminalOpen:de,settingsSection:ye,newProjectDialogOpen:Oe,newProjectMode:$e,newProjectName:Ge,newProjectPath:yt,newProjectBusy:Se,commitDialogOpen:Le,commitMessage:Ae,commitIncludeUnstaged:qe,commitNextStep:Ue,commitDraft:bn,branchDialogOpen:Mt,branchDialogName:pe,toast:fe,error:Fe}=a,Pe=XV(me==="labs"),{setQuery:Ne,setSearchOpen:ot,setArchivedChatsOpen:ut,setSectionMenuOpen:At,setProjectsExpanded:mt,setCloudProjectsExpanded:at,setChatRowsVisibleCount:Ct,setSidebarOpen:Be,setView:Et,setSelectedAppId:dn,setSelectedProjectId:jn,setSelectedSessionId:kt,setPrompt:kr,setDraftProvider:un,setDraftModel:yn,setDraftExperience:Ut,setCodexPermissionMode:Rn,setCodexReasoningEffort:Sn,setOpenPondCommandAccessMode:Pn,setDiffPanelOpen:Mn,setDiffPanelExpanded:qt,setRightPanelMode:gt,setRightChatPanels:qn,setTerminalOpen:mn,setSyncingWorkspaceAppId:pt,setSettingsSection:_t,setNewProjectDialogOpen:Ot,setNewProjectMode:pn,setNewProjectName:oa,setNewProjectPath:Ze,setNewProjectBusy:Tn,setCommitDialogOpen:Za,setCommitMessage:Ea,setCommitIncludeUnstaged:Ln,setCommitNextStep:An,setCommitDraft:Ja,setBranchDialogOpen:wr,setBranchDialogName:ja,setError:lt}=n,{connectionRef:rn,setError:Ke,showToast:St}=zV({appDispatch:t,error:Fe,setErrorState:lt}),{appPreferences:en,applyBootstrapPayload:zn,applyPreferencesPayload:xn,bootstrap:D,codexHistorySessions:we,connection:le,events:Je,runtimeEventStore:ga,approvals:Bn,sessions:Ma,startup:kn,setAppPreferences:ao,setBootstrap:Ir,setCodexHistorySessions:On,setEvents:ia,setSessions:ca}=NV({selectedSessionId:xe,setDraftModel:yn,setDraftProvider:un,setCodexPermissionMode:Rn,setCodexReasoningEffort:Sn,setOpenPondCommandAccessMode:Pn,setError:Ke,setSelectedAppId:dn,setSelectedProjectId:jn,setSelectedSessionId:kt});rn.current=le,h.useEffect(()=>{D&&b(D.sidebarFileBookmarks??[])},[D?.sidebarFileBookmarks]);const _r=h.useMemo(()=>[...Je].reverse().find(Ve=>Ve.name==="tool.completed"&&Ve.action==="manage_sidebar_file")??null,[Je]),ks=h.useRef(null);h.useEffect(()=>{!le||!_r||ks.current===_r.id||(ks.current=_r.id,Z.sidebarFiles(le).then(Ve=>b(Ve.items)).catch(Ve=>Ke(Ve instanceof Error?Ve.message:String(Ve))))},[le,_r,Ke]);const ws=h.useCallback(async(Ve,tn)=>{if(!le)return;const Bt=S;b(Vt=>tn==="none"?Vt.filter(ua=>ua.id!==Ve.id):Vt.some(ua=>ua.id===Ve.id)?Vt.map(ua=>ua.id===Ve.id?{...ua,status:tn}:ua):[...Vt,{...Ve,status:tn}]);try{const Vt=await Z.patchSidebarFile(le,{workspaceKind:Ve.workspaceKind,workspaceId:Ve.workspaceId,workspaceName:Ve.workspaceName,path:Ve.path,status:tn,sourceSessionId:Ve.sourceSessionId});b(Vt.items)}catch(Vt){b(Bt),Ke(Vt instanceof Error?Vt.message:String(Vt))}},[le,Ke,S]),Is=E9(le),ft=sK({connection:le,profileId:D?.profile?.activeProfile??"default"}),{pinnedCollapsed:Ii,projectsCollapsed:_s,cloudProjectsCollapsed:_i,chatsCollapsed:ro,savedForLaterCollapsed:Ci,sidebarWidth:Cr,sidebarResizing:Ri,diffPanelWidth:so,diffPanelResizing:oo,togglePinnedCollapsed:io,toggleProjectsCollapsed:Pi,toggleCloudProjectsCollapsed:Ti,toggleChatsCollapsed:Qa,toggleSavedForLaterCollapsed:Ai,startSidebarResize:co,startDiffPanelResize:Cs}=QV({connection:le,preferences:D?.preferences,sidebarOpen:be,diffPanelExpanded:X,setBootstrap:Ir,setError:Ke}),{cloudProjectById:Rs,linkedProjectByAppId:lo,localProjectById:la,mentionableSandboxApps:Ei,selectedApp:Ps,selectedCloudProject:Rr,selectedProject:Gn,selectedProjectLinkedApp:ji,selectedProjectLinkedOpenPondApp:Mi,selectedSession:wn,selectedSessionLinkedProject:Kr,sidebarSessions:Zn}=p5({bootstrap:D,codexHistorySessions:we,selectedAppId:Re,selectedProjectId:Q,selectedSessionId:xe,sessions:Ma}),Pr=wn?.experience??He;h.useEffect(()=>{HF(Pr)},[Pr]);const Ts=h.useMemo(()=>xq(Zn,Pr),[Pr,Zn]),Wr=gK(Je,Bn),{chatMentionApps:Oi,connectedAppMentions:uo,pendingApproval:As}=j5({bootstrap:D,connectedAppRows:Is,mentionableSandboxApps:Ei,runtimeIndexes:Wr,selectedApp:Ps,selectedCloudProject:Rr,selectedProject:Gn,selectedSession:wn,selectedSessionId:xe}),{codexHistoryEvents:Tr,setCodexHistoryEvents:Ar}=Q5({connection:le,selectedSessionId:xe,selectedSessionLocallyActive:!!(xe&&w.has(xe)),selectedSessionStatus:wn?.status,setCodexHistorySessions:On,setError:Ke}),{account:Es,accountPending:mo,accountSignedOut:Gr,activeModel:Ya,activeProvider:va,activeWorkspaceAppId:po,activeWorkspaceId:Zr,activeWorkspaceKind:Xa,activeWorkspaceLocation:fo,appDefaults:Oa,cloudLinked:ho,selectedCodexHistoryPending:$i,selectedSessionProjectId:go,startMessage:Ni,workspaceName:vo}=c5({bootstrap:D,draftModel:De,draftProvider:je,selectedApp:Ps,selectedAppId:Re,selectedCloudProject:Rr,selectedProject:Gn,selectedSession:wn,selectedSessionId:xe,selectedSessionLinkedProject:Kr}),bo=h.useMemo(()=>XF(D?.account??null),[D?.account]),yo=h.useMemo(()=>Pf(D?.account??null),[D?.account]),js=A9(yo),So=h.useMemo(()=>n5(js,Oa.defaultTeamId),[Oa.defaultTeamId,js]),Ms=So?.teamId??null,er=f9({connection:le,teamId:Ms,currentUserId:Es?.profile?.id??null,refreshToken:D?.accountMeta.asOf??null}),Di=y9({connection:le,teamId:Ms,applyBootstrapPayload:zn,refreshDirectory:er.refreshDirectory});x9({notification:er.incomingNotification,dismiss:er.dismissIncomingNotification,selectThread:er.selectThread,setView:Et,showToast:St});const{communities:Li,sidebar:zi,view:Hi}=P9({connection:le,currentUserId:Es?.profile?.id??null,refreshToken:D?.accountMeta.asOf??null,setView:Et,showToast:St}),tr=er.aiThread?.conversationId??null,xo=me==="team"&&!!tr&&q&&U==="chat";h.useEffect(()=>{if(me==="team"){if(tr){gt("chat"),Mn(!0);return}U==="chat"&&Mn(!1)}},[U,Mn,gt,tr,me]);const Ui=h.useCallback(()=>{if(tr){if(xo){Mn(!1);return}gt("chat"),Mn(!0)}},[Mn,gt,xo,tr]),qi=h.useMemo(()=>Ra(Gn,D?.cloudProjects??[]),[D?.cloudProjects,Gn]),Bi=wn?.provider==="codex"?Te:wn?.openPondCommandAccessMode??Te,da=po,ko=Zr,et=Xa,Ft=vo,{openPondActionCatalog:nr,selectedActionCatalog:sn}=EK({cloudProjectById:Rs,cloudProjects:D?.cloudProjects??[],connection:le,defaultTeamId:Oa.defaultTeamId,accountScopeKey:bo,localProjects:D?.localProjects??[],profile:D?.profile,selectedCloudProject:Rr,selectedProject:Gn,reportError:Ke}),{expandedProjectIds:Hn,expandProject:$n,toggleProjectExpanded:ju,setExpandedProjectIds:Mu}=jK({selectedProjectId:Q});S5({activeWorkspaceId:Zr,activeWorkspaceKind:Xa,appDispatch:t,connection:le,expandProject:$n,linkedProjectByAppId:lo,providerSettings:D?.providers??null,selectedAppId:Re,selectedSession:wn,selectedSessionId:xe,selectedSessionProjectId:go,setDiffPanelExpanded:qt,setDraftModel:yn,setDraftProvider:un,setError:Ke,setSelectedAppId:dn,setSelectedProjectId:jn,setSessions:ca,setTerminalOpen:mn,toast:fe});const{changeCodexPermissionMode:Ou,changeCodexReasoningEffort:$u}=M5({connection:le,setBootstrap:Ir,setCodexPermissionMode:Rn,setCodexReasoningEffort:Sn,setError:Ke}),{changeOpenPondCommandAccessMode:sl}=F3({connection:le,selectedSession:wn,setBootstrap:Ir,setError:Ke,setOpenPondCommandAccessMode:Pn,setSessions:ca}),Nu=x5({connection:le,setError:Ke}),Os=h.useCallback(()=>{$(Ve=>Ve+1)},[]),ol=w5({appDispatch:t,expandProject:$n,linkedProjectByAppId:lo,requestComposerFocus:Os,onBeginNewChat:()=>{Lt({kind:"chat",sessionId:null}),Y(null),Ut(Ve=>Ve==="development"?"work":Ve)},setMentionedAppId:f}),wo=h.useCallback(Ve=>{const tn=ct("local",Ve);t({type:"selectProject",projectId:tn}),$n(tn)},[t,$n]),{advanceAfterTurn:Du,begin:Lu,bindSession:zu,dismiss:Hu,handoff:Uu,prepareTurn:qu,selectTask:Bu}=uK({activeModel:Ya,activeProvider:va,applyBootstrapPayload:zn,beginNewChat:ol,composerDraftStore:e,connection:le,requestComposerFocus:Os,selectedLocalProjectId:Gn?.id??null,selectedSessionId:xe,selectLocalProject:wo,setDraftModel:yn,setDraftProvider:un,setError:Ke,view:me});JV({connection:le,events:Je,showToast:St}),Y3({searchOpen:K,sectionMenuOpen:ne,setSectionMenuOpen:At,setSearchOpen:ot,setQuery:Ne}),h.useEffect(()=>{y({})},[D?.server.id]);const{chatHistoryLoadStates:Fu,loadMoreSelectedChatHistory:Vu,selectedPagedSessionEvents:Ku,selectedRuntimeIndexes:il}=fK({approvals:Bn,codexHistoryEvents:Tr,connection:le,runtimeIndexes:Wr,runtimeEventStore:ga,selectedSessionId:xe,serverId:D?.server.id,setCodexHistoryEvents:Ar,setCodexHistorySessions:On,setError:Ke}),{activeSessions:Wu,archivedSessions:Gu,pinnedProjects:Zu,pinnedSessions:Fi,savedForLaterSessions:cl,pinnedFiles:Ju,savedForLaterFiles:Qu,pinnedItems:ll,projectRows:dl,localProjectRows:Yu,visibleProjectRows:Io,cloudProjectRows:Xu,projectSessionRowsByProjectId:ul,childSessionRowsByParentId:em,sidebarProjectIdBySessionId:Vi,chatRows:ml,visibleChatRows:pl,sessionEvents:tm,chatMessages:fl,contextUsage:nm,goalRuntime:am,subagentRuntime:hl}=V3({localProjects:D?.localProjects??[],cloudProjects:D?.cloudProjects??[],teamId:Oa.defaultTeamId,sessions:Ts,runtimeIndexes:il,appPreferences:en,selectedSessionId:xe,selectedProjectId:Q,archivedChatsOpen:B,projectsExpanded:G,chatRowsVisibleCount:oe,sidebarFileBookmarks:S}),rm=h.useCallback(Ve=>{Ut(Ve);const tn=[...Ts].filter(Bt=>Ve==="work"?Bt.experience==="work"||Bt.experience==="development":Bt.experience===Ve).sort((Bt,Vt)=>Vt.updatedAt.localeCompare(Bt.updatedAt))[0]??[...Zn].filter(Bt=>Bt.experience===Ve).sort((Bt,Vt)=>Vt.updatedAt.localeCompare(Bt.updatedAt))[0]??null;if(tn)t({type:"selectSession",sessionId:tn.id,appId:Ve!=="chat"?tn.appId:null,projectId:Ve!=="chat"?Vi[tn.id]??null:null});else if(t({type:"beginNewChat",appId:null}),Ve==="chat"&&va==="codex"){const Bt=Sf(D?.providers,{enabledOnly:!0}).find(Vt=>Vt.value!=="codex")?.value??Ks;un(Bt),yn(Nd(Bt,D?.providers)??wc)}Ve==="chat"&&(mn(!1),qt(!1),gt("home")),Et("chat")},[t,va,D?.providers,Ts,qt,Ut,yn,un,gt,mn,Et,Vi,Zn]),gl=h.useCallback(Ve=>{const tn=e.getSnapshot();if(Ut(Ve),(xe||Re||Q)&&(t({type:"beginNewChat",appId:null}),tn&&e.set(tn)),Ve==="chat"&&va==="codex"){const Bt=Sf(D?.providers,{enabledOnly:!0}).find(Vt=>Vt.value!=="codex")?.value??Ks;un(Bt),yn(Nd(Bt,D?.providers)??wc)}Ve==="chat"&&(mn(!1),qt(!1),gt("home")),Et("chat")},[va,t,D?.providers,e,Re,Q,xe,qt,Ut,yn,un,gt,mn,Et]),{pendingChatUserMessages:sm,recordPendingChatUserMessage:om,visibleChatMessages:im}=B3({chatMessages:fl,runtimeIndexes:il,selectedSessionId:xe}),Jr=h.useMemo(()=>jq({selectedAppId:Re,selectedProjectId:Q,selectedSessionId:xe}),[Re,Q,xe]),vl=h.useRef(null);h.useEffect(()=>{const Ve=vl.current;vl.current=Jr,!(!Ve||Ve.kind!=="draft"||Jr.kind!=="session")&&(Nc(Ve,Jr)||c(tn=>{const Bt=Mq({tabs:tn,previousScope:Ve,activeScope:Jr});return Bt.some((ua,Dm)=>ua!==tn[Dm])?Bt:tn}))},[Jr]);const cm=h.useMemo(()=>Oq(i),[i]),{goalRuntime:lm,runningSessionIds:Ki,selectedSessionRunning:dm,sidebarGoalRuntimeBySessionId:um,sidebarSubagentRuntimeBySessionId:mm}=Q3({codexHistoryEvents:Tr,codexHistorySessions:we,connection:le,expandedProjectIds:Hn,goalRuntime:am,locallyActiveCodexHistorySessionIds:w,pinnedSessions:Fi,savedForLaterSessions:cl,projectSessionRowsByProjectId:ul,rightChatHistoryEvents:T,runtimeIndexes:Wr,selectedSession:wn,selectedSessionId:xe,serverId:D?.server.id,setCodexHistorySessions:On,sidebarSessions:Zn,subagentRuntime:hl,visibleChatRows:pl,visibleProjectRows:Io}),{dragItem:pm,pinnedPreviewKeys:fm,startPinnedDrag:hm,clearSidebarDrag:gm,previewPinnedDrop:vm,commitPinnedDrop:bm,commitPinnedPreviewDrop:ym}=Y5({connection:le,appPreferences:en,sessions:Zn,pinnedItems:ll,setAppPreferences:ao,setCodexHistorySessions:On,setSessions:ca,sidebarFileBookmarks:S,setSidebarFileBookmarks:b,setError:Ke}),{clearTaskDrag:Sm,commitTaskDrop:bl,commitTaskPreviewDrop:xm,previewTaskDrop:$a,startTaskDrag:_o,taskDragSessionId:km,taskPreviewSessionIds:wm}=X5({connection:le,sessions:Zn,setCodexHistorySessions:On,setError:Ke,setSessions:ca}),{commandProjectRows:Im,contextWindowStatus:Wi,pinnedRows:_m,sidebarWorkspaceAppIds:Cm}=k5({activeProvider:va,contextCompaction:Oa.contextCompaction,contextUsage:nm,pinnedItems:ll,pinnedPreviewKeys:fm??[],pinnedProjects:Zu,projectRows:dl,visibleProjectRows:Io}),Er=!!(da&&(me==="chat"||me==="labs")&&(Le||q&&(U==="changes"||U==="goal"))),{workspaceStates:Co,workspaceBusy:Ro,diffBusy:Rm,visibleWorkspaceState:$s,visibleWorkspaceDiff:Gi,rememberWorkspaceState:Po,refreshWorkspace:Zi,refreshWorkspaceDiff:ar,setWorkspaceBusy:Sl}=$K({connection:le,activeWorkspaceAppId:da,view:me,shouldLoadWorkspaceDiff:Er,sidebarWorkspaceAppIds:Cm,setError:Ke});re.current=Po;const Pm=h.useCallback((Ve=da)=>!Ve||Ve!==da||!Er?Promise.resolve(null):ar(Ve),[ar,Er,da]),Tm=h.useCallback(async(Ve={})=>{!da||!Er||await ar(da,Ve)},[ar,Er,da]),Am=!1,Em=!!(wn?.provider==="codex"&&wn.cwd&&!Sr(wn.workspaceKind)),jm=!!($s&&!$s.initialized&&Xa!=="local_project"&&va!=="codex"&&!Em&&!$i),Mm=Xa==="local_project"&&!!Gn?.sandboxTemplate?.detected&&!Gn?.linkedOpenPondApp?.appId,[xl,kl]=h.useState(null),[Om,wl]=h.useState(null),{projectTarget:$m,workspaceTarget:Nm}=l5({accountPending:mo,accountSignedOut:Gr,activeWorkspaceLocation:fo,bootstrap:D,busy:N,cloudLinked:ho,selectedCloudProject:Rr,selectedProject:Gn,selectedSession:wn,pendingWorkspaceTarget:xl,workspaceStates:Co,workspaceBusy:Ro});return h.useEffect(()=>{kl(null)},[wn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:r,setPendingTerminalCommand:s,terminalTabs:i,setTerminalTabs:c,trainingDetailTasksetId:d,setTrainingDetailTasksetId:l,mentionedAppId:p,setMentionedAppId:f,cloudSetupDialog:I,setCloudSetupDialog:C,rightPanelTabRequest:P,setRightPanelTabRequest:_,workspaceDiffPanelViewState:M,setWorkspaceDiffPanelViewState:A,rightChatHistoryEvents:T,setRightChatHistoryEvents:y,locallyActiveCodexHistorySessionIds:w,setCodexHistoryTurnLocallyActive:O,mainComposerFocusRequestId:z,requestMainComposerFocus:Os,draftSubagentDelegationMode:V,setDraftSubagentDelegationMode:Y,confirmProjectAction:ee,projectConfirmDialog:H,resolveProjectConfirmDialog:F,query:J,searchOpen:K,archivedChatsOpen:B,sectionMenuOpen:ne,projectsExpanded:G,cloudProjectsExpanded:te,sidebarOpen:be,view:me,selectedAppId:Re,selectedProjectId:Q,selectedSessionId:xe,draftProvider:je,draftModel:De,draftExperience:He,activeExperience:Pr,changeExperience:rm,changeNewExperience:gl,codexPermissionMode:Ie,codexReasoningEffort:Me,openPondCommandAccessMode:Te,busy:N,diffPanelOpen:q,diffPanelExpanded:X,rightPanelMode:U,rightChatPanels:ae,terminalOpen:de,settingsSection:ye,newProjectDialogOpen:Oe,newProjectMode:$e,newProjectName:Ge,newProjectPath:yt,newProjectBusy:Se,commitDialogOpen:Le,commitMessage:Ae,commitIncludeUnstaged:qe,commitNextStep:Ue,commitDraft:bn,branchDialogOpen:Mt,branchDialogName:pe,toast:fe,error:Fe,labDetailNavigation:Pe,setQuery:Ne,setSearchOpen:ot,setArchivedChatsOpen:ut,setSectionMenuOpen:At,setProjectsExpanded:mt,setCloudProjectsExpanded:at,setChatRowsVisibleCount:Ct,setSidebarOpen:Be,setView:Et,setSelectedAppId:dn,setSelectedProjectId:jn,setSelectedSessionId:kt,setPrompt:kr,setDraftProvider:un,setDraftModel:yn,setDraftExperience:Ut,setDiffPanelOpen:Mn,setDiffPanelExpanded:qt,setRightPanelMode:gt,setRightChatPanels:qn,setTerminalOpen:mn,setSyncingWorkspaceAppId:pt,setSettingsSection:_t,setNewProjectDialogOpen:Ot,setNewProjectMode:pn,setNewProjectName:oa,setNewProjectPath:Ze,setNewProjectBusy:Tn,setCommitDialogOpen:Za,setCommitMessage:Ea,setCommitIncludeUnstaged:Ln,setCommitNextStep:An,setCommitDraft:Ja,setBranchDialogOpen:wr,setBranchDialogName:ja,setError:Ke,showToast:St,appPreferences:en,applyBootstrapPayload:zn,applyPreferencesPayload:xn,approvals:Bn,bootstrap:D,connection:le,events:Je,runtimeEventStore:ga,sessions:Ma,startup:kn,setAppPreferences:ao,setCodexHistorySessions:On,setEvents:ia,setSessions:ca,training:ft,pinnedCollapsed:Ii,projectsCollapsed:_s,cloudProjectsCollapsed:_i,chatsCollapsed:ro,savedForLaterCollapsed:Ci,sidebarWidth:Cr,sidebarResizing:Ri,diffPanelWidth:so,diffPanelResizing:oo,togglePinnedCollapsed:io,toggleProjectsCollapsed:Pi,toggleCloudProjectsCollapsed:Ti,toggleChatsCollapsed:Qa,toggleSavedForLaterCollapsed:Ai,startSidebarResize:co,startDiffPanelResize:Cs,cloudProjectById:Rs,localProjectById:la,selectedApp:Ps,selectedCloudProject:Rr,selectedProject:Gn,selectedProjectLinkedApp:ji,selectedProjectLinkedOpenPondApp:Mi,selectedSession:wn,sidebarSessions:Zn,runtimeIndexes:Wr,chatMentionApps:Oi,connectedAppMentions:uo,pendingApproval:As,codexHistoryEvents:Tr,setCodexHistoryEvents:Ar,account:Es,accountPending:mo,accountSignedOut:Gr,activeModel:Ya,activeProvider:va,activeWorkspaceAppId:po,activeWorkspaceId:Zr,activeWorkspaceKind:Xa,activeWorkspaceLocation:fo,appDefaults:Oa,selectedSessionProjectId:go,startMessage:Ni,workspaceName:vo,accountScopeKey:bo,organizations:js,teamChatOrganization:So,teamChatTeamId:Ms,teamChat:er,publishTeamProfileAgent:Di,communities:Li,communitySidebar:zi,communityView:Hi,teamAiThreadId:tr,toggleTeamAiSidebar:Ui,selectedProjectConfirmedCloudProject:qi,activeOpenPondCommandAccessMode:Bi,viewWorkspaceAppId:da,viewWorkspaceId:ko,viewWorkspaceKind:et,viewWorkspaceName:Ft,openPondActionCatalog:nr,selectedActionCatalog:sn,expandedProjectIds:Hn,expandProject:$n,toggleProjectExpanded:ju,setExpandedProjectIds:Mu,changeCodexPermissionMode:Ou,changeCodexReasoningEffort:$u,changeOpenPondCommandAccessMode:sl,resolveApproval:Nu,beginNewChat:ol,advanceTrainingModelChatAfterTurn:Du,beginNewChatWithTrainingModel:Lu,bindTrainingModelChatSession:zu,dismissTrainingChatHandoff:Hu,trainingChatHandoff:Uu,prepareTrainingModelChatTurn:qu,selectTrainingChatTaskForComposer:Bu,chatHistoryLoadStates:Fu,loadMoreSelectedChatHistory:Vu,selectedPagedSessionEvents:Ku,activeSessions:Wu,archivedSessions:Gu,pinnedSessions:Fi,savedForLaterSessions:cl,pinnedFiles:Ju,savedForLaterFiles:Qu,sidebarFileBookmarks:S,setSidebarFileStatus:ws,projectRows:dl,localProjectRows:Yu,visibleProjectRows:Io,cloudProjectRows:Xu,projectSessionRowsByProjectId:ul,childSessionRowsByParentId:em,sidebarProjectIdBySessionId:Vi,chatRows:ml,visibleChatRows:pl,chatRowsVisibleCount:oe,sessionEvents:tm,chatMessages:fl,goalRuntime:lm,subagentRuntime:hl,pendingChatUserMessages:sm,recordPendingChatUserMessage:om,visibleChatMessages:im,activeTerminalScope:Jr,terminalSummaries:cm,runningSessionIds:Ki,selectedSessionRunning:dm,sidebarGoalRuntimeBySessionId:um,sidebarSubagentRuntimeBySessionId:mm,taskDragSessionId:km,taskPreviewSessionIds:wm,startTaskDrag:_o,clearTaskDrag:Sm,previewTaskDrop:$a,commitTaskDrop:bl,commitTaskPreviewDrop:xm,dragItem:pm,startPinnedDrag:hm,clearSidebarDrag:gm,previewPinnedDrop:vm,commitPinnedDrop:bm,commitPinnedPreviewDrop:ym,commandProjectRows:Im,contextWindowStatus:Wi,pinnedRows:_m,workspaceStates:Co,workspaceBusy:Ro,diffBusy:Rm,visibleWorkspaceState:$s,visibleWorkspaceDiff:Gi,rememberWorkspaceState:Po,refreshWorkspace:Zi,refreshWorkspaceDiff:ar,setWorkspaceBusy:Sl,refreshWorkspaceDiffWhenNeeded:Pm,refreshVisibleWorkspaceDiff:Tm,managedWorkspace:Am,canSyncActiveWorkspace:jm,canPublishOpenPondProject:Mm,pendingWorkspaceTarget:xl,setPendingWorkspaceTarget:kl,pendingSidebarWorkspaceTarget:Om,setPendingSidebarWorkspaceTarget:wl,projectTarget:$m,workspaceTarget:Nm}}const M9=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,O9=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function $9(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)?Ql(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?Ql(n,new Set(["file:"])):null:M9.test(n)?Ql(`http://${n}`,new Set(["http:"])):O9.test(n)?Ql(`https://${n}`,new Set(["https:"])):null}function Ql(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function N9(e){const t=$9(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 D9="openpond-coding-core-v1",L9="feature";function Lf(e){const t=new URL("/sandboxes",Vg(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",L9),t.searchParams.set("runtimeProfileId",D9),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 m7(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Vg(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function r0(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Vg(e.accountBaseUrl)).toString()}function Vg(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 z9({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:r,rightPanelMode:s,selectedProjectId:i,setDiffPanelOpen:c,setNewProjectDialogOpen:d,setNewProjectMode:l,setNewProjectName:p,setRightPanelMode:f}){const S=h.useCallback(()=>{f("changes"),c(!0)},[c,f]),b=h.useCallback(()=>{if(r&&s==="changes"){c(!1);return}S()},[r,s,c,S]),I=h.useCallback(()=>{f("browser"),c(!0)},[c,f]),C=h.useCallback(()=>{f("goal"),c(!0)},[c,f]),P=h.useCallback((T,y)=>{N9({conversationId:t,href:T,explicitFile:y?.explicitFile,newTab:y?.newTab}).then(w=>{w&&I()})},[t,I]),_=h.useCallback(()=>{l("cloud"),p(""),d(!0)},[d,l,p]),M=h.useCallback(T=>{const y=n.get(T);y&&P(Lf({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:y.teamId,projectId:y.id,projectName:y.name,baseBranch:y.defaultBranch,source:"openpond-app"}),{newTab:!0})},[e,n,P]);return{createCloudEnvironmentFromSidebar:h.useCallback(()=>{const T=i?.startsWith("cloud:")?i.slice(6):a[0]?.id??null;if(T){M(T);return}_()},[a,_,i,M]),openCloudProjectDialog:_,openUrlInBrowserPanel:P,showBrowserPanel:I,showChangesPanel:S,showGoalSidebarTab:C,toggleChangesPanel:b}}function H9(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 U9({browserConversationId:e,sessionIds:t,onOpenSession:n,onShowBrowserPanel:a}){h.useEffect(()=>window.openpond?.browser?.onRevealRequest?.(s=>{const i=H9({currentConversationId:e,requestConversationId:s.conversationId,sessionIds:t});i.reveal&&(i.sessionIdToOpen&&n(i.sessionIdToOpen),a())}),[e,n,a,t])}const q9="chat",B9=["help me","please","can you","could you","make","create","build"],F9=new Set(["a","an","and","for","from","i","me","my","of","our","please","produce","summary","the","to","with"]);function s0(e){const t=$p(e.label);if(t&&!zf(t))return o0(t);const n=$p(e.name);if(n&&!zf(n))return o0(n);const a=$p(e.actionId)?.replace(/\.chat$/i,"")??"";return V9(a||t||"Profile Agent")}function zf(e){return e.trim().toLowerCase()===q9}function V9(e){const t=K9(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(r=>r.replace(/[^a-z0-9]/g,"")).filter(r=>r&&!F9.has(r)).slice(0,3);return e_(a.length?a.join(" "):t||e)}function o0(e){return e_(e).split(/\s+/).slice(0,4).join(" ")}function K9(e){let t=e.trim();for(const n of B9)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function $p(e){return typeof e=="string"&&e.trim()?e.trim():null}function e_(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const W9="openpond-profile-action";function G9(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Yl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Z9(e){const t=G9(e.implementation);if(t?.type!==W9)return null;const n=Yl(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=Yl(e.label);if(a&&!zf(a))return s0({label:a,description:e.description});const r=Yl(t.agentName)??Yl(e.name);return s0({actionId:n,description:e.description,name:r})}function J9(e){const t=Z9(e);return t||e.label?.trim()||e.name?.trim()||e.id}function t_(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 Q9=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function n_(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function vi(e){return typeof e=="string"&&e.trim()?e.trim():null}function Qo(e,t,n={}){const a=vi(t)?Un(String(t)):"";a&&(!n.generic&&Q9.has(a)||e.add(a))}function Xl(e,t){const n=vi(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Qo(e,a)}function Y9(e,t){const n=vi(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Qo(e,a)}function a_(e){const t=new Set,n=n_(e.implementation),a=vi(n?.actionId);return Qo(t,e.id,{generic:!0}),Xl(t,e.id),Qo(t,a,{generic:!0}),Xl(t,a),Qo(t,e.name,{generic:!0}),Xl(t,e.name),Qo(t,e.label,{generic:!0}),Xl(t,e.label),Y9(t,e.description),t}function X9(e){const t=n_(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",vi(t?.actionId)??"",vi(t?.agentName)??"",t_(e),...Array.from(a_(e))].join(" ").toLowerCase()}function p7(e,t,n=8){const a=Un(t);return e.length===0?[]:e.filter(r=>a?X9(r).includes(a):!0).slice(0,n)}function eW(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Un(t[1]??"")).filter(Boolean)}function tW(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function nW(e,t){const n=eW(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const s of n)for(const i of t)a_(i).has(s)&&a.set(i.id,{action:i,mention:s});if(a.size!==1)return null;const r=Array.from(a.values())[0];return{action:r.action,mention:r.mention,prompt:tW(e,r.mention)}}function f7(e){return J9(e)}function h7(e){return e.description||t_(e)}const Kg=[{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 aW(e){return Kg.filter(t=>t.id!=="goal"||e==="codex")}function r_(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 g7(e,t){return aW(e).filter(n=>r_(n,t))}const rW=new Set(Kg.map(e=>e.id));function v7(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function sW(e){return[e.id,e.command,e.label,e.description].join(" ")}function oW(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function iW(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return rW.has(n)?{command:n,args:t[2]?.trim()??""}:null}function cW(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function b7({commands:e=Kg,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const r=e.filter(c=>c.id.startsWith(a));if(r.length>0)return r.slice(0,n);const s=e.filter(c=>sW(c).toLowerCase().includes(a));return(s.length>0?s:e.filter(c=>oW(c).toLowerCase().includes(a))).slice(0,n)}function y7(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function Au(e){return e?.role==="owner"||e?.role==="admin"}function S7(e){const t=Eu(e.organizations,e.defaultTeamId),n=Au(t),a=e.localProject??null;if(!a)return lW("Open a local project to set up an Agent.");const r=dW(a,e.projects),s=uW(a,r,e.agents),i=!!a.sandboxTemplate?.detected,c=t&&!n?"Ask an owner or admin to connect this project.":null;return i?r?mW(a,r)?ed({state:"needs_sync",actionLabel:"Sync Project",project:r,agent:s,canManage:n,actionBlockedReason:c}):s?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:r,agent:s}:ed({state:"needs_agent",actionLabel:"Create Agent",project:r,agent:null,canManage:n,actionBlockedReason:c}):ed({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:c}):ed({state:"missing_config",actionLabel:"Add Agent config",project:r,agent:s,canManage:n,actionBlockedReason:c})}function ed(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 lW(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function Eu(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(r=>r.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 dW(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function uW(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const r=n.find(s=>s.id===a&&s.projectId===t.id);if(r)return r}return n.find(r=>r.projectId===t.id)??null}function mW(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 Ns=e=>e.slice(0,2e4);function pW({model:e,provider:t,providerSettings:n}){return{model:_g(t,e,n),modelRef:Da(t,e,n)}}function fW(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function hW(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 gW(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 i0({action:e,prompt:t,runPayload:n,sessionId:a}){const r=new Date().toISOString(),s=`openpond_action_${n.run.id}`,i=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${s}_user`,sessionId:a,turnId:s,name:"turn.started",timestamp:r,source:"chat_action",args:{prompt:t}},{id:`${s}_result`,sessionId:a,turnId:s,name:"workspace_action_result",timestamp:n.run.updatedAt??r,source:"chat_action",action:"sandbox_run_action",appId:null,status:i,output:i==="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 vW({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:r,draftModel:s,draftProvider:i,experience:c,expandProject:d,ensureCloudSessionReady:l,getPrompt:p,bootstrap:f,chatMessages:S,apps:b,connectedAppMentions:I,mentionedAppId:C,refreshWorkspace:P,refreshWorkspaceDiff:_,selectedApp:M,selectedActionCatalog:A,openPondActionCatalog:T,cloudProjects:y,accountScopeKey:w,selectedCloudProject:R,selectedProject:O,selectedProjectLinkedOpenPondApp:z,selectedSession:$,workspaceTarget:V,subagentDelegationMode:Y,setDraftModel:re,setDraftProvider:ee,setError:H,setPrompt:F,setMentionedAppId:J,setCodexHistoryEvents:K,setCodexHistorySessions:B,onCodexHistoryTurnActivityChange:ne,onCodexHistoryTurnPayload:G,onPendingUserMessage:te,setEvents:oe,setSelectedAppId:be,setSelectedProjectId:me,setSelectedSessionId:Re,setSessions:Q,setView:xe,setWorkspaceBusy:je}){function De(pe){Z.bootstrap(pe).then(e).catch(fe=>{console.warn("[chat] Message was accepted, but the post-send bootstrap refresh failed.",fe);const Fe=fe instanceof Error?fe.message:String(fe);H(`Message sent, but the chat list could not refresh: ${Fe}`)})}const He=h.useRef(new Set),Ie=f?.providers??null;function Me(pe,fe){return pe==="codex"?void 0:fe}function Te(pe){return!!(pe&&pe.provider!=="codex"&&(pe.workspaceKind==="local_project"&&pe.cwd?.trim()||(pe.workspaceKind==="sandbox"||pe.workspaceKind==="sandbox_template"||pe.workspaceKind==="sandbox_app")&&pe.workspaceId))}function N(pe){ee(pe),re(fe=>Ss(pe,fe,Ie)),xe("chat")}async function q(pe,fe){return(L1(fe,w)??await zg({teamId:fe,accountKey:w,fetchAgents:async Ne=>(await Z.listSandboxAgents(t,{teamId:Ne})).agents})).find(Ne=>Ne.projectId===pe)??null}async function X(){if(!t)throw new Error("OpenPond App server is not connected.");if(f?.account.state!=="signed_in")throw new Error("Add an OpenPond account before syncing a Project to Cloud.");const pe=await Z.organizations(t),fe=Eu(pe.organizations.map(_u).filter(Fe=>!!Fe).filter(Fe=>Fe.status==="active"),f?.preferences.defaultTeamId??null);if(!fe)throw new Error("Add an OpenPond account before syncing a Project to Cloud.");if(!Au(fe))throw new Error(`You need owner or admin access to create projects in ${fe.displayName}.`);return fe}async function U(pe){if(!t)return!1;const fe=O;if(!fe)throw new Error("Select a local Project before using /sync-cloud.");const Fe=await X(),Pe=fe.linkedSandboxProject?.defaultBranch?.trim()||"main",Ne=ct("local",fe.id),ot=Ra(fe,y),ut=await Z.createSession(t,{provider:"openpond",modelRef:Da("openpond",oi,Ie),openPondCommandAccessMode:Me("openpond",r),appId:null,appName:null,workspaceKind:"local_project",workspaceId:fe.id,workspaceName:fe.name,localProjectId:fe.id,cloudProjectId:ot?.id??null,cloudTeamId:ot?.teamId??null,cwd:fe.workspacePath,title:`Sync ${fe.name} to Cloud`});Q(At=>[ut,...At]),pe.onSessionCreated?.(ut),pe.selectSession&&(Re(ut.id),me(Ne),be(null),xe("chat"),d(Ne)),pe.clearPromptForTurn(),je(!0);try{const At=await Z.uploadLocalProjectCloudSource(t,fe.id,{teamId:Fe.teamId,projectName:fe.name,branch:Pe,chatSessionId:ut.id,displayPrompt:pe.displayPrompt});return e(At.bootstrap),d(Ne),d(ct("cloud",At.project.id)),!0}catch(At){const mt=await Z.bootstrap(t).catch(()=>null);throw mt&&e(mt),At}finally{je(!1)}}async function ae(pe){if(!t||pe.providerForTurn==="codex"||pe.selectedSessionForTurn?.provider==="codex")return!1;let fe=Te(pe.selectedSessionForTurn)?pe.selectedSessionForTurn:null;if(!fe&&pe.selectedSessionForTurn)throw new Error("Select a project to use this.");if(!fe)if(R){const Pe=ct("cloud",R.id),Ne=pe.providerForTurn;fe=await Z.createSession(t,{provider:Ne,modelRef:Da(Ne,pe.modelForTurnValue,Ie),openPondCommandAccessMode:Me(Ne,pe.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:R.id,workspaceName:R.name,localProjectId:null,cloudProjectId:R.id,cloudTeamId:R.teamId,cwd:null,autoTitlePrompt:Ns(pe.command)}),Q(ot=>[fe,...ot]),pe.onSessionCreated?.(fe),pe.selectSession&&(Re(fe.id),me(Pe),be(null),xe("chat"),d(Pe))}else{const Pe=O;if(!Pe)throw new Error("Select a project to use this.");const Ne=Ra(Pe,y),ot=ct("local",Pe.id),ut=pe.providerForTurn;fe=await Z.createSession(t,{provider:ut,modelRef:Da(ut,pe.modelForTurnValue,Ie),openPondCommandAccessMode:Me(ut,pe.openPondCommandAccessModeForTurn),appId:null,appName:null,workspaceKind:"local_project",workspaceId:Pe.id,workspaceName:Pe.name,localProjectId:Pe.id,cloudProjectId:Ne?.id??null,cloudTeamId:Ne?.teamId??null,cwd:Pe.workspacePath,autoTitlePrompt:Ns(pe.command)}),Q(At=>[fe,...At]),pe.onSessionCreated?.(fe),pe.selectSession&&(Re(fe.id),me(ot),be(null),xe("chat"),d(ot))}if(!fe)throw new Error("Select a project to use this.");pe.clearPromptForTurn();const Fe=await Z.runSessionCommand(t,fe.id,{command:pe.command,cwd:fe.cwd});return Q(Pe=>cc(Pe,Fe.session)),oe(Pe=>Dr(Pe,Fe.events)),!0}async function de(pe=[],fe=null,Fe,Pe={}){const Ne=Fe??p();let ot=Ne.trim()||(pe.length>0?"Please review the attached files.":"");if(!t||!ot)return!1;const ut=Pe.displayPrompt?.trim()||ot,At=Pe.provider??i,mt=Pe.model??s,at=Pe.openPondCommandAccessMode??r,Ct=Pe.session!==void 0,Be=Ct?Pe.session??null:$,Et=Pe.experience??Be?.experience??c,dn=Et==="development"||Et==="work"&&(Be?.workspaceKind==="local_project"||!!Be?.localProjectId||!!Be?.cloudProjectId||!Ct&&!!(O||R||M||V==="hybrid"||V==="local")),jn=Ct||!dn?null:M,kt=Ct||!dn?null:O,kr=Ct||!dn?null:R,un=Ct||!dn?null:z,yn=!Ct&&dn&&V==="hybrid",Ut=Pe.selectSession??!0,Rn=Pe.chatMessages??S,Sn=Pe.session!==void 0?null:C,Pn=Pe.clearPrompt===void 0?()=>{F(""),J(null)}:Pe.clearPrompt,Mn=fe?null:nW(ot,A),qt=fe??Mn?.action??null,gt=Mn?.prompt||ot,qn=dn&&!qt?cW(ot):null,mn=qt||qn?null:iW(ot),pt=mn&&!r_({id:mn.command},Et)?mn:null,_t=Pe.usageAttribution??(mn?{surface:"chat",workflowKind:"slash_command",commandName:`/${mn.command}`,commandSource:"prompt_parse"}:void 0);H(null);let Ot=null,pn=!1,oa=null;try{if(!dn&&At==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(pt)throw new Error(`/${pt.command} isn't available in ${Et}.`);if(qn&&At!=="codex"&&Be?.provider!=="codex"){if(pe.length>0)throw new Error("Direct commands do not accept attachments.");return await ae({command:qn.command,clearPromptForTurn:Pn,modelForTurnValue:mt,onSessionCreated:Pe.onSessionCreated,openPondCommandAccessModeForTurn:at,providerForTurn:At,selectedSessionForTurn:Be,selectSession:Ut})}if(!Ct&&mn?.command==="sync-cloud")return await U({clearPromptForTurn:Pn,displayPrompt:ut,onSessionCreated:Pe.onSessionCreated,selectSession:Ut});if(qt){const lt=kK(qt);if(lt){let D=Be;if(!D||D.cloudProjectId!==lt.projectId){D=await Z.createSession(t,{provider:"openpond",modelRef:Da("openpond",mt,Ie),openPondCommandAccessMode:Me("openpond",at),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:lt.projectId,workspaceName:lt.projectName??lt.agentName,localProjectId:null,cloudProjectId:lt.projectId,cloudTeamId:lt.teamId,cwd:null,autoTitlePrompt:Ns(ut)}),Q(ga=>[D,...ga]),Pe.onSessionCreated?.(D),Ut&&Re(D.id);const Je=ct("cloud",lt.projectId);Ut&&me(Je),Ut&&d(Je)}const we=await Z.runSandboxAgent(t,lt.agentId,RK({agent:lt,attachments:pe,displayPrompt:ut,prompt:gt})),le=await Z.bootstrap(t);return e(le),Pn(),oe(Je=>Dr(Je,i0({action:qt,prompt:ut,runPayload:we,sessionId:D.id}))),!0}const rn=Bg(qt);if(rn){let D=Be;(!D||D.provider!=="openpond")&&(D=await Z.createSession(t,{provider:"openpond",modelRef:Da("openpond",mt,Ie),openPondCommandAccessMode:Me("openpond",at),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:Ns(ut)}),Q(le=>[D,...le]),Pe.onSessionCreated?.(D),Ut&&Re(D.id)),await Z.runProfileAction(t,_K({action:rn,attachments:pe,displayPrompt:ut,prompt:gt,sessionId:D.id}));const we=await Z.bootstrap(t);return e(we),Pn(),!0}const Ke=F1({cloudProjects:y,selectedCloudProject:R,selectedProject:O});if(!Ke)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let St=Be;(!St||St.cloudProjectId!==Ke.id)&&(St=await Z.createSession(t,{provider:"openpond",modelRef:Da("openpond",mt,Ie),openPondCommandAccessMode:Me("openpond",at),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:Ke.id,workspaceName:Ke.name,localProjectId:Ke.localProjectId,cloudProjectId:Ke.id,cloudTeamId:Ke.teamId,cwd:null,autoTitlePrompt:Ns(ut)}),Q(D=>[St,...D]),Pe.onSessionCreated?.(St),Ut&&(Re(St.id),me(Ke.selectionKey),d(Ke.selectionKey)));const en=await q(Ke.id,Ke.teamId);if(!en)throw new Error("No OpenPond Agent is available for this Project.");Pn();const zn=await Z.runSandboxAgent(t,en.id,CK({action:qt,attachments:pe,displayPrompt:ut,prompt:gt,teamId:Ke.teamId})),xn=await Z.bootstrap(t);return e(xn),oe(D=>Dr(D,i0({action:qt,prompt:ut,runPayload:zn,sessionId:St.id}))),!0}let Ze=Be;if(Ze&&Gt(Ze.id)){oa=by({afterMessageId:Rn.at(-1)?.id??null,attachments:pe,content:ot,sessionId:Ze.id}),Pn(),Ot=Ze.id,He.current.add(Ot),te?.(oa),ne?.(Ot,!0);const lt=hW(Ze.id,ot),rn=St=>{(!Ct||$?.id===Ze.id)&&K(en=>fW(en,St)),Pe.onCodexHistoryOptimisticEvent?.(St)};rn(lt),B(St=>St.map(en=>en.id===Ze.id?{...en,status:"active"}:en));const Ke=await Z.sendCodexHistoryTurn(t,Ze.id,{prompt:ot,attachments:pe.length>0?pe:void 0,model:_g("codex",mt,Ie),modelRef:Da("codex",mt,Ie),...Pb(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(St=>{throw rn(gW(lt,St)),St});return(!Ct||$?.id===Ze.id)&&K(St=>Dr(St,Ke.events)),B(St=>cc(St,Ke.session)),G?.(Ke),De(t),!0}const Za=(Sn?b.find(lt=>lt.id===Sn&&d5(Ne,lt)&<.sandbox)??null:null)??u5(Ne,i1(b)),Ea=Et==="chat"?[]:C5(Ne,I).map(lt=>lt.ref);if(!Ze){const lt=un?.appId??jn?.id??null,rn=un?.appName??jn?.name??null,Ke=kr,St=Ct?null:Ra(kt,y),en=yn?t1({cloudProjects:y,selectedCloudProject:Ke,selectedProject:kt}):null;if(en?.kind==="missing_cloud_project")throw new Error(en.message);const zn=en?.kind==="ready",xn=zn?At:Ke?"openpond":At,D=Da(xn,mt,Ie),we=Me(xn,at),le=zn?n1({modelRef:D,provider:xn,target:en,title:ot.slice(0,64)}):null;Ze=await Z.createSession(t,le?{...le,subagentDelegationMode:Y,metadata:{...le.metadata,...Pe.sessionMetadata??{}},...we?{openPondCommandAccessMode:we}:{},autoTitlePrompt:Ns(ot)}:{experience:Et,provider:xn,modelRef:D,subagentDelegationMode:Y,...we?{openPondCommandAccessMode:we}:{},appId:lt,appName:rn,workspaceKind:Ke?"sandbox":kt?"local_project":jn?"sandbox_app":void 0,workspaceId:kt?.id??(jn?lt:void 0),workspaceName:Ke?.name??kt?.name??rn,localProjectId:kt?.id??null,cloudProjectId:Ke?.id??St?.id??null,cloudTeamId:Ke?.teamId??St?.teamId??null,...!Ke&&!kt&&!jn&&V==="local"?{metadata:{...BF(),...Pe.sessionMetadata??{}}}:{cwd:kt?kt.workspacePath:null,...Pe.sessionMetadata?{metadata:Pe.sessionMetadata}:{}},autoTitlePrompt:Ns(ot)}),Q(Je=>[Ze,...Je]),Pe.onSessionCreated?.(Ze),Ut&&(Re(Ze.id),Ke&&me(ct("cloud",Ke.id)),Ze.workspaceKind==="local_project"&&Ze.workspaceId&&d(ct("local",Ze.workspaceId)),Ke&&d(ct("cloud",Ke.id)))}if(c0(Ze)&&Sr(Ze.workspaceKind)&&Ze.provider!=="openpond"&&!xr(Ze))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(c0(Ze)&&Sr(Ze.workspaceKind)&&l)try{Ze=await l(Ze)}catch(lt){const rn=lt instanceof Error?lt.message:String(lt);throw await Z.recordPreflightTurnFailure(t,Ze.id,{prompt:ot,error:rn,target:xr(Ze)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),lt}oa=by({afterMessageId:Rn.at(-1)?.id??null,attachments:pe,content:ot,sessionId:Ze.id}),Pn(),Ot=Ze.id,He.current.add(Ot),te?.(oa),Q(lt=>lt.map(rn=>rn.id===Ot?{...rn,status:"active"}:rn));const Ln=At,An=pW({provider:Ln,model:mt,providerSettings:Ie}),Ja=Sq(Ln,An.model??mt,Ie),wr=Ln==="codex"?Pb(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await Z.sendTurn(t,Ze.id,{prompt:ot,metadata:Pe.turnMetadata,attachments:pe.length>0?pe:void 0,mentionedAppIds:Za?[Za.id]:void 0,mentionedConnectedApps:Ea.length>0?Ea:void 0,openPondActionCatalog:T.length>0?T:void 0,usageAttribution:_t,...An,...wr,codexPermissionMode:Ln==="codex"?n:"default",codexReasoningEffort:Ja?yq(Ln,An.model??mt,a,Ie):void 0}),pn=!0,De(t);const ja=Ze.workspaceId??Ze.appId;return ja&&Ze.workspaceKind!=="sandbox"&&Ze.workspaceKind!=="sandbox_template"&&P(ja,!1).then(lt=>{lt?.initialized&&_(ja)}),!0}catch(Ze){return H(Ze instanceof Error?Ze.message:String(Ze)),!1}finally{Ot&&He.current.delete(Ot),Ot&&Gt(Ot)&&ne?.(Ot,!1),Ot&&(Gt(Ot)?B(Ze=>Ze.map(Tn=>Tn.id===Ot&&Tn.status==="active"?{...Tn,status:"idle"}:Tn)):pn||Q(Ze=>Ze.map(Tn=>Tn.id===Ot&&Tn.status==="active"?{...Tn,status:"idle"}:Tn)))}}async function ye(pe,fe){const Fe=He.current.values().next().value??null,Pe=pe??$?.id??Fe;if(!t||!Pe)return!1;if(H(null),Gt(Pe))try{const Ne=await Z.interruptCodexHistoryTurn(t,Pe);if(!Ne.interrupted){if(Ne.reason==="no_active_openpond_turn"){const ut=await Z.codexHistoryThread(t,Pe,{tail:!0}),At={...ut.session,status:"idle"};return $?.id===Pe&&K(mt=>Dr(mt,ut.events)),B(mt=>cc(mt,At)),H("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 H("This Codex history turn is still starting. Try stopping it again in a moment."),!1}const ot=await Z.codexHistoryThread(t,Pe,{tail:!0});return $?.id===Pe&&K(ut=>Dr(ut,ot.events)),B(ut=>cc(ut,ot.session)),!0}catch(Ne){const ot=Ne instanceof Error?Ne.message:String(Ne);return H(ot==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":ot),!1}try{await Z.interruptTurn(t,Pe,fe);const Ne=await Z.bootstrap(t);return e(Ne),!0}catch(Ne){return H(Ne instanceof Error?Ne.message:String(Ne)),!1}}async function Oe(pe,fe){if(!t){H("OpenPond App server is not connected.");return}H(null),await Z.applyCreateImproveAction(t,pe.id,{...fe,runId:pe.id,expectedRevision:pe.revision,actionId:`web:${fe.type}:${crypto.randomUUID()}`});const Fe=await Z.bootstrap(t);e(Fe)}async function $e(pe){await Oe(pe.run,{type:"approve_plan"})}async function Ge(pe){await Oe(pe.run,{type:"cancel",reason:null})}async function yt(pe,fe){await Oe(pe.run,{type:"revise_plan",revision:fe})}async function Se(pe,fe,Fe){await Oe(pe.run,{type:"answer_question",questionId:fe,value:Fe})}async function Le(pe){await Oe(pe.run,{type:"pause"})}async function Ae(pe){await Oe(pe.run,{type:"resume"})}async function qe(pe,fe){await Oe(pe.run,{type:"open_pull_request",candidateId:fe})}async function Ue(pe,fe){await Oe(pe.run,{type:"apply_candidate",candidateId:fe})}async function bn(pe,fe){await Oe(pe.run,{type:"reject_candidate",candidateId:fe,reason:null})}async function Mt(pe,fe){await Oe(pe.run,{type:"reconcile_pull_request",candidateId:fe})}return{answerCreateImproveQuestion:Se,approveCreateImproveRun:$e,applyCreateImproveCandidate:Ue,cancelCreateImproveRun:Ge,changeDraftProvider:N,openCreateImprovePullRequest:qe,pauseCreateImproveRun:Le,reconcileCreateImprovePullRequest:Mt,rejectCreateImproveCandidate:bn,resumeCreateImproveRun:Ae,reviseCreateImproveRun:yt,sendPrompt:de,stopTurn:ye}}function c0(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function bW({branch:e,connection:t,session:n}){if(!Sr(n.workspaceKind))return{sandbox:null,session:n,status:"already_running"};const a=await Z.ensureCloudWorkspaceReady(t,n.id,{branch:e,surface:"desktop"});return{bootstrap:await Z.bootstrap(t),output:a.output,sandbox:null,session:a.session,status:a.status}}function yW(e){return xr(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function SW(e,t){if(e==="already_running")return null;const n=xr(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 xW(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function kW({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:r,selectedProject:s,setWorkspaceBusy:i,showToast:c,visibleWorkspaceState:d}){return h.useCallback(async l=>{if(!n)throw new Error("OpenPond App server is not connected.");const p=s??(l.localProjectId?a.get(l.localProjectId)??null:null);if(l.cloudProjectId&&l.cloudTeamId&&!xW(l,t))throw new Error("This Cloud session belongs to a different OpenPond account. Sync or select a Project in the current account.");l.workspaceId||c(yW(l),"info"),i(!0);try{const f=await bW({branch:s?.linkedSandboxProject?.defaultBranch??r?.defaultBranch??d?.currentBranch??null,connection:n,localProject:p,session:l,source:xr(l)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});f.bootstrap&&e(f.bootstrap);const S=SW(f.status,l);return S&&c(S,"success"),f.session}finally{i(!1)}},[e,t,n,a,r,s,i,c,d?.currentBranch])}function wW(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function IW(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function l0(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function _W(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 r=t.rightChatPanels[a];return!!(r&&n.id===r.id&&n.activationVersion===r.activationVersion&&n.sessionId===r.sessionId&&n.prompt===r.prompt&&n.provider===r.provider&&n.model===r.model&&n.scrollTop===r.scrollTop&&n.stickyToBottom===r.stickyToBottom)})}function CW(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function RW(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:r,rightPanelMode:s,selectedAppId:i,selectedCloudProject:c,selectedProjectId:d,selectedSession:l,selectedSessionId:p,setWorkspaceDiffPanelViewState:f,view:S,viewWorkspaceAppId:b,viewWorkspaceId:I,viewWorkspaceKind:C,workspaceDiffPanelViewState:P}=e,_=h.useRef(new Map),M=h.useRef(new Map),A=h.useRef(null),T=h.useRef(null),y=p??`draft:${d??i??c?.id??"general"}`,w=h.useMemo(()=>I?`${C??"workspace"}:${I}`:b?`app:${b}`:l?.cwd&&!Sr(l.workspaceKind)?`cwd:${l.cwd}`:"none",[l?.cwd,l?.workspaceKind,S,b,I,C]),R=CW({conversationId:y,workspaceSourceKey:w}),O=h.useMemo(()=>IW({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:r,rightPanelMode:s}),[n,a,r,s]);h.useEffect(()=>{const $=A.current;$&&_.current.set($,l0(O))},[y,O]),h.useEffect(()=>{if(A.current===y)return;A.current=y;const V=_.current.get(y)??wW();_W(O,V)||t({type:"patch",patch:l0(V)})},[y,O]),h.useEffect(()=>{const $=T.current;$&&M.current.set($,bp(P))},[R,P]),h.useEffect(()=>{if(T.current===R)return;T.current=R;const V=M.current.get(R)??a1();f(Y=>oy(Y,V)?Y:bp(V))},[R]);const z=h.useCallback($=>{f(V=>oy(V,$)?V:bp($))},[]);return{browserConversationId:y,handleWorkspaceDiffPanelViewStateChange:z}}function PW({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:r,appDispatch:s,applyBootstrapPayload:i,busy:c,cloudSetupDialog:d,cloudProjects:l,connection:p,defaultTeamId:f,expandProject:S,localProjectById:b,selectedCloudProject:I,selectedProject:C,selectedSession:P,selectedSessionProjectId:_,setCloudSetupDialog:M,setDiffPanelOpen:A,setError:T,setSessions:y,setWorkspaceBusy:w,showToast:R,visibleWorkspaceState:O,workspaceBusy:z}){const $=e?.baseUrl??e?.activeProfile?.baseUrl??null,V=h.useCallback(async(F,J)=>{if(p)try{const K=await Z.previewLocalProjectCloudSource(p,F.id,{branch:J});M(B=>!B||B.status!=="confirm"||B.localProjectId!==F.id||B.branch!==J?B:{...B,branch:K.preview.branch,cloudProjectId:K.preview.targetProjectId,preview:K.preview,previewLoading:!1,previewError:null})}catch(K){const B=K instanceof Error?K.message:String(K);M(ne=>!ne||ne.status!=="confirm"||ne.localProjectId!==F.id||ne.branch!==J?ne:{...ne,preview:null,previewLoading:!1,previewError:B})}},[p,M]),Y=h.useCallback(async()=>{const F=d;if(!F||F.status==="uploading")return;if(F.projectKind==="cloud"){M(ne=>ne&&{...ne,status:"ready",error:null});return}if(!p){M(ne=>ne&&{...ne,status:"error",error:"OpenPond App server is not connected."});return}const J=F.localProjectId??"",K=b.get(J);if(!K){M(ne=>ne&&{...ne,status:"error",error:"Project is no longer available."});return}w(!0);const B=Ra(K,l);M(ne=>ne&&{...ne,status:"uploading",error:null,previewLoading:!1});try{const ne=await Z.organizations(p),G=Eu(ne.organizations.map(_u).filter(xe=>!!xe).filter(xe=>xe.status==="active"),f);if(!G)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!Au(G))throw new Error(`You need owner or admin access to create projects in ${G.displayName}.`);const te=F.branch||K.linkedSandboxProject?.defaultBranch||"main",oe=ct("local",K.id),be=await Z.createSession(p,{provider:"openpond",appId:null,appName:null,workspaceKind:"local_project",workspaceId:K.id,workspaceName:K.name,localProjectId:K.id,cloudProjectId:B?.id??null,cloudTeamId:B?.teamId??null,cwd:K.workspacePath,title:`Sync ${K.name} to Cloud`});y(xe=>[be,...xe]),s({type:"selectSession",sessionId:be.id,projectId:oe}),S(oe);const me=await Z.uploadLocalProjectCloudSource(p,K.id,{teamId:G.teamId,projectName:K.name,branch:te,chatSessionId:be.id,displayPrompt:`/sync-cloud ${K.name}`});i(me.bootstrap),S(oe),S(ct("cloud",me.project.id));const Re=Lf({accountBaseUrl:$,teamId:me.project.teamId,projectId:me.project.id,projectName:me.project.name,baseBranch:me.upload.branch,localProjectId:K.id,source:"openpond-app"}),Q=r0({accountBaseUrl:$,organizationSlug:me.project.organizationSlug,projectSlug:me.project.slug});M({status:"ready",localProjectId:K.id,cloudProjectId:me.project.id,teamId:me.project.teamId,projectName:me.project.name,projectKind:"local",projectUrl:Q,setupUrl:Re,branch:me.upload.branch,preview:F.preview??null,previewLoading:!1,previewError:null,upload:{branch:me.upload.branch,headCommit:me.upload.headCommit,fileCount:me.upload.fileCount,byteCount:me.upload.byteCount,skippedCount:me.upload.skippedCount,initializedEmptyProject:me.upload.initializedEmptyProject},error:null}),R("Source uploaded to OpenPond Git. Cloud setup link is ready.","success")}catch(ne){const G=ne instanceof Error?ne.message:String(ne),te=p?await Z.bootstrap(p).catch(()=>null):null;te&&i(te),T(G),M(oe=>oe&&{...oe,status:"error",error:G})}finally{w(!1)}},[$,s,i,d,l,p,f,S,b,M,T,y,w,R]),re=h.useCallback((F,J)=>{if(!p){R("OpenPond App server is not connected.","error");return}if(t){R("Checking OpenPond account. Try again in a moment.","info");return}if(n){R("Add an OpenPond account before using Cloud.","error");return}const K=J||F.linkedSandboxProject?.defaultBranch||"main";M({status:"confirm",localProjectId:F.id,projectName:F.name,projectKind:"local",projectUrl:null,setupUrl:null,branch:K,preview:null,previewLoading:!0,previewError:null,upload:null,error:null}),V(F,K)},[t,n,p,V,M,R]),ee=h.useCallback(async F=>{if(F===r||z||c)return;if(T(null),F==="upload_cloud"){if(!C){R("Select a local Project before uploading source.","error");return}re(C,O?.currentBranch??null);return}if(F==="local"){const B=P?.localProjectId??C?.id??_??null,ne=B?b.get(B)??null:null;if(!ne){R("No linked local workspace for this Cloud chat.","error");return}if(Sr(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const G=ct("local",ne.id);s({type:"selectProject",projectId:G}),S(G),A(!1),R(`Switched to Local: ${ne.name}`,"info");return}if(!p){R("OpenPond App server is not connected.","error");return}if(t){R("Checking OpenPond account. Try again in a moment.","info");return}if(n){R("Add an OpenPond account before using Cloud.","error");return}if(I){M({status:"ready",cloudProjectId:I.id,teamId:I.teamId,projectName:I.name,projectKind:"cloud",projectUrl:r0({accountBaseUrl:$,organizationSlug:I.organizationSlug,projectSlug:I.slug}),setupUrl:Lf({accountBaseUrl:$,teamId:I.teamId,projectId:I.id,projectName:I.name,baseBranch:I.defaultBranch,source:"openpond-app"}),branch:I.defaultBranch??"main",preview:null,previewLoading:!1,previewError:null,upload:null,error:null});return}const J=C;if(!J){R("Select a Project before Cloud coding.","error");return}const K=O?.currentBranch||J.linkedSandboxProject?.defaultBranch||"main";re(J,K)},[$,t,n,a,r,s,c,p,l,S,b,re,I,C,P,_,M,A,T,R,O?.currentBranch,z]),H=h.useCallback(F=>{kg(F)&&re(F.project)},[re]);return{changeWorkspaceTarget:ee,moveProjectToCloud:H,openCloudSetupForLocalProject:re,startCloudSetupUpload:Y}}function TW({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:r,prepareTrainingTurn:s,sendPrompt:i,setMentionedAppId:c,showToast:d}){return h.useCallback(async(l=[],p=null,f,S={})=>{const b=f??n.getSnapshot(),I=s(b);if(I.active&&b.trim()&&!I.metadata)return d(I.error??"Load the selected generated Taskset question before sending, or close the generated-question handoff to write a normal prompt.","error"),!1;const C=await i(l,p,f,{clearPrompt:S.preservePrompt?()=>{}:void 0,displayPrompt:S.displayPrompt,onSessionCreated:P=>{a(P),I.metadata&&t(P.id)},turnMetadata:I.metadata||S.turnMetadata?{...I.metadata??{},...S.turnMetadata??{}}:void 0,sessionMetadata:I.metadata?{trainingTasksetId:I.metadata.trainingTasksetId,trainingTasksetName:I.metadata.trainingTasksetName}:void 0});return C&&await r?.(),C&&I.metadata&&e(),C},[e,t,n,a,r,s,i,c,d])}function AW({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:r,setSessions:s,setView:i}){return h.useCallback(async c=>{if(!t)return;const d=n.find(f=>!f.archived&&f.workspaceKind==="sandbox"&&f.workspaceId===c.sandboxId);if(d){e({type:"selectSession",sessionId:d.id,appId:null,projectId:null}),r("changes"),a(!0),i("chat");return}const l=c.name??`Sandbox ${c.sandboxId.slice(0,8)}`,p=await Z.createSession(t,{provider:"openpond",appId:null,appName:null,workspaceKind:"sandbox",workspaceId:c.sandboxId,workspaceName:l,cwd:null,title:l});s(f=>[p,...f]),e({type:"selectSession",sessionId:p.id,appId:null,projectId:null}),r("changes"),a(!0),i("chat")},[e,t,n,a,r,s,i])}function EW({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:r,applyBootstrapPayload:s,expandProject:i,setExpandedProjectIds:c,setSelectedAppId:d,setSelectedProjectId:l,setSelectedSessionId:p,setError:f,setView:S,showToast:b}){function I(A){const T=ct("local",A.id);d(null),l(T),p(null),S("chat"),i(T)}async function C(A){if(!e)return!1;f(null);try{const T=await Z.createLocalProject(e,A);return s(T.bootstrap),I(T.project),b(T.created===!1?`Opened ${T.project.name}`:`Created ${T.project.name}`,"success"),!0}catch(T){const y=T instanceof Error?T.message:String(T);return f(y),b(y,"error"),!1}}async function P(A){if(!e)return!1;const T=A.trim();if(!T)return!1;f(null);try{const y=await Z.createLocalProject(e,{createNew:!0,name:T});return s(y.bootstrap),I(y.project),b(`Created ${y.project.name}`,"success"),!0}catch(y){return f(y instanceof Error?y.message:String(y)),b("Project could not be created","error"),!1}}async function _(A){if(!e)return!1;const T=A.trim();if(!T)return!1;f(null);try{const y=await Z.organizations(e),w=Eu(y.organizations.map(_u).filter(V=>!!V).filter(V=>V.status==="active"),t);if(!w)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!Au(w))throw new Error(`You need owner or admin access to create projects in ${w.displayName}.`);const R=`${r1(T)}-${Date.now().toString(36)}`;let O=(await Z.upsertSandboxProject(e,{teamId:w.teamId,name:T,sourceType:"internal_repo",normalizedSourceIdentity:R,internalRepoPath:R,defaultBranch:"main",sourceConfig:{sourceType:"internal_repo",sourceValue:R},metadata:{source:"openpond-app-new-cloud-project"}})).project;O=(await Z.uploadSandboxProjectSource(e,O.id,{teamId:w.teamId,branch:"main",commitMessage:"Initialize cloud project",entries:[{path:"README.md",type:"file",contentsBase64:e5(`# ${T}
|
|
139
|
+
|
|
140
|
+
Created in OpenPond Cloud.
|
|
141
|
+
`)}]})).project;const z=await Z.bootstrap(e);s(z);const $=ct("cloud",O.id);return d(null),l($),p(null),S("chat"),i($),b(`Created Cloud Project: ${O.name}`,"success"),!0}catch(y){const w=y instanceof Error?y.message:String(y);return f(w),b(w,"error"),!1}}async function M(A){if(!e)return;if(mq(A)){const R=`Archive ${A.project.name} in OpenPond Cloud?`;if(!(r?await r({title:"Archive Cloud Project",body:`${A.project.name} will be archived in OpenPond Cloud. Existing task history stays available through Cloud history.`,confirmLabel:"Archive project"}):window.confirm(R)))return;f(null);try{await Z.archiveSandboxProject(e,A.project.id,{teamId:A.project.teamId}),s(await Z.bootstrap(e)),c(z=>{const $=new Set(z);return $.delete(A.id),$}),a===A.id&&(l(null),p(null)),b(`Archived ${A.project.name}`,"success")}catch(z){f(z instanceof Error?z.message:String(z)),b("Cloud Project could not be archived","error")}return}if(!kg(A))return;const T=A.project,y=`Remove ${T.name} from Projects? The folder will not be deleted.`;if(r?await r({title:"Remove Project",body:`${T.name} will be removed from the sidebar. The folder and files on disk will not be deleted.`,confirmLabel:"Remove project"}):window.confirm(y)){f(null);try{const R=await Z.deleteLocalProject(e,T.id);s(R),c(O=>{const z=new Set(O);return z.delete(A.id),z}),a===A.id&&(l(null),p(O=>{const z=n.find($=>$.id===O);return z?.workspaceKind==="local_project"&&z.workspaceId===T.id?null:O})),b(`Removed ${T.name}`,"success")}catch(R){f(R instanceof Error?R.message:String(R)),b("Project could not be removed","error")}}}return{createCloudProjectFromScratch:_,createProjectFromScratch:P,createProjectCollection:C,removeProject:M}}function jW({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:r,createProjectCollection:s,expandProject:i,localProjectById:c,onCreateCloudEnvironment:d,onNewCloudProject:l,onNewLocalProject:p,onUseExistingFolderPath:f,newProjectBusy:S,newProjectMode:b,newProjectName:I,projectTargetValue:C,setDiffPanelOpen:P,setDraftModel:_,setDraftProvider:M,setError:A,setNewProjectBusy:T,setNewProjectDialogOpen:y,setNewProjectName:w,setNewProjectPath:R,showToast:O,workspaceBusy:z}){const $=h.useCallback(Y=>{if(Y===C||t||z)return;if(A(null),Y==="action:new-local-project"){p();return}if(Y==="action:add-local-project"){f();return}if(Y==="action:add-local-project-path"){f();return}if(Y==="action:new-cloud-project"){l();return}if(Y==="action:create-cloud-environment"){d();return}if(Y==="none"){e({type:"selectProject",projectId:null}),P(!1),O("Started a chat without project files.","info");return}const re=Y.indexOf(":"),ee=re>=0?Y.slice(0,re):"",H=re>=0?Y.slice(re+1):"";if(ee==="local"){const F=c.get(H);if(!F){O("Project is no longer available.","error");return}const J=ct("local",F.id);e({type:"selectProject",projectId:J}),i(J),P(!1);return}if(ee==="cloud"){const F=n.get(H);if(!F){O("Cloud Project is no longer available.","error");return}const J=ct("cloud",F.id);e({type:"selectProject",projectId:J}),i(J),M("openpond"),_(K=>Ss("openpond",K)),P(!1)}},[e,t,n,i,c,d,l,p,f,C,P,_,M,A,O,z]),V=h.useCallback(async Y=>{const re=I.trim();if(!S){if(b==="existing-local"?!Y?.name.trim()||!Y.sourceFolders.length:!re)return!1;T(!0);try{const ee=b==="cloud"?await a(re):b==="existing-local"?await s(Y):await r(re);return ee&&(y(!1),w(""),R("")),!!ee}finally{T(!1)}}},[a,r,s,S,b,I,T,y,w,R]);return{changeProjectTarget:$,submitNewProjectDialog:V}}function MW(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 x7(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function OW(e,t){const n=Math.max(0,...e.map(s=>s.activationVersion))+1;let a=!1;const r=e.map(s=>s.id!==t?s:(a=!0,{...s,activationVersion:n}));return a?r:[...e]}function $W(e,t){const n=Math.max(0,...e.map(s=>s.activationVersion))+1;let a=!1;const r=e.map(s=>s.sessionId!==t.sessionId?s:(a=!0,{...s,activationVersion:n,prompt:t.prompt??s.prompt}));return a?r:[...e]}function s_(e){return!!(e.parentSessionId&&e.subagentRunId)}function NW(e){const t=e.sessions.filter(s_);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function DW(e,t){const n=new Set(e.map(r=>r.sessionId).filter(Boolean)),a=t.filter(s_).filter(r=>!n.has(r.id)).map(r=>({id:`right-subagent-${r.id}`,activationVersion:1,sessionId:r.id,prompt:"",provider:r.provider,model:r.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const d0="openpond/openpond",LW="github.issue.write";function zW(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(LW))}function k7(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
|
|
142
|
+
`)}function HW(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${d0}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${d0}, 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:
|
|
143
|
+
${t}`].join(`
|
|
144
|
+
`)}function UW(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(`
|
|
145
|
+
|
|
146
|
+
`),requiresInstructions:!0};case"train":return{kind:"open_training",objective:n||null};case"submit-issue":return{kind:"send_prompt",prompt:HW(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const u0=[];function qW(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:r,rightChatHistoryEvents:s,rightChatPanels:i,runningSessionIds:c,selectedSessionId:d,sidebarSessions:l}=e;return h.useMemo(()=>{const p=new Map(l.map(S=>[S.id,S])),f=BW(t);return i.map(S=>{const b=S.sessionId?p.get(S.sessionId)??null:null,I=Gt(S.sessionId),C=I?(S.sessionId?s[S.sessionId]:void 0)??(S.sessionId===d?n:u0):u0,P=Rf(C,[]),_=S.sessionId?f.get(S.sessionId)??null:null,M=!!(b&&c.has(b.id)),A=I?cF({events:C}):null,T=b?.cwd??null,y=b?.appId??b?.localProjectId??(b?.workspaceKind==="local_project"?b.workspaceId??null:null)??(b?.cwd&&!Sr(b.workspaceKind)?TS(b.cwd):null),w=S.sessionId?r[S.sessionId]??null:null;return{...S,session:b,title:lF(A,b?.title??"New task"),messages:I?g1(Pu(C),w):[],createImproveRun:A,contextWindowStatus:OI({provider:S.provider,snapshot:JI(P,S.sessionId),preferences:a}),goalRuntime:QI(P,S.sessionId),pendingApproval:_,running:M,workspaceRootPath:T,activeWorkspaceAppId:y,pendingUserMessage:w,runtimeSource:I?"history":"live"}})},[t,n,a,r,s,i,c,d,l])}function BW(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 FW(e){const{applyPayload:t,connection:n,locallyActiveSessionIds:a,panels:r,sessions:s,setError:i}=e,c=h.useMemo(()=>{const p=new Set,f=[];for(const S of r)!Gt(S.sessionId)||!S.sessionId||p.has(S.sessionId)||(p.add(S.sessionId),f.push(S.sessionId));return f.join(`
|
|
147
|
+
`)},[r]),d=h.useMemo(()=>{if(!c)return"";const p=new Set(c.split(`
|
|
148
|
+
`).filter(Boolean));return s.filter(f=>p.has(f.id)&&f.status==="active").map(f=>f.id).join(`
|
|
149
|
+
`)},[c,s]),l=h.useMemo(()=>c?c.split(`
|
|
150
|
+
`).filter(p=>a.has(p)).join(`
|
|
151
|
+
`):"",[a,c]);h.useEffect(()=>{if(!n||!c)return;const p=c.split(`
|
|
152
|
+
`).filter(Boolean),f=new Set(d.split(`
|
|
153
|
+
`).filter(Boolean)),S=new Set(l.split(`
|
|
154
|
+
`).filter(Boolean)),b=p.map(I=>Ng({connection:n,locallyActive:S.has(I),onError:C=>i(C instanceof Error?C.message:String(C)),onPayload:C=>t($g(C,S.has(I))),reportedActive:f.has(I),sessionId:I,surface:"thread"}));return()=>b.forEach(I=>I())},[d,t,n,l,c,i])}const m0=[];function VW(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:r,codexHistoryEvents:s,connectedAppMentions:i,connection:c,contextCompaction:d,openLabTraining:l,locallyActiveCodexHistorySessionIds:p,openPondCommandAccessMode:f,pendingChatUserMessages:S,providerSettings:b,rightChatHistoryEvents:I,rightChatPanels:C,rightPanelMode:P,runtimeIndexes:_,runtimeEventStore:M,runningSessionIds:A,selectedSession:T,selectedSessionId:y,sendPrompt:w,setDiffPanelOpen:R,setError:O,setRightChatHistoryEvents:z,setRightChatPanels:$,setRightPanelMode:V,setRightPanelTabRequest:Y,setView:re,showChangesPanel:ee,showToast:H,sidebarSessions:F,startupReady:J}=e,K=h.useRef(null),B=h.useRef(new Map),ne=h.useRef(new Set);h.useEffect(()=>{if(!c)return;const Ie=C.flatMap(Me=>Me.sessionId&&!Gt(Me.sessionId)?[Me.sessionId]:[]);for(const Me of Ie)Object.hasOwn(I,Me)||ne.current.has(Me)||(ne.current.add(Me),Z.runtimeEventsPage(c,{sessionId:Me,beforeSequence:Number.MAX_SAFE_INTEGER,limit:500}).then(Te=>{const N=Te.events.map(q=>q.event);z(q=>({...q,[Me]:ai(q[Me]??m0,N)}))}).catch(Te=>{O(Te instanceof Error?Te.message:String(Te))}).finally(()=>{ne.current.delete(Me)}))},[c,I,C,O,z]);const G=h.useCallback(Ie=>{Y(Me=>({id:(Me?.id??0)+1,tab:Ie})),ee()},[ee]),te=h.useCallback((Ie=null,Me={})=>{const Te=Ie?.id?C.find(q=>q.sessionId===Ie.id)??null:null;if(Te)return $(q=>$W(q,{sessionId:Ie.id,prompt:Me.prompt})),R(!0),V("chat"),Me.preserveView||re("chat"),Te.id;const N=MW({sessionId:Ie?.id??null,provider:Ie?.provider??n,model:Ie?.modelRef?.modelId??t,prompt:Me.prompt});return $(q=>[...q,N]),R(!0),V("chat"),Me.preserveView||re("chat"),N.id},[t,n,C,R,$,V,re]);h.useEffect(()=>{if(!J)return;const Ie=K.current;if(!Ie){K.current=new Set(F.filter(q=>!!(q.parentSessionId&&q.subagentRunId)).map(q=>q.id));return}const Me=NW({sessions:F,knownSessionIds:Ie});K.current=Me.knownSessionIds;for(const q of Me.newSessions)B.current.set(q.id,q);const Te=T?.parentSessionId??T?.id??null;if(!Te)return;const N=[...B.current.values()].filter(q=>q.parentSessionId===Te);if(N.length!==0){for(const q of N)B.current.delete(q.id);$(q=>DW(q,N)),R(!0),V("chat")}},[T?.id,T?.parentSessionId,R,$,V,F,J]);const oe=h.useCallback(()=>{if(C.length===0){te(null);return}R(!0),V("chat"),re("chat")},[te,C.length,R,V,re]),be=h.useCallback(Ie=>{const Me=C.length<=1&&C.some(N=>N.id===Ie),Te=()=>{$(N=>N.filter(q=>q.id!==Ie))};if(Me&&P==="chat"){if(G("files"),typeof window>"u"){Te();return}window.requestAnimationFrame(Te);return}Te()},[C,P,$,G]),me=h.useCallback((Ie,Me)=>{$(Te=>Te.map(N=>N.id===Ie?{...N,prompt:Me}:N))},[$]),Re=h.useCallback(Ie=>{$(Me=>OW(Me,Ie))},[$]),Q=h.useCallback((Ie,Me)=>{$(Te=>Te.map(N=>N.id===Ie?{...N,...Me}:N))},[$]),xe=h.useCallback((Ie,Me)=>{$(Te=>Te.map(N=>N.id===Ie?{...N,model:Me}:N))},[$]),je=h.useCallback((Ie,Me)=>{$(Te=>Te.map(N=>N.id===Ie?{...N,provider:Me,model:Ss(Me,N.model,b)}:N))},[b,$]);FW({applyPayload:r,connection:c,locallyActiveSessionIds:p,panels:C,sessions:F,setError:O});const De=qW({approvals:a,codexHistoryEvents:s,contextCompaction:d,pendingChatUserMessages:S,rightChatHistoryEvents:I,rightChatPanels:C,runningSessionIds:A,selectedSessionId:y,sidebarSessions:F}),He=h.useCallback(async(Ie,Me=[],Te=null,N=null,q={})=>{const X=C.find(yt=>yt.id===Ie);if(!X)return!1;const U=q.promptOverride??X.prompt,ae=N?UW(N,U):null;if(ae?.kind==="open_training")return Me.length>0?(H("/train uses this chat; add other chats from Models.","error"),!1):(l({objective:ae.objective,sessionId:X.sessionId}),q.preservePrompt||me(Ie,""),!0);if(N&&ae?.kind==="send_prompt"&&ae.requiresInstructions&&!U.trim())return H(`Add instructions after ${N.command}.`,"info"),!1;if(N&&Me.length>0)return H(`${N.command} tasks do not accept attachments yet. Add file context in the task thread.`,"error"),!1;if(N?.id==="submit-issue"&&!zW(i))return H("Connect the GitHub app before using /submit-issue.","error"),!1;const de=X.sessionId?F.find(yt=>yt.id===X.sessionId)??null:null,ye=X.provider==="codex"?f:de?.openPondCommandAccessMode??f,Oe=ae?.kind==="send_prompt"?ae.prompt:U,$e=Gt(X.sessionId)?(X.sessionId?I[X.sessionId]:void 0)??(X.sessionId===y?s:m0):M.getSessionEvents(X.sessionId),Ge=Gt(X.sessionId)&&X.sessionId?yt=>{const Se=X.sessionId;z(Le=>({...Le,[Se]:ai(Le[Se]??$e,[yt])}))}:void 0;return w(Me,Te,Oe,{session:de,selectSession:!1,provider:X.provider,model:X.model,openPondCommandAccessMode:ye,chatMessages:Pu($e),displayPrompt:q.displayPrompt,turnMetadata:q.turnMetadata,usageAttribution:N?.id==="submit-issue"?{surface:"chat",workflowKind:"slash_command",commandName:N.command,commandSource:"composer_selection"}:void 0,onCodexHistoryOptimisticEvent:Ge,clearPrompt:q.preservePrompt?()=>{}:()=>me(Ie,""),onSessionCreated:yt=>{$(Se=>Se.map(Le=>Le.id===Ie?{...Le,sessionId:yt.id,provider:yt.provider,model:yt.modelRef?.modelId??Le.model}:Le))}})},[s,i,I,C,_,M,y,l,f,w,$,re,F,H,me]);return{activateRightChatPanel:Re,closeRightChatPanel:be,openRightChatPanel:te,rightChatPanelViews:De,showRightChatPanel:oe,showRightPanelDiffTab:G,submitRightChatPrompt:He,updateRightChatModel:xe,updateRightChatPrompt:me,updateRightChatProvider:je,updateRightChatScrollState:Q}}function KW(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:r,setCodexHistorySessions:s,setError:i,setSelectedSessionId:c,setSessions:d}=e;async function l(_,M){if(!n)return;const A=t[_]??{},T={...A,...M,archived:M.pinned?!1:M.archived??A.archived};r(y=>({...y,[_]:T}));try{const y=await Z.patchSidebarAppPreference(n,_,M);r(w=>({...w,[_]:y}))}catch(y){i(y instanceof Error?y.message:String(y)),r(w=>({...w,[_]:A}))}}function p(_){l(_.id,{pinned:!_.pinned,archived:!1})}async function f(_,M){if(!n)return;const A=Gt(_.id)?s:d,T={..._,...M};A(y=>y.some(w=>w.id===_.id)?y.map(w=>w.id===_.id?T:w):[T,...y]);try{const y=await Z.patchSession(n,_.id,M);A(w=>w.some(R=>R.id===y.id)?w.map(R=>R.id===y.id?y:R):[y,...w])}catch(y){i(y instanceof Error?y.message:String(y)),A(w=>w.map(R=>R.id===_.id?_:R))}}function S(_){f(_,{pinned:!1,savedForLater:!_.savedForLater,archived:!1})}function b(_){f(_,{pinned:!_.pinned,savedForLater:!1,archived:!1})}function I(_){f(_,{pinned:!1,savedForLater:!1,archived:!0}),a===_.id&&c(null)}function C(_){f(_,{archived:!1})}function P(_,M){const A=M.trim();!A||A===_.title||f(_,{title:A})}return{archiveSession:I,renameSession:P,restoreSession:C,toggleProjectPinned:p,toggleSessionPinned:b,toggleSessionSavedForLater:S}}function WW(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function GW({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:r,commitIncludeUnstaged:s,commitMessage:i,commitNextStep:c,draftModel:d,draftProvider:l,cloudProjects:p,selectedApp:f,selectedProject:S,selectedProjectLinkedOpenPondApp:b,selectedSession:I,sessions:C,title:P,visibleWorkspaceDiff:_,visibleWorkspaceState:M,workspaceBusy:A,workspaceName:T,appDispatch:y,applyBootstrapPayload:w,expandProject:R,refreshWorkspace:O,refreshWorkspaceDiff:z,rememberWorkspaceState:$,setBranchDialogOpen:V,setCommitDialogOpen:Y,setError:re,setSessions:ee,setSettingsSection:H,setSyncingWorkspaceAppId:F,setView:J,setWorkspaceBusy:K,showToast:B}){function ne(){return`${dI(n.defaultBranchPrefix)}${WW(T??P??"new-branch")}`}function G(){return T?`Update ${T}`:(_?.filesChanged??M?.changedFilesCount??0)===1?"Update workspace file":"Update workspace files"}function te(Te="commit"){y({type:"openCommitDialog",nextStep:Te})}function oe(){y({type:"openBranchDialog",branchName:ne()})}function be(){A||V(!1),H("configuration"),J("settings"),Lt({kind:"settings",section:"configuration"})}async function me(Te){if(!(!e||!t)){K(!0),re(null);try{const N=await Z.checkoutWorkspaceBranch(e,t,{branch:Te});$(N),N.initialized&&z(t)}catch(N){re(N instanceof Error?N.message:String(N))}finally{K(!1)}}}async function Re(){if(!e||!t)return;const Te=r.trim();if(Te){K(!0),re(null);try{const N=await Z.createWorkspaceBranch(e,t,{branch:Te});$(N),N.initialized&&z(t),V(!1),B(`Checked out ${Te}`,"success")}catch(N){re(N instanceof Error?N.message:String(N))}finally{K(!1)}}}async function Q(Te){F(Te);const N=a?.apps.find(q=>q.id===Te)?.name??a?.localProjects.find(q=>q.id===Te)?.name??"Workspace";try{const q=await O(Te,!0);q?.initialized&&Te===t&&z(Te),q?.initialized&&!q.error?B(`${N} synced locally`,"success"):q?.error&&B("Workspace sync failed","error")}finally{F(q=>q===Te?null:q)}}async function xe(){t&&await Q(t)}async function je(Te,N,q={}){if(!e)return null;const X=I&&!Gt(I.id)?I:null;if(YW(N,X,q)||X&&ZW(X,S,f))return X;const U=X?await De(X):null;if(U)return U;const ae=JW(C,S,f);if(ae){const $e=ae.workspaceKind==="local_project"&&ae.workspaceId?ct("local",ae.workspaceId):null;return y({type:"selectSession",sessionId:ae.id,appId:ae.appId,projectId:$e}),ae.workspaceKind==="local_project"&&ae.workspaceId&&R(ct("local",ae.workspaceId)),ae}const de=Ra(S,p),ye=await Z.createSession(e,{provider:l,modelRef:Da(l,d,a?.providers??null),appId:b?.appId??f?.id??null,appName:b?.appName??f?.name??null,workspaceKind:S?"local_project":f?"sandbox_app":void 0,workspaceId:S?.id??f?.id??null,workspaceName:S?.name??f?.name??null,localProjectId:S?.id??null,cloudProjectId:de?.id??null,cloudTeamId:de?.teamId??null,cwd:S?S.workspacePath:null,title:Te});ee($e=>[ye,...$e]);const Oe=ye.workspaceKind==="local_project"&&ye.workspaceId?ct("local",ye.workspaceId):null;return y({type:"selectSession",sessionId:ye.id,appId:ye.appId,projectId:Oe}),ye.workspaceKind==="local_project"&&ye.workspaceId&&R(ct("local",ye.workspaceId)),ye}async function De(Te){if(!e||!S||!b?.appId||Gt(Te.id)||Te.workspaceKind==="local_project"||Te.appId!==b.appId)return null;const N=Ra(S,p),q=await Z.patchSession(e,Te.id,{appId:b.appId,appName:b.appName,workspaceKind:"local_project",workspaceId:S.id,workspaceName:S.name,localProjectId:S.id,cloudProjectId:N?.id??null,cloudTeamId:N?.teamId??null,cwd:S.workspacePath});return ee(X=>X.map(U=>U.id===q.id?q:U)),y({type:"selectSession",sessionId:q.id,appId:q.appId,projectId:ct("local",S.id)}),R(ct("local",S.id)),q}async function He(Te,N={}){if(!e)return null;const q=await je(T?`${T} workspace`:"Workspace action",Te,N);if(!q)return null;const X=await Z.workspaceTool(e,q.id,{action:Te,args:N,source:"ui_button"});B(X.output,X.ok?"success":"error"),w(await Z.bootstrap(e));const U=X.appId??QW(q);return U&&(await O(U,!1))?.initialized&&await z(U),X}async function Ie(Te,N={}){if(Te==="git_commit"&&typeof N.message!="string")return te("commit"),null;K(!0),re(null);try{return await He(Te,N)}catch(q){return re(q instanceof Error?q.message:String(q)),null}finally{K(!1)}}async function Me(){const Te=i.trim()||G(),N=c==="commit_publish",q=N&&!!M?.remoteUrl;if(!(q&&!window.confirm("Replace the current origin remote with the new OpenPond repo after committing?"))){K(!0),re(null);try{if(!(await He("git_commit",{message:Te,includeUnstaged:s}))?.ok||c==="commit_push"&&!(await He("git_push",{runChecks:!1}))?.ok||N&&!(await He("publish_openpond_repo",{replaceOrigin:q}))?.ok)return;Y(!1)}catch(X){re(X instanceof Error?X.message:String(X))}finally{K(!1)}}}return{changeWorkspaceBranch:me,openCommitDialog:te,openCreateWorkspaceBranchDialog:oe,openDefaultsSettingsFromBranchDialog:be,runWorkspaceTool:Ie,submitCommitDialog:Me,submitCreateWorkspaceBranch:Re,syncWorkspaceLocally:xe,syncWorkspaceLocallyForApp:Q}}function ZW(e,t,n){return!t&&!n?!0:o_(e,t,n)}function JW(e,t,n){if(!t&&!n)return null;let a=null,r=Number.NEGATIVE_INFINITY;for(const s of e){if(s.archived||!o_(s,t,n))continue;const i=Date.parse(s.updatedAt),c=Number.isFinite(i)?i:0;(!a||c>r)&&(a=s,r=c)}return a}function o_(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function QW(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function YW(e,t,n={}){return(XW(e)||t8(e,n))&&e8(t)}function XW(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function e8(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function t8(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 n8(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const a8=[];function r8(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:r,cloudSetupDialog:s,setCloudSetupDialog:i,setRightPanelTabRequest:c,workspaceDiffPanelViewState:d,setWorkspaceDiffPanelViewState:l,rightChatHistoryEvents:p,setRightChatHistoryEvents:f,locallyActiveCodexHistorySessionIds:S,setCodexHistoryTurnLocallyActive:b,draftSubagentDelegationMode:I,setDraftSubagentDelegationMode:C,confirmProjectAction:P,view:_,selectedAppId:M,selectedProjectId:A,selectedSessionId:T,draftProvider:y,draftModel:w,activeExperience:R,codexPermissionMode:O,codexReasoningEffort:z,openPondCommandAccessMode:$,busy:V,diffPanelOpen:Y,diffPanelExpanded:re,rightPanelMode:ee,rightChatPanels:H,newProjectMode:F,newProjectName:J,newProjectBusy:K,commitMessage:B,commitIncludeUnstaged:ne,commitNextStep:G,branchDialogName:te,setSectionMenuOpen:oe,setView:be,setSelectedAppId:me,setSelectedProjectId:Re,setSelectedSessionId:Q,setPrompt:xe,setDraftProvider:je,setDraftModel:De,setDiffPanelOpen:He,setRightPanelMode:Ie,setRightChatPanels:Me,setSyncingWorkspaceAppId:Te,setSettingsSection:N,setNewProjectDialogOpen:q,setNewProjectMode:X,setNewProjectName:U,setNewProjectPath:ae,setNewProjectBusy:de,setCommitDialogOpen:ye,setBranchDialogOpen:Oe,setError:$e,showToast:Ge,appPreferences:yt,applyBootstrapPayload:Se,approvals:Le,bootstrap:Ae,connection:qe,events:Ue,runtimeEventStore:bn,sessions:Mt,startup:pe,setAppPreferences:fe,setCodexHistorySessions:Fe,setEvents:Pe,setSessions:Ne,cloudProjectById:ot,localProjectById:ut,selectedApp:At,selectedCloudProject:mt,selectedProject:at,selectedProjectLinkedOpenPondApp:Ct,selectedSession:Be,sidebarSessions:Et,runtimeIndexes:dn,connectedAppMentions:jn,codexHistoryEvents:kt,setCodexHistoryEvents:kr,account:un,accountPending:yn,accountSignedOut:Ut,activeModel:Rn,activeProvider:Sn,activeWorkspaceAppId:Pn,activeWorkspaceKind:Mn,activeWorkspaceLocation:qt,appDefaults:gt,selectedSessionProjectId:qn,workspaceName:mn,accountScopeKey:pt,teamChat:_t,communities:Ot,selectedProjectConfirmedCloudProject:pn,activeOpenPondCommandAccessMode:oa,viewWorkspaceAppId:Ze,viewWorkspaceId:Tn,viewWorkspaceKind:Za,openPondActionCatalog:Ea,selectedActionCatalog:Ln,expandProject:An,setExpandedProjectIds:Ja,advanceTrainingModelChatAfterTurn:wr,bindTrainingModelChatSession:ja,prepareTrainingModelChatTurn:lt,chatMessages:rn,pendingChatUserMessages:Ke,recordPendingChatUserMessage:St,runningSessionIds:en,workspaceBusy:zn,visibleWorkspaceState:xn,visibleWorkspaceDiff:D,rememberWorkspaceState:we,refreshWorkspace:le,setWorkspaceBusy:Je,refreshWorkspaceDiffWhenNeeded:ga,setPendingWorkspaceTarget:Bn,pendingSidebarWorkspaceTarget:Ma,setPendingSidebarWorkspaceTarget:kn,projectTarget:ao,workspaceTarget:Ir}=e,On=_==="apps"?"Apps":_==="get-started"?"Walkthroughs":_==="labs"?"Models":_==="scheduled"?"Workflows":_==="outputs"?"Outputs":_==="projects"?"Projects":_==="team"?_t.detail?n8(_t.detail.thread,_t.currentUserId):"Team Chat":_==="community"?Ot.preview?.displayName??"Communities":Be?.title??Qw(R),{browserConversationId:ia,handleWorkspaceDiffPanelViewStateChange:ca}=RW({appDispatch:n,diffPanelExpanded:re,diffPanelOpen:Y,rightChatPanels:H,rightPanelMode:ee,selectedAppId:M,selectedCloudProject:mt,selectedProjectId:A,selectedSession:Be,selectedSessionId:T,setWorkspaceDiffPanelViewState:l,view:_,viewWorkspaceAppId:Ze,viewWorkspaceId:Tn,viewWorkspaceKind:Za,workspaceDiffPanelViewState:d}),_r=h.useCallback(et=>{Lt({kind:"chat",sessionId:et}),Q(et),me(null),Re(null),be("chat")},[me,Re,Q,be]),ks=h.useCallback(()=>{X("existing-local"),U(""),ae(""),q(!0)},[q,X,U,ae]),ws=h.useCallback(()=>{X("local"),U(""),ae(""),q(!0)},[q,X,U,ae]),{createCloudProjectFromScratch:Is,createProjectFromScratch:ft,createProjectCollection:Ii,removeProject:_s}=EW({connection:qe,defaultTeamId:gt.defaultTeamId,sessions:Mt,selectedProjectId:A,confirmProjectAction:P,applyBootstrapPayload:Se,expandProject:An,setExpandedProjectIds:Ja,setSelectedAppId:me,setSelectedProjectId:Re,setSelectedSessionId:Q,setError:$e,setView:be,showToast:Ge}),{changeWorkspaceBranch:_i,openCommitDialog:ro,openCreateWorkspaceBranchDialog:Ci,openDefaultsSettingsFromBranchDialog:Cr,runWorkspaceTool:Ri,submitCommitDialog:so,submitCreateWorkspaceBranch:oo,syncWorkspaceLocally:io}=GW({connection:qe,activeWorkspaceAppId:Pn,appDefaults:gt,bootstrap:Ae,branchDialogName:te,commitIncludeUnstaged:ne,commitMessage:B,commitNextStep:G,draftModel:w,draftProvider:y,cloudProjects:Ae?.cloudProjects??[],selectedApp:At,selectedProject:at,selectedProjectLinkedOpenPondApp:Ct,selectedSession:Be,sessions:Mt,title:On,visibleWorkspaceDiff:D,visibleWorkspaceState:xn,workspaceBusy:zn,workspaceName:mn,appDispatch:n,applyBootstrapPayload:Se,expandProject:An,refreshWorkspace:le,refreshWorkspaceDiff:ga,rememberWorkspaceState:we,setBranchDialogOpen:Oe,setCommitDialogOpen:ye,setError:$e,setSessions:Ne,setSettingsSection:N,setSyncingWorkspaceAppId:Te,setView:be,setWorkspaceBusy:Je,showToast:Ge}),Pi=kW({applyBootstrapPayload:Se,cloudProjects:Ae?.cloudProjects??[],connection:qe,localProjectById:ut,selectedCloudProject:mt,selectedProject:at,setWorkspaceBusy:Je,showToast:Ge,visibleWorkspaceState:xn}),Ti=Ae?.preferences.subagents.delegationMode??"manual",Qa=Be?.subagentDelegationMode??I,Ai=!!(R==="development"&&Ae?.preferences.subagents.enabled&&Sn!=="codex"&&!Gt(T)&&!Be?.subagentRunId),co=h.useCallback(et=>{if(!Be){C(et);return}if(!qe||Gt(Be.id)||Be.subagentRunId)return;const Ft=Be.id,nr=Be.subagentDelegationMode??null;Ne(sn=>sn.map(Hn=>Hn.id===Ft?{...Hn,subagentDelegationMode:et}:Hn)),Z.patchSession(qe,Ft,{subagentDelegationMode:et}).then(sn=>{Ne(Hn=>Hn.map($n=>$n.id===sn.id?sn:$n))}).catch(sn=>{Ne(Hn=>Hn.map($n=>$n.id===Ft?{...$n,subagentDelegationMode:nr}:$n)),$e(sn instanceof Error?sn.message:String(sn))})},[qe,Be,$e,Ne]),Cs=h.useCallback(et=>{f(Ft=>Ft[et.session.id]===et.events?Ft:{...Ft,[et.session.id]:et.events}),Fe(Ft=>Cu(Ft,et.session))},[Fe]),{answerCreateImproveQuestion:Rs,applyCreateImproveCandidate:lo,approveCreateImproveRun:la,cancelCreateImproveRun:Ei,changeDraftProvider:Ps,openCreateImprovePullRequest:Rr,reconcileCreateImprovePullRequest:Gn,rejectCreateImproveCandidate:ji,pauseCreateImproveRun:Mi,resumeCreateImproveRun:wn,reviseCreateImproveRun:Kr,sendPrompt:Zn,stopTurn:Pr}=vW({applyBootstrapPayload:Se,bootstrap:Ae,chatMessages:rn,connection:qe,codexPermissionMode:O,codexReasoningEffort:z,openPondCommandAccessMode:oa,draftModel:w,draftProvider:y,experience:R,expandProject:An,getPrompt:t.getSnapshot,apps:Ae?.apps??[],connectedAppMentions:jn,mentionedAppId:a,ensureCloudSessionReady:Pi,refreshWorkspace:le,refreshWorkspaceDiff:ga,selectedApp:At,selectedActionCatalog:Ln,openPondActionCatalog:Ea,cloudProjects:Ae?.cloudProjects??[],accountScopeKey:pt,selectedCloudProject:mt,selectedProject:at,selectedProjectLinkedOpenPondApp:Ct,selectedSession:Be,sessions:Mt,workspaceTarget:Ir.value,subagentDelegationMode:Be?.subagentDelegationMode??I,setDraftModel:De,setDraftProvider:je,setError:$e,setPrompt:xe,setMentionedAppId:r,setCodexHistoryEvents:kr,setCodexHistorySessions:Fe,onCodexHistoryTurnActivityChange:b,onCodexHistoryTurnPayload:Cs,onPendingUserMessage:St,setEvents:Pe,setSelectedAppId:me,setSelectedProjectId:Re,setSelectedSessionId:Q,setSessions:Ne,setView:be,setWorkspaceBusy:Je}),{archiveSession:Ts,restoreSession:Wr,renameSession:Oi,toggleProjectPinned:uo,toggleSessionPinned:As,toggleSessionSavedForLater:Tr}=KW({appPreferences:yt,connection:qe,selectedSessionId:T,setAppPreferences:fe,setCodexHistorySessions:Fe,setError:$e,setSelectedSessionId:Q,setSessions:Ne}),{changeWorkspaceTarget:Ar,moveProjectToCloud:Es,startCloudSetupUpload:mo}=PW({account:un,accountPending:yn,accountSignedOut:Ut,activeWorkspaceKind:Mn,activeWorkspaceLocation:qt,appDispatch:n,applyBootstrapPayload:Se,busy:V,cloudSetupDialog:s,cloudProjects:Ae?.cloudProjects??[],connection:qe,defaultTeamId:gt.defaultTeamId,expandProject:An,localProjectById:ut,selectedCloudProject:mt,selectedProject:at,selectedSession:Be,selectedSessionProjectId:qn,setCloudSetupDialog:i,setDiffPanelOpen:He,setError:$e,setSessions:Ne,setWorkspaceBusy:Je,showToast:Ge,visibleWorkspaceState:xn,workspaceBusy:zn}),Gr=h.useCallback(async et=>{if(R==="work"&&!Be){if(et==="local"){Bn("local"),Ge(at?`Next task will use the local ${at.name} checkout.`:"Next task will use an app-managed local workspace.","info");return}if(et==="cloud"&&!at&&!mt){if(yn){Ge("Checking OpenPond account. Try again in a moment.","info");return}if(Ut){Ge("Add an OpenPond account before using Hosted.","error");return}Bn("cloud"),Ge("Next task will use Hosted without a Project.","info");return}}if(et==="hybrid"){const Ft=mt?.id??pn?.id??Be?.cloudProjectId??null,nr=mt?.teamId??pn?.teamId??Be?.cloudTeamId??null;if(yn){Ge("Checking OpenPond account. Try again in a moment.","info");return}if(Ut){Ge("Add an OpenPond account before using Hybrid.","error");return}if(!Ft||!nr){Bn(null),Ge("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Be&&!Gt(Be.id)){if(xr(Be))return;if(!qe){Ge("OpenPond App server is not connected.","error");return}const sn=await Z.patchSession(qe,Be.id,{provider:y,modelRef:Da(y,w,Ae?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:mt?.name??pn?.name??at?.name??Be.workspaceName??"Hybrid workspace",localProjectId:at?.id??Be.localProjectId??null,cloudProjectId:Ft,cloudTeamId:nr,metadata:e1(Be.metadata),cwd:at?.workspacePath??Be.cwd??null});Ne(Hn=>Hn.map($n=>$n.id===sn.id?sn:$n)),Bn(null),Ge("Hybrid will use your selected model with hosted sandbox edits.","info");return}Bn("hybrid"),Ge("Next message will use Hybrid with a hosted sandbox.","info");return}Bn(null),await Ar(et)},[yn,Ut,R,Ae?.providers,Ar,qe,w,y,mt?.id,mt?.name,mt?.teamId,at?.id,pn?.id,pn?.name,pn?.teamId,at?.name,at?.workspacePath,Be,Bn,Ne,Ge]),Ya=h.useCallback((et,Ft)=>{me(null),Re(et),Q(null),be("chat"),An(et),kn({projectId:et,target:Ft})},[An,me,Re,Q,be]);h.useEffect(()=>{if(!Ma||_!=="chat"||A!==Ma.projectId||T!==null)return;const et=Ma.target;kn(null),Gr(et)},[Gr,Ma,A,T,_]);const va=TW({advanceTrainingTurn:wr,bindTrainingSession:ja,composerDraftStore:t,onSessionCreated:et=>{Q(et.id),be("chat"),Lt({kind:"chat",sessionId:et.id}),C(null)},onSubmitted:async()=>{const et=Be;if(!(!qe||!et||!$c(et)))try{const Ft=await Z.patchSession(qe,et.id,{metadata:Iq(et.metadata)});Ne(nr=>nr.map(sn=>sn.id===Ft.id?Ft:sn))}catch(Ft){Ge(Ft instanceof Error?`Task started, but its Draft label could not be cleared: ${Ft.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:lt,sendPrompt:Zn,setMentionedAppId:r,showToast:Ge}),po=AW({appDispatch:n,connection:qe,sessions:Mt,setDiffPanelOpen:He,setRightPanelMode:Ie,setSessions:Ne,setView:be}),{createCloudEnvironmentFromSidebar:Zr,openCloudProjectDialog:Xa,openUrlInBrowserPanel:fo,showBrowserPanel:Oa,showChangesPanel:ho,showGoalSidebarTab:$i}=z9({account:un,browserConversationId:ia,cloudProjectById:ot,cloudProjects:Ae?.cloudProjects??[],diffPanelOpen:Y,rightPanelMode:ee,selectedProjectId:A,setDiffPanelOpen:He,setNewProjectDialogOpen:q,setNewProjectMode:X,setNewProjectName:U,setRightPanelMode:Ie}),{changeProjectTarget:go,submitNewProjectDialog:Ni}=jW({appDispatch:n,busy:V,cloudProjectById:ot,createCloudProjectFromScratch:Is,createProjectFromScratch:ft,createProjectCollection:Ii,expandProject:An,localProjectById:ut,newProjectBusy:K,newProjectMode:F,newProjectName:J,onCreateCloudEnvironment:Zr,onNewCloudProject:Xa,onNewLocalProject:ws,onUseExistingFolderPath:ks,projectTargetValue:ao.value,setDiffPanelOpen:He,setDraftModel:De,setDraftProvider:je,setError:$e,setNewProjectBusy:de,setNewProjectDialogOpen:q,setNewProjectName:U,setNewProjectPath:ae,showToast:Ge,workspaceBusy:zn}),vo=h.useMemo(()=>Mt.map(et=>et.id),[Mt]);U9({browserConversationId:ia,sessionIds:vo,onOpenSession:_r,onShowBrowserPanel:Oa});const[bo,yo]=h.useState(null),js=h.useCallback(et=>{yo({id:Date.now(),objective:et.objective,initialSessionIds:et.sessionId?[et.sessionId]:[]}),Fs(wa()),be("labs")},[be]),{activateRightChatPanel:So,closeRightChatPanel:Ms,openRightChatPanel:er,rightChatPanelViews:Di,showRightChatPanel:Li,showRightPanelDiffTab:zi,submitRightChatPrompt:Hi,updateRightChatModel:tr,updateRightChatPrompt:xo,updateRightChatProvider:Ui,updateRightChatScrollState:qi}=VW({activeModel:Rn,activeProvider:Sn,approvals:Le,applyRightCodexHistoryPayload:Cs,codexHistoryEvents:kt,connectedAppMentions:jn,connection:qe,contextCompaction:gt.contextCompaction,openLabTraining:js,locallyActiveCodexHistorySessionIds:S,openPondCommandAccessMode:$,pendingChatUserMessages:Ke,providerSettings:Ae?.providers??null,rightChatHistoryEvents:p,rightChatPanels:H,rightPanelMode:ee,runtimeIndexes:dn,runtimeEventStore:bn,runningSessionIds:en,selectedSession:Be,selectedSessionId:T,sendPrompt:Zn,setDiffPanelOpen:He,setError:$e,setRightChatHistoryEvents:f,setRightChatPanels:Me,setRightPanelMode:Ie,setRightPanelTabRequest:c,setView:be,showChangesPanel:ho,showToast:Ge,sidebarSessions:Et,startupReady:pe.ready}),Bi=h.useCallback(()=>{oe(null),N("profile"),be("settings"),Lt({kind:"settings",section:"profile"})},[oe,N,be]),da=h.useMemo(()=>Dr(Ae?.diagnostics??a8,Ue.filter(et=>et.name==="diagnostic")),[Ae?.diagnostics,Ue]),ko=h.useCallback(()=>{if(Y){He(!1);return}if(_==="labs"){Ie("changes"),c({id:Date.now(),tab:"summary"}),He(!0);return}Ie("home"),He(!0)},[Y,He,Ie,c,_]);return{title:On,browserConversationId:ia,handleWorkspaceDiffPanelViewStateChange:ca,openSessionInChat:_r,openExistingProjectPathDialog:ks,removeProject:_s,changeProjectTarget:go,submitNewProjectDialog:Ni,changeWorkspaceBranch:_i,openCommitDialog:ro,openCreateWorkspaceBranchDialog:Ci,openDefaultsSettingsFromBranchDialog:Cr,runWorkspaceTool:Ri,submitCommitDialog:so,submitCreateWorkspaceBranch:oo,syncWorkspaceLocally:io,subagentDelegationDefaultMode:Ti,subagentDelegationMode:Qa,subagentDelegationAvailable:Ai,changeSubagentDelegationMode:co,answerCreateImproveQuestion:Rs,applyCreateImproveCandidate:lo,approveCreateImproveRun:la,cancelCreateImproveRun:Ei,changeDraftProvider:Ps,openCreateImprovePullRequest:Rr,reconcileCreateImprovePullRequest:Gn,rejectCreateImproveCandidate:ji,pauseCreateImproveRun:Mi,resumeCreateImproveRun:wn,reviseCreateImproveRun:Kr,sendPrompt:Zn,stopTurn:Pr,archiveSession:Ts,restoreSession:Wr,renameSession:Oi,toggleProjectPinned:uo,toggleSessionPinned:As,toggleSessionSavedForLater:Tr,moveProjectToCloud:Es,startCloudSetupUpload:mo,changeWorkspaceTarget:Gr,switchProjectWorkspaceTarget:Ya,sendPromptFromMainComposer:va,openSandboxWorkspace:po,createCloudEnvironmentFromSidebar:Zr,openCloudProjectDialog:Xa,openUrlInBrowserPanel:fo,showBrowserPanel:Oa,showChangesPanel:ho,showGoalSidebarTab:$i,rightChatTrainingLaunchRequest:bo,setRightChatTrainingLaunchRequest:yo,closeRightChatPanel:Ms,openRightChatPanel:er,rightChatPanelViews:Di,showRightChatPanel:Li,showRightPanelDiffTab:zi,submitRightChatPrompt:Hi,activateRightChatPanel:So,updateRightChatModel:tr,updateRightChatPrompt:xo,updateRightChatProvider:Ui,updateRightChatScrollState:qi,openProfileSettings:Bi,diagnosticEvents:da,toggleRightSidebar:ko}}const s8=eC();function o8(){return g.jsx(v_,{client:s8,children:g.jsx(i8,{})})}function i8(){const e=j9(),t=r8(e);return g.jsx(WF,{primary:e,secondary:t})}const w7=Object.freeze(Object.defineProperty({__proto__:null,App:o8},Symbol.toStringTag,{value:"Module"}));export{gG as $,dC as A,yq as B,ms as C,aI as D,ZG as E,Bw as F,TG as G,s6 as H,kb as I,xb as J,og as K,J9 as L,f7 as M,v7 as N,Pg as O,gu as P,t_ as Q,h7 as R,KU as S,wb as T,pi as U,Z as V,no as W,el as X,Sq as Y,hG as Z,k as _,K8 as a,Sr as a$,Gw as a0,bq as a1,oU as a2,d0 as a3,Hs as a4,Kg as a5,Un as a6,p7 as a7,s1 as a8,GG as a9,Kw as aA,JG as aB,df as aC,Dd as aD,S1 as aE,jd as aF,xu as aG,uU as aH,TU as aI,Fw as aJ,b8 as aK,m7 as aL,ZH as aM,lU as aN,sp as aO,W8 as aP,Gt as aQ,ai as aR,g1 as aS,$G as aT,$F as aU,IK as aV,OG as aW,AF as aX,r7 as aY,wK as aZ,Sa as a_,b7 as aa,Zp as ab,Ss as ac,g7 as ad,Sf as ae,yG as af,KG as ag,d5 as ah,k7 as ai,iW as aj,VG as ak,WG as al,s7 as am,t7 as an,BB as ao,Da as ap,cF as aq,Lo as ar,By as as,e7 as at,YG as au,XG as av,s0 as aw,zf as ax,sd as ay,rU as az,j as b,Qe as b$,r_ as b0,zW as b1,HW as b2,N9 as b3,NG as b4,mq as b5,lg as b6,Lw as b7,Su as b8,QG as b9,g8 as bA,RS as bB,SG as bC,fG as bD,ku as bE,Zw as bF,Lt as bG,qU as bH,y1 as bI,ea as bJ,v as bK,x as bL,ve as bM,ke as bN,Dl as bO,AH as bP,S7 as bQ,Eu as bR,vI as bS,xG as bT,Nc as bU,p8 as bV,f8 as bW,kG as bX,fU as bY,wa as bZ,Fs as b_,kg as ba,sq as bb,pG as bc,Jb as bd,Ww as be,LB as bf,Pf as bg,y7 as bh,GF as bi,sy as bj,_u as bk,zB as bl,zg as bm,dI as bn,QH as bo,vG as bp,bG as bq,yE as br,RU as bs,OF as bt,MF as bu,ig as bv,IU as bw,cH as bx,Uw as by,cg as bz,Jh as c,W as c$,rh as c0,dg as c1,zw as c2,Xc as c3,LG as c4,BG as c5,FG as c6,iy as c7,HG as c8,bp as c9,wG as cA,IG as cB,N_ as cC,u8 as cD,d8 as cE,Lc as cF,Hm as cG,bc as cH,z_ as cI,Dn as cJ,Yn as cK,S0 as cL,X_ as cM,h8 as cN,oS as cO,Eh as cP,_8 as cQ,Aa as cR,l$ as cS,Fa as cT,w8 as cU,Ph as cV,au as cW,Ye as cX,Tt as cY,nu as cZ,Ce as c_,qG as ca,UG as cb,zG as cc,oy as cd,DG as ce,Rt as cf,a1 as cg,y8 as ch,lG as ci,bt as cj,st as ck,Id as cl,Th as cm,Ht as cn,kI as co,F4 as cp,s4 as cq,Km as cr,v8 as cs,uB as ct,vq as cu,_G as cv,CG as cw,RG as cx,PG as cy,oq as cz,WD as d,z8 as d$,E as d0,v$ as d1,Zx as d2,Zm as d3,Kx as d4,s$ as d5,$x as d6,VO as d7,c$ as d8,h$ as d9,O8 as dA,Yp as dB,Cn as dC,$8 as dD,G$ as dE,Gs as dF,aE as dG,Ba as dH,D8 as dI,Gc as dJ,r2 as dK,fu as dL,lD as dM,hx as dN,DO as dO,NO as dP,L8 as dQ,Wh as dR,q8 as dS,Xd as dT,U8 as dU,Dx as dV,oD as dW,is as dX,os as dY,Xo as dZ,sS as d_,R8 as da,m$ as db,I$ as dc,se as dd,Bx as de,jx as df,S$ as dg,y$ as dh,g$ as di,Vx as dj,jh as dk,Fx as dl,ru as dm,su as dn,A8 as dp,C8 as dq,k8 as dr,u$ as ds,na as dt,xk as du,pu as dv,mD as dw,m2 as dx,a$ as dy,hn as dz,We as e,oG as e$,MG as e0,mG as e1,YL as e2,lL as e3,Y8 as e4,X8 as e5,uG as e6,N8 as e7,iS as e8,Kh as e9,H8 as eA,nD as eB,AG as eC,EG as eD,I8 as eE,T8 as eF,E8 as eG,P8 as eH,Ha as eI,j8 as eJ,D$ as eK,lu as eL,Vk as eM,V8 as eN,aG as eO,nG as eP,tG as eQ,cG as eR,M8 as eS,ik as eT,SN as eU,e2 as eV,eG as eW,Zz as eX,Yc as eY,rG as eZ,iG as e_,pg as ea,kx as eb,Bl as ec,S8 as ed,gn as ee,yx as ef,PB as eg,Kc as eh,Ih as ei,Wv as ej,x8 as ek,_c as el,Wa as em,qO as en,J8 as eo,gw as ep,Q8 as eq,ok as er,Z8 as es,G8 as et,fc as eu,hw as ev,t$ as ew,_h as ex,jl as ey,Vc as ez,a6 as f,sG as f0,jz as f1,tH as f2,WU as f3,eq as f4,dG as f5,B8 as f6,F8 as f7,wu as f8,n7 as f9,a7 as fa,pk as fb,y2 as fc,vs as fd,ds as fe,Kv as ff,jG as fg,Hw as fh,r0 as fi,$9 as fj,Rf as fk,QI as fl,OI as fm,JI as fn,x7 as fo,c7 as fp,o7 as fq,i7 as fr,ZK as fs,n8 as ft,l7 as fu,d7 as fv,u7 as fw,Ib as fx,w7 as fy,L as g,N3 as h,Pb as i,h0 as j,PI as k,R0 as l,lH as m,m as n,u as o,Oc as p,xc as q,Nd as r,o as s,kU as t,dt as u,ps as v,OH as w,lr as x,yu as y,cI as z};
|