openpond 0.2.53 → 0.2.55
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 +1514 -100
- package/dist/app-server.js +1 -1
- package/dist/chunks/actions-command-WTFZA7LF.js +2 -0
- package/dist/chunks/{app-layer-I7MZYVLL.js → app-layer-Y2UERCPY.js} +1 -1
- package/dist/chunks/app-server-runtime-2RM3N4I6.js +2 -0
- package/dist/chunks/apps-KDNWYO3G.js +2 -0
- package/dist/chunks/chunk-2DFR7PJ4.js +2460 -0
- package/dist/chunks/chunk-4CRM2ADK.js +2 -0
- package/dist/chunks/{chunk-7ZG3IT7C.js → chunk-4WEUCGJ3.js} +6 -6
- package/dist/chunks/chunk-55G6B54U.js +6 -0
- package/dist/chunks/chunk-73G5UYBB.js +12 -0
- package/dist/chunks/{chunk-DALJMSJG.js → chunk-ARQEJOEK.js} +24 -24
- package/dist/chunks/chunk-B7QDZPNX.js +2 -0
- package/dist/chunks/chunk-BFKYRQMA.js +2 -0
- package/dist/chunks/{chunk-AH22RHPS.js → chunk-BQAF5P7K.js} +2 -2
- package/dist/chunks/{chunk-YJ4PNAST.js → chunk-BTI4N7YO.js} +1 -1
- package/dist/chunks/chunk-C6D4WAYN.js +6 -0
- package/dist/chunks/chunk-CGBI2VYJ.js +2 -0
- package/dist/chunks/chunk-DLVPSCTB.js +2 -0
- package/dist/chunks/{chunk-UJ5EFSEC.js → chunk-G6JMQGX7.js} +1 -1
- package/dist/chunks/chunk-GGIG3XU7.js +3 -0
- package/dist/chunks/chunk-IODUCRBA.js +58 -0
- package/dist/chunks/chunk-JIMU3KDA.js +24 -0
- package/dist/chunks/chunk-JUJSA7KI.js +22 -0
- package/dist/chunks/chunk-K5SBVO3B.js +195 -0
- package/dist/chunks/chunk-KD3QVRIJ.js +21 -0
- package/dist/chunks/chunk-KGNCKIFP.js +3 -0
- package/dist/chunks/chunk-L4235TRQ.js +140 -0
- package/dist/chunks/{chunk-N5QNXMIS.js → chunk-MH3LHSGX.js} +1 -1
- package/dist/chunks/chunk-MVF3F5QS.js +2 -0
- package/dist/chunks/{chunk-N3DEA6PG.js → chunk-NNIRIUSY.js} +1 -1
- package/dist/chunks/{chunk-WITSXYEW.js → chunk-NOTXPD2T.js} +1 -1
- package/dist/chunks/{chunk-T5LE6R5S.js → chunk-OSIO7PLX.js} +1 -1
- package/dist/chunks/chunk-OULAKUIN.js +2 -0
- package/dist/chunks/chunk-OWNLDB2O.js +2 -0
- package/dist/chunks/{chunk-NAZ26IZL.js → chunk-Q7AXHFZV.js} +1 -1
- package/dist/chunks/chunk-QDHMP5FS.js +2 -0
- package/dist/chunks/chunk-QKD5OMDI.js +2 -0
- package/dist/chunks/{chunk-YD55Z5H3.js → chunk-QRAKXZOC.js} +10 -10
- package/dist/chunks/{chunk-JDLAHVAJ.js → chunk-R27YGT77.js} +1 -1
- package/dist/chunks/chunk-R2BSIRYL.js +3 -0
- package/dist/chunks/chunk-SHQOIROR.js +42 -0
- package/dist/chunks/chunk-STDMBJOQ.js +9 -0
- package/dist/chunks/chunk-T4QGDQHP.js +4 -0
- package/dist/chunks/{chunk-R3XFY7VL.js → chunk-TERVLCRG.js} +1 -1
- package/dist/chunks/{chunk-PA7XP42P.js → chunk-U2YMBCX7.js} +1 -1
- package/dist/chunks/{chunk-GXSTZBM6.js → chunk-UA5DA5I2.js} +1 -1
- package/dist/chunks/chunk-VJEZPDBS.js +5 -0
- package/dist/chunks/chunk-WDFLCNRC.js +8 -0
- package/dist/chunks/chunk-WZYRAR7X.js +16 -0
- package/dist/chunks/chunk-YDT7L3VZ.js +24 -0
- package/dist/chunks/chunk-YR5ID2SS.js +2 -0
- package/dist/chunks/chunk-YUPBAWBJ.js +554 -0
- package/dist/chunks/cli-465VC2WP.js +2 -0
- package/dist/chunks/{configuration-command-MATM4XR5.js → configuration-command-LAAP2EXT.js} +1 -1
- package/dist/chunks/connected-evidence-XM626247.js +2 -0
- package/dist/chunks/{continual-PKK2BOTB.js → continual-TTGJ6YTR.js} +1 -1
- package/dist/chunks/core-commands-W7EK552V.js +2 -0
- package/dist/chunks/datasets-QJWYTTQL.js +2 -0
- package/dist/chunks/desktop-test-3B2D34NF.js +3 -0
- package/dist/chunks/dist-FAJX2UBW.js +2 -0
- package/dist/chunks/{dist-4HV2W6V4.js → dist-HUAE2KFZ.js} +1 -1
- package/dist/chunks/{chunk-6VF3Q6QJ.js → dist-SKYG5LZO.js} +2 -4
- package/dist/chunks/evaluation-coordination-2MONR4AX.js +2 -0
- package/dist/chunks/experiment-improvements-WVQ5FK46.js +2 -0
- package/dist/chunks/experiments-S5UQ32QB.js +2 -0
- package/dist/chunks/extension-DWMY6D2R.js +4 -0
- package/dist/chunks/{help-WLKSACLZ.js → help-A72QDRNG.js} +1 -1
- package/dist/chunks/hosted-experiment-improvement-2OWOQLHC.js +3 -0
- package/dist/chunks/hosted-harness-runtime-TGFMAV7W.js +2 -0
- package/dist/chunks/hosted-profile-candidate-WQSI6HZO.js +3 -0
- package/dist/chunks/hosted-profile-compiler-Z2A4TEA6.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-control-FKGARUEE.js +2 -0
- package/dist/chunks/hosted-profile-evaluation-inspection-QOY2JKV4.js +3 -0
- package/dist/chunks/hosted-profile-evaluation-preparation-WVP6CALP.js +3 -0
- package/dist/chunks/human-review-TGHQKXFZ.js +2 -0
- package/dist/chunks/{import-V3HUGRHR.js → import-4UE5XNSG.js} +1 -1
- package/dist/chunks/javascript-isolate-process-source-ZPQKKLR4.js +2 -0
- package/dist/chunks/javascript-verifier-worker-source-F3LSGPOY.js +2 -0
- package/dist/chunks/learning-R2XBMMEM.js +2 -0
- package/dist/chunks/opchat-WULL6CUP.js +3 -0
- package/dist/chunks/organizations-I37HISVX.js +2 -0
- package/dist/chunks/profile-NOZ6TVXL.js +3 -0
- package/dist/chunks/project-agent-T6XKC54C.js +2 -0
- package/dist/chunks/sandbox-command-STB47FRY.js +2 -0
- package/dist/chunks/{sandbox-template-BBGGPJMI.js → sandbox-template-LKGBDVJ4.js} +1 -1
- package/dist/chunks/sql-execution-process-source-B4HQM6ZV.js +2 -0
- package/dist/chunks/src-T3KWWCAH.js +322 -0
- package/dist/chunks/{src-CR6UZYTX.js → src-ZWJ5IO7A.js} +1 -1
- package/dist/chunks/{taskset-LUG3ZU6J.js → taskset-RNYDR4GS.js} +1 -1
- package/dist/chunks/{teams-bot-7I4BAUVO.js → teams-bot-H7XT23XB.js} +1 -1
- package/dist/chunks/{training-XHE6FVII.js → training-M6FAPRSJ.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/web/assets/App-CLFfy_Av.js +154 -0
- package/dist/web/assets/App-CTlAPuCY.css +1 -0
- package/dist/web/assets/{AppDialog-BdusXgU0.js → AppDialog-CPHTPqrx.js} +1 -1
- package/dist/web/assets/{AppTerminalPanel-C4uRpnBz.js → AppTerminalPanel-BVj5Tj93.js} +2 -2
- package/dist/web/assets/AppsView-O69zEBY3.js +1 -0
- package/dist/web/assets/{BrowserSidebar-Bl7V6YO2.js → BrowserSidebar-Pr_Kpe8p.js} +1 -1
- package/dist/web/assets/{CartesianChart-BstFbsdn.js → CartesianChart-JPqo6YOf.js} +1 -1
- package/dist/web/assets/{CollaborationTabs-B8YAf0c1.js → CollaborationTabs-CAJcQFn2.js} +1 -1
- package/dist/web/assets/{CommandMenu-DZct7zUJ.js → CommandMenu-B-w53n9A.js} +1 -1
- package/dist/web/assets/{CommunityView-CR0-W-uG.js → CommunityView-DbZKK8_P.js} +1 -1
- package/dist/web/assets/{ComposerCreateImproveStrip-DR-Qo7b4.js → ComposerCreateImproveStrip-3_083PF4.js} +1 -1
- package/dist/web/assets/{GetStartedView-xqQoMMei.js → GetStartedView-D7JGm_6c.js} +1 -1
- package/dist/web/assets/HostedModelLearningReview-DwgMfZ7_.js +1 -0
- package/dist/web/assets/{HostedModelLearningSettings-De3i9wF4.js → HostedModelLearningSettings-JRfQadRl.js} +1 -1
- package/dist/web/assets/{LabModelVersionDetailPage-DAY1MmqP.js → LabModelVersionDetailPage-BUYflJY_.js} +1 -1
- package/dist/web/assets/{LabSkillSidebar-DLnIgnry.js → LabSkillSidebar-BBiqk7Rf.js} +1 -1
- package/dist/web/assets/LabsRoute-Ci6vUnSd.js +99 -0
- package/dist/web/assets/MainChatThread-BQK3oI2N.js +2 -0
- package/dist/web/assets/MainPane-D3ojiN-p.js +18 -0
- package/dist/web/assets/{MarkdownText-gJMuefaJ.js → MarkdownText-DOdOVFXL.js} +25 -25
- package/dist/web/assets/{NativeSkillSidebar-Dlxb8iOC.js → NativeSkillSidebar-CRI_ri8z.js} +1 -1
- package/dist/web/assets/{NewExperienceSwitcher-DM-cqJ-K.js → NewExperienceSwitcher-DhYtfE68.js} +1 -1
- package/dist/web/assets/{NewProjectDialog-Cu1q75gq.js → NewProjectDialog-D8sy1gOz.js} +1 -1
- package/dist/web/assets/{OutputsPage-DiXMkasl.js → OutputsPage-CbWgrhXA.js} +1 -1
- package/dist/web/assets/{ProjectsPage-DqiBHiCB.js → ProjectsPage-DLB67lyA.js} +1 -1
- package/dist/web/assets/RightChatPanelStack-ozSKnDyX.js +1 -0
- package/dist/web/assets/{RightSidebarHomePanel-CeSFJM5s.js → RightSidebarHomePanel-CKs3OwhD.js} +1 -1
- package/dist/web/assets/ScheduledWorkPage-Cafv_QnR.js +1 -0
- package/dist/web/assets/SettingsView-T1vYDPjh.js +5 -0
- package/dist/web/assets/{TeamChatView-DM0adMtj.js → TeamChatView-vIrmXOY_.js} +2 -2
- package/dist/web/assets/{TerminalOverlay-CFlH51DD.js → TerminalOverlay-CAmF__Dq.js} +1 -1
- package/dist/web/assets/{TrainingCreationPanel-CgIBVGha.js → TrainingCreationPanel-D75K0yk5.js} +1 -1
- package/dist/web/assets/{TrainingDraftPanel-Bbo3RRie.js → TrainingDraftPanel-D7XZePAk.js} +1 -1
- package/dist/web/assets/{UsageSettingsSection-CSRjJUSa.js → UsageSettingsSection-CYTmp7PG.js} +1 -1
- package/dist/web/assets/WorkSidebarPanel-CODMjVHY.js +1 -0
- package/dist/web/assets/WorkspaceDiffPanel-DQGoIjH9.js +14 -0
- package/dist/web/assets/WorkspaceEnvironmentMenu-c1pHDskn.js +63 -0
- package/dist/web/assets/{WorkspaceGitDialogs-Dgmg-6XG.js → WorkspaceGitDialogs-DrVtapQQ.js} +1 -1
- package/dist/web/assets/{WorkspaceMonacoEditor-BR4qxMgU.js → WorkspaceMonacoEditor-BCKzvSj2.js} +3 -3
- package/dist/web/assets/arrow-up-right-CP4hZdrJ.js +1 -0
- package/dist/web/assets/chunk-NOJECMB7-Bhcms-w5.js +1 -0
- package/dist/web/assets/{clipboard-BZzZ82Bk.js → clipboard-BgrXorn-.js} +1 -1
- package/dist/web/assets/{cloud-upload-CJPYPVl8.js → cloud-upload-B_zYztb6.js} +1 -1
- package/dist/web/assets/{cssMode-WC4Rg1l-.js → cssMode-DanjGgA8.js} +1 -1
- package/dist/web/assets/{folder-open-sLZJxLQy.js → folder-open-CdVKbtGq.js} +1 -1
- package/dist/web/assets/folder-plus-Cc5KElB6.js +1 -0
- package/dist/web/assets/{git-commit-horizontal-Cotm7KEC.js → git-commit-horizontal-CjGIIgRi.js} +1 -1
- package/dist/web/assets/{htmlMode-C6oZGeaB.js → htmlMode-DRGDF_UL.js} +1 -1
- package/dist/web/assets/index-B5re-RJy.css +1 -0
- package/dist/web/assets/{index-BxWTVKtn.js → index-BE-wXZ5R.js} +2 -2
- package/dist/web/assets/info-BLj0RvhA.js +1 -0
- package/dist/web/assets/{jsonMode-BET4LQIn.js → jsonMode-CCu0j2GD.js} +1 -1
- package/dist/web/assets/{lspLanguageFeatures-BPxA_-Kg.js → lspLanguageFeatures-s_Lhm7P6.js} +1 -1
- package/dist/web/assets/minimize-2-Cyg_zD9z.js +1 -0
- package/dist/web/assets/{monaco.contribution-DXzyQfVi.js → monaco.contribution-CAzXvYkn.js} +2 -2
- package/dist/web/assets/{monaco.contribution-DFzEyaHi.js → monaco.contribution-CY7mRgOB.js} +2 -2
- package/dist/web/assets/{monaco.contribution-7AUuf2NS.js → monaco.contribution-aUeLcBEg.js} +2 -2
- package/dist/web/assets/{monaco.contribution-BH6kkO4b.js → monaco.contribution-mUPNK9ra.js} +2 -2
- package/dist/web/assets/monitor-DZvOs_wC.js +1 -0
- package/dist/web/assets/play-BJPzemuY.js +1 -0
- package/dist/web/assets/{python-PzBkTjWx.js → python-B_qnnVaG.js} +1 -1
- package/dist/web/assets/{save-DpezrtH2.js → save-BDy9tA3E.js} +1 -1
- package/dist/web/assets/square-Cb2c5td4.js +1 -0
- package/dist/web/assets/{toggleHighContrast-Cto-fOXm.js → toggleHighContrast-MhO1JLyR.js} +1 -1
- package/dist/web/assets/{tsMode-BYA4LNc6.js → tsMode-DfBXJb9V.js} +1 -1
- package/dist/web/assets/{upload-C5YFNgtS.js → upload-D56kThRh.js} +1 -1
- package/dist/web/assets/{useLocalAgentSchedules-CnyTsqlf.js → useLocalAgentSchedules-DMnGfswi.js} +1 -1
- package/dist/web/assets/useProviderSettings-Bv5B9eNk.js +5 -0
- package/dist/web/assets/{useSessionTurnCache-DICuJSJW.js → useSessionTurnCache-ClAY8gze.js} +1 -1
- package/dist/web/assets/{wifi-off-nzHj7JXp.js → wifi-off-C9lWJmVm.js} +1 -1
- package/dist/web/assets/{workers-Dboaw6f_.js → workers-BYzrH8by.js} +1 -1
- package/dist/web/assets/{yaml-uuY5JmO8.js → yaml-D3T8UkT3.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +3 -3
- package/dist/chunks/actions-command-DSO6YOEE.js +0 -2
- package/dist/chunks/app-server-runtime-KZP2LB5X.js +0 -2
- package/dist/chunks/apps-TM74FFQB.js +0 -2
- package/dist/chunks/chunk-2JO2KWT3.js +0 -5
- package/dist/chunks/chunk-2SPZYBDN.js +0 -16
- package/dist/chunks/chunk-3LX6RU3C.js +0 -3
- package/dist/chunks/chunk-4SHKI3BH.js +0 -2
- package/dist/chunks/chunk-4TZHH5FC.js +0 -2409
- package/dist/chunks/chunk-5TNDPNS3.js +0 -2
- package/dist/chunks/chunk-6JAN4RMN.js +0 -42
- package/dist/chunks/chunk-7QEE4PBI.js +0 -8
- package/dist/chunks/chunk-AFUDIT36.js +0 -2
- package/dist/chunks/chunk-BX4J2VDU.js +0 -2
- package/dist/chunks/chunk-EMKZVP7Z.js +0 -2
- package/dist/chunks/chunk-FPUUZQUP.js +0 -6
- package/dist/chunks/chunk-GCOUYYHG.js +0 -5
- package/dist/chunks/chunk-GS2NKNKG.js +0 -4
- package/dist/chunks/chunk-H2VT22JK.js +0 -2
- package/dist/chunks/chunk-HA7EFTPF.js +0 -23
- package/dist/chunks/chunk-IKWDL3RB.js +0 -17
- package/dist/chunks/chunk-L3KS6MOV.js +0 -2
- package/dist/chunks/chunk-NHFGEVVH.js +0 -518
- package/dist/chunks/chunk-NNF6KCHD.js +0 -3
- package/dist/chunks/chunk-PJM2G7SG.js +0 -21
- package/dist/chunks/chunk-PQHTZ5CP.js +0 -2
- package/dist/chunks/chunk-PYABBF53.js +0 -53
- package/dist/chunks/chunk-QRWPEW3Z.js +0 -24
- package/dist/chunks/chunk-QXVIIM4T.js +0 -2
- package/dist/chunks/chunk-SDEDAHV6.js +0 -160
- package/dist/chunks/chunk-TGIB24K4.js +0 -22
- package/dist/chunks/chunk-USKE34VR.js +0 -9
- package/dist/chunks/chunk-WV2APYWG.js +0 -2
- package/dist/chunks/chunk-XGE2XI6M.js +0 -191
- package/dist/chunks/chunk-XM26DGML.js +0 -3
- package/dist/chunks/chunk-YIB3J4RC.js +0 -2
- package/dist/chunks/chunk-YL6VFJ4P.js +0 -2
- package/dist/chunks/chunk-Z3D4C7BG.js +0 -12
- package/dist/chunks/cli-JVB345H2.js +0 -2
- package/dist/chunks/connected-evidence-YDPGNHLP.js +0 -2
- package/dist/chunks/core-commands-MTV4EKXY.js +0 -2
- package/dist/chunks/datasets-CP3IT47T.js +0 -2
- package/dist/chunks/desktop-test-IAZC5MAH.js +0 -3
- package/dist/chunks/dist-SAABJU5F.js +0 -2
- package/dist/chunks/evaluation-coordination-EPHLZXYM.js +0 -2
- package/dist/chunks/experiment-improvements-6JTOPA74.js +0 -2
- package/dist/chunks/experiments-XHPFGECH.js +0 -2
- package/dist/chunks/extension-GX7DLW2X.js +0 -4
- package/dist/chunks/hosted-experiment-improvement-HAB3UE6A.js +0 -3
- package/dist/chunks/hosted-harness-runtime-YM23QNDK.js +0 -2
- package/dist/chunks/hosted-profile-candidate-EOBGKQAS.js +0 -3
- package/dist/chunks/hosted-profile-compiler-OZAOZ2ES.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-control-RJ6XJZCS.js +0 -2
- package/dist/chunks/hosted-profile-evaluation-inspection-SJIDXPHI.js +0 -3
- package/dist/chunks/hosted-profile-evaluation-preparation-26EI5LJR.js +0 -3
- package/dist/chunks/human-review-AAVMISBF.js +0 -2
- package/dist/chunks/learning-FNBEIAY6.js +0 -2
- package/dist/chunks/opchat-QK43DXTY.js +0 -3
- package/dist/chunks/organizations-SRPAWKC7.js +0 -2
- package/dist/chunks/profile-C6CQNVYE.js +0 -3
- package/dist/chunks/project-agent-GZV5HNYI.js +0 -2
- package/dist/chunks/sandbox-command-4TJXQTKT.js +0 -2
- package/dist/chunks/src-P3VYLFLI.js +0 -329
- package/dist/web/assets/App-CO2F717V.css +0 -1
- package/dist/web/assets/App-CuhaCsfb.js +0 -235
- package/dist/web/assets/AppsView-BS1czXUP.js +0 -1
- package/dist/web/assets/HostedModelLearningReview-CHxxf_Lu.js +0 -1
- package/dist/web/assets/LabsRoute-CXJRJMhr.js +0 -99
- package/dist/web/assets/MainChatThread-BwAla81W.js +0 -2
- package/dist/web/assets/MainPane-CakOBCHw.js +0 -19
- package/dist/web/assets/RightChatPanelStack-VaOOmxwd.js +0 -1
- package/dist/web/assets/ScheduledWorkPage-D1jRQxFs.js +0 -1
- package/dist/web/assets/SettingsView-RA9OXgcu.js +0 -5
- package/dist/web/assets/WorkSidebarPanel-DwlEMEoG.js +0 -1
- package/dist/web/assets/WorkspaceDiffPanel-pGVezNMw.js +0 -14
- package/dist/web/assets/WorkspaceEnvironmentMenu-Byjngd9V.js +0 -32
- package/dist/web/assets/arrow-up-right-H0pvnH2s.js +0 -1
- package/dist/web/assets/chunk-UHVJOMWN-BqXRe639.js +0 -1
- package/dist/web/assets/folder-plus-C84wrpt_.js +0 -1
- package/dist/web/assets/index-dSmk3FLJ.css +0 -1
- package/dist/web/assets/info-Dc81lEfw.js +0 -1
- package/dist/web/assets/minimize-2-Bs7MVN3C.js +0 -1
- package/dist/web/assets/monitor-DXL019Wf.js +0 -1
- package/dist/web/assets/play-CXkxUZeU.js +0 -1
- package/dist/web/assets/square-oy7f5Ce6.js +0 -1
- package/dist/web/assets/useProviderSettings-B_KeQjE5.js +0 -5
- /package/dist/chunks/{chunk-OGPHXXCD.js → chunk-BT5YNE5U.js} +0 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalOverlay-CAmF__Dq.js","assets/index-BE-wXZ5R.js","assets/index-B5re-RJy.css","assets/TerminalOverlay-DwBiZLwk.css","assets/CommandMenu-B-w53n9A.js","assets/CommandMenu-Cb3vNGJr.css","assets/SettingsView-T1vYDPjh.js","assets/useProviderSettings-Bv5B9eNk.js","assets/save-BDy9tA3E.js","assets/MarkdownText-DOdOVFXL.js","assets/useProviderSettings-Bw-csWbH.css","assets/folder-open-CdVKbtGq.js","assets/play-BJPzemuY.js","assets/wifi-off-C9lWJmVm.js","assets/cloud-upload-B_zYztb6.js","assets/git-commit-horizontal-CjGIIgRi.js","assets/useLocalAgentSchedules-DMnGfswi.js","assets/folder-plus-Cc5KElB6.js","assets/AppDialog-CPHTPqrx.js","assets/WorkspaceDiffPanel-DQGoIjH9.js","assets/training-model-data-CKOkpBBL.js","assets/info-BLj0RvhA.js","assets/minimize-2-Cyg_zD9z.js","assets/clipboard-BgrXorn-.js","assets/SettingsView-BnANbPLS.css","assets/git-dialogs-C-F47S10.css","assets/NewProjectDialog-D8sy1gOz.js","assets/monitor-DZvOs_wC.js","assets/WorkspaceGitDialogs-DrVtapQQ.js","assets/upload-D56kThRh.js","assets/WorkspaceEnvironmentMenu-c1pHDskn.js","assets/square-Cb2c5td4.js","assets/WorkspaceEnvironmentMenu-DGIFdG3o.css","assets/MainPane-D3ojiN-p.js","assets/arrow-up-right-CP4hZdrJ.js","assets/MainPane-DOWsSew1.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as h,j as g,a as r_,g as i0,_ as fr}from"./index-BE-wXZ5R.js";const c0=h.createContext(void 0),l0=e=>{const t=h.useContext(c0);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},o_=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),g.jsx(c0.Provider,{value:e,children:t})),i_={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)};var c_=class{#e=i_;#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 Lr=new c_;function l_(e){setTimeout(e,0)}const d_=typeof window>"u"||"Deno"in globalThis;function Qn(){}function u_(e,t){return typeof e=="function"?e(t):e}function d0(e){return typeof e=="number"&&e>=0&&e!==1/0}function u0(e,t){return Math.max(e+(t||0)-Date.now(),0)}function rn(e,t){return typeof e=="function"?e(t):e}function Bg(e,t){const{type:n="all",exact:a,fetchStatus:s,predicate:r,queryKey:i,stale:c}=e;if(i){if(a){if(t.queryHash!==Nf(i,t.options))return!1}else if(!ti(t.queryKey,i))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||r&&!r(t))}function Fg(e,t){const{exact:n,status:a,predicate:s,mutationKey:r}=e;if(r){if(!t.options.mutationKey)return!1;if(n){if(vc(t.options.mutationKey)!==vc(r))return!1}else if(!ti(t.options.mutationKey,r))return!1}return!(a&&t.state.status!==a||s&&!s(t))}function Nf(e,t){return(t?.queryKeyHashFn||vc)(e)}function vc(e){return JSON.stringify(e,(t,n)=>jp(n)?Object.keys(n).sort().reduce((a,s)=>(a[s]=n[s],a),{}):n)}function ti(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(!ti(e[a],t[a]))return!1;return!0}const n=Object.keys(t);for(const a of n)if(!ti(e[a],t[a]))return!1;return!0}return!1}const m_=Object.prototype.hasOwnProperty;function m0(e,t,n=0){if(e===t)return e;if(n>500)return t;const a=Vg(e)&&Vg(t);if(!a&&!(jp(e)&&jp(t)))return t;const s=(a?e:Object.keys(e)).length,r=a?t:Object.keys(t),i=r.length,c=a?new Array(i):{};let u=0;for(let l=0;l<i;l++){const p=a?l:r[l],f=e[p],y=t[p];if(f===y){c[p]=f,(a?l<s:m_.call(e,p))&&u++;continue}if(f===null||y===null||typeof f!="object"||typeof y!="object"){c[p]=y;continue}const b=m0(f,y,n+1);c[p]=b,b===f&&u++}return s===i&&u===s?e:c}function Nm(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 Vg(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function jp(e){if(!Kg(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!Kg(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Kg(e){return Object.prototype.toString.call(e)==="[object Object]"}function p_(e){return new Promise(t=>{Lr.setTimeout(t,e)})}function Mp(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?m0(e,t):t}function f_(e,t,n=0){const a=[...e,t];return n&&a.length>n?a.slice(1):a}function h_(e,t,n=0){const a=[t,...e];return n&&a.length>n?a.slice(0,-1):a}const Df=Symbol();function p0(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Df?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function f0(e,t){return typeof e=="function"?e(...t):!!e}function g_(e,t,n){let a=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??=t(),a||(a=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}let v_=()=>d_;const Lf=()=>v_();var Nc=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(){}},b_=class extends Nc{#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 zf=new b_,y_=l_;function S_(){let e=[],t=0,n=c=>{c()},a=c=>{c()},s=y_;const r=c=>{t?e.push(c):s(()=>{n(c)})},i=()=>{const c=e;e=[],c.length&&s(()=>{a(()=>{c.forEach(u=>{n(u)})})})};return{batch:c=>{let u;t++;try{u=c()}finally{t--,t||i()}return u},batchCalls:c=>(...u)=>{r(()=>{c(...u)})},schedule:r,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{a=c},setScheduler:c=>{s=c}}}const Nn=S_();var x_=class extends Nc{#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 pd=new x_;function k_(e){return Math.min(1e3*2**e,3e4)}function h0(e){return(e??"online")==="online"?pd.isOnline():!0}var Op=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function g0(e){let t=!1,n=0,a,s="pending",r,i;const c=new Promise((M,A)=>{r=M,i=A});c.catch(Qn);const u=()=>s!=="pending",l=M=>{if(!u()){const A=new Op(M);C(A),e.onCancel?.(A)}},p=()=>{t=!0},f=()=>{t=!1},y=()=>zf.isFocused()&&(e.networkMode==="always"||pd.isOnline())&&e.canRun(),b=()=>h0(e.networkMode)&&e.canRun(),I=M=>{u()||(a?.(),s="resolved",r(M))},C=M=>{u()||(a?.(),s="rejected",i(M))},P=()=>new Promise(M=>{a=A=>{(u()||y())&&M(A)},e.onPause?.()}).then(()=>{a=void 0,u()||e.onContinue?.()}),_=()=>{if(u())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(u())return;const S=e.retry??(Lf()?0:3),w=e.retryDelay??k_,R=typeof w=="function"?w(n,T):w,O=S===!0||typeof S=="number"&&n<S||typeof S=="function"&&S(n,T);if(t||!O){C(T);return}n++,e.onFail?.(n,T),p_(R).then(()=>y()?void 0:P()).then(()=>{t?C(T):_()})})};return{promise:c,status:()=>s,cancel:l,continue:()=>(a?.(),c),cancelRetry:p,continueRetry:f,canStart:b,start:()=>(b()?_():P().then(_),c)}}var v0=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),d0(this.gcTime)&&(this.#e=Lr.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Lf()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Lr.clearTimeout(this.#e),this.#e=void 0)}};function w_(e){return{onFetch:(t,n)=>{const a=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,r=t.state.data?.pages||[],i=t.state.data?.pageParams||[];let c={pages:[],pageParams:[]},u=0;const l=async()=>{let p=!1;const f=I=>{g_(I,()=>t.signal,()=>p=!0)},y=p0(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 y(M),{maxPages:T}=t.options,S=P?h_:f_;return{pages:S(I.pages,A,T),pageParams:S(I.pageParams,C,T)}};if(s&&r.length){const I=s==="backward",C=I?b0:$p,P={pages:r,pageParams:i};c=await b(P,C(a,P),I)}else{const I=e??r.length;do{const C=u===0?i[0]??a.initialPageParam:$p(a,c);if(u>0&&C==null)break;c=await b(c,C),u++}while(u<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 $p(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 b0(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function OW(e,t){return t?$p(e,t)!=null:!1}function $W(e,t){return!t||!e.getPreviousPageParam?!1:b0(e,t)!=null}var I_=class extends v0{#e;#t;#n;#a;#r;#s;#o;#c;constructor(e){super(),this.#c=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#a=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Gg(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.#s?.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=Gg(this.options);t.data!==void 0&&(this.setState(Wg(t.data,t.dataUpdatedAt)),this.#t=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#a.remove(this)}setData(e,t){const n=Mp(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.#s?.promise;return this.#s?.cancel(e),t?t.then(Qn).catch(Qn):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=>rn(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Df||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>rn(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:!u0(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#s?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#s?.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.#s&&(this.#c||this.state.fetchStatus==="paused"&&this.state.status==="pending"?this.#s.cancel({revert:!0}):this.#s.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.#s?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#s)return this.#s.continueRetry(),this.#s.promise}if(e&&this.setOptions(e),!this.options.queryFn){const u=this.observers.find(l=>l.options.queryFn);u&&this.setOptions(u.options)}const n=new AbortController,a=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(this.#c=!0,n.signal)})},s=()=>{const u=p0(this.options,t),p=(()=>{const f={client:this.#r,queryKey:this.queryKey,meta:this.meta};return a(f),f})();return this.#c=!1,this.options.persister?this.options.persister(u,p,this):u(p)},i=(()=>{const u={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:s};return a(u),u})();(this.#e==="infinite"?w_(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.#s=g0({initialPromise:t?.initialPromise,fn:i.fetchFn,onCancel:u=>{u instanceof Op&&u.revert&&this.setState({...this.#n,fetchStatus:"idle"}),n.abort()},onFail:(u,l)=>{this.#i({type:"failed",failureCount:u,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 u=await c.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#a.config.onSuccess?.(u,this),this.#a.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Op){if(u.silent)return this.#s.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#i({type:"error",error:u}),this.#a.config.onError?.(u,this),this.#a.config.onSettled?.(this.state.data,u,this),u}finally{this.#s===c&&(this.#s=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,...y0(n.data,this.options),fetchMeta:e.meta??null};case"success":const a={...n,...Wg(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 s=e.error;return{...n,error:s,errorUpdateCount:n.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:n.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...n,isInvalidated:!0};case"setState":return{...n,...e.state}}};this.state=t(this.state),Nn.batch(()=>{this.observers.slice().forEach(n=>{n.onQueryUpdate()}),this.#a.notify({query:this,type:"updated",action:e})})}};function y0(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:h0(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Wg(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Gg(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 __=class extends Nc{#e;#t=void 0;#n=void 0;#a=void 0;#r;#s;#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),Zg(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Np(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Np(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 rn(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&&!Nm(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const a=this.hasListeners();a&&Jg(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),a&&(this.#t!==n||rn(this.options.enabled,this.#t)!==rn(t.enabled,this.#t)||rn(this.options.staleTime,this.#t)!==rn(t.staleTime,this.#t))&&this.#g();const s=this.#v();a&&(this.#t!==n||rn(this.options.enabled,this.#t)!==rn(t.enabled,this.#t)||s!==this.#l)&&this.#b(s)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Nm(this.getCurrentResult(),n)||(this.#a=n,this.#s=this.options,this.#r=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=()=>{},s;const r=new Promise(i=>{s=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 s?.(i),i}).finally(()=>{a()}),r])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#a))}#m(e){this.#k();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Qn)),t}#h(e){return!Lf()&&rn(this.options.enabled,this.#t)!==!1&&d0(e)}#g(){this.#S();const e=rn(this.options.staleTime,this.#t);if(this.#a.isStale||!this.#h(e))return;const t=u0(this.#a.dataUpdatedAt,e)+1;this.#d=Lr.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=Lr.setInterval(()=>{(this.options.refetchIntervalInBackground||zf.isFocused())&&this.#m()},this.#l))}#y(){this.#g(),this.#b(this.#v())}#S(){this.#d!==void 0&&(Lr.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#u!==void 0&&(Lr.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const n=this.#t,a=this.options,s=this.#a,r=this.#r,i=this.#s,c=e!==n?e.state:this.#n,{state:u}=e;let l={...u},p=!1,f;if(t._optimisticResults){const S=this.hasListeners(),w=!S&&Zg(e,t),R=S&&Jg(e,n,t,a);(w||R)&&(l={...l,...y0(u.data,e.options)}),t._optimisticResults==="isRestoring"&&(l.fetchStatus="idle")}let{error:y,errorUpdatedAt:b,status:I}=l;f=l.data;let C=!1;if(t.placeholderData!==void 0&&f===void 0&&I==="pending"){let S;s?.isPlaceholderData&&t.placeholderData===i?.placeholderData?(S=s.data,C=!0):S=typeof t.placeholderData=="function"?t.placeholderData(this.#p?.state.data,this.#p):t.placeholderData,S!==void 0&&(I="success",f=Mp(s?.data,S,t),p=!0)}if(t.select&&f!==void 0&&!C)if(s&&f===r?.data&&t.select===this.#c)f=this.#i;else try{this.#c=t.select,f=t.select(f),f=Mp(s?.data,f,t),this.#i=f,this.#o=null}catch(S){this.#o=S}else f===void 0&&(this.#o=null);this.#o&&(y=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:y,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:Hf(e,t),refetch:this.refetch,isEnabled:rn(t.enabled,e)!==!1}}updateResult(){const e=this.#a,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#s=this.options,this.#r.data!==void 0&&(this.#p=this.#t),Nm(t,e))return;this.#a=t;const a=(()=>{if(!e)return!0;const{notifyOnChangeProps:s}=this.options,r=typeof s=="function"?s():s;if(r==="all"||!r&&!this.#f.size)return!0;const i=new Set(r??this.#f);return this.options.throwOnError&&i.add("error"),Object.keys(this.#a).some(c=>{const u=c;return this.#a[u]!==e[u]&&i.has(u)})})();Nn.batch(()=>{a&&this.listeners.forEach(s=>{s(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 C_(e,t){return rn(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&rn(t.retryOnMount,e)===!1)}function Zg(e,t){return C_(e,t)||e.state.data!==void 0&&Np(e,t,t.refetchOnMount)}function Np(e,t,n){if(rn(t.enabled,e)!==!1&&rn(t.staleTime,e)!=="static"){const a=typeof n=="function"?n(e):n;return a==="always"||a!==!1&&Hf(e,t)}return!1}function Jg(e,t,n,a){return(e!==t||rn(a.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Hf(e,n)}function Hf(e,t){return rn(t.enabled,e)!==!1&&e.isStaleByTime(rn(t.staleTime,e))}var R_=class extends v0{#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||P_(),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.#r({type:"continue"})},a={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},s=this.#a=g0({fn:()=>this.options.mutationFn?this.options.mutationFn(t,a):Promise.reject(new Error("No mutationFn found")),onFail:(c,u)=>{this.#r({type:"failed",failureCount:c,error:u})},onPause:()=>{this.#r({type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),r=this.state.status==="pending",i=!s.canStart();try{if(r)n();else{this.#r({type:"pending",variables:t,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(t,this,a);const u=await this.options.onMutate?.(t,a);u!==this.state.context&&this.#r({type:"pending",context:u,variables:t,isPaused:i})}const c=await s.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.#r({type:"success",data:c}),c}catch(c){try{await this.#n.config.onError?.(c,t,this.state.context,this,a)}catch(u){Promise.reject(u)}try{await this.options.onError?.(c,t,this.state.context,a)}catch(u){Promise.reject(u)}try{await this.#n.config.onSettled?.(void 0,c,this.state.variables,this.state.context,this,a)}catch(u){Promise.reject(u)}try{await this.options.onSettled?.(void 0,c,t,this.state.context,a)}catch(u){Promise.reject(u)}throw this.#r({type:"error",error:c}),c}finally{this.#a===s&&(this.#a=void 0),this.#n.runNext(this)}}#r(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),Nn.batch(()=>{this.#t.forEach(a=>{a.onMutationUpdate(t)}),this.#n.notify({mutation:this,type:"updated",action:t})})}};function P_(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var T_=class extends Nc{#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 R_({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=Sl(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=Sl(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=Sl(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=Sl(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){Nn.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=>Fg(t,n))}findAll(e={}){return this.getAll().filter(t=>Fg(e,t))}notify(e){Nn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return Nn.batch(()=>Promise.all(e.map(t=>t.continue().catch(Qn))))}};function Sl(e){return e.options.scope?.id}var A_=class extends Nc{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){const a=t.queryKey,s=t.queryHash??Nf(a,t);let r=this.get(s);return r||(r=new I_({client:e,queryKey:a,queryHash:s,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(a)}),this.add(r)),r}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){Nn.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=>Bg(t,n))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(n=>Bg(e,n)):t}notify(e){Nn.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Nn.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Nn.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},E_=class{#e;#t;#n;#a;#r;#s;#o;#c;constructor(e={}){this.#e=e.queryCache||new A_,this.#t=e.mutationCache||new T_,this.#n=e.defaultOptions||{},this.#a=new Map,this.#r=new Map,this.#s=0}mount(){this.#s++,this.#s===1&&(this.#o=zf.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#c=pd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#s--,this.#s===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(rn(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}),s=this.#e.get(a.queryHash)?.state.data,r=u_(t,s);if(r!==void 0)return this.#e.build(this,a).setData(r,{...n,manual:!0})}setQueriesData(e,t,n){return Nn.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;Nn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=this.#e;return Nn.batch(()=>{const a=n.findAll(e),s=new Set(a);return a.forEach(r=>{r.reset()}),this.refetchQueries({type:"active",predicate:r=>s.has(r)},t)})}cancelQueries(e,t={}){const n={revert:!0,...t},a=Nn.batch(()=>this.#e.findAll(e).map(s=>s.cancel(n)));return Promise.all(a).then(Qn).catch(Qn)}invalidateQueries(e,t={}){return Nn.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=Nn.batch(()=>this.#e.findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let r=s.fetch(void 0,n);return n.throwOnError||(r=r.catch(Qn)),s.state.fetchStatus==="paused"?Promise.resolve():r}));return Promise.all(a).then(Qn)}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(rn(t.staleTime,n))?await n.fetch(t):n.state.data,s=t.select;return s?s(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(rn(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Qn).catch(Qn)}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(Qn).catch(Qn)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return pd.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(vc(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#a.values()],n={};return t.forEach(a=>{ti(e,a.queryKey)&&Object.assign(n,a.defaultOptions)}),n}setMutationDefaults(e,t){this.#r.set(vc(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],n={};return t.forEach(a=>{ti(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=Nf(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===Df&&(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 S0=h.createContext(!1),j_=()=>h.useContext(S0);S0.Provider;function M_(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}const O_=h.createContext(M_()),$_=()=>h.useContext(O_),N_=(e,t,n)=>{const a=n?.state.error&&typeof e.throwOnError=="function"?f0(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||a)&&(t.isReset()||(e.retryOnMount=!1))},D_=e=>{h.useEffect(()=>{e.clearReset()},[e])},L_=({result:e,errorResetBoundary:t,throwOnError:n,query:a,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&a&&(s&&e.data===void 0||f0(n,[e.error,a])),z_=e=>{if(e.suspense){const n=s=>s==="static"?s:Math.max(s??1e3,1e3),a=e.staleTime;e.staleTime=typeof a=="function"?(...s)=>n(a(...s)):n(a),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},H_=(e,t)=>e?.suspense&&t.isPending,U_=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function q_(e,t,n){const a=j_(),s=$_(),r=l0(),i=r.defaultQueryOptions(e),c=r.getQueryCache().get(i.queryHash),u=e.subscribed!==!1;i._optimisticResults=a?"isRestoring":u?"optimistic":void 0,z_(i),N_(i,s,c),D_(s);const[l]=h.useState(()=>new t(r,i)),p=l.getOptimisticResult(i),f=!a&&u;if(h.useSyncExternalStore(h.useCallback(y=>{const b=f?l.subscribe(Nn.batchCalls(y)):Qn;return l.updateResult(),b},[l,f]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),h.useEffect(()=>{l.setOptions(i)},[i,l]),H_(i,p))throw U_(i,l,s);if(L_({result:p,errorResetBoundary:s,throwOnError:i.throwOnError,query:c,suspense:i.suspense}))throw p.error;return i.notifyOnChangeProps?p:l.trackResult(p)}function x0(e,t){return q_(e,__)}function B_(){return new E_({defaultOptions:{queries:{staleTime:6e4,gcTime:15*6e4,retry:1,refetchOnWindowFocus:!1}}})}const F_=new Set(["turn.started","turn.completed","turn.failed","turn.interrupted","approval.requested","approval.resolved","task.input","task.wait"]);function V_(e){const t={};for(const n of e)n.sessionId&&F_.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 K_(e,t,n){return[...new Map(e.map(a=>[a.id,a])).values()].sort((a,s)=>Number(n.has(s.id))-Number(n.has(a.id))||fd(s,t)-fd(a,t)||a.id.localeCompare(s.id))}function fd(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 W_(e,t,n,a=new Date){const s=c=>`${c.getFullYear()}-${c.getMonth()}-${c.getDate()}`,r=new Date(a);r.setDate(a.getDate()-1);const i=[];for(const c of e){const u=new Date(fd(c,t)),l=n.has(c.id),p=l?"running":s(u);let f=i.at(-1);f?.key!==p&&(f={key:p,label:l||p===s(a)?null:p===s(r)?"Yesterday":u.toLocaleDateString(void 0,{month:"short",day:"numeric",...u.getFullYear()!==a.getFullYear()?{year:"numeric"}:{}}),sessions:[]},i.push(f)),f.sessions.push(c)}return i}function G_(e,t,n){const a=new Headers;a.set("Accept","text/event-stream"),a.set("Authorization",`Bearer ${e.token}`);const s=new URL(`${e.serverUrl.replace(/\/$/,"")}/v1/events`);return n!==void 0&&Number.isSafeInteger(n)&&n>0&&s.searchParams.set("afterSequence",String(n)),{url:s.toString(),init:{headers:a,signal:t}}}function Z_(e){return Math.min(500*2**Math.max(0,e),1e4)}async function J_(e,t,n,a){k0(e);const s=e.body.getReader(),r=new TextDecoder;let i="";for(;!a?.aborted;){const{done:c,value:u}=await s.read();if(c){i+=r.decode();break}i+=r.decode(u,{stream:!0});let l=i.indexOf(`
|
|
3
|
+
|
|
4
|
+
`);for(;l>=0;){const p=i.slice(0,l);i=i.slice(l+2),Yg(p,t,n),l=i.indexOf(`
|
|
5
|
+
|
|
6
|
+
`)}}!a?.aborted&&i.trim()&&Yg(i,t,n)}function k0(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 Q_(e,t,n,a,s={}){const r=new AbortController,i=s.fetchImpl??fetch,c=s.reconnectDelayMs??Z_;let u=Qg(s.afterSequence),l=!1;return(async()=>{let p=0;for(;!r.signal.aborted;)try{const f=G_(e,r.signal,u),y=await i(f.url,f.init);if(k0(y),l=!0,p=0,await J_(y,b=>{const I=Qg(b.sequence);I>0&&I<=u||(I>0&&(u=I),t(b))},a,r.signal),l=!1,r.signal.aborted)break;throw new Error("event stream ended")}catch(f){if(l=!1,r.signal.aborted)break;n(f),await Y_(c(p),r.signal),p+=1}})().catch(()=>{}),{close(){r.abort()},isOpen(){return l}}}function Qg(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:0}function Yg(e,t,n){let a="message";const s=[];for(const r of e.split(`
|
|
7
|
+
`))r.startsWith(":")||(r.startsWith("event: ")&&(a=r.slice(7).trim()),r.startsWith("data: ")&&s.push(r.slice(6)));if(a==="ready"){n?.();return}if(!(a!=="runtime"||s.length===0))try{t(JSON.parse(s.join(`
|
|
8
|
+
`)))}catch{}}async function Y_(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 X_ extends Error{constructor(t,n){super(t),this.status=n,this.name="ApiRequestError"}status}function Xg(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 ev=new WeakMap,tv=new WeakMap,xl=new WeakMap;let eC=0;async function L(e,t,n){if(t==="/v1/preferences"&&typeof n?.body=="string"){const s=(xl.get(e)??Promise.resolve()).catch(()=>{}).then(()=>nv(e,t,n));xl.set(e,s);try{return await s}finally{xl.get(e)===s&&xl.delete(e)}}return nv(e,t,n)}async function nv(e,t,n){const a=++eC;if(t==="/v1/preferences"&&typeof n?.body=="string"){const u=ev.get(e);if(!u)throw new Error("Reload settings before saving so changes can be checked against the current file.");n={...n,body:JSON.stringify({expectedRevision:u,...JSON.parse(n.body)})}}const s=new Headers(n?.headers);s.set("Content-Type","application/json"),s.set("Authorization",`Bearer ${e.token}`);const r=await fetch(`${e.serverUrl}${t}`,{...n,headers:s});if(!r.ok){const u=await r.json().catch(()=>({})),l=u&&typeof u=="object"&&"error"in u?String(u.error):r.statusText;throw new X_(l,r.status)}if(r.status===204)return;const i=await r.json(),c=i?.configuration?.rawRevision??(t==="/v1/preferences"?i?.rawRevision:void 0);return typeof c=="string"&&a>=(tv.get(e)??0)&&(ev.set(e,c),tv.set(e,a)),i}function DW(e){const t=new URL("/v1/terminal",e.serverUrl);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.toString()}function LW(e){return["openpond-terminal",`openpond-token.${nC(e.token)}`]}function tC(e){const t=new TextEncoder().encode(e);let n="";for(let a=0;a<t.length;a+=32768){const s=t.subarray(a,a+32768);n+=String.fromCharCode(...s)}return btoa(n)}function nC(e){return tC(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function aC(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 sC(e,t,n){const a=h.useRef(n);a.current=n,h.useEffect(()=>{if(!e||!t)return;let s=!1,r=!1,i=null;const c=new Set,u=new Map,l=C=>`openpond:ponder-notification-delivery:${t}:${C}`;async function p(C){if(!(s||!i))try{const P=await L(e,"/v1/ponder/notifications");if(s||P.bindingId!==i||!P.items.some(_=>_.id===C)||(await L(e,`/v1/ponder/notifications/${encodeURIComponent(C)}/read`,{method:"POST",body:"{}"}),s))return;window.focus(),a.current?.()}catch{}}const f=window.openpond?.onPonderNotification?.(C=>{p(C.id)});async function y(){if(!(s||r)){r=!0;try{const[C,P]=await Promise.all([L(e,"/v1/ponder/settings"),L(e,"/v1/ponder/notifications")]);if(s||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 u)_.has(M)||(A.close(),u.delete(M));if(localStorage.getItem("openpond:ponder-notifications")!=="on"||C.settings.notifications==="off")return;for(const M of P.items){if(s||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 S=new Notification(A.title,{body:A.body,tag:A.id});S.onclick=()=>{S.close(),p(M.id)},u.set(M.id,S),T=!0}if(s)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{r=!1}}}y();const b=window.setInterval(()=>{y()},1e4),I=()=>{y()};return window.addEventListener("ponder-settings-changed",I),()=>{s=!0,window.clearInterval(b),f?.(),window.removeEventListener("ponder-settings-changed",I);for(const C of u.values())C.close()}},[e,t])}var av;function le(e,t,n){function a(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const l=i.prototype,p=Object.keys(l);for(let f=0;f<p.length;f++){const y=p[f];y in c||(c[y]=l[y].bind(c))}}const s=n?.Parent??Object;class r extends s{}Object.defineProperty(r,"name",{value:e});function i(c){var u;const l=n?.Parent?new r:this;a(l,c),(u=l._zod).deferred??(u.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 Zo extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class w0 extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(av=globalThis).__zod_globalConfig??(av.__zod_globalConfig={});const Uf=globalThis.__zod_globalConfig;function qs(e){return Uf}function I0(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,s])=>t.indexOf(+a)===-1).map(([a,s])=>s)}function Dp(e,t){return typeof t=="bigint"?t.toString():t}function Hd(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function qf(e){return e==null}function Bf(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function rC(e,t){const n=e/t,a=Math.round(n),s=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-a)<s?0:n-a}const sv=Symbol("evaluating");function St(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==sv)return a===void 0&&(a=sv,a=n()),a},set(s){Object.defineProperty(e,t,{value:s})},configurable:!0})}function Zr(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function hr(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function rv(e){return JSON.stringify(e)}function oC(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const _0="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function bc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const iC=Hd(()=>{if(Uf.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ni(e){if(bc(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(bc(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function C0(e){return ni(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const cC=new Set(["string","number","symbol"]);function ai(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gr(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function Ue(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 lC(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const dC={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 uC(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const r=hr(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 Zr(this,"shape",i),i},checks:[]});return gr(e,r)}function mC(e,t){const n=e._zod.def,a=n.checks;if(a&&a.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const r=hr(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 Zr(this,"shape",i),i},checks:[]});return gr(e,r)}function pC(e,t){if(!ni(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const r=e._zod.def.shape;for(const i in t)if(Object.getOwnPropertyDescriptor(r,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const s=hr(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Zr(this,"shape",r),r}});return gr(e,s)}function fC(e,t){if(!ni(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=hr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t};return Zr(this,"shape",a),a}});return gr(e,n)}function hC(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=hr(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Zr(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return gr(e,n)}function gC(e,t,n){const s=t._zod.def.checks;if(s&&s.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const i=hr(t._zod.def,{get shape(){const c=t._zod.def.shape,u={...c};if(n)for(const l in n){if(!(l in c))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(u[l]=e?new e({type:"optional",innerType:c[l]}):c[l])}else for(const l in c)u[l]=e?new e({type:"optional",innerType:c[l]}):c[l];return Zr(this,"shape",u),u},checks:[]});return gr(t,i)}function vC(e,t,n){const a=hr(t._zod.def,{get shape(){const s=t._zod.def.shape,r={...s};if(n)for(const i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(r[i]=new e({type:"nonoptional",innerType:s[i]}))}else for(const i in s)r[i]=new e({type:"nonoptional",innerType:s[i]});return Zr(this,"shape",r),r}});return gr(t,a)}function No(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 bC(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 Do(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function kl(e){return typeof e=="string"?e:e?.message}function Bs(e,t,n){const a=e.message?e.message:kl(e.inst?._zod.def?.error?.(e))??kl(t?.error?.(e))??kl(n.customError?.(e))??kl(n.localeError?.(e))??"Invalid input",{inst:s,continue:r,input:i,...c}=e;return c.path??(c.path=[]),c.message=a,t?.reportInput&&(c.input=i),c}function Ff(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function yc(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}const R0=(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,Dp,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},P0=le("$ZodError",R0),T0=le("$ZodError",R0,{Parent:Error});function yC(e,t=n=>n.message){const n={},a=[];for(const s of e.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(t(s))):a.push(t(s));return{formErrors:a,fieldErrors:n}}function SC(e,t=n=>n.message){const n={_errors:[]},a=(s,r=[])=>{for(const i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(c=>a({issues:c},[...r,...i.path]));else if(i.code==="invalid_key")a({issues:i.issues},[...r,...i.path]);else if(i.code==="invalid_element")a({issues:i.issues},[...r,...i.path]);else{const c=[...r,...i.path];if(c.length===0)n._errors.push(t(i));else{let u=n,l=0;for(;l<c.length;){const p=c[l];l===c.length-1?(u[p]=u[p]||{_errors:[]},u[p]._errors.push(t(i))):u[p]=u[p]||{_errors:[]},u=u[p],l++}}}};return a(e),n}const Vf=e=>(t,n,a,s)=>{const r=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new Zo;if(i.issues.length){const c=new(s?.Err??e)(i.issues.map(u=>Bs(u,r,qs())));throw _0(c,s?.callee),c}return i.value},Kf=e=>async(t,n,a,s)=>{const r=a?{...a,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(s?.Err??e)(i.issues.map(u=>Bs(u,r,qs())));throw _0(c,s?.callee),c}return i.value},Ud=e=>(t,n,a)=>{const s=a?{...a,async:!1}:{async:!1},r=t._zod.run({value:n,issues:[]},s);if(r instanceof Promise)throw new Zo;return r.issues.length?{success:!1,error:new(e??P0)(r.issues.map(i=>Bs(i,s,qs())))}:{success:!0,data:r.value}},xC=Ud(T0),qd=e=>async(t,n,a)=>{const s=a?{...a,async:!0}:{async:!0};let r=t._zod.run({value:n,issues:[]},s);return r instanceof Promise&&(r=await r),r.issues.length?{success:!1,error:new e(r.issues.map(i=>Bs(i,s,qs())))}:{success:!0,data:r.value}},kC=qd(T0),wC=e=>(t,n,a)=>{const s=a?{...a,direction:"backward"}:{direction:"backward"};return Vf(e)(t,n,s)},IC=e=>(t,n,a)=>Vf(e)(t,n,a),_C=e=>async(t,n,a)=>{const s=a?{...a,direction:"backward"}:{direction:"backward"};return Kf(e)(t,n,s)},CC=e=>async(t,n,a)=>Kf(e)(t,n,a),RC=e=>(t,n,a)=>{const s=a?{...a,direction:"backward"}:{direction:"backward"};return Ud(e)(t,n,s)},PC=e=>(t,n,a)=>Ud(e)(t,n,a),TC=e=>async(t,n,a)=>{const s=a?{...a,direction:"backward"}:{direction:"backward"};return qd(e)(t,n,s)},AC=e=>async(t,n,a)=>qd(e)(t,n,a),EC=/^[cC][0-9a-z]{6,}$/,jC=/^[0-9a-z]+$/,MC=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,OC=/^[0-9a-vA-V]{20}$/,$C=/^[A-Za-z0-9]{27}$/,NC=/^[a-zA-Z0-9_-]{21}$/,DC=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,LC=/^([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})$/,ov=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)$/,zC=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,HC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function UC(){return new RegExp(HC,"u")}const qC=/^(?:(?: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])$/,BC=/^(([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}|:))$/,FC=/^((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])$/,VC=/^(([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])$/,KC=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,A0=/^[A-Za-z0-9_-]*$/,WC=/^https?$/,GC=/^\+[1-9]\d{6,14}$/,E0="(?:(?:\\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])))",ZC=new RegExp(`^${E0}$`);function j0(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 JC(e){return new RegExp(`^${j0(e)}$`)}function QC(e){const t=j0({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(`^${E0}T(?:${a})$`)}const YC=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},XC=/^-?\d+$/,M0=/^-?\d+(?:\.\d+)?$/,eR=/^(?:true|false)$/i,tR=/^null$/i,nR=/^[^A-Z]*$/,aR=/^[^a-z]*$/,sa=le("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),O0={number:"number",bigint:"bigint",object:"date"},$0=le("$ZodCheckLessThan",(e,t)=>{sa.init(e,t);const n=O0[typeof t.value];e._zod.onattach.push(a=>{const s=a._zod.bag,r=(t.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?s.maximum=t.value:s.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})}}),N0=le("$ZodCheckGreaterThan",(e,t)=>{sa.init(e,t);const n=O0[typeof t.value];e._zod.onattach.push(a=>{const s=a._zod.bag,r=(t.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?s.minimum=t.value:s.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})}}),sR=le("$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):rC(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})}}),rR=le("$ZodCheckNumberFormat",(e,t)=>{sa.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[s,r]=dC[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=s,c.maximum=r,n&&(c.pattern=XC)}),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<s&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:s,inclusive:!0,inst:e,continue:!t.abort}),c>r&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:r,inclusive:!0,inst:e,continue:!t.abort})}}),oR=le("$ZodCheckMaxLength",(e,t)=>{var n;sa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const s=a.value;return!qf(s)&&s.length!==void 0}),e._zod.onattach.push(a=>{const s=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<s&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const s=a.value;if(s.length<=t.maximum)return;const i=Ff(s);a.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),iR=le("$ZodCheckMinLength",(e,t)=>{var n;sa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const s=a.value;return!qf(s)&&s.length!==void 0}),e._zod.onattach.push(a=>{const s=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>s&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const s=a.value;if(s.length>=t.minimum)return;const i=Ff(s);a.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),cR=le("$ZodCheckLengthEquals",(e,t)=>{var n;sa.init(e,t),(n=e._zod.def).when??(n.when=a=>{const s=a.value;return!qf(s)&&s.length!==void 0}),e._zod.onattach.push(a=>{const s=a._zod.bag;s.minimum=t.length,s.maximum=t.length,s.length=t.length}),e._zod.check=a=>{const s=a.value,r=s.length;if(r===t.length)return;const i=Ff(s),c=r>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})}}),Bd=le("$ZodCheckStringFormat",(e,t)=>{var n,a;sa.init(e,t),e._zod.onattach.push(s=>{const r=s._zod.bag;r.format=t.format,t.pattern&&(r.patterns??(r.patterns=new Set),r.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=s=>{t.pattern.lastIndex=0,!t.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:t.format,input:s.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),lR=le("$ZodCheckRegex",(e,t)=>{Bd.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})}}),dR=le("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=nR),Bd.init(e,t)}),uR=le("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=aR),Bd.init(e,t)}),mR=le("$ZodCheckIncludes",(e,t)=>{sa.init(e,t);const n=ai(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(s=>{const r=s._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(a)}),e._zod.check=s=>{s.value.includes(t.includes,t.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:s.value,inst:e,continue:!t.abort})}}),pR=le("$ZodCheckStartsWith",(e,t)=>{sa.init(e,t);const n=new RegExp(`^${ai(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const s=a._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),fR=le("$ZodCheckEndsWith",(e,t)=>{sa.init(e,t);const n=new RegExp(`.*${ai(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const s=a._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),hR=le("$ZodCheckOverwrite",(e,t)=>{sa.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class gR{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),s=Math.min(...a.map(i=>i.length-i.trimStart().length)),r=a.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(const i of r)this.content.push(i)}compile(){const t=Function,n=this?.args,s=[...(this?.content??[""]).map(r=>` ${r}`)];return new t(...n,s.join(`
|
|
10
|
+
`))}}const vR={major:4,minor:4,patch:3},Qt=le("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=vR;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const s of a)for(const r of s._zod.onattach)r(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const s=(i,c,u)=>{let l=No(i),p;for(const f of c){if(f._zod.def.when){if(bC(i)||!f._zod.def.when(i))continue}else if(l)continue;const y=i.issues.length,b=f._zod.check(i);if(b instanceof Promise&&u?.async===!1)throw new Zo;if(p||b instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await b,i.issues.length!==y&&(l||(l=No(i,y)))});else{if(i.issues.length===y)continue;l||(l=No(i,y))}}return p?p.then(()=>i):i},r=(i,c,u)=>{if(No(i))return i.aborted=!0,i;const l=s(c,a,u);if(l instanceof Promise){if(u.async===!1)throw new Zo;return l.then(p=>e._zod.parse(p,u))}return e._zod.parse(l,u)};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=>r(p,i,c)):r(l,i,c)}const u=e._zod.parse(i,c);if(u instanceof Promise){if(c.async===!1)throw new Zo;return u.then(l=>s(l,a,c))}return s(u,a,c)}}St(e,"~standard",()=>({validate:s=>{try{const r=xC(e,s);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return kC(e,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Wf=le("$ZodString",(e,t)=>{Qt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??YC(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}}),tn=le("$ZodStringFormat",(e,t)=>{Bd.init(e,t),Wf.init(e,t)}),bR=le("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=LC),tn.init(e,t)}),yR=le("$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=ov(a))}else t.pattern??(t.pattern=ov());tn.init(e,t)}),SR=le("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=zC),tn.init(e,t)}),xR=le("$ZodURL",(e,t)=>{tn.init(e,t),e._zod.check=n=>{try{const a=n.value.trim();if(!t.normalize&&t.protocol?.source===WC.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 s=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(s.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(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.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=s.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),kR=le("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=UC()),tn.init(e,t)}),wR=le("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=NC),tn.init(e,t)}),IR=le("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=EC),tn.init(e,t)}),_R=le("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=jC),tn.init(e,t)}),CR=le("$ZodULID",(e,t)=>{t.pattern??(t.pattern=MC),tn.init(e,t)}),RR=le("$ZodXID",(e,t)=>{t.pattern??(t.pattern=OC),tn.init(e,t)}),PR=le("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=$C),tn.init(e,t)}),TR=le("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=QC(t)),tn.init(e,t)}),AR=le("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ZC),tn.init(e,t)}),ER=le("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=JC(t)),tn.init(e,t)}),jR=le("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=DC),tn.init(e,t)}),MR=le("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=qC),tn.init(e,t),e._zod.bag.format="ipv4"}),OR=le("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=BC),tn.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})}}}),$R=le("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=FC),tn.init(e,t)}),NR=le("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=VC),tn.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[s,r]=a;if(!r)throw new Error;const i=Number(r);if(`${i}`!==r)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${s}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function D0(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const DR=le("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=KC),tn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{D0(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function LR(e){if(!A0.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return D0(n)}const zR=le("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=A0),tn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{LR(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),HR=le("$ZodE164",(e,t)=>{t.pattern??(t.pattern=GC),tn.init(e,t)});function UR(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const s=JSON.parse(atob(a));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||t&&(!("alg"in s)||s.alg!==t))}catch{return!1}}const qR=le("$ZodJWT",(e,t)=>{tn.init(e,t),e._zod.check=n=>{UR(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),L0=le("$ZodNumber",(e,t)=>{Qt.init(e,t),e._zod.pattern=e._zod.bag.pattern??M0,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;const r=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:e,...r?{received:r}:{}}),n}}),BR=le("$ZodNumberFormat",(e,t)=>{rR.init(e,t),L0.init(e,t)}),FR=le("$ZodBoolean",(e,t)=>{Qt.init(e,t),e._zod.pattern=eR,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:e}),n}}),VR=le("$ZodNull",(e,t)=>{Qt.init(e,t),e._zod.pattern=tR,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const s=n.value;return s===null||n.issues.push({expected:"null",code:"invalid_type",input:s,inst:e}),n}}),KR=le("$ZodUnknown",(e,t)=>{Qt.init(e,t),e._zod.parse=n=>n}),WR=le("$ZodNever",(e,t)=>{Qt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function iv(e,t,n){e.issues.length&&t.issues.push(...Do(n,e.issues)),t.value[n]=e.value}const GR=le("$ZodArray",(e,t)=>{Qt.init(e,t),e._zod.parse=(n,a)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=Array(s.length);const r=[];for(let i=0;i<s.length;i++){const c=s[i],u=t.element._zod.run({value:c,issues:[]},a);u instanceof Promise?r.push(u.then(l=>iv(l,n,i))):iv(u,n,i)}return r.length?Promise.all(r).then(()=>n):n}});function hd(e,t,n,a,s,r){const i=n in a;if(e.issues.length){if(s&&r&&!i)return;t.issues.push(...Do(n,e.issues))}if(!i&&!s){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 z0(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=lC(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function H0(e,t,n,a,s,r){const i=[],c=s.keySet,u=s.catchall._zod,l=u.def.type,p=u.optin==="optional",f=u.optout==="optional";for(const y in t){if(y==="__proto__"||c.has(y))continue;if(l==="never"){i.push(y);continue}const b=u.run({value:t[y],issues:[]},a);b instanceof Promise?e.push(b.then(I=>hd(I,n,y,t,p,f))):hd(b,n,y,t,p,f)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:r}),e.length?Promise.all(e).then(()=>n):n}const ZR=le("$ZodObject",(e,t)=>{if(Qt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...c};return Object.defineProperty(t,"shape",{value:u}),u}})}const a=Hd(()=>z0(t));St(e._zod,"propValues",()=>{const c=t.shape,u={};for(const l in c){const p=c[l]._zod;if(p.values){u[l]??(u[l]=new Set);for(const f of p.values)u[l].add(f)}}return u});const s=bc,r=t.catchall;let i;e._zod.parse=(c,u)=>{i??(i=a.value);const l=c.value;if(!s(l))return c.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),c;c.value={};const p=[],f=i.shape;for(const y of i.keys){const b=f[y],I=b._zod.optin==="optional",C=b._zod.optout==="optional",P=b._zod.run({value:l[y],issues:[]},u);P instanceof Promise?p.push(P.then(_=>hd(_,c,y,l,I,C))):hd(P,c,y,l,I,C)}return r?H0(p,l,c,u,a.value,e):p.length?Promise.all(p).then(()=>c):c}}),JR=le("$ZodObjectJIT",(e,t)=>{ZR.init(e,t);const n=e._zod.parse,a=Hd(()=>z0(t)),s=y=>{const b=new gR(["shape","payload","ctx"]),I=a.value,C=A=>{const T=rv(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],S=rv(A),w=y[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 (${S} in input) {
|
|
13
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
14
|
+
...iss,
|
|
15
|
+
path: iss.path ? [${S}, ...iss.path] : [${S}]
|
|
16
|
+
})));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (${T}.value === undefined) {
|
|
21
|
+
if (${S} in input) {
|
|
22
|
+
newResult[${S}] = undefined;
|
|
23
|
+
}
|
|
24
|
+
} else {
|
|
25
|
+
newResult[${S}] = ${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 ? [${S}, ...iss.path] : [${S}]
|
|
33
|
+
})));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (${T}.value === undefined) {
|
|
37
|
+
if (${S} in input) {
|
|
38
|
+
newResult[${S}] = undefined;
|
|
39
|
+
}
|
|
40
|
+
} else {
|
|
41
|
+
newResult[${S}] = ${T}.value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
`):b.write(`
|
|
45
|
+
const ${T}_present = ${S} in input;
|
|
46
|
+
if (${T}.issues.length) {
|
|
47
|
+
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
|
|
48
|
+
...iss,
|
|
49
|
+
path: iss.path ? [${S}, ...iss.path] : [${S}]
|
|
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: [${S}]
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (${T}_present) {
|
|
62
|
+
if (${T}.value === undefined) {
|
|
63
|
+
newResult[${S}] = undefined;
|
|
64
|
+
} else {
|
|
65
|
+
newResult[${S}] = ${T}.value;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
`)}b.write("payload.value = newResult;"),b.write("return payload;");const M=b.compile();return(A,T)=>M(y,A,T)};let r;const i=bc,c=!Uf.jitless,l=c&&iC.value,p=t.catchall;let f;e._zod.parse=(y,b)=>{f??(f=a.value);const I=y.value;return i(I)?c&&l&&b?.async===!1&&b.jitless!==!0?(r||(r=s(t.shape)),y=r(y,b),p?H0([],I,y,b,f,e):y):n(y,b):(y.issues.push({expected:"object",code:"invalid_type",input:I,inst:e}),y)}});function cv(e,t,n,a){for(const r of e)if(r.issues.length===0)return t.value=r.value,t;const s=e.filter(r=>!No(r));return s.length===1?(t.value=s[0].value,s[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(r=>r.issues.map(i=>Bs(i,a,qs())))}),t)}const U0=le("$ZodUnion",(e,t)=>{Qt.init(e,t),St(e._zod,"optin",()=>t.options.some(a=>a._zod.optin==="optional")?"optional":void 0),St(e._zod,"optout",()=>t.options.some(a=>a._zod.optout==="optional")?"optional":void 0),St(e._zod,"values",()=>{if(t.options.every(a=>a._zod.values))return new Set(t.options.flatMap(a=>Array.from(a._zod.values)))}),St(e._zod,"pattern",()=>{if(t.options.every(a=>a._zod.pattern)){const a=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${a.map(s=>Bf(s.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(a,s)=>{if(n)return n(a,s);let r=!1;const i=[];for(const c of t.options){const u=c._zod.run({value:a.value,issues:[]},s);if(u instanceof Promise)i.push(u),r=!0;else{if(u.issues.length===0)return u;i.push(u)}}return r?Promise.all(i).then(c=>cv(c,a,e,s)):cv(i,a,e,s)}}),QR=le("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,U0.init(e,t);const n=e._zod.parse;St(e._zod,"propValues",()=>{const s={};for(const r of t.options){const i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const[c,u]of Object.entries(i)){s[c]||(s[c]=new Set);for(const l of u)s[c].add(l)}}return s});const a=Hd(()=>{const s=t.options,r=new Map;for(const i of s){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 u of c){if(r.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);r.set(u,i)}}return r});e._zod.parse=(s,r)=>{const i=s.value;if(!bc(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:e}),s;const c=a.value.get(i?.[t.discriminator]);return c?c._zod.run(s,r):t.unionFallback||r.direction==="backward"?n(s,r):(s.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}),s)}}),YR=le("$ZodIntersection",(e,t)=>{Qt.init(e,t),e._zod.parse=(n,a)=>{const s=n.value,r=t.left._zod.run({value:s,issues:[]},a),i=t.right._zod.run({value:s,issues:[]},a);return r instanceof Promise||i instanceof Promise?Promise.all([r,i]).then(([u,l])=>lv(n,u,l)):lv(n,r,i)}});function Lp(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(ni(e)&&ni(t)){const n=Object.keys(t),a=Object.keys(e).filter(r=>n.indexOf(r)!==-1),s={...e,...t};for(const r of a){const i=Lp(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};s[r]=i.data}return{valid:!0,data:s}}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 s=e[a],r=t[a],i=Lp(s,r);if(!i.valid)return{valid:!1,mergeErrorPath:[a,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function lv(e,t,n){const a=new Map;let s;for(const c of t.issues)if(c.code==="unrecognized_keys"){s??(s=c);for(const u of c.keys)a.has(u)||a.set(u,{}),a.get(u).l=!0}else e.issues.push(c);for(const c of n.issues)if(c.code==="unrecognized_keys")for(const u of c.keys)a.has(u)||a.set(u,{}),a.get(u).r=!0;else e.issues.push(c);const r=[...a].filter(([,c])=>c.l&&c.r).map(([c])=>c);if(r.length&&s&&e.issues.push({...s,keys:r}),No(e))return e;const i=Lp(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 XR=le("$ZodRecord",(e,t)=>{Qt.init(e,t),e._zod.parse=(n,a)=>{const s=n.value;if(!ni(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;const r=[],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=>Bs(b,a,qs())),input:l,path:[l],inst:e});continue}const f=p.value,y=t.valueType._zod.run({value:s[l],issues:[]},a);y instanceof Promise?r.push(y.then(b=>{b.issues.length&&n.issues.push(...Do(l,b.issues)),n.value[f]=b.value})):(y.issues.length&&n.issues.push(...Do(l,y.issues)),n.value[f]=y.value)}let u;for(const l in s)c.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:u})}else{n.value={};for(const c of Reflect.ownKeys(s)){if(c==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,c))continue;let u=t.keyType._zod.run({value:c,issues:[]},a);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof c=="string"&&M0.test(c)&&u.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&&(u=f)}if(u.issues.length){t.mode==="loose"?n.value[c]=s[c]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(f=>Bs(f,a,qs())),input:c,path:[c],inst:e});continue}const p=t.valueType._zod.run({value:s[c],issues:[]},a);p instanceof Promise?r.push(p.then(f=>{f.issues.length&&n.issues.push(...Do(c,f.issues)),n.value[u.value]=f.value})):(p.issues.length&&n.issues.push(...Do(c,p.issues)),n.value[u.value]=p.value)}}return r.length?Promise.all(r).then(()=>n):n}}),eP=le("$ZodEnum",(e,t)=>{Qt.init(e,t);const n=I0(t.entries),a=new Set(n);e._zod.values=a,e._zod.pattern=new RegExp(`^(${n.filter(s=>cC.has(typeof s)).map(s=>typeof s=="string"?ai(s):s.toString()).join("|")})$`),e._zod.parse=(s,r)=>{const i=s.value;return a.has(i)||s.issues.push({code:"invalid_value",values:n,input:i,inst:e}),s}}),tP=le("$ZodLiteral",(e,t)=>{if(Qt.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"?ai(a):a?ai(a.toString()):String(a)).join("|")})$`),e._zod.parse=(a,s)=>{const r=a.value;return n.has(r)||a.issues.push({code:"invalid_value",values:t.values,input:r,inst:e}),a}}),nP=le("$ZodTransform",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new w0(e.constructor.name);const s=t.transform(n.value,n);if(a.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(n.value=i,n.fallback=!0,n));if(s instanceof Promise)throw new Zo;return n.value=s,n.fallback=!0,n}});function dv(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const q0=le("$ZodOptional",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",St(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bf(n.source)})?$`):void 0}),e._zod.parse=(n,a)=>{if(t.innerType._zod.optin==="optional"){const s=n.value,r=t.innerType._zod.run(n,a);return r instanceof Promise?r.then(i=>dv(i,s)):dv(r,s)}return n.value===void 0?n:t.innerType._zod.run(n,a)}}),aP=le("$ZodExactOptional",(e,t)=>{q0.init(e,t),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,a)=>t.innerType._zod.run(n,a)}),sP=le("$ZodNullable",(e,t)=>{Qt.init(e,t),St(e._zod,"optin",()=>t.innerType._zod.optin),St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Bf(n.source)}|null)$`):void 0}),St(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)}),rP=le("$ZodDefault",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",St(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 s=t.innerType._zod.run(n,a);return s instanceof Promise?s.then(r=>uv(r,t)):uv(s,t)}});function uv(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const oP=le("$ZodPrefault",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",St(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))}),iP=le("$ZodNonOptional",(e,t)=>{Qt.init(e,t),St(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 s=t.innerType._zod.run(n,a);return s instanceof Promise?s.then(r=>mv(r,e)):mv(s,e)}});function mv(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 cP=le("$ZodCatch",(e,t)=>{Qt.init(e,t),e._zod.optin="optional",St(e._zod,"optout",()=>t.innerType._zod.optout),St(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const s=t.innerType._zod.run(n,a);return s instanceof Promise?s.then(r=>(n.value=r.value,r.issues.length&&(n.value=t.catchValue({...n,error:{issues:r.issues.map(i=>Bs(i,a,qs()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(r=>Bs(r,a,qs()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),B0=le("$ZodPipe",(e,t)=>{Qt.init(e,t),St(e._zod,"values",()=>t.in._zod.values),St(e._zod,"optin",()=>t.in._zod.optin),St(e._zod,"optout",()=>t.out._zod.optout),St(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,a)=>{if(a.direction==="backward"){const r=t.out._zod.run(n,a);return r instanceof Promise?r.then(i=>wl(i,t.in,a)):wl(r,t.in,a)}const s=t.in._zod.run(n,a);return s instanceof Promise?s.then(r=>wl(r,t.out,a)):wl(s,t.out,a)}});function wl(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 lP=le("$ZodPreprocess",(e,t)=>{B0.init(e,t)}),dP=le("$ZodReadonly",(e,t)=>{Qt.init(e,t),St(e._zod,"propValues",()=>t.innerType._zod.propValues),St(e._zod,"values",()=>t.innerType._zod.values),St(e._zod,"optin",()=>t.innerType?._zod?.optin),St(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,a)=>{if(a.direction==="backward")return t.innerType._zod.run(n,a);const s=t.innerType._zod.run(n,a);return s instanceof Promise?s.then(pv):pv(s)}});function pv(e){return e.value=Object.freeze(e.value),e}const uP=le("$ZodLazy",(e,t)=>{Qt.init(e,t),St(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),St(e._zod,"pattern",()=>e._zod.innerType?._zod?.pattern),St(e._zod,"propValues",()=>e._zod.innerType?._zod?.propValues),St(e._zod,"optin",()=>e._zod.innerType?._zod?.optin??void 0),St(e._zod,"optout",()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(n,a)=>e._zod.innerType._zod.run(n,a)}),mP=le("$ZodCustom",(e,t)=>{sa.init(e,t),Qt.init(e,t),e._zod.parse=(n,a)=>n,e._zod.check=n=>{const a=n.value,s=t.fn(a);if(s instanceof Promise)return s.then(r=>fv(r,n,a,e));fv(s,n,a,e)}});function fv(e,t,n,a){if(!e){const s={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(s.params=a._zod.def.params),t.issues.push(yc(s))}}var hv;class pP{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 s={...a,...this._map.get(t)};return Object.keys(s).length?s:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function fP(){return new pP}(hv=globalThis).__zod_globalRegistry??(hv.__zod_globalRegistry=fP());const Xi=globalThis.__zod_globalRegistry;function hP(e,t){return new e({type:"string",...Ue(t)})}function gP(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Ue(t)})}function gv(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Ue(t)})}function F0(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Ue(t)})}function vP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ue(t)})}function bP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ue(t)})}function yP(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ue(t)})}function SP(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Ue(t)})}function xP(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Ue(t)})}function kP(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ue(t)})}function wP(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Ue(t)})}function IP(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ue(t)})}function _P(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Ue(t)})}function CP(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Ue(t)})}function RP(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ue(t)})}function PP(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ue(t)})}function TP(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ue(t)})}function AP(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ue(t)})}function EP(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ue(t)})}function jP(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Ue(t)})}function MP(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Ue(t)})}function OP(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Ue(t)})}function $P(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Ue(t)})}function NP(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ue(t)})}function DP(e,t){return new e({type:"string",format:"date",check:"string_format",...Ue(t)})}function LP(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Ue(t)})}function zP(e,t){return new e({type:"string",format:"duration",check:"string_format",...Ue(t)})}function HP(e,t){return new e({type:"number",checks:[],...Ue(t)})}function zW(e,t){return new e({type:"number",coerce:!0,checks:[],...Ue(t)})}function UP(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Ue(t)})}function qP(e,t){return new e({type:"boolean",...Ue(t)})}function BP(e,t){return new e({type:"null",...Ue(t)})}function FP(e){return new e({type:"unknown"})}function VP(e,t){return new e({type:"never",...Ue(t)})}function vv(e,t){return new $0({check:"less_than",...Ue(t),value:e,inclusive:!1})}function Dm(e,t){return new $0({check:"less_than",...Ue(t),value:e,inclusive:!0})}function bv(e,t){return new N0({check:"greater_than",...Ue(t),value:e,inclusive:!1})}function Lm(e,t){return new N0({check:"greater_than",...Ue(t),value:e,inclusive:!0})}function yv(e,t){return new sR({check:"multiple_of",...Ue(t),value:e})}function V0(e,t){return new oR({check:"max_length",...Ue(t),maximum:e})}function gd(e,t){return new iR({check:"min_length",...Ue(t),minimum:e})}function K0(e,t){return new cR({check:"length_equals",...Ue(t),length:e})}function KP(e,t){return new lR({check:"string_format",format:"regex",...Ue(t),pattern:e})}function WP(e){return new dR({check:"string_format",format:"lowercase",...Ue(e)})}function GP(e){return new uR({check:"string_format",format:"uppercase",...Ue(e)})}function ZP(e,t){return new mR({check:"string_format",format:"includes",...Ue(t),includes:e})}function JP(e,t){return new pR({check:"string_format",format:"starts_with",...Ue(t),prefix:e})}function QP(e,t){return new fR({check:"string_format",format:"ends_with",...Ue(t),suffix:e})}function gi(e){return new hR({check:"overwrite",tx:e})}function YP(e){return gi(t=>t.normalize(e))}function XP(){return gi(e=>e.trim())}function eT(){return gi(e=>e.toLowerCase())}function tT(){return gi(e=>e.toUpperCase())}function nT(){return gi(e=>oC(e))}function aT(e,t,n){return new e({type:"array",element:t,...Ue(n)})}function sT(e,t,n){const a=Ue(n);return a.abort??(a.abort=!0),new e({type:"custom",check:"custom",fn:t,...a})}function rT(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Ue(n)})}function oT(e,t){const n=iT(a=>(a.addIssue=s=>{if(typeof s=="string")a.issues.push(yc(s,a.value,n._zod.def));else{const r=s;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),a.issues.push(yc(r))}},e(a.value,a)),t);return n}function iT(e,t){const n=new sa({check:"custom",...Ue(t)});return n._zod.check=e,n}function W0(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??Xi,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 on(e,t,n={path:[],schemaPath:[]}){var a;const s=e._zod.def,r=t.seen.get(e);if(r)return r.count++,n.schemaPath.includes(e)&&(r.cycle=n.path),r.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 y=i.schema,b=t.processors[s.type];if(!b)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${s.type}`);b(e,t,y,p)}const f=e._zod.parent;f&&(i.ref||(i.ref=f),on(f,t,p),t.seen.get(f).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&Object.assign(i.schema,u),t.io==="input"&&Fn(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 G0(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 u=a.get(c);if(u&&u!==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 s=i=>{const c=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const f=e.external.registry.get(i[0])?.id,y=e.external.uri??(I=>I);if(f)return{ref:y(f)};const b=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=b,{defId:b,ref:`${y("__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}},r=i=>{if(i[1].schema.$ref)return;const c=i[1],{ref:u,defId:l}=s(i);c.def={...c.schema},l&&(c.defId=l);const p=c.schema;for(const f in p)delete p[f];p.$ref=u};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]){r(i);continue}if(e.external){const l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){r(i);continue}}if(e.metadataRegistry.get(i[0])?.id){r(i);continue}if(c.cycle){r(i);continue}if(c.count>1&&e.reused==="ref"){r(i);continue}}}function Z0(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 u=e.seen.get(c);if(u.ref===null)return;const l=u.def??u.schema,p={...l},f=u.ref;if(u.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 y=c._zod.parent;if(y&&y!==f){a(y);const b=e.seen.get(y);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:u.path??[]})};for(const c of[...e.seen.entries()].reverse())a(c[0]);const s={};if(e.target==="draft-2020-12"?s.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?s.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?s.$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");s.$id=e.external.uri(c)}Object.assign(s,n.def??n.schema);const r=e.metadataRegistry.get(t)?.id;r!==void 0&&s.id===r&&delete s.id;const i=e.external?.defs??{};for(const c of e.seen.entries()){const u=c[1];u.def&&u.defId&&(u.def.id===u.defId&&delete u.def.id,i[u.defId]=u.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?s.$defs=i:s.definitions=i);try{const c=JSON.parse(JSON.stringify(s));return Object.defineProperty(c,"~standard",{value:{...t["~standard"],jsonSchema:{input:vd(t,"input",e.processors),output:vd(t,"output",e.processors)}},enumerable:!1,writable:!1}),c}catch{throw new Error("Error converting schema to JSON.")}}function Fn(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 Fn(a.element,n);if(a.type==="set")return Fn(a.valueType,n);if(a.type==="lazy")return Fn(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 Fn(a.innerType,n);if(a.type==="intersection")return Fn(a.left,n)||Fn(a.right,n);if(a.type==="record"||a.type==="map")return Fn(a.keyType,n)||Fn(a.valueType,n);if(a.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:Fn(a.in,n)||Fn(a.out,n);if(a.type==="object"){for(const s in a.shape)if(Fn(a.shape[s],n))return!0;return!1}if(a.type==="union"){for(const s of a.options)if(Fn(s,n))return!0;return!1}if(a.type==="tuple"){for(const s of a.items)if(Fn(s,n))return!0;return!!(a.rest&&Fn(a.rest,n))}return!1}const cT=(e,t={})=>n=>{const a=W0({...n,processors:t});return on(e,a),G0(a,e),Z0(a,e)},vd=(e,t,n={})=>a=>{const{libraryOptions:s,target:r}=a??{},i=W0({...s??{},target:r,io:t,processors:n});return on(e,i),G0(i,e),Z0(i,e)},lT={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dT=(e,t,n,a)=>{const s=n;s.type="string";const{minimum:r,maximum:i,format:c,patterns:u,contentEncoding:l}=e._zod.bag;if(typeof r=="number"&&(s.minLength=r),typeof i=="number"&&(s.maxLength=i),c&&(s.format=lT[c]??c,s.format===""&&delete s.format,c==="time"&&delete s.format),l&&(s.contentEncoding=l),u&&u.size>0){const p=[...u];p.length===1?s.pattern=p[0].source:p.length>1&&(s.allOf=[...p.map(f=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},uT=(e,t,n,a)=>{const s=n,{minimum:r,maximum:i,format:c,multipleOf:u,exclusiveMaximum:l,exclusiveMinimum:p}=e._zod.bag;typeof c=="string"&&c.includes("int")?s.type="integer":s.type="number";const f=typeof p=="number"&&p>=(r??Number.NEGATIVE_INFINITY),y=typeof l=="number"&&l<=(i??Number.POSITIVE_INFINITY),b=t.target==="draft-04"||t.target==="openapi-3.0";f?b?(s.minimum=p,s.exclusiveMinimum=!0):s.exclusiveMinimum=p:typeof r=="number"&&(s.minimum=r),y?b?(s.maximum=l,s.exclusiveMaximum=!0):s.exclusiveMaximum=l:typeof i=="number"&&(s.maximum=i),typeof u=="number"&&(s.multipleOf=u)},mT=(e,t,n,a)=>{n.type="boolean"},pT=(e,t,n,a)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},fT=(e,t,n,a)=>{n.not={}},hT=(e,t,n,a)=>{},gT=(e,t,n,a)=>{const s=e._zod.def,r=I0(s.entries);r.every(i=>typeof i=="number")&&(n.type="number"),r.every(i=>typeof i=="string")&&(n.type="string"),n.enum=r},vT=(e,t,n,a)=>{const s=e._zod.def,r=[];for(const i of s.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");r.push(Number(i))}else r.push(i);if(r.length!==0)if(r.length===1){const i=r[0];n.type=i===null?"null":typeof i,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[i]:n.const=i}else r.every(i=>typeof i=="number")&&(n.type="number"),r.every(i=>typeof i=="string")&&(n.type="string"),r.every(i=>typeof i=="boolean")&&(n.type="boolean"),r.every(i=>i===null)&&(n.type="null"),n.enum=r},bT=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},yT=(e,t,n,a)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},ST=(e,t,n,a)=>{const s=n,r=e._zod.def,{minimum:i,maximum:c}=e._zod.bag;typeof i=="number"&&(s.minItems=i),typeof c=="number"&&(s.maxItems=c),s.type="array",s.items=on(r.element,t,{...a,path:[...a.path,"items"]})},xT=(e,t,n,a)=>{const s=n,r=e._zod.def;s.type="object",s.properties={};const i=r.shape;for(const l in i)s.properties[l]=on(i[l],t,{...a,path:[...a.path,"properties",l]});const c=new Set(Object.keys(i)),u=new Set([...c].filter(l=>{const p=r.shape[l]._zod;return t.io==="input"?p.optin===void 0:p.optout===void 0}));u.size>0&&(s.required=Array.from(u)),r.catchall?._zod.def.type==="never"?s.additionalProperties=!1:r.catchall?r.catchall&&(s.additionalProperties=on(r.catchall,t,{...a,path:[...a.path,"additionalProperties"]})):t.io==="output"&&(s.additionalProperties=!1)},kT=(e,t,n,a)=>{const s=e._zod.def,r=s.inclusive===!1,i=s.options.map((c,u)=>on(c,t,{...a,path:[...a.path,r?"oneOf":"anyOf",u]}));r?n.oneOf=i:n.anyOf=i},wT=(e,t,n,a)=>{const s=e._zod.def,r=on(s.left,t,{...a,path:[...a.path,"allOf",0]}),i=on(s.right,t,{...a,path:[...a.path,"allOf",1]}),c=l=>"allOf"in l&&Object.keys(l).length===1,u=[...c(r)?r.allOf:[r],...c(i)?i.allOf:[i]];n.allOf=u},IT=(e,t,n,a)=>{const s=n,r=e._zod.def;s.type="object";const i=r.keyType,u=i._zod.bag?.patterns;if(r.mode==="loose"&&u&&u.size>0){const p=on(r.valueType,t,{...a,path:[...a.path,"patternProperties","*"]});s.patternProperties={};for(const f of u)s.patternProperties[f.source]=p}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(s.propertyNames=on(r.keyType,t,{...a,path:[...a.path,"propertyNames"]})),s.additionalProperties=on(r.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&&(s.required=p)}},_T=(e,t,n,a)=>{const s=e._zod.def,r=on(s.innerType,t,a),i=t.seen.get(e);t.target==="openapi-3.0"?(i.ref=s.innerType,n.nullable=!0):n.anyOf=[r,{type:"null"}]},CT=(e,t,n,a)=>{const s=e._zod.def;on(s.innerType,t,a);const r=t.seen.get(e);r.ref=s.innerType},RT=(e,t,n,a)=>{const s=e._zod.def;on(s.innerType,t,a);const r=t.seen.get(e);r.ref=s.innerType,n.default=JSON.parse(JSON.stringify(s.defaultValue))},PT=(e,t,n,a)=>{const s=e._zod.def;on(s.innerType,t,a);const r=t.seen.get(e);r.ref=s.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(s.defaultValue)))},TT=(e,t,n,a)=>{const s=e._zod.def;on(s.innerType,t,a);const r=t.seen.get(e);r.ref=s.innerType;let i;try{i=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i},AT=(e,t,n,a)=>{const s=e._zod.def,r=s.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?r?s.out:s.in:s.out;on(i,t,a);const c=t.seen.get(e);c.ref=i},ET=(e,t,n,a)=>{const s=e._zod.def;on(s.innerType,t,a);const r=t.seen.get(e);r.ref=s.innerType,n.readOnly=!0},J0=(e,t,n,a)=>{const s=e._zod.def;on(s.innerType,t,a);const r=t.seen.get(e);r.ref=s.innerType},jT=(e,t,n,a)=>{const s=e._zod.innerType;on(s,t,a);const r=t.seen.get(e);r.ref=s},MT=le("ZodISODateTime",(e,t)=>{TR.init(e,t),nn.init(e,t)});function ta(e){return NP(MT,e)}const OT=le("ZodISODate",(e,t)=>{AR.init(e,t),nn.init(e,t)});function $T(e){return DP(OT,e)}const NT=le("ZodISOTime",(e,t)=>{ER.init(e,t),nn.init(e,t)});function DT(e){return LP(NT,e)}const LT=le("ZodISODuration",(e,t)=>{jR.init(e,t),nn.init(e,t)});function zT(e){return zP(LT,e)}const Q0=(e,t)=>{P0.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>SC(e,n)},flatten:{value:n=>yC(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,Dp,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,Dp,2)}},isEmpty:{get(){return e.issues.length===0}}})},HT=le("ZodError",Q0),Ra=le("ZodError",Q0,{Parent:Error}),UT=Vf(Ra),qT=Kf(Ra),BT=Ud(Ra),FT=qd(Ra),VT=wC(Ra),KT=IC(Ra),WT=_C(Ra),GT=CC(Ra),ZT=RC(Ra),JT=PC(Ra),QT=TC(Ra),YT=AC(Ra),Sv=new WeakMap;function Dc(e,t,n){const a=Object.getPrototypeOf(e);let s=Sv.get(a);if(s||(s=new Set,Sv.set(a,s)),!s.has(t)){s.add(t);for(const r in n){const i=n[r];Object.defineProperty(a,r,{configurable:!0,enumerable:!1,get(){const c=i.bind(this);return Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:c}),c},set(c){Object.defineProperty(this,r,{configurable:!0,writable:!0,enumerable:!0,value:c})}})}}}const Yt=le("ZodType",(e,t)=>(Qt.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:vd(e,"input"),output:vd(e,"output")}}),e.toJSONSchema=cT(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,a)=>UT(e,n,a,{callee:e.parse}),e.safeParse=(n,a)=>BT(e,n,a),e.parseAsync=async(n,a)=>qT(e,n,a,{callee:e.parseAsync}),e.safeParseAsync=async(n,a)=>FT(e,n,a),e.spa=e.safeParseAsync,e.encode=(n,a)=>VT(e,n,a),e.decode=(n,a)=>KT(e,n,a),e.encodeAsync=async(n,a)=>WT(e,n,a),e.decodeAsync=async(n,a)=>GT(e,n,a),e.safeEncode=(n,a)=>ZT(e,n,a),e.safeDecode=(n,a)=>JT(e,n,a),e.safeEncodeAsync=async(n,a)=>QT(e,n,a),e.safeDecodeAsync=async(n,a)=>YT(e,n,a),Dc(e,"ZodType",{check(...n){const a=this.def;return this.clone(hr(a,{checks:[...a.checks??[],...n.map(s=>typeof s=="function"?{_zod:{check:s,def:{check:"custom"},onattach:[]}}:s)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,a){return gr(this,n,a)},brand(){return this},register(n,a){return n.add(this,a),this},refine(n,a){return this.check(BA(n,a))},superRefine(n,a){return this.check(FA(n,a))},overwrite(n){return this.check(gi(n))},optional(){return Iv(this)},exactOptional(){return TA(this)},nullable(){return _v(this)},nullish(){return Iv(_v(this))},nonoptional(n){return $A(this,n)},array(){return v(this)},or(n){return gt([this,n])},and(n){return _A(this,n)},transform(n){return Cv(this,sS(n))},default(n){return jA(this,n)},prefault(n){return OA(this,n)},catch(n){return DA(this,n)},pipe(n){return Cv(this,n)},readonly(){return HA(this)},describe(n){const a=this.clone();return Xi.add(a,{description:n}),a},meta(...n){if(n.length===0)return Xi.get(this);const a=this.clone();return Xi.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 Xi.get(e)?.description},configurable:!0}),e)),Y0=le("_ZodString",(e,t)=>{Wf.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,s,r)=>dT(e,a,s);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Dc(e,"_ZodString",{regex(...a){return this.check(KP(...a))},includes(...a){return this.check(ZP(...a))},startsWith(...a){return this.check(JP(...a))},endsWith(...a){return this.check(QP(...a))},min(...a){return this.check(gd(...a))},max(...a){return this.check(V0(...a))},length(...a){return this.check(K0(...a))},nonempty(...a){return this.check(gd(1,...a))},lowercase(a){return this.check(WP(a))},uppercase(a){return this.check(GP(a))},trim(){return this.check(XP())},normalize(...a){return this.check(YP(...a))},toLowerCase(){return this.check(eT())},toUpperCase(){return this.check(tT())},slugify(){return this.check(nT())}})}),XT=le("ZodString",(e,t)=>{Wf.init(e,t),Y0.init(e,t),e.email=n=>e.check(gP(eA,n)),e.url=n=>e.check(SP(tA,n)),e.jwt=n=>e.check($P(gA,n)),e.emoji=n=>e.check(xP(nA,n)),e.guid=n=>e.check(gv(xv,n)),e.uuid=n=>e.check(F0(ec,n)),e.uuidv4=n=>e.check(vP(ec,n)),e.uuidv6=n=>e.check(bP(ec,n)),e.uuidv7=n=>e.check(yP(ec,n)),e.nanoid=n=>e.check(kP(aA,n)),e.guid=n=>e.check(gv(xv,n)),e.cuid=n=>e.check(wP(sA,n)),e.cuid2=n=>e.check(IP(rA,n)),e.ulid=n=>e.check(_P(oA,n)),e.base64=n=>e.check(jP(pA,n)),e.base64url=n=>e.check(MP(fA,n)),e.xid=n=>e.check(CP(iA,n)),e.ksuid=n=>e.check(RP(cA,n)),e.ipv4=n=>e.check(PP(lA,n)),e.ipv6=n=>e.check(TP(dA,n)),e.cidrv4=n=>e.check(AP(uA,n)),e.cidrv6=n=>e.check(EP(mA,n)),e.e164=n=>e.check(OP(hA,n)),e.datetime=n=>e.check(ta(n)),e.date=n=>e.check($T(n)),e.time=n=>e.check(DT(n)),e.duration=n=>e.check(zT(n))});function o(e){return hP(XT,e)}const nn=le("ZodStringFormat",(e,t)=>{tn.init(e,t),Y0.init(e,t)}),eA=le("ZodEmail",(e,t)=>{SR.init(e,t),nn.init(e,t)}),xv=le("ZodGUID",(e,t)=>{bR.init(e,t),nn.init(e,t)}),ec=le("ZodUUID",(e,t)=>{yR.init(e,t),nn.init(e,t)});function X0(e){return F0(ec,e)}const tA=le("ZodURL",(e,t)=>{xR.init(e,t),nn.init(e,t)}),nA=le("ZodEmoji",(e,t)=>{kR.init(e,t),nn.init(e,t)}),aA=le("ZodNanoID",(e,t)=>{wR.init(e,t),nn.init(e,t)}),sA=le("ZodCUID",(e,t)=>{IR.init(e,t),nn.init(e,t)}),rA=le("ZodCUID2",(e,t)=>{_R.init(e,t),nn.init(e,t)}),oA=le("ZodULID",(e,t)=>{CR.init(e,t),nn.init(e,t)}),iA=le("ZodXID",(e,t)=>{RR.init(e,t),nn.init(e,t)}),cA=le("ZodKSUID",(e,t)=>{PR.init(e,t),nn.init(e,t)}),lA=le("ZodIPv4",(e,t)=>{MR.init(e,t),nn.init(e,t)}),dA=le("ZodIPv6",(e,t)=>{OR.init(e,t),nn.init(e,t)}),uA=le("ZodCIDRv4",(e,t)=>{$R.init(e,t),nn.init(e,t)}),mA=le("ZodCIDRv6",(e,t)=>{NR.init(e,t),nn.init(e,t)}),pA=le("ZodBase64",(e,t)=>{DR.init(e,t),nn.init(e,t)}),fA=le("ZodBase64URL",(e,t)=>{zR.init(e,t),nn.init(e,t)}),hA=le("ZodE164",(e,t)=>{HR.init(e,t),nn.init(e,t)}),gA=le("ZodJWT",(e,t)=>{qR.init(e,t),nn.init(e,t)}),eS=le("ZodNumber",(e,t)=>{L0.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,s,r)=>uT(e,a,s),Dc(e,"ZodNumber",{gt(a,s){return this.check(bv(a,s))},gte(a,s){return this.check(Lm(a,s))},min(a,s){return this.check(Lm(a,s))},lt(a,s){return this.check(vv(a,s))},lte(a,s){return this.check(Dm(a,s))},max(a,s){return this.check(Dm(a,s))},int(a){return this.check(kv(a))},safe(a){return this.check(kv(a))},positive(a){return this.check(bv(0,a))},nonnegative(a){return this.check(Lm(0,a))},negative(a){return this.check(vv(0,a))},nonpositive(a){return this.check(Dm(0,a))},multipleOf(a,s){return this.check(yv(a,s))},step(a,s){return this.check(yv(a,s))},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 HP(eS,e)}const vA=le("ZodNumberFormat",(e,t)=>{BR.init(e,t),eS.init(e,t)});function kv(e){return UP(vA,e)}const bA=le("ZodBoolean",(e,t)=>{FR.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>mT(e,n,a)});function j(e){return qP(bA,e)}const yA=le("ZodNull",(e,t)=>{VR.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>pT(e,n,a)});function vi(e){return BP(yA,e)}const SA=le("ZodUnknown",(e,t)=>{KR.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>hT()});function Ie(){return FP(SA)}const xA=le("ZodNever",(e,t)=>{WR.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>fT(e,n,a)});function tS(e){return VP(xA,e)}const kA=le("ZodArray",(e,t)=>{GR.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>ST(e,n,a,s),e.element=t.element,Dc(e,"ZodArray",{min(n,a){return this.check(gd(n,a))},nonempty(n){return this.check(gd(1,n))},max(n,a){return this.check(V0(n,a))},length(n,a){return this.check(K0(n,a))},unwrap(){return this.element}})});function v(e,t){return aT(kA,e,t)}const nS=le("ZodObject",(e,t)=>{JR.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>xT(e,n,a,s),St(e,"shape",()=>t.shape),Dc(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:Ie()})},loose(){return this.clone({...this._zod.def,catchall:Ie()})},strict(){return this.clone({...this._zod.def,catchall:tS()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return pC(this,n)},safeExtend(n){return fC(this,n)},merge(n){return hC(this,n)},pick(n){return uC(this,n)},omit(n){return mC(this,n)},partial(...n){return gC(rS,this,n[0])},required(...n){return vC(oS,this,n[0])}})});function d(e,t){const n={type:"object",shape:e??{},...Ue(t)};return new nS(n)}function zm(e,t){return new nS({type:"object",shape:e,catchall:tS(),...Ue(t)})}const aS=le("ZodUnion",(e,t)=>{U0.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>kT(e,n,a,s),e.options=t.options});function gt(e,t){return new aS({type:"union",options:e,...Ue(t)})}const wA=le("ZodDiscriminatedUnion",(e,t)=>{aS.init(e,t),QR.init(e,t)});function pt(e,t,n){return new wA({type:"union",options:t,discriminator:e,...Ue(n)})}const IA=le("ZodIntersection",(e,t)=>{YR.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>wT(e,n,a,s)});function _A(e,t){return new IA({type:"intersection",left:e,right:t})}const wv=le("ZodRecord",(e,t)=>{XR.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>IT(e,n,a,s),e.keyType=t.keyType,e.valueType=t.valueType});function Se(e,t,n){return!t||!t._zod?new wv({type:"record",keyType:o(),valueType:e,...Ue(t)}):new wv({type:"record",keyType:e,valueType:t,...Ue(n)})}const zp=le("ZodEnum",(e,t)=>{eP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(a,s,r)=>gT(e,a,s),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(a,s)=>{const r={};for(const i of a)if(n.has(i))r[i]=t.entries[i];else throw new Error(`Key ${i} not found in enum`);return new zp({...t,checks:[],...Ue(s),entries:r})},e.exclude=(a,s)=>{const r={...t.entries};for(const i of a)if(n.has(i))delete r[i];else throw new Error(`Key ${i} not found in enum`);return new zp({...t,checks:[],...Ue(s),entries:r})}});function k(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e;return new zp({type:"enum",entries:n,...Ue(t)})}const CA=le("ZodLiteral",(e,t)=>{tP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>vT(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 CA({type:"literal",values:Array.isArray(e)?e:[e],...Ue(t)})}const RA=le("ZodTransform",(e,t)=>{nP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>yT(e,n),e._zod.parse=(n,a)=>{if(a.direction==="backward")throw new w0(e.constructor.name);n.addIssue=r=>{if(typeof r=="string")n.issues.push(yc(r,n.value,t));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),n.issues.push(yc(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(r=>(n.value=r,n.fallback=!0,n)):(n.value=s,n.fallback=!0,n)}});function sS(e){return new RA({type:"transform",transform:e})}const rS=le("ZodOptional",(e,t)=>{q0.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>J0(e,n,a,s),e.unwrap=()=>e._zod.def.innerType});function Iv(e){return new rS({type:"optional",innerType:e})}const PA=le("ZodExactOptional",(e,t)=>{aP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>J0(e,n,a,s),e.unwrap=()=>e._zod.def.innerType});function TA(e){return new PA({type:"optional",innerType:e})}const AA=le("ZodNullable",(e,t)=>{sP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>_T(e,n,a,s),e.unwrap=()=>e._zod.def.innerType});function _v(e){return new AA({type:"nullable",innerType:e})}const EA=le("ZodDefault",(e,t)=>{rP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>RT(e,n,a,s),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function jA(e,t){return new EA({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():C0(t)}})}const MA=le("ZodPrefault",(e,t)=>{oP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>PT(e,n,a,s),e.unwrap=()=>e._zod.def.innerType});function OA(e,t){return new MA({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():C0(t)}})}const oS=le("ZodNonOptional",(e,t)=>{iP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>CT(e,n,a,s),e.unwrap=()=>e._zod.def.innerType});function $A(e,t){return new oS({type:"nonoptional",innerType:e,...Ue(t)})}const NA=le("ZodCatch",(e,t)=>{cP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>TT(e,n,a,s),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function DA(e,t){return new NA({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const iS=le("ZodPipe",(e,t)=>{B0.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>AT(e,n,a,s),e.in=t.in,e.out=t.out});function Cv(e,t){return new iS({type:"pipe",in:e,out:t})}const LA=le("ZodPreprocess",(e,t)=>{iS.init(e,t),lP.init(e,t)}),zA=le("ZodReadonly",(e,t)=>{dP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>ET(e,n,a,s),e.unwrap=()=>e._zod.def.innerType});function HA(e){return new zA({type:"readonly",innerType:e})}const UA=le("ZodLazy",(e,t)=>{uP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>jT(e,n,a,s),e.unwrap=()=>e._zod.def.getter()});function qA(e){return new UA({type:"lazy",getter:e})}const cS=le("ZodCustom",(e,t)=>{mP.init(e,t),Yt.init(e,t),e._zod.processJSONSchema=(n,a,s)=>bT(e,n)});function Hm(e,t){return sT(cS,(()=>!0),t)}function BA(e,t={}){return rT(cS,e,t)}function FA(e,t){return oT(e,t)}function dr(e){const t=qA(()=>gt([o(e),m(),j(),vi(),v(t),Se(o(),t)]));return t}function VA(e,t){return new LA({type:"pipe",in:sS(e),out:t})}const KA=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),WA=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 GA=class lS{state=new Uint32Array(KA);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 s=Math.min(64-this.pendingLength,n.length);this.pending.set(n.subarray(0,s),this.pendingLength),this.pendingLength+=s,a+=s,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 lS;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,s=new DataView(n.buffer);return s.setUint32(n.length-8,Math.floor(a/4294967296),!1),s.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,r=>r.toString(16).padStart(8,"0")).join("")}compress(t){const n=new DataView(t.buffer,t.byteOffset,64),a=this.state,s=this.words;for(let b=0;b<16;b+=1)s[b]=n.getUint32(b*4,!1);for(let b=16;b<64;b+=1){const I=s[b-15],C=s[b-2],P=as(I,7)^as(I,18)^I>>>3,_=as(C,17)^as(C,19)^C>>>10;s[b]=s[b-16]+P+s[b-7]+_>>>0}let r=a[0],i=a[1],c=a[2],u=a[3],l=a[4],p=a[5],f=a[6],y=a[7];for(let b=0;b<64;b+=1){const I=l&p^~l&f,C=r&i^r&c^i&c,P=as(r,2)^as(r,13)^as(r,22),_=as(l,6)^as(l,11)^as(l,25),M=y+_+I+WA[b]+s[b]>>>0,A=P+C>>>0;y=f,f=p,p=l,l=u+M>>>0,u=c,c=i,i=r,r=M+A>>>0}a[0]=a[0]+r>>>0,a[1]=a[1]+i>>>0,a[2]=a[2]+c>>>0,a[3]=a[3]+u>>>0,a[4]=a[4]+l>>>0,a[5]=a[5]+p>>>0,a[6]=a[6]+f>>>0,a[7]=a[7]+y>>>0}};function ZA(e){return new GA().update(e).digestHex()}function as(e,t){return e>>>t|e<<32-t}const JA=2e3,dS=25e7,E=o().trim().min(1).max(240),W=o().regex(/^[a-f0-9]{64}$/),Ce=o().datetime({offset:!0}),pa=Se(o(),Ie()).default({}),re=d({id:E,contentHash:W}).strict(),Vt=re.extend({revision:m().int().positive()}).strict(),na=d({id:E,path:o().trim().min(1).max(JA).refine(XA),contentHash:W,sizeBytes:m().int().nonnegative().max(dS),mediaType:o().trim().min(1).max(200),visibility:k(["policy","verifier","host_private"])}).strict(),vs=d({id:E,contentHash:W,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:m().int().nonnegative().max(dS).nullable().default(null)}).strict(),Fd=k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function QA(e){return`${JSON.stringify(Hp(e),null,2)}
|
|
72
|
+
`}function Gf(e){return ZA(e)}function Qe(e){return Gf(QA(e))}function YA(e,t){const{contentHash:n,...a}=e,s=Qe(a);if(n!==s)throw new Error(`${t} contentHash is ${n}; expected ${s}.`)}function XA(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Hp(e){return Array.isArray(e)?e.map(Hp):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Hp(n)]))}const Zf=d({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(),Jf=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],uS=k(Jf),cn=d({providerId:uS,modelId:o().trim().min(1).max(300)}),eE=["coding","research","review","test","docs","planner","summarizer"];k(eE);const bi=o().trim().min(1).max(80).regex(/^[a-z][a-z0-9_-]*$/),mS=k(["none","worktree","copy_on_write"]),pS=k(["read_only","workspace_write","full_tools"]),fS=k(["disabled","parent_scoped"]),Vd=k(["manual","balanced","proactive"]),tE=k(["queued","running","completed","failed","cancelled","needs_resume"]),nE=["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(nE);const aE=[{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"}],Qf=d({id:bi,enabled:j().default(!0),modelRef:cn.nullable().default(null),isolationMode:mS.default("none"),maxConcurrentRuns:m().int().min(1).max(16).default(1),toolPolicy:pS.default("read_only"),background:j().default(!0),peerMessages:fS.default("parent_scoped")}),Sc=d({enabled:j().default(!0),workspaceDefaultsVersion:x(1).default(1),toolDefaultsVersion:x(1).default(1),delegationMode:Vd.default("manual"),defaultModelRef:cn.nullable().default(null),roles:v(Qf).max(64).default(()=>vS()),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:fE(e.roles)})),cc=d({kind:k(["session","turn","file","diff","artifact"]),id:o().trim().min(1).max(500),label:o().trim().min(1).max(500)}),sE=d({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})),rE=k(["orient","edit","validate","report"]),oE=d({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)}),iE=d({phase:rE.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(cc).max(100).default([]),validationAttempts:v(oE).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})),cE=d({summary:o().trim().max(2e4).default(""),findings:v(o().trim().min(1).max(5e3)).max(200).default([]),artifacts:v(cc).max(200).default([]),patchRef:cc.nullable().default(null),diffRef:cc.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)}),hS=d({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:bi,objective:o().trim().min(1).max(5e4),modelRef:cn.nullable().default(null),isolationMode:mS.default("none"),toolPolicy:pS.default("read_only"),background:j().default(!0),peerMessages:fS.default("parent_scoped"),status:tE.default("queued"),progress:iE,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:cE.nullable().default(null),metadata:Se(o(),Ie()).optional().default({})}),gS=k(["cleanup","archive","cleanup_and_archive"]);d({action:gS,reason:o().trim().min(1).max(2e3).nullable().default(null)});d({action:gS,run:hS,workspaceCleanup:Se(o(),Ie()).nullable().default(null),sessionArchive:Se(o(),Ie()).nullable().default(null),nextStep:o()});const lE=k(["question","answer","handoff","artifact","status","blocker"]),dE=k(["normal","interrupt"]),uE=d({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)}),mE=d({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:bi.nullable().default(null),kind:lE,priority:dE.optional(),body:o().trim().min(1).max(5e4),refs:v(cc).max(100).default([]),delivery:uE.optional(),createdAt:o()});function vS(){return aE.map(e=>Qf.parse({id:e.id,toolPolicy:e.defaultToolPolicy}))}function pE(){return Sc.parse({})}function fE(e){const t=vS(),n=new Map(t.map(s=>[s.id,s])),a=[];for(const s of e??[]){const r=Qf.parse(s);n.has(r.id)?n.set(r.id,r):a.push(r)}return[...t.map(s=>n.get(s.id)??s),...a]}const hE=d({id:o().trim().min(1).max(80),label:o().trim().min(1).max(160),description:o().trim().max(500).nullable().optional().default(null)}),gE=d({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(hE).max(5).default([]),allowFreeform:j().default(!0),status:k(["pending","answered","dismissed"]),answer:d({optionId:o().trim().min(1).nullable(),text:o().max(4e3)}).nullable(),createdAt:o(),answeredAt:o().nullable()}),vE=d({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("")}),Um="https://openpond.ai",Yf=["slack","google","github","turnkey","x","microsoft_teams","mcp"],Xf={slack:[Gt("slack.channel.bind","Bind channels","Bind Slack channels or threads to OpenPond profiles.","setup",!1),Gt("slack.message.ingest","Ingest messages","Ingest Slack channel or thread activity into OpenPond context.","setup",!1)],microsoft_teams:[Gt("microsoft_teams.channel.bind","Bind channels","Bind Teams channels or chats to OpenPond profiles.","setup",!1),Gt("microsoft_teams.message.ingest","Ingest messages","Ingest Teams channel or chat activity into OpenPond context.","setup",!1)],google:[Gt("google.drive.file.read","Read Drive files","Find and read Google Drive files.","read",!0),Gt("google.drive.file.write","Write Drive files","Create or update approved Google Drive files.","write",!0),Gt("google.docs.read","Read Docs","Read Google Docs content and structure.","read",!0),Gt("google.docs.write","Edit Docs","Apply approved Google Docs edits.","write",!0),Gt("google.comments.read","Read comments","Read Google file comments.","read",!0),Gt("google.comments.write","Write comments","Create or resolve approved Google comments.","write",!0)],github:[Gt("github.repo.read","Read repositories","Read repository metadata and file context.","read",!0),Gt("github.issue.read","Read issues","Read GitHub issues and comments.","read",!0),Gt("github.issue.write","Update issues","Create or update approved GitHub issue content.","write",!0),Gt("github.pull_request.read","Read pull requests","Read pull request metadata, diffs, checks, and reviews.","read",!0),Gt("github.pull_request.write","Update pull requests","Create approved comments or pull request updates.","write",!0)],turnkey:[Gt("turnkey.wallets.read","Read Agent Wallet","Read the connected OpenPond Agent Wallet address and metadata.","read",!0),Gt("turnkey.balances.read","Read wallet balances","Read balances for the connected OpenPond Agent Wallet.","read",!0),Gt("turnkey.activities.read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.","read",!0)],x:[Gt("x.profile.read","Read profile","Read the connected X profile.","read",!0),Gt("x.search.read","Search X","Search public X posts when granted.","read",!0),Gt("x.mentions.read","Read mentions","Read mentions for the connected X account.","read",!0),Gt("x.post.write","Post","Create approved X posts.","write",!0),Gt("x.reply.write","Reply","Create approved X replies.","write",!0)],mcp:[Gt("mcp.tool.discover","Discover tools","Discover team-scoped MCP tools.","tooling",!1),Gt("mcp.tool.call","Call tools","Call approved MCP tools through the team endpoint.","tooling",!1)]},bS={slack:[],microsoft_teams:[],google:[Lt("google.drive.search","search","Search Drive","Search Google Drive files by grounded query.",["google.drive.file.read"]),Lt("google.drive.read_file","read","Read Drive file","Read Drive file metadata or exported content by stable ref.",["google.drive.file.read"],{requiredKeys:["ref"]}),Lt("google.docs.read","read","Read Google Doc","Read Google Docs content and structure by stable ref.",["google.docs.read"],{requiredKeys:["ref"]}),Lt("google.comments.read","read","Read comments","Read comments for a grounded Google file ref.",["google.comments.read"],{requiredKeys:["ref"]}),Lt("google.docs.update","write","Update Google Doc","Apply an explicitly approved Google Docs edit and return readback verification.",["google.docs.write"],{requiredKeys:["ref","patch"]}),Lt("google.comments.create","write","Create comment","Create an explicitly approved Google file comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","body"]}),Lt("google.comments.resolve","write","Resolve comment","Resolve an explicitly approved Google comment and return readback verification.",["google.comments.write"],{requiredKeys:["ref","commentId"]})],github:[Lt("github.repo.search","search","Search repositories","Search accessible repositories by owner, name, or topic.",["github.repo.read"]),Lt("github.issue.search","search","Search issues","Search accessible GitHub issues.",["github.issue.read"]),Lt("github.pull_request.search","search","Search pull requests","Search accessible GitHub pull requests.",["github.pull_request.read"]),Lt("github.repo.read","read","Read repository","Read grounded repository metadata or file context.",["github.repo.read"],{requiredKeys:["ref"]}),Lt("github.issue.read","read","Read issue","Read a grounded GitHub issue and comments.",["github.issue.read"],{requiredKeys:["ref"]}),Lt("github.pull_request.read","read","Read pull request","Read a grounded pull request, checks, reviews, or diff summary.",["github.pull_request.read"],{requiredKeys:["ref"]}),Lt("github.issue.create","write","Create issue","Create an explicitly approved GitHub issue and return readback verification.",["github.issue.write"],{requiredKeys:["repo","title","body"]}),Lt("github.issue.comment","write","Comment on issue","Create an explicitly approved GitHub issue comment and return readback verification.",["github.issue.write"],{requiredKeys:["ref","body"]}),Lt("github.issue.update","write","Update issue","Apply an explicitly approved issue metadata/content update and return readback verification.",["github.issue.write"],{requiredKeys:["ref"]}),Lt("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"]}),Lt("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:[Lt("turnkey.wallets.read","read","Read Agent Wallet","Read the address and metadata for the connected OpenPond Agent Wallet.",["turnkey.wallets.read"]),Lt("turnkey.balances.read","read","Read wallet balances","Read supported-network balances for the connected OpenPond Agent Wallet.",["turnkey.balances.read"]),Lt("turnkey.activities.read","read","Read wallet activity","Read recent Turnkey activity for the connected OpenPond Agent Wallet.",["turnkey.activities.read"])],x:[Lt("x.profile.read","read","Read profile","Read the connected X account profile.",["x.profile.read"]),Lt("x.post.read","read","Read post","Read a public X post by stable ref, status URL, or post id.",["x.search.read"],{requiredKeys:["ref"]}),Lt("x.search.posts","search","Search recent posts","Search public X posts from the X recent-search window by grounded query.",["x.search.read"]),Lt("x.mentions.search","search","Search mentions","Search mentions for the connected X account.",["x.mentions.read"]),Lt("x.mention.read","read","Read mention","Read a grounded mention or post ref.",["x.mentions.read"],{requiredKeys:["ref"]}),Lt("x.post.create","write","Create post","Create an explicitly approved X post and return readback verification.",["x.post.write"],{requiredKeys:["text"]}),Lt("x.reply.create","write","Create reply","Create an explicitly approved X reply and return readback verification.",["x.reply.write"],{requiredKeys:["inReplyToRef","text"]})],mcp:[]},bE={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
|
+
`)},HW=Yf.map(e=>{const t=xS(e),n=bE[e];return{...t,provider:e,body:n,sourceHash:`connected-app-skill:${e}:${AE(n)}`,charCount:n.length}}),yE=[{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"}],Kd=yE,SE=Yf.map(e=>{const t=Kd.filter(a=>a.providerFamily===e),n=t[0];return{id:e,label:lc(e),shortLabel:n.shortLabel,category:n.category,icon:n.icon,description:n.description,setupSurfaces:t,capabilities:Xf[e],skills:IE(e),tools:_E(e),operations:bS[e],leasePolicy:CE(e)}});function yS(e){const t=xE(e);return t?Kd.find(n=>n.id===t)??null:null}function SS(e){const t=eh(e);return t?SE.find(n=>n.id===t)??null:null}function UW(e){const t=yS(e.appId),n=kE(e.baseUrl),a=t?.kind==="mcp"?"/sandboxes/mcp":"/sandboxes/apps",s=new URL(a,n);t?.kind!=="mcp"&&s.searchParams.set("app",t?.deepLinkAppId??e.appId);const r=e.teamId?.trim();return r&&s.searchParams.set("teamId",r),s.toString()}function xE(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Kd.some(n=>n.id===t)?t:null:null}function eh(e){const t=e?.trim().toLowerCase().replace(/[-\s]+/g,"_");return t?t==="teams"||t==="microsoft"?"microsoft_teams":Yf.includes(t)?t:yS(t)?.providerFamily??null:null}function qm(e={}){const t=RE(e.connections??[]);return Kd.map(n=>{const a=SS(n.providerFamily),s=n.statusSource==="integration_connection"?t.filter(c=>c.provider===n.providerFamily):[],r=s.some(c=>c.status==="active"),i=PE(n,r);return{...n,providerLabel:a.label,setupSurfaceLabel:wE(n.setupSurface),status:i,statusLabel:TE(n,i,s),connections:s,connected:r,capabilities:Rv(n,a.capabilities),capabilityLabels:Rv(n,a.capabilities).map(c=>c.label),leasePolicy:a.leasePolicy}})}function Gt(e,t,n,a,s){return{id:e,label:t,description:n,access:a,leaseable:s}}function Lt(e,t,n,a,s,r){return{id:e,operation:t,label:n,description:a,capabilityIds:s,...r?{input:r}:{},requiresReadback:t==="write",requiresRuntimeLease:!1}}function kE(e){const t=e?.trim();if(!t)return Um;try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?Um:(n.pathname="/",n.search="",n.hash="",n.toString())}catch{return Um}}function lc(e){return e==="microsoft_teams"?"Microsoft Teams":e==="mcp"?"OpenPond MCP":e==="x"?"X":e[0].toUpperCase()+e.slice(1)}function wE(e){return e==="native_bot"?"Native app":e==="oauth_connector"?"OAuth connector":e==="wallet_connector"?"Wallet connector":"MCP endpoint"}function IE(e){return[xS(e)]}function xS(e){return{name:`${e}-connected-app`,description:`Use ${lc(e)} safely through connected app tools.`,path:`integration_skills/${e}.md`}}function _E(e){if(e==="mcp")return[];const t=Xf[e],n=bS[e],a=t.filter(i=>i.access==="read").map(i=>i.id),s=t.filter(i=>i.access==="write").map(i=>i.id),r=[];return n.some(i=>i.operation==="search")&&r.push({name:"connected_app_search",description:`Search ${lc(e)} through a server-owned connected app connector.`,capabilityIds:a,write:!1}),n.some(i=>i.operation==="read")&&r.push({name:"connected_app_read",description:`Read a grounded ${lc(e)} object through a server-owned connected app connector.`,capabilityIds:a,write:!1}),s.length>0&&n.some(i=>i.operation==="write")&&r.push({name:"connected_app_write",description:`Perform an explicitly approved ${lc(e)} write through a server-owned connected app connector.`,capabilityIds:s,write:!0}),r}function CE(e){const t=Xf[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 Rv(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 RE(e){return e.flatMap(t=>{const n=eh(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 PE(e,t){return e.statusSource==="integration_connection"?t?"connected":"disconnected":"setup_available"}function TE(e,t,n){if(t==="connected"){const a=n.filter(s=>s.status==="active").length;return a>1?`${a} connected`:"Connected"}return t==="disconnected"?"Not connected":e.statusSource==="native_binding"?"Bot setup":"Configure"}function AE(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 EE="local_path:";function kS(e){return`${EE}${e.trim()}`}d({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 jE=d({path:o(),status:o(),additions:m(),deletions:m(),patch:o(),content:o().nullable().optional().default(null)}),ME=d({appId:o(),repoPath:o(),initialized:j(),dirty:j(),filesChanged:m(),additions:m(),deletions:m(),repoFiles:v(o()).optional().default([]),files:v(jE),error:o().nullable(),updatedAt:o()});d({branch:o().trim().min(1).max(160)});d({path:o().trim().min(1),content:o()});const Pv=d({line:m().int().nonnegative(),character:m().int().nonnegative()}),OE=d({start:Pv,end:Pv}),$E=d({path:o(),range:OE,severity:k(["error","warning","info","hint"]),message:o(),source:o().nullable().optional().default(null),code:o().nullable().optional().default(null)}),wS=d({id:o(),root:o(),status:k(["connected","unavailable","error"]),message:o().nullable().optional().default(null)});d({path:o().trim().min(1),content:o().optional(),waitForDiagnostics:j().optional().default(!0)});d({appId:o(),path:o(),diagnostics:v($E),servers:v(wS),updatedAt:o()});const NE=d({operation:k(["hover","definition","references","documentSymbol"]),path:o().trim().min(1),content:o().optional(),line:m().int().nonnegative().optional(),character:m().int().nonnegative().optional()});d({appId:o(),operation:NE.shape.operation,path:o(),results:Ie(),servers:v(wS),updatedAt:o()});const DE=d({pinned:j().optional(),archived:j().optional(),order:m().optional()});Se(o(),DE);const th="gpt-5.6-sol",si="openpond-chat",Fr="openpond",xc=si,nh="default",ah="high",Wd="ask",yi=uS,sh=k(["default","auto-review","full-access"]),Lc=k(["ask","full-access","disabled"]),Gd=k(["off","low","medium","high","xhigh","max"]),zc=k(["sandbox_app","local_project","sandbox","sandbox_template"]);k(["openpond"]);const LE=k(["provider_usage","provider_tokenizer","model_family","heuristic"]),zE=d({provider:yi,model:o().min(1),usedTokens:m().int().nonnegative(),maxContextTokens:m().int().positive(),usableContextTokens:m().int().positive(),percentFull:m().min(0).max(100),source:LE,updatedAtEventId:o().nullable()}),Up=d({pinned:j().default(!1),projects:j().default(!1),cloudProjects:j().default(!1),chats:j().default(!1),savedForLater:j().default(!0)}),HE=k(["auto","off"]),UE=k(["typescript","python","rust"]),IS=k(["auto","disabled","custom"]),js=d({mode:IS.default("auto"),customCommand:o().trim().max(4096).default("")}),bd=d({languageServers:HE.default("auto"),diagnosticsWhileEditing:j().default(!0),checkOnSave:j().default(!0),languages:d({typescript:js.optional().default(()=>js.parse({})),python:js.optional().default(()=>js.parse({})),rust:js.optional().default(()=>js.parse({}))}).optional().default(()=>({typescript:js.parse({}),python:js.parse({}),rust:js.parse({})}))}),qE=d({language:UE,label:o(),mode:IS,status:k(["found","missing","disabled","error"]),command:o().nullable(),message:o().nullable()});d({settings:bd,languages:v(qE),updatedAt:o()});const BE=d({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()});d({clients:v(BE),maxClients:m().int().positive(),idleTimeoutMs:m().int().positive(),updatedAt:o()});const qp=d({autoEnabled:j().default(!0),triggerPercent:m().int().min(50).max(95).default(85),summaryModel:k(["same_model"]).default("same_model")}),Bp=d({defaultModelRef:cn.nullable().default(null),creationMode:k(["defaults","customize"]).default("customize"),autoApproveEvidence:j().default(!1)});d({defaultChatProvider:yi.default(Fr),defaultChatModel:o().min(1).default(xc),defaultChatModelRef:cn.nullable().optional(),subagents:Sc.optional().default(()=>Sc.parse({})),codexPermissionMode:sh.default(nh),codexReasoningEffort:Gd.default(ah),openPondCommandAccessMode:Lc.default(Wd),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:qp.optional().default(()=>qp.parse({})),training:Bp.optional().default(()=>Bp.parse({})),sidebarWidth:m().int().min(244).max(560).default(332),diffPanelWidth:m().int().min(320).max(2400).default(560),sidebarSectionsCollapsed:Up.optional().default(()=>Up.parse({})),editor:bd.optional().default(()=>bd.parse({}))});const FE="default",VE=[{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.`}],rh=o().trim().min(1).max(120),KE=d({id:rh,name:o(),source:k(["built_in","custom"]).default("custom"),description:o(),content:o()});d({activeTemplateId:rh.default(FE),customized:j().default(!1),soul:o(),soulPath:o().nullable(),updatedAt:o().nullable(),templates:v(KE).default(()=>[...VE])});d({id:o(),host:o(),port:m(),startedAt:o(),storePath:o(),version:o(),runtimeVersion:o()});const oh=k(["chat","work","development"]);k(["chat","models","console","development"]);const WE="work",Ee=o().trim().min(1).nullable(),Pa=Se(o(),Ie()).default({}),GE=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"]),_S=k(["/create","/edit","openpond extend","create_as_agent","suggest_workflow","local_import","lab_create","lab_improve","training"]),ZE=k(["create","improve","import","promote"]),JE=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"]),Il=k(["always_require_plan_approval","approval_already_granted"]);k(["local_profile","hosted_profile","promote_local_to_hosted","managed_artifact"]);const QE=pt("kind",[d({kind:x("local"),sourceAuthority:x("local_profile"),activeProfile:o().trim().min(1).nullable(),repoPath:Ee,sourcePath:Ee,localHead:Ee,confirmationPolicy:Il.default("always_require_plan_approval")}),d({kind:x("hosted"),sourceAuthority:x("hosted_profile"),teamId:Ee,projectId:Ee,activeProfile:o().trim().min(1).nullable(),sourceRef:Ee,baseSha:Ee,confirmationPolicy:Il.default("always_require_plan_approval")}),d({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:Il.default("always_require_plan_approval")}),d({kind:x("managed_artifact"),sourceAuthority:x("managed_artifact"),activeProfile:o().trim().min(1).nullable(),confirmationPolicy:Il.default("always_require_plan_approval")})]),YE=d({id:Ee,kind:k(["user","system","automation"]).default("user"),label:Ee}),XE=d({profileId:o().trim().min(1),conversationId:Ee,originTurnId:Ee,projectId:Ee,targetProject:d({id:Ee,name:Ee,workspacePath:Ee,sourceRef:Ee,baseSha:Ee}).nullable()}),tc=d({messageIds:v(o().trim().min(1)).default([]),conversationExcerpts:v(d({messageId:Ee,role:o().trim().min(1).nullable(),excerpt:o().trim().min(1),reason:o().trim().min(1).nullable()})).default([]),attachments:v(d({id:Ee,name:o().trim().min(1),mediaType:Ee,ref:Ee})).default([]),apps:v(d({id:o().trim().min(1),name:o().trim().min(1),connectionId:Ee,required:j().default(!1)})).default([]),tools:v(d({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([])}),Po={id:Ee,displayName:Ee},ih=pt("kind",[d({kind:x("unselected"),...Po}),d({kind:x("agent"),...Po,defaultActionKey:Ee}),d({kind:x("skill"),...Po,skillName:Ee}),d({kind:x("extension"),...Po,slot:Ee}),d({kind:x("model"),...Po,trainingPlanId:Ee,trainingJobId:Ee,artifactId:Ee}),d({kind:x("configuration"),...Po,key:Ee})]),Fp=k(["agent","skill","extension","model","configuration"]),ej=d({schemaVersion:x("openpond.createImprove.evidenceSnapshot.v1"),id:o().trim().min(1),contentHash:o().trim().min(8),consent:d({status:k(["granted","denied","revoked"]),scope:k(["metadata_only","selected_turns","full_session","direct_intent"]),reviewedBy:Ee,reviewedAt:o().trim().min(1)}),sources:v(d({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:Pa}),CS=d({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:d({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:d({kind:Fp,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:Pa}),tj=d({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:Pa}),nj=d({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)}),aj=d({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:d({key:Ee,label:Ee,required:j().default(!0)}),sourcePlan:v(d({path:o().trim().min(1),operation:k(["create","update","delete","inspect"]),reason:o().trim().min(1)})).default([]),requirements:v(tj).default([]),checks:v(d({name:o().trim().min(1),command:o().trim().min(1),required:j().default(!0)})).default([]),approvalId:Ee,approvedAt:Ee,editedFromPlanId:Ee,metadata:Pa,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),sj=d({id:o().trim().min(1),label:o().trim().min(1),value:o().trim().min(1),description:Ee,metadata:Pa}),rj=d({value:o().trim().min(1),label:Ee,detail:Ee,answeredAt:o().trim().min(1),metadata:Pa}),oj=d({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:rj.nullable().default(null),metadata:Pa}),ij=d({schemaVersion:x("openpond.createImprove.workflowCapture.v1"),id:o().trim().min(1),runId:o().trim().min(1),command:_S,objective:o().trim().min(1),conversationExcerpts:tc.shape.conversationExcerpts,attachments:tc.shape.attachments,apps:tc.shape.apps,tools:tc.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:Pa,createdAt:o().trim().min(1)}),RS=d({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)}),cj=d({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:RS.nullable().default(null)}),lj=d({id:o().trim().min(1),target:ih,status:k(["draft","authored","checking","evaluated","accepted","rejected","failed"]),git:cj.nullable().default(null),parentCandidateId:Ee.default(null),tasksetRef:CS.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:Pa}),dj=d({id:o().trim().min(1),candidateId:Ee,target:ih,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:d({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:Pa}),uj=d({mode:k(["foreground","background"]).default("background"),pauseAllowed:j().default(!0),cancellationAllowed:j().default(!0)}),mj=d({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)}),pj=d({kind:k(["candidate_authoring","local_apply","hosted_turn","training_job","evaluation","pull_request","release"]),id:o().trim().min(1),status:Ee,metadata:Pa}),fj=d({status:k(["not_requested","pending","released","rejected","rolled_back"]),profileCommit:Ee,profileTag:Ee,releaseReceiptRef:Ee,pullRequest:RS.nullable().default(null),updatedAt:Ee}),Hc=d({schemaVersion:x("openpond.createImprove.run.v1"),id:o().trim().min(1),revision:m().int().nonnegative(),operation:ZE,surface:GE,command:_S,objective:o().trim().min(1),state:JE,adapter:QE,actor:YE,scope:XE,context:tc,target:ih,evidenceSnapshots:v(ej).default([]),tasksetRef:CS.nullable().default(null),targetSelection:d({status:k(["open","recommended","confirmed"]),preselectedKind:Fp.nullable(),confirmedKind:Fp.nullable()}).nullable().default(null),plan:aj.nullable(),workflowCapture:ij.nullable(),executionPolicy:uj.default({mode:"background",pauseAllowed:!0,cancellationAllowed:!0}),iterationPolicy:mj.default({mode:"single",maximumAttempts:1,currentAttempt:0}),approvalIds:v(o().trim().min(1)).default([]),questionIds:v(o().trim().min(1)).default([]),questions:v(oj).default([]),candidates:v(lj).default([]),evaluationReceipts:v(dj).default([]),checkRefs:v(o().trim().min(1)).default([]),sourceRefs:v(o().trim().min(1)).default([]),externalExecutionRefs:v(pj).default([]),localProfileCommit:Ee,hostedSourceCommit:Ee,hostedSourceRef:Ee,releaseOutcome:fj.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:Pa,createdAt:o().trim().min(1),updatedAt:o().trim().min(1)}),ss={runId:o().trim().min(1),expectedRevision:m().int().nonnegative(),actionId:o().trim().min(1)};pt("type",[d({...ss,type:x("answer_question"),questionId:o().trim().min(1),value:o().trim().min(1)}),d({...ss,type:x("approve_plan")}),d({...ss,type:x("revise_plan"),revision:o().trim().min(1)}),d({...ss,type:x("cancel"),reason:Ee.optional().default(null)}),d({...ss,type:x("pause")}),d({...ss,type:x("resume")}),d({...ss,type:x("open_pull_request"),candidateId:o().trim().min(1)}),d({...ss,type:x("apply_candidate"),candidateId:o().trim().min(1)}),d({...ss,type:x("reject_candidate"),candidateId:o().trim().min(1),reason:Ee.optional().default(null)}),d({...ss,type:x("reconcile_pull_request"),candidateId:o().trim().min(1)})]);d({schemaVersion:x("openpond.createImprove.runList.v1"),runs:v(Hc),generatedAt:o().trim().min(1)});function qW(e){const t=nj.safeParse(e?.actionShape);return t.success?t.data:null}const Zd=d({source:k(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}),hj=d({ref:Zd,revision:o().nullable(),sourceHash:o()}),Si=Se(o(),Ie()).default({}),xa=m().int().nonnegative(),Jd=o().trim().min(1).max(1e5),PS=d({kind:k(["personal","team"]),id:E}).strict(),gj=d({name:E,release:re.nullable(),revision:xa}).strict();d({schemaVersion:x("openpond.harnessWorkspace.v1"),id:E,ownerScope:PS,name:o().trim().min(1).max(240),location:k(["local","hosted"]),sourceRevision:o().trim().min(1).max(500),revision:xa,dirty:j(),currentChannel:gj,createdAt:Ce,updatedAt:Ce,metadata:Si}).strict();const TS=k(["runtime","memory","prompt","skill","agent","product","taskset","training"]),AS=k(["text_instruction","memory","dependency_selection","executable_code","business_logic","financial_logic","permission","connected_app","publication","deployment","training","model_binding","team_or_global"]),ES=d({id:E,route:TS,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(AS).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"]})}),jS=d({workspaceId:E,revision:xa,sourceRevision:o().trim().min(1).max(500),channelRevision:xa}).strict(),dc=d({id:E,revision:xa,contentHash:W}).strict(),vj=d({schemaVersion:x("openpond.harnessTurnSnapshot.v1"),workspaceId:E,workspaceRevision:xa,sourceRevision:o().trim().min(1).max(500),channelName:E,channelRevision:xa,harnessRelease:re,toolCatalogHash:W.nullable().optional(),overlay:dc.nullable().optional().default(null)}).strict(),bj=d({schemaVersion:x("openpond.harnessRunOverlay.v1"),id:E,runId:E,baseHarnessRelease:re,workspace:jS,revision:xa,status:k(["active","frozen","abandoned"]),edits:v(ES).max(1e3),createdAt:Ce,updatedAt:Ce,metadata:Si}).strict();bj.extend({contentHash:W}).strict();const MS=d({kind:k(["tool_event","recovery","validation","user_turn","work_output","work_receipt"]),id:E,contentHash:W.nullable()}).strict(),OS=d({id:E,kind:k(["dependency","schema","package","file_render","skill","prompt","business_formula","targeted_evaluation","observed_recovery","memory","component_activation"]),description:Jd,required:j()}).strict(),yj=d({schemaVersion:x("openpond.harnessImprovementProposal.v1"),id:E,overlay:dc,baseHarnessRelease:re,expectedWorkspace:jS,requestedScope:k(["personal","team","global"]),route:TS,risk:k(["low","review","restricted"]),effects:v(AS).min(1).max(20),evidence:v(MS).min(1).max(1e3),edits:v(ES).min(1).max(1e3),validationPlan:v(OS).min(1).max(100),expectedOutcome:Jd,createdAt:Ce,metadata:Si}).strict().superRefine((e,t)=>{const n=new Set(e.effects);for(const[a,s]of e.edits.entries()){s.route!==e.route&&t.addIssue({code:"custom",message:"every edit route must match the proposal route",path:["edits",a,"route"]});for(const r of s.effects)n.has(r)||t.addIssue({code:"custom",message:`edit effect ${r} is missing from proposal effects`,path:["edits",a,"effects"]})}new Set(e.validationPlan.map(a=>a.id)).size!==e.validationPlan.length&&t.addIssue({code:"custom",message:"validation plan ids must be unique",path:["validationPlan"]})});yj.extend({contentHash:W}).strict();const Sj=d({schemaVersion:x("openpond.harnessTargetedValidationReceipt.v1"),id:E,proposal:re,validationId:E,kind:OS.shape.kind,status:k(["passed","failed","blocked","skipped"]),summary:Jd,evidenceRefs:v(MS).max(1e3),createdAt:Ce,metadata:Si}).strict();Sj.extend({contentHash:W}).strict();const xj=k(["advanced","retained","conflict","rolled_back"]),kj=d({schemaVersion:x("openpond.harnessAdvanceReceipt.v1"),id:E,workspaceId:E,ownerScope:PS,proposal:re.nullable(),expectedWorkspaceRevision:xa,observedWorkspaceRevision:xa,previousChannelRevision:xa,nextChannelRevision:xa,previousRelease:re.nullable(),nextRelease:re.nullable(),validationReceipts:v(re).max(100),decision:xj,reason:Jd,rollbackOf:re.nullable(),createdAt:Ce,metadata:Si}).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"]})});kj.extend({contentHash:W}).strict();const wj=d({schemaVersion:x("openpond.harnessOverlayMergeReceipt.v1"),id:E,workspaceId:E,baseHarnessRelease:re,leftOverlay:dc,rightOverlay:dc,decision:k(["merged","conflict"]),mergedOverlay:dc.nullable(),conflictTargets:v(o().trim().min(1).max(2e3)).max(1e3),requiresRevalidation:x(!0),createdAt:Ce,metadata:Si}).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"]})});wj.extend({contentHash:W}).strict();const $S=d({name:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(2e3),inputSchema:Se(o(),Ie()),inputSchemaHash:W,sideEffect:k(["read","write"]),timeoutMs:m().int().positive().max(36e5)}).strict(),Ij=d({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(),NS=o().regex(/^[a-z][a-z0-9_-]{0,119}$/),DS=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"),_j=d({id:NS,label:o().trim().min(1).max(240),description:o().max(4e3),inputSchema:Se(o(),Ie()),invocation:pt("kind",[d({kind:x("instructions"),instructions:o().min(1).max(1e5).refine(e=>!!e.trim())}).strict(),d({kind:x("agent_action"),actionId:o().trim().min(1).max(240)}).strict()]),skillPaths:v(DS).max(100)}).strict();d({schemaVersion:x("openpond.profileWorkflows.v1"),workflows:v(_j).max(1e3)}).strict();const Cj=d({id:o().trim().min(1).max(240),agentId:o().regex(/^[a-zA-Z0-9_-]{1,240}$/),sourceActionId:o().trim().min(1).max(240),inputSchema:Se(o(),Ie())}).strict();d({schemaVersion:x("openpond.profileWorkflowActions.v1"),actions:v(Cj).max(200)}).strict();const Rj=d({schemaVersion:x("openpond.profileWorkflowBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:re,catalogHash:W,workflowId:NS}).strict(),Pj=d({schemaVersion:x("openpond.profileComponentBinding.v1"),profileId:o().trim().min(1).max(240),sourceRevision:o().trim().min(1).max(240),harnessRelease:re,target:pt("kind",[d({kind:x("profile")}).strict(),d({kind:x("skill"),skillPath:DS}).strict(),d({kind:x("agent_action"),actionId:o().trim().min(1).max(240)}).strict()])}).strict(),LS=k(["openpond.lab"]),Vp=d({id:o(),experience:oh.default(WE),provider:yi,modelRef:cn.nullable().optional(),openPondCommandAccessMode:Lc.default(Wd),systemKind:LS.nullable().optional(),hiddenFromDefaultSidebar:j().optional(),parentSessionId:o().nullable().optional(),parentTurnId:o().nullable().optional(),subagentRunId:o().nullable().optional(),subagentRoleId:bi.nullable().optional(),subagentDelegationMode:Vd.nullable().optional(),title:o(),appId:o().nullable(),appName:o().nullable(),workspaceKind:zc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Zd.nullable().optional(),profileWorkflowBinding:Rj.nullable().optional(),profileComponentBinding:Pj.nullable().optional(),metadata:Se(o(),Ie()).optional(),cwd:o().nullable(),codexThreadId:o().nullable(),nativeAgent:d({provider:k(["claude-code","grok-build","opencode"]),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()});d({id:o(),sessionId:o(),providerTurnId:o().nullable(),modelRef:cn.nullable().optional(),prompt:o(),startedAt:o(),completedAt:o().nullable(),status:k(["in_progress","completed","failed","interrupted"]),error:o().nullable(),metadata:Se(o(),Ie()).optional().default({}),createImproveRun:Hc.nullable().optional().default(null),profileSnapshot:hj.nullable().optional(),harnessSnapshot:vj.nullable().optional()});const Tj=d({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:gt([o().trim().max(191),Se(o(),Ie())]).optional().nullable(),outputSchema:gt([o().trim().max(191),Se(o(),Ie())]).optional().nullable(),approvalPolicy:Se(o(),Ie()).optional().nullable(),artifactPolicy:Se(o(),Ie()).optional().nullable(),setupRequirements:v(Se(o(),Ie())).optional(),mcp:Se(o(),Ie()).optional().nullable(),schedulePolicy:Se(o(),Ie()).optional().nullable(),trace:Se(o(),Ie()).optional().nullable(),implementation:Se(o(),Ie()).optional().nullable(),invokesModel:j().optional()}),Aj=[{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"]}],Ej=d({name:o(),description:o(),relativePath:o(),sourcePath:o(),charCount:m().int().nonnegative(),sourceHash:o(),resourceFiles:v(o()),validationStatus:k(["valid","error"]),validationMessages:v(o())}),zS=d({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(Ej),validationStatus:k(["valid","error"]),validationMessages:v(o())});zS.omit({installedAt:!0,updatedAt:!0,sourcePath:!0}).extend({sourcePath:vi()});d({rootPath:o(),registryPath:o(),extensions:v(zS),error:o().nullable()});d({source:o().trim().min(1),ref:o().trim().min(1).optional()});const ch=k(["openpond_hosted","local_byok","codex_app_server","unknown"]),HS=k(["provider_usage","codex_context_usage","missing"]),jj=k(["provider_usage_body","provider_response_headers"]),Mj=k(["chat_turn","tool_loop","slash_command","create_improve_planner","harness_refiner","context_compaction","subagent","codex_context","other"]),Oj=k(["foreground","tool_loop","compaction","subagent","refiner","other"]),US=k(["user_facing","background","system"]),qS=k(["started","completed","failed","interrupted"]),lh=k(["composer_selection","prompt_parse","server_parser","model_tool","api"]),BS=k(["chat","settings","goal","create_improve","compaction","system"]),FS=k(["direct_chat","tool_loop","slash_command","planner","summary","scan","subagent","other"]),$j=d({surface:BS,workflowKind:FS,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:lh.nullable().default(null),appId:o().trim().min(1).nullable().default(null),workspaceKind:zc.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)}),Nj=d({surface:BS.optional(),workflowKind:FS.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:lh.nullable().optional()}).strict(),Jr=o().trim().min(1).max(160),Dj=d({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:Jr,model:o().trim().min(1),route:ch,source:HS,requestKind:Mj,visibility:US,status:qS,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:jj.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:$j}),VS=d({from:o().trim().min(1),to:o().trim().min(1),bucket:k(["day","all_time"])}),dh=gt([x("all"),US]),uh=k(["all","started","completed","failed","interrupted","missing"]),Lj=d({range:k(["7d","30d","90d","all"]).default("30d"),visibility:dh.default("all"),status:uh.default("all"),provider:Jr.optional(),model:o().trim().min(1).optional()});Lj.extend({sessionId:o().trim().min(1).optional(),turnId:o().trim().min(1).optional(),limit:m().int().positive().max(500).default(100)});d({sessionId:o().trim().min(1)});const Qr=d({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)}),zj=Qr.extend({provider:Jr,model:o().trim().min(1),route:ch}),Hj=Qr.extend({sessionId:o().trim().min(1),title:o().trim().min(1).nullable(),workspaceKind:zc.nullable(),workspaceId:o().trim().min(1).nullable()}),Uj=Qr.extend({commandName:o().trim().min(1),commandSource:lh.nullable()}),qj=Qr.extend({route:ch}),Bj=Qr.extend({status:qS}),Fj=Qr.extend({source:HS}),Vj=Qr.extend({cohort:Oj}),Kj=d({date:o().trim().min(1),totalTokens:m().int().nonnegative(),requests:m().int().nonnegative(),models:v(d({provider:Jr,model:o().trim().min(1),totalTokens:m().int().nonnegative(),requests:m().int().nonnegative()}))}),Wj=d({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()});d({generatedAt:o().trim().min(1),range:VS,filters:d({visibility:dh,status:uh,provider:Jr.nullable(),model:o().trim().min(1).nullable()}),totals:Wj,daily:v(Kj),models:v(zj),threads:v(Hj),commands:v(Uj),routes:v(qj),statuses:v(Bj),sources:v(Fj),cohorts:v(Vj)});d({generatedAt:o().trim().min(1),range:VS,filters:d({visibility:dh,status:uh,provider:Jr.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(Dj)});const Gj=d({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(Jr)});d({generatedAt:o().trim().min(1),sessionId:o().trim().min(1),turns:v(Gj)});const Zj=k(["usage_spike","model_usage_spike","latency_regression","failure_cluster","missing_usage_frames"]);d({type:Zj,title:o().trim().min(1),summary:o().trim().min(1),severity:k(["nit","concern","blocker"]),payload:Se(o(),Ie()).default({})});const Jj=k(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),Qj=k(["slack","microsoft_teams","github","google","turnkey","x","mcp"]),Yj=k(["native_bot","oauth_connector","wallet_connector","mcp_endpoint"]),Xj=d({kind:x("integration"),provider:Jj,appIds:v(Qj).min(1).max(4),setupSurfaces:v(Yj).min(1).max(4),connectionIds:v(o().trim().min(1)).max(8).optional(),capabilities:v(o().trim().min(1)).max(64).optional()}).strict(),zr={maxAttachments:10,maxAttachmentBytes:12*1024*1024,maxAttachmentBase64Chars:Math.ceil(12*1024*1024*4/3)+16,maxTextChars:2e5},eM=k(["image","text","file"]),tM=d({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)}),nM=d({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)}),KS=d({id:o().trim().min(1),name:o().trim().min(1).max(240),mediaType:o().trim().min(1).max(160),sizeBytes:m().int().nonnegative().max(zr.maxAttachmentBytes),kind:eM,lineCount:m().int().nonnegative().max(zr.maxAttachmentBytes+1).optional(),relativePath:o().trim().min(1).max(1024).optional(),text:o().max(zr.maxTextChars).optional(),contentsBase64:o().max(zr.maxAttachmentBase64Chars).optional()}),aM=KS.omit({text:!0,contentsBase64:!0}).extend({imagePreview:tM.optional(),filePreview:nM.optional()});d({experience:oh.optional(),provider:yi.default(Fr),modelRef:cn.optional(),openPondCommandAccessMode:Lc.optional(),systemKind:LS.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:bi.nullable().optional(),subagentDelegationMode:Vd.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:zc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Zd.nullable().optional(),profileWorkflowBinding:Vp.shape.profileWorkflowBinding,profileComponentBinding:Vp.shape.profileComponentBinding,metadata:Se(o(),Ie()).optional(),cwd:o().nullable().optional(),title:o().optional(),autoTitlePrompt:o().trim().min(1).max(2e4).optional()});d({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()});d({branch:o().trim().min(1).max(120).optional()});d({prompt:o().min(1),workflowInput:Ie().optional(),metadata:Se(o(),Ie()).optional(),usageAttribution:Nj.optional().nullable(),cwd:o().nullable().optional(),model:o().nullable().optional(),modelRef:cn.optional(),mentionedAppIds:v(o().trim().min(1)).max(8).optional(),mentionedConnectedApps:v(Xj).max(8).optional(),openPondActionCatalog:v(Tj).max(100).optional(),attachments:v(KS).max(zr.maxAttachments).optional(),createImproveRun:Hc.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:sh.default("default"),codexReasoningEffort:Gd.optional()});d({prompt:o().min(1),error:o().min(1),target:k(["cloud_workspace","hybrid_sandbox"])});d({reason:k(["manual"]).default("manual"),model:o().nullable().optional(),modelRef:cn.optional()});d({experience:oh.optional(),provider:yi.optional(),modelRef:cn.nullable().optional(),openPondCommandAccessMode:Lc.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:bi.nullable().optional(),subagentDelegationMode:Vd.nullable().optional(),appId:o().nullable().optional(),appName:o().nullable().optional(),workspaceKind:zc.optional(),workspaceId:o().nullable().optional(),workspaceName:o().nullable().optional(),localProjectId:o().nullable().optional(),cloudProjectId:o().nullable().optional(),cloudTeamId:o().nullable().optional(),currentProfile:Zd.nullable().optional(),metadata:Se(o(),Ie()).optional(),cwd:o().nullable().optional()});d({command:o().trim().min(1),cwd:o().trim().min(1).max(4096).nullable().optional(),timeoutSeconds:m().int().min(1).max(3600).optional()});d({appIds:v(o()).min(1)});d({expectedRevision:o().optional(),defaultChatProvider:yi.optional(),defaultChatModel:o().min(1).optional(),defaultChatModelRef:cn.nullable().optional(),subagents:Sc.optional(),codexPermissionMode:sh.optional(),codexReasoningEffort:Gd.optional(),openPondCommandAccessMode:Lc.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:qp.optional(),training:Bp.optional(),sidebarWidth:m().int().min(244).max(560).optional(),diffPanelWidth:m().int().min(320).max(2400).optional(),sidebarSectionsCollapsed:Up.optional(),editor:bd.optional()});d({message:o().trim().min(1).max(4e3),surface:o().trim().min(1).max(120).default("app"),stack:o().max(12e3).nullable().optional(),context:Se(o(),Ie()).optional()}).strict();d({activeTemplateId:rh,templateName:o().trim().min(1).max(80),soul:o().trim().min(1).max(8e3),saveAsNew:j().optional().default(!1)});d({decision:k(["accept","acceptForSession","decline","cancel"]),answers:Se(o().min(1).max(2e3),o().trim().min(1).max(8e3)).optional()});d({branch:o().trim().min(1).max(240).nullable().optional(),surface:k(["desktop","terminal"])});d({handle:o().min(1),baseUrl:o().nullable().optional()});d({handle:o().min(1),baseUrl:o().nullable().optional()});d({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()});d({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 mh=Se(o(),Ie());d({userId:o(),role:k(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable()});const sM=d({userId:o(),role:k(["owner","admin","member"]),name:o(),handle:o().nullable(),image:o().nullable(),lastReadSequence:m().int().nonnegative()}),rM=d({id:o(),messageId:o(),refType:k(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:mh,createdAt:o()}),WS=d({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()});d({attachment:WS,uploadUrl:o().url().nullable(),uploadHeaders:Se(o(),o()),expiresAt:o().nullable()});d({url:o().url(),expiresAt:o()});const ph=d({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:mh,editedAt:o().nullable(),deletedAt:o().nullable(),createdAt:o(),refs:v(rM),attachments:v(WS)}),oM=d({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(sM),lastMessage:ph.nullable()});d({thread:oM,messages:v(ph),hasMoreBefore:j()});d({threadId:o(),mutedAt:o().nullable()});const iM=k(["pending","running","completed","failed","interrupted","cancelled"]),Tv=d({id:o(),conversationId:o(),threadId:o(),teamId:o(),requestedByUserId:o(),executorUserId:o().nullable(),providerId:o(),modelId:o(),clientRequestId:o(),baseMessageSequence:m().int().nonnegative(),status:iM,partialBody:o().nullable(),userMessageId:o(),assistantMessageId:o().nullable(),errorCode:o().nullable(),cancelledByUserId:o().nullable(),leaseExpiresAt:o().nullable(),heartbeatAt:o().nullable(),createdAt:o(),updatedAt:o()}),cM=d({id:o(),conversationId:o(),sequence:m().int().nonnegative(),role:k(["user","assistant","system","action"]),body:o(),createdByUserId:o().nullable(),createdAt:o()});d({conversationId:o(),parentThreadId:o(),parentMessageId:o(),teamId:o(),title:o().nullable(),providerId:o().nullable(),modelId:o(),createdByUserId:o(),messages:v(cM),turns:v(Tv),activeTurn:Tv.nullable(),createdAt:o(),updatedAt:o()});const GS=d({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:mh,createdAt:o()});d({events:v(GS),cursor:m().int().nonnegative(),hasMore:j()});d({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 fh=Se(o(),Ie()),wa=o().nullable(),lM=k(["draft","published","archived"]),hh=k(["owner","admin","member"]),ZS=k(["active","left"]),JS=k(["mentions","all","none"]),QS=k(["public_preview","members"]),dM=k(["members","admins"]),uM=d({canPreview:j(),canJoin:j(),canLeave:j(),canRead:j(),canPost:j(),canUpload:j(),canMention:j(),canManage:j(),requiresRulesAcceptance:j(),currentRulesVersionId:o().nullable()}),YS=d({id:o(),communityId:o(),version:m().int().positive(),title:o(),requiresReacceptance:j(),publishedAt:o()}),mM=YS.extend({bodyMarkdown:o(),contentHash:o()}),pM=d({role:hh,status:ZS,notificationMode:JS}),fM=d({id:o(),communityId:o(),userId:o(),role:hh,status:ZS,notificationMode:JS,joinedAt:o(),leftAt:wa,createdAt:o(),updatedAt:o()}),XS=d({id:o(),slug:o(),displayName:o(),description:o(),imageUrl:o().nullable(),status:lM,visibility:k(["public","private"]),joinPolicy:k(["open","closed"]),historyVisibility:QS,featuredAt:wa,publishedAt:wa,archivedAt:wa,memberCount:m().int().nonnegative(),membership:pM.nullable(),capabilities:uM,currentRules:YS.nullable()});d({items:v(XS),nextCursor:o().nullable()});const ex=d({lastReadSequence:m().int().nonnegative(),lastReadAt:wa.optional(),mutedAt:wa,pinnedAt:wa}),gh=d({id:o(),communityId:o(),chatThreadId:o().nullable(),slug:o(),displayName:o(),topic:o(),position:m().int().nonnegative(),visibility:QS,postingPolicy:dM,isDefault:j(),archivedAt:wa,lastMessageSequence:m().int().nonnegative(),unreadCount:m().int().nonnegative(),readState:ex.nullable()});XS.omit({currentRules:!0}).extend({currentRules:mM.nullable(),channels:v(gh),previewMessageLimit:m().int().positive()});const hM=d({id:o(),messageId:o(),refType:k(["hosted_ai_thread","goal","openpond_session","project","agent_run","message_reply"]),refId:o(),preview:fh,createdAt:o()}),tx=d({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:wa});d({attachment:tx,uploadUrl:o().url().nullable(),uploadHeaders:Se(o(),o()),expiresAt:wa});d({url:o().url(),expiresAt:o()});const nx=d({id:o(),threadId:o(),teamId:vi(),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:fh,editedAt:wa,deletedAt:wa,createdAt:o(),refs:v(hM),attachments:v(tx)});d({messages:v(nx),hasMoreBefore:j(),channelId:o(),readState:ex.omit({lastReadAt:!0}).nullable(),preview:j()});const gM=d({userId:o(),handle:o().nullable(),name:o().nullable(),role:hh});d({items:v(gM),nextCursor:o().nullable()});const ax=d({id:m().int().nonnegative(),communityId:o(),channelId:o(),threadId:o(),type:k(["thread.created","message.created","message.updated","message.deleted","read.updated"]),payload:fh,createdAt:o()});d({events:v(ax),cursor:m().int().nonnegative(),hasMore:j()});d({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)});d({membership:fM,channels:v(gh)});d({channels:v(gh)});const vM=d({candidateId:o().min(1).max(240),frozenRevision:m().int().positive(),frozenHash:o().regex(/^[a-f0-9]{64}$/),harnessRelease:re,protectedClosureHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),Av=o().trim().min(1).max(240),bM=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."),Uc=d({schemaVersion:x("openpond.tasksetMetricPolicy.v1"),primaryMetric:Av,aggregation:k(["mean_score","pass_rate","weighted_mean","custom"]),missingReward:k(["zero","exclude"]),taskWeights:Se(Av,m().positive().max(1e6)).optional(),customAggregator:d({module:bM,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."})}),yM=d({schemaVersion:x("openpond.tasksetMetricResult.v1"),runManifest:re,tasksetRelease:re,policy:Uc,policyHash:W,receiptRefs:v(re).min(1).max(1e6),includedCount:m().int().nonnegative(),missingRewardCount:m().int().nonnegative(),excludedCount:m().int().nonnegative(),value:m().min(0).max(1).nullable()}).strict(),sx=yM.extend({contentHash:W}).strict(),Kt=E,tr=W,rx=d({id:Kt,revision:m().int().positive(),contentHash:tr}).strict(),vh=d({kind:x("owner_attested_local"),ownerActorId:Kt,teamId:Kt,executionHash:tr,configurationHash:tr,retainedAttemptHash:tr,traceHash:tr,publicationCutoffHash:tr}).strict(),SM=vh.omit({publicationCutoffHash:!0,kind:!0}).extend({kind:x("native_local")}).strict(),xM=d({origin:vh,executionId:Kt,receiptId:Kt,taskId:Kt,targetId:Kt,familyKey:Kt,split:k(["train","validation","test","frozen_eval"]),input:Se(o(),Ie()),policyVisibleContext:Se(o(),Ie()),output:o().nullable(),error:o().nullable(),events:v(Se(o(),Ie())).max(1e3),coverage:d({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."})}),kM=d({schemaVersion:x("openpond.humanLocalEvidenceExport.v1"),actorId:Kt,scope:Kt,projectId:Kt,dataset:rx,graderId:Kt,compiledGraderHash:tr,attempts:v(xM).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."})}),wM=kM.safeExtend({contentHash:tr}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;Qe(a)!==n&&t.addIssue({code:"custom",message:"Local evidence export bytes changed."})}),ox=d({endpoint:x("export_local"),scope:Kt,projectId:Kt,graderId:Kt,selections:v(d({executionId:Kt,receiptId:Kt}).strict()).min(1).max(2)}).strict(),IM=d({endpoint:x("publish_local"),scope:Kt,projectId:Kt,operationId:Kt,audience:v(Kt).max(100),workspaceVisible:j(),evidence:wM}).strict(),_M=ox.omit({endpoint:!0}).extend({endpoint:x("share_local"),operationId:Kt,audience:v(Kt).max(100),workspaceVisible:j()}).strict(),CM=d({endpoint:x("local_publications"),scope:Kt,executionId:Kt}).strict(),RM=d({endpoint:x("revoke_local"),scope:Kt,publication:rx}).strict();var ix=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},PM=ix((e,t)=>{"use strict";t.exports=function n(a,s){if(a===s)return!0;if(a&&s&&typeof a=="object"&&typeof s=="object"){if(a.constructor!==s.constructor)return!1;var r,i,c;if(Array.isArray(a)){if(r=a.length,r!=s.length)return!1;for(i=r;i--!==0;)if(!n(a[i],s[i]))return!1;return!0}if(a.constructor===RegExp)return a.source===s.source&&a.flags===s.flags;if(a.valueOf!==Object.prototype.valueOf)return a.valueOf()===s.valueOf();if(a.toString!==Object.prototype.toString)return a.toString()===s.toString();if(c=Object.keys(a),r=c.length,r!==Object.keys(s).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(s,c[i]))return!1;for(i=r;i--!==0;){var u=c[i];if(!n(a[u],s[u]))return!1}return!0}return a!==a&&s!==s}}),TM=ix(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0});var t=PM();t.code='require("ajv/dist/runtime/equal").default',e.default=t}),Ev=$t,jv={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"}}},AM=Object.prototype.hasOwnProperty,EM=TM().default,ht={validate:$t};function ua(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:s=e,dynamicAnchors:r={}}={}){let i=null,c=0,u=ua.evaluated;if(u.dynamicProps&&(u.props=void 0),u.dynamicItems&&(u.items=void 0),c===0)if(e&&typeof e=="object"&&!Array.isArray(e))for(let p in e){let f=c;ht.validate(e[p],{instancePath:t+"/"+p.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:e,parentDataProperty:p,rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=f===c;if(!l)break}else return ua.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"object"}}],!1;return ua.errors=i,c===0}ua.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};function An(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:s=e,dynamicAnchors:r={}}={}){let i=null,c=0,u=An.evaluated;if(u.dynamicProps&&(u.props=void 0),u.dynamicItems&&(u.items=void 0),c===0)if(Array.isArray(e)){if(e.length>32)return An.errors=[{instancePath:t,schemaPath:"#/maxItems",keyword:"maxItems",params:{limit:32}}],!1;if(e.length<1)return An.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 y=c;ht.validate(e[f],{instancePath:t+"/"+f,parentData:e,parentDataProperty:f,rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=y===c;if(!l)break}}}else return An.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return An.errors=i,c===0}An.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};var jM={enum:["array","boolean","integer","null","number","object","string"]};function us(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:s=e,dynamicAnchors:r={}}={}){let i=null,c=0,u=us.evaluated;return u.dynamicProps&&(u.props=void 0),u.dynamicItems&&(u.items=void 0),e==="array"||e==="boolean"||e==="integer"||e==="null"||e==="number"||e==="object"||e==="string"?(us.errors=i,c===0):(us.errors=[{instancePath:t,schemaPath:"#/enum",keyword:"enum",params:{allowedValues:jM.enum}}],!1)}us.evaluated={dynamicProps:!1,dynamicItems:!1};function Nt(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:s=e,dynamicAnchors:r={}}={}){let i=null,c=0,u=Nt.evaluated;return u.dynamicProps&&(u.props=void 0),u.dynamicItems&&(u.items=void 0),typeof e=="number"&&!(e%1)&&!isNaN(e)&&isFinite(e)?typeof e=="number"&&isFinite(e)&&(e<0||isNaN(e))?(Nt.errors=[{instancePath:t,schemaPath:"#/minimum",keyword:"minimum",params:{comparison:">=",limit:0}}],!1):(Nt.errors=i,c===0):(Nt.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"integer"}}],!1)}Nt.evaluated={dynamicProps:!1,dynamicItems:!1};function Sa(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:s=e,dynamicAnchors:r={}}={}){let i=null,c=0,u=Sa.evaluated;if(u.dynamicProps&&(u.props=void 0),u.dynamicItems&&(u.items=void 0),c===0)if(Array.isArray(e)){var l=!0;let p=e.length;for(let f=0;f<p;f++){let y=c;if(typeof e[f]!="string")return Sa.errors=[{instancePath:t+"/"+f,schemaPath:"#/items/type",keyword:"type",params:{type:"string"}}],!1;var l=y===c;if(!l)break}if(l){let f=e.length,y;if(f>1){let b={};for(;f--;){let I=e[f];if(typeof I=="string"){if(typeof b[I]=="number")return y=b[I],Sa.errors=[{instancePath:t,schemaPath:"#/uniqueItems",keyword:"uniqueItems",params:{i:f,j:y}}],!1;b[I]=f}}}}}else return Sa.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:"array"}}],!1;return Sa.errors=i,c===0}Sa.evaluated={items:!0,dynamicProps:!1,dynamicItems:!1};function $t(e,{instancePath:t="",parentData:n,parentDataProperty:a,rootData:s=e,dynamicAnchors:r={}}={}){let i=null,c=0,u=$t.evaluated;if(u.dynamicProps&&(u.props=void 0),u.dynamicItems&&(u.items=void 0),!(e&&typeof e=="object"&&!Array.isArray(e))&&typeof e!="boolean")return $t.errors=[{instancePath:t,schemaPath:"#/type",keyword:"type",params:{type:jv.type}}],!1;if(c===0&&e&&typeof e=="object"&&!Array.isArray(e)){let b=c;for(let I in e)if(!AM.call(jv.properties,I))return $t.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 $t.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 $t.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 $t.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;ua(e.$defs,{instancePath:t+"/$defs",parentData:e,parentDataProperty:"$defs",rootData:s,dynamicAnchors:r})||(i=i===null?ua.errors:i.concat(ua.errors),c=i.length);var l=_===c}else var l=!0;if(l){if(e.properties!==void 0){let M=c;ua(e.properties,{instancePath:t+"/properties",parentData:e,parentDataProperty:"properties",rootData:s,dynamicAnchors:r})||(i=i===null?ua.errors:i.concat(ua.errors),c=i.length);var l=M===c}else var l=!0;if(l){if(e.dependentSchemas!==void 0){let A=c;ua(e.dependentSchemas,{instancePath:t+"/dependentSchemas",parentData:e,parentDataProperty:"dependentSchemas",rootData:s,dynamicAnchors:r})||(i=i===null?ua.errors:i.concat(ua.errors),c=i.length);var l=A===c}else var l=!0;if(l){if(e.allOf!==void 0){let T=c;An(e.allOf,{instancePath:t+"/allOf",parentData:e,parentDataProperty:"allOf",rootData:s,dynamicAnchors:r})||(i=i===null?An.errors:i.concat(An.errors),c=i.length);var l=T===c}else var l=!0;if(l){if(e.anyOf!==void 0){let S=c;An(e.anyOf,{instancePath:t+"/anyOf",parentData:e,parentDataProperty:"anyOf",rootData:s,dynamicAnchors:r})||(i=i===null?An.errors:i.concat(An.errors),c=i.length);var l=S===c}else var l=!0;if(l){if(e.oneOf!==void 0){let w=c;An(e.oneOf,{instancePath:t+"/oneOf",parentData:e,parentDataProperty:"oneOf",rootData:s,dynamicAnchors:r})||(i=i===null?An.errors:i.concat(An.errors),c=i.length);var l=w===c}else var l=!0;if(l){if(e.prefixItems!==void 0){let R=c;An(e.prefixItems,{instancePath:t+"/prefixItems",parentData:e,parentDataProperty:"prefixItems",rootData:s,dynamicAnchors:r})||(i=i===null?An.errors:i.concat(An.errors),c=i.length);var l=R===c}else var l=!0;if(l){if(e.items!==void 0){let O=c;ht.validate(e.items,{instancePath:t+"/items",parentData:e,parentDataProperty:"items",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=O===c}else var l=!0;if(l){if(e.additionalProperties!==void 0){let z=c;ht.validate(e.additionalProperties,{instancePath:t+"/additionalProperties",parentData:e,parentDataProperty:"additionalProperties",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=z===c}else var l=!0;if(l){if(e.not!==void 0){let $=c;ht.validate(e.not,{instancePath:t+"/not",parentData:e,parentDataProperty:"not",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=$===c}else var l=!0;if(l){if(e.if!==void 0){let V=c;ht.validate(e.if,{instancePath:t+"/if",parentData:e,parentDataProperty:"if",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=V===c}else var l=!0;if(l){if(e.then!==void 0){let Y=c;ht.validate(e.then,{instancePath:t+"/then",parentData:e,parentDataProperty:"then",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=Y===c}else var l=!0;if(l){if(e.else!==void 0){let se=c;ht.validate(e.else,{instancePath:t+"/else",parentData:e,parentDataProperty:"else",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=se===c}else var l=!0;if(l){if(e.contains!==void 0){let ee=c;ht.validate(e.contains,{instancePath:t+"/contains",parentData:e,parentDataProperty:"contains",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=ee===c}else var l=!0;if(l){if(e.unevaluatedProperties!==void 0){let H=c;ht.validate(e.unevaluatedProperties,{instancePath:t+"/unevaluatedProperties",parentData:e,parentDataProperty:"unevaluatedProperties",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=H===c}else var l=!0;if(l){if(e.unevaluatedItems!==void 0){let F=c;ht.validate(e.unevaluatedItems,{instancePath:t+"/unevaluatedItems",parentData:e,parentDataProperty:"unevaluatedItems",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.validate.errors),c=i.length);var l=F===c}else var l=!0;if(l){if(e.propertyNames!==void 0){let J=c;ht.validate(e.propertyNames,{instancePath:t+"/propertyNames",parentData:e,parentDataProperty:"propertyNames",rootData:s,dynamicAnchors:r})||(i=i===null?ht.validate.errors:i.concat(ht.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;us(K,{instancePath:t+"/type",parentData:e,parentDataProperty:"type",rootData:s,dynamicAnchors:r})||(i=i===null?us.errors:i.concat(us.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;us(K[Re],{instancePath:t+"/type/"+Re,parentData:K,parentDataProperty:Re,rootData:s,dynamicAnchors:r})||(i=i===null?us.errors:i.concat(us.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(EM(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++,$t.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 $t.errors=[{instancePath:t+"/enum",schemaPath:"#/properties/enum/minItems",keyword:"minItems",params:{limit:1}}],!1}else return $t.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 $t.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 $t.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 $t.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 $t.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 ve=c;if(typeof e.writeOnly!="boolean")return $t.errors=[{instancePath:t+"/writeOnly",schemaPath:"#/properties/writeOnly/type",keyword:"type",params:{type:"boolean"}}],!1;var l=ve===c}else var l=!0;if(l){if(e.deprecated!==void 0){let me=c;if(typeof e.deprecated!="boolean")return $t.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 $t.errors=[{instancePath:t+"/multipleOf",schemaPath:"#/properties/multipleOf/exclusiveMinimum",keyword:"exclusiveMinimum",params:{comparison:">",limit:0}}],!1}else return $t.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 $t.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 $t.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 $t.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,ze=c;if(!(typeof De=="number"&&isFinite(De)))return $t.errors=[{instancePath:t+"/exclusiveMinimum",schemaPath:"#/properties/exclusiveMinimum/type",keyword:"type",params:{type:"number"}}],!1;var l=ze===c}else var l=!0;if(l){if(e.maxLength!==void 0){let ze=c;Nt(e.maxLength,{instancePath:t+"/maxLength",parentData:e,parentDataProperty:"maxLength",rootData:s,dynamicAnchors:r})||(i=i===null?Nt.errors:i.concat(Nt.errors),c=i.length);var l=ze===c}else var l=!0;if(l){if(e.minLength!==void 0){let we=c;Nt(e.minLength,{instancePath:t+"/minLength",parentData:e,parentDataProperty:"minLength",rootData:s,dynamicAnchors:r})||(i=i===null?Nt.errors:i.concat(Nt.errors),c=i.length);var l=we===c}else var l=!0;if(l){if(e.maxItems!==void 0){let Me=c;Nt(e.maxItems,{instancePath:t+"/maxItems",parentData:e,parentDataProperty:"maxItems",rootData:s,dynamicAnchors:r})||(i=i===null?Nt.errors:i.concat(Nt.errors),c=i.length);var l=Me===c}else var l=!0;if(l){if(e.minItems!==void 0){let Te=c;Nt(e.minItems,{instancePath:t+"/minItems",parentData:e,parentDataProperty:"minItems",rootData:s,dynamicAnchors:r})||(i=i===null?Nt.errors:i.concat(Nt.errors),c=i.length);var l=Te===c}else var l=!0;if(l){if(e.maxContains!==void 0){let N=c;Nt(e.maxContains,{instancePath:t+"/maxContains",parentData:e,parentDataProperty:"maxContains",rootData:s,dynamicAnchors:r})||(i=i===null?Nt.errors:i.concat(Nt.errors),c=i.length);var l=N===c}else var l=!0;if(l){if(e.minContains!==void 0){let q=c;Nt(e.minContains,{instancePath:t+"/minContains",parentData:e,parentDataProperty:"minContains",rootData:s,dynamicAnchors:r})||(i=i===null?Nt.errors:i.concat(Nt.errors),c=i.length);var l=q===c}else var l=!0;if(l){if(e.maxProperties!==void 0){let X=c;Nt(e.maxProperties,{instancePath:t+"/maxProperties",parentData:e,parentDataProperty:"maxProperties",rootData:s,dynamicAnchors:r})||(i=i===null?Nt.errors:i.concat(Nt.errors),c=i.length);var l=X===c}else var l=!0;if(l){if(e.minProperties!==void 0){let U=c;Nt(e.minProperties,{instancePath:t+"/minProperties",parentData:e,parentDataProperty:"minProperties",rootData:s,dynamicAnchors:r})||(i=i===null?Nt.errors:i.concat(Nt.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 $t.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;Sa(e.required,{instancePath:t+"/required",parentData:e,parentDataProperty:"required",rootData:s,dynamicAnchors:r})||(i=i===null?Sa.errors:i.concat(Sa.errors),c=i.length);var l=de===c}else var l=!0;if(l){if(e.dependentRequired!==void 0){let be=e.dependentRequired,Oe=c;if(c===Oe)if(be&&typeof be=="object"&&!Array.isArray(be))for(let Ge in be){let bt=c;Sa(be[Ge],{instancePath:t+"/dependentRequired/"+Ge.replace(/~/g,"~0").replace(/\//g,"~1"),parentData:be,parentDataProperty:Ge,rootData:s,dynamicAnchors:r})||(i=i===null?Sa.errors:i.concat(Sa.errors),c=i.length);var y=bt===c;if(!y)break}else return $t.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 $t.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 $t.errors=[{instancePath:t+"/contentMediaType",schemaPath:"#/properties/contentMediaType/type",keyword:"type",params:{type:"string"}}],!1;var l=Oe===c}else var l=!0}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}return $t.errors=i,c===0}$t.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};const Mv="https://json-schema.org/draft/2020-12/schema",MM=1048576,OM=32768,$M=new Set(["properties","$defs","dependentSchemas"]),NM=new Set(["allOf","anyOf","oneOf","prefixItems"]),DM=new Set(["items","additionalProperties","not","if","then","else","contains","unevaluatedProperties","unevaluatedItems","propertyNames"]);function Ta(e,t=MM){const n=[{value:e,depth:0}],a=new Set;let s=0;for(;n.length;){const r=n.pop();if(r.exit){a.delete(r.value);continue}if(++s>1e5||r.depth>48)throw new Error("task_json_complexity_exceeded");if(r.value===null||typeof r.value=="string"||typeof r.value=="boolean"||typeof r.value=="number"&&Number.isFinite(r.value))continue;if(typeof r.value!="object")throw new Error("task_json_value_invalid");if(a.has(r.value))throw new Error("task_json_cycle");a.add(r.value),n.push({...r,exit:!0});const i=Object.getPrototypeOf(r.value);if(!Array.isArray(r.value)&&i!==Object.prototype&&i!==null)throw new Error("task_json_object_invalid");if(Object.getOwnPropertySymbols(r.value).length)throw new Error("task_json_symbol_invalid");if(Object.hasOwn(r.value,"toJSON"))throw new Error("task_json_serializer_invalid");if(Array.isArray(r.value)&&(r.value.length>1e4||Object.keys(r.value).length!==r.value.length))throw new Error("task_json_array_invalid");for(const[c,u]of Object.entries(Object.getOwnPropertyDescriptors(r.value))){if(u.get||u.set)throw new Error("task_json_accessor_invalid");if(Array.isArray(r.value)&&c!=="length"&&(!/^(0|[1-9]\d*)$/u.test(c)||Number(c)>=r.value.length))throw new Error("task_json_array_invalid");u.enumerable&&n.push({value:u.value,depth:r.depth+1})}}if(new TextEncoder().encode(JSON.stringify(e)).byteLength>t)throw new Error("task_json_size_exceeded")}function bh(e){try{return LM(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 LM(e){if(Ta(e,OM),nc(e,e,new Set,0,{remaining:2048}),!Ev(e)){const t=Ev.errors?.[0];throw new Error(`Task schema ${t?.instancePath||"/"} violates ${t?.keyword??"schema"}.`)}}function nc(e,t,n,a,s){if(--s.remaining<0)throw new Error("Task schema reference expansion exceeds the validation budget.");if(typeof e=="boolean")return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("A task schema must be an object or boolean.");if(a>24||n.has(e))throw new Error("Recursive or deeply nested task schemas are not supported.");const r=new Set(n).add(e),i=e;if(i.$schema!==void 0&&i.$schema!==Mv)throw new Error(`Task schemas must use ${Mv}.`);for(const[c,u]of Object.entries(i))if(c==="$ref"){if(typeof u!="string"||!u.startsWith("#/$defs/"))throw new Error("Task schema references must be local JSON pointers into $defs.");let l=t;for(const p of u.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 ${u} is missing.`);l=l[f]}nc(l,t,r,a+1,s)}else if($M.has(c)){if(!u||typeof u!="object"||Array.isArray(u))throw new Error(`Invalid schema map ${c}.`);for(const l of Object.values(u))nc(l,t,r,a+1,s)}else if(NM.has(c)){if(!Array.isArray(u)||u.length>32)throw new Error(`Schema ${c} must contain at most 32 alternatives.`);for(const l of u)nc(l,t,r,a+1,s)}else DM.has(c)&&nc(u,t,r,a+1,s)}const cx=d({taskId:E,input:Se(o(),Ie()),policyVisibleContext:Se(o(),Ie()),expectedOutput:Se(o(),Ie()).nullable().optional(),tags:v(E).max(100).optional()}).strict(),ri=d({schemaVersion:x("openpond.humanTaskProposal.v1"),tasks:v(cx).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(s=>s.taskId)).size!==e.tasks.length&&t.addIssue({code:"custom",message:"Each task may be proposed once."});try{Ta(e,1048576)}catch{t.addIssue({code:"custom",message:"Task proposal exceeds retained data bounds."})}}),Ov=d({schemaVersion:x("openpond.humanTaskProposal.v1"),tasks:v(cx).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."}):ri.safeParse(e).success||t.addIssue({code:"custom",message:"Task proposal integrity differs."})});function BW(e){const t={schemaVersion:"openpond.humanTaskProposal.v1",tasks:e};return ri.parse({...t,contentHash:Qe(t)})}const _e=E,hn=d({id:_e,revision:m().int().positive(),contentHash:W}).strict(),zM=pt("kind",[d({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(d({value:gt([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."),d({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(d({value:gt([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."),d({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(d({value:gt([m(),o(),j()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:x("boolean")}).strict(),d({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(d({value:gt([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(),d({id:_e,label:o().trim().min(1).max(500),instructions:o().max(2e4),required:j(),allowAbstain:j(),requireRationale:j().optional(),anchors:v(d({value:gt([m(),o(),j()]),description:o().min(1).max(2e3)}).strict()).max(100).optional(),kind:x("preference"),requireStrength:j().optional(),allowTie:j()}).strict()]),qc=d({schemaVersion:x("openpond.humanForm.v1"),mode:k(["individual","pairwise"]),instructions:o().max(2e4),criteria:v(zM).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 s=new Set;n.anchors?.forEach((r,i)=>{const c=r.value,u=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);(!u||s.has(l))&&t.addIssue({code:"custom",path:["criteria",a,"anchors",i,"value"],message:"Each anchor must describe a unique valid raw value."}),s.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."})}),HM=d({localSource:gt([vh,SM]).optional(),recordedSource:d({id:_e,snapshotHash:W,boundaryId:_e,boundaryRevisionHash:W}).strict().optional(),experimentId:_e,attemptId:_e,taskId:_e,targetId:_e,output:hn,trace:hn.nullable(),familyKey:_e,split:k(["train","validation","test","frozen_eval"])}).strict(),yh=d({publication:hn.optional(),dataset:hn,grader:hn,graderBinding:d({id:_e,version:o().min(1).max(100),contentHash:W}).strict(),rubric:hn,attempts:v(HM).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."})}),oi=d({criterionId:_e,value:gt([m().finite(),j(),o().max(2e4),vi()]),abstain:j(),note:o().max(2e4),strength:k(["slight","moderate","strong"]).optional()}).strict(),lx=d({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."})}),dx=d({taskProposal:ri.optional(),id:_e,revision:m().int().positive(),actorId:_e,generation:m().int().positive(),evidenceHash:W,formHash:W,answers:v(oi).max(100),note:o().max(2e4),submittedAt:Ce,supersedes:_e.nullable(),contentHash:W}).strict(),ac=d({taskProposalHash:W.optional(),id:_e,revision:m().int().positive(),actorId:_e,outcome:k(["accept","reject","request_changes"]),submissions:v(d({id:_e,contentHash:W}).strict()).min(1).max(100),answers:v(oi).max(100),note:o().max(2e4),decidedAt:Ce,contentHash:W}).strict(),yd=d({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:d({proposalHash:W,dataset:hn,operationId:_e,publishedBy:_e,publishedAt:Ce}).strict().nullable(),evidence:yh,form:qc,policy:lx,status:k(["queued","assigned","in_progress","submitted","returned","accepted","rejected","cancelled"]),assigneeId:_e.nullable(),generation:m().int().positive(),drafts:v(d({taskProposal:ri.optional(),actorId:_e,generation:m().int().positive(),answers:v(oi).max(100),note:o().max(2e4),updatedAt:Ce}).strict()).max(100),submissions:v(dx).max(1e3),decisions:v(ac).max(1e3),audit:v(d({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:d({executionId:_e.nullable(),operationId:_e,boundBy:_e,configurationHash:W,generation:m().int().positive(),result:hn.nullable()}).strict().nullable(),createdAt:Ce,updatedAt:Ce,contentHash:W}).strict(),rs={operationId:_e,id:_e,expectedRevision:m().int().nonnegative()},UM=pt("action",[d({...rs,action:x("create"),projectId:_e,kind:yd.shape.kind,title:yd.shape.title,dueAt:Ce.optional(),evidence:yh,form:qc,policy:lx,assigneeId:_e.nullable()}).strict(),d({...rs,action:x("claim")}).strict(),d({...rs,action:x("bind_author_publication"),proposalHash:W,dataset:hn}).strict(),d({...rs,action:x("reserve_execution"),generation:m().int().positive(),runOperationId:_e,configurationHash:W}).strict(),d({...rs,action:x("bind_execution"),generation:m().int().positive(),executionId:_e,runOperationId:_e,configurationHash:W}).strict(),d({...rs,action:x("reassign"),assigneeId:_e.nullable(),note:o().trim().min(1).max(2e4)}).strict(),d({...rs,action:x("cancel"),note:o().max(2e4)}).strict(),d({...rs,action:x("save_draft"),taskProposal:ri.optional(),generation:m().int().positive(),answers:v(oi).max(100),note:o().max(2e4)}).strict(),d({...rs,action:x("submit"),taskProposal:ri.optional(),generation:m().int().positive(),evidenceHash:W,formHash:W,executionResult:hn.optional(),answers:v(oi).max(100),note:o().max(2e4)}).strict(),d({...rs,action:x("decide"),taskProposalHash:W.optional(),outcome:ac.shape.outcome,submissions:ac.shape.submissions,answers:ac.shape.answers,note:ac.shape.note}).strict()]),qM=pt("endpoint",[d({endpoint:x("command"),scope:_e,command:UM}).strict(),d({endpoint:x("get"),scope:_e,id:_e,revision:m().int().positive().optional()}).strict(),d({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()]),ux=yd.omit({evidence:!0,drafts:!0,submissions:!0}).extend({drafts:v(yd.shape.drafts.element.omit({taskProposal:!0}).extend({taskProposal:Ov.optional()})).max(100),submissions:v(dx.omit({taskProposal:!0}).extend({taskProposal:Ov.optional()})).max(1e3),evidence:yh.nullable(),evidenceHash:W,formHash:W,permissions:d({owner:j(),manager:j(),reviewer:j(),claim:j()}).strict()}).strict(),BM=d({items:v(ux).max(100),nextCursor:_e.nullable(),actionCount:m().int().nonnegative(),approvalAvailable:j()}).strict(),mx=d({endpoint:x("snapshot"),scope:_e,projectId:_e,graderId:_e,selections:v(d({executionId:_e,receiptId:_e}).strict()).min(1).max(2)}).strict(),FM=d({endpoint:x("snapshot_tasks"),scope:_e,projectId:_e,graderId:_e,dataset:hn,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."),VM=d({endpoint:x("inspect"),scope:_e,id:_e,slot:m().int().min(0).max(1).optional(),afterId:o().min(1).max(500).optional()}).strict(),KM=d({endpoint:x("results"),scope:_e,executionId:_e,selection:v(hn).max(1e4).optional()}).strict(),WM=d({endpoint:x("members"),scope:_e}).strict(),GM=d({endpoint:x("execute"),scope:_e,id:_e,expectedRevision:m().int().positive(),generation:m().int().positive(),operationId:_e,configuration:Ie()}).strict(),ZM=d({endpoint:x("execution"),scope:_e,id:_e,action:k(["status","result","cancel"])}).strict(),JM=mx.omit({endpoint:!0}).extend({endpoint:x("publish_evidence"),operationId:_e,audience:v(_e).max(100),workspaceVisible:j()}).strict(),QM=d({endpoint:x("publication_access"),scope:_e,projectId:_e}).strict(),YM=d({endpoint:x("revoke_publication"),scope:_e,publication:hn}).strict(),XM=d({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(),eO=d({endpoint:x("author_tasks"),scope:_e,id:_e,includeReference:x(!0).optional()}).strict(),tO=d({endpoint:x("graders"),scope:_e,projectId:_e,dataset:hn}).strict(),FW=v(d({id:_e,name:o(),version:o(),contentHash:W,mode:k(["individual","pairwise"])}).strict()).max(1e3),nO=gt([RM,CM,ox,IM,_M,QM,XM,eO,tO,JM,YM,GM,ZM,qM,mx,FM,VM,KM,WM]),aO=v(d({origin:x("owner_attested_local").optional(),coverage:d({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:Ie(),output:Ie(),error:o().nullable(),events:v(Se(o(),Ie())),eventCount:m().int().nonnegative(),evidenceLimited:j(),nextEventCursor:o().nullable(),slotIndex:m().int().nonnegative(),executionId:_e.optional(),receiptId:_e.optional()}).strict()).max(1e3),Ka=k(["train","validation","test","frozen_eval"]),sO=d({path:o().trim().min(1).max(2e3).refine(oO),mediaType:o().trim().min(1).max(200),schemaRef:na.nullable().default(null),maxBytes:m().int().positive().max(25e7).nullable().default(null),metadata:pa}).strict(),rO=d({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(),px=d({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(),Qd=d({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)}),fx=Qd.extend({kind:k(["content","schema","artifact","runtime_event","state"]),config:Se(o(),Ie())}).strict(),hx=Qd.extend({kind:x("model_judge"),rubricRef:na,calibrationStatus:k(["pending","passed","failed"]),model:d({providerId:E,modelId:E,revision:o().trim().min(1).max(500).nullable()}).strict().optional(),temperature:m().min(0).max(2).optional()}).strict(),gx=k(["isolated_javascript","sandbox_process"]),vx=Qd.extend({kind:x("custom_verifier"),runtime:gx.optional(),verifierRef:na,exportName:o().trim().min(1).max(240).optional(),timeoutMs:m().int().positive().max(3e5),networkPolicy:x("none")}).strict(),bx=Qd.extend({kind:x("human"),rubricRef:na,reviewerRole:o().trim().min(1).max(500),form:qc.optional()}).strict(),yx=gt([fx,hx,vx,bx]),Sh=d({id:E,clusterKey:E,split:Ka,input:Se(o(),Ie()),expectedOutput:Se(o(),Ie()).nullable(),policyVisibleContext:Se(o(),Ie()).default({}),privilegedContextRef:E.nullable(),artifactRefs:v(na).max(1e3).default([]),requiredOutputs:v(sO).max(1e3).optional(),tags:v(E).max(100).default([])}).strict(),Sx=d({schemaVersion:x("openpond.tasksetRelease.v2"),id:E,revision:m().int().positive(),policy:rO,environment:px,environmentRelease:d({id:E,contentHash:W}).strict().optional(),tools:v($S).max(200),capabilities:v(Ij).max(200),tasks:v(Sh).min(1).max(1e6),graders:v(yx).min(1).max(1e3),verifierSetRelease:d({id:E,contentHash:W}).strict().optional(),metrics:Uc.optional(),metadata:pa}).strict(),xx=Sx.extend({contentHash:W}).strict();function oO(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}const iO=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."),xh=pt("kind",[d({kind:x("profile")}).strict(),d({kind:x("workflow"),workflowId:E}).strict(),d({kind:x("skill"),skillPath:iO}).strict(),d({kind:x("agent_action"),actionId:E}).strict()]),cO=d({taskId:E,seed:o().min(1).max(500),fixtureId:E.nullable()}).strict(),$v=o().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),Nv=k(["input","output","expectedOutput","evaluatorContext"]),lO=v(d({graderId:E,fields:v(d({destination:Nv,path:v($v).min(1).max(20),source:Nv,sourcePath:v($v).max(20)}).strict()).max(100)}).strict()).max(100),dO=d({execution:re,originalEvidence:re,members:v(d({caseId:E,seed:o().min(1).max(500),fixtureId:W,sourceId:E,snapshotHash:W,boundaryRevisionHash:W}).strict()).min(1).max(500)}).strict(),uO=d({release:re.extend({revision:gt([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(),mO=d({schemaVersion:x("openpond.profileExternalDatasetBinding.v1"),dataset:re.extend({revision:m().int().positive()}).strict(),packageHash:W,profileId:E,target:xh,declaredProfileCatalogHash:W.nullable(),protectedProfileClosureHash:W,recordedOrigin:dO.optional(),gradingSource:d({pass:re,evidence:re}).strict().optional(),split:Ka,population:v(cO).min(1).max(1e4),evaluators:v(uO).min(1).max(100),fieldMappingsHash:W,fieldMappings:lO,environmentHash:W,privateDatasetClosureHash:W,criterion:d({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."})}),ur=mO.safeExtend({contentHash:W}).strict();function Kp(e){const t=ur.parse(e),{contentHash:n,...a}=t;if(Qe(a)!==n)throw new Error("External Dataset binding integrity failed.");return t}const pO=d({id:E,label:o().trim().min(1).max(240),description:o().max(4e3),target:xh,tasksetRelease:re,split:Ka,taskIds:v(E).min(1).max(1e5),seeds:v(o().trim().min(1).max(500)).min(1).max(100),criterion:d({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."})}),fO=d({id:E,label:o().trim().min(1).max(240),scope:k(["component","profile"]),definitionIds:v(E).min(1).max(1e3)}).strict();d({schemaVersion:x("openpond.profileEvaluations.v1"),definitions:v(pO).max(1e3),suites:v(fO).max(100)}).strict();const Sd=d({profileId:E,sourceRevision:o().trim().min(1).max(240),harnessRelease:re,catalogHash:W,definitionId:E,definitionHash:W,target:xh,environmentHash:W,externalDatasetBinding:ur.optional(),sourceCandidate:vM.optional()}).strict();class Ba extends Error{code;status;constructor(t,n=422,a){super(a?`${t}: ${a}`:t),this.code=t,this.status=n,this.name="LearningDomainError"}}const hO=d({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(),gO=d({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:hO.optional(),effectiveRequestHash:W.optional(),finishReason:o().trim().min(1).max(200).nullable().optional(),reasoningTokens:m().int().nonnegative().nullable().optional()}).strict(),vO=d({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:Fd.nullable(),feedback:v(o().max(2e4)).max(1e3),visibleEvidenceRefs:v(E).max(1e4),privilegedEvidenceRefs:v(E).max(1e4),modelJudgeReceipt:gO.optional()}).strict(),kx=vO.extend({contentHash:W}).strict(),bO=d({score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),failureClass:Fd.nullable(),gradingStatus:k(["scored","pending","unscorable","not_configured"])}).strict(),wx=bO.extend({schemaVersion:x("openpond.taskGrade.v1"),taskHash:W,evidenceHash:W,graderSetHash:W,components:v(kx).max(1e3),contentHash:W}).strict(),_l={id:!0,version:!0,weight:!0,hardGate:!0,rewardEligible:!0,privileged:!0},Bc=o().regex(/^[a-z][a-z0-9_]{0,79}$/);function yO(e){return e.feedbackKey??`reward_${Qe(e.id).slice(0,24)}`}const SO=gt([fx.omit(_l),hx.omit(_l),vx.omit(_l),bx.omit(_l),d({kind:x("learned_model"),modelVersion:re,inputContract:na}).strict()]),Ix=d({schemaVersion:x("openpond.rewardRelease.v1"),id:E,revision:m().int().positive(),name:o().trim().min(1).max(500),description:o().max(1e4),feedbackKey:Bc.optional(),implementation:SO,rawScore:d({minimum:m().finite(),maximum:m().finite()}).strict(),assets:v(na).max(1e3),fixtureSetRef:na.optional(),calibrationCheckRef:re.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=bh(e.implementation.config.jsonSchema);n.valid||t.addIssue({code:"custom",path:["implementation","config","jsonSchema"],message:n.issues[0].message})}}),Yd=Ix.safeExtend({contentHash:W}).strict(),vr=re.extend({revision:m().int().positive()}).strict(),xO=pt("kind",[d({kind:x("identity")}).strict(),d({kind:x("linear"),minimum:m().finite(),maximum:m().finite(),direction:k(["higher","lower"])}).strict()]),kh=d({graderId:E,reward:vr,role:k(["training","evaluation"]),normalization:xO,weight:m().nonnegative().max(1e3),required:j(),hardGate:j(),privileged:j(),fixtureRefs:v(re).max(1e3)}).strict(),kO=d({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:vr.optional(),sources:v(kh).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."})}),wh=kO.safeExtend({contentHash:W}).strict(),_x=d({graderId:E,reward:vr,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:kx.optional(),message:o().max(2e4).nullable()}).strict(),wO=d({schemaVersion:x("openpond.rewardComposition.v1"),binding:vr,taskHash:W,outputHash:W,results:v(_x).max(100),training:d({status:k(["scored","pending","unscorable","not_configured"]),score:m().min(0).max(1).nullable(),passed:j().nullable()}).strict(),evaluation:d({status:k(["scored","pending","unscorable","not_configured"]),score:m().min(0).max(1).nullable(),passed:j().nullable()}).strict()}).strict(),kc=wO.extend({contentHash:W}).strict();function IO(e){Ta(e);const t=Ix.parse(e);return Yd.parse({...t,contentHash:Qe(t)})}const Ih=d({harnessRelease:re,agentSnapshot:re,sourcePackageHash:W}).strict(),Bm=o().trim().min(1).max(200),Cx=d({sessionId:Bm,turnId:Bm,source:Ih,admissionHash:W,modelConfigurationHash:W,traceHash:W,runtimeEventRefs:v(Bm).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."})}),_O=d({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(Ie()).max(4002),collected:j(),environmentCleanupComplete:x(!0),snapshot:vi(),native:Cx}).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."})});_O.extend({contentHash:W}).strict();const Rx=m().finite().nonnegative(),Px=pt("kind",[d({kind:x("model"),modelId:E,configurationHash:W}).strict(),d({kind:x("harness"),source:Sd,model:d({modelId:E,configurationHash:W}).strict()}).strict(),d({kind:x("agent"),source:Ih,model:d({modelId:E,configurationHash:W}).strict()}).strict(),d({kind:x("fixture"),configurationHash:W}).strict()]),Tx=d({release:re.extend({revision:gt([m().int().positive(),o().trim().min(1).max(200)])}).strict(),feedbackKey:Bc,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."})}),_h=d({caseId:E,seed:o().trim().min(1).max(500),fixtureId:E.nullable()}).strict();function wc(e){const t=_h.parse(e);return JSON.stringify([t.caseId,t.seed,t.fixtureId])}function CO(e,t,n){return`human-projection-${Qe({originalManifest:e,selectionHash:t,rulesHash:n}).slice(0,48)}`}const RO=d({schemaVersion:x("openpond.experimentManifest.v1"),id:E,name:o().trim().min(1).max(500),teamId:E,operationId:E,maximumCostUsd:Rx.nullable(),dataset:re.extend({revision:m().int().positive()}).strict(),target:Px,execution:d({packageHash:W,runtimeTargetHash:W,metricPolicyHash:W,compatibility:d({protocol:x("openpond.evaluation-execution.v1"),targetKind:k(["model","agent","harness","fixture"])}).strict().optional()}).strict().optional(),lineage:d({definition:re.extend({revision:m().int().positive()}).strict().nullable(),execution:re,scoringPassId:E.nullable(),humanProjection:d({originalManifest:re,selectionHash:W,rulesHash:W}).strict().optional()}).strict().optional(),evaluators:v(Tx).max(100),population:v(_h).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!==CO(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(wc)).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."})}),or=RO.extend({contentHash:W}).strict(),PO=d({feedbackKey:Bc,evaluator:Tx.shape.release,status:k(["scored","unavailable","failed","pending"]),value:gt([j(),m().finite(),o().max(500)]).nullable(),passed:j().nullable().optional(),reasoning:o().max(2e4).nullable(),evidenceRefs:v(vs).max(1e3)}).strict(),TO=d({inputTokens:m().int().nonnegative().nullable(),outputTokens:m().int().nonnegative().nullable(),totalTokens:m().int().nonnegative().nullable(),costUsd:Rx.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."})}),AO=d({identity:_h,status:k(["completed","failed","cancelled","unavailable"]),output:Ie().nullable(),error:d({code:E,message:o().max(2e3)}).strict().nullable(),feedback:v(PO).max(100),usage:TO,traceRef:vs.nullable(),startedAt:Ce.nullable(),completedAt:Ce.nullable()}).strict(),Ax=d({schemaVersion:x("openpond.experimentResult.v1"),manifest:re,status:k(["completed","failed","cancelled"]),cases:v(AO).min(1).max(1e4),completedAt:Ce}).strict(),ir=Ax.extend({contentHash:W}).strict();function EO(e,t){or.parse(t),YA(t,"Experiment manifest");const n=Ax.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(wc)),s=new Set,r=new Map(t.evaluators.map(i=>[i.feedbackKey,i]));for(const i of n.cases){const c=wc(i.identity);if(!a.has(c)||s.has(c))throw new Error("Experiment result has an unexpected or repeated case.");s.add(c);const u=new Set;for(const l of i.feedback){const p=r.get(l.feedbackKey);if(!p||u.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(u.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(s.size!==a.size)throw new Error("Experiment result omits admitted cases.");return ir.parse({...n,contentHash:Qe(n)})}function Jo(e){const t=or.parse(e.manifest),n=ir.parse(e.result),{contentHash:a,...s}=n;if(Qe(s)!==a)throw new Error("Experiment result integrity failed.");return EO(s,t),{manifest:t,result:n}}function jO(e,t){for(const f of[e,t])Jo(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 y=f.execution;if(!y?.compatibility)return y??null;const{runtimeTargetHash:b,...I}=y;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,y=t.manifest.target.source;(f.profileId!==y.profileId||Qe(f.target)!==Qe(y.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!==y.environmentHash&&!b&&n.push("different_environment"),(f.definitionId!==y.definitionId||f.definitionHash!==y.definitionHash)&&n.push("different_evaluation_definition")}const s=f=>[...f.evaluators].sort((y,b)=>y.feedbackKey.localeCompare(b.feedbackKey));Qe(s(e.manifest))!==Qe(s(t.manifest))&&n.push("different_evaluators");const r=new Map(e.result.cases.map(f=>[wc(f.identity),f])),i=new Map(t.result.cases.map(f=>[wc(f.identity),f])),c=[...new Set([...r.keys(),...i.keys()])].sort();(r.size!==i.size||c.some(f=>!r.has(f)||!i.has(f)))&&n.push("different_population");const u=n.length===0,l=c.map(f=>{const y=r.get(f)??null,b=i.get(f)??null,I=new Map(y?.feedback.map(P=>[P.feedbackKey,P])??[]),C=new Map(b?.feedback.map(P=>[P.feedbackKey,P])??[]);return{identity:(y??b).identity,baseline:y,candidate:b,feedback:e.manifest.evaluators.map(P=>{const _=I.get(P.feedbackKey),M=C.get(P.feedbackKey),A=u?!y||!b?"missing_case":y.status!=="completed"||b.status!=="completed"||y.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,S=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:S,candidate:w,delta:S===null||w===null?null:w-S,baselinePassed:R(_),candidatePassed:R(M)}})}}),p=e.manifest.evaluators.map((f,y)=>{const b=l.map(T=>T.feedback[y]).filter(T=>T.eligible),I=T=>b.length?b.reduce((S,w)=>S+w[T],0)/b.length:null,C=I("baseline"),P=I("candidate"),_=T=>b.length&&b.every(S=>S[T]!==null)?b.reduce((S,w)=>S+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:u,reasons:n,cases:l,metrics:p}}const Xs=o().trim().min(1).max(200),sc=o().regex(/^[a-f0-9]{64}$/),MO=d({id:Xs,contentHash:sc}).strict(),OO=d({schemaVersion:x("openpond.trainingHandoffOrigin.v1"),teamId:Xs,projectId:Xs.nullable(),configurationId:Xs,source:d({executionId:Xs,passId:Xs.nullable(),manifestHash:sc,resultHash:sc}).strict(),dataset:d({id:Xs,revision:m().int().positive(),contentHash:sc}).strict(),target:Px,graders:v(d({feedbackKey:Xs,evaluator:MO,expectedCount:m().int().positive(),scoredCount:m().int().nonnegative(),score:m().finite().nullable()}).strict()).max(100),contentHash:sc}).strict(),$O=d({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(),Ex=d({id:E,requestHash:W,reservedUsd:m().finite().positive(),status:k(["reserved","settled","not_dispatched"]),response:$O.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."})}),jx=d({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(),Pt=Se(o(),dr()),Ye=vr,Qs=o().max(2e3).refine(e=>e===""||e.startsWith("/")&&!/~(?![01])/u.test(e),"Use an RFC 6901 JSON pointer."),NO=d({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:Se(o(),Ie()),outputSchema:Se(o(),Ie()),requiredOutputs:Sh.shape.requiredOutputs,contextRequirements:v(o().trim().min(1).max(2e3)).max(100).optional(),rewardBinding:Ye,harness:re.nullable(),execution:Sx.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 s=bh(a);s.valid||t.addIssue({code:"custom",path:[n],message:s.issues[0].message})}!!e.execution.environmentRelease!=!!e.execution.verifierSetRelease&&t.addIssue({code:"custom",path:["execution"],message:"Bind both the environment and verifier-set releases."})}),Xd=NO.safeExtend({contentHash:W}).strict(),DO=d({schemaVersion:x("openpond.taskSourceMapping.v1"),exampleId:Qs,attemptId:Qs,occurredAt:Qs,input:Qs,observedOutput:Qs.nullable(),expected:Qs.nullable(),evaluatorContext:Qs.nullable(),familyKey:Qs,split:Ka}).strict(),LO=d({modelId:E,packageHash:W,taskset:Ye,batch:Ye,rewardBinding:Ye}).strict(),zO=d({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(Ka).min(1).max(4),mapping:DO.nullable(),adapterVersion:o().trim().min(1).max(200).nullable(),reviewOrigin:LO.optional(),capturedOrigin:d({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."})}),Ch=zO.safeExtend({contentHash:W}).strict(),HO=d({schemaVersion:x("openpond.taskExample.v1"),sourceId:E,idempotencyKey:E,taskDefinition:Ye,exampleId:E,attemptId:E,occurredAt:Ce,familyKey:E.nullable(),split:Ka,input:Pt,observedOutput:Pt.nullable(),expected:Pt.nullable(),evaluatorContext:Pt.nullable(),assets:v(na).max(1e3),requiredOutputs:Sh.shape.requiredOutputs,provenance:d({sourceRecordRef:o().max(2e3).nullable(),mappingHash:W.nullable()}).strict()}).strict(),UO=d({schemaVersion:x("openpond.taskEvidence.v1"),id:E,revision:m().int().positive(),source:Ye,submission:HO,supersedes:Ye.nullable(),correctionFeedbackId:E.nullable(),receivedAt:Ce}).strict(),eu=UO.extend({contentHash:W}).strict(),qO=d({schemaVersion:x("openpond.taskRating.v1"),criteria:o().trim().min(1).max(2e4),scale:d({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."})}),BO=d({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:Pt,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=qO.safeParse(e.value);if(!n.success)for(const a of n.error.issues)t.addIssue({code:"custom",path:["value",...a.path],message:a.message})}),Mx=d({schemaVersion:x("openpond.taskFeedbackRecord.v1"),id:E,submission:BO,status:k(["pending_example","pending_review","applied","superseded","rejected"]),evidence:Ye.nullable(),createdAt:Ce,revision:m().int().positive(),submittedBy:d({id:E,role:k(["editor","reviewer","source"]),sourceId:E.nullable()}).strict().nullable().default(null),review:d({actorId:E,decision:Ye.nullable(),note:o().max(2e4),resolvedAt:Ce}).strict().nullable().default(null)}).strict(),FO=d({schemaVersion:x("openpond.taskAdmissionDecision.v1"),id:E,revision:m().int().positive(),evidence:Ye,supersedes:Ye.nullable(),actor:d({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:Pt.nullable(),grade:kc.nullable(),targetGrade:kc.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."})}),Rh=FO.safeExtend({contentHash:W}).strict(),VO=d({schemaVersion:x("openpond.taskBatch.v1"),id:E,revision:x(1),taskDefinition:Ye,rewardBinding:Ye,purpose:k(["supervised_training","reward_training","evaluation"]),examples:v(d({evidence:Ye,decision:Ye,familyKey:E,inputHash:W,split:Ka}).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,s]of e.examples.entries()){e.purpose==="evaluation"==(s.split==="train")&&t.addIssue({code:"custom",path:["examples",a,"split"],message:"Training uses train examples; evaluation uses held-out examples."});for(const r of[`family:${s.familyKey}`,`input:${s.inputHash}`])n.has(r)&&n.get(r)!==s.split&&t.addIssue({code:"custom",path:["examples",a],message:"A task family or identical input cannot cross splits."}),n.set(r,s.split)}}),Ox=VO.safeExtend({contentHash:W}).strict(),KO=d({origin:OO.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:d({mode:k(["human","qualified_automatic"]),qualification:re.nullable(),minimumApprovedExamples:m().int().positive().max(1e5)}).strict(),trigger:pt("kind",[d({kind:x("manual")}).strict(),d({kind:x("approved_count")}).strict(),d({kind:x("schedule"),intervalSeconds:m().int().min(60).max(31536e3)}).strict(),jx.extend({kind:x("nightly")}).strict(),d({kind:x("upstream_accepted"),modelProjectId:E}).strict()]),trainingParent:re,teacher:re.nullable(),training:d({method:k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),recipe:re,retentionEvaluation:re,replayBatches:v(re).max(100)}).strict(),limits:d({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:d({collect:j(),train:j(),accept:j(),serve:j()}).strict(),acceptance:d({minimumScore:m().min(0).max(1),maximumRetentionRegression:m().min(0).max(1),requireImprovement:j(),rollbackVersion:re.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."})}),WO=KO.safeExtend({contentHash:W}).strict(),GO=d({iterationId:E,iterationRevision:m().int().positive(),candidate:re,decision:Ye,decidedAt:Ce}).strict(),ZO=k(["waiting_for_data","waiting_for_review","ready","dispatching","training","evaluating","candidate_ready","accepted","rejected","paused","failed","cancelling","cancelled","completed_without_candidate"]),JO=d({schemaVersion:x("openpond.learningIteration.v1"),id:E,revision:m().int().positive(),policy:Ye,status:ZO,triggerIdentity:E,batch:Ye.nullable(),sourceWatermarks:Se(E,m().int().nonnegative()),trainingParent:re,trainingParentSelection:GO.nullable().optional(),teacher:re.nullable(),upstreamEvent:re.nullable(),trainingJob:re.nullable(),evaluationJob:re.nullable(),candidateVersion:re.nullable(),candidateDecision:Ye.nullable().default(null),candidateDecisionAt:Ce.nullable().optional(),dispatchId:E,retryCount:m().int().nonnegative(),spendUsd:m().nonnegative(),failure:d({code:E,message:o().max(2e4)}).strict().nullable(),createdAt:Ce,updatedAt:Ce}).strict(),QO=d({schemaVersion:x("openpond.taskGradeRun.v1"),id:E,revision:m().int().positive(),evidence:Ye,binding:Ye,target:k(["observed","proposed_target"]),output:Pt,status:k(["queued","running","completed","failed","cancelling","cancelled"]),composition:kc.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(Ex).max(1e4).optional(),requestedBy:E.optional(),failure:o().max(2e4).nullable(),createdAt:Ce,updatedAt:Ce}).strict();gt([Xd,Yd,wh,Ch,eu,Mx,Rh,Ox,WO,JO,QO]);function VW(e){return Ye.parse({id:e.id,revision:e.revision,contentHash:e.contentHash})}function KW(e,t){return e.id===t.id&&e.revision===t.revision&&e.contentHash===t.contentHash}function WW(e){return Ta(e,16777216),{...e,contentHash:Qe(e)}}function GW(e){const{contentHash:t,...n}=e;if(Ta(n,16777216),Qe(n)!==t)throw new Ba("learning_content_hash_mismatch",422)}const $x=d({schemaVersion:x("openpond.learningTextAsset.v1"),id:E,revision:x(1),asset:na,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!==Gf(e.text)&&t.addIssue({code:"custom",path:["asset","contentHash"],message:"Asset source does not match its SHA-256."})}),tu=$x.safeExtend({contentHash:W}).strict();function Cl(e){Ta(e);const{text:t,...n}=e,a=Gf(t),s=`asset-${a}-${Qe(n).slice(0,16)}`,r=$x.parse({schemaVersion:"openpond.learningTextAsset.v1",id:s,revision:1,asset:{...n,id:s,contentHash:a,sizeBytes:new TextEncoder().encode(t).byteLength},text:t});return tu.parse({...r,contentHash:Qe(r)})}function Dv(e,t){const{contentHash:n,...a}=tu.parse(e);if(Qe(a)!==n||Qe(a.asset)!==Qe(t))throw new Ba("learning_asset_reference_mismatch",409);return a.text}const Nx=d({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:d({evidence:Ye,feedback:d({id:E,revision:m().int().positive()}).strict()}).strict().optional()}).strict(),Dx=d({name:o().max(500),description:o().max(1e4),feedbackKey:Bc.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(Nx).max(50).optional()}).strict(),YO=d({name:o().max(500),description:o().max(1e4),instructions:o().max(2e4),input:o(),output:o(),familyNamespace:o(),sources:v(kh).max(100),recipeRef:vr.optional()}).strict(),XO=d({name:o().max(500),description:o().max(1e4),sources:v(kh).max(100)}).strict(),e$=k(["definition","reward","binding"]),Fm=d({id:E,targetId:E,baseRelease:Ye.nullable(),editorVersion:x("openpond.modelsEditor.v1")}),Vm=pt("targetKind",[Fm.extend({targetKind:x("definition"),fields:YO}).strict(),Fm.extend({targetKind:x("reward"),fields:Dx}).strict(),Fm.extend({targetKind:x("binding"),fields:XO}).strict()]),Km={schemaVersion:x("openpond.authoringDraft.v1"),revision:m().int().positive(),status:k(["draft","archived","published"]),publishedRelease:Ye.nullable(),createdAt:Ce,updatedAt:Ce},Wm=pt("targetKind",[Vm.options[0].extend(Km).strict(),Vm.options[1].extend(Km).strict(),Vm.options[2].extend(Km).strict()]),ZW=pt("targetKind",[Wm.options[0].extend({contentHash:W}).strict(),Wm.options[1].extend({contentHash:W}).strict(),Wm.options[2].extend({contentHash:W}).strict()]),JW=d({draft:Ye,targetKind:e$,release:Ye}).strict(),za={bytes:5*1024*1024,records:1e3,files:100,messages:2e3},Lx=k(["json","jsonl","csv","hermes","openclaw"]),t$=d({path:o().min(1).max(500),text:o()}).strict(),Ph=d({id:o().min(1).max(200),familyKey:o().min(1).max(200),split:Ka,kind:k(["task","attempt"]),input:Pt,observedOutput:Pt.nullable(),expected:Pt.nullable(),sourceId:o().min(1).max(2e3),sourceHash:o().length(64),occurredAt:o().datetime().nullable(),metadata:Pt,warnings:v(o().max(2e3)).max(100),needsContext:j()}).strict(),zx=d({schemaVersion:x("openpond.taskIntakePreview.v1"),format:Lx,contentHash:o().length(64),records:v(Ph).max(za.records),issues:v(d({file:o(),row:m().int().positive().nullable(),message:o()}).strict()).max(1e3)}).strict();function xd(e,t){return`${e}-${Qe(t)}`}function Hx(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 n$=`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 QW(e){Ta(e,262144);const t=Dx.parse(e.fields),n=e.base?Yd.parse(e.base):null;if(n&&n.id!==e.id)throw new Ba("reward_authoring_base_mismatch",422);const a=t.fixtures?.length?Cl({text:JSON.stringify(t.fixtures),path:"reward-fixtures.json",mediaType:"application/json",visibility:"verifier"}):null;let s=null,r,i;if(t.kind==="custom_verifier")s=Cl({text:t.code,path:"verifier.mjs",mediaType:"application/javascript",visibility:"verifier"}),r={kind:t.kind,verifierRef:s.asset,exportName:t.exportName,timeoutMs:zo(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 Ba("reward_rubric_required",422,"Write the rubric before checking or publishing this Reward.");if(s=Cl({text:t.rubric,path:"rubric.md",mediaType:"text/markdown",visibility:"verifier"}),t.kind==="human")r={kind:t.kind,rubricRef:s.asset,reviewerRole:t.reviewerRole,form:qc.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=zo(t.temperature,"Temperature"),f=n?.implementation,y=f?.kind==="model_judge"&&f.rubricRef.contentHash===s.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;r={kind:t.kind,rubricRef:s.asset,model:l,temperature:p,calibrationStatus:y?f.calibrationStatus:"pending"},y&&(i=n?.calibrationCheckRef)}}else t.kind==="learned_model"?(Lo(t.inputContract,"Model input contract"),s=Cl({text:t.inputContract,path:"input-contract.json",mediaType:"application/json",visibility:"verifier"}),r={kind:t.kind,modelVersion:{id:t.learnedId,contentHash:t.learnedHash},inputContract:s.asset}):t.kind==="state"?r={kind:t.kind,config:{fields:zv(t.fields)}}:t.kind==="content"?r={kind:t.kind,config:{outputField:t.outputField,expectedField:t.expectedField,...t.expectedValue?{expectedValue:t.expectedValue}:{}}}:t.kind==="schema"?r={kind:t.kind,config:{jsonSchema:Lo(t.schema,"Output schema")}}:t.kind==="artifact"?r={kind:t.kind,config:{refIncludes:t.reference}}:r={kind:t.kind,config:{requiredEvents:zv(t.events)}};const c=[...s?[s]:[],...a?[a]:[]];return{reward:IO({schemaVersion:"openpond.rewardRelease.v1",id:e.id,revision:(n?.revision??0)+1,name:t.name,description:t.description,feedbackKey:t.feedbackKey??yO({id:e.id}),implementation:r,rawScore:t.kind==="learned_model"?{minimum:zo(t.minimum,"Minimum score"),maximum:zo(t.maximum,"Maximum score")}:{minimum:0,maximum:1},assets:c.map(l=>l.asset),...a?{fixtureSetRef:a.asset}:{},...i?{calibrationCheckRef:i}:{}}),assets:c}}function YW(e,t,n=null){const a=e?.implementation,s=a&&"verifierRef"in a?a.verifierRef:a&&"rubricRef"in a?a.rubricRef:a&&"inputContract"in a?a.inputContract:null;if(s&&!t)throw new Ba("reward_source_required",422);const r=s&&t?Dv(t,s):"";if(e?.fixtureSetRef&&!n)throw new Ba("reward_fixtures_required",422);const i=e?.fixtureSetRef&&n?Nx.array().max(50).parse(JSON.parse(Dv(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:Lv(c.fields).join(", ")||"answer",outputField:Rl(c.outputField)||"text",expectedField:Rl(c.expectedField)||"text",expectedValue:Rl(c.expectedValue),schema:JSON.stringify(c.jsonSchema??{type:"object",properties:{answer:{type:"string"}},required:["answer"]},null,2),reference:Rl(c.refIncludes),events:Lv(c.requiredEvents).join(", "),code:a?.kind==="custom_verifier"?r:n$,verifierRuntime:a?.kind==="custom_verifier"?a.runtime??"isolated_javascript":"isolated_javascript",exportName:a?.kind==="custom_verifier"?a.exportName??"verify":"verify",timeout:String(a?.kind==="custom_verifier"?a.timeoutMs:5e3),rubric:a?.kind==="model_judge"||a?.kind==="human"?r:"",providerId:a?.kind==="model_judge"?a.model?.providerId??"":"",modelId:a?.kind==="model_judge"?a.model?.modelId??"":"",modelRevision:a?.kind==="model_judge"?a.model?.revision??"":"",temperature:String(a?.kind==="model_judge"?a.temperature??0:0),reviewerRole:a?.kind==="human"?a.reviewerRole:"Subject matter reviewer",humanForm:a?.kind==="human"&&a.form?JSON.stringify(a.form,null,2):"",learnedId:a?.kind==="learned_model"?a.modelVersion.id:"",learnedHash:a?.kind==="learned_model"?a.modelVersion.contentHash:"",inputContract:a?.kind==="learned_model"?r:"{}",minimum:String(e?.rawScore.minimum??0),maximum:String(e?.rawScore.maximum??1),...i.length?{fixtures:i}:{}}}function Lo(e,t){try{const n=JSON.parse(e);return Ta(n,131072),Pt.parse(n)}catch{throw new Ba("reward_authoring_json_invalid",422,`${t} must be a JSON object.`)}}function zo(e,t){const n=Number(e);if(!e.trim()||!Number.isFinite(n))throw new Ba("reward_authoring_number_invalid",422,`${t} must be a finite number.`);return n}function Rl(e){return typeof e=="string"?e:""}function Lv(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function zv(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}const Ux=d({id:E,name:o().trim().min(1).max(500),input:Pt,output:Pt,expectedOutput:Pt.nullable(),evaluatorContext:Pt.nullable(),artifactRefs:v(E).max(100),runtimeEventRefs:v(E).max(100),infrastructureError:o().max(2e4).nullable(),expected:pt("status",[d({status:x("scored"),minimum:m().finite(),maximum:m().finite(),passed:j().nullable()}).strict(),d({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."})}),a$=d({id:E,packageVersion:o().min(1).max(100),engine:o().min(1).max(200)}).strict(),s$=d({fixture:d({id:E,contentHash:W}).strict(),result:_x,matchesExpectation:j()}).strict(),XW=d({schemaVersion:x("openpond.rewardCheckRun.v1"),id:E,revision:m().int().positive(),draft:Ye,reward:Ye,snapshotHash:W,fixtureRefs:v(d({id:E,contentHash:W}).strict()).min(1).max(50),status:k(["queued","running","completed","failed","cancelling","cancelled"]),runtime:a$.nullable(),results:v(s$).max(50),matchesExpectations:j().nullable(),failure:o().max(2e4).nullable(),timeoutMs:m().int().min(100).max(3e5),maximumSpendUsd:m().nonnegative().max(1e3),judgeCalls:v(Ex).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 Ba("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 Ba("reward_fixture_id_duplicate",422);return e.map(t=>Ux.parse({id:t.id,name:t.name,input:Lo(t.input,`${t.name}: input`),output:Lo(t.output,`${t.name}: output`),expectedOutput:t.expectedOutput.trim()?Lo(t.expectedOutput,`${t.name}: expected answer`):null,evaluatorContext:t.evaluatorContext.trim()?Lo(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:zo(t.minimumScore,`${t.name}: minimum score`),maximum:zo(t.maximumScore,`${t.name}: maximum score`),passed:t.expectedPassed==="any"?null:t.expectedPassed==="true"}:{status:t.expectedStatus}}))}function r$(e){const t=[];let n=[],a="",s=!1,r=!1;const i=()=>{n.push(a),a="",r=!1},c=()=>{if(i(),n.some(p=>p.length)&&t.push(n),n=[],t.length>za.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(s)f==='"'&&e[p+1]==='"'?(a+='"',p++):f==='"'?(s=!1,r=!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&&!r)s=!0;else{if(r||f==='"')throw new Error("CSV has an invalid quoted field.");a+=f}}if(s)throw new Error("CSV has an unterminated quoted field.");(a||n.length||r)&&c();const u=t.shift()?.map(p=>p.trim().replace(/^\uFEFF/u,""));if(!u?.includes("instruction"))throw new Error("CSV requires an instruction column.");const l=new Set(["instruction","context","reference","labels","id","familyKey","split"]);if(u.some(p=>!l.has(p))||new Set(u).size!==u.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!==u.length)throw new Error(`CSV record ${f+2} has a different number of columns from its header.`);return Object.fromEntries(u.map((y,b)=>[y,p[b]]).filter(([,y])=>y!==""))})}function t8(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 qx(e){return e.startsWith("\uFEFF")?e.slice(1):e}const Bx=d({role:o().min(1),content:dr().nullable().optional()}).catchall(dr()),o$=d({id:o().min(1),messages:v(Bx).min(1).max(za.messages),lineage_session_ids:v(o()).optional(),parent_session_id:o().nullable().optional()}).catchall(dr());function i$(e){const t=o$.parse(e),n=t.lineage_session_ids?.[0]??t.parent_session_id??t.id,{messages:a,segments:s,...r}=t;return Fx("hermes",t.id,n,t.messages,{sourceHash:Qe(e),metadata:{session:r},warnings:["Imported session context and tools need review before this can become an executable task."]})}const c$=d({traceSchema:x("openclaw-trajectory"),schemaVersion:x(1),traceId:o().min(1),sessionId:o().min(1),leafId:o().nullable(),eventCount:m().int().nonnegative(),warnings:v(Pt).optional()}).catchall(dr()),l$=d({traceSchema:x("openclaw-trajectory"),schemaVersion:x(1),traceId:o(),sessionId:o(),seq:m().int().nonnegative(),type:o(),ts:o()}).catchall(dr()),d$=d({header:Pt.nullable(),leafId:o().nullable(),entries:v(d({id:o().min(1),type:o().min(1),parentId:o().nullable().optional(),message:Bx.optional()}).catchall(dr())).max(za.messages)}).strict();function u$(e){const t=c=>{const u=e.find(l=>l.path===c);if(!u)throw new Error(`OpenClaw bundle is missing ${c}.`);return qx(u.text)},n=c$.parse(JSON.parse(t("manifest.json"))),a=d$.parse(JSON.parse(t("session-branch.json")));if(a.leafId!==n.leafId)throw new Error("OpenClaw manifest and session branch identify different leaves.");const s=t("events.jsonl").split(/\r?\n/u).filter(c=>c.trim()).map(c=>l$.parse(JSON.parse(c)));if(s.length!==n.eventCount||s.some(c=>c.traceId!==n.traceId||c.sessionId!==n.sessionId))throw new Error("OpenClaw events do not match the manifest identity or count.");if(a.header&&a.header.id!==n.sessionId)throw new Error("OpenClaw session header does not match the manifest.");const r=new Set;for(const[c,u]of a.entries.entries()){if(r.has(u.id))throw new Error("OpenClaw branch contains duplicate entry IDs.");if(c&&u.parentId!==a.entries[c-1].id)throw new Error("OpenClaw branch is incomplete or out of order.");r.add(u.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 Fx("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 Fx(e,t,n,a,s){const r=a.flatMap((c,u)=>c.role==="user"?[u]:[]);if(!r.length)throw new Error("This history contains no user request. Supply a session with its request context.");let i=0;return r.map((c,u)=>{const l=r[u+1]??a.length,p=a.slice(c+1,l),f=p.filter(C=>C.role==="assistant").at(-1),y=a[c],b=y.entryId??y.message_id??y.id??Qe({start:c,request:y}),I={id:xd(e,[t,b]),familyKey:xd(e,n),split:"train",kind:"attempt",input:{request:y.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:s.sourceHash,occurredAt:Hx(f?.timestamp??y.timestamp),metadata:s.metadata,warnings:[...s.warnings,...f?[]:["No assistant response was recorded for this request."]],needsContext:!0};if(Ta(I),i+=new TextEncoder().encode(JSON.stringify(I)).length,i>za.bytes)throw new Error("Expanded history exceeds the 5 MiB preview limit. Export a smaller session selection.");return Ph.parse(I)})}const m$=d({instruction:o().trim().min(1).max(1e5),context:gt([o(),Pt]).optional(),reference:gt([o(),Pt]).optional(),labels:gt([o(),v(o()),Pt]).optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Ka.optional()}).strict(),p$=d({input:Pt,observedOutput:Pt.nullable().optional(),expectedOutput:Pt.nullable().optional(),id:o().min(1).max(200).optional(),familyKey:o().min(1).max(200).optional(),split:Ka.optional(),occurredAt:o().datetime().optional(),labels:Pt.optional()}).strict();function f$(e){const t=Lx.parse(e.format),n=v(t$).min(1).max(za.files).parse(e.files);if(n.reduce((l,p)=>l+new TextEncoder().encode(p.text).length,0)>za.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=[],s=[],r=new Map,i=new Map;let c=0;function u(l,p,f){try{const y=f();if(a.length+y.length>za.records)throw new Error("Import exceeds the 1,000-record limit.");const b=new Map(r),I=new Map(i);let C=0;for(const P of y){Ta(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>za.bytes*2)throw new Error("Expanded import exceeds the 10 MiB preview limit. Select fewer source files.");for(const P of y)r.has(P.id)||a.push(P),r.set(P.id,Qe(P));for(const[P,_]of I)i.set(P,_);c+=C}catch(y){s.push({file:l,row:p,message:y instanceof HT?`Unsupported record fields or values (${y.issues.slice(0,3).map(b=>b.path.join(".")||"record").join(", ")}).`:y instanceof SyntaxError?"Invalid JSON.":y instanceof Error?y.message:"Invalid import record."})}}if(t==="openclaw")u("manifest.json",null,()=>u$(n));else for(const l of n){const p=qx(l.text);if(t==="jsonl"||t==="hermes"){for(const[f,y]of p.split(/\r?\n/u).entries())if(y.trim()){if(s.length>=za.records)break;u(l.path,f+1,()=>t==="hermes"?i$(JSON.parse(y)):[Hv(JSON.parse(y))])}}else{let f;try{const y=t==="csv"?r$(p):JSON.parse(p);f=Array.isArray(y)?y:[y]}catch(y){u(l.path,null,()=>{throw y});continue}if(f.length>za.records){u(l.path,null,()=>{throw new Error("Import exceeds the 1,000-record limit.")});continue}f.forEach((y,b)=>u(l.path,b+(t==="csv"?2:1),()=>[Hv(y)]))}}return zx.parse({schemaVersion:"openpond.taskIntakePreview.v1",format:t,contentHash:Qe({format:t,files:n}),records:a,issues:s.slice(0,1e3)})}function Hv(e){const t=gt([m$,p$]).parse(e),n="instruction"in t,a=n?{instruction:t.instruction,...t.context===void 0?{}:{context:t.context}}:t.input,s=n?t.reference===void 0?null:typeof t.reference=="string"?{text:t.reference}:t.reference:t.expectedOutput??null,r=n?null:t.observedOutput??null,i=t.familyKey??xd("family",a),c=t.id??xd("task",{input:a,expected:s,observedOutput:r});return Ph.parse({id:c,familyKey:i,split:t.split??"train",kind:r?"attempt":"task",input:a,expected:s,observedOutput:r,sourceId:c,sourceHash:Qe(e),occurredAt:n?null:Hx(t.occurredAt),metadata:t.labels===void 0?{}:{importedLabels:t.labels,labelOrigin:"unverified_import"},warnings:[],needsContext:!1})}var Vr=Ye.shape.id,Ic=o().regex(/^[a-f0-9]{64}$/),h$=d({scopeId:Vr,modelId:Vr}).strict(),g$=d({schemaVersion:x("openpond.modelTasksetAuthoring.v1"),owner:h$,root:Ye,parent:Ye}).strict(),n8=d({schemaVersion:x("openpond.modelTasksetDraftRequest.v1"),operationId:Vr,modelId:Vr,expectedModelRevision:m().int().positive(),sourcePackageHash:Ic}).strict(),v$=d({schemaVersion:x("openpond.modelTasksetDraftPreparation.v1"),draftId:Vr,requestHash:Ic,sourcePackageHash:Ic,sourceTasksetRef:Ye,tasksetId:Vr,tasksetRevision:m().int().positive(),lineage:g$,authoringGraph:x("bound").optional()}).strict(),nu=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."),Vx=d({path:nu,sizeBytes:m().int().nonnegative(),writable:j()}).strict(),Kx=d({encoding:k(["utf8","base64"]),data:o().max(8e6)}).strict(),b$=Vx.extend({contentHash:Ic,content:Kx}).strict();d({draftId:Vr,expectedDraftRevision:m().int().positive(),path:nu,expectedFileHash:Ic.nullable(),content:Kx.nullable()}).strict();var y$=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),S$=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]),x$=class Wx{state=new Uint32Array(y$);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 s=Math.min(64-this.pendingLength,n.length);this.pending.set(n.subarray(0,s),this.pendingLength),this.pendingLength+=s,a+=s,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 Wx;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,s=new DataView(n.buffer);return s.setUint32(n.length-8,Math.floor(a/4294967296),!1),s.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,r=>r.toString(16).padStart(8,"0")).join("")}compress(t){const n=new DataView(t.buffer,t.byteOffset,64),a=this.state,s=this.words;for(let b=0;b<16;b+=1)s[b]=n.getUint32(b*4,!1);for(let b=16;b<64;b+=1){const I=s[b-15],C=s[b-2],P=os(I,7)^os(I,18)^I>>>3,_=os(C,17)^os(C,19)^C>>>10;s[b]=s[b-16]+P+s[b-7]+_>>>0}let r=a[0],i=a[1],c=a[2],u=a[3],l=a[4],p=a[5],f=a[6],y=a[7];for(let b=0;b<64;b+=1){const I=l&p^~l&f,C=r&i^r&c^i&c,P=os(r,2)^os(r,13)^os(r,22),_=os(l,6)^os(l,11)^os(l,25),M=y+_+I+S$[b]+s[b]>>>0,A=P+C>>>0;y=f,f=p,p=l,l=u+M>>>0,u=c,c=i,i=r,r=M+A>>>0}a[0]=a[0]+r>>>0,a[1]=a[1]+i>>>0,a[2]=a[2]+c>>>0,a[3]=a[3]+u>>>0,a[4]=a[4]+l>>>0,a[5]=a[5]+p>>>0,a[6]=a[6]+f>>>0,a[7]=a[7]+y>>>0}};function k$(e){return new x$().update(e).digestHex()}function os(e,t){return e>>>t|e<<32-t}var w$=2e3,Gx=25e7,_n=o().trim().min(1).max(240),fn=o().regex(/^[a-f0-9]{64}$/),Wp=o().datetime({offset:!0}),a8=Se(o(),Ie()).default({}),vt=d({id:_n,contentHash:fn}).strict(),I$=vt.extend({revision:m().int().positive()}).strict(),Gp=d({id:_n,path:o().trim().min(1).max(w$).refine(R$),contentHash:fn,sizeBytes:m().int().nonnegative().max(Gx),mediaType:o().trim().min(1).max(200),visibility:k(["policy","verifier","host_private"])}).strict(),s8=d({id:_n,contentHash:fn,mediaType:o().trim().min(1).max(200).nullable().default(null),sizeBytes:m().int().nonnegative().max(Gx).nullable().default(null)}).strict(),_$=k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]);function C$(e){return`${JSON.stringify(Zp(e),null,2)}
|
|
108
|
+
`}function Zx(e){return k$(e)}function zt(e){return Zx(C$(e))}function r8(e,t){const{contentHash:n,...a}=e,s=zt(a);if(n!==s)throw new Error(`${t} contentHash is ${n}; expected ${s}.`)}function R$(e){const t=e.replaceAll("\\","/");return!t||t.startsWith("/")||t.includes("\0")?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function Zp(e){return Array.isArray(e)?e.map(Zp):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Zp(n)]))}d({provider:_n,model:_n,revision:o().trim().min(1).max(500).nullable().default(null),artifactHash:fn.nullable().default(null),tokenizerRevision:o().trim().min(1).max(500).nullable().default(null),chatTemplateHash:fn.nullable().default(null)}).strict();var P$=["openpond","codex","claude-code","grok-build","opencode","anthropic","openai","xai","google","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],T$=k(P$),Th=d({providerId:T$,modelId:o().trim().min(1).max(300)}),A$=jx.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."})}),o8=67108864,Jp=524288,rc=class extends Error{code;constructor(e,t){super(t),this.name="OpenPondProtocolError",this.code=e}};function Ah(e){return JSON.stringify(Qp(e))}function E$(e){return new TextEncoder().encode(Ah(e)).byteLength}async function j$(e){const t=new TextEncoder().encode(Ah(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 M$(e,t,n){const a=E$(e);if(a>t)throw new rc("payload_too_large",`${n} is ${a} bytes; the maximum is ${t} bytes.`)}function Qp(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new rc("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=>Qp(t));if(typeof e=="object"){const t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw new rc("non_json_value","Canonical JSON accepts only plain objects.");const n={};for(const a of Object.keys(e).sort()){const s=e[a];if(s===void 0||typeof s=="function"||typeof s=="symbol")throw new rc("non_json_value",`Canonical JSON cannot contain ${typeof s} at ${a}.`);n[a]=Qp(s)}return n}throw new rc("non_json_value",`Canonical JSON cannot contain ${typeof e}.`)}var Et=o().trim().min(1).max(500),ms=o().regex(/^[a-f0-9]{64}$/),Ia=o().datetime({offset:!0}),Kr=d({id:Et,contentHash:ms}).strict(),qa=Kr.extend({revision:m().int().positive()}).strict(),Fc=d({schemaVersion:x("openpond.baseModelPreference.v1"),modelId:Et,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:Et.nullable(),source:k(["managed","local","builtin"])}).strict(),Jx=k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),O$=d({schemaVersion:o().regex(/^openpond\.[A-Za-z0-9]+Recipe\.v\d+$/),method:Jx,parameterization:k(["lora","full"])}).catchall(Ie()),$$=d({profileProjectId:Et,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),harnessRelease:Kr}).strict(),N$=d({profileProjectId:Et,sourceRevision:o().regex(/^[a-f0-9]{40,64}$/),catalogHash:ms,definitionId:Et,harnessRelease:Kr,tasksetRelease:Kr}).strict(),Qx=d({tasksetRef:qa.nullable().default(null),evaluationTasksetRef:qa.nullable().optional(),profileSource:$$.nullable().optional(),profileEvaluation:N$.nullable().optional(),rewardBindingRef:qa.nullable().optional(),tasksetRelease:Kr.nullable().default(null),harnessRelease:Kr.nullable().default(null),baseModel:Fc.nullable().default(null),method:Jx.nullable().default(null),destinationId:Et.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:O$.nullable().default(null),preferredMaximumSpendUsd:m().nonnegative().nullable().default(null),preferredRetentionDays:m().int().nonnegative().nullable().default(null)}).strict(),Yx=Qx.omit({managedGpuRequirement:!0}),D$=d({schemaVersion:x("openpond.hostedModelProjectLink.v1"),apiOrigin:o().url().refine(e=>new URL(e).origin===e,"Use a canonical API origin.").nullable().default(null),teamId:Et,projectId:Et,portableProjectId:Et,revision:m().int().positive(),etag:ms,syncedSourceRevision:m().int().positive(),syncedAt:Ia,tasksets:v(d({localTasksetId:Et,localTasksetHash:ms.nullable().default(null),releaseId:Et,releaseRevision:m().int().positive(),releaseHash:ms,packageHash:ms.nullable().default(null),hostedTasksetId:Et,syncedAt:Ia}).strict()).max(1e4).default([])}).strict(),L$=d({localTasksetId:Et,releaseId:Et,releaseRevision:m().int().positive(),releaseHash:ms,state:k(["syncing","synced","sync_failed"]),hostedTasksetId:Et.nullable().default(null),lastAttemptAt:Ia,syncedAt:Ia.nullable().default(null),lastError:o().trim().min(1).max(5e3).nullable().default(null)}).strict(),Xx=d({schemaVersion:x("openpond.modelProject.v2"),id:Et,profileId:Et,revision:m().int().positive().default(1),name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Fc.nullable(),defaultDestinationId:Et.nullable(),trainingSetup:Qx,hosted:D$.nullable().default(null),tasksetSyncs:v(L$).max(1e4).default([]),createdAt:Ia,updatedAt:Ia}).strict(),ek=Xx.pick({id:!0,profileId:!0,name:!0,objective:!0,defaultBaseModel:!0,defaultDestinationId:!0,trainingSetup:!0}),z$=d({schemaVersion:x("openpond.modelProjectSave.v1"),operationId:Et,expectedRevision:m().int().nonnegative(),project:ek,learning:A$.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."})}),tk=d({schemaVersion:x("openpond.modelProjectConfigurationCheck.v1"),configurationHash:ms,projectId:Et,expectedRevision:m().int().nonnegative(),checkedAt:Ia,canSave:j(),deferred:v(k(["base_model","taskset"])).max(2),findings:v(d({code:Et,severity:k(["error","warning"]),message:o().min(1).max(5e3),field:o().min(1).max(500).nullable()}).strict()).max(100)}).strict();d({id:Et,name:o().min(1).max(500),available:j(),preference:Fc}).strict();function H$(e){try{Ta(e,Jp)}catch{throw new F$(400,{schemaVersion:"openpond.modelProjectApiError.v2",code:"model_configuration_json_invalid",message:"Model configuration must be bounded JSON data.",retryable:!1,requestId:null,details:{}})}return z$.parse(e)}async function U$(e,t,n){Ta(e,Jp);const a=ek.parse(e);M$(a,Jp,"Model configuration");const s=await j$({project:a,expectedRevision:t});return H$({schemaVersion:"openpond.modelProjectSave.v1",operationId:`model-save:${s}`,expectedRevision:t,project:a})}d({schemaVersion:x("openpond.hostedModelProjectSync.v2"),portableProjectId:Et,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Fc.nullable(),defaultDestinationId:Et.nullable(),trainingSetup:Yx,sourceRevision:m().int().positive(),sourceUpdatedAt:Ia,expectedEtag:ms.nullable().default(null)}).strict();var q$=d({id:Et,teamId:Et,portableProjectId:Et,name:o().trim().min(1).max(200),objective:o().trim().max(5e3).nullable(),defaultBaseModel:Fc.nullable(),defaultDestinationId:Et.nullable(),trainingSetup:Yx,sourceRevision:m().int().positive(),sourceUpdatedAt:Ia,revision:m().int().positive(),etag:ms,createdAt:Ia,updatedAt:Ia}).strict(),B$=d({kind:k(["taskset_release","harness_release","dataset_release","evidence_set","model_version","reward_model_version","evaluation_receipt"]),ref:Kr,role:o().trim().min(1).max(200).nullable().default(null),updatedAt:Ia}).strict();d({project:q$,resources:v(B$).max(1e4),jobCount:m().int().nonnegative(),latestJobIds:v(Et).max(100)}).strict();d({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:Se(o(),Ie()).default({})}).strict();var F$=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 V$="openpond.connectedEvidence.v1",K$="connected-evidence-1",Pl={files:100,sourceBytes:32*1024*1024,events:1e5,sessions:1e3,boundaries:5e3},ma=o().min(1).max(500),uc=o().regex(/^[a-f0-9]{64}$/),W$=o().datetime().nullable(),Tl=m().int().nonnegative().nullable(),nk=k(["native_chat","native_work","codex","claude_code","hermes","openclaw","opencode","grok_build","pi","oh_my_pi"]),G$=d({invocationId:ma,inputTokens:Tl,outputTokens:Tl,cachedInputTokens:Tl,totalTokens:Tl,provenance:k(["billed_invocation","reported_invocation","reported_cumulative"])}).strict(),Uv=d({id:ma,sequence:m().int().nonnegative(),occurredAt:W$,kind:k(["message","tool_call","tool_result","compaction","artifact","terminal","usage","unknown"]),role:k(["user","assistant","system","tool"]).nullable(),callId:ma.nullable(),parentId:ma.nullable(),content:dr(),usage:G$.nullable()}).strict(),Z$=d({id:ma,familyKey:ma,projection:k(["turn","conversation"]),requestEventId:ma,start:m().int().nonnegative(),end:m().int().positive(),inputHash:uc,outputHash:uc.nullable(),revisionHash:uc,terminal:k(["completed","failed","cancelled","unknown"]),coverage:d({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();d({schemaVersion:x(V$),normalizerVersion:x(K$),origin:nk,sessionId:ma,branchId:ma.nullable(),parentSessionId:ma.nullable(),exporterVersion:o().max(200).nullable(),acquisition:d({machineId:ma,sourceInstanceId:ma}).strict().optional(),sourceFiles:v(d({path:ma,contentHash:uc,sizeBytes:m().int().nonnegative()}).strict()).max(Pl.files),events:v(Uv).max(Pl.events),unmappedEvents:v(Uv).max(Pl.events),boundaries:v(Z$).max(Pl.boundaries),warnings:v(o().max(500)).max(100),contentHash:uc}).strict();const J$=d({schemaVersion:x("openpond.humanResultView.v1"),executionId:o().min(1),executionHash:o().regex(/^[a-f0-9]{64}$/),selection:v(hn).max(1e4),coverage:d({pending:m().int().nonnegative(),submitted:m().int().nonnegative(),accepted:m().int().nonnegative(),rejected:m().int().nonnegative(),cancelled:m().int().nonnegative()}).strict(),results:v(d({review:hn,decision:hn.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:hn,answers:v(oi).max(100)}).strict()).max(1e4)}).strict(),qv=J$.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),kd=o().regex(/^[a-f0-9]{64}$/),_c=o().min(1).max(240),Al={feedbackKey:_c,criterionId:_c},Q$=pt("kind",[d({...Al,kind:x("normalized_score"),minimum:m().finite(),maximum:m().finite(),passThreshold:m().min(0).max(1).optional()}).strict(),d({...Al,kind:x("boolean")}).strict(),d({...Al,kind:x("category")}).strict(),d({...Al,kind:x("preference_score"),tieScore:m().min(0).max(1).nullable()}).strict()]),Bv=d({execution:re,resultHash:kd,reviews:v(d({review:hn,decision:hn}).strict()).min(1).max(1e4)}).strict(),ak=d({rules:v(Q$).min(1).max(100),baseline:Bv,candidate:Bv}).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."})}),Fv=d({manifest:or,result:ir}).strict(),Vv=d({id:_c,manifestHash:kd,resultHash:kd}).strict(),Y$=d({schemaVersion:x("openpond.humanComparisonProjection.v1"),teamId:_c,projectId:_c,selections:ak,original:d({baseline:Vv,candidate:Vv}).strict(),humanResults:d({baseline:qv,candidate:qv}).strict(),baseline:Fv,candidate:Fv}).strict(),Yp=Y$.extend({contentHash:kd}).strict();function Gm(e){throw new Ba(e,409)}function X$(e,t){const n=Yp.parse(e),{contentHash:a,...s}=n;a!==Qe(s)&&Gm("human_comparison_projection_invalid");for(const r of["baseline","candidate"]){const i=Jo(n[r]),c=i.manifest.lineage,u=c?.humanProjection,l=n.original[r],p=n.selections[r];(!c||!u||u.originalManifest.id!==l.id||u.originalManifest.contentHash!==l.manifestHash||u.selectionHash!==Qe(p)||u.rulesHash!==Qe(n.selections.rules)||Qe(c.execution)!==Qe(p.execution)||i.manifest.teamId!==n.teamId||n.humanResults[r].contentHash!==p.resultHash)&&Gm("human_comparison_projection_lineage_changed");const{contentHash:f,...y}=n.humanResults[r];(Qe(y)!==f||y.executionId!==p.execution.id||y.executionHash!==p.execution.contentHash||Qe(y.selection)!==Qe(p.reviews.map(b=>b.review)))&&Gm("human_comparison_human_result_changed")}return n}const sk=d({adapterId:E,placement:k(["local","remote","colocated","provider_native"]),runtimeVersion:o().trim().min(1).max(200),capabilityReceipt:W}).strict(),rk=d({maxTurns:m().int().positive().max(1e5),timeoutMs:m().int().positive().max(864e5),maxOutputBytes:m().int().positive().max(25e7),maximumSpendUsd:m().nonnegative().nullable()}).strict(),e2=d({schemaVersion:x("openpond.runManifest.v1"),id:E,harnessRelease:re,tasksetRelease:re,model:Zf,runtimeTarget:sk,limits:rk,approval:d({id:E,contentHash:W}).strict().nullable(),createdAt:Ce,metadata:pa}).strict();e2.extend({contentHash:W}).strict();const t2=d({schemaVersion:x("openpond.attemptReceipt.v1"),id:E,runManifest:re,taskId:E,seed:o().trim().min(1).max(500),terminal:j(),failureClass:Fd.nullable(),outputHash:W.nullable(),traceHash:W,artifactRefs:v(vs).max(1e5),graderEvidenceRefs:v(vs).max(1e4),startedAt:Ce,completedAt:Ce,latencyMs:m().int().nonnegative(),costUsd:m().nonnegative().nullable(),legacyAttemptRef:E.nullable().default(null),metadata:pa}).strict(),n2=t2.extend({contentHash:W}).strict(),a2=d({schemaVersion:x("openpond.evaluationResult.v1"),id:E,runManifest:re,harnessRelease:re,tasksetRelease:re,model:Zf,receiptRefs:v(re).min(1).max(1e6),attemptCount:m().int().positive(),rewardEligibleCount:m().int().nonnegative(),terminalCount:m().int().nonnegative(),meanScore:m().min(0).max(1).nullable(),failureCounts:Se(Fd,m().int().nonnegative()),authoredMetric:sx.optional(),metadata:pa}).strict(),s2=a2.extend({contentHash:W}).strict(),r2=d({schemaVersion:x("openpond.harnessCompatibility.v1"),id:E,baseHarnessRelease:re,candidateHarnessRelease:re,tasksetRelease:re,environmentHash:W,toolContractHash:W,policyHash:W,graderInterfaceHash:W,metadata:pa}).strict();r2.extend({contentHash:W}).strict();const ok=k(["scored","unscorable"]),Eh=k(["policy","environment","collector","verifier","provider","host","user","scheduler"]),o2=k(["completed","policy_failure","incomplete_output","task_deadline","environment_failure","collector_failure","verifier_failure","provider_failure","host_failure","infrastructure_timeout","cancelled"]),i2=d({schemaVersion:x("openpond.environmentRelease.v1"),id:E,revision:m().int().positive(),contract:px,actionSchemaRef:na.nullable(),observationSchemaRef:na.nullable(),stateSchemaRef:na.nullable(),artifactCollection:d({maxArtifacts:m().int().positive().max(1e5),maxTotalBytes:m().int().positive().max(1e10)}).strict(),adapterConformanceHashes:Se(E,W),metadata:pa}).strict(),jh=i2.extend({contentHash:W}).strict(),c2=k(["collected","missing","skipped","failed"]),Kv=k(["not_requested","passed","failed"]),l2=d({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:vs.nullable(),status:c2,parseStatus:Kv,schemaStatus:Kv,errorCode:E.nullable(),failureOwner:Eh.nullable(),evidenceRefs:v(vs).max(1e4),metadata:pa}).strict(),d2=d({schemaVersion:x("openpond.artifactManifest.v1"),id:E,attemptRef:re,entries:v(l2).max(1e5),createdAt:Ce,metadata:pa}).strict();d2.extend({contentHash:W}).strict();const u2=d({schemaVersion:x("openpond.verifierSetRelease.v1"),id:E,revision:m().int().positive(),graders:v(yx).min(1).max(1e3),isolation:d({processBoundary:k(["same_process","isolated_process","container"]),networkPolicy:x("none"),defaultTimeoutMs:m().int().positive().max(3e5)}).strict(),calibrationReceiptRefs:v(re).max(1e4),metadata:pa}).strict(),Mh=u2.extend({contentHash:W}).strict(),m2=d({verifierId:E,verifierVersion:o().trim().min(1).max(100),status:ok,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:Eh.nullable(),feedback:v(o().max(2e4)).max(1e3),visibleEvidenceRefs:v(vs).max(1e4),privilegedEvidenceRefs:v(vs).max(1e4),metadata:pa}).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"]})}),ik=d({schemaVersion:x("openpond.rewardReceipt.v1"),id:E,attemptRef:re,verifierSetRef:re,artifactManifestRef:re,status:ok,reward:m().min(0).max(1).nullable(),learningEligible:j(),passed:j(),outcomeClass:o2,failureOwner:Eh.nullable(),components:v(m2).min(1).max(1e4),visibleEvidenceRefs:v(vs).max(1e5),privilegedEvidenceRefs:v(vs).max(1e5),supersedes:re.nullable(),createdAt:Ce,metadata:pa}).strict();function ck(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"]})}ik.superRefine(ck);ik.extend({contentHash:W}).strict().superRefine(ck);const p2=pt("kind",[d({kind:x("model"),model:Zf,configurationHash:W}).strict(),d({kind:x("fixture")}).strict()]),f2=pt("kind",[d({kind:x("taskset"),environmentRelease:re,verifierSetRelease:re,policyHash:W}).strict(),d({kind:x("harness"),harnessRelease:re}).strict()]),lk=d({receiptId:E,taskId:E,seed:o().trim().min(1).max(500),fixtureId:E.nullable()}).strict(),h2=d({schemaVersion:x("openpond.tasksetRunManifest.v1"),id:E,tasksetRelease:re,packageHash:W,execution:f2,profileEvaluation:Sd.optional(),policy:p2,gradingRole:x("evaluation"),metricPolicy:Uc,population:v(lk).min(1).max(1e5),runtimeTarget:sk,limits:rk,createdAt:Ce,metadata:pa}).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."})}),dk=h2.safeExtend({contentHash:W}),g2=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."),uk=gt([vi(),o().max(262144),m().finite(),d({integer:g2}).strict(),d({blobBase64:o().max(349528).regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)}).strict()]),Wv=o().min(1).max(128).refine(e=>!e.includes("\0")),v2=d({tables:v(d({name:Wv,columns:v(d({name:Wv,type:k(["INTEGER","REAL","TEXT","BLOB"])}).strict()).min(1).max(128),rows:v(v(uk).max(128)).max(4096)}).strict()).max(64)}).strict().superRefine((e,t)=>{const n=new Set;for(const[a,s]of e.tables.entries()){const r=s.name.toLowerCase();(n.has(r)||r.startsWith("sqlite_"))&&t.addIssue({code:"custom",path:["tables",a,"name"],message:"Table names must be unique and outside SQLite's reserved namespace."}),n.add(r),new Set(s.columns.map(i=>i.name.toLowerCase())).size!==s.columns.length&&t.addIssue({code:"custom",path:["tables",a,"columns"],message:"Column names must be unique."}),s.rows.some(i=>i.length!==s.columns.length)&&t.addIssue({code:"custom",path:["tables",a,"rows"],message:"Each row must match the declared columns."})}}),Gv=d({schemaVersion:x("openpond.sqlExecution.v1"),snapshot:v2,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();pt("status",[d({status:x("completed"),columns:v(o()).max(128),rows:v(v(uk).max(128)).max(4096)}).strict(),d({status:x("rejected"),code:k(["invalid_query","multiple_statements","result_too_large","memory_limit"])}).strict()]);const El=d({scope:k(["input","initialState","state","arguments"]),path:v(o().min(1).max(256)).max(16)}).strict(),Zv={id:o().min(1).max(128),operation:k(["step","collect"]),toolName:o().min(1).max(500).optional(),timeoutMs:m().int().min(1).max(2e4)},b2=pt("kind",[d({...Zv,kind:x("sqlite.v1"),sql:El,snapshot:El,maxRows:Gv.shape.maxRows,maxResultBytes:Gv.shape.maxResultBytes}).strict(),d({...Zv,kind:x("javascript.v1"),source:El,cases:El,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."})}),y2=d({schemaVersion:x("openpond.javascriptEnvironment.v1"),id:o().trim().min(1).max(500),revision:m().int().positive(),module:na.refine(e=>e.visibility==="host_private","Environment code belongs to the execution owner."),tools:v($S).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(b2).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,s)=>{bh(a.inputSchema).valid||t.addIssue({code:"custom",path:["tools",s,"inputSchema"],message:"Environment tools require a supported JSON schema."}),a.inputSchemaHash!==Qe(a.inputSchema)&&t.addIssue({code:"custom",path:["tools",s,"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,s)=>{const r=e.tools.find(i=>i.name===a.toolName);a.operation==="step"&&!r&&t.addIssue({code:"custom",path:["executionServices",s,"toolName"],message:"Execution services must target a declared tool."}),a.timeoutMs>=Math.min(e.operationTimeoutMs,r?.timeoutMs??e.operationTimeoutMs)&&t.addIssue({code:"custom",path:["executionServices",s,"timeoutMs"],message:"Service budgets must leave time for the authored controller."})})}),S2=y2.safeExtend({contentHash:o().regex(/^[a-f0-9]{64}$/)});k(["create","reset","step","collect","destroy"]);d({state:Se(o(),Ie()),observation:Se(o(),Ie())}).strict();var x2=d({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:nk,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:Se(o(),Ie()).default({})}).strict(),_a=o().trim().min(1).max(240),zs=o().trim().min(1),cr=o().trim().min(8).max(256),mk=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."),br=k(["train","validation","test","frozen_eval"]),k2=d({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=d({schemaVersion:x("openpond.datasetSemanticSchema.v1"),fields:v(k2).min(1).max(1e4),schemaHash:cr}),I2=d({id:_a,split:br,path:mk,contentHash:cr,schemaHash:cr,sizeBytes:m().int().nonnegative(),rowCount:m().int().positive(),rowGroupCount:m().int().positive()}),Oh=d({schemaVersion:x("openpond.datasetArtifact.v1"),id:_a,tasksetId:_a,tasksetRevision:m().int().positive(),contentHash:cr,format:x("parquet"),schema:w2,shards:v(I2).min(1).max(1e5),rowCount:m().int().positive(),splitCounts:Se(br,m().int().nonnegative()),sourceReceiptRefs:v(_a).min(1).max(1e5),mappingHash:cr,qualityReportHash:cr,createdAt:zs}),_2=d({schemaVersion:x("openpond.datasetArtifactSummary.v1"),artifactId:_a,tasksetId:_a,tasksetRevision:m().int().positive(),format:x("parquet"),rowCount:m().int().positive(),splitCounts:Se(br,m().int().nonnegative()),sizeBytes:m().int().nonnegative(),contentHash:cr,available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:zs}),C2=d({schemaVersion:x("openpond.datasetCatalogItem.v1"),tasksetId:_a,tasksetRevision:m().int().positive(),artifactId:_a.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:Se(br,m().int().nonnegative()),sizeBytes:m().int().nonnegative().nullable(),available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),createdAt:zs,updatedAt:zs});d({schemaVersion:x("openpond.datasetCatalog.v1"),profileId:_a,datasets:v(C2),generatedAt:zs});d({schemaVersion:x("openpond.datasetArtifactRegistry.v1"),manifest:Oh,profileId:_a,storageRoot:o().trim().min(1).max(4e3),relativeManifestPath:mk,available:j(),unavailableReason:o().trim().min(1).max(2e3).nullable(),verifiedAt:zs.nullable(),createdAt:zs,updatedAt:zs});d({split:br.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([])});d({schemaVersion:x("openpond.datasetRowPage.v1"),tasksetId:_a,tasksetRevision:m().int().positive(),artifactHash:cr,split:br.nullable(),rows:v(Se(o(),Ie())).max(100),nextCursor:o().max(2e3).nullable(),totalRows:m().int().nonnegative(),returnedRows:m().int().nonnegative()});var R2=d({schemaVersion:x("openpond.datasetStorageSettings.v1"),datasetStorePath:o().trim().min(1).max(4e3),updatedAt:zs}),P2=d({id:_a,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()});d({schemaVersion:x("openpond.datasetStorageState.v1"),settings:R2,storageRoots:v(P2)});d({datasetStorePath:o().trim().min(1).max(4e3)});var Qo=o().trim().min(1).max(240),T2=o().trim().min(1),ii=o().trim().min(8).max(256),A2=Se(o(),Ie()).default({}),E2=o().trim().min(7).max(256),j2=k(["pending","approved","review","blocked"]),au=d({id:Qo,profileId:Qo,title:o().trim().min(1).max(500),sourceHash:ii,occurredAt:T2,licensingStatus:j2,secretScanStatus:k(["pending","passed","blocked"]),piiScanStatus:k(["pending","passed","review","blocked"]),metadata:A2}),M2=au.extend({schemaVersion:x("openpond.huggingFaceDatasetSource.v1"),kind:x("huggingface"),repositoryId:o().trim().regex(/^[^/\s]+\/[^/\s]+$/).max(500),repositoryUrl:o().url().max(2e3),revision:E2,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(ii).min(1).max(1e5)}),O2=au.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(ii).min(1).max(1e3),totalBytes:m().int().nonnegative(),parserVersion:o().trim().min(1).max(200)}),$2=au.extend({schemaVersion:x("openpond.generatedDatasetSource.v1"),kind:x("generated"),generatorId:Qo,generatorVersion:o().trim().min(1).max(200),seed:m().int(),generatorHash:ii}),N2=au.extend({schemaVersion:x("openpond.learningBatchDatasetSource.v1"),kind:x("learning_batch"),batch:d({id:Qo,revision:m().int().positive(),contentHash:ii}).strict(),taskDefinition:d({id:Qo,revision:m().int().positive(),contentHash:ii}).strict(),admittedBy:Qo}),D2=pt("kind",[M2,O2,$2,N2]),L2=d({schemaVersion:x("openpond.harnessActionBinding.v1"),actionId:_n,modelToolName:o().trim().min(1).max(64).regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/),description:o().trim().min(1).max(1e3),inputSchema:Se(o(),Ie()),actionSchemaHash:fn,agentRelease:vt,implementationHash:fn,runtimeBindingId:_n,capabilityReceiptHash:fn,sideEffect:k(["read","write"]),studentVisible:j(),timeoutMs:m().int().positive().max(36e5),episodeArgumentBindings:v(d({argument:_n,source:x("case_id")}).strict()).max(20).default([])}).strict(),kt=o().trim().min(1).max(240),$h=o().trim().min(1),z2=o().trim().min(8).max(256),Nh=o().trim().regex(/^[a-f0-9]{64}$/),H2=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),Wa=Se(o(),Ie()).default({}),su=kt.nullable();function Vc(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}function U2(e){const t=e.trim();return t.length>0&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")}var ci=br,pk=k(["general","benchmark"]),fk=d({schemaVersion:x("openpond.tasksetBenchmark.v1"),definitionId:kt,releaseId:kt,releaseHash:Nh,managedReleasePath:o().trim().min(1).max(1e3).refine(Vc,"Benchmark release paths must remain relative."),adaptationSplit:ci,evaluationSplit:ci,primaryMetric:k(["foreground_tokens","success_rate","latency_ms","cost_usd"]),qualityGate:k(["none","non_regression","all_pass"]),source:k(["builtin","imported"]),metadata:Wa}),hk=d({schemaVersion:x("openpond.tasksetPreferenceComparisonBinding.v1"),releaseId:kt,releaseHash:Nh,publishedAt:$h,metadata:Wa}),q2=d({status:k(["pending","granted","denied","revoked"]),scope:k(["metadata_only","selected_turns","full_session"]),grantedBy:su,grantedAt:$h.nullable(),purpose:x("task_authoring_and_evaluation")}),gk=d({schemaVersion:x("openpond.trainingSource.v1"),id:kt,profileId:kt,sessionId:kt,turnIds:v(kt).max(1e3).default([]),workspaceId:su,sourceHash:z2,clusterKey:kt,title:o().trim().min(1).max(500),occurredAt:$h,consent:q2,connectedAppIds:v(kt).max(100).default([]),secretScanStatus:k(["pending","passed","blocked"]),piiScanStatus:k(["pending","passed","review","blocked"]),licensingStatus:k(["pending","approved","review","blocked"]),metadata:Wa}),vk=gt([gk,D2,x2]),Dh=d({policyVisibleFields:v(kt).max(1e3).default([]),privilegedFields:v(kt).max(1e3).default([]),hiddenGraderRefs:v(kt).max(100).default([]),connectedAppScopes:v(kt).max(100).default([])}),B2=d({id:kt,sourceRefId:kt,artifactRef:o().trim().min(1).max(4e3).refine(Vc,"Task asset references must be safe relative paths."),fileName:o().trim().min(1).max(500).refine(U2,"Task asset file names must not contain path separators."),mediaType:o().trim().min(1).max(200),sha256:Nh,sizeBytes:m().int().nonnegative().max(25e7),split:ci,metadata:Wa}),F2=d({path:o().trim().min(1).max(1e3).refine(Vc,"Required output paths must stay inside the Work output directory."),mediaType:o().trim().min(1).max(200),schemaRef:kt.nullable().optional(),maxBytes:m().int().positive().max(1e7).optional(),metadata:Wa}),ru=d({schemaVersion:x("openpond.taskData.v1"),id:kt,clusterKey:kt,split:ci,input:Se(o(),Ie()),expectedOutput:Se(o(),Ie()).nullable(),policyVisibleContext:Se(o(),Ie()).default({}),privilegedContextRef:su,sourceRefs:v(kt).min(1).max(100),assets:v(B2).max(1e3).optional(),resourceRefs:v(kt).max(1e3).optional(),requiredOutputs:v(F2).max(100).optional(),tags:v(kt).max(100).default([]),metadata:Wa}),V2=d({id:kt,kind:k(["file","catalog","configuration","code_module"]),path:o().trim().min(1).max(1e3).refine(Vc,"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:Wa}),xi=d({id:kt,taskId:su,sourceRefs:v(kt).min(1).max(100),artifactRef:kt,approved:j(),confidence:m().min(0).max(1),metadata:Wa}),bk=xi.extend({kind:x("demonstration"),prompt:o().max(1e5).nullable().default(null),response:o().max(2e5).nullable().default(null)}),yk=xi.extend({kind:x("preference"),prompt:o().max(1e5),chosen:o().max(2e5),rejected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),Sk=xi.extend({kind:x("correction"),original:o().max(2e5),corrected:o().max(2e5),rationale:o().max(1e5).nullable().default(null)}),xk=xi.extend({kind:x("feedback"),feedback:o().max(1e5),polarity:k(["positive","negative","mixed","neutral"])}),kk=xi.extend({kind:x("reward"),task:o().max(1e5),rules:v(d({id:kt,points:m().finite(),condition:o().trim().min(1).max(1e5)})).min(1).max(1e3),otherwisePoints:m().finite(),executable:j()}),wk=xi.extend({kind:x("label"),labelKind:x("rubric"),task:o().max(1e5),criteria:v(d({id:kt,label:o().trim().min(1).max(500),description:o().trim().min(1).max(1e5)})).min(1).max(1e3),calibrationExamples:d({positive:o().trim().min(1).max(2e5),negative:o().trim().min(1).max(2e5),boundary:o().trim().min(1).max(2e5)})});pt("kind",[bk,yk,Sk,xk,kk,wk]);var Ik=d({demonstrations:v(bk).max(1e5).default([]),preferences:v(yk).max(1e5).default([]),corrections:v(Sk).max(1e5).default([]),feedback:v(xk).max(1e5).default([]),rewards:v(kk).max(1e5).default([]),labels:v(wk).max(1e5).default([])}),_k=d({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(kt).max(200).default([]),actionBindings:v(L2).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(V2).max(1e4).optional(),metadata:Wa}),Lh=d({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([])}),ou=d({id:kt,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:Wa}),K2=ou.extend({kind:k(["content","schema","file","diff","test","runtime_event","state"]),config:Se(o(),Ie())}),W2=ou.extend({kind:x("model_judge"),rubric:o().trim().min(1).max(5e4),judge:Th,calibrationFixtureRefs:v(kt).min(1).max(500),calibrationStatus:k(["pending","passed","failed"]),temperature:m().min(0).max(2).default(0)}),G2=ou.extend({kind:x("human"),form:qc.optional(),rubric:o().trim().min(1).max(5e4),reviewerRole:o().trim().min(1).max(500)}),Z2=ou.extend({kind:x("custom_verifier"),runtime:gx.optional(),module:o().trim().min(1).max(1e3).refine(Vc,"Custom verifier modules must use a safe relative path."),exportName:H2,timeoutMs:m().int().positive().max(3e5),networkPolicy:x("none")}),iu=gt([K2,W2,G2,Z2]),zh=k(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]),Ck=d({id:kt,taskId:kt,label:zh,output:Se(o(),Ie()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:j(),expectedRewardEligible:j(),metadata:Wa});o().regex(/^[a-f0-9]{64}$/);var J2=d({environment:jh,verifierSet:Mh,javascript:S2}).strict();d({actions:v(d({name:o().min(1).max(64),arguments:Se(o(),Ie())}).strict()).max(1e3)}).strict();var Q2=d({environment:jh,verifierSet:Mh}).strict(),Y2=d({scopeId:o().trim().min(1).max(500),modelId:o().trim().min(1).max(500)}).strict();d({schemaVersion:x("openpond.modelTasksetDerivation.v1"),owner:Y2,root:qa,parent:qa}).strict();var X2=d({taskset:xx,taskDefinition:Xd,rewardBinding:wh,rewards:v(Yd).min(1).max(100),assets:v(tu).max(1e3),executionResources:Q2.optional(),execution:J2.optional(),instructionMode:x("per_task").optional()}).strict(),eN=d({batch:Ox,evidence:v(eu).min(1).max(1e4),decisions:v(Rh).min(1).max(1e4),sources:v(Ch).min(1).max(1e4),assets:v(tu).max(1e3)}).strict(),tN=64*1024*1024,nN=d({asset:Gp,base64:o().max(Math.ceil(tN/3)*4)}).strict();d({schemaVersion:x("openpond.connectedRewardCalibrationProjection.v1"),sourceReward:vr,fixtureSet:Gp,calibrationCheck:Ye,fixture:Ux,fixtureHash:o().regex(/^[a-f0-9]{64}$/),checkResultHash:o().regex(/^[a-f0-9]{64}$/),independentCalibrationTask:x(!0),closureRef:Gp,graderId:o().min(1).max(240).optional()}).strict();var aN=X2.omit({taskset:!0,executionResources:!0}),sN=d({schemaVersion:x("openpond.tasksetPackage.v1"),taskset:xx,environment:jh,verifierSet:Mh,files:v(nN).max(1e4),modelResources:aN.optional(),learningResources:eN.optional()}).strict(),i8=sN.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict(),ps=o().trim().min(1).max(240),Cc=o().trim().min(1),wd=o().trim().min(8).max(256),Rk=Se(o(),Ie()).default({}),rN=ps.nullable(),oN=["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"],iN=k(["draft","awaiting_disclosure_approval","awaiting_materialization_approval","materializing","validating","needs_review","baselining","ready","blocked","failed","archived"]),Pk=k(["demonstrations","preferences","verifiable_reward","rubric","discovery"]),Bn=o().trim().max(1e5),Tk=pt("kind",[d({kind:x("demonstrations"),behavior:Bn,examples:v(d({id:ps,prompt:Bn,response:Bn})).max(1e3).default([])}),d({kind:x("preferences"),preference:Bn,pairs:v(d({id:ps,prompt:Bn,chosen:Bn,rejected:Bn,rationale:Bn})).max(1e3).default([])}),d({kind:x("verifiable_reward"),task:Bn,rules:v(d({id:ps,points:m().finite(),condition:Bn})).max(1e3).default([]),otherwisePoints:m().finite().default(0)}),d({kind:x("rubric"),task:Bn,criteria:v(d({id:ps,label:o().trim().max(500),description:Bn})).max(1e3).default([]),positiveExample:Bn,negativeExample:Bn,boundaryExample:Bn})]),cN=d({path:o().trim().min(1).max(1e3),role:k(["environment","verifier","fixture"]),content:o().max(25e4)}),Ak=d({primaryMethod:k(["sft","dpo","grpo","ppo","sdft","opsd","sdpo"]),bootstrap:d({method:x("sft"),purpose:x("trajectory_bootstrap"),demonstrationRefs:v(ps).min(1).max(1e5),limitations:v(o().trim().min(1).max(5e3)).min(1).max(100)}).nullable()}),Ek=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"]),lN=d({method:k(["sft","dpo","grpo","ppo"]),status:k(["recommended","compatible","needs_dataset_work"]),reasonCodes:v(Ek).default([]),reasons:v(o().trim().min(1).max(5e3)).default([])}),Jv=d({code:ps,message:o().trim().min(1).max(5e3),path:o().trim().max(2e3).nullable()}),jk=d({schemaVersion:x("openpond.tasksetReadiness.v1"),tasksetId:ps,tasksetHash:wd,ready:j(),recommendedMethod:k(["none","retrieval","sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),trainingPath:Ak.nullable().default(null),methodReadiness:v(lN).default([]),compatibleDestinationClasses:v(k(["export","custom","hosted_managed"])),blockers:v(Jv).default([]),advisories:v(Jv).default([]),warnings:v(o().trim().min(1).max(5e3)).default([]),generatedAt:Cc}),Mk=d({attempt:m().int().positive(),summary:o().trim().min(1).max(5e3),createdAt:Cc}),dN=d({schemaVersion:x("openpond.taskAuthoringProvenance.v1"),model:Th.nullable(),modelConfig:Rk,skillHash:wd,promptTemplateVersion:o().trim().min(1).max(200),buildIntent:Pk.default("demonstrations"),buildSpecification:Tk.nullable().default(null),evidenceHashes:v(wd).max(1e5),tasksetSdkVersion:o().trim().min(1).max(100),sourceCommit:o().trim().min(1).max(256).nullable(),repairHistory:v(Mk).max(1e3),createdAt:Cc}),Rc=d({schemaVersion:x("openpond.taskset.v1"),id:ps,revision:m().int().positive().default(1),profileId:ps,profileRelease:I$.nullable().optional(),createImproveRunId:rN.default(null),name:o().trim().min(1).max(500),objective:o().trim().max(2e4),purpose:pk.default("general"),benchmark:fk.nullable().default(null),preferenceComparison:hk.nullable().default(null),status:iN,sourceRefs:v(vk).min(1).max(1e5),datasetArtifact:Oh.nullable().optional(),policy:Dh,environment:_k,capabilities:Lh,metrics:Uc.optional(),tasks:v(ru).max(1e6),graders:v(iu).min(1).max(1e3),graderFixtures:v(Ck).max(1e5),learningSignals:Ik,authoringProvenance:dN,readiness:jk.nullable(),contentHash:wd,createdAt:Cc,updatedAt:Cc,metadata:Rk}).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 Ok(e){return e.schemaVersion==="openpond.trainingSource.v1"}function uN(e,t={}){const n=Rc.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,s=[];hN(a,s),pN(a,s),gN(a,s),bN(a,s),yN(a,s),mN(a,s,t),SN(a,s),xN(a.capabilities,s,a),vN(a,s);const r=$k(a);return a.contentHash!==r&&s.push({code:"content_hash_mismatch",severity:"error",message:`Taskset contentHash is ${a.contentHash}, expected ${r}.`,path:"contentHash"}),{valid:!s.some(i=>i.severity==="error"),taskset:a,computedHash:r,issues:s}}function mN(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 s=new Set(e.tasks.map(i=>i.id)),r=new Set(["positive","negative","boundary","adversarial","prompt_injection","infrastructure_failure"]);for(const i of e.graderFixtures)!e.datasetArtifact&&!s.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`}),r.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?[]:r)t.push({code:"grader_fixture_missing",severity:"warning",message:`Taskset does not include the optional ${i} grader calibration fixture.`,path:"graderFixtures"})}function pN(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((u,l)=>u+l,0),s=n.shards.reduce((u,l)=>u+l.rowCount,0);(a!==n.rowCount||s!==n.rowCount)&&t.push({code:"dataset_artifact_row_count_mismatch",severity:"error",message:"Dataset artifact row, split, and shard counts do not agree.",path:"datasetArtifact.rowCount"});const r=new Map;for(const u of n.shards)r.set(u.split,(r.get(u.split)??0)+u.rowCount);for(const[u,l]of Object.entries(n.splitCounts))(r.get(u)??0)!==l&&t.push({code:"dataset_artifact_split_count_mismatch",severity:"error",message:`Dataset artifact ${u} shard counts do not match its manifest.`,path:`datasetArtifact.splitCounts.${u}`});const{contentHash:i,...c}=n;zt(c)!==n.contentHash&&t.push({code:"dataset_artifact_hash_mismatch",severity:"error",message:"Dataset artifact manifest content hash is invalid.",path:"datasetArtifact.contentHash"})}function fN(e){return $k(e)}function $k(e){const{contentHash:t,status:n,readiness:a,updatedAt:s,...r}=e;return zt(r)}function hN(e,t){for(const[n,a]of e.sourceRefs.entries())Ok(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 gN(e,t){const n=new Map;for(const s of e.tasks){const r=n.get(s.clusterKey)??new Set;r.add(s.split),n.set(s.clusterKey,r)}for(const[s,r]of n)r.size>1&&t.push({code:"split_cluster_contamination",severity:"error",message:`Source cluster ${s} appears in multiple splits: ${[...r].join(", ")}.`,path:"tasks"});(e.datasetArtifact?e.datasetArtifact.splitCounts.frozen_eval??0:e.tasks.filter(s=>s.split==="frozen_eval").length)===0&&t.push({code:"frozen_eval_missing",severity:"warning",message:"Add an independent test example before training.",path:"tasks"})}function vN(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(oN),a=e.environment.toolNames.filter(r=>!n.has(r));a.length&&t.push({code:"work_tool_unknown",severity:"error",message:`Work Taskset declares unknown tools: ${a.join(", ")}.`,path:"environment.toolNames"}),e.environment.toolNames.includes("work_save_output")||t.push({code:"work_output_tool_missing",severity:"error",message:"Work Tasksets must declare work_save_output.",path:"environment.toolNames"});for(const r of["create","reset","step","grade","cleanup"])e.environment.lifecycle.includes(r)||t.push({code:"work_lifecycle_incomplete",severity:"error",message:`Work Tasksets require the ${r} lifecycle stage.`,path:"environment.lifecycle"});const s=new Map(e.sourceRefs.map(r=>[r.id,r]));for(const[r,i]of e.tasks.entries()){const c=new Set,u=new Set;for(const[p,f]of(i.assets??[]).entries()){const y=`tasks.${r}.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:`${y}.id`}),u.has(f.fileName)&&t.push({code:"work_asset_duplicate_name",severity:"error",message:`Task ${i.id} repeats staged file name ${f.fileName}.`,path:`${y}.fileName`}),c.add(f.id),u.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:`${y}.sourceRefId`});const b=s.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:`${y}.sha256`}):t.push({code:"work_asset_source_missing",severity:"error",message:`Asset ${f.id} references missing source ${f.sourceRefId}.`,path:`${y}.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:`${y}.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:`${y}.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:`${y}.split`})}const l=new Set;for(const[p,f]of(i.requiredOutputs??[]).entries()){const y=f.path.replaceAll("\\","/"),b=`tasks.${r}.requiredOutputs.${p}.path`;l.has(y)&&t.push({code:"work_output_duplicate_path",severity:"error",message:`Task ${i.id} repeats required output path ${y}.`,path:b}),l.add(y)}(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.${r}.requiredOutputs`})}}function bN(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 yN(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 SN(e,t){const n=new Set(e.tasks.map(s=>s.id)),a=new Set(e.sourceRefs.map(s=>s.id));for(const s of[...e.learningSignals.demonstrations,...e.learningSignals.preferences,...e.learningSignals.corrections,...e.learningSignals.feedback,...e.learningSignals.rewards,...e.learningSignals.labels])s.taskId&&!e.datasetArtifact&&!n.has(s.taskId)&&t.push({code:"learning_signal_task_missing",severity:"error",message:`Signal ${s.id} references missing task ${s.taskId}.`,path:`learningSignals.${s.kind}.${s.id}.taskId`}),s.sourceRefs.some(r=>!a.has(r))&&t.push({code:"learning_signal_source_missing",severity:"error",message:`Signal ${s.id} references a source outside the Dataset.`,path:`learningSignals.${s.kind}.${s.id}.sourceRefs`});for(const s of e.learningSignals.preferences)s.chosen.trim()===s.rejected.trim()&&t.push({code:"preference_pair_identical",severity:"error",message:`Preference ${s.id} has identical chosen and rejected responses.`,path:`learningSignals.preferences.${s.id}`});for(const s of e.learningSignals.rewards)s.executable||t.push({code:"reward_not_executable",severity:"warning",message:`Reward ${s.id} is a reviewed specification but has no executable verifier yet.`,path:`learningSignals.rewards.${s.id}.executable`})}function xN(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 Ho=o().trim().min(1).max(240),Qv=o().trim().min(1),kN=o().trim().min(8).max(256),wN=o().trim().regex(/^[A-Za-z_$][A-Za-z0-9_$]*$/),IN=Se(o(),Ie()).default({});function Yv(e){const t=e.trim().replaceAll("\\","/");return!t||t.startsWith("/")||t==="."||t===".."?!1:!t.split("/").some(n=>!n||n==="."||n==="..")}var Nk=ru.extend({sourceRefs:v(Ho).max(100).default([])}),Dk=k(["draft","validating","needs_review","published"]),_N=d({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(d({id:Ho,label:o().trim().min(1).max(500),description:o().trim().max(1e4),weight:m().nonnegative().max(1e3)})).max(100)}),CN=d({mode:k(["text","structured_json","artifacts"]),jsonSchema:Se(o(),Ie()).nullable(),renderer:d({module:o().trim().min(1).max(1e3).refine(Yv,"Renderer modules must use a safe relative path."),exportName:wN,configRef:o().trim().min(1).max(1e3).refine(Yv,"Renderer configuration must use a safe relative path.").nullable().default(null)}).nullable()}).superRefine((e,t)=>{e.mode==="structured_json"&&!e.jsonSchema&&t.addIssue({code:"custom",message:"Structured JSON output requires a JSON Schema.",path:["jsonSchema"]}),e.mode==="text"&&e.renderer&&t.addIssue({code:"custom",message:"Text output cannot configure an artifact renderer.",path:["renderer"]})}),Fa=d({schemaVersion:x("openpond.tasksetDraft.v1"),id:Ho,revision:m().int().positive(),profileId:Ho,modelScope:d({modelId:Ho,expectedModelRevision:m().int().positive(),source:v$.optional()}).strict().nullable().default(null),name:o().trim().max(500),objective:o().trim().max(2e4),purpose:pk.default("general"),benchmark:fk.nullable().default(null),preferenceComparison:hk.nullable().default(null),status:Dk,sourceRefs:v(vk).max(1e5).default([]),datasetArtifact:Oh.nullable().optional(),policy:Dh,environment:_k,output:CN.default({mode:"text",jsonSchema:null,renderer:null}),capabilities:Lh,metrics:Uc,review:_N,tasks:v(Nk).max(1e6).default([]),graders:v(iu).max(1e3).default([]),graderFixtures:v(Ck).max(1e5).default([]),learningSignals:Ik,publishedTasksetRef:d({id:Ho,revision:m().int().positive(),contentHash:kN}).nullable(),createdAt:Qv,updatedAt:Qv,metadata:IN}).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"]})}),RN=6e6,PN=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 TN(e){const t=nu.parse(e);return!PN.has(t)&&!t.startsWith("source-artifacts/")}function Xv(e,t){const n=TN(e);if(t.byteLength>RN)throw new Error("Taskset draft file content is invalid or exceeds 6 MB.");let a;try{const s=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t);a=/[\u0000-\u0008\u000e-\u001f]/.test(s)?eb(t):{encoding:"utf8",data:s}}catch{a=eb(t)}return{path:e,writable:n,content:a,sizeBytes:t.byteLength,contentHash:Zx(t)}}function eb(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 tb=64*1024*1024,Lk=o().regex(/^[a-f0-9]{64}$/),AN=d({path:nu,contentHash:Lk,sizeBytes:m().int().nonnegative().max(tb),base64:o().max(tb)}).strict(),EN=d({schemaVersion:x("openpond.tasksetDraftWorkspace.v1"),draft:Fa,files:v(AN).max(1e4)}).strict(),c8=EN.extend({contentHash:Lk}).strict(),nb=class extends Error{issues;constructor(e){super(e.map(t=>t.message).join(`
|
|
109
|
+
`)),this.name="TasksetDraftPublishError",this.issues=e}};function jN(e){const t=[];e.name.trim()||t.push({code:"name_missing",message:"Name is required.",path:"name"}),e.objective.trim()||t.push({code:"objective_missing",message:"Objective is required.",path:"objective"}),!e.datasetArtifact&&e.tasks.length===0&&t.push({code:"tasks_missing",message:"Add at least one task or Dataset artifact.",path:"tasks"}),e.graders.length===0&&t.push({code:"graders_missing",message:"Add at least one grader.",path:"graders"}),!(e.graders.length>0&&e.graders.every(s=>s.kind==="human"))&&e.graderFixtures.length===0&&t.push({code:"grader_fixtures_missing",message:"Add grader fixtures before publishing.",path:"graderFixtures"});const a=new Set(e.sourceRefs.map(s=>s.id));for(const s of e.tasks)for(const r of s.sourceRefs)a.has(r)||t.push({code:"task_source_missing",message:`Task ${s.id} references missing source ${r}.`,path:`tasks.${s.id}.sourceRefs`});return t}function l8(e){const t=Fa.parse(e.draft),n=e.now??new Date().toISOString(),a=jN(t);if(a.length)throw new nb(a);const s=t.modelScope?.source;if(s&&e.tasksetId&&e.tasksetId!==s.tasksetId)throw new Error("Taskset draft publication differs from its prepared identity.");const r=s?.tasksetId||e.tasksetId?.trim()||t.publishedTasksetRef?.id||t.id.replace(/-draft$/,""),i=s?.tasksetRevision??(t.publishedTasksetRef?.id===r?t.publishedTasksetRef.revision+1:1),c=t.sourceRefs.length?t.sourceRefs:[MN(t,r,n)],u=c[0].id,l=t.tasks.map(A=>ru.parse({...A,sourceRefs:A.sourceRefs.length?A.sourceRefs:[u],metadata:{exampleOrigin:"expert_authored",...A.metadata}})),p=t.capabilities.compatibleMethods.find(A=>A!=="none"&&A!=="retrieval")??null,f=ON(t),y=t.graders.filter(A=>A.rewardEligible&&A.weight>0&&A.kind!=="human"),b=p===null&&f==="verifiable_reward"&&y.length>0,I=p??(b?"grpo":null),C=Rc.parse({schemaVersion:"openpond.taskset.v1",id:r,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(y.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:zt("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,...s?{modelTasksetAuthoring:s.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=Rc.parse({...C,contentHash:fN(C)}),M=uN(P).issues.filter(A=>A.severity==="error");if(M.length)throw new nb(M.map(A=>({code:A.code,message:A.message,path:A.path})));return P}function MN(e,t,n){const a=zt({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 ON(e){return e.learningSignals.preferences.length?"preferences":e.learningSignals.rewards.length?"verifiable_reward":e.learningSignals.labels.length?"rubric":!e.capabilities.compatibleMethods.some(t=>t!=="none"&&t!=="retrieval")&&e.graders.some(t=>t.rewardEligible&&t.weight>0&&t.kind!=="human")?"verifiable_reward":"demonstrations"}var Yo=o().regex(/^[a-f0-9]{64}$/),zk=d({providerId:x("claude-code"),configurationHash:Yo,executableHash:Yo,version:o().regex(/^2\.\d+\.\d+$/),capabilityHash:Yo,maximumRequestCostUsd:m().finite().positive().max(1e4),requestTimeoutMs:m().int().min(1e3).max(3e5),maximumTurns:m().int().min(1).max(100),holdOpen:j()}).strict();d({id:o().min(1).max(200),receiptId:o().min(1).max(200),sessionId:X0(),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 d8=d({provider:x("claude-code"),sessionId:X0(),requestId:o().min(1).max(200),modelId:o().min(1).max(500),runtime:zk,sourceHash:Yo,outputHash:Yo,traceHash:Yo,runtimeEventRefs:v(o().min(1).max(200)).min(1).max(2e4),eventCount:m().int().positive().max(2e4),startedAt:ta(),completedAt:ta(),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."})}),cu=d({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(),$N=v(d({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."})}),NN=d({schemaVersion:x("openpond.experimentAttemptGrade.v1"),selectionHash:o().regex(/^[a-f0-9]{64}$/),grades:v(wx).min(1).max(100),score:m().min(0).max(1).nullable(),passed:j(),rewardEligible:j(),gradingStatus:k(["scored","pending","unscorable","not_configured"]),failureClass:_$.nullable(),contentHash:o().regex(/^[a-f0-9]{64}$/)}).strict().superRefine((e,t)=>{const{contentHash:n,...a}=e;zt(a)!==n&&t.addIssue({code:"custom",message:"Experiment grading integrity failed."});const s=e.grades.flatMap(r=>r.components);(s.length!==e.grades.length||new Set(s.map(r=>r.graderId)).size!==s.length)&&t.addIssue({code:"custom",message:"Each selected criterion requires exactly one distinct grader result."});for(const r of e.grades){const{contentHash:i,...c}=r;zt(c)!==i&&t.addIssue({code:"custom",message:"A retained criterion changed."});for(const u of r.components){const{contentHash:l,...p}=u;zt(p)!==l&&t.addIssue({code:"custom",message:"A retained grader result changed."})}}}),Jt=o().trim().min(1).max(200),Hr=o().regex(/^[a-f0-9]{64}$/),Hk=pt("kind",[d({kind:x("hosted_chat"),modelId:Jt,localRuntime:gt([d({providerId:x("custom-openai-compatible"),configurationHash:Hr,maximumRequestCostUsd:m().finite().positive().max(1e4),requestTimeoutMs:m().int().min(1e3).max(3e5)}).strict(),zk]).optional(),candidate:d({artifactId:Jt,contentHash:Hr,preparationId:Jt,dispatchId:Jt,baseProfileId:Jt,workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),harness:Ih.optional(),messages:$N.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(),d({kind:x("fixture"),fixtureId:Jt}).strict()]),DN=d({schemaVersion:x("openpond.modelStarterAttemptRequest.v1"),operationId:Jt,teamId:Jt,modelProjectId:Jt.nullable(),project:cu.optional(),taskset:qa,taskId:Jt,environmentSeed:m().int().min(0).max(2147483647).default(0),policy:Hk}).strict();d({modelProjectId:Jt.nullable(),taskset:qa,afterTaskId:Jt.optional(),limit:m().int().min(1).max(100).default(25)}).strict();d({modelProjectId:Jt.nullable(),taskset:qa,available:j(),unavailableReason:o().max(1e3).nullable(),models:v(d({id:Jt,name:o().max(500),maximumOutputTokens:m().int().min(1).max(1e6).optional()}).strict()).max(200),tasks:v(d({id:Jt,split:Ka,inputPreview:o().max(500),fixtures:v(d({id:Jt,label:o().max(200)}).strict()).max(1e3)}).strict()).max(100),nextCursor:Jt.nullable()}).strict();var Hh=d({schemaVersion:x("openpond.modelStarterAttemptSummary.v1"),id:Jt,revision:m().int().positive(),request:DN,status:k(["queued","running","cancelling","completed","failed","cancelled"]),policySnapshot:d({modelId:Jt,provider:Jt,upstreamModelId:o().min(1).max(500),configurationHash:Hr}).strict().nullable(),createdAt:ta(),startedAt:ta().nullable(),completedAt:ta().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:d({code:Jt,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."})});d({modelProjectId:Jt,afterId:Jt.optional(),limit:m().int().min(1).max(100).default(25)}).strict();d({items:v(Hh).max(100),nextCursor:Jt.nullable()}).strict();d({schemaVersion:x("openpond.modelStarterAttemptResult.v1"),attempt:Hh,output:o().max(1048576).nullable(),messages:v(Se(o(),Ie())).max(4002),composition:kc.nullable(),grade:wx.nullable().optional(),experimentGrade:NN.nullable().optional(),environment:d({status:k(["completed","budget_exhausted","cancelled","timed_out","policy_failure","environment_failure"]),collected:j(),definition:qa,initialStateHash:Hr.nullable(),finalStateHash:Hr.nullable(),attemptHash:Hr}).strict(),native:Cx.optional(),providerRequestIds:v(Jt).max(1001),contentHash:Hr}).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||zt(n)!==zt(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!==zt(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 To=o().trim().min(1).max(240),Zm=o().regex(/^[a-f0-9]{64}$/),Uk=d({kind:x("hosted_harness"),modelId:To,candidate:d({artifactId:To,contentHash:Zm,preparationId:To,dispatchId:To,baseProfileId:To,workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/)}).strict().optional(),sourceCandidate:Sd.shape.sourceCandidate,reasoningEffort:k(["off","low","medium","high","xhigh","max"]).optional(),profileRepositoryId:To,source:Sd,modelConfigurationHash:Zm,packageHash:Zm,externalDatasetBinding:ur.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."})}),Ua=o().trim().min(1).max(200),qk=o().regex(/^[a-f0-9]{64}$/),LN=pt("kind",[Hk.options[0],d({kind:x("fixture")}).strict(),Uk]),lu=d({schemaVersion:x("openpond.modelTasksetRunRequest.v1"),operationId:Ua,teamId:Ua,modelProjectId:Ua.nullable(),name:o().trim().min(1).max(200).optional(),project:cu.optional(),taskset:qa,policy:LN,population:v(lk).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=>Ah([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."})}),Bk=d({schemaVersion:x("openpond.modelTasksetRunSummary.v1"),id:Ua,revision:m().int().positive(),teamId:Ua,modelProjectId:Ua.nullable(),name:o().trim().min(1).max(200).optional(),project:cu.optional(),operationId:Ua,taskset:qa,policyKind:k(["hosted_chat","fixture","hosted_harness"]),manifestHash:qk,status:k(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:m().int().min(1).max(1e4),counts:d({pending:m().int().nonnegative(),running:m().int().nonnegative(),completed:m().int().nonnegative(),failed:m().int().nonnegative(),cancelled:m().int().nonnegative()}).strict(),createdAt:ta(),startedAt:ta().nullable(),completedAt:ta().nullable(),cleanupComplete:j(),resultAvailable:j(),score:m().min(0).max(1).nullable(),metricName:o().min(1).max(240),error:d({code:Ua,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."})}),zN=d({summary:Bk,request:lu,manifest:dk,policySnapshot:Hh.shape.policySnapshot}).strict();d({modelProjectId:Ua.optional(),projectId:cu.shape.id.optional(),afterId:Ua.optional(),limit:m().int().min(1).max(100).default(25)}).strict();d({items:v(Bk).max(100),nextCursor:Ua.nullable()}).strict();d({schemaVersion:x("openpond.modelTasksetRunResult.v1"),run:zN,receipts:v(n2).min(1).max(1e4),metric:sx.nullable(),contentHash:qk}).strict();var Fk=o().min(1).max(200).refine(e=>!["__proto__","prototype","constructor"].includes(e),"Use an ordinary field name."),HN=v(Fk).min(1).max(20),ab=k(["input","output","expectedOutput","evaluatorContext"]),UN=d({destination:ab,path:HN,source:ab,sourcePath:v(Fk).max(20)}).strict(),Uh=v(UN).max(100).superRefine((e,t)=>{for(const[n,a]of e.entries())e.slice(0,n).some(s=>s.destination===a.destination&&(sb(s.path,a.path)||sb(a.path,s.path)))&&t.addIssue({code:"custom",path:[n,"path"],message:"Mapped destination paths must not overlap."})});function sb(e,t){return e.length<=t.length&&e.every((n,a)=>n===t[a])}var Kn=o().trim().min(1).max(200),Wr=o().regex(/^[a-f0-9]{64}$/),qh=d({id:Kn,revision:m().int().positive(),contentHash:Wr}).strict(),du=d({id:Kn,version:o().min(1).max(200),contentHash:Wr,name:o().trim().min(1).max(500).optional(),feedbackKey:Bc,release:qh.nullable(),mappings:Uh.optional()}).strict(),qN=d({id:Kn,version:o().min(1).max(200),contentHash:Wr,mappings:Uh}).strict(),u8=d({operationId:Kn,id:Kn.optional(),expectedRevision:m().int().nonnegative(),request:lu,maximumCostUsd:m().finite().positive().max(1e4),graders:v(qN).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."})}),BN=d({schemaVersion:x("openpond.experimentDefinition.v1"),id:Kn,teamId:Kn,revision:m().int().positive(),request:lu,maximumCostUsd:m().finite().positive().max(1e4),graders:v(du).min(1).max(100),createdAt:ta(),updatedAt:ta()}).strict();BN.extend({contentHash:Wr});d({operationId:Kn,definition:qh}).strict();d({projectId:Kn.optional(),datasetHash:Wr.optional(),search:o().trim().max(200).optional(),status:k(["queued","running","cancelling","completed","failed","cancelled"]).optional(),afterId:Kn.optional(),limit:m().int().min(1).max(100).default(30)}).strict();d({definition:qh.nullable(),configurationHash:Wr.optional(),admissionRequestHash:Wr.optional(),sourceExperimentId:Kn.optional(),maximumCostUsd:m().finite().positive().max(1e4),graders:v(du).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."})});d({operationId:Kn,profileRepositoryId:Kn,definitionId:Kn,modelId:Kn,reasoningEffort:k(["off","low","medium","high","xhigh","max"]).optional(),maximumCostUsd:m().finite().positive().max(1e4),externalDatasetBinding:ur.optional(),sourceCandidate:Uk.shape.sourceCandidate}).strict();d({request:lu,manifest:dk,maximumCostUsd:m().finite().positive().max(1e4),graders:v(du).min(1).max(100)}).strict();var bs=Fa.shape.id,Va=m().int().positive(),Gr=o().regex(/^[a-f0-9]{64}$/),Yr={teamId:bs,modelId:bs};d({schemaVersion:x("openpond.tasksetDraftCreate.v1"),operationId:bs,modelId:bs,expectedModelRevision:Va,name:Fa.shape.name}).strict();d({schemaVersion:x("openpond.tasksetDraftSourceDescriptor.v1"),...Yr,expectedModelRevision:Va,sourcePackageHash:Gr}).strict();d({schemaVersion:x("openpond.tasksetDraftReadback.v1"),...Yr,draft:Fa,workspaceHash:Gr,projectEtag:Gr}).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 FN=d({id:bs,revision:Va,name:Fa.shape.name,status:Dk,updatedAt:Fa.shape.updatedAt,sourceTasksetRef:Ye.nullable()}).strict();d({schemaVersion:x("openpond.tasksetDraftList.v1"),...Yr,drafts:v(FN).max(100),nextCursor:o().min(1).max(2e3).nullable()}).strict();d({expectedDraftRevision:Va,draft:Fa}).strict();d({expectedDraftRevision:Va,expectedModelRevision:Va}).strict();var VN=d({expectedDraftRevision:Va,expectedWorkspaceHash:Gr}).strict();d({schemaVersion:x("openpond.tasksetDraftValidation.v1"),...Yr,draftId:bs,draftRevision:Va,workspaceHash:Gr,valid:j(),issues:v(d({code:o().min(1),severity:k(["warning","error"]),message:o(),path:o().nullable()}).strict()),packageHash:Gr.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.");VN.extend({operationId:bs,expectedPackageHash:Gr,expectedTasksetRef:Ye}).strict();d({schemaVersion:x("openpond.tasksetDraftFileList.v1"),...Yr,draftId:bs,draftRevision:Va,files:v(Vx).max(10020)}).strict();d({schemaVersion:x("openpond.tasksetDraftFileReadback.v1"),...Yr,draftId:bs,draftRevision:Va,file:b$}).strict();d({schemaVersion:x("openpond.tasksetDraftDeletion.v1"),...Yr,draftId:bs,revision:Va,deleted:x(!0)}).strict();Fa.shape.id;m().int().positive();var Ls=o().trim().min(1).max(500),KN=d({projectId:Ls.optional(),tasksetId:Ls.optional(),draftId:Ls.optional(),taskId:Ls.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(),WN=d({id:Ls,method:k(["code","judge","human"]),required:j()}),Vk=d({tasksetId:Ls,tasksetName:o(),tasksetRevision:m().int().positive(),tasksetHash:o(),taskId:Ls,ordinal:m().int().nonnegative(),title:o(),description:o(),split:o(),scoring:v(WN),configuration:k(["configured","needs_reward","needs_checks"]),draftId:Ls.nullable().default(null),modelId:Ls.nullable().default(null)}),GN=d({items:v(Vk).max(100),nextCursor:o().nullable()});function m8(e,t){if(f$({format:e.format,files:t}).contentHash!==e.contentHash)throw new Error("The source files differ from the import preview.");const n=`private/intake/${e.contentHash}`,a=t.map((r,i)=>({file:r,path:`${n}/${String(i).padStart(4,"0")}.txt`})),s={schemaVersion:"openpond.taskIntakeSources.v1",format:e.format,previewHash:e.contentHash,files:a.map(({file:r,path:i})=>({originalPath:r.path,retainedPath:i}))};return[...a.map(({file:r,path:i})=>Xv(i,new TextEncoder().encode(r.text))),Xv(`${n}/manifest.json`,new TextEncoder().encode(JSON.stringify(s)))]}function p8(e,t,n){const a=zx.parse(t);if(!n.length||new Set(n).size!==n.length)throw new Error("Select unique task records to import.");const s=[...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 u=Nk.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=s.find(p=>p.id===u.id);if(l&&zt(l)!==zt(u))throw new Error(`Task ${u.id} already exists with different content. Import will not replace saved edits.`);l||s.push(u)}const r=new Map;for(const i of s)for(const c of[`family:${i.clusterKey}`,`input:${zt(i.input)}`]){if(r.has(c)&&r.get(c)!==i.split)throw new Error("The imported task family or request already occurs in another split.");r.set(c,i.split)}return Fa.parse({...e,tasks:s})}const ea=o().trim().min(1).max(240),sr=o().trim().min(1),Kk=Se(o(),Ie()).default({}),Wk=k(["nominated","needs_review","approved_for_creation","creating","needs_task_review","baselining","ready_for_export","rejected","dismissed","retired","blocked"]),Gk=k(["no_training","prompting","retrieval","sft","preference","grpo_rft","sdft_opsd","sdpo","agentic_rl"]),ZN=d({id:ea,kind:k(["repeated_success","accepted_correction","agent_action_recurrence","outcome_linked_change","frontier_cost","expert_label","runtime_feedback"]),sourceRefIds:v(ea).min(1).max(1e4),occurredAt:sr,signature:o().trim().min(1).max(2e3),summary:o().trim().min(1).max(5e3),confidence:m().min(0).max(1),consented:j(),metadata:Kk}),JN=d({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)}),QN=d({tactic:Gk,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"])}),Zk=d({schemaVersion:x("openpond.taskCandidate.v1"),id:ea,profileId:ea,status:Wk,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(ZN).min(1).max(1e5),scorecard:JN,recommendation:QN,mergedIntoId:ea.nullable(),createdAt:sr,updatedAt:sr,metadata:Kk}),uu=d({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)});d({items:v(Zk),generatedAt:sr,config:uu});d({status:Wk.optional(),mergeIntoId:ea.nullable().optional()});d({profileId:ea,sourceIds:v(ea).max(1e5).default([]),sessionIds:v(ea).max(1e5).default([]),config:uu.optional()});const YN=d({schemaVersion:x("openpond.taskMinerRun.v1"),id:ea,profileId:ea,status:k(["queued","running","cancelling","cancelled","succeeded","failed"]),config:uu,sourceIds:v(ea).max(1e5),sessionIds:v(ea).max(1e5).default([]),progress:d({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(ea).max(1e5),cancelRequested:j(),error:o().trim().min(1).max(2e4).nullable(),createdAt:sr,startedAt:sr.nullable(),completedAt:sr.nullable(),updatedAt:sr});var XN=d({id:_n,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(),eD=d({declarationId:_n,leaseRef:o().trim().min(8).max(1e3),audience:XN.shape.audience,expiresAt:Wp}).strict(),tD=d({adapterId:_n,placement:k(["local","remote","colocated","provider_native"]),capabilityReceipt:fn,runtimeVersion:o().trim().min(1).max(200),dataPlane:d({provider:_n,dataPlaneId:_n,cellId:_n,runnerPoolId:_n,runtimeImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/),capabilityReceipt:fn}).strict().nullable()}).strict(),nD=d({adapterId:_n,kind:k(["local","ssh","managed","custom"]),deviceOrPool:o().trim().min(1).max(1e3),capabilityReceipt:fn,provider:_n.nullable()}).strict(),aD=d({adapterId:_n,workerVersion:o().trim().min(1).max(200),workerImageDigest:o().regex(/^sha256:[a-f0-9]{64}$/).nullable(),upstreamRevision:o().trim().min(1).max(500),capabilityReceipt:fn}).strict(),sD=d({schemaVersion:x("openpond.harnessRunManifest.v1"),id:_n,harnessRelease:vt,datasetRelease:vt,evidenceSets:v(vt).max(1e4),model:d({source:o().trim().min(1).max(200),revision:o().trim().min(1).max(500),artifactHash:fn.nullable(),tokenizerRevision:o().trim().min(1).max(500),chatTemplateHash:fn}).strict(),recipe:d({method:o().trim().min(1).max(100),version:o().trim().min(1).max(200),configHash:fn}).strict(),runtimeTarget:tD,computeTarget:nD,engine:aD,resolvedBundleHash:fn,secretLeaseRefs:v(eD).max(1e3),approval:d({approvalHash:fn,approvedAt:Wp,maximumSpendUsd:m().nonnegative().nullable()}).strict(),createdAt:Wp}).strict();sD.extend({contentHash:fn}).strict();var rD=d({schemaVersion:x("openpond.resolvedTrainingBundle.v1"),projection:x("trainer"),harnessRelease:vt,datasetRelease:vt,evidenceSetRelease:vt.nullable(),files:v(d({path:o().trim().min(1).max(2e3),sha256:fn,sizeBytes:m().int().nonnegative()}).strict()).max(1e5)}).strict();rD.extend({contentHash:fn}).strict();var Jk=d({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),aa=o().trim().min(1),li=o().trim().min(8).max(256),Bh=Se(o(),Ie()).default({}),fs=nt.nullable(),oD=k(["slash_train","session_menu","bulk_selection","training_page","task_candidate"]),iD=k(["defaults","customize"]),cD=k(["automated","manual"]);d({schemaVersion:x("openpond.trainingSourceEstimate.v1"),sessionId:nt,messageCount:m().int().nonnegative(),estimatedTokens:m().int().nonnegative(),textBytes:m().int().nonnegative()});d({query:o().max(500).default(""),offset:m().int().nonnegative().default(0),limit:m().int().min(1).max(100).default(20),candidates:v(d({sessionId:nt,title:o().trim().min(1).max(500),updatedAt:aa})).max(500).default([])});const lD=d({sessionId:nt,title:o().trim().min(1).max(500),updatedAt:aa,snippet:o().max(2e3).nullable()});d({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(lD)});const Fh=k(["policy_failure","grader_failure","environment_failure","infrastructure_failure","timeout","cancelled"]),dD=d({graderId:nt.nullable(),path:o().trim().min(1).max(1e3),language:k(["javascript","typescript","python","json","text"]),content:o().max(2e6),sha256:li,declaredSha256:li.nullable(),integrity:k(["verified","unverified","mismatch"])}),uD=d({protocolVersion:o().trim().min(1).max(200),module:o().trim().min(1).max(1e3),moduleSha256:li,command:v(o().max(2e3)).max(100),cwd:o().trim().min(1).max(4e3),maxTurns:m().int().positive().max(100)});d({schemaVersion:x("openpond.tasksetGraderDetails.v1"),taskset:Vt,sourceTasksetId:nt,graders:v(iu).max(1e3),runtime:uD.nullable(),sources:v(dD).max(1e3),unavailableReason:o().max(2e3).nullable()});const mD=d({id:nt,taskIndex:m().int().nonnegative(),label:zh,output:Se(o(),Ie()),infrastructureError:o().trim().min(1).max(1e4).nullable(),expectedPassed:j(),expectedRewardEligible:j(),metadata:Bh}),pD=d({schemaVersion:x("openpond.taskAttempt.v1"),id:nt,tasksetId:nt,taskId:nt,split:ci,attempt:m().int().nonnegative(),seed:m().int(),modelRef:cn.nullable(),startedAt:aa,completedAt:aa,output:Se(o(),Ie()),runtimeEventRefs:v(nt).max(1e4).default([]),artifactRefs:v(nt).max(1e4).default([]),privilegedOutcomeRef:fs,infrastructureError:o().trim().min(1).max(1e4).nullable(),costUsd:m().nonnegative().nullable(),latencyMs:m().int().nonnegative(),userInterventions:m().int().nonnegative().default(0),metadata:Bh}),fD=d({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:li,sizeBytes:m().int().nonnegative(),createdAt:aa,metadata:Bh}),hD=d({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:cn.nullable().optional().default(null),calibrationStatus:k(["not_applicable","pending","passed","failed"])}),gD=d({schemaVersion:x("openpond.gradeResult.v1"),id:nt,attemptId:nt,graderSetHash:li,score:m().min(0).max(1).nullable(),passed:j(),components:v(hD).min(1).max(1e3),failureClass:Fh.nullable(),feedback:v(o().trim().min(1).max(2e4)).max(1e3).default([]),rewardEligible:j(),rewardComposition:kc.optional(),createdAt:aa});k(["stable_hash_top_n","rft_easy_curriculum_v1"]);const vD=d({schemaVersion:x("openpond.graderAuditReport.v1"),id:nt,tasksetId:nt,tasksetHash:li,fixtureRefs:v(nt).min(1).max(1e5),gradeRefs:v(nt).min(1).max(1e5),passed:j(),hackingChecksPassed:j(),leakageChecksPassed:j(),infrastructureSafetyPassed:j(),failures:v(d({fixtureId:nt,label:zh,gradeId:nt,reason:o().trim().min(1).max(5e3)})).max(1e5),createdAt:aa}),bD=d({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:Gk,trainingEligible:j(),rationale:v(o().trim().min(1).max(5e3)).min(1).max(100),confidence:m().min(0).max(1)}),yD=d({id:nt,sourceId:nt,sourceTurnId:fs,split:ci,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)}),SD=d({schemaVersion:x("openpond.taskDesignProposal.v1"),id:nt,name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),diagnosis:bD.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:Lh.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(iu).max(1e3).default([]),graderFixtures:v(mD).max(1e5).default([]),generatedFiles:v(cN).max(1e3).default([]),proposedExamples:v(yD).max(1e5).default([]),proposedMethod:jk.shape.recommendedMethod,trainingPath:Ak.nullable().default(null),policy:Dh,warnings:v(o().trim().min(1).max(5e3)).default([]),createdAt:aa}),xD=5;function f8(e,t="New model"){const n=e?.trim().split(/\s+/).filter(Boolean)??[];return n.length===0?t:n.slice(0,xD).join(" ")}const Kc=d({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:fs,source:k(["managed","local","builtin"])}),kD=d({schemaVersion:x("openpond.taskCreationRequest.v1"),id:nt,profileId:nt,surface:oD,mode:iD,entryMode:cD.default("manual"),resourceIntent:k(["workproduct","dataset"]).default("workproduct"),buildIntent:Pk.default("demonstrations"),buildSpecification:Tk.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:Kc.nullable().default(null),sourceIds:v(nt).max(1e5),candidateId:fs,analysisModel:cn.nullable(),analysisReasoningEffort:Gd.nullable().default(null),createImproveRunId:fs.default(null),targetIntent:d({kind:k(["agent","skill","extension","model","configuration"]).nullable(),id:fs,displayName:o().trim().min(1).max(500).nullable(),operation:k(["create","improve"])}).default({kind:"model",id:null,displayName:null,operation:"create"}),disclosure:d({status:k(["not_required","pending","approved","declined"]),content:x("raw_excerpts"),sourceIds:v(nt).max(1e5),providerModel:cn.nullable(),approvalId:fs,approvedAt:aa.nullable()}).default({status:"not_required",content:"raw_excerpts",sourceIds:[],providerModel:null,approvalId:null,approvedAt:null}),createdAt:aa}),Qk=d({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:SD.nullable(),materializedTasksetId:fs,disclosureApprovalId:fs,materializationApprovalId:fs,blockingQuestions:v(d({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(d({id:nt,role:k(["user","assistant","system","tool"]),text:o().max(1e5),createdAt:aa})).max(1e4).default([]),repairHistory:v(Mk).max(1e3).default([]),blockedReason:o().trim().min(1).max(1e4).nullable(),createdAt:aa,updatedAt:aa});d({schemaVersion:x("openpond.taskCreationTranscript.v1"),creationId:nt,profileId:nt,messages:Qk.shape.transcript,updatedAt:aa});d({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 ot=o().trim().min(1).max(200),Fs=o().regex(/^[a-f0-9]{64}$/),mu=d({installationId:o().uuid(),profileId:ot,ownerUserId:ot,teamId:ot,bindingId:ot,bindingRevision:m().int().positive()}).strict();d({version:x(1),scope:mu,epoch:o().uuid().nullable(),runtimeId:o().uuid(),audience:o().url(),nonce:o().uuid(),issuedAt:o().datetime(),payloadHash:Fs,signature:o().regex(/^[A-Za-z0-9+/]{86}==$/)}).strict();const Vh=d({id:ot,kind:k(["session","starter"]),title:o().trim().min(1).max(300),providerId:ot,modelId:o().trim().min(1).max(300).nullable(),experience:k(["chat","work"]),workspaceId:ot,workspaceLabel:o().trim().min(1).max(300),profileSelectionId:ot.nullable(),revision:Fs,available:j(),unavailableReason:o().max(500).nullable(),canMessage:j(),canSteer:j(),canStop:j(),activeTurnId:ot.nullable()}).strict(),Yk=2e4;d({revision:Fs,capturedAt:o().datetime(),targets:v(Vh).max(Yk)}).strict();const Ql=100,Xk=d({revision:Fs,capturedAt:o().datetime(),targetCount:m().int().min(0).max(Yk),pageCount:m().int().min(0).max(200)}).strict().refine(e=>e.pageCount===Math.ceil(e.targetCount/Ql),{message:"ponder_desktop_catalog_page_count_invalid"});d({catalog:Xk,index:m().int().min(0).max(199),targets:Vh.array().min(1).max(Ql)}).strict().refine(e=>e.index<e.catalog.pageCount&&e.targets.length===Math.min(Ql,e.catalog.targetCount-e.index*Ql),{message:"ponder_desktop_catalog_page_size_invalid"});const h8=d({revision:Fs,pageIndex:m().int().min(0).max(199)}).strict();d({scope:mu,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:Xk.nullable()}).strict();const Ao={targetId:ot,targetRevision:Fs},Jm=o().trim().min(1).max(32e3),wD=pt("action",[d({...Ao,action:x("create"),prompt:Jm,title:o().trim().min(1).max(300)}).strict(),d({...Ao,action:x("message"),prompt:Jm}).strict(),d({...Ao,action:x("steer"),prompt:Jm,expectedTurnId:ot}).strict(),d({...Ao,action:x("stop"),expectedTurnId:ot}).strict(),d({...Ao,action:x("observe"),expectedTurnId:ot}).strict(),d({...Ao,action:x("inspect"),expectedTurnId:ot}).strict()]),ID=d({scope:mu,epoch:o().uuid(),originChatTurnId:ot,originToolCallId:ot,humanControlId:ot.optional(),authorizationRevision:m().int().positive()}).strict();d({scope:mu,epoch:o().uuid(),runtimeId:o().uuid(),authorizationRevision:m().int().positive()}).strict();const _D=d({id:ot,origin:ID,payloadHash:Fs,intent:wD,target:Vh,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:d({sessionId:ot,sessionTitle:o().min(1).max(300),inputId:ot.nullable(),turnId:ot.nullable(),state:ot}).strict().nullable(),error:o().max(1e3).nullable()}).strict(),CD=d({operationId:ot,payloadHash:Fs,sessionId:ot,sessionTitle:o().min(1).max(300),inputId:ot.nullable(),turnId:ot,completedAt:o().datetime(),outcome:k(["completed","failed","cancelled"]),body:o().max(128e3),bodyTruncated:j(),assistantEventIds:v(ot).max(2e3),providerId:ot,modelId:ot.nullable(),workspaceId:ot,outputs:v(d({id:ot,title:o().min(1).max(300),contentType:ot,sizeBytes:m().int().nonnegative(),sha256:Fs}).strict()).max(100),error:o().max(2e3).nullable()}).strict(),g8=d({version:x(1),direction:k(["sent","received"]),operationId:ot,installationId:o().uuid(),profileId:ot,ownerUserId:ot,teamId:ot,sessionId:ot,title:o().min(1).max(300),turnId:ot.nullable(),receiptId:ot,status:ot,body:o(),outputs:CD.shape.outputs}).strict(),Uo=o().trim().min(1).max(240),Yl=o().trim().min(1),Xp=o().trim().min(8).max(256),ew=Se(o(),Ie()).default({}),RD=k(["created","inspecting","awaiting_source_review","awaiting_mapping","awaiting_materialization_approval","materializing","validating","ready","cancelling","cancelled","failed"]),tw=d({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()}),PD=d({path:o().trim().min(1).max(1e3),logicalType:o().trim().min(1).max(500),nullable:j(),sampleValues:v(Ie()).max(5)}),TD=d({configuration:o().trim().min(1).max(500),split:o().trim().min(1).max(500),rowCount:m().int().nonnegative().nullable(),sizeBytes:m().int().nonnegative().nullable()}),AD=d({schemaVersion:x("openpond.huggingFaceDatasetInspection.v1"),id:Uo,locator:tw,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(TD).min(1).max(1e4),columns:v(PD).min(1).max(1e4),previewRows:v(Se(o(),Ie())).max(25),sourceFiles:v(d({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:Xp.nullable()})).max(1e5),inspectedAt:Yl,metadata:ew}),ED=k(["row_id","cluster_id","prompt","messages","demonstration","chosen","rejected","expected_output","privileged_context","reward","feedback","tag","metadata"]),jD=d({sourcePath:o().trim().min(1).max(1e3),target:ED,transform:k(["identity","string","json","messages","numeric","math_final_answer"]),policy:k(["visible","privileged","metadata"]),required:j()}),nw=d({schemaVersion:x("openpond.datasetImportMapping.v1"),sourceSchemaHash:Xp,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(jD).min(1).max(1e4),nullPolicy:k(["reject","drop","preserve"]),invalidRowPolicy:k(["reject_import","drop_with_receipt"]),splitPolicy:d({seed:m().int(),assignments:Se(o(),br),validationPercent:m().min(0).max(100),frozenEvalPercent:m().min(0).max(100)}),importerVersion:o().trim().min(1).max(200),mappingHash:Xp}),MD=d({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()}),OD=d({schemaVersion:x("openpond.datasetImportJob.v1"),id:Uo,profileId:Uo,sourceKind:k(["huggingface","uploaded_file"]),status:RD,locator:tw.nullable(),inspection:AD.nullable(),mapping:nw.nullable(),progress:MD,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),tasksetId:Uo.nullable(),tasksetRevision:m().int().positive().nullable(),artifactId:Uo.nullable(),error:o().trim().min(1).max(2e4).nullable(),cancellationRequested:j(),createdAt:Yl,updatedAt:Yl,completedAt:Yl.nullable(),metadata:ew});d({profileId:Uo,url:o().trim().min(1).max(2e3)});d({name:o().trim().min(1).max(500),objective:o().trim().min(1).max(2e4),mapping:nw,targetStorageRoot:o().trim().min(1).max(4e3).nullable(),licenseApproved:j().default(!1)});var mc=o().trim().min(1).max(200),ef=d({operationId:mc,execution:vt,executionKind:x("recorded_evidence").optional(),graders:v(vr).min(1).max(100),maximumCostUsd:m().finite().min(1e-6).max(1e4),mappings:v(d({graderId:mc,fields:Uh}).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."})}),$D=d({schemaVersion:x("openpond.experimentScoringPass.v1"),id:mc,teamId:mc,revision:m().int().positive(),request:ef,graders:v(du).min(1).max(100),status:k(["queued","running","cancelling","completed","failed","cancelled"]),totalCount:m().int().min(1).max(1e4),counts:d({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:ta(),startedAt:ta().nullable(),completedAt:ta().nullable(),error:d({code:mc,message:o().max(2e3)}).strict().nullable()}).strict();$D.extend({contentHash:o().regex(/^[a-f0-9]{64}$/)});var aw=d({sourcePass:vt,graders:ef.shape.graders,mappings:ef.shape.mappings,maximumCostUsd:m().finite().positive().max(1e4)}).strict(),sw=d({externalDatasetBinding:ur,scoring:aw.optional(),modelId:o().min(1).max(300),maximumCostUsd:m().finite().positive().max(1e4)}).strict(),Kh=d({source:k(["local","github","openpond_git"]),repositoryId:o().trim().min(1),profileId:o().trim().min(1)}).strict(),Rt=o().min(1).max(240),Zn=o().regex(/^[a-f0-9]{64}$/),pc=d({schemaVersion:x("openpond.experimentImprovement.v1"),id:Rt,operationId:Rt,requestHash:Zn,actorId:Rt,teamId:Rt,projectId:Rt.nullable(),ownerWorkspaceId:Rt,ownerRevision:m().int().nonnegative(),ownerSourceRevision:o().min(1).max(500),baseRelease:vt,profileRef:Kh,baseProfileSourceRevision:o().min(1).max(500),evidence:d({manifest:or,result:ir}).strict(),component:d({kind:k(["skill","workflow","agent","instruction"]),path:o().min(1).max(2e3),workflowId:Rt.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:d({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:d({sessionId:Rt,turnId:Rt,revision:m().int().positive(),startedAt:o().datetime()}).strict().nullable(),frozen:d({release:vt,sourceRevision:o().min(1).max(500),profileSourceRevision:o().min(1).max(500),authoringHash:Zn,partitionHash:Zn,executableSourceHash:Zn,protectedClosureHash:Zn,candidateRevision:m().int().positive(),diff:v(d({path:o(),before:Zn.nullable(),after:Zn.nullable()}).strict()).max(1e4)}).strict().nullable(),test:d({recipe:sw,recipeHash:o().regex(/^[a-f0-9]{64}$/),baselineOperationId:o(),candidateOperationId:o(),cancelRequestedAt:o().datetime().nullable(),dispatching:d({kind:k(["baseline","candidate"]),token:Rt,pid:m().int().positive(),processStart:o().nullable(),startedAt:o().datetime()}).strict().nullable()}).strict().nullable(),comparison:d({baseline:d({manifest:or,result:ir}).strict(),candidate:d({manifest:or,result:ir}).strict(),frozenHash:Zn,humanProjection:Yp.optional()}).strict().nullable(),adoptionIntent:d({operationId:Rt,expectedOwnerRevision:m().int().nonnegative(),frozenHash:Zn,humanProjection:Yp.optional()}).strict().nullable(),acceptance:vt.nullable(),rollback:vt.nullable(),error:o().max(2e3).nullable(),createdAt:o().datetime(),updatedAt:o().datetime(),contentHash:Zn}).strict();function v8(e){const t=pc.parse(e),{contentHash:n,...a}=t;if(zt(a)!==n)throw new Error("Improvement state integrity failed.");if(Jo(t.evidence),t.evidence.manifest.teamId!==t.teamId||t.evidence.result.status!=="completed"||!t.evidence.result.cases.some(s=>s.status==="completed"))throw new Error("Improvement requires usable completed owner evidence.");if(t.test&&(zt(t.test.recipe)!==t.test.recipeHash||Kp(t.test.recipe.externalDatasetBinding).profileId!==t.profileRef.profileId))throw new Error("The test recipe changed its exact selected Profile.");if(t.comparison?.humanProjection){const s=X$(t.comparison.humanProjection);if(s.teamId!==t.teamId||s.projectId!==t.projectId||zt(s.baseline)!==zt(t.comparison.baseline)||zt(s.candidate)!==zt(t.comparison.candidate))throw new Error("Human comparison projection differs from its exact owner evidence.")}if(t.comparison&&(Jo(t.comparison.baseline),Jo(t.comparison.candidate),!t.frozen||t.comparison.frozenHash!==zt(t.frozen)||!jO(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!==zt(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 b8=d({states:v(pc).max(50),nextCursor:Rt.nullable()}).strict(),ND=d({operationId:Rt,ownerWorkspaceId:Rt,expectedOwnerRevision:m().int().nonnegative(),baseRelease:vt,profileRef:Kh,profileSourceRevision:o().min(1).max(500),projectId:Rt.nullable(),evidence:vt,component:pc.shape.component,mode:pc.shape.mode,limits:pc.shape.limits}).strict(),y8=pt("operation",[d({operation:x("list"),limit:m().int().min(1).max(50).default(30),cursor:Rt.optional()}).strict(),d({operation:x("options"),evidence:vt}).strict(),d({operation:x("start"),request:ND}).strict(),d({operation:k(["read","humanComparisonOptions"]),id:Rt}).strict(),d({operation:x("instructions"),id:Rt}).strict(),d({operation:x("edit"),id:Rt,revision:m().int().positive(),expectedFileHash:Zn,text:o().max(25e4)}).strict(),d({operation:x("mode"),id:Rt,revision:m().int().positive(),mode:k(["manual","llm_assisted"])}).strict(),d({operation:x("author"),id:Rt,revision:m().int().positive(),modelId:Rt,prompt:o().min(1).max(2e4)}).strict(),d({operation:k(["freeze","finishAuthoring","useCandidate","discard","cancel","rollback"]),id:Rt,revision:m().int().positive()}).strict(),d({operation:x("test"),id:Rt,revision:m().int().positive(),recipe:sw}).strict(),d({operation:x("compare"),id:Rt,revision:m().int().positive(),baseline:vt,candidate:vt,humanSelections:ak.optional()}).strict()]),rw=d({teamId:Rt,evidence:vt,scoring:aw.optional(),profiles:v(d({id:Zn,name:o(),profileRef:Kh,ownerWorkspaceId:Rt,ownerRevision:m().int().nonnegative(),baseRelease:vt,profileSourceRevision:o(),components:v(d({kind:k(["skill","instruction","agent","workflow"]),path:o(),agentId:o().optional(),workflowId:o().optional(),label:o(),binding:ur}).strict()).max(500)}).strict()).max(100)}).strict(),DD=d({candidateId:Rt,actorId:Rt,teamId:Rt,projectId:Rt.nullable(),candidateRevision:m().int().positive(),recipeHash:Zn,baseline:d({manifest:or,result:ir}).strict(),candidate:d({manifest:or,result:ir}).strict(),contentHash:Zn}).strict();function S8(e){const t=DD.parse(e),{contentHash:n,...a}=t;if(zt(a)!==n)throw new Error("Accepted Human discovery integrity failed.");for(const s of[t.baseline,t.candidate])if(Jo(s),s.manifest.teamId!==t.teamId||s.manifest.lineage?.humanProjection)throw new Error("Discovery must retain original owner evidence.");return t}var Zt=o().trim().min(1).max(240),hs=o().regex(/^[a-f0-9]{64}$/),Wh=d({schemaVersion:x("openpond.advancedRefinerEvaluation.v1"),operationId:Zt,actorId:Zt,teamId:Zt,projectId:Zt.nullable(),mode:k(["review_quality","downstream_adaptation"]),profileRef:d({source:k(["local","github","openpond_git"]),repositoryId:Zt,profileId:Zt}).strict(),sourceRevision:o().min(1).max(500),baselineRelease:vt,refinerRelease:vt,evidence:vt,externalDatasetBinding:ur,adaptationDatasetBinding:ur,privateClosureHash:hs,adaptationTaskIds:v(Zt).min(1).max(1e4),holdoutTaskIds:v(Zt).min(1).max(1e4),adaptationSplit:k(["train","validation","test","frozen_eval"]),holdoutSplit:k(["train","validation","test","frozen_eval"]),environmentPolicy:pt("kind",[d({kind:x("resettable"),environmentHash:hs}).strict(),d({kind:x("frozen_observations"),environmentHash:hs}).strict()]),maximumCostUsd:m().finite().positive().max(1e4),maximumDurationMs:m().int().min(1e3).max(864e5),maximumModelSteps:m().int().min(1).max(1e3),contentHash:hs}).strict();function x8(e){const t=Wh.parse(e),{contentHash:n,...a}=t;if(zt(a)!==n)throw new Error("Advanced Refiner evaluation admission changed.");const s=Kp(t.externalDatasetBinding);if(s.profileId!==t.profileRef.profileId||s.protectedProfileClosureHash!==t.privateClosureHash)throw new Error("Advanced evaluation changed its Profile or protected evaluator closure.");if(t.adaptationSplit===t.holdoutSplit||new Set([...t.adaptationTaskIds,...t.holdoutTaskIds]).size!==t.adaptationTaskIds.length+t.holdoutTaskIds.length)throw new Error("Adaptation and private holdout must be disjoint ordered cases.");const r=Kp(t.adaptationDatasetBinding);if(r.profileId!==s.profileId||r.packageHash!==s.packageHash||zt(r.dataset)!==zt(s.dataset)||zt(r.target)!==zt(s.target)||r.protectedProfileClosureHash!==s.protectedProfileClosureHash)throw new Error("This native advanced adapter needs separate adaptation and holdout recipes from the same exact released package and target.");if(r.split!==t.adaptationSplit||s.split!==t.holdoutSplit)throw new Error("Advanced split policies differ from their exact admitted recipes.");const i=new Set(s.population.map(u=>u.taskId)),c=new Set(r.population.map(u=>u.taskId));if(t.holdoutTaskIds.some(u=>!i.has(u))||t.adaptationTaskIds.some(u=>!c.has(u)))throw new Error("Advanced evaluation selected cases outside its exact Dataset recipe.");return t}var LD=d({pin:Wh,modelId:Zt,profileId:Zt,model:Th,seed:m().int(),reasoningEffort:k(["none","off","low","medium","high","xhigh","max"]).nullable()}).strict(),zD=pt("operation",[d({operation:x("start"),request:LD}).strict(),d({operation:k(["read","cancel","resume"]),id:Zt}).strict(),d({operation:x("list")}).strict()]),HD=d({taskId:Zt,sourceCaseHash:hs,reviewSessionId:Zt,reviewTurnId:Zt,inputHarness:vt,trigger:vt,decision:k(["no_action","route_deterministically","queue_refiner"]),outcome:vt.nullable(),proposal:vt.nullable(),validations:v(vt).max(100),grade:d({id:Zt,contentHash:hs,score:m().min(0).max(1).nullable(),passed:j(),failureClass:o().nullable()}).strict(),resetComplete:j()}).strict(),UD=d({schemaVersion:x("openpond.advancedRefinerReviewReceipt.v1"),id:Zt,runId:Zt,pinHash:hs,ownerActorId:Zt,teamId:Zt,privateClosureHash:hs,refinerRelease:vt,cases:v(HD).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:hs}).strict(),rb=rw.shape.profiles.element,k8=rw.extend({profiles:v(rb.extend({components:v(rb.shape.components.element.extend({adaptationSplits:v(d({split:k(["train","validation","test","frozen_eval"]),taskIds:v(Zt)})),environmentHash:hs,resettable:j(),reviewQuality:j()}))})),refinerReleases:v(vt),activeRefiner:vt.nullable(),models:v(d({id:Zt,profileId:Zt,name:o(),location:k(["local","hosted"])}))}),qD=d({operation:x("prepare"),evidence:vt,profileOptionId:Zt,componentLabel:Zt,mode:k(["review_quality","downstream_adaptation"]),adaptationSplit:k(["train","validation","test","frozen_eval"]),operationId:Zt,refinerRelease:vt,maximumCostUsd:m().positive(),maximumDurationMs:m().int().positive(),maximumModelSteps:m().int().positive()}).strict();gt([zD,qD,d({operation:x("options"),evidence:vt}).strict()]);var BD=d({modelRequests:m().int().nonnegative(),knownSpendUsd:m().nonnegative(),totalSpendUsd:m().nonnegative().nullable(),heldUsd:m().nonnegative(),uncertainRequests:m().int().nonnegative()}).strict();const Ys=E.nullable(),Ms=m().int().nonnegative(),FD=o().regex(/^[a-f0-9]{40}$/),VD=d({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(),KD=d({schemaVersion:x("openpond.correlatedTelemetryReceipt.v1"),stage:k(["training","evaluation","deployment","inference"]),correlation:d({modelRunId:Ys,modelVersionId:Ys,policyVersion:Ms.nullable(),taskId:Ys,rolloutGroupId:Ys,providerResourceId:Ys,deploymentId:Ys,inferenceRequestId:Ys}).strict(),spans:v(VD).max(1e4),usage:d({promptTokens:Ms.nullable(),generatedTokens:Ms.nullable(),gpuSeconds:m().nonnegative().nullable(),workerActiveSeconds:m().nonnegative().nullable(),optimizerSteps:Ms.nullable(),rolloutGroups:Ms.nullable(),successfulTrajectories:Ms.nullable(),failedTrajectories:Ms.nullable(),peakGpuMemoryBytes:Ms.nullable(),peakGpuUtilizationPercent:m().min(0).max(100).nullable()}).strict(),resource:d({provider:E,resourceIds:v(E).max(1e3),gpuType:o().trim().min(1).max(300).nullable(),gpuCount:Ms.nullable(),baseProfileId:Ys,baseRepository:o().trim().min(1).max(512).nullable(),baseRevision:FD.nullable(),adapterContentHash:W.nullable()}).strict(),cost:d({currency:x("USD"),providerReportedUsd:m().nonnegative().nullable(),quotedHourlyUsd:m().nonnegative().nullable(),estimatedUsd:m().nonnegative().nullable(),methodologyVersion:o().trim().min(1).max(160),pricingInputs:Se(o().trim().min(1).max(160),m().finite()),unitEstimates:Se(o().trim().min(1).max(160),m().nonnegative())}).strict(),recordedAt:Ce,contentHash:W}).strict(),gn=o().trim().min(1).max(240),Hs=o().regex(/^[a-f0-9]{64}$/),nr=o().datetime({offset:!0}),In=d({id:gn,contentHash:Hs}).strict(),WD=In.extend({revision:m().int().positive()}).strict(),ow=d({providerId:gn,modelId:o().trim().min(1).max(300)}).strict(),pu=k(["correction","sibling_verification","cumulative_known","development","retained","frozen_final","training_eligible"]),GD=d({taskId:gn,taskContentHash:Hs,panelRole:pu,passLabel:gn.nullable(),optimizerEligible:j(),criticalInvariantIds:v(gn).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."})}),ZD=d({schemaVersion:x("openpond.continualBenchIssuePacket.v1"),id:gn,revision:m().int().positive(),contentHash:Hs,familyId:gn,familyLabel:o().trim().min(1).max(500),severity:k(["low","medium","high","critical"]),cases:v(GD).min(2).max(1e4),duplicateEvidence:In,leakageEvidence:In,priorExposureEvidence:In,observedAt:nr,reviewedAt:nr,queuedAt:nr.nullable(),runAt:nr.nullable(),createdBy:gn,createdAt:nr}).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."})}),JD=d({id:gn,role:pu,passLabel:gn.nullable(),taskset:WD,familyIds:v(gn).min(1).max(1e5),taskCount:m().int().positive().max(1e6),sealedAt:nr}).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."})}),Qm=pt("kind",[d({kind:x("base_model"),id:gn,revision:o().trim().min(1).max(500),contentHash:Hs}).strict(),d({kind:x("model_version"),id:gn,contentHash:Hs}).strict(),d({kind:x("external_reference"),id:gn,model:ow,providerRevision:o().trim().min(1).max(500),contentHash:Hs}).strict()]),QD=d({scheduleEntryId:gn,ordinal:m().int().nonnegative(),label:gn,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(gn).min(1).max(1e3),optimizerGroupsPerTask:m().int().positive().max(1e3),trajectoriesPerGroup:m().int().min(4).max(1e3)}).strict(),YD=d({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(),XD=d({schemaVersion:x("openpond.continualBenchmarkProtocol.v1"),id:gn,revision:m().int().positive(),contentHash:Hs,ownerId:gn,createdAt:nr,sealedAt:nr,creationReceipt:In,predecessorSeries:d({id:gn,revision:m().int().positive(),contentHash:Hs}).strict().nullable(),scenarioPack:In,issueFamilyLedger:In,issuePacketRelease:In,panels:v(JD).min(6).max(1e4),grader:In,judge:d({release:In,rubricRelease:In,calibrationRelease:In,model:ow}).strict().nullable(),policies:d({base:Qm,master:Qm.nullable(),externalReferences:v(Qm).min(1).max(20)}).strict(),invariants:d({systemPromptHash:Hs,toolSchema:In,application:In,harness:In,runtime:In,workerImage:In,autoRefiner:d({enabled:j(),release:In.nullable()}).strict()}).strict(),schedule:v(QD).min(1).max(1e3),evaluation:d({seeds:v(m().int()).min(3).max(100),repetitions:m().int().min(3).max(20),powerRule:In,pairedBootstrapSamples:m().int().min(1e3).max(1e6),confidenceLevel:x(.95)}).strict(),resources:d({maximumTrainingGpuSeconds:m().int().positive(),maximumEvaluationGpuSeconds:m().int().positive(),maximumProviderSpendUsd:m().positive(),maximumTotalSpendUsd:m().positive(),maximumConcurrentGroups:m().int().positive().max(1e3)}).strict(),currencyThresholds:YD}).strict().superRefine((e,t)=>{const n=e.panels.map(r=>r.id);new Set(n).size!==n.length&&t.addIssue({code:"custom",path:["panels"],message:"Protocol panel ids must be unique."});for(const r of["development","retained","frozen_final","training_eligible"])e.panels.filter(i=>i.role===r).length!==1&&t.addIssue({code:"custom",path:["panels"],message:`A protocol requires exactly one ${r} panel.`});[...e.schedule].sort((r,i)=>r.ordinal-i.ordinal).some((r,i)=>r.ordinal!==i)&&t.addIssue({code:"custom",path:["schedule"],message:"Protocol schedule ordinals must be contiguous from zero."});const s=new Set(n);e.schedule.some(r=>r.correctionPanelIds.some(i=>!s.has(i)))&&t.addIssue({code:"custom",path:["schedule"],message:"Every scheduled correction panel must belong to the protocol."})}),eL=k(["draft","active","completed","archived"]),tL=k(["draft","ready","queued","running","candidate","accepted","rejected","no_signal","failed","cancelled"]),iw=k(["seed","daily_residual","rank_candidate","weekly_rollup","full_refresh"]),nL=k(["base_model","previous_release","seed_release","accepted_daily_head","accepted_seed"]),aL=k(["seed_taskset","nightly_selection","daily_cohort_union","eligible_task_pool"]),sL=k(["live_client","evaluation_attempt","replay_evidence","manual"]),rL=d({id:E,ordinal:m().int().nonnegative(),label:o().trim().min(1).max(100),role:iw,parentRule:nL,taskSource:aL,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:s}=n[e.role];a.includes(e.parentRule)||t.addIssue({code:"custom",path:["parentRule"],message:`${e.role} requires parent rule ${a.join(" or ")}.`}),e.taskSource!==s&&t.addIssue({code:"custom",path:["taskSource"],message:`${e.role} requires task source ${s}.`}),e.ordinal===0&&e.role!=="seed"&&t.addIssue({code:"custom",path:["role"],message:"The first series entry must be the seed."})}),oL=d({id:E,version:m().int().positive(),requireCheckpoint:j(),requireAppliedOptimizerUpdate:j(),minimumCurrentCohortMeanImprovement:m().finite(),maximumRetainedMeanRegression:m().finite().nonnegative(),blockCriticalInvariantRegression:j(),automaticDailyAdvancement:j()}).strict(),iL=d({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:eL,revision:m().int().positive(),productionBinding:d({role:x("chat_manual"),roleTargetId:E}).strict(),baseModel:d({id:E,revision:o().trim().min(1).max(256)}).strict(),seedTaskset:Vt,eligibleTaskPool:Vt,evaluationTasksets:d({development:Vt,retained:Vt,frozenFinal:Vt}).strict(),grader:re,benchmarkProtocol:XD.nullable().default(null),automaticEvaluation:d({enabled:j()}).strict().default({enabled:!1}),residualProfile:d({profileId:E,serializedEnvelopeRank:m().int().positive().max(1024),maximumEnabledRank:m().int().positive().max(1024),topology:x("uniform_block_masked")}).strict(),schedule:v(rL).min(1).max(1e3),scheduleSealedAt:Ce.nullable(),advancementPolicy:oL,executionPolicy:d({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((u,l)=>u.ordinal-l.ordinal).some((u,l)=>u.ordinal!==l)&&t.addIssue({code:"custom",path:["schedule"],message:"Schedule ordinals must be unique and contiguous from zero."}),(new Set(e.schedule.map(u=>u.id)).size!==e.schedule.length||new Set(e.schedule.map(u=>u.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(u=>`${u.id}:${u.revision}:${u.contentHash}`)).size!==a.length&&t.addIssue({code:"custom",path:["evaluationTasksets"],message:"Development, retained, and frozen-final cohorts require distinct immutable Taskset releases."});const s=e.schedule.find(u=>u.role==="seed");if(!s||e.schedule.filter(u=>u.role==="seed").length!==1){t.addIssue({code:"custom",path:["schedule"],message:"A series requires exactly one seed entry."});return}const r=e.schedule.filter(u=>u.role==="rank_candidate");r.length===1&&t.addIssue({code:"custom",path:["schedule"],message:"A causal rank comparison requires at least two rank candidates."}),new Set(r.map(u=>u.trainableRank)).size!==r.length&&t.addIssue({code:"custom",path:["schedule"],message:"Causal rank candidates must use distinct trainable ranks."}),[s.trainableRank+e.schedule.filter(u=>u.role==="daily_residual").reduce((u,l)=>u+l.trainableRank,0),...e.schedule.filter(u=>u.role==="weekly_rollup").map(u=>s.trainableRank+u.trainableRank),...e.schedule.filter(u=>u.role==="rank_candidate").map(u=>s.trainableRank+u.trainableRank),...e.schedule.filter(u=>u.role==="full_refresh").map(u=>u.trainableRank)].some(u=>u>e.residualProfile.maximumEnabledRank)&&t.addIssue({code:"custom",path:["schedule"],message:"A declared branch exceeds the maximum enabled rank."})}),cw=d({source:sL,taskIds:v(E).min(1).max(1e5),observedFrom:Ce,observedTo:Ce,reviewedAt:Ce,reviewedBy:E,sourceTaskset:Vt}).strict(),cL=cw.extend({derivedFamilyKeys:v(E).min(1).max(1e5),familyDerivation:d({algorithm:E,sourceTasksetHash:W}).strict(),selectionHash:W}).strict(),lw=pt("kind",[d({kind:x("base_model"),id:E,revision:o().trim().min(1).max(256)}).strict(),d({kind:x("model_version"),id:E,contentHash:W}).strict()]),lL=d({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."})}),dL=d({disposition:k(["advance","hold","no_signal"]),policy:d({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(),uL=d({evaluationRunId:E,modelVersionId:E,taskset:Vt,grader:re,cohortRole:k(["current","correction","sibling_verification","cumulative_known","development","retained","prior_disclosed","frozen_final"]),panelId:E.nullable().default(null),protocol:d({id:E,revision:m().int().positive(),contentHash:W}).strict().nullable().default(null)}).strict(),mL=d({attemptOrdinal:m().int().positive(),trainingPlanId:E.nullable(),modelRunId:E.nullable(),terminalStatus:k(["failed","cancelled"]),queuedAt:Ce.nullable(),startedAt:Ce.nullable(),completedAt:Ce}).strict(),di=d({seriesId:E,entryId:E,scheduleEntryId:E,ordinal:m().int().nonnegative(),releaseHash:W}).strict(),pL=d({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:iw,branch:k(["daily","rank_candidate","weekly_rollup","full_refresh"]),status:tL,parent:lw,taskset:Vt,sourceTasksets:v(Vt).min(1).max(1e3),taskSelection:cL.nullable(),trainableRank:m().int().positive().max(1024),serializedEnvelopeRank:m().int().positive().max(1024),enabledCumulativeRank:m().int().positive().max(1024),trainableBlockId:E,residualBlocks:v(lL).min(1).max(1024),attemptOrdinal:m().int().positive().default(1),priorRunAttempts:v(mL).max(100).default([]),trainingPlanId:E.nullable(),modelRunId:E.nullable(),modelVersionId:E.nullable(),evaluations:v(uL).max(1e5),decision:dL.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 s=e.residualBlocks.filter(i=>i.optimizationRole==="trainable");(s.length!==1||s[0]?.id!==e.trainableBlockId||s[0]?.rank!==e.trainableRank)&&t.addIssue({code:"custom",path:["trainableBlockId"],message:"Exactly one block must be trainable during the Run and match trainableRank."});const r=e.priorRunAttempts.map(i=>i.attemptOrdinal);(e.priorRunAttempts.length!==e.attemptOrdinal-1||r.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."})});d({seriesId:E,scheduleEntryId:E,taskSelection:cw.nullable(),expectedSeriesRevision:m().int().positive()}).strict();const fL=k(["base_reference","lora_adapter"]),dw=d({baseModel:d({source:x("huggingface"),repoId:E,revision:o().regex(/^[a-f0-9]{40}$/),configHash:W,tokenizerHash:W,licenseId:E,gated:j()}).strict(),processor:d({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."})}),hL=d({schemaVersion:x("openpond.modelVersion.v1"),id:E,modelId:E,profileId:E,version:m().int().nonnegative(),kind:fL,status:k(["available","failed"]),baseModel:Kc,taskset:Vt,comparisonSeriesEntry:di.nullable().optional(),evaluationTasksetRef:Vt.nullable().optional(),releaseGraph:d({resolvedBundleHash:W,profileRelease:Vt,harnessRelease:re,agentRelease:re.nullable(),grader:d({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."})}),gL=d({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:Kc,runtime:dw.nullable().default(null),taskset:Vt,preferenceDatasetRelease:re,releaseGraph:d({resolvedBundleHash:W,profileRelease:Vt,harnessRelease:re,grader:d({id:E,contentHash:W}).strict()}).strict(),artifacts:d({checkpoint:re.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:v(d({path:o().trim().min(1).max(512),sizeBytes:m().int().positive(),sha256:W}).strict()).min(4).max(128)}).strict(),adapter:re,scalarHead:re,bucketHead:re.nullable(),processorRelease:re}).strict(),qualificationReport:re.nullable(),createdAt:Ce,contentHash:W}).strict(),vL=d({schemaVersion:x("openpond.rewardModelRunReceipt.v1"),provider:E,providerRunId:E,resolvedBundleHash:W,finalCheckpoint:re.extend({objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/)}).strict(),adapter:re,scalarHead:re,bucketHead:re.nullable(),processorRelease:re,optimizerEvidence:re,managedExecutionReceipt:re.nullable().default(null),parameterDeltaHash:W,cleanup:d({computeReleased:j(),providerTerminalObserved:j()}).strict(),contentHash:W}).strict(),bL=VA(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}}},d({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:Vt,tasksetRelease:re,preferenceDatasetRelease:re,recipeRelease:re,destinationId:E,quote:d({maximumSpendUsd:m().positive(),hourlyCostUsd:m().nonnegative().nullable()}).strict(),managedRunId:E.nullable(),progress:d({completedSteps:m().int().nonnegative(),totalSteps:m().int().positive(),latestLoss:m().finite().nullable()}).strict(),receipt:vL.nullable(),qualificationReport:re.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."})}),yL=d({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:d({computeReleased:j(),tunnelClosed:j()}).strict(),telemetry:KD.nullable().default(null),contentHash:W}).strict(),er=d({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),totalTokens:m().int().nonnegative(),costUsd:m().nonnegative().nullable()}).strict(),ob=o().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),Gh=d({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:Fh.nullable(),inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),totalTokens:m().int().nonnegative(),latencyMs:m().int().nonnegative(),costUsd:m().nonnegative().nullable(),startedAt:Ce}).strict(),ib=d({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(),uw=d({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:d({adaptation:ib,heldOut:ib}).strict()}).strict(),Zh=d({baseline:er,adaptation:er,candidateAdaptation:er,candidate:er,refiner:er,grader:er}).strict(),SL=d({usage:Zh,observedSpendUsd:m().nonnegative(),attempts:v(Gh).max(1e4)}).strict(),xL=d({id:E,contentHash:W,artifactPath:o().trim().min(1).max(2e3)}).strict(),kL=d({schemaVersion:x("openpond.modelEvaluationReceipt.v1"),benchmarkId:E,resultManifest:d({id:E,contentHash:W,artifactPath:o().trim().min(1).max(2e3)}).strict(),stages:d({baseline:re,adaptation:re,refiner:re,candidateAdaptation:re,candidate:re,comparison:re}).strict(),usage:Zh,quality:d({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:uw.optional(),efficiency:d({grossForegroundTokenSavings:m().int(),overheadTokens:m().int().nonnegative(),firstPassNetTokenSavings:m().int(),breakEvenReuseCount:m().int().nonnegative().nullable(),amortizedTokenSavings:m().int(),amortizedReuseCount:m().int().positive()}).strict(),budget:d({maximumSpendUsd:m().nonnegative(),observedSpendUsd:m().nonnegative(),enforced:j()}).strict(),evidenceSnapshot:re,lineage:d({adaptationEvidenceHash:W,refinerInputHash:W,refinerOutcomeHash:W,validationHash:W,applyReceiptHash:W,candidateRelease:re,valid:j()}).strict(),invalidReasons:v(o().trim().min(1).max(2e3)).max(100),attempts:v(Gh).max(1e4).default([]),terminalClassification:k(["improved","no_improvement","regressed","inconclusive","cancelled","infrastructure_failure"]),profileGit:d({ref:o().trim().min(1).max(2e3),commit:ob,baseCommit:ob}).strict().nullable(),contentHash:W}).strict(),wL=d({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:re,candidateHarness:re,refiner:d({id:E,contentHash:W,outcomeCount:m().int().nonnegative()}).strict(),usage:Zh,budget:d({maximumSpendUsd:m().nonnegative(),observedSpendUsd:m().nonnegative(),enforced:j()}).strict(),evidenceSnapshot:re,attempts:v(Gh).max(1e4),contentHash:W}).strict(),cb=d({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."})}),IL=d({schemaVersion:x("openpond.modelComparisonBenchmarkReceipt.v1"),benchmarkId:x("model-comparison"),target:d({kind:k(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:E.nullable(),model:cn.nullable()}).strict(),taskset:Vt,grader:re,sampling:d({seeds:v(m().int()).min(1).max(100),repetitions:m().int().positive().max(20)}).strict(),deterministic:d({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:cb.nullable()}).strict(),judge:d({judgeModel:cn,judgeRelease:re,rubricRelease:re,calibrationRelease:re,score:m().min(0).max(100),scoreCi95:cb,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(d({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:d({artifactPath:o().trim().min(1).max(2e3),jsonPointer:o().trim().min(1).max(1e3)}).strict().nullable().default(null),traceArtifact:d({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:Fh.nullable()}).strict()).max(1e5),usage:d({policy:er.nullable(),judge:er.nullable(),observedSpendUsd:m().nonnegative().nullable(),evaluationGpuSeconds:m().nonnegative().nullable().default(null)}).strict(),managedServing:d({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:d({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."})}),_L=d({advancedEvaluation:Wh.optional(),benchmarkId:x("harness-refiner"),model:cn,upstreamModel:d({providerId:E,modelId:o().trim().min(1).max(300),revision:o().trim().min(1).max(300),pricing:d({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(d({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(),CL=d({benchmarkId:x("model-comparison"),target:d({kind:k(["base_model","model_version","external_reference"]),label:o().trim().min(1).max(300),modelVersionId:E.nullable(),model:cn.nullable()}).strict(),grader:re,judge:d({model:cn,release:re,rubricRelease:re,calibrationRelease:re,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:d({id:E,protocol:d({id:E,revision:m().int().positive(),contentHash:W}).strict()}).strict().nullable().default(null),panel:d({id:E,role:k(["correction","sibling_verification","cumulative_known","development","retained","frozen_final"]),passLabel:E.nullable()}).strict().nullable().default(null),comparisonPair:d({entryId:E,parent:lw,candidateModelVersionId:E}).strict().nullable().default(null),attemptPlan:v(d({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(),RL=gt([_L,CL]),PL=d({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:Vt,comparisonSeriesEntry:di.nullable().optional(),evaluationTasksetRef:Vt.nullable().optional(),harnessRelease:re.nullable().optional(),quote:d({maximumSpendUsd:m().nonnegative(),hourlyCostUsd:m().nonnegative().nullable()}).strict().nullable(),evaluation:RL.nullable().default(null),evaluationProgress:d({stage:k(["baseline","adaptation","refiner","candidate_adaptation","candidate","comparison"]),completedAttempts:m().int().nonnegative(),totalAttempts:m().int().positive(),accounting:SL.nullable().default(null),advancedAccounting:BD.optional(),evidenceSnapshot:xL.nullable().default(null)}).strict().nullable().default(null),reward:d({raw:m(),components:Se(o(),m())}).strict().nullable(),receipt:gt([yL,kL,wL,IL,UD]).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 w8(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}]:[]})}),s=new Set(n.filter(I=>I.phase==="baseline"||I.phase==="adaptation").map(I=>I.taskId)).size,r=e.targetTaskCount??s;if(!Number.isInteger(r)||r<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}),u=c(a,r),l=a.reduce((I,C)=>I+C.baseline.totalTokens,0),p=a.reduce((I,C)=>I+C.refined.totalTokens,0),f=p-l,y=a.length===r;return{summary:uw.parse({target:"all_tasks_lower",...u,baselineTokens:l,refinedTokens:p,tokenDelta:f,tokenDeltaPercent:l>0?f/l*100:null,complete:y,passed:y&&u.passedTaskCount===r,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 TL=k(["measuring","up_to_date","needs_attention"]),AL=k(["fixed","retained","regressed","unresolved","unavailable"]),lb=d({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(),tf=d({level:x(.95),lower:m().finite(),upper:m().finite()}).strict(),EL=d({panelId:E,panelRole:pu,passLabel:E.nullable(),taskset:Vt,attempted:m().int().nonnegative(),available:m().int().nonnegative(),passed:m().int().nonnegative(),strictSuccess:m().min(0).max(1).nullable(),strictSuccessCi95:tf.nullable(),judgeScore:m().min(0).max(100).nullable(),judgeScoreCi95:tf.nullable()}).strict(),jL=d({schemaVersion:x("openpond.modelCurrencySnapshot.v1"),id:E,contentHash:W,seriesId:E,protocol:d({id:E,revision:m().int().positive(),contentHash:W}).strict(),entryId:E,passLabel:E,parent:pt("kind",[d({kind:x("base_model"),id:E,revision:o().trim().min(1).max(500)}).strict(),d({kind:x("model_version"),id:E,contentHash:W}).strict()]),candidate:d({kind:x("model_version"),id:E,contentHash:W}).strict(),sources:d({evaluationRunIds:v(E).max(1e5),attemptIds:v(E).max(1e6),tasksets:v(Vt).max(1e4),grader:re,judge:re.nullable(),calibration:re.nullable()}).strict(),matches:v(d({key:E,panelId:E,panelRole:pu,taskId:E,issueFamilyId:E,seed:m().int(),repetition:m().int().nonnegative(),classification:AL,parentPassed:j().nullable(),candidatePassed:j().nullable(),parentAttempt:lb.nullable(),candidateAttempt:lb.nullable()}).strict()).max(1e6),taskIds:d({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(EL).max(1e4),metrics:d({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:d({matchedAttemptCount:m().int().nonnegative(),strictDelta:m().finite().nullable(),strictDeltaCi95:tf.nullable(),exactPairedBinaryPValue:m().min(0).max(1).nullable(),pairedBootstrapSamples:m().int().positive()}).strict(),criteria:d({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:re}).strict(),efficiency:d({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:d({systemPromptHash:W,toolSchema:re,application:re,harness:re,runtime:re,grader:re,autoRefinerEnabled:j()}).strict(),evidenceState:TL,evidenceReasons:v(E).max(100),projectedAt:Ce}).strict(),Xl=pt("kind",[d({kind:x("base_model"),id:E,revision:o().trim().min(1).max(500),label:o().trim().min(1).max(300)}).strict(),d({kind:x("model_version"),id:E,label:o().trim().min(1).max(300)}).strict(),d({kind:x("captured_model"),id:E,label:o().trim().min(1).max(300)}).strict()]),fc=gt([d({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:Se(o(),m().finite()).default({})}).strict(),d({source:x("imported_response"),modelLabel:o().trim().min(1).max(300),modelVersionId:E.nullable().default(null),response:Ie().refine(e=>e!==void 0,"An imported model response is required."),reward:m().finite().nullable().default(null),components:Se(o(),m().finite()).default({})}).strict()]),ML=gt([d({taskId:E,target:Xl,attempt:fc}).strict(),d({taskId:E,target:k(["base","current"]).default("current"),attempt:fc}).strict(),d({taskId:E,target:k(["base","current"]).default("current"),evaluationRunId:E,attemptId:E,reward:m().finite().nullable(),components:Se(o(),m().finite()).default({})}).strict().transform(({taskId:e,target:t,...n})=>({taskId:e,target:t,attempt:{source:"evaluation_run",modelLabel:null,modelVersionId:null,...n}}))]);d({schemaVersion:x("openpond.continualLearningDailyBatchManifest.v1"),id:E,seriesId:E,scheduleEntryId:E,dayOrdinal:m().int().positive().max(1e4),sourceTaskset:Vt,taskIds:v(E).min(1).max(1e3),observedAttempts:v(ML).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}:${NL(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 OL=d({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:Vt,tasks:v(d({taskId:E,taskContentHash:W,familyKey:E,disposition:k(["include","defer","exclude"]).nullable(),oracleReview:k(["pending","confirmed","needs_correction"]),note:o().trim().max(2e3),observedAttempt:fc.nullable(),baselineAttempt:fc.nullable().default(null),responses:v(d({target:Xl,attempt:fc}).strict()).max(100).default([]),stagedAt:Ce.nullable().default(null),queuedEntry:di.nullable().default(null)}).strict()).min(1).max(1e3),intakeEvaluation:d({status:k(["awaiting","running","ready","failed"]),requestedTargets:v(k(["base","current"])).max(2).default(["base","current"]),requestedPolicies:v(Xl).max(100).default([]),runs:v(d({target:Xl,runId:E}).strict()).max(100).default([]),baselineRunId:E.nullable(),currentRunId:E.nullable(),currentPolicy:pt("kind",[d({kind:x("base_model"),id:E}).strict(),d({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:di.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,s]of e.tasks.entries()){const r=s.responses.map(i=>mw(i.target));new Set(r).size!==r.length&&t.addIssue({code:"custom",path:["tasks",a,"responses"],message:"A task cannot repeat a model response target."})}const n=e.tasks.every(a=>a.disposition!==null&&a.oracleReview!=="pending"&&(a.oracleReview!=="needs_correction"||a.note.length>0));e.status!=="pending"&&!n&&t.addIssue({code:"custom",path:["tasks"],message:"Every task requires a decision and oracle review before the day completes."}),e.status==="queued"!=(e.queuedEntry!==null)&&t.addIssue({code:"custom",path:["queuedEntry"],message:"Only a queued day carries an exact series-entry reference."}),e.status==="pending"&&(e.reviewedAt!==null||e.reviewedBy!==null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"A pending day cannot carry reviewer completion identity."}),e.status!=="pending"&&(e.reviewedAt===null||e.reviewedBy===null)&&t.addIssue({code:"custom",path:["reviewedAt"],message:"Reviewed identity is required after a day review completes."})}),$L=d({schemaVersion:x("openpond.continualBenchIssueReview.v1"),id:E,seriesId:E,scheduleEntryId:E,passLabel:E,packet:ZD,splitManifest:d({id:E,contentHash:W}).strict(),decisions:v(d({taskId:E,disposition:k(["include","defer","exclude"]).nullable(),note:o().trim().max(2e3)}).strict()).min(2).max(1e4),status:k(["pending","reviewed","queued"]),queuedEntry:di.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(r=>r.taskId)].sort(),a=[...e.decisions.map(r=>r.taskId)].sort();JSON.stringify(n)!==JSON.stringify(a)&&t.addIssue({code:"custom",path:["decisions"],message:"Review decisions must cover the exact issue-packet cases."});const s=e.decisions.every(r=>r.disposition!==null&&r.note.length>0);e.status!=="pending"&&!s&&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 mw(e){return`${e.kind}:${e.id}`}function NL(e){return typeof e=="string"?e:mw(e)}const Da=o().trim().min(1).max(240),ba=o().trim().min(8).max(256),pw=k(["grpo","dapo","gspo-token"]),Pc=d({id:Da,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:ba}),DL=d({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()}),LL=d({method:x("grpo"),groupSize:m().int().min(2).max(128),normalization:x("group_standardized"),advantageEpsilon:m().positive().max(.01).default(1e-8),loss:pw,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:Jk}),fw=d({method:x("ppo"),valueModel:Pc,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)}),zL=pt("method",[LL,fw]),hw=d({rewardModelVersion:d({id:Da,contentHash:ba}).strict(),qualificationReport:d({id:Da,contentHash:ba}).strict().nullable().default(null),evaluationReferences:v(d({id:Da,contentHash:ba}).strict()).max(1e3).default([]),checkpoint:d({id:Da,contentHash:ba,objectRef:o().regex(/^r2:\/\/[A-Za-z0-9._/-]+$/),files:v(d({path:o().trim().min(1).max(512),sizeBytes:m().int().positive(),sha256:ba}).strict()).min(4).max(128)}).strict(),runtime:dw,processorRelease:d({id:Da,contentHash:ba}).strict(),rewardComposerRelease:d({id:Da,contentHash:ba}).strict(),executionReceipt:d({id:Da,contentHash:ba}).strict()}).strict(),gw=d({schemaVersion:x("openpond.policyOptimization.v1"),policyModel:Pc,referenceModel:Pc,dataset:d({tasksetId:Da,tasksetHash:ba,split:x("train"),selectionStrategy:k(["stable_hash_top_n","rft_easy_curriculum_v1"]),selectionSeed:m().int(),maxExamples:m().int().positive().max(1e5)}),sampler:d({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:d({id:Da,version:o().trim().min(1).max(256),toolContractHash:ba}),reward:d({graderId:Da,graderHash:ba,learnedPreference:hw.nullable().default(null)}),kl:d({coefficient:m().nonnegative().nullable(),referenceConstraint:x("fixed_reference")}),budgets:DL,checkpointEverySteps:m().int().positive(),seed:m().int(),evaluationSplit:x("frozen_eval"),optimizer:zL}),ge=o().trim().min(1).max(240),wt=o().trim().min(1),tt=o().trim().min(8).max(256),Wc=Se(o(),Ie()).default({}),vw=d({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:wt.nullable().default(null)}),HL=vw.parse({}),UL=d({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:wt.nullable(),lastSyncedAt:wt,lastError:o().trim().min(1).max(5e3).nullable()});function I8(e){const t=e.managedServing;return!!(t?.source==="sandbox_managed_rl"&&t.canonicalArtifactState==="promotable"&&t.customerBindingAllowed)}function bw(e){return e.state==="ready"&&e.canonicalArtifactState==="promotable"&&e.canonicalDeploymentState==="ready"&&e.customerBindingAllowed&&!!e.teamId&&!!e.canonicalArtifactId&&!!e.canonicalDeploymentId}function _8(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"&&bw(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_customer_binding",evaluationArtifactId:null,canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null}function C8(e){const t=e.managedServing;return t?bw(t)&&t.canonicalArtifactId&&t.canonicalDeploymentId?{kind:"sandbox_serving",canonicalArtifactId:t.canonicalArtifactId,canonicalDeploymentId:t.canonicalDeploymentId}:null:{kind:"source_artifact",canonicalArtifactId:null,canonicalDeploymentId:null}}const Jh="openpond.crossSystemOperations.v1",R8="1.0.0",yw="openpond.crossSystemTools.v1",qL=["search_crm","query_billing","search_support","run_python"],BL=k(["train","validation","frozen_eval"]),FL=k(["easy","medium","hard"]),VL=k(["renewal_risk_v2"]);k(["renewal_exposure","collections_prioritization","invoice_reconciliation","sla_escalation","contract_billing_mismatch"]);d({seed:m().int().nonnegative(),split:BL,difficulty:FL,scenarioProfile:VL.optional()});const Ym={anyOf:[{type:"string",minLength:1,maxLength:256},{type:"null"}],default:null},Xm={type:"integer",minimum:1,maximum:50,default:25},Sw=[{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:Ym,limit:Xm}}},{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:Ym,limit:Xm}}},{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:Ym,limit:Xm}}},{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}}}}],Gc=nz({schemaVersion:yw,tools:Sw}),KL=[`Use only the four registered synthetic Cross-System Operations tools. Contract ${Gc}.`,"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(" "),WL=15;function GL(e="auto"){return[KL,"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: ${WL}.`,`Registered tool signatures: ${Sw.map(ZL).join("; ")}`].join(`
|
|
110
|
+
`)}GL();function ZL(e){const t=Id(e.parameters),n=Id(t.properties),a=xw(t.required),s=Object.fromEntries(a.map(r=>[r,ed(n[r])]));return`${e.name}(${JSON.stringify(s)})`}function ed(e){const t=Id(e),n=nf(t.anyOf);if(n.length)return n.map(ed).join("|");const a=nf(t.enum);if(a.length)return a.join("|");if(t.type==="array")return[ed(t.items)];if(t.type==="object"){const s=Id(t.properties),r=xw(t.required);return Object.fromEntries(r.map(i=>[i,ed(s[i])]))}return typeof t.type=="string"?t.type:"unknown"}function Id(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function nf(e){return Array.isArray(e)?e:[]}function xw(e){return nf(e).filter(t=>typeof t=="string")}const _d=k(qL),JL=pt("kind",[d({kind:x("model"),turn:m().int().nonnegative(),content:o().max(1e5)}),d({kind:x("tool_call"),turn:m().int().nonnegative(),callId:o().trim().min(1).max(240),name:_d,arguments:Se(o(),Ie())}),d({kind:x("tool_result"),turn:m().int().nonnegative(),callId:o().trim().min(1).max(240),name:_d,ok:j(),result:Ie(),rows:m().int().nonnegative(),bytes:m().int().nonnegative(),durationMs:m().int().nonnegative(),error:o().trim().min(1).max(2e4).nullable()}),d({kind:x("final"),turn:m().int().nonnegative(),content:o().max(1e5)})]),QL=d({schemaVersion:x(Jh),id:o().trim().min(1).max(240),worldId:o().trim().min(1).max(240),taskId:o().trim().min(1).max(240),toolContractHash:x(Gc),modelRef:d({providerId:o().trim().min(1),modelId:o().trim().min(1)}).nullable(),status:k(["completed","budget_exhausted","cancelled","infrastructure_failure"]),steps:v(JL).max(1e3),startedAt:o().trim().min(1),completedAt:o().trim().min(1),infrastructureError:o().trim().min(1).max(2e4).nullable(),metadata:Se(o(),Ie()).default({})}),YL=d({schemaVersion:x(Jh),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:d({exactAnswer:m().min(0).max(1),efficiency:m().min(0).max(.1),conciseOutput:m().min(0).max(.05)}),metrics:d({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:Ie().nullable(),feedback:v(o().trim().min(1).max(5e3)).max(100)}),XL=d({id:o().trim().min(1).max(240),type:x("function"),function:d({name:_d,arguments:o().max(2e4)})}),kw=d({role:k(["system","user","assistant","tool"]),content:o().max(2e5).nullable(),tool_call_id:o().trim().min(1).max(240).optional(),tool_calls:v(XL).max(4).optional()});d({schemaVersion:x(Jh),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(Gc),approval:d({status:x("approved"),approvedBy:o().trim().min(1).max(240),approvedAt:o().trim().min(1)}),messages:v(kw).min(3).max(1e3)});const ez=d({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(_d).min(1).max(100),toolCallCount:m().int().positive(),messageCount:m().int().min(3),reward:m().min(0).max(1.15),messages:v(kw).min(3).max(1e3)}),tz=d({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()});d({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(Gc),status:k(["ready_for_review","approved"]),approval:tz.nullable(),tasks:v(ez).min(1).max(100)});function nz(e){const t=af(e);let n=2166136261,a=2654435769;for(let s=0;s<t.length;s+=1){const r=t.charCodeAt(s);n=Math.imul(n^r,16777619),a=Math.imul(a^r,2246822507)}return`${yw}:${db(n)}${db(a)}`}function af(e){return Array.isArray(e)?`[${e.map(af).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${af(n)}`).join(",")}}`:JSON.stringify(e)}function db(e){return(e>>>0).toString(16).padStart(8,"0")}const az=d({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:wt,completedAt:wt,metadata:Wc}),sz=d({schemaVersion:x("openpond.ppoTrajectory.v1"),id:ge,taskId:ge,policyModelId:ge,referenceModelId:ge,valueModelId:ge,steps:v(d({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:wt}),rz=d({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)}),oz=d({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:d({invocationId:ge,experimentId:ge,rolloutId:ge,runId:ge,rowId:ge}),optimizerMethod:k(["grpo","ppo"]).default("grpo"),evidenceLevels:d({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:d({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:d({id:ge,version:o().trim().min(1).max(256),worldId:ge,worldHash:tt,toolContractHash:tt}),policy:d({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:d({eligible:j(),raw:m().min(0).max(1.15).nullable(),normalized:m().min(0).max(1).nullable(),components:Se(o(),m())}),trajectory:gt([QL,az,sz]).nullable(),verifier:gt([YL,rz]).nullable(),providerStatus:Se(o(),Ie()).default({}),receivedAt:wt,startedAt:wt.nullable(),completedAt:wt.nullable(),updatedAt:wt}),P8="dataset-exact-answer",T8="dataset-exact-answer-v1",A8="no-tools-v1",yr=k(["sft","dpo","grpo","ppo","sdft","opd","opsd","sdpo"]),fu=k(["lora","full"]),Xr=k(["openpond_managed"]),iz=d({schemaVersion:x("openpond.sftRecipe.v1"),method:x("sft"),parameterization:x("lora"),baseModel:d({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:tt}),dataset:d({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:d({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:d({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:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})});d({id:ge,input:Se(o(),Ie()),expectedOutput:Se(o(),Ie()),tags:v(ge).max(100).default([])});d({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)});d({id:ge,input:Se(o(),Ie()),tags:v(ge).max(100).default([])});d({schemaVersion:x("openpond.rewardModelRecipe.v1"),method:x("reward_model"),parameterization:x("lora_with_scalar_head"),runScope:k(["synthetic_smoke","human_preference"]),baseModel:d({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:re,preferenceDatasetRelease:re,processorRelease:re,input:d({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:d({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:d({scalar:x("pooled_hidden_state_linear"),bucket:k(["none","three_class"]).default("three_class")}).strict(),loss:d({ranking:x("bradley_terry"),rankingWeight:m().positive(),bucketWeight:m().nonnegative(),tieWeight:m().nonnegative()}).strict(),optimizer:d({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:d({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 cz=d({schemaVersion:x("openpond.rftRecipe.v1"),method:x("grpo"),parameterization:x("lora"),baseModel:d({id:ge,revision:o().trim().min(1).max(256),tokenizerRevision:o().trim().min(1).max(256),chatTemplateHash:tt}),dataset:d({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:d({rank:m().int().positive().max(256)}),rollout:d({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:d({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:Jk}),loss:d({method:pw.default("grpo"),klBeta:m().min(0).nullable().default(null)}).default({method:"grpo",klBeta:null}),reward:d({graderId:ge,graderHash:tt,environmentId:ge,environmentVersion:o().trim().min(1).max(256),toolContractHash:tt,learnedPreference:hw.nullable().optional()}),resourceLimits:d({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:gw.nullable().default(null),continuation:d({schemaVersion:x("openpond.crossJobContinuationRequest.v1"),parentArtifact:re,sourceArtifact:d({jobId:ge,artifactId:ge,checkpointId:ge,contentHash:tt}).strict(),optimizerMode:k(["continue","reset"])}).strict().optional()}),lz=d({schemaVersion:x("openpond.dpoRecipe.v1"),method:x("dpo"),parameterization:x("lora"),policyModel:Pc,referenceModel:Pc,dataset:d({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:d({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:d({variant:x("sigmoid"),beta:m().positive().max(10),labelSmoothing:m().min(0).max(.5).default(0)}),optimizer:d({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:d({cacheSchemaVersion:x("openpond.dpoReferenceLogprobs.v1"),cacheKey:tt,invalidationHash:tt}),resourceLimits:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})}),dz=d({schemaVersion:x("openpond.ppoRecipe.v1"),method:x("ppo"),parameterization:x("lora"),policyOptimization:gw.extend({optimizer:fw}),lora:d({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:d({initialization:x("policy_hidden_state_linear"),optimizerLearningRate:m().positive(),artifactName:x("value_head.safetensors")}),policyLearningRate:m().positive(),resume:d({checkpointId:ge.nullable(),policyHash:tt,referenceHash:tt,valueModelHash:tt,optimizerStateHash:tt.nullable()}),resourceLimits:d({cpuThreads:m().int().positive().max(256),memoryBytes:m().int().positive(),wallTimeMs:m().int().positive()})}),uz=d({schemaVersion:x("openpond.unsupportedRecipe.v1"),method:yr.exclude(["sft","dpo","grpo","ppo"]),parameterization:fu,unsupportedReason:o().trim().min(1).max(5e3)}),mz=gt([iz,lz,cz,dz,uz]),pz=d({schemaVersion:x("openpond.trainingDestinationCapabilities.v1"),destinationId:Xr,available:j(),methods:v(yr),parameterizations:v(fu),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:wt}),fz=d({destinationId:Xr,available:j(),methods:v(yr),parameterizations:v(fu),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable()}),hz=d({schemaVersion:x("openpond.baseModelCandidate.v1"),selectionKey:ge,label:o().trim().min(1).max(500),sourceLabel:o().trim().min(1).max(500),preference:Kc,available:j(),nonProduction:j(),unavailableReason:o().trim().min(1).max(5e3).nullable(),methods:v(yr),executionOptions:v(fz).min(1)}),gz=d({code:ge,severity:k(["warning","error"]),path:o().trim().max(2e3).nullable(),message:o().trim().min(1).max(5e3)}),vz=d({schemaVersion:x("openpond.trainingCompatibility.v1"),compatible:j(),destinationId:Xr,tasksetId:ge,recipeMethod:yr,issues:v(gz),checkedAt:wt}),bz=gt([Ek,k(["destination_unavailable","destination_method_unsupported","destination_model_unsupported","destination_parameterization_unsupported","experimental_destination"])]);d({method:yr,state:k(["recommended","compatible","needs_dataset_work","destination_unavailable","experimental_destination"]),reasonCodes:v(bz).default([]),reasons:v(o().trim().min(1).max(5e3)).default([]),destinationId:Xr.nullable().default(null)});k(["small","standard","custom","small_experiment"]);const yz=Xx,ww=d({schemaVersion:x("openpond.trainingPlan.v1"),id:ge,modelId:ge,tasksetId:ge,tasksetHash:tt,comparisonSeriesEntry:di.nullable().optional(),evaluationTasksetRef:Vt.nullable().optional(),harnessRelease:re.nullable().optional(),modelImprovementQualification:re.nullable().optional(),destinationId:Xr,recipe:mz,environmentPlacement:k(["none","local","remote","colocated","provider_native"]),compatibility:vz,dataPolicy:d({exportApproved:j(),approvedSourceIds:v(ge),retentionDays:m().int().nonnegative().nullable(),region:o().trim().min(1).max(200).nullable()}),estimatedCostUsd:m().nonnegative().nullable(),createdAt:wt,contentHash:tt}),Sz=d({path:o().trim().min(1).max(2e3),sha256:tt,sizeBytes:m().int().nonnegative(),role:k(["manifest","task_data","grader","environment","recipe","policy","provenance"])}),Qh=d({schemaVersion:x("openpond.trainingBundle.v1"),id:ge,planId:ge,tasksetId:ge,tasksetHash:tt,recipeHash:tt,files:v(Sz).min(1).max(1e6),totalSizeBytes:m().int().nonnegative(),sourceIds:v(ge),excludedSourceIds:v(ge),containsRawChats:x(!1),containsSecrets:x(!1),containsHiddenGraderAssets:x(!1),createdAt:wt,contentHash:tt});d({schemaVersion:x("openpond.trainingBundleExport.v1"),manifest:Qh,files:v(d({path:o().trim().min(1).max(2e3),sha256:tt,sizeBytes:m().int().nonnegative(),encoding:x("base64"),content:o()})).min(1),contentHash:tt});d({schemaVersion:x("openpond.trainingPreparedStart.v1"),plan:ww,bundle:Qh,approvalActor:ge.nullable(),preparedAt:wt});d({schemaVersion:x("openpond.trainingApproval.v1"),evaluationTasksetRef:Vt.nullable().optional(),id:ge,planId:ge,bundleHash:tt,harnessRelease:re.nullable().optional(),modelImprovementQualification:re.nullable().optional(),destinationId:Xr,modelId:ge,method:yr,parameterization:fu,maximumCostUsd:m().nonnegative().nullable(),approvedBy:ge,approvedAt:wt});d({schemaVersion:x("openpond.trainingJobSourceSnapshot.v1"),evaluationTasksetRef:Vt.nullable().optional(),modelProjectId:ge,sourceProjectRevision:m().int().positive(),profileId:ge,taskset:d({id:ge,revision:m().int().positive(),contentHash:tt}).strict(),tasksetRelease:re,harnessRelease:re,baseModel:Kc,method:yr}).strict();const xz=k(["queued","starting","running","cancelling","cancelled","succeeded","failed","reconciling"]),Iw=d({schemaVersion:x("openpond.trainingJob.v1"),id:ge,planId:ge,bundleHash:tt,approvalId:ge,destinationId:Xr,status:xz,nonProduction:j(),workerPid:m().int().positive().nullable(),startedAt:wt.nullable(),completedAt:wt.nullable(),error:o().trim().min(1).max(2e4).nullable(),createdAt:wt,updatedAt:wt,metadata:Wc}),kz=d({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:wt,payload:Wc}),wz=d({schemaVersion:x("openpond.sftStepMetric.v1"),step:m().int().nonnegative(),maxSteps:m().int().positive(),timestamp:wt,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()}),Iz=d({schemaVersion:x("openpond.policyOptimizationMetric.v1"),method:k(["grpo","ppo"]),step:m().int().nonnegative(),timestamp:wt,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()}),_z=d({schemaVersion:x("openpond.managedTrainingRunEvidence.v2"),provider:ge,providerRunId:ge,state:ge,progress:d({targetOptimizerSteps:m().int().nonnegative(),committedOptimizerSteps:m().int().nonnegative(),skippedOptimizerSteps:m().int().nonnegative()}),reward:d({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:d({inputTokens:m().int().nonnegative(),outputTokens:m().int().nonnegative(),environmentExecutions:m().int().nonnegative()}),resource:d({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:d({totalUsd:m().nonnegative().nullable()}),checkpoint:d({id:ge,policyVersion:m().int().nonnegative(),sha256:tt.nullable(),sizeBytes:m().int().nonnegative().nullable()}).nullable(),movement:d({adapterDeltaNorm:m().nonnegative().nullable()}),evaluations:v(d({reference:d({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:d({state:ge.nullable(),artifactId:ge.nullable()}),syncedAt:wt}),ub=d({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()}),mb=d({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(d({graderId:ge,score:m().min(0).max(1).nullable(),passed:j(),feedback:o().trim().max(2e4).nullable()})).max(1e3)}),Cz=d({taskId:ge,input:Se(o(),Ie()),baseOutput:Se(o(),Ie()).nullable(),trainedOutput:Se(o(),Ie()).nullable(),baseGrade:mb.nullable(),trainedGrade:mb.nullable()}),Rz=d({schemaVersion:x("openpond.trainingEvaluationSummary.v1"),jobId:ge,tasksetId:ge,base:ub,trained:ub,meanScoreDelta:m().min(-1).max(1).nullable(),examples:v(Cz).max(1e6)});d({schemaVersion:x("openpond.trainingRunDetail.v1"),job:Iw,events:v(kz),stepMetrics:v(wz),policyMetrics:v(Iz).default([]),managedEvidence:_z.nullable().default(null),evaluation:Rz.nullable(),generatedAt:wt});const Pz=d({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:wt,metadata:Wc}),Tz=d({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:wt,frozenEvaluationArtifactId:ge.nullable(),promotable:j(),pinned:j().default(!1),status:k(["imported","rejected"]).default("imported"),rejectedAt:wt.nullable().default(null),rejectionReason:o().trim().min(1).max(5e3).nullable().default(null),chatConfiguration:vw.default(HL),managedServing:UL.nullable().default(null)}),Az=k(["chat_manual","agent","extension","authoring_optimizer"]),Ez=d({schemaVersion:x("openpond.modelBinding.v1"),id:ge,profileId:ge,role:Az,roleTargetId:ge,modelArtifactLineageId:ge,tasksetId:ge,evaluationArtifactId:ge.nullable(),status:k(["active","rolled_back"]),priorBindingId:ge.nullable(),rollbackTargetBindingId:ge.nullable(),promotedBy:ge,promotedAt:wt,rolledBackAt:wt.nullable(),metadata:Wc});d({schemaVersion:x("openpond.trainingActivity.v1"),profileId:ge,active:j(),activeCounts:d({jobs:m().int().nonnegative(),creations:m().int().nonnegative(),minerRuns:m().int().nonnegative(),datasetImports:m().int().nonnegative()}),revision:tt,generatedAt:wt});d({schemaVersion:x("openpond.tasksetOperationalState.v1"),tasksetId:ge,attempts:v(pD),artifacts:v(fD),grades:v(gD),evaluationResults:v(s2).default([]),generatedAt:wt});const jz=d({schemaVersion:x("openpond.trainingState.v1"),profileId:ge,sources:v(gk),creations:v(Qk),tasksetDrafts:v(Fa).default([]),tasksets:v(Rc),benchmarkRuns:v(Hm()).default([]),benchmarkComparisons:v(Hm()).default([]),datasetImports:v(OD).default([]),datasetArtifacts:v(_2).default([]),graderAuditReports:v(vD),evaluationResults:v(Hm()).default([]),candidates:v(Zk),minerConfig:uu,minerRuns:v(YN).default([]),modelProjects:v(yz).default([]),modelVersions:v(hL).default([]),modelRuns:v(PL).default([]),comparisonSeries:v(iL).default([]),comparisonSeriesEntries:v(pL).default([]),modelCurrencySnapshots:v(jL).default([]),continualBenchIssueReviews:v($L).default([]),continualLearningDailyBatches:v(OL).default([]),rewardModelVersions:v(gL).default([]),rewardModelRuns:v(bL).default([]),modelTasksets:v(Rc).default([]),plans:v(ww),bundles:v(Qh),jobs:v(Iw),artifacts:v(Pz),models:v(Tz),rolloutReceipts:v(oz).default([]),modelBindings:v(Ez).default([]),destinations:v(pz),baseModelCandidates:v(hz).default([]),activityRevision:tt.optional(),generatedAt:wt}),Yh=32e3,Mz=k(["steer","message","followup","queued","result"]),Oz=k(["pending","included","resolved","cancelled","rejected"]),Xh=d({id:o().min(1),sequence:m().int().nonnegative(),sessionId:o().min(1),senderSessionId:o().min(1).nullable(),senderKind:k(["user","task","runtime","ponder"]),kind:Mz,body:o().trim().min(1).max(Yh),payload:Se(o(),Ie()).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:Oz,revision:m().int().positive(),createdAt:o(),updatedAt:o(),error:o().nullable()}).strict();d({expectedTurnId:o().trim().min(1),idempotencyKey:o().trim().min(1).max(200),prompt:o().trim().min(1).max(Yh)}).strict();pt("action",[d({action:x("resume"),expectedRevision:m().int().positive()}).strict(),d({action:x("cancel"),expectedRevision:m().int().positive()}).strict(),d({action:x("edit"),expectedRevision:m().int().positive(),body:o().trim().min(1).max(Yh)}).strict(),d({action:x("steer"),expectedRevision:m().int().positive(),expectedTurnId:o().trim().min(1)}).strict()]);const $z=d({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();d({sessionId:o(),activeTurnId:o().nullable(),acceptingInput:j(),paused:j(),inputs:v(Xh),waits:v($z)});var Cd=Ye.shape.id,Nz=d({schemaVersion:x("openpond.modelBatchReviewInspection.v1"),packageHash:o().regex(/^[a-f0-9]{64}$/),definition:Xd,binding:wh,evidence:v(eu).min(1).max(1e4),decisions:v(Rh).min(1).max(1e4)}).strict(),E8=d({schemaVersion:x("openpond.modelBatchReviewRequest.v1"),operationId:Cd,modelId:Cd,expectedModelRevision:m().int().positive(),tasksetRef:Ye,rewardBindingRef:Ye.nullable(),definition:d({name:o().trim().min(1).max(500).optional(),instructions:o().trim().min(1).max(2e4).optional(),inputSchema:Pt.optional(),outputSchema:Pt.optional(),requiredOutputs:Xd.shape.requiredOutputs}).strict(),examples:v(d({evidence:Ye,input:Pt.optional(),expected:Pt.nullable().optional(),evaluatorContext:Pt.nullable().optional(),proposedTarget:Pt.nullable().optional()}).strict()).max(1e4)}).strict(),Dz=d({schemaVersion:x("openpond.modelBatchReviewReceipt.v1"),operationId:Cd,modelId:Cd,source:Ch,evidence:v(eu).min(1).max(1e4),proposals:v(Mx).max(1e4)}).strict();const Lz={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"})},zz={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?${Hz(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 Hz(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 Uz={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 s=new URLSearchParams({path:n});a.offsetBytes!==void 0&&s.set("offsetBytes",String(a.offsetBytes)),a.maxBytes!==void 0&&s.set("maxBytes",String(a.maxBytes));const r=await L(e,`/v1/sandboxes/${encodeURIComponent(t)}/files?${s.toString()}`);return{...r,contents:r.file.isBinary?"":aC(r.file.contentsBase64)}}},qz={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)})},Bz={connectedAppStatus:(e,t={})=>{const n=Xg(t);return n.set("status",t.status??"all"),L(e,`/v1/connected-apps/status${n.size>0?`?${n.toString()}`:""}`)},integrationConnections:(e,t={})=>{const n=Xg(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})})},Fz={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:s,...r}=n;return L(e,`/v1/sandbox-projects/${encodeURIComponent(t)}/source?${a.toString()}`,{method:"POST",body:JSON.stringify(r)})},archiveSandboxProject:(e,t,n)=>{const a=new URLSearchParams({teamId:n.teamId});return 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)})},Vz={sandbox:(e,t)=>L(e,`/v1/sandboxes/${encodeURIComponent(t)}`)},Kz={...Bz,...Fz,...Vz,...qz,...Uz},Wz={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 s=new URLSearchParams;return a.beforeSequence!=null&&s.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&s.set("limit",String(a.limit)),L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages${s.size?`?${s}`:""}`)},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,s)=>L(e,`/v1/communities/${encodeURIComponent(t)}/channels/${encodeURIComponent(n)}/messages/${encodeURIComponent(a)}`,{method:"PATCH",body:JSON.stringify({body:s})}),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`)},eg="openpond-app-server-url",Tc="openpond-app-token",Gz=750;function _w(){return window.location.protocol!=="http:"&&window.location.protocol!=="https:"?null:window.location.origin&&window.location.origin!=="null"?window.location.origin:null}function sf(e){const t=e.getItem(eg)?.trim(),n=e.getItem(Tc)?.trim();return t&&n?{serverUrl:t,token:n}:null}function Rd(e){if(!e)return null;try{const t="__openpond_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function Eo(e,t){e.setItem(eg,t.serverUrl),e.setItem(Tc,t.token)}function pb(e,t){const n=sf(e);n?.serverUrl!==t.serverUrl||n.token!==t.token||(e.removeItem(eg),e.removeItem(Tc))}function Zz(){const e=window.__OPENPOND_WEB_CONNECTION__,t=e?.serverUrl?.trim(),n=e?.token?.trim();return t&&n?{serverUrl:t,token:n}:null}function Jz(){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()||_w();return!a||!n?null:{serverUrl:a,token:n}}function Qz(){window.location.hash&&window.history.replaceState(null,"",`${window.location.pathname}${window.location.search}`)}function jl(e,t){t&&(e.some(n=>n.serverUrl===t.serverUrl&&n.token===t.token)||e.push(t))}function Yz(){const e=[],t=Rd(window.sessionStorage),n=Rd(window.localStorage),a=_w(),s=t?.getItem(Tc)??n?.getItem(Tc);return jl(e,null),jl(e,a&&s?{serverUrl:a,token:s.trim()}:null),jl(e,t?sf(t):null),jl(e,n?sf(n):null),e}async function ep(e){const t=new AbortController,n=window.setTimeout(()=>t.abort(),Gz);try{const a=await fetch(`${e}/health`,{signal:t.signal}),s=await a.json().catch(()=>null);return a.ok&&s?.server==="openpond-app-server"}catch{return!1}finally{window.clearTimeout(n)}}async function Xz(){if(window.openpond)return window.openpond.getConnection();const e=Rd(window.sessionStorage),t=Rd(window.localStorage),n=Jz();if(n&&await ep(n.serverUrl))return t&&Eo(t,n),e&&Eo(e,n),Qz(),{...n,platform:navigator.platform};const a=Zz();if(a&&await ep(a.serverUrl))return t&&Eo(t,a),e&&Eo(e,a),{...a,platform:navigator.platform};const s=Yz();for(const r of s){if(await ep(r.serverUrl))return t&&Eo(t,r),e&&Eo(e,r),{...r,platform:navigator.platform};e&&pb(e,r),t&&pb(t,r)}throw new Error("No reachable OpenPond app server. Start `openpond ui` again and open the full printed URL.")}const Z={...Wz,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 s=new URLSearchParams({teamId:t});return a.beforeSequence!=null&&s.set("beforeSequence",String(a.beforeSequence)),a.limit!=null&&s.set("limit",String(a.limit)),L(e,`/v1/team-chat/threads/${encodeURIComponent(n)}?${s.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=fb(t),a=n.size?`?${n.toString()}`:"";return L(e,`/v1/usage${a}`)},usageRecords:(e,t={})=>{const n=fb(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 s=new URLSearchParams({limit:"25"});return a&&s.set("cursor",a),L(e,`/v1/training/jobs/${encodeURIComponent(t)}/evaluations/${encodeURIComponent(n.id)}/tasks?${s}`)},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 s=a.size?`?${a.toString()}`:"";return L(e,`/v1/local-agent-schedules/${encodeURIComponent(t)}/runs${s}`)},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 s=a.size?`?${a.toString()}`:"";return L(e,`/v1/providers/${encodeURIComponent(t)}/models${s}`)},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 s=a.size?`?${a.toString()}`:"";return L(e,`/v1/codex-history/${encodeURIComponent(t)}${s}`)},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}),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`),...Lz,...Kz,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 s=a.toString()?`?${a.toString()}`:"";return L(e,`/v1/projects/${encodeURIComponent(t)}/cloud-source/preview${s}`)},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({})}),...zz,resolveApproval:(e,t,n)=>L(e,`/v1/approvals/${t}`,{method:"POST",body:JSON.stringify(n)})};function fb(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 eH=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),tH=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),hb=e=>{const t=tH(e);return t.charAt(0).toUpperCase()+t.slice(1)},Cw=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),nH=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var aH={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 sH=h.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:s="",children:r,iconNode:i,...c},u)=>h.createElement("svg",{ref:u,...aH,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:Cw("lucide",s),...!r&&!nH(c)&&{"aria-hidden":"true"},...c},[...i.map(([l,p])=>h.createElement(l,p)),...Array.isArray(r)?r:[r]]));const We=(e,t)=>{const n=h.forwardRef(({className:a,...s},r)=>h.createElement(sH,{ref:r,iconNode:t,className:Cw(`lucide-${eH(hb(e))}`,`lucide-${e}`,a),...s}));return n.displayName=hb(e),n};const rH=[["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"}]],oH=We("activity",rH);const iH=[["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"}]],cH=We("archive-restore",iH);const lH=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],dH=We("arrow-left",lH);const uH=[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]],Rw=We("bookmark",uH);const mH=[["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"}]],Pw=We("bookmark-x",mH);const pH=[["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"}]],gb=We("book-open-text",pH);const fH=[["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"}]],hH=We("bot",fH);const gH=[["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"}]],Ml=We("boxes",gH);const vH=[["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"}]],Tw=We("calendar-clock",vH);const bH=[["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"}]],Aw=We("chart-column-stacked",bH);const yH=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],cs=We("check",yH);const SH=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],td=We("circle-check",SH);const xH=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],mr=We("chevron-down",xH);const kH=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],pr=We("chevron-right",kH);const wH=[["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"}]],Pd=We("circle-alert",wH);const IH=[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]],hu=We("cloud",IH);const _H=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],CH=We("credit-card",_H);const RH=[["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"}]],PH=We("download",RH);const TH=[["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"}]],tp=We("external-link",TH);const AH=[["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"}]],Ew=We("file-output",AH);const EH=[["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"}]],tg=We("file-text",EH);const jH=[["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"}]],jw=We("folder",jH);const MH=[["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"}]],ng=We("folder-git-2",MH);const OH=[["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"}]],$H=We("git-branch",OH);const NH=[["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"}]],DH=We("github",NH);const LH=[["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"}]],Mw=We("earth",LH);const zH=[["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"}]],HH=We("circle-question-mark",zH);const UH=[["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M9 19h6",key:"456am0"}]],qH=We("list-filter",UH);const BH=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ag=We("loader-circle",BH);const FH=[["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"}]],VH=We("maximize-2",FH);const KH=[["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"}]],gu=We("message-square",KH);const WH=[["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"}]],Zc=We("ellipsis",WH);const GH=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Ow=We("panel-left",GH);const ZH=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],rf=We("panel-right",ZH);const JH=[["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"}]],sg=We("pin",JH);const QH=[["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"}]],rg=We("pin-off",QH);const YH=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],XH=We("plus",YH);const eU=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],tU=We("power",eU);const nU=[["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"}]],$w=We("refresh-cw",nU);const aU=[["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"}]],sU=We("rotate-ccw",aU);const rU=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],oU=We("search",rU);const iU=[["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"}]],Nw=We("settings",iU);const cU=[["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"}]],og=We("shapes",cU);const lU=[["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"}]],vb=We("shield",lU);const dU=[["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"}]],vu=We("square-pen",dU);const uU=[["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"}]],Dw=We("square-terminal",uU);const mU=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],bb=We("user-round",mU);const pU=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Jc=We("x",pU);const fU=[["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"}]],ig=We("inbox",fU);const hU=[["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"}]],gU=We("list",hU);const vU=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],bU=We("terminal",vU);function yU({platform:e}){return!bu()||Lw(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:()=>{np("minimize")},children:g.jsx(mr,{size:14})}),g.jsx("button",{type:"button",className:"window-control maximize",title:"Maximize",onClick:()=>{np("toggleMaximize")},children:g.jsx(VH,{size:12})}),g.jsx("button",{type:"button",className:"window-control close",title:"Close",onClick:()=>{np("close")},children:g.jsx(Jc,{size:13})})]})}function Lw(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")}function bu(){if(typeof window>"u")return!1;const e=window.openpond;return!!(e?.minimizeWindow||e?.toggleMaximizeWindow||e?.closeWindow)}async function np(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 SU=[["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"}]],zw=We("house",SU);const xU=[["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"}]],kU=We("panels-top-left",xU);function wU({value:e,options:t,disabled:n,compact:a,className:s,icon:r,placement:i="bottom",label:c,tooltip:u,searchable:l=!1,floating:p=!1,onChange:f}){const[y,b]=h.useState(!1),[I,C]=h.useState(""),P=h.useRef(null),[_,M]=h.useState();h.useLayoutEffect(()=>{if(!y||!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)}},[y,p]);const A=t.find(w=>w.value===e)??t[0],T=I.trim().toLowerCase(),S=T?t.filter(w=>[w.label,w.shortLabel,w.description].some(R=>R?.toLowerCase().includes(T))):t;return h.useEffect(()=>{if(!y){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)}},[y]),g.jsxs("div",{className:`dropdown-select ${s??""} ${a?"compact":""} ${i==="top"?"open-up":""}`,"data-tooltip":u,ref:P,children:[g.jsxs("button",{type:"button",className:`dropdown-trigger ${y?"active":""}`,disabled:n,"aria-label":c,"aria-haspopup":"menu","aria-expanded":y,onClick:()=>b(w=>!w),children:[r,g.jsx("span",{children:A?.shortLabel??A?.label??e}),g.jsx(mr,{size:14})]}),y&&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,S.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(XH,{size:13}):null,g.jsx("span",{children:w.label})]}),w.description&&g.jsx("small",{children:w.description})]},w.value)),S.length?null:g.jsx("div",{className:"dropdown-empty",children:"No matches"})]})]})}const j8=[{value:"chat",label:"Chat"},{value:"work",label:"Work"}];function Hw(e){return e==="chat"?"New chat":"New task"}const of=["get-started","home","inbox","models","datasets","graders","experiments","tasks","tasksets","labeling","rewards","evaluations","runs","versions","serving"],IU={"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"},_U={tasks:["drafts"],tasksets:["drafts","formats","batches"],rewards:["scorers","combined"],evaluations:["results","review","comparisons"],runs:["series","new"]},CU={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 ka(e="models",t=null,n={}){return e==="evaluations"&&n.collection==="review"?ka("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 cg(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]&&!of.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 s=n.shift(),r=s??"models";if(!of.includes(r)||s==="models"||a&&r==="get-started")return null;let i=r==="evaluations"?"results":"default";if(_U[r]?.includes(n[0]))i=n.shift();else if(r==="evaluations"&&n.length)return null;if(r==="experiments"&&n[0]==="history")return null;const c=n.shift()??null,u=n.shift()??null;if(n.length||u&&!c||(r==="models"||r==="get-started"||r==="home")&&c)return null;if(i==="drafts"||i==="new"){if(!c||u)return null}else if(i!=="series"){if(["review","formats","batches","comparisons","scorers","combined"].includes(i)){if(u)return null}else if(u&&!CU[r]?.includes(u))return null}if(r==="serving"&&u)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&&(r!=="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 y=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&&(r!=="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(r);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&&(r!=="labeling"&&(r!=="evaluations"||i!=="review")||!_.trim()||_.length>500)||l.has("dataset")&&(r!=="datasets"||!c||l.get("dataset")!=="release"))return null;const M=["home","inbox","datasets","graders","experiments"].includes(r),A=r==="runs"&&!!(c?.startsWith("hosted-run:")||c?.startsWith("hosted-policy:")),T=l.get("location");if(T!==null&&(!M||!["local","hosted"].includes(T)))return null;const S=l.get("kind");if(S!==null&&(r!=="experiments"||!c||T==="local"||S!=="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)||r!=="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(r==="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:ka(r,z,{...y?{reviewSource:y}:{},collection:i,resourceId:c,detailTab:u,query:$,after:V,...S?{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 yu(e){const t=[e.area==="console"?"/console":"/models"];if(e.modelId&&t.push(encodeURIComponent(e.modelId)),e.page==="evaluations"&&e.collection==="review")return yu(ka("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 RU(e,t){return ka(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 M8(e,t,n=null){return{...e,resourceId:t,detailTab:n,after:null,...t!==e.resourceId?{revision:void 0,contentHash:void 0}:{}}}const Td=new Set,cf=new Set,PU=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"]),lf={apps:"/apps",outputs:"/outputs",projects:"/projects",scheduled:"/workflows","get-started":"/get-started",team:"/team",community:"/community"};let df=!1,uf="",nd=null,Uw=null,Ac="",La=0,Gi=null,hc=!1,ap=null,ad=!1;function lg(e){const t=cg(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&&PU.has(n[1])){const s=dg(new URLSearchParams(e.search??"").get("returnTo"));return{kind:"settings",section:n[1],...s?{returnTo:s}:{}}}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(lf).find(s=>lf[s]===e.pathname);return a?{kind:"view",view:a}:null}function qw(e){if(e.kind==="models")return yu(e.route);if(e.kind==="models_unavailable")return`${e.pathname}${e.search}`;if(e.kind==="settings"){const t=dg(e.returnTo??null);return`/settings/${e.section}${t?`?${new URLSearchParams({returnTo:t})}`:""}`}return e.kind==="chat"?e.sessionId?`/chat/${encodeURIComponent(e.sessionId)}`:"/chat/new":lf[e.view]}function TU(e){const t=e?.kind==="settings"?dg(e.returnTo??null):null;if(t){const n=new URL(t,"https://local.openpond.invalid"),a=cg(n);if(a)return{kind:"models",route:a}}return{kind:"chat",sessionId:null}}function dg(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=cg(t);return n?yu(n):null}function Qc(){return`${window.location.pathname}${window.location.search}`}function ug(){if(typeof window>"u")return;const e=df?Ac:Qc();e!==uf&&(uf=e,nd=lg(new URL(e,window.location.origin)),Uw=nd?.kind==="models"?nd.route:null)}function Bw(){uf="",ug();for(const e of cf)e()}async function mg(e){if(ad)return!1;ad=!0;try{for(const t of[...Td].reverse())if(!await t(e))return!1;return!0}finally{ad=!1}}function pg(e){return{...window.history.state,openpondNavigationIndex:e}}async function AU(){const e=Qc(),t=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:La-1;if(Gi&&t===La){const a=Gi;Gi=null,a();return}if(ap===t||Td.size===0){ap=null,Ac=e,La=t,window.history.replaceState(pg(La),"",e),Bw();return}if(t===La)return;if(hc||ad){Gi??=()=>{},window.history.go(La-t);return}hc=!0;const n=t-La;try{await new Promise(a=>{Gi=a,window.history.go(-n)}),await mg(e)&&(ap=t,window.history.go(n))}finally{hc=!1}}function fg(){if(df||typeof window>"u")return;const e=lg(window.location);Ac=e?qw(e):Qc(),La=typeof window.history.state?.openpondNavigationIndex=="number"?window.history.state.openpondNavigationIndex:0,window.history.replaceState(pg(La),"",Ac),window.addEventListener("popstate",AU),df=!0}function Fw(e){return cf.add(e),fg(),()=>{cf.delete(e)}}function O8(e){return Td.add(e),fg(),()=>{Td.delete(e)}}async function $8(e){!hc&&await mg(Qc())&&e()}function EU(){return h.useSyncExternalStore(Fw,()=>(ug(),Uw),()=>null)}function jU(){return h.useSyncExternalStore(Fw,()=>(ug(),nd),()=>null)}async function Dt(e,t="push"){if(typeof window>"u"||(fg(),hc))return!1;if(e.kind==="settings"&&!e.returnTo){const a=lg(window.location),s=a?.kind==="models"?yu(a.route):a?.kind==="settings"?a.returnTo:void 0;s&&(e={...e,returnTo:s})}const n=qw(e);return Qc()===n?!0:await mg(n)?(t==="push"&&La++,window.history[t==="replace"?"replaceState":"pushState"](pg(La),"",n),Ac=n,Bw(),!0):!1}function Br(e,t="push"){return Dt({kind:"models",route:e},t)}function MU({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 Dt({kind:"chat",sessionId:null})&&t(null)},children:[g.jsx("span",{className:"conversation-source-icon","aria-hidden":"true",children:g.jsx(vu,{size:18})}),g.jsx("span",{children:Hw(e)})]})})}function OU({productArea:e="chat",setSectionMenuOpen:t,setSelectedAppId:n,setSelectedProjectId:a,setSelectedSessionId:s,setView:r,view:i,modelProjects:c=[],modelTrainingActivityByProjectId:u={}}){const l=EU(),p=l?.modelId??null,f=l?.page??"models";function y(){n(null),a(null),s(null),t(null)}async function b(_){await Br(ka(_,["home","inbox","datasets","graders","experiments"].includes(_)?null:p,{...e==="console"?{area:"console"}:{},...l?.projectId!==void 0?{projectId:l.projectId}:{}}))&&(y(),r("labs"))}async function I(_){await Br(RU(l??ka(),_||null))&&(y(),r("labs"))}async function C(_){await Dt({kind:"view",view:_})&&(y(),r(_))}const P=p?u[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(wU,{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(_)}})]}),of.filter(_=>e==="console"?["home","inbox","datasets","graders","experiments"].includes(_):_!=="home"&&_!=="tasksets"&&_!=="evaluations").map(_=>{const M={"get-started":Ml,home:zw,inbox:ig,models:oH,datasets:Ml,graders:vb,experiments:td,tasks:Ml,tasksets:Ml,labeling:td,rewards:vb,evaluations:td,runs:Aw,versions:$H,serving:hu}[_];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:IU[_]}),_==="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(Tw,{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(Ew,{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(og,{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(ng,{size:18}),g.jsx("span",{children:"Projects"})]})]}):null]})}const Vw=zm({chatMode:k(["chat","work"]).optional(),sidebarPresentation:k(["grouped","inbox"]).optional(),notificationMode:k(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:j().optional(),sidebarVisibility:zm({showCodexChats:j(),onlyRunningTasks:j()}).optional(),scheduledWorkView:k(["calendar","list"]).optional(),editorControlsVisible:j().optional(),voiceNoticeAcknowledged:j().optional(),lessonProgress:Se(o().min(1).max(200),zm({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()}),mf={"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"},pf=new Set;let gc=null,Us=null,Ha={},Ec={},sp=!1,sd=0,Xo=null,yb=0;const $U="openpond-client-choices-changed";function hg(){pf.forEach(e=>e()),typeof window<"u"&&window.dispatchEvent(new Event($U))}function NU(){return Xo}function DU(e){return pf.add(e),()=>{pf.delete(e)}}function ui(e){const t=h.useRef(e);t.current=e,h.useEffect(()=>DU(()=>t.current()),[])}async function Sb(e){const t=++yb,n=await L(e,"/v1/configuration");if(n.clientState?.revision===null){const s=LU();if(Object.keys(s.patch).length){n.clientState=await L(e,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n.clientState.owner,patch:s.patch,importOnly:!0})});for(const r of s.keys)try{window.localStorage.removeItem(r)}catch{}}}if(t!==yb)return;const a=gc?.serverUrl!==e.serverUrl||gc?.token!==e.token||Us?.owner!==n.clientState?.owner;a&&(sd++,Ha={},Ec={},Xo=null),gc=e,(a||(n.clientState?.revision??0)>=(Us?.revision??0))&&(Us=n.clientState),hg()}async function gg(){if(sp||!gc||!Us||!Object.keys(Ha).length)return;sp=!0;const e=Ha,t=gc,n=Us.owner,a=sd;Ha={},Ec=e;try{const s=await L(t,"/v1/configuration",{method:"POST",body:JSON.stringify({action:"client-state",owner:n,patch:e})});a===sd&&(Us=s,Xo=null)}catch(s){a===sd&&(Ha={...e,...Ha},Xo=`Preference changes have not been saved. ${s instanceof Error?s.message:String(s)}`)}finally{Ec={},sp=!1,hg(),!Xo&&Object.keys(Ha).length&&gg()}}function N8(){Xo=null,gg()}const eo={getItem(e){const t=mf[e];if(!t)return null;const n={...Us?.value,...Ec,...Ha}[t];return n===void 0?null:typeof n=="string"?n:JSON.stringify(n)},setItem(e,t){if(!Us)return;const n=mf[e];if(!n)throw new Error("Unregistered client preference.");let a;try{a=JSON.parse(t)}catch{a=t}const s=Vw.parse({[n]:a});JSON.stringify({...Us.value,...Ec,...Ha}[n])!==JSON.stringify(s[n])&&(Ha={...Ha,...s},hg(),gg())}};function LU(){const e={},t=[];if(typeof window>"u")return{patch:e,keys:t};for(const[n,a]of Object.entries(mf))try{const s=window.localStorage.getItem(n);if(s===null)continue;let r;try{r=JSON.parse(s)}catch{r=s}const i=Vw.safeParse({[a]:r});i.success&&(Object.assign(e,i.data),t.push(n))}catch{}return{patch:e,keys:t}}function Kw(e){return e.replace(/\s+\(default\)$/i,"").replace(/^(?:openai|anthropic|google|xai|deepseek|qwen|meta-llama)\//i,"").replace(/^gpt-/i,"GPT-")}const rd=5,$n=15,ff=10,Ct={defaultChatProvider:Fr,subagents:pE(),codexPermissionMode:nh,codexReasoningEffort:ah,openPondCommandAccessMode:Wd,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:""}}}},D8={activeTemplateId:"default",customized:!1,soul:"",soulPath:null,updatedAt:null,templates:[]},Ww=[{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"}],rp=[{value:"openpond",label:"OpenPond Chat"},{value:"codex",label:"OpenAI Codex",description:"Codex login"}],zU=["openai","xai","openrouter","deepseek","zai","moonshot","together","groq","custom-openai-compatible"],HU=["openpond","codex","claude-code","grok-build","opencode",...zU],Gw=new Set(HU),Zw=[{value:th,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"}],L8=[{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."}],hf=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High",shortLabel:"Extra High"}],UU=[{value:"off",label:"Off"},...hf,{value:"max",label:"Max"}],z8=[{value:"ask",label:"Ask",description:"Ask before running shell commands."},{value:"full-access",label:"Full access",description:"Run shell commands without approval prompts."}],H8=[{value:"auto",label:"Auto",description:"Use installed language servers when available."},{value:"off",label:"Off",description:"Disable editor language servers."}],U8=[{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 vg(e){return e.kind==="local"}function qU(e){return e.kind==="cloud"}function it(e,t){return`${e}:${t}`}function Jw(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),s=t.slice(n+1);return(a==="local"||a==="cloud")&&s?{kind:a,id:s}:{kind:"local",id:t}}function Ur(e){return`${e.type}:${e.id}`}function Ad(e){const t=e.currentTarget.getBoundingClientRect();return e.clientY<t.top+t.height/2?"before":"after"}function Ed(e,t,n,a="before"){if(t===n)return e;const s=e.filter(i=>i!==t),r=s.indexOf(n);return r===-1?e:(s.splice(a==="after"?r+1:r,0,t),s)}function xb(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function BU(e,t){if(!t)return e;const n=new Map(e.map(r=>[r.key,r])),a=t.map(r=>n.get(r)).filter(r=>!!r),s=new Set(a.map(r=>r.key));return[...a,...e.filter(r=>!s.has(r.key))]}function bg(e,t){return e?.statuses?.[t]??null}function Qw(e,t){return e?.providers?.[t]??null}function yg(e,t){return e?.modelCaches?.[t]??null}function FU(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:Kw(e.displayName||e.id),description:t.join(" · ")||void 0}}function VU(e){return e==="openpond"?Ww:e==="codex"||e==="openai"?Zw:[]}function KU(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 q8(e){return Gw.has(e)}function gf(e,t={}){if(!e)return t.localOnly,rp;const n=t.includeUnavailable??!1,a=t.enabledOnly??!1,s=[];for(const r of Jf){if(!["openpond","codex","openai","claude-code","grok-build","opencode"].includes(r)||!Gw.has(r)||t.localOnly&&r==="openpond")continue;const i=bg(e,r);i&&(!n&&(r==="codex"&&!i.available&&!i.credential.connected||r!=="openpond"&&r!=="codex"&&!i.enabled)||a&&r!=="openpond"&&!i.enabled||a&&r==="codex"&&!i.available&&!i.credential.connected||s.push({value:r,label:r==="openpond"?"OpenPond Chat":i.displayName,description:r==="openpond"?void 0:i.available?"Connected":i.credential.connected?"Configured":i.routing.localByok?"Set up key":i.enabled?"Enabled":void 0}))}return s.length>0?s:rp}function jc(e,t){const a=(yg(t,e)?.models??[]).filter(c=>e!=="openpond"||c.id!==si).map(FU),s=Qw(t,e),r=[...s?.modelOverrides??[],s?.defaultModel].filter(c=>!!c?.trim()&&(e!=="openpond"||c!==si)).map(c=>({value:c,label:Kw(c)})),i=e==="openpond"&&a.length>0?[]:VU(e);return KU([...a,...r,...i])}function Yw(e,t,n){if(e!=="openpond")return hf;const a=yg(n,e)?.models.find(r=>r.id===t)?.capabilities;if(!a?.reasoningEfforts.length)return hf;const s=new Set(a.reasoningEfforts);return UU.filter(r=>s.has(r.value))}function WU(e,t,n){const a=Yw(e,t,n),s=e==="openpond"&&(t==="gpt-6-luna"||t==="gpt-6-sol"||t==="claude-opus-5-5")?"medium":"high";return a.some(r=>r.value===s)?s:a[0]?.value??"high"}function GU(e,t,n,a){return Yw(e,t,a).some(s=>s.value===n)?n:WU(e,t,a)}function ZU(e,t,n){if(e==="codex"||e==="openai")return!0;const a=t.trim();if(!a)return!1;const s=yg(n,e)?.models.find(r=>r.id===a);return s?!!s.capabilities.reasoning:jc(e,n).some(r=>r.value===a&&/\breasoning\b/i.test(r.description??""))}function jd(e,t){const n=Qw(t,e)?.defaultModel?.trim();if(n)return n;const a=bg(t,e)?.defaultModel?.trim();if(a)return a;const s=jc(e,t)[0]?.value?.trim();return s||(e==="codex"?th:e==="openpond"?si:"")}function Sr(e,t,n){const a=t?.trim();if(a&&["opencode","grok-build","claude-code"].includes(e))return a;if(e==="codex"&&(a==="codex-default"||a==="gpt-5.5"))return th;const s=jc(e,n);return a&&s.some(r=>r.value===a)||a&&e!=="codex"&&s.length===0&&!n?a:jd(e,n)}function Xw(e,t){const n=e.modelRef?.providerId??e.provider;return{provider:n,model:Sr(n,e.modelRef?.modelId,t)}}function Sg(e,t,n){return Sr(e,t,n)||void 0}function Na(e,t,n){const a=Sg(e,t,n);return a?{providerId:e,modelId:a}:void 0}function kb(e){return e==="full-access"?{approvalPolicy:"never",sandbox:"danger-full-access"}:{approvalPolicy:"on-request",sandbox:"workspace-write"}}function ya(e){const t=e?.defaultChatProvider??Ct.defaultChatProvider;return{defaultChatProvider:t,defaultChatModel:Sr(t,e?.defaultChatModel),subagents:Sc.parse(e?.subagents??Ct.subagents),codexPermissionMode:e?.codexPermissionMode??Ct.codexPermissionMode,codexReasoningEffort:e?.codexReasoningEffort??Ct.codexReasoningEffort,openPondCommandAccessMode:e?.openPondCommandAccessMode??Ct.openPondCommandAccessMode,defaultBranchPrefix:eI(e?.defaultBranchPrefix),defaultNewProjectDirectory:e?.defaultNewProjectDirectory??Ct.defaultNewProjectDirectory,defaultTeamId:e?.defaultTeamId?.trim()||null,advancedWorkspaceControls:e?.advancedWorkspaceControls??Ct.advancedWorkspaceControls,steerActiveResponses:e?.steerActiveResponses??Ct.steerActiveResponses,contextCompaction:{autoEnabled:e?.contextCompaction?.autoEnabled??Ct.contextCompaction.autoEnabled,triggerPercent:e?.contextCompaction?.triggerPercent??Ct.contextCompaction.triggerPercent,summaryModel:e?.contextCompaction?.summaryModel??Ct.contextCompaction.summaryModel},training:{defaultModelRef:e?.training?.defaultModelRef??Ct.training.defaultModelRef,creationMode:e?.training?.creationMode??Ct.training.creationMode,autoApproveEvidence:e?.training?.autoApproveEvidence??Ct.training.autoApproveEvidence},sidebarWidth:e?.sidebarWidth??Ct.sidebarWidth,diffPanelWidth:e?.diffPanelWidth??Ct.diffPanelWidth,sidebarSectionsCollapsed:{pinned:e?.sidebarSectionsCollapsed?.pinned??Ct.sidebarSectionsCollapsed.pinned,projects:e?.sidebarSectionsCollapsed?.projects??Ct.sidebarSectionsCollapsed.projects,cloudProjects:e?.sidebarSectionsCollapsed?.cloudProjects??Ct.sidebarSectionsCollapsed.cloudProjects,chats:e?.sidebarSectionsCollapsed?.chats??Ct.sidebarSectionsCollapsed.chats,savedForLater:e?.sidebarSectionsCollapsed?.savedForLater??Ct.sidebarSectionsCollapsed.savedForLater},editor:{languageServers:e?.editor?.languageServers??Ct.editor.languageServers,diagnosticsWhileEditing:e?.editor?.diagnosticsWhileEditing??Ct.editor.diagnosticsWhileEditing,checkOnSave:e?.editor?.checkOnSave??Ct.editor.checkOnSave,languages:{typescript:{mode:e?.editor?.languages?.typescript?.mode??Ct.editor.languages.typescript.mode,customCommand:e?.editor?.languages?.typescript?.customCommand??Ct.editor.languages.typescript.customCommand},python:{mode:e?.editor?.languages?.python?.mode??Ct.editor.languages.python.mode,customCommand:e?.editor?.languages?.python?.customCommand??Ct.editor.languages.python.customCommand},rust:{mode:e?.editor?.languages?.rust?.mode??Ct.editor.languages.rust.mode,customCommand:e?.editor?.languages?.rust?.customCommand??Ct.editor.languages.rust.customCommand}}}}}function eI(e){const t=e?.trim()??Ct.defaultBranchPrefix;if(!t)return"";const a=t.toLowerCase().replace(/[^a-z0-9._/-]+/g,"-").replace(/\/{2,}/g,"/").replace(/^-+/,"").slice(0,48).split("/").map(s=>s.replace(/^-+|-+$/g,"")).filter(Boolean).join("/");return a?`${a}/`:""}function B8(e,t){return e==="openpond"?"OpenPond Chat":bg(t,e)?.displayName??(e==="codex"?"OpenAI Codex":e)}function F8(e,t,n){if(n){const a=jc(n,t).find(s=>s.value===e);if(a)return a.label}if(t)for(const a of Jf){const s=jc(a,t).find(r=>r.value===e);if(s)return s.label}return[...Ww,...Zw].find(a=>a.value===e)?.label??e}function JU(e,t){return t==="chat"?e.filter(n=>n.experience==="chat"):e.filter(n=>n.experience==="work"||n.experience==="development")}function QU(e){return e.experience==="chat"?"Chat":"Work"}const xg="taskDraft";function tI(e){if(e?.experience!=="work")return null;const t=e.metadata?.[xg];if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.prompt;return typeof n=="string"&&n.trim()?n:null}function Mc(e){return tI(e)!==null}function YU(e){return(e.split(/\r?\n/u).map(n=>n.trim()).find(Boolean)||"Task draft").slice(0,64)}function op(e,t,n=new Date().toISOString()){const a={version:1,prompt:t,savedAt:n};return{...e??{},[xg]:a}}function XU(e){const t={...e??{}};return delete t[xg],t}function qo(e){const t=Ol(e.metadata?.trainingTasksetId)??Ol(e.metadata?.tasksetId);return t?{id:t,name:Ol(e.metadata?.trainingTasksetName)??Ol(e.metadata?.tasksetName)??eq(t)}:null}function eq(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 Ol(e){return typeof e=="string"&&e.trim()?e.trim():null}const tq="codex_history_";function Wt(e){return!!e?.startsWith(tq)}function nI(e){const t=[],n=new Set;for(const a of e)for(const s of[a.workspacePath,a.path]){const r=Su(s);if(!r)continue;const i=`${a.id}:${r}`;n.has(i)||(n.add(i),t.push({projectId:a.id,path:r}))}return t.sort((a,s)=>s.path.length-a.path.length)}function nq(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return e.localProjectId;if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return e.workspaceId;if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=aI(e.cwd,n);if(r)return r}if(e.cloudProjectId&&a.has(e.cloudProjectId))return e.cloudProjectId;if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!sI(e))return null;const s=Su(e.cwd);if(!s)return null;for(const r of n)if(kg(s,r.path))return r.projectId;return null}function wb(e,t,n,a=new Set){if(e.localProjectId&&t.has(e.localProjectId))return it("local",e.localProjectId);if(e.workspaceKind==="local_project"&&e.workspaceId&&t.has(e.workspaceId))return it("local",e.workspaceId);if(e.metadata?.workspaceTarget==="hybrid"&&e.cwd){const r=aI(e.cwd,n);if(r)return it("local",r)}if(e.cloudProjectId&&a.has(e.cloudProjectId))return it("cloud",e.cloudProjectId);if(!e.cwd||e.workspaceKind==="sandbox"||e.workspaceKind==="sandbox_template"||e.workspaceKind==="sandbox_app"||!sI(e))return null;const s=Su(e.cwd);if(!s)return null;for(const r of n)if(kg(s,r.path))return it("local",r.projectId);return null}function aI(e,t){const n=Su(e);if(!n)return null;for(const a of t)if(kg(n,a.path))return a.projectId;return null}function sI(e){return e.workspaceKind==="local_project"||e.provider==="codex"||Wt(e.id)}function Su(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 kg(e,t){const n=Ib(e),a=Ib(t);return n===a||n.startsWith(`${a}/`)}function Ib(e){return/^[A-Z]:\//.test(e)?e.toLowerCase():e}const _b=[{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"}],aq=[{value:"recent",label:"Recent first"},{value:"manual",label:"Manual order"}];function ip(e){const t=[];if(e.filter==="done")t.push(...e.doneSessions.filter(s=>!qo(s)));else if(e.filter==="all")t.push(...e.activeSessions.filter(s=>!qo(s)),...e.doneSessions.filter(s=>!qo(s)));else if(e.filter==="tasksets")t.push(...e.activeSessions.filter(s=>Cb(s,e.selectedTasksetId)),...e.doneSessions.filter(s=>Cb(s,e.selectedTasksetId)));else for(const s of e.activeSessions)qo(s)||(e.filter==="active"?s.savedForLater||t.push(s):e.filter==="in_progress"?!s.savedForLater&&e.inProgressSessionIds.has(s.id)&&t.push(s):e.filter==="pinned"?s.pinned&&!s.savedForLater&&t.push(s):e.filter==="saved_for_later"&&s.savedForLater&&t.push(s));const n=t.filter(s=>od(s,{inProgressSessionIds:e.inProgressSessionIds,onlyRunningTasks:e.onlyRunningTasks,showCodexChats:e.showCodexChats})),a=e.previewSessionIds?new Map(e.previewSessionIds.map((s,r)=>[s,r])):null;return e.sort==="recent"?n.sort((s,r)=>Tb(s,r,a)):n.sort((s,r)=>{const i=a?.get(s.id),c=a?.get(r.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 s.order!==r.order?s.order-r.order:Tb(s,r)})}function od(e,t){return t.showCodexChats===!1&&(e.provider==="codex"||Wt(e.id))?!1:!t.onlyRunningTasks||t.inProgressSessionIds.has(e.id)}function Cb(e,t){const n=qo(e);return!!(n&&(!t||n.id===t))}function Rb(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 Pb(e,t,n){const a=new Set(t);let s=0;return e.map(r=>{if(!a.has(r))return r;const i=n[s];return s+=1,i??r})}function Tb(e,t,n=null){const a=Bo(e),s=Bo(t);if(a!==s)return a?-1:1;if(a&&s){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 r=Date.parse(t.updatedAt)-Date.parse(e.updatedAt);return r!==0?r:e.title.localeCompare(t.title)}function Bo(e){return e.pinned&&!e.savedForLater&&!e.archived}const $l={showCodexChats:!0,onlyRunningTasks:!1},rI="openpond.sidebar-task-visibility.v1";function Ab(e=oI()){try{const t=e?.getItem(rI);if(!t)return $l;const n=JSON.parse(t);return{showCodexChats:typeof n.showCodexChats=="boolean"?n.showCodexChats:$l.showCodexChats,onlyRunningTasks:typeof n.onlyRunningTasks=="boolean"?n.onlyRunningTasks:$l.onlyRunningTasks}}catch{return $l}}function Eb(e,t=oI()){try{t?.setItem(rI,JSON.stringify(e))}catch{}}function oI(){return typeof window>"u"?null:eo}function iI(e){return`${e.kind}:${e.id}`}function Oc(e,t){return!!(e&&t&&e.kind===t.kind&&e.id===t.id)}function sq(e){return{kind:"session",id:e}}function rq(e){return{kind:"project",id:e}}function oq(e){return{kind:"draft",id:e}}function iq(e){return e.selectedSessionId?sq(e.selectedSessionId):e.selectedProjectId?rq(e.selectedProjectId):oq(e.selectedAppId?`app:${e.selectedAppId}`:"new-chat")}function cq(e){if(!e.previousScope||e.previousScope.kind!=="draft"||e.activeScope.kind!=="session")return[...e.tabs];if(Oc(e.previousScope,e.activeScope))return[...e.tabs];const t=e.now??Date.now();return e.tabs.map(n=>Oc(n.scope,e.previousScope)?{...n,scope:e.activeScope,updatedAt:t}:n)}function V8(e,t){return e.filter(n=>Oc(n.scope,t))}function K8(e,t){return!!(e&&Oc(e.scope,t))}function lq(e){const t={};for(const n of e){const a=iI(n.scope),s=t[a]??{scope:n.scope,tabCount:0,runningCount:0,failedCount:0,lastExitCode:null,status:"none"};s.tabCount+=1,n.commandStatus==="running"&&(s.runningCount+=1),(n.commandStatus==="failed"||n.status==="error")&&(s.failedCount+=1),n.lastExitCode!==null&&(s.lastExitCode=n.lastExitCode),s.status=uq(s.status,n.status,n.commandStatus),t[a]=s}return t}function dq(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 uq(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 cI(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"],s=pq(e),r=t?.linkedCloudSourceKnown===!1&&!!e.headCommit;return s?a.push(s):r?a.push("upload required"):e.diverged?(e.ahead>0&&a.push(rr("ahead",e.ahead)),e.behind>0&&a.push(rr("behind",e.behind)),a.push("diverged")):(e.ahead>0&&a.push(rr("ahead",e.ahead)),e.behind>0&&a.push(rr("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 lI(e,t,n,a={}){const s=e?.linkedSandboxProject??null;if(!s?.projectId&&!t)return"upload required";if(s?.projectId&&a.cloudLinkTrusted===!1)return"uploaded to a different account";const r=s?.defaultBranch??t?.defaultBranch??"main",i=s?.manifestHash??null,c=e?.sandboxTemplate?.manifestHash??null,u=s?.syncedAt??t?.syncedAt??null,l=!!(i&&c&&i!==c),p=!!(s?.projectId&&n?.headCommit&&!s.lastUploadedCommit),f=fq(n);return f?`${r} / ${f}`:p?`${r} / upload required`:`${r} / ${l||!u?"needs sync":"setup ready"}`}function mq(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=[],s=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"),s>0&&a.push(dI(s)),t.linkedSourceHeadCommit&&t.headCommit&&t.linkedSourceHeadCommit!==t.headCommit&&t.linkedSourceComparisonError&&s===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 pq(e){return e.linkedSourceHeadCommit?e.divergedFromLinkedSource?"diverged":e.aheadOfLinkedSource>0?rr("local ahead",e.aheadOfLinkedSource):e.behindLinkedSource>0?rr("cloud ahead",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"sync unknown":null:null}function fq(e){return e?.linkedSourceHeadCommit?e.dirty?"local dirty files not in cloud":e.divergedFromLinkedSource?"diverged from local":e.aheadOfLinkedSource>0?rr("cloud behind local",e.aheadOfLinkedSource):e.behindLinkedSource>0?rr("cloud ahead local",e.behindLinkedSource):e.linkedSourceComparisonError&&e.headCommit&&e.linkedSourceHeadCommit!==e.headCommit?"source check unavailable":"synced":null}function rr(e,t){return`${e} by ${dI(t)}`}function dI(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 uI({kind:e,linkedCloud:t=!1,open:n=!1,className:a,baseSize:s=15}){const r=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-${r} project-kind-icon-svg`,xmlns:"http://www.w3.org/2000/svg",width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e==="cloud"?g.jsx(bq,{}):n?g.jsx(vq,{}):g.jsx(gq,{}),t&&e==="local"?g.jsx(yq,{}):null]})})}function gq(){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 vq(){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 yq(){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 Md=r_();function Sq({title:e,pinned:t,savedForLater:n,archived:a,onRename:s,onTogglePin:r,onToggleSaveForLater:i,onDockRight:c,onArchive:u}){const l=h.useRef(null),p=h.useRef(null),[f,y]=h.useState(null),b=[...s?[{label:"Rename",Icon:vu,action:s}]:[],{label:t?"Unpin":"Pin",Icon:t?rg:sg,action:r},...i?[{label:n?"Return to active":"Save for later",Icon:n?Pw:Rw,action:i}]:[],...c?[{label:"Open in right panel",Icon:rf,action:c}]:[],{label:a?"Reopen":"Mark done",Icon:a?cH:cs,action:u}];function I(C=!1){y(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)&&y(null)},P=()=>y(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();y({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(Zc,{size:16})})}),f&&Md.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 xq({session:e,onSave:t,onClose:n}){const[a,s]=h.useState(e.title),r=h.useRef(null);h.useEffect(()=>{const u=r.current;u&&(u.focus(),u.select())},[]),h.useEffect(()=>{function u(l){l.key==="Escape"&&n()}return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[n]);function i(){const u=a.trim();u&&(t(u),n())}function c(u){u.key==="Enter"&&!u.shiftKey&&(u.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:u=>u.stopPropagation(),children:[g.jsx("h2",{id:"rename-chat-title",children:"Rename chat"}),g.jsx("textarea",{ref:r,className:"rename-chat-input",value:a,rows:1,maxLength:200,onChange:u=>s(u.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 kq=24;function wq({title:e}){const t=h.useRef(e),[n,a]=h.useState(e);return h.useEffect(()=>{const s=t.current;if(t.current=e,!e){a("");return}if(s||window.matchMedia("(prefers-reduced-motion: reduce)").matches){a(e);return}const r=Array.from(e);let i=0;a("");const c=window.setInterval(()=>{i+=1,a(r.slice(0,i).join("")),i>=r.length&&window.clearInterval(c)},kq);return()=>window.clearInterval(c)},[e]),g.jsx("span",{className:"sidebar-task-title-text","aria-label":e||"New task",children:n||"New task"})}const Iq="/";function Xn(e){return`${Iq}${e.replace(/^\.?\//,"")}`}const wg=Xn("openpond-icon.png"),_q=Xn("openpond-wordlogo-white.png"),W8=Xn("tutorials/what-is-an-openpond-agent-poster.png"),G8=Xn("tutorials/what-is-an-openpond-agent.vtt"),Z8=Xn("tutorials/how-to-make-an-agent-poster.png"),J8=Xn("tutorials/how-to-make-an-agent.vtt");function Q8(e){return Xn(`tutorials/how-to-make-an-agent-${e}-poster.png`)}function Y8(e){return Xn(`tutorials/how-to-make-an-agent-${e}.vtt`)}const jb={github:Xn("connected-apps/github.svg"),google:Xn("connected-apps/google.svg"),microsoft_teams:Xn("connected-apps/microsoft.svg"),mcp:Xn("connected-apps/openpond-mcp.svg"),slack:Xn("connected-apps/slack.svg"),x:Xn("connected-apps/x.svg")};function X8(e){return jb[e]??jb.mcp}const Cq={codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode","grok-build":"Grok Build"};function Rq({session:e}){const t=Cq[e.provider],n=t??(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:wg,alt:""}):e.metadata?.nativeSource?g.jsx(bU,{size:15,"aria-hidden":"true"}):e.provider==="openai"?g.jsx(hH,{size:15,"aria-hidden":"true"}):g.jsx(gu,{size:15,"aria-hidden":"true"})})}var id={exports:{}},Pq=id.exports,Mb;function Tq(){return Mb||(Mb=1,(function(e,t){(function(n,a){e.exports=a()})(Pq,(function(){var n=1e3,a=6e4,s=36e5,r="millisecond",i="second",c="minute",u="hour",l="day",p="week",f="month",y="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:u,m:c,s:i,ms:r,Q:y}[ee]||String(ee||"").toLowerCase().replace(/s$/,"")},u:function(ee){return ee===void 0}},S="en",w={};w[S]=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 S;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&&(S=K),K||!J&&S},$=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 ze=V.w(K.$u?Date.UTC(K.$y,De,je):new Date(K.$y,De,je),K);return B?ze:ze.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,ve=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,ve):G(0,ve+1);case p:var Q=this.$locale().weekStart||0,xe=(oe<Q?oe+7:oe)-Q;return G(B?me-xe:me+(6-xe),ve);case l:case I:return te(Re+"Hours",0);case u: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[u]=ne+"Hours",K[c]=ne+"Minutes",K[i]=ne+"Seconds",K[r]=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(ve){var me=$(B);return V.w(me.date(me.date()+Math.round(ve*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[u]=s,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,ve=K.weekdays,me=K.months,Re=K.meridiem,Q=function(De,ze,we,Me){return De&&(De[ze]||De(J,B))||we[ze].slice(0,Me)},xe=function(De){return V.s(G%12||12,De,"0")},je=Re||function(De,ze,we){var Me=De<12?"AM":"PM";return we?Me.toLowerCase():Me};return B.replace(_,(function(De,ze){return ze||(function(we){switch(we){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,ve,2);case"ddd":return Q(K.weekdaysShort,J.$W,ve,3);case"dddd":return ve[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,ve=this-te,me=function(){return V.m(ne,te)};switch(G){case b:B=me()/12;break;case f:B=me();break;case y:B=me()/3;break;case p:B=(ve-oe)/6048e5;break;case l:B=(ve-oe)/864e5;break;case u:B=ve/s;break;case c:B=ve/a;break;case i:B=ve/n;break;default:B=ve}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})(),se=Y.prototype;return $.prototype=se,[["$ms",r],["$s",i],["$m",c],["$H",u],["$W",l],["$M",f],["$y",b],["$D",I]].forEach((function(ee){se[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[S],$.Ls=w,$.p={},$}))})(id)),id.exports}var Aq=Tq();const mI=i0(Aq);var cd={exports:{}},Eq=cd.exports,Ob;function jq(){return Ob||(Ob=1,(function(e,t){(function(n,a){e.exports=a()})(Eq,(function(){return function(n,a,s){n=n||{};var r=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,y){return r.fromToBase(l,p,f,y)}s.en.relativeTime=i,r.fromToBase=function(l,p,f,y,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 S=M[T];S.d&&(I=y?s(l).diff(f,S.d,!0):f.diff(l,S.d,!0));var w=(n.rounding||Math.round)(Math.abs(I));if(P=I>0,w<=S.r||!S.r){w<=1&&T>0&&(S=M[T-1]);var R=_[S.l];b&&(w=b(""+w)),C=typeof R=="string"?R.replace("%d",w):R(w,p,S.l,P);break}}if(p)return C;var O=P?_.future:_.past;return typeof O=="function"?O(C):O.replace("%s",C)},r.to=function(l,p){return c(l,p,this,!0)},r.from=function(l,p){return c(l,p,this)};var u=function(l){return l.$u?s.utc():s()};r.toNow=function(l){return this.to(u(this),l)},r.fromNow=function(l){return this.from(u(this),l)}}}))})(cd)),cd.exports}var Mq=jq();const Oq=i0(Mq);mI.extend(Oq);let vf=Date.now(),Nl;const Dl=new Set,$b=()=>vf;function $q(e){return Dl.add(e),Nl||(vf=Date.now(),Nl=setInterval(()=>{vf=Date.now();for(const t of Dl)t()},3e4)),()=>{Dl.delete(e),Dl.size===0&&(clearInterval(Nl),Nl=void 0)}}function pI({value:e,className:t}){const n=h.useSyncExternalStore($q,$b,$b),a=e==null?null:mI(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 Nq=2650,Dq=304,Lq=260;function zq(){return{animationDelay:`${-(Date.now()%Nq)}ms`}}function Hq(e){const t=e.currentTarget,n=t.firstElementChild;if(!(n instanceof HTMLElement))return;const a=Math.max(0,n.scrollWidth-t.clientWidth),s=a>2;t.dataset.overflowing=String(s),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 cp({label:e,actions:t,actionsVisible:n=!1,className:a,titleAccessory:s,children:r,collapsed:i=!1,titleActive:c=!1,onTitleClick:u,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:[u?g.jsxs("div",{className:"section-title-combo",children:[g.jsx("button",{type:"button",className:`section-title-link${c?" active":""}`,onClick:u,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(pr,{size:13}):g.jsx(mr,{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(pr,{size:13}):g.jsx(mr,{size:13})]}):g.jsx("span",{children:e}),s]}),t&&g.jsx("div",{className:"section-actions",children:t})]}),!i&&g.jsx("div",{className:"sidebar-section-body",children:r})]})}function Nb({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 Db({session:e,selected:t,icon:n,archived:a=!1,nested:s=!1,dragging:r,placeholder:i,running:c,goalRuntime:u,subagentRuntime:l,terminalIndicator:p,projectLabel:f,inbox:y=!1,activityAt:b,ariaDescribedBy:I,childSessionCount:C=0,childSessionsExpanded:P=!1,onSelect:_,onToggleChildSessions:M,onTogglePin:A,onToggleSaveForLater:T,onDockRight:S,onArchive:w,onDragStart:R,onDragEnd:O,onDragOver:z,onDrop:$,onRename:V}){const[Y,se]=h.useState(!1),ee=u?.status==="queued",H=u?.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&&u?qq(u):"Running",ne=["sidebar-task-row",Mc(e)?"is-draft":"",K?"has-running-dot":"",y?"sidebar-inbox-row":""].filter(Boolean).join(" "),G=h.useMemo(zq,[]),te=g.jsx(Sq,{title:e.title,pinned:!!e.pinned,savedForLater:!!e.savedForLater,archived:a,onRename:V?()=>se(!0):void 0,onTogglePin:A,onToggleSaveForLater:T,onDockRight:S,onArchive:w}),oe=g.jsxs(Ig,{selected:t,dataSessionId:e.id,dragging:r,nested:s,placeholder:i,className:ne||void 0,ariaExpanded:J?P:void 0,ariaDescribedBy:I,onSelect:_,onDragStart:R,onDragEnd:O,onDragOver:z,onDrop:$,onDoubleClick:V?()=>se(!0):void 0,children:[g.jsx("span",{className:"sidebar-source-slot",children:n??g.jsx(Rq,{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(mr,{size:13}):g.jsx(pr,{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:Hq,children:g.jsx(wq,{title:e.title})})}),y?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(pI,{value:b??e.createdAt})]}):null]})]}),g.jsxs("div",{className:"row-meta",children:[g.jsxs("span",{className:"row-meta-status",children:[p?g.jsx(fI,{indicator:p}):null,K?g.jsx("span",{className:`sidebar-running-dot${F?" subagent":H?" goal":""}`,style:G,"aria-label":B}):null]}),te,y?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(sU,{size:19}):g.jsx(cs,{size:21})}):null]})]}),ve=Y&&V?g.jsx(xq,{session:e,onSave:me=>V(e,me),onClose:()=>se(!1)}):null;return g.jsxs(g.Fragment,{children:[oe,ve]})}function Uq({file:e,selected:t=!1,placeholder:n,onSelect:a,onTogglePin:s,onToggleSaveForLater:r,onDragStart:i,onDragEnd:c,onDragOver:u,onDrop:l}){const p=e.path.split("/").at(-1)??e.path,f=`${e.workspaceName} · ${e.path}`;return g.jsxs(Ig,{selected:t,placeholder:n,className:`sidebar-file-row actions-2${e.available?"":" unavailable"}`,onSelect:a,onDragStart:i,onDragEnd:c,onDragOver:u,onDrop:l,children:[e.available?g.jsx(tg,{size:15}):g.jsx(Pd,{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(Od,{label:e.status==="pinned"?"Unpin file":"Pin file",onClick:s,children:e.status==="pinned"?g.jsx(rg,{size:13}):g.jsx(sg,{size:13})}),g.jsx(Od,{label:e.status==="saved_for_later"?"Remove from Save for later":"Save file for later",onClick:r,children:e.status==="saved_for_later"?g.jsx(Pw,{size:13}):g.jsx(Rw,{size:13})})]})})]})}function qq(e){return e.actionLabel}function Bq({kind:e="local",project:t,pinned:n=!1,selected:a,expanded:s=!1,disclosure:r=!0,workspaceState:i,cloudLinkTrusted:c=!0,cloudLinkWarning:u=null,placeholder:l,terminalIndicator:p,onSelect:f,onNewChat:y,onMoveToCloud:b,onWorkspaceTargetSelect:I,onTogglePin:C,onRemove:P,onDragStart:_,onDragEnd:M,onDragOver:A,onDrop:T}){const[S,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-Dq-12),J=Math.max(12,window.innerHeight-Lq),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)},[]),se=h.useCallback(()=>{Y(),f()},[f,Y]);function ee(){w(!1)}return g.jsxs("div",{ref:R,className:["sidebar-project-row-shell",S?"project-menu-open":""].filter(Boolean).join(" "),onFocusCapture:Y,onPointerEnter:Y,children:[g.jsxs(Ig,{selected:a,placeholder:l,className:["sidebar-project-row",S?"project-menu-open":""].filter(Boolean).join(" "),ariaExpanded:r?s:void 0,onSelect:se,onDragStart:_,onDragEnd:M,onDragOver:A,onDrop:T,children:[g.jsx(uI,{kind:e,linkedCloud:V,open:e==="local"&&s,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(pI,{value:t.updatedAt})]}),r?g.jsx("span",{className:"sidebar-project-caret","aria-hidden":"true",children:s?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})}):null]})}),g.jsxs("div",{className:"row-meta",children:[g.jsx("span",{className:"row-meta-status",children:p?g.jsx(fI,{indicator:p}):null}),g.jsxs("div",{className:"sidebar-row-actions",children:[g.jsx(Od,{label:n?"Unpin project":"Pin project",onClick:C,children:n?g.jsx(rg,{size:13}):g.jsx(sg,{size:13})}),$&&g.jsx(nB,{open:S,onToggleOpen:()=>w(H=>!H)}),g.jsx(Od,{label:"New task",onClick:y,children:g.jsx(vu,{size:13})})]})]})]}),g.jsx(Fq,{kind:e,project:t,workspaceState:i,cloudLinkTrusted:c,cloudLinkWarning:u,onWorkspaceTargetSelect:I,style:O}),S&&g.jsx(aB,{onClose:ee,onMoveToCloud:b?()=>{ee(),b()}:void 0,onRemove:()=>{ee(),P()}})]})}function fI({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(Dw,{size:13})})}function Fq({kind:e,project:t,workspaceState:n,cloudLinkTrusted:a,cloudLinkWarning:s,onWorkspaceTargetSelect:r,style:i}){const c=Wq(e,t,n,a,s);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(u=>{const l=["sidebar-project-location-row",u.tone??"",u.actionTarget?"clickable":""].filter(Boolean).join(" "),p=g.jsxs(g.Fragment,{children:[g.jsx("span",{className:["sidebar-project-location-icon",u.key].filter(Boolean).join(" "),"aria-hidden":"true",children:u.icon}),g.jsx("span",{className:"sidebar-project-location-copy",children:g.jsx(Vq,{value:u.value})})]});return u.actionTarget?g.jsx("button",{type:"button",className:l,"data-workspace-target":u.actionTarget,disabled:u.disabled||!r,title:u.disabledReason??void 0,onClick:f=>{f.stopPropagation(),!u.disabled&&r?.(u.actionTarget)},children:p},u.key):g.jsx("div",{className:l,children:p},u.key)})})]})}function Vq({value:e}){const t=Kq(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 Kq(e){const n=e.indexOf(" / ");return n===-1?{branch:null,status:e}:{branch:e.slice(0,n),status:e.slice(n+3)}}function Wq(e,t,n,a=!0,s=null){return e==="cloud"?Zq(t):Gq(t,n,a,s)}function Gq(e,t,n=!0,a=null){const s=Jq(e,t,n),r=Qq(t),i=Xq(e,n),c=n===!1&&a;return[{key:"local",value:s,tone:r?"attention":"local",icon:e.source==="git"?g.jsx(ng,{size:13}):g.jsx(jw,{size:13}),actionTarget:"local"},{key:"cloud",value:c||(i?eB(e,t,n):"not in cloud"),tone:c?"attention":"cloud",icon:g.jsx(hu,{size:13}),actionTarget:i?"cloud":"upload_cloud"}]}function Zq(e){return[{key:"cloud",value:tB(e),tone:e.syncedAt?"cloud":"attention",icon:g.jsx(hu,{size:13}),actionTarget:"cloud"}]}function Jq(e,t,n){const a=Yq(e,t);return t?t.error?`${a} / status unavailable`:t.initialized?cI(t,{branch:e.linkedSandboxProject?.defaultBranch??null,linkedCloudSourceKnown:e.linkedSandboxProject?.projectId&&n?!!e.linkedSandboxProject.lastUploadedCommit||!t.headCommit:!0}):`${a} / not checked out`:`${a} / available`}function Qq(e){return!!(e?.dirty||(e?.changedFilesCount??0)>0||(e?.untrackedFilesCount??0)>0)}function Yq(e,t){return t?.currentBranch??t?.defaultBranch??e.linkedSandboxProject?.defaultBranch??"local"}function Xq(e,t=!0){return!!(t&&e.linkedSandboxProject?.projectId||e.linkedOpenPondApp?.appId)}function eB(e,t,n){return lI(e,null,t,{cloudLinkTrusted:n})}function tB(e){const t=e.defaultBranch??"main",n=e.syncedAt?"setup ready":"needs setup";return`${t} / ${n}`}function nB({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(Zc,{size:13})})}function aB({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(Jc,{size:13}),g.jsx("span",{children:"Remove from Projects"})]})]})]})}function Ig({children:e,className:t,dataSessionId:n,dragging:a,iconless:s=!1,nested:r=!1,placeholder:i=!1,selected:c,ariaExpanded:u,ariaDescribedBy:l,onSelect:p,onDragStart:f,onDragEnd:y,onDragOver:b,onDrop:I,onDoubleClick:C}){const P=!!f;return g.jsx("div",{className:["sidebar-row",t??"",c?"selected":"",a?"dragging":"",s?"iconless":"",r?"nested":"",i?"placeholder":""].filter(Boolean).join(" "),draggable:P,"data-session-id":n,role:"button",tabIndex:0,"aria-expanded":u,"aria-describedby":l,onClick:p,onDoubleClick:C,onKeyDown:_=>{_.target===_.currentTarget&&(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),p())},onDragStart:f,onDragEnd:y,onDragEnter:_=>{b&&(_.preventDefault(),_.dataTransfer.dropEffect="move",b(_))},onDragOver:_=>{b&&(_.preventDefault(),_.dataTransfer.dropEffect="move",b(_))},onDrop:_=>{I&&(_.preventDefault(),I(_))},children:e})}function Od({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 sB({filter:e,activityOrder:t=!1,groupByProject:n,noun:a,onFilterChange:s,onGroupByProjectChange:r,onOnlyRunningTasksChange:i,onShowCodexChatsChange:c,onTasksetChange:u,onSortChange:l,onlyRunningTasks:p,openMenu:f,setOpenMenu:y,showCodexChats:b,sort:I,selectedTasksetId:C,tasksets:P}){const _=h.useRef(null),[M,A]=h.useState(!1),S=P.find(O=>O.id===C)?.name??_b.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)||y(null)}return document.addEventListener("pointerdown",O),()=>document.removeEventListener("pointerdown",O)},[w,y,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:()=>y(O=>O==="chats"?null:"chats"),children:g.jsx(Zc,{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(cs,{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(cs,{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:()=>r(!n),children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:n?g.jsx(cs,{size:13}):null}),g.jsx("span",{children:"Group by project"})]}):null,t?g.jsx("p",{className:"empty-row",children:"Latest activity first"}):aq.map(O=>g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":I===O.value,onClick:()=>{l(O.value),y(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:I===O.value?g.jsx(cs,{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}: ${S}`,"aria-haspopup":"menu","aria-expanded":w,onClick:()=>y(O=>O==="tasks-filter"?null:"tasks-filter"),children:g.jsx(qH,{size:14})}),w?g.jsx("div",{className:"section-menu-popover",role:"menu","aria-label":`Filter ${a}`,children:_b.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(mr,{size:13}):g.jsx(pr,{size:13})}),g.jsx("span",{children:O.label})]}):g.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":e===O.value,onClick:()=>{s(O.value),y(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e===O.value?g.jsx(cs,{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:()=>{u(null),y(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&!C?g.jsx(cs,{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:()=>{u(z.id),y(null)},children:[g.jsx("span",{className:"section-menu-check","aria-hidden":"true",children:e==="tasksets"&&C===z.id?g.jsx(cs,{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 rB({onAddProject:e,onViewProjects:t}){const[n,a]=h.useState(!1),s=h.useRef(null),r=h.useRef(null);return h.useEffect(()=>{if(!n)return;s.current?.querySelector('[role="menuitem"]')?.focus();const i=c=>{s.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:s,onKeyDown:i=>{i.key==="Escape"&&(i.stopPropagation(),a(!1),r.current?.focus())},children:[g.jsx("button",{ref:r,type:"button",className:`section-icon${n?" active":""}`,"aria-label":"Project options","aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(i=>!i),children:g.jsx(Zc,{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 oB=240,iB=36;function cB(e,t,n=!1){const a=Math.max(12,t.width-oB-12),s=Math.max(12,t.height-iB-(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,s)))}px`}}function lB({detail:e,onClose:t}){if(h.useEffect(()=>{if(!e||typeof window>"u")return;const s=c=>{c.key==="Escape"&&t()};let r=!1;const i=window.requestAnimationFrame(()=>{window.addEventListener("scroll",t,!0),r=!0});return window.addEventListener("keydown",s),()=>{window.cancelAnimationFrame(i),window.removeEventListener("keydown",s),r&&window.removeEventListener("scroll",t,!0)}},[e,t]),!e)return null;const n=new Date(e.updatedAt),a=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(n);return 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(jw,{size:13,"aria-hidden":"true"}),g.jsx("span",{children:e.folderName})]}):null]})}function dB({children:e,expanded:t,groupKey:n,kind:a,label:s,onToggle:r,onNewTask:i,onOpenProject:c,onRemoveProject:u,project:l}){const p=`sidebar-task-group-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}`,f=a==="draft"?tg:gu,[y,b]=h.useState(!1),I=!!(i||c||u);return g.jsxs("section",{className:"sidebar-task-project-group",children:[g.jsxs("div",{className:`sidebar-task-project-group-header-shell${y?" menu-open":""}`,children:[g.jsxs("button",{type:"button",className:"sidebar-task-project-group-header","aria-controls":p,"aria-expanded":t,onClick:()=>{b(!1),r()},children:[l?g.jsx(uI,{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:s}),g.jsx("span",{className:"sidebar-task-project-group-caret","aria-hidden":"true",children:t?g.jsx(mr,{size:13}):g.jsx(pr,{size:13})})]}),l&&I?g.jsxs("div",{className:"sidebar-task-project-group-actions",children:[c||u?g.jsx("button",{type:"button",className:`sidebar-row-action${y?" active":""}`,"data-tooltip":"More project actions","aria-label":"More project actions","aria-expanded":y,"aria-haspopup":"menu",onClick:()=>b(C=>!C),children:g.jsx(Zc,{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(vu,{size:13})}):null]}):null,y?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,u?g.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),u()},children:[g.jsx(Jc,{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 uB={},mB=new Map,pB=new Map;function Lb(){const e=eo.getItem("openpond.sidebar.presentation.v1");return e==="inbox"||e==="grouped"?e:bu()?"inbox":"grouped"}function fB(e,t){return Math.min(Math.max(e,$n)+ff,t)}function hB(e,t){const n=Math.max($n,Math.min(e,t));if(n<=$n)return $n;const a=Math.ceil((n-$n)/ff);return Math.max($n,$n+(a-1)*ff)}function gB(e,t){const n=new Map;for(const a of e){const s=t(a),r=n.get(s.key);r?r.sessions.push(a):n.set(s.key,{...s,sessions:[a]})}return[...n.values()]}function vB({activeSessions:e,activityTimes:t={},onSelectSession:n,archiveSession:a,archivedSessions:s,chatRowsVisibleCount:r,childSessionRowsByParentId:i={},cloudProjectRows:c,beginProjectChat:u,onAddProject:l,commitTaskDrop:p,commitTaskPreviewDrop:f,dockSessionRight:y,experience:b="work",goalRuntimeBySessionId:I=mB,localProjectRows:C,openSidebarFile:P,pinnedCollapsed:_,pinnedRows:M,previewTaskDrop:A,previewPinnedDrop:T,projectRows:S,renameSession:w,restoreSession:R,runningSessionIds:O,sectionMenuOpen:z,selectedProjectId:$,selectedSessionId:V,setChatRowsVisibleCount:Y,setSectionMenuOpen:se,setSelectedAppId:ee,setSelectedProjectId:H,setSelectedSessionId:F,setView:J,sidebarProjectIdBySessionId:K,startTaskDrag:B,startPinnedDrag:ne,subagentRuntimeBySessionId:G=pB,taskDragSessionId:te,taskPreviewSessionIds:oe,terminalSummaries:ve=uB,toggleSessionPinned:me,toggleSessionSavedForLater:Re,view:Q,clearTaskDrag:xe,removeProject:je,toggleProjectPinned:De,onTogglePinnedCollapsed:ze,setSidebarFileStatus:we,commitPinnedDrop:Me,commitPinnedPreviewDrop:Te,clearSidebarDrag:N,dragItem:q}){const[X,U]=h.useState(Lb);ui(()=>U(Lb()));const ae=X==="inbox",[de,be]=h.useState("active"),[Oe,$e]=h.useState("recent"),[Ge,bt]=h.useState(!0);h.useEffect(()=>{b!=="chat"&&bt(!0)},[b]);const[ye,Le]=h.useState({work:!1,chat:!0}),[Ae,qe]=h.useState({work:!1,chat:!1}),He=b==="chat"?"chat":"work",vn=ye[He],[jt,pe]=h.useState(Ab);ui(()=>pe(Ab()));const{onlyRunningTasks:fe,showCodexChats:Fe}=jt,[Pe,Ne]=h.useState(null),[rt,lt]=h.useState(()=>new Set),[Tt,dt]=h.useState(()=>new Map),[at,_t]=h.useState(null);h.useEffect(()=>{$&&Le(D=>D[He]?{...D,[He]:!1}:D)},[He,$]);const Be=b==="chat"?"chats":"tasks",At=S??[...C,...c],ln=h.useMemo(()=>new Map(At.map(D=>[D.id,D.project.name])),[At]),En=h.useMemo(()=>new Map(At.map(D=>[D.id,D])),[At]),xt=h.useMemo(()=>{const D=new Set(O);for(const ke of[...e,...Object.values(i).flat()]){const ie=I.get(ke.id),Je=G.get(ke.id);(ie?.tone==="active"&&ie.status!=="queued"||(Je?.activeCount??0)>0||It(ke.id)?.status==="running")&&D.add(ke.id)}return D},[e,i,I,O,G,ve]),xs=h.useMemo(()=>ip({activeSessions:e,doneSessions:s,filter:"all",inProgressSessionIds:xt,sort:"manual"}),[e,s,xt]),dn=h.useMemo(()=>ip({activeSessions:e,doneSessions:s,filter:de,inProgressSessionIds:xt,onlyRunningTasks:fe,selectedTasksetId:Pe,previewSessionIds:oe,showCodexChats:Fe,sort:Oe}),[e,s,xt,fe,Pe,Fe,de,oe,Oe]),bn=h.useMemo(()=>{const D=new Map;for(const ke of[...e,...s]){if(!od(ke,{inProgressSessionIds:xt,onlyRunningTasks:fe,showCodexChats:Fe}))continue;const ie=qo(ke);if(!ie)continue;const Je=D.get(ie.id);Je?Je.chatCount+=1:D.set(ie.id,{...ie,chatCount:1})}return[...D.values()].sort((ke,ie)=>ke.name.localeCompare(ie.name))},[e,s,xt,fe,Fe]),Ht=h.useMemo(()=>M.filter(D=>D.type!=="session"||od(D.session,{inProgressSessionIds:xt,onlyRunningTasks:fe,showCodexChats:Fe})),[xt,fe,M,Fe]),Cn=h.useMemo(()=>dn.filter(D=>!Bo(D)),[dn]),yn=h.useMemo(()=>Cn.slice(0,Math.max($n,r)),[r,Cn]),Rn=h.useMemo(()=>{const D=gB(yn,ke=>{if(Mc(ke))return{key:"draft",label:"Drafts",projectId:null,project:null,kind:"draft"};const ie=K[ke.id],Je=Mt(ke)??"Work";return{key:ie?`project:${ie}`:`projectless:${Je}`,label:Je,projectId:ie??null,project:ie?En.get(ie)??null:null,kind:ie?"project":"projectless"}});for(const ke of At)D.some(ie=>ie.projectId===ke.id)||D.push({key:`project:${ke.id}`,label:ke.project.name,projectId:ke.id,project:ke,kind:"project",sessions:[]});return D},[At,ln,En,K,yn]),jn=yn.length<Cn.length,Ut=yn.length>$n,ft=h.useMemo(()=>new Set(Rn.filter(D=>D.sessions.some(ke=>ke.id===V||xt.has(ke.id))).map(D=>D.key)),[Rn,xt,V]),Un=xs.filter(D=>!Bo(D)).map(D=>D.id),un=yn.map(D=>D.id),ut=JSON.stringify(Object.entries(i).filter(([D,ke])=>ke.some(ie=>!ie.archived)&&(G.get(D)?.activeCount??0)>0).flatMap(([D,ke])=>ke.filter(ie=>!ie.archived).map(ie=>[D,ie.id])).sort(([D,ke],[ie,Je])=>D.localeCompare(ie)||ke.localeCompare(Je)));h.useEffect(()=>{const D=JSON.parse(ut);if(D.length===0)return;const ke=new Set(D.map(([ie])=>ie));lt(ie=>[...ke].every(Je=>ie.has(Je))?ie:new Set([...ie,...ke]))},[ut]);function It(D){return dq(ve[iI({kind:"session",id:D})])}function Mt(D){if(Mc(D))return"Draft";const ke=K[D.id];return ke?ln.get(ke)??D.workspaceName??"Project":QU(D)}function mn(D){if(n){n(D);return}Dt({kind:"chat",sessionId:D.id}),F(D.id);const ke=K[D.id]??null;ee(ke?null:D.appId),H(ke),J("chat")}function ra(D){return(i[D.id]??[]).filter(ke=>!ke.archived&&od(ke,{inProgressSessionIds:xt,onlyRunningTasks:fe,showCodexChats:Fe}))}function Ze(D,ke){return rt.has(D.id)||ke.some(ie=>ie.id===V)}function Pn(D){lt(ke=>{const ie=new Set(ke);return ie.has(D)?ie.delete(D):ie.add(D),ie})}function Ga(D){const ke=ra(D);return ke.length===0||!Ze(D,ke)?null:g.jsx("div",{className:"sidebar-child-session-group",children:ke.map(ie=>g.jsx(Db,{session:ie,selected:Q==="chat"&&V===ie.id,nested:!0,running:xt.has(ie.id),goalRuntime:I.get(ie.id)??null,subagentRuntime:G.get(ie.id)??null,terminalIndicator:It(ie.id),projectLabel:Mt(D),onSelect:()=>mn(ie),onTogglePin:()=>me(ie),onToggleSaveForLater:()=>Re(ie),onDockRight:()=>y(ie),onArchive:()=>ie.archived?R(ie):a(ie),onRename:w},ie.id))})}function Aa(D,ke){if(typeof window>"u")return;const ie=Bo(D)?Mt(D):null;_t({descriptionId:`sidebar-task-detail-${D.id}`,sessionId:D.id,title:D.title,updatedAt:D.updatedAt,folderName:ie,style:cB(ke.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight},!!ie)})}function Dn(D,ke={}){const ie=D.archived,Je=ke.pinnedRow?.placeholder??te===D.id,fa=ra(D),qn="sidebar-session-group",ja=ke.pinnedRow?.dragProps??(!ae&&Oe==="manual"?{onDragStart:xn=>B(xn,{allSessionIds:Un,visibleSessionIds:un,sessionId:D.id}),onDragEnd:xe,onDragOver:xn=>{Je||A(xn,D.id)},onDrop:xn=>{Je?f():p(xn,D.id)}}:{});return g.jsxs("div",{className:qn,onPointerEnter:xn=>Aa(D,xn.currentTarget),onPointerLeave:()=>_t(null),onFocusCapture:xn=>Aa(D,xn.currentTarget),onBlurCapture:xn=>{xn.currentTarget.contains(xn.relatedTarget)||_t(null)},children:[g.jsx(Db,{session:D,selected:!ie&&Q==="chat"&&V===D.id,archived:ie,inbox:ae,activityAt:fd(D,t),placeholder:Je,running:xt.has(D.id),goalRuntime:I.get(D.id)??null,subagentRuntime:G.get(D.id)??null,terminalIndicator:It(D.id),projectLabel:ke.projectLabel===void 0?Mt(D):ke.projectLabel,metadataPresentation:ke.metadataPresentation,ariaDescribedBy:at?.sessionId===D.id?at.descriptionId:void 0,childSessionCount:fa.length,childSessionsExpanded:Ze(D,fa),onToggleChildSessions:()=>Pn(D.id),onSelect:()=>{_t(null),ie&&R(D),mn(D)},onTogglePin:()=>me(D),onToggleSaveForLater:()=>Re(D),onDockRight:()=>y(D),onArchive:()=>ie?R(D):a(D),onRename:w,...ja}),!ae&&!Je?Ga(D):null]},ke.pinnedRow?.key??D.id)}function Tn(D){D!=="tasksets"&&Ne(null),be(D),Y($n)}function Za(D){Ne(D),be("tasksets"),Y($n)}function ks(D){$e(D),Y($n)}function Ea(){Y(D=>fB(D,Cn.length))}function ct(){Y(D=>hB(D,Cn.length))}function an(D){const ke={id:D.id,type:D.type};return{onDragStart:ie=>ne(ie,ke),onDragEnd:N,onDragOver:ie=>T(ie,ke),onDrop:ie=>{q?.id===D.id&&q.type===D.type?Te():Me(ie,ke)}}}function Ke(D){const ke=an(D),ie=q?.id===D.id&&q.type===D.type;if(D.type==="project"){const Je=D.item;return g.jsx(Bq,{kind:Je.kind,project:Je.project,pinned:!0,selected:Q==="chat"&&$===Je.id,expanded:!1,disclosure:!1,placeholder:ie,onSelect:()=>{ee(null),H(Je.id),F(null),J("chat")},onNewChat:()=>u(Je.id),onTogglePin:()=>De(Je),onRemove:()=>je(Je),...ke},D.key)}return D.type==="file"?g.jsx(Uq,{file:D.file,placeholder:ie,onSelect:()=>P(D.file),onTogglePin:()=>we(D.file,"none"),onToggleSaveForLater:()=>we(D.file,"saved_for_later"),...ke},D.key):Dn(D.session,{projectLabel:ae&&!K[D.session.id]?null:Mt(D.session),pinnedRow:{key:D.key,dragProps:ke,placeholder:ie}})}function yt(D){const ke=ft.has(D.key)||Tt.get(D.key)!==!1;return g.jsx(dB,{expanded:ke,groupKey:D.key,kind:D.kind,label:D.label,onToggle:()=>{dt(ie=>{const Je=new Map(ie);return Je.set(D.key,!ke),Je})},onNewTask:D.project?()=>u(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(ie=>Dn(ie,{metadataPresentation:"flyout",projectLabel:D.label}))},D.key)}const Xt=g.jsx(sB,{activityOrder:ae,filter:de,groupByProject:Ge,noun:Be,onFilterChange:Tn,onGroupByProjectChange:bt,onOnlyRunningTasksChange:D=>{pe(ke=>{const ie={...ke,onlyRunningTasks:D};return Eb(ie),ie}),Y($n)},onShowCodexChatsChange:D=>{pe(ke=>{const ie={...ke,showCodexChats:D};return Eb(ie),ie}),Y($n)},onTasksetChange:Za,onSortChange:ks,onlyRunningTasks:fe,openMenu:z,setOpenMenu:se,showCodexChats:Fe,sort:Oe,selectedTasksetId:Pe,tasksets:bn}),Ln=ip({activeSessions:Object.values(i).flat().filter(D=>!D.archived),doneSessions:Object.values(i).flat().filter(D=>D.archived),filter:de,inProgressSessionIds:xt,onlyRunningTasks:fe,selectedTasksetId:Pe,showCodexChats:Fe,sort:"recent"}),Sn=K_([...dn,...Ln].filter(D=>!Bo(D)),t,xt);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?Xt: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),eo.setItem("openpond.sidebar.presentation.v1",D)},children:ae?g.jsx(gU,{size:16}):g.jsx(ig,{size:16})})]})]}),Ht.length>0?g.jsx(cp,{label:"Pinned",className:"sidebar-pinned-section",collapsed:_,onToggleCollapsed:ze,children:Ht.map(Ke)}):null,ae?g.jsxs("section",{className:"sidebar-thread-inbox","aria-label":"Thread inbox",children:[W_(Sn,t,xt).map(D=>g.jsxs("div",{children:[D.label?g.jsx("h3",{className:"sidebar-inbox-date",children:D.label}):null,D.sessions.map(ke=>Dn(ke,{projectLabel:K[ke.id]?Mt(ke):null}))]},D.key)),Sn.length===0&&Ht.length===0?g.jsx("div",{className:"empty-row",children:Rb(de,Be)}):null]}):g.jsxs(g.Fragment,{children:[g.jsx(cp,{label:"Projects",className:`sidebar-projects-section${b!=="chat"?" development":""}`,collapsed:vn,onToggleCollapsed:()=>Le(D=>({...D,[He]:!D[He]})),actions:g.jsx(rB,{onAddProject:l,onViewProjects:()=>{(async()=>await Dt({kind:"view",view:"projects"})&&(ee(null),H(null),F(null),J("projects")))()}}),children:Rn.filter(D=>D.kind==="project").map(D=>yt(b==="chat"||!Ge?{...D,sessions:[]}:D))}),g.jsxs(cp,{label:b==="chat"?"Chat":"Work",className:"sidebar-task-section sidebar-ordinary-section",collapsed:Ae[He],onToggleCollapsed:()=>qe(D=>({...D,[He]:!D[He]})),actionsVisible:z==="chats"||z==="tasks-filter"||de!=="active"||fe||!Fe,actions:Xt,children:[(b==="chat"||!Ge?yn:yn.filter(D=>!K[D.id])).map(D=>Dn(D)),Cn.length===0&&Ht.length===0?g.jsx("div",{className:"empty-row",children:Rb(de,Be)}):null,Cn.length>$n&&(jn||Ut)?g.jsxs("div",{className:"sidebar-pagination-controls","aria-label":`Showing ${yn.length} of ${Cn.length} ${Be}`,children:[jn?g.jsx(Nb,{onClick:Ea,children:"Show more"}):null,Ut?g.jsx(Nb,{onClick:ct,children:"Show less"}):null]}):null]})]}),g.jsx(lB,{detail:at,onClose:()=>_t(null)})]})}const bB=h.lazy(()=>fr(()=>import("./TerminalOverlay-CAmF__Dq.js"),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.TerminalOverlay})));function yB({connection:e,command:t,onClose:n,onComplete:a}){const[s,r]=h.useState([]),[i]=h.useState(()=>({kind:"draft",id:`native-setup-${crypto.randomUUID()}`})),c=h.useRef(!1),[u]=h.useState(()=>({id:Date.now(),scope:i,command:t}));return h.useEffect(()=>{!c.current&&s.some(l=>l.lastExitCode!==null&&(l.commandStatus==="success"||l.commandStatus==="failed"))&&(c.current=!0,a?.())},[s,a]),Md.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(bB,{open:!0,disposeOnUnmount:!0,connection:e,scope:i,tabs:s,onTabsChange:r,cwd:null,appId:null,workspaceName:"Agent setup",queuedCommand:u,onClose:n})})}),document.body)}const Ll={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 SB({status:e,busy:t,onControl:n,onConnectionControl:a,onReconnect:s}){const r=e.desiredState==="stopped",i=r?"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 u=c.backfill,l=u.stage==="complete",p=u.admitted+u.skipped;return g.jsxs("div",{className:"native-importer-connection",children:[g.jsxs("span",{children:[c.error?g.jsx(Pd,{size:12}):l?g.jsx(cs,{size:12}):g.jsx(ag,{size:12}),Ll[c.source]??c.source]}),g.jsx("small",{children:c.state==="paused"?"Paused":c.state==="disconnected"?"Disconnected":l?e.running&&!r?"Watching for new conversations":`${u.admitted} conversations imported`:u.stage==="discovering"?"Finding conversations":`${p} of ${u.total} conversations processed`}),g.jsxs("small",{children:[c.admitted," tasks admitted",u.skipped>0?`, ${u.skipped} conversations skipped`:"",u.failed>0?`, ${u.failed} failed`:""]}),!l&&u.total>0?g.jsx("progress",{"aria-label":`${Ll[c.source]??c.source} import progress`,value:p,max:u.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:()=>s(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"," ",Ll[c.source]??c.source]}),g.jsxs("button",{type:"button",disabled:t,onClick:()=>a("disconnect",c.id),children:["Disconnect ",Ll[c.source]??c.source]})]})]},c.id)}),g.jsx("button",{type:"button",disabled:t||r,onClick:()=>n("sync"),children:"Sync now"}),g.jsxs("button",{type:"button",disabled:t,onClick:()=>n(r||!e.running?"start":"stop"),children:[r?"Start":e.running?"Stop":"Restart"," importer"]}),!e.running&&!r?g.jsx("button",{type:"button",disabled:t,onClick:()=>n("stop"),children:"Stop importer"}):null,!e.running&&!r?g.jsx("button",{type:"button",disabled:t,onClick:()=>n("install"),children:"Reinstall background service"}):null]})}function xB({title:e,inspection:t,busy:n,onSelect:a,onRefresh:s,onClose:r}){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:s,children:"Refresh branches"}),g.jsx("button",{type:"button",disabled:n,onClick:r,children:"Cancel"})]})]})}function kB({connection:e,selectedSessionId:t,selectedSession:n,active:a=!0,onOpen:s}){const r=h.useRef({selectedSessionId:t,active:a});r.current={selectedSessionId:t,active:a};const i=h.useRef(null),c=h.useRef(0),u=h.useRef(null);h.useEffect(()=>(c.current++,i.current=null,M(null),I(null),P(null),y(null),w(null),p(null),()=>{c.current++}),[e]);const[l,p]=h.useState(null),[f,y]=h.useState(null),[b,I]=h.useState(null),[C,P]=h.useState(null),[_,M]=h.useState(null),[A,T]=h.useState(!1),[S,w]=h.useState(null),R=h.useCallback(async()=>{if(!e||u.current===c.current)return;const ee=c.current;u.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{u.current===ee&&(u.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=r.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){r.current.active&&r.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),r.current.active&&r.current.selectedSessionId===F&&await s(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;y(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;y(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 se(ee){const H=ee.metadata?.nativeHistoryId;await s(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:S,setCommand:y,setExpanded:T,setBranchSelection:w,refresh:R,more:O,open:z,control:$,connectionControl:V,connect:Y,select:se}}function wB({history:e}){const{connection:t,history:n,error:a,busy:s,command:r,expanded:i,branchSelection:c,setCommand:u,setExpanded:l,setBranchSelection:p,refresh:f,more:y,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:s!==null,onClick:()=>{f()},children:s==="refresh"?g.jsx(ag,{size:14}):g.jsx($w,{size:14})})]}),r?g.jsx(yB,{connection:t,command:r,onClose:()=>{u(null),f()}}):null,c?g.jsx(xB,{title:n?.items.find(_=>_.id===c.id)?.title??"",inspection:c.inspection,busy:s!==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:s!==null,onClick:()=>{P()},children:"Connect an import source"}),n&&Object.keys(n.nextCursors).length?g.jsx("button",{type:"button",disabled:s!==null,onClick:()=>{y()},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(Pd,{size:12,"aria-hidden":"true"})," ",_]},_)),n?.collector.connections.length?g.jsx(SB,{status:n.collector,busy:s!==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(Pd,{size:12,"aria-hidden":"true"})," ",a]}):null]}):null}function zb(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 IB(e,t){const n=zb(e),a=zb(t);if(!n||!a)return!1;for(let s=0;s<a.length;s+=1){if(a[s]>n[s])return!0;if(a[s]<n[s])return!1}return!1}function hI(e){const t=e?.toLowerCase()??"";return t==="darwin"||t.includes("mac")?"mac":t==="linux"||t.includes("linux")?"linux":null}function _B(e){const t=e?.toLowerCase()??"";return t==="arm64"||t==="aarch64"?"arm64":t==="x64"||t==="x86_64"||t==="amd64"?"x64":null}function CB(e,t,n){const a=hI(t),s=_B(n);if(a==="mac"){const r=e.filter(i=>/-mac-.*\.zip$/i.test(i.name));return s==="arm64"?r.find(i=>/-mac-arm64\.zip$/i.test(i.name))??null:s==="x64"?r.find(i=>/-mac-x64\.zip$/i.test(i.name))??r.find(i=>/-mac-universal\.zip$/i.test(i.name))??null:r.find(i=>/-mac-universal\.zip$/i.test(i.name))??r.find(i=>/-mac-arm64\.zip$/i.test(i.name))??r[0]??null}if(a==="linux"){const r=e.filter(i=>/\.AppImage$/i.test(i.name));return s==="arm64"?r.find(i=>/(?:arm64|aarch64).*\.AppImage$/i.test(i.name))??null:s==="x64"?r.find(i=>/(?:x86_64|x64|amd64).*\.AppImage$/i.test(i.name))??r[0]??null:r[0]??null}return null}function RB(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(!IB(e.currentVersion,a))return null;const s=typeof t.html_url=="string"?t.html_url:"",i=(Array.isArray(t.assets)?t.assets:[]).flatMap(u=>{if(!u||typeof u!="object")return[];const l=u;return typeof l.name!="string"||typeof l.browser_download_url!="string"?[]:[{name:l.name,downloadUrl:l.browser_download_url}]}),c=CB(i,e.platform,e.arch);return!c||!s?null:{version:a,releaseUrl:s,assetName:c.name,downloadUrl:c.downloadUrl}}const PB=3600*1e3,TB="https://api.github.com/repos/openpond/openpond/releases/latest";function AB(e){const[t,n]=h.useState({status:"idle",update:null,lastCheckedAt:null}),a=e.currentVersion?.trim()??"",s=e.platform??"",r=e.arch??"",i=e.enabled&&!!a&&!!hI(s);return h.useEffect(()=>{if(!i){n({status:"idle",update:null,lastCheckedAt:null});return}let c=!1;async function u(){n(p=>({...p,status:p.update?"available":"checking"}));try{const p=await fetch(TB,{headers:{Accept:"application/vnd.github+json"}});if(!p.ok)throw new Error(`GitHub release check failed: ${p.status}`);const f=await p.json(),y=RB({payload:f,currentVersion:a,platform:s,arch:r});if(c)return;n({status:y?"available":"current",update:y,lastCheckedAt:Date.now()})}catch{if(c)return;n(p=>({status:p.update?"available":"error",update:p.update,lastCheckedAt:Date.now()}))}}u();const l=window.setInterval(()=>{u()},PB);return()=>{c=!0,window.clearInterval(l)}},[r,a,i,s]),t}const gI="openpond.sidebar.continuous-learning.dismissed.v1";function Hb(e=vI()){if(!e)return!1;try{return e.getItem(gI)==="true"}catch{return!1}}function EB(e=vI()){if(e)try{e.setItem(gI,"true")}catch{}}function vI(){return typeof window>"u"?null:eo}function jB({connection:e,onOpenSettings:t}){const[n,a]=h.useState(null),[s,r]=h.useState(Hb);ui(()=>r(Hb()));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]),s||!e||!n?.workspace)return null;const c=n.evaluationReviewSchedule,u=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(Nw,{size:14})}),g.jsx("button",{className:"sidebar-learning-notice-action","aria-label":"Close continuous learning",onClick:()=>{r(!0),EB()},type:"button",children:g.jsx(Jc,{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:u})]})]})}function MB(e){const{arch:t,currentVersion:n,productArea:a,platform:s,setSectionMenuOpen:r,setSelectedAppId:i,setSelectedProjectId:c,setSelectedSessionId:u,setSidebarOpen:l,setView:p,view:f,modelProjects:y,modelTrainingActivityByProjectId:b}=e,I=h.useCallback(A=>{r(A)},[r]),C=AB({currentVersion:n,platform:s,arch:t,enabled:bu()}),P=C.status==="available"?C.update:null,_=h.useCallback(async A=>{if(!await Dt({kind:"chat",sessionId:A.id}))return!1;u(A.id);const T=e.sidebarProjectIdBySessionId[A.id]??null;return c(T),i(T?null:A.appId),p("chat"),!0},[u,c,i,p,e.sidebarProjectIdBySessionId]),M=kB({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(Ow,{size:16})}),g.jsx("div",{className:"sidebar-brand",children:g.jsx("img",{className:"sidebar-wordmark",src:_q,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:()=>{OB(P.downloadUrl)},children:[g.jsx(PH,{size:14}),g.jsx("span",{children:"Update"})]})]}),a==="chat"?g.jsxs("div",{className:"sidebar-fixed-actions",children:[g.jsx(MU,{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:wg,alt:""})}),g.jsx("span",{children:"Ponder Pal"})]})}):null]}):null,g.jsxs("div",{className:"sidebar-scroll",children:[a!=="chat"?g.jsx(OU,{productArea:a,setSectionMenuOpen:I,setSelectedAppId:i,setSelectedProjectId:c,setSelectedSessionId:u,setView:p,view:f,modelProjects:y,modelTrainingActivityByProjectId:b}):null,a!=="chat"||f!=="chat"?null:g.jsx(vB,{...e,onSelectSession:M.select,setSectionMenuOpen:I}),a==="chat"&&f==="chat"?g.jsx(wB,{history:M}):null]}),g.jsx("div",{className:"sidebar-bottom-stack",children:a!=="chat"?null:g.jsx(jB,{connection:e.connection,onOpenSettings:()=>{r(null),Dt({kind:"settings",section:"harness"})}})})]})}async function OB(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-update",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const $B=[{destination:"walkthroughs",icon:gb,label:"Walkthroughs"},{destination:"external",icon:gb,label:"Docs",url:"https://openpond.ai/docs"},{destination:"external",icon:tg,label:"Blog",url:"https://openpond.ai/blog"},{destination:"external",icon:CH,label:"Pricing",url:"https://openpond.ai/pricing"},{destination:"external",icon:Mw,label:"Web app",url:"https://openpond.ai/sandboxes"},{destination:"external",icon:DH,label:"GitHub",url:"https://github.com/openpond/openpond"},{destination:"external",icon:gu,label:"Submit issue",url:"https://github.com/openpond/openpond/issues/new/choose"}];function NB({onOpenWalkthroughs:e,onCloseAccount:t,walkthroughsActive:n}){const[a,s]=h.useState(!1),r=h.useRef(null),i=h.useRef(null);h.useLayoutEffect(()=>{a&&i.current?.querySelector('[role="menuitem"]')?.focus()},[a]);function c(){s(!0)}function u(){s(!1),r.current?.focus()}return g.jsxs("div",{className:"user-auth-help",onKeyDown:l=>{a&&(l.key==="Escape"||l.key==="ArrowLeft")&&(l.preventDefault(),l.stopPropagation(),u())},children:[g.jsxs("button",{ref:r,type:"button",className:"user-auth-menu-link",role:"menuitem","aria-haspopup":"menu","aria-expanded":a,onClick:()=>a?u():c(),onKeyDown:l=>{l.key==="ArrowRight"&&(l.preventDefault(),c())},children:[g.jsx(HH,{size:15}),g.jsx("span",{children:"Help"}),g.jsx(pr,{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),y=l.key==="Home"?0:l.key==="End"?p.length-1:(f+(l.key==="ArrowDown"?1:-1)+p.length)%p.length;p[y]?.focus()},children:$B.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:y=>{y.preventDefault(),t(),DB(l.url)},children:f},l.label)})}):null]})}async function DB(e){const t=window.openpond?.browser;t?.openExternal&&(await t.openExternal({conversationId:"openpond-help",url:e})).ok||window.open(e,"_blank","noopener,noreferrer")}const Ub=new WeakMap,bf=new WeakMap;function bI(e){if(!e)return"disconnected";let t=Ub.get(e);return(!t||t.serverUrl!==e.serverUrl||t.token!==e.token)&&(t={serverUrl:e.serverUrl,token:e.token,id:crypto.randomUUID()},Ub.set(e,t)),t.id}function eG(e,t){return bf.set(e,t),e}function tG(e){if(!e)return["learning","disconnected"];let t=bf.get(e);return t||(t=["learning",crypto.randomUUID()],bf.set(e,t)),t}function LB(e,t){return x0({queryKey:["provider-plan-usage",bI(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 lp(e){return`${Math.floor(e)}%`}function qb(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 zB(e,t){return t?"Loading…":e?.status==="signed_out"?"Sign in":e?.status==="unsupported"?"Not available":"Unavailable"}function HB({connection:e,provider:t,compact:n=!1,onOpen:a}){const s=LB(e,t),r=s.data,i=r?.windows.filter(b=>b.shared)??[],c=!!r?.windows.some(b=>b.resetsAt&&Date.parse(b.resetsAt)<=Date.now()),u=s.isError||c||!!(r&&Date.parse(r.refreshAfter)+6e4<Date.now()),l=t==="claude-code"?"Claude":"Codex",p=r?.status==="ready",f=zB(r,s.isPending&&!!e),y=r?.windows.map(b=>`${b.label}: ${lp(b.remainingPercent)} remaining. ${qb(b)}.`).join(`
|
|
111
|
+
`);return n?g.jsxs("button",{type:"button",role:"menuitem",className:"plan-usage-compact",onClick:a,title:u?`Usage needs refreshing. ${y??""}`:y||r?.message||"View plan usage in Providers",children:[g.jsx("span",{children:l}),g.jsx("span",{className:"plan-usage-compact-values",children:!u&&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:lp(b.remainingPercent)})]},b.id)):g.jsx("strong",{children:u?"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||s.isFetching,onClick:()=>{s.refetch()},children:g.jsx($w,{size:13,className:s.isFetching?"settings-spin":void 0})})}),p?g.jsxs(g.Fragment,{children:[r.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:[lp(b.remainingPercent),u?" · 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:qb(b)})]},b.id)),u?g.jsxs("small",{role:"status",children:["Usage needs refreshing. Last checked ",new Date(r.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:s.isError?"Could not load usage. Try refreshing.":r?.message??(e?"Loading plan usage…":"Connect to load plan usage.")})]})}function UB(...e){for(const t of e){const n=t?.trim();if(n)return n}return null}function qB(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"?UB(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 BB({connection:e,onOpenProviders:t,account:n,open:a,organizations:s,selectedTeamId:r,onOpenActivity:i,onOpenChange:c,onOpenSettings:u,onOpenWalkthroughs:l,walkthroughsActive:p,onSelectTeam:f,onLogOut:y,railTooltip:b}){const[I,C]=h.useState(null),[P,_]=h.useState(!1),M=h.useRef(null),A=h.useMemo(()=>qB(n),[n]),T=A.label.trim().slice(0,1).toUpperCase(),S=s.find(w=>w.teamId===r)??s[0]??null;return h.useEffect(()=>{if(!a)return;function w(O){M.current?.contains(O.target)||c(!1)}function R(O){O.key==="Escape"&&c(!1)}return document.addEventListener("pointerdown",w),document.addEventListener("keydown",R),()=>{document.removeEventListener("pointerdown",w),document.removeEventListener("keydown",R)}},[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(bb,{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(bb,{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]})]}),s.length>0&&f?g.jsxs("label",{className:"user-auth-team-picker",children:[g.jsx(og,{size:15,"aria-hidden":"true"}),g.jsx("span",{className:"user-auth-team-picker-label",children:"Team"}),g.jsx("select",{"aria-label":"Active team",disabled:I!==null,value:S?.teamId??"",onChange:async w=>{const R=w.currentTarget.value;C(R);try{await f(R)}catch{}finally{C(null)}},children:s.map(w=>g.jsx("option",{value:w.teamId,children:w.displayName},w.teamId))})]}):null,g.jsx("div",{className:"user-auth-plan-usage",children:["claude-code","codex"].map(w=>g.jsx(HB,{connection:e,provider:w,compact:!0,onOpen:()=>{c(!1),t()}},w))}),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(Aw,{size:15}),g.jsx("span",{children:"Activity"})]}):null,g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",onClick:()=>{c(!1),u()},children:[g.jsx(Nw,{size:15}),g.jsx("span",{children:"Settings"})]}),g.jsx(NB,{onOpenWalkthroughs:l,walkthroughsActive:p,onCloseAccount:()=>c(!1)}),n?.state==="signed_in"&&y?g.jsxs("button",{type:"button",className:"user-auth-menu-link",role:"menuitem",disabled:P,onClick:async()=>{_(!0);try{await y(),c(!1)}catch{}finally{_(!1)}},children:[g.jsx(tU,{size:15}),g.jsx("span",{children:P?"Logging out…":"Log out"})]}):null]}):null]})}function FB({sidebar:e,open:t}){const[n,a]=h.useState(!1),s=[{view:"chat",label:"Home",Icon:zw},{view:"scheduled",label:"Workflows",Icon:Tw},{view:"outputs",label:"Outputs",Icon:Ew},{view:"apps",label:"Apps",Icon:og},{view:"projects",label:"Projects",Icon:ng}];async function r(c){if(a(!1),e.productArea==="chat"&&e.view===c){c==="chat"&&e.setSidebarOpen(!t);return}const u=c==="chat"?{kind:"chat",sessionId:e.selectedSessionId}:{kind:"view",view:c};await Dt(u)&&(e.setSectionMenuOpen(null),e.setView(c),c==="chat"&&e.setSidebarOpen(!0))}async function i(){await Dt({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(kU,{size:19})}),s.map(({view:c,label:u,Icon:l})=>{const p=e.productArea==="chat"&&e.view===c;return g.jsx("button",{type:"button","data-rail-tooltip":u,"aria-label":u,"aria-current":p?"page":void 0,"aria-expanded":c==="chat"?p&&t:void 0,className:`desktop-rail-button${p?" active":""}`,onClick:()=>{r(c)},children:g.jsx(l,{size:19})},c)}),[{view:"team",label:"Team chat",Icon:gu,onOpen:e.onOpenTeamChat},{view:"community",label:"Discover communities",Icon:Mw,onOpen:e.discoverCommunities}].map(({view:c,label:u,Icon:l,onOpen:p})=>g.jsx("button",{type:"button","data-rail-tooltip":u,"aria-label":u,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(BB,{account:e.account,open:n,onOpenChange:a,connection:e.connection,onOpenProviders:()=>{Dt({kind:"settings",section:"providers"})},railTooltip:n?void 0:"Account",organizations:e.organizations,selectedTeamId:e.teamChatOrganization?.teamId??null,onSelectTeam:e.onSelectTeam,onLogOut:e.onLogOut,walkthroughsActive:e.view==="get-started",onOpenWalkthroughs:()=>{i()},onOpenActivity:()=>{Dt({kind:"settings",section:"usage"})},onOpenSettings:()=>{Dt({kind:"settings",section:"account"})}})})]})}const VB=[/^(?:(?:type)?error:\s*)?failed to fetch\.?$/i,/^networkerror when attempting to fetch resource\.?$/i,/^load failed\.?$/i];function yI(e,t="Something went wrong."){const a=(e instanceof Error?e.message:String(e??"")).trim();return a?SI(a)?"Couldn’t connect to OpenPond.":a:t}function SI(e){const t=e.trim();return VB.some(n=>n.test(t))}const xI=h.createContext(null);function Bb({children:e,showToast:t}){return g.jsx(xI.Provider,{value:t,children:e})}function KB(){return h.useContext(xI)}function Fb(e,t={}){const n=KB(),a=h.useRef(null),s=t.enabled??!0,r=t.fallback??"Something went wrong.",i=t.prefix?.trim()??"",c=e==null||e===""?null:`${i}${i?": ":""}${yI(e,r)}`;h.useEffect(()=>{if(!s||!c){a.current=null;return}a.current!==c&&(a.current=c,n?.(c,"error"))},[s,c,n])}function WB({state:e,onClose:t,onOpenBrowserUrl:n,onStart:a}){if(Fb(e?.previewError,{prefix:"Upload preview"}),Fb(e?.error,{prefix:"Cloud setup"}),!e)return null;const s=e.status==="uploading",r=e.status==="ready",i=e.status==="error",c=e.projectKind==="cloud",u=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:s,type:"button",onClick:t,"aria-label":"Close Cloud setup",title:"Close",children:g.jsx(Jc,{size:14})}),g.jsx("div",{className:"git-dialog-icon",children:r?g.jsx(td,{size:18}):g.jsx(hu,{size:18})}),g.jsx("h2",{children:r?"Cloud repo ready":"Set up Cloud coding"}),g.jsx("p",{children:r?"Your source is ready in OpenPond Git. Finish by creating the Cloud sandbox environment.":c?"This Cloud Project is ready for a sandbox environment.":"OpenPond will upload tracked and unignored files into OpenPond Git, then send you to the Cloud sandbox setup page."}),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:u?.branch??e.branch??"main"})]}),!c&&g.jsxs("div",{className:"git-dialog-row",children:[g.jsx("span",{children:"Cloud project"}),g.jsx("strong",{children:u?.targetProjectId??e.cloudProjectId??"New on upload"})]})]}),!r&&!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."})]}):u?g.jsxs(g.Fragment,{children:[g.jsx("strong",{children:u.initializedEmptyProject?"Will initialize an empty project":`Will upload ${u.fileCount} files`}),g.jsx("span",{children:Vb({byteCount:u.byteCount,skippedCount:u.skippedCount,headCommit:u.headCommit,targetProjectName:u.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."})]})}),s&&g.jsxs("div",{className:"cloud-setup-progress",role:"status","aria-live":"polite",children:[g.jsx(ag,{className:"cloud-setup-spinner",size:16}),g.jsx("span",{children:"Uploading source to OpenPond Git..."})]}),r&&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:Vb({byteCount:e.upload.byteCount,skippedCount:e.upload.skippedCount,headCommit:e.upload.headCommit,targetProjectName:e.upload.branch})})]}),r&&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=>dp(l,e.projectUrl,n,{newTab:!0}),children:["Project page",g.jsx(tp,{size:13})]})]}):g.jsx("span",{children:"Your repo is ready. Next step:"}),g.jsxs("a",{href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:l=>dp(l,e.setupUrl,n),children:["Setup the Cloud sandbox",g.jsx(tp,{size:13})]})]}),g.jsxs("div",{className:"git-dialog-footer",children:[g.jsx("button",{className:"git-dialog-secondary",disabled:s,type:"button",onClick:t,children:r?"Done":"Cancel"}),r?e.setupUrl?g.jsxs("a",{className:"git-dialog-primary cloud-setup-primary-link",href:e.setupUrl,target:"_blank",rel:"noreferrer",onClick:l=>dp(l,e.setupUrl,n),children:["Open setup",g.jsx(tp,{size:13})]}):null:g.jsx("button",{className:"git-dialog-primary",disabled:s,type:"button",onClick:a,children:s?"Uploading":i?"Try again":c?"Show setup link":"Upload source"})]})]})})}function dp(e,t,n,a={}){!t||!n||(e.preventDefault(),n(t,a))}function GB(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 Vb({byteCount:e,skippedCount:t,headCommit:n,targetProjectName:a}){const s=[GB(e),`${t} skipped`],r=ZB(n);return r&&s.push(`local ${r}`),s.push(a),s.join(" · ")}function ZB(e){const t=e?.trim();return t?t.slice(0,7):null}const JB=h.lazy(()=>fr(()=>import("./CommandMenu-B-w53n9A.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.CommandMenu}))),QB=h.lazy(()=>fr(()=>import("./SettingsView-T1vYDPjh.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}))),YB=h.lazy(()=>fr(()=>import("./NewProjectDialog-D8sy1gOz.js"),__vite__mapDeps([26,1,2,11,17,27])).then(e=>({default:e.NewProjectDialog}))),XB=h.lazy(()=>fr(()=>import("./WorkspaceGitDialogs-DrVtapQQ.js"),__vite__mapDeps([28,1,2,14,15,29,25])).then(e=>({default:e.CommitDialog}))),e4=h.lazy(()=>fr(()=>import("./WorkspaceGitDialogs-DrVtapQQ.js"),__vite__mapDeps([28,1,2,14,15,29,25])).then(e=>({default:e.BranchDialog})));function t4({payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:s,onError:r,onToast:i,onBack:c,onOpenSourceSession:u,onStartRefinerAuthoring:l,onAcceptEvaluationReview:p,onOpenSkill:f,onOpenExtension:y,teamChatCurrentUserId:b,teamChatEnabled:I,teamChatNotificationMode:C,teamChatThreads:P,onTeamChatNotificationModeChange:_,onTeamChatThreadMuteChange:M,diffPanelWidth:A,diffPanelResizing:T,diffPanelExpanded:S,onDiffPanelResizeStart:w,onDiffPanelExpandedChange:R}){return g.jsx(h.Suspense,{fallback:null,children:g.jsx(QB,{payload:e,connection:t,diagnostics:n,initialSection:a,onPayload:s,onError:r,onToast:i,onBack:c,onOpenSourceSession:u,onStartRefinerAuthoring:l,onAcceptEvaluationReview:p,onOpenSkill:f,onOpenExtension:y,teamChatCurrentUserId:b,teamChatEnabled:I,teamChatNotificationMode:C,teamChatThreads:P,onTeamChatNotificationModeChange:_,onTeamChatThreadMuteChange:M,diffPanelWidth:A,diffPanelResizing:T,diffPanelExpanded:S,onDiffPanelResizeStart:w,onDiffPanelExpandedChange:R})})}function n4({activeSessions:e,branchDialogName:t,branchDialogOpen:n,commitDialogOpen:a,commitDraft:s,commitIncludeUnstaged:r,commitMessage:i,commitNextStep:c,canPublishOpenPondProject:u,expandProject:l,newProjectBusy:p,newProjectDialogOpen:f,newProjectDirectory:y,newProjectMode:b,newProjectName:I,newProjectPath:C,projectRows:P,query:_,searchOpen:M,visibleWorkspaceDiff:A,visibleWorkspaceState:T,workspaceBusy:S,appDispatch:w,beginNewChat:R,openDefaultsSettingsFromBranchDialog:O,setBranchDialogName:z,setBranchDialogOpen:$,setCommitDialogOpen:V,setCommitDraft:Y,setCommitIncludeUnstaged:se,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(JB,{open:M,query:_,projects:P,sessions:e,onQueryChange:B,onClose:()=>{ne(!1),B("")},onNewChat:()=>{ne(!1),B(""),R()},onOpenProject:ve=>{w({type:"selectProject",projectId:ve.id}),w({type:"patch",patch:{searchOpen:!1,query:""}}),l(ve.id)},onOpenSession:ve=>{w({type:"selectSession",sessionId:ve.id,appId:ve.appId,projectId:ve.workspaceKind==="local_project"&&ve.workspaceId?it("local",ve.workspaceId):null}),w({type:"patch",patch:{searchOpen:!1,query:""}})}})}),f&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(YB,{open:f,mode:b,name:I,path:C,directory:y,busy:p,onNameChange:J,onPathChange:K,onClose:()=>{p||F(!1)},onSubmit:oe})}),a&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(XB,{open:a,branch:T?.currentBranch??null,filesChanged:A?.filesChanged??T?.changedFilesCount??0,additions:A?.additions??0,deletions:A?.deletions??0,message:i,includeUnstaged:r,nextStep:c,draft:s,busy:S,canPush:!!T?.remoteUrl,canPublish:u,onMessageChange:ee,onIncludeUnstagedChange:se,onNextStepChange:H,onDraftChange:Y,onClose:()=>{S||V(!1)},onSubmit:G})}),n&&g.jsx(h.Suspense,{fallback:null,children:g.jsx(e4,{open:n,branchName:t,busy:S,onBranchNameChange:z,onSetPrefix:O,onClose:()=>{S||$(!1)},onSubmit:te})})]})}function kI({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 zl(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(nO.parse(t)),signal:n})}function Kb(e,t,n){const a=ux.parse(e);if(a.scope!==t.scope||a.id!==n)throw new Error("Review response identity differs from the requested assignment.");return a}const a4={inbox:async(e,t,n)=>s4(await zl(e,{...t,endpoint:"inbox",scope:e.scope},n),e),get:async(e,t,n)=>Kb(await zl(e,{endpoint:"get",scope:e.scope,id:t},n),e,t),inspect:async(e,t,n,a,s)=>r4(await zl(e,{endpoint:"inspect",scope:e.scope,id:t,...n===void 0?{}:{slot:n},...a?{afterId:a}:{}},s),t),command:async(e,t)=>Kb(await zl(e,{endpoint:"command",scope:e.scope,command:t}),e,t.id)};function s4(e,t){const n=BM.parse(e);if(n.items.some(a=>a.scope!==t.scope))throw new Error("Inbox response belongs to another workspace.");return n}function r4(e,t){const n=aO.parse(e);if(n.some(a=>a.reviewId!==t))throw new Error("Evidence response belongs to another assignment.");return n}function o4({context:e,onOpen:t}){const[n,a]=h.useState(null);return h.useEffect(()=>{const s=new AbortController;let r=0;async function i(){const u=++r;try{const l=await a4.inbox(e,{view:"mine",status:"active",limit:1},s.signal);!s.signal.aborted&&u===r&&a(l.actionCount)}catch{!s.signal.aborted&&u===r&&a(null)}}a(null),i();const c=window.setInterval(()=>{document.visibilityState==="visible"&&i()},15e3);return window.addEventListener("human-review-changed",i),()=>{s.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(ig,{size:17,"aria-hidden":"true"}),n?g.jsx("span",{className:"human-review-inbox-count","aria-hidden":"true",children:n>99?"99+":n}):null]})}function i4({connection:e,teamId:t,actorId:n,projectId:a}){if(!e||!t||!n)return null;const s=()=>{Br(ka("inbox",null,{area:"console",projectId:a}))};return g.jsx(o4,{context:{connection:e,scope:t,actorId:n,location:"hosted"},onOpen:s})}const Yc=h.createContext(null);function c4({children:e}){const[t,n]=h.useState(null),[a,s]=h.useState(null),[r,i]=h.useState(null),c=h.useMemo(()=>({title:t,actions:a,activity:r,setTitle:n,setActions:s,setActivity:i}),[t,a,r]);return g.jsx(Yc.Provider,{value:c,children:e})}function nG({children:e}){return g.jsx(Yc.Provider,{value:null,children:e})}function l4({children:e,className:t=""}){const n=h.useContext(Yc);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 d4({className:e=""}){const t=h.useContext(Yc);return g.jsx("div",{ref:t?.setActions,className:e})}function aG({title:e,actions:t,fallback:n,children:a}){const s=h.useContext(Yc);return s?g.jsxs(g.Fragment,{children:[s.title?Md.createPortal(g.jsx("div",{className:"page-chrome-title",children:e}),s.title):null,s.actions&&t?Md.createPortal(t,s.actions):null,a]}):n??g.jsxs("header",{children:[e,t]})}const u4=h.lazy(()=>fr(()=>import("./WorkspaceEnvironmentMenu-c1pHDskn.js"),__vite__mapDeps([30,1,2,21,27,12,15,31,29,32])).then(e=>({default:e.WorkspaceEnvironmentMenu})));function m4({sidebarOpen:e,sidebarAvailable:t=!0,title:n,breadcrumbs:a,backAction:s,workspaceName:r,workspaceId:i,busy:c,workspaceState:u,workspaceKind:l,selectedApp:p,selectedProject:f,workspaceDiff:y,managedWorkspace:b,workspaceBusy:I,defaultTeamId:C,activityActorId:P,activityProjectId:_,showDiffControls:M,diffPanelOpen:A,terminalOpen:T,rightSidebarAvailable:S=!1,rightSidebarOpen:w=!1,onToggleDiffPanel:R,onToggleRightSidebar:O,onOpenSearch:z,onToggleTerminal:$,onRunTerminalCommand:V,onWorkspaceToolAction:Y,onOpenCommitDialog:se,onWorkspaceBranchChange:ee,onWorkspaceBranchCreate:H,connection:F,onBootstrap:J,onOpenSandboxWorkspace:K,onShowSidebar:B,platform:ne,showWorkspaceControls:G=!0}){const te=y?.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(Ow,{size:16})}),s?g.jsx("button",{className:"titlebar-icon",type:"button","aria-label":s.label,title:s.label,onClick:s.onSelect,children:g.jsx(dH,{size:16})}):null,g.jsx(l4,{children:a?.length?g.jsx("nav",{className:"titlebar-breadcrumbs","aria-label":"Breadcrumb",children:a.map((oe,ve)=>{const me=ve===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(pr,{size:14})]},`${oe.label}-${ve}`)})}):g.jsxs("div",{className:"titlebar-title",children:[g.jsx("strong",{children:n}),r&&g.jsx("span",{children:r})]})})]}),g.jsxs("div",{className:"titlebar-right",children:[g.jsx(d4,{className:"page-chrome-actions"}),g.jsx(i4,{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(u4,{mode:"topbar",busy:c,workspaceState:u,workspaceId:i,workspaceKind:l,selectedApp:p,selectedProject:f,workspaceBusy:I,defaultTeamId:C,workspaceDiff:y,managedWorkspace:b,showDiffControls:M,diffPanelOpen:A,onToggleDiffPanel:R,onRunTerminalCommand:V,onWorkspaceToolAction:Y,onOpenCommitDialog:se,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(oU,{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(Dw,{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(rf,{size:16})})]}),S&&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(rf,{size:16})})}):null,g.jsx(yU,{platform:ne})]})]})}function p4(){const[e,t]=h.useState(null),n=h.useRef(null),a=h.useCallback(r=>new Promise(i=>{n.current?.resolve(!1);const c={...r,cancelLabel:r.cancelLabel??"Cancel",tone:r.tone??"default",resolve:i};n.current=c,t(c)}),[]),s=h.useCallback(r=>{const i=n.current;n.current=null,t(null),i?.resolve(r)},[]);return{confirmAction:a,confirmDialog:e,resolveConfirmDialog:s}}function f4({state:e,onResolve:t}){const n=h.useId(),a=h.useId();if(h.useEffect(()=>{if(!e)return;function r(i){i.key==="Escape"&&t(!1)}return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,e]),!e)return null;const s=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:r=>r.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:s,autoFocus:!0,onClick:()=>t(!0),children:e.confirmLabel})]})]})})}function h4(){const{confirmAction:e,confirmDialog:t,resolveConfirmDialog:n}=p4();return{confirmProjectAction:h.useCallback(s=>e({tone:"danger",...s}),[e]),projectConfirmDialog:t,resolveProjectConfirmDialog:n}}function g4({state:e,onResolve:t}){return g.jsx(f4,{state:e,onResolve:t})}const $d=new Map,v4=(e,t,n)=>{const a=$d.get(e)??{commits:0,maxActualDurationMs:0,totalActualDurationMs:0};a.commits+=1,a.maxActualDurationMs=Math.max(a.maxActualDurationMs,n),a.totalActualDurationMs+=n,$d.set(e,a)};function b4({children:e,id:t}){return g.jsx(h.Profiler,{id:t,onRender:v4,children:e})}typeof window<"u"&&(window.__OPENPOND_RENDER_COMMITS__={get:()=>Object.fromEntries([...$d.entries()].map(([e,t])=>[e,{...t}])),reset:()=>$d.clear()});const y4=h.lazy(()=>fr(()=>import("./MainPane-D3ojiN-p.js").then(e=>e.q),__vite__mapDeps([33,1,2,9,14,34,31,11,12,35])).then(e=>({default:e.MainPane})));function S4({className:e,style:t,sidebar:n,topBar:a,mainPane:s,cloudSetup:r,projectConfirm:i,lazyPanels:c,toast:u}){return g.jsx(c4,{children:g.jsxs("div",{className:e,style:t,children:[g.jsx(FB,{sidebar:n,open:a.sidebarOpen}),a.sidebarAvailable!==!1?g.jsxs(b4,{id:"sidebar",children:[g.jsx(MB,{...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(m4,{...a}),g.jsx(h.Suspense,{fallback:g.jsx("main",{className:"main-pane","aria-busy":"true","aria-label":"Loading workspace"}),children:g.jsx(y4,{...s})})]}),g.jsx(WB,{...r}),g.jsx(g4,{...i}),g.jsx(n4,{...c}),g.jsx(kI,{...u})]})})}function x4({settings:e,toast:t}){return g.jsxs(g.Fragment,{children:[g.jsx(t4,{...e}),g.jsx(kI,{...t})]})}const ld="OpenPond".split("");function k4({visibleLetterCount:e=ld.length}){const t=ld.slice(0,Math.max(0,Math.min(e,ld.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:wg})}),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 up=ld.length,w4=520,I4=240;function Wb(){return typeof window>"u"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function _4({startup:e}){const[t,n]=h.useState(()=>Wb()?up:0);return h.useEffect(()=>{if(Wb()){n(up);return}const a=Array.from({length:up},(s,r)=>window.setTimeout(()=>n(r+1),w4+I4*r));return()=>{a.forEach(s=>window.clearTimeout(s))}},[]),g.jsxs("main",{className:"app-splash","aria-busy":"true","aria-label":e.label,role:"status",children:[g.jsx(k4,{visibleLetterCount:t}),g.jsx("span",{className:"app-splash-status",children:e.label})]})}const _g=5e3;function ei(e,t){if(e.length===0)return t;if(t.length===0)return e;const n=new Set,a=[];for(const s of[...e,...t])n.has(s.id)||(n.add(s.id),a.push(s));return a}function Ns(e,t,n=_g){return dd(ei(e,t),n)}function dd(e,t=_g){return e.length<=t?e:e.slice(e.length-t)}function C4(e,t){if(t.length===0)return dd(e);if(e.length===0)return dd(t);const n=new Map;let a=0;for(const s of[...e,...t])n.has(s.id)||n.set(s.id,{event:s,index:a}),a+=1;return dd([...n.values()].sort((s,r)=>P4(s,r)).map(({event:s})=>s))}function yf(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 R4(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function P4(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 s=Date.parse(e.event.timestamp),r=Date.parse(t.event.timestamp);if(Number.isFinite(s)&&Number.isFinite(r)){const i=s-r;if(i!==0)return i}return e.index-t.index}function Gb(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 T4(e){return e===null?"unknown":e>=85?"high":e>=65?"medium":"low"}function A4(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 Zb(e){return e==="codex"||e==="claude-code"}function E4(e){return e==="openpond"}function wI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="session.context.updated")continue;const a=zE.safeParse(n.data);if(a.success)return a.data}return null}function II(e){if(e.snapshot&&e.snapshot.provider===e.provider){const n=e.snapshot.usedTokens,a=e.snapshot.maxContextTokens,s=Math.min(100,Math.round(e.snapshot.percentFull)),r=`${s}% full`,i=`${Gb(n)} / ${Gb(a)} tokens used`,c=Zb(e.provider)?`Context and compaction are managed by ${e.provider==="claude-code"?"Claude Code":"Codex app-server"}.`:A4(e.preferences,s);return{usedTokens:n,maxTokens:a,percent:s,summary:r,tokensLabel:i,detail:c,tooltip:`Context window: ${r} ${i}. ${c}`,tone:T4(s)}}if(Zb(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(!E4(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 Cg(e){let t=!1;const n=_I(e);for(let a=e.length-1;a>=0;a-=1){const s=e[a];if(j4(s)){t=!0;continue}const r=mi(s?.data);if(!(s?.name!=="diagnostic"||!r)){if(r.kind==="thread_goal_cleared")return null;if(r.kind==="thread_goal"){const i=Rg(mi(r.goal),Jn(r.provider),n);if(i){const c=$c(i);return t&&c.tone==="active"?null:c}}if(r.kind==="goal_context"){const i=RI(s.output??"",Jn(r.provider)??"codex",n);if(i){const c=$c(i);return t&&c.tone==="active"?null:c}}}}return null}function Nd(e){const t=_I(e);for(let n=e.length-1;n>=0;n-=1){const a=e[n],s=mi(a?.data);if(!(a?.name!=="diagnostic"||!s)){if(s.kind==="thread_goal_cleared"&&s.synthetic!==!0)return null;if(s.kind==="thread_goal"){const r=Rg(mi(s.goal),Jn(s.provider),t);if(!r)continue;const i=$c(r);return i.tone==="active"?i:null}if(s.kind==="goal_context"){const r=RI(a.output??"",Jn(s.provider)??"codex",t);if(!r)continue;const i=$c(r);return i.tone==="active"?i:null}}}return null}function mp(e){const t=mi(mi(e)?.codexGoalRuntime),n=Rg(t,Jn(t?.provider)??"codex");if(!n)return null;const a=$c(n);return a.tone==="active"?a:null}function j4(e){return e?.name==="turn.completed"||e?.name==="turn.interrupted"||e?.name==="turn.failed"}function $c(e){const t=PI(e.status),n=EI(e.timeUsedSeconds),a=`Goal ${n}`,s=e.tokensUsed===null?null:e.tokenBudget===null?`${pp(e.tokensUsed)} tokens`:`${pp(e.tokensUsed)} / ${pp(e.tokenBudget)} tokens`,r=s?`${e.statusLabel} · ${s}`:e.statusLabel;return{objective:e.objective,status:e.status,timeUsedSeconds:e.timeUsedSeconds,tokensUsed:e.tokensUsed,tokenBudget:e.tokenBudget,actionLabel:t.actionLabel,timeLabel:n,label:a,detail:r,tooltip:`Goal runtime: ${jI(e.timeUsedSeconds)}. ${r}. ${e.objective}`,tone:t.tone,observedAt:e.observedAt}}function M4(e,t){if(!e||e.tone!=="active"||!e.observedAt)return e;const n=CI(e.observedAt,t);if(n<=0)return e;const a=e.timeUsedSeconds+n,s=EI(a);return{...e,timeUsedSeconds:a,timeLabel:s,label:`Goal ${s}`,tooltip:`Goal runtime: ${jI(a)}. ${e.detail}. ${e.objective}`,observedAt:t}}function Rg(e,t=null,n=null){if(!e)return null;const a=Jn(e.objective)??"Active goal",s=Jn(e.status)??"active";if((Sf(t)??Sf(Jn(e.provider)))!=="codex")return null;const i=n??Jn(e.updatedAt)??Jn(e.updated_at)??null,c=jo(e.timeUsedSeconds)??jo(e.time_used_seconds)??0,u=Jn(e.activeSinceAt)??Jn(e.active_since_at),l=PI(s).tone==="active"?CI(u??Jn(e.createdAt)??Jn(e.created_at),i):0,p=u?c+l:Math.max(c,l),f=jo(e.tokensUsed)??jo(e.tokens_used),y=jo(e.tokenBudget)??jo(e.token_budget);return{objective:a,status:s,statusLabel:AI(s),timeUsedSeconds:Math.max(0,Math.floor(p)),tokensUsed:f===null?null:Math.max(0,Math.floor(f)),tokenBudget:y===null?null:Math.max(0,Math.floor(y)),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 CI(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 RI(e,t=null,n=null){if(!e.trim()||Sf(t)!=="codex")return null;const a=TI(e,"Status")??"active",s=Zi(e,"Tokens used"),r=Zi(e,"Token budget"),i=Zi(e,"Time used seconds")??Zi(e,"Time spent pursuing goal")??Zi(e,"Elapsed seconds")??0;return{objective:Jb(e,"objective")??Jb(e,"untrusted_objective")??"Active goal",status:a,statusLabel:AI(a),timeUsedSeconds:Math.max(0,Math.floor(i)),tokensUsed:s,tokenBudget:r,observedAt:n}}function PI(e){switch(O4(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 O4(e){return e.trim().toLowerCase().replace(/[-\s]+/g,"_")}function TI(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\s*-?\\s*${n}:\\s*(.+?)\\s*$`,"im").exec(e)?.[1]?.trim()||null}function Zi(e,t){const n=TI(e,t);if(!n)return null;const a=n.replace(/,/g,""),s=/-?\d+(?:\.\d+)?/.exec(a);if(!s)return null;const r=Number(s[0]);return Number.isFinite(r)?r:null}function Jb(e,t){return new RegExp(`<${t}>\\s*([\\s\\S]*?)\\s*<\\/${t}>`,"i").exec(e)?.[1]?.trim()||null}function AI(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function EI(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 jI(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 pp(e){if(e<1e3)return String(e);if(e>=1e6){const n=e/1e6;return n<10?`${Qb(n,2)}M`:n<100?`${Qb(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 Qb(e,t){return e.toFixed(t).replace(/\.?0+$/,"")}function mi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jn(e){return typeof e=="string"&&e.trim()?e.trim():null}function Sf(e){return e?.trim().toLowerCase()||null}function jo(e){return typeof e=="number"&&Number.isFinite(e)?e:null}const $4=new Set(["planning","applying_source","running_checks","evaluating","pushing_hosted","running_hosted_checks"]),N4=new Set(["awaiting_questions","awaiting_plan_approval","paused"]);function xf(e){const t=MI(e);return t?H4(t):null}function MI(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.name!=="create_improve.updated")continue;const a=z4(V4(n.data));if(a)return a}return null}function D4(e){if(e.events)return MI(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 L4(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 z4(e){const t=Hc.safeParse(e?.createImproveRun);return t.success?t.data:null}function H4(e){const t=U4(e);if(!t)return null;const n=q4(e.createdAt,e.updatedAt),a=e.blockedReason??B4(e.state);return{objective:e.objective,status:e.state,timeUsedSeconds:n,tokensUsed:null,tokenBudget:null,actionLabel:t.actionLabel,timeLabel:F4(n),label:t.actionLabel,detail:a,tooltip:`${t.actionLabel}: ${a}. ${e.objective}`,tone:t.tone}}function U4(e){const t=e.state,n=e.target.kind==="agent"?"Agent":"Work";return $4.has(t)?{tone:"active",actionLabel:`${n} running`}:N4.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 q4(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 B4(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function F4(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 V4(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function OI(e,t){if(!t)return null;const n=new Map,a=[];for(const T of e){if(!T.name.startsWith("subagent."))continue;const S=G4(T);S&&a.push(S);const w=W4(T);w?.parentSessionId===t&&n.set(w.id,w)}if(n.size===0)return null;const s=[...n.values()].sort((T,S)=>Mo(S).localeCompare(Mo(T))),r=s.filter(T=>T.status==="queued"||T.status==="running"),i=s.filter(T=>T.status==="completed"),c=s.filter(T=>T.status==="failed"),u=s.filter(T=>T.status==="cancelled"),l=s.filter(T=>T.status==="needs_resume"),p=[...i,...c,...u].sort((T,S)=>Mo(S).localeCompare(Mo(T))),f=s.reduce((T,S)=>{const w=pi(S.metadata?.usage);return T.totalTokens+=Ul(w?.totalTokens),T.promptTokens+=Ul(w?.promptTokens),T.completionTokens+=Ul(w?.completionTokens),T.requestCount+=Ul(w?.requestCount),T},{totalTokens:0,promptTokens:0,completionTokens:0,requestCount:0}),y=s.flatMap(T=>$I([...T.report?.blockers??[],T.error,T.progress.currentBlocker]).map(S=>({runId:T.id,roleId:T.roleId,status:T.status,message:S}))),b=s.flatMap(T=>NI([...T.report?.artifacts??[],T.report?.patchRef,T.report?.diffRef,...T.progress.patchRefs]).map(S=>({...S,runId:T.id,roleId:T.roleId}))),I=p.map(T=>K4(T,a)),C=s[0]??null,P=C?{runId:C.id,roleId:C.roleId,status:C.status,message:C.progress.latestMeaningfulActivity||C.report?.summary||C.objective,updatedAt:Mo(C)}:null,_=r.length>0?`${r.length} ${r.length===1?"child":"children"} running`:`${p.length} ${p.length===1?"child":"children"} finished`,M=[r.length?`${r.length} active`:null,i.length?`${i.length} completed`:null,c.length?`${c.length} failed`:null,u.length?`${u.length} cancelled`:null,l.length?`${l.length} paused`:null].filter(Boolean).join(" · "),A=P?`${Q4(P.roleId)}: ${P.message}`:"";return{sessionId:t,runs:s,activeRuns:r,completedRuns:i,failedRuns:c,cancelledRuns:u,needsResumeRuns:l,terminalRuns:p,latestRun:C,latestMeaningfulUpdate:P,activeCount:r.length,completedCount:i.length,failedCount:c.length,cancelledCount:u.length,needsResumeCount:l.length,terminalCount:p.length,usage:f,blockers:y,evidenceRefs:b,finalResults:I,testsRunCount:s.reduce((T,S)=>T+S.progress.validationAttempts.length,0),label:_,tooltip:[M,A].filter(Boolean).join(". ")}}function K4(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:NI([...e.report?.artifacts??[],e.report?.patchRef,e.report?.diffRef]),testsRun:e.report?.testsRun??[],validationAttempts:e.progress.validationAttempts.map(n=>n.command),blockers:$I([...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:Z4(e),updatedAt:Mo(e)}}function W4(e){const t=pi(e.data),n=[t?.run,pi(t?.message)?.run];for(const a of n){const s=hS.safeParse(a);if(s.success)return s.data}return null}function G4(e){const t=mE.safeParse(pi(e.data)?.message);return t.success?t.data:null}function Z4(e){const t=pi(pi(e.metadata?.workspaceHandoff)?.workspaceRetention);return t?.status!=="retained"?null:{status:"retained",reason:Hl(t.reason),retainedAt:Hl(t.retainedAt),expiresAt:Hl(t.expiresAt),retentionDays:J4(t.retentionDays),trigger:Hl(t.trigger),cleanupAfterExpiry:t.cleanupAfterExpiry===!0}}function Mo(e){return e.updatedAt??e.completedAt??e.startedAt??e.createdAt}function $I(e){return[...new Set(e.map(t=>t?.trim()).filter(t=>!!t))]}function NI(e){const t=new Map;for(const n of e)n&&t.set(`${n.kind}:${n.id}`,n);return[...t.values()]}function pi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Hl(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ul(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function J4(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Q4(e){return e.slice(0,1).toUpperCase()+e.slice(1).replace(/[-_]+/g," ")}const kf=[];function wf(e,t){return DI(e,t,null)}function DI(e,t,n){const a=n&&nF(n.events,e)?X4(n.indexes,n.events.length,e):Y4(e),s=tF(t);return{...a,...s}}function Y4(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 eF(t)}function X4(e,t,n){const a=new Map(e.eventsBySessionId),s=new Map(e.latestContextUsageBySessionId),r=new Map(e.latestGoalRuntimeBySessionId),i=new Map(e.latestSubagentRuntimeBySessionId),c=new Set(e.activeGoalSessionIds),u=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 y=a.get(f.sessionId);a.set(f.sessionId,y?[...y,f]:[f]),l.add(f.sessionId)}for(const p of l){const f=a.get(p)??kf,y=wI(f);y?s.set(p,y):s.delete(p);const b=zI(f);b?(r.set(p,b),b.tone==="active"?c.add(p):c.delete(p)):(r.delete(p),c.delete(p));const I=OI(f,p);I?(i.set(p,I),LI({sessionEvents:f,sessionId:p,latestGoalRuntimeBySessionId:r,activeGoalSessionIds:c}),I.activeCount>0?u.add(p):u.delete(p)):(i.delete(p),u.delete(p))}return{eventsBySessionId:a,latestContextUsageBySessionId:s,latestGoalRuntimeBySessionId:r,latestSubagentRuntimeBySessionId:i,activeGoalSessionIds:c,activeSubagentSessionIds:u}}function eF(e){const t=new Map,n=new Map,a=new Map,s=new Set,r=new Set;for(const[i,c]of e){const u=wI(c);u&&t.set(i,u);const l=zI(c);l&&(n.set(i,l),l.tone==="active"&&s.add(i))}for(const[i,c]of e){const u=OI(c,i);u&&(a.set(i,u),LI({sessionEvents:c,sessionId:i,latestGoalRuntimeBySessionId:n,activeGoalSessionIds:s}),u.activeCount>0&&r.add(i))}return{eventsBySessionId:e,latestContextUsageBySessionId:t,latestGoalRuntimeBySessionId:n,latestSubagentRuntimeBySessionId:a,activeGoalSessionIds:s,activeSubagentSessionIds:r}}function LI(e){if(e.latestGoalRuntimeBySessionId.has(e.sessionId))return;const t=Nd(e.sessionEvents);t&&(e.latestGoalRuntimeBySessionId.set(e.sessionId,t),t.tone==="active"&&e.activeGoalSessionIds.add(e.sessionId))}function zI(e){return xf(e)??Cg(e)??Nd(e)}function tF(e){const t=new Map,n=new Map,a=new Map,s=new Map;for(const r of e){t.set(r.id,r);const i=n.get(r.status);if(i?i.push(r):n.set(r.status,[r]),r.status!=="pending")continue;const c=a.get(r.sessionId);c?c.push(r):a.set(r.sessionId,[r]);const u=s.get(r.sessionId);(!u||Yb(r.createdAt)>Yb(u.createdAt))&&s.set(r.sessionId,r)}return{approvalsById:t,approvalsByStatus:n,pendingApprovalsBySessionId:a,latestPendingApprovalBySessionId:s}}function nF(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 Xc(e,t){return t?e.eventsBySessionId.get(t)??kf:kf}function HI(e,t){return t?e.latestContextUsageBySessionId.get(t)??null:null}function UI(e,t){return t?e.latestGoalRuntimeBySessionId.get(t)??null:null}function aF(e,t){return t?e.latestSubagentRuntimeBySessionId.get(t)??null:null}function sF(e,t){return t?e.latestPendingApprovalBySessionId.get(t)??null:null}function Yb(e){const t=Date.parse(e);return Number.isFinite(t)?t:Number.NEGATIVE_INFINITY}function rF(e,t){return e?.conversationId===t}function oF(e,t){return e?.id===t?null:e}function iF(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("/"),s=a>=0?n.relativePath.slice(0,a):"";for(const r of n.resourceFiles)t.add(s?`${s}/${r}`:r)}return{name:`${e.owner}/${e.repo}`,description:`${e.skills.length} installed skill${e.skills.length===1?"":"s"} from GitHub.`,scope:"extension",packagePath:e.sourcePath,files:[...t]}}function cF(e){return JSON.stringify([e.source,e.repositoryId,e.profileId])}function sG(e,t){return e.profiles.find(n=>cF(n.ref)===t)?.ref??null}function lF(e,t){return!!(e&&t&&e.source===t.source&&e.repositoryId===t.repositoryId&&e.profileId===t.profileId)}function rG(e,t){return e.profiles.find(n=>lF(n.ref,t))?.state??null}function dF(e,t){const n=new Map(Aj.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 s of a.skills)s.validationStatus!=="valid"||n.has(s.name)||n.set(s.name,{name:s.name,description:s.description,path:s.relativePath,scope:"profile",enabled:!0,sourcePath:a.sourcePath,charCount:s.charCount,sourceHash:s.sourceHash,validationStatus:"valid",validationMessages:[],resourceFiles:s.resourceFiles});return[...n.values()].sort((a,s)=>a.name.localeCompare(s.name))}function uF(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 oG(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 qI="openpond:last-chat-task-mode";function mF(e,t){return e==="labs"?"models":"chat"}function pF(e){try{return e.getItem(qI)==="work"?"work":"chat"}catch{return"chat"}}function Pg(){if(typeof window>"u")return"chat";try{return pF(eo)}catch{return"chat"}}function fF(e,t){try{e.setItem(qI,t==="chat"?"chat":"work")}catch{}}function hF(e){if(!(typeof window>"u"))try{fF(eo,e)}catch{}}const gF="uploaded to a different account";function BI(e,t){const n=e?.linkedSandboxProject??null;if(!n?.projectId||!n.teamId)return{state:"none",linked:null,cloudProject:null};const a=t?.find(s=>s.id===n.projectId&&s.teamId===n.teamId)??null;return a?{state:"confirmed",linked:n,cloudProject:a}:{state:"different_account",linked:n,cloudProject:null}}function Ca(e,t){const n=BI(e,t);return n.state==="confirmed"?n.cloudProject:null}function vF(e,t){return BI(e,t).state==="different_account"?gF:null}function ys(e){return e==="sandbox"||e==="sandbox_template"||e==="sandbox_app"}function FI(e={}){return{...e,workspaceTarget:"hybrid"}}function bF(e={}){return{...e,workspaceTarget:"local"}}function Ss(e){return e?.metadata?.workspaceTarget==="hybrid"}function yF(e){return!!(e&&e.provider==="openpond"&&e.workspaceKind==="local_project"&&e.cloudProjectId&&e.title.trim().endsWith(" Cloud"))}function VI({cloudProjects:e,selectedCloudProject:t,selectedProject:n}){const a=n?.linkedSandboxProject??null,s=e?Ca(n,e):null,r=t?.id??s?.id??(e?null:a?.projectId??null),i=t?.teamId??s?.teamId??(e?null:a?.teamId??null);return!r||!i?{kind:"missing_cloud_project",message:"Upload/sync this Project to Cloud before using Hybrid."}:{kind:"ready",cloudProjectId:r,cloudTeamId:i,cwd:n?.workspacePath??null,localProjectId:n?.id??null,workspaceName:t?.name??s?.name??a?.projectName??n?.name??"Hybrid workspace"}}function KI({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:FI(),cwd:n.cwd,title:a}}function SF(e){return h.useEffect(()=>{const t=tI(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=YU(n);try{let s;const r=e.selectedSession;if(r&&Mc(r))s=await Z.patchSession(e.connection,r.id,{title:a,metadata:op(r.metadata,n)}),e.setSessions(i=>i.map(c=>c.id===s.id?s:c));else{const i=r?.metadata?.workspaceTarget==="hybrid"?"hybrid":r?.metadata?.workspaceTarget==="local"?"local":null,c=r?.provider??(e.selectedCloudProject?"openpond":e.activeProvider),u=r?.modelRef??(c==="openpond"?{providerId:"openpond",modelId:si}:{providerId:c,modelId:e.activeModel}),l=i?{workspaceTarget:i}:!r&&e.workspaceTarget==="local"?{workspaceTarget:"local"}:{};let p;if(!r&&e.workspaceTarget==="hybrid"){const f=VI({cloudProjects:e.cloudProjects,selectedCloudProject:e.selectedCloudProject,selectedProject:e.selectedProject});if(f.kind!=="ready")throw new Error(f.message);const y=KI({modelRef:u,provider:c,target:f,title:a});p={...y,experience:"work",metadata:op(y.metadata,n)}}else p={experience:"work",provider:c,modelRef:u,openPondCommandAccessMode:r?.openPondCommandAccessMode??e.activeOpenPondCommandAccessMode,appId:r?.appId??null,appName:r?.appName??null,workspaceKind:r?.workspaceKind??(e.selectedCloudProject?"sandbox":e.selectedProject?"local_project":void 0),workspaceId:r?.workspaceId??e.selectedCloudProject?.id??e.selectedProject?.id??null,workspaceName:r?.workspaceName??e.selectedCloudProject?.name??e.selectedProject?.name??null,localProjectId:r?.localProjectId??e.selectedProject?.id??null,cloudProjectId:r?.cloudProjectId??e.selectedCloudProject?.id??null,cloudTeamId:r?.cloudTeamId??e.selectedCloudProject?.teamId??null,cwd:r?.cwd??e.selectedProject?.workspacePath??null,metadata:op(l,n),title:a};s=await Z.createSession(e.connection,p),e.setSessions(f=>[s,...f])}return e.composerDraftStore.set(""),e.setMentionedAppId(null),e.setSelectedSessionId(null),e.setView("chat"),e.requestComposerFocus(),e.showToast("Task draft saved.","success"),!0}catch(s){return e.showToast(s instanceof Error?s.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 xF=[];function kF({primary:e,secondary:t}){const[n,a]=h.useState(null),s=h.useRef(new Set),[r,i]=h.useState(!1),[c,u]=h.useState(null),l=jU(),p=l?.kind==="models"&&["home","inbox","datasets","graders","experiments"].includes(l.route.page),{composerDraftStore:f,appDispatch:y,pendingTerminalCommand:b,setPendingTerminalCommand:I,terminalTabs:C,setTerminalTabs:P,trainingDetailTasksetId:_,setTrainingDetailTasksetId:M,mentionedAppId:A,setMentionedAppId:T,cloudSetupDialog:S,setCloudSetupDialog:w,rightPanelTabRequest:R,workspaceDiffPanelViewState:O,mainComposerFocusRequestId:z,requestMainComposerFocus:$,projectConfirmDialog:V,resolveProjectConfirmDialog:Y,query:se,searchOpen:ee,archivedChatsOpen:H,sectionMenuOpen:F,cloudProjectsExpanded:J,sidebarOpen:K,view:B,selectedAppId:ne,selectedProjectId:G,selectedSessionId:te,codexPermissionMode:oe,codexReasoningEffort:ve,busy:me,diffPanelOpen:Re,diffPanelExpanded:Q,rightPanelMode:xe,activeExperience:je,changeNewExperience:De,terminalOpen:ze,settingsSection:we,newProjectDialogOpen:Me,newProjectMode:Te,newProjectName:N,newProjectPath:q,newProjectBusy:X,commitDialogOpen:U,commitMessage:ae,commitIncludeUnstaged:de,commitNextStep:be,commitDraft:Oe,branchDialogOpen:$e,branchDialogName:Ge,toast:bt,labDetailNavigation:ye,setQuery:Le,setSearchOpen:Ae,setArchivedChatsOpen:qe,setSectionMenuOpen:He,setCloudProjectsExpanded:vn,setChatRowsVisibleCount:jt,setSidebarOpen:pe,setView:fe,setSelectedAppId:Fe,setSelectedProjectId:Pe,setSelectedSessionId:Ne,setPrompt:rt,setDraftProvider:lt,setDraftModel:Tt,setDraftExperience:dt,setDiffPanelOpen:at,setDiffPanelExpanded:_t,setRightPanelMode:Be,setTerminalOpen:At,setSettingsSection:ln,setNewProjectDialogOpen:En,setNewProjectName:xt,setNewProjectPath:xs,setCommitDialogOpen:dn,setCommitMessage:bn,setCommitIncludeUnstaged:Ht,setCommitNextStep:Cn,setCommitDraft:yn,setBranchDialogOpen:Rn,setBranchDialogName:jn,setError:Ut,showToast:ft,applyBootstrapPayload:Un,applyPreferencesPayload:un,bootstrap:ut,connection:It,startup:Mt,training:mn,pinnedCollapsed:ra,cloudProjectsCollapsed:Ze,chatsCollapsed:Pn,savedForLaterCollapsed:Ga,sidebarWidth:Aa,sidebarResizing:Dn,diffPanelWidth:Tn,diffPanelResizing:Za,togglePinnedCollapsed:ks,toggleCloudProjectsCollapsed:Ea,toggleChatsCollapsed:ct,toggleSavedForLaterCollapsed:an,startSidebarResize:Ke,startDiffPanelResize:yt,selectedApp:Xt,selectedCloudProject:Ln,selectedProject:Sn,selectedProjectLinkedApp:D,selectedSession:ke,sidebarSessions:ie,runtimeIndexes:Je,runtimeEventStore:fa,chatMentionApps:qn,connectedAppMentions:ja,pendingApproval:xn,pendingChatUserMessages:to,account:ws,activeModel:Mn,activeProvider:oa,appDefaults:ha,startMessage:Is,organizations:kr,teamChatOrganization:wr,teamChatTeamId:Vs,teamChat:mt,publishTeamProfileAgent:ki,communitySidebar:Ir,communityView:wi,teamAiThreadId:no,toggleTeamAiSidebar:Ii,activeOpenPondCommandAccessMode:_s,viewWorkspaceAppId:_i,viewWorkspaceId:ao,viewWorkspaceKind:so,viewWorkspaceName:ro,selectedActionCatalog:Ci,expandedProjectIds:Ri,expandProject:Ja,toggleProjectExpanded:Pi,changeCodexPermissionMode:oo,changeCodexReasoningEffort:_r,changeOpenPondCommandAccessMode:Cr,resolveApproval:io,beginNewChat:ia,beginNewChatWithTrainingModel:Ti,dismissTrainingChatHandoff:Rr,trainingChatHandoff:Cs,selectTrainingChatTaskForComposer:Wn,chatHistoryLoadStates:Ai,loadMoreSelectedChatHistory:Ei,selectedPagedSessionEvents:kn,activeSessions:Ks,archivedSessions:Gn,pinnedSessions:Rs,savedForLaterSessions:Pr,savedForLaterFiles:Ws,sidebarFileBookmarks:ji,setSidebarFileStatus:co,setSessions:Tr,projectRows:Ps,localProjectRows:Ts,cloudProjectRows:Ar,projectSessionRowsByProjectId:lo,childSessionRowsByParentId:Gs,sidebarProjectIdBySessionId:Qa,chatRows:ga,visibleChatRows:uo,chatRowsVisibleCount:Zs,sessionEvents:Ya,goalRuntime:mo,subagentRuntime:Ma,visibleChatMessages:po,activeTerminalScope:Mi,terminalSummaries:fo,runningSessionIds:Oi,selectedSessionRunning:ho,sidebarGoalRuntimeBySessionId:go,sidebarSubagentRuntimeBySessionId:vo,taskDragSessionId:Er,taskPreviewSessionIds:bo,startTaskDrag:jr,clearTaskDrag:Xa,previewTaskDrop:$i,commitTaskDrop:Ni,commitTaskPreviewDrop:Di,dragItem:Li,startPinnedDrag:es,clearSidebarDrag:yo,previewPinnedDrop:zi,commitPinnedDrop:Hi,commitPinnedPreviewDrop:Ui,commandProjectRows:ca,contextWindowStatus:So,pinnedRows:et,workspaceBusy:Bt,diffBusy:ts,visibleWorkspaceState:sn,visibleWorkspaceDiff:zn,refreshVisibleWorkspaceDiff:On,managedWorkspace:Pu,canSyncActiveWorkspace:Tu,canPublishOpenPondProject:Au,projectTarget:Eu,workspaceTarget:tl}=e,{title:ju,browserConversationId:Mr,handleWorkspaceDiffPanelViewStateChange:nl,openSessionInChat:xo,changeProjectTarget:Mu,submitNewProjectDialog:Ou,changeWorkspaceBranch:$u,openCommitDialog:Nu,openCreateWorkspaceBranchDialog:Du,openDefaultsSettingsFromBranchDialog:Lu,runWorkspaceTool:zu,submitCommitDialog:Hu,submitCreateWorkspaceBranch:Uu,syncWorkspaceLocally:qu,answerCreateImproveQuestion:al,applyCreateImproveCandidate:Bu,approveCreateImproveRun:Fu,cancelCreateImproveRun:Vu,changeDraftProvider:qi,openCreateImprovePullRequest:sl,reconcileCreateImprovePullRequest:Ku,rejectCreateImproveCandidate:Wu,pauseCreateImproveRun:rl,resumeCreateImproveRun:ol,reviseCreateImproveRun:Gu,stopTurn:ko,archiveSession:Zu,restoreSession:il,renameSession:Ju,toggleSessionPinned:Bi,toggleProjectPinned:cl,toggleSessionSavedForLater:ll,moveProjectToCloud:Qu,startCloudSetupUpload:dl,changeWorkspaceTarget:Yu,sendPromptFromMainComposer:Xu,openSandboxWorkspace:ul,openCloudProjectDialog:em,openExistingProjectPathDialog:ml,openUrlInBrowserPanel:tm,showBrowserPanel:nm,showChangesPanel:am,showGoalSidebarTab:Js,rightChatTrainingLaunchRequest:pl,setRightChatTrainingLaunchRequest:sm,closeRightChatPanel:rm,openRightChatPanel:Fi,rightChatPanelViews:om,showRightChatPanel:im,showRightPanelDiffTab:cm,submitRightChatPrompt:lm,activateRightChatPanel:dm,updateRightChatModel:um,updateRightChatPrompt:mm,updateRightChatProvider:pm,updateRightChatScrollState:fm,openProfileSettings:hm,diagnosticEvents:gm,toggleRightSidebar:fl,removeProject:vm}=t;sC(It,ut?.account.activeProfile&&ut.preferences.defaultTeamId?JSON.stringify([ut.account.baseUrl,ut.account.activeProfile,ut.account.profile?.id,ut.account.state,ut.preferences.defaultTeamId]):null,()=>{Dt({kind:"chat",sessionId:null}).then(he=>{he&&(Ne(null),fe("chat"),a("activity"))})});const Oa=ut?.account.activeProfile&&ut?.preferences.defaultTeamId?`${ut.account.activeProfile.handle}:${ut.preferences.defaultTeamId}`:null;h.useEffect(()=>{if(!(!Oa||B!=="chat"||l?.kind!=="chat"||l.sessionId||te||s.current.has(Oa))){s.current.add(Oa);try{const he=localStorage.getItem(`openpond:ponder-mode:v1:${Oa}`);(he==="clean"||he==="activity")&&a(he)}catch{}}},[Oa,l,B,te]),h.useEffect(()=>{if(!(!Oa||!s.current.has(Oa)))try{localStorage.setItem(`openpond:ponder-mode:v1:${Oa}`,n??"off")}catch{}},[Oa,n]);const wo=h.useCallback(he=>{Fe(null),Pe(he),Ne(null),fe("chat"),Ja(he),$()},[Ja,$,Fe,Pe,Ne,fe]),bm=h.useCallback((he=null)=>{a(null);const Xe=te?Qa[te]??null:null;if(!he&&Xe){wo(Xe);return}ia(he)},[ia,wo,te,Qa]),ym=h.useCallback(async he=>{if(!(!It||!ut))try{const Xe=await Z.savePreferences(It,{defaultTeamId:he});un(Xe)}catch(Xe){const Ot=Xe instanceof Error?Xe.message:String(Xe);throw Ut(Ot),ft("Could not switch teams","error"),Xe}},[un,ut,It,Ut,ft]),Sm=h.useCallback(async()=>{if(It)try{const he=await Z.signOutOpenPondAccount(It);Un(he),ft("Logged out","success")}catch(he){const Xe=he instanceof Error?he.message:String(he);throw Ut(Xe),ft("Could not log out","error"),he}},[Un,It,Ut,ft]),Vi=Vs??ha.defaultTeamId??null,xm=h.useMemo(()=>Ps.filter(he=>he.kind==="local"||Vi!==null&&he.project.teamId===Vi),[Ps,Vi]),km=h.useMemo(()=>{const he={};for(const Xe of Ks){const Ot=Qa[Xe.id];Ot&&(he[Ot]=(he[Ot]??0)+1)}for(const Xe of Ts){if(Xe.kind!=="local")continue;const Ot=Xe.project.linkedSandboxProject?.projectId;if(!Ot||!Xe.cloudLinkTrusted)continue;const va=it("cloud",Ot);he[Xe.id]=(he[Xe.id]??0)+(he[va]??0)}return he},[Ks,Ts,Qa]),[hl,As]=h.useState(null),[Io,_o]=h.useState(null),wm=dF(ut?.profile,ut?.extensionCatalog),[Or,Ki]=h.useState(null),[Co,Wi]=h.useState(null),[ns,gl]=h.useState(null),Im=h.useCallback(async()=>{await Dt({kind:"view",view:"team"})&&(Fe(null),Pe(null),Ne(null),He(null),fe("team"))},[He,Fe,Pe,Ne,fe]),_m=h.useCallback(async()=>{await Dt({kind:"view",view:"community"})&&(Fe(null),Pe(null),Ne(null),He(null),Ir.discoverCommunities())},[Ir.discoverCommunities,He,Fe,Pe,Ne]),Cm=SF({activeExperience:je,activeModel:Mn,activeOpenPondCommandAccessMode:_s,activeProvider:oa,cloudProjects:ut?.cloudProjects??xF,composerDraftStore:f,connection:It,requestComposerFocus:$,selectedCloudProject:Ln,selectedProject:Sn,selectedSession:ke,setMentionedAppId:T,setSelectedSessionId:Ne,setSessions:Tr,setView:fe,showToast:ft,workspaceTarget:tl.value}),Rm=h.useCallback(async he=>{if(!It)throw new Error("OpenPond is not connected.");let Xe=oa,Ot=Mn;Xe==="codex"&&(Xe=gf(ut?.providers,{enabledOnly:!0}).find(wn=>wn.value!=="codex")?.value??Fr,Ot=jd(Xe,ut?.providers)??xc);const va=ie.find(wn=>wn.id===he.sourceSessionId),Es=await Z.createSession(It,{experience:he.target,provider:Xe,modelRef:{providerId:Xe,modelId:Ot},openPondCommandAccessMode:_s,appId:null,appName:null,workspaceId:null,workspaceName:null,localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,title:`Continue ${va?.title??"task"}`.slice(0,120),metadata:{experienceHandoff:uF({sourceTaskId:he.sourceSessionId,sourceExperience:va?.experience??null,targetExperience:he.target,sourceMessageIds:he.sourceMessageIds??[],sourceContext:he.sourceContext,output:he.output})}});return Tr(wn=>[Es,...wn]),dt(he.target),lt(Xe),Tt(Ot),f.set(he.prompt),Dt({kind:"chat",sessionId:Es.id}),y({type:"selectSession",sessionId:Es.id,appId:null,projectId:null}),Fe(null),Pe(null),At(!1),fe("chat"),Be("home"),at(he.target==="work"),_t(!1),Es},[Mn,_s,oa,y,ut?.providers,f,It,_t,at,dt,Tt,lt,Be,Fe,Pe,Tr,At,fe,ie]),Pm=h.useCallback(he=>{Ki(he),Wi(null),ia(null),pe(!0)},[ia,pe]),Tm=h.useCallback(he=>{ia(null),dt("work"),f.set(`$openpond-refiner-authoring ${he}`),fe("chat"),pe(!0)},[ia,f,dt,pe,fe]),vl=h.useCallback(he=>{Wi(iF(he)),Ki(null),ia(null),pe(!0)},[ia,pe]);h.useEffect(()=>{!Or&&!Co||B!=="chat"||te||G||ne||(As(Or),_o(Co),Ki(null),Wi(null),Be("home"),_t(!1),at(!0))},[Or,Co,ne,G,te,_t,at,Be,B]),h.useEffect(()=>{!hl&&!Io||B==="chat"&&Re&&xe==="home"||(As(null),_o(null))},[Re,Io,hl,xe,B]);const bl=h.useCallback(()=>{As(null),_o(null),_t(!1),at(!1)},[_t,at]),Am=h.useCallback(he=>{let Xe;if(he.workspaceKind==="local"){const Ot=it("local",he.workspaceId);Xe=`draft:${Ot}`,Fe(null),Pe(Ot),Ne(null),Ja(Ot),fe("chat")}else{const Ot=ie.find(va=>va.id===he.sourceSessionId||va.workspaceId===he.workspaceId);if(!Ot){ft("This saved file's cloud chat is no longer available.","error");return}Xe=Ot.id,xo(Ot.id)}Be("changes"),at(!0),gl({id:Date.now(),conversationId:Xe,file:he}),he.available||ft(`File unavailable: ${he.path}`,"error")},[Ja,xo,at,Be,Fe,Pe,Ne,fe,ft,ie]);h.useEffect(()=>{if(!rF(ns,Mr))return;const he=window.setTimeout(()=>{Be("changes"),at(!0),gl(Xe=>oF(Xe,ns.id))},0);return()=>window.clearTimeout(he)},[Mr,at,Be,ns]);const yl=l?.kind==="models"&&l.route.area==="console"?"console":mF(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),ln(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,ln,fe,B]);const Em=h.useCallback(he=>{if(He(null),Fe(null),Pe(null),Ne(null),he==="models"||he==="console"){Br(he==="console"?ka("datasets",null,{area:"console"}):ka()),fe("labs");return}he==="chat"&&Dt({kind:"chat",sessionId:null}),De(Pg())},[De,Dt,He,Fe,Pe,Ne,fe]),jm=h.useCallback(async(he,Xe)=>{const Ot=await mn.actions.acceptHarnessReview(he,Xe,{providerId:oa,modelId:Mn},ve);return Ot?(M(Ot.materializedTasksetId??null),Br(ka()),fe("labs"),!0):(ft("Taskset review could not be opened.","error"),!1)},[Mn,oa,ve,Br,ka,M,fe,ft,mn.actions]),Ve=h.useMemo(()=>V_([...Je.eventsBySessionId.values()].flat()),[Je.eventsBySessionId]);if(!Mt.ready)return g.jsx(_4,{startup:Mt});if(B==="settings")return g.jsx(Bb,{showToast:ft,children:g.jsx(x4,{settings:{payload:ut,connection:It,diagnostics:gm,initialSection:we,onPayload:Un,onError:Ut,onToast:ft,onOpenSourceSession:xo,onStartRefinerAuthoring:Tm,onAcceptEvaluationReview:jm,onOpenSkill:Pm,onOpenExtension:vl,teamChatCurrentUserId:mt.currentUserId,teamChatEnabled:Vs!==null,teamChatNotificationMode:mt.notificationMode,teamChatThreads:mt.threads,onTeamChatNotificationModeChange:mt.setNotificationMode,onTeamChatThreadMuteChange:mt.setThreadMuted,diffPanelWidth:Tn,diffPanelResizing:Za,diffPanelExpanded:Q,onDiffPanelResizeStart:yt,onDiffPanelExpandedChange:_t,onBack:()=>{const he=TU(l);Dt(he),fe(he.kind==="models"?"labs":"chat"),pe(!0)}},toast:{toast:bt,onDismiss:()=>y({type:"field",key:"toast",value:null})}})});const en=bu(),qt=yl==="console"||B==="chat",Ft=qt&&K,la=It?.platform??navigator.platform,Mm=en&&Lw(la),qg=Mi,J1=sn?.initialized?sn.repoPath:ke?.cwd??null,Q1={"--sidebar-width":`${Aa}px`,"--diff-panel-width":`${Tn}px`},Y1=B==="chat"&&je!=="chat"||B==="labs"||B==="scheduled"&&r||B==="team"&&!!no,X1=["app-shell",Mm?"platform-macos":"",Ft?"sidebar-open":"sidebar-closed",Dn?"sidebar-resizing":"",Za?"diff-panel-resizing":""].filter(Boolean).join(" "),Om=te?Ai[te]:null,e_=te?Om?.cursorSequence??R4(Ns(kn,Xc(Je,te))):null,t_=!!te&&!!It&&(Wt(te)?!0:!!ut?.eventWindow?.hasMoreBefore&&!!e_)&&(Om?.hasMore??!0),n_=!!Om?.loading,a_=(()=>{const he=mn.payload;if(!he)return{};const Xe=new Map(he.plans.map(wn=>[wn.id,wn])),Ot=new Set(["queued","starting","running","cancelling","reconciling"]),va={queued:"Queued",starting:"Starting",running:"Running",cancelling:"Cancelling",reconciling:"Reconciling"},Es={};for(const wn of[...he.modelRuns].sort(($a,Ro)=>Ro.updatedAt.localeCompare($a.updatedAt))){if(wn.kind==="evaluation"||!["prepared","running"].includes(wn.status))continue;const $a=he.jobs.filter($m=>$m.metadata.modelRunId===wn.id).sort(($m,s_)=>s_.updatedAt.localeCompare($m.updatedAt))[0];if($a&&!Ot.has($a.status))continue;const Ro=$a?.status??(wn.status==="prepared"?"starting":"running");Es[wn.modelId]={label:va[Ro]??"Running",status:Ro}}for(const wn of[...he.jobs].sort(($a,Ro)=>Ro.updatedAt.localeCompare($a.updatedAt))){if(!Ot.has(wn.status))continue;const $a=Xe.get(wn.planId)?.modelId;!$a||Es[$a]||(Es[$a]={label:va[wn.status]??"Active",status:wn.status})}return Es})();return g.jsx(Bb,{showToast:ft,children:g.jsx(S4,{className:X1,style:Q1,sidebar:{activityTimes:Ve,onOpenPonder:()=>{Dt({kind:"chat",sessionId:null}),Ne(null),fe("chat"),a("activity")},productArea:yl,modelProjects:(mn.payload?.modelProjects??[]).filter(he=>he.hosted===null||he.hosted.teamId===(ha.defaultTeamId?.trim()??null)),modelTrainingActivityByProjectId:a_,onProductAreaChange:Em,experience:je,view:B,selectedAppId:ne,selectedProjectId:G,selectedSessionId:te,selectedTeamThreadId:mt.selectedThreadId,teamChatEnabled:Vs!==null,organizations:kr,teamChatOrganization:wr,teamChatLoading:mt.loading,currentUserId:mt.currentUserId,teamMembers:mt.members,teamThreads:mt.threads,...Ir,onOpenTeamChat:Im,discoverCommunities:_m,account:ws,connection:It,profile:ut?.profile,pinnedCollapsed:ra,cloudProjectsCollapsed:Ze,chatsCollapsed:Pn,savedForLaterCollapsed:Ga,archivedChatsOpen:H,cloudProjectsExpanded:J,sectionMenuOpen:F,dragItem:Li,taskDragSessionId:Er,taskPreviewSessionIds:bo,activeSessions:Ks,archivedSessions:Gn,pinnedRows:et,pinnedSessions:Rs,savedForLaterSessions:Pr,savedForLaterFiles:Ws,projectRows:Ps,localProjectRows:Ts,cloudProjectRows:Ar,projectSessionRowsByProjectId:lo,childSessionRowsByParentId:Gs,sidebarProjectIdBySessionId:Qa,terminalSummaries:fo,runningSessionIds:Oi,goalRuntimeBySessionId:go,subagentRuntimeBySessionId:vo,visibleChatRows:uo,chatRows:ga,chatRowsVisibleCount:Zs,expandedProjectIds:Ri,currentVersion:ut?.server.version??null,platform:la,arch:It?.arch??null,onSidebarResizeStart:Ke,setSidebarOpen:pe,setView:fe,setSelectedAppId:Fe,setSelectedProjectId:Pe,setSelectedSessionId:Ne,setSearchOpen:Ae,setSectionMenuOpen:He,setSettingsSection:ln,onSelectTeam:ym,onLogOut:Sm,onTogglePinnedCollapsed:ks,onToggleCloudProjectsCollapsed:Ea,onToggleChatsCollapsed:ct,onToggleSavedForLaterCollapsed:an,setArchivedChatsOpen:qe,setCloudProjectsExpanded:vn,setChatRowsVisibleCount:jt,beginNewChat:bm,beginProjectChat:wo,onAddProject:ml,dockSessionRight:Fi,selectTeamThread:he=>{fe("team"),mt.selectThread(he)},openTeamDm:he=>{fe("team"),mt.openDm(he)},toggleSessionPinned:Bi,toggleProjectPinned:cl,toggleSessionSavedForLater:ll,openSidebarFile:Am,setSidebarFileStatus:(he,Xe)=>{co(he,Xe)},archiveSession:Zu,restoreSession:il,renameSession:Ju,removeProject:vm,expandProject:Ja,toggleProjectExpanded:Pi,startPinnedDrag:es,clearSidebarDrag:yo,previewPinnedDrop:zi,commitPinnedDrop:Hi,commitPinnedPreviewDrop:Ui,startTaskDrag:jr,clearTaskDrag:Xa,previewTaskDrop:$i,commitTaskDrop:Ni,commitTaskPreviewDrop:Di},topBar:{sidebarOpen:Ft,sidebarAvailable:qt,title:B==="chat"&&n?"Ponder Pal":ju,backAction:ye.backAction,breadcrumbs:ye.breadcrumbs,workspaceName:ro,workspaceId:ao,busy:me,workspaceState:sn,workspaceKind:so,selectedApp:D??Xt,selectedProject:Sn,workspaceDiff:zn,managedWorkspace:Pu,workspaceBusy:Bt,defaultTeamId:ha.defaultTeamId,activityActorId:ut?.account.profile?.id??null,activityProjectId:l?.kind==="models"?l.route.projectId??null:null,showDiffControls:B==="chat"&&je==="development",diffPanelOpen:Re,terminalOpen:ze,rightSidebarAvailable:Y1,rightSidebarOpen:B==="labs"&&p?c?.open??!1:B==="scheduled"?r:Re,onToggleDiffPanel:fl,onToggleRightSidebar:B==="labs"&&p?c?.toggle:B==="scheduled"?()=>i(he=>!he):B==="team"&&no?Ii:fl,onOpenSearch:()=>{He(null),Ae(!0)},onToggleTerminal:()=>At(he=>!he),onRunTerminalCommand:he=>{I({id:Date.now(),scope:qg,command:he}),At(!0)},onWorkspaceToolAction:zu,onOpenCommitDialog:Nu,onWorkspaceBranchChange:$u,onWorkspaceBranchCreate:Du,connection:It,onBootstrap:Un,onOpenSandboxWorkspace:ul,onShowSidebar:()=>pe(!0),platform:la,showWorkspaceControls:B!=="team"&&B!=="community"&&B!=="labs"&&B!=="scheduled"&&B!=="outputs"&&B!=="projects"&&(je==="development"||je==="work"&&!!(Sn||ke?.localProjectId||ke?.cloudProjectId||ke?.workspaceKind==="local_project"))},mainPane:{ponderMode:n,onPonderModeChange:a,experience:je,onNewExperienceChange:De,view:B,teamChat:{currentUserId:mt.currentUserId,members:mt.members,agents:mt.agents,profile:ut?.profile??null,teamId:Vs,teamName:wr?.displayName??null,detail:mt.detail,aiThread:mt.aiThread,agentConversation:mt.agentConversation,loading:mt.loading,busy:mt.busy,error:mt.error,connection:It,providerSettings:ut?.providers??null,provider:oa,model:Mn,codexPermissionMode:oe,codexReasoningEffort:ve,openPondCommandAccessMode:_s,contextWindowStatus:So,showToast:ft,onProviderChange:qi,onModelChange:Tt,onCodexPermissionModeChange:oo,onCodexReasoningEffortChange:_r,onOpenPondCommandAccessModeChange:Cr,onOpenProviderSettings:()=>{Dt({kind:"view",view:"apps"})},onSendMessage:mt.sendMessage,onPublishProfileAgent:ki,onOpenAiThread:async he=>{await mt.openAiThread(he),Be("chat"),at(!0)},onOpenAgentConversation:async he=>{await mt.openAgentConversation(he),Be("chat"),at(!0)},onCloseAiThread:()=>at(!1),onCloseAgentConversation:()=>{mt.closeAgentConversation(),at(!1)},onSendAgentTurn:mt.sendAgentTurn,onSendAiTurn:mt.sendAiTurn,onStopAiTurn:mt.stopAiTurn,onEditMessage:mt.editMessage,onDeleteMessage:mt.deleteMessage,onRetryMessage:mt.retryMessage,onDismissFailedMessage:mt.dismissFailedMessage,onLoadMoreMessages:mt.loadMoreMessages,onRetryLoad:mt.refresh},community:wi,bootstrap:ut,runtimeEvents:Ya,chatMessages:po,pendingUserMessage:te?to[te]??null:null,contextWindowStatus:So,goalRuntime:mo,subagentRuntime:Ma,selectedSessionId:te,composerDraftStore:f,mainComposerFocusRequestId:z,labCloseDetailRequestId:ye.closeDetailRequestId,labCloseDetailKind:ye.closeDetailKind,sideChatTrainingLaunchRequest:pl,onSideChatTrainingLaunchHandled:he=>sm(Xe=>Xe?.id===he?null:Xe),mentionApps:qn,connectedAppMentions:ja,profileSkills:wm,selectedMentionAppId:A,busy:me,turnRunning:ho,activeProvider:oa,activeModel:Mn,codexPermissionMode:oe,codexReasoningEffort:ve,openPondCommandAccessMode:_s,pendingApproval:xn,activeWorkspaceAppId:_i,activeWorkspaceId:ao,activeWorkspaceKind:so,projectTarget:Eu,actionCatalog:Ci,workspaceTarget:tl,connection:It,workspaceName:ro,workspaceState:sn,workspaceDiff:zn,workspaceBusy:Bt,diffBusy:ts,forceChatThread:!!te,diffPanelOpen:Re,diffPanelExpanded:Q,rightPanelMode:xe,rightPanelTabRequest:R,rightChatPanels:om,runtimeEventStore:fa,nativeSkillSidebar:hl,extensionSkillSidebar:Io,workspaceDiffPanelViewState:O,sidebarFileOpenRequest:ns,sidebarFileBookmarks:ji,onSetSidebarFileStatus:(he,Xe)=>{co(he,Xe)},browserConversationId:Mr,terminalScope:qg,terminalTabs:C,terminalCwd:J1,pendingTerminalCommand:b,terminalOpen:ze,onToggleTerminal:()=>At(he=>!he),onWorkspaceDiffPanelViewStateChange:nl,training:mn,trainingSessions:ie,trainingChatHandoff:Cs,trainingDetailTasksetId:_,onTrainingDetailTasksetIdChange:M,onTrainingChatTaskSelect:Wn,onTrainingChatHandoffDismiss:Rr,onOpenSession:xo,onExperienceHandoff:Rm,cloudProjects:ut?.cloudProjects??[],projects:xm,projectsAccountBaseUrl:ws?.baseUrl??ws?.activeProfile?.baseUrl??null,projectsTeamName:wr?.displayName??null,projectTaskCounts:km,onNewCloudProject:em,onNewLocalProject:ml,onNewProjectTask:he=>wo(he.id),onToggleProjectPinned:cl,onUploadLocalProject:Qu,chatHistoryHasMore:t_,chatHistoryLoading:n_,onDiffPanelResizeStart:yt,onToggleDiffPanelExpanded:()=>_t(he=>!he),onShowDiffPanel:am,onShowBrowserPanel:nm,onShowFilesPanel:()=>cm("files"),onShowGoalSidebarTab:Js,onShowTrainingDraftPanel:()=>{Be("training"),at(!0)},onShowRightChatPanel:im,onAddRightChat:()=>Fi(null),onOpenRightChatForSession:(he,Xe)=>{const Ot=Xe??ie.find(va=>va.id===he)??null;Ot&&Fi(Ot,{preserveView:!0})},onLabDetailOpenChange:ye.onDetailOpenChange,evaluationSidebarActive:B==="labs"&&p,onEvaluationSidebarControl:u,scheduledDetailOpen:r,onScheduledDetailOpenChange:i,onTerminalTabsChange:P,onCloseRightChatPanel:rm,onCloseNativeSkillSidebar:bl,onActivateRightChatPanel:dm,onRightChatModelChange:um,onRightChatPromptChange:mm,onRightChatScrollStateChange:fm,onRightChatProviderChange:pm,onSubmitRightChat:lm,onStopRightChat:he=>ko(he),onCloseTerminal:()=>At(!1),onLoadMoreChatHistory:Ei,canSyncWorkspace:Tu,startMessage:Is,onPayload:Un,onError:Ut,setView:fe,onOpenProfileSettings:hm,onOpenProviderSettings:()=>{Dt({kind:"view",view:"apps"})},onOpenTrainingSettings:()=>{Dt({kind:"settings",section:"training"})},onOpenDatasetStorageSettings:()=>{Dt({kind:"settings",section:"dataset-storage"})},changeDraftProvider:qi,changeProjectTarget:Mu,changeWorkspaceTarget:Yu,setDraftProvider:lt,setDraftModel:Tt,onBeginNewChatWithModel:Ti,changeCodexPermissionMode:oo,changeCodexReasoningEffort:_r,changeOpenPondCommandAccessMode:Cr,resolveApproval:io,answerCreateImproveQuestion:al,applyCreateImproveCandidate:Bu,approveCreateImproveRun:Fu,cancelCreateImproveRun:Vu,openCreateImprovePullRequest:sl,reconcileCreateImprovePullRequest:Ku,rejectCreateImproveCandidate:Wu,pauseCreateImproveRun:rl,resumeCreateImproveRun:ol,reviseCreateImproveRun:Gu,setMentionedAppId:T,showToast:ft,onSaveTaskDraft:Cm,sendPrompt:Xu,stopTurn:he=>ko(void 0,he),syncWorkspaceLocally:qu,refreshWorkspaceDiff:On},cloudSetup:{state:S,onClose:()=>w(null),onOpenBrowserUrl:tm,onStart:()=>{dl()}},projectConfirm:{state:V,onResolve:Y},lazyPanels:{activeSessions:Ks,branchDialogName:Ge,branchDialogOpen:$e,commitDialogOpen:U,commitDraft:Oe,commitIncludeUnstaged:de,commitMessage:ae,commitNextStep:be,canPublishOpenPondProject:Au,connection:It,expandProject:Ja,newProjectBusy:X,newProjectDialogOpen:Me,newProjectDirectory:ha.defaultNewProjectDirectory,newProjectMode:Te,newProjectName:N,newProjectPath:q,projectRows:ca,query:se,searchOpen:ee,visibleWorkspaceDiff:zn,visibleWorkspaceState:sn,workspaceBusy:Bt,appDispatch:y,beginNewChat:()=>ia(null),openDefaultsSettingsFromBranchDialog:Lu,setBranchDialogName:jn,setBranchDialogOpen:Rn,setCommitDialogOpen:dn,setCommitDraft:yn,setCommitIncludeUnstaged:Ht,setCommitMessage:bn,setCommitNextStep:Cn,setNewProjectDialogOpen:En,setNewProjectName:xt,setNewProjectPath:xs,setPrompt:rt,setQuery:Le,setSearchOpen:Ae,submitCommitDialog:Hu,submitCreateWorkspaceBranch:Uu,submitNewProjectDialog:Ou},toast:{toast:bt,onDismiss:()=>y({type:"field",key:"toast",value:null})}})})}const Fo=new Map,ud=new Map;function If(e){if(!e||e.state!=="signed_in")return null;const t=e.accounts.find(s=>s.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 wF(e){const t=e?.trim();if(!t)return null;const n=Fo.get(t);return n?.updatedAt?n.organizations:null}function IF(e,t){const n=e?.trim();if(n){Fo.set(n,{organizations:t,promise:null,updatedAt:Date.now()});for(const a of ud.get(n)??[])a()}}function _F(e,t){const n=e?.trim();if(!n)return()=>{};const a=ud.get(n)??new Set;return a.add(t),ud.set(n,a),()=>{a.delete(t),a.size===0&&ud.delete(n)}}function Xb(e){const t=e.accountKey?.trim();if(!t)return Promise.resolve([]);const n=Fo.get(t);if(!e.force){if(n?.updatedAt)return Promise.resolve(n.organizations);if(n?.promise)return n.promise}const a=e.fetchOrganizations().then(s=>(IF(t,s),s)).catch(s=>{const r=Fo.get(t);throw r?.promise===a&&Fo.set(t,{organizations:r.organizations,promise:null,updatedAt:r.updatedAt}),s});return Fo.set(t,{organizations:n?.organizations??[],promise:a,updatedAt:n?.updatedAt??0}),a}const iG="openpond.config.json";function cG(e,t,n){return t<=0?-1:n==="Home"?0:n==="End"?t-1:n==="ArrowRight"?(e+1)%t:(e-1+t)%t}function WI(){return{activeTab:"files",openFilePaths:[],selectedPath:null}}function fp(e){return{activeTab:e.activeTab,openFilePaths:[...e.openFilePaths],selectedPath:e.selectedPath}}function lG(e,t=null){const n=RF(e.openFilePaths.map(s=>ty(s,t)).filter(Boolean)),a=e.selectedPath&&ty(e.selectedPath,t)||null;return{activeTab:e.activeTab==="file"&&!a?"files":e.activeTab,openFilePaths:n,selectedPath:a}}function ey(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 ty(e,t=null){let n=CF(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 s=a.split("/").filter(Boolean).at(-1);return s&&n.startsWith(`${s}/`)&&(n=n.slice(s.length+1)),n}function dG(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 mG(e,t){const n=ny(e.path);return!n||e.path.endsWith("/")||e.content==null&&/Could not access .+\/null['"]?/.test(e.patch)?!0:t.some(a=>{const s=ny(a);return!!(s&&s.startsWith(`${n}/`))})}function pG(e){return/\.(?:md|markdown|mdx)$/i.test(e)||/(?:^|\/)readme$/i.test(e)}function fG(e){return/\.(?:doc|docx|pdf)$/i.test(e)}function CF(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 RF(e){return Array.from(new Set(e))}function ny(e){const n=e.replace(/\\/g,"/").replace(/^\.\/+/,"").split("/").filter(Boolean);return n.length===0?null:n.join("/")}function PF(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",s=e.activeProfile?.baseUrl??t?.baseUrl??e.baseUrl??"",r=e.apiBaseUrl??t?.apiBaseUrl??"",i=e.chatApiBaseUrl??t?.chatApiBaseUrl??"";return[n?`profile:${n}`:"profile:unknown",a,s,r,i].join("|")}function GI(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"cloud-project"}function TF(e){const t=new TextEncoder().encode(e);let n="";for(const a of t)n+=String.fromCharCode(a);return btoa(n)}function xu(e){const t=e,n=t.teamId||t.id||"";if(!n)return null;const a=t.displayName||t.name||n,s=t.workspaceKind==="personal"||t.isPersonalDefault===!0||t.kind==="personal_default"||t.name?.trim().toLowerCase()==="personal";return{teamId:n,slug:t.slug||GI(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:s?"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:s,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 AF(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 EF(e,t){const n=e.filter(s=>s.status==="active"&&s.workspaceKind==="shared"),a=t?.trim()??"";if(a){const s=n.find(r=>r.teamId===a);if(s)return s}return n.find(s=>s.role==="owner")??n.find(s=>s.role==="admin")??n[0]??null}function jF(...e){for(const t of e){const n=t?.trim();if(n)return n}return""}function MF({draftProvider:e,hasSelectedCloudProject:t,selectedSessionHybridWorkspace:n}){return t&&!n?"openpond":e}const OF=[{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 $F(...e){return jF(...e.map(t=>{const n=t?.trim();return n&&!n.includes("@")?n:null}))}function NF(e){if(e?.state!=="signed_in")return"";const t=e.accounts.find(n=>n.isActive)??null;return $F(e.profile?.name,e.label,t?.displayLabel,e.profile?.handle,t?.handle,e.activeProfile?.handle)}function DF({bootstrap:e,draftModel:t,draftProvider:n,selectedApp:a,selectedAppId:s,selectedCloudProject:r,selectedProject:i,selectedSession:c,selectedSessionId:u,selectedSessionLinkedProject:l}){const p=c?.workspaceKind==="local_project"?c.workspaceId??null:l?.id??null,f=Wt(u)&&!c,y=c?ys(c.workspaceKind):!1,b=Ss(c),I=c?yF(c):!1,C=c?.cwd&&(!y||b)?kS(c.cwd):null,P=e?.providers??null,_=Ca(i,e?.cloudProjects??[]),M=MF({draftProvider:n,hasSelectedCloudProject:!!r,selectedSessionHybridWorkspace:b}),A=Sr(M,t,P),T=ya(e?.preferences),S=f?null:c?y?c.workspaceKind??"sandbox":I?"sandbox":p?"local_project":c.workspaceKind??(c.appId?"sandbox_app":C?"local_project":null):r?"sandbox":i?"local_project":s?"sandbox_app":null,w=f?null:c?y&&!b||I?null:p||(c.workspaceId??c.appId??C):r?null:i?.id??s,R=f?null:c?y?c.workspaceId??null:I?null:p??c.workspaceId??c.appId??C:r?null:i?.id??s,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=NF(O),se=Y?`Welcome, ${Y}`:"Welcome",ee=c?.workspaceName??c?.appName??r?.name??i?.name??a?.name??null,H=ys(S)?"cloud":"local",F=i?.name??l?.name??(c?.workspaceKind==="local_project"?c.workspaceName:null)??"Local workspace",J=(H==="cloud"?ee:null)??r?.name??_?.name??i?.name??"Cloud workspace",K=!!(r?.id||_?.id||c?.cloudProjectId||H==="cloud");return{account:O,accountLabel:V,accountPending:z,accountSignedOut:$,activeModel:A,activeProvider:M,activeWorkspaceAppId:w,activeWorkspaceId:R,activeWorkspaceKind:S,activeWorkspaceLocation:H,appDefaults:T,cloudLinked:K,cloudTargetName:J,localTargetName:F,selectedCodexHistoryPending:f,selectedSessionCloudWorkspace:y,selectedSessionLocalPathWorkspaceId:C,selectedSessionPendingCloudStart:I,selectedSessionProjectId:p,startMessage:se,workspaceName:ee}}function LF({accountPending:e,accountSignedOut:t,activeWorkspaceLocation:n,bootstrap:a,busy:s,cloudLinked:r,selectedCloudProject:i,selectedProject:c,selectedSession:u,pendingWorkspaceTarget:l,workspaceStates:p,workspaceBusy:f}){const y=Ca(c,a?.cloudProjects??[]),I=!!!c?.linkedSandboxProject?.projectId||!!y,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||s,options:[...R,...O,...OF,{value:"none",label:"Don't work in a project",detail:"General chat without project files",kind:"none"}]}},[a?.cloudProjects,a?.localProjects,s,i,c,f]),P=!!(r||c),_=!!(i?.id||y?.id||u?.cloudProjectId||Ss(u)),M=c?p[c.id]??null:null,A=cI(M,{branch:c?.linkedSandboxProject?.defaultBranch??null,path:c?.workspacePath??u?.cwd??null,linkedCloudSourceKnown:c?.linkedSandboxProject?.projectId&&I?!!c.linkedSandboxProject.lastUploadedCommit||!M?.headCommit:!0}),T=lI(c,i??y,M,{cloudLinkTrusted:I}),S=mq(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:S,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 se=n==="cloud"?z:R;return l==="cloud"?se=z:l==="local"?se=R:(Ss(u)||l==="hybrid")&&(se=O),{value:se.value,label:se.label,detail:se.stateNote||se.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,r,P,T,_,A,l,c,u,S,f]);return{projectTarget:C,workspaceTarget:w}}function Hn(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")}function ZI(e){return Hn(e.name||e.gitRepo||e.id)}function hG(e){return`@${ZI(e)}`}function JI(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Hn(t[1]??"")).filter(Boolean)}function zF(e,t){const n=JI(e);if(n.length===0)return!1;const a=new Set([Hn(t.id),ZI(t),t.gitRepo?Hn(t.gitRepo):""].filter(Boolean));return n.some(s=>a.has(s))}function QI(e){return e.filter(t=>t.sandbox)}function HF(e,t){const n=JI(e);if(n.length===0)return null;const a=new Map;for(const s of n){const r=t.find(i=>{const c=Hn(i.id),u=Hn(i.name),l=i.gitRepo?Hn(i.gitRepo):"";return s===c||s===u||s===l});r&&a.set(r.id,r)}return a.size===1?Array.from(a.values())[0]??null:null}function gG(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 s=n.slice(a.index).indexOf("@");return s<0?null:{query:Hn(a[1]??""),start:a.index+s}}function UF(e){return new Set(e.map(t=>t.id))}function ay(e,t){const n=e?.linkedOpenPondApp??null;return n?.appId&&t.has(n.appId)?n:null}function qF({bootstrap:e,codexHistorySessions:t,selectedProjectId:n,selectedSessionId:a,selectedAppId:s,sessions:r}){const i=h.useMemo(()=>e?.apps.find($=>$.id===s)??null,[e?.apps,s]),c=h.useMemo(()=>new Map((e?.localProjects??[]).map($=>[$.id,$])),[e?.localProjects]),u=h.useMemo(()=>new Map((e?.cloudProjects??[]).map($=>[$.id,$])),[e?.cloudProjects]),l=h.useMemo(()=>Jw(n),[n]),p=h.useMemo(()=>l?.kind==="local"?c.get(l.id)??null:null,[c,l]),f=h.useMemo(()=>l?.kind==="cloud"?u.get(l.id)??null:null,[u,l]),y=h.useMemo(()=>UF(e?.apps??[]),[e?.apps]),b=h.useMemo(()=>QI(e?.apps??[]),[e?.apps]),I=h.useMemo(()=>{const $=[];for(const V of e?.localProjects??[]){const Y=ay(V,y);Y&&$.push([Y.appId,V.id])}return new Map($)},[e?.localProjects,y]),C=h.useMemo(()=>new Set((e?.localProjects??[]).map($=>$.id)),[e?.localProjects]),P=h.useMemo(()=>nI(e?.localProjects??[]),[e?.localProjects]),_=h.useRef([]),M=h.useMemo(()=>BF(r,t,_.current),[t,r]),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 $=nq(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]),S=h.useMemo(()=>A?.cloudProjectId?u.get(A.cloudProjectId)??null:null,[u,A]),w=p??T,R=f??S,O=h.useMemo(()=>ay(w,y),[y,w]),z=h.useMemo(()=>O?e?.apps.find($=>$.id===O.appId)??null:null,[e?.apps,O]);return{cloudProjectById:u,currentAppIds:y,linkedProjectByAppId:I,localProjectById:c,mentionableSandboxApps:b,selectedApp:i,selectedCloudProject:R,selectedProject:w,selectedProjectLinkedApp:z,selectedProjectLinkedOpenPondApp:O,selectedSession:A,selectedSessionLinkedProject:T,sidebarSessions:M}}function BF(e,t,n){const a=new Map;for(const l of e){const p=sy(l);a.set(p,l)}for(const l of t){const p=sy(l),f=a.get(p);a.set(p,f?FF(f,l):l)}const s=Array.from(a.entries());if(!n)return s.sort((l,p)=>ry(l[1],p[1])).map(l=>l[1]);const r=[],i=new Set;for(const l of n){const p=a.get(l);p&&(r.push([l,p]),i.add(l))}const u=[...s.filter(([l])=>!i.has(l)).sort((l,p)=>ry(l[1],p[1])),...r];return n.splice(0,n.length,...u.map(([l])=>l)),u.map(l=>l[1])}function FF(e,t){return{...e,metadata:VF(e.metadata,t.metadata),status:e.status==="active"||t.status==="active"?"active":e.status,updatedAt:KF(e.updatedAt,t.updatedAt)}}function sy(e){return e.codexThreadId?`codex:${e.codexThreadId}`:`session:${e.id}`}function ry(e,t){const n=oy(t)-oy(e);return n!==0?n:e.title.localeCompare(t.title)}function VF(e,t){const n={...e??{},...t??{}};return Object.keys(n).length>0?n:void 0}function KF(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 oy(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 WF(e){return!!(e&&ys(e.workspaceKind)&&!Ss(e)&&e.provider!=="openpond")}function GF(e,t){const n=Xw(e,t);return`${e.id}\0${n.provider}\0${n.model}`}function ZF({activeWorkspaceId:e,activeWorkspaceKind:t,appDispatch:n,connection:a,expandProject:s,linkedProjectByAppId:r,providerSettings:i,selectedAppId:c,selectedSession:u,selectedSessionId:l,selectedSessionProjectId:p,setDiffPanelExpanded:f,setDraftModel:y,setDraftProvider:b,setError:I,setSelectedAppId:C,setSelectedProjectId:P,setSessions:_,setTerminalOpen:M,toast:A}){const T=h.useRef(null);h.useEffect(()=>{if(!c)return;const S=p??(l?null:r.get(c)??null);if(!S)return;const w=it("local",S);C(null),P(w),s(w)},[s,r,c,l,p,C,P]),h.useEffect(()=>{if(!A||A.persistent)return;const S=window.setTimeout(()=>{n({type:"clearToast",toastId:A.id})},A.durationMs??(A.tone==="error"?7e3:3500));return()=>window.clearTimeout(S)},[n,A]),h.useEffect(()=>{function S(w){(w.metaKey||w.ctrlKey)&&w.key==="`"&&(w.preventDefault(),M(R=>!R))}return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[M]),h.useEffect(()=>{f(!1)},[e,t,f]),h.useEffect(()=>{if(!l){T.current=null;return}if(!u||u.id!==l)return;const S=GF(u,i);if(T.current===S)return;T.current=S;const w=Xw(u,i);b(w.provider),y(w.model)},[i,u,l,y,b]),h.useEffect(()=>{!a||!u||!WF(u)||Z.patchSession(a,u.id,{provider:"openpond"}).then(S=>{_(w=>w.map(R=>R.id===S.id?S:R)),b("openpond"),y(w=>Sr("openpond",w))}).catch(S=>{I(S instanceof Error?S.message:String(S))})},[a,u,y,b,I,_])}function JF({connection:e,setError:t}){return h.useCallback(async(n,a,s)=>{if(!e){const r=new Error("OpenPond App server is not connected.");throw t(r.message),r}t(null);try{await Z.resolveApproval(e,n,{decision:a,answers:s})}catch(r){const i=r instanceof Error?r.message:String(r);throw t(i),r}},[e,t])}function QF({activeProvider:e,contextCompaction:t,contextUsage:n,pinnedItems:a,pinnedPreviewKeys:s,pinnedProjects:r,projectRows:i,visibleProjectRows:c}){const u=h.useMemo(()=>BU(a,s),[a,s]),l=h.useMemo(()=>II({provider:e,snapshot:n,preferences:t}),[e,t,n]),p=h.useMemo(()=>Array.from(new Set([...r,...c].filter(vg).map(y=>y.project.id))),[r,c]);return{commandProjectRows:h.useMemo(()=>i,[i]),contextWindowStatus:l,pinnedRows:u,sidebarWorkspaceAppIds:p}}function YF({appDispatch:e,expandProject:t,linkedProjectByAppId:n,requestComposerFocus:a,onBeginNewChat:s,setMentionedAppId:r}){return h.useCallback((i=null)=>{s?.();const c=i?.id?n.get(i.id)??null:null;if(c){const u=it("local",c);r(null),e({type:"selectProject",projectId:u}),t(u),a();return}r(null),e({type:"beginNewChat",appId:i?.id??null}),a()},[e,t,n,s,a,r])}const YI={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 vG(e){return`@${e.token}`}function XF(e){return`@${s5(e)}`}function e5(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 s=a[0],r=Oo(a.flatMap(f=>f.capabilities.map(y=>y.id))),i=Oo(a.flatMap(f=>f.capabilityLabels)),c=Oo(a.flatMap(f=>f.connections.map(y=>y.id).filter(o5))),u=Oo(a.map(f=>f.id)),l=Oo(a.map(f=>f.setupSurface)),p=a5(n);return{provider:n,label:s.providerLabel,detail:i.length>0?i.slice(0,4).join(", "):s.description,token:p,tokens:n5(a),ref:{kind:"integration",provider:n,appIds:u,setupSurfaces:l,...c.length>0?{connectionIds:c}:{},...r.length>0?{capabilities:r}:{}}}})}function bG(e,t){const n=Hn(t);return e.filter(a=>n?a.tokens.some(s=>s.includes(n)):!0).slice(0,8)}function t5(e,t){const n=r5(e);if(n.length===0)return[];const a=new Map;for(const s of n){const r=t.find(i=>i.tokens.includes(s));r&&a.set(r.provider,r)}return Array.from(a.values())}function yG(e,t){if(t.length===0)return[];const n=[];for(const a of e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)){const s=a[1]??"",r=Hn(s);if(!r)continue;const i=t.find(f=>f.tokens.includes(r));if(!i)continue;const u=(a[0]??"").indexOf("@");if(u<0||typeof a.index!="number")continue;const l=a.index+u,p=`@${s}`;n.push({detail:i.detail,displayText:XF(i),end:l+p.length,label:i.label,provider:i.provider,start:l,text:p})}return n}function n5(e){return Oo(e.flatMap(t=>[...YI[t.providerFamily],t.providerFamily,t.id,t.label,t.shortLabel]).map(Hn).filter(Boolean))}function a5(e){return Hn(YI[e][0]??e)}function s5(e){return e.provider==="github"?"GitHub":e.provider==="x"?"X":e.provider==="mcp"?"MCP":e.label}function r5(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Hn(t[1]??"")).filter(Boolean)}function Oo(e){return Array.from(new Set(e))}function o5(e){return typeof e=="string"&&e.length>0}function i5({bootstrap:e,connectedAppRows:t,mentionableSandboxApps:n,runtimeIndexes:a,selectedApp:s,selectedCloudProject:r,selectedProject:i,selectedSession:c,selectedSessionId:u}){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||s||i||r)?[]:n,y=h.useMemo(()=>e5(t),[t]),b=h.useMemo(()=>sF(a,u),[a,u]);return{chatMentionApps:f,cloudProjectIdsByTeam:l,connectedAppMentions:y,pendingApproval:b}}function c5({connection:e,setBootstrap:t,setCodexPermissionMode:n,setCodexReasoningEffort:a,setError:s}){const r=h.useCallback(c=>{if(!e){s("Connect to OpenPond before saving preferences.");return}Z.savePreferences(e,{codexPermissionMode:c}).then(u=>{n(u.preferences.codexPermissionMode),a(u.preferences.codexReasoningEffort),t(l=>l&&{...l,preferences:u.preferences})}).catch(u=>{s(u instanceof Error?u.message:String(u))})},[e,t,n,a,s]),i=h.useCallback(c=>{if(!e){s("Connect to OpenPond before saving preferences.");return}Z.savePreferences(e,{codexReasoningEffort:c}).then(u=>{n(u.preferences.codexPermissionMode),a(u.preferences.codexReasoningEffort),t(l=>l&&{...l,preferences:u.preferences})}).catch(u=>{s(u instanceof Error?u.message:String(u))})},[e,t,n,a,s]);return{changeCodexPermissionMode:r,changeCodexReasoningEffort:i}}const l5=6e4;function Tg(e,t){if(!e)return t;const n=u5(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 e1(e,n)?e:n}function d5(e,t){const n=Tg(e,t),a=e?{...n,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order,updatedAt:e.updatedAt}:n;return e&&e1(e,a)?e:a}function oc(e,t){let n=!1,a=!1;const s=e.map(r=>{if(r.id!==t.id)return r;n=!0;const i=Tg(r,t);return i!==r&&(a=!0),i});return n?a?s:e:[t,...e]}function ku(e,t){let n=!1,a=!1;const s=e.map(r=>{if(r.id!==t.id)return r;n=!0;const i=d5(r,t);return i!==r&&(a=!0),i});return n?a?s:e:[t,...e]}function _f(e,t,n,a=Date.now()){const s=new Map(e.map(r=>[r.id,r]));return t.map(r=>{const i=s.get(r.id);if(i&&n){const c=p5(i,r,n,a);if(c)return c}return Tg(i,r)})}function iy(e,t,n,a=Date.now()){const s=new Map(e.map(l=>[l.id,l])),r=new Map(_f(e,t,n,a).map(l=>[l.id,l])),i=new Set(s.keys()),c=t.filter(l=>!i.has(l.id)).map(l=>r.get(l.id)??l),u=e.map(l=>{const p=r.get(l.id);return p||(XI(l,t)?l:null)}).filter(l=>!!l);return[...c,...u]}function XI(e,t){const n=Date.parse(e.updatedAt);if(!Number.isFinite(n))return!1;const a=m5(t);return a===null||n>=a}function cy(e,t,n,a=Date.now()){const s=new Map(t.map(r=>[r.id,r]));for(const r of n){const i=s.get(r.id);i&&(t1(i,r)||(e[r.id]=a))}}function u5(e,t){const n=Date.parse(e),a=Date.parse(t);return Number.isFinite(n)&&Number.isFinite(a)&&n>a}function e1(e,t){return JSON.stringify(e)===JSON.stringify(t)}function m5(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 p5(e,t,n,a){const s=n[t.id];return s===void 0?null:a-s>l5||t1(e,t)?(delete n[t.id],null):{...t,pinned:e.pinned,savedForLater:e.savedForLater,archived:e.archived,order:e.order}}function t1(e,t){return e.pinned===t.pinned&&e.savedForLater===t.savedForLater&&e.archived===t.archived&&e.order===t.order}const n1=800,f5=5e3,ly=5e4,h5=16,g5=3e4,Yn=new Map;function v5(e,t){return Yn.get(s1(e,t))?.payload??null}async function a1(e,t,n={}){const a=s1(e,t),s=Yn.get(a),r=n.limit??n1,i=n.tail??!0;if(s?.promise)return s.promise;if(!n.force&&i&&s?.payload&&Date.now()-s.fetchedAt<=g5)return dy(a,s),s.payload;const c=!!(n.force&&i&&s?.payload),u=c?s?.payload?.events.at(-1)?.id:void 0,l=Z.codexHistoryThreadIncremental(e,t,{afterEventId:u,limit:r,revision:c?s?.revision:void 0,tail:i}).then(p=>{const f=Yn.get(a)?.payload??s?.payload;if(p.unchanged){if(!f)throw new Error("Codex history revision matched without a cached thread.");return Yn.set(a,{fetchedAt:Date.now(),payload:f,revision:p.revision}),dy(a,Yn.get(a)),f}const y={session:p.session,events:p.events},b=i&&f&&!p.reset?{...y,events:b5(f.events,y.events)}:y;return Yn.set(a,{fetchedAt:Date.now(),payload:b,revision:p.revision}),uy(),b}).catch(p=>{throw Yn.get(a)?.promise===l&&Yn.delete(a),p});return Yn.set(a,{fetchedAt:s?.fetchedAt??0,payload:s?.payload,promise:l,revision:s?.revision}),uy(),l}function s1(e,t){return`${e.serverUrl}
|
|
112
|
+
${e.token}
|
|
113
|
+
${t}`}function dy(e,t){Yn.delete(e),Yn.set(e,t)}function uy(){for(;Yn.size>h5;){const e=Yn.keys().next().value;if(!e)return;Yn.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 y5=500,S5=2500,x5=15e3;function k5(e){return e.active?y5:e.surface==="thread"?S5:x5}function Ag(e,t){return!t||e.session.status==="active"?e:{...e,session:{...e.session,status:"active"}}}function w5(e={}){const t={cachedPayload:e.cachedPayload??v5,clearTimer:e.clearTimer??(l=>globalThis.clearTimeout(l)),loadPayload:e.loadPayload??a1,now:e.now??Date.now,setTimer:e.setTimer??((l,p)=>globalThis.setTimeout(l,p))},n=new Map;let a=1;function s(l){const p=_5(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 y=a++;return f.subscribers.set(y,l),f.latestPayload&&l.onPayload(f.latestPayload),r(f,0),()=>{const b=n.get(p);if(b){if(b.subscribers.delete(y),b.subscribers.size>0){r(b,c(b));return}b.disposed=!0,u(b),n.delete(p)}}}function r(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||(u(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 y of l.subscribers.values())y.onPayload(f)}catch(f){if(l.disposed)return;for(const y of l.subscribers.values())y.onError?.(f)}finally{l.inFlight===p&&(l.inFlight=null),l.disposed||r(l,c(l))}}function c(l){const p=[...l.subscribers.values()],f=p.some(b=>b.locallyActive||b.reportedActive)||l.latestPayload?.session.status==="active"||Cg(l.latestPayload?.events??[])?.tone==="active",y=p.some(b=>b.surface==="thread")?"thread":"sidebar";return k5({active:f,surface:y})}function u(l){l.timer&&t.clearTimer(l.timer),l.timer=null,l.nextRefreshAt=null}return{subscribe:s}}const I5=w5();function Eg(e){return I5.subscribe(e)}function _5(e,t){return`${e.serverUrl}
|
|
114
|
+
${e.token}
|
|
115
|
+
${t}`}function C5({connection:e,selectedSessionId:t,selectedSessionLocallyActive:n,selectedSessionStatus:a,setCodexHistorySessions:s,setError:r}){const[i,c]=h.useState({events:[],sessionId:null}),u=Wt(t)?t:null,l=u&&i.sessionId===u?i.events:[],p=h.useCallback(f=>{c(y=>{if(!u)return{events:[],sessionId:null};const b=y.sessionId===u?y.events:[];return{events:typeof f=="function"?f(b):f,sessionId:u}})},[u]);return h.useEffect(()=>{if(!e||!u){c(b=>b.sessionId===null&&b.events.length===0?b:{events:[],sessionId:null});return}r(b=>b==="Session not found"?null:b);const f=n;return Eg({connection:e,locallyActive:f,onError:b=>r(b instanceof Error?b.message:String(b)),onPayload:b=>{const I=Ag(b,f);c(C=>C.sessionId!==u?{events:I.events,sessionId:u}:{events:Ns(C.events,I.events),sessionId:u}),r(C=>C==="Session not found"?null:C),s(C=>ku(C,I.session))},reportedActive:a==="active",sessionId:u,surface:"thread"})},[e,u,n,a,s,r]),{codexHistoryEvents:l,setCodexHistoryEvents:p}}function r1(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 R5({connection:e,appPreferences:t,sessions:n,pinnedItems:a,setAppPreferences:s,setCodexHistorySessions:r,setSessions:i,sidebarFileBookmarks:c,setSidebarFileBookmarks:u,setError:l}){const[p,f]=h.useState(null),[y,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}`),r1(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=Ad(w),$=C.current??a.map(Y=>Y.key),V=Ed($,Ur(O),Ur(R),z);xb($,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(xb(R,z))return;const $=t,V=new Map(n.map(H=>[H.id,H])),Y=c,se=new Map(a.map(H=>[H.key,H]));s(H=>{const F={...H};return z.forEach((J,K)=>{const B=se.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=se.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),r(ee),u(H=>{const F=new Map;return z.forEach((J,K)=>{const B=se.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=se.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)),s($);const F=J=>J.map(K=>V.get(K.id)??K);i(F),r(F),u(Y)})}function T(w,R){const O=I.current;if(O){const z=C.current??a.map(V=>V.key),$=Ed(z,Ur(O),Ur(R),Ad(w));A($)}_()}function S(){I.current&&A(C.current??a.map(R=>R.key)),_()}return{dragItem:p,pinnedPreviewKeys:y,startPinnedDrag:P,clearSidebarDrag:_,previewPinnedDrop:M,commitPinnedDrop:T,commitPinnedPreviewDrop:S}}function P5({connection:e,sessions:t,setCodexHistorySessions:n,setError:a,setSessions:s}){const[r,i]=h.useState(null),[c,u]=h.useState(null),l=h.useRef(null),p=h.useRef(null);function f(_,M){_.dataTransfer.effectAllowed="move",_.dataTransfer.setData("text/plain",`session:${M.sessionId}`),r1(_),l.current=M,p.current=M.visibleSessionIds,i(M.sessionId),u(M.visibleSessionIds)}function y(_,M){const A=l.current;if(!A)return;const T=p.current??A.visibleSessionIds,S=Ed(T,A.sessionId,M,Ad(_));T5(T,S)||(p.current=S,u(S))}function b(){l.current=null,p.current=null,i(null),u(null)}function I(_,M){const A=l.current;if(!A){b();return}const T=p.current??A.visibleSessionIds,S=Ed(T,A.sessionId,M,Ad(_));P(Pb(A.allSessionIds,A.visibleSessionIds,S)),b()}function C(){const _=l.current;_&&P(Pb(_.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 S=w=>w.map(R=>{const O=M.get(R.id);return O===void 0||O===R.order?R:{...R,order:O}});s(S),n(S),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:$}});s(R),n(R),a(w instanceof Error?w.message:String(w))})}return{clearTaskDrag:b,commitTaskDrop:I,commitTaskPreviewDrop:C,previewTaskDrop:y,startTaskDrag:f,taskDragSessionId:r,taskPreviewSessionIds:c}}function T5(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function my({afterMessageId:e=null,attachments:t,content:n,sessionId:a}){const s=new Date().toISOString(),r=`pending_user_${a}_${s}_${Math.random().toString(36).slice(2,8)}`,i=A5(t);return{id:r,role:"user",content:n,sessionId:a,afterMessageId:e,timestamp:s,turnId:r,...i.length>0?{attachments:i}:{}}}function o1(e,t){return!t||i1(e,t)?e:[...e,t]}function i1(e,t){const n=t.afterMessageId?e.findIndex(r=>r.id===t.afterMessageId):-1,a=n>=0?n+1:0,s=Date.parse(t.timestamp);for(let r=a;r<e.length;r+=1){const i=e[r];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(s)||!Number.isFinite(c)||c>=s)return!0}return!1}function A5(e){return e.map(({contentsBase64:t,text:n,...a})=>a)}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 xr(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 gs(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];if(t(a))return a}return null}function E5(e,t,n){if(t.name==="workspace_action_result"){const a=gs(e,s=>s.role==="assistant"&&s.turnId===t.turnId&&s.actionRun?.actionName===n.actionName);if(a?.actionRun){a.id=t.id,a.timestamp=t.timestamp,a.actionRun={...a.actionRun,...n,refs:Cf([...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 j5(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"])??hp(t)??hp(ce(t?.run))??hp(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 r=ce(t?.run)??ce(t?.agentRun),i=ce(r?.metadata),c=ce(t?.actionSummary)??ce(r?.actionSummary)??ce(i?.actionSummary),u=ce(t?.action)??c??ce(i?.selectedAction)??null,l=ce(t?.responseSummary)??ce(r?.responseSummary)??ce(i?.responseSummary),p=ce(t?.sourceSummary)??ce(r?.sourceSummary)??ce(i?.sourceSummary),f=ce(t?.traceSummary)??ce(r?.traceSummary)??ce(i?.traceSummary),y=ce(t?.evalSummary)??ce(r?.evalSummary)??ce(i?.evalSummary),b=Cf([...Os("artifact",t?.artifactRefs,"Artifact"),...Os("artifact",u?.artifactRefs,"Artifact"),...Os("artifact",c?.artifactRefs,"Artifact"),...Os("artifact",l?.artifactRefs,"Artifact"),...Os("trace",t?.traceArtifactRefs,"Trace"),...Os("trace",f?.artifactRefs,"Trace"),...Os("eval",t?.evalResultArtifactRefs,"Eval"),...Os("eval",y?.artifactRefs,"Eval"),...Os("output",t?.outputRefs,"Output")]),I=ue(p,["sourceRef","ref"]);return I&&b.push({id:Rf("source",I),kind:"source",label:"Source",target:I}),{actionName:a,title:ue(u,["label","title","name"])??ue(i,["selectedActionLabel"])??L5(a),status:M5(e,l,r),responseText:ue(l,["text","summary","message"])??(e.name==="workspace_action_result"&&e.output?.trim()||null),runId:ue(r,["id","runId"])??ue(t,["runId","agentRunId"])??null,projectId:ue(r,["projectId"])??ue(t,["projectId"])??ue(n,["projectId"])??null,agentId:ue(r,["agentId"])??ue(t,["agentId"])??ue(n,["agentId"])??null,agentName:ue(ce(u?.implementation),["agentName"])??ue(u,["agentName"])??ue(i,["selectedAgentName"])??null,sandboxId:ue(r,["sandboxId"])??ue(t,["sandboxId"])??ue(ce(t?.sandbox),["id"])??ue(ce(t?.createdSandbox),["id"])??ue(n,["sandboxId"])??null,runtimeId:ue(r,["runtimeId"])??ue(t,["runtimeId"])??null,implementationType:ue(t,["implementationType"])??ue(u,["implementationType","type","kind"])??ue(ce(u?.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:Cf(b),childCalls:$5(t,r,i)}}function hp(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 M5(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 s=ue(n,["status"]);return s==="failed"?"failed":s==="succeeded"||s==="completed"?"completed":s==="queued"||s==="running"||s==="runtime_created"?"running":e.status==="pending"?"pending":e.status==="started"||e.name==="workspace_action"?"running":"unknown"}function Os(e,t,n){return(Array.isArray(t)?t:t?[t]:[]).flatMap(s=>{const r=O5(e,s,n);return r?[r]:[]})}function O5(e,t,n){if(typeof t=="string"&&t.trim()){const i=t.trim();return{id:Rf(e,i),kind:e,label:n,target:i}}const a=ce(t);if(!a)return null;const s=ue(a,["url","webUrl","artifactPath","path","ref"])??ue(ce(a.artifact),["url","webUrl","path","ref"]);if(!s)return null;const r=ue(a,["label","title","name","type","kind"])??n;return{id:Rf(e,s),kind:e,label:r,target:s}}function Cf(e){const t=new Set,n=[];for(const a of e){const s=`${a.kind}:${a.target}`;t.has(s)||(t.add(s),n.push(a))}return n}function Rf(e,t){return`${e}:${t}`}function $5(e,t,n){return[e?.childCalls,e?.childRuns,e?.implementationCalls,t?.childCalls,t?.childRuns,n?.childCalls,n?.childRuns].flatMap(s=>N5(s)).slice(0,6)}function N5(e){return(Array.isArray(e)?e:e?[e]:[]).flatMap((n,a)=>{const s=ce(n);if(!s)return[];const r=ue(s,["id","runId","callId"])??`child_${a+1}`,i=ue(s,["label","title","actionName","name","tool"])??ue(ce(s.action),["label","name"])??"Implementation call",c=ue(s,["detail","summary","runId","sandboxId","runtimeId"])??null;return[{id:r,label:i,status:D5(s),detail:c}]})}function D5(e){const t=ue(e,["status","state"]);return t==="running"||t==="completed"||t==="failed"||t==="pending"?t:t==="succeeded"?"completed":"unknown"}function L5(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}const z5=new Set([".avif",".gif",".jpeg",".jpg",".png",".webp"]);function c1(e){if(!e)return!1;const t=e.split("?")[0]?.split("#")[0]??e,n=t.lastIndexOf(".");return n<0?!1:z5.has(t.slice(n).toLowerCase())}function l1(e){return e.split("/").filter(Boolean).pop()??e}function H5(e){if(!Tf(e))return;const t=ce(e.data),a=(typeof t?.openpondImagePreviewPath=="string"?t.openpondImagePreviewPath:null)??qr(e.data)??qr(e.args)??qr(e.output);if(!(!a||!c1(a)))return{path:a,appId:e.appId??null,title:l1(a)}}function U5(e){if(e.name!=="tool.completed"&&e.name!=="workspace_action_result")return[];const t=[],n=new Set;return Pf(e.data,t,n),t.slice(0,12)}function Pf(e,t,n,a=0){if(a>7||e==null)return;if(Array.isArray(e)){for(const c of e)Pf(c,t,n,a+1);return}const s=ce(e);if(!s)return;const r=ue(s,["path","artifactRef"]),i=ue(s,["contentType","mimeType"]);r&&i&&!n.has(r)&&(n.add(r),t.push({path:r,title:ue(s,["title","name"])??l1(r),contentType:i,sizeBytes:typeof s.sizeBytes=="number"?s.sizeBytes:null}));for(const c of Object.values(s))Pf(c,t,n,a+1)}function Tf(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 qr(e,t=0,n=""){if(t>5||e==null)return null;if(typeof e=="string"){if(gp(n)&&c1(e.trim()))return e.trim();const s=xr(e);if(s!==null){const r=qr(s,t+1,n);if(r)return r}return q5(e)}if(Array.isArray(e)){for(const s of e){const r=qr(s,t+1,n);if(r)return r}return null}const a=ce(e);if(!a)return null;for(const[s,r]of Object.entries(a)){if(!gp(s))continue;const i=qr(r,t+1,s);if(i)return i}for(const[s,r]of Object.entries(a)){if(gp(s))continue;const i=qr(r,t+1,s);if(i)return i}return null}function gp(e){return/^(path|filePath|filepath|imagePath|image|localPath|uri|url)$/i.test(e)}function q5(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 B5(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=V5(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 F5(e){if(e.action!=="connected_app_search"&&e.action!=="connected_app_read"&&e.action!=="connected_app_write")return null;const t=d1(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 V5(e){return d1(e).providerLabel}function d1(e){const t=ce(e.args),n=ce(e.data),a=ce(n?.result),s=eh(ue(t,["provider"])??ue(a,["provider"])??ue(n,["provider"])??void 0),r=ue(a,["providerLabel"])??ue(n,["providerLabel"])??(s?SS(s)?.label:null)??"connected app",i=ue(t,["operation"]),c=ue(a,["operation"])??ue(n,["operation"]),u=vp(t?.capabilityIds)||vp(a?.capabilityIds)||vp(n?.capabilityIds);return{providerLabel:r,providerOperation:i,operation:c,capabilityCount:u}}function vp(e){return Array.isArray(e)?e.length:0}function u1(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()||bp(a)}}return t==="<turn_aborted>"?{kind:"turn_aborted",text:bp("turn_aborted")}:t==="<goal_context>"?{kind:"goal_context",text:bp("goal_context")}:null}function bp(e){return e==="turn_aborted"?"The previous turn was interrupted.":"Goal context updated."}function wu(e){return e.name==="diagnostic"&&ce(e.data)?.kind==="goal_context"}const K5="Steered by user";function W5(e){return e?.trim().toLowerCase()===K5.toLowerCase()}function G5(e,t){if(!t.turnId)return;X5(e,t.turnId);const n=Z5(t);if(!n)return;const a=Y5(e,t.turnId);if(a){a.refinerActivity=n;return}const s={id:`${t.id}:work-refiner`,role:"activity_group",activities:[],timestamp:t.timestamp,turnId:t.turnId,traceState:"completed",traceStartedAt:t.timestamp,traceCompletedAt:t.timestamp,refinerActivity:n},r=e.findIndex(i=>i.role==="assistant"&&i.turnId===t.turnId);r>=0?e.splice(r,0,s):e.push(s)}function Z5(e){const t=ce(e.data),n=ce(t?.activity);return n?J5(n,e):Q5(e,t)}function SG(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 · ${a6(e.route??"external")} issue routed`;const t=e.result==="applied"?"Applied":"Needs review";return`Refiner · ${e.summary} — ${t}`}function J5(e,t){const n=ds(e.state,["running","completed","failed"]);if(!n)return null;const a=n==="failed"?"failed":ds(e.result,["no_action","routed","applied","retained"]),s=Vn(e.reason)??t.output??t.error??null;return{state:n,visibility:ds(e.visibility,["always","material_only"])??"material_only",result:n==="running"?null:a,workspaceId:Vn(e.workspaceId),decision:ds(e.decision,["no_action","route","propose"]),route:Vn(e.route),operation:ds(e.operation,["create","update","delete"]),target:Vn(e.target),summary:Vn(e.summary)??m1(n,a),expectedOutcome:Vn(e.expectedOutcome),reason:s,evidenceBasis:e6(e.evidenceBasis),critiqueStatus:ds(e.critiqueStatus,["not_applicable","pending","passed","rejected","failed"])??(n==="running"?"pending":"not_applicable"),validationStatus:ds(e.validationStatus,["not_applicable","pending","passed","failed"])??(n==="running"?"pending":"not_applicable"),validations:t6(e.validationReceipts),edits:n6(e.edits),refs:{trigger:ls(e.trigger),outcome:ls(e.outcome),proposal:ls(e.proposal),applyReceipt:ls(e.applyReceipt),advanceReceipt:ls(e.advanceReceipt),inputHarness:ls(e.inputHarness),outputHarness:ls(e.outputHarness)}}}function Q5(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",s=ce(t?.outcome),r=ce(t?.proposal),i=s?.routed===!0,c=Vn(t?.workspaceAdvance),u=n?"failed":a?r?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:u,workspaceId:null,decision:r?"propose":i?"route":a?"no_action":null,route:Vn(s?.route),operation:null,target:null,summary:m1(n?"failed":a?"completed":"running",u),expectedOutcome:null,reason:e.output??e.error??null,evidenceBasis:null,critiqueStatus:r?"passed":"not_applicable",validationStatus:r?"pending":"not_applicable",validations:[],edits:[],refs:{trigger:ls(t?.trigger),outcome:ls(s),proposal:ls(r),applyReceipt:null,advanceReceipt:null,inputHarness:null,outputHarness:null}}}function Y5(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(s=>s.subagentMessage))return a}return null}function X5(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 e6(e){const t=ce(e),n=ds(t?.kind,["single_deterministic","recurrent_independent"]);return!t||!n?null:{kind:n,supportingEvidenceIds:py(t.supportingEvidenceIds),counterevidence:py(t.counterevidence)}}function t6(e){return Array.isArray(e)?e.flatMap(t=>{const n=ce(t),a=Vn(n?.id),s=ds(n?.status,["passed","failed","blocked","skipped"]),r=Vn(n?.summary);return a&&s&&r?[{id:a,status:s,summary:r}]:[]}):[]}function n6(e){return Array.isArray(e)?e.flatMap(t=>{const n=ce(t),a=Vn(n?.id),s=ds(n?.operation,["create","update","delete"]),r=Vn(n?.target),i=Vn(n?.summary);return!a||!s||!r||!i?[]:[{id:a,operation:s,target:r,summary:i,content:typeof n?.content=="string"?n.content:null}]}):[]}function ls(e){const t=ce(e),n=Vn(t?.id),a=Vn(t?.contentHash);return n&&a?`${n} · ${a.slice(0,12)}`:null}function py(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()):[]}function Vn(e){return typeof e=="string"&&e.trim()?e.trim():null}function ds(e,t){return typeof e=="string"&&t.includes(e)?e:null}function m1(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 a6(e){return e.length>0?`${e[0].toUpperCase()}${e.slice(1)}`:e}const fy=64*1024,hy=8*1024;function gy(e,t){const n=p1(t);if(n.subagentMessage){e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId});return}const a=s6(e,t.turnId);if(a){a.activities=i6(a.activities??[],t,n),a.timestamp=t.timestamp;return}ic(e,t),e.push({id:t.id,role:"activity_group",activities:[n],timestamp:t.timestamp,turnId:t.turnId,traceState:"running",traceStartedAt:t.timestamp})}function ic(e,t){for(let n=e.length-1;n>=0;n-=1){const a=e[n];a.role!=="activity_group"||a.activities?.some(s=>s.subagentMessage)||a.traceState==="running"&&(a.traceState="settled",a.traceCompletedAt=t.timestamp)}}function s6(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(s=>s.subagentMessage))return a}return null}function Af(e,t,n){if(!t.turnId)return;const a=e.filter(c=>c.role==="activity_group"&&c.turnId===t.turnId&&!c.activities?.some(u=>u.subagentMessage)),s=a.filter(c=>c.traceState==="running"),r=s.length>0?s:a.length>0?[a[a.length-1]]:[];for(const c of r)c.traceState=n;const i=r.at(-1);i&&(i.traceCompletedAt=t.timestamp,i.timestamp=t.timestamp)}function r6(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 s=a.activities?.filter(r=>r.controlKind!=="turn_aborted")??[];s.length!==a.activities?.length&&(s.length===0?e.splice(n,1):a.activities=s)}Af(e,t,"interrupted"),!W5(t.output)&&e.push({id:t.id,role:"status_divider",content:o6(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"interruption",statusState:"failed",statusTone:"danger"})}function o6(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 i6(e,t,n=p1(t)){const a=[...e];if(t.name==="tool.started"&&ce(t.data)?.nativeTool===!0&&n.callId){const s=gs(a,r=>r.callId===n.callId&&r.state==="running");if(s){const r=s.timestamp;return Object.assign(s,n,{timestamp:r}),a}}return v6(a,t,n)||f6(a,t,n)||h6(a,t,n)||g6(a,t,n)?a:[...a,n]}function c6(e){return e.name==="session.compaction.started"||e.name==="session.compaction.completed"||e.name==="session.compaction.failed"}function l6(e,t){const n={id:t.id,role:"status_divider",content:d6(t),timestamp:t.timestamp,turnId:t.turnId,statusKind:"compaction",statusState:u6(t),statusTone:m6(t)};if(t.name!=="session.compaction.started"){const a=gs(e,s=>s.role==="status_divider"&&s.statusKind==="compaction"&&s.statusState==="running"&&s.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 d6(e){const t=p6(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 m6(e){return e.name==="session.compaction.failed"?"danger":e.name==="session.compaction.completed"?"success":"info"}function p6(e){return ce(e.data)?.reason==="auto"?"auto":"manual"}function p1(e){const t=H5(e),n=e.name==="assistant.reasoning.delta"?"reasoning":R6(e),a=P6(e),s=E6(e),r=A6(e),i=j6(e),c=M6(e),u=U5(e);return{id:e.id,label:c?c.direction==="received"?"Child message received":"Child message sent":S6(e),content:c?.summary??k6(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:jg(e)??void 0}:{},...n&&e.name==="command.output"?{detail:Ef(e)}:{},...n!=="command"&&e.name==="tool.started"&&ce(e.data)?.nativeTool===!0&&e.args&&Object.keys(e.args).length>0?{detail:lr(JSON.stringify(e.args,null,2))}:{},...n!=="command"&&e.name==="tool.completed"&&ce(e.data)?.nativeTool===!0&&e.output?{detail:lr(e.output)}:{},...n==="command"?{terminal:z6(e)}:{},...r?{meta:r}:{},...s?{receipt:s}:{},...i?{openSession:i}:{},...c?{subagentMessage:c}:{},state:y6(e),...t?{imagePreview:t}:{},...u.length>0?{artifacts:u}:{}}}function f6(e,t,n){if(t.name==="tool.completed"){const a=vy(e,t);if(!a)return!1;const s=H6(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,...s!==null?{durationMs:s}:{}};const r=Ef(t);return r&&r!==a.content&&(a.detail=Dd(a.detail,r)),!0}if(t.name==="command.output"){const a=vy(e,t);if(!a)return!1;const s=Ef(t);return s&&(a.detail=Dd(a.detail,s)),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 h6(e,t,n){if(t.name!=="tool.completed"||n.kind==="command")return!1;const a=jg(t),s=gs(e,i=>i.state==="running"&&i.kind!=="command"&&(a?i.callId===a:!!t.action&&i.action===t.action));if(!s)return!1;const r=n.content.trim();return s.id=n.id,s.label=n.label,s.timestamp=n.timestamp,s.state=n.state,r&&r!==s.content.trim()&&(s.content.trim()===s.action?s.content=r:s.detail=Dd(s.detail,r)),n.detail&&(s.detail=Dd(s.detail,n.detail)),s.meta=n.meta,s.receipt=n.receipt,s.imagePreview=n.imagePreview??s.imagePreview,s.artifacts=n.artifacts,!0}function g6(e,t,n){if(t.name!=="workspace_action_result")return!1;const a=b6(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 v6(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 vy(e,t){const n=jg(t);if(n){const a=gs(e,s=>s.kind==="command"&&s.callId===n);if(a)return a}return gs(e,a=>a.kind==="command")}function b6(e,t){const n=t.action??"",a=f1[n]??{started:"Running workspace action"};return gs(e,s=>s.state==="running"&&s.label===a.started&&s.kind!=="command"&&!s.controlKind)}function y6(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 S6(e){if(e.name==="assistant.reasoning.delta")return ue(ce(e.data),["kind"])==="commentary"?"Update":"Reasoning";if(wu(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(Tf(e)&&e.name==="tool.started")return"Reading image";if(Tf(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=B5(e);if(t)return t;const n=I6(e);if(n)return n;const a=w6(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"?x6(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 f1={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 x6(e){const t=e.action??"",n=f1[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 k6(e,t){if(e.name==="assistant.reasoning.delta")return e.output??"";if(t)return t.path;const n=u1(e.output??"");if(n)return n.text;if(wu(e)||e.name==="turn.interrupted")return e.output??e.error??"";const a=_6(e);if(a)return a;const s=C6(e);if(s)return s;const r=F5(e);if(r)return r;const i=h1(e);if(i)return i;if(e.name==="command.output")return v1(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 u=c.command;if(typeof u=="string"&&u.trim())return u;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 w6(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 I6(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 _6(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(xr(e.output??"")),s=ue(a,["output"]);if(s)return s;const r=ce(e.args),i=ue(r,["url"]);return i||(e.action==="openpond_browser_type"?"Text redacted":e.error??e.output??e.action)}function C6(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(xr(e.output??"")),s=ue(a,["output"]);if(s)return s;const r=ce(e.args),i=ue(r,["reason"]);if(i)return i;const c=ue(r,["objective"]);return c||(e.error??null)}function R6(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"||h1(e)||a&&/(^|[._-])exec_command$/i.test(a))return"command"}function P6(e){if(e.name==="turn.interrupted")return"turn_aborted";if(wu(e))return"goal_context"}function h1(e){const t=ce(e.data),n=ue(t,["type"]),a=ue(t,["tool","toolName","tool_name","name","functionName","function_name"]),s=ce(t?.result),r=ce(xr(e.output??"")),i=ce(r?.data),c=ue(t,["command","cmd"])??ue(ce(t?.input),["command","cmd"])??ue(ce(t?.arguments),["command","cmd"])??ue(ce(t?.args),["command","cmd"])??T6(ue(t,["arguments","args","input"]))??ue(ce(e.args),["command","cmd"])??ue(s,["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 T6(e){if(!e)return null;const t=xr(e),n=ce(t);return ue(n,["command","cmd"])}function jg(e){const t=ce(e.data);return ue(t,["callId","call_id","toolCallId","tool_call_id","id","itemId","item_id"])}function A6(e){const t=ce(e.data);if(!t)return null;const n=[],a=ce(t.workspaceToolTiming),s=typeof a?.durationMs=="number"?a.durationMs:null;s!==null&&n.push(N6(s));const r=ce(t.workspaceExecutionTarget),i=ue(r,["target"]);if(i==="sandbox"){const l=r?.hybrid===!0,p=ue(r,["sandboxId","workspaceId"]);n.push(`${l?"Hybrid ":""}sandbox${p?` ${by(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 ${L6(l)}`:"checkpoint saved")}else n.push("checkpoint clean");const u=g1(t);return u&&(n.push(`receipt ${by(u.id)}`),n.push(`${D6(u.totalUsd)} ${u.status}`)),n.length>0?n.join(" · "):null}function E6(e){const t=g1(ce(e.data));return t?{id:t.id,status:t.status,totalUsd:t.totalUsd}:void 0}function j6(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 s=ue(n,["roleId"])??ue(t,["roleId"]),r=ue(n,["status"])??ue(t,["status"]);return{sessionId:a,label:"Open conversation",...s?{roleId:s}:{},...r?{status:r}:{}}}function M6(e){if(e.name!=="subagent.message")return;const t=ce(e.data),n=ce(t?.message);if(!n)return;const a=ue(n,["id"]),s=ue(n,["kind"]),r=ue(n,["fromRunId"]),i=ue(n,["body"]);if(!a||!s||!r||!i)return;const c=ce(t?.delivery??n.delivery),u=ce(t?.modelRef),l=ue(u,["providerId"]),p=ue(u,["modelId"]),y=ue(c,["deliveredParentSessionId"])===e.sessionId&&!r.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:y,summary:O6(i),body:i,messageId:a,kind:s,fromRunId:r,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 O6(e){const t=e.replace(/\s+/g," ").trim();if(!t)return"No message body";const n=/^(.*?[.!?])(?:\s|$)/.exec(t)?.[1]??t;return $6(n,96)}function $6(e,t){if(e.length<=t)return e;const n=e.slice(0,t-1),a=n.lastIndexOf(" "),s=a>=Math.floor(t*.55)?a:t-1;return`${n.slice(0,s).trimEnd()}...`}function g1(e){const t=ce(e?.sandbox),n=Array.isArray(t?.receipts)?t.receipts:[];for(let a=n.length-1;a>=0;a-=1){const s=ce(n[a]),r=ue(s,["id"]),i=ue(s,["status"]),c=ue(s,["totalUsd","retailTotalUsd"]);if(r&&i&&c)return{id:r,status:i,totalUsd:c}}return null}function N6(e){return e<1e3?`${Math.max(0,Math.round(e))} ms`:e<1e4?`${(e/1e3).toFixed(1)} s`:`${Math.round(e/1e3)} s`}function D6(e){const t=e.trim();return t.startsWith("$")?t:`$${t}`}function L6(e){return e.length>12?e.slice(0,12):e}function by(e){const t=e.trim();return t.length<=14?t:`${t.slice(0,6)}...${t.slice(-4)}`}function v1(e){let t=e.replace(/\r\n/g,`
|
|
116
|
+
`).trim();if(!t)return"";const n=U6(t);if(n!==null)return lr(n);const a=`
|
|
117
|
+
Output:
|
|
118
|
+
`,s=t.indexOf(a);return s>=0&&q6(t.slice(0,s))&&(t=t.slice(s+a.length).trim()),t=t.replace(/^Total output lines: \d+\n\n/,""),lr(t.trim())}function Ef(e){const t=v1(e.output??"");if(t)return t;const n=ce(ce(e.data)?.result);return n?lr(b1(n)):""}function z6(e){const t=ce(e.data),n=ce(t?.result),a=ce(xr(e.output??"")),s=ce(a?.data),r=ce(t?.workspaceToolTiming),i=[n?.exitCode,s?.exitCode,t?.exitCode].find(u=>typeof u=="number"),c=r?.durationMs;return{...typeof i=="number"?{exitCode:i}:{},...typeof c=="number"?{durationMs:c}:{}}}function H6(e,t){const n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function U6(e){const t=ce(xr(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?b1(a,ue(t,["output"])):typeof t.output=="string"?t.output.trim():""}function b1(e,t=null){const n=ue(e,["stdout"])?.replace(/\r\n/g,`
|
|
119
|
+
`).trimEnd()??"",a=ue(e,["stderr"])?.replace(/\r\n/g,`
|
|
120
|
+
`).trimEnd()??"",s=[n,a].filter(Boolean);return s.length>0?s.join(`
|
|
121
|
+
`):t?.replace(/\r\n/g,`
|
|
122
|
+
`).trim()??""}function q6(e){return/^(Chunk ID|Exit code):/m.test(e)&&/Wall time:/m.test(e)}function Dd(e,t){const n=e??"";if(!n)return lr(t);if(n===t||n.includes(t))return n;if(t.includes(n))return lr(t);const a=n.endsWith(`
|
|
123
|
+
`)||t.startsWith(`
|
|
124
|
+
`)?"":`
|
|
125
|
+
`;return lr(`${n}${a}${t}`)}function lr(e){if(e.length<=fy)return e;const t=`
|
|
126
|
+
|
|
127
|
+
… output omitted from live view; full output remains in task history …
|
|
128
|
+
|
|
129
|
+
`,n=Math.max(0,fy-hy-t.length);return`${e.slice(0,hy)}${t}${e.slice(-n)}`}const B6=/\bopenpond\s+opchat\b/i,F6=/\b(?:50[0-9]|52[0-9]|53[0-9])\b|bad\s+gateway|gateway\s+timeout|service\s+unavailable/i;function y1(e){const t=e?.trim()||"Turn failed";return B6.test(t)&&F6.test(t)?"Server connection lost. Retry your message.":t}function V6(e,t){if((ql(t,"code")??ql(t,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const a=t&&typeof t=="object"?t.error:null;if(a&&typeof a=="object"&&(ql(a,"code")??ql(a,"errorCode"))==="opchat_quota_exceeded")return"opchat_quota_exceeded";const s=e??"";return/\bopchat_quota_exceeded\b/i.test(s)||/OpChat token allowance is exhausted/i.test(s)?"opchat_quota_exceeded":null}function ql(e,t){if(!e||typeof e!="object")return null;const a=e[t];return typeof a=="string"&&a.trim()?a.trim():null}function K6(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 s=W6(a.activities??[]);if(s.length===0){a.deliverables=void 0;continue}const r=t.get(a.turnId)??"",i=r?G6(s,r):[];if(i.length>0){a.deliverables=i;continue}a.deliverables=n.has(a.turnId)?[s[s.length-1]]:void 0}}function W6(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 s of a.artifacts??[])t.has(s.path)||(n.delete(s.path),n.set(s.path,s));return[...n.values()]}function G6(e,t){const n=S1(t);return e.filter(a=>Z6(a).some(s=>t.includes(s)||n.includes(s)))}function Z6(e){const t=new Set;for(const n of[e.path,e.title,J6(e.path)]){const a=n.trim();a&&(t.add(a),t.add(S1(a)))}return[...t]}function J6(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).at(-1)??e}function S1(e){try{return decodeURIComponent(e)}catch{return e}}const x1=8;function Q6(e){if(e.name!=="tool.completed"||e.status==="failed")return[];if(e.action!=="web_search"&&e.action!=="web_fetch")return[];const t=jf(e.data),n=e.output?jf(xr(e.output)):null;return Y6(t??n)}function Ld(e,t){if(t.length===0)return e;const n=[],a=new Set;for(const s of[...e??[],...t]){const r=k1(s.url);if(!(!r||a.has(r))&&(a.add(r),n.push(s),n.length>=x1))break}return n.length>0?n:void 0}function jf(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 s of["result","data","output"]){const r=jf(n[s],t+1);if(r)return r}return null}function Y6(e){if(!e)return[];const t=[],n=new Set;for(let a=0;a<e.results.length;a+=1){const s=X6(e.results[a],a,e.provider);if(!s)continue;const r=k1(s.url);if(!(!r||n.has(r))&&(n.add(r),t.push(s),t.length>=x1))break}return t}function X6(e,t,n){const a=ce(e);if(!a)return null;const s=ue(a,["url","href"]);if(!s||!e3(s))return null;const r=ue(a,["title"])??yy(s)??`Source ${t+1}`;return{id:ue(a,["id"])??`source_${t+1}`,title:r,url:s,sourceName:ue(a,["sourceName","source_name","source"])??yy(s),snippet:ue(a,["snippet","description"]),provider:n,faviconUrl:t3(ue(a,["faviconUrl","favicon_url","iconUrl","icon_url"]))??n3(s),publishedAt:ue(a,["publishedAt","published_at"]),updatedAt:ue(a,["updatedAt","updated_at"])}}function e3(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function k1(e){try{const t=new URL(e);return t.hash="",t.toString()}catch{return null}}function t3(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 n3(e){try{return new URL("/favicon.ico",e).toString()}catch{return null}}function yy(e){try{return new URL(e).hostname.replace(/^www\./i,"")}catch{return null}}function a3(e){const t=ce(e.data),n=Xh.safeParse(t?.input);if(!n.success||n.data.senderKind==="user")return null;const a=n.data,s=ce(t?.delivery);if(a.senderKind==="ponder"){const l=_D.safeParse(ce(a.payload.ponderDesktop)?.operation),p=ce(s?.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 r=s?.direction==="sent"&&e.sessionId===a.senderSessionId;if(!r&&e.sessionId!==a.sessionId)return null;const i=r?a.sessionId:a.senderSessionId,c=ce(s?.peer),u=c?.sessionId===i;return{id:`task-input:${a.id}:${r?"sent":"received"}`,role:"task_message",content:a.body,timestamp:a.createdAt,turnId:r?void 0:a.turnId??void 0,taskMessage:{input:a,direction:r?"sent":"received",peer:{sessionId:i,title:u&&typeof c.title=="string"?c.title:"Another task",provider:u&&typeof c.provider=="string"?c.provider:""}}}}function Sy(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 s3(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)??{},s=e.name==="tool.started",r=typeof n.callId=="string"?n.callId:null,i=s&&typeof a.name=="string"?a.name:(r?t.get(r):void 0)??"native_tool";s&&r&&t.set(r,i);let c=a.input??a.arguments;if(typeof c=="string")try{c=JSON.parse(c)}catch{c={input:c}}const u=a.error||(a.is_error===!0?a.content:null);return{...e,action:i,status:s?"started":u!=null||a.status==="error"?"failed":"completed",...s?{args:ce(c)??{}}:{output:Sy(a.output??a.content??n.content),...u!=null?{error:Sy(u)}:{}}}}function r3(e,t,n){const a=ce(n.data),s=n.name==="assistant.delta"&&a?.phase==="final_answer"&&a.nativeMessageSnapshot===!0,r=n.name==="assistant.reasoning.delta"&&(a?.phase==="commentary"||a?.phase==="reasoning");if(!s&&!r||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)),s){c.content=n.output,delete c.reasoningContent;const u=e.indexOf(c);u!==e.length-1&&(e.splice(u,1),e.push(c))}else c.content===void 0&&(c.reasoningContent=`${c.reasoningContent??""}${n.output}`);return c.timestamp=n.timestamp,c}const xy=new WeakMap;function Iu(e){const t=xy.get(e);if(t)return t;const n=o3(e);return xy.set(e,n),n}function o3(e){const t=[],n=new Set,a=new Map,s=new Map,r=new Map,i=new Map;for(const c of e){const u=s3(c,r);if(u.name==="task.input"){const p=a3(u);if(p){const y=a.get(p.id);if(!y)a.set(p.id,p),t.push(p);else{const b=p.taskMessage.input,I=y.taskMessage.input;(b.revision>I.revision||b.revision===I.revision&&b.updatedAt>=I.updatedAt)&&Object.assign(y,p)}continue}const f=Xh.safeParse(ce(u.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:u.timestamp,turnId:f.data.turnId??void 0}));continue}if(u.name==="turn.started"){ic(t,u),i3(t,u);const p=u3(u.args);if(p){const f=ce(u.args)?.taskInputId,y=typeof f=="string"?a.get(`task-input:${f}:received`):null;if(y?.taskMessage?.input.kind==="followup"){y.turnId=u.turnId;continue}const b=u1(p);if(b){gy(t,{...u,name:b.kind==="turn_aborted"?"turn.interrupted":"diagnostic",output:b.text,data:{...ce(u.data)??{},kind:b.kind}});continue}t.push({id:u.id,role:"user",content:p,attachments:m3(u.args),timestamp:u.timestamp,turnId:u.turnId});const I=ky(u.args);I&&t.push({id:`${u.id}:create-improve`,role:"assistant",timestamp:u.timestamp,turnId:u.turnId,createImproveRun:I})}continue}if(u.name==="create_improve.updated"){const p=ky(u.data);if(!p)continue;const f=gs(t,y=>y.turnId===u.turnId&&!!y.createImproveRun);f?(f.createImproveRun=p,f.timestamp=u.timestamp):t.push({id:`${u.id}:create-improve`,role:"assistant",timestamp:u.timestamp,turnId:u.turnId,createImproveRun:p});continue}const l=r3(t,i,u);if(l){ic(t,u),l.sources=Ld(l.sources,yp(s,u.turnId)??[]);continue}if(u.name==="assistant.delta"){const p=u.output??"";if(!p)continue;ic(t,u);const f=ce(u.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=u.timestamp):t.push({id:b,role:"assistant",content:p,timestamp:u.timestamp,turnId:u.turnId});continue}const y=t[t.length-1];if(y?.role==="assistant"&&y.turnId===u.turnId&&!y.createImproveRun)y.content=`${y.content??""}${p}`,y.timestamp=u.timestamp,y.sources=Ld(y.sources,yp(s,u.turnId)??[]);else{const b=yp(s,u.turnId);t.push({id:u.id,role:"assistant",content:p,timestamp:u.timestamp,turnId:u.turnId,...b?.length?{sources:b}:{}})}continue}if(u.name==="assistant.reasoning.delta"){const p=u.output??"";if(!p)continue;ic(t,u);const f=t[t.length-1];f?.role==="assistant"&&f.turnId===u.turnId&&f.reasoningContent!==void 0&&!f.createImproveRun?(f.reasoningContent=`${f.reasoningContent}${p}`,f.timestamp=u.timestamp):f?.role==="assistant"&&f.turnId===u.turnId&&!f.reasoningContent&&!f.createImproveRun?(f.reasoningContent=p,f.timestamp=u.timestamp):t.push({id:u.id,role:"assistant",reasoningContent:p,timestamp:u.timestamp,turnId:u.turnId});continue}if(u.name==="user_question.asked"){const p=ce(u.data),f=gE.safeParse(p?.question);if(!f.success)continue;t.push({id:u.id,role:"assistant",timestamp:u.timestamp,turnId:u.turnId,userQuestion:f.data});continue}if(u.name==="user_question.answered"||u.name==="user_question.dismissed"){const p=ce(u.data),f=vE.safeParse(p?.resolution);if(!f.success)continue;const y=gs(t,b=>b.userQuestion?.id===f.data.questionId);if(!y?.userQuestion||y.userQuestion.status!=="pending")continue;y.userQuestion={...y.userQuestion,status:f.data.action==="answer"?"answered":"dismissed",answer:f.data.action==="answer"?{optionId:f.data.optionId,text:f.data.text}:null,answeredAt:u.timestamp},y.timestamp=u.timestamp;continue}if(u.name==="turn.completed"){Af(t,u,"completed");continue}if(u.name==="turn.failed"){Af(t,u,"failed");const p=u.error??"Turn failed",f=V6(p,u.data);t.push({id:u.id,role:"error",content:y1(p),...f?{errorKind:f}:{},timestamp:u.timestamp,turnId:u.turnId});continue}if(u.name==="turn.interrupted"){r6(t,u);continue}if(c6(u)){l6(t,u);continue}if(u.name.startsWith("harness.refiner.")){G5(t,u);continue}if(u.name==="tool.started"||u.name==="tool.completed"||u.name==="skill.selected"||u.name==="skill.loaded"||u.name==="skill.load_failed"||u.name==="command.output"||u.name==="workspace_action"||u.name==="workspace_action_result"||u.name==="approval.requested"||u.name.startsWith("subagent.")||wu(u)){if(l3(u))continue;const p=j5(u);if(p){E5(t,u,p);continue}const f=Q6(u);f.length>0&&c3(t,s,u.turnId,f),gy(t,u)}if(u.name==="workspace.diff"){const p=d3(u.data);if(!p||p.filesChanged===0)continue;const f=gs(t,y=>y.role==="assistant"&&y.turnId===u.turnId);f&&(f.changeSummary=p,f.timestamp=u.timestamp)}}return K6(t),t}function i3(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 c3(e,t,n,a){if(!n)return;const s=e[e.length-1];if(s?.role!=="assistant"||s.turnId!==n){t.set(n,Ld(t.get(n),a));return}s.sources=Ld(s.sources,a)}function yp(e,t){if(!t)return;const n=e.get(t);return n&&e.delete(t),n}function l3(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 d3(e){const t=ME.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 m3(e){if(!e||typeof e!="object"||!("attachments"in e))return;const t=aM.array().safeParse(e.attachments);return t.success&&t.data.length>0?t.data:void 0}function ky(e){const t=ce(e);if(!t)return null;const n=Hc.safeParse(t.createImproveRun);return n.success?n.data:null}function xG(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 s=Math.floor(a/60);return s<48?`${s}h`:`${Math.floor(s/24)}d`}function kG(e){const t=w1(e);return t?t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):""}function wG(e){const t=w1(e);return t?t.toLocaleString():""}function w1(e){if(!e)return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function p3(e){const{chatMessages:t,runtimeIndexes:n,selectedSessionId:a}=e,[s,r]=h.useState({}),i=h.useCallback(u=>{r(l=>({...l,[u.sessionId]:u}))},[]);h.useEffect(()=>{r(u=>{let l=u;for(const[p,f]of Object.entries(u)){const y=Iu(Xc(n,p));i1(y,f)&&(l===u&&(l={...u}),delete l[p])}return l})},[n]);const c=h.useMemo(()=>o1(t,a?s[a]:null),[t,s,a]);return{pendingChatUserMessages:s,recordPendingChatUserMessage:i,visibleChatMessages:c}}function f3({connection:e,selectedSession:t,setBootstrap:n,setError:a,setOpenPondCommandAccessMode:s,setSessions:r}){return{changeOpenPondCommandAccessMode:h.useCallback((c,u=t)=>{if(!e){a("Connect to OpenPond before saving preferences.");return}const l=u?.provider==="codex"?null:u;Z.savePreferences(e,{openPondCommandAccessMode:c}).then(p=>{s(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=>{r(f=>f.map(y=>y.id===p.id?p:y))}).catch(p=>{a(p instanceof Error?p.message:String(p))})},[e,t,n,a,s,r])}}function h3({localProjects:e,cloudProjects:t,teamId:n,sessions:a,runtimeIndexes:s,appPreferences:r,selectedSessionId:i,selectedProjectId:c,archivedChatsOpen:u,projectsExpanded:l,chatRowsVisibleCount:p,sidebarFileBookmarks:f=[]}){const y=h.useMemo(()=>e.filter(Q=>!Q.hiddenFromDefaultSidebar),[e]),b=h.useMemo(()=>a.filter(Q=>!Q.archived&&wy(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&&wy(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(()=>nI(e),[e]),T=h.useMemo(()=>{const Q={};for(const je of a){const De=wb(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 ze=je.parentSessionId;for(;ze&&!De.has(ze);){if(Q[ze]){Q[je.id]=Q[ze];break}De.add(ze),ze=xe.get(ze)?.parentSessionId}}return Q},[a,M,_,A]),S=h.useMemo(()=>b.filter(Q=>!Q.pinned&&!Q.savedForLater&&!Q.appId&&!T[Q.id]),[b,T]),w=h.useMemo(()=>P.filter(Q=>!Q.appId&&!wb(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(!I1(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(()=>y.map((Q,xe)=>{const je=it("local",Q.id),De=vF(Q,t);return{id:je,kind:"local",project:Q,pinned:!!r[je]?.pinned,order:r[je]?.order??xe,cloudLinkTrusted:!De,cloudLinkWarning:De}}).sort(Sp),[r,t,y]),$=h.useMemo(()=>t.filter(Q=>!!n&&Q.teamId===n).map((Q,xe)=>{const je=it("cloud",Q.id);return{id:je,kind:"cloud",project:Q,pinned:!!r[je]?.pinned,order:r[je]?.order??xe,cloudLinkTrusted:!0,cloudLinkWarning:null}}).sort(Sp),[r,t,n]),V=h.useMemo(()=>new Set(y.map(Q=>Ca(Q,t)?.id??null).filter(Q=>!!Q)),[t,y]),Y=h.useMemo(()=>$.filter(Q=>!V.has(Q.project.id)),[$,V]),se=h.useMemo(()=>[...z,...Y].sort(Sp),[Y,z]),ee=h.useMemo(()=>se.filter(Q=>Q.pinned),[se]),H=h.useMemo(()=>f.filter(Q=>Q.status==="pinned"),[f]),F=h.useMemo(()=>f.filter(Q=>Q.status==="saved_for_later"),[f]),J=se,K=h.useMemo(()=>g3(J,l,c),[J,l,c]),B=h.useMemo(()=>[...ee.map(Q=>({type:"project",key:Ur({type:"project",id:Q.id}),id:Q.id,item:Q,order:Q.order})),...I.map(Q=>({type:"session",key:Ur({type:"session",id:Q.id}),id:Q.id,session:Q,order:Q.order})),...H.map((Q,xe)=>({type:"file",key:Ur({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 ze={project:0,session:1,file:2};return ze[Q.type]-ze[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(()=>u?[...S,...w]:S,[u,w,S]),G=h.useMemo(()=>ne.slice(0,Math.max($n,p)),[ne,p]),te=h.useMemo(()=>Xc(s,i),[s,i]),oe=h.useMemo(()=>Iu(te),[te]),ve=HI(s,i),me=UI(s,i),Re=aF(s,i);return{activeSessions:b,pinnedSessions:I,savedForLaterSessions:C,pinnedFiles:H,savedForLaterFiles:F,chatSessions:S,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:ve,goalRuntime:me,subagentRuntime:Re}}function wy(e){return I1(e)?!1:e.hiddenFromDefaultSidebar?e.metadata?.benchmarkRuntime==="desktop_local_work":!0}function I1(e){return!!(e.parentSessionId&&e.subagentRunId)}function Sp(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 g3(e,t,n){if(t||e.length<=rd)return e;const a=e.slice(0,rd);if(!n||a.some(r=>r.id===n))return a;const s=e.find(r=>r.id===n);return s?[...a.slice(0,rd-1),s]:a}function v3(e){return e.name==="turn.completed"||e.name==="turn.failed"||e.name==="turn.interrupted"}function _1(e){let t=-1,n=null;for(let a=e.length-1;a>=0;a-=1){const s=e[a];if(s?.name==="turn.started"){t=a,n=s.turnId??null;break}}if(t===-1)return"none";for(let a=e.length-1;a>t;a-=1){const s=e[a];if(!(!s||!v3(s))&&!(n&&s.turnId&&s.turnId!==n))return s.name==="turn.completed"?"completed":"blocked"}return"pending"}function Iy(e,t){if(e.systemKind)return!1;const n=Xc(t,e.id);if(n.length===0)return!1;const a=_1(n);return a==="pending"||a==="none"&&C1(n)==="pending"}function _y(e,t){if(e.systemKind||e.status!=="active")return!1;const n=Xc(t,e.id);if(n.length===0)return!0;const a=_1(n);return a==="pending"||a==="none"&&C1(n)!=="terminal"}function C1(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 b3({goalRuntime:e,goalRuntimeBySessionId:t,runtimeIndexes:n,selectedSession:a,selectedSessionId:s,sidebarSessions:r,subagentRuntimeBySessionId:i}){const c=h.useMemo(()=>new Map(r.map(y=>[y.id,y])),[r]),u=h.useMemo(()=>{const y=new Set;for(const[b,I]of t??[]){const C=c.get(b);I.tone==="active"&&!C?.systemKind&&y.add(b)}for(const b of n.activeGoalSessionIds)c.get(b)?.systemKind||y.add(b);return s&&!a?.systemKind&&e?.tone==="active"&&y.add(s),y},[e,t,n,a,s,c]),l=h.useMemo(()=>{const y=new Set(u);for(const[b,I]of i??[]){const C=c.get(b);I.activeCount>0&&!C?.systemKind&&y.add(b)}for(const b of n.activeSubagentSessionIds)c.get(b)?.systemKind||y.add(b);for(const b of r)b.systemKind||Iy(b,n)&&y.add(b.id);return a&&Iy(a,n)&&y.add(a.id),y},[u,n,a,r,c,i]),p=h.useMemo(()=>{const y=new Set(l);for(const b of r)_y(b,n)&&y.add(b.id);return a&&_y(a,n)&&y.add(a.id),y},[l,n,a,r]),f=!!(a&&!a.systemKind&&l.has(a.id));return{runningSessionIds:p,selectedSessionRunning:f}}const y3=1e3;function S3(e){const[t,n]=h.useState(()=>new Date().toISOString());return h.useEffect(()=>{if(!e)return;const a=()=>n(new Date().toISOString());a();const s=window.setInterval(a,y3);return()=>window.clearInterval(s)},[e]),t}function x3(e){const{codexHistoryEvents:t,codexHistorySessions:n,connection:a,expandedProjectIds:s,goalRuntime:r,locallyActiveCodexHistorySessionIds:i,pinnedSessions:c,savedForLaterSessions:u,projectSessionRowsByProjectId:l,rightChatHistoryEvents:p,runtimeIndexes:f,selectedSession:y,selectedSessionId:b,serverId:I,setCodexHistorySessions:C,sidebarSessions:P,subagentRuntime:_,visibleChatRows:M,visibleProjectRows:A}=e,[T,S]=h.useState({});h.useEffect(()=>{S({})},[I]);const w=h.useMemo(()=>{const B=[],ne=new Set,G=oe=>{!oe||oe.id===b||!Wt(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 ve of(l[oe.id]??[]).slice(0,2))G(ve);for(const oe of s)for(const ve of(l[oe]??[]).slice(0,rd))G(ve);for(const oe of c)G(oe);for(const oe of u)G(oe);for(const oe of M)G(oe);return[...B.slice(0,te),...B.slice(te,te+8)].join(`
|
|
131
|
+
`)},[n,s,i,c,u,l,b,M,A]),R=h.useCallback(B=>{S(ne=>ne[B.session.id]===B.events?ne:{...ne,[B.session.id]:B.events}),C(ne=>ku(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(()=>{!y||!b||!Wt(b)||t.length===0||R({session:y,events:t})},[R,t,y,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(ve=>Eg({connection:B,locallyActive:te.has(ve),onPayload:me=>R(Ag(me,te.has(ve))),reportedActive:G.has(ve),sessionId:ve,surface:"sidebar"}));return()=>oe.forEach(ve=>ve())},[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"?mp(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),ve=oe?.status==="active"?mp(oe.metadata):null,me=xf(te)??Cg(te)??(oe?.status==="active"?Nd(te)??ve:null);me?B.set(G,me):B.delete(G)}if(b)if(r)B.set(b,r);else if(y?.status==="active"&&t.length>0){const ne=xf(t)??Nd(t)??mp(y.metadata);ne?B.set(b,ne):B.delete(b)}else(!Wt(b)||t.length>0)&&B.delete(b);return B},[t.length,T,r,p,f.latestGoalRuntimeBySessionId,y?.status,y?.metadata,b,$,P]),Y=h.useMemo(()=>[...V.values()].some(B=>B.tone==="active"&&!!B.observedAt),[V]),se=S3(Y),ee=h.useMemo(()=>Y?new Map([...V].map(([B,ne])=>[B,M4(ne,se)??ne])):V,[V,se,Y]),H=b?ee.get(b)??r:r,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}=b3({goalRuntime:H,goalRuntimeBySessionId:ee,runtimeIndexes:f,selectedSession:y,selectedSessionId:b,sidebarSessions:P,subagentRuntimeBySessionId:F});return{goalRuntime:H,runningSessionIds:J,selectedSessionRunning:K,sidebarGoalRuntimeBySessionId:ee,sidebarSubagentRuntimeBySessionId:F}}function k3({searchOpen:e,sectionMenuOpen:t,setSectionMenuOpen:n,setSearchOpen:a,setQuery:s}){h.useEffect(()=>{const r=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),s(""),n(null);return}i.key==="Escape"&&t&&(i.preventDefault(),n(null))};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[e,t,s,a,n])}function w3({afterSequence:e,appendEvents:t,connection:n,setApprovals:a,setSessions:s,setError:r,onDisconnected:i}){h.useEffect(()=>{if(!n?.token||e===null)return;const c=n;let u=null,l=[],p=null,f=null,y=!1;const b=new Map;let I=0;const C=16;function P(){u!==null&&(window.clearTimeout(u),u=null)}function _(){r($=>$==="Event stream disconnected"?null:$)}function M(){p=null;const $=l;if(l=[],$.length===0)return;I=Date.now(),t($);const V=I3($);V.length>0&&s(Y=>V.reduce(oc,Y)),a(Y=>{let se=Y;for(const ee of $)if(ee.name==="approval.requested"&&ee.data&&(se=[ee.data,...se]),ee.name==="approval.resolved"&&ee.data&&typeof ee.data=="object"){const H=ee.data;H.approvalId&&(se=se.filter(F=>F.id!==H.approvalId))}return se})}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($){S($),l.push($),A()}function S($){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(!(y||b.size===0)){y=!0;try{await Promise.all([...b].map(async([$,V])=>{const Y=await Z.runtimeEventsPage(c,{sessionId:$,afterSequence:V,limit:100});for(const se of Y.events){const ee=se.event;b.set($,Math.max(b.get($)??0,se.sequence)),T(ee)}}))}catch{}finally{y=!1,w()}}}function O(){p!==null&&(window.clearTimeout(p),p=null),M()}document.addEventListener("visibilitychange",O);const z=Q_(n,$=>{P(),_(),T($)},()=>{P(),u=window.setTimeout(()=>{z.isOpen()||(r("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,r,s])}function I3(e){const t=new Map;for(const n of e){const a=n.data;if(!a||typeof a!="object"||Array.isArray(a))continue;const s=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(!s)continue;const r=Vp.safeParse(a[s]);r.success&&t.set(r.data.id,r.data)}return[...t.values()]}function xp(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function _3(e){return typeof e=="string"&&e.trim()?e.trim():null}function C3(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.name!=="create_improve.updated")continue;const a=xp(n.data),s=xp(a?.createImproveRun);if(s?.state!=="ready_local"&&s?.state!=="released"||xp(s.adapter)?.kind!=="local")continue;const i=_3(s.id)??n.id;return[n.sessionId??"global",n.turnId??"turn",i].join(":")}return null}const R3=332,Cy=244,Ry=560,P3=560,Py=320,Ty=2400,T3=440;function kp(e){const t=typeof window>"u"?Ry:Math.min(Ry,Math.max(Cy,window.innerWidth-420));return Math.min(t,Math.max(Cy,Math.round(e)))}function wp(e){const t=typeof window>"u"?Ty:Math.min(Ty,Math.max(Py,window.innerWidth-T3));return Math.min(t,Math.max(Py,Math.round(e)))}function A3(e,t){return!!(e&&e.serverUrl===t.serverUrl&&e.token===t.token&&e.platform===t.platform)}const Vo=new Map;function Mg(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function R1(e,t){const n=Mg(e,t);if(!n)return null;const a=Vo.get(n);return a?.updatedAt?a.agents:null}function E3(e,t,n){const a=Mg(e,n);a&&Vo.set(a,{agents:t,promise:null,updatedAt:Date.now()})}function Og(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=Mg(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Vo.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.agents);if(a?.promise)return a.promise}const s=e.fetchAgents(t).then(r=>(E3(t,r,e.accountKey),r)).catch(r=>{const i=Vo.get(n);throw i?.promise===s&&Vo.set(n,{agents:i.agents,promise:null,updatedAt:i.updatedAt}),r});return Vo.set(n,{agents:a?.agents??[],promise:s,updatedAt:a?.updatedAt??0}),s}const j3=6e4,M3=6e4,O3=6e4,$g=["pinned","projects","cloudProjects","chats","savedForLater"];function $3(e,t,n,a=Date.now()){for(const s of z3(t,n))P1(t[s],n[s])||(e[s]=a)}function N3(e,t,n,a=Date.now()){const s={...t};for(const[r,i]of Object.entries(n)){if(a-i>j3){delete n[r];continue}const c=U3(e,r),u=e[r];!c||P1(u,t[r])||(s[r]=u)}return s}function D3(e,t,n,a=Date.now()){for(const s of $g)t[s]!==n[s]&&(e[s]=a)}function L3(e,t,n,a=Date.now()){const s={...t};for(const r of $g){const i=n[r];if(i!==void 0){if(a-i>M3){delete n[r];continue}if(e[r]===t[r]){delete n[r];continue}s[r]=e[r]}}return H3(e,s)?e:s}function Ay(e,t,n=Date.now()){return e===t?null:{value:t,changedAt:n}}function Ey(e,t,n=Date.now()){return t?n-t.changedAt>O3?{value:e,localChange:null}:e===t.value?{value:e,localChange:t}:{value:t.value,localChange:t}:{value:e,localChange:null}}function z3(e,t){return new Set([...Object.keys(e),...Object.keys(t)])}function P1(e,t){return e?.pinned===t?.pinned&&e?.archived===t?.archived&&e?.order===t?.order}function H3(e,t){return $g.every(n=>e[n]===t[n])}function U3(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const q3=5e4,ar="\0openpond-unscoped-runtime-events",is=[];class B3{perSessionLimit;totalLimit;entries=new Map;eventKeyById=new Map;listenersByKey=new Map;allListeners=new Set;summaryListeners=new Set;retainedKeys=new Set;allEventsSnapshot=is;summaryEventsSnapshot=is;clock=0;eventCount=0;constructor(t={}){if(this.perSessionLimit=Oy(t.perSessionLimit??_g,"perSessionLimit"),this.totalLimit=Oy(t.totalLimit??q3,"totalLimit"),this.totalLimit<this.perSessionLimit)throw new Error("totalLimit must be greater than or equal to perSessionLimit")}append(t){if(t.length===0)return My();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||ar,f=n.get(p);f?f.push(l):n.set(p,[l]),this.eventKeyById.set(l.id,p)}if(n.size===0)return{...My(),duplicateEventCount:a};const s=new Set;let r=0,i=0,c=!1;for(const[l,p]of n){p.some($y)&&(c=!0);const f=this.entries.get(l),y=f?.snapshot.events??is,b=Math.max(0,Math.min(y.length,this.perSessionLimit-p.length)),I=p.length>this.perSessionLimit?p.slice(p.length-this.perSessionLimit):p,C=b===y.length?y:y.slice(y.length-b),P=C.length===0?I:[...C,...I],_=y.slice(0,y.length-C.length);_.some($y)&&(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:yf(P),revision:(f?.snapshot.revision??0)+1}};this.entries.set(l,A),this.eventCount+=P.length-y.length,r+=I.length,i+=_.length+p.length-I.length,s.add(l)}const u=this.enforceTotalLimit(s);return i+=u,this.publish(s,c||u>0),V3({acceptedEventCount:r,duplicateEventCount:a,evictedEventCount:i,changedKeys:s})}mergeBootstrap(t){const n=F3(t),a=new Set([...this.entries.keys(),...n.keys()]),s=[];for(const r of a){const i=n.get(r)??is,c=this.entries.get(r)?.snapshot.events??is;s.push(...C4(i,c))}return this.replace(s)}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=is,this.summaryEventsSnapshot=is;const s=this.append(t);for(const u of this.retainedKeys){const l=this.entries.get(u);l&&(l.retained=!0)}const r=this.eventKeyById;let i=0;for(const u of n)r.has(u)||(i+=1);const c=new Set([...a].filter(u=>!this.entries.has(u)));return c.size>0&&this.publish(c,!0),{...s,evictedEventCount:s.evictedEventCount+i,changedSessionIds:new Set([...s.changedSessionIds,...[...c].filter(u=>u!==ar)]),unscopedEventsChanged:s.unscopedEventsChanged||c.has(ar)}}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=is,this.summaryEventsSnapshot=is,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??jy:jy;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(K3),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!==ar&&a.retained&&(t+=1);return{eventCount:this.eventCount,retainedSessionCount:t,sessionCount:this.entries.size-(this.entries.has(ar)?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[s,r]=a,i=this.eventCount-this.totalLimit;if(!r.retained||r.snapshot.events.length<=i){n+=r.snapshot.events.length,this.removeEntry(s),t.add(s);continue}const c=r.snapshot.events.slice(0,i),u=r.snapshot.events.slice(i);for(const l of c)this.eventKeyById.delete(l.id);r.eventIds=new Set(u.map(l=>l.id)),r.snapshot={events:u,latestSequence:yf(u),revision:r.snapshot.revision+1},this.eventCount-=c.length,n+=c.length,t.add(s)}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 s of this.listenersByKey.get(a)??[])s();for(const a of this.allListeners)a();if(n)for(const a of this.summaryListeners)a()}}}const jy=Object.freeze({events:is,latestSequence:null,revision:0});function F3(e){const t=new Map;for(const n of e){const a=n.sessionId||ar,s=t.get(a);s?s.push(n):t.set(a,[n])}return t}function V3(e){return{acceptedEventCount:e.acceptedEventCount,duplicateEventCount:e.duplicateEventCount,evictedEventCount:e.evictedEventCount,changedSessionIds:new Set([...e.changedKeys].filter(t=>t!==ar)),unscopedEventsChanged:e.changedKeys.has(ar)}}function My(){return{acceptedEventCount:0,duplicateEventCount:0,evictedEventCount:0,changedSessionIds:new Set,unscopedEventsChanged:!1}}function K3(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 Oy(e,t){if(!Number.isInteger(e)||e<=0)throw new Error(`${t} must be a positive integer`);return e}function $y(e){return e.name!=="assistant.delta"&&e.name!=="assistant.reasoning.delta"&&e.name!=="command.output"}const W3=256,Ny=15e3,G3=5e3,Z3=3e4;class J3{constructor(t={}){this.options=t}options;entries=new Map;connection=null;accountScope=null;generation=0;activateConnection(t){Q3(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,Y3(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 s=this.now(),r=this.entries.get(t);if(r?.state==="loading"&&!this.expired(r,s))return r.promise;if(r?.state==="failed"&&!this.expired(r,s))return Promise.resolve(null);const i=this.generation,c=n().then(u=>this.generation!==i?null:(this.entries.set(t,{state:"ready",url:u.url,expiresAt:u.expiresAt,lastAccessedAt:this.now()}),this.prune(),u.url)).catch(()=>{if(this.generation!==i)return null;const u=this.now();return this.entries.set(t,{state:"failed",expiresAt:u+(this.options.failureTtlMs??G3),lastAccessedAt:u}),this.prune(),null});return this.entries.set(t,{state:"loading",promise:c,expiresAt:s+(this.options.loadingTtlMs??Z3),lastAccessedAt:s}),this.prune(),c}clear(){this.generation+=1,this.entries.clear()}watch(t,n,a){let s=!1,r=0,i=0,c;const u=async(l=!1)=>{if(s)return;const p=++r;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 y=await this.load(t,n);if(s||p!==r)return;if(a({url:y,status:y?"ready":"error"}),!y){++i<=3&&(c=setTimeout(()=>{u()},[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??Ny));c=setTimeout(()=>{u()},I)};return u(),{refresh:(l=!1)=>{i=0,u(l)},close:()=>{s=!0,r+=1,clearTimeout(c)}}}size(){return this.prune(),this.entries.size}prune(){const t=this.now();for(const[a,s]of this.entries)this.expired(s,t)&&this.entries.delete(a);const n=this.options.maxEntries??W3;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??Ny:0;return t.expiresAt<=n+a}now(){return(this.options.now??Date.now)()}}const Dy=new J3;function IG(e,t,...n){return[t,e.serverUrl,...n].join("\0")}function Q3(e,t){return e?.serverUrl===t?.serverUrl&&e?.token===t?.token&&e?.platform===t?.platform}function Y3(e,t,n){e.delete(t),e.set(t,n)}const X3={connecting:"Connecting to OpenPond",account:"Loading account",team:"Loading default team",ready:"Ready"};function eV(e){return{label:X3[e],ready:e==="ready",stage:e}}function tV(e){let t=0,n=!1,a=!1,s=null;async function r(){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,s??=r().finally(()=>{s=null}),s)},invalidate(){t+=1,s&&(n=!0)},dispose(){a=!0,t+=1,n=!1}}}function nV({connection:e,events:t,refreshRef:n,setBootstrap:a,setError:s}){h.useEffect(()=>{if(!e)return;const i=tV({fetch:()=>Z.accountScopeSnapshot(e),apply:u=>a(l=>l&&{...l,account:u.account,accountMeta:u.accountMeta,preferences:u.preferences,configuration:u.configuration,providers:u.providers,apps:u.apps,appsError:u.appsError,appsMeta:u.appsMeta,cloudProjects:u.cloudProjects}),onError:u=>s(u instanceof Error?u.message:String(u))});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,s]);let r;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")){r=c.id;break}}h.useEffect(()=>{r&&n.current?.refresh()},[e,n,r])}const aV=650,sV=1200,rV=6e4;function oV(e){const{selectedSessionId:t,setDraftModel:n,setDraftProvider:a,setCodexPermissionMode:s,setCodexReasoningEffort:r,setOpenPondCommandAccessMode:i,setError:c,setSelectedAppId:u,setSelectedProjectId:l,setSelectedSessionId:p}=e,[f,y]=h.useState(null),[b,I]=h.useState(null),[C]=h.useState(()=>new B3),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),[S,w]=h.useState([]),[R,O]=h.useState([]),[z,$]=h.useState([]),[V,Y]=h.useState({}),[se,ee]=h.useState("connecting"),H=If(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),ve=h.useRef(Date.now()),me=h.useRef(null),Re=h.useRef(null),Q=h.useRef(null);h.useEffect(()=>{Dy.activateConnection(f),Dy.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 $3(F.current,ae,de),de})},[]),De=h.useCallback(U=>{w(ae=>{const de=typeof U=="function"?U(ae):U;return cy(J.current,ae,de),B.current=de,de})},[]),ze=h.useCallback(U=>{O(ae=>{const de=typeof U=="function"?U(ae):U;return cy(K.current,ae,de),ne.current=de,de})},[]),we=h.useCallback(()=>{if(oe.current||me.current!==null)return;const U=()=>{me.current=null,!oe.current&&(oe.current=!0,ee("ready"))},ae=Date.now()-ve.current,de=iV(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(be=>be?.serverId===U.server.id?be:{afterSequence:U.eventWindow?.latestSequence??yf(U.events)??0,serverId:U.server.id}),I(U),de?C.mergeBootstrap(U.events):C.replace(U.events),w(be=>{const Oe=de?iy(be,U.sessions,J.current):_f(be,U.sessions,J.current);return B.current=Oe,Oe}),O(be=>{const Oe=de?iy(be,U.codexHistorySessions??[],K.current):_f(be,U.codexHistorySessions??[],K.current);return ne.current=Oe,Oe}),$(U.approvals),Y(be=>N3(be,U.sidebarAppPreferences,F.current)),u(be=>be&&U.apps.some(Oe=>Oe.id===be)?be:null),l(be=>{if(!be)return null;const Oe=Jw(be);return Oe?.kind==="local"&&U.localProjects.some($e=>$e.id===Oe.id)?it("local",Oe.id):Oe?.kind==="cloud"&&(U.cloudProjects??[]).some($e=>$e.id===Oe.id)?it("cloud",Oe.id):U.localProjects.some($e=>$e.id===be)?it("local",be):(U.cloudProjects??[]).some($e=>$e.id===be)?it("cloud",be):null}),p(be=>{if(!be)return null;const Oe=[...U.sessions,...U.codexHistorySessions??[]];if(Oe.some(Ge=>Ge.id===be&&!Ge.archived))return be;if(!de)return null;const $e=B.current.find(Ge=>Ge.id===be)??ne.current.find(Ge=>Ge.id===be)??null;return $e&&!$e.archived&&XI($e,Oe)?be:null})},[C,u,l,p]),Te=h.useCallback(U=>{Q.current?.invalidate(),I(ae=>ae&&{...ae,preferences:U.preferences})},[]);nV({connection:f,events:P,refreshRef:Q,setBootstrap:I,setError:c}),h.useEffect(()=>{if(t)return;const U=ya(b?.preferences);a(U.defaultChatProvider),n(U.defaultChatModel)},[t,b?.preferences.defaultChatProvider,b?.preferences.defaultChatModel,n,a]),h.useEffect(()=>{s(ya(b?.preferences).codexPermissionMode)},[b?.preferences.codexPermissionMode,s]),h.useEffect(()=>{r(ya(b?.preferences).codexReasoningEffort)},[b?.preferences.codexReasoningEffort,r]),h.useEffect(()=>{i(ya(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,we();return}const U=If(b.account);if(!U){te.current=null,we();return}we(),xe("team");const ae=b.preferences.defaultTeamId?.trim()??"",de=cV(U,ae,b.accountMeta.asOf??"initial");if(te.current===de)return;te.current=de;let be=!1;const Oe=$e=>Og({teamId:$e,accountKey:U,fetchAgents:async Ge=>(await Z.listSandboxAgents(f,{teamId:Ge})).agents}).catch(()=>{!be&&te.current===de&&(te.current=null)});return Xb({accountKey:U,force:!0,fetchOrganizations:()=>Ly(f)}).then(async $e=>{if(be)return;if($e.length===0){we();return}if(!!ae&&$e.some(ye=>ye.teamId===ae)){await Oe(ae),we();return}const bt=AF($e)?.teamId;if(!bt){we();return}if(ae){c("The configured default team is unavailable for this account. Select an available team in account settings."),we();return}await Oe(bt),be||we()}).catch($e=>{be||(te.current=null,c($e instanceof Error?$e.message:String($e)),we())}),()=>{be=!0}},[Me,Te,b?.account,b?.accountMeta.asOf,b?.preferences.defaultTeamId,we,f,xe,c]),h.useEffect(()=>{if(!f||!H)return;let U=!1;const ae=()=>{U||(U=!0,Xb({accountKey:H,force:!0,fetchOrganizations:()=>Ly(f)}).catch(()=>{}).finally(()=>{U=!1}))},de=()=>{document.visibilityState==="visible"&&ae()},be=window.setInterval(ae,rV);return window.addEventListener("focus",ae),document.addEventListener("visibilitychange",de),()=>{window.clearInterval(be),window.removeEventListener("focus",ae),document.removeEventListener("visibilitychange",de)}},[f,H]),ui(()=>{const U=NU();c(U||(ae=>ae?.startsWith("Preference changes have not been saved.")?null:ae))}),h.useEffect(()=>{f&&Sb(f).catch(U=>c(String(U)))},[f,H,c]);const N=h.useCallback(async()=>{xe("connecting"),T(null);const U=await Xz();y(de=>A3(de,U)?de:U),xe("account");const ae=await Z.bootstrap(U);await Sb(U),Me(ae),we(),c(de=>de&&(SI(de)||de==="Event stream disconnected")?null:de)},[Me,we,xe,c]);h.useEffect(()=>{let U=!1,ae=null;const de=async be=>{try{await N()}catch(Oe){if(U)return;c(Oe instanceof Error?Oe.message:String(Oe));const $e=Math.min(5e3,750+be*750);ae=window.setTimeout(()=>{de(be+1)},$e)}};return de(0),()=>{U=!0,ae!==null&&window.clearTimeout(ae)}},[N,c]);const q=h.useCallback(()=>{N().catch(()=>{})},[N]);w3({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=C3(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:S,startup:eV(se),setAppPreferences:je,setBootstrap:I,setCodexHistorySessions:ze,setEvents:_,setSessions:De}}async function Ly(e){return(await Z.organizations(e)).organizations.map(xu).filter(n=>!!n).filter(n=>n.status==="active")}function iV(e){return e>=sV?0:Math.max(0,aV-e)}function cV(e,t,n){return`${e}::${t||"none"}::${n}`}function lV({appDispatch:e,error:t,setErrorState:n}){const a=h.useRef(null),s=h.useRef(null),r=h.useRef(null),i=h.useRef(0),c=h.useCallback((l,p="info",f={})=>{const y=Date.now()+ ++i.current;return e({type:"showToast",toast:{id:y,message:l,tone:p,...f}}),y},[e]),u=h.useCallback(l=>{const p=s.current,f=typeof l=="function"?l(p):l;if(Object.is(p,f))return;if(s.current=f,n(f),!f){r.current!==null&&(e({type:"clearToast",toastId:r.current}),r.current=null);return}r.current=c(dV(f),"error");const y=a.current;y&&Z.recordClientDiagnostic(y,{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(()=>{s.current=t,!(t||r.current===null)&&(e({type:"clearToast",toastId:r.current}),r.current=null)},[e,t]),{connectionRef:a,setError:u,showToast:c}}function dV(e){return yI(e)}const uV={query:"",searchOpen:!1,archivedChatsOpen:!1,sectionMenuOpen:null,projectsExpanded:!1,cloudProjectsExpanded:!1,chatRowsVisibleCount:$n,sidebarOpen:!0,view:"chat",selectedAppId:null,selectedProjectId:null,selectedSessionId:null,prompt:"",promptDrafts:{},draftProvider:Fr,draftModel:xc,draftExperience:"chat",codexPermissionMode:nh,codexReasoningEffort:ah,openPondCommandAccessMode:Wd,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 Ng(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:`new-${e.draftExperience}`}function zd(e,t,n){if(!n){if(!(t in e))return e;const{[t]:a,...s}=e;return s}return e[t]===n?e:{...e,[t]:n}}function mV(e){return zd(e.promptDrafts,Ng(e),e.prompt)}function Ji(e,t,n={}){const a={...e,...t},s=Ng(a),r=mV(e),i=n.clearSelectedDraft?zd(r,s,""):n.preserveCurrentPrompt?zd(r,s,e.prompt):r;return{...e,...t,promptDrafts:i,prompt:n.clearSelectedDraft?"":n.preserveCurrentPrompt?e.prompt:i[s]??""}}function pV(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 s=String(a);return{...e,prompt:s,promptDrafts:zd(e.promptDrafts,Ng(e),s)}}return pV(t.key)?Ji(e,{[t.key]:a}):{...e,[t.key]:a}}case"patch":return{...e,...t.patch};case"selectApp":return Ji(e,{selectedAppId:t.appId,selectedProjectId:null,selectedSessionId:null,view:"chat"});case"selectProject":return Ji(e,{selectedAppId:null,selectedProjectId:t.projectId,selectedSessionId:null,view:"chat"},{preserveCurrentPrompt:!0});case"selectSession":{const n=t.projectId??null;return Ji(e,{selectedSessionId:t.sessionId,selectedAppId:n?null:t.appId??null,selectedProjectId:n,view:"chat"})}case"beginNewChat":return Ji(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 st(e,t){return n=>e({type:"field",key:t,value:n})}function hV(e){return{setQuery:st(e,"query"),setSearchOpen:st(e,"searchOpen"),setArchivedChatsOpen:st(e,"archivedChatsOpen"),setSectionMenuOpen:st(e,"sectionMenuOpen"),setProjectsExpanded:st(e,"projectsExpanded"),setCloudProjectsExpanded:st(e,"cloudProjectsExpanded"),setChatRowsVisibleCount:st(e,"chatRowsVisibleCount"),setSidebarOpen:st(e,"sidebarOpen"),setView:st(e,"view"),setSelectedAppId:st(e,"selectedAppId"),setSelectedProjectId:st(e,"selectedProjectId"),setSelectedSessionId:st(e,"selectedSessionId"),setPrompt:st(e,"prompt"),setDraftProvider:st(e,"draftProvider"),setDraftModel:st(e,"draftModel"),setDraftExperience:st(e,"draftExperience"),setCodexPermissionMode:st(e,"codexPermissionMode"),setCodexReasoningEffort:st(e,"codexReasoningEffort"),setOpenPondCommandAccessMode:st(e,"openPondCommandAccessMode"),setBusy:st(e,"busy"),setDiffPanelOpen:st(e,"diffPanelOpen"),setDiffPanelExpanded:st(e,"diffPanelExpanded"),setRightPanelMode:st(e,"rightPanelMode"),setRightChatPanels:st(e,"rightChatPanels"),setTerminalOpen:st(e,"terminalOpen"),setSyncingWorkspaceAppId:st(e,"syncingWorkspaceAppId"),setSettingsSection:st(e,"settingsSection"),setNewProjectDialogOpen:st(e,"newProjectDialogOpen"),setNewProjectMode:st(e,"newProjectMode"),setNewProjectName:st(e,"newProjectName"),setNewProjectPath:st(e,"newProjectPath"),setNewProjectBusy:st(e,"newProjectBusy"),setCommitDialogOpen:st(e,"commitDialogOpen"),setCommitMessage:st(e,"commitMessage"),setCommitIncludeUnstaged:st(e,"commitIncludeUnstaged"),setCommitNextStep:st(e,"commitNextStep"),setCommitDraft:st(e,"commitDraft"),setBranchDialogOpen:st(e,"branchDialogOpen"),setBranchDialogName:st(e,"branchDialogName"),setToast:st(e,"toast"),setError:st(e,"error")}}function Qi(e){return e.selectedSessionId?`session:${e.selectedSessionId}`:e.selectedProjectId?`project:${e.selectedProjectId}`:e.selectedAppId?`app:${e.selectedAppId}`:"new-chat"}function gV(e={selectedAppId:null,selectedProjectId:null,selectedSessionId:null}){let t=e,n="";const a=new Map,s=new Set,r=l=>{if(!Object.is(n,l)){n=l;for(const p of s)p()}},i=()=>{const l=Qi(t);n?a.set(l,n):a.delete(l)},c=(l,p={})=>{const f=n;i(),t={...t,...l};const y=Qi(t);if(p.clear&&a.delete(y),p.preserveCurrentDraft){f?a.set(y,f):a.delete(y),r(f);return}r(p.clear?"":a.get(y)??"")},u={getScopeKey:()=>Qi(t),getSnapshot:()=>n,subscribe(l){return s.add(l),()=>s.delete(l)},set:l=>u.setForScope(Qi(t),l),setForScope(l,p){const f=Qi(t),y=l===f?n:a.get(l)??"",b=typeof p=="function"?p(y):p;Object.is(y,b)||(b?a.set(l,b):a.delete(l),l===f&&r(b))},applyAppAction(l){if(l.type==="field"){if(l.key==="prompt"){u.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"&&u.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 u}function _G(e){return h.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot)}function vV(e){return{...e,draftExperience:Pg()}}function bV(){const[e,t]=h.useReducer(fV,uV,vV),[n]=h.useState(()=>gV()),a=h.useCallback(r=>{n.applyAppAction(r),t(r)},[n]),s=h.useMemo(()=>({...hV(a),setPrompt:n.set}),[n,a]);return ui(()=>s.setDraftExperience(Pg())),{composerDraftStore:n,dispatch:a,setters:s,state:e}}function yV(e){return!!(e&&e.includes("Git is required for OpenPond app workspaces")&&e.includes("Command Line Tools"))}function SV(e){const{connection:t,events:n,showToast:a}=e,s=h.useRef(new Set),r=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:()=>{r()},persistent:!0})},[a,r]);h.useEffect(()=>{if(!t)return;let c=!1;return Z.gitAvailability(t).then(u=>{c||u.ok||u.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(s.current.has(c.id))continue;const u=c.error??c.output??null;c.name==="workspace_action_result"&&c.status==="failed"&&yV(u)&&(s.current.add(c.id),i("OpenPond needs Git before it can update this project."))}},[n,i])}function xV({connection:e,preferences:t,sidebarOpen:n,diffPanelExpanded:a,setBootstrap:s,setError:r}){const[i,c]=h.useState(()=>ya().sidebarSectionsCollapsed),u=h.useRef(i),l=h.useRef({}),p=h.useRef(null),f=h.useRef(null),[y,b]=h.useState(R3),[I,C]=h.useState(!1),[P,_]=h.useState(P3),[M,A]=h.useState(!1),{pinned:T,projects:S,cloudProjects:w,chats:R,savedForLater:O}=i;h.useEffect(()=>{if(I)return;const G=kp(ya(t).sidebarWidth),te=Ey(G,p.current);p.current=te.localChange,b(te.value)},[t,I]),h.useEffect(()=>{if(M)return;const G=wp(ya(t).diffPanelWidth),te=Ey(G,f.current);f.current=te.localChange,_(te.value)},[M,t]),h.useEffect(()=>{const G=ya(t).sidebarSectionsCollapsed;c(te=>{const oe=L3(te,G,l.current);return u.current=oe,oe})},[t]);const z=h.useCallback(G=>{s(te=>te&&{...te,preferences:G.preferences})},[s]),$=h.useCallback(async G=>{if(e&&kp(ya(t).sidebarWidth)!==G)try{z(await Z.savePreferences(e,{sidebarWidth:G}))}catch(te){r(te instanceof Error?te.message:String(te))}},[e,t,r,z]),V=h.useCallback(async G=>{if(e&&wp(ya(t).diffPanelWidth)!==G)try{z(await Z.savePreferences(e,{diffPanelWidth:G}))}catch(te){r(te instanceof Error?te.message:String(te))}},[e,t,r,z]),Y=h.useCallback(async G=>{if(!e)return;const te=ya(t).sidebarSectionsCollapsed;if(!kV(te,G))try{z(await Z.savePreferences(e,{sidebarSectionsCollapsed:G}))}catch(oe){r(oe instanceof Error?oe.message:String(oe))}},[e,t,r,z]),se=h.useCallback(G=>{const te=u.current;D3(l.current,te,G),u.current=G,c(G),Y(G)},[Y]),ee=h.useCallback(()=>{const G=u.current;se({...G,pinned:!G.pinned})},[se]),H=h.useCallback(()=>{const G=u.current;se({...G,projects:!G.projects})},[se]),F=h.useCallback(()=>{const G=u.current;se({...G,cloudProjects:!G.cloudProjects})},[se]),J=h.useCallback(()=>{const G=u.current;se({...G,chats:!G.chats})},[se]),K=h.useCallback(()=>{const G=u.current;se({...G,savedForLater:!G.savedForLater})},[se]),B=h.useCallback(G=>{if(!n)return;G.preventDefault();const te=G.clientX,oe=y;let ve=oe;C(!0);function me(Q){ve=kp(oe+Q.clientX-te),b(ve)}function Re(){window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",Re);const Q=Ay(oe,ve);Q&&(p.current=Q),C(!1),$(ve)}window.addEventListener("pointermove",me),window.addEventListener("pointerup",Re,{once:!0})},[$,n,y]),ne=h.useCallback(G=>{if(a)return;G.preventDefault();const te=G.clientX,oe=P;let ve=oe;A(!0);function me(Q){ve=wp(oe-(Q.clientX-te)),_(ve)}function Re(){window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",Re);const Q=Ay(oe,ve);Q&&(f.current=Q),A(!1),V(ve)}window.addEventListener("pointermove",me),window.addEventListener("pointerup",Re,{once:!0})},[a,P,V]);return{pinnedCollapsed:T,projectsCollapsed:S,cloudProjectsCollapsed:w,chatsCollapsed:R,savedForLaterCollapsed:O,sidebarWidth:y,sidebarResizing:I,diffPanelWidth:P,diffPanelResizing:M,togglePinnedCollapsed:ee,toggleProjectsCollapsed:H,toggleCloudProjectsCollapsed:F,toggleChatsCollapsed:J,toggleSavedForLaterCollapsed:K,startSidebarResize:B,startDiffPanelResize:ne}}function kV(e,t){return e.pinned===t.pinned&&e.projects===t.projects&&e.cloudProjects===t.cloudProjects&&e.chats===t.chats&&e.savedForLater===t.savedForLater}function wV(e){const[t,n]=h.useState({id:0,kind:null}),[a,s]=h.useState(null),r=h.useCallback((l=null)=>{n(p=>({id:p.id+1,kind:l}))},[]),i=h.useCallback(l=>{s(l)},[]),c=null,u=h.useMemo(()=>{if(e)return IV(a,r)},[e,a,r]);return{backAction:c,breadcrumbs:u,closeDetailKind:t.kind,closeDetailRequestId:t.id,onDetailOpenChange:i}}function IV(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 _V(e,t,n){return{inspectModelBatch:async a=>{if(!e)throw new Error("Connect to OpenPond to inspect this batch.");return Nz.parse(await Z.trainingRequest(e,"/models/batch-review/inspect",{profileId:t,modelId:a},"POST"))},beginModelBatchReview:async a=>{const s=await n(a);return s?Dz.parse(s):null}}}function CV(e,t,n,a){async function s(r,i){if(!e)throw new Error("Connect to OpenPond to load tasks.");const c=KN.parse(i),u=new URLSearchParams({profileId:t});for(const[l,p]of Object.entries(c))p!==void 0&&u.set(l,String(p));return Z.trainingRequest(e,`${r}?${u}`,{},"GET")}return{taskInventory:async(r={})=>GN.parse(await s("/tasks",r)),taskInventoryDetail:async r=>{const i=await s("/tasks/detail",r);return{item:Vk.parse(i.item),task:ru.parse(i.task)}},tasksetDraftFiles:async r=>{if(!e)return null;try{return await Z.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/files?${new URLSearchParams({profileId:t})}`,{},"GET")}catch(i){return a(i),null}},tasksetDraftFile:async(r,i)=>{if(!e)return null;try{return await Z.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/file?${new URLSearchParams({profileId:t,path:i})}`,{},"GET")}catch(c){return a(c),null}},saveTasksetDraftFile:r=>n("save-taskset-draft-file",`/taskset-drafts/${encodeURIComponent(r.draftId)}/file`,{profileId:t,...r},"PATCH"),inspectTasksetDraftSource:(r,i)=>n("inspect-taskset-draft-source","/taskset-drafts/source",{profileId:t,modelId:r,expectedModelRevision:i}),createTasksetDraftFromSource:r=>n("create-taskset-draft","/taskset-drafts",{profileId:t,sourceRequest:r}),createTasksetDraft:(r="",i)=>n("create-taskset-draft","/taskset-drafts",{profileId:t,name:r,modelId:i??null}),importTasksetDraftPackage:r=>n("import-taskset-draft-package","/taskset-drafts/import",{packagePath:r,profileId:t}),saveTasksetDraft:r=>n("save-taskset-draft",`/taskset-drafts/${encodeURIComponent(r.id)}`,r,"PUT"),tasksetDraftWorkspace:async r=>{if(!e)return null;try{return await Z.trainingRequest(e,`/taskset-drafts/${encodeURIComponent(r)}/workspace`,{},"GET")}catch(i){return a(i),null}},publishTasksetDraft:(r,i)=>n("publish-taskset-draft",`/taskset-drafts/${encodeURIComponent(r)}/publish`,{modelId:i??null}),refreshTasksetDraftModel:(r,i)=>n("refresh-taskset-draft-model",`/taskset-drafts/${encodeURIComponent(r.id)}/model-revision`,{expectedDraftRevision:r.revision,expectedModelRevision:i}),deleteTasksetDraft:r=>n("delete-taskset-draft",`/taskset-drafts/${encodeURIComponent(r)}`,{},"DELETE")}}function T1(e,t){return U$({id:e.id,profileId:e.profileId,name:e.name,objective:e.objective,defaultBaseModel:e.defaultBaseModel,defaultDestinationId:e.defaultDestinationId,trainingSetup:e.trainingSetup},t)}async function RV(e,t,n){if(!e)throw new Error("Connect to the execution owner to check this configuration.");const a=await T1(t,n);return tk.parse(await Z.trainingRequest(e,"/models/check",a,"POST"))}function PV(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 tk.parse(await Z.trainingRequest(e,"/model-starters/check",n))},createModelFromStarter:n=>t("create-model-from-starter","/model-starters/create",n)}}const zy=1e4,Hy=3e4;function TV(e){const{connection:t,profileId:n}=e,a=l0(),s=bI(t),r=h.useMemo(()=>["training",s,n],[s,n]),i=h.useCallback(async()=>jz.parse(await Z.trainingState(t,n)),[t,n]),c=x0({queryKey:r,queryFn:i,enabled:!!t}),u=c.data??null,l=!!t&&c.isPending,[p,f]=h.useState(null),[y,b]=h.useState(null),I=h.useRef(null);I.current=u?.activityRevision??null;const C=h.useCallback(async()=>{if(!t)return null;try{const S=await a.fetchQuery({queryKey:r,queryFn:i,staleTime:0});return b(null),S}catch(S){return b($s(S)),null}},[t,a,r,i]),P=h.useCallback(async()=>(await a.cancelQueries({queryKey:r,exact:!0}),await a.invalidateQueries({queryKey:r,exact:!0,refetchType:"none"}),await a.invalidateQueries({queryKey:["task-inventory",s,n]}),C()),[a,r,s,n,C]),_=h.useCallback(async(S,w,R,O="POST",z={})=>{if(!t)return null;z.silent||f(S);try{const $=await Z.trainingRequest(t,w,R,O);return await P(),z.silent||b(null),$}catch($){return z.silent||b($s($)),null}finally{z.silent||f(null)}},[t,P]),M=u?[u.jobs.some(S=>["queued","starting","running","cancelling","reconciling"].includes(S.status)),u.creations.some(S=>["planning","materializing","validating"].includes(S.state)),u.minerRuns.some(S=>["queued","running","cancelling"].includes(S.status)),u.datasetImports.some(S=>["inspecting","materializing","validating","cancelling"].includes(S.status))].some(Boolean):!1;h.useEffect(()=>{if(!t)return;let S=!0,w=null;const R=M?zy:Hy,O=async()=>{let z=R;try{const $=await Z.trainingActivity(t,n);z=$.active?zy:Hy,(I.current===null||I.current!==$.revision)&&await C()}catch($){b($s($))}S&&(w=window.setTimeout(()=>{O()},z))};return w=window.setTimeout(()=>{O()},R),()=>{S=!1,w!==null&&window.clearTimeout(w)}},[t,M,n,C]);const A=h.useMemo(()=>({...PV(t,_),saveComparisonSeries:S=>_("save-comparison-series","/comparison-series",{series:S}),saveContinualBenchIssueReview:S=>_("save-continual-support-issue-review","/continual-support/issue-reviews",{review:S},"PUT"),importContinualLearningDailyBatch:(S,w="json_upload")=>_("import-continual-learning-daily-batch","/continual-learning/daily-batches/import",{manifest:S,source:w}),saveContinualLearningDailyBatch:S=>_("save-continual-learning-daily-batch","/continual-learning/daily-batches",{batch:S},"PUT"),generateContinualLearningResponses:S=>_("generate-continual-learning-responses","/continual-learning/responses",S),sealComparisonSeries:(S,w)=>_("seal-comparison-series",`/comparison-series/${encodeURIComponent(S)}/seal`,{expectedRevision:w}),archiveComparisonSeries:(S,w)=>_("archive-comparison-series",`/comparison-series/${encodeURIComponent(S)}/archive`,{expectedRevision:w}),queueComparisonRelease:S=>_("queue-comparison-release",`/comparison-series/${encodeURIComponent(S.seriesId)}/releases`,S),startComparisonEvaluation:S=>_("start-comparison-evaluation",`/comparison-series-entries/${encodeURIComponent(S.entryId)}/evaluations`,S),loadComparisonAttemptEvidence:S=>t?Z.trainingRequest(t,`/model-runs/${encodeURIComponent(S.runId)}/attempts/${encodeURIComponent(S.attemptId)}/evidence?kind=${S.kind}`,{},"GET"):Promise.resolve(null),linkComparisonRun:S=>_("link-comparison-run",`/comparison-series-entries/${encodeURIComponent(S.entryId)}/run`,S,"PATCH"),decideComparisonEntry:S=>_("decide-comparison-entry",`/comparison-series-entries/${encodeURIComponent(S.entryId)}/decision`,S),recordComparisonPromotion:S=>_("record-comparison-promotion",`/comparison-series-entries/${encodeURIComponent(S.entryId)}/promotion`,S),checkModelProject:(S,w=S.revision)=>RV(t,S,w),..._V(t,n,S=>_("begin-model-batch-review","/models/batch-review",{profileId:n,request:S})),saveModelProject:async(S,w=S.revision)=>_("save-model-project","/models",await T1(S,w),"PUT"),listHostedModelProjects:async(S={})=>{if(!t)return null;S.silent||f("list-hosted-model-projects");try{const w=await Z.trainingRequest(t,`/hosted-model-projects?profileId=${encodeURIComponent(n)}&refresh=${S.refresh===!0}`,{},"GET");return S.silent||b(null),w}catch(w){return S.silent||b($s(w)),null}finally{S.silent||f(w=>w==="list-hosted-model-projects"?null:w)}},openHostedModelProject:(S,w,R,O={})=>_(`open-hosted-model-project:${S}`,`/hosted-model-projects/${encodeURIComponent(S)}/open`,{profileId:n,teamId:w,apiOrigin:R},"POST",O),pullHostedModelProject:S=>_(`pull-hosted-model-project:${S}`,`/hosted-model-projects/${encodeURIComponent(S)}/pull`,{profileId:n}),syncModelProject:S=>_("sync-model-project",`/models/${encodeURIComponent(S)}/sync`,{}),publishModelProjectTaskset:(S,w)=>_("publish-model-project-taskset",`/models/${encodeURIComponent(S)}/tasksets/${encodeURIComponent(w)}/publish`,{}),createScorer:(S,w,R)=>_("create-scorer","/scorers",{grader:S,tasksetId:w,modelProjectId:R??null}),prepareLearningBatch:S=>_("prepare-learning-batch","/learning-batches/prepare",{profileId:n,batchId:S}),...CV(t,n,_,S=>b($s(S))),tasksetGraderDetails:async S=>{if(!t)return null;try{return await Z.trainingRequest(t,`/tasksets/${encodeURIComponent(S)}/graders`,{},"GET")}catch(w){return b($s(w)),null}},inspectHuggingFaceDataset:S=>_("inspect-huggingface-dataset","/dataset-imports/huggingface/inspect",{profileId:n,url:S}),materializeDatasetImport:(S,w)=>_("materialize-dataset-import",`/dataset-imports/${encodeURIComponent(S)}/materialize`,w),cancelDatasetImport:S=>_("cancel-dataset-import",`/dataset-imports/${encodeURIComponent(S)}/cancel`,{}),datasetRows:(S,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(S)}/rows?${R}`,{},"GET")},addSource:(S,w)=>_("add-source","/sources",{profileId:n,sessionId:S,turnIds:w}),addSources:S=>_("add-sources","/sources/batch",{profileId:n,sessionIds:S}),estimateSources:S=>t?Z.trainingRequest(t,"/sources/estimate",{sessionIds:S}):Promise.resolve([]),searchChats:(S,w,R=0,O=20)=>t?Z.trainingRequest(t,"/sources/search",{query:S,candidates:w,offset:R,limit:O}):Promise.resolve({schemaVersion:"openpond.trainingChatSearchResult.v1",query:S,offset:R,limit:O,total:0,hasMore:!1,indexedChats:0,totalChats:0,indexing:!1,entries:[]}),removeSource:S=>_("remove-source",`/sources/${encodeURIComponent(S)}`,{},"DELETE"),deleteTaskset:S=>_("delete-model",`/tasksets/${encodeURIComponent(S)}`,{},"DELETE"),runBenchmark:(S,w,R,O)=>_(`run-benchmark-${w}`,`/tasksets/${encodeURIComponent(S)}/benchmark-runs`,{phase:w,model:R,reasoningEffort:O,seeds:[17],repetitions:1}),startHarnessRefinerBenchmark:(S,w,R)=>_("run-harness-refiner-benchmark",`/models/${encodeURIComponent(S)}/harness-refiner-benchmark`,{profileId:n,model:w,reasoningEffort:R,maximumSpendUsd:10}),acceptHarnessReview:(S,w,R=null,O=null)=>_("accept-harness-review","/harness-reviews/accept",{profileId:n,workspaceId:S,reviewRef:w,analysisModel:R,analysisReasoningEffort:O}),startCreation:(S,w={})=>_("create-taskset","/task-creations",{profileId:n,sourceIds:S,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:(S,w)=>_("create-model","/models/from-taskset",{profileId:n,tasksetId:S,preferredBaseModelId:w.modelId,preferredBaseModel:w}),scanBaseModels:async()=>{if(!t)return null;f("scan-base-models");try{const S=await C();return b(null),S}catch(S){return b($s(S)),null}finally{f(null)}},approveDisclosure:(S,w)=>_("approve-disclosure",`/task-creations/${encodeURIComponent(S)}/disclosure`,{approved:w}),retryCreation:S=>_("retry-creation",`/task-creations/${encodeURIComponent(S)}/retry`,{}),answerQuestions:(S,w)=>_("answer-questions",`/task-creations/${encodeURIComponent(S)}/questions`,{answers:w}),materialize:(S,w)=>_("materialize",`/task-creations/${encodeURIComponent(S)}/materialize`,{approved:w}),chatCreation:(S,w)=>_("task-creator-chat",`/task-creations/${encodeURIComponent(S)}/chat`,{message:w}),renameCreation:(S,w)=>_("rename-creation",`/task-creations/${encodeURIComponent(S)}/name`,{name:w},"PATCH"),cancelCreation:S=>_("cancel-creation",`/task-creations/${encodeURIComponent(S)}/cancel`,{}),runMiner:(S=[],w=[],R)=>_("run-miner","/miner/run",{profileId:n,sourceIds:S,sessionIds:w,config:R}),cancelMinerRun:S=>_("cancel-miner-run",`/miner/runs/${encodeURIComponent(S)}/cancel`,{}),configureMiner:S=>_("configure-miner","/miner/config",{profileId:n,config:S},"PUT"),patchCandidate:(S,w)=>_("candidate",`/candidates/${encodeURIComponent(S)}`,w,"PATCH"),createCandidate:(S,w,R,O)=>_("create-candidate",`/candidates/${encodeURIComponent(S)}/create`,{mode:w,analysisModel:R??null,analysisReasoningEffort:O??null}),auditGraders:S=>_("audit-graders","/audit-graders",{tasksetId:S}),executeTasksetAttempt:(S,w,R)=>_("execute-taskset-attempt",`/tasksets/${encodeURIComponent(S)}/attempts`,{taskId:w,model:R,seed:17,attempt:0,sampling:{maxOutputTokens:4096,temperature:0,topP:1}}),materializeSyntheticPreferenceCollection:S=>_("materialize-synthetic-preference-collection",`/tasksets/${encodeURIComponent(S.tasksetId)}/synthetic-preference-collection`,S),tasksetOperationalState:S=>t?Z.trainingRequest(t,`/tasksets/${encodeURIComponent(S)}/operations`,{},"GET"):Promise.resolve(null),calibrateJudges:S=>_("calibrate-judges","/calibrate-judges",{tasksetId:S}),nextPreferenceComparison:(S,w)=>_("next-preference-comparison",`/tasksets/${encodeURIComponent(S)}/preference-comparisons/next`,{reviewerKey:w}),submitPreferenceComparison:S=>_("submit-preference-comparison",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-comparisons/${encodeURIComponent(S.assignmentId)}/submit`,S),submitSyntheticFixturePreference:S=>_("submit-synthetic-fixture-preference",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-comparisons/${encodeURIComponent(S.assignmentId)}/fixture-submit`,{...S,id:crypto.randomUUID()}),listPreferenceDatasets:S=>t?Z.trainingRequest(t,`/tasksets/${encodeURIComponent(S)}/preference-datasets`,{},"GET"):Promise.resolve(null),materializePreferenceDataset:S=>_("materialize-preference-dataset",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-datasets`,{...S,id:`preference-dataset-${crypto.randomUUID()}`,revision:1}),launchRewardModelRun:S=>_("launch-reward-model-run",`/tasksets/${encodeURIComponent(S.tasksetId)}/reward-model-runs`,{...S,id:`reward-model-run-${crypto.randomUUID()}`}),learnedPreferenceRewardBinding:S=>_("learned-preference-reward-binding",`/tasksets/${encodeURIComponent(S.tasksetId)}/learned-preference-reward-binding`,S),retryRewardModelQualification:S=>_("retry-reward-model-qualification",`/reward-model-runs/${encodeURIComponent(S.runId)}/retry-qualification`,S),cancelRewardModelRun:S=>_("cancel-reward-model-run",`/reward-model-runs/${encodeURIComponent(S)}/cancel`,{}),markPreferenceComparisonUnreviewable:S=>_("mark-preference-comparison-unreviewable",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-comparisons/${encodeURIComponent(S.assignmentId)}/unreviewable`,S),preferenceCalibrationStatus:(S,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(S)}/preference-comparisons/calibration/status?${O}`,{},"GET")},startPreferenceCalibrationBatch:S=>_("start-preference-calibration-batch",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-comparisons/calibration/batches`,{...S,id:crypto.randomUUID()}),syncPreferenceCalibrationBatch:S=>_("sync-preference-calibration-batch",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-comparisons/calibration/batches/${encodeURIComponent(S.jobId)}/sync`,S),reviewPreferenceComparisonWithModel:S=>_("review-preference-comparison-with-model",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-comparisons/${encodeURIComponent(S.assignmentId)}/model-review`,{...S,id:crypto.randomUUID()}),runNextPreferenceCalibrationReview:S=>_("run-next-preference-calibration-review",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-comparisons/calibration/model-reviews/next`,{...S,id:crypto.randomUUID()}),savePreferenceCalibration:S=>_("save-preference-calibration",`/tasksets/${encodeURIComponent(S.tasksetId)}/preference-comparisons/calibration/report`,{...S,id:crypto.randomUUID()}),preferenceArtifactUrl:async S=>{if(!t)return null;const w=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(S)}/download`,{headers:{Authorization:`Bearer ${t.token}`}});if(!w.ok)throw new Error(await w.text());return URL.createObjectURL(await w.blob())},readiness:S=>_("readiness","/readiness",{tasksetId:S}),previewExpertBootstrap:S=>_("preview-expert-bootstrap",`/tasksets/${encodeURIComponent(S)}/expert-bootstrap/preview`,{}),approveExpertBootstrap:(S,w)=>_("approve-expert-bootstrap",`/tasksets/${encodeURIComponent(S)}/expert-bootstrap/approve`,{previewHash:w}),createPlan:S=>_("create-plan","/plans",{...S,tasksetId:S.tasksetId}),buildBundle:S=>_("build-bundle","/bundles",{planId:S}),approveTraining:(S,w)=>_("approve-training","/approvals",{planId:S,bundleId:w}),launch:(S,w)=>_("launch","/launch",{planId:S,approvalId:w}),prepareTraining:S=>_("prepare-training","/prepare",S),prepareModelRun:(S,w)=>_("prepare-model-run",`/model-projects/${encodeURIComponent(S)}/training/prepare`,w),startModelRun:(S,w)=>_("start-model-run",`/model-projects/${encodeURIComponent(S)}/training/start`,w),startPreparedTraining:S=>_("start-prepared-training","/start/prepared",S),startTraining:S=>_("start-training","/start",S),cancelJob:S=>_("cancel-job",`/jobs/${encodeURIComponent(S)}/cancel`,{}),retryModelRunCollection:S=>_("retry-model-run-collection",`/model-runs/${encodeURIComponent(S)}/retry-collection`,{}),cancelModelRun:S=>_("cancel-model-run",`/model-runs/${encodeURIComponent(S)}/cancel`,{}),rejectModel:(S,w)=>_("reject-model",`/models/${encodeURIComponent(S)}/reject`,{reason:w}),bindModel:(S,w,R)=>_("bind-model",`/models/${encodeURIComponent(S)}/bind`,{profileId:n,role:w,roleTargetId:R,promotedBy:n}),rollbackModelBinding:S=>_("rollback-model-binding",`/bindings/${encodeURIComponent(S)}/rollback`,{rolledBackBy:n}),updateModelConfiguration:(S,w)=>_("update-model-configuration",`/models/${encodeURIComponent(S)}/configuration`,w,"PATCH",{silent:!0}),setModelPinned:(S,w)=>_("pin-model-version",`/models/${encodeURIComponent(S)}/pin`,{pinned:w},"PATCH"),downloadArtifact:async S=>{if(!t)return!1;f("download-artifact");try{const w=await fetch(`${t.serverUrl}/v1/training/artifacts/${encodeURIComponent(S)}/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($s(w)),!1}finally{f(null)}},downloadModelPackage:async S=>T(`/models/${encodeURIComponent(S)}/download`,`${S}.openpond-lora.tar`),downloadBundle:async S=>T(`/bundles/${encodeURIComponent(S)}/download`,"openpond-model-improvement-bundle.json")}),[t,_,n,C]);async function T(S,w){if(!t)return!1;f("download-bundle");try{const R=await fetch(`${t.serverUrl}/v1/training${S}`,{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($s(R)),!1}finally{f(null)}}return{connection:t,payload:u,loading:l,busyAction:p,error:y??c.error?.message??null,refresh:C,actions:A}}function $s(e){return e instanceof Error?e.message:String(e)}function CG({modelId:e,taskset:t}){const n=t.metadata.toolContractHash===Gc?"cross_system":t.environment.kind==="stateful_harness"&&t.environment.actionBindings?.length?"harness":null,a=n?MV(t,n):[];return{model:{providerId:"openpond",modelId:e},tasksetId:t.id,tasksetName:t.name,taskRuntime:n,sourceProjectId:OV(t),tasks:a,selectedTaskIndex:0,sessionId:null}}function RG(e){return{model:{providerId:"openpond",modelId:e.modelId},tasksetId:e.tasksetId,tasksetName:e.modelName,taskRuntime:null,sourceProjectId:null,tasks:[],selectedTaskIndex:0,sessionId:null}}function $o(e){return e?.tasks.length?e.tasks[j1(e,e.selectedTaskIndex)]??null:null}function A1(e,t){return{...e,selectedTaskIndex:j1(e,t)}}function AV(e){return A1(e,e.selectedTaskIndex+1)}function EV(e,t,n){if(!e||E1(e,n))return null;const a=$o(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 E1(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 jV({model:e,connection:t,loadBootstrap:n,applyBootstrap:a}){e.providerId!=="openpond"||!t||a(await n(t))}function MV(e,t){const n=new Set;return e.tasks.flatMap(a=>{const s=t==="cross_system"?a.metadata.taskId:a.metadata.caseId,r=typeof s=="string"?s.trim():"",i=typeof a.input.prompt=="string"?a.input.prompt.trim():"";return!r||!i||n.has(r)?[]:(n.add(r),[{authoredTaskId:a.id,generatedTaskId:r,prompt:i,split:a.split}])})}function OV(e){const t=new Set(e.sourceRefs.filter(Ok).flatMap(n=>{const a=n.workspaceId?.trim();return a?[a]:[]}));return t.size===1?t.values().next().value??null:null}function j1(e,t){return e.tasks.length?Math.max(0,Math.min(Math.trunc(t),e.tasks.length-1)):0}function $V({activeModel:e,activeProvider:t,applyBootstrapPayload:n,beginNewChat:a,composerDraftStore:s,connection:r,requestComposerFocus:i,selectedLocalProjectId:c,selectedSessionId:u,selectLocalProject:l,setDraftModel:p,setDraftProvider:f,setError:y,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={...A1(I,R),sessionId:I.sessionId?null:I.sessionId},z=$o(O);C(O),z&&(I.sessionId&&P(O),s.set(z.prompt),i())},[P,s,I,i]),M=h.useCallback(()=>{const R=$o(I);R&&s.getSnapshot().trim()===R.prompt.trim()&&s.set(""),C(null)},[s,I]),A=h.useCallback(R=>{const O=R.model;jV({model:O,connection:r,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 $=$o(z);$&&s.set($.prompt)}).catch(y)},[n,P,s,r,p,f,y]),T=h.useCallback(R=>{const O=!!(I&&I.model.providerId===t&&I.model.modelId===e);return{active:O,error:O?E1(I,c):null,metadata:O?EV(I,R,c):null}},[e,t,I,c]),S=h.useCallback(R=>{C(O=>O&&{...O,sessionId:R})},[]),w=h.useCallback(()=>{if(!I)return;const R={...AV(I),sessionId:null},O=$o(R);C(R),O&&(P(R),s.set(O.prompt),i())},[P,s,I,i]);return h.useEffect(()=>{const R=$o(I);!R||b!=="chat"||u||s.set(O=>O.trim()?O:R.prompt)},[s,I,c,u,b]),h.useEffect(()=>{I&&u&&I.sessionId!==u&&C(null)},[I?.sessionId,u]),{advanceAfterTurn:w,begin:A,bindSession:S,dismiss:M,handoff:I,prepareTurn:T,selectTask:_}}function NV(e){let t=null,n=!1,a=null,s=!1;async function r(){try{do{s=!1;let i;do{const c=t===null,u=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<=u)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??u??0,e.onPage(l,c),i=!c&&l.hasMore}while(i&&!n)}while(s&&!n)}catch(i){n||e.onError(i)}}return{refresh(){return n?Promise.resolve():a?(s=!0,a):(a=r().finally(()=>{a=null}),a)},close(){n=!0}}}const Bl=[],DV=500;function LV(e){const{approvals:t,codexHistoryEvents:n,connection:a,runtimeIndexes:s,runtimeEventStore:r,selectedSessionId:i,serverId:c,setCodexHistoryEvents:u,setCodexHistorySessions:l,setError:p}=e,[f,y]=h.useState({}),[b,I]=h.useState({}),C=h.useRef(new Set);h.useEffect(()=>{y({}),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(Wt(i)){const w=Math.max(A?.totalMatchingEvents??0,n.length,n1),R=Math.min(ly,Math.max(f5,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 a1(a,i,{force:!0,limit:R,tail:!1});return u(O.events),l(z=>ku(z,O.session)),I(z=>({...z,[i]:{cursorSequence:null,hasMore:O.events.length>=R&&R<ly,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=ei(f[i]??Bl,r.getSessionEvents(i)),S=A?.cursorSequence??zV(T);if(!S)return!1;C.current.add(i),I(w=>({...w,[i]:{cursorSequence:w[i]?.cursorSequence??S,hasMore:w[i]?.hasMore??!0,loading:!0,totalMatchingEvents:w[i]?.totalMatchingEvents??null}}));try{const w=await Z.runtimeEventsPage(a,{sessionId:i,beforeSequence:S,limit:DV}),R=w.events.map(O=>O.event);return y(O=>({...O,[i]:ei(R,O[i]??Bl)})),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??S,hasMore:R[i]?.hasMore??!0,loading:!1,totalMatchingEvents:R[i]?.totalMatchingEvents??null}})),!1}finally{C.current.delete(i)}},[b,n.length,a,f,r,i,u,l,p]),_=i?f[i]??Bl:Bl;h.useEffect(()=>{if(!a||!i||Wt(i))return;const A=i,T=NV({sessionId:A,store:r,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))}),S=()=>{document.visibilityState==="visible"&&T.refresh()};T.refresh();const w=window.setInterval(S,1e4);return window.addEventListener("focus",S),window.addEventListener("openpond-runtime-connected",S),document.addEventListener("visibilitychange",S),()=>{T.close(),window.clearInterval(w),window.removeEventListener("focus",S),window.removeEventListener("openpond-runtime-connected",S),document.removeEventListener("visibilitychange",S)}},[a,r,i,c,p]);const M=h.useMemo(()=>Wt(i)?wf(n,[]):!i||_.length===0?s:wf(ei(_,r.getSessionEvents(i)),t),[t,n,s,_,i]);return{chatHistoryLoadStates:b,loadMoreSelectedChatHistory:P,selectedPagedSessionEvents:_,selectedRuntimeIndexes:M}}function zV(e){let t=null;for(const n of e)n.sequence!==void 0&&(t===null||n.sequence<t)&&(t=n.sequence);return t}function HV(e,t){const n=h.useRef(null);return h.useMemo(()=>{const a=DI(e,t,n.current);return n.current={events:e,indexes:a},a},[t,e])}function Ko(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ip(e){return Array.isArray(e)?e.filter(t=>!!Ko(t)):[]}function Nr(e){return typeof e=="string"&&e.trim()?e.trim():null}function Uy(e){return Nr(e)??Ko(e)}function UV(e){if(!e)return[];const t=Ko(e.sandboxActionRegistry),n=Ko(e.sandboxManifest),a=new Map;for(const s of[...Ip(n?.actionCatalog),...Ip(t?.actions),...Ip(n?.actions)]){const r=Nr(s.id)??Nr(s.name);if(!r)continue;const i=a.get(r);a.set(r,{id:r,name:Nr(s.name)??i?.name??r,label:Nr(s.label)??i?.label??qV(r),description:Nr(s.description)??i?.description??null,visibility:Nr(s.visibility)??i?.visibility??"default",inputSchema:Uy(s.inputSchema)??i?.inputSchema??null,outputSchema:Uy(s.outputSchema)??i?.outputSchema??null,implementation:Ko(s.implementation)??i?.implementation??null,mcp:Ko(s.mcp)??i?.mcp??null,invokesModel:typeof s.invokesModel=="boolean"?s.invokesModel:i?.invokesModel})}return Array.from(a.values()).filter(s=>s.visibility!=="internal"&&s.visibility!=="debug")}function qV(e){const t=e.replace(/[._-]+/g," ").trim();return t?t.replace(/\b\w/g,n=>n.toUpperCase()):e}function M1(e){if(e.selectedCloudProject)return{id:e.selectedCloudProject.id,teamId:e.selectedCloudProject.teamId,name:e.selectedCloudProject.name,selectionKey:it("cloud",e.selectedCloudProject.id),localProjectId:null};const t=e.selectedProject?.linkedSandboxProject??null;if(!t?.projectId||!t.teamId)return null;const n=e.cloudProjects?Ca(e.selectedProject,e.cloudProjects):null;return e.cloudProjects&&!n?null:{id:n?.id??t.projectId,teamId:n?.teamId??t.teamId,name:n?.name??t.projectName??e.selectedProject?.name??"Cloud Project",selectionKey:it("cloud",n?.id??t.projectId),localProjectId:e.selectedProject?.id??null}}const O1="openpond-agent",$1="openpond-profile-action";function _u(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Ds(e){return typeof e=="string"&&e.trim()?e.trim():null}function Dg(e){return e.displayPrompt&&/(?:^|\s)@[A-Za-z0-9_-]+/.test(e.displayPrompt)?"mention":"slash"}function BV(e){const t=_u(e),n=Ds(t?.scope);return n!=="entire_manifest"&&n!=="start"&&n!=="action"&&n!=="service"&&n!=="schedule"?null:{scope:n,name:Ds(t?.name)}}function FV(e){const t=Ds(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 VV(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:O1,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 KV(e){const t=_u(e.implementation);if(t?.type!==O1)return null;const n=Ds(t.agentId),a=Ds(t.teamId),s=Ds(t.projectId),r=BV(t.selectedEntrypoint),i=FV(t.workflowMode);return!n||!a||!s||!r||!i?null:{agentId:n,agentName:Ds(t.agentName)??e.label??e.name??e.id,teamId:a,projectId:s,projectName:Ds(t.projectName),selectedEntrypoint:r,workflowMode:i}}function WV(e,t={}){const n=t.agentName?.trim()||null;return{...e,implementation:{..._u(e.implementation)??{},type:$1,actionId:e.id,...n?{agentName:n}:{}},invokesModel:e.invokesModel??!0}}function GV(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=>WV(n,{agentName:n.agentId?t.get(n.agentId):null}))}function PG(e){return!!(e&&Lg(e))}function TG(e){return!!(e&&Lg(e)&&e.sourceActionId==="chat")}function Lg(e){const t=_u(e.implementation);if(t?.type!==$1)return null;const n=Ds(t.actionId)??e.id;return n?{actionId:n,actionLabel:e.label??e.name??n}:null}function ZV({action:e,attachments:t=[],displayPrompt:n,prompt:a,sessionId:s}){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:Dg({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{},...s?{sessionId:s}:{}}}}function JV({action:e,attachments:t=[],displayPrompt:n,prompt:a,teamId:s}){return{teamId:s,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:Dg({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}}}}function QV({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:Dg({displayPrompt:n}),...n&&n!==a?{displayPrompt:n}:{}},workflowMode:e.workflowMode}}const Wo=new Map;function zg(e,t){const n=e?.trim();return n?`${t?.trim()||"global"}|${n}`:null}function YV(e,t){const n=zg(e,t);if(!n)return null;const a=Wo.get(n);return a?.updatedAt?a.projects:null}function XV(e,t,n){const a=zg(e,n);a&&Wo.set(a,{projects:t,promise:null,updatedAt:Date.now()})}function eK(e){const t=e.teamId?.trim();if(!t)return Promise.resolve([]);const n=zg(t,e.accountKey);if(!n)return Promise.resolve([]);const a=Wo.get(n);if(!e.force){if(a?.updatedAt)return Promise.resolve(a.projects);if(a?.promise)return a.promise}const s=e.fetchProjects(t).then(r=>(XV(t,r,e.accountKey),r)).catch(r=>{const i=Wo.get(n);throw i?.promise===s&&Wo.set(n,{projects:i.projects,promise:null,updatedAt:i.updatedAt}),r});return Wo.set(n,{projects:a?.projects??[],promise:s,updatedAt:a?.updatedAt??0}),s}function _p(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 tK({cloudProjectById:e,cloudProjects:t,connection:n,defaultTeamId:a,accountScopeKey:s,localProjects:r,profile:i,selectedCloudProject:c,selectedProject:u,reportError:l}){const[p,f]=h.useState(null),[y,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 r){const z=t.find($=>$.id===O.linkedSandboxProject?.projectId&&$.teamId===O.linkedSandboxProject?.teamId);z?.teamId&&R.add(z.teamId)}return[...R].sort()},[t,a,r]),_=P.join("\0"),M=h.useMemo(()=>M1({cloudProjects:t,selectedCloudProject:c,selectedProject:u}),[t,c,u]);h.useEffect(()=>{if(!n||P.length===0){C([]);return}let R=!1;const O=P.flatMap(z=>R1(z,s)??[]);return C(_p(O)),Promise.all(P.map(z=>Og({teamId:z,accountKey:s,fetchAgents:async $=>(await Z.listSandboxAgents(n,{teamId:$})).agents}))).then(z=>{R||C(_p(z.flat()))}).catch(()=>{R||C(_p(O))}),()=>{R=!0}},[s,n,_]),h.useEffect(()=>{if(!n||!M){f(null);return}const R=YV(M.teamId,s);R&&f(R.find(z=>z.id===M.id)??null);let O=!1;return eK({teamId:M.teamId,accountKey:s,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}},[s,n,M?.id,M?.teamId]),h.useEffect(()=>{if(!n||!u){b([]);return}let R=!1;return Z.localProjectActions(n,u.id).then(O=>{R||b(O.actions)}).catch(O=>{R||(b([]),l?.(`Could not load Project Actions for ${u.name}: ${O instanceof Error?O.message:String(O)}`))}),()=>{R=!0}},[n,l,u?.id,u?.name,u?.updatedAt]);const A=h.useMemo(()=>{const R=new Map;for(const O of UV(p))R.set(O.id,O);for(const O of y)R.set(O.id,O);return[...R.values()]},[y,p]),T=h.useMemo(()=>GV(i),[i]),S=h.useMemo(()=>[...I.map(R=>VV(R,e.get(R.projectId)?.name??null)),...T,...A],[e,T,A,I]);return{openPondActionCatalog:h.useMemo(()=>[...T,...A],[T,A]),selectedActionCatalog:S,selectedProjectActionCatalog:A}}function nK({selectedProjectId:e}){const[t,n]=h.useState(()=>new Set),a=h.useCallback(r=>{n(i=>{if(i.has(r))return i;const c=new Set(i);return c.add(r),c})},[]),s=h.useCallback(r=>{n(i=>{const c=new Set(i);return c.has(r)?c.delete(r):c.add(r),c})},[]);return h.useEffect(()=>{e&&a(e)},[a,e]),{expandedProjectIds:t,expandProject:a,toggleProjectExpanded:s,setExpandedProjectIds:n}}function aK(){const e=new Map;function t(s,r){const i=e.get(s);if(i)return i.consumers+=1,n(s,i,!0);const c=new AbortController,u={controller:c,consumers:1,settled:!1,promise:Promise.resolve().then(()=>r(c.signal)).finally(()=>{u.settled=!0,e.get(s)===u&&e.delete(s)})};return e.set(s,u),n(s,u,!1)}function n(s,r,i){let c=!1;return{key:s,promise:r.promise,shared:i,release:()=>{c||(c=!0,r.consumers=Math.max(0,r.consumers-1),r.consumers===0&&!r.settled&&r.controller.abort())}}}function a(){for(const s of e.values())s.consumers=0,s.settled||s.controller.abort()}return{request:t,cancelAll:a,inFlightCount:()=>e.size}}function Cp(e,t,n){return`workspace-status:${e.serverUrl}:${t}:${n?"ensure":"read"}`}function sK(e,t){return`workspace-diff:${e.serverUrl}:${t}`}function Rp(e){return e instanceof Error&&e.name==="AbortError"}function rK({connection:e,activeWorkspaceAppId:t,view:n,shouldLoadWorkspaceDiff:a,sidebarWorkspaceAppIds:s,setError:r}){const[i,c]=h.useState(null),[u,l]=h.useState({}),[p,f]=h.useState(null),[y,b]=h.useState(!1),[I,C]=h.useState(!1),P=h.useRef(new Set),_=h.useRef(new Set),M=h.useRef(aK()),A=t?u[t]??(i?.appId===t?i:null):null,T=p?.appId===t?p:null,S=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(Cp(e,z,$),Y=>Z.workspaceStatus(e,z,$,{signal:Y}));try{const Y=await V.promise;return w(Y),$&&Y.error?r(`Workspace sync failed: ${Y.error}`):$&&r(null),Y}catch(Y){return Rp(Y)||(c(null),r(Y instanceof Error?Y.message:String(Y))),null}finally{V.release(),b(!1)}},[e,w,r]),O=h.useCallback(async(z=t,$={})=>{if(!e||!z)return f(null),null;$.silent||C(!0);const V=M.current.request(sK(e,z),Y=>Z.workspaceDiff(e,z,{signal:Y}));try{const Y=await V.promise;return f(Y),Y}catch(Y){return Rp(Y)||(f(null),r(Y instanceof Error?Y.message:String(Y))),null}finally{V.release(),$.silent||C(!1)}},[t,e,r]);return h.useEffect(()=>{if(!e||!t||!S){c(null),f(null),b(!1);return}let z=!1;const $=M.current.request(Cp(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=>{Rp(V)||z||(c(null),r(V instanceof Error?V.message:String(V)))}).finally(()=>{$.release(),z||b(!1)}),()=>{z=!0,$.release()}},[t,e,w,r,S]),h.useEffect(()=>{if(!e||!t||!S){f(null);return}if(!A?.initialized){A&&!A.initialized&&f(z=>z?.appId===t?null:z);return}a&&O(t)},[t,e,O,a,S,A?.dirty,A?.initialized]),h.useEffect(()=>{if(!e||s.length===0)return;const z=s.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(Cp(e,Y,!1),se=>Z.workspaceStatus(e,Y,!1,{signal:se}))}));return Promise.all(V.map(({appId:Y,request:se})=>se.promise.then(ee=>({appId:Y,state:ee})).catch(()=>({appId:Y,state:null})).finally(()=>{se.release(),_.current.delete(Y)}))).then(Y=>{if(!$)for(const se of Y)se.state&&w(se.state)}),()=>{$=!0,V.forEach(({appId:Y,request:se})=>{se.release(),_.current.delete(Y)})}},[e,w,s]),h.useEffect(()=>()=>M.current.cancelAll(),[]),{workspaceState:i,workspaceStates:u,workspaceDiff:p,workspaceBusy:y,diffBusy:I,visibleWorkspaceState:A,visibleWorkspaceDiff:T,rememberWorkspaceState:w,refreshWorkspace:R,refreshWorkspaceDiff:O,setWorkspaceBusy:b}}const oK=1,iK=15e3,cK=15e3,N1=5*6e4,lK=5e3,dK=1e4;function D1(e,t=(a,s)=>new WebSocket(a,s),n={}){const a=new uK(e,t,n.reconnectDelayMs??mK);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=N1;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===oK)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-${pK(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."))},iK))},n.onmessage=a=>{this.isCurrent(n,t)&&this.handleMessage(n,a)},n.onerror=()=>{this.isCurrent(n,t)&&this.failConnection(new Error("Team chat realtime socket failed."),!1)},n.onclose=a=>{this.isCurrent(n,t)&&(this.socket=null,this.clearConnectionTimers(),this.closed||((a.code===4401||a.code===4403)&&this.reportError(new Error("Team chat realtime authorization expired.")),this.scheduleReconnect()))}}handleMessage(t,n){if(typeof n.data!="string")return;let a;try{const r=JSON.parse(n.data);if(!r||typeof r!="object"||Array.isArray(r))return;a=r}catch{this.reportError(new Error("Team chat realtime returned an invalid frame."));return}const s=typeof a.type=="string"?a.type:"";if(s==="connection_ack"){this.connectionAckTimer&&clearTimeout(this.connectionAckTimer),this.connectionAckTimer=null,this.keepAliveTimeoutMs=hK(a.connectionTimeoutMs),this.lastKeepAliveAt=Date.now(),this.startKeepAliveMonitor(),this.subscribe(t);return}if(s==="ka"){this.lastKeepAliveAt=Date.now();return}if(s==="subscribe_success"){const r=typeof a.id=="string"?a.id:"";if(!this.subscriptionChannels.has(r))return;this.acknowledgedSubscriptions.add(r),this.markReadyWhenSubscribed();return}if(s==="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(s==="connection_error"||s==="subscribe_error"){const r=gK(a);if(this.reportError(r),s==="connection_error")this.failConnection(r,!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 s=fK();this.subscriptionChannels.set(s,a),t.send(JSON.stringify({type:"subscribe",id:s,channel:a,authorization:n}))}this.subscriptionAckTimer=setTimeout(()=>{this.failConnection(new Error("Team chat realtime subscription acknowledgement timed out."))},cK)}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."))},lK)}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 mK(e){const t=Math.min(dK,500*2**Math.min(e,5));return Math.max(100,Math.floor(Math.random()*t))}function pK(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 hK(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:N1}function gK(e){const n=(Array.isArray(e.errors)?e.errors:[])[0];if(n&&typeof n=="object"){const a=n,s=typeof a.errorType=="string"?a.errorType:"RealtimeError",r=typeof a.message=="string"?a.message:"Request failed";return new Error(`${s}: ${r}`)}return new Error("Team chat realtime request failed.")}function vK(e,t,n){const a=[`/team-chat/users/${e.session.userId}/${e.session.teamId}`,...Array.from(new Set(e.threadIds)).map(s=>`/team-chat/threads/${s}`)];return D1({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:a,onEvent:s=>{const r=GS.safeParse(s);r.success&&e.onEvent(r.data)},onReady:e.onReady,onError:e.onError},t,n)}function bK(e){return e.refs.find(t=>t.refType==="message_reply")??null}function yK(e){return{id:e.id,authorType:e.authorType,authorUserId:e.authorUserId,authorAgentId:e.authorAgentId,body:e.body,deleted:!!e.deletedAt}}function AG(e,t){const n=bK(e);if(!n)return null;const a=t.get(n.refId);return a?yK(a):xK(n)}function SK(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 EG(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 jG(e){return e.deleted?"Message deleted":e.body.replace(/\s+/g," ").trim()||"Attachment"}function xK(e){const t=e.preview;return{id:e.refId,authorType:kK(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 kK(e){return e==="agent"||e==="system"?e:"user"}function qy(e,t,n){return n===t.conversationId?{...e,aiThread:t}:e}function wK(e,t){return!e||e.thread.id!==t.thread.id?t:{...t,messages:el([...e.messages,...t.messages]),hasMoreBefore:e.messages.length>t.messages.length?e.hasMoreBefore:t.hasMoreBefore}}function Pp(e,t){const n=Array.from(t.values()).filter(s=>s.threadId===e.thread.id);if(n.length===0)return e;let a=e.thread;for(const s of n)a=fi(a,s,"message.created",!0,s.authorUserId);return{...e,thread:a,messages:el([...e.messages,...n])}}function IK(e,t){const n=new Set(e.map(s=>s.lastMessage?.clientRequestId).filter(s=>!!s)),a=new Map;for(const s of t.values()){if(s.clientRequestId&&n.has(s.clientRequestId))continue;const r=a.get(s.threadId)??[];r.push(s),a.set(s.threadId,r)}return e.map(s=>{let r=s;for(const i of a.get(s.id)??[])r=fi(r,i,"message.created",!0,i.authorUserId);return r}).sort((s,r)=>r.lastMessageAt.localeCompare(s.lastMessageAt))}function Tp(e,t,n){for(const a of e)!a.clientRequestId||a.id.startsWith("pending:")||(t.delete(a.clientRequestId),n.delete(a.clientRequestId))}function Ap(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,deliveryStatus:n}})}function By(e,t,n){const a=e.get(t);a&&e.set(t,{...a,metadata:{...a.metadata,uploadProgress:n}})}function el(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,s)=>a.sequence!==s.sequence?a.sequence-s.sequence:a.createdAt.localeCompare(s.createdAt))}function L1(e){return e.type!=="message.created"&&e.type!=="message.updated"&&e.type!=="message.deleted"?null:ph.safeParse(e.payload.message).data??null}function z1(e,t,n){const a=L1(t);if(a){const s=e.selectedThreadId===a.threadId,r=e.detail?.thread.id===a.threadId?{...e.detail,thread:fi(e.detail.thread,a,t.type,s,n),messages:el([...e.detail.messages,a])}:e.detail,c=e.threads.some(u=>u.id===a.threadId)?e.threads.map(u=>u.id===a.threadId?fi(u,a,t.type,s,n):u).sort((u,l)=>l.lastMessageAt.localeCompare(u.lastMessageAt)):e.threads;return{...e,detail:r,threads:c,error:null}}if(t.type==="read.updated"){const s=typeof t.payload.userId=="string"?t.payload.userId:null,r=Number(t.payload.sequence);if(!s||!Number.isSafeInteger(r)||r<0)return e;const i=c=>({...c,participants:c.participants.map(u=>u.userId===s?{...u,lastReadSequence:Math.max(u.lastReadSequence,r)}:u)});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 fi(e,t,n,a,s){const r=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===s?0:r?e.unreadCount+1:e.unreadCount}}function _K(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:SK(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 CK(e,t){const n=e.detail?.thread.id===t.threadId?{...e.detail,thread:fi(e.detail.thread,t,"message.created",!0,t.authorUserId),messages:el([...e.detail.messages,t])}:e.detail;return{...e,detail:n,threads:e.threads.map(a=>a.id===t.threadId?fi(a,t,"message.created",!0,t.authorUserId):a).sort((a,s)=>s.lastMessageAt.localeCompare(a.lastMessageAt)),error:null}}function Fy(e,t,n){return z1(e,{teamId:t.teamId,threadId:t.threadId,type:"message.created",payload:{message:t},createdAt:t.createdAt},n)}function RK(e,t){return Mf(e,t,"failed")}function Mf(e,t,n){const a=s=>s.clientRequestId===t&&s.id.startsWith("pending:")?{...s,metadata:{...s.metadata,deliveryStatus:n}}:s;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(s=>({...s,lastMessage:s.lastMessage?a(s.lastMessage):null}))}}function Vy(e,t,n){const a=s=>s.clientRequestId===t&&s.id.startsWith("pending:")?{...s,metadata:{...s.metadata,uploadProgress:n}}:s;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(s=>({...s,lastMessage:s.lastMessage?a(s.lastMessage):null}))}}function PK(e,t){const n=e.detail?.messages.filter(r=>r.id!==t)??[],a=n.at(-1)??null,s=e.detail?{...e.detail,thread:e.detail.thread.lastMessageId===t?Ky(e.detail.thread,a):e.detail.thread,messages:n}:null;return{...e,detail:s,threads:e.threads.map(r=>r.lastMessageId===t?Ky(r,a):r)}}function TK(e){if(e.length>zr.maxAttachments)return null;const t=[];for(const n of e){if(n.kind!=="image"||!AK(n.mediaType)||!n.contentsBase64||n.sizeBytes<=0||n.sizeBytes>zr.maxAttachmentBytes)return null;t.push({...n,kind:"image",mediaType:n.mediaType,contentsBase64:n.contentsBase64})}return t}function Ky(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 AK(e){return e==="image/png"||e==="image/jpeg"||e==="image/webp"||e==="image/gif"}const EK={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 jK(e){const t=e instanceof Error?e.message:String(e),n=t.trim().toLowerCase();for(const[a,s]of Object.entries(EK))if(n.includes(a))return s;return n.includes("event stream ended")?"Team chat realtime disconnected. Messages will continue to refresh automatically.":y1(t)}const H1="openpond.team-chat.notification-mode";function U1(){try{return typeof window>"u"?null:eo}catch{return null}}function Wy(e=U1()){const t=e?.getItem(H1);return t==="direct_mentions"||t==="none"?t:"all"}function MK(e,t=U1()){try{t?.setItem(H1,e)}catch{}}function OK(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 $K(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}`,r=e.message.body.replace(/\s+/g," ").trim()||(e.message.attachments.length===1?"Sent an image":e.message.attachments.length>1?`Sent ${e.message.attachments.length} images`:"New message");return{eventId:e.eventId,threadId:e.message.threadId,title:a,body:r.length>160?`${r.slice(0,157)}…`:r}}const Gy={members:[],agents:[],threads:[],selectedThreadId:null,detail:null,aiThread:null,agentConversation:null,loading:!1,busy:!1,error:null};function Fl(e,t){return e.map(n=>n.id===t&&n.unreadCount!==0?{...n,unreadCount:0}:n)}function Vl(e){return!e||e.thread.unreadCount===0?e:{...e,thread:{...e.thread,unreadCount:0}}}function NK(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedAgentId:e.conversation.agent.id,conversationId:e.conversation.conversationId}}function DK(e){return{teamId:e.teamId,body:e.body.trim(),clientRequestId:e.clientRequestId,selectedActionKey:e.selectedActionKey,approvalId:e.approvalId??null}}async function Zy(e,t=Z.markTeamChatRead){return e.lastMessageSequence<=0?!1:t(e.connection,e.threadId,e.teamId,e.lastMessageSequence).then(()=>!0,()=>!1)}function LK(e){const[t,n]=h.useState(Gy),a=h.useRef(t);a.current=t;const[s,r]=h.useState(Wy);ui(()=>r(Wy()));const[i,c]=h.useState(null),u=h.useRef(null),l=h.useRef(null),p=h.useRef(0),f=h.useRef(new Map),y=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),[S,w]=h.useState(null),[R,O]=h.useState(null),z=h.useCallback(N=>{r(N),MK(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=IK(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]),se=h.useCallback(async N=>{const q=N??u.current;if(!e.connection||!e.teamId||!q)return null;const X=(y.current.get(q)??0)+1;y.current.set(q,X);const U=await Z.teamChatThread(e.connection,e.teamId,q);Tp(U.messages,A.current,T.current);const ae=Pp(U,A.current);return y.current.get(q)!==X||(n(de=>de.selectedThreadId===q?{...de,threads:Fl(de.threads,q),detail:Vl(wK(de.detail,ae))}:de),u.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=>qy(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(()=>{u.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:pn(X)}))})},2500);return()=>window.clearInterval(q)},[H,t.agentConversation?.run.status]),h.useEffect(()=>{if(!e.connection||!e.teamId||!e.currentUserId){n(Gy),w(null),O(null),T.current.clear(),A.current.clear(),y.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,be,Oe]=await Promise.all([X,U,Z.teamChatThreads(e.connection,e.teamId)]);if(N)return;const $e=u.current&&Oe.threads.some(ye=>ye.id===u.current)?u.current:ae.thread.id,Ge=$e===ae.thread.id?ae:await Z.teamChatThread(e.connection,e.teamId,$e);if(N)return;const bt=Vl(Ge);n(ye=>({...ye,members:de.members,agents:be.agents,threads:Fl(Oe.threads,$e),selectedThreadId:$e,detail:bt,loading:!1,error:null})),Zy({connection:e.connection,teamId:e.teamId,threadId:$e,lastMessageSequence:bt?.thread.lastMessageSequence??0}),O(e.teamId)}catch(q){if(N)return;n(X=>({...X,loading:!1,error:pn(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=L1(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||OK({mode:s,currentUserId:e.currentUserId,message:q,thread:de})&&(_.current=N.id,c($K({eventId:N.id,message:q,thread:de,members:X.members})))};U?ae(U):V().then(de=>{const be=de.find(Oe=>Oe.id===q.threadId);be&&ae(be)}).catch(()=>{})}q?.clientRequestId&&!q.id.startsWith("pending:")&&(A.current.delete(q.clientRequestId),T.current.delete(q.clientRequestId)),n(X=>z1(X,N,e.currentUserId)),N.type==="thread.created"&&V().catch(X=>{n(U=>({...U,error:pn(X)}))}),(N.type==="ai_thread.created"||N.type==="ai_turn.updated")&&(se(N.threadId).catch(X=>{n(U=>({...U,error:pn(X)}))}),N.conversationId===l.current&&ee(N.conversationId).catch(X=>{n(U=>({...U,error:pn(X)}))})),q&&N.type==="message.created"&&u.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,s,ee,se,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(!S)return;const N=vK({session:S,threadIds:K?K.split(","):[],onEvent:F,onReady:()=>{J().catch(q=>{n(X=>({...X,error:pn(q)}))})},onError:()=>{J().catch(()=>{})}});return()=>{N.close()}},[F,J,S,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=u.current!==N;u.current=N,X&&(p.current+=1,l.current=null),n(U=>({...U,threads:Fl(U.threads,N),selectedThreadId:N,detail:U.detail?.thread.id===N?Vl(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||u.current!==N)return;Tp(U.messages,A.current,T.current);const ae=Pp(U,A.current);n(de=>({...de,threads:Fl(de.threads,N),detail:Vl(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:pn(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;Tp(X.messages,A.current,T.current);const U=Pp(X,A.current),ae=u.current!==U.thread.id;return u.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 Zy({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:pn(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:el(ae),hasMoreBefore:X.hasMoreBefore}}}),!0}catch(X){return n(U=>({...U,loading:!1,error:pn(X)})),!1}},[e.connection,e.teamId,t.detail]),te=h.useCallback(async N=>{const q=u.current,X=TK(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(be=>({...be,error:"Images can be sent to the team thread with Use model turned off."})),!1;const de=p.current;n(be=>({...be,busy:!0,error:null}));try{const be=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&&u.current===q;return Oe&&(p.current+=1,l.current=be.conversationId),n($e=>({...$e,aiThread:Oe?be:$e.aiThread})),be.activeTurn&&await Z.executeTeamChatAiTurn(e.connection,be.activeTurn.id,e.teamId),await Promise.all([se(q),V()]),n($e=>({...$e,busy:!1})),!0}catch(be){return n(Oe=>({...Oe,busy:!1,error:pn(be)})),!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,DK({teamId:e.teamId,body:N.body,clientRequestId:U,selectedActionKey:N.selectedActionKey,approvalId:N.approvalId})),await Promise.all([se(q),V()]),n(de=>({...de,busy:!1})),!0}catch(de){return n(be=>({...be,busy:!1,error:pn(de)})),!1}}T.current.set(U,{inputs:X,uploaded:null});const ae=_K({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=>CK(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})),By(A.current,U,`${$e+1} of ${X.length}`),n(bt=>Vy(bt,U,`${$e+1} of ${X.length}`));const be=T.current.get(U);be&&(be.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=>Fy($e,Oe,e.currentUserId)),!0}catch(de){return Ap(A.current,U,"failed"),n(be=>({...RK(be,U),error:pn(de)})),!1}},[e.connection,e.currentUserId,e.teamId,se,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:pn(q)}))}}},[e.connection,e.teamId]),ve=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:pn(q)}))}}},[e.connection,e.teamId]),me=h.useCallback(()=>{I.current=null,n(N=>({...N,agentConversation:null}))},[]),Re=h.useCallback(async N=>{const q=u.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,NK({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),se(q),V()]);return n(de=>({...de,agentConversation:ae,busy:!1})),!0}catch(U){return n(ae=>({...ae,busy:!1,error:pn(U)})),!1}},[e.connection,e.teamId,se,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=>({...qy(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:pn(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 se(N.threadId),!0}catch(X){return n(U=>({...U,error:pn(X)})),!1}},[e.connection,e.teamId,se]),ze=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 se(N.threadId),!0}catch(q){return n(X=>({...X,error:pn(q)})),!1}},[e.connection,e.teamId,se]),we=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");Ap(A.current,N.clientRequestId,"sending"),n(ae=>Mf(ae,N.clientRequestId,"sending"));try{let ae=X?.uploaded??[];if(X&&!X.uploaded){ae=[];for(const[be,Oe]of X.inputs.entries())ae.push(await Z.uploadTeamChatAttachment(e.connection,N.threadId,{teamId:e.teamId,attachment:Oe})),By(A.current,N.clientRequestId,`${be+1} of ${X.inputs.length}`),n($e=>Vy($e,N.clientRequestId,`${be+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(be=>be.id),replyToMessageId:U?.refId??null});return T.current.delete(N.clientRequestId),A.current.delete(N.clientRequestId),n(be=>Fy(be,de,e.currentUserId)),!0}catch(ae){return Ap(A.current,N.clientRequestId,"failed"),n(de=>({...Mf(de,N.clientRequestId,"failed"),error:pn(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=>PK(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:pn(X)})),!1}},[e.connection,e.teamId]);return{...t,currentUserId:e.currentUserId,notificationMode:s,incomingNotification:i,setNotificationMode:z,dismissIncomingNotification:$,setThreadMuted:Te,selectThread:B,openDm:ne,loadMoreMessages:G,sendMessage:te,openAiThread:oe,openAgentConversation:ve,closeAgentConversation:me,sendAgentTurn:Re,closeAiThread:Q,sendAiTurn:xe,stopAiTurn:je,editMessage:De,deleteMessage:ze,retryMessage:we,dismissFailedMessage:Me,refreshDirectory:Y,refresh:async()=>{await Promise.all([Y(),V(),se(),ee(),H()])}}}function pn(e){return jK(e)}const q1="local-profile-agent";function MG(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?[]:[Dr(c.agentName),Dr(i.name),Dr(i.label)].filter(Boolean)})),a=t.hosted?.teamId===e.teamId?t.hosted.hostedSourceMaterialization:null,s=new Set(e.hostedActions.map(i=>i.implementation?.agentId).filter(i=>typeof i=="string")),r=t.agents.flatMap(i=>i.enabled?a?.agentId===i.id&&!!(a.runtimeAgentId&&s.has(a.runtimeAgentId))||n.has(Dr(i.name))||n.has(Dr(i.id))?[]:[UK(t,i)]:[]);return[...e.hostedActions,...r]}function OG(e){return e?.implementation?.type===q1}function $G(e){const t=e.implementation?.profileAgentId;return typeof t=="string"&&t.trim()?t.trim():null}function zK(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 HK(e,t){const n=t.runtimeAgentId?.trim()??"",a=t.profileName?.trim()??"",s=Dr(t.agentName);return e.find(r=>{const i=r.implementation;return i?.type!=="openpond-agent"?!1:n&&typeof i.agentId=="string"&&i.agentId===n?!0:!!(a&&i.profileName===a&&s&&[i.agentName,r.name,r.label].some(c=>Dr(c)===s))})??null}function UK(e,t){return{id:`local-profile:${e.activeProfile??"default"}:${t.id}:chat`,name:t.name,label:t.name,description:qK(e),approvalPolicy:{required:!1,risk:"write"},setupRequirements:e.setupGate.blockingRequirements,invokesModel:!0,implementation:{type:q1,profileAgentId:t.id,profileName:e.activeProfile??"default"}}}function qK(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 Dr(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""):""}const Jy=5;function BK(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=zK(n,t);if(a)throw new Error(a);const s=n?.agents.find(l=>l.id===t);if(!s)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 u=null;for(let l=0;l<Jy;l+=1){const p=await e.refreshDirectory();if(u=HK(p.agents,{runtimeAgentId:c,profileName:n.activeProfile,agentName:s.name}),u)break;l<Jy-1&&await FK(200*(l+1))}if(!u)throw new Error(`${s.name} was published, but the Team agent directory has not refreshed yet. Retry the mention in a moment.`);return u},[e.applyBootstrapPayload,e.connection,e.refreshDirectory,e.teamId])}function FK(e){return new Promise(t=>{setTimeout(t,e)})}function VK(e){h.useEffect(()=>{if(!e.notification)return;const{eventId:t,threadId:n,title:a,body:s}=e.notification;e.showToast(`${a}: ${s}`,"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 KK(e){const{connection:t,refreshToken:n=null}=e,[a,s]=h.useState([]),[r,i]=h.useState(null),[c,u]=h.useState(null),[l,p]=h.useState(null),[f,y]=h.useState(!1),[b,I]=h.useState(!1),[C,P]=h.useState(!1),[_,M]=h.useState(null),[A,T]=h.useState(null),[S,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;y(!0),M(null);try{const G=await Z.communities(t);return s(G.items),i(G.nextCursor),u(te=>te&&G.items.some(oe=>oe.id===te)?te:null),!0}catch(G){return M(md(G)),!1}finally{y(!1)}},[t]),Y=h.useCallback(async()=>{if(!t||!r||f)return!1;y(!0),M(null);try{const G=await Z.communities(t,r);return s(te=>WK(te,G.items)),i(G.nextCursor),!0}catch(G){return M(md(G)),!1}finally{y(!1)}},[t,f,r]),se=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(md(oe)),null}finally{z.current===te&&I(!1)}},[t]),ee=h.useCallback(G=>{const te=a.find(oe=>oe.id===G);te&&(u(te.id),p(oe=>oe?.id===te.id?oe:null),w(null),se(te))},[a,se]),H=h.useCallback(()=>{z.current+=1,u(null),p(null),T(null),w(null)},[]);h.useEffect(()=>{if(!t){s([]),p(null),u(null);return}V()},[t,V,n]),h.useEffect(()=>{!$||l?.id===$.id||b||se($)},[se,l?.id,b,$]);const F=h.useCallback(async()=>{const G=$;await V(),G&&await se(G)},[se,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=Kl(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=Kl(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(Kl(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),s(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(Kl(te)),!1}finally{P(!1)}},[t,C,l]);return{items:a,nextCursor:r,selectedCommunityId:c,selectedSummary:$,preview:l,discoveryLoading:f,previewLoading:b,membershipBusy:C,discoveryError:_,previewError:A,membershipError:S,membershipVersion:R,refresh:V,loadMore:Y,showDiscovery:H,selectCommunity:ee,join:J,acceptRules:K,leave:B,updateNotifications:ne,clearMembershipError:()=>w(null)}}function WK(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 md(e){return e instanceof Error?e.message:String(e)}function Kl(e){const t=md(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 GK(e,t,n){return D1({realtimeUrl:e.session.realtimeUrl,httpUrl:e.session.httpUrl,authorizationToken:e.session.token,channels:[e.session.channel],onEvent:a=>{const s=ax.safeParse(a);s.success&&e.onEvent(s.data)},onReady:e.onReady,onError:e.onError},t,n)}function ZK(e){const{connection:t,preview:n,currentUserId:a,membershipVersion:s}=e,r=n?.id??null,i=n?.membership?.status==="active",c=!n?.capabilities.requiresRulesAcceptance,[u,l]=h.useState([]),[p,f]=h.useState(null),[y,b]=h.useState({}),[I,C]=h.useState([]),[P,_]=h.useState(!1),[M,A]=h.useState(!1),[T,S]=h.useState(!1),[w,R]=h.useState(!1),[O,z]=h.useState(null),[$,V]=h.useState(null),[Y,se]=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([]),ve=h.useRef("mentions"),me=h.useRef(0),Re=h.useRef({}),Q=h.useRef(new Set),xe=h.useMemo(()=>u.find(ye=>ye.id===p)??null,[u,p]),je=p?y[p]??null:null;h.useEffect(()=>{te.current=p},[p]),h.useEffect(()=>{oe.current=u},[u]),h.useEffect(()=>{ve.current=n?.membership?.notificationMode??"mentions"},[n?.membership?.notificationMode]);const De=h.useCallback(async()=>{if(!t||!r)return!1;_(!0),z(null);try{const ye=await Z.communityChannels(t,r);return l(ye.channels),f(Le=>Le&&ye.channels.some(Ae=>Ae.id===Le)?Le:ye.channels.find(Ae=>Ae.isDefault)?.id??ye.channels[0]?.id??null),J(!1),!0}catch(ye){const Le=da(ye);return z(Le),Yi(Le)&&J(!0),!1}finally{_(!1)}},[r,t]),ze=h.useCallback(async ye=>{if(!t||!r)return!1;const Le=++me.current;A(!0),V(null);try{const Ae=await Z.communityMessages(t,r,ye,{limit:50});return Le!==me.current?!1:(b(qe=>({...qe,[ye]:{items:Ae.messages,hasMoreBefore:Ae.hasMoreBefore,preview:Ae.preview}})),J(!1),!0)}catch(Ae){if(Le!==me.current)return!1;const qe=da(Ae);return V(qe),Yi(qe)&&J(!0),!1}finally{Le===me.current&&A(!1)}},[r,t]);h.useEffect(()=>{l(n?.channels??[]),b({}),f(n?.channels.find(ye=>ye.isDefault)?.id??n?.channels[0]?.id??null),z(null),V(null),se(null),J(!1),Q.current.clear(),r&&De()},[r,De,s]),h.useEffect(()=>{p&&ze(p)},[ze,p]);const we=h.useCallback(async(ye,Le)=>{if(!t||!r||!i||!c||Le<=0)return!1;if((Re.current[ye]??0)>=Le)return!0;Re.current[ye]=Le;try{const Ae=await Z.markCommunityRead(t,r,ye,Le);return l(qe=>qe.map(He=>He.id===ye?{...He,unreadCount:0,readState:He.readState?{...He.readState,lastReadSequence:Ae.sequence,lastReadAt:new Date().toISOString()}:{lastReadSequence:Ae.sequence,lastReadAt:new Date().toISOString(),mutedAt:null,pinnedAt:null}}:He)),!0}catch(Ae){const qe=da(Ae);return Yi(qe)&&J(!0),!1}},[r,t,i,c]);h.useEffect(()=>{const ye=je?.items.at(-1)?.sequence??0;p&&ye>0&&we(p,ye)},[we,p,je?.items]);const Me=h.useCallback(ye=>{if(ye.communityId!==r||Q.current.has(ye.id))return;Q.current.add(ye.id);const Le=nx.safeParse(ye.payload.message);if(Le.success&&ye.type!=="read.updated"){const Ae=Le.data;if(b(qe=>{const He=qe[ye.channelId];if(!He)return qe;const jt=He.items.some(pe=>pe.id===Ae.id)?He.items.map(pe=>pe.id===Ae.id?Ae:pe):[...He.items,Ae].sort((pe,fe)=>pe.sequence-fe.sequence);return{...qe,[ye.channelId]:{...He,items:jt}}}),l(qe=>qe.map(He=>He.id===ye.channelId?{...He,lastMessageSequence:Math.max(He.lastMessageSequence,Ae.sequence),unreadCount:te.current===ye.channelId||Ae.authorUserId===a?0:Math.max(He.unreadCount+(ye.type==="message.created"?1:0),0)}:He)),ye.type==="message.created"&&Ae.authorUserId!==a){const qe=oe.current.find(jt=>jt.id===ye.channelId),He=JK(Ae).includes(a??""),vn=ve.current;!qe?.readState?.mutedAt&&(vn==="all"||vn==="mentions"&&He)&&G({communityId:ye.communityId,channelId:ye.channelId,message:Ae})}te.current===ye.channelId&&we(ye.channelId,Ae.sequence);return}ye.type==="read.updated"&&ye.payload.userId===a&&De()},[r,a,De,we]);h.useEffect(()=>{if(!t||!r||!i||!c)return;let ye=!1,Le=null;return se(null),Promise.all([Z.communityRealtimeSession(t,r),Z.communityEvents(t,r)]).then(async([Ae,qe])=>{if(ye)return;const He=async()=>{let jt=qe.cursor;for(;;){const pe=await Z.communityEvents(t,r,{after:jt,limit:200});if(ye)return;for(const fe of pe.events)Me(fe);if(jt=pe.cursor,!pe.hasMore)return}},vn=GK({session:Ae,onEvent:Me,onReady:()=>{se(null),He().catch(jt=>se(da(jt)))},onError:jt=>se(da(jt))});Le=()=>vn.close(),await He()}).catch(Ae=>{if(!ye){const qe=da(Ae);se(qe),Yi(qe)&&J(!0)}}),()=>{ye=!0,Le?.()}},[Me,r,t,i,s,c]);const Te=h.useCallback(async()=>{if(!t||!r||!p||T)return!1;const ye=y[p],Le=ye?.items[0]?.sequence;if(!ye?.hasMoreBefore||Le==null)return!1;S(!0),V(null);try{const Ae=await Z.communityMessages(t,r,p,{beforeSequence:Le,limit:50});return b(qe=>{const He=qe[p]??ye,vn=new Set(He.items.map(jt=>jt.id));return{...qe,[p]:{...He,items:[...Ae.messages.filter(jt=>!vn.has(jt.id)),...He.items],hasMoreBefore:Ae.hasMoreBefore}}}),!0}catch(Ae){return V(da(Ae)),!1}finally{S(!1)}},[r,t,y,T,p]),N=h.useCallback(async ye=>{if(!t||!r||!p||w)return!1;R(!0),H(null),B(null);try{const Le=await Promise.all(ye.attachments.map(qe=>Z.uploadCommunityAttachment(t,r,p,qe))),Ae=await Z.sendCommunityMessage(t,r,p,{body:ye.body,clientRequestId:ye.clientRequestId,mentionUserIds:ye.mentionUserIds,attachmentIds:Le.map(qe=>qe.id),replyToMessageId:ye.replyToMessageId});return b(qe=>{const He=qe[p]??{items:[],hasMoreBefore:!1,preview:!1};return He.items.some(vn=>vn.id===Ae.id)?qe:{...qe,[p]:{...He,items:[...He.items,Ae]}}}),await we(p,Ae.sequence),!0}catch(Le){const Ae=da(Le);return H(Ae),B({...ye,message:Ae}),Yi(Ae)&&J(!0),!1}finally{R(!1)}},[r,t,we,p,w]),q=h.useCallback(ye=>N({body:ye.body,clientRequestId:crypto.randomUUID(),mentionUserIds:ye.mentionUserIds??[],attachments:ye.attachments??[],replyToMessageId:ye.replyToMessageId??null}),[N]),X=h.useCallback(async(ye,Le)=>{if(!t||!r||!p)return!1;H(null);try{const Ae=await Z.editCommunityMessage(t,r,p,ye,Le);return Qy(b,p,Ae),!0}catch(Ae){return H(da(Ae)),!1}},[r,t,p]),U=h.useCallback(async ye=>{if(!t||!r||!p)return!1;H(null);try{const Le=await Z.deleteCommunityMessage(t,r,p,ye);return Qy(b,p,Le),!0}catch(Le){return H(da(Le)),!1}},[r,t,p]),ae=h.useCallback(async(ye,Le)=>{if(!t||!r)return!1;H(null);try{const Ae=await Z.setCommunityChannelMuted(t,r,ye,Le);return l(qe=>qe.map(He=>He.id===ye&&He.readState?{...He,readState:{...He.readState,mutedAt:Ae.mutedAt}}:He)),!0}catch(Ae){return H(da(Ae)),!1}},[r,t]),de=h.useCallback(async(ye="")=>{if(!t||!r||!i)return[];try{const Le=await Z.searchCommunityMembers(t,r,{query:ye,limit:50});return C(Ae=>QK(Ae,Le.items)),Le.items}catch(Le){return H(da(Le)),[]}},[r,t,i]);h.useEffect(()=>{i&&c?de():C([])},[i,c,de]);const be=h.useCallback(async ye=>{if(!t||!r||!p)return!1;try{const Le=await Z.communityAttachmentDownload(t,r,p,ye);return window.open(Le.url,"_blank","noopener,noreferrer"),!0}catch(Le){return H(da(Le)),!1}},[r,t,p]),Oe=h.useCallback(()=>p?ze(p):Promise.resolve(!1),[ze,p]),$e=h.useCallback(()=>K?N(K):Promise.resolve(!1),[K,N]),Ge=h.useCallback(()=>B(null),[]),bt=h.useCallback(()=>G(null),[]);return{channels:u,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:be,dismissIncomingNotification:bt}}function Qy(e,t,n){e(a=>{const s=a[t];return s?{...a,[t]:{...s,items:s.items.map(r=>r.id===n.id?n:r)}}:a})}function JK(e){const t=e.metadata.mentionUserIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function QK(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 Yi(e){return e.includes("community_membership_required")||e.includes("community_rules")}function da(e){return e instanceof Error?e.message:String(e)}function YK(e){const t=KK({connection:e.connection,refreshToken:e.refreshToken}),n=ZK({connection:e.connection,preview:t.preview,currentUserId:e.currentUserId,membershipVersion:t.membershipVersion}),a=n.incomingNotification,s=t.items,r=n.channels,i=t.selectCommunity,c=n.selectChannel,u=n.dismissIncomingNotification,{setView:l,showToast:p}=e,f=h.useCallback(()=>{t.showDiscovery(),l("community")},[t.showDiscovery,l]),y=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=s.find(P=>P.id===a.communityId),C=r.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"}),u()},[r,s,u,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:y,selectCommunityChannel:b},view:{communities:t,chat:n,currentUserId:e.currentUserId}}}const XK=[];function e9(e){const t=h.useCallback(a=>_F(e,a),[e]),n=h.useCallback(()=>wF(e)??XK,[e]);return h.useSyncExternalStore(t,n,n)}function t9(e){const[t,n]=h.useState(()=>qm());return h.useEffect(()=>{let a=!0;return e?(Z.connectedAppStatus(e,{status:"all"}).then(s=>{a&&n(s.apps)}).catch(s=>{console.warn("Unable to load connected app mention status.",s),a&&n(qm())}),()=>{a=!1}):(n(qm()),()=>{a=!1})},[e]),t}function n9(){const{composerDraftStore:e,dispatch:t,setters:n,state:a}=bV(),[s,r]=h.useState(null),[i,c]=h.useState([]),[u,l]=h.useState(null),[p,f]=h.useState(null),[y,b]=h.useState([]),[I,C]=h.useState(null),[P,_]=h.useState(null),[M,A]=h.useState(WI),[T,S]=h.useState({}),[w,R]=h.useState(()=>new Set),O=h.useCallback((Ve,en)=>{R(qt=>{if(qt.has(Ve)===en)return qt;const Ft=new Set(qt);return en?Ft.add(Ve):Ft.delete(Ve),Ft})},[]),[z,$]=h.useState(0),[V,Y]=h.useState(null),se=h.useRef(null),{confirmProjectAction:ee,projectConfirmDialog:H,resolveProjectConfirmDialog:F}=h4(),{query:J,searchOpen:K,archivedChatsOpen:B,sectionMenuOpen:ne,projectsExpanded:G,cloudProjectsExpanded:te,chatRowsVisibleCount:oe,sidebarOpen:ve,view:me,selectedAppId:Re,selectedProjectId:Q,selectedSessionId:xe,draftProvider:je,draftModel:De,draftExperience:ze,codexPermissionMode:we,codexReasoningEffort:Me,openPondCommandAccessMode:Te,busy:N,diffPanelOpen:q,diffPanelExpanded:X,rightPanelMode:U,rightChatPanels:ae,terminalOpen:de,settingsSection:be,newProjectDialogOpen:Oe,newProjectMode:$e,newProjectName:Ge,newProjectPath:bt,newProjectBusy:ye,commitDialogOpen:Le,commitMessage:Ae,commitIncludeUnstaged:qe,commitNextStep:He,commitDraft:vn,branchDialogOpen:jt,branchDialogName:pe,toast:fe,error:Fe}=a,Pe=wV(me==="labs"),{setQuery:Ne,setSearchOpen:rt,setArchivedChatsOpen:lt,setSectionMenuOpen:Tt,setProjectsExpanded:dt,setCloudProjectsExpanded:at,setChatRowsVisibleCount:_t,setSidebarOpen:Be,setView:At,setSelectedAppId:ln,setSelectedProjectId:En,setSelectedSessionId:xt,setPrompt:xs,setDraftProvider:dn,setDraftModel:bn,setDraftExperience:Ht,setCodexPermissionMode:Cn,setCodexReasoningEffort:yn,setOpenPondCommandAccessMode:Rn,setDiffPanelOpen:jn,setDiffPanelExpanded:Ut,setRightPanelMode:ft,setRightChatPanels:Un,setTerminalOpen:un,setSyncingWorkspaceAppId:ut,setSettingsSection:It,setNewProjectDialogOpen:Mt,setNewProjectMode:mn,setNewProjectName:ra,setNewProjectPath:Ze,setNewProjectBusy:Pn,setCommitDialogOpen:Ga,setCommitMessage:Aa,setCommitIncludeUnstaged:Dn,setCommitNextStep:Tn,setCommitDraft:Za,setBranchDialogOpen:ks,setBranchDialogName:Ea,setError:ct}=n,{connectionRef:an,setError:Ke,showToast:yt}=lV({appDispatch:t,error:Fe,setErrorState:ct}),{appPreferences:Xt,applyBootstrapPayload:Ln,applyPreferencesPayload:Sn,bootstrap:D,codexHistorySessions:ke,connection:ie,events:Je,runtimeEventStore:fa,approvals:qn,sessions:ja,startup:xn,setAppPreferences:to,setBootstrap:ws,setCodexHistorySessions:Mn,setEvents:oa,setSessions:ha}=oV({selectedSessionId:xe,setDraftModel:bn,setDraftProvider:dn,setCodexPermissionMode:Cn,setCodexReasoningEffort:yn,setOpenPondCommandAccessMode:Rn,setError:Ke,setSelectedAppId:ln,setSelectedProjectId:En,setSelectedSessionId:xt});an.current=ie,h.useEffect(()=>{D&&b(D.sidebarFileBookmarks??[])},[D?.sidebarFileBookmarks]);const Is=h.useMemo(()=>[...Je].reverse().find(Ve=>Ve.name==="tool.completed"&&Ve.action==="manage_sidebar_file")??null,[Je]),kr=h.useRef(null);h.useEffect(()=>{!ie||!Is||kr.current===Is.id||(kr.current=Is.id,Z.sidebarFiles(ie).then(Ve=>b(Ve.items)).catch(Ve=>Ke(Ve instanceof Error?Ve.message:String(Ve))))},[ie,Is,Ke]);const wr=h.useCallback(async(Ve,en)=>{if(!ie)return;const qt=y;b(Ft=>en==="none"?Ft.filter(la=>la.id!==Ve.id):Ft.some(la=>la.id===Ve.id)?Ft.map(la=>la.id===Ve.id?{...la,status:en}:la):[...Ft,{...Ve,status:en}]);try{const Ft=await Z.patchSidebarFile(ie,{workspaceKind:Ve.workspaceKind,workspaceId:Ve.workspaceId,workspaceName:Ve.workspaceName,path:Ve.path,status:en,sourceSessionId:Ve.sourceSessionId});b(Ft.items)}catch(Ft){b(qt),Ke(Ft instanceof Error?Ft.message:String(Ft))}},[ie,Ke,y]),Vs=t9(ie),mt=TV({connection:ie,profileId:D?.profile?.activeProfile??"default"}),{pinnedCollapsed:ki,projectsCollapsed:Ir,cloudProjectsCollapsed:wi,chatsCollapsed:no,savedForLaterCollapsed:Ii,sidebarWidth:_s,sidebarResizing:_i,diffPanelWidth:ao,diffPanelResizing:so,togglePinnedCollapsed:ro,toggleProjectsCollapsed:Ci,toggleCloudProjectsCollapsed:Ri,toggleChatsCollapsed:Ja,toggleSavedForLaterCollapsed:Pi,startSidebarResize:oo,startDiffPanelResize:_r}=xV({connection:ie,preferences:D?.preferences,sidebarOpen:ve,diffPanelExpanded:X,setBootstrap:ws,setError:Ke}),{cloudProjectById:Cr,linkedProjectByAppId:io,localProjectById:ia,mentionableSandboxApps:Ti,selectedApp:Rr,selectedCloudProject:Cs,selectedProject:Wn,selectedProjectLinkedApp:Ai,selectedProjectLinkedOpenPondApp:Ei,selectedSession:kn,selectedSessionLinkedProject:Ks,sidebarSessions:Gn}=qF({bootstrap:D,codexHistorySessions:ke,selectedAppId:Re,selectedProjectId:Q,selectedSessionId:xe,sessions:ja}),Rs=kn?.experience??ze;h.useEffect(()=>{hF(Rs)},[Rs]);const Pr=h.useMemo(()=>JU(Gn,Rs),[Rs,Gn]),Ws=HV(Je,qn),{chatMentionApps:ji,connectedAppMentions:co,pendingApproval:Tr}=i5({bootstrap:D,connectedAppRows:Vs,mentionableSandboxApps:Ti,runtimeIndexes:Ws,selectedApp:Rr,selectedCloudProject:Cs,selectedProject:Wn,selectedSession:kn,selectedSessionId:xe}),{codexHistoryEvents:Ps,setCodexHistoryEvents:Ts}=C5({connection:ie,selectedSessionId:xe,selectedSessionLocallyActive:!!(xe&&w.has(xe)),selectedSessionStatus:kn?.status,setCodexHistorySessions:Mn,setError:Ke}),{account:Ar,accountPending:lo,accountSignedOut:Gs,activeModel:Qa,activeProvider:ga,activeWorkspaceAppId:uo,activeWorkspaceId:Zs,activeWorkspaceKind:Ya,activeWorkspaceLocation:mo,appDefaults:Ma,cloudLinked:po,selectedCodexHistoryPending:Mi,selectedSessionProjectId:fo,startMessage:Oi,workspaceName:ho}=DF({bootstrap:D,draftModel:De,draftProvider:je,selectedApp:Rr,selectedAppId:Re,selectedCloudProject:Cs,selectedProject:Wn,selectedSession:kn,selectedSessionId:xe,selectedSessionLinkedProject:Ks}),go=h.useMemo(()=>PF(D?.account??null),[D?.account]),vo=h.useMemo(()=>If(D?.account??null),[D?.account]),Er=e9(vo),bo=h.useMemo(()=>EF(Er,Ma.defaultTeamId),[Ma.defaultTeamId,Er]),jr=bo?.teamId??null,Xa=LK({connection:ie,teamId:jr,currentUserId:Ar?.profile?.id??null,refreshToken:D?.accountMeta.asOf??null}),$i=BK({connection:ie,teamId:jr,applyBootstrapPayload:Ln,refreshDirectory:Xa.refreshDirectory});VK({notification:Xa.incomingNotification,dismiss:Xa.dismissIncomingNotification,selectThread:Xa.selectThread,setView:At,showToast:yt});const{communities:Ni,sidebar:Di,view:Li}=YK({connection:ie,currentUserId:Ar?.profile?.id??null,refreshToken:D?.accountMeta.asOf??null,setView:At,showToast:yt}),es=Xa.aiThread?.conversationId??null,yo=me==="team"&&!!es&&q&&U==="chat";h.useEffect(()=>{if(me==="team"){if(es){ft("chat"),jn(!0);return}U==="chat"&&jn(!1)}},[U,jn,ft,es,me]);const zi=h.useCallback(()=>{if(es){if(yo){jn(!1);return}ft("chat"),jn(!0)}},[jn,ft,yo,es]),Hi=h.useMemo(()=>Ca(Wn,D?.cloudProjects??[]),[D?.cloudProjects,Wn]),Ui=kn?.provider==="codex"?Te:kn?.openPondCommandAccessMode??Te,ca=uo,So=Zs,et=Ya,Bt=ho,{openPondActionCatalog:ts,selectedActionCatalog:sn}=tK({cloudProjectById:Cr,cloudProjects:D?.cloudProjects??[],connection:ie,defaultTeamId:Ma.defaultTeamId,accountScopeKey:go,localProjects:D?.localProjects??[],profile:D?.profile,selectedCloudProject:Cs,selectedProject:Wn,reportError:Ke}),{expandedProjectIds:zn,expandProject:On,toggleProjectExpanded:Pu,setExpandedProjectIds:Tu}=nK({selectedProjectId:Q});ZF({activeWorkspaceId:Zs,activeWorkspaceKind:Ya,appDispatch:t,connection:ie,expandProject:On,linkedProjectByAppId:io,providerSettings:D?.providers??null,selectedAppId:Re,selectedSession:kn,selectedSessionId:xe,selectedSessionProjectId:fo,setDiffPanelExpanded:Ut,setDraftModel:bn,setDraftProvider:dn,setError:Ke,setSelectedAppId:ln,setSelectedProjectId:En,setSessions:ha,setTerminalOpen:un,toast:fe});const{changeCodexPermissionMode:Au,changeCodexReasoningEffort:Eu}=c5({connection:ie,setBootstrap:ws,setCodexPermissionMode:Cn,setCodexReasoningEffort:yn,setError:Ke}),{changeOpenPondCommandAccessMode:tl}=f3({connection:ie,selectedSession:kn,setBootstrap:ws,setError:Ke,setOpenPondCommandAccessMode:Rn,setSessions:ha}),ju=JF({connection:ie,setError:Ke}),Mr=h.useCallback(()=>{$(Ve=>Ve+1)},[]),nl=YF({appDispatch:t,expandProject:On,linkedProjectByAppId:io,requestComposerFocus:Mr,onBeginNewChat:()=>{Dt({kind:"chat",sessionId:null}),Y(null),Ht(Ve=>Ve==="development"?"work":Ve)},setMentionedAppId:f}),xo=h.useCallback(Ve=>{const en=it("local",Ve);t({type:"selectProject",projectId:en}),On(en)},[t,On]),{advanceAfterTurn:Mu,begin:Ou,bindSession:$u,dismiss:Nu,handoff:Du,prepareTurn:Lu,selectTask:zu}=$V({activeModel:Qa,activeProvider:ga,applyBootstrapPayload:Ln,beginNewChat:nl,composerDraftStore:e,connection:ie,requestComposerFocus:Mr,selectedLocalProjectId:Wn?.id??null,selectedSessionId:xe,selectLocalProject:xo,setDraftModel:bn,setDraftProvider:dn,setError:Ke,view:me});SV({connection:ie,events:Je,showToast:yt}),k3({searchOpen:K,sectionMenuOpen:ne,setSectionMenuOpen:Tt,setSearchOpen:rt,setQuery:Ne}),h.useEffect(()=>{S({})},[D?.server.id]);const{chatHistoryLoadStates:Hu,loadMoreSelectedChatHistory:Uu,selectedPagedSessionEvents:qu,selectedRuntimeIndexes:al}=LV({approvals:qn,codexHistoryEvents:Ps,connection:ie,runtimeIndexes:Ws,runtimeEventStore:fa,selectedSessionId:xe,serverId:D?.server.id,setCodexHistoryEvents:Ts,setCodexHistorySessions:Mn,setError:Ke}),{activeSessions:Bu,archivedSessions:Fu,pinnedProjects:Vu,pinnedSessions:qi,savedForLaterSessions:sl,pinnedFiles:Ku,savedForLaterFiles:Wu,pinnedItems:rl,projectRows:ol,localProjectRows:Gu,visibleProjectRows:ko,cloudProjectRows:Zu,projectSessionRowsByProjectId:il,childSessionRowsByParentId:Ju,sidebarProjectIdBySessionId:Bi,chatRows:cl,visibleChatRows:ll,sessionEvents:Qu,chatMessages:dl,contextUsage:Yu,goalRuntime:Xu,subagentRuntime:ul}=h3({localProjects:D?.localProjects??[],cloudProjects:D?.cloudProjects??[],teamId:Ma.defaultTeamId,sessions:Pr,runtimeIndexes:al,appPreferences:Xt,selectedSessionId:xe,selectedProjectId:Q,archivedChatsOpen:B,projectsExpanded:G,chatRowsVisibleCount:oe,sidebarFileBookmarks:y}),em=h.useCallback(Ve=>{Ht(Ve);const en=[...Pr].filter(qt=>Ve==="work"?qt.experience==="work"||qt.experience==="development":qt.experience===Ve).sort((qt,Ft)=>Ft.updatedAt.localeCompare(qt.updatedAt))[0]??[...Gn].filter(qt=>qt.experience===Ve).sort((qt,Ft)=>Ft.updatedAt.localeCompare(qt.updatedAt))[0]??null;if(en)t({type:"selectSession",sessionId:en.id,appId:Ve!=="chat"?en.appId:null,projectId:Ve!=="chat"?Bi[en.id]??null:null});else if(t({type:"beginNewChat",appId:null}),Ve==="chat"&&ga==="codex"){const qt=gf(D?.providers,{enabledOnly:!0}).find(Ft=>Ft.value!=="codex")?.value??Fr;dn(qt),bn(jd(qt,D?.providers)??xc)}Ve==="chat"&&(un(!1),Ut(!1),ft("home")),At("chat")},[t,ga,D?.providers,Pr,Ut,Ht,bn,dn,ft,un,At,Bi,Gn]),ml=h.useCallback(Ve=>{const en=e.getSnapshot();if(Ht(Ve),(xe||Re||Q)&&(t({type:"beginNewChat",appId:null}),en&&e.set(en)),Ve==="chat"&&ga==="codex"){const qt=gf(D?.providers,{enabledOnly:!0}).find(Ft=>Ft.value!=="codex")?.value??Fr;dn(qt),bn(jd(qt,D?.providers)??xc)}Ve==="chat"&&(un(!1),Ut(!1),ft("home")),At("chat")},[ga,t,D?.providers,e,Re,Q,xe,Ut,Ht,bn,dn,ft,un,At]),{pendingChatUserMessages:tm,recordPendingChatUserMessage:nm,visibleChatMessages:am}=p3({chatMessages:dl,runtimeIndexes:al,selectedSessionId:xe}),Js=h.useMemo(()=>iq({selectedAppId:Re,selectedProjectId:Q,selectedSessionId:xe}),[Re,Q,xe]),pl=h.useRef(null);h.useEffect(()=>{const Ve=pl.current;pl.current=Js,!(!Ve||Ve.kind!=="draft"||Js.kind!=="session")&&(Oc(Ve,Js)||c(en=>{const qt=cq({tabs:en,previousScope:Ve,activeScope:Js});return qt.some((la,Mm)=>la!==en[Mm])?qt:en}))},[Js]);const sm=h.useMemo(()=>lq(i),[i]),{goalRuntime:rm,runningSessionIds:Fi,selectedSessionRunning:om,sidebarGoalRuntimeBySessionId:im,sidebarSubagentRuntimeBySessionId:cm}=x3({codexHistoryEvents:Ps,codexHistorySessions:ke,connection:ie,expandedProjectIds:zn,goalRuntime:Xu,locallyActiveCodexHistorySessionIds:w,pinnedSessions:qi,savedForLaterSessions:sl,projectSessionRowsByProjectId:il,rightChatHistoryEvents:T,runtimeIndexes:Ws,selectedSession:kn,selectedSessionId:xe,serverId:D?.server.id,setCodexHistorySessions:Mn,sidebarSessions:Gn,subagentRuntime:ul,visibleChatRows:ll,visibleProjectRows:ko}),{dragItem:lm,pinnedPreviewKeys:dm,startPinnedDrag:um,clearSidebarDrag:mm,previewPinnedDrop:pm,commitPinnedDrop:fm,commitPinnedPreviewDrop:hm}=R5({connection:ie,appPreferences:Xt,sessions:Gn,pinnedItems:rl,setAppPreferences:to,setCodexHistorySessions:Mn,setSessions:ha,sidebarFileBookmarks:y,setSidebarFileBookmarks:b,setError:Ke}),{clearTaskDrag:gm,commitTaskDrop:fl,commitTaskPreviewDrop:vm,previewTaskDrop:Oa,startTaskDrag:wo,taskDragSessionId:bm,taskPreviewSessionIds:ym}=P5({connection:ie,sessions:Gn,setCodexHistorySessions:Mn,setError:Ke,setSessions:ha}),{commandProjectRows:Sm,contextWindowStatus:Vi,pinnedRows:xm,sidebarWorkspaceAppIds:km}=QF({activeProvider:ga,contextCompaction:Ma.contextCompaction,contextUsage:Yu,pinnedItems:rl,pinnedPreviewKeys:dm??[],pinnedProjects:Vu,projectRows:ol,visibleProjectRows:ko}),As=!!(ca&&(me==="chat"||me==="labs")&&(Le||q&&(U==="changes"||U==="goal"))),{workspaceStates:Io,workspaceBusy:_o,diffBusy:wm,visibleWorkspaceState:Or,visibleWorkspaceDiff:Ki,rememberWorkspaceState:Co,refreshWorkspace:Wi,refreshWorkspaceDiff:ns,setWorkspaceBusy:gl}=rK({connection:ie,activeWorkspaceAppId:ca,view:me,shouldLoadWorkspaceDiff:As,sidebarWorkspaceAppIds:km,setError:Ke});se.current=Co;const Im=h.useCallback((Ve=ca)=>!Ve||Ve!==ca||!As?Promise.resolve(null):ns(Ve),[ns,As,ca]),_m=h.useCallback(async(Ve={})=>{!ca||!As||await ns(ca,Ve)},[ns,As,ca]),Cm=!1,Rm=!!(kn?.provider==="codex"&&kn.cwd&&!ys(kn.workspaceKind)),Pm=!!(Or&&!Or.initialized&&Ya!=="local_project"&&ga!=="codex"&&!Rm&&!Mi),Tm=Ya==="local_project"&&!!Wn?.sandboxTemplate?.detected&&!Wn?.linkedOpenPondApp?.appId,[vl,bl]=h.useState(null),[Am,yl]=h.useState(null),{projectTarget:Em,workspaceTarget:jm}=LF({accountPending:lo,accountSignedOut:Gs,activeWorkspaceLocation:mo,bootstrap:D,busy:N,cloudLinked:po,selectedCloudProject:Cs,selectedProject:Wn,selectedSession:kn,pendingWorkspaceTarget:vl,workspaceStates:Io,workspaceBusy:_o});return h.useEffect(()=>{bl(null)},[kn?.id]),{composerDraftStore:e,appDispatch:t,pendingTerminalCommand:s,setPendingTerminalCommand:r,terminalTabs:i,setTerminalTabs:c,trainingDetailTasksetId:u,setTrainingDetailTasksetId:l,mentionedAppId:p,setMentionedAppId:f,cloudSetupDialog:I,setCloudSetupDialog:C,rightPanelTabRequest:P,setRightPanelTabRequest:_,workspaceDiffPanelViewState:M,setWorkspaceDiffPanelViewState:A,rightChatHistoryEvents:T,setRightChatHistoryEvents:S,locallyActiveCodexHistorySessionIds:w,setCodexHistoryTurnLocallyActive:O,mainComposerFocusRequestId:z,requestMainComposerFocus:Mr,draftSubagentDelegationMode:V,setDraftSubagentDelegationMode:Y,confirmProjectAction:ee,projectConfirmDialog:H,resolveProjectConfirmDialog:F,query:J,searchOpen:K,archivedChatsOpen:B,sectionMenuOpen:ne,projectsExpanded:G,cloudProjectsExpanded:te,sidebarOpen:ve,view:me,selectedAppId:Re,selectedProjectId:Q,selectedSessionId:xe,draftProvider:je,draftModel:De,draftExperience:ze,activeExperience:Rs,changeExperience:em,changeNewExperience:ml,codexPermissionMode:we,codexReasoningEffort:Me,openPondCommandAccessMode:Te,busy:N,diffPanelOpen:q,diffPanelExpanded:X,rightPanelMode:U,rightChatPanels:ae,terminalOpen:de,settingsSection:be,newProjectDialogOpen:Oe,newProjectMode:$e,newProjectName:Ge,newProjectPath:bt,newProjectBusy:ye,commitDialogOpen:Le,commitMessage:Ae,commitIncludeUnstaged:qe,commitNextStep:He,commitDraft:vn,branchDialogOpen:jt,branchDialogName:pe,toast:fe,error:Fe,labDetailNavigation:Pe,setQuery:Ne,setSearchOpen:rt,setArchivedChatsOpen:lt,setSectionMenuOpen:Tt,setProjectsExpanded:dt,setCloudProjectsExpanded:at,setChatRowsVisibleCount:_t,setSidebarOpen:Be,setView:At,setSelectedAppId:ln,setSelectedProjectId:En,setSelectedSessionId:xt,setPrompt:xs,setDraftProvider:dn,setDraftModel:bn,setDraftExperience:Ht,setDiffPanelOpen:jn,setDiffPanelExpanded:Ut,setRightPanelMode:ft,setRightChatPanels:Un,setTerminalOpen:un,setSyncingWorkspaceAppId:ut,setSettingsSection:It,setNewProjectDialogOpen:Mt,setNewProjectMode:mn,setNewProjectName:ra,setNewProjectPath:Ze,setNewProjectBusy:Pn,setCommitDialogOpen:Ga,setCommitMessage:Aa,setCommitIncludeUnstaged:Dn,setCommitNextStep:Tn,setCommitDraft:Za,setBranchDialogOpen:ks,setBranchDialogName:Ea,setError:Ke,showToast:yt,appPreferences:Xt,applyBootstrapPayload:Ln,applyPreferencesPayload:Sn,approvals:qn,bootstrap:D,connection:ie,events:Je,runtimeEventStore:fa,sessions:ja,startup:xn,setAppPreferences:to,setCodexHistorySessions:Mn,setEvents:oa,setSessions:ha,training:mt,pinnedCollapsed:ki,projectsCollapsed:Ir,cloudProjectsCollapsed:wi,chatsCollapsed:no,savedForLaterCollapsed:Ii,sidebarWidth:_s,sidebarResizing:_i,diffPanelWidth:ao,diffPanelResizing:so,togglePinnedCollapsed:ro,toggleProjectsCollapsed:Ci,toggleCloudProjectsCollapsed:Ri,toggleChatsCollapsed:Ja,toggleSavedForLaterCollapsed:Pi,startSidebarResize:oo,startDiffPanelResize:_r,cloudProjectById:Cr,localProjectById:ia,selectedApp:Rr,selectedCloudProject:Cs,selectedProject:Wn,selectedProjectLinkedApp:Ai,selectedProjectLinkedOpenPondApp:Ei,selectedSession:kn,sidebarSessions:Gn,runtimeIndexes:Ws,chatMentionApps:ji,connectedAppMentions:co,pendingApproval:Tr,codexHistoryEvents:Ps,setCodexHistoryEvents:Ts,account:Ar,accountPending:lo,accountSignedOut:Gs,activeModel:Qa,activeProvider:ga,activeWorkspaceAppId:uo,activeWorkspaceId:Zs,activeWorkspaceKind:Ya,activeWorkspaceLocation:mo,appDefaults:Ma,selectedSessionProjectId:fo,startMessage:Oi,workspaceName:ho,accountScopeKey:go,organizations:Er,teamChatOrganization:bo,teamChatTeamId:jr,teamChat:Xa,publishTeamProfileAgent:$i,communities:Ni,communitySidebar:Di,communityView:Li,teamAiThreadId:es,toggleTeamAiSidebar:zi,selectedProjectConfirmedCloudProject:Hi,activeOpenPondCommandAccessMode:Ui,viewWorkspaceAppId:ca,viewWorkspaceId:So,viewWorkspaceKind:et,viewWorkspaceName:Bt,openPondActionCatalog:ts,selectedActionCatalog:sn,expandedProjectIds:zn,expandProject:On,toggleProjectExpanded:Pu,setExpandedProjectIds:Tu,changeCodexPermissionMode:Au,changeCodexReasoningEffort:Eu,changeOpenPondCommandAccessMode:tl,resolveApproval:ju,beginNewChat:nl,advanceTrainingModelChatAfterTurn:Mu,beginNewChatWithTrainingModel:Ou,bindTrainingModelChatSession:$u,dismissTrainingChatHandoff:Nu,trainingChatHandoff:Du,prepareTrainingModelChatTurn:Lu,selectTrainingChatTaskForComposer:zu,chatHistoryLoadStates:Hu,loadMoreSelectedChatHistory:Uu,selectedPagedSessionEvents:qu,activeSessions:Bu,archivedSessions:Fu,pinnedSessions:qi,savedForLaterSessions:sl,pinnedFiles:Ku,savedForLaterFiles:Wu,sidebarFileBookmarks:y,setSidebarFileStatus:wr,projectRows:ol,localProjectRows:Gu,visibleProjectRows:ko,cloudProjectRows:Zu,projectSessionRowsByProjectId:il,childSessionRowsByParentId:Ju,sidebarProjectIdBySessionId:Bi,chatRows:cl,visibleChatRows:ll,chatRowsVisibleCount:oe,sessionEvents:Qu,chatMessages:dl,goalRuntime:rm,subagentRuntime:ul,pendingChatUserMessages:tm,recordPendingChatUserMessage:nm,visibleChatMessages:am,activeTerminalScope:Js,terminalSummaries:sm,runningSessionIds:Fi,selectedSessionRunning:om,sidebarGoalRuntimeBySessionId:im,sidebarSubagentRuntimeBySessionId:cm,taskDragSessionId:bm,taskPreviewSessionIds:ym,startTaskDrag:wo,clearTaskDrag:gm,previewTaskDrop:Oa,commitTaskDrop:fl,commitTaskPreviewDrop:vm,dragItem:lm,startPinnedDrag:um,clearSidebarDrag:mm,previewPinnedDrop:pm,commitPinnedDrop:fm,commitPinnedPreviewDrop:hm,commandProjectRows:Sm,contextWindowStatus:Vi,pinnedRows:xm,workspaceStates:Io,workspaceBusy:_o,diffBusy:wm,visibleWorkspaceState:Or,visibleWorkspaceDiff:Ki,rememberWorkspaceState:Co,refreshWorkspace:Wi,refreshWorkspaceDiff:ns,setWorkspaceBusy:gl,refreshWorkspaceDiffWhenNeeded:Im,refreshVisibleWorkspaceDiff:_m,managedWorkspace:Cm,canSyncActiveWorkspace:Pm,canPublishOpenPondProject:Tm,pendingWorkspaceTarget:vl,setPendingWorkspaceTarget:bl,pendingSidebarWorkspaceTarget:Am,setPendingSidebarWorkspaceTarget:yl,projectTarget:Em,workspaceTarget:jm}}const a9=/^(localhost|\[::1\]|127(?:\.\d{1,3}){3})(?::\d+)?(?:[/?#].*)?$/i,s9=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?:[:/?#].*)?$/i;function r9(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)?Wl(n,new Set(["http:","https:"])):/^file:\/\//i.test(n)?t.explicitFile?Wl(n,new Set(["file:"])):null:a9.test(n)?Wl(`http://${n}`,new Set(["http:"])):s9.test(n)?Wl(`https://${n}`,new Set(["https:"])):null}function Wl(e,t){try{const n=new URL(e);return t.has(n.protocol)?n.toString():null}catch{return null}}async function o9(e){const t=r9(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 i9="openpond-coding-core-v1",c9="feature";function Of(e){const t=new URL("/sandboxes",Hg(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",c9),t.searchParams.set("runtimeProfileId",i9),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 NG(e){const t=e.organizationSlug?.trim(),n=t?`/sandboxes/${encodeURIComponent(t)}/billing`:"/sandboxes/billing",a=new URL(n,Hg(e.accountBaseUrl));return!t&&e.teamId?.trim()&&a.searchParams.set("teamId",e.teamId.trim()),a.toString()}function Yy(e){const t=e.organizationSlug?.trim(),n=e.projectSlug?.trim();return!t||!n?null:new URL(`/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,Hg(e.accountBaseUrl)).toString()}function Hg(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 l9({account:e,browserConversationId:t,cloudProjectById:n,cloudProjects:a,diffPanelOpen:s,rightPanelMode:r,selectedProjectId:i,setDiffPanelOpen:c,setNewProjectDialogOpen:u,setNewProjectMode:l,setNewProjectName:p,setRightPanelMode:f}){const y=h.useCallback(()=>{f("changes"),c(!0)},[c,f]),b=h.useCallback(()=>{if(s&&r==="changes"){c(!1);return}y()},[s,r,c,y]),I=h.useCallback(()=>{f("browser"),c(!0)},[c,f]),C=h.useCallback(()=>{f("goal"),c(!0)},[c,f]),P=h.useCallback((T,S)=>{o9({conversationId:t,href:T,explicitFile:S?.explicitFile,newTab:S?.newTab}).then(w=>{w&&I()})},[t,I]),_=h.useCallback(()=>{l("cloud"),p(""),u(!0)},[u,l,p]),M=h.useCallback(T=>{const S=n.get(T);S&&P(Of({accountBaseUrl:e?.baseUrl??e?.activeProfile?.baseUrl??null,teamId:S.teamId,projectId:S.id,projectName:S.name,baseBranch:S.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:y,showGoalSidebarTab:C,toggleChangesPanel:b}}function d9(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?.(r=>{const i=d9({currentConversationId:e,requestConversationId:r.conversationId,sessionIds:t});i.reveal&&(i.sessionIdToOpen&&n(i.sessionIdToOpen),a())}),[e,n,a,t])}const m9="chat",p9=["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 Xy(e){const t=Ep(e.label);if(t&&!$f(t))return e0(t);const n=Ep(e.name);if(n&&!$f(n))return e0(n);const a=Ep(e.actionId)?.replace(/\.chat$/i,"")??"";return h9(a||t||"Profile Agent")}function $f(e){return e.trim().toLowerCase()===m9}function h9(e){const t=g9(e.replace(/\.chat$/i,"").replace(/[._-]+/g," ").replace(/\s+/g," ").trim()),a=t.toLowerCase().split(/\s+/).map(s=>s.replace(/[^a-z0-9]/g,"")).filter(s=>s&&!f9.has(s)).slice(0,3);return B1(a.length?a.join(" "):t||e)}function e0(e){return B1(e).split(/\s+/).slice(0,4).join(" ")}function g9(e){let t=e.trim();for(const n of p9)if(t.toLowerCase().startsWith(`${n} `)){t=t.slice(n.length).trim();break}return t}function Ep(e){return typeof e=="string"&&e.trim()?e.trim():null}function B1(e){return e.replace(/[._-]+/g," ").replace(/\s+/g," ").trim().replace(/\b[a-z0-9]/gi,t=>t.toUpperCase())}const v9="openpond-profile-action";function b9(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Gl(e){return typeof e=="string"&&e.trim()?e.trim():null}function y9(e){const t=b9(e.implementation);if(t?.type!==v9)return null;const n=Gl(t.actionId)??e.id;if(e.sourceActionId!=="chat"&&n!=="chat"&&!n.endsWith(".chat"))return null;const a=Gl(e.label);if(a&&!$f(a))return Xy({label:a,description:e.description});const s=Gl(t.agentName)??Gl(e.name);return Xy({actionId:n,description:e.description,name:s})}function S9(e){const t=y9(e);return t||e.label?.trim()||e.name?.trim()||e.id}function F1(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 x9=new Set(["action","agent","chat","customer","default","filter","items","open","openpond","profile","run","summarize","track","workflow"]);function V1(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function hi(e){return typeof e=="string"&&e.trim()?e.trim():null}function Go(e,t,n={}){const a=hi(t)?Hn(String(t)):"";a&&(!n.generic&&x9.has(a)||e.add(a))}function Zl(e,t){const n=hi(t);if(n)for(const a of n.split(/[.:/\\\s]+/g))Go(e,a)}function k9(e,t){const n=hi(t);if(n)for(const a of n.split(/[^A-Za-z0-9_-]+/g))a.length<4||Go(e,a)}function K1(e){const t=new Set,n=V1(e.implementation),a=hi(n?.actionId);return Go(t,e.id,{generic:!0}),Zl(t,e.id),Go(t,a,{generic:!0}),Zl(t,a),Go(t,e.name,{generic:!0}),Zl(t,e.name),Go(t,e.label,{generic:!0}),Zl(t,e.label),k9(t,e.description),t}function w9(e){const t=V1(e.implementation);return[e.id,e.name??"",e.label??"",e.description??"",hi(t?.actionId)??"",hi(t?.agentName)??"",F1(e),...Array.from(K1(e))].join(" ").toLowerCase()}function DG(e,t,n=8){const a=Hn(t);return e.length===0?[]:e.filter(s=>a?w9(s).includes(a):!0).slice(0,n)}function I9(e){return Array.from(e.matchAll(/(?:^|\s)@([A-Za-z0-9_-]+)/g)).map(t=>Hn(t[1]??"")).filter(Boolean)}function _9(e,t){const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return e.replace(new RegExp(`(^|\\s)@${n}(?=\\s|$)`,"g"),"$1").replace(/\s+/g," ").trim()}function C9(e,t){const n=I9(e);if(n.length===0||t.length===0)return null;const a=new Map;for(const r of n)for(const i of t)K1(i).has(r)&&a.set(i.id,{action:i,mention:r});if(a.size!==1)return null;const s=Array.from(a.values())[0];return{action:s.action,mention:s.mention,prompt:_9(e,s.mention)}}function LG(e){return S9(e)}function zG(e){return e.description||F1(e)}const Ug=[{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 R9(e){return Ug.filter(t=>t.id!=="goal"||e==="codex")}function W1(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 HG(e,t){return R9(e).filter(n=>W1(n,t))}const P9=new Set(Ug.map(e=>e.id));function UG(e){return e.subcommands?.length?e.subcommands.join(", "):e.description}function T9(e){return[e.id,e.command,e.label,e.description].join(" ")}function A9(e){return(e.subcommands??[]).flatMap(t=>[t,`${e.id} ${t}`,`${e.command} ${t}`]).join(" ")}function E9(e){const t=/^\/([a-z][a-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(e.trim());if(!t)return null;const n=t[1];return P9.has(n)?{command:n,args:t[2]?.trim()??""}:null}function j9(e){const t=e.trim();if(!t.startsWith("!"))return null;const n=t.slice(1).trim();return n?{command:n}:null}function qG({commands:e=Ug,prompt:t,limit:n=10}){if(!t.startsWith("/"))return[];const a=t.slice(1).trim().toLowerCase();if(!a)return e.slice(0,n);const s=e.filter(c=>c.id.startsWith(a));if(s.length>0)return s.slice(0,n);const r=e.filter(c=>T9(c).toLowerCase().includes(a));return(r.length>0?r:e.filter(c=>A9(c).toLowerCase().includes(a))).slice(0,n)}function BG(e){return e==="owner"?"Owner":e==="admin"?"Admin":"Member"}function Cu(e){return e?.role==="owner"||e?.role==="admin"}function FG(e){const t=Ru(e.organizations,e.defaultTeamId),n=Cu(t),a=e.localProject??null;if(!a)return M9("Open a local project to set up an Agent.");const s=O9(a,e.projects),r=$9(a,s,e.agents),i=!!a.sandboxTemplate?.detected,c=t&&!n?"Ask an owner or admin to connect this project.":null;return i?s?N9(a,s)?Jl({state:"needs_sync",actionLabel:"Sync Project",project:s,agent:r,canManage:n,actionBlockedReason:c}):r?{state:"ready",actionLabel:"Run Agent",canAct:!0,reason:null,project:s,agent:r}:Jl({state:"needs_agent",actionLabel:"Create Agent",project:s,agent:null,canManage:n,actionBlockedReason:c}):Jl({state:"needs_project",actionLabel:"Connect Project",project:null,agent:null,canManage:n,actionBlockedReason:c}):Jl({state:"missing_config",actionLabel:"Add Agent config",project:s,agent:r,canManage:n,actionBlockedReason:c})}function Jl(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 M9(e){return{state:"blocked",actionLabel:"Ask admin",canAct:!1,reason:e,project:null,agent:null}}function Ru(e,t){if(e.length===0)return null;const n=t?.trim()??"";if(n){const a=e.find(s=>s.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 O9(e,t){const n=e.linkedSandboxProject;return n?.projectId?t.find(a=>a.id===n.projectId)??null:null}function $9(e,t,n){if(!t)return null;const a=e.preferredSandboxAgentId;if(a){const s=n.find(r=>r.id===a&&r.projectId===t.id);if(s)return s}return n.find(s=>s.projectId===t.id)??null}function N9(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 $r=e=>e.slice(0,2e4);function D9({model:e,provider:t,providerSettings:n}){return{model:Sg(t,e,n),modelRef:Na(t,e,n)}}function L9(e,t){return e.some(n=>n.id===t.id)?e:[...e,t]}function z9(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 H9(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 t0({action:e,prompt:t,runPayload:n,sessionId:a}){const s=new Date().toISOString(),r=`openpond_action_${n.run.id}`,i=n.run.status==="failed"?"failed":n.run.status==="succeeded"?"completed":"started";return[{id:`${r}_user`,sessionId:a,turnId:r,name:"turn.started",timestamp:s,source:"chat_action",args:{prompt:t}},{id:`${r}_result`,sessionId:a,turnId:r,name:"workspace_action_result",timestamp:n.run.updatedAt??s,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 U9({applyBootstrapPayload:e,connection:t,codexPermissionMode:n,codexReasoningEffort:a,openPondCommandAccessMode:s,draftModel:r,draftProvider:i,experience:c,expandProject:u,ensureCloudSessionReady:l,getPrompt:p,bootstrap:f,chatMessages:y,apps:b,connectedAppMentions:I,mentionedAppId:C,refreshWorkspace:P,refreshWorkspaceDiff:_,selectedApp:M,selectedActionCatalog:A,openPondActionCatalog:T,cloudProjects:S,accountScopeKey:w,selectedCloudProject:R,selectedProject:O,selectedProjectLinkedOpenPondApp:z,selectedSession:$,workspaceTarget:V,subagentDelegationMode:Y,setDraftModel:se,setDraftProvider:ee,setError:H,setPrompt:F,setMentionedAppId:J,setCodexHistoryEvents:K,setCodexHistorySessions:B,onCodexHistoryTurnActivityChange:ne,onCodexHistoryTurnPayload:G,onPendingUserMessage:te,setEvents:oe,setSelectedAppId:ve,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 ze=h.useRef(new Set),we=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),se(fe=>Sr(pe,fe,we)),xe("chat")}async function q(pe,fe){return(R1(fe,w)??await Og({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=Ru(pe.organizations.map(xu).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(!Cu(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=it("local",fe.id),rt=Ca(fe,S),lt=await Z.createSession(t,{provider:"openpond",modelRef:Na("openpond",si,we),openPondCommandAccessMode:Me("openpond",s),appId:null,appName:null,workspaceKind:"local_project",workspaceId:fe.id,workspaceName:fe.name,localProjectId:fe.id,cloudProjectId:rt?.id??null,cloudTeamId:rt?.teamId??null,cwd:fe.workspacePath,title:`Sync ${fe.name} to Cloud`});Q(Tt=>[lt,...Tt]),pe.onSessionCreated?.(lt),pe.selectSession&&(Re(lt.id),me(Ne),ve(null),xe("chat"),u(Ne)),pe.clearPromptForTurn(),je(!0);try{const Tt=await Z.uploadLocalProjectCloudSource(t,fe.id,{teamId:Fe.teamId,projectName:fe.name,branch:Pe,chatSessionId:lt.id,displayPrompt:pe.displayPrompt});return e(Tt.bootstrap),u(Ne),u(it("cloud",Tt.project.id)),!0}catch(Tt){const dt=await Z.bootstrap(t).catch(()=>null);throw dt&&e(dt),Tt}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=it("cloud",R.id),Ne=pe.providerForTurn;fe=await Z.createSession(t,{provider:Ne,modelRef:Na(Ne,pe.modelForTurnValue,we),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:$r(pe.command)}),Q(rt=>[fe,...rt]),pe.onSessionCreated?.(fe),pe.selectSession&&(Re(fe.id),me(Pe),ve(null),xe("chat"),u(Pe))}else{const Pe=O;if(!Pe)throw new Error("Select a project to use this.");const Ne=Ca(Pe,S),rt=it("local",Pe.id),lt=pe.providerForTurn;fe=await Z.createSession(t,{provider:lt,modelRef:Na(lt,pe.modelForTurnValue,we),openPondCommandAccessMode:Me(lt,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:$r(pe.command)}),Q(Tt=>[fe,...Tt]),pe.onSessionCreated?.(fe),pe.selectSession&&(Re(fe.id),me(rt),ve(null),xe("chat"),u(rt))}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=>oc(Pe,Fe.session)),oe(Pe=>Ns(Pe,Fe.events)),!0}async function de(pe=[],fe=null,Fe,Pe={}){const Ne=Fe??p();let rt=Ne.trim()||(pe.length>0?"Please review the attached files.":"");if(!t||!rt)return!1;const lt=Pe.displayPrompt?.trim()||rt,Tt=Pe.provider??i,dt=Pe.model??r,at=Pe.openPondCommandAccessMode??s,_t=Pe.session!==void 0,Be=_t?Pe.session??null:$,At=Pe.experience??Be?.experience??c,ln=At==="development"||At==="work"&&(Be?.workspaceKind==="local_project"||!!Be?.localProjectId||!!Be?.cloudProjectId||!_t&&!!(O||R||M||V==="hybrid"||V==="local")),En=_t||!ln?null:M,xt=_t||!ln?null:O,xs=_t||!ln?null:R,dn=_t||!ln?null:z,bn=!_t&&ln&&V==="hybrid",Ht=Pe.selectSession??!0,Cn=Pe.chatMessages??y,yn=Pe.session!==void 0?null:C,Rn=Pe.clearPrompt===void 0?()=>{F(""),J(null)}:Pe.clearPrompt,jn=fe?null:C9(rt,A),Ut=fe??jn?.action??null,ft=jn?.prompt||rt,Un=ln&&!Ut?j9(rt):null,un=Ut||Un?null:E9(rt),ut=un&&!W1({id:un.command},At)?un:null,It=Pe.usageAttribution??(un?{surface:"chat",workflowKind:"slash_command",commandName:`/${un.command}`,commandSource:"prompt_parse"}:void 0);H(null);let Mt=null,mn=!1,ra=null;try{if(!ln&&Tt==="codex")throw new Error("The Codex provider requires repository-aware Work.");if(ut)throw new Error(`/${ut.command} isn't available in ${At}.`);if(Un&&Tt!=="codex"&&Be?.provider!=="codex"){if(pe.length>0)throw new Error("Direct commands do not accept attachments.");return await ae({command:Un.command,clearPromptForTurn:Rn,modelForTurnValue:dt,onSessionCreated:Pe.onSessionCreated,openPondCommandAccessModeForTurn:at,providerForTurn:Tt,selectedSessionForTurn:Be,selectSession:Ht})}if(!_t&&un?.command==="sync-cloud")return await U({clearPromptForTurn:Rn,displayPrompt:lt,onSessionCreated:Pe.onSessionCreated,selectSession:Ht});if(Ut){const ct=KV(Ut);if(ct){let D=Be;if(!D||D.cloudProjectId!==ct.projectId){D=await Z.createSession(t,{provider:"openpond",modelRef:Na("openpond",dt,we),openPondCommandAccessMode:Me("openpond",at),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:ct.projectId,workspaceName:ct.projectName??ct.agentName,localProjectId:null,cloudProjectId:ct.projectId,cloudTeamId:ct.teamId,cwd:null,autoTitlePrompt:$r(lt)}),Q(fa=>[D,...fa]),Pe.onSessionCreated?.(D),Ht&&Re(D.id);const Je=it("cloud",ct.projectId);Ht&&me(Je),Ht&&u(Je)}const ke=await Z.runSandboxAgent(t,ct.agentId,QV({agent:ct,attachments:pe,displayPrompt:lt,prompt:ft})),ie=await Z.bootstrap(t);return e(ie),Rn(),oe(Je=>Ns(Je,t0({action:Ut,prompt:lt,runPayload:ke,sessionId:D.id}))),!0}const an=Lg(Ut);if(an){let D=Be;(!D||D.provider!=="openpond")&&(D=await Z.createSession(t,{provider:"openpond",modelRef:Na("openpond",dt,we),openPondCommandAccessMode:Me("openpond",at),appId:null,appName:null,workspaceId:null,workspaceName:"OpenPond profile",localProjectId:null,cloudProjectId:null,cloudTeamId:null,cwd:null,autoTitlePrompt:$r(lt)}),Q(ie=>[D,...ie]),Pe.onSessionCreated?.(D),Ht&&Re(D.id)),await Z.runProfileAction(t,ZV({action:an,attachments:pe,displayPrompt:lt,prompt:ft,sessionId:D.id}));const ke=await Z.bootstrap(t);return e(ke),Rn(),!0}const Ke=M1({cloudProjects:S,selectedCloudProject:R,selectedProject:O});if(!Ke)throw new Error("Select a Project linked to an OpenPond Cloud Project before running an action.");let yt=Be;(!yt||yt.cloudProjectId!==Ke.id)&&(yt=await Z.createSession(t,{provider:"openpond",modelRef:Na("openpond",dt,we),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:$r(lt)}),Q(D=>[yt,...D]),Pe.onSessionCreated?.(yt),Ht&&(Re(yt.id),me(Ke.selectionKey),u(Ke.selectionKey)));const Xt=await q(Ke.id,Ke.teamId);if(!Xt)throw new Error("No OpenPond Agent is available for this Project.");Rn();const Ln=await Z.runSandboxAgent(t,Xt.id,JV({action:Ut,attachments:pe,displayPrompt:lt,prompt:ft,teamId:Ke.teamId})),Sn=await Z.bootstrap(t);return e(Sn),oe(D=>Ns(D,t0({action:Ut,prompt:lt,runPayload:Ln,sessionId:yt.id}))),!0}let Ze=Be;if(Ze&&Wt(Ze.id)){ra=my({afterMessageId:Cn.at(-1)?.id??null,attachments:pe,content:rt,sessionId:Ze.id}),Rn(),Mt=Ze.id,ze.current.add(Mt),te?.(ra),ne?.(Mt,!0);const ct=z9(Ze.id,rt),an=yt=>{(!_t||$?.id===Ze.id)&&K(Xt=>L9(Xt,yt)),Pe.onCodexHistoryOptimisticEvent?.(yt)};an(ct),B(yt=>yt.map(Xt=>Xt.id===Ze.id?{...Xt,status:"active"}:Xt));const Ke=await Z.sendCodexHistoryTurn(t,Ze.id,{prompt:rt,attachments:pe.length>0?pe:void 0,model:Sg("codex",dt,we),modelRef:Na("codex",dt,we),...kb(n),codexPermissionMode:n,codexReasoningEffort:a}).catch(yt=>{throw an(H9(ct,yt)),yt});return(!_t||$?.id===Ze.id)&&K(yt=>Ns(yt,Ke.events)),B(yt=>oc(yt,Ke.session)),G?.(Ke),De(t),!0}const Ga=(yn?b.find(ct=>ct.id===yn&&zF(Ne,ct)&&ct.sandbox)??null:null)??HF(Ne,QI(b)),Aa=At==="chat"?[]:t5(Ne,I).map(ct=>ct.ref);if(!Ze){const ct=dn?.appId??En?.id??null,an=dn?.appName??En?.name??null,Ke=xs,yt=_t?null:Ca(xt,S),Xt=bn?VI({cloudProjects:S,selectedCloudProject:Ke,selectedProject:xt}):null;if(Xt?.kind==="missing_cloud_project")throw new Error(Xt.message);const Ln=Xt?.kind==="ready",Sn=Ln?Tt:Ke?"openpond":Tt,D=Na(Sn,dt,we),ke=Me(Sn,at),ie=Ln?KI({modelRef:D,provider:Sn,target:Xt,title:rt.slice(0,64)}):null;Ze=await Z.createSession(t,ie?{...ie,subagentDelegationMode:Y,metadata:{...ie.metadata,...Pe.sessionMetadata??{}},...ke?{openPondCommandAccessMode:ke}:{},autoTitlePrompt:$r(rt)}:{experience:At,provider:Sn,modelRef:D,subagentDelegationMode:Y,...ke?{openPondCommandAccessMode:ke}:{},appId:ct,appName:an,workspaceKind:Ke?"sandbox":xt?"local_project":En?"sandbox_app":void 0,workspaceId:xt?.id??(En?ct:void 0),workspaceName:Ke?.name??xt?.name??an,localProjectId:xt?.id??null,cloudProjectId:Ke?.id??yt?.id??null,cloudTeamId:Ke?.teamId??yt?.teamId??null,...!Ke&&!xt&&!En&&V==="local"?{metadata:{...bF(),...Pe.sessionMetadata??{}}}:{cwd:xt?xt.workspacePath:null,...Pe.sessionMetadata?{metadata:Pe.sessionMetadata}:{}},autoTitlePrompt:$r(rt)}),Q(Je=>[Ze,...Je]),Pe.onSessionCreated?.(Ze),Ht&&(Re(Ze.id),Ke&&me(it("cloud",Ke.id)),Ze.workspaceKind==="local_project"&&Ze.workspaceId&&u(it("local",Ze.workspaceId)),Ke&&u(it("cloud",Ke.id)))}if(n0(Ze)&&ys(Ze.workspaceKind)&&Ze.provider!=="openpond"&&!Ss(Ze))throw new Error("Cloud workspaces use OpenPond Chat. Switch to Local to use local providers.");if(n0(Ze)&&ys(Ze.workspaceKind)&&l)try{Ze=await l(Ze)}catch(ct){const an=ct instanceof Error?ct.message:String(ct);throw await Z.recordPreflightTurnFailure(t,Ze.id,{prompt:rt,error:an,target:Ss(Ze)?"hybrid_sandbox":"cloud_workspace"}).then(e).catch(()=>{}),ct}ra=my({afterMessageId:Cn.at(-1)?.id??null,attachments:pe,content:rt,sessionId:Ze.id}),Rn(),Mt=Ze.id,ze.current.add(Mt),te?.(ra),Q(ct=>ct.map(an=>an.id===Mt?{...an,status:"active"}:an));const Dn=Tt,Tn=D9({provider:Dn,model:dt,providerSettings:we}),Za=ZU(Dn,Tn.model??dt,we),ks=Dn==="codex"?kb(n):{approvalPolicy:"on-request",sandbox:"workspace-write"};await Z.sendTurn(t,Ze.id,{prompt:rt,metadata:Pe.turnMetadata,attachments:pe.length>0?pe:void 0,mentionedAppIds:Ga?[Ga.id]:void 0,mentionedConnectedApps:Aa.length>0?Aa:void 0,openPondActionCatalog:T.length>0?T:void 0,usageAttribution:It,...Tn,...ks,codexPermissionMode:Dn==="codex"?n:"default",codexReasoningEffort:Za?GU(Dn,Tn.model??dt,a,we):void 0}),mn=!0,De(t);const Ea=Ze.workspaceId??Ze.appId;return Ea&&Ze.workspaceKind!=="sandbox"&&Ze.workspaceKind!=="sandbox_template"&&P(Ea,!1).then(ct=>{ct?.initialized&&_(Ea)}),!0}catch(Ze){return H(Ze instanceof Error?Ze.message:String(Ze)),!1}finally{Mt&&ze.current.delete(Mt),Mt&&Wt(Mt)&&ne?.(Mt,!1),Mt&&(Wt(Mt)?B(Ze=>Ze.map(Pn=>Pn.id===Mt&&Pn.status==="active"?{...Pn,status:"idle"}:Pn)):mn||Q(Ze=>Ze.map(Pn=>Pn.id===Mt&&Pn.status==="active"?{...Pn,status:"idle"}:Pn)))}}async function be(pe,fe){const Fe=ze.current.values().next().value??null,Pe=pe??$?.id??Fe;if(!t||!Pe)return!1;if(H(null),Wt(Pe))try{const Ne=await Z.interruptCodexHistoryTurn(t,Pe);if(!Ne.interrupted){if(Ne.reason==="no_active_openpond_turn"){const lt=await Z.codexHistoryThread(t,Pe,{tail:!0}),Tt={...lt.session,status:"idle"};return $?.id===Pe&&K(dt=>Ns(dt,lt.events)),B(dt=>oc(dt,Tt)),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 rt=await Z.codexHistoryThread(t,Pe,{tail:!0});return $?.id===Pe&&K(lt=>Ns(lt,rt.events)),B(lt=>oc(lt,rt.session)),!0}catch(Ne){const rt=Ne instanceof Error?Ne.message:String(Ne);return H(rt==="Not found"?"OpenPond could not find this Codex history session, so it cannot interrupt it here.":rt),!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 bt(pe,fe){await Oe(pe.run,{type:"revise_plan",revision:fe})}async function ye(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 He(pe,fe){await Oe(pe.run,{type:"apply_candidate",candidateId:fe})}async function vn(pe,fe){await Oe(pe.run,{type:"reject_candidate",candidateId:fe,reason:null})}async function jt(pe,fe){await Oe(pe.run,{type:"reconcile_pull_request",candidateId:fe})}return{answerCreateImproveQuestion:ye,approveCreateImproveRun:$e,applyCreateImproveCandidate:He,cancelCreateImproveRun:Ge,changeDraftProvider:N,openCreateImprovePullRequest:qe,pauseCreateImproveRun:Le,reconcileCreateImprovePullRequest:jt,rejectCreateImproveCandidate:vn,resumeCreateImproveRun:Ae,reviseCreateImproveRun:bt,sendPrompt:de,stopTurn:be}}function n0(e){return e.experience==="development"||e.experience==="work"&&(e.workspaceKind==="local_project"||!!e.localProjectId||!!e.cloudProjectId||e.metadata?.workspaceTarget==="local")}async function q9({branch:e,connection:t,session:n}){if(!ys(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 B9(e){return Ss(e)?"Preparing Hybrid sandbox...":"Starting Cloud workspace..."}function F9(e,t){if(e==="already_running")return null;const n=Ss(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 V9(e,t){return!e.cloudProjectId||!e.cloudTeamId?!0:t.some(n=>n.id===e.cloudProjectId&&n.teamId===e.cloudTeamId)}function K9({applyBootstrapPayload:e,cloudProjects:t,connection:n,localProjectById:a,selectedCloudProject:s,selectedProject:r,setWorkspaceBusy:i,showToast:c,visibleWorkspaceState:u}){return h.useCallback(async l=>{if(!n)throw new Error("OpenPond App server is not connected.");const p=r??(l.localProjectId?a.get(l.localProjectId)??null:null);if(l.cloudProjectId&&l.cloudTeamId&&!V9(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(B9(l),"info"),i(!0);try{const f=await q9({branch:r?.linkedSandboxProject?.defaultBranch??s?.defaultBranch??u?.currentBranch??null,connection:n,localProject:p,session:l,source:Ss(l)?"openpond-app-hybrid-chat-preflight":"openpond-app-cloud-chat-preflight"});f.bootstrap&&e(f.bootstrap);const y=F9(f.status,l);return y&&c(y,"success"),f.session}finally{i(!1)}},[e,t,n,a,s,r,i,c,u?.currentBranch])}function W9(){return{diffPanelOpen:!1,diffPanelExpanded:!1,rightPanelMode:"changes",rightChatPanels:[]}}function G9(e){return{diffPanelOpen:e.diffPanelOpen,diffPanelExpanded:e.diffPanelExpanded,rightPanelMode:e.rightPanelMode,rightChatPanels:e.rightChatPanels}}function a0(e){return{...e,rightChatPanels:e.rightChatPanels.map(t=>({...t}))}}function Z9(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 s=t.rightChatPanels[a];return!!(s&&n.id===s.id&&n.activationVersion===s.activationVersion&&n.sessionId===s.sessionId&&n.prompt===s.prompt&&n.provider===s.provider&&n.model===s.model&&n.scrollTop===s.scrollTop&&n.stickyToBottom===s.stickyToBottom)})}function J9(e){return`${e.conversationId}\0${e.workspaceSourceKey||"none"}`}function Q9(e){const{appDispatch:t,diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:s,rightPanelMode:r,selectedAppId:i,selectedCloudProject:c,selectedProjectId:u,selectedSession:l,selectedSessionId:p,setWorkspaceDiffPanelViewState:f,view:y,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),S=p??`draft:${u??i??c?.id??"general"}`,w=h.useMemo(()=>I?`${C??"workspace"}:${I}`:b?`app:${b}`:l?.cwd&&!ys(l.workspaceKind)?`cwd:${l.cwd}`:"none",[l?.cwd,l?.workspaceKind,y,b,I,C]),R=J9({conversationId:S,workspaceSourceKey:w}),O=h.useMemo(()=>G9({diffPanelExpanded:n,diffPanelOpen:a,rightChatPanels:s,rightPanelMode:r}),[n,a,s,r]);h.useEffect(()=>{const $=A.current;$&&_.current.set($,a0(O))},[S,O]),h.useEffect(()=>{if(A.current===S)return;A.current=S;const V=_.current.get(S)??W9();Z9(O,V)||t({type:"patch",patch:a0(V)})},[S,O]),h.useEffect(()=>{const $=T.current;$&&M.current.set($,fp(P))},[R,P]),h.useEffect(()=>{if(T.current===R)return;T.current=R;const V=M.current.get(R)??WI();f(Y=>ey(Y,V)?Y:fp(V))},[R]);const z=h.useCallback($=>{f(V=>ey(V,$)?V:fp($))},[]);return{browserConversationId:S,handleWorkspaceDiffPanelViewStateChange:z}}function Y9({account:e,accountPending:t,accountSignedOut:n,activeWorkspaceKind:a,activeWorkspaceLocation:s,appDispatch:r,applyBootstrapPayload:i,busy:c,cloudSetupDialog:u,cloudProjects:l,connection:p,defaultTeamId:f,expandProject:y,localProjectById:b,selectedCloudProject:I,selectedProject:C,selectedSession:P,selectedSessionProjectId:_,setCloudSetupDialog:M,setDiffPanelOpen:A,setError:T,setSessions:S,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=u;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=Ca(K,l);M(ne=>ne&&{...ne,status:"uploading",error:null,previewLoading:!1});try{const ne=await Z.organizations(p),G=Ru(ne.organizations.map(xu).filter(xe=>!!xe).filter(xe=>xe.status==="active"),f);if(!G)throw new Error("Add an OpenPond account before creating a Cloud environment.");if(!Cu(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=it("local",K.id),ve=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`});S(xe=>[ve,...xe]),r({type:"selectSession",sessionId:ve.id,projectId:oe}),y(oe);const me=await Z.uploadLocalProjectCloudSource(p,K.id,{teamId:G.teamId,projectName:K.name,branch:te,chatSessionId:ve.id,displayPrompt:`/sync-cloud ${K.name}`});i(me.bootstrap),y(oe),y(it("cloud",me.project.id));const Re=Of({accountBaseUrl:$,teamId:me.project.teamId,projectId:me.project.id,projectName:me.project.name,baseBranch:me.upload.branch,localProjectId:K.id,source:"openpond-app"}),Q=Yy({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)}},[$,r,i,u,l,p,f,y,b,M,T,S,w,R]),se=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===s||z||c)return;if(T(null),F==="upload_cloud"){if(!C){R("Select a local Project before uploading source.","error");return}se(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(ys(a)&&!window.confirm("Switch to Local? Cloud changes will stay in the hosted workspace until you preserve or export them."))return;const G=it("local",ne.id);r({type:"selectProject",projectId:G}),y(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:Yy({accountBaseUrl:$,organizationSlug:I.organizationSlug,projectSlug:I.slug}),setupUrl:Of({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";se(J,K)},[$,t,n,a,s,r,c,p,l,y,b,se,I,C,P,_,M,A,T,R,O?.currentBranch,z]),H=h.useCallback(F=>{vg(F)&&se(F.project)},[se]);return{changeWorkspaceTarget:ee,moveProjectToCloud:H,openCloudSetupForLocalProject:se,startCloudSetupUpload:Y}}function X9({advanceTrainingTurn:e,bindTrainingSession:t,composerDraftStore:n,onSessionCreated:a,onSubmitted:s,prepareTrainingTurn:r,sendPrompt:i,setMentionedAppId:c,showToast:u}){return h.useCallback(async(l=[],p=null,f,y={})=>{const b=f??n.getSnapshot(),I=r(b);if(I.active&&b.trim()&&!I.metadata)return u(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:y.preservePrompt?()=>{}:void 0,displayPrompt:y.displayPrompt,onSessionCreated:P=>{a(P),I.metadata&&t(P.id)},turnMetadata:I.metadata||y.turnMetadata?{...I.metadata??{},...y.turnMetadata??{}}:void 0,sessionMetadata:I.metadata?{trainingTasksetId:I.metadata.trainingTasksetId,trainingTasksetName:I.metadata.trainingTasksetName}:void 0});return C&&await s?.(),C&&I.metadata&&e(),C},[e,t,n,a,s,r,i,c,u])}function eW({appDispatch:e,connection:t,sessions:n,setDiffPanelOpen:a,setRightPanelMode:s,setSessions:r,setView:i}){return h.useCallback(async c=>{if(!t)return;const u=n.find(f=>!f.archived&&f.workspaceKind==="sandbox"&&f.workspaceId===c.sandboxId);if(u){e({type:"selectSession",sessionId:u.id,appId:null,projectId:null}),s("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});r(f=>[p,...f]),e({type:"selectSession",sessionId:p.id,appId:null,projectId:null}),s("changes"),a(!0),i("chat")},[e,t,n,a,s,r,i])}function tW({connection:e,defaultTeamId:t,sessions:n,selectedProjectId:a,confirmProjectAction:s,applyBootstrapPayload:r,expandProject:i,setExpandedProjectIds:c,setSelectedAppId:u,setSelectedProjectId:l,setSelectedSessionId:p,setError:f,setView:y,showToast:b}){function I(A){const T=it("local",A.id);u(null),l(T),p(null),y("chat"),i(T)}async function C(A){if(!e)return!1;f(null);try{const T=await Z.createLocalProject(e,A);return r(T.bootstrap),I(T.project),b(T.created===!1?`Opened ${T.project.name}`:`Created ${T.project.name}`,"success"),!0}catch(T){const S=T instanceof Error?T.message:String(T);return f(S),b(S,"error"),!1}}async function P(A){if(!e)return!1;const T=A.trim();if(!T)return!1;f(null);try{const S=await Z.createLocalProject(e,{createNew:!0,name:T});return r(S.bootstrap),I(S.project),b(`Created ${S.project.name}`,"success"),!0}catch(S){return f(S instanceof Error?S.message:String(S)),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 S=await Z.organizations(e),w=Ru(S.organizations.map(xu).filter(V=>!!V).filter(V=>V.status==="active"),t);if(!w)throw new Error("Add an OpenPond account before creating a Cloud Project.");if(!Cu(w))throw new Error(`You need owner or admin access to create projects in ${w.displayName}.`);const R=`${GI(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:TF(`# ${T}
|
|
139
|
+
|
|
140
|
+
Created in OpenPond Cloud.
|
|
141
|
+
`)}]})).project;const z=await Z.bootstrap(e);r(z);const $=it("cloud",O.id);return u(null),l($),p(null),y("chat"),i($),b(`Created Cloud Project: ${O.name}`,"success"),!0}catch(S){const w=S instanceof Error?S.message:String(S);return f(w),b(w,"error"),!1}}async function M(A){if(!e)return;if(qU(A)){const R=`Archive ${A.project.name} in OpenPond Cloud?`;if(!(s?await s({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}),r(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(!vg(A))return;const T=A.project,S=`Remove ${T.name} from Projects? The folder will not be deleted.`;if(s?await s({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(S)){f(null);try{const R=await Z.deleteLocalProject(e,T.id);r(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 nW({appDispatch:e,busy:t,cloudProjectById:n,createCloudProjectFromScratch:a,createProjectFromScratch:s,createProjectCollection:r,expandProject:i,localProjectById:c,onCreateCloudEnvironment:u,onNewCloudProject:l,onNewLocalProject:p,onUseExistingFolderPath:f,newProjectBusy:y,newProjectMode:b,newProjectName:I,projectTargetValue:C,setDiffPanelOpen:P,setDraftModel:_,setDraftProvider:M,setError:A,setNewProjectBusy:T,setNewProjectDialogOpen:S,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"){u();return}if(Y==="none"){e({type:"selectProject",projectId:null}),P(!1),O("Started a chat without project files.","info");return}const se=Y.indexOf(":"),ee=se>=0?Y.slice(0,se):"",H=se>=0?Y.slice(se+1):"";if(ee==="local"){const F=c.get(H);if(!F){O("Project is no longer available.","error");return}const J=it("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=it("cloud",F.id);e({type:"selectProject",projectId:J}),i(J),M("openpond"),_(K=>Sr("openpond",K)),P(!1)}},[e,t,n,i,c,u,l,p,f,C,P,_,M,A,O,z]),V=h.useCallback(async Y=>{const se=I.trim();if(!y){if(b==="existing-local"?!Y?.name.trim()||!Y.sourceFolders.length:!se)return!1;T(!0);try{const ee=b==="cloud"?await a(se):b==="existing-local"?await r(Y):await s(se);return ee&&(S(!1),w(""),R("")),!!ee}finally{T(!1)}}},[a,s,r,y,b,I,T,S,w,R]);return{changeProjectTarget:$,submitNewProjectDialog:V}}function aW(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 VG(e){return e.reduce((t,n)=>!t||n.activationVersion>=t.activationVersion?n:t,null)}function sW(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const s=e.map(r=>r.id!==t?r:(a=!0,{...r,activationVersion:n}));return a?s:[...e]}function rW(e,t){const n=Math.max(0,...e.map(r=>r.activationVersion))+1;let a=!1;const s=e.map(r=>r.sessionId!==t.sessionId?r:(a=!0,{...r,activationVersion:n,prompt:t.prompt??r.prompt}));return a?s:[...e]}function G1(e){return!!(e.parentSessionId&&e.subagentRunId)}function oW(e){const t=e.sessions.filter(G1);return{knownSessionIds:new Set(t.map(n=>n.id)),newSessions:t.filter(n=>!e.knownSessionIds.has(n.id))}}function iW(e,t){const n=new Set(e.map(s=>s.sessionId).filter(Boolean)),a=t.filter(G1).filter(s=>!n.has(s.id)).map(s=>({id:`right-subagent-${s.id}`,activationVersion:1,sessionId:s.id,prompt:"",provider:s.provider,model:s.modelRef?.modelId??"",scrollTop:0,stickyToBottom:!0}));return a.length>0?[...e,...a]:e}const s0="openpond/openpond",cW="github.issue.write";function lW(e){return e.some(t=>t.provider==="github"&&(t.ref.capabilities??[]).includes(cW))}function KG(e){return[`Title: ${e.title.trim()}`,"","Description:",e.description.trim()].join(`
|
|
142
|
+
`)}function dW(e){const t=e.trim();return[`@github Submit this request as a new GitHub issue in ${s0}.`,`Use the GitHub connected app write operation github.issue.create with input.repo set to ${s0}, 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:dW(n),requiresInstructions:!0};case"sync-cloud":return{kind:"send_prompt",prompt:`/sync-cloud ${n}`,requiresInstructions:!1}}}const r0=[];function mW(e){const{approvals:t,codexHistoryEvents:n,contextCompaction:a,pendingChatUserMessages:s,rightChatHistoryEvents:r,rightChatPanels:i,runningSessionIds:c,selectedSessionId:u,sidebarSessions:l}=e;return h.useMemo(()=>{const p=new Map(l.map(y=>[y.id,y])),f=pW(t);return i.map(y=>{const b=y.sessionId?p.get(y.sessionId)??null:null,I=Wt(y.sessionId),C=I?(y.sessionId?r[y.sessionId]:void 0)??(y.sessionId===u?n:r0):r0,P=wf(C,[]),_=y.sessionId?f.get(y.sessionId)??null:null,M=!!(b&&c.has(b.id)),A=I?D4({events:C}):null,T=b?.cwd??null,S=b?.appId??b?.localProjectId??(b?.workspaceKind==="local_project"?b.workspaceId??null:null)??(b?.cwd&&!ys(b.workspaceKind)?kS(b.cwd):null),w=y.sessionId?s[y.sessionId]??null:null;return{...y,session:b,title:L4(A,b?.title??"New task"),messages:I?o1(Iu(C),w):[],createImproveRun:A,contextWindowStatus:II({provider:y.provider,snapshot:HI(P,y.sessionId),preferences:a}),goalRuntime:UI(P,y.sessionId),pendingApproval:_,running:M,workspaceRootPath:T,activeWorkspaceAppId:S,pendingUserMessage:w,runtimeSource:I?"history":"live"}})},[t,n,a,s,r,i,c,u,l])}function pW(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:s,sessions:r,setError:i}=e,c=h.useMemo(()=>{const p=new Set,f=[];for(const y of s)!Wt(y.sessionId)||!y.sessionId||p.has(y.sessionId)||(p.add(y.sessionId),f.push(y.sessionId));return f.join(`
|
|
147
|
+
`)},[s]),u=h.useMemo(()=>{if(!c)return"";const p=new Set(c.split(`
|
|
148
|
+
`).filter(Boolean));return r.filter(f=>p.has(f.id)&&f.status==="active").map(f=>f.id).join(`
|
|
149
|
+
`)},[c,r]),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(u.split(`
|
|
153
|
+
`).filter(Boolean)),y=new Set(l.split(`
|
|
154
|
+
`).filter(Boolean)),b=p.map(I=>Eg({connection:n,locallyActive:y.has(I),onError:C=>i(C instanceof Error?C.message:String(C)),onPayload:C=>t(Ag(C,y.has(I))),reportedActive:f.has(I),sessionId:I,surface:"thread"}));return()=>b.forEach(I=>I())},[u,t,n,l,c,i])}const o0=[];function hW(e){const{activeModel:t,activeProvider:n,approvals:a,applyRightCodexHistoryPayload:s,codexHistoryEvents:r,connectedAppMentions:i,connection:c,contextCompaction:u,openLabTraining:l,locallyActiveCodexHistorySessionIds:p,openPondCommandAccessMode:f,pendingChatUserMessages:y,providerSettings:b,rightChatHistoryEvents:I,rightChatPanels:C,rightPanelMode:P,runtimeIndexes:_,runtimeEventStore:M,runningSessionIds:A,selectedSession:T,selectedSessionId:S,sendPrompt:w,setDiffPanelOpen:R,setError:O,setRightChatHistoryEvents:z,setRightChatPanels:$,setRightPanelMode:V,setRightPanelTabRequest:Y,setView:se,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 we=C.flatMap(Me=>Me.sessionId&&!Wt(Me.sessionId)?[Me.sessionId]:[]);for(const Me of we)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]:ei(q[Me]??o0,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(we=>{Y(Me=>({id:(Me?.id??0)+1,tab:we})),ee()},[ee]),te=h.useCallback((we=null,Me={})=>{const Te=we?.id?C.find(q=>q.sessionId===we.id)??null:null;if(Te)return $(q=>rW(q,{sessionId:we.id,prompt:Me.prompt})),R(!0),V("chat"),Me.preserveView||se("chat"),Te.id;const N=aW({sessionId:we?.id??null,provider:we?.provider??n,model:we?.modelRef?.modelId??t,prompt:Me.prompt});return $(q=>[...q,N]),R(!0),V("chat"),Me.preserveView||se("chat"),N.id},[t,n,C,R,$,V,se]);h.useEffect(()=>{if(!J)return;const we=K.current;if(!we){K.current=new Set(F.filter(q=>!!(q.parentSessionId&&q.subagentRunId)).map(q=>q.id));return}const Me=oW({sessions:F,knownSessionIds:we});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=>iW(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"),se("chat")},[te,C.length,R,V,se]),ve=h.useCallback(we=>{const Me=C.length<=1&&C.some(N=>N.id===we),Te=()=>{$(N=>N.filter(q=>q.id!==we))};if(Me&&P==="chat"){if(G("files"),typeof window>"u"){Te();return}window.requestAnimationFrame(Te);return}Te()},[C,P,$,G]),me=h.useCallback((we,Me)=>{$(Te=>Te.map(N=>N.id===we?{...N,prompt:Me}:N))},[$]),Re=h.useCallback(we=>{$(Me=>sW(Me,we))},[$]),Q=h.useCallback((we,Me)=>{$(Te=>Te.map(N=>N.id===we?{...N,...Me}:N))},[$]),xe=h.useCallback((we,Me)=>{$(Te=>Te.map(N=>N.id===we?{...N,model:Me}:N))},[$]),je=h.useCallback((we,Me)=>{$(Te=>Te.map(N=>N.id===we?{...N,provider:Me,model:Sr(Me,N.model,b)}:N))},[b,$]);fW({applyPayload:s,connection:c,locallyActiveSessionIds:p,panels:C,sessions:F,setError:O});const De=mW({approvals:a,codexHistoryEvents:r,contextCompaction:u,pendingChatUserMessages:y,rightChatHistoryEvents:I,rightChatPanels:C,runningSessionIds:A,selectedSessionId:S,sidebarSessions:F}),ze=h.useCallback(async(we,Me=[],Te=null,N=null,q={})=>{const X=C.find(bt=>bt.id===we);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(we,""),!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"&&!lW(i))return H("Connect the GitHub app before using /submit-issue.","error"),!1;const de=X.sessionId?F.find(bt=>bt.id===X.sessionId)??null:null,be=X.provider==="codex"?f:de?.openPondCommandAccessMode??f,Oe=ae?.kind==="send_prompt"?ae.prompt:U,$e=Wt(X.sessionId)?(X.sessionId?I[X.sessionId]:void 0)??(X.sessionId===S?r:o0):M.getSessionEvents(X.sessionId),Ge=Wt(X.sessionId)&&X.sessionId?bt=>{const ye=X.sessionId;z(Le=>({...Le,[ye]:ei(Le[ye]??$e,[bt])}))}:void 0;return w(Me,Te,Oe,{session:de,selectSession:!1,provider:X.provider,model:X.model,openPondCommandAccessMode:be,chatMessages:Iu($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(we,""),onSessionCreated:bt=>{$(ye=>ye.map(Le=>Le.id===we?{...Le,sessionId:bt.id,provider:bt.provider,model:bt.modelRef?.modelId??Le.model}:Le))}})},[r,i,I,C,_,M,S,l,f,w,$,se,F,H,me]);return{activateRightChatPanel:Re,closeRightChatPanel:ve,openRightChatPanel:te,rightChatPanelViews:De,showRightChatPanel:oe,showRightPanelDiffTab:G,submitRightChatPrompt:ze,updateRightChatModel:xe,updateRightChatPrompt:me,updateRightChatProvider:je,updateRightChatScrollState:Q}}function gW(e){const{appPreferences:t,connection:n,selectedSessionId:a,setAppPreferences:s,setCodexHistorySessions:r,setError:i,setSelectedSessionId:c,setSessions:u}=e;async function l(_,M){if(!n)return;const A=t[_]??{},T={...A,...M,archived:M.pinned?!1:M.archived??A.archived};s(S=>({...S,[_]:T}));try{const S=await Z.patchSidebarAppPreference(n,_,M);s(w=>({...w,[_]:S}))}catch(S){i(S instanceof Error?S.message:String(S)),s(w=>({...w,[_]:A}))}}function p(_){l(_.id,{pinned:!_.pinned,archived:!1})}async function f(_,M){if(!n)return;const A=Wt(_.id)?r:u,T={..._,...M};A(S=>S.some(w=>w.id===_.id)?S.map(w=>w.id===_.id?T:w):[T,...S]);try{const S=await Z.patchSession(n,_.id,M);A(w=>w.some(R=>R.id===S.id)?w.map(R=>R.id===S.id?S:R):[S,...w])}catch(S){i(S instanceof Error?S.message:String(S)),A(w=>w.map(R=>R.id===_.id?_:R))}}function y(_){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:y}}function vW(e){return e.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,72)||"new-branch"}function bW({connection:e,activeWorkspaceAppId:t,appDefaults:n,bootstrap:a,branchDialogName:s,commitIncludeUnstaged:r,commitMessage:i,commitNextStep:c,draftModel:u,draftProvider:l,cloudProjects:p,selectedApp:f,selectedProject:y,selectedProjectLinkedOpenPondApp:b,selectedSession:I,sessions:C,title:P,visibleWorkspaceDiff:_,visibleWorkspaceState:M,workspaceBusy:A,workspaceName:T,appDispatch:S,applyBootstrapPayload:w,expandProject:R,refreshWorkspace:O,refreshWorkspaceDiff:z,rememberWorkspaceState:$,setBranchDialogOpen:V,setCommitDialogOpen:Y,setError:se,setSessions:ee,setSettingsSection:H,setSyncingWorkspaceAppId:F,setView:J,setWorkspaceBusy:K,showToast:B}){function ne(){return`${eI(n.defaultBranchPrefix)}${vW(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"){S({type:"openCommitDialog",nextStep:Te})}function oe(){S({type:"openBranchDialog",branchName:ne()})}function ve(){A||V(!1),H("configuration"),J("settings"),Dt({kind:"settings",section:"configuration"})}async function me(Te){if(!(!e||!t)){K(!0),se(null);try{const N=await Z.checkoutWorkspaceBranch(e,t,{branch:Te});$(N),N.initialized&&z(t)}catch(N){se(N instanceof Error?N.message:String(N))}finally{K(!1)}}}async function Re(){if(!e||!t)return;const Te=s.trim();if(Te){K(!0),se(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){se(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&&!Wt(I.id)?I:null;if(kW(N,X,q)||X&&yW(X,y,f))return X;const U=X?await De(X):null;if(U)return U;const ae=SW(C,y,f);if(ae){const $e=ae.workspaceKind==="local_project"&&ae.workspaceId?it("local",ae.workspaceId):null;return S({type:"selectSession",sessionId:ae.id,appId:ae.appId,projectId:$e}),ae.workspaceKind==="local_project"&&ae.workspaceId&&R(it("local",ae.workspaceId)),ae}const de=Ca(y,p),be=await Z.createSession(e,{provider:l,modelRef:Na(l,u,a?.providers??null),appId:b?.appId??f?.id??null,appName:b?.appName??f?.name??null,workspaceKind:y?"local_project":f?"sandbox_app":void 0,workspaceId:y?.id??f?.id??null,workspaceName:y?.name??f?.name??null,localProjectId:y?.id??null,cloudProjectId:de?.id??null,cloudTeamId:de?.teamId??null,cwd:y?y.workspacePath:null,title:Te});ee($e=>[be,...$e]);const Oe=be.workspaceKind==="local_project"&&be.workspaceId?it("local",be.workspaceId):null;return S({type:"selectSession",sessionId:be.id,appId:be.appId,projectId:Oe}),be.workspaceKind==="local_project"&&be.workspaceId&&R(it("local",be.workspaceId)),be}async function De(Te){if(!e||!y||!b?.appId||Wt(Te.id)||Te.workspaceKind==="local_project"||Te.appId!==b.appId)return null;const N=Ca(y,p),q=await Z.patchSession(e,Te.id,{appId:b.appId,appName:b.appName,workspaceKind:"local_project",workspaceId:y.id,workspaceName:y.name,localProjectId:y.id,cloudProjectId:N?.id??null,cloudTeamId:N?.teamId??null,cwd:y.workspacePath});return ee(X=>X.map(U=>U.id===q.id?q:U)),S({type:"selectSession",sessionId:q.id,appId:q.appId,projectId:it("local",y.id)}),R(it("local",y.id)),q}async function ze(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??xW(q);return U&&(await O(U,!1))?.initialized&&await z(U),X}async function we(Te,N={}){if(Te==="git_commit"&&typeof N.message!="string")return te("commit"),null;K(!0),se(null);try{return await ze(Te,N)}catch(q){return se(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),se(null);try{if(!(await ze("git_commit",{message:Te,includeUnstaged:r}))?.ok||c==="commit_push"&&!(await ze("git_push",{runChecks:!1}))?.ok||N&&!(await ze("publish_openpond_repo",{replaceOrigin:q}))?.ok)return;Y(!1)}catch(X){se(X instanceof Error?X.message:String(X))}finally{K(!1)}}}return{changeWorkspaceBranch:me,openCommitDialog:te,openCreateWorkspaceBranchDialog:oe,openDefaultsSettingsFromBranchDialog:ve,runWorkspaceTool:we,submitCommitDialog:Me,submitCreateWorkspaceBranch:Re,syncWorkspaceLocally:xe,syncWorkspaceLocallyForApp:Q}}function yW(e,t,n){return!t&&!n?!0:Z1(e,t,n)}function SW(e,t,n){if(!t&&!n)return null;let a=null,s=Number.NEGATIVE_INFINITY;for(const r of e){if(r.archived||!Z1(r,t,n))continue;const i=Date.parse(r.updatedAt),c=Number.isFinite(i)?i:0;(!a||c>s)&&(a=r,s=c)}return a}function Z1(e,t,n){return t?e.workspaceKind==="local_project"&&e.workspaceId===t.id:n?e.appId===n.id||e.workspaceId===n.id:!1}function xW(e){return e.workspaceKind==="sandbox"?e.localProjectId??null:e.workspaceId??e.appId??null}function kW(e,t,n={}){return(wW(e)||_W(e,n))&&IW(t)}function wW(e){return e.startsWith("sandbox_")?e!=="sandbox_create"&&e!=="sandbox_templates"&&e!=="sandbox_template_launch":!1}function IW(e){return e?.workspaceKind==="sandbox"||e?.workspaceKind==="sandbox_template"}function _W(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 CW(e,t){return e.kind==="general"?"# general":e.title?e.title:e.participants.find(a=>a.userId!==t)?.name??"Direct message"}const RW=[];function PW(e){const{composerDraftStore:t,appDispatch:n,mentionedAppId:a,setMentionedAppId:s,cloudSetupDialog:r,setCloudSetupDialog:i,setRightPanelTabRequest:c,workspaceDiffPanelViewState:u,setWorkspaceDiffPanelViewState:l,rightChatHistoryEvents:p,setRightChatHistoryEvents:f,locallyActiveCodexHistorySessionIds:y,setCodexHistoryTurnLocallyActive:b,draftSubagentDelegationMode:I,setDraftSubagentDelegationMode:C,confirmProjectAction:P,view:_,selectedAppId:M,selectedProjectId:A,selectedSessionId:T,draftProvider:S,draftModel:w,activeExperience:R,codexPermissionMode:O,codexReasoningEffort:z,openPondCommandAccessMode:$,busy:V,diffPanelOpen:Y,diffPanelExpanded:se,rightPanelMode:ee,rightChatPanels:H,newProjectMode:F,newProjectName:J,newProjectBusy:K,commitMessage:B,commitIncludeUnstaged:ne,commitNextStep:G,branchDialogName:te,setSectionMenuOpen:oe,setView:ve,setSelectedAppId:me,setSelectedProjectId:Re,setSelectedSessionId:Q,setPrompt:xe,setDraftProvider:je,setDraftModel:De,setDiffPanelOpen:ze,setRightPanelMode:we,setRightChatPanels:Me,setSyncingWorkspaceAppId:Te,setSettingsSection:N,setNewProjectDialogOpen:q,setNewProjectMode:X,setNewProjectName:U,setNewProjectPath:ae,setNewProjectBusy:de,setCommitDialogOpen:be,setBranchDialogOpen:Oe,setError:$e,showToast:Ge,appPreferences:bt,applyBootstrapPayload:ye,approvals:Le,bootstrap:Ae,connection:qe,events:He,runtimeEventStore:vn,sessions:jt,startup:pe,setAppPreferences:fe,setCodexHistorySessions:Fe,setEvents:Pe,setSessions:Ne,cloudProjectById:rt,localProjectById:lt,selectedApp:Tt,selectedCloudProject:dt,selectedProject:at,selectedProjectLinkedOpenPondApp:_t,selectedSession:Be,sidebarSessions:At,runtimeIndexes:ln,connectedAppMentions:En,codexHistoryEvents:xt,setCodexHistoryEvents:xs,account:dn,accountPending:bn,accountSignedOut:Ht,activeModel:Cn,activeProvider:yn,activeWorkspaceAppId:Rn,activeWorkspaceKind:jn,activeWorkspaceLocation:Ut,appDefaults:ft,selectedSessionProjectId:Un,workspaceName:un,accountScopeKey:ut,teamChat:It,communities:Mt,selectedProjectConfirmedCloudProject:mn,activeOpenPondCommandAccessMode:ra,viewWorkspaceAppId:Ze,viewWorkspaceId:Pn,viewWorkspaceKind:Ga,openPondActionCatalog:Aa,selectedActionCatalog:Dn,expandProject:Tn,setExpandedProjectIds:Za,advanceTrainingModelChatAfterTurn:ks,bindTrainingModelChatSession:Ea,prepareTrainingModelChatTurn:ct,chatMessages:an,pendingChatUserMessages:Ke,recordPendingChatUserMessage:yt,runningSessionIds:Xt,workspaceBusy:Ln,visibleWorkspaceState:Sn,visibleWorkspaceDiff:D,rememberWorkspaceState:ke,refreshWorkspace:ie,setWorkspaceBusy:Je,refreshWorkspaceDiffWhenNeeded:fa,setPendingWorkspaceTarget:qn,pendingSidebarWorkspaceTarget:ja,setPendingSidebarWorkspaceTarget:xn,projectTarget:to,workspaceTarget:ws}=e,Mn=_==="apps"?"Apps":_==="get-started"?"Walkthroughs":_==="labs"?"Models":_==="scheduled"?"Workflows":_==="outputs"?"Outputs":_==="projects"?"Projects":_==="team"?It.detail?CW(It.detail.thread,It.currentUserId):"Team Chat":_==="community"?Mt.preview?.displayName??"Communities":Be?.title??Hw(R),{browserConversationId:oa,handleWorkspaceDiffPanelViewStateChange:ha}=Q9({appDispatch:n,diffPanelExpanded:se,diffPanelOpen:Y,rightChatPanels:H,rightPanelMode:ee,selectedAppId:M,selectedCloudProject:dt,selectedProjectId:A,selectedSession:Be,selectedSessionId:T,setWorkspaceDiffPanelViewState:l,view:_,viewWorkspaceAppId:Ze,viewWorkspaceId:Pn,viewWorkspaceKind:Ga,workspaceDiffPanelViewState:u}),Is=h.useCallback(et=>{Dt({kind:"chat",sessionId:et}),Q(et),me(null),Re(null),ve("chat")},[me,Re,Q,ve]),kr=h.useCallback(()=>{X("existing-local"),U(""),ae(""),q(!0)},[q,X,U,ae]),wr=h.useCallback(()=>{X("local"),U(""),ae(""),q(!0)},[q,X,U,ae]),{createCloudProjectFromScratch:Vs,createProjectFromScratch:mt,createProjectCollection:ki,removeProject:Ir}=tW({connection:qe,defaultTeamId:ft.defaultTeamId,sessions:jt,selectedProjectId:A,confirmProjectAction:P,applyBootstrapPayload:ye,expandProject:Tn,setExpandedProjectIds:Za,setSelectedAppId:me,setSelectedProjectId:Re,setSelectedSessionId:Q,setError:$e,setView:ve,showToast:Ge}),{changeWorkspaceBranch:wi,openCommitDialog:no,openCreateWorkspaceBranchDialog:Ii,openDefaultsSettingsFromBranchDialog:_s,runWorkspaceTool:_i,submitCommitDialog:ao,submitCreateWorkspaceBranch:so,syncWorkspaceLocally:ro}=bW({connection:qe,activeWorkspaceAppId:Rn,appDefaults:ft,bootstrap:Ae,branchDialogName:te,commitIncludeUnstaged:ne,commitMessage:B,commitNextStep:G,draftModel:w,draftProvider:S,cloudProjects:Ae?.cloudProjects??[],selectedApp:Tt,selectedProject:at,selectedProjectLinkedOpenPondApp:_t,selectedSession:Be,sessions:jt,title:Mn,visibleWorkspaceDiff:D,visibleWorkspaceState:Sn,workspaceBusy:Ln,workspaceName:un,appDispatch:n,applyBootstrapPayload:ye,expandProject:Tn,refreshWorkspace:ie,refreshWorkspaceDiff:fa,rememberWorkspaceState:ke,setBranchDialogOpen:Oe,setCommitDialogOpen:be,setError:$e,setSessions:Ne,setSettingsSection:N,setSyncingWorkspaceAppId:Te,setView:ve,setWorkspaceBusy:Je,showToast:Ge}),Ci=K9({applyBootstrapPayload:ye,cloudProjects:Ae?.cloudProjects??[],connection:qe,localProjectById:lt,selectedCloudProject:dt,selectedProject:at,setWorkspaceBusy:Je,showToast:Ge,visibleWorkspaceState:Sn}),Ri=Ae?.preferences.subagents.delegationMode??"manual",Ja=Be?.subagentDelegationMode??I,Pi=!!(R==="development"&&Ae?.preferences.subagents.enabled&&yn!=="codex"&&!Wt(T)&&!Be?.subagentRunId),oo=h.useCallback(et=>{if(!Be){C(et);return}if(!qe||Wt(Be.id)||Be.subagentRunId)return;const Bt=Be.id,ts=Be.subagentDelegationMode??null;Ne(sn=>sn.map(zn=>zn.id===Bt?{...zn,subagentDelegationMode:et}:zn)),Z.patchSession(qe,Bt,{subagentDelegationMode:et}).then(sn=>{Ne(zn=>zn.map(On=>On.id===sn.id?sn:On))}).catch(sn=>{Ne(zn=>zn.map(On=>On.id===Bt?{...On,subagentDelegationMode:ts}:On)),$e(sn instanceof Error?sn.message:String(sn))})},[qe,Be,$e,Ne]),_r=h.useCallback(et=>{f(Bt=>Bt[et.session.id]===et.events?Bt:{...Bt,[et.session.id]:et.events}),Fe(Bt=>ku(Bt,et.session))},[Fe]),{answerCreateImproveQuestion:Cr,applyCreateImproveCandidate:io,approveCreateImproveRun:ia,cancelCreateImproveRun:Ti,changeDraftProvider:Rr,openCreateImprovePullRequest:Cs,reconcileCreateImprovePullRequest:Wn,rejectCreateImproveCandidate:Ai,pauseCreateImproveRun:Ei,resumeCreateImproveRun:kn,reviseCreateImproveRun:Ks,sendPrompt:Gn,stopTurn:Rs}=U9({applyBootstrapPayload:ye,bootstrap:Ae,chatMessages:an,connection:qe,codexPermissionMode:O,codexReasoningEffort:z,openPondCommandAccessMode:ra,draftModel:w,draftProvider:S,experience:R,expandProject:Tn,getPrompt:t.getSnapshot,apps:Ae?.apps??[],connectedAppMentions:En,mentionedAppId:a,ensureCloudSessionReady:Ci,refreshWorkspace:ie,refreshWorkspaceDiff:fa,selectedApp:Tt,selectedActionCatalog:Dn,openPondActionCatalog:Aa,cloudProjects:Ae?.cloudProjects??[],accountScopeKey:ut,selectedCloudProject:dt,selectedProject:at,selectedProjectLinkedOpenPondApp:_t,selectedSession:Be,sessions:jt,workspaceTarget:ws.value,subagentDelegationMode:Be?.subagentDelegationMode??I,setDraftModel:De,setDraftProvider:je,setError:$e,setPrompt:xe,setMentionedAppId:s,setCodexHistoryEvents:xs,setCodexHistorySessions:Fe,onCodexHistoryTurnActivityChange:b,onCodexHistoryTurnPayload:_r,onPendingUserMessage:yt,setEvents:Pe,setSelectedAppId:me,setSelectedProjectId:Re,setSelectedSessionId:Q,setSessions:Ne,setView:ve,setWorkspaceBusy:Je}),{archiveSession:Pr,restoreSession:Ws,renameSession:ji,toggleProjectPinned:co,toggleSessionPinned:Tr,toggleSessionSavedForLater:Ps}=gW({appPreferences:bt,connection:qe,selectedSessionId:T,setAppPreferences:fe,setCodexHistorySessions:Fe,setError:$e,setSelectedSessionId:Q,setSessions:Ne}),{changeWorkspaceTarget:Ts,moveProjectToCloud:Ar,startCloudSetupUpload:lo}=Y9({account:dn,accountPending:bn,accountSignedOut:Ht,activeWorkspaceKind:jn,activeWorkspaceLocation:Ut,appDispatch:n,applyBootstrapPayload:ye,busy:V,cloudSetupDialog:r,cloudProjects:Ae?.cloudProjects??[],connection:qe,defaultTeamId:ft.defaultTeamId,expandProject:Tn,localProjectById:lt,selectedCloudProject:dt,selectedProject:at,selectedSession:Be,selectedSessionProjectId:Un,setCloudSetupDialog:i,setDiffPanelOpen:ze,setError:$e,setSessions:Ne,setWorkspaceBusy:Je,showToast:Ge,visibleWorkspaceState:Sn,workspaceBusy:Ln}),Gs=h.useCallback(async et=>{if(R==="work"&&!Be){if(et==="local"){qn("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&&!dt){if(bn){Ge("Checking OpenPond account. Try again in a moment.","info");return}if(Ht){Ge("Add an OpenPond account before using Hosted.","error");return}qn("cloud"),Ge("Next task will use Hosted without a Project.","info");return}}if(et==="hybrid"){const Bt=dt?.id??mn?.id??Be?.cloudProjectId??null,ts=dt?.teamId??mn?.teamId??Be?.cloudTeamId??null;if(bn){Ge("Checking OpenPond account. Try again in a moment.","info");return}if(Ht){Ge("Add an OpenPond account before using Hybrid.","error");return}if(!Bt||!ts){qn(null),Ge("Upload/sync this Project to Cloud before using Hybrid.","error");return}if(Be&&!Wt(Be.id)){if(Ss(Be))return;if(!qe){Ge("OpenPond App server is not connected.","error");return}const sn=await Z.patchSession(qe,Be.id,{provider:S,modelRef:Na(S,w,Ae?.providers??null),appId:null,appName:null,workspaceKind:"sandbox",workspaceId:null,workspaceName:dt?.name??mn?.name??at?.name??Be.workspaceName??"Hybrid workspace",localProjectId:at?.id??Be.localProjectId??null,cloudProjectId:Bt,cloudTeamId:ts,metadata:FI(Be.metadata),cwd:at?.workspacePath??Be.cwd??null});Ne(zn=>zn.map(On=>On.id===sn.id?sn:On)),qn(null),Ge("Hybrid will use your selected model with hosted sandbox edits.","info");return}qn("hybrid"),Ge("Next message will use Hybrid with a hosted sandbox.","info");return}qn(null),await Ts(et)},[bn,Ht,R,Ae?.providers,Ts,qe,w,S,dt?.id,dt?.name,dt?.teamId,at?.id,mn?.id,mn?.name,mn?.teamId,at?.name,at?.workspacePath,Be,qn,Ne,Ge]),Qa=h.useCallback((et,Bt)=>{me(null),Re(et),Q(null),ve("chat"),Tn(et),xn({projectId:et,target:Bt})},[Tn,me,Re,Q,ve]);h.useEffect(()=>{if(!ja||_!=="chat"||A!==ja.projectId||T!==null)return;const et=ja.target;xn(null),Gs(et)},[Gs,ja,A,T,_]);const ga=X9({advanceTrainingTurn:ks,bindTrainingSession:Ea,composerDraftStore:t,onSessionCreated:et=>{Q(et.id),ve("chat"),Dt({kind:"chat",sessionId:et.id}),C(null)},onSubmitted:async()=>{const et=Be;if(!(!qe||!et||!Mc(et)))try{const Bt=await Z.patchSession(qe,et.id,{metadata:XU(et.metadata)});Ne(ts=>ts.map(sn=>sn.id===Bt.id?Bt:sn))}catch(Bt){Ge(Bt instanceof Error?`Task started, but its Draft label could not be cleared: ${Bt.message}`:"Task started, but its Draft label could not be cleared.","error")}},prepareTrainingTurn:ct,sendPrompt:Gn,setMentionedAppId:s,showToast:Ge}),uo=eW({appDispatch:n,connection:qe,sessions:jt,setDiffPanelOpen:ze,setRightPanelMode:we,setSessions:Ne,setView:ve}),{createCloudEnvironmentFromSidebar:Zs,openCloudProjectDialog:Ya,openUrlInBrowserPanel:mo,showBrowserPanel:Ma,showChangesPanel:po,showGoalSidebarTab:Mi}=l9({account:dn,browserConversationId:oa,cloudProjectById:rt,cloudProjects:Ae?.cloudProjects??[],diffPanelOpen:Y,rightPanelMode:ee,selectedProjectId:A,setDiffPanelOpen:ze,setNewProjectDialogOpen:q,setNewProjectMode:X,setNewProjectName:U,setRightPanelMode:we}),{changeProjectTarget:fo,submitNewProjectDialog:Oi}=nW({appDispatch:n,busy:V,cloudProjectById:rt,createCloudProjectFromScratch:Vs,createProjectFromScratch:mt,createProjectCollection:ki,expandProject:Tn,localProjectById:lt,newProjectBusy:K,newProjectMode:F,newProjectName:J,onCreateCloudEnvironment:Zs,onNewCloudProject:Ya,onNewLocalProject:wr,onUseExistingFolderPath:kr,projectTargetValue:to.value,setDiffPanelOpen:ze,setDraftModel:De,setDraftProvider:je,setError:$e,setNewProjectBusy:de,setNewProjectDialogOpen:q,setNewProjectName:U,setNewProjectPath:ae,showToast:Ge,workspaceBusy:Ln}),ho=h.useMemo(()=>jt.map(et=>et.id),[jt]);u9({browserConversationId:oa,sessionIds:ho,onOpenSession:Is,onShowBrowserPanel:Ma});const[go,vo]=h.useState(null),Er=h.useCallback(et=>{vo({id:Date.now(),objective:et.objective,initialSessionIds:et.sessionId?[et.sessionId]:[]}),Br(ka()),ve("labs")},[ve]),{activateRightChatPanel:bo,closeRightChatPanel:jr,openRightChatPanel:Xa,rightChatPanelViews:$i,showRightChatPanel:Ni,showRightPanelDiffTab:Di,submitRightChatPrompt:Li,updateRightChatModel:es,updateRightChatPrompt:yo,updateRightChatProvider:zi,updateRightChatScrollState:Hi}=hW({activeModel:Cn,activeProvider:yn,approvals:Le,applyRightCodexHistoryPayload:_r,codexHistoryEvents:xt,connectedAppMentions:En,connection:qe,contextCompaction:ft.contextCompaction,openLabTraining:Er,locallyActiveCodexHistorySessionIds:y,openPondCommandAccessMode:$,pendingChatUserMessages:Ke,providerSettings:Ae?.providers??null,rightChatHistoryEvents:p,rightChatPanels:H,rightPanelMode:ee,runtimeIndexes:ln,runtimeEventStore:vn,runningSessionIds:Xt,selectedSession:Be,selectedSessionId:T,sendPrompt:Gn,setDiffPanelOpen:ze,setError:$e,setRightChatHistoryEvents:f,setRightChatPanels:Me,setRightPanelMode:we,setRightPanelTabRequest:c,setView:ve,showChangesPanel:po,showToast:Ge,sidebarSessions:At,startupReady:pe.ready}),Ui=h.useCallback(()=>{oe(null),N("profile"),ve("settings"),Dt({kind:"settings",section:"profile"})},[oe,N,ve]),ca=h.useMemo(()=>Ns(Ae?.diagnostics??RW,He.filter(et=>et.name==="diagnostic")),[Ae?.diagnostics,He]),So=h.useCallback(()=>{if(Y){ze(!1);return}if(_==="labs"){we("changes"),c({id:Date.now(),tab:"summary"}),ze(!0);return}we("home"),ze(!0)},[Y,ze,we,c,_]);return{title:Mn,browserConversationId:oa,handleWorkspaceDiffPanelViewStateChange:ha,openSessionInChat:Is,openExistingProjectPathDialog:kr,removeProject:Ir,changeProjectTarget:fo,submitNewProjectDialog:Oi,changeWorkspaceBranch:wi,openCommitDialog:no,openCreateWorkspaceBranchDialog:Ii,openDefaultsSettingsFromBranchDialog:_s,runWorkspaceTool:_i,submitCommitDialog:ao,submitCreateWorkspaceBranch:so,syncWorkspaceLocally:ro,subagentDelegationDefaultMode:Ri,subagentDelegationMode:Ja,subagentDelegationAvailable:Pi,changeSubagentDelegationMode:oo,answerCreateImproveQuestion:Cr,applyCreateImproveCandidate:io,approveCreateImproveRun:ia,cancelCreateImproveRun:Ti,changeDraftProvider:Rr,openCreateImprovePullRequest:Cs,reconcileCreateImprovePullRequest:Wn,rejectCreateImproveCandidate:Ai,pauseCreateImproveRun:Ei,resumeCreateImproveRun:kn,reviseCreateImproveRun:Ks,sendPrompt:Gn,stopTurn:Rs,archiveSession:Pr,restoreSession:Ws,renameSession:ji,toggleProjectPinned:co,toggleSessionPinned:Tr,toggleSessionSavedForLater:Ps,moveProjectToCloud:Ar,startCloudSetupUpload:lo,changeWorkspaceTarget:Gs,switchProjectWorkspaceTarget:Qa,sendPromptFromMainComposer:ga,openSandboxWorkspace:uo,createCloudEnvironmentFromSidebar:Zs,openCloudProjectDialog:Ya,openUrlInBrowserPanel:mo,showBrowserPanel:Ma,showChangesPanel:po,showGoalSidebarTab:Mi,rightChatTrainingLaunchRequest:go,setRightChatTrainingLaunchRequest:vo,closeRightChatPanel:jr,openRightChatPanel:Xa,rightChatPanelViews:$i,showRightChatPanel:Ni,showRightPanelDiffTab:Di,submitRightChatPrompt:Li,activateRightChatPanel:bo,updateRightChatModel:es,updateRightChatPrompt:yo,updateRightChatProvider:zi,updateRightChatScrollState:Hi,openProfileSettings:Ui,diagnosticEvents:ca,toggleRightSidebar:So}}const TW=B_();function AW(){return g.jsx(o_,{client:TW,children:g.jsx(EW,{})})}function EW(){const e=n9(),t=PW(e);return g.jsx(kF,{primary:e,secondary:t})}const WG=Object.freeze(Object.defineProperty({__proto__:null,App:AW},Symbol.toStringTag,{value:"Module"}));export{DH as $,X_ as A,X8 as B,mr as C,hH as D,gb as E,jw as F,tg as G,S9 as H,LG as I,UG as J,F1 as K,zG as L,L as M,wU as N,wg as O,mu as P,ui as Q,Z as R,vb as S,eo as T,ZU as U,L8 as V,z8 as W,Jc as X,Dw as Y,WU as Z,k as _,h8 as a,dW as a$,s0 as a0,zr as a1,Ug as a2,Hn as a3,DG as a4,ZI as a5,bG as a6,qG as a7,Vp as a8,Sr as a9,Md as aA,l1 as aB,Pd as aC,vu as aD,qH as aE,oU as aF,Mw as aG,qW as aH,NG as aI,CH as aJ,HH as aK,tp as aL,g8 as aM,Wt as aN,ei as aO,o1 as aP,rG as aQ,dF as aR,GV as aS,sG as aT,rF as aU,PG as aV,WV as aW,ya as aX,ys as aY,W1 as aZ,lW as a_,HG as aa,gf as ab,B8 as ac,gG as ad,zF as ae,KG as af,E9 as ag,hG as ah,vG as ai,TG as aj,_G as ak,b4 as al,Na as am,D4 as an,$o as ao,Dy as ap,IG as aq,kG as ar,wG as as,Xy as at,$f as au,td as av,$H as aw,$w as ax,SG as ay,rf as az,j as b,Pw as b$,o9 as b0,oG as b1,qU as b2,sg as b3,Rw as b4,gu as b5,xG as b6,vg as b7,NU as b8,N8 as b9,D8 as bA,bu as bB,Lw as bC,Dt as bD,yU as bE,c1 as bF,Xn as bG,v as bH,x as bI,Se as bJ,Ie as bK,Ml as bL,oH as bM,FG as bN,Ru as bO,iI as bP,V8 as bQ,Oc as bR,DW as bS,LW as bT,K8 as bU,VH as bV,ka as bW,Br as bX,Qe as bY,eh as bZ,rg as b_,Fb as ba,Nw as bb,p4 as bc,If as bd,AF as be,BG as bf,wF as bg,Xb as bh,xu as bi,f4 as bj,Og as bk,eI as bl,PH as bm,H8 as bn,U8 as bo,aE as bp,sU as bq,lF as br,cF as bs,ng as bt,tU as bu,Aw as bv,ag as bw,HW as bx,SS as by,F8 as bz,Vh as c,Vm as c$,Zc as c0,cG as c1,pG as c2,fG as c3,ty as c4,dG as c5,fp as c6,mG as c7,uG as c8,lG as c9,OW as cA,Nc as cB,Nm as cC,vc as cD,P_ as cE,Nn as cF,Qn as cG,f0 as cH,q_ as cI,zW as cJ,eS as cK,Ch as cL,GW as cM,Ta as cN,HO as cO,Ba as cP,KW as cQ,wh as cR,Xd as cS,Ye as cT,Pt as cU,Yd as cV,Ce as cW,W as cX,E as cY,GO as cZ,Lx as c_,ey as ca,iG as cb,Ct as cc,WI as cd,pt as ce,j8 as cf,vt as cg,Sd as ch,Ih as ci,zt as cj,mI as ck,yB as cl,Oq as cm,qm as cn,UW as co,HB as cp,q8 as cq,Z8 as cr,J8 as cs,Q8 as ct,Y8 as cu,DU as cv,W8 as cw,G8 as cx,__ as cy,$W as cz,wD as d,zD as d$,$x as d0,NO as d1,Ix as d2,kO as d3,zO as d4,KO as d5,JW as d6,BO as d7,t$ as d8,re as d9,_$ as dA,Kr as dB,qA as dC,qa as dD,o8 as dE,Fc as dF,O$ as dG,du as dH,zN as dI,sx as dJ,fO as dK,pO as dL,i8 as dM,qh as dN,u8 as dO,Zd as dP,d8 as dQ,Cx as dR,NN as dS,ir as dT,or as dU,Jo as dV,X0 as dW,c8 as dX,aG as dY,$8 as dZ,PL as d_,jx as da,xx as db,QO as dc,JO as dd,WO as de,Ox as df,Rh as dg,Mx as dh,eu as di,tu as dj,XW as dk,ZW as dl,VW as dm,qO as dn,ta as dp,dk as dq,lu as dr,qN as ds,q$ as dt,OO as du,fn as dv,a8 as dw,Gp as dx,_n as dy,s8 as dz,We as e,IU as e$,x8 as e0,k8 as e1,O8 as e2,r8 as e3,tS as e4,Uh as e5,cg as e6,ux as e7,zl as e8,BW as e9,WW as eA,YW as eB,e8 as eC,QW as eD,za as eE,t8 as eF,f$ as eG,ru as eH,Ok as eI,f8 as eJ,C8 as eK,_8 as eL,I8 as eM,E8 as eN,n8 as eO,Jx as eP,J2 as eQ,A$ as eR,w8 as eS,_z as eT,Gc as eU,R8 as eV,A8 as eW,T8 as eX,P8 as eY,cz as eZ,Ez as e_,hn as ea,cx as eb,a4 as ec,qc as ed,yh as ee,qv as ef,FW as eg,wc as eh,Ka as ei,yO as ej,y8 as ek,rw as el,S8 as em,Zx as en,b8 as eo,v8 as ep,pc as eq,sw as er,jO as es,Sh as et,Pl as eu,Uc as ev,l8 as ew,jN as ex,eG as ey,tG as ez,o3 as f,EU as f0,M8 as f1,m8 as f2,p8 as f3,yu as f4,CG as f5,RG as f6,nk as f7,Z$ as f8,vr as f9,dr as fa,Uv as fb,nG as fc,Tw as fd,Yy as fe,r9 as ff,wf as fg,UI as fh,II as fi,HI as fj,VG as fk,jG as fl,AG as fm,EG as fn,yK as fo,CW as fp,MG as fq,OG as fr,$G as fs,bb as ft,WG as fu,kb as g,l0 as h,bI as i,x0 as j,zz as k,jd as l,jc as m,m as n,d as o,XH as p,pr as q,dH as r,o as s,cs as t,gt as u,hu as v,Yw as w,GU as x,Kw as y,yG as z};
|